]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/back/lto.rs
Beginning of moving all backend-agnostic code to rustc_codegen_ssa
[rust.git] / src / librustc_codegen_llvm / back / lto.rs
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.
4 //
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.
10
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};
17 use memmap;
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;
27 use ModuleLlvm;
28 use rustc_codegen_ssa::{ModuleCodegen, ModuleKind};
29
30 use libc;
31
32 use std::ffi::{CStr, CString};
33 use std::fs;
34 use std::ptr;
35 use std::slice;
36 use std::sync::Arc;
37
38 pub fn crate_type_allows_lto(crate_type: config::CrateType) -> bool {
39     match crate_type {
40         config::CrateType::Executable |
41         config::CrateType::Staticlib  |
42         config::CrateType::Cdylib     => true,
43
44         config::CrateType::Dylib     |
45         config::CrateType::Rlib      |
46         config::CrateType::ProcMacro => false,
47     }
48 }
49
50 pub(crate) enum LtoModuleCodegen {
51     Fat {
52         module: Option<ModuleCodegen<ModuleLlvm>>,
53         _serialized_bitcode: Vec<SerializedModule>,
54     },
55
56     Thin(ThinModule),
57 }
58
59 impl LtoModuleCodegen {
60     pub fn name(&self) -> &str {
61         match *self {
62             LtoModuleCodegen::Fat { .. } => "everything",
63             LtoModuleCodegen::Thin(ref m) => m.name(),
64         }
65     }
66
67     /// Optimize this module within the given codegen context.
68     ///
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>
77     {
78         match *self {
79             LtoModuleCodegen::Fat { ref mut module, .. } => {
80                 let module = module.take().unwrap();
81                 {
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");
87                 }
88                 Ok(module)
89             }
90             LtoModuleCodegen::Thin(ref mut thin) => thin.optimize(cgcx, timeline),
91         }
92     }
93
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 {
97         match *self {
98             // Only one module with fat LTO, so the cost doesn't matter.
99             LtoModuleCodegen::Fat { .. } => 0,
100             LtoModuleCodegen::Thin(ref m) => m.cost(),
101         }
102     }
103 }
104
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>
115 {
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,
120
121         // We're doing LTO for the entire crate graph
122         Lto::Fat | Lto::Thin => {
123             symbol_export::crates_export_threshold(&cgcx.crate_types)
124         }
125
126         Lto::No => panic!("didn't request LTO but we're doing LTO"),
127     };
128
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())
134         } else {
135             None
136         }
137     };
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]
141         .iter()
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());
146
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
149     // from the archive.
150     //
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 \
158                                supported with LTO")
159                         .emit();
160             return Err(FatalError)
161         }
162
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");
168                 return Err(e)
169             }
170         }
171
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]
177                     .iter()
178                     .filter_map(symbol_filter));
179
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();
187
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)),
192                     }
193                 })?;
194                 let bc = SerializedModule::FromRlib(bc);
195                 upstream_modules.push((bc, CString::new(id).unwrap()));
196             }
197             timeline.record(&format!("load: {}", path.display()));
198         }
199     }
200
201     let symbol_white_list = symbol_white_list.iter()
202                                              .map(|c| c.as_ptr())
203                                              .collect::<Vec<_>>();
204     match cgcx.lto {
205         Lto::Fat => {
206             assert!(cached_modules.is_empty());
207             let opt_jobs = fat_lto(cgcx,
208                                    &diag_handler,
209                                    modules,
210                                    upstream_modules,
211                                    &symbol_white_list,
212                                    timeline);
213             opt_jobs.map(|opt_jobs| (opt_jobs, vec![]))
214         }
215         Lto::Thin |
216         Lto::ThinLocal => {
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");
220             }
221             thin_lto(cgcx,
222                      &diag_handler,
223                      modules,
224                      upstream_modules,
225                      cached_modules,
226                      &symbol_white_list,
227                      timeline)
228         }
229         Lto::No => unreachable!(),
230     }
231 }
232
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>
240 {
241     info!("going for a fat lto");
242
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
246     // codegen unit.
247     //
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()
253         .enumerate()
254         .filter(|&(_, module)| module.kind == ModuleKind::Regular)
255         .map(|(i, module)| {
256             let cost = unsafe {
257                 llvm::LLVMRustModuleCost(module.module_llvm.llmod())
258             };
259             (cost, i)
260         })
261         .max()
262         .expect("must be codegen'ing at least one module");
263     let module = modules.remove(costliest_module);
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 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));
286         }
287
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)
300                 })
301             })?;
302             timeline.record(&format!("link {:?}", name));
303             serialized_bitcode.push(bc_decoded);
304         }
305         drop(linker);
306         cgcx.save_temp_bitcode(&module, "lto.input");
307
308         // Internalize everything that *isn't* in our whitelist to help strip out
309         // more modules and such
310         unsafe {
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");
316         }
317
318         if cgcx.no_landing_pads {
319             unsafe {
320                 llvm::LLVMRustMarkAllFunctionsNounwind(llmod);
321             }
322             cgcx.save_temp_bitcode(&module, "lto.after-nounwind");
323         }
324         timeline.record("passes");
325     }
326
327     Ok(vec![LtoModuleCodegen::Fat {
328         module: Some(module),
329         _serialized_bitcode: serialized_bitcode,
330     }])
331 }
332
333 struct Linker<'a>(&'a mut llvm::Linker<'a>);
334
335 impl Linker<'a> {
336     fn new(llmod: &'a llvm::Module) -> Self {
337         unsafe { Linker(llvm::LLVMRustLinkerNew(llmod)) }
338     }
339
340     fn add(&mut self, bytecode: &[u8]) -> Result<(), ()> {
341         unsafe {
342             if llvm::LLVMRustLinkerAdd(self.0,
343                                        bytecode.as_ptr() as *const libc::c_char,
344                                        bytecode.len()) {
345                 Ok(())
346             } else {
347                 Err(())
348             }
349         }
350     }
351 }
352
353 impl Drop for Linker<'a> {
354     fn drop(&mut self) {
355         unsafe { llvm::LLVMRustLinkerFree(&mut *(self.0 as *mut _)); }
356     }
357 }
358
359 /// Prepare "thin" LTO to get run on these modules.
360 ///
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.
366 ///
367 /// At a high level Thin LTO looks like:
368 ///
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.
378 ///
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.
384 ///
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>
397 {
398     unsafe {
399         info!("going for that thin, thin LTO");
400
401         let green_modules: FxHashMap<_, _> = cached_modules
402             .iter()
403             .map(|&(_, ref wp)| (wp.cgu_name.clone(), wp.clone()))
404             .collect();
405
406         let mut thin_buffers = Vec::new();
407         let mut module_names = Vec::new();
408         let mut thin_modules = Vec::new();
409
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
416         //        analysis!
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());
421
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));
428
429                     fs::write(&path, buffer.data()).unwrap_or_else(|e| {
430                         panic!("Error writing pre-lto-bitcode file `{}`: {}",
431                                path.display(),
432                                e);
433                     });
434                 }
435             }
436
437             thin_modules.push(llvm::ThinLTOModule {
438                 identifier: name.as_ptr(),
439                 data: buffer.data().as_ptr(),
440                 len: buffer.data().len(),
441             });
442             thin_buffers.push(buffer);
443             module_names.push(name);
444             timeline.record(&module.name);
445         }
446
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.
457         //
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();
464
465         let cached_modules = cached_modules.into_iter().map(|(sm, wp)| {
466             (sm, CString::new(wp.cgu_name).unwrap())
467         });
468
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(),
475             });
476             serialized.push(module);
477             module_names.push(name);
478         }
479
480         // Sanity check
481         assert_eq!(thin_modules.len(), module_names.len());
482
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
486         // upstream...
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,
492         ).ok_or_else(|| {
493             write::llvm_err(&diag_handler, "failed to prepare thin LTO context")
494         })?;
495
496         info!("thin LTO data created");
497         timeline.record("data");
498
499         let import_map = if cgcx.incr_comp_session_dir.is_some() {
500             ThinLTOImports::from_thin_lto_data(data)
501         } else {
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()
506         };
507         info!("thin LTO import map loaded");
508         timeline.record("import-map-loaded");
509
510         let data = ThinData(data);
511
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 {
517             data,
518             thin_buffers,
519             serialized_modules: serialized,
520             module_names,
521         });
522
523         let mut copy_jobs = vec![];
524         let mut opt_jobs = vec![];
525
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);
529
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
532             // module.
533             if green_modules.contains_key(module_name) {
534                 let imports_all_green = import_map.modules_imported_by(module_name)
535                     .iter()
536                     .all(|imported_module| green_modules.contains_key(imported_module));
537
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,
543                                                             CguReuse::PostLto);
544                     continue
545                 }
546             }
547
548             info!(" - {}: re-compiled", module_name);
549             opt_jobs.push(LtoModuleCodegen::Thin(ThinModule {
550                 shared: shared.clone(),
551                 idx: module_index,
552             }));
553         }
554
555         Ok((opt_jobs, copy_jobs))
556     }
557 }
558
559 fn run_pass_manager(cgcx: &CodegenContext,
560                     tm: &llvm::TargetMachine,
561                     llmod: &llvm::Module,
562                     config: &ModuleConfig,
563                     thin: bool) {
564     // Now we have one massive module inside of llmod. Time to run the
565     // LTO-specific optimization passes that LLVM provides.
566     //
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");
570     unsafe {
571         let pm = llvm::LLVMCreatePassManager();
572         llvm::LLVMRustAddAnalysisPasses(tm, pm, llmod);
573
574         if config.verify_llvm_ir {
575             let pass = llvm::LLVMRustFindAndCreatePass("verify\0".as_ptr() as *const _);
576             llvm::LLVMRustAddPass(pm, pass.unwrap());
577         }
578
579         // When optimizing for LTO we don't actually pass in `-O0`, but we force
580         // it to always happen at least with `-O1`.
581         //
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.
587         //
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
590         // otherwise.
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,
594             level => level,
595         };
596         with_llvm_pmb(llmod, config, opt_level, false, &mut |b| {
597             if thin {
598                 llvm::LLVMRustPassManagerBuilderPopulateThinLTOPassManager(b, pm);
599             } else {
600                 llvm::LLVMPassManagerBuilderPopulateLTOPassManager(b, pm,
601                     /* Internalize = */ False,
602                     /* RunInliner = */ True);
603             }
604         });
605
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());
611         }
612
613         if config.verify_llvm_ir {
614             let pass = llvm::LLVMRustFindAndCreatePass("verify\0".as_ptr() as *const _);
615             llvm::LLVMRustAddPass(pm, pass.unwrap());
616         }
617
618         time_ext(cgcx.time_passes, None, "LTO passes", || llvm::LLVMRunPassManager(pm, llmod));
619
620         llvm::LLVMDisposePassManager(pm);
621     }
622     debug!("lto done");
623 }
624
625 pub enum SerializedModule {
626     Local(ModuleBuffer),
627     FromRlib(Vec<u8>),
628     FromUncompressedFile(memmap::Mmap),
629 }
630
631 impl SerializedModule {
632     fn data(&self) -> &[u8] {
633         match *self {
634             SerializedModule::Local(ref m) => m.data(),
635             SerializedModule::FromRlib(ref m) => m,
636             SerializedModule::FromUncompressedFile(ref m) => m,
637         }
638     }
639 }
640
641 pub struct ModuleBuffer(&'static mut llvm::ModuleBuffer);
642
643 unsafe impl Send for ModuleBuffer {}
644 unsafe impl Sync for ModuleBuffer {}
645
646 impl ModuleBuffer {
647     pub fn new(m: &llvm::Module) -> ModuleBuffer {
648         ModuleBuffer(unsafe {
649             llvm::LLVMRustModuleBufferCreate(m)
650         })
651     }
652
653     pub fn data(&self) -> &[u8] {
654         unsafe {
655             let ptr = llvm::LLVMRustModuleBufferPtr(self.0);
656             let len = llvm::LLVMRustModuleBufferLen(self.0);
657             slice::from_raw_parts(ptr, len)
658         }
659     }
660 }
661
662 impl Drop for ModuleBuffer {
663     fn drop(&mut self) {
664         unsafe { llvm::LLVMRustModuleBufferFree(&mut *(self.0 as *mut _)); }
665     }
666 }
667
668 pub struct ThinModule {
669     shared: Arc<ThinShared>,
670     idx: usize,
671 }
672
673 struct ThinShared {
674     data: ThinData,
675     thin_buffers: Vec<ThinBuffer>,
676     serialized_modules: Vec<SerializedModule>,
677     module_names: Vec<CString>,
678 }
679
680 struct ThinData(&'static mut llvm::ThinLTOData);
681
682 unsafe impl Send for ThinData {}
683 unsafe impl Sync for ThinData {}
684
685 impl Drop for ThinData {
686     fn drop(&mut self) {
687         unsafe {
688             llvm::LLVMRustFreeThinLTOData(&mut *(self.0 as *mut _));
689         }
690     }
691 }
692
693 pub struct ThinBuffer(&'static mut llvm::ThinLTOBuffer);
694
695 unsafe impl Send for ThinBuffer {}
696 unsafe impl Sync for ThinBuffer {}
697
698 impl ThinBuffer {
699     pub fn new(m: &llvm::Module) -> ThinBuffer {
700         unsafe {
701             let buffer = llvm::LLVMRustThinLTOBufferCreate(m);
702             ThinBuffer(buffer)
703         }
704     }
705
706     pub fn data(&self) -> &[u8] {
707         unsafe {
708             let ptr = llvm::LLVMRustThinLTOBufferPtr(self.0) as *const _;
709             let len = llvm::LLVMRustThinLTOBufferLen(self.0);
710             slice::from_raw_parts(ptr, len)
711         }
712     }
713 }
714
715 impl Drop for ThinBuffer {
716     fn drop(&mut self) {
717         unsafe {
718             llvm::LLVMRustThinLTOBufferFree(&mut *(self.0 as *mut _));
719         }
720     }
721 }
722
723 impl ThinModule {
724     fn name(&self) -> &str {
725         self.shared.module_names[self.idx].to_str().unwrap()
726     }
727
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
732     }
733
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()
739         })
740     }
741
742     unsafe fn optimize(&mut self, cgcx: &CodegenContext, timeline: &mut Timeline)
743         -> Result<ModuleCodegen<ModuleLlvm>, FatalError>
744     {
745         let diag_handler = cgcx.create_diag_handler();
746         let tm = (cgcx.tm_factory)().map_err(|e| {
747             write::llvm_err(&diag_handler, &e)
748         })?;
749
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(
757             llcx,
758             self.data().as_ptr(),
759             self.data().len(),
760             self.shared.module_names[self.idx].as_ptr(),
761         ).ok_or_else(|| {
762             let msg = "failed to parse bitcode for thin LTO module";
763             write::llvm_err(&diag_handler, msg)
764         })? as *const _;
765         let module = ModuleCodegen {
766             module_llvm: ModuleLlvm {
767                 llmod_raw,
768                 llcx,
769                 tm,
770             },
771             name: self.name().to_string(),
772             kind: ModuleKind::Regular,
773         };
774         {
775             let llmod = module.module_llvm.llmod();
776             cgcx.save_temp_bitcode(&module, "thin-lto-input");
777
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
781             // an error.
782             let mut cu1 = ptr::null_mut();
783             let mut cu2 = ptr::null_mut();
784             llvm::LLVMRustThinLTOGetDICompileUnit(llmod, &mut cu1, &mut cu2);
785             if !cu2.is_null() {
786                 let msg = "multiple source DICompileUnits found";
787                 return Err(write::llvm_err(&diag_handler, msg))
788             }
789
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");
796             }
797
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!
803             //
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))
809             }
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))
815             }
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))
821             }
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))
827             }
828             cgcx.save_temp_bitcode(&module, "thin-lto-after-import");
829             timeline.record("import");
830
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.
834             //
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
841             // like this:
842             //
843             //  https://bugs.llvm.org/show_bug.cgi?id=35212
844             //  https://bugs.llvm.org/show_bug.cgi?id=35562
845             //
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
848             // fixed.
849             //
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.
855             //
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
859             // fixed in LLVM.
860             llvm::LLVMRustThinLTOPatchDICompileUnit(llmod, cu1);
861             cgcx.save_temp_bitcode(&module, "thin-lto-after-patch");
862             timeline.record("patch");
863
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");
874         }
875
876         Ok(module)
877     }
878 }
879
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>>,
884 }
885
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(&[])
889     }
890
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);
901
902             if !map.imports.contains_key(importing_module_name) {
903                 map.imports.insert(importing_module_name.to_owned(), vec![]);
904             }
905
906             map.imports
907                .get_mut(importing_module_name)
908                .unwrap()
909                .push(imported_module_name.to_owned());
910         }
911         let mut map = ThinLTOImports::default();
912         llvm::LLVMRustGetThinLTOModuleImports(data,
913                                               imported_module_callback,
914                                               &mut map as *mut _ as *mut libc::c_void);
915         map
916     }
917 }
918
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))
922 }