]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/lib.rs
Moved Backend interface into rustc_codegen_utils
[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 syntax_pos::symbol::Symbol;
41
42 #[macro_use] extern crate bitflags;
43 extern crate flate2;
44 extern crate libc;
45 #[macro_use] extern crate rustc;
46 extern crate jobserver;
47 extern crate num_cpus;
48 extern crate rustc_mir;
49 extern crate rustc_allocator;
50 extern crate rustc_apfloat;
51 extern crate rustc_target;
52 #[macro_use] extern crate rustc_data_structures;
53 extern crate rustc_demangle;
54 extern crate rustc_incremental;
55 extern crate rustc_llvm;
56 extern crate rustc_platform_intrinsics as intrinsics;
57 extern crate rustc_codegen_utils;
58 extern crate rustc_fs_util;
59
60 #[macro_use] extern crate log;
61 #[macro_use] extern crate syntax;
62 extern crate syntax_pos;
63 extern crate rustc_errors as errors;
64 extern crate serialize;
65 extern crate cc; // Used to locate MSVC
66 extern crate tempfile;
67 extern crate memmap;
68
69 use interfaces::*;
70 use time_graph::TimeGraph;
71 use std::sync::mpsc::Receiver;
72 use back::write::{self, OngoingCodegen};
73 use syntax_pos::symbol::InternedString;
74 use rustc::mir::mono::Stats;
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::{ModuleCodegen, CompiledModule};
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 Module = 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<'b, 'gcx>(
149         &self,
150         tcx: TyCtxt<'b, '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     fn compile_codegen_unit<'a, 'tcx: 'a>(
189         &self,
190         tcx: TyCtxt<'a, 'tcx, 'tcx>,
191         cgu_name: InternedString,
192     ) -> Stats {
193         base::compile_codegen_unit(tcx, cgu_name)
194     }
195 }
196
197
198 impl !Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
199 impl !Sync for LlvmCodegenBackend {}
200
201 impl LlvmCodegenBackend {
202     pub fn new() -> Box<dyn CodegenBackend> {
203         box LlvmCodegenBackend(())
204     }
205 }
206
207 impl CodegenBackend for LlvmCodegenBackend {
208     fn init(&self, sess: &Session) {
209         llvm_util::init(sess); // Make sure llvm is inited
210     }
211
212     fn print(&self, req: PrintRequest, sess: &Session) {
213         match req {
214             PrintRequest::RelocationModels => {
215                 println!("Available relocation models:");
216                 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
217                     println!("    {}", name);
218                 }
219                 println!("");
220             }
221             PrintRequest::CodeModels => {
222                 println!("Available code models:");
223                 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
224                     println!("    {}", name);
225                 }
226                 println!("");
227             }
228             PrintRequest::TlsModels => {
229                 println!("Available TLS models:");
230                 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
231                     println!("    {}", name);
232                 }
233                 println!("");
234             }
235             req => llvm_util::print(req, sess),
236         }
237     }
238
239     fn print_passes(&self) {
240         llvm_util::print_passes();
241     }
242
243     fn print_version(&self) {
244         llvm_util::print_version();
245     }
246
247     fn diagnostics(&self) -> &[(&'static str, &'static str)] {
248         &DIAGNOSTICS
249     }
250
251     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
252         target_features(sess)
253     }
254
255     fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
256         box metadata::LlvmMetadataLoader
257     }
258
259     fn provide(&self, providers: &mut ty::query::Providers) {
260         rustc_codegen_utils::symbol_export::provide(providers);
261         rustc_codegen_utils::symbol_names::provide(providers);
262         base::provide_both(providers);
263         attributes::provide(providers);
264     }
265
266     fn provide_extern(&self, providers: &mut ty::query::Providers) {
267         rustc_codegen_utils::symbol_export::provide_extern(providers);
268         base::provide_both(providers);
269         attributes::provide_extern(providers);
270     }
271
272     fn codegen_crate<'a, 'tcx>(
273         &self,
274         tcx: TyCtxt<'a, 'tcx, 'tcx>,
275         rx: mpsc::Receiver<Box<dyn Any + Send>>
276     ) -> Box<dyn Any> {
277         box base::codegen_crate(LlvmCodegenBackend(()), tcx, rx)
278     }
279
280     fn join_codegen_and_link(
281         &self,
282         ongoing_codegen: Box<dyn Any>,
283         sess: &Session,
284         dep_graph: &DepGraph,
285         outputs: &OutputFilenames,
286     ) -> Result<(), CompileIncomplete>{
287         use rustc::util::common::time;
288         let (ongoing_codegen, work_products) =
289             ongoing_codegen.downcast::<::back::write::OngoingCodegen>()
290                 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
291                 .join(sess);
292         if sess.opts.debugging_opts.incremental_info {
293             back::write::dump_incremental_data(&ongoing_codegen);
294         }
295
296         time(sess,
297              "serialize work products",
298              move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
299
300         sess.compile_status()?;
301
302         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
303                                                    i == OutputType::Metadata) {
304             return Ok(());
305         }
306
307         // Run the linker on any artifacts that resulted from the LLVM run.
308         // This should produce either a finished executable or library.
309         sess.profiler(|p| p.start_activity(ProfileCategory::Linking));
310         time(sess, "linking", || {
311             back::link::link_binary(sess, &ongoing_codegen,
312                                     outputs, &ongoing_codegen.crate_name.as_str());
313         });
314         sess.profiler(|p| p.end_activity(ProfileCategory::Linking));
315
316         // Now that we won't touch anything in the incremental compilation directory
317         // any more, we can finalize it (which involves renaming it)
318         rustc_incremental::finalize_session_directory(sess, ongoing_codegen.crate_hash);
319
320         Ok(())
321     }
322 }
323
324 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
325 #[no_mangle]
326 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
327     LlvmCodegenBackend::new()
328 }
329
330 pub struct ModuleLlvm {
331     llcx: &'static mut llvm::Context,
332     llmod_raw: *const llvm::Module,
333     tm: &'static mut llvm::TargetMachine,
334 }
335
336 unsafe impl Send for ModuleLlvm { }
337 unsafe impl Sync for ModuleLlvm { }
338
339 impl ModuleLlvm {
340     fn new(sess: &Session, mod_name: &str) -> Self {
341         unsafe {
342             let llcx = llvm::LLVMRustContextCreate(sess.fewer_names());
343             let llmod_raw = context::create_module(sess, llcx, mod_name) as *const _;
344
345             ModuleLlvm {
346                 llmod_raw,
347                 llcx,
348                 tm: create_target_machine(sess, false),
349             }
350         }
351     }
352
353     fn llmod(&self) -> &llvm::Module {
354         unsafe {
355             &*self.llmod_raw
356         }
357     }
358 }
359
360 impl Drop for ModuleLlvm {
361     fn drop(&mut self) {
362         unsafe {
363             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
364             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
365         }
366     }
367 }
368
369 struct CodegenResults {
370     crate_name: Symbol,
371     modules: Vec<CompiledModule>,
372     allocator_module: Option<CompiledModule>,
373     metadata_module: CompiledModule,
374     crate_hash: Svh,
375     metadata: rustc::middle::cstore::EncodedMetadata,
376     windows_subsystem: Option<String>,
377     linker_info: rustc_codegen_utils::linker::LinkerInfo,
378     crate_info: CrateInfo,
379 }
380
381 /// Misc info we load from metadata to persist beyond the tcx
382 struct CrateInfo {
383     panic_runtime: Option<CrateNum>,
384     compiler_builtins: Option<CrateNum>,
385     profiler_runtime: Option<CrateNum>,
386     sanitizer_runtime: Option<CrateNum>,
387     is_no_builtins: FxHashSet<CrateNum>,
388     native_libraries: FxHashMap<CrateNum, Lrc<Vec<NativeLibrary>>>,
389     crate_name: FxHashMap<CrateNum, String>,
390     used_libraries: Lrc<Vec<NativeLibrary>>,
391     link_args: Lrc<Vec<String>>,
392     used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
393     used_crates_static: Vec<(CrateNum, LibSource)>,
394     used_crates_dynamic: Vec<(CrateNum, LibSource)>,
395     wasm_imports: FxHashMap<String, String>,
396     lang_item_to_crate: FxHashMap<LangItem, CrateNum>,
397     missing_lang_items: FxHashMap<CrateNum, Vec<LangItem>>,
398 }
399
400 __build_diagnostic_array! { librustc_codegen_llvm, DIAGNOSTICS }