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