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.
21 use context::{CrateContext, SharedCrateContext};
25 use monomorphize::Instance;
26 use rustc::dep_graph::DepNode;
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};
35 use back::symbol_names;
39 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
40 pub enum TransItem<'tcx> {
46 /// Describes how a translation item will be instantiated in object files.
47 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
48 pub enum InstantiationMode {
49 /// There will be exactly one instance of the given TransItem. It will have
50 /// external linkage so that it can be linked to from other codegen units.
53 /// Each codegen unit containing a reference to the given TransItem will
54 /// have its own private copy of the function (with internal linkage).
58 impl<'a, 'tcx> TransItem<'tcx> {
60 pub fn define(&self, ccx: &CrateContext<'a, 'tcx>) {
61 debug!("BEGIN IMPLEMENTING '{} ({})' in cgu {}",
62 self.to_string(ccx.tcx()),
64 ccx.codegen_unit().name());
66 // (*) This code executes in the context of a dep-node for the
67 // entire CGU. In some cases, we introduce dep-nodes for
68 // particular items that we are translating (these nodes will
69 // have read edges coming into the CGU node). These smaller
70 // nodes are not needed for correctness -- we always
71 // invalidate an entire CGU at a time -- but they enable
72 // finer-grained testing, since you can write tests that check
73 // that the incoming edges to a particular fn are from a
77 TransItem::Static(node_id) => {
78 let def_id = ccx.tcx().hir.local_def_id(node_id);
79 let _task = ccx.tcx().dep_graph.in_task(DepNode::TransCrateItem(def_id)); // (*)
80 let item = ccx.tcx().hir.expect_item(node_id);
81 if let hir::ItemStatic(_, m, _) = item.node {
82 match consts::trans_static(&ccx, m, item.id, &item.attrs) {
83 Ok(_) => { /* Cool, everything's alright. */ },
85 // FIXME: shouldn't this be a `span_err`?
87 ccx.tcx(), &err, item.span, "static");
91 span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
94 TransItem::GlobalAsm(node_id) => {
95 let item = ccx.tcx().hir.expect_item(node_id);
96 if let hir::ItemGlobalAsm(ref ga) = item.node {
97 asm::trans_global_asm(ccx, ga);
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_id())); // (*)
106 base::trans_instance(&ccx, instance);
110 debug!("END IMPLEMENTING '{} ({})' in cgu {}",
111 self.to_string(ccx.tcx()),
112 self.to_raw_string(),
113 ccx.codegen_unit().name());
116 pub fn predefine(&self,
117 ccx: &CrateContext<'a, 'tcx>,
118 linkage: llvm::Linkage) {
119 debug!("BEGIN PREDEFINING '{} ({})' in cgu {}",
120 self.to_string(ccx.tcx()),
121 self.to_raw_string(),
122 ccx.codegen_unit().name());
124 let symbol_name = ccx.symbol_map()
125 .get_or_compute(ccx.shared(), *self);
127 debug!("symbol {}", &symbol_name);
130 TransItem::Static(node_id) => {
131 TransItem::predefine_static(ccx, node_id, linkage, &symbol_name);
133 TransItem::Fn(instance) => {
134 TransItem::predefine_fn(ccx, instance, linkage, &symbol_name);
136 TransItem::GlobalAsm(..) => {}
139 debug!("END PREDEFINING '{} ({})' in cgu {}",
140 self.to_string(ccx.tcx()),
141 self.to_raw_string(),
142 ccx.codegen_unit().name());
145 fn predefine_static(ccx: &CrateContext<'a, 'tcx>,
146 node_id: ast::NodeId,
147 linkage: llvm::Linkage,
149 let def_id = ccx.tcx().hir.local_def_id(node_id);
150 let instance = Instance::mono(ccx.tcx(), def_id);
151 let ty = common::instance_ty(ccx.shared(), &instance);
152 let llty = type_of::type_of(ccx, ty);
154 let g = declare::define_global(ccx, symbol_name, llty).unwrap_or_else(|| {
155 ccx.sess().span_fatal(ccx.tcx().hir.span(node_id),
156 &format!("symbol `{}` is already defined", symbol_name))
159 unsafe { llvm::LLVMRustSetLinkage(g, linkage) };
161 ccx.instances().borrow_mut().insert(instance, g);
162 ccx.statics().borrow_mut().insert(g, def_id);
165 fn predefine_fn(ccx: &CrateContext<'a, 'tcx>,
166 instance: Instance<'tcx>,
167 linkage: llvm::Linkage,
169 assert!(!instance.substs.needs_infer() &&
170 !instance.substs.has_param_types());
172 let mono_ty = common::instance_ty(ccx.shared(), &instance);
173 let attrs = instance.def.attrs(ccx.tcx());
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);
182 debug!("predefine_fn: mono_ty = {:?} instance = {:?}", mono_ty, instance);
183 if common::is_inline_instance(ccx.tcx(), &instance) {
184 attributes::inline(lldecl, attributes::InlineAttr::Hint);
186 attributes::from_fn_attrs(ccx, &attrs, lldecl);
188 ccx.instances().borrow_mut().insert(instance, lldecl);
191 pub fn compute_symbol_name(&self,
192 scx: &SharedCrateContext<'a, 'tcx>) -> String {
194 TransItem::Fn(instance) => symbol_names::symbol_name(instance, scx),
195 TransItem::Static(node_id) => {
196 let def_id = scx.tcx().hir.local_def_id(node_id);
197 symbol_names::symbol_name(Instance::mono(scx.tcx(), def_id), scx)
199 TransItem::GlobalAsm(node_id) => {
200 let def_id = scx.tcx().hir.local_def_id(node_id);
201 format!("global_asm_{:?}", def_id)
206 pub fn instantiation_mode(&self,
207 tcx: TyCtxt<'a, 'tcx, 'tcx>)
208 -> InstantiationMode {
210 TransItem::Fn(ref instance) => {
211 if self.explicit_linkage(tcx).is_none() &&
212 common::requests_inline(tcx, instance)
214 InstantiationMode::LocalCopy
216 InstantiationMode::GloballyShared
219 TransItem::Static(..) => InstantiationMode::GloballyShared,
220 TransItem::GlobalAsm(..) => InstantiationMode::GloballyShared,
224 pub fn is_generic_fn(&self) -> bool {
226 TransItem::Fn(ref instance) => {
227 instance.substs.types().next().is_some()
229 TransItem::Static(..) |
230 TransItem::GlobalAsm(..) => false,
234 pub fn explicit_linkage(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<llvm::Linkage> {
235 let def_id = match *self {
236 TransItem::Fn(ref instance) => instance.def_id(),
237 TransItem::Static(node_id) => tcx.hir.local_def_id(node_id),
238 TransItem::GlobalAsm(..) => return None,
241 let attributes = tcx.get_attrs(def_id);
242 if let Some(name) = attr::first_attr_value_str_by_name(&attributes, "linkage") {
243 if let Some(linkage) = base::llvm_linkage_by_name(&name.as_str()) {
246 let span = tcx.hir.span_if_local(def_id);
247 if let Some(span) = span {
248 tcx.sess.span_fatal(span, "invalid linkage specified")
250 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
258 pub fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> String {
259 let hir_map = &tcx.hir;
262 TransItem::Fn(instance) => {
263 to_string_internal(tcx, "fn ", instance)
265 TransItem::Static(node_id) => {
266 let def_id = hir_map.local_def_id(node_id);
267 let instance = Instance::new(def_id, tcx.intern_substs(&[]));
268 to_string_internal(tcx, "static ", instance)
270 TransItem::GlobalAsm(..) => {
271 "global_asm".to_string()
275 fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
277 instance: Instance<'tcx>)
279 let mut result = String::with_capacity(32);
280 result.push_str(prefix);
281 let printer = DefPathBasedNames::new(tcx, false, false);
282 printer.push_instance_as_string(instance, &mut result);
287 pub fn to_raw_string(&self) -> String {
289 TransItem::Fn(instance) => {
290 format!("Fn({:?}, {})",
292 instance.substs.as_ptr() as usize)
294 TransItem::Static(id) => {
295 format!("Static({:?})", id)
297 TransItem::GlobalAsm(id) => {
298 format!("GlobalAsm({:?})", id)
305 //=-----------------------------------------------------------------------------
306 // TransItem String Keys
307 //=-----------------------------------------------------------------------------
309 // The code below allows for producing a unique string key for a trans item.
310 // These keys are used by the handwritten auto-tests, so they need to be
311 // predictable and human-readable.
313 // Note: A lot of this could looks very similar to what's already in the
314 // ppaux module. It would be good to refactor things so we only have one
315 // parameterizable implementation for printing types.
317 /// Same as `unique_type_name()` but with the result pushed onto the given
318 /// `output` parameter.
319 pub struct DefPathBasedNames<'a, 'tcx: 'a> {
320 tcx: TyCtxt<'a, 'tcx, 'tcx>,
321 omit_disambiguators: bool,
322 omit_local_crate_name: bool,
325 impl<'a, 'tcx> DefPathBasedNames<'a, 'tcx> {
326 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
327 omit_disambiguators: bool,
328 omit_local_crate_name: bool)
332 omit_disambiguators: omit_disambiguators,
333 omit_local_crate_name: omit_local_crate_name,
337 pub fn push_type_name(&self, t: Ty<'tcx>, output: &mut String) {
339 ty::TyBool => output.push_str("bool"),
340 ty::TyChar => output.push_str("char"),
341 ty::TyStr => output.push_str("str"),
342 ty::TyNever => output.push_str("!"),
343 ty::TyInt(ast::IntTy::Is) => output.push_str("isize"),
344 ty::TyInt(ast::IntTy::I8) => output.push_str("i8"),
345 ty::TyInt(ast::IntTy::I16) => output.push_str("i16"),
346 ty::TyInt(ast::IntTy::I32) => output.push_str("i32"),
347 ty::TyInt(ast::IntTy::I64) => output.push_str("i64"),
348 ty::TyInt(ast::IntTy::I128) => output.push_str("i128"),
349 ty::TyUint(ast::UintTy::Us) => output.push_str("usize"),
350 ty::TyUint(ast::UintTy::U8) => output.push_str("u8"),
351 ty::TyUint(ast::UintTy::U16) => output.push_str("u16"),
352 ty::TyUint(ast::UintTy::U32) => output.push_str("u32"),
353 ty::TyUint(ast::UintTy::U64) => output.push_str("u64"),
354 ty::TyUint(ast::UintTy::U128) => output.push_str("u128"),
355 ty::TyFloat(ast::FloatTy::F32) => output.push_str("f32"),
356 ty::TyFloat(ast::FloatTy::F64) => output.push_str("f64"),
357 ty::TyAdt(adt_def, substs) => {
358 self.push_def_path(adt_def.did, output);
359 self.push_type_params(substs, iter::empty(), output);
361 ty::TyTuple(component_types, _) => {
363 for &component_type in component_types {
364 self.push_type_name(component_type, output);
365 output.push_str(", ");
367 if !component_types.is_empty() {
373 ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
376 hir::MutImmutable => output.push_str("const "),
377 hir::MutMutable => output.push_str("mut "),
380 self.push_type_name(inner_type, output);
382 ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
384 if mutbl == hir::MutMutable {
385 output.push_str("mut ");
388 self.push_type_name(inner_type, output);
390 ty::TyArray(inner_type, len) => {
392 self.push_type_name(inner_type, output);
393 write!(output, "; {}", len).unwrap();
396 ty::TySlice(inner_type) => {
398 self.push_type_name(inner_type, output);
401 ty::TyDynamic(ref trait_data, ..) => {
402 if let Some(principal) = trait_data.principal() {
403 self.push_def_path(principal.def_id(), output);
404 self.push_type_params(principal.skip_binder().substs,
405 trait_data.projection_bounds(),
409 ty::TyFnDef(.., sig) |
410 ty::TyFnPtr(sig) => {
411 if sig.unsafety() == hir::Unsafety::Unsafe {
412 output.push_str("unsafe ");
416 if abi != ::abi::Abi::Rust {
417 output.push_str("extern \"");
418 output.push_str(abi.name());
419 output.push_str("\" ");
422 output.push_str("fn(");
424 let sig = self.tcx.erase_late_bound_regions_and_normalize(&sig);
426 if !sig.inputs().is_empty() {
427 for ¶meter_type in sig.inputs() {
428 self.push_type_name(parameter_type, output);
429 output.push_str(", ");
436 if !sig.inputs().is_empty() {
437 output.push_str(", ...");
439 output.push_str("...");
445 if !sig.output().is_nil() {
446 output.push_str(" -> ");
447 self.push_type_name(sig.output(), output);
450 ty::TyClosure(def_id, ref closure_substs) => {
451 self.push_def_path(def_id, output);
452 let generics = self.tcx.item_generics(self.tcx.closure_base_def_id(def_id));
453 let substs = closure_substs.substs.truncate_to(self.tcx, generics);
454 self.push_type_params(substs, iter::empty(), output);
458 ty::TyProjection(..) |
461 bug!("DefPathBasedNames: Trying to create type name for \
462 unexpected type: {:?}", t);
467 pub fn push_def_path(&self,
469 output: &mut String) {
470 let def_path = self.tcx.def_path(def_id);
473 if !(self.omit_local_crate_name && def_id.is_local()) {
474 output.push_str(&self.tcx.crate_name(def_path.krate).as_str());
475 output.push_str("::");
478 // foo::bar::ItemName::
479 for part in self.tcx.def_path(def_id).data {
480 if self.omit_disambiguators {
481 write!(output, "{}::", part.data.as_interned_str()).unwrap();
483 write!(output, "{}[{}]::",
484 part.data.as_interned_str(),
485 part.disambiguator).unwrap();
494 fn push_type_params<I>(&self,
495 substs: &Substs<'tcx>,
498 where I: Iterator<Item=ty::PolyExistentialProjection<'tcx>>
500 let mut projections = projections.peekable();
501 if substs.types().next().is_none() && projections.peek().is_none() {
507 for type_parameter in substs.types() {
508 self.push_type_name(type_parameter, output);
509 output.push_str(", ");
512 for projection in projections {
513 let projection = projection.skip_binder();
514 let name = &projection.item_name.as_str();
515 output.push_str(name);
516 output.push_str("=");
517 self.push_type_name(projection.ty, output);
518 output.push_str(", ");
527 pub fn push_instance_as_string(&self,
528 instance: Instance<'tcx>,
529 output: &mut String) {
530 self.push_def_path(instance.def_id(), output);
531 self.push_type_params(instance.substs, iter::empty(), output);