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