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