rustc_codegen_ssa/back/
write.rs

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