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 syntax_pos::symbol::Symbol;
42 #[macro_use] 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_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_fs_util;
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 tempfile;
70 use time_graph::TimeGraph;
71 use std::sync::mpsc::Receiver;
72 use back::write::{self, OngoingCodegen};
73 use syntax_pos::symbol::InternedString;
74 use rustc::mir::mono::Stats;
76 pub use llvm_util::target_features;
79 use rustc_data_structures::sync::Lrc;
81 use rustc::dep_graph::DepGraph;
82 use rustc::hir::def_id::CrateNum;
83 use rustc::middle::allocator::AllocatorKind;
84 use rustc::middle::cstore::{EncodedMetadata, MetadataLoader};
85 use rustc::middle::cstore::{NativeLibrary, CrateSource, LibSource};
86 use rustc::middle::lang_items::LangItem;
87 use rustc::session::{Session, CompileIncomplete};
88 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
89 use rustc::ty::{self, TyCtxt};
90 use rustc::util::time_graph;
91 use rustc::util::nodemap::{FxHashSet, FxHashMap};
92 use rustc::util::profiling::ProfileCategory;
93 use rustc_mir::monomorphize;
94 use rustc_codegen_utils::{ModuleCodegen, CompiledModule};
95 use rustc_codegen_utils::codegen_backend::CodegenBackend;
96 use rustc_data_structures::svh::Svh;
127 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
128 #[path = "llvm/mod.rs"] mod llvm_; pub mod llvm { pub use super::llvm_::*; }
139 pub struct LlvmCodegenBackend(());
141 impl BackendMethods for LlvmCodegenBackend {
142 type Module = ModuleLlvm;
143 type OngoingCodegen = OngoingCodegen;
145 fn new_metadata(&self, sess: &Session, mod_name: &str) -> ModuleLlvm {
146 ModuleLlvm::new(sess, mod_name)
148 fn write_metadata<'b, 'gcx>(
150 tcx: TyCtxt<'b, 'gcx, 'gcx>,
151 metadata: &ModuleLlvm
152 ) -> EncodedMetadata {
153 base::write_metadata(tcx, metadata)
155 fn start_async_codegen(
158 time_graph: Option<TimeGraph>,
159 metadata: EncodedMetadata,
160 coordinator_receive: Receiver<Box<dyn Any + Send>>,
162 ) -> OngoingCodegen {
163 write::start_async_codegen(tcx, time_graph, metadata, coordinator_receive, total_cgus)
165 fn submit_pre_codegened_module_to_llvm(
167 codegen: &OngoingCodegen,
169 module: ModuleCodegen<ModuleLlvm>
171 codegen.submit_pre_codegened_module_to_llvm(tcx, module)
173 fn codegen_aborted(codegen: OngoingCodegen) {
174 codegen.codegen_aborted();
176 fn codegen_finished(&self, codegen: &OngoingCodegen, tcx: TyCtxt) {
177 codegen.codegen_finished(tcx)
179 fn check_for_errors(&self, codegen: &OngoingCodegen, sess: &Session) {
180 codegen.check_for_errors(sess)
182 fn codegen_allocator(&self, tcx: TyCtxt, mods: &ModuleLlvm, kind: AllocatorKind) {
183 unsafe { allocator::codegen(tcx, mods, kind) }
185 fn wait_for_signal_to_codegen_item(&self, codegen: &OngoingCodegen) {
186 codegen.wait_for_signal_to_codegen_item()
188 fn compile_codegen_unit<'a, 'tcx: 'a>(
190 tcx: TyCtxt<'a, 'tcx, 'tcx>,
191 cgu_name: InternedString,
193 base::compile_codegen_unit(tcx, cgu_name)
198 impl !Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
199 impl !Sync for LlvmCodegenBackend {}
201 impl LlvmCodegenBackend {
202 pub fn new() -> Box<dyn CodegenBackend> {
203 box LlvmCodegenBackend(())
207 impl CodegenBackend for LlvmCodegenBackend {
208 fn init(&self, sess: &Session) {
209 llvm_util::init(sess); // Make sure llvm is inited
212 fn print(&self, req: PrintRequest, sess: &Session) {
214 PrintRequest::RelocationModels => {
215 println!("Available relocation models:");
216 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
217 println!(" {}", name);
221 PrintRequest::CodeModels => {
222 println!("Available code models:");
223 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
224 println!(" {}", name);
228 PrintRequest::TlsModels => {
229 println!("Available TLS models:");
230 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
231 println!(" {}", name);
235 req => llvm_util::print(req, sess),
239 fn print_passes(&self) {
240 llvm_util::print_passes();
243 fn print_version(&self) {
244 llvm_util::print_version();
247 fn diagnostics(&self) -> &[(&'static str, &'static str)] {
251 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
252 target_features(sess)
255 fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
256 box metadata::LlvmMetadataLoader
259 fn provide(&self, providers: &mut ty::query::Providers) {
260 rustc_codegen_utils::symbol_export::provide(providers);
261 rustc_codegen_utils::symbol_names::provide(providers);
262 base::provide_both(providers);
263 attributes::provide(providers);
266 fn provide_extern(&self, providers: &mut ty::query::Providers) {
267 rustc_codegen_utils::symbol_export::provide_extern(providers);
268 base::provide_both(providers);
269 attributes::provide_extern(providers);
272 fn codegen_crate<'a, 'tcx>(
274 tcx: TyCtxt<'a, 'tcx, 'tcx>,
275 rx: mpsc::Receiver<Box<dyn Any + Send>>
277 box base::codegen_crate(LlvmCodegenBackend(()), tcx, rx)
280 fn join_codegen_and_link(
282 ongoing_codegen: Box<dyn Any>,
284 dep_graph: &DepGraph,
285 outputs: &OutputFilenames,
286 ) -> Result<(), CompileIncomplete>{
287 use rustc::util::common::time;
288 let (ongoing_codegen, work_products) =
289 ongoing_codegen.downcast::<::back::write::OngoingCodegen>()
290 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
292 if sess.opts.debugging_opts.incremental_info {
293 back::write::dump_incremental_data(&ongoing_codegen);
297 "serialize work products",
298 move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
300 sess.compile_status()?;
302 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
303 i == OutputType::Metadata) {
307 // Run the linker on any artifacts that resulted from the LLVM run.
308 // This should produce either a finished executable or library.
309 sess.profiler(|p| p.start_activity(ProfileCategory::Linking));
310 time(sess, "linking", || {
311 back::link::link_binary(sess, &ongoing_codegen,
312 outputs, &ongoing_codegen.crate_name.as_str());
314 sess.profiler(|p| p.end_activity(ProfileCategory::Linking));
316 // Now that we won't touch anything in the incremental compilation directory
317 // any more, we can finalize it (which involves renaming it)
318 rustc_incremental::finalize_session_directory(sess, ongoing_codegen.crate_hash);
324 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
326 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
327 LlvmCodegenBackend::new()
330 pub struct ModuleLlvm {
331 llcx: &'static mut llvm::Context,
332 llmod_raw: *const llvm::Module,
333 tm: &'static mut llvm::TargetMachine,
336 unsafe impl Send for ModuleLlvm { }
337 unsafe impl Sync for ModuleLlvm { }
340 fn new(sess: &Session, mod_name: &str) -> Self {
342 let llcx = llvm::LLVMRustContextCreate(sess.fewer_names());
343 let llmod_raw = context::create_module(sess, llcx, mod_name) as *const _;
348 tm: create_target_machine(sess, false),
353 fn llmod(&self) -> &llvm::Module {
360 impl Drop for ModuleLlvm {
363 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
364 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
369 struct CodegenResults {
371 modules: Vec<CompiledModule>,
372 allocator_module: Option<CompiledModule>,
373 metadata_module: CompiledModule,
375 metadata: rustc::middle::cstore::EncodedMetadata,
376 windows_subsystem: Option<String>,
377 linker_info: rustc_codegen_utils::linker::LinkerInfo,
378 crate_info: CrateInfo,
381 /// Misc info we load from metadata to persist beyond the tcx
383 panic_runtime: Option<CrateNum>,
384 compiler_builtins: Option<CrateNum>,
385 profiler_runtime: Option<CrateNum>,
386 sanitizer_runtime: Option<CrateNum>,
387 is_no_builtins: FxHashSet<CrateNum>,
388 native_libraries: FxHashMap<CrateNum, Lrc<Vec<NativeLibrary>>>,
389 crate_name: FxHashMap<CrateNum, String>,
390 used_libraries: Lrc<Vec<NativeLibrary>>,
391 link_args: Lrc<Vec<String>>,
392 used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
393 used_crates_static: Vec<(CrateNum, LibSource)>,
394 used_crates_dynamic: Vec<(CrateNum, LibSource)>,
395 wasm_imports: FxHashMap<String, String>,
396 lang_item_to_crate: FxHashMap<LangItem, CrateNum>,
397 missing_lang_items: FxHashMap<CrateNum, Vec<LangItem>>,
400 __build_diagnostic_array! { librustc_codegen_llvm, DIAGNOSTICS }