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