1use std::any::Any;
2use std::assert_matches::assert_matches;
3use std::marker::PhantomData;
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_ast::expand::autodiff_attrs::AutoDiffItem;
12use rustc_data_structures::fx::{FxHashMap, FxIndexMap};
13use rustc_data_structures::jobserver::{self, Acquired};
14use rustc_data_structures::memmap::Mmap;
15use rustc_data_structures::profiling::{SelfProfilerRef, VerboseTimingGuard};
16use rustc_errors::emitter::Emitter;
17use rustc_errors::translation::Translator;
18use rustc_errors::{
19 Diag, DiagArgMap, DiagCtxt, DiagMessage, ErrCode, FatalError, Level, MultiSpan, Style,
20 Suggestions,
21};
22use rustc_fs_util::link_or_copy;
23use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
24use rustc_incremental::{
25 copy_cgu_workproduct_to_incr_comp_cache_dir, in_incr_comp_dir, in_incr_comp_dir_sess,
26};
27use rustc_metadata::fs::copy_to_stdout;
28use rustc_middle::bug;
29use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
30use rustc_middle::middle::exported_symbols::SymbolExportInfo;
31use rustc_middle::ty::TyCtxt;
32use rustc_session::Session;
33use rustc_session::config::{
34 self, CrateType, Lto, OutFileName, OutputFilenames, OutputType, Passes, SwitchWithOptPath,
35};
36use rustc_span::source_map::SourceMap;
37use rustc_span::{FileName, InnerSpan, Span, SpanData, sym};
38use rustc_target::spec::{MergeFunctions, SanitizerSet};
39use tracing::debug;
40
41use super::link::{self, ensure_removed};
42use super::lto::{self, SerializedModule};
43use super::symbol_export::symbol_name_for_instance_in_crate;
44use crate::errors::{AutodiffWithoutLto, ErrorCreatingRemarkDir};
45use crate::traits::*;
46use crate::{
47 CachedModuleCodegen, CodegenResults, CompiledModule, CrateInfo, ModuleCodegen, ModuleKind,
48 errors,
49};
50
51const PRE_LTO_BC_EXT: &str = "pre-lto.bc";
52
53#[derive(Clone, Copy, PartialEq)]
55pub enum EmitObj {
56 None,
58
59 Bitcode,
62
63 ObjectCode(BitcodeSection),
65}
66
67#[derive(Clone, Copy, PartialEq)]
69pub enum BitcodeSection {
70 None,
72
73 Full,
75}
76
77pub struct ModuleConfig {
79 pub passes: Vec<String>,
81 pub opt_level: Option<config::OptLevel>,
84
85 pub opt_size: Option<config::OptLevel>,
87
88 pub pgo_gen: SwitchWithOptPath,
89 pub pgo_use: Option<PathBuf>,
90 pub pgo_sample_use: Option<PathBuf>,
91 pub debug_info_for_profiling: bool,
92 pub instrument_coverage: bool,
93
94 pub sanitizer: SanitizerSet,
95 pub sanitizer_recover: SanitizerSet,
96 pub sanitizer_dataflow_abilist: Vec<String>,
97 pub sanitizer_memory_track_origins: usize,
98
99 pub emit_pre_lto_bc: bool,
101 pub emit_no_opt_bc: bool,
102 pub emit_bc: bool,
103 pub emit_ir: bool,
104 pub emit_asm: bool,
105 pub emit_obj: EmitObj,
106 pub emit_thin_lto: bool,
107 pub emit_thin_lto_summary: bool,
108 pub bc_cmdline: String,
109
110 pub verify_llvm_ir: bool,
113 pub lint_llvm_ir: bool,
114 pub no_prepopulate_passes: bool,
115 pub no_builtins: bool,
116 pub time_module: bool,
117 pub vectorize_loop: bool,
118 pub vectorize_slp: bool,
119 pub merge_functions: bool,
120 pub emit_lifetime_markers: bool,
121 pub llvm_plugins: Vec<String>,
122 pub autodiff: Vec<config::AutoDiff>,
123}
124
125impl ModuleConfig {
126 fn new(kind: ModuleKind, tcx: TyCtxt<'_>, no_builtins: bool) -> ModuleConfig {
127 macro_rules! if_regular {
130 ($regular: expr, $other: expr) => {
131 if let ModuleKind::Regular = kind { $regular } else { $other }
132 };
133 }
134
135 let sess = tcx.sess;
136 let opt_level_and_size = if_regular!(Some(sess.opts.optimize), None);
137
138 let save_temps = sess.opts.cg.save_temps;
139
140 let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
141 || match kind {
142 ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
143 ModuleKind::Allocator => false,
144 };
145
146 let emit_obj = if !should_emit_obj {
147 EmitObj::None
148 } else if sess.target.obj_is_bitcode
149 || (sess.opts.cg.linker_plugin_lto.enabled() && !no_builtins)
150 {
151 EmitObj::Bitcode
166 } else if need_bitcode_in_object(tcx) {
167 EmitObj::ObjectCode(BitcodeSection::Full)
168 } else {
169 EmitObj::ObjectCode(BitcodeSection::None)
170 };
171
172 ModuleConfig {
173 passes: if_regular!(sess.opts.cg.passes.clone(), vec![]),
174
175 opt_level: opt_level_and_size,
176 opt_size: opt_level_and_size,
177
178 pgo_gen: if_regular!(
179 sess.opts.cg.profile_generate.clone(),
180 SwitchWithOptPath::Disabled
181 ),
182 pgo_use: if_regular!(sess.opts.cg.profile_use.clone(), None),
183 pgo_sample_use: if_regular!(sess.opts.unstable_opts.profile_sample_use.clone(), None),
184 debug_info_for_profiling: sess.opts.unstable_opts.debug_info_for_profiling,
185 instrument_coverage: if_regular!(sess.instrument_coverage(), false),
186
187 sanitizer: if_regular!(sess.opts.unstable_opts.sanitizer, SanitizerSet::empty()),
188 sanitizer_dataflow_abilist: if_regular!(
189 sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
190 Vec::new()
191 ),
192 sanitizer_recover: if_regular!(
193 sess.opts.unstable_opts.sanitizer_recover,
194 SanitizerSet::empty()
195 ),
196 sanitizer_memory_track_origins: if_regular!(
197 sess.opts.unstable_opts.sanitizer_memory_track_origins,
198 0
199 ),
200
201 emit_pre_lto_bc: if_regular!(
202 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
203 false
204 ),
205 emit_no_opt_bc: if_regular!(save_temps, false),
206 emit_bc: if_regular!(
207 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
208 save_temps
209 ),
210 emit_ir: if_regular!(
211 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
212 false
213 ),
214 emit_asm: if_regular!(
215 sess.opts.output_types.contains_key(&OutputType::Assembly),
216 false
217 ),
218 emit_obj,
219 emit_thin_lto: sess.opts.unstable_opts.emit_thin_lto,
220 emit_thin_lto_summary: if_regular!(
221 sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode),
222 false
223 ),
224 bc_cmdline: sess.target.bitcode_llvm_cmdline.to_string(),
225
226 verify_llvm_ir: sess.verify_llvm_ir(),
227 lint_llvm_ir: sess.opts.unstable_opts.lint_llvm_ir,
228 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
229 no_builtins: no_builtins || sess.target.no_builtins,
230
231 time_module: if_regular!(true, false),
234
235 vectorize_loop: !sess.opts.cg.no_vectorize_loops
238 && (sess.opts.optimize == config::OptLevel::More
239 || sess.opts.optimize == config::OptLevel::Aggressive),
240 vectorize_slp: !sess.opts.cg.no_vectorize_slp
241 && sess.opts.optimize == config::OptLevel::Aggressive,
242
243 merge_functions: match sess
253 .opts
254 .unstable_opts
255 .merge_functions
256 .unwrap_or(sess.target.merge_functions)
257 {
258 MergeFunctions::Disabled => false,
259 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
260 use config::OptLevel::*;
261 match sess.opts.optimize {
262 Aggressive | More | SizeMin | Size => true,
263 Less | No => false,
264 }
265 }
266 },
267
268 emit_lifetime_markers: sess.emit_lifetime_markers(),
269 llvm_plugins: if_regular!(sess.opts.unstable_opts.llvm_plugins.clone(), vec![]),
270 autodiff: if_regular!(sess.opts.unstable_opts.autodiff.clone(), vec![]),
271 }
272 }
273
274 pub fn bitcode_needed(&self) -> bool {
275 self.emit_bc
276 || self.emit_thin_lto_summary
277 || self.emit_obj == EmitObj::Bitcode
278 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
279 }
280
281 pub fn embed_bitcode(&self) -> bool {
282 self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
283 }
284}
285
286pub struct TargetMachineFactoryConfig {
288 pub split_dwarf_file: Option<PathBuf>,
292
293 pub output_obj_file: Option<PathBuf>,
296}
297
298impl TargetMachineFactoryConfig {
299 pub fn new(
300 cgcx: &CodegenContext<impl WriteBackendMethods>,
301 module_name: &str,
302 ) -> TargetMachineFactoryConfig {
303 let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
304 cgcx.output_filenames.split_dwarf_path(
305 cgcx.split_debuginfo,
306 cgcx.split_dwarf_kind,
307 module_name,
308 cgcx.invocation_temp.as_deref(),
309 )
310 } else {
311 None
312 };
313
314 let output_obj_file = Some(cgcx.output_filenames.temp_path_for_cgu(
315 OutputType::Object,
316 module_name,
317 cgcx.invocation_temp.as_deref(),
318 ));
319 TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }
320 }
321}
322
323pub type TargetMachineFactoryFn<B> = Arc<
324 dyn Fn(
325 TargetMachineFactoryConfig,
326 ) -> Result<
327 <B as WriteBackendMethods>::TargetMachine,
328 <B as WriteBackendMethods>::TargetMachineError,
329 > + Send
330 + Sync,
331>;
332
333type ExportedSymbols = FxHashMap<CrateNum, Arc<Vec<(String, SymbolExportInfo)>>>;
334
335#[derive(Clone)]
337pub struct CodegenContext<B: WriteBackendMethods> {
338 pub prof: SelfProfilerRef,
340 pub lto: Lto,
341 pub save_temps: bool,
342 pub fewer_names: bool,
343 pub time_trace: bool,
344 pub exported_symbols: Option<Arc<ExportedSymbols>>,
345 pub opts: Arc<config::Options>,
346 pub crate_types: Vec<CrateType>,
347 pub each_linked_rlib_for_lto: Vec<(CrateNum, PathBuf)>,
348 pub output_filenames: Arc<OutputFilenames>,
349 pub invocation_temp: Option<String>,
350 pub regular_module_config: Arc<ModuleConfig>,
351 pub allocator_module_config: Arc<ModuleConfig>,
352 pub tm_factory: TargetMachineFactoryFn<B>,
353 pub msvc_imps_needed: bool,
354 pub is_pe_coff: bool,
355 pub target_can_use_split_dwarf: bool,
356 pub target_arch: String,
357 pub target_is_like_darwin: bool,
358 pub target_is_like_aix: bool,
359 pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
360 pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
361 pub pointer_size: Size,
362
363 pub expanded_args: Vec<String>,
368
369 pub diag_emitter: SharedEmitter,
371 pub remark: Passes,
373 pub remark_dir: Option<PathBuf>,
376 pub incr_comp_session_dir: Option<PathBuf>,
379 pub coordinator_send: Sender<Box<dyn Any + Send>>,
381 pub parallel: bool,
385}
386
387impl<B: WriteBackendMethods> CodegenContext<B> {
388 pub fn create_dcx(&self) -> DiagCtxt {
389 DiagCtxt::new(Box::new(self.diag_emitter.clone()))
390 }
391
392 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
393 match kind {
394 ModuleKind::Regular => &self.regular_module_config,
395 ModuleKind::Allocator => &self.allocator_module_config,
396 }
397 }
398}
399
400fn generate_thin_lto_work<B: ExtraBackendMethods>(
401 cgcx: &CodegenContext<B>,
402 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
403 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
404) -> Vec<(WorkItem<B>, u64)> {
405 let _prof_timer = cgcx.prof.generic_activity("codegen_thin_generate_lto_work");
406
407 let (lto_modules, copy_jobs) =
408 B::run_thin_lto(cgcx, needs_thin_lto, import_only_modules).unwrap_or_else(|e| e.raise());
409 lto_modules
410 .into_iter()
411 .map(|module| {
412 let cost = module.cost();
413 (WorkItem::ThinLto(module), cost)
414 })
415 .chain(copy_jobs.into_iter().map(|wp| {
416 (
417 WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
418 name: wp.cgu_name.clone(),
419 source: wp,
420 }),
421 0, )
423 }))
424 .collect()
425}
426
427struct CompiledModules {
428 modules: Vec<CompiledModule>,
429 allocator_module: Option<CompiledModule>,
430}
431
432fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
433 let sess = tcx.sess;
434 sess.opts.cg.embed_bitcode
435 && tcx.crate_types().contains(&CrateType::Rlib)
436 && sess.opts.output_types.contains_key(&OutputType::Exe)
437}
438
439fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
440 if sess.opts.incremental.is_none() {
441 return false;
442 }
443
444 match sess.lto() {
445 Lto::No => false,
446 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
447 }
448}
449
450pub(crate) fn start_async_codegen<B: ExtraBackendMethods>(
451 backend: B,
452 tcx: TyCtxt<'_>,
453 target_cpu: String,
454 autodiff_items: &[AutoDiffItem],
455) -> OngoingCodegen<B> {
456 let (coordinator_send, coordinator_receive) = channel();
457
458 let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
459 let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins);
460
461 let crate_info = CrateInfo::new(tcx, target_cpu);
462
463 let regular_config = ModuleConfig::new(ModuleKind::Regular, tcx, no_builtins);
464 let allocator_config = ModuleConfig::new(ModuleKind::Allocator, tcx, no_builtins);
465
466 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
467 let (codegen_worker_send, codegen_worker_receive) = channel();
468
469 let coordinator_thread = start_executing_work(
470 backend.clone(),
471 tcx,
472 &crate_info,
473 autodiff_items,
474 shared_emitter,
475 codegen_worker_send,
476 coordinator_receive,
477 Arc::new(regular_config),
478 Arc::new(allocator_config),
479 coordinator_send.clone(),
480 );
481
482 OngoingCodegen {
483 backend,
484 crate_info,
485
486 codegen_worker_receive,
487 shared_emitter_main,
488 coordinator: Coordinator {
489 sender: coordinator_send,
490 future: Some(coordinator_thread),
491 phantom: PhantomData,
492 },
493 output_filenames: Arc::clone(tcx.output_filenames(())),
494 }
495}
496
497fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
498 sess: &Session,
499 compiled_modules: &CompiledModules,
500) -> FxIndexMap<WorkProductId, WorkProduct> {
501 let mut work_products = FxIndexMap::default();
502
503 if sess.opts.incremental.is_none() {
504 return work_products;
505 }
506
507 let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
508
509 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
510 let mut files = Vec::new();
511 if let Some(object_file_path) = &module.object {
512 files.push((OutputType::Object.extension(), object_file_path.as_path()));
513 }
514 if let Some(dwarf_object_file_path) = &module.dwarf_object {
515 files.push(("dwo", dwarf_object_file_path.as_path()));
516 }
517 if let Some(path) = &module.assembly {
518 files.push((OutputType::Assembly.extension(), path.as_path()));
519 }
520 if let Some(path) = &module.llvm_ir {
521 files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
522 }
523 if let Some(path) = &module.bytecode {
524 files.push((OutputType::Bitcode.extension(), path.as_path()));
525 }
526 if let Some((id, product)) = copy_cgu_workproduct_to_incr_comp_cache_dir(
527 sess,
528 &module.name,
529 files.as_slice(),
530 &module.links_from_incr_cache,
531 ) {
532 work_products.insert(id, product);
533 }
534 }
535
536 work_products
537}
538
539fn produce_final_output_artifacts(
540 sess: &Session,
541 compiled_modules: &CompiledModules,
542 crate_output: &OutputFilenames,
543) {
544 let mut user_wants_bitcode = false;
545 let mut user_wants_objects = false;
546
547 let copy_gracefully = |from: &Path, to: &OutFileName| match to {
549 OutFileName::Stdout if let Err(e) = copy_to_stdout(from) => {
550 sess.dcx().emit_err(errors::CopyPath::new(from, to.as_path(), e));
551 }
552 OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
553 sess.dcx().emit_err(errors::CopyPath::new(from, path, e));
554 }
555 _ => {}
556 };
557
558 let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
559 if let [module] = &compiled_modules.modules[..] {
560 let path = crate_output.temp_path_for_cgu(
563 output_type,
564 &module.name,
565 sess.invocation_temp.as_deref(),
566 );
567 let output = crate_output.path(output_type);
568 if !output_type.is_text_output() && output.is_tty() {
569 sess.dcx()
570 .emit_err(errors::BinaryOutputToTty { shorthand: output_type.shorthand() });
571 } else {
572 copy_gracefully(&path, &output);
573 }
574 if !sess.opts.cg.save_temps && !keep_numbered {
575 ensure_removed(sess.dcx(), &path);
577 }
578 } else {
579 if crate_output.outputs.contains_explicit_name(&output_type) {
580 sess.dcx()
583 .emit_warn(errors::IgnoringEmitPath { extension: output_type.extension() });
584 } else if crate_output.single_output_file.is_some() {
585 sess.dcx().emit_warn(errors::IgnoringOutput { extension: output_type.extension() });
588 } else {
589 }
593 }
594 };
595
596 for output_type in crate_output.outputs.keys() {
600 match *output_type {
601 OutputType::Bitcode => {
602 user_wants_bitcode = true;
603 copy_if_one_unit(OutputType::Bitcode, true);
607 }
608 OutputType::ThinLinkBitcode => {
609 copy_if_one_unit(OutputType::ThinLinkBitcode, false);
610 }
611 OutputType::LlvmAssembly => {
612 copy_if_one_unit(OutputType::LlvmAssembly, false);
613 }
614 OutputType::Assembly => {
615 copy_if_one_unit(OutputType::Assembly, false);
616 }
617 OutputType::Object => {
618 user_wants_objects = true;
619 copy_if_one_unit(OutputType::Object, true);
620 }
621 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
622 }
623 }
624
625 if !sess.opts.cg.save_temps {
638 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
654
655 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
656
657 let keep_numbered_objects =
658 needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
659
660 for module in compiled_modules.modules.iter() {
661 if !keep_numbered_objects {
662 if let Some(ref path) = module.object {
663 ensure_removed(sess.dcx(), path);
664 }
665
666 if let Some(ref path) = module.dwarf_object {
667 ensure_removed(sess.dcx(), path);
668 }
669 }
670
671 if let Some(ref path) = module.bytecode {
672 if !keep_numbered_bitcode {
673 ensure_removed(sess.dcx(), path);
674 }
675 }
676 }
677
678 if !user_wants_bitcode
679 && let Some(ref allocator_module) = compiled_modules.allocator_module
680 && let Some(ref path) = allocator_module.bytecode
681 {
682 ensure_removed(sess.dcx(), path);
683 }
684 }
685
686 if sess.opts.json_artifact_notifications {
687 if let [module] = &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 let path = crate_output.path(ty);
694 sess.dcx().emit_artifact_notification(path.as_path(), descr);
695 }
696 });
697 } else {
698 for module in &compiled_modules.modules {
699 module.for_each_output(|path, ty| {
700 if sess.opts.output_types.contains_key(&ty) {
701 let descr = ty.shorthand();
702 sess.dcx().emit_artifact_notification(&path, descr);
703 }
704 });
705 }
706 }
707 }
708
709 }
715
716pub(crate) enum WorkItem<B: WriteBackendMethods> {
717 Optimize(ModuleCodegen<B::Module>),
719 CopyPostLtoArtifacts(CachedModuleCodegen),
722 FatLto {
724 needs_fat_lto: Vec<FatLtoInput<B>>,
725 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
726 autodiff: Vec<AutoDiffItem>,
727 },
728 ThinLto(lto::ThinModule<B>),
730}
731
732impl<B: WriteBackendMethods> WorkItem<B> {
733 fn module_kind(&self) -> ModuleKind {
734 match *self {
735 WorkItem::Optimize(ref m) => m.kind,
736 WorkItem::CopyPostLtoArtifacts(_) | WorkItem::FatLto { .. } | WorkItem::ThinLto(_) => {
737 ModuleKind::Regular
738 }
739 }
740 }
741
742 fn short_description(&self) -> String {
744 #[cfg(not(windows))]
748 fn desc(short: &str, _long: &str, name: &str) -> String {
749 assert_eq!(short.len(), 3);
769 let name = if let Some(index) = name.find("-cgu.") {
770 &name[index + 1..] } else {
772 name
773 };
774 format!("{short} {name}")
775 }
776
777 #[cfg(windows)]
779 fn desc(_short: &str, long: &str, name: &str) -> String {
780 format!("{long} {name}")
781 }
782
783 match self {
784 WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
785 WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
786 WorkItem::FatLto { .. } => desc("lto", "fat LTO module", "everything"),
787 WorkItem::ThinLto(m) => desc("lto", "thin-LTO module", m.name()),
788 }
789 }
790}
791
792pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
794 Finished(CompiledModule),
796
797 NeedsLink(ModuleCodegen<B::Module>),
800
801 NeedsFatLto(FatLtoInput<B>),
804
805 NeedsThinLto(String, B::ThinBuffer),
808}
809
810pub enum FatLtoInput<B: WriteBackendMethods> {
811 Serialized { name: String, buffer: B::ModuleBuffer },
812 InMemory(ModuleCodegen<B::Module>),
813}
814
815pub(crate) enum ComputedLtoType {
817 No,
818 Thin,
819 Fat,
820}
821
822pub(crate) fn compute_per_cgu_lto_type(
823 sess_lto: &Lto,
824 opts: &config::Options,
825 sess_crate_types: &[CrateType],
826 module_kind: ModuleKind,
827) -> ComputedLtoType {
828 let linker_does_lto = opts.cg.linker_plugin_lto.enabled();
832
833 let is_allocator = module_kind == ModuleKind::Allocator;
838
839 let is_rlib = matches!(sess_crate_types, [CrateType::Rlib]);
848
849 match sess_lto {
850 Lto::ThinLocal if !linker_does_lto && !is_allocator => ComputedLtoType::Thin,
851 Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
852 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
853 _ => ComputedLtoType::No,
854 }
855}
856
857fn execute_optimize_work_item<B: ExtraBackendMethods>(
858 cgcx: &CodegenContext<B>,
859 mut module: ModuleCodegen<B::Module>,
860 module_config: &ModuleConfig,
861) -> Result<WorkItemResult<B>, FatalError> {
862 let dcx = cgcx.create_dcx();
863 let dcx = dcx.handle();
864
865 B::optimize(cgcx, dcx, &mut module, module_config)?;
866
867 let lto_type = compute_per_cgu_lto_type(&cgcx.lto, &cgcx.opts, &cgcx.crate_types, module.kind);
873
874 let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
877 let filename = pre_lto_bitcode_filename(&module.name);
878 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
879 } else {
880 None
881 };
882
883 match lto_type {
884 ComputedLtoType::No => finish_intra_module_work(cgcx, module, module_config),
885 ComputedLtoType::Thin => {
886 let (name, thin_buffer) = B::prepare_thin(module, false);
887 if let Some(path) = bitcode {
888 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
889 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
890 });
891 }
892 Ok(WorkItemResult::NeedsThinLto(name, thin_buffer))
893 }
894 ComputedLtoType::Fat => match bitcode {
895 Some(path) => {
896 let (name, buffer) = B::serialize_module(module);
897 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
898 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
899 });
900 Ok(WorkItemResult::NeedsFatLto(FatLtoInput::Serialized { name, buffer }))
901 }
902 None => Ok(WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module))),
903 },
904 }
905}
906
907fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
908 cgcx: &CodegenContext<B>,
909 module: CachedModuleCodegen,
910 module_config: &ModuleConfig,
911) -> WorkItemResult<B> {
912 let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
913
914 let mut links_from_incr_cache = Vec::new();
915
916 let mut load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
917 let source_file = in_incr_comp_dir(incr_comp_session_dir, saved_path);
918 debug!(
919 "copying preexisting module `{}` from {:?} to {}",
920 module.name,
921 source_file,
922 output_path.display()
923 );
924 match link_or_copy(&source_file, &output_path) {
925 Ok(_) => {
926 links_from_incr_cache.push(source_file);
927 Some(output_path)
928 }
929 Err(error) => {
930 cgcx.create_dcx().handle().emit_err(errors::CopyPathBuf {
931 source_file,
932 output_path,
933 error,
934 });
935 None
936 }
937 }
938 };
939
940 let dwarf_object =
941 module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
942 let dwarf_obj_out = cgcx
943 .output_filenames
944 .split_dwarf_path(
945 cgcx.split_debuginfo,
946 cgcx.split_dwarf_kind,
947 &module.name,
948 cgcx.invocation_temp.as_deref(),
949 )
950 .expect(
951 "saved dwarf object in work product but `split_dwarf_path` returned `None`",
952 );
953 load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
954 });
955
956 let mut load_from_incr_cache = |perform, output_type: OutputType| {
957 if perform {
958 let saved_file = module.source.saved_files.get(output_type.extension())?;
959 let output_path = cgcx.output_filenames.temp_path_for_cgu(
960 output_type,
961 &module.name,
962 cgcx.invocation_temp.as_deref(),
963 );
964 load_from_incr_comp_dir(output_path, &saved_file)
965 } else {
966 None
967 }
968 };
969
970 let should_emit_obj = module_config.emit_obj != EmitObj::None;
971 let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
972 let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
973 let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
974 let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
975 if should_emit_obj && object.is_none() {
976 cgcx.create_dcx().handle().emit_fatal(errors::NoSavedObjectFile { cgu_name: &module.name })
977 }
978
979 WorkItemResult::Finished(CompiledModule {
980 links_from_incr_cache,
981 name: module.name,
982 kind: ModuleKind::Regular,
983 object,
984 dwarf_object,
985 bytecode,
986 assembly,
987 llvm_ir,
988 })
989}
990
991fn execute_fat_lto_work_item<B: ExtraBackendMethods>(
992 cgcx: &CodegenContext<B>,
993 needs_fat_lto: Vec<FatLtoInput<B>>,
994 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
995 autodiff: Vec<AutoDiffItem>,
996 module_config: &ModuleConfig,
997) -> Result<WorkItemResult<B>, FatalError> {
998 let module = B::run_and_optimize_fat_lto(cgcx, needs_fat_lto, import_only_modules, autodiff)?;
999 let module = B::codegen(cgcx, module, module_config)?;
1000 Ok(WorkItemResult::Finished(module))
1001}
1002
1003fn execute_thin_lto_work_item<B: ExtraBackendMethods>(
1004 cgcx: &CodegenContext<B>,
1005 module: lto::ThinModule<B>,
1006 module_config: &ModuleConfig,
1007) -> Result<WorkItemResult<B>, FatalError> {
1008 let module = B::optimize_thin(cgcx, module)?;
1009 finish_intra_module_work(cgcx, module, module_config)
1010}
1011
1012fn finish_intra_module_work<B: ExtraBackendMethods>(
1013 cgcx: &CodegenContext<B>,
1014 module: ModuleCodegen<B::Module>,
1015 module_config: &ModuleConfig,
1016) -> Result<WorkItemResult<B>, FatalError> {
1017 if !cgcx.opts.unstable_opts.combine_cgu || module.kind == ModuleKind::Allocator {
1018 let module = B::codegen(cgcx, module, module_config)?;
1019 Ok(WorkItemResult::Finished(module))
1020 } else {
1021 Ok(WorkItemResult::NeedsLink(module))
1022 }
1023}
1024
1025pub(crate) enum Message<B: WriteBackendMethods> {
1027 Token(io::Result<Acquired>),
1030
1031 WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>>, worker_id: usize },
1034
1035 CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
1039
1040 AddImportOnlyModule {
1043 module_data: SerializedModule<B::ModuleBuffer>,
1044 work_product: WorkProduct,
1045 },
1046
1047 CodegenComplete,
1050
1051 CodegenAborted,
1054}
1055
1056pub struct CguMessage;
1059
1060struct Diagnostic {
1070 level: Level,
1071 messages: Vec<(DiagMessage, Style)>,
1072 code: Option<ErrCode>,
1073 children: Vec<Subdiagnostic>,
1074 args: DiagArgMap,
1075}
1076
1077pub(crate) struct Subdiagnostic {
1081 level: Level,
1082 messages: Vec<(DiagMessage, Style)>,
1083}
1084
1085#[derive(PartialEq, Clone, Copy, Debug)]
1086enum MainThreadState {
1087 Idle,
1089
1090 Codegenning,
1092
1093 Lending,
1095}
1096
1097fn start_executing_work<B: ExtraBackendMethods>(
1098 backend: B,
1099 tcx: TyCtxt<'_>,
1100 crate_info: &CrateInfo,
1101 autodiff_items: &[AutoDiffItem],
1102 shared_emitter: SharedEmitter,
1103 codegen_worker_send: Sender<CguMessage>,
1104 coordinator_receive: Receiver<Box<dyn Any + Send>>,
1105 regular_config: Arc<ModuleConfig>,
1106 allocator_config: Arc<ModuleConfig>,
1107 tx_to_llvm_workers: Sender<Box<dyn Any + Send>>,
1108) -> thread::JoinHandle<Result<CompiledModules, ()>> {
1109 let coordinator_send = tx_to_llvm_workers;
1110 let sess = tcx.sess;
1111 let autodiff_items = autodiff_items.to_vec();
1112
1113 let mut each_linked_rlib_for_lto = Vec::new();
1114 drop(link::each_linked_rlib(crate_info, None, &mut |cnum, path| {
1115 if link::ignored_for_lto(sess, crate_info, cnum) {
1116 return;
1117 }
1118 each_linked_rlib_for_lto.push((cnum, path.to_path_buf()));
1119 }));
1120
1121 let exported_symbols = {
1123 let mut exported_symbols = FxHashMap::default();
1124
1125 let copy_symbols = |cnum| {
1126 let symbols = tcx
1127 .exported_non_generic_symbols(cnum)
1128 .iter()
1129 .chain(tcx.exported_generic_symbols(cnum))
1130 .map(|&(s, lvl)| (symbol_name_for_instance_in_crate(tcx, s, cnum), lvl))
1131 .collect();
1132 Arc::new(symbols)
1133 };
1134
1135 match sess.lto() {
1136 Lto::No => None,
1137 Lto::ThinLocal => {
1138 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1139 Some(Arc::new(exported_symbols))
1140 }
1141 Lto::Fat | Lto::Thin => {
1142 exported_symbols.insert(LOCAL_CRATE, copy_symbols(LOCAL_CRATE));
1143 for &(cnum, ref _path) in &each_linked_rlib_for_lto {
1144 exported_symbols.insert(cnum, copy_symbols(cnum));
1145 }
1146 Some(Arc::new(exported_symbols))
1147 }
1148 }
1149 };
1150
1151 let coordinator_send2 = coordinator_send.clone();
1157 let helper = jobserver::client()
1158 .into_helper_thread(move |token| {
1159 drop(coordinator_send2.send(Box::new(Message::Token::<B>(token))));
1160 })
1161 .expect("failed to spawn helper thread");
1162
1163 let ol =
1164 if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
1165 config::OptLevel::No
1167 } else {
1168 tcx.backend_optimization_level(())
1169 };
1170 let backend_features = tcx.global_backend_features(());
1171
1172 let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1173 let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1174 match result {
1175 Ok(dir) => Some(dir),
1176 Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1177 }
1178 } else {
1179 None
1180 };
1181
1182 let cgcx = CodegenContext::<B> {
1183 crate_types: tcx.crate_types().to_vec(),
1184 each_linked_rlib_for_lto,
1185 lto: sess.lto(),
1186 fewer_names: sess.fewer_names(),
1187 save_temps: sess.opts.cg.save_temps,
1188 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1189 opts: Arc::new(sess.opts.clone()),
1190 prof: sess.prof.clone(),
1191 exported_symbols,
1192 remark: sess.opts.cg.remark.clone(),
1193 remark_dir,
1194 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1195 coordinator_send,
1196 expanded_args: tcx.sess.expanded_args.clone(),
1197 diag_emitter: shared_emitter.clone(),
1198 output_filenames: Arc::clone(tcx.output_filenames(())),
1199 regular_module_config: regular_config,
1200 allocator_module_config: allocator_config,
1201 tm_factory: backend.target_machine_factory(tcx.sess, ol, backend_features),
1202 msvc_imps_needed: msvc_imps_needed(tcx),
1203 is_pe_coff: tcx.sess.target.is_like_windows,
1204 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1205 target_arch: tcx.sess.target.arch.to_string(),
1206 target_is_like_darwin: tcx.sess.target.is_like_darwin,
1207 target_is_like_aix: tcx.sess.target.is_like_aix,
1208 split_debuginfo: tcx.sess.split_debuginfo(),
1209 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1210 parallel: backend.supports_parallel() && !sess.opts.unstable_opts.no_parallel_backend,
1211 pointer_size: tcx.data_layout.pointer_size(),
1212 invocation_temp: sess.invocation_temp.clone(),
1213 };
1214
1215 return B::spawn_named_thread(cgcx.time_trace, "coordinator".to_string(), move || {
1351 let mut worker_id_counter = 0;
1352 let mut free_worker_ids = Vec::new();
1353 let mut get_worker_id = |free_worker_ids: &mut Vec<usize>| {
1354 if let Some(id) = free_worker_ids.pop() {
1355 id
1356 } else {
1357 let id = worker_id_counter;
1358 worker_id_counter += 1;
1359 id
1360 }
1361 };
1362
1363 let mut compiled_modules = vec![];
1366 let mut compiled_allocator_module = None;
1367 let mut needs_link = Vec::new();
1368 let mut needs_fat_lto = Vec::new();
1369 let mut needs_thin_lto = Vec::new();
1370 let mut lto_import_only_modules = Vec::new();
1371 let mut started_lto = false;
1372
1373 #[derive(Debug, PartialEq)]
1378 enum CodegenState {
1379 Ongoing,
1380 Completed,
1381 Aborted,
1382 }
1383 use CodegenState::*;
1384 let mut codegen_state = Ongoing;
1385
1386 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1388
1389 let mut tokens = Vec::new();
1392
1393 let mut main_thread_state = MainThreadState::Idle;
1394
1395 let mut running_with_own_token = 0;
1398
1399 let running_with_any_token = |main_thread_state, running_with_own_token| {
1402 running_with_own_token
1403 + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1404 };
1405
1406 let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
1407
1408 loop {
1414 if codegen_state == Ongoing {
1418 if main_thread_state == MainThreadState::Idle {
1419 let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1427 let additional_running = std::cmp::min(extra_tokens, work_items.len());
1428 let anticipated_running = running_with_own_token + additional_running + 1;
1429
1430 if !queue_full_enough(work_items.len(), anticipated_running) {
1431 if codegen_worker_send.send(CguMessage).is_err() {
1433 panic!("Could not send CguMessage to main thread")
1434 }
1435 main_thread_state = MainThreadState::Codegenning;
1436 } else {
1437 let (item, _) =
1441 work_items.pop().expect("queue empty - queue_full_enough() broken?");
1442 main_thread_state = MainThreadState::Lending;
1443 spawn_work(
1444 &cgcx,
1445 &mut llvm_start_time,
1446 get_worker_id(&mut free_worker_ids),
1447 item,
1448 );
1449 }
1450 }
1451 } else if codegen_state == Completed {
1452 if running_with_any_token(main_thread_state, running_with_own_token) == 0
1453 && work_items.is_empty()
1454 {
1455 if needs_fat_lto.is_empty()
1457 && needs_thin_lto.is_empty()
1458 && lto_import_only_modules.is_empty()
1459 {
1460 break;
1462 }
1463
1464 assert!(!started_lto);
1470 started_lto = true;
1471
1472 let needs_fat_lto = mem::take(&mut needs_fat_lto);
1473 let needs_thin_lto = mem::take(&mut needs_thin_lto);
1474 let import_only_modules = mem::take(&mut lto_import_only_modules);
1475
1476 if !needs_fat_lto.is_empty() {
1477 assert!(needs_thin_lto.is_empty());
1478
1479 work_items.push((
1480 WorkItem::FatLto {
1481 needs_fat_lto,
1482 import_only_modules,
1483 autodiff: autodiff_items.clone(),
1484 },
1485 0,
1486 ));
1487 if cgcx.parallel {
1488 helper.request_token();
1489 }
1490 } else {
1491 if !autodiff_items.is_empty() {
1492 let dcx = cgcx.create_dcx();
1493 dcx.handle().emit_fatal(AutodiffWithoutLto {});
1494 }
1495
1496 for (work, cost) in
1497 generate_thin_lto_work(&cgcx, needs_thin_lto, import_only_modules)
1498 {
1499 let insertion_index = work_items
1500 .binary_search_by_key(&cost, |&(_, cost)| cost)
1501 .unwrap_or_else(|e| e);
1502 work_items.insert(insertion_index, (work, cost));
1503 if cgcx.parallel {
1504 helper.request_token();
1505 }
1506 }
1507 }
1508 }
1509
1510 match main_thread_state {
1514 MainThreadState::Idle => {
1515 if let Some((item, _)) = work_items.pop() {
1516 main_thread_state = MainThreadState::Lending;
1517 spawn_work(
1518 &cgcx,
1519 &mut llvm_start_time,
1520 get_worker_id(&mut free_worker_ids),
1521 item,
1522 );
1523 } else {
1524 assert!(running_with_own_token > 0);
1531 running_with_own_token -= 1;
1532 main_thread_state = MainThreadState::Lending;
1533 }
1534 }
1535 MainThreadState::Codegenning => bug!(
1536 "codegen worker should not be codegenning after \
1537 codegen was already completed"
1538 ),
1539 MainThreadState::Lending => {
1540 }
1542 }
1543 } else {
1544 assert!(codegen_state == Aborted);
1547 if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1548 break;
1549 }
1550 }
1551
1552 if codegen_state != Aborted {
1555 while running_with_own_token < tokens.len()
1556 && let Some((item, _)) = work_items.pop()
1557 {
1558 spawn_work(
1559 &cgcx,
1560 &mut llvm_start_time,
1561 get_worker_id(&mut free_worker_ids),
1562 item,
1563 );
1564 running_with_own_token += 1;
1565 }
1566 }
1567
1568 tokens.truncate(running_with_own_token);
1570
1571 let mut free_worker = |worker_id| {
1577 if main_thread_state == MainThreadState::Lending {
1578 main_thread_state = MainThreadState::Idle;
1579 } else {
1580 running_with_own_token -= 1;
1581 }
1582
1583 free_worker_ids.push(worker_id);
1584 };
1585
1586 let msg = coordinator_receive.recv().unwrap();
1587 match *msg.downcast::<Message<B>>().ok().unwrap() {
1588 Message::Token(token) => {
1592 match token {
1593 Ok(token) => {
1594 tokens.push(token);
1595
1596 if main_thread_state == MainThreadState::Lending {
1597 main_thread_state = MainThreadState::Idle;
1602 running_with_own_token += 1;
1603 }
1604 }
1605 Err(e) => {
1606 let msg = &format!("failed to acquire jobserver token: {e}");
1607 shared_emitter.fatal(msg);
1608 codegen_state = Aborted;
1609 }
1610 }
1611 }
1612
1613 Message::CodegenDone { llvm_work_item, cost } => {
1614 let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1623 let insertion_index = match insertion_index {
1624 Ok(idx) | Err(idx) => idx,
1625 };
1626 work_items.insert(insertion_index, (llvm_work_item, cost));
1627
1628 if cgcx.parallel {
1629 helper.request_token();
1630 }
1631 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1632 main_thread_state = MainThreadState::Idle;
1633 }
1634
1635 Message::CodegenComplete => {
1636 if codegen_state != Aborted {
1637 codegen_state = Completed;
1638 }
1639 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1640 main_thread_state = MainThreadState::Idle;
1641 }
1642
1643 Message::CodegenAborted => {
1651 codegen_state = Aborted;
1652 }
1653
1654 Message::WorkItem { result, worker_id } => {
1655 free_worker(worker_id);
1656
1657 match result {
1658 Ok(WorkItemResult::Finished(compiled_module)) => {
1659 match compiled_module.kind {
1660 ModuleKind::Regular => {
1661 assert!(needs_link.is_empty());
1662 compiled_modules.push(compiled_module);
1663 }
1664 ModuleKind::Allocator => {
1665 assert!(compiled_allocator_module.is_none());
1666 compiled_allocator_module = Some(compiled_module);
1667 }
1668 }
1669 }
1670 Ok(WorkItemResult::NeedsLink(module)) => {
1671 assert!(compiled_modules.is_empty());
1672 needs_link.push(module);
1673 }
1674 Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1675 assert!(!started_lto);
1676 assert!(needs_thin_lto.is_empty());
1677 needs_fat_lto.push(fat_lto_input);
1678 }
1679 Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1680 assert!(!started_lto);
1681 assert!(needs_fat_lto.is_empty());
1682 needs_thin_lto.push((name, thin_buffer));
1683 }
1684 Err(Some(WorkerFatalError)) => {
1685 codegen_state = Aborted;
1687 }
1688 Err(None) => {
1689 bug!("worker thread panicked");
1692 }
1693 }
1694 }
1695
1696 Message::AddImportOnlyModule { module_data, work_product } => {
1697 assert!(!started_lto);
1698 assert_eq!(codegen_state, Ongoing);
1699 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1700 lto_import_only_modules.push((module_data, work_product));
1701 main_thread_state = MainThreadState::Idle;
1702 }
1703 }
1704 }
1705
1706 if codegen_state == Aborted {
1707 return Err(());
1708 }
1709
1710 let needs_link = mem::take(&mut needs_link);
1711 if !needs_link.is_empty() {
1712 assert!(compiled_modules.is_empty());
1713 let dcx = cgcx.create_dcx();
1714 let dcx = dcx.handle();
1715 let module = B::run_link(&cgcx, dcx, needs_link).map_err(|_| ())?;
1716 let module =
1717 B::codegen(&cgcx, module, cgcx.config(ModuleKind::Regular)).map_err(|_| ())?;
1718 compiled_modules.push(module);
1719 }
1720
1721 drop(llvm_start_time);
1723
1724 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1728
1729 Ok(CompiledModules {
1730 modules: compiled_modules,
1731 allocator_module: compiled_allocator_module,
1732 })
1733 })
1734 .expect("failed to spawn coordinator thread");
1735
1736 fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1739 let quarter_of_workers = workers_running - 3 * workers_running / 4;
1790 items_in_queue > 0 && items_in_queue >= quarter_of_workers
1791 }
1792}
1793
1794#[must_use]
1796pub(crate) struct WorkerFatalError;
1797
1798fn spawn_work<'a, B: ExtraBackendMethods>(
1799 cgcx: &'a CodegenContext<B>,
1800 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1801 worker_id: usize,
1802 work: WorkItem<B>,
1803) {
1804 if cgcx.config(work.module_kind()).time_module && llvm_start_time.is_none() {
1805 *llvm_start_time = Some(cgcx.prof.verbose_generic_activity("LLVM_passes"));
1806 }
1807
1808 let cgcx = cgcx.clone();
1809
1810 B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1811 struct Bomb<B: ExtraBackendMethods> {
1814 coordinator_send: Sender<Box<dyn Any + Send>>,
1815 result: Option<Result<WorkItemResult<B>, FatalError>>,
1816 worker_id: usize,
1817 }
1818 impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1819 fn drop(&mut self) {
1820 let worker_id = self.worker_id;
1821 let msg = match self.result.take() {
1822 Some(Ok(result)) => Message::WorkItem::<B> { result: Ok(result), worker_id },
1823 Some(Err(FatalError)) => {
1824 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)), worker_id }
1825 }
1826 None => Message::WorkItem::<B> { result: Err(None), worker_id },
1827 };
1828 drop(self.coordinator_send.send(Box::new(msg)));
1829 }
1830 }
1831
1832 let mut bomb =
1833 Bomb::<B> { coordinator_send: cgcx.coordinator_send.clone(), result: None, worker_id };
1834
1835 bomb.result = {
1842 let module_config = cgcx.config(work.module_kind());
1843
1844 Some(match work {
1845 WorkItem::Optimize(m) => {
1846 let _timer =
1847 cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &*m.name);
1848 execute_optimize_work_item(&cgcx, m, module_config)
1849 }
1850 WorkItem::CopyPostLtoArtifacts(m) => {
1851 let _timer = cgcx.prof.generic_activity_with_arg(
1852 "codegen_copy_artifacts_from_incr_cache",
1853 &*m.name,
1854 );
1855 Ok(execute_copy_from_cache_work_item(&cgcx, m, module_config))
1856 }
1857 WorkItem::FatLto { needs_fat_lto, import_only_modules, autodiff } => {
1858 let _timer = cgcx
1859 .prof
1860 .generic_activity_with_arg("codegen_module_perform_lto", "everything");
1861 execute_fat_lto_work_item(
1862 &cgcx,
1863 needs_fat_lto,
1864 import_only_modules,
1865 autodiff,
1866 module_config,
1867 )
1868 }
1869 WorkItem::ThinLto(m) => {
1870 let _timer =
1871 cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", m.name());
1872 execute_thin_lto_work_item(&cgcx, m, module_config)
1873 }
1874 })
1875 };
1876 })
1877 .expect("failed to spawn work thread");
1878}
1879
1880enum SharedEmitterMessage {
1881 Diagnostic(Diagnostic),
1882 InlineAsmError(SpanData, String, Level, Option<(String, Vec<InnerSpan>)>),
1883 Fatal(String),
1884}
1885
1886#[derive(Clone)]
1887pub struct SharedEmitter {
1888 sender: Sender<SharedEmitterMessage>,
1889}
1890
1891pub struct SharedEmitterMain {
1892 receiver: Receiver<SharedEmitterMessage>,
1893}
1894
1895impl SharedEmitter {
1896 fn new() -> (SharedEmitter, SharedEmitterMain) {
1897 let (sender, receiver) = channel();
1898
1899 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1900 }
1901
1902 pub fn inline_asm_error(
1903 &self,
1904 span: SpanData,
1905 msg: String,
1906 level: Level,
1907 source: Option<(String, Vec<InnerSpan>)>,
1908 ) {
1909 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(span, msg, level, source)));
1910 }
1911
1912 fn fatal(&self, msg: &str) {
1913 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1914 }
1915}
1916
1917impl Emitter for SharedEmitter {
1918 fn emit_diagnostic(
1919 &mut self,
1920 mut diag: rustc_errors::DiagInner,
1921 _registry: &rustc_errors::registry::Registry,
1922 ) {
1923 assert_eq!(diag.span, MultiSpan::new());
1926 assert_eq!(diag.suggestions, Suggestions::Enabled(vec![]));
1927 assert_eq!(diag.sort_span, rustc_span::DUMMY_SP);
1928 assert_eq!(diag.is_lint, None);
1929 let args = mem::replace(&mut diag.args, DiagArgMap::default());
1932 drop(
1933 self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1934 level: diag.level(),
1935 messages: diag.messages,
1936 code: diag.code,
1937 children: diag
1938 .children
1939 .into_iter()
1940 .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
1941 .collect(),
1942 args,
1943 })),
1944 );
1945 }
1946
1947 fn source_map(&self) -> Option<&SourceMap> {
1948 None
1949 }
1950
1951 fn translator(&self) -> &Translator {
1952 panic!("shared emitter attempted to translate a diagnostic");
1953 }
1954}
1955
1956impl SharedEmitterMain {
1957 fn check(&self, sess: &Session, blocking: bool) {
1958 loop {
1959 let message = if blocking {
1960 match self.receiver.recv() {
1961 Ok(message) => Ok(message),
1962 Err(_) => Err(()),
1963 }
1964 } else {
1965 match self.receiver.try_recv() {
1966 Ok(message) => Ok(message),
1967 Err(_) => Err(()),
1968 }
1969 };
1970
1971 match message {
1972 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1973 let dcx = sess.dcx();
1976 let mut d =
1977 rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
1978 d.code = diag.code; d.children = diag
1980 .children
1981 .into_iter()
1982 .map(|sub| rustc_errors::Subdiag {
1983 level: sub.level,
1984 messages: sub.messages,
1985 span: MultiSpan::new(),
1986 })
1987 .collect();
1988 d.args = diag.args;
1989 dcx.emit_diagnostic(d);
1990 sess.dcx().abort_if_errors();
1991 }
1992 Ok(SharedEmitterMessage::InlineAsmError(span, msg, level, source)) => {
1993 assert_matches!(level, Level::Error | Level::Warning | Level::Note);
1994 let mut err = Diag::<()>::new(sess.dcx(), level, msg);
1995 if !span.is_dummy() {
1996 err.span(span.span());
1997 }
1998
1999 if let Some((buffer, spans)) = source {
2001 let source = sess
2002 .source_map()
2003 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
2004 let spans: Vec<_> = spans
2005 .iter()
2006 .map(|sp| {
2007 Span::with_root_ctxt(
2008 source.normalized_byte_pos(sp.start as u32),
2009 source.normalized_byte_pos(sp.end as u32),
2010 )
2011 })
2012 .collect();
2013 err.span_note(spans, "instantiated into assembly here");
2014 }
2015
2016 err.emit();
2017 }
2018 Ok(SharedEmitterMessage::Fatal(msg)) => {
2019 sess.dcx().fatal(msg);
2020 }
2021 Err(_) => {
2022 break;
2023 }
2024 }
2025 }
2026 }
2027}
2028
2029pub struct Coordinator<B: ExtraBackendMethods> {
2030 pub sender: Sender<Box<dyn Any + Send>>,
2031 future: Option<thread::JoinHandle<Result<CompiledModules, ()>>>,
2032 phantom: PhantomData<B>,
2034}
2035
2036impl<B: ExtraBackendMethods> Coordinator<B> {
2037 fn join(mut self) -> std::thread::Result<Result<CompiledModules, ()>> {
2038 self.future.take().unwrap().join()
2039 }
2040}
2041
2042impl<B: ExtraBackendMethods> Drop for Coordinator<B> {
2043 fn drop(&mut self) {
2044 if let Some(future) = self.future.take() {
2045 drop(self.sender.send(Box::new(Message::CodegenAborted::<B>)));
2048 drop(future.join());
2049 }
2050 }
2051}
2052
2053pub struct OngoingCodegen<B: ExtraBackendMethods> {
2054 pub backend: B,
2055 pub crate_info: CrateInfo,
2056 pub codegen_worker_receive: Receiver<CguMessage>,
2057 pub shared_emitter_main: SharedEmitterMain,
2058 pub output_filenames: Arc<OutputFilenames>,
2059 pub coordinator: Coordinator<B>,
2060}
2061
2062impl<B: ExtraBackendMethods> OngoingCodegen<B> {
2063 pub fn join(self, sess: &Session) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
2064 self.shared_emitter_main.check(sess, true);
2065 let compiled_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
2066 Ok(Ok(compiled_modules)) => compiled_modules,
2067 Ok(Err(())) => {
2068 sess.dcx().abort_if_errors();
2069 panic!("expected abort due to worker thread errors")
2070 }
2071 Err(_) => {
2072 bug!("panic during codegen/LLVM phase");
2073 }
2074 });
2075
2076 sess.dcx().abort_if_errors();
2077
2078 let work_products =
2079 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
2080 produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
2081
2082 if sess.codegen_units().as_usize() == 1 && sess.opts.unstable_opts.time_llvm_passes {
2085 self.backend.print_pass_timings()
2086 }
2087
2088 if sess.print_llvm_stats() {
2089 self.backend.print_statistics()
2090 }
2091
2092 (
2093 CodegenResults {
2094 crate_info: self.crate_info,
2095
2096 modules: compiled_modules.modules,
2097 allocator_module: compiled_modules.allocator_module,
2098 },
2099 work_products,
2100 )
2101 }
2102
2103 pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2104 self.wait_for_signal_to_codegen_item();
2105 self.check_for_errors(tcx.sess);
2106 drop(self.coordinator.sender.send(Box::new(Message::CodegenComplete::<B>)));
2107 }
2108
2109 pub(crate) fn check_for_errors(&self, sess: &Session) {
2110 self.shared_emitter_main.check(sess, false);
2111 }
2112
2113 pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2114 match self.codegen_worker_receive.recv() {
2115 Ok(CguMessage) => {
2116 }
2118 Err(_) => {
2119 }
2122 }
2123 }
2124}
2125
2126pub(crate) fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
2127 _backend: &B,
2128 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
2129 module: ModuleCodegen<B::Module>,
2130 cost: u64,
2131) {
2132 let llvm_work_item = WorkItem::Optimize(module);
2133 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost })));
2134}
2135
2136pub(crate) fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
2137 _backend: &B,
2138 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
2139 module: CachedModuleCodegen,
2140) {
2141 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2142 drop(tx_to_llvm_workers.send(Box::new(Message::CodegenDone::<B> { llvm_work_item, cost: 0 })));
2143}
2144
2145pub(crate) fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
2146 _backend: &B,
2147 tcx: TyCtxt<'_>,
2148 tx_to_llvm_workers: &Sender<Box<dyn Any + Send>>,
2149 module: CachedModuleCodegen,
2150) {
2151 let filename = pre_lto_bitcode_filename(&module.name);
2152 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2153 let file = fs::File::open(&bc_path)
2154 .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
2155
2156 let mmap = unsafe {
2157 Mmap::map(file).unwrap_or_else(|e| {
2158 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2159 })
2160 };
2161 drop(tx_to_llvm_workers.send(Box::new(Message::AddImportOnlyModule::<B> {
2163 module_data: SerializedModule::FromUncompressedFile(mmap),
2164 work_product: module.source,
2165 })));
2166}
2167
2168fn pre_lto_bitcode_filename(module_name: &str) -> String {
2169 format!("{module_name}.{PRE_LTO_BC_EXT}")
2170}
2171
2172fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2173 assert!(
2176 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2177 && tcx.sess.target.is_like_windows
2178 && tcx.sess.opts.cg.prefer_dynamic)
2179 );
2180
2181 let can_have_static_objects =
2185 tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
2186
2187 tcx.sess.target.is_like_windows &&
2188 can_have_static_objects &&
2189 !tcx.sess.opts.cg.linker_plugin_lto.enabled()
2193}