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_hir::attrs::SanitizerSet;
19use rustc_middle::bug;
20use rustc_middle::dep_graph::WorkProduct;
21use rustc_session::config::{self, Lto};
22use tracing::{debug, info};
23
24use crate::back::write::{
25 self, CodegenDiagnosticsStage, DiagnosticHandlers, bitcode_section_name, save_temp_bitcode,
26};
27use crate::errors::{LlvmError, LtoBitcodeFromRlib};
28use crate::llvm::{self, build_string};
29use crate::{LlvmCodegenBackend, ModuleLlvm};
30
31const THIN_LTO_KEYS_INCR_COMP_FILE_NAME: &str = "thin-lto-past-keys.bin";
34
35fn prepare_lto(
36 cgcx: &CodegenContext<LlvmCodegenBackend>,
37 exported_symbols_for_lto: &[String],
38 each_linked_rlib_for_lto: &[PathBuf],
39 dcx: DiagCtxtHandle<'_>,
40) -> (Vec<CString>, Vec<(SerializedModule<ModuleBuffer>, CString)>) {
41 let mut symbols_below_threshold = exported_symbols_for_lto
42 .iter()
43 .map(|symbol| CString::new(symbol.to_owned()).unwrap())
44 .collect::<Vec<CString>>();
45
46 if cgcx.module_config.instrument_coverage || cgcx.module_config.pgo_gen.enabled() {
47 const PROFILER_WEAK_SYMBOLS: [&CStr; 2] =
51 [c"__llvm_profile_raw_version", c"__llvm_profile_filename"];
52
53 symbols_below_threshold.extend(PROFILER_WEAK_SYMBOLS.iter().map(|&sym| sym.to_owned()));
54 }
55
56 if cgcx.module_config.sanitizer.contains(SanitizerSet::MEMORY) {
57 let mut msan_weak_symbols = Vec::new();
58
59 if cgcx.module_config.sanitizer_recover.contains(SanitizerSet::MEMORY) {
61 msan_weak_symbols.push(c"__msan_keep_going");
62 }
63
64 if cgcx.module_config.sanitizer_memory_track_origins != 0 {
65 msan_weak_symbols.push(c"__msan_track_origins");
66 }
67
68 symbols_below_threshold.extend(msan_weak_symbols.into_iter().map(|sym| sym.to_owned()));
69 }
70
71 symbols_below_threshold.push(c"___asan_globals_registered".to_owned());
74
75 symbols_below_threshold.push(c"__llvm_profile_counter_bias".to_owned());
79
80 symbols_below_threshold.push(c"rust_eh_personality".to_owned());
82
83 let mut upstream_modules = Vec::new();
90 if cgcx.lto != Lto::ThinLocal {
91 for path in each_linked_rlib_for_lto {
92 let archive_data = unsafe {
93 Mmap::map(std::fs::File::open(&path).expect("couldn't open rlib"))
94 .expect("couldn't map rlib")
95 };
96 let archive = ArchiveFile::parse(&*archive_data).expect("wanted an rlib");
97 let obj_files = archive
98 .members()
99 .filter_map(|child| {
100 child.ok().and_then(|c| {
101 std::str::from_utf8(c.name()).ok().map(|name| (name.trim(), c))
102 })
103 })
104 .filter(|&(name, _)| looks_like_rust_object_file(name));
105 for (name, child) in obj_files {
106 info!("adding bitcode from {}", name);
107 match get_bitcode_slice_from_object_data(
108 child.data(&*archive_data).expect("corrupt rlib"),
109 cgcx,
110 ) {
111 Ok(data) => {
112 let module = SerializedModule::FromRlib(data.to_vec());
113 upstream_modules.push((module, CString::new(name).unwrap()));
114 }
115 Err(e) => dcx.emit_fatal(e),
116 }
117 }
118 }
119 }
120
121 (symbols_below_threshold, upstream_modules)
122}
123
124fn get_bitcode_slice_from_object_data<'a>(
125 obj: &'a [u8],
126 cgcx: &CodegenContext<LlvmCodegenBackend>,
127) -> Result<&'a [u8], LtoBitcodeFromRlib> {
128 if obj.starts_with(b"\xDE\xC0\x17\x0B") || obj.starts_with(b"BC\xC0\xDE") {
132 return Ok(obj);
133 }
134 let section_name = bitcode_section_name(cgcx).to_str().unwrap().trim_start_matches("__LLVM,");
138
139 let obj =
140 object::File::parse(obj).map_err(|err| LtoBitcodeFromRlib { err: err.to_string() })?;
141
142 let section = obj
143 .section_by_name(section_name)
144 .ok_or_else(|| LtoBitcodeFromRlib { err: format!("Can't find section {section_name}") })?;
145
146 section.data().map_err(|err| LtoBitcodeFromRlib { err: err.to_string() })
147}
148
149pub(crate) fn run_fat(
152 cgcx: &CodegenContext<LlvmCodegenBackend>,
153 exported_symbols_for_lto: &[String],
154 each_linked_rlib_for_lto: &[PathBuf],
155 modules: Vec<FatLtoInput<LlvmCodegenBackend>>,
156) -> ModuleCodegen<ModuleLlvm> {
157 let dcx = cgcx.create_dcx();
158 let dcx = dcx.handle();
159 let (symbols_below_threshold, upstream_modules) =
160 prepare_lto(cgcx, exported_symbols_for_lto, each_linked_rlib_for_lto, dcx);
161 let symbols_below_threshold =
162 symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
163 fat_lto(cgcx, dcx, modules, upstream_modules, &symbols_below_threshold)
164}
165
166pub(crate) fn run_thin(
170 cgcx: &CodegenContext<LlvmCodegenBackend>,
171 exported_symbols_for_lto: &[String],
172 each_linked_rlib_for_lto: &[PathBuf],
173 modules: Vec<(String, ThinBuffer)>,
174 cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
175) -> (Vec<ThinModule<LlvmCodegenBackend>>, Vec<WorkProduct>) {
176 let dcx = cgcx.create_dcx();
177 let dcx = dcx.handle();
178 let (symbols_below_threshold, upstream_modules) =
179 prepare_lto(cgcx, exported_symbols_for_lto, each_linked_rlib_for_lto, dcx);
180 let symbols_below_threshold =
181 symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
182 if cgcx.opts.cg.linker_plugin_lto.enabled() {
183 unreachable!(
184 "We should never reach this case if the LTO step \
185 is deferred to the linker"
186 );
187 }
188 thin_lto(cgcx, dcx, modules, upstream_modules, cached_modules, &symbols_below_threshold)
189}
190
191pub(crate) fn prepare_thin(module: ModuleCodegen<ModuleLlvm>) -> (String, ThinBuffer) {
192 let name = module.name;
193 let buffer = ThinBuffer::new(module.module_llvm.llmod(), true);
194 (name, buffer)
195}
196
197fn fat_lto(
198 cgcx: &CodegenContext<LlvmCodegenBackend>,
199 dcx: DiagCtxtHandle<'_>,
200 modules: Vec<FatLtoInput<LlvmCodegenBackend>>,
201 mut serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
202 symbols_below_threshold: &[*const libc::c_char],
203) -> ModuleCodegen<ModuleLlvm> {
204 let _timer = cgcx.prof.generic_activity("LLVM_fat_lto_build_monolithic_module");
205 info!("going for a fat lto");
206
207 let mut in_memory = Vec::new();
214 for module in modules {
215 match module {
216 FatLtoInput::InMemory(m) => in_memory.push(m),
217 FatLtoInput::Serialized { name, buffer } => {
218 info!("pushing serialized module {:?}", name);
219 serialized_modules.push((buffer, CString::new(name).unwrap()));
220 }
221 }
222 }
223
224 let costliest_module = in_memory
234 .iter()
235 .enumerate()
236 .filter(|&(_, module)| module.kind == ModuleKind::Regular)
237 .map(|(i, module)| {
238 let cost = unsafe { llvm::LLVMRustModuleCost(module.module_llvm.llmod()) };
239 (cost, i)
240 })
241 .max();
242
243 let module: ModuleCodegen<ModuleLlvm> = match costliest_module {
249 Some((_cost, i)) => in_memory.remove(i),
250 None => {
251 assert!(!serialized_modules.is_empty(), "must have at least one serialized module");
252 let (buffer, name) = serialized_modules.remove(0);
253 info!("no in-memory regular modules to choose from, parsing {:?}", name);
254 let llvm_module = ModuleLlvm::parse(cgcx, &name, buffer.data(), dcx);
255 ModuleCodegen::new_regular(name.into_string().unwrap(), llvm_module)
256 }
257 };
258 {
259 let (llcx, llmod) = {
260 let llvm = &module.module_llvm;
261 (&llvm.llcx, llvm.llmod())
262 };
263 info!("using {:?} as a base module", module.name);
264
265 let _handler =
269 DiagnosticHandlers::new(cgcx, dcx, llcx, &module, CodegenDiagnosticsStage::LTO);
270
271 for module in in_memory {
277 let buffer = ModuleBuffer::new(module.module_llvm.llmod());
278 let llmod_id = CString::new(&module.name[..]).unwrap();
279 serialized_modules.push((SerializedModule::Local(buffer), llmod_id));
280 }
281 serialized_modules.sort_by(|module1, module2| module1.1.cmp(&module2.1));
283
284 let mut linker = Linker::new(llmod);
287 for (bc_decoded, name) in serialized_modules {
288 let _timer = cgcx
289 .prof
290 .generic_activity_with_arg_recorder("LLVM_fat_lto_link_module", |recorder| {
291 recorder.record_arg(format!("{name:?}"))
292 });
293 info!("linking {:?}", name);
294 let data = bc_decoded.data();
295 linker
296 .add(data)
297 .unwrap_or_else(|()| write::llvm_err(dcx, LlvmError::LoadBitcode { name }));
298 }
299 drop(linker);
300 save_temp_bitcode(cgcx, &module, "lto.input");
301
302 unsafe {
304 let ptr = symbols_below_threshold.as_ptr();
305 llvm::LLVMRustRunRestrictionPass(
306 llmod,
307 ptr as *const *const libc::c_char,
308 symbols_below_threshold.len() as libc::size_t,
309 );
310 }
311 save_temp_bitcode(cgcx, &module, "lto.after-restriction");
312 }
313
314 module
315}
316
317pub(crate) struct Linker<'a>(&'a mut llvm::Linker<'a>);
318
319impl<'a> Linker<'a> {
320 pub(crate) fn new(llmod: &'a llvm::Module) -> Self {
321 unsafe { Linker(llvm::LLVMRustLinkerNew(llmod)) }
322 }
323
324 pub(crate) fn add(&mut self, bytecode: &[u8]) -> Result<(), ()> {
325 unsafe {
326 if llvm::LLVMRustLinkerAdd(
327 self.0,
328 bytecode.as_ptr() as *const libc::c_char,
329 bytecode.len(),
330 ) {
331 Ok(())
332 } else {
333 Err(())
334 }
335 }
336 }
337}
338
339impl Drop for Linker<'_> {
340 fn drop(&mut self) {
341 unsafe {
342 llvm::LLVMRustLinkerFree(&mut *(self.0 as *mut _));
343 }
344 }
345}
346
347fn thin_lto(
378 cgcx: &CodegenContext<LlvmCodegenBackend>,
379 dcx: DiagCtxtHandle<'_>,
380 modules: Vec<(String, ThinBuffer)>,
381 serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
382 cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
383 symbols_below_threshold: &[*const libc::c_char],
384) -> (Vec<ThinModule<LlvmCodegenBackend>>, Vec<WorkProduct>) {
385 let _timer = cgcx.prof.generic_activity("LLVM_thin_lto_global_analysis");
386 unsafe {
387 info!("going for that thin, thin LTO");
388
389 let green_modules: FxHashMap<_, _> =
390 cached_modules.iter().map(|(_, wp)| (wp.cgu_name.clone(), wp.clone())).collect();
391
392 let full_scope_len = modules.len() + serialized_modules.len() + cached_modules.len();
393 let mut thin_buffers = Vec::with_capacity(modules.len());
394 let mut module_names = Vec::with_capacity(full_scope_len);
395 let mut thin_modules = Vec::with_capacity(full_scope_len);
396
397 for (i, (name, buffer)) in modules.into_iter().enumerate() {
398 info!("local module: {} - {}", i, name);
399 let cname = CString::new(name.as_bytes()).unwrap();
400 thin_modules.push(llvm::ThinLTOModule {
401 identifier: cname.as_ptr(),
402 data: buffer.data().as_ptr(),
403 len: buffer.data().len(),
404 });
405 thin_buffers.push(buffer);
406 module_names.push(cname);
407 }
408
409 let mut serialized = Vec::with_capacity(serialized_modules.len() + cached_modules.len());
426
427 let cached_modules =
428 cached_modules.into_iter().map(|(sm, wp)| (sm, CString::new(wp.cgu_name).unwrap()));
429
430 for (module, name) in serialized_modules.into_iter().chain(cached_modules) {
431 info!("upstream or cached module {:?}", name);
432 thin_modules.push(llvm::ThinLTOModule {
433 identifier: name.as_ptr(),
434 data: module.data().as_ptr(),
435 len: module.data().len(),
436 });
437 serialized.push(module);
438 module_names.push(name);
439 }
440
441 assert_eq!(thin_modules.len(), module_names.len());
443
444 let data = llvm::LLVMRustCreateThinLTOData(
449 thin_modules.as_ptr(),
450 thin_modules.len(),
451 symbols_below_threshold.as_ptr(),
452 symbols_below_threshold.len(),
453 )
454 .unwrap_or_else(|| write::llvm_err(dcx, LlvmError::PrepareThinLtoContext));
455
456 let data = ThinData(data);
457
458 info!("thin LTO data created");
459
460 let (key_map_path, prev_key_map, curr_key_map) = if let Some(ref incr_comp_session_dir) =
461 cgcx.incr_comp_session_dir
462 {
463 let path = incr_comp_session_dir.join(THIN_LTO_KEYS_INCR_COMP_FILE_NAME);
464 let prev =
468 if path.exists() { ThinLTOKeysMap::load_from_file(&path).ok() } else { None };
469 let curr = ThinLTOKeysMap::from_thin_lto_modules(&data, &thin_modules, &module_names);
470 (Some(path), prev, curr)
471 } else {
472 assert!(green_modules.is_empty());
475 let curr = ThinLTOKeysMap::default();
476 (None, None, curr)
477 };
478 info!("thin LTO cache key map loaded");
479 info!("prev_key_map: {:#?}", prev_key_map);
480 info!("curr_key_map: {:#?}", curr_key_map);
481
482 let shared = Arc::new(ThinShared {
487 data,
488 thin_buffers,
489 serialized_modules: serialized,
490 module_names,
491 });
492
493 let mut copy_jobs = vec![];
494 let mut opt_jobs = vec![];
495
496 info!("checking which modules can be-reused and which have to be re-optimized.");
497 for (module_index, module_name) in shared.module_names.iter().enumerate() {
498 let module_name = module_name_to_str(module_name);
499 if let (Some(prev_key_map), true) =
500 (prev_key_map.as_ref(), green_modules.contains_key(module_name))
501 {
502 assert!(cgcx.incr_comp_session_dir.is_some());
503
504 if prev_key_map.keys.get(module_name) == curr_key_map.keys.get(module_name) {
507 let work_product = green_modules[module_name].clone();
508 copy_jobs.push(work_product);
509 info!(" - {}: re-used", module_name);
510 assert!(cgcx.incr_comp_session_dir.is_some());
511 continue;
512 }
513 }
514
515 info!(" - {}: re-compiled", module_name);
516 opt_jobs.push(ThinModule { shared: Arc::clone(&shared), idx: module_index });
517 }
518
519 if let Some(path) = key_map_path
522 && let Err(err) = curr_key_map.save_to_file(&path)
523 {
524 write::llvm_err(dcx, LlvmError::WriteThinLtoKey { err });
525 }
526
527 (opt_jobs, copy_jobs)
528 }
529}
530
531fn enable_autodiff_settings(ad: &[config::AutoDiff]) {
532 for val in ad {
533 match val {
535 config::AutoDiff::PrintPerf => {
536 llvm::set_print_perf(true);
537 }
538 config::AutoDiff::PrintAA => {
539 llvm::set_print_activity(true);
540 }
541 config::AutoDiff::PrintTA => {
542 llvm::set_print_type(true);
543 }
544 config::AutoDiff::PrintTAFn(fun) => {
545 llvm::set_print_type(true); llvm::set_print_type_fun(&fun); }
548 config::AutoDiff::Inline => {
549 llvm::set_inline(true);
550 }
551 config::AutoDiff::LooseTypes => {
552 llvm::set_loose_types(true);
553 }
554 config::AutoDiff::PrintSteps => {
555 llvm::set_print(true);
556 }
557 config::AutoDiff::PrintPasses => {}
559 config::AutoDiff::PrintModBefore => {}
561 config::AutoDiff::PrintModAfter => {}
563 config::AutoDiff::PrintModFinal => {}
565 config::AutoDiff::Enable => {}
567 config::AutoDiff::NoPostopt => {}
569 config::AutoDiff::NoTT => {}
571 }
572 }
573 llvm::set_strict_aliasing(false);
575 llvm::set_rust_rules(true);
577}
578
579pub(crate) fn run_pass_manager(
580 cgcx: &CodegenContext<LlvmCodegenBackend>,
581 dcx: DiagCtxtHandle<'_>,
582 module: &mut ModuleCodegen<ModuleLlvm>,
583 thin: bool,
584) {
585 let _timer = cgcx.prof.generic_activity_with_arg("LLVM_lto_optimize", &*module.name);
586 let config = &cgcx.module_config;
587
588 debug!("running the pass manager");
594 let opt_stage = if thin { llvm::OptStage::ThinLTO } else { llvm::OptStage::FatLTO };
595 let opt_level = config.opt_level.unwrap_or(config::OptLevel::No);
596
597 let enable_ad = config.autodiff.contains(&config::AutoDiff::Enable);
604 let stage = if thin {
605 write::AutodiffStage::PreAD
606 } else {
607 if enable_ad { write::AutodiffStage::DuringAD } else { write::AutodiffStage::PostAD }
608 };
609
610 if enable_ad {
611 enable_autodiff_settings(&config.autodiff);
612 }
613
614 unsafe {
615 write::llvm_optimize(cgcx, dcx, module, None, config, opt_level, opt_stage, stage);
616 }
617
618 if cfg!(feature = "llvm_enzyme") && enable_ad && !thin {
619 let opt_stage = llvm::OptStage::FatLTO;
620 let stage = write::AutodiffStage::PostAD;
621 if !config.autodiff.contains(&config::AutoDiff::NoPostopt) {
622 unsafe {
623 write::llvm_optimize(cgcx, dcx, module, None, config, opt_level, opt_stage, stage);
624 }
625 }
626
627 if config.autodiff.contains(&config::AutoDiff::PrintModFinal) {
630 unsafe { llvm::LLVMDumpModule(module.module_llvm.llmod()) };
631 }
632 }
633
634 debug!("lto done");
635}
636
637pub struct ModuleBuffer(&'static mut llvm::ModuleBuffer);
638
639unsafe impl Send for ModuleBuffer {}
640unsafe impl Sync for ModuleBuffer {}
641
642impl ModuleBuffer {
643 pub(crate) fn new(m: &llvm::Module) -> ModuleBuffer {
644 ModuleBuffer(unsafe { llvm::LLVMRustModuleBufferCreate(m) })
645 }
646}
647
648impl ModuleBufferMethods for ModuleBuffer {
649 fn data(&self) -> &[u8] {
650 unsafe {
651 let ptr = llvm::LLVMRustModuleBufferPtr(self.0);
652 let len = llvm::LLVMRustModuleBufferLen(self.0);
653 slice::from_raw_parts(ptr, len)
654 }
655 }
656}
657
658impl Drop for ModuleBuffer {
659 fn drop(&mut self) {
660 unsafe {
661 llvm::LLVMRustModuleBufferFree(&mut *(self.0 as *mut _));
662 }
663 }
664}
665
666pub struct ThinData(&'static mut llvm::ThinLTOData);
667
668unsafe impl Send for ThinData {}
669unsafe impl Sync for ThinData {}
670
671impl Drop for ThinData {
672 fn drop(&mut self) {
673 unsafe {
674 llvm::LLVMRustFreeThinLTOData(&mut *(self.0 as *mut _));
675 }
676 }
677}
678
679pub struct ThinBuffer(&'static mut llvm::ThinLTOBuffer);
680
681unsafe impl Send for ThinBuffer {}
682unsafe impl Sync for ThinBuffer {}
683
684impl ThinBuffer {
685 pub(crate) fn new(m: &llvm::Module, is_thin: bool) -> ThinBuffer {
686 unsafe {
687 let buffer = llvm::LLVMRustThinLTOBufferCreate(m, is_thin);
688 ThinBuffer(buffer)
689 }
690 }
691
692 pub(crate) unsafe fn from_raw_ptr(ptr: *mut llvm::ThinLTOBuffer) -> ThinBuffer {
693 let mut ptr = NonNull::new(ptr).unwrap();
694 ThinBuffer(unsafe { ptr.as_mut() })
695 }
696
697 pub(crate) fn thin_link_data(&self) -> &[u8] {
698 unsafe {
699 let ptr = llvm::LLVMRustThinLTOBufferThinLinkDataPtr(self.0) as *const _;
700 let len = llvm::LLVMRustThinLTOBufferThinLinkDataLen(self.0);
701 slice::from_raw_parts(ptr, len)
702 }
703 }
704}
705
706impl ThinBufferMethods for ThinBuffer {
707 fn data(&self) -> &[u8] {
708 unsafe {
709 let ptr = llvm::LLVMRustThinLTOBufferPtr(self.0) as *const _;
710 let len = llvm::LLVMRustThinLTOBufferLen(self.0);
711 slice::from_raw_parts(ptr, len)
712 }
713 }
714}
715
716impl Drop for ThinBuffer {
717 fn drop(&mut self) {
718 unsafe {
719 llvm::LLVMRustThinLTOBufferFree(&mut *(self.0 as *mut _));
720 }
721 }
722}
723
724pub(crate) fn optimize_thin_module(
725 thin_module: ThinModule<LlvmCodegenBackend>,
726 cgcx: &CodegenContext<LlvmCodegenBackend>,
727) -> ModuleCodegen<ModuleLlvm> {
728 let dcx = cgcx.create_dcx();
729 let dcx = dcx.handle();
730
731 let module_name = &thin_module.shared.module_names[thin_module.idx];
732
733 let module_llvm = ModuleLlvm::parse(cgcx, module_name, thin_module.data(), dcx);
739 let mut module = ModuleCodegen::new_regular(thin_module.name(), module_llvm);
740 if cgcx.module_config.embed_bitcode() {
742 module.thin_lto_buffer = Some(thin_module.data().to_vec());
743 }
744 {
745 let target = &*module.module_llvm.tm;
746 let llmod = module.module_llvm.llmod();
747 save_temp_bitcode(cgcx, &module, "thin-lto-input");
748
749 {
758 let _timer =
759 cgcx.prof.generic_activity_with_arg("LLVM_thin_lto_rename", thin_module.name());
760 unsafe {
761 llvm::LLVMRustPrepareThinLTORename(thin_module.shared.data.0, llmod, target.raw())
762 };
763 save_temp_bitcode(cgcx, &module, "thin-lto-after-rename");
764 }
765
766 {
767 let _timer = cgcx
768 .prof
769 .generic_activity_with_arg("LLVM_thin_lto_resolve_weak", thin_module.name());
770 if unsafe { !llvm::LLVMRustPrepareThinLTOResolveWeak(thin_module.shared.data.0, llmod) }
771 {
772 write::llvm_err(dcx, LlvmError::PrepareThinLtoModule);
773 }
774 save_temp_bitcode(cgcx, &module, "thin-lto-after-resolve");
775 }
776
777 {
778 let _timer = cgcx
779 .prof
780 .generic_activity_with_arg("LLVM_thin_lto_internalize", thin_module.name());
781 if unsafe { !llvm::LLVMRustPrepareThinLTOInternalize(thin_module.shared.data.0, llmod) }
782 {
783 write::llvm_err(dcx, LlvmError::PrepareThinLtoModule);
784 }
785 save_temp_bitcode(cgcx, &module, "thin-lto-after-internalize");
786 }
787
788 {
789 let _timer =
790 cgcx.prof.generic_activity_with_arg("LLVM_thin_lto_import", thin_module.name());
791 if unsafe {
792 !llvm::LLVMRustPrepareThinLTOImport(thin_module.shared.data.0, llmod, target.raw())
793 } {
794 write::llvm_err(dcx, LlvmError::PrepareThinLtoModule);
795 }
796 save_temp_bitcode(cgcx, &module, "thin-lto-after-import");
797 }
798
799 {
805 info!("running thin lto passes over {}", module.name);
806 run_pass_manager(cgcx, dcx, &mut module, true);
807 save_temp_bitcode(cgcx, &module, "thin-lto-after-pm");
808 }
809 }
810 module
811}
812
813#[derive(Debug, Default)]
815struct ThinLTOKeysMap {
816 keys: BTreeMap<String, String>,
818}
819
820impl ThinLTOKeysMap {
821 fn save_to_file(&self, path: &Path) -> io::Result<()> {
822 use std::io::Write;
823 let mut writer = File::create_buffered(path)?;
824 for (module, key) in &self.keys {
827 writeln!(writer, "{module} {key}")?;
828 }
829 Ok(())
830 }
831
832 fn load_from_file(path: &Path) -> io::Result<Self> {
833 use std::io::BufRead;
834 let mut keys = BTreeMap::default();
835 let file = File::open_buffered(path)?;
836 for line in file.lines() {
837 let line = line?;
838 let mut split = line.split(' ');
839 let module = split.next().unwrap();
840 let key = split.next().unwrap();
841 assert_eq!(split.next(), None, "Expected two space-separated values, found {line:?}");
842 keys.insert(module.to_string(), key.to_string());
843 }
844 Ok(Self { keys })
845 }
846
847 fn from_thin_lto_modules(
848 data: &ThinData,
849 modules: &[llvm::ThinLTOModule],
850 names: &[CString],
851 ) -> Self {
852 let keys = iter::zip(modules, names)
853 .map(|(module, name)| {
854 let key = build_string(|rust_str| unsafe {
855 llvm::LLVMRustComputeLTOCacheKey(rust_str, module.identifier, data.0);
856 })
857 .expect("Invalid ThinLTO module key");
858 (module_name_to_str(name).to_string(), key)
859 })
860 .collect();
861 Self { keys }
862 }
863}
864
865fn module_name_to_str(c_str: &CStr) -> &str {
866 c_str.to_str().unwrap_or_else(|e| {
867 bug!("Encountered non-utf8 LLVM module name `{}`: {}", c_str.to_string_lossy(), e)
868 })
869}
870
871pub(crate) fn parse_module<'a>(
872 cx: &'a llvm::Context,
873 name: &CStr,
874 data: &[u8],
875 dcx: DiagCtxtHandle<'_>,
876) -> &'a llvm::Module {
877 unsafe {
878 llvm::LLVMRustParseBitcodeForLTO(cx, data.as_ptr(), data.len(), name.as_ptr())
879 .unwrap_or_else(|| write::llvm_err(dcx, LlvmError::ParseBitcode))
880 }
881}