]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/lib.rs
Rollup merge of #80035 - ChayimFriedman2:patch-1, r=nagisa
[rust.git] / compiler / rustc_codegen_llvm / src / 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/nightly-rustc/")]
8 #![feature(bool_to_option)]
9 #![feature(const_cstr_unchecked)]
10 #![feature(crate_visibility_modifier)]
11 #![feature(extern_types)]
12 #![feature(in_band_lifetimes)]
13 #![feature(nll)]
14 #![feature(or_patterns)]
15 #![recursion_limit = "256"]
16
17 use back::write::{create_informational_target_machine, create_target_machine};
18
19 pub use llvm_util::target_features;
20 use rustc_ast::expand::allocator::AllocatorKind;
21 use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
22 use rustc_codegen_ssa::back::write::{
23     CodegenContext, FatLTOInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
24 };
25 use rustc_codegen_ssa::traits::*;
26 use rustc_codegen_ssa::ModuleCodegen;
27 use rustc_codegen_ssa::{CodegenResults, CompiledModule};
28 use rustc_data_structures::fx::FxHashMap;
29 use rustc_errors::{ErrorReported, FatalError, Handler};
30 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
31 use rustc_middle::middle::cstore::{EncodedMetadata, MetadataLoaderDyn};
32 use rustc_middle::ty::{self, TyCtxt};
33 use rustc_session::config::{OptLevel, OutputFilenames, PrintRequest};
34 use rustc_session::Session;
35 use rustc_span::symbol::Symbol;
36
37 use std::any::Any;
38 use std::ffi::CStr;
39
40 mod back {
41     pub mod archive;
42     pub mod lto;
43     mod profiling;
44     pub mod write;
45 }
46
47 mod abi;
48 mod allocator;
49 mod asm;
50 mod attributes;
51 mod base;
52 mod builder;
53 mod callee;
54 mod common;
55 mod consts;
56 mod context;
57 mod coverageinfo;
58 mod debuginfo;
59 mod declare;
60 mod intrinsic;
61
62 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
63 #[path = "llvm/mod.rs"]
64 mod llvm_;
65 pub mod llvm {
66     pub use super::llvm_::*;
67 }
68
69 mod llvm_util;
70 mod metadata;
71 mod mono_item;
72 mod type_;
73 mod type_of;
74 mod va_arg;
75 mod value;
76
77 #[derive(Clone)]
78 pub struct LlvmCodegenBackend(());
79
80 impl ExtraBackendMethods for LlvmCodegenBackend {
81     fn new_metadata(&self, tcx: TyCtxt<'_>, mod_name: &str) -> ModuleLlvm {
82         ModuleLlvm::new_metadata(tcx, mod_name)
83     }
84
85     fn write_compressed_metadata<'tcx>(
86         &self,
87         tcx: TyCtxt<'tcx>,
88         metadata: &EncodedMetadata,
89         llvm_module: &mut ModuleLlvm,
90     ) {
91         base::write_compressed_metadata(tcx, metadata, llvm_module)
92     }
93     fn codegen_allocator<'tcx>(
94         &self,
95         tcx: TyCtxt<'tcx>,
96         mods: &mut ModuleLlvm,
97         kind: AllocatorKind,
98         has_alloc_error_handler: bool,
99     ) {
100         unsafe { allocator::codegen(tcx, mods, kind, has_alloc_error_handler) }
101     }
102     fn compile_codegen_unit(
103         &self,
104         tcx: TyCtxt<'_>,
105         cgu_name: Symbol,
106     ) -> (ModuleCodegen<ModuleLlvm>, u64) {
107         base::compile_codegen_unit(tcx, cgu_name)
108     }
109     fn target_machine_factory(
110         &self,
111         sess: &Session,
112         optlvl: OptLevel,
113     ) -> TargetMachineFactoryFn<Self> {
114         back::write::target_machine_factory(sess, optlvl)
115     }
116     fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
117         llvm_util::target_cpu(sess)
118     }
119     fn tune_cpu<'b>(&self, sess: &'b Session) -> Option<&'b str> {
120         llvm_util::tune_cpu(sess)
121     }
122 }
123
124 impl WriteBackendMethods for LlvmCodegenBackend {
125     type Module = ModuleLlvm;
126     type ModuleBuffer = back::lto::ModuleBuffer;
127     type Context = llvm::Context;
128     type TargetMachine = &'static mut llvm::TargetMachine;
129     type ThinData = back::lto::ThinData;
130     type ThinBuffer = back::lto::ThinBuffer;
131     fn print_pass_timings(&self) {
132         unsafe {
133             llvm::LLVMRustPrintPassTimings();
134         }
135     }
136     fn run_link(
137         cgcx: &CodegenContext<Self>,
138         diag_handler: &Handler,
139         modules: Vec<ModuleCodegen<Self::Module>>,
140     ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
141         back::write::link(cgcx, diag_handler, modules)
142     }
143     fn run_fat_lto(
144         cgcx: &CodegenContext<Self>,
145         modules: Vec<FatLTOInput<Self>>,
146         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
147     ) -> Result<LtoModuleCodegen<Self>, FatalError> {
148         back::lto::run_fat(cgcx, modules, cached_modules)
149     }
150     fn run_thin_lto(
151         cgcx: &CodegenContext<Self>,
152         modules: Vec<(String, Self::ThinBuffer)>,
153         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
154     ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
155         back::lto::run_thin(cgcx, modules, cached_modules)
156     }
157     unsafe fn optimize(
158         cgcx: &CodegenContext<Self>,
159         diag_handler: &Handler,
160         module: &ModuleCodegen<Self::Module>,
161         config: &ModuleConfig,
162     ) -> Result<(), FatalError> {
163         back::write::optimize(cgcx, diag_handler, module, config)
164     }
165     unsafe fn optimize_thin(
166         cgcx: &CodegenContext<Self>,
167         thin: &mut ThinModule<Self>,
168     ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
169         back::lto::optimize_thin_module(thin, cgcx)
170     }
171     unsafe fn codegen(
172         cgcx: &CodegenContext<Self>,
173         diag_handler: &Handler,
174         module: ModuleCodegen<Self::Module>,
175         config: &ModuleConfig,
176     ) -> Result<CompiledModule, FatalError> {
177         back::write::codegen(cgcx, diag_handler, module, config)
178     }
179     fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
180         back::lto::prepare_thin(module)
181     }
182     fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
183         (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
184     }
185     fn run_lto_pass_manager(
186         cgcx: &CodegenContext<Self>,
187         module: &ModuleCodegen<Self::Module>,
188         config: &ModuleConfig,
189         thin: bool,
190     ) {
191         back::lto::run_pass_manager(cgcx, module, config, thin)
192     }
193 }
194
195 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
196 unsafe impl Sync for LlvmCodegenBackend {}
197
198 impl LlvmCodegenBackend {
199     pub fn new() -> Box<dyn CodegenBackend> {
200         Box::new(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
214                     &["static", "pic", "dynamic-no-pic", "ropi", "rwpi", "ropi-rwpi", "default"]
215                 {
216                     println!("    {}", name);
217                 }
218                 println!();
219             }
220             PrintRequest::CodeModels => {
221                 println!("Available code models:");
222                 for name in &["tiny", "small", "kernel", "medium", "large"] {
223                     println!("    {}", name);
224                 }
225                 println!();
226             }
227             PrintRequest::TlsModels => {
228                 println!("Available TLS models:");
229                 for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
230                     println!("    {}", name);
231                 }
232                 println!();
233             }
234             req => llvm_util::print(req, sess),
235         }
236     }
237
238     fn print_passes(&self) {
239         llvm_util::print_passes();
240     }
241
242     fn print_version(&self) {
243         llvm_util::print_version();
244     }
245
246     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
247         target_features(sess)
248     }
249
250     fn metadata_loader(&self) -> Box<MetadataLoaderDyn> {
251         Box::new(metadata::LlvmMetadataLoader)
252     }
253
254     fn provide(&self, providers: &mut ty::query::Providers) {
255         attributes::provide_both(providers);
256     }
257
258     fn provide_extern(&self, providers: &mut ty::query::Providers) {
259         attributes::provide_both(providers);
260     }
261
262     fn codegen_crate<'tcx>(
263         &self,
264         tcx: TyCtxt<'tcx>,
265         metadata: EncodedMetadata,
266         need_metadata_module: bool,
267     ) -> Box<dyn Any> {
268         Box::new(rustc_codegen_ssa::base::codegen_crate(
269             LlvmCodegenBackend(()),
270             tcx,
271             metadata,
272             need_metadata_module,
273         ))
274     }
275
276     fn join_codegen(
277         &self,
278         ongoing_codegen: Box<dyn Any>,
279         sess: &Session,
280     ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorReported> {
281         let (codegen_results, work_products) = ongoing_codegen
282             .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
283             .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
284             .join(sess);
285
286         sess.time("llvm_dump_timing_file", || {
287             if sess.opts.debugging_opts.llvm_time_trace {
288                 llvm_util::time_trace_profiler_finish("llvm_timings.json");
289             }
290         });
291
292         Ok((codegen_results, work_products))
293     }
294
295     fn link(
296         &self,
297         sess: &Session,
298         codegen_results: CodegenResults,
299         outputs: &OutputFilenames,
300     ) -> Result<(), ErrorReported> {
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         Ok(())
318     }
319 }
320
321 pub struct ModuleLlvm {
322     llcx: &'static mut llvm::Context,
323     llmod_raw: *const llvm::Module,
324     tm: &'static mut llvm::TargetMachine,
325 }
326
327 unsafe impl Send for ModuleLlvm {}
328 unsafe impl Sync for ModuleLlvm {}
329
330 impl ModuleLlvm {
331     fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
332         unsafe {
333             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
334             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
335             ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx, mod_name) }
336         }
337     }
338
339     fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
340         unsafe {
341             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
342             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
343             ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
344         }
345     }
346
347     fn parse(
348         cgcx: &CodegenContext<LlvmCodegenBackend>,
349         name: &CStr,
350         buffer: &[u8],
351         handler: &Handler,
352     ) -> Result<Self, FatalError> {
353         unsafe {
354             let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
355             let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
356
357             let split_dwarf_file = cgcx
358                 .output_filenames
359                 .split_dwarf_filename(cgcx.split_dwarf_kind, Some(name.to_str().unwrap()));
360             let tm_factory_config = TargetMachineFactoryConfig { split_dwarf_file };
361
362             let tm = match (cgcx.tm_factory)(tm_factory_config) {
363                 Ok(m) => m,
364                 Err(e) => {
365                     handler.struct_err(&e).emit();
366                     return Err(FatalError);
367                 }
368             };
369
370             Ok(ModuleLlvm { llmod_raw, llcx, tm })
371         }
372     }
373
374     fn llmod(&self) -> &llvm::Module {
375         unsafe { &*self.llmod_raw }
376     }
377 }
378
379 impl Drop for ModuleLlvm {
380     fn drop(&mut self) {
381         unsafe {
382             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
383             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
384         }
385     }
386 }