]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans_item.rs
avoid translating roots with predicates that do not hold
[rust.git] / src / librustc_trans / trans_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 asm;
18 use attributes;
19 use base;
20 use consts;
21 use context::CrateContext;
22 use common;
23 use declare;
24 use llvm;
25 use monomorphize::Instance;
26 use rustc::hir;
27 use rustc::hir::def_id::DefId;
28 use rustc::traits;
29 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
30 use rustc::ty::subst::{Subst, Substs};
31 use syntax::ast::{self, NodeId};
32 use syntax::attr;
33 use syntax_pos::Span;
34 use syntax_pos::symbol::Symbol;
35 use type_of;
36 use std::fmt::Write;
37 use std::iter;
38
39 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
40 pub enum TransItem<'tcx> {
41     Fn(Instance<'tcx>),
42     Static(NodeId),
43     GlobalAsm(NodeId),
44 }
45
46 /// Describes how a translation item will be instantiated in object files.
47 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
48 pub enum InstantiationMode {
49     /// There will be exactly one instance of the given TransItem. It will have
50     /// external linkage so that it can be linked to from other codegen units.
51     GloballyShared,
52
53     /// Each codegen unit containing a reference to the given TransItem will
54     /// have its own private copy of the function (with internal linkage).
55     LocalCopy,
56 }
57
58 impl<'a, 'tcx> TransItem<'tcx> {
59
60     pub fn define(&self, ccx: &CrateContext<'a, 'tcx>) {
61         debug!("BEGIN IMPLEMENTING '{} ({})' in cgu {}",
62                   self.to_string(ccx.tcx()),
63                   self.to_raw_string(),
64                   ccx.codegen_unit().name());
65
66         match *self {
67             TransItem::Static(node_id) => {
68                 let tcx = ccx.tcx();
69                 let item = tcx.hir.expect_item(node_id);
70                 if let hir::ItemStatic(_, m, _) = item.node {
71                     match consts::trans_static(&ccx, m, item.id, &item.attrs) {
72                         Ok(_) => { /* Cool, everything's alright. */ },
73                         Err(err) => {
74                             err.report(tcx, item.span, "static");
75                         }
76                     };
77                 } else {
78                     span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
79                 }
80             }
81             TransItem::GlobalAsm(node_id) => {
82                 let item = ccx.tcx().hir.expect_item(node_id);
83                 if let hir::ItemGlobalAsm(ref ga) = item.node {
84                     asm::trans_global_asm(ccx, ga);
85                 } else {
86                     span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
87                 }
88             }
89             TransItem::Fn(instance) => {
90                 base::trans_instance(&ccx, instance);
91             }
92         }
93
94         debug!("END IMPLEMENTING '{} ({})' in cgu {}",
95                self.to_string(ccx.tcx()),
96                self.to_raw_string(),
97                ccx.codegen_unit().name());
98     }
99
100     pub fn predefine(&self,
101                      ccx: &CrateContext<'a, 'tcx>,
102                      linkage: llvm::Linkage) {
103         debug!("BEGIN PREDEFINING '{} ({})' in cgu {}",
104                self.to_string(ccx.tcx()),
105                self.to_raw_string(),
106                ccx.codegen_unit().name());
107
108         let symbol_name = self.symbol_name(ccx.tcx());
109
110         debug!("symbol {}", &symbol_name);
111
112         match *self {
113             TransItem::Static(node_id) => {
114                 TransItem::predefine_static(ccx, node_id, linkage, &symbol_name);
115             }
116             TransItem::Fn(instance) => {
117                 TransItem::predefine_fn(ccx, instance, linkage, &symbol_name);
118             }
119             TransItem::GlobalAsm(..) => {}
120         }
121
122         debug!("END PREDEFINING '{} ({})' in cgu {}",
123                self.to_string(ccx.tcx()),
124                self.to_raw_string(),
125                ccx.codegen_unit().name());
126     }
127
128     fn predefine_static(ccx: &CrateContext<'a, 'tcx>,
129                         node_id: ast::NodeId,
130                         linkage: llvm::Linkage,
131                         symbol_name: &str) {
132         let def_id = ccx.tcx().hir.local_def_id(node_id);
133         let instance = Instance::mono(ccx.tcx(), def_id);
134         let ty = common::instance_ty(ccx.shared(), &instance);
135         let llty = type_of::type_of(ccx, ty);
136
137         let g = declare::define_global(ccx, symbol_name, llty).unwrap_or_else(|| {
138             ccx.sess().span_fatal(ccx.tcx().hir.span(node_id),
139                 &format!("symbol `{}` is already defined", symbol_name))
140         });
141
142         unsafe { llvm::LLVMRustSetLinkage(g, linkage) };
143
144         ccx.instances().borrow_mut().insert(instance, g);
145         ccx.statics().borrow_mut().insert(g, def_id);
146     }
147
148     fn predefine_fn(ccx: &CrateContext<'a, 'tcx>,
149                     instance: Instance<'tcx>,
150                     linkage: llvm::Linkage,
151                     symbol_name: &str) {
152         assert!(!instance.substs.needs_infer() &&
153                 !instance.substs.has_param_types());
154
155         let mono_ty = common::instance_ty(ccx.shared(), &instance);
156         let attrs = instance.def.attrs(ccx.tcx());
157         let lldecl = declare::declare_fn(ccx, symbol_name, mono_ty);
158         unsafe { llvm::LLVMRustSetLinkage(lldecl, linkage) };
159         base::set_link_section(ccx, lldecl, &attrs);
160         if linkage == llvm::Linkage::LinkOnceODRLinkage ||
161             linkage == llvm::Linkage::WeakODRLinkage {
162             llvm::SetUniqueComdat(ccx.llmod(), lldecl);
163         }
164
165         debug!("predefine_fn: mono_ty = {:?} instance = {:?}", mono_ty, instance);
166         if common::is_inline_instance(ccx.tcx(), &instance) {
167             attributes::inline(lldecl, attributes::InlineAttr::Hint);
168         }
169         attributes::from_fn_attrs(ccx, &attrs, lldecl);
170
171         ccx.instances().borrow_mut().insert(instance, lldecl);
172     }
173
174     pub fn symbol_name(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> ty::SymbolName {
175         match *self {
176             TransItem::Fn(instance) => tcx.symbol_name(instance),
177             TransItem::Static(node_id) => {
178                 let def_id = tcx.hir.local_def_id(node_id);
179                 tcx.symbol_name(Instance::mono(tcx, def_id))
180             }
181             TransItem::GlobalAsm(node_id) => {
182                 let def_id = tcx.hir.local_def_id(node_id);
183                 ty::SymbolName {
184                     name: Symbol::intern(&format!("global_asm_{:?}", def_id)).as_str()
185                 }
186             }
187         }
188     }
189
190     pub fn local_span(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<Span> {
191         match *self {
192             TransItem::Fn(Instance { def, .. }) => {
193                 tcx.hir.as_local_node_id(def.def_id())
194             }
195             TransItem::Static(node_id) |
196             TransItem::GlobalAsm(node_id) => {
197                 Some(node_id)
198             }
199         }.map(|node_id| tcx.hir.span(node_id))
200     }
201
202     pub fn instantiation_mode(&self,
203                               tcx: TyCtxt<'a, 'tcx, 'tcx>)
204                               -> InstantiationMode {
205         match *self {
206             TransItem::Fn(ref instance) => {
207                 if self.explicit_linkage(tcx).is_none() &&
208                     common::requests_inline(tcx, instance)
209                 {
210                     InstantiationMode::LocalCopy
211                 } else {
212                     InstantiationMode::GloballyShared
213                 }
214             }
215             TransItem::Static(..) => InstantiationMode::GloballyShared,
216             TransItem::GlobalAsm(..) => InstantiationMode::GloballyShared,
217         }
218     }
219
220     pub fn is_generic_fn(&self) -> bool {
221         match *self {
222             TransItem::Fn(ref instance) => {
223                 instance.substs.types().next().is_some()
224             }
225             TransItem::Static(..) |
226             TransItem::GlobalAsm(..) => false,
227         }
228     }
229
230     pub fn explicit_linkage(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<llvm::Linkage> {
231         let def_id = match *self {
232             TransItem::Fn(ref instance) => instance.def_id(),
233             TransItem::Static(node_id) => tcx.hir.local_def_id(node_id),
234             TransItem::GlobalAsm(..) => return None,
235         };
236
237         let attributes = tcx.get_attrs(def_id);
238         if let Some(name) = attr::first_attr_value_str_by_name(&attributes, "linkage") {
239             if let Some(linkage) = base::llvm_linkage_by_name(&name.as_str()) {
240                 Some(linkage)
241             } else {
242                 let span = tcx.hir.span_if_local(def_id);
243                 if let Some(span) = span {
244                     tcx.sess.span_fatal(span, "invalid linkage specified")
245                 } else {
246                     tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
247                 }
248             }
249         } else {
250             None
251         }
252     }
253
254     /// Returns whether this instance is instantiable - whether it has no unsatisfied
255     /// predicates.
256     pub fn is_instantiable(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> bool {
257         debug!("is_instantiable({:?})", self);
258         let (def_id, substs) = match *self {
259             TransItem::Fn(ref instance) => (instance.def_id(), instance.substs),
260             TransItem::Static(node_id) => (tcx.hir.local_def_id(node_id), Substs::empty()),
261             // global asm never has predicates
262             TransItem::GlobalAsm(..) => return true
263         };
264
265         let predicates = tcx.predicates_of(def_id).predicates.subst(tcx, substs);
266         traits::normalize_and_test_predicates(tcx, predicates)
267     }
268
269     pub fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> String {
270         let hir_map = &tcx.hir;
271
272         return match *self {
273             TransItem::Fn(instance) => {
274                 to_string_internal(tcx, "fn ", instance)
275             },
276             TransItem::Static(node_id) => {
277                 let def_id = hir_map.local_def_id(node_id);
278                 let instance = Instance::new(def_id, tcx.intern_substs(&[]));
279                 to_string_internal(tcx, "static ", instance)
280             },
281             TransItem::GlobalAsm(..) => {
282                 "global_asm".to_string()
283             }
284         };
285
286         fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
287                                         prefix: &str,
288                                         instance: Instance<'tcx>)
289                                         -> String {
290             let mut result = String::with_capacity(32);
291             result.push_str(prefix);
292             let printer = DefPathBasedNames::new(tcx, false, false);
293             printer.push_instance_as_string(instance, &mut result);
294             result
295         }
296     }
297
298     pub fn to_raw_string(&self) -> String {
299         match *self {
300             TransItem::Fn(instance) => {
301                 format!("Fn({:?}, {})",
302                          instance.def,
303                          instance.substs.as_ptr() as usize)
304             }
305             TransItem::Static(id) => {
306                 format!("Static({:?})", id)
307             }
308             TransItem::GlobalAsm(id) => {
309                 format!("GlobalAsm({:?})", id)
310             }
311         }
312     }
313 }
314
315
316 //=-----------------------------------------------------------------------------
317 // TransItem String Keys
318 //=-----------------------------------------------------------------------------
319
320 // The code below allows for producing a unique string key for a trans item.
321 // These keys are used by the handwritten auto-tests, so they need to be
322 // predictable and human-readable.
323 //
324 // Note: A lot of this could looks very similar to what's already in the
325 //       ppaux module. It would be good to refactor things so we only have one
326 //       parameterizable implementation for printing types.
327
328 /// Same as `unique_type_name()` but with the result pushed onto the given
329 /// `output` parameter.
330 pub struct DefPathBasedNames<'a, 'tcx: 'a> {
331     tcx: TyCtxt<'a, 'tcx, 'tcx>,
332     omit_disambiguators: bool,
333     omit_local_crate_name: bool,
334 }
335
336 impl<'a, 'tcx> DefPathBasedNames<'a, 'tcx> {
337     pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
338                omit_disambiguators: bool,
339                omit_local_crate_name: bool)
340                -> Self {
341         DefPathBasedNames {
342             tcx: tcx,
343             omit_disambiguators: omit_disambiguators,
344             omit_local_crate_name: omit_local_crate_name,
345         }
346     }
347
348     pub fn push_type_name(&self, t: Ty<'tcx>, output: &mut String) {
349         match t.sty {
350             ty::TyBool              => output.push_str("bool"),
351             ty::TyChar              => output.push_str("char"),
352             ty::TyStr               => output.push_str("str"),
353             ty::TyNever             => output.push_str("!"),
354             ty::TyInt(ast::IntTy::Is)    => output.push_str("isize"),
355             ty::TyInt(ast::IntTy::I8)    => output.push_str("i8"),
356             ty::TyInt(ast::IntTy::I16)   => output.push_str("i16"),
357             ty::TyInt(ast::IntTy::I32)   => output.push_str("i32"),
358             ty::TyInt(ast::IntTy::I64)   => output.push_str("i64"),
359             ty::TyInt(ast::IntTy::I128)   => output.push_str("i128"),
360             ty::TyUint(ast::UintTy::Us)   => output.push_str("usize"),
361             ty::TyUint(ast::UintTy::U8)   => output.push_str("u8"),
362             ty::TyUint(ast::UintTy::U16)  => output.push_str("u16"),
363             ty::TyUint(ast::UintTy::U32)  => output.push_str("u32"),
364             ty::TyUint(ast::UintTy::U64)  => output.push_str("u64"),
365             ty::TyUint(ast::UintTy::U128)  => output.push_str("u128"),
366             ty::TyFloat(ast::FloatTy::F32) => output.push_str("f32"),
367             ty::TyFloat(ast::FloatTy::F64) => output.push_str("f64"),
368             ty::TyAdt(adt_def, substs) => {
369                 self.push_def_path(adt_def.did, output);
370                 self.push_type_params(substs, iter::empty(), output);
371             },
372             ty::TyTuple(component_types, _) => {
373                 output.push('(');
374                 for &component_type in component_types {
375                     self.push_type_name(component_type, output);
376                     output.push_str(", ");
377                 }
378                 if !component_types.is_empty() {
379                     output.pop();
380                     output.pop();
381                 }
382                 output.push(')');
383             },
384             ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
385                 output.push('*');
386                 match mutbl {
387                     hir::MutImmutable => output.push_str("const "),
388                     hir::MutMutable => output.push_str("mut "),
389                 }
390
391                 self.push_type_name(inner_type, output);
392             },
393             ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
394                 output.push('&');
395                 if mutbl == hir::MutMutable {
396                     output.push_str("mut ");
397                 }
398
399                 self.push_type_name(inner_type, output);
400             },
401             ty::TyArray(inner_type, len) => {
402                 output.push('[');
403                 self.push_type_name(inner_type, output);
404                 write!(output, "; {}", len).unwrap();
405                 output.push(']');
406             },
407             ty::TySlice(inner_type) => {
408                 output.push('[');
409                 self.push_type_name(inner_type, output);
410                 output.push(']');
411             },
412             ty::TyDynamic(ref trait_data, ..) => {
413                 if let Some(principal) = trait_data.principal() {
414                     self.push_def_path(principal.def_id(), output);
415                     self.push_type_params(principal.skip_binder().substs,
416                         trait_data.projection_bounds(),
417                         output);
418                 }
419             },
420             ty::TyFnDef(.., sig) |
421             ty::TyFnPtr(sig) => {
422                 if sig.unsafety() == hir::Unsafety::Unsafe {
423                     output.push_str("unsafe ");
424                 }
425
426                 let abi = sig.abi();
427                 if abi != ::abi::Abi::Rust {
428                     output.push_str("extern \"");
429                     output.push_str(abi.name());
430                     output.push_str("\" ");
431                 }
432
433                 output.push_str("fn(");
434
435                 let sig = self.tcx.erase_late_bound_regions_and_normalize(&sig);
436
437                 if !sig.inputs().is_empty() {
438                     for &parameter_type in sig.inputs() {
439                         self.push_type_name(parameter_type, output);
440                         output.push_str(", ");
441                     }
442                     output.pop();
443                     output.pop();
444                 }
445
446                 if sig.variadic {
447                     if !sig.inputs().is_empty() {
448                         output.push_str(", ...");
449                     } else {
450                         output.push_str("...");
451                     }
452                 }
453
454                 output.push(')');
455
456                 if !sig.output().is_nil() {
457                     output.push_str(" -> ");
458                     self.push_type_name(sig.output(), output);
459                 }
460             },
461             ty::TyClosure(def_id, ref closure_substs) => {
462                 self.push_def_path(def_id, output);
463                 let generics = self.tcx.generics_of(self.tcx.closure_base_def_id(def_id));
464                 let substs = closure_substs.substs.truncate_to(self.tcx, generics);
465                 self.push_type_params(substs, iter::empty(), output);
466             }
467             ty::TyError |
468             ty::TyInfer(_) |
469             ty::TyProjection(..) |
470             ty::TyParam(_) |
471             ty::TyAnon(..) => {
472                 bug!("DefPathBasedNames: Trying to create type name for \
473                                          unexpected type: {:?}", t);
474             }
475         }
476     }
477
478     pub fn push_def_path(&self,
479                          def_id: DefId,
480                          output: &mut String) {
481         let def_path = self.tcx.def_path(def_id);
482
483         // some_crate::
484         if !(self.omit_local_crate_name && def_id.is_local()) {
485             output.push_str(&self.tcx.crate_name(def_path.krate).as_str());
486             output.push_str("::");
487         }
488
489         // foo::bar::ItemName::
490         for part in self.tcx.def_path(def_id).data {
491             if self.omit_disambiguators {
492                 write!(output, "{}::", part.data.as_interned_str()).unwrap();
493             } else {
494                 write!(output, "{}[{}]::",
495                        part.data.as_interned_str(),
496                        part.disambiguator).unwrap();
497             }
498         }
499
500         // remove final "::"
501         output.pop();
502         output.pop();
503     }
504
505     fn push_type_params<I>(&self,
506                             substs: &Substs<'tcx>,
507                             projections: I,
508                             output: &mut String)
509         where I: Iterator<Item=ty::PolyExistentialProjection<'tcx>>
510     {
511         let mut projections = projections.peekable();
512         if substs.types().next().is_none() && projections.peek().is_none() {
513             return;
514         }
515
516         output.push('<');
517
518         for type_parameter in substs.types() {
519             self.push_type_name(type_parameter, output);
520             output.push_str(", ");
521         }
522
523         for projection in projections {
524             let projection = projection.skip_binder();
525             let name = &projection.item_name.as_str();
526             output.push_str(name);
527             output.push_str("=");
528             self.push_type_name(projection.ty, output);
529             output.push_str(", ");
530         }
531
532         output.pop();
533         output.pop();
534
535         output.push('>');
536     }
537
538     pub fn push_instance_as_string(&self,
539                                    instance: Instance<'tcx>,
540                                    output: &mut String) {
541         self.push_def_path(instance.def_id(), output);
542         self.push_type_params(instance.substs, iter::empty(), output);
543     }
544 }