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#![feature(extern_types)]
10#![feature(file_buffered)]
11#![feature(if_let_guard)]
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::{CodegenResults, CompiledModule, 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    enabled: bool,
84}
85
86impl TimeTraceProfiler {
87    fn new(enabled: bool) -> Self {
88        if enabled {
89            unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() }
90        }
91        TimeTraceProfiler { enabled }
92    }
93}
94
95impl Drop for TimeTraceProfiler {
96    fn drop(&mut self) {
97        if self.enabled {
98            unsafe { llvm::LLVMRustTimeTraceProfilerFinishThread() }
99        }
100    }
101}
102
103impl ExtraBackendMethods for LlvmCodegenBackend {
104    fn codegen_allocator<'tcx>(
105        &self,
106        tcx: TyCtxt<'tcx>,
107        module_name: &str,
108        methods: &[AllocatorMethod],
109    ) -> ModuleLlvm {
110        let module_llvm = ModuleLlvm::new_metadata(tcx, module_name);
111        let cx =
112            SimpleCx::new(module_llvm.llmod(), &module_llvm.llcx, tcx.data_layout.pointer_size());
113        unsafe {
114            allocator::codegen(tcx, cx, module_name, methods);
115        }
116        module_llvm
117    }
118    fn compile_codegen_unit(
119        &self,
120        tcx: TyCtxt<'_>,
121        cgu_name: Symbol,
122    ) -> (ModuleCodegen<ModuleLlvm>, u64) {
123        base::compile_codegen_unit(tcx, cgu_name)
124    }
125    fn target_machine_factory(
126        &self,
127        sess: &Session,
128        optlvl: OptLevel,
129        target_features: &[String],
130    ) -> TargetMachineFactoryFn<Self> {
131        back::write::target_machine_factory(sess, optlvl, target_features)
132    }
133
134    fn spawn_named_thread<F, T>(
135        time_trace: bool,
136        name: String,
137        f: F,
138    ) -> std::io::Result<std::thread::JoinHandle<T>>
139    where
140        F: FnOnce() -> T,
141        F: Send + 'static,
142        T: Send + 'static,
143    {
144        std::thread::Builder::new().name(name).spawn(move || {
145            let _profiler = TimeTraceProfiler::new(time_trace);
146            f()
147        })
148    }
149}
150
151impl WriteBackendMethods for LlvmCodegenBackend {
152    type Module = ModuleLlvm;
153    type ModuleBuffer = back::lto::ModuleBuffer;
154    type TargetMachine = OwnedTargetMachine;
155    type ThinData = back::lto::ThinData;
156    type ThinBuffer = back::lto::ThinBuffer;
157    fn print_pass_timings(&self) {
158        let timings = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintPassTimings(s) }).unwrap();
159        { ::std::io::_print(format_args!("{0}", timings)); };print!("{timings}");
160    }
161    fn print_statistics(&self) {
162        let stats = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatistics(s) }).unwrap();
163        { ::std::io::_print(format_args!("{0}", stats)); };print!("{stats}");
164    }
165    fn run_and_optimize_fat_lto(
166        cgcx: &CodegenContext,
167        prof: &SelfProfilerRef,
168        shared_emitter: &SharedEmitter,
169        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
170        exported_symbols_for_lto: &[String],
171        each_linked_rlib_for_lto: &[PathBuf],
172        modules: Vec<FatLtoInput<Self>>,
173    ) -> ModuleCodegen<Self::Module> {
174        let mut module = back::lto::run_fat(
175            cgcx,
176            prof,
177            shared_emitter,
178            tm_factory,
179            exported_symbols_for_lto,
180            each_linked_rlib_for_lto,
181            modules,
182        );
183
184        let dcx = DiagCtxt::new(Box::new(shared_emitter.clone()));
185        let dcx = dcx.handle();
186        back::lto::run_pass_manager(cgcx, prof, dcx, &mut module, false);
187
188        module
189    }
190    fn run_thin_lto(
191        cgcx: &CodegenContext,
192        prof: &SelfProfilerRef,
193        dcx: DiagCtxtHandle<'_>,
194        exported_symbols_for_lto: &[String],
195        each_linked_rlib_for_lto: &[PathBuf],
196        modules: Vec<(String, Self::ThinBuffer)>,
197        cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
198    ) -> (Vec<ThinModule<Self>>, Vec<WorkProduct>) {
199        back::lto::run_thin(
200            cgcx,
201            prof,
202            dcx,
203            exported_symbols_for_lto,
204            each_linked_rlib_for_lto,
205            modules,
206            cached_modules,
207        )
208    }
209    fn optimize(
210        cgcx: &CodegenContext,
211        prof: &SelfProfilerRef,
212        shared_emitter: &SharedEmitter,
213        module: &mut ModuleCodegen<Self::Module>,
214        config: &ModuleConfig,
215    ) {
216        back::write::optimize(cgcx, prof, shared_emitter, module, config)
217    }
218    fn optimize_thin(
219        cgcx: &CodegenContext,
220        prof: &SelfProfilerRef,
221        shared_emitter: &SharedEmitter,
222        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
223        thin: ThinModule<Self>,
224    ) -> ModuleCodegen<Self::Module> {
225        back::lto::optimize_thin_module(cgcx, prof, shared_emitter, tm_factory, thin)
226    }
227    fn codegen(
228        cgcx: &CodegenContext,
229        prof: &SelfProfilerRef,
230        shared_emitter: &SharedEmitter,
231        module: ModuleCodegen<Self::Module>,
232        config: &ModuleConfig,
233    ) -> CompiledModule {
234        back::write::codegen(cgcx, prof, shared_emitter, module, config)
235    }
236    fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
237        back::lto::prepare_thin(module)
238    }
239    fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
240        (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
241    }
242}
243
244impl LlvmCodegenBackend {
245    pub fn new() -> Box<dyn CodegenBackend> {
246        Box::new(LlvmCodegenBackend(()))
247    }
248}
249
250impl CodegenBackend for LlvmCodegenBackend {
251    fn name(&self) -> &'static str {
252        "llvm"
253    }
254
255    fn init(&self, sess: &Session) {
256        llvm_util::init(sess); // Make sure llvm is inited
257
258        // autodiff is based on Enzyme, a library which we might not have available, when it was
259        // neither build, nor downloaded via rustup. If autodiff is used, but not available we emit
260        // an early error here and abort compilation.
261        {
262            use rustc_session::config::AutoDiff;
263
264            use crate::back::lto::enable_autodiff_settings;
265            if sess.opts.unstable_opts.autodiff.contains(&AutoDiff::Enable) {
266                match llvm::EnzymeWrapper::get_or_init(&sess.opts.sysroot) {
267                    Ok(_) => {}
268                    Err(llvm::EnzymeLibraryError::NotFound { err }) => {
269                        sess.dcx().emit_fatal(crate::errors::AutoDiffComponentMissing { err });
270                    }
271                    Err(llvm::EnzymeLibraryError::LoadFailed { err }) => {
272                        sess.dcx().emit_fatal(crate::errors::AutoDiffComponentUnavailable { err });
273                    }
274                }
275                enable_autodiff_settings(&sess.opts.unstable_opts.autodiff);
276            }
277        }
278    }
279
280    fn provide(&self, providers: &mut Providers) {
281        providers.queries.global_backend_features =
282            |tcx, ()| llvm_util::global_llvm_features(tcx.sess, false)
283    }
284
285    fn print(&self, req: &PrintRequest, out: &mut String, sess: &Session) {
286        use std::fmt::Write;
287        match req.kind {
288            PrintKind::RelocationModels => {
289                out.write_fmt(format_args!("Available relocation models:\n"))writeln!(out, "Available relocation models:").unwrap();
290                for name in RelocModel::ALL.iter().map(RelocModel::desc).chain(["default"]) {
291                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
292                }
293                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
294            }
295            PrintKind::CodeModels => {
296                out.write_fmt(format_args!("Available code models:\n"))writeln!(out, "Available code models:").unwrap();
297                for name in &["tiny", "small", "kernel", "medium", "large"] {
298                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
299                }
300                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
301            }
302            PrintKind::TlsModels => {
303                out.write_fmt(format_args!("Available TLS models:\n"))writeln!(out, "Available TLS models:").unwrap();
304                for name in TlsModel::ALL.iter().map(TlsModel::desc) {
305                    out.write_fmt(format_args!("    {0}\n", name))writeln!(out, "    {name}").unwrap();
306                }
307                out.write_fmt(format_args!("\n"))writeln!(out).unwrap();
308            }
309            PrintKind::StackProtectorStrategies => {
310                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!(
311                    out,
312                    r#"Available stack protector strategies:
313    all
314        Generate stack canaries in all functions.
315
316    strong
317        Generate stack canaries in a function if it either:
318        - has a local variable of `[T; N]` type, regardless of `T` and `N`
319        - takes the address of a local variable.
320
321          (Note that a local variable being borrowed is not equivalent to its
322          address being taken: e.g. some borrows may be removed by optimization,
323          while by-value argument passing may be implemented with reference to a
324          local stack variable in the ABI.)
325
326    basic
327        Generate stack canaries in functions with local variables of `[T; N]`
328        type, where `T` is byte-sized and `N` >= 8.
329
330    none
331        Do not generate stack canaries.
332"#
333                )
334                .unwrap();
335            }
336            _other => llvm_util::print(req, out, sess),
337        }
338    }
339
340    fn print_passes(&self) {
341        llvm_util::print_passes();
342    }
343
344    fn print_version(&self) {
345        llvm_util::print_version();
346    }
347
348    fn has_zstd(&self) -> bool {
349        llvm::LLVMRustLLVMHasZstdCompression()
350    }
351
352    fn target_config(&self, sess: &Session) -> TargetConfig {
353        target_config(sess)
354    }
355
356    fn replaced_intrinsics(&self) -> Vec<Symbol> {
357        <[_]>::into_vec(::alloc::boxed::box_new([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]
358    }
359
360    fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
361        Box::new(rustc_codegen_ssa::base::codegen_crate(
362            LlvmCodegenBackend(()),
363            tcx,
364            crate::llvm_util::target_cpu(tcx.sess).to_string(),
365        ))
366    }
367
368    fn join_codegen(
369        &self,
370        ongoing_codegen: Box<dyn Any>,
371        sess: &Session,
372        outputs: &OutputFilenames,
373    ) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
374        let (codegen_results, work_products) = ongoing_codegen
375            .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
376            .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
377            .join(sess);
378
379        if sess.opts.unstable_opts.llvm_time_trace {
380            sess.time("llvm_dump_timing_file", || {
381                let file_name = outputs.with_extension("llvm_timings.json");
382                llvm_util::time_trace_profiler_finish(&file_name);
383            });
384        }
385
386        (codegen_results, work_products)
387    }
388
389    fn link(
390        &self,
391        sess: &Session,
392        codegen_results: CodegenResults,
393        metadata: EncodedMetadata,
394        outputs: &OutputFilenames,
395    ) {
396        use rustc_codegen_ssa::back::link::link_binary;
397
398        use crate::back::archive::LlvmArchiveBuilderBuilder;
399
400        // Run the linker on any artifacts that resulted from the LLVM run.
401        // This should produce either a finished executable or library.
402        link_binary(
403            sess,
404            &LlvmArchiveBuilderBuilder,
405            codegen_results,
406            metadata,
407            outputs,
408            self.name(),
409        );
410    }
411}
412
413pub struct ModuleLlvm {
414    llcx: &'static mut llvm::Context,
415    llmod_raw: *const llvm::Module,
416
417    // This field is `ManuallyDrop` because it is important that the `TargetMachine`
418    // is disposed prior to the `Context` being disposed otherwise UAFs can occur.
419    tm: ManuallyDrop<OwnedTargetMachine>,
420}
421
422unsafe impl Send for ModuleLlvm {}
423unsafe impl Sync for ModuleLlvm {}
424
425impl ModuleLlvm {
426    fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
427        unsafe {
428            let llcx = llvm::LLVMContextCreate();
429            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
430            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
431            ModuleLlvm {
432                llmod_raw,
433                llcx,
434                tm: ManuallyDrop::new(create_target_machine(tcx, mod_name)),
435            }
436        }
437    }
438
439    fn new_metadata(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_informational_target_machine(tcx.sess, false)),
448            }
449        }
450    }
451
452    fn parse(
453        cgcx: &CodegenContext,
454        tm_factory: TargetMachineFactoryFn<LlvmCodegenBackend>,
455        name: &CStr,
456        buffer: &[u8],
457        dcx: DiagCtxtHandle<'_>,
458    ) -> Self {
459        unsafe {
460            let llcx = llvm::LLVMContextCreate();
461            llvm::LLVMContextSetDiscardValueNames(llcx, cgcx.fewer_names.to_llvm_bool());
462            let llmod_raw = back::lto::parse_module(llcx, name, buffer, dcx);
463            let tm = tm_factory(dcx, TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap()));
464
465            ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) }
466        }
467    }
468
469    fn llmod(&self) -> &llvm::Module {
470        unsafe { &*self.llmod_raw }
471    }
472}
473
474impl Drop for ModuleLlvm {
475    fn drop(&mut self) {
476        unsafe {
477            ManuallyDrop::drop(&mut self.tm);
478            llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
479        }
480    }
481}