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