Skip to main content

rustc_codegen_ssa/back/
write.rs

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