]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/lib.rs
Rollup merge of #94363 - aDotInTheVoid:fmt-needless-borrows, r=scottmcm
[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(crate_visibility_modifier)]
10 #![feature(let_else)]
11 #![feature(extern_types)]
12 #![feature(once_cell)]
13 #![feature(nll)]
14 #![recursion_limit = "256"]
15 #![allow(rustc::potential_query_instability)]
16
17 #[macro_use]
18 extern crate rustc_macros;
19
20 use back::write::{create_informational_target_machine, create_target_machine};
21
22 pub use llvm_util::target_features;
23 use rustc_ast::expand::allocator::AllocatorKind;
24 use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
25 use rustc_codegen_ssa::back::write::{
26     CodegenContext, FatLTOInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
27 };
28 use rustc_codegen_ssa::traits::*;
29 use rustc_codegen_ssa::ModuleCodegen;
30 use rustc_codegen_ssa::{CodegenResults, CompiledModule};
31 use rustc_data_structures::fx::FxHashMap;
32 use rustc_errors::{ErrorReported, FatalError, Handler};
33 use rustc_metadata::EncodedMetadata;
34 use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
35 use rustc_middle::ty::TyCtxt;
36 use rustc_session::config::{OptLevel, OutputFilenames, PrintRequest};
37 use rustc_session::Session;
38 use rustc_span::symbol::Symbol;
39
40 use std::any::Any;
41 use std::ffi::CStr;
42
43 mod back {
44     pub mod archive;
45     pub mod lto;
46     mod profiling;
47     pub mod write;
48 }
49
50 mod abi;
51 mod allocator;
52 mod asm;
53 mod attributes;
54 mod base;
55 mod builder;
56 mod callee;
57 mod common;
58 mod consts;
59 mod context;
60 mod coverageinfo;
61 mod debuginfo;
62 mod declare;
63 mod intrinsic;
64
65 // The following is a work around that replaces `pub mod llvm;` and that fixes issue 53912.
66 #[path = "llvm/mod.rs"]
67 mod llvm_;
68 pub mod llvm {
69     pub use super::llvm_::*;
70 }
71
72 mod llvm_util;
73 mod mono_item;
74 mod type_;
75 mod type_of;
76 mod va_arg;
77 mod value;
78
79 #[derive(Clone)]
80 pub struct LlvmCodegenBackend(());
81
82 struct TimeTraceProfiler {
83     enabled: bool,
84 }
85
86 impl TimeTraceProfiler {
87     fn new(enabled: bool) -> Self {
88         if enabled {
89             unsafe { llvm::LLVMTimeTraceProfilerInitialize() }
90         }
91         TimeTraceProfiler { enabled }
92     }
93 }
94
95 impl Drop for TimeTraceProfiler {
96     fn drop(&mut self) {
97         if self.enabled {
98             unsafe { llvm::LLVMTimeTraceProfilerFinishThread() }
99         }
100     }
101 }
102
103 impl ExtraBackendMethods for LlvmCodegenBackend {
104     fn new_metadata(&self, tcx: TyCtxt<'_>, mod_name: &str) -> ModuleLlvm {
105         ModuleLlvm::new_metadata(tcx, mod_name)
106     }
107
108     fn codegen_allocator<'tcx>(
109         &self,
110         tcx: TyCtxt<'tcx>,
111         module_llvm: &mut ModuleLlvm,
112         module_name: &str,
113         kind: AllocatorKind,
114         has_alloc_error_handler: bool,
115     ) {
116         unsafe { allocator::codegen(tcx, module_llvm, module_name, kind, has_alloc_error_handler) }
117     }
118     fn compile_codegen_unit(
119         &self,
120         tcx: TyCtxt<'_>,
121         cgu_name: Symbol,
122     ) -> (ModuleCodegen<ModuleLlvm>, u64) {
123         base::compile_codegen_unit(tcx, cgu_name)
124     }
125     fn target_machine_factory(
126         &self,
127         sess: &Session,
128         optlvl: OptLevel,
129     ) -> TargetMachineFactoryFn<Self> {
130         back::write::target_machine_factory(sess, optlvl)
131     }
132     fn target_cpu<'b>(&self, sess: &'b Session) -> &'b str {
133         llvm_util::target_cpu(sess)
134     }
135     fn tune_cpu<'b>(&self, sess: &'b Session) -> Option<&'b str> {
136         llvm_util::tune_cpu(sess)
137     }
138
139     fn spawn_thread<F, T>(time_trace: bool, f: F) -> std::thread::JoinHandle<T>
140     where
141         F: FnOnce() -> T,
142         F: Send + 'static,
143         T: Send + 'static,
144     {
145         std::thread::spawn(move || {
146             let _profiler = TimeTraceProfiler::new(time_trace);
147             f()
148         })
149     }
150
151     fn spawn_named_thread<F, T>(
152         time_trace: bool,
153         name: String,
154         f: F,
155     ) -> std::io::Result<std::thread::JoinHandle<T>>
156     where
157         F: FnOnce() -> T,
158         F: Send + 'static,
159         T: Send + 'static,
160     {
161         std::thread::Builder::new().name(name).spawn(move || {
162             let _profiler = TimeTraceProfiler::new(time_trace);
163             f()
164         })
165     }
166 }
167
168 impl WriteBackendMethods for LlvmCodegenBackend {
169     type Module = ModuleLlvm;
170     type ModuleBuffer = back::lto::ModuleBuffer;
171     type Context = llvm::Context;
172     type TargetMachine = &'static mut llvm::TargetMachine;
173     type ThinData = back::lto::ThinData;
174     type ThinBuffer = back::lto::ThinBuffer;
175     fn print_pass_timings(&self) {
176         unsafe {
177             llvm::LLVMRustPrintPassTimings();
178         }
179     }
180     fn run_link(
181         cgcx: &CodegenContext<Self>,
182         diag_handler: &Handler,
183         modules: Vec<ModuleCodegen<Self::Module>>,
184     ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
185         back::write::link(cgcx, diag_handler, modules)
186     }
187     fn run_fat_lto(
188         cgcx: &CodegenContext<Self>,
189         modules: Vec<FatLTOInput<Self>>,
190         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
191     ) -> Result<LtoModuleCodegen<Self>, FatalError> {
192         back::lto::run_fat(cgcx, modules, cached_modules)
193     }
194     fn run_thin_lto(
195         cgcx: &CodegenContext<Self>,
196         modules: Vec<(String, Self::ThinBuffer)>,
197         cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
198     ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
199         back::lto::run_thin(cgcx, modules, cached_modules)
200     }
201     unsafe fn optimize(
202         cgcx: &CodegenContext<Self>,
203         diag_handler: &Handler,
204         module: &ModuleCodegen<Self::Module>,
205         config: &ModuleConfig,
206     ) -> Result<(), FatalError> {
207         back::write::optimize(cgcx, diag_handler, module, config)
208     }
209     unsafe fn optimize_thin(
210         cgcx: &CodegenContext<Self>,
211         thin: &mut ThinModule<Self>,
212     ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
213         back::lto::optimize_thin_module(thin, cgcx)
214     }
215     unsafe fn codegen(
216         cgcx: &CodegenContext<Self>,
217         diag_handler: &Handler,
218         module: ModuleCodegen<Self::Module>,
219         config: &ModuleConfig,
220     ) -> Result<CompiledModule, FatalError> {
221         back::write::codegen(cgcx, diag_handler, module, config)
222     }
223     fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
224         back::lto::prepare_thin(module)
225     }
226     fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
227         (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
228     }
229     fn run_lto_pass_manager(
230         cgcx: &CodegenContext<Self>,
231         module: &ModuleCodegen<Self::Module>,
232         config: &ModuleConfig,
233         thin: bool,
234     ) -> Result<(), FatalError> {
235         let diag_handler = cgcx.create_diag_handler();
236         back::lto::run_pass_manager(cgcx, &diag_handler, module, config, thin)
237     }
238 }
239
240 unsafe impl Send for LlvmCodegenBackend {} // Llvm is on a per-thread basis
241 unsafe impl Sync for LlvmCodegenBackend {}
242
243 impl LlvmCodegenBackend {
244     pub fn new() -> Box<dyn CodegenBackend> {
245         Box::new(LlvmCodegenBackend(()))
246     }
247 }
248
249 impl CodegenBackend for LlvmCodegenBackend {
250     fn init(&self, sess: &Session) {
251         llvm_util::init(sess); // Make sure llvm is inited
252     }
253
254     fn print(&self, req: PrintRequest, sess: &Session) {
255         match req {
256             PrintRequest::RelocationModels => {
257                 println!("Available relocation models:");
258                 for name in &[
259                     "static",
260                     "pic",
261                     "pie",
262                     "dynamic-no-pic",
263                     "ropi",
264                     "rwpi",
265                     "ropi-rwpi",
266                     "default",
267                 ] {
268                     println!("    {}", name);
269                 }
270                 println!();
271             }
272             PrintRequest::CodeModels => {
273                 println!("Available code models:");
274                 for name in &["tiny", "small", "kernel", "medium", "large"] {
275                     println!("    {}", name);
276                 }
277                 println!();
278             }
279             PrintRequest::TlsModels => {
280                 println!("Available TLS models:");
281                 for name in &["global-dynamic", "local-dynamic", "initial-exec", "local-exec"] {
282                     println!("    {}", name);
283                 }
284                 println!();
285             }
286             PrintRequest::StackProtectorStrategies => {
287                 println!(
288                     r#"Available stack protector strategies:
289     all
290         Generate stack canaries in all functions.
291
292     strong
293         Generate stack canaries in a function if it either:
294         - has a local variable of `[T; N]` type, regardless of `T` and `N`
295         - takes the address of a local variable.
296
297           (Note that a local variable being borrowed is not equivalent to its
298           address being taken: e.g. some borrows may be removed by optimization,
299           while by-value argument passing may be implemented with reference to a
300           local stack variable in the ABI.)
301
302     basic
303         Generate stack canaries in functions with:
304         - local variables of `[T; N]` type, where `T` is byte-sized and `N` > 8.
305
306     none
307         Do not generate stack canaries.
308 "#
309                 );
310             }
311             req => llvm_util::print(req, sess),
312         }
313     }
314
315     fn print_passes(&self) {
316         llvm_util::print_passes();
317     }
318
319     fn print_version(&self) {
320         llvm_util::print_version();
321     }
322
323     fn target_features(&self, sess: &Session) -> Vec<Symbol> {
324         target_features(sess)
325     }
326
327     fn codegen_crate<'tcx>(
328         &self,
329         tcx: TyCtxt<'tcx>,
330         metadata: EncodedMetadata,
331         need_metadata_module: bool,
332     ) -> Box<dyn Any> {
333         Box::new(rustc_codegen_ssa::base::codegen_crate(
334             LlvmCodegenBackend(()),
335             tcx,
336             crate::llvm_util::target_cpu(tcx.sess).to_string(),
337             metadata,
338             need_metadata_module,
339         ))
340     }
341
342     fn join_codegen(
343         &self,
344         ongoing_codegen: Box<dyn Any>,
345         sess: &Session,
346         outputs: &OutputFilenames,
347     ) -> Result<(CodegenResults, FxHashMap<WorkProductId, WorkProduct>), ErrorReported> {
348         let (codegen_results, work_products) = ongoing_codegen
349             .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
350             .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
351             .join(sess);
352
353         sess.time("llvm_dump_timing_file", || {
354             if sess.opts.debugging_opts.llvm_time_trace {
355                 let file_name = outputs.with_extension("llvm_timings.json");
356                 llvm_util::time_trace_profiler_finish(&file_name);
357             }
358         });
359
360         Ok((codegen_results, work_products))
361     }
362
363     fn link(
364         &self,
365         sess: &Session,
366         codegen_results: CodegenResults,
367         outputs: &OutputFilenames,
368     ) -> Result<(), ErrorReported> {
369         use crate::back::archive::LlvmArchiveBuilder;
370         use rustc_codegen_ssa::back::link::link_binary;
371
372         // Run the linker on any artifacts that resulted from the LLVM run.
373         // This should produce either a finished executable or library.
374         link_binary::<LlvmArchiveBuilder<'_>>(sess, &codegen_results, outputs)
375     }
376 }
377
378 pub struct ModuleLlvm {
379     llcx: &'static mut llvm::Context,
380     llmod_raw: *const llvm::Module,
381     tm: &'static mut llvm::TargetMachine,
382 }
383
384 unsafe impl Send for ModuleLlvm {}
385 unsafe impl Sync for ModuleLlvm {}
386
387 impl ModuleLlvm {
388     fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
389         unsafe {
390             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
391             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
392             ModuleLlvm { llmod_raw, llcx, tm: create_target_machine(tcx, mod_name) }
393         }
394     }
395
396     fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
397         unsafe {
398             let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
399             let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
400             ModuleLlvm { llmod_raw, llcx, tm: create_informational_target_machine(tcx.sess) }
401         }
402     }
403
404     fn parse(
405         cgcx: &CodegenContext<LlvmCodegenBackend>,
406         name: &CStr,
407         buffer: &[u8],
408         handler: &Handler,
409     ) -> Result<Self, FatalError> {
410         unsafe {
411             let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
412             let llmod_raw = back::lto::parse_module(llcx, name, buffer, handler)?;
413             let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap());
414             let tm = match (cgcx.tm_factory)(tm_factory_config) {
415                 Ok(m) => m,
416                 Err(e) => {
417                     handler.struct_err(&e).emit();
418                     return Err(FatalError);
419                 }
420             };
421
422             Ok(ModuleLlvm { llmod_raw, llcx, tm })
423         }
424     }
425
426     fn llmod(&self) -> &llvm::Module {
427         unsafe { &*self.llmod_raw }
428     }
429 }
430
431 impl Drop for ModuleLlvm {
432     fn drop(&mut self) {
433         unsafe {
434             llvm::LLVMRustDisposeTargetMachine(&mut *(self.tm as *mut _));
435             llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
436         }
437     }
438 }