Skip to main content

rustc_codegen_ssa/back/
write.rs

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