]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/monomorphize/item.rs
6b40245d39a8eae5fb7c094cb85f3d8bd0d122d0
[rust.git] / src / librustc_mir / monomorphize / item.rs
1 use crate::monomorphize::Instance;
2 use rustc::hir;
3 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
4 use rustc::mir::interpret::ConstValue;
5 use rustc::session::config::OptLevel;
6 use rustc::ty::{self, Ty, TyCtxt, Const, ClosureSubsts, GeneratorSubsts};
7 use rustc::ty::subst::{SubstsRef, InternalSubsts};
8 use syntax::ast;
9 use syntax::attr::InlineAttr;
10 use std::fmt::{self, Write};
11 use std::iter;
12 use rustc::mir::mono::Linkage;
13 use syntax_pos::symbol::InternedString;
14 use syntax::source_map::Span;
15 pub use rustc::mir::mono::MonoItem;
16
17 /// Describes how a monomorphization will be instantiated in object files.
18 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
19 pub enum InstantiationMode {
20     /// There will be exactly one instance of the given MonoItem. It will have
21     /// external linkage so that it can be linked to from other codegen units.
22     GloballyShared {
23         /// In some compilation scenarios we may decide to take functions that
24         /// are typically `LocalCopy` and instead move them to `GloballyShared`
25         /// to avoid codegenning them a bunch of times. In this situation,
26         /// however, our local copy may conflict with other crates also
27         /// inlining the same function.
28         ///
29         /// This flag indicates that this situation is occurring, and informs
30         /// symbol name calculation that some extra mangling is needed to
31         /// avoid conflicts. Note that this may eventually go away entirely if
32         /// ThinLTO enables us to *always* have a globally shared instance of a
33         /// function within one crate's compilation.
34         may_conflict: bool,
35     },
36
37     /// Each codegen unit containing a reference to the given MonoItem will
38     /// have its own private copy of the function (with internal linkage).
39     LocalCopy,
40 }
41
42 pub trait MonoItemExt<'a, 'tcx>: fmt::Debug {
43     fn as_mono_item(&self) -> &MonoItem<'tcx>;
44
45     fn is_generic_fn(&self) -> bool {
46         match *self.as_mono_item() {
47             MonoItem::Fn(ref instance) => {
48                 instance.substs.non_erasable_generics().next().is_some()
49             }
50             MonoItem::Static(..) |
51             MonoItem::GlobalAsm(..) => false,
52         }
53     }
54
55     fn symbol_name(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> ty::SymbolName {
56         match *self.as_mono_item() {
57             MonoItem::Fn(instance) => tcx.symbol_name(instance),
58             MonoItem::Static(def_id) => {
59                 tcx.symbol_name(Instance::mono(tcx, def_id))
60             }
61             MonoItem::GlobalAsm(hir_id) => {
62                 let def_id = tcx.hir().local_def_id_from_hir_id(hir_id);
63                 ty::SymbolName {
64                     name: InternedString::intern(&format!("global_asm_{:?}", def_id))
65                 }
66             }
67         }
68     }
69     fn instantiation_mode(&self,
70                           tcx: TyCtxt<'a, 'tcx, 'tcx>)
71                           -> InstantiationMode {
72         let inline_in_all_cgus =
73             tcx.sess.opts.debugging_opts.inline_in_all_cgus.unwrap_or_else(|| {
74                 tcx.sess.opts.optimize != OptLevel::No
75             }) && !tcx.sess.opts.cg.link_dead_code;
76
77         match *self.as_mono_item() {
78             MonoItem::Fn(ref instance) => {
79                 let entry_def_id = tcx.entry_fn(LOCAL_CRATE).map(|(id, _)| id);
80                 // If this function isn't inlined or otherwise has explicit
81                 // linkage, then we'll be creating a globally shared version.
82                 if self.explicit_linkage(tcx).is_some() ||
83                     !instance.def.requires_local(tcx) ||
84                     Some(instance.def_id()) == entry_def_id
85                 {
86                     return InstantiationMode::GloballyShared  { may_conflict: false }
87                 }
88
89                 // At this point we don't have explicit linkage and we're an
90                 // inlined function. If we're inlining into all CGUs then we'll
91                 // be creating a local copy per CGU
92                 if inline_in_all_cgus {
93                     return InstantiationMode::LocalCopy
94                 }
95
96                 // Finally, if this is `#[inline(always)]` we're sure to respect
97                 // that with an inline copy per CGU, but otherwise we'll be
98                 // creating one copy of this `#[inline]` function which may
99                 // conflict with upstream crates as it could be an exported
100                 // symbol.
101                 match tcx.codegen_fn_attrs(instance.def_id()).inline {
102                     InlineAttr::Always => InstantiationMode::LocalCopy,
103                     _ => {
104                         InstantiationMode::GloballyShared  { may_conflict: true }
105                     }
106                 }
107             }
108             MonoItem::Static(..) |
109             MonoItem::GlobalAsm(..) => {
110                 InstantiationMode::GloballyShared { may_conflict: false }
111             }
112         }
113     }
114
115     fn explicit_linkage(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<Linkage> {
116         let def_id = match *self.as_mono_item() {
117             MonoItem::Fn(ref instance) => instance.def_id(),
118             MonoItem::Static(def_id) => def_id,
119             MonoItem::GlobalAsm(..) => return None,
120         };
121
122         let codegen_fn_attrs = tcx.codegen_fn_attrs(def_id);
123         codegen_fn_attrs.linkage
124     }
125
126     /// Returns `true` if this instance is instantiable - whether it has no unsatisfied
127     /// predicates.
128     ///
129     /// In order to codegen an item, all of its predicates must hold, because
130     /// otherwise the item does not make sense. Type-checking ensures that
131     /// the predicates of every item that is *used by* a valid item *do*
132     /// hold, so we can rely on that.
133     ///
134     /// However, we codegen collector roots (reachable items) and functions
135     /// in vtables when they are seen, even if they are not used, and so they
136     /// might not be instantiable. For example, a programmer can define this
137     /// public function:
138     ///
139     ///     pub fn foo<'a>(s: &'a mut ()) where &'a mut (): Clone {
140     ///         <&mut () as Clone>::clone(&s);
141     ///     }
142     ///
143     /// That function can't be codegened, because the method `<&mut () as Clone>::clone`
144     /// does not exist. Luckily for us, that function can't ever be used,
145     /// because that would require for `&'a mut (): Clone` to hold, so we
146     /// can just not emit any code, or even a linker reference for it.
147     ///
148     /// Similarly, if a vtable method has such a signature, and therefore can't
149     /// be used, we can just not emit it and have a placeholder (a null pointer,
150     /// which will never be accessed) in its place.
151     fn is_instantiable(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> bool {
152         debug!("is_instantiable({:?})", self);
153         let (def_id, substs) = match *self.as_mono_item() {
154             MonoItem::Fn(ref instance) => (instance.def_id(), instance.substs),
155             MonoItem::Static(def_id) => (def_id, InternalSubsts::empty()),
156             // global asm never has predicates
157             MonoItem::GlobalAsm(..) => return true
158         };
159
160         tcx.substitute_normalize_and_test_predicates((def_id, &substs))
161     }
162
163     fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>, debug: bool) -> String {
164         return match *self.as_mono_item() {
165             MonoItem::Fn(instance) => {
166                 to_string_internal(tcx, "fn ", instance, debug)
167             },
168             MonoItem::Static(def_id) => {
169                 let instance = Instance::new(def_id, tcx.intern_substs(&[]));
170                 to_string_internal(tcx, "static ", instance, debug)
171             },
172             MonoItem::GlobalAsm(..) => {
173                 "global_asm".to_string()
174             }
175         };
176
177         fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
178                                         prefix: &str,
179                                         instance: Instance<'tcx>,
180                                         debug: bool)
181                                         -> String {
182             let mut result = String::with_capacity(32);
183             result.push_str(prefix);
184             let printer = DefPathBasedNames::new(tcx, false, false);
185             printer.push_instance_as_string(instance, &mut result, debug);
186             result
187         }
188     }
189
190     fn local_span(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<Span> {
191         match *self.as_mono_item() {
192             MonoItem::Fn(Instance { def, .. }) => {
193                 tcx.hir().as_local_hir_id(def.def_id())
194             }
195             MonoItem::Static(def_id) => {
196                 tcx.hir().as_local_hir_id(def_id)
197             }
198             MonoItem::GlobalAsm(hir_id) => {
199                 Some(hir_id)
200             }
201         }.map(|hir_id| tcx.hir().span_by_hir_id(hir_id))
202     }
203 }
204
205 impl<'a, 'tcx> MonoItemExt<'a, 'tcx> for MonoItem<'tcx> {
206     fn as_mono_item(&self) -> &MonoItem<'tcx> {
207         self
208     }
209 }
210
211 //=-----------------------------------------------------------------------------
212 // MonoItem String Keys
213 //=-----------------------------------------------------------------------------
214
215 // The code below allows for producing a unique string key for a mono item.
216 // These keys are used by the handwritten auto-tests, so they need to be
217 // predictable and human-readable.
218 //
219 // Note: A lot of this could looks very similar to what's already in `ty::print`.
220 // FIXME(eddyb) implement a custom `PrettyPrinter` for this.
221
222 /// Same as `unique_type_name()` but with the result pushed onto the given
223 /// `output` parameter.
224 pub struct DefPathBasedNames<'a, 'tcx: 'a> {
225     tcx: TyCtxt<'a, 'tcx, 'tcx>,
226     omit_disambiguators: bool,
227     omit_local_crate_name: bool,
228 }
229
230 impl<'a, 'tcx> DefPathBasedNames<'a, 'tcx> {
231     pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
232                omit_disambiguators: bool,
233                omit_local_crate_name: bool)
234                -> Self {
235         DefPathBasedNames {
236             tcx,
237             omit_disambiguators,
238             omit_local_crate_name,
239         }
240     }
241
242     // Pushes the type name of the specified type to the provided string.
243     // If `debug` is true, printing normally unprintable types is allowed
244     // (e.g. `ty::GeneratorWitness`). This parameter should only be set when
245     // this method is being used for logging purposes (e.g. with `debug!` or `info!`)
246     // When being used for codegen purposes, `debug` should be set to `false`
247     // in order to catch unexpected types that should never end up in a type name.
248     pub fn push_type_name(&self, t: Ty<'tcx>, output: &mut String, debug: bool) {
249         match t.sty {
250             ty::Bool              => output.push_str("bool"),
251             ty::Char              => output.push_str("char"),
252             ty::Str               => output.push_str("str"),
253             ty::Never             => output.push_str("!"),
254             ty::Int(ast::IntTy::Isize)    => output.push_str("isize"),
255             ty::Int(ast::IntTy::I8)    => output.push_str("i8"),
256             ty::Int(ast::IntTy::I16)   => output.push_str("i16"),
257             ty::Int(ast::IntTy::I32)   => output.push_str("i32"),
258             ty::Int(ast::IntTy::I64)   => output.push_str("i64"),
259             ty::Int(ast::IntTy::I128)   => output.push_str("i128"),
260             ty::Uint(ast::UintTy::Usize)   => output.push_str("usize"),
261             ty::Uint(ast::UintTy::U8)   => output.push_str("u8"),
262             ty::Uint(ast::UintTy::U16)  => output.push_str("u16"),
263             ty::Uint(ast::UintTy::U32)  => output.push_str("u32"),
264             ty::Uint(ast::UintTy::U64)  => output.push_str("u64"),
265             ty::Uint(ast::UintTy::U128)  => output.push_str("u128"),
266             ty::Float(ast::FloatTy::F32) => output.push_str("f32"),
267             ty::Float(ast::FloatTy::F64) => output.push_str("f64"),
268             ty::Adt(adt_def, substs) => {
269                 self.push_def_path(adt_def.did, output);
270                 self.push_generic_params(substs, iter::empty(), output, debug);
271             },
272             ty::Tuple(component_types) => {
273                 output.push('(');
274                 for &component_type in component_types {
275                     self.push_type_name(component_type.expect_ty(), output, debug);
276                     output.push_str(", ");
277                 }
278                 if !component_types.is_empty() {
279                     output.pop();
280                     output.pop();
281                 }
282                 output.push(')');
283             },
284             ty::RawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
285                 output.push('*');
286                 match mutbl {
287                     hir::MutImmutable => output.push_str("const "),
288                     hir::MutMutable => output.push_str("mut "),
289                 }
290
291                 self.push_type_name(inner_type, output, debug);
292             },
293             ty::Ref(_, inner_type, mutbl) => {
294                 output.push('&');
295                 if mutbl == hir::MutMutable {
296                     output.push_str("mut ");
297                 }
298
299                 self.push_type_name(inner_type, output, debug);
300             },
301             ty::Array(inner_type, len) => {
302                 output.push('[');
303                 self.push_type_name(inner_type, output, debug);
304                 write!(output, "; {}", len.unwrap_usize(self.tcx)).unwrap();
305                 output.push(']');
306             },
307             ty::Slice(inner_type) => {
308                 output.push('[');
309                 self.push_type_name(inner_type, output, debug);
310                 output.push(']');
311             },
312             ty::Dynamic(ref trait_data, ..) => {
313                 if let Some(principal) = trait_data.principal() {
314                     self.push_def_path(principal.def_id(), output);
315                     self.push_generic_params(
316                         principal.skip_binder().substs,
317                         trait_data.projection_bounds(),
318                         output,
319                         debug
320                     );
321                 } else {
322                     output.push_str("dyn '_");
323                 }
324             },
325             ty::Foreign(did) => self.push_def_path(did, output),
326             ty::FnDef(..) |
327             ty::FnPtr(_) => {
328                 let sig = t.fn_sig(self.tcx);
329                 if sig.unsafety() == hir::Unsafety::Unsafe {
330                     output.push_str("unsafe ");
331                 }
332
333                 let abi = sig.abi();
334                 if abi != ::rustc_target::spec::abi::Abi::Rust {
335                     output.push_str("extern \"");
336                     output.push_str(abi.name());
337                     output.push_str("\" ");
338                 }
339
340                 output.push_str("fn(");
341
342                 let sig = self.tcx.normalize_erasing_late_bound_regions(
343                     ty::ParamEnv::reveal_all(),
344                     &sig,
345                 );
346
347                 if !sig.inputs().is_empty() {
348                     for &parameter_type in sig.inputs() {
349                         self.push_type_name(parameter_type, output, debug);
350                         output.push_str(", ");
351                     }
352                     output.pop();
353                     output.pop();
354                 }
355
356                 if sig.c_variadic {
357                     if !sig.inputs().is_empty() {
358                         output.push_str(", ...");
359                     } else {
360                         output.push_str("...");
361                     }
362                 }
363
364                 output.push(')');
365
366                 if !sig.output().is_unit() {
367                     output.push_str(" -> ");
368                     self.push_type_name(sig.output(), output, debug);
369                 }
370             },
371             ty::Generator(def_id, GeneratorSubsts { ref substs }, _) |
372             ty::Closure(def_id, ClosureSubsts { ref substs }) => {
373                 self.push_def_path(def_id, output);
374                 let generics = self.tcx.generics_of(self.tcx.closure_base_def_id(def_id));
375                 let substs = substs.truncate_to(self.tcx, generics);
376                 self.push_generic_params(substs, iter::empty(), output, debug);
377             }
378             ty::Error |
379             ty::Bound(..) |
380             ty::Infer(_) |
381             ty::Placeholder(..) |
382             ty::UnnormalizedProjection(..) |
383             ty::Projection(..) |
384             ty::Param(_) |
385             ty::GeneratorWitness(_) |
386             ty::Opaque(..) => {
387                 if debug {
388                     output.push_str(&format!("`{:?}`", t));
389                 } else {
390                     bug!(
391                         "DefPathBasedNames: trying to create type name for unexpected type: {:?}",
392                         t,
393                     );
394                 }
395             }
396         }
397     }
398
399     // Pushes the the name of the specified const to the provided string.
400     // If `debug` is true, usually-unprintable consts (such as `Infer`) will be printed,
401     // as well as the unprintable types of constants (see `push_type_name` for more details).
402     pub fn push_const_name(&self, c: &Const<'tcx>, output: &mut String, debug: bool) {
403         match c.val {
404             ConstValue::Scalar(..) | ConstValue::Slice(..) | ConstValue::ByRef(..) => {
405                 // FIXME(const_generics): we could probably do a better job here.
406                 write!(output, "{:?}", c).unwrap()
407             }
408             _ => {
409                 if debug {
410                     write!(output, "{:?}", c).unwrap()
411                 } else {
412                     bug!(
413                         "DefPathBasedNames: trying to create const name for unexpected const: {:?}",
414                         c,
415                     );
416                 }
417             }
418         }
419         output.push_str(": ");
420         self.push_type_name(c.ty, output, debug);
421     }
422
423     pub fn push_def_path(&self,
424                          def_id: DefId,
425                          output: &mut String) {
426         let def_path = self.tcx.def_path(def_id);
427
428         // some_crate::
429         if !(self.omit_local_crate_name && def_id.is_local()) {
430             output.push_str(&self.tcx.crate_name(def_path.krate).as_str());
431             output.push_str("::");
432         }
433
434         // foo::bar::ItemName::
435         for part in self.tcx.def_path(def_id).data {
436             if self.omit_disambiguators {
437                 write!(output, "{}::", part.data.as_interned_str()).unwrap();
438             } else {
439                 write!(output, "{}[{}]::",
440                        part.data.as_interned_str(),
441                        part.disambiguator).unwrap();
442             }
443         }
444
445         // remove final "::"
446         output.pop();
447         output.pop();
448     }
449
450     fn push_generic_params<I>(
451         &self,
452         substs: SubstsRef<'tcx>,
453         projections: I,
454         output: &mut String,
455         debug: bool,
456     ) where I: Iterator<Item=ty::PolyExistentialProjection<'tcx>> {
457         let mut projections = projections.peekable();
458         if substs.non_erasable_generics().next().is_none() && projections.peek().is_none() {
459             return;
460         }
461
462         output.push('<');
463
464         for type_parameter in substs.types() {
465             self.push_type_name(type_parameter, output, debug);
466             output.push_str(", ");
467         }
468
469         for projection in projections {
470             let projection = projection.skip_binder();
471             let name = &self.tcx.associated_item(projection.item_def_id).ident.as_str();
472             output.push_str(name);
473             output.push_str("=");
474             self.push_type_name(projection.ty, output, debug);
475             output.push_str(", ");
476         }
477
478         for const_parameter in substs.consts() {
479             self.push_const_name(const_parameter, output, debug);
480             output.push_str(", ");
481         }
482
483         output.pop();
484         output.pop();
485
486         output.push('>');
487     }
488
489     pub fn push_instance_as_string(&self,
490                                    instance: Instance<'tcx>,
491                                    output: &mut String,
492                                    debug: bool) {
493         self.push_def_path(instance.def_id(), output);
494         self.push_generic_params(instance.substs, iter::empty(), output, debug);
495     }
496 }