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