rustc_codegen_ssa/back/
write.rs

1use std::assert_matches::assert_matches;
2use std::marker::PhantomData;
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_ast::expand::autodiff_attrs::AutoDiffItem;
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, FatalError, 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::{AutodiffWithoutLto, 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/// What kind of object file to emit.
51#[derive(Clone, Copy, PartialEq)]
52pub enum EmitObj {
53    // No object file.
54    None,
55
56    // Just uncompressed llvm bitcode. Provides easy compatibility with
57    // emscripten's ecc compiler, when used as the linker.
58    Bitcode,
59
60    // Object code, possibly augmented with a bitcode section.
61    ObjectCode(BitcodeSection),
62}
63
64/// What kind of llvm bitcode section to embed in an object file.
65#[derive(Clone, Copy, PartialEq)]
66pub enum BitcodeSection {
67    // No bitcode section.
68    None,
69
70    // A full, uncompressed bitcode section.
71    Full,
72}
73
74/// Module-specific configuration for `optimize_and_codegen`.
75pub struct ModuleConfig {
76    /// Names of additional optimization passes to run.
77    pub passes: Vec<String>,
78    /// Some(level) to optimize at a certain level, or None to run
79    /// absolutely no optimizations (used for the metadata module).
80    pub opt_level: Option<config::OptLevel>,
81
82    /// Some(level) to optimize binary size, or None to not affect program size.
83    pub opt_size: Option<config::OptLevel>,
84
85    pub pgo_gen: SwitchWithOptPath,
86    pub pgo_use: Option<PathBuf>,
87    pub pgo_sample_use: Option<PathBuf>,
88    pub debug_info_for_profiling: bool,
89    pub instrument_coverage: bool,
90
91    pub sanitizer: SanitizerSet,
92    pub sanitizer_recover: SanitizerSet,
93    pub sanitizer_dataflow_abilist: Vec<String>,
94    pub sanitizer_memory_track_origins: usize,
95
96    // Flags indicating which outputs to produce.
97    pub emit_pre_lto_bc: bool,
98    pub emit_no_opt_bc: bool,
99    pub emit_bc: bool,
100    pub emit_ir: bool,
101    pub emit_asm: bool,
102    pub emit_obj: EmitObj,
103    pub emit_thin_lto: bool,
104    pub emit_thin_lto_summary: bool,
105    pub bc_cmdline: String,
106
107    // Miscellaneous flags. These are mostly copied from command-line
108    // options.
109    pub verify_llvm_ir: bool,
110    pub lint_llvm_ir: bool,
111    pub no_prepopulate_passes: bool,
112    pub no_builtins: bool,
113    pub time_module: bool,
114    pub vectorize_loop: bool,
115    pub vectorize_slp: bool,
116    pub merge_functions: bool,
117    pub emit_lifetime_markers: bool,
118    pub llvm_plugins: Vec<String>,
119    pub autodiff: Vec<config::AutoDiff>,
120    pub offload: Vec<config::Offload>,
121}
122
123impl ModuleConfig {
124    fn new(kind: ModuleKind, tcx: TyCtxt<'_>, no_builtins: bool) -> ModuleConfig {
125        // If it's a regular module, use `$regular`, otherwise use `$other`.
126        // `$regular` and `$other` are evaluated lazily.
127        macro_rules! if_regular {
128            ($regular: expr, $other: expr) => {
129                if let ModuleKind::Regular = kind { $regular } else { $other }
130            };
131        }
132
133        let sess = tcx.sess;
134        let opt_level_and_size = if_regular!(Some(sess.opts.optimize), None);
135
136        let save_temps = sess.opts.cg.save_temps;
137
138        let should_emit_obj = sess.opts.output_types.contains_key(&OutputType::Exe)
139            || match kind {
140                ModuleKind::Regular => sess.opts.output_types.contains_key(&OutputType::Object),
141                ModuleKind::Allocator => false,
142            };
143
144        let emit_obj = if !should_emit_obj {
145            EmitObj::None
146        } else if sess.target.obj_is_bitcode
147            || (sess.opts.cg.linker_plugin_lto.enabled() && !no_builtins)
148        {
149            // This case is selected if the target uses objects as bitcode, or
150            // if linker plugin LTO is enabled. In the linker plugin LTO case
151            // the assumption is that the final link-step will read the bitcode
152            // and convert it to object code. This may be done by either the
153            // native linker or rustc itself.
154            //
155            // Note, however, that the linker-plugin-lto requested here is
156            // explicitly ignored for `#![no_builtins]` crates. These crates are
157            // specifically ignored by rustc's LTO passes and wouldn't work if
158            // loaded into the linker. These crates define symbols that LLVM
159            // lowers intrinsics to, and these symbol dependencies aren't known
160            // until after codegen. As a result any crate marked
161            // `#![no_builtins]` is assumed to not participate in LTO and
162            // instead goes on to generate object code.
163            EmitObj::Bitcode
164        } else if need_bitcode_in_object(tcx) {
165            EmitObj::ObjectCode(BitcodeSection::Full)
166        } else {
167            EmitObj::ObjectCode(BitcodeSection::None)
168        };
169
170        ModuleConfig {
171            passes: if_regular!(sess.opts.cg.passes.clone(), vec![]),
172
173            opt_level: opt_level_and_size,
174            opt_size: opt_level_and_size,
175
176            pgo_gen: if_regular!(
177                sess.opts.cg.profile_generate.clone(),
178                SwitchWithOptPath::Disabled
179            ),
180            pgo_use: if_regular!(sess.opts.cg.profile_use.clone(), None),
181            pgo_sample_use: if_regular!(sess.opts.unstable_opts.profile_sample_use.clone(), None),
182            debug_info_for_profiling: sess.opts.unstable_opts.debug_info_for_profiling,
183            instrument_coverage: if_regular!(sess.instrument_coverage(), false),
184
185            sanitizer: if_regular!(sess.opts.unstable_opts.sanitizer, SanitizerSet::empty()),
186            sanitizer_dataflow_abilist: if_regular!(
187                sess.opts.unstable_opts.sanitizer_dataflow_abilist.clone(),
188                Vec::new()
189            ),
190            sanitizer_recover: if_regular!(
191                sess.opts.unstable_opts.sanitizer_recover,
192                SanitizerSet::empty()
193            ),
194            sanitizer_memory_track_origins: if_regular!(
195                sess.opts.unstable_opts.sanitizer_memory_track_origins,
196                0
197            ),
198
199            emit_pre_lto_bc: if_regular!(
200                save_temps || need_pre_lto_bitcode_for_incr_comp(sess),
201                false
202            ),
203            emit_no_opt_bc: if_regular!(save_temps, false),
204            emit_bc: if_regular!(
205                save_temps || sess.opts.output_types.contains_key(&OutputType::Bitcode),
206                save_temps
207            ),
208            emit_ir: if_regular!(
209                sess.opts.output_types.contains_key(&OutputType::LlvmAssembly),
210                false
211            ),
212            emit_asm: if_regular!(
213                sess.opts.output_types.contains_key(&OutputType::Assembly),
214                false
215            ),
216            emit_obj,
217            // thin lto summaries prevent fat lto, so do not emit them if fat
218            // lto is requested. See PR #136840 for background information.
219            emit_thin_lto: sess.opts.unstable_opts.emit_thin_lto && sess.lto() != Lto::Fat,
220            emit_thin_lto_summary: if_regular!(
221                sess.opts.output_types.contains_key(&OutputType::ThinLinkBitcode),
222                false
223            ),
224            bc_cmdline: sess.target.bitcode_llvm_cmdline.to_string(),
225
226            verify_llvm_ir: sess.verify_llvm_ir(),
227            lint_llvm_ir: sess.opts.unstable_opts.lint_llvm_ir,
228            no_prepopulate_passes: sess.opts.cg.no_prepopulate_passes,
229            no_builtins: no_builtins || sess.target.no_builtins,
230
231            // Exclude metadata and allocator modules from time_passes output,
232            // since they throw off the "LLVM passes" measurement.
233            time_module: if_regular!(true, false),
234
235            // Copy what clang does by turning on loop vectorization at O2 and
236            // slp vectorization at O3.
237            vectorize_loop: !sess.opts.cg.no_vectorize_loops
238                && (sess.opts.optimize == config::OptLevel::More
239                    || sess.opts.optimize == config::OptLevel::Aggressive),
240            vectorize_slp: !sess.opts.cg.no_vectorize_slp
241                && sess.opts.optimize == config::OptLevel::Aggressive,
242
243            // Some targets (namely, NVPTX) interact badly with the
244            // MergeFunctions pass. This is because MergeFunctions can generate
245            // new function calls which may interfere with the target calling
246            // convention; e.g. for the NVPTX target, PTX kernels should not
247            // call other PTX kernels. MergeFunctions can also be configured to
248            // generate aliases instead, but aliases are not supported by some
249            // backends (again, NVPTX). Therefore, allow targets to opt out of
250            // the MergeFunctions pass, but otherwise keep the pass enabled (at
251            // O2 and O3) since it can be useful for reducing code size.
252            merge_functions: match sess
253                .opts
254                .unstable_opts
255                .merge_functions
256                .unwrap_or(sess.target.merge_functions)
257            {
258                MergeFunctions::Disabled => false,
259                MergeFunctions::Trampolines | MergeFunctions::Aliases => {
260                    use config::OptLevel::*;
261                    match sess.opts.optimize {
262                        Aggressive | More | SizeMin | Size => true,
263                        Less | No => false,
264                    }
265                }
266            },
267
268            emit_lifetime_markers: sess.emit_lifetime_markers(),
269            llvm_plugins: if_regular!(sess.opts.unstable_opts.llvm_plugins.clone(), vec![]),
270            autodiff: if_regular!(sess.opts.unstable_opts.autodiff.clone(), vec![]),
271            offload: if_regular!(sess.opts.unstable_opts.offload.clone(), vec![]),
272        }
273    }
274
275    pub fn bitcode_needed(&self) -> bool {
276        self.emit_bc
277            || self.emit_thin_lto_summary
278            || self.emit_obj == EmitObj::Bitcode
279            || self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
280    }
281
282    pub fn embed_bitcode(&self) -> bool {
283        self.emit_obj == EmitObj::ObjectCode(BitcodeSection::Full)
284    }
285}
286
287/// Configuration passed to the function returned by the `target_machine_factory`.
288pub struct TargetMachineFactoryConfig {
289    /// Split DWARF is enabled in LLVM by checking that `TM.MCOptions.SplitDwarfFile` isn't empty,
290    /// so the path to the dwarf object has to be provided when we create the target machine.
291    /// This can be ignored by backends which do not need it for their Split DWARF support.
292    pub split_dwarf_file: Option<PathBuf>,
293
294    /// The name of the output object file. Used for setting OutputFilenames in target options
295    /// so that LLVM can emit the CodeView S_OBJNAME record in pdb files
296    pub output_obj_file: Option<PathBuf>,
297}
298
299impl TargetMachineFactoryConfig {
300    pub fn new(
301        cgcx: &CodegenContext<impl WriteBackendMethods>,
302        module_name: &str,
303    ) -> TargetMachineFactoryConfig {
304        let split_dwarf_file = if cgcx.target_can_use_split_dwarf {
305            cgcx.output_filenames.split_dwarf_path(
306                cgcx.split_debuginfo,
307                cgcx.split_dwarf_kind,
308                module_name,
309                cgcx.invocation_temp.as_deref(),
310            )
311        } else {
312            None
313        };
314
315        let output_obj_file = Some(cgcx.output_filenames.temp_path_for_cgu(
316            OutputType::Object,
317            module_name,
318            cgcx.invocation_temp.as_deref(),
319        ));
320        TargetMachineFactoryConfig { split_dwarf_file, output_obj_file }
321    }
322}
323
324pub type TargetMachineFactoryFn<B> = Arc<
325    dyn Fn(
326            TargetMachineFactoryConfig,
327        ) -> Result<
328            <B as WriteBackendMethods>::TargetMachine,
329            <B as WriteBackendMethods>::TargetMachineError,
330        > + Send
331        + Sync,
332>;
333
334/// Additional resources used by optimize_and_codegen (not module specific)
335#[derive(Clone)]
336pub struct CodegenContext<B: WriteBackendMethods> {
337    // Resources needed when running LTO
338    pub prof: SelfProfilerRef,
339    pub lto: Lto,
340    pub save_temps: bool,
341    pub fewer_names: bool,
342    pub time_trace: bool,
343    pub opts: Arc<config::Options>,
344    pub crate_types: Vec<CrateType>,
345    pub output_filenames: Arc<OutputFilenames>,
346    pub invocation_temp: Option<String>,
347    pub regular_module_config: Arc<ModuleConfig>,
348    pub allocator_module_config: Arc<ModuleConfig>,
349    pub tm_factory: TargetMachineFactoryFn<B>,
350    pub msvc_imps_needed: bool,
351    pub is_pe_coff: bool,
352    pub target_can_use_split_dwarf: bool,
353    pub target_arch: String,
354    pub target_is_like_darwin: bool,
355    pub target_is_like_aix: bool,
356    pub split_debuginfo: rustc_target::spec::SplitDebuginfo,
357    pub split_dwarf_kind: rustc_session::config::SplitDwarfKind,
358    pub pointer_size: Size,
359
360    /// All commandline args used to invoke the compiler, with @file args fully expanded.
361    /// This will only be used within debug info, e.g. in the pdb file on windows
362    /// This is mainly useful for other tools that reads that debuginfo to figure out
363    /// how to call the compiler with the same arguments.
364    pub expanded_args: Vec<String>,
365
366    /// Emitter to use for diagnostics produced during codegen.
367    pub diag_emitter: SharedEmitter,
368    /// LLVM optimizations for which we want to print remarks.
369    pub remark: Passes,
370    /// Directory into which should the LLVM optimization remarks be written.
371    /// If `None`, they will be written to stderr.
372    pub remark_dir: Option<PathBuf>,
373    /// The incremental compilation session directory, or None if we are not
374    /// compiling incrementally
375    pub incr_comp_session_dir: Option<PathBuf>,
376    /// `true` if the codegen should be run in parallel.
377    ///
378    /// Depends on [`ExtraBackendMethods::supports_parallel()`] and `-Zno_parallel_backend`.
379    pub parallel: bool,
380}
381
382impl<B: WriteBackendMethods> CodegenContext<B> {
383    pub fn create_dcx(&self) -> DiagCtxt {
384        DiagCtxt::new(Box::new(self.diag_emitter.clone()))
385    }
386
387    pub fn config(&self, kind: ModuleKind) -> &ModuleConfig {
388        match kind {
389            ModuleKind::Regular => &self.regular_module_config,
390            ModuleKind::Allocator => &self.allocator_module_config,
391        }
392    }
393}
394
395fn generate_thin_lto_work<B: ExtraBackendMethods>(
396    cgcx: &CodegenContext<B>,
397    exported_symbols_for_lto: &[String],
398    each_linked_rlib_for_lto: &[PathBuf],
399    needs_thin_lto: Vec<(String, B::ThinBuffer)>,
400    import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
401) -> Vec<(WorkItem<B>, u64)> {
402    let _prof_timer = cgcx.prof.generic_activity("codegen_thin_generate_lto_work");
403
404    let (lto_modules, copy_jobs) = B::run_thin_lto(
405        cgcx,
406        exported_symbols_for_lto,
407        each_linked_rlib_for_lto,
408        needs_thin_lto,
409        import_only_modules,
410    )
411    .unwrap_or_else(|e| e.raise());
412    lto_modules
413        .into_iter()
414        .map(|module| {
415            let cost = module.cost();
416            (WorkItem::ThinLto(module), cost)
417        })
418        .chain(copy_jobs.into_iter().map(|wp| {
419            (
420                WorkItem::CopyPostLtoArtifacts(CachedModuleCodegen {
421                    name: wp.cgu_name.clone(),
422                    source: wp,
423                }),
424                0, // copying is very cheap
425            )
426        }))
427        .collect()
428}
429
430struct CompiledModules {
431    modules: Vec<CompiledModule>,
432    allocator_module: Option<CompiledModule>,
433}
434
435fn need_bitcode_in_object(tcx: TyCtxt<'_>) -> bool {
436    let sess = tcx.sess;
437    sess.opts.cg.embed_bitcode
438        && tcx.crate_types().contains(&CrateType::Rlib)
439        && sess.opts.output_types.contains_key(&OutputType::Exe)
440}
441
442fn need_pre_lto_bitcode_for_incr_comp(sess: &Session) -> bool {
443    if sess.opts.incremental.is_none() {
444        return false;
445    }
446
447    match sess.lto() {
448        Lto::No => false,
449        Lto::Fat | Lto::Thin | Lto::ThinLocal => true,
450    }
451}
452
453pub(crate) fn start_async_codegen<B: ExtraBackendMethods>(
454    backend: B,
455    tcx: TyCtxt<'_>,
456    target_cpu: String,
457    autodiff_items: &[AutoDiffItem],
458) -> OngoingCodegen<B> {
459    let (coordinator_send, coordinator_receive) = channel();
460
461    let crate_attrs = tcx.hir_attrs(rustc_hir::CRATE_HIR_ID);
462    let no_builtins = attr::contains_name(crate_attrs, sym::no_builtins);
463
464    let crate_info = CrateInfo::new(tcx, target_cpu);
465
466    let regular_config = ModuleConfig::new(ModuleKind::Regular, tcx, no_builtins);
467    let allocator_config = ModuleConfig::new(ModuleKind::Allocator, tcx, no_builtins);
468
469    let (shared_emitter, shared_emitter_main) = SharedEmitter::new();
470    let (codegen_worker_send, codegen_worker_receive) = channel();
471
472    let coordinator_thread = start_executing_work(
473        backend.clone(),
474        tcx,
475        &crate_info,
476        autodiff_items,
477        shared_emitter,
478        codegen_worker_send,
479        coordinator_receive,
480        Arc::new(regular_config),
481        Arc::new(allocator_config),
482        coordinator_send.clone(),
483    );
484
485    OngoingCodegen {
486        backend,
487        crate_info,
488
489        codegen_worker_receive,
490        shared_emitter_main,
491        coordinator: Coordinator {
492            sender: coordinator_send,
493            future: Some(coordinator_thread),
494            phantom: PhantomData,
495        },
496        output_filenames: Arc::clone(tcx.output_filenames(())),
497    }
498}
499
500fn copy_all_cgu_workproducts_to_incr_comp_cache_dir(
501    sess: &Session,
502    compiled_modules: &CompiledModules,
503) -> FxIndexMap<WorkProductId, WorkProduct> {
504    let mut work_products = FxIndexMap::default();
505
506    if sess.opts.incremental.is_none() {
507        return work_products;
508    }
509
510    let _timer = sess.timer("copy_all_cgu_workproducts_to_incr_comp_cache_dir");
511
512    for module in compiled_modules.modules.iter().filter(|m| m.kind == ModuleKind::Regular) {
513        let mut files = Vec::new();
514        if let Some(object_file_path) = &module.object {
515            files.push((OutputType::Object.extension(), object_file_path.as_path()));
516        }
517        if let Some(dwarf_object_file_path) = &module.dwarf_object {
518            files.push(("dwo", dwarf_object_file_path.as_path()));
519        }
520        if let Some(path) = &module.assembly {
521            files.push((OutputType::Assembly.extension(), path.as_path()));
522        }
523        if let Some(path) = &module.llvm_ir {
524            files.push((OutputType::LlvmAssembly.extension(), path.as_path()));
525        }
526        if let Some(path) = &module.bytecode {
527            files.push((OutputType::Bitcode.extension(), path.as_path()));
528        }
529        if let Some((id, product)) = copy_cgu_workproduct_to_incr_comp_cache_dir(
530            sess,
531            &module.name,
532            files.as_slice(),
533            &module.links_from_incr_cache,
534        ) {
535            work_products.insert(id, product);
536        }
537    }
538
539    work_products
540}
541
542fn produce_final_output_artifacts(
543    sess: &Session,
544    compiled_modules: &CompiledModules,
545    crate_output: &OutputFilenames,
546) {
547    let mut user_wants_bitcode = false;
548    let mut user_wants_objects = false;
549
550    // Produce final compile outputs.
551    let copy_gracefully = |from: &Path, to: &OutFileName| match to {
552        OutFileName::Stdout if let Err(e) = copy_to_stdout(from) => {
553            sess.dcx().emit_err(errors::CopyPath::new(from, to.as_path(), e));
554        }
555        OutFileName::Real(path) if let Err(e) = fs::copy(from, path) => {
556            sess.dcx().emit_err(errors::CopyPath::new(from, path, e));
557        }
558        _ => {}
559    };
560
561    let copy_if_one_unit = |output_type: OutputType, keep_numbered: bool| {
562        if let [module] = &compiled_modules.modules[..] {
563            // 1) Only one codegen unit. In this case it's no difficulty
564            //    to copy `foo.0.x` to `foo.x`.
565            let path = crate_output.temp_path_for_cgu(
566                output_type,
567                &module.name,
568                sess.invocation_temp.as_deref(),
569            );
570            let output = crate_output.path(output_type);
571            if !output_type.is_text_output() && output.is_tty() {
572                sess.dcx()
573                    .emit_err(errors::BinaryOutputToTty { shorthand: output_type.shorthand() });
574            } else {
575                copy_gracefully(&path, &output);
576            }
577            if !sess.opts.cg.save_temps && !keep_numbered {
578                // The user just wants `foo.x`, not `foo.#module-name#.x`.
579                ensure_removed(sess.dcx(), &path);
580            }
581        } else {
582            if crate_output.outputs.contains_explicit_name(&output_type) {
583                // 2) Multiple codegen units, with `--emit foo=some_name`. We have
584                //    no good solution for this case, so warn the user.
585                sess.dcx()
586                    .emit_warn(errors::IgnoringEmitPath { extension: output_type.extension() });
587            } else if crate_output.single_output_file.is_some() {
588                // 3) Multiple codegen units, with `-o some_name`. We have
589                //    no good solution for this case, so warn the user.
590                sess.dcx().emit_warn(errors::IgnoringOutput { extension: output_type.extension() });
591            } else {
592                // 4) Multiple codegen units, but no explicit name. We
593                //    just leave the `foo.0.x` files in place.
594                // (We don't have to do any work in this case.)
595            }
596        }
597    };
598
599    // Flag to indicate whether the user explicitly requested bitcode.
600    // Otherwise, we produced it only as a temporary output, and will need
601    // to get rid of it.
602    for output_type in crate_output.outputs.keys() {
603        match *output_type {
604            OutputType::Bitcode => {
605                user_wants_bitcode = true;
606                // Copy to .bc, but always keep the .0.bc. There is a later
607                // check to figure out if we should delete .0.bc files, or keep
608                // them for making an rlib.
609                copy_if_one_unit(OutputType::Bitcode, true);
610            }
611            OutputType::ThinLinkBitcode => {
612                copy_if_one_unit(OutputType::ThinLinkBitcode, false);
613            }
614            OutputType::LlvmAssembly => {
615                copy_if_one_unit(OutputType::LlvmAssembly, false);
616            }
617            OutputType::Assembly => {
618                copy_if_one_unit(OutputType::Assembly, false);
619            }
620            OutputType::Object => {
621                user_wants_objects = true;
622                copy_if_one_unit(OutputType::Object, true);
623            }
624            OutputType::Mir | OutputType::Metadata | OutputType::Exe | OutputType::DepInfo => {}
625        }
626    }
627
628    // Clean up unwanted temporary files.
629
630    // We create the following files by default:
631    //  - #crate#.#module-name#.bc
632    //  - #crate#.#module-name#.o
633    //  - #crate#.crate.metadata.bc
634    //  - #crate#.crate.metadata.o
635    //  - #crate#.o (linked from crate.##.o)
636    //  - #crate#.bc (copied from crate.##.bc)
637    // We may create additional files if requested by the user (through
638    // `-C save-temps` or `--emit=` flags).
639
640    if !sess.opts.cg.save_temps {
641        // Remove the temporary .#module-name#.o objects. If the user didn't
642        // explicitly request bitcode (with --emit=bc), and the bitcode is not
643        // needed for building an rlib, then we must remove .#module-name#.bc as
644        // well.
645
646        // Specific rules for keeping .#module-name#.bc:
647        //  - If the user requested bitcode (`user_wants_bitcode`), and
648        //    codegen_units > 1, then keep it.
649        //  - If the user requested bitcode but codegen_units == 1, then we
650        //    can toss .#module-name#.bc because we copied it to .bc earlier.
651        //  - If we're not building an rlib and the user didn't request
652        //    bitcode, then delete .#module-name#.bc.
653        // If you change how this works, also update back::link::link_rlib,
654        // where .#module-name#.bc files are (maybe) deleted after making an
655        // rlib.
656        let needs_crate_object = crate_output.outputs.contains_key(&OutputType::Exe);
657
658        let keep_numbered_bitcode = user_wants_bitcode && sess.codegen_units().as_usize() > 1;
659
660        let keep_numbered_objects =
661            needs_crate_object || (user_wants_objects && sess.codegen_units().as_usize() > 1);
662
663        for module in compiled_modules.modules.iter() {
664            if !keep_numbered_objects {
665                if let Some(ref path) = module.object {
666                    ensure_removed(sess.dcx(), path);
667                }
668
669                if let Some(ref path) = module.dwarf_object {
670                    ensure_removed(sess.dcx(), path);
671                }
672            }
673
674            if let Some(ref path) = module.bytecode {
675                if !keep_numbered_bitcode {
676                    ensure_removed(sess.dcx(), path);
677                }
678            }
679        }
680
681        if !user_wants_bitcode
682            && let Some(ref allocator_module) = compiled_modules.allocator_module
683            && let Some(ref path) = allocator_module.bytecode
684        {
685            ensure_removed(sess.dcx(), path);
686        }
687    }
688
689    if sess.opts.json_artifact_notifications {
690        if let [module] = &compiled_modules.modules[..] {
691            module.for_each_output(|_path, ty| {
692                if sess.opts.output_types.contains_key(&ty) {
693                    let descr = ty.shorthand();
694                    // for single cgu file is renamed to drop cgu specific suffix
695                    // so we regenerate it the same way
696                    let path = crate_output.path(ty);
697                    sess.dcx().emit_artifact_notification(path.as_path(), descr);
698                }
699            });
700        } else {
701            for module in &compiled_modules.modules {
702                module.for_each_output(|path, ty| {
703                    if sess.opts.output_types.contains_key(&ty) {
704                        let descr = ty.shorthand();
705                        sess.dcx().emit_artifact_notification(&path, descr);
706                    }
707                });
708            }
709        }
710    }
711
712    // We leave the following files around by default:
713    //  - #crate#.o
714    //  - #crate#.crate.metadata.o
715    //  - #crate#.bc
716    // These are used in linking steps and will be cleaned up afterward.
717}
718
719pub(crate) enum WorkItem<B: WriteBackendMethods> {
720    /// Optimize a newly codegened, totally unoptimized module.
721    Optimize(ModuleCodegen<B::Module>),
722    /// Copy the post-LTO artifacts from the incremental cache to the output
723    /// directory.
724    CopyPostLtoArtifacts(CachedModuleCodegen),
725    /// Performs fat LTO on the given module.
726    FatLto {
727        exported_symbols_for_lto: Arc<Vec<String>>,
728        each_linked_rlib_for_lto: Vec<PathBuf>,
729        needs_fat_lto: Vec<FatLtoInput<B>>,
730        import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
731        autodiff: Vec<AutoDiffItem>,
732    },
733    /// Performs thin-LTO on the given module.
734    ThinLto(lto::ThinModule<B>),
735}
736
737impl<B: WriteBackendMethods> WorkItem<B> {
738    fn module_kind(&self) -> ModuleKind {
739        match *self {
740            WorkItem::Optimize(ref m) => m.kind,
741            WorkItem::CopyPostLtoArtifacts(_) | WorkItem::FatLto { .. } | WorkItem::ThinLto(_) => {
742                ModuleKind::Regular
743            }
744        }
745    }
746
747    /// Generate a short description of this work item suitable for use as a thread name.
748    fn short_description(&self) -> String {
749        // `pthread_setname()` on *nix ignores anything beyond the first 15
750        // bytes. Use short descriptions to maximize the space available for
751        // the module name.
752        #[cfg(not(windows))]
753        fn desc(short: &str, _long: &str, name: &str) -> String {
754            // The short label is three bytes, and is followed by a space. That
755            // leaves 11 bytes for the CGU name. How we obtain those 11 bytes
756            // depends on the CGU name form.
757            //
758            // - Non-incremental, e.g. `regex.f10ba03eb5ec7975-cgu.0`: the part
759            //   before the `-cgu.0` is the same for every CGU, so use the
760            //   `cgu.0` part. The number suffix will be different for each
761            //   CGU.
762            //
763            // - Incremental (normal), e.g. `2i52vvl2hco29us0`: use the whole
764            //   name because each CGU will have a unique ASCII hash, and the
765            //   first 11 bytes will be enough to identify it.
766            //
767            // - Incremental (with `-Zhuman-readable-cgu-names`), e.g.
768            //   `regex.f10ba03eb5ec7975-re_builder.volatile`: use the whole
769            //   name. The first 11 bytes won't be enough to uniquely identify
770            //   it, but no obvious substring will, and this is a rarely used
771            //   option so it doesn't matter much.
772            //
773            assert_eq!(short.len(), 3);
774            let name = if let Some(index) = name.find("-cgu.") {
775                &name[index + 1..] // +1 skips the leading '-'.
776            } else {
777                name
778            };
779            format!("{short} {name}")
780        }
781
782        // Windows has no thread name length limit, so use more descriptive names.
783        #[cfg(windows)]
784        fn desc(_short: &str, long: &str, name: &str) -> String {
785            format!("{long} {name}")
786        }
787
788        match self {
789            WorkItem::Optimize(m) => desc("opt", "optimize module", &m.name),
790            WorkItem::CopyPostLtoArtifacts(m) => desc("cpy", "copy LTO artifacts for", &m.name),
791            WorkItem::FatLto { .. } => desc("lto", "fat LTO module", "everything"),
792            WorkItem::ThinLto(m) => desc("lto", "thin-LTO module", m.name()),
793        }
794    }
795}
796
797/// A result produced by the backend.
798pub(crate) enum WorkItemResult<B: WriteBackendMethods> {
799    /// The backend has finished compiling a CGU, nothing more required.
800    Finished(CompiledModule),
801
802    /// The backend has finished compiling a CGU, which now needs to go through
803    /// fat LTO.
804    NeedsFatLto(FatLtoInput<B>),
805
806    /// The backend has finished compiling a CGU, which now needs to go through
807    /// thin LTO.
808    NeedsThinLto(String, B::ThinBuffer),
809}
810
811pub enum FatLtoInput<B: WriteBackendMethods> {
812    Serialized { name: String, buffer: SerializedModule<B::ModuleBuffer> },
813    InMemory(ModuleCodegen<B::Module>),
814}
815
816/// Actual LTO type we end up choosing based on multiple factors.
817pub(crate) enum ComputedLtoType {
818    No,
819    Thin,
820    Fat,
821}
822
823pub(crate) fn compute_per_cgu_lto_type(
824    sess_lto: &Lto,
825    opts: &config::Options,
826    sess_crate_types: &[CrateType],
827    module_kind: ModuleKind,
828) -> ComputedLtoType {
829    // If the linker does LTO, we don't have to do it. Note that we
830    // keep doing full LTO, if it is requested, as not to break the
831    // assumption that the output will be a single module.
832    let linker_does_lto = opts.cg.linker_plugin_lto.enabled();
833
834    // When we're automatically doing ThinLTO for multi-codegen-unit
835    // builds we don't actually want to LTO the allocator modules if
836    // it shows up. This is due to various linker shenanigans that
837    // we'll encounter later.
838    let is_allocator = module_kind == ModuleKind::Allocator;
839
840    // We ignore a request for full crate graph LTO if the crate type
841    // is only an rlib, as there is no full crate graph to process,
842    // that'll happen later.
843    //
844    // This use case currently comes up primarily for targets that
845    // require LTO so the request for LTO is always unconditionally
846    // passed down to the backend, but we don't actually want to do
847    // anything about it yet until we've got a final product.
848    let is_rlib = matches!(sess_crate_types, [CrateType::Rlib]);
849
850    match sess_lto {
851        Lto::ThinLocal if !linker_does_lto && !is_allocator => ComputedLtoType::Thin,
852        Lto::Thin if !linker_does_lto && !is_rlib => ComputedLtoType::Thin,
853        Lto::Fat if !is_rlib => ComputedLtoType::Fat,
854        _ => ComputedLtoType::No,
855    }
856}
857
858fn execute_optimize_work_item<B: ExtraBackendMethods>(
859    cgcx: &CodegenContext<B>,
860    mut module: ModuleCodegen<B::Module>,
861    module_config: &ModuleConfig,
862) -> Result<WorkItemResult<B>, FatalError> {
863    let dcx = cgcx.create_dcx();
864    let dcx = dcx.handle();
865
866    B::optimize(cgcx, dcx, &mut module, module_config)?;
867
868    // After we've done the initial round of optimizations we need to
869    // decide whether to synchronously codegen this module or ship it
870    // back to the coordinator thread for further LTO processing (which
871    // has to wait for all the initial modules to be optimized).
872
873    let lto_type = compute_per_cgu_lto_type(&cgcx.lto, &cgcx.opts, &cgcx.crate_types, module.kind);
874
875    // If we're doing some form of incremental LTO then we need to be sure to
876    // save our module to disk first.
877    let bitcode = if cgcx.config(module.kind).emit_pre_lto_bc {
878        let filename = pre_lto_bitcode_filename(&module.name);
879        cgcx.incr_comp_session_dir.as_ref().map(|path| path.join(&filename))
880    } else {
881        None
882    };
883
884    match lto_type {
885        ComputedLtoType::No => {
886            let module = B::codegen(cgcx, module, module_config)?;
887            Ok(WorkItemResult::Finished(module))
888        }
889        ComputedLtoType::Thin => {
890            let (name, thin_buffer) = B::prepare_thin(module, false);
891            if let Some(path) = bitcode {
892                fs::write(&path, thin_buffer.data()).unwrap_or_else(|e| {
893                    panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
894                });
895            }
896            Ok(WorkItemResult::NeedsThinLto(name, thin_buffer))
897        }
898        ComputedLtoType::Fat => match bitcode {
899            Some(path) => {
900                let (name, buffer) = B::serialize_module(module);
901                fs::write(&path, buffer.data()).unwrap_or_else(|e| {
902                    panic!("Error writing pre-lto-bitcode file `{}`: {}", path.display(), e);
903                });
904                Ok(WorkItemResult::NeedsFatLto(FatLtoInput::Serialized {
905                    name,
906                    buffer: SerializedModule::Local(buffer),
907                }))
908            }
909            None => Ok(WorkItemResult::NeedsFatLto(FatLtoInput::InMemory(module))),
910        },
911    }
912}
913
914fn execute_copy_from_cache_work_item<B: ExtraBackendMethods>(
915    cgcx: &CodegenContext<B>,
916    module: CachedModuleCodegen,
917    module_config: &ModuleConfig,
918) -> WorkItemResult<B> {
919    let incr_comp_session_dir = cgcx.incr_comp_session_dir.as_ref().unwrap();
920
921    let mut links_from_incr_cache = Vec::new();
922
923    let mut load_from_incr_comp_dir = |output_path: PathBuf, saved_path: &str| {
924        let source_file = in_incr_comp_dir(incr_comp_session_dir, saved_path);
925        debug!(
926            "copying preexisting module `{}` from {:?} to {}",
927            module.name,
928            source_file,
929            output_path.display()
930        );
931        match link_or_copy(&source_file, &output_path) {
932            Ok(_) => {
933                links_from_incr_cache.push(source_file);
934                Some(output_path)
935            }
936            Err(error) => {
937                cgcx.create_dcx().handle().emit_err(errors::CopyPathBuf {
938                    source_file,
939                    output_path,
940                    error,
941                });
942                None
943            }
944        }
945    };
946
947    let dwarf_object =
948        module.source.saved_files.get("dwo").as_ref().and_then(|saved_dwarf_object_file| {
949            let dwarf_obj_out = cgcx
950                .output_filenames
951                .split_dwarf_path(
952                    cgcx.split_debuginfo,
953                    cgcx.split_dwarf_kind,
954                    &module.name,
955                    cgcx.invocation_temp.as_deref(),
956                )
957                .expect(
958                    "saved dwarf object in work product but `split_dwarf_path` returned `None`",
959                );
960            load_from_incr_comp_dir(dwarf_obj_out, saved_dwarf_object_file)
961        });
962
963    let mut load_from_incr_cache = |perform, output_type: OutputType| {
964        if perform {
965            let saved_file = module.source.saved_files.get(output_type.extension())?;
966            let output_path = cgcx.output_filenames.temp_path_for_cgu(
967                output_type,
968                &module.name,
969                cgcx.invocation_temp.as_deref(),
970            );
971            load_from_incr_comp_dir(output_path, &saved_file)
972        } else {
973            None
974        }
975    };
976
977    let should_emit_obj = module_config.emit_obj != EmitObj::None;
978    let assembly = load_from_incr_cache(module_config.emit_asm, OutputType::Assembly);
979    let llvm_ir = load_from_incr_cache(module_config.emit_ir, OutputType::LlvmAssembly);
980    let bytecode = load_from_incr_cache(module_config.emit_bc, OutputType::Bitcode);
981    let object = load_from_incr_cache(should_emit_obj, OutputType::Object);
982    if should_emit_obj && object.is_none() {
983        cgcx.create_dcx().handle().emit_fatal(errors::NoSavedObjectFile { cgu_name: &module.name })
984    }
985
986    WorkItemResult::Finished(CompiledModule {
987        links_from_incr_cache,
988        name: module.name,
989        kind: ModuleKind::Regular,
990        object,
991        dwarf_object,
992        bytecode,
993        assembly,
994        llvm_ir,
995    })
996}
997
998fn execute_fat_lto_work_item<B: ExtraBackendMethods>(
999    cgcx: &CodegenContext<B>,
1000    exported_symbols_for_lto: &[String],
1001    each_linked_rlib_for_lto: &[PathBuf],
1002    mut needs_fat_lto: Vec<FatLtoInput<B>>,
1003    import_only_modules: Vec<(SerializedModule<B::ModuleBuffer>, WorkProduct)>,
1004    autodiff: Vec<AutoDiffItem>,
1005    module_config: &ModuleConfig,
1006) -> Result<WorkItemResult<B>, FatalError> {
1007    for (module, wp) in import_only_modules {
1008        needs_fat_lto.push(FatLtoInput::Serialized { name: wp.cgu_name, buffer: module })
1009    }
1010
1011    let module = B::run_and_optimize_fat_lto(
1012        cgcx,
1013        exported_symbols_for_lto,
1014        each_linked_rlib_for_lto,
1015        needs_fat_lto,
1016        autodiff,
1017    )?;
1018    let module = B::codegen(cgcx, module, module_config)?;
1019    Ok(WorkItemResult::Finished(module))
1020}
1021
1022fn execute_thin_lto_work_item<B: ExtraBackendMethods>(
1023    cgcx: &CodegenContext<B>,
1024    module: lto::ThinModule<B>,
1025    module_config: &ModuleConfig,
1026) -> Result<WorkItemResult<B>, FatalError> {
1027    let module = B::optimize_thin(cgcx, module)?;
1028    let module = B::codegen(cgcx, module, module_config)?;
1029    Ok(WorkItemResult::Finished(module))
1030}
1031
1032/// Messages sent to the coordinator.
1033pub(crate) enum Message<B: WriteBackendMethods> {
1034    /// A jobserver token has become available. Sent from the jobserver helper
1035    /// thread.
1036    Token(io::Result<Acquired>),
1037
1038    /// The backend has finished processing a work item for a codegen unit.
1039    /// Sent from a backend worker thread.
1040    WorkItem { result: Result<WorkItemResult<B>, Option<WorkerFatalError>> },
1041
1042    /// The frontend has finished generating something (backend IR or a
1043    /// post-LTO artifact) for a codegen unit, and it should be passed to the
1044    /// backend. Sent from the main thread.
1045    CodegenDone { llvm_work_item: WorkItem<B>, cost: u64 },
1046
1047    /// Similar to `CodegenDone`, but for reusing a pre-LTO artifact
1048    /// Sent from the main thread.
1049    AddImportOnlyModule {
1050        module_data: SerializedModule<B::ModuleBuffer>,
1051        work_product: WorkProduct,
1052    },
1053
1054    /// The frontend has finished generating everything for all codegen units.
1055    /// Sent from the main thread.
1056    CodegenComplete,
1057
1058    /// Some normal-ish compiler error occurred, and codegen should be wound
1059    /// down. Sent from the main thread.
1060    CodegenAborted,
1061}
1062
1063/// A message sent from the coordinator thread to the main thread telling it to
1064/// process another codegen unit.
1065pub struct CguMessage;
1066
1067// A cut-down version of `rustc_errors::DiagInner` that impls `Send`, which
1068// can be used to send diagnostics from codegen threads to the main thread.
1069// It's missing the following fields from `rustc_errors::DiagInner`.
1070// - `span`: it doesn't impl `Send`.
1071// - `suggestions`: it doesn't impl `Send`, and isn't used for codegen
1072//   diagnostics.
1073// - `sort_span`: it doesn't impl `Send`.
1074// - `is_lint`: lints aren't relevant during codegen.
1075// - `emitted_at`: not used for codegen diagnostics.
1076struct Diagnostic {
1077    level: Level,
1078    messages: Vec<(DiagMessage, Style)>,
1079    code: Option<ErrCode>,
1080    children: Vec<Subdiagnostic>,
1081    args: DiagArgMap,
1082}
1083
1084// A cut-down version of `rustc_errors::Subdiag` that impls `Send`. It's
1085// missing the following fields from `rustc_errors::Subdiag`.
1086// - `span`: it doesn't impl `Send`.
1087pub(crate) struct Subdiagnostic {
1088    level: Level,
1089    messages: Vec<(DiagMessage, Style)>,
1090}
1091
1092#[derive(PartialEq, Clone, Copy, Debug)]
1093enum MainThreadState {
1094    /// Doing nothing.
1095    Idle,
1096
1097    /// Doing codegen, i.e. MIR-to-LLVM-IR conversion.
1098    Codegenning,
1099
1100    /// Idle, but lending the compiler process's Token to an LLVM thread so it can do useful work.
1101    Lending,
1102}
1103
1104fn start_executing_work<B: ExtraBackendMethods>(
1105    backend: B,
1106    tcx: TyCtxt<'_>,
1107    crate_info: &CrateInfo,
1108    autodiff_items: &[AutoDiffItem],
1109    shared_emitter: SharedEmitter,
1110    codegen_worker_send: Sender<CguMessage>,
1111    coordinator_receive: Receiver<Message<B>>,
1112    regular_config: Arc<ModuleConfig>,
1113    allocator_config: Arc<ModuleConfig>,
1114    tx_to_llvm_workers: Sender<Message<B>>,
1115) -> thread::JoinHandle<Result<CompiledModules, ()>> {
1116    let coordinator_send = tx_to_llvm_workers;
1117    let sess = tcx.sess;
1118    let autodiff_items = autodiff_items.to_vec();
1119
1120    let mut each_linked_rlib_for_lto = Vec::new();
1121    let mut each_linked_rlib_file_for_lto = Vec::new();
1122    drop(link::each_linked_rlib(crate_info, None, &mut |cnum, path| {
1123        if link::ignored_for_lto(sess, crate_info, cnum) {
1124            return;
1125        }
1126        each_linked_rlib_for_lto.push(cnum);
1127        each_linked_rlib_file_for_lto.push(path.to_path_buf());
1128    }));
1129
1130    // Compute the set of symbols we need to retain when doing LTO (if we need to)
1131    let exported_symbols_for_lto =
1132        Arc::new(lto::exported_symbols_for_lto(tcx, &each_linked_rlib_for_lto));
1133
1134    // First up, convert our jobserver into a helper thread so we can use normal
1135    // mpsc channels to manage our messages and such.
1136    // After we've requested tokens then we'll, when we can,
1137    // get tokens on `coordinator_receive` which will
1138    // get managed in the main loop below.
1139    let coordinator_send2 = coordinator_send.clone();
1140    let helper = jobserver::client()
1141        .into_helper_thread(move |token| {
1142            drop(coordinator_send2.send(Message::Token::<B>(token)));
1143        })
1144        .expect("failed to spawn helper thread");
1145
1146    let ol =
1147        if tcx.sess.opts.unstable_opts.no_codegen || !tcx.sess.opts.output_types.should_codegen() {
1148            // If we know that we won’t be doing codegen, create target machines without optimisation.
1149            config::OptLevel::No
1150        } else {
1151            tcx.backend_optimization_level(())
1152        };
1153    let backend_features = tcx.global_backend_features(());
1154
1155    let remark_dir = if let Some(ref dir) = sess.opts.unstable_opts.remark_dir {
1156        let result = fs::create_dir_all(dir).and_then(|_| dir.canonicalize());
1157        match result {
1158            Ok(dir) => Some(dir),
1159            Err(error) => sess.dcx().emit_fatal(ErrorCreatingRemarkDir { error }),
1160        }
1161    } else {
1162        None
1163    };
1164
1165    let cgcx = CodegenContext::<B> {
1166        crate_types: tcx.crate_types().to_vec(),
1167        lto: sess.lto(),
1168        fewer_names: sess.fewer_names(),
1169        save_temps: sess.opts.cg.save_temps,
1170        time_trace: sess.opts.unstable_opts.llvm_time_trace,
1171        opts: Arc::new(sess.opts.clone()),
1172        prof: sess.prof.clone(),
1173        remark: sess.opts.cg.remark.clone(),
1174        remark_dir,
1175        incr_comp_session_dir: sess.incr_comp_session_dir_opt().map(|r| r.clone()),
1176        expanded_args: tcx.sess.expanded_args.clone(),
1177        diag_emitter: shared_emitter.clone(),
1178        output_filenames: Arc::clone(tcx.output_filenames(())),
1179        regular_module_config: regular_config,
1180        allocator_module_config: allocator_config,
1181        tm_factory: backend.target_machine_factory(tcx.sess, ol, backend_features),
1182        msvc_imps_needed: msvc_imps_needed(tcx),
1183        is_pe_coff: tcx.sess.target.is_like_windows,
1184        target_can_use_split_dwarf: tcx.sess.target_can_use_split_dwarf(),
1185        target_arch: tcx.sess.target.arch.to_string(),
1186        target_is_like_darwin: tcx.sess.target.is_like_darwin,
1187        target_is_like_aix: tcx.sess.target.is_like_aix,
1188        split_debuginfo: tcx.sess.split_debuginfo(),
1189        split_dwarf_kind: tcx.sess.opts.unstable_opts.split_dwarf_kind,
1190        parallel: backend.supports_parallel() && !sess.opts.unstable_opts.no_parallel_backend,
1191        pointer_size: tcx.data_layout.pointer_size(),
1192        invocation_temp: sess.invocation_temp.clone(),
1193    };
1194
1195    // This is the "main loop" of parallel work happening for parallel codegen.
1196    // It's here that we manage parallelism, schedule work, and work with
1197    // messages coming from clients.
1198    //
1199    // There are a few environmental pre-conditions that shape how the system
1200    // is set up:
1201    //
1202    // - Error reporting can only happen on the main thread because that's the
1203    //   only place where we have access to the compiler `Session`.
1204    // - LLVM work can be done on any thread.
1205    // - Codegen can only happen on the main thread.
1206    // - Each thread doing substantial work must be in possession of a `Token`
1207    //   from the `Jobserver`.
1208    // - The compiler process always holds one `Token`. Any additional `Tokens`
1209    //   have to be requested from the `Jobserver`.
1210    //
1211    // Error Reporting
1212    // ===============
1213    // The error reporting restriction is handled separately from the rest: We
1214    // set up a `SharedEmitter` that holds an open channel to the main thread.
1215    // When an error occurs on any thread, the shared emitter will send the
1216    // error message to the receiver main thread (`SharedEmitterMain`). The
1217    // main thread will periodically query this error message queue and emit
1218    // any error messages it has received. It might even abort compilation if
1219    // it has received a fatal error. In this case we rely on all other threads
1220    // being torn down automatically with the main thread.
1221    // Since the main thread will often be busy doing codegen work, error
1222    // reporting will be somewhat delayed, since the message queue can only be
1223    // checked in between two work packages.
1224    //
1225    // Work Processing Infrastructure
1226    // ==============================
1227    // The work processing infrastructure knows three major actors:
1228    //
1229    // - the coordinator thread,
1230    // - the main thread, and
1231    // - LLVM worker threads
1232    //
1233    // The coordinator thread is running a message loop. It instructs the main
1234    // thread about what work to do when, and it will spawn off LLVM worker
1235    // threads as open LLVM WorkItems become available.
1236    //
1237    // The job of the main thread is to codegen CGUs into LLVM work packages
1238    // (since the main thread is the only thread that can do this). The main
1239    // thread will block until it receives a message from the coordinator, upon
1240    // which it will codegen one CGU, send it to the coordinator and block
1241    // again. This way the coordinator can control what the main thread is
1242    // doing.
1243    //
1244    // The coordinator keeps a queue of LLVM WorkItems, and when a `Token` is
1245    // available, it will spawn off a new LLVM worker thread and let it process
1246    // a WorkItem. When a LLVM worker thread is done with its WorkItem,
1247    // it will just shut down, which also frees all resources associated with
1248    // the given LLVM module, and sends a message to the coordinator that the
1249    // WorkItem has been completed.
1250    //
1251    // Work Scheduling
1252    // ===============
1253    // The scheduler's goal is to minimize the time it takes to complete all
1254    // work there is, however, we also want to keep memory consumption low
1255    // if possible. These two goals are at odds with each other: If memory
1256    // consumption were not an issue, we could just let the main thread produce
1257    // LLVM WorkItems at full speed, assuring maximal utilization of
1258    // Tokens/LLVM worker threads. However, since codegen is usually faster
1259    // than LLVM processing, the queue of LLVM WorkItems would fill up and each
1260    // WorkItem potentially holds on to a substantial amount of memory.
1261    //
1262    // So the actual goal is to always produce just enough LLVM WorkItems as
1263    // not to starve our LLVM worker threads. That means, once we have enough
1264    // WorkItems in our queue, we can block the main thread, so it does not
1265    // produce more until we need them.
1266    //
1267    // Doing LLVM Work on the Main Thread
1268    // ----------------------------------
1269    // Since the main thread owns the compiler process's implicit `Token`, it is
1270    // wasteful to keep it blocked without doing any work. Therefore, what we do
1271    // in this case is: We spawn off an additional LLVM worker thread that helps
1272    // reduce the queue. The work it is doing corresponds to the implicit
1273    // `Token`. The coordinator will mark the main thread as being busy with
1274    // LLVM work. (The actual work happens on another OS thread but we just care
1275    // about `Tokens`, not actual threads).
1276    //
1277    // When any LLVM worker thread finishes while the main thread is marked as
1278    // "busy with LLVM work", we can do a little switcheroo: We give the Token
1279    // of the just finished thread to the LLVM worker thread that is working on
1280    // behalf of the main thread's implicit Token, thus freeing up the main
1281    // thread again. The coordinator can then again decide what the main thread
1282    // should do. This allows the coordinator to make decisions at more points
1283    // in time.
1284    //
1285    // Striking a Balance between Throughput and Memory Consumption
1286    // ------------------------------------------------------------
1287    // Since our two goals, (1) use as many Tokens as possible and (2) keep
1288    // memory consumption as low as possible, are in conflict with each other,
1289    // we have to find a trade off between them. Right now, the goal is to keep
1290    // all workers busy, which means that no worker should find the queue empty
1291    // when it is ready to start.
1292    // How do we do achieve this? Good question :) We actually never know how
1293    // many `Tokens` are potentially available so it's hard to say how much to
1294    // fill up the queue before switching the main thread to LLVM work. Also we
1295    // currently don't have a means to estimate how long a running LLVM worker
1296    // will still be busy with it's current WorkItem. However, we know the
1297    // maximal count of available Tokens that makes sense (=the number of CPU
1298    // cores), so we can take a conservative guess. The heuristic we use here
1299    // is implemented in the `queue_full_enough()` function.
1300    //
1301    // Some Background on Jobservers
1302    // -----------------------------
1303    // It's worth also touching on the management of parallelism here. We don't
1304    // want to just spawn a thread per work item because while that's optimal
1305    // parallelism it may overload a system with too many threads or violate our
1306    // configuration for the maximum amount of cpu to use for this process. To
1307    // manage this we use the `jobserver` crate.
1308    //
1309    // Job servers are an artifact of GNU make and are used to manage
1310    // parallelism between processes. A jobserver is a glorified IPC semaphore
1311    // basically. Whenever we want to run some work we acquire the semaphore,
1312    // and whenever we're done with that work we release the semaphore. In this
1313    // manner we can ensure that the maximum number of parallel workers is
1314    // capped at any one point in time.
1315    //
1316    // LTO and the coordinator thread
1317    // ------------------------------
1318    //
1319    // The final job the coordinator thread is responsible for is managing LTO
1320    // and how that works. When LTO is requested what we'll do is collect all
1321    // optimized LLVM modules into a local vector on the coordinator. Once all
1322    // modules have been codegened and optimized we hand this to the `lto`
1323    // module for further optimization. The `lto` module will return back a list
1324    // of more modules to work on, which the coordinator will continue to spawn
1325    // work for.
1326    //
1327    // Each LLVM module is automatically sent back to the coordinator for LTO if
1328    // necessary. There's already optimizations in place to avoid sending work
1329    // back to the coordinator if LTO isn't requested.
1330    return B::spawn_named_thread(cgcx.time_trace, "coordinator".to_string(), move || {
1331        // This is where we collect codegen units that have gone all the way
1332        // through codegen and LLVM.
1333        let mut compiled_modules = vec![];
1334        let mut compiled_allocator_module = None;
1335        let mut needs_fat_lto = Vec::new();
1336        let mut needs_thin_lto = Vec::new();
1337        let mut lto_import_only_modules = Vec::new();
1338        let mut started_lto = false;
1339
1340        /// Possible state transitions:
1341        /// - Ongoing -> Completed
1342        /// - Ongoing -> Aborted
1343        /// - Completed -> Aborted
1344        #[derive(Debug, PartialEq)]
1345        enum CodegenState {
1346            Ongoing,
1347            Completed,
1348            Aborted,
1349        }
1350        use CodegenState::*;
1351        let mut codegen_state = Ongoing;
1352
1353        // This is the queue of LLVM work items that still need processing.
1354        let mut work_items = Vec::<(WorkItem<B>, u64)>::new();
1355
1356        // This are the Jobserver Tokens we currently hold. Does not include
1357        // the implicit Token the compiler process owns no matter what.
1358        let mut tokens = Vec::new();
1359
1360        let mut main_thread_state = MainThreadState::Idle;
1361
1362        // How many LLVM worker threads are running while holding a Token. This
1363        // *excludes* any that the main thread is lending a Token to.
1364        let mut running_with_own_token = 0;
1365
1366        // How many LLVM worker threads are running in total. This *includes*
1367        // any that the main thread is lending a Token to.
1368        let running_with_any_token = |main_thread_state, running_with_own_token| {
1369            running_with_own_token
1370                + if main_thread_state == MainThreadState::Lending { 1 } else { 0 }
1371        };
1372
1373        let mut llvm_start_time: Option<VerboseTimingGuard<'_>> = None;
1374
1375        // Run the message loop while there's still anything that needs message
1376        // processing. Note that as soon as codegen is aborted we simply want to
1377        // wait for all existing work to finish, so many of the conditions here
1378        // only apply if codegen hasn't been aborted as they represent pending
1379        // work to be done.
1380        loop {
1381            // While there are still CGUs to be codegened, the coordinator has
1382            // to decide how to utilize the compiler processes implicit Token:
1383            // For codegenning more CGU or for running them through LLVM.
1384            if codegen_state == Ongoing {
1385                if main_thread_state == MainThreadState::Idle {
1386                    // Compute the number of workers that will be running once we've taken as many
1387                    // items from the work queue as we can, plus one for the main thread. It's not
1388                    // critically important that we use this instead of just
1389                    // `running_with_own_token`, but it prevents the `queue_full_enough` heuristic
1390                    // from fluctuating just because a worker finished up and we decreased the
1391                    // `running_with_own_token` count, even though we're just going to increase it
1392                    // right after this when we put a new worker to work.
1393                    let extra_tokens = tokens.len().checked_sub(running_with_own_token).unwrap();
1394                    let additional_running = std::cmp::min(extra_tokens, work_items.len());
1395                    let anticipated_running = running_with_own_token + additional_running + 1;
1396
1397                    if !queue_full_enough(work_items.len(), anticipated_running) {
1398                        // The queue is not full enough, process more codegen units:
1399                        if codegen_worker_send.send(CguMessage).is_err() {
1400                            panic!("Could not send CguMessage to main thread")
1401                        }
1402                        main_thread_state = MainThreadState::Codegenning;
1403                    } else {
1404                        // The queue is full enough to not let the worker
1405                        // threads starve. Use the implicit Token to do some
1406                        // LLVM work too.
1407                        let (item, _) =
1408                            work_items.pop().expect("queue empty - queue_full_enough() broken?");
1409                        main_thread_state = MainThreadState::Lending;
1410                        spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1411                    }
1412                }
1413            } else if codegen_state == Completed {
1414                if running_with_any_token(main_thread_state, running_with_own_token) == 0
1415                    && work_items.is_empty()
1416                {
1417                    // All codegen work is done. Do we have LTO work to do?
1418                    if needs_fat_lto.is_empty()
1419                        && needs_thin_lto.is_empty()
1420                        && lto_import_only_modules.is_empty()
1421                    {
1422                        // Nothing more to do!
1423                        break;
1424                    }
1425
1426                    // We have LTO work to do. Perform the serial work here of
1427                    // figuring out what we're going to LTO and then push a
1428                    // bunch of work items onto our queue to do LTO. This all
1429                    // happens on the coordinator thread but it's very quick so
1430                    // we don't worry about tokens.
1431                    assert!(!started_lto);
1432                    started_lto = true;
1433
1434                    let needs_fat_lto = mem::take(&mut needs_fat_lto);
1435                    let needs_thin_lto = mem::take(&mut needs_thin_lto);
1436                    let import_only_modules = mem::take(&mut lto_import_only_modules);
1437                    let each_linked_rlib_file_for_lto =
1438                        mem::take(&mut each_linked_rlib_file_for_lto);
1439
1440                    check_lto_allowed(&cgcx);
1441
1442                    if !needs_fat_lto.is_empty() {
1443                        assert!(needs_thin_lto.is_empty());
1444
1445                        work_items.push((
1446                            WorkItem::FatLto {
1447                                exported_symbols_for_lto: Arc::clone(&exported_symbols_for_lto),
1448                                each_linked_rlib_for_lto: each_linked_rlib_file_for_lto,
1449                                needs_fat_lto,
1450                                import_only_modules,
1451                                autodiff: autodiff_items.clone(),
1452                            },
1453                            0,
1454                        ));
1455                        if cgcx.parallel {
1456                            helper.request_token();
1457                        }
1458                    } else {
1459                        if !autodiff_items.is_empty() {
1460                            let dcx = cgcx.create_dcx();
1461                            dcx.handle().emit_fatal(AutodiffWithoutLto {});
1462                        }
1463
1464                        for (work, cost) in generate_thin_lto_work(
1465                            &cgcx,
1466                            &exported_symbols_for_lto,
1467                            &each_linked_rlib_file_for_lto,
1468                            needs_thin_lto,
1469                            import_only_modules,
1470                        ) {
1471                            let insertion_index = work_items
1472                                .binary_search_by_key(&cost, |&(_, cost)| cost)
1473                                .unwrap_or_else(|e| e);
1474                            work_items.insert(insertion_index, (work, cost));
1475                            if cgcx.parallel {
1476                                helper.request_token();
1477                            }
1478                        }
1479                    }
1480                }
1481
1482                // In this branch, we know that everything has been codegened,
1483                // so it's just a matter of determining whether the implicit
1484                // Token is free to use for LLVM work.
1485                match main_thread_state {
1486                    MainThreadState::Idle => {
1487                        if let Some((item, _)) = work_items.pop() {
1488                            main_thread_state = MainThreadState::Lending;
1489                            spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1490                        } else {
1491                            // There is no unstarted work, so let the main thread
1492                            // take over for a running worker. Otherwise the
1493                            // implicit token would just go to waste.
1494                            // We reduce the `running` counter by one. The
1495                            // `tokens.truncate()` below will take care of
1496                            // giving the Token back.
1497                            assert!(running_with_own_token > 0);
1498                            running_with_own_token -= 1;
1499                            main_thread_state = MainThreadState::Lending;
1500                        }
1501                    }
1502                    MainThreadState::Codegenning => bug!(
1503                        "codegen worker should not be codegenning after \
1504                              codegen was already completed"
1505                    ),
1506                    MainThreadState::Lending => {
1507                        // Already making good use of that token
1508                    }
1509                }
1510            } else {
1511                // Don't queue up any more work if codegen was aborted, we're
1512                // just waiting for our existing children to finish.
1513                assert!(codegen_state == Aborted);
1514                if running_with_any_token(main_thread_state, running_with_own_token) == 0 {
1515                    break;
1516                }
1517            }
1518
1519            // Spin up what work we can, only doing this while we've got available
1520            // parallelism slots and work left to spawn.
1521            if codegen_state != Aborted {
1522                while running_with_own_token < tokens.len()
1523                    && let Some((item, _)) = work_items.pop()
1524                {
1525                    spawn_work(&cgcx, coordinator_send.clone(), &mut llvm_start_time, item);
1526                    running_with_own_token += 1;
1527                }
1528            }
1529
1530            // Relinquish accidentally acquired extra tokens.
1531            tokens.truncate(running_with_own_token);
1532
1533            match coordinator_receive.recv().unwrap() {
1534                // Save the token locally and the next turn of the loop will use
1535                // this to spawn a new unit of work, or it may get dropped
1536                // immediately if we have no more work to spawn.
1537                Message::Token(token) => {
1538                    match token {
1539                        Ok(token) => {
1540                            tokens.push(token);
1541
1542                            if main_thread_state == MainThreadState::Lending {
1543                                // If the main thread token is used for LLVM work
1544                                // at the moment, we turn that thread into a regular
1545                                // LLVM worker thread, so the main thread is free
1546                                // to react to codegen demand.
1547                                main_thread_state = MainThreadState::Idle;
1548                                running_with_own_token += 1;
1549                            }
1550                        }
1551                        Err(e) => {
1552                            let msg = &format!("failed to acquire jobserver token: {e}");
1553                            shared_emitter.fatal(msg);
1554                            codegen_state = Aborted;
1555                        }
1556                    }
1557                }
1558
1559                Message::CodegenDone { llvm_work_item, cost } => {
1560                    // We keep the queue sorted by estimated processing cost,
1561                    // so that more expensive items are processed earlier. This
1562                    // is good for throughput as it gives the main thread more
1563                    // time to fill up the queue and it avoids scheduling
1564                    // expensive items to the end.
1565                    // Note, however, that this is not ideal for memory
1566                    // consumption, as LLVM module sizes are not evenly
1567                    // distributed.
1568                    let insertion_index = work_items.binary_search_by_key(&cost, |&(_, cost)| cost);
1569                    let insertion_index = match insertion_index {
1570                        Ok(idx) | Err(idx) => idx,
1571                    };
1572                    work_items.insert(insertion_index, (llvm_work_item, cost));
1573
1574                    if cgcx.parallel {
1575                        helper.request_token();
1576                    }
1577                    assert_eq!(main_thread_state, MainThreadState::Codegenning);
1578                    main_thread_state = MainThreadState::Idle;
1579                }
1580
1581                Message::CodegenComplete => {
1582                    if codegen_state != Aborted {
1583                        codegen_state = Completed;
1584                    }
1585                    assert_eq!(main_thread_state, MainThreadState::Codegenning);
1586                    main_thread_state = MainThreadState::Idle;
1587                }
1588
1589                // If codegen is aborted that means translation was aborted due
1590                // to some normal-ish compiler error. In this situation we want
1591                // to exit as soon as possible, but we want to make sure all
1592                // existing work has finished. Flag codegen as being done, and
1593                // then conditions above will ensure no more work is spawned but
1594                // we'll keep executing this loop until `running_with_own_token`
1595                // hits 0.
1596                Message::CodegenAborted => {
1597                    codegen_state = Aborted;
1598                }
1599
1600                Message::WorkItem { result } => {
1601                    // If a thread exits successfully then we drop a token associated
1602                    // with that worker and update our `running_with_own_token` count.
1603                    // We may later re-acquire a token to continue running more work.
1604                    // We may also not actually drop a token here if the worker was
1605                    // running with an "ephemeral token".
1606                    if main_thread_state == MainThreadState::Lending {
1607                        main_thread_state = MainThreadState::Idle;
1608                    } else {
1609                        running_with_own_token -= 1;
1610                    }
1611
1612                    match result {
1613                        Ok(WorkItemResult::Finished(compiled_module)) => {
1614                            match compiled_module.kind {
1615                                ModuleKind::Regular => {
1616                                    compiled_modules.push(compiled_module);
1617                                }
1618                                ModuleKind::Allocator => {
1619                                    assert!(compiled_allocator_module.is_none());
1620                                    compiled_allocator_module = Some(compiled_module);
1621                                }
1622                            }
1623                        }
1624                        Ok(WorkItemResult::NeedsFatLto(fat_lto_input)) => {
1625                            assert!(!started_lto);
1626                            assert!(needs_thin_lto.is_empty());
1627                            needs_fat_lto.push(fat_lto_input);
1628                        }
1629                        Ok(WorkItemResult::NeedsThinLto(name, thin_buffer)) => {
1630                            assert!(!started_lto);
1631                            assert!(needs_fat_lto.is_empty());
1632                            needs_thin_lto.push((name, thin_buffer));
1633                        }
1634                        Err(Some(WorkerFatalError)) => {
1635                            // Like `CodegenAborted`, wait for remaining work to finish.
1636                            codegen_state = Aborted;
1637                        }
1638                        Err(None) => {
1639                            // If the thread failed that means it panicked, so
1640                            // we abort immediately.
1641                            bug!("worker thread panicked");
1642                        }
1643                    }
1644                }
1645
1646                Message::AddImportOnlyModule { module_data, work_product } => {
1647                    assert!(!started_lto);
1648                    assert_eq!(codegen_state, Ongoing);
1649                    assert_eq!(main_thread_state, MainThreadState::Codegenning);
1650                    lto_import_only_modules.push((module_data, work_product));
1651                    main_thread_state = MainThreadState::Idle;
1652                }
1653            }
1654        }
1655
1656        if codegen_state == Aborted {
1657            return Err(());
1658        }
1659
1660        // Drop to print timings
1661        drop(llvm_start_time);
1662
1663        // Regardless of what order these modules completed in, report them to
1664        // the backend in the same order every time to ensure that we're handing
1665        // out deterministic results.
1666        compiled_modules.sort_by(|a, b| a.name.cmp(&b.name));
1667
1668        Ok(CompiledModules {
1669            modules: compiled_modules,
1670            allocator_module: compiled_allocator_module,
1671        })
1672    })
1673    .expect("failed to spawn coordinator thread");
1674
1675    // A heuristic that determines if we have enough LLVM WorkItems in the
1676    // queue so that the main thread can do LLVM work instead of codegen
1677    fn queue_full_enough(items_in_queue: usize, workers_running: usize) -> bool {
1678        // This heuristic scales ahead-of-time codegen according to available
1679        // concurrency, as measured by `workers_running`. The idea is that the
1680        // more concurrency we have available, the more demand there will be for
1681        // work items, and the fuller the queue should be kept to meet demand.
1682        // An important property of this approach is that we codegen ahead of
1683        // time only as much as necessary, so as to keep fewer LLVM modules in
1684        // memory at once, thereby reducing memory consumption.
1685        //
1686        // When the number of workers running is less than the max concurrency
1687        // available to us, this heuristic can cause us to instruct the main
1688        // thread to work on an LLVM item (that is, tell it to "LLVM") instead
1689        // of codegen, even though it seems like it *should* be codegenning so
1690        // that we can create more work items and spawn more LLVM workers.
1691        //
1692        // But this is not a problem. When the main thread is told to LLVM,
1693        // according to this heuristic and how work is scheduled, there is
1694        // always at least one item in the queue, and therefore at least one
1695        // pending jobserver token request. If there *is* more concurrency
1696        // available, we will immediately receive a token, which will upgrade
1697        // the main thread's LLVM worker to a real one (conceptually), and free
1698        // up the main thread to codegen if necessary. On the other hand, if
1699        // there isn't more concurrency, then the main thread working on an LLVM
1700        // item is appropriate, as long as the queue is full enough for demand.
1701        //
1702        // Speaking of which, how full should we keep the queue? Probably less
1703        // full than you'd think. A lot has to go wrong for the queue not to be
1704        // full enough and for that to have a negative effect on compile times.
1705        //
1706        // Workers are unlikely to finish at exactly the same time, so when one
1707        // finishes and takes another work item off the queue, we often have
1708        // ample time to codegen at that point before the next worker finishes.
1709        // But suppose that codegen takes so long that the workers exhaust the
1710        // queue, and we have one or more workers that have nothing to work on.
1711        // Well, it might not be so bad. Of all the LLVM modules we create and
1712        // optimize, one has to finish last. It's not necessarily the case that
1713        // by losing some concurrency for a moment, we delay the point at which
1714        // that last LLVM module is finished and the rest of compilation can
1715        // proceed. Also, when we can't take advantage of some concurrency, we
1716        // give tokens back to the job server. That enables some other rustc to
1717        // potentially make use of the available concurrency. That could even
1718        // *decrease* overall compile time if we're lucky. But yes, if no other
1719        // rustc can make use of the concurrency, then we've squandered it.
1720        //
1721        // However, keeping the queue full is also beneficial when we have a
1722        // surge in available concurrency. Then items can be taken from the
1723        // queue immediately, without having to wait for codegen.
1724        //
1725        // So, the heuristic below tries to keep one item in the queue for every
1726        // four running workers. Based on limited benchmarking, this appears to
1727        // be more than sufficient to avoid increasing compilation times.
1728        let quarter_of_workers = workers_running - 3 * workers_running / 4;
1729        items_in_queue > 0 && items_in_queue >= quarter_of_workers
1730    }
1731}
1732
1733/// `FatalError` is explicitly not `Send`.
1734#[must_use]
1735pub(crate) struct WorkerFatalError;
1736
1737fn spawn_work<'a, B: ExtraBackendMethods>(
1738    cgcx: &'a CodegenContext<B>,
1739    coordinator_send: Sender<Message<B>>,
1740    llvm_start_time: &mut Option<VerboseTimingGuard<'a>>,
1741    work: WorkItem<B>,
1742) {
1743    if cgcx.config(work.module_kind()).time_module && llvm_start_time.is_none() {
1744        *llvm_start_time = Some(cgcx.prof.verbose_generic_activity("LLVM_passes"));
1745    }
1746
1747    let cgcx = cgcx.clone();
1748
1749    B::spawn_named_thread(cgcx.time_trace, work.short_description(), move || {
1750        // Set up a destructor which will fire off a message that we're done as
1751        // we exit.
1752        struct Bomb<B: ExtraBackendMethods> {
1753            coordinator_send: Sender<Message<B>>,
1754            result: Option<Result<WorkItemResult<B>, FatalError>>,
1755        }
1756        impl<B: ExtraBackendMethods> Drop for Bomb<B> {
1757            fn drop(&mut self) {
1758                let msg = match self.result.take() {
1759                    Some(Ok(result)) => Message::WorkItem::<B> { result: Ok(result) },
1760                    Some(Err(FatalError)) => {
1761                        Message::WorkItem::<B> { result: Err(Some(WorkerFatalError)) }
1762                    }
1763                    None => Message::WorkItem::<B> { result: Err(None) },
1764                };
1765                drop(self.coordinator_send.send(msg));
1766            }
1767        }
1768
1769        let mut bomb = Bomb::<B> { coordinator_send, result: None };
1770
1771        // Execute the work itself, and if it finishes successfully then flag
1772        // ourselves as a success as well.
1773        //
1774        // Note that we ignore any `FatalError` coming out of `execute_work_item`,
1775        // as a diagnostic was already sent off to the main thread - just
1776        // surface that there was an error in this worker.
1777        bomb.result = {
1778            let module_config = cgcx.config(work.module_kind());
1779
1780            Some(match work {
1781                WorkItem::Optimize(m) => {
1782                    let _timer =
1783                        cgcx.prof.generic_activity_with_arg("codegen_module_optimize", &*m.name);
1784                    execute_optimize_work_item(&cgcx, m, module_config)
1785                }
1786                WorkItem::CopyPostLtoArtifacts(m) => {
1787                    let _timer = cgcx.prof.generic_activity_with_arg(
1788                        "codegen_copy_artifacts_from_incr_cache",
1789                        &*m.name,
1790                    );
1791                    Ok(execute_copy_from_cache_work_item(&cgcx, m, module_config))
1792                }
1793                WorkItem::FatLto {
1794                    exported_symbols_for_lto,
1795                    each_linked_rlib_for_lto,
1796                    needs_fat_lto,
1797                    import_only_modules,
1798                    autodiff,
1799                } => {
1800                    let _timer = cgcx
1801                        .prof
1802                        .generic_activity_with_arg("codegen_module_perform_lto", "everything");
1803                    execute_fat_lto_work_item(
1804                        &cgcx,
1805                        &exported_symbols_for_lto,
1806                        &each_linked_rlib_for_lto,
1807                        needs_fat_lto,
1808                        import_only_modules,
1809                        autodiff,
1810                        module_config,
1811                    )
1812                }
1813                WorkItem::ThinLto(m) => {
1814                    let _timer =
1815                        cgcx.prof.generic_activity_with_arg("codegen_module_perform_lto", m.name());
1816                    execute_thin_lto_work_item(&cgcx, m, module_config)
1817                }
1818            })
1819        };
1820    })
1821    .expect("failed to spawn work thread");
1822}
1823
1824enum SharedEmitterMessage {
1825    Diagnostic(Diagnostic),
1826    InlineAsmError(SpanData, String, Level, Option<(String, Vec<InnerSpan>)>),
1827    Fatal(String),
1828}
1829
1830#[derive(Clone)]
1831pub struct SharedEmitter {
1832    sender: Sender<SharedEmitterMessage>,
1833}
1834
1835pub struct SharedEmitterMain {
1836    receiver: Receiver<SharedEmitterMessage>,
1837}
1838
1839impl SharedEmitter {
1840    fn new() -> (SharedEmitter, SharedEmitterMain) {
1841        let (sender, receiver) = channel();
1842
1843        (SharedEmitter { sender }, SharedEmitterMain { receiver })
1844    }
1845
1846    pub fn inline_asm_error(
1847        &self,
1848        span: SpanData,
1849        msg: String,
1850        level: Level,
1851        source: Option<(String, Vec<InnerSpan>)>,
1852    ) {
1853        drop(self.sender.send(SharedEmitterMessage::InlineAsmError(span, msg, level, source)));
1854    }
1855
1856    fn fatal(&self, msg: &str) {
1857        drop(self.sender.send(SharedEmitterMessage::Fatal(msg.to_string())));
1858    }
1859}
1860
1861impl Emitter for SharedEmitter {
1862    fn emit_diagnostic(
1863        &mut self,
1864        mut diag: rustc_errors::DiagInner,
1865        _registry: &rustc_errors::registry::Registry,
1866    ) {
1867        // Check that we aren't missing anything interesting when converting to
1868        // the cut-down local `DiagInner`.
1869        assert_eq!(diag.span, MultiSpan::new());
1870        assert_eq!(diag.suggestions, Suggestions::Enabled(vec![]));
1871        assert_eq!(diag.sort_span, rustc_span::DUMMY_SP);
1872        assert_eq!(diag.is_lint, None);
1873        // No sensible check for `diag.emitted_at`.
1874
1875        let args = mem::replace(&mut diag.args, DiagArgMap::default());
1876        drop(
1877            self.sender.send(SharedEmitterMessage::Diagnostic(Diagnostic {
1878                level: diag.level(),
1879                messages: diag.messages,
1880                code: diag.code,
1881                children: diag
1882                    .children
1883                    .into_iter()
1884                    .map(|child| Subdiagnostic { level: child.level, messages: child.messages })
1885                    .collect(),
1886                args,
1887            })),
1888        );
1889    }
1890
1891    fn source_map(&self) -> Option<&SourceMap> {
1892        None
1893    }
1894
1895    fn translator(&self) -> &Translator {
1896        panic!("shared emitter attempted to translate a diagnostic");
1897    }
1898}
1899
1900impl SharedEmitterMain {
1901    fn check(&self, sess: &Session, blocking: bool) {
1902        loop {
1903            let message = if blocking {
1904                match self.receiver.recv() {
1905                    Ok(message) => Ok(message),
1906                    Err(_) => Err(()),
1907                }
1908            } else {
1909                match self.receiver.try_recv() {
1910                    Ok(message) => Ok(message),
1911                    Err(_) => Err(()),
1912                }
1913            };
1914
1915            match message {
1916                Ok(SharedEmitterMessage::Diagnostic(diag)) => {
1917                    // The diagnostic has been received on the main thread.
1918                    // Convert it back to a full `Diagnostic` and emit.
1919                    let dcx = sess.dcx();
1920                    let mut d =
1921                        rustc_errors::DiagInner::new_with_messages(diag.level, diag.messages);
1922                    d.code = diag.code; // may be `None`, that's ok
1923                    d.children = diag
1924                        .children
1925                        .into_iter()
1926                        .map(|sub| rustc_errors::Subdiag {
1927                            level: sub.level,
1928                            messages: sub.messages,
1929                            span: MultiSpan::new(),
1930                        })
1931                        .collect();
1932                    d.args = diag.args;
1933                    dcx.emit_diagnostic(d);
1934                    sess.dcx().abort_if_errors();
1935                }
1936                Ok(SharedEmitterMessage::InlineAsmError(span, msg, level, source)) => {
1937                    assert_matches!(level, Level::Error | Level::Warning | Level::Note);
1938                    let mut err = Diag::<()>::new(sess.dcx(), level, msg);
1939                    if !span.is_dummy() {
1940                        err.span(span.span());
1941                    }
1942
1943                    // Point to the generated assembly if it is available.
1944                    if let Some((buffer, spans)) = source {
1945                        let source = sess
1946                            .source_map()
1947                            .new_source_file(FileName::inline_asm_source_code(&buffer), buffer);
1948                        let spans: Vec<_> = spans
1949                            .iter()
1950                            .map(|sp| {
1951                                Span::with_root_ctxt(
1952                                    source.normalized_byte_pos(sp.start as u32),
1953                                    source.normalized_byte_pos(sp.end as u32),
1954                                )
1955                            })
1956                            .collect();
1957                        err.span_note(spans, "instantiated into assembly here");
1958                    }
1959
1960                    err.emit();
1961                }
1962                Ok(SharedEmitterMessage::Fatal(msg)) => {
1963                    sess.dcx().fatal(msg);
1964                }
1965                Err(_) => {
1966                    break;
1967                }
1968            }
1969        }
1970    }
1971}
1972
1973pub struct Coordinator<B: ExtraBackendMethods> {
1974    sender: Sender<Message<B>>,
1975    future: Option<thread::JoinHandle<Result<CompiledModules, ()>>>,
1976    // Only used for the Message type.
1977    phantom: PhantomData<B>,
1978}
1979
1980impl<B: ExtraBackendMethods> Coordinator<B> {
1981    fn join(mut self) -> std::thread::Result<Result<CompiledModules, ()>> {
1982        self.future.take().unwrap().join()
1983    }
1984}
1985
1986impl<B: ExtraBackendMethods> Drop for Coordinator<B> {
1987    fn drop(&mut self) {
1988        if let Some(future) = self.future.take() {
1989            // If we haven't joined yet, signal to the coordinator that it should spawn no more
1990            // work, and wait for worker threads to finish.
1991            drop(self.sender.send(Message::CodegenAborted::<B>));
1992            drop(future.join());
1993        }
1994    }
1995}
1996
1997pub struct OngoingCodegen<B: ExtraBackendMethods> {
1998    pub backend: B,
1999    pub crate_info: CrateInfo,
2000    pub codegen_worker_receive: Receiver<CguMessage>,
2001    pub shared_emitter_main: SharedEmitterMain,
2002    pub output_filenames: Arc<OutputFilenames>,
2003    pub coordinator: Coordinator<B>,
2004}
2005
2006impl<B: ExtraBackendMethods> OngoingCodegen<B> {
2007    pub fn join(self, sess: &Session) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
2008        self.shared_emitter_main.check(sess, true);
2009        let compiled_modules = sess.time("join_worker_thread", || match self.coordinator.join() {
2010            Ok(Ok(compiled_modules)) => compiled_modules,
2011            Ok(Err(())) => {
2012                sess.dcx().abort_if_errors();
2013                panic!("expected abort due to worker thread errors")
2014            }
2015            Err(_) => {
2016                bug!("panic during codegen/LLVM phase");
2017            }
2018        });
2019
2020        sess.dcx().abort_if_errors();
2021
2022        let work_products =
2023            copy_all_cgu_workproducts_to_incr_comp_cache_dir(sess, &compiled_modules);
2024        produce_final_output_artifacts(sess, &compiled_modules, &self.output_filenames);
2025
2026        // FIXME: time_llvm_passes support - does this use a global context or
2027        // something?
2028        if sess.codegen_units().as_usize() == 1 && sess.opts.unstable_opts.time_llvm_passes {
2029            self.backend.print_pass_timings()
2030        }
2031
2032        if sess.print_llvm_stats() {
2033            self.backend.print_statistics()
2034        }
2035
2036        (
2037            CodegenResults {
2038                crate_info: self.crate_info,
2039
2040                modules: compiled_modules.modules,
2041                allocator_module: compiled_modules.allocator_module,
2042            },
2043            work_products,
2044        )
2045    }
2046
2047    pub(crate) fn codegen_finished(&self, tcx: TyCtxt<'_>) {
2048        self.wait_for_signal_to_codegen_item();
2049        self.check_for_errors(tcx.sess);
2050        drop(self.coordinator.sender.send(Message::CodegenComplete::<B>));
2051    }
2052
2053    pub(crate) fn check_for_errors(&self, sess: &Session) {
2054        self.shared_emitter_main.check(sess, false);
2055    }
2056
2057    pub(crate) fn wait_for_signal_to_codegen_item(&self) {
2058        match self.codegen_worker_receive.recv() {
2059            Ok(CguMessage) => {
2060                // Ok to proceed.
2061            }
2062            Err(_) => {
2063                // One of the LLVM threads must have panicked, fall through so
2064                // error handling can be reached.
2065            }
2066        }
2067    }
2068}
2069
2070pub(crate) fn submit_codegened_module_to_llvm<B: ExtraBackendMethods>(
2071    coordinator: &Coordinator<B>,
2072    module: ModuleCodegen<B::Module>,
2073    cost: u64,
2074) {
2075    let llvm_work_item = WorkItem::Optimize(module);
2076    drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost }));
2077}
2078
2079pub(crate) fn submit_post_lto_module_to_llvm<B: ExtraBackendMethods>(
2080    coordinator: &Coordinator<B>,
2081    module: CachedModuleCodegen,
2082) {
2083    let llvm_work_item = WorkItem::CopyPostLtoArtifacts(module);
2084    drop(coordinator.sender.send(Message::CodegenDone::<B> { llvm_work_item, cost: 0 }));
2085}
2086
2087pub(crate) fn submit_pre_lto_module_to_llvm<B: ExtraBackendMethods>(
2088    tcx: TyCtxt<'_>,
2089    coordinator: &Coordinator<B>,
2090    module: CachedModuleCodegen,
2091) {
2092    let filename = pre_lto_bitcode_filename(&module.name);
2093    let bc_path = in_incr_comp_dir_sess(tcx.sess, &filename);
2094    let file = fs::File::open(&bc_path)
2095        .unwrap_or_else(|e| panic!("failed to open bitcode file `{}`: {}", bc_path.display(), e));
2096
2097    let mmap = unsafe {
2098        Mmap::map(file).unwrap_or_else(|e| {
2099            panic!("failed to mmap bitcode file `{}`: {}", bc_path.display(), e)
2100        })
2101    };
2102    // Schedule the module to be loaded
2103    drop(coordinator.sender.send(Message::AddImportOnlyModule::<B> {
2104        module_data: SerializedModule::FromUncompressedFile(mmap),
2105        work_product: module.source,
2106    }));
2107}
2108
2109fn pre_lto_bitcode_filename(module_name: &str) -> String {
2110    format!("{module_name}.{PRE_LTO_BC_EXT}")
2111}
2112
2113fn msvc_imps_needed(tcx: TyCtxt<'_>) -> bool {
2114    // This should never be true (because it's not supported). If it is true,
2115    // something is wrong with commandline arg validation.
2116    assert!(
2117        !(tcx.sess.opts.cg.linker_plugin_lto.enabled()
2118            && tcx.sess.target.is_like_windows
2119            && tcx.sess.opts.cg.prefer_dynamic)
2120    );
2121
2122    // We need to generate _imp__ symbol if we are generating an rlib or we include one
2123    // indirectly from ThinLTO. In theory these are not needed as ThinLTO could resolve
2124    // these, but it currently does not do so.
2125    let can_have_static_objects =
2126        tcx.sess.lto() == Lto::Thin || tcx.crate_types().contains(&CrateType::Rlib);
2127
2128    tcx.sess.target.is_like_windows &&
2129    can_have_static_objects   &&
2130    // ThinLTO can't handle this workaround in all cases, so we don't
2131    // emit the `__imp_` symbols. Instead we make them unnecessary by disallowing
2132    // dynamic linking when linker plugin LTO is enabled.
2133    !tcx.sess.opts.cg.linker_plugin_lto.enabled()
2134}