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
30const 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 symbols_below_threshold.push(c"__llvm_profile_counter_bias".to_owned());
49
50 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 if obj.starts_with(b"\xDE\xC0\x17\x0B") || obj.starts_with(b"BC\xC0\xDE") {
99 return Ok(obj);
100 }
101 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
116pub(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
133pub(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 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 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 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 let _handler =
239 DiagnosticHandlers::new(cgcx, dcx, llcx, &module, CodegenDiagnosticsStage::LTO);
240
241 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 serialized_modules.sort_by(|module1, module2| module1.1.cmp(&module2.1));
253
254 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 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
317fn 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 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 assert_eq!(thin_modules.len(), module_names.len());
413
414 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 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 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 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 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 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 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); llvm::set_print_type_fun(&fun); }
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 config::AutoDiff::PrintPasses => {}
529 config::AutoDiff::PrintModBefore => {}
531 config::AutoDiff::PrintModAfter => {}
533 config::AutoDiff::PrintModFinal => {}
535 config::AutoDiff::Enable => {}
537 config::AutoDiff::NoPostopt => {}
539 }
540 }
541 llvm::set_strict_aliasing(false);
543 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 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 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 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 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 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 {
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 {
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#[derive(Debug, Default)]
790struct ThinLTOKeysMap {
791 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 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}