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