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.
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.
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.
20 use context::{CrateContext, SharedCrateContext};
22 use glue::DropGlueKind;
24 use monomorphize::{self, Instance};
25 use rustc::dep_graph::DepNode;
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};
36 use abi::{Abi, FnType};
37 use back::symbol_names;
39 #[derive(PartialEq, Eq, Clone, Copy, Debug)]
40 pub enum TransItem<'tcx> {
41 DropGlue(DropGlueKind<'tcx>),
46 impl<'tcx> Hash for TransItem<'tcx> {
47 fn hash<H: Hasher>(&self, s: &mut H) {
49 TransItem::DropGlue(t) => {
53 TransItem::Fn(instance) => {
56 (instance.substs as *const _ as usize).hash(s);
58 TransItem::Static(node_id) => {
66 impl<'a, 'tcx> TransItem<'tcx> {
68 pub fn define(&self, ccx: &CrateContext<'a, 'tcx>) {
69 debug!("BEGIN IMPLEMENTING '{} ({})' in cgu {}",
70 self.to_string(ccx.tcx()),
72 ccx.codegen_unit().name());
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
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. */ },
93 // FIXME: shouldn't this be a `span_err`?
95 ccx.tcx(), &err, item.span, "static");
99 span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
102 TransItem::Fn(instance) => {
103 let _task = ccx.tcx().dep_graph.in_task(
104 DepNode::TransCrateItem(instance.def)); // (*)
106 base::trans_instance(&ccx, instance);
108 TransItem::DropGlue(dg) => {
109 glue::implement_drop_glue(&ccx, dg);
113 debug!("END IMPLEMENTING '{} ({})' in cgu {}",
114 self.to_string(ccx.tcx()),
115 self.to_raw_string(),
116 ccx.codegen_unit().name());
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());
127 let symbol_name = ccx.symbol_map()
128 .get_or_compute(ccx.shared(), *self);
130 debug!("symbol {}", &symbol_name);
133 TransItem::Static(node_id) => {
134 TransItem::predefine_static(ccx, node_id, linkage, &symbol_name);
136 TransItem::Fn(instance) => {
137 TransItem::predefine_fn(ccx, instance, linkage, &symbol_name);
139 TransItem::DropGlue(dg) => {
140 TransItem::predefine_drop_glue(ccx, dg, linkage, &symbol_name);
144 debug!("END PREDEFINING '{} ({})' in cgu {}",
145 self.to_string(ccx.tcx()),
146 self.to_raw_string(),
147 ccx.codegen_unit().name());
150 fn predefine_static(ccx: &CrateContext<'a, 'tcx>,
151 node_id: ast::NodeId,
152 linkage: llvm::Linkage,
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);
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))
163 unsafe { llvm::LLVMSetLinkage(g, linkage) };
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);
170 fn predefine_fn(ccx: &CrateContext<'a, 'tcx>,
171 instance: Instance<'tcx>,
172 linkage: llvm::Linkage,
174 assert!(!instance.substs.needs_infer() &&
175 !instance.substs.has_param_types());
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);
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);
190 attributes::from_fn_attrs(ccx, &attrs, lldecl);
192 ccx.instances().borrow_mut().insert(instance, lldecl);
195 fn predefine_drop_glue(ccx: &CrateContext<'a, 'tcx>,
196 dg: glue::DropGlueKind<'tcx>,
197 linkage: llvm::Linkage,
200 assert_eq!(dg.ty(), glue::get_drop_glue_type(tcx, dg.ty()));
203 let sig = ty::FnSig {
204 inputs: vec![tcx.mk_mut_ptr(tcx.types.i8)],
205 output: tcx.mk_nil(),
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);
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);
222 attributes::set_frame_pointer_elimination(ccx, llfn);
223 ccx.drop_glues().borrow_mut().insert(dg, (llfn, fn_ty));
226 pub fn compute_symbol_name(&self,
227 scx: &SharedCrateContext<'a, 'tcx>) -> String {
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)
234 TransItem::DropGlue(dg) => {
235 let prefix = match dg {
236 DropGlueKind::Ty(_) => "drop",
237 DropGlueKind::TyContents(_) => "drop_contents",
239 symbol_names::exported_name_from_type_and_prefix(scx, dg.ty(), prefix)
244 pub fn requests_inline(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> bool {
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[..])
252 TransItem::DropGlue(..) => true,
253 TransItem::Static(..) => false,
257 pub fn is_from_extern_crate(&self) -> bool {
259 TransItem::Fn(ref instance) => !instance.def.is_local(),
260 TransItem::DropGlue(..) |
261 TransItem::Static(..) => false,
265 pub fn is_instantiated_only_on_demand(&self) -> bool {
267 TransItem::Fn(ref instance) => {
268 !instance.def.is_local() || instance.substs.types().next().is_some()
270 TransItem::DropGlue(..) => true,
271 TransItem::Static(..) => false,
275 pub fn is_generic_fn(&self) -> bool {
277 TransItem::Fn(ref instance) => {
278 instance.substs.types().next().is_some()
280 TransItem::DropGlue(..) |
281 TransItem::Static(..) => false,
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,
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) {
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")
301 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
309 pub fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> String {
310 let hir_map = &tcx.map;
313 TransItem::DropGlue(dg) => {
314 let mut s = String::with_capacity(32);
316 DropGlueKind::Ty(_) => s.push_str("drop-glue "),
317 DropGlueKind::TyContents(_) => s.push_str("drop-glue-contents "),
319 push_unique_type_name(tcx, dg.ty(), &mut s);
322 TransItem::Fn(instance) => {
323 to_string_internal(tcx, "fn ", instance)
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)
332 fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
334 instance: Instance<'tcx>)
336 let mut result = String::with_capacity(32);
337 result.push_str(prefix);
338 push_instance_as_string(tcx, instance, &mut result);
343 pub fn to_raw_string(&self) -> String {
345 TransItem::DropGlue(dg) => {
346 let prefix = match dg {
347 DropGlueKind::Ty(_) => "Ty",
348 DropGlueKind::TyContents(_) => "TyContents",
350 format!("DropGlue({}: {})", prefix, dg.ty() as *const _ as usize)
352 TransItem::Fn(instance) => {
353 format!("Fn({:?}, {})",
355 instance.substs as *const _ as usize)
357 TransItem::Static(id) => {
358 format!("Static({:?})", id)
365 //=-----------------------------------------------------------------------------
366 // TransItem String Keys
367 //=-----------------------------------------------------------------------------
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.
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.
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>,
381 output: &mut String) {
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);
404 ty::TyTuple(component_types) => {
406 for &component_type in component_types {
407 push_unique_type_name(tcx, component_type, output);
408 output.push_str(", ");
410 if !component_types.is_empty() {
416 ty::TyBox(inner_type) => {
417 output.push_str("Box<");
418 push_unique_type_name(tcx, inner_type, output);
421 ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
424 hir::MutImmutable => output.push_str("const "),
425 hir::MutMutable => output.push_str("mut "),
428 push_unique_type_name(tcx, inner_type, output);
430 ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
432 if mutbl == hir::MutMutable {
433 output.push_str("mut ");
436 push_unique_type_name(tcx, inner_type, output);
438 ty::TyArray(inner_type, len) => {
440 push_unique_type_name(tcx, inner_type, output);
441 output.push_str(&format!("; {}", len));
444 ty::TySlice(inner_type) => {
446 push_unique_type_name(tcx, inner_type, output);
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,
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 ");
462 if abi != ::abi::Abi::Rust {
463 output.push_str("extern \"");
464 output.push_str(abi.name());
465 output.push_str("\" ");
468 output.push_str("fn(");
470 let sig = tcx.erase_late_bound_regions(sig);
471 if !sig.inputs.is_empty() {
472 for ¶meter_type in &sig.inputs {
473 push_unique_type_name(tcx, parameter_type, output);
474 output.push_str(", ");
481 if !sig.inputs.is_empty() {
482 output.push_str(", ...");
484 output.push_str("...");
490 if !sig.output.is_nil() {
491 output.push_str(" -> ");
492 push_unique_type_name(tcx, sig.output, output);
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);
504 ty::TyProjection(..) |
507 bug!("debuginfo: Trying to create type name for \
508 unexpected type: {:?}", t);
513 fn push_item_name(tcx: TyCtxt,
515 output: &mut String) {
516 let def_path = tcx.def_path(def_id);
519 output.push_str(&tcx.crate_name(def_path.krate));
520 output.push_str("::");
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));
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() {
544 for type_parameter in substs.types() {
545 push_unique_type_name(tcx, type_parameter, output);
546 output.push_str(", ");
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(", ");
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);
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);
577 pub fn type_to_string<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
580 let mut output = String::new();
581 push_unique_type_name(tcx, ty, &mut output);