1use std::assert_matches::assert_matches;
2use std::marker::PhantomData;
3use std::path::{Path, PathBuf};
4use std::sync::Arc;
5use std::sync::mpsc::{Receiver, Sender, channel};
6use std::{fs, io, mem, str, thread};
7
8use rustc_abi::Size;
9use rustc_ast::attr;
10use rustc_ast::expand::autodiff_attrs::AutoDiffItem;
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, Level, MultiSpan, Style,
19 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::{AutodiffWithoutLto, 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 opt_size: Option<config::OptLevel>,
84
85 pub pgo_gen: SwitchWithOptPath,
86 pub pgo_use: Option<PathBuf>,
87 pub pgo_sample_use: Option<PathBuf>,
88 pub debug_info_for_profiling: bool,
89 pub instrument_coverage: bool,
90
91 pub sanitizer: SanitizerSet,
92 pub sanitizer_recover: SanitizerSet,
93 pub sanitizer_dataflow_abilist: Vec<String>,
94 pub sanitizer_memory_track_origins: usize,
95
96 pub emit_pre_lto_bc: bool,
98 pub emit_no_opt_bc: bool,
99 pub emit_bc: bool,
100 pub emit_ir: bool,
101 pub emit_asm: bool,
102 pub emit_obj: EmitObj,
103 pub emit_thin_lto: bool,
104 pub emit_thin_lto_summary: bool,
105 pub bc_cmdline: String,
106
107 pub verify_llvm_ir: bool,
110 pub lint_llvm_ir: bool,
111 pub no_prepopulate_passes: bool,
112 pub no_builtins: bool,
113 pub time_module: bool,
114 pub vectorize_loop: bool,
115 pub vectorize_slp: bool,
116 pub merge_functions: bool,
117 pub emit_lifetime_markers: bool,
118 pub llvm_plugins: Vec<String>,
119 pub autodiff: Vec<config::AutoDiff>,
120 pub offload: Vec<config::Offload>,
121}
122
123impl ModuleConfig {
124 fn new(kind: ModuleKind, tcx: TyCtxt<'_>, no_builtins: bool) -> ModuleConfig {
125 macro_rules! if_regular {
128 ($regular: expr, $other: expr) => {
129 if let ModuleKind::Regular = kind { $regular } else { $other }
130 };
131 }
132
133 let sess = tcx.sess;
134 let opt_level_and_size = if_regular!(Some(sess.opts.optimize), None);
135
136 let save_temps = sess.opts.cg.save_temps;
137
138 let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
139 || match kind {
140 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
141 ModuleKind::Allocator => false,
142 };
143
144 let emit_obj = if !should_emit_obj {
145 EmitObj::None
146 } else if sess.target.obj_is_bitcode
147 || (sess.opts.cg.linker_plugin_lto.enabled() && !no_builtins)
148 {
149 EmitObj::Bitcode
164 } else if need_bitcode_in_object(tcx) {
165 EmitObj::ObjectCode(BitcodeSection::Full)
166 } else {
167 EmitObj::ObjectCode(BitcodeSection::None)
168 };
169
170 ModuleConfig {
171 passes: if_regular!(sess.opts.cg.passes.clone(), vec![]),
172
173 opt_level: opt_level_and_size,
174 opt_size: opt_level_and_size,
175
176 pgo_gen: if_regular!(
177 sess.opts.cg.profile_generate.clone(),
178 SwitchWithOptPath::Disabled
179 ),
180 pgo_use: if_regular!(sess.opts.cg.profile_use.clone(), None),
181 pgo_sample_use: if_regular!(sess.opts.unstable_opts.profile_sample_use.clone(), None),
182 debug_info_for_profiling: sess.opts.unstable_opts.debug_info_for_profiling,
183 instrument_coverage: if_regular!(sess.instrument_coverage(), false),
184
185 sanitizer: if_regular!(sess.opts.unstable_opts.sanitizer, SanitizerSet::empty()),
186 sanitizer_dataflow_abilist: if_regular!(
187 sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
188 Vec::new()
189 ),
190 sanitizer_recover: if_regular!(
191 sess.opts.unstable_opts.sanitizer_recover,
192 SanitizerSet::empty()
193 ),
194 sanitizer_memory_track_origins: if_regular!(
195 sess.opts.unstable_opts.sanitizer_memory_track_origins,
196 0
197 ),
198
199 emit_pre_lto_bc: if_regular!(
200 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
201 false
202 ),
203 emit_no_opt_bc: if_regular!(save_temps, false),
204 emit_bc: if_regular!(
205 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
206 save_temps
207 ),
208 emit_ir: if_regular!(
209 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
210 false
211 ),
212 emit_asm: if_regular!(
213 sess.opts.output_types.contains_key(&OutputType::Assembly),
214 false
215 ),
216 emit_obj,
217 emit_thin_lto: sess.opts.unstable_opts.emit_thin_lto && sess.lto() != Lto::Fat,
220 emit_thin_lto_summary: if_regular!(
221 sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode),
222 false
223 ),
224 bc_cmdline: sess.target.bitcode_llvm_cmdline.to_string(),
225
226 verify_llvm_ir: sess.verify_llvm_ir(),
227 lint_llvm_ir: sess.opts.unstable_opts.lint_llvm_ir,
228 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
229 no_builtins: no_builtins || sess.target.no_builtins,
230
231 time_module: if_regular!(true, false),
234
235 vectorize_loop: !sess.opts.cg.no_vectorize_loops
238 && (sess.opts.optimize == config::OptLevel::More
239 || sess.opts.optimize == config::OptLevel::Aggressive),
240 vectorize_slp: !sess.opts.cg.no_vectorize_slp
241 && sess.opts.optimize == config::OptLevel::Aggressive,
242
243 merge_functions: match sess
253 .opts
254 .unstable_opts
255 .merge_functions
256 .unwrap_or(sess.target.merge_functions)
257 {
258 MergeFunctions::Disabled => false,
259 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
260 use config::OptLevel::*;
261 match sess.opts.optimize {
262 Aggressive | More | SizeMin | Size => true,
263 Less | No => false,
264 }
265 }
266 },
267
268 emit_lifetime_markers: sess.emit_lifetime_markers(),
269 llvm_plugins: if_regular!(sess.opts.unstable_opts.llvm_plugins.clone(), vec![]),
270 autodiff: if_regular!(sess.opts.unstable_opts.autodiff.clone(), vec![]),
271 offload: if_regular!(sess.opts.unstable_opts.offload.clone(), vec![]),
272 }
273 }
274
275 pub fn bitcode_needed(&self) -> bool {
276 self.emit_bc
277 || self.emit_thin_lto_summary
278 || self.emit_obj == EmitObj::Bitcode
279 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
280 }
281
282 pub fn embed_bitcode(&self) -> bool {
283 self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
284 }
285}
286
287pub struct TargetMachineFactoryConfig {
289 pub split_dwarf_file: Option<PathBuf>,
293
294 pub output_obj_file: Option<PathBuf>,
297}
298
299impl TargetMachineFactoryConfig {
300 pub fn new(
301 cgcx: &CodegenContext<impl WriteBackendMethods>,
302 module_name: &str,
303 ) -> TargetMachineFactoryConfig {
304 let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
305 cgcx.output_filenames.split_dwarf_path(
306 cgcx.split_debuginfo,
307 cgcx.split_dwarf_kind,
308 module_name,
309 cgcx.invocation_temp.as_deref(),
310 )
311 } else {
312 None
313 };
314
315 let output_obj_file = Some(cgcx.output_filenames.temp_path_for_cgu(
316 OutputType::Object,
317 module_name,
318 cgcx.invocation_temp.as_deref(),
319 ));
320 TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }
321 }
322}
323
324pub type TargetMachineFactoryFn<B> = Arc<
325 dyn Fn(
326 TargetMachineFactoryConfig,
327 ) -> Result<
328 <B as WriteBackendMethods>::TargetMachine,
329 <B as WriteBackendMethods>::TargetMachineError,
330 > + Send
331 + Sync,
332>;
333
334#[derive(Clone)]
336pub struct CodegenContext<B: WriteBackendMethods> {
337 pub prof: SelfProfilerRef,
339 pub lto: Lto,
340 pub save_temps: bool,
341 pub fewer_names: bool,
342 pub time_trace: bool,
343 pub opts: Arc<config::Options>,
344 pub crate_types: Vec<CrateType>,
345 pub output_filenames: Arc<OutputFilenames>,
346 pub invocation_temp: Option<String>,
347 pub regular_module_config: Arc<ModuleConfig>,
348 pub allocator_module_config: Arc<ModuleConfig>,
349 pub tm_factory: TargetMachineFactoryFn<B>,
350 pub msvc_imps_needed: bool,
351 pub is_pe_coff: bool,
352 pub target_can_use_split_dwarf: bool,
353 pub target_arch: String,
354 pub target_is_like_darwin: bool,
355 pub target_is_like_aix: bool,
356 pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
357 pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
358 pub pointer_size: Size,
359
360 pub expanded_args: Vec<String>,
365
366 pub diag_emitter: SharedEmitter,
368 pub remark: Passes,
370 pub remark_dir: Option<PathBuf>,
373 pub incr_comp_session_dir: Option<PathBuf>,
376 pub parallel: bool,
380}
381
382impl<B: WriteBackendMethods> CodegenContext<B> {
383 pub fn create_dcx(&self) -> DiagCtxt {
384 DiagCtxt::new(Box::new(self.diag_emitter.clone()))
385 }
386
387 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
388 match kind {
389 ModuleKind::Regular => &self.regular_module_config,
390 ModuleKind::Allocator => &self.allocator_module_config,
391 }
392 }
393}
394
395fn generate_thin_lto_work<B: ExtraBackendMethods>(
396 cgcx: &CodegenContext<B>,
397 exported_symbols_for_lto: &[String],
398 each_linked_rlib_for_lto: &[PathBuf],
399 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
400 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
401) -> Vec<(WorkItem<B>, u64)> {
402 let _prof_timer = cgcx.prof.generic_activity("codegen_thin_generate_lto_work");
403
404 let (lto_modules, copy_jobs) = B::run_thin_lto(
405 cgcx,
406 exported_symbols_for_lto,
407 each_linked_rlib_for_lto,
408 needs_thin_lto,
409 import_only_modules,
410 )
411 .unwrap_or_else(|e| e.raise());
412 lto_modules
413 .into_iter()
414 .map(|module| {
415 let cost = module.cost();
416 (WorkItem::ThinLto(module), cost)
417 })
418 .chain(copy_jobs.into_iter().map(|wp| {
419 (
420 WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
421 name: wp.cgu_name.clone(),
422 source: wp,
423 }),
424 0, )
426 }))
427 .collect()
428}
429
430struct CompiledModules {
431 modules: Vec<CompiledModule>,
432 allocator_module: Option<CompiledModule>,
433}
434
435fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
436 let sess = tcx.sess;
437 sess.opts.cg.embed_bitcode
438 && tcx.crate_types().contains(&CrateType::Rlib)
439 && sess.opts.output_types.contains_key(&OutputType::Exe)
440}
441
442fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
443 if sess.opts.incremental.is_none() {
444 return false;
445 }
446
447 match sess.lto() {
448 Lto::No => false,
449 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
450 }
451}
452
453pub(crate) fn start_async_codegen<B: ExtraBackendMethods>(
454 backend: B,
455 tcx: TyCtxt<'_>,
456 target_cpu: String,
457 autodiff_items: &[AutoDiffItem],
458) -> OngoingCodegen<B> {
459 let (coordinator_send, coordinator_receive) = channel();
460
461 let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
462 let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins);
463
464 let crate_info = CrateInfo::new(tcx, target_cpu);
465
466 let regular_config = ModuleConfig::new(ModuleKind::Regular, tcx, no_builtins);
467 let allocator_config = ModuleConfig::new(ModuleKind::Allocator, tcx, no_builtins);
468
469 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
470 let (codegen_worker_send, codegen_worker_receive) = channel();
471
472 let coordinator_thread = start_executing_work(
473 backend.clone(),
474 tcx,
475 &crate_info,
476 autodiff_items,
477 shared_emitter,
478 codegen_worker_send,
479 coordinator_receive,
480 Arc::new(regular_config),
481 Arc::new(allocator_config),
482 coordinator_send.clone(),
483 );
484
485 OngoingCodegen {
486 backend,
487 crate_info,
488
489 codegen_worker_receive,
490 shared_emitter_main,
491 coordinator: Coordinator {
492 sender: coordinator_send,
493 future: Some(coordinator_thread),
494 phantom: PhantomData,
495 },
496 output_filenames: Arc::clone(tcx.output_filenames(())),
497 }
498}
499
500fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
501 sess: &Session,
502 compiled_modules: &CompiledModules,
503) -> FxIndexMap<WorkProductId, WorkProduct> {
504 let mut work_products = FxIndexMap::default();
505
506 if sess.opts.incremental.is_none() {
507 return work_products;
508 }
509
510 let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
511
512 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
513 let mut files = Vec::new();
514 if let Some(object_file_path) = &module.object {
515 files.push((OutputType::Object.extension(), object_file_path.as_path()));
516 }
517 if let Some(dwarf_object_file_path) = &module.dwarf_object {
518 files.push(("dwo", dwarf_object_file_path.as_path()));
519 }
520 if let Some(path) = &module.assembly {
521 files.push((OutputType::Assembly.extension(), path.as_path()));
522 }
523 if let Some(path) = &module.llvm_ir {
524 files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
525 }
526 if let Some(path) = &module.bytecode {
527 files.push((OutputType::Bitcode.extension(), path.as_path()));
528 }
529 if let Some((id, product)) = copy_cgu_workproduct_to_incr_comp_cache_dir(
530 sess,
531 &module.name,
532 files.as_slice(),
533 &module.links_from_incr_cache,
534 ) {
535 work_products.insert(id, product);
536 }
537 }
538
539 work_products
540}
541
542fn produce_final_output_artifacts(
543 sess: &Session,
544 compiled_modules: &CompiledModules,
545 crate_output: &OutputFilenames,
546) {
547 let mut user_wants_bitcode = false;
548 let mut user_wants_objects = false;
549
550 let copy_gracefully = |from: &Path, to: &OutFileName| match to {
552 OutFileName::Stdout if let Err(e) = copy_to_stdout(from) => {
553 sess.dcx().emit_err(errors::CopyPath::new(from, to.as_path(), e));
554 }
555 OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
556 sess.dcx().emit_err(errors::CopyPath::new(from, path, e));
557 }
558 _ => {}
559 };
560
561 let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
562 if let [module] = &compiled_modules.modules[..] {
563 let path = crate_output.temp_path_for_cgu(
566 output_type,
567 &module.name,
568 sess.invocation_temp.as_deref(),
569 );
570 let output = crate_output.path(output_type);
571 if !output_type.is_text_output() && output.is_tty() {
572 sess.dcx()
573 .emit_err(errors::BinaryOutputToTty { shorthand: output_type.shorthand() });
574 } else {
575 copy_gracefully(&path, &output);
576 }
577 if !sess.opts.cg.save_temps && !keep_numbered {
578 ensure_removed(sess.dcx(), &path);
580 }
581 } else {
582 if crate_output.outputs.contains_explicit_name(&output_type) {
583 sess.dcx()
586 .emit_warn(errors::IgnoringEmitPath { extension: output_type.extension() });
587 } else if crate_output.single_output_file.is_some() {
588 sess.dcx().emit_warn(errors::IgnoringOutput { extension: output_type.extension() });
591 } else {
592 }
596 }
597 };
598
599 for output_type in crate_output.outputs.keys() {
603 match *output_type {
604 OutputType::Bitcode => {
605 user_wants_bitcode = true;
606 copy_if_one_unit(OutputType::Bitcode, true);
610 }
611 OutputType::ThinLinkBitcode => {
612 copy_if_one_unit(OutputType::ThinLinkBitcode, false);
613 }
614 OutputType::LlvmAssembly => {
615 copy_if_one_unit(OutputType::LlvmAssembly, false);
616 }
617 OutputType::Assembly => {
618 copy_if_one_unit(OutputType::Assembly, false);
619 }
620 OutputType::Object => {
621 user_wants_objects = true;
622 copy_if_one_unit(OutputType::Object, true);
623 }
624 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
625 }
626 }
627
628 if !sess.opts.cg.save_temps {
641 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
657
658 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
659
660 let keep_numbered_objects =
661 needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
662
663 for module in compiled_modules.modules.iter() {
664 if !keep_numbered_objects {
665 if let Some(ref path) = module.object {
666 ensure_removed(sess.dcx(), path);
667 }
668
669 if let Some(ref path) = module.dwarf_object {
670 ensure_removed(sess.dcx(), path);
671 }
672 }
673
674 if let Some(ref path) = module.bytecode {
675 if !keep_numbered_bitcode {
676 ensure_removed(sess.dcx(), path);
677 }
678 }
679 }
680
681 if !user_wants_bitcode
682 && let Some(ref allocator_module) = compiled_modules.allocator_module
683 && let Some(ref path) = allocator_module.bytecode
684 {
685 ensure_removed(sess.dcx(), path);
686 }
687 }
688
689 if sess.opts.json_artifact_notifications {
690 if let [module] = &compiled_modules.modules[..] {
691 module.for_each_output(|_path, ty| {
692 if sess.opts.output_types.contains_key(&ty) {
693 let descr = ty.shorthand();
694 let path = crate_output.path(ty);
697 sess.dcx().emit_artifact_notification(path.as_path(), descr);
698 }
699 });
700 } else {
701 for module in &compiled_modules.modules {
702 module.for_each_output(|path, ty| {
703 if sess.opts.output_types.contains_key(&ty) {
704 let descr = ty.shorthand();
705 sess.dcx().emit_artifact_notification(&path, descr);
706 }
707 });
708 }
709 }
710 }
711
712 }
718
719pub(crate) enum WorkItem<B: WriteBackendMethods> {
720 Optimize(ModuleCodegen<B::Module>),
722 CopyPostLtoArtifacts(CachedModuleCodegen),
725 FatLto {
727 exported_symbols_for_lto: Arc<Vec<String>>,
728 each_linked_rlib_for_lto: Vec<PathBuf>,
729 needs_fat_lto: Vec<FatLtoInput<B>>,
730 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
731 autodiff: Vec<AutoDiffItem>,
732 },
733 ThinLto(lto::ThinModule<B>),
735}
736
737impl<B: WriteBackendMethods> WorkItem<B> {
738 fn module_kind(&self) -> ModuleKind {
739 match *self {
740 WorkItem::Optimize(ref m) => m.kind,
741 WorkItem::CopyPostLtoArtifacts(_) | WorkItem::FatLto { .. } | WorkItem::ThinLto(_) => {
742 ModuleKind::Regular
743 }
744 }
745 }
746
747 fn short_description(&self) -> String {
749 #[cfg(not(windows))]
753 fn desc(short: &str, _long: &str, name: &str) -> String {
754 assert_eq!(short.len(), 3);
774 let name = if let Some(index) = name.find("-cgu.") {
775 &name[index + 1..] } else {
777 name
778 };
779 format!("{short} {name}")
780 }
781
782 #[cfg(windows)]
784 fn desc(_short: &str, long: &str, name: &str) -> String {
785 format!("{long} {name}")
786 }
787
788 match self {
789 WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
790 WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
791 WorkItem::FatLto { .. } => desc("lto", "fat LTO module", "everything"),
792 WorkItem::ThinLto(m) => desc("lto", "thin-LTO module", m.name()),
793 }
794 }
795}
796
797pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
799 Finished(CompiledModule),
801
802 NeedsFatLto(FatLtoInput<B>),
805
806 NeedsThinLto(String, B::ThinBuffer),
809}
810
811pub enum FatLtoInput<B: WriteBackendMethods> {
812 Serialized { name: String, buffer: SerializedModule<B::ModuleBuffer> },
813 InMemory(ModuleCodegen<B::Module>),
814}
815
816pub(crate) enum ComputedLtoType {
818 No,
819 Thin,
820 Fat,
821}
822
823pub(crate) fn compute_per_cgu_lto_type(
824 sess_lto: &Lto,
825 opts: &config::Options,
826 sess_crate_types: &[CrateType],
827 module_kind: ModuleKind,
828) -> ComputedLtoType {
829 let linker_does_lto = opts.cg.linker_plugin_lto.enabled();
833
834 let is_allocator = module_kind == ModuleKind::Allocator;
839
840 let is_rlib = matches!(sess_crate_types, [CrateType::Rlib]);
849
850 match sess_lto {
851 Lto::ThinLocal if !linker_does_lto && !is_allocator => ComputedLtoType::Thin,
852 Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
853 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
854 _ => ComputedLtoType::No,
855 }
856}
857
858fn execute_optimize_work_item<B: ExtraBackendMethods>(
859 cgcx: &CodegenContext<B>,
860 mut module: ModuleCodegen<B::Module>,
861 module_config: &ModuleConfig,
862) -> Result<WorkItemResult<B>, FatalError> {
863 let dcx = cgcx.create_dcx();
864 let dcx = dcx.handle();
865
866 B::optimize(cgcx, dcx, &mut module, module_config)?;
867
868 let lto_type = compute_per_cgu_lto_type(&cgcx.lto, &cgcx.opts, &cgcx.crate_types, module.kind);
874
875 let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
878 let filename = pre_lto_bitcode_filename(&module.name);
879 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
880 } else {
881 None
882 };
883
884 match lto_type {
885 ComputedLtoType::No => {
886 let module = B::codegen(cgcx, module, module_config)?;
887 Ok(WorkItemResult::Finished(module))
888 }
889 ComputedLtoType::Thin => {
890 let (name, thin_buffer) = B::prepare_thin(module, false);
891 if let Some(path) = bitcode {
892 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
893 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
894 });
895 }
896 Ok(WorkItemResult::NeedsThinLto(name, thin_buffer))
897 }
898 ComputedLtoType::Fat => match bitcode {
899 Some(path) => {
900 let (name, buffer) = B::serialize_module(module);
901 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
902 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
903 });
904 Ok(WorkItemResult::NeedsFatLto(FatLtoInput::Serialized {
905 name,
906 buffer: SerializedModule::Local(buffer),
907 }))
908 }
909 None => Ok(WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module))),
910 },
911 }
912}
913
914fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
915 cgcx: &CodegenContext<B>,
916 module: CachedModuleCodegen,
917 module_config: &ModuleConfig,
918) -> WorkItemResult<B> {
919 let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
920
921 let mut links_from_incr_cache = Vec::new();
922
923 let mut load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
924 let source_file = in_incr_comp_dir(incr_comp_session_dir, saved_path);
925 debug!(
926 "copying preexisting module `{}` from {:?} to {}",
927 module.name,
928 source_file,
929 output_path.display()
930 );
931 match link_or_copy(&source_file, &output_path) {
932 Ok(_) => {
933 links_from_incr_cache.push(source_file);
934 Some(output_path)
935 }
936 Err(error) => {
937 cgcx.create_dcx().handle().emit_err(errors::CopyPathBuf {
938 source_file,
939 output_path,
940 error,
941 });
942 None
943 }
944 }
945 };
946
947 let dwarf_object =
948 module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
949 let dwarf_obj_out = cgcx
950 .output_filenames
951 .split_dwarf_path(
952 cgcx.split_debuginfo,
953 cgcx.split_dwarf_kind,
954 &module.name,
955 cgcx.invocation_temp.as_deref(),
956 )
957 .expect(
958 "saved dwarf object in work product but `split_dwarf_path` returned `None`",
959 );
960 load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
961 });
962
963 let mut load_from_incr_cache = |perform, output_type: OutputType| {
964 if perform {
965 let saved_file = module.source.saved_files.get(output_type.extension())?;
966 let output_path = cgcx.output_filenames.temp_path_for_cgu(
967 output_type,
968 &module.name,
969 cgcx.invocation_temp.as_deref(),
970 );
971 load_from_incr_comp_dir(output_path, &saved_file)
972 } else {
973 None
974 }
975 };
976
977 let should_emit_obj = module_config.emit_obj != EmitObj::None;
978 let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
979 let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
980 let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
981 let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
982 if should_emit_obj && object.is_none() {
983 cgcx.create_dcx().handle().emit_fatal(errors::NoSavedObjectFile { cgu_name: &module.name })
984 }
985
986 WorkItemResult::Finished(CompiledModule {
987 links_from_incr_cache,
988 name: module.name,
989 kind: ModuleKind::Regular,
990 object,
991 dwarf_object,
992 bytecode,
993 assembly,
994 llvm_ir,
995 })
996}
997
998fn execute_fat_lto_work_item<B: ExtraBackendMethods>(
999 cgcx: &CodegenContext<B>,
1000 exported_symbols_for_lto: &[String],
1001 each_linked_rlib_for_lto: &[PathBuf],
1002 mut needs_fat_lto: Vec<FatLtoInput<B>>,
1003 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
1004 autodiff: Vec<AutoDiffItem>,
1005 module_config: &ModuleConfig,
1006) -> Result<WorkItemResult<B>, FatalError> {
1007 for (module, wp) in import_only_modules {
1008 needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, buffer: module })
1009 }
1010
1011 let module = B::run_and_optimize_fat_lto(
1012 cgcx,
1013 exported_symbols_for_lto,
1014 each_linked_rlib_for_lto,
1015 needs_fat_lto,
1016 autodiff,
1017 )?;
1018 let module = B::codegen(cgcx, module, module_config)?;
1019 Ok(WorkItemResult::Finished(module))
1020}
1021
1022fn execute_thin_lto_work_item<B: ExtraBackendMethods>(
1023 cgcx: &CodegenContext<B>,
1024 module: lto::ThinModule<B>,
1025 module_config: &ModuleConfig,
1026) -> Result<WorkItemResult<B>, FatalError> {
1027 let module = B::optimize_thin(cgcx, module)?;
1028 let module = B::codegen(cgcx, module, module_config)?;
1029 Ok(WorkItemResult::Finished(module))
1030}
1031
1032pub(crate) enum Message<B: WriteBackendMethods> {
1034 Token(io::Result<Acquired>),
1037
1038 WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>> },
1041
1042 CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
1046
1047 AddImportOnlyModule {
1050 module_data: SerializedModule<B::ModuleBuffer>,
1051 work_product: WorkProduct,
1052 },
1053
1054 CodegenComplete,
1057
1058 CodegenAborted,
1061}
1062
1063pub struct CguMessage;
1066
1067struct Diagnostic {
1077 level: Level,
1078 messages: Vec<(DiagMessage, Style)>,
1079 code: Option<ErrCode>,
1080 children: Vec<Subdiagnostic>,
1081 args: DiagArgMap,
1082}
1083
1084pub(crate) struct Subdiagnostic {
1088 level: Level,
1089 messages: Vec<(DiagMessage, Style)>,
1090}
1091
1092#[derive(PartialEq, Clone, Copy, Debug)]
1093enum MainThreadState {
1094 Idle,
1096
1097 Codegenning,
1099
1100 Lending,
1102}
1103
1104fn start_executing_work<B: ExtraBackendMethods>(
1105 backend: B,
1106 tcx: TyCtxt<'_>,
1107 crate_info: &CrateInfo,
1108 autodiff_items: &[AutoDiffItem],
1109 shared_emitter: SharedEmitter,
1110 codegen_worker_send: Sender<CguMessage>,
1111 coordinator_receive: Receiver<Message<B>>,
1112 regular_config: Arc<ModuleConfig>,
1113 allocator_config: Arc<ModuleConfig>,
1114 tx_to_llvm_workers: Sender<Message<B>>,
1115) -> thread::JoinHandle<Result<CompiledModules, ()>> {
1116 let coordinator_send = tx_to_llvm_workers;
1117 let sess = tcx.sess;
1118 let autodiff_items = autodiff_items.to_vec();
1119
1120 let mut each_linked_rlib_for_lto = Vec::new();
1121 let mut each_linked_rlib_file_for_lto = Vec::new();
1122 drop(link::each_linked_rlib(crate_info, None, &mut |cnum, path| {
1123 if link::ignored_for_lto(sess, crate_info, cnum) {
1124 return;
1125 }
1126 each_linked_rlib_for_lto.push(cnum);
1127 each_linked_rlib_file_for_lto.push(path.to_path_buf());
1128 }));
1129
1130 let exported_symbols_for_lto =
1132 Arc::new(lto::exported_symbols_for_lto(tcx, &each_linked_rlib_for_lto));
1133
1134 let coordinator_send2 = coordinator_send.clone();
1140 let helper = jobserver::client()
1141 .into_helper_thread(move |token| {
1142 drop(coordinator_send2.send(Message::Token::<B>(token)));
1143 })
1144 .expect("failed to spawn helper thread");
1145
1146 let ol =
1147 if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
1148 config::OptLevel::No
1150 } else {
1151 tcx.backend_optimization_level(())
1152 };
1153 let backend_features = tcx.global_backend_features(());
1154
1155 let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1156 let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1157 match result {
1158 Ok(dir) => Some(dir),
1159 Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1160 }
1161 } else {
1162 None
1163 };
1164
1165 let cgcx = CodegenContext::<B> {
1166 crate_types: tcx.crate_types().to_vec(),
1167 lto: sess.lto(),
1168 fewer_names: sess.fewer_names(),
1169 save_temps: sess.opts.cg.save_temps,
1170 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1171 opts: Arc::new(sess.opts.clone()),
1172 prof: sess.prof.clone(),
1173 remark: sess.opts.cg.remark.clone(),
1174 remark_dir,
1175 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1176 expanded_args: tcx.sess.expanded_args.clone(),
1177 diag_emitter: shared_emitter.clone(),
1178 output_filenames: Arc::clone(tcx.output_filenames(())),
1179 regular_module_config: regular_config,
1180 allocator_module_config: allocator_config,
1181 tm_factory: backend.target_machine_factory(tcx.sess, ol, backend_features),
1182 msvc_imps_needed: msvc_imps_needed(tcx),
1183 is_pe_coff: tcx.sess.target.is_like_windows,
1184 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1185 target_arch: tcx.sess.target.arch.to_string(),
1186 target_is_like_darwin: tcx.sess.target.is_like_darwin,
1187 target_is_like_aix: tcx.sess.target.is_like_aix,
1188 split_debuginfo: tcx.sess.split_debuginfo(),
1189 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1190 parallel: backend.supports_parallel() && !sess.opts.unstable_opts.no_parallel_backend,
1191 pointer_size: tcx.data_layout.pointer_size(),
1192 invocation_temp: sess.invocation_temp.clone(),
1193 };
1194
1195 return B::spawn_named_thread(cgcx.time_trace, "coordinator".to_string(), move || {
1331 let mut compiled_modules = vec![];
1334 let mut compiled_allocator_module = None;
1335 let mut needs_fat_lto = Vec::new();
1336 let mut needs_thin_lto = Vec::new();
1337 let mut lto_import_only_modules = Vec::new();
1338 let mut started_lto = false;
1339
1340 #[derive(Debug, PartialEq)]
1345 enum CodegenState {
1346 Ongoing,
1347 Completed,
1348 Aborted,
1349 }
1350 use CodegenState::*;
1351 let mut codegen_state = Ongoing;
1352
1353 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1355
1356 let mut tokens = Vec::new();
1359
1360 let mut main_thread_state = MainThreadState::Idle;
1361
1362 let mut running_with_own_token = 0;
1365
1366 let running_with_any_token = |main_thread_state, running_with_own_token| {
1369 running_with_own_token
1370 + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1371 };
1372
1373 let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
1374
1375 loop {
1381 if codegen_state == Ongoing {
1385 if main_thread_state == MainThreadState::Idle {
1386 let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1394 let additional_running = std::cmp::min(extra_tokens, work_items.len());
1395 let anticipated_running = running_with_own_token + additional_running + 1;
1396
1397 if !queue_full_enough(work_items.len(), anticipated_running) {
1398 if codegen_worker_send.send(CguMessage).is_err() {
1400 panic!("Could not send CguMessage to main thread")
1401 }
1402 main_thread_state = MainThreadState::Codegenning;
1403 } else {
1404 let (item, _) =
1408 work_items.pop().expect("queue empty - queue_full_enough() broken?");
1409 main_thread_state = MainThreadState::Lending;
1410 spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1411 }
1412 }
1413 } else if codegen_state == Completed {
1414 if running_with_any_token(main_thread_state, running_with_own_token) == 0
1415 && work_items.is_empty()
1416 {
1417 if needs_fat_lto.is_empty()
1419 && needs_thin_lto.is_empty()
1420 && lto_import_only_modules.is_empty()
1421 {
1422 break;
1424 }
1425
1426 assert!(!started_lto);
1432 started_lto = true;
1433
1434 let needs_fat_lto = mem::take(&mut needs_fat_lto);
1435 let needs_thin_lto = mem::take(&mut needs_thin_lto);
1436 let import_only_modules = mem::take(&mut lto_import_only_modules);
1437 let each_linked_rlib_file_for_lto =
1438 mem::take(&mut each_linked_rlib_file_for_lto);
1439
1440 check_lto_allowed(&cgcx);
1441
1442 if !needs_fat_lto.is_empty() {
1443 assert!(needs_thin_lto.is_empty());
1444
1445 work_items.push((
1446 WorkItem::FatLto {
1447 exported_symbols_for_lto: Arc::clone(&exported_symbols_for_lto),
1448 each_linked_rlib_for_lto: each_linked_rlib_file_for_lto,
1449 needs_fat_lto,
1450 import_only_modules,
1451 autodiff: autodiff_items.clone(),
1452 },
1453 0,
1454 ));
1455 if cgcx.parallel {
1456 helper.request_token();
1457 }
1458 } else {
1459 if !autodiff_items.is_empty() {
1460 let dcx = cgcx.create_dcx();
1461 dcx.handle().emit_fatal(AutodiffWithoutLto {});
1462 }
1463
1464 for (work, cost) in generate_thin_lto_work(
1465 &cgcx,
1466 &exported_symbols_for_lto,
1467 &each_linked_rlib_file_for_lto,
1468 needs_thin_lto,
1469 import_only_modules,
1470 ) {
1471 let insertion_index = work_items
1472 .binary_search_by_key(&cost, |&(_, cost)| cost)
1473 .unwrap_or_else(|e| e);
1474 work_items.insert(insertion_index, (work, cost));
1475 if cgcx.parallel {
1476 helper.request_token();
1477 }
1478 }
1479 }
1480 }
1481
1482 match main_thread_state {
1486 MainThreadState::Idle => {
1487 if let Some((item, _)) = work_items.pop() {
1488 main_thread_state = MainThreadState::Lending;
1489 spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1490 } else {
1491 assert!(running_with_own_token > 0);
1498 running_with_own_token -= 1;
1499 main_thread_state = MainThreadState::Lending;
1500 }
1501 }
1502 MainThreadState::Codegenning => bug!(
1503 "codegen worker should not be codegenning after \
1504 codegen was already completed"
1505 ),
1506 MainThreadState::Lending => {
1507 }
1509 }
1510 } else {
1511 assert!(codegen_state == Aborted);
1514 if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1515 break;
1516 }
1517 }
1518
1519 if codegen_state != Aborted {
1522 while running_with_own_token < tokens.len()
1523 && let Some((item, _)) = work_items.pop()
1524 {
1525 spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1526 running_with_own_token += 1;
1527 }
1528 }
1529
1530 tokens.truncate(running_with_own_token);
1532
1533 match coordinator_receive.recv().unwrap() {
1534 Message::Token(token) => {
1538 match token {
1539 Ok(token) => {
1540 tokens.push(token);
1541
1542 if main_thread_state == MainThreadState::Lending {
1543 main_thread_state = MainThreadState::Idle;
1548 running_with_own_token += 1;
1549 }
1550 }
1551 Err(e) => {
1552 let msg = &format!("failed to acquire jobserver token: {e}");
1553 shared_emitter.fatal(msg);
1554 codegen_state = Aborted;
1555 }
1556 }
1557 }
1558
1559 Message::CodegenDone { llvm_work_item, cost } => {
1560 let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1569 let insertion_index = match insertion_index {
1570 Ok(idx) | Err(idx) => idx,
1571 };
1572 work_items.insert(insertion_index, (llvm_work_item, cost));
1573
1574 if cgcx.parallel {
1575 helper.request_token();
1576 }
1577 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1578 main_thread_state = MainThreadState::Idle;
1579 }
1580
1581 Message::CodegenComplete => {
1582 if codegen_state != Aborted {
1583 codegen_state = Completed;
1584 }
1585 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1586 main_thread_state = MainThreadState::Idle;
1587 }
1588
1589 Message::CodegenAborted => {
1597 codegen_state = Aborted;
1598 }
1599
1600 Message::WorkItem { result } => {
1601 if main_thread_state == MainThreadState::Lending {
1607 main_thread_state = MainThreadState::Idle;
1608 } else {
1609 running_with_own_token -= 1;
1610 }
1611
1612 match result {
1613 Ok(WorkItemResult::Finished(compiled_module)) => {
1614 match compiled_module.kind {
1615 ModuleKind::Regular => {
1616 compiled_modules.push(compiled_module);
1617 }
1618 ModuleKind::Allocator => {
1619 assert!(compiled_allocator_module.is_none());
1620 compiled_allocator_module = Some(compiled_module);
1621 }
1622 }
1623 }
1624 Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1625 assert!(!started_lto);
1626 assert!(needs_thin_lto.is_empty());
1627 needs_fat_lto.push(fat_lto_input);
1628 }
1629 Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1630 assert!(!started_lto);
1631 assert!(needs_fat_lto.is_empty());
1632 needs_thin_lto.push((name, thin_buffer));
1633 }
1634 Err(Some(WorkerFatalError)) => {
1635 codegen_state = Aborted;
1637 }
1638 Err(None) => {
1639 bug!("worker thread panicked");
1642 }
1643 }
1644 }
1645
1646 Message::AddImportOnlyModule { module_data, work_product } => {
1647 assert!(!started_lto);
1648 assert_eq!(codegen_state, Ongoing);
1649 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1650 lto_import_only_modules.push((module_data, work_product));
1651 main_thread_state = MainThreadState::Idle;
1652 }
1653 }
1654 }
1655
1656 if codegen_state == Aborted {
1657 return Err(());
1658 }
1659
1660 drop(llvm_start_time);
1662
1663 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1667
1668 Ok(CompiledModules {
1669 modules: compiled_modules,
1670 allocator_module: compiled_allocator_module,
1671 })
1672 })
1673 .expect("failed to spawn coordinator thread");
1674
1675 fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1678 let quarter_of_workers = workers_running - 3 * workers_running / 4;
1729 items_in_queue > 0 && items_in_queue >= quarter_of_workers
1730 }
1731}
1732
1733#[must_use]
1735pub(crate) struct WorkerFatalError;
1736
1737fn spawn_work<'a, B: ExtraBackendMethods>(
1738 cgcx: &'a CodegenContext<B>,
1739 coordinator_send: Sender<Message<B>>,
1740 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1741 work: WorkItem<B>,
1742) {
1743 if cgcx.config(work.module_kind()).time_module && llvm_start_time.is_none() {
1744 *llvm_start_time = Some(cgcx.prof.verbose_generic_activity("LLVM_passes"));
1745 }
1746
1747 let cgcx = cgcx.clone();
1748
1749 B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1750 struct Bomb<B: ExtraBackendMethods> {
1753 coordinator_send: Sender<Message<B>>,
1754 result: Option<Result<WorkItemResult<B>, FatalError>>,
1755 }
1756 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1757 fn drop(&mut self) {
1758 let msg = match self.result.take() {
1759 Some(Ok(result)) => Message::WorkItem::<B> { result: Ok(result) },
1760 Some(Err(FatalError)) => {
1761 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1762 }
1763 None => Message::WorkItem::<B> { result: Err(None) },
1764 };
1765 drop(self.coordinator_send.send(msg));
1766 }
1767 }
1768
1769 let mut bomb = Bomb::<B> { coordinator_send, result: None };
1770
1771 bomb.result = {
1778 let module_config = cgcx.config(work.module_kind());
1779
1780 Some(match work {
1781 WorkItem::Optimize(m) => {
1782 let _timer =
1783 cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &*m.name);
1784 execute_optimize_work_item(&cgcx, m, module_config)
1785 }
1786 WorkItem::CopyPostLtoArtifacts(m) => {
1787 let _timer = cgcx.prof.generic_activity_with_arg(
1788 "codegen_copy_artifacts_from_incr_cache",
1789 &*m.name,
1790 );
1791 Ok(execute_copy_from_cache_work_item(&cgcx, m, module_config))
1792 }
1793 WorkItem::FatLto {
1794 exported_symbols_for_lto,
1795 each_linked_rlib_for_lto,
1796 needs_fat_lto,
1797 import_only_modules,
1798 autodiff,
1799 } => {
1800 let _timer = cgcx
1801 .prof
1802 .generic_activity_with_arg("codegen_module_perform_lto", "everything");
1803 execute_fat_lto_work_item(
1804 &cgcx,
1805 &exported_symbols_for_lto,
1806 &each_linked_rlib_for_lto,
1807 needs_fat_lto,
1808 import_only_modules,
1809 autodiff,
1810 module_config,
1811 )
1812 }
1813 WorkItem::ThinLto(m) => {
1814 let _timer =
1815 cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", m.name());
1816 execute_thin_lto_work_item(&cgcx, m, module_config)
1817 }
1818 })
1819 };
1820 })
1821 .expect("failed to spawn work thread");
1822}
1823
1824enum SharedEmitterMessage {
1825 Diagnostic(Diagnostic),
1826 InlineAsmError(SpanData, String, Level, Option<(String, Vec<InnerSpan>)>),
1827 Fatal(String),
1828}
1829
1830#[derive(Clone)]
1831pub struct SharedEmitter {
1832 sender: Sender<SharedEmitterMessage>,
1833}
1834
1835pub struct SharedEmitterMain {
1836 receiver: Receiver<SharedEmitterMessage>,
1837}
1838
1839impl SharedEmitter {
1840 fn new() -> (SharedEmitter, SharedEmitterMain) {
1841 let (sender, receiver) = channel();
1842
1843 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1844 }
1845
1846 pub fn inline_asm_error(
1847 &self,
1848 span: SpanData,
1849 msg: String,
1850 level: Level,
1851 source: Option<(String, Vec<InnerSpan>)>,
1852 ) {
1853 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(span, msg, level, source)));
1854 }
1855
1856 fn fatal(&self, msg: &str) {
1857 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1858 }
1859}
1860
1861impl Emitter for SharedEmitter {
1862 fn emit_diagnostic(
1863 &mut self,
1864 mut diag: rustc_errors::DiagInner,
1865 _registry: &rustc_errors::registry::Registry,
1866 ) {
1867 assert_eq!(diag.span, MultiSpan::new());
1870 assert_eq!(diag.suggestions, Suggestions::Enabled(vec![]));
1871 assert_eq!(diag.sort_span, rustc_span::DUMMY_SP);
1872 assert_eq!(diag.is_lint, None);
1873 let args = mem::replace(&mut diag.args, DiagArgMap::default());
1876 drop(
1877 self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1878 level: diag.level(),
1879 messages: diag.messages,
1880 code: diag.code,
1881 children: diag
1882 .children
1883 .into_iter()
1884 .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
1885 .collect(),
1886 args,
1887 })),
1888 );
1889 }
1890
1891 fn source_map(&self) -> Option<&SourceMap> {
1892 None
1893 }
1894
1895 fn translator(&self) -> &Translator {
1896 panic!("shared emitter attempted to translate a diagnostic");
1897 }
1898}
1899
1900impl SharedEmitterMain {
1901 fn check(&self, sess: &Session, blocking: bool) {
1902 loop {
1903 let message = if blocking {
1904 match self.receiver.recv() {
1905 Ok(message) => Ok(message),
1906 Err(_) => Err(()),
1907 }
1908 } else {
1909 match self.receiver.try_recv() {
1910 Ok(message) => Ok(message),
1911 Err(_) => Err(()),
1912 }
1913 };
1914
1915 match message {
1916 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1917 let dcx = sess.dcx();
1920 let mut d =
1921 rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
1922 d.code = diag.code; d.children = diag
1924 .children
1925 .into_iter()
1926 .map(|sub| rustc_errors::Subdiag {
1927 level: sub.level,
1928 messages: sub.messages,
1929 span: MultiSpan::new(),
1930 })
1931 .collect();
1932 d.args = diag.args;
1933 dcx.emit_diagnostic(d);
1934 sess.dcx().abort_if_errors();
1935 }
1936 Ok(SharedEmitterMessage::InlineAsmError(span, msg, level, source)) => {
1937 assert_matches!(level, Level::Error | Level::Warning | Level::Note);
1938 let mut err = Diag::<()>::new(sess.dcx(), level, msg);
1939 if !span.is_dummy() {
1940 err.span(span.span());
1941 }
1942
1943 if let Some((buffer, spans)) = source {
1945 let source = sess
1946 .source_map()
1947 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
1948 let spans: Vec<_> = spans
1949 .iter()
1950 .map(|sp| {
1951 Span::with_root_ctxt(
1952 source.normalized_byte_pos(sp.start as u32),
1953 source.normalized_byte_pos(sp.end as u32),
1954 )
1955 })
1956 .collect();
1957 err.span_note(spans, "instantiated into assembly here");
1958 }
1959
1960 err.emit();
1961 }
1962 Ok(SharedEmitterMessage::Fatal(msg)) => {
1963 sess.dcx().fatal(msg);
1964 }
1965 Err(_) => {
1966 break;
1967 }
1968 }
1969 }
1970 }
1971}
1972
1973pub struct Coordinator<B: ExtraBackendMethods> {
1974 sender: Sender<Message<B>>,
1975 future: Option<thread::JoinHandle<Result<CompiledModules, ()>>>,
1976 phantom: PhantomData<B>,
1978}
1979
1980impl<B: ExtraBackendMethods> Coordinator<B> {
1981 fn join(mut self) -> std::thread::Result<Result<CompiledModules, ()>> {
1982 self.future.take().unwrap().join()
1983 }
1984}
1985
1986impl<B: ExtraBackendMethods> Drop for Coordinator<B> {
1987 fn drop(&mut self) {
1988 if let Some(future) = self.future.take() {
1989 drop(self.sender.send(Message::CodegenAborted::<B>));
1992 drop(future.join());
1993 }
1994 }
1995}
1996
1997pub struct OngoingCodegen<B: ExtraBackendMethods> {
1998 pub backend: B,
1999 pub crate_info: CrateInfo,
2000 pub codegen_worker_receive: Receiver<CguMessage>,
2001 pub shared_emitter_main: SharedEmitterMain,
2002 pub output_filenames: Arc<OutputFilenames>,
2003 pub coordinator: Coordinator<B>,
2004}
2005
2006impl<B: ExtraBackendMethods> OngoingCodegen<B> {
2007 pub fn join(self, sess: &Session) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
2008 self.shared_emitter_main.check(sess, true);
2009 let compiled_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
2010 Ok(Ok(compiled_modules)) => compiled_modules,
2011 Ok(Err(())) => {
2012 sess.dcx().abort_if_errors();
2013 panic!("expected abort due to worker thread errors")
2014 }
2015 Err(_) => {
2016 bug!("panic during codegen/LLVM phase");
2017 }
2018 });
2019
2020 sess.dcx().abort_if_errors();
2021
2022 let work_products =
2023 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
2024 produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
2025
2026 if sess.codegen_units().as_usize() == 1 && sess.opts.unstable_opts.time_llvm_passes {
2029 self.backend.print_pass_timings()
2030 }
2031
2032 if sess.print_llvm_stats() {
2033 self.backend.print_statistics()
2034 }
2035
2036 (
2037 CodegenResults {
2038 crate_info: self.crate_info,
2039
2040 modules: compiled_modules.modules,
2041 allocator_module: compiled_modules.allocator_module,
2042 },
2043 work_products,
2044 )
2045 }
2046
2047 pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2048 self.wait_for_signal_to_codegen_item();
2049 self.check_for_errors(tcx.sess);
2050 drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
2051 }
2052
2053 pub(crate) fn check_for_errors(&self, sess: &Session) {
2054 self.shared_emitter_main.check(sess, false);
2055 }
2056
2057 pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2058 match self.codegen_worker_receive.recv() {
2059 Ok(CguMessage) => {
2060 }
2062 Err(_) => {
2063 }
2066 }
2067 }
2068}
2069
2070pub(crate) fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
2071 coordinator: &Coordinator<B>,
2072 module: ModuleCodegen<B::Module>,
2073 cost: u64,
2074) {
2075 let llvm_work_item = WorkItem::Optimize(module);
2076 drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2077}
2078
2079pub(crate) fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
2080 coordinator: &Coordinator<B>,
2081 module: CachedModuleCodegen,
2082) {
2083 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2084 drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2085}
2086
2087pub(crate) fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
2088 tcx: TyCtxt<'_>,
2089 coordinator: &Coordinator<B>,
2090 module: CachedModuleCodegen,
2091) {
2092 let filename = pre_lto_bitcode_filename(&module.name);
2093 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2094 let file = fs::File::open(&bc_path)
2095 .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
2096
2097 let mmap = unsafe {
2098 Mmap::map(file).unwrap_or_else(|e| {
2099 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2100 })
2101 };
2102 drop(coordinator.sender.send(Message::AddImportOnlyModule::<B> {
2104 module_data: SerializedModule::FromUncompressedFile(mmap),
2105 work_product: module.source,
2106 }));
2107}
2108
2109fn pre_lto_bitcode_filename(module_name: &str) -> String {
2110 format!("{module_name}.{PRE_LTO_BC_EXT}")
2111}
2112
2113fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2114 assert!(
2117 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2118 && tcx.sess.target.is_like_windows
2119 && tcx.sess.opts.cg.prefer_dynamic)
2120 );
2121
2122 let can_have_static_objects =
2126 tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
2127
2128 tcx.sess.target.is_like_windows &&
2129 can_have_static_objects &&
2130 !tcx.sess.opts.cg.linker_plugin_lto.enabled()
2134}