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#![cfg_attr(bootstrap, feature(assert_matches))]
9#![cfg_attr(bootstrap, feature(if_let_guard))]
10#![feature(extern_types)]
11#![feature(file_buffered)]
12#![feature(impl_trait_in_assoc_type)]
13#![feature(iter_intersperse)]
14#![feature(macro_derive)]
15#![feature(once_cell_try)]
16#![feature(trim_prefix_suffix)]
17#![feature(try_blocks)]
18// tidy-alphabetical-end
19
20use std::any::Any;
21use std::ffi::CStr;
22use std::mem::ManuallyDrop;
23use std::path::PathBuf;
24
25use back::owned_target_machine::OwnedTargetMachine;
26use back::write::{create_informational_target_machine, create_target_machine};
27use context::SimpleCx;
28use llvm_util::target_config;
29use rustc_ast::expand::allocator::AllocatorMethod;
30use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule};
31use rustc_codegen_ssa::back::write::{
32    CodegenContext, FatLtoInput, ModuleConfig, SharedEmitter, TargetMachineFactoryConfig,
33    TargetMachineFactoryFn,
34};
35use rustc_codegen_ssa::traits::*;
36use rustc_codegen_ssa::{CompiledModule, CompiledModules, CrateInfo, ModuleCodegen, TargetConfig};
37use rustc_data_structures::fx::FxIndexMap;
38use rustc_data_structures::profiling::SelfProfilerRef;
39use rustc_errors::{DiagCtxt, DiagCtxtHandle};
40use rustc_metadata::EncodedMetadata;
41use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
42use rustc_middle::ty::TyCtxt;
43use rustc_middle::util::Providers;
44use rustc_session::Session;
45use rustc_session::config::{OptLevel, OutputFilenames, PrintKind, PrintRequest};
46use rustc_span::{Symbol, sym};
47use rustc_target::spec::{RelocModel, TlsModel};
48
49use crate::llvm::ToLlvmBool;
50
51mod abi;
52mod allocator;
53mod asm;
54mod attributes;
55mod back;
56mod base;
57mod builder;
58mod callee;
59mod common;
60mod consts;
61mod context;
62mod coverageinfo;
63mod debuginfo;
64mod declare;
65mod errors;
66mod intrinsic;
67mod llvm;
68mod llvm_util;
69mod macros;
70mod mono_item;
71mod type_;
72mod type_of;
73mod typetree;
74mod va_arg;
75mod value;
76
77pub(crate) use macros::TryFromU32;
78
79#[derive(#[automatically_derived]
impl ::core::clone::Clone for LlvmCodegenBackend {
    #[inline]
    fn clone(&self) -> LlvmCodegenBackend {
        LlvmCodegenBackend(::core::clone::Clone::clone(&self.0))
    }
}Clone)]
80pub struct LlvmCodegenBackend(());
81
82struct TimeTraceProfiler {}
83
84impl TimeTraceProfiler {
85    fn new() -> Self {
86        unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() }
87        TimeTraceProfiler {}
88    }
89}
90
91impl Drop for TimeTraceProfiler {
92    fn drop(&mut self) {
93        unsafe { llvm::LLVMRustTimeTraceProfilerFinishThread() }
94    }
95}
96
97impl ExtraBackendMethods for LlvmCodegenBackend {
98    fn codegen_allocator<'tcx>(
99        &self,
100        tcx: TyCtxt<'tcx>,
101        module_name: &str,
102        methods: &[AllocatorMethod],
103    ) -> ModuleLlvm {
104        let module_llvm = ModuleLlvm::new_metadata(tcx, module_name);
105        let cx =
106            SimpleCx::new(module_llvm.llmod(), &module_llvm.llcx, tcx.data_layout.pointer_size());
107        unsafe {
108            allocator::codegen(tcx, cx, module_name, methods);
109        }
110        module_llvm
111    }
112    fn compile_codegen_unit(
113        &self,
114        tcx: TyCtxt<'_>,
115        cgu_name: Symbol,
116    ) -> (ModuleCodegen<ModuleLlvm>, u64) {
117        base::compile_codegen_unit(tcx, cgu_name)
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    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        cgcx: &CodegenContext,
139        prof: &SelfProfilerRef,
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            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, prof, dcx, &mut module, false);
159
160        back::write::codegen(cgcx, 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<(String, Self::ModuleBuffer)>,
169        cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
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            cached_modules,
179        )
180    }
181    fn optimize(
182        cgcx: &CodegenContext,
183        prof: &SelfProfilerRef,
184        shared_emitter: &SharedEmitter,
185        module: &mut ModuleCodegen<Self::Module>,
186        config: &ModuleConfig,
187    ) {
188        back::write::optimize(cgcx, prof, shared_emitter, module, config)
189    }
190    fn optimize_and_codegen_thin(
191        cgcx: &CodegenContext,
192        prof: &SelfProfilerRef,
193        shared_emitter: &SharedEmitter,
194        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
195        thin: ThinModule<Self>,
196    ) -> CompiledModule {
197        back::lto::optimize_and_codegen_thin_module(cgcx, prof, shared_emitter, tm_factory, thin)
198    }
199    fn codegen(
200        cgcx: &CodegenContext,
201        prof: &SelfProfilerRef,
202        shared_emitter: &SharedEmitter,
203        module: ModuleCodegen<Self::Module>,
204        config: &ModuleConfig,
205    ) -> CompiledModule {
206        back::write::codegen(cgcx, prof, shared_emitter, module, config)
207    }
208    fn serialize_module(module: Self::Module, is_thin: bool) -> Self::ModuleBuffer {
209        back::lto::ModuleBuffer::new(module.llmod(), is_thin)
210    }
211}
212
213impl LlvmCodegenBackend {
214    pub fn new() -> Box<dyn CodegenBackend> {
215        Box::new(LlvmCodegenBackend(()))
216    }
217}
218
219impl CodegenBackend for LlvmCodegenBackend {
220    fn name(&self) -> &'static str {
221        "llvm"
222    }
223
224    fn init(&self, sess: &Session) {
225        llvm_util::init(sess); // Make sure llvm is inited
226
227        // autodiff is based on Enzyme, a library which we might not have available, when it was
228        // neither build, nor downloaded via rustup. If autodiff is used, but not available we emit
229        // an early error here and abort compilation.
230        {
231            use rustc_session::config::AutoDiff;
232
233            use crate::back::lto::enable_autodiff_settings;
234            if sess.opts.unstable_opts.autodiff.contains(&AutoDiff::Enable) {
235                match llvm::EnzymeWrapper::get_or_init(&sess.opts.sysroot) {
236                    Ok(_) => {}
237                    Err(llvm::EnzymeLibraryError::NotFound { err }) => {
238                        sess.dcx().emit_fatal(crate::errors::AutoDiffComponentMissing { err });
239                    }
240                    Err(llvm::EnzymeLibraryError::LoadFailed { err }) => {
241                        sess.dcx().emit_fatal(crate::errors::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 target_config(&self, sess: &Session) -> TargetConfig {
322        target_config(sess)
323    }
324
325    fn replaced_intrinsics(&self) -> Vec<Symbol> {
326        let mut will_not_use_fallback =
327            ::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]))vec![sym::unchecked_funnel_shl, sym::unchecked_funnel_shr, sym::carrying_mul_add];
328
329        if llvm_util::get_version() >= (22, 0, 0) {
330            will_not_use_fallback.push(sym::carryless_mul);
331        }
332
333        will_not_use_fallback
334    }
335
336    fn target_cpu(&self, sess: &Session) -> String {
337        crate::llvm_util::target_cpu(sess).to_string()
338    }
339
340    fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>, crate_info: &CrateInfo) -> Box<dyn Any> {
341        Box::new(rustc_codegen_ssa::base::codegen_crate(LlvmCodegenBackend(()), tcx, crate_info))
342    }
343
344    fn join_codegen(
345        &self,
346        ongoing_codegen: Box<dyn Any>,
347        sess: &Session,
348        outputs: &OutputFilenames,
349    ) -> (CompiledModules, FxIndexMap<WorkProductId, WorkProduct>) {
350        let (compiled_modules, work_products) = ongoing_codegen
351            .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
352            .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
353            .join(sess);
354
355        if sess.opts.unstable_opts.llvm_time_trace {
356            sess.time("llvm_dump_timing_file", || {
357                let file_name = outputs.with_extension("llvm_timings.json");
358                llvm_util::time_trace_profiler_finish(&file_name);
359            });
360        }
361
362        (compiled_modules, work_products)
363    }
364
365    fn print_pass_timings(&self) {
366        let timings = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintPassTimings(s) }).unwrap();
367        { ::std::io::_print(format_args!("{0}", timings)); };print!("{timings}");
368    }
369
370    fn print_statistics(&self) {
371        let stats = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatistics(s) }).unwrap();
372        { ::std::io::_print(format_args!("{0}", stats)); };print!("{stats}");
373    }
374
375    fn link(
376        &self,
377        sess: &Session,
378        compiled_modules: CompiledModules,
379        crate_info: CrateInfo,
380        metadata: EncodedMetadata,
381        outputs: &OutputFilenames,
382    ) {
383        use rustc_codegen_ssa::back::link::link_binary;
384
385        use crate::back::archive::LlvmArchiveBuilderBuilder;
386
387        // Run the linker on any artifacts that resulted from the LLVM run.
388        // This should produce either a finished executable or library.
389        link_binary(
390            sess,
391            &LlvmArchiveBuilderBuilder,
392            compiled_modules,
393            crate_info,
394            metadata,
395            outputs,
396            self.name(),
397        );
398    }
399}
400
401pub struct ModuleLlvm {
402    llcx: &'static mut llvm::Context,
403    llmod_raw: *const llvm::Module,
404
405    // This field is `ManuallyDrop` because it is important that the `TargetMachine`
406    // is disposed prior to the `Context` being disposed otherwise UAFs can occur.
407    tm: ManuallyDrop<OwnedTargetMachine>,
408}
409
410unsafe impl Send for ModuleLlvm {}
411unsafe impl Sync for ModuleLlvm {}
412
413impl ModuleLlvm {
414    fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
415        unsafe {
416            let llcx = llvm::LLVMContextCreate();
417            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
418            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
419            ModuleLlvm {
420                llmod_raw,
421                llcx,
422                tm: ManuallyDrop::new(create_target_machine(tcx, mod_name)),
423            }
424        }
425    }
426
427    fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
428        unsafe {
429            let llcx = llvm::LLVMContextCreate();
430            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
431            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
432            ModuleLlvm {
433                llmod_raw,
434                llcx,
435                tm: ManuallyDrop::new(create_informational_target_machine(tcx.sess, false)),
436            }
437        }
438    }
439
440    fn parse(
441        cgcx: &CodegenContext,
442        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
443        name: &CStr,
444        buffer: &[u8],
445        dcx: DiagCtxtHandle<'_>,
446    ) -> Self {
447        unsafe {
448            let llcx = llvm::LLVMContextCreate();
449            llvm::LLVMContextSetDiscardValueNames(llcx, cgcx.fewer_names.to_llvm_bool());
450            let llmod_raw = back::lto::parse_module(llcx, name, buffer, dcx);
451            let tm = tm_factory(dcx, TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap()));
452
453            ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) }
454        }
455    }
456
457    fn llmod(&self) -> &llvm::Module {
458        unsafe { &*self.llmod_raw }
459    }
460}
461
462impl Drop for ModuleLlvm {
463    fn drop(&mut self) {
464        unsafe {
465            ManuallyDrop::drop(&mut self.tm);
466            llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
467        }
468    }
469}