1use std::marker::PhantomData;
2use std::num::NonZero;
3use std::panic::AssertUnwindSafe;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use std::sync::mpsc::{Receiver, Sender, channel};
7use std::{assert_matches, fs, io, str, thread};
89use rustc_abi::Size;
10use rustc_data_structures::jobserver::{self, Acquired};
11use rustc_data_structures::profiling::{SelfProfilerRef, VerboseTimingGuard};
12use rustc_errors::emitter::Emitter;
13use rustc_errors::{
14Diag, DiagCtxt, DiagCtxtHandle, DiagInner, FatalError, FatalErrorMarker, Level,
15catch_fatal_errors,
16};
17use rustc_fs_util::link_or_copy;
18use rustc_incremental::{
19copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir_sess, in_old_incr_comp_dir_sess,
20};
21use rustc_macros::{Decodable, Encodable};
22use rustc_metadata::fs::copy_to_stdout;
23use rustc_middle::dep_graph::{WorkProduct, WorkProductMap};
24use rustc_middle::ty::TyCtxt;
25use rustc_session::config::{
26self, Lto, OptLevel, OutFileName, OutputFilenames, OutputType, Passes, SwitchWithOptPath,
27};
28use rustc_session::{IncrCompSession, Session};
29use rustc_span::source_map::SourceMap;
30use rustc_span::{BytePos, FileName, InnerSpan, Span, SyntaxContext, bug};
31use rustc_structures::CrateType;
32use rustc_target::spec::{MergeFunctions, SanitizerSet};
33use tracing::debug;
3435use crate::back::link::ensure_removed;
36use crate::back::lto::{self, SerializedModule, check_lto_allowed};
37use crate::diagnostics::ErrorCreatingRemarkDir;
38use crate::traits::*;
39use crate::{
40CachedModuleCodegen, CompiledModule, CompiledModules, CrateInfo, ModuleCodegen, ModuleKind,
41diagnostics,
42};
4344const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
4546/// What kind of object file to emit.
47#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for EmitObj { }
#[automatically_derived]
impl ::core::clone::Clone for EmitObj {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<BitcodeSection>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for EmitObj { }Copy, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for EmitObj { }
#[automatically_derived]
impl ::core::cmp::PartialEq for EmitObj {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::ObjectCode(__self_0), Self::ObjectCode(__arg1_0)) =>
__self_0 == __arg1_0,
_ => true,
}
}
}PartialEq, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for EmitObj {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
EmitObj::None => { 0usize }
EmitObj::Bitcode => { 1usize }
EmitObj::ObjectCode(ref __binding_0) => { 2usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
match *self {
EmitObj::None => {}
EmitObj::Bitcode => {}
EmitObj::ObjectCode(ref __binding_0) => {
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
}
}
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for EmitObj {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { EmitObj::None }
1usize => { EmitObj::Bitcode }
2usize => {
EmitObj::ObjectCode(::rustc_serialize::Decodable::decode(__decoder))
}
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `EmitObj`, expected 0..3, actual {0}",
n));
}
}
}
}
};Decodable)]
48pub enum EmitObj {
49// No object file.
50None,
5152// Just uncompressed llvm bitcode. Provides easy compatibility with
53 // emscripten's ecc compiler, when used as the linker.
54Bitcode,
5556// Object code, possibly augmented with a bitcode section.
57ObjectCode(BitcodeSection),
58}
5960/// What kind of llvm bitcode section to embed in an object file.
61#[derive(#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for BitcodeSection { }
#[automatically_derived]
impl ::core::clone::Clone for BitcodeSection {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for BitcodeSection { }Copy, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for BitcodeSection { }
#[automatically_derived]
impl ::core::cmp::PartialEq for BitcodeSection {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for BitcodeSection {
fn encode(&self, __encoder: &mut __E) {
let disc =
match *self {
BitcodeSection::None => { 0usize }
BitcodeSection::Full => { 1usize }
};
::rustc_serialize::Encoder::emit_u8(__encoder, disc as u8);
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for BitcodeSection {
fn decode(__decoder: &mut __D) -> Self {
match ::rustc_serialize::Decoder::read_u8(__decoder) as usize
{
0usize => { BitcodeSection::None }
1usize => { BitcodeSection::Full }
n => {
::core::panicking::panic_fmt(format_args!("invalid enum variant tag while decoding `BitcodeSection`, expected 0..2, actual {0}",
n));
}
}
}
}
};Decodable)]
62pub enum BitcodeSection {
63// No bitcode section.
64None,
6566// A full, uncompressed bitcode section.
67Full,
68}
6970/// Module-specific configuration for `optimize_and_codegen`.
71#[derive(const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for ModuleConfig {
fn encode(&self, __encoder: &mut __E) {
let ModuleConfig {
passes: ref __binding_0,
opt_level: ref __binding_1,
pgo_gen: ref __binding_2,
pgo_use: ref __binding_3,
pgo_sample_use: ref __binding_4,
debug_info_for_profiling: ref __binding_5,
instrument_coverage: ref __binding_6,
sanitizer: ref __binding_7,
sanitizer_cfi_diag: ref __binding_8,
sanitizer_cfi_recover: ref __binding_9,
sanitizer_recover: ref __binding_10,
sanitizer_dataflow_abilist: ref __binding_11,
sanitizer_memory_track_origins: ref __binding_12,
emit_pre_lto_bc: ref __binding_13,
emit_bc: ref __binding_14,
emit_ir: ref __binding_15,
emit_asm: ref __binding_16,
emit_obj: ref __binding_17,
emit_thin_lto_summary: ref __binding_18,
verify_llvm_ir: ref __binding_19,
lint_llvm_ir: ref __binding_20,
no_prepopulate_passes: ref __binding_21,
no_builtins: ref __binding_22,
vectorize_loop: ref __binding_23,
vectorize_slp: ref __binding_24,
merge_functions: ref __binding_25,
emit_lifetime_markers: ref __binding_26,
llvm_plugins: ref __binding_27,
autodiff: ref __binding_28,
autodiff_post_passes: ref __binding_29,
offload: ref __binding_30 } = *self;
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_2,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_3,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_4,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_5,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_6,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_7,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_8,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_9,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_10,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_11,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_12,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_13,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_14,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_15,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_16,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_17,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_18,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_19,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_20,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_21,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_22,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_23,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_24,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_25,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_26,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_27,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_28,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_29,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_30,
__encoder);
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for ModuleConfig {
fn decode(__decoder: &mut __D) -> Self {
ModuleConfig {
passes: ::rustc_serialize::Decodable::decode(__decoder),
opt_level: ::rustc_serialize::Decodable::decode(__decoder),
pgo_gen: ::rustc_serialize::Decodable::decode(__decoder),
pgo_use: ::rustc_serialize::Decodable::decode(__decoder),
pgo_sample_use: ::rustc_serialize::Decodable::decode(__decoder),
debug_info_for_profiling: ::rustc_serialize::Decodable::decode(__decoder),
instrument_coverage: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer_cfi_diag: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer_cfi_recover: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer_recover: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer_dataflow_abilist: ::rustc_serialize::Decodable::decode(__decoder),
sanitizer_memory_track_origins: ::rustc_serialize::Decodable::decode(__decoder),
emit_pre_lto_bc: ::rustc_serialize::Decodable::decode(__decoder),
emit_bc: ::rustc_serialize::Decodable::decode(__decoder),
emit_ir: ::rustc_serialize::Decodable::decode(__decoder),
emit_asm: ::rustc_serialize::Decodable::decode(__decoder),
emit_obj: ::rustc_serialize::Decodable::decode(__decoder),
emit_thin_lto_summary: ::rustc_serialize::Decodable::decode(__decoder),
verify_llvm_ir: ::rustc_serialize::Decodable::decode(__decoder),
lint_llvm_ir: ::rustc_serialize::Decodable::decode(__decoder),
no_prepopulate_passes: ::rustc_serialize::Decodable::decode(__decoder),
no_builtins: ::rustc_serialize::Decodable::decode(__decoder),
vectorize_loop: ::rustc_serialize::Decodable::decode(__decoder),
vectorize_slp: ::rustc_serialize::Decodable::decode(__decoder),
merge_functions: ::rustc_serialize::Decodable::decode(__decoder),
emit_lifetime_markers: ::rustc_serialize::Decodable::decode(__decoder),
llvm_plugins: ::rustc_serialize::Decodable::decode(__decoder),
autodiff: ::rustc_serialize::Decodable::decode(__decoder),
autodiff_post_passes: ::rustc_serialize::Decodable::decode(__decoder),
offload: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
72pub struct ModuleConfig {
73/// Names of additional optimization passes to run.
74pub passes: Vec<String>,
75/// Some(level) to optimize at a certain level, or None to run
76 /// absolutely no optimizations (used for the allocator module).
77pub opt_level: Option<config::OptLevel>,
7879pub pgo_gen: SwitchWithOptPath,
80pub pgo_use: Option<PathBuf>,
81pub pgo_sample_use: Option<PathBuf>,
82pub debug_info_for_profiling: bool,
83pub instrument_coverage: bool,
8485pub sanitizer: SanitizerSet,
86pub sanitizer_cfi_diag: Option<bool>,
87pub sanitizer_cfi_recover: Option<bool>,
88pub sanitizer_recover: SanitizerSet,
89pub sanitizer_dataflow_abilist: Vec<String>,
90pub sanitizer_memory_track_origins: usize,
9192// Flags indicating which outputs to produce.
93pub emit_pre_lto_bc: bool,
94pub emit_bc: bool,
95pub emit_ir: bool,
96pub emit_asm: bool,
97pub emit_obj: EmitObj,
98pub emit_thin_lto_summary: bool,
99100// Miscellaneous flags. These are mostly copied from command-line
101 // options.
102pub verify_llvm_ir: bool,
103pub lint_llvm_ir: bool,
104pub no_prepopulate_passes: bool,
105pub no_builtins: bool,
106pub vectorize_loop: bool,
107pub vectorize_slp: bool,
108pub merge_functions: bool,
109pub emit_lifetime_markers: bool,
110pub llvm_plugins: Vec<String>,
111pub autodiff: Vec<config::AutoDiff>,
112pub autodiff_post_passes: Option<String>,
113pub offload: Vec<config::Offload>,
114}
115116impl ModuleConfig {
117pub(crate) fn new(kind: ModuleKind, tcx: TyCtxt<'_>, no_builtins: bool) -> ModuleConfig {
118// If it's a regular module, use `$regular`, otherwise use `$other`.
119 // `$regular` and `$other` are evaluated lazily.
120macro_rules! if_regular {
121 ($regular: expr, $other: expr) => {
122if let ModuleKind::Regular = kind { $regular } else { $other }
123 };
124 }
125126let sess = tcx.sess;
127let opt_level_and_size = if let ModuleKind::Regular = kind { Some(sess.opts.optimize) } else { None }if_regular!(Some(sess.opts.optimize), None);
128129let save_temps = sess.opts.cg.save_temps;
130131let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
132 || match kind {
133 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
134 ModuleKind::Allocator => false,
135 };
136137let emit_obj = if !should_emit_obj {
138 EmitObj::None139 } else if sess.target.obj_is_bitcode
140 || (sess.opts.cg.linker_plugin_lto.enabled()
141 && (!no_builtins || tcx.sess.is_sanitizer_cfi_enabled()))
142 {
143// This case is selected if the target uses objects as bitcode, or
144 // if linker plugin LTO is enabled. In the linker plugin LTO case
145 // the assumption is that the final link-step will read the bitcode
146 // and convert it to object code. This may be done by either the
147 // native linker or rustc itself.
148 //
149 // By default this branch is skipped for `#![no_builtins]` crates so
150 // they emit native object files (machine code), not LLVM bitcode
151 // objects for the linker (see rust-lang/rust#146133).
152 //
153 // However, when LLVM CFI is enabled (`-Zsanitizer=cfi`), this
154 // breaks LLVM's expected pipeline: LLVM emits `llvm.type.test`
155 // intrinsics and related metadata that must be lowered by LLVM's
156 // `LowerTypeTests` pass before instruction selection during
157 // link-time LTO. Otherwise, `llvm.type.test` intrinsics and related
158 // metadata are not lowered by LLVM's `LowerTypeTests` pass before
159 // reaching the target backend, and LLVM may abort during codegen
160 // (for example in SelectionDAG type legalization) (see
161 // rust-lang/rust#142284).
162 //
163 // Therefore, with `-Clinker-plugin-lto` and `-Zsanitizer=cfi`, a
164 // `#![no_builtins]` crate must still use rustc's `EmitObj::Bitcode`
165 // path (and emit LLVM bitcode in the `.o` for linker-based LTO).
166EmitObj::Bitcode167 } else if need_bitcode_in_object(tcx) || sess.target.requires_lto {
168 EmitObj::ObjectCode(BitcodeSection::Full)
169 } else {
170 EmitObj::ObjectCode(BitcodeSection::None)
171 };
172173ModuleConfig {
174 passes: if let ModuleKind::Regular = kind {
sess.opts.cg.passes.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.cg.passes.clone(), vec![]),
175176 opt_level: opt_level_and_size,
177178 pgo_gen: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_generate.clone()
} else { SwitchWithOptPath::Disabled }if_regular!(
179 sess.opts.cg.profile_generate.clone(),
180 SwitchWithOptPath::Disabled
181 ),
182 pgo_use: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_use.clone()
} else { None }if_regular!(sess.opts.cg.profile_use.clone(), None),
183 pgo_sample_use: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_sample_use.clone()
} else { None }if_regular!(sess.opts.cg.profile_sample_use.clone(), None),
184 debug_info_for_profiling: sess.opts.unstable_opts.debuginfo_for_profiling,
185 instrument_coverage: if let ModuleKind::Regular = kind {
sess.instrument_coverage()
} else { false }if_regular!(sess.instrument_coverage(), false),
186187 sanitizer: if let ModuleKind::Regular = kind {
sess.sanitizers()
} else { SanitizerSet::empty() }if_regular!(sess.sanitizers(), SanitizerSet::empty()),
188 sanitizer_cfi_diag: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_cfi_diag
} else { None }if_regular!(sess.opts.unstable_opts.sanitizer_cfi_diag, None),
189 sanitizer_cfi_recover: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_cfi_recover
} else { None }if_regular!(sess.opts.unstable_opts.sanitizer_cfi_recover, None),
190 sanitizer_dataflow_abilist: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone()
} else { Vec::new() }if_regular!(
191 sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
192 Vec::new()
193 ),
194 sanitizer_recover: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_recover
} else { SanitizerSet::empty() }if_regular!(
195 sess.opts.unstable_opts.sanitizer_recover,
196 SanitizerSet::empty()
197 ),
198 sanitizer_memory_track_origins: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_memory_track_origins
} else { 0 }if_regular!(
199 sess.opts.unstable_opts.sanitizer_memory_track_origins,
2000
201),
202203 emit_pre_lto_bc: if let ModuleKind::Regular = kind {
save_temps || need_pre_lto_bitcode_for_incr_comp(sess)
} else { false }if_regular!(
204 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
205false
206),
207 emit_bc: if let ModuleKind::Regular = kind {
save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode)
} else { save_temps }if_regular!(
208 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
209 save_temps
210 ),
211 emit_ir: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::LlvmAssembly)
} else { false }if_regular!(
212 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
213false
214),
215 emit_asm: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::Assembly)
} else { false }if_regular!(
216 sess.opts.output_types.contains_key(&OutputType::Assembly),
217false
218),
219emit_obj,
220 emit_thin_lto_summary: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode)
} else { false }if_regular!(
221 sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode),
222false
223),
224225 verify_llvm_ir: sess.verify_llvm_ir(),
226 lint_llvm_ir: sess.opts.unstable_opts.lint_llvm_ir,
227 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
228 no_builtins: no_builtins || sess.target.no_builtins,
229230// Copy what clang does by turning on loop vectorization at O2 and
231 // slp vectorization at O3.
232vectorize_loop: !sess.opts.cg.no_vectorize_loops
233 && (sess.opts.optimize == config::OptLevel::More234 || sess.opts.optimize == config::OptLevel::Aggressive),
235 vectorize_slp: !sess.opts.cg.no_vectorize_slp
236 && sess.opts.optimize == config::OptLevel::Aggressive,
237238// Some targets (namely, NVPTX) interact badly with the
239 // MergeFunctions pass. This is because MergeFunctions can generate
240 // new function calls which may interfere with the target calling
241 // convention; e.g. for the NVPTX target, PTX kernels should not
242 // call other PTX kernels. MergeFunctions can also be configured to
243 // generate aliases instead, but aliases are not supported by some
244 // backends (again, NVPTX). Therefore, allow targets to opt out of
245 // the MergeFunctions pass, but otherwise keep the pass enabled (at
246 // O2 and O3) since it can be useful for reducing code size.
247merge_functions: match sess.merge_functions() {
248 MergeFunctions::Disabled => false,
249 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
250use config::OptLevel::*;
251match sess.opts.optimize {
252Aggressive | More | SizeMin | Size => true,
253Less | No => false,
254 }
255 }
256 },
257258 emit_lifetime_markers: sess.emit_lifetime_markers(),
259 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![]),
260 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![]),
261 autodiff_post_passes: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.autodiff_post_passes.clone()
} else { None }if_regular!(
262 sess.opts.unstable_opts.autodiff_post_passes.clone(),
263None
264),
265 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![]),
266 }
267 }
268269pub fn bitcode_needed(&self) -> bool {
270self.emit_bc
271 || self.emit_thin_lto_summary
272 || self.emit_obj == EmitObj::Bitcode273 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
274 }
275276pub fn embed_bitcode(&self) -> bool {
277self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
278 }
279}
280281/// Configuration passed to the function returned by the `target_machine_factory`.
282pub struct TargetMachineFactoryConfig {
283/// Split DWARF is enabled in LLVM by checking that `TM.MCOptions.SplitDwarfFile` isn't empty,
284 /// so the path to the dwarf object has to be provided when we create the target machine.
285 /// This can be ignored by backends which do not need it for their Split DWARF support.
286pub split_dwarf_file: Option<PathBuf>,
287288/// The name of the output object file. Used for setting OutputFilenames in target options
289 /// so that LLVM can emit the CodeView S_OBJNAME record in pdb files
290pub output_obj_file: Option<PathBuf>,
291}
292293impl TargetMachineFactoryConfig {
294pub fn new(cgcx: &CodegenContext, module_name: &str) -> TargetMachineFactoryConfig {
295let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
296cgcx.output_filenames.split_dwarf_path(
297cgcx.split_debuginfo,
298cgcx.split_dwarf_kind,
299module_name,
300 )
301 } else {
302None303 };
304305let output_obj_file =
306Some(cgcx.output_filenames.temp_path_for_cgu(OutputType::Object, module_name));
307TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }
308 }
309}
310311pub type TargetMachineFactoryFn<B> = Arc<
312dyn Fn(
313DiagCtxtHandle<'_>,
314TargetMachineFactoryConfig,
315 ) -> <B as WriteBackendMethods>::TargetMachine316 + Send317 + Sync,
318>;
319320/// Additional resources used by optimize_and_codegen (not module specific)
321#[derive(#[automatically_derived]
impl ::core::clone::Clone for CodegenContext {
#[inline]
fn clone(&self) -> Self {
CodegenContext {
lto: ::core::clone::Clone::clone(&self.lto),
use_linker_plugin_lto: ::core::clone::Clone::clone(&self.use_linker_plugin_lto),
dylib_lto: ::core::clone::Clone::clone(&self.dylib_lto),
prefer_dynamic: ::core::clone::Clone::clone(&self.prefer_dynamic),
save_temps: ::core::clone::Clone::clone(&self.save_temps),
fewer_names: ::core::clone::Clone::clone(&self.fewer_names),
time_trace: ::core::clone::Clone::clone(&self.time_trace),
crate_types: ::core::clone::Clone::clone(&self.crate_types),
output_filenames: ::core::clone::Clone::clone(&self.output_filenames),
module_config: ::core::clone::Clone::clone(&self.module_config),
opt_level: ::core::clone::Clone::clone(&self.opt_level),
msvc_imps_needed: ::core::clone::Clone::clone(&self.msvc_imps_needed),
is_pe_coff: ::core::clone::Clone::clone(&self.is_pe_coff),
target_can_use_split_dwarf: ::core::clone::Clone::clone(&self.target_can_use_split_dwarf),
target_arch: ::core::clone::Clone::clone(&self.target_arch),
target_is_like_darwin: ::core::clone::Clone::clone(&self.target_is_like_darwin),
target_is_like_aix: ::core::clone::Clone::clone(&self.target_is_like_aix),
target_is_like_gpu: ::core::clone::Clone::clone(&self.target_is_like_gpu),
split_debuginfo: ::core::clone::Clone::clone(&self.split_debuginfo),
split_dwarf_kind: ::core::clone::Clone::clone(&self.split_dwarf_kind),
pointer_size: ::core::clone::Clone::clone(&self.pointer_size),
rust_eh_personality_symbol: ::core::clone::Clone::clone(&self.rust_eh_personality_symbol),
remark: ::core::clone::Clone::clone(&self.remark),
remark_dir: ::core::clone::Clone::clone(&self.remark_dir),
old_incr_comp_session_dir: ::core::clone::Clone::clone(&self.old_incr_comp_session_dir),
new_incr_comp_session_dir: ::core::clone::Clone::clone(&self.new_incr_comp_session_dir),
parallel: ::core::clone::Clone::clone(&self.parallel),
}
}
}Clone, const _: () =
{
impl<__E: ::rustc_span::SpanEncoder> ::rustc_serialize::Encodable<__E>
for CodegenContext {
fn encode(&self, __encoder: &mut __E) {
let CodegenContext {
lto: ref __binding_0,
use_linker_plugin_lto: ref __binding_1,
dylib_lto: ref __binding_2,
prefer_dynamic: ref __binding_3,
save_temps: ref __binding_4,
fewer_names: ref __binding_5,
time_trace: ref __binding_6,
crate_types: ref __binding_7,
output_filenames: ref __binding_8,
module_config: ref __binding_9,
opt_level: ref __binding_10,
msvc_imps_needed: ref __binding_11,
is_pe_coff: ref __binding_12,
target_can_use_split_dwarf: ref __binding_13,
target_arch: ref __binding_14,
target_is_like_darwin: ref __binding_15,
target_is_like_aix: ref __binding_16,
target_is_like_gpu: ref __binding_17,
split_debuginfo: ref __binding_18,
split_dwarf_kind: ref __binding_19,
pointer_size: ref __binding_20,
rust_eh_personality_symbol: ref __binding_21,
remark: ref __binding_22,
remark_dir: ref __binding_23,
old_incr_comp_session_dir: ref __binding_24,
new_incr_comp_session_dir: ref __binding_25,
parallel: ref __binding_26 } = *self;
::rustc_serialize::Encodable::<__E>::encode(__binding_0,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_1,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_2,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_3,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_4,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_5,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_6,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_7,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_8,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_9,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_10,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_11,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_12,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_13,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_14,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_15,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_16,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_17,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_18,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_19,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_20,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_21,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_22,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_23,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_24,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_25,
__encoder);
::rustc_serialize::Encodable::<__E>::encode(__binding_26,
__encoder);
}
}
};Encodable, const _: () =
{
impl<__D: ::rustc_span::SpanDecoder> ::rustc_serialize::Decodable<__D>
for CodegenContext {
fn decode(__decoder: &mut __D) -> Self {
CodegenContext {
lto: ::rustc_serialize::Decodable::decode(__decoder),
use_linker_plugin_lto: ::rustc_serialize::Decodable::decode(__decoder),
dylib_lto: ::rustc_serialize::Decodable::decode(__decoder),
prefer_dynamic: ::rustc_serialize::Decodable::decode(__decoder),
save_temps: ::rustc_serialize::Decodable::decode(__decoder),
fewer_names: ::rustc_serialize::Decodable::decode(__decoder),
time_trace: ::rustc_serialize::Decodable::decode(__decoder),
crate_types: ::rustc_serialize::Decodable::decode(__decoder),
output_filenames: ::rustc_serialize::Decodable::decode(__decoder),
module_config: ::rustc_serialize::Decodable::decode(__decoder),
opt_level: ::rustc_serialize::Decodable::decode(__decoder),
msvc_imps_needed: ::rustc_serialize::Decodable::decode(__decoder),
is_pe_coff: ::rustc_serialize::Decodable::decode(__decoder),
target_can_use_split_dwarf: ::rustc_serialize::Decodable::decode(__decoder),
target_arch: ::rustc_serialize::Decodable::decode(__decoder),
target_is_like_darwin: ::rustc_serialize::Decodable::decode(__decoder),
target_is_like_aix: ::rustc_serialize::Decodable::decode(__decoder),
target_is_like_gpu: ::rustc_serialize::Decodable::decode(__decoder),
split_debuginfo: ::rustc_serialize::Decodable::decode(__decoder),
split_dwarf_kind: ::rustc_serialize::Decodable::decode(__decoder),
pointer_size: ::rustc_serialize::Decodable::decode(__decoder),
rust_eh_personality_symbol: ::rustc_serialize::Decodable::decode(__decoder),
remark: ::rustc_serialize::Decodable::decode(__decoder),
remark_dir: ::rustc_serialize::Decodable::decode(__decoder),
old_incr_comp_session_dir: ::rustc_serialize::Decodable::decode(__decoder),
new_incr_comp_session_dir: ::rustc_serialize::Decodable::decode(__decoder),
parallel: ::rustc_serialize::Decodable::decode(__decoder),
}
}
}
};Decodable)]
322pub struct CodegenContext {
323// Resources needed when running LTO
324pub lto: Lto,
325pub use_linker_plugin_lto: bool,
326pub dylib_lto: bool,
327pub prefer_dynamic: bool,
328pub save_temps: bool,
329pub fewer_names: bool,
330pub time_trace: bool,
331pub crate_types: Vec<CrateType>,
332pub output_filenames: Arc<OutputFilenames>,
333pub module_config: Arc<ModuleConfig>,
334pub opt_level: OptLevel,
335pub msvc_imps_needed: bool,
336pub is_pe_coff: bool,
337pub target_can_use_split_dwarf: bool,
338pub target_arch: String,
339pub target_is_like_darwin: bool,
340pub target_is_like_aix: bool,
341pub target_is_like_gpu: bool,
342pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
343pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
344pub pointer_size: Size,
345pub rust_eh_personality_symbol: String,
346347/// LLVM optimizations for which we want to print remarks.
348pub remark: Passes,
349/// Directory into which should the LLVM optimization remarks be written.
350 /// If `None`, they will be written to stderr.
351pub remark_dir: Option<PathBuf>,
352/// The previous incremental compilation session directory, or None if we
353 /// are not compiling incrementally or there is no previous session.
354pub old_incr_comp_session_dir: Option<PathBuf>,
355/// The incremental compilation session directory, or None if we are not
356 /// compiling incrementally
357pub new_incr_comp_session_dir: Option<PathBuf>,
358/// `Some(limit)` if the codegen should be run in parallel.
359 ///
360 /// Depends on [`WriteBackendMethods::supports_parallel()`] and `--jobs-backend`.
361pub parallel: Option<NonZero<usize>>,
362}
363364fn generate_thin_lto_work<B: WriteBackendMethods>(
365 cgcx: &CodegenContext,
366 prof: &SelfProfilerRef,
367 dcx: DiagCtxtHandle<'_>,
368 exported_symbols_for_lto: &[String],
369 each_linked_rlib_for_lto: &[PathBuf],
370 needs_thin_lto: Vec<ThinLtoInput<B>>,
371) -> Vec<(ThinLtoWorkItem<B>, u64)> {
372let _prof_timer = prof.generic_activity("codegen_thin_generate_lto_work");
373374let (lto_modules, copy_jobs) = B::run_thin_lto(
375cgcx,
376prof,
377dcx,
378exported_symbols_for_lto,
379each_linked_rlib_for_lto,
380needs_thin_lto,
381 );
382lto_modules383 .into_iter()
384 .map(|module| {
385let cost = module.cost();
386 (ThinLtoWorkItem::ThinLto(module), cost)
387 })
388 .chain(copy_jobs.into_iter().map(|wp| {
389 (
390 ThinLtoWorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
391 name: wp.cgu_name.clone(),
392 source: wp,
393 }),
3940, // copying is very cheap
395)
396 }))
397 .collect()
398}
399400enum MaybeLtoModules<B: WriteBackendMethods> {
401 NoLto(CompiledModules),
402 FatLto { cgcx: CodegenContext, needs_fat_lto: Vec<FatLtoInput<B>> },
403 ThinLto { cgcx: CodegenContext, needs_thin_lto: Vec<ThinLtoInput<B>> },
404}
405406fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
407let sess = tcx.sess;
408sess.opts.cg.embed_bitcode
409 && tcx.crate_types().contains(&CrateType::Rlib)
410 && sess.opts.output_types.contains_key(&OutputType::Exe)
411}
412413fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
414if sess.opts.incremental.is_none() {
415return false;
416 }
417418match sess.lto() {
419 Lto::No => false,
420 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
421 }
422}
423424pub(crate) fn start_async_codegen<B: WriteBackendMethods>(
425 backend: B,
426 tcx: TyCtxt<'_>,
427 regular_config: Arc<ModuleConfig>,
428 allocator_config: Arc<ModuleConfig>,
429 allocator_module: Option<ModuleCodegen<B::Module>>,
430) -> OngoingCodegen<B> {
431let (coordinator_send, coordinator_receive) = channel();
432433let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
434let (codegen_worker_send, codegen_worker_receive) = channel();
435436let coordinator_thread = start_executing_work(
437backend.clone(),
438tcx,
439shared_emitter,
440codegen_worker_send,
441coordinator_receive,
442regular_config,
443allocator_config,
444allocator_module,
445coordinator_send.clone(),
446 );
447448OngoingCodegen {
449backend,
450451codegen_worker_receive,
452shared_emitter_main,
453 coordinator: Coordinator {
454 sender: coordinator_send,
455 future: Some(coordinator_thread),
456 phantom: PhantomData,
457 },
458 output_filenames: Arc::clone(tcx.output_filenames(())),
459 }
460}
461462fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
463 sess: &Session,
464 incr_comp_session: Option<&IncrCompSession>,
465 compiled_modules: &CompiledModules,
466) -> WorkProductMap {
467let mut work_products = WorkProductMap::default();
468469if sess.opts.incremental.is_none() || sess.opts.unstable_opts.disable_incr_comp_backend_caching
470 {
471return work_products;
472 }
473474let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
475476for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
477let mut files = Vec::new();
478if let Some(object_file_path) = &module.object {
479 files.push((OutputType::Object.extension(), object_file_path.as_path()));
480 }
481if let Some(global_asm_object_file_path) = &module.global_asm_object {
482 files.push(("asm.o", global_asm_object_file_path.as_path()));
483 }
484if let Some(dwarf_object_file_path) = &module.dwarf_object {
485 files.push(("dwo", dwarf_object_file_path.as_path()));
486 }
487if let Some(path) = &module.assembly {
488 files.push((OutputType::Assembly.extension(), path.as_path()));
489 }
490if let Some(path) = &module.llvm_ir {
491 files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
492 }
493if let Some(path) = &module.bytecode {
494 files.push((OutputType::Bitcode.extension(), path.as_path()));
495 }
496let (id, product) = copy_cgu_workproduct_to_incr_comp_cache_dir(
497 sess,
498 incr_comp_session.unwrap(),
499&module.name,
500 files.as_slice(),
501 );
502 work_products.insert(id, product);
503 }
504505work_products506}
507508pub fn produce_final_output_artifacts(
509 sess: &Session,
510 compiled_modules: &CompiledModules,
511 crate_output: &OutputFilenames,
512) {
513let mut user_wants_bitcode = false;
514let mut user_wants_objects = false;
515516// Produce final compile outputs.
517let copy_gracefully = |from: &Path, to: &OutFileName| match to {
518 OutFileName::Stdoutif let Err(e) = copy_to_stdout(from) => {
519sess.dcx().emit_err(diagnostics::CopyPath::new(from, to.as_path(), e));
520 }
521 OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
522sess.dcx().emit_err(diagnostics::CopyPath::new(from, path, e));
523 }
524_ => {}
525 };
526527let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
528if let [module] = &compiled_modules.modules[..] {
529// 1) Only one codegen unit. In this case it's no difficulty
530 // to copy `foo.0.x` to `foo.x`.
531let path = crate_output.temp_path_for_cgu(output_type, &module.name);
532let output = crate_output.path(output_type);
533if !output_type.is_text_output() && output.is_tty() {
534sess.dcx().emit_err(diagnostics::BinaryOutputToTty {
535 shorthand: output_type.shorthand(),
536 });
537 } else {
538copy_gracefully(&path, &output);
539 }
540if !sess.opts.cg.save_temps && !keep_numbered {
541// The user just wants `foo.x`, not `foo.#module-name#.x`.
542ensure_removed(sess.dcx(), &path);
543 }
544 } else {
545if crate_output.outputs.contains_explicit_name(&output_type) {
546// 2) Multiple codegen units, with `--emit foo=some_name`. We have
547 // no good solution for this case, so warn the user.
548sess.dcx().emit_warn(diagnostics::IgnoringEmitPath {
549 extension: output_type.extension(),
550 });
551 } else if crate_output.single_output_file.is_some() {
552// 3) Multiple codegen units, with `-o some_name`. We have
553 // no good solution for this case, so warn the user.
554sess.dcx()
555 .emit_warn(diagnostics::IgnoringOutput { extension: output_type.extension() });
556 } else {
557// 4) Multiple codegen units, but no explicit name. We
558 // just leave the `foo.0.x` files in place.
559 // (We don't have to do any work in this case.)
560}
561 }
562 };
563564// Flag to indicate whether the user explicitly requested bitcode.
565 // Otherwise, we produced it only as a temporary output, and will need
566 // to get rid of it.
567for output_type in crate_output.outputs.keys() {
568match *output_type {
569 OutputType::Bitcode => {
570 user_wants_bitcode = true;
571// Copy to .bc, but always keep the .0.bc. There is a later
572 // check to figure out if we should delete .0.bc files, or keep
573 // them for making an rlib.
574copy_if_one_unit(OutputType::Bitcode, true);
575 }
576 OutputType::ThinLinkBitcode => {
577 copy_if_one_unit(OutputType::ThinLinkBitcode, false);
578 }
579 OutputType::LlvmAssembly => {
580 copy_if_one_unit(OutputType::LlvmAssembly, false);
581 }
582 OutputType::Assembly => {
583 copy_if_one_unit(OutputType::Assembly, false);
584 }
585 OutputType::Object => {
586 user_wants_objects = true;
587 copy_if_one_unit(OutputType::Object, true);
588 }
589 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
590 }
591 }
592593// Clean up unwanted temporary files.
594595 // We create the following files by default:
596 // - #crate#.#module-name#.rcgu.bc
597 // - #crate#.#module-name#.rcgu.o
598 // - #crate#.o (linked from crate.##.rcgu.o)
599 // - #crate#.bc (copied from crate.##.rcgu.bc)
600 // We may create additional files if requested by the user (through
601 // `-C save-temps` or `--emit=` flags).
602603if !sess.opts.cg.save_temps {
604// Remove the temporary .#module-name#.rcgu.o objects. If the user didn't
605 // explicitly request bitcode (with --emit=bc), and the bitcode is not
606 // needed for building an rlib, then we must remove .#module-name#.bc as
607 // well.
608609 // Specific rules for keeping .#module-name#.rcgu.bc:
610 // - If the user requested bitcode (`user_wants_bitcode`), and
611 // codegen_units > 1, then keep it.
612 // - If the user requested bitcode but codegen_units == 1, then we
613 // can toss .#module-name#.rcgu.bc because we copied it to .bc earlier.
614 // - If we're not building an rlib and the user didn't request
615 // bitcode, then delete .#module-name#.rcgu.bc.
616 // If you change how this works, also update back::link::link_rlib,
617 // where .#module-name#.rcgu.bc files are (maybe) deleted after making an
618 // rlib.
619let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
620621let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
622623let keep_numbered_objects =
624needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
625626for module in compiled_modules.modules.iter() {
627if !keep_numbered_objects {
628if let Some(ref path) = module.object {
629 ensure_removed(sess.dcx(), path);
630 }
631632if let Some(ref path) = module.global_asm_object {
633 ensure_removed(sess.dcx(), path);
634 }
635636if let Some(ref path) = module.dwarf_object {
637 ensure_removed(sess.dcx(), path);
638 }
639 }
640641if let Some(ref path) = module.bytecode {
642if !keep_numbered_bitcode {
643 ensure_removed(sess.dcx(), path);
644 }
645 }
646 }
647648if !user_wants_bitcode649 && let Some(ref allocator_module) = compiled_modules.allocator_module
650 && let Some(ref path) = allocator_module.bytecode
651 {
652ensure_removed(sess.dcx(), path);
653 }
654 }
655656if sess.opts.json_artifact_notifications {
657if let [module] = &compiled_modules.modules[..] {
658module.for_each_output(|_path, ty| {
659if sess.opts.output_types.contains_key(&ty) {
660let descr = ty.shorthand();
661// for single cgu file is renamed to drop cgu specific suffix
662 // so we regenerate it the same way
663let path = crate_output.path(ty);
664sess.dcx().emit_artifact_notification(path.as_path(), descr);
665 }
666 });
667 } else {
668for module in &compiled_modules.modules {
669 module.for_each_output(|path, ty| {
670if sess.opts.output_types.contains_key(&ty) {
671let descr = ty.shorthand();
672 sess.dcx().emit_artifact_notification(&path, descr);
673 }
674 });
675 }
676 }
677 }
678679// We leave the following files around by default:
680 // - #crate#.o
681 // - #crate#.bc
682 // These are used in linking steps and will be cleaned up afterward.
683}
684685pub(crate) enum WorkItem<B: WriteBackendMethods> {
686/// Optimize a newly codegened, totally unoptimized module.
687Optimize(ModuleCodegen<B::Module>),
688/// Copy the post-LTO artifacts from the incremental cache to the output
689 /// directory.
690CopyPostLtoArtifacts(CachedModuleCodegen),
691}
692693enum ThinLtoWorkItem<B: WriteBackendMethods> {
694/// Copy the post-LTO artifacts from the incremental cache to the output
695 /// directory.
696CopyPostLtoArtifacts(CachedModuleCodegen),
697/// Performs thin-LTO on the given module.
698ThinLto(lto::ThinModule<B>),
699}
700701// `pthread_setname()` on *nix ignores anything beyond the first 15
702// bytes. Use short descriptions to maximize the space available for
703// the module name.
704#[cfg(not(windows))]
705fn desc(short: &str, _long: &str, name: &str) -> String {
706// The short label is three bytes, and is followed by a space. That
707 // leaves 11 bytes for the CGU name. How we obtain those 11 bytes
708 // depends on the CGU name form.
709 //
710 // - Non-incremental, e.g. `regex.f10ba03eb5ec7975-cgu.0`: the part
711 // before the `-cgu.0` is the same for every CGU, so use the
712 // `cgu.0` part. The number suffix will be different for each
713 // CGU.
714 //
715 // - Incremental (normal), e.g. `2i52vvl2hco29us0`: use the whole
716 // name because each CGU will have a unique ASCII hash, and the
717 // first 11 bytes will be enough to identify it.
718 //
719 // - Incremental (with `-Zhuman-readable-cgu-names`), e.g.
720 // `regex.f10ba03eb5ec7975-re_builder.volatile`: use the whole
721 // name. The first 11 bytes won't be enough to uniquely identify
722 // it, but no obvious substring will, and this is a rarely used
723 // option so it doesn't matter much.
724 //
725{
match (&short.len(), &3) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(short.len(), 3);
726let name = if let Some(index) = name.find("-cgu.") {
727&name[index + 1..] // +1 skips the leading '-'.
728} else {
729name730 };
731::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}", short, name))
})format!("{short} {name}")732}
733734// Windows has no thread name length limit, so use more descriptive names.
735#[cfg(windows)]
736fn desc(_short: &str, long: &str, name: &str) -> String {
737format!("{long} {name}")
738}
739740impl<B: WriteBackendMethods> WorkItem<B> {
741/// Generate a short description of this work item suitable for use as a thread name.
742fn short_description(&self) -> String {
743match self {
744 WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
745 WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
746 }
747 }
748}
749750impl<B: WriteBackendMethods> ThinLtoWorkItem<B> {
751/// Generate a short description of this work item suitable for use as a thread name.
752fn short_description(&self) -> String {
753match self {
754 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
755desc("cpy", "copy LTO artifacts for", &m.name)
756 }
757 ThinLtoWorkItem::ThinLto(m) => desc("lto", "thin-LTO module", m.name()),
758 }
759 }
760}
761762/// A result produced by the backend.
763pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
764/// The backend has finished compiling a CGU, nothing more required.
765Finished(CompiledModule),
766767/// The backend has finished compiling a CGU, which now needs to go through
768 /// fat LTO.
769NeedsFatLto(FatLtoInput<B>),
770771/// The backend has finished compiling a CGU, which now needs to go through
772 /// thin LTO.
773NeedsThinLto(String, B::ModuleBuffer),
774}
775776pub enum FatLtoInput<B: WriteBackendMethods> {
777 Serialized { name: String, bitcode_path: PathBuf },
778 InMemory(ModuleCodegen<B::Module>),
779}
780781pub enum ThinLtoInput<B: WriteBackendMethods> {
782 Red { name: String, buffer: SerializedModule<B::ModuleBuffer> },
783 Green { wp: WorkProduct, bitcode_path: PathBuf },
784}
785786/// Actual LTO type we end up choosing based on multiple factors.
787pub(crate) enum ComputedLtoType {
788 No,
789 Thin,
790 Fat,
791}
792793pub(crate) fn compute_per_cgu_lto_type(
794 sess_lto: &Lto,
795 linker_does_lto: bool,
796 sess_crate_types: &[CrateType],
797) -> ComputedLtoType {
798// If the linker does LTO, we don't have to do it. Note that we
799 // keep doing full LTO, if it is requested, as not to break the
800 // assumption that the output will be a single module.
801802 // We ignore a request for full crate graph LTO if the crate type
803 // is only an rlib, as there is no full crate graph to process,
804 // that'll happen later.
805 //
806 // This use case currently comes up primarily for targets that
807 // require LTO so the request for LTO is always unconditionally
808 // passed down to the backend, but we don't actually want to do
809 // anything about it yet until we've got a final product.
810let is_rlib = #[allow(non_exhaustive_omitted_patterns)] match sess_crate_types {
[CrateType::Rlib] => true,
_ => false,
}matches!(sess_crate_types, [CrateType::Rlib]);
811812match sess_lto {
813 Lto::ThinLocalif !linker_does_lto => ComputedLtoType::Thin,
814 Lto::Thinif !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
815 Lto::Fatif !is_rlib => ComputedLtoType::Fat,
816_ => ComputedLtoType::No,
817 }
818}
819820fn execute_optimize_work_item<B: WriteBackendMethods>(
821 cgcx: &CodegenContext,
822 prof: &SelfProfilerRef,
823 shared_emitter: SharedEmitter,
824mut module: ModuleCodegen<B::Module>,
825) -> WorkItemResult<B> {
826let _timer = prof.generic_activity_with_arg("codegen_module_optimize", &*module.name);
827828 B::optimize(cgcx, prof, &shared_emitter, &mut module, &cgcx.module_config);
829830// After we've done the initial round of optimizations we need to
831 // decide whether to synchronously codegen this module or ship it
832 // back to the coordinator thread for further LTO processing (which
833 // has to wait for all the initial modules to be optimized).
834835let lto_type =
836compute_per_cgu_lto_type(&cgcx.lto, cgcx.use_linker_plugin_lto, &cgcx.crate_types);
837838// If we're doing some form of incremental LTO then we need to be sure to
839 // save our module to disk first.
840let bitcode = if cgcx.module_config.emit_pre_lto_bc {
841let filename = pre_lto_bitcode_filename(&module.name);
842cgcx.new_incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
843 } else {
844None845 };
846847match lto_type {
848 ComputedLtoType::No => {
849let module = B::codegen(cgcx, &prof, &shared_emitter, module, &cgcx.module_config);
850 WorkItemResult::Finished(module)
851 }
852 ComputedLtoType::Thin => {
853let thin_buffer = B::serialize_module(module.module_llvm, true);
854if let Some(path) = bitcode {
855 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
856{
::core::panicking::panic_fmt(format_args!("Error writing pre-lto-bitcode file `{0}`: {1}",
path.display(), e));
};panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
857 });
858 }
859 WorkItemResult::NeedsThinLto(module.name, thin_buffer)
860 }
861 ComputedLtoType::Fat => match bitcode {
862Some(path) => {
863let buffer = B::serialize_module(module.module_llvm, false);
864 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
865{
::core::panicking::panic_fmt(format_args!("Error writing pre-lto-bitcode file `{0}`: {1}",
path.display(), e));
};panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
866 });
867 WorkItemResult::NeedsFatLto(FatLtoInput::Serialized {
868 name: module.name,
869 bitcode_path: path,
870 })
871 }
872None => WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module)),
873 },
874 }
875}
876877fn execute_copy_from_cache_work_item(
878 cgcx: &CodegenContext,
879 prof: &SelfProfilerRef,
880 shared_emitter: SharedEmitter,
881 module: CachedModuleCodegen,
882) -> CompiledModule {
883let _timer =
884prof.generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &*module.name);
885886let dcx = DiagCtxt::new(Box::new(shared_emitter));
887let dcx = dcx.handle();
888889let incr_comp_session_dir = cgcx.old_incr_comp_session_dir.as_ref().unwrap();
890891let load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
892let source_file_in_incr_comp_dir = incr_comp_session_dir.join(saved_path);
893{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/back/write.rs:893",
"rustc_codegen_ssa::back::write", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/4ebd258257737d5b7635c116fa7d281627a7e937/compiler/rustc_codegen_ssa/src/back/write.rs"),
::tracing_core::__macro_support::Option::Some(893u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::write"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("copying preexisting module `{0}` from {1:?} to {2}",
module.name, source_file_in_incr_comp_dir,
output_path.display()) as &dyn ::tracing::field::Value))])
});
} else { ; }
};debug!(
894"copying preexisting module `{}` from {:?} to {}",
895 module.name,
896 source_file_in_incr_comp_dir,
897 output_path.display()
898 );
899match link_or_copy(&source_file_in_incr_comp_dir, &output_path) {
900Ok(_) => Some(output_path),
901Err(error) => {
902dcx.emit_err(diagnostics::CopyPathBuf {
903 source_file: source_file_in_incr_comp_dir,
904output_path,
905error,
906 });
907None908 }
909 }
910 };
911912let dwarf_object =
913module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
914let dwarf_obj_out = cgcx915 .output_filenames
916 .split_dwarf_path(cgcx.split_debuginfo, cgcx.split_dwarf_kind, &module.name)
917 .expect(
918"saved dwarf object in work product but `split_dwarf_path` returned `None`",
919 );
920load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
921 });
922923let load_from_incr_cache = |perform, output_type: OutputType| {
924if perform {
925let saved_file = module.source.saved_files.get(output_type.extension())?;
926let output_path = cgcx.output_filenames.temp_path_for_cgu(output_type, &module.name);
927load_from_incr_comp_dir(output_path, &saved_file)
928 } else {
929None930 }
931 };
932933let module_config = &cgcx.module_config;
934let should_emit_obj = module_config.emit_obj != EmitObj::None;
935let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
936let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
937let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
938let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
939let global_asm_object =
940if should_emit_obj && let Some(saved_file) = module.source.saved_files.get("asm.o") {
941let output_path = cgcx.output_filenames.temp_path_ext_for_cgu("asm.o", &module.name);
942load_from_incr_comp_dir(output_path, &saved_file)
943 } else {
944None945 };
946if should_emit_obj && object.is_none() {
947dcx.emit_fatal(diagnostics::NoSavedObjectFile { cgu_name: &module.name })
948 }
949950CompiledModule {
951 kind: ModuleKind::Regular,
952 name: module.name,
953object,
954global_asm_object,
955dwarf_object,
956bytecode,
957assembly,
958llvm_ir,
959 }
960}
961962fn do_fat_lto<B: WriteBackendMethods>(
963 sess: &Session,
964 cgcx: &CodegenContext,
965 shared_emitter: SharedEmitter,
966 tm_factory: TargetMachineFactoryFn<B>,
967 exported_symbols_for_lto: &[String],
968 each_linked_rlib_for_lto: &[PathBuf],
969 needs_fat_lto: Vec<FatLtoInput<B>>,
970) -> CompiledModule {
971let _timer = sess.prof.verbose_generic_activity("LLVM_fatlto");
972973let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
974let dcx = dcx.handle();
975976check_lto_allowed(&cgcx, dcx);
977978 B::optimize_and_codegen_fat_lto(
979sess,
980cgcx,
981&shared_emitter,
982tm_factory,
983exported_symbols_for_lto,
984each_linked_rlib_for_lto,
985needs_fat_lto,
986 )
987}
988989fn do_thin_lto<B: WriteBackendMethods>(
990 cgcx: &CodegenContext,
991 prof: &SelfProfilerRef,
992 shared_emitter: SharedEmitter,
993 tm_factory: TargetMachineFactoryFn<B>,
994 exported_symbols_for_lto: &[String],
995 each_linked_rlib_for_lto: &[PathBuf],
996 needs_thin_lto: Vec<ThinLtoInput<B>>,
997 stack_size: usize,
998) -> Vec<CompiledModule> {
999let _timer = prof.verbose_generic_activity("LLVM_thinlto");
10001001let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
1002let dcx = dcx.handle();
10031004check_lto_allowed(&cgcx, dcx);
10051006let (coordinator_send, coordinator_receive) = channel();
10071008// First up, convert our jobserver into a helper thread so we can use normal
1009 // mpsc channels to manage our messages and such.
1010 // After we've requested tokens then we'll, when we can,
1011 // get tokens on `coordinator_receive` which will
1012 // get managed in the main loop below.
1013 // Note that using `jobserver::Proxy` is not necessary here, the code below always acquires
1014 // tokens before releasing them, so we can never accidentally release the last token
1015 // permanently held by rustc process.
1016let jobserver_helper = cgcx.parallel.map(|_| {
1017let coordinator_send2 = coordinator_send.clone();
1018 jobserver::client()
1019 .into_helper_thread(move |token| {
1020drop(coordinator_send2.send(ThinLtoMessage::Token(token)));
1021 })
1022 .expect("failed to spawn helper thread")
1023 });
10241025let mut work_items = ::alloc::vec::Vec::new()vec![];
10261027// We have LTO work to do. Perform the serial work here of
1028 // figuring out what we're going to LTO and then push a
1029 // bunch of work items onto our queue to do LTO. This all
1030 // happens on the coordinator thread but it's very quick so
1031 // we don't worry about tokens.
1032for (i, (work, cost)) in generate_thin_lto_work::<B>(
1033 cgcx,
1034 prof,
1035 dcx,
1036&exported_symbols_for_lto,
1037&each_linked_rlib_for_lto,
1038 needs_thin_lto,
1039 )
1040 .into_iter()
1041 .enumerate()
1042 {
1043let insertion_index =
1044 work_items.binary_search_by_key(&cost, |&(_, cost)| cost).unwrap_or_else(|e| e);
1045 work_items.insert(insertion_index, (work, cost));
1046if let Some(helper) = &jobserver_helper
1047 && i < cgcx.parallel.unwrap().get()
1048 {
1049 helper.request_token();
1050 }
1051 }
10521053let mut codegen_aborted = None;
10541055// These are the Jobserver Tokens we currently hold. Does not include
1056 // the implicit Token the compiler process owns no matter what.
1057let mut tokens = ::alloc::vec::Vec::new()vec![];
10581059// Amount of tokens that are used (including the implicit token).
1060let mut used_token_count = 0;
10611062let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
10631064// Run the message loop while there's still anything that needs message
1065 // processing. Note that as soon as codegen is aborted we simply want to
1066 // wait for all existing work to finish, so many of the conditions here
1067 // only apply if codegen hasn't been aborted as they represent pending
1068 // work to be done.
1069loop {
1070if codegen_aborted.is_none() {
1071if used_token_count == 0 && work_items.is_empty() {
1072// All codegen work is done.
1073break;
1074 }
10751076// Spin up what work we can, only doing this while we've got available
1077 // parallelism slots and work left to spawn.
1078while used_token_count < tokens.len() + 1
1079&& let Some((item, _)) = work_items.pop()
1080 {
1081 spawn_thin_lto_work(
1082&cgcx,
1083 prof,
1084 shared_emitter.clone(),
1085 Arc::clone(&tm_factory),
1086 coordinator_send.clone(),
1087 item,
1088 stack_size,
1089 );
1090 used_token_count += 1;
1091 }
1092 } else {
1093// Don't queue up any more work if codegen was aborted, we're
1094 // just waiting for our existing children to finish.
1095if used_token_count == 0 {
1096break;
1097 }
1098 }
10991100// Relinquish accidentally acquired extra tokens. Subtract 1 for the implicit token.
1101tokens.truncate(used_token_count.saturating_sub(1));
11021103match coordinator_receive.recv().unwrap() {
1104// Save the token locally and the next turn of the loop will use
1105 // this to spawn a new unit of work, or it may get dropped
1106 // immediately if we have no more work to spawn.
1107ThinLtoMessage::Token(token) => match token {
1108Ok(token) => {
1109tokens.push(token);
1110 }
1111Err(e) => {
1112let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1113shared_emitter.fatal(msg);
1114codegen_aborted = Some(FatalError);
1115 }
1116 },
11171118 ThinLtoMessage::WorkItem { result } => {
1119// If a thread exits successfully then we drop a token associated
1120 // with that worker and update our `used_token_count` count.
1121 // We may later re-acquire a token to continue running more work.
1122 // We may also not actually drop a token here if the worker was
1123 // running with an "ephemeral token".
1124used_token_count -= 1;
11251126match result {
1127Ok(compiled_module) => compiled_modules.push(compiled_module),
1128Err(Some(WorkerFatalError)) => {
1129// Like `CodegenAborted`, wait for remaining work to finish.
1130codegen_aborted = Some(FatalError);
1131 }
1132Err(None) => {
1133// If the thread failed that means it panicked, so
1134 // we abort immediately.
1135::rustc_span::macros::bug_impl(None, format_args!("worker thread panicked"),
Location::caller());bug!("worker thread panicked");
1136 }
1137 }
1138 }
1139 }
1140 }
11411142if let Some(codegen_aborted) = codegen_aborted {
1143codegen_aborted.raise();
1144 }
11451146compiled_modules1147}
11481149/// Messages sent to the coordinator.
1150pub(crate) enum Message<B: WriteBackendMethods> {
1151/// A jobserver token has become available. Sent from the jobserver helper
1152 /// thread.
1153Token(io::Result<Acquired>),
11541155/// The backend has finished processing a work item for a codegen unit.
1156 /// Sent from a backend worker thread.
1157WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>> },
11581159/// The frontend has finished generating something (backend IR or a
1160 /// post-LTO artifact) for a codegen unit, and it should be passed to the
1161 /// backend. Sent from the main thread.
1162CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
11631164/// Similar to `CodegenDone`, but for reusing a pre-LTO artifact
1165 /// Sent from the main thread.
1166AddImportOnlyModule { bitcode_path: PathBuf, work_product: WorkProduct },
11671168/// The frontend has finished generating everything for all codegen units.
1169 /// Sent from the main thread.
1170CodegenComplete,
11711172/// Some normal-ish compiler error occurred, and codegen should be wound
1173 /// down. Sent from the main thread.
1174CodegenAborted,
1175}
11761177/// Messages sent to the coordinator.
1178pub(crate) enum ThinLtoMessage {
1179/// A jobserver token has become available. Sent from the jobserver helper
1180 /// thread.
1181Token(io::Result<Acquired>),
11821183/// The backend has finished processing a work item for a codegen unit.
1184 /// Sent from a backend worker thread.
1185WorkItem { result: Result<CompiledModule, Option<WorkerFatalError>> },
1186}
11871188/// A message sent from the coordinator thread to the main thread telling it to
1189/// process another codegen unit.
1190pub struct CguMessage;
11911192#[derive(#[automatically_derived]
impl ::core::marker::StructuralPartialEq for MainThreadState { }
#[automatically_derived]
impl ::core::cmp::PartialEq for MainThreadState {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for MainThreadState { }
#[automatically_derived]
impl ::core::clone::Clone for MainThreadState {
#[inline]
fn clone(&self) -> Self { *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)]
1193enum MainThreadState {
1194/// Doing nothing.
1195Idle,
11961197/// Doing codegen, i.e. MIR-to-LLVM-IR conversion.
1198Codegenning,
11991200/// Idle, but lending the compiler process's Token to an LLVM thread so it can do useful work.
1201Lending,
1202}
12031204fn start_executing_work<B: WriteBackendMethods>(
1205 backend: B,
1206 tcx: TyCtxt<'_>,
1207 shared_emitter: SharedEmitter,
1208 codegen_worker_send: Sender<CguMessage>,
1209 coordinator_receive: Receiver<Message<B>>,
1210 regular_config: Arc<ModuleConfig>,
1211 allocator_config: Arc<ModuleConfig>,
1212mut allocator_module: Option<ModuleCodegen<B::Module>>,
1213 coordinator_send: Sender<Message<B>>,
1214) -> thread::JoinHandle<Result<MaybeLtoModules<B>, ()>> {
1215let sess = tcx.sess;
1216let prof = sess.prof.clone();
12171218// Compute the set of symbols we need to retain when doing thin local LTO (if we need to)
1219let exported_symbols_for_lto =
1220if sess.lto() == Lto::ThinLocal { lto::exported_symbols_for_lto(tcx, &[]) } else { ::alloc::vec::Vec::new()vec![] };
12211222// First up, convert our jobserver into a helper thread so we can use normal
1223 // mpsc channels to manage our messages and such.
1224 // After we've requested tokens then we'll, when we can,
1225 // get tokens on `coordinator_receive` which will
1226 // get managed in the main loop below.
1227 // Note that using `jobserver::Proxy` is not necessary here, the code below always acquires
1228 // tokens before releasing them, so we can never accidentally release the last token
1229 // permanently held by rustc process.
1230let parallel = match sess.opts.jobs.backend {
1231Some(n) if backend.supports_parallel() => Some(n),
1232_ => None,
1233 };
1234let jobserver_helper = parallel.map(|_| {
1235let coordinator_send2 = coordinator_send.clone();
1236 jobserver::client()
1237 .into_helper_thread(move |token| {
1238drop(coordinator_send2.send(Message::Token::<B>(token)));
1239 })
1240 .expect("failed to spawn helper thread")
1241 });
12421243let opt_level = tcx.backend_optimization_level(());
1244let tm_factory = backend.target_machine_factory(tcx.sess, opt_level);
12451246let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1247let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1248match result {
1249Ok(dir) => Some(dir),
1250Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1251 }
1252 } else {
1253None1254 };
12551256let stack_size = sess.opts.recommended_stack_size;
12571258let cgcx = CodegenContext {
1259 crate_types: tcx.crate_types().to_vec(),
1260 lto: sess.lto(),
1261 use_linker_plugin_lto: sess.opts.cg.linker_plugin_lto.enabled(),
1262 dylib_lto: sess.opts.unstable_opts.dylib_lto,
1263 prefer_dynamic: sess.opts.cg.prefer_dynamic,
1264 fewer_names: sess.fewer_names(),
1265 save_temps: sess.opts.cg.save_temps,
1266 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1267 remark: sess.opts.cg.remark.clone(),
1268remark_dir,
1269 old_incr_comp_session_dir: tcx1270 .incr_comp_session
1271 .as_ref()
1272 .and_then(|incr_comp_session| incr_comp_session.old_session_directory.as_deref())
1273 .map(ToOwned::to_owned),
1274 new_incr_comp_session_dir: tcx1275 .incr_comp_session
1276 .as_ref()
1277 .map(|incr_comp_session| (&*incr_comp_session.new_session_directory).to_owned()),
1278 output_filenames: Arc::clone(tcx.output_filenames(())),
1279 module_config: regular_config,
1280opt_level,
1281 msvc_imps_needed: msvc_imps_needed(tcx),
1282 is_pe_coff: tcx.sess.target.is_like_windows,
1283 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1284 target_arch: tcx.sess.target.arch.to_string(),
1285 target_is_like_darwin: tcx.sess.target.is_like_darwin,
1286 target_is_like_aix: tcx.sess.target.is_like_aix,
1287 target_is_like_gpu: tcx.sess.target.is_like_gpu,
1288 rust_eh_personality_symbol: rustc_symbol_mangling::eh_personality_symbol(tcx),
1289 split_debuginfo: tcx.sess.split_debuginfo(),
1290 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1291parallel,
1292 pointer_size: tcx.data_layout.pointer_size(),
1293 };
12941295// This is the "main loop" of parallel work happening for parallel codegen.
1296 // It's here that we manage parallelism, schedule work, and work with
1297 // messages coming from clients.
1298 //
1299 // There are a few environmental pre-conditions that shape how the system
1300 // is set up:
1301 //
1302 // - Error reporting can only happen on the main thread because that's the
1303 // only place where we have access to the compiler `Session`.
1304 // - LLVM work can be done on any thread.
1305 // - Codegen can only happen on the main thread.
1306 // - Each thread doing substantial work must be in possession of a `Token`
1307 // from the `Jobserver`.
1308 // - The compiler process always holds one `Token`. Any additional `Tokens`
1309 // have to be requested from the `Jobserver`.
1310 //
1311 // Error Reporting
1312 // ===============
1313 // The error reporting restriction is handled separately from the rest: We
1314 // set up a `SharedEmitter` that holds an open channel to the main thread.
1315 // When an error occurs on any thread, the shared emitter will send the
1316 // error message to the receiver main thread (`SharedEmitterMain`). The
1317 // main thread will periodically query this error message queue and emit
1318 // any error messages it has received. It might even abort compilation if
1319 // it has received a fatal error. In this case we rely on all other threads
1320 // being torn down automatically with the main thread.
1321 // Since the main thread will often be busy doing codegen work, error
1322 // reporting will be somewhat delayed, since the message queue can only be
1323 // checked in between two work packages.
1324 //
1325 // Work Processing Infrastructure
1326 // ==============================
1327 // The work processing infrastructure knows three major actors:
1328 //
1329 // - the coordinator thread,
1330 // - the main thread, and
1331 // - LLVM worker threads
1332 //
1333 // The coordinator thread is running a message loop. It instructs the main
1334 // thread about what work to do when, and it will spawn off LLVM worker
1335 // threads as open LLVM WorkItems become available.
1336 //
1337 // The job of the main thread is to codegen CGUs into LLVM work packages
1338 // (since the main thread is the only thread that can do this). The main
1339 // thread will block until it receives a message from the coordinator, upon
1340 // which it will codegen one CGU, send it to the coordinator and block
1341 // again. This way the coordinator can control what the main thread is
1342 // doing.
1343 //
1344 // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1345 // available, it will spawn off a new LLVM worker thread and let it process
1346 // a WorkItem. When a LLVM worker thread is done with its WorkItem,
1347 // it will just shut down, which also frees all resources associated with
1348 // the given LLVM module, and sends a message to the coordinator that the
1349 // WorkItem has been completed.
1350 //
1351 // Work Scheduling
1352 // ===============
1353 // The scheduler's goal is to minimize the time it takes to complete all
1354 // work there is, however, we also want to keep memory consumption low
1355 // if possible. These two goals are at odds with each other: If memory
1356 // consumption were not an issue, we could just let the main thread produce
1357 // LLVM WorkItems at full speed, assuring maximal utilization of
1358 // Tokens/LLVM worker threads. However, since codegen is usually faster
1359 // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1360 // WorkItem potentially holds on to a substantial amount of memory.
1361 //
1362 // So the actual goal is to always produce just enough LLVM WorkItems as
1363 // not to starve our LLVM worker threads. That means, once we have enough
1364 // WorkItems in our queue, we can block the main thread, so it does not
1365 // produce more until we need them.
1366 //
1367 // Doing LLVM Work on the Main Thread
1368 // ----------------------------------
1369 // Since the main thread owns the compiler process's implicit `Token`, it is
1370 // wasteful to keep it blocked without doing any work. Therefore, what we do
1371 // in this case is: We spawn off an additional LLVM worker thread that helps
1372 // reduce the queue. The work it is doing corresponds to the implicit
1373 // `Token`. The coordinator will mark the main thread as being busy with
1374 // LLVM work. (The actual work happens on another OS thread but we just care
1375 // about `Tokens`, not actual threads).
1376 //
1377 // When any LLVM worker thread finishes while the main thread is marked as
1378 // "busy with LLVM work", we can do a little switcheroo: We give the Token
1379 // of the just finished thread to the LLVM worker thread that is working on
1380 // behalf of the main thread's implicit Token, thus freeing up the main
1381 // thread again. The coordinator can then again decide what the main thread
1382 // should do. This allows the coordinator to make decisions at more points
1383 // in time.
1384 //
1385 // Striking a Balance between Throughput and Memory Consumption
1386 // ------------------------------------------------------------
1387 // Since our two goals, (1) use as many Tokens as possible and (2) keep
1388 // memory consumption as low as possible, are in conflict with each other,
1389 // we have to find a trade off between them. Right now, the goal is to keep
1390 // all workers busy, which means that no worker should find the queue empty
1391 // when it is ready to start.
1392 // How do we do achieve this? Good question :) We actually never know how
1393 // many `Tokens` are potentially available so it's hard to say how much to
1394 // fill up the queue before switching the main thread to LLVM work. Also we
1395 // currently don't have a means to estimate how long a running LLVM worker
1396 // will still be busy with it's current WorkItem. However, we know the
1397 // maximal count of available Tokens that makes sense (=the number of CPU
1398 // cores), so we can take a conservative guess. The heuristic we use here
1399 // is implemented in the `queue_full_enough()` function.
1400 //
1401 // Some Background on Jobservers
1402 // -----------------------------
1403 // It's worth also touching on the management of parallelism here. We don't
1404 // want to just spawn a thread per work item because while that's optimal
1405 // parallelism it may overload a system with too many threads or violate our
1406 // configuration for the maximum amount of cpu to use for this process. To
1407 // manage this we use the `jobserver` crate.
1408 //
1409 // Job servers are an artifact of GNU make and are used to manage
1410 // parallelism between processes. A jobserver is a glorified IPC semaphore
1411 // basically. Whenever we want to run some work we acquire the semaphore,
1412 // and whenever we're done with that work we release the semaphore. In this
1413 // manner we can ensure that the maximum number of parallel workers is
1414 // capped at any one point in time.
1415 //
1416 // LTO and the coordinator thread
1417 // ------------------------------
1418 //
1419 // The final job the coordinator thread is responsible for is managing LTO
1420 // and how that works. When LTO is requested what we'll do is collect all
1421 // optimized LLVM modules into a local vector on the coordinator. Once all
1422 // modules have been codegened and optimized we hand this to the `lto`
1423 // module for further optimization. The `lto` module will return back a list
1424 // of more modules to work on, which the coordinator will continue to spawn
1425 // work for.
1426 //
1427 // Each LLVM module is automatically sent back to the coordinator for LTO if
1428 // necessary. There's already optimizations in place to avoid sending work
1429 // back to the coordinator if LTO isn't requested.
1430let f = move || {
1431let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
14321433// This is where we collect codegen units that have gone all the way
1434 // through codegen and LLVM.
1435let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
1436let mut needs_fat_lto = Vec::new();
1437let mut needs_thin_lto = Vec::new();
1438let mut lto_import_only_modules = Vec::new();
14391440/// Possible state transitions:
1441 /// - Ongoing -> Completed
1442 /// - Ongoing -> Aborted
1443 /// - Completed -> Aborted
1444#[derive(#[automatically_derived]
impl ::core::fmt::Debug for CodegenState {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
CodegenState::Ongoing => "Ongoing",
CodegenState::Completed => "Completed",
CodegenState::Aborted => "Aborted",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for CodegenState { }
#[automatically_derived]
impl ::core::cmp::PartialEq for CodegenState {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
1445enum CodegenState {
1446 Ongoing,
1447 Completed,
1448 Aborted,
1449 }
1450use CodegenState::*;
1451let mut codegen_state = Ongoing;
14521453// This is the queue of LLVM work items that still need processing.
1454let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
14551456// This are the Jobserver Tokens we currently hold. Does not include
1457 // the implicit Token the compiler process owns no matter what.
1458let mut tokens = Vec::new();
14591460let mut main_thread_state = MainThreadState::Idle;
14611462// How many LLVM worker threads are running while holding a Token. This
1463 // *excludes* any that the main thread is lending a Token to.
1464let mut running_with_own_token = 0;
14651466// How many LLVM worker threads are running in total. This *includes*
1467 // any that the main thread is lending a Token to.
1468let running_with_any_token = |main_thread_state, running_with_own_token| {
1469running_with_own_token1470 + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1471 };
14721473let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
14741475if let Some(allocator_module) = &mut allocator_module {
1476 B::optimize(&cgcx, &prof, &shared_emitter, allocator_module, &allocator_config);
1477 }
14781479// Run the message loop while there's still anything that needs message
1480 // processing. Note that as soon as codegen is aborted we simply want to
1481 // wait for all existing work to finish, so many of the conditions here
1482 // only apply if codegen hasn't been aborted as they represent pending
1483 // work to be done.
1484loop {
1485// While there are still CGUs to be codegened, the coordinator has
1486 // to decide how to utilize the compiler processes implicit Token:
1487 // For codegenning more CGU or for running them through LLVM.
1488if codegen_state == Ongoing {
1489if main_thread_state == MainThreadState::Idle {
1490// Compute the number of workers that will be running once we've taken as many
1491 // items from the work queue as we can, plus one for the main thread. It's not
1492 // critically important that we use this instead of just
1493 // `running_with_own_token`, but it prevents the `queue_full_enough` heuristic
1494 // from fluctuating just because a worker finished up and we decreased the
1495 // `running_with_own_token` count, even though we're just going to increase it
1496 // right after this when we put a new worker to work.
1497let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1498let additional_running = std::cmp::min(extra_tokens, work_items.len());
1499let anticipated_running = running_with_own_token + additional_running + 1;
15001501if !queue_full_enough(work_items.len(), anticipated_running) {
1502// The queue is not full enough, process more codegen units:
1503if codegen_worker_send.send(CguMessage).is_err() {
1504{
::core::panicking::panic_fmt(format_args!("Could not send CguMessage to main thread"));
}panic!("Could not send CguMessage to main thread")1505 }
1506main_thread_state = MainThreadState::Codegenning;
1507 } else {
1508// The queue is full enough to not let the worker
1509 // threads starve. Use the implicit Token to do some
1510 // LLVM work too.
1511let (item, _) =
1512work_items.pop().expect("queue empty - queue_full_enough() broken?");
1513main_thread_state = MainThreadState::Lending;
1514spawn_work(
1515&cgcx,
1516&prof,
1517shared_emitter.clone(),
1518coordinator_send.clone(),
1519&mut llvm_start_time,
1520item,
1521stack_size,
1522 );
1523 }
1524 }
1525 } else if codegen_state == Completed {
1526if running_with_any_token(main_thread_state, running_with_own_token) == 0
1527&& work_items.is_empty()
1528 {
1529// All codegen work is done.
1530break;
1531 }
15321533// In this branch, we know that everything has been codegened,
1534 // so it's just a matter of determining whether the implicit
1535 // Token is free to use for LLVM work.
1536match main_thread_state {
1537 MainThreadState::Idle => {
1538if let Some((item, _)) = work_items.pop() {
1539main_thread_state = MainThreadState::Lending;
1540spawn_work(
1541&cgcx,
1542&prof,
1543shared_emitter.clone(),
1544coordinator_send.clone(),
1545&mut llvm_start_time,
1546item,
1547stack_size,
1548 );
1549 } else {
1550// There is no unstarted work, so let the main thread
1551 // take over for a running worker. Otherwise the
1552 // implicit token would just go to waste.
1553 // We reduce the `running` counter by one. The
1554 // `tokens.truncate()` below will take care of
1555 // giving the Token back.
1556if !(running_with_own_token > 0) {
::core::panicking::panic("assertion failed: running_with_own_token > 0")
};assert!(running_with_own_token > 0);
1557running_with_own_token -= 1;
1558main_thread_state = MainThreadState::Lending;
1559 }
1560 }
1561 MainThreadState::Codegenning => ::rustc_span::macros::bug_impl(None,
format_args!("codegen worker should not be codegenning after codegen was already completed"),
Location::caller())bug!(
1562"codegen worker should not be codegenning after \
1563 codegen was already completed"
1564),
1565 MainThreadState::Lending => {
1566// Already making good use of that token
1567}
1568 }
1569 } else {
1570// Don't queue up any more work if codegen was aborted, we're
1571 // just waiting for our existing children to finish.
1572if !(codegen_state == Aborted) {
::core::panicking::panic("assertion failed: codegen_state == Aborted")
};assert!(codegen_state == Aborted);
1573if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1574break;
1575 }
1576 }
15771578// Spin up what work we can, only doing this while we've got available
1579 // parallelism slots and work left to spawn.
1580if codegen_state != Aborted {
1581while running_with_own_token < tokens.len()
1582 && let Some((item, _)) = work_items.pop()
1583 {
1584 spawn_work(
1585&cgcx,
1586&prof,
1587 shared_emitter.clone(),
1588 coordinator_send.clone(),
1589&mut llvm_start_time,
1590 item,
1591 stack_size,
1592 );
1593 running_with_own_token += 1;
1594 }
1595 }
15961597// Relinquish accidentally acquired extra tokens.
1598tokens.truncate(running_with_own_token);
15991600match coordinator_receive.recv().unwrap() {
1601// Save the token locally and the next turn of the loop will use
1602 // this to spawn a new unit of work, or it may get dropped
1603 // immediately if we have no more work to spawn.
1604Message::Token(token) => {
1605match token {
1606Ok(token) => {
1607tokens.push(token);
16081609if main_thread_state == MainThreadState::Lending {
1610// If the main thread token is used for LLVM work
1611 // at the moment, we turn that thread into a regular
1612 // LLVM worker thread, so the main thread is free
1613 // to react to codegen demand.
1614main_thread_state = MainThreadState::Idle;
1615running_with_own_token += 1;
1616 }
1617 }
1618Err(e) => {
1619let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1620shared_emitter.fatal(msg);
1621codegen_state = Aborted;
1622 }
1623 }
1624 }
16251626 Message::CodegenDone { llvm_work_item, cost } => {
1627// We keep the queue sorted by estimated processing cost,
1628 // so that more expensive items are processed earlier. This
1629 // is good for throughput as it gives the main thread more
1630 // time to fill up the queue and it avoids scheduling
1631 // expensive items to the end.
1632 // Note, however, that this is not ideal for memory
1633 // consumption, as LLVM module sizes are not evenly
1634 // distributed.
1635let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1636let insertion_index = match insertion_index {
1637Ok(idx) | Err(idx) => idx,
1638 };
1639work_items.insert(insertion_index, (llvm_work_item, cost));
16401641if let Some(helper) = &jobserver_helper1642 && running_with_any_token(main_thread_state, running_with_own_token)
1643 < cgcx.parallel.unwrap().get()
1644 {
1645helper.request_token();
1646 }
1647{
match (&main_thread_state, &MainThreadState::Codegenning) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(main_thread_state, MainThreadState::Codegenning);
1648main_thread_state = MainThreadState::Idle;
1649 }
16501651 Message::CodegenComplete => {
1652if codegen_state != Aborted {
1653codegen_state = Completed;
1654 }
1655{
match (&main_thread_state, &MainThreadState::Codegenning) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(main_thread_state, MainThreadState::Codegenning);
1656main_thread_state = MainThreadState::Idle;
1657 }
16581659// If codegen is aborted that means translation was aborted due
1660 // to some normal-ish compiler error. In this situation we want
1661 // to exit as soon as possible, but we want to make sure all
1662 // existing work has finished. Flag codegen as being done, and
1663 // then conditions above will ensure no more work is spawned but
1664 // we'll keep executing this loop until `running_with_own_token`
1665 // hits 0.
1666Message::CodegenAborted => {
1667codegen_state = Aborted;
1668 }
16691670 Message::WorkItem { result } => {
1671// If a thread exits successfully then we drop a token associated
1672 // with that worker and update our `running_with_own_token` count.
1673 // We may later re-acquire a token to continue running more work.
1674 // We may also not actually drop a token here if the worker was
1675 // running with an "ephemeral token".
1676if main_thread_state == MainThreadState::Lending {
1677main_thread_state = MainThreadState::Idle;
1678 } else {
1679running_with_own_token -= 1;
1680 }
16811682match result {
1683Ok(WorkItemResult::Finished(compiled_module)) => {
1684compiled_modules.push(compiled_module);
1685 }
1686Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1687if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
1688needs_fat_lto.push(fat_lto_input);
1689 }
1690Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1691if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
1692needs_thin_lto.push(ThinLtoInput::Red {
1693name,
1694 buffer: SerializedModule::Local(thin_buffer),
1695 });
1696 }
1697Err(Some(WorkerFatalError)) => {
1698// Like `CodegenAborted`, wait for remaining work to finish.
1699codegen_state = Aborted;
1700 }
1701Err(None) => {
1702// If the thread failed that means it panicked, so
1703 // we abort immediately.
1704::rustc_span::macros::bug_impl(None, format_args!("worker thread panicked"),
Location::caller());bug!("worker thread panicked");
1705 }
1706 }
1707 }
17081709 Message::AddImportOnlyModule { bitcode_path, work_product } => {
1710{
match (&codegen_state, &Ongoing) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(codegen_state, Ongoing);
1711{
match (&main_thread_state, &MainThreadState::Codegenning) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};assert_eq!(main_thread_state, MainThreadState::Codegenning);
1712lto_import_only_modules.push((bitcode_path, work_product));
1713main_thread_state = MainThreadState::Idle;
1714 }
1715 }
1716 }
17171718// Drop to print timings
1719drop(llvm_start_time);
17201721if codegen_state == Aborted {
1722return Err(());
1723 }
17241725drop(codegen_state);
1726drop(tokens);
1727drop(jobserver_helper);
1728if !work_items.is_empty() {
::core::panicking::panic("assertion failed: work_items.is_empty()")
};assert!(work_items.is_empty());
17291730if !needs_fat_lto.is_empty() {
1731if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1732if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
17331734if let Some(allocator_module) = allocator_module.take() {
1735needs_fat_lto.push(FatLtoInput::InMemory(allocator_module));
1736 }
17371738for (bitcode_path, wp) in lto_import_only_modules {
1739 needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, bitcode_path })
1740 }
17411742return Ok(MaybeLtoModules::FatLto { cgcx, needs_fat_lto });
1743 } else if !needs_thin_lto.is_empty() || !lto_import_only_modules.is_empty() {
1744if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1745if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
17461747for (bitcode_path, wp) in lto_import_only_modules {
1748 needs_thin_lto.push(ThinLtoInput::Green { wp, bitcode_path })
1749 }
17501751if cgcx.lto == Lto::ThinLocal {
1752compiled_modules.extend(do_thin_lto::<B>(
1753&cgcx,
1754&prof,
1755shared_emitter.clone(),
1756tm_factory,
1757&exported_symbols_for_lto,
1758&[],
1759needs_thin_lto,
1760stack_size,
1761 ));
1762 } else {
1763if let Some(allocator_module) = allocator_module.take() {
1764let thin_buffer = B::serialize_module(allocator_module.module_llvm, true);
1765needs_thin_lto.push(ThinLtoInput::Red {
1766 name: allocator_module.name,
1767 buffer: SerializedModule::Local(thin_buffer),
1768 });
1769 }
17701771return Ok(MaybeLtoModules::ThinLto { cgcx, needs_thin_lto });
1772 }
1773 }
17741775Ok(MaybeLtoModules::NoLto(CompiledModules {
1776 modules: compiled_modules,
1777 allocator_module: allocator_module.map(|allocator_module| {
1778 B::codegen(&cgcx, &prof, &shared_emitter, allocator_module, &allocator_config)
1779 }),
1780 }))
1781 };
1782return std::thread::Builder::new()
1783 .name("coordinator".to_owned())
1784 .spawn(f)
1785 .expect("failed to spawn coordinator thread");
17861787// A heuristic that determines if we have enough LLVM WorkItems in the
1788 // queue so that the main thread can do LLVM work instead of codegen
1789fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1790// This heuristic scales ahead-of-time codegen according to available
1791 // concurrency, as measured by `workers_running`. The idea is that the
1792 // more concurrency we have available, the more demand there will be for
1793 // work items, and the fuller the queue should be kept to meet demand.
1794 // An important property of this approach is that we codegen ahead of
1795 // time only as much as necessary, so as to keep fewer LLVM modules in
1796 // memory at once, thereby reducing memory consumption.
1797 //
1798 // When the number of workers running is less than the max concurrency
1799 // available to us, this heuristic can cause us to instruct the main
1800 // thread to work on an LLVM item (that is, tell it to "LLVM") instead
1801 // of codegen, even though it seems like it *should* be codegenning so
1802 // that we can create more work items and spawn more LLVM workers.
1803 //
1804 // But this is not a problem. When the main thread is told to LLVM,
1805 // according to this heuristic and how work is scheduled, there is
1806 // always at least one item in the queue, and therefore at least one
1807 // pending jobserver token request. If there *is* more concurrency
1808 // available, we will immediately receive a token, which will upgrade
1809 // the main thread's LLVM worker to a real one (conceptually), and free
1810 // up the main thread to codegen if necessary. On the other hand, if
1811 // there isn't more concurrency, then the main thread working on an LLVM
1812 // item is appropriate, as long as the queue is full enough for demand.
1813 //
1814 // Speaking of which, how full should we keep the queue? Probably less
1815 // full than you'd think. A lot has to go wrong for the queue not to be
1816 // full enough and for that to have a negative effect on compile times.
1817 //
1818 // Workers are unlikely to finish at exactly the same time, so when one
1819 // finishes and takes another work item off the queue, we often have
1820 // ample time to codegen at that point before the next worker finishes.
1821 // But suppose that codegen takes so long that the workers exhaust the
1822 // queue, and we have one or more workers that have nothing to work on.
1823 // Well, it might not be so bad. Of all the LLVM modules we create and
1824 // optimize, one has to finish last. It's not necessarily the case that
1825 // by losing some concurrency for a moment, we delay the point at which
1826 // that last LLVM module is finished and the rest of compilation can
1827 // proceed. Also, when we can't take advantage of some concurrency, we
1828 // give tokens back to the job server. That enables some other rustc to
1829 // potentially make use of the available concurrency. That could even
1830 // *decrease* overall compile time if we're lucky. But yes, if no other
1831 // rustc can make use of the concurrency, then we've squandered it.
1832 //
1833 // However, keeping the queue full is also beneficial when we have a
1834 // surge in available concurrency. Then items can be taken from the
1835 // queue immediately, without having to wait for codegen.
1836 //
1837 // So, the heuristic below tries to keep one item in the queue for every
1838 // four running workers. Based on limited benchmarking, this appears to
1839 // be more than sufficient to avoid increasing compilation times.
1840let quarter_of_workers = workers_running - 3 * workers_running / 4;
1841items_in_queue > 0 && items_in_queue >= quarter_of_workers1842 }
1843}
18441845/// `FatalError` is explicitly not `Send`.
1846#[must_use]
1847pub(crate) struct WorkerFatalError;
18481849fn spawn_work<'a, B: WriteBackendMethods>(
1850 cgcx: &CodegenContext,
1851 prof: &'a SelfProfilerRef,
1852 shared_emitter: SharedEmitter,
1853 coordinator_send: Sender<Message<B>>,
1854 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1855 work: WorkItem<B>,
1856 stack_size: usize,
1857) {
1858if llvm_start_time.is_none() {
1859*llvm_start_time = Some(prof.verbose_generic_activity("LLVM_passes"));
1860 }
18611862let cgcx = cgcx.clone();
1863let prof = prof.clone();
18641865let name = work.short_description();
1866let f = move || {
1867let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
18681869let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1870 WorkItem::Optimize(m) => execute_optimize_work_item(&cgcx, &prof, shared_emitter, m),
1871 WorkItem::CopyPostLtoArtifacts(m) => WorkItemResult::Finished(
1872execute_copy_from_cache_work_item(&cgcx, &prof, shared_emitter, m),
1873 ),
1874 }));
18751876let msg = match result {
1877Ok(result) => Message::WorkItem::<B> { result: Ok(result) },
18781879// We ignore any `FatalError` coming out of `execute_work_item`, as a
1880 // diagnostic was already sent off to the main thread - just surface
1881 // that there was an error in this worker.
1882Err(err) if err.is::<FatalErrorMarker>() => {
1883 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1884 }
18851886Err(_) => Message::WorkItem::<B> { result: Err(None) },
1887 };
1888drop(coordinator_send.send(msg));
1889 };
1890 std::thread::Builder::new()
1891 .name(name)
1892 .stack_size(stack_size)
1893 .spawn(f)
1894 .expect("failed to spawn work thread");
1895}
18961897fn spawn_thin_lto_work<B: WriteBackendMethods>(
1898 cgcx: &CodegenContext,
1899 prof: &SelfProfilerRef,
1900 shared_emitter: SharedEmitter,
1901 tm_factory: TargetMachineFactoryFn<B>,
1902 coordinator_send: Sender<ThinLtoMessage>,
1903 work: ThinLtoWorkItem<B>,
1904 stack_size: usize,
1905) {
1906let cgcx = cgcx.clone();
1907let prof = prof.clone();
19081909let name = work.short_description();
1910let f = move || {
1911let _profiler = if cgcx.time_trace { B::thread_profiler() } else { Box::new(()) };
19121913let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1914 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
1915execute_copy_from_cache_work_item(&cgcx, &prof, shared_emitter, m)
1916 }
1917 ThinLtoWorkItem::ThinLto(m) => {
1918let _timer = prof.generic_activity_with_arg("codegen_module_perform_lto", m.name());
1919 B::optimize_and_codegen_thin(&cgcx, &prof, &shared_emitter, tm_factory, m)
1920 }
1921 }));
19221923let msg = match result {
1924Ok(result) => ThinLtoMessage::WorkItem { result: Ok(result) },
19251926// We ignore any `FatalError` coming out of `execute_work_item`, as a
1927 // diagnostic was already sent off to the main thread - just surface
1928 // that there was an error in this worker.
1929Err(err) if err.is::<FatalErrorMarker>() => {
1930 ThinLtoMessage::WorkItem { result: Err(Some(WorkerFatalError)) }
1931 }
19321933Err(_) => ThinLtoMessage::WorkItem { result: Err(None) },
1934 };
1935drop(coordinator_send.send(msg));
1936 };
1937 std::thread::Builder::new()
1938 .name(name)
1939 .stack_size(stack_size)
1940 .spawn(f)
1941 .expect("failed to spawn work thread");
1942}
19431944enum SharedEmitterMessage {
1945 Diagnostic(DiagInner),
1946 InlineAsmError(InlineAsmError),
1947 Fatal(String),
1948}
19491950pub struct InlineAsmError {
1951// We store byte positions rather than a `Span` because this error is created on a codegen
1952 // thread which doesn't have access to the span interner within the session globals. The byte
1953 // positions are converted to a `Span` once they reach a thread with access to the span
1954 // interner.
1955pub lo: BytePos,
1956pub hi: BytePos,
1957pub msg: String,
1958pub level: Level,
1959pub source: Option<(String, Vec<InnerSpan>)>,
1960}
19611962#[derive(#[automatically_derived]
impl ::core::clone::Clone for SharedEmitter {
#[inline]
fn clone(&self) -> Self {
SharedEmitter { sender: ::core::clone::Clone::clone(&self.sender) }
}
}Clone)]
1963pub struct SharedEmitter {
1964 sender: Sender<SharedEmitterMessage>,
1965}
19661967pub struct SharedEmitterMain {
1968 receiver: Receiver<SharedEmitterMessage>,
1969}
19701971impl SharedEmitter {
1972fn new() -> (SharedEmitter, SharedEmitterMain) {
1973let (sender, receiver) = channel();
19741975 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1976 }
19771978pub fn inline_asm_error(&self, err: InlineAsmError) {
1979drop(self.sender.send(SharedEmitterMessage::InlineAsmError(err)));
1980 }
19811982fn fatal(&self, msg: &str) {
1983drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1984 }
1985}
19861987impl Emitterfor SharedEmitter {
1988fn emit_diagnostic(&mut self, diag: DiagInner) {
1989drop(self.sender.send(SharedEmitterMessage::Diagnostic(diag)));
1990 }
19911992fn source_map(&self) -> Option<&SourceMap> {
1993None1994 }
1995}
19961997impl SharedEmitterMain {
1998fn check(&self, sess: &Session, blocking: bool) {
1999loop {
2000let message = if blocking {
2001match self.receiver.recv() {
2002Ok(message) => Ok(message),
2003Err(_) => Err(()),
2004 }
2005 } else {
2006match self.receiver.try_recv() {
2007Ok(message) => Ok(message),
2008Err(_) => Err(()),
2009 }
2010 };
20112012match message {
2013Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2014let dcx = sess.dcx();
2015dcx.emit_diagnostic(diag);
2016sess.dcx().abort_if_errors();
2017 }
2018Ok(SharedEmitterMessage::InlineAsmError(inner)) => {
2019{
match inner.level {
Level::Error | Level::Warning(None) | Level::Note => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"Level::Error | Level::Warning(None) | Level::Note",
::core::option::Option::None);
}
}
};assert_matches!(inner.level, Level::Error | Level::Warning(None) | Level::Note);
2020let mut err = Diag::new(sess.dcx(), inner.level, inner.msg);
2021let span = Span::new(inner.lo, inner.hi, SyntaxContext::root(), None);
2022if !span.is_dummy() {
2023err.span(span);
2024 }
20252026// Point to the generated assembly if it is available.
2027if let Some((buffer, spans)) = inner.source {
2028let source = sess2029 .source_map()
2030 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
2031let spans: Vec<_> = spans2032 .iter()
2033 .map(|sp| {
2034Span::with_root_ctxt(
2035source.normalized_byte_pos(sp.start as u32),
2036source.normalized_byte_pos(sp.end as u32),
2037 )
2038 })
2039 .collect();
2040err.span_note(spans, "instantiated into assembly here");
2041 }
20422043err.emit();
2044 }
2045Ok(SharedEmitterMessage::Fatal(msg)) => {
2046sess.dcx().fatal(msg);
2047 }
2048Err(_) => {
2049break;
2050 }
2051 }
2052 }
2053 }
2054}
20552056pub struct Coordinator<B: WriteBackendMethods> {
2057 sender: Sender<Message<B>>,
2058 future: Option<thread::JoinHandle<Result<MaybeLtoModules<B>, ()>>>,
2059// Only used for the Message type.
2060phantom: PhantomData<B>,
2061}
20622063impl<B: WriteBackendMethods> Coordinator<B> {
2064fn join(mut self) -> std::thread::Result<Result<MaybeLtoModules<B>, ()>> {
2065self.future.take().unwrap().join()
2066 }
2067}
20682069impl<B: WriteBackendMethods> Dropfor Coordinator<B> {
2070fn drop(&mut self) {
2071if let Some(future) = self.future.take() {
2072// If we haven't joined yet, signal to the coordinator that it should spawn no more
2073 // work, and wait for worker threads to finish.
2074drop(self.sender.send(Message::CodegenAborted::<B>));
2075drop(future.join());
2076 }
2077 }
2078}
20792080pub struct OngoingCodegen<B: WriteBackendMethods> {
2081 backend: B,
2082 output_filenames: Arc<OutputFilenames>,
2083// Field order below is intended to terminate the coordinator thread before two fields below
2084 // drop and prematurely close channels used by coordinator thread. See `Coordinator`'s
2085 // `Drop` implementation for more info.
2086pub(crate) coordinator: Coordinator<B>,
2087 codegen_worker_receive: Receiver<CguMessage>,
2088 shared_emitter_main: SharedEmitterMain,
2089}
20902091impl<B: WriteBackendMethods> OngoingCodegen<B> {
2092pub fn join(
2093self,
2094 sess: &Session,
2095 incr_comp_session: Option<&IncrCompSession>,
2096 crate_info: &CrateInfo,
2097 ) -> (CompiledModules, WorkProductMap) {
2098self.shared_emitter_main.check(sess, true);
20992100let maybe_lto_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
2101Ok(Ok(maybe_lto_modules)) => maybe_lto_modules,
2102Ok(Err(())) => {
2103sess.dcx().abort_if_errors();
2104{
::core::panicking::panic_fmt(format_args!("expected abort due to worker thread errors"));
}panic!("expected abort due to worker thread errors")2105 }
2106Err(_) => {
2107::rustc_span::macros::bug_impl(None,
format_args!("panic during codegen/LLVM phase"), Location::caller());bug!("panic during codegen/LLVM phase");
2108 }
2109 });
21102111sess.dcx().abort_if_errors();
21122113let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
21142115// Catch fatal errors to ensure shared_emitter_main.check() can emit the actual diagnostics
2116let compiled_modules = catch_fatal_errors(|| match maybe_lto_modules {
2117 MaybeLtoModules::NoLto(compiled_modules) => {
2118drop(shared_emitter);
2119compiled_modules2120 }
2121 MaybeLtoModules::FatLto { cgcx, needs_fat_lto } => {
2122let tm_factory = self.backend.target_machine_factory(sess, cgcx.opt_level);
21232124CompiledModules {
2125 modules: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[do_fat_lto(sess, &cgcx, shared_emitter, tm_factory,
&crate_info.exported_symbols_for_lto,
&crate_info.each_linked_rlib_file_for_lto, needs_fat_lto)]))vec![do_fat_lto(
2126 sess,
2127&cgcx,
2128 shared_emitter,
2129 tm_factory,
2130&crate_info.exported_symbols_for_lto,
2131&crate_info.each_linked_rlib_file_for_lto,
2132 needs_fat_lto,
2133 )],
2134 allocator_module: None,
2135 }
2136 }
2137 MaybeLtoModules::ThinLto { cgcx, needs_thin_lto } => {
2138let tm_factory = self.backend.target_machine_factory(sess, cgcx.opt_level);
21392140CompiledModules {
2141 modules: do_thin_lto::<B>(
2142&cgcx,
2143&sess.prof,
2144shared_emitter,
2145tm_factory,
2146&crate_info.exported_symbols_for_lto,
2147&crate_info.each_linked_rlib_file_for_lto,
2148needs_thin_lto,
2149sess.opts.recommended_stack_size,
2150 ),
2151 allocator_module: None,
2152 }
2153 }
2154 });
21552156shared_emitter_main.check(sess, true);
21572158sess.dcx().abort_if_errors();
21592160let mut compiled_modules =
2161compiled_modules.expect("fatal error emitted but not sent to SharedEmitter");
21622163// Regardless of what order these modules completed in, report them to
2164 // the backend in the same order every time to ensure that we're handing
2165 // out deterministic results.
2166compiled_modules.modules.sort_by(|a, b| a.name.cmp(&b.name));
21672168let work_products = copy_all_cgu_workproducts_to_incr_comp_cache_dir(
2169sess,
2170incr_comp_session,
2171&compiled_modules,
2172 );
2173produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
21742175 (compiled_modules, work_products)
2176 }
21772178pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2179self.wait_for_signal_to_codegen_item();
2180self.check_for_errors(tcx.sess);
2181drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
2182 }
21832184pub(crate) fn check_for_errors(&self, sess: &Session) {
2185self.shared_emitter_main.check(sess, false);
2186 }
21872188pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2189match self.codegen_worker_receive.recv() {
2190Ok(CguMessage) => {
2191// Ok to proceed.
2192}
2193Err(_) => {
2194// One of the LLVM threads must have panicked, fall through so
2195 // error handling can be reached.
2196}
2197 }
2198 }
2199}
22002201pub(crate) fn submit_codegened_module_to_llvm<B: WriteBackendMethods>(
2202 coordinator: &Coordinator<B>,
2203 module: ModuleCodegen<B::Module>,
2204 cost: u64,
2205) {
2206let llvm_work_item = WorkItem::Optimize(module);
2207drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2208}
22092210pub(crate) fn submit_post_lto_module_to_llvm<B: WriteBackendMethods>(
2211 coordinator: &Coordinator<B>,
2212 module: CachedModuleCodegen,
2213) {
2214let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2215drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2216}
22172218pub(crate) fn submit_pre_lto_module_to_llvm<B: WriteBackendMethods>(
2219 tcx: TyCtxt<'_>,
2220 coordinator: &Coordinator<B>,
2221 module: CachedModuleCodegen,
2222) {
2223let filename = pre_lto_bitcode_filename(&module.name);
2224let old_bitcode_path =
2225in_old_incr_comp_dir_sess(tcx.incr_comp_session.unwrap(), &filename).unwrap();
2226let bitcode_path = in_incr_comp_dir_sess(tcx.incr_comp_session.unwrap(), &filename);
22272228match link_or_copy(&old_bitcode_path, &bitcode_path) {
2229Ok(_) => {}
2230Err(error) => {
2231tcx.sess.dcx().emit_err(diagnostics::CopyPathBuf {
2232 source_file: old_bitcode_path,
2233 output_path: bitcode_path,
2234error,
2235 });
2236return;
2237 }
2238 }
22392240// Schedule the module to be loaded
2241drop(
2242coordinator2243 .sender
2244 .send(Message::AddImportOnlyModule::<B> { bitcode_path, work_product: module.source }),
2245 );
2246}
22472248fn pre_lto_bitcode_filename(module_name: &str) -> String {
2249::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.{1}", module_name,
PRE_LTO_BC_EXT))
})format!("{module_name}.{PRE_LTO_BC_EXT}")2250}
22512252fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2253// This should never be true (because it's not supported). If it is true,
2254 // something is wrong with commandline arg validation.
2255if !!(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!(
2256 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2257 && tcx.sess.target.is_like_windows
2258 && tcx.sess.opts.cg.prefer_dynamic)
2259 );
22602261// We need to generate _imp__ symbol if we are generating an rlib or we include one
2262 // indirectly from ThinLTO. In theory these are not needed as ThinLTO could resolve
2263 // these, but it currently does not do so.
2264let can_have_static_objects =
2265tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
22662267tcx.sess.target.is_like_windows &&
2268can_have_static_objects &&
2269// ThinLTO can't handle this workaround in all cases, so we don't
2270 // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2271 // dynamic linking when linker plugin LTO is enabled.
2272!tcx.sess.opts.cg.linker_plugin_lto.enabled()
2273}