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 || sess.opts.cg.linker_plugin_lto.enabled() {
142 EmitObj::Bitcode
148 } else if need_bitcode_in_object(tcx) {
149 EmitObj::ObjectCode(BitcodeSection::Full)
150 } else {
151 EmitObj::ObjectCode(BitcodeSection::None)
152 };
153
154 ModuleConfig {
155 passes: if_regular!(sess.opts.cg.passes.clone(), vec![]),
156
157 opt_level: opt_level_and_size,
158
159 pgo_gen: if_regular!(
160 sess.opts.cg.profile_generate.clone(),
161 SwitchWithOptPath::Disabled
162 ),
163 pgo_use: if_regular!(sess.opts.cg.profile_use.clone(), None),
164 pgo_sample_use: if_regular!(sess.opts.unstable_opts.profile_sample_use.clone(), None),
165 debug_info_for_profiling: sess.opts.unstable_opts.debug_info_for_profiling,
166 instrument_coverage: if_regular!(sess.instrument_coverage(), false),
167
168 sanitizer: if_regular!(sess.opts.unstable_opts.sanitizer, SanitizerSet::empty()),
169 sanitizer_dataflow_abilist: if_regular!(
170 sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
171 Vec::new()
172 ),
173 sanitizer_recover: if_regular!(
174 sess.opts.unstable_opts.sanitizer_recover,
175 SanitizerSet::empty()
176 ),
177 sanitizer_memory_track_origins: if_regular!(
178 sess.opts.unstable_opts.sanitizer_memory_track_origins,
179 0
180 ),
181
182 emit_pre_lto_bc: if_regular!(
183 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
184 false
185 ),
186 emit_no_opt_bc: if_regular!(save_temps, false),
187 emit_bc: if_regular!(
188 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
189 save_temps
190 ),
191 emit_ir: if_regular!(
192 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
193 false
194 ),
195 emit_asm: if_regular!(
196 sess.opts.output_types.contains_key(&OutputType::Assembly),
197 false
198 ),
199 emit_obj,
200 emit_thin_lto: sess.opts.unstable_opts.emit_thin_lto && sess.lto() != Lto::Fat,
203 emit_thin_lto_summary: if_regular!(
204 sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode),
205 false
206 ),
207
208 verify_llvm_ir: sess.verify_llvm_ir(),
209 lint_llvm_ir: sess.opts.unstable_opts.lint_llvm_ir,
210 no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
211 no_builtins: no_builtins || sess.target.no_builtins,
212
213 vectorize_loop: !sess.opts.cg.no_vectorize_loops
216 && (sess.opts.optimize == config::OptLevel::More
217 || sess.opts.optimize == config::OptLevel::Aggressive),
218 vectorize_slp: !sess.opts.cg.no_vectorize_slp
219 && sess.opts.optimize == config::OptLevel::Aggressive,
220
221 merge_functions: match sess
231 .opts
232 .unstable_opts
233 .merge_functions
234 .unwrap_or(sess.target.merge_functions)
235 {
236 MergeFunctions::Disabled => false,
237 MergeFunctions::Trampolines | MergeFunctions::Aliases => {
238 use config::OptLevel::*;
239 match sess.opts.optimize {
240 Aggressive | More | SizeMin | Size => true,
241 Less | No => false,
242 }
243 }
244 },
245
246 emit_lifetime_markers: sess.emit_lifetime_markers(),
247 llvm_plugins: if_regular!(sess.opts.unstable_opts.llvm_plugins.clone(), vec![]),
248 autodiff: if_regular!(sess.opts.unstable_opts.autodiff.clone(), vec![]),
249 offload: if_regular!(sess.opts.unstable_opts.offload.clone(), vec![]),
250 }
251 }
252
253 pub fn bitcode_needed(&self) -> bool {
254 self.emit_bc
255 || self.emit_thin_lto_summary
256 || self.emit_obj == EmitObj::Bitcode
257 || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
258 }
259
260 pub fn embed_bitcode(&self) -> bool {
261 self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
262 }
263}
264
265pub struct TargetMachineFactoryConfig {
267 pub split_dwarf_file: Option<PathBuf>,
271
272 pub output_obj_file: Option<PathBuf>,
275}
276
277impl TargetMachineFactoryConfig {
278 pub fn new(
279 cgcx: &CodegenContext<impl WriteBackendMethods>,
280 module_name: &str,
281 ) -> TargetMachineFactoryConfig {
282 let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
283 cgcx.output_filenames.split_dwarf_path(
284 cgcx.split_debuginfo,
285 cgcx.split_dwarf_kind,
286 module_name,
287 cgcx.invocation_temp.as_deref(),
288 )
289 } else {
290 None
291 };
292
293 let output_obj_file = Some(cgcx.output_filenames.temp_path_for_cgu(
294 OutputType::Object,
295 module_name,
296 cgcx.invocation_temp.as_deref(),
297 ));
298 TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }
299 }
300}
301
302pub type TargetMachineFactoryFn<B> = Arc<
303 dyn Fn(
304 TargetMachineFactoryConfig,
305 ) -> Result<
306 <B as WriteBackendMethods>::TargetMachine,
307 <B as WriteBackendMethods>::TargetMachineError,
308 > + Send
309 + Sync,
310>;
311
312#[derive(Clone)]
314pub struct CodegenContext<B: WriteBackendMethods> {
315 pub prof: SelfProfilerRef,
317 pub lto: Lto,
318 pub save_temps: bool,
319 pub fewer_names: bool,
320 pub time_trace: bool,
321 pub opts: Arc<config::Options>,
322 pub crate_types: Vec<CrateType>,
323 pub output_filenames: Arc<OutputFilenames>,
324 pub invocation_temp: Option<String>,
325 pub regular_module_config: Arc<ModuleConfig>,
326 pub allocator_module_config: Arc<ModuleConfig>,
327 pub tm_factory: TargetMachineFactoryFn<B>,
328 pub msvc_imps_needed: bool,
329 pub is_pe_coff: bool,
330 pub target_can_use_split_dwarf: bool,
331 pub target_arch: String,
332 pub target_is_like_darwin: bool,
333 pub target_is_like_aix: bool,
334 pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
335 pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
336 pub pointer_size: Size,
337
338 pub expanded_args: Vec<String>,
343
344 pub diag_emitter: SharedEmitter,
346 pub remark: Passes,
348 pub remark_dir: Option<PathBuf>,
351 pub incr_comp_session_dir: Option<PathBuf>,
354 pub parallel: bool,
358}
359
360impl<B: WriteBackendMethods> CodegenContext<B> {
361 pub fn create_dcx(&self) -> DiagCtxt {
362 DiagCtxt::new(Box::new(self.diag_emitter.clone()))
363 }
364
365 pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
366 match kind {
367 ModuleKind::Regular => &self.regular_module_config,
368 ModuleKind::Allocator => &self.allocator_module_config,
369 }
370 }
371}
372
373fn generate_thin_lto_work<B: ExtraBackendMethods>(
374 cgcx: &CodegenContext<B>,
375 exported_symbols_for_lto: &[String],
376 each_linked_rlib_for_lto: &[PathBuf],
377 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
378 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
379) -> Vec<(WorkItem<B>, u64)> {
380 let _prof_timer = cgcx.prof.generic_activity("codegen_thin_generate_lto_work");
381
382 let (lto_modules, copy_jobs) = B::run_thin_lto(
383 cgcx,
384 exported_symbols_for_lto,
385 each_linked_rlib_for_lto,
386 needs_thin_lto,
387 import_only_modules,
388 );
389 lto_modules
390 .into_iter()
391 .map(|module| {
392 let cost = module.cost();
393 (WorkItem::ThinLto(module), cost)
394 })
395 .chain(copy_jobs.into_iter().map(|wp| {
396 (
397 WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
398 name: wp.cgu_name.clone(),
399 source: wp,
400 }),
401 0, )
403 }))
404 .collect()
405}
406
407struct CompiledModules {
408 modules: Vec<CompiledModule>,
409 allocator_module: Option<CompiledModule>,
410}
411
412fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
413 let sess = tcx.sess;
414 sess.opts.cg.embed_bitcode
415 && tcx.crate_types().contains(&CrateType::Rlib)
416 && sess.opts.output_types.contains_key(&OutputType::Exe)
417}
418
419fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
420 if sess.opts.incremental.is_none() {
421 return false;
422 }
423
424 match sess.lto() {
425 Lto::No => false,
426 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
427 }
428}
429
430pub(crate) fn start_async_codegen<B: ExtraBackendMethods>(
431 backend: B,
432 tcx: TyCtxt<'_>,
433 target_cpu: String,
434) -> OngoingCodegen<B> {
435 let (coordinator_send, coordinator_receive) = channel();
436
437 let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
438 let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins);
439
440 let crate_info = CrateInfo::new(tcx, target_cpu);
441
442 let regular_config = ModuleConfig::new(ModuleKind::Regular, tcx, no_builtins);
443 let allocator_config = ModuleConfig::new(ModuleKind::Allocator, tcx, no_builtins);
444
445 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
446 let (codegen_worker_send, codegen_worker_receive) = channel();
447
448 let coordinator_thread = start_executing_work(
449 backend.clone(),
450 tcx,
451 &crate_info,
452 shared_emitter,
453 codegen_worker_send,
454 coordinator_receive,
455 Arc::new(regular_config),
456 Arc::new(allocator_config),
457 coordinator_send.clone(),
458 );
459
460 OngoingCodegen {
461 backend,
462 crate_info,
463
464 codegen_worker_receive,
465 shared_emitter_main,
466 coordinator: Coordinator {
467 sender: coordinator_send,
468 future: Some(coordinator_thread),
469 phantom: PhantomData,
470 },
471 output_filenames: Arc::clone(tcx.output_filenames(())),
472 }
473}
474
475fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
476 sess: &Session,
477 compiled_modules: &CompiledModules,
478) -> FxIndexMap<WorkProductId, WorkProduct> {
479 let mut work_products = FxIndexMap::default();
480
481 if sess.opts.incremental.is_none() {
482 return work_products;
483 }
484
485 let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
486
487 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
488 let mut files = Vec::new();
489 if let Some(object_file_path) = &module.object {
490 files.push((OutputType::Object.extension(), object_file_path.as_path()));
491 }
492 if let Some(dwarf_object_file_path) = &module.dwarf_object {
493 files.push(("dwo", dwarf_object_file_path.as_path()));
494 }
495 if let Some(path) = &module.assembly {
496 files.push((OutputType::Assembly.extension(), path.as_path()));
497 }
498 if let Some(path) = &module.llvm_ir {
499 files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
500 }
501 if let Some(path) = &module.bytecode {
502 files.push((OutputType::Bitcode.extension(), path.as_path()));
503 }
504 if let Some((id, product)) = copy_cgu_workproduct_to_incr_comp_cache_dir(
505 sess,
506 &module.name,
507 files.as_slice(),
508 &module.links_from_incr_cache,
509 ) {
510 work_products.insert(id, product);
511 }
512 }
513
514 work_products
515}
516
517fn produce_final_output_artifacts(
518 sess: &Session,
519 compiled_modules: &CompiledModules,
520 crate_output: &OutputFilenames,
521) {
522 let mut user_wants_bitcode = false;
523 let mut user_wants_objects = false;
524
525 let copy_gracefully = |from: &Path, to: &OutFileName| match to {
527 OutFileName::Stdout if let Err(e) = copy_to_stdout(from) => {
528 sess.dcx().emit_err(errors::CopyPath::new(from, to.as_path(), e));
529 }
530 OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
531 sess.dcx().emit_err(errors::CopyPath::new(from, path, e));
532 }
533 _ => {}
534 };
535
536 let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
537 if let [module] = &compiled_modules.modules[..] {
538 let path = crate_output.temp_path_for_cgu(
541 output_type,
542 &module.name,
543 sess.invocation_temp.as_deref(),
544 );
545 let output = crate_output.path(output_type);
546 if !output_type.is_text_output() && output.is_tty() {
547 sess.dcx()
548 .emit_err(errors::BinaryOutputToTty { shorthand: output_type.shorthand() });
549 } else {
550 copy_gracefully(&path, &output);
551 }
552 if !sess.opts.cg.save_temps && !keep_numbered {
553 ensure_removed(sess.dcx(), &path);
555 }
556 } else {
557 if crate_output.outputs.contains_explicit_name(&output_type) {
558 sess.dcx()
561 .emit_warn(errors::IgnoringEmitPath { extension: output_type.extension() });
562 } else if crate_output.single_output_file.is_some() {
563 sess.dcx().emit_warn(errors::IgnoringOutput { extension: output_type.extension() });
566 } else {
567 }
571 }
572 };
573
574 for output_type in crate_output.outputs.keys() {
578 match *output_type {
579 OutputType::Bitcode => {
580 user_wants_bitcode = true;
581 copy_if_one_unit(OutputType::Bitcode, true);
585 }
586 OutputType::ThinLinkBitcode => {
587 copy_if_one_unit(OutputType::ThinLinkBitcode, false);
588 }
589 OutputType::LlvmAssembly => {
590 copy_if_one_unit(OutputType::LlvmAssembly, false);
591 }
592 OutputType::Assembly => {
593 copy_if_one_unit(OutputType::Assembly, false);
594 }
595 OutputType::Object => {
596 user_wants_objects = true;
597 copy_if_one_unit(OutputType::Object, true);
598 }
599 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
600 }
601 }
602
603 if !sess.opts.cg.save_temps {
616 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
632
633 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
634
635 let keep_numbered_objects =
636 needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
637
638 for module in compiled_modules.modules.iter() {
639 if !keep_numbered_objects {
640 if let Some(ref path) = module.object {
641 ensure_removed(sess.dcx(), path);
642 }
643
644 if let Some(ref path) = module.dwarf_object {
645 ensure_removed(sess.dcx(), path);
646 }
647 }
648
649 if let Some(ref path) = module.bytecode {
650 if !keep_numbered_bitcode {
651 ensure_removed(sess.dcx(), path);
652 }
653 }
654 }
655
656 if !user_wants_bitcode
657 && let Some(ref allocator_module) = compiled_modules.allocator_module
658 && let Some(ref path) = allocator_module.bytecode
659 {
660 ensure_removed(sess.dcx(), path);
661 }
662 }
663
664 if sess.opts.json_artifact_notifications {
665 if let [module] = &compiled_modules.modules[..] {
666 module.for_each_output(|_path, ty| {
667 if sess.opts.output_types.contains_key(&ty) {
668 let descr = ty.shorthand();
669 let path = crate_output.path(ty);
672 sess.dcx().emit_artifact_notification(path.as_path(), descr);
673 }
674 });
675 } else {
676 for module in &compiled_modules.modules {
677 module.for_each_output(|path, ty| {
678 if sess.opts.output_types.contains_key(&ty) {
679 let descr = ty.shorthand();
680 sess.dcx().emit_artifact_notification(&path, descr);
681 }
682 });
683 }
684 }
685 }
686
687 }
693
694pub(crate) enum WorkItem<B: WriteBackendMethods> {
695 Optimize(ModuleCodegen<B::Module>),
697 CopyPostLtoArtifacts(CachedModuleCodegen),
700 FatLto {
702 exported_symbols_for_lto: Arc<Vec<String>>,
703 each_linked_rlib_for_lto: Vec<PathBuf>,
704 needs_fat_lto: Vec<FatLtoInput<B>>,
705 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
706 },
707 ThinLto(lto::ThinModule<B>),
709}
710
711impl<B: WriteBackendMethods> WorkItem<B> {
712 fn module_kind(&self) -> ModuleKind {
713 match *self {
714 WorkItem::Optimize(ref m) => m.kind,
715 WorkItem::CopyPostLtoArtifacts(_) | WorkItem::FatLto { .. } | WorkItem::ThinLto(_) => {
716 ModuleKind::Regular
717 }
718 }
719 }
720
721 fn short_description(&self) -> String {
723 #[cfg(not(windows))]
727 fn desc(short: &str, _long: &str, name: &str) -> String {
728 assert_eq!(short.len(), 3);
748 let name = if let Some(index) = name.find("-cgu.") {
749 &name[index + 1..] } else {
751 name
752 };
753 format!("{short} {name}")
754 }
755
756 #[cfg(windows)]
758 fn desc(_short: &str, long: &str, name: &str) -> String {
759 format!("{long} {name}")
760 }
761
762 match self {
763 WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
764 WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
765 WorkItem::FatLto { .. } => desc("lto", "fat LTO module", "everything"),
766 WorkItem::ThinLto(m) => desc("lto", "thin-LTO module", m.name()),
767 }
768 }
769}
770
771pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
773 Finished(CompiledModule),
775
776 NeedsFatLto(FatLtoInput<B>),
779
780 NeedsThinLto(String, B::ThinBuffer),
783}
784
785pub enum FatLtoInput<B: WriteBackendMethods> {
786 Serialized { name: String, buffer: SerializedModule<B::ModuleBuffer> },
787 InMemory(ModuleCodegen<B::Module>),
788}
789
790pub(crate) enum ComputedLtoType {
792 No,
793 Thin,
794 Fat,
795}
796
797pub(crate) fn compute_per_cgu_lto_type(
798 sess_lto: &Lto,
799 opts: &config::Options,
800 sess_crate_types: &[CrateType],
801 module_kind: ModuleKind,
802) -> ComputedLtoType {
803 let linker_does_lto = opts.cg.linker_plugin_lto.enabled();
807
808 let is_allocator = module_kind == ModuleKind::Allocator;
813
814 let is_rlib = matches!(sess_crate_types, [CrateType::Rlib]);
823
824 match sess_lto {
825 Lto::ThinLocal if !linker_does_lto && !is_allocator => ComputedLtoType::Thin,
826 Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
827 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
828 _ => ComputedLtoType::No,
829 }
830}
831
832fn execute_optimize_work_item<B: ExtraBackendMethods>(
833 cgcx: &CodegenContext<B>,
834 mut module: ModuleCodegen<B::Module>,
835 module_config: &ModuleConfig,
836) -> WorkItemResult<B> {
837 let dcx = cgcx.create_dcx();
838 let dcx = dcx.handle();
839
840 B::optimize(cgcx, dcx, &mut module, module_config);
841
842 let lto_type = compute_per_cgu_lto_type(&cgcx.lto, &cgcx.opts, &cgcx.crate_types, module.kind);
848
849 let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
852 let filename = pre_lto_bitcode_filename(&module.name);
853 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
854 } else {
855 None
856 };
857
858 match lto_type {
859 ComputedLtoType::No => {
860 let module = B::codegen(cgcx, module, module_config);
861 WorkItemResult::Finished(module)
862 }
863 ComputedLtoType::Thin => {
864 let (name, thin_buffer) = B::prepare_thin(module, false);
865 if let Some(path) = bitcode {
866 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
867 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
868 });
869 }
870 WorkItemResult::NeedsThinLto(name, thin_buffer)
871 }
872 ComputedLtoType::Fat => match bitcode {
873 Some(path) => {
874 let (name, buffer) = B::serialize_module(module);
875 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
876 panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
877 });
878 WorkItemResult::NeedsFatLto(FatLtoInput::Serialized {
879 name,
880 buffer: SerializedModule::Local(buffer),
881 })
882 }
883 None => WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module)),
884 },
885 }
886}
887
888fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
889 cgcx: &CodegenContext<B>,
890 module: CachedModuleCodegen,
891 module_config: &ModuleConfig,
892) -> WorkItemResult<B> {
893 let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
894
895 let mut links_from_incr_cache = Vec::new();
896
897 let mut load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
898 let source_file = in_incr_comp_dir(incr_comp_session_dir, saved_path);
899 debug!(
900 "copying preexisting module `{}` from {:?} to {}",
901 module.name,
902 source_file,
903 output_path.display()
904 );
905 match link_or_copy(&source_file, &output_path) {
906 Ok(_) => {
907 links_from_incr_cache.push(source_file);
908 Some(output_path)
909 }
910 Err(error) => {
911 cgcx.create_dcx().handle().emit_err(errors::CopyPathBuf {
912 source_file,
913 output_path,
914 error,
915 });
916 None
917 }
918 }
919 };
920
921 let dwarf_object =
922 module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
923 let dwarf_obj_out = cgcx
924 .output_filenames
925 .split_dwarf_path(
926 cgcx.split_debuginfo,
927 cgcx.split_dwarf_kind,
928 &module.name,
929 cgcx.invocation_temp.as_deref(),
930 )
931 .expect(
932 "saved dwarf object in work product but `split_dwarf_path` returned `None`",
933 );
934 load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
935 });
936
937 let mut load_from_incr_cache = |perform, output_type: OutputType| {
938 if perform {
939 let saved_file = module.source.saved_files.get(output_type.extension())?;
940 let output_path = cgcx.output_filenames.temp_path_for_cgu(
941 output_type,
942 &module.name,
943 cgcx.invocation_temp.as_deref(),
944 );
945 load_from_incr_comp_dir(output_path, &saved_file)
946 } else {
947 None
948 }
949 };
950
951 let should_emit_obj = module_config.emit_obj != EmitObj::None;
952 let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
953 let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
954 let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
955 let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
956 if should_emit_obj && object.is_none() {
957 cgcx.create_dcx().handle().emit_fatal(errors::NoSavedObjectFile { cgu_name: &module.name })
958 }
959
960 WorkItemResult::Finished(CompiledModule {
961 links_from_incr_cache,
962 name: module.name,
963 kind: ModuleKind::Regular,
964 object,
965 dwarf_object,
966 bytecode,
967 assembly,
968 llvm_ir,
969 })
970}
971
972fn execute_fat_lto_work_item<B: ExtraBackendMethods>(
973 cgcx: &CodegenContext<B>,
974 exported_symbols_for_lto: &[String],
975 each_linked_rlib_for_lto: &[PathBuf],
976 mut needs_fat_lto: Vec<FatLtoInput<B>>,
977 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
978 module_config: &ModuleConfig,
979) -> WorkItemResult<B> {
980 for (module, wp) in import_only_modules {
981 needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, buffer: module })
982 }
983
984 let module = B::run_and_optimize_fat_lto(
985 cgcx,
986 exported_symbols_for_lto,
987 each_linked_rlib_for_lto,
988 needs_fat_lto,
989 );
990 let module = B::codegen(cgcx, module, module_config);
991 WorkItemResult::Finished(module)
992}
993
994fn execute_thin_lto_work_item<B: ExtraBackendMethods>(
995 cgcx: &CodegenContext<B>,
996 module: lto::ThinModule<B>,
997 module_config: &ModuleConfig,
998) -> WorkItemResult<B> {
999 let module = B::optimize_thin(cgcx, module);
1000 let module = B::codegen(cgcx, module, module_config);
1001 WorkItemResult::Finished(module)
1002}
1003
1004pub(crate) enum Message<B: WriteBackendMethods> {
1006 Token(io::Result<Acquired>),
1009
1010 WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>> },
1013
1014 CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
1018
1019 AddImportOnlyModule {
1022 module_data: SerializedModule<B::ModuleBuffer>,
1023 work_product: WorkProduct,
1024 },
1025
1026 CodegenComplete,
1029
1030 CodegenAborted,
1033}
1034
1035pub struct CguMessage;
1038
1039struct Diagnostic {
1049 level: Level,
1050 messages: Vec<(DiagMessage, Style)>,
1051 code: Option<ErrCode>,
1052 children: Vec<Subdiagnostic>,
1053 args: DiagArgMap,
1054}
1055
1056pub(crate) struct Subdiagnostic {
1060 level: Level,
1061 messages: Vec<(DiagMessage, Style)>,
1062}
1063
1064#[derive(PartialEq, Clone, Copy, Debug)]
1065enum MainThreadState {
1066 Idle,
1068
1069 Codegenning,
1071
1072 Lending,
1074}
1075
1076fn start_executing_work<B: ExtraBackendMethods>(
1077 backend: B,
1078 tcx: TyCtxt<'_>,
1079 crate_info: &CrateInfo,
1080 shared_emitter: SharedEmitter,
1081 codegen_worker_send: Sender<CguMessage>,
1082 coordinator_receive: Receiver<Message<B>>,
1083 regular_config: Arc<ModuleConfig>,
1084 allocator_config: Arc<ModuleConfig>,
1085 tx_to_llvm_workers: Sender<Message<B>>,
1086) -> thread::JoinHandle<Result<CompiledModules, ()>> {
1087 let coordinator_send = tx_to_llvm_workers;
1088 let sess = tcx.sess;
1089
1090 let mut each_linked_rlib_for_lto = Vec::new();
1091 let mut each_linked_rlib_file_for_lto = Vec::new();
1092 drop(link::each_linked_rlib(crate_info, None, &mut |cnum, path| {
1093 if link::ignored_for_lto(sess, crate_info, cnum) {
1094 return;
1095 }
1096 each_linked_rlib_for_lto.push(cnum);
1097 each_linked_rlib_file_for_lto.push(path.to_path_buf());
1098 }));
1099
1100 let exported_symbols_for_lto =
1102 Arc::new(lto::exported_symbols_for_lto(tcx, &each_linked_rlib_for_lto));
1103
1104 let coordinator_send2 = coordinator_send.clone();
1110 let helper = jobserver::client()
1111 .into_helper_thread(move |token| {
1112 drop(coordinator_send2.send(Message::Token::<B>(token)));
1113 })
1114 .expect("failed to spawn helper thread");
1115
1116 let ol =
1117 if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
1118 config::OptLevel::No
1120 } else {
1121 tcx.backend_optimization_level(())
1122 };
1123 let backend_features = tcx.global_backend_features(());
1124
1125 let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1126 let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1127 match result {
1128 Ok(dir) => Some(dir),
1129 Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1130 }
1131 } else {
1132 None
1133 };
1134
1135 let cgcx = CodegenContext::<B> {
1136 crate_types: tcx.crate_types().to_vec(),
1137 lto: sess.lto(),
1138 fewer_names: sess.fewer_names(),
1139 save_temps: sess.opts.cg.save_temps,
1140 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1141 opts: Arc::new(sess.opts.clone()),
1142 prof: sess.prof.clone(),
1143 remark: sess.opts.cg.remark.clone(),
1144 remark_dir,
1145 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1146 expanded_args: tcx.sess.expanded_args.clone(),
1147 diag_emitter: shared_emitter.clone(),
1148 output_filenames: Arc::clone(tcx.output_filenames(())),
1149 regular_module_config: regular_config,
1150 allocator_module_config: allocator_config,
1151 tm_factory: backend.target_machine_factory(tcx.sess, ol, backend_features),
1152 msvc_imps_needed: msvc_imps_needed(tcx),
1153 is_pe_coff: tcx.sess.target.is_like_windows,
1154 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1155 target_arch: tcx.sess.target.arch.to_string(),
1156 target_is_like_darwin: tcx.sess.target.is_like_darwin,
1157 target_is_like_aix: tcx.sess.target.is_like_aix,
1158 split_debuginfo: tcx.sess.split_debuginfo(),
1159 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1160 parallel: backend.supports_parallel() && !sess.opts.unstable_opts.no_parallel_backend,
1161 pointer_size: tcx.data_layout.pointer_size(),
1162 invocation_temp: sess.invocation_temp.clone(),
1163 };
1164
1165 return B::spawn_named_thread(cgcx.time_trace, "coordinator".to_string(), move || {
1301 let mut compiled_modules = vec![];
1304 let mut compiled_allocator_module = None;
1305 let mut needs_fat_lto = Vec::new();
1306 let mut needs_thin_lto = Vec::new();
1307 let mut lto_import_only_modules = Vec::new();
1308 let mut started_lto = false;
1309
1310 #[derive(Debug, PartialEq)]
1315 enum CodegenState {
1316 Ongoing,
1317 Completed,
1318 Aborted,
1319 }
1320 use CodegenState::*;
1321 let mut codegen_state = Ongoing;
1322
1323 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1325
1326 let mut tokens = Vec::new();
1329
1330 let mut main_thread_state = MainThreadState::Idle;
1331
1332 let mut running_with_own_token = 0;
1335
1336 let running_with_any_token = |main_thread_state, running_with_own_token| {
1339 running_with_own_token
1340 + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1341 };
1342
1343 let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
1344
1345 loop {
1351 if codegen_state == Ongoing {
1355 if main_thread_state == MainThreadState::Idle {
1356 let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1364 let additional_running = std::cmp::min(extra_tokens, work_items.len());
1365 let anticipated_running = running_with_own_token + additional_running + 1;
1366
1367 if !queue_full_enough(work_items.len(), anticipated_running) {
1368 if codegen_worker_send.send(CguMessage).is_err() {
1370 panic!("Could not send CguMessage to main thread")
1371 }
1372 main_thread_state = MainThreadState::Codegenning;
1373 } else {
1374 let (item, _) =
1378 work_items.pop().expect("queue empty - queue_full_enough() broken?");
1379 main_thread_state = MainThreadState::Lending;
1380 spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1381 }
1382 }
1383 } else if codegen_state == Completed {
1384 if running_with_any_token(main_thread_state, running_with_own_token) == 0
1385 && work_items.is_empty()
1386 {
1387 if needs_fat_lto.is_empty()
1389 && needs_thin_lto.is_empty()
1390 && lto_import_only_modules.is_empty()
1391 {
1392 break;
1394 }
1395
1396 assert!(!started_lto);
1402 started_lto = true;
1403
1404 let needs_fat_lto = mem::take(&mut needs_fat_lto);
1405 let needs_thin_lto = mem::take(&mut needs_thin_lto);
1406 let import_only_modules = mem::take(&mut lto_import_only_modules);
1407 let each_linked_rlib_file_for_lto =
1408 mem::take(&mut each_linked_rlib_file_for_lto);
1409
1410 check_lto_allowed(&cgcx);
1411
1412 if !needs_fat_lto.is_empty() {
1413 assert!(needs_thin_lto.is_empty());
1414
1415 work_items.push((
1416 WorkItem::FatLto {
1417 exported_symbols_for_lto: Arc::clone(&exported_symbols_for_lto),
1418 each_linked_rlib_for_lto: each_linked_rlib_file_for_lto,
1419 needs_fat_lto,
1420 import_only_modules,
1421 },
1422 0,
1423 ));
1424 if cgcx.parallel {
1425 helper.request_token();
1426 }
1427 } else {
1428 for (work, cost) in generate_thin_lto_work(
1429 &cgcx,
1430 &exported_symbols_for_lto,
1431 &each_linked_rlib_file_for_lto,
1432 needs_thin_lto,
1433 import_only_modules,
1434 ) {
1435 let insertion_index = work_items
1436 .binary_search_by_key(&cost, |&(_, cost)| cost)
1437 .unwrap_or_else(|e| e);
1438 work_items.insert(insertion_index, (work, cost));
1439 if cgcx.parallel {
1440 helper.request_token();
1441 }
1442 }
1443 }
1444 }
1445
1446 match main_thread_state {
1450 MainThreadState::Idle => {
1451 if let Some((item, _)) = work_items.pop() {
1452 main_thread_state = MainThreadState::Lending;
1453 spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1454 } else {
1455 assert!(running_with_own_token > 0);
1462 running_with_own_token -= 1;
1463 main_thread_state = MainThreadState::Lending;
1464 }
1465 }
1466 MainThreadState::Codegenning => bug!(
1467 "codegen worker should not be codegenning after \
1468 codegen was already completed"
1469 ),
1470 MainThreadState::Lending => {
1471 }
1473 }
1474 } else {
1475 assert!(codegen_state == Aborted);
1478 if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1479 break;
1480 }
1481 }
1482
1483 if codegen_state != Aborted {
1486 while running_with_own_token < tokens.len()
1487 && let Some((item, _)) = work_items.pop()
1488 {
1489 spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1490 running_with_own_token += 1;
1491 }
1492 }
1493
1494 tokens.truncate(running_with_own_token);
1496
1497 match coordinator_receive.recv().unwrap() {
1498 Message::Token(token) => {
1502 match token {
1503 Ok(token) => {
1504 tokens.push(token);
1505
1506 if main_thread_state == MainThreadState::Lending {
1507 main_thread_state = MainThreadState::Idle;
1512 running_with_own_token += 1;
1513 }
1514 }
1515 Err(e) => {
1516 let msg = &format!("failed to acquire jobserver token: {e}");
1517 shared_emitter.fatal(msg);
1518 codegen_state = Aborted;
1519 }
1520 }
1521 }
1522
1523 Message::CodegenDone { llvm_work_item, cost } => {
1524 let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1533 let insertion_index = match insertion_index {
1534 Ok(idx) | Err(idx) => idx,
1535 };
1536 work_items.insert(insertion_index, (llvm_work_item, cost));
1537
1538 if cgcx.parallel {
1539 helper.request_token();
1540 }
1541 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1542 main_thread_state = MainThreadState::Idle;
1543 }
1544
1545 Message::CodegenComplete => {
1546 if codegen_state != Aborted {
1547 codegen_state = Completed;
1548 }
1549 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1550 main_thread_state = MainThreadState::Idle;
1551 }
1552
1553 Message::CodegenAborted => {
1561 codegen_state = Aborted;
1562 }
1563
1564 Message::WorkItem { result } => {
1565 if main_thread_state == MainThreadState::Lending {
1571 main_thread_state = MainThreadState::Idle;
1572 } else {
1573 running_with_own_token -= 1;
1574 }
1575
1576 match result {
1577 Ok(WorkItemResult::Finished(compiled_module)) => {
1578 match compiled_module.kind {
1579 ModuleKind::Regular => {
1580 compiled_modules.push(compiled_module);
1581 }
1582 ModuleKind::Allocator => {
1583 assert!(compiled_allocator_module.is_none());
1584 compiled_allocator_module = Some(compiled_module);
1585 }
1586 }
1587 }
1588 Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1589 assert!(!started_lto);
1590 assert!(needs_thin_lto.is_empty());
1591 needs_fat_lto.push(fat_lto_input);
1592 }
1593 Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1594 assert!(!started_lto);
1595 assert!(needs_fat_lto.is_empty());
1596 needs_thin_lto.push((name, thin_buffer));
1597 }
1598 Err(Some(WorkerFatalError)) => {
1599 codegen_state = Aborted;
1601 }
1602 Err(None) => {
1603 bug!("worker thread panicked");
1606 }
1607 }
1608 }
1609
1610 Message::AddImportOnlyModule { module_data, work_product } => {
1611 assert!(!started_lto);
1612 assert_eq!(codegen_state, Ongoing);
1613 assert_eq!(main_thread_state, MainThreadState::Codegenning);
1614 lto_import_only_modules.push((module_data, work_product));
1615 main_thread_state = MainThreadState::Idle;
1616 }
1617 }
1618 }
1619
1620 if codegen_state == Aborted {
1621 return Err(());
1622 }
1623
1624 drop(llvm_start_time);
1626
1627 compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1631
1632 Ok(CompiledModules {
1633 modules: compiled_modules,
1634 allocator_module: compiled_allocator_module,
1635 })
1636 })
1637 .expect("failed to spawn coordinator thread");
1638
1639 fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1642 let quarter_of_workers = workers_running - 3 * workers_running / 4;
1693 items_in_queue > 0 && items_in_queue >= quarter_of_workers
1694 }
1695}
1696
1697#[must_use]
1699pub(crate) struct WorkerFatalError;
1700
1701fn spawn_work<'a, B: ExtraBackendMethods>(
1702 cgcx: &'a CodegenContext<B>,
1703 coordinator_send: Sender<Message<B>>,
1704 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1705 work: WorkItem<B>,
1706) {
1707 if llvm_start_time.is_none() {
1708 *llvm_start_time = Some(cgcx.prof.verbose_generic_activity("LLVM_passes"));
1709 }
1710
1711 let cgcx = cgcx.clone();
1712
1713 B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1714 let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
1715 let module_config = cgcx.config(work.module_kind());
1716
1717 match work {
1718 WorkItem::Optimize(m) => {
1719 let _timer =
1720 cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &*m.name);
1721 execute_optimize_work_item(&cgcx, m, module_config)
1722 }
1723 WorkItem::CopyPostLtoArtifacts(m) => {
1724 let _timer = cgcx.prof.generic_activity_with_arg(
1725 "codegen_copy_artifacts_from_incr_cache",
1726 &*m.name,
1727 );
1728 execute_copy_from_cache_work_item(&cgcx, m, module_config)
1729 }
1730 WorkItem::FatLto {
1731 exported_symbols_for_lto,
1732 each_linked_rlib_for_lto,
1733 needs_fat_lto,
1734 import_only_modules,
1735 } => {
1736 let _timer = cgcx
1737 .prof
1738 .generic_activity_with_arg("codegen_module_perform_lto", "everything");
1739 execute_fat_lto_work_item(
1740 &cgcx,
1741 &exported_symbols_for_lto,
1742 &each_linked_rlib_for_lto,
1743 needs_fat_lto,
1744 import_only_modules,
1745 module_config,
1746 )
1747 }
1748 WorkItem::ThinLto(m) => {
1749 let _timer =
1750 cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", m.name());
1751 execute_thin_lto_work_item(&cgcx, m, module_config)
1752 }
1753 }
1754 }));
1755
1756 let msg = match result {
1757 Ok(result) => Message::WorkItem::<B> { result: Ok(result) },
1758
1759 Err(err) if err.is::<FatalErrorMarker>() => {
1763 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1764 }
1765
1766 Err(_) => Message::WorkItem::<B> { result: Err(None) },
1767 };
1768 drop(coordinator_send.send(msg));
1769 })
1770 .expect("failed to spawn work thread");
1771}
1772
1773enum SharedEmitterMessage {
1774 Diagnostic(Diagnostic),
1775 InlineAsmError(SpanData, String, Level, Option<(String, Vec<InnerSpan>)>),
1776 Fatal(String),
1777}
1778
1779#[derive(Clone)]
1780pub struct SharedEmitter {
1781 sender: Sender<SharedEmitterMessage>,
1782}
1783
1784pub struct SharedEmitterMain {
1785 receiver: Receiver<SharedEmitterMessage>,
1786}
1787
1788impl SharedEmitter {
1789 fn new() -> (SharedEmitter, SharedEmitterMain) {
1790 let (sender, receiver) = channel();
1791
1792 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1793 }
1794
1795 pub fn inline_asm_error(
1796 &self,
1797 span: SpanData,
1798 msg: String,
1799 level: Level,
1800 source: Option<(String, Vec<InnerSpan>)>,
1801 ) {
1802 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(span, msg, level, source)));
1803 }
1804
1805 fn fatal(&self, msg: &str) {
1806 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1807 }
1808}
1809
1810impl Emitter for SharedEmitter {
1811 fn emit_diagnostic(
1812 &mut self,
1813 mut diag: rustc_errors::DiagInner,
1814 _registry: &rustc_errors::registry::Registry,
1815 ) {
1816 assert_eq!(diag.span, MultiSpan::new());
1819 assert_eq!(diag.suggestions, Suggestions::Enabled(vec![]));
1820 assert_eq!(diag.sort_span, rustc_span::DUMMY_SP);
1821 assert_eq!(diag.is_lint, None);
1822 let args = mem::replace(&mut diag.args, DiagArgMap::default());
1825 drop(
1826 self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1827 level: diag.level(),
1828 messages: diag.messages,
1829 code: diag.code,
1830 children: diag
1831 .children
1832 .into_iter()
1833 .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
1834 .collect(),
1835 args,
1836 })),
1837 );
1838 }
1839
1840 fn source_map(&self) -> Option<&SourceMap> {
1841 None
1842 }
1843
1844 fn translator(&self) -> &Translator {
1845 panic!("shared emitter attempted to translate a diagnostic");
1846 }
1847}
1848
1849impl SharedEmitterMain {
1850 fn check(&self, sess: &Session, blocking: bool) {
1851 loop {
1852 let message = if blocking {
1853 match self.receiver.recv() {
1854 Ok(message) => Ok(message),
1855 Err(_) => Err(()),
1856 }
1857 } else {
1858 match self.receiver.try_recv() {
1859 Ok(message) => Ok(message),
1860 Err(_) => Err(()),
1861 }
1862 };
1863
1864 match message {
1865 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1866 let dcx = sess.dcx();
1869 let mut d =
1870 rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
1871 d.code = diag.code; d.children = diag
1873 .children
1874 .into_iter()
1875 .map(|sub| rustc_errors::Subdiag {
1876 level: sub.level,
1877 messages: sub.messages,
1878 span: MultiSpan::new(),
1879 })
1880 .collect();
1881 d.args = diag.args;
1882 dcx.emit_diagnostic(d);
1883 sess.dcx().abort_if_errors();
1884 }
1885 Ok(SharedEmitterMessage::InlineAsmError(span, msg, level, source)) => {
1886 assert_matches!(level, Level::Error | Level::Warning | Level::Note);
1887 let mut err = Diag::<()>::new(sess.dcx(), level, msg);
1888 if !span.is_dummy() {
1889 err.span(span.span());
1890 }
1891
1892 if let Some((buffer, spans)) = source {
1894 let source = sess
1895 .source_map()
1896 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
1897 let spans: Vec<_> = spans
1898 .iter()
1899 .map(|sp| {
1900 Span::with_root_ctxt(
1901 source.normalized_byte_pos(sp.start as u32),
1902 source.normalized_byte_pos(sp.end as u32),
1903 )
1904 })
1905 .collect();
1906 err.span_note(spans, "instantiated into assembly here");
1907 }
1908
1909 err.emit();
1910 }
1911 Ok(SharedEmitterMessage::Fatal(msg)) => {
1912 sess.dcx().fatal(msg);
1913 }
1914 Err(_) => {
1915 break;
1916 }
1917 }
1918 }
1919 }
1920}
1921
1922pub struct Coordinator<B: ExtraBackendMethods> {
1923 sender: Sender<Message<B>>,
1924 future: Option<thread::JoinHandle<Result<CompiledModules, ()>>>,
1925 phantom: PhantomData<B>,
1927}
1928
1929impl<B: ExtraBackendMethods> Coordinator<B> {
1930 fn join(mut self) -> std::thread::Result<Result<CompiledModules, ()>> {
1931 self.future.take().unwrap().join()
1932 }
1933}
1934
1935impl<B: ExtraBackendMethods> Drop for Coordinator<B> {
1936 fn drop(&mut self) {
1937 if let Some(future) = self.future.take() {
1938 drop(self.sender.send(Message::CodegenAborted::<B>));
1941 drop(future.join());
1942 }
1943 }
1944}
1945
1946pub struct OngoingCodegen<B: ExtraBackendMethods> {
1947 pub backend: B,
1948 pub crate_info: CrateInfo,
1949 pub output_filenames: Arc<OutputFilenames>,
1950 pub coordinator: Coordinator<B>,
1954 pub codegen_worker_receive: Receiver<CguMessage>,
1955 pub shared_emitter_main: SharedEmitterMain,
1956}
1957
1958impl<B: ExtraBackendMethods> OngoingCodegen<B> {
1959 pub fn join(self, sess: &Session) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
1960 self.shared_emitter_main.check(sess, true);
1961 let compiled_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
1962 Ok(Ok(compiled_modules)) => compiled_modules,
1963 Ok(Err(())) => {
1964 sess.dcx().abort_if_errors();
1965 panic!("expected abort due to worker thread errors")
1966 }
1967 Err(_) => {
1968 bug!("panic during codegen/LLVM phase");
1969 }
1970 });
1971
1972 sess.dcx().abort_if_errors();
1973
1974 let work_products =
1975 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
1976 produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
1977
1978 if sess.codegen_units().as_usize() == 1 && sess.opts.unstable_opts.time_llvm_passes {
1981 self.backend.print_pass_timings()
1982 }
1983
1984 if sess.print_llvm_stats() {
1985 self.backend.print_statistics()
1986 }
1987
1988 (
1989 CodegenResults {
1990 crate_info: self.crate_info,
1991
1992 modules: compiled_modules.modules,
1993 allocator_module: compiled_modules.allocator_module,
1994 },
1995 work_products,
1996 )
1997 }
1998
1999 pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2000 self.wait_for_signal_to_codegen_item();
2001 self.check_for_errors(tcx.sess);
2002 drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
2003 }
2004
2005 pub(crate) fn check_for_errors(&self, sess: &Session) {
2006 self.shared_emitter_main.check(sess, false);
2007 }
2008
2009 pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2010 match self.codegen_worker_receive.recv() {
2011 Ok(CguMessage) => {
2012 }
2014 Err(_) => {
2015 }
2018 }
2019 }
2020}
2021
2022pub(crate) fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
2023 coordinator: &Coordinator<B>,
2024 module: ModuleCodegen<B::Module>,
2025 cost: u64,
2026) {
2027 let llvm_work_item = WorkItem::Optimize(module);
2028 drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2029}
2030
2031pub(crate) fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
2032 coordinator: &Coordinator<B>,
2033 module: CachedModuleCodegen,
2034) {
2035 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2036 drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2037}
2038
2039pub(crate) fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
2040 tcx: TyCtxt<'_>,
2041 coordinator: &Coordinator<B>,
2042 module: CachedModuleCodegen,
2043) {
2044 let filename = pre_lto_bitcode_filename(&module.name);
2045 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2046 let file = fs::File::open(&bc_path)
2047 .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
2048
2049 let mmap = unsafe {
2050 Mmap::map(file).unwrap_or_else(|e| {
2051 panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2052 })
2053 };
2054 drop(coordinator.sender.send(Message::AddImportOnlyModule::<B> {
2056 module_data: SerializedModule::FromUncompressedFile(mmap),
2057 work_product: module.source,
2058 }));
2059}
2060
2061fn pre_lto_bitcode_filename(module_name: &str) -> String {
2062 format!("{module_name}.{PRE_LTO_BC_EXT}")
2063}
2064
2065fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2066 assert!(
2069 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2070 && tcx.sess.target.is_like_windows
2071 && tcx.sess.opts.cg.prefer_dynamic)
2072 );
2073
2074 let can_have_static_objects =
2078 tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
2079
2080 tcx.sess.target.is_like_windows &&
2081 can_have_static_objects &&
2082 !tcx.sess.opts.cg.linker_plugin_lto.enabled()
2086}