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;
43 #[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_codegen_ssa;
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 rustc_codegen_ssa::traits::*;
71 use rustc_codegen_ssa::back::write::{CodegenContext, ModuleConfig};
72 use rustc_codegen_ssa::back::lto::{SerializedModule, LtoModuleCodegen, ThinModule};
73 use rustc_codegen_ssa::CompiledModule;
74 use errors::{FatalError, Handler};
75 use rustc::dep_graph::WorkProduct;
76 use rustc::util::time_graph::Timeline;
77 use syntax_pos::symbol::InternedString;
78 use rustc::mir::mono::Stats;
79 pub use llvm_util::target_features;
81 use std::sync::{mpsc, Arc};
83 use rustc::dep_graph::DepGraph;
84 use rustc::middle::allocator::AllocatorKind;
85 use rustc::middle::cstore::{EncodedMetadata, MetadataLoader};
86 use rustc::session::{Session, CompileIncomplete};
87 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
88 use rustc::ty::{self, TyCtxt};
89 use rustc::util::time_graph;
90 use rustc::util::profiling::ProfileCategory;
91 use rustc_mir::monomorphize;
92 use rustc_codegen_ssa::ModuleCodegen;
93 use rustc_codegen_utils::codegen_backend::CodegenBackend;
121 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
122 #[path = "llvm/mod.rs"] mod llvm_; pub mod llvm { pub use super::llvm_::*; }
132 pub struct LlvmCodegenBackend(());
134 impl ExtraBackendMethods for LlvmCodegenBackend {
135 fn new_metadata(&self, sess: &Session, mod_name: &str) -> ModuleLlvm {
136 ModuleLlvm::new(sess, mod_name)
138 fn write_metadata<'b, 'gcx>(
140 tcx: TyCtxt<'b, 'gcx, 'gcx>,
141 metadata: &ModuleLlvm
142 ) -> EncodedMetadata {
143 base::write_metadata(tcx, metadata)
145 fn codegen_allocator(&self, tcx: TyCtxt, mods: &ModuleLlvm, kind: AllocatorKind) {
146 unsafe { allocator::codegen(tcx, mods, kind) }
148 fn compile_codegen_unit<'a, 'tcx: 'a>(
150 tcx: TyCtxt<'a, 'tcx, 'tcx>,
151 cgu_name: InternedString,
153 base::compile_codegen_unit(tcx, cgu_name)
155 fn target_machine_factory(
160 Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
161 back::write::target_machine_factory(sess, find_features)
163 fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
164 llvm_util::target_cpu(sess)
168 impl WriteBackendMethods for LlvmCodegenBackend {
169 type Module = ModuleLlvm;
170 type ModuleBuffer = back::lto::ModuleBuffer;
171 type Context = llvm::Context;
172 type TargetMachine = &'static mut llvm::TargetMachine;
173 type ThinData = back::lto::ThinData;
174 type ThinBuffer = back::lto::ThinBuffer;
175 fn print_pass_timings(&self) {
176 unsafe { llvm::LLVMRustPrintPassTimings(); }
179 cgcx: &CodegenContext<Self>,
180 modules: Vec<ModuleCodegen<Self::Module>>,
181 cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
182 timeline: &mut Timeline
183 ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
184 back::lto::run(cgcx, modules, cached_modules, timeline)
187 cgcx: &CodegenContext<Self>,
188 diag_handler: &Handler,
189 module: &ModuleCodegen<Self::Module>,
190 config: &ModuleConfig,
191 timeline: &mut Timeline
192 ) -> Result<(), FatalError> {
193 back::write::optimize(cgcx, diag_handler, module, config, timeline)
195 unsafe fn optimize_thin(
196 cgcx: &CodegenContext<Self>,
197 thin: &mut ThinModule<Self>,
198 timeline: &mut Timeline
199 ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
200 back::lto::optimize_thin_module(thin, cgcx, timeline)
203 cgcx: &CodegenContext<Self>,
204 diag_handler: &Handler,
205 module: ModuleCodegen<Self::Module>,
206 config: &ModuleConfig,
207 timeline: &mut Timeline
208 ) -> Result<CompiledModule, FatalError> {
209 back::write::codegen(cgcx, diag_handler, module, config, timeline)
211 fn run_lto_pass_manager(
212 cgcx: &CodegenContext<Self>,
213 module: &ModuleCodegen<Self::Module>,
214 config: &ModuleConfig,
217 back::lto::run_pass_manager(cgcx, module, config, thin)
221 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
222 unsafe impl Sync for LlvmCodegenBackend {}
224 impl LlvmCodegenBackend {
225 pub fn new() -> Box<dyn CodegenBackend> {
226 box LlvmCodegenBackend(())
230 impl CodegenBackend for LlvmCodegenBackend {
231 fn init(&self, sess: &Session) {
232 llvm_util::init(sess); // Make sure llvm is inited
235 fn print(&self, req: PrintRequest, sess: &Session) {
237 PrintRequest::RelocationModels => {
238 println!("Available relocation models:");
239 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
240 println!(" {}", name);
244 PrintRequest::CodeModels => {
245 println!("Available code models:");
246 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
247 println!(" {}", name);
251 PrintRequest::TlsModels => {
252 println!("Available TLS models:");
253 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
254 println!(" {}", name);
258 req => llvm_util::print(req, sess),
262 fn print_passes(&self) {
263 llvm_util::print_passes();
266 fn print_version(&self) {
267 llvm_util::print_version();
270 fn diagnostics(&self) -> &[(&'static str, &'static str)] {
274 fn target_features(&self, sess: &Session) -> Vec<Symbol> {
275 target_features(sess)
278 fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
279 box metadata::LlvmMetadataLoader
282 fn provide(&self, providers: &mut ty::query::Providers) {
283 rustc_codegen_utils::symbol_names::provide(providers);
284 rustc_codegen_ssa::back::symbol_export::provide(providers);
285 rustc_codegen_ssa::base::provide_both(providers);
286 attributes::provide(providers);
289 fn provide_extern(&self, providers: &mut ty::query::Providers) {
290 rustc_codegen_ssa::back::symbol_export::provide_extern(providers);
291 rustc_codegen_ssa::base::provide_both(providers);
292 attributes::provide_extern(providers);
295 fn codegen_crate<'b, 'tcx>(
297 tcx: TyCtxt<'b, 'tcx, 'tcx>,
298 rx: mpsc::Receiver<Box<dyn Any + Send>>
300 box rustc_codegen_ssa::base::codegen_crate(LlvmCodegenBackend(()), tcx, rx)
303 fn join_codegen_and_link(
305 ongoing_codegen: Box<dyn Any>,
307 dep_graph: &DepGraph,
308 outputs: &OutputFilenames,
309 ) -> Result<(), CompileIncomplete>{
310 use rustc::util::common::time;
311 let (codegen_results, work_products) =
312 ongoing_codegen.downcast::
313 <rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
314 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
316 if sess.opts.debugging_opts.incremental_info {
317 rustc_codegen_ssa::back::write::dump_incremental_data(&codegen_results);
321 "serialize work products",
322 move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
324 sess.compile_status()?;
326 if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
327 i == OutputType::Metadata) {
331 // Run the linker on any artifacts that resulted from the LLVM run.
332 // This should produce either a finished executable or library.
333 sess.profiler(|p| p.start_activity(ProfileCategory::Linking));
334 time(sess, "linking", || {
335 back::link::link_binary(sess, &codegen_results,
336 outputs, &codegen_results.crate_name.as_str());
338 sess.profiler(|p| p.end_activity(ProfileCategory::Linking));
340 // Now that we won't touch anything in the incremental compilation directory
341 // any more, we can finalize it (which involves renaming it)
342 rustc_incremental::finalize_session_directory(sess, codegen_results.crate_hash);
348 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
350 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
351 LlvmCodegenBackend::new()
354 pub struct ModuleLlvm {
355 llcx: &'static mut llvm::Context,
356 llmod_raw: *const llvm::Module,
357 tm: &'static mut llvm::TargetMachine,
360 unsafe impl Send for ModuleLlvm { }
361 unsafe impl Sync for ModuleLlvm { }
364 fn new(sess: &Session, mod_name: &str) -> Self {
366 let llcx = llvm::LLVMRustContextCreate(sess.fewer_names());
367 let llmod_raw = context::create_module(sess, llcx, mod_name) as *const _;
372 tm: create_target_machine(sess, false),
377 fn llmod(&self) -> &llvm::Module {
384 impl Drop for ModuleLlvm {
387 llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
388 llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
393 __build_diagnostic_array! { librustc_codegen_llvm, DIAGNOSTICS }