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