Skip to main content

rustc_codegen_ssa/back/
write.rs

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