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.types.needs_infer() &&
175 !instance.substs.types.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.tcx(), 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.is_empty() || {
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) => !instance.def.is_local() ||
268 !instance.substs.types.is_empty(),
269 TransItem::DropGlue(..) => true,
270 TransItem::Static(..) => false,
274 pub fn is_generic_fn(&self) -> bool {
276 TransItem::Fn(ref instance) => !instance.substs.types.is_empty(),
277 TransItem::DropGlue(..) |
278 TransItem::Static(..) => false,
282 pub fn explicit_linkage(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<llvm::Linkage> {
283 let def_id = match *self {
284 TransItem::Fn(ref instance) => instance.def,
285 TransItem::Static(node_id) => tcx.map.local_def_id(node_id),
286 TransItem::DropGlue(..) => return None,
289 let attributes = tcx.get_attrs(def_id);
290 if let Some(name) = attr::first_attr_value_str_by_name(&attributes, "linkage") {
291 if let Some(linkage) = base::llvm_linkage_by_name(&name) {
294 let span = tcx.map.span_if_local(def_id);
295 if let Some(span) = span {
296 tcx.sess.span_fatal(span, "invalid linkage specified")
298 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
306 pub fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> String {
307 let hir_map = &tcx.map;
310 TransItem::DropGlue(dg) => {
311 let mut s = String::with_capacity(32);
313 DropGlueKind::Ty(_) => s.push_str("drop-glue "),
314 DropGlueKind::TyContents(_) => s.push_str("drop-glue-contents "),
316 push_unique_type_name(tcx, dg.ty(), &mut s);
319 TransItem::Fn(instance) => {
320 to_string_internal(tcx, "fn ", instance)
322 TransItem::Static(node_id) => {
323 let def_id = hir_map.local_def_id(node_id);
324 let instance = Instance::new(def_id, Substs::empty(tcx));
325 to_string_internal(tcx, "static ", instance)
329 fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
331 instance: Instance<'tcx>)
333 let mut result = String::with_capacity(32);
334 result.push_str(prefix);
335 push_instance_as_string(tcx, instance, &mut result);
340 pub fn to_raw_string(&self) -> String {
342 TransItem::DropGlue(dg) => {
343 let prefix = match dg {
344 DropGlueKind::Ty(_) => "Ty",
345 DropGlueKind::TyContents(_) => "TyContents",
347 format!("DropGlue({}: {})", prefix, dg.ty() as *const _ as usize)
349 TransItem::Fn(instance) => {
350 format!("Fn({:?}, {})",
352 instance.substs as *const _ as usize)
354 TransItem::Static(id) => {
355 format!("Static({:?})", id)
362 //=-----------------------------------------------------------------------------
363 // TransItem String Keys
364 //=-----------------------------------------------------------------------------
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.
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.
374 /// Same as `unique_type_name()` but with the result pushed onto the given
375 /// `output` parameter.
376 pub fn push_unique_type_name<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
378 output: &mut String) {
380 ty::TyBool => output.push_str("bool"),
381 ty::TyChar => output.push_str("char"),
382 ty::TyStr => output.push_str("str"),
383 ty::TyNever => output.push_str("!"),
384 ty::TyInt(ast::IntTy::Is) => output.push_str("isize"),
385 ty::TyInt(ast::IntTy::I8) => output.push_str("i8"),
386 ty::TyInt(ast::IntTy::I16) => output.push_str("i16"),
387 ty::TyInt(ast::IntTy::I32) => output.push_str("i32"),
388 ty::TyInt(ast::IntTy::I64) => output.push_str("i64"),
389 ty::TyUint(ast::UintTy::Us) => output.push_str("usize"),
390 ty::TyUint(ast::UintTy::U8) => output.push_str("u8"),
391 ty::TyUint(ast::UintTy::U16) => output.push_str("u16"),
392 ty::TyUint(ast::UintTy::U32) => output.push_str("u32"),
393 ty::TyUint(ast::UintTy::U64) => output.push_str("u64"),
394 ty::TyFloat(ast::FloatTy::F32) => output.push_str("f32"),
395 ty::TyFloat(ast::FloatTy::F64) => output.push_str("f64"),
396 ty::TyStruct(adt_def, substs) |
397 ty::TyEnum(adt_def, substs) => {
398 push_item_name(tcx, adt_def.did, output);
399 push_type_params(tcx, &substs.types, &[], output);
401 ty::TyTuple(component_types) => {
403 for &component_type in component_types {
404 push_unique_type_name(tcx, component_type, output);
405 output.push_str(", ");
407 if !component_types.is_empty() {
413 ty::TyBox(inner_type) => {
414 output.push_str("Box<");
415 push_unique_type_name(tcx, inner_type, output);
418 ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
421 hir::MutImmutable => output.push_str("const "),
422 hir::MutMutable => output.push_str("mut "),
425 push_unique_type_name(tcx, inner_type, output);
427 ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
429 if mutbl == hir::MutMutable {
430 output.push_str("mut ");
433 push_unique_type_name(tcx, inner_type, output);
435 ty::TyArray(inner_type, len) => {
437 push_unique_type_name(tcx, inner_type, output);
438 output.push_str(&format!("; {}", len));
441 ty::TySlice(inner_type) => {
443 push_unique_type_name(tcx, inner_type, output);
446 ty::TyTrait(ref trait_data) => {
447 push_item_name(tcx, trait_data.principal.def_id(), output);
448 push_type_params(tcx,
449 &trait_data.principal.skip_binder().substs.types,
450 &trait_data.projection_bounds,
453 ty::TyFnDef(_, _, &ty::BareFnTy{ unsafety, abi, ref sig } ) |
454 ty::TyFnPtr(&ty::BareFnTy{ unsafety, abi, ref sig } ) => {
455 if unsafety == hir::Unsafety::Unsafe {
456 output.push_str("unsafe ");
459 if abi != ::abi::Abi::Rust {
460 output.push_str("extern \"");
461 output.push_str(abi.name());
462 output.push_str("\" ");
465 output.push_str("fn(");
467 let sig = tcx.erase_late_bound_regions(sig);
468 if !sig.inputs.is_empty() {
469 for ¶meter_type in &sig.inputs {
470 push_unique_type_name(tcx, parameter_type, output);
471 output.push_str(", ");
478 if !sig.inputs.is_empty() {
479 output.push_str(", ...");
481 output.push_str("...");
487 if !sig.output.is_nil() {
488 output.push_str(" -> ");
489 push_unique_type_name(tcx, sig.output, output);
492 ty::TyClosure(def_id, ref closure_substs) => {
493 push_item_name(tcx, def_id, output);
494 output.push_str("{");
495 output.push_str(&format!("{}:{}", def_id.krate, def_id.index.as_usize()));
496 output.push_str("}");
497 push_type_params(tcx, &closure_substs.func_substs.types, &[], output);
501 ty::TyProjection(..) |
504 bug!("debuginfo: Trying to create type name for \
505 unexpected type: {:?}", t);
510 fn push_item_name(tcx: TyCtxt,
512 output: &mut String) {
513 let def_path = tcx.def_path(def_id);
516 output.push_str(&tcx.crate_name(def_path.krate));
517 output.push_str("::");
519 // foo::bar::ItemName::
520 for part in tcx.def_path(def_id).data {
521 output.push_str(&format!("{}[{}]::",
522 part.data.as_interned_str(),
523 part.disambiguator));
531 fn push_type_params<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
533 projections: &[ty::PolyExistentialProjection<'tcx>],
534 output: &mut String) {
535 if types.is_empty() && projections.is_empty() {
541 for &type_parameter in types {
542 push_unique_type_name(tcx, type_parameter, output);
543 output.push_str(", ");
546 for projection in projections {
547 let projection = projection.skip_binder();
548 let name = &projection.item_name.as_str();
549 output.push_str(name);
550 output.push_str("=");
551 push_unique_type_name(tcx, projection.ty, output);
552 output.push_str(", ");
561 fn push_instance_as_string<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
562 instance: Instance<'tcx>,
563 output: &mut String) {
564 push_item_name(tcx, instance.def, output);
565 push_type_params(tcx, &instance.substs.types, &[], output);
568 pub fn def_id_to_string(tcx: TyCtxt, def_id: DefId) -> String {
569 let mut output = String::new();
570 push_item_name(tcx, def_id, &mut output);
574 pub fn type_to_string<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
577 let mut output = String::new();
578 push_unique_type_name(tcx, ty, &mut output);