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