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(slice_as_array))]
9#![feature(assert_matches)]
10#![feature(extern_types)]
11#![feature(file_buffered)]
12#![feature(if_let_guard)]
13#![feature(impl_trait_in_assoc_type)]
14#![feature(iter_intersperse)]
15#![feature(macro_derive)]
16#![feature(once_cell_try)]
17#![feature(trim_prefix_suffix)]
18#![feature(try_blocks)]
19// tidy-alphabetical-end
20
21use std::any::Any;
22use std::ffi::CStr;
23use std::mem::ManuallyDrop;
24use std::path::PathBuf;
25
26use back::owned_target_machine::OwnedTargetMachine;
27use back::write::{create_informational_target_machine, create_target_machine};
28use context::SimpleCx;
29use errors::ParseTargetMachineConfig;
30use llvm_util::target_config;
31use rustc_ast::expand::allocator::AllocatorMethod;
32use rustc_codegen_ssa::back::lto::{SerializedModule, ThinModule};
33use rustc_codegen_ssa::back::write::{
34    CodegenContext, FatLtoInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
35};
36use rustc_codegen_ssa::traits::*;
37use rustc_codegen_ssa::{CodegenResults, CompiledModule, ModuleCodegen, TargetConfig};
38use rustc_data_structures::fx::FxIndexMap;
39use rustc_errors::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;
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
77rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
78
79pub(crate) use macros::TryFromU32;
80
81#[derive(Clone)]
82pub struct LlvmCodegenBackend(());
83
84struct TimeTraceProfiler {
85    enabled: bool,
86}
87
88impl TimeTraceProfiler {
89    fn new(enabled: bool) -> Self {
90        if enabled {
91            unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() }
92        }
93        TimeTraceProfiler { enabled }
94    }
95}
96
97impl Drop for TimeTraceProfiler {
98    fn drop(&mut self) {
99        if self.enabled {
100            unsafe { llvm::LLVMRustTimeTraceProfilerFinishThread() }
101        }
102    }
103}
104
105impl ExtraBackendMethods for LlvmCodegenBackend {
106    fn codegen_allocator<'tcx>(
107        &self,
108        tcx: TyCtxt<'tcx>,
109        module_name: &str,
110        methods: &[AllocatorMethod],
111    ) -> ModuleLlvm {
112        let module_llvm = ModuleLlvm::new_metadata(tcx, module_name);
113        let cx =
114            SimpleCx::new(module_llvm.llmod(), &module_llvm.llcx, tcx.data_layout.pointer_size());
115        unsafe {
116            allocator::codegen(tcx, cx, module_name, methods);
117        }
118        module_llvm
119    }
120    fn compile_codegen_unit(
121        &self,
122        tcx: TyCtxt<'_>,
123        cgu_name: Symbol,
124    ) -> (ModuleCodegen<ModuleLlvm>, u64) {
125        base::compile_codegen_unit(tcx, cgu_name)
126    }
127    fn target_machine_factory(
128        &self,
129        sess: &Session,
130        optlvl: OptLevel,
131        target_features: &[String],
132    ) -> TargetMachineFactoryFn<Self> {
133        back::write::target_machine_factory(sess, optlvl, target_features)
134    }
135
136    fn spawn_named_thread<F, T>(
137        time_trace: bool,
138        name: String,
139        f: F,
140    ) -> std::io::Result<std::thread::JoinHandle<T>>
141    where
142        F: FnOnce() -> T,
143        F: Send + 'static,
144        T: Send + 'static,
145    {
146        std::thread::Builder::new().name(name).spawn(move || {
147            let _profiler = TimeTraceProfiler::new(time_trace);
148            f()
149        })
150    }
151}
152
153impl WriteBackendMethods for LlvmCodegenBackend {
154    type Module = ModuleLlvm;
155    type ModuleBuffer = back::lto::ModuleBuffer;
156    type TargetMachine = OwnedTargetMachine;
157    type TargetMachineError = crate::errors::LlvmError<'static>;
158    type ThinData = back::lto::ThinData;
159    type ThinBuffer = back::lto::ThinBuffer;
160    fn print_pass_timings(&self) {
161        let timings = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintPassTimings(s) }).unwrap();
162        print!("{timings}");
163    }
164    fn print_statistics(&self) {
165        let stats = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatistics(s) }).unwrap();
166        print!("{stats}");
167    }
168    fn run_and_optimize_fat_lto(
169        cgcx: &CodegenContext<Self>,
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 =
175            back::lto::run_fat(cgcx, exported_symbols_for_lto, each_linked_rlib_for_lto, modules);
176
177        let dcx = cgcx.create_dcx();
178        let dcx = dcx.handle();
179        back::lto::run_pass_manager(cgcx, dcx, &mut module, false);
180
181        module
182    }
183    fn run_thin_lto(
184        cgcx: &CodegenContext<Self>,
185        exported_symbols_for_lto: &[String],
186        each_linked_rlib_for_lto: &[PathBuf],
187        modules: Vec<(String, Self::ThinBuffer)>,
188        cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
189    ) -> (Vec<ThinModule<Self>>, Vec<WorkProduct>) {
190        back::lto::run_thin(
191            cgcx,
192            exported_symbols_for_lto,
193            each_linked_rlib_for_lto,
194            modules,
195            cached_modules,
196        )
197    }
198    fn optimize(
199        cgcx: &CodegenContext<Self>,
200        dcx: DiagCtxtHandle<'_>,
201        module: &mut ModuleCodegen<Self::Module>,
202        config: &ModuleConfig,
203    ) {
204        back::write::optimize(cgcx, dcx, module, config)
205    }
206    fn optimize_thin(
207        cgcx: &CodegenContext<Self>,
208        thin: ThinModule<Self>,
209    ) -> ModuleCodegen<Self::Module> {
210        back::lto::optimize_thin_module(thin, cgcx)
211    }
212    fn codegen(
213        cgcx: &CodegenContext<Self>,
214        module: ModuleCodegen<Self::Module>,
215        config: &ModuleConfig,
216    ) -> CompiledModule {
217        back::write::codegen(cgcx, module, config)
218    }
219    fn prepare_thin(module: ModuleCodegen<Self::Module>) -> (String, Self::ThinBuffer) {
220        back::lto::prepare_thin(module)
221    }
222    fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
223        (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
224    }
225}
226
227impl LlvmCodegenBackend {
228    pub fn new() -> Box<dyn CodegenBackend> {
229        Box::new(LlvmCodegenBackend(()))
230    }
231}
232
233impl CodegenBackend for LlvmCodegenBackend {
234    fn locale_resource(&self) -> &'static str {
235        crate::DEFAULT_LOCALE_RESOURCE
236    }
237
238    fn name(&self) -> &'static str {
239        "llvm"
240    }
241
242    fn init(&self, sess: &Session) {
243        llvm_util::init(sess); // Make sure llvm is inited
244
245        #[cfg(feature = "llvm_enzyme")]
246        {
247            use rustc_session::config::AutoDiff;
248
249            use crate::back::lto::enable_autodiff_settings;
250            if sess.opts.unstable_opts.autodiff.contains(&AutoDiff::Enable) {
251                if let Err(_) = llvm::EnzymeWrapper::get_or_init(&sess.opts.sysroot) {
252                    sess.dcx().emit_fatal(crate::errors::AutoDiffComponentUnavailable);
253                }
254                enable_autodiff_settings(&sess.opts.unstable_opts.autodiff);
255            }
256        }
257    }
258
259    fn provide(&self, providers: &mut Providers) {
260        providers.global_backend_features =
261            |tcx, ()| llvm_util::global_llvm_features(tcx.sess, false)
262    }
263
264    fn print(&self, req: &PrintRequest, out: &mut String, sess: &Session) {
265        use std::fmt::Write;
266        match req.kind {
267            PrintKind::RelocationModels => {
268                writeln!(out, "Available relocation models:").unwrap();
269                for name in RelocModel::ALL.iter().map(RelocModel::desc).chain(["default"]) {
270                    writeln!(out, "    {name}").unwrap();
271                }
272                writeln!(out).unwrap();
273            }
274            PrintKind::CodeModels => {
275                writeln!(out, "Available code models:").unwrap();
276                for name in &["tiny", "small", "kernel", "medium", "large"] {
277                    writeln!(out, "    {name}").unwrap();
278                }
279                writeln!(out).unwrap();
280            }
281            PrintKind::TlsModels => {
282                writeln!(out, "Available TLS models:").unwrap();
283                for name in TlsModel::ALL.iter().map(TlsModel::desc) {
284                    writeln!(out, "    {name}").unwrap();
285                }
286                writeln!(out).unwrap();
287            }
288            PrintKind::StackProtectorStrategies => {
289                writeln!(
290                    out,
291                    r#"Available stack protector strategies:
292    all
293        Generate stack canaries in all functions.
294
295    strong
296        Generate stack canaries in a function if it either:
297        - has a local variable of `[T; N]` type, regardless of `T` and `N`
298        - takes the address of a local variable.
299
300          (Note that a local variable being borrowed is not equivalent to its
301          address being taken: e.g. some borrows may be removed by optimization,
302          while by-value argument passing may be implemented with reference to a
303          local stack variable in the ABI.)
304
305    basic
306        Generate stack canaries in functions with local variables of `[T; N]`
307        type, where `T` is byte-sized and `N` >= 8.
308
309    none
310        Do not generate stack canaries.
311"#
312                )
313                .unwrap();
314            }
315            _other => llvm_util::print(req, out, sess),
316        }
317    }
318
319    fn print_passes(&self) {
320        llvm_util::print_passes();
321    }
322
323    fn print_version(&self) {
324        llvm_util::print_version();
325    }
326
327    fn has_zstd(&self) -> bool {
328        llvm::LLVMRustLLVMHasZstdCompression()
329    }
330
331    fn target_config(&self, sess: &Session) -> TargetConfig {
332        target_config(sess)
333    }
334
335    fn codegen_crate<'tcx>(&self, tcx: TyCtxt<'tcx>) -> Box<dyn Any> {
336        Box::new(rustc_codegen_ssa::base::codegen_crate(
337            LlvmCodegenBackend(()),
338            tcx,
339            crate::llvm_util::target_cpu(tcx.sess).to_string(),
340        ))
341    }
342
343    fn join_codegen(
344        &self,
345        ongoing_codegen: Box<dyn Any>,
346        sess: &Session,
347        outputs: &OutputFilenames,
348    ) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
349        let (codegen_results, work_products) = ongoing_codegen
350            .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
351            .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
352            .join(sess);
353
354        if sess.opts.unstable_opts.llvm_time_trace {
355            sess.time("llvm_dump_timing_file", || {
356                let file_name = outputs.with_extension("llvm_timings.json");
357                llvm_util::time_trace_profiler_finish(&file_name);
358            });
359        }
360
361        (codegen_results, work_products)
362    }
363
364    fn link(
365        &self,
366        sess: &Session,
367        codegen_results: CodegenResults,
368        metadata: EncodedMetadata,
369        outputs: &OutputFilenames,
370    ) {
371        use rustc_codegen_ssa::back::link::link_binary;
372
373        use crate::back::archive::LlvmArchiveBuilderBuilder;
374
375        // Run the linker on any artifacts that resulted from the LLVM run.
376        // This should produce either a finished executable or library.
377        link_binary(
378            sess,
379            &LlvmArchiveBuilderBuilder,
380            codegen_results,
381            metadata,
382            outputs,
383            self.name(),
384        );
385    }
386}
387
388pub struct ModuleLlvm {
389    llcx: &'static mut llvm::Context,
390    llmod_raw: *const llvm::Module,
391
392    // This field is `ManuallyDrop` because it is important that the `TargetMachine`
393    // is disposed prior to the `Context` being disposed otherwise UAFs can occur.
394    tm: ManuallyDrop<OwnedTargetMachine>,
395}
396
397unsafe impl Send for ModuleLlvm {}
398unsafe impl Sync for ModuleLlvm {}
399
400impl ModuleLlvm {
401    fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
402        unsafe {
403            let llcx = llvm::LLVMContextCreate();
404            llvm::LLVMContextSetDiscardValueNames(llcx, tcx.sess.fewer_names().to_llvm_bool());
405            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
406            ModuleLlvm {
407                llmod_raw,
408                llcx,
409                tm: ManuallyDrop::new(create_target_machine(tcx, mod_name)),
410            }
411        }
412    }
413
414    fn new_metadata(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_informational_target_machine(tcx.sess, false)),
423            }
424        }
425    }
426
427    fn tm_from_cgcx(
428        cgcx: &CodegenContext<LlvmCodegenBackend>,
429        name: &str,
430        dcx: DiagCtxtHandle<'_>,
431    ) -> OwnedTargetMachine {
432        let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name);
433        match (cgcx.tm_factory)(tm_factory_config) {
434            Ok(m) => m,
435            Err(e) => {
436                dcx.emit_fatal(ParseTargetMachineConfig(e));
437            }
438        }
439    }
440
441    fn parse(
442        cgcx: &CodegenContext<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 = ModuleLlvm::tm_from_cgcx(cgcx, name.to_str().unwrap(), dcx);
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}