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(macro_derive)]
18#![feature(rustdoc_internals)]
19#![feature(slice_as_array)]
20#![feature(try_blocks)]
21// tidy-alphabetical-end
22
23use std::any::Any;
24use std::ffi::CStr;
25use std::mem::ManuallyDrop;
26use std::path::PathBuf;
27
28use back::owned_target_machine::OwnedTargetMachine;
29use back::write::{create_informational_target_machine, create_target_machine};
30use context::SimpleCx;
31use errors::ParseTargetMachineConfig;
32use llvm_util::target_config;
33use rustc_ast::expand::allocator::AllocatorMethod;
34use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule};
35use rustc_codegen_ssa::back::write::{
36    CodegenContext, FatLtoInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
37};
38use rustc_codegen_ssa::traits::*;
39use rustc_codegen_ssa::{CodegenResults, CompiledModule, ModuleCodegen, TargetConfig};
40use rustc_data_structures::fx::FxIndexMap;
41use rustc_errors::DiagCtxtHandle;
42use rustc_metadata::EncodedMetadata;
43use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
44use rustc_middle::ty::TyCtxt;
45use rustc_middle::util::Providers;
46use rustc_session::Session;
47use rustc_session::config::{OptLevel, OutputFilenames, PrintKind, PrintRequest};
48use rustc_span::Symbol;
49use rustc_target::spec::{RelocModel, TlsModel};
50
51use crate::llvm::ToLlvmBool;
52
53mod abi;
54mod allocator;
55mod asm;
56mod attributes;
57mod back;
58mod base;
59mod builder;
60mod callee;
61mod common;
62mod consts;
63mod context;
64mod coverageinfo;
65mod debuginfo;
66mod declare;
67mod errors;
68mod intrinsic;
69mod llvm;
70mod llvm_util;
71mod macros;
72mod mono_item;
73mod type_;
74mod type_of;
75mod typetree;
76mod va_arg;
77mod value;
78
79rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
80
81pub(crate) use macros::TryFromU32;
82
83#[derive(Clone)]
84pub struct LlvmCodegenBackend(());
85
86struct TimeTraceProfiler {
87    enabled: bool,
88}
89
90impl TimeTraceProfiler {
91    fn new(enabled: bool) -> Self {
92        if enabled {
93            unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() }
94        }
95        TimeTraceProfiler { enabled }
96    }
97}
98
99impl Drop for TimeTraceProfiler {
100    fn drop(&mut self) {
101        if self.enabled {
102            unsafe { llvm::LLVMRustTimeTraceProfilerFinishThread() }
103        }
104    }
105}
106
107impl ExtraBackendMethods for LlvmCodegenBackend {
108    fn codegen_allocator<'tcx>(
109        &self,
110        tcx: TyCtxt<'tcx>,
111        module_name: &str,
112        methods: &[AllocatorMethod],
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, methods);
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    ) -> ModuleCodegen<Self::Module> {
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        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    ) -> (Vec<ThinModule<Self>>, Vec<WorkProduct>) {
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    ) {
206        back::write::optimize(cgcx, dcx, module, config)
207    }
208    fn optimize_thin(
209        cgcx: &CodegenContext<Self>,
210        thin: ThinModule<Self>,
211    ) -> ModuleCodegen<Self::Module> {
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    ) -> CompiledModule {
219        back::write::codegen(cgcx, module, config)
220    }
221    fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
222        back::lto::prepare_thin(module)
223    }
224    fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
225        (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
226    }
227}
228
229impl LlvmCodegenBackend {
230    pub fn new() -> Box<dyn CodegenBackend> {
231        Box::new(LlvmCodegenBackend(()))
232    }
233}
234
235impl CodegenBackend for LlvmCodegenBackend {
236    fn locale_resource(&self) -> &'static str {
237        crate::DEFAULT_LOCALE_RESOURCE
238    }
239
240    fn name(&self) -> &'static str {
241        "llvm"
242    }
243
244    fn init(&self, sess: &Session) {
245        llvm_util::init(sess); // Make sure llvm is inited
246    }
247
248    fn provide(&self, providers: &mut Providers) {
249        providers.global_backend_features =
250            |tcx, ()| llvm_util::global_llvm_features(tcx.sess, true, false)
251    }
252
253    fn print(&self, req: &PrintRequest, out: &mut String, sess: &Session) {
254        use std::fmt::Write;
255        match req.kind {
256            PrintKind::RelocationModels => {
257                writeln!(out, "Available relocation models:").unwrap();
258                for name in RelocModel::ALL.iter().map(RelocModel::desc).chain(["default"]) {
259                    writeln!(out, "    {name}").unwrap();
260                }
261                writeln!(out).unwrap();
262            }
263            PrintKind::CodeModels => {
264                writeln!(out, "Available code models:").unwrap();
265                for name in &["tiny", "small", "kernel", "medium", "large"] {
266                    writeln!(out, "    {name}").unwrap();
267                }
268                writeln!(out).unwrap();
269            }
270            PrintKind::TlsModels => {
271                writeln!(out, "Available TLS models:").unwrap();
272                for name in TlsModel::ALL.iter().map(TlsModel::desc) {
273                    writeln!(out, "    {name}").unwrap();
274                }
275                writeln!(out).unwrap();
276            }
277            PrintKind::StackProtectorStrategies => {
278                writeln!(
279                    out,
280                    r#"Available stack protector strategies:
281    all
282        Generate stack canaries in all functions.
283
284    strong
285        Generate stack canaries in a function if it either:
286        - has a local variable of `[T; N]` type, regardless of `T` and `N`
287        - takes the address of a local variable.
288
289          (Note that a local variable being borrowed is not equivalent to its
290          address being taken: e.g. some borrows may be removed by optimization,
291          while by-value argument passing may be implemented with reference to a
292          local stack variable in the ABI.)
293
294    basic
295        Generate stack canaries in functions with local variables of `[T; N]`
296        type, where `T` is byte-sized and `N` >= 8.
297
298    none
299        Do not generate stack canaries.
300"#
301                )
302                .unwrap();
303            }
304            _other => llvm_util::print(req, out, sess),
305        }
306    }
307
308    fn print_passes(&self) {
309        llvm_util::print_passes();
310    }
311
312    fn print_version(&self) {
313        llvm_util::print_version();
314    }
315
316    fn target_config(&self, sess: &Session) -> TargetConfig {
317        target_config(sess)
318    }
319
320    fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
321        Box::new(rustc_codegen_ssa::base::codegen_crate(
322            LlvmCodegenBackend(()),
323            tcx,
324            crate::llvm_util::target_cpu(tcx.sess).to_string(),
325        ))
326    }
327
328    fn join_codegen(
329        &self,
330        ongoing_codegen: Box<dyn Any>,
331        sess: &Session,
332        outputs: &OutputFilenames,
333    ) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
334        let (codegen_results, work_products) = ongoing_codegen
335            .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
336            .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
337            .join(sess);
338
339        if sess.opts.unstable_opts.llvm_time_trace {
340            sess.time("llvm_dump_timing_file", || {
341                let file_name = outputs.with_extension("llvm_timings.json");
342                llvm_util::time_trace_profiler_finish(&file_name);
343            });
344        }
345
346        (codegen_results, work_products)
347    }
348
349    fn link(
350        &self,
351        sess: &Session,
352        codegen_results: CodegenResults,
353        metadata: EncodedMetadata,
354        outputs: &OutputFilenames,
355    ) {
356        use rustc_codegen_ssa::back::link::link_binary;
357
358        use crate::back::archive::LlvmArchiveBuilderBuilder;
359
360        // Run the linker on any artifacts that resulted from the LLVM run.
361        // This should produce either a finished executable or library.
362        link_binary(
363            sess,
364            &LlvmArchiveBuilderBuilder,
365            codegen_results,
366            metadata,
367            outputs,
368            self.name(),
369        );
370    }
371}
372
373pub struct ModuleLlvm {
374    llcx: &'static mut llvm::Context,
375    llmod_raw: *const llvm::Module,
376
377    // This field is `ManuallyDrop` because it is important that the `TargetMachine`
378    // is disposed prior to the `Context` being disposed otherwise UAFs can occur.
379    tm: ManuallyDrop<OwnedTargetMachine>,
380}
381
382unsafe impl Send for ModuleLlvm {}
383unsafe impl Sync for ModuleLlvm {}
384
385impl ModuleLlvm {
386    fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
387        unsafe {
388            let llcx = llvm::LLVMContextCreate();
389            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
390            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
391            ModuleLlvm {
392                llmod_raw,
393                llcx,
394                tm: ManuallyDrop::new(create_target_machine(tcx, mod_name)),
395            }
396        }
397    }
398
399    fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
400        unsafe {
401            let llcx = llvm::LLVMContextCreate();
402            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
403            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
404            ModuleLlvm {
405                llmod_raw,
406                llcx,
407                tm: ManuallyDrop::new(create_informational_target_machine(tcx.sess, false)),
408            }
409        }
410    }
411
412    fn tm_from_cgcx(
413        cgcx: &CodegenContext<LlvmCodegenBackend>,
414        name: &str,
415        dcx: DiagCtxtHandle<'_>,
416    ) -> OwnedTargetMachine {
417        let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name);
418        match (cgcx.tm_factory)(tm_factory_config) {
419            Ok(m) => m,
420            Err(e) => {
421                dcx.emit_fatal(ParseTargetMachineConfig(e));
422            }
423        }
424    }
425
426    fn parse(
427        cgcx: &CodegenContext<LlvmCodegenBackend>,
428        name: &CStr,
429        buffer: &[u8],
430        dcx: DiagCtxtHandle<'_>,
431    ) -> Self {
432        unsafe {
433            let llcx = llvm::LLVMContextCreate();
434            llvm::LLVMContextSetDiscardValueNames(llcx, cgcx.fewer_names.to_llvm_bool());
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            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}