1 use crate::back::write::{self, save_temp_bitcode, DiagnosticHandlers};
2 use crate::errors::DynamicLinkingWithLTO;
3 use crate::llvm::{self, build_string};
4 use crate::{LlvmCodegenBackend, ModuleLlvm};
5 use object::read::archive::ArchiveFile;
6 use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule, ThinShared};
7 use rustc_codegen_ssa::back::symbol_export;
8 use rustc_codegen_ssa::back::write::{CodegenContext, FatLTOInput, TargetMachineFactoryConfig};
9 use rustc_codegen_ssa::traits::*;
10 use rustc_codegen_ssa::{looks_like_rust_object_file, ModuleCodegen, ModuleKind};
11 use rustc_data_structures::fx::FxHashMap;
12 use rustc_data_structures::memmap::Mmap;
13 use rustc_errors::{FatalError, Handler};
14 use rustc_hir::def_id::LOCAL_CRATE;
15 use rustc_middle::bug;
16 use rustc_middle::dep_graph::WorkProduct;
17 use rustc_middle::middle::exported_symbols::{SymbolExportInfo, SymbolExportLevel};
18 use rustc_session::cgu_reuse_tracker::CguReuse;
19 use rustc_session::config::{self, CrateType, Lto};
21 use std::ffi::{CStr, CString};
30 /// We keep track of the computed LTO cache keys from the previous
31 /// session to determine which CGUs we can reuse.
32 pub const THIN_LTO_KEYS_INCR_COMP_FILE_NAME: &str = "thin-lto-past-keys.bin";
34 pub fn crate_type_allows_lto(crate_type: CrateType) -> bool {
36 CrateType::Executable | CrateType::Dylib | CrateType::Staticlib | CrateType::Cdylib => true,
37 CrateType::Rlib | CrateType::ProcMacro => false,
42 cgcx: &CodegenContext<LlvmCodegenBackend>,
43 diag_handler: &Handler,
44 ) -> Result<(Vec<CString>, Vec<(SerializedModule<ModuleBuffer>, CString)>), FatalError> {
45 let export_threshold = match cgcx.lto {
46 // We're just doing LTO for our one crate
47 Lto::ThinLocal => SymbolExportLevel::Rust,
49 // We're doing LTO for the entire crate graph
50 Lto::Fat | Lto::Thin => symbol_export::crates_export_threshold(&cgcx.crate_types),
52 Lto::No => panic!("didn't request LTO but we're doing LTO"),
55 let symbol_filter = &|&(ref name, info): &(String, SymbolExportInfo)| {
56 if info.level.is_below_threshold(export_threshold) || info.used {
57 Some(CString::new(name.as_str()).unwrap())
62 let exported_symbols = cgcx.exported_symbols.as_ref().expect("needs exported symbols for LTO");
63 let mut symbols_below_threshold = {
64 let _timer = cgcx.prof.generic_activity("LLVM_lto_generate_symbols_below_threshold");
65 exported_symbols[&LOCAL_CRATE].iter().filter_map(symbol_filter).collect::<Vec<CString>>()
67 info!("{} symbols to preserve in this crate", symbols_below_threshold.len());
69 // If we're performing LTO for the entire crate graph, then for each of our
70 // upstream dependencies, find the corresponding rlib and load the bitcode
73 // We save off all the bytecode and LLVM module ids for later processing
74 // with either fat or thin LTO
75 let mut upstream_modules = Vec::new();
76 if cgcx.lto != Lto::ThinLocal {
77 // Make sure we actually can run LTO
78 for crate_type in cgcx.crate_types.iter() {
79 if !crate_type_allows_lto(*crate_type) {
80 let e = diag_handler.fatal(
81 "lto can only be run for executables, cdylibs and \
82 static library outputs",
85 } else if *crate_type == CrateType::Dylib {
86 if !cgcx.opts.unstable_opts.dylib_lto {
87 return Err(diag_handler
88 .fatal("lto cannot be used for `dylib` crate type without `-Zdylib-lto`"));
93 if cgcx.opts.cg.prefer_dynamic && !cgcx.opts.unstable_opts.dylib_lto {
94 diag_handler.emit_err(DynamicLinkingWithLTO);
95 return Err(FatalError);
98 for &(cnum, ref path) in cgcx.each_linked_rlib_for_lto.iter() {
99 let exported_symbols =
100 cgcx.exported_symbols.as_ref().expect("needs exported symbols for LTO");
103 cgcx.prof.generic_activity("LLVM_lto_generate_symbols_below_threshold");
104 symbols_below_threshold
105 .extend(exported_symbols[&cnum].iter().filter_map(symbol_filter));
108 let archive_data = unsafe {
109 Mmap::map(std::fs::File::open(&path).expect("couldn't open rlib"))
110 .expect("couldn't map rlib")
112 let archive = ArchiveFile::parse(&*archive_data).expect("wanted an rlib");
113 let obj_files = archive
115 .filter_map(|child| {
116 child.ok().and_then(|c| {
117 std::str::from_utf8(c.name()).ok().map(|name| (name.trim(), c))
120 .filter(|&(name, _)| looks_like_rust_object_file(name));
121 for (name, child) in obj_files {
122 info!("adding bitcode from {}", name);
123 match get_bitcode_slice_from_object_data(
124 child.data(&*archive_data).expect("corrupt rlib"),
127 let module = SerializedModule::FromRlib(data.to_vec());
128 upstream_modules.push((module, CString::new(name).unwrap()));
130 Err(msg) => return Err(diag_handler.fatal(&msg)),
136 // __llvm_profile_counter_bias is pulled in at link time by an undefined reference to
137 // __llvm_profile_runtime, therefore we won't know until link time if this symbol
138 // should have default visibility.
139 symbols_below_threshold.push(CString::new("__llvm_profile_counter_bias").unwrap());
140 Ok((symbols_below_threshold, upstream_modules))
143 fn get_bitcode_slice_from_object_data(obj: &[u8]) -> Result<&[u8], String> {
146 unsafe { llvm::LLVMRustGetBitcodeSliceFromObjectData(obj.as_ptr(), obj.len(), &mut len) };
149 let bc = unsafe { slice::from_raw_parts(data, len) };
151 // `bc` must be a sub-slice of `obj`.
152 assert!(obj.as_ptr() <= bc.as_ptr());
153 assert!(bc[bc.len()..bc.len()].as_ptr() <= obj[obj.len()..obj.len()].as_ptr());
158 let msg = llvm::last_error().unwrap_or_else(|| "unknown LLVM error".to_string());
159 Err(format!("failed to get bitcode from object file for LTO ({})", msg))
163 /// Performs fat LTO by merging all modules into a single one and returning it
164 /// for further optimization.
165 pub(crate) fn run_fat(
166 cgcx: &CodegenContext<LlvmCodegenBackend>,
167 modules: Vec<FatLTOInput<LlvmCodegenBackend>>,
168 cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
169 ) -> Result<LtoModuleCodegen<LlvmCodegenBackend>, FatalError> {
170 let diag_handler = cgcx.create_diag_handler();
171 let (symbols_below_threshold, upstream_modules) = prepare_lto(cgcx, &diag_handler)?;
172 let symbols_below_threshold =
173 symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
180 &symbols_below_threshold,
184 /// Performs thin LTO by performing necessary global analysis and returning two
185 /// lists, one of the modules that need optimization and another for modules that
186 /// can simply be copied over from the incr. comp. cache.
187 pub(crate) fn run_thin(
188 cgcx: &CodegenContext<LlvmCodegenBackend>,
189 modules: Vec<(String, ThinBuffer)>,
190 cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
191 ) -> Result<(Vec<LtoModuleCodegen<LlvmCodegenBackend>>, Vec<WorkProduct>), FatalError> {
192 let diag_handler = cgcx.create_diag_handler();
193 let (symbols_below_threshold, upstream_modules) = prepare_lto(cgcx, &diag_handler)?;
194 let symbols_below_threshold =
195 symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
196 if cgcx.opts.cg.linker_plugin_lto.enabled() {
198 "We should never reach this case if the LTO step \
199 is deferred to the linker"
208 &symbols_below_threshold,
212 pub(crate) fn prepare_thin(module: ModuleCodegen<ModuleLlvm>) -> (String, ThinBuffer) {
213 let name = module.name;
214 let buffer = ThinBuffer::new(module.module_llvm.llmod(), true);
219 cgcx: &CodegenContext<LlvmCodegenBackend>,
220 diag_handler: &Handler,
221 modules: Vec<FatLTOInput<LlvmCodegenBackend>>,
222 cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
223 mut serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
224 symbols_below_threshold: &[*const libc::c_char],
225 ) -> Result<LtoModuleCodegen<LlvmCodegenBackend>, FatalError> {
226 let _timer = cgcx.prof.generic_activity("LLVM_fat_lto_build_monolithic_module");
227 info!("going for a fat lto");
229 // Sort out all our lists of incoming modules into two lists.
231 // * `serialized_modules` (also and argument to this function) contains all
232 // modules that are serialized in-memory.
233 // * `in_memory` contains modules which are already parsed and in-memory,
234 // such as from multi-CGU builds.
236 // All of `cached_modules` (cached from previous incremental builds) can
237 // immediately go onto the `serialized_modules` modules list and then we can
238 // split the `modules` array into these two lists.
239 let mut in_memory = Vec::new();
240 serialized_modules.extend(cached_modules.into_iter().map(|(buffer, wp)| {
241 info!("pushing cached module {:?}", wp.cgu_name);
242 (buffer, CString::new(wp.cgu_name).unwrap())
244 for module in modules {
246 FatLTOInput::InMemory(m) => in_memory.push(m),
247 FatLTOInput::Serialized { name, buffer } => {
248 info!("pushing serialized module {:?}", name);
249 let buffer = SerializedModule::Local(buffer);
250 serialized_modules.push((buffer, CString::new(name).unwrap()));
255 // Find the "costliest" module and merge everything into that codegen unit.
256 // All the other modules will be serialized and reparsed into the new
257 // context, so this hopefully avoids serializing and parsing the largest
260 // Additionally use a regular module as the base here to ensure that various
261 // file copy operations in the backend work correctly. The only other kind
262 // of module here should be an allocator one, and if your crate is smaller
263 // than the allocator module then the size doesn't really matter anyway.
264 let costliest_module = in_memory
267 .filter(|&(_, module)| module.kind == ModuleKind::Regular)
269 let cost = unsafe { llvm::LLVMRustModuleCost(module.module_llvm.llmod()) };
274 // If we found a costliest module, we're good to go. Otherwise all our
275 // inputs were serialized which could happen in the case, for example, that
276 // all our inputs were incrementally reread from the cache and we're just
277 // re-executing the LTO passes. If that's the case deserialize the first
278 // module and create a linker with it.
279 let module: ModuleCodegen<ModuleLlvm> = match costliest_module {
280 Some((_cost, i)) => in_memory.remove(i),
282 assert!(!serialized_modules.is_empty(), "must have at least one serialized module");
283 let (buffer, name) = serialized_modules.remove(0);
284 info!("no in-memory regular modules to choose from, parsing {:?}", name);
286 module_llvm: ModuleLlvm::parse(cgcx, &name, buffer.data(), diag_handler)?,
287 name: name.into_string().unwrap(),
288 kind: ModuleKind::Regular,
292 let mut serialized_bitcode = Vec::new();
294 let (llcx, llmod) = {
295 let llvm = &module.module_llvm;
296 (&llvm.llcx, llvm.llmod())
298 info!("using {:?} as a base module", module.name);
300 // The linking steps below may produce errors and diagnostics within LLVM
301 // which we'd like to handle and print, so set up our diagnostic handlers
302 // (which get unregistered when they go out of scope below).
303 let _handler = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
305 // For all other modules we codegened we'll need to link them into our own
306 // bitcode. All modules were codegened in their own LLVM context, however,
307 // and we want to move everything to the same LLVM context. Currently the
308 // way we know of to do that is to serialize them to a string and them parse
309 // them later. Not great but hey, that's why it's "fat" LTO, right?
310 for module in in_memory {
311 let buffer = ModuleBuffer::new(module.module_llvm.llmod());
312 let llmod_id = CString::new(&module.name[..]).unwrap();
313 serialized_modules.push((SerializedModule::Local(buffer), llmod_id));
315 // Sort the modules to ensure we produce deterministic results.
316 serialized_modules.sort_by(|module1, module2| module1.1.cmp(&module2.1));
318 // For all serialized bitcode files we parse them and link them in as we did
319 // above, this is all mostly handled in C++. Like above, though, we don't
320 // know much about the memory management here so we err on the side of being
321 // save and persist everything with the original module.
322 let mut linker = Linker::new(llmod);
323 for (bc_decoded, name) in serialized_modules {
326 .generic_activity_with_arg_recorder("LLVM_fat_lto_link_module", |recorder| {
327 recorder.record_arg(format!("{:?}", name))
329 info!("linking {:?}", name);
330 let data = bc_decoded.data();
331 linker.add(data).map_err(|()| {
332 let msg = format!("failed to load bitcode of module {:?}", name);
333 write::llvm_err(diag_handler, &msg)
335 serialized_bitcode.push(bc_decoded);
338 save_temp_bitcode(cgcx, &module, "lto.input");
340 // Internalize everything below threshold to help strip out more modules and such.
342 let ptr = symbols_below_threshold.as_ptr();
343 llvm::LLVMRustRunRestrictionPass(
345 ptr as *const *const libc::c_char,
346 symbols_below_threshold.len() as libc::size_t,
348 save_temp_bitcode(cgcx, &module, "lto.after-restriction");
352 Ok(LtoModuleCodegen::Fat { module, _serialized_bitcode: serialized_bitcode })
355 pub(crate) struct Linker<'a>(&'a mut llvm::Linker<'a>);
357 impl<'a> Linker<'a> {
358 pub(crate) fn new(llmod: &'a llvm::Module) -> Self {
359 unsafe { Linker(llvm::LLVMRustLinkerNew(llmod)) }
362 pub(crate) fn add(&mut self, bytecode: &[u8]) -> Result<(), ()> {
364 if llvm::LLVMRustLinkerAdd(
366 bytecode.as_ptr() as *const libc::c_char,
377 impl Drop for Linker<'_> {
380 llvm::LLVMRustLinkerFree(&mut *(self.0 as *mut _));
385 /// Prepare "thin" LTO to get run on these modules.
387 /// The general structure of ThinLTO is quite different from the structure of
388 /// "fat" LTO above. With "fat" LTO all LLVM modules in question are merged into
389 /// one giant LLVM module, and then we run more optimization passes over this
390 /// big module after internalizing most symbols. Thin LTO, on the other hand,
391 /// avoid this large bottleneck through more targeted optimization.
393 /// At a high level Thin LTO looks like:
395 /// 1. Prepare a "summary" of each LLVM module in question which describes
396 /// the values inside, cost of the values, etc.
397 /// 2. Merge the summaries of all modules in question into one "index"
398 /// 3. Perform some global analysis on this index
399 /// 4. For each module, use the index and analysis calculated previously to
400 /// perform local transformations on the module, for example inlining
401 /// small functions from other modules.
402 /// 5. Run thin-specific optimization passes over each module, and then code
403 /// generate everything at the end.
405 /// The summary for each module is intended to be quite cheap, and the global
406 /// index is relatively quite cheap to create as well. As a result, the goal of
407 /// ThinLTO is to reduce the bottleneck on LTO and enable LTO to be used in more
408 /// situations. For example one cheap optimization is that we can parallelize
409 /// all codegen modules, easily making use of all the cores on a machine.
411 /// With all that in mind, the function here is designed at specifically just
412 /// calculating the *index* for ThinLTO. This index will then be shared amongst
413 /// all of the `LtoModuleCodegen` units returned below and destroyed once
414 /// they all go out of scope.
416 cgcx: &CodegenContext<LlvmCodegenBackend>,
417 diag_handler: &Handler,
418 modules: Vec<(String, ThinBuffer)>,
419 serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
420 cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
421 symbols_below_threshold: &[*const libc::c_char],
422 ) -> Result<(Vec<LtoModuleCodegen<LlvmCodegenBackend>>, Vec<WorkProduct>), FatalError> {
423 let _timer = cgcx.prof.generic_activity("LLVM_thin_lto_global_analysis");
425 info!("going for that thin, thin LTO");
427 let green_modules: FxHashMap<_, _> =
428 cached_modules.iter().map(|(_, wp)| (wp.cgu_name.clone(), wp.clone())).collect();
430 let full_scope_len = modules.len() + serialized_modules.len() + cached_modules.len();
431 let mut thin_buffers = Vec::with_capacity(modules.len());
432 let mut module_names = Vec::with_capacity(full_scope_len);
433 let mut thin_modules = Vec::with_capacity(full_scope_len);
435 for (i, (name, buffer)) in modules.into_iter().enumerate() {
436 info!("local module: {} - {}", i, name);
437 let cname = CString::new(name.clone()).unwrap();
438 thin_modules.push(llvm::ThinLTOModule {
439 identifier: cname.as_ptr(),
440 data: buffer.data().as_ptr(),
441 len: buffer.data().len(),
443 thin_buffers.push(buffer);
444 module_names.push(cname);
447 // FIXME: All upstream crates are deserialized internally in the
448 // function below to extract their summary and modules. Note that
449 // unlike the loop above we *must* decode and/or read something
450 // here as these are all just serialized files on disk. An
451 // improvement, however, to make here would be to store the
452 // module summary separately from the actual module itself. Right
453 // now this is store in one large bitcode file, and the entire
454 // file is deflate-compressed. We could try to bypass some of the
455 // decompression by storing the index uncompressed and only
456 // lazily decompressing the bytecode if necessary.
458 // Note that truly taking advantage of this optimization will
459 // likely be further down the road. We'd have to implement
460 // incremental ThinLTO first where we could actually avoid
461 // looking at upstream modules entirely sometimes (the contents,
462 // we must always unconditionally look at the index).
463 let mut serialized = Vec::with_capacity(serialized_modules.len() + cached_modules.len());
466 cached_modules.into_iter().map(|(sm, wp)| (sm, CString::new(wp.cgu_name).unwrap()));
468 for (module, name) in serialized_modules.into_iter().chain(cached_modules) {
469 info!("upstream or cached module {:?}", name);
470 thin_modules.push(llvm::ThinLTOModule {
471 identifier: name.as_ptr(),
472 data: module.data().as_ptr(),
473 len: module.data().len(),
475 serialized.push(module);
476 module_names.push(name);
480 assert_eq!(thin_modules.len(), module_names.len());
482 // Delegate to the C++ bindings to create some data here. Once this is a
483 // tried-and-true interface we may wish to try to upstream some of this
484 // to LLVM itself, right now we reimplement a lot of what they do
486 let data = llvm::LLVMRustCreateThinLTOData(
487 thin_modules.as_ptr(),
488 thin_modules.len() as u32,
489 symbols_below_threshold.as_ptr(),
490 symbols_below_threshold.len() as u32,
492 .ok_or_else(|| write::llvm_err(diag_handler, "failed to prepare thin LTO context"))?;
494 let data = ThinData(data);
496 info!("thin LTO data created");
498 let (key_map_path, prev_key_map, curr_key_map) = if let Some(ref incr_comp_session_dir) =
499 cgcx.incr_comp_session_dir
501 let path = incr_comp_session_dir.join(THIN_LTO_KEYS_INCR_COMP_FILE_NAME);
502 // If the previous file was deleted, or we get an IO error
503 // reading the file, then we'll just use `None` as the
504 // prev_key_map, which will force the code to be recompiled.
506 if path.exists() { ThinLTOKeysMap::load_from_file(&path).ok() } else { None };
507 let curr = ThinLTOKeysMap::from_thin_lto_modules(&data, &thin_modules, &module_names);
508 (Some(path), prev, curr)
510 // If we don't compile incrementally, we don't need to load the
511 // import data from LLVM.
512 assert!(green_modules.is_empty());
513 let curr = ThinLTOKeysMap::default();
516 info!("thin LTO cache key map loaded");
517 info!("prev_key_map: {:#?}", prev_key_map);
518 info!("curr_key_map: {:#?}", curr_key_map);
520 // Throw our data in an `Arc` as we'll be sharing it across threads. We
521 // also put all memory referenced by the C++ data (buffers, ids, etc)
522 // into the arc as well. After this we'll create a thin module
523 // codegen per module in this data.
524 let shared = Arc::new(ThinShared {
527 serialized_modules: serialized,
531 let mut copy_jobs = vec![];
532 let mut opt_jobs = vec![];
534 info!("checking which modules can be-reused and which have to be re-optimized.");
535 for (module_index, module_name) in shared.module_names.iter().enumerate() {
536 let module_name = module_name_to_str(module_name);
537 if let (Some(prev_key_map), true) =
538 (prev_key_map.as_ref(), green_modules.contains_key(module_name))
540 assert!(cgcx.incr_comp_session_dir.is_some());
542 // If a module exists in both the current and the previous session,
543 // and has the same LTO cache key in both sessions, then we can re-use it
544 if prev_key_map.keys.get(module_name) == curr_key_map.keys.get(module_name) {
545 let work_product = green_modules[module_name].clone();
546 copy_jobs.push(work_product);
547 info!(" - {}: re-used", module_name);
548 assert!(cgcx.incr_comp_session_dir.is_some());
549 cgcx.cgu_reuse_tracker.set_actual_reuse(module_name, CguReuse::PostLto);
554 info!(" - {}: re-compiled", module_name);
555 opt_jobs.push(LtoModuleCodegen::Thin(ThinModule {
556 shared: shared.clone(),
561 // Save the current ThinLTO import information for the next compilation
562 // session, overwriting the previous serialized data (if any).
563 if let Some(path) = key_map_path {
564 if let Err(err) = curr_key_map.save_to_file(&path) {
565 let msg = format!("Error while writing ThinLTO key data: {}", err);
566 return Err(write::llvm_err(diag_handler, &msg));
570 Ok((opt_jobs, copy_jobs))
574 pub(crate) fn run_pass_manager(
575 cgcx: &CodegenContext<LlvmCodegenBackend>,
576 diag_handler: &Handler,
577 module: &mut ModuleCodegen<ModuleLlvm>,
579 ) -> Result<(), FatalError> {
580 let _timer = cgcx.prof.verbose_generic_activity_with_arg("LLVM_lto_optimize", &*module.name);
581 let config = cgcx.config(module.kind);
583 // Now we have one massive module inside of llmod. Time to run the
584 // LTO-specific optimization passes that LLVM provides.
586 // This code is based off the code found in llvm's LTO code generator:
587 // llvm/lib/LTO/LTOCodeGenerator.cpp
588 debug!("running the pass manager");
590 if !llvm::LLVMRustHasModuleFlag(
591 module.module_llvm.llmod(),
592 "LTOPostLink".as_ptr().cast(),
595 llvm::LLVMRustAddModuleFlag(
596 module.module_llvm.llmod(),
597 llvm::LLVMModFlagBehavior::Error,
598 "LTOPostLink\0".as_ptr().cast(),
602 let opt_stage = if thin { llvm::OptStage::ThinLTO } else { llvm::OptStage::FatLTO };
603 let opt_level = config.opt_level.unwrap_or(config::OptLevel::No);
604 write::llvm_optimize(cgcx, diag_handler, module, config, opt_level, opt_stage)?;
610 pub struct ModuleBuffer(&'static mut llvm::ModuleBuffer);
612 unsafe impl Send for ModuleBuffer {}
613 unsafe impl Sync for ModuleBuffer {}
616 pub fn new(m: &llvm::Module) -> ModuleBuffer {
617 ModuleBuffer(unsafe { llvm::LLVMRustModuleBufferCreate(m) })
621 impl ModuleBufferMethods for ModuleBuffer {
622 fn data(&self) -> &[u8] {
624 let ptr = llvm::LLVMRustModuleBufferPtr(self.0);
625 let len = llvm::LLVMRustModuleBufferLen(self.0);
626 slice::from_raw_parts(ptr, len)
631 impl Drop for ModuleBuffer {
634 llvm::LLVMRustModuleBufferFree(&mut *(self.0 as *mut _));
639 pub struct ThinData(&'static mut llvm::ThinLTOData);
641 unsafe impl Send for ThinData {}
642 unsafe impl Sync for ThinData {}
644 impl Drop for ThinData {
647 llvm::LLVMRustFreeThinLTOData(&mut *(self.0 as *mut _));
652 pub struct ThinBuffer(&'static mut llvm::ThinLTOBuffer);
654 unsafe impl Send for ThinBuffer {}
655 unsafe impl Sync for ThinBuffer {}
658 pub fn new(m: &llvm::Module, is_thin: bool) -> ThinBuffer {
660 let buffer = llvm::LLVMRustThinLTOBufferCreate(m, is_thin);
666 impl ThinBufferMethods for ThinBuffer {
667 fn data(&self) -> &[u8] {
669 let ptr = llvm::LLVMRustThinLTOBufferPtr(self.0) as *const _;
670 let len = llvm::LLVMRustThinLTOBufferLen(self.0);
671 slice::from_raw_parts(ptr, len)
676 impl Drop for ThinBuffer {
679 llvm::LLVMRustThinLTOBufferFree(&mut *(self.0 as *mut _));
684 pub unsafe fn optimize_thin_module(
685 thin_module: ThinModule<LlvmCodegenBackend>,
686 cgcx: &CodegenContext<LlvmCodegenBackend>,
687 ) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
688 let diag_handler = cgcx.create_diag_handler();
690 let module_name = &thin_module.shared.module_names[thin_module.idx];
691 let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, module_name.to_str().unwrap());
693 (cgcx.tm_factory)(tm_factory_config).map_err(|e| write::llvm_err(&diag_handler, &e))?;
695 // Right now the implementation we've got only works over serialized
696 // modules, so we create a fresh new LLVM context and parse the module
697 // into that context. One day, however, we may do this for upstream
698 // crates but for locally codegened modules we may be able to reuse
699 // that LLVM Context and Module.
700 let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
701 let llmod_raw = parse_module(llcx, module_name, thin_module.data(), &diag_handler)? as *const _;
702 let mut module = ModuleCodegen {
703 module_llvm: ModuleLlvm { llmod_raw, llcx, tm },
704 name: thin_module.name().to_string(),
705 kind: ModuleKind::Regular,
708 let target = &*module.module_llvm.tm;
709 let llmod = module.module_llvm.llmod();
710 save_temp_bitcode(cgcx, &module, "thin-lto-input");
712 // Before we do much else find the "main" `DICompileUnit` that we'll be
713 // using below. If we find more than one though then rustc has changed
714 // in a way we're not ready for, so generate an ICE by returning
716 let mut cu1 = ptr::null_mut();
717 let mut cu2 = ptr::null_mut();
718 llvm::LLVMRustThinLTOGetDICompileUnit(llmod, &mut cu1, &mut cu2);
720 let msg = "multiple source DICompileUnits found";
721 return Err(write::llvm_err(&diag_handler, msg));
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!
730 // You can find some more comments about these functions in the LLVM
731 // bindings we've got (currently `PassWrapper.cpp`)
734 cgcx.prof.generic_activity_with_arg("LLVM_thin_lto_rename", thin_module.name());
735 if !llvm::LLVMRustPrepareThinLTORename(thin_module.shared.data.0, llmod, target) {
736 let msg = "failed to prepare thin LTO module";
737 return Err(write::llvm_err(&diag_handler, msg));
739 save_temp_bitcode(cgcx, &module, "thin-lto-after-rename");
745 .generic_activity_with_arg("LLVM_thin_lto_resolve_weak", thin_module.name());
746 if !llvm::LLVMRustPrepareThinLTOResolveWeak(thin_module.shared.data.0, llmod) {
747 let msg = "failed to prepare thin LTO module";
748 return Err(write::llvm_err(&diag_handler, msg));
750 save_temp_bitcode(cgcx, &module, "thin-lto-after-resolve");
756 .generic_activity_with_arg("LLVM_thin_lto_internalize", thin_module.name());
757 if !llvm::LLVMRustPrepareThinLTOInternalize(thin_module.shared.data.0, llmod) {
758 let msg = "failed to prepare thin LTO module";
759 return Err(write::llvm_err(&diag_handler, msg));
761 save_temp_bitcode(cgcx, &module, "thin-lto-after-internalize");
766 cgcx.prof.generic_activity_with_arg("LLVM_thin_lto_import", thin_module.name());
767 if !llvm::LLVMRustPrepareThinLTOImport(thin_module.shared.data.0, llmod, target) {
768 let msg = "failed to prepare thin LTO module";
769 return Err(write::llvm_err(&diag_handler, msg));
771 save_temp_bitcode(cgcx, &module, "thin-lto-after-import");
774 // Ok now this is a bit unfortunate. This is also something you won't
775 // find upstream in LLVM's ThinLTO passes! This is a hack for now to
776 // work around bugs in LLVM.
778 // First discovered in #45511 it was found that as part of ThinLTO
779 // importing passes LLVM will import `DICompileUnit` metadata
780 // information across modules. This means that we'll be working with one
781 // LLVM module that has multiple `DICompileUnit` instances in it (a
782 // bunch of `llvm.dbg.cu` members). Unfortunately there's a number of
783 // bugs in LLVM's backend which generates invalid DWARF in a situation
786 // https://bugs.llvm.org/show_bug.cgi?id=35212
787 // https://bugs.llvm.org/show_bug.cgi?id=35562
789 // While the first bug there is fixed the second ended up causing #46346
790 // which was basically a resurgence of #45511 after LLVM's bug 35212 was
793 // This function below is a huge hack around this problem. The function
794 // below is defined in `PassWrapper.cpp` and will basically "merge"
795 // all `DICompileUnit` instances in a module. Basically it'll take all
796 // the objects, rewrite all pointers of `DISubprogram` to point to the
797 // first `DICompileUnit`, and then delete all the other units.
799 // This is probably mangling to the debug info slightly (but hopefully
800 // not too much) but for now at least gets LLVM to emit valid DWARF (or
801 // so it appears). Hopefully we can remove this once upstream bugs are
806 .generic_activity_with_arg("LLVM_thin_lto_patch_debuginfo", thin_module.name());
807 llvm::LLVMRustThinLTOPatchDICompileUnit(llmod, cu1);
808 save_temp_bitcode(cgcx, &module, "thin-lto-after-patch");
811 // Alright now that we've done everything related to the ThinLTO
812 // analysis it's time to run some optimizations! Here we use the same
813 // `run_pass_manager` as the "fat" LTO above except that we tell it to
814 // populate a thin-specific pass manager, which presumably LLVM treats a
815 // little differently.
817 info!("running thin lto passes over {}", module.name);
818 run_pass_manager(cgcx, &diag_handler, &mut module, true)?;
819 save_temp_bitcode(cgcx, &module, "thin-lto-after-pm");
825 /// Maps LLVM module identifiers to their corresponding LLVM LTO cache keys
826 #[derive(Debug, Default)]
827 pub struct ThinLTOKeysMap {
828 // key = llvm name of importing module, value = LLVM cache key
829 keys: FxHashMap<String, String>,
832 impl ThinLTOKeysMap {
833 fn save_to_file(&self, path: &Path) -> io::Result<()> {
835 let file = File::create(path)?;
836 let mut writer = io::BufWriter::new(file);
837 for (module, key) in &self.keys {
838 writeln!(writer, "{} {}", module, key)?;
843 fn load_from_file(path: &Path) -> io::Result<Self> {
844 use std::io::BufRead;
845 let mut keys = FxHashMap::default();
846 let file = File::open(path)?;
847 for line in io::BufReader::new(file).lines() {
849 let mut split = line.split(' ');
850 let module = split.next().unwrap();
851 let key = split.next().unwrap();
852 assert_eq!(split.next(), None, "Expected two space-separated values, found {:?}", line);
853 keys.insert(module.to_string(), key.to_string());
858 fn from_thin_lto_modules(
860 modules: &[llvm::ThinLTOModule],
863 let keys = iter::zip(modules, names)
864 .map(|(module, name)| {
865 let key = build_string(|rust_str| unsafe {
866 llvm::LLVMRustComputeLTOCacheKey(rust_str, module.identifier, data.0);
868 .expect("Invalid ThinLTO module key");
869 (name.clone().into_string().unwrap(), key)
876 fn module_name_to_str(c_str: &CStr) -> &str {
877 c_str.to_str().unwrap_or_else(|e| {
878 bug!("Encountered non-utf8 LLVM module name `{}`: {}", c_str.to_string_lossy(), e)
882 pub fn parse_module<'a>(
883 cx: &'a llvm::Context,
886 diag_handler: &Handler,
887 ) -> Result<&'a llvm::Module, FatalError> {
889 llvm::LLVMRustParseBitcodeForLTO(cx, data.as_ptr(), data.len(), name.as_ptr()).ok_or_else(
891 let msg = "failed to parse bitcode for LTO module";
892 write::llvm_err(diag_handler, msg)