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 =
1278 if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
1279 config::OptLevel::No
1281 } else {
1282 tcx.backend_optimization_level(())
1283 };
1284 let backend_features = tcx.global_backend_features(());
1285
1286 let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1287 let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1288 match result {
1289 Ok(dir) => Some(dir),
1290 Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1291 }
1292 } else {
1293 None
1294 };
1295
1296 let cgcx = CodegenContext::<B> {
1297 crate_types: tcx.crate_types().to_vec(),
1298 lto: sess.lto(),
1299 fewer_names: sess.fewer_names(),
1300 save_temps: sess.opts.cg.save_temps,
1301 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1302 opts: Arc::new(sess.opts.clone()),
1303 prof: sess.prof.clone(),
1304 remark: sess.opts.cg.remark.clone(),
1305 remark_dir,
1306 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1307 diag_emitter: shared_emitter.clone(),
1308 output_filenames: Arc::clone(tcx.output_filenames(())),
1309 module_config: regular_config,
1310 allocator_config,
1311 tm_factory: backend.target_machine_factory(tcx.sess, ol, backend_features),
1312 msvc_imps_needed: msvc_imps_needed(tcx),
1313 is_pe_coff: tcx.sess.target.is_like_windows,
1314 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1315 target_arch: tcx.sess.target.arch.to_string(),
1316 target_is_like_darwin: tcx.sess.target.is_like_darwin,
1317 target_is_like_aix: tcx.sess.target.is_like_aix,
1318 split_debuginfo: tcx.sess.split_debuginfo(),
1319 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1320 parallel: backend.supports_parallel() && !sess.opts.unstable_opts.no_parallel_backend,
1321 pointer_size: tcx.data_layout.pointer_size(),
1322 invocation_temp: sess.invocation_temp.clone(),
1323 };
1324
1325 return B::spawn_named_thread(cgcx.time_trace, "coordinator".to_string(), move || {
1461 let mut compiled_modules = vec![];
1464 let mut needs_fat_lto = Vec::new();
1465 let mut needs_thin_lto = Vec::new();
1466 let mut lto_import_only_modules = Vec::new();
1467
1468 #[derive(Debug, PartialEq)]
1473 enum CodegenState {
1474 Ongoing,
1475 Completed,
1476 Aborted,
1477 }
1478 use CodegenState::*;
1479 let mut codegen_state = Ongoing;
1480
1481 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1483
1484 let mut tokens = Vec::new();
1487
1488 let mut main_thread_state = MainThreadState::Idle;
1489
1490 let mut running_with_own_token = 0;
1493
1494 let running_with_any_token = |main_thread_state, running_with_own_token| {
1497 running_with_own_token
1498 + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1499 };
1500
1501 let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
1502
1503 let compiled_allocator_module = allocator_module.and_then(|allocator_module| {
1504 match execute_optimize_work_item(&cgcx, allocator_module) {
1505 WorkItemResult::Finished(compiled_module) => return Some(compiled_module),
1506 WorkItemResult::NeedsFatLto(fat_lto_input) => needs_fat_lto.push(fat_lto_input),
1507 WorkItemResult::NeedsThinLto(name, thin_buffer) => {
1508 needs_thin_lto.push((name, thin_buffer))
1509 }
1510 }
1511 None
1512 });
1513
1514 loop {
1520 if codegen_state == Ongoing {
1524 if main_thread_state == MainThreadState::Idle {
1525 let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1533 let additional_running = std::cmp::min(extra_tokens, work_items.len());
1534 let anticipated_running = running_with_own_token + additional_running + 1;
1535
1536 if !queue_full_enough(work_items.len(), anticipated_running) {
1537 if codegen_worker_send.send(CguMessage).is_err() {
1539 panic!("Could not send CguMessage to main thread")
1540 }
1541 main_thread_state = MainThreadState::Codegenning;
1542 } else {
1543 let (item, _) =
1547 work_items.pop().expect("queue empty - queue_full_enough() broken?");
1548 main_thread_state = MainThreadState::Lending;
1549 spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1550 }
1551 }
1552 } else if codegen_state == Completed {
1553 if running_with_any_token(main_thread_state, running_with_own_token) == 0
1554 && work_items.is_empty()
1555 {
1556 break;
1558 }
1559
1560 match main_thread_state {
1564 MainThreadState::Idle => {
1565 if let Some((item, _)) = work_items.pop() {
1566 main_thread_state = MainThreadState::Lending;
1567 spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1568 } else {
1569 assert!(running_with_own_token > 0);
1576 running_with_own_token -= 1;
1577 main_thread_state = MainThreadState::Lending;
1578 }
1579 }
1580 MainThreadState::Codegenning => bug!(
1581 "codegen worker should not be codegenning after \
1582 codegen was already completed"
1583 ),
1584 MainThreadState::Lending => {
1585 }
1587 }
1588 } else {
1589 assert!(codegen_state == Aborted);
1592 if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1593 break;
1594 }
1595 }
1596
1597 if codegen_state != Aborted {
1600 while running_with_own_token < tokens.len()
1601 && let Some((item, _)) = work_items.pop()
1602 {
1603 spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1604 running_with_own_token += 1;
1605 }
1606 }
1607
1608 tokens.truncate(running_with_own_token);
1610
1611 match coordinator_receive.recv().unwrap() {
1612 Message::Token(token) => {
1616 match token {
1617 Ok(token) => {
1618 tokens.push(token);
1619
1620 if main_thread_state == MainThreadState::Lending {
1621 main_thread_state = MainThreadState::Idle;
1626 running_with_own_token += 1;
1627 }
1628 }
1629 Err(e) => {
1630 let msg = &format!("failed to acquire jobserver token: {e}");
1631 shared_emitter.fatal(msg);
1632 codegen_state = Aborted;
1633 }
1634 }
1635 }
1636
1637 Message::CodegenDone { llvm_work_item, cost } => {
1638 let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1647 let insertion_index = match insertion_index {
1648 Ok(idx) | Err(idx) => idx,
1649 };
1650 work_items.insert(insertion_index, (llvm_work_item, cost));
1651
1652 if cgcx.parallel {
1653 helper.request_token();
1654 }
1655 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1656 main_thread_state = MainThreadState::Idle;
1657 }
1658
1659 Message::CodegenComplete => {
1660 if codegen_state != Aborted {
1661 codegen_state = Completed;
1662 }
1663 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1664 main_thread_state = MainThreadState::Idle;
1665 }
1666
1667 Message::CodegenAborted => {
1675 codegen_state = Aborted;
1676 }
1677
1678 Message::WorkItem { result } => {
1679 if main_thread_state == MainThreadState::Lending {
1685 main_thread_state = MainThreadState::Idle;
1686 } else {
1687 running_with_own_token -= 1;
1688 }
1689
1690 match result {
1691 Ok(WorkItemResult::Finished(compiled_module)) => {
1692 compiled_modules.push(compiled_module);
1693 }
1694 Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1695 assert!(needs_thin_lto.is_empty());
1696 needs_fat_lto.push(fat_lto_input);
1697 }
1698 Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1699 assert!(needs_fat_lto.is_empty());
1700 needs_thin_lto.push((name, thin_buffer));
1701 }
1702 Err(Some(WorkerFatalError)) => {
1703 codegen_state = Aborted;
1705 }
1706 Err(None) => {
1707 bug!("worker thread panicked");
1710 }
1711 }
1712 }
1713
1714 Message::AddImportOnlyModule { module_data, work_product } => {
1715 assert_eq!(codegen_state, Ongoing);
1716 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1717 lto_import_only_modules.push((module_data, work_product));
1718 main_thread_state = MainThreadState::Idle;
1719 }
1720 }
1721 }
1722
1723 drop(llvm_start_time);
1725
1726 if codegen_state == Aborted {
1727 return Err(());
1728 }
1729
1730 drop(codegen_state);
1731 drop(tokens);
1732 drop(helper);
1733 assert!(work_items.is_empty());
1734
1735 if !needs_fat_lto.is_empty() {
1736 assert!(compiled_modules.is_empty());
1737 assert!(needs_thin_lto.is_empty());
1738
1739 let module = do_fat_lto(
1741 &cgcx,
1742 &exported_symbols_for_lto,
1743 &each_linked_rlib_file_for_lto,
1744 needs_fat_lto,
1745 lto_import_only_modules,
1746 );
1747 compiled_modules.push(module);
1748 } else if !needs_thin_lto.is_empty() || !lto_import_only_modules.is_empty() {
1749 assert!(compiled_modules.is_empty());
1750 assert!(needs_fat_lto.is_empty());
1751
1752 compiled_modules.extend(do_thin_lto(
1753 &cgcx,
1754 exported_symbols_for_lto,
1755 each_linked_rlib_file_for_lto,
1756 needs_thin_lto,
1757 lto_import_only_modules,
1758 ));
1759 }
1760
1761 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1765
1766 Ok(CompiledModules {
1767 modules: compiled_modules,
1768 allocator_module: compiled_allocator_module,
1769 })
1770 })
1771 .expect("failed to spawn coordinator thread");
1772
1773 fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1776 let quarter_of_workers = workers_running - 3 * workers_running / 4;
1827 items_in_queue > 0 && items_in_queue >= quarter_of_workers
1828 }
1829}
1830
1831#[must_use]
1833pub(crate) struct WorkerFatalError;
1834
1835fn spawn_work<'a, B: ExtraBackendMethods>(
1836 cgcx: &'a CodegenContext<B>,
1837 coordinator_send: Sender<Message<B>>,
1838 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1839 work: WorkItem<B>,
1840) {
1841 if llvm_start_time.is_none() {
1842 *llvm_start_time = Some(cgcx.prof.verbose_generic_activity("LLVM_passes"));
1843 }
1844
1845 let cgcx = cgcx.clone();
1846
1847 B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1848 let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1849 WorkItem::Optimize(m) => execute_optimize_work_item(&cgcx, m),
1850 WorkItem::CopyPostLtoArtifacts(m) => {
1851 WorkItemResult::Finished(execute_copy_from_cache_work_item(&cgcx, m))
1852 }
1853 }));
1854
1855 let msg = match result {
1856 Ok(result) => Message::WorkItem::<B> { result: Ok(result) },
1857
1858 Err(err) if err.is::<FatalErrorMarker>() => {
1862 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1863 }
1864
1865 Err(_) => Message::WorkItem::<B> { result: Err(None) },
1866 };
1867 drop(coordinator_send.send(msg));
1868 })
1869 .expect("failed to spawn work thread");
1870}
1871
1872fn spawn_thin_lto_work<'a, B: ExtraBackendMethods>(
1873 cgcx: &'a CodegenContext<B>,
1874 coordinator_send: Sender<ThinLtoMessage>,
1875 work: ThinLtoWorkItem<B>,
1876) {
1877 let cgcx = cgcx.clone();
1878
1879 B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1880 let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1881 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => execute_copy_from_cache_work_item(&cgcx, m),
1882 ThinLtoWorkItem::ThinLto(m) => execute_thin_lto_work_item(&cgcx, m),
1883 }));
1884
1885 let msg = match result {
1886 Ok(result) => ThinLtoMessage::WorkItem { result: Ok(result) },
1887
1888 Err(err) if err.is::<FatalErrorMarker>() => {
1892 ThinLtoMessage::WorkItem { result: Err(Some(WorkerFatalError)) }
1893 }
1894
1895 Err(_) => ThinLtoMessage::WorkItem { result: Err(None) },
1896 };
1897 drop(coordinator_send.send(msg));
1898 })
1899 .expect("failed to spawn work thread");
1900}
1901
1902enum SharedEmitterMessage {
1903 Diagnostic(Diagnostic),
1904 InlineAsmError(SpanData, String, Level, Option<(String, Vec<InnerSpan>)>),
1905 Fatal(String),
1906}
1907
1908#[derive(Clone)]
1909pub struct SharedEmitter {
1910 sender: Sender<SharedEmitterMessage>,
1911}
1912
1913pub struct SharedEmitterMain {
1914 receiver: Receiver<SharedEmitterMessage>,
1915}
1916
1917impl SharedEmitter {
1918 fn new() -> (SharedEmitter, SharedEmitterMain) {
1919 let (sender, receiver) = channel();
1920
1921 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1922 }
1923
1924 pub fn inline_asm_error(
1925 &self,
1926 span: SpanData,
1927 msg: String,
1928 level: Level,
1929 source: Option<(String, Vec<InnerSpan>)>,
1930 ) {
1931 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(span, msg, level, source)));
1932 }
1933
1934 fn fatal(&self, msg: &str) {
1935 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1936 }
1937}
1938
1939impl Emitter for SharedEmitter {
1940 fn emit_diagnostic(
1941 &mut self,
1942 mut diag: rustc_errors::DiagInner,
1943 _registry: &rustc_errors::registry::Registry,
1944 ) {
1945 assert_eq!(diag.span, MultiSpan::new());
1948 assert_eq!(diag.suggestions, Suggestions::Enabled(vec![]));
1949 assert_eq!(diag.sort_span, rustc_span::DUMMY_SP);
1950 assert_eq!(diag.is_lint, None);
1951 let args = mem::replace(&mut diag.args, DiagArgMap::default());
1954 drop(
1955 self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1956 level: diag.level(),
1957 messages: diag.messages,
1958 code: diag.code,
1959 children: diag
1960 .children
1961 .into_iter()
1962 .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
1963 .collect(),
1964 args,
1965 })),
1966 );
1967 }
1968
1969 fn source_map(&self) -> Option<&SourceMap> {
1970 None
1971 }
1972
1973 fn translator(&self) -> &Translator {
1974 panic!("shared emitter attempted to translate a diagnostic");
1975 }
1976}
1977
1978impl SharedEmitterMain {
1979 fn check(&self, sess: &Session, blocking: bool) {
1980 loop {
1981 let message = if blocking {
1982 match self.receiver.recv() {
1983 Ok(message) => Ok(message),
1984 Err(_) => Err(()),
1985 }
1986 } else {
1987 match self.receiver.try_recv() {
1988 Ok(message) => Ok(message),
1989 Err(_) => Err(()),
1990 }
1991 };
1992
1993 match message {
1994 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1995 let dcx = sess.dcx();
1998 let mut d =
1999 rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
2000 d.code = diag.code; d.children = diag
2002 .children
2003 .into_iter()
2004 .map(|sub| rustc_errors::Subdiag {
2005 level: sub.level,
2006 messages: sub.messages,
2007 span: MultiSpan::new(),
2008 })
2009 .collect();
2010 d.args = diag.args;
2011 dcx.emit_diagnostic(d);
2012 sess.dcx().abort_if_errors();
2013 }
2014 Ok(SharedEmitterMessage::InlineAsmError(span, msg, level, source)) => {
2015 assert_matches!(level, Level::Error | Level::Warning | Level::Note);
2016 let mut err = Diag::<()>::new(sess.dcx(), level, msg);
2017 if !span.is_dummy() {
2018 err.span(span.span());
2019 }
2020
2021 if let Some((buffer, spans)) = source {
2023 let source = sess
2024 .source_map()
2025 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
2026 let spans: Vec<_> = spans
2027 .iter()
2028 .map(|sp| {
2029 Span::with_root_ctxt(
2030 source.normalized_byte_pos(sp.start as u32),
2031 source.normalized_byte_pos(sp.end as u32),
2032 )
2033 })
2034 .collect();
2035 err.span_note(spans, "instantiated into assembly here");
2036 }
2037
2038 err.emit();
2039 }
2040 Ok(SharedEmitterMessage::Fatal(msg)) => {
2041 sess.dcx().fatal(msg);
2042 }
2043 Err(_) => {
2044 break;
2045 }
2046 }
2047 }
2048 }
2049}
2050
2051pub struct Coordinator<B: ExtraBackendMethods> {
2052 sender: Sender<Message<B>>,
2053 future: Option<thread::JoinHandle<Result<CompiledModules, ()>>>,
2054 phantom: PhantomData<B>,
2056}
2057
2058impl<B: ExtraBackendMethods> Coordinator<B> {
2059 fn join(mut self) -> std::thread::Result<Result<CompiledModules, ()>> {
2060 self.future.take().unwrap().join()
2061 }
2062}
2063
2064impl<B: ExtraBackendMethods> Drop for Coordinator<B> {
2065 fn drop(&mut self) {
2066 if let Some(future) = self.future.take() {
2067 drop(self.sender.send(Message::CodegenAborted::<B>));
2070 drop(future.join());
2071 }
2072 }
2073}
2074
2075pub struct OngoingCodegen<B: ExtraBackendMethods> {
2076 pub backend: B,
2077 pub crate_info: CrateInfo,
2078 pub output_filenames: Arc<OutputFilenames>,
2079 pub coordinator: Coordinator<B>,
2083 pub codegen_worker_receive: Receiver<CguMessage>,
2084 pub shared_emitter_main: SharedEmitterMain,
2085}
2086
2087impl<B: ExtraBackendMethods> OngoingCodegen<B> {
2088 pub fn join(self, sess: &Session) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
2089 self.shared_emitter_main.check(sess, true);
2090 let compiled_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
2091 Ok(Ok(compiled_modules)) => compiled_modules,
2092 Ok(Err(())) => {
2093 sess.dcx().abort_if_errors();
2094 panic!("expected abort due to worker thread errors")
2095 }
2096 Err(_) => {
2097 bug!("panic during codegen/LLVM phase");
2098 }
2099 });
2100
2101 sess.dcx().abort_if_errors();
2102
2103 let work_products =
2104 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
2105 produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
2106
2107 if sess.codegen_units().as_usize() == 1 && sess.opts.unstable_opts.time_llvm_passes {
2110 self.backend.print_pass_timings()
2111 }
2112
2113 if sess.print_llvm_stats() {
2114 self.backend.print_statistics()
2115 }
2116
2117 (
2118 CodegenResults {
2119 crate_info: self.crate_info,
2120
2121 modules: compiled_modules.modules,
2122 allocator_module: compiled_modules.allocator_module,
2123 },
2124 work_products,
2125 )
2126 }
2127
2128 pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2129 self.wait_for_signal_to_codegen_item();
2130 self.check_for_errors(tcx.sess);
2131 drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
2132 }
2133
2134 pub(crate) fn check_for_errors(&self, sess: &Session) {
2135 self.shared_emitter_main.check(sess, false);
2136 }
2137
2138 pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2139 match self.codegen_worker_receive.recv() {
2140 Ok(CguMessage) => {
2141 }
2143 Err(_) => {
2144 }
2147 }
2148 }
2149}
2150
2151pub(crate) fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
2152 coordinator: &Coordinator<B>,
2153 module: ModuleCodegen<B::Module>,
2154 cost: u64,
2155) {
2156 let llvm_work_item = WorkItem::Optimize(module);
2157 drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2158}
2159
2160pub(crate) fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
2161 coordinator: &Coordinator<B>,
2162 module: CachedModuleCodegen,
2163) {
2164 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2165 drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2166}
2167
2168pub(crate) fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
2169 tcx: TyCtxt<'_>,
2170 coordinator: &Coordinator<B>,
2171 module: CachedModuleCodegen,
2172) {
2173 let filename = pre_lto_bitcode_filename(&module.name);
2174 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2175 let file = fs::File::open(&bc_path)
2176 .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
2177
2178 let mmap = unsafe {
2179 Mmap::map(file).unwrap_or_else(|e| {
2180 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2181 })
2182 };
2183 drop(coordinator.sender.send(Message::AddImportOnlyModule::<B> {
2185 module_data: SerializedModule::FromUncompressedFile(mmap),
2186 work_product: module.source,
2187 }));
2188}
2189
2190fn pre_lto_bitcode_filename(module_name: &str) -> String {
2191 format!("{module_name}.{PRE_LTO_BC_EXT}")
2192}
2193
2194fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2195 assert!(
2198 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2199 && tcx.sess.target.is_like_windows
2200 && tcx.sess.opts.cg.prefer_dynamic)
2201 );
2202
2203 let can_have_static_objects =
2207 tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
2208
2209 tcx.sess.target.is_like_windows &&
2210 can_have_static_objects &&
2211 !tcx.sess.opts.cg.linker_plugin_lto.enabled()
2215}