]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/lib.rs
Preparing the generalization of base:compile_coodegen_unit
[rust.git] / src / librustc_codegen_llvm / lib.rs
1 // Copyright 2012-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 //! The Rust compiler.
12 //!
13 //! # Note
14 //!
15 //! This API is completely unstable and subject to change.
16
17 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
18       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
19       html_root_url = "https://doc.rust-lang.org/nightly/")]
20
21 #![feature(box_patterns)]
22 #![feature(box_syntax)]
23 #![feature(crate_visibility_modifier)]
24 #![feature(custom_attribute)]
25 #![feature(extern_types)]
26 #![feature(in_band_lifetimes)]
27 #![allow(unused_attributes)]
28 #![feature(libc)]
29 #![feature(nll)]
30 #![feature(quote)]
31 #![feature(range_contains)]
32 #![feature(rustc_diagnostic_macros)]
33 #![feature(slice_sort_by_cached_key)]
34 #![feature(optin_builtin_traits)]
35 #![feature(concat_idents)]
36 #![feature(link_args)]
37 #![feature(static_nobundle)]
38
39 use back::write::create_target_machine;
40 use rustc::dep_graph::WorkProduct;
41 use syntax_pos::symbol::Symbol;
42
43 #[macro_use] extern crate bitflags;
44 extern crate flate2;
45 extern crate libc;
46 #[macro_use] extern crate rustc;
47 extern crate jobserver;
48 extern crate num_cpus;
49 extern crate rustc_mir;
50 extern crate rustc_allocator;
51 extern crate rustc_apfloat;
52 extern crate rustc_target;
53 #[macro_use] extern crate rustc_data_structures;
54 extern crate rustc_demangle;
55 extern crate rustc_incremental;
56 extern crate rustc_llvm;
57 extern crate rustc_platform_intrinsics as intrinsics;
58 extern crate rustc_codegen_utils;
59 extern crate rustc_fs_util;
60
61 #[macro_use] extern crate log;
62 #[macro_use] extern crate syntax;
63 extern crate syntax_pos;
64 extern crate rustc_errors as errors;
65 extern crate serialize;
66 extern crate cc; // Used to locate MSVC
67 extern crate tempfile;
68 extern crate memmap;
69
70 use back::bytecode::RLIB_BYTECODE_EXTENSION;
71 use interfaces::*;
72 use time_graph::TimeGraph;
73 use std::sync::mpsc::Receiver;
74 use back::write::{self, OngoingCodegen};
75 use context::CodegenCx;
76 use monomorphize::partitioning::CodegenUnit;
77
78 pub use llvm_util::target_features;
79 use std::any::Any;
80 use std::sync::Arc;
81 use std::sync::mpsc;
82 use rustc_data_structures::sync::Lrc;
83
84 use rustc::dep_graph::DepGraph;
85 use rustc::hir::def_id::CrateNum;
86 use rustc::middle::allocator::AllocatorKind;
87 use rustc::middle::cstore::{EncodedMetadata, MetadataLoader};
88 use rustc::middle::cstore::{NativeLibrary, CrateSource, LibSource};
89 use rustc::middle::lang_items::LangItem;
90 use rustc::session::{Session, CompileIncomplete};
91 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
92 use rustc::ty::{self, TyCtxt};
93 use rustc::util::time_graph;
94 use rustc::util::nodemap::{FxHashSet, FxHashMap};
95 use rustc::util::profiling::ProfileCategory;
96 use rustc_mir::monomorphize;
97 use rustc_codegen_utils::{CompiledModule, ModuleKind};
98 use rustc_codegen_utils::codegen_backend::CodegenBackend;
99 use rustc_data_structures::svh::Svh;
100
101 mod diagnostics;
102
103 mod back {
104     mod archive;
105     pub mod bytecode;
106     pub mod link;
107     pub mod lto;
108     pub mod write;
109     mod rpath;
110     pub mod wasm;
111 }
112
113 mod interfaces;
114
115 mod abi;
116 mod allocator;
117 mod asm;
118 mod attributes;
119 mod base;
120 mod builder;
121 mod callee;
122 mod common;
123 mod consts;
124 mod context;
125 mod debuginfo;
126 mod declare;
127 mod glue;
128 mod intrinsic;
129
130 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
131 #[path = "llvm/mod.rs"] mod llvm_; pub mod llvm { pub use super::llvm_::*; }
132
133 mod llvm_util;
134 mod metadata;
135 mod meth;
136 mod mir;
137 mod mono_item;
138 mod type_;
139 mod type_of;
140 mod value;
141
142 pub struct LlvmCodegenBackend(());
143
144 impl BackendMethods for LlvmCodegenBackend {
145     type Module = ModuleLlvm;
146     type OngoingCodegen = OngoingCodegen;
147
148     fn new_metadata(&self, sess: &Session, mod_name: &str) -> ModuleLlvm {
149         ModuleLlvm::new(sess, mod_name)
150     }
151     fn write_metadata<'b, 'gcx>(
152         &self,
153         tcx: TyCtxt<'b, 'gcx, 'gcx>,
154         metadata: &ModuleLlvm
155     ) -> EncodedMetadata {
156         base::write_metadata(tcx, metadata)
157     }
158     fn start_async_codegen(
159         &self,
160         tcx: TyCtxt,
161         time_graph: Option<TimeGraph>,
162         metadata: EncodedMetadata,
163         coordinator_receive: Receiver<Box<dyn Any + Send>>,
164         total_cgus: usize
165     ) -> OngoingCodegen {
166         write::start_async_codegen(tcx, time_graph, metadata, coordinator_receive, total_cgus)
167     }
168     fn submit_pre_codegened_module_to_llvm(
169         &self,
170         codegen: &OngoingCodegen,
171         tcx: TyCtxt,
172         module: ModuleCodegen<ModuleLlvm>
173     ) {
174         codegen.submit_pre_codegened_module_to_llvm(tcx, module)
175     }
176     fn codegen_aborted(codegen: OngoingCodegen) {
177         codegen.codegen_aborted();
178     }
179     fn codegen_finished(&self, codegen: &OngoingCodegen, tcx: TyCtxt) {
180         codegen.codegen_finished(tcx)
181     }
182     fn check_for_errors(&self, codegen: &OngoingCodegen, sess: &Session) {
183         codegen.check_for_errors(sess)
184     }
185     fn codegen_allocator(&self, tcx: TyCtxt, mods: &ModuleLlvm, kind: AllocatorKind) {
186         unsafe { allocator::codegen(tcx, mods, kind) }
187     }
188     fn wait_for_signal_to_codegen_item(&self, codegen: &OngoingCodegen) {
189         codegen.wait_for_signal_to_codegen_item()
190     }
191 }
192
193 impl<'a, 'tcx: 'a> BackendCodegenCxMethods<'a, 'tcx> for LlvmCodegenBackend {
194     type CodegenCx = CodegenCx<'a, 'tcx>;
195
196     fn new_codegen_context(
197         &self,
198         tcx: TyCtxt<'a, 'tcx, 'tcx>,
199         codegen_unit: Arc<CodegenUnit<'tcx>>,
200         llvm_module: &'a ModuleLlvm
201     ) -> CodegenCx<'a, 'tcx> {
202         CodegenCx::new(tcx, codegen_unit, llvm_module)
203     }
204 }
205
206
207 impl !Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
208 impl !Sync for LlvmCodegenBackend {}
209
210 impl LlvmCodegenBackend {
211     pub fn new() -> Box<dyn CodegenBackend> {
212         box LlvmCodegenBackend(())
213     }
214 }
215
216 impl CodegenBackend for LlvmCodegenBackend {
217     fn init(&self, sess: &Session) {
218         llvm_util::init(sess); // Make sure llvm is inited
219     }
220
221     fn print(&self, req: PrintRequest, sess: &Session) {
222         match req {
223             PrintRequest::RelocationModels => {
224                 println!("Available relocation models:");
225                 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
226                     println!("    {}", name);
227                 }
228                 println!("");
229             }
230             PrintRequest::CodeModels => {
231                 println!("Available code models:");
232                 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
233                     println!("    {}", name);
234                 }
235                 println!("");
236             }
237             PrintRequest::TlsModels => {
238                 println!("Available TLS models:");
239                 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
240                     println!("    {}", name);
241                 }
242                 println!("");
243             }
244             req => llvm_util::print(req, sess),
245         }
246     }
247
248     fn print_passes(&self) {
249         llvm_util::print_passes();
250     }
251
252     fn print_version(&self) {
253         llvm_util::print_version();
254     }
255
256     fn diagnostics(&self) -> &[(&'static str, &'static str)] {
257         &DIAGNOSTICS
258     }
259
260     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
261         target_features(sess)
262     }
263
264     fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
265         box metadata::LlvmMetadataLoader
266     }
267
268     fn provide(&self, providers: &mut ty::query::Providers) {
269         rustc_codegen_utils::symbol_export::provide(providers);
270         rustc_codegen_utils::symbol_names::provide(providers);
271         base::provide_both(providers);
272         attributes::provide(providers);
273     }
274
275     fn provide_extern(&self, providers: &mut ty::query::Providers) {
276         rustc_codegen_utils::symbol_export::provide_extern(providers);
277         base::provide_both(providers);
278         attributes::provide_extern(providers);
279     }
280
281     fn codegen_crate<'a, 'tcx>(
282         &self,
283         tcx: TyCtxt<'a, 'tcx, 'tcx>,
284         rx: mpsc::Receiver<Box<dyn Any + Send>>
285     ) -> Box<dyn Any> {
286         box base::codegen_crate(LlvmCodegenBackend(()), tcx, rx)
287     }
288
289     fn join_codegen_and_link(
290         &self,
291         ongoing_codegen: Box<dyn Any>,
292         sess: &Session,
293         dep_graph: &DepGraph,
294         outputs: &OutputFilenames,
295     ) -> Result<(), CompileIncomplete>{
296         use rustc::util::common::time;
297         let (ongoing_codegen, work_products) =
298             ongoing_codegen.downcast::<::back::write::OngoingCodegen>()
299                 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
300                 .join(sess);
301         if sess.opts.debugging_opts.incremental_info {
302             back::write::dump_incremental_data(&ongoing_codegen);
303         }
304
305         time(sess,
306              "serialize work products",
307              move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
308
309         sess.compile_status()?;
310
311         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
312                                                    i == OutputType::Metadata) {
313             return Ok(());
314         }
315
316         // Run the linker on any artifacts that resulted from the LLVM run.
317         // This should produce either a finished executable or library.
318         sess.profiler(|p| p.start_activity(ProfileCategory::Linking));
319         time(sess, "linking", || {
320             back::link::link_binary(sess, &ongoing_codegen,
321                                     outputs, &ongoing_codegen.crate_name.as_str());
322         });
323         sess.profiler(|p| p.end_activity(ProfileCategory::Linking));
324
325         // Now that we won't touch anything in the incremental compilation directory
326         // any more, we can finalize it (which involves renaming it)
327         rustc_incremental::finalize_session_directory(sess, ongoing_codegen.crate_hash);
328
329         Ok(())
330     }
331 }
332
333 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
334 #[no_mangle]
335 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
336     LlvmCodegenBackend::new()
337 }
338
339 pub struct ModuleCodegen<M> {
340     /// The name of the module. When the crate may be saved between
341     /// compilations, incremental compilation requires that name be
342     /// unique amongst **all** crates.  Therefore, it should contain
343     /// something unique to this crate (e.g., a module path) as well
344     /// as the crate name and disambiguator.
345     /// We currently generate these names via CodegenUnit::build_cgu_name().
346     name: String,
347     module_llvm: M,
348     kind: ModuleKind,
349 }
350
351 struct CachedModuleCodegen {
352     name: String,
353     source: WorkProduct,
354 }
355
356 impl ModuleCodegen<ModuleLlvm> {
357     fn into_compiled_module(self,
358                             emit_obj: bool,
359                             emit_bc: bool,
360                             emit_bc_compressed: bool,
361                             outputs: &OutputFilenames) -> CompiledModule {
362         let object = if emit_obj {
363             Some(outputs.temp_path(OutputType::Object, Some(&self.name)))
364         } else {
365             None
366         };
367         let bytecode = if emit_bc {
368             Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name)))
369         } else {
370             None
371         };
372         let bytecode_compressed = if emit_bc_compressed {
373             Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name))
374                         .with_extension(RLIB_BYTECODE_EXTENSION))
375         } else {
376             None
377         };
378
379         CompiledModule {
380             name: self.name.clone(),
381             kind: self.kind,
382             object,
383             bytecode,
384             bytecode_compressed,
385         }
386     }
387 }
388
389 pub struct ModuleLlvm {
390     llcx: &'static mut llvm::Context,
391     llmod_raw: *const llvm::Module,
392     tm: &'static mut llvm::TargetMachine,
393 }
394
395 unsafe impl Send for ModuleLlvm { }
396 unsafe impl Sync for ModuleLlvm { }
397
398 impl ModuleLlvm {
399     fn new(sess: &Session, mod_name: &str) -> Self {
400         unsafe {
401             let llcx = llvm::LLVMRustContextCreate(sess.fewer_names());
402             let llmod_raw = context::create_module(sess, llcx, mod_name) as *const _;
403
404             ModuleLlvm {
405                 llmod_raw,
406                 llcx,
407                 tm: create_target_machine(sess, false),
408             }
409         }
410     }
411
412     fn llmod(&self) -> &llvm::Module {
413         unsafe {
414             &*self.llmod_raw
415         }
416     }
417 }
418
419 impl Drop for ModuleLlvm {
420     fn drop(&mut self) {
421         unsafe {
422             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
423             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
424         }
425     }
426 }
427
428 struct CodegenResults {
429     crate_name: Symbol,
430     modules: Vec<CompiledModule>,
431     allocator_module: Option<CompiledModule>,
432     metadata_module: CompiledModule,
433     crate_hash: Svh,
434     metadata: rustc::middle::cstore::EncodedMetadata,
435     windows_subsystem: Option<String>,
436     linker_info: rustc_codegen_utils::linker::LinkerInfo,
437     crate_info: CrateInfo,
438 }
439
440 /// Misc info we load from metadata to persist beyond the tcx
441 struct CrateInfo {
442     panic_runtime: Option<CrateNum>,
443     compiler_builtins: Option<CrateNum>,
444     profiler_runtime: Option<CrateNum>,
445     sanitizer_runtime: Option<CrateNum>,
446     is_no_builtins: FxHashSet<CrateNum>,
447     native_libraries: FxHashMap<CrateNum, Lrc<Vec<NativeLibrary>>>,
448     crate_name: FxHashMap<CrateNum, String>,
449     used_libraries: Lrc<Vec<NativeLibrary>>,
450     link_args: Lrc<Vec<String>>,
451     used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
452     used_crates_static: Vec<(CrateNum, LibSource)>,
453     used_crates_dynamic: Vec<(CrateNum, LibSource)>,
454     wasm_imports: FxHashMap<String, String>,
455     lang_item_to_crate: FxHashMap<LangItem, CrateNum>,
456     missing_lang_items: FxHashMap<CrateNum, Vec<LangItem>>,
457 }
458
459 __build_diagnostic_array! { librustc_codegen_llvm, DIAGNOSTICS }