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