1use std::marker::PhantomData;
2use std::panic::AssertUnwindSafe;
3use std::path::{Path, PathBuf};
4use std::sync::Arc;
5use std::sync::mpsc::{Receiver, Sender, channel};
6use std::{fs, io, mem, str, thread};
7
8use rustc_abi::Size;
9use rustc_ast::attr;
10use rustc_data_structures::assert_matches;
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, DiagCtxtHandle, DiagMessage, ErrCode, FatalError, FatalErrorMarker,
19 Level, MultiSpan, Style, Suggestions, catch_fatal_errors,
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(#[automatically_derived]
impl ::core::clone::Clone for EmitObj {
#[inline]
fn clone(&self) -> EmitObj {
let _: ::core::clone::AssertParamIsClone<BitcodeSection>;
*self
}
}Clone, #[automatically_derived]
impl ::core::marker::Copy for EmitObj { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for EmitObj {
#[inline]
fn eq(&self, other: &EmitObj) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr &&
match (self, other) {
(EmitObj::ObjectCode(__self_0), EmitObj::ObjectCode(__arg1_0))
=> __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq)]
52pub enum EmitObj {
53 None,
55
56 Bitcode,
59
60 ObjectCode(BitcodeSection),
62}
63
64#[derive(#[automatically_derived]
impl ::core::clone::Clone for BitcodeSection {
#[inline]
fn clone(&self) -> BitcodeSection { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for BitcodeSection { }Copy, #[automatically_derived]
impl ::core::cmp::PartialEq for BitcodeSection {
#[inline]
fn eq(&self, other: &BitcodeSection) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}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 let ModuleKind::Regular = kind { Some(sess.opts.optimize) } else { None }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 let ModuleKind::Regular = kind {
sess.opts.cg.passes.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.cg.passes.clone(), vec![]),
167
168 opt_level: opt_level_and_size,
169
170 pgo_gen: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_generate.clone()
} else { SwitchWithOptPath::Disabled }if_regular!(
171 sess.opts.cg.profile_generate.clone(),
172 SwitchWithOptPath::Disabled
173 ),
174 pgo_use: if let ModuleKind::Regular = kind {
sess.opts.cg.profile_use.clone()
} else { None }if_regular!(sess.opts.cg.profile_use.clone(), None),
175 pgo_sample_use: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.profile_sample_use.clone()
} else { None }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 let ModuleKind::Regular = kind {
sess.instrument_coverage()
} else { false }if_regular!(sess.instrument_coverage(), false),
178
179 sanitizer: if let ModuleKind::Regular = kind {
sess.sanitizers()
} else { SanitizerSet::empty() }if_regular!(sess.sanitizers(), SanitizerSet::empty()),
180 sanitizer_dataflow_abilist: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone()
} else { Vec::new() }if_regular!(
181 sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
182 Vec::new()
183 ),
184 sanitizer_recover: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_recover
} else { SanitizerSet::empty() }if_regular!(
185 sess.opts.unstable_opts.sanitizer_recover,
186 SanitizerSet::empty()
187 ),
188 sanitizer_memory_track_origins: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.sanitizer_memory_track_origins
} else { 0 }if_regular!(
189 sess.opts.unstable_opts.sanitizer_memory_track_origins,
190 0
191 ),
192
193 emit_pre_lto_bc: if let ModuleKind::Regular = kind {
save_temps || need_pre_lto_bitcode_for_incr_comp(sess)
} else { false }if_regular!(
194 save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
195 false
196 ),
197 emit_no_opt_bc: if let ModuleKind::Regular = kind { save_temps } else { false }if_regular!(save_temps, false),
198 emit_bc: if let ModuleKind::Regular = kind {
save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode)
} else { save_temps }if_regular!(
199 save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
200 save_temps
201 ),
202 emit_ir: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::LlvmAssembly)
} else { false }if_regular!(
203 sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
204 false
205 ),
206 emit_asm: if let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::Assembly)
} else { false }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 let ModuleKind::Regular = kind {
sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode)
} else { false }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 let ModuleKind::Regular = kind {
sess.opts.unstable_opts.llvm_plugins.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.unstable_opts.llvm_plugins.clone(), vec![]),
259 autodiff: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.autodiff.clone()
} else { ::alloc::vec::Vec::new() }if_regular!(sess.opts.unstable_opts.autodiff.clone(), vec![]),
260 offload: if let ModuleKind::Regular = kind {
sess.opts.unstable_opts.offload.clone()
} else { ::alloc::vec::Vec::new() }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(#[automatically_derived]
impl<B: ::core::clone::Clone + WriteBackendMethods> ::core::clone::Clone for
CodegenContext<B> {
#[inline]
fn clone(&self) -> CodegenContext<B> {
CodegenContext {
prof: ::core::clone::Clone::clone(&self.prof),
lto: ::core::clone::Clone::clone(&self.lto),
use_linker_plugin_lto: ::core::clone::Clone::clone(&self.use_linker_plugin_lto),
dylib_lto: ::core::clone::Clone::clone(&self.dylib_lto),
prefer_dynamic: ::core::clone::Clone::clone(&self.prefer_dynamic),
save_temps: ::core::clone::Clone::clone(&self.save_temps),
fewer_names: ::core::clone::Clone::clone(&self.fewer_names),
time_trace: ::core::clone::Clone::clone(&self.time_trace),
crate_types: ::core::clone::Clone::clone(&self.crate_types),
output_filenames: ::core::clone::Clone::clone(&self.output_filenames),
invocation_temp: ::core::clone::Clone::clone(&self.invocation_temp),
module_config: ::core::clone::Clone::clone(&self.module_config),
tm_factory: ::core::clone::Clone::clone(&self.tm_factory),
msvc_imps_needed: ::core::clone::Clone::clone(&self.msvc_imps_needed),
is_pe_coff: ::core::clone::Clone::clone(&self.is_pe_coff),
target_can_use_split_dwarf: ::core::clone::Clone::clone(&self.target_can_use_split_dwarf),
target_arch: ::core::clone::Clone::clone(&self.target_arch),
target_is_like_darwin: ::core::clone::Clone::clone(&self.target_is_like_darwin),
target_is_like_aix: ::core::clone::Clone::clone(&self.target_is_like_aix),
target_is_like_gpu: ::core::clone::Clone::clone(&self.target_is_like_gpu),
split_debuginfo: ::core::clone::Clone::clone(&self.split_debuginfo),
split_dwarf_kind: ::core::clone::Clone::clone(&self.split_dwarf_kind),
pointer_size: ::core::clone::Clone::clone(&self.pointer_size),
remark: ::core::clone::Clone::clone(&self.remark),
remark_dir: ::core::clone::Clone::clone(&self.remark_dir),
incr_comp_session_dir: ::core::clone::Clone::clone(&self.incr_comp_session_dir),
parallel: ::core::clone::Clone::clone(&self.parallel),
}
}
}Clone)]
325pub struct CodegenContext<B: WriteBackendMethods> {
326 pub prof: SelfProfilerRef,
328 pub lto: Lto,
329 pub use_linker_plugin_lto: bool,
330 pub dylib_lto: bool,
331 pub prefer_dynamic: bool,
332 pub save_temps: bool,
333 pub fewer_names: bool,
334 pub time_trace: bool,
335 pub crate_types: Vec<CrateType>,
336 pub output_filenames: Arc<OutputFilenames>,
337 pub invocation_temp: Option<String>,
338 pub module_config: Arc<ModuleConfig>,
339 pub tm_factory: TargetMachineFactoryFn<B>,
340 pub msvc_imps_needed: bool,
341 pub is_pe_coff: bool,
342 pub target_can_use_split_dwarf: bool,
343 pub target_arch: String,
344 pub target_is_like_darwin: bool,
345 pub target_is_like_aix: bool,
346 pub target_is_like_gpu: bool,
347 pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
348 pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
349 pub pointer_size: Size,
350
351 pub remark: Passes,
353 pub remark_dir: Option<PathBuf>,
356 pub incr_comp_session_dir: Option<PathBuf>,
359 pub parallel: bool,
363}
364
365fn generate_thin_lto_work<B: ExtraBackendMethods>(
366 cgcx: &CodegenContext<B>,
367 dcx: DiagCtxtHandle<'_>,
368 exported_symbols_for_lto: &[String],
369 each_linked_rlib_for_lto: &[PathBuf],
370 needs_thin_lto: Vec<(String, B::ThinBuffer)>,
371 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
372) -> Vec<(ThinLtoWorkItem<B>, u64)> {
373 let _prof_timer = cgcx.prof.generic_activity("codegen_thin_generate_lto_work");
374
375 let (lto_modules, copy_jobs) = B::run_thin_lto(
376 cgcx,
377 dcx,
378 exported_symbols_for_lto,
379 each_linked_rlib_for_lto,
380 needs_thin_lto,
381 import_only_modules,
382 );
383 lto_modules
384 .into_iter()
385 .map(|module| {
386 let cost = module.cost();
387 (ThinLtoWorkItem::ThinLto(module), cost)
388 })
389 .chain(copy_jobs.into_iter().map(|wp| {
390 (
391 ThinLtoWorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
392 name: wp.cgu_name.clone(),
393 source: wp,
394 }),
395 0, )
397 }))
398 .collect()
399}
400
401struct CompiledModules {
402 modules: Vec<CompiledModule>,
403 allocator_module: Option<CompiledModule>,
404}
405
406enum MaybeLtoModules<B: WriteBackendMethods> {
407 NoLto {
408 modules: Vec<CompiledModule>,
409 allocator_module: Option<CompiledModule>,
410 },
411 FatLto {
412 cgcx: CodegenContext<B>,
413 exported_symbols_for_lto: Arc<Vec<String>>,
414 each_linked_rlib_file_for_lto: Vec<PathBuf>,
415 needs_fat_lto: Vec<FatLtoInput<B>>,
416 lto_import_only_modules:
417 Vec<(SerializedModule<<B as WriteBackendMethods>::ModuleBuffer>, WorkProduct)>,
418 },
419 ThinLto {
420 cgcx: CodegenContext<B>,
421 exported_symbols_for_lto: Arc<Vec<String>>,
422 each_linked_rlib_file_for_lto: Vec<PathBuf>,
423 needs_thin_lto: Vec<(String, <B as WriteBackendMethods>::ThinBuffer)>,
424 lto_import_only_modules:
425 Vec<(SerializedModule<<B as WriteBackendMethods>::ModuleBuffer>, WorkProduct)>,
426 },
427}
428
429fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
430 let sess = tcx.sess;
431 sess.opts.cg.embed_bitcode
432 && tcx.crate_types().contains(&CrateType::Rlib)
433 && sess.opts.output_types.contains_key(&OutputType::Exe)
434}
435
436fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
437 if sess.opts.incremental.is_none() {
438 return false;
439 }
440
441 match sess.lto() {
442 Lto::No => false,
443 Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
444 }
445}
446
447pub(crate) fn start_async_codegen<B: ExtraBackendMethods>(
448 backend: B,
449 tcx: TyCtxt<'_>,
450 target_cpu: String,
451 allocator_module: Option<ModuleCodegen<B::Module>>,
452) -> OngoingCodegen<B> {
453 let (coordinator_send, coordinator_receive) = channel();
454
455 let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
456 let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins);
457
458 let crate_info = CrateInfo::new(tcx, target_cpu);
459
460 let regular_config = ModuleConfig::new(ModuleKind::Regular, tcx, no_builtins);
461 let allocator_config = ModuleConfig::new(ModuleKind::Allocator, tcx, no_builtins);
462
463 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
464 let (codegen_worker_send, codegen_worker_receive) = channel();
465
466 let coordinator_thread = start_executing_work(
467 backend.clone(),
468 tcx,
469 &crate_info,
470 shared_emitter,
471 codegen_worker_send,
472 coordinator_receive,
473 Arc::new(regular_config),
474 Arc::new(allocator_config),
475 allocator_module,
476 coordinator_send.clone(),
477 );
478
479 OngoingCodegen {
480 backend,
481 crate_info,
482
483 codegen_worker_receive,
484 shared_emitter_main,
485 coordinator: Coordinator {
486 sender: coordinator_send,
487 future: Some(coordinator_thread),
488 phantom: PhantomData,
489 },
490 output_filenames: Arc::clone(tcx.output_filenames(())),
491 }
492}
493
494fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
495 sess: &Session,
496 compiled_modules: &CompiledModules,
497) -> FxIndexMap<WorkProductId, WorkProduct> {
498 let mut work_products = FxIndexMap::default();
499
500 if sess.opts.incremental.is_none() {
501 return work_products;
502 }
503
504 let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
505
506 for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
507 let mut files = Vec::new();
508 if let Some(object_file_path) = &module.object {
509 files.push((OutputType::Object.extension(), object_file_path.as_path()));
510 }
511 if let Some(dwarf_object_file_path) = &module.dwarf_object {
512 files.push(("dwo", dwarf_object_file_path.as_path()));
513 }
514 if let Some(path) = &module.assembly {
515 files.push((OutputType::Assembly.extension(), path.as_path()));
516 }
517 if let Some(path) = &module.llvm_ir {
518 files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
519 }
520 if let Some(path) = &module.bytecode {
521 files.push((OutputType::Bitcode.extension(), path.as_path()));
522 }
523 if let Some((id, product)) = copy_cgu_workproduct_to_incr_comp_cache_dir(
524 sess,
525 &module.name,
526 files.as_slice(),
527 &module.links_from_incr_cache,
528 ) {
529 work_products.insert(id, product);
530 }
531 }
532
533 work_products
534}
535
536fn produce_final_output_artifacts(
537 sess: &Session,
538 compiled_modules: &CompiledModules,
539 crate_output: &OutputFilenames,
540) {
541 let mut user_wants_bitcode = false;
542 let mut user_wants_objects = false;
543
544 let copy_gracefully = |from: &Path, to: &OutFileName| match to {
546 OutFileName::Stdout if let Err(e) = copy_to_stdout(from) => {
547 sess.dcx().emit_err(errors::CopyPath::new(from, to.as_path(), e));
548 }
549 OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
550 sess.dcx().emit_err(errors::CopyPath::new(from, path, e));
551 }
552 _ => {}
553 };
554
555 let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
556 if let [module] = &compiled_modules.modules[..] {
557 let path = crate_output.temp_path_for_cgu(
560 output_type,
561 &module.name,
562 sess.invocation_temp.as_deref(),
563 );
564 let output = crate_output.path(output_type);
565 if !output_type.is_text_output() && output.is_tty() {
566 sess.dcx()
567 .emit_err(errors::BinaryOutputToTty { shorthand: output_type.shorthand() });
568 } else {
569 copy_gracefully(&path, &output);
570 }
571 if !sess.opts.cg.save_temps && !keep_numbered {
572 ensure_removed(sess.dcx(), &path);
574 }
575 } else {
576 if crate_output.outputs.contains_explicit_name(&output_type) {
577 sess.dcx()
580 .emit_warn(errors::IgnoringEmitPath { extension: output_type.extension() });
581 } else if crate_output.single_output_file.is_some() {
582 sess.dcx().emit_warn(errors::IgnoringOutput { extension: output_type.extension() });
585 } else {
586 }
590 }
591 };
592
593 for output_type in crate_output.outputs.keys() {
597 match *output_type {
598 OutputType::Bitcode => {
599 user_wants_bitcode = true;
600 copy_if_one_unit(OutputType::Bitcode, true);
604 }
605 OutputType::ThinLinkBitcode => {
606 copy_if_one_unit(OutputType::ThinLinkBitcode, false);
607 }
608 OutputType::LlvmAssembly => {
609 copy_if_one_unit(OutputType::LlvmAssembly, false);
610 }
611 OutputType::Assembly => {
612 copy_if_one_unit(OutputType::Assembly, false);
613 }
614 OutputType::Object => {
615 user_wants_objects = true;
616 copy_if_one_unit(OutputType::Object, true);
617 }
618 OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
619 }
620 }
621
622 if !sess.opts.cg.save_temps {
635 let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
651
652 let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
653
654 let keep_numbered_objects =
655 needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
656
657 for module in compiled_modules.modules.iter() {
658 if !keep_numbered_objects {
659 if let Some(ref path) = module.object {
660 ensure_removed(sess.dcx(), path);
661 }
662
663 if let Some(ref path) = module.dwarf_object {
664 ensure_removed(sess.dcx(), path);
665 }
666 }
667
668 if let Some(ref path) = module.bytecode {
669 if !keep_numbered_bitcode {
670 ensure_removed(sess.dcx(), path);
671 }
672 }
673 }
674
675 if !user_wants_bitcode
676 && let Some(ref allocator_module) = compiled_modules.allocator_module
677 && let Some(ref path) = allocator_module.bytecode
678 {
679 ensure_removed(sess.dcx(), path);
680 }
681 }
682
683 if sess.opts.json_artifact_notifications {
684 if let [module] = &compiled_modules.modules[..] {
685 module.for_each_output(|_path, ty| {
686 if sess.opts.output_types.contains_key(&ty) {
687 let descr = ty.shorthand();
688 let path = crate_output.path(ty);
691 sess.dcx().emit_artifact_notification(path.as_path(), descr);
692 }
693 });
694 } else {
695 for module in &compiled_modules.modules {
696 module.for_each_output(|path, ty| {
697 if sess.opts.output_types.contains_key(&ty) {
698 let descr = ty.shorthand();
699 sess.dcx().emit_artifact_notification(&path, descr);
700 }
701 });
702 }
703 }
704 }
705
706 }
712
713pub(crate) enum WorkItem<B: WriteBackendMethods> {
714 Optimize(ModuleCodegen<B::Module>),
716 CopyPostLtoArtifacts(CachedModuleCodegen),
719}
720
721enum ThinLtoWorkItem<B: WriteBackendMethods> {
722 CopyPostLtoArtifacts(CachedModuleCodegen),
725 ThinLto(lto::ThinModule<B>),
727}
728
729#[cfg(not(windows))]
733fn desc(short: &str, _long: &str, name: &str) -> String {
734 match (&short.len(), &3) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(short.len(), 3);
754 let name = if let Some(index) = name.find("-cgu.") {
755 &name[index + 1..] } else {
757 name
758 };
759 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0} {1}", short, name))
})format!("{short} {name}")
760}
761
762#[cfg(windows)]
764fn desc(_short: &str, long: &str, name: &str) -> String {
765 format!("{long} {name}")
766}
767
768impl<B: WriteBackendMethods> WorkItem<B> {
769 fn short_description(&self) -> String {
771 match self {
772 WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
773 WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
774 }
775 }
776}
777
778impl<B: WriteBackendMethods> ThinLtoWorkItem<B> {
779 fn short_description(&self) -> String {
781 match self {
782 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
783 desc("cpy", "copy LTO artifacts for", &m.name)
784 }
785 ThinLtoWorkItem::ThinLto(m) => desc("lto", "thin-LTO module", m.name()),
786 }
787 }
788}
789
790pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
792 Finished(CompiledModule),
794
795 NeedsFatLto(FatLtoInput<B>),
798
799 NeedsThinLto(String, B::ThinBuffer),
802}
803
804pub enum FatLtoInput<B: WriteBackendMethods> {
805 Serialized { name: String, buffer: SerializedModule<B::ModuleBuffer> },
806 InMemory(ModuleCodegen<B::Module>),
807}
808
809pub(crate) enum ComputedLtoType {
811 No,
812 Thin,
813 Fat,
814}
815
816pub(crate) fn compute_per_cgu_lto_type(
817 sess_lto: &Lto,
818 linker_does_lto: bool,
819 sess_crate_types: &[CrateType],
820) -> ComputedLtoType {
821 let is_rlib = #[allow(non_exhaustive_omitted_patterns)] match sess_crate_types {
[CrateType::Rlib] => true,
_ => false,
}matches!(sess_crate_types, [CrateType::Rlib]);
834
835 match sess_lto {
836 Lto::ThinLocal if !linker_does_lto => ComputedLtoType::Thin,
837 Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
838 Lto::Fat if !is_rlib => ComputedLtoType::Fat,
839 _ => ComputedLtoType::No,
840 }
841}
842
843fn execute_optimize_work_item<B: ExtraBackendMethods>(
844 cgcx: &CodegenContext<B>,
845 shared_emitter: SharedEmitter,
846 mut module: ModuleCodegen<B::Module>,
847) -> WorkItemResult<B> {
848 let _timer = cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &*module.name);
849
850 B::optimize(cgcx, &shared_emitter, &mut module, &cgcx.module_config);
851
852 let lto_type =
858 compute_per_cgu_lto_type(&cgcx.lto, cgcx.use_linker_plugin_lto, &cgcx.crate_types);
859
860 let bitcode = if cgcx.module_config.emit_pre_lto_bc {
863 let filename = pre_lto_bitcode_filename(&module.name);
864 cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
865 } else {
866 None
867 };
868
869 match lto_type {
870 ComputedLtoType::No => {
871 let module = B::codegen(cgcx, &shared_emitter, module, &cgcx.module_config);
872 WorkItemResult::Finished(module)
873 }
874 ComputedLtoType::Thin => {
875 let (name, thin_buffer) = B::prepare_thin(module);
876 if let Some(path) = bitcode {
877 fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
878 {
::core::panicking::panic_fmt(format_args!("Error writing pre-lto-bitcode file `{0}`: {1}",
path.display(), e));
};panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
879 });
880 }
881 WorkItemResult::NeedsThinLto(name, thin_buffer)
882 }
883 ComputedLtoType::Fat => match bitcode {
884 Some(path) => {
885 let (name, buffer) = B::serialize_module(module);
886 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
887 {
::core::panicking::panic_fmt(format_args!("Error writing pre-lto-bitcode file `{0}`: {1}",
path.display(), e));
};panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
888 });
889 WorkItemResult::NeedsFatLto(FatLtoInput::Serialized {
890 name,
891 buffer: SerializedModule::Local(buffer),
892 })
893 }
894 None => WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module)),
895 },
896 }
897}
898
899fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
900 cgcx: &CodegenContext<B>,
901 shared_emitter: SharedEmitter,
902 module: CachedModuleCodegen,
903) -> CompiledModule {
904 let _timer = cgcx
905 .prof
906 .generic_activity_with_arg("codegen_copy_artifacts_from_incr_cache", &*module.name);
907
908 let dcx = DiagCtxt::new(Box::new(shared_emitter));
909 let dcx = dcx.handle();
910
911 let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
912
913 let mut links_from_incr_cache = Vec::new();
914
915 let mut load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
916 let source_file = in_incr_comp_dir(incr_comp_session_dir, saved_path);
917 {
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/write.rs:917",
"rustc_codegen_ssa::back::write", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/write.rs"),
::tracing_core::__macro_support::Option::Some(917u32),
::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::write"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("copying preexisting module `{0}` from {1:?} to {2}",
module.name, source_file, output_path.display()) as
&dyn Value))])
});
} else { ; }
};debug!(
918 "copying preexisting module `{}` from {:?} to {}",
919 module.name,
920 source_file,
921 output_path.display()
922 );
923 match link_or_copy(&source_file, &output_path) {
924 Ok(_) => {
925 links_from_incr_cache.push(source_file);
926 Some(output_path)
927 }
928 Err(error) => {
929 dcx.emit_err(errors::CopyPathBuf { source_file, output_path, error });
930 None
931 }
932 }
933 };
934
935 let dwarf_object =
936 module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
937 let dwarf_obj_out = cgcx
938 .output_filenames
939 .split_dwarf_path(
940 cgcx.split_debuginfo,
941 cgcx.split_dwarf_kind,
942 &module.name,
943 cgcx.invocation_temp.as_deref(),
944 )
945 .expect(
946 "saved dwarf object in work product but `split_dwarf_path` returned `None`",
947 );
948 load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
949 });
950
951 let mut load_from_incr_cache = |perform, output_type: OutputType| {
952 if perform {
953 let saved_file = module.source.saved_files.get(output_type.extension())?;
954 let output_path = cgcx.output_filenames.temp_path_for_cgu(
955 output_type,
956 &module.name,
957 cgcx.invocation_temp.as_deref(),
958 );
959 load_from_incr_comp_dir(output_path, &saved_file)
960 } else {
961 None
962 }
963 };
964
965 let module_config = &cgcx.module_config;
966 let should_emit_obj = module_config.emit_obj != EmitObj::None;
967 let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
968 let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
969 let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
970 let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
971 if should_emit_obj && object.is_none() {
972 dcx.emit_fatal(errors::NoSavedObjectFile { cgu_name: &module.name })
973 }
974
975 CompiledModule {
976 links_from_incr_cache,
977 kind: ModuleKind::Regular,
978 name: module.name,
979 object,
980 dwarf_object,
981 bytecode,
982 assembly,
983 llvm_ir,
984 }
985}
986
987fn do_fat_lto<B: ExtraBackendMethods>(
988 cgcx: &CodegenContext<B>,
989 shared_emitter: SharedEmitter,
990 exported_symbols_for_lto: &[String],
991 each_linked_rlib_for_lto: &[PathBuf],
992 mut needs_fat_lto: Vec<FatLtoInput<B>>,
993 import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
994) -> CompiledModule {
995 let _timer = cgcx.prof.verbose_generic_activity("LLVM_fatlto");
996
997 let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
998 let dcx = dcx.handle();
999
1000 check_lto_allowed(&cgcx, dcx);
1001
1002 for (module, wp) in import_only_modules {
1003 needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, buffer: module })
1004 }
1005
1006 let module = B::run_and_optimize_fat_lto(
1007 cgcx,
1008 &shared_emitter,
1009 exported_symbols_for_lto,
1010 each_linked_rlib_for_lto,
1011 needs_fat_lto,
1012 );
1013 B::codegen(cgcx, &shared_emitter, module, &cgcx.module_config)
1014}
1015
1016fn do_thin_lto<'a, B: ExtraBackendMethods>(
1017 cgcx: &'a CodegenContext<B>,
1018 shared_emitter: SharedEmitter,
1019 exported_symbols_for_lto: Arc<Vec<String>>,
1020 each_linked_rlib_for_lto: Vec<PathBuf>,
1021 needs_thin_lto: Vec<(String, <B as WriteBackendMethods>::ThinBuffer)>,
1022 lto_import_only_modules: Vec<(
1023 SerializedModule<<B as WriteBackendMethods>::ModuleBuffer>,
1024 WorkProduct,
1025 )>,
1026) -> Vec<CompiledModule> {
1027 let _timer = cgcx.prof.verbose_generic_activity("LLVM_thinlto");
1028
1029 let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
1030 let dcx = dcx.handle();
1031
1032 check_lto_allowed(&cgcx, dcx);
1033
1034 let (coordinator_send, coordinator_receive) = channel();
1035
1036 let coordinator_send2 = coordinator_send.clone();
1042 let helper = jobserver::client()
1043 .into_helper_thread(move |token| {
1044 drop(coordinator_send2.send(ThinLtoMessage::Token(token)));
1045 })
1046 .expect("failed to spawn helper thread");
1047
1048 let mut work_items = ::alloc::vec::Vec::new()vec![];
1049
1050 for (work, cost) in generate_thin_lto_work(
1056 cgcx,
1057 dcx,
1058 &exported_symbols_for_lto,
1059 &each_linked_rlib_for_lto,
1060 needs_thin_lto,
1061 lto_import_only_modules,
1062 ) {
1063 let insertion_index =
1064 work_items.binary_search_by_key(&cost, |&(_, cost)| cost).unwrap_or_else(|e| e);
1065 work_items.insert(insertion_index, (work, cost));
1066 if cgcx.parallel {
1067 helper.request_token();
1068 }
1069 }
1070
1071 let mut codegen_aborted = None;
1072
1073 let mut tokens = ::alloc::vec::Vec::new()vec![];
1076
1077 let mut used_token_count = 0;
1079
1080 let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
1081
1082 loop {
1088 if codegen_aborted.is_none() {
1089 if used_token_count == 0 && work_items.is_empty() {
1090 break;
1092 }
1093
1094 while used_token_count < tokens.len() + 1
1097 && let Some((item, _)) = work_items.pop()
1098 {
1099 spawn_thin_lto_work(&cgcx, shared_emitter.clone(), coordinator_send.clone(), item);
1100 used_token_count += 1;
1101 }
1102 } else {
1103 if used_token_count == 0 {
1106 break;
1107 }
1108 }
1109
1110 tokens.truncate(used_token_count.saturating_sub(1));
1112
1113 match coordinator_receive.recv().unwrap() {
1114 ThinLtoMessage::Token(token) => match token {
1118 Ok(token) => {
1119 tokens.push(token);
1120 }
1121 Err(e) => {
1122 let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1123 shared_emitter.fatal(msg);
1124 codegen_aborted = Some(FatalError);
1125 }
1126 },
1127
1128 ThinLtoMessage::WorkItem { result } => {
1129 used_token_count -= 1;
1135
1136 match result {
1137 Ok(compiled_module) => compiled_modules.push(compiled_module),
1138 Err(Some(WorkerFatalError)) => {
1139 codegen_aborted = Some(FatalError);
1141 }
1142 Err(None) => {
1143 ::rustc_middle::util::bug::bug_fmt(format_args!("worker thread panicked"));bug!("worker thread panicked");
1146 }
1147 }
1148 }
1149 }
1150 }
1151
1152 if let Some(codegen_aborted) = codegen_aborted {
1153 codegen_aborted.raise();
1154 }
1155
1156 compiled_modules
1157}
1158
1159fn execute_thin_lto_work_item<B: ExtraBackendMethods>(
1160 cgcx: &CodegenContext<B>,
1161 shared_emitter: SharedEmitter,
1162 module: lto::ThinModule<B>,
1163) -> CompiledModule {
1164 let _timer = cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", module.name());
1165
1166 let module = B::optimize_thin(cgcx, &shared_emitter, module);
1167 B::codegen(cgcx, &shared_emitter, module, &cgcx.module_config)
1168}
1169
1170pub(crate) enum Message<B: WriteBackendMethods> {
1172 Token(io::Result<Acquired>),
1175
1176 WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>> },
1179
1180 CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
1184
1185 AddImportOnlyModule {
1188 module_data: SerializedModule<B::ModuleBuffer>,
1189 work_product: WorkProduct,
1190 },
1191
1192 CodegenComplete,
1195
1196 CodegenAborted,
1199}
1200
1201pub(crate) enum ThinLtoMessage {
1203 Token(io::Result<Acquired>),
1206
1207 WorkItem { result: Result<CompiledModule, Option<WorkerFatalError>> },
1210}
1211
1212pub struct CguMessage;
1215
1216struct Diagnostic {
1226 span: Vec<SpanData>,
1227 level: Level,
1228 messages: Vec<(DiagMessage, Style)>,
1229 code: Option<ErrCode>,
1230 children: Vec<Subdiagnostic>,
1231 args: DiagArgMap,
1232}
1233
1234struct Subdiagnostic {
1238 level: Level,
1239 messages: Vec<(DiagMessage, Style)>,
1240}
1241
1242#[derive(#[automatically_derived]
impl ::core::cmp::PartialEq for MainThreadState {
#[inline]
fn eq(&self, other: &MainThreadState) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq, #[automatically_derived]
impl ::core::clone::Clone for MainThreadState {
#[inline]
fn clone(&self) -> MainThreadState { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for MainThreadState { }Copy, #[automatically_derived]
impl ::core::fmt::Debug for MainThreadState {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
MainThreadState::Idle => "Idle",
MainThreadState::Codegenning => "Codegenning",
MainThreadState::Lending => "Lending",
})
}
}Debug)]
1243enum MainThreadState {
1244 Idle,
1246
1247 Codegenning,
1249
1250 Lending,
1252}
1253
1254fn start_executing_work<B: ExtraBackendMethods>(
1255 backend: B,
1256 tcx: TyCtxt<'_>,
1257 crate_info: &CrateInfo,
1258 shared_emitter: SharedEmitter,
1259 codegen_worker_send: Sender<CguMessage>,
1260 coordinator_receive: Receiver<Message<B>>,
1261 regular_config: Arc<ModuleConfig>,
1262 allocator_config: Arc<ModuleConfig>,
1263 mut allocator_module: Option<ModuleCodegen<B::Module>>,
1264 coordinator_send: Sender<Message<B>>,
1265) -> thread::JoinHandle<Result<MaybeLtoModules<B>, ()>> {
1266 let sess = tcx.sess;
1267
1268 let mut each_linked_rlib_for_lto = Vec::new();
1269 let mut each_linked_rlib_file_for_lto = Vec::new();
1270 drop(link::each_linked_rlib(crate_info, None, &mut |cnum, path| {
1271 if link::ignored_for_lto(sess, crate_info, cnum) {
1272 return;
1273 }
1274 each_linked_rlib_for_lto.push(cnum);
1275 each_linked_rlib_file_for_lto.push(path.to_path_buf());
1276 }));
1277
1278 let exported_symbols_for_lto =
1280 Arc::new(lto::exported_symbols_for_lto(tcx, &each_linked_rlib_for_lto));
1281
1282 let coordinator_send2 = coordinator_send.clone();
1288 let helper = jobserver::client()
1289 .into_helper_thread(move |token| {
1290 drop(coordinator_send2.send(Message::Token::<B>(token)));
1291 })
1292 .expect("failed to spawn helper thread");
1293
1294 let ol = tcx.backend_optimization_level(());
1295 let backend_features = tcx.global_backend_features(());
1296
1297 let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1298 let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1299 match result {
1300 Ok(dir) => Some(dir),
1301 Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1302 }
1303 } else {
1304 None
1305 };
1306
1307 let cgcx = CodegenContext::<B> {
1308 crate_types: tcx.crate_types().to_vec(),
1309 lto: sess.lto(),
1310 use_linker_plugin_lto: sess.opts.cg.linker_plugin_lto.enabled(),
1311 dylib_lto: sess.opts.unstable_opts.dylib_lto,
1312 prefer_dynamic: sess.opts.cg.prefer_dynamic,
1313 fewer_names: sess.fewer_names(),
1314 save_temps: sess.opts.cg.save_temps,
1315 time_trace: sess.opts.unstable_opts.llvm_time_trace,
1316 prof: sess.prof.clone(),
1317 remark: sess.opts.cg.remark.clone(),
1318 remark_dir,
1319 incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1320 output_filenames: Arc::clone(tcx.output_filenames(())),
1321 module_config: regular_config,
1322 tm_factory: backend.target_machine_factory(tcx.sess, ol, backend_features),
1323 msvc_imps_needed: msvc_imps_needed(tcx),
1324 is_pe_coff: tcx.sess.target.is_like_windows,
1325 target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1326 target_arch: tcx.sess.target.arch.to_string(),
1327 target_is_like_darwin: tcx.sess.target.is_like_darwin,
1328 target_is_like_aix: tcx.sess.target.is_like_aix,
1329 target_is_like_gpu: tcx.sess.target.is_like_gpu,
1330 split_debuginfo: tcx.sess.split_debuginfo(),
1331 split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1332 parallel: backend.supports_parallel() && !sess.opts.unstable_opts.no_parallel_backend,
1333 pointer_size: tcx.data_layout.pointer_size(),
1334 invocation_temp: sess.invocation_temp.clone(),
1335 };
1336
1337 return B::spawn_named_thread(cgcx.time_trace, "coordinator".to_string(), move || {
1473 let mut compiled_modules = ::alloc::vec::Vec::new()vec![];
1476 let mut needs_fat_lto = Vec::new();
1477 let mut needs_thin_lto = Vec::new();
1478 let mut lto_import_only_modules = Vec::new();
1479
1480 #[derive(#[automatically_derived]
impl ::core::fmt::Debug for CodegenState {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
CodegenState::Ongoing => "Ongoing",
CodegenState::Completed => "Completed",
CodegenState::Aborted => "Aborted",
})
}
}Debug, #[automatically_derived]
impl ::core::cmp::PartialEq for CodegenState {
#[inline]
fn eq(&self, other: &CodegenState) -> bool {
let __self_discr = ::core::intrinsics::discriminant_value(self);
let __arg1_discr = ::core::intrinsics::discriminant_value(other);
__self_discr == __arg1_discr
}
}PartialEq)]
1485 enum CodegenState {
1486 Ongoing,
1487 Completed,
1488 Aborted,
1489 }
1490 use CodegenState::*;
1491 let mut codegen_state = Ongoing;
1492
1493 let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1495
1496 let mut tokens = Vec::new();
1499
1500 let mut main_thread_state = MainThreadState::Idle;
1501
1502 let mut running_with_own_token = 0;
1505
1506 let running_with_any_token = |main_thread_state, running_with_own_token| {
1509 running_with_own_token
1510 + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1511 };
1512
1513 let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
1514
1515 if let Some(allocator_module) = &mut allocator_module {
1516 B::optimize(&cgcx, &shared_emitter, allocator_module, &allocator_config);
1517 }
1518
1519 loop {
1525 if codegen_state == Ongoing {
1529 if main_thread_state == MainThreadState::Idle {
1530 let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1538 let additional_running = std::cmp::min(extra_tokens, work_items.len());
1539 let anticipated_running = running_with_own_token + additional_running + 1;
1540
1541 if !queue_full_enough(work_items.len(), anticipated_running) {
1542 if codegen_worker_send.send(CguMessage).is_err() {
1544 {
::core::panicking::panic_fmt(format_args!("Could not send CguMessage to main thread"));
}panic!("Could not send CguMessage to main thread")
1545 }
1546 main_thread_state = MainThreadState::Codegenning;
1547 } else {
1548 let (item, _) =
1552 work_items.pop().expect("queue empty - queue_full_enough() broken?");
1553 main_thread_state = MainThreadState::Lending;
1554 spawn_work(
1555 &cgcx,
1556 shared_emitter.clone(),
1557 coordinator_send.clone(),
1558 &mut llvm_start_time,
1559 item,
1560 );
1561 }
1562 }
1563 } else if codegen_state == Completed {
1564 if running_with_any_token(main_thread_state, running_with_own_token) == 0
1565 && work_items.is_empty()
1566 {
1567 break;
1569 }
1570
1571 match main_thread_state {
1575 MainThreadState::Idle => {
1576 if let Some((item, _)) = work_items.pop() {
1577 main_thread_state = MainThreadState::Lending;
1578 spawn_work(
1579 &cgcx,
1580 shared_emitter.clone(),
1581 coordinator_send.clone(),
1582 &mut llvm_start_time,
1583 item,
1584 );
1585 } else {
1586 if !(running_with_own_token > 0) {
::core::panicking::panic("assertion failed: running_with_own_token > 0")
};assert!(running_with_own_token > 0);
1593 running_with_own_token -= 1;
1594 main_thread_state = MainThreadState::Lending;
1595 }
1596 }
1597 MainThreadState::Codegenning => ::rustc_middle::util::bug::bug_fmt(format_args!("codegen worker should not be codegenning after codegen was already completed"))bug!(
1598 "codegen worker should not be codegenning after \
1599 codegen was already completed"
1600 ),
1601 MainThreadState::Lending => {
1602 }
1604 }
1605 } else {
1606 if !(codegen_state == Aborted) {
::core::panicking::panic("assertion failed: codegen_state == Aborted")
};assert!(codegen_state == Aborted);
1609 if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1610 break;
1611 }
1612 }
1613
1614 if codegen_state != Aborted {
1617 while running_with_own_token < tokens.len()
1618 && let Some((item, _)) = work_items.pop()
1619 {
1620 spawn_work(
1621 &cgcx,
1622 shared_emitter.clone(),
1623 coordinator_send.clone(),
1624 &mut llvm_start_time,
1625 item,
1626 );
1627 running_with_own_token += 1;
1628 }
1629 }
1630
1631 tokens.truncate(running_with_own_token);
1633
1634 match coordinator_receive.recv().unwrap() {
1635 Message::Token(token) => {
1639 match token {
1640 Ok(token) => {
1641 tokens.push(token);
1642
1643 if main_thread_state == MainThreadState::Lending {
1644 main_thread_state = MainThreadState::Idle;
1649 running_with_own_token += 1;
1650 }
1651 }
1652 Err(e) => {
1653 let msg = &::alloc::__export::must_use({
::alloc::fmt::format(format_args!("failed to acquire jobserver token: {0}",
e))
})format!("failed to acquire jobserver token: {e}");
1654 shared_emitter.fatal(msg);
1655 codegen_state = Aborted;
1656 }
1657 }
1658 }
1659
1660 Message::CodegenDone { llvm_work_item, cost } => {
1661 let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1670 let insertion_index = match insertion_index {
1671 Ok(idx) | Err(idx) => idx,
1672 };
1673 work_items.insert(insertion_index, (llvm_work_item, cost));
1674
1675 if cgcx.parallel {
1676 helper.request_token();
1677 }
1678 match (&main_thread_state, &MainThreadState::Codegenning) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(main_thread_state, MainThreadState::Codegenning);
1679 main_thread_state = MainThreadState::Idle;
1680 }
1681
1682 Message::CodegenComplete => {
1683 if codegen_state != Aborted {
1684 codegen_state = Completed;
1685 }
1686 match (&main_thread_state, &MainThreadState::Codegenning) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(main_thread_state, MainThreadState::Codegenning);
1687 main_thread_state = MainThreadState::Idle;
1688 }
1689
1690 Message::CodegenAborted => {
1698 codegen_state = Aborted;
1699 }
1700
1701 Message::WorkItem { result } => {
1702 if main_thread_state == MainThreadState::Lending {
1708 main_thread_state = MainThreadState::Idle;
1709 } else {
1710 running_with_own_token -= 1;
1711 }
1712
1713 match result {
1714 Ok(WorkItemResult::Finished(compiled_module)) => {
1715 compiled_modules.push(compiled_module);
1716 }
1717 Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1718 if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
1719 needs_fat_lto.push(fat_lto_input);
1720 }
1721 Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1722 if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
1723 needs_thin_lto.push((name, thin_buffer));
1724 }
1725 Err(Some(WorkerFatalError)) => {
1726 codegen_state = Aborted;
1728 }
1729 Err(None) => {
1730 ::rustc_middle::util::bug::bug_fmt(format_args!("worker thread panicked"));bug!("worker thread panicked");
1733 }
1734 }
1735 }
1736
1737 Message::AddImportOnlyModule { module_data, work_product } => {
1738 match (&codegen_state, &Ongoing) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(codegen_state, Ongoing);
1739 match (&main_thread_state, &MainThreadState::Codegenning) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(main_thread_state, MainThreadState::Codegenning);
1740 lto_import_only_modules.push((module_data, work_product));
1741 main_thread_state = MainThreadState::Idle;
1742 }
1743 }
1744 }
1745
1746 drop(llvm_start_time);
1748
1749 if codegen_state == Aborted {
1750 return Err(());
1751 }
1752
1753 drop(codegen_state);
1754 drop(tokens);
1755 drop(helper);
1756 if !work_items.is_empty() {
::core::panicking::panic("assertion failed: work_items.is_empty()")
};assert!(work_items.is_empty());
1757
1758 if !needs_fat_lto.is_empty() {
1759 if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1760 if !needs_thin_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_thin_lto.is_empty()")
};assert!(needs_thin_lto.is_empty());
1761
1762 if let Some(allocator_module) = allocator_module.take() {
1763 needs_fat_lto.push(FatLtoInput::InMemory(allocator_module));
1764 }
1765
1766 return Ok(MaybeLtoModules::FatLto {
1767 cgcx,
1768 exported_symbols_for_lto,
1769 each_linked_rlib_file_for_lto,
1770 needs_fat_lto,
1771 lto_import_only_modules,
1772 });
1773 } else if !needs_thin_lto.is_empty() || !lto_import_only_modules.is_empty() {
1774 if !compiled_modules.is_empty() {
::core::panicking::panic("assertion failed: compiled_modules.is_empty()")
};assert!(compiled_modules.is_empty());
1775 if !needs_fat_lto.is_empty() {
::core::panicking::panic("assertion failed: needs_fat_lto.is_empty()")
};assert!(needs_fat_lto.is_empty());
1776
1777 if cgcx.lto == Lto::ThinLocal {
1778 compiled_modules.extend(do_thin_lto(
1779 &cgcx,
1780 shared_emitter.clone(),
1781 exported_symbols_for_lto,
1782 each_linked_rlib_file_for_lto,
1783 needs_thin_lto,
1784 lto_import_only_modules,
1785 ));
1786 } else {
1787 if let Some(allocator_module) = allocator_module.take() {
1788 let (name, thin_buffer) = B::prepare_thin(allocator_module);
1789 needs_thin_lto.push((name, thin_buffer));
1790 }
1791
1792 return Ok(MaybeLtoModules::ThinLto {
1793 cgcx,
1794 exported_symbols_for_lto,
1795 each_linked_rlib_file_for_lto,
1796 needs_thin_lto,
1797 lto_import_only_modules,
1798 });
1799 }
1800 }
1801
1802 Ok(MaybeLtoModules::NoLto {
1803 modules: compiled_modules,
1804 allocator_module: allocator_module.map(|allocator_module| {
1805 B::codegen(&cgcx, &shared_emitter, allocator_module, &allocator_config)
1806 }),
1807 })
1808 })
1809 .expect("failed to spawn coordinator thread");
1810
1811 fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1814 let quarter_of_workers = workers_running - 3 * workers_running / 4;
1865 items_in_queue > 0 && items_in_queue >= quarter_of_workers
1866 }
1867}
1868
1869#[must_use]
1871pub(crate) struct WorkerFatalError;
1872
1873fn spawn_work<'a, B: ExtraBackendMethods>(
1874 cgcx: &'a CodegenContext<B>,
1875 shared_emitter: SharedEmitter,
1876 coordinator_send: Sender<Message<B>>,
1877 llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1878 work: WorkItem<B>,
1879) {
1880 if llvm_start_time.is_none() {
1881 *llvm_start_time = Some(cgcx.prof.verbose_generic_activity("LLVM_passes"));
1882 }
1883
1884 let cgcx = cgcx.clone();
1885
1886 B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1887 let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1888 WorkItem::Optimize(m) => execute_optimize_work_item(&cgcx, shared_emitter, m),
1889 WorkItem::CopyPostLtoArtifacts(m) => WorkItemResult::Finished(
1890 execute_copy_from_cache_work_item(&cgcx, shared_emitter, m),
1891 ),
1892 }));
1893
1894 let msg = match result {
1895 Ok(result) => Message::WorkItem::<B> { result: Ok(result) },
1896
1897 Err(err) if err.is::<FatalErrorMarker>() => {
1901 Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1902 }
1903
1904 Err(_) => Message::WorkItem::<B> { result: Err(None) },
1905 };
1906 drop(coordinator_send.send(msg));
1907 })
1908 .expect("failed to spawn work thread");
1909}
1910
1911fn spawn_thin_lto_work<'a, B: ExtraBackendMethods>(
1912 cgcx: &'a CodegenContext<B>,
1913 shared_emitter: SharedEmitter,
1914 coordinator_send: Sender<ThinLtoMessage>,
1915 work: ThinLtoWorkItem<B>,
1916) {
1917 let cgcx = cgcx.clone();
1918
1919 B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1920 let result = std::panic::catch_unwind(AssertUnwindSafe(|| match work {
1921 ThinLtoWorkItem::CopyPostLtoArtifacts(m) => {
1922 execute_copy_from_cache_work_item(&cgcx, shared_emitter, m)
1923 }
1924 ThinLtoWorkItem::ThinLto(m) => execute_thin_lto_work_item(&cgcx, shared_emitter, m),
1925 }));
1926
1927 let msg = match result {
1928 Ok(result) => ThinLtoMessage::WorkItem { result: Ok(result) },
1929
1930 Err(err) if err.is::<FatalErrorMarker>() => {
1934 ThinLtoMessage::WorkItem { result: Err(Some(WorkerFatalError)) }
1935 }
1936
1937 Err(_) => ThinLtoMessage::WorkItem { result: Err(None) },
1938 };
1939 drop(coordinator_send.send(msg));
1940 })
1941 .expect("failed to spawn work thread");
1942}
1943
1944enum SharedEmitterMessage {
1945 Diagnostic(Diagnostic),
1946 InlineAsmError(InlineAsmError),
1947 Fatal(String),
1948}
1949
1950pub struct InlineAsmError {
1951 pub span: SpanData,
1952 pub msg: String,
1953 pub level: Level,
1954 pub source: Option<(String, Vec<InnerSpan>)>,
1955}
1956
1957#[derive(#[automatically_derived]
impl ::core::clone::Clone for SharedEmitter {
#[inline]
fn clone(&self) -> SharedEmitter {
SharedEmitter { sender: ::core::clone::Clone::clone(&self.sender) }
}
}Clone)]
1958pub struct SharedEmitter {
1959 sender: Sender<SharedEmitterMessage>,
1960}
1961
1962pub struct SharedEmitterMain {
1963 receiver: Receiver<SharedEmitterMessage>,
1964}
1965
1966impl SharedEmitter {
1967 fn new() -> (SharedEmitter, SharedEmitterMain) {
1968 let (sender, receiver) = channel();
1969
1970 (SharedEmitter { sender }, SharedEmitterMain { receiver })
1971 }
1972
1973 pub fn inline_asm_error(&self, err: InlineAsmError) {
1974 drop(self.sender.send(SharedEmitterMessage::InlineAsmError(err)));
1975 }
1976
1977 fn fatal(&self, msg: &str) {
1978 drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1979 }
1980}
1981
1982impl Emitter for SharedEmitter {
1983 fn emit_diagnostic(
1984 &mut self,
1985 mut diag: rustc_errors::DiagInner,
1986 _registry: &rustc_errors::registry::Registry,
1987 ) {
1988 if !!diag.span.has_span_labels() {
::core::panicking::panic("assertion failed: !diag.span.has_span_labels()")
};assert!(!diag.span.has_span_labels());
1991 match (&diag.suggestions, &Suggestions::Enabled(::alloc::vec::Vec::new())) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(diag.suggestions, Suggestions::Enabled(vec![]));
1992 match (&diag.sort_span, &rustc_span::DUMMY_SP) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(diag.sort_span, rustc_span::DUMMY_SP);
1993 match (&diag.is_lint, &None) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val, &*right_val,
::core::option::Option::None);
}
}
};assert_eq!(diag.is_lint, None);
1994 let args = mem::replace(&mut diag.args, DiagArgMap::default());
1997 drop(
1998 self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1999 span: diag.span.primary_spans().iter().map(|span| span.data()).collect::<Vec<_>>(),
2000 level: diag.level(),
2001 messages: diag.messages,
2002 code: diag.code,
2003 children: diag
2004 .children
2005 .into_iter()
2006 .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
2007 .collect(),
2008 args,
2009 })),
2010 );
2011 }
2012
2013 fn source_map(&self) -> Option<&SourceMap> {
2014 None
2015 }
2016
2017 fn translator(&self) -> &Translator {
2018 {
::core::panicking::panic_fmt(format_args!("shared emitter attempted to translate a diagnostic"));
};panic!("shared emitter attempted to translate a diagnostic");
2019 }
2020}
2021
2022impl SharedEmitterMain {
2023 fn check(&self, sess: &Session, blocking: bool) {
2024 loop {
2025 let message = if blocking {
2026 match self.receiver.recv() {
2027 Ok(message) => Ok(message),
2028 Err(_) => Err(()),
2029 }
2030 } else {
2031 match self.receiver.try_recv() {
2032 Ok(message) => Ok(message),
2033 Err(_) => Err(()),
2034 }
2035 };
2036
2037 match message {
2038 Ok(SharedEmitterMessage::Diagnostic(diag)) => {
2039 let dcx = sess.dcx();
2042 let mut d =
2043 rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
2044 d.span = MultiSpan::from_spans(
2045 diag.span.into_iter().map(|span| span.span()).collect(),
2046 );
2047 d.code = diag.code; d.children = diag
2049 .children
2050 .into_iter()
2051 .map(|sub| rustc_errors::Subdiag {
2052 level: sub.level,
2053 messages: sub.messages,
2054 span: MultiSpan::new(),
2055 })
2056 .collect();
2057 d.args = diag.args;
2058 dcx.emit_diagnostic(d);
2059 sess.dcx().abort_if_errors();
2060 }
2061 Ok(SharedEmitterMessage::InlineAsmError(inner)) => {
2062 match inner.level {
Level::Error | Level::Warning | Level::Note => {}
ref left_val => {
::core::panicking::assert_matches_failed(left_val,
"Level::Error | Level::Warning | Level::Note",
::core::option::Option::None);
}
};assert_matches!(inner.level, Level::Error | Level::Warning | Level::Note);
2063 let mut err = Diag::<()>::new(sess.dcx(), inner.level, inner.msg);
2064 if !inner.span.is_dummy() {
2065 err.span(inner.span.span());
2066 }
2067
2068 if let Some((buffer, spans)) = inner.source {
2070 let source = sess
2071 .source_map()
2072 .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
2073 let spans: Vec<_> = spans
2074 .iter()
2075 .map(|sp| {
2076 Span::with_root_ctxt(
2077 source.normalized_byte_pos(sp.start as u32),
2078 source.normalized_byte_pos(sp.end as u32),
2079 )
2080 })
2081 .collect();
2082 err.span_note(spans, "instantiated into assembly here");
2083 }
2084
2085 err.emit();
2086 }
2087 Ok(SharedEmitterMessage::Fatal(msg)) => {
2088 sess.dcx().fatal(msg);
2089 }
2090 Err(_) => {
2091 break;
2092 }
2093 }
2094 }
2095 }
2096}
2097
2098pub struct Coordinator<B: ExtraBackendMethods> {
2099 sender: Sender<Message<B>>,
2100 future: Option<thread::JoinHandle<Result<MaybeLtoModules<B>, ()>>>,
2101 phantom: PhantomData<B>,
2103}
2104
2105impl<B: ExtraBackendMethods> Coordinator<B> {
2106 fn join(mut self) -> std::thread::Result<Result<MaybeLtoModules<B>, ()>> {
2107 self.future.take().unwrap().join()
2108 }
2109}
2110
2111impl<B: ExtraBackendMethods> Drop for Coordinator<B> {
2112 fn drop(&mut self) {
2113 if let Some(future) = self.future.take() {
2114 drop(self.sender.send(Message::CodegenAborted::<B>));
2117 drop(future.join());
2118 }
2119 }
2120}
2121
2122pub struct OngoingCodegen<B: ExtraBackendMethods> {
2123 pub backend: B,
2124 pub crate_info: CrateInfo,
2125 pub output_filenames: Arc<OutputFilenames>,
2126 pub coordinator: Coordinator<B>,
2130 pub codegen_worker_receive: Receiver<CguMessage>,
2131 pub shared_emitter_main: SharedEmitterMain,
2132}
2133
2134impl<B: ExtraBackendMethods> OngoingCodegen<B> {
2135 pub fn join(self, sess: &Session) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
2136 self.shared_emitter_main.check(sess, true);
2137
2138 let maybe_lto_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
2139 Ok(Ok(maybe_lto_modules)) => maybe_lto_modules,
2140 Ok(Err(())) => {
2141 sess.dcx().abort_if_errors();
2142 {
::core::panicking::panic_fmt(format_args!("expected abort due to worker thread errors"));
}panic!("expected abort due to worker thread errors")
2143 }
2144 Err(_) => {
2145 ::rustc_middle::util::bug::bug_fmt(format_args!("panic during codegen/LLVM phase"));bug!("panic during codegen/LLVM phase");
2146 }
2147 });
2148
2149 sess.dcx().abort_if_errors();
2150
2151 let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
2152
2153 let compiled_modules = catch_fatal_errors(|| match maybe_lto_modules {
2155 MaybeLtoModules::NoLto { modules, allocator_module } => {
2156 drop(shared_emitter);
2157 CompiledModules { modules, allocator_module }
2158 }
2159 MaybeLtoModules::FatLto {
2160 cgcx,
2161 exported_symbols_for_lto,
2162 each_linked_rlib_file_for_lto,
2163 needs_fat_lto,
2164 lto_import_only_modules,
2165 } => CompiledModules {
2166 modules: <[_]>::into_vec(::alloc::boxed::box_new([do_fat_lto(&cgcx, shared_emitter,
&exported_symbols_for_lto, &each_linked_rlib_file_for_lto,
needs_fat_lto, lto_import_only_modules)]))vec![do_fat_lto(
2167 &cgcx,
2168 shared_emitter,
2169 &exported_symbols_for_lto,
2170 &each_linked_rlib_file_for_lto,
2171 needs_fat_lto,
2172 lto_import_only_modules,
2173 )],
2174 allocator_module: None,
2175 },
2176 MaybeLtoModules::ThinLto {
2177 cgcx,
2178 exported_symbols_for_lto,
2179 each_linked_rlib_file_for_lto,
2180 needs_thin_lto,
2181 lto_import_only_modules,
2182 } => CompiledModules {
2183 modules: do_thin_lto(
2184 &cgcx,
2185 shared_emitter,
2186 exported_symbols_for_lto,
2187 each_linked_rlib_file_for_lto,
2188 needs_thin_lto,
2189 lto_import_only_modules,
2190 ),
2191 allocator_module: None,
2192 },
2193 });
2194
2195 shared_emitter_main.check(sess, true);
2196
2197 sess.dcx().abort_if_errors();
2198
2199 let mut compiled_modules =
2200 compiled_modules.expect("fatal error emitted but not sent to SharedEmitter");
2201
2202 compiled_modules.modules.sort_by(|a, b| a.name.cmp(&b.name));
2206
2207 let work_products =
2208 copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
2209 produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
2210
2211 if sess.codegen_units().as_usize() == 1 && sess.opts.unstable_opts.time_llvm_passes {
2214 self.backend.print_pass_timings()
2215 }
2216
2217 if sess.print_llvm_stats() {
2218 self.backend.print_statistics()
2219 }
2220
2221 (
2222 CodegenResults {
2223 crate_info: self.crate_info,
2224
2225 modules: compiled_modules.modules,
2226 allocator_module: compiled_modules.allocator_module,
2227 },
2228 work_products,
2229 )
2230 }
2231
2232 pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2233 self.wait_for_signal_to_codegen_item();
2234 self.check_for_errors(tcx.sess);
2235 drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
2236 }
2237
2238 pub(crate) fn check_for_errors(&self, sess: &Session) {
2239 self.shared_emitter_main.check(sess, false);
2240 }
2241
2242 pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2243 match self.codegen_worker_receive.recv() {
2244 Ok(CguMessage) => {
2245 }
2247 Err(_) => {
2248 }
2251 }
2252 }
2253}
2254
2255pub(crate) fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
2256 coordinator: &Coordinator<B>,
2257 module: ModuleCodegen<B::Module>,
2258 cost: u64,
2259) {
2260 let llvm_work_item = WorkItem::Optimize(module);
2261 drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2262}
2263
2264pub(crate) fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
2265 coordinator: &Coordinator<B>,
2266 module: CachedModuleCodegen,
2267) {
2268 let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2269 drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2270}
2271
2272pub(crate) fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
2273 tcx: TyCtxt<'_>,
2274 coordinator: &Coordinator<B>,
2275 module: CachedModuleCodegen,
2276) {
2277 let filename = pre_lto_bitcode_filename(&module.name);
2278 let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2279 let file = fs::File::open(&bc_path)
2280 .unwrap_or_else(|e| {
::core::panicking::panic_fmt(format_args!("failed to open bitcode file `{0}`: {1}",
bc_path.display(), e));
}panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
2281
2282 let mmap = unsafe {
2283 Mmap::map(file).unwrap_or_else(|e| {
2284 {
::core::panicking::panic_fmt(format_args!("failed to mmap bitcode file `{0}`: {1}",
bc_path.display(), e));
}panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2285 })
2286 };
2287 drop(coordinator.sender.send(Message::AddImportOnlyModule::<B> {
2289 module_data: SerializedModule::FromUncompressedFile(mmap),
2290 work_product: module.source,
2291 }));
2292}
2293
2294fn pre_lto_bitcode_filename(module_name: &str) -> String {
2295 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}.{1}", module_name,
PRE_LTO_BC_EXT))
})format!("{module_name}.{PRE_LTO_BC_EXT}")
2296}
2297
2298fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2299 if !!(tcx.sess.opts.cg.linker_plugin_lto.enabled() &&
tcx.sess.target.is_like_windows &&
tcx.sess.opts.cg.prefer_dynamic) {
::core::panicking::panic("assertion failed: !(tcx.sess.opts.cg.linker_plugin_lto.enabled() &&\n tcx.sess.target.is_like_windows &&\n tcx.sess.opts.cg.prefer_dynamic)")
};assert!(
2302 !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2303 && tcx.sess.target.is_like_windows
2304 && tcx.sess.opts.cg.prefer_dynamic)
2305 );
2306
2307 let can_have_static_objects =
2311 tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
2312
2313 tcx.sess.target.is_like_windows &&
2314 can_have_static_objects &&
2315 !tcx.sess.opts.cg.linker_plugin_lto.enabled()
2319}