]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/lib.rs
Rollup merge of #59600 - tobia:master, r=pnkfelix
[rust.git] / src / librustc_codegen_llvm / lib.rs
1 //! The Rust compiler.
2 //!
3 //! # Note
4 //!
5 //! This API is completely unstable and subject to change.
6
7 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
8
9 #![feature(box_patterns)]
10 #![feature(box_syntax)]
11 #![feature(const_cstr_unchecked)]
12 #![feature(crate_visibility_modifier)]
13 #![feature(extern_types)]
14 #![feature(in_band_lifetimes)]
15 #![allow(unused_attributes)]
16 #![feature(libc)]
17 #![feature(nll)]
18 #![feature(rustc_diagnostic_macros)]
19 #![feature(optin_builtin_traits)]
20 #![feature(concat_idents)]
21 #![feature(link_args)]
22 #![feature(static_nobundle)]
23 #![feature(trusted_len)]
24 #![deny(rust_2018_idioms)]
25 #![allow(explicit_outlives_requirements)]
26
27 use back::write::{create_target_machine, create_informational_target_machine};
28 use syntax_pos::symbol::Symbol;
29
30 extern crate flate2;
31 #[macro_use] extern crate bitflags;
32 extern crate libc;
33 #[macro_use] extern crate rustc;
34 extern crate rustc_allocator;
35 extern crate rustc_target;
36 #[macro_use] extern crate rustc_data_structures;
37 extern crate rustc_incremental;
38 extern crate rustc_codegen_utils;
39 extern crate rustc_codegen_ssa;
40 extern crate rustc_fs_util;
41
42 #[macro_use] extern crate log;
43 #[macro_use] extern crate syntax;
44 extern crate syntax_pos;
45 extern crate rustc_errors as errors;
46
47 use rustc_codegen_ssa::traits::*;
48 use rustc_codegen_ssa::back::write::{CodegenContext, ModuleConfig, FatLTOInput};
49 use rustc_codegen_ssa::back::lto::{SerializedModule, LtoModuleCodegen, ThinModule};
50 use rustc_codegen_ssa::CompiledModule;
51 use errors::{FatalError, Handler};
52 use rustc::dep_graph::WorkProduct;
53 use syntax_pos::symbol::InternedString;
54 pub use llvm_util::target_features;
55 use std::any::Any;
56 use std::sync::{mpsc, Arc};
57
58 use rustc::dep_graph::DepGraph;
59 use rustc::middle::allocator::AllocatorKind;
60 use rustc::middle::cstore::{EncodedMetadata, MetadataLoader};
61 use rustc::session::Session;
62 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest, OptLevel};
63 use rustc::ty::{self, TyCtxt};
64 use rustc::util::common::ErrorReported;
65 use rustc_codegen_ssa::ModuleCodegen;
66 use rustc_codegen_utils::codegen_backend::CodegenBackend;
67
68 mod error_codes;
69
70 mod back {
71     pub mod archive;
72     pub mod bytecode;
73     pub mod lto;
74     pub mod write;
75 }
76
77 mod abi;
78 mod allocator;
79 mod asm;
80 mod attributes;
81 mod base;
82 mod builder;
83 mod callee;
84 mod common;
85 mod consts;
86 mod context;
87 mod debuginfo;
88 mod declare;
89 mod intrinsic;
90
91 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
92 #[path = "llvm/mod.rs"] mod llvm_; pub mod llvm { pub use super::llvm_::*; }
93
94 mod llvm_util;
95 mod metadata;
96 mod mono_item;
97 mod type_;
98 mod type_of;
99 mod value;
100 mod va_arg;
101
102 #[derive(Clone)]
103 pub struct LlvmCodegenBackend(());
104
105 impl ExtraBackendMethods for LlvmCodegenBackend {
106     fn new_metadata(&self, tcx: TyCtxt<'_, '_, '_>, mod_name: &str) -> ModuleLlvm {
107         ModuleLlvm::new_metadata(tcx, mod_name)
108     }
109
110     fn write_compressed_metadata<'b, 'gcx>(
111         &self,
112         tcx: TyCtxt<'b, 'gcx, 'gcx>,
113         metadata: &EncodedMetadata,
114         llvm_module: &mut ModuleLlvm
115     ) {
116         base::write_compressed_metadata(tcx, metadata, llvm_module)
117     }
118     fn codegen_allocator<'b, 'gcx>(
119         &self,
120         tcx: TyCtxt<'b, 'gcx, 'gcx>,
121         mods: &mut ModuleLlvm,
122         kind: AllocatorKind
123     ) {
124         unsafe { allocator::codegen(tcx, mods, kind) }
125     }
126     fn compile_codegen_unit<'a, 'tcx: 'a>(
127         &self,
128         tcx: TyCtxt<'a, 'tcx, 'tcx>,
129         cgu_name: InternedString,
130     ) {
131         base::compile_codegen_unit(tcx, cgu_name);
132     }
133     fn target_machine_factory(
134         &self,
135         sess: &Session,
136         optlvl: OptLevel,
137         find_features: bool
138     ) -> Arc<dyn Fn() ->
139         Result<&'static mut llvm::TargetMachine, String> + Send + Sync> {
140         back::write::target_machine_factory(sess, optlvl, find_features)
141     }
142     fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
143         llvm_util::target_cpu(sess)
144     }
145 }
146
147 impl WriteBackendMethods for LlvmCodegenBackend {
148     type Module = ModuleLlvm;
149     type ModuleBuffer = back::lto::ModuleBuffer;
150     type Context = llvm::Context;
151     type TargetMachine = &'static mut llvm::TargetMachine;
152     type ThinData = back::lto::ThinData;
153     type ThinBuffer = back::lto::ThinBuffer;
154     fn print_pass_timings(&self) {
155             unsafe { llvm::LLVMRustPrintPassTimings(); }
156     }
157     fn run_fat_lto(
158         cgcx: &CodegenContext<Self>,
159         modules: Vec<FatLTOInput<Self>>,
160         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
161     ) -> Result<LtoModuleCodegen<Self>, FatalError> {
162         back::lto::run_fat(cgcx, modules, cached_modules)
163     }
164     fn run_thin_lto(
165         cgcx: &CodegenContext<Self>,
166         modules: Vec<(String, Self::ThinBuffer)>,
167         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
168     ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
169         back::lto::run_thin(cgcx, modules, cached_modules)
170     }
171     unsafe fn optimize(
172         cgcx: &CodegenContext<Self>,
173         diag_handler: &Handler,
174         module: &ModuleCodegen<Self::Module>,
175         config: &ModuleConfig,
176     ) -> Result<(), FatalError> {
177         back::write::optimize(cgcx, diag_handler, module, config)
178     }
179     unsafe fn optimize_thin(
180         cgcx: &CodegenContext<Self>,
181         thin: &mut ThinModule<Self>,
182     ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
183         back::lto::optimize_thin_module(thin, cgcx)
184     }
185     unsafe fn codegen(
186         cgcx: &CodegenContext<Self>,
187         diag_handler: &Handler,
188         module: ModuleCodegen<Self::Module>,
189         config: &ModuleConfig,
190     ) -> Result<CompiledModule, FatalError> {
191         back::write::codegen(cgcx, diag_handler, module, config)
192     }
193     fn prepare_thin(
194         module: ModuleCodegen<Self::Module>
195     ) -> (String, Self::ThinBuffer) {
196         back::lto::prepare_thin(module)
197     }
198     fn serialize_module(
199         module: ModuleCodegen<Self::Module>
200     ) -> (String, Self::ModuleBuffer) {
201         (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
202     }
203     fn run_lto_pass_manager(
204         cgcx: &CodegenContext<Self>,
205         module: &ModuleCodegen<Self::Module>,
206         config: &ModuleConfig,
207         thin: bool
208     ) {
209         back::lto::run_pass_manager(cgcx, module, config, thin)
210     }
211 }
212
213 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
214 unsafe impl Sync for LlvmCodegenBackend {}
215
216 impl LlvmCodegenBackend {
217     pub fn new() -> Box<dyn CodegenBackend> {
218         box LlvmCodegenBackend(())
219     }
220 }
221
222 impl CodegenBackend for LlvmCodegenBackend {
223     fn init(&self, sess: &Session) {
224         llvm_util::init(sess); // Make sure llvm is inited
225     }
226
227     fn print(&self, req: PrintRequest, sess: &Session) {
228         match req {
229             PrintRequest::RelocationModels => {
230                 println!("Available relocation models:");
231                 for &(name, _) in back::write::RELOC_MODEL_ARGS.iter() {
232                     println!("    {}", name);
233                 }
234                 println!("");
235             }
236             PrintRequest::CodeModels => {
237                 println!("Available code models:");
238                 for &(name, _) in back::write::CODE_GEN_MODEL_ARGS.iter(){
239                     println!("    {}", name);
240                 }
241                 println!("");
242             }
243             PrintRequest::TlsModels => {
244                 println!("Available TLS models:");
245                 for &(name, _) in back::write::TLS_MODEL_ARGS.iter(){
246                     println!("    {}", name);
247                 }
248                 println!("");
249             }
250             req => llvm_util::print(req, sess),
251         }
252     }
253
254     fn print_passes(&self) {
255         llvm_util::print_passes();
256     }
257
258     fn print_version(&self) {
259         llvm_util::print_version();
260     }
261
262     fn diagnostics(&self) -> &[(&'static str, &'static str)] {
263         &DIAGNOSTICS
264     }
265
266     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
267         target_features(sess)
268     }
269
270     fn metadata_loader(&self) -> Box<dyn MetadataLoader + Sync> {
271         box metadata::LlvmMetadataLoader
272     }
273
274     fn provide(&self, providers: &mut ty::query::Providers<'_>) {
275         rustc_codegen_utils::symbol_names::provide(providers);
276         rustc_codegen_ssa::back::symbol_export::provide(providers);
277         rustc_codegen_ssa::base::provide_both(providers);
278         attributes::provide(providers);
279     }
280
281     fn provide_extern(&self, providers: &mut ty::query::Providers<'_>) {
282         rustc_codegen_ssa::back::symbol_export::provide_extern(providers);
283         rustc_codegen_ssa::base::provide_both(providers);
284         attributes::provide_extern(providers);
285     }
286
287     fn codegen_crate<'b, 'tcx>(
288         &self,
289         tcx: TyCtxt<'b, 'tcx, 'tcx>,
290         metadata: EncodedMetadata,
291         need_metadata_module: bool,
292         rx: mpsc::Receiver<Box<dyn Any + Send>>
293     ) -> Box<dyn Any> {
294         box rustc_codegen_ssa::base::codegen_crate(
295             LlvmCodegenBackend(()), tcx, metadata, need_metadata_module, rx)
296     }
297
298     fn join_codegen_and_link(
299         &self,
300         ongoing_codegen: Box<dyn Any>,
301         sess: &Session,
302         dep_graph: &DepGraph,
303         outputs: &OutputFilenames,
304     ) -> Result<(), ErrorReported> {
305         use rustc::util::common::time;
306         let (codegen_results, work_products) =
307             ongoing_codegen.downcast::
308                 <rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
309                 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
310                 .join(sess);
311         if sess.opts.debugging_opts.incremental_info {
312             rustc_codegen_ssa::back::write::dump_incremental_data(&codegen_results);
313         }
314
315         time(sess,
316              "serialize work products",
317              move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
318
319         sess.compile_status()?;
320
321         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
322                                                    i == OutputType::Metadata) {
323             return Ok(());
324         }
325
326         // Run the linker on any artifacts that resulted from the LLVM run.
327         // This should produce either a finished executable or library.
328         sess.profiler(|p| p.start_activity("link_crate"));
329         time(sess, "linking", || {
330             use rustc_codegen_ssa::back::link::link_binary;
331             use crate::back::archive::LlvmArchiveBuilder;
332
333             let target_cpu = crate::llvm_util::target_cpu(sess);
334             link_binary::<LlvmArchiveBuilder<'_>>(
335                 sess,
336                 &codegen_results,
337                 outputs,
338                 &codegen_results.crate_name.as_str(),
339                 target_cpu,
340             );
341         });
342         sess.profiler(|p| p.end_activity("link_crate"));
343
344         // Now that we won't touch anything in the incremental compilation directory
345         // any more, we can finalize it (which involves renaming it)
346         rustc_incremental::finalize_session_directory(sess, codegen_results.crate_hash);
347
348         Ok(())
349     }
350 }
351
352 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
353 #[no_mangle]
354 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
355     LlvmCodegenBackend::new()
356 }
357
358 pub struct ModuleLlvm {
359     llcx: &'static mut llvm::Context,
360     llmod_raw: *const llvm::Module,
361     tm: &'static mut llvm::TargetMachine,
362 }
363
364 unsafe impl Send for ModuleLlvm { }
365 unsafe impl Sync for ModuleLlvm { }
366
367 impl ModuleLlvm {
368     fn new(tcx: TyCtxt<'_, '_, '_>, mod_name: &str) -> Self {
369         unsafe {
370             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
371             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
372             ModuleLlvm {
373                 llmod_raw,
374                 llcx,
375                 tm: create_target_machine(tcx, false),
376             }
377         }
378     }
379
380     fn new_metadata(tcx: TyCtxt<'_, '_, '_>, mod_name: &str) -> Self {
381         unsafe {
382             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
383             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
384             ModuleLlvm {
385                 llmod_raw,
386                 llcx,
387                 tm: create_informational_target_machine(&tcx.sess, false),
388             }
389         }
390     }
391
392     fn parse(
393         cgcx: &CodegenContext<LlvmCodegenBackend>,
394         name: &str,
395         buffer: &back::lto::ModuleBuffer,
396         handler: &Handler,
397     ) -> Result<Self, FatalError> {
398         unsafe {
399             let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
400             let llmod_raw = buffer.parse(name, llcx, handler)?;
401             let tm = match (cgcx.tm_factory.0)() {
402                 Ok(m) => m,
403                 Err(e) => {
404                     handler.struct_err(&e).emit();
405                     return Err(FatalError)
406                 }
407             };
408
409             Ok(ModuleLlvm {
410                 llmod_raw,
411                 llcx,
412                 tm,
413             })
414         }
415     }
416
417     fn llmod(&self) -> &llvm::Module {
418         unsafe {
419             &*self.llmod_raw
420         }
421     }
422 }
423
424 impl Drop for ModuleLlvm {
425     fn drop(&mut self) {
426         unsafe {
427             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
428             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
429         }
430     }
431 }
432
433 __build_diagnostic_array! { librustc_codegen_llvm, DIAGNOSTICS }