]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/back/lto.rs
Auto merge of #107843 - bjorn3:sync_cg_clif-2023-02-09, r=bjorn3
[rust.git] / compiler / rustc_codegen_llvm / src / back / lto.rs
1 use crate::back::write::{self, save_temp_bitcode, DiagnosticHandlers};
2 use crate::errors::{
3     DynamicLinkingWithLTO, LlvmError, LtoBitcodeFromRlib, LtoDisallowed, LtoDylib,
4 };
5 use crate::llvm::{self, build_string};
6 use crate::{LlvmCodegenBackend, ModuleLlvm};
7 use object::read::archive::ArchiveFile;
8 use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule, ThinShared};
9 use rustc_codegen_ssa::back::symbol_export;
10 use rustc_codegen_ssa::back::write::{CodegenContext, FatLTOInput, TargetMachineFactoryConfig};
11 use rustc_codegen_ssa::traits::*;
12 use rustc_codegen_ssa::{looks_like_rust_object_file, ModuleCodegen, ModuleKind};
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_data_structures::memmap::Mmap;
15 use rustc_errors::{FatalError, Handler};
16 use rustc_hir::def_id::LOCAL_CRATE;
17 use rustc_middle::bug;
18 use rustc_middle::dep_graph::WorkProduct;
19 use rustc_middle::middle::exported_symbols::{SymbolExportInfo, SymbolExportLevel};
20 use rustc_session::cgu_reuse_tracker::CguReuse;
21 use rustc_session::config::{self, CrateType, Lto};
22
23 use std::ffi::{CStr, CString};
24 use std::fs::File;
25 use std::io;
26 use std::iter;
27 use std::path::Path;
28 use std::ptr;
29 use std::slice;
30 use std::sync::Arc;
31
32 /// We keep track of the computed LTO cache keys from the previous
33 /// session to determine which CGUs we can reuse.
34 pub const THIN_LTO_KEYS_INCR_COMP_FILE_NAME: &str = "thin-lto-past-keys.bin";
35
36 pub fn crate_type_allows_lto(crate_type: CrateType) -> bool {
37     match crate_type {
38         CrateType::Executable | CrateType::Dylib | CrateType::Staticlib | CrateType::Cdylib => true,
39         CrateType::Rlib | CrateType::ProcMacro => false,
40     }
41 }
42
43 fn prepare_lto(
44     cgcx: &CodegenContext<LlvmCodegenBackend>,
45     diag_handler: &Handler,
46 ) -> Result<(Vec<CString>, Vec<(SerializedModule<ModuleBuffer>, CString)>), FatalError> {
47     let export_threshold = match cgcx.lto {
48         // We're just doing LTO for our one crate
49         Lto::ThinLocal => SymbolExportLevel::Rust,
50
51         // We're doing LTO for the entire crate graph
52         Lto::Fat | Lto::Thin => symbol_export::crates_export_threshold(&cgcx.crate_types),
53
54         Lto::No => panic!("didn't request LTO but we're doing LTO"),
55     };
56
57     let symbol_filter = &|&(ref name, info): &(String, SymbolExportInfo)| {
58         if info.level.is_below_threshold(export_threshold) || info.used {
59             Some(CString::new(name.as_str()).unwrap())
60         } else {
61             None
62         }
63     };
64     let exported_symbols = cgcx.exported_symbols.as_ref().expect("needs exported symbols for LTO");
65     let mut symbols_below_threshold = {
66         let _timer = cgcx.prof.generic_activity("LLVM_lto_generate_symbols_below_threshold");
67         exported_symbols[&LOCAL_CRATE].iter().filter_map(symbol_filter).collect::<Vec<CString>>()
68     };
69     info!("{} symbols to preserve in this crate", symbols_below_threshold.len());
70
71     // If we're performing LTO for the entire crate graph, then for each of our
72     // upstream dependencies, find the corresponding rlib and load the bitcode
73     // from the archive.
74     //
75     // We save off all the bytecode and LLVM module ids for later processing
76     // with either fat or thin LTO
77     let mut upstream_modules = Vec::new();
78     if cgcx.lto != Lto::ThinLocal {
79         // Make sure we actually can run LTO
80         for crate_type in cgcx.crate_types.iter() {
81             if !crate_type_allows_lto(*crate_type) {
82                 diag_handler.emit_err(LtoDisallowed);
83                 return Err(FatalError);
84             } else if *crate_type == CrateType::Dylib {
85                 if !cgcx.opts.unstable_opts.dylib_lto {
86                     diag_handler.emit_err(LtoDylib);
87                     return Err(FatalError);
88                 }
89             }
90         }
91
92         if cgcx.opts.cg.prefer_dynamic && !cgcx.opts.unstable_opts.dylib_lto {
93             diag_handler.emit_err(DynamicLinkingWithLTO);
94             return Err(FatalError);
95         }
96
97         for &(cnum, ref path) in cgcx.each_linked_rlib_for_lto.iter() {
98             let exported_symbols =
99                 cgcx.exported_symbols.as_ref().expect("needs exported symbols for LTO");
100             {
101                 let _timer =
102                     cgcx.prof.generic_activity("LLVM_lto_generate_symbols_below_threshold");
103                 symbols_below_threshold
104                     .extend(exported_symbols[&cnum].iter().filter_map(symbol_filter));
105             }
106
107             let archive_data = unsafe {
108                 Mmap::map(std::fs::File::open(&path).expect("couldn't open rlib"))
109                     .expect("couldn't map rlib")
110             };
111             let archive = ArchiveFile::parse(&*archive_data).expect("wanted an rlib");
112             let obj_files = archive
113                 .members()
114                 .filter_map(|child| {
115                     child.ok().and_then(|c| {
116                         std::str::from_utf8(c.name()).ok().map(|name| (name.trim(), c))
117                     })
118                 })
119                 .filter(|&(name, _)| looks_like_rust_object_file(name));
120             for (name, child) in obj_files {
121                 info!("adding bitcode from {}", name);
122                 match get_bitcode_slice_from_object_data(
123                     child.data(&*archive_data).expect("corrupt rlib"),
124                 ) {
125                     Ok(data) => {
126                         let module = SerializedModule::FromRlib(data.to_vec());
127                         upstream_modules.push((module, CString::new(name).unwrap()));
128                     }
129                     Err(e) => {
130                         diag_handler.emit_err(e);
131                         return Err(FatalError);
132                     }
133                 }
134             }
135         }
136     }
137
138     // __llvm_profile_counter_bias is pulled in at link time by an undefined reference to
139     // __llvm_profile_runtime, therefore we won't know until link time if this symbol
140     // should have default visibility.
141     symbols_below_threshold.push(CString::new("__llvm_profile_counter_bias").unwrap());
142     Ok((symbols_below_threshold, upstream_modules))
143 }
144
145 fn get_bitcode_slice_from_object_data(obj: &[u8]) -> Result<&[u8], LtoBitcodeFromRlib> {
146     let mut len = 0;
147     let data =
148         unsafe { llvm::LLVMRustGetBitcodeSliceFromObjectData(obj.as_ptr(), obj.len(), &mut len) };
149     if !data.is_null() {
150         assert!(len != 0);
151         let bc = unsafe { slice::from_raw_parts(data, len) };
152
153         // `bc` must be a sub-slice of `obj`.
154         assert!(obj.as_ptr() <= bc.as_ptr());
155         assert!(bc[bc.len()..bc.len()].as_ptr() <= obj[obj.len()..obj.len()].as_ptr());
156
157         Ok(bc)
158     } else {
159         assert!(len == 0);
160         Err(LtoBitcodeFromRlib {
161             llvm_err: llvm::last_error().unwrap_or_else(|| "unknown LLVM error".to_string()),
162         })
163     }
164 }
165
166 /// Performs fat LTO by merging all modules into a single one and returning it
167 /// for further optimization.
168 pub(crate) fn run_fat(
169     cgcx: &CodegenContext<LlvmCodegenBackend>,
170     modules: Vec<FatLTOInput<LlvmCodegenBackend>>,
171     cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
172 ) -> Result<LtoModuleCodegen<LlvmCodegenBackend>, FatalError> {
173     let diag_handler = cgcx.create_diag_handler();
174     let (symbols_below_threshold, upstream_modules) = prepare_lto(cgcx, &diag_handler)?;
175     let symbols_below_threshold =
176         symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
177     fat_lto(
178         cgcx,
179         &diag_handler,
180         modules,
181         cached_modules,
182         upstream_modules,
183         &symbols_below_threshold,
184     )
185 }
186
187 /// Performs thin LTO by performing necessary global analysis and returning two
188 /// lists, one of the modules that need optimization and another for modules that
189 /// can simply be copied over from the incr. comp. cache.
190 pub(crate) fn run_thin(
191     cgcx: &CodegenContext<LlvmCodegenBackend>,
192     modules: Vec<(String, ThinBuffer)>,
193     cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
194 ) -> Result<(Vec<LtoModuleCodegen<LlvmCodegenBackend>>, Vec<WorkProduct>), FatalError> {
195     let diag_handler = cgcx.create_diag_handler();
196     let (symbols_below_threshold, upstream_modules) = prepare_lto(cgcx, &diag_handler)?;
197     let symbols_below_threshold =
198         symbols_below_threshold.iter().map(|c| c.as_ptr()).collect::<Vec<_>>();
199     if cgcx.opts.cg.linker_plugin_lto.enabled() {
200         unreachable!(
201             "We should never reach this case if the LTO step \
202                       is deferred to the linker"
203         );
204     }
205     thin_lto(
206         cgcx,
207         &diag_handler,
208         modules,
209         upstream_modules,
210         cached_modules,
211         &symbols_below_threshold,
212     )
213 }
214
215 pub(crate) fn prepare_thin(module: ModuleCodegen<ModuleLlvm>) -> (String, ThinBuffer) {
216     let name = module.name;
217     let buffer = ThinBuffer::new(module.module_llvm.llmod(), true);
218     (name, buffer)
219 }
220
221 fn fat_lto(
222     cgcx: &CodegenContext<LlvmCodegenBackend>,
223     diag_handler: &Handler,
224     modules: Vec<FatLTOInput<LlvmCodegenBackend>>,
225     cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
226     mut serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
227     symbols_below_threshold: &[*const libc::c_char],
228 ) -> Result<LtoModuleCodegen<LlvmCodegenBackend>, FatalError> {
229     let _timer = cgcx.prof.generic_activity("LLVM_fat_lto_build_monolithic_module");
230     info!("going for a fat lto");
231
232     // Sort out all our lists of incoming modules into two lists.
233     //
234     // * `serialized_modules` (also and argument to this function) contains all
235     //   modules that are serialized in-memory.
236     // * `in_memory` contains modules which are already parsed and in-memory,
237     //   such as from multi-CGU builds.
238     //
239     // All of `cached_modules` (cached from previous incremental builds) can
240     // immediately go onto the `serialized_modules` modules list and then we can
241     // split the `modules` array into these two lists.
242     let mut in_memory = Vec::new();
243     serialized_modules.extend(cached_modules.into_iter().map(|(buffer, wp)| {
244         info!("pushing cached module {:?}", wp.cgu_name);
245         (buffer, CString::new(wp.cgu_name).unwrap())
246     }));
247     for module in modules {
248         match module {
249             FatLTOInput::InMemory(m) => in_memory.push(m),
250             FatLTOInput::Serialized { name, buffer } => {
251                 info!("pushing serialized module {:?}", name);
252                 let buffer = SerializedModule::Local(buffer);
253                 serialized_modules.push((buffer, CString::new(name).unwrap()));
254             }
255         }
256     }
257
258     // Find the "costliest" module and merge everything into that codegen unit.
259     // All the other modules will be serialized and reparsed into the new
260     // context, so this hopefully avoids serializing and parsing the largest
261     // codegen unit.
262     //
263     // Additionally use a regular module as the base here to ensure that various
264     // file copy operations in the backend work correctly. The only other kind
265     // of module here should be an allocator one, and if your crate is smaller
266     // than the allocator module then the size doesn't really matter anyway.
267     let costliest_module = in_memory
268         .iter()
269         .enumerate()
270         .filter(|&(_, module)| module.kind == ModuleKind::Regular)
271         .map(|(i, module)| {
272             let cost = unsafe { llvm::LLVMRustModuleCost(module.module_llvm.llmod()) };
273             (cost, i)
274         })
275         .max();
276
277     // If we found a costliest module, we're good to go. Otherwise all our
278     // inputs were serialized which could happen in the case, for example, that
279     // all our inputs were incrementally reread from the cache and we're just
280     // re-executing the LTO passes. If that's the case deserialize the first
281     // module and create a linker with it.
282     let module: ModuleCodegen<ModuleLlvm> = match costliest_module {
283         Some((_cost, i)) => in_memory.remove(i),
284         None => {
285             assert!(!serialized_modules.is_empty(), "must have at least one serialized module");
286             let (buffer, name) = serialized_modules.remove(0);
287             info!("no in-memory regular modules to choose from, parsing {:?}", name);
288             ModuleCodegen {
289                 module_llvm: ModuleLlvm::parse(cgcx, &name, buffer.data(), diag_handler)?,
290                 name: name.into_string().unwrap(),
291                 kind: ModuleKind::Regular,
292             }
293         }
294     };
295     let mut serialized_bitcode = Vec::new();
296     {
297         let (llcx, llmod) = {
298             let llvm = &module.module_llvm;
299             (&llvm.llcx, llvm.llmod())
300         };
301         info!("using {:?} as a base module", module.name);
302
303         // The linking steps below may produce errors and diagnostics within LLVM
304         // which we'd like to handle and print, so set up our diagnostic handlers
305         // (which get unregistered when they go out of scope below).
306         let _handler = DiagnosticHandlers::new(cgcx, diag_handler, llcx);
307
308         // For all other modules we codegened we'll need to link them into our own
309         // bitcode. All modules were codegened in their own LLVM context, however,
310         // and we want to move everything to the same LLVM context. Currently the
311         // way we know of to do that is to serialize them to a string and them parse
312         // them later. Not great but hey, that's why it's "fat" LTO, right?
313         for module in in_memory {
314             let buffer = ModuleBuffer::new(module.module_llvm.llmod());
315             let llmod_id = CString::new(&module.name[..]).unwrap();
316             serialized_modules.push((SerializedModule::Local(buffer), llmod_id));
317         }
318         // Sort the modules to ensure we produce deterministic results.
319         serialized_modules.sort_by(|module1, module2| module1.1.cmp(&module2.1));
320
321         // For all serialized bitcode files we parse them and link them in as we did
322         // above, this is all mostly handled in C++. Like above, though, we don't
323         // know much about the memory management here so we err on the side of being
324         // save and persist everything with the original module.
325         let mut linker = Linker::new(llmod);
326         for (bc_decoded, name) in serialized_modules {
327             let _timer = cgcx
328                 .prof
329                 .generic_activity_with_arg_recorder("LLVM_fat_lto_link_module", |recorder| {
330                     recorder.record_arg(format!("{:?}", name))
331                 });
332             info!("linking {:?}", name);
333             let data = bc_decoded.data();
334             linker
335                 .add(data)
336                 .map_err(|()| write::llvm_err(diag_handler, LlvmError::LoadBitcode { name }))?;
337             serialized_bitcode.push(bc_decoded);
338         }
339         drop(linker);
340         save_temp_bitcode(cgcx, &module, "lto.input");
341
342         // Internalize everything below threshold to help strip out more modules and such.
343         unsafe {
344             let ptr = symbols_below_threshold.as_ptr();
345             llvm::LLVMRustRunRestrictionPass(
346                 llmod,
347                 ptr as *const *const libc::c_char,
348                 symbols_below_threshold.len() as libc::size_t,
349             );
350             save_temp_bitcode(cgcx, &module, "lto.after-restriction");
351         }
352     }
353
354     Ok(LtoModuleCodegen::Fat { module, _serialized_bitcode: serialized_bitcode })
355 }
356
357 pub(crate) struct Linker<'a>(&'a mut llvm::Linker<'a>);
358
359 impl<'a> Linker<'a> {
360     pub(crate) fn new(llmod: &'a llvm::Module) -> Self {
361         unsafe { Linker(llvm::LLVMRustLinkerNew(llmod)) }
362     }
363
364     pub(crate) fn add(&mut self, bytecode: &[u8]) -> Result<(), ()> {
365         unsafe {
366             if llvm::LLVMRustLinkerAdd(
367                 self.0,
368                 bytecode.as_ptr() as *const libc::c_char,
369                 bytecode.len(),
370             ) {
371                 Ok(())
372             } else {
373                 Err(())
374             }
375         }
376     }
377 }
378
379 impl Drop for Linker<'_> {
380     fn drop(&mut self) {
381         unsafe {
382             llvm::LLVMRustLinkerFree(&mut *(self.0 as *mut _));
383         }
384     }
385 }
386
387 /// Prepare "thin" LTO to get run on these modules.
388 ///
389 /// The general structure of ThinLTO is quite different from the structure of
390 /// "fat" LTO above. With "fat" LTO all LLVM modules in question are merged into
391 /// one giant LLVM module, and then we run more optimization passes over this
392 /// big module after internalizing most symbols. Thin LTO, on the other hand,
393 /// avoid this large bottleneck through more targeted optimization.
394 ///
395 /// At a high level Thin LTO looks like:
396 ///
397 ///    1. Prepare a "summary" of each LLVM module in question which describes
398 ///       the values inside, cost of the values, etc.
399 ///    2. Merge the summaries of all modules in question into one "index"
400 ///    3. Perform some global analysis on this index
401 ///    4. For each module, use the index and analysis calculated previously to
402 ///       perform local transformations on the module, for example inlining
403 ///       small functions from other modules.
404 ///    5. Run thin-specific optimization passes over each module, and then code
405 ///       generate everything at the end.
406 ///
407 /// The summary for each module is intended to be quite cheap, and the global
408 /// index is relatively quite cheap to create as well. As a result, the goal of
409 /// ThinLTO is to reduce the bottleneck on LTO and enable LTO to be used in more
410 /// situations. For example one cheap optimization is that we can parallelize
411 /// all codegen modules, easily making use of all the cores on a machine.
412 ///
413 /// With all that in mind, the function here is designed at specifically just
414 /// calculating the *index* for ThinLTO. This index will then be shared amongst
415 /// all of the `LtoModuleCodegen` units returned below and destroyed once
416 /// they all go out of scope.
417 fn thin_lto(
418     cgcx: &CodegenContext<LlvmCodegenBackend>,
419     diag_handler: &Handler,
420     modules: Vec<(String, ThinBuffer)>,
421     serialized_modules: Vec<(SerializedModule<ModuleBuffer>, CString)>,
422     cached_modules: Vec<(SerializedModule<ModuleBuffer>, WorkProduct)>,
423     symbols_below_threshold: &[*const libc::c_char],
424 ) -> Result<(Vec<LtoModuleCodegen<LlvmCodegenBackend>>, Vec<WorkProduct>), FatalError> {
425     let _timer = cgcx.prof.generic_activity("LLVM_thin_lto_global_analysis");
426     unsafe {
427         info!("going for that thin, thin LTO");
428
429         let green_modules: FxHashMap<_, _> =
430             cached_modules.iter().map(|(_, wp)| (wp.cgu_name.clone(), wp.clone())).collect();
431
432         let full_scope_len = modules.len() + serialized_modules.len() + cached_modules.len();
433         let mut thin_buffers = Vec::with_capacity(modules.len());
434         let mut module_names = Vec::with_capacity(full_scope_len);
435         let mut thin_modules = Vec::with_capacity(full_scope_len);
436
437         for (i, (name, buffer)) in modules.into_iter().enumerate() {
438             info!("local module: {} - {}", i, name);
439             let cname = CString::new(name.clone()).unwrap();
440             thin_modules.push(llvm::ThinLTOModule {
441                 identifier: cname.as_ptr(),
442                 data: buffer.data().as_ptr(),
443                 len: buffer.data().len(),
444             });
445             thin_buffers.push(buffer);
446             module_names.push(cname);
447         }
448
449         // FIXME: All upstream crates are deserialized internally in the
450         //        function below to extract their summary and modules. Note that
451         //        unlike the loop above we *must* decode and/or read something
452         //        here as these are all just serialized files on disk. An
453         //        improvement, however, to make here would be to store the
454         //        module summary separately from the actual module itself. Right
455         //        now this is store in one large bitcode file, and the entire
456         //        file is deflate-compressed. We could try to bypass some of the
457         //        decompression by storing the index uncompressed and only
458         //        lazily decompressing the bytecode if necessary.
459         //
460         //        Note that truly taking advantage of this optimization will
461         //        likely be further down the road. We'd have to implement
462         //        incremental ThinLTO first where we could actually avoid
463         //        looking at upstream modules entirely sometimes (the contents,
464         //        we must always unconditionally look at the index).
465         let mut serialized = Vec::with_capacity(serialized_modules.len() + cached_modules.len());
466
467         let cached_modules =
468             cached_modules.into_iter().map(|(sm, wp)| (sm, CString::new(wp.cgu_name).unwrap()));
469
470         for (module, name) in serialized_modules.into_iter().chain(cached_modules) {
471             info!("upstream or cached module {:?}", name);
472             thin_modules.push(llvm::ThinLTOModule {
473                 identifier: name.as_ptr(),
474                 data: module.data().as_ptr(),
475                 len: module.data().len(),
476             });
477             serialized.push(module);
478             module_names.push(name);
479         }
480
481         // Sanity check
482         assert_eq!(thin_modules.len(), module_names.len());
483
484         // Delegate to the C++ bindings to create some data here. Once this is a
485         // tried-and-true interface we may wish to try to upstream some of this
486         // to LLVM itself, right now we reimplement a lot of what they do
487         // upstream...
488         let data = llvm::LLVMRustCreateThinLTOData(
489             thin_modules.as_ptr(),
490             thin_modules.len() as u32,
491             symbols_below_threshold.as_ptr(),
492             symbols_below_threshold.len() as u32,
493         )
494         .ok_or_else(|| write::llvm_err(diag_handler, LlvmError::PrepareThinLtoContext))?;
495
496         let data = ThinData(data);
497
498         info!("thin LTO data created");
499
500         let (key_map_path, prev_key_map, curr_key_map) = if let Some(ref incr_comp_session_dir) =
501             cgcx.incr_comp_session_dir
502         {
503             let path = incr_comp_session_dir.join(THIN_LTO_KEYS_INCR_COMP_FILE_NAME);
504             // If the previous file was deleted, or we get an IO error
505             // reading the file, then we'll just use `None` as the
506             // prev_key_map, which will force the code to be recompiled.
507             let prev =
508                 if path.exists() { ThinLTOKeysMap::load_from_file(&path).ok() } else { None };
509             let curr = ThinLTOKeysMap::from_thin_lto_modules(&data, &thin_modules, &module_names);
510             (Some(path), prev, curr)
511         } else {
512             // If we don't compile incrementally, we don't need to load the
513             // import data from LLVM.
514             assert!(green_modules.is_empty());
515             let curr = ThinLTOKeysMap::default();
516             (None, None, curr)
517         };
518         info!("thin LTO cache key map loaded");
519         info!("prev_key_map: {:#?}", prev_key_map);
520         info!("curr_key_map: {:#?}", curr_key_map);
521
522         // Throw our data in an `Arc` as we'll be sharing it across threads. We
523         // also put all memory referenced by the C++ data (buffers, ids, etc)
524         // into the arc as well. After this we'll create a thin module
525         // codegen per module in this data.
526         let shared = Arc::new(ThinShared {
527             data,
528             thin_buffers,
529             serialized_modules: serialized,
530             module_names,
531         });
532
533         let mut copy_jobs = vec![];
534         let mut opt_jobs = vec![];
535
536         info!("checking which modules can be-reused and which have to be re-optimized.");
537         for (module_index, module_name) in shared.module_names.iter().enumerate() {
538             let module_name = module_name_to_str(module_name);
539             if let (Some(prev_key_map), true) =
540                 (prev_key_map.as_ref(), green_modules.contains_key(module_name))
541             {
542                 assert!(cgcx.incr_comp_session_dir.is_some());
543
544                 // If a module exists in both the current and the previous session,
545                 // and has the same LTO cache key in both sessions, then we can re-use it
546                 if prev_key_map.keys.get(module_name) == curr_key_map.keys.get(module_name) {
547                     let work_product = green_modules[module_name].clone();
548                     copy_jobs.push(work_product);
549                     info!(" - {}: re-used", module_name);
550                     assert!(cgcx.incr_comp_session_dir.is_some());
551                     cgcx.cgu_reuse_tracker.set_actual_reuse(module_name, CguReuse::PostLto);
552                     continue;
553                 }
554             }
555
556             info!(" - {}: re-compiled", module_name);
557             opt_jobs.push(LtoModuleCodegen::Thin(ThinModule {
558                 shared: shared.clone(),
559                 idx: module_index,
560             }));
561         }
562
563         // Save the current ThinLTO import information for the next compilation
564         // session, overwriting the previous serialized data (if any).
565         if let Some(path) = key_map_path {
566             if let Err(err) = curr_key_map.save_to_file(&path) {
567                 return Err(write::llvm_err(diag_handler, LlvmError::WriteThinLtoKey { err }));
568             }
569         }
570
571         Ok((opt_jobs, copy_jobs))
572     }
573 }
574
575 pub(crate) fn run_pass_manager(
576     cgcx: &CodegenContext<LlvmCodegenBackend>,
577     diag_handler: &Handler,
578     module: &mut ModuleCodegen<ModuleLlvm>,
579     thin: bool,
580 ) -> Result<(), FatalError> {
581     let _timer = cgcx.prof.verbose_generic_activity_with_arg("LLVM_lto_optimize", &*module.name);
582     let config = cgcx.config(module.kind);
583
584     // Now we have one massive module inside of llmod. Time to run the
585     // LTO-specific optimization passes that LLVM provides.
586     //
587     // This code is based off the code found in llvm's LTO code generator:
588     //      llvm/lib/LTO/LTOCodeGenerator.cpp
589     debug!("running the pass manager");
590     unsafe {
591         if !llvm::LLVMRustHasModuleFlag(
592             module.module_llvm.llmod(),
593             "LTOPostLink".as_ptr().cast(),
594             11,
595         ) {
596             llvm::LLVMRustAddModuleFlag(
597                 module.module_llvm.llmod(),
598                 llvm::LLVMModFlagBehavior::Error,
599                 "LTOPostLink\0".as_ptr().cast(),
600                 1,
601             );
602         }
603         let opt_stage = if thin { llvm::OptStage::ThinLTO } else { llvm::OptStage::FatLTO };
604         let opt_level = config.opt_level.unwrap_or(config::OptLevel::No);
605         write::llvm_optimize(cgcx, diag_handler, module, config, opt_level, opt_stage)?;
606     }
607     debug!("lto done");
608     Ok(())
609 }
610
611 pub struct ModuleBuffer(&'static mut llvm::ModuleBuffer);
612
613 unsafe impl Send for ModuleBuffer {}
614 unsafe impl Sync for ModuleBuffer {}
615
616 impl ModuleBuffer {
617     pub fn new(m: &llvm::Module) -> ModuleBuffer {
618         ModuleBuffer(unsafe { llvm::LLVMRustModuleBufferCreate(m) })
619     }
620 }
621
622 impl ModuleBufferMethods for ModuleBuffer {
623     fn data(&self) -> &[u8] {
624         unsafe {
625             let ptr = llvm::LLVMRustModuleBufferPtr(self.0);
626             let len = llvm::LLVMRustModuleBufferLen(self.0);
627             slice::from_raw_parts(ptr, len)
628         }
629     }
630 }
631
632 impl Drop for ModuleBuffer {
633     fn drop(&mut self) {
634         unsafe {
635             llvm::LLVMRustModuleBufferFree(&mut *(self.0 as *mut _));
636         }
637     }
638 }
639
640 pub struct ThinData(&'static mut llvm::ThinLTOData);
641
642 unsafe impl Send for ThinData {}
643 unsafe impl Sync for ThinData {}
644
645 impl Drop for ThinData {
646     fn drop(&mut self) {
647         unsafe {
648             llvm::LLVMRustFreeThinLTOData(&mut *(self.0 as *mut _));
649         }
650     }
651 }
652
653 pub struct ThinBuffer(&'static mut llvm::ThinLTOBuffer);
654
655 unsafe impl Send for ThinBuffer {}
656 unsafe impl Sync for ThinBuffer {}
657
658 impl ThinBuffer {
659     pub fn new(m: &llvm::Module, is_thin: bool) -> ThinBuffer {
660         unsafe {
661             let buffer = llvm::LLVMRustThinLTOBufferCreate(m, is_thin);
662             ThinBuffer(buffer)
663         }
664     }
665 }
666
667 impl ThinBufferMethods for ThinBuffer {
668     fn data(&self) -> &[u8] {
669         unsafe {
670             let ptr = llvm::LLVMRustThinLTOBufferPtr(self.0) as *const _;
671             let len = llvm::LLVMRustThinLTOBufferLen(self.0);
672             slice::from_raw_parts(ptr, len)
673         }
674     }
675 }
676
677 impl Drop for ThinBuffer {
678     fn drop(&mut self) {
679         unsafe {
680             llvm::LLVMRustThinLTOBufferFree(&mut *(self.0 as *mut _));
681         }
682     }
683 }
684
685 pub unsafe fn optimize_thin_module(
686     thin_module: ThinModule<LlvmCodegenBackend>,
687     cgcx: &CodegenContext<LlvmCodegenBackend>,
688 ) -> Result<ModuleCodegen<ModuleLlvm>, FatalError> {
689     let diag_handler = cgcx.create_diag_handler();
690
691     let module_name = &thin_module.shared.module_names[thin_module.idx];
692     let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, module_name.to_str().unwrap());
693     let tm = (cgcx.tm_factory)(tm_factory_config).map_err(|e| write::llvm_err(&diag_handler, e))?;
694
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,
706     };
707     {
708         let target = &*module.module_llvm.tm;
709         let llmod = module.module_llvm.llmod();
710         save_temp_bitcode(cgcx, &module, "thin-lto-input");
711
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
715         // an error.
716         let mut cu1 = ptr::null_mut();
717         let mut cu2 = ptr::null_mut();
718         llvm::LLVMRustThinLTOGetDICompileUnit(llmod, &mut cu1, &mut cu2);
719         if !cu2.is_null() {
720             return Err(write::llvm_err(&diag_handler, LlvmError::MultipleSourceDiCompileUnit));
721         }
722
723         // Up next comes the per-module local analyses that we do for Thin LTO.
724         // Each of these functions is basically copied from the LLVM
725         // implementation and then tailored to suit this implementation. Ideally
726         // each of these would be supported by upstream LLVM but that's perhaps
727         // a patch for another day!
728         //
729         // You can find some more comments about these functions in the LLVM
730         // bindings we've got (currently `PassWrapper.cpp`)
731         {
732             let _timer =
733                 cgcx.prof.generic_activity_with_arg("LLVM_thin_lto_rename", thin_module.name());
734             if !llvm::LLVMRustPrepareThinLTORename(thin_module.shared.data.0, llmod, target) {
735                 return Err(write::llvm_err(&diag_handler, LlvmError::PrepareThinLtoModule));
736             }
737             save_temp_bitcode(cgcx, &module, "thin-lto-after-rename");
738         }
739
740         {
741             let _timer = cgcx
742                 .prof
743                 .generic_activity_with_arg("LLVM_thin_lto_resolve_weak", thin_module.name());
744             if !llvm::LLVMRustPrepareThinLTOResolveWeak(thin_module.shared.data.0, llmod) {
745                 return Err(write::llvm_err(&diag_handler, LlvmError::PrepareThinLtoModule));
746             }
747             save_temp_bitcode(cgcx, &module, "thin-lto-after-resolve");
748         }
749
750         {
751             let _timer = cgcx
752                 .prof
753                 .generic_activity_with_arg("LLVM_thin_lto_internalize", thin_module.name());
754             if !llvm::LLVMRustPrepareThinLTOInternalize(thin_module.shared.data.0, llmod) {
755                 return Err(write::llvm_err(&diag_handler, LlvmError::PrepareThinLtoModule));
756             }
757             save_temp_bitcode(cgcx, &module, "thin-lto-after-internalize");
758         }
759
760         {
761             let _timer =
762                 cgcx.prof.generic_activity_with_arg("LLVM_thin_lto_import", thin_module.name());
763             if !llvm::LLVMRustPrepareThinLTOImport(thin_module.shared.data.0, llmod, target) {
764                 return Err(write::llvm_err(&diag_handler, LlvmError::PrepareThinLtoModule));
765             }
766             save_temp_bitcode(cgcx, &module, "thin-lto-after-import");
767         }
768
769         // Ok now this is a bit unfortunate. This is also something you won't
770         // find upstream in LLVM's ThinLTO passes! This is a hack for now to
771         // work around bugs in LLVM.
772         //
773         // First discovered in #45511 it was found that as part of ThinLTO
774         // importing passes LLVM will import `DICompileUnit` metadata
775         // information across modules. This means that we'll be working with one
776         // LLVM module that has multiple `DICompileUnit` instances in it (a
777         // bunch of `llvm.dbg.cu` members). Unfortunately there's a number of
778         // bugs in LLVM's backend which generates invalid DWARF in a situation
779         // like this:
780         //
781         //  https://bugs.llvm.org/show_bug.cgi?id=35212
782         //  https://bugs.llvm.org/show_bug.cgi?id=35562
783         //
784         // While the first bug there is fixed the second ended up causing #46346
785         // which was basically a resurgence of #45511 after LLVM's bug 35212 was
786         // fixed.
787         //
788         // This function below is a huge hack around this problem. The function
789         // below is defined in `PassWrapper.cpp` and will basically "merge"
790         // all `DICompileUnit` instances in a module. Basically it'll take all
791         // the objects, rewrite all pointers of `DISubprogram` to point to the
792         // first `DICompileUnit`, and then delete all the other units.
793         //
794         // This is probably mangling to the debug info slightly (but hopefully
795         // not too much) but for now at least gets LLVM to emit valid DWARF (or
796         // so it appears). Hopefully we can remove this once upstream bugs are
797         // fixed in LLVM.
798         {
799             let _timer = cgcx
800                 .prof
801                 .generic_activity_with_arg("LLVM_thin_lto_patch_debuginfo", thin_module.name());
802             llvm::LLVMRustThinLTOPatchDICompileUnit(llmod, cu1);
803             save_temp_bitcode(cgcx, &module, "thin-lto-after-patch");
804         }
805
806         // Alright now that we've done everything related to the ThinLTO
807         // analysis it's time to run some optimizations! Here we use the same
808         // `run_pass_manager` as the "fat" LTO above except that we tell it to
809         // populate a thin-specific pass manager, which presumably LLVM treats a
810         // little differently.
811         {
812             info!("running thin lto passes over {}", module.name);
813             run_pass_manager(cgcx, &diag_handler, &mut module, true)?;
814             save_temp_bitcode(cgcx, &module, "thin-lto-after-pm");
815         }
816     }
817     Ok(module)
818 }
819
820 /// Maps LLVM module identifiers to their corresponding LLVM LTO cache keys
821 #[derive(Debug, Default)]
822 pub struct ThinLTOKeysMap {
823     // key = llvm name of importing module, value = LLVM cache key
824     keys: FxHashMap<String, String>,
825 }
826
827 impl ThinLTOKeysMap {
828     fn save_to_file(&self, path: &Path) -> io::Result<()> {
829         use std::io::Write;
830         let file = File::create(path)?;
831         let mut writer = io::BufWriter::new(file);
832         for (module, key) in &self.keys {
833             writeln!(writer, "{} {}", module, key)?;
834         }
835         Ok(())
836     }
837
838     fn load_from_file(path: &Path) -> io::Result<Self> {
839         use std::io::BufRead;
840         let mut keys = FxHashMap::default();
841         let file = File::open(path)?;
842         for line in io::BufReader::new(file).lines() {
843             let line = line?;
844             let mut split = line.split(' ');
845             let module = split.next().unwrap();
846             let key = split.next().unwrap();
847             assert_eq!(split.next(), None, "Expected two space-separated values, found {:?}", line);
848             keys.insert(module.to_string(), key.to_string());
849         }
850         Ok(Self { keys })
851     }
852
853     fn from_thin_lto_modules(
854         data: &ThinData,
855         modules: &[llvm::ThinLTOModule],
856         names: &[CString],
857     ) -> Self {
858         let keys = iter::zip(modules, names)
859             .map(|(module, name)| {
860                 let key = build_string(|rust_str| unsafe {
861                     llvm::LLVMRustComputeLTOCacheKey(rust_str, module.identifier, data.0);
862                 })
863                 .expect("Invalid ThinLTO module key");
864                 (name.clone().into_string().unwrap(), key)
865             })
866             .collect();
867         Self { keys }
868     }
869 }
870
871 fn module_name_to_str(c_str: &CStr) -> &str {
872     c_str.to_str().unwrap_or_else(|e| {
873         bug!("Encountered non-utf8 LLVM module name `{}`: {}", c_str.to_string_lossy(), e)
874     })
875 }
876
877 pub fn parse_module<'a>(
878     cx: &'a llvm::Context,
879     name: &CStr,
880     data: &[u8],
881     diag_handler: &Handler,
882 ) -> Result<&'a llvm::Module, FatalError> {
883     unsafe {
884         llvm::LLVMRustParseBitcodeForLTO(cx, data.as_ptr(), data.len(), name.as_ptr())
885             .ok_or_else(|| write::llvm_err(diag_handler, LlvmError::ParseBitcode))
886     }
887 }