Skip to main content

rustc_codegen_ssa/back/
write.rs

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