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