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::write::{ModuleConfig, with_llvm_pmb, CodegenContext};
13 use back::write::{self, DiagnosticHandlers, pre_lto_bitcode_filename};
14 use errors::{FatalError, Handler};
15 use llvm::archive_ro::ArchiveRO;
16 use llvm::{self, True, False};
18 use rustc::dep_graph::WorkProduct;
19 use rustc::dep_graph::cgu_reuse_tracker::CguReuse;
20 use rustc::hir::def_id::LOCAL_CRATE;
21 use rustc::middle::exported_symbols::SymbolExportLevel;
22 use rustc::session::config::{self, Lto};
23 use rustc::util::common::time_ext;
24 use rustc_data_structures::fx::FxHashMap;
25 use rustc_codegen_utils::symbol_export;
26 use time_graph::Timeline;
28 use rustc_codegen_ssa::{ModuleCodegen, 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<ModuleLlvm>>,
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<ModuleLlvm>, FatalError>
79 LtoModuleCodegen::Fat { ref mut module, .. } => {
80 let module = module.take().unwrap();
82 let config = cgcx.config(module.kind);
83 let llmod = module.module_llvm.llmod();
84 let tm = &*module.module_llvm.tm;
85 run_pass_manager(cgcx, tm, llmod, config, false);
86 timeline.record("fat-done");
90 LtoModuleCodegen::Thin(ref mut thin) => thin.optimize(cgcx, timeline),
94 /// A "gauge" of how costly it is to optimize this module, used to sort
95 /// biggest modules first.
96 pub fn cost(&self) -> u64 {
98 // Only one module with fat LTO, so the cost doesn't matter.
99 LtoModuleCodegen::Fat { .. } => 0,
100 LtoModuleCodegen::Thin(ref m) => m.cost(),
105 /// Performs LTO, which in the case of full LTO means merging all modules into
106 /// a single one and returning it for further optimizing. For ThinLTO, it will
107 /// do the global analysis necessary and return two lists, one of the modules
108 /// the need optimization and another for modules that can simply be copied over
109 /// from the incr. comp. cache.
110 pub(crate) fn run(cgcx: &CodegenContext,
111 modules: Vec<ModuleCodegen<ModuleLlvm>>,
112 cached_modules: Vec<(SerializedModule, WorkProduct)>,
113 timeline: &mut Timeline)
114 -> Result<(Vec<LtoModuleCodegen>, Vec<WorkProduct>), FatalError>
116 let diag_handler = cgcx.create_diag_handler();
117 let export_threshold = match cgcx.lto {
118 // We're just doing LTO for our one crate
119 Lto::ThinLocal => SymbolExportLevel::Rust,
121 // We're doing LTO for the entire crate graph
122 Lto::Fat | Lto::Thin => {
123 symbol_export::crates_export_threshold(&cgcx.crate_types)
126 Lto::No => panic!("didn't request LTO but we're doing LTO"),
129 let symbol_filter = &|&(ref name, level): &(String, SymbolExportLevel)| {
130 if level.is_below_threshold(export_threshold) {
131 let mut bytes = Vec::with_capacity(name.len() + 1);
132 bytes.extend(name.bytes());
133 Some(CString::new(bytes).unwrap())
138 let exported_symbols = cgcx.exported_symbols
139 .as_ref().expect("needs exported symbols for LTO");
140 let mut symbol_white_list = exported_symbols[&LOCAL_CRATE]
142 .filter_map(symbol_filter)
143 .collect::<Vec<CString>>();
144 timeline.record("whitelist");
145 info!("{} symbols to preserve in this crate", symbol_white_list.len());
147 // If we're performing LTO for the entire crate graph, then for each of our
148 // upstream dependencies, find the corresponding rlib and load the bitcode
151 // We save off all the bytecode and LLVM module ids for later processing
152 // with either fat or thin LTO
153 let mut upstream_modules = Vec::new();
154 if cgcx.lto != Lto::ThinLocal {
155 if cgcx.opts.cg.prefer_dynamic {
156 diag_handler.struct_err("cannot prefer dynamic linking when performing LTO")
157 .note("only 'staticlib', 'bin', and 'cdylib' outputs are \
160 return Err(FatalError)
163 // Make sure we actually can run LTO
164 for crate_type in cgcx.crate_types.iter() {
165 if !crate_type_allows_lto(*crate_type) {
166 let e = diag_handler.fatal("lto can only be run for executables, cdylibs and \
167 static library outputs");
172 for &(cnum, ref path) in cgcx.each_linked_rlib_for_lto.iter() {
173 let exported_symbols = cgcx.exported_symbols
174 .as_ref().expect("needs exported symbols for LTO");
175 symbol_white_list.extend(
176 exported_symbols[&cnum]
178 .filter_map(symbol_filter));
180 let archive = ArchiveRO::open(&path).expect("wanted an rlib");
181 let bytecodes = archive.iter().filter_map(|child| {
182 child.ok().and_then(|c| c.name().map(|name| (name, c)))
183 }).filter(|&(name, _)| name.ends_with(RLIB_BYTECODE_EXTENSION));
184 for (name, data) in bytecodes {
185 info!("adding bytecode {}", name);
186 let bc_encoded = data.data();
188 let (bc, id) = time_ext(cgcx.time_passes, None, &format!("decode {}", name), || {
189 match DecodedBytecode::new(bc_encoded) {
190 Ok(b) => Ok((b.bytecode(), b.identifier().to_string())),
191 Err(e) => Err(diag_handler.fatal(&e)),
194 let bc = SerializedModule::FromRlib(bc);
195 upstream_modules.push((bc, CString::new(id).unwrap()));
197 timeline.record(&format!("load: {}", path.display()));
201 let symbol_white_list = symbol_white_list.iter()
203 .collect::<Vec<_>>();
206 assert!(cached_modules.is_empty());
207 let opt_jobs = fat_lto(cgcx,
213 opt_jobs.map(|opt_jobs| (opt_jobs, vec![]))
217 if cgcx.opts.debugging_opts.cross_lang_lto.enabled() {
218 unreachable!("We should never reach this case if the LTO step \
219 is deferred to the linker");
229 Lto::No => unreachable!(),
233 fn fat_lto(cgcx: &CodegenContext,
234 diag_handler: &Handler,
235 mut modules: Vec<ModuleCodegen<ModuleLlvm>>,
236 mut serialized_modules: Vec<(SerializedModule, CString)>,
237 symbol_white_list: &[*const libc::c_char],
238 timeline: &mut Timeline)
239 -> Result<Vec<LtoModuleCodegen>, FatalError>
241 info!("going for a fat lto");
243 // Find the "costliest" module and merge everything into that codegen unit.
244 // All the other modules will be serialized and reparsed into the new
245 // context, so this hopefully avoids serializing and parsing the largest
248 // Additionally use a regular module as the base here to ensure that various
249 // file copy operations in the backend work correctly. The only other kind
250 // of module here should be an allocator one, and if your crate is smaller
251 // than the allocator module then the size doesn't really matter anyway.
252 let (_, costliest_module) = modules.iter()
254 .filter(|&(_, module)| module.kind == ModuleKind::Regular)
257 llvm::LLVMRustModuleCost(module.module_llvm.llmod())
262 .expect("must be codegen'ing at least one module");
263 let module = modules.remove(costliest_module);
264 let mut serialized_bitcode = Vec::new();
266 let (llcx, llmod) = {
267 let llvm = &module.module_llvm;
268 (&llvm.llcx, llvm.llmod())
270 info!("using {:?} as a base module", module.name);
272 // The linking steps below may produce errors and diagnostics within LLVM
273 // which we'd like to handle and print, so set up our diagnostic handlers
274 // (which get unregistered when they go out of scope below).
275 let _handler = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
277 // For all other modules we codegened we'll need to link them into our own
278 // bitcode. All modules were codegened in their own LLVM context, however,
279 // and we want to move everything to the same LLVM context. Currently the
280 // way we know of to do that is to serialize them to a string and them parse
281 // them later. Not great but hey, that's why it's "fat" LTO, right?
282 for module in modules {
283 let buffer = ModuleBuffer::new(module.module_llvm.llmod());
284 let llmod_id = CString::new(&module.name[..]).unwrap();
285 serialized_modules.push((SerializedModule::Local(buffer), llmod_id));
288 // For all serialized bitcode files we parse them and link them in as we did
289 // above, this is all mostly handled in C++. Like above, though, we don't
290 // know much about the memory management here so we err on the side of being
291 // save and persist everything with the original module.
292 let mut linker = Linker::new(llmod);
293 for (bc_decoded, name) in serialized_modules {
294 info!("linking {:?}", name);
295 time_ext(cgcx.time_passes, None, &format!("ll link {:?}", name), || {
296 let data = bc_decoded.data();
297 linker.add(&data).map_err(|()| {
298 let msg = format!("failed to load bc of {:?}", name);
299 write::llvm_err(&diag_handler, &msg)
302 timeline.record(&format!("link {:?}", name));
303 serialized_bitcode.push(bc_decoded);
306 cgcx.save_temp_bitcode(&module, "lto.input");
308 // Internalize everything that *isn't* in our whitelist to help strip out
309 // more modules and such
311 let ptr = symbol_white_list.as_ptr();
312 llvm::LLVMRustRunRestrictionPass(llmod,
313 ptr as *const *const libc::c_char,
314 symbol_white_list.len() as libc::size_t);
315 cgcx.save_temp_bitcode(&module, "lto.after-restriction");
318 if cgcx.no_landing_pads {
320 llvm::LLVMRustMarkAllFunctionsNounwind(llmod);
322 cgcx.save_temp_bitcode(&module, "lto.after-nounwind");
324 timeline.record("passes");
327 Ok(vec![LtoModuleCodegen::Fat {
328 module: Some(module),
329 _serialized_bitcode: serialized_bitcode,
333 struct Linker<'a>(&'a mut llvm::Linker<'a>);
336 fn new(llmod: &'a llvm::Module) -> Self {
337 unsafe { Linker(llvm::LLVMRustLinkerNew(llmod)) }
340 fn add(&mut self, bytecode: &[u8]) -> Result<(), ()> {
342 if llvm::LLVMRustLinkerAdd(self.0,
343 bytecode.as_ptr() as *const libc::c_char,
353 impl Drop for Linker<'a> {
355 unsafe { llvm::LLVMRustLinkerFree(&mut *(self.0 as *mut _)); }
359 /// Prepare "thin" LTO to get run on these modules.
361 /// The general structure of ThinLTO is quite different from the structure of
362 /// "fat" LTO above. With "fat" LTO all LLVM modules in question are merged into
363 /// one giant LLVM module, and then we run more optimization passes over this
364 /// big module after internalizing most symbols. Thin LTO, on the other hand,
365 /// avoid this large bottleneck through more targeted optimization.
367 /// At a high level Thin LTO looks like:
369 /// 1. Prepare a "summary" of each LLVM module in question which describes
370 /// the values inside, cost of the values, etc.
371 /// 2. Merge the summaries of all modules in question into one "index"
372 /// 3. Perform some global analysis on this index
373 /// 4. For each module, use the index and analysis calculated previously to
374 /// perform local transformations on the module, for example inlining
375 /// small functions from other modules.
376 /// 5. Run thin-specific optimization passes over each module, and then code
377 /// generate everything at the end.
379 /// The summary for each module is intended to be quite cheap, and the global
380 /// index is relatively quite cheap to create as well. As a result, the goal of
381 /// ThinLTO is to reduce the bottleneck on LTO and enable LTO to be used in more
382 /// situations. For example one cheap optimization is that we can parallelize
383 /// all codegen modules, easily making use of all the cores on a machine.
385 /// With all that in mind, the function here is designed at specifically just
386 /// calculating the *index* for ThinLTO. This index will then be shared amongst
387 /// all of the `LtoModuleCodegen` units returned below and destroyed once
388 /// they all go out of scope.
389 fn thin_lto(cgcx: &CodegenContext,
390 diag_handler: &Handler,
391 modules: Vec<ModuleCodegen<ModuleLlvm>>,
392 serialized_modules: Vec<(SerializedModule, CString)>,
393 cached_modules: Vec<(SerializedModule, WorkProduct)>,
394 symbol_white_list: &[*const libc::c_char],
395 timeline: &mut Timeline)
396 -> Result<(Vec<LtoModuleCodegen>, Vec<WorkProduct>), FatalError>
399 info!("going for that thin, thin LTO");
401 let green_modules: FxHashMap<_, _> = cached_modules
403 .map(|&(_, ref wp)| (wp.cgu_name.clone(), wp.clone()))
406 let mut thin_buffers = Vec::new();
407 let mut module_names = Vec::new();
408 let mut thin_modules = Vec::new();
410 // FIXME: right now, like with fat LTO, we serialize all in-memory
411 // modules before working with them and ThinLTO. We really
412 // shouldn't do this, however, and instead figure out how to
413 // extract a summary from an in-memory module and then merge that
414 // into the global index. It turns out that this loop is by far
415 // the most expensive portion of this small bit of global
417 for (i, module) in modules.iter().enumerate() {
418 info!("local module: {} - {}", i, module.name);
419 let name = CString::new(module.name.clone()).unwrap();
420 let buffer = ThinBuffer::new(module.module_llvm.llmod());
422 // We emit the module after having serialized it into a ThinBuffer
423 // because only then it will contain the ThinLTO module summary.
424 if let Some(ref incr_comp_session_dir) = cgcx.incr_comp_session_dir {
425 if cgcx.config(module.kind).emit_pre_thin_lto_bc {
426 let path = incr_comp_session_dir
427 .join(pre_lto_bitcode_filename(&module.name));
429 fs::write(&path, buffer.data()).unwrap_or_else(|e| {
430 panic!("Error writing pre-lto-bitcode file `{}`: {}",
437 thin_modules.push(llvm::ThinLTOModule {
438 identifier: name.as_ptr(),
439 data: buffer.data().as_ptr(),
440 len: buffer.data().len(),
442 thin_buffers.push(buffer);
443 module_names.push(name);
444 timeline.record(&module.name);
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::new();
465 let cached_modules = cached_modules.into_iter().map(|(sm, wp)| {
466 (sm, CString::new(wp.cgu_name).unwrap())
469 for (module, name) in serialized_modules.into_iter().chain(cached_modules) {
470 info!("upstream or cached module {:?}", name);
471 thin_modules.push(llvm::ThinLTOModule {
472 identifier: name.as_ptr(),
473 data: module.data().as_ptr(),
474 len: module.data().len(),
476 serialized.push(module);
477 module_names.push(name);
481 assert_eq!(thin_modules.len(), module_names.len());
483 // Delegate to the C++ bindings to create some data here. Once this is a
484 // tried-and-true interface we may wish to try to upstream some of this
485 // to LLVM itself, right now we reimplement a lot of what they do
487 let data = llvm::LLVMRustCreateThinLTOData(
488 thin_modules.as_ptr(),
489 thin_modules.len() as u32,
490 symbol_white_list.as_ptr(),
491 symbol_white_list.len() as u32,
493 write::llvm_err(&diag_handler, "failed to prepare thin LTO context")
496 info!("thin LTO data created");
497 timeline.record("data");
499 let import_map = if cgcx.incr_comp_session_dir.is_some() {
500 ThinLTOImports::from_thin_lto_data(data)
502 // If we don't compile incrementally, we don't need to load the
503 // import data from LLVM.
504 assert!(green_modules.is_empty());
505 ThinLTOImports::default()
507 info!("thin LTO import map loaded");
508 timeline.record("import-map-loaded");
510 let data = ThinData(data);
512 // Throw our data in an `Arc` as we'll be sharing it across threads. We
513 // also put all memory referenced by the C++ data (buffers, ids, etc)
514 // into the arc as well. After this we'll create a thin module
515 // codegen per module in this data.
516 let shared = Arc::new(ThinShared {
519 serialized_modules: serialized,
523 let mut copy_jobs = vec![];
524 let mut opt_jobs = vec![];
526 info!("checking which modules can be-reused and which have to be re-optimized.");
527 for (module_index, module_name) in shared.module_names.iter().enumerate() {
528 let module_name = module_name_to_str(module_name);
530 // If the module hasn't changed and none of the modules it imports
531 // from has changed, we can re-use the post-ThinLTO version of the
533 if green_modules.contains_key(module_name) {
534 let imports_all_green = import_map.modules_imported_by(module_name)
536 .all(|imported_module| green_modules.contains_key(imported_module));
538 if imports_all_green {
539 let work_product = green_modules[module_name].clone();
540 copy_jobs.push(work_product);
541 info!(" - {}: re-used", module_name);
542 cgcx.cgu_reuse_tracker.set_actual_reuse(module_name,
548 info!(" - {}: re-compiled", module_name);
549 opt_jobs.push(LtoModuleCodegen::Thin(ThinModule {
550 shared: shared.clone(),
555 Ok((opt_jobs, copy_jobs))
559 fn run_pass_manager(cgcx: &CodegenContext,
560 tm: &llvm::TargetMachine,
561 llmod: &llvm::Module,
562 config: &ModuleConfig,
564 // Now we have one massive module inside of llmod. Time to run the
565 // LTO-specific optimization passes that LLVM provides.
567 // This code is based off the code found in llvm's LTO code generator:
568 // tools/lto/LTOCodeGenerator.cpp
569 debug!("running the pass manager");
571 let pm = llvm::LLVMCreatePassManager();
572 llvm::LLVMRustAddAnalysisPasses(tm, pm, llmod);
574 if config.verify_llvm_ir {
575 let pass = llvm::LLVMRustFindAndCreatePass("verify\0".as_ptr() as *const _);
576 llvm::LLVMRustAddPass(pm, pass.unwrap());
579 // When optimizing for LTO we don't actually pass in `-O0`, but we force
580 // it to always happen at least with `-O1`.
582 // With ThinLTO we mess around a lot with symbol visibility in a way
583 // that will actually cause linking failures if we optimize at O0 which
584 // notable is lacking in dead code elimination. To ensure we at least
585 // get some optimizations and correctly link we forcibly switch to `-O1`
586 // to get dead code elimination.
588 // Note that in general this shouldn't matter too much as you typically
589 // only turn on ThinLTO when you're compiling with optimizations
591 let opt_level = config.opt_level.unwrap_or(llvm::CodeGenOptLevel::None);
592 let opt_level = match opt_level {
593 llvm::CodeGenOptLevel::None => llvm::CodeGenOptLevel::Less,
596 with_llvm_pmb(llmod, config, opt_level, false, &mut |b| {
598 llvm::LLVMRustPassManagerBuilderPopulateThinLTOPassManager(b, pm);
600 llvm::LLVMPassManagerBuilderPopulateLTOPassManager(b, pm,
601 /* Internalize = */ False,
602 /* RunInliner = */ True);
606 // We always generate bitcode through ThinLTOBuffers,
607 // which do not support anonymous globals
608 if config.bitcode_needed() {
609 let pass = llvm::LLVMRustFindAndCreatePass("name-anon-globals\0".as_ptr() as *const _);
610 llvm::LLVMRustAddPass(pm, pass.unwrap());
613 if config.verify_llvm_ir {
614 let pass = llvm::LLVMRustFindAndCreatePass("verify\0".as_ptr() as *const _);
615 llvm::LLVMRustAddPass(pm, pass.unwrap());
618 time_ext(cgcx.time_passes, None, "LTO passes", || llvm::LLVMRunPassManager(pm, llmod));
620 llvm::LLVMDisposePassManager(pm);
625 pub enum SerializedModule {
628 FromUncompressedFile(memmap::Mmap),
631 impl SerializedModule {
632 fn data(&self) -> &[u8] {
634 SerializedModule::Local(ref m) => m.data(),
635 SerializedModule::FromRlib(ref m) => m,
636 SerializedModule::FromUncompressedFile(ref m) => m,
641 pub struct ModuleBuffer(&'static mut llvm::ModuleBuffer);
643 unsafe impl Send for ModuleBuffer {}
644 unsafe impl Sync for ModuleBuffer {}
647 pub fn new(m: &llvm::Module) -> ModuleBuffer {
648 ModuleBuffer(unsafe {
649 llvm::LLVMRustModuleBufferCreate(m)
653 pub fn data(&self) -> &[u8] {
655 let ptr = llvm::LLVMRustModuleBufferPtr(self.0);
656 let len = llvm::LLVMRustModuleBufferLen(self.0);
657 slice::from_raw_parts(ptr, len)
662 impl Drop for ModuleBuffer {
664 unsafe { llvm::LLVMRustModuleBufferFree(&mut *(self.0 as *mut _)); }
668 pub struct ThinModule {
669 shared: Arc<ThinShared>,
675 thin_buffers: Vec<ThinBuffer>,
676 serialized_modules: Vec<SerializedModule>,
677 module_names: Vec<CString>,
680 struct ThinData(&'static mut llvm::ThinLTOData);
682 unsafe impl Send for ThinData {}
683 unsafe impl Sync for ThinData {}
685 impl Drop for ThinData {
688 llvm::LLVMRustFreeThinLTOData(&mut *(self.0 as *mut _));
693 pub struct ThinBuffer(&'static mut llvm::ThinLTOBuffer);
695 unsafe impl Send for ThinBuffer {}
696 unsafe impl Sync for ThinBuffer {}
699 pub fn new(m: &llvm::Module) -> ThinBuffer {
701 let buffer = llvm::LLVMRustThinLTOBufferCreate(m);
706 pub fn data(&self) -> &[u8] {
708 let ptr = llvm::LLVMRustThinLTOBufferPtr(self.0) as *const _;
709 let len = llvm::LLVMRustThinLTOBufferLen(self.0);
710 slice::from_raw_parts(ptr, len)
715 impl Drop for ThinBuffer {
718 llvm::LLVMRustThinLTOBufferFree(&mut *(self.0 as *mut _));
724 fn name(&self) -> &str {
725 self.shared.module_names[self.idx].to_str().unwrap()
728 fn cost(&self) -> u64 {
729 // Yes, that's correct, we're using the size of the bytecode as an
730 // indicator for how costly this codegen unit is.
731 self.data().len() as u64
734 fn data(&self) -> &[u8] {
735 let a = self.shared.thin_buffers.get(self.idx).map(|b| b.data());
736 a.unwrap_or_else(|| {
737 let len = self.shared.thin_buffers.len();
738 self.shared.serialized_modules[self.idx - len].data()
742 unsafe fn optimize(&mut self, cgcx: &CodegenContext, timeline: &mut Timeline)
743 -> Result<ModuleCodegen<ModuleLlvm>, FatalError>
745 let diag_handler = cgcx.create_diag_handler();
746 let tm = (cgcx.tm_factory)().map_err(|e| {
747 write::llvm_err(&diag_handler, &e)
750 // Right now the implementation we've got only works over serialized
751 // modules, so we create a fresh new LLVM context and parse the module
752 // into that context. One day, however, we may do this for upstream
753 // crates but for locally codegened modules we may be able to reuse
754 // that LLVM Context and Module.
755 let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
756 let llmod_raw = llvm::LLVMRustParseBitcodeForThinLTO(
758 self.data().as_ptr(),
760 self.shared.module_names[self.idx].as_ptr(),
762 let msg = "failed to parse bitcode for thin LTO module";
763 write::llvm_err(&diag_handler, msg)
765 let module = ModuleCodegen {
766 module_llvm: ModuleLlvm {
771 name: self.name().to_string(),
772 kind: ModuleKind::Regular,
775 let llmod = module.module_llvm.llmod();
776 cgcx.save_temp_bitcode(&module, "thin-lto-input");
778 // Before we do much else find the "main" `DICompileUnit` that we'll be
779 // using below. If we find more than one though then rustc has changed
780 // in a way we're not ready for, so generate an ICE by returning
782 let mut cu1 = ptr::null_mut();
783 let mut cu2 = ptr::null_mut();
784 llvm::LLVMRustThinLTOGetDICompileUnit(llmod, &mut cu1, &mut cu2);
786 let msg = "multiple source DICompileUnits found";
787 return Err(write::llvm_err(&diag_handler, msg))
790 // Like with "fat" LTO, get some better optimizations if landing pads
791 // are disabled by removing all landing pads.
792 if cgcx.no_landing_pads {
793 llvm::LLVMRustMarkAllFunctionsNounwind(llmod);
794 cgcx.save_temp_bitcode(&module, "thin-lto-after-nounwind");
795 timeline.record("nounwind");
798 // Up next comes the per-module local analyses that we do for Thin LTO.
799 // Each of these functions is basically copied from the LLVM
800 // implementation and then tailored to suit this implementation. Ideally
801 // each of these would be supported by upstream LLVM but that's perhaps
802 // a patch for another day!
804 // You can find some more comments about these functions in the LLVM
805 // bindings we've got (currently `PassWrapper.cpp`)
806 if !llvm::LLVMRustPrepareThinLTORename(self.shared.data.0, llmod) {
807 let msg = "failed to prepare thin LTO module";
808 return Err(write::llvm_err(&diag_handler, msg))
810 cgcx.save_temp_bitcode(&module, "thin-lto-after-rename");
811 timeline.record("rename");
812 if !llvm::LLVMRustPrepareThinLTOResolveWeak(self.shared.data.0, llmod) {
813 let msg = "failed to prepare thin LTO module";
814 return Err(write::llvm_err(&diag_handler, msg))
816 cgcx.save_temp_bitcode(&module, "thin-lto-after-resolve");
817 timeline.record("resolve");
818 if !llvm::LLVMRustPrepareThinLTOInternalize(self.shared.data.0, llmod) {
819 let msg = "failed to prepare thin LTO module";
820 return Err(write::llvm_err(&diag_handler, msg))
822 cgcx.save_temp_bitcode(&module, "thin-lto-after-internalize");
823 timeline.record("internalize");
824 if !llvm::LLVMRustPrepareThinLTOImport(self.shared.data.0, llmod) {
825 let msg = "failed to prepare thin LTO module";
826 return Err(write::llvm_err(&diag_handler, msg))
828 cgcx.save_temp_bitcode(&module, "thin-lto-after-import");
829 timeline.record("import");
831 // Ok now this is a bit unfortunate. This is also something you won't
832 // find upstream in LLVM's ThinLTO passes! This is a hack for now to
833 // work around bugs in LLVM.
835 // First discovered in #45511 it was found that as part of ThinLTO
836 // importing passes LLVM will import `DICompileUnit` metadata
837 // information across modules. This means that we'll be working with one
838 // LLVM module that has multiple `DICompileUnit` instances in it (a
839 // bunch of `llvm.dbg.cu` members). Unfortunately there's a number of
840 // bugs in LLVM's backend which generates invalid DWARF in a situation
843 // https://bugs.llvm.org/show_bug.cgi?id=35212
844 // https://bugs.llvm.org/show_bug.cgi?id=35562
846 // While the first bug there is fixed the second ended up causing #46346
847 // which was basically a resurgence of #45511 after LLVM's bug 35212 was
850 // This function below is a huge hack around this problem. The function
851 // below is defined in `PassWrapper.cpp` and will basically "merge"
852 // all `DICompileUnit` instances in a module. Basically it'll take all
853 // the objects, rewrite all pointers of `DISubprogram` to point to the
854 // first `DICompileUnit`, and then delete all the other units.
856 // This is probably mangling to the debug info slightly (but hopefully
857 // not too much) but for now at least gets LLVM to emit valid DWARF (or
858 // so it appears). Hopefully we can remove this once upstream bugs are
860 llvm::LLVMRustThinLTOPatchDICompileUnit(llmod, cu1);
861 cgcx.save_temp_bitcode(&module, "thin-lto-after-patch");
862 timeline.record("patch");
864 // Alright now that we've done everything related to the ThinLTO
865 // analysis it's time to run some optimizations! Here we use the same
866 // `run_pass_manager` as the "fat" LTO above except that we tell it to
867 // populate a thin-specific pass manager, which presumably LLVM treats a
868 // little differently.
869 info!("running thin lto passes over {}", module.name);
870 let config = cgcx.config(module.kind);
871 run_pass_manager(cgcx, module.module_llvm.tm, llmod, config, true);
872 cgcx.save_temp_bitcode(&module, "thin-lto-after-pm");
873 timeline.record("thin-done");
880 #[derive(Debug, Default)]
881 pub struct ThinLTOImports {
882 // key = llvm name of importing module, value = list of modules it imports from
883 imports: FxHashMap<String, Vec<String>>,
886 impl ThinLTOImports {
887 fn modules_imported_by(&self, llvm_module_name: &str) -> &[String] {
888 self.imports.get(llvm_module_name).map(|v| &v[..]).unwrap_or(&[])
891 /// Load the ThinLTO import map from ThinLTOData.
892 unsafe fn from_thin_lto_data(data: *const llvm::ThinLTOData) -> ThinLTOImports {
893 unsafe extern "C" fn imported_module_callback(payload: *mut libc::c_void,
894 importing_module_name: *const libc::c_char,
895 imported_module_name: *const libc::c_char) {
896 let map = &mut* (payload as *mut ThinLTOImports);
897 let importing_module_name = CStr::from_ptr(importing_module_name);
898 let importing_module_name = module_name_to_str(&importing_module_name);
899 let imported_module_name = CStr::from_ptr(imported_module_name);
900 let imported_module_name = module_name_to_str(&imported_module_name);
902 if !map.imports.contains_key(importing_module_name) {
903 map.imports.insert(importing_module_name.to_owned(), vec![]);
907 .get_mut(importing_module_name)
909 .push(imported_module_name.to_owned());
911 let mut map = ThinLTOImports::default();
912 llvm::LLVMRustGetThinLTOModuleImports(data,
913 imported_module_callback,
914 &mut map as *mut _ as *mut libc::c_void);
919 fn module_name_to_str(c_str: &CStr) -> &str {
920 c_str.to_str().unwrap_or_else(|e|
921 bug!("Encountered non-utf8 LLVM module name `{}`: {}", c_str.to_string_lossy(), e))