1 //! Mono Item Collection
2 //! ===========================
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.
15 //! The following kinds of "mono items" are handled here:
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
34 //! Let's define some terms first:
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
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".
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.
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:
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.
60 //! ### Discovering roots
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.
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:
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.
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:
91 //! fn print_val<T: Display>(x: T) {
92 //! println!("{}", x);
95 //! fn call_fn(f: &Fn(i32), x: i32) {
100 //! let print_i32 = print_val::<i32>;
101 //! call_fn(&print_i32, 0);
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.
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.
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.
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.
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.
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
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.
150 //! Eager and Lazy Collection Mode
151 //! ------------------------------
152 //! Mono item collection can be performed in one of two modes:
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
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.
168 //! Some things are not yet fully implemented in the current version of this
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.
177 use rustc::hir::{self, CodegenFnAttrFlags};
178 use rustc::hir::itemlikevisit::ItemLikeVisitor;
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};
192 use crate::monomorphize::{self, Instance};
193 use rustc::util::nodemap::{FxHashSet, FxHashMap, DefIdMap};
194 use rustc::util::common::time;
196 use crate::monomorphize::item::{MonoItemExt, DefPathBasedNames, InstantiationMode};
198 use rustc_data_structures::bit_set::GrowableBitSet;
199 use rustc_data_structures::sync::{MTRef, MTLock, ParallelIterator, par_iter};
201 #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)]
202 pub enum MonoItemCollectionMode {
207 /// Maps every mono item to all mono items it references in its
209 pub struct InliningMap<'tcx> {
210 // Maps a source mono item to the range of mono items
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>>,
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>,
222 impl<'tcx> InliningMap<'tcx> {
224 fn new() -> InliningMap<'tcx> {
226 index: FxHashMap::default(),
228 inlines: GrowableBitSet::with_capacity(1024),
232 fn record_accesses<I>(&mut self,
233 source: MonoItem<'tcx>,
235 where I: Iterator<Item=(MonoItem<'tcx>, bool)> + ExactSizeIterator
237 assert!(!self.index.contains_key(&source));
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();
243 self.targets.reserve(new_items_count);
244 self.inlines.ensure(new_items_count_total);
246 for (i, (target, inline)) in new_targets.enumerate() {
247 self.targets.push(target);
249 self.inlines.insert(i + start_index);
253 let end_index = self.targets.len();
254 self.index.insert(source, (start_index, end_index));
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>)
262 if let Some(&(start_index, end_index)) = self.index.get(&source) {
263 for (i, candidate) in self.targets[start_index .. end_index]
266 if self.inlines.contains(start_index + i) {
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>])
277 for (&accessor, &(start_index, end_index)) in &self.index {
278 f(accessor, &self.targets[start_index .. end_index])
283 pub fn collect_crate_mono_items<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
284 mode: MonoItemCollectionMode)
285 -> (FxHashSet<MonoItem<'tcx>>,
287 let roots = time(tcx.sess, "collecting roots", || {
288 collect_roots(tcx, mode)
291 debug!("Building mono item graph, beginning at roots");
293 let mut visited = MTLock::new(FxHashSet::default());
294 let mut inlining_map = MTLock::new(InliningMap::new());
297 let visited: MTRef<'_, _> = &mut visited;
298 let inlining_map: MTRef<'_, _> = &mut inlining_map;
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,
306 &mut recursion_depths,
312 (visited.into_inner(), inlining_map.into_inner())
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();
324 let entry_fn = tcx.entry_fn(LOCAL_CRATE);
326 debug!("collect_roots: entry_fn = {:?}", entry_fn);
328 let mut visitor = RootCollector {
335 tcx.hir().krate().visit_all_item_likes(&mut visitor);
337 visitor.push_extra_entry_roots();
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));
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.
358 debug!("BEGIN collect_items_rec({})", starting_point.to_string(tcx, true));
360 let mut neighbors = Vec::new();
361 let recursion_depth_reset;
363 match starting_point {
364 MonoItem::Static(def_id) => {
365 let instance = Instance::mono(tcx, def_id);
367 // Sanity check whether this ended up being collected accidentally
368 debug_assert!(should_monomorphize_locally(tcx, &instance));
370 let ty = instance.ty(tcx);
371 visit_drop_use(tcx, ty, true, &mut neighbors);
373 recursion_depth_reset = None;
379 let param_env = ty::ParamEnv::reveal_all();
381 if let Ok(val) = tcx.const_eval(param_env.and(cid)) {
382 collect_const(tcx, val, &mut neighbors);
385 MonoItem::Fn(instance) => {
386 // Sanity check whether this ended up being collected accidentally
387 debug_assert!(should_monomorphize_locally(tcx, &instance));
389 // Keep track of the monomorphization recursion depth
390 recursion_depth_reset = Some(check_recursion_limit(tcx,
393 check_type_length_limit(tcx, instance);
395 collect_neighbours(tcx, instance, &mut neighbors);
397 MonoItem::GlobalAsm(..) => {
398 recursion_depth_reset = None;
402 record_accesses(tcx, starting_point, &neighbors[..], inlining_map);
404 for neighbour in neighbors {
405 collect_items_rec(tcx, neighbour, visited, recursion_depths, inlining_map);
408 if let Some((def_id, depth)) = recursion_depth_reset {
409 recursion_depths.insert(def_id, depth);
412 debug!("END collect_items_rec({})", starting_point.to_string(tcx, true));
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
423 let accesses = callees.into_iter()
425 (*mono_item, is_inlining_candidate(mono_item))
428 inlining_map.lock_mut().record_accesses(caller, accesses);
431 fn check_recursion_limit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
432 instance: Instance<'tcx>,
433 recursion_depths: &mut DefIdMap<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);
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
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 `{}`",
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);
456 tcx.sess.fatal(&error);
460 recursion_depths.insert(def_id, recursion_depth + 1);
462 (def_id, recursion_depth)
465 fn check_type_length_limit<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
466 instance: Instance<'tcx>)
468 let type_length = instance.substs.types().flat_map(|ty| ty.walk()).count();
469 debug!(" => type length={}", type_length);
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.
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}...`",
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)
488 tcx.sess.struct_fatal(&msg)
492 "consider adding a `#![type_length_limit=\"{}\"]` attribute to your crate",
493 type_length_limit*2));
495 tcx.sess.abort_if_errors();
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>,
506 impl<'a, 'tcx> MirVisitor<'tcx> for MirNeighborCollector<'a, 'tcx> {
508 fn visit_rvalue(&mut self, rvalue: &mir::Rvalue<'tcx>, location: Location) {
509 debug!("visiting rvalue {:?}", *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(
518 ty::ParamEnv::reveal_all(),
521 let source_ty = operand.ty(self.mir, self.tcx);
522 let source_ty = self.tcx.subst_and_normalize_erasing_regions(
524 ty::ParamEnv::reveal_all(),
527 let (source_ty, target_ty) = find_vtable_types_for_unsizing(self.tcx,
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,
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(
544 ty::ParamEnv::reveal_all(),
547 visit_fn_use(self.tcx, fn_ty, false, &mut self.output);
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(
553 ty::ParamEnv::reveal_all(),
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));
567 mir::Rvalue::NullaryOp(mir::NullOp::Box, _) => {
569 let exchange_malloc_fn_def_id = tcx
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));
578 _ => { /* not interesting */ }
581 self.super_rvalue(rvalue, location);
584 fn visit_const(&mut self, constant: &&'tcx ty::LazyConst<'tcx>, location: Location) {
585 debug!("visiting const {:?} @ {:?}", *constant, location);
587 collect_lazy_const(self.tcx, constant, self.param_substs, self.output);
589 self.super_const(constant);
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);
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(
604 ty::ParamEnv::reveal_all(),
607 visit_fn_use(self.tcx, callee_ty, true, &mut self.output);
609 mir::TerminatorKind::Drop { ref location, .. } |
610 mir::TerminatorKind::DropAndReplace { ref location, .. } => {
611 let ty = location.ty(self.mir, self.tcx)
613 let ty = tcx.subst_and_normalize_erasing_regions(
615 ty::ParamEnv::reveal_all(),
618 visit_drop_use(self.tcx, ty, true, self.output);
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!(),
633 self.super_terminator_kind(block, kind, location);
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);
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));
648 self.super_static(static_, context, location);
652 fn visit_drop_use<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
654 is_direct_call: bool,
655 output: &mut Vec<MonoItem<'tcx>>)
657 let instance = monomorphize::resolve_drop_in_place(tcx, ty);
658 visit_instance_use(tcx, instance, is_direct_call, output);
661 fn visit_fn_use<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
663 is_direct_call: bool,
664 output: &mut Vec<MonoItem<'tcx>>)
666 if let ty::FnDef(def_id, substs) = ty.sty {
667 let instance = ty::Instance::resolve(tcx,
668 ty::ParamEnv::reveal_all(),
671 visit_instance_use(tcx, instance, is_direct_call, output);
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>>)
680 debug!("visit_item_use({:?}, is_direct_call={:?})", instance, is_direct_call);
681 if !should_monomorphize_locally(tcx, &instance) {
686 ty::InstanceDef::Intrinsic(def_id) => {
688 bug!("intrinsic {:?} being reified", def_id);
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.
696 output.push(create_fn_mono_item(instance));
699 ty::InstanceDef::DropGlue(_, Some(_)) => {
700 output.push(create_fn_mono_item(instance));
702 ty::InstanceDef::ClosureOnceShim { .. } |
703 ty::InstanceDef::Item(..) |
704 ty::InstanceDef::FnPtrShim(..) |
705 ty::InstanceDef::CloneShim(..) => {
706 output.push(create_fn_mono_item(instance));
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
714 fn should_monomorphize_locally<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, instance: &Instance<'tcx>)
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
727 if tcx.is_foreign_item(def_id) {
728 // We can always link to foreign items
732 if def_id.is_local() {
733 // local items cannot be referred to locally without monomorphizing them locally
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
744 if !tcx.is_mir_available(def_id) {
745 bug!("Cannot create local mono-item for {:?}", def_id)
749 fn is_available_upstream_generic<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
751 substs: &'tcx Substs<'tcx>)
753 debug_assert!(!def_id.is_local());
755 // If we are not in share generics mode, we don't link to upstream
756 // monomorphizations but always instantiate our own internal versions
758 if !tcx.sess.opts.share_generics() {
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() {
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))
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
781 /// For example, the source type might be `&SomeStruct` and the target type\
782 /// might be `&SomeTrait` in a cast like:
784 /// let src: &SomeStruct = ...;
785 /// let target = src as &SomeTrait;
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.
790 /// Things can get more complicated though because there's also the case where
791 /// the unsized type occurs as a field:
794 /// struct ComplexStruct<T: ?Sized> {
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:
806 /// let src: &ComplexStruct<SomeStruct> = ...;
807 /// let target = src as &ComplexStruct<SomeTrait>;
809 /// Again, we want this `find_vtable_types_for_unsizing()` to provide the pair
810 /// `(SomeStruct, SomeTrait)`.
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>,
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()) {
824 let tail = tcx.struct_tail(ty);
826 ty::Foreign(..) => false,
827 ty::Str | ty::Slice(..) | ty::Dynamic(..) => true,
828 _ => bug!("unexpected unsized tail: {:?}", tail.sty),
831 if type_has_metadata(inner_source) {
832 (inner_source, inner_target)
834 tcx.struct_lockstep_tails(inner_source, inner_target)
838 match (&source_ty.sty, &target_ty.sty) {
842 &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) |
843 (&ty::RawPtr(ty::TypeAndMut { ty: a, .. }),
844 &ty::RawPtr(ty::TypeAndMut { ty: b, .. })) => {
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())
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);
856 monomorphize::custom_coerce_unsize_info(tcx, source_ty, target_ty);
858 let coerce_index = match kind {
859 CustomCoerceUnsized::Struct(i) => i
862 let source_fields = &source_adt_def.non_enum_variant().fields;
863 let target_fields = &target_adt_def.non_enum_variant().fields;
865 assert!(coerce_index < source_fields.len() &&
866 source_fields.len() == target_fields.len());
868 find_vtable_types_for_unsizing(tcx,
869 source_fields[coerce_index].ty(tcx,
871 target_fields[coerce_index].ty(tcx,
874 _ => bug!("find_vtable_types_for_unsizing: invalid coercion {:?} -> {:?}",
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)
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>,
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());
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());
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(
904 ty::ParamEnv::reveal_all(),
907 .filter(|&instance| should_monomorphize_locally(tcx, &instance))
908 .map(|instance| create_fn_mono_item(instance));
909 output.extend(methods);
912 // Also add the destructor
913 visit_drop_use(tcx, impl_ty, false, output);
917 //=-----------------------------------------------------------------------------
919 //=-----------------------------------------------------------------------------
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)>,
928 impl<'b, 'a, 'v> ItemLikeVisitor<'v> for RootCollector<'b, 'a, 'v> {
929 fn visit_item(&mut self, item: &'v hir::Item) {
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...
942 hir::ItemKind::Impl(..) => {
943 if self.mode == MonoItemCollectionMode::Eager {
944 create_mono_items_for_default_impls(self.tcx,
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));
959 let ty = Instance::new(def_id, Substs::empty()).ty(self.tcx);
960 visit_drop_use(self.tcx, ty, true, self.output);
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));
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));
976 hir::ItemKind::Const(..) => {
977 // const items only generate mono items if they are
978 // actually used somewhere. Just declaring them is insufficient.
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);
983 let instance = Instance::mono(self.tcx, def_id);
988 let param_env = ty::ParamEnv::reveal_all();
990 if let Ok(val) = self.tcx.const_eval(param_env.and(cid)) {
991 collect_const(self.tcx, val, &mut self.output);
994 hir::ItemKind::Fn(..) => {
995 let def_id = self.tcx.hir().local_def_id(item.id);
996 self.push_if_root(def_id);
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.
1006 fn visit_impl_item(&mut self, ii: &'v hir::ImplItem) {
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);
1012 _ => { /* Nothing to do here */ }
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 => {
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)
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);
1038 let instance = Instance::mono(self.tcx, def_id);
1039 self.output.push(create_fn_mono_item(instance));
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,
1054 let start_def_id = match self.tcx.lang_items().require(StartFnLangItem) {
1056 Err(err) => self.tcx.sess.fatal(&err),
1058 let main_ret_ty = self.tcx.fn_sig(main_def_id).output();
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
1065 let main_ret_ty = self.tcx.erase_regions(
1066 &main_ret_ty.no_bound_vars().unwrap(),
1069 let start_instance = Instance::resolve(
1071 ty::ParamEnv::reveal_all(),
1073 self.tcx.intern_substs(&[main_ret_ty.into()])
1076 self.output.push(create_fn_mono_item(start_instance));
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)
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>>) {
1089 hir::ItemKind::Impl(_, _, _, ref generics, .., ref impl_item_refs) => {
1090 for param in &generics.params {
1092 hir::GenericParamKind::Lifetime { .. } => {}
1093 hir::GenericParamKind::Type { .. } |
1094 hir::GenericParamKind::Const { .. } => {
1100 let impl_def_id = tcx.hir().local_def_id(item.id);
1102 debug!("create_mono_items_for_default_impls(item={})",
1103 def_id_to_string(tcx, impl_def_id));
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())
1110 for method in tcx.provided_trait_methods(trait_ref.def_id) {
1111 if overridden_methods.contains(&method.ident.modern()) {
1115 if tcx.generics_of(method.def_id).own_counts().types != 0 {
1119 let substs = Substs::for_item(tcx, method.def_id, |param, _| {
1121 GenericParamDefKind::Lifetime => tcx.types.re_erased.into(),
1122 GenericParamDefKind::Type {..} => {
1123 trait_ref.substs[param.index as usize]
1128 let instance = ty::Instance::resolve(tcx,
1129 ty::ParamEnv::reveal_all(),
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);
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>,
1151 output: &mut Vec<MonoItem<'tcx>>,
1153 let alloc_kind = tcx.alloc_map.lock().get(alloc_id);
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));
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);
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));
1174 None => bug!("alloc id without corresponding allocation: {}", alloc_id),
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>>)
1183 let mir = tcx.instance_mir(instance.def);
1185 MirNeighborCollector {
1189 param_substs: instance.substs,
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 {
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",
1209 fn def_id_to_string<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1212 let mut output = String::new();
1213 let printer = DefPathBasedNames::new(tcx, false, false);
1214 printer.push_def_path(def_id, &mut output);
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>>,
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),
1228 let param_env = ty::ParamEnv::reveal_all();
1229 let substs = tcx.subst_and_normalize_erasing_regions(
1234 let instance = ty::Instance::resolve(tcx,
1239 let cid = GlobalId {
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",
1252 fn collect_const<'a, 'tcx>(
1253 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1254 constant: ty::Const<'tcx>,
1255 output: &mut Vec<MonoItem<'tcx>>,
1257 debug!("visiting const {:?}", constant);
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);