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