]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/monomorphize/collector.rs
Take Const into account in HIR
[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 rustc::hir::{self, CodegenFnAttrFlags};
178 use rustc::hir::itemlikevisit::ItemLikeVisitor;
179
180 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
181 use rustc::mir::interpret::{AllocId, ConstValue};
182 use rustc::middle::lang_items::{ExchangeMallocFnLangItem, StartFnLangItem};
183 use rustc::ty::subst::Substs;
184 use rustc::ty::{self, TypeFoldable, Ty, TyCtxt, GenericParamDefKind};
185 use rustc::ty::adjustment::CustomCoerceUnsized;
186 use rustc::session::config::EntryFnType;
187 use rustc::mir::{self, Location, Promoted};
188 use rustc::mir::visit::Visitor as MirVisitor;
189 use rustc::mir::mono::MonoItem;
190 use rustc::mir::interpret::{Scalar, GlobalId, AllocKind, ErrorHandled};
191
192 use crate::monomorphize::{self, Instance};
193 use rustc::util::nodemap::{FxHashSet, FxHashMap, DefIdMap};
194 use rustc::util::common::time;
195
196 use crate::monomorphize::item::{MonoItemExt, DefPathBasedNames, InstantiationMode};
197
198 use rustc_data_structures::bit_set::GrowableBitSet;
199 use rustc_data_structures::sync::{MTRef, MTLock, ParallelIterator, par_iter};
200
201 #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
202 pub enum MonoItemCollectionMode {
203     Eager,
204     Lazy
205 }
206
207 /// Maps every mono item to all mono items it references in its
208 /// body.
209 pub struct InliningMap<'tcx> {
210     // Maps a source mono item to the range of mono items
211     // accessed by it.
212     // The two numbers in the tuple are the start (inclusive) and
213     // end index (exclusive) within the `targets` vecs.
214     index: FxHashMap<MonoItem<'tcx>, (usize, usize)>,
215     targets: Vec<MonoItem<'tcx>>,
216
217     // Contains one bit per mono item in the `targets` field. That bit
218     // is true if that mono item needs to be inlined into every CGU.
219     inlines: GrowableBitSet<usize>,
220 }
221
222 impl<'tcx> InliningMap<'tcx> {
223
224     fn new() -> InliningMap<'tcx> {
225         InliningMap {
226             index: FxHashMap::default(),
227             targets: Vec::new(),
228             inlines: GrowableBitSet::with_capacity(1024),
229         }
230     }
231
232     fn record_accesses<I>(&mut self,
233                           source: MonoItem<'tcx>,
234                           new_targets: I)
235         where I: Iterator<Item=(MonoItem<'tcx>, bool)> + ExactSizeIterator
236     {
237         assert!(!self.index.contains_key(&source));
238
239         let start_index = self.targets.len();
240         let new_items_count = new_targets.len();
241         let new_items_count_total = new_items_count + self.targets.len();
242
243         self.targets.reserve(new_items_count);
244         self.inlines.ensure(new_items_count_total);
245
246         for (i, (target, inline)) in new_targets.enumerate() {
247             self.targets.push(target);
248             if inline {
249                 self.inlines.insert(i + start_index);
250             }
251         }
252
253         let end_index = self.targets.len();
254         self.index.insert(source, (start_index, end_index));
255     }
256
257     // Internally iterate over all items referenced by `source` which will be
258     // made available for inlining.
259     pub fn with_inlining_candidates<F>(&self, source: MonoItem<'tcx>, mut f: F)
260         where F: FnMut(MonoItem<'tcx>)
261     {
262         if let Some(&(start_index, end_index)) = self.index.get(&source) {
263             for (i, candidate) in self.targets[start_index .. end_index]
264                                       .iter()
265                                       .enumerate() {
266                 if self.inlines.contains(start_index + i) {
267                     f(*candidate);
268                 }
269             }
270         }
271     }
272
273     // Internally iterate over all items and the things each accesses.
274     pub fn iter_accesses<F>(&self, mut f: F)
275         where F: FnMut(MonoItem<'tcx>, &[MonoItem<'tcx>])
276     {
277         for (&accessor, &(start_index, end_index)) in &self.index {
278             f(accessor, &self.targets[start_index .. end_index])
279         }
280     }
281 }
282
283 pub fn collect_crate_mono_items<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
284                                           mode: MonoItemCollectionMode)
285                                           -> (FxHashSet<MonoItem<'tcx>>,
286                                                      InliningMap<'tcx>) {
287     let roots = time(tcx.sess, "collecting roots", || {
288         collect_roots(tcx, mode)
289     });
290
291     debug!("Building mono item graph, beginning at roots");
292
293     let mut visited = MTLock::new(FxHashSet::default());
294     let mut inlining_map = MTLock::new(InliningMap::new());
295
296     {
297         let visited: MTRef<'_, _> = &mut visited;
298         let inlining_map: MTRef<'_, _> = &mut inlining_map;
299
300         time(tcx.sess, "collecting mono items", || {
301             par_iter(roots).for_each(|root| {
302                 let mut recursion_depths = DefIdMap::default();
303                 collect_items_rec(tcx,
304                                 root,
305                                 visited,
306                                 &mut recursion_depths,
307                                 inlining_map);
308             });
309         });
310     }
311
312     (visited.into_inner(), inlining_map.into_inner())
313 }
314
315 // Find all non-generic items by walking the HIR. These items serve as roots to
316 // start monomorphizing from.
317 fn collect_roots<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
318                            mode: MonoItemCollectionMode)
319                            -> Vec<MonoItem<'tcx>> {
320     debug!("Collecting roots");
321     let mut roots = Vec::new();
322
323     {
324         let entry_fn = tcx.entry_fn(LOCAL_CRATE);
325
326         debug!("collect_roots: entry_fn = {:?}", entry_fn);
327
328         let mut visitor = RootCollector {
329             tcx,
330             mode,
331             entry_fn,
332             output: &mut roots,
333         };
334
335         tcx.hir().krate().visit_all_item_likes(&mut visitor);
336
337         visitor.push_extra_entry_roots();
338     }
339
340     // We can only codegen items that are instantiable - items all of
341     // whose predicates hold. Luckily, items that aren't instantiable
342     // can't actually be used, so we can just skip codegenning them.
343     roots.retain(|root| root.is_instantiable(tcx));
344
345     roots
346 }
347
348 // Collect all monomorphized items reachable from `starting_point`
349 fn collect_items_rec<'a, 'tcx: 'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
350                                    starting_point: MonoItem<'tcx>,
351                                    visited: MTRef<'_, MTLock<FxHashSet<MonoItem<'tcx>>>>,
352                                    recursion_depths: &mut DefIdMap<usize>,
353                                    inlining_map: MTRef<'_, MTLock<InliningMap<'tcx>>>) {
354     if !visited.lock_mut().insert(starting_point.clone()) {
355         // We've been here already, no need to search again.
356         return;
357     }
358     debug!("BEGIN collect_items_rec({})", starting_point.to_string(tcx, true));
359
360     let mut neighbors = Vec::new();
361     let recursion_depth_reset;
362
363     match starting_point {
364         MonoItem::Static(def_id) => {
365             let instance = Instance::mono(tcx, def_id);
366
367             // Sanity check whether this ended up being collected accidentally
368             debug_assert!(should_monomorphize_locally(tcx, &instance));
369
370             let ty = instance.ty(tcx);
371             visit_drop_use(tcx, ty, true, &mut neighbors);
372
373             recursion_depth_reset = None;
374
375             let cid = GlobalId {
376                 instance,
377                 promoted: None,
378             };
379             let param_env = ty::ParamEnv::reveal_all();
380
381             if let Ok(val) = tcx.const_eval(param_env.and(cid)) {
382                 collect_const(tcx, val, &mut neighbors);
383             }
384         }
385         MonoItem::Fn(instance) => {
386             // Sanity check whether this ended up being collected accidentally
387             debug_assert!(should_monomorphize_locally(tcx, &instance));
388
389             // Keep track of the monomorphization recursion depth
390             recursion_depth_reset = Some(check_recursion_limit(tcx,
391                                                                instance,
392                                                                recursion_depths));
393             check_type_length_limit(tcx, instance);
394
395             collect_neighbours(tcx, instance, &mut neighbors);
396         }
397         MonoItem::GlobalAsm(..) => {
398             recursion_depth_reset = None;
399         }
400     }
401
402     record_accesses(tcx, starting_point, &neighbors[..], inlining_map);
403
404     for neighbour in neighbors {
405         collect_items_rec(tcx, neighbour, visited, recursion_depths, inlining_map);
406     }
407
408     if let Some((def_id, depth)) = recursion_depth_reset {
409         recursion_depths.insert(def_id, depth);
410     }
411
412     debug!("END collect_items_rec({})", starting_point.to_string(tcx, true));
413 }
414
415 fn record_accesses<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
416                              caller: MonoItem<'tcx>,
417                              callees: &[MonoItem<'tcx>],
418                              inlining_map: MTRef<'_, MTLock<InliningMap<'tcx>>>) {
419     let is_inlining_candidate = |mono_item: &MonoItem<'tcx>| {
420         mono_item.instantiation_mode(tcx) == InstantiationMode::LocalCopy
421     };
422
423     let accesses = callees.into_iter()
424                           .map(|mono_item| {
425                              (*mono_item, is_inlining_candidate(mono_item))
426                           });
427
428     inlining_map.lock_mut().record_accesses(caller, accesses);
429 }
430
431 fn check_recursion_limit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
432                                    instance: Instance<'tcx>,
433                                    recursion_depths: &mut DefIdMap<usize>)
434                                    -> (DefId, usize) {
435     let def_id = instance.def_id();
436     let recursion_depth = recursion_depths.get(&def_id).cloned().unwrap_or(0);
437     debug!(" => recursion depth={}", recursion_depth);
438
439     let recursion_depth = if Some(def_id) == tcx.lang_items().drop_in_place_fn() {
440         // HACK: drop_in_place creates tight monomorphization loops. Give
441         // it more margin.
442         recursion_depth / 4
443     } else {
444         recursion_depth
445     };
446
447     // Code that needs to instantiate the same function recursively
448     // more than the recursion limit is assumed to be causing an
449     // infinite expansion.
450     if recursion_depth > *tcx.sess.recursion_limit.get() {
451         let error = format!("reached the recursion limit while instantiating `{}`",
452                             instance);
453         if let Some(hir_id) = tcx.hir().as_local_hir_id(def_id) {
454             tcx.sess.span_fatal(tcx.hir().span_by_hir_id(hir_id), &error);
455         } else {
456             tcx.sess.fatal(&error);
457         }
458     }
459
460     recursion_depths.insert(def_id, recursion_depth + 1);
461
462     (def_id, recursion_depth)
463 }
464
465 fn check_type_length_limit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
466                                      instance: Instance<'tcx>)
467 {
468     let type_length = instance.substs.types().flat_map(|ty| ty.walk()).count();
469     debug!(" => type length={}", type_length);
470
471     // Rust code can easily create exponentially-long types using only a
472     // polynomial recursion depth. Even with the default recursion
473     // depth, you can easily get cases that take >2^60 steps to run,
474     // which means that rustc basically hangs.
475     //
476     // Bail out in these cases to avoid that bad user experience.
477     let type_length_limit = *tcx.sess.type_length_limit.get();
478     if type_length > type_length_limit {
479         // The instance name is already known to be too long for rustc. Use
480         // `{:.64}` to avoid blasting the user's terminal with thousands of
481         // lines of type-name.
482         let instance_name = instance.to_string();
483         let msg = format!("reached the type-length limit while instantiating `{:.64}...`",
484                           instance_name);
485         let mut diag = if let Some(hir_id) = tcx.hir().as_local_hir_id(instance.def_id()) {
486             tcx.sess.struct_span_fatal(tcx.hir().span_by_hir_id(hir_id), &msg)
487         } else {
488             tcx.sess.struct_fatal(&msg)
489         };
490
491         diag.note(&format!(
492             "consider adding a `#![type_length_limit=\"{}\"]` attribute to your crate",
493             type_length_limit*2));
494         diag.emit();
495         tcx.sess.abort_if_errors();
496     }
497 }
498
499 struct MirNeighborCollector<'a, 'tcx: 'a> {
500     tcx: TyCtxt<'a, 'tcx, 'tcx>,
501     mir: &'a mir::Mir<'tcx>,
502     output: &'a mut Vec<MonoItem<'tcx>>,
503     param_substs: &'tcx Substs<'tcx>,
504 }
505
506 impl<'a, 'tcx> MirVisitor<'tcx> for MirNeighborCollector<'a, 'tcx> {
507
508     fn visit_rvalue(&mut self, rvalue: &mir::Rvalue<'tcx>, location: Location) {
509         debug!("visiting rvalue {:?}", *rvalue);
510
511         match *rvalue {
512             // When doing an cast from a regular pointer to a fat pointer, we
513             // have to instantiate all methods of the trait being cast to, so we
514             // can build the appropriate vtable.
515             mir::Rvalue::Cast(mir::CastKind::Unsize, ref operand, target_ty) => {
516                 let target_ty = self.tcx.subst_and_normalize_erasing_regions(
517                     self.param_substs,
518                     ty::ParamEnv::reveal_all(),
519                     &target_ty,
520                 );
521                 let source_ty = operand.ty(self.mir, self.tcx);
522                 let source_ty = self.tcx.subst_and_normalize_erasing_regions(
523                     self.param_substs,
524                     ty::ParamEnv::reveal_all(),
525                     &source_ty,
526                 );
527                 let (source_ty, target_ty) = find_vtable_types_for_unsizing(self.tcx,
528                                                                             source_ty,
529                                                                             target_ty);
530                 // This could also be a different Unsize instruction, like
531                 // from a fixed sized array to a slice. But we are only
532                 // interested in things that produce a vtable.
533                 if target_ty.is_trait() && !source_ty.is_trait() {
534                     create_mono_items_for_vtable_methods(self.tcx,
535                                                          target_ty,
536                                                          source_ty,
537                                                          self.output);
538                 }
539             }
540             mir::Rvalue::Cast(mir::CastKind::ReifyFnPointer, ref operand, _) => {
541                 let fn_ty = operand.ty(self.mir, self.tcx);
542                 let fn_ty = self.tcx.subst_and_normalize_erasing_regions(
543                     self.param_substs,
544                     ty::ParamEnv::reveal_all(),
545                     &fn_ty,
546                 );
547                 visit_fn_use(self.tcx, fn_ty, false, &mut self.output);
548             }
549             mir::Rvalue::Cast(mir::CastKind::ClosureFnPointer, ref operand, _) => {
550                 let source_ty = operand.ty(self.mir, self.tcx);
551                 let source_ty = self.tcx.subst_and_normalize_erasing_regions(
552                     self.param_substs,
553                     ty::ParamEnv::reveal_all(),
554                     &source_ty,
555                 );
556                 match source_ty.sty {
557                     ty::Closure(def_id, substs) => {
558                         let instance = monomorphize::resolve_closure(
559                             self.tcx, def_id, substs, ty::ClosureKind::FnOnce);
560                         if should_monomorphize_locally(self.tcx, &instance) {
561                             self.output.push(create_fn_mono_item(instance));
562                         }
563                     }
564                     _ => bug!(),
565                 }
566             }
567             mir::Rvalue::NullaryOp(mir::NullOp::Box, _) => {
568                 let tcx = self.tcx;
569                 let exchange_malloc_fn_def_id = tcx
570                     .lang_items()
571                     .require(ExchangeMallocFnLangItem)
572                     .unwrap_or_else(|e| tcx.sess.fatal(&e));
573                 let instance = Instance::mono(tcx, exchange_malloc_fn_def_id);
574                 if should_monomorphize_locally(tcx, &instance) {
575                     self.output.push(create_fn_mono_item(instance));
576                 }
577             }
578             _ => { /* not interesting */ }
579         }
580
581         self.super_rvalue(rvalue, location);
582     }
583
584     fn visit_const(&mut self, constant: &&'tcx ty::LazyConst<'tcx>, location: Location) {
585         debug!("visiting const {:?} @ {:?}", *constant, location);
586
587         collect_lazy_const(self.tcx, constant, self.param_substs, self.output);
588
589         self.super_const(constant);
590     }
591
592     fn visit_terminator_kind(&mut self,
593                              block: mir::BasicBlock,
594                              kind: &mir::TerminatorKind<'tcx>,
595                              location: Location) {
596         debug!("visiting terminator {:?} @ {:?}", kind, location);
597
598         let tcx = self.tcx;
599         match *kind {
600             mir::TerminatorKind::Call { ref func, .. } => {
601                 let callee_ty = func.ty(self.mir, tcx);
602                 let callee_ty = tcx.subst_and_normalize_erasing_regions(
603                     self.param_substs,
604                     ty::ParamEnv::reveal_all(),
605                     &callee_ty,
606                 );
607                 visit_fn_use(self.tcx, callee_ty, true, &mut self.output);
608             }
609             mir::TerminatorKind::Drop { ref location, .. } |
610             mir::TerminatorKind::DropAndReplace { ref location, .. } => {
611                 let ty = location.ty(self.mir, self.tcx)
612                     .to_ty(self.tcx);
613                 let ty = tcx.subst_and_normalize_erasing_regions(
614                     self.param_substs,
615                     ty::ParamEnv::reveal_all(),
616                     &ty,
617                 );
618                 visit_drop_use(self.tcx, ty, true, self.output);
619             }
620             mir::TerminatorKind::Goto { .. } |
621             mir::TerminatorKind::SwitchInt { .. } |
622             mir::TerminatorKind::Resume |
623             mir::TerminatorKind::Abort |
624             mir::TerminatorKind::Return |
625             mir::TerminatorKind::Unreachable |
626             mir::TerminatorKind::Assert { .. } => {}
627             mir::TerminatorKind::GeneratorDrop |
628             mir::TerminatorKind::Yield { .. } |
629             mir::TerminatorKind::FalseEdges { .. } |
630             mir::TerminatorKind::FalseUnwind { .. } => bug!(),
631         }
632
633         self.super_terminator_kind(block, kind, location);
634     }
635
636     fn visit_static(&mut self,
637                     static_: &mir::Static<'tcx>,
638                     context: mir::visit::PlaceContext<'tcx>,
639                     location: Location) {
640         debug!("visiting static {:?} @ {:?}", static_.def_id, location);
641
642         let tcx = self.tcx;
643         let instance = Instance::mono(tcx, static_.def_id);
644         if should_monomorphize_locally(tcx, &instance) {
645             self.output.push(MonoItem::Static(static_.def_id));
646         }
647
648         self.super_static(static_, context, location);
649     }
650 }
651
652 fn visit_drop_use<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
653                             ty: Ty<'tcx>,
654                             is_direct_call: bool,
655                             output: &mut Vec<MonoItem<'tcx>>)
656 {
657     let instance = monomorphize::resolve_drop_in_place(tcx, ty);
658     visit_instance_use(tcx, instance, is_direct_call, output);
659 }
660
661 fn visit_fn_use<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
662                           ty: Ty<'tcx>,
663                           is_direct_call: bool,
664                           output: &mut Vec<MonoItem<'tcx>>)
665 {
666     if let ty::FnDef(def_id, substs) = ty.sty {
667         let instance = ty::Instance::resolve(tcx,
668                                              ty::ParamEnv::reveal_all(),
669                                              def_id,
670                                              substs).unwrap();
671         visit_instance_use(tcx, instance, is_direct_call, output);
672     }
673 }
674
675 fn visit_instance_use<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
676                                 instance: ty::Instance<'tcx>,
677                                 is_direct_call: bool,
678                                 output: &mut Vec<MonoItem<'tcx>>)
679 {
680     debug!("visit_item_use({:?}, is_direct_call={:?})", instance, is_direct_call);
681     if !should_monomorphize_locally(tcx, &instance) {
682         return
683     }
684
685     match instance.def {
686         ty::InstanceDef::Intrinsic(def_id) => {
687             if !is_direct_call {
688                 bug!("intrinsic {:?} being reified", def_id);
689             }
690         }
691         ty::InstanceDef::VtableShim(..) |
692         ty::InstanceDef::Virtual(..) |
693         ty::InstanceDef::DropGlue(_, None) => {
694             // don't need to emit shim if we are calling directly.
695             if !is_direct_call {
696                 output.push(create_fn_mono_item(instance));
697             }
698         }
699         ty::InstanceDef::DropGlue(_, Some(_)) => {
700             output.push(create_fn_mono_item(instance));
701         }
702         ty::InstanceDef::ClosureOnceShim { .. } |
703         ty::InstanceDef::Item(..) |
704         ty::InstanceDef::FnPtrShim(..) |
705         ty::InstanceDef::CloneShim(..) => {
706             output.push(create_fn_mono_item(instance));
707         }
708     }
709 }
710
711 // Returns true if we should codegen an instance in the local crate.
712 // Returns false if we can just link to the upstream crate and therefore don't
713 // need a mono item.
714 fn should_monomorphize_locally<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, instance: &Instance<'tcx>)
715                                          -> bool {
716     let def_id = match instance.def {
717         ty::InstanceDef::Item(def_id) => def_id,
718         ty::InstanceDef::VtableShim(..) |
719         ty::InstanceDef::ClosureOnceShim { .. } |
720         ty::InstanceDef::Virtual(..) |
721         ty::InstanceDef::FnPtrShim(..) |
722         ty::InstanceDef::DropGlue(..) |
723         ty::InstanceDef::Intrinsic(_) |
724         ty::InstanceDef::CloneShim(..) => return true
725     };
726
727     if tcx.is_foreign_item(def_id) {
728         // We can always link to foreign items
729         return false;
730     }
731
732     if def_id.is_local() {
733         // local items cannot be referred to locally without monomorphizing them locally
734         return true;
735     }
736
737     if tcx.is_reachable_non_generic(def_id) ||
738        is_available_upstream_generic(tcx, def_id, instance.substs) {
739         // We can link to the item in question, no instance needed
740         // in this crate
741         return false;
742     }
743
744     if !tcx.is_mir_available(def_id) {
745         bug!("Cannot create local mono-item for {:?}", def_id)
746     }
747     return true;
748
749     fn is_available_upstream_generic<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
750                                                def_id: DefId,
751                                                substs: &'tcx Substs<'tcx>)
752                                                -> bool {
753         debug_assert!(!def_id.is_local());
754
755         // If we are not in share generics mode, we don't link to upstream
756         // monomorphizations but always instantiate our own internal versions
757         // instead.
758         if !tcx.sess.opts.share_generics() {
759             return false
760         }
761
762         // If this instance has no type parameters, it cannot be a shared
763         // monomorphization. Non-generic instances are already handled above
764         // by `is_reachable_non_generic()`
765         if substs.types().next().is_none() {
766             return false
767         }
768
769         // Take a look at the available monomorphizations listed in the metadata
770         // of upstream crates.
771         tcx.upstream_monomorphizations_for(def_id)
772            .map(|set| set.contains_key(substs))
773            .unwrap_or(false)
774     }
775 }
776
777 /// For given pair of source and target type that occur in an unsizing coercion,
778 /// this function finds the pair of types that determines the vtable linking
779 /// them.
780 ///
781 /// For example, the source type might be `&SomeStruct` and the target type\
782 /// might be `&SomeTrait` in a cast like:
783 ///
784 /// let src: &SomeStruct = ...;
785 /// let target = src as &SomeTrait;
786 ///
787 /// Then the output of this function would be (SomeStruct, SomeTrait) since for
788 /// constructing the `target` fat-pointer we need the vtable for that pair.
789 ///
790 /// Things can get more complicated though because there's also the case where
791 /// the unsized type occurs as a field:
792 ///
793 /// ```rust
794 /// struct ComplexStruct<T: ?Sized> {
795 ///    a: u32,
796 ///    b: f64,
797 ///    c: T
798 /// }
799 /// ```
800 ///
801 /// In this case, if `T` is sized, `&ComplexStruct<T>` is a thin pointer. If `T`
802 /// is unsized, `&SomeStruct` is a fat pointer, and the vtable it points to is
803 /// for the pair of `T` (which is a trait) and the concrete type that `T` was
804 /// originally coerced from:
805 ///
806 /// let src: &ComplexStruct<SomeStruct> = ...;
807 /// let target = src as &ComplexStruct<SomeTrait>;
808 ///
809 /// Again, we want this `find_vtable_types_for_unsizing()` to provide the pair
810 /// `(SomeStruct, SomeTrait)`.
811 ///
812 /// Finally, there is also the case of custom unsizing coercions, e.g., for
813 /// smart pointers such as `Rc` and `Arc`.
814 fn find_vtable_types_for_unsizing<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
815                                             source_ty: Ty<'tcx>,
816                                             target_ty: Ty<'tcx>)
817                                             -> (Ty<'tcx>, Ty<'tcx>) {
818     let ptr_vtable = |inner_source: Ty<'tcx>, inner_target: Ty<'tcx>| {
819         let type_has_metadata = |ty: Ty<'tcx>| -> bool {
820             use syntax_pos::DUMMY_SP;
821             if ty.is_sized(tcx.at(DUMMY_SP), ty::ParamEnv::reveal_all()) {
822                 return false;
823             }
824             let tail = tcx.struct_tail(ty);
825             match tail.sty {
826                 ty::Foreign(..) => false,
827                 ty::Str | ty::Slice(..) | ty::Dynamic(..) => true,
828                 _ => bug!("unexpected unsized tail: {:?}", tail.sty),
829             }
830         };
831         if type_has_metadata(inner_source) {
832             (inner_source, inner_target)
833         } else {
834             tcx.struct_lockstep_tails(inner_source, inner_target)
835         }
836     };
837
838     match (&source_ty.sty, &target_ty.sty) {
839         (&ty::Ref(_, a, _),
840          &ty::Ref(_, b, _)) |
841         (&ty::Ref(_, a, _),
842          &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) |
843         (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }),
844          &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => {
845             ptr_vtable(a, b)
846         }
847         (&ty::Adt(def_a, _), &ty::Adt(def_b, _)) if def_a.is_box() && def_b.is_box() => {
848             ptr_vtable(source_ty.boxed_ty(), target_ty.boxed_ty())
849         }
850
851         (&ty::Adt(source_adt_def, source_substs),
852          &ty::Adt(target_adt_def, target_substs)) => {
853             assert_eq!(source_adt_def, target_adt_def);
854
855             let kind =
856                 monomorphize::custom_coerce_unsize_info(tcx, source_ty, target_ty);
857
858             let coerce_index = match kind {
859                 CustomCoerceUnsized::Struct(i) => i
860             };
861
862             let source_fields = &source_adt_def.non_enum_variant().fields;
863             let target_fields = &target_adt_def.non_enum_variant().fields;
864
865             assert!(coerce_index < source_fields.len() &&
866                     source_fields.len() == target_fields.len());
867
868             find_vtable_types_for_unsizing(tcx,
869                                            source_fields[coerce_index].ty(tcx,
870                                                                           source_substs),
871                                            target_fields[coerce_index].ty(tcx,
872                                                                           target_substs))
873         }
874         _ => bug!("find_vtable_types_for_unsizing: invalid coercion {:?} -> {:?}",
875                   source_ty,
876                   target_ty)
877     }
878 }
879
880 fn create_fn_mono_item<'a, 'tcx>(instance: Instance<'tcx>) -> MonoItem<'tcx> {
881     debug!("create_fn_mono_item(instance={})", instance);
882     MonoItem::Fn(instance)
883 }
884
885 /// Creates a `MonoItem` for each method that is referenced by the vtable for
886 /// the given trait/impl pair.
887 fn create_mono_items_for_vtable_methods<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
888                                                   trait_ty: Ty<'tcx>,
889                                                   impl_ty: Ty<'tcx>,
890                                                   output: &mut Vec<MonoItem<'tcx>>) {
891     assert!(!trait_ty.needs_subst() && !trait_ty.has_escaping_bound_vars() &&
892             !impl_ty.needs_subst() && !impl_ty.has_escaping_bound_vars());
893
894     if let ty::Dynamic(ref trait_ty, ..) = trait_ty.sty {
895         if let Some(principal) = trait_ty.principal() {
896             let poly_trait_ref = principal.with_self_ty(tcx, impl_ty);
897             assert!(!poly_trait_ref.has_escaping_bound_vars());
898
899             // Walk all methods of the trait, including those of its supertraits
900             let methods = tcx.vtable_methods(poly_trait_ref);
901             let methods = methods.iter().cloned().filter_map(|method| method)
902                 .map(|(def_id, substs)| ty::Instance::resolve_for_vtable(
903                     tcx,
904                     ty::ParamEnv::reveal_all(),
905                     def_id,
906                     substs).unwrap())
907                 .filter(|&instance| should_monomorphize_locally(tcx, &instance))
908                 .map(|instance| create_fn_mono_item(instance));
909             output.extend(methods);
910         }
911
912         // Also add the destructor
913         visit_drop_use(tcx, impl_ty, false, output);
914     }
915 }
916
917 //=-----------------------------------------------------------------------------
918 // Root Collection
919 //=-----------------------------------------------------------------------------
920
921 struct RootCollector<'b, 'a: 'b, 'tcx: 'a + 'b> {
922     tcx: TyCtxt<'a, 'tcx, 'tcx>,
923     mode: MonoItemCollectionMode,
924     output: &'b mut Vec<MonoItem<'tcx>>,
925     entry_fn: Option<(DefId, EntryFnType)>,
926 }
927
928 impl<'b, 'a, 'v> ItemLikeVisitor<'v> for RootCollector<'b, 'a, 'v> {
929     fn visit_item(&mut self, item: &'v hir::Item) {
930         match item.node {
931             hir::ItemKind::ExternCrate(..) |
932             hir::ItemKind::Use(..)         |
933             hir::ItemKind::ForeignMod(..)  |
934             hir::ItemKind::Ty(..)          |
935             hir::ItemKind::Trait(..)       |
936             hir::ItemKind::TraitAlias(..)  |
937             hir::ItemKind::Existential(..) |
938             hir::ItemKind::Mod(..)         => {
939                 // Nothing to do, just keep recursing...
940             }
941
942             hir::ItemKind::Impl(..) => {
943                 if self.mode == MonoItemCollectionMode::Eager {
944                     create_mono_items_for_default_impls(self.tcx,
945                                                         item,
946                                                         self.output);
947                 }
948             }
949
950             hir::ItemKind::Enum(_, ref generics) |
951             hir::ItemKind::Struct(_, ref generics) |
952             hir::ItemKind::Union(_, ref generics) => {
953                 if generics.params.is_empty() {
954                     if self.mode == MonoItemCollectionMode::Eager {
955                         let def_id = self.tcx.hir().local_def_id(item.id);
956                         debug!("RootCollector: ADT drop-glue for {}",
957                                def_id_to_string(self.tcx, def_id));
958
959                         let ty = Instance::new(def_id, Substs::empty()).ty(self.tcx);
960                         visit_drop_use(self.tcx, ty, true, self.output);
961                     }
962                 }
963             }
964             hir::ItemKind::GlobalAsm(..) => {
965                 debug!("RootCollector: ItemKind::GlobalAsm({})",
966                        def_id_to_string(self.tcx,
967                                         self.tcx.hir().local_def_id(item.id)));
968                 self.output.push(MonoItem::GlobalAsm(item.id));
969             }
970             hir::ItemKind::Static(..) => {
971                 let def_id = self.tcx.hir().local_def_id(item.id);
972                 debug!("RootCollector: ItemKind::Static({})",
973                        def_id_to_string(self.tcx, def_id));
974                 self.output.push(MonoItem::Static(def_id));
975             }
976             hir::ItemKind::Const(..) => {
977                 // const items only generate mono items if they are
978                 // actually used somewhere. Just declaring them is insufficient.
979
980                 // but even just declaring them must collect the items they refer to
981                 let def_id = self.tcx.hir().local_def_id(item.id);
982
983                 let instance = Instance::mono(self.tcx, def_id);
984                 let cid = GlobalId {
985                     instance,
986                     promoted: None,
987                 };
988                 let param_env = ty::ParamEnv::reveal_all();
989
990                 if let Ok(val) = self.tcx.const_eval(param_env.and(cid)) {
991                     collect_const(self.tcx, val, &mut self.output);
992                 }
993             }
994             hir::ItemKind::Fn(..) => {
995                 let def_id = self.tcx.hir().local_def_id(item.id);
996                 self.push_if_root(def_id);
997             }
998         }
999     }
1000
1001     fn visit_trait_item(&mut self, _: &'v hir::TraitItem) {
1002         // Even if there's a default body with no explicit generics,
1003         // it's still generic over some `Self: Trait`, so not a root.
1004     }
1005
1006     fn visit_impl_item(&mut self, ii: &'v hir::ImplItem) {
1007         match ii.node {
1008             hir::ImplItemKind::Method(hir::MethodSig { .. }, _) => {
1009                 let def_id = self.tcx.hir().local_def_id(ii.id);
1010                 self.push_if_root(def_id);
1011             }
1012             _ => { /* Nothing to do here */ }
1013         }
1014     }
1015 }
1016
1017 impl<'b, 'a, 'v> RootCollector<'b, 'a, 'v> {
1018     fn is_root(&self, def_id: DefId) -> bool {
1019         !item_has_type_parameters(self.tcx, def_id) && match self.mode {
1020             MonoItemCollectionMode::Eager => {
1021                 true
1022             }
1023             MonoItemCollectionMode::Lazy => {
1024                 self.entry_fn.map(|(id, _)| id) == Some(def_id) ||
1025                 self.tcx.is_reachable_non_generic(def_id) ||
1026                 self.tcx.codegen_fn_attrs(def_id).flags.contains(
1027                     CodegenFnAttrFlags::RUSTC_STD_INTERNAL_SYMBOL)
1028             }
1029         }
1030     }
1031
1032     /// If `def_id` represents a root, then push it onto the list of
1033     /// outputs. (Note that all roots must be monomorphic.)
1034     fn push_if_root(&mut self, def_id: DefId) {
1035         if self.is_root(def_id) {
1036             debug!("RootCollector::push_if_root: found root def_id={:?}", def_id);
1037
1038             let instance = Instance::mono(self.tcx, def_id);
1039             self.output.push(create_fn_mono_item(instance));
1040         }
1041     }
1042
1043     /// As a special case, when/if we encounter the
1044     /// `main()` function, we also have to generate a
1045     /// monomorphized copy of the start lang item based on
1046     /// the return type of `main`. This is not needed when
1047     /// the user writes their own `start` manually.
1048     fn push_extra_entry_roots(&mut self) {
1049         let main_def_id = match self.entry_fn {
1050             Some((def_id, EntryFnType::Main)) => def_id,
1051             _ => return,
1052         };
1053
1054         let start_def_id = match self.tcx.lang_items().require(StartFnLangItem) {
1055             Ok(s) => s,
1056             Err(err) => self.tcx.sess.fatal(&err),
1057         };
1058         let main_ret_ty = self.tcx.fn_sig(main_def_id).output();
1059
1060         // Given that `main()` has no arguments,
1061         // then its return type cannot have
1062         // late-bound regions, since late-bound
1063         // regions must appear in the argument
1064         // listing.
1065         let main_ret_ty = self.tcx.erase_regions(
1066             &main_ret_ty.no_bound_vars().unwrap(),
1067         );
1068
1069         let start_instance = Instance::resolve(
1070             self.tcx,
1071             ty::ParamEnv::reveal_all(),
1072             start_def_id,
1073             self.tcx.intern_substs(&[main_ret_ty.into()])
1074         ).unwrap();
1075
1076         self.output.push(create_fn_mono_item(start_instance));
1077     }
1078 }
1079
1080 fn item_has_type_parameters<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
1081     let generics = tcx.generics_of(def_id);
1082     generics.requires_monomorphization(tcx)
1083 }
1084
1085 fn create_mono_items_for_default_impls<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1086                                                  item: &'tcx hir::Item,
1087                                                  output: &mut Vec<MonoItem<'tcx>>) {
1088     match item.node {
1089         hir::ItemKind::Impl(_, _, _, ref generics, .., ref impl_item_refs) => {
1090             for param in &generics.params {
1091                 match param.kind {
1092                     hir::GenericParamKind::Lifetime { .. } => {}
1093                     hir::GenericParamKind::Type { .. } |
1094                     hir::GenericParamKind::Const { .. } => {
1095                         return
1096                     }
1097                 }
1098             }
1099
1100             let impl_def_id = tcx.hir().local_def_id(item.id);
1101
1102             debug!("create_mono_items_for_default_impls(item={})",
1103                    def_id_to_string(tcx, impl_def_id));
1104
1105             if let Some(trait_ref) = tcx.impl_trait_ref(impl_def_id) {
1106                 let overridden_methods: FxHashSet<_> =
1107                     impl_item_refs.iter()
1108                                   .map(|iiref| iiref.ident.modern())
1109                                   .collect();
1110                 for method in tcx.provided_trait_methods(trait_ref.def_id) {
1111                     if overridden_methods.contains(&method.ident.modern()) {
1112                         continue;
1113                     }
1114
1115                     if tcx.generics_of(method.def_id).own_counts().types != 0 {
1116                         continue;
1117                     }
1118
1119                     let substs = Substs::for_item(tcx, method.def_id, |param, _| {
1120                         match param.kind {
1121                             GenericParamDefKind::Lifetime => tcx.types.re_erased.into(),
1122                             GenericParamDefKind::Type {..} => {
1123                                 trait_ref.substs[param.index as usize]
1124                             }
1125                         }
1126                     });
1127
1128                     let instance = ty::Instance::resolve(tcx,
1129                                                          ty::ParamEnv::reveal_all(),
1130                                                          method.def_id,
1131                                                          substs).unwrap();
1132
1133                     let mono_item = create_fn_mono_item(instance);
1134                     if mono_item.is_instantiable(tcx)
1135                         && should_monomorphize_locally(tcx, &instance) {
1136                         output.push(mono_item);
1137                     }
1138                 }
1139             }
1140         }
1141         _ => {
1142             bug!()
1143         }
1144     }
1145 }
1146
1147 /// Scan the miri alloc in order to find function calls, closures, and drop-glue
1148 fn collect_miri<'a, 'tcx>(
1149     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1150     alloc_id: AllocId,
1151     output: &mut Vec<MonoItem<'tcx>>,
1152 ) {
1153     let alloc_kind = tcx.alloc_map.lock().get(alloc_id);
1154     match alloc_kind {
1155         Some(AllocKind::Static(did)) => {
1156             let instance = Instance::mono(tcx, did);
1157             if should_monomorphize_locally(tcx, &instance) {
1158                 trace!("collecting static {:?}", did);
1159                 output.push(MonoItem::Static(did));
1160             }
1161         }
1162         Some(AllocKind::Memory(alloc)) => {
1163             trace!("collecting {:?} with {:#?}", alloc_id, alloc);
1164             for &((), inner) in alloc.relocations.values() {
1165                 collect_miri(tcx, inner, output);
1166             }
1167         },
1168         Some(AllocKind::Function(fn_instance)) => {
1169             if should_monomorphize_locally(tcx, &fn_instance) {
1170                 trace!("collecting {:?} with {:#?}", alloc_id, fn_instance);
1171                 output.push(create_fn_mono_item(fn_instance));
1172             }
1173         }
1174         None => bug!("alloc id without corresponding allocation: {}", alloc_id),
1175     }
1176 }
1177
1178 /// Scan the MIR in order to find function calls, closures, and drop-glue
1179 fn collect_neighbours<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1180                                 instance: Instance<'tcx>,
1181                                 output: &mut Vec<MonoItem<'tcx>>)
1182 {
1183     let mir = tcx.instance_mir(instance.def);
1184
1185     MirNeighborCollector {
1186         tcx,
1187         mir: &mir,
1188         output,
1189         param_substs: instance.substs,
1190     }.visit_mir(&mir);
1191     let param_env = ty::ParamEnv::reveal_all();
1192     for i in 0..mir.promoted.len() {
1193         use rustc_data_structures::indexed_vec::Idx;
1194         let i = Promoted::new(i);
1195         let cid = GlobalId {
1196             instance,
1197             promoted: Some(i),
1198         };
1199         match tcx.const_eval(param_env.and(cid)) {
1200             Ok(val) => collect_const(tcx, val, output),
1201             Err(ErrorHandled::Reported) => {},
1202             Err(ErrorHandled::TooGeneric) => span_bug!(
1203                 mir.promoted[i].span, "collection encountered polymorphic constant",
1204             ),
1205         }
1206     }
1207 }
1208
1209 fn def_id_to_string<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1210                               def_id: DefId)
1211                               -> String {
1212     let mut output = String::new();
1213     let printer = DefPathBasedNames::new(tcx, false, false);
1214     printer.push_def_path(def_id, &mut output);
1215     output
1216 }
1217
1218 fn collect_lazy_const<'a, 'tcx>(
1219     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1220     constant: &ty::LazyConst<'tcx>,
1221     param_substs: &'tcx Substs<'tcx>,
1222     output: &mut Vec<MonoItem<'tcx>>,
1223 ) {
1224     let (def_id, substs) = match *constant {
1225         ty::LazyConst::Evaluated(c) => return collect_const(tcx, c, output),
1226         ty::LazyConst::Unevaluated(did, substs) => (did, substs),
1227     };
1228     let param_env = ty::ParamEnv::reveal_all();
1229     let substs = tcx.subst_and_normalize_erasing_regions(
1230         param_substs,
1231         param_env,
1232         &substs,
1233     );
1234     let instance = ty::Instance::resolve(tcx,
1235                                         param_env,
1236                                         def_id,
1237                                         substs).unwrap();
1238
1239     let cid = GlobalId {
1240         instance,
1241         promoted: None,
1242     };
1243     match tcx.const_eval(param_env.and(cid)) {
1244         Ok(val) => collect_const(tcx, val, output),
1245         Err(ErrorHandled::Reported) => {},
1246         Err(ErrorHandled::TooGeneric) => span_bug!(
1247             tcx.def_span(def_id), "collection encountered polymorphic constant",
1248         ),
1249     }
1250 }
1251
1252 fn collect_const<'a, 'tcx>(
1253     tcx: TyCtxt<'a, 'tcx, 'tcx>,
1254     constant: ty::Const<'tcx>,
1255     output: &mut Vec<MonoItem<'tcx>>,
1256 ) {
1257     debug!("visiting const {:?}", constant);
1258
1259     match constant.val {
1260         ConstValue::Slice(Scalar::Ptr(ptr), _) |
1261         ConstValue::Scalar(Scalar::Ptr(ptr)) =>
1262             collect_miri(tcx, ptr.alloc_id, output),
1263         ConstValue::ByRef(_id, alloc, _offset) => {
1264             for &((), id) in alloc.relocations.values() {
1265                 collect_miri(tcx, id, output);
1266             }
1267         }
1268         _ => {},
1269     }
1270 }