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