rustc_codegen_llvm/
lib.rs

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