1use std::assert_matches::assert_matches;
2use std::marker::PhantomData;
3use std::panic::AssertUnwindSafe;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use std::sync::mpsc::{Receiver, Sender, channel};
7use std::{fs, io, mem, str, thread};
8
9use rustc_abi::Size;
10use rustc_ast::attr;
11use rustc_data_structures::fx::FxIndexMap;
12use rustc_data_structures::jobserver::{self, Acquired};
13use rustc_data_structures::memmap::Mmap;
14use rustc_data_structures::profiling::{SelfProfilerRef, VerboseTimingGuard};
15use rustc_errors::emitter::Emitter;
16use rustc_errors::translation::Translator;
17use rustc_errors::{
18 Diag, DiagArgMap, DiagCtxt, DiagMessage, ErrCode, FatalError, FatalErrorMarker, Level,
19 MultiSpan, Style, Suggestions,
20};
21use rustc_fs_util::link_or_copy;
22use rustc_incremental::{
23 copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess,
24};
25use rustc_metadata::fs::copy_to_stdout;
26use rustc_middle::bug;
27use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
28use rustc_middle::ty::TyCtxt;
29use rustc_session::Session;
30use rustc_session::config::{
31 self, CrateType, Lto, OutFileName, OutputFilenames, OutputType, Passes, SwitchWithOptPath,
32};
33use rustc_span::source_map::SourceMap;
34use rustc_span::{FileName, InnerSpan, Span, SpanData, sym};
35use rustc_target::spec::{MergeFunctions, SanitizerSet};
36use tracing::debug;
37
38use super::link::{self, ensure_removed};
39use super::lto::{self, SerializedModule};
40use crate::back::lto::check_lto_allowed;
41use crate::errors::ErrorCreatingRemarkDir;
42use crate::traits::*;
43use crate::{
44 CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
45 errors,
46};
47
48const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
49
50#[derive(Clone, Copy, PartialEq)]
52pub enum EmitObj {
53 None,
55
56 Bitcode,
59
60 ObjectCode(BitcodeSection),
62}
63
64#[derive(Clone, Copy, PartialEq)]
66pub enum BitcodeSection {
67 None,
69
70 Full,
72}
73
74pub struct ModuleConfig {
76 pub passes: Vec<String>,
78 pub opt_level: Option<config::OptLevel>,
81
82 pub pgo_gen: SwitchWithOptPath,
83 pub pgo_use: Option<PathBuf>,
84 pub pgo_sample_use: Option<PathBuf>,
85 pub debug_info_for_profiling: bool,
86 pub instrument_coverage: bool,
87
88 pub sanitizer: SanitizerSet,
89 pub sanitizer_recover: SanitizerSet,
90 pub sanitizer_dataflow_abilist: Vec<String>,
91 pub sanitizer_memory_track_origins: usize,
92
93 pub emit_pre_lto_bc: bool,
95 pub emit_no_opt_bc: bool,
96 pub emit_bc: bool,
97 pub emit_ir: bool,
98 pub emit_asm: bool,
99 pub emit_obj: EmitObj,
100 pub emit_thin_lto: bool,
101 pub emit_thin_lto_summary: bool,
102
103 pub verify_llvm_ir: bool,
106 pub lint_llvm_ir: bool,
107 pub no_prepopulate_passes: bool,
108 pub no_builtins: bool,
109 pub vectorize_loop: bool,
110 pub vectorize_slp: bool,
111 pub merge_functions: bool,
112 pub emit_lifetime_markers: bool,
113 pub llvm_plugins: Vec<String>,
114 pub autodiff: Vec<config::AutoDiff>,
115 pub offload: Vec<config::Offload>,
116}
117
118impl ModuleConfig {
119 fn new(kind: ModuleKind, tcx: TyCtxt<'_>, no_builtins: bool) -> ModuleConfig {
120 macro_rules! if_regular {
123 ($regular: expr, $other: expr) => {
124 if let ModuleKind::Regular = kind { $regular } else { $other }
125 };
126 }
127
128 let sess = tcx.sess;
129 let opt_level_and_size = if_regular!(Some(sess.opts.optimize), None);
130
131 let save_temps = sess.opts.cg.save_temps;
132
133 let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
134 || match kind {
135 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
136 ModuleKind::Allocator => false,
137 };
138
139 let emit_obj = if !should_emit_obj {
140 EmitObj::None
141 } else if sess.target.obj_is_bitcode
142 || (sess.opts.cg.linker_plugin_lto.enabled() && !no_builtins)
143 {
144 EmitObj::Bitcode
159 } else if need_bitcode_in_object(tcx) {
160 EmitObj::ObjectCode(BitcodeSection::Full)
161 } else {
162 EmitObj::ObjectCode(BitcodeSection::None)
163 };
164
165 ModuleConfig {
166 passes: if_regular!(sess.opts.cg.passes.clone(), vec![]),
167
168 opt_level: opt_level_and_size,
169
170 pgo_gen: if_regular!(
171 sess.opts.cg.profile_generate.clone(),
172 SwitchWithOptPath::Disabled
173 ),
174 pgo_use: if_regular!(sess.opts.cg.profile_use.clone(), None),
175 pgo_sample_use: if_regular!(sess.opts.unstable_opts.profile_sample_use.clone(), None),
176 debug_info_for_profiling: sess.opts.unstable_opts.debug_info_for_profiling,
177 instrument_coverage: if_regular!(sess.instrument_coverage(), false),
178
179 sanitizer: if_regular!(sess.opts.unstable_opts.sanitizer, SanitizerSet::empty()),
180 sanitizer_dataflow_abilist: if_regular!(
181 sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
182 Vec::new()
183 ),
184 sanitizer_recover: if_regular!(
185 sess.opts.unstable_opts.sanitizer_recover,
186 SanitizerSet::empty()
187 ),
188 sanitizer_memory_track_origins: if_regular!(
189 sess.opts.unstable_opts.sanitizer_memory_track_origins,
190 0
191 ),
192
193 emit_pre_lto_bc: if_regular!(
194 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
195 false
196 ),
197 emit_no_opt_bc: if_regular!(save_temps, false),
198 emit_bc: if_regular!(
199 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
200 save_temps
201 ),
202 emit_ir: if_regular!(
203 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
204 false
205 ),
206 emit_asm: if_regular!(
207 sess.opts.output_types.contains_key(&OutputType::Assembly),
208 false
209 ),
210 emit_obj,
211 emit_thin_lto: sess.opts.unstable_opts.emit_thin_lto && sess.lto() != Lto::Fat,
214 emit_thin_lto_summary: if_regular!(
215 sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode),
216 false
217 ),
218
219 verify_llvm_ir: sess.verify_llvm_ir(),
220 lint_llvm_ir: sess.opts.unstable_opts.lint_llvm_ir,
221 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
222 no_builtins: no_builtins || sess.target.no_builtins,
223
224 vectorize_loop: !sess.opts.cg.no_vectorize_loops
227 && (sess.opts.optimize == config::OptLevel::More
228 || sess.opts.optimize == config::OptLevel::Aggressive),
229 vectorize_slp: !sess.opts.cg.no_vectorize_slp
230 && sess.opts.optimize == config::OptLevel::Aggressive,
231
232 merge_functions: match sess
242 .opts
243 .unstable_opts
244 .merge_functions
245 .unwrap_or(sess.target.merge_functions)
246 {
247 MergeFunctions::Disabled => false,
248 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
249 use config::OptLevel::*;
250 match sess.opts.optimize {
251 Aggressive | More | SizeMin | Size => true,
252 Less | No => false,
253 }
254 }
255 },
256
257 emit_lifetime_markers: sess.emit_lifetime_markers(),
258 llvm_plugins: if_regular!(sess.opts.unstable_opts.llvm_plugins.clone(), vec![]),
259 autodiff: if_regular!(sess.opts.unstable_opts.autodiff.clone(), vec![]),
260 offload: if_regular!(sess.opts.unstable_opts.offload.clone(), vec![]),
261 }
262 }
263
264 pub fn bitcode_needed(&self) -> bool {
265 self.emit_bc
266 || self.emit_thin_lto_summary
267 || self.emit_obj == EmitObj::Bitcode
268 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
269 }
270
271 pub fn embed_bitcode(&self) -> bool {
272 self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
273 }
274}
275
276pub struct TargetMachineFactoryConfig {
278 pub split_dwarf_file: Option<PathBuf>,
282
283 pub output_obj_file: Option<PathBuf>,
286}
287
288impl TargetMachineFactoryConfig {
289 pub fn new(
290 cgcx: &CodegenContext<impl WriteBackendMethods>,
291 module_name: &str,
292 ) -> TargetMachineFactoryConfig {
293 let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
294 cgcx.output_filenames.split_dwarf_path(
295 cgcx.split_debuginfo,
296 cgcx.split_dwarf_kind,
297 module_name,
298 cgcx.invocation_temp.as_deref(),
299 )
300 } else {
301 None
302 };
303
304 let output_obj_file = Some(cgcx.output_filenames.temp_path_for_cgu(
305 OutputType::Object,
306 module_name,
307 cgcx.invocation_temp.as_deref(),
308 ));
309 TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }
310 }
311}
312
313pub type TargetMachineFactoryFn<B> = Arc<
314 dyn Fn(
315 TargetMachineFactoryConfig,
316 ) -> Result<
317 <B as WriteBackendMethods>::TargetMachine,
318 <B as WriteBackendMethods>::TargetMachineError,
319 > + Send
320 + Sync,
321>;
322
323#[derive(Clone)]
325pub struct CodegenContext<B: WriteBackendMethods> {
326 pub prof: SelfProfilerRef,
328 pub lto: Lto,
329 pub save_temps: bool,
330 pub fewer_names: bool,
331 pub time_trace: bool,
332 pub opts: Arc<config::Options>,
333 pub crate_types: Vec<CrateType>,
334 pub output_filenames: Arc<OutputFilenames>,
335 pub invocation_temp: Option<String>,
336 pub module_config: Arc<ModuleConfig>,
337 pub allocator_config: Arc<ModuleConfig>,
338 pub tm_factory: TargetMachineFactoryFn<B>,
339 pub msvc_imps_needed: bool,
340 pub is_pe_coff: bool,
341 pub target_can_use_split_dwarf: bool,
342 pub target_arch: String,
343 pub target_is_like_darwin: bool,
344 pub target_is_like_aix: bool,
345 pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
346 pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
347 pub pointer_size: Size,
348
349 pub diag_emitter: SharedEmitter,
351 pub remark: Passes,
353 pub remark_dir: Option<PathBuf>,
356 pub incr_comp_session_dir: Option<PathBuf>,
359 pub parallel: bool,
363}
364
365impl<B: WriteBackendMethods> CodegenContext<B> {
366 pub fn create_dcx(&self) -> DiagCtxt {
367 DiagCtxt::new(Box::new(self.diag_emitter.clone()))
368 }
369}
370
371fn generate_thin_lto_work<B: ExtraBackendMethods>(
372 cgcx: &CodegenContext<B>,
373 exported_symbols_for_lto: &[String],
374 each_linked_rlib_for_lto: &[PathBuf],
375 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
376 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
377) -> Vec<(ThinLtoWorkItem<B>, u64)> {
378 let _prof_timer = cgcx.prof.generic_activity("codegen_thin_generate_lto_work");
379
380 let (lto_modules, copy_jobs) = B::run_thin_lto(
381 cgcx,
382 exported_symbols_for_lto,
383 each_linked_rlib_for_lto,
384 needs_thin_lto,
385 import_only_modules,
386 );
387 lto_modules
388 .into_iter()
389 .map(|module| {
390 let cost = module.cost();
391 (ThinLtoWorkItem::ThinLto(module), cost)
392 })
393 .chain(copy_jobs.into_iter().map(|wp| {
394 (
395 ThinLtoWorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
396 name: wp.cgu_name.clone(),
397 source: wp,
398 }),
399 0, )
401 }))
402 .collect()
403}
404
405struct CompiledModules {
406 modules: Vec<CompiledModule>,
407 allocator_module: Option<CompiledModule>,
408}
409
410fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
411 let sess = tcx.sess;
412 sess.opts.cg.embed_bitcode
413 && tcx.crate_types().contains(&CrateType::Rlib)
414 && sess.opts.output_types.contains_key(&OutputType::Exe)
415}
416
417fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
418 if sess.opts.incremental.is_none() {
419 return false;
420 }
421
422 match sess.lto() {
423 Lto::No => false,
424 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
425 }
426}
427
428pub(crate) fn start_async_codegen<B: ExtraBackendMethods>(
429 backend: B,
430 tcx: TyCtxt<'_>,
431 target_cpu: String,
432 allocator_module: Option<ModuleCodegen<B::Module>>,
433) -> OngoingCodegen<B> {
434 let (coordinator_send, coordinator_receive) = channel();
435
436 let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
437 let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins);
438
439 let crate_info = CrateInfo::new(tcx, target_cpu);
440
441 let regular_config = ModuleConfig::new(ModuleKind::Regular, tcx, no_builtins);
442 let allocator_config = ModuleConfig::new(ModuleKind::Allocator, tcx, no_builtins);
443
444 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
445 let (codegen_worker_send, codegen_worker_receive) = channel();
446
447 let coordinator_thread = start_executing_work(
448 backend.clone(),
449 tcx,
450 &crate_info,
451 shared_emitter,
452 codegen_worker_send,
453 coordinator_receive,
454 Arc::new(regular_config),
455 Arc::new(allocator_config),
456 allocator_module,
457 coordinator_send.clone(),
458 );
459
460 OngoingCodegen {
461 backend,
462 crate_info,
463
464 codegen_worker_receive,
465 shared_emitter_main,
466 coordinator: Coordinator {
467 sender: coordinator_send,
468 future: Some(coordinator_thread),
469 phantom: PhantomData,
470 },
471 output_filenames: Arc::clone(tcx.output_filenames(())),
472 }
473}
474
475fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
476 sess: &Session,
477 compiled_modules: &CompiledModules,
478) -> FxIndexMap<WorkProductId, WorkProduct> {
479 let mut work_products = FxIndexMap::default();
480
481 if sess.opts.incremental.is_none() {
482 return work_products;
483 }
484
485 let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
486
487 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
488 let mut files = Vec::new();
489 if let Some(object_file_path) = &module.object {
490 files.push((OutputType::Object.extension(), object_file_path.as_path()));
491 }
492 if let Some(dwarf_object_file_path) = &module.dwarf_object {
493 files.push(("dwo", dwarf_object_file_path.as_path()));
494 }
495 if let Some(path) = &module.assembly {
496 files.push((OutputType::Assembly.extension(), path.as_path()));
497 }
498 if let Some(path) = &module.llvm_ir {
499 files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
500 }
501 if let Some(path) = &module.bytecode {
502 files.push((OutputType::Bitcode.extension(), path.as_path()));
503 }
504 if let Some((id, product)) = copy_cgu_workproduct_to_incr_comp_cache_dir(
505 sess,
506 &module.name,
507 files.as_slice(),
508 &module.links_from_incr_cache,
509 ) {
510 work_products.insert(id, product);
511 }
512 }
513
514 work_products
515}
516
517fn produce_final_output_artifacts(
518 sess: &Session,
519 compiled_modules: &CompiledModules,
520 crate_output: &OutputFilenames,
521) {
522 let mut user_wants_bitcode = false;
523 let mut user_wants_objects = false;
524
525 let copy_gracefully = |from: &Path, to: &OutFileName| match to {
527 OutFileName::Stdout if let Err(e) = copy_to_stdout(from) => {
528 sess.dcx().emit_err(errors::CopyPath::new(from, to.as_path(), e));
529 }
530 OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
531 sess.dcx().emit_err(errors::CopyPath::new(from, path, e));
532 }
533 _ => {}
534 };
535
536 let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
537 if let [module] = &compiled_modules.modules[..] {
538 let path = crate_output.temp_path_for_cgu(
541 output_type,
542 &module.name,
543 sess.invocation_temp.as_deref(),
544 );
545 let output = crate_output.path(output_type);
546 if !output_type.is_text_output() && output.is_tty() {
547 sess.dcx()
548 .emit_err(errors::BinaryOutputToTty { shorthand: output_type.shorthand() });
549 } else {
550 copy_gracefully(&path, &output);
551 }
552 if !sess.opts.cg.save_temps && !keep_numbered {
553 ensure_removed(sess.dcx(), &path);
555 }
556 } else {
557 if crate_output.outputs.contains_explicit_name(&output_type) {
558 sess.dcx()
561 .emit_warn(errors::IgnoringEmitPath { extension: output_type.extension() });
562 } else if crate_output.single_output_file.is_some() {
563 sess.dcx().emit_warn(errors::IgnoringOutput { extension: output_type.extension() });
566 } else {
567 }
571 }
572 };
573
574 for output_type in crate_output.outputs.keys() {
578 match *output_type {
579 OutputType::Bitcode => {
580 user_wants_bitcode = true;
581 copy_if_one_unit(OutputType::Bitcode, true);
585 }
586 OutputType::ThinLinkBitcode => {
587 copy_if_one_unit(OutputType::ThinLinkBitcode, false);
588 }
589 OutputType::LlvmAssembly => {
590 copy_if_one_unit(OutputType::LlvmAssembly, false);
591 }
592 OutputType::Assembly => {
593 copy_if_one_unit(OutputType::Assembly, false);
594 }
595 OutputType::Object => {
596 user_wants_objects = true;
597 copy_if_one_unit(OutputType::Object, true);
598 }
599 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
600 }
601 }
602
603 if !sess.opts.cg.save_temps {
616 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
632
633 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
634
635 let keep_numbered_objects =
636 needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
637
638 for module in compiled_modules.modules.iter() {
639 if !keep_numbered_objects {
640 if let Some(ref path) = module.object {
641 ensure_removed(sess.dcx(), path);
642 }
643
644 if let Some(ref path) = module.dwarf_object {
645 ensure_removed(sess.dcx(), path);
646 }
647 }
648
649 if let Some(ref path) = module.bytecode {
650 if !keep_numbered_bitcode {
651 ensure_removed(sess.dcx(), path);
652 }
653 }
654 }
655
656 if !user_wants_bitcode
657 && let Some(ref allocator_module) = compiled_modules.allocator_module
658 && let Some(ref path) = allocator_module.bytecode
659 {
660 ensure_removed(sess.dcx(), path);
661 }
662 }
663
664 if sess.opts.json_artifact_notifications {
665 if let [module] = &compiled_modules.modules[..] {
666 module.for_each_output(|_path, ty| {
667 if sess.opts.output_types.contains_key(&ty) {
668 let descr = ty.shorthand();
669 let path = crate_output.path(ty);
672 sess.dcx().emit_artifact_notification(path.as_path(), descr);
673 }
674 });
675 } else {
676 for module in &compiled_modules.modules {
677 module.for_each_output(|path, ty| {
678 if sess.opts.output_types.contains_key(&ty) {
679 let descr = ty.shorthand();
680 sess.dcx().emit_artifact_notification(&path, descr);
681 }
682 });
683 }
684 }
685 }
686
687 }
693
694pub(crate) enum WorkItem<B: WriteBackendMethods> {
695 Optimize(ModuleCodegen<B::Module>),
697 CopyPostLtoArtifacts(CachedModuleCodegen),
700}
701
702enum ThinLtoWorkItem<B: WriteBackendMethods> {
703 CopyPostLtoArtifacts(CachedModuleCodegen),
706 ThinLto(lto::ThinModule<B>),
708}
709
710#[cfg(not(windows))]
714fn desc(short: &str, _long: &str, name: &str) -> String {
715 assert_eq!(short.len(), 3);
735 let name = if let Some(index) = name.find("-cgu.") {
736 &name[index + 1..] } else {
738 name
739 };
740 format!("{short} {name}")
741}
742
743#[cfg(windows)]
745fn desc(_short: &str, long: &str, name: &str) -> String {
746 format!("{long} {name}")
747}
748
749impl<B: WriteBackendMethods> WorkItem<B> {
750 fn short_description(&self) -> String {
752 match self {
753 WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
754 WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
755 }
756 }
757}
758
759impl<B: WriteBackendMethods> ThinLtoWorkItem<B> {
760 fn short_description(&self) -> String {
762 match self {
763 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
764 desc("cpy", "copy LTO artifacts for", &m.name)
765 }
766 ThinLtoWorkItem::ThinLto(m) => desc("lto", "thin-LTO module", m.name()),
767 }
768 }
769}
770
771pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
773 Finished(CompiledModule),
775
776 NeedsFatLto(FatLtoInput<B>),
779
780 NeedsThinLto(String, B::ThinBuffer),
783}
784
785pub enum FatLtoInput<B: WriteBackendMethods> {
786 Serialized { name: String, buffer: SerializedModule<B::ModuleBuffer> },
787 InMemory(ModuleCodegen<B::Module>),
788}
789
790pub(crate) enum ComputedLtoType {
792 No,
793 Thin,
794 Fat,
795}
796
797pub(crate) fn compute_per_cgu_lto_type(
798 sess_lto: &Lto,
799 opts: &config::Options,
800 sess_crate_types: &[CrateType],
801 module_kind: ModuleKind,
802) -> ComputedLtoType {
803 let linker_does_lto = opts.cg.linker_plugin_lto.enabled();
807
808 let is_allocator = module_kind == ModuleKind::Allocator;
813
814 let is_rlib = matches!(sess_crate_types, [CrateType::Rlib]);
823
824 match sess_lto {
825 Lto::ThinLocal if !linker_does_lto && !is_allocator => ComputedLtoType::Thin,
826 Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
827 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
828 _ => ComputedLtoType::No,
829 }
830}
831
832fn execute_optimize_work_item<B: ExtraBackendMethods>(
833 cgcx: &CodegenContext<B>,
834 mut module: ModuleCodegen<B::Module>,
835) -> WorkItemResult<B> {
836 let _timer = cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &*module.name);
837
838 let dcx = cgcx.create_dcx();
839 let dcx = dcx.handle();
840
841 let module_config = match module.kind {
842 ModuleKind::Regular => &cgcx.module_config,
843 ModuleKind::Allocator => &cgcx.allocator_config,
844 };
845
846 B::optimize(cgcx, dcx, &mut module, module_config);
847
848 let lto_type = compute_per_cgu_lto_type(&cgcx.lto, &cgcx.opts, &cgcx.crate_types, module.kind);
854
855 let bitcode = if module_config.emit_pre_lto_bc {
858 let filename = pre_lto_bitcode_filename(&module.name);
859 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
860 } else {
861 None
862 };
863
864 match lto_type {
865 ComputedLtoType::No => {
866 let module = B::codegen(cgcx, module, module_config);
867 WorkItemResult::Finished(module)
868 }
869 ComputedLtoType::Thin => {
870 let (name, thin_buffer) = B::prepare_thin(module);
871 if let Some(path) = bitcode {
872 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
873 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
874 });
875 }
876 WorkItemResult::NeedsThinLto(name, thin_buffer)
877 }
878 ComputedLtoType::Fat => match bitcode {
879 Some(path) => {
880 let (name, buffer) = B::serialize_module(module);
881 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
882 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
883 });
884 WorkItemResult::NeedsFatLto(FatLtoInput::Serialized {
885 name,
886 buffer: SerializedModule::Local(buffer),
887 })
888 }
889 None => WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module)),
890 },
891 }
892}
893
894fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
895 cgcx: &CodegenContext<B>,
896 module: CachedModuleCodegen,
897) -> CompiledModule {
898 let _timer = cgcx
899 .prof
900 .generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &*module.name);
901
902 let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
903
904 let mut links_from_incr_cache = Vec::new();
905
906 let mut load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
907 let source_file = in_incr_comp_dir(incr_comp_session_dir, saved_path);
908 debug!(
909 "copying preexisting module `{}` from {:?} to {}",
910 module.name,
911 source_file,
912 output_path.display()
913 );
914 match link_or_copy(&source_file, &output_path) {
915 Ok(_) => {
916 links_from_incr_cache.push(source_file);
917 Some(output_path)
918 }
919 Err(error) => {
920 cgcx.create_dcx().handle().emit_err(errors::CopyPathBuf {
921 source_file,
922 output_path,
923 error,
924 });
925 None
926 }
927 }
928 };
929
930 let dwarf_object =
931 module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
932 let dwarf_obj_out = cgcx
933 .output_filenames
934 .split_dwarf_path(
935 cgcx.split_debuginfo,
936 cgcx.split_dwarf_kind,
937 &module.name,
938 cgcx.invocation_temp.as_deref(),
939 )
940 .expect(
941 "saved dwarf object in work product but `split_dwarf_path` returned `None`",
942 );
943 load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
944 });
945
946 let mut load_from_incr_cache = |perform, output_type: OutputType| {
947 if perform {
948 let saved_file = module.source.saved_files.get(output_type.extension())?;
949 let output_path = cgcx.output_filenames.temp_path_for_cgu(
950 output_type,
951 &module.name,
952 cgcx.invocation_temp.as_deref(),
953 );
954 load_from_incr_comp_dir(output_path, &saved_file)
955 } else {
956 None
957 }
958 };
959
960 let module_config = &cgcx.module_config;
961 let should_emit_obj = module_config.emit_obj != EmitObj::None;
962 let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
963 let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
964 let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
965 let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
966 if should_emit_obj && object.is_none() {
967 cgcx.create_dcx().handle().emit_fatal(errors::NoSavedObjectFile { cgu_name: &module.name })
968 }
969
970 CompiledModule {
971 links_from_incr_cache,
972 kind: ModuleKind::Regular,
973 name: module.name,
974 object,
975 dwarf_object,
976 bytecode,
977 assembly,
978 llvm_ir,
979 }
980}
981
982fn do_fat_lto<B: ExtraBackendMethods>(
983 cgcx: &CodegenContext<B>,
984 exported_symbols_for_lto: &[String],
985 each_linked_rlib_for_lto: &[PathBuf],
986 mut needs_fat_lto: Vec<FatLtoInput<B>>,
987 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
988) -> CompiledModule {
989 let _timer = cgcx.prof.verbose_generic_activity("LLVM_fatlto");
990
991 check_lto_allowed(&cgcx);
992
993 for (module, wp) in import_only_modules {
994 needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, buffer: module })
995 }
996
997 let module = B::run_and_optimize_fat_lto(
998 cgcx,
999 exported_symbols_for_lto,
1000 each_linked_rlib_for_lto,
1001 needs_fat_lto,
1002 );
1003 B::codegen(cgcx, module, &cgcx.module_config)
1004}
1005
1006fn do_thin_lto<'a, B: ExtraBackendMethods>(
1007 cgcx: &'a CodegenContext<B>,
1008 exported_symbols_for_lto: Arc<Vec<String>>,
1009 each_linked_rlib_for_lto: Vec<PathBuf>,
1010 needs_thin_lto: Vec<(String, <B as WriteBackendMethods>::ThinBuffer)>,
1011 lto_import_only_modules: Vec<(
1012 SerializedModule<<B as WriteBackendMethods>::ModuleBuffer>,
1013 WorkProduct,
1014 )>,
1015) -> Vec<CompiledModule> {
1016 let _timer = cgcx.prof.verbose_generic_activity("LLVM_thinlto");
1017
1018 check_lto_allowed(&cgcx);
1019
1020 let (coordinator_send, coordinator_receive) = channel();
1021
1022 let coordinator_send2 = coordinator_send.clone();
1028 let helper = jobserver::client()
1029 .into_helper_thread(move |token| {
1030 drop(coordinator_send2.send(ThinLtoMessage::Token(token)));
1031 })
1032 .expect("failed to spawn helper thread");
1033
1034 let mut work_items = vec![];
1035
1036 for (work, cost) in generate_thin_lto_work(
1042 cgcx,
1043 &exported_symbols_for_lto,
1044 &each_linked_rlib_for_lto,
1045 needs_thin_lto,
1046 lto_import_only_modules,
1047 ) {
1048 let insertion_index =
1049 work_items.binary_search_by_key(&cost, |&(_, cost)| cost).unwrap_or_else(|e| e);
1050 work_items.insert(insertion_index, (work, cost));
1051 if cgcx.parallel {
1052 helper.request_token();
1053 }
1054 }
1055
1056 let mut codegen_aborted = None;
1057
1058 let mut tokens = vec![];
1061
1062 let mut used_token_count = 0;
1064
1065 let mut compiled_modules = vec![];
1066
1067 loop {
1073 if codegen_aborted.is_none() {
1074 if used_token_count == 0 && work_items.is_empty() {
1075 break;
1077 }
1078
1079 while used_token_count < tokens.len() + 1
1082 && let Some((item, _)) = work_items.pop()
1083 {
1084 spawn_thin_lto_work(&cgcx, coordinator_send.clone(), item);
1085 used_token_count += 1;
1086 }
1087 } else {
1088 if used_token_count == 0 {
1091 break;
1092 }
1093 }
1094
1095 tokens.truncate(used_token_count.saturating_sub(1));
1097
1098 match coordinator_receive.recv().unwrap() {
1099 ThinLtoMessage::Token(token) => match token {
1103 Ok(token) => {
1104 tokens.push(token);
1105 }
1106 Err(e) => {
1107 let msg = &format!("failed to acquire jobserver token: {e}");
1108 cgcx.diag_emitter.fatal(msg);
1109 codegen_aborted = Some(FatalError);
1110 }
1111 },
1112
1113 ThinLtoMessage::WorkItem { result } => {
1114 used_token_count -= 1;
1120
1121 match result {
1122 Ok(compiled_module) => compiled_modules.push(compiled_module),
1123 Err(Some(WorkerFatalError)) => {
1124 codegen_aborted = Some(FatalError);
1126 }
1127 Err(None) => {
1128 bug!("worker thread panicked");
1131 }
1132 }
1133 }
1134 }
1135 }
1136
1137 if let Some(codegen_aborted) = codegen_aborted {
1138 codegen_aborted.raise();
1139 }
1140
1141 compiled_modules
1142}
1143
1144fn execute_thin_lto_work_item<B: ExtraBackendMethods>(
1145 cgcx: &CodegenContext<B>,
1146 module: lto::ThinModule<B>,
1147) -> CompiledModule {
1148 let _timer = cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", module.name());
1149
1150 let module = B::optimize_thin(cgcx, module);
1151 B::codegen(cgcx, module, &cgcx.module_config)
1152}
1153
1154pub(crate) enum Message<B: WriteBackendMethods> {
1156 Token(io::Result<Acquired>),
1159
1160 WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>> },
1163
1164 CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
1168
1169 AddImportOnlyModule {
1172 module_data: SerializedModule<B::ModuleBuffer>,
1173 work_product: WorkProduct,
1174 },
1175
1176 CodegenComplete,
1179
1180 CodegenAborted,
1183}
1184
1185pub(crate) enum ThinLtoMessage {
1187 Token(io::Result<Acquired>),
1190
1191 WorkItem { result: Result<CompiledModule, Option<WorkerFatalError>> },
1194}
1195
1196pub struct CguMessage;
1199
1200struct Diagnostic {
1210 level: Level,
1211 messages: Vec<(DiagMessage, Style)>,
1212 code: Option<ErrCode>,
1213 children: Vec<Subdiagnostic>,
1214 args: DiagArgMap,
1215}
1216
1217pub(crate) struct Subdiagnostic {
1221 level: Level,
1222 messages: Vec<(DiagMessage, Style)>,
1223}
1224
1225#[derive(PartialEq, Clone, Copy, Debug)]
1226enum MainThreadState {
1227 Idle,
1229
1230 Codegenning,
1232
1233 Lending,
1235}
1236
1237fn start_executing_work<B: ExtraBackendMethods>(
1238 backend: B,
1239 tcx: TyCtxt<'_>,
1240 crate_info: &CrateInfo,
1241 shared_emitter: SharedEmitter,
1242 codegen_worker_send: Sender<CguMessage>,
1243 coordinator_receive: Receiver<Message<B>>,
1244 regular_config: Arc<ModuleConfig>,
1245 allocator_config: Arc<ModuleConfig>,
1246 allocator_module: Option<ModuleCodegen<B::Module>>,
1247 coordinator_send: Sender<Message<B>>,
1248) -> thread::JoinHandle<Result<CompiledModules, ()>> {
1249 let sess = tcx.sess;
1250
1251 let mut each_linked_rlib_for_lto = Vec::new();
1252 let mut each_linked_rlib_file_for_lto = Vec::new();
1253 drop(link::each_linked_rlib(crate_info, None, &mut |cnum, path| {
1254 if link::ignored_for_lto(sess, crate_info, cnum) {
1255 return;
1256 }
1257 each_linked_rlib_for_lto.push(cnum);
1258 each_linked_rlib_file_for_lto.push(path.to_path_buf());
1259 }));
1260
1261 let exported_symbols_for_lto =
1263 Arc::new(lto::exported_symbols_for_lto(tcx, &each_linked_rlib_for_lto));
1264
1265 let coordinator_send2 = coordinator_send.clone();
1271 let helper = jobserver::client()
1272 .into_helper_thread(move |token| {
1273 drop(coordinator_send2.send(Message::Token::<B>(token)));
1274 })
1275 .expect("failed to spawn helper thread");
1276
1277 let ol = tcx.backend_optimization_level(());
1278 let backend_features = tcx.global_backend_features(());
1279
1280 let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1281 let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1282 match result {
1283 Ok(dir) => Some(dir),
1284 Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1285 }
1286 } else {
1287 None
1288 };
1289
1290 let cgcx = CodegenContext::<B> {
1291 crate_types: tcx.crate_types().to_vec(),
1292 lto: sess.lto(),
1293 fewer_names: sess.fewer_names(),
1294 save_temps: sess.opts.cg.save_temps,
1295 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1296 opts: Arc::new(sess.opts.clone()),
1297 prof: sess.prof.clone(),
1298 remark: sess.opts.cg.remark.clone(),
1299 remark_dir,
1300 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1301 diag_emitter: shared_emitter.clone(),
1302 output_filenames: Arc::clone(tcx.output_filenames(())),
1303 module_config: regular_config,
1304 allocator_config,
1305 tm_factory: backend.target_machine_factory(tcx.sess, ol, backend_features),
1306 msvc_imps_needed: msvc_imps_needed(tcx),
1307 is_pe_coff: tcx.sess.target.is_like_windows,
1308 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1309 target_arch: tcx.sess.target.arch.to_string(),
1310 target_is_like_darwin: tcx.sess.target.is_like_darwin,
1311 target_is_like_aix: tcx.sess.target.is_like_aix,
1312 split_debuginfo: tcx.sess.split_debuginfo(),
1313 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1314 parallel: backend.supports_parallel() && !sess.opts.unstable_opts.no_parallel_backend,
1315 pointer_size: tcx.data_layout.pointer_size(),
1316 invocation_temp: sess.invocation_temp.clone(),
1317 };
1318
1319 return B::spawn_named_thread(cgcx.time_trace, "coordinator".to_string(), move || {
1455 let mut compiled_modules = vec![];
1458 let mut needs_fat_lto = Vec::new();
1459 let mut needs_thin_lto = Vec::new();
1460 let mut lto_import_only_modules = Vec::new();
1461
1462 #[derive(Debug, PartialEq)]
1467 enum CodegenState {
1468 Ongoing,
1469 Completed,
1470 Aborted,
1471 }
1472 use CodegenState::*;
1473 let mut codegen_state = Ongoing;
1474
1475 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1477
1478 let mut tokens = Vec::new();
1481
1482 let mut main_thread_state = MainThreadState::Idle;
1483
1484 let mut running_with_own_token = 0;
1487
1488 let running_with_any_token = |main_thread_state, running_with_own_token| {
1491 running_with_own_token
1492 + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1493 };
1494
1495 let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
1496
1497 let compiled_allocator_module = allocator_module.and_then(|allocator_module| {
1498 match execute_optimize_work_item(&cgcx, allocator_module) {
1499 WorkItemResult::Finished(compiled_module) => return Some(compiled_module),
1500 WorkItemResult::NeedsFatLto(fat_lto_input) => needs_fat_lto.push(fat_lto_input),
1501 WorkItemResult::NeedsThinLto(name, thin_buffer) => {
1502 needs_thin_lto.push((name, thin_buffer))
1503 }
1504 }
1505 None
1506 });
1507
1508 loop {
1514 if codegen_state == Ongoing {
1518 if main_thread_state == MainThreadState::Idle {
1519 let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1527 let additional_running = std::cmp::min(extra_tokens, work_items.len());
1528 let anticipated_running = running_with_own_token + additional_running + 1;
1529
1530 if !queue_full_enough(work_items.len(), anticipated_running) {
1531 if codegen_worker_send.send(CguMessage).is_err() {
1533 panic!("Could not send CguMessage to main thread")
1534 }
1535 main_thread_state = MainThreadState::Codegenning;
1536 } else {
1537 let (item, _) =
1541 work_items.pop().expect("queue empty - queue_full_enough() broken?");
1542 main_thread_state = MainThreadState::Lending;
1543 spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1544 }
1545 }
1546 } else if codegen_state == Completed {
1547 if running_with_any_token(main_thread_state, running_with_own_token) == 0
1548 && work_items.is_empty()
1549 {
1550 break;
1552 }
1553
1554 match main_thread_state {
1558 MainThreadState::Idle => {
1559 if let Some((item, _)) = work_items.pop() {
1560 main_thread_state = MainThreadState::Lending;
1561 spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1562 } else {
1563 assert!(running_with_own_token > 0);
1570 running_with_own_token -= 1;
1571 main_thread_state = MainThreadState::Lending;
1572 }
1573 }
1574 MainThreadState::Codegenning => bug!(
1575 "codegen worker should not be codegenning after \
1576 codegen was already completed"
1577 ),
1578 MainThreadState::Lending => {
1579 }
1581 }
1582 } else {
1583 assert!(codegen_state == Aborted);
1586 if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1587 break;
1588 }
1589 }
1590
1591 if codegen_state != Aborted {
1594 while running_with_own_token < tokens.len()
1595 && let Some((item, _)) = work_items.pop()
1596 {
1597 spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1598 running_with_own_token += 1;
1599 }
1600 }
1601
1602 tokens.truncate(running_with_own_token);
1604
1605 match coordinator_receive.recv().unwrap() {
1606 Message::Token(token) => {
1610 match token {
1611 Ok(token) => {
1612 tokens.push(token);
1613
1614 if main_thread_state == MainThreadState::Lending {
1615 main_thread_state = MainThreadState::Idle;
1620 running_with_own_token += 1;
1621 }
1622 }
1623 Err(e) => {
1624 let msg = &format!("failed to acquire jobserver token: {e}");
1625 shared_emitter.fatal(msg);
1626 codegen_state = Aborted;
1627 }
1628 }
1629 }
1630
1631 Message::CodegenDone { llvm_work_item, cost } => {
1632 let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1641 let insertion_index = match insertion_index {
1642 Ok(idx) | Err(idx) => idx,
1643 };
1644 work_items.insert(insertion_index, (llvm_work_item, cost));
1645
1646 if cgcx.parallel {
1647 helper.request_token();
1648 }
1649 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1650 main_thread_state = MainThreadState::Idle;
1651 }
1652
1653 Message::CodegenComplete => {
1654 if codegen_state != Aborted {
1655 codegen_state = Completed;
1656 }
1657 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1658 main_thread_state = MainThreadState::Idle;
1659 }
1660
1661 Message::CodegenAborted => {
1669 codegen_state = Aborted;
1670 }
1671
1672 Message::WorkItem { result } => {
1673 if main_thread_state == MainThreadState::Lending {
1679 main_thread_state = MainThreadState::Idle;
1680 } else {
1681 running_with_own_token -= 1;
1682 }
1683
1684 match result {
1685 Ok(WorkItemResult::Finished(compiled_module)) => {
1686 compiled_modules.push(compiled_module);
1687 }
1688 Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1689 assert!(needs_thin_lto.is_empty());
1690 needs_fat_lto.push(fat_lto_input);
1691 }
1692 Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1693 assert!(needs_fat_lto.is_empty());
1694 needs_thin_lto.push((name, thin_buffer));
1695 }
1696 Err(Some(WorkerFatalError)) => {
1697 codegen_state = Aborted;
1699 }
1700 Err(None) => {
1701 bug!("worker thread panicked");
1704 }
1705 }
1706 }
1707
1708 Message::AddImportOnlyModule { module_data, work_product } => {
1709 assert_eq!(codegen_state, Ongoing);
1710 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1711 lto_import_only_modules.push((module_data, work_product));
1712 main_thread_state = MainThreadState::Idle;
1713 }
1714 }
1715 }
1716
1717 drop(llvm_start_time);
1719
1720 if codegen_state == Aborted {
1721 return Err(());
1722 }
1723
1724 drop(codegen_state);
1725 drop(tokens);
1726 drop(helper);
1727 assert!(work_items.is_empty());
1728
1729 if !needs_fat_lto.is_empty() {
1730 assert!(compiled_modules.is_empty());
1731 assert!(needs_thin_lto.is_empty());
1732
1733 let module = do_fat_lto(
1735 &cgcx,
1736 &exported_symbols_for_lto,
1737 &each_linked_rlib_file_for_lto,
1738 needs_fat_lto,
1739 lto_import_only_modules,
1740 );
1741 compiled_modules.push(module);
1742 } else if !needs_thin_lto.is_empty() || !lto_import_only_modules.is_empty() {
1743 assert!(compiled_modules.is_empty());
1744 assert!(needs_fat_lto.is_empty());
1745
1746 compiled_modules.extend(do_thin_lto(
1747 &cgcx,
1748 exported_symbols_for_lto,
1749 each_linked_rlib_file_for_lto,
1750 needs_thin_lto,
1751 lto_import_only_modules,
1752 ));
1753 }
1754
1755 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1759
1760 Ok(CompiledModules {
1761 modules: compiled_modules,
1762 allocator_module: compiled_allocator_module,
1763 })
1764 })
1765 .expect("failed to spawn coordinator thread");
1766
1767 fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1770 let quarter_of_workers = workers_running - 3 * workers_running / 4;
1821 items_in_queue > 0 && items_in_queue >= quarter_of_workers
1822 }
1823}
1824
1825#[must_use]
1827pub(crate) struct WorkerFatalError;
1828
1829fn spawn_work<'a, B: ExtraBackendMethods>(
1830 cgcx: &'a CodegenContext<B>,
1831 coordinator_send: Sender<Message<B>>,
1832 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1833 work: WorkItem<B>,
1834) {
1835 if llvm_start_time.is_none() {
1836 *llvm_start_time = Some(cgcx.prof.verbose_generic_activity("LLVM_passes"));
1837 }
1838
1839 let cgcx = cgcx.clone();
1840
1841 B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1842 let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1843 WorkItem::Optimize(m) => execute_optimize_work_item(&cgcx, m),
1844 WorkItem::CopyPostLtoArtifacts(m) => {
1845 WorkItemResult::Finished(execute_copy_from_cache_work_item(&cgcx, m))
1846 }
1847 }));
1848
1849 let msg = match result {
1850 Ok(result) => Message::WorkItem::<B> { result: Ok(result) },
1851
1852 Err(err) if err.is::<FatalErrorMarker>() => {
1856 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1857 }
1858
1859 Err(_) => Message::WorkItem::<B> { result: Err(None) },
1860 };
1861 drop(coordinator_send.send(msg));
1862 })
1863 .expect("failed to spawn work thread");
1864}
1865
1866fn spawn_thin_lto_work<'a, B: ExtraBackendMethods>(
1867 cgcx: &'a CodegenContext<B>,
1868 coordinator_send: Sender<ThinLtoMessage>,
1869 work: ThinLtoWorkItem<B>,
1870) {
1871 let cgcx = cgcx.clone();
1872
1873 B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1874 let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1875 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => execute_copy_from_cache_work_item(&cgcx, m),
1876 ThinLtoWorkItem::ThinLto(m) => execute_thin_lto_work_item(&cgcx, m),
1877 }));
1878
1879 let msg = match result {
1880 Ok(result) => ThinLtoMessage::WorkItem { result: Ok(result) },
1881
1882 Err(err) if err.is::<FatalErrorMarker>() => {
1886 ThinLtoMessage::WorkItem { result: Err(Some(WorkerFatalError)) }
1887 }
1888
1889 Err(_) => ThinLtoMessage::WorkItem { result: Err(None) },
1890 };
1891 drop(coordinator_send.send(msg));
1892 })
1893 .expect("failed to spawn work thread");
1894}
1895
1896enum SharedEmitterMessage {
1897 Diagnostic(Diagnostic),
1898 InlineAsmError(SpanData, String, Level, Option<(String, Vec<InnerSpan>)>),
1899 Fatal(String),
1900}
1901
1902#[derive(Clone)]
1903pub struct SharedEmitter {
1904 sender: Sender<SharedEmitterMessage>,
1905}
1906
1907pub struct SharedEmitterMain {
1908 receiver: Receiver<SharedEmitterMessage>,
1909}
1910
1911impl SharedEmitter {
1912 fn new() -> (SharedEmitter, SharedEmitterMain) {
1913 let (sender, receiver) = channel();
1914
1915 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1916 }
1917
1918 pub fn inline_asm_error(
1919 &self,
1920 span: SpanData,
1921 msg: String,
1922 level: Level,
1923 source: Option<(String, Vec<InnerSpan>)>,
1924 ) {
1925 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(span, msg, level, source)));
1926 }
1927
1928 fn fatal(&self, msg: &str) {
1929 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1930 }
1931}
1932
1933impl Emitter for SharedEmitter {
1934 fn emit_diagnostic(
1935 &mut self,
1936 mut diag: rustc_errors::DiagInner,
1937 _registry: &rustc_errors::registry::Registry,
1938 ) {
1939 assert_eq!(diag.span, MultiSpan::new());
1942 assert_eq!(diag.suggestions, Suggestions::Enabled(vec![]));
1943 assert_eq!(diag.sort_span, rustc_span::DUMMY_SP);
1944 assert_eq!(diag.is_lint, None);
1945 let args = mem::replace(&mut diag.args, DiagArgMap::default());
1948 drop(
1949 self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1950 level: diag.level(),
1951 messages: diag.messages,
1952 code: diag.code,
1953 children: diag
1954 .children
1955 .into_iter()
1956 .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
1957 .collect(),
1958 args,
1959 })),
1960 );
1961 }
1962
1963 fn source_map(&self) -> Option<&SourceMap> {
1964 None
1965 }
1966
1967 fn translator(&self) -> &Translator {
1968 panic!("shared emitter attempted to translate a diagnostic");
1969 }
1970}
1971
1972impl SharedEmitterMain {
1973 fn check(&self, sess: &Session, blocking: bool) {
1974 loop {
1975 let message = if blocking {
1976 match self.receiver.recv() {
1977 Ok(message) => Ok(message),
1978 Err(_) => Err(()),
1979 }
1980 } else {
1981 match self.receiver.try_recv() {
1982 Ok(message) => Ok(message),
1983 Err(_) => Err(()),
1984 }
1985 };
1986
1987 match message {
1988 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1989 let dcx = sess.dcx();
1992 let mut d =
1993 rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
1994 d.code = diag.code; d.children = diag
1996 .children
1997 .into_iter()
1998 .map(|sub| rustc_errors::Subdiag {
1999 level: sub.level,
2000 messages: sub.messages,
2001 span: MultiSpan::new(),
2002 })
2003 .collect();
2004 d.args = diag.args;
2005 dcx.emit_diagnostic(d);
2006 sess.dcx().abort_if_errors();
2007 }
2008 Ok(SharedEmitterMessage::InlineAsmError(span, msg, level, source)) => {
2009 assert_matches!(level, Level::Error | Level::Warning | Level::Note);
2010 let mut err = Diag::<()>::new(sess.dcx(), level, msg);
2011 if !span.is_dummy() {
2012 err.span(span.span());
2013 }
2014
2015 if let Some((buffer, spans)) = source {
2017 let source = sess
2018 .source_map()
2019 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
2020 let spans: Vec<_> = spans
2021 .iter()
2022 .map(|sp| {
2023 Span::with_root_ctxt(
2024 source.normalized_byte_pos(sp.start as u32),
2025 source.normalized_byte_pos(sp.end as u32),
2026 )
2027 })
2028 .collect();
2029 err.span_note(spans, "instantiated into assembly here");
2030 }
2031
2032 err.emit();
2033 }
2034 Ok(SharedEmitterMessage::Fatal(msg)) => {
2035 sess.dcx().fatal(msg);
2036 }
2037 Err(_) => {
2038 break;
2039 }
2040 }
2041 }
2042 }
2043}
2044
2045pub struct Coordinator<B: ExtraBackendMethods> {
2046 sender: Sender<Message<B>>,
2047 future: Option<thread::JoinHandle<Result<CompiledModules, ()>>>,
2048 phantom: PhantomData<B>,
2050}
2051
2052impl<B: ExtraBackendMethods> Coordinator<B> {
2053 fn join(mut self) -> std::thread::Result<Result<CompiledModules, ()>> {
2054 self.future.take().unwrap().join()
2055 }
2056}
2057
2058impl<B: ExtraBackendMethods> Drop for Coordinator<B> {
2059 fn drop(&mut self) {
2060 if let Some(future) = self.future.take() {
2061 drop(self.sender.send(Message::CodegenAborted::<B>));
2064 drop(future.join());
2065 }
2066 }
2067}
2068
2069pub struct OngoingCodegen<B: ExtraBackendMethods> {
2070 pub backend: B,
2071 pub crate_info: CrateInfo,
2072 pub output_filenames: Arc<OutputFilenames>,
2073 pub coordinator: Coordinator<B>,
2077 pub codegen_worker_receive: Receiver<CguMessage>,
2078 pub shared_emitter_main: SharedEmitterMain,
2079}
2080
2081impl<B: ExtraBackendMethods> OngoingCodegen<B> {
2082 pub fn join(self, sess: &Session) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
2083 self.shared_emitter_main.check(sess, true);
2084 let compiled_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
2085 Ok(Ok(compiled_modules)) => compiled_modules,
2086 Ok(Err(())) => {
2087 sess.dcx().abort_if_errors();
2088 panic!("expected abort due to worker thread errors")
2089 }
2090 Err(_) => {
2091 bug!("panic during codegen/LLVM phase");
2092 }
2093 });
2094
2095 sess.dcx().abort_if_errors();
2096
2097 let work_products =
2098 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
2099 produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
2100
2101 if sess.codegen_units().as_usize() == 1 && sess.opts.unstable_opts.time_llvm_passes {
2104 self.backend.print_pass_timings()
2105 }
2106
2107 if sess.print_llvm_stats() {
2108 self.backend.print_statistics()
2109 }
2110
2111 (
2112 CodegenResults {
2113 crate_info: self.crate_info,
2114
2115 modules: compiled_modules.modules,
2116 allocator_module: compiled_modules.allocator_module,
2117 },
2118 work_products,
2119 )
2120 }
2121
2122 pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2123 self.wait_for_signal_to_codegen_item();
2124 self.check_for_errors(tcx.sess);
2125 drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
2126 }
2127
2128 pub(crate) fn check_for_errors(&self, sess: &Session) {
2129 self.shared_emitter_main.check(sess, false);
2130 }
2131
2132 pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2133 match self.codegen_worker_receive.recv() {
2134 Ok(CguMessage) => {
2135 }
2137 Err(_) => {
2138 }
2141 }
2142 }
2143}
2144
2145pub(crate) fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
2146 coordinator: &Coordinator<B>,
2147 module: ModuleCodegen<B::Module>,
2148 cost: u64,
2149) {
2150 let llvm_work_item = WorkItem::Optimize(module);
2151 drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2152}
2153
2154pub(crate) fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
2155 coordinator: &Coordinator<B>,
2156 module: CachedModuleCodegen,
2157) {
2158 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2159 drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2160}
2161
2162pub(crate) fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
2163 tcx: TyCtxt<'_>,
2164 coordinator: &Coordinator<B>,
2165 module: CachedModuleCodegen,
2166) {
2167 let filename = pre_lto_bitcode_filename(&module.name);
2168 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2169 let file = fs::File::open(&bc_path)
2170 .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
2171
2172 let mmap = unsafe {
2173 Mmap::map(file).unwrap_or_else(|e| {
2174 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2175 })
2176 };
2177 drop(coordinator.sender.send(Message::AddImportOnlyModule::<B> {
2179 module_data: SerializedModule::FromUncompressedFile(mmap),
2180 work_product: module.source,
2181 }));
2182}
2183
2184fn pre_lto_bitcode_filename(module_name: &str) -> String {
2185 format!("{module_name}.{PRE_LTO_BC_EXT}")
2186}
2187
2188fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2189 assert!(
2192 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2193 && tcx.sess.target.is_like_windows
2194 && tcx.sess.opts.cg.prefer_dynamic)
2195 );
2196
2197 let can_have_static_objects =
2201 tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
2202
2203 tcx.sess.target.is_like_windows &&
2204 can_have_static_objects &&
2205 !tcx.sess.opts.cg.linker_plugin_lto.enabled()
2209}