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_data_structures::fx::FxIndexMap;
11use rustc_data_structures::jobserver::{self, Acquired};
12use rustc_data_structures::memmap::Mmap;
13use rustc_data_structures::profiling::{SelfProfilerRef, VerboseTimingGuard};
14use rustc_errors::emitter::Emitter;
15use rustc_errors::translation::Translator;
16use rustc_errors::{
17 Diag, DiagArgMap, DiagCtxt, DiagMessage, ErrCode, FatalError, Level, MultiSpan, Style,
18 Suggestions,
19};
20use rustc_fs_util::link_or_copy;
21use rustc_incremental::{
22 copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess,
23};
24use rustc_metadata::fs::copy_to_stdout;
25use rustc_middle::bug;
26use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
27use rustc_middle::ty::TyCtxt;
28use rustc_session::Session;
29use rustc_session::config::{
30 self, CrateType, Lto, OutFileName, OutputFilenames, OutputType, Passes, SwitchWithOptPath,
31};
32use rustc_span::source_map::SourceMap;
33use rustc_span::{FileName, InnerSpan, Span, SpanData, sym};
34use rustc_target::spec::{MergeFunctions, SanitizerSet};
35use tracing::debug;
36
37use super::link::{self, ensure_removed};
38use super::lto::{self, SerializedModule};
39use crate::back::lto::check_lto_allowed;
40use crate::errors::ErrorCreatingRemarkDir;
41use crate::traits::*;
42use crate::{
43 CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
44 errors,
45};
46
47const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
48
49#[derive(Clone, Copy, PartialEq)]
51pub enum EmitObj {
52 None,
54
55 Bitcode,
58
59 ObjectCode(BitcodeSection),
61}
62
63#[derive(Clone, Copy, PartialEq)]
65pub enum BitcodeSection {
66 None,
68
69 Full,
71}
72
73pub struct ModuleConfig {
75 pub passes: Vec<String>,
77 pub opt_level: Option<config::OptLevel>,
80
81 pub pgo_gen: SwitchWithOptPath,
82 pub pgo_use: Option<PathBuf>,
83 pub pgo_sample_use: Option<PathBuf>,
84 pub debug_info_for_profiling: bool,
85 pub instrument_coverage: bool,
86
87 pub sanitizer: SanitizerSet,
88 pub sanitizer_recover: SanitizerSet,
89 pub sanitizer_dataflow_abilist: Vec<String>,
90 pub sanitizer_memory_track_origins: usize,
91
92 pub emit_pre_lto_bc: bool,
94 pub emit_no_opt_bc: bool,
95 pub emit_bc: bool,
96 pub emit_ir: bool,
97 pub emit_asm: bool,
98 pub emit_obj: EmitObj,
99 pub emit_thin_lto: bool,
100 pub emit_thin_lto_summary: bool,
101
102 pub verify_llvm_ir: bool,
105 pub lint_llvm_ir: bool,
106 pub no_prepopulate_passes: bool,
107 pub no_builtins: bool,
108 pub vectorize_loop: bool,
109 pub vectorize_slp: bool,
110 pub merge_functions: bool,
111 pub emit_lifetime_markers: bool,
112 pub llvm_plugins: Vec<String>,
113 pub autodiff: Vec<config::AutoDiff>,
114 pub offload: Vec<config::Offload>,
115}
116
117impl ModuleConfig {
118 fn new(kind: ModuleKind, tcx: TyCtxt<'_>, no_builtins: bool) -> ModuleConfig {
119 macro_rules! if_regular {
122 ($regular: expr, $other: expr) => {
123 if let ModuleKind::Regular = kind { $regular } else { $other }
124 };
125 }
126
127 let sess = tcx.sess;
128 let opt_level_and_size = if_regular!(Some(sess.opts.optimize), None);
129
130 let save_temps = sess.opts.cg.save_temps;
131
132 let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
133 || match kind {
134 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
135 ModuleKind::Allocator => false,
136 };
137
138 let emit_obj = if !should_emit_obj {
139 EmitObj::None
140 } else if sess.target.obj_is_bitcode
141 || (sess.opts.cg.linker_plugin_lto.enabled() && !no_builtins)
142 {
143 EmitObj::Bitcode
158 } else if need_bitcode_in_object(tcx) {
159 EmitObj::ObjectCode(BitcodeSection::Full)
160 } else {
161 EmitObj::ObjectCode(BitcodeSection::None)
162 };
163
164 ModuleConfig {
165 passes: if_regular!(sess.opts.cg.passes.clone(), vec![]),
166
167 opt_level: opt_level_and_size,
168
169 pgo_gen: if_regular!(
170 sess.opts.cg.profile_generate.clone(),
171 SwitchWithOptPath::Disabled
172 ),
173 pgo_use: if_regular!(sess.opts.cg.profile_use.clone(), None),
174 pgo_sample_use: if_regular!(sess.opts.unstable_opts.profile_sample_use.clone(), None),
175 debug_info_for_profiling: sess.opts.unstable_opts.debug_info_for_profiling,
176 instrument_coverage: if_regular!(sess.instrument_coverage(), false),
177
178 sanitizer: if_regular!(sess.opts.unstable_opts.sanitizer, SanitizerSet::empty()),
179 sanitizer_dataflow_abilist: if_regular!(
180 sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
181 Vec::new()
182 ),
183 sanitizer_recover: if_regular!(
184 sess.opts.unstable_opts.sanitizer_recover,
185 SanitizerSet::empty()
186 ),
187 sanitizer_memory_track_origins: if_regular!(
188 sess.opts.unstable_opts.sanitizer_memory_track_origins,
189 0
190 ),
191
192 emit_pre_lto_bc: if_regular!(
193 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
194 false
195 ),
196 emit_no_opt_bc: if_regular!(save_temps, false),
197 emit_bc: if_regular!(
198 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
199 save_temps
200 ),
201 emit_ir: if_regular!(
202 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
203 false
204 ),
205 emit_asm: if_regular!(
206 sess.opts.output_types.contains_key(&OutputType::Assembly),
207 false
208 ),
209 emit_obj,
210 emit_thin_lto: sess.opts.unstable_opts.emit_thin_lto && sess.lto() != Lto::Fat,
213 emit_thin_lto_summary: if_regular!(
214 sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode),
215 false
216 ),
217
218 verify_llvm_ir: sess.verify_llvm_ir(),
219 lint_llvm_ir: sess.opts.unstable_opts.lint_llvm_ir,
220 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
221 no_builtins: no_builtins || sess.target.no_builtins,
222
223 vectorize_loop: !sess.opts.cg.no_vectorize_loops
226 && (sess.opts.optimize == config::OptLevel::More
227 || sess.opts.optimize == config::OptLevel::Aggressive),
228 vectorize_slp: !sess.opts.cg.no_vectorize_slp
229 && sess.opts.optimize == config::OptLevel::Aggressive,
230
231 merge_functions: match sess
241 .opts
242 .unstable_opts
243 .merge_functions
244 .unwrap_or(sess.target.merge_functions)
245 {
246 MergeFunctions::Disabled => false,
247 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
248 use config::OptLevel::*;
249 match sess.opts.optimize {
250 Aggressive | More | SizeMin | Size => true,
251 Less | No => false,
252 }
253 }
254 },
255
256 emit_lifetime_markers: sess.emit_lifetime_markers(),
257 llvm_plugins: if_regular!(sess.opts.unstable_opts.llvm_plugins.clone(), vec![]),
258 autodiff: if_regular!(sess.opts.unstable_opts.autodiff.clone(), vec![]),
259 offload: if_regular!(sess.opts.unstable_opts.offload.clone(), vec![]),
260 }
261 }
262
263 pub fn bitcode_needed(&self) -> bool {
264 self.emit_bc
265 || self.emit_thin_lto_summary
266 || self.emit_obj == EmitObj::Bitcode
267 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
268 }
269
270 pub fn embed_bitcode(&self) -> bool {
271 self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
272 }
273}
274
275pub struct TargetMachineFactoryConfig {
277 pub split_dwarf_file: Option<PathBuf>,
281
282 pub output_obj_file: Option<PathBuf>,
285}
286
287impl TargetMachineFactoryConfig {
288 pub fn new(
289 cgcx: &CodegenContext<impl WriteBackendMethods>,
290 module_name: &str,
291 ) -> TargetMachineFactoryConfig {
292 let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
293 cgcx.output_filenames.split_dwarf_path(
294 cgcx.split_debuginfo,
295 cgcx.split_dwarf_kind,
296 module_name,
297 cgcx.invocation_temp.as_deref(),
298 )
299 } else {
300 None
301 };
302
303 let output_obj_file = Some(cgcx.output_filenames.temp_path_for_cgu(
304 OutputType::Object,
305 module_name,
306 cgcx.invocation_temp.as_deref(),
307 ));
308 TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }
309 }
310}
311
312pub type TargetMachineFactoryFn<B> = Arc<
313 dyn Fn(
314 TargetMachineFactoryConfig,
315 ) -> Result<
316 <B as WriteBackendMethods>::TargetMachine,
317 <B as WriteBackendMethods>::TargetMachineError,
318 > + Send
319 + Sync,
320>;
321
322#[derive(Clone)]
324pub struct CodegenContext<B: WriteBackendMethods> {
325 pub prof: SelfProfilerRef,
327 pub lto: Lto,
328 pub save_temps: bool,
329 pub fewer_names: bool,
330 pub time_trace: bool,
331 pub opts: Arc<config::Options>,
332 pub crate_types: Vec<CrateType>,
333 pub output_filenames: Arc<OutputFilenames>,
334 pub invocation_temp: Option<String>,
335 pub regular_module_config: Arc<ModuleConfig>,
336 pub allocator_module_config: Arc<ModuleConfig>,
337 pub tm_factory: TargetMachineFactoryFn<B>,
338 pub msvc_imps_needed: bool,
339 pub is_pe_coff: bool,
340 pub target_can_use_split_dwarf: bool,
341 pub target_arch: String,
342 pub target_is_like_darwin: bool,
343 pub target_is_like_aix: bool,
344 pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
345 pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
346 pub pointer_size: Size,
347
348 pub expanded_args: Vec<String>,
353
354 pub diag_emitter: SharedEmitter,
356 pub remark: Passes,
358 pub remark_dir: Option<PathBuf>,
361 pub incr_comp_session_dir: Option<PathBuf>,
364 pub parallel: bool,
368}
369
370impl<B: WriteBackendMethods> CodegenContext<B> {
371 pub fn create_dcx(&self) -> DiagCtxt {
372 DiagCtxt::new(Box::new(self.diag_emitter.clone()))
373 }
374
375 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
376 match kind {
377 ModuleKind::Regular => &self.regular_module_config,
378 ModuleKind::Allocator => &self.allocator_module_config,
379 }
380 }
381}
382
383fn generate_thin_lto_work<B: ExtraBackendMethods>(
384 cgcx: &CodegenContext<B>,
385 exported_symbols_for_lto: &[String],
386 each_linked_rlib_for_lto: &[PathBuf],
387 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
388 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
389) -> Vec<(WorkItem<B>, u64)> {
390 let _prof_timer = cgcx.prof.generic_activity("codegen_thin_generate_lto_work");
391
392 let (lto_modules, copy_jobs) = B::run_thin_lto(
393 cgcx,
394 exported_symbols_for_lto,
395 each_linked_rlib_for_lto,
396 needs_thin_lto,
397 import_only_modules,
398 )
399 .unwrap_or_else(|e| e.raise());
400 lto_modules
401 .into_iter()
402 .map(|module| {
403 let cost = module.cost();
404 (WorkItem::ThinLto(module), cost)
405 })
406 .chain(copy_jobs.into_iter().map(|wp| {
407 (
408 WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
409 name: wp.cgu_name.clone(),
410 source: wp,
411 }),
412 0, )
414 }))
415 .collect()
416}
417
418struct CompiledModules {
419 modules: Vec<CompiledModule>,
420 allocator_module: Option<CompiledModule>,
421}
422
423fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
424 let sess = tcx.sess;
425 sess.opts.cg.embed_bitcode
426 && tcx.crate_types().contains(&CrateType::Rlib)
427 && sess.opts.output_types.contains_key(&OutputType::Exe)
428}
429
430fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
431 if sess.opts.incremental.is_none() {
432 return false;
433 }
434
435 match sess.lto() {
436 Lto::No => false,
437 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
438 }
439}
440
441pub(crate) fn start_async_codegen<B: ExtraBackendMethods>(
442 backend: B,
443 tcx: TyCtxt<'_>,
444 target_cpu: String,
445) -> OngoingCodegen<B> {
446 let (coordinator_send, coordinator_receive) = channel();
447
448 let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
449 let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins);
450
451 let crate_info = CrateInfo::new(tcx, target_cpu);
452
453 let regular_config = ModuleConfig::new(ModuleKind::Regular, tcx, no_builtins);
454 let allocator_config = ModuleConfig::new(ModuleKind::Allocator, tcx, no_builtins);
455
456 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
457 let (codegen_worker_send, codegen_worker_receive) = channel();
458
459 let coordinator_thread = start_executing_work(
460 backend.clone(),
461 tcx,
462 &crate_info,
463 shared_emitter,
464 codegen_worker_send,
465 coordinator_receive,
466 Arc::new(regular_config),
467 Arc::new(allocator_config),
468 coordinator_send.clone(),
469 );
470
471 OngoingCodegen {
472 backend,
473 crate_info,
474
475 codegen_worker_receive,
476 shared_emitter_main,
477 coordinator: Coordinator {
478 sender: coordinator_send,
479 future: Some(coordinator_thread),
480 phantom: PhantomData,
481 },
482 output_filenames: Arc::clone(tcx.output_filenames(())),
483 }
484}
485
486fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
487 sess: &Session,
488 compiled_modules: &CompiledModules,
489) -> FxIndexMap<WorkProductId, WorkProduct> {
490 let mut work_products = FxIndexMap::default();
491
492 if sess.opts.incremental.is_none() {
493 return work_products;
494 }
495
496 let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
497
498 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
499 let mut files = Vec::new();
500 if let Some(object_file_path) = &module.object {
501 files.push((OutputType::Object.extension(), object_file_path.as_path()));
502 }
503 if let Some(dwarf_object_file_path) = &module.dwarf_object {
504 files.push(("dwo", dwarf_object_file_path.as_path()));
505 }
506 if let Some(path) = &module.assembly {
507 files.push((OutputType::Assembly.extension(), path.as_path()));
508 }
509 if let Some(path) = &module.llvm_ir {
510 files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
511 }
512 if let Some(path) = &module.bytecode {
513 files.push((OutputType::Bitcode.extension(), path.as_path()));
514 }
515 if let Some((id, product)) = copy_cgu_workproduct_to_incr_comp_cache_dir(
516 sess,
517 &module.name,
518 files.as_slice(),
519 &module.links_from_incr_cache,
520 ) {
521 work_products.insert(id, product);
522 }
523 }
524
525 work_products
526}
527
528fn produce_final_output_artifacts(
529 sess: &Session,
530 compiled_modules: &CompiledModules,
531 crate_output: &OutputFilenames,
532) {
533 let mut user_wants_bitcode = false;
534 let mut user_wants_objects = false;
535
536 let copy_gracefully = |from: &Path, to: &OutFileName| match to {
538 OutFileName::Stdout if let Err(e) = copy_to_stdout(from) => {
539 sess.dcx().emit_err(errors::CopyPath::new(from, to.as_path(), e));
540 }
541 OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
542 sess.dcx().emit_err(errors::CopyPath::new(from, path, e));
543 }
544 _ => {}
545 };
546
547 let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
548 if let [module] = &compiled_modules.modules[..] {
549 let path = crate_output.temp_path_for_cgu(
552 output_type,
553 &module.name,
554 sess.invocation_temp.as_deref(),
555 );
556 let output = crate_output.path(output_type);
557 if !output_type.is_text_output() && output.is_tty() {
558 sess.dcx()
559 .emit_err(errors::BinaryOutputToTty { shorthand: output_type.shorthand() });
560 } else {
561 copy_gracefully(&path, &output);
562 }
563 if !sess.opts.cg.save_temps && !keep_numbered {
564 ensure_removed(sess.dcx(), &path);
566 }
567 } else {
568 if crate_output.outputs.contains_explicit_name(&output_type) {
569 sess.dcx()
572 .emit_warn(errors::IgnoringEmitPath { extension: output_type.extension() });
573 } else if crate_output.single_output_file.is_some() {
574 sess.dcx().emit_warn(errors::IgnoringOutput { extension: output_type.extension() });
577 } else {
578 }
582 }
583 };
584
585 for output_type in crate_output.outputs.keys() {
589 match *output_type {
590 OutputType::Bitcode => {
591 user_wants_bitcode = true;
592 copy_if_one_unit(OutputType::Bitcode, true);
596 }
597 OutputType::ThinLinkBitcode => {
598 copy_if_one_unit(OutputType::ThinLinkBitcode, false);
599 }
600 OutputType::LlvmAssembly => {
601 copy_if_one_unit(OutputType::LlvmAssembly, false);
602 }
603 OutputType::Assembly => {
604 copy_if_one_unit(OutputType::Assembly, false);
605 }
606 OutputType::Object => {
607 user_wants_objects = true;
608 copy_if_one_unit(OutputType::Object, true);
609 }
610 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
611 }
612 }
613
614 if !sess.opts.cg.save_temps {
627 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
643
644 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
645
646 let keep_numbered_objects =
647 needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
648
649 for module in compiled_modules.modules.iter() {
650 if !keep_numbered_objects {
651 if let Some(ref path) = module.object {
652 ensure_removed(sess.dcx(), path);
653 }
654
655 if let Some(ref path) = module.dwarf_object {
656 ensure_removed(sess.dcx(), path);
657 }
658 }
659
660 if let Some(ref path) = module.bytecode {
661 if !keep_numbered_bitcode {
662 ensure_removed(sess.dcx(), path);
663 }
664 }
665 }
666
667 if !user_wants_bitcode
668 && let Some(ref allocator_module) = compiled_modules.allocator_module
669 && let Some(ref path) = allocator_module.bytecode
670 {
671 ensure_removed(sess.dcx(), path);
672 }
673 }
674
675 if sess.opts.json_artifact_notifications {
676 if let [module] = &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 let path = crate_output.path(ty);
683 sess.dcx().emit_artifact_notification(path.as_path(), descr);
684 }
685 });
686 } else {
687 for module in &compiled_modules.modules {
688 module.for_each_output(|path, ty| {
689 if sess.opts.output_types.contains_key(&ty) {
690 let descr = ty.shorthand();
691 sess.dcx().emit_artifact_notification(&path, descr);
692 }
693 });
694 }
695 }
696 }
697
698 }
704
705pub(crate) enum WorkItem<B: WriteBackendMethods> {
706 Optimize(ModuleCodegen<B::Module>),
708 CopyPostLtoArtifacts(CachedModuleCodegen),
711 FatLto {
713 exported_symbols_for_lto: Arc<Vec<String>>,
714 each_linked_rlib_for_lto: Vec<PathBuf>,
715 needs_fat_lto: Vec<FatLtoInput<B>>,
716 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
717 },
718 ThinLto(lto::ThinModule<B>),
720}
721
722impl<B: WriteBackendMethods> WorkItem<B> {
723 fn module_kind(&self) -> ModuleKind {
724 match *self {
725 WorkItem::Optimize(ref m) => m.kind,
726 WorkItem::CopyPostLtoArtifacts(_) | WorkItem::FatLto { .. } | WorkItem::ThinLto(_) => {
727 ModuleKind::Regular
728 }
729 }
730 }
731
732 fn short_description(&self) -> String {
734 #[cfg(not(windows))]
738 fn desc(short: &str, _long: &str, name: &str) -> String {
739 assert_eq!(short.len(), 3);
759 let name = if let Some(index) = name.find("-cgu.") {
760 &name[index + 1..] } else {
762 name
763 };
764 format!("{short} {name}")
765 }
766
767 #[cfg(windows)]
769 fn desc(_short: &str, long: &str, name: &str) -> String {
770 format!("{long} {name}")
771 }
772
773 match self {
774 WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
775 WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
776 WorkItem::FatLto { .. } => desc("lto", "fat LTO module", "everything"),
777 WorkItem::ThinLto(m) => desc("lto", "thin-LTO module", m.name()),
778 }
779 }
780}
781
782pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
784 Finished(CompiledModule),
786
787 NeedsFatLto(FatLtoInput<B>),
790
791 NeedsThinLto(String, B::ThinBuffer),
794}
795
796pub enum FatLtoInput<B: WriteBackendMethods> {
797 Serialized { name: String, buffer: SerializedModule<B::ModuleBuffer> },
798 InMemory(ModuleCodegen<B::Module>),
799}
800
801pub(crate) enum ComputedLtoType {
803 No,
804 Thin,
805 Fat,
806}
807
808pub(crate) fn compute_per_cgu_lto_type(
809 sess_lto: &Lto,
810 opts: &config::Options,
811 sess_crate_types: &[CrateType],
812 module_kind: ModuleKind,
813) -> ComputedLtoType {
814 let linker_does_lto = opts.cg.linker_plugin_lto.enabled();
818
819 let is_allocator = module_kind == ModuleKind::Allocator;
824
825 let is_rlib = matches!(sess_crate_types, [CrateType::Rlib]);
834
835 match sess_lto {
836 Lto::ThinLocal if !linker_does_lto && !is_allocator => ComputedLtoType::Thin,
837 Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
838 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
839 _ => ComputedLtoType::No,
840 }
841}
842
843fn execute_optimize_work_item<B: ExtraBackendMethods>(
844 cgcx: &CodegenContext<B>,
845 mut module: ModuleCodegen<B::Module>,
846 module_config: &ModuleConfig,
847) -> Result<WorkItemResult<B>, FatalError> {
848 let dcx = cgcx.create_dcx();
849 let dcx = dcx.handle();
850
851 B::optimize(cgcx, dcx, &mut module, module_config)?;
852
853 let lto_type = compute_per_cgu_lto_type(&cgcx.lto, &cgcx.opts, &cgcx.crate_types, module.kind);
859
860 let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
863 let filename = pre_lto_bitcode_filename(&module.name);
864 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
865 } else {
866 None
867 };
868
869 match lto_type {
870 ComputedLtoType::No => {
871 let module = B::codegen(cgcx, module, module_config)?;
872 Ok(WorkItemResult::Finished(module))
873 }
874 ComputedLtoType::Thin => {
875 let (name, thin_buffer) = B::prepare_thin(module, false);
876 if let Some(path) = bitcode {
877 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
878 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
879 });
880 }
881 Ok(WorkItemResult::NeedsThinLto(name, thin_buffer))
882 }
883 ComputedLtoType::Fat => match bitcode {
884 Some(path) => {
885 let (name, buffer) = B::serialize_module(module);
886 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
887 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
888 });
889 Ok(WorkItemResult::NeedsFatLto(FatLtoInput::Serialized {
890 name,
891 buffer: SerializedModule::Local(buffer),
892 }))
893 }
894 None => Ok(WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module))),
895 },
896 }
897}
898
899fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
900 cgcx: &CodegenContext<B>,
901 module: CachedModuleCodegen,
902 module_config: &ModuleConfig,
903) -> WorkItemResult<B> {
904 let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
905
906 let mut links_from_incr_cache = Vec::new();
907
908 let mut load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
909 let source_file = in_incr_comp_dir(incr_comp_session_dir, saved_path);
910 debug!(
911 "copying preexisting module `{}` from {:?} to {}",
912 module.name,
913 source_file,
914 output_path.display()
915 );
916 match link_or_copy(&source_file, &output_path) {
917 Ok(_) => {
918 links_from_incr_cache.push(source_file);
919 Some(output_path)
920 }
921 Err(error) => {
922 cgcx.create_dcx().handle().emit_err(errors::CopyPathBuf {
923 source_file,
924 output_path,
925 error,
926 });
927 None
928 }
929 }
930 };
931
932 let dwarf_object =
933 module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
934 let dwarf_obj_out = cgcx
935 .output_filenames
936 .split_dwarf_path(
937 cgcx.split_debuginfo,
938 cgcx.split_dwarf_kind,
939 &module.name,
940 cgcx.invocation_temp.as_deref(),
941 )
942 .expect(
943 "saved dwarf object in work product but `split_dwarf_path` returned `None`",
944 );
945 load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
946 });
947
948 let mut load_from_incr_cache = |perform, output_type: OutputType| {
949 if perform {
950 let saved_file = module.source.saved_files.get(output_type.extension())?;
951 let output_path = cgcx.output_filenames.temp_path_for_cgu(
952 output_type,
953 &module.name,
954 cgcx.invocation_temp.as_deref(),
955 );
956 load_from_incr_comp_dir(output_path, &saved_file)
957 } else {
958 None
959 }
960 };
961
962 let should_emit_obj = module_config.emit_obj != EmitObj::None;
963 let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
964 let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
965 let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
966 let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
967 if should_emit_obj && object.is_none() {
968 cgcx.create_dcx().handle().emit_fatal(errors::NoSavedObjectFile { cgu_name: &module.name })
969 }
970
971 WorkItemResult::Finished(CompiledModule {
972 links_from_incr_cache,
973 name: module.name,
974 kind: ModuleKind::Regular,
975 object,
976 dwarf_object,
977 bytecode,
978 assembly,
979 llvm_ir,
980 })
981}
982
983fn execute_fat_lto_work_item<B: ExtraBackendMethods>(
984 cgcx: &CodegenContext<B>,
985 exported_symbols_for_lto: &[String],
986 each_linked_rlib_for_lto: &[PathBuf],
987 mut needs_fat_lto: Vec<FatLtoInput<B>>,
988 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
989 module_config: &ModuleConfig,
990) -> Result<WorkItemResult<B>, FatalError> {
991 for (module, wp) in import_only_modules {
992 needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, buffer: module })
993 }
994
995 let module = B::run_and_optimize_fat_lto(
996 cgcx,
997 exported_symbols_for_lto,
998 each_linked_rlib_for_lto,
999 needs_fat_lto,
1000 )?;
1001 let module = B::codegen(cgcx, module, module_config)?;
1002 Ok(WorkItemResult::Finished(module))
1003}
1004
1005fn execute_thin_lto_work_item<B: ExtraBackendMethods>(
1006 cgcx: &CodegenContext<B>,
1007 module: lto::ThinModule<B>,
1008 module_config: &ModuleConfig,
1009) -> Result<WorkItemResult<B>, FatalError> {
1010 let module = B::optimize_thin(cgcx, module)?;
1011 let module = B::codegen(cgcx, module, module_config)?;
1012 Ok(WorkItemResult::Finished(module))
1013}
1014
1015pub(crate) enum Message<B: WriteBackendMethods> {
1017 Token(io::Result<Acquired>),
1020
1021 WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>> },
1024
1025 CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
1029
1030 AddImportOnlyModule {
1033 module_data: SerializedModule<B::ModuleBuffer>,
1034 work_product: WorkProduct,
1035 },
1036
1037 CodegenComplete,
1040
1041 CodegenAborted,
1044}
1045
1046pub struct CguMessage;
1049
1050struct Diagnostic {
1060 level: Level,
1061 messages: Vec<(DiagMessage, Style)>,
1062 code: Option<ErrCode>,
1063 children: Vec<Subdiagnostic>,
1064 args: DiagArgMap,
1065}
1066
1067pub(crate) struct Subdiagnostic {
1071 level: Level,
1072 messages: Vec<(DiagMessage, Style)>,
1073}
1074
1075#[derive(PartialEq, Clone, Copy, Debug)]
1076enum MainThreadState {
1077 Idle,
1079
1080 Codegenning,
1082
1083 Lending,
1085}
1086
1087fn start_executing_work<B: ExtraBackendMethods>(
1088 backend: B,
1089 tcx: TyCtxt<'_>,
1090 crate_info: &CrateInfo,
1091 shared_emitter: SharedEmitter,
1092 codegen_worker_send: Sender<CguMessage>,
1093 coordinator_receive: Receiver<Message<B>>,
1094 regular_config: Arc<ModuleConfig>,
1095 allocator_config: Arc<ModuleConfig>,
1096 tx_to_llvm_workers: Sender<Message<B>>,
1097) -> thread::JoinHandle<Result<CompiledModules, ()>> {
1098 let coordinator_send = tx_to_llvm_workers;
1099 let sess = tcx.sess;
1100
1101 let mut each_linked_rlib_for_lto = Vec::new();
1102 let mut each_linked_rlib_file_for_lto = Vec::new();
1103 drop(link::each_linked_rlib(crate_info, None, &mut |cnum, path| {
1104 if link::ignored_for_lto(sess, crate_info, cnum) {
1105 return;
1106 }
1107 each_linked_rlib_for_lto.push(cnum);
1108 each_linked_rlib_file_for_lto.push(path.to_path_buf());
1109 }));
1110
1111 let exported_symbols_for_lto =
1113 Arc::new(lto::exported_symbols_for_lto(tcx, &each_linked_rlib_for_lto));
1114
1115 let coordinator_send2 = coordinator_send.clone();
1121 let helper = jobserver::client()
1122 .into_helper_thread(move |token| {
1123 drop(coordinator_send2.send(Message::Token::<B>(token)));
1124 })
1125 .expect("failed to spawn helper thread");
1126
1127 let ol =
1128 if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
1129 config::OptLevel::No
1131 } else {
1132 tcx.backend_optimization_level(())
1133 };
1134 let backend_features = tcx.global_backend_features(());
1135
1136 let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1137 let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1138 match result {
1139 Ok(dir) => Some(dir),
1140 Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1141 }
1142 } else {
1143 None
1144 };
1145
1146 let cgcx = CodegenContext::<B> {
1147 crate_types: tcx.crate_types().to_vec(),
1148 lto: sess.lto(),
1149 fewer_names: sess.fewer_names(),
1150 save_temps: sess.opts.cg.save_temps,
1151 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1152 opts: Arc::new(sess.opts.clone()),
1153 prof: sess.prof.clone(),
1154 remark: sess.opts.cg.remark.clone(),
1155 remark_dir,
1156 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1157 expanded_args: tcx.sess.expanded_args.clone(),
1158 diag_emitter: shared_emitter.clone(),
1159 output_filenames: Arc::clone(tcx.output_filenames(())),
1160 regular_module_config: regular_config,
1161 allocator_module_config: allocator_config,
1162 tm_factory: backend.target_machine_factory(tcx.sess, ol, backend_features),
1163 msvc_imps_needed: msvc_imps_needed(tcx),
1164 is_pe_coff: tcx.sess.target.is_like_windows,
1165 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1166 target_arch: tcx.sess.target.arch.to_string(),
1167 target_is_like_darwin: tcx.sess.target.is_like_darwin,
1168 target_is_like_aix: tcx.sess.target.is_like_aix,
1169 split_debuginfo: tcx.sess.split_debuginfo(),
1170 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1171 parallel: backend.supports_parallel() && !sess.opts.unstable_opts.no_parallel_backend,
1172 pointer_size: tcx.data_layout.pointer_size(),
1173 invocation_temp: sess.invocation_temp.clone(),
1174 };
1175
1176 return B::spawn_named_thread(cgcx.time_trace, "coordinator".to_string(), move || {
1312 let mut compiled_modules = vec![];
1315 let mut compiled_allocator_module = None;
1316 let mut needs_fat_lto = Vec::new();
1317 let mut needs_thin_lto = Vec::new();
1318 let mut lto_import_only_modules = Vec::new();
1319 let mut started_lto = false;
1320
1321 #[derive(Debug, PartialEq)]
1326 enum CodegenState {
1327 Ongoing,
1328 Completed,
1329 Aborted,
1330 }
1331 use CodegenState::*;
1332 let mut codegen_state = Ongoing;
1333
1334 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1336
1337 let mut tokens = Vec::new();
1340
1341 let mut main_thread_state = MainThreadState::Idle;
1342
1343 let mut running_with_own_token = 0;
1346
1347 let running_with_any_token = |main_thread_state, running_with_own_token| {
1350 running_with_own_token
1351 + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1352 };
1353
1354 let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
1355
1356 loop {
1362 if codegen_state == Ongoing {
1366 if main_thread_state == MainThreadState::Idle {
1367 let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1375 let additional_running = std::cmp::min(extra_tokens, work_items.len());
1376 let anticipated_running = running_with_own_token + additional_running + 1;
1377
1378 if !queue_full_enough(work_items.len(), anticipated_running) {
1379 if codegen_worker_send.send(CguMessage).is_err() {
1381 panic!("Could not send CguMessage to main thread")
1382 }
1383 main_thread_state = MainThreadState::Codegenning;
1384 } else {
1385 let (item, _) =
1389 work_items.pop().expect("queue empty - queue_full_enough() broken?");
1390 main_thread_state = MainThreadState::Lending;
1391 spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1392 }
1393 }
1394 } else if codegen_state == Completed {
1395 if running_with_any_token(main_thread_state, running_with_own_token) == 0
1396 && work_items.is_empty()
1397 {
1398 if needs_fat_lto.is_empty()
1400 && needs_thin_lto.is_empty()
1401 && lto_import_only_modules.is_empty()
1402 {
1403 break;
1405 }
1406
1407 assert!(!started_lto);
1413 started_lto = true;
1414
1415 let needs_fat_lto = mem::take(&mut needs_fat_lto);
1416 let needs_thin_lto = mem::take(&mut needs_thin_lto);
1417 let import_only_modules = mem::take(&mut lto_import_only_modules);
1418 let each_linked_rlib_file_for_lto =
1419 mem::take(&mut each_linked_rlib_file_for_lto);
1420
1421 check_lto_allowed(&cgcx);
1422
1423 if !needs_fat_lto.is_empty() {
1424 assert!(needs_thin_lto.is_empty());
1425
1426 work_items.push((
1427 WorkItem::FatLto {
1428 exported_symbols_for_lto: Arc::clone(&exported_symbols_for_lto),
1429 each_linked_rlib_for_lto: each_linked_rlib_file_for_lto,
1430 needs_fat_lto,
1431 import_only_modules,
1432 },
1433 0,
1434 ));
1435 if cgcx.parallel {
1436 helper.request_token();
1437 }
1438 } else {
1439 for (work, cost) in generate_thin_lto_work(
1440 &cgcx,
1441 &exported_symbols_for_lto,
1442 &each_linked_rlib_file_for_lto,
1443 needs_thin_lto,
1444 import_only_modules,
1445 ) {
1446 let insertion_index = work_items
1447 .binary_search_by_key(&cost, |&(_, cost)| cost)
1448 .unwrap_or_else(|e| e);
1449 work_items.insert(insertion_index, (work, cost));
1450 if cgcx.parallel {
1451 helper.request_token();
1452 }
1453 }
1454 }
1455 }
1456
1457 match main_thread_state {
1461 MainThreadState::Idle => {
1462 if let Some((item, _)) = work_items.pop() {
1463 main_thread_state = MainThreadState::Lending;
1464 spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1465 } else {
1466 assert!(running_with_own_token > 0);
1473 running_with_own_token -= 1;
1474 main_thread_state = MainThreadState::Lending;
1475 }
1476 }
1477 MainThreadState::Codegenning => bug!(
1478 "codegen worker should not be codegenning after \
1479 codegen was already completed"
1480 ),
1481 MainThreadState::Lending => {
1482 }
1484 }
1485 } else {
1486 assert!(codegen_state == Aborted);
1489 if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1490 break;
1491 }
1492 }
1493
1494 if codegen_state != Aborted {
1497 while running_with_own_token < tokens.len()
1498 && let Some((item, _)) = work_items.pop()
1499 {
1500 spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1501 running_with_own_token += 1;
1502 }
1503 }
1504
1505 tokens.truncate(running_with_own_token);
1507
1508 match coordinator_receive.recv().unwrap() {
1509 Message::Token(token) => {
1513 match token {
1514 Ok(token) => {
1515 tokens.push(token);
1516
1517 if main_thread_state == MainThreadState::Lending {
1518 main_thread_state = MainThreadState::Idle;
1523 running_with_own_token += 1;
1524 }
1525 }
1526 Err(e) => {
1527 let msg = &format!("failed to acquire jobserver token: {e}");
1528 shared_emitter.fatal(msg);
1529 codegen_state = Aborted;
1530 }
1531 }
1532 }
1533
1534 Message::CodegenDone { llvm_work_item, cost } => {
1535 let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1544 let insertion_index = match insertion_index {
1545 Ok(idx) | Err(idx) => idx,
1546 };
1547 work_items.insert(insertion_index, (llvm_work_item, cost));
1548
1549 if cgcx.parallel {
1550 helper.request_token();
1551 }
1552 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1553 main_thread_state = MainThreadState::Idle;
1554 }
1555
1556 Message::CodegenComplete => {
1557 if codegen_state != Aborted {
1558 codegen_state = Completed;
1559 }
1560 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1561 main_thread_state = MainThreadState::Idle;
1562 }
1563
1564 Message::CodegenAborted => {
1572 codegen_state = Aborted;
1573 }
1574
1575 Message::WorkItem { result } => {
1576 if main_thread_state == MainThreadState::Lending {
1582 main_thread_state = MainThreadState::Idle;
1583 } else {
1584 running_with_own_token -= 1;
1585 }
1586
1587 match result {
1588 Ok(WorkItemResult::Finished(compiled_module)) => {
1589 match compiled_module.kind {
1590 ModuleKind::Regular => {
1591 compiled_modules.push(compiled_module);
1592 }
1593 ModuleKind::Allocator => {
1594 assert!(compiled_allocator_module.is_none());
1595 compiled_allocator_module = Some(compiled_module);
1596 }
1597 }
1598 }
1599 Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1600 assert!(!started_lto);
1601 assert!(needs_thin_lto.is_empty());
1602 needs_fat_lto.push(fat_lto_input);
1603 }
1604 Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1605 assert!(!started_lto);
1606 assert!(needs_fat_lto.is_empty());
1607 needs_thin_lto.push((name, thin_buffer));
1608 }
1609 Err(Some(WorkerFatalError)) => {
1610 codegen_state = Aborted;
1612 }
1613 Err(None) => {
1614 bug!("worker thread panicked");
1617 }
1618 }
1619 }
1620
1621 Message::AddImportOnlyModule { module_data, work_product } => {
1622 assert!(!started_lto);
1623 assert_eq!(codegen_state, Ongoing);
1624 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1625 lto_import_only_modules.push((module_data, work_product));
1626 main_thread_state = MainThreadState::Idle;
1627 }
1628 }
1629 }
1630
1631 if codegen_state == Aborted {
1632 return Err(());
1633 }
1634
1635 drop(llvm_start_time);
1637
1638 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1642
1643 Ok(CompiledModules {
1644 modules: compiled_modules,
1645 allocator_module: compiled_allocator_module,
1646 })
1647 })
1648 .expect("failed to spawn coordinator thread");
1649
1650 fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1653 let quarter_of_workers = workers_running - 3 * workers_running / 4;
1704 items_in_queue > 0 && items_in_queue >= quarter_of_workers
1705 }
1706}
1707
1708#[must_use]
1710pub(crate) struct WorkerFatalError;
1711
1712fn spawn_work<'a, B: ExtraBackendMethods>(
1713 cgcx: &'a CodegenContext<B>,
1714 coordinator_send: Sender<Message<B>>,
1715 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1716 work: WorkItem<B>,
1717) {
1718 if llvm_start_time.is_none() {
1719 *llvm_start_time = Some(cgcx.prof.verbose_generic_activity("LLVM_passes"));
1720 }
1721
1722 let cgcx = cgcx.clone();
1723
1724 B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1725 struct Bomb<B: ExtraBackendMethods> {
1728 coordinator_send: Sender<Message<B>>,
1729 result: Option<Result<WorkItemResult<B>, FatalError>>,
1730 }
1731 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1732 fn drop(&mut self) {
1733 let msg = match self.result.take() {
1734 Some(Ok(result)) => Message::WorkItem::<B> { result: Ok(result) },
1735 Some(Err(FatalError)) => {
1736 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1737 }
1738 None => Message::WorkItem::<B> { result: Err(None) },
1739 };
1740 drop(self.coordinator_send.send(msg));
1741 }
1742 }
1743
1744 let mut bomb = Bomb::<B> { coordinator_send, result: None };
1745
1746 bomb.result = {
1753 let module_config = cgcx.config(work.module_kind());
1754
1755 Some(match work {
1756 WorkItem::Optimize(m) => {
1757 let _timer =
1758 cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &*m.name);
1759 execute_optimize_work_item(&cgcx, m, module_config)
1760 }
1761 WorkItem::CopyPostLtoArtifacts(m) => {
1762 let _timer = cgcx.prof.generic_activity_with_arg(
1763 "codegen_copy_artifacts_from_incr_cache",
1764 &*m.name,
1765 );
1766 Ok(execute_copy_from_cache_work_item(&cgcx, m, module_config))
1767 }
1768 WorkItem::FatLto {
1769 exported_symbols_for_lto,
1770 each_linked_rlib_for_lto,
1771 needs_fat_lto,
1772 import_only_modules,
1773 } => {
1774 let _timer = cgcx
1775 .prof
1776 .generic_activity_with_arg("codegen_module_perform_lto", "everything");
1777 execute_fat_lto_work_item(
1778 &cgcx,
1779 &exported_symbols_for_lto,
1780 &each_linked_rlib_for_lto,
1781 needs_fat_lto,
1782 import_only_modules,
1783 module_config,
1784 )
1785 }
1786 WorkItem::ThinLto(m) => {
1787 let _timer =
1788 cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", m.name());
1789 execute_thin_lto_work_item(&cgcx, m, module_config)
1790 }
1791 })
1792 };
1793 })
1794 .expect("failed to spawn work thread");
1795}
1796
1797enum SharedEmitterMessage {
1798 Diagnostic(Diagnostic),
1799 InlineAsmError(SpanData, String, Level, Option<(String, Vec<InnerSpan>)>),
1800 Fatal(String),
1801}
1802
1803#[derive(Clone)]
1804pub struct SharedEmitter {
1805 sender: Sender<SharedEmitterMessage>,
1806}
1807
1808pub struct SharedEmitterMain {
1809 receiver: Receiver<SharedEmitterMessage>,
1810}
1811
1812impl SharedEmitter {
1813 fn new() -> (SharedEmitter, SharedEmitterMain) {
1814 let (sender, receiver) = channel();
1815
1816 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1817 }
1818
1819 pub fn inline_asm_error(
1820 &self,
1821 span: SpanData,
1822 msg: String,
1823 level: Level,
1824 source: Option<(String, Vec<InnerSpan>)>,
1825 ) {
1826 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(span, msg, level, source)));
1827 }
1828
1829 fn fatal(&self, msg: &str) {
1830 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1831 }
1832}
1833
1834impl Emitter for SharedEmitter {
1835 fn emit_diagnostic(
1836 &mut self,
1837 mut diag: rustc_errors::DiagInner,
1838 _registry: &rustc_errors::registry::Registry,
1839 ) {
1840 assert_eq!(diag.span, MultiSpan::new());
1843 assert_eq!(diag.suggestions, Suggestions::Enabled(vec![]));
1844 assert_eq!(diag.sort_span, rustc_span::DUMMY_SP);
1845 assert_eq!(diag.is_lint, None);
1846 let args = mem::replace(&mut diag.args, DiagArgMap::default());
1849 drop(
1850 self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1851 level: diag.level(),
1852 messages: diag.messages,
1853 code: diag.code,
1854 children: diag
1855 .children
1856 .into_iter()
1857 .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
1858 .collect(),
1859 args,
1860 })),
1861 );
1862 }
1863
1864 fn source_map(&self) -> Option<&SourceMap> {
1865 None
1866 }
1867
1868 fn translator(&self) -> &Translator {
1869 panic!("shared emitter attempted to translate a diagnostic");
1870 }
1871}
1872
1873impl SharedEmitterMain {
1874 fn check(&self, sess: &Session, blocking: bool) {
1875 loop {
1876 let message = if blocking {
1877 match self.receiver.recv() {
1878 Ok(message) => Ok(message),
1879 Err(_) => Err(()),
1880 }
1881 } else {
1882 match self.receiver.try_recv() {
1883 Ok(message) => Ok(message),
1884 Err(_) => Err(()),
1885 }
1886 };
1887
1888 match message {
1889 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1890 let dcx = sess.dcx();
1893 let mut d =
1894 rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
1895 d.code = diag.code; d.children = diag
1897 .children
1898 .into_iter()
1899 .map(|sub| rustc_errors::Subdiag {
1900 level: sub.level,
1901 messages: sub.messages,
1902 span: MultiSpan::new(),
1903 })
1904 .collect();
1905 d.args = diag.args;
1906 dcx.emit_diagnostic(d);
1907 sess.dcx().abort_if_errors();
1908 }
1909 Ok(SharedEmitterMessage::InlineAsmError(span, msg, level, source)) => {
1910 assert_matches!(level, Level::Error | Level::Warning | Level::Note);
1911 let mut err = Diag::<()>::new(sess.dcx(), level, msg);
1912 if !span.is_dummy() {
1913 err.span(span.span());
1914 }
1915
1916 if let Some((buffer, spans)) = source {
1918 let source = sess
1919 .source_map()
1920 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
1921 let spans: Vec<_> = spans
1922 .iter()
1923 .map(|sp| {
1924 Span::with_root_ctxt(
1925 source.normalized_byte_pos(sp.start as u32),
1926 source.normalized_byte_pos(sp.end as u32),
1927 )
1928 })
1929 .collect();
1930 err.span_note(spans, "instantiated into assembly here");
1931 }
1932
1933 err.emit();
1934 }
1935 Ok(SharedEmitterMessage::Fatal(msg)) => {
1936 sess.dcx().fatal(msg);
1937 }
1938 Err(_) => {
1939 break;
1940 }
1941 }
1942 }
1943 }
1944}
1945
1946pub struct Coordinator<B: ExtraBackendMethods> {
1947 sender: Sender<Message<B>>,
1948 future: Option<thread::JoinHandle<Result<CompiledModules, ()>>>,
1949 phantom: PhantomData<B>,
1951}
1952
1953impl<B: ExtraBackendMethods> Coordinator<B> {
1954 fn join(mut self) -> std::thread::Result<Result<CompiledModules, ()>> {
1955 self.future.take().unwrap().join()
1956 }
1957}
1958
1959impl<B: ExtraBackendMethods> Drop for Coordinator<B> {
1960 fn drop(&mut self) {
1961 if let Some(future) = self.future.take() {
1962 drop(self.sender.send(Message::CodegenAborted::<B>));
1965 drop(future.join());
1966 }
1967 }
1968}
1969
1970pub struct OngoingCodegen<B: ExtraBackendMethods> {
1971 pub backend: B,
1972 pub crate_info: CrateInfo,
1973 pub codegen_worker_receive: Receiver<CguMessage>,
1974 pub shared_emitter_main: SharedEmitterMain,
1975 pub output_filenames: Arc<OutputFilenames>,
1976 pub coordinator: Coordinator<B>,
1977}
1978
1979impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1980 pub fn join(self, sess: &Session) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
1981 self.shared_emitter_main.check(sess, true);
1982 let compiled_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
1983 Ok(Ok(compiled_modules)) => compiled_modules,
1984 Ok(Err(())) => {
1985 sess.dcx().abort_if_errors();
1986 panic!("expected abort due to worker thread errors")
1987 }
1988 Err(_) => {
1989 bug!("panic during codegen/LLVM phase");
1990 }
1991 });
1992
1993 sess.dcx().abort_if_errors();
1994
1995 let work_products =
1996 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
1997 produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
1998
1999 if sess.codegen_units().as_usize() == 1 && sess.opts.unstable_opts.time_llvm_passes {
2002 self.backend.print_pass_timings()
2003 }
2004
2005 if sess.print_llvm_stats() {
2006 self.backend.print_statistics()
2007 }
2008
2009 (
2010 CodegenResults {
2011 crate_info: self.crate_info,
2012
2013 modules: compiled_modules.modules,
2014 allocator_module: compiled_modules.allocator_module,
2015 },
2016 work_products,
2017 )
2018 }
2019
2020 pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2021 self.wait_for_signal_to_codegen_item();
2022 self.check_for_errors(tcx.sess);
2023 drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
2024 }
2025
2026 pub(crate) fn check_for_errors(&self, sess: &Session) {
2027 self.shared_emitter_main.check(sess, false);
2028 }
2029
2030 pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2031 match self.codegen_worker_receive.recv() {
2032 Ok(CguMessage) => {
2033 }
2035 Err(_) => {
2036 }
2039 }
2040 }
2041}
2042
2043pub(crate) fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
2044 coordinator: &Coordinator<B>,
2045 module: ModuleCodegen<B::Module>,
2046 cost: u64,
2047) {
2048 let llvm_work_item = WorkItem::Optimize(module);
2049 drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2050}
2051
2052pub(crate) fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
2053 coordinator: &Coordinator<B>,
2054 module: CachedModuleCodegen,
2055) {
2056 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2057 drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2058}
2059
2060pub(crate) fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
2061 tcx: TyCtxt<'_>,
2062 coordinator: &Coordinator<B>,
2063 module: CachedModuleCodegen,
2064) {
2065 let filename = pre_lto_bitcode_filename(&module.name);
2066 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2067 let file = fs::File::open(&bc_path)
2068 .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
2069
2070 let mmap = unsafe {
2071 Mmap::map(file).unwrap_or_else(|e| {
2072 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2073 })
2074 };
2075 drop(coordinator.sender.send(Message::AddImportOnlyModule::<B> {
2077 module_data: SerializedModule::FromUncompressedFile(mmap),
2078 work_product: module.source,
2079 }));
2080}
2081
2082fn pre_lto_bitcode_filename(module_name: &str) -> String {
2083 format!("{module_name}.{PRE_LTO_BC_EXT}")
2084}
2085
2086fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2087 assert!(
2090 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2091 && tcx.sess.target.is_like_windows
2092 && tcx.sess.opts.cg.prefer_dynamic)
2093 );
2094
2095 let can_have_static_objects =
2099 tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
2100
2101 tcx.sess.target.is_like_windows &&
2102 can_have_static_objects &&
2103 !tcx.sess.opts.cg.linker_plugin_lto.enabled()
2107}