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