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