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::{
22copy_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, CodegenResults, CompiledModule, 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_no_opt_bc: ref __binding_12,
emit_bc: ref __binding_13,
emit_ir: ref __binding_14,
emit_asm: ref __binding_15,
emit_obj: ref __binding_16,
emit_thin_lto_summary: ref __binding_17,
verify_llvm_ir: ref __binding_18,
lint_llvm_ir: ref __binding_19,
no_prepopulate_passes: ref __binding_20,
no_builtins: ref __binding_21,
vectorize_loop: ref __binding_22,
vectorize_slp: ref __binding_23,
merge_functions: ref __binding_24,
emit_lifetime_markers: ref __binding_25,
llvm_plugins: ref __binding_26,
autodiff: ref __binding_27,
offload: ref __binding_28 } => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_2,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_3,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_4,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_5,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_6,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_7,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_8,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_9,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_10,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_11,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_12,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_13,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_14,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_15,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_16,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_17,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_18,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_19,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_20,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_21,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_22,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_23,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_24,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_25,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_26,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_27,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_28,
__encoder);
}
}
}
}
};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_no_opt_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_no_opt_bc: bool,
98pub emit_bc: bool,
99pub emit_ir: bool,
100pub emit_asm: bool,
101pub emit_obj: EmitObj,
102pub emit_thin_lto_summary: bool,
103104// Miscellaneous flags. These are mostly copied from command-line
105 // options.
106pub verify_llvm_ir: bool,
107pub lint_llvm_ir: bool,
108pub no_prepopulate_passes: bool,
109pub no_builtins: bool,
110pub vectorize_loop: bool,
111pub vectorize_slp: bool,
112pub merge_functions: bool,
113pub emit_lifetime_markers: bool,
114pub llvm_plugins: Vec<String>,
115pub autodiff: Vec<config::AutoDiff>,
116pub offload: Vec<config::Offload>,
117}
118119impl ModuleConfig {
120fn new(kind: ModuleKind, tcx: TyCtxt<'_>, no_builtins: bool) -> ModuleConfig {
121// If it's a regular module, use `$regular`, otherwise use `$other`.
122 // `$regular` and `$other` are evaluated lazily.
123macro_rules! if_regular {
124 ($regular: expr, $other: expr) => {
125if let ModuleKind::Regular = kind { $regular } else { $other }
126 };
127 }
128129let sess = tcx.sess;
130let opt_level_and_size = if let ModuleKind::Regular = kind { Some(sess.opts.optimize) } else { None }if_regular!(Some(sess.opts.optimize), None);
131132let save_temps = sess.opts.cg.save_temps;
133134let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
135 || match kind {
136 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
137 ModuleKind::Allocator => false,
138 };
139140let emit_obj = if !should_emit_obj {
141 EmitObj::None142 } else if sess.target.obj_is_bitcode
143 || (sess.opts.cg.linker_plugin_lto.enabled() && !no_builtins)
144 {
145// This case is selected if the target uses objects as bitcode, or
146 // if linker plugin LTO is enabled. In the linker plugin LTO case
147 // the assumption is that the final link-step will read the bitcode
148 // and convert it to object code. This may be done by either the
149 // native linker or rustc itself.
150 //
151 // Note, however, that the linker-plugin-lto requested here is
152 // explicitly ignored for `#![no_builtins]` crates. These crates are
153 // specifically ignored by rustc's LTO passes and wouldn't work if
154 // loaded into the linker. These crates define symbols that LLVM
155 // lowers intrinsics to, and these symbol dependencies aren't known
156 // until after codegen. As a result any crate marked
157 // `#![no_builtins]` is assumed to not participate in LTO and
158 // instead goes on to generate object code.
159EmitObj::Bitcode160 } else if need_bitcode_in_object(tcx) {
161 EmitObj::ObjectCode(BitcodeSection::Full)
162 } else {
163 EmitObj::ObjectCode(BitcodeSection::None)
164 };
165166ModuleConfig {
167 passes: if let ModuleKind::Regular = kind {
sess.opts.cg.passes.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.cg.passes.clone(), vec![]),
168169 opt_level: opt_level_and_size,
170171 pgo_gen: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_generate.clone()
} else { SwitchWithOptPath::Disabled }if_regular!(
172 sess.opts.cg.profile_generate.clone(),
173 SwitchWithOptPath::Disabled
174 ),
175 pgo_use: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_use.clone()
} else { None }if_regular!(sess.opts.cg.profile_use.clone(), None),
176 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),
177 debug_info_for_profiling: sess.opts.unstable_opts.debug_info_for_profiling,
178 instrument_coverage: if let ModuleKind::Regular = kind {
sess.instrument_coverage()
} else { false }if_regular!(sess.instrument_coverage(), false),
179180 sanitizer: if let ModuleKind::Regular = kind {
sess.sanitizers()
} else { SanitizerSet::empty() }if_regular!(sess.sanitizers(), SanitizerSet::empty()),
181 sanitizer_dataflow_abilist: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone()
} else { Vec::new() }if_regular!(
182 sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
183 Vec::new()
184 ),
185 sanitizer_recover: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_recover
} else { SanitizerSet::empty() }if_regular!(
186 sess.opts.unstable_opts.sanitizer_recover,
187 SanitizerSet::empty()
188 ),
189 sanitizer_memory_track_origins: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_memory_track_origins
} else { 0 }if_regular!(
190 sess.opts.unstable_opts.sanitizer_memory_track_origins,
1910
192),
193194 emit_pre_lto_bc: if let ModuleKind::Regular = kind {
save_temps || need_pre_lto_bitcode_for_incr_comp(sess)
} else { false }if_regular!(
195 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
196false
197),
198 emit_no_opt_bc: if let ModuleKind::Regular = kind { save_temps } else { false }if_regular!(save_temps, false),
199 emit_bc: if let ModuleKind::Regular = kind {
save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode)
} else { save_temps }if_regular!(
200 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
201 save_temps
202 ),
203 emit_ir: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::LlvmAssembly)
} else { false }if_regular!(
204 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
205false
206),
207 emit_asm: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::Assembly)
} else { false }if_regular!(
208 sess.opts.output_types.contains_key(&OutputType::Assembly),
209false
210),
211emit_obj,
212 emit_thin_lto_summary: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode)
} else { false }if_regular!(
213 sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode),
214false
215),
216217 verify_llvm_ir: sess.verify_llvm_ir(),
218 lint_llvm_ir: sess.opts.unstable_opts.lint_llvm_ir,
219 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
220 no_builtins: no_builtins || sess.target.no_builtins,
221222// Copy what clang does by turning on loop vectorization at O2 and
223 // slp vectorization at O3.
224vectorize_loop: !sess.opts.cg.no_vectorize_loops
225 && (sess.opts.optimize == config::OptLevel::More226 || sess.opts.optimize == config::OptLevel::Aggressive),
227 vectorize_slp: !sess.opts.cg.no_vectorize_slp
228 && sess.opts.optimize == config::OptLevel::Aggressive,
229230// Some targets (namely, NVPTX) interact badly with the
231 // MergeFunctions pass. This is because MergeFunctions can generate
232 // new function calls which may interfere with the target calling
233 // convention; e.g. for the NVPTX target, PTX kernels should not
234 // call other PTX kernels. MergeFunctions can also be configured to
235 // generate aliases instead, but aliases are not supported by some
236 // backends (again, NVPTX). Therefore, allow targets to opt out of
237 // the MergeFunctions pass, but otherwise keep the pass enabled (at
238 // O2 and O3) since it can be useful for reducing code size.
239merge_functions: match sess240 .opts
241 .unstable_opts
242 .merge_functions
243 .unwrap_or(sess.target.merge_functions)
244 {
245 MergeFunctions::Disabled => false,
246 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
247use config::OptLevel::*;
248match sess.opts.optimize {
249Aggressive | More | SizeMin | Size => true,
250Less | No => false,
251 }
252 }
253 },
254255 emit_lifetime_markers: sess.emit_lifetime_markers(),
256 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![]),
257 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![]),
258 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![]),
259 }
260 }
261262pub fn bitcode_needed(&self) -> bool {
263self.emit_bc
264 || self.emit_thin_lto_summary
265 || self.emit_obj == EmitObj::Bitcode266 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
267 }
268269pub fn embed_bitcode(&self) -> bool {
270self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
271 }
272}
273274/// Configuration passed to the function returned by the `target_machine_factory`.
275pub struct TargetMachineFactoryConfig {
276/// Split DWARF is enabled in LLVM by checking that `TM.MCOptions.SplitDwarfFile` isn't empty,
277 /// so the path to the dwarf object has to be provided when we create the target machine.
278 /// This can be ignored by backends which do not need it for their Split DWARF support.
279pub split_dwarf_file: Option<PathBuf>,
280281/// The name of the output object file. Used for setting OutputFilenames in target options
282 /// so that LLVM can emit the CodeView S_OBJNAME record in pdb files
283pub output_obj_file: Option<PathBuf>,
284}
285286impl TargetMachineFactoryConfig {
287pub fn new(cgcx: &CodegenContext, module_name: &str) -> TargetMachineFactoryConfig {
288let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
289cgcx.output_filenames.split_dwarf_path(
290cgcx.split_debuginfo,
291cgcx.split_dwarf_kind,
292module_name,
293cgcx.invocation_temp.as_deref(),
294 )
295 } else {
296None297 };
298299let output_obj_file = Some(cgcx.output_filenames.temp_path_for_cgu(
300 OutputType::Object,
301module_name,
302cgcx.invocation_temp.as_deref(),
303 ));
304TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }
305 }
306}
307308pub type TargetMachineFactoryFn<B> = Arc<
309dyn Fn(
310DiagCtxtHandle<'_>,
311TargetMachineFactoryConfig,
312 ) -> <B as WriteBackendMethods>::TargetMachine313 + Send314 + Sync,
315>;
316317/// Additional resources used by optimize_and_codegen (not module specific)
318#[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)]
319pub struct CodegenContext {
320// Resources needed when running LTO
321pub lto: Lto,
322pub use_linker_plugin_lto: bool,
323pub dylib_lto: bool,
324pub prefer_dynamic: bool,
325pub save_temps: bool,
326pub fewer_names: bool,
327pub time_trace: bool,
328pub crate_types: Vec<CrateType>,
329pub output_filenames: Arc<OutputFilenames>,
330pub invocation_temp: Option<String>,
331pub module_config: Arc<ModuleConfig>,
332pub opt_level: OptLevel,
333pub backend_features: Vec<String>,
334pub msvc_imps_needed: bool,
335pub is_pe_coff: bool,
336pub target_can_use_split_dwarf: bool,
337pub target_arch: String,
338pub target_is_like_darwin: bool,
339pub target_is_like_aix: bool,
340pub target_is_like_gpu: bool,
341pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
342pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
343pub pointer_size: Size,
344345/// LLVM optimizations for which we want to print remarks.
346pub remark: Passes,
347/// Directory into which should the LLVM optimization remarks be written.
348 /// If `None`, they will be written to stderr.
349pub remark_dir: Option<PathBuf>,
350/// The incremental compilation session directory, or None if we are not
351 /// compiling incrementally
352pub incr_comp_session_dir: Option<PathBuf>,
353/// `true` if the codegen should be run in parallel.
354 ///
355 /// Depends on [`ExtraBackendMethods::supports_parallel()`] and `-Zno_parallel_backend`.
356pub parallel: bool,
357}
358359fn generate_thin_lto_work<B: ExtraBackendMethods>(
360 cgcx: &CodegenContext,
361 prof: &SelfProfilerRef,
362 dcx: DiagCtxtHandle<'_>,
363 exported_symbols_for_lto: &[String],
364 each_linked_rlib_for_lto: &[PathBuf],
365 needs_thin_lto: Vec<(String, B::ModuleBuffer)>,
366 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
367) -> Vec<(ThinLtoWorkItem<B>, u64)> {
368let _prof_timer = prof.generic_activity("codegen_thin_generate_lto_work");
369370let (lto_modules, copy_jobs) = B::run_thin_lto(
371cgcx,
372prof,
373dcx,
374exported_symbols_for_lto,
375each_linked_rlib_for_lto,
376needs_thin_lto,
377import_only_modules,
378 );
379lto_modules380 .into_iter()
381 .map(|module| {
382let cost = module.cost();
383 (ThinLtoWorkItem::ThinLto(module), cost)
384 })
385 .chain(copy_jobs.into_iter().map(|wp| {
386 (
387 ThinLtoWorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
388 name: wp.cgu_name.clone(),
389 source: wp,
390 }),
3910, // copying is very cheap
392)
393 }))
394 .collect()
395}
396397pub struct CompiledModules {
398pub modules: Vec<CompiledModule>,
399pub allocator_module: Option<CompiledModule>,
400}
401402enum MaybeLtoModules<B: WriteBackendMethods> {
403 NoLto {
404 modules: Vec<CompiledModule>,
405 allocator_module: Option<CompiledModule>,
406 },
407 FatLto {
408 cgcx: CodegenContext,
409 exported_symbols_for_lto: Arc<Vec<String>>,
410 each_linked_rlib_file_for_lto: Vec<PathBuf>,
411 needs_fat_lto: Vec<FatLtoInput<B>>,
412 lto_import_only_modules:
413Vec<(SerializedModule<<B as WriteBackendMethods>::ModuleBuffer>, WorkProduct)>,
414 },
415 ThinLto {
416 cgcx: CodegenContext,
417 exported_symbols_for_lto: Arc<Vec<String>>,
418 each_linked_rlib_file_for_lto: Vec<PathBuf>,
419 needs_thin_lto: Vec<(String, <B as WriteBackendMethods>::ModuleBuffer)>,
420 lto_import_only_modules:
421Vec<(SerializedModule<<B as WriteBackendMethods>::ModuleBuffer>, WorkProduct)>,
422 },
423}
424425fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
426let sess = tcx.sess;
427sess.opts.cg.embed_bitcode
428 && tcx.crate_types().contains(&CrateType::Rlib)
429 && sess.opts.output_types.contains_key(&OutputType::Exe)
430}
431432fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
433if sess.opts.incremental.is_none() {
434return false;
435 }
436437match sess.lto() {
438 Lto::No => false,
439 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
440 }
441}
442443pub(crate) fn start_async_codegen<B: ExtraBackendMethods>(
444 backend: B,
445 tcx: TyCtxt<'_>,
446 target_cpu: String,
447 allocator_module: Option<ModuleCodegen<B::Module>>,
448) -> OngoingCodegen<B> {
449let (coordinator_send, coordinator_receive) = channel();
450451let 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);
452453let crate_info = CrateInfo::new(tcx, target_cpu);
454455let regular_config = ModuleConfig::new(ModuleKind::Regular, tcx, no_builtins);
456let allocator_config = ModuleConfig::new(ModuleKind::Allocator, tcx, no_builtins);
457458let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
459let (codegen_worker_send, codegen_worker_receive) = channel();
460461let coordinator_thread = start_executing_work(
462backend.clone(),
463tcx,
464&crate_info,
465shared_emitter,
466codegen_worker_send,
467coordinator_receive,
468Arc::new(regular_config),
469Arc::new(allocator_config),
470allocator_module,
471coordinator_send.clone(),
472 );
473474OngoingCodegen {
475backend,
476crate_info,
477478codegen_worker_receive,
479shared_emitter_main,
480 coordinator: Coordinator {
481 sender: coordinator_send,
482 future: Some(coordinator_thread),
483 phantom: PhantomData,
484 },
485 output_filenames: Arc::clone(tcx.output_filenames(())),
486 }
487}
488489fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
490 sess: &Session,
491 compiled_modules: &CompiledModules,
492) -> FxIndexMap<WorkProductId, WorkProduct> {
493let mut work_products = FxIndexMap::default();
494495if sess.opts.incremental.is_none() {
496return work_products;
497 }
498499let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
500501for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
502let mut files = Vec::new();
503if let Some(object_file_path) = &module.object {
504 files.push((OutputType::Object.extension(), object_file_path.as_path()));
505 }
506if let Some(dwarf_object_file_path) = &module.dwarf_object {
507 files.push(("dwo", dwarf_object_file_path.as_path()));
508 }
509if let Some(path) = &module.assembly {
510 files.push((OutputType::Assembly.extension(), path.as_path()));
511 }
512if let Some(path) = &module.llvm_ir {
513 files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
514 }
515if let Some(path) = &module.bytecode {
516 files.push((OutputType::Bitcode.extension(), path.as_path()));
517 }
518if let Some((id, product)) = copy_cgu_workproduct_to_incr_comp_cache_dir(
519 sess,
520&module.name,
521 files.as_slice(),
522&module.links_from_incr_cache,
523 ) {
524 work_products.insert(id, product);
525 }
526 }
527528work_products529}
530531pub fn produce_final_output_artifacts(
532 sess: &Session,
533 compiled_modules: &CompiledModules,
534 crate_output: &OutputFilenames,
535) {
536let mut user_wants_bitcode = false;
537let mut user_wants_objects = false;
538539// Produce final compile outputs.
540let copy_gracefully = |from: &Path, to: &OutFileName| match to {
541 OutFileName::Stdoutif let Err(e) = copy_to_stdout(from) => {
542sess.dcx().emit_err(errors::CopyPath::new(from, to.as_path(), e));
543 }
544 OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
545sess.dcx().emit_err(errors::CopyPath::new(from, path, e));
546 }
547_ => {}
548 };
549550let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
551if let [module] = &compiled_modules.modules[..] {
552// 1) Only one codegen unit. In this case it's no difficulty
553 // to copy `foo.0.x` to `foo.x`.
554let path = crate_output.temp_path_for_cgu(
555output_type,
556&module.name,
557sess.invocation_temp.as_deref(),
558 );
559let output = crate_output.path(output_type);
560if !output_type.is_text_output() && output.is_tty() {
561sess.dcx()
562 .emit_err(errors::BinaryOutputToTty { shorthand: output_type.shorthand() });
563 } else {
564copy_gracefully(&path, &output);
565 }
566if !sess.opts.cg.save_temps && !keep_numbered {
567// The user just wants `foo.x`, not `foo.#module-name#.x`.
568ensure_removed(sess.dcx(), &path);
569 }
570 } else {
571if crate_output.outputs.contains_explicit_name(&output_type) {
572// 2) Multiple codegen units, with `--emit foo=some_name`. We have
573 // no good solution for this case, so warn the user.
574sess.dcx()
575 .emit_warn(errors::IgnoringEmitPath { extension: output_type.extension() });
576 } else if crate_output.single_output_file.is_some() {
577// 3) Multiple codegen units, with `-o some_name`. We have
578 // no good solution for this case, so warn the user.
579sess.dcx().emit_warn(errors::IgnoringOutput { extension: output_type.extension() });
580 } else {
581// 4) Multiple codegen units, but no explicit name. We
582 // just leave the `foo.0.x` files in place.
583 // (We don't have to do any work in this case.)
584}
585 }
586 };
587588// Flag to indicate whether the user explicitly requested bitcode.
589 // Otherwise, we produced it only as a temporary output, and will need
590 // to get rid of it.
591for output_type in crate_output.outputs.keys() {
592match *output_type {
593 OutputType::Bitcode => {
594 user_wants_bitcode = true;
595// Copy to .bc, but always keep the .0.bc. There is a later
596 // check to figure out if we should delete .0.bc files, or keep
597 // them for making an rlib.
598copy_if_one_unit(OutputType::Bitcode, true);
599 }
600 OutputType::ThinLinkBitcode => {
601 copy_if_one_unit(OutputType::ThinLinkBitcode, false);
602 }
603 OutputType::LlvmAssembly => {
604 copy_if_one_unit(OutputType::LlvmAssembly, false);
605 }
606 OutputType::Assembly => {
607 copy_if_one_unit(OutputType::Assembly, false);
608 }
609 OutputType::Object => {
610 user_wants_objects = true;
611 copy_if_one_unit(OutputType::Object, true);
612 }
613 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
614 }
615 }
616617// Clean up unwanted temporary files.
618619 // We create the following files by default:
620 // - #crate#.#module-name#.bc
621 // - #crate#.#module-name#.o
622 // - #crate#.crate.metadata.bc
623 // - #crate#.crate.metadata.o
624 // - #crate#.o (linked from crate.##.o)
625 // - #crate#.bc (copied from crate.##.bc)
626 // We may create additional files if requested by the user (through
627 // `-C save-temps` or `--emit=` flags).
628629if !sess.opts.cg.save_temps {
630// Remove the temporary .#module-name#.o objects. If the user didn't
631 // explicitly request bitcode (with --emit=bc), and the bitcode is not
632 // needed for building an rlib, then we must remove .#module-name#.bc as
633 // well.
634635 // Specific rules for keeping .#module-name#.bc:
636 // - If the user requested bitcode (`user_wants_bitcode`), and
637 // codegen_units > 1, then keep it.
638 // - If the user requested bitcode but codegen_units == 1, then we
639 // can toss .#module-name#.bc because we copied it to .bc earlier.
640 // - If we're not building an rlib and the user didn't request
641 // bitcode, then delete .#module-name#.bc.
642 // If you change how this works, also update back::link::link_rlib,
643 // where .#module-name#.bc files are (maybe) deleted after making an
644 // rlib.
645let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
646647let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
648649let keep_numbered_objects =
650needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
651652for module in compiled_modules.modules.iter() {
653if !keep_numbered_objects {
654if let Some(ref path) = module.object {
655 ensure_removed(sess.dcx(), path);
656 }
657658if let Some(ref path) = module.dwarf_object {
659 ensure_removed(sess.dcx(), path);
660 }
661 }
662663if let Some(ref path) = module.bytecode {
664if !keep_numbered_bitcode {
665 ensure_removed(sess.dcx(), path);
666 }
667 }
668 }
669670if !user_wants_bitcode671 && let Some(ref allocator_module) = compiled_modules.allocator_module
672 && let Some(ref path) = allocator_module.bytecode
673 {
674ensure_removed(sess.dcx(), path);
675 }
676 }
677678if sess.opts.json_artifact_notifications {
679if let [module] = &compiled_modules.modules[..] {
680module.for_each_output(|_path, ty| {
681if sess.opts.output_types.contains_key(&ty) {
682let descr = ty.shorthand();
683// for single cgu file is renamed to drop cgu specific suffix
684 // so we regenerate it the same way
685let path = crate_output.path(ty);
686sess.dcx().emit_artifact_notification(path.as_path(), descr);
687 }
688 });
689 } else {
690for module in &compiled_modules.modules {
691 module.for_each_output(|path, ty| {
692if sess.opts.output_types.contains_key(&ty) {
693let descr = ty.shorthand();
694 sess.dcx().emit_artifact_notification(&path, descr);
695 }
696 });
697 }
698 }
699 }
700701// We leave the following files around by default:
702 // - #crate#.o
703 // - #crate#.crate.metadata.o
704 // - #crate#.bc
705 // These are used in linking steps and will be cleaned up afterward.
706}
707708pub(crate) enum WorkItem<B: WriteBackendMethods> {
709/// Optimize a newly codegened, totally unoptimized module.
710Optimize(ModuleCodegen<B::Module>),
711/// Copy the post-LTO artifacts from the incremental cache to the output
712 /// directory.
713CopyPostLtoArtifacts(CachedModuleCodegen),
714}
715716enum ThinLtoWorkItem<B: WriteBackendMethods> {
717/// Copy the post-LTO artifacts from the incremental cache to the output
718 /// directory.
719CopyPostLtoArtifacts(CachedModuleCodegen),
720/// Performs thin-LTO on the given module.
721ThinLto(lto::ThinModule<B>),
722}
723724// `pthread_setname()` on *nix ignores anything beyond the first 15
725// bytes. Use short descriptions to maximize the space available for
726// the module name.
727#[cfg(not(windows))]
728fn desc(short: &str, _long: &str, name: &str) -> String {
729// The short label is three bytes, and is followed by a space. That
730 // leaves 11 bytes for the CGU name. How we obtain those 11 bytes
731 // depends on the CGU name form.
732 //
733 // - Non-incremental, e.g. `regex.f10ba03eb5ec7975-cgu.0`: the part
734 // before the `-cgu.0` is the same for every CGU, so use the
735 // `cgu.0` part. The number suffix will be different for each
736 // CGU.
737 //
738 // - Incremental (normal), e.g. `2i52vvl2hco29us0`: use the whole
739 // name because each CGU will have a unique ASCII hash, and the
740 // first 11 bytes will be enough to identify it.
741 //
742 // - Incremental (with `-Zhuman-readable-cgu-names`), e.g.
743 // `regex.f10ba03eb5ec7975-re_builder.volatile`: use the whole
744 // name. The first 11 bytes won't be enough to uniquely identify
745 // it, but no obvious substring will, and this is a rarely used
746 // option so it doesn't matter much.
747 //
748match (&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);
749let name = if let Some(index) = name.find("-cgu.") {
750&name[index + 1..] // +1 skips the leading '-'.
751} else {
752name753 };
754::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}", short, name))
})format!("{short} {name}")755}
756757// Windows has no thread name length limit, so use more descriptive names.
758#[cfg(windows)]
759fn desc(_short: &str, long: &str, name: &str) -> String {
760format!("{long} {name}")
761}
762763impl<B: WriteBackendMethods> WorkItem<B> {
764/// Generate a short description of this work item suitable for use as a thread name.
765fn short_description(&self) -> String {
766match self {
767 WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
768 WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
769 }
770 }
771}
772773impl<B: WriteBackendMethods> ThinLtoWorkItem<B> {
774/// Generate a short description of this work item suitable for use as a thread name.
775fn short_description(&self) -> String {
776match self {
777 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
778desc("cpy", "copy LTO artifacts for", &m.name)
779 }
780 ThinLtoWorkItem::ThinLto(m) => desc("lto", "thin-LTO module", m.name()),
781 }
782 }
783}
784785/// A result produced by the backend.
786pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
787/// The backend has finished compiling a CGU, nothing more required.
788Finished(CompiledModule),
789790/// The backend has finished compiling a CGU, which now needs to go through
791 /// fat LTO.
792NeedsFatLto(FatLtoInput<B>),
793794/// The backend has finished compiling a CGU, which now needs to go through
795 /// thin LTO.
796NeedsThinLto(String, B::ModuleBuffer),
797}
798799pub enum FatLtoInput<B: WriteBackendMethods> {
800 Serialized { name: String, buffer: SerializedModule<B::ModuleBuffer> },
801 InMemory(ModuleCodegen<B::Module>),
802}
803804/// Actual LTO type we end up choosing based on multiple factors.
805pub(crate) enum ComputedLtoType {
806 No,
807 Thin,
808 Fat,
809}
810811pub(crate) fn compute_per_cgu_lto_type(
812 sess_lto: &Lto,
813 linker_does_lto: bool,
814 sess_crate_types: &[CrateType],
815) -> ComputedLtoType {
816// If the linker does LTO, we don't have to do it. Note that we
817 // keep doing full LTO, if it is requested, as not to break the
818 // assumption that the output will be a single module.
819820 // We ignore a request for full crate graph LTO if the crate type
821 // is only an rlib, as there is no full crate graph to process,
822 // that'll happen later.
823 //
824 // This use case currently comes up primarily for targets that
825 // require LTO so the request for LTO is always unconditionally
826 // passed down to the backend, but we don't actually want to do
827 // anything about it yet until we've got a final product.
828let is_rlib = #[allow(non_exhaustive_omitted_patterns)] match sess_crate_types {
[CrateType::Rlib] => true,
_ => false,
}matches!(sess_crate_types, [CrateType::Rlib]);
829830match sess_lto {
831 Lto::ThinLocalif !linker_does_lto => ComputedLtoType::Thin,
832 Lto::Thinif !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
833 Lto::Fatif !is_rlib => ComputedLtoType::Fat,
834_ => ComputedLtoType::No,
835 }
836}
837838fn execute_optimize_work_item<B: ExtraBackendMethods>(
839 cgcx: &CodegenContext,
840 prof: &SelfProfilerRef,
841 shared_emitter: SharedEmitter,
842mut module: ModuleCodegen<B::Module>,
843) -> WorkItemResult<B> {
844let _timer = prof.generic_activity_with_arg("codegen_module_optimize", &*module.name);
845846 B::optimize(cgcx, prof, &shared_emitter, &mut module, &cgcx.module_config);
847848// After we've done the initial round of optimizations we need to
849 // decide whether to synchronously codegen this module or ship it
850 // back to the coordinator thread for further LTO processing (which
851 // has to wait for all the initial modules to be optimized).
852853let lto_type =
854compute_per_cgu_lto_type(&cgcx.lto, cgcx.use_linker_plugin_lto, &cgcx.crate_types);
855856// If we're doing some form of incremental LTO then we need to be sure to
857 // save our module to disk first.
858let bitcode = if cgcx.module_config.emit_pre_lto_bc {
859let filename = pre_lto_bitcode_filename(&module.name);
860cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
861 } else {
862None863 };
864865match lto_type {
866 ComputedLtoType::No => {
867let module = B::codegen(cgcx, &prof, &shared_emitter, module, &cgcx.module_config);
868 WorkItemResult::Finished(module)
869 }
870 ComputedLtoType::Thin => {
871let thin_buffer = B::serialize_module(module.module_llvm, true);
872if let Some(path) = bitcode {
873 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
874{
::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);
875 });
876 }
877 WorkItemResult::NeedsThinLto(module.name, thin_buffer)
878 }
879 ComputedLtoType::Fat => match bitcode {
880Some(path) => {
881let buffer = B::serialize_module(module.module_llvm, false);
882 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
883{
::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);
884 });
885 WorkItemResult::NeedsFatLto(FatLtoInput::Serialized {
886 name: module.name,
887 buffer: SerializedModule::Local(buffer),
888 })
889 }
890None => WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module)),
891 },
892 }
893}
894895fn execute_copy_from_cache_work_item(
896 cgcx: &CodegenContext,
897 prof: &SelfProfilerRef,
898 shared_emitter: SharedEmitter,
899 module: CachedModuleCodegen,
900) -> CompiledModule {
901let _timer =
902prof.generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &*module.name);
903904let dcx = DiagCtxt::new(Box::new(shared_emitter));
905let dcx = dcx.handle();
906907let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
908909let mut links_from_incr_cache = Vec::new();
910911let mut load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
912let source_file = in_incr_comp_dir(incr_comp_session_dir, saved_path);
913{
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:913",
"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(913u32),
::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!(
914"copying preexisting module `{}` from {:?} to {}",
915 module.name,
916 source_file,
917 output_path.display()
918 );
919match link_or_copy(&source_file, &output_path) {
920Ok(_) => {
921links_from_incr_cache.push(source_file);
922Some(output_path)
923 }
924Err(error) => {
925dcx.emit_err(errors::CopyPathBuf { source_file, output_path, error });
926None927 }
928 }
929 };
930931let dwarf_object =
932module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
933let dwarf_obj_out = cgcx934 .output_filenames
935 .split_dwarf_path(
936cgcx.split_debuginfo,
937cgcx.split_dwarf_kind,
938&module.name,
939cgcx.invocation_temp.as_deref(),
940 )
941 .expect(
942"saved dwarf object in work product but `split_dwarf_path` returned `None`",
943 );
944load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
945 });
946947let mut load_from_incr_cache = |perform, output_type: OutputType| {
948if perform {
949let saved_file = module.source.saved_files.get(output_type.extension())?;
950let output_path = cgcx.output_filenames.temp_path_for_cgu(
951output_type,
952&module.name,
953cgcx.invocation_temp.as_deref(),
954 );
955load_from_incr_comp_dir(output_path, &saved_file)
956 } else {
957None958 }
959 };
960961let module_config = &cgcx.module_config;
962let should_emit_obj = module_config.emit_obj != EmitObj::None;
963let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
964let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
965let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
966let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
967if should_emit_obj && object.is_none() {
968dcx.emit_fatal(errors::NoSavedObjectFile { cgu_name: &module.name })
969 }
970971CompiledModule {
972links_from_incr_cache,
973 kind: ModuleKind::Regular,
974 name: module.name,
975object,
976dwarf_object,
977bytecode,
978assembly,
979llvm_ir,
980 }
981}
982983fn do_fat_lto<B: ExtraBackendMethods>(
984 cgcx: &CodegenContext,
985 prof: &SelfProfilerRef,
986 shared_emitter: SharedEmitter,
987 tm_factory: TargetMachineFactoryFn<B>,
988 exported_symbols_for_lto: &[String],
989 each_linked_rlib_for_lto: &[PathBuf],
990mut needs_fat_lto: Vec<FatLtoInput<B>>,
991 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
992) -> CompiledModule {
993let _timer = prof.verbose_generic_activity("LLVM_fatlto");
994995let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
996let dcx = dcx.handle();
997998check_lto_allowed(&cgcx, dcx);
9991000for (module, wp) in import_only_modules {
1001 needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, buffer: module })
1002 }
10031004let module = B::run_and_optimize_fat_lto(
1005cgcx,
1006prof,
1007&shared_emitter,
1008tm_factory,
1009exported_symbols_for_lto,
1010each_linked_rlib_for_lto,
1011needs_fat_lto,
1012 );
1013 B::codegen(cgcx, prof, &shared_emitter, module, &cgcx.module_config)
1014}
10151016fn do_thin_lto<B: ExtraBackendMethods>(
1017 cgcx: &CodegenContext,
1018 prof: &SelfProfilerRef,
1019 shared_emitter: SharedEmitter,
1020 tm_factory: TargetMachineFactoryFn<B>,
1021 exported_symbols_for_lto: Arc<Vec<String>>,
1022 each_linked_rlib_for_lto: Vec<PathBuf>,
1023 needs_thin_lto: Vec<(String, <B as WriteBackendMethods>::ModuleBuffer)>,
1024 lto_import_only_modules: Vec<(
1025SerializedModule<<B as WriteBackendMethods>::ModuleBuffer>,
1026WorkProduct,
1027 )>,
1028) -> Vec<CompiledModule> {
1029let _timer = prof.verbose_generic_activity("LLVM_thinlto");
10301031let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
1032let dcx = dcx.handle();
10331034check_lto_allowed(&cgcx, dcx);
10351036let (coordinator_send, coordinator_receive) = channel();
10371038// First up, convert our jobserver into a helper thread so we can use normal
1039 // mpsc channels to manage our messages and such.
1040 // After we've requested tokens then we'll, when we can,
1041 // get tokens on `coordinator_receive` which will
1042 // get managed in the main loop below.
1043let coordinator_send2 = coordinator_send.clone();
1044let helper = jobserver::client()
1045 .into_helper_thread(move |token| {
1046drop(coordinator_send2.send(ThinLtoMessage::Token(token)));
1047 })
1048 .expect("failed to spawn helper thread");
10491050let mut work_items = ::alloc::vec::Vec::new()vec![];
10511052// We have LTO work to do. Perform the serial work here of
1053 // figuring out what we're going to LTO and then push a
1054 // bunch of work items onto our queue to do LTO. This all
1055 // happens on the coordinator thread but it's very quick so
1056 // we don't worry about tokens.
1057for (work, cost) in generate_thin_lto_work::<B>(
1058 cgcx,
1059 prof,
1060 dcx,
1061&exported_symbols_for_lto,
1062&each_linked_rlib_for_lto,
1063 needs_thin_lto,
1064 lto_import_only_modules,
1065 ) {
1066let insertion_index =
1067 work_items.binary_search_by_key(&cost, |&(_, cost)| cost).unwrap_or_else(|e| e);
1068 work_items.insert(insertion_index, (work, cost));
1069if cgcx.parallel {
1070 helper.request_token();
1071 }
1072 }
10731074let mut codegen_aborted = None;
10751076// These are the Jobserver Tokens we currently hold. Does not include
1077 // the implicit Token the compiler process owns no matter what.
1078let mut tokens = ::alloc::vec::Vec::new()vec![];
10791080// Amount of tokens that are used (including the implicit token).
1081let mut used_token_count = 0;
10821083let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
10841085// Run the message loop while there's still anything that needs message
1086 // processing. Note that as soon as codegen is aborted we simply want to
1087 // wait for all existing work to finish, so many of the conditions here
1088 // only apply if codegen hasn't been aborted as they represent pending
1089 // work to be done.
1090loop {
1091if codegen_aborted.is_none() {
1092if used_token_count == 0 && work_items.is_empty() {
1093// All codegen work is done.
1094break;
1095 }
10961097// Spin up what work we can, only doing this while we've got available
1098 // parallelism slots and work left to spawn.
1099while used_token_count < tokens.len() + 1
1100&& let Some((item, _)) = work_items.pop()
1101 {
1102 spawn_thin_lto_work(
1103&cgcx,
1104 prof,
1105 shared_emitter.clone(),
1106 Arc::clone(&tm_factory),
1107 coordinator_send.clone(),
1108 item,
1109 );
1110 used_token_count += 1;
1111 }
1112 } else {
1113// Don't queue up any more work if codegen was aborted, we're
1114 // just waiting for our existing children to finish.
1115if used_token_count == 0 {
1116break;
1117 }
1118 }
11191120// Relinquish accidentally acquired extra tokens. Subtract 1 for the implicit token.
1121tokens.truncate(used_token_count.saturating_sub(1));
11221123match coordinator_receive.recv().unwrap() {
1124// Save the token locally and the next turn of the loop will use
1125 // this to spawn a new unit of work, or it may get dropped
1126 // immediately if we have no more work to spawn.
1127ThinLtoMessage::Token(token) => match token {
1128Ok(token) => {
1129tokens.push(token);
1130 }
1131Err(e) => {
1132let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1133shared_emitter.fatal(msg);
1134codegen_aborted = Some(FatalError);
1135 }
1136 },
11371138 ThinLtoMessage::WorkItem { result } => {
1139// If a thread exits successfully then we drop a token associated
1140 // with that worker and update our `used_token_count` count.
1141 // We may later re-acquire a token to continue running more work.
1142 // We may also not actually drop a token here if the worker was
1143 // running with an "ephemeral token".
1144used_token_count -= 1;
11451146match result {
1147Ok(compiled_module) => compiled_modules.push(compiled_module),
1148Err(Some(WorkerFatalError)) => {
1149// Like `CodegenAborted`, wait for remaining work to finish.
1150codegen_aborted = Some(FatalError);
1151 }
1152Err(None) => {
1153// If the thread failed that means it panicked, so
1154 // we abort immediately.
1155::rustc_middle::util::bug::bug_fmt(format_args!("worker thread panicked"));bug!("worker thread panicked");
1156 }
1157 }
1158 }
1159 }
1160 }
11611162if let Some(codegen_aborted) = codegen_aborted {
1163codegen_aborted.raise();
1164 }
11651166compiled_modules1167}
11681169fn execute_thin_lto_work_item<B: ExtraBackendMethods>(
1170 cgcx: &CodegenContext,
1171 prof: &SelfProfilerRef,
1172 shared_emitter: SharedEmitter,
1173 tm_factory: TargetMachineFactoryFn<B>,
1174 module: lto::ThinModule<B>,
1175) -> CompiledModule {
1176let _timer = prof.generic_activity_with_arg("codegen_module_perform_lto", module.name());
11771178let module = B::optimize_thin(cgcx, prof, &shared_emitter, tm_factory, module);
1179 B::codegen(cgcx, prof, &shared_emitter, module, &cgcx.module_config)
1180}
11811182/// Messages sent to the coordinator.
1183pub(crate) enum Message<B: WriteBackendMethods> {
1184/// A jobserver token has become available. Sent from the jobserver helper
1185 /// thread.
1186Token(io::Result<Acquired>),
11871188/// The backend has finished processing a work item for a codegen unit.
1189 /// Sent from a backend worker thread.
1190WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>> },
11911192/// The frontend has finished generating something (backend IR or a
1193 /// post-LTO artifact) for a codegen unit, and it should be passed to the
1194 /// backend. Sent from the main thread.
1195CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
11961197/// Similar to `CodegenDone`, but for reusing a pre-LTO artifact
1198 /// Sent from the main thread.
1199AddImportOnlyModule {
1200 module_data: SerializedModule<B::ModuleBuffer>,
1201 work_product: WorkProduct,
1202 },
12031204/// The frontend has finished generating everything for all codegen units.
1205 /// Sent from the main thread.
1206CodegenComplete,
12071208/// Some normal-ish compiler error occurred, and codegen should be wound
1209 /// down. Sent from the main thread.
1210CodegenAborted,
1211}
12121213/// Messages sent to the coordinator.
1214pub(crate) enum ThinLtoMessage {
1215/// A jobserver token has become available. Sent from the jobserver helper
1216 /// thread.
1217Token(io::Result<Acquired>),
12181219/// The backend has finished processing a work item for a codegen unit.
1220 /// Sent from a backend worker thread.
1221WorkItem { result: Result<CompiledModule, Option<WorkerFatalError>> },
1222}
12231224/// A message sent from the coordinator thread to the main thread telling it to
1225/// process another codegen unit.
1226pub struct CguMessage;
12271228// A cut-down version of `rustc_errors::DiagInner` that impls `Send`, which
1229// can be used to send diagnostics from codegen threads to the main thread.
1230// It's missing the following fields from `rustc_errors::DiagInner`.
1231// - `span`: it doesn't impl `Send`.
1232// - `suggestions`: it doesn't impl `Send`, and isn't used for codegen
1233// diagnostics.
1234// - `sort_span`: it doesn't impl `Send`.
1235// - `is_lint`: lints aren't relevant during codegen.
1236// - `emitted_at`: not used for codegen diagnostics.
1237struct Diagnostic {
1238 span: Vec<SpanData>,
1239 level: Level,
1240 messages: Vec<(DiagMessage, Style)>,
1241 code: Option<ErrCode>,
1242 children: Vec<Subdiagnostic>,
1243 args: DiagArgMap,
1244}
12451246// A cut-down version of `rustc_errors::Subdiag` that impls `Send`. It's
1247// missing the following fields from `rustc_errors::Subdiag`.
1248// - `span`: it doesn't impl `Send`.
1249struct Subdiagnostic {
1250 level: Level,
1251 messages: Vec<(DiagMessage, Style)>,
1252}
12531254#[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)]
1255enum MainThreadState {
1256/// Doing nothing.
1257Idle,
12581259/// Doing codegen, i.e. MIR-to-LLVM-IR conversion.
1260Codegenning,
12611262/// Idle, but lending the compiler process's Token to an LLVM thread so it can do useful work.
1263Lending,
1264}
12651266fn start_executing_work<B: ExtraBackendMethods>(
1267 backend: B,
1268 tcx: TyCtxt<'_>,
1269 crate_info: &CrateInfo,
1270 shared_emitter: SharedEmitter,
1271 codegen_worker_send: Sender<CguMessage>,
1272 coordinator_receive: Receiver<Message<B>>,
1273 regular_config: Arc<ModuleConfig>,
1274 allocator_config: Arc<ModuleConfig>,
1275mut allocator_module: Option<ModuleCodegen<B::Module>>,
1276 coordinator_send: Sender<Message<B>>,
1277) -> thread::JoinHandle<Result<MaybeLtoModules<B>, ()>> {
1278let sess = tcx.sess;
1279let prof = sess.prof.clone();
12801281let mut each_linked_rlib_for_lto = Vec::new();
1282let mut each_linked_rlib_file_for_lto = Vec::new();
1283drop(link::each_linked_rlib(crate_info, None, &mut |cnum, path| {
1284if link::ignored_for_lto(sess, crate_info, cnum) {
1285return;
1286 }
1287each_linked_rlib_for_lto.push(cnum);
1288each_linked_rlib_file_for_lto.push(path.to_path_buf());
1289 }));
12901291// Compute the set of symbols we need to retain when doing LTO (if we need to)
1292let exported_symbols_for_lto =
1293Arc::new(lto::exported_symbols_for_lto(tcx, &each_linked_rlib_for_lto));
12941295// First up, convert our jobserver into a helper thread so we can use normal
1296 // mpsc channels to manage our messages and such.
1297 // After we've requested tokens then we'll, when we can,
1298 // get tokens on `coordinator_receive` which will
1299 // get managed in the main loop below.
1300let coordinator_send2 = coordinator_send.clone();
1301let helper = jobserver::client()
1302 .into_helper_thread(move |token| {
1303drop(coordinator_send2.send(Message::Token::<B>(token)));
1304 })
1305 .expect("failed to spawn helper thread");
13061307let opt_level = tcx.backend_optimization_level(());
1308let backend_features = tcx.global_backend_features(()).clone();
1309let tm_factory = backend.target_machine_factory(tcx.sess, opt_level, &backend_features);
13101311let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1312let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1313match result {
1314Ok(dir) => Some(dir),
1315Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1316 }
1317 } else {
1318None1319 };
13201321let cgcx = CodegenContext {
1322 crate_types: tcx.crate_types().to_vec(),
1323 lto: sess.lto(),
1324 use_linker_plugin_lto: sess.opts.cg.linker_plugin_lto.enabled(),
1325 dylib_lto: sess.opts.unstable_opts.dylib_lto,
1326 prefer_dynamic: sess.opts.cg.prefer_dynamic,
1327 fewer_names: sess.fewer_names(),
1328 save_temps: sess.opts.cg.save_temps,
1329 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1330 remark: sess.opts.cg.remark.clone(),
1331remark_dir,
1332 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1333 output_filenames: Arc::clone(tcx.output_filenames(())),
1334 module_config: regular_config,
1335opt_level,
1336backend_features,
1337 msvc_imps_needed: msvc_imps_needed(tcx),
1338 is_pe_coff: tcx.sess.target.is_like_windows,
1339 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1340 target_arch: tcx.sess.target.arch.to_string(),
1341 target_is_like_darwin: tcx.sess.target.is_like_darwin,
1342 target_is_like_aix: tcx.sess.target.is_like_aix,
1343 target_is_like_gpu: tcx.sess.target.is_like_gpu,
1344 split_debuginfo: tcx.sess.split_debuginfo(),
1345 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1346 parallel: backend.supports_parallel() && !sess.opts.unstable_opts.no_parallel_backend,
1347 pointer_size: tcx.data_layout.pointer_size(),
1348 invocation_temp: sess.invocation_temp.clone(),
1349 };
13501351// This is the "main loop" of parallel work happening for parallel codegen.
1352 // It's here that we manage parallelism, schedule work, and work with
1353 // messages coming from clients.
1354 //
1355 // There are a few environmental pre-conditions that shape how the system
1356 // is set up:
1357 //
1358 // - Error reporting can only happen on the main thread because that's the
1359 // only place where we have access to the compiler `Session`.
1360 // - LLVM work can be done on any thread.
1361 // - Codegen can only happen on the main thread.
1362 // - Each thread doing substantial work must be in possession of a `Token`
1363 // from the `Jobserver`.
1364 // - The compiler process always holds one `Token`. Any additional `Tokens`
1365 // have to be requested from the `Jobserver`.
1366 //
1367 // Error Reporting
1368 // ===============
1369 // The error reporting restriction is handled separately from the rest: We
1370 // set up a `SharedEmitter` that holds an open channel to the main thread.
1371 // When an error occurs on any thread, the shared emitter will send the
1372 // error message to the receiver main thread (`SharedEmitterMain`). The
1373 // main thread will periodically query this error message queue and emit
1374 // any error messages it has received. It might even abort compilation if
1375 // it has received a fatal error. In this case we rely on all other threads
1376 // being torn down automatically with the main thread.
1377 // Since the main thread will often be busy doing codegen work, error
1378 // reporting will be somewhat delayed, since the message queue can only be
1379 // checked in between two work packages.
1380 //
1381 // Work Processing Infrastructure
1382 // ==============================
1383 // The work processing infrastructure knows three major actors:
1384 //
1385 // - the coordinator thread,
1386 // - the main thread, and
1387 // - LLVM worker threads
1388 //
1389 // The coordinator thread is running a message loop. It instructs the main
1390 // thread about what work to do when, and it will spawn off LLVM worker
1391 // threads as open LLVM WorkItems become available.
1392 //
1393 // The job of the main thread is to codegen CGUs into LLVM work packages
1394 // (since the main thread is the only thread that can do this). The main
1395 // thread will block until it receives a message from the coordinator, upon
1396 // which it will codegen one CGU, send it to the coordinator and block
1397 // again. This way the coordinator can control what the main thread is
1398 // doing.
1399 //
1400 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1401 // available, it will spawn off a new LLVM worker thread and let it process
1402 // a WorkItem. When a LLVM worker thread is done with its WorkItem,
1403 // it will just shut down, which also frees all resources associated with
1404 // the given LLVM module, and sends a message to the coordinator that the
1405 // WorkItem has been completed.
1406 //
1407 // Work Scheduling
1408 // ===============
1409 // The scheduler's goal is to minimize the time it takes to complete all
1410 // work there is, however, we also want to keep memory consumption low
1411 // if possible. These two goals are at odds with each other: If memory
1412 // consumption were not an issue, we could just let the main thread produce
1413 // LLVM WorkItems at full speed, assuring maximal utilization of
1414 // Tokens/LLVM worker threads. However, since codegen is usually faster
1415 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1416 // WorkItem potentially holds on to a substantial amount of memory.
1417 //
1418 // So the actual goal is to always produce just enough LLVM WorkItems as
1419 // not to starve our LLVM worker threads. That means, once we have enough
1420 // WorkItems in our queue, we can block the main thread, so it does not
1421 // produce more until we need them.
1422 //
1423 // Doing LLVM Work on the Main Thread
1424 // ----------------------------------
1425 // Since the main thread owns the compiler process's implicit `Token`, it is
1426 // wasteful to keep it blocked without doing any work. Therefore, what we do
1427 // in this case is: We spawn off an additional LLVM worker thread that helps
1428 // reduce the queue. The work it is doing corresponds to the implicit
1429 // `Token`. The coordinator will mark the main thread as being busy with
1430 // LLVM work. (The actual work happens on another OS thread but we just care
1431 // about `Tokens`, not actual threads).
1432 //
1433 // When any LLVM worker thread finishes while the main thread is marked as
1434 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1435 // of the just finished thread to the LLVM worker thread that is working on
1436 // behalf of the main thread's implicit Token, thus freeing up the main
1437 // thread again. The coordinator can then again decide what the main thread
1438 // should do. This allows the coordinator to make decisions at more points
1439 // in time.
1440 //
1441 // Striking a Balance between Throughput and Memory Consumption
1442 // ------------------------------------------------------------
1443 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1444 // memory consumption as low as possible, are in conflict with each other,
1445 // we have to find a trade off between them. Right now, the goal is to keep
1446 // all workers busy, which means that no worker should find the queue empty
1447 // when it is ready to start.
1448 // How do we do achieve this? Good question :) We actually never know how
1449 // many `Tokens` are potentially available so it's hard to say how much to
1450 // fill up the queue before switching the main thread to LLVM work. Also we
1451 // currently don't have a means to estimate how long a running LLVM worker
1452 // will still be busy with it's current WorkItem. However, we know the
1453 // maximal count of available Tokens that makes sense (=the number of CPU
1454 // cores), so we can take a conservative guess. The heuristic we use here
1455 // is implemented in the `queue_full_enough()` function.
1456 //
1457 // Some Background on Jobservers
1458 // -----------------------------
1459 // It's worth also touching on the management of parallelism here. We don't
1460 // want to just spawn a thread per work item because while that's optimal
1461 // parallelism it may overload a system with too many threads or violate our
1462 // configuration for the maximum amount of cpu to use for this process. To
1463 // manage this we use the `jobserver` crate.
1464 //
1465 // Job servers are an artifact of GNU make and are used to manage
1466 // parallelism between processes. A jobserver is a glorified IPC semaphore
1467 // basically. Whenever we want to run some work we acquire the semaphore,
1468 // and whenever we're done with that work we release the semaphore. In this
1469 // manner we can ensure that the maximum number of parallel workers is
1470 // capped at any one point in time.
1471 //
1472 // LTO and the coordinator thread
1473 // ------------------------------
1474 //
1475 // The final job the coordinator thread is responsible for is managing LTO
1476 // and how that works. When LTO is requested what we'll do is collect all
1477 // optimized LLVM modules into a local vector on the coordinator. Once all
1478 // modules have been codegened and optimized we hand this to the `lto`
1479 // module for further optimization. The `lto` module will return back a list
1480 // of more modules to work on, which the coordinator will continue to spawn
1481 // work for.
1482 //
1483 // Each LLVM module is automatically sent back to the coordinator for LTO if
1484 // necessary. There's already optimizations in place to avoid sending work
1485 // back to the coordinator if LTO isn't requested.
1486return B::spawn_named_thread(cgcx.time_trace, "coordinator".to_string(), move || {
1487// This is where we collect codegen units that have gone all the way
1488 // through codegen and LLVM.
1489let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
1490let mut needs_fat_lto = Vec::new();
1491let mut needs_thin_lto = Vec::new();
1492let mut lto_import_only_modules = Vec::new();
14931494/// Possible state transitions:
1495 /// - Ongoing -> Completed
1496 /// - Ongoing -> Aborted
1497 /// - Completed -> Aborted
1498#[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)]
1499enum CodegenState {
1500 Ongoing,
1501 Completed,
1502 Aborted,
1503 }
1504use CodegenState::*;
1505let mut codegen_state = Ongoing;
15061507// This is the queue of LLVM work items that still need processing.
1508let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
15091510// This are the Jobserver Tokens we currently hold. Does not include
1511 // the implicit Token the compiler process owns no matter what.
1512let mut tokens = Vec::new();
15131514let mut main_thread_state = MainThreadState::Idle;
15151516// How many LLVM worker threads are running while holding a Token. This
1517 // *excludes* any that the main thread is lending a Token to.
1518let mut running_with_own_token = 0;
15191520// How many LLVM worker threads are running in total. This *includes*
1521 // any that the main thread is lending a Token to.
1522let running_with_any_token = |main_thread_state, running_with_own_token| {
1523running_with_own_token1524 + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1525 };
15261527let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
15281529if let Some(allocator_module) = &mut allocator_module {
1530 B::optimize(&cgcx, &prof, &shared_emitter, allocator_module, &allocator_config);
1531 }
15321533// Run the message loop while there's still anything that needs message
1534 // processing. Note that as soon as codegen is aborted we simply want to
1535 // wait for all existing work to finish, so many of the conditions here
1536 // only apply if codegen hasn't been aborted as they represent pending
1537 // work to be done.
1538loop {
1539// While there are still CGUs to be codegened, the coordinator has
1540 // to decide how to utilize the compiler processes implicit Token:
1541 // For codegenning more CGU or for running them through LLVM.
1542if codegen_state == Ongoing {
1543if main_thread_state == MainThreadState::Idle {
1544// Compute the number of workers that will be running once we've taken as many
1545 // items from the work queue as we can, plus one for the main thread. It's not
1546 // critically important that we use this instead of just
1547 // `running_with_own_token`, but it prevents the `queue_full_enough` heuristic
1548 // from fluctuating just because a worker finished up and we decreased the
1549 // `running_with_own_token` count, even though we're just going to increase it
1550 // right after this when we put a new worker to work.
1551let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1552let additional_running = std::cmp::min(extra_tokens, work_items.len());
1553let anticipated_running = running_with_own_token + additional_running + 1;
15541555if !queue_full_enough(work_items.len(), anticipated_running) {
1556// The queue is not full enough, process more codegen units:
1557if codegen_worker_send.send(CguMessage).is_err() {
1558{
::core::panicking::panic_fmt(format_args!("Could not send CguMessage to main thread"));
}panic!("Could not send CguMessage to main thread")1559 }
1560main_thread_state = MainThreadState::Codegenning;
1561 } else {
1562// The queue is full enough to not let the worker
1563 // threads starve. Use the implicit Token to do some
1564 // LLVM work too.
1565let (item, _) =
1566work_items.pop().expect("queue empty - queue_full_enough() broken?");
1567main_thread_state = MainThreadState::Lending;
1568spawn_work(
1569&cgcx,
1570&prof,
1571shared_emitter.clone(),
1572coordinator_send.clone(),
1573&mut llvm_start_time,
1574item,
1575 );
1576 }
1577 }
1578 } else if codegen_state == Completed {
1579if running_with_any_token(main_thread_state, running_with_own_token) == 0
1580&& work_items.is_empty()
1581 {
1582// All codegen work is done.
1583break;
1584 }
15851586// In this branch, we know that everything has been codegened,
1587 // so it's just a matter of determining whether the implicit
1588 // Token is free to use for LLVM work.
1589match main_thread_state {
1590 MainThreadState::Idle => {
1591if let Some((item, _)) = work_items.pop() {
1592main_thread_state = MainThreadState::Lending;
1593spawn_work(
1594&cgcx,
1595&prof,
1596shared_emitter.clone(),
1597coordinator_send.clone(),
1598&mut llvm_start_time,
1599item,
1600 );
1601 } else {
1602// There is no unstarted work, so let the main thread
1603 // take over for a running worker. Otherwise the
1604 // implicit token would just go to waste.
1605 // We reduce the `running` counter by one. The
1606 // `tokens.truncate()` below will take care of
1607 // giving the Token back.
1608if !(running_with_own_token > 0) {
::core::panicking::panic("assertion failed: running_with_own_token > 0")
};assert!(running_with_own_token > 0);
1609running_with_own_token -= 1;
1610main_thread_state = MainThreadState::Lending;
1611 }
1612 }
1613 MainThreadState::Codegenning => ::rustc_middle::util::bug::bug_fmt(format_args!("codegen worker should not be codegenning after codegen was already completed"))bug!(
1614"codegen worker should not be codegenning after \
1615 codegen was already completed"
1616),
1617 MainThreadState::Lending => {
1618// Already making good use of that token
1619}
1620 }
1621 } else {
1622// Don't queue up any more work if codegen was aborted, we're
1623 // just waiting for our existing children to finish.
1624if !(codegen_state == Aborted) {
::core::panicking::panic("assertion failed: codegen_state == Aborted")
};assert!(codegen_state == Aborted);
1625if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1626break;
1627 }
1628 }
16291630// Spin up what work we can, only doing this while we've got available
1631 // parallelism slots and work left to spawn.
1632if codegen_state != Aborted {
1633while running_with_own_token < tokens.len()
1634 && let Some((item, _)) = work_items.pop()
1635 {
1636 spawn_work(
1637&cgcx,
1638&prof,
1639 shared_emitter.clone(),
1640 coordinator_send.clone(),
1641&mut llvm_start_time,
1642 item,
1643 );
1644 running_with_own_token += 1;
1645 }
1646 }
16471648// Relinquish accidentally acquired extra tokens.
1649tokens.truncate(running_with_own_token);
16501651match coordinator_receive.recv().unwrap() {
1652// Save the token locally and the next turn of the loop will use
1653 // this to spawn a new unit of work, or it may get dropped
1654 // immediately if we have no more work to spawn.
1655Message::Token(token) => {
1656match token {
1657Ok(token) => {
1658tokens.push(token);
16591660if main_thread_state == MainThreadState::Lending {
1661// If the main thread token is used for LLVM work
1662 // at the moment, we turn that thread into a regular
1663 // LLVM worker thread, so the main thread is free
1664 // to react to codegen demand.
1665main_thread_state = MainThreadState::Idle;
1666running_with_own_token += 1;
1667 }
1668 }
1669Err(e) => {
1670let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1671shared_emitter.fatal(msg);
1672codegen_state = Aborted;
1673 }
1674 }
1675 }
16761677 Message::CodegenDone { llvm_work_item, cost } => {
1678// We keep the queue sorted by estimated processing cost,
1679 // so that more expensive items are processed earlier. This
1680 // is good for throughput as it gives the main thread more
1681 // time to fill up the queue and it avoids scheduling
1682 // expensive items to the end.
1683 // Note, however, that this is not ideal for memory
1684 // consumption, as LLVM module sizes are not evenly
1685 // distributed.
1686let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1687let insertion_index = match insertion_index {
1688Ok(idx) | Err(idx) => idx,
1689 };
1690work_items.insert(insertion_index, (llvm_work_item, cost));
16911692if cgcx.parallel {
1693helper.request_token();
1694 }
1695match (&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);
1696main_thread_state = MainThreadState::Idle;
1697 }
16981699 Message::CodegenComplete => {
1700if codegen_state != Aborted {
1701codegen_state = Completed;
1702 }
1703match (&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);
1704main_thread_state = MainThreadState::Idle;
1705 }
17061707// If codegen is aborted that means translation was aborted due
1708 // to some normal-ish compiler error. In this situation we want
1709 // to exit as soon as possible, but we want to make sure all
1710 // existing work has finished. Flag codegen as being done, and
1711 // then conditions above will ensure no more work is spawned but
1712 // we'll keep executing this loop until `running_with_own_token`
1713 // hits 0.
1714Message::CodegenAborted => {
1715codegen_state = Aborted;
1716 }
17171718 Message::WorkItem { result } => {
1719// If a thread exits successfully then we drop a token associated
1720 // with that worker and update our `running_with_own_token` count.
1721 // We may later re-acquire a token to continue running more work.
1722 // We may also not actually drop a token here if the worker was
1723 // running with an "ephemeral token".
1724if main_thread_state == MainThreadState::Lending {
1725main_thread_state = MainThreadState::Idle;
1726 } else {
1727running_with_own_token -= 1;
1728 }
17291730match result {
1731Ok(WorkItemResult::Finished(compiled_module)) => {
1732compiled_modules.push(compiled_module);
1733 }
1734Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1735if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
1736needs_fat_lto.push(fat_lto_input);
1737 }
1738Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1739if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
1740needs_thin_lto.push((name, thin_buffer));
1741 }
1742Err(Some(WorkerFatalError)) => {
1743// Like `CodegenAborted`, wait for remaining work to finish.
1744codegen_state = Aborted;
1745 }
1746Err(None) => {
1747// If the thread failed that means it panicked, so
1748 // we abort immediately.
1749::rustc_middle::util::bug::bug_fmt(format_args!("worker thread panicked"));bug!("worker thread panicked");
1750 }
1751 }
1752 }
17531754 Message::AddImportOnlyModule { module_data, work_product } => {
1755match (&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);
1756match (&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);
1757lto_import_only_modules.push((module_data, work_product));
1758main_thread_state = MainThreadState::Idle;
1759 }
1760 }
1761 }
17621763// Drop to print timings
1764drop(llvm_start_time);
17651766if codegen_state == Aborted {
1767return Err(());
1768 }
17691770drop(codegen_state);
1771drop(tokens);
1772drop(helper);
1773if !work_items.is_empty() {
::core::panicking::panic("assertion failed: work_items.is_empty()")
};assert!(work_items.is_empty());
17741775if !needs_fat_lto.is_empty() {
1776if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1777if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
17781779if let Some(allocator_module) = allocator_module.take() {
1780needs_fat_lto.push(FatLtoInput::InMemory(allocator_module));
1781 }
17821783return Ok(MaybeLtoModules::FatLto {
1784cgcx,
1785exported_symbols_for_lto,
1786each_linked_rlib_file_for_lto,
1787needs_fat_lto,
1788lto_import_only_modules,
1789 });
1790 } else if !needs_thin_lto.is_empty() || !lto_import_only_modules.is_empty() {
1791if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1792if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
17931794if cgcx.lto == Lto::ThinLocal {
1795compiled_modules.extend(do_thin_lto::<B>(
1796&cgcx,
1797&prof,
1798shared_emitter.clone(),
1799tm_factory,
1800exported_symbols_for_lto,
1801each_linked_rlib_file_for_lto,
1802needs_thin_lto,
1803lto_import_only_modules,
1804 ));
1805 } else {
1806if let Some(allocator_module) = allocator_module.take() {
1807let thin_buffer = B::serialize_module(allocator_module.module_llvm, true);
1808needs_thin_lto.push((allocator_module.name, thin_buffer));
1809 }
18101811return Ok(MaybeLtoModules::ThinLto {
1812cgcx,
1813exported_symbols_for_lto,
1814each_linked_rlib_file_for_lto,
1815needs_thin_lto,
1816lto_import_only_modules,
1817 });
1818 }
1819 }
18201821Ok(MaybeLtoModules::NoLto {
1822 modules: compiled_modules,
1823 allocator_module: allocator_module.map(|allocator_module| {
1824 B::codegen(&cgcx, &prof, &shared_emitter, allocator_module, &allocator_config)
1825 }),
1826 })
1827 })
1828 .expect("failed to spawn coordinator thread");
18291830// A heuristic that determines if we have enough LLVM WorkItems in the
1831 // queue so that the main thread can do LLVM work instead of codegen
1832fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1833// This heuristic scales ahead-of-time codegen according to available
1834 // concurrency, as measured by `workers_running`. The idea is that the
1835 // more concurrency we have available, the more demand there will be for
1836 // work items, and the fuller the queue should be kept to meet demand.
1837 // An important property of this approach is that we codegen ahead of
1838 // time only as much as necessary, so as to keep fewer LLVM modules in
1839 // memory at once, thereby reducing memory consumption.
1840 //
1841 // When the number of workers running is less than the max concurrency
1842 // available to us, this heuristic can cause us to instruct the main
1843 // thread to work on an LLVM item (that is, tell it to "LLVM") instead
1844 // of codegen, even though it seems like it *should* be codegenning so
1845 // that we can create more work items and spawn more LLVM workers.
1846 //
1847 // But this is not a problem. When the main thread is told to LLVM,
1848 // according to this heuristic and how work is scheduled, there is
1849 // always at least one item in the queue, and therefore at least one
1850 // pending jobserver token request. If there *is* more concurrency
1851 // available, we will immediately receive a token, which will upgrade
1852 // the main thread's LLVM worker to a real one (conceptually), and free
1853 // up the main thread to codegen if necessary. On the other hand, if
1854 // there isn't more concurrency, then the main thread working on an LLVM
1855 // item is appropriate, as long as the queue is full enough for demand.
1856 //
1857 // Speaking of which, how full should we keep the queue? Probably less
1858 // full than you'd think. A lot has to go wrong for the queue not to be
1859 // full enough and for that to have a negative effect on compile times.
1860 //
1861 // Workers are unlikely to finish at exactly the same time, so when one
1862 // finishes and takes another work item off the queue, we often have
1863 // ample time to codegen at that point before the next worker finishes.
1864 // But suppose that codegen takes so long that the workers exhaust the
1865 // queue, and we have one or more workers that have nothing to work on.
1866 // Well, it might not be so bad. Of all the LLVM modules we create and
1867 // optimize, one has to finish last. It's not necessarily the case that
1868 // by losing some concurrency for a moment, we delay the point at which
1869 // that last LLVM module is finished and the rest of compilation can
1870 // proceed. Also, when we can't take advantage of some concurrency, we
1871 // give tokens back to the job server. That enables some other rustc to
1872 // potentially make use of the available concurrency. That could even
1873 // *decrease* overall compile time if we're lucky. But yes, if no other
1874 // rustc can make use of the concurrency, then we've squandered it.
1875 //
1876 // However, keeping the queue full is also beneficial when we have a
1877 // surge in available concurrency. Then items can be taken from the
1878 // queue immediately, without having to wait for codegen.
1879 //
1880 // So, the heuristic below tries to keep one item in the queue for every
1881 // four running workers. Based on limited benchmarking, this appears to
1882 // be more than sufficient to avoid increasing compilation times.
1883let quarter_of_workers = workers_running - 3 * workers_running / 4;
1884items_in_queue > 0 && items_in_queue >= quarter_of_workers1885 }
1886}
18871888/// `FatalError` is explicitly not `Send`.
1889#[must_use]
1890pub(crate) struct WorkerFatalError;
18911892fn spawn_work<'a, B: ExtraBackendMethods>(
1893 cgcx: &CodegenContext,
1894 prof: &'a SelfProfilerRef,
1895 shared_emitter: SharedEmitter,
1896 coordinator_send: Sender<Message<B>>,
1897 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1898 work: WorkItem<B>,
1899) {
1900if llvm_start_time.is_none() {
1901*llvm_start_time = Some(prof.verbose_generic_activity("LLVM_passes"));
1902 }
19031904let cgcx = cgcx.clone();
1905let prof = prof.clone();
19061907 B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1908let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1909 WorkItem::Optimize(m) => execute_optimize_work_item(&cgcx, &prof, shared_emitter, m),
1910 WorkItem::CopyPostLtoArtifacts(m) => WorkItemResult::Finished(
1911execute_copy_from_cache_work_item(&cgcx, &prof, shared_emitter, m),
1912 ),
1913 }));
19141915let msg = match result {
1916Ok(result) => Message::WorkItem::<B> { result: Ok(result) },
19171918// We ignore any `FatalError` coming out of `execute_work_item`, as a
1919 // diagnostic was already sent off to the main thread - just surface
1920 // that there was an error in this worker.
1921Err(err) if err.is::<FatalErrorMarker>() => {
1922 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1923 }
19241925Err(_) => Message::WorkItem::<B> { result: Err(None) },
1926 };
1927drop(coordinator_send.send(msg));
1928 })
1929 .expect("failed to spawn work thread");
1930}
19311932fn spawn_thin_lto_work<B: ExtraBackendMethods>(
1933 cgcx: &CodegenContext,
1934 prof: &SelfProfilerRef,
1935 shared_emitter: SharedEmitter,
1936 tm_factory: TargetMachineFactoryFn<B>,
1937 coordinator_send: Sender<ThinLtoMessage>,
1938 work: ThinLtoWorkItem<B>,
1939) {
1940let cgcx = cgcx.clone();
1941let prof = prof.clone();
19421943 B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1944let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1945 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
1946execute_copy_from_cache_work_item(&cgcx, &prof, shared_emitter, m)
1947 }
1948 ThinLtoWorkItem::ThinLto(m) => {
1949execute_thin_lto_work_item(&cgcx, &prof, shared_emitter, tm_factory, m)
1950 }
1951 }));
19521953let msg = match result {
1954Ok(result) => ThinLtoMessage::WorkItem { result: Ok(result) },
19551956// We ignore any `FatalError` coming out of `execute_work_item`, as a
1957 // diagnostic was already sent off to the main thread - just surface
1958 // that there was an error in this worker.
1959Err(err) if err.is::<FatalErrorMarker>() => {
1960 ThinLtoMessage::WorkItem { result: Err(Some(WorkerFatalError)) }
1961 }
19621963Err(_) => ThinLtoMessage::WorkItem { result: Err(None) },
1964 };
1965drop(coordinator_send.send(msg));
1966 })
1967 .expect("failed to spawn work thread");
1968}
19691970enum SharedEmitterMessage {
1971 Diagnostic(Diagnostic),
1972 InlineAsmError(InlineAsmError),
1973 Fatal(String),
1974}
19751976pub struct InlineAsmError {
1977pub span: SpanData,
1978pub msg: String,
1979pub level: Level,
1980pub source: Option<(String, Vec<InnerSpan>)>,
1981}
19821983#[derive(#[automatically_derived]
impl ::core::clone::Clone for SharedEmitter {
#[inline]
fn clone(&self) -> SharedEmitter {
SharedEmitter { sender: ::core::clone::Clone::clone(&self.sender) }
}
}Clone)]
1984pub struct SharedEmitter {
1985 sender: Sender<SharedEmitterMessage>,
1986}
19871988pub struct SharedEmitterMain {
1989 receiver: Receiver<SharedEmitterMessage>,
1990}
19911992impl SharedEmitter {
1993fn new() -> (SharedEmitter, SharedEmitterMain) {
1994let (sender, receiver) = channel();
19951996 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1997 }
19981999pub fn inline_asm_error(&self, err: InlineAsmError) {
2000drop(self.sender.send(SharedEmitterMessage::InlineAsmError(err)));
2001 }
20022003fn fatal(&self, msg: &str) {
2004drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
2005 }
2006}
20072008impl Emitterfor SharedEmitter {
2009fn emit_diagnostic(&mut self, mut diag: rustc_errors::DiagInner) {
2010// Check that we aren't missing anything interesting when converting to
2011 // the cut-down local `DiagInner`.
2012if !!diag.span.has_span_labels() {
::core::panicking::panic("assertion failed: !diag.span.has_span_labels()")
};assert!(!diag.span.has_span_labels());
2013match (&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![]));
2014match (&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);
2015match (&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);
2016// No sensible check for `diag.emitted_at`.
20172018let args = mem::replace(&mut diag.args, DiagArgMap::default());
2019drop(
2020self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2021 span: diag.span.primary_spans().iter().map(|span| span.data()).collect::<Vec<_>>(),
2022 level: diag.level(),
2023 messages: diag.messages,
2024 code: diag.code,
2025 children: diag2026 .children
2027 .into_iter()
2028 .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
2029 .collect(),
2030args,
2031 })),
2032 );
2033 }
20342035fn source_map(&self) -> Option<&SourceMap> {
2036None2037 }
2038}
20392040impl SharedEmitterMain {
2041fn check(&self, sess: &Session, blocking: bool) {
2042loop {
2043let message = if blocking {
2044match self.receiver.recv() {
2045Ok(message) => Ok(message),
2046Err(_) => Err(()),
2047 }
2048 } else {
2049match self.receiver.try_recv() {
2050Ok(message) => Ok(message),
2051Err(_) => Err(()),
2052 }
2053 };
20542055match message {
2056Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2057// The diagnostic has been received on the main thread.
2058 // Convert it back to a full `Diagnostic` and emit.
2059let dcx = sess.dcx();
2060let mut d =
2061 rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
2062d.span = MultiSpan::from_spans(
2063diag.span.into_iter().map(|span| span.span()).collect(),
2064 );
2065d.code = diag.code; // may be `None`, that's ok
2066d.children = diag2067 .children
2068 .into_iter()
2069 .map(|sub| rustc_errors::Subdiag {
2070 level: sub.level,
2071 messages: sub.messages,
2072 span: MultiSpan::new(),
2073 })
2074 .collect();
2075d.args = diag.args;
2076dcx.emit_diagnostic(d);
2077sess.dcx().abort_if_errors();
2078 }
2079Ok(SharedEmitterMessage::InlineAsmError(inner)) => {
2080match 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);
2081let mut err = Diag::<()>::new(sess.dcx(), inner.level, inner.msg);
2082if !inner.span.is_dummy() {
2083err.span(inner.span.span());
2084 }
20852086// Point to the generated assembly if it is available.
2087if let Some((buffer, spans)) = inner.source {
2088let source = sess2089 .source_map()
2090 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
2091let spans: Vec<_> = spans2092 .iter()
2093 .map(|sp| {
2094Span::with_root_ctxt(
2095source.normalized_byte_pos(sp.start as u32),
2096source.normalized_byte_pos(sp.end as u32),
2097 )
2098 })
2099 .collect();
2100err.span_note(spans, "instantiated into assembly here");
2101 }
21022103err.emit();
2104 }
2105Ok(SharedEmitterMessage::Fatal(msg)) => {
2106sess.dcx().fatal(msg);
2107 }
2108Err(_) => {
2109break;
2110 }
2111 }
2112 }
2113 }
2114}
21152116pub struct Coordinator<B: ExtraBackendMethods> {
2117 sender: Sender<Message<B>>,
2118 future: Option<thread::JoinHandle<Result<MaybeLtoModules<B>, ()>>>,
2119// Only used for the Message type.
2120phantom: PhantomData<B>,
2121}
21222123impl<B: ExtraBackendMethods> Coordinator<B> {
2124fn join(mut self) -> std::thread::Result<Result<MaybeLtoModules<B>, ()>> {
2125self.future.take().unwrap().join()
2126 }
2127}
21282129impl<B: ExtraBackendMethods> Dropfor Coordinator<B> {
2130fn drop(&mut self) {
2131if let Some(future) = self.future.take() {
2132// If we haven't joined yet, signal to the coordinator that it should spawn no more
2133 // work, and wait for worker threads to finish.
2134drop(self.sender.send(Message::CodegenAborted::<B>));
2135drop(future.join());
2136 }
2137 }
2138}
21392140pub struct OngoingCodegen<B: ExtraBackendMethods> {
2141pub backend: B,
2142pub crate_info: CrateInfo,
2143pub output_filenames: Arc<OutputFilenames>,
2144// Field order below is intended to terminate the coordinator thread before two fields below
2145 // drop and prematurely close channels used by coordinator thread. See `Coordinator`'s
2146 // `Drop` implementation for more info.
2147pub coordinator: Coordinator<B>,
2148pub codegen_worker_receive: Receiver<CguMessage>,
2149pub shared_emitter_main: SharedEmitterMain,
2150}
21512152impl<B: ExtraBackendMethods> OngoingCodegen<B> {
2153pub fn join(self, sess: &Session) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
2154self.shared_emitter_main.check(sess, true);
21552156let maybe_lto_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
2157Ok(Ok(maybe_lto_modules)) => maybe_lto_modules,
2158Ok(Err(())) => {
2159sess.dcx().abort_if_errors();
2160{
::core::panicking::panic_fmt(format_args!("expected abort due to worker thread errors"));
}panic!("expected abort due to worker thread errors")2161 }
2162Err(_) => {
2163::rustc_middle::util::bug::bug_fmt(format_args!("panic during codegen/LLVM phase"));bug!("panic during codegen/LLVM phase");
2164 }
2165 });
21662167sess.dcx().abort_if_errors();
21682169let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
21702171// Catch fatal errors to ensure shared_emitter_main.check() can emit the actual diagnostics
2172let compiled_modules = catch_fatal_errors(|| match maybe_lto_modules {
2173 MaybeLtoModules::NoLto { modules, allocator_module } => {
2174drop(shared_emitter);
2175CompiledModules { modules, allocator_module }
2176 }
2177 MaybeLtoModules::FatLto {
2178 cgcx,
2179 exported_symbols_for_lto,
2180 each_linked_rlib_file_for_lto,
2181 needs_fat_lto,
2182 lto_import_only_modules,
2183 } => {
2184let tm_factory = self.backend.target_machine_factory(
2185sess,
2186cgcx.opt_level,
2187&cgcx.backend_features,
2188 );
21892190CompiledModules {
2191 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(
2192&cgcx,
2193&sess.prof,
2194 shared_emitter,
2195 tm_factory,
2196&exported_symbols_for_lto,
2197&each_linked_rlib_file_for_lto,
2198 needs_fat_lto,
2199 lto_import_only_modules,
2200 )],
2201 allocator_module: None,
2202 }
2203 }
2204 MaybeLtoModules::ThinLto {
2205 cgcx,
2206 exported_symbols_for_lto,
2207 each_linked_rlib_file_for_lto,
2208 needs_thin_lto,
2209 lto_import_only_modules,
2210 } => {
2211let tm_factory = self.backend.target_machine_factory(
2212sess,
2213cgcx.opt_level,
2214&cgcx.backend_features,
2215 );
22162217CompiledModules {
2218 modules: do_thin_lto::<B>(
2219&cgcx,
2220&sess.prof,
2221shared_emitter,
2222tm_factory,
2223exported_symbols_for_lto,
2224each_linked_rlib_file_for_lto,
2225needs_thin_lto,
2226lto_import_only_modules,
2227 ),
2228 allocator_module: None,
2229 }
2230 }
2231 });
22322233shared_emitter_main.check(sess, true);
22342235sess.dcx().abort_if_errors();
22362237let mut compiled_modules =
2238compiled_modules.expect("fatal error emitted but not sent to SharedEmitter");
22392240// Regardless of what order these modules completed in, report them to
2241 // the backend in the same order every time to ensure that we're handing
2242 // out deterministic results.
2243compiled_modules.modules.sort_by(|a, b| a.name.cmp(&b.name));
22442245let work_products =
2246copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
2247produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
22482249// FIXME: time_llvm_passes support - does this use a global context or
2250 // something?
2251if sess.codegen_units().as_usize() == 1 && sess.opts.unstable_opts.time_llvm_passes {
2252self.backend.print_pass_timings()
2253 }
22542255if sess.print_llvm_stats() {
2256self.backend.print_statistics()
2257 }
22582259 (
2260CodegenResults {
2261 crate_info: self.crate_info,
22622263 modules: compiled_modules.modules,
2264 allocator_module: compiled_modules.allocator_module,
2265 },
2266work_products,
2267 )
2268 }
22692270pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2271self.wait_for_signal_to_codegen_item();
2272self.check_for_errors(tcx.sess);
2273drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
2274 }
22752276pub(crate) fn check_for_errors(&self, sess: &Session) {
2277self.shared_emitter_main.check(sess, false);
2278 }
22792280pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2281match self.codegen_worker_receive.recv() {
2282Ok(CguMessage) => {
2283// Ok to proceed.
2284}
2285Err(_) => {
2286// One of the LLVM threads must have panicked, fall through so
2287 // error handling can be reached.
2288}
2289 }
2290 }
2291}
22922293pub(crate) fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
2294 coordinator: &Coordinator<B>,
2295 module: ModuleCodegen<B::Module>,
2296 cost: u64,
2297) {
2298let llvm_work_item = WorkItem::Optimize(module);
2299drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2300}
23012302pub(crate) fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
2303 coordinator: &Coordinator<B>,
2304 module: CachedModuleCodegen,
2305) {
2306let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2307drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2308}
23092310pub(crate) fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
2311 tcx: TyCtxt<'_>,
2312 coordinator: &Coordinator<B>,
2313 module: CachedModuleCodegen,
2314) {
2315let filename = pre_lto_bitcode_filename(&module.name);
2316let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2317let file = fs::File::open(&bc_path)
2318 .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));
23192320let mmap = unsafe {
2321Mmap::map(file).unwrap_or_else(|e| {
2322{
::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)2323 })
2324 };
2325// Schedule the module to be loaded
2326drop(coordinator.sender.send(Message::AddImportOnlyModule::<B> {
2327 module_data: SerializedModule::FromUncompressedFile(mmap),
2328 work_product: module.source,
2329 }));
2330}
23312332fn pre_lto_bitcode_filename(module_name: &str) -> String {
2333::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.{1}", module_name,
PRE_LTO_BC_EXT))
})format!("{module_name}.{PRE_LTO_BC_EXT}")2334}
23352336fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2337// This should never be true (because it's not supported). If it is true,
2338 // something is wrong with commandline arg validation.
2339if !!(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!(
2340 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2341 && tcx.sess.target.is_like_windows
2342 && tcx.sess.opts.cg.prefer_dynamic)
2343 );
23442345// We need to generate _imp__ symbol if we are generating an rlib or we include one
2346 // indirectly from ThinLTO. In theory these are not needed as ThinLTO could resolve
2347 // these, but it currently does not do so.
2348let can_have_static_objects =
2349tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
23502351tcx.sess.target.is_like_windows &&
2352can_have_static_objects &&
2353// ThinLTO can't handle this workaround in all cases, so we don't
2354 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2355 // dynamic linking when linker plugin LTO is enabled.
2356!tcx.sess.opts.cg.linker_plugin_lto.enabled()
2357}