1 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
3 #![feature(rustdoc_internals)]
4 #![allow(internal_features)]
5 #![feature(associated_type_bounds)]
6 #![feature(box_patterns)]
7 #![feature(if_let_guard)]
8 #![feature(let_chains)]
9 #![feature(negative_impls)]
10 #![feature(strict_provenance)]
11 #![feature(try_blocks)]
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 backend.
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
::debugger_visualizer
::DebuggerVisualizerFile
;
30 use rustc_middle
::middle
::dependency_format
::Dependencies
;
31 use rustc_middle
::middle
::exported_symbols
::SymbolExportKind
;
32 use rustc_middle
::util
::Providers
;
33 use rustc_serialize
::opaque
::{FileEncoder, MemDecoder}
;
34 use rustc_serialize
::{Decodable, Decoder, Encodable, Encoder}
;
35 use rustc_session
::config
::{CrateType, OutputFilenames, OutputType, RUST_CGU_EXT}
;
36 use rustc_session
::cstore
::{self, CrateSource}
;
37 use rustc_session
::utils
::NativeLibKind
;
38 use rustc_session
::Session
;
39 use rustc_span
::symbol
::Symbol
;
40 use std
::collections
::BTreeSet
;
42 use std
::path
::{Path, PathBuf}
;
44 pub mod assert_module_sources
;
47 pub mod codegen_attrs
;
55 pub mod target_features
;
58 rustc_fluent_macro
::fluent_messages
! { "../messages.ftl" }
60 pub struct ModuleCodegen
<M
> {
61 /// The name of the module. When the crate may be saved between
62 /// compilations, incremental compilation requires that name be
63 /// unique amongst **all** crates. Therefore, it should contain
64 /// something unique to this crate (e.g., a module path) as well
65 /// as the crate name and disambiguator.
66 /// We currently generate these names via CodegenUnit::build_cgu_name().
72 impl<M
> ModuleCodegen
<M
> {
73 pub fn into_compiled_module(
78 outputs
: &OutputFilenames
,
80 let object
= emit_obj
.then(|| outputs
.temp_path(OutputType
::Object
, Some(&self.name
)));
81 let dwarf_object
= emit_dwarf_obj
.then(|| outputs
.temp_path_dwo(Some(&self.name
)));
82 let bytecode
= emit_bc
.then(|| outputs
.temp_path(OutputType
::Bitcode
, Some(&self.name
)));
84 CompiledModule { name: self.name.clone(), kind: self.kind, object, dwarf_object, bytecode }
88 #[derive(Debug, Encodable, Decodable)]
89 pub struct CompiledModule
{
92 pub object
: Option
<PathBuf
>,
93 pub dwarf_object
: Option
<PathBuf
>,
94 pub bytecode
: Option
<PathBuf
>,
97 pub struct CachedModuleCodegen
{
99 pub source
: WorkProduct
,
102 #[derive(Copy, Clone, Debug, PartialEq, Encodable, Decodable)]
103 pub enum ModuleKind
{
109 bitflags
::bitflags
! {
110 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
111 pub struct MemFlags
: u8 {
112 const VOLATILE
= 1 << 0;
113 const NONTEMPORAL
= 1 << 1;
114 const UNALIGNED
= 1 << 2;
118 #[derive(Clone, Debug, Encodable, Decodable, HashStable)]
119 pub struct NativeLib
{
120 pub kind
: NativeLibKind
,
122 pub filename
: Option
<Symbol
>,
123 pub cfg
: Option
<ast
::MetaItem
>,
125 pub dll_imports
: Vec
<cstore
::DllImport
>,
128 impl From
<&cstore
::NativeLib
> for NativeLib
{
129 fn from(lib
: &cstore
::NativeLib
) -> Self {
132 filename
: lib
.filename
,
134 cfg
: lib
.cfg
.clone(),
135 verbatim
: lib
.verbatim
.unwrap_or(false),
136 dll_imports
: lib
.dll_imports
.clone(),
141 /// Misc info we load from metadata to persist beyond the tcx.
143 /// Note: though `CrateNum` is only meaningful within the same tcx, information within `CrateInfo`
144 /// is self-contained. `CrateNum` can be viewed as a unique identifier within a `CrateInfo`, where
145 /// `used_crate_source` contains all `CrateSource` of the dependents, and maintains a mapping from
146 /// identifiers (`CrateNum`) to `CrateSource`. The other fields map `CrateNum` to the crate's own
147 /// additional properties, so that effectively we can retrieve each dependent crate's `CrateSource`
148 /// and the corresponding properties without referencing information outside of a `CrateInfo`.
149 #[derive(Debug, Encodable, Decodable)]
150 pub struct CrateInfo
{
151 pub target_cpu
: String
,
152 pub crate_types
: Vec
<CrateType
>,
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
>,
169 #[derive(Encodable, Decodable)]
170 pub struct CodegenResults
{
171 pub modules
: Vec
<CompiledModule
>,
172 pub allocator_module
: Option
<CompiledModule
>,
173 pub metadata_module
: Option
<CompiledModule
>,
174 pub metadata
: rustc_metadata
::EncodedMetadata
,
175 pub crate_info
: CrateInfo
,
178 pub enum CodegenErrors
{
181 EncodingVersionMismatch { version_array: String, rlink_version: u32 }
,
182 RustcVersionMismatch { rustc_version: String }
,
185 pub fn provide(providers
: &mut Providers
) {
186 crate::back
::symbol_export
::provide(providers
);
187 crate::base
::provide(providers
);
188 crate::target_features
::provide(providers
);
189 crate::codegen_attrs
::provide(providers
);
192 /// Checks if the given filename ends with the `.rcgu.o` extension that `rustc`
193 /// uses for the object files it generates.
194 pub fn looks_like_rust_object_file(filename
: &str) -> bool
{
195 let path
= Path
::new(filename
);
196 let ext
= path
.extension().and_then(|s
| s
.to_str());
197 if ext
!= Some(OutputType
::Object
.extension()) {
198 // The file name does not end with ".o", so it can't be an object file.
202 // Strip the ".o" at the end
203 let ext2
= path
.file_stem().and_then(|s
| Path
::new(s
).extension()).and_then(|s
| s
.to_str());
205 // Check if the "inner" extension
206 ext2
== Some(RUST_CGU_EXT
)
209 const RLINK_VERSION
: u32 = 1;
210 const RLINK_MAGIC
: &[u8] = b
"rustlink";
212 impl CodegenResults
{
213 pub fn serialize_rlink(
216 codegen_results
: &CodegenResults
,
217 outputs
: &OutputFilenames
,
218 ) -> Result
<usize, io
::Error
> {
219 let mut encoder
= FileEncoder
::new(rlink_file
)?
;
220 encoder
.emit_raw_bytes(RLINK_MAGIC
);
221 // `emit_raw_bytes` is used to make sure that the version representation does not depend on
222 // Encoder's inner representation of `u32`.
223 encoder
.emit_raw_bytes(&RLINK_VERSION
.to_be_bytes());
224 encoder
.emit_str(sess
.cfg_version
);
225 Encodable
::encode(codegen_results
, &mut encoder
);
226 Encodable
::encode(outputs
, &mut encoder
);
227 encoder
.finish().map_err(|(_path
, err
)| err
)
230 pub fn deserialize_rlink(
233 ) -> Result
<(Self, OutputFilenames
), 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
);
239 let data
= &data
[RLINK_MAGIC
.len()..];
241 return Err(CodegenErrors
::EmptyVersionNumber
);
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
,
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(),
261 let codegen_results
= CodegenResults
::decode(&mut decoder
);
262 let outputs
= OutputFilenames
::decode(&mut decoder
);
263 Ok((codegen_results
, outputs
))