]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/lib.rs
[eddyb] rustc_codegen_llvm: remove unnecessary `'a` from `LlvmCodegenBackend` impls.
[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 extern crate flate2;
43 #[macro_use] extern crate bitflags;
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_codegen_ssa;
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 rustc_codegen_ssa::interfaces::*;
71 use rustc_codegen_ssa::back::write::{CodegenContext, ModuleConfig};
72 use rustc_codegen_ssa::back::lto::{SerializedModule, LtoModuleCodegen, ThinModule};
73 use rustc_codegen_ssa::CompiledModule;
74 use errors::{FatalError, Handler};
75 use rustc::dep_graph::WorkProduct;
76 use rustc::util::time_graph::Timeline;
77 use syntax_pos::symbol::InternedString;
78 use rustc::mir::mono::Stats;
79 pub use llvm_util::target_features;
80 use std::any::Any;
81 use std::sync::{mpsc, Arc};
82
83 use rustc::dep_graph::DepGraph;
84 use rustc::middle::allocator::AllocatorKind;
85 use rustc::middle::cstore::{EncodedMetadata, MetadataLoader};
86 use rustc::session::{Session, CompileIncomplete};
87 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
88 use rustc::ty::{self, TyCtxt};
89 use rustc::util::time_graph;
90 use rustc::util::profiling::ProfileCategory;
91 use rustc_mir::monomorphize;
92 use rustc_codegen_ssa::ModuleCodegen;
93 use rustc_codegen_utils::codegen_backend::CodegenBackend;
94
95 mod diagnostics;
96
97 mod back {
98     mod archive;
99     pub mod bytecode;
100     pub mod link;
101     pub mod lto;
102     pub mod write;
103     mod rpath;
104     pub mod wasm;
105 }
106
107 mod abi;
108 mod allocator;
109 mod asm;
110 mod attributes;
111 mod base;
112 mod builder;
113 mod callee;
114 mod common;
115 mod consts;
116 mod context;
117 mod debuginfo;
118 mod declare;
119 mod intrinsic;
120
121 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
122 #[path = "llvm/mod.rs"] mod llvm_; pub mod llvm { pub use super::llvm_::*; }
123
124 mod llvm_util;
125 mod metadata;
126 mod mono_item;
127 mod type_;
128 mod type_of;
129 mod value;
130
131 #[derive(Clone)]
132 pub struct LlvmCodegenBackend(());
133
134 impl ExtraBackendMethods for LlvmCodegenBackend {
135     fn new_metadata(&self, sess: &Session, mod_name: &str) -> ModuleLlvm {
136         ModuleLlvm::new(sess, mod_name)
137     }
138     fn write_metadata<'b, 'gcx>(
139         &self,
140         tcx: TyCtxt<'b, 'gcx, 'gcx>,
141         metadata: &ModuleLlvm
142     ) -> EncodedMetadata {
143         base::write_metadata(tcx, metadata)
144     }
145     fn codegen_allocator(&self, tcx: TyCtxt, mods: &ModuleLlvm, kind: AllocatorKind) {
146         unsafe { allocator::codegen(tcx, mods, kind) }
147     }
148     fn compile_codegen_unit<'a, 'tcx: 'a>(
149         &self,
150         tcx: TyCtxt<'a, 'tcx, 'tcx>,
151         cgu_name: InternedString,
152     ) -> Stats {
153         base::compile_codegen_unit(tcx, cgu_name)
154     }
155     fn target_machine_factory(
156         &self,
157         sess: &Session,
158         find_features: bool
159     ) -> Arc<dyn Fn() ->
160         Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
161         back::write::target_machine_factory(sess, find_features)
162     }
163     fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
164         llvm_util::target_cpu(sess)
165     }
166 }
167
168 impl Clone for &'static mut llvm::TargetMachine {
169     fn clone(&self) -> Self {
170         // This method should never be called. It is put here because in
171         // rustc_codegen_ssa::back::write::CodegenContext, the TargetMachine is contained in a
172         // closure returned by a function under an Arc. The clone-deriving algorithm works when the
173         // struct contains the original LLVM TargetMachine type but not any more when supplied with
174         // a generic type. Hence this dummy Clone implementation.
175         panic!()
176     }
177 }
178
179 impl WriteBackendMethods for LlvmCodegenBackend {
180     type Module = ModuleLlvm;
181     type ModuleBuffer = back::lto::ModuleBuffer;
182     type Context = llvm::Context;
183     type TargetMachine = &'static mut llvm::TargetMachine;
184     type ThinData = back::lto::ThinData;
185     type ThinBuffer = back::lto::ThinBuffer;
186     fn print_pass_timings(&self) {
187             unsafe { llvm::LLVMRustPrintPassTimings(); }
188     }
189     fn run_lto(
190         cgcx: &CodegenContext<Self>,
191         modules: Vec<ModuleCodegen<Self::Module>>,
192         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
193         timeline: &mut Timeline
194     ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
195         back::lto::run(cgcx, modules, cached_modules, timeline)
196     }
197     unsafe fn optimize(
198         cgcx: &CodegenContext<Self>,
199         diag_handler: &Handler,
200         module: &ModuleCodegen<Self::Module>,
201         config: &ModuleConfig,
202         timeline: &mut Timeline
203     ) -> Result<(), FatalError> {
204         back::write::optimize(cgcx, diag_handler, module, config, timeline)
205     }
206     unsafe fn optimize_thin(
207         cgcx: &CodegenContext<Self>,
208         thin: &mut ThinModule<Self>,
209         timeline: &mut Timeline
210     ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
211         back::lto::optimize_thin_module(thin, cgcx, timeline)
212     }
213     unsafe fn codegen(
214         cgcx: &CodegenContext<Self>,
215         diag_handler: &Handler,
216         module: ModuleCodegen<Self::Module>,
217         config: &ModuleConfig,
218         timeline: &mut Timeline
219     ) -> Result<CompiledModule, FatalError> {
220         back::write::codegen(cgcx, diag_handler, module, config, timeline)
221     }
222     fn run_lto_pass_manager(
223         cgcx: &CodegenContext<Self>,
224         module: &ModuleCodegen<Self::Module>,
225         config: &ModuleConfig,
226         thin: bool
227     ) {
228         back::lto::run_pass_manager(cgcx, module, config, thin)
229     }
230 }
231
232 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
233 unsafe impl Sync for LlvmCodegenBackend {}
234
235 impl LlvmCodegenBackend {
236     pub fn new() -> Box<dyn CodegenBackend> {
237         box LlvmCodegenBackend(())
238     }
239 }
240
241 impl CodegenBackend for LlvmCodegenBackend {
242     fn init(&self, sess: &Session) {
243         llvm_util::init(sess); // Make sure llvm is inited
244     }
245
246     fn print(&self, req: PrintRequest, sess: &Session) {
247         match req {
248             PrintRequest::RelocationModels => {
249                 println!("Available relocation models:");
250                 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
251                     println!("    {}", name);
252                 }
253                 println!("");
254             }
255             PrintRequest::CodeModels => {
256                 println!("Available code models:");
257                 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
258                     println!("    {}", name);
259                 }
260                 println!("");
261             }
262             PrintRequest::TlsModels => {
263                 println!("Available TLS models:");
264                 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
265                     println!("    {}", name);
266                 }
267                 println!("");
268             }
269             req => llvm_util::print(req, sess),
270         }
271     }
272
273     fn print_passes(&self) {
274         llvm_util::print_passes();
275     }
276
277     fn print_version(&self) {
278         llvm_util::print_version();
279     }
280
281     fn diagnostics(&self) -> &[(&'static str, &'static str)] {
282         &DIAGNOSTICS
283     }
284
285     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
286         target_features(sess)
287     }
288
289     fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
290         box metadata::LlvmMetadataLoader
291     }
292
293     fn provide(&self, providers: &mut ty::query::Providers) {
294         rustc_codegen_utils::symbol_names::provide(providers);
295         rustc_codegen_ssa::back::symbol_export::provide(providers);
296         rustc_codegen_ssa::base::provide_both(providers);
297         attributes::provide(providers);
298     }
299
300     fn provide_extern(&self, providers: &mut ty::query::Providers) {
301         rustc_codegen_ssa::back::symbol_export::provide_extern(providers);
302         rustc_codegen_ssa::base::provide_both(providers);
303         attributes::provide_extern(providers);
304     }
305
306     fn codegen_crate<'b, 'tcx>(
307         &self,
308         tcx: TyCtxt<'b, 'tcx, 'tcx>,
309         rx: mpsc::Receiver<Box<dyn Any + Send>>
310     ) -> Box<dyn Any> {
311         box rustc_codegen_ssa::base::codegen_crate(LlvmCodegenBackend(()), tcx, rx)
312     }
313
314     fn join_codegen_and_link(
315         &self,
316         ongoing_codegen: Box<dyn Any>,
317         sess: &Session,
318         dep_graph: &DepGraph,
319         outputs: &OutputFilenames,
320     ) -> Result<(), CompileIncomplete>{
321         use rustc::util::common::time;
322         let (codegen_results, work_products) =
323             ongoing_codegen.downcast::
324                 <rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
325                 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
326                 .join(sess);
327         if sess.opts.debugging_opts.incremental_info {
328             rustc_codegen_ssa::back::write::dump_incremental_data(&codegen_results);
329         }
330
331         time(sess,
332              "serialize work products",
333              move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
334
335         sess.compile_status()?;
336
337         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
338                                                    i == OutputType::Metadata) {
339             return Ok(());
340         }
341
342         // Run the linker on any artifacts that resulted from the LLVM run.
343         // This should produce either a finished executable or library.
344         sess.profiler(|p| p.start_activity(ProfileCategory::Linking));
345         time(sess, "linking", || {
346             back::link::link_binary(sess, &codegen_results,
347                                     outputs, &codegen_results.crate_name.as_str());
348         });
349         sess.profiler(|p| p.end_activity(ProfileCategory::Linking));
350
351         // Now that we won't touch anything in the incremental compilation directory
352         // any more, we can finalize it (which involves renaming it)
353         rustc_incremental::finalize_session_directory(sess, codegen_results.crate_hash);
354
355         Ok(())
356     }
357 }
358
359 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
360 #[no_mangle]
361 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
362     LlvmCodegenBackend::new()
363 }
364
365 pub struct ModuleLlvm {
366     llcx: &'static mut llvm::Context,
367     llmod_raw: *const llvm::Module,
368     tm: &'static mut llvm::TargetMachine,
369 }
370
371 unsafe impl Send for ModuleLlvm { }
372 unsafe impl Sync for ModuleLlvm { }
373
374 impl ModuleLlvm {
375     fn new(sess: &Session, mod_name: &str) -> Self {
376         unsafe {
377             let llcx = llvm::LLVMRustContextCreate(sess.fewer_names());
378             let llmod_raw = context::create_module(sess, llcx, mod_name) as *const _;
379
380             ModuleLlvm {
381                 llmod_raw,
382                 llcx,
383                 tm: create_target_machine(sess, false),
384             }
385         }
386     }
387
388     fn llmod(&self) -> &llvm::Module {
389         unsafe {
390             &*self.llmod_raw
391         }
392     }
393 }
394
395 impl Drop for ModuleLlvm {
396     fn drop(&mut self) {
397         unsafe {
398             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
399             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
400         }
401     }
402 }
403
404 __build_diagnostic_array! { librustc_codegen_llvm, DIAGNOSTICS }