Skip to main content

rustc_codegen_llvm/back/
lto.rs

1use std::collections::BTreeMap;
2use std::ffi::{CStr, CString};
3use std::fs::File;
4use std::path::{Path, PathBuf};
5use std::sync::Arc;
6use std::{io, iter, slice};
7
8use object::read::archive::ArchiveFile;
9use object::{Object, ObjectSection};
10use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule, ThinShared};
11use rustc_codegen_ssa::back::rmeta_link;
12use rustc_codegen_ssa::back::write::{
13    CodegenContext, FatLtoInput, SharedEmitter, TargetMachineFactoryFn, ThinLtoInput,
14};
15use rustc_codegen_ssa::traits::*;
16use rustc_codegen_ssa::{CompiledModule, ModuleCodegen, ModuleKind};
17use rustc_data_structures::fx::FxHashMap;
18use rustc_data_structures::memmap::Mmap;
19use rustc_data_structures::profiling::SelfProfilerRef;
20use rustc_errors::{DiagCtxt, DiagCtxtHandle};
21use rustc_hir::attrs::SanitizerSet;
22use rustc_middle::bug;
23use rustc_middle::dep_graph::WorkProduct;
24use rustc_session::config;
25use tracing::{debug, info};
26
27use crate::back::write::{
28    self, CodegenDiagnosticsStage, DiagnosticHandlers, bitcode_section_name, codegen,
29    save_temp_bitcode,
30};
31use crate::errors::{LlvmError, LtoBitcodeFromRlib};
32use crate::llvm::{self, build_string};
33use crate::{LlvmCodegenBackend, ModuleLlvm};
34
35/// We keep track of the computed LTO cache keys from the previous
36/// session to determine which CGUs we can reuse.
37const THIN_LTO_KEYS_INCR_COMP_FILE_NAME: &str = "thin-lto-past-keys.bin";
38
39fn prepare_lto(
40    cgcx: &CodegenContext,
41    exported_symbols_for_lto: &[String],
42    each_linked_rlib_for_lto: &[PathBuf],
43    dcx: DiagCtxtHandle<'_>,
44) -> (Vec<CString>, Vec<(SerializedModule<ModuleBuffer>, CString)>) {
45    let mut symbols_below_threshold = exported_symbols_for_lto
46        .iter()
47        .map(|symbol| CString::new(symbol.to_owned()).unwrap())
48        .collect::<Vec<CString>>();
49
50    if cgcx.module_config.instrument_coverage || cgcx.module_config.pgo_gen.enabled() {
51        // These are weak symbols that point to the profile version and the
52        // profile name, which need to be treated as exported so LTO doesn't nix
53        // them.
54        const PROFILER_WEAK_SYMBOLS: [&CStr; 2] =
55            [c"__llvm_profile_raw_version", c"__llvm_profile_filename"];
56
57        symbols_below_threshold.extend(PROFILER_WEAK_SYMBOLS.iter().map(|&sym| sym.to_owned()));
58    }
59
60    if cgcx.module_config.sanitizer.contains(SanitizerSet::MEMORY) {
61        let mut msan_weak_symbols = Vec::new();
62
63        // Similar to profiling, preserve weak msan symbol during LTO.
64        if cgcx.module_config.sanitizer_recover.contains(SanitizerSet::MEMORY) {
65            msan_weak_symbols.push(c"__msan_keep_going");
66        }
67
68        if cgcx.module_config.sanitizer_memory_track_origins != 0 {
69            msan_weak_symbols.push(c"__msan_track_origins");
70        }
71
72        symbols_below_threshold.extend(msan_weak_symbols.into_iter().map(|sym| sym.to_owned()));
73    }
74
75    // Preserve LLVM-injected, ASAN-related symbols.
76    // See also https://github.com/rust-lang/rust/issues/113404.
77    symbols_below_threshold.push(c"___asan_globals_registered".to_owned());
78
79    // __llvm_profile_counter_bias is pulled in at link time by an undefined reference to
80    // __llvm_profile_runtime, therefore we won't know until link time if this symbol
81    // should have default visibility.
82    symbols_below_threshold.push(c"__llvm_profile_counter_bias".to_owned());
83
84    // LTO seems to discard this otherwise under certain circumstances.
85    symbols_below_threshold.push(c"rust_eh_personality".to_owned());
86
87    // If we're performing LTO for the entire crate graph, then for each of our
88    // upstream dependencies, find the corresponding rlib and load the bitcode
89    // from the archive.
90    //
91    // We save off all the bytecode and LLVM module ids for later processing
92    // with either fat or thin LTO
93    let mut upstream_modules = Vec::new();
94    for path in each_linked_rlib_for_lto {
95        let archive_data = unsafe {
96            Mmap::map(std::fs::File::open(&path).expect("couldn't open rlib"))
97                .expect("couldn't map rlib")
98        };
99        let archive = ArchiveFile::parse(&*archive_data).expect("wanted an rlib");
100        let metadata_link = rmeta_link::read(&archive, &archive_data, &path).unwrap();
101        let obj_files = archive
102            .members()
103            .filter_map(|child| {
104                child
105                    .ok()
106                    .and_then(|c| std::str::from_utf8(c.name()).ok().map(|name| (name.trim(), c)))
107            })
108            .filter(|&(name, _)| metadata_link.rust_object_files.iter().any(|f| f == name));
109        for (name, child) in obj_files {
110            {
    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_llvm/src/back/lto.rs:110",
                        "rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
                        ::tracing_core::__macro_support::Option::Some(110u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::lto"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!("adding bitcode from {0}",
                                                    name) as &dyn Value))])
            });
    } else { ; }
};info!("adding bitcode from {}", name);
111            match get_bitcode_slice_from_object_data(
112                child.data(&*archive_data).expect("corrupt rlib"),
113                cgcx,
114            ) {
115                Ok(data) => {
116                    let module = SerializedModule::FromRlib(data.to_vec());
117                    upstream_modules.push((module, CString::new(name).unwrap()));
118                }
119                Err(e) => dcx.emit_fatal(e),
120            }
121        }
122    }
123
124    (symbols_below_threshold, upstream_modules)
125}
126
127fn get_bitcode_slice_from_object_data<'a>(
128    obj: &'a [u8],
129    cgcx: &CodegenContext,
130) -> Result<&'a [u8], LtoBitcodeFromRlib> {
131    // We're about to assume the data here is an object file with sections, but if it's raw LLVM IR
132    // that won't work. Fortunately, if that's what we have we can just return the object directly,
133    // so we sniff the relevant magic strings here and return.
134    if obj.starts_with(b"\xDE\xC0\x17\x0B") || obj.starts_with(b"BC\xC0\xDE") {
135        return Ok(obj);
136    }
137    // We drop the "__LLVM," prefix here because on Apple platforms there's a notion of "segment
138    // name" which in the public API for sections gets treated as part of the section name, but
139    // internally in MachOObjectFile.cpp gets treated separately.
140    let section_name = bitcode_section_name(cgcx).to_str().unwrap().trim_start_matches("__LLVM,");
141
142    let obj =
143        object::File::parse(obj).map_err(|err| LtoBitcodeFromRlib { err: err.to_string() })?;
144
145    let section = obj
146        .section_by_name(section_name)
147        .ok_or_else(|| LtoBitcodeFromRlib { err: ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("Can\'t find section {0}",
                section_name))
    })format!("Can't find section {section_name}") })?;
148
149    section.data().map_err(|err| LtoBitcodeFromRlib { err: err.to_string() })
150}
151
152/// Performs fat LTO by merging all modules into a single one and returning it
153/// for further optimization.
154pub(crate) fn run_fat(
155    cgcx: &CodegenContext,
156    prof: &SelfProfilerRef,
157    shared_emitter: &SharedEmitter,
158    tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
159    exported_symbols_for_lto: &[String],
160    each_linked_rlib_for_lto: &[PathBuf],
161    modules: Vec<FatLtoInput<LlvmCodegenBackend>>,
162) -> ModuleCodegen<ModuleLlvm> {
163    let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
164    let dcx = dcx.handle();
165    let (symbols_below_threshold, upstream_modules) =
166        prepare_lto(cgcx, exported_symbols_for_lto, each_linked_rlib_for_lto, dcx);
167    let symbols_below_threshold =
168        symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
169    fat_lto(
170        cgcx,
171        prof,
172        dcx,
173        shared_emitter,
174        tm_factory,
175        modules,
176        upstream_modules,
177        &symbols_below_threshold,
178    )
179}
180
181/// Performs thin LTO by performing necessary global analysis and returning two
182/// lists, one of the modules that need optimization and another for modules that
183/// can simply be copied over from the incr. comp. cache.
184pub(crate) fn run_thin(
185    cgcx: &CodegenContext,
186    prof: &SelfProfilerRef,
187    dcx: DiagCtxtHandle<'_>,
188    exported_symbols_for_lto: &[String],
189    each_linked_rlib_for_lto: &[PathBuf],
190    modules: Vec<ThinLtoInput<LlvmCodegenBackend>>,
191) -> (Vec<ThinModule<LlvmCodegenBackend>>, Vec<WorkProduct>) {
192    let (symbols_below_threshold, upstream_modules) =
193        prepare_lto(cgcx, exported_symbols_for_lto, each_linked_rlib_for_lto, dcx);
194    let symbols_below_threshold =
195        symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
196    if cgcx.use_linker_plugin_lto {
197        {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("We should never reach this case if the LTO step is deferred to the linker")));
};unreachable!(
198            "We should never reach this case if the LTO step \
199                      is deferred to the linker"
200        );
201    }
202    thin_lto(cgcx, prof, dcx, modules, upstream_modules, &symbols_below_threshold)
203}
204
205fn fat_lto(
206    cgcx: &CodegenContext,
207    prof: &SelfProfilerRef,
208    dcx: DiagCtxtHandle<'_>,
209    shared_emitter: &SharedEmitter,
210    tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
211    modules: Vec<FatLtoInput<LlvmCodegenBackend>>,
212    mut serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
213    symbols_below_threshold: &[*const libc::c_char],
214) -> ModuleCodegen<ModuleLlvm> {
215    let _timer = prof.generic_activity("LLVM_fat_lto_build_monolithic_module");
216    {
    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_llvm/src/back/lto.rs:216",
                        "rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
                        ::tracing_core::__macro_support::Option::Some(216u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::lto"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!("going for a fat lto")
                                            as &dyn Value))])
            });
    } else { ; }
};info!("going for a fat lto");
217
218    // Sort out all our lists of incoming modules into two lists.
219    //
220    // * `serialized_modules` (also and argument to this function) contains all
221    //   modules that are serialized in-memory.
222    // * `in_memory` contains modules which are already parsed and in-memory,
223    //   such as from multi-CGU builds.
224    let mut in_memory = Vec::new();
225    for module in modules {
226        match module {
227            FatLtoInput::InMemory(m) => in_memory.push(m),
228            FatLtoInput::Serialized { name, bitcode_path } => {
229                {
    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_llvm/src/back/lto.rs:229",
                        "rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
                        ::tracing_core::__macro_support::Option::Some(229u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::lto"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!("pushing serialized module {0:?}",
                                                    name) as &dyn Value))])
            });
    } else { ; }
};info!("pushing serialized module {:?}", name);
230                serialized_modules.push((
231                    SerializedModule::from_file(&bitcode_path),
232                    CString::new(name).unwrap(),
233                ));
234            }
235        }
236    }
237
238    // Find the "costliest" module and merge everything into that codegen unit.
239    // All the other modules will be serialized and reparsed into the new
240    // context, so this hopefully avoids serializing and parsing the largest
241    // codegen unit.
242    //
243    // Additionally use a regular module as the base here to ensure that various
244    // file copy operations in the backend work correctly. The only other kind
245    // of module here should be an allocator one, and if your crate is smaller
246    // than the allocator module then the size doesn't really matter anyway.
247    let costliest_module = in_memory
248        .iter()
249        .enumerate()
250        .filter(|&(_, module)| module.kind == ModuleKind::Regular)
251        .map(|(i, module)| {
252            let cost = unsafe { llvm::LLVMRustModuleCost(module.module_llvm.llmod()) };
253            (cost, i)
254        })
255        .max();
256
257    // If we found a costliest module, we're good to go. Otherwise all our
258    // inputs were serialized which could happen in the case, for example, that
259    // all our inputs were incrementally reread from the cache and we're just
260    // re-executing the LTO passes. If that's the case deserialize the first
261    // module and create a linker with it.
262    let module: ModuleCodegen<ModuleLlvm> = match costliest_module {
263        Some((_cost, i)) => in_memory.remove(i),
264        None => {
265            if !!serialized_modules.is_empty() {
    {
        ::core::panicking::panic_fmt(format_args!("must have at least one serialized module"));
    }
};assert!(!serialized_modules.is_empty(), "must have at least one serialized module");
266            let (buffer, name) = serialized_modules.remove(0);
267            {
    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_llvm/src/back/lto.rs:267",
                        "rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
                        ::tracing_core::__macro_support::Option::Some(267u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::lto"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!("no in-memory regular modules to choose from, parsing {0:?}",
                                                    name) as &dyn Value))])
            });
    } else { ; }
};info!("no in-memory regular modules to choose from, parsing {:?}", name);
268            let llvm_module = ModuleLlvm::parse(cgcx, tm_factory, &name, buffer.data(), dcx);
269            ModuleCodegen::new_regular(name.into_string().unwrap(), llvm_module)
270        }
271    };
272    {
273        let (llcx, llmod) = {
274            let llvm = &module.module_llvm;
275            (&llvm.llcx, llvm.llmod())
276        };
277        {
    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_llvm/src/back/lto.rs:277",
                        "rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
                        ::tracing_core::__macro_support::Option::Some(277u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::lto"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!("using {0:?} as a base module",
                                                    module.name) as &dyn Value))])
            });
    } else { ; }
};info!("using {:?} as a base module", module.name);
278
279        // The linking steps below may produce errors and diagnostics within LLVM
280        // which we'd like to handle and print, so set up our diagnostic handlers
281        // (which get unregistered when they go out of scope below).
282        let _handler = DiagnosticHandlers::new(
283            cgcx,
284            shared_emitter,
285            llcx,
286            &module,
287            CodegenDiagnosticsStage::LTO,
288        );
289
290        // For all other modules we codegened we'll need to link them into our own
291        // bitcode. All modules were codegened in their own LLVM context, however,
292        // and we want to move everything to the same LLVM context. Currently the
293        // way we know of to do that is to serialize them to a string and them parse
294        // them later. Not great but hey, that's why it's "fat" LTO, right?
295        for module in in_memory {
296            let buffer = ModuleBuffer::new(module.module_llvm.llmod(), false);
297            let llmod_id = CString::new(&module.name[..]).unwrap();
298            serialized_modules.push((SerializedModule::Local(buffer), llmod_id));
299        }
300        // Sort the modules to ensure we produce deterministic results.
301        serialized_modules.sort_by(|module1, module2| module1.1.cmp(&module2.1));
302
303        // For all serialized bitcode files we parse them and link them in as we did
304        // above, this is all mostly handled in C++.
305        let linker = unsafe { llvm::LLVMRustLinkerNew(llmod) };
306        for (bc_decoded, name) in serialized_modules {
307            let _timer = prof
308                .generic_activity_with_arg_recorder("LLVM_fat_lto_link_module", |recorder| {
309                    recorder.record_arg(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", name))
    })format!("{name:?}"))
310                });
311            {
    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_llvm/src/back/lto.rs:311",
                        "rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
                        ::tracing_core::__macro_support::Option::Some(311u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::lto"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!("linking {0:?}",
                                                    name) as &dyn Value))])
            });
    } else { ; }
};info!("linking {:?}", name);
312            let data = bc_decoded.data();
313
314            unsafe {
315                if !llvm::LLVMRustLinkerAdd(
316                    linker,
317                    data.as_ptr() as *const libc::c_char,
318                    data.len(),
319                ) {
320                    llvm::LLVMRustLinkerFree(linker);
321                    write::llvm_err(dcx, LlvmError::LoadBitcode { name })
322                }
323            }
324        }
325        unsafe { llvm::LLVMRustLinkerFree(linker) };
326        save_temp_bitcode(cgcx, &module, "lto.input");
327
328        // Internalize everything below threshold to help strip out more modules and such.
329        unsafe {
330            let ptr = symbols_below_threshold.as_ptr();
331            llvm::LLVMRustRunRestrictionPass(
332                llmod,
333                ptr as *const *const libc::c_char,
334                symbols_below_threshold.len() as libc::size_t,
335            );
336        }
337        save_temp_bitcode(cgcx, &module, "lto.after-restriction");
338    }
339
340    module
341}
342
343/// Prepare "thin" LTO to get run on these modules.
344///
345/// The general structure of ThinLTO is quite different from the structure of
346/// "fat" LTO above. With "fat" LTO all LLVM modules in question are merged into
347/// one giant LLVM module, and then we run more optimization passes over this
348/// big module after internalizing most symbols. Thin LTO, on the other hand,
349/// avoid this large bottleneck through more targeted optimization.
350///
351/// At a high level Thin LTO looks like:
352///
353///    1. Prepare a "summary" of each LLVM module in question which describes
354///       the values inside, cost of the values, etc.
355///    2. Merge the summaries of all modules in question into one "index"
356///    3. Perform some global analysis on this index
357///    4. For each module, use the index and analysis calculated previously to
358///       perform local transformations on the module, for example inlining
359///       small functions from other modules.
360///    5. Run thin-specific optimization passes over each module, and then code
361///       generate everything at the end.
362///
363/// The summary for each module is intended to be quite cheap, and the global
364/// index is relatively quite cheap to create as well. As a result, the goal of
365/// ThinLTO is to reduce the bottleneck on LTO and enable LTO to be used in more
366/// situations. For example one cheap optimization is that we can parallelize
367/// all codegen modules, easily making use of all the cores on a machine.
368///
369/// With all that in mind, the function here is designed at specifically just
370/// calculating the *index* for ThinLTO. This index will then be shared amongst
371/// all of the `LtoModuleCodegen` units returned below and destroyed once
372/// they all go out of scope.
373fn thin_lto(
374    cgcx: &CodegenContext,
375    prof: &SelfProfilerRef,
376    dcx: DiagCtxtHandle<'_>,
377    modules: Vec<ThinLtoInput<LlvmCodegenBackend>>,
378    serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
379    symbols_below_threshold: &[*const libc::c_char],
380) -> (Vec<ThinModule<LlvmCodegenBackend>>, Vec<WorkProduct>) {
381    let _timer = prof.generic_activity("LLVM_thin_lto_global_analysis");
382    unsafe {
383        {
    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_llvm/src/back/lto.rs:383",
                        "rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
                        ::tracing_core::__macro_support::Option::Some(383u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::lto"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!("going for that thin, thin LTO")
                                            as &dyn Value))])
            });
    } else { ; }
};info!("going for that thin, thin LTO");
384
385        let green_modules: FxHashMap<_, _> = modules
386            .iter()
387            .filter_map(|module| {
388                if let ThinLtoInput::Green { wp, .. } = module {
389                    Some((wp.cgu_name.clone(), wp.clone()))
390                } else {
391                    None
392                }
393            })
394            .collect();
395
396        let full_scope_len = modules.len();
397        let mut thin_buffers = Vec::with_capacity(modules.len());
398        let mut module_names = Vec::with_capacity(full_scope_len);
399        let mut thin_modules = Vec::with_capacity(full_scope_len);
400
401        for (i, module) in modules.into_iter().enumerate() {
402            let (name, buffer) = match module {
403                ThinLtoInput::Red { name, buffer } => (name, buffer),
404                ThinLtoInput::Green { wp, bitcode_path } => {
405                    (wp.cgu_name, SerializedModule::from_file(&bitcode_path))
406                }
407            };
408            {
    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_llvm/src/back/lto.rs:408",
                        "rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
                        ::tracing_core::__macro_support::Option::Some(408u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::lto"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!("local module: {0} - {1}",
                                                    i, name) as &dyn Value))])
            });
    } else { ; }
};info!("local module: {} - {}", i, name);
409            let cname = CString::new(name.as_bytes()).unwrap();
410            thin_modules.push(llvm::ThinLTOModule {
411                identifier: cname.as_ptr(),
412                data: buffer.data().as_ptr(),
413                len: buffer.data().len(),
414            });
415            thin_buffers.push(buffer);
416            module_names.push(cname);
417        }
418
419        // FIXME: All upstream crates are deserialized internally in the
420        //        function below to extract their summary and modules. Note that
421        //        unlike the loop above we *must* decode and/or read something
422        //        here as these are all just serialized files on disk. An
423        //        improvement, however, to make here would be to store the
424        //        module summary separately from the actual module itself. Right
425        //        now this is store in one large bitcode file, and the entire
426        //        file is deflate-compressed. We could try to bypass some of the
427        //        decompression by storing the index uncompressed and only
428        //        lazily decompressing the bytecode if necessary.
429        //
430        //        Note that truly taking advantage of this optimization will
431        //        likely be further down the road. We'd have to implement
432        //        incremental ThinLTO first where we could actually avoid
433        //        looking at upstream modules entirely sometimes (the contents,
434        //        we must always unconditionally look at the index).
435
436        for (module, name) in serialized_modules {
437            {
    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_llvm/src/back/lto.rs:437",
                        "rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
                        ::tracing_core::__macro_support::Option::Some(437u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::lto"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!("upstream module {0:?}",
                                                    name) as &dyn Value))])
            });
    } else { ; }
};info!("upstream module {:?}", name);
438            thin_modules.push(llvm::ThinLTOModule {
439                identifier: name.as_ptr(),
440                data: module.data().as_ptr(),
441                len: module.data().len(),
442            });
443            thin_buffers.push(module);
444            module_names.push(name);
445        }
446
447        // Sanity check
448        match (&thin_modules.len(), &module_names.len()) {
    (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!(thin_modules.len(), module_names.len());
449
450        // Delegate to the C++ bindings to create some data here. Once this is a
451        // tried-and-true interface we may wish to try to upstream some of this
452        // to LLVM itself, right now we reimplement a lot of what they do
453        // upstream...
454        let data = llvm::LLVMRustCreateThinLTOData(
455            thin_modules.as_ptr(),
456            thin_modules.len(),
457            symbols_below_threshold.as_ptr(),
458            symbols_below_threshold.len(),
459        )
460        .unwrap_or_else(|| write::llvm_err(dcx, LlvmError::PrepareThinLtoContext));
461
462        let data = ThinData(data);
463
464        {
    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_llvm/src/back/lto.rs:464",
                        "rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
                        ::tracing_core::__macro_support::Option::Some(464u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::lto"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!("thin LTO data created")
                                            as &dyn Value))])
            });
    } else { ; }
};info!("thin LTO data created");
465
466        let (key_map_path, prev_key_map, curr_key_map) = if let Some(ref incr_comp_session_dir) =
467            cgcx.incr_comp_session_dir
468        {
469            let path = incr_comp_session_dir.join(THIN_LTO_KEYS_INCR_COMP_FILE_NAME);
470            // If the previous file was deleted, or we get an IO error
471            // reading the file, then we'll just use `None` as the
472            // prev_key_map, which will force the code to be recompiled.
473            let prev =
474                if path.exists() { ThinLTOKeysMap::load_from_file(&path).ok() } else { None };
475            let curr = ThinLTOKeysMap::from_thin_lto_modules(&data, &thin_modules, &module_names);
476            (Some(path), prev, curr)
477        } else {
478            // If we don't compile incrementally, we don't need to load the
479            // import data from LLVM.
480            if !green_modules.is_empty() {
    ::core::panicking::panic("assertion failed: green_modules.is_empty()")
};assert!(green_modules.is_empty());
481            let curr = ThinLTOKeysMap::default();
482            (None, None, curr)
483        };
484        {
    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_llvm/src/back/lto.rs:484",
                        "rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
                        ::tracing_core::__macro_support::Option::Some(484u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::lto"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!("thin LTO cache key map loaded")
                                            as &dyn Value))])
            });
    } else { ; }
};info!("thin LTO cache key map loaded");
485        {
    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_llvm/src/back/lto.rs:485",
                        "rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
                        ::tracing_core::__macro_support::Option::Some(485u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::lto"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!("prev_key_map: {0:#?}",
                                                    prev_key_map) as &dyn Value))])
            });
    } else { ; }
};info!("prev_key_map: {:#?}", prev_key_map);
486        {
    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_llvm/src/back/lto.rs:486",
                        "rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
                        ::tracing_core::__macro_support::Option::Some(486u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::lto"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!("curr_key_map: {0:#?}",
                                                    curr_key_map) as &dyn Value))])
            });
    } else { ; }
};info!("curr_key_map: {:#?}", curr_key_map);
487
488        // Throw our data in an `Arc` as we'll be sharing it across threads. We
489        // also put all memory referenced by the C++ data (buffers, ids, etc)
490        // into the arc as well. After this we'll create a thin module
491        // codegen per module in this data.
492        let shared = Arc::new(ThinShared { data, modules: thin_buffers, module_names });
493
494        let mut copy_jobs = ::alloc::vec::Vec::new()vec![];
495        let mut opt_jobs = ::alloc::vec::Vec::new()vec![];
496
497        {
    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_llvm/src/back/lto.rs:497",
                        "rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
                        ::tracing_core::__macro_support::Option::Some(497u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::lto"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!("checking which modules can be-reused and which have to be re-optimized.")
                                            as &dyn Value))])
            });
    } else { ; }
};info!("checking which modules can be-reused and which have to be re-optimized.");
498        for (module_index, module_name) in shared.module_names.iter().enumerate() {
499            let module_name = module_name_to_str(module_name);
500            if let (Some(prev_key_map), true) =
501                (prev_key_map.as_ref(), green_modules.contains_key(module_name))
502            {
503                if !cgcx.incr_comp_session_dir.is_some() {
    ::core::panicking::panic("assertion failed: cgcx.incr_comp_session_dir.is_some()")
};assert!(cgcx.incr_comp_session_dir.is_some());
504
505                // If a module exists in both the current and the previous session,
506                // and has the same LTO cache key in both sessions, then we can re-use it
507                if prev_key_map.keys.get(module_name) == curr_key_map.keys.get(module_name) {
508                    let work_product = green_modules[module_name].clone();
509                    copy_jobs.push(work_product);
510                    {
    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_llvm/src/back/lto.rs:510",
                        "rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
                        ::tracing_core::__macro_support::Option::Some(510u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::lto"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!(" - {0}: re-used",
                                                    module_name) as &dyn Value))])
            });
    } else { ; }
};info!(" - {}: re-used", module_name);
511                    if !cgcx.incr_comp_session_dir.is_some() {
    ::core::panicking::panic("assertion failed: cgcx.incr_comp_session_dir.is_some()")
};assert!(cgcx.incr_comp_session_dir.is_some());
512                    continue;
513                }
514            }
515
516            {
    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_llvm/src/back/lto.rs:516",
                        "rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
                        ::tracing_core::__macro_support::Option::Some(516u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::lto"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!(" - {0}: re-compiled",
                                                    module_name) as &dyn Value))])
            });
    } else { ; }
};info!(" - {}: re-compiled", module_name);
517            opt_jobs.push(ThinModule { shared: Arc::clone(&shared), idx: module_index });
518        }
519
520        // Save the current ThinLTO import information for the next compilation
521        // session, overwriting the previous serialized data (if any).
522        if let Some(path) = key_map_path
523            && let Err(err) = curr_key_map.save_to_file(&path)
524        {
525            write::llvm_err(dcx, LlvmError::WriteThinLtoKey { err });
526        }
527
528        (opt_jobs, copy_jobs)
529    }
530}
531
532pub(crate) fn enable_autodiff_settings(ad: &[config::AutoDiff]) {
533    let mut enzyme = llvm::EnzymeWrapper::get_instance();
534
535    for val in ad {
536        // We intentionally don't use a wildcard, to not forget handling anything new.
537        match val {
538            config::AutoDiff::PrintPerf => {
539                enzyme.set_print_perf(true);
540            }
541            config::AutoDiff::PrintAA => {
542                enzyme.set_print_activity(true);
543            }
544            config::AutoDiff::PrintTA => {
545                enzyme.set_print_type(true);
546            }
547            config::AutoDiff::PrintTAFn(fun) => {
548                enzyme.set_print_type(true); // Enable general type printing
549                enzyme.set_print_type_fun(&fun); // Set specific function to analyze
550            }
551            config::AutoDiff::Inline => {
552                enzyme.set_inline(true);
553            }
554            config::AutoDiff::LooseTypes => {
555                enzyme.set_loose_types(true);
556            }
557            config::AutoDiff::PrintSteps => {
558                enzyme.set_print(true);
559            }
560            // We handle this in the PassWrapper.cpp
561            config::AutoDiff::PrintPasses => {}
562            // We handle this in the PassWrapper.cpp
563            config::AutoDiff::PrintModBefore => {}
564            // We handle this in the PassWrapper.cpp
565            config::AutoDiff::PrintModAfter => {}
566            // We handle this in the PassWrapper.cpp
567            config::AutoDiff::PrintModFinal => {}
568            // This is required and already checked
569            config::AutoDiff::Enable => {}
570            // We handle this below
571            config::AutoDiff::NoPostopt => {}
572            // Disables TypeTree generation
573            config::AutoDiff::NoTT => {}
574        }
575    }
576    // This helps with handling enums for now.
577    enzyme.set_strict_aliasing(false);
578    // FIXME(ZuseZ4): Test this, since it was added a long time ago.
579    enzyme.set_rust_rules(true);
580}
581
582pub(crate) fn run_pass_manager(
583    cgcx: &CodegenContext,
584    prof: &SelfProfilerRef,
585    dcx: DiagCtxtHandle<'_>,
586    module: &mut ModuleCodegen<ModuleLlvm>,
587    thin: bool,
588) {
589    let _timer = prof.generic_activity_with_arg("LLVM_lto_optimize", &*module.name);
590    let config = &cgcx.module_config;
591
592    // Now we have one massive module inside of llmod. Time to run the
593    // LTO-specific optimization passes that LLVM provides.
594    //
595    // This code is based off the code found in llvm's LTO code generator:
596    //      llvm/lib/LTO/LTOCodeGenerator.cpp
597    {
    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_llvm/src/back/lto.rs:597",
                        "rustc_codegen_llvm::back::lto", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
                        ::tracing_core::__macro_support::Option::Some(597u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::lto"),
                        ::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!("running the pass manager")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("running the pass manager");
598    let opt_stage = if thin { llvm::OptStage::ThinLTO } else { llvm::OptStage::FatLTO };
599    let opt_level = config.opt_level.unwrap_or(config::OptLevel::No);
600
601    // The PostAD behavior is the same that we would have if no autodiff was used.
602    // It will run the default optimization pipeline. If AD is enabled we select
603    // the DuringAD stage, which will disable vectorization and loop unrolling, and
604    // schedule two autodiff optimization + differentiation passes.
605    // We then run the llvm_optimize function a second time, to optimize the code which we generated
606    // in the enzyme differentiation pass.
607    let enable_ad = config.autodiff.contains(&config::AutoDiff::Enable);
608    let stage = if thin {
609        write::AutodiffStage::PreAD
610    } else {
611        if enable_ad { write::AutodiffStage::DuringAD } else { write::AutodiffStage::PostAD }
612    };
613
614    unsafe {
615        write::llvm_optimize(
616            cgcx, prof, dcx, module, None, None, config, opt_level, opt_stage, stage,
617        );
618    }
619
620    if falsecfg!(feature = "llvm_enzyme") && enable_ad && !thin {
621        let opt_stage = llvm::OptStage::FatLTO;
622        let stage = write::AutodiffStage::PostAD;
623        if !config.autodiff.contains(&config::AutoDiff::NoPostopt) {
624            unsafe {
625                write::llvm_optimize(
626                    cgcx, prof, dcx, module, None, None, config, opt_level, opt_stage, stage,
627                );
628            }
629        }
630
631        // This is the final IR, so people should be able to inspect the optimized autodiff output,
632        // for manual inspection.
633        if config.autodiff.contains(&config::AutoDiff::PrintModFinal) {
634            unsafe { llvm::LLVMDumpModule(module.module_llvm.llmod()) };
635        }
636    }
637
638    {
    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_llvm/src/back/lto.rs:638",
                        "rustc_codegen_llvm::back::lto", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
                        ::tracing_core::__macro_support::Option::Some(638u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::lto"),
                        ::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!("lto done")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("lto done");
639}
640
641#[repr(transparent)]
642pub(crate) struct Buffer(&'static mut llvm::Buffer);
643
644unsafe impl Send for Buffer {}
645unsafe impl Sync for Buffer {}
646
647impl Buffer {
648    pub(crate) fn data(&self) -> &[u8] {
649        unsafe {
650            let ptr = llvm::LLVMRustBufferPtr(self.0);
651            let len = llvm::LLVMRustBufferLen(self.0);
652            slice::from_raw_parts(ptr, len)
653        }
654    }
655}
656
657impl Drop for Buffer {
658    fn drop(&mut self) {
659        unsafe {
660            llvm::LLVMRustBufferFree(&mut *(self.0 as *mut _));
661        }
662    }
663}
664
665pub struct ThinData(&'static mut llvm::ThinLTOData);
666
667unsafe impl Send for ThinData {}
668unsafe impl Sync for ThinData {}
669
670impl Drop for ThinData {
671    fn drop(&mut self) {
672        unsafe {
673            llvm::LLVMRustFreeThinLTOData(&mut *(self.0 as *mut _));
674        }
675    }
676}
677
678pub struct ModuleBuffer {
679    data: Buffer,
680}
681
682impl ModuleBuffer {
683    pub(crate) fn new(m: &llvm::Module, is_thin: bool) -> ModuleBuffer {
684        unsafe {
685            let buffer = llvm::LLVMRustModuleSerialize(m, is_thin);
686            ModuleBuffer { data: Buffer(buffer) }
687        }
688    }
689}
690
691impl ModuleBufferMethods for ModuleBuffer {
692    fn data(&self) -> &[u8] {
693        self.data.data()
694    }
695}
696
697pub(crate) fn optimize_and_codegen_thin_module(
698    cgcx: &CodegenContext,
699    prof: &SelfProfilerRef,
700    shared_emitter: &SharedEmitter,
701    tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
702    thin_module: ThinModule<LlvmCodegenBackend>,
703) -> CompiledModule {
704    let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
705    let dcx = dcx.handle();
706
707    let module_name = &thin_module.shared.module_names[thin_module.idx];
708
709    // Right now the implementation we've got only works over serialized
710    // modules, so we create a fresh new LLVM context and parse the module
711    // into that context. One day, however, we may do this for upstream
712    // crates but for locally codegened modules we may be able to reuse
713    // that LLVM Context and Module.
714    let module_llvm = ModuleLlvm::parse(cgcx, tm_factory, module_name, thin_module.data(), dcx);
715    let mut module = ModuleCodegen::new_regular(thin_module.name(), module_llvm);
716    // Given that the newly created module lacks a thinlto buffer for embedding, we need to re-add it here.
717    if cgcx.module_config.embed_bitcode() {
718        module.thin_lto_buffer = Some(thin_module.data().to_vec());
719    }
720    {
721        let target = &*module.module_llvm.tm;
722        let llmod = module.module_llvm.llmod();
723        save_temp_bitcode(cgcx, &module, "thin-lto-input");
724
725        // Up next comes the per-module local analyses that we do for Thin LTO.
726        // Each of these functions is basically copied from the LLVM
727        // implementation and then tailored to suit this implementation. Ideally
728        // each of these would be supported by upstream LLVM but that's perhaps
729        // a patch for another day!
730        //
731        // You can find some more comments about these functions in the LLVM
732        // bindings we've got (currently `PassWrapper.cpp`)
733        {
734            let _timer = prof.generic_activity_with_arg("LLVM_thin_lto_rename", thin_module.name());
735            unsafe {
736                llvm::LLVMRustPrepareThinLTORename(thin_module.shared.data.0, llmod, target.raw())
737            };
738            save_temp_bitcode(cgcx, &module, "thin-lto-after-rename");
739        }
740
741        {
742            let _timer =
743                prof.generic_activity_with_arg("LLVM_thin_lto_resolve_weak", thin_module.name());
744            if unsafe { !llvm::LLVMRustPrepareThinLTOResolveWeak(thin_module.shared.data.0, llmod) }
745            {
746                write::llvm_err(dcx, LlvmError::PrepareThinLtoModule);
747            }
748            save_temp_bitcode(cgcx, &module, "thin-lto-after-resolve");
749        }
750
751        {
752            let _timer =
753                prof.generic_activity_with_arg("LLVM_thin_lto_internalize", thin_module.name());
754            if unsafe { !llvm::LLVMRustPrepareThinLTOInternalize(thin_module.shared.data.0, llmod) }
755            {
756                write::llvm_err(dcx, LlvmError::PrepareThinLtoModule);
757            }
758            save_temp_bitcode(cgcx, &module, "thin-lto-after-internalize");
759        }
760
761        {
762            let _timer = prof.generic_activity_with_arg("LLVM_thin_lto_import", thin_module.name());
763            if unsafe {
764                !llvm::LLVMRustPrepareThinLTOImport(thin_module.shared.data.0, llmod, target.raw())
765            } {
766                write::llvm_err(dcx, LlvmError::PrepareThinLtoModule);
767            }
768            save_temp_bitcode(cgcx, &module, "thin-lto-after-import");
769        }
770
771        // Alright now that we've done everything related to the ThinLTO
772        // analysis it's time to run some optimizations! Here we use the same
773        // `run_pass_manager` as the "fat" LTO above except that we tell it to
774        // populate a thin-specific pass manager, which presumably LLVM treats a
775        // little differently.
776        {
777            {
    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_llvm/src/back/lto.rs:777",
                        "rustc_codegen_llvm::back::lto", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_llvm/src/back/lto.rs"),
                        ::tracing_core::__macro_support::Option::Some(777u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::back::lto"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!("running thin lto passes over {0}",
                                                    module.name) as &dyn Value))])
            });
    } else { ; }
};info!("running thin lto passes over {}", module.name);
778            run_pass_manager(cgcx, prof, dcx, &mut module, true);
779            save_temp_bitcode(cgcx, &module, "thin-lto-after-pm");
780        }
781    }
782    codegen(cgcx, prof, shared_emitter, module, &cgcx.module_config)
783}
784
785/// Maps LLVM module identifiers to their corresponding LLVM LTO cache keys
786#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ThinLTOKeysMap {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        ::core::fmt::Formatter::debug_struct_field1_finish(f,
            "ThinLTOKeysMap", "keys", &&self.keys)
    }
}Debug, #[automatically_derived]
impl ::core::default::Default for ThinLTOKeysMap {
    #[inline]
    fn default() -> ThinLTOKeysMap {
        ThinLTOKeysMap { keys: ::core::default::Default::default() }
    }
}Default)]
787struct ThinLTOKeysMap {
788    // key = llvm name of importing module, value = LLVM cache key
789    keys: BTreeMap<String, String>,
790}
791
792impl ThinLTOKeysMap {
793    fn save_to_file(&self, path: &Path) -> io::Result<()> {
794        use std::io::Write;
795        let mut writer = File::create_buffered(path)?;
796        // The entries are loaded back into a hash map in `load_from_file()`, so
797        // the order in which we write them to file here does not matter.
798        for (module, key) in &self.keys {
799            writer.write_fmt(format_args!("{0} {1}\n", module, key))writeln!(writer, "{module} {key}")?;
800        }
801        Ok(())
802    }
803
804    fn load_from_file(path: &Path) -> io::Result<Self> {
805        use std::io::BufRead;
806        let mut keys = BTreeMap::default();
807        let file = File::open_buffered(path)?;
808        for line in file.lines() {
809            let line = line?;
810            let mut split = line.split(' ');
811            let module = split.next().unwrap();
812            let key = split.next().unwrap();
813            match (&split.next(), &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::Some(format_args!("Expected two space-separated values, found {0:?}",
                        line)));
        }
    }
};assert_eq!(split.next(), None, "Expected two space-separated values, found {line:?}");
814            keys.insert(module.to_string(), key.to_string());
815        }
816        Ok(Self { keys })
817    }
818
819    fn from_thin_lto_modules(
820        data: &ThinData,
821        modules: &[llvm::ThinLTOModule],
822        names: &[CString],
823    ) -> Self {
824        let keys = iter::zip(modules, names)
825            .map(|(module, name)| {
826                let key = build_string(|rust_str| unsafe {
827                    llvm::LLVMRustComputeLTOCacheKey(rust_str, module.identifier, data.0);
828                })
829                .expect("Invalid ThinLTO module key");
830                (module_name_to_str(name).to_string(), key)
831            })
832            .collect();
833        Self { keys }
834    }
835}
836
837fn module_name_to_str(c_str: &CStr) -> &str {
838    c_str.to_str().unwrap_or_else(|e| {
839        ::rustc_middle::util::bug::bug_fmt(format_args!("Encountered non-utf8 LLVM module name `{0}`: {1}",
        c_str.to_string_lossy(), e))bug!("Encountered non-utf8 LLVM module name `{}`: {}", c_str.to_string_lossy(), e)
840    })
841}
842
843pub(crate) fn parse_module<'a>(
844    cx: &'a llvm::Context,
845    name: &CStr,
846    data: &[u8],
847    dcx: DiagCtxtHandle<'_>,
848) -> &'a llvm::Module {
849    unsafe {
850        llvm::LLVMRustParseBitcodeForLTO(cx, data.as_ptr(), data.len(), name.as_ptr())
851            .unwrap_or_else(|| write::llvm_err(dcx, LlvmError::ParseBitcode))
852    }
853}