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 abi;
50mod allocator;
51mod asm;
52mod attributes;
53mod back;
54mod base;
55mod builder;
56mod callee;
57mod common;
58mod consts;
59mod context;
60mod coverageinfo;
61mod debuginfo;
62mod declare;
63mod errors;
64mod intrinsic;
65mod llvm;
66mod llvm_util;
67mod mono_item;
68mod type_;
69mod type_of;
70mod va_arg;
71mod value;
72
73rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
74
75#[derive(Clone)]
76pub struct LlvmCodegenBackend(());
77
78struct TimeTraceProfiler {
79    enabled: bool,
80}
81
82impl TimeTraceProfiler {
83    fn new(enabled: bool) -> Self {
84        if enabled {
85            unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() }
86        }
87        TimeTraceProfiler { enabled }
88    }
89}
90
91impl Drop for TimeTraceProfiler {
92    fn drop(&mut self) {
93        if self.enabled {
94            unsafe { llvm::LLVMRustTimeTraceProfilerFinishThread() }
95        }
96    }
97}
98
99impl ExtraBackendMethods for LlvmCodegenBackend {
100    fn codegen_allocator<'tcx>(
101        &self,
102        tcx: TyCtxt<'tcx>,
103        module_name: &str,
104        kind: AllocatorKind,
105        alloc_error_handler_kind: AllocatorKind,
106    ) -> ModuleLlvm {
107        let module_llvm = ModuleLlvm::new_metadata(tcx, module_name);
108        let cx =
109            SimpleCx::new(module_llvm.llmod(), &module_llvm.llcx, tcx.data_layout.pointer_size());
110        unsafe {
111            allocator::codegen(tcx, cx, module_name, kind, alloc_error_handler_kind);
112        }
113        module_llvm
114    }
115    fn compile_codegen_unit(
116        &self,
117        tcx: TyCtxt<'_>,
118        cgu_name: Symbol,
119    ) -> (ModuleCodegen<ModuleLlvm>, u64) {
120        base::compile_codegen_unit(tcx, cgu_name)
121    }
122    fn target_machine_factory(
123        &self,
124        sess: &Session,
125        optlvl: OptLevel,
126        target_features: &[String],
127    ) -> TargetMachineFactoryFn<Self> {
128        back::write::target_machine_factory(sess, optlvl, target_features)
129    }
130
131    fn spawn_named_thread<F, T>(
132        time_trace: bool,
133        name: String,
134        f: F,
135    ) -> std::io::Result<std::thread::JoinHandle<T>>
136    where
137        F: FnOnce() -> T,
138        F: Send + 'static,
139        T: Send + 'static,
140    {
141        std::thread::Builder::new().name(name).spawn(move || {
142            let _profiler = TimeTraceProfiler::new(time_trace);
143            f()
144        })
145    }
146}
147
148impl WriteBackendMethods for LlvmCodegenBackend {
149    type Module = ModuleLlvm;
150    type ModuleBuffer = back::lto::ModuleBuffer;
151    type TargetMachine = OwnedTargetMachine;
152    type TargetMachineError = crate::errors::LlvmError<'static>;
153    type ThinData = back::lto::ThinData;
154    type ThinBuffer = back::lto::ThinBuffer;
155    fn print_pass_timings(&self) {
156        let timings = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintPassTimings(s) }).unwrap();
157        print!("{timings}");
158    }
159    fn print_statistics(&self) {
160        let stats = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatistics(s) }).unwrap();
161        print!("{stats}");
162    }
163    fn run_and_optimize_fat_lto(
164        cgcx: &CodegenContext<Self>,
165        exported_symbols_for_lto: &[String],
166        each_linked_rlib_for_lto: &[PathBuf],
167        modules: Vec<FatLtoInput<Self>>,
168    ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
169        let mut module =
170            back::lto::run_fat(cgcx, exported_symbols_for_lto, each_linked_rlib_for_lto, modules)?;
171
172        let dcx = cgcx.create_dcx();
173        let dcx = dcx.handle();
174        back::lto::run_pass_manager(cgcx, dcx, &mut module, false)?;
175
176        Ok(module)
177    }
178    fn run_thin_lto(
179        cgcx: &CodegenContext<Self>,
180        exported_symbols_for_lto: &[String],
181        each_linked_rlib_for_lto: &[PathBuf],
182        modules: Vec<(String, Self::ThinBuffer)>,
183        cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
184    ) -> Result<(Vec<ThinModule<Self>>, Vec<WorkProduct>), FatalError> {
185        back::lto::run_thin(
186            cgcx,
187            exported_symbols_for_lto,
188            each_linked_rlib_for_lto,
189            modules,
190            cached_modules,
191        )
192    }
193    fn optimize(
194        cgcx: &CodegenContext<Self>,
195        dcx: DiagCtxtHandle<'_>,
196        module: &mut ModuleCodegen<Self::Module>,
197        config: &ModuleConfig,
198    ) -> Result<(), FatalError> {
199        back::write::optimize(cgcx, dcx, module, config)
200    }
201    fn optimize_thin(
202        cgcx: &CodegenContext<Self>,
203        thin: ThinModule<Self>,
204    ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
205        back::lto::optimize_thin_module(thin, cgcx)
206    }
207    fn codegen(
208        cgcx: &CodegenContext<Self>,
209        module: ModuleCodegen<Self::Module>,
210        config: &ModuleConfig,
211    ) -> Result<CompiledModule, FatalError> {
212        back::write::codegen(cgcx, module, config)
213    }
214    fn prepare_thin(
215        module: ModuleCodegen<Self::Module>,
216        emit_summary: bool,
217    ) -> (String, Self::ThinBuffer) {
218        back::lto::prepare_thin(module, emit_summary)
219    }
220    fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
221        (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
222    }
223}
224
225impl LlvmCodegenBackend {
226    pub fn new() -> Box<dyn CodegenBackend> {
227        Box::new(LlvmCodegenBackend(()))
228    }
229}
230
231impl CodegenBackend for LlvmCodegenBackend {
232    fn locale_resource(&self) -> &'static str {
233        crate::DEFAULT_LOCALE_RESOURCE
234    }
235
236    fn init(&self, sess: &Session) {
237        llvm_util::init(sess); // Make sure llvm is inited
238    }
239
240    fn provide(&self, providers: &mut Providers) {
241        providers.global_backend_features =
242            |tcx, ()| llvm_util::global_llvm_features(tcx.sess, true, false)
243    }
244
245    fn print(&self, req: &PrintRequest, out: &mut String, sess: &Session) {
246        use std::fmt::Write;
247        match req.kind {
248            PrintKind::RelocationModels => {
249                writeln!(out, "Available relocation models:").unwrap();
250                for name in &[
251                    "static",
252                    "pic",
253                    "pie",
254                    "dynamic-no-pic",
255                    "ropi",
256                    "rwpi",
257                    "ropi-rwpi",
258                    "default",
259                ] {
260                    writeln!(out, "    {name}").unwrap();
261                }
262                writeln!(out).unwrap();
263            }
264            PrintKind::CodeModels => {
265                writeln!(out, "Available code models:").unwrap();
266                for name in &["tiny", "small", "kernel", "medium", "large"] {
267                    writeln!(out, "    {name}").unwrap();
268                }
269                writeln!(out).unwrap();
270            }
271            PrintKind::TlsModels => {
272                writeln!(out, "Available TLS models:").unwrap();
273                for name in
274                    &["global-dynamic", "local-dynamic", "initial-exec", "local-exec", "emulated"]
275                {
276                    writeln!(out, "    {name}").unwrap();
277                }
278                writeln!(out).unwrap();
279            }
280            PrintKind::StackProtectorStrategies => {
281                writeln!(
282                    out,
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 local variables of `[T; N]`
299        type, where `T` is byte-sized and `N` >= 8.
300
301    none
302        Do not generate stack canaries.
303"#
304                )
305                .unwrap();
306            }
307            _other => llvm_util::print(req, out, 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_config(&self, sess: &Session) -> TargetConfig {
320        target_config(sess)
321    }
322
323    fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
324        Box::new(rustc_codegen_ssa::base::codegen_crate(
325            LlvmCodegenBackend(()),
326            tcx,
327            crate::llvm_util::target_cpu(tcx.sess).to_string(),
328        ))
329    }
330
331    fn join_codegen(
332        &self,
333        ongoing_codegen: Box<dyn Any>,
334        sess: &Session,
335        outputs: &OutputFilenames,
336    ) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
337        let (codegen_results, work_products) = ongoing_codegen
338            .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
339            .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
340            .join(sess);
341
342        if sess.opts.unstable_opts.llvm_time_trace {
343            sess.time("llvm_dump_timing_file", || {
344                let file_name = outputs.with_extension("llvm_timings.json");
345                llvm_util::time_trace_profiler_finish(&file_name);
346            });
347        }
348
349        (codegen_results, work_products)
350    }
351
352    fn link(
353        &self,
354        sess: &Session,
355        codegen_results: CodegenResults,
356        metadata: EncodedMetadata,
357        outputs: &OutputFilenames,
358    ) {
359        use rustc_codegen_ssa::back::link::link_binary;
360
361        use crate::back::archive::LlvmArchiveBuilderBuilder;
362
363        // Run the linker on any artifacts that resulted from the LLVM run.
364        // This should produce either a finished executable or library.
365        link_binary(sess, &LlvmArchiveBuilderBuilder, codegen_results, metadata, outputs);
366    }
367}
368
369pub struct ModuleLlvm {
370    llcx: &'static mut llvm::Context,
371    llmod_raw: *const llvm::Module,
372
373    // This field is `ManuallyDrop` because it is important that the `TargetMachine`
374    // is disposed prior to the `Context` being disposed otherwise UAFs can occur.
375    tm: ManuallyDrop<OwnedTargetMachine>,
376}
377
378unsafe impl Send for ModuleLlvm {}
379unsafe impl Sync for ModuleLlvm {}
380
381impl ModuleLlvm {
382    fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
383        unsafe {
384            let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
385            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
386            ModuleLlvm {
387                llmod_raw,
388                llcx,
389                tm: ManuallyDrop::new(create_target_machine(tcx, mod_name)),
390            }
391        }
392    }
393
394    fn new_metadata(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 {
399                llmod_raw,
400                llcx,
401                tm: ManuallyDrop::new(create_informational_target_machine(tcx.sess, false)),
402            }
403        }
404    }
405
406    fn tm_from_cgcx(
407        cgcx: &CodegenContext<LlvmCodegenBackend>,
408        name: &str,
409        dcx: DiagCtxtHandle<'_>,
410    ) -> Result<OwnedTargetMachine, FatalError> {
411        let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name);
412        match (cgcx.tm_factory)(tm_factory_config) {
413            Ok(m) => Ok(m),
414            Err(e) => {
415                return Err(dcx.emit_almost_fatal(ParseTargetMachineConfig(e)));
416            }
417        }
418    }
419
420    fn parse(
421        cgcx: &CodegenContext<LlvmCodegenBackend>,
422        name: &CStr,
423        buffer: &[u8],
424        dcx: DiagCtxtHandle<'_>,
425    ) -> Result<Self, FatalError> {
426        unsafe {
427            let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
428            let llmod_raw = back::lto::parse_module(llcx, name, buffer, dcx)?;
429            let tm = ModuleLlvm::tm_from_cgcx(cgcx, name.to_str().unwrap(), dcx)?;
430
431            Ok(ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) })
432        }
433    }
434
435    fn llmod(&self) -> &llvm::Module {
436        unsafe { &*self.llmod_raw }
437    }
438}
439
440impl Drop for ModuleLlvm {
441    fn drop(&mut self) {
442        unsafe {
443            ManuallyDrop::drop(&mut self.tm);
444            llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
445        }
446    }
447}