Skip to main content

rustc_codegen_ssa/back/
write.rs

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