]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans_item.rs
Auto merge of #35856 - phimuemue:master, r=brson
[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 declare;
22 use glue::DropGlueKind;
23 use llvm;
24 use monomorphize::{self, Instance};
25 use rustc::dep_graph::DepNode;
26 use rustc::hir;
27 use rustc::hir::def_id::DefId;
28 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
29 use rustc::ty::subst::Substs;
30 use rustc_const_eval::fatal_const_eval_err;
31 use std::hash::{Hash, Hasher};
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
39 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
40 pub enum TransItem<'tcx> {
41     DropGlue(DropGlueKind<'tcx>),
42     Fn(Instance<'tcx>),
43     Static(NodeId)
44 }
45
46 impl<'tcx> Hash for TransItem<'tcx> {
47     fn hash<H: Hasher>(&self, s: &mut H) {
48         match *self {
49             TransItem::DropGlue(t) => {
50                 0u8.hash(s);
51                 t.hash(s);
52             },
53             TransItem::Fn(instance) => {
54                 1u8.hash(s);
55                 instance.def.hash(s);
56                 (instance.substs as *const _ as usize).hash(s);
57             }
58             TransItem::Static(node_id) => {
59                 2u8.hash(s);
60                 node_id.hash(s);
61             }
62         };
63     }
64 }
65
66 impl<'a, 'tcx> TransItem<'tcx> {
67
68     pub fn define(&self, ccx: &CrateContext<'a, 'tcx>) {
69         debug!("BEGIN IMPLEMENTING '{} ({})' in cgu {}",
70                   self.to_string(ccx.tcx()),
71                   self.to_raw_string(),
72                   ccx.codegen_unit().name());
73
74         // (*) This code executes in the context of a dep-node for the
75         // entire CGU. In some cases, we introduce dep-nodes for
76         // particular items that we are translating (these nodes will
77         // have read edges coming into the CGU node). These smaller
78         // nodes are not needed for correctness -- we always
79         // invalidate an entire CGU at a time -- but they enable
80         // finer-grained testing, since you can write tests that check
81         // that the incoming edges to a particular fn are from a
82         // particular set.
83
84         match *self {
85             TransItem::Static(node_id) => {
86                 let def_id = ccx.tcx().map.local_def_id(node_id);
87                 let _task = ccx.tcx().dep_graph.in_task(DepNode::TransCrateItem(def_id)); // (*)
88                 let item = ccx.tcx().map.expect_item(node_id);
89                 if let hir::ItemStatic(_, m, _) = item.node {
90                     match consts::trans_static(&ccx, m, item.id, &item.attrs) {
91                         Ok(_) => { /* Cool, everything's alright. */ },
92                         Err(err) => {
93                             // FIXME: shouldn't this be a `span_err`?
94                             fatal_const_eval_err(
95                                 ccx.tcx(), &err, item.span, "static");
96                         }
97                     };
98                 } else {
99                     span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
100                 }
101             }
102             TransItem::Fn(instance) => {
103                 let _task = ccx.tcx().dep_graph.in_task(
104                     DepNode::TransCrateItem(instance.def)); // (*)
105
106                 base::trans_instance(&ccx, instance);
107             }
108             TransItem::DropGlue(dg) => {
109                 glue::implement_drop_glue(&ccx, dg);
110             }
111         }
112
113         debug!("END IMPLEMENTING '{} ({})' in cgu {}",
114                self.to_string(ccx.tcx()),
115                self.to_raw_string(),
116                ccx.codegen_unit().name());
117     }
118
119     pub fn predefine(&self,
120                      ccx: &CrateContext<'a, 'tcx>,
121                      linkage: llvm::Linkage) {
122         debug!("BEGIN PREDEFINING '{} ({})' in cgu {}",
123                self.to_string(ccx.tcx()),
124                self.to_raw_string(),
125                ccx.codegen_unit().name());
126
127         let symbol_name = ccx.symbol_map()
128                              .get_or_compute(ccx.shared(), *self);
129
130         debug!("symbol {}", &symbol_name);
131
132         match *self {
133             TransItem::Static(node_id) => {
134                 TransItem::predefine_static(ccx, node_id, linkage, &symbol_name);
135             }
136             TransItem::Fn(instance) => {
137                 TransItem::predefine_fn(ccx, instance, linkage, &symbol_name);
138             }
139             TransItem::DropGlue(dg) => {
140                 TransItem::predefine_drop_glue(ccx, dg, linkage, &symbol_name);
141             }
142         }
143
144         debug!("END PREDEFINING '{} ({})' in cgu {}",
145                self.to_string(ccx.tcx()),
146                self.to_raw_string(),
147                ccx.codegen_unit().name());
148     }
149
150     fn predefine_static(ccx: &CrateContext<'a, 'tcx>,
151                         node_id: ast::NodeId,
152                         linkage: llvm::Linkage,
153                         symbol_name: &str) {
154         let def_id = ccx.tcx().map.local_def_id(node_id);
155         let ty = ccx.tcx().lookup_item_type(def_id).ty;
156         let llty = type_of::type_of(ccx, ty);
157
158         let g = declare::define_global(ccx, symbol_name, llty).unwrap_or_else(|| {
159             ccx.sess().span_fatal(ccx.tcx().map.span(node_id),
160                 &format!("symbol `{}` is already defined", symbol_name))
161         });
162
163         unsafe { llvm::LLVMSetLinkage(g, linkage) };
164
165         let instance = Instance::mono(ccx.shared(), def_id);
166         ccx.instances().borrow_mut().insert(instance, g);
167         ccx.statics().borrow_mut().insert(g, def_id);
168     }
169
170     fn predefine_fn(ccx: &CrateContext<'a, 'tcx>,
171                     instance: Instance<'tcx>,
172                     linkage: llvm::Linkage,
173                     symbol_name: &str) {
174         assert!(!instance.substs.needs_infer() &&
175                 !instance.substs.has_param_types());
176
177         let item_ty = ccx.tcx().lookup_item_type(instance.def).ty;
178         let item_ty = ccx.tcx().erase_regions(&item_ty);
179         let mono_ty = monomorphize::apply_param_substs(ccx.shared(), instance.substs, &item_ty);
180
181         let attrs = ccx.tcx().get_attrs(instance.def);
182         let lldecl = declare::declare_fn(ccx, symbol_name, mono_ty);
183         unsafe { llvm::LLVMSetLinkage(lldecl, linkage) };
184         base::set_link_section(ccx, lldecl, &attrs);
185         if linkage == llvm::LinkOnceODRLinkage ||
186             linkage == llvm::WeakODRLinkage {
187             llvm::SetUniqueComdat(ccx.llmod(), lldecl);
188         }
189
190         attributes::from_fn_attrs(ccx, &attrs, lldecl);
191
192         ccx.instances().borrow_mut().insert(instance, lldecl);
193     }
194
195     fn predefine_drop_glue(ccx: &CrateContext<'a, 'tcx>,
196                            dg: glue::DropGlueKind<'tcx>,
197                            linkage: llvm::Linkage,
198                            symbol_name: &str) {
199         let tcx = ccx.tcx();
200         assert_eq!(dg.ty(), glue::get_drop_glue_type(tcx, dg.ty()));
201         let t = dg.ty();
202
203         let sig = ty::FnSig {
204             inputs: vec![tcx.mk_mut_ptr(tcx.types.i8)],
205             output: tcx.mk_nil(),
206             variadic: false,
207         };
208
209         // Create a FnType for fn(*mut i8) and substitute the real type in
210         // later - that prevents FnType from splitting fat pointers up.
211         let mut fn_ty = FnType::new(ccx, Abi::Rust, &sig, &[]);
212         fn_ty.args[0].original_ty = type_of::type_of(ccx, t).ptr_to();
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::LLVMSetLinkage(llfn, linkage) };
218         if linkage == llvm::LinkOnceODRLinkage ||
219            linkage == llvm::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().map.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 requests_inline(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> bool {
245         match *self {
246             TransItem::Fn(ref instance) => {
247                 instance.substs.types().next().is_some() || {
248                     let attributes = tcx.get_attrs(instance.def);
249                     attr::requests_inline(&attributes[..])
250                 }
251             }
252             TransItem::DropGlue(..) => true,
253             TransItem::Static(..)   => false,
254         }
255     }
256
257     pub fn is_from_extern_crate(&self) -> bool {
258         match *self {
259             TransItem::Fn(ref instance) => !instance.def.is_local(),
260             TransItem::DropGlue(..) |
261             TransItem::Static(..)   => false,
262         }
263     }
264
265     pub fn is_instantiated_only_on_demand(&self) -> bool {
266         match *self {
267             TransItem::Fn(ref instance) => {
268                 !instance.def.is_local() || instance.substs.types().next().is_some()
269             }
270             TransItem::DropGlue(..) => true,
271             TransItem::Static(..)   => false,
272         }
273     }
274
275     pub fn is_generic_fn(&self) -> bool {
276         match *self {
277             TransItem::Fn(ref instance) => {
278                 instance.substs.types().next().is_some()
279             }
280             TransItem::DropGlue(..) |
281             TransItem::Static(..)   => false,
282         }
283     }
284
285     pub fn explicit_linkage(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<llvm::Linkage> {
286         let def_id = match *self {
287             TransItem::Fn(ref instance) => instance.def,
288             TransItem::Static(node_id) => tcx.map.local_def_id(node_id),
289             TransItem::DropGlue(..) => return None,
290         };
291
292         let attributes = tcx.get_attrs(def_id);
293         if let Some(name) = attr::first_attr_value_str_by_name(&attributes, "linkage") {
294             if let Some(linkage) = base::llvm_linkage_by_name(&name) {
295                 Some(linkage)
296             } else {
297                 let span = tcx.map.span_if_local(def_id);
298                 if let Some(span) = span {
299                     tcx.sess.span_fatal(span, "invalid linkage specified")
300                 } else {
301                     tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
302                 }
303             }
304         } else {
305             None
306         }
307     }
308
309     pub fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> String {
310         let hir_map = &tcx.map;
311
312         return match *self {
313             TransItem::DropGlue(dg) => {
314                 let mut s = String::with_capacity(32);
315                 match dg {
316                     DropGlueKind::Ty(_) => s.push_str("drop-glue "),
317                     DropGlueKind::TyContents(_) => s.push_str("drop-glue-contents "),
318                 };
319                 push_unique_type_name(tcx, dg.ty(), &mut s);
320                 s
321             }
322             TransItem::Fn(instance) => {
323                 to_string_internal(tcx, "fn ", instance)
324             },
325             TransItem::Static(node_id) => {
326                 let def_id = hir_map.local_def_id(node_id);
327                 let instance = Instance::new(def_id, Substs::empty(tcx));
328                 to_string_internal(tcx, "static ", instance)
329             },
330         };
331
332         fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
333                                         prefix: &str,
334                                         instance: Instance<'tcx>)
335                                         -> String {
336             let mut result = String::with_capacity(32);
337             result.push_str(prefix);
338             push_instance_as_string(tcx, 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 *const _ 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 fn push_unique_type_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
380                                        t: Ty<'tcx>,
381                                        output: &mut String) {
382     match t.sty {
383         ty::TyBool              => output.push_str("bool"),
384         ty::TyChar              => output.push_str("char"),
385         ty::TyStr               => output.push_str("str"),
386         ty::TyNever             => output.push_str("!"),
387         ty::TyInt(ast::IntTy::Is)    => output.push_str("isize"),
388         ty::TyInt(ast::IntTy::I8)    => output.push_str("i8"),
389         ty::TyInt(ast::IntTy::I16)   => output.push_str("i16"),
390         ty::TyInt(ast::IntTy::I32)   => output.push_str("i32"),
391         ty::TyInt(ast::IntTy::I64)   => output.push_str("i64"),
392         ty::TyUint(ast::UintTy::Us)   => output.push_str("usize"),
393         ty::TyUint(ast::UintTy::U8)   => output.push_str("u8"),
394         ty::TyUint(ast::UintTy::U16)  => output.push_str("u16"),
395         ty::TyUint(ast::UintTy::U32)  => output.push_str("u32"),
396         ty::TyUint(ast::UintTy::U64)  => output.push_str("u64"),
397         ty::TyFloat(ast::FloatTy::F32) => output.push_str("f32"),
398         ty::TyFloat(ast::FloatTy::F64) => output.push_str("f64"),
399         ty::TyStruct(adt_def, substs) |
400         ty::TyEnum(adt_def, substs) => {
401             push_item_name(tcx, adt_def.did, output);
402             push_type_params(tcx, substs, &[], output);
403         },
404         ty::TyTuple(component_types) => {
405             output.push('(');
406             for &component_type in component_types {
407                 push_unique_type_name(tcx, component_type, output);
408                 output.push_str(", ");
409             }
410             if !component_types.is_empty() {
411                 output.pop();
412                 output.pop();
413             }
414             output.push(')');
415         },
416         ty::TyBox(inner_type) => {
417             output.push_str("Box<");
418             push_unique_type_name(tcx, inner_type, output);
419             output.push('>');
420         },
421         ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
422             output.push('*');
423             match mutbl {
424                 hir::MutImmutable => output.push_str("const "),
425                 hir::MutMutable => output.push_str("mut "),
426             }
427
428             push_unique_type_name(tcx, inner_type, output);
429         },
430         ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
431             output.push('&');
432             if mutbl == hir::MutMutable {
433                 output.push_str("mut ");
434             }
435
436             push_unique_type_name(tcx, inner_type, output);
437         },
438         ty::TyArray(inner_type, len) => {
439             output.push('[');
440             push_unique_type_name(tcx, inner_type, output);
441             output.push_str(&format!("; {}", len));
442             output.push(']');
443         },
444         ty::TySlice(inner_type) => {
445             output.push('[');
446             push_unique_type_name(tcx, inner_type, output);
447             output.push(']');
448         },
449         ty::TyTrait(ref trait_data) => {
450             push_item_name(tcx, trait_data.principal.def_id(), output);
451             push_type_params(tcx,
452                              trait_data.principal.skip_binder().substs,
453                              &trait_data.projection_bounds,
454                              output);
455         },
456         ty::TyFnDef(_, _, &ty::BareFnTy{ unsafety, abi, ref sig } ) |
457         ty::TyFnPtr(&ty::BareFnTy{ unsafety, abi, ref sig } ) => {
458             if unsafety == hir::Unsafety::Unsafe {
459                 output.push_str("unsafe ");
460             }
461
462             if abi != ::abi::Abi::Rust {
463                 output.push_str("extern \"");
464                 output.push_str(abi.name());
465                 output.push_str("\" ");
466             }
467
468             output.push_str("fn(");
469
470             let sig = tcx.erase_late_bound_regions(sig);
471             if !sig.inputs.is_empty() {
472                 for &parameter_type in &sig.inputs {
473                     push_unique_type_name(tcx, parameter_type, output);
474                     output.push_str(", ");
475                 }
476                 output.pop();
477                 output.pop();
478             }
479
480             if sig.variadic {
481                 if !sig.inputs.is_empty() {
482                     output.push_str(", ...");
483                 } else {
484                     output.push_str("...");
485                 }
486             }
487
488             output.push(')');
489
490             if !sig.output.is_nil() {
491                 output.push_str(" -> ");
492                 push_unique_type_name(tcx, sig.output, output);
493             }
494         },
495         ty::TyClosure(def_id, ref closure_substs) => {
496             push_item_name(tcx, def_id, output);
497             output.push_str("{");
498             output.push_str(&format!("{}:{}", def_id.krate, def_id.index.as_usize()));
499             output.push_str("}");
500             push_type_params(tcx, closure_substs.func_substs, &[], output);
501         }
502         ty::TyError |
503         ty::TyInfer(_) |
504         ty::TyProjection(..) |
505         ty::TyParam(_) |
506         ty::TyAnon(..) => {
507             bug!("debuginfo: Trying to create type name for \
508                   unexpected type: {:?}", t);
509         }
510     }
511 }
512
513 fn push_item_name(tcx: TyCtxt,
514                   def_id: DefId,
515                   output: &mut String) {
516     let def_path = tcx.def_path(def_id);
517
518     // some_crate::
519     output.push_str(&tcx.crate_name(def_path.krate));
520     output.push_str("::");
521
522     // foo::bar::ItemName::
523     for part in tcx.def_path(def_id).data {
524         output.push_str(&format!("{}[{}]::",
525                         part.data.as_interned_str(),
526                         part.disambiguator));
527     }
528
529     // remove final "::"
530     output.pop();
531     output.pop();
532 }
533
534 fn push_type_params<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
535                               substs: &Substs<'tcx>,
536                               projections: &[ty::PolyExistentialProjection<'tcx>],
537                               output: &mut String) {
538     if substs.types().next().is_none() && projections.is_empty() {
539         return;
540     }
541
542     output.push('<');
543
544     for type_parameter in substs.types() {
545         push_unique_type_name(tcx, type_parameter, output);
546         output.push_str(", ");
547     }
548
549     for projection in projections {
550         let projection = projection.skip_binder();
551         let name = &projection.item_name.as_str();
552         output.push_str(name);
553         output.push_str("=");
554         push_unique_type_name(tcx, projection.ty, output);
555         output.push_str(", ");
556     }
557
558     output.pop();
559     output.pop();
560
561     output.push('>');
562 }
563
564 fn push_instance_as_string<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
565                                      instance: Instance<'tcx>,
566                                      output: &mut String) {
567     push_item_name(tcx, instance.def, output);
568     push_type_params(tcx, instance.substs, &[], output);
569 }
570
571 pub fn def_id_to_string(tcx: TyCtxt, def_id: DefId) -> String {
572     let mut output = String::new();
573     push_item_name(tcx, def_id, &mut output);
574     output
575 }
576
577 pub fn type_to_string<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
578                                 ty: Ty<'tcx>)
579                                 -> String {
580     let mut output = String::new();
581     push_unique_type_name(tcx, ty, &mut output);
582     output
583 }