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.
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.
11 //! The Rust compiler.
15 //! This API is completely unstable and subject to change.
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/")]
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)]
29 #![feature(inclusive_range)]
30 #![feature(inclusive_range_syntax)]
33 #![feature(rustc_diagnostic_macros)]
34 #![feature(slice_patterns)]
35 #![feature(conservative_impl_trait)]
36 #![feature(optin_builtin_traits)]
38 use rustc::dep_graph::WorkProduct;
39 use syntax_pos::symbol::Symbol;
42 extern crate bitflags;
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 #[macro_use] 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;
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
68 use back::bytecode::RLIB_BYTECODE_EXTENSION;
70 pub use llvm_util::target_features;
73 use std::path::PathBuf;
75 use rustc_data_structures::sync::Lrc;
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;
91 pub use rustc_trans_utils::symbol_names;
98 pub mod symbol_export;
145 pub struct LlvmTransCrate(());
147 impl !Send for LlvmTransCrate {} // Llvm is on a per-thread basis
148 impl !Sync for LlvmTransCrate {}
150 impl LlvmTransCrate {
151 pub fn new() -> Box<TransCrate> {
152 box LlvmTransCrate(())
156 impl TransCrate for LlvmTransCrate {
157 fn init(&self, sess: &Session) {
158 llvm_util::init(sess); // Make sure llvm is inited
161 fn print(&self, req: PrintRequest, sess: &Session) {
163 PrintRequest::RelocationModels => {
164 println!("Available relocation models:");
165 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
166 println!(" {}", name);
170 PrintRequest::CodeModels => {
171 println!("Available code models:");
172 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
173 println!(" {}", name);
177 PrintRequest::TlsModels => {
178 println!("Available TLS models:");
179 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
180 println!(" {}", name);
184 req => llvm_util::print(req, sess),
188 fn print_passes(&self) {
189 llvm_util::print_passes();
192 fn print_version(&self) {
193 llvm_util::print_version();
196 fn diagnostics(&self) -> &[(&'static str, &'static str)] {
200 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
201 target_features(sess)
204 fn metadata_loader(&self) -> Box<MetadataLoader> {
205 box metadata::LlvmMetadataLoader
208 fn provide(&self, providers: &mut ty::maps::Providers) {
209 back::symbol_names::provide(providers);
210 back::symbol_export::provide(providers);
211 base::provide(providers);
212 attributes::provide(providers);
215 fn provide_extern(&self, providers: &mut ty::maps::Providers) {
216 back::symbol_export::provide_extern(providers);
219 fn trans_crate<'a, 'tcx>(
221 tcx: TyCtxt<'a, 'tcx, 'tcx>,
222 rx: mpsc::Receiver<Box<Any + Send>>
224 box base::trans_crate(tcx, rx)
227 fn join_trans_and_link(
231 dep_graph: &DepGraph,
232 outputs: &OutputFilenames,
233 ) -> Result<(), CompileIncomplete>{
234 use rustc::util::common::time;
235 let trans = trans.downcast::<::back::write::OngoingCrateTranslation>()
236 .expect("Expected LlvmTransCrate's OngoingCrateTranslation, found Box<Any>")
237 .join(sess, dep_graph);
238 if sess.opts.debugging_opts.incremental_info {
239 back::write::dump_incremental_data(&trans);
243 "serialize work products",
244 move || rustc_incremental::save_work_products(sess, &dep_graph));
246 sess.compile_status()?;
248 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
249 i == OutputType::Metadata) {
253 // Run the linker on any artifacts that resulted from the LLVM run.
254 // This should produce either a finished executable or library.
255 time(sess, "linking", || {
256 back::link::link_binary(sess, &trans, outputs, &trans.crate_name.as_str());
259 // Now that we won't touch anything in the incremental compilation directory
260 // any more, we can finalize it (which involves renaming it)
261 rustc_incremental::finalize_session_directory(sess, trans.link.crate_hash);
267 /// This is the entrypoint for a hot plugged rustc_trans
269 pub fn __rustc_codegen_backend() -> Box<TransCrate> {
270 LlvmTransCrate::new()
273 struct ModuleTranslation {
274 /// The name of the module. When the crate may be saved between
275 /// compilations, incremental compilation requires that name be
276 /// unique amongst **all** crates. Therefore, it should contain
277 /// something unique to this crate (e.g., a module path) as well
278 /// as the crate name and disambiguator.
281 source: ModuleSource,
285 #[derive(Copy, Clone, Debug, PartialEq)]
292 impl ModuleTranslation {
293 fn llvm(&self) -> Option<&ModuleLlvm> {
295 ModuleSource::Translated(ref llvm) => Some(llvm),
296 ModuleSource::Preexisting(_) => None,
300 fn into_compiled_module(self,
303 emit_bc_compressed: bool,
304 outputs: &OutputFilenames) -> CompiledModule {
305 let pre_existing = match self.source {
306 ModuleSource::Preexisting(_) => true,
307 ModuleSource::Translated(_) => false,
309 let object = if emit_obj {
310 Some(outputs.temp_path(OutputType::Object, Some(&self.name)))
314 let bytecode = if emit_bc {
315 Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name)))
319 let bytecode_compressed = if emit_bc_compressed {
320 Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name))
321 .with_extension(RLIB_BYTECODE_EXTENSION))
327 llmod_id: self.llmod_id,
328 name: self.name.clone(),
339 struct CompiledModule {
344 object: Option<PathBuf>,
345 bytecode: Option<PathBuf>,
346 bytecode_compressed: Option<PathBuf>,
350 /// Copy the `.o` files or whatever from the incr. comp. directory.
351 Preexisting(WorkProduct),
353 /// Rebuild from this LLVM module.
354 Translated(ModuleLlvm),
359 llcx: llvm::ContextRef,
360 llmod: llvm::ModuleRef,
361 tm: llvm::TargetMachineRef,
364 unsafe impl Send for ModuleLlvm { }
365 unsafe impl Sync for ModuleLlvm { }
367 impl Drop for ModuleLlvm {
370 llvm::LLVMDisposeModule(self.llmod);
371 llvm::LLVMContextDispose(self.llcx);
372 llvm::LLVMRustDisposeTargetMachine(self.tm);
377 struct CrateTranslation {
379 modules: Vec<CompiledModule>,
380 allocator_module: Option<CompiledModule>,
381 metadata_module: CompiledModule,
382 link: rustc::middle::cstore::LinkMeta,
383 metadata: rustc::middle::cstore::EncodedMetadata,
384 windows_subsystem: Option<String>,
385 linker_info: back::linker::LinkerInfo,
386 crate_info: CrateInfo,
389 // Misc info we load from metadata to persist beyond the tcx
391 panic_runtime: Option<CrateNum>,
392 compiler_builtins: Option<CrateNum>,
393 profiler_runtime: Option<CrateNum>,
394 sanitizer_runtime: Option<CrateNum>,
395 is_no_builtins: FxHashSet<CrateNum>,
396 native_libraries: FxHashMap<CrateNum, Lrc<Vec<NativeLibrary>>>,
397 crate_name: FxHashMap<CrateNum, String>,
398 used_libraries: Lrc<Vec<NativeLibrary>>,
399 link_args: Lrc<Vec<String>>,
400 used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
401 used_crates_static: Vec<(CrateNum, LibSource)>,
402 used_crates_dynamic: Vec<(CrateNum, LibSource)>,
405 __build_diagnostic_array! { librustc_trans, DIAGNOSTICS }