1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
2 #![feature(box_patterns)]
3 #![feature(try_blocks)]
6 #![feature(associated_type_bounds)]
7 #![feature(strict_provenance)]
8 #![feature(int_roundings)]
9 #![feature(if_let_guard)]
10 #![recursion_limit = "256"]
11 #![allow(rustc::potential_query_instability)]
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.
18 extern crate rustc_macros;
22 extern crate rustc_middle;
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_middle::dep_graph::WorkProduct;
29 use rustc_middle::middle::dependency_format::Dependencies;
30 use rustc_middle::middle::exported_symbols::SymbolExportKind;
31 use rustc_middle::ty::query::{ExternProviders, Providers};
32 use rustc_serialize::opaque::{MemDecoder, MemEncoder};
33 use rustc_serialize::{Decodable, Decoder, Encodable, 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 rustc_span::DebuggerVisualizerFile;
39 use std::collections::BTreeSet;
40 use std::path::{Path, PathBuf};
51 pub mod target_features;
54 pub struct ModuleCodegen<M> {
55 /// The name of the module. When the crate may be saved between
56 /// compilations, incremental compilation requires that name be
57 /// unique amongst **all** crates. Therefore, it should contain
58 /// something unique to this crate (e.g., a module path) as well
59 /// as the crate name and disambiguator.
60 /// We currently generate these names via CodegenUnit::build_cgu_name().
66 impl<M> ModuleCodegen<M> {
67 pub fn into_compiled_module(
72 outputs: &OutputFilenames,
74 let object = emit_obj.then(|| outputs.temp_path(OutputType::Object, Some(&self.name)));
75 let dwarf_object = emit_dwarf_obj.then(|| outputs.temp_path_dwo(Some(&self.name)));
76 let bytecode = emit_bc.then(|| outputs.temp_path(OutputType::Bitcode, Some(&self.name)));
78 CompiledModule { name: self.name.clone(), kind: self.kind, object, dwarf_object, bytecode }
82 #[derive(Debug, Encodable, Decodable)]
83 pub struct CompiledModule {
86 pub object: Option<PathBuf>,
87 pub dwarf_object: Option<PathBuf>,
88 pub bytecode: Option<PathBuf>,
91 pub struct CachedModuleCodegen {
93 pub source: WorkProduct,
96 #[derive(Copy, Clone, Debug, PartialEq, Encodable, Decodable)]
103 bitflags::bitflags! {
104 pub struct MemFlags: u8 {
105 const VOLATILE = 1 << 0;
106 const NONTEMPORAL = 1 << 1;
107 const UNALIGNED = 1 << 2;
111 #[derive(Clone, Debug, Encodable, Decodable, HashStable)]
112 pub struct NativeLib {
113 pub kind: NativeLibKind,
114 pub name: Option<Symbol>,
115 pub cfg: Option<ast::MetaItem>,
116 pub verbatim: Option<bool>,
117 pub dll_imports: Vec<cstore::DllImport>,
120 impl From<&cstore::NativeLib> for NativeLib {
121 fn from(lib: &cstore::NativeLib) -> Self {
125 cfg: lib.cfg.clone(),
126 verbatim: lib.verbatim,
127 dll_imports: lib.dll_imports.clone(),
132 /// Misc info we load from metadata to persist beyond the tcx.
134 /// Note: though `CrateNum` is only meaningful within the same tcx, information within `CrateInfo`
135 /// is self-contained. `CrateNum` can be viewed as a unique identifier within a `CrateInfo`, where
136 /// `used_crate_source` contains all `CrateSource` of the dependents, and maintains a mapping from
137 /// identifiers (`CrateNum`) to `CrateSource`. The other fields map `CrateNum` to the crate's own
138 /// additional properties, so that effectively we can retrieve each dependent crate's `CrateSource`
139 /// and the corresponding properties without referencing information outside of a `CrateInfo`.
140 #[derive(Debug, Encodable, Decodable)]
141 pub struct CrateInfo {
142 pub target_cpu: String,
143 pub exported_symbols: FxHashMap<CrateType, Vec<String>>,
144 pub linked_symbols: FxHashMap<CrateType, Vec<(String, SymbolExportKind)>>,
145 pub local_crate_name: Symbol,
146 pub compiler_builtins: Option<CrateNum>,
147 pub profiler_runtime: Option<CrateNum>,
148 pub is_no_builtins: FxHashSet<CrateNum>,
149 pub native_libraries: FxHashMap<CrateNum, Vec<NativeLib>>,
150 pub crate_name: FxHashMap<CrateNum, Symbol>,
151 pub used_libraries: Vec<NativeLib>,
152 pub used_crate_source: FxHashMap<CrateNum, Lrc<CrateSource>>,
153 pub used_crates: Vec<CrateNum>,
154 pub dependency_formats: Lrc<Dependencies>,
155 pub windows_subsystem: Option<String>,
156 pub natvis_debugger_visualizers: BTreeSet<DebuggerVisualizerFile>,
159 #[derive(Encodable, Decodable)]
160 pub struct CodegenResults {
161 pub modules: Vec<CompiledModule>,
162 pub allocator_module: Option<CompiledModule>,
163 pub metadata_module: Option<CompiledModule>,
164 pub metadata: rustc_metadata::EncodedMetadata,
165 pub crate_info: CrateInfo,
168 pub enum CodegenErrors<'a> {
171 EncodingVersionMismatch { version_array: String, rlink_version: u32 },
172 RustcVersionMismatch { rustc_version: String, current_version: &'a str },
175 pub fn provide(providers: &mut Providers) {
176 crate::back::symbol_export::provide(providers);
177 crate::base::provide(providers);
178 crate::target_features::provide(providers);
181 pub fn provide_extern(providers: &mut ExternProviders) {
182 crate::back::symbol_export::provide_extern(providers);
185 /// Checks if the given filename ends with the `.rcgu.o` extension that `rustc`
186 /// uses for the object files it generates.
187 pub fn looks_like_rust_object_file(filename: &str) -> bool {
188 let path = Path::new(filename);
189 let ext = path.extension().and_then(|s| s.to_str());
190 if ext != Some(OutputType::Object.extension()) {
191 // The file name does not end with ".o", so it can't be an object file.
195 // Strip the ".o" at the end
196 let ext2 = path.file_stem().and_then(|s| Path::new(s).extension()).and_then(|s| s.to_str());
198 // Check if the "inner" extension
199 ext2 == Some(RUST_CGU_EXT)
202 const RLINK_VERSION: u32 = 1;
203 const RLINK_MAGIC: &[u8] = b"rustlink";
205 const RUSTC_VERSION: Option<&str> = option_env!("CFG_VERSION");
207 impl CodegenResults {
208 pub fn serialize_rlink(codegen_results: &CodegenResults) -> Vec<u8> {
209 let mut encoder = MemEncoder::new();
210 encoder.emit_raw_bytes(RLINK_MAGIC);
211 // `emit_raw_bytes` is used to make sure that the version representation does not depend on
212 // Encoder's inner representation of `u32`.
213 encoder.emit_raw_bytes(&RLINK_VERSION.to_be_bytes());
214 encoder.emit_str(RUSTC_VERSION.unwrap());
215 Encodable::encode(codegen_results, &mut encoder);
219 pub fn deserialize_rlink<'a>(data: Vec<u8>) -> Result<Self, CodegenErrors<'a>> {
220 // The Decodable machinery is not used here because it panics if the input data is invalid
221 // and because its internal representation may change.
222 if !data.starts_with(RLINK_MAGIC) {
223 return Err(CodegenErrors::WrongFileType);
225 let data = &data[RLINK_MAGIC.len()..];
227 return Err(CodegenErrors::EmptyVersionNumber);
230 let mut version_array: [u8; 4] = Default::default();
231 version_array.copy_from_slice(&data[..4]);
232 if u32::from_be_bytes(version_array) != RLINK_VERSION {
233 return Err(CodegenErrors::EncodingVersionMismatch {
234 version_array: String::from_utf8_lossy(&version_array).to_string(),
235 rlink_version: RLINK_VERSION,
239 let mut decoder = MemDecoder::new(&data[4..], 0);
240 let rustc_version = decoder.read_str();
241 let current_version = RUSTC_VERSION.unwrap();
242 if rustc_version != current_version {
243 return Err(CodegenErrors::RustcVersionMismatch {
244 rustc_version: rustc_version.to_string(),
249 let codegen_results = CodegenResults::decode(&mut decoder);