]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/lib.rs
Rollup merge of #65995 - GuillaumeGomez:add-err-code-E0743, r=estebank
[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 #![feature(libc)]
16 #![feature(nll)]
17 #![feature(optin_builtin_traits)]
18 #![feature(concat_idents)]
19 #![feature(link_args)]
20 #![feature(static_nobundle)]
21 #![feature(trusted_len)]
22
23 use back::write::{create_target_machine, create_informational_target_machine};
24 use syntax_pos::symbol::Symbol;
25
26 extern crate rustc_demangle;
27 extern crate flate2;
28 #[macro_use] extern crate bitflags;
29 extern crate libc;
30 #[macro_use] extern crate rustc;
31 extern crate rustc_target;
32 #[macro_use] extern crate rustc_data_structures;
33 extern crate rustc_index;
34 extern crate rustc_incremental;
35 extern crate rustc_codegen_utils;
36 extern crate rustc_codegen_ssa;
37 extern crate rustc_fs_util;
38 extern crate rustc_driver as _;
39
40 #[macro_use] extern crate log;
41 extern crate smallvec;
42 extern crate syntax;
43 extern crate syntax_pos;
44 extern crate rustc_errors as errors;
45
46 use rustc_codegen_ssa::traits::*;
47 use rustc_codegen_ssa::back::write::{CodegenContext, ModuleConfig, FatLTOInput};
48 use rustc_codegen_ssa::back::lto::{SerializedModule, LtoModuleCodegen, ThinModule};
49 use rustc_codegen_ssa::CompiledModule;
50 use errors::{FatalError, Handler};
51 use rustc::dep_graph::WorkProduct;
52 use syntax::expand::allocator::AllocatorKind;
53 pub use llvm_util::target_features;
54 use std::any::Any;
55 use std::sync::Arc;
56 use std::ffi::CStr;
57
58 use rustc::dep_graph::DepGraph;
59 use rustc::middle::cstore::{EncodedMetadata, MetadataLoaderDyn};
60 use rustc::session::Session;
61 use rustc::session::config::{OutputFilenames, OutputType, PrintRequest, OptLevel};
62 use rustc::ty::{self, TyCtxt};
63 use rustc::util::common::ErrorReported;
64 use rustc_codegen_ssa::ModuleCodegen;
65 use rustc_codegen_utils::codegen_backend::CodegenBackend;
66
67 mod back {
68     pub mod archive;
69     pub mod bytecode;
70     pub mod lto;
71     pub mod write;
72 }
73
74 mod abi;
75 mod allocator;
76 mod asm;
77 mod attributes;
78 mod base;
79 mod builder;
80 mod callee;
81 mod common;
82 mod consts;
83 mod context;
84 mod debuginfo;
85 mod declare;
86 mod intrinsic;
87
88 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
89 #[path = "llvm/mod.rs"] mod llvm_; pub mod llvm { pub use super::llvm_::*; }
90
91 mod llvm_util;
92 mod metadata;
93 mod mono_item;
94 mod type_;
95 mod type_of;
96 mod value;
97 mod va_arg;
98
99 #[derive(Clone)]
100 pub struct LlvmCodegenBackend(());
101
102 impl ExtraBackendMethods for LlvmCodegenBackend {
103     fn new_metadata(&self, tcx: TyCtxt<'_>, mod_name: &str) -> ModuleLlvm {
104         ModuleLlvm::new_metadata(tcx, mod_name)
105     }
106
107     fn write_compressed_metadata<'tcx>(
108         &self,
109         tcx: TyCtxt<'tcx>,
110         metadata: &EncodedMetadata,
111         llvm_module: &mut ModuleLlvm,
112     ) {
113         base::write_compressed_metadata(tcx, metadata, llvm_module)
114     }
115     fn codegen_allocator<'tcx>(
116         &self,
117         tcx: TyCtxt<'tcx>,
118         mods: &mut ModuleLlvm,
119         kind: AllocatorKind,
120     ) {
121         unsafe { allocator::codegen(tcx, mods, kind) }
122     }
123     fn compile_codegen_unit(
124         &self, tcx: TyCtxt<'_>,
125         cgu_name: Symbol,
126         tx: &std::sync::mpsc::Sender<Box<dyn Any + Send>>,
127     ) {
128         base::compile_codegen_unit(tcx, cgu_name, tx);
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 target_features(&self, sess: &Session) -> Vec<Symbol> {
260         target_features(sess)
261     }
262
263     fn metadata_loader(&self) -> Box<MetadataLoaderDyn> {
264         box metadata::LlvmMetadataLoader
265     }
266
267     fn provide(&self, providers: &mut ty::query::Providers<'_>) {
268         attributes::provide(providers);
269     }
270
271     fn provide_extern(&self, providers: &mut ty::query::Providers<'_>) {
272         attributes::provide_extern(providers);
273     }
274
275     fn codegen_crate<'tcx>(
276         &self,
277         tcx: TyCtxt<'tcx>,
278         metadata: EncodedMetadata,
279         need_metadata_module: bool,
280     ) -> Box<dyn Any> {
281         box rustc_codegen_ssa::base::codegen_crate(
282             LlvmCodegenBackend(()), tcx, metadata, need_metadata_module)
283     }
284
285     fn join_codegen_and_link(
286         &self,
287         ongoing_codegen: Box<dyn Any>,
288         sess: &Session,
289         dep_graph: &DepGraph,
290         outputs: &OutputFilenames,
291     ) -> Result<(), ErrorReported> {
292         use rustc::util::common::time;
293         let (codegen_results, work_products) =
294             ongoing_codegen.downcast::
295                 <rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
296                 .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
297                 .join(sess);
298         if sess.opts.debugging_opts.incremental_info {
299             rustc_codegen_ssa::back::write::dump_incremental_data(&codegen_results);
300         }
301
302         time(sess,
303              "serialize work products",
304              move || rustc_incremental::save_work_product_index(sess, &dep_graph, work_products));
305
306         sess.compile_status()?;
307
308         if !sess.opts.output_types.keys().any(|&i| i == OutputType::Exe ||
309                                                    i == OutputType::Metadata) {
310             return Ok(());
311         }
312
313         // Run the linker on any artifacts that resulted from the LLVM run.
314         // This should produce either a finished executable or library.
315         time(sess, "linking", || {
316             let _prof_timer = sess.prof.generic_activity("link_crate");
317
318             use rustc_codegen_ssa::back::link::link_binary;
319             use crate::back::archive::LlvmArchiveBuilder;
320
321             let target_cpu = crate::llvm_util::target_cpu(sess);
322             link_binary::<LlvmArchiveBuilder<'_>>(
323                 sess,
324                 &codegen_results,
325                 outputs,
326                 &codegen_results.crate_name.as_str(),
327                 target_cpu,
328             );
329         });
330
331         // Now that we won't touch anything in the incremental compilation directory
332         // any more, we can finalize it (which involves renaming it)
333         rustc_incremental::finalize_session_directory(sess, codegen_results.crate_hash);
334
335         Ok(())
336     }
337 }
338
339 /// This is the entrypoint for a hot plugged rustc_codegen_llvm
340 #[no_mangle]
341 pub fn __rustc_codegen_backend() -> Box<dyn CodegenBackend> {
342     LlvmCodegenBackend::new()
343 }
344
345 pub struct ModuleLlvm {
346     llcx: &'static mut llvm::Context,
347     llmod_raw: *const llvm::Module,
348     tm: &'static mut llvm::TargetMachine,
349 }
350
351 unsafe impl Send for ModuleLlvm { }
352 unsafe impl Sync for ModuleLlvm { }
353
354 impl ModuleLlvm {
355     fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
356         unsafe {
357             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
358             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
359             ModuleLlvm {
360                 llmod_raw,
361                 llcx,
362                 tm: create_target_machine(tcx, false),
363             }
364         }
365     }
366
367     fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
368         unsafe {
369             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
370             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
371             ModuleLlvm {
372                 llmod_raw,
373                 llcx,
374                 tm: create_informational_target_machine(&tcx.sess, false),
375             }
376         }
377     }
378
379     fn parse(
380         cgcx: &CodegenContext<LlvmCodegenBackend>,
381         name: &CStr,
382         buffer: &[u8],
383         handler: &Handler,
384     ) -> Result<Self, FatalError> {
385         unsafe {
386             let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
387             let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
388             let tm = match (cgcx.tm_factory.0)() {
389                 Ok(m) => m,
390                 Err(e) => {
391                     handler.struct_err(&e).emit();
392                     return Err(FatalError)
393                 }
394             };
395
396             Ok(ModuleLlvm {
397                 llmod_raw,
398                 llcx,
399                 tm,
400             })
401         }
402     }
403
404     fn llmod(&self) -> &llvm::Module {
405         unsafe {
406             &*self.llmod_raw
407         }
408     }
409 }
410
411 impl Drop for ModuleLlvm {
412     fn drop(&mut self) {
413         unsafe {
414             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
415             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
416         }
417     }
418 }