]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/monomorphize/item.rs
2ba9600dfc9f03b189918fee05e21d43a1f1f8eb
[rust.git] / src / librustc_mir / monomorphize / item.rs
1 use rustc::hir::def_id::LOCAL_CRATE;
2 use rustc::mir::mono::MonoItem;
3 use rustc::session::config::OptLevel;
4 use rustc::ty::{self, TyCtxt, Instance};
5 use rustc::ty::subst::InternalSubsts;
6 use rustc::ty::print::obsolete::DefPathBasedNames;
7 use syntax::attr::InlineAttr;
8 use std::fmt;
9 use rustc::mir::mono::Linkage;
10 use syntax_pos::symbol::InternedString;
11 use syntax::source_map::Span;
12
13 /// Describes how a monomorphization will be instantiated in object files.
14 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
15 pub enum InstantiationMode {
16     /// There will be exactly one instance of the given MonoItem. It will have
17     /// external linkage so that it can be linked to from other codegen units.
18     GloballyShared {
19         /// In some compilation scenarios we may decide to take functions that
20         /// are typically `LocalCopy` and instead move them to `GloballyShared`
21         /// to avoid codegenning them a bunch of times. In this situation,
22         /// however, our local copy may conflict with other crates also
23         /// inlining the same function.
24         ///
25         /// This flag indicates that this situation is occurring, and informs
26         /// symbol name calculation that some extra mangling is needed to
27         /// avoid conflicts. Note that this may eventually go away entirely if
28         /// ThinLTO enables us to *always* have a globally shared instance of a
29         /// function within one crate's compilation.
30         may_conflict: bool,
31     },
32
33     /// Each codegen unit containing a reference to the given MonoItem will
34     /// have its own private copy of the function (with internal linkage).
35     LocalCopy,
36 }
37
38 pub trait MonoItemExt<'tcx>: fmt::Debug {
39     fn as_mono_item(&self) -> &MonoItem<'tcx>;
40
41     fn is_generic_fn(&self) -> bool {
42         match *self.as_mono_item() {
43             MonoItem::Fn(ref instance) => {
44                 instance.substs.non_erasable_generics().next().is_some()
45             }
46             MonoItem::Static(..) |
47             MonoItem::GlobalAsm(..) => false,
48         }
49     }
50
51     fn symbol_name(&self, tcx: TyCtxt<'tcx, 'tcx>) -> ty::SymbolName {
52         match *self.as_mono_item() {
53             MonoItem::Fn(instance) => tcx.symbol_name(instance),
54             MonoItem::Static(def_id) => {
55                 tcx.symbol_name(Instance::mono(tcx, def_id))
56             }
57             MonoItem::GlobalAsm(hir_id) => {
58                 let def_id = tcx.hir().local_def_id_from_hir_id(hir_id);
59                 ty::SymbolName {
60                     name: InternedString::intern(&format!("global_asm_{:?}", def_id))
61                 }
62             }
63         }
64     }
65     fn instantiation_mode(&self,
66                           tcx: TyCtxt<'tcx, 'tcx>)
67                           -> InstantiationMode {
68         let inline_in_all_cgus =
69             tcx.sess.opts.debugging_opts.inline_in_all_cgus.unwrap_or_else(|| {
70                 tcx.sess.opts.optimize != OptLevel::No
71             }) && !tcx.sess.opts.cg.link_dead_code;
72
73         match *self.as_mono_item() {
74             MonoItem::Fn(ref instance) => {
75                 let entry_def_id = tcx.entry_fn(LOCAL_CRATE).map(|(id, _)| id);
76                 // If this function isn't inlined or otherwise has explicit
77                 // linkage, then we'll be creating a globally shared version.
78                 if self.explicit_linkage(tcx).is_some() ||
79                     !instance.def.requires_local(tcx) ||
80                     Some(instance.def_id()) == entry_def_id
81                 {
82                     return InstantiationMode::GloballyShared  { may_conflict: false }
83                 }
84
85                 // At this point we don't have explicit linkage and we're an
86                 // inlined function. If we're inlining into all CGUs then we'll
87                 // be creating a local copy per CGU
88                 if inline_in_all_cgus {
89                     return InstantiationMode::LocalCopy
90                 }
91
92                 // Finally, if this is `#[inline(always)]` we're sure to respect
93                 // that with an inline copy per CGU, but otherwise we'll be
94                 // creating one copy of this `#[inline]` function which may
95                 // conflict with upstream crates as it could be an exported
96                 // symbol.
97                 match tcx.codegen_fn_attrs(instance.def_id()).inline {
98                     InlineAttr::Always => InstantiationMode::LocalCopy,
99                     _ => {
100                         InstantiationMode::GloballyShared  { may_conflict: true }
101                     }
102                 }
103             }
104             MonoItem::Static(..) |
105             MonoItem::GlobalAsm(..) => {
106                 InstantiationMode::GloballyShared { may_conflict: false }
107             }
108         }
109     }
110
111     fn explicit_linkage(&self, tcx: TyCtxt<'tcx, 'tcx>) -> Option<Linkage> {
112         let def_id = match *self.as_mono_item() {
113             MonoItem::Fn(ref instance) => instance.def_id(),
114             MonoItem::Static(def_id) => def_id,
115             MonoItem::GlobalAsm(..) => return None,
116         };
117
118         let codegen_fn_attrs = tcx.codegen_fn_attrs(def_id);
119         codegen_fn_attrs.linkage
120     }
121
122     /// Returns `true` if this instance is instantiable - whether it has no unsatisfied
123     /// predicates.
124     ///
125     /// In order to codegen an item, all of its predicates must hold, because
126     /// otherwise the item does not make sense. Type-checking ensures that
127     /// the predicates of every item that is *used by* a valid item *do*
128     /// hold, so we can rely on that.
129     ///
130     /// However, we codegen collector roots (reachable items) and functions
131     /// in vtables when they are seen, even if they are not used, and so they
132     /// might not be instantiable. For example, a programmer can define this
133     /// public function:
134     ///
135     ///     pub fn foo<'a>(s: &'a mut ()) where &'a mut (): Clone {
136     ///         <&mut () as Clone>::clone(&s);
137     ///     }
138     ///
139     /// That function can't be codegened, because the method `<&mut () as Clone>::clone`
140     /// does not exist. Luckily for us, that function can't ever be used,
141     /// because that would require for `&'a mut (): Clone` to hold, so we
142     /// can just not emit any code, or even a linker reference for it.
143     ///
144     /// Similarly, if a vtable method has such a signature, and therefore can't
145     /// be used, we can just not emit it and have a placeholder (a null pointer,
146     /// which will never be accessed) in its place.
147     fn is_instantiable(&self, tcx: TyCtxt<'tcx, 'tcx>) -> bool {
148         debug!("is_instantiable({:?})", self);
149         let (def_id, substs) = match *self.as_mono_item() {
150             MonoItem::Fn(ref instance) => (instance.def_id(), instance.substs),
151             MonoItem::Static(def_id) => (def_id, InternalSubsts::empty()),
152             // global asm never has predicates
153             MonoItem::GlobalAsm(..) => return true
154         };
155
156         tcx.substitute_normalize_and_test_predicates((def_id, &substs))
157     }
158
159     fn to_string(&self, tcx: TyCtxt<'tcx, 'tcx>, debug: bool) -> String {
160         return match *self.as_mono_item() {
161             MonoItem::Fn(instance) => {
162                 to_string_internal(tcx, "fn ", instance, debug)
163             },
164             MonoItem::Static(def_id) => {
165                 let instance = Instance::new(def_id, tcx.intern_substs(&[]));
166                 to_string_internal(tcx, "static ", instance, debug)
167             },
168             MonoItem::GlobalAsm(..) => {
169                 "global_asm".to_string()
170             }
171         };
172
173         fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'tcx, 'tcx>,
174                                         prefix: &str,
175                                         instance: Instance<'tcx>,
176                                         debug: bool)
177                                         -> String {
178             let mut result = String::with_capacity(32);
179             result.push_str(prefix);
180             let printer = DefPathBasedNames::new(tcx, false, false);
181             printer.push_instance_as_string(instance, &mut result, debug);
182             result
183         }
184     }
185
186     fn local_span(&self, tcx: TyCtxt<'tcx, 'tcx>) -> Option<Span> {
187         match *self.as_mono_item() {
188             MonoItem::Fn(Instance { def, .. }) => {
189                 tcx.hir().as_local_hir_id(def.def_id())
190             }
191             MonoItem::Static(def_id) => {
192                 tcx.hir().as_local_hir_id(def_id)
193             }
194             MonoItem::GlobalAsm(hir_id) => {
195                 Some(hir_id)
196             }
197         }.map(|hir_id| tcx.hir().span_by_hir_id(hir_id))
198     }
199 }
200
201 impl MonoItemExt<'tcx> for MonoItem<'tcx> {
202     fn as_mono_item(&self) -> &MonoItem<'tcx> {
203         self
204     }
205 }