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