]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/lib.rs
Rollup merge of #96384 - lcnr:extern-types-similar, r=compiler-errors
[rust.git] / compiler / rustc_codegen_ssa / src / lib.rs
1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
2 #![feature(bool_to_option)]
3 #![feature(box_patterns)]
4 #![feature(try_blocks)]
5 #![feature(let_else)]
6 #![feature(once_cell)]
7 #![feature(nll)]
8 #![feature(associated_type_bounds)]
9 #![feature(strict_provenance)]
10 #![recursion_limit = "256"]
11 #![allow(rustc::potential_query_instability)]
12
13 //! This crate contains codegen code that is used by all codegen backends (LLVM and others).
14 //! The backend-agnostic functions of this crate use functions defined in various traits that
15 //! have to be implemented by each backends.
16
17 #[macro_use]
18 extern crate rustc_macros;
19 #[macro_use]
20 extern crate tracing;
21 #[macro_use]
22 extern crate rustc_middle;
23
24 use rustc_ast as ast;
25 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
26 use rustc_data_structures::sync::Lrc;
27 use rustc_hir::def_id::CrateNum;
28 use rustc_hir::LangItem;
29 use rustc_middle::dep_graph::WorkProduct;
30 use rustc_middle::middle::dependency_format::Dependencies;
31 use rustc_middle::middle::exported_symbols::SymbolExportKind;
32 use rustc_middle::ty::query::{ExternProviders, Providers};
33 use rustc_serialize::{opaque, Decodable, Decoder, Encoder};
34 use rustc_session::config::{CrateType, OutputFilenames, OutputType, RUST_CGU_EXT};
35 use rustc_session::cstore::{self, CrateSource};
36 use rustc_session::utils::NativeLibKind;
37 use rustc_span::symbol::Symbol;
38 use std::path::{Path, PathBuf};
39
40 pub mod back;
41 pub mod base;
42 pub mod common;
43 pub mod coverageinfo;
44 pub mod debuginfo;
45 pub mod glue;
46 pub mod meth;
47 pub mod mir;
48 pub mod mono_item;
49 pub mod target_features;
50 pub mod traits;
51
52 pub struct ModuleCodegen<M> {
53     /// The name of the module. When the crate may be saved between
54     /// compilations, incremental compilation requires that name be
55     /// unique amongst **all** crates. Therefore, it should contain
56     /// something unique to this crate (e.g., a module path) as well
57     /// as the crate name and disambiguator.
58     /// We currently generate these names via CodegenUnit::build_cgu_name().
59     pub name: String,
60     pub module_llvm: M,
61     pub kind: ModuleKind,
62 }
63
64 // FIXME(eddyb) maybe include the crate name in this?
65 pub const METADATA_FILENAME: &str = "lib.rmeta";
66
67 impl<M> ModuleCodegen<M> {
68     pub fn into_compiled_module(
69         self,
70         emit_obj: bool,
71         emit_dwarf_obj: bool,
72         emit_bc: bool,
73         outputs: &OutputFilenames,
74     ) -> CompiledModule {
75         let object = emit_obj.then(|| outputs.temp_path(OutputType::Object, Some(&self.name)));
76         let dwarf_object = emit_dwarf_obj.then(|| outputs.temp_path_dwo(Some(&self.name)));
77         let bytecode = emit_bc.then(|| outputs.temp_path(OutputType::Bitcode, Some(&self.name)));
78
79         CompiledModule { name: self.name.clone(), kind: self.kind, object, dwarf_object, bytecode }
80     }
81 }
82
83 #[derive(Debug, Encodable, Decodable)]
84 pub struct CompiledModule {
85     pub name: String,
86     pub kind: ModuleKind,
87     pub object: Option<PathBuf>,
88     pub dwarf_object: Option<PathBuf>,
89     pub bytecode: Option<PathBuf>,
90 }
91
92 pub struct CachedModuleCodegen {
93     pub name: String,
94     pub source: WorkProduct,
95 }
96
97 #[derive(Copy, Clone, Debug, PartialEq, Encodable, Decodable)]
98 pub enum ModuleKind {
99     Regular,
100     Metadata,
101     Allocator,
102 }
103
104 bitflags::bitflags! {
105     pub struct MemFlags: u8 {
106         const VOLATILE = 1 << 0;
107         const NONTEMPORAL = 1 << 1;
108         const UNALIGNED = 1 << 2;
109     }
110 }
111
112 #[derive(Clone, Debug, Encodable, Decodable, HashStable)]
113 pub struct NativeLib {
114     pub kind: NativeLibKind,
115     pub name: Option<Symbol>,
116     pub cfg: Option<ast::MetaItem>,
117     pub verbatim: Option<bool>,
118     pub dll_imports: Vec<cstore::DllImport>,
119 }
120
121 impl From<&cstore::NativeLib> for NativeLib {
122     fn from(lib: &cstore::NativeLib) -> Self {
123         NativeLib {
124             kind: lib.kind,
125             name: lib.name,
126             cfg: lib.cfg.clone(),
127             verbatim: lib.verbatim,
128             dll_imports: lib.dll_imports.clone(),
129         }
130     }
131 }
132
133 /// Misc info we load from metadata to persist beyond the tcx.
134 ///
135 /// Note: though `CrateNum` is only meaningful within the same tcx, information within `CrateInfo`
136 /// is self-contained. `CrateNum` can be viewed as a unique identifier within a `CrateInfo`, where
137 /// `used_crate_source` contains all `CrateSource` of the dependents, and maintains a mapping from
138 /// identifiers (`CrateNum`) to `CrateSource`. The other fields map `CrateNum` to the crate's own
139 /// additional properties, so that effectively we can retrieve each dependent crate's `CrateSource`
140 /// and the corresponding properties without referencing information outside of a `CrateInfo`.
141 #[derive(Debug, Encodable, Decodable)]
142 pub struct CrateInfo {
143     pub target_cpu: String,
144     pub exported_symbols: FxHashMap<CrateType, Vec<String>>,
145     pub linked_symbols: FxHashMap<CrateType, Vec<(String, SymbolExportKind)>>,
146     pub local_crate_name: Symbol,
147     pub compiler_builtins: Option<CrateNum>,
148     pub profiler_runtime: Option<CrateNum>,
149     pub is_no_builtins: FxHashSet<CrateNum>,
150     pub native_libraries: FxHashMap<CrateNum, Vec<NativeLib>>,
151     pub crate_name: FxHashMap<CrateNum, Symbol>,
152     pub used_libraries: Vec<NativeLib>,
153     pub used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
154     pub used_crates: Vec<CrateNum>,
155     pub lang_item_to_crate: FxHashMap<LangItem, CrateNum>,
156     pub missing_lang_items: FxHashMap<CrateNum, Vec<LangItem>>,
157     pub dependency_formats: Lrc<Dependencies>,
158     pub windows_subsystem: Option<String>,
159 }
160
161 #[derive(Encodable, Decodable)]
162 pub struct CodegenResults {
163     pub modules: Vec<CompiledModule>,
164     pub allocator_module: Option<CompiledModule>,
165     pub metadata_module: Option<CompiledModule>,
166     pub metadata: rustc_metadata::EncodedMetadata,
167     pub crate_info: CrateInfo,
168 }
169
170 pub fn provide(providers: &mut Providers) {
171     crate::back::symbol_export::provide(providers);
172     crate::base::provide(providers);
173     crate::target_features::provide(providers);
174 }
175
176 pub fn provide_extern(providers: &mut ExternProviders) {
177     crate::back::symbol_export::provide_extern(providers);
178 }
179
180 /// Checks if the given filename ends with the `.rcgu.o` extension that `rustc`
181 /// uses for the object files it generates.
182 pub fn looks_like_rust_object_file(filename: &str) -> bool {
183     let path = Path::new(filename);
184     let ext = path.extension().and_then(|s| s.to_str());
185     if ext != Some(OutputType::Object.extension()) {
186         // The file name does not end with ".o", so it can't be an object file.
187         return false;
188     }
189
190     // Strip the ".o" at the end
191     let ext2 = path.file_stem().and_then(|s| Path::new(s).extension()).and_then(|s| s.to_str());
192
193     // Check if the "inner" extension
194     ext2 == Some(RUST_CGU_EXT)
195 }
196
197 const RLINK_VERSION: u32 = 1;
198 const RLINK_MAGIC: &[u8] = b"rustlink";
199
200 const RUSTC_VERSION: Option<&str> = option_env!("CFG_VERSION");
201
202 impl CodegenResults {
203     pub fn serialize_rlink(codegen_results: &CodegenResults) -> Vec<u8> {
204         let mut encoder = opaque::Encoder::new(vec![]);
205         encoder.emit_raw_bytes(RLINK_MAGIC).unwrap();
206         // `emit_raw_bytes` is used to make sure that the version representation does not depend on
207         // Encoder's inner representation of `u32`.
208         encoder.emit_raw_bytes(&RLINK_VERSION.to_be_bytes()).unwrap();
209         encoder.emit_str(RUSTC_VERSION.unwrap()).unwrap();
210
211         let mut encoder = rustc_serialize::opaque::Encoder::new(encoder.into_inner());
212         rustc_serialize::Encodable::encode(codegen_results, &mut encoder).unwrap();
213         encoder.into_inner()
214     }
215
216     pub fn deserialize_rlink(data: Vec<u8>) -> Result<Self, String> {
217         // The Decodable machinery is not used here because it panics if the input data is invalid
218         // and because its internal representation may change.
219         if !data.starts_with(RLINK_MAGIC) {
220             return Err("The input does not look like a .rlink file".to_string());
221         }
222         let data = &data[RLINK_MAGIC.len()..];
223         if data.len() < 4 {
224             return Err("The input does not contain version number".to_string());
225         }
226
227         let mut version_array: [u8; 4] = Default::default();
228         version_array.copy_from_slice(&data[..4]);
229         if u32::from_be_bytes(version_array) != RLINK_VERSION {
230             return Err(".rlink file was produced with encoding version {version_array}, but the current version is {RLINK_VERSION}".to_string());
231         }
232
233         let mut decoder = opaque::Decoder::new(&data[4..], 0);
234         let rustc_version = decoder.read_str();
235         let current_version = RUSTC_VERSION.unwrap();
236         if rustc_version != current_version {
237             return Err(format!(
238                 ".rlink file was produced by rustc version {rustc_version}, but the current version is {current_version}."
239             ));
240         }
241
242         let codegen_results = CodegenResults::decode(&mut decoder);
243         Ok(codegen_results)
244     }
245 }