]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans_item.rs
Rollup merge of #40142 - MajorBreakfast:patch-4, r=steveklabnik
[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::{self, 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 = ccx.tcx().item_type(def_id);
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 item_ty = ccx.tcx().item_type(instance.def);
172         let item_ty = ccx.tcx().erase_regions(&item_ty);
173         let mono_ty = monomorphize::apply_param_substs(ccx.shared(), instance.substs, &item_ty);
174
175         let attrs = ccx.tcx().get_attrs(instance.def);
176         let lldecl = declare::declare_fn(ccx, symbol_name, mono_ty);
177         unsafe { llvm::LLVMRustSetLinkage(lldecl, linkage) };
178         base::set_link_section(ccx, lldecl, &attrs);
179         if linkage == llvm::Linkage::LinkOnceODRLinkage ||
180             linkage == llvm::Linkage::WeakODRLinkage {
181             llvm::SetUniqueComdat(ccx.llmod(), lldecl);
182         }
183
184         if let ty::TyClosure(..) = mono_ty.sty {
185             // set an inline hint for all closures
186             attributes::inline(lldecl, attributes::InlineAttr::Hint);
187         }
188
189         attributes::from_fn_attrs(ccx, &attrs, lldecl);
190
191         ccx.instances().borrow_mut().insert(instance, lldecl);
192     }
193
194     fn predefine_drop_glue(ccx: &CrateContext<'a, 'tcx>,
195                            dg: glue::DropGlueKind<'tcx>,
196                            linkage: llvm::Linkage,
197                            symbol_name: &str) {
198         let tcx = ccx.tcx();
199         assert_eq!(dg.ty(), glue::get_drop_glue_type(ccx.shared(), dg.ty()));
200         let t = dg.ty();
201
202         let sig = tcx.mk_fn_sig(
203             iter::once(tcx.mk_mut_ptr(t)),
204             tcx.mk_nil(),
205             false,
206             hir::Unsafety::Normal,
207             Abi::Rust
208         );
209
210         debug!("predefine_drop_glue: sig={}", sig);
211
212         let fn_ty = FnType::new(ccx, sig, &[]);
213         let llfnty = fn_ty.llvm_type(ccx);
214
215         assert!(declare::get_defined_value(ccx, symbol_name).is_none());
216         let llfn = declare::declare_cfn(ccx, symbol_name, llfnty);
217         unsafe { llvm::LLVMRustSetLinkage(llfn, linkage) };
218         if linkage == llvm::Linkage::LinkOnceODRLinkage ||
219            linkage == llvm::Linkage::WeakODRLinkage {
220             llvm::SetUniqueComdat(ccx.llmod(), llfn);
221         }
222         attributes::set_frame_pointer_elimination(ccx, llfn);
223         ccx.drop_glues().borrow_mut().insert(dg, (llfn, fn_ty));
224     }
225
226     pub fn compute_symbol_name(&self,
227                                scx: &SharedCrateContext<'a, 'tcx>) -> String {
228         match *self {
229             TransItem::Fn(instance) => instance.symbol_name(scx),
230             TransItem::Static(node_id) => {
231                 let def_id = scx.tcx().hir.local_def_id(node_id);
232                 Instance::mono(scx, def_id).symbol_name(scx)
233             }
234             TransItem::DropGlue(dg) => {
235                 let prefix = match dg {
236                     DropGlueKind::Ty(_) => "drop",
237                     DropGlueKind::TyContents(_) => "drop_contents",
238                 };
239                 symbol_names::exported_name_from_type_and_prefix(scx, dg.ty(), prefix)
240             }
241         }
242     }
243
244     pub fn is_from_extern_crate(&self) -> bool {
245         match *self {
246             TransItem::Fn(ref instance) => !instance.def.is_local(),
247             TransItem::DropGlue(..) |
248             TransItem::Static(..)   => false,
249         }
250     }
251
252     pub fn instantiation_mode(&self,
253                               tcx: TyCtxt<'a, 'tcx, 'tcx>)
254                               -> InstantiationMode {
255         match *self {
256             TransItem::Fn(ref instance) => {
257                 if self.explicit_linkage(tcx).is_none() &&
258                    (common::is_closure(tcx, instance.def) ||
259                     attr::requests_inline(&tcx.get_attrs(instance.def)[..])) {
260                     InstantiationMode::LocalCopy
261                 } else {
262                     InstantiationMode::GloballyShared
263                 }
264             }
265             TransItem::DropGlue(..) => InstantiationMode::LocalCopy,
266             TransItem::Static(..) => InstantiationMode::GloballyShared,
267         }
268     }
269
270     pub fn is_generic_fn(&self) -> bool {
271         match *self {
272             TransItem::Fn(ref instance) => {
273                 instance.substs.types().next().is_some()
274             }
275             TransItem::DropGlue(..) |
276             TransItem::Static(..)   => false,
277         }
278     }
279
280     pub fn explicit_linkage(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<llvm::Linkage> {
281         let def_id = match *self {
282             TransItem::Fn(ref instance) => instance.def,
283             TransItem::Static(node_id) => tcx.hir.local_def_id(node_id),
284             TransItem::DropGlue(..) => return None,
285         };
286
287         let attributes = tcx.get_attrs(def_id);
288         if let Some(name) = attr::first_attr_value_str_by_name(&attributes, "linkage") {
289             if let Some(linkage) = base::llvm_linkage_by_name(&name.as_str()) {
290                 Some(linkage)
291             } else {
292                 let span = tcx.hir.span_if_local(def_id);
293                 if let Some(span) = span {
294                     tcx.sess.span_fatal(span, "invalid linkage specified")
295                 } else {
296                     tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
297                 }
298             }
299         } else {
300             None
301         }
302     }
303
304     pub fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> String {
305         let hir_map = &tcx.hir;
306
307         return match *self {
308             TransItem::DropGlue(dg) => {
309                 let mut s = String::with_capacity(32);
310                 match dg {
311                     DropGlueKind::Ty(_) => s.push_str("drop-glue "),
312                     DropGlueKind::TyContents(_) => s.push_str("drop-glue-contents "),
313                 };
314                 let printer = DefPathBasedNames::new(tcx, false, false);
315                 printer.push_type_name(dg.ty(), &mut s);
316                 s
317             }
318             TransItem::Fn(instance) => {
319                 to_string_internal(tcx, "fn ", instance)
320             },
321             TransItem::Static(node_id) => {
322                 let def_id = hir_map.local_def_id(node_id);
323                 let instance = Instance::new(def_id, tcx.intern_substs(&[]));
324                 to_string_internal(tcx, "static ", instance)
325             },
326         };
327
328         fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
329                                         prefix: &str,
330                                         instance: Instance<'tcx>)
331                                         -> String {
332             let mut result = String::with_capacity(32);
333             result.push_str(prefix);
334             let printer = DefPathBasedNames::new(tcx, false, false);
335             printer.push_instance_as_string(instance, &mut result);
336             result
337         }
338     }
339
340     pub fn to_raw_string(&self) -> String {
341         match *self {
342             TransItem::DropGlue(dg) => {
343                 let prefix = match dg {
344                     DropGlueKind::Ty(_) => "Ty",
345                     DropGlueKind::TyContents(_) => "TyContents",
346                 };
347                 format!("DropGlue({}: {})", prefix, dg.ty() as *const _ as usize)
348             }
349             TransItem::Fn(instance) => {
350                 format!("Fn({:?}, {})",
351                          instance.def,
352                          instance.substs.as_ptr() as usize)
353             }
354             TransItem::Static(id) => {
355                 format!("Static({:?})", id)
356             }
357         }
358     }
359 }
360
361
362 //=-----------------------------------------------------------------------------
363 // TransItem String Keys
364 //=-----------------------------------------------------------------------------
365
366 // The code below allows for producing a unique string key for a trans item.
367 // These keys are used by the handwritten auto-tests, so they need to be
368 // predictable and human-readable.
369 //
370 // Note: A lot of this could looks very similar to what's already in the
371 //       ppaux module. It would be good to refactor things so we only have one
372 //       parameterizable implementation for printing types.
373
374 /// Same as `unique_type_name()` but with the result pushed onto the given
375 /// `output` parameter.
376 pub struct DefPathBasedNames<'a, 'tcx: 'a> {
377     tcx: TyCtxt<'a, 'tcx, 'tcx>,
378     omit_disambiguators: bool,
379     omit_local_crate_name: bool,
380 }
381
382 impl<'a, 'tcx> DefPathBasedNames<'a, 'tcx> {
383     pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
384                omit_disambiguators: bool,
385                omit_local_crate_name: bool)
386                -> Self {
387         DefPathBasedNames {
388             tcx: tcx,
389             omit_disambiguators: omit_disambiguators,
390             omit_local_crate_name: omit_local_crate_name,
391         }
392     }
393
394     pub fn push_type_name(&self, t: Ty<'tcx>, output: &mut String) {
395         match t.sty {
396             ty::TyBool              => output.push_str("bool"),
397             ty::TyChar              => output.push_str("char"),
398             ty::TyStr               => output.push_str("str"),
399             ty::TyNever             => output.push_str("!"),
400             ty::TyInt(ast::IntTy::Is)    => output.push_str("isize"),
401             ty::TyInt(ast::IntTy::I8)    => output.push_str("i8"),
402             ty::TyInt(ast::IntTy::I16)   => output.push_str("i16"),
403             ty::TyInt(ast::IntTy::I32)   => output.push_str("i32"),
404             ty::TyInt(ast::IntTy::I64)   => output.push_str("i64"),
405             ty::TyInt(ast::IntTy::I128)   => output.push_str("i128"),
406             ty::TyUint(ast::UintTy::Us)   => output.push_str("usize"),
407             ty::TyUint(ast::UintTy::U8)   => output.push_str("u8"),
408             ty::TyUint(ast::UintTy::U16)  => output.push_str("u16"),
409             ty::TyUint(ast::UintTy::U32)  => output.push_str("u32"),
410             ty::TyUint(ast::UintTy::U64)  => output.push_str("u64"),
411             ty::TyUint(ast::UintTy::U128)  => output.push_str("u128"),
412             ty::TyFloat(ast::FloatTy::F32) => output.push_str("f32"),
413             ty::TyFloat(ast::FloatTy::F64) => output.push_str("f64"),
414             ty::TyAdt(adt_def, substs) => {
415                 self.push_def_path(adt_def.did, output);
416                 self.push_type_params(substs, iter::empty(), output);
417             },
418             ty::TyTuple(component_types, _) => {
419                 output.push('(');
420                 for &component_type in component_types {
421                     self.push_type_name(component_type, output);
422                     output.push_str(", ");
423                 }
424                 if !component_types.is_empty() {
425                     output.pop();
426                     output.pop();
427                 }
428                 output.push(')');
429             },
430             ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
431                 output.push('*');
432                 match mutbl {
433                     hir::MutImmutable => output.push_str("const "),
434                     hir::MutMutable => output.push_str("mut "),
435                 }
436
437                 self.push_type_name(inner_type, output);
438             },
439             ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
440                 output.push('&');
441                 if mutbl == hir::MutMutable {
442                     output.push_str("mut ");
443                 }
444
445                 self.push_type_name(inner_type, output);
446             },
447             ty::TyArray(inner_type, len) => {
448                 output.push('[');
449                 self.push_type_name(inner_type, output);
450                 write!(output, "; {}", len).unwrap();
451                 output.push(']');
452             },
453             ty::TySlice(inner_type) => {
454                 output.push('[');
455                 self.push_type_name(inner_type, output);
456                 output.push(']');
457             },
458             ty::TyDynamic(ref trait_data, ..) => {
459                 if let Some(principal) = trait_data.principal() {
460                     self.push_def_path(principal.def_id(), output);
461                     self.push_type_params(principal.skip_binder().substs,
462                         trait_data.projection_bounds(),
463                         output);
464                 }
465             },
466             ty::TyFnDef(.., sig) |
467             ty::TyFnPtr(sig) => {
468                 if sig.unsafety() == hir::Unsafety::Unsafe {
469                     output.push_str("unsafe ");
470                 }
471
472                 let abi = sig.abi();
473                 if abi != ::abi::Abi::Rust {
474                     output.push_str("extern \"");
475                     output.push_str(abi.name());
476                     output.push_str("\" ");
477                 }
478
479                 output.push_str("fn(");
480
481                 let sig = self.tcx.erase_late_bound_regions_and_normalize(&sig);
482
483                 if !sig.inputs().is_empty() {
484                     for &parameter_type in sig.inputs() {
485                         self.push_type_name(parameter_type, output);
486                         output.push_str(", ");
487                     }
488                     output.pop();
489                     output.pop();
490                 }
491
492                 if sig.variadic {
493                     if !sig.inputs().is_empty() {
494                         output.push_str(", ...");
495                     } else {
496                         output.push_str("...");
497                     }
498                 }
499
500                 output.push(')');
501
502                 if !sig.output().is_nil() {
503                     output.push_str(" -> ");
504                     self.push_type_name(sig.output(), output);
505                 }
506             },
507             ty::TyClosure(def_id, ref closure_substs) => {
508                 self.push_def_path(def_id, output);
509                 let generics = self.tcx.item_generics(self.tcx.closure_base_def_id(def_id));
510                 let substs = closure_substs.substs.truncate_to(self.tcx, generics);
511                 self.push_type_params(substs, iter::empty(), output);
512             }
513             ty::TyError |
514             ty::TyInfer(_) |
515             ty::TyProjection(..) |
516             ty::TyParam(_) |
517             ty::TyAnon(..) => {
518                 bug!("DefPathBasedNames: Trying to create type name for \
519                                          unexpected type: {:?}", t);
520             }
521         }
522     }
523
524     pub fn push_def_path(&self,
525                          def_id: DefId,
526                          output: &mut String) {
527         let def_path = self.tcx.def_path(def_id);
528
529         // some_crate::
530         if !(self.omit_local_crate_name && def_id.is_local()) {
531             output.push_str(&self.tcx.crate_name(def_path.krate).as_str());
532             output.push_str("::");
533         }
534
535         // foo::bar::ItemName::
536         for part in self.tcx.def_path(def_id).data {
537             if self.omit_disambiguators {
538                 write!(output, "{}::", part.data.as_interned_str()).unwrap();
539             } else {
540                 write!(output, "{}[{}]::",
541                        part.data.as_interned_str(),
542                        part.disambiguator).unwrap();
543             }
544         }
545
546         // remove final "::"
547         output.pop();
548         output.pop();
549     }
550
551     fn push_type_params<I>(&self,
552                             substs: &Substs<'tcx>,
553                             projections: I,
554                             output: &mut String)
555         where I: Iterator<Item=ty::PolyExistentialProjection<'tcx>>
556     {
557         let mut projections = projections.peekable();
558         if substs.types().next().is_none() && projections.peek().is_none() {
559             return;
560         }
561
562         output.push('<');
563
564         for type_parameter in substs.types() {
565             self.push_type_name(type_parameter, output);
566             output.push_str(", ");
567         }
568
569         for projection in projections {
570             let projection = projection.skip_binder();
571             let name = &projection.item_name.as_str();
572             output.push_str(name);
573             output.push_str("=");
574             self.push_type_name(projection.ty, output);
575             output.push_str(", ");
576         }
577
578         output.pop();
579         output.pop();
580
581         output.push('>');
582     }
583
584     pub fn push_instance_as_string(&self,
585                                    instance: Instance<'tcx>,
586                                    output: &mut String) {
587         self.push_def_path(instance.def, output);
588         self.push_type_params(instance.substs, iter::empty(), output);
589     }
590 }