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