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