1use std::assert_matches::assert_matches;
2use std::marker::PhantomData;
3use std::panic::AssertUnwindSafe;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use std::sync::mpsc::{Receiver, Sender, channel};
7use std::{fs, io, mem, str, thread};
8
9use rustc_abi::Size;
10use rustc_ast::attr;
11use rustc_data_structures::fx::FxIndexMap;
12use rustc_data_structures::jobserver::{self, Acquired};
13use rustc_data_structures::memmap::Mmap;
14use rustc_data_structures::profiling::{SelfProfilerRef, VerboseTimingGuard};
15use rustc_errors::emitter::Emitter;
16use rustc_errors::translation::Translator;
17use rustc_errors::{
18 Diag, DiagArgMap, DiagCtxt, DiagMessage, ErrCode, FatalErrorMarker, 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::ErrorCreatingRemarkDir;
42use crate::traits::*;
43use crate::{
44 CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
45 errors,
46};
47
48const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
49
50#[derive(Clone, Copy, PartialEq)]
52pub enum EmitObj {
53 None,
55
56 Bitcode,
59
60 ObjectCode(BitcodeSection),
62}
63
64#[derive(Clone, Copy, PartialEq)]
66pub enum BitcodeSection {
67 None,
69
70 Full,
72}
73
74pub struct ModuleConfig {
76 pub passes: Vec<String>,
78 pub opt_level: Option<config::OptLevel>,
81
82 pub pgo_gen: SwitchWithOptPath,
83 pub pgo_use: Option<PathBuf>,
84 pub pgo_sample_use: Option<PathBuf>,
85 pub debug_info_for_profiling: bool,
86 pub instrument_coverage: bool,
87
88 pub sanitizer: SanitizerSet,
89 pub sanitizer_recover: SanitizerSet,
90 pub sanitizer_dataflow_abilist: Vec<String>,
91 pub sanitizer_memory_track_origins: usize,
92
93 pub emit_pre_lto_bc: bool,
95 pub emit_no_opt_bc: bool,
96 pub emit_bc: bool,
97 pub emit_ir: bool,
98 pub emit_asm: bool,
99 pub emit_obj: EmitObj,
100 pub emit_thin_lto: bool,
101 pub emit_thin_lto_summary: bool,
102
103 pub verify_llvm_ir: bool,
106 pub lint_llvm_ir: bool,
107 pub no_prepopulate_passes: bool,
108 pub no_builtins: bool,
109 pub vectorize_loop: bool,
110 pub vectorize_slp: bool,
111 pub merge_functions: bool,
112 pub emit_lifetime_markers: bool,
113 pub llvm_plugins: Vec<String>,
114 pub autodiff: Vec<config::AutoDiff>,
115 pub offload: Vec<config::Offload>,
116}
117
118impl ModuleConfig {
119 fn new(kind: ModuleKind, tcx: TyCtxt<'_>, no_builtins: bool) -> ModuleConfig {
120 macro_rules! if_regular {
123 ($regular: expr, $other: expr) => {
124 if let ModuleKind::Regular = kind { $regular } else { $other }
125 };
126 }
127
128 let sess = tcx.sess;
129 let opt_level_and_size = if_regular!(Some(sess.opts.optimize), None);
130
131 let save_temps = sess.opts.cg.save_temps;
132
133 let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
134 || match kind {
135 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
136 ModuleKind::Allocator => false,
137 };
138
139 let emit_obj = if !should_emit_obj {
140 EmitObj::None
141 } else if sess.target.obj_is_bitcode
142 || (sess.opts.cg.linker_plugin_lto.enabled() && !no_builtins)
143 {
144 EmitObj::Bitcode
159 } else if need_bitcode_in_object(tcx) {
160 EmitObj::ObjectCode(BitcodeSection::Full)
161 } else {
162 EmitObj::ObjectCode(BitcodeSection::None)
163 };
164
165 ModuleConfig {
166 passes: if_regular!(sess.opts.cg.passes.clone(), vec![]),
167
168 opt_level: opt_level_and_size,
169
170 pgo_gen: if_regular!(
171 sess.opts.cg.profile_generate.clone(),
172 SwitchWithOptPath::Disabled
173 ),
174 pgo_use: if_regular!(sess.opts.cg.profile_use.clone(), None),
175 pgo_sample_use: if_regular!(sess.opts.unstable_opts.profile_sample_use.clone(), None),
176 debug_info_for_profiling: sess.opts.unstable_opts.debug_info_for_profiling,
177 instrument_coverage: if_regular!(sess.instrument_coverage(), false),
178
179 sanitizer: if_regular!(sess.opts.unstable_opts.sanitizer, SanitizerSet::empty()),
180 sanitizer_dataflow_abilist: if_regular!(
181 sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
182 Vec::new()
183 ),
184 sanitizer_recover: if_regular!(
185 sess.opts.unstable_opts.sanitizer_recover,
186 SanitizerSet::empty()
187 ),
188 sanitizer_memory_track_origins: if_regular!(
189 sess.opts.unstable_opts.sanitizer_memory_track_origins,
190 0
191 ),
192
193 emit_pre_lto_bc: if_regular!(
194 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
195 false
196 ),
197 emit_no_opt_bc: if_regular!(save_temps, false),
198 emit_bc: if_regular!(
199 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
200 save_temps
201 ),
202 emit_ir: if_regular!(
203 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
204 false
205 ),
206 emit_asm: if_regular!(
207 sess.opts.output_types.contains_key(&OutputType::Assembly),
208 false
209 ),
210 emit_obj,
211 emit_thin_lto: sess.opts.unstable_opts.emit_thin_lto && sess.lto() != Lto::Fat,
214 emit_thin_lto_summary: if_regular!(
215 sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode),
216 false
217 ),
218
219 verify_llvm_ir: sess.verify_llvm_ir(),
220 lint_llvm_ir: sess.opts.unstable_opts.lint_llvm_ir,
221 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
222 no_builtins: no_builtins || sess.target.no_builtins,
223
224 vectorize_loop: !sess.opts.cg.no_vectorize_loops
227 && (sess.opts.optimize == config::OptLevel::More
228 || sess.opts.optimize == config::OptLevel::Aggressive),
229 vectorize_slp: !sess.opts.cg.no_vectorize_slp
230 && sess.opts.optimize == config::OptLevel::Aggressive,
231
232 merge_functions: match sess
242 .opts
243 .unstable_opts
244 .merge_functions
245 .unwrap_or(sess.target.merge_functions)
246 {
247 MergeFunctions::Disabled => false,
248 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
249 use config::OptLevel::*;
250 match sess.opts.optimize {
251 Aggressive | More | SizeMin | Size => true,
252 Less | No => false,
253 }
254 }
255 },
256
257 emit_lifetime_markers: sess.emit_lifetime_markers(),
258 llvm_plugins: if_regular!(sess.opts.unstable_opts.llvm_plugins.clone(), vec![]),
259 autodiff: if_regular!(sess.opts.unstable_opts.autodiff.clone(), vec![]),
260 offload: if_regular!(sess.opts.unstable_opts.offload.clone(), vec![]),
261 }
262 }
263
264 pub fn bitcode_needed(&self) -> bool {
265 self.emit_bc
266 || self.emit_thin_lto_summary
267 || self.emit_obj == EmitObj::Bitcode
268 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
269 }
270
271 pub fn embed_bitcode(&self) -> bool {
272 self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
273 }
274}
275
276pub struct TargetMachineFactoryConfig {
278 pub split_dwarf_file: Option<PathBuf>,
282
283 pub output_obj_file: Option<PathBuf>,
286}
287
288impl TargetMachineFactoryConfig {
289 pub fn new(
290 cgcx: &CodegenContext<impl WriteBackendMethods>,
291 module_name: &str,
292 ) -> TargetMachineFactoryConfig {
293 let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
294 cgcx.output_filenames.split_dwarf_path(
295 cgcx.split_debuginfo,
296 cgcx.split_dwarf_kind,
297 module_name,
298 cgcx.invocation_temp.as_deref(),
299 )
300 } else {
301 None
302 };
303
304 let output_obj_file = Some(cgcx.output_filenames.temp_path_for_cgu(
305 OutputType::Object,
306 module_name,
307 cgcx.invocation_temp.as_deref(),
308 ));
309 TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }
310 }
311}
312
313pub type TargetMachineFactoryFn<B> = Arc<
314 dyn Fn(
315 TargetMachineFactoryConfig,
316 ) -> Result<
317 <B as WriteBackendMethods>::TargetMachine,
318 <B as WriteBackendMethods>::TargetMachineError,
319 > + Send
320 + Sync,
321>;
322
323#[derive(Clone)]
325pub struct CodegenContext<B: WriteBackendMethods> {
326 pub prof: SelfProfilerRef,
328 pub lto: Lto,
329 pub save_temps: bool,
330 pub fewer_names: bool,
331 pub time_trace: bool,
332 pub opts: Arc<config::Options>,
333 pub crate_types: Vec<CrateType>,
334 pub output_filenames: Arc<OutputFilenames>,
335 pub invocation_temp: Option<String>,
336 pub regular_module_config: Arc<ModuleConfig>,
337 pub allocator_module_config: Arc<ModuleConfig>,
338 pub tm_factory: TargetMachineFactoryFn<B>,
339 pub msvc_imps_needed: bool,
340 pub is_pe_coff: bool,
341 pub target_can_use_split_dwarf: bool,
342 pub target_arch: String,
343 pub target_is_like_darwin: bool,
344 pub target_is_like_aix: bool,
345 pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
346 pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
347 pub pointer_size: Size,
348
349 pub expanded_args: Vec<String>,
354
355 pub diag_emitter: SharedEmitter,
357 pub remark: Passes,
359 pub remark_dir: Option<PathBuf>,
362 pub incr_comp_session_dir: Option<PathBuf>,
365 pub parallel: bool,
369}
370
371impl<B: WriteBackendMethods> CodegenContext<B> {
372 pub fn create_dcx(&self) -> DiagCtxt {
373 DiagCtxt::new(Box::new(self.diag_emitter.clone()))
374 }
375
376 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
377 match kind {
378 ModuleKind::Regular => &self.regular_module_config,
379 ModuleKind::Allocator => &self.allocator_module_config,
380 }
381 }
382}
383
384fn generate_thin_lto_work<B: ExtraBackendMethods>(
385 cgcx: &CodegenContext<B>,
386 exported_symbols_for_lto: &[String],
387 each_linked_rlib_for_lto: &[PathBuf],
388 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
389 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
390) -> Vec<(WorkItem<B>, u64)> {
391 let _prof_timer = cgcx.prof.generic_activity("codegen_thin_generate_lto_work");
392
393 let (lto_modules, copy_jobs) = B::run_thin_lto(
394 cgcx,
395 exported_symbols_for_lto,
396 each_linked_rlib_for_lto,
397 needs_thin_lto,
398 import_only_modules,
399 );
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) -> WorkItemResult<B> {
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 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 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 WorkItemResult::NeedsFatLto(FatLtoInput::Serialized {
890 name,
891 buffer: SerializedModule::Local(buffer),
892 })
893 }
894 None => 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) -> WorkItemResult<B> {
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 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) -> WorkItemResult<B> {
1010 let module = B::optimize_thin(cgcx, module);
1011 let module = B::codegen(cgcx, module, module_config);
1012 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 let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
1726 let module_config = cgcx.config(work.module_kind());
1727
1728 match work {
1729 WorkItem::Optimize(m) => {
1730 let _timer =
1731 cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &*m.name);
1732 execute_optimize_work_item(&cgcx, m, module_config)
1733 }
1734 WorkItem::CopyPostLtoArtifacts(m) => {
1735 let _timer = cgcx.prof.generic_activity_with_arg(
1736 "codegen_copy_artifacts_from_incr_cache",
1737 &*m.name,
1738 );
1739 execute_copy_from_cache_work_item(&cgcx, m, module_config)
1740 }
1741 WorkItem::FatLto {
1742 exported_symbols_for_lto,
1743 each_linked_rlib_for_lto,
1744 needs_fat_lto,
1745 import_only_modules,
1746 } => {
1747 let _timer = cgcx
1748 .prof
1749 .generic_activity_with_arg("codegen_module_perform_lto", "everything");
1750 execute_fat_lto_work_item(
1751 &cgcx,
1752 &exported_symbols_for_lto,
1753 &each_linked_rlib_for_lto,
1754 needs_fat_lto,
1755 import_only_modules,
1756 module_config,
1757 )
1758 }
1759 WorkItem::ThinLto(m) => {
1760 let _timer =
1761 cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", m.name());
1762 execute_thin_lto_work_item(&cgcx, m, module_config)
1763 }
1764 }
1765 }));
1766
1767 let msg = match result {
1768 Ok(result) => Message::WorkItem::<B> { result: Ok(result) },
1769
1770 Err(err) if err.is::<FatalErrorMarker>() => {
1774 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1775 }
1776
1777 Err(_) => Message::WorkItem::<B> { result: Err(None) },
1778 };
1779 drop(coordinator_send.send(msg));
1780 })
1781 .expect("failed to spawn work thread");
1782}
1783
1784enum SharedEmitterMessage {
1785 Diagnostic(Diagnostic),
1786 InlineAsmError(SpanData, String, Level, Option<(String, Vec<InnerSpan>)>),
1787 Fatal(String),
1788}
1789
1790#[derive(Clone)]
1791pub struct SharedEmitter {
1792 sender: Sender<SharedEmitterMessage>,
1793}
1794
1795pub struct SharedEmitterMain {
1796 receiver: Receiver<SharedEmitterMessage>,
1797}
1798
1799impl SharedEmitter {
1800 fn new() -> (SharedEmitter, SharedEmitterMain) {
1801 let (sender, receiver) = channel();
1802
1803 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1804 }
1805
1806 pub fn inline_asm_error(
1807 &self,
1808 span: SpanData,
1809 msg: String,
1810 level: Level,
1811 source: Option<(String, Vec<InnerSpan>)>,
1812 ) {
1813 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(span, msg, level, source)));
1814 }
1815
1816 fn fatal(&self, msg: &str) {
1817 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1818 }
1819}
1820
1821impl Emitter for SharedEmitter {
1822 fn emit_diagnostic(
1823 &mut self,
1824 mut diag: rustc_errors::DiagInner,
1825 _registry: &rustc_errors::registry::Registry,
1826 ) {
1827 assert_eq!(diag.span, MultiSpan::new());
1830 assert_eq!(diag.suggestions, Suggestions::Enabled(vec![]));
1831 assert_eq!(diag.sort_span, rustc_span::DUMMY_SP);
1832 assert_eq!(diag.is_lint, None);
1833 let args = mem::replace(&mut diag.args, DiagArgMap::default());
1836 drop(
1837 self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1838 level: diag.level(),
1839 messages: diag.messages,
1840 code: diag.code,
1841 children: diag
1842 .children
1843 .into_iter()
1844 .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
1845 .collect(),
1846 args,
1847 })),
1848 );
1849 }
1850
1851 fn source_map(&self) -> Option<&SourceMap> {
1852 None
1853 }
1854
1855 fn translator(&self) -> &Translator {
1856 panic!("shared emitter attempted to translate a diagnostic");
1857 }
1858}
1859
1860impl SharedEmitterMain {
1861 fn check(&self, sess: &Session, blocking: bool) {
1862 loop {
1863 let message = if blocking {
1864 match self.receiver.recv() {
1865 Ok(message) => Ok(message),
1866 Err(_) => Err(()),
1867 }
1868 } else {
1869 match self.receiver.try_recv() {
1870 Ok(message) => Ok(message),
1871 Err(_) => Err(()),
1872 }
1873 };
1874
1875 match message {
1876 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1877 let dcx = sess.dcx();
1880 let mut d =
1881 rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
1882 d.code = diag.code; d.children = diag
1884 .children
1885 .into_iter()
1886 .map(|sub| rustc_errors::Subdiag {
1887 level: sub.level,
1888 messages: sub.messages,
1889 span: MultiSpan::new(),
1890 })
1891 .collect();
1892 d.args = diag.args;
1893 dcx.emit_diagnostic(d);
1894 sess.dcx().abort_if_errors();
1895 }
1896 Ok(SharedEmitterMessage::InlineAsmError(span, msg, level, source)) => {
1897 assert_matches!(level, Level::Error | Level::Warning | Level::Note);
1898 let mut err = Diag::<()>::new(sess.dcx(), level, msg);
1899 if !span.is_dummy() {
1900 err.span(span.span());
1901 }
1902
1903 if let Some((buffer, spans)) = source {
1905 let source = sess
1906 .source_map()
1907 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
1908 let spans: Vec<_> = spans
1909 .iter()
1910 .map(|sp| {
1911 Span::with_root_ctxt(
1912 source.normalized_byte_pos(sp.start as u32),
1913 source.normalized_byte_pos(sp.end as u32),
1914 )
1915 })
1916 .collect();
1917 err.span_note(spans, "instantiated into assembly here");
1918 }
1919
1920 err.emit();
1921 }
1922 Ok(SharedEmitterMessage::Fatal(msg)) => {
1923 sess.dcx().fatal(msg);
1924 }
1925 Err(_) => {
1926 break;
1927 }
1928 }
1929 }
1930 }
1931}
1932
1933pub struct Coordinator<B: ExtraBackendMethods> {
1934 sender: Sender<Message<B>>,
1935 future: Option<thread::JoinHandle<Result<CompiledModules, ()>>>,
1936 phantom: PhantomData<B>,
1938}
1939
1940impl<B: ExtraBackendMethods> Coordinator<B> {
1941 fn join(mut self) -> std::thread::Result<Result<CompiledModules, ()>> {
1942 self.future.take().unwrap().join()
1943 }
1944}
1945
1946impl<B: ExtraBackendMethods> Drop for Coordinator<B> {
1947 fn drop(&mut self) {
1948 if let Some(future) = self.future.take() {
1949 drop(self.sender.send(Message::CodegenAborted::<B>));
1952 drop(future.join());
1953 }
1954 }
1955}
1956
1957pub struct OngoingCodegen<B: ExtraBackendMethods> {
1958 pub backend: B,
1959 pub crate_info: CrateInfo,
1960 pub codegen_worker_receive: Receiver<CguMessage>,
1961 pub shared_emitter_main: SharedEmitterMain,
1962 pub output_filenames: Arc<OutputFilenames>,
1963 pub coordinator: Coordinator<B>,
1964}
1965
1966impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1967 pub fn join(self, sess: &Session) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
1968 self.shared_emitter_main.check(sess, true);
1969 let compiled_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
1970 Ok(Ok(compiled_modules)) => compiled_modules,
1971 Ok(Err(())) => {
1972 sess.dcx().abort_if_errors();
1973 panic!("expected abort due to worker thread errors")
1974 }
1975 Err(_) => {
1976 bug!("panic during codegen/LLVM phase");
1977 }
1978 });
1979
1980 sess.dcx().abort_if_errors();
1981
1982 let work_products =
1983 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
1984 produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
1985
1986 if sess.codegen_units().as_usize() == 1 && sess.opts.unstable_opts.time_llvm_passes {
1989 self.backend.print_pass_timings()
1990 }
1991
1992 if sess.print_llvm_stats() {
1993 self.backend.print_statistics()
1994 }
1995
1996 (
1997 CodegenResults {
1998 crate_info: self.crate_info,
1999
2000 modules: compiled_modules.modules,
2001 allocator_module: compiled_modules.allocator_module,
2002 },
2003 work_products,
2004 )
2005 }
2006
2007 pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2008 self.wait_for_signal_to_codegen_item();
2009 self.check_for_errors(tcx.sess);
2010 drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
2011 }
2012
2013 pub(crate) fn check_for_errors(&self, sess: &Session) {
2014 self.shared_emitter_main.check(sess, false);
2015 }
2016
2017 pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2018 match self.codegen_worker_receive.recv() {
2019 Ok(CguMessage) => {
2020 }
2022 Err(_) => {
2023 }
2026 }
2027 }
2028}
2029
2030pub(crate) fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
2031 coordinator: &Coordinator<B>,
2032 module: ModuleCodegen<B::Module>,
2033 cost: u64,
2034) {
2035 let llvm_work_item = WorkItem::Optimize(module);
2036 drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2037}
2038
2039pub(crate) fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
2040 coordinator: &Coordinator<B>,
2041 module: CachedModuleCodegen,
2042) {
2043 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2044 drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2045}
2046
2047pub(crate) fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
2048 tcx: TyCtxt<'_>,
2049 coordinator: &Coordinator<B>,
2050 module: CachedModuleCodegen,
2051) {
2052 let filename = pre_lto_bitcode_filename(&module.name);
2053 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2054 let file = fs::File::open(&bc_path)
2055 .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
2056
2057 let mmap = unsafe {
2058 Mmap::map(file).unwrap_or_else(|e| {
2059 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2060 })
2061 };
2062 drop(coordinator.sender.send(Message::AddImportOnlyModule::<B> {
2064 module_data: SerializedModule::FromUncompressedFile(mmap),
2065 work_product: module.source,
2066 }));
2067}
2068
2069fn pre_lto_bitcode_filename(module_name: &str) -> String {
2070 format!("{module_name}.{PRE_LTO_BC_EXT}")
2071}
2072
2073fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2074 assert!(
2077 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2078 && tcx.sess.target.is_like_windows
2079 && tcx.sess.opts.cg.prefer_dynamic)
2080 );
2081
2082 let can_have_static_objects =
2086 tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
2087
2088 tcx.sess.target.is_like_windows &&
2089 can_have_static_objects &&
2090 !tcx.sess.opts.cg.linker_plugin_lto.enabled()
2094}