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::config::{OptLevel, OutputFilenames, PrintKind, PrintRequest};
42use rustc_session::{IncrCompSession, Session};
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        bitcode_needed: bool,
116    ) -> (ModuleCodegen<ModuleLlvm>, u64) {
117        base::compile_codegen_unit(tcx, cgu_name, bitcode_needed)
118    }
119}
120
121impl WriteBackendMethods for LlvmCodegenBackend {
122    type Module = ModuleLlvm;
123    type ModuleBuffer = back::lto::ModuleBuffer;
124    type TargetMachine = OwnedTargetMachine;
125    type ThinData = back::lto::ThinData;
126
127    fn thread_profiler() -> Box<dyn Any> {
128        Box::new(TimeTraceProfiler::new())
129    }
130    fn target_machine_factory(
131        &self,
132        sess: &Session,
133        optlvl: OptLevel,
134        target_features: &[String],
135    ) -> TargetMachineFactoryFn<Self> {
136        back::write::target_machine_factory(sess, optlvl, target_features)
137    }
138    fn optimize_and_codegen_fat_lto(
139        sess: &Session,
140        cgcx: &CodegenContext,
141        shared_emitter: &SharedEmitter,
142        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
143        exported_symbols_for_lto: &[String],
144        each_linked_rlib_for_lto: &[PathBuf],
145        modules: Vec<FatLtoInput<Self>>,
146    ) -> CompiledModule {
147        let mut module = back::lto::run_fat(
148            cgcx,
149            &sess.prof,
150            shared_emitter,
151            tm_factory,
152            exported_symbols_for_lto,
153            each_linked_rlib_for_lto,
154            modules,
155        );
156
157        let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
158        let dcx = dcx.handle();
159        back::lto::run_pass_manager(cgcx, &sess.prof, dcx, &mut module, false);
160
161        back::write::codegen(cgcx, &sess.prof, shared_emitter, module, &cgcx.module_config)
162    }
163    fn run_thin_lto(
164        cgcx: &CodegenContext,
165        prof: &SelfProfilerRef,
166        dcx: DiagCtxtHandle<'_>,
167        exported_symbols_for_lto: &[String],
168        each_linked_rlib_for_lto: &[PathBuf],
169        modules: Vec<ThinLtoInput<Self>>,
170    ) -> (Vec<ThinModule<Self>>, Vec<WorkProduct>) {
171        back::lto::run_thin(
172            cgcx,
173            prof,
174            dcx,
175            exported_symbols_for_lto,
176            each_linked_rlib_for_lto,
177            modules,
178        )
179    }
180    fn optimize(
181        cgcx: &CodegenContext,
182        prof: &SelfProfilerRef,
183        shared_emitter: &SharedEmitter,
184        module: &mut ModuleCodegen<Self::Module>,
185        config: &ModuleConfig,
186    ) {
187        back::write::optimize(cgcx, prof, shared_emitter, module, config)
188    }
189    fn optimize_and_codegen_thin(
190        cgcx: &CodegenContext,
191        prof: &SelfProfilerRef,
192        shared_emitter: &SharedEmitter,
193        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
194        thin: ThinModule<Self>,
195    ) -> CompiledModule {
196        back::lto::optimize_and_codegen_thin_module(cgcx, prof, shared_emitter, tm_factory, thin)
197    }
198    fn codegen(
199        cgcx: &CodegenContext,
200        prof: &SelfProfilerRef,
201        shared_emitter: &SharedEmitter,
202        module: ModuleCodegen<Self::Module>,
203        config: &ModuleConfig,
204    ) -> CompiledModule {
205        back::write::codegen(cgcx, prof, shared_emitter, module, config)
206    }
207    fn serialize_module(module: Self::Module, is_thin: bool) -> Self::ModuleBuffer {
208        back::lto::ModuleBuffer::new(module.llmod(), is_thin)
209    }
210}
211
212impl LlvmCodegenBackend {
213    pub fn new() -> Box<dyn CodegenBackend> {
214        Box::new(LlvmCodegenBackend(()))
215    }
216}
217
218impl CodegenBackend for LlvmCodegenBackend {
219    fn name(&self) -> &'static str {
220        "llvm"
221    }
222
223    fn init(&self, sess: &Session) {
224        llvm_util::init(sess); // Make sure llvm is inited
225
226        // autodiff is based on Enzyme, a library which we might not have available, when it was
227        // neither build, nor downloaded via rustup. If autodiff is used, but not available we emit
228        // an early error here and abort compilation.
229        {
230            use rustc_session::config::AutoDiff;
231
232            use crate::back::lto::enable_autodiff_settings;
233            if sess.opts.unstable_opts.autodiff.contains(&AutoDiff::Enable) {
234                match llvm::EnzymeWrapper::get_or_init(&sess.opts.sysroot) {
235                    Ok(_) => {}
236                    Err(llvm::EnzymeLibraryError::NotFound { err }) => {
237                        sess.dcx().emit_fatal(crate::diagnostics::AutoDiffComponentMissing { err });
238                    }
239                    Err(llvm::EnzymeLibraryError::LoadFailed { err }) => {
240                        sess.dcx()
241                            .emit_fatal(crate::diagnostics::AutoDiffComponentUnavailable { err });
242                    }
243                }
244                enable_autodiff_settings(&sess.opts.unstable_opts.autodiff);
245            }
246        }
247    }
248
249    fn provide(&self, providers: &mut Providers) {
250        providers.queries.global_backend_features =
251            |tcx, ()| llvm_util::global_llvm_features(tcx.sess, false)
252    }
253
254    fn print(&self, req: &PrintRequest, out: &mut String, sess: &Session) {
255        use std::fmt::Write;
256        match req.kind {
257            PrintKind::RelocationModels => {
258                out.write_fmt(format_args!("Available relocation models:\n"))writeln!(out, "Available relocation models:").unwrap();
259                for name in RelocModel::ALL.iter().map(RelocModel::desc).chain(["default"]) {
260                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
261                }
262                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
263            }
264            PrintKind::CodeModels => {
265                out.write_fmt(format_args!("Available code models:\n"))writeln!(out, "Available code models:").unwrap();
266                for name in &["tiny", "small", "kernel", "medium", "large"] {
267                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
268                }
269                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
270            }
271            PrintKind::TlsModels => {
272                out.write_fmt(format_args!("Available TLS models:\n"))writeln!(out, "Available TLS models:").unwrap();
273                for name in TlsModel::ALL.iter().map(TlsModel::desc) {
274                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
275                }
276                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
277            }
278            PrintKind::StackProtectorStrategies => {
279                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!(
280                    out,
281                    r#"Available stack protector strategies:
282    all
283        Generate stack canaries in all functions.
284
285    strong
286        Generate stack canaries in a function if it either:
287        - has a local variable of `[T; N]` type, regardless of `T` and `N`
288        - takes the address of a local variable.
289
290          (Note that a local variable being borrowed is not equivalent to its
291          address being taken: e.g. some borrows may be removed by optimization,
292          while by-value argument passing may be implemented with reference to a
293          local stack variable in the ABI.)
294
295    basic
296        Generate stack canaries in functions with local variables of `[T; N]`
297        type, where `T` is byte-sized and `N` >= 8.
298
299    none
300        Do not generate stack canaries.
301"#
302                )
303                .unwrap();
304            }
305            _other => llvm_util::print(req, out, sess),
306        }
307    }
308
309    fn print_passes(&self) {
310        llvm_util::print_passes();
311    }
312
313    fn print_version(&self) {
314        llvm_util::print_version();
315    }
316
317    fn has_zstd(&self) -> bool {
318        llvm::LLVMRustLLVMHasZstdCompression()
319    }
320
321    fn has_mnemonic(&self, sess: &Session, mnemonic: &str) -> bool {
322        llvm_util::target_has_mnemonic(sess, mnemonic)
323    }
324
325    fn target_config(&self, sess: &Session) -> TargetConfig {
326        target_config(sess)
327    }
328
329    /// Intrinsics whose fallback body will not be used by the LLVM backend.
330    fn replaced_intrinsics(&self) -> Vec<Symbol> {
331        #[rustfmt::skip]
332        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::integer_max, sym::integer_min,
                sym::sin, sym::cos, sym::powf16, sym::powf32, sym::powf64,
                sym::exp, sym::exp2, sym::log, sym::log10, sym::log2,
                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![
333            // These are mapped to LLVM intrinsics instead.
334            sym::unchecked_funnel_shl,
335            sym::unchecked_funnel_shr,
336            sym::carrying_mul_add,
337            sym::integer_max,
338            sym::integer_min,
339
340            // Fallback via libm, but the LLVM intrinsic is used instead.
341            sym::sin,
342            sym::cos,
343            sym::powf16, sym::powf32, sym::powf64,
344            sym::exp,
345            sym::exp2,
346            sym::log,
347            sym::log10,
348            sym::log2,
349
350            // Fallback via f32 or f64, but the LLVM intrinsic is used instead.
351            sym::floorf16, sym::ceilf16, sym::truncf16,
352            sym::round_ties_even_f16, sym::roundf16,
353            sym::sqrtf16, sym::powif16,
354            sym::fmaf16,
355
356            sym::copysignf16, sym::copysignf32, sym::copysignf64, sym::copysignf128,
357        ];
358
359        if llvm_util::get_version() >= (22, 0, 0) {
360            will_not_use_fallback.push(sym::carryless_mul);
361        }
362
363        will_not_use_fallback
364    }
365
366    fn fallback_intrinsics(&self) -> Vec<Symbol> {
367        // `type_id_eq` is a safe choice since *all* backends use the fallback body for that.
368        // When adding more intrinsics, keep in mind that the distributed standard library
369        // is compiled with the LLVM backend but might later be included in a project built
370        // with cranelift or GCC.
371        ::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]
372    }
373
374    fn target_cpu(&self, sess: &Session) -> String {
375        crate::llvm_util::target_cpu(sess).to_string()
376    }
377
378    fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
379        use rustc_session::config::Offload;
380
381        if tcx.sess.opts.unstable_opts.offload.iter().any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
    Offload::Device(_) => true,
    _ => false,
}matches!(o, Offload::Device(_)))
382            || tcx.sess.opts.unstable_opts.offload.iter().any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
    Offload::Host(_) => true,
    _ => false,
}matches!(o, Offload::Host(_)))
383        {
384            match llvm::RustOffloadWrapper::get_or_init(&tcx.sess.opts.sysroot) {
385                Ok(_) => {}
386                Err(llvm::RustOffloadLibraryError::NotFound { err }) => {
387                    tcx.sess
388                        .dcx()
389                        .emit_fatal(crate::diagnostics::RustOffloadComponentMissing { err });
390                }
391                Err(llvm::RustOffloadLibraryError::LoadFailed { err }) => {
392                    tcx.sess
393                        .dcx()
394                        .emit_fatal(crate::diagnostics::RustOffloadComponentUnavailable { err });
395                }
396            }
397        }
398
399        Box::new(rustc_codegen_ssa::base::codegen_crate(LlvmCodegenBackend(()), tcx))
400    }
401
402    fn join_codegen(
403        &self,
404        ongoing_codegen: Box<dyn Any>,
405        sess: &Session,
406        incr_comp_session: Option<&IncrCompSession>,
407        outputs: &OutputFilenames,
408        crate_info: &CrateInfo,
409    ) -> (CompiledModules, WorkProductMap) {
410        let (compiled_modules, work_products) = ongoing_codegen
411            .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
412            .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
413            .join(sess, incr_comp_session, crate_info);
414
415        if sess.opts.unstable_opts.llvm_time_trace {
416            sess.time("llvm_dump_timing_file", || {
417                let file_name = outputs.with_extension("llvm_timings.json");
418                llvm_util::time_trace_profiler_finish(&file_name);
419            });
420        }
421
422        (compiled_modules, work_products)
423    }
424
425    fn print_pass_timings(&self) {
426        let timings = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintPassTimings(s) }).unwrap();
427        { ::std::io::_print(format_args!("{0}", timings)); };print!("{timings}");
428    }
429
430    fn print_statistics(&self) {
431        let stats = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatistics(s) }).unwrap();
432        { ::std::io::_print(format_args!("{0}", stats)); };print!("{stats}");
433    }
434
435    fn print_statistics_json(&self) -> String {
436        llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatisticsJSON(s) }).unwrap()
437    }
438
439    fn link(
440        &self,
441        sess: &Session,
442        compiled_modules: CompiledModules,
443        crate_info: CrateInfo,
444        metadata: EncodedMetadata,
445        outputs: &OutputFilenames,
446    ) {
447        use rustc_codegen_ssa::back::link::link_binary;
448
449        use crate::back::archive::LlvmArchiveBuilderBuilder;
450
451        // Run the linker on any artifacts that resulted from the LLVM run.
452        // This should produce either a finished executable or library.
453        link_binary(
454            sess,
455            &LlvmArchiveBuilderBuilder,
456            compiled_modules,
457            crate_info,
458            metadata,
459            outputs,
460            self.name(),
461        );
462    }
463}
464
465pub struct ModuleLlvm {
466    llcx: &'static mut llvm::Context,
467    llmod_raw: *const llvm::Module,
468
469    // This field is `ManuallyDrop` because it is important that the `TargetMachine`
470    // is disposed prior to the `Context` being disposed otherwise UAFs can occur.
471    tm: ManuallyDrop<OwnedTargetMachine>,
472}
473
474unsafe impl Send for ModuleLlvm {}
475unsafe impl Sync for ModuleLlvm {}
476
477impl ModuleLlvm {
478    fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
479        unsafe {
480            let llcx = llvm::LLVMContextCreate();
481            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
482            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
483            ModuleLlvm {
484                llmod_raw,
485                llcx,
486                tm: ManuallyDrop::new(create_target_machine(tcx, mod_name)),
487            }
488        }
489    }
490
491    fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
492        unsafe {
493            let llcx = llvm::LLVMContextCreate();
494            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
495            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
496            ModuleLlvm {
497                llmod_raw,
498                llcx,
499                tm: ManuallyDrop::new(create_informational_target_machine(tcx.sess, false)),
500            }
501        }
502    }
503
504    fn parse(
505        cgcx: &CodegenContext,
506        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
507        name: &CStr,
508        buffer: &[u8],
509        dcx: DiagCtxtHandle<'_>,
510    ) -> Self {
511        unsafe {
512            let llcx = llvm::LLVMContextCreate();
513            llvm::LLVMContextSetDiscardValueNames(llcx, cgcx.fewer_names.to_llvm_bool());
514            let llmod_raw = back::lto::parse_module(llcx, name, buffer, dcx);
515            let tm = tm_factory(dcx, TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap()));
516
517            ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) }
518        }
519    }
520
521    fn llmod(&self) -> &llvm::Module {
522        unsafe { &*self.llmod_raw }
523    }
524}
525
526impl Drop for ModuleLlvm {
527    fn drop(&mut self) {
528        unsafe {
529            ManuallyDrop::drop(&mut self.tm);
530            llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
531        }
532    }
533}