Skip to main content

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#![feature(extern_types)]
9#![feature(file_buffered)]
10#![feature(impl_trait_in_assoc_type)]
11#![feature(iter_intersperse)]
12#![feature(macro_derive)]
13#![feature(once_cell_try)]
14#![feature(trim_prefix_suffix)]
15#![feature(try_blocks)]
16// tidy-alphabetical-end
17
18use std::any::Any;
19use std::ffi::CStr;
20use std::mem::ManuallyDrop;
21use std::path::PathBuf;
22
23use back::owned_target_machine::OwnedTargetMachine;
24use back::write::{create_informational_target_machine, create_target_machine};
25use context::SimpleCx;
26use llvm_util::target_config;
27use rustc_ast::expand::allocator::AllocatorMethod;
28use rustc_codegen_ssa::back::lto::ThinModule;
29use rustc_codegen_ssa::back::write::{
30    CodegenContext, FatLtoInput, ModuleConfig, SharedEmitter, TargetMachineFactoryConfig,
31    TargetMachineFactoryFn, ThinLtoInput,
32};
33use rustc_codegen_ssa::traits::*;
34use rustc_codegen_ssa::{CompiledModule, CompiledModules, CrateInfo, ModuleCodegen, TargetConfig};
35use rustc_data_structures::profiling::SelfProfilerRef;
36use rustc_errors::{DiagCtxt, DiagCtxtHandle};
37use rustc_metadata::EncodedMetadata;
38use rustc_middle::dep_graph::{WorkProduct, WorkProductMap};
39use rustc_middle::ty::TyCtxt;
40use rustc_middle::util::Providers;
41use rustc_session::Session;
42use rustc_session::config::{OptLevel, OutputFilenames, PrintKind, PrintRequest};
43use rustc_span::{Symbol, sym};
44use rustc_target::spec::{RelocModel, TlsModel};
45
46use crate::llvm::ToLlvmBool;
47
48mod abi;
49mod allocator;
50mod asm;
51mod attributes;
52mod back;
53mod base;
54mod builder;
55mod callee;
56mod common;
57mod consts;
58mod context;
59mod coverageinfo;
60mod debuginfo;
61mod declare;
62mod errors;
63mod intrinsic;
64mod llvm;
65mod llvm_util;
66mod macros;
67mod mono_item;
68mod type_;
69mod type_of;
70mod typetree;
71mod va_arg;
72mod value;
73
74pub(crate) use macros::TryFromU32;
75
76#[derive(#[automatically_derived]
impl ::core::clone::Clone for LlvmCodegenBackend {
    #[inline]
    fn clone(&self) -> LlvmCodegenBackend {
        LlvmCodegenBackend(::core::clone::Clone::clone(&self.0))
    }
}Clone)]
77pub struct LlvmCodegenBackend(());
78
79struct TimeTraceProfiler {}
80
81impl TimeTraceProfiler {
82    fn new() -> Self {
83        unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() }
84        TimeTraceProfiler {}
85    }
86}
87
88impl Drop for TimeTraceProfiler {
89    fn drop(&mut self) {
90        unsafe { llvm::LLVMRustTimeTraceProfilerFinishThread() }
91    }
92}
93
94impl ExtraBackendMethods for LlvmCodegenBackend {
95    type Module = ModuleLlvm;
96
97    fn codegen_allocator<'tcx>(
98        &self,
99        tcx: TyCtxt<'tcx>,
100        module_name: &str,
101        methods: &[AllocatorMethod],
102    ) -> ModuleLlvm {
103        let module_llvm = ModuleLlvm::new_metadata(tcx, module_name);
104        let cx =
105            SimpleCx::new(module_llvm.llmod(), &module_llvm.llcx, tcx.data_layout.pointer_size());
106        unsafe {
107            allocator::codegen(tcx, cx, module_name, methods);
108        }
109        module_llvm
110    }
111    fn compile_codegen_unit(
112        &self,
113        tcx: TyCtxt<'_>,
114        cgu_name: Symbol,
115    ) -> (ModuleCodegen<ModuleLlvm>, u64) {
116        base::compile_codegen_unit(tcx, cgu_name)
117    }
118}
119
120impl WriteBackendMethods for LlvmCodegenBackend {
121    type Module = ModuleLlvm;
122    type ModuleBuffer = back::lto::ModuleBuffer;
123    type TargetMachine = OwnedTargetMachine;
124    type ThinData = back::lto::ThinData;
125
126    fn thread_profiler() -> Box<dyn Any> {
127        Box::new(TimeTraceProfiler::new())
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    fn optimize_and_codegen_fat_lto(
138        sess: &Session,
139        cgcx: &CodegenContext,
140        shared_emitter: &SharedEmitter,
141        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
142        exported_symbols_for_lto: &[String],
143        each_linked_rlib_for_lto: &[PathBuf],
144        modules: Vec<FatLtoInput<Self>>,
145    ) -> CompiledModule {
146        let mut module = back::lto::run_fat(
147            cgcx,
148            &sess.prof,
149            shared_emitter,
150            tm_factory,
151            exported_symbols_for_lto,
152            each_linked_rlib_for_lto,
153            modules,
154        );
155
156        let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
157        let dcx = dcx.handle();
158        back::lto::run_pass_manager(cgcx, &sess.prof, dcx, &mut module, false);
159
160        back::write::codegen(cgcx, &sess.prof, shared_emitter, module, &cgcx.module_config)
161    }
162    fn run_thin_lto(
163        cgcx: &CodegenContext,
164        prof: &SelfProfilerRef,
165        dcx: DiagCtxtHandle<'_>,
166        exported_symbols_for_lto: &[String],
167        each_linked_rlib_for_lto: &[PathBuf],
168        modules: Vec<ThinLtoInput<Self>>,
169    ) -> (Vec<ThinModule<Self>>, Vec<WorkProduct>) {
170        back::lto::run_thin(
171            cgcx,
172            prof,
173            dcx,
174            exported_symbols_for_lto,
175            each_linked_rlib_for_lto,
176            modules,
177        )
178    }
179    fn optimize(
180        cgcx: &CodegenContext,
181        prof: &SelfProfilerRef,
182        shared_emitter: &SharedEmitter,
183        module: &mut ModuleCodegen<Self::Module>,
184        config: &ModuleConfig,
185    ) {
186        back::write::optimize(cgcx, prof, shared_emitter, module, config)
187    }
188    fn optimize_and_codegen_thin(
189        cgcx: &CodegenContext,
190        prof: &SelfProfilerRef,
191        shared_emitter: &SharedEmitter,
192        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
193        thin: ThinModule<Self>,
194    ) -> CompiledModule {
195        back::lto::optimize_and_codegen_thin_module(cgcx, prof, shared_emitter, tm_factory, thin)
196    }
197    fn codegen(
198        cgcx: &CodegenContext,
199        prof: &SelfProfilerRef,
200        shared_emitter: &SharedEmitter,
201        module: ModuleCodegen<Self::Module>,
202        config: &ModuleConfig,
203    ) -> CompiledModule {
204        back::write::codegen(cgcx, prof, shared_emitter, module, config)
205    }
206    fn serialize_module(module: Self::Module, is_thin: bool) -> Self::ModuleBuffer {
207        back::lto::ModuleBuffer::new(module.llmod(), is_thin)
208    }
209}
210
211impl LlvmCodegenBackend {
212    pub fn new() -> Box<dyn CodegenBackend> {
213        Box::new(LlvmCodegenBackend(()))
214    }
215}
216
217impl CodegenBackend for LlvmCodegenBackend {
218    fn name(&self) -> &'static str {
219        "llvm"
220    }
221
222    fn init(&self, sess: &Session) {
223        llvm_util::init(sess); // Make sure llvm is inited
224
225        // autodiff is based on Enzyme, a library which we might not have available, when it was
226        // neither build, nor downloaded via rustup. If autodiff is used, but not available we emit
227        // an early error here and abort compilation.
228        {
229            use rustc_session::config::AutoDiff;
230
231            use crate::back::lto::enable_autodiff_settings;
232            if sess.opts.unstable_opts.autodiff.contains(&AutoDiff::Enable) {
233                match llvm::EnzymeWrapper::get_or_init(&sess.opts.sysroot) {
234                    Ok(_) => {}
235                    Err(llvm::EnzymeLibraryError::NotFound { err }) => {
236                        sess.dcx().emit_fatal(crate::errors::AutoDiffComponentMissing { err });
237                    }
238                    Err(llvm::EnzymeLibraryError::LoadFailed { err }) => {
239                        sess.dcx().emit_fatal(crate::errors::AutoDiffComponentUnavailable { err });
240                    }
241                }
242                enable_autodiff_settings(&sess.opts.unstable_opts.autodiff);
243            }
244        }
245    }
246
247    fn provide(&self, providers: &mut Providers) {
248        providers.queries.global_backend_features =
249            |tcx, ()| llvm_util::global_llvm_features(tcx.sess, 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                out.write_fmt(format_args!("Available relocation models:\n"))writeln!(out, "Available relocation models:").unwrap();
257                for name in RelocModel::ALL.iter().map(RelocModel::desc).chain(["default"]) {
258                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
259                }
260                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
261            }
262            PrintKind::CodeModels => {
263                out.write_fmt(format_args!("Available code models:\n"))writeln!(out, "Available code models:").unwrap();
264                for name in &["tiny", "small", "kernel", "medium", "large"] {
265                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
266                }
267                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
268            }
269            PrintKind::TlsModels => {
270                out.write_fmt(format_args!("Available TLS models:\n"))writeln!(out, "Available TLS models:").unwrap();
271                for name in TlsModel::ALL.iter().map(TlsModel::desc) {
272                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
273                }
274                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
275            }
276            PrintKind::StackProtectorStrategies => {
277                out.write_fmt(format_args!("Available stack protector strategies:\n    all\n        Generate stack canaries in all functions.\n\n    strong\n        Generate stack canaries in a function if it either:\n        - has a local variable of `[T; N]` type, regardless of `T` and `N`\n        - takes the address of a local variable.\n\n          (Note that a local variable being borrowed is not equivalent to its\n          address being taken: e.g. some borrows may be removed by optimization,\n          while by-value argument passing may be implemented with reference to a\n          local stack variable in the ABI.)\n\n    basic\n        Generate stack canaries in functions with local variables of `[T; N]`\n        type, where `T` is byte-sized and `N` >= 8.\n\n    none\n        Do not generate stack canaries.\n\n"))writeln!(
278                    out,
279                    r#"Available stack protector strategies:
280    all
281        Generate stack canaries in all functions.
282
283    strong
284        Generate stack canaries in a function if it either:
285        - has a local variable of `[T; N]` type, regardless of `T` and `N`
286        - takes the address of a local variable.
287
288          (Note that a local variable being borrowed is not equivalent to its
289          address being taken: e.g. some borrows may be removed by optimization,
290          while by-value argument passing may be implemented with reference to a
291          local stack variable in the ABI.)
292
293    basic
294        Generate stack canaries in functions with local variables of `[T; N]`
295        type, where `T` is byte-sized and `N` >= 8.
296
297    none
298        Do not generate stack canaries.
299"#
300                )
301                .unwrap();
302            }
303            _other => llvm_util::print(req, out, sess),
304        }
305    }
306
307    fn print_passes(&self) {
308        llvm_util::print_passes();
309    }
310
311    fn print_version(&self) {
312        llvm_util::print_version();
313    }
314
315    fn has_zstd(&self) -> bool {
316        llvm::LLVMRustLLVMHasZstdCompression()
317    }
318
319    fn has_mnemonic(&self, sess: &Session, mnemonic: &str) -> bool {
320        llvm_util::target_has_mnemonic(sess, mnemonic)
321    }
322
323    fn target_config(&self, sess: &Session) -> TargetConfig {
324        target_config(sess)
325    }
326
327    /// Intrinsics whose fallback body will not be used by the LLVM backend.
328    fn replaced_intrinsics(&self) -> Vec<Symbol> {
329        #[rustfmt::skip]
330        let mut will_not_use_fallback = ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [sym::unchecked_funnel_shl, sym::unchecked_funnel_shr,
                sym::carrying_mul_add, sym::sinf16, sym::sinf32, sym::sinf64,
                sym::cosf16, sym::cosf32, sym::cosf64, sym::powf16,
                sym::powf32, sym::powf64, sym::expf16, sym::expf32,
                sym::expf64, sym::exp2f16, sym::exp2f32, sym::exp2f64,
                sym::logf16, sym::logf32, sym::logf64, sym::log10f16,
                sym::log10f32, sym::log10f64, sym::log2f16, sym::log2f32,
                sym::log2f64, sym::floorf16, sym::ceilf16, sym::truncf16,
                sym::round_ties_even_f16, sym::roundf16, sym::sqrtf16,
                sym::powif16, sym::fmaf16, sym::copysignf16, sym::copysignf32,
                sym::copysignf64, sym::copysignf128]))vec![
331            // These are mapped to LLVM intrinsics instead.
332            sym::unchecked_funnel_shl,
333            sym::unchecked_funnel_shr,
334            sym::carrying_mul_add,
335
336            // Fallback via libm, but the LLVM intrinsic is used instead.
337            sym::sinf16, sym::sinf32, sym::sinf64,
338            sym::cosf16, sym::cosf32, sym::cosf64,
339            sym::powf16, sym::powf32, sym::powf64,
340            sym::expf16, sym::expf32, sym::expf64,
341            sym::exp2f16, sym::exp2f32, sym::exp2f64,
342            sym::logf16, sym::logf32, sym::logf64,
343            sym::log10f16, sym::log10f32, sym::log10f64,
344            sym::log2f16, sym::log2f32, sym::log2f64,
345
346            // Fallback via f32 or f64, but the LLVM intrinsic is used instead.
347            sym::floorf16, sym::ceilf16, sym::truncf16,
348            sym::round_ties_even_f16, sym::roundf16,
349            sym::sqrtf16, sym::powif16,
350            sym::fmaf16,
351
352            sym::copysignf16, sym::copysignf32, sym::copysignf64, sym::copysignf128,
353        ];
354
355        if llvm_util::get_version() >= (22, 0, 0) {
356            will_not_use_fallback.push(sym::carryless_mul);
357        }
358
359        will_not_use_fallback
360    }
361
362    fn fallback_intrinsics(&self) -> Vec<Symbol> {
363        // `type_id_eq` is a safe choice since *all* backends use the fallback body for that.
364        // When adding more intrinsics, keep in mind that the distributed standard library
365        // is compiled with the LLVM backend but might later be included in a project built
366        // with cranelift or GCC.
367        ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [sym::type_id_eq]))vec![sym::type_id_eq]
368    }
369
370    fn target_cpu(&self, sess: &Session) -> String {
371        crate::llvm_util::target_cpu(sess).to_string()
372    }
373
374    fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
375        Box::new(rustc_codegen_ssa::base::codegen_crate(LlvmCodegenBackend(()), tcx))
376    }
377
378    fn join_codegen(
379        &self,
380        ongoing_codegen: Box<dyn Any>,
381        sess: &Session,
382        outputs: &OutputFilenames,
383        crate_info: &CrateInfo,
384    ) -> (CompiledModules, WorkProductMap) {
385        let (compiled_modules, work_products) = ongoing_codegen
386            .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
387            .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
388            .join(sess, crate_info);
389
390        if sess.opts.unstable_opts.llvm_time_trace {
391            sess.time("llvm_dump_timing_file", || {
392                let file_name = outputs.with_extension("llvm_timings.json");
393                llvm_util::time_trace_profiler_finish(&file_name);
394            });
395        }
396
397        (compiled_modules, work_products)
398    }
399
400    fn print_pass_timings(&self) {
401        let timings = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintPassTimings(s) }).unwrap();
402        { ::std::io::_print(format_args!("{0}", timings)); };print!("{timings}");
403    }
404
405    fn print_statistics(&self) {
406        let stats = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatistics(s) }).unwrap();
407        { ::std::io::_print(format_args!("{0}", stats)); };print!("{stats}");
408    }
409
410    fn print_statistics_json(&self) -> String {
411        llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatisticsJSON(s) }).unwrap()
412    }
413
414    fn link(
415        &self,
416        sess: &Session,
417        compiled_modules: CompiledModules,
418        crate_info: CrateInfo,
419        metadata: EncodedMetadata,
420        outputs: &OutputFilenames,
421    ) {
422        use rustc_codegen_ssa::back::link::link_binary;
423
424        use crate::back::archive::LlvmArchiveBuilderBuilder;
425
426        // Run the linker on any artifacts that resulted from the LLVM run.
427        // This should produce either a finished executable or library.
428        link_binary(
429            sess,
430            &LlvmArchiveBuilderBuilder,
431            compiled_modules,
432            crate_info,
433            metadata,
434            outputs,
435            self.name(),
436        );
437    }
438}
439
440pub struct ModuleLlvm {
441    llcx: &'static mut llvm::Context,
442    llmod_raw: *const llvm::Module,
443
444    // This field is `ManuallyDrop` because it is important that the `TargetMachine`
445    // is disposed prior to the `Context` being disposed otherwise UAFs can occur.
446    tm: ManuallyDrop<OwnedTargetMachine>,
447}
448
449unsafe impl Send for ModuleLlvm {}
450unsafe impl Sync for ModuleLlvm {}
451
452impl ModuleLlvm {
453    fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
454        unsafe {
455            let llcx = llvm::LLVMContextCreate();
456            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
457            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
458            ModuleLlvm {
459                llmod_raw,
460                llcx,
461                tm: ManuallyDrop::new(create_target_machine(tcx, mod_name)),
462            }
463        }
464    }
465
466    fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
467        unsafe {
468            let llcx = llvm::LLVMContextCreate();
469            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
470            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
471            ModuleLlvm {
472                llmod_raw,
473                llcx,
474                tm: ManuallyDrop::new(create_informational_target_machine(tcx.sess, false)),
475            }
476        }
477    }
478
479    fn parse(
480        cgcx: &CodegenContext,
481        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
482        name: &CStr,
483        buffer: &[u8],
484        dcx: DiagCtxtHandle<'_>,
485    ) -> Self {
486        unsafe {
487            let llcx = llvm::LLVMContextCreate();
488            llvm::LLVMContextSetDiscardValueNames(llcx, cgcx.fewer_names.to_llvm_bool());
489            let llmod_raw = back::lto::parse_module(llcx, name, buffer, dcx);
490            let tm = tm_factory(dcx, TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap()));
491
492            ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) }
493        }
494    }
495
496    fn llmod(&self) -> &llvm::Module {
497        unsafe { &*self.llmod_raw }
498    }
499}
500
501impl Drop for ModuleLlvm {
502    fn drop(&mut self) {
503        unsafe {
504            ManuallyDrop::drop(&mut self.tm);
505            llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
506        }
507    }
508}