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