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 diagnostics;
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::diagnostics::AutoDiffComponentMissing { err });
237                    }
238                    Err(llvm::EnzymeLibraryError::LoadFailed { err }) => {
239                        sess.dcx()
240                            .emit_fatal(crate::diagnostics::AutoDiffComponentUnavailable { err });
241                    }
242                }
243                enable_autodiff_settings(&sess.opts.unstable_opts.autodiff);
244            }
245        }
246    }
247
248    fn provide(&self, providers: &mut Providers) {
249        providers.queries.global_backend_features =
250            |tcx, ()| llvm_util::global_llvm_features(tcx.sess, 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                out.write_fmt(format_args!("Available relocation models:\n"))writeln!(out, "Available relocation models:").unwrap();
258                for name in RelocModel::ALL.iter().map(RelocModel::desc).chain(["default"]) {
259                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
260                }
261                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
262            }
263            PrintKind::CodeModels => {
264                out.write_fmt(format_args!("Available code models:\n"))writeln!(out, "Available code models:").unwrap();
265                for name in &["tiny", "small", "kernel", "medium", "large"] {
266                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
267                }
268                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
269            }
270            PrintKind::TlsModels => {
271                out.write_fmt(format_args!("Available TLS models:\n"))writeln!(out, "Available TLS models:").unwrap();
272                for name in TlsModel::ALL.iter().map(TlsModel::desc) {
273                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
274                }
275                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
276            }
277            PrintKind::StackProtectorStrategies => {
278                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!(
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 has_zstd(&self) -> bool {
317        llvm::LLVMRustLLVMHasZstdCompression()
318    }
319
320    fn has_mnemonic(&self, sess: &Session, mnemonic: &str) -> bool {
321        llvm_util::target_has_mnemonic(sess, mnemonic)
322    }
323
324    fn target_config(&self, sess: &Session) -> TargetConfig {
325        target_config(sess)
326    }
327
328    /// Intrinsics whose fallback body will not be used by the LLVM backend.
329    fn replaced_intrinsics(&self) -> Vec<Symbol> {
330        #[rustfmt::skip]
331        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![
332            // These are mapped to LLVM intrinsics instead.
333            sym::unchecked_funnel_shl,
334            sym::unchecked_funnel_shr,
335            sym::carrying_mul_add,
336
337            // Fallback via libm, but the LLVM intrinsic is used instead.
338            sym::sinf16, sym::sinf32, sym::sinf64,
339            sym::cosf16, sym::cosf32, sym::cosf64,
340            sym::powf16, sym::powf32, sym::powf64,
341            sym::expf16, sym::expf32, sym::expf64,
342            sym::exp2f16, sym::exp2f32, sym::exp2f64,
343            sym::logf16, sym::logf32, sym::logf64,
344            sym::log10f16, sym::log10f32, sym::log10f64,
345            sym::log2f16, sym::log2f32, sym::log2f64,
346
347            // Fallback via f32 or f64, but the LLVM intrinsic is used instead.
348            sym::floorf16, sym::ceilf16, sym::truncf16,
349            sym::round_ties_even_f16, sym::roundf16,
350            sym::sqrtf16, sym::powif16,
351            sym::fmaf16,
352
353            sym::copysignf16, sym::copysignf32, sym::copysignf64, sym::copysignf128,
354        ];
355
356        if llvm_util::get_version() >= (22, 0, 0) {
357            will_not_use_fallback.push(sym::carryless_mul);
358        }
359
360        will_not_use_fallback
361    }
362
363    fn fallback_intrinsics(&self) -> Vec<Symbol> {
364        // `type_id_eq` is a safe choice since *all* backends use the fallback body for that.
365        // When adding more intrinsics, keep in mind that the distributed standard library
366        // is compiled with the LLVM backend but might later be included in a project built
367        // with cranelift or GCC.
368        ::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]
369    }
370
371    fn target_cpu(&self, sess: &Session) -> String {
372        crate::llvm_util::target_cpu(sess).to_string()
373    }
374
375    fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
376        Box::new(rustc_codegen_ssa::base::codegen_crate(LlvmCodegenBackend(()), tcx))
377    }
378
379    fn join_codegen(
380        &self,
381        ongoing_codegen: Box<dyn Any>,
382        sess: &Session,
383        outputs: &OutputFilenames,
384        crate_info: &CrateInfo,
385    ) -> (CompiledModules, WorkProductMap) {
386        let (compiled_modules, work_products) = ongoing_codegen
387            .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
388            .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
389            .join(sess, crate_info);
390
391        if sess.opts.unstable_opts.llvm_time_trace {
392            sess.time("llvm_dump_timing_file", || {
393                let file_name = outputs.with_extension("llvm_timings.json");
394                llvm_util::time_trace_profiler_finish(&file_name);
395            });
396        }
397
398        (compiled_modules, work_products)
399    }
400
401    fn print_pass_timings(&self) {
402        let timings = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintPassTimings(s) }).unwrap();
403        { ::std::io::_print(format_args!("{0}", timings)); };print!("{timings}");
404    }
405
406    fn print_statistics(&self) {
407        let stats = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatistics(s) }).unwrap();
408        { ::std::io::_print(format_args!("{0}", stats)); };print!("{stats}");
409    }
410
411    fn print_statistics_json(&self) -> String {
412        llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatisticsJSON(s) }).unwrap()
413    }
414
415    fn link(
416        &self,
417        sess: &Session,
418        compiled_modules: CompiledModules,
419        crate_info: CrateInfo,
420        metadata: EncodedMetadata,
421        outputs: &OutputFilenames,
422    ) {
423        use rustc_codegen_ssa::back::link::link_binary;
424
425        use crate::back::archive::LlvmArchiveBuilderBuilder;
426
427        // Run the linker on any artifacts that resulted from the LLVM run.
428        // This should produce either a finished executable or library.
429        link_binary(
430            sess,
431            &LlvmArchiveBuilderBuilder,
432            compiled_modules,
433            crate_info,
434            metadata,
435            outputs,
436            self.name(),
437        );
438    }
439}
440
441pub struct ModuleLlvm {
442    llcx: &'static mut llvm::Context,
443    llmod_raw: *const llvm::Module,
444
445    // This field is `ManuallyDrop` because it is important that the `TargetMachine`
446    // is disposed prior to the `Context` being disposed otherwise UAFs can occur.
447    tm: ManuallyDrop<OwnedTargetMachine>,
448}
449
450unsafe impl Send for ModuleLlvm {}
451unsafe impl Sync for ModuleLlvm {}
452
453impl ModuleLlvm {
454    fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
455        unsafe {
456            let llcx = llvm::LLVMContextCreate();
457            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
458            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
459            ModuleLlvm {
460                llmod_raw,
461                llcx,
462                tm: ManuallyDrop::new(create_target_machine(tcx, mod_name)),
463            }
464        }
465    }
466
467    fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
468        unsafe {
469            let llcx = llvm::LLVMContextCreate();
470            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
471            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
472            ModuleLlvm {
473                llmod_raw,
474                llcx,
475                tm: ManuallyDrop::new(create_informational_target_machine(tcx.sess, false)),
476            }
477        }
478    }
479
480    fn parse(
481        cgcx: &CodegenContext,
482        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
483        name: &CStr,
484        buffer: &[u8],
485        dcx: DiagCtxtHandle<'_>,
486    ) -> Self {
487        unsafe {
488            let llcx = llvm::LLVMContextCreate();
489            llvm::LLVMContextSetDiscardValueNames(llcx, cgcx.fewer_names.to_llvm_bool());
490            let llmod_raw = back::lto::parse_module(llcx, name, buffer, dcx);
491            let tm = tm_factory(dcx, TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap()));
492
493            ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) }
494        }
495    }
496
497    fn llmod(&self) -> &llvm::Module {
498        unsafe { &*self.llmod_raw }
499    }
500}
501
502impl Drop for ModuleLlvm {
503    fn drop(&mut self) {
504        unsafe {
505            ManuallyDrop::drop(&mut self.tm);
506            llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
507        }
508    }
509}