1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use back::bytecode::{DecodedBytecode, RLIB_BYTECODE_EXTENSION};
12 use back::symbol_export;
13 use back::write::{ModuleConfig, with_llvm_pmb, CodegenContext};
14 use back::write::{self, DiagnosticHandlers, pre_lto_bitcode_filename};
15 use errors::{FatalError, Handler};
16 use llvm::archive_ro::ArchiveRO;
17 use llvm::{True, False};
20 use rustc::dep_graph::WorkProduct;
21 use rustc::dep_graph::cgu_reuse_tracker::CguReuse;
22 use rustc::hir::def_id::LOCAL_CRATE;
23 use rustc::middle::exported_symbols::SymbolExportLevel;
24 use rustc::session::config::{self, Lto};
25 use rustc::util::common::time_ext;
26 use rustc_data_structures::fx::FxHashMap;
27 use time_graph::Timeline;
28 use {ModuleCodegen, ModuleLlvm, ModuleKind};
32 use std::ffi::{CStr, CString};
38 pub fn crate_type_allows_lto(crate_type: config::CrateType) -> bool {
40 config::CrateType::Executable |
41 config::CrateType::Staticlib |
42 config::CrateType::Cdylib => true,
44 config::CrateType::Dylib |
45 config::CrateType::Rlib |
46 config::CrateType::ProcMacro => false,
50 pub(crate) enum LtoModuleCodegen {
52 module: Option<ModuleCodegen>,
53 _serialized_bitcode: Vec<SerializedModule>,
59 impl LtoModuleCodegen {
60 pub fn name(&self) -> &str {
62 LtoModuleCodegen::Fat { .. } => "everything",
63 LtoModuleCodegen::Thin(ref m) => m.name(),
67 /// Optimize this module within the given codegen context.
69 /// This function is unsafe as it'll return a `ModuleCodegen` still
70 /// points to LLVM data structures owned by this `LtoModuleCodegen`.
71 /// It's intended that the module returned is immediately code generated and
72 /// dropped, and then this LTO module is dropped.
73 pub(crate) unsafe fn optimize(&mut self,
74 cgcx: &CodegenContext,
75 timeline: &mut Timeline)
76 -> Result<ModuleCodegen, FatalError>
79 LtoModuleCodegen::Fat { ref mut module, .. } => {
80 let module = module.take().unwrap();
82 let config = cgcx.config(module.kind);
83 run_pass_manager(cgcx, &module, config, false);
84 timeline.record("fat-done");
88 LtoModuleCodegen::Thin(ref mut thin) => thin.optimize(cgcx, timeline),
92 /// A "gauge" of how costly it is to optimize this module, used to sort
93 /// biggest modules first.
94 pub fn cost(&self) -> u64 {
96 // Only one module with fat LTO, so the cost doesn't matter.
97 LtoModuleCodegen::Fat { .. } => 0,
98 LtoModuleCodegen::Thin(ref m) => m.cost(),
103 /// Performs LTO, which in the case of full LTO means merging all modules into
104 /// a single one and returning it for further optimizing. For ThinLTO, it will
105 /// do the global analysis necessary and return two lists, one of the modules
106 /// the need optimization and another for modules that can simply be copied over
107 /// from the incr. comp. cache.
108 pub(crate) fn run(cgcx: &CodegenContext,
109 modules: Vec<ModuleCodegen>,
110 cached_modules: Vec<(SerializedModule, WorkProduct)>,
111 timeline: &mut Timeline)
112 -> Result<(Vec<LtoModuleCodegen>, Vec<WorkProduct>), FatalError>
114 let diag_handler = cgcx.create_diag_handler();
115 let export_threshold = match cgcx.lto {
116 // We're just doing LTO for our one crate
117 Lto::ThinLocal => SymbolExportLevel::Rust,
119 // We're doing LTO for the entire crate graph
120 Lto::Fat | Lto::Thin => {
121 symbol_export::crates_export_threshold(&cgcx.crate_types)
124 Lto::No => panic!("didn't request LTO but we're doing LTO"),
127 let symbol_filter = &|&(ref name, level): &(String, SymbolExportLevel)| {
128 if level.is_below_threshold(export_threshold) {
129 let mut bytes = Vec::with_capacity(name.len() + 1);
130 bytes.extend(name.bytes());
131 Some(CString::new(bytes).unwrap())
136 let exported_symbols = cgcx.exported_symbols
137 .as_ref().expect("needs exported symbols for LTO");
138 let mut symbol_white_list = exported_symbols[&LOCAL_CRATE]
140 .filter_map(symbol_filter)
141 .collect::<Vec<CString>>();
142 timeline.record("whitelist");
143 info!("{} symbols to preserve in this crate", symbol_white_list.len());
145 // If we're performing LTO for the entire crate graph, then for each of our
146 // upstream dependencies, find the corresponding rlib and load the bitcode
149 // We save off all the bytecode and LLVM module ids for later processing
150 // with either fat or thin LTO
151 let mut upstream_modules = Vec::new();
152 if cgcx.lto != Lto::ThinLocal {
153 if cgcx.opts.cg.prefer_dynamic {
154 diag_handler.struct_err("cannot prefer dynamic linking when performing LTO")
155 .note("only 'staticlib', 'bin', and 'cdylib' outputs are \
158 return Err(FatalError)
161 // Make sure we actually can run LTO
162 for crate_type in cgcx.crate_types.iter() {
163 if !crate_type_allows_lto(*crate_type) {
164 let e = diag_handler.fatal("lto can only be run for executables, cdylibs and \
165 static library outputs");
170 for &(cnum, ref path) in cgcx.each_linked_rlib_for_lto.iter() {
171 let exported_symbols = cgcx.exported_symbols
172 .as_ref().expect("needs exported symbols for LTO");
173 symbol_white_list.extend(
174 exported_symbols[&cnum]
176 .filter_map(symbol_filter));
178 let archive = ArchiveRO::open(&path).expect("wanted an rlib");
179 let bytecodes = archive.iter().filter_map(|child| {
180 child.ok().and_then(|c| c.name().map(|name| (name, c)))
181 }).filter(|&(name, _)| name.ends_with(RLIB_BYTECODE_EXTENSION));
182 for (name, data) in bytecodes {
183 info!("adding bytecode {}", name);
184 let bc_encoded = data.data();
186 let (bc, id) = time_ext(cgcx.time_passes, None, &format!("decode {}", name), || {
187 match DecodedBytecode::new(bc_encoded) {
188 Ok(b) => Ok((b.bytecode(), b.identifier().to_string())),
189 Err(e) => Err(diag_handler.fatal(&e)),
192 let bc = SerializedModule::FromRlib(bc);
193 upstream_modules.push((bc, CString::new(id).unwrap()));
195 timeline.record(&format!("load: {}", path.display()));
199 let symbol_white_list = symbol_white_list.iter()
201 .collect::<Vec<_>>();
204 assert!(cached_modules.is_empty());
205 let opt_jobs = fat_lto(cgcx,
211 opt_jobs.map(|opt_jobs| (opt_jobs, vec![]))
215 if cgcx.opts.debugging_opts.cross_lang_lto.enabled() {
216 unreachable!("We should never reach this case if the LTO step \
217 is deferred to the linker");
227 Lto::No => unreachable!(),
231 fn fat_lto(cgcx: &CodegenContext,
232 diag_handler: &Handler,
233 mut modules: Vec<ModuleCodegen>,
234 mut serialized_modules: Vec<(SerializedModule, CString)>,
235 symbol_white_list: &[*const libc::c_char],
236 timeline: &mut Timeline)
237 -> Result<Vec<LtoModuleCodegen>, FatalError>
239 info!("going for a fat lto");
241 // Find the "costliest" module and merge everything into that codegen unit.
242 // All the other modules will be serialized and reparsed into the new
243 // context, so this hopefully avoids serializing and parsing the largest
246 // Additionally use a regular module as the base here to ensure that various
247 // file copy operations in the backend work correctly. The only other kind
248 // of module here should be an allocator one, and if your crate is smaller
249 // than the allocator module then the size doesn't really matter anyway.
250 let (_, costliest_module) = modules.iter()
252 .filter(|&(_, module)| module.kind == ModuleKind::Regular)
255 llvm::LLVMRustModuleCost(module.module_llvm.llmod())
260 .expect("must be codegen'ing at least one module");
261 let module = modules.remove(costliest_module);
262 let mut serialized_bitcode = Vec::new();
264 let (llcx, llmod) = {
265 let llvm = &module.module_llvm;
266 (&llvm.llcx, llvm.llmod())
268 info!("using {:?} as a base module", module.name);
270 // The linking steps below may produce errors and diagnostics within LLVM
271 // which we'd like to handle and print, so set up our diagnostic handlers
272 // (which get unregistered when they go out of scope below).
273 let _handler = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
275 // For all other modules we codegened we'll need to link them into our own
276 // bitcode. All modules were codegened in their own LLVM context, however,
277 // and we want to move everything to the same LLVM context. Currently the
278 // way we know of to do that is to serialize them to a string and them parse
279 // them later. Not great but hey, that's why it's "fat" LTO, right?
280 for module in modules {
281 let buffer = ModuleBuffer::new(module.module_llvm.llmod());
282 let llmod_id = CString::new(&module.name[..]).unwrap();
283 serialized_modules.push((SerializedModule::Local(buffer), llmod_id));
286 // For all serialized bitcode files we parse them and link them in as we did
287 // above, this is all mostly handled in C++. Like above, though, we don't
288 // know much about the memory management here so we err on the side of being
289 // save and persist everything with the original module.
290 let mut linker = Linker::new(llmod);
291 for (bc_decoded, name) in serialized_modules {
292 info!("linking {:?}", name);
293 time_ext(cgcx.time_passes, None, &format!("ll link {:?}", name), || {
294 let data = bc_decoded.data();
295 linker.add(&data).map_err(|()| {
296 let msg = format!("failed to load bc of {:?}", name);
297 write::llvm_err(&diag_handler, msg)
300 timeline.record(&format!("link {:?}", name));
301 serialized_bitcode.push(bc_decoded);
304 cgcx.save_temp_bitcode(&module, "lto.input");
306 // Internalize everything that *isn't* in our whitelist to help strip out
307 // more modules and such
309 let ptr = symbol_white_list.as_ptr();
310 llvm::LLVMRustRunRestrictionPass(llmod,
311 ptr as *const *const libc::c_char,
312 symbol_white_list.len() as libc::size_t);
313 cgcx.save_temp_bitcode(&module, "lto.after-restriction");
316 if cgcx.no_landing_pads {
318 llvm::LLVMRustMarkAllFunctionsNounwind(llmod);
320 cgcx.save_temp_bitcode(&module, "lto.after-nounwind");
322 timeline.record("passes");
325 Ok(vec![LtoModuleCodegen::Fat {
326 module: Some(module),
327 _serialized_bitcode: serialized_bitcode,
331 struct Linker<'a>(&'a mut llvm::Linker<'a>);
334 fn new(llmod: &'a llvm::Module) -> Self {
335 unsafe { Linker(llvm::LLVMRustLinkerNew(llmod)) }
338 fn add(&mut self, bytecode: &[u8]) -> Result<(), ()> {
340 if llvm::LLVMRustLinkerAdd(self.0,
341 bytecode.as_ptr() as *const libc::c_char,
351 impl Drop for Linker<'a> {
353 unsafe { llvm::LLVMRustLinkerFree(&mut *(self.0 as *mut _)); }
357 /// Prepare "thin" LTO to get run on these modules.
359 /// The general structure of ThinLTO is quite different from the structure of
360 /// "fat" LTO above. With "fat" LTO all LLVM modules in question are merged into
361 /// one giant LLVM module, and then we run more optimization passes over this
362 /// big module after internalizing most symbols. Thin LTO, on the other hand,
363 /// avoid this large bottleneck through more targeted optimization.
365 /// At a high level Thin LTO looks like:
367 /// 1. Prepare a "summary" of each LLVM module in question which describes
368 /// the values inside, cost of the values, etc.
369 /// 2. Merge the summaries of all modules in question into one "index"
370 /// 3. Perform some global analysis on this index
371 /// 4. For each module, use the index and analysis calculated previously to
372 /// perform local transformations on the module, for example inlining
373 /// small functions from other modules.
374 /// 5. Run thin-specific optimization passes over each module, and then code
375 /// generate everything at the end.
377 /// The summary for each module is intended to be quite cheap, and the global
378 /// index is relatively quite cheap to create as well. As a result, the goal of
379 /// ThinLTO is to reduce the bottleneck on LTO and enable LTO to be used in more
380 /// situations. For example one cheap optimization is that we can parallelize
381 /// all codegen modules, easily making use of all the cores on a machine.
383 /// With all that in mind, the function here is designed at specifically just
384 /// calculating the *index* for ThinLTO. This index will then be shared amongst
385 /// all of the `LtoModuleCodegen` units returned below and destroyed once
386 /// they all go out of scope.
387 fn thin_lto(cgcx: &CodegenContext,
388 diag_handler: &Handler,
389 modules: Vec<ModuleCodegen>,
390 serialized_modules: Vec<(SerializedModule, CString)>,
391 cached_modules: Vec<(SerializedModule, WorkProduct)>,
392 symbol_white_list: &[*const libc::c_char],
393 timeline: &mut Timeline)
394 -> Result<(Vec<LtoModuleCodegen>, Vec<WorkProduct>), FatalError>
397 info!("going for that thin, thin LTO");
399 let green_modules: FxHashMap<_, _> = cached_modules
401 .map(|&(_, ref wp)| (wp.cgu_name.clone(), wp.clone()))
404 let mut thin_buffers = Vec::new();
405 let mut module_names = Vec::new();
406 let mut thin_modules = Vec::new();
408 // FIXME: right now, like with fat LTO, we serialize all in-memory
409 // modules before working with them and ThinLTO. We really
410 // shouldn't do this, however, and instead figure out how to
411 // extract a summary from an in-memory module and then merge that
412 // into the global index. It turns out that this loop is by far
413 // the most expensive portion of this small bit of global
415 for (i, module) in modules.iter().enumerate() {
416 info!("local module: {} - {}", i, module.name);
417 let name = CString::new(module.name.clone()).unwrap();
418 let buffer = ThinBuffer::new(module.module_llvm.llmod());
420 // We emit the module after having serialized it into a ThinBuffer
421 // because only then it will contain the ThinLTO module summary.
422 if let Some(ref incr_comp_session_dir) = cgcx.incr_comp_session_dir {
423 if cgcx.config(module.kind).emit_pre_thin_lto_bc {
424 let path = incr_comp_session_dir
425 .join(pre_lto_bitcode_filename(&module.name));
427 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
428 panic!("Error writing pre-lto-bitcode file `{}`: {}",
435 thin_modules.push(llvm::ThinLTOModule {
436 identifier: name.as_ptr(),
437 data: buffer.data().as_ptr(),
438 len: buffer.data().len(),
440 thin_buffers.push(buffer);
441 module_names.push(name);
442 timeline.record(&module.name);
445 // FIXME: All upstream crates are deserialized internally in the
446 // function below to extract their summary and modules. Note that
447 // unlike the loop above we *must* decode and/or read something
448 // here as these are all just serialized files on disk. An
449 // improvement, however, to make here would be to store the
450 // module summary separately from the actual module itself. Right
451 // now this is store in one large bitcode file, and the entire
452 // file is deflate-compressed. We could try to bypass some of the
453 // decompression by storing the index uncompressed and only
454 // lazily decompressing the bytecode if necessary.
456 // Note that truly taking advantage of this optimization will
457 // likely be further down the road. We'd have to implement
458 // incremental ThinLTO first where we could actually avoid
459 // looking at upstream modules entirely sometimes (the contents,
460 // we must always unconditionally look at the index).
461 let mut serialized = Vec::new();
463 let cached_modules = cached_modules.into_iter().map(|(sm, wp)| {
464 (sm, CString::new(wp.cgu_name).unwrap())
467 for (module, name) in serialized_modules.into_iter().chain(cached_modules) {
468 info!("upstream or cached module {:?}", name);
469 thin_modules.push(llvm::ThinLTOModule {
470 identifier: name.as_ptr(),
471 data: module.data().as_ptr(),
472 len: module.data().len(),
474 serialized.push(module);
475 module_names.push(name);
479 assert_eq!(thin_modules.len(), module_names.len());
481 // Delegate to the C++ bindings to create some data here. Once this is a
482 // tried-and-true interface we may wish to try to upstream some of this
483 // to LLVM itself, right now we reimplement a lot of what they do
485 let data = llvm::LLVMRustCreateThinLTOData(
486 thin_modules.as_ptr(),
487 thin_modules.len() as u32,
488 symbol_white_list.as_ptr(),
489 symbol_white_list.len() as u32,
491 write::llvm_err(&diag_handler, "failed to prepare thin LTO context".to_string())
494 info!("thin LTO data created");
495 timeline.record("data");
497 let import_map = if cgcx.incr_comp_session_dir.is_some() {
498 ThinLTOImports::from_thin_lto_data(data)
500 // If we don't compile incrementally, we don't need to load the
501 // import data from LLVM.
502 assert!(green_modules.is_empty());
503 ThinLTOImports::default()
505 info!("thin LTO import map loaded");
506 timeline.record("import-map-loaded");
508 let data = ThinData(data);
510 // Throw our data in an `Arc` as we'll be sharing it across threads. We
511 // also put all memory referenced by the C++ data (buffers, ids, etc)
512 // into the arc as well. After this we'll create a thin module
513 // codegen per module in this data.
514 let shared = Arc::new(ThinShared {
517 serialized_modules: serialized,
521 let mut copy_jobs = vec![];
522 let mut opt_jobs = vec![];
524 info!("checking which modules can be-reused and which have to be re-optimized.");
525 for (module_index, module_name) in shared.module_names.iter().enumerate() {
526 let module_name = module_name_to_str(module_name);
528 // If the module hasn't changed and none of the modules it imports
529 // from has changed, we can re-use the post-ThinLTO version of the
531 if green_modules.contains_key(module_name) {
532 let imports_all_green = import_map.modules_imported_by(module_name)
534 .all(|imported_module| green_modules.contains_key(imported_module));
536 if imports_all_green {
537 let work_product = green_modules[module_name].clone();
538 copy_jobs.push(work_product);
539 info!(" - {}: re-used", module_name);
540 cgcx.cgu_reuse_tracker.set_actual_reuse(module_name,
546 info!(" - {}: re-compiled", module_name);
547 opt_jobs.push(LtoModuleCodegen::Thin(ThinModule {
548 shared: shared.clone(),
553 Ok((opt_jobs, copy_jobs))
557 fn run_pass_manager(cgcx: &CodegenContext,
558 module: &ModuleCodegen,
559 config: &ModuleConfig,
561 // Now we have one massive module inside of llmod. Time to run the
562 // LTO-specific optimization passes that LLVM provides.
564 // This code is based off the code found in llvm's LTO code generator:
565 // tools/lto/LTOCodeGenerator.cpp
566 debug!("running the pass manager");
568 let pm = llvm::LLVMCreatePassManager();
569 let llmod = module.module_llvm.llmod();
570 llvm::LLVMRustAddAnalysisPasses(module.module_llvm.tm, pm, llmod);
572 if config.verify_llvm_ir {
573 let pass = llvm::LLVMRustFindAndCreatePass("verify\0".as_ptr() as *const _);
574 llvm::LLVMRustAddPass(pm, pass.unwrap());
577 // When optimizing for LTO we don't actually pass in `-O0`, but we force
578 // it to always happen at least with `-O1`.
580 // With ThinLTO we mess around a lot with symbol visibility in a way
581 // that will actually cause linking failures if we optimize at O0 which
582 // notable is lacking in dead code elimination. To ensure we at least
583 // get some optimizations and correctly link we forcibly switch to `-O1`
584 // to get dead code elimination.
586 // Note that in general this shouldn't matter too much as you typically
587 // only turn on ThinLTO when you're compiling with optimizations
589 let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
590 let opt_level = match opt_level {
591 llvm::CodeGenOptLevel::None => llvm::CodeGenOptLevel::Less,
594 with_llvm_pmb(llmod, config, opt_level, false, &mut |b| {
596 if !llvm::LLVMRustPassManagerBuilderPopulateThinLTOPassManager(b, pm) {
597 panic!("this version of LLVM does not support ThinLTO");
600 llvm::LLVMPassManagerBuilderPopulateLTOPassManager(b, pm,
601 /* Internalize = */ False,
602 /* RunInliner = */ True);
606 if config.verify_llvm_ir {
607 let pass = llvm::LLVMRustFindAndCreatePass("verify\0".as_ptr() as *const _);
608 llvm::LLVMRustAddPass(pm, pass.unwrap());
611 time_ext(cgcx.time_passes, None, "LTO passes", ||
612 llvm::LLVMRunPassManager(pm, llmod));
614 llvm::LLVMDisposePassManager(pm);
619 pub enum SerializedModule {
622 FromUncompressedFile(memmap::Mmap),
625 impl SerializedModule {
626 fn data(&self) -> &[u8] {
628 SerializedModule::Local(ref m) => m.data(),
629 SerializedModule::FromRlib(ref m) => m,
630 SerializedModule::FromUncompressedFile(ref m) => m,
635 pub struct ModuleBuffer(&'static mut llvm::ModuleBuffer);
637 unsafe impl Send for ModuleBuffer {}
638 unsafe impl Sync for ModuleBuffer {}
641 pub fn new(m: &llvm::Module) -> ModuleBuffer {
642 ModuleBuffer(unsafe {
643 llvm::LLVMRustModuleBufferCreate(m)
647 pub fn data(&self) -> &[u8] {
649 let ptr = llvm::LLVMRustModuleBufferPtr(self.0);
650 let len = llvm::LLVMRustModuleBufferLen(self.0);
651 slice::from_raw_parts(ptr, len)
656 impl Drop for ModuleBuffer {
658 unsafe { llvm::LLVMRustModuleBufferFree(&mut *(self.0 as *mut _)); }
662 pub struct ThinModule {
663 shared: Arc<ThinShared>,
669 thin_buffers: Vec<ThinBuffer>,
670 serialized_modules: Vec<SerializedModule>,
671 module_names: Vec<CString>,
674 struct ThinData(&'static mut llvm::ThinLTOData);
676 unsafe impl Send for ThinData {}
677 unsafe impl Sync for ThinData {}
679 impl Drop for ThinData {
682 llvm::LLVMRustFreeThinLTOData(&mut *(self.0 as *mut _));
687 pub struct ThinBuffer(&'static mut llvm::ThinLTOBuffer);
689 unsafe impl Send for ThinBuffer {}
690 unsafe impl Sync for ThinBuffer {}
693 pub fn new(m: &llvm::Module) -> ThinBuffer {
695 let buffer = llvm::LLVMRustThinLTOBufferCreate(m);
700 pub fn data(&self) -> &[u8] {
702 let ptr = llvm::LLVMRustThinLTOBufferPtr(self.0) as *const _;
703 let len = llvm::LLVMRustThinLTOBufferLen(self.0);
704 slice::from_raw_parts(ptr, len)
709 impl Drop for ThinBuffer {
712 llvm::LLVMRustThinLTOBufferFree(&mut *(self.0 as *mut _));
718 fn name(&self) -> &str {
719 self.shared.module_names[self.idx].to_str().unwrap()
722 fn cost(&self) -> u64 {
723 // Yes, that's correct, we're using the size of the bytecode as an
724 // indicator for how costly this codegen unit is.
725 self.data().len() as u64
728 fn data(&self) -> &[u8] {
729 let a = self.shared.thin_buffers.get(self.idx).map(|b| b.data());
730 a.unwrap_or_else(|| {
731 let len = self.shared.thin_buffers.len();
732 self.shared.serialized_modules[self.idx - len].data()
736 unsafe fn optimize(&mut self, cgcx: &CodegenContext, timeline: &mut Timeline)
737 -> Result<ModuleCodegen, FatalError>
739 let diag_handler = cgcx.create_diag_handler();
740 let tm = (cgcx.tm_factory)().map_err(|e| {
741 write::llvm_err(&diag_handler, e)
744 // Right now the implementation we've got only works over serialized
745 // modules, so we create a fresh new LLVM context and parse the module
746 // into that context. One day, however, we may do this for upstream
747 // crates but for locally codegened modules we may be able to reuse
748 // that LLVM Context and Module.
749 let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
750 let llmod_raw = llvm::LLVMRustParseBitcodeForThinLTO(
752 self.data().as_ptr(),
754 self.shared.module_names[self.idx].as_ptr(),
756 let msg = "failed to parse bitcode for thin LTO module".to_string();
757 write::llvm_err(&diag_handler, msg)
759 let module = ModuleCodegen {
760 module_llvm: ModuleLlvm {
765 name: self.name().to_string(),
766 kind: ModuleKind::Regular,
769 let llmod = module.module_llvm.llmod();
770 cgcx.save_temp_bitcode(&module, "thin-lto-input");
772 // Before we do much else find the "main" `DICompileUnit` that we'll be
773 // using below. If we find more than one though then rustc has changed
774 // in a way we're not ready for, so generate an ICE by returning
776 let mut cu1 = ptr::null_mut();
777 let mut cu2 = ptr::null_mut();
778 llvm::LLVMRustThinLTOGetDICompileUnit(llmod, &mut cu1, &mut cu2);
780 let msg = "multiple source DICompileUnits found".to_string();
781 return Err(write::llvm_err(&diag_handler, msg))
784 // Like with "fat" LTO, get some better optimizations if landing pads
785 // are disabled by removing all landing pads.
786 if cgcx.no_landing_pads {
787 llvm::LLVMRustMarkAllFunctionsNounwind(llmod);
788 cgcx.save_temp_bitcode(&module, "thin-lto-after-nounwind");
789 timeline.record("nounwind");
792 // Up next comes the per-module local analyses that we do for Thin LTO.
793 // Each of these functions is basically copied from the LLVM
794 // implementation and then tailored to suit this implementation. Ideally
795 // each of these would be supported by upstream LLVM but that's perhaps
796 // a patch for another day!
798 // You can find some more comments about these functions in the LLVM
799 // bindings we've got (currently `PassWrapper.cpp`)
800 if !llvm::LLVMRustPrepareThinLTORename(self.shared.data.0, llmod) {
801 let msg = "failed to prepare thin LTO module".to_string();
802 return Err(write::llvm_err(&diag_handler, msg))
804 cgcx.save_temp_bitcode(&module, "thin-lto-after-rename");
805 timeline.record("rename");
806 if !llvm::LLVMRustPrepareThinLTOResolveWeak(self.shared.data.0, llmod) {
807 let msg = "failed to prepare thin LTO module".to_string();
808 return Err(write::llvm_err(&diag_handler, msg))
810 cgcx.save_temp_bitcode(&module, "thin-lto-after-resolve");
811 timeline.record("resolve");
812 if !llvm::LLVMRustPrepareThinLTOInternalize(self.shared.data.0, llmod) {
813 let msg = "failed to prepare thin LTO module".to_string();
814 return Err(write::llvm_err(&diag_handler, msg))
816 cgcx.save_temp_bitcode(&module, "thin-lto-after-internalize");
817 timeline.record("internalize");
818 if !llvm::LLVMRustPrepareThinLTOImport(self.shared.data.0, llmod) {
819 let msg = "failed to prepare thin LTO module".to_string();
820 return Err(write::llvm_err(&diag_handler, msg))
822 cgcx.save_temp_bitcode(&module, "thin-lto-after-import");
823 timeline.record("import");
825 // Ok now this is a bit unfortunate. This is also something you won't
826 // find upstream in LLVM's ThinLTO passes! This is a hack for now to
827 // work around bugs in LLVM.
829 // First discovered in #45511 it was found that as part of ThinLTO
830 // importing passes LLVM will import `DICompileUnit` metadata
831 // information across modules. This means that we'll be working with one
832 // LLVM module that has multiple `DICompileUnit` instances in it (a
833 // bunch of `llvm.dbg.cu` members). Unfortunately there's a number of
834 // bugs in LLVM's backend which generates invalid DWARF in a situation
837 // https://bugs.llvm.org/show_bug.cgi?id=35212
838 // https://bugs.llvm.org/show_bug.cgi?id=35562
840 // While the first bug there is fixed the second ended up causing #46346
841 // which was basically a resurgence of #45511 after LLVM's bug 35212 was
844 // This function below is a huge hack around this problem. The function
845 // below is defined in `PassWrapper.cpp` and will basically "merge"
846 // all `DICompileUnit` instances in a module. Basically it'll take all
847 // the objects, rewrite all pointers of `DISubprogram` to point to the
848 // first `DICompileUnit`, and then delete all the other units.
850 // This is probably mangling to the debug info slightly (but hopefully
851 // not too much) but for now at least gets LLVM to emit valid DWARF (or
852 // so it appears). Hopefully we can remove this once upstream bugs are
854 llvm::LLVMRustThinLTOPatchDICompileUnit(llmod, cu1);
855 cgcx.save_temp_bitcode(&module, "thin-lto-after-patch");
856 timeline.record("patch");
858 // Alright now that we've done everything related to the ThinLTO
859 // analysis it's time to run some optimizations! Here we use the same
860 // `run_pass_manager` as the "fat" LTO above except that we tell it to
861 // populate a thin-specific pass manager, which presumably LLVM treats a
862 // little differently.
863 info!("running thin lto passes over {}", module.name);
864 let config = cgcx.config(module.kind);
865 run_pass_manager(cgcx, &module, config, true);
866 cgcx.save_temp_bitcode(&module, "thin-lto-after-pm");
867 timeline.record("thin-done");
874 #[derive(Debug, Default)]
875 pub struct ThinLTOImports {
876 // key = llvm name of importing module, value = list of modules it imports from
877 imports: FxHashMap<String, Vec<String>>,
880 impl ThinLTOImports {
881 fn modules_imported_by(&self, llvm_module_name: &str) -> &[String] {
882 self.imports.get(llvm_module_name).map(|v| &v[..]).unwrap_or(&[])
885 /// Load the ThinLTO import map from ThinLTOData.
886 unsafe fn from_thin_lto_data(data: *const llvm::ThinLTOData) -> ThinLTOImports {
887 unsafe extern "C" fn imported_module_callback(payload: *mut libc::c_void,
888 importing_module_name: *const libc::c_char,
889 imported_module_name: *const libc::c_char) {
890 let map = &mut* (payload as *mut ThinLTOImports);
891 let importing_module_name = CStr::from_ptr(importing_module_name);
892 let importing_module_name = module_name_to_str(&importing_module_name);
893 let imported_module_name = CStr::from_ptr(imported_module_name);
894 let imported_module_name = module_name_to_str(&imported_module_name);
896 if !map.imports.contains_key(importing_module_name) {
897 map.imports.insert(importing_module_name.to_owned(), vec![]);
901 .get_mut(importing_module_name)
903 .push(imported_module_name.to_owned());
905 let mut map = ThinLTOImports::default();
906 llvm::LLVMRustGetThinLTOModuleImports(data,
907 imported_module_callback,
908 &mut map as *mut _ as *mut libc::c_void);
913 fn module_name_to_str(c_str: &CStr) -> &str {
914 match c_str.to_str() {
917 bug!("Encountered non-utf8 LLVM module name `{}`: {}",
918 c_str.to_string_lossy(),