]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/monomorphize/collector.rs
1106eba104682fb2cdfb739369bdcd3145d531f9
[rust.git] / src / librustc_mir / monomorphize / collector.rs
1 //! Mono Item Collection
2 //! ====================
3 //!
4 //! This module is responsible for discovering all items that will contribute to
5 //! to code generation of the crate. The important part here is that it not only
6 //! needs to find syntax-level items (functions, structs, etc) but also all
7 //! their monomorphized instantiations. Every non-generic, non-const function
8 //! maps to one LLVM artifact. Every generic function can produce
9 //! from zero to N artifacts, depending on the sets of type arguments it
10 //! is instantiated with.
11 //! This also applies to generic items from other crates: A generic definition
12 //! in crate X might produce monomorphizations that are compiled into crate Y.
13 //! We also have to collect these here.
14 //!
15 //! The following kinds of "mono items" are handled here:
16 //!
17 //! - Functions
18 //! - Methods
19 //! - Closures
20 //! - Statics
21 //! - Drop glue
22 //!
23 //! The following things also result in LLVM artifacts, but are not collected
24 //! here, since we instantiate them locally on demand when needed in a given
25 //! codegen unit:
26 //!
27 //! - Constants
28 //! - Vtables
29 //! - Object Shims
30 //!
31 //!
32 //! General Algorithm
33 //! -----------------
34 //! Let's define some terms first:
35 //!
36 //! - A "mono item" is something that results in a function or global in
37 //!   the LLVM IR of a codegen unit. Mono items do not stand on their
38 //!   own, they can reference other mono items. For example, if function
39 //!   `foo()` calls function `bar()` then the mono item for `foo()`
40 //!   references the mono item for function `bar()`. In general, the
41 //!   definition for mono item A referencing a mono item B is that
42 //!   the LLVM artifact produced for A references the LLVM artifact produced
43 //!   for B.
44 //!
45 //! - Mono items and the references between them form a directed graph,
46 //!   where the mono items are the nodes and references form the edges.
47 //!   Let's call this graph the "mono item graph".
48 //!
49 //! - The mono item graph for a program contains all mono items
50 //!   that are needed in order to produce the complete LLVM IR of the program.
51 //!
52 //! The purpose of the algorithm implemented in this module is to build the
53 //! mono item graph for the current crate. It runs in two phases:
54 //!
55 //! 1. Discover the roots of the graph by traversing the HIR of the crate.
56 //! 2. Starting from the roots, find neighboring nodes by inspecting the MIR
57 //!    representation of the item corresponding to a given node, until no more
58 //!    new nodes are found.
59 //!
60 //! ### Discovering roots
61 //!
62 //! The roots of the mono item graph correspond to the non-generic
63 //! syntactic items in the source code. We find them by walking the HIR of the
64 //! crate, and whenever we hit upon a function, method, or static item, we
65 //! create a mono item consisting of the items DefId and, since we only
66 //! consider non-generic items, an empty type-substitution set.
67 //!
68 //! ### Finding neighbor nodes
69 //! Given a mono item node, we can discover neighbors by inspecting its
70 //! MIR. We walk the MIR and any time we hit upon something that signifies a
71 //! reference to another mono item, we have found a neighbor. Since the
72 //! mono item we are currently at is always monomorphic, we also know the
73 //! concrete type arguments of its neighbors, and so all neighbors again will be
74 //! monomorphic. The specific forms a reference to a neighboring node can take
75 //! in MIR are quite diverse. Here is an overview:
76 //!
77 //! #### Calling Functions/Methods
78 //! The most obvious form of one mono item referencing another is a
79 //! function or method call (represented by a CALL terminator in MIR). But
80 //! calls are not the only thing that might introduce a reference between two
81 //! function mono items, and as we will see below, they are just a
82 //! specialized of the form described next, and consequently will don't get any
83 //! special treatment in the algorithm.
84 //!
85 //! #### Taking a reference to a function or method
86 //! A function does not need to actually be called in order to be a neighbor of
87 //! another function. It suffices to just take a reference in order to introduce
88 //! an edge. Consider the following example:
89 //!
90 //! ```rust
91 //! fn print_val<T: Display>(x: T) {
92 //!     println!("{}", x);
93 //! }
94 //!
95 //! fn call_fn(f: &Fn(i32), x: i32) {
96 //!     f(x);
97 //! }
98 //!
99 //! fn main() {
100 //!     let print_i32 = print_val::<i32>;
101 //!     call_fn(&print_i32, 0);
102 //! }
103 //! ```
104 //! The MIR of none of these functions will contain an explicit call to
105 //! `print_val::<i32>`. Nonetheless, in order to mono this program, we need
106 //! an instance of this function. Thus, whenever we encounter a function or
107 //! method in operand position, we treat it as a neighbor of the current
108 //! mono item. Calls are just a special case of that.
109 //!
110 //! #### Closures
111 //! In a way, closures are a simple case. Since every closure object needs to be
112 //! constructed somewhere, we can reliably discover them by observing
113 //! `RValue::Aggregate` expressions with `AggregateKind::Closure`. This is also
114 //! true for closures inlined from other crates.
115 //!
116 //! #### Drop glue
117 //! Drop glue mono items are introduced by MIR drop-statements. The
118 //! generated mono item will again have drop-glue item neighbors if the
119 //! type to be dropped contains nested values that also need to be dropped. It
120 //! might also have a function item neighbor for the explicit `Drop::drop`
121 //! implementation of its type.
122 //!
123 //! #### Unsizing Casts
124 //! A subtle way of introducing neighbor edges is by casting to a trait object.
125 //! Since the resulting fat-pointer contains a reference to a vtable, we need to
126 //! instantiate all object-save methods of the trait, as we need to store
127 //! pointers to these functions even if they never get called anywhere. This can
128 //! be seen as a special case of taking a function reference.
129 //!
130 //! #### Boxes
131 //! Since `Box` expression have special compiler support, no explicit calls to
132 //! `exchange_malloc()` and `box_free()` may show up in MIR, even if the
133 //! compiler will generate them. We have to observe `Rvalue::Box` expressions
134 //! and Box-typed drop-statements for that purpose.
135 //!
136 //!
137 //! Interaction with Cross-Crate Inlining
138 //! -------------------------------------
139 //! The binary of a crate will not only contain machine code for the items
140 //! defined in the source code of that crate. It will also contain monomorphic
141 //! instantiations of any extern generic functions and of functions marked with
142 //! `#[inline]`.
143 //! The collection algorithm handles this more or less mono. If it is
144 //! about to create a mono item for something with an external `DefId`,
145 //! it will take a look if the MIR for that item is available, and if so just
146 //! proceed normally. If the MIR is not available, it assumes that the item is
147 //! just linked to and no node is created; which is exactly what we want, since
148 //! no machine code should be generated in the current crate for such an item.
149 //!
150 //! Eager and Lazy Collection Mode
151 //! ------------------------------
152 //! Mono item collection can be performed in one of two modes:
153 //!
154 //! - Lazy mode means that items will only be instantiated when actually
155 //!   referenced. The goal is to produce the least amount of machine code
156 //!   possible.
157 //!
158 //! - Eager mode is meant to be used in conjunction with incremental compilation
159 //!   where a stable set of mono items is more important than a minimal
160 //!   one. Thus, eager mode will instantiate drop-glue for every drop-able type
161 //!   in the crate, even of no drop call for that type exists (yet). It will
162 //!   also instantiate default implementations of trait methods, something that
163 //!   otherwise is only done on demand.
164 //!
165 //!
166 //! Open Issues
167 //! -----------
168 //! Some things are not yet fully implemented in the current version of this
169 //! module.
170 //!
171 //! ### Const Fns
172 //! Ideally, no mono item should be generated for const fns unless there
173 //! is a call to them that cannot be evaluated at compile time. At the moment
174 //! this is not implemented however: a mono item will be produced
175 //! regardless of whether it is actually needed or not.
176
177 use crate::monomorphize;
178
179 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
180 use rustc_data_structures::sync::{par_iter, MTLock, MTRef, ParallelIterator};
181 use rustc_hir as hir;
182 use rustc_hir::def_id::{DefId, DefIdMap, LOCAL_CRATE};
183 use rustc_hir::itemlikevisit::ItemLikeVisitor;
184 use rustc_index::bit_set::GrowableBitSet;
185 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
186 use rustc_middle::middle::lang_items::{ExchangeMallocFnLangItem, StartFnLangItem};
187 use rustc_middle::mir::interpret::{AllocId, ConstValue};
188 use rustc_middle::mir::interpret::{ErrorHandled, GlobalAlloc, Scalar};
189 use rustc_middle::mir::mono::{InstantiationMode, MonoItem};
190 use rustc_middle::mir::visit::Visitor as MirVisitor;
191 use rustc_middle::mir::{self, Local, Location};
192 use rustc_middle::ty::adjustment::{CustomCoerceUnsized, PointerCast};
193 use rustc_middle::ty::print::obsolete::DefPathBasedNames;
194 use rustc_middle::ty::subst::InternalSubsts;
195 use rustc_middle::ty::{self, GenericParamDefKind, Instance, Ty, TyCtxt, TypeFoldable};
196 use rustc_session::config::EntryFnType;
197 use smallvec::SmallVec;
198 use std::iter;
199
200 #[derive(PartialEq)]
201 pub enum MonoItemCollectionMode {
202     Eager,
203     Lazy,
204 }
205
206 /// Maps every mono item to all mono items it references in its
207 /// body.
208 pub struct InliningMap<'tcx> {
209     // Maps a source mono item to the range of mono items
210     // accessed by it.
211     // The two numbers in the tuple are the start (inclusive) and
212     // end index (exclusive) within the `targets` vecs.
213     index: FxHashMap<MonoItem<'tcx>, (usize, usize)>,
214     targets: Vec<MonoItem<'tcx>>,
215
216     // Contains one bit per mono item in the `targets` field. That bit
217     // is true if that mono item needs to be inlined into every CGU.
218     inlines: GrowableBitSet<usize>,
219 }
220
221 impl<'tcx> InliningMap<'tcx> {
222     fn new() -> InliningMap<'tcx> {
223         InliningMap {
224             index: FxHashMap::default(),
225             targets: Vec::new(),
226             inlines: GrowableBitSet::with_capacity(1024),
227         }
228     }
229
230     fn record_accesses(&mut self, source: MonoItem<'tcx>, new_targets: &[(MonoItem<'tcx>, bool)]) {
231         let start_index = self.targets.len();
232         let new_items_count = new_targets.len();
233         let new_items_count_total = new_items_count + self.targets.len();
234
235         self.targets.reserve(new_items_count);
236         self.inlines.ensure(new_items_count_total);
237
238         for (i, (target, inline)) in new_targets.iter().enumerate() {
239             self.targets.push(*target);
240             if *inline {
241                 self.inlines.insert(i + start_index);
242             }
243         }
244
245         let end_index = self.targets.len();
246         assert!(self.index.insert(source, (start_index, end_index)).is_none());
247     }
248
249     // Internally iterate over all items referenced by `source` which will be
250     // made available for inlining.
251     pub fn with_inlining_candidates<F>(&self, source: MonoItem<'tcx>, mut f: F)
252     where
253         F: FnMut(MonoItem<'tcx>),
254     {
255         if let Some(&(start_index, end_index)) = self.index.get(&source) {
256             for (i, candidate) in self.targets[start_index..end_index].iter().enumerate() {
257                 if self.inlines.contains(start_index + i) {
258                     f(*candidate);
259                 }
260             }
261         }
262     }
263
264     // Internally iterate over all items and the things each accesses.
265     pub fn iter_accesses<F>(&self, mut f: F)
266     where
267         F: FnMut(MonoItem<'tcx>, &[MonoItem<'tcx>]),
268     {
269         for (&accessor, &(start_index, end_index)) in &self.index {
270             f(accessor, &self.targets[start_index..end_index])
271         }
272     }
273 }
274
275 pub fn collect_crate_mono_items(
276     tcx: TyCtxt<'_>,
277     mode: MonoItemCollectionMode,
278 ) -> (FxHashSet<MonoItem<'_>>, InliningMap<'_>) {
279     let _prof_timer = tcx.prof.generic_activity("monomorphization_collector");
280
281     let roots =
282         tcx.sess.time("monomorphization_collector_root_collections", || collect_roots(tcx, mode));
283
284     debug!("building mono item graph, beginning at roots");
285
286     let mut visited = MTLock::new(FxHashSet::default());
287     let mut inlining_map = MTLock::new(InliningMap::new());
288
289     {
290         let visited: MTRef<'_, _> = &mut visited;
291         let inlining_map: MTRef<'_, _> = &mut inlining_map;
292
293         tcx.sess.time("monomorphization_collector_graph_walk", || {
294             par_iter(roots).for_each(|root| {
295                 let mut recursion_depths = DefIdMap::default();
296                 collect_items_rec(tcx, root, visited, &mut recursion_depths, inlining_map);
297             });
298         });
299     }
300
301     (visited.into_inner(), inlining_map.into_inner())
302 }
303
304 // Find all non-generic items by walking the HIR. These items serve as roots to
305 // start monomorphizing from.
306 fn collect_roots(tcx: TyCtxt<'_>, mode: MonoItemCollectionMode) -> Vec<MonoItem<'_>> {
307     debug!("collecting roots");
308     let mut roots = Vec::new();
309
310     {
311         let entry_fn = tcx.entry_fn(LOCAL_CRATE);
312
313         debug!("collect_roots: entry_fn = {:?}", entry_fn);
314
315         let mut visitor = RootCollector { tcx, mode, entry_fn, output: &mut roots };
316
317         tcx.hir().krate().visit_all_item_likes(&mut visitor);
318
319         visitor.push_extra_entry_roots();
320     }
321
322     // We can only codegen items that are instantiable - items all of
323     // whose predicates hold. Luckily, items that aren't instantiable
324     // can't actually be used, so we can just skip codegenning them.
325     roots.retain(|root| root.is_instantiable(tcx));
326
327     roots
328 }
329
330 // Collect all monomorphized items reachable from `starting_point`
331 fn collect_items_rec<'tcx>(
332     tcx: TyCtxt<'tcx>,
333     starting_point: MonoItem<'tcx>,
334     visited: MTRef<'_, MTLock<FxHashSet<MonoItem<'tcx>>>>,
335     recursion_depths: &mut DefIdMap<usize>,
336     inlining_map: MTRef<'_, MTLock<InliningMap<'tcx>>>,
337 ) {
338     if !visited.lock_mut().insert(starting_point.clone()) {
339         // We've been here already, no need to search again.
340         return;
341     }
342     debug!("BEGIN collect_items_rec({})", starting_point.to_string(tcx, true));
343
344     let mut neighbors = Vec::new();
345     let recursion_depth_reset;
346
347     match starting_point {
348         MonoItem::Static(def_id) => {
349             let instance = Instance::mono(tcx, def_id);
350
351             // Sanity check whether this ended up being collected accidentally
352             debug_assert!(should_monomorphize_locally(tcx, &instance));
353
354             let ty = instance.monomorphic_ty(tcx);
355             visit_drop_use(tcx, ty, true, &mut neighbors);
356
357             recursion_depth_reset = None;
358
359             if let Ok(val) = tcx.const_eval_poly(def_id) {
360                 collect_const_value(tcx, val, &mut neighbors);
361             }
362         }
363         MonoItem::Fn(instance) => {
364             // Sanity check whether this ended up being collected accidentally
365             debug_assert!(should_monomorphize_locally(tcx, &instance));
366
367             // Keep track of the monomorphization recursion depth
368             recursion_depth_reset = Some(check_recursion_limit(tcx, instance, recursion_depths));
369             check_type_length_limit(tcx, instance);
370
371             collect_neighbours(tcx, instance, &mut neighbors);
372         }
373         MonoItem::GlobalAsm(..) => {
374             recursion_depth_reset = None;
375         }
376     }
377
378     record_accesses(tcx, starting_point, &neighbors[..], inlining_map);
379
380     for neighbour in neighbors {
381         collect_items_rec(tcx, neighbour, visited, recursion_depths, inlining_map);
382     }
383
384     if let Some((def_id, depth)) = recursion_depth_reset {
385         recursion_depths.insert(def_id, depth);
386     }
387
388     debug!("END collect_items_rec({})", starting_point.to_string(tcx, true));
389 }
390
391 fn record_accesses<'tcx>(
392     tcx: TyCtxt<'tcx>,
393     caller: MonoItem<'tcx>,
394     callees: &[MonoItem<'tcx>],
395     inlining_map: MTRef<'_, MTLock<InliningMap<'tcx>>>,
396 ) {
397     let is_inlining_candidate = |mono_item: &MonoItem<'tcx>| {
398         mono_item.instantiation_mode(tcx) == InstantiationMode::LocalCopy
399     };
400
401     // We collect this into a `SmallVec` to avoid calling `is_inlining_candidate` in the lock.
402     // FIXME: Call `is_inlining_candidate` when pushing to `neighbors` in `collect_items_rec`
403     // instead to avoid creating this `SmallVec`.
404     let accesses: SmallVec<[_; 128]> =
405         callees.iter().map(|mono_item| (*mono_item, is_inlining_candidate(mono_item))).collect();
406
407     inlining_map.lock_mut().record_accesses(caller, &accesses);
408 }
409
410 fn check_recursion_limit<'tcx>(
411     tcx: TyCtxt<'tcx>,
412     instance: Instance<'tcx>,
413     recursion_depths: &mut DefIdMap<usize>,
414 ) -> (DefId, usize) {
415     let def_id = instance.def_id();
416     let recursion_depth = recursion_depths.get(&def_id).cloned().unwrap_or(0);
417     debug!(" => recursion depth={}", recursion_depth);
418
419     let adjusted_recursion_depth = if Some(def_id) == tcx.lang_items().drop_in_place_fn() {
420         // HACK: drop_in_place creates tight monomorphization loops. Give
421         // it more margin.
422         recursion_depth / 4
423     } else {
424         recursion_depth
425     };
426
427     // Code that needs to instantiate the same function recursively
428     // more than the recursion limit is assumed to be causing an
429     // infinite expansion.
430     if adjusted_recursion_depth > *tcx.sess.recursion_limit.get() {
431         let error = format!("reached the recursion limit while instantiating `{}`", instance);
432         if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
433             tcx.sess.span_fatal(tcx.hir().span(hir_id), &error);
434         } else {
435             tcx.sess.fatal(&error);
436         }
437     }
438
439     recursion_depths.insert(def_id, recursion_depth + 1);
440
441     (def_id, recursion_depth)
442 }
443
444 fn check_type_length_limit<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) {
445     let type_length = instance.substs.types().flat_map(|ty| ty.walk()).count();
446     let const_length = instance.substs.consts().flat_map(|ct| ct.ty.walk()).count();
447     debug!(" => type length={}, const length={}", type_length, const_length);
448
449     // Rust code can easily create exponentially-long types using only a
450     // polynomial recursion depth. Even with the default recursion
451     // depth, you can easily get cases that take >2^60 steps to run,
452     // which means that rustc basically hangs.
453     //
454     // Bail out in these cases to avoid that bad user experience.
455     let type_length_limit = *tcx.sess.type_length_limit.get();
456     // We include the const length in the type length, as it's better
457     // to be overly conservative.
458     // FIXME(const_generics): we should instead uniformly walk through `substs`,
459     // ignoring lifetimes.
460     if type_length + const_length > type_length_limit {
461         // The instance name is already known to be too long for rustc.
462         // Show only the first and last 32 characters to avoid blasting
463         // the user's terminal with thousands of lines of type-name.
464         let shrink = |s: String, before: usize, after: usize| {
465             // An iterator of all byte positions including the end of the string.
466             let positions = || s.char_indices().map(|(i, _)| i).chain(iter::once(s.len()));
467
468             let shrunk = format!(
469                 "{before}...{after}",
470                 before = &s[..positions().nth(before).unwrap_or(s.len())],
471                 after = &s[positions().rev().nth(after).unwrap_or(0)..],
472             );
473
474             // Only use the shrunk version if it's really shorter.
475             // This also avoids the case where before and after slices overlap.
476             if shrunk.len() < s.len() { shrunk } else { s }
477         };
478         let msg = format!(
479             "reached the type-length limit while instantiating `{}`",
480             shrink(instance.to_string(), 32, 32)
481         );
482         let mut diag = tcx.sess.struct_span_fatal(tcx.def_span(instance.def_id()), &msg);
483         diag.note(&format!(
484             "consider adding a `#![type_length_limit=\"{}\"]` attribute to your crate",
485             type_length
486         ));
487         diag.emit();
488         tcx.sess.abort_if_errors();
489     }
490 }
491
492 struct MirNeighborCollector<'a, 'tcx> {
493     tcx: TyCtxt<'tcx>,
494     body: &'a mir::Body<'tcx>,
495     output: &'a mut Vec<MonoItem<'tcx>>,
496     instance: Instance<'tcx>,
497 }
498
499 impl<'a, 'tcx> MirNeighborCollector<'a, 'tcx> {
500     pub fn monomorphize<T>(&self, value: T) -> T
501     where
502         T: TypeFoldable<'tcx>,
503     {
504         debug!("monomorphize: self.instance={:?}", self.instance);
505         if let Some(substs) = self.instance.substs_for_mir_body() {
506             self.tcx.subst_and_normalize_erasing_regions(substs, ty::ParamEnv::reveal_all(), &value)
507         } else {
508             self.tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), value)
509         }
510     }
511 }
512
513 impl<'a, 'tcx> MirVisitor<'tcx> for MirNeighborCollector<'a, 'tcx> {
514     fn visit_rvalue(&mut self, rvalue: &mir::Rvalue<'tcx>, location: Location) {
515         debug!("visiting rvalue {:?}", *rvalue);
516
517         match *rvalue {
518             // When doing an cast from a regular pointer to a fat pointer, we
519             // have to instantiate all methods of the trait being cast to, so we
520             // can build the appropriate vtable.
521             mir::Rvalue::Cast(
522                 mir::CastKind::Pointer(PointerCast::Unsize),
523                 ref operand,
524                 target_ty,
525             ) => {
526                 let target_ty = self.monomorphize(target_ty);
527                 let source_ty = operand.ty(self.body, self.tcx);
528                 let source_ty = self.monomorphize(source_ty);
529                 let (source_ty, target_ty) =
530                     find_vtable_types_for_unsizing(self.tcx, source_ty, target_ty);
531                 // This could also be a different Unsize instruction, like
532                 // from a fixed sized array to a slice. But we are only
533                 // interested in things that produce a vtable.
534                 if target_ty.is_trait() && !source_ty.is_trait() {
535                     create_mono_items_for_vtable_methods(
536                         self.tcx,
537                         target_ty,
538                         source_ty,
539                         self.output,
540                     );
541                 }
542             }
543             mir::Rvalue::Cast(
544                 mir::CastKind::Pointer(PointerCast::ReifyFnPointer),
545                 ref operand,
546                 _,
547             ) => {
548                 let fn_ty = operand.ty(self.body, self.tcx);
549                 let fn_ty = self.monomorphize(fn_ty);
550                 visit_fn_use(self.tcx, fn_ty, false, &mut self.output);
551             }
552             mir::Rvalue::Cast(
553                 mir::CastKind::Pointer(PointerCast::ClosureFnPointer(_)),
554                 ref operand,
555                 _,
556             ) => {
557                 let source_ty = operand.ty(self.body, self.tcx);
558                 let source_ty = self.monomorphize(source_ty);
559                 match source_ty.kind {
560                     ty::Closure(def_id, substs) => {
561                         let instance = Instance::resolve_closure(
562                             self.tcx,
563                             def_id,
564                             substs,
565                             ty::ClosureKind::FnOnce,
566                         );
567                         if should_monomorphize_locally(self.tcx, &instance) {
568                             self.output.push(create_fn_mono_item(instance));
569                         }
570                     }
571                     _ => bug!(),
572                 }
573             }
574             mir::Rvalue::NullaryOp(mir::NullOp::Box, _) => {
575                 let tcx = self.tcx;
576                 let exchange_malloc_fn_def_id = tcx
577                     .lang_items()
578                     .require(ExchangeMallocFnLangItem)
579                     .unwrap_or_else(|e| tcx.sess.fatal(&e));
580                 let instance = Instance::mono(tcx, exchange_malloc_fn_def_id);
581                 if should_monomorphize_locally(tcx, &instance) {
582                     self.output.push(create_fn_mono_item(instance));
583                 }
584             }
585             _ => { /* not interesting */ }
586         }
587
588         self.super_rvalue(rvalue, location);
589     }
590
591     fn visit_const(&mut self, constant: &&'tcx ty::Const<'tcx>, location: Location) {
592         debug!("visiting const {:?} @ {:?}", *constant, location);
593
594         let substituted_constant = self.monomorphize(*constant);
595         let param_env = ty::ParamEnv::reveal_all();
596
597         match substituted_constant.val {
598             ty::ConstKind::Value(val) => collect_const_value(self.tcx, val, self.output),
599             ty::ConstKind::Unevaluated(def_id, substs, promoted) => {
600                 match self.tcx.const_eval_resolve(param_env, def_id, substs, promoted, None) {
601                     Ok(val) => collect_const_value(self.tcx, val, self.output),
602                     Err(ErrorHandled::Reported) => {}
603                     Err(ErrorHandled::TooGeneric) => span_bug!(
604                         self.tcx.def_span(def_id),
605                         "collection encountered polymorphic constant",
606                     ),
607                 }
608             }
609             _ => {}
610         }
611
612         self.super_const(constant);
613     }
614
615     fn visit_terminator_kind(&mut self, kind: &mir::TerminatorKind<'tcx>, location: Location) {
616         debug!("visiting terminator {:?} @ {:?}", kind, location);
617
618         let tcx = self.tcx;
619         match *kind {
620             mir::TerminatorKind::Call { ref func, .. } => {
621                 let callee_ty = func.ty(self.body, tcx);
622                 let callee_ty = self.monomorphize(callee_ty);
623                 visit_fn_use(self.tcx, callee_ty, true, &mut self.output);
624             }
625             mir::TerminatorKind::Drop { ref location, .. }
626             | mir::TerminatorKind::DropAndReplace { ref location, .. } => {
627                 let ty = location.ty(self.body, self.tcx).ty;
628                 let ty = self.monomorphize(ty);
629                 visit_drop_use(self.tcx, ty, true, self.output);
630             }
631             mir::TerminatorKind::Goto { .. }
632             | mir::TerminatorKind::SwitchInt { .. }
633             | mir::TerminatorKind::Resume
634             | mir::TerminatorKind::Abort
635             | mir::TerminatorKind::Return
636             | mir::TerminatorKind::Unreachable
637             | mir::TerminatorKind::Assert { .. } => {}
638             mir::TerminatorKind::GeneratorDrop
639             | mir::TerminatorKind::Yield { .. }
640             | mir::TerminatorKind::FalseEdges { .. }
641             | mir::TerminatorKind::FalseUnwind { .. } => bug!(),
642         }
643
644         self.super_terminator_kind(kind, location);
645     }
646
647     fn visit_place_base(
648         &mut self,
649         _place_local: &Local,
650         _context: mir::visit::PlaceContext,
651         _location: Location,
652     ) {
653     }
654 }
655
656 fn visit_drop_use<'tcx>(
657     tcx: TyCtxt<'tcx>,
658     ty: Ty<'tcx>,
659     is_direct_call: bool,
660     output: &mut Vec<MonoItem<'tcx>>,
661 ) {
662     let instance = Instance::resolve_drop_in_place(tcx, ty);
663     visit_instance_use(tcx, instance, is_direct_call, output);
664 }
665
666 fn visit_fn_use<'tcx>(
667     tcx: TyCtxt<'tcx>,
668     ty: Ty<'tcx>,
669     is_direct_call: bool,
670     output: &mut Vec<MonoItem<'tcx>>,
671 ) {
672     if let ty::FnDef(def_id, substs) = ty.kind {
673         let resolver =
674             if is_direct_call { ty::Instance::resolve } else { ty::Instance::resolve_for_fn_ptr };
675         let instance = resolver(tcx, ty::ParamEnv::reveal_all(), def_id, substs).unwrap();
676         visit_instance_use(tcx, instance, is_direct_call, output);
677     }
678 }
679
680 fn visit_instance_use<'tcx>(
681     tcx: TyCtxt<'tcx>,
682     instance: ty::Instance<'tcx>,
683     is_direct_call: bool,
684     output: &mut Vec<MonoItem<'tcx>>,
685 ) {
686     debug!("visit_item_use({:?}, is_direct_call={:?})", instance, is_direct_call);
687     if !should_monomorphize_locally(tcx, &instance) {
688         return;
689     }
690
691     match instance.def {
692         ty::InstanceDef::Virtual(..) | ty::InstanceDef::Intrinsic(_) => {
693             if !is_direct_call {
694                 bug!("{:?} being reified", instance);
695             }
696         }
697         ty::InstanceDef::DropGlue(_, None) => {
698             // Don't need to emit noop drop glue if we are calling directly.
699             if !is_direct_call {
700                 output.push(create_fn_mono_item(instance));
701             }
702         }
703         ty::InstanceDef::DropGlue(_, Some(_))
704         | ty::InstanceDef::VtableShim(..)
705         | ty::InstanceDef::ReifyShim(..)
706         | ty::InstanceDef::ClosureOnceShim { .. }
707         | ty::InstanceDef::Item(..)
708         | ty::InstanceDef::FnPtrShim(..)
709         | ty::InstanceDef::CloneShim(..) => {
710             output.push(create_fn_mono_item(instance));
711         }
712     }
713 }
714
715 // Returns `true` if we should codegen an instance in the local crate.
716 // Returns `false` if we can just link to the upstream crate and therefore don't
717 // need a mono item.
718 fn should_monomorphize_locally<'tcx>(tcx: TyCtxt<'tcx>, instance: &Instance<'tcx>) -> bool {
719     let def_id = match instance.def {
720         ty::InstanceDef::Item(def_id) | ty::InstanceDef::DropGlue(def_id, Some(_)) => def_id,
721
722         ty::InstanceDef::VtableShim(..)
723         | ty::InstanceDef::ReifyShim(..)
724         | ty::InstanceDef::ClosureOnceShim { .. }
725         | ty::InstanceDef::Virtual(..)
726         | ty::InstanceDef::FnPtrShim(..)
727         | ty::InstanceDef::DropGlue(..)
728         | ty::InstanceDef::Intrinsic(_)
729         | ty::InstanceDef::CloneShim(..) => return true,
730     };
731
732     if tcx.is_foreign_item(def_id) {
733         // Foreign items are always linked against, there's no way of
734         // instantiating them.
735         return false;
736     }
737
738     if def_id.is_local() {
739         // Local items cannot be referred to locally without
740         // monomorphizing them locally.
741         return true;
742     }
743
744     if tcx.is_reachable_non_generic(def_id) || instance.upstream_monomorphization(tcx).is_some() {
745         // We can link to the item in question, no instance needed
746         // in this crate.
747         return false;
748     }
749
750     if !tcx.is_mir_available(def_id) {
751         bug!("cannot create local mono-item for {:?}", def_id)
752     }
753
754     true
755 }
756
757 /// For a given pair of source and target type that occur in an unsizing coercion,
758 /// this function finds the pair of types that determines the vtable linking
759 /// them.
760 ///
761 /// For example, the source type might be `&SomeStruct` and the target type\
762 /// might be `&SomeTrait` in a cast like:
763 ///
764 /// let src: &SomeStruct = ...;
765 /// let target = src as &SomeTrait;
766 ///
767 /// Then the output of this function would be (SomeStruct, SomeTrait) since for
768 /// constructing the `target` fat-pointer we need the vtable for that pair.
769 ///
770 /// Things can get more complicated though because there's also the case where
771 /// the unsized type occurs as a field:
772 ///
773 /// ```rust
774 /// struct ComplexStruct<T: ?Sized> {
775 ///    a: u32,
776 ///    b: f64,
777 ///    c: T
778 /// }
779 /// ```
780 ///
781 /// In this case, if `T` is sized, `&ComplexStruct<T>` is a thin pointer. If `T`
782 /// is unsized, `&SomeStruct` is a fat pointer, and the vtable it points to is
783 /// for the pair of `T` (which is a trait) and the concrete type that `T` was
784 /// originally coerced from:
785 ///
786 /// let src: &ComplexStruct<SomeStruct> = ...;
787 /// let target = src as &ComplexStruct<SomeTrait>;
788 ///
789 /// Again, we want this `find_vtable_types_for_unsizing()` to provide the pair
790 /// `(SomeStruct, SomeTrait)`.
791 ///
792 /// Finally, there is also the case of custom unsizing coercions, e.g., for
793 /// smart pointers such as `Rc` and `Arc`.
794 fn find_vtable_types_for_unsizing<'tcx>(
795     tcx: TyCtxt<'tcx>,
796     source_ty: Ty<'tcx>,
797     target_ty: Ty<'tcx>,
798 ) -> (Ty<'tcx>, Ty<'tcx>) {
799     let ptr_vtable = |inner_source: Ty<'tcx>, inner_target: Ty<'tcx>| {
800         let param_env = ty::ParamEnv::reveal_all();
801         let type_has_metadata = |ty: Ty<'tcx>| -> bool {
802             use rustc_span::DUMMY_SP;
803             if ty.is_sized(tcx.at(DUMMY_SP), param_env) {
804                 return false;
805             }
806             let tail = tcx.struct_tail_erasing_lifetimes(ty, param_env);
807             match tail.kind {
808                 ty::Foreign(..) => false,
809                 ty::Str | ty::Slice(..) | ty::Dynamic(..) => true,
810                 _ => bug!("unexpected unsized tail: {:?}", tail),
811             }
812         };
813         if type_has_metadata(inner_source) {
814             (inner_source, inner_target)
815         } else {
816             tcx.struct_lockstep_tails_erasing_lifetimes(inner_source, inner_target, param_env)
817         }
818     };
819
820     match (&source_ty.kind, &target_ty.kind) {
821         (&ty::Ref(_, a, _), &ty::Ref(_, b, _))
822         | (&ty::Ref(_, a, _), &ty::RawPtr(ty::TypeAndMut { ty: b, .. }))
823         | (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }), &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => {
824             ptr_vtable(a, b)
825         }
826         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
827             ptr_vtable(source_ty.boxed_ty(), target_ty.boxed_ty())
828         }
829
830         (&ty::Adt(source_adt_def, source_substs), &ty::Adt(target_adt_def, target_substs)) => {
831             assert_eq!(source_adt_def, target_adt_def);
832
833             let CustomCoerceUnsized::Struct(coerce_index) =
834                 monomorphize::custom_coerce_unsize_info(tcx, source_ty, target_ty);
835
836             let source_fields = &source_adt_def.non_enum_variant().fields;
837             let target_fields = &target_adt_def.non_enum_variant().fields;
838
839             assert!(
840                 coerce_index < source_fields.len() && source_fields.len() == target_fields.len()
841             );
842
843             find_vtable_types_for_unsizing(
844                 tcx,
845                 source_fields[coerce_index].ty(tcx, source_substs),
846                 target_fields[coerce_index].ty(tcx, target_substs),
847             )
848         }
849         _ => bug!(
850             "find_vtable_types_for_unsizing: invalid coercion {:?} -> {:?}",
851             source_ty,
852             target_ty
853         ),
854     }
855 }
856
857 fn create_fn_mono_item(instance: Instance<'_>) -> MonoItem<'_> {
858     debug!("create_fn_mono_item(instance={})", instance);
859     MonoItem::Fn(instance)
860 }
861
862 /// Creates a `MonoItem` for each method that is referenced by the vtable for
863 /// the given trait/impl pair.
864 fn create_mono_items_for_vtable_methods<'tcx>(
865     tcx: TyCtxt<'tcx>,
866     trait_ty: Ty<'tcx>,
867     impl_ty: Ty<'tcx>,
868     output: &mut Vec<MonoItem<'tcx>>,
869 ) {
870     assert!(
871         !trait_ty.needs_subst()
872             && !trait_ty.has_escaping_bound_vars()
873             && !impl_ty.needs_subst()
874             && !impl_ty.has_escaping_bound_vars()
875     );
876
877     if let ty::Dynamic(ref trait_ty, ..) = trait_ty.kind {
878         if let Some(principal) = trait_ty.principal() {
879             let poly_trait_ref = principal.with_self_ty(tcx, impl_ty);
880             assert!(!poly_trait_ref.has_escaping_bound_vars());
881
882             // Walk all methods of the trait, including those of its supertraits
883             let methods = tcx.vtable_methods(poly_trait_ref);
884             let methods = methods
885                 .iter()
886                 .cloned()
887                 .filter_map(|method| method)
888                 .map(|(def_id, substs)| {
889                     ty::Instance::resolve_for_vtable(
890                         tcx,
891                         ty::ParamEnv::reveal_all(),
892                         def_id,
893                         substs,
894                     )
895                     .unwrap()
896                 })
897                 .filter(|&instance| should_monomorphize_locally(tcx, &instance))
898                 .map(create_fn_mono_item);
899             output.extend(methods);
900         }
901
902         // Also add the destructor.
903         visit_drop_use(tcx, impl_ty, false, output);
904     }
905 }
906
907 //=-----------------------------------------------------------------------------
908 // Root Collection
909 //=-----------------------------------------------------------------------------
910
911 struct RootCollector<'a, 'tcx> {
912     tcx: TyCtxt<'tcx>,
913     mode: MonoItemCollectionMode,
914     output: &'a mut Vec<MonoItem<'tcx>>,
915     entry_fn: Option<(DefId, EntryFnType)>,
916 }
917
918 impl ItemLikeVisitor<'v> for RootCollector<'_, 'v> {
919     fn visit_item(&mut self, item: &'v hir::Item<'v>) {
920         match item.kind {
921             hir::ItemKind::ExternCrate(..)
922             | hir::ItemKind::Use(..)
923             | hir::ItemKind::ForeignMod(..)
924             | hir::ItemKind::TyAlias(..)
925             | hir::ItemKind::Trait(..)
926             | hir::ItemKind::TraitAlias(..)
927             | hir::ItemKind::OpaqueTy(..)
928             | hir::ItemKind::Mod(..) => {
929                 // Nothing to do, just keep recursing.
930             }
931
932             hir::ItemKind::Impl { .. } => {
933                 if self.mode == MonoItemCollectionMode::Eager {
934                     create_mono_items_for_default_impls(self.tcx, item, self.output);
935                 }
936             }
937
938             hir::ItemKind::Enum(_, ref generics)
939             | hir::ItemKind::Struct(_, ref generics)
940             | hir::ItemKind::Union(_, ref generics) => {
941                 if generics.params.is_empty() {
942                     if self.mode == MonoItemCollectionMode::Eager {
943                         let def_id = self.tcx.hir().local_def_id(item.hir_id);
944                         debug!(
945                             "RootCollector: ADT drop-glue for {}",
946                             def_id_to_string(self.tcx, def_id)
947                         );
948
949                         let ty =
950                             Instance::new(def_id, InternalSubsts::empty()).monomorphic_ty(self.tcx);
951                         visit_drop_use(self.tcx, ty, true, self.output);
952                     }
953                 }
954             }
955             hir::ItemKind::GlobalAsm(..) => {
956                 debug!(
957                     "RootCollector: ItemKind::GlobalAsm({})",
958                     def_id_to_string(self.tcx, self.tcx.hir().local_def_id(item.hir_id))
959                 );
960                 self.output.push(MonoItem::GlobalAsm(item.hir_id));
961             }
962             hir::ItemKind::Static(..) => {
963                 let def_id = self.tcx.hir().local_def_id(item.hir_id);
964                 debug!("RootCollector: ItemKind::Static({})", def_id_to_string(self.tcx, def_id));
965                 self.output.push(MonoItem::Static(def_id));
966             }
967             hir::ItemKind::Const(..) => {
968                 // const items only generate mono items if they are
969                 // actually used somewhere. Just declaring them is insufficient.
970
971                 // but even just declaring them must collect the items they refer to
972                 let def_id = self.tcx.hir().local_def_id(item.hir_id);
973
974                 if let Ok(val) = self.tcx.const_eval_poly(def_id) {
975                     collect_const_value(self.tcx, val, &mut self.output);
976                 }
977             }
978             hir::ItemKind::Fn(..) => {
979                 let def_id = self.tcx.hir().local_def_id(item.hir_id);
980                 self.push_if_root(def_id);
981             }
982         }
983     }
984
985     fn visit_trait_item(&mut self, _: &'v hir::TraitItem<'v>) {
986         // Even if there's a default body with no explicit generics,
987         // it's still generic over some `Self: Trait`, so not a root.
988     }
989
990     fn visit_impl_item(&mut self, ii: &'v hir::ImplItem<'v>) {
991         if let hir::ImplItemKind::Fn(hir::FnSig { .. }, _) = ii.kind {
992             let def_id = self.tcx.hir().local_def_id(ii.hir_id);
993             self.push_if_root(def_id);
994         }
995     }
996 }
997
998 impl RootCollector<'_, 'v> {
999     fn is_root(&self, def_id: DefId) -> bool {
1000         !item_requires_monomorphization(self.tcx, def_id)
1001             && match self.mode {
1002                 MonoItemCollectionMode::Eager => true,
1003                 MonoItemCollectionMode::Lazy => {
1004                     self.entry_fn.map(|(id, _)| id) == Some(def_id)
1005                         || self.tcx.is_reachable_non_generic(def_id)
1006                         || self
1007                             .tcx
1008                             .codegen_fn_attrs(def_id)
1009                             .flags
1010                             .contains(CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
1011                 }
1012             }
1013     }
1014
1015     /// If `def_id` represents a root, pushes it onto the list of
1016     /// outputs. (Note that all roots must be monomorphic.)
1017     fn push_if_root(&mut self, def_id: DefId) {
1018         if self.is_root(def_id) {
1019             debug!("RootCollector::push_if_root: found root def_id={:?}", def_id);
1020
1021             let instance = Instance::mono(self.tcx, def_id);
1022             self.output.push(create_fn_mono_item(instance));
1023         }
1024     }
1025
1026     /// As a special case, when/if we encounter the
1027     /// `main()` function, we also have to generate a
1028     /// monomorphized copy of the start lang item based on
1029     /// the return type of `main`. This is not needed when
1030     /// the user writes their own `start` manually.
1031     fn push_extra_entry_roots(&mut self) {
1032         let main_def_id = match self.entry_fn {
1033             Some((def_id, EntryFnType::Main)) => def_id,
1034             _ => return,
1035         };
1036
1037         let start_def_id = match self.tcx.lang_items().require(StartFnLangItem) {
1038             Ok(s) => s,
1039             Err(err) => self.tcx.sess.fatal(&err),
1040         };
1041         let main_ret_ty = self.tcx.fn_sig(main_def_id).output();
1042
1043         // Given that `main()` has no arguments,
1044         // then its return type cannot have
1045         // late-bound regions, since late-bound
1046         // regions must appear in the argument
1047         // listing.
1048         let main_ret_ty = self.tcx.erase_regions(&main_ret_ty.no_bound_vars().unwrap());
1049
1050         let start_instance = Instance::resolve(
1051             self.tcx,
1052             ty::ParamEnv::reveal_all(),
1053             start_def_id,
1054             self.tcx.intern_substs(&[main_ret_ty.into()]),
1055         )
1056         .unwrap();
1057
1058         self.output.push(create_fn_mono_item(start_instance));
1059     }
1060 }
1061
1062 fn item_requires_monomorphization(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
1063     let generics = tcx.generics_of(def_id);
1064     generics.requires_monomorphization(tcx)
1065 }
1066
1067 fn create_mono_items_for_default_impls<'tcx>(
1068     tcx: TyCtxt<'tcx>,
1069     item: &'tcx hir::Item<'tcx>,
1070     output: &mut Vec<MonoItem<'tcx>>,
1071 ) {
1072     match item.kind {
1073         hir::ItemKind::Impl { ref generics, ref items, .. } => {
1074             for param in generics.params {
1075                 match param.kind {
1076                     hir::GenericParamKind::Lifetime { .. } => {}
1077                     hir::GenericParamKind::Type { .. } | hir::GenericParamKind::Const { .. } => {
1078                         return;
1079                     }
1080                 }
1081             }
1082
1083             let impl_def_id = tcx.hir().local_def_id(item.hir_id);
1084
1085             debug!(
1086                 "create_mono_items_for_default_impls(item={})",
1087                 def_id_to_string(tcx, impl_def_id)
1088             );
1089
1090             if let Some(trait_ref) = tcx.impl_trait_ref(impl_def_id) {
1091                 let param_env = ty::ParamEnv::reveal_all();
1092                 let trait_ref = tcx.normalize_erasing_regions(param_env, trait_ref);
1093                 let overridden_methods: FxHashSet<_> =
1094                     items.iter().map(|iiref| iiref.ident.normalize_to_macros_2_0()).collect();
1095                 for method in tcx.provided_trait_methods(trait_ref.def_id) {
1096                     if overridden_methods.contains(&method.ident.normalize_to_macros_2_0()) {
1097                         continue;
1098                     }
1099
1100                     if tcx.generics_of(method.def_id).own_requires_monomorphization() {
1101                         continue;
1102                     }
1103
1104                     let substs =
1105                         InternalSubsts::for_item(tcx, method.def_id, |param, _| match param.kind {
1106                             GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
1107                             GenericParamDefKind::Type { .. } | GenericParamDefKind::Const => {
1108                                 trait_ref.substs[param.index as usize]
1109                             }
1110                         });
1111                     let instance =
1112                         ty::Instance::resolve(tcx, param_env, method.def_id, substs).unwrap();
1113
1114                     let mono_item = create_fn_mono_item(instance);
1115                     if mono_item.is_instantiable(tcx) && should_monomorphize_locally(tcx, &instance)
1116                     {
1117                         output.push(mono_item);
1118                     }
1119                 }
1120             }
1121         }
1122         _ => bug!(),
1123     }
1124 }
1125
1126 /// Scans the miri alloc in order to find function calls, closures, and drop-glue.
1127 fn collect_miri<'tcx>(tcx: TyCtxt<'tcx>, alloc_id: AllocId, output: &mut Vec<MonoItem<'tcx>>) {
1128     let alloc_kind = tcx.alloc_map.lock().get(alloc_id);
1129     match alloc_kind {
1130         Some(GlobalAlloc::Static(def_id)) => {
1131             let instance = Instance::mono(tcx, def_id);
1132             if should_monomorphize_locally(tcx, &instance) {
1133                 trace!("collecting static {:?}", def_id);
1134                 output.push(MonoItem::Static(def_id));
1135             }
1136         }
1137         Some(GlobalAlloc::Memory(alloc)) => {
1138             trace!("collecting {:?} with {:#?}", alloc_id, alloc);
1139             for &((), inner) in alloc.relocations().values() {
1140                 collect_miri(tcx, inner, output);
1141             }
1142         }
1143         Some(GlobalAlloc::Function(fn_instance)) => {
1144             if should_monomorphize_locally(tcx, &fn_instance) {
1145                 trace!("collecting {:?} with {:#?}", alloc_id, fn_instance);
1146                 output.push(create_fn_mono_item(fn_instance));
1147             }
1148         }
1149         None => bug!("alloc id without corresponding allocation: {}", alloc_id),
1150     }
1151 }
1152
1153 /// Scans the MIR in order to find function calls, closures, and drop-glue.
1154 fn collect_neighbours<'tcx>(
1155     tcx: TyCtxt<'tcx>,
1156     instance: Instance<'tcx>,
1157     output: &mut Vec<MonoItem<'tcx>>,
1158 ) {
1159     debug!("collect_neighbours: {:?}", instance.def_id());
1160     let body = tcx.instance_mir(instance.def);
1161
1162     MirNeighborCollector { tcx, body: &body, output, instance }.visit_body(&body);
1163 }
1164
1165 fn def_id_to_string(tcx: TyCtxt<'_>, def_id: DefId) -> String {
1166     let mut output = String::new();
1167     let printer = DefPathBasedNames::new(tcx, false, false);
1168     printer.push_def_path(def_id, &mut output);
1169     output
1170 }
1171
1172 fn collect_const_value<'tcx>(
1173     tcx: TyCtxt<'tcx>,
1174     value: ConstValue<'tcx>,
1175     output: &mut Vec<MonoItem<'tcx>>,
1176 ) {
1177     match value {
1178         ConstValue::Scalar(Scalar::Ptr(ptr)) => collect_miri(tcx, ptr.alloc_id, output),
1179         ConstValue::Slice { data: alloc, start: _, end: _ } | ConstValue::ByRef { alloc, .. } => {
1180             for &((), id) in alloc.relocations().values() {
1181                 collect_miri(tcx, id, output);
1182             }
1183         }
1184         _ => {}
1185     }
1186 }