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