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;
9 use rustc::mir::mono::Linkage;
10 use syntax_pos::symbol::InternedString;
11 use syntax::source_map::Span;
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.
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.
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.
33 /// Each codegen unit containing a reference to the given MonoItem will
34 /// have its own private copy of the function (with internal linkage).
38 pub trait MonoItemExt<'tcx>: fmt::Debug {
39 fn as_mono_item(&self) -> &MonoItem<'tcx>;
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()
46 MonoItem::Static(..) |
47 MonoItem::GlobalAsm(..) => false,
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))
57 MonoItem::GlobalAsm(hir_id) => {
58 let def_id = tcx.hir().local_def_id_from_hir_id(hir_id);
60 name: InternedString::intern(&format!("global_asm_{:?}", def_id))
65 fn instantiation_mode(&self, tcx: TyCtxt<'tcx, 'tcx>) -> InstantiationMode {
66 let inline_in_all_cgus =
67 tcx.sess.opts.debugging_opts.inline_in_all_cgus.unwrap_or_else(|| {
68 tcx.sess.opts.optimize != OptLevel::No
69 }) && !tcx.sess.opts.cg.link_dead_code;
71 match *self.as_mono_item() {
72 MonoItem::Fn(ref instance) => {
73 let entry_def_id = tcx.entry_fn(LOCAL_CRATE).map(|(id, _)| id);
74 // If this function isn't inlined or otherwise has explicit
75 // linkage, then we'll be creating a globally shared version.
76 if self.explicit_linkage(tcx).is_some() ||
77 !instance.def.requires_local(tcx) ||
78 Some(instance.def_id()) == entry_def_id
80 return InstantiationMode::GloballyShared { may_conflict: false }
83 // At this point we don't have explicit linkage and we're an
84 // inlined function. If we're inlining into all CGUs then we'll
85 // be creating a local copy per CGU
86 if inline_in_all_cgus {
87 return InstantiationMode::LocalCopy
90 // Finally, if this is `#[inline(always)]` we're sure to respect
91 // that with an inline copy per CGU, but otherwise we'll be
92 // creating one copy of this `#[inline]` function which may
93 // conflict with upstream crates as it could be an exported
95 match tcx.codegen_fn_attrs(instance.def_id()).inline {
96 InlineAttr::Always => InstantiationMode::LocalCopy,
98 InstantiationMode::GloballyShared { may_conflict: true }
102 MonoItem::Static(..) |
103 MonoItem::GlobalAsm(..) => {
104 InstantiationMode::GloballyShared { may_conflict: false }
109 fn explicit_linkage(&self, tcx: TyCtxt<'tcx, 'tcx>) -> Option<Linkage> {
110 let def_id = match *self.as_mono_item() {
111 MonoItem::Fn(ref instance) => instance.def_id(),
112 MonoItem::Static(def_id) => def_id,
113 MonoItem::GlobalAsm(..) => return None,
116 let codegen_fn_attrs = tcx.codegen_fn_attrs(def_id);
117 codegen_fn_attrs.linkage
120 /// Returns `true` if this instance is instantiable - whether it has no unsatisfied
123 /// In order to codegen an item, all of its predicates must hold, because
124 /// otherwise the item does not make sense. Type-checking ensures that
125 /// the predicates of every item that is *used by* a valid item *do*
126 /// hold, so we can rely on that.
128 /// However, we codegen collector roots (reachable items) and functions
129 /// in vtables when they are seen, even if they are not used, and so they
130 /// might not be instantiable. For example, a programmer can define this
133 /// pub fn foo<'a>(s: &'a mut ()) where &'a mut (): Clone {
134 /// <&mut () as Clone>::clone(&s);
137 /// That function can't be codegened, because the method `<&mut () as Clone>::clone`
138 /// does not exist. Luckily for us, that function can't ever be used,
139 /// because that would require for `&'a mut (): Clone` to hold, so we
140 /// can just not emit any code, or even a linker reference for it.
142 /// Similarly, if a vtable method has such a signature, and therefore can't
143 /// be used, we can just not emit it and have a placeholder (a null pointer,
144 /// which will never be accessed) in its place.
145 fn is_instantiable(&self, tcx: TyCtxt<'tcx, 'tcx>) -> bool {
146 debug!("is_instantiable({:?})", self);
147 let (def_id, substs) = match *self.as_mono_item() {
148 MonoItem::Fn(ref instance) => (instance.def_id(), instance.substs),
149 MonoItem::Static(def_id) => (def_id, InternalSubsts::empty()),
150 // global asm never has predicates
151 MonoItem::GlobalAsm(..) => return true
154 tcx.substitute_normalize_and_test_predicates((def_id, &substs))
157 fn to_string(&self, tcx: TyCtxt<'tcx, 'tcx>, debug: bool) -> String {
158 return match *self.as_mono_item() {
159 MonoItem::Fn(instance) => {
160 to_string_internal(tcx, "fn ", instance, debug)
162 MonoItem::Static(def_id) => {
163 let instance = Instance::new(def_id, tcx.intern_substs(&[]));
164 to_string_internal(tcx, "static ", instance, debug)
166 MonoItem::GlobalAsm(..) => {
167 "global_asm".to_string()
171 fn to_string_internal<'a, 'tcx>(
172 tcx: TyCtxt<'tcx, 'tcx>,
174 instance: Instance<'tcx>,
177 let mut result = String::with_capacity(32);
178 result.push_str(prefix);
179 let printer = DefPathBasedNames::new(tcx, false, false);
180 printer.push_instance_as_string(instance, &mut result, debug);
185 fn local_span(&self, tcx: TyCtxt<'tcx, 'tcx>) -> Option<Span> {
186 match *self.as_mono_item() {
187 MonoItem::Fn(Instance { def, .. }) => {
188 tcx.hir().as_local_hir_id(def.def_id())
190 MonoItem::Static(def_id) => {
191 tcx.hir().as_local_hir_id(def_id)
193 MonoItem::GlobalAsm(hir_id) => {
196 }.map(|hir_id| tcx.hir().span_by_hir_id(hir_id))
200 impl MonoItemExt<'tcx> for MonoItem<'tcx> {
201 fn as_mono_item(&self) -> &MonoItem<'tcx> {