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