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 { Self(::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 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::carryless_mul, 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::carryless_mul,
217                sym::integer_max,
218                sym::integer_min,
219
220                // Fallback via libm, but the LLVM intrinsic is used instead.
221                sym::sin,
222                sym::cos,
223                sym::powf16, sym::powf32, sym::powf64,
224                sym::exp,
225                sym::exp2,
226                sym::log,
227                sym::log10,
228                sym::log2,
229
230                // Fallback via f32 or f64, but the LLVM intrinsic is used instead.
231                sym::floorf16, sym::ceilf16, sym::truncf16,
232                sym::round_ties_even_f16, sym::roundf16,
233                sym::sqrtf16, sym::powif16,
234                sym::fmaf16,
235
236                sym::copysignf16, sym::copysignf32, sym::copysignf64, sym::copysignf128,
237            ];
238
239            will_not_use_fallback
240        };
241
242        // `type_id_eq` is a safe choice since *all* backends use the fallback body for that. When
243        // adding more intrinsics, keep in mind that the distributed standard library is compiled
244        // with the LLVM backend but might later be included in a project built with cranelift or
245        // GCC. Adding an intrinsic here can therefore mean the fallback body is used with
246        // cranelift/GCC even if they have dedicated implementations.
247        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];
248
249        CodegenBackendInit {
250            global_backend_features,
251            replaced_intrinsics,
252            fallback_intrinsics,
253            thin_lto_supported: true,
254        }
255    }
256
257    fn print(&self, req: &PrintRequest, out: &mut String, sess: &Session) {
258        use std::fmt::Write;
259        match req.kind {
260            PrintKind::RelocationModels => {
261                out.write_fmt(format_args!("Available relocation models:\n"))writeln!(out, "Available relocation models:").unwrap();
262                for name in RelocModel::ALL.iter().map(RelocModel::desc).chain(["default"]) {
263                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
264                }
265                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
266            }
267            PrintKind::CodeModels => {
268                out.write_fmt(format_args!("Available code models:\n"))writeln!(out, "Available code models:").unwrap();
269                for name in &["tiny", "small", "kernel", "medium", "large"] {
270                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
271                }
272                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
273            }
274            PrintKind::TlsModels => {
275                out.write_fmt(format_args!("Available TLS models:\n"))writeln!(out, "Available TLS models:").unwrap();
276                for name in TlsModel::ALL.iter().map(TlsModel::desc) {
277                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
278                }
279                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
280            }
281            PrintKind::StackProtectorStrategies => {
282                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!(
283                    out,
284                    r#"Available stack protector strategies:
285    all
286        Generate stack canaries in all functions.
287
288    strong
289        Generate stack canaries in a function if it either:
290        - has a local variable of `[T; N]` type, regardless of `T` and `N`
291        - takes the address of a local variable.
292
293          (Note that a local variable being borrowed is not equivalent to its
294          address being taken: e.g. some borrows may be removed by optimization,
295          while by-value argument passing may be implemented with reference to a
296          local stack variable in the ABI.)
297
298    basic
299        Generate stack canaries in functions with local variables of `[T; N]`
300        type, where `T` is byte-sized and `N` >= 8.
301
302    none
303        Do not generate stack canaries.
304"#
305                )
306                .unwrap();
307            }
308            _other => llvm_util::print(req, out, sess),
309        }
310    }
311
312    fn print_passes(&self) {
313        llvm_util::print_passes();
314    }
315
316    fn print_version(&self) {
317        llvm_util::print_version();
318    }
319
320    fn has_zstd(&self) -> bool {
321        llvm::LLVMRustLLVMHasZstdCompression()
322    }
323
324    fn has_mnemonic(&self, sess: &Session, mnemonic: &str) -> bool {
325        llvm_util::target_has_mnemonic(sess, mnemonic)
326    }
327
328    fn target_config(&self, sess: &EarlySession) -> TargetConfig {
329        target_config(sess)
330    }
331
332    fn target_cpu(&self, sess: &Session) -> String {
333        crate::llvm_util::target_cpu(sess).to_string()
334    }
335
336    fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
337        use rustc_session::config::Offload;
338
339        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(_)))
340            || tcx.sess.opts.unstable_opts.offload.iter().any(|o| #[allow(non_exhaustive_omitted_patterns)] match o {
    Offload::Host(_) => true,
    _ => false,
}matches!(o, Offload::Host(_)))
341        {
342            match llvm::RustOffloadWrapper::get_or_init(&tcx.sess.opts.sysroot) {
343                Ok(_) => {}
344                Err(llvm::RustOffloadLibraryError::NotFound { err }) => {
345                    tcx.sess
346                        .dcx()
347                        .emit_fatal(crate::diagnostics::RustOffloadComponentMissing { err });
348                }
349                Err(llvm::RustOffloadLibraryError::LoadFailed { err }) => {
350                    tcx.sess
351                        .dcx()
352                        .emit_fatal(crate::diagnostics::RustOffloadComponentUnavailable { err });
353                }
354            }
355        }
356
357        Box::new(rustc_codegen_ssa::base::codegen_crate(LlvmCodegenBackend(()), tcx))
358    }
359
360    fn join_codegen(
361        &self,
362        ongoing_codegen: Box<dyn Any>,
363        sess: &Session,
364        incr_comp_session: Option<&IncrCompSession>,
365        outputs: &OutputFilenames,
366        crate_info: &CrateInfo,
367    ) -> (CompiledModules, WorkProductMap) {
368        let (compiled_modules, work_products) = ongoing_codegen
369            .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
370            .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
371            .join(sess, incr_comp_session, crate_info);
372
373        if sess.opts.unstable_opts.llvm_time_trace {
374            sess.time("llvm_dump_timing_file", || {
375                let file_name = outputs.with_extension("llvm_timings.json");
376                llvm_util::time_trace_profiler_finish(&file_name);
377            });
378        }
379
380        (compiled_modules, work_products)
381    }
382
383    fn print_pass_timings(&self) {
384        let timings = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintPassTimings(s) }).unwrap();
385        { ::std::io::_print(format_args!("{0}", timings)); };print!("{timings}");
386    }
387
388    fn print_statistics(&self) {
389        let stats = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatistics(s) }).unwrap();
390        { ::std::io::_print(format_args!("{0}", stats)); };print!("{stats}");
391    }
392
393    fn print_statistics_json(&self) -> String {
394        llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatisticsJSON(s) }).unwrap()
395    }
396
397    fn link(
398        &self,
399        sess: &Session,
400        compiled_modules: CompiledModules,
401        crate_info: CrateInfo,
402        metadata: EncodedMetadata,
403        outputs: &OutputFilenames,
404    ) {
405        use rustc_codegen_ssa::back::link::link_binary;
406
407        use crate::back::archive::LlvmArchiveBuilderBuilder;
408
409        // Run the linker on any artifacts that resulted from the LLVM run.
410        // This should produce either a finished executable or library.
411        link_binary(
412            sess,
413            &LlvmArchiveBuilderBuilder,
414            compiled_modules,
415            crate_info,
416            metadata,
417            outputs,
418            self.name(),
419        );
420    }
421}
422
423pub struct ModuleLlvm {
424    pub(crate) llcx: &'static mut llvm::Context,
425    llmod_raw: *const llvm::Module,
426
427    // This field is `ManuallyDrop` because it is important that the `TargetMachine`
428    // is disposed prior to the `Context` being disposed otherwise UAFs can occur.
429    pub(crate) tm: ManuallyDrop<OwnedTargetMachine>,
430}
431
432unsafe impl Send for ModuleLlvm {}
433unsafe impl Sync for ModuleLlvm {}
434
435impl ModuleLlvm {
436    pub(crate) fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
437        unsafe {
438            let llcx = llvm::LLVMContextCreate();
439            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
440            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
441            ModuleLlvm {
442                llmod_raw,
443                llcx,
444                tm: ManuallyDrop::new(create_target_machine(tcx, mod_name)),
445            }
446        }
447    }
448
449    pub(crate) fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
450        unsafe {
451            let llcx = llvm::LLVMContextCreate();
452            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
453            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
454            ModuleLlvm {
455                llmod_raw,
456                llcx,
457                tm: ManuallyDrop::new(create_informational_target_machine(tcx.sess)),
458            }
459        }
460    }
461
462    pub(crate) fn parse(
463        cgcx: &CodegenContext,
464        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
465        name: &CStr,
466        buffer: &[u8],
467        dcx: DiagCtxtHandle<'_>,
468    ) -> Self {
469        unsafe {
470            let llcx = llvm::LLVMContextCreate();
471            llvm::LLVMContextSetDiscardValueNames(llcx, cgcx.fewer_names.to_llvm_bool());
472            let llmod_raw = back::lto::parse_module(llcx, name, buffer, dcx);
473            let tm = tm_factory(dcx, TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap()));
474
475            ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) }
476        }
477    }
478
479    pub(crate) fn llmod(&self) -> &llvm::Module {
480        unsafe { &*self.llmod_raw }
481    }
482}
483
484impl Drop for ModuleLlvm {
485    fn drop(&mut self) {
486        unsafe {
487            ManuallyDrop::drop(&mut self.tm);
488            llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
489        }
490    }
491}