]>
Commit | Line | Data |
---|---|---|
c295e0f8 | 1 | use crate::rmeta::def_path_hash_map::DefPathHashMapRef; |
3dfed10e | 2 | use crate::rmeta::table::{FixedSizeEncoding, TableBuilder}; |
dfeec247 | 3 | use crate::rmeta::*; |
92a42be0 | 4 | |
5869c6ff | 5 | use rustc_data_structures::fx::{FxHashMap, FxIndexSet}; |
ba9703b0 | 6 | use rustc_data_structures::stable_hasher::StableHasher; |
5869c6ff | 7 | use rustc_data_structures::sync::{join, par_iter, Lrc, ParallelIterator}; |
ba9703b0 | 8 | use rustc_hir as hir; |
5869c6ff | 9 | use rustc_hir::def::{CtorOf, DefKind}; |
6a06907d XL |
10 | use rustc_hir::def_id::{ |
11 | CrateNum, DefId, DefIndex, LocalDefId, CRATE_DEF_ID, CRATE_DEF_INDEX, LOCAL_CRATE, | |
12 | }; | |
fc512014 | 13 | use rustc_hir::definitions::DefPathData; |
ba9703b0 | 14 | use rustc_hir::intravisit::{self, NestedVisitorMap, Visitor}; |
5869c6ff | 15 | use rustc_hir::itemlikevisit::ItemLikeVisitor; |
ba9703b0 | 16 | use rustc_hir::lang_items; |
dfeec247 | 17 | use rustc_hir::{AnonConst, GenericParamKind}; |
f035d41b | 18 | use rustc_index::bit_set::GrowableBitSet; |
dfeec247 | 19 | use rustc_index::vec::Idx; |
ba9703b0 | 20 | use rustc_middle::hir::map::Map; |
ba9703b0 XL |
21 | use rustc_middle::middle::dependency_format::Linkage; |
22 | use rustc_middle::middle::exported_symbols::{ | |
23 | metadata_symbol_name, ExportedSymbol, SymbolExportLevel, | |
24 | }; | |
3dfed10e | 25 | use rustc_middle::mir::interpret; |
c295e0f8 | 26 | use rustc_middle::thir; |
ba9703b0 | 27 | use rustc_middle::traits::specialization_graph; |
3dfed10e | 28 | use rustc_middle::ty::codec::TyEncoder; |
ba9703b0 | 29 | use rustc_middle::ty::{self, SymbolName, Ty, TyCtxt}; |
3dfed10e | 30 | use rustc_serialize::{opaque, Encodable, Encoder}; |
f9f354fc | 31 | use rustc_session::config::CrateType; |
c295e0f8 | 32 | use rustc_session::cstore::{ForeignModule, LinkagePreference, NativeLib}; |
f035d41b | 33 | use rustc_span::symbol::{sym, Ident, Symbol}; |
3dfed10e | 34 | use rustc_span::{self, ExternalSource, FileName, SourceFile, Span, SyntaxContext}; |
17df50a5 | 35 | use rustc_span::{ |
136023e0 | 36 | hygiene::{ExpnIndex, HygieneEncodeContext, MacroKind}, |
17df50a5 XL |
37 | RealFileName, |
38 | }; | |
ba9703b0 | 39 | use rustc_target::abi::VariantIdx; |
ff7c6d11 | 40 | use std::hash::Hash; |
e74abb32 | 41 | use std::num::NonZeroUsize; |
7cac9316 | 42 | use std::path::Path; |
3dfed10e | 43 | use tracing::{debug, trace}; |
9e0c209e | 44 | |
3dfed10e | 45 | pub(super) struct EncodeContext<'a, 'tcx> { |
8faf50e0 | 46 | opaque: opaque::Encoder, |
e74abb32 | 47 | tcx: TyCtxt<'tcx>, |
1b1a35ee | 48 | feat: &'tcx rustc_feature::Features, |
dc9dc135 | 49 | |
ba9703b0 | 50 | tables: TableBuilders<'tcx>, |
9e0c209e SL |
51 | |
52 | lazy_state: LazyState, | |
476ff2be | 53 | type_shorthands: FxHashMap<Ty<'tcx>, usize>, |
5869c6ff | 54 | predicate_shorthands: FxHashMap<ty::PredicateKind<'tcx>, usize>, |
2c00a5a8 | 55 | |
3dfed10e | 56 | interpret_allocs: FxIndexSet<interpret::AllocId>, |
0531ce1d | 57 | |
2c00a5a8 | 58 | // This is used to speed up Span encoding. |
f035d41b XL |
59 | // The `usize` is an index into the `MonotonicVec` |
60 | // that stores the `SourceFile` | |
61 | source_file_cache: (Lrc<SourceFile>, usize), | |
62 | // The indices (into the `SourceMap`'s `MonotonicVec`) | |
63 | // of all of the `SourceFiles` that we need to serialize. | |
64 | // When we serialize a `Span`, we insert the index of its | |
65 | // `SourceFile` into the `GrowableBitSet`. | |
66 | // | |
67 | // This needs to be a `GrowableBitSet` and not a | |
68 | // regular `BitSet` because we may actually import new `SourceFiles` | |
69 | // during metadata encoding, due to executing a query | |
70 | // with a result containing a foreign `Span`. | |
71 | required_source_files: Option<GrowableBitSet<usize>>, | |
72 | is_proc_macro: bool, | |
3dfed10e | 73 | hygiene_ctxt: &'a HygieneEncodeContext, |
9e0c209e SL |
74 | } |
75 | ||
1b1a35ee XL |
76 | /// If the current crate is a proc-macro, returns early with `Lazy:empty()`. |
77 | /// This is useful for skipping the encoding of things that aren't needed | |
78 | /// for proc-macro crates. | |
79 | macro_rules! empty_proc_macro { | |
80 | ($self:ident) => { | |
81 | if $self.is_proc_macro { | |
82 | return Lazy::empty(); | |
83 | } | |
84 | }; | |
85 | } | |
86 | ||
9e0c209e SL |
87 | macro_rules! encoder_methods { |
88 | ($($name:ident($ty:ty);)*) => { | |
89 | $(fn $name(&mut self, value: $ty) -> Result<(), Self::Error> { | |
90 | self.opaque.$name(value) | |
91 | })* | |
b039eaaf SL |
92 | } |
93 | } | |
94 | ||
3dfed10e | 95 | impl<'a, 'tcx> Encoder for EncodeContext<'a, 'tcx> { |
8faf50e0 | 96 | type Error = <opaque::Encoder as Encoder>::Error; |
b039eaaf | 97 | |
f9f354fc | 98 | #[inline] |
b7449926 | 99 | fn emit_unit(&mut self) -> Result<(), Self::Error> { |
9e0c209e | 100 | Ok(()) |
b039eaaf SL |
101 | } |
102 | ||
9e0c209e SL |
103 | encoder_methods! { |
104 | emit_usize(usize); | |
32a655c1 | 105 | emit_u128(u128); |
9e0c209e SL |
106 | emit_u64(u64); |
107 | emit_u32(u32); | |
108 | emit_u16(u16); | |
109 | emit_u8(u8); | |
110 | ||
111 | emit_isize(isize); | |
32a655c1 | 112 | emit_i128(i128); |
9e0c209e SL |
113 | emit_i64(i64); |
114 | emit_i32(i32); | |
115 | emit_i16(i16); | |
116 | emit_i8(i8); | |
117 | ||
118 | emit_bool(bool); | |
119 | emit_f64(f64); | |
120 | emit_f32(f32); | |
121 | emit_char(char); | |
122 | emit_str(&str); | |
cdc7bbd5 | 123 | emit_raw_bytes(&[u8]); |
b039eaaf SL |
124 | } |
125 | } | |
126 | ||
3dfed10e XL |
127 | impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>> |
128 | for Lazy<T> | |
129 | { | |
130 | fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { | |
131 | e.emit_lazy_distance(*self) | |
9e0c209e | 132 | } |
223e47cc LB |
133 | } |
134 | ||
3dfed10e XL |
135 | impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>> |
136 | for Lazy<[T]> | |
137 | { | |
138 | fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { | |
139 | e.emit_usize(self.meta)?; | |
140 | if self.meta == 0 { | |
9e0c209e SL |
141 | return Ok(()); |
142 | } | |
3dfed10e | 143 | e.emit_lazy_distance(*self) |
9e0c209e | 144 | } |
223e47cc LB |
145 | } |
146 | ||
3dfed10e XL |
147 | impl<'a, 'tcx, I: Idx, T: Encodable<EncodeContext<'a, 'tcx>>> Encodable<EncodeContext<'a, 'tcx>> |
148 | for Lazy<Table<I, T>> | |
dfeec247 XL |
149 | where |
150 | Option<T>: FixedSizeEncoding, | |
e74abb32 | 151 | { |
3dfed10e XL |
152 | fn encode(&self, e: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { |
153 | e.emit_usize(self.meta)?; | |
154 | e.emit_lazy_distance(*self) | |
e74abb32 XL |
155 | } |
156 | } | |
157 | ||
1b1a35ee XL |
158 | impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for CrateNum { |
159 | fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { | |
160 | if *self != LOCAL_CRATE && s.is_proc_macro { | |
161 | panic!("Attempted to encode non-local CrateNum {:?} for proc-macro crate", self); | |
162 | } | |
163 | s.emit_u32(self.as_u32()) | |
164 | } | |
165 | } | |
166 | ||
3dfed10e XL |
167 | impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for DefIndex { |
168 | fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { | |
169 | s.emit_u32(self.as_u32()) | |
abe05a73 XL |
170 | } |
171 | } | |
172 | ||
136023e0 XL |
173 | impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnIndex { |
174 | fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { | |
175 | s.emit_u32(self.as_u32()) | |
176 | } | |
177 | } | |
178 | ||
3dfed10e XL |
179 | impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for SyntaxContext { |
180 | fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { | |
181 | rustc_span::hygiene::raw_encode_syntax_context(*self, &s.hygiene_ctxt, s) | |
abe05a73 XL |
182 | } |
183 | } | |
184 | ||
3dfed10e XL |
185 | impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for ExpnId { |
186 | fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { | |
136023e0 XL |
187 | if self.krate == LOCAL_CRATE { |
188 | // We will only write details for local expansions. Non-local expansions will fetch | |
189 | // data from the corresponding crate's metadata. | |
190 | // FIXME(#43047) FIXME(#74731) We may eventually want to avoid relying on external | |
191 | // metadata from proc-macro crates. | |
192 | s.hygiene_ctxt.schedule_expn_data_for_encoding(*self); | |
193 | } | |
194 | self.krate.encode(s)?; | |
195 | self.local_id.encode(s) | |
2c00a5a8 XL |
196 | } |
197 | } | |
198 | ||
3dfed10e XL |
199 | impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for Span { |
200 | fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { | |
cdc7bbd5 XL |
201 | let span = self.data(); |
202 | ||
203 | // Don't serialize any `SyntaxContext`s from a proc-macro crate, | |
204 | // since we don't load proc-macro dependencies during serialization. | |
205 | // This means that any hygiene information from macros used *within* | |
206 | // a proc-macro crate (e.g. invoking a macro that expands to a proc-macro | |
207 | // definition) will be lost. | |
208 | // | |
209 | // This can show up in two ways: | |
210 | // | |
211 | // 1. Any hygiene information associated with identifier of | |
212 | // a proc macro (e.g. `#[proc_macro] pub fn $name`) will be lost. | |
213 | // Since proc-macros can only be invoked from a different crate, | |
214 | // real code should never need to care about this. | |
215 | // | |
216 | // 2. Using `Span::def_site` or `Span::mixed_site` will not | |
217 | // include any hygiene information associated with the definition | |
218 | // site. This means that a proc-macro cannot emit a `$crate` | |
219 | // identifier which resolves to one of its dependencies, | |
220 | // which also should never come up in practice. | |
221 | // | |
222 | // Additionally, this affects `Span::parent`, and any other | |
223 | // span inspection APIs that would otherwise allow traversing | |
224 | // the `SyntaxContexts` associated with a span. | |
225 | // | |
226 | // None of these user-visible effects should result in any | |
227 | // cross-crate inconsistencies (getting one behavior in the same | |
228 | // crate, and a different behavior in another crate) due to the | |
229 | // limited surface that proc-macros can expose. | |
230 | // | |
231 | // IMPORTANT: If this is ever changed, be sure to update | |
232 | // `rustc_span::hygiene::raw_encode_expn_id` to handle | |
233 | // encoding `ExpnData` for proc-macro crates. | |
234 | if s.is_proc_macro { | |
235 | SyntaxContext::root().encode(s)?; | |
236 | } else { | |
237 | span.ctxt.encode(s)?; | |
2c00a5a8 XL |
238 | } |
239 | ||
cdc7bbd5 XL |
240 | if self.is_dummy() { |
241 | return TAG_PARTIAL_SPAN.encode(s); | |
242 | } | |
2c00a5a8 XL |
243 | |
244 | // The Span infrastructure should make sure that this invariant holds: | |
245 | debug_assert!(span.lo <= span.hi); | |
246 | ||
3dfed10e XL |
247 | if !s.source_file_cache.0.contains(span.lo) { |
248 | let source_map = s.tcx.sess.source_map(); | |
b7449926 | 249 | let source_file_index = source_map.lookup_source_file_idx(span.lo); |
3dfed10e | 250 | s.source_file_cache = |
f035d41b | 251 | (source_map.files()[source_file_index].clone(), source_file_index); |
2c00a5a8 XL |
252 | } |
253 | ||
3dfed10e | 254 | if !s.source_file_cache.0.contains(span.hi) { |
2c00a5a8 XL |
255 | // Unfortunately, macro expansion still sometimes generates Spans |
256 | // that malformed in this way. | |
cdc7bbd5 | 257 | return TAG_PARTIAL_SPAN.encode(s); |
2c00a5a8 XL |
258 | } |
259 | ||
3dfed10e | 260 | let source_files = s.required_source_files.as_mut().expect("Already encoded SourceMap!"); |
f035d41b | 261 | // Record the fact that we need to encode the data for this `SourceFile` |
3dfed10e | 262 | source_files.insert(s.source_file_cache.1); |
f035d41b | 263 | |
ba9703b0 XL |
264 | // There are two possible cases here: |
265 | // 1. This span comes from a 'foreign' crate - e.g. some crate upstream of the | |
266 | // crate we are writing metadata for. When the metadata for *this* crate gets | |
267 | // deserialized, the deserializer will need to know which crate it originally came | |
268 | // from. We use `TAG_VALID_SPAN_FOREIGN` to indicate that a `CrateNum` should | |
269 | // be deserialized after the rest of the span data, which tells the deserializer | |
270 | // which crate contains the source map information. | |
271 | // 2. This span comes from our own crate. No special hamdling is needed - we just | |
272 | // write `TAG_VALID_SPAN_LOCAL` to let the deserializer know that it should use | |
273 | // our own source map information. | |
f035d41b XL |
274 | // |
275 | // If we're a proc-macro crate, we always treat this as a local `Span`. | |
276 | // In `encode_source_map`, we serialize foreign `SourceFile`s into our metadata | |
277 | // if we're a proc-macro crate. | |
278 | // This allows us to avoid loading the dependencies of proc-macro crates: all of | |
279 | // the information we need to decode `Span`s is stored in the proc-macro crate. | |
3dfed10e | 280 | let (tag, lo, hi) = if s.source_file_cache.0.is_imported() && !s.is_proc_macro { |
ba9703b0 XL |
281 | // To simplify deserialization, we 'rebase' this span onto the crate it originally came from |
282 | // (the crate that 'owns' the file it references. These rebased 'lo' and 'hi' values | |
283 | // are relative to the source map information for the 'foreign' crate whose CrateNum | |
284 | // we write into the metadata. This allows `imported_source_files` to binary | |
285 | // search through the 'foreign' crate's source map information, using the | |
286 | // deserialized 'lo' and 'hi' values directly. | |
287 | // | |
288 | // All of this logic ensures that the final result of deserialization is a 'normal' | |
289 | // Span that can be used without any additional trouble. | |
290 | let external_start_pos = { | |
291 | // Introduce a new scope so that we drop the 'lock()' temporary | |
3dfed10e | 292 | match &*s.source_file_cache.0.external_src.lock() { |
ba9703b0 XL |
293 | ExternalSource::Foreign { original_start_pos, .. } => *original_start_pos, |
294 | src => panic!("Unexpected external source {:?}", src), | |
295 | } | |
296 | }; | |
3dfed10e XL |
297 | let lo = (span.lo - s.source_file_cache.0.start_pos) + external_start_pos; |
298 | let hi = (span.hi - s.source_file_cache.0.start_pos) + external_start_pos; | |
e74abb32 | 299 | |
ba9703b0 XL |
300 | (TAG_VALID_SPAN_FOREIGN, lo, hi) |
301 | } else { | |
302 | (TAG_VALID_SPAN_LOCAL, span.lo, span.hi) | |
303 | }; | |
304 | ||
3dfed10e XL |
305 | tag.encode(s)?; |
306 | lo.encode(s)?; | |
2c00a5a8 XL |
307 | |
308 | // Encode length which is usually less than span.hi and profits more | |
309 | // from the variable-length integer encoding that we use. | |
ba9703b0 | 310 | let len = hi - lo; |
3dfed10e XL |
311 | len.encode(s)?; |
312 | ||
ba9703b0 | 313 | if tag == TAG_VALID_SPAN_FOREIGN { |
3dfed10e XL |
314 | // This needs to be two lines to avoid holding the `s.source_file_cache` |
315 | // while calling `cnum.encode(s)` | |
316 | let cnum = s.source_file_cache.0.cnum; | |
317 | cnum.encode(s)?; | |
ba9703b0 | 318 | } |
2c00a5a8 | 319 | |
3dfed10e | 320 | Ok(()) |
abe05a73 XL |
321 | } |
322 | } | |
323 | ||
3dfed10e XL |
324 | impl<'a, 'tcx> TyEncoder<'tcx> for EncodeContext<'a, 'tcx> { |
325 | const CLEAR_CROSS_CRATE: bool = true; | |
d9579d0f | 326 | |
3dfed10e XL |
327 | fn position(&self) -> usize { |
328 | self.opaque.position() | |
f035d41b | 329 | } |
f035d41b | 330 | |
3dfed10e XL |
331 | fn type_shorthands(&mut self) -> &mut FxHashMap<Ty<'tcx>, usize> { |
332 | &mut self.type_shorthands | |
0531ce1d | 333 | } |
0531ce1d | 334 | |
5869c6ff | 335 | fn predicate_shorthands(&mut self) -> &mut FxHashMap<ty::PredicateKind<'tcx>, usize> { |
3dfed10e | 336 | &mut self.predicate_shorthands |
2c00a5a8 | 337 | } |
2c00a5a8 | 338 | |
3dfed10e XL |
339 | fn encode_alloc_id( |
340 | &mut self, | |
341 | alloc_id: &rustc_middle::mir::interpret::AllocId, | |
342 | ) -> Result<(), Self::Error> { | |
343 | let (index, _) = self.interpret_allocs.insert_full(*alloc_id); | |
344 | ||
345 | index.encode(self) | |
ff7c6d11 XL |
346 | } |
347 | } | |
348 | ||
c295e0f8 | 349 | impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [thir::abstract_const::Node<'tcx>] { |
1b1a35ee XL |
350 | fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { |
351 | (**self).encode(s) | |
352 | } | |
353 | } | |
354 | ||
3dfed10e XL |
355 | impl<'a, 'tcx> Encodable<EncodeContext<'a, 'tcx>> for &'tcx [(ty::Predicate<'tcx>, Span)] { |
356 | fn encode(&self, s: &mut EncodeContext<'a, 'tcx>) -> opaque::EncodeResult { | |
357 | (**self).encode(s) | |
9e0c209e | 358 | } |
abe05a73 XL |
359 | } |
360 | ||
e1599b0c | 361 | /// Helper trait to allow overloading `EncodeContext::lazy` for iterators. |
3dfed10e XL |
362 | trait EncodeContentsForLazy<'a, 'tcx, T: ?Sized + LazyMeta> { |
363 | fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> T::Meta; | |
e1599b0c XL |
364 | } |
365 | ||
3dfed10e XL |
366 | impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for &T { |
367 | fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { | |
e1599b0c | 368 | self.encode(ecx).unwrap() |
9e0c209e | 369 | } |
e1599b0c XL |
370 | } |
371 | ||
3dfed10e XL |
372 | impl<'a, 'tcx, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, T> for T { |
373 | fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) { | |
e1599b0c XL |
374 | self.encode(ecx).unwrap() |
375 | } | |
376 | } | |
85aaf69f | 377 | |
3dfed10e | 378 | impl<'a, 'tcx, I, T: Encodable<EncodeContext<'a, 'tcx>>> EncodeContentsForLazy<'a, 'tcx, [T]> for I |
dfeec247 XL |
379 | where |
380 | I: IntoIterator, | |
3dfed10e | 381 | I::Item: EncodeContentsForLazy<'a, 'tcx, T>, |
e1599b0c | 382 | { |
3dfed10e | 383 | fn encode_contents_for_lazy(self, ecx: &mut EncodeContext<'a, 'tcx>) -> usize { |
e1599b0c XL |
384 | self.into_iter().map(|value| value.encode_contents_for_lazy(ecx)).count() |
385 | } | |
386 | } | |
387 | ||
60c5eb7d | 388 | // Shorthand for `$self.$tables.$table.set($def_id.index, $self.lazy($value))`, which would |
e74abb32 XL |
389 | // normally need extra variables to avoid errors about multiple mutable borrows. |
390 | macro_rules! record { | |
60c5eb7d | 391 | ($self:ident.$tables:ident.$table:ident[$def_id:expr] <- $value:expr) => {{ |
e74abb32 XL |
392 | { |
393 | let value = $value; | |
394 | let lazy = $self.lazy(value); | |
60c5eb7d | 395 | $self.$tables.$table.set($def_id.index, lazy); |
e74abb32 | 396 | } |
dfeec247 | 397 | }}; |
e74abb32 XL |
398 | } |
399 | ||
3dfed10e | 400 | impl<'a, 'tcx> EncodeContext<'a, 'tcx> { |
e1599b0c XL |
401 | fn emit_lazy_distance<T: ?Sized + LazyMeta>( |
402 | &mut self, | |
403 | lazy: Lazy<T>, | |
404 | ) -> Result<(), <Self as Encoder>::Error> { | |
e74abb32 | 405 | let min_end = lazy.position.get() + T::min_size(lazy.meta); |
9e0c209e | 406 | let distance = match self.lazy_state { |
c30ab7b3 | 407 | LazyState::NoNode => bug!("emit_lazy_distance: outside of a metadata node"), |
9e0c209e | 408 | LazyState::NodeStart(start) => { |
e74abb32 | 409 | let start = start.get(); |
9e0c209e SL |
410 | assert!(min_end <= start); |
411 | start - min_end | |
412 | } | |
413 | LazyState::Previous(last_min_end) => { | |
0531ce1d | 414 | assert!( |
e1599b0c | 415 | last_min_end <= lazy.position, |
0531ce1d | 416 | "make sure that the calls to `lazy*` \ |
74b04a01 | 417 | are in the same order as the metadata fields", |
0531ce1d | 418 | ); |
e74abb32 | 419 | lazy.position.get() - last_min_end.get() |
9e0c209e SL |
420 | } |
421 | }; | |
e74abb32 | 422 | self.lazy_state = LazyState::Previous(NonZeroUsize::new(min_end).unwrap()); |
9e0c209e SL |
423 | self.emit_usize(distance) |
424 | } | |
1a4d82fc | 425 | |
3dfed10e XL |
426 | fn lazy<T: ?Sized + LazyMeta>( |
427 | &mut self, | |
428 | value: impl EncodeContentsForLazy<'a, 'tcx, T>, | |
429 | ) -> Lazy<T> { | |
e74abb32 | 430 | let pos = NonZeroUsize::new(self.position()).unwrap(); |
223e47cc | 431 | |
e1599b0c XL |
432 | assert_eq!(self.lazy_state, LazyState::NoNode); |
433 | self.lazy_state = LazyState::NodeStart(pos); | |
434 | let meta = value.encode_contents_for_lazy(self); | |
435 | self.lazy_state = LazyState::NoNode; | |
1a4d82fc | 436 | |
e74abb32 | 437 | assert!(pos.get() + <T>::min_size(meta) <= self.position()); |
1a4d82fc | 438 | |
e1599b0c | 439 | Lazy::from_position_and_meta(pos, meta) |
1a4d82fc | 440 | } |
223e47cc | 441 | |
dc9dc135 | 442 | fn encode_info_for_items(&mut self) { |
c295e0f8 | 443 | self.encode_info_for_mod(CRATE_DEF_ID, self.tcx.hir().root_module()); |
1b1a35ee XL |
444 | |
445 | // Proc-macro crates only export proc-macro items, which are looked | |
446 | // up using `proc_macro_data` | |
447 | if self.is_proc_macro { | |
448 | return; | |
449 | } | |
450 | ||
c295e0f8 | 451 | self.tcx.hir().visit_all_item_likes(&mut self.as_deep_visitor()); |
7cac9316 XL |
452 | } |
453 | ||
3dfed10e | 454 | fn encode_def_path_table(&mut self) { |
136023e0 | 455 | let table = self.tcx.resolutions(()).definitions.def_path_table(); |
1b1a35ee XL |
456 | if self.is_proc_macro { |
457 | for def_index in std::iter::once(CRATE_DEF_INDEX) | |
94222f64 | 458 | .chain(self.tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index)) |
1b1a35ee XL |
459 | { |
460 | let def_key = self.lazy(table.def_key(def_index)); | |
461 | let def_path_hash = self.lazy(table.def_path_hash(def_index)); | |
462 | self.tables.def_keys.set(def_index, def_key); | |
463 | self.tables.def_path_hashes.set(def_index, def_path_hash); | |
464 | } | |
465 | } else { | |
466 | for (def_index, def_key, def_path_hash) in table.enumerated_keys_and_path_hashes() { | |
467 | let def_key = self.lazy(def_key); | |
468 | let def_path_hash = self.lazy(def_path_hash); | |
469 | self.tables.def_keys.set(def_index, def_key); | |
470 | self.tables.def_path_hashes.set(def_index, def_path_hash); | |
471 | } | |
3dfed10e | 472 | } |
7cac9316 XL |
473 | } |
474 | ||
c295e0f8 XL |
475 | fn encode_def_path_hash_map(&mut self) -> Lazy<DefPathHashMapRef<'tcx>> { |
476 | self.lazy(DefPathHashMapRef::BorrowedFromTcx( | |
477 | self.tcx.resolutions(()).definitions.def_path_hash_to_def_index_map(), | |
478 | )) | |
479 | } | |
480 | ||
dfeec247 | 481 | fn encode_source_map(&mut self) -> Lazy<[rustc_span::SourceFile]> { |
b7449926 XL |
482 | let source_map = self.tcx.sess.source_map(); |
483 | let all_source_files = source_map.files(); | |
7cac9316 | 484 | |
f035d41b XL |
485 | // By replacing the `Option` with `None`, we ensure that we can't |
486 | // accidentally serialize any more `Span`s after the source map encoding | |
487 | // is done. | |
488 | let required_source_files = self.required_source_files.take().unwrap(); | |
7cac9316 | 489 | |
dfeec247 XL |
490 | let adapted = all_source_files |
491 | .iter() | |
f035d41b XL |
492 | .enumerate() |
493 | .filter(|(idx, source_file)| { | |
494 | // Only serialize `SourceFile`s that were used | |
495 | // during the encoding of a `Span` | |
496 | required_source_files.contains(*idx) && | |
497 | // Don't serialize imported `SourceFile`s, unless | |
498 | // we're in a proc-macro crate. | |
499 | (!source_file.is_imported() || self.is_proc_macro) | |
7cac9316 | 500 | }) |
f035d41b XL |
501 | .map(|(_, source_file)| { |
502 | let mut adapted = match source_file.name { | |
17df50a5 | 503 | FileName::Real(ref realname) => { |
a1dfa0c6 | 504 | let mut adapted = (**source_file).clone(); |
17df50a5 XL |
505 | adapted.name = FileName::Real(match realname { |
506 | RealFileName::LocalPath(path_to_file) => { | |
507 | // Prepend path of working directory onto potentially | |
508 | // relative paths, because they could become relative | |
509 | // to a wrong directory. | |
94222f64 XL |
510 | // We include `working_dir` as part of the crate hash, |
511 | // so it's okay for us to use it as part of the encoded | |
512 | // metadata. | |
513 | let working_dir = &self.tcx.sess.opts.working_dir; | |
17df50a5 XL |
514 | match working_dir { |
515 | RealFileName::LocalPath(absolute) => { | |
94222f64 XL |
516 | // Although neither working_dir or the file name were subject |
517 | // to path remapping, the concatenation between the two may | |
518 | // be. Hence we need to do a remapping here. | |
519 | let joined = Path::new(absolute).join(path_to_file); | |
520 | let (joined, remapped) = | |
521 | source_map.path_mapping().map_prefix(joined); | |
522 | if remapped { | |
523 | RealFileName::Remapped { | |
524 | local_path: None, | |
525 | virtual_name: joined, | |
526 | } | |
527 | } else { | |
528 | RealFileName::LocalPath(joined) | |
529 | } | |
17df50a5 XL |
530 | } |
531 | RealFileName::Remapped { local_path: _, virtual_name } => { | |
532 | // If working_dir has been remapped, then we emit | |
533 | // Remapped variant as the expanded path won't be valid | |
534 | RealFileName::Remapped { | |
535 | local_path: None, | |
536 | virtual_name: Path::new(virtual_name) | |
537 | .join(path_to_file), | |
538 | } | |
539 | } | |
540 | } | |
541 | } | |
542 | RealFileName::Remapped { local_path: _, virtual_name } => { | |
543 | RealFileName::Remapped { | |
544 | // We do not want any local path to be exported into metadata | |
545 | local_path: None, | |
546 | virtual_name: virtual_name.clone(), | |
547 | } | |
548 | } | |
549 | }); | |
a1dfa0c6 | 550 | adapted.name_hash = { |
e74abb32 | 551 | let mut hasher: StableHasher = StableHasher::new(); |
a1dfa0c6 | 552 | adapted.name.hash(&mut hasher); |
e74abb32 | 553 | hasher.finish::<u128>() |
a1dfa0c6 XL |
554 | }; |
555 | Lrc::new(adapted) | |
dfeec247 | 556 | } |
a1dfa0c6 | 557 | |
ff7c6d11 | 558 | // expanded code, not from a file |
b7449926 | 559 | _ => source_file.clone(), |
f035d41b XL |
560 | }; |
561 | ||
562 | // We're serializing this `SourceFile` into our crate metadata, | |
563 | // so mark it as coming from this crate. | |
564 | // This also ensures that we don't try to deserialize the | |
565 | // `CrateNum` for a proc-macro dependency - since proc macro | |
566 | // dependencies aren't loaded when we deserialize a proc-macro, | |
567 | // trying to remap the `CrateNum` would fail. | |
568 | if self.is_proc_macro { | |
569 | Lrc::make_mut(&mut adapted).cnum = LOCAL_CRATE; | |
7cac9316 | 570 | } |
f035d41b | 571 | adapted |
7cac9316 XL |
572 | }) |
573 | .collect::<Vec<_>>(); | |
574 | ||
e1599b0c | 575 | self.lazy(adapted.iter().map(|rc| &**rc)) |
7cac9316 XL |
576 | } |
577 | ||
dc9dc135 | 578 | fn encode_crate_root(&mut self) -> Lazy<CrateRoot<'tcx>> { |
7cac9316 XL |
579 | let mut i = self.position(); |
580 | ||
3dfed10e | 581 | // Encode the crate deps |
dc9dc135 XL |
582 | let crate_deps = self.encode_crate_deps(); |
583 | let dylib_dependency_formats = self.encode_dylib_dependency_formats(); | |
7cac9316 XL |
584 | let dep_bytes = self.position() - i; |
585 | ||
b7449926 XL |
586 | // Encode the lib features. |
587 | i = self.position(); | |
dc9dc135 | 588 | let lib_features = self.encode_lib_features(); |
b7449926 XL |
589 | let lib_feature_bytes = self.position() - i; |
590 | ||
7cac9316 XL |
591 | // Encode the language items. |
592 | i = self.position(); | |
dc9dc135 XL |
593 | let lang_items = self.encode_lang_items(); |
594 | let lang_items_missing = self.encode_lang_items_missing(); | |
7cac9316 XL |
595 | let lang_item_bytes = self.position() - i; |
596 | ||
e1599b0c XL |
597 | // Encode the diagnostic items. |
598 | i = self.position(); | |
599 | let diagnostic_items = self.encode_diagnostic_items(); | |
600 | let diagnostic_item_bytes = self.position() - i; | |
601 | ||
7cac9316 XL |
602 | // Encode the native libraries used |
603 | i = self.position(); | |
dc9dc135 | 604 | let native_libraries = self.encode_native_libraries(); |
7cac9316 XL |
605 | let native_lib_bytes = self.position() - i; |
606 | ||
dc9dc135 | 607 | let foreign_modules = self.encode_foreign_modules(); |
0531ce1d | 608 | |
7cac9316 XL |
609 | // Encode DefPathTable |
610 | i = self.position(); | |
3dfed10e | 611 | self.encode_def_path_table(); |
7cac9316 XL |
612 | let def_path_table_bytes = self.position() - i; |
613 | ||
614 | // Encode the def IDs of impls, for coherence checking. | |
615 | i = self.position(); | |
dc9dc135 | 616 | let impls = self.encode_impls(); |
7cac9316 XL |
617 | let impl_bytes = self.position() - i; |
618 | ||
0531ce1d XL |
619 | let tcx = self.tcx; |
620 | ||
6a06907d XL |
621 | // Encode MIR. |
622 | i = self.position(); | |
623 | self.encode_mir(); | |
624 | let mir_bytes = self.position() - i; | |
625 | ||
0531ce1d | 626 | // Encode the items. |
7cac9316 | 627 | i = self.position(); |
5869c6ff | 628 | self.encode_def_ids(); |
dc9dc135 | 629 | self.encode_info_for_items(); |
7cac9316 XL |
630 | let item_bytes = self.position() - i; |
631 | ||
0531ce1d XL |
632 | // Encode the allocation index |
633 | let interpret_alloc_index = { | |
634 | let mut interpret_alloc_index = Vec::new(); | |
635 | let mut n = 0; | |
636 | trace!("beginning to encode alloc ids"); | |
637 | loop { | |
3dfed10e | 638 | let new_n = self.interpret_allocs.len(); |
0531ce1d XL |
639 | // if we have found new ids, serialize those, too |
640 | if n == new_n { | |
641 | // otherwise, abort | |
642 | break; | |
643 | } | |
644 | trace!("encoding {} further alloc ids", new_n - n); | |
645 | for idx in n..new_n { | |
3dfed10e | 646 | let id = self.interpret_allocs[idx]; |
0531ce1d XL |
647 | let pos = self.position() as u32; |
648 | interpret_alloc_index.push(pos); | |
dfeec247 | 649 | interpret::specialized_encode_alloc_id(self, tcx, id).unwrap(); |
0531ce1d XL |
650 | } |
651 | n = new_n; | |
652 | } | |
e1599b0c | 653 | self.lazy(interpret_alloc_index) |
0531ce1d XL |
654 | }; |
655 | ||
1b1a35ee XL |
656 | // Encode the proc macro data. This affects 'tables', |
657 | // so we need to do this before we encode the tables | |
e1599b0c XL |
658 | i = self.position(); |
659 | let proc_macro_data = self.encode_proc_macros(); | |
660 | let proc_macro_data_bytes = self.position() - i; | |
661 | ||
1b1a35ee XL |
662 | i = self.position(); |
663 | let tables = self.tables.encode(&mut self.opaque); | |
664 | let tables_bytes = self.position() - i; | |
665 | ||
ba9703b0 | 666 | // Encode exported symbols info. This is prefetched in `encode_metadata` so we encode |
3dfed10e | 667 | // this as late as possible to give the prefetching as much time as possible to complete. |
ba9703b0 | 668 | i = self.position(); |
3dfed10e | 669 | let exported_symbols = tcx.exported_symbols(LOCAL_CRATE); |
ba9703b0 XL |
670 | let exported_symbols = self.encode_exported_symbols(&exported_symbols); |
671 | let exported_symbols_bytes = self.position() - i; | |
672 | ||
3dfed10e XL |
673 | // Encode the hygiene data, |
674 | // IMPORTANT: this *must* be the last thing that we encode (other than `SourceMap`). The process | |
675 | // of encoding other items (e.g. `optimized_mir`) may cause us to load | |
676 | // data from the incremental cache. If this causes us to deserialize a `Span`, | |
677 | // then we may load additional `SyntaxContext`s into the global `HygieneData`. | |
678 | // Therefore, we need to encode the hygiene data last to ensure that we encode | |
679 | // any `SyntaxContext`s that might be used. | |
680 | i = self.position(); | |
136023e0 | 681 | let (syntax_contexts, expn_data, expn_hashes) = self.encode_hygiene(); |
3dfed10e XL |
682 | let hygiene_bytes = self.position() - i; |
683 | ||
c295e0f8 XL |
684 | i = self.position(); |
685 | let def_path_hash_map = self.encode_def_path_hash_map(); | |
686 | let def_path_hash_map_bytes = self.position() - i; | |
687 | ||
f035d41b XL |
688 | // Encode source_map. This needs to be done last, |
689 | // since encoding `Span`s tells us which `SourceFiles` we actually | |
690 | // need to encode. | |
691 | i = self.position(); | |
692 | let source_map = self.encode_source_map(); | |
693 | let source_map_bytes = self.position() - i; | |
694 | ||
0731742a | 695 | let attrs = tcx.hir().krate_attrs(); |
3dfed10e | 696 | let has_default_lib_allocator = tcx.sess.contains_name(&attrs, sym::default_lib_allocator); |
0531ce1d | 697 | |
e1599b0c | 698 | let root = self.lazy(CrateRoot { |
7cac9316 | 699 | name: tcx.crate_name(LOCAL_CRATE), |
83c7162d | 700 | extra_filename: tcx.sess.opts.cg.extra_filename.clone(), |
7cac9316 | 701 | triple: tcx.sess.opts.target_triple.clone(), |
b7449926 | 702 | hash: tcx.crate_hash(LOCAL_CRATE), |
6a06907d | 703 | stable_crate_id: tcx.def_path_hash(LOCAL_CRATE.as_def_id()).stable_crate_id(), |
ea8adc8c | 704 | panic_strategy: tcx.sess.panic_strategy(), |
c295e0f8 | 705 | panic_in_drop_strategy: tcx.sess.opts.debugging_opts.panic_in_drop, |
dc9dc135 | 706 | edition: tcx.sess.edition(), |
60c5eb7d XL |
707 | has_global_allocator: tcx.has_global_allocator(LOCAL_CRATE), |
708 | has_panic_handler: tcx.has_panic_handler(LOCAL_CRATE), | |
74b04a01 | 709 | has_default_lib_allocator, |
e1599b0c | 710 | proc_macro_data, |
3dfed10e XL |
711 | compiler_builtins: tcx.sess.contains_name(&attrs, sym::compiler_builtins), |
712 | needs_allocator: tcx.sess.contains_name(&attrs, sym::needs_allocator), | |
713 | needs_panic_runtime: tcx.sess.contains_name(&attrs, sym::needs_panic_runtime), | |
714 | no_builtins: tcx.sess.contains_name(&attrs, sym::no_builtins), | |
715 | panic_runtime: tcx.sess.contains_name(&attrs, sym::panic_runtime), | |
716 | profiler_runtime: tcx.sess.contains_name(&attrs, sym::profiler_runtime), | |
fc512014 | 717 | symbol_mangling_version: tcx.sess.opts.debugging_opts.get_symbol_mangling_version(), |
94b46f34 | 718 | |
3b2f2976 XL |
719 | crate_deps, |
720 | dylib_dependency_formats, | |
b7449926 | 721 | lib_features, |
3b2f2976 | 722 | lang_items, |
e1599b0c | 723 | diagnostic_items, |
3b2f2976 XL |
724 | lang_items_missing, |
725 | native_libraries, | |
0531ce1d | 726 | foreign_modules, |
b7449926 | 727 | source_map, |
3b2f2976 XL |
728 | impls, |
729 | exported_symbols, | |
0531ce1d | 730 | interpret_alloc_index, |
ba9703b0 | 731 | tables, |
3dfed10e XL |
732 | syntax_contexts, |
733 | expn_data, | |
136023e0 | 734 | expn_hashes, |
c295e0f8 | 735 | def_path_hash_map, |
7cac9316 XL |
736 | }); |
737 | ||
738 | let total_bytes = self.position(); | |
739 | ||
3dfed10e | 740 | if tcx.sess.meta_stats() { |
7cac9316 | 741 | let mut zero_bytes = 0; |
8faf50e0 | 742 | for e in self.opaque.data.iter() { |
7cac9316 XL |
743 | if *e == 0 { |
744 | zero_bytes += 1; | |
745 | } | |
746 | } | |
747 | ||
6a06907d XL |
748 | eprintln!("metadata stats:"); |
749 | eprintln!(" dep bytes: {}", dep_bytes); | |
750 | eprintln!(" lib feature bytes: {}", lib_feature_bytes); | |
751 | eprintln!(" lang item bytes: {}", lang_item_bytes); | |
752 | eprintln!(" diagnostic item bytes: {}", diagnostic_item_bytes); | |
753 | eprintln!(" native bytes: {}", native_lib_bytes); | |
754 | eprintln!(" source_map bytes: {}", source_map_bytes); | |
755 | eprintln!(" impl bytes: {}", impl_bytes); | |
756 | eprintln!(" exp. symbols bytes: {}", exported_symbols_bytes); | |
757 | eprintln!(" def-path table bytes: {}", def_path_table_bytes); | |
c295e0f8 | 758 | eprintln!(" def-path hashes bytes: {}", def_path_hash_map_bytes); |
6a06907d XL |
759 | eprintln!(" proc-macro-data-bytes: {}", proc_macro_data_bytes); |
760 | eprintln!(" mir bytes: {}", mir_bytes); | |
761 | eprintln!(" item bytes: {}", item_bytes); | |
762 | eprintln!(" table bytes: {}", tables_bytes); | |
763 | eprintln!(" hygiene bytes: {}", hygiene_bytes); | |
764 | eprintln!(" zero bytes: {}", zero_bytes); | |
765 | eprintln!(" total bytes: {}", total_bytes); | |
7cac9316 XL |
766 | } |
767 | ||
768 | root | |
769 | } | |
cc61c64b | 770 | } |
1a4d82fc | 771 | |
5869c6ff XL |
772 | fn should_encode_visibility(def_kind: DefKind) -> bool { |
773 | match def_kind { | |
774 | DefKind::Mod | |
775 | | DefKind::Struct | |
776 | | DefKind::Union | |
777 | | DefKind::Enum | |
778 | | DefKind::Variant | |
779 | | DefKind::Trait | |
780 | | DefKind::TyAlias | |
781 | | DefKind::ForeignTy | |
782 | | DefKind::TraitAlias | |
783 | | DefKind::AssocTy | |
784 | | DefKind::Fn | |
785 | | DefKind::Const | |
786 | | DefKind::Static | |
787 | | DefKind::Ctor(..) | |
788 | | DefKind::AssocFn | |
789 | | DefKind::AssocConst | |
790 | | DefKind::Macro(..) | |
791 | | DefKind::Use | |
792 | | DefKind::ForeignMod | |
793 | | DefKind::OpaqueTy | |
794 | | DefKind::Impl | |
795 | | DefKind::Field => true, | |
796 | DefKind::TyParam | |
797 | | DefKind::ConstParam | |
798 | | DefKind::LifetimeParam | |
799 | | DefKind::AnonConst | |
3c0e092e | 800 | | DefKind::InlineConst |
5869c6ff XL |
801 | | DefKind::GlobalAsm |
802 | | DefKind::Closure | |
803 | | DefKind::Generator | |
804 | | DefKind::ExternCrate => false, | |
805 | } | |
806 | } | |
807 | ||
808 | fn should_encode_stability(def_kind: DefKind) -> bool { | |
809 | match def_kind { | |
810 | DefKind::Mod | |
811 | | DefKind::Ctor(..) | |
812 | | DefKind::Variant | |
813 | | DefKind::Field | |
814 | | DefKind::Struct | |
815 | | DefKind::AssocTy | |
816 | | DefKind::AssocFn | |
817 | | DefKind::AssocConst | |
818 | | DefKind::TyParam | |
819 | | DefKind::ConstParam | |
820 | | DefKind::Static | |
821 | | DefKind::Const | |
822 | | DefKind::Fn | |
823 | | DefKind::ForeignMod | |
824 | | DefKind::TyAlias | |
825 | | DefKind::OpaqueTy | |
826 | | DefKind::Enum | |
827 | | DefKind::Union | |
828 | | DefKind::Impl | |
829 | | DefKind::Trait | |
830 | | DefKind::TraitAlias | |
831 | | DefKind::Macro(..) | |
832 | | DefKind::ForeignTy => true, | |
833 | DefKind::Use | |
834 | | DefKind::LifetimeParam | |
835 | | DefKind::AnonConst | |
3c0e092e | 836 | | DefKind::InlineConst |
5869c6ff XL |
837 | | DefKind::GlobalAsm |
838 | | DefKind::Closure | |
839 | | DefKind::Generator | |
840 | | DefKind::ExternCrate => false, | |
841 | } | |
842 | } | |
843 | ||
844 | /// Whether we should encode MIR. | |
845 | /// | |
846 | /// Computing, optimizing and encoding the MIR is a relatively expensive operation. | |
847 | /// We want to avoid this work when not required. Therefore: | |
848 | /// - we only compute `mir_for_ctfe` on items with const-eval semantics; | |
849 | /// - we skip `optimized_mir` for check runs. | |
850 | /// | |
851 | /// Return a pair, resp. for CTFE and for LLVM. | |
852 | fn should_encode_mir(tcx: TyCtxt<'_>, def_id: LocalDefId) -> (bool, bool) { | |
853 | match tcx.def_kind(def_id) { | |
854 | // Constructors | |
855 | DefKind::Ctor(_, _) => { | |
856 | let mir_opt_base = tcx.sess.opts.output_types.should_codegen() | |
857 | || tcx.sess.opts.debugging_opts.always_encode_mir; | |
858 | (true, mir_opt_base) | |
859 | } | |
860 | // Constants | |
3c0e092e XL |
861 | DefKind::AnonConst |
862 | | DefKind::InlineConst | |
863 | | DefKind::AssocConst | |
864 | | DefKind::Static | |
865 | | DefKind::Const => (true, false), | |
5869c6ff XL |
866 | // Full-fledged functions |
867 | DefKind::AssocFn | DefKind::Fn => { | |
868 | let generics = tcx.generics_of(def_id); | |
869 | let needs_inline = (generics.requires_monomorphization(tcx) | |
870 | || tcx.codegen_fn_attrs(def_id).requests_inline()) | |
871 | && tcx.sess.opts.output_types.should_codegen(); | |
872 | // Only check the presence of the `const` modifier. | |
873 | let is_const_fn = tcx.is_const_fn_raw(def_id.to_def_id()); | |
874 | let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir; | |
875 | (is_const_fn, needs_inline || always_encode_mir) | |
876 | } | |
877 | // Closures can't be const fn. | |
878 | DefKind::Closure => { | |
879 | let generics = tcx.generics_of(def_id); | |
880 | let needs_inline = (generics.requires_monomorphization(tcx) | |
881 | || tcx.codegen_fn_attrs(def_id).requests_inline()) | |
882 | && tcx.sess.opts.output_types.should_codegen(); | |
883 | let always_encode_mir = tcx.sess.opts.debugging_opts.always_encode_mir; | |
884 | (false, needs_inline || always_encode_mir) | |
885 | } | |
886 | // Generators require optimized MIR to compute layout. | |
887 | DefKind::Generator => (false, true), | |
888 | // The others don't have MIR. | |
889 | _ => (false, false), | |
890 | } | |
891 | } | |
892 | ||
6a06907d XL |
893 | fn should_encode_variances(def_kind: DefKind) -> bool { |
894 | match def_kind { | |
895 | DefKind::Struct | |
896 | | DefKind::Union | |
897 | | DefKind::Enum | |
898 | | DefKind::Variant | |
899 | | DefKind::Fn | |
900 | | DefKind::Ctor(..) | |
901 | | DefKind::AssocFn => true, | |
902 | DefKind::Mod | |
903 | | DefKind::Field | |
904 | | DefKind::AssocTy | |
905 | | DefKind::AssocConst | |
906 | | DefKind::TyParam | |
907 | | DefKind::ConstParam | |
908 | | DefKind::Static | |
909 | | DefKind::Const | |
910 | | DefKind::ForeignMod | |
911 | | DefKind::TyAlias | |
912 | | DefKind::OpaqueTy | |
913 | | DefKind::Impl | |
914 | | DefKind::Trait | |
915 | | DefKind::TraitAlias | |
916 | | DefKind::Macro(..) | |
917 | | DefKind::ForeignTy | |
918 | | DefKind::Use | |
919 | | DefKind::LifetimeParam | |
920 | | DefKind::AnonConst | |
3c0e092e | 921 | | DefKind::InlineConst |
6a06907d XL |
922 | | DefKind::GlobalAsm |
923 | | DefKind::Closure | |
924 | | DefKind::Generator | |
925 | | DefKind::ExternCrate => false, | |
926 | } | |
927 | } | |
928 | ||
929 | fn should_encode_generics(def_kind: DefKind) -> bool { | |
930 | match def_kind { | |
931 | DefKind::Struct | |
932 | | DefKind::Union | |
933 | | DefKind::Enum | |
934 | | DefKind::Variant | |
935 | | DefKind::Trait | |
936 | | DefKind::TyAlias | |
937 | | DefKind::ForeignTy | |
938 | | DefKind::TraitAlias | |
939 | | DefKind::AssocTy | |
940 | | DefKind::Fn | |
941 | | DefKind::Const | |
942 | | DefKind::Static | |
943 | | DefKind::Ctor(..) | |
944 | | DefKind::AssocFn | |
945 | | DefKind::AssocConst | |
946 | | DefKind::AnonConst | |
3c0e092e | 947 | | DefKind::InlineConst |
6a06907d XL |
948 | | DefKind::OpaqueTy |
949 | | DefKind::Impl | |
94222f64 XL |
950 | | DefKind::Field |
951 | | DefKind::TyParam | |
6a06907d XL |
952 | | DefKind::Closure |
953 | | DefKind::Generator => true, | |
954 | DefKind::Mod | |
6a06907d | 955 | | DefKind::ForeignMod |
6a06907d XL |
956 | | DefKind::ConstParam |
957 | | DefKind::Macro(..) | |
958 | | DefKind::Use | |
959 | | DefKind::LifetimeParam | |
960 | | DefKind::GlobalAsm | |
961 | | DefKind::ExternCrate => false, | |
962 | } | |
963 | } | |
964 | ||
3dfed10e | 965 | impl EncodeContext<'a, 'tcx> { |
5869c6ff XL |
966 | fn encode_def_ids(&mut self) { |
967 | if self.is_proc_macro { | |
968 | return; | |
969 | } | |
970 | let tcx = self.tcx; | |
971 | let hir = tcx.hir(); | |
972 | for local_id in hir.iter_local_def_id() { | |
973 | let def_id = local_id.to_def_id(); | |
974 | let def_kind = tcx.opt_def_kind(local_id); | |
975 | let def_kind = if let Some(def_kind) = def_kind { def_kind } else { continue }; | |
976 | record!(self.tables.def_kind[def_id] <- match def_kind { | |
977 | // Replace Ctor by the enclosing object to avoid leaking details in children crates. | |
978 | DefKind::Ctor(CtorOf::Struct, _) => DefKind::Struct, | |
979 | DefKind::Ctor(CtorOf::Variant, _) => DefKind::Variant, | |
980 | def_kind => def_kind, | |
981 | }); | |
982 | record!(self.tables.span[def_id] <- tcx.def_span(def_id)); | |
983 | record!(self.tables.attributes[def_id] <- tcx.get_attrs(def_id)); | |
17df50a5 | 984 | record!(self.tables.expn_that_defined[def_id] <- self.tcx.expn_that_defined(def_id)); |
5869c6ff XL |
985 | if should_encode_visibility(def_kind) { |
986 | record!(self.tables.visibility[def_id] <- self.tcx.visibility(def_id)); | |
987 | } | |
988 | if should_encode_stability(def_kind) { | |
989 | self.encode_stability(def_id); | |
990 | self.encode_const_stability(def_id); | |
991 | self.encode_deprecation(def_id); | |
992 | } | |
6a06907d XL |
993 | if should_encode_variances(def_kind) { |
994 | let v = self.tcx.variances_of(def_id); | |
995 | record!(self.tables.variances[def_id] <- v); | |
996 | } | |
997 | if should_encode_generics(def_kind) { | |
998 | let g = tcx.generics_of(def_id); | |
999 | record!(self.tables.generics[def_id] <- g); | |
1000 | record!(self.tables.explicit_predicates[def_id] <- self.tcx.explicit_predicates_of(def_id)); | |
1001 | let inferred_outlives = self.tcx.inferred_outlives_of(def_id); | |
1002 | if !inferred_outlives.is_empty() { | |
1003 | record!(self.tables.inferred_outlives[def_id] <- inferred_outlives); | |
1004 | } | |
1005 | } | |
1006 | if let DefKind::Trait | DefKind::TraitAlias = def_kind { | |
1007 | record!(self.tables.super_predicates[def_id] <- self.tcx.super_predicates_of(def_id)); | |
1008 | } | |
1009 | } | |
17df50a5 | 1010 | let inherent_impls = tcx.crate_inherent_impls(()); |
6a06907d | 1011 | for (def_id, implementations) in inherent_impls.inherent_impls.iter() { |
6a06907d XL |
1012 | if implementations.is_empty() { |
1013 | continue; | |
1014 | } | |
17df50a5 | 1015 | record!(self.tables.inherent_impls[def_id.to_def_id()] <- implementations.iter().map(|&def_id| { |
6a06907d XL |
1016 | assert!(def_id.is_local()); |
1017 | def_id.index | |
1018 | })); | |
5869c6ff | 1019 | } |
223e47cc | 1020 | } |
970d7e83 | 1021 | |
e74abb32 XL |
1022 | fn encode_item_type(&mut self, def_id: DefId) { |
1023 | debug!("EncodeContext::encode_item_type({:?})", def_id); | |
ba9703b0 | 1024 | record!(self.tables.ty[def_id] <- self.tcx.type_of(def_id)); |
970d7e83 LB |
1025 | } |
1026 | ||
f9f354fc | 1027 | fn encode_enum_variant_info(&mut self, def: &ty::AdtDef, index: VariantIdx) { |
9e0c209e | 1028 | let tcx = self.tcx; |
9e0c209e | 1029 | let variant = &def.variants[index]; |
532ac7d7 | 1030 | let def_id = variant.def_id; |
dc9dc135 | 1031 | debug!("EncodeContext::encode_enum_variant_info({:?})", def_id); |
9e0c209e SL |
1032 | |
1033 | let data = VariantData { | |
c30ab7b3 | 1034 | ctor_kind: variant.ctor_kind, |
8bb4bdeb | 1035 | discr: variant.discr, |
532ac7d7 | 1036 | ctor: variant.ctor_def_id.map(|did| did.index), |
3dfed10e | 1037 | is_non_exhaustive: variant.is_field_list_non_exhaustive(), |
9e0c209e | 1038 | }; |
970d7e83 | 1039 | |
ba9703b0 | 1040 | record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data))); |
ba9703b0 | 1041 | record!(self.tables.children[def_id] <- variant.fields.iter().map(|f| { |
e74abb32 XL |
1042 | assert!(f.did.is_local()); |
1043 | f.did.index | |
1044 | })); | |
ba9703b0 | 1045 | self.encode_ident_span(def_id, variant.ident); |
e74abb32 XL |
1046 | self.encode_item_type(def_id); |
1047 | if variant.ctor_kind == CtorKind::Fn { | |
1048 | // FIXME(eddyb) encode signature only in `encode_enum_variant_ctor`. | |
1049 | if let Some(ctor_def_id) = variant.ctor_def_id { | |
ba9703b0 | 1050 | record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(ctor_def_id)); |
e74abb32 | 1051 | } |
9e0c209e | 1052 | } |
970d7e83 | 1053 | } |
223e47cc | 1054 | |
f9f354fc | 1055 | fn encode_enum_variant_ctor(&mut self, def: &ty::AdtDef, index: VariantIdx) { |
532ac7d7 | 1056 | let tcx = self.tcx; |
532ac7d7 XL |
1057 | let variant = &def.variants[index]; |
1058 | let def_id = variant.ctor_def_id.unwrap(); | |
dc9dc135 | 1059 | debug!("EncodeContext::encode_enum_variant_ctor({:?})", def_id); |
532ac7d7 | 1060 | |
e74abb32 | 1061 | // FIXME(eddyb) encode only the `CtorKind` for constructors. |
532ac7d7 XL |
1062 | let data = VariantData { |
1063 | ctor_kind: variant.ctor_kind, | |
1064 | discr: variant.discr, | |
1065 | ctor: Some(def_id.index), | |
3dfed10e | 1066 | is_non_exhaustive: variant.is_field_list_non_exhaustive(), |
532ac7d7 XL |
1067 | }; |
1068 | ||
ba9703b0 | 1069 | record!(self.tables.kind[def_id] <- EntryKind::Variant(self.lazy(data))); |
e74abb32 XL |
1070 | self.encode_item_type(def_id); |
1071 | if variant.ctor_kind == CtorKind::Fn { | |
ba9703b0 | 1072 | record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); |
532ac7d7 XL |
1073 | } |
1074 | } | |
1075 | ||
6a06907d | 1076 | fn encode_info_for_mod(&mut self, local_def_id: LocalDefId, md: &hir::Mod<'_>) { |
9e0c209e | 1077 | let tcx = self.tcx; |
3dfed10e | 1078 | let def_id = local_def_id.to_def_id(); |
dc9dc135 | 1079 | debug!("EncodeContext::encode_info_for_mod({:?})", def_id); |
9e0c209e | 1080 | |
1b1a35ee XL |
1081 | // If we are encoding a proc-macro crates, `encode_info_for_mod` will |
1082 | // only ever get called for the crate root. We still want to encode | |
1083 | // the crate root for consistency with other crates (some of the resolver | |
1084 | // code uses it). However, we skip encoding anything relating to child | |
1085 | // items - we encode information about proc-macros later on. | |
1086 | let reexports = if !self.is_proc_macro { | |
1087 | match tcx.module_exports(local_def_id) { | |
c295e0f8 | 1088 | Some(exports) => self.lazy(exports), |
e1599b0c | 1089 | _ => Lazy::empty(), |
1b1a35ee XL |
1090 | } |
1091 | } else { | |
1092 | Lazy::empty() | |
1093 | }; | |
1094 | ||
3c0e092e | 1095 | record!(self.tables.kind[def_id] <- EntryKind::Mod(reexports)); |
1b1a35ee XL |
1096 | if self.is_proc_macro { |
1097 | record!(self.tables.children[def_id] <- &[]); | |
3c0e092e XL |
1098 | // Encode this here because we don't do it in encode_def_ids. |
1099 | record!(self.tables.expn_that_defined[def_id] <- tcx.expn_that_defined(local_def_id)); | |
1b1a35ee XL |
1100 | } else { |
1101 | record!(self.tables.children[def_id] <- md.item_ids.iter().map(|item_id| { | |
6a06907d | 1102 | item_id.def_id.local_def_index |
1b1a35ee XL |
1103 | })); |
1104 | } | |
9e0c209e | 1105 | } |
223e47cc | 1106 | |
f9f354fc XL |
1107 | fn encode_field( |
1108 | &mut self, | |
1109 | adt_def: &ty::AdtDef, | |
1110 | variant_index: VariantIdx, | |
1111 | field_index: usize, | |
1112 | ) { | |
f9f354fc | 1113 | let variant = &adt_def.variants[variant_index]; |
9e0c209e SL |
1114 | let field = &variant.fields[field_index]; |
1115 | ||
1116 | let def_id = field.did; | |
dc9dc135 | 1117 | debug!("EncodeContext::encode_field({:?})", def_id); |
cc61c64b | 1118 | |
ba9703b0 | 1119 | record!(self.tables.kind[def_id] <- EntryKind::Field); |
ba9703b0 | 1120 | self.encode_ident_span(def_id, field.ident); |
e74abb32 | 1121 | self.encode_item_type(def_id); |
223e47cc | 1122 | } |
223e47cc | 1123 | |
f9f354fc | 1124 | fn encode_struct_ctor(&mut self, adt_def: &ty::AdtDef, def_id: DefId) { |
dc9dc135 | 1125 | debug!("EncodeContext::encode_struct_ctor({:?})", def_id); |
c30ab7b3 | 1126 | let tcx = self.tcx; |
2c00a5a8 | 1127 | let variant = adt_def.non_enum_variant(); |
1a4d82fc | 1128 | |
9e0c209e | 1129 | let data = VariantData { |
c30ab7b3 | 1130 | ctor_kind: variant.ctor_kind, |
8bb4bdeb | 1131 | discr: variant.discr, |
532ac7d7 | 1132 | ctor: Some(def_id.index), |
3dfed10e | 1133 | is_non_exhaustive: variant.is_field_list_non_exhaustive(), |
9e0c209e | 1134 | }; |
223e47cc | 1135 | |
ba9703b0 | 1136 | record!(self.tables.kind[def_id] <- EntryKind::Struct(self.lazy(data), adt_def.repr)); |
e74abb32 XL |
1137 | self.encode_item_type(def_id); |
1138 | if variant.ctor_kind == CtorKind::Fn { | |
ba9703b0 | 1139 | record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); |
9e0c209e | 1140 | } |
e74abb32 XL |
1141 | } |
1142 | ||
29967ef6 XL |
1143 | fn encode_explicit_item_bounds(&mut self, def_id: DefId) { |
1144 | debug!("EncodeContext::encode_explicit_item_bounds({:?})", def_id); | |
1145 | let bounds = self.tcx.explicit_item_bounds(def_id); | |
1146 | if !bounds.is_empty() { | |
1147 | record!(self.tables.explicit_item_bounds[def_id] <- bounds); | |
1148 | } | |
1149 | } | |
1150 | ||
e74abb32 | 1151 | fn encode_info_for_trait_item(&mut self, def_id: DefId) { |
dc9dc135 | 1152 | debug!("EncodeContext::encode_info_for_trait_item({:?})", def_id); |
9e0c209e | 1153 | let tcx = self.tcx; |
c34b1796 | 1154 | |
3dfed10e | 1155 | let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); |
532ac7d7 | 1156 | let ast_item = tcx.hir().expect_trait_item(hir_id); |
476ff2be SL |
1157 | let trait_item = tcx.associated_item(def_id); |
1158 | ||
1159 | let container = match trait_item.defaultness { | |
dfeec247 XL |
1160 | hir::Defaultness::Default { has_value: true } => AssocContainer::TraitWithDefault, |
1161 | hir::Defaultness::Default { has_value: false } => AssocContainer::TraitRequired, | |
1162 | hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"), | |
b039eaaf | 1163 | }; |
1a4d82fc | 1164 | |
5869c6ff | 1165 | match trait_item.kind { |
dc9dc135 | 1166 | ty::AssocKind::Const => { |
ba9703b0 XL |
1167 | let rendered = rustc_hir_pretty::to_string( |
1168 | &(&self.tcx.hir() as &dyn intravisit::Map<'_>), | |
5869c6ff | 1169 | |s| s.print_trait_item(ast_item), |
ba9703b0 | 1170 | ); |
e1599b0c | 1171 | let rendered_const = self.lazy(RenderedConst(rendered)); |
83c7162d | 1172 | |
5869c6ff | 1173 | record!(self.tables.kind[def_id] <- EntryKind::AssocConst( |
60c5eb7d XL |
1174 | container, |
1175 | Default::default(), | |
1176 | rendered_const, | |
5869c6ff | 1177 | )); |
8bb4bdeb | 1178 | } |
ba9703b0 XL |
1179 | ty::AssocKind::Fn => { |
1180 | let fn_data = if let hir::TraitItemKind::Fn(m_sig, m) = &ast_item.kind { | |
e1599b0c | 1181 | let param_names = match *m { |
5869c6ff XL |
1182 | hir::TraitFn::Required(ref names) => self.encode_fn_param_names(names), |
1183 | hir::TraitFn::Provided(body) => self.encode_fn_param_names_for_body(body), | |
32a655c1 | 1184 | }; |
9e0c209e | 1185 | FnData { |
e74abb32 | 1186 | asyncness: m_sig.header.asyncness, |
9e0c209e | 1187 | constness: hir::Constness::NotConst, |
e1599b0c | 1188 | param_names, |
9e0c209e SL |
1189 | } |
1190 | } else { | |
1191 | bug!() | |
1192 | }; | |
5869c6ff | 1193 | record!(self.tables.kind[def_id] <- EntryKind::AssocFn(self.lazy(AssocFnData { |
3b2f2976 XL |
1194 | fn_data, |
1195 | container, | |
ba9703b0 | 1196 | has_self: trait_item.fn_has_self_parameter, |
5869c6ff | 1197 | }))); |
9e0c209e | 1198 | } |
29967ef6 XL |
1199 | ty::AssocKind::Type => { |
1200 | self.encode_explicit_item_bounds(def_id); | |
5869c6ff | 1201 | record!(self.tables.kind[def_id] <- EntryKind::AssocType(container)); |
29967ef6 | 1202 | } |
5869c6ff | 1203 | } |
ba9703b0 | 1204 | self.encode_ident_span(def_id, ast_item.ident); |
e74abb32 | 1205 | match trait_item.kind { |
ba9703b0 | 1206 | ty::AssocKind::Const | ty::AssocKind::Fn => { |
e74abb32 XL |
1207 | self.encode_item_type(def_id); |
1208 | } | |
1209 | ty::AssocKind::Type => { | |
1210 | if trait_item.defaultness.has_value() { | |
1211 | self.encode_item_type(def_id); | |
9e0c209e | 1212 | } |
e74abb32 | 1213 | } |
e74abb32 | 1214 | } |
ba9703b0 XL |
1215 | if trait_item.kind == ty::AssocKind::Fn { |
1216 | record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); | |
1a4d82fc | 1217 | } |
83c7162d XL |
1218 | } |
1219 | ||
e74abb32 | 1220 | fn encode_info_for_impl_item(&mut self, def_id: DefId) { |
dc9dc135 | 1221 | debug!("EncodeContext::encode_info_for_impl_item({:?})", def_id); |
041b39d2 XL |
1222 | let tcx = self.tcx; |
1223 | ||
3dfed10e | 1224 | let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id.expect_local()); |
532ac7d7 | 1225 | let ast_item = self.tcx.hir().expect_impl_item(hir_id); |
476ff2be | 1226 | let impl_item = self.tcx.associated_item(def_id); |
d9579d0f | 1227 | |
476ff2be | 1228 | let container = match impl_item.defaultness { |
dc9dc135 XL |
1229 | hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault, |
1230 | hir::Defaultness::Final => AssocContainer::ImplFinal, | |
dfeec247 XL |
1231 | hir::Defaultness::Default { has_value: false } => { |
1232 | span_bug!(ast_item.span, "impl items always have values (currently)") | |
1233 | } | |
9e0c209e | 1234 | }; |
d9579d0f | 1235 | |
5869c6ff | 1236 | match impl_item.kind { |
dc9dc135 | 1237 | ty::AssocKind::Const => { |
e74abb32 | 1238 | if let hir::ImplItemKind::Const(_, body_id) = ast_item.kind { |
60c5eb7d | 1239 | let qualifs = self.tcx.at(ast_item.span).mir_const_qualif(def_id); |
83c7162d | 1240 | |
5869c6ff | 1241 | record!(self.tables.kind[def_id] <- EntryKind::AssocConst( |
60c5eb7d XL |
1242 | container, |
1243 | qualifs, | |
83c7162d | 1244 | self.encode_rendered_const_for_body(body_id)) |
5869c6ff | 1245 | ); |
83c7162d XL |
1246 | } else { |
1247 | bug!() | |
1248 | } | |
8bb4bdeb | 1249 | } |
ba9703b0 XL |
1250 | ty::AssocKind::Fn => { |
1251 | let fn_data = if let hir::ImplItemKind::Fn(ref sig, body) = ast_item.kind { | |
9e0c209e | 1252 | FnData { |
e1599b0c | 1253 | asyncness: sig.header.asyncness, |
136023e0 XL |
1254 | // Can be inside `impl const Trait`, so using sig.header.constness is not reliable |
1255 | constness: if self.tcx.is_const_fn_raw(def_id) { | |
1256 | hir::Constness::Const | |
1257 | } else { | |
1258 | hir::Constness::NotConst | |
1259 | }, | |
e1599b0c | 1260 | param_names: self.encode_fn_param_names_for_body(body), |
9e0c209e SL |
1261 | } |
1262 | } else { | |
1263 | bug!() | |
1264 | }; | |
5869c6ff | 1265 | record!(self.tables.kind[def_id] <- EntryKind::AssocFn(self.lazy(AssocFnData { |
3b2f2976 XL |
1266 | fn_data, |
1267 | container, | |
ba9703b0 | 1268 | has_self: impl_item.fn_has_self_parameter, |
5869c6ff | 1269 | }))); |
9e0c209e | 1270 | } |
5869c6ff XL |
1271 | ty::AssocKind::Type => { |
1272 | record!(self.tables.kind[def_id] <- EntryKind::AssocType(container)); | |
1273 | } | |
1274 | } | |
ba9703b0 | 1275 | self.encode_ident_span(def_id, impl_item.ident); |
e74abb32 | 1276 | self.encode_item_type(def_id); |
ba9703b0 XL |
1277 | if impl_item.kind == ty::AssocKind::Fn { |
1278 | record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); | |
e74abb32 | 1279 | } |
223e47cc | 1280 | } |
1a4d82fc | 1281 | |
f035d41b | 1282 | fn encode_fn_param_names_for_body(&mut self, body_id: hir::BodyId) -> Lazy<[Ident]> { |
3dfed10e | 1283 | self.lazy(self.tcx.hir().body_param_names(body_id)) |
1a4d82fc | 1284 | } |
1a4d82fc | 1285 | |
f035d41b XL |
1286 | fn encode_fn_param_names(&mut self, param_names: &[Ident]) -> Lazy<[Ident]> { |
1287 | self.lazy(param_names.iter()) | |
32a655c1 SL |
1288 | } |
1289 | ||
5869c6ff XL |
1290 | fn encode_mir(&mut self) { |
1291 | if self.is_proc_macro { | |
1292 | return; | |
1293 | } | |
3dfed10e | 1294 | |
5869c6ff XL |
1295 | let mut keys_and_jobs = self |
1296 | .tcx | |
17df50a5 | 1297 | .mir_keys(()) |
5869c6ff XL |
1298 | .iter() |
1299 | .filter_map(|&def_id| { | |
1300 | let (encode_const, encode_opt) = should_encode_mir(self.tcx, def_id); | |
1301 | if encode_const || encode_opt { | |
1302 | Some((def_id, encode_const, encode_opt)) | |
1303 | } else { | |
1304 | None | |
1305 | } | |
1306 | }) | |
1307 | .collect::<Vec<_>>(); | |
1308 | // Sort everything to ensure a stable order for diagnotics. | |
1309 | keys_and_jobs.sort_by_key(|&(def_id, _, _)| def_id); | |
1310 | for (def_id, encode_const, encode_opt) in keys_and_jobs.into_iter() { | |
1311 | debug_assert!(encode_const || encode_opt); | |
1312 | ||
1313 | debug!("EntryBuilder::encode_mir({:?})", def_id); | |
1314 | if encode_opt { | |
1315 | record!(self.tables.mir[def_id.to_def_id()] <- self.tcx.optimized_mir(def_id)); | |
3dfed10e | 1316 | } |
5869c6ff XL |
1317 | if encode_const { |
1318 | record!(self.tables.mir_for_ctfe[def_id.to_def_id()] <- self.tcx.mir_for_ctfe(def_id)); | |
1b1a35ee | 1319 | |
c295e0f8 XL |
1320 | // FIXME(generic_const_exprs): this feels wrong to have in `encode_mir` |
1321 | let abstract_const = self.tcx.thir_abstract_const(def_id); | |
5869c6ff | 1322 | if let Ok(Some(abstract_const)) = abstract_const { |
c295e0f8 | 1323 | record!(self.tables.thir_abstract_consts[def_id.to_def_id()] <- abstract_const); |
5869c6ff | 1324 | } |
1b1a35ee | 1325 | } |
f9f354fc | 1326 | record!(self.tables.promoted_mir[def_id.to_def_id()] <- self.tcx.promoted_mir(def_id)); |
5869c6ff | 1327 | |
c295e0f8 XL |
1328 | let instance = |
1329 | ty::InstanceDef::Item(ty::WithOptConstParam::unknown(def_id.to_def_id())); | |
1330 | let unused = self.tcx.unused_generic_params(instance); | |
5869c6ff XL |
1331 | if !unused.is_empty() { |
1332 | record!(self.tables.unused_generic_params[def_id.to_def_id()] <- unused); | |
1333 | } | |
7cac9316 | 1334 | } |
9cc50fc6 | 1335 | } |
223e47cc | 1336 | |
e74abb32 | 1337 | fn encode_stability(&mut self, def_id: DefId) { |
dc9dc135 | 1338 | debug!("EncodeContext::encode_stability({:?})", def_id); |
1b1a35ee XL |
1339 | |
1340 | // The query lookup can take a measurable amount of time in crates with many items. Check if | |
1341 | // the stability attributes are even enabled before using their queries. | |
1342 | if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked { | |
1343 | if let Some(stab) = self.tcx.lookup_stability(def_id) { | |
1344 | record!(self.tables.stability[def_id] <- stab) | |
1345 | } | |
e74abb32 | 1346 | } |
9e0c209e | 1347 | } |
1a4d82fc | 1348 | |
60c5eb7d XL |
1349 | fn encode_const_stability(&mut self, def_id: DefId) { |
1350 | debug!("EncodeContext::encode_const_stability({:?})", def_id); | |
1b1a35ee XL |
1351 | |
1352 | // The query lookup can take a measurable amount of time in crates with many items. Check if | |
1353 | // the stability attributes are even enabled before using their queries. | |
1354 | if self.feat.staged_api || self.tcx.sess.opts.debugging_opts.force_unstable_if_unmarked { | |
1355 | if let Some(stab) = self.tcx.lookup_const_stability(def_id) { | |
1356 | record!(self.tables.const_stability[def_id] <- stab) | |
1357 | } | |
60c5eb7d XL |
1358 | } |
1359 | } | |
1360 | ||
e74abb32 | 1361 | fn encode_deprecation(&mut self, def_id: DefId) { |
dc9dc135 | 1362 | debug!("EncodeContext::encode_deprecation({:?})", def_id); |
e74abb32 | 1363 | if let Some(depr) = self.tcx.lookup_deprecation(def_id) { |
ba9703b0 | 1364 | record!(self.tables.deprecation[def_id] <- depr); |
e74abb32 | 1365 | } |
9e0c209e | 1366 | } |
9cc50fc6 | 1367 | |
83c7162d | 1368 | fn encode_rendered_const_for_body(&mut self, body_id: hir::BodyId) -> Lazy<RenderedConst> { |
ba9703b0 XL |
1369 | let hir = self.tcx.hir(); |
1370 | let body = hir.body(body_id); | |
1371 | let rendered = rustc_hir_pretty::to_string(&(&hir as &dyn intravisit::Map<'_>), |s| { | |
1372 | s.print_expr(&body.value) | |
1373 | }); | |
83c7162d XL |
1374 | let rendered_const = &RenderedConst(rendered); |
1375 | self.lazy(rendered_const) | |
1376 | } | |
1377 | ||
dfeec247 | 1378 | fn encode_info_for_item(&mut self, def_id: DefId, item: &'tcx hir::Item<'tcx>) { |
9e0c209e SL |
1379 | let tcx = self.tcx; |
1380 | ||
dc9dc135 | 1381 | debug!("EncodeContext::encode_info_for_item({:?})", def_id); |
9e0c209e | 1382 | |
ba9703b0 XL |
1383 | self.encode_ident_span(def_id, item.ident); |
1384 | ||
5869c6ff | 1385 | let entry_kind = match item.kind { |
dfeec247 XL |
1386 | hir::ItemKind::Static(_, hir::Mutability::Mut, _) => EntryKind::MutStatic, |
1387 | hir::ItemKind::Static(_, hir::Mutability::Not, _) => EntryKind::ImmStatic, | |
8faf50e0 | 1388 | hir::ItemKind::Const(_, body_id) => { |
60c5eb7d | 1389 | let qualifs = self.tcx.at(item.span).mir_const_qualif(def_id); |
5869c6ff | 1390 | EntryKind::Const(qualifs, self.encode_rendered_const_for_body(body_id)) |
8bb4bdeb | 1391 | } |
60c5eb7d | 1392 | hir::ItemKind::Fn(ref sig, .., body) => { |
9e0c209e | 1393 | let data = FnData { |
60c5eb7d XL |
1394 | asyncness: sig.header.asyncness, |
1395 | constness: sig.header.constness, | |
e1599b0c | 1396 | param_names: self.encode_fn_param_names_for_body(body), |
9e0c209e | 1397 | }; |
54a0048b | 1398 | |
e1599b0c | 1399 | EntryKind::Fn(self.lazy(data)) |
b039eaaf | 1400 | } |
94222f64 XL |
1401 | hir::ItemKind::Macro(ref macro_def) => { |
1402 | EntryKind::MacroDef(self.lazy(macro_def.clone())) | |
1403 | } | |
8faf50e0 | 1404 | hir::ItemKind::Mod(ref m) => { |
6a06907d | 1405 | return self.encode_info_for_mod(item.def_id, m); |
9e0c209e | 1406 | } |
fc512014 | 1407 | hir::ItemKind::ForeignMod { .. } => EntryKind::ForeignMod, |
8faf50e0 | 1408 | hir::ItemKind::GlobalAsm(..) => EntryKind::GlobalAsm, |
416331ca | 1409 | hir::ItemKind::TyAlias(..) => EntryKind::Type, |
29967ef6 XL |
1410 | hir::ItemKind::OpaqueTy(..) => { |
1411 | self.encode_explicit_item_bounds(def_id); | |
1412 | EntryKind::OpaqueTy | |
1413 | } | |
e74abb32 | 1414 | hir::ItemKind::Enum(..) => EntryKind::Enum(self.tcx.adt_def(def_id).repr), |
8faf50e0 | 1415 | hir::ItemKind::Struct(ref struct_def, _) => { |
e74abb32 XL |
1416 | let adt_def = self.tcx.adt_def(def_id); |
1417 | let variant = adt_def.non_enum_variant(); | |
9e0c209e | 1418 | |
c30ab7b3 SL |
1419 | // Encode def_ids for each field and method |
1420 | // for methods, write all the stuff get_trait_method | |
1421 | // needs to know | |
5869c6ff XL |
1422 | let ctor = struct_def |
1423 | .ctor_hir_id() | |
1424 | .map(|ctor_hir_id| self.tcx.hir().local_def_id(ctor_hir_id).local_def_index); | |
1425 | ||
1426 | EntryKind::Struct( | |
1427 | self.lazy(VariantData { | |
1428 | ctor_kind: variant.ctor_kind, | |
1429 | discr: variant.discr, | |
1430 | ctor, | |
1431 | is_non_exhaustive: variant.is_field_list_non_exhaustive(), | |
1432 | }), | |
1433 | adt_def.repr, | |
1434 | ) | |
9e0c209e | 1435 | } |
8faf50e0 | 1436 | hir::ItemKind::Union(..) => { |
e74abb32 XL |
1437 | let adt_def = self.tcx.adt_def(def_id); |
1438 | let variant = adt_def.non_enum_variant(); | |
9e0c209e | 1439 | |
5869c6ff XL |
1440 | EntryKind::Union( |
1441 | self.lazy(VariantData { | |
1442 | ctor_kind: variant.ctor_kind, | |
1443 | discr: variant.discr, | |
1444 | ctor: None, | |
1445 | is_non_exhaustive: variant.is_field_list_non_exhaustive(), | |
1446 | }), | |
1447 | adt_def.repr, | |
1448 | ) | |
9e0c209e | 1449 | } |
136023e0 | 1450 | hir::ItemKind::Impl(hir::Impl { defaultness, constness, .. }) => { |
e74abb32 XL |
1451 | let trait_ref = self.tcx.impl_trait_ref(def_id); |
1452 | let polarity = self.tcx.impl_polarity(def_id); | |
9e0c209e | 1453 | let parent = if let Some(trait_ref) = trait_ref { |
e74abb32 | 1454 | let trait_def = self.tcx.trait_def(trait_ref.def_id); |
5869c6ff XL |
1455 | trait_def.ancestors(self.tcx, def_id).ok().and_then(|mut an| { |
1456 | an.nth(1).and_then(|node| match node { | |
1457 | specialization_graph::Node::Impl(parent) => Some(parent), | |
1458 | _ => None, | |
1459 | }) | |
1460 | }) | |
9e0c209e SL |
1461 | } else { |
1462 | None | |
1463 | }; | |
b039eaaf | 1464 | |
cc61c64b XL |
1465 | // if this is an impl of `CoerceUnsized`, create its |
1466 | // "unsized info", else just store None | |
5869c6ff XL |
1467 | let coerce_unsized_info = trait_ref.and_then(|t| { |
1468 | if Some(t.def_id) == self.tcx.lang_items().coerce_unsized_trait() { | |
1469 | Some(self.tcx.at(item.span).coerce_unsized_info(def_id)) | |
1470 | } else { | |
1471 | None | |
1472 | } | |
1473 | }); | |
1474 | ||
136023e0 XL |
1475 | let data = ImplData { |
1476 | polarity, | |
1477 | defaultness, | |
1478 | constness, | |
1479 | parent_impl: parent, | |
1480 | coerce_unsized_info, | |
1481 | }; | |
1a4d82fc | 1482 | |
e1599b0c | 1483 | EntryKind::Impl(self.lazy(data)) |
9e0c209e | 1484 | } |
9fa01778 | 1485 | hir::ItemKind::Trait(..) => { |
e74abb32 | 1486 | let trait_def = self.tcx.trait_def(def_id); |
9e0c209e SL |
1487 | let data = TraitData { |
1488 | unsafety: trait_def.unsafety, | |
1489 | paren_sugar: trait_def.paren_sugar, | |
e74abb32 | 1490 | has_auto_impl: self.tcx.trait_is_auto(def_id), |
0bf4aa26 | 1491 | is_marker: trait_def.is_marker, |
cdc7bbd5 | 1492 | skip_array_during_method_dispatch: trait_def.skip_array_during_method_dispatch, |
ba9703b0 | 1493 | specialization_kind: trait_def.specialization_kind, |
9e0c209e | 1494 | }; |
b039eaaf | 1495 | |
e1599b0c | 1496 | EntryKind::Trait(self.lazy(data)) |
d9579d0f | 1497 | } |
e74abb32 | 1498 | hir::ItemKind::TraitAlias(..) => EntryKind::TraitAlias, |
5869c6ff XL |
1499 | hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => { |
1500 | bug!("cannot encode info for item {:?}", item) | |
1501 | } | |
1502 | }; | |
1503 | record!(self.tables.kind[def_id] <- entry_kind); | |
e74abb32 XL |
1504 | // FIXME(eddyb) there should be a nicer way to do this. |
1505 | match item.kind { | |
fc512014 XL |
1506 | hir::ItemKind::ForeignMod { items, .. } => record!(self.tables.children[def_id] <- |
1507 | items | |
e74abb32 | 1508 | .iter() |
6a06907d | 1509 | .map(|foreign_item| foreign_item.id.def_id.local_def_index) |
e74abb32 | 1510 | ), |
ba9703b0 | 1511 | hir::ItemKind::Enum(..) => record!(self.tables.children[def_id] <- |
e74abb32 XL |
1512 | self.tcx.adt_def(def_id).variants.iter().map(|v| { |
1513 | assert!(v.def_id.is_local()); | |
1514 | v.def_id.index | |
1515 | }) | |
1516 | ), | |
dfeec247 | 1517 | hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) => { |
ba9703b0 | 1518 | record!(self.tables.children[def_id] <- |
dfeec247 XL |
1519 | self.tcx.adt_def(def_id).non_enum_variant().fields.iter().map(|f| { |
1520 | assert!(f.did.is_local()); | |
1521 | f.did.index | |
1522 | }) | |
1523 | ) | |
1524 | } | |
1525 | hir::ItemKind::Impl { .. } | hir::ItemKind::Trait(..) => { | |
e74abb32 | 1526 | let associated_item_def_ids = self.tcx.associated_item_def_ids(def_id); |
ba9703b0 | 1527 | record!(self.tables.children[def_id] <- |
e74abb32 XL |
1528 | associated_item_def_ids.iter().map(|&def_id| { |
1529 | assert!(def_id.is_local()); | |
1530 | def_id.index | |
1531 | }) | |
1532 | ); | |
1533 | } | |
1534 | _ => {} | |
1535 | } | |
e74abb32 | 1536 | match item.kind { |
dfeec247 XL |
1537 | hir::ItemKind::Static(..) |
1538 | | hir::ItemKind::Const(..) | |
1539 | | hir::ItemKind::Fn(..) | |
1540 | | hir::ItemKind::TyAlias(..) | |
1541 | | hir::ItemKind::OpaqueTy(..) | |
1542 | | hir::ItemKind::Enum(..) | |
1543 | | hir::ItemKind::Struct(..) | |
1544 | | hir::ItemKind::Union(..) | |
1545 | | hir::ItemKind::Impl { .. } => self.encode_item_type(def_id), | |
e74abb32 XL |
1546 | _ => {} |
1547 | } | |
1548 | if let hir::ItemKind::Fn(..) = item.kind { | |
ba9703b0 | 1549 | record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); |
e74abb32 | 1550 | } |
dfeec247 | 1551 | if let hir::ItemKind::Impl { .. } = item.kind { |
e74abb32 | 1552 | if let Some(trait_ref) = self.tcx.impl_trait_ref(def_id) { |
ba9703b0 | 1553 | record!(self.tables.impl_trait_ref[def_id] <- trait_ref); |
e74abb32 XL |
1554 | } |
1555 | } | |
9e0c209e | 1556 | } |
476ff2be | 1557 | |
74b04a01 | 1558 | fn encode_info_for_generic_param(&mut self, def_id: DefId, kind: EntryKind, encode_type: bool) { |
ba9703b0 | 1559 | record!(self.tables.kind[def_id] <- kind); |
e74abb32 XL |
1560 | if encode_type { |
1561 | self.encode_item_type(def_id); | |
223e47cc | 1562 | } |
223e47cc | 1563 | } |
223e47cc | 1564 | |
f9f354fc | 1565 | fn encode_info_for_closure(&mut self, def_id: LocalDefId) { |
dc9dc135 | 1566 | debug!("EncodeContext::encode_info_for_closure({:?})", def_id); |
223e47cc | 1567 | |
e74abb32 | 1568 | // NOTE(eddyb) `tcx.type_of(def_id)` isn't used because it's fully generic, |
3dfed10e XL |
1569 | // including on the signature, which is inferred in `typeck. |
1570 | let hir_id = self.tcx.hir().local_def_id_to_hir_id(def_id); | |
1571 | let ty = self.tcx.typeck(def_id).node_type(hir_id); | |
e74abb32 | 1572 | |
5869c6ff | 1573 | match ty.kind() { |
74b04a01 XL |
1574 | ty::Generator(..) => { |
1575 | let data = self.tcx.generator_kind(def_id).unwrap(); | |
5869c6ff | 1576 | record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Generator(data)); |
ff7c6d11 XL |
1577 | } |
1578 | ||
5869c6ff XL |
1579 | ty::Closure(..) => { |
1580 | record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::Closure); | |
1581 | } | |
223e47cc | 1582 | |
e74abb32 | 1583 | _ => bug!("closure that is neither generator nor closure"), |
5869c6ff | 1584 | } |
f9f354fc | 1585 | self.encode_item_type(def_id.to_def_id()); |
1b1a35ee | 1586 | if let ty::Closure(def_id, substs) = *ty.kind() { |
ba9703b0 | 1587 | record!(self.tables.fn_sig[def_id] <- substs.as_closure().sig()); |
223e47cc | 1588 | } |
223e47cc LB |
1589 | } |
1590 | ||
f9f354fc | 1591 | fn encode_info_for_anon_const(&mut self, def_id: LocalDefId) { |
dc9dc135 | 1592 | debug!("EncodeContext::encode_info_for_anon_const({:?})", def_id); |
3dfed10e | 1593 | let id = self.tcx.hir().local_def_id_to_hir_id(def_id); |
e74abb32 | 1594 | let body_id = self.tcx.hir().body_owned_by(id); |
83c7162d | 1595 | let const_data = self.encode_rendered_const_for_body(body_id); |
60c5eb7d | 1596 | let qualifs = self.tcx.mir_const_qualif(def_id); |
cc61c64b | 1597 | |
f035d41b | 1598 | record!(self.tables.kind[def_id.to_def_id()] <- EntryKind::AnonConst(qualifs, const_data)); |
f9f354fc | 1599 | self.encode_item_type(def_id.to_def_id()); |
cc61c64b | 1600 | } |
cc61c64b | 1601 | |
f9f354fc | 1602 | fn encode_native_libraries(&mut self) -> Lazy<[NativeLib]> { |
1b1a35ee | 1603 | empty_proc_macro!(self); |
ea8adc8c | 1604 | let used_libraries = self.tcx.native_libraries(LOCAL_CRATE); |
136023e0 | 1605 | self.lazy(used_libraries.iter()) |
1a4d82fc | 1606 | } |
1a4d82fc | 1607 | |
e1599b0c | 1608 | fn encode_foreign_modules(&mut self) -> Lazy<[ForeignModule]> { |
1b1a35ee | 1609 | empty_proc_macro!(self); |
0531ce1d | 1610 | let foreign_modules = self.tcx.foreign_modules(LOCAL_CRATE); |
29967ef6 | 1611 | self.lazy(foreign_modules.iter().map(|(_, m)| m).cloned()) |
e1599b0c XL |
1612 | } |
1613 | ||
136023e0 | 1614 | fn encode_hygiene(&mut self) -> (SyntaxContextTable, ExpnDataTable, ExpnHashTable) { |
3dfed10e XL |
1615 | let mut syntax_contexts: TableBuilder<_, _> = Default::default(); |
1616 | let mut expn_data_table: TableBuilder<_, _> = Default::default(); | |
136023e0 | 1617 | let mut expn_hash_table: TableBuilder<_, _> = Default::default(); |
3dfed10e XL |
1618 | |
1619 | let _: Result<(), !> = self.hygiene_ctxt.encode( | |
136023e0 XL |
1620 | &mut (&mut *self, &mut syntax_contexts, &mut expn_data_table, &mut expn_hash_table), |
1621 | |(this, syntax_contexts, _, _), index, ctxt_data| { | |
3dfed10e XL |
1622 | syntax_contexts.set(index, this.lazy(ctxt_data)); |
1623 | Ok(()) | |
1624 | }, | |
136023e0 XL |
1625 | |(this, _, expn_data_table, expn_hash_table), index, expn_data, hash| { |
1626 | if let Some(index) = index.as_local() { | |
1627 | expn_data_table.set(index.as_raw(), this.lazy(expn_data)); | |
1628 | expn_hash_table.set(index.as_raw(), this.lazy(hash)); | |
1629 | } | |
3dfed10e XL |
1630 | Ok(()) |
1631 | }, | |
1632 | ); | |
1633 | ||
136023e0 XL |
1634 | ( |
1635 | syntax_contexts.encode(&mut self.opaque), | |
1636 | expn_data_table.encode(&mut self.opaque), | |
1637 | expn_hash_table.encode(&mut self.opaque), | |
1638 | ) | |
3dfed10e XL |
1639 | } |
1640 | ||
1b1a35ee | 1641 | fn encode_proc_macros(&mut self) -> Option<ProcMacroData> { |
f9f354fc | 1642 | let is_proc_macro = self.tcx.sess.crate_types().contains(&CrateType::ProcMacro); |
e1599b0c XL |
1643 | if is_proc_macro { |
1644 | let tcx = self.tcx; | |
1b1a35ee XL |
1645 | let hir = tcx.hir(); |
1646 | ||
17df50a5 | 1647 | let proc_macro_decls_static = tcx.proc_macro_decls_static(()).unwrap().local_def_index; |
1b1a35ee | 1648 | let stability = tcx.lookup_stability(DefId::local(CRATE_DEF_INDEX)).copied(); |
94222f64 XL |
1649 | let macros = |
1650 | self.lazy(tcx.resolutions(()).proc_macros.iter().map(|p| p.local_def_index)); | |
17df50a5 XL |
1651 | let spans = self.tcx.sess.parse_sess.proc_macro_quoted_spans(); |
1652 | for (i, span) in spans.into_iter().enumerate() { | |
1653 | let span = self.lazy(span); | |
1654 | self.tables.proc_macro_quoted_spans.set(i, span); | |
1655 | } | |
1b1a35ee | 1656 | |
5869c6ff XL |
1657 | record!(self.tables.def_kind[LOCAL_CRATE.as_def_id()] <- DefKind::Mod); |
1658 | record!(self.tables.span[LOCAL_CRATE.as_def_id()] <- tcx.def_span(LOCAL_CRATE.as_def_id())); | |
1659 | record!(self.tables.attributes[LOCAL_CRATE.as_def_id()] <- tcx.get_attrs(LOCAL_CRATE.as_def_id())); | |
1660 | record!(self.tables.visibility[LOCAL_CRATE.as_def_id()] <- tcx.visibility(LOCAL_CRATE.as_def_id())); | |
1661 | if let Some(stability) = stability { | |
1662 | record!(self.tables.stability[LOCAL_CRATE.as_def_id()] <- stability); | |
1663 | } | |
1664 | self.encode_deprecation(LOCAL_CRATE.as_def_id()); | |
1665 | ||
1b1a35ee XL |
1666 | // Normally, this information is encoded when we walk the items |
1667 | // defined in this crate. However, we skip doing that for proc-macro crates, | |
1668 | // so we manually encode just the information that we need | |
94222f64 XL |
1669 | for &proc_macro in &tcx.resolutions(()).proc_macros { |
1670 | let id = proc_macro; | |
1671 | let proc_macro = hir.local_def_id_to_hir_id(proc_macro); | |
1672 | let mut name = hir.name(proc_macro); | |
1673 | let span = hir.span(proc_macro); | |
1b1a35ee XL |
1674 | // Proc-macros may have attributes like `#[allow_internal_unstable]`, |
1675 | // so downstream crates need access to them. | |
94222f64 | 1676 | let attrs = hir.attrs(proc_macro); |
fc512014 XL |
1677 | let macro_kind = if tcx.sess.contains_name(attrs, sym::proc_macro) { |
1678 | MacroKind::Bang | |
1679 | } else if tcx.sess.contains_name(attrs, sym::proc_macro_attribute) { | |
1680 | MacroKind::Attr | |
1681 | } else if let Some(attr) = tcx.sess.find_by_name(attrs, sym::proc_macro_derive) { | |
1682 | // This unwrap chain should have been checked by the proc-macro harness. | |
1683 | name = attr.meta_item_list().unwrap()[0] | |
1684 | .meta_item() | |
1685 | .unwrap() | |
1686 | .ident() | |
1687 | .unwrap() | |
1688 | .name; | |
1689 | MacroKind::Derive | |
1690 | } else { | |
1691 | bug!("Unknown proc-macro type for item {:?}", id); | |
1692 | }; | |
1693 | ||
94222f64 | 1694 | let mut def_key = self.tcx.hir().def_key(id); |
fc512014 XL |
1695 | def_key.disambiguated_data.data = DefPathData::MacroNs(name); |
1696 | ||
94222f64 | 1697 | let def_id = id.to_def_id(); |
5869c6ff | 1698 | record!(self.tables.def_kind[def_id] <- DefKind::Macro(macro_kind)); |
fc512014 XL |
1699 | record!(self.tables.kind[def_id] <- EntryKind::ProcMacro(macro_kind)); |
1700 | record!(self.tables.attributes[def_id] <- attrs); | |
1701 | record!(self.tables.def_keys[def_id] <- def_key); | |
1702 | record!(self.tables.ident_span[def_id] <- span); | |
1703 | record!(self.tables.span[def_id] <- span); | |
1704 | record!(self.tables.visibility[def_id] <- ty::Visibility::Public); | |
1705 | if let Some(stability) = stability { | |
1706 | record!(self.tables.stability[def_id] <- stability); | |
1707 | } | |
1b1a35ee XL |
1708 | } |
1709 | ||
1710 | Some(ProcMacroData { proc_macro_decls_static, stability, macros }) | |
e1599b0c XL |
1711 | } else { |
1712 | None | |
1713 | } | |
0531ce1d XL |
1714 | } |
1715 | ||
e1599b0c | 1716 | fn encode_crate_deps(&mut self) -> Lazy<[CrateDep]> { |
1b1a35ee | 1717 | empty_proc_macro!(self); |
9e0c209e | 1718 | |
c295e0f8 XL |
1719 | let deps = self |
1720 | .tcx | |
1721 | .crates(()) | |
7cac9316 XL |
1722 | .iter() |
1723 | .map(|&cnum| { | |
1724 | let dep = CrateDep { | |
17df50a5 | 1725 | name: self.tcx.crate_name(cnum), |
ea8adc8c | 1726 | hash: self.tcx.crate_hash(cnum), |
e74abb32 | 1727 | host_hash: self.tcx.crate_host_hash(cnum), |
ea8adc8c | 1728 | kind: self.tcx.dep_kind(cnum), |
83c7162d | 1729 | extra_filename: self.tcx.extra_filename(cnum), |
7cac9316 XL |
1730 | }; |
1731 | (cnum, dep) | |
1732 | }) | |
1733 | .collect::<Vec<_>>(); | |
1734 | ||
7cac9316 | 1735 | { |
9e0c209e SL |
1736 | // Sanity-check the crate numbers |
1737 | let mut expected_cnum = 1; | |
1738 | for &(n, _) in &deps { | |
1739 | assert_eq!(n, CrateNum::new(expected_cnum)); | |
1740 | expected_cnum += 1; | |
1a4d82fc JJ |
1741 | } |
1742 | } | |
1a4d82fc | 1743 | |
9e0c209e SL |
1744 | // We're just going to write a list of crate 'name-hash-version's, with |
1745 | // the assumption that they are numbered 1 to n. | |
1746 | // FIXME (#2166): This is not nearly enough to support correct versioning | |
1747 | // but is enough to get transitive crate dependencies working. | |
e1599b0c | 1748 | self.lazy(deps.iter().map(|&(_, ref dep)| dep)) |
223e47cc | 1749 | } |
1a4d82fc | 1750 | |
f9f354fc | 1751 | fn encode_lib_features(&mut self) -> Lazy<[(Symbol, Option<Symbol>)]> { |
1b1a35ee | 1752 | empty_proc_macro!(self); |
b7449926 XL |
1753 | let tcx = self.tcx; |
1754 | let lib_features = tcx.lib_features(); | |
e1599b0c XL |
1755 | self.lazy(lib_features.to_vec()) |
1756 | } | |
1757 | ||
1758 | fn encode_diagnostic_items(&mut self) -> Lazy<[(Symbol, DefIndex)]> { | |
1b1a35ee | 1759 | empty_proc_macro!(self); |
e1599b0c | 1760 | let tcx = self.tcx; |
c295e0f8 | 1761 | let diagnostic_items = &tcx.diagnostic_items(LOCAL_CRATE).name_to_id; |
e1599b0c | 1762 | self.lazy(diagnostic_items.iter().map(|(&name, def_id)| (name, def_id.index))) |
b7449926 XL |
1763 | } |
1764 | ||
e1599b0c | 1765 | fn encode_lang_items(&mut self) -> Lazy<[(DefIndex, usize)]> { |
1b1a35ee | 1766 | empty_proc_macro!(self); |
9e0c209e | 1767 | let tcx = self.tcx; |
ea8adc8c XL |
1768 | let lang_items = tcx.lang_items(); |
1769 | let lang_items = lang_items.items().iter(); | |
e1599b0c | 1770 | self.lazy(lang_items.enumerate().filter_map(|(i, &opt_def_id)| { |
9e0c209e SL |
1771 | if let Some(def_id) = opt_def_id { |
1772 | if def_id.is_local() { | |
1773 | return Some((def_id.index, i)); | |
1774 | } | |
1a4d82fc | 1775 | } |
9e0c209e | 1776 | None |
7cac9316 | 1777 | })) |
1a4d82fc | 1778 | } |
476ff2be | 1779 | |
e1599b0c | 1780 | fn encode_lang_items_missing(&mut self) -> Lazy<[lang_items::LangItem]> { |
1b1a35ee | 1781 | empty_proc_macro!(self); |
7cac9316 | 1782 | let tcx = self.tcx; |
e1599b0c | 1783 | self.lazy(&tcx.lang_items().missing) |
476ff2be | 1784 | } |
1a4d82fc | 1785 | |
9e0c209e | 1786 | /// Encodes an index, mapping each trait to its (local) implementations. |
e1599b0c | 1787 | fn encode_impls(&mut self) -> Lazy<[TraitImpls]> { |
1b1a35ee | 1788 | empty_proc_macro!(self); |
dc9dc135 | 1789 | debug!("EncodeContext::encode_impls()"); |
7cac9316 | 1790 | let tcx = self.tcx; |
dfeec247 | 1791 | let mut visitor = ImplVisitor { tcx, impls: FxHashMap::default() }; |
c295e0f8 | 1792 | tcx.hir().visit_all_item_likes(&mut visitor); |
1a4d82fc | 1793 | |
7cac9316 XL |
1794 | let mut all_impls: Vec<_> = visitor.impls.into_iter().collect(); |
1795 | ||
1796 | // Bring everything into deterministic order for hashing | |
dfeec247 | 1797 | all_impls.sort_by_cached_key(|&(trait_def_id, _)| tcx.def_path_hash(trait_def_id)); |
7cac9316 XL |
1798 | |
1799 | let all_impls: Vec<_> = all_impls | |
c30ab7b3 | 1800 | .into_iter() |
7cac9316 XL |
1801 | .map(|(trait_def_id, mut impls)| { |
1802 | // Bring everything into deterministic order for hashing | |
3dfed10e | 1803 | impls.sort_by_cached_key(|&(index, _)| { |
136023e0 | 1804 | tcx.hir().def_path_hash(LocalDefId { local_def_index: index }) |
7cac9316 XL |
1805 | }); |
1806 | ||
c30ab7b3 SL |
1807 | TraitImpls { |
1808 | trait_id: (trait_def_id.krate.as_u32(), trait_def_id.index), | |
e1599b0c | 1809 | impls: self.lazy(&impls), |
c30ab7b3 SL |
1810 | } |
1811 | }) | |
1812 | .collect(); | |
1a4d82fc | 1813 | |
e1599b0c | 1814 | self.lazy(&all_impls) |
1a4d82fc | 1815 | } |
970d7e83 | 1816 | |
476ff2be | 1817 | // Encodes all symbols exported from this crate into the metadata. |
9e0c209e SL |
1818 | // |
1819 | // This pass is seeded off the reachability list calculated in the | |
1820 | // middle::reachable module but filters out items that either don't have a | |
1821 | // symbol associated with them (they weren't translated) or if they're an FFI | |
1822 | // definition (as that's not defined in this crate). | |
dfeec247 XL |
1823 | fn encode_exported_symbols( |
1824 | &mut self, | |
1825 | exported_symbols: &[(ExportedSymbol<'tcx>, SymbolExportLevel)], | |
1826 | ) -> Lazy<[(ExportedSymbol<'tcx>, SymbolExportLevel)]> { | |
1b1a35ee | 1827 | empty_proc_macro!(self); |
0531ce1d XL |
1828 | // The metadata symbol name is special. It should not show up in |
1829 | // downstream crates. | |
3dfed10e | 1830 | let metadata_symbol_name = SymbolName::new(self.tcx, &metadata_symbol_name(self.tcx)); |
0531ce1d | 1831 | |
dfeec247 XL |
1832 | self.lazy( |
1833 | exported_symbols | |
1834 | .iter() | |
1835 | .filter(|&&(ref exported_symbol, _)| match *exported_symbol { | |
1836 | ExportedSymbol::NoDefId(symbol_name) => symbol_name != metadata_symbol_name, | |
0531ce1d | 1837 | _ => true, |
dfeec247 XL |
1838 | }) |
1839 | .cloned(), | |
1840 | ) | |
0531ce1d XL |
1841 | } |
1842 | ||
e1599b0c | 1843 | fn encode_dylib_dependency_formats(&mut self) -> Lazy<[Option<LinkagePreference>]> { |
1b1a35ee | 1844 | empty_proc_macro!(self); |
17df50a5 | 1845 | let formats = self.tcx.dependency_formats(()); |
e74abb32 | 1846 | for (ty, arr) in formats.iter() { |
f9f354fc | 1847 | if *ty != CrateType::Dylib { |
e74abb32 | 1848 | continue; |
9e0c209e | 1849 | } |
dfeec247 XL |
1850 | return self.lazy(arr.iter().map(|slot| match *slot { |
1851 | Linkage::NotLinked | Linkage::IncludedFromDylib => None, | |
e74abb32 | 1852 | |
dfeec247 XL |
1853 | Linkage::Dynamic => Some(LinkagePreference::RequireDynamic), |
1854 | Linkage::Static => Some(LinkagePreference::RequireStatic), | |
e74abb32 | 1855 | })); |
a7813a04 | 1856 | } |
e74abb32 | 1857 | Lazy::empty() |
a7813a04 | 1858 | } |
1a4d82fc | 1859 | |
dfeec247 | 1860 | fn encode_info_for_foreign_item(&mut self, def_id: DefId, nitem: &hir::ForeignItem<'_>) { |
7cac9316 | 1861 | let tcx = self.tcx; |
9e0c209e | 1862 | |
dc9dc135 | 1863 | debug!("EncodeContext::encode_info_for_foreign_item({:?})", def_id); |
9e0c209e | 1864 | |
5869c6ff | 1865 | match nitem.kind { |
8faf50e0 | 1866 | hir::ForeignItemKind::Fn(_, ref names, _) => { |
7cac9316 | 1867 | let data = FnData { |
e1599b0c | 1868 | asyncness: hir::IsAsync::NotAsync, |
60c5eb7d XL |
1869 | constness: if self.tcx.is_const_fn_raw(def_id) { |
1870 | hir::Constness::Const | |
1871 | } else { | |
1872 | hir::Constness::NotConst | |
1873 | }, | |
e1599b0c | 1874 | param_names: self.encode_fn_param_names(names), |
7cac9316 | 1875 | }; |
5869c6ff | 1876 | record!(self.tables.kind[def_id] <- EntryKind::ForeignFn(self.lazy(data))); |
7cac9316 | 1877 | } |
5869c6ff XL |
1878 | hir::ForeignItemKind::Static(_, hir::Mutability::Mut) => { |
1879 | record!(self.tables.kind[def_id] <- EntryKind::ForeignMutStatic); | |
1880 | } | |
1881 | hir::ForeignItemKind::Static(_, hir::Mutability::Not) => { | |
1882 | record!(self.tables.kind[def_id] <- EntryKind::ForeignImmStatic); | |
1883 | } | |
1884 | hir::ForeignItemKind::Type => { | |
1885 | record!(self.tables.kind[def_id] <- EntryKind::ForeignType); | |
1886 | } | |
1887 | } | |
ba9703b0 | 1888 | self.encode_ident_span(def_id, nitem.ident); |
e74abb32 XL |
1889 | self.encode_item_type(def_id); |
1890 | if let hir::ForeignItemKind::Fn(..) = nitem.kind { | |
ba9703b0 | 1891 | record!(self.tables.fn_sig[def_id] <- tcx.fn_sig(def_id)); |
7cac9316 XL |
1892 | } |
1893 | } | |
1894 | } | |
9e0c209e | 1895 | |
e74abb32 | 1896 | // FIXME(eddyb) make metadata encoding walk over all definitions, instead of HIR. |
3dfed10e | 1897 | impl Visitor<'tcx> for EncodeContext<'a, 'tcx> { |
dfeec247 XL |
1898 | type Map = Map<'tcx>; |
1899 | ||
ba9703b0 XL |
1900 | fn nested_visit_map(&mut self) -> NestedVisitorMap<Self::Map> { |
1901 | NestedVisitorMap::OnlyBodies(self.tcx.hir()) | |
7cac9316 | 1902 | } |
dfeec247 | 1903 | fn visit_expr(&mut self, ex: &'tcx hir::Expr<'tcx>) { |
7cac9316 | 1904 | intravisit::walk_expr(self, ex); |
dc9dc135 | 1905 | self.encode_info_for_expr(ex); |
7cac9316 | 1906 | } |
e74abb32 XL |
1907 | fn visit_anon_const(&mut self, c: &'tcx AnonConst) { |
1908 | intravisit::walk_anon_const(self, c); | |
1909 | let def_id = self.tcx.hir().local_def_id(c.hir_id); | |
1910 | self.encode_info_for_anon_const(def_id); | |
1911 | } | |
dfeec247 | 1912 | fn visit_item(&mut self, item: &'tcx hir::Item<'tcx>) { |
7cac9316 | 1913 | intravisit::walk_item(self, item); |
e74abb32 | 1914 | match item.kind { |
dfeec247 | 1915 | hir::ItemKind::ExternCrate(_) | hir::ItemKind::Use(..) => {} // ignore these |
6a06907d | 1916 | _ => self.encode_info_for_item(item.def_id.to_def_id(), item), |
7cac9316 | 1917 | } |
dc9dc135 | 1918 | self.encode_addl_info_for_item(item); |
7cac9316 | 1919 | } |
dfeec247 | 1920 | fn visit_foreign_item(&mut self, ni: &'tcx hir::ForeignItem<'tcx>) { |
7cac9316 | 1921 | intravisit::walk_foreign_item(self, ni); |
6a06907d | 1922 | self.encode_info_for_foreign_item(ni.def_id.to_def_id(), ni); |
7cac9316 | 1923 | } |
dfeec247 | 1924 | fn visit_generics(&mut self, generics: &'tcx hir::Generics<'tcx>) { |
7cac9316 | 1925 | intravisit::walk_generics(self, generics); |
dc9dc135 | 1926 | self.encode_info_for_generics(generics); |
7cac9316 | 1927 | } |
7cac9316 | 1928 | } |
9e0c209e | 1929 | |
3dfed10e | 1930 | impl EncodeContext<'a, 'tcx> { |
f9f354fc XL |
1931 | fn encode_fields(&mut self, adt_def: &ty::AdtDef) { |
1932 | for (variant_index, variant) in adt_def.variants.iter_enumerated() { | |
e74abb32 | 1933 | for (field_index, _field) in variant.fields.iter().enumerate() { |
f9f354fc | 1934 | self.encode_field(adt_def, variant_index, field_index); |
7cac9316 XL |
1935 | } |
1936 | } | |
1937 | } | |
9e0c209e | 1938 | |
dfeec247 XL |
1939 | fn encode_info_for_generics(&mut self, generics: &hir::Generics<'tcx>) { |
1940 | for param in generics.params { | |
416331ca | 1941 | let def_id = self.tcx.hir().local_def_id(param.hir_id); |
b7449926 | 1942 | match param.kind { |
532ac7d7 | 1943 | GenericParamKind::Lifetime { .. } => continue, |
5869c6ff | 1944 | GenericParamKind::Type { default, .. } => { |
e74abb32 | 1945 | self.encode_info_for_generic_param( |
f9f354fc | 1946 | def_id.to_def_id(), |
e74abb32 XL |
1947 | EntryKind::TypeParam, |
1948 | default.is_some(), | |
532ac7d7 | 1949 | ); |
b7449926 | 1950 | } |
cdc7bbd5 XL |
1951 | GenericParamKind::Const { ref default, .. } => { |
1952 | let def_id = def_id.to_def_id(); | |
1953 | self.encode_info_for_generic_param(def_id, EntryKind::ConstParam, true); | |
1954 | if default.is_some() { | |
1955 | record!(self.tables.const_defaults[def_id] <- self.tcx.const_param_default(def_id)) | |
1956 | } | |
9fa01778 | 1957 | } |
8faf50e0 | 1958 | } |
b7449926 | 1959 | } |
7cac9316 | 1960 | } |
9cc50fc6 | 1961 | |
dfeec247 | 1962 | fn encode_info_for_expr(&mut self, expr: &hir::Expr<'_>) { |
ba9703b0 XL |
1963 | if let hir::ExprKind::Closure(..) = expr.kind { |
1964 | let def_id = self.tcx.hir().local_def_id(expr.hir_id); | |
1965 | self.encode_info_for_closure(def_id); | |
7cac9316 XL |
1966 | } |
1967 | } | |
1968 | ||
ba9703b0 XL |
1969 | fn encode_ident_span(&mut self, def_id: DefId, ident: Ident) { |
1970 | record!(self.tables.ident_span[def_id] <- ident.span); | |
1971 | } | |
1972 | ||
7cac9316 XL |
1973 | /// In some cases, along with the item itself, we also |
1974 | /// encode some sub-items. Usually we want some info from the item | |
1975 | /// so it's easier to do that here then to wait until we would encounter | |
1976 | /// normally in the visitor walk. | |
dfeec247 | 1977 | fn encode_addl_info_for_item(&mut self, item: &hir::Item<'_>) { |
e74abb32 | 1978 | match item.kind { |
dfeec247 XL |
1979 | hir::ItemKind::Static(..) |
1980 | | hir::ItemKind::Const(..) | |
1981 | | hir::ItemKind::Fn(..) | |
94222f64 | 1982 | | hir::ItemKind::Macro(..) |
dfeec247 | 1983 | | hir::ItemKind::Mod(..) |
fc512014 | 1984 | | hir::ItemKind::ForeignMod { .. } |
dfeec247 XL |
1985 | | hir::ItemKind::GlobalAsm(..) |
1986 | | hir::ItemKind::ExternCrate(..) | |
1987 | | hir::ItemKind::Use(..) | |
1988 | | hir::ItemKind::TyAlias(..) | |
1989 | | hir::ItemKind::OpaqueTy(..) | |
1990 | | hir::ItemKind::TraitAlias(..) => { | |
7cac9316 XL |
1991 | // no sub-item recording needed in these cases |
1992 | } | |
8faf50e0 | 1993 | hir::ItemKind::Enum(..) => { |
6a06907d | 1994 | let def = self.tcx.adt_def(item.def_id.to_def_id()); |
f9f354fc | 1995 | self.encode_fields(def); |
7cac9316 | 1996 | |
a1dfa0c6 | 1997 | for (i, variant) in def.variants.iter_enumerated() { |
f9f354fc | 1998 | self.encode_enum_variant_info(def, i); |
e74abb32 | 1999 | |
e74abb32 | 2000 | if let Some(_ctor_def_id) = variant.ctor_def_id { |
f9f354fc | 2001 | self.encode_enum_variant_ctor(def, i); |
532ac7d7 | 2002 | } |
7cac9316 XL |
2003 | } |
2004 | } | |
8faf50e0 | 2005 | hir::ItemKind::Struct(ref struct_def, _) => { |
6a06907d | 2006 | let def = self.tcx.adt_def(item.def_id.to_def_id()); |
f9f354fc | 2007 | self.encode_fields(def); |
7cac9316 XL |
2008 | |
2009 | // If the struct has a constructor, encode it. | |
532ac7d7 | 2010 | if let Some(ctor_hir_id) = struct_def.ctor_hir_id() { |
416331ca | 2011 | let ctor_def_id = self.tcx.hir().local_def_id(ctor_hir_id); |
f9f354fc | 2012 | self.encode_struct_ctor(def, ctor_def_id.to_def_id()); |
7cac9316 XL |
2013 | } |
2014 | } | |
8faf50e0 | 2015 | hir::ItemKind::Union(..) => { |
6a06907d | 2016 | let def = self.tcx.adt_def(item.def_id.to_def_id()); |
f9f354fc | 2017 | self.encode_fields(def); |
7cac9316 | 2018 | } |
dfeec247 | 2019 | hir::ItemKind::Impl { .. } => { |
f9f354fc | 2020 | for &trait_item_def_id in |
6a06907d | 2021 | self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter() |
f9f354fc | 2022 | { |
e74abb32 | 2023 | self.encode_info_for_impl_item(trait_item_def_id); |
7cac9316 XL |
2024 | } |
2025 | } | |
8faf50e0 | 2026 | hir::ItemKind::Trait(..) => { |
6a06907d XL |
2027 | for &item_def_id in self.tcx.associated_item_def_ids(item.def_id.to_def_id()).iter() |
2028 | { | |
e74abb32 | 2029 | self.encode_info_for_trait_item(item_def_id); |
9e0c209e | 2030 | } |
223e47cc | 2031 | } |
7cac9316 XL |
2032 | } |
2033 | } | |
2034 | } | |
9e0c209e | 2035 | |
dc9dc135 XL |
2036 | struct ImplVisitor<'tcx> { |
2037 | tcx: TyCtxt<'tcx>, | |
3dfed10e | 2038 | impls: FxHashMap<DefId, Vec<(DefIndex, Option<ty::fast_reject::SimplifiedType>)>>, |
7cac9316 XL |
2039 | } |
2040 | ||
dc9dc135 | 2041 | impl<'tcx, 'v> ItemLikeVisitor<'v> for ImplVisitor<'tcx> { |
dfeec247 XL |
2042 | fn visit_item(&mut self, item: &hir::Item<'_>) { |
2043 | if let hir::ItemKind::Impl { .. } = item.kind { | |
6a06907d | 2044 | if let Some(trait_ref) = self.tcx.impl_trait_ref(item.def_id.to_def_id()) { |
3dfed10e XL |
2045 | let simplified_self_ty = |
2046 | ty::fast_reject::simplify_type(self.tcx, trait_ref.self_ty(), false); | |
2047 | ||
2048 | self.impls | |
2049 | .entry(trait_ref.def_id) | |
2050 | .or_default() | |
6a06907d | 2051 | .push((item.def_id.local_def_index, simplified_self_ty)); |
7cac9316 | 2052 | } |
223e47cc | 2053 | } |
7cac9316 | 2054 | } |
223e47cc | 2055 | |
dfeec247 | 2056 | fn visit_trait_item(&mut self, _trait_item: &'v hir::TraitItem<'v>) {} |
7cac9316 | 2057 | |
dfeec247 | 2058 | fn visit_impl_item(&mut self, _impl_item: &'v hir::ImplItem<'v>) { |
7cac9316 | 2059 | // handled in `visit_item` above |
223e47cc | 2060 | } |
fc512014 XL |
2061 | |
2062 | fn visit_foreign_item(&mut self, _foreign_item: &'v hir::ForeignItem<'v>) {} | |
223e47cc LB |
2063 | } |
2064 | ||
ba9703b0 XL |
2065 | /// Used to prefetch queries which will be needed later by metadata encoding. |
2066 | /// Only a subset of the queries are actually prefetched to keep this code smaller. | |
5869c6ff XL |
2067 | fn prefetch_mir(tcx: TyCtxt<'_>) { |
2068 | if !tcx.sess.opts.output_types.should_codegen() { | |
2069 | // We won't emit MIR, so don't prefetch it. | |
2070 | return; | |
ba9703b0 | 2071 | } |
ba9703b0 | 2072 | |
17df50a5 | 2073 | par_iter(tcx.mir_keys(())).for_each(|&def_id| { |
5869c6ff | 2074 | let (encode_const, encode_opt) = should_encode_mir(tcx, def_id); |
ba9703b0 | 2075 | |
5869c6ff XL |
2076 | if encode_const { |
2077 | tcx.ensure().mir_for_ctfe(def_id); | |
ba9703b0 | 2078 | } |
5869c6ff XL |
2079 | if encode_opt { |
2080 | tcx.ensure().optimized_mir(def_id); | |
2081 | } | |
2082 | if encode_opt || encode_const { | |
2083 | tcx.ensure().promoted_mir(def_id); | |
2084 | } | |
2085 | }) | |
ba9703b0 XL |
2086 | } |
2087 | ||
9e0c209e SL |
2088 | // NOTE(eddyb) The following comment was preserved for posterity, even |
2089 | // though it's no longer relevant as EBML (which uses nested & tagged | |
2090 | // "documents") was replaced with a scheme that can't go out of bounds. | |
2091 | // | |
2092 | // And here we run into yet another obscure archive bug: in which metadata | |
2093 | // loaded from archives may have trailing garbage bytes. Awhile back one of | |
cc61c64b | 2094 | // our tests was failing sporadically on the macOS 64-bit builders (both nopt |
9e0c209e SL |
2095 | // and opt) by having ebml generate an out-of-bounds panic when looking at |
2096 | // metadata. | |
2097 | // | |
2098 | // Upon investigation it turned out that the metadata file inside of an rlib | |
2099 | // (and ar archive) was being corrupted. Some compilations would generate a | |
2100 | // metadata file which would end in a few extra bytes, while other | |
2101 | // compilations would not have these extra bytes appended to the end. These | |
2102 | // extra bytes were interpreted by ebml as an extra tag, so they ended up | |
2103 | // being interpreted causing the out-of-bounds. | |
2104 | // | |
2105 | // The root cause of why these extra bytes were appearing was never | |
2106 | // discovered, and in the meantime the solution we're employing is to insert | |
2107 | // the length of the metadata to the start of the metadata. Later on this | |
2108 | // will allow us to slice the metadata to the precise length that we just | |
2109 | // generated regardless of trailing bytes that end up in it. | |
2110 | ||
c295e0f8 XL |
2111 | #[derive(Encodable, Decodable)] |
2112 | pub struct EncodedMetadata { | |
2113 | raw_data: Vec<u8>, | |
2114 | } | |
2115 | ||
2116 | impl EncodedMetadata { | |
2117 | #[inline] | |
2118 | pub fn new() -> EncodedMetadata { | |
2119 | EncodedMetadata { raw_data: Vec::new() } | |
2120 | } | |
2121 | ||
2122 | #[inline] | |
2123 | pub fn raw_data(&self) -> &[u8] { | |
2124 | &self.raw_data[..] | |
2125 | } | |
2126 | } | |
2127 | ||
2128 | pub fn encode_metadata(tcx: TyCtxt<'_>) -> EncodedMetadata { | |
2129 | let _prof_timer = tcx.prof.verbose_generic_activity("generate_crate_metadata"); | |
2130 | ||
ba9703b0 XL |
2131 | // Since encoding metadata is not in a query, and nothing is cached, |
2132 | // there's no need to do dep-graph tracking for any of it. | |
2133 | tcx.dep_graph.assert_ignored(); | |
2134 | ||
2135 | join( | |
2136 | || encode_metadata_impl(tcx), | |
2137 | || { | |
2138 | if tcx.sess.threads() == 1 { | |
2139 | return; | |
2140 | } | |
2141 | // Prefetch some queries used by metadata encoding. | |
2142 | // This is not necessary for correctness, but is only done for performance reasons. | |
2143 | // It can be removed if it turns out to cause trouble or be detrimental to performance. | |
5869c6ff | 2144 | join(|| prefetch_mir(tcx), || tcx.exported_symbols(LOCAL_CRATE)); |
ba9703b0 XL |
2145 | }, |
2146 | ) | |
2147 | .0 | |
2148 | } | |
2149 | ||
2150 | fn encode_metadata_impl(tcx: TyCtxt<'_>) -> EncodedMetadata { | |
8faf50e0 | 2151 | let mut encoder = opaque::Encoder::new(vec![]); |
cdc7bbd5 | 2152 | encoder.emit_raw_bytes(METADATA_HEADER).unwrap(); |
9e0c209e | 2153 | |
7cac9316 | 2154 | // Will be filled with the root position after encoding everything. |
cdc7bbd5 | 2155 | encoder.emit_raw_bytes(&[0, 0, 0, 0]).unwrap(); |
9e0c209e | 2156 | |
f035d41b | 2157 | let source_map_files = tcx.sess.source_map().files(); |
29967ef6 XL |
2158 | let source_file_cache = (source_map_files[0].clone(), 0); |
2159 | let required_source_files = Some(GrowableBitSet::with_capacity(source_map_files.len())); | |
2160 | drop(source_map_files); | |
2161 | ||
3dfed10e | 2162 | let hygiene_ctxt = HygieneEncodeContext::default(); |
f035d41b | 2163 | |
ba9703b0 XL |
2164 | let mut ecx = EncodeContext { |
2165 | opaque: encoder, | |
2166 | tcx, | |
1b1a35ee | 2167 | feat: tcx.features(), |
ba9703b0 XL |
2168 | tables: Default::default(), |
2169 | lazy_state: LazyState::NoNode, | |
2170 | type_shorthands: Default::default(), | |
2171 | predicate_shorthands: Default::default(), | |
29967ef6 | 2172 | source_file_cache, |
ba9703b0 | 2173 | interpret_allocs: Default::default(), |
29967ef6 | 2174 | required_source_files, |
f035d41b | 2175 | is_proc_macro: tcx.sess.crate_types().contains(&CrateType::ProcMacro), |
3dfed10e | 2176 | hygiene_ctxt: &hygiene_ctxt, |
ba9703b0 XL |
2177 | }; |
2178 | ||
2179 | // Encode the rustc version string in a predictable location. | |
2180 | rustc_version().encode(&mut ecx).unwrap(); | |
2181 | ||
2182 | // Encode all the entries and extra information in the crate, | |
2183 | // culminating in the `CrateRoot` which points to all of it. | |
2184 | let root = ecx.encode_crate_root(); | |
2185 | ||
2186 | let mut result = ecx.opaque.into_inner(); | |
9e0c209e SL |
2187 | |
2188 | // Encode the root position. | |
2189 | let header = METADATA_HEADER.len(); | |
e74abb32 | 2190 | let pos = root.position.get(); |
9e0c209e SL |
2191 | result[header + 0] = (pos >> 24) as u8; |
2192 | result[header + 1] = (pos >> 16) as u8; | |
c30ab7b3 SL |
2193 | result[header + 2] = (pos >> 8) as u8; |
2194 | result[header + 3] = (pos >> 0) as u8; | |
9e0c209e | 2195 | |
3c0e092e XL |
2196 | // Record metadata size for self-profiling |
2197 | tcx.prof.artifact_size("crate_metadata", "crate_metadata", result.len() as u64); | |
2198 | ||
ff7c6d11 | 2199 | EncodedMetadata { raw_data: result } |
223e47cc | 2200 | } |