rustc_codegen_ssa/back/
write.rs

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