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