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