1use std::marker::PhantomData;
2use std::panic::AssertUnwindSafe;
3use std::path::{Path, PathBuf};
4use std::sync::Arc;
5use std::sync::mpsc::{Receiver, Sender, channel};
6use std::{fs, io, mem, str, thread};
7
8use rustc_abi::Size;
9use rustc_data_structures::assert_matches;
10use rustc_data_structures::fx::FxIndexMap;
11use rustc_data_structures::jobserver::{self, Acquired};
12use rustc_data_structures::memmap::Mmap;
13use rustc_data_structures::profiling::{SelfProfilerRef, VerboseTimingGuard};
14use rustc_errors::emitter::Emitter;
15use rustc_errors::translation::Translator;
16use rustc_errors::{
17 Diag, DiagArgMap, DiagCtxt, DiagCtxtHandle, DiagMessage, ErrCode, FatalError, FatalErrorMarker,
18 Level, MultiSpan, Style, Suggestions, catch_fatal_errors,
19};
20use rustc_fs_util::link_or_copy;
21use rustc_hir::attrs::AttributeKind;
22use rustc_hir::find_attr;
23use rustc_incremental::{
24 copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess,
25};
26use rustc_metadata::fs::copy_to_stdout;
27use rustc_middle::bug;
28use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
29use rustc_middle::ty::TyCtxt;
30use rustc_session::Session;
31use rustc_session::config::{
32 self, CrateType, Lto, OutFileName, OutputFilenames, OutputType, Passes, SwitchWithOptPath,
33};
34use rustc_span::source_map::SourceMap;
35use rustc_span::{FileName, InnerSpan, Span, SpanData};
36use rustc_target::spec::{MergeFunctions, SanitizerSet};
37use tracing::debug;
38
39use super::link::{self, ensure_removed};
40use super::lto::{self, SerializedModule};
41use crate::back::lto::check_lto_allowed;
42use crate::errors::ErrorCreatingRemarkDir;
43use crate::traits::*;
44use crate::{
45 CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
46 errors,
47};
48
49const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
50
51#[derive(#[automatically_derived]
impl ::core::clone::Clone for EmitObj {
#[inline]
fn clone(&self) -> EmitObj {
let _: ::core::clone::AssertParamIsClone<BitcodeSection>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for EmitObj { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for EmitObj {
#[inline]
fn eq(&self, other: &EmitObj) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(EmitObj::ObjectCode(__self_0), EmitObj::ObjectCode(__arg1_0))
=> __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq)]
53pub enum EmitObj {
54 None,
56
57 Bitcode,
60
61 ObjectCode(BitcodeSection),
63}
64
65#[derive(#[automatically_derived]
impl ::core::clone::Clone for BitcodeSection {
#[inline]
fn clone(&self) -> BitcodeSection { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for BitcodeSection { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for BitcodeSection {
#[inline]
fn eq(&self, other: &BitcodeSection) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
67pub enum BitcodeSection {
68 None,
70
71 Full,
73}
74
75pub struct ModuleConfig {
77 pub passes: Vec<String>,
79 pub opt_level: Option<config::OptLevel>,
82
83 pub pgo_gen: SwitchWithOptPath,
84 pub pgo_use: Option<PathBuf>,
85 pub pgo_sample_use: Option<PathBuf>,
86 pub debug_info_for_profiling: bool,
87 pub instrument_coverage: bool,
88
89 pub sanitizer: SanitizerSet,
90 pub sanitizer_recover: SanitizerSet,
91 pub sanitizer_dataflow_abilist: Vec<String>,
92 pub sanitizer_memory_track_origins: usize,
93
94 pub emit_pre_lto_bc: bool,
96 pub emit_no_opt_bc: bool,
97 pub emit_bc: bool,
98 pub emit_ir: bool,
99 pub emit_asm: bool,
100 pub emit_obj: EmitObj,
101 pub emit_thin_lto: bool,
102 pub emit_thin_lto_summary: bool,
103
104 pub verify_llvm_ir: bool,
107 pub lint_llvm_ir: bool,
108 pub no_prepopulate_passes: bool,
109 pub no_builtins: bool,
110 pub vectorize_loop: bool,
111 pub vectorize_slp: bool,
112 pub merge_functions: bool,
113 pub emit_lifetime_markers: bool,
114 pub llvm_plugins: Vec<String>,
115 pub autodiff: Vec<config::AutoDiff>,
116 pub offload: Vec<config::Offload>,
117}
118
119impl ModuleConfig {
120 fn new(kind: ModuleKind, tcx: TyCtxt<'_>, no_builtins: bool) -> ModuleConfig {
121 macro_rules! if_regular {
124 ($regular: expr, $other: expr) => {
125 if let ModuleKind::Regular = kind { $regular } else { $other }
126 };
127 }
128
129 let sess = tcx.sess;
130 let opt_level_and_size = if let ModuleKind::Regular = kind { Some(sess.opts.optimize) } else { None }if_regular!(Some(sess.opts.optimize), None);
131
132 let save_temps = sess.opts.cg.save_temps;
133
134 let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
135 || match kind {
136 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
137 ModuleKind::Allocator => false,
138 };
139
140 let emit_obj = if !should_emit_obj {
141 EmitObj::None
142 } else if sess.target.obj_is_bitcode
143 || (sess.opts.cg.linker_plugin_lto.enabled() && !no_builtins)
144 {
145 EmitObj::Bitcode
160 } else if need_bitcode_in_object(tcx) {
161 EmitObj::ObjectCode(BitcodeSection::Full)
162 } else {
163 EmitObj::ObjectCode(BitcodeSection::None)
164 };
165
166 ModuleConfig {
167 passes: if let ModuleKind::Regular = kind {
sess.opts.cg.passes.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.cg.passes.clone(), vec![]),
168
169 opt_level: opt_level_and_size,
170
171 pgo_gen: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_generate.clone()
} else { SwitchWithOptPath::Disabled }if_regular!(
172 sess.opts.cg.profile_generate.clone(),
173 SwitchWithOptPath::Disabled
174 ),
175 pgo_use: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_use.clone()
} else { None }if_regular!(sess.opts.cg.profile_use.clone(), None),
176 pgo_sample_use: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.profile_sample_use.clone()
} else { None }if_regular!(sess.opts.unstable_opts.profile_sample_use.clone(), None),
177 debug_info_for_profiling: sess.opts.unstable_opts.debug_info_for_profiling,
178 instrument_coverage: if let ModuleKind::Regular = kind {
sess.instrument_coverage()
} else { false }if_regular!(sess.instrument_coverage(), false),
179
180 sanitizer: if let ModuleKind::Regular = kind {
sess.sanitizers()
} else { SanitizerSet::empty() }if_regular!(sess.sanitizers(), SanitizerSet::empty()),
181 sanitizer_dataflow_abilist: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone()
} else { Vec::new() }if_regular!(
182 sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
183 Vec::new()
184 ),
185 sanitizer_recover: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_recover
} else { SanitizerSet::empty() }if_regular!(
186 sess.opts.unstable_opts.sanitizer_recover,
187 SanitizerSet::empty()
188 ),
189 sanitizer_memory_track_origins: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_memory_track_origins
} else { 0 }if_regular!(
190 sess.opts.unstable_opts.sanitizer_memory_track_origins,
191 0
192 ),
193
194 emit_pre_lto_bc: if let ModuleKind::Regular = kind {
save_temps || need_pre_lto_bitcode_for_incr_comp(sess)
} else { false }if_regular!(
195 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
196 false
197 ),
198 emit_no_opt_bc: if let ModuleKind::Regular = kind { save_temps } else { false }if_regular!(save_temps, false),
199 emit_bc: if let ModuleKind::Regular = kind {
save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode)
} else { save_temps }if_regular!(
200 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
201 save_temps
202 ),
203 emit_ir: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::LlvmAssembly)
} else { false }if_regular!(
204 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
205 false
206 ),
207 emit_asm: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::Assembly)
} else { false }if_regular!(
208 sess.opts.output_types.contains_key(&OutputType::Assembly),
209 false
210 ),
211 emit_obj,
212 emit_thin_lto: sess.opts.unstable_opts.emit_thin_lto && sess.lto() != Lto::Fat,
215 emit_thin_lto_summary: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode)
} else { false }if_regular!(
216 sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode),
217 false
218 ),
219
220 verify_llvm_ir: sess.verify_llvm_ir(),
221 lint_llvm_ir: sess.opts.unstable_opts.lint_llvm_ir,
222 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
223 no_builtins: no_builtins || sess.target.no_builtins,
224
225 vectorize_loop: !sess.opts.cg.no_vectorize_loops
228 && (sess.opts.optimize == config::OptLevel::More
229 || sess.opts.optimize == config::OptLevel::Aggressive),
230 vectorize_slp: !sess.opts.cg.no_vectorize_slp
231 && sess.opts.optimize == config::OptLevel::Aggressive,
232
233 merge_functions: match sess
243 .opts
244 .unstable_opts
245 .merge_functions
246 .unwrap_or(sess.target.merge_functions)
247 {
248 MergeFunctions::Disabled => false,
249 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
250 use config::OptLevel::*;
251 match sess.opts.optimize {
252 Aggressive | More | SizeMin | Size => true,
253 Less | No => false,
254 }
255 }
256 },
257
258 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 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![]),
262 }
263 }
264
265 pub fn bitcode_needed(&self) -> bool {
266 self.emit_bc
267 || self.emit_thin_lto_summary
268 || self.emit_obj == EmitObj::Bitcode
269 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
270 }
271
272 pub fn embed_bitcode(&self) -> bool {
273 self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
274 }
275}
276
277pub struct TargetMachineFactoryConfig {
279 pub split_dwarf_file: Option<PathBuf>,
283
284 pub output_obj_file: Option<PathBuf>,
287}
288
289impl TargetMachineFactoryConfig {
290 pub fn new(
291 cgcx: &CodegenContext<impl WriteBackendMethods>,
292 module_name: &str,
293 ) -> TargetMachineFactoryConfig {
294 let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
295 cgcx.output_filenames.split_dwarf_path(
296 cgcx.split_debuginfo,
297 cgcx.split_dwarf_kind,
298 module_name,
299 cgcx.invocation_temp.as_deref(),
300 )
301 } else {
302 None
303 };
304
305 let output_obj_file = Some(cgcx.output_filenames.temp_path_for_cgu(
306 OutputType::Object,
307 module_name,
308 cgcx.invocation_temp.as_deref(),
309 ));
310 TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }
311 }
312}
313
314pub type TargetMachineFactoryFn<B> = Arc<
315 dyn Fn(
316 TargetMachineFactoryConfig,
317 ) -> Result<
318 <B as WriteBackendMethods>::TargetMachine,
319 <B as WriteBackendMethods>::TargetMachineError,
320 > + Send
321 + Sync,
322>;
323
324#[derive(#[automatically_derived]
impl<B: ::core::clone::Clone + WriteBackendMethods> ::core::clone::Clone for
CodegenContext<B> {
#[inline]
fn clone(&self) -> CodegenContext<B> {
CodegenContext {
prof: ::core::clone::Clone::clone(&self.prof),
lto: ::core::clone::Clone::clone(&self.lto),
use_linker_plugin_lto: ::core::clone::Clone::clone(&self.use_linker_plugin_lto),
dylib_lto: ::core::clone::Clone::clone(&self.dylib_lto),
prefer_dynamic: ::core::clone::Clone::clone(&self.prefer_dynamic),
save_temps: ::core::clone::Clone::clone(&self.save_temps),
fewer_names: ::core::clone::Clone::clone(&self.fewer_names),
time_trace: ::core::clone::Clone::clone(&self.time_trace),
crate_types: ::core::clone::Clone::clone(&self.crate_types),
output_filenames: ::core::clone::Clone::clone(&self.output_filenames),
invocation_temp: ::core::clone::Clone::clone(&self.invocation_temp),
module_config: ::core::clone::Clone::clone(&self.module_config),
tm_factory: ::core::clone::Clone::clone(&self.tm_factory),
msvc_imps_needed: ::core::clone::Clone::clone(&self.msvc_imps_needed),
is_pe_coff: ::core::clone::Clone::clone(&self.is_pe_coff),
target_can_use_split_dwarf: ::core::clone::Clone::clone(&self.target_can_use_split_dwarf),
target_arch: ::core::clone::Clone::clone(&self.target_arch),
target_is_like_darwin: ::core::clone::Clone::clone(&self.target_is_like_darwin),
target_is_like_aix: ::core::clone::Clone::clone(&self.target_is_like_aix),
target_is_like_gpu: ::core::clone::Clone::clone(&self.target_is_like_gpu),
split_debuginfo: ::core::clone::Clone::clone(&self.split_debuginfo),
split_dwarf_kind: ::core::clone::Clone::clone(&self.split_dwarf_kind),
pointer_size: ::core::clone::Clone::clone(&self.pointer_size),
remark: ::core::clone::Clone::clone(&self.remark),
remark_dir: ::core::clone::Clone::clone(&self.remark_dir),
incr_comp_session_dir: ::core::clone::Clone::clone(&self.incr_comp_session_dir),
parallel: ::core::clone::Clone::clone(&self.parallel),
}
}
}Clone)]
326pub struct CodegenContext<B: WriteBackendMethods> {
327 pub prof: SelfProfilerRef,
329 pub lto: Lto,
330 pub use_linker_plugin_lto: bool,
331 pub dylib_lto: bool,
332 pub prefer_dynamic: bool,
333 pub save_temps: bool,
334 pub fewer_names: bool,
335 pub time_trace: bool,
336 pub crate_types: Vec<CrateType>,
337 pub output_filenames: Arc<OutputFilenames>,
338 pub invocation_temp: Option<String>,
339 pub module_config: Arc<ModuleConfig>,
340 pub tm_factory: TargetMachineFactoryFn<B>,
341 pub msvc_imps_needed: bool,
342 pub is_pe_coff: bool,
343 pub target_can_use_split_dwarf: bool,
344 pub target_arch: String,
345 pub target_is_like_darwin: bool,
346 pub target_is_like_aix: bool,
347 pub target_is_like_gpu: bool,
348 pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
349 pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
350 pub pointer_size: Size,
351
352 pub remark: Passes,
354 pub remark_dir: Option<PathBuf>,
357 pub incr_comp_session_dir: Option<PathBuf>,
360 pub parallel: bool,
364}
365
366fn generate_thin_lto_work<B: ExtraBackendMethods>(
367 cgcx: &CodegenContext<B>,
368 dcx: DiagCtxtHandle<'_>,
369 exported_symbols_for_lto: &[String],
370 each_linked_rlib_for_lto: &[PathBuf],
371 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
372 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
373) -> Vec<(ThinLtoWorkItem<B>, u64)> {
374 let _prof_timer = cgcx.prof.generic_activity("codegen_thin_generate_lto_work");
375
376 let (lto_modules, copy_jobs) = B::run_thin_lto(
377 cgcx,
378 dcx,
379 exported_symbols_for_lto,
380 each_linked_rlib_for_lto,
381 needs_thin_lto,
382 import_only_modules,
383 );
384 lto_modules
385 .into_iter()
386 .map(|module| {
387 let cost = module.cost();
388 (ThinLtoWorkItem::ThinLto(module), cost)
389 })
390 .chain(copy_jobs.into_iter().map(|wp| {
391 (
392 ThinLtoWorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
393 name: wp.cgu_name.clone(),
394 source: wp,
395 }),
396 0, )
398 }))
399 .collect()
400}
401
402struct CompiledModules {
403 modules: Vec<CompiledModule>,
404 allocator_module: Option<CompiledModule>,
405}
406
407enum MaybeLtoModules<B: WriteBackendMethods> {
408 NoLto {
409 modules: Vec<CompiledModule>,
410 allocator_module: Option<CompiledModule>,
411 },
412 FatLto {
413 cgcx: CodegenContext<B>,
414 exported_symbols_for_lto: Arc<Vec<String>>,
415 each_linked_rlib_file_for_lto: Vec<PathBuf>,
416 needs_fat_lto: Vec<FatLtoInput<B>>,
417 lto_import_only_modules:
418 Vec<(SerializedModule<<B as WriteBackendMethods>::ModuleBuffer>, WorkProduct)>,
419 },
420 ThinLto {
421 cgcx: CodegenContext<B>,
422 exported_symbols_for_lto: Arc<Vec<String>>,
423 each_linked_rlib_file_for_lto: Vec<PathBuf>,
424 needs_thin_lto: Vec<(String, <B as WriteBackendMethods>::ThinBuffer)>,
425 lto_import_only_modules:
426 Vec<(SerializedModule<<B as WriteBackendMethods>::ModuleBuffer>, WorkProduct)>,
427 },
428}
429
430fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
431 let sess = tcx.sess;
432 sess.opts.cg.embed_bitcode
433 && tcx.crate_types().contains(&CrateType::Rlib)
434 && sess.opts.output_types.contains_key(&OutputType::Exe)
435}
436
437fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
438 if sess.opts.incremental.is_none() {
439 return false;
440 }
441
442 match sess.lto() {
443 Lto::No => false,
444 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
445 }
446}
447
448pub(crate) fn start_async_codegen<B: ExtraBackendMethods>(
449 backend: B,
450 tcx: TyCtxt<'_>,
451 target_cpu: String,
452 allocator_module: Option<ModuleCodegen<B::Module>>,
453) -> OngoingCodegen<B> {
454 let (coordinator_send, coordinator_receive) = channel();
455
456 let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
457 let no_builtins = {
{
'done:
{
for i in crate_attrs {
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(AttributeKind::NoBuiltins) => {
break 'done Some(());
}
_ => {}
}
}
None
}
}.is_some()
}find_attr!(crate_attrs, AttributeKind::NoBuiltins);
458
459 let crate_info = CrateInfo::new(tcx, target_cpu);
460
461 let regular_config = ModuleConfig::new(ModuleKind::Regular, tcx, no_builtins);
462 let allocator_config = ModuleConfig::new(ModuleKind::Allocator, tcx, no_builtins);
463
464 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
465 let (codegen_worker_send, codegen_worker_receive) = channel();
466
467 let coordinator_thread = start_executing_work(
468 backend.clone(),
469 tcx,
470 &crate_info,
471 shared_emitter,
472 codegen_worker_send,
473 coordinator_receive,
474 Arc::new(regular_config),
475 Arc::new(allocator_config),
476 allocator_module,
477 coordinator_send.clone(),
478 );
479
480 OngoingCodegen {
481 backend,
482 crate_info,
483
484 codegen_worker_receive,
485 shared_emitter_main,
486 coordinator: Coordinator {
487 sender: coordinator_send,
488 future: Some(coordinator_thread),
489 phantom: PhantomData,
490 },
491 output_filenames: Arc::clone(tcx.output_filenames(())),
492 }
493}
494
495fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
496 sess: &Session,
497 compiled_modules: &CompiledModules,
498) -> FxIndexMap<WorkProductId, WorkProduct> {
499 let mut work_products = FxIndexMap::default();
500
501 if sess.opts.incremental.is_none() {
502 return work_products;
503 }
504
505 let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
506
507 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
508 let mut files = Vec::new();
509 if let Some(object_file_path) = &module.object {
510 files.push((OutputType::Object.extension(), object_file_path.as_path()));
511 }
512 if let Some(dwarf_object_file_path) = &module.dwarf_object {
513 files.push(("dwo", dwarf_object_file_path.as_path()));
514 }
515 if let Some(path) = &module.assembly {
516 files.push((OutputType::Assembly.extension(), path.as_path()));
517 }
518 if let Some(path) = &module.llvm_ir {
519 files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
520 }
521 if let Some(path) = &module.bytecode {
522 files.push((OutputType::Bitcode.extension(), path.as_path()));
523 }
524 if let Some((id, product)) = copy_cgu_workproduct_to_incr_comp_cache_dir(
525 sess,
526 &module.name,
527 files.as_slice(),
528 &module.links_from_incr_cache,
529 ) {
530 work_products.insert(id, product);
531 }
532 }
533
534 work_products
535}
536
537fn produce_final_output_artifacts(
538 sess: &Session,
539 compiled_modules: &CompiledModules,
540 crate_output: &OutputFilenames,
541) {
542 let mut user_wants_bitcode = false;
543 let mut user_wants_objects = false;
544
545 let copy_gracefully = |from: &Path, to: &OutFileName| match to {
547 OutFileName::Stdout if let Err(e) = copy_to_stdout(from) => {
548 sess.dcx().emit_err(errors::CopyPath::new(from, to.as_path(), e));
549 }
550 OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
551 sess.dcx().emit_err(errors::CopyPath::new(from, path, e));
552 }
553 _ => {}
554 };
555
556 let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
557 if let [module] = &compiled_modules.modules[..] {
558 let path = crate_output.temp_path_for_cgu(
561 output_type,
562 &module.name,
563 sess.invocation_temp.as_deref(),
564 );
565 let output = crate_output.path(output_type);
566 if !output_type.is_text_output() && output.is_tty() {
567 sess.dcx()
568 .emit_err(errors::BinaryOutputToTty { shorthand: output_type.shorthand() });
569 } else {
570 copy_gracefully(&path, &output);
571 }
572 if !sess.opts.cg.save_temps && !keep_numbered {
573 ensure_removed(sess.dcx(), &path);
575 }
576 } else {
577 if crate_output.outputs.contains_explicit_name(&output_type) {
578 sess.dcx()
581 .emit_warn(errors::IgnoringEmitPath { extension: output_type.extension() });
582 } else if crate_output.single_output_file.is_some() {
583 sess.dcx().emit_warn(errors::IgnoringOutput { extension: output_type.extension() });
586 } else {
587 }
591 }
592 };
593
594 for output_type in crate_output.outputs.keys() {
598 match *output_type {
599 OutputType::Bitcode => {
600 user_wants_bitcode = true;
601 copy_if_one_unit(OutputType::Bitcode, true);
605 }
606 OutputType::ThinLinkBitcode => {
607 copy_if_one_unit(OutputType::ThinLinkBitcode, false);
608 }
609 OutputType::LlvmAssembly => {
610 copy_if_one_unit(OutputType::LlvmAssembly, false);
611 }
612 OutputType::Assembly => {
613 copy_if_one_unit(OutputType::Assembly, false);
614 }
615 OutputType::Object => {
616 user_wants_objects = true;
617 copy_if_one_unit(OutputType::Object, true);
618 }
619 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
620 }
621 }
622
623 if !sess.opts.cg.save_temps {
636 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
652
653 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
654
655 let keep_numbered_objects =
656 needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
657
658 for module in compiled_modules.modules.iter() {
659 if !keep_numbered_objects {
660 if let Some(ref path) = module.object {
661 ensure_removed(sess.dcx(), path);
662 }
663
664 if let Some(ref path) = module.dwarf_object {
665 ensure_removed(sess.dcx(), path);
666 }
667 }
668
669 if let Some(ref path) = module.bytecode {
670 if !keep_numbered_bitcode {
671 ensure_removed(sess.dcx(), path);
672 }
673 }
674 }
675
676 if !user_wants_bitcode
677 && let Some(ref allocator_module) = compiled_modules.allocator_module
678 && let Some(ref path) = allocator_module.bytecode
679 {
680 ensure_removed(sess.dcx(), path);
681 }
682 }
683
684 if sess.opts.json_artifact_notifications {
685 if let [module] = &compiled_modules.modules[..] {
686 module.for_each_output(|_path, ty| {
687 if sess.opts.output_types.contains_key(&ty) {
688 let descr = ty.shorthand();
689 let path = crate_output.path(ty);
692 sess.dcx().emit_artifact_notification(path.as_path(), descr);
693 }
694 });
695 } else {
696 for module in &compiled_modules.modules {
697 module.for_each_output(|path, ty| {
698 if sess.opts.output_types.contains_key(&ty) {
699 let descr = ty.shorthand();
700 sess.dcx().emit_artifact_notification(&path, descr);
701 }
702 });
703 }
704 }
705 }
706
707 }
713
714pub(crate) enum WorkItem<B: WriteBackendMethods> {
715 Optimize(ModuleCodegen<B::Module>),
717 CopyPostLtoArtifacts(CachedModuleCodegen),
720}
721
722enum ThinLtoWorkItem<B: WriteBackendMethods> {
723 CopyPostLtoArtifacts(CachedModuleCodegen),
726 ThinLto(lto::ThinModule<B>),
728}
729
730#[cfg(not(windows))]
734fn desc(short: &str, _long: &str, name: &str) -> String {
735 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);
755 let name = if let Some(index) = name.find("-cgu.") {
756 &name[index + 1..] } else {
758 name
759 };
760 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}", short, name))
})format!("{short} {name}")
761}
762
763#[cfg(windows)]
765fn desc(_short: &str, long: &str, name: &str) -> String {
766 format!("{long} {name}")
767}
768
769impl<B: WriteBackendMethods> WorkItem<B> {
770 fn short_description(&self) -> String {
772 match self {
773 WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
774 WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
775 }
776 }
777}
778
779impl<B: WriteBackendMethods> ThinLtoWorkItem<B> {
780 fn short_description(&self) -> String {
782 match self {
783 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
784 desc("cpy", "copy LTO artifacts for", &m.name)
785 }
786 ThinLtoWorkItem::ThinLto(m) => desc("lto", "thin-LTO module", m.name()),
787 }
788 }
789}
790
791pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
793 Finished(CompiledModule),
795
796 NeedsFatLto(FatLtoInput<B>),
799
800 NeedsThinLto(String, B::ThinBuffer),
803}
804
805pub enum FatLtoInput<B: WriteBackendMethods> {
806 Serialized { name: String, buffer: SerializedModule<B::ModuleBuffer> },
807 InMemory(ModuleCodegen<B::Module>),
808}
809
810pub(crate) enum ComputedLtoType {
812 No,
813 Thin,
814 Fat,
815}
816
817pub(crate) fn compute_per_cgu_lto_type(
818 sess_lto: &Lto,
819 linker_does_lto: bool,
820 sess_crate_types: &[CrateType],
821) -> ComputedLtoType {
822 let is_rlib = #[allow(non_exhaustive_omitted_patterns)] match sess_crate_types {
[CrateType::Rlib] => true,
_ => false,
}matches!(sess_crate_types, [CrateType::Rlib]);
835
836 match sess_lto {
837 Lto::ThinLocal if !linker_does_lto => ComputedLtoType::Thin,
838 Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
839 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
840 _ => ComputedLtoType::No,
841 }
842}
843
844fn execute_optimize_work_item<B: ExtraBackendMethods>(
845 cgcx: &CodegenContext<B>,
846 shared_emitter: SharedEmitter,
847 mut module: ModuleCodegen<B::Module>,
848) -> WorkItemResult<B> {
849 let _timer = cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &*module.name);
850
851 B::optimize(cgcx, &shared_emitter, &mut module, &cgcx.module_config);
852
853 let lto_type =
859 compute_per_cgu_lto_type(&cgcx.lto, cgcx.use_linker_plugin_lto, &cgcx.crate_types);
860
861 let bitcode = if cgcx.module_config.emit_pre_lto_bc {
864 let filename = pre_lto_bitcode_filename(&module.name);
865 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
866 } else {
867 None
868 };
869
870 match lto_type {
871 ComputedLtoType::No => {
872 let module = B::codegen(cgcx, &shared_emitter, module, &cgcx.module_config);
873 WorkItemResult::Finished(module)
874 }
875 ComputedLtoType::Thin => {
876 let (name, thin_buffer) = B::prepare_thin(module);
877 if let Some(path) = bitcode {
878 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
879 {
::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);
880 });
881 }
882 WorkItemResult::NeedsThinLto(name, thin_buffer)
883 }
884 ComputedLtoType::Fat => match bitcode {
885 Some(path) => {
886 let (name, buffer) = B::serialize_module(module);
887 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
888 {
::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);
889 });
890 WorkItemResult::NeedsFatLto(FatLtoInput::Serialized {
891 name,
892 buffer: SerializedModule::Local(buffer),
893 })
894 }
895 None => WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module)),
896 },
897 }
898}
899
900fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
901 cgcx: &CodegenContext<B>,
902 shared_emitter: SharedEmitter,
903 module: CachedModuleCodegen,
904) -> CompiledModule {
905 let _timer = cgcx
906 .prof
907 .generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &*module.name);
908
909 let dcx = DiagCtxt::new(Box::new(shared_emitter));
910 let dcx = dcx.handle();
911
912 let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
913
914 let mut links_from_incr_cache = Vec::new();
915
916 let mut load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
917 let source_file = in_incr_comp_dir(incr_comp_session_dir, saved_path);
918 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/write.rs:918",
"rustc_codegen_ssa::back::write", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/write.rs"),
::tracing_core::__macro_support::Option::Some(918u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::write"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("copying preexisting module `{0}` from {1:?} to {2}",
module.name, source_file, output_path.display()) as
&dyn Value))])
});
} else { ; }
};debug!(
919 "copying preexisting module `{}` from {:?} to {}",
920 module.name,
921 source_file,
922 output_path.display()
923 );
924 match link_or_copy(&source_file, &output_path) {
925 Ok(_) => {
926 links_from_incr_cache.push(source_file);
927 Some(output_path)
928 }
929 Err(error) => {
930 dcx.emit_err(errors::CopyPathBuf { source_file, output_path, error });
931 None
932 }
933 }
934 };
935
936 let dwarf_object =
937 module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
938 let dwarf_obj_out = cgcx
939 .output_filenames
940 .split_dwarf_path(
941 cgcx.split_debuginfo,
942 cgcx.split_dwarf_kind,
943 &module.name,
944 cgcx.invocation_temp.as_deref(),
945 )
946 .expect(
947 "saved dwarf object in work product but `split_dwarf_path` returned `None`",
948 );
949 load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
950 });
951
952 let mut load_from_incr_cache = |perform, output_type: OutputType| {
953 if perform {
954 let saved_file = module.source.saved_files.get(output_type.extension())?;
955 let output_path = cgcx.output_filenames.temp_path_for_cgu(
956 output_type,
957 &module.name,
958 cgcx.invocation_temp.as_deref(),
959 );
960 load_from_incr_comp_dir(output_path, &saved_file)
961 } else {
962 None
963 }
964 };
965
966 let module_config = &cgcx.module_config;
967 let should_emit_obj = module_config.emit_obj != EmitObj::None;
968 let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
969 let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
970 let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
971 let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
972 if should_emit_obj && object.is_none() {
973 dcx.emit_fatal(errors::NoSavedObjectFile { cgu_name: &module.name })
974 }
975
976 CompiledModule {
977 links_from_incr_cache,
978 kind: ModuleKind::Regular,
979 name: module.name,
980 object,
981 dwarf_object,
982 bytecode,
983 assembly,
984 llvm_ir,
985 }
986}
987
988fn do_fat_lto<B: ExtraBackendMethods>(
989 cgcx: &CodegenContext<B>,
990 shared_emitter: SharedEmitter,
991 exported_symbols_for_lto: &[String],
992 each_linked_rlib_for_lto: &[PathBuf],
993 mut needs_fat_lto: Vec<FatLtoInput<B>>,
994 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
995) -> CompiledModule {
996 let _timer = cgcx.prof.verbose_generic_activity("LLVM_fatlto");
997
998 let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
999 let dcx = dcx.handle();
1000
1001 check_lto_allowed(&cgcx, dcx);
1002
1003 for (module, wp) in import_only_modules {
1004 needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, buffer: module })
1005 }
1006
1007 let module = B::run_and_optimize_fat_lto(
1008 cgcx,
1009 &shared_emitter,
1010 exported_symbols_for_lto,
1011 each_linked_rlib_for_lto,
1012 needs_fat_lto,
1013 );
1014 B::codegen(cgcx, &shared_emitter, module, &cgcx.module_config)
1015}
1016
1017fn do_thin_lto<'a, B: ExtraBackendMethods>(
1018 cgcx: &'a CodegenContext<B>,
1019 shared_emitter: SharedEmitter,
1020 exported_symbols_for_lto: Arc<Vec<String>>,
1021 each_linked_rlib_for_lto: Vec<PathBuf>,
1022 needs_thin_lto: Vec<(String, <B as WriteBackendMethods>::ThinBuffer)>,
1023 lto_import_only_modules: Vec<(
1024 SerializedModule<<B as WriteBackendMethods>::ModuleBuffer>,
1025 WorkProduct,
1026 )>,
1027) -> Vec<CompiledModule> {
1028 let _timer = cgcx.prof.verbose_generic_activity("LLVM_thinlto");
1029
1030 let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
1031 let dcx = dcx.handle();
1032
1033 check_lto_allowed(&cgcx, dcx);
1034
1035 let (coordinator_send, coordinator_receive) = channel();
1036
1037 let coordinator_send2 = coordinator_send.clone();
1043 let helper = jobserver::client()
1044 .into_helper_thread(move |token| {
1045 drop(coordinator_send2.send(ThinLtoMessage::Token(token)));
1046 })
1047 .expect("failed to spawn helper thread");
1048
1049 let mut work_items = ::alloc::vec::Vec::new()vec![];
1050
1051 for (work, cost) in generate_thin_lto_work(
1057 cgcx,
1058 dcx,
1059 &exported_symbols_for_lto,
1060 &each_linked_rlib_for_lto,
1061 needs_thin_lto,
1062 lto_import_only_modules,
1063 ) {
1064 let insertion_index =
1065 work_items.binary_search_by_key(&cost, |&(_, cost)| cost).unwrap_or_else(|e| e);
1066 work_items.insert(insertion_index, (work, cost));
1067 if cgcx.parallel {
1068 helper.request_token();
1069 }
1070 }
1071
1072 let mut codegen_aborted = None;
1073
1074 let mut tokens = ::alloc::vec::Vec::new()vec![];
1077
1078 let mut used_token_count = 0;
1080
1081 let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
1082
1083 loop {
1089 if codegen_aborted.is_none() {
1090 if used_token_count == 0 && work_items.is_empty() {
1091 break;
1093 }
1094
1095 while used_token_count < tokens.len() + 1
1098 && let Some((item, _)) = work_items.pop()
1099 {
1100 spawn_thin_lto_work(&cgcx, shared_emitter.clone(), coordinator_send.clone(), item);
1101 used_token_count += 1;
1102 }
1103 } else {
1104 if used_token_count == 0 {
1107 break;
1108 }
1109 }
1110
1111 tokens.truncate(used_token_count.saturating_sub(1));
1113
1114 match coordinator_receive.recv().unwrap() {
1115 ThinLtoMessage::Token(token) => match token {
1119 Ok(token) => {
1120 tokens.push(token);
1121 }
1122 Err(e) => {
1123 let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1124 shared_emitter.fatal(msg);
1125 codegen_aborted = Some(FatalError);
1126 }
1127 },
1128
1129 ThinLtoMessage::WorkItem { result } => {
1130 used_token_count -= 1;
1136
1137 match result {
1138 Ok(compiled_module) => compiled_modules.push(compiled_module),
1139 Err(Some(WorkerFatalError)) => {
1140 codegen_aborted = Some(FatalError);
1142 }
1143 Err(None) => {
1144 ::rustc_middle::util::bug::bug_fmt(format_args!("worker thread panicked"));bug!("worker thread panicked");
1147 }
1148 }
1149 }
1150 }
1151 }
1152
1153 if let Some(codegen_aborted) = codegen_aborted {
1154 codegen_aborted.raise();
1155 }
1156
1157 compiled_modules
1158}
1159
1160fn execute_thin_lto_work_item<B: ExtraBackendMethods>(
1161 cgcx: &CodegenContext<B>,
1162 shared_emitter: SharedEmitter,
1163 module: lto::ThinModule<B>,
1164) -> CompiledModule {
1165 let _timer = cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", module.name());
1166
1167 let module = B::optimize_thin(cgcx, &shared_emitter, module);
1168 B::codegen(cgcx, &shared_emitter, module, &cgcx.module_config)
1169}
1170
1171pub(crate) enum Message<B: WriteBackendMethods> {
1173 Token(io::Result<Acquired>),
1176
1177 WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>> },
1180
1181 CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
1185
1186 AddImportOnlyModule {
1189 module_data: SerializedModule<B::ModuleBuffer>,
1190 work_product: WorkProduct,
1191 },
1192
1193 CodegenComplete,
1196
1197 CodegenAborted,
1200}
1201
1202pub(crate) enum ThinLtoMessage {
1204 Token(io::Result<Acquired>),
1207
1208 WorkItem { result: Result<CompiledModule, Option<WorkerFatalError>> },
1211}
1212
1213pub struct CguMessage;
1216
1217struct Diagnostic {
1227 span: Vec<SpanData>,
1228 level: Level,
1229 messages: Vec<(DiagMessage, Style)>,
1230 code: Option<ErrCode>,
1231 children: Vec<Subdiagnostic>,
1232 args: DiagArgMap,
1233}
1234
1235struct Subdiagnostic {
1239 level: Level,
1240 messages: Vec<(DiagMessage, Style)>,
1241}
1242
1243#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for MainThreadState {
#[inline]
fn eq(&self, other: &MainThreadState) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::clone::Clone for MainThreadState {
#[inline]
fn clone(&self) -> MainThreadState { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for MainThreadState { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for MainThreadState {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
MainThreadState::Idle => "Idle",
MainThreadState::Codegenning => "Codegenning",
MainThreadState::Lending => "Lending",
})
}
}Debug)]
1244enum MainThreadState {
1245 Idle,
1247
1248 Codegenning,
1250
1251 Lending,
1253}
1254
1255fn start_executing_work<B: ExtraBackendMethods>(
1256 backend: B,
1257 tcx: TyCtxt<'_>,
1258 crate_info: &CrateInfo,
1259 shared_emitter: SharedEmitter,
1260 codegen_worker_send: Sender<CguMessage>,
1261 coordinator_receive: Receiver<Message<B>>,
1262 regular_config: Arc<ModuleConfig>,
1263 allocator_config: Arc<ModuleConfig>,
1264 mut allocator_module: Option<ModuleCodegen<B::Module>>,
1265 coordinator_send: Sender<Message<B>>,
1266) -> thread::JoinHandle<Result<MaybeLtoModules<B>, ()>> {
1267 let sess = tcx.sess;
1268
1269 let mut each_linked_rlib_for_lto = Vec::new();
1270 let mut each_linked_rlib_file_for_lto = Vec::new();
1271 drop(link::each_linked_rlib(crate_info, None, &mut |cnum, path| {
1272 if link::ignored_for_lto(sess, crate_info, cnum) {
1273 return;
1274 }
1275 each_linked_rlib_for_lto.push(cnum);
1276 each_linked_rlib_file_for_lto.push(path.to_path_buf());
1277 }));
1278
1279 let exported_symbols_for_lto =
1281 Arc::new(lto::exported_symbols_for_lto(tcx, &each_linked_rlib_for_lto));
1282
1283 let coordinator_send2 = coordinator_send.clone();
1289 let helper = jobserver::client()
1290 .into_helper_thread(move |token| {
1291 drop(coordinator_send2.send(Message::Token::<B>(token)));
1292 })
1293 .expect("failed to spawn helper thread");
1294
1295 let ol = tcx.backend_optimization_level(());
1296 let backend_features = tcx.global_backend_features(());
1297
1298 let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1299 let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1300 match result {
1301 Ok(dir) => Some(dir),
1302 Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1303 }
1304 } else {
1305 None
1306 };
1307
1308 let cgcx = CodegenContext::<B> {
1309 crate_types: tcx.crate_types().to_vec(),
1310 lto: sess.lto(),
1311 use_linker_plugin_lto: sess.opts.cg.linker_plugin_lto.enabled(),
1312 dylib_lto: sess.opts.unstable_opts.dylib_lto,
1313 prefer_dynamic: sess.opts.cg.prefer_dynamic,
1314 fewer_names: sess.fewer_names(),
1315 save_temps: sess.opts.cg.save_temps,
1316 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1317 prof: sess.prof.clone(),
1318 remark: sess.opts.cg.remark.clone(),
1319 remark_dir,
1320 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1321 output_filenames: Arc::clone(tcx.output_filenames(())),
1322 module_config: regular_config,
1323 tm_factory: backend.target_machine_factory(tcx.sess, ol, backend_features),
1324 msvc_imps_needed: msvc_imps_needed(tcx),
1325 is_pe_coff: tcx.sess.target.is_like_windows,
1326 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1327 target_arch: tcx.sess.target.arch.to_string(),
1328 target_is_like_darwin: tcx.sess.target.is_like_darwin,
1329 target_is_like_aix: tcx.sess.target.is_like_aix,
1330 target_is_like_gpu: tcx.sess.target.is_like_gpu,
1331 split_debuginfo: tcx.sess.split_debuginfo(),
1332 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1333 parallel: backend.supports_parallel() && !sess.opts.unstable_opts.no_parallel_backend,
1334 pointer_size: tcx.data_layout.pointer_size(),
1335 invocation_temp: sess.invocation_temp.clone(),
1336 };
1337
1338 return B::spawn_named_thread(cgcx.time_trace, "coordinator".to_string(), move || {
1474 let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
1477 let mut needs_fat_lto = Vec::new();
1478 let mut needs_thin_lto = Vec::new();
1479 let mut lto_import_only_modules = Vec::new();
1480
1481 #[derive(#[automatically_derived]
impl ::core::fmt::Debug for CodegenState {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
CodegenState::Ongoing => "Ongoing",
CodegenState::Completed => "Completed",
CodegenState::Aborted => "Aborted",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for CodegenState {
#[inline]
fn eq(&self, other: &CodegenState) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
1486 enum CodegenState {
1487 Ongoing,
1488 Completed,
1489 Aborted,
1490 }
1491 use CodegenState::*;
1492 let mut codegen_state = Ongoing;
1493
1494 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1496
1497 let mut tokens = Vec::new();
1500
1501 let mut main_thread_state = MainThreadState::Idle;
1502
1503 let mut running_with_own_token = 0;
1506
1507 let running_with_any_token = |main_thread_state, running_with_own_token| {
1510 running_with_own_token
1511 + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1512 };
1513
1514 let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
1515
1516 if let Some(allocator_module) = &mut allocator_module {
1517 B::optimize(&cgcx, &shared_emitter, allocator_module, &allocator_config);
1518 }
1519
1520 loop {
1526 if codegen_state == Ongoing {
1530 if main_thread_state == MainThreadState::Idle {
1531 let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1539 let additional_running = std::cmp::min(extra_tokens, work_items.len());
1540 let anticipated_running = running_with_own_token + additional_running + 1;
1541
1542 if !queue_full_enough(work_items.len(), anticipated_running) {
1543 if codegen_worker_send.send(CguMessage).is_err() {
1545 {
::core::panicking::panic_fmt(format_args!("Could not send CguMessage to main thread"));
}panic!("Could not send CguMessage to main thread")
1546 }
1547 main_thread_state = MainThreadState::Codegenning;
1548 } else {
1549 let (item, _) =
1553 work_items.pop().expect("queue empty - queue_full_enough() broken?");
1554 main_thread_state = MainThreadState::Lending;
1555 spawn_work(
1556 &cgcx,
1557 shared_emitter.clone(),
1558 coordinator_send.clone(),
1559 &mut llvm_start_time,
1560 item,
1561 );
1562 }
1563 }
1564 } else if codegen_state == Completed {
1565 if running_with_any_token(main_thread_state, running_with_own_token) == 0
1566 && work_items.is_empty()
1567 {
1568 break;
1570 }
1571
1572 match main_thread_state {
1576 MainThreadState::Idle => {
1577 if let Some((item, _)) = work_items.pop() {
1578 main_thread_state = MainThreadState::Lending;
1579 spawn_work(
1580 &cgcx,
1581 shared_emitter.clone(),
1582 coordinator_send.clone(),
1583 &mut llvm_start_time,
1584 item,
1585 );
1586 } else {
1587 if !(running_with_own_token > 0) {
::core::panicking::panic("assertion failed: running_with_own_token > 0")
};assert!(running_with_own_token > 0);
1594 running_with_own_token -= 1;
1595 main_thread_state = MainThreadState::Lending;
1596 }
1597 }
1598 MainThreadState::Codegenning => ::rustc_middle::util::bug::bug_fmt(format_args!("codegen worker should not be codegenning after codegen was already completed"))bug!(
1599 "codegen worker should not be codegenning after \
1600 codegen was already completed"
1601 ),
1602 MainThreadState::Lending => {
1603 }
1605 }
1606 } else {
1607 if !(codegen_state == Aborted) {
::core::panicking::panic("assertion failed: codegen_state == Aborted")
};assert!(codegen_state == Aborted);
1610 if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1611 break;
1612 }
1613 }
1614
1615 if codegen_state != Aborted {
1618 while running_with_own_token < tokens.len()
1619 && let Some((item, _)) = work_items.pop()
1620 {
1621 spawn_work(
1622 &cgcx,
1623 shared_emitter.clone(),
1624 coordinator_send.clone(),
1625 &mut llvm_start_time,
1626 item,
1627 );
1628 running_with_own_token += 1;
1629 }
1630 }
1631
1632 tokens.truncate(running_with_own_token);
1634
1635 match coordinator_receive.recv().unwrap() {
1636 Message::Token(token) => {
1640 match token {
1641 Ok(token) => {
1642 tokens.push(token);
1643
1644 if main_thread_state == MainThreadState::Lending {
1645 main_thread_state = MainThreadState::Idle;
1650 running_with_own_token += 1;
1651 }
1652 }
1653 Err(e) => {
1654 let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1655 shared_emitter.fatal(msg);
1656 codegen_state = Aborted;
1657 }
1658 }
1659 }
1660
1661 Message::CodegenDone { llvm_work_item, cost } => {
1662 let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1671 let insertion_index = match insertion_index {
1672 Ok(idx) | Err(idx) => idx,
1673 };
1674 work_items.insert(insertion_index, (llvm_work_item, cost));
1675
1676 if cgcx.parallel {
1677 helper.request_token();
1678 }
1679 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);
1680 main_thread_state = MainThreadState::Idle;
1681 }
1682
1683 Message::CodegenComplete => {
1684 if codegen_state != Aborted {
1685 codegen_state = Completed;
1686 }
1687 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);
1688 main_thread_state = MainThreadState::Idle;
1689 }
1690
1691 Message::CodegenAborted => {
1699 codegen_state = Aborted;
1700 }
1701
1702 Message::WorkItem { result } => {
1703 if main_thread_state == MainThreadState::Lending {
1709 main_thread_state = MainThreadState::Idle;
1710 } else {
1711 running_with_own_token -= 1;
1712 }
1713
1714 match result {
1715 Ok(WorkItemResult::Finished(compiled_module)) => {
1716 compiled_modules.push(compiled_module);
1717 }
1718 Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1719 if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
1720 needs_fat_lto.push(fat_lto_input);
1721 }
1722 Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1723 if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
1724 needs_thin_lto.push((name, thin_buffer));
1725 }
1726 Err(Some(WorkerFatalError)) => {
1727 codegen_state = Aborted;
1729 }
1730 Err(None) => {
1731 ::rustc_middle::util::bug::bug_fmt(format_args!("worker thread panicked"));bug!("worker thread panicked");
1734 }
1735 }
1736 }
1737
1738 Message::AddImportOnlyModule { module_data, work_product } => {
1739 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);
1740 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);
1741 lto_import_only_modules.push((module_data, work_product));
1742 main_thread_state = MainThreadState::Idle;
1743 }
1744 }
1745 }
1746
1747 drop(llvm_start_time);
1749
1750 if codegen_state == Aborted {
1751 return Err(());
1752 }
1753
1754 drop(codegen_state);
1755 drop(tokens);
1756 drop(helper);
1757 if !work_items.is_empty() {
::core::panicking::panic("assertion failed: work_items.is_empty()")
};assert!(work_items.is_empty());
1758
1759 if !needs_fat_lto.is_empty() {
1760 if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1761 if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
1762
1763 if let Some(allocator_module) = allocator_module.take() {
1764 needs_fat_lto.push(FatLtoInput::InMemory(allocator_module));
1765 }
1766
1767 return Ok(MaybeLtoModules::FatLto {
1768 cgcx,
1769 exported_symbols_for_lto,
1770 each_linked_rlib_file_for_lto,
1771 needs_fat_lto,
1772 lto_import_only_modules,
1773 });
1774 } else if !needs_thin_lto.is_empty() || !lto_import_only_modules.is_empty() {
1775 if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1776 if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
1777
1778 if cgcx.lto == Lto::ThinLocal {
1779 compiled_modules.extend(do_thin_lto(
1780 &cgcx,
1781 shared_emitter.clone(),
1782 exported_symbols_for_lto,
1783 each_linked_rlib_file_for_lto,
1784 needs_thin_lto,
1785 lto_import_only_modules,
1786 ));
1787 } else {
1788 if let Some(allocator_module) = allocator_module.take() {
1789 let (name, thin_buffer) = B::prepare_thin(allocator_module);
1790 needs_thin_lto.push((name, thin_buffer));
1791 }
1792
1793 return Ok(MaybeLtoModules::ThinLto {
1794 cgcx,
1795 exported_symbols_for_lto,
1796 each_linked_rlib_file_for_lto,
1797 needs_thin_lto,
1798 lto_import_only_modules,
1799 });
1800 }
1801 }
1802
1803 Ok(MaybeLtoModules::NoLto {
1804 modules: compiled_modules,
1805 allocator_module: allocator_module.map(|allocator_module| {
1806 B::codegen(&cgcx, &shared_emitter, allocator_module, &allocator_config)
1807 }),
1808 })
1809 })
1810 .expect("failed to spawn coordinator thread");
1811
1812 fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1815 let quarter_of_workers = workers_running - 3 * workers_running / 4;
1866 items_in_queue > 0 && items_in_queue >= quarter_of_workers
1867 }
1868}
1869
1870#[must_use]
1872pub(crate) struct WorkerFatalError;
1873
1874fn spawn_work<'a, B: ExtraBackendMethods>(
1875 cgcx: &'a CodegenContext<B>,
1876 shared_emitter: SharedEmitter,
1877 coordinator_send: Sender<Message<B>>,
1878 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1879 work: WorkItem<B>,
1880) {
1881 if llvm_start_time.is_none() {
1882 *llvm_start_time = Some(cgcx.prof.verbose_generic_activity("LLVM_passes"));
1883 }
1884
1885 let cgcx = cgcx.clone();
1886
1887 B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1888 let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1889 WorkItem::Optimize(m) => execute_optimize_work_item(&cgcx, shared_emitter, m),
1890 WorkItem::CopyPostLtoArtifacts(m) => WorkItemResult::Finished(
1891 execute_copy_from_cache_work_item(&cgcx, shared_emitter, m),
1892 ),
1893 }));
1894
1895 let msg = match result {
1896 Ok(result) => Message::WorkItem::<B> { result: Ok(result) },
1897
1898 Err(err) if err.is::<FatalErrorMarker>() => {
1902 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1903 }
1904
1905 Err(_) => Message::WorkItem::<B> { result: Err(None) },
1906 };
1907 drop(coordinator_send.send(msg));
1908 })
1909 .expect("failed to spawn work thread");
1910}
1911
1912fn spawn_thin_lto_work<'a, B: ExtraBackendMethods>(
1913 cgcx: &'a CodegenContext<B>,
1914 shared_emitter: SharedEmitter,
1915 coordinator_send: Sender<ThinLtoMessage>,
1916 work: ThinLtoWorkItem<B>,
1917) {
1918 let cgcx = cgcx.clone();
1919
1920 B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1921 let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1922 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
1923 execute_copy_from_cache_work_item(&cgcx, shared_emitter, m)
1924 }
1925 ThinLtoWorkItem::ThinLto(m) => execute_thin_lto_work_item(&cgcx, shared_emitter, m),
1926 }));
1927
1928 let msg = match result {
1929 Ok(result) => ThinLtoMessage::WorkItem { result: Ok(result) },
1930
1931 Err(err) if err.is::<FatalErrorMarker>() => {
1935 ThinLtoMessage::WorkItem { result: Err(Some(WorkerFatalError)) }
1936 }
1937
1938 Err(_) => ThinLtoMessage::WorkItem { result: Err(None) },
1939 };
1940 drop(coordinator_send.send(msg));
1941 })
1942 .expect("failed to spawn work thread");
1943}
1944
1945enum SharedEmitterMessage {
1946 Diagnostic(Diagnostic),
1947 InlineAsmError(InlineAsmError),
1948 Fatal(String),
1949}
1950
1951pub struct InlineAsmError {
1952 pub span: SpanData,
1953 pub msg: String,
1954 pub level: Level,
1955 pub source: Option<(String, Vec<InnerSpan>)>,
1956}
1957
1958#[derive(#[automatically_derived]
impl ::core::clone::Clone for SharedEmitter {
#[inline]
fn clone(&self) -> SharedEmitter {
SharedEmitter { sender: ::core::clone::Clone::clone(&self.sender) }
}
}Clone)]
1959pub struct SharedEmitter {
1960 sender: Sender<SharedEmitterMessage>,
1961}
1962
1963pub struct SharedEmitterMain {
1964 receiver: Receiver<SharedEmitterMessage>,
1965}
1966
1967impl SharedEmitter {
1968 fn new() -> (SharedEmitter, SharedEmitterMain) {
1969 let (sender, receiver) = channel();
1970
1971 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1972 }
1973
1974 pub fn inline_asm_error(&self, err: InlineAsmError) {
1975 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(err)));
1976 }
1977
1978 fn fatal(&self, msg: &str) {
1979 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1980 }
1981}
1982
1983impl Emitter for SharedEmitter {
1984 fn emit_diagnostic(
1985 &mut self,
1986 mut diag: rustc_errors::DiagInner,
1987 _registry: &rustc_errors::registry::Registry,
1988 ) {
1989 if !!diag.span.has_span_labels() {
::core::panicking::panic("assertion failed: !diag.span.has_span_labels()")
};assert!(!diag.span.has_span_labels());
1992 match (&diag.suggestions, &Suggestions::Enabled(::alloc::vec::Vec::new())) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(diag.suggestions, Suggestions::Enabled(vec![]));
1993 match (&diag.sort_span, &rustc_span::DUMMY_SP) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(diag.sort_span, rustc_span::DUMMY_SP);
1994 match (&diag.is_lint, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(diag.is_lint, None);
1995 let args = mem::replace(&mut diag.args, DiagArgMap::default());
1998 drop(
1999 self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
2000 span: diag.span.primary_spans().iter().map(|span| span.data()).collect::<Vec<_>>(),
2001 level: diag.level(),
2002 messages: diag.messages,
2003 code: diag.code,
2004 children: diag
2005 .children
2006 .into_iter()
2007 .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
2008 .collect(),
2009 args,
2010 })),
2011 );
2012 }
2013
2014 fn source_map(&self) -> Option<&SourceMap> {
2015 None
2016 }
2017
2018 fn translator(&self) -> &Translator {
2019 {
::core::panicking::panic_fmt(format_args!("shared emitter attempted to translate a diagnostic"));
};panic!("shared emitter attempted to translate a diagnostic");
2020 }
2021}
2022
2023impl SharedEmitterMain {
2024 fn check(&self, sess: &Session, blocking: bool) {
2025 loop {
2026 let message = if blocking {
2027 match self.receiver.recv() {
2028 Ok(message) => Ok(message),
2029 Err(_) => Err(()),
2030 }
2031 } else {
2032 match self.receiver.try_recv() {
2033 Ok(message) => Ok(message),
2034 Err(_) => Err(()),
2035 }
2036 };
2037
2038 match message {
2039 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2040 let dcx = sess.dcx();
2043 let mut d =
2044 rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
2045 d.span = MultiSpan::from_spans(
2046 diag.span.into_iter().map(|span| span.span()).collect(),
2047 );
2048 d.code = diag.code; d.children = diag
2050 .children
2051 .into_iter()
2052 .map(|sub| rustc_errors::Subdiag {
2053 level: sub.level,
2054 messages: sub.messages,
2055 span: MultiSpan::new(),
2056 })
2057 .collect();
2058 d.args = diag.args;
2059 dcx.emit_diagnostic(d);
2060 sess.dcx().abort_if_errors();
2061 }
2062 Ok(SharedEmitterMessage::InlineAsmError(inner)) => {
2063 match inner.level {
Level::Error | Level::Warning | Level::Note => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"Level::Error | Level::Warning | Level::Note",
::core::option::Option::None);
}
};assert_matches!(inner.level, Level::Error | Level::Warning | Level::Note);
2064 let mut err = Diag::<()>::new(sess.dcx(), inner.level, inner.msg);
2065 if !inner.span.is_dummy() {
2066 err.span(inner.span.span());
2067 }
2068
2069 if let Some((buffer, spans)) = inner.source {
2071 let source = sess
2072 .source_map()
2073 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
2074 let spans: Vec<_> = spans
2075 .iter()
2076 .map(|sp| {
2077 Span::with_root_ctxt(
2078 source.normalized_byte_pos(sp.start as u32),
2079 source.normalized_byte_pos(sp.end as u32),
2080 )
2081 })
2082 .collect();
2083 err.span_note(spans, "instantiated into assembly here");
2084 }
2085
2086 err.emit();
2087 }
2088 Ok(SharedEmitterMessage::Fatal(msg)) => {
2089 sess.dcx().fatal(msg);
2090 }
2091 Err(_) => {
2092 break;
2093 }
2094 }
2095 }
2096 }
2097}
2098
2099pub struct Coordinator<B: ExtraBackendMethods> {
2100 sender: Sender<Message<B>>,
2101 future: Option<thread::JoinHandle<Result<MaybeLtoModules<B>, ()>>>,
2102 phantom: PhantomData<B>,
2104}
2105
2106impl<B: ExtraBackendMethods> Coordinator<B> {
2107 fn join(mut self) -> std::thread::Result<Result<MaybeLtoModules<B>, ()>> {
2108 self.future.take().unwrap().join()
2109 }
2110}
2111
2112impl<B: ExtraBackendMethods> Drop for Coordinator<B> {
2113 fn drop(&mut self) {
2114 if let Some(future) = self.future.take() {
2115 drop(self.sender.send(Message::CodegenAborted::<B>));
2118 drop(future.join());
2119 }
2120 }
2121}
2122
2123pub struct OngoingCodegen<B: ExtraBackendMethods> {
2124 pub backend: B,
2125 pub crate_info: CrateInfo,
2126 pub output_filenames: Arc<OutputFilenames>,
2127 pub coordinator: Coordinator<B>,
2131 pub codegen_worker_receive: Receiver<CguMessage>,
2132 pub shared_emitter_main: SharedEmitterMain,
2133}
2134
2135impl<B: ExtraBackendMethods> OngoingCodegen<B> {
2136 pub fn join(self, sess: &Session) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
2137 self.shared_emitter_main.check(sess, true);
2138
2139 let maybe_lto_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
2140 Ok(Ok(maybe_lto_modules)) => maybe_lto_modules,
2141 Ok(Err(())) => {
2142 sess.dcx().abort_if_errors();
2143 {
::core::panicking::panic_fmt(format_args!("expected abort due to worker thread errors"));
}panic!("expected abort due to worker thread errors")
2144 }
2145 Err(_) => {
2146 ::rustc_middle::util::bug::bug_fmt(format_args!("panic during codegen/LLVM phase"));bug!("panic during codegen/LLVM phase");
2147 }
2148 });
2149
2150 sess.dcx().abort_if_errors();
2151
2152 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
2153
2154 let compiled_modules = catch_fatal_errors(|| match maybe_lto_modules {
2156 MaybeLtoModules::NoLto { modules, allocator_module } => {
2157 drop(shared_emitter);
2158 CompiledModules { modules, allocator_module }
2159 }
2160 MaybeLtoModules::FatLto {
2161 cgcx,
2162 exported_symbols_for_lto,
2163 each_linked_rlib_file_for_lto,
2164 needs_fat_lto,
2165 lto_import_only_modules,
2166 } => CompiledModules {
2167 modules: <[_]>::into_vec(::alloc::boxed::box_new([do_fat_lto(&cgcx, shared_emitter,
&exported_symbols_for_lto, &each_linked_rlib_file_for_lto,
needs_fat_lto, lto_import_only_modules)]))vec![do_fat_lto(
2168 &cgcx,
2169 shared_emitter,
2170 &exported_symbols_for_lto,
2171 &each_linked_rlib_file_for_lto,
2172 needs_fat_lto,
2173 lto_import_only_modules,
2174 )],
2175 allocator_module: None,
2176 },
2177 MaybeLtoModules::ThinLto {
2178 cgcx,
2179 exported_symbols_for_lto,
2180 each_linked_rlib_file_for_lto,
2181 needs_thin_lto,
2182 lto_import_only_modules,
2183 } => CompiledModules {
2184 modules: do_thin_lto(
2185 &cgcx,
2186 shared_emitter,
2187 exported_symbols_for_lto,
2188 each_linked_rlib_file_for_lto,
2189 needs_thin_lto,
2190 lto_import_only_modules,
2191 ),
2192 allocator_module: None,
2193 },
2194 });
2195
2196 shared_emitter_main.check(sess, true);
2197
2198 sess.dcx().abort_if_errors();
2199
2200 let mut compiled_modules =
2201 compiled_modules.expect("fatal error emitted but not sent to SharedEmitter");
2202
2203 compiled_modules.modules.sort_by(|a, b| a.name.cmp(&b.name));
2207
2208 let work_products =
2209 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
2210 produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
2211
2212 if sess.codegen_units().as_usize() == 1 && sess.opts.unstable_opts.time_llvm_passes {
2215 self.backend.print_pass_timings()
2216 }
2217
2218 if sess.print_llvm_stats() {
2219 self.backend.print_statistics()
2220 }
2221
2222 (
2223 CodegenResults {
2224 crate_info: self.crate_info,
2225
2226 modules: compiled_modules.modules,
2227 allocator_module: compiled_modules.allocator_module,
2228 },
2229 work_products,
2230 )
2231 }
2232
2233 pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2234 self.wait_for_signal_to_codegen_item();
2235 self.check_for_errors(tcx.sess);
2236 drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
2237 }
2238
2239 pub(crate) fn check_for_errors(&self, sess: &Session) {
2240 self.shared_emitter_main.check(sess, false);
2241 }
2242
2243 pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2244 match self.codegen_worker_receive.recv() {
2245 Ok(CguMessage) => {
2246 }
2248 Err(_) => {
2249 }
2252 }
2253 }
2254}
2255
2256pub(crate) fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
2257 coordinator: &Coordinator<B>,
2258 module: ModuleCodegen<B::Module>,
2259 cost: u64,
2260) {
2261 let llvm_work_item = WorkItem::Optimize(module);
2262 drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2263}
2264
2265pub(crate) fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
2266 coordinator: &Coordinator<B>,
2267 module: CachedModuleCodegen,
2268) {
2269 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2270 drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2271}
2272
2273pub(crate) fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
2274 tcx: TyCtxt<'_>,
2275 coordinator: &Coordinator<B>,
2276 module: CachedModuleCodegen,
2277) {
2278 let filename = pre_lto_bitcode_filename(&module.name);
2279 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2280 let file = fs::File::open(&bc_path)
2281 .unwrap_or_else(|e| {
::core::panicking::panic_fmt(format_args!("failed to open bitcode file `{0}`: {1}",
bc_path.display(), e));
}panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
2282
2283 let mmap = unsafe {
2284 Mmap::map(file).unwrap_or_else(|e| {
2285 {
::core::panicking::panic_fmt(format_args!("failed to mmap bitcode file `{0}`: {1}",
bc_path.display(), e));
}panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2286 })
2287 };
2288 drop(coordinator.sender.send(Message::AddImportOnlyModule::<B> {
2290 module_data: SerializedModule::FromUncompressedFile(mmap),
2291 work_product: module.source,
2292 }));
2293}
2294
2295fn pre_lto_bitcode_filename(module_name: &str) -> String {
2296 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.{1}", module_name,
PRE_LTO_BC_EXT))
})format!("{module_name}.{PRE_LTO_BC_EXT}")
2297}
2298
2299fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2300 if !!(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!(
2303 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2304 && tcx.sess.target.is_like_windows
2305 && tcx.sess.opts.cg.prefer_dynamic)
2306 );
2307
2308 let can_have_static_objects =
2312 tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
2313
2314 tcx.sess.target.is_like_windows &&
2315 can_have_static_objects &&
2316 !tcx.sess.opts.cg.linker_plugin_lto.enabled()
2320}