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#![allow(internal_features)]
9#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
10#![doc(rust_logo)]
11#![feature(assert_matches)]
12#![feature(exact_size_is_empty)]
13#![feature(extern_types)]
14#![feature(file_buffered)]
15#![feature(hash_raw_entry)]
16#![feature(if_let_guard)]
17#![feature(impl_trait_in_assoc_type)]
18#![feature(iter_intersperse)]
19#![feature(let_chains)]
20#![feature(rustdoc_internals)]
21#![feature(slice_as_array)]
22#![feature(try_blocks)]
23#![warn(unreachable_pub)]
24// tidy-alphabetical-end
25
26use std::any::Any;
27use std::ffi::CStr;
28use std::mem::ManuallyDrop;
29
30use back::owned_target_machine::OwnedTargetMachine;
31use back::write::{create_informational_target_machine, create_target_machine};
32use errors::{AutoDiffWithoutLTO, ParseTargetMachineConfig};
33pub(crate) use llvm_util::target_features_cfg;
34use rustc_ast::expand::allocator::AllocatorKind;
35use rustc_ast::expand::autodiff_attrs::AutoDiffItem;
36use rustc_codegen_ssa::back::lto::{LtoModuleCodegen, SerializedModule, ThinModule};
37use rustc_codegen_ssa::back::write::{
38    CodegenContext, FatLtoInput, ModuleConfig, TargetMachineFactoryConfig, TargetMachineFactoryFn,
39};
40use rustc_codegen_ssa::traits::*;
41use rustc_codegen_ssa::{CodegenResults, CompiledModule, ModuleCodegen};
42use rustc_data_structures::fx::FxIndexMap;
43use rustc_errors::{DiagCtxtHandle, FatalError};
44use rustc_metadata::EncodedMetadata;
45use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
46use rustc_middle::ty::TyCtxt;
47use rustc_middle::util::Providers;
48use rustc_session::Session;
49use rustc_session::config::{Lto, OptLevel, OutputFilenames, PrintKind, PrintRequest};
50use rustc_span::Symbol;
51
52mod back {
53    pub(crate) mod archive;
54    pub(crate) mod lto;
55    pub(crate) mod owned_target_machine;
56    mod profiling;
57    pub(crate) mod write;
58}
59
60mod abi;
61mod allocator;
62mod asm;
63mod attributes;
64mod base;
65mod builder;
66mod callee;
67mod common;
68mod consts;
69mod context;
70mod coverageinfo;
71mod debuginfo;
72mod declare;
73mod errors;
74mod intrinsic;
75// FIXME(Zalathar): Fix all the unreachable-pub warnings that would occur if
76// this isn't pub, then make it not pub.
77pub mod llvm;
78mod llvm_util;
79mod mono_item;
80mod type_;
81mod type_of;
82mod va_arg;
83mod value;
84
85rustc_fluent_macro::fluent_messages! { "../messages.ftl" }
86
87#[derive(Clone)]
88pub struct LlvmCodegenBackend(());
89
90struct TimeTraceProfiler {
91    enabled: bool,
92}
93
94impl TimeTraceProfiler {
95    fn new(enabled: bool) -> Self {
96        if enabled {
97            unsafe { llvm::LLVMRustTimeTraceProfilerInitialize() }
98        }
99        TimeTraceProfiler { enabled }
100    }
101}
102
103impl Drop for TimeTraceProfiler {
104    fn drop(&mut self) {
105        if self.enabled {
106            unsafe { llvm::LLVMRustTimeTraceProfilerFinishThread() }
107        }
108    }
109}
110
111impl ExtraBackendMethods for LlvmCodegenBackend {
112    fn codegen_allocator<'tcx>(
113        &self,
114        tcx: TyCtxt<'tcx>,
115        module_name: &str,
116        kind: AllocatorKind,
117        alloc_error_handler_kind: AllocatorKind,
118    ) -> ModuleLlvm {
119        let mut module_llvm = ModuleLlvm::new_metadata(tcx, module_name);
120        unsafe {
121            allocator::codegen(tcx, &mut module_llvm, module_name, kind, alloc_error_handler_kind);
122        }
123        module_llvm
124    }
125    fn compile_codegen_unit(
126        &self,
127        tcx: TyCtxt<'_>,
128        cgu_name: Symbol,
129    ) -> (ModuleCodegen<ModuleLlvm>, u64) {
130        base::compile_codegen_unit(tcx, cgu_name)
131    }
132    fn target_machine_factory(
133        &self,
134        sess: &Session,
135        optlvl: OptLevel,
136        target_features: &[String],
137    ) -> TargetMachineFactoryFn<Self> {
138        back::write::target_machine_factory(sess, optlvl, target_features)
139    }
140
141    fn spawn_named_thread<F, T>(
142        time_trace: bool,
143        name: String,
144        f: F,
145    ) -> std::io::Result<std::thread::JoinHandle<T>>
146    where
147        F: FnOnce() -> T,
148        F: Send + 'static,
149        T: Send + 'static,
150    {
151        std::thread::Builder::new().name(name).spawn(move || {
152            let _profiler = TimeTraceProfiler::new(time_trace);
153            f()
154        })
155    }
156}
157
158impl WriteBackendMethods for LlvmCodegenBackend {
159    type Module = ModuleLlvm;
160    type ModuleBuffer = back::lto::ModuleBuffer;
161    type TargetMachine = OwnedTargetMachine;
162    type TargetMachineError = crate::errors::LlvmError<'static>;
163    type ThinData = back::lto::ThinData;
164    type ThinBuffer = back::lto::ThinBuffer;
165    fn print_pass_timings(&self) {
166        let timings = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintPassTimings(s) }).unwrap();
167        print!("{timings}");
168    }
169    fn print_statistics(&self) {
170        let stats = llvm::build_string(|s| unsafe { llvm::LLVMRustPrintStatistics(s) }).unwrap();
171        print!("{stats}");
172    }
173    fn run_link(
174        cgcx: &CodegenContext<Self>,
175        dcx: DiagCtxtHandle<'_>,
176        modules: Vec<ModuleCodegen<Self::Module>>,
177    ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
178        back::write::link(cgcx, dcx, modules)
179    }
180    fn run_fat_lto(
181        cgcx: &CodegenContext<Self>,
182        modules: Vec<FatLtoInput<Self>>,
183        cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
184    ) -> Result<LtoModuleCodegen<Self>, FatalError> {
185        back::lto::run_fat(cgcx, modules, cached_modules)
186    }
187    fn run_thin_lto(
188        cgcx: &CodegenContext<Self>,
189        modules: Vec<(String, Self::ThinBuffer)>,
190        cached_modules: Vec<(SerializedModule<Self::ModuleBuffer>, WorkProduct)>,
191    ) -> Result<(Vec<LtoModuleCodegen<Self>>, Vec<WorkProduct>), FatalError> {
192        back::lto::run_thin(cgcx, modules, cached_modules)
193    }
194    unsafe fn optimize(
195        cgcx: &CodegenContext<Self>,
196        dcx: DiagCtxtHandle<'_>,
197        module: &ModuleCodegen<Self::Module>,
198        config: &ModuleConfig,
199    ) -> Result<(), FatalError> {
200        unsafe { back::write::optimize(cgcx, dcx, module, config) }
201    }
202    fn optimize_fat(
203        cgcx: &CodegenContext<Self>,
204        module: &mut ModuleCodegen<Self::Module>,
205    ) -> Result<(), FatalError> {
206        let dcx = cgcx.create_dcx();
207        let dcx = dcx.handle();
208        back::lto::run_pass_manager(cgcx, dcx, module, false)
209    }
210    unsafe fn optimize_thin(
211        cgcx: &CodegenContext<Self>,
212        thin: ThinModule<Self>,
213    ) -> Result<ModuleCodegen<Self::Module>, FatalError> {
214        unsafe { back::lto::optimize_thin_module(thin, cgcx) }
215    }
216    unsafe fn codegen(
217        cgcx: &CodegenContext<Self>,
218        dcx: DiagCtxtHandle<'_>,
219        module: ModuleCodegen<Self::Module>,
220        config: &ModuleConfig,
221    ) -> Result<CompiledModule, FatalError> {
222        unsafe { back::write::codegen(cgcx, dcx, module, config) }
223    }
224    fn prepare_thin(
225        module: ModuleCodegen<Self::Module>,
226        emit_summary: bool,
227    ) -> (String, Self::ThinBuffer) {
228        back::lto::prepare_thin(module, emit_summary)
229    }
230    fn serialize_module(module: ModuleCodegen<Self::Module>) -> (String, Self::ModuleBuffer) {
231        (module.name, back::lto::ModuleBuffer::new(module.module_llvm.llmod()))
232    }
233    /// Generate autodiff rules
234    fn autodiff(
235        cgcx: &CodegenContext<Self>,
236        module: &ModuleCodegen<Self::Module>,
237        diff_fncs: Vec<AutoDiffItem>,
238        config: &ModuleConfig,
239    ) -> Result<(), FatalError> {
240        if cgcx.lto != Lto::Fat {
241            let dcx = cgcx.create_dcx();
242            return Err(dcx.handle().emit_almost_fatal(AutoDiffWithoutLTO));
243        }
244        builder::autodiff::differentiate(module, cgcx, diff_fncs, config)
245    }
246}
247
248impl LlvmCodegenBackend {
249    pub fn new() -> Box<dyn CodegenBackend> {
250        Box::new(LlvmCodegenBackend(()))
251    }
252}
253
254impl CodegenBackend for LlvmCodegenBackend {
255    fn locale_resource(&self) -> &'static str {
256        crate::DEFAULT_LOCALE_RESOURCE
257    }
258
259    fn init(&self, sess: &Session) {
260        llvm_util::init(sess); // Make sure llvm is inited
261    }
262
263    fn provide(&self, providers: &mut Providers) {
264        providers.global_backend_features =
265            |tcx, ()| llvm_util::global_llvm_features(tcx.sess, true, false)
266    }
267
268    fn print(&self, req: &PrintRequest, out: &mut String, sess: &Session) {
269        use std::fmt::Write;
270        match req.kind {
271            PrintKind::RelocationModels => {
272                writeln!(out, "Available relocation models:").unwrap();
273                for name in &[
274                    "static",
275                    "pic",
276                    "pie",
277                    "dynamic-no-pic",
278                    "ropi",
279                    "rwpi",
280                    "ropi-rwpi",
281                    "default",
282                ] {
283                    writeln!(out, "    {name}").unwrap();
284                }
285                writeln!(out).unwrap();
286            }
287            PrintKind::CodeModels => {
288                writeln!(out, "Available code models:").unwrap();
289                for name in &["tiny", "small", "kernel", "medium", "large"] {
290                    writeln!(out, "    {name}").unwrap();
291                }
292                writeln!(out).unwrap();
293            }
294            PrintKind::TlsModels => {
295                writeln!(out, "Available TLS models:").unwrap();
296                for name in
297                    &["global-dynamic", "local-dynamic", "initial-exec", "local-exec", "emulated"]
298                {
299                    writeln!(out, "    {name}").unwrap();
300                }
301                writeln!(out).unwrap();
302            }
303            PrintKind::StackProtectorStrategies => {
304                writeln!(
305                    out,
306                    r#"Available stack protector strategies:
307    all
308        Generate stack canaries in all functions.
309
310    strong
311        Generate stack canaries in a function if it either:
312        - has a local variable of `[T; N]` type, regardless of `T` and `N`
313        - takes the address of a local variable.
314
315          (Note that a local variable being borrowed is not equivalent to its
316          address being taken: e.g. some borrows may be removed by optimization,
317          while by-value argument passing may be implemented with reference to a
318          local stack variable in the ABI.)
319
320    basic
321        Generate stack canaries in functions with local variables of `[T; N]`
322        type, where `T` is byte-sized and `N` >= 8.
323
324    none
325        Do not generate stack canaries.
326"#
327                )
328                .unwrap();
329            }
330            _other => llvm_util::print(req, out, sess),
331        }
332    }
333
334    fn print_passes(&self) {
335        llvm_util::print_passes();
336    }
337
338    fn print_version(&self) {
339        llvm_util::print_version();
340    }
341
342    fn target_features_cfg(&self, sess: &Session, allow_unstable: bool) -> Vec<Symbol> {
343        target_features_cfg(sess, allow_unstable)
344    }
345
346    fn codegen_crate<'tcx>(
347        &self,
348        tcx: TyCtxt<'tcx>,
349        metadata: EncodedMetadata,
350        need_metadata_module: bool,
351    ) -> Box<dyn Any> {
352        Box::new(rustc_codegen_ssa::base::codegen_crate(
353            LlvmCodegenBackend(()),
354            tcx,
355            crate::llvm_util::target_cpu(tcx.sess).to_string(),
356            metadata,
357            need_metadata_module,
358        ))
359    }
360
361    fn join_codegen(
362        &self,
363        ongoing_codegen: Box<dyn Any>,
364        sess: &Session,
365        outputs: &OutputFilenames,
366    ) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>) {
367        let (codegen_results, work_products) = ongoing_codegen
368            .downcast::<rustc_codegen_ssa::back::write::OngoingCodegen<LlvmCodegenBackend>>()
369            .expect("Expected LlvmCodegenBackend's OngoingCodegen, found Box<Any>")
370            .join(sess);
371
372        if sess.opts.unstable_opts.llvm_time_trace {
373            sess.time("llvm_dump_timing_file", || {
374                let file_name = outputs.with_extension("llvm_timings.json");
375                llvm_util::time_trace_profiler_finish(&file_name);
376            });
377        }
378
379        (codegen_results, work_products)
380    }
381
382    fn link(&self, sess: &Session, codegen_results: CodegenResults, outputs: &OutputFilenames) {
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(sess, &LlvmArchiveBuilderBuilder, codegen_results, outputs);
390    }
391}
392
393pub struct ModuleLlvm {
394    llcx: &'static mut llvm::Context,
395    llmod_raw: *const llvm::Module,
396
397    // This field is `ManuallyDrop` because it is important that the `TargetMachine`
398    // is disposed prior to the `Context` being disposed otherwise UAFs can occur.
399    tm: ManuallyDrop<OwnedTargetMachine>,
400}
401
402unsafe impl Send for ModuleLlvm {}
403unsafe impl Sync for ModuleLlvm {}
404
405impl ModuleLlvm {
406    fn new(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
407        unsafe {
408            let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
409            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
410            ModuleLlvm {
411                llmod_raw,
412                llcx,
413                tm: ManuallyDrop::new(create_target_machine(tcx, mod_name)),
414            }
415        }
416    }
417
418    fn new_metadata(tcx: TyCtxt<'_>, mod_name: &str) -> Self {
419        unsafe {
420            let llcx = llvm::LLVMRustContextCreate(tcx.sess.fewer_names());
421            let llmod_raw = context::create_module(tcx, llcx, mod_name) as *const _;
422            ModuleLlvm {
423                llmod_raw,
424                llcx,
425                tm: ManuallyDrop::new(create_informational_target_machine(tcx.sess, false)),
426            }
427        }
428    }
429
430    fn parse(
431        cgcx: &CodegenContext<LlvmCodegenBackend>,
432        name: &CStr,
433        buffer: &[u8],
434        dcx: DiagCtxtHandle<'_>,
435    ) -> Result<Self, FatalError> {
436        unsafe {
437            let llcx = llvm::LLVMRustContextCreate(cgcx.fewer_names);
438            let llmod_raw = back::lto::parse_module(llcx, name, buffer, dcx)?;
439            let tm_factory_config = TargetMachineFactoryConfig::new(cgcx, name.to_str().unwrap());
440            let tm = match (cgcx.tm_factory)(tm_factory_config) {
441                Ok(m) => m,
442                Err(e) => {
443                    return Err(dcx.emit_almost_fatal(ParseTargetMachineConfig(e)));
444                }
445            };
446
447            Ok(ModuleLlvm { llmod_raw, llcx, tm: ManuallyDrop::new(tm) })
448        }
449    }
450
451    fn llmod(&self) -> &llvm::Module {
452        unsafe { &*self.llmod_raw }
453    }
454}
455
456impl Drop for ModuleLlvm {
457    fn drop(&mut self) {
458        unsafe {
459            ManuallyDrop::drop(&mut self.tm);
460            llvm::LLVMContextDispose(&mut *(self.llcx as *mut _));
461        }
462    }
463}