rustc_codegen_ssa/traits/
backend.rs

1use std::any::Any;
2use std::hash::Hash;
3
4use rustc_ast::expand::allocator::AllocatorKind;
5use rustc_data_structures::fx::FxIndexMap;
6use rustc_data_structures::sync::{DynSend, DynSync};
7use rustc_metadata::EncodedMetadata;
8use rustc_metadata::creader::MetadataLoaderDyn;
9use rustc_middle::dep_graph::{WorkProduct, WorkProductId};
10use rustc_middle::ty::TyCtxt;
11use rustc_middle::util::Providers;
12use rustc_session::Session;
13use rustc_session::config::{self, OutputFilenames, PrintRequest};
14use rustc_span::Symbol;
15
16use super::CodegenObject;
17use super::write::WriteBackendMethods;
18use crate::back::archive::ArArchiveBuilderBuilder;
19use crate::back::link::link_binary;
20use crate::back::write::TargetMachineFactoryFn;
21use crate::{CodegenResults, ModuleCodegen, TargetConfig};
22
23pub trait BackendTypes {
24    type Value: CodegenObject + PartialEq;
25    type Metadata: CodegenObject;
26    type Function: CodegenObject;
27
28    type BasicBlock: Copy;
29    type Type: CodegenObject + PartialEq;
30    type Funclet;
31
32    // FIXME(eddyb) find a common convention for all of the debuginfo-related
33    // names (choose between `Dbg`, `Debug`, `DebugInfo`, `DI` etc.).
34    type DIScope: Copy + Hash + PartialEq + Eq;
35    type DILocation: Copy;
36    type DIVariable: Copy;
37}
38
39pub trait CodegenBackend {
40    /// Locale resources for diagnostic messages - a string the content of the Fluent resource.
41    /// Called before `init` so that all other functions are able to emit translatable diagnostics.
42    fn locale_resource(&self) -> &'static str;
43
44    fn init(&self, _sess: &Session) {}
45
46    fn print(&self, _req: &PrintRequest, _out: &mut String, _sess: &Session) {}
47
48    /// Collect target-specific options that should be set in `cfg(...)`, including
49    /// `target_feature` and support for unstable float types.
50    fn target_config(&self, _sess: &Session) -> TargetConfig {
51        TargetConfig {
52            target_features: vec![],
53            unstable_target_features: vec![],
54            // `true` is used as a default so backends need to acknowledge when they do not
55            // support the float types, rather than accidentally quietly skipping all tests.
56            has_reliable_f16: true,
57            has_reliable_f16_math: true,
58            has_reliable_f128: true,
59            has_reliable_f128_math: true,
60        }
61    }
62
63    fn print_passes(&self) {}
64
65    fn print_version(&self) {}
66
67    /// The metadata loader used to load rlib and dylib metadata.
68    ///
69    /// Alternative codegen backends may want to use different rlib or dylib formats than the
70    /// default native static archives and dynamic libraries.
71    fn metadata_loader(&self) -> Box<MetadataLoaderDyn> {
72        Box::new(crate::back::metadata::DefaultMetadataLoader)
73    }
74
75    fn provide(&self, _providers: &mut Providers) {}
76
77    fn codegen_crate<'tcx>(
78        &self,
79        tcx: TyCtxt<'tcx>,
80        metadata: EncodedMetadata,
81        need_metadata_module: bool,
82    ) -> Box<dyn Any>;
83
84    /// This is called on the returned `Box<dyn Any>` from [`codegen_crate`](Self::codegen_crate)
85    ///
86    /// # Panics
87    ///
88    /// Panics when the passed `Box<dyn Any>` was not returned by [`codegen_crate`](Self::codegen_crate).
89    fn join_codegen(
90        &self,
91        ongoing_codegen: Box<dyn Any>,
92        sess: &Session,
93        outputs: &OutputFilenames,
94    ) -> (CodegenResults, FxIndexMap<WorkProductId, WorkProduct>);
95
96    /// This is called on the returned [`CodegenResults`] from [`join_codegen`](Self::join_codegen).
97    fn link(&self, sess: &Session, codegen_results: CodegenResults, outputs: &OutputFilenames) {
98        link_binary(sess, &ArArchiveBuilderBuilder, codegen_results, outputs);
99    }
100}
101
102pub trait ExtraBackendMethods:
103    CodegenBackend + WriteBackendMethods + Sized + Send + Sync + DynSend + DynSync
104{
105    fn codegen_allocator<'tcx>(
106        &self,
107        tcx: TyCtxt<'tcx>,
108        module_name: &str,
109        kind: AllocatorKind,
110        alloc_error_handler_kind: AllocatorKind,
111    ) -> Self::Module;
112
113    /// This generates the codegen unit and returns it along with
114    /// a `u64` giving an estimate of the unit's processing cost.
115    fn compile_codegen_unit(
116        &self,
117        tcx: TyCtxt<'_>,
118        cgu_name: Symbol,
119    ) -> (ModuleCodegen<Self::Module>, u64);
120
121    fn target_machine_factory(
122        &self,
123        sess: &Session,
124        opt_level: config::OptLevel,
125        target_features: &[String],
126    ) -> TargetMachineFactoryFn<Self>;
127
128    fn spawn_named_thread<F, T>(
129        _time_trace: bool,
130        name: String,
131        f: F,
132    ) -> std::io::Result<std::thread::JoinHandle<T>>
133    where
134        F: FnOnce() -> T,
135        F: Send + 'static,
136        T: Send + 'static,
137    {
138        std::thread::Builder::new().name(name).spawn(f)
139    }
140
141    /// Returns `true` if this backend can be safely called from multiple threads.
142    ///
143    /// Defaults to `true`.
144    fn supports_parallel(&self) -> bool {
145        true
146    }
147}