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