]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/lib.rs
rustc: Load the `rustc_trans` crate at runtime
[rust.git] / src / librustc_trans / 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 #![deny(warnings)]
21
22 #![feature(box_patterns)]
23 #![feature(box_syntax)]
24 #![feature(custom_attribute)]
25 #![feature(fs_read_write)]
26 #![allow(unused_attributes)]
27 #![feature(i128_type)]
28 #![feature(i128)]
29 #![feature(inclusive_range)]
30 #![feature(inclusive_range_syntax)]
31 #![feature(libc)]
32 #![feature(quote)]
33 #![feature(rustc_diagnostic_macros)]
34 #![feature(slice_patterns)]
35 #![feature(conservative_impl_trait)]
36 #![feature(optin_builtin_traits)]
37
38 use rustc::dep_graph::WorkProduct;
39 use syntax_pos::symbol::Symbol;
40
41 #[macro_use]
42 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_back;
52 extern crate rustc_binaryen;
53 extern crate rustc_const_math;
54 extern crate rustc_data_structures;
55 extern crate rustc_demangle;
56 extern crate rustc_incremental;
57 extern crate rustc_llvm as llvm;
58 extern crate rustc_platform_intrinsics as intrinsics;
59 extern crate rustc_trans_utils;
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 #[cfg(windows)]
67 extern crate cc; // Used to locate MSVC
68 extern crate tempdir;
69
70 use back::bytecode::RLIB_BYTECODE_EXTENSION;
71
72 pub use llvm_util::target_features;
73
74 use std::any::Any;
75 use std::path::PathBuf;
76 use std::rc::Rc;
77 use std::sync::mpsc;
78
79 use rustc::dep_graph::DepGraph;
80 use rustc::hir::def_id::CrateNum;
81 use rustc::middle::cstore::MetadataLoader;
82 use rustc::middle::cstore::{NativeLibrary, CrateSource, LibSource};
83 use rustc::session::{Session, CompileIncomplete};
84 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
85 use rustc::ty::{self, TyCtxt};
86 use rustc::util::nodemap::{FxHashSet, FxHashMap};
87 use rustc_mir::monomorphize;
88 use rustc_trans_utils::trans_crate::TransCrate;
89
90 mod diagnostics;
91
92 mod back {
93     pub use rustc_trans_utils::symbol_names;
94     mod archive;
95     pub mod bytecode;
96     mod command;
97     pub mod linker;
98     pub mod link;
99     mod lto;
100     pub mod symbol_export;
101     pub mod write;
102     mod rpath;
103 }
104
105 mod abi;
106 mod allocator;
107 mod asm;
108 mod attributes;
109 mod base;
110 mod builder;
111 mod cabi_aarch64;
112 mod cabi_arm;
113 mod cabi_asmjs;
114 mod cabi_hexagon;
115 mod cabi_mips;
116 mod cabi_mips64;
117 mod cabi_msp430;
118 mod cabi_nvptx;
119 mod cabi_nvptx64;
120 mod cabi_powerpc;
121 mod cabi_powerpc64;
122 mod cabi_s390x;
123 mod cabi_sparc;
124 mod cabi_sparc64;
125 mod cabi_x86;
126 mod cabi_x86_64;
127 mod cabi_x86_win64;
128 mod callee;
129 mod common;
130 mod consts;
131 mod context;
132 mod debuginfo;
133 mod declare;
134 mod glue;
135 mod intrinsic;
136 mod llvm_util;
137 mod metadata;
138 mod meth;
139 mod mir;
140 mod time_graph;
141 mod trans_item;
142 mod type_;
143 mod type_of;
144 mod value;
145
146 pub struct LlvmTransCrate(());
147
148 impl !Send for LlvmTransCrate {} // Llvm is on a per-thread basis
149 impl !Sync for LlvmTransCrate {}
150
151 impl LlvmTransCrate {
152     pub fn new() -> Box<TransCrate> {
153         box LlvmTransCrate(())
154     }
155 }
156
157 impl TransCrate for LlvmTransCrate {
158     fn init(&self, sess: &Session) {
159         llvm_util::init(sess); // Make sure llvm is inited
160     }
161
162     fn print(&self, req: PrintRequest, sess: &Session) {
163         match req {
164             PrintRequest::RelocationModels => {
165                 println!("Available relocation models:");
166                 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
167                     println!("    {}", name);
168                 }
169                 println!("");
170             }
171             PrintRequest::CodeModels => {
172                 println!("Available code models:");
173                 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
174                     println!("    {}", name);
175                 }
176                 println!("");
177             }
178             PrintRequest::TlsModels => {
179                 println!("Available TLS models:");
180                 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
181                     println!("    {}", name);
182                 }
183                 println!("");
184             }
185             req => llvm_util::print(req, sess),
186         }
187     }
188
189     fn print_passes(&self) {
190         llvm_util::print_passes();
191     }
192
193     fn print_version(&self) {
194         llvm_util::print_version();
195     }
196
197     #[cfg(not(stage0))]
198     fn diagnostics(&self) -> &[(&'static str, &'static str)] {
199         &DIAGNOSTICS
200     }
201
202     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
203         target_features(sess)
204     }
205
206     fn metadata_loader(&self) -> Box<MetadataLoader> {
207         box metadata::LlvmMetadataLoader
208     }
209
210     fn provide(&self, providers: &mut ty::maps::Providers) {
211         back::symbol_names::provide(providers);
212         back::symbol_export::provide(providers);
213         base::provide(providers);
214         attributes::provide(providers);
215     }
216
217     fn provide_extern(&self, providers: &mut ty::maps::Providers) {
218         back::symbol_export::provide_extern(providers);
219     }
220
221     fn trans_crate<'a, 'tcx>(
222         &self,
223         tcx: TyCtxt<'a, 'tcx, 'tcx>,
224         rx: mpsc::Receiver<Box<Any + Send>>
225     ) -> Box<Any> {
226         box base::trans_crate(tcx, rx)
227     }
228
229     fn join_trans_and_link(
230         &self,
231         trans: Box<Any>,
232         sess: &Session,
233         dep_graph: &DepGraph,
234         outputs: &OutputFilenames,
235     ) -> Result<(), CompileIncomplete>{
236         use rustc::util::common::time;
237         let trans = trans.downcast::<::back::write::OngoingCrateTranslation>()
238             .expect("Expected LlvmTransCrate's OngoingCrateTranslation, found Box<Any>")
239             .join(sess, dep_graph);
240         if sess.opts.debugging_opts.incremental_info {
241             back::write::dump_incremental_data(&trans);
242         }
243
244         time(sess.time_passes(),
245              "serialize work products",
246              move || rustc_incremental::save_work_products(sess, &dep_graph));
247
248         sess.compile_status()?;
249
250         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
251                                                    i == OutputType::Metadata) {
252             return Ok(());
253         }
254
255         // Run the linker on any artifacts that resulted from the LLVM run.
256         // This should produce either a finished executable or library.
257         time(sess.time_passes(), "linking", || {
258             back::link::link_binary(sess, &trans, outputs, &trans.crate_name.as_str());
259         });
260
261         // Now that we won't touch anything in the incremental compilation directory
262         // any more, we can finalize it (which involves renaming it)
263         rustc_incremental::finalize_session_directory(sess, trans.link.crate_hash);
264
265         Ok(())
266     }
267 }
268
269 /// This is the entrypoint for a hot plugged rustc_trans
270 #[no_mangle]
271 pub fn __rustc_codegen_backend() -> Box<TransCrate> {
272     LlvmTransCrate::new()
273 }
274
275 struct ModuleTranslation {
276     /// The name of the module. When the crate may be saved between
277     /// compilations, incremental compilation requires that name be
278     /// unique amongst **all** crates.  Therefore, it should contain
279     /// something unique to this crate (e.g., a module path) as well
280     /// as the crate name and disambiguator.
281     name: String,
282     llmod_id: String,
283     source: ModuleSource,
284     kind: ModuleKind,
285 }
286
287 #[derive(Copy, Clone, Debug, PartialEq)]
288 enum ModuleKind {
289     Regular,
290     Metadata,
291     Allocator,
292 }
293
294 impl ModuleTranslation {
295     fn llvm(&self) -> Option<&ModuleLlvm> {
296         match self.source {
297             ModuleSource::Translated(ref llvm) => Some(llvm),
298             ModuleSource::Preexisting(_) => None,
299         }
300     }
301
302     fn into_compiled_module(self,
303                                 emit_obj: bool,
304                                 emit_bc: bool,
305                                 emit_bc_compressed: bool,
306                                 outputs: &OutputFilenames) -> CompiledModule {
307         let pre_existing = match self.source {
308             ModuleSource::Preexisting(_) => true,
309             ModuleSource::Translated(_) => false,
310         };
311         let object = if emit_obj {
312             Some(outputs.temp_path(OutputType::Object, Some(&self.name)))
313         } else {
314             None
315         };
316         let bytecode = if emit_bc {
317             Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name)))
318         } else {
319             None
320         };
321         let bytecode_compressed = if emit_bc_compressed {
322             Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name))
323                     .with_extension(RLIB_BYTECODE_EXTENSION))
324         } else {
325             None
326         };
327
328         CompiledModule {
329             llmod_id: self.llmod_id,
330             name: self.name.clone(),
331             kind: self.kind,
332             pre_existing,
333             object,
334             bytecode,
335             bytecode_compressed,
336         }
337     }
338 }
339
340 #[derive(Debug)]
341 struct CompiledModule {
342     name: String,
343     llmod_id: String,
344     kind: ModuleKind,
345     pre_existing: bool,
346     object: Option<PathBuf>,
347     bytecode: Option<PathBuf>,
348     bytecode_compressed: Option<PathBuf>,
349 }
350
351 enum ModuleSource {
352     /// Copy the `.o` files or whatever from the incr. comp. directory.
353     Preexisting(WorkProduct),
354
355     /// Rebuild from this LLVM module.
356     Translated(ModuleLlvm),
357 }
358
359 #[derive(Debug)]
360 struct ModuleLlvm {
361     llcx: llvm::ContextRef,
362     llmod: llvm::ModuleRef,
363     tm: llvm::TargetMachineRef,
364 }
365
366 unsafe impl Send for ModuleLlvm { }
367 unsafe impl Sync for ModuleLlvm { }
368
369 impl Drop for ModuleLlvm {
370     fn drop(&mut self) {
371         unsafe {
372             llvm::LLVMDisposeModule(self.llmod);
373             llvm::LLVMContextDispose(self.llcx);
374             llvm::LLVMRustDisposeTargetMachine(self.tm);
375         }
376     }
377 }
378
379 struct CrateTranslation {
380     crate_name: Symbol,
381     modules: Vec<CompiledModule>,
382     allocator_module: Option<CompiledModule>,
383     metadata_module: CompiledModule,
384     link: rustc::middle::cstore::LinkMeta,
385     metadata: rustc::middle::cstore::EncodedMetadata,
386     windows_subsystem: Option<String>,
387     linker_info: back::linker::LinkerInfo,
388     crate_info: CrateInfo,
389 }
390
391 // Misc info we load from metadata to persist beyond the tcx
392 struct CrateInfo {
393     panic_runtime: Option<CrateNum>,
394     compiler_builtins: Option<CrateNum>,
395     profiler_runtime: Option<CrateNum>,
396     sanitizer_runtime: Option<CrateNum>,
397     is_no_builtins: FxHashSet<CrateNum>,
398     native_libraries: FxHashMap<CrateNum, Rc<Vec<NativeLibrary>>>,
399     crate_name: FxHashMap<CrateNum, String>,
400     used_libraries: Rc<Vec<NativeLibrary>>,
401     link_args: Rc<Vec<String>>,
402     used_crate_source: FxHashMap<CrateNum, Rc<CrateSource>>,
403     used_crates_static: Vec<(CrateNum, LibSource)>,
404     used_crates_dynamic: Vec<(CrateNum, LibSource)>,
405 }
406
407 #[cfg(not(stage0))] // remove after the next snapshot
408 __build_diagnostic_array! { librustc_trans, DIAGNOSTICS }