Skip to main content

rustc_codegen_llvm/back/
llvm_backend.rs

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