rustc_codegen_ssa/back/
write.rs

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