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/")]
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)]
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)]
39 use back::write::create_target_machine;
40 use rustc::dep_graph::WorkProduct;
41 use syntax_pos::symbol::Symbol;
43 #[macro_use] extern crate bitflags;
46 #[macro_use] extern crate rustc;
47 extern crate jobserver;
48 extern crate num_cpus;
49 extern crate rustc_mir;
50 extern crate rustc_allocator;
51 extern crate rustc_apfloat;
52 extern crate rustc_target;
53 #[macro_use] extern crate rustc_data_structures;
54 extern crate rustc_demangle;
55 extern crate rustc_incremental;
56 extern crate rustc_llvm;
57 extern crate rustc_platform_intrinsics as intrinsics;
58 extern crate rustc_codegen_utils;
59 extern crate rustc_fs_util;
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;
70 use back::bytecode::RLIB_BYTECODE_EXTENSION;
72 pub use llvm_util::target_features;
74 use std::path::{PathBuf};
76 use rustc_data_structures::sync::Lrc;
78 use rustc::dep_graph::DepGraph;
79 use rustc::hir::def_id::CrateNum;
80 use rustc::middle::cstore::MetadataLoader;
81 use rustc::middle::cstore::{NativeLibrary, CrateSource, LibSource};
82 use rustc::middle::lang_items::LangItem;
83 use rustc::session::{Session, CompileIncomplete};
84 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
85 use rustc::ty::{self, TyCtxt};
86 use rustc::util::time_graph;
87 use rustc::util::nodemap::{FxHashSet, FxHashMap};
88 use rustc::util::profiling::ProfileCategory;
89 use rustc_mir::monomorphize;
90 use rustc_codegen_utils::codegen_backend::CodegenBackend;
91 use rustc_data_structures::svh::Svh;
96 pub use rustc_codegen_utils::symbol_names;
103 pub mod symbol_export;
133 pub struct LlvmCodegenBackend(());
135 impl !Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
136 impl !Sync for LlvmCodegenBackend {}
138 impl LlvmCodegenBackend {
139 pub fn new() -> Box<dyn CodegenBackend> {
140 box LlvmCodegenBackend(())
144 impl CodegenBackend for LlvmCodegenBackend {
145 fn init(&self, sess: &Session) {
146 llvm_util::init(sess); // Make sure llvm is inited
149 fn print(&self, req: PrintRequest, sess: &Session) {
151 PrintRequest::RelocationModels => {
152 println!("Available relocation models:");
153 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
154 println!(" {}", name);
158 PrintRequest::CodeModels => {
159 println!("Available code models:");
160 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
161 println!(" {}", name);
165 PrintRequest::TlsModels => {
166 println!("Available TLS models:");
167 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
168 println!(" {}", name);
172 req => llvm_util::print(req, sess),
176 fn print_passes(&self) {
177 llvm_util::print_passes();
180 fn print_version(&self) {
181 llvm_util::print_version();
184 fn diagnostics(&self) -> &[(&'static str, &'static str)] {
188 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
189 target_features(sess)
192 fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
193 box metadata::LlvmMetadataLoader
196 fn provide(&self, providers: &mut ty::query::Providers) {
197 back::symbol_names::provide(providers);
198 back::symbol_export::provide(providers);
199 base::provide(providers);
200 attributes::provide(providers);
203 fn provide_extern(&self, providers: &mut ty::query::Providers) {
204 back::symbol_export::provide_extern(providers);
205 base::provide_extern(providers);
206 attributes::provide_extern(providers);
209 fn codegen_crate<'a, 'tcx>(
211 tcx: TyCtxt<'a, 'tcx, 'tcx>,
212 rx: mpsc::Receiver<Box<dyn Any + Send>>
214 box base::codegen_crate(tcx, rx)
217 fn join_codegen_and_link(
219 ongoing_codegen: Box<dyn Any>,
221 dep_graph: &DepGraph,
222 outputs: &OutputFilenames,
223 ) -> Result<(), CompileIncomplete>{
224 use rustc::util::common::time;
225 let (ongoing_codegen, work_products) =
226 ongoing_codegen.downcast::<::back::write::OngoingCodegen>()
227 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
229 if sess.opts.debugging_opts.incremental_info {
230 back::write::dump_incremental_data(&ongoing_codegen);
234 "serialize work products",
235 move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
237 sess.compile_status()?;
239 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
240 i == OutputType::Metadata) {
244 // Run the linker on any artifacts that resulted from the LLVM run.
245 // This should produce either a finished executable or library.
246 sess.profiler(|p| p.start_activity(ProfileCategory::Linking));
247 time(sess, "linking", || {
248 back::link::link_binary(sess, &ongoing_codegen,
249 outputs, &ongoing_codegen.crate_name.as_str());
251 sess.profiler(|p| p.end_activity(ProfileCategory::Linking));
253 // Now that we won't touch anything in the incremental compilation directory
254 // any more, we can finalize it (which involves renaming it)
255 rustc_incremental::finalize_session_directory(sess, ongoing_codegen.crate_hash);
261 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
263 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
264 LlvmCodegenBackend::new()
267 struct ModuleCodegen {
268 /// The name of the module. When the crate may be saved between
269 /// compilations, incremental compilation requires that name be
270 /// unique amongst **all** crates. Therefore, it should contain
271 /// something unique to this crate (e.g., a module path) as well
272 /// as the crate name and disambiguator.
273 /// We currently generate these names via CodegenUnit::build_cgu_name().
275 module_llvm: ModuleLlvm,
279 struct CachedModuleCodegen {
284 #[derive(Copy, Clone, Debug, PartialEq)]
292 fn into_compiled_module(self,
295 emit_bc_compressed: bool,
296 outputs: &OutputFilenames) -> CompiledModule {
297 let object = if emit_obj {
298 Some(outputs.temp_path(OutputType::Object, Some(&self.name)))
302 let bytecode = if emit_bc {
303 Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name)))
307 let bytecode_compressed = if emit_bc_compressed {
308 Some(outputs.temp_path(OutputType::Bitcode, Some(&self.name))
309 .with_extension(RLIB_BYTECODE_EXTENSION))
315 name: self.name.clone(),
325 struct CompiledModule {
328 object: Option<PathBuf>,
329 bytecode: Option<PathBuf>,
330 bytecode_compressed: Option<PathBuf>,
334 llcx: &'static mut llvm::Context,
335 llmod_raw: *const llvm::Module,
336 tm: &'static mut llvm::TargetMachine,
339 unsafe impl Send for ModuleLlvm { }
340 unsafe impl Sync for ModuleLlvm { }
343 fn new(sess: &Session, mod_name: &str) -> Self {
345 let llcx = llvm::LLVMRustContextCreate(sess.fewer_names());
346 let llmod_raw = context::create_module(sess, llcx, mod_name) as *const _;
351 tm: create_target_machine(sess, false),
356 fn llmod(&self) -> &llvm::Module {
363 impl Drop for ModuleLlvm {
366 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
367 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
372 struct CodegenResults {
374 modules: Vec<CompiledModule>,
375 allocator_module: Option<CompiledModule>,
376 metadata_module: CompiledModule,
378 metadata: rustc::middle::cstore::EncodedMetadata,
379 windows_subsystem: Option<String>,
380 linker_info: back::linker::LinkerInfo,
381 crate_info: CrateInfo,
384 /// Misc info we load from metadata to persist beyond the tcx
386 panic_runtime: Option<CrateNum>,
387 compiler_builtins: Option<CrateNum>,
388 profiler_runtime: Option<CrateNum>,
389 sanitizer_runtime: Option<CrateNum>,
390 is_no_builtins: FxHashSet<CrateNum>,
391 native_libraries: FxHashMap<CrateNum, Lrc<Vec<NativeLibrary>>>,
392 crate_name: FxHashMap<CrateNum, String>,
393 used_libraries: Lrc<Vec<NativeLibrary>>,
394 link_args: Lrc<Vec<String>>,
395 used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
396 used_crates_static: Vec<(CrateNum, LibSource)>,
397 used_crates_dynamic: Vec<(CrateNum, LibSource)>,
398 wasm_imports: FxHashMap<String, String>,
399 lang_item_to_crate: FxHashMap<LangItem, CrateNum>,
400 missing_lang_items: FxHashMap<CrateNum, Vec<LangItem>>,
403 __build_diagnostic_array! { librustc_codegen_llvm, DIAGNOSTICS }