]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/lib.rs
560d266e9263263a8fff5ad667a712bedbc79363
[rust.git] / src / librustc_codegen_llvm / 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
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)]
28 #![feature(libc)]
29 #![feature(nll)]
30 #![feature(quote)]
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)]
38
39 use back::write::create_target_machine;
40 use syntax_pos::symbol::Symbol;
41
42 extern crate flate2;
43 #[macro_use] extern crate bitflags;
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_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;
60
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;
68 extern crate memmap;
69
70 use rustc_codegen_ssa::interfaces::*;
71 use time_graph::TimeGraph;
72 use std::sync::mpsc::Receiver;
73 use back::write::{self, OngoingCodegen};
74 use syntax_pos::symbol::InternedString;
75 use rustc::mir::mono::Stats;
76
77 pub use llvm_util::target_features;
78 use std::any::Any;
79 use std::sync::mpsc;
80
81 use rustc::dep_graph::DepGraph;
82 use rustc::middle::allocator::AllocatorKind;
83 use rustc::middle::cstore::{EncodedMetadata, MetadataLoader};
84 use rustc::session::{Session, CompileIncomplete};
85 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest};
86 use rustc::ty::{self, TyCtxt};
87 use rustc::util::time_graph;
88 use rustc::util::profiling::ProfileCategory;
89 use rustc_mir::monomorphize;
90 use rustc_codegen_ssa::{ModuleCodegen, CompiledModule, CachedModuleCodegen, CrateInfo};
91 use rustc_codegen_utils::codegen_backend::CodegenBackend;
92 use rustc_data_structures::svh::Svh;
93
94 mod diagnostics;
95
96 mod back {
97     mod archive;
98     pub mod bytecode;
99     pub mod link;
100     pub mod lto;
101     pub mod write;
102     mod rpath;
103     pub mod wasm;
104 }
105
106 mod abi;
107 mod allocator;
108 mod asm;
109 mod attributes;
110 mod base;
111 mod builder;
112 mod callee;
113 mod common;
114 mod consts;
115 mod context;
116 mod debuginfo;
117 mod declare;
118 mod intrinsic;
119
120 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
121 #[path = "llvm/mod.rs"] mod llvm_; pub mod llvm { pub use super::llvm_::*; }
122
123 mod llvm_util;
124 mod metadata;
125 mod mono_item;
126 mod type_;
127 mod type_of;
128 mod value;
129
130 pub struct LlvmCodegenBackend(());
131
132 impl BackendMethods for LlvmCodegenBackend {
133     type Module = ModuleLlvm;
134     type OngoingCodegen = OngoingCodegen;
135
136     fn new_metadata(&self, sess: &Session, mod_name: &str) -> ModuleLlvm {
137         ModuleLlvm::new(sess, mod_name)
138     }
139     fn write_metadata<'b, 'gcx>(
140         &self,
141         tcx: TyCtxt<'b, 'gcx, 'gcx>,
142         metadata: &ModuleLlvm
143     ) -> EncodedMetadata {
144         base::write_metadata(tcx, metadata)
145     }
146     fn start_async_codegen(
147         &self,
148         tcx: TyCtxt,
149         time_graph: Option<TimeGraph>,
150         metadata: EncodedMetadata,
151         coordinator_receive: Receiver<Box<dyn Any + Send>>,
152         total_cgus: usize
153     ) -> OngoingCodegen {
154         write::start_async_codegen(tcx, time_graph, metadata, coordinator_receive, total_cgus)
155     }
156     fn submit_pre_codegened_module_to_backend(
157         &self,
158         codegen: &OngoingCodegen,
159         tcx: TyCtxt,
160         module: ModuleCodegen<ModuleLlvm>
161     ) {
162         codegen.submit_pre_codegened_module_to_llvm(tcx, module)
163     }
164     fn submit_pre_lto_module_to_backend(&self, tcx: TyCtxt, module: CachedModuleCodegen) {
165         write::submit_pre_lto_module_to_llvm(tcx, module)
166     }
167     fn submit_post_lto_module_to_backend(&self, tcx: TyCtxt, module: CachedModuleCodegen) {
168         write::submit_post_lto_module_to_llvm(tcx, module)
169     }
170     fn codegen_aborted(codegen: OngoingCodegen) {
171         codegen.codegen_aborted();
172     }
173     fn codegen_finished(&self, codegen: &OngoingCodegen, tcx: TyCtxt) {
174         codegen.codegen_finished(tcx)
175     }
176     fn check_for_errors(&self, codegen: &OngoingCodegen, sess: &Session) {
177         codegen.check_for_errors(sess)
178     }
179     fn codegen_allocator(&self, tcx: TyCtxt, mods: &ModuleLlvm, kind: AllocatorKind) {
180         unsafe { allocator::codegen(tcx, mods, kind) }
181     }
182     fn wait_for_signal_to_codegen_item(&self, codegen: &OngoingCodegen) {
183         codegen.wait_for_signal_to_codegen_item()
184     }
185     fn compile_codegen_unit<'a, 'tcx: 'a>(
186         &self,
187         tcx: TyCtxt<'a, 'tcx, 'tcx>,
188         cgu_name: InternedString,
189     ) -> Stats {
190         base::compile_codegen_unit(tcx, cgu_name)
191     }
192 }
193
194
195 impl !Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
196 impl !Sync for LlvmCodegenBackend {}
197
198 impl LlvmCodegenBackend {
199     pub fn new() -> Box<dyn CodegenBackend> {
200         box LlvmCodegenBackend(())
201     }
202 }
203
204 impl CodegenBackend for LlvmCodegenBackend {
205     fn init(&self, sess: &Session) {
206         llvm_util::init(sess); // Make sure llvm is inited
207     }
208
209     fn print(&self, req: PrintRequest, sess: &Session) {
210         match req {
211             PrintRequest::RelocationModels => {
212                 println!("Available relocation models:");
213                 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
214                     println!("    {}", name);
215                 }
216                 println!("");
217             }
218             PrintRequest::CodeModels => {
219                 println!("Available code models:");
220                 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
221                     println!("    {}", name);
222                 }
223                 println!("");
224             }
225             PrintRequest::TlsModels => {
226                 println!("Available TLS models:");
227                 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
228                     println!("    {}", name);
229                 }
230                 println!("");
231             }
232             req => llvm_util::print(req, sess),
233         }
234     }
235
236     fn print_passes(&self) {
237         llvm_util::print_passes();
238     }
239
240     fn print_version(&self) {
241         llvm_util::print_version();
242     }
243
244     fn diagnostics(&self) -> &[(&'static str, &'static str)] {
245         &DIAGNOSTICS
246     }
247
248     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
249         target_features(sess)
250     }
251
252     fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
253         box metadata::LlvmMetadataLoader
254     }
255
256     fn provide(&self, providers: &mut ty::query::Providers) {
257         rustc_codegen_utils::symbol_export::provide(providers);
258         rustc_codegen_utils::symbol_names::provide(providers);
259         rustc_codegen_ssa::base::provide_both(providers);
260         attributes::provide(providers);
261     }
262
263     fn provide_extern(&self, providers: &mut ty::query::Providers) {
264         rustc_codegen_utils::symbol_export::provide_extern(providers);
265         rustc_codegen_ssa::base::provide_both(providers);
266         attributes::provide_extern(providers);
267     }
268
269     fn codegen_crate<'a, 'tcx>(
270         &self,
271         tcx: TyCtxt<'a, 'tcx, 'tcx>,
272         rx: mpsc::Receiver<Box<dyn Any + Send>>
273     ) -> Box<dyn Any> {
274         box rustc_codegen_ssa::base::codegen_crate(LlvmCodegenBackend(()), tcx, rx)
275     }
276
277     fn join_codegen_and_link(
278         &self,
279         ongoing_codegen: Box<dyn Any>,
280         sess: &Session,
281         dep_graph: &DepGraph,
282         outputs: &OutputFilenames,
283     ) -> Result<(), CompileIncomplete>{
284         use rustc::util::common::time;
285         let (ongoing_codegen, work_products) =
286             ongoing_codegen.downcast::<::back::write::OngoingCodegen>()
287                 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
288                 .join(sess);
289         if sess.opts.debugging_opts.incremental_info {
290             back::write::dump_incremental_data(&ongoing_codegen);
291         }
292
293         time(sess,
294              "serialize work products",
295              move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
296
297         sess.compile_status()?;
298
299         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
300                                                    i == OutputType::Metadata) {
301             return Ok(());
302         }
303
304         // Run the linker on any artifacts that resulted from the LLVM run.
305         // This should produce either a finished executable or library.
306         sess.profiler(|p| p.start_activity(ProfileCategory::Linking));
307         time(sess, "linking", || {
308             back::link::link_binary(sess, &ongoing_codegen,
309                                     outputs, &ongoing_codegen.crate_name.as_str());
310         });
311         sess.profiler(|p| p.end_activity(ProfileCategory::Linking));
312
313         // Now that we won't touch anything in the incremental compilation directory
314         // any more, we can finalize it (which involves renaming it)
315         rustc_incremental::finalize_session_directory(sess, ongoing_codegen.crate_hash);
316
317         Ok(())
318     }
319 }
320
321 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
322 #[no_mangle]
323 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
324     LlvmCodegenBackend::new()
325 }
326
327 pub struct ModuleLlvm {
328     llcx: &'static mut llvm::Context,
329     llmod_raw: *const llvm::Module,
330     tm: &'static mut llvm::TargetMachine,
331 }
332
333 unsafe impl Send for ModuleLlvm { }
334 unsafe impl Sync for ModuleLlvm { }
335
336 impl ModuleLlvm {
337     fn new(sess: &Session, mod_name: &str) -> Self {
338         unsafe {
339             let llcx = llvm::LLVMRustContextCreate(sess.fewer_names());
340             let llmod_raw = context::create_module(sess, llcx, mod_name) as *const _;
341
342             ModuleLlvm {
343                 llmod_raw,
344                 llcx,
345                 tm: create_target_machine(sess, false),
346             }
347         }
348     }
349
350     fn llmod(&self) -> &llvm::Module {
351         unsafe {
352             &*self.llmod_raw
353         }
354     }
355 }
356
357 impl Drop for ModuleLlvm {
358     fn drop(&mut self) {
359         unsafe {
360             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
361             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
362         }
363     }
364 }
365
366 struct CodegenResults {
367     crate_name: Symbol,
368     modules: Vec<CompiledModule>,
369     allocator_module: Option<CompiledModule>,
370     metadata_module: CompiledModule,
371     crate_hash: Svh,
372     metadata: rustc::middle::cstore::EncodedMetadata,
373     windows_subsystem: Option<String>,
374     linker_info: rustc_codegen_utils::linker::LinkerInfo,
375     crate_info: CrateInfo,
376 }
377 __build_diagnostic_array! { librustc_codegen_llvm, DIAGNOSTICS }