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};
24 use monomorphize::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 syntax::ast::{self, NodeId};
34 use back::symbol_names;
38 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
39 pub enum TransItem<'tcx> {
44 /// Describes how a translation item will be instantiated in object files.
45 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
46 pub enum InstantiationMode {
47 /// There will be exactly one instance of the given TransItem. It will have
48 /// external linkage so that it can be linked to from other codegen units.
51 /// Each codegen unit containing a reference to the given TransItem will
52 /// have its own private copy of the function (with internal linkage).
56 impl<'a, 'tcx> TransItem<'tcx> {
58 pub fn define(&self, ccx: &CrateContext<'a, 'tcx>) {
59 debug!("BEGIN IMPLEMENTING '{} ({})' in cgu {}",
60 self.to_string(ccx.tcx()),
62 ccx.codegen_unit().name());
64 // (*) This code executes in the context of a dep-node for the
65 // entire CGU. In some cases, we introduce dep-nodes for
66 // particular items that we are translating (these nodes will
67 // have read edges coming into the CGU node). These smaller
68 // nodes are not needed for correctness -- we always
69 // invalidate an entire CGU at a time -- but they enable
70 // finer-grained testing, since you can write tests that check
71 // that the incoming edges to a particular fn are from a
75 TransItem::Static(node_id) => {
76 let def_id = ccx.tcx().hir.local_def_id(node_id);
77 let _task = ccx.tcx().dep_graph.in_task(DepNode::TransCrateItem(def_id)); // (*)
78 let item = ccx.tcx().hir.expect_item(node_id);
79 if let hir::ItemStatic(_, m, _) = item.node {
80 match consts::trans_static(&ccx, m, item.id, &item.attrs) {
81 Ok(_) => { /* Cool, everything's alright. */ },
83 // FIXME: shouldn't this be a `span_err`?
85 ccx.tcx(), &err, item.span, "static");
89 span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
92 TransItem::Fn(instance) => {
93 let _task = ccx.tcx().dep_graph.in_task(
94 DepNode::TransCrateItem(instance.def_id())); // (*)
96 base::trans_instance(&ccx, instance);
100 debug!("END IMPLEMENTING '{} ({})' in cgu {}",
101 self.to_string(ccx.tcx()),
102 self.to_raw_string(),
103 ccx.codegen_unit().name());
106 pub fn predefine(&self,
107 ccx: &CrateContext<'a, 'tcx>,
108 linkage: llvm::Linkage) {
109 debug!("BEGIN PREDEFINING '{} ({})' in cgu {}",
110 self.to_string(ccx.tcx()),
111 self.to_raw_string(),
112 ccx.codegen_unit().name());
114 let symbol_name = ccx.symbol_map()
115 .get_or_compute(ccx.shared(), *self);
117 debug!("symbol {}", &symbol_name);
120 TransItem::Static(node_id) => {
121 TransItem::predefine_static(ccx, node_id, linkage, &symbol_name);
123 TransItem::Fn(instance) => {
124 TransItem::predefine_fn(ccx, instance, linkage, &symbol_name);
128 debug!("END PREDEFINING '{} ({})' in cgu {}",
129 self.to_string(ccx.tcx()),
130 self.to_raw_string(),
131 ccx.codegen_unit().name());
134 fn predefine_static(ccx: &CrateContext<'a, 'tcx>,
135 node_id: ast::NodeId,
136 linkage: llvm::Linkage,
138 let def_id = ccx.tcx().hir.local_def_id(node_id);
139 let instance = Instance::mono(ccx.tcx(), def_id);
140 let ty = common::instance_ty(ccx.shared(), &instance);
141 let llty = type_of::type_of(ccx, ty);
143 let g = declare::define_global(ccx, symbol_name, llty).unwrap_or_else(|| {
144 ccx.sess().span_fatal(ccx.tcx().hir.span(node_id),
145 &format!("symbol `{}` is already defined", symbol_name))
148 unsafe { llvm::LLVMRustSetLinkage(g, linkage) };
150 ccx.instances().borrow_mut().insert(instance, g);
151 ccx.statics().borrow_mut().insert(g, def_id);
154 fn predefine_fn(ccx: &CrateContext<'a, 'tcx>,
155 instance: Instance<'tcx>,
156 linkage: llvm::Linkage,
158 assert!(!instance.substs.needs_infer() &&
159 !instance.substs.has_param_types());
161 let mono_ty = common::instance_ty(ccx.shared(), &instance);
162 let attrs = instance.def.attrs(ccx.tcx());
163 let lldecl = declare::declare_fn(ccx, symbol_name, mono_ty);
164 unsafe { llvm::LLVMRustSetLinkage(lldecl, linkage) };
165 base::set_link_section(ccx, lldecl, &attrs);
166 if linkage == llvm::Linkage::LinkOnceODRLinkage ||
167 linkage == llvm::Linkage::WeakODRLinkage {
168 llvm::SetUniqueComdat(ccx.llmod(), lldecl);
171 debug!("predefine_fn: mono_ty = {:?} instance = {:?}", mono_ty, instance);
172 if common::is_inline_instance(ccx.tcx(), &instance) {
173 attributes::inline(lldecl, attributes::InlineAttr::Hint);
175 attributes::from_fn_attrs(ccx, &attrs, lldecl);
177 ccx.instances().borrow_mut().insert(instance, lldecl);
180 pub fn compute_symbol_name(&self,
181 scx: &SharedCrateContext<'a, 'tcx>) -> String {
183 TransItem::Fn(instance) => symbol_names::symbol_name(instance, scx),
184 TransItem::Static(node_id) => {
185 let def_id = scx.tcx().hir.local_def_id(node_id);
186 symbol_names::symbol_name(Instance::mono(scx.tcx(), def_id), scx)
191 pub fn instantiation_mode(&self,
192 tcx: TyCtxt<'a, 'tcx, 'tcx>)
193 -> InstantiationMode {
195 TransItem::Fn(ref instance) => {
196 if self.explicit_linkage(tcx).is_none() &&
197 common::requests_inline(tcx, instance)
199 InstantiationMode::LocalCopy
201 InstantiationMode::GloballyShared
204 TransItem::Static(..) => InstantiationMode::GloballyShared,
208 pub fn is_generic_fn(&self) -> bool {
210 TransItem::Fn(ref instance) => {
211 instance.substs.types().next().is_some()
213 TransItem::Static(..) => false,
217 pub fn explicit_linkage(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<llvm::Linkage> {
218 let def_id = match *self {
219 TransItem::Fn(ref instance) => instance.def_id(),
220 TransItem::Static(node_id) => tcx.hir.local_def_id(node_id),
223 let attributes = tcx.get_attrs(def_id);
224 if let Some(name) = attr::first_attr_value_str_by_name(&attributes, "linkage") {
225 if let Some(linkage) = base::llvm_linkage_by_name(&name.as_str()) {
228 let span = tcx.hir.span_if_local(def_id);
229 if let Some(span) = span {
230 tcx.sess.span_fatal(span, "invalid linkage specified")
232 tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
240 pub fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> String {
241 let hir_map = &tcx.hir;
244 TransItem::Fn(instance) => {
245 to_string_internal(tcx, "fn ", instance)
247 TransItem::Static(node_id) => {
248 let def_id = hir_map.local_def_id(node_id);
249 let instance = Instance::new(def_id, tcx.intern_substs(&[]));
250 to_string_internal(tcx, "static ", instance)
254 fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
256 instance: Instance<'tcx>)
258 let mut result = String::with_capacity(32);
259 result.push_str(prefix);
260 let printer = DefPathBasedNames::new(tcx, false, false);
261 printer.push_instance_as_string(instance, &mut result);
266 pub fn to_raw_string(&self) -> String {
268 TransItem::Fn(instance) => {
269 format!("Fn({:?}, {})",
271 instance.substs.as_ptr() as usize)
273 TransItem::Static(id) => {
274 format!("Static({:?})", id)
281 //=-----------------------------------------------------------------------------
282 // TransItem String Keys
283 //=-----------------------------------------------------------------------------
285 // The code below allows for producing a unique string key for a trans item.
286 // These keys are used by the handwritten auto-tests, so they need to be
287 // predictable and human-readable.
289 // Note: A lot of this could looks very similar to what's already in the
290 // ppaux module. It would be good to refactor things so we only have one
291 // parameterizable implementation for printing types.
293 /// Same as `unique_type_name()` but with the result pushed onto the given
294 /// `output` parameter.
295 pub struct DefPathBasedNames<'a, 'tcx: 'a> {
296 tcx: TyCtxt<'a, 'tcx, 'tcx>,
297 omit_disambiguators: bool,
298 omit_local_crate_name: bool,
301 impl<'a, 'tcx> DefPathBasedNames<'a, 'tcx> {
302 pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
303 omit_disambiguators: bool,
304 omit_local_crate_name: bool)
308 omit_disambiguators: omit_disambiguators,
309 omit_local_crate_name: omit_local_crate_name,
313 pub fn push_type_name(&self, t: Ty<'tcx>, output: &mut String) {
315 ty::TyBool => output.push_str("bool"),
316 ty::TyChar => output.push_str("char"),
317 ty::TyStr => output.push_str("str"),
318 ty::TyNever => output.push_str("!"),
319 ty::TyInt(ast::IntTy::Is) => output.push_str("isize"),
320 ty::TyInt(ast::IntTy::I8) => output.push_str("i8"),
321 ty::TyInt(ast::IntTy::I16) => output.push_str("i16"),
322 ty::TyInt(ast::IntTy::I32) => output.push_str("i32"),
323 ty::TyInt(ast::IntTy::I64) => output.push_str("i64"),
324 ty::TyInt(ast::IntTy::I128) => output.push_str("i128"),
325 ty::TyUint(ast::UintTy::Us) => output.push_str("usize"),
326 ty::TyUint(ast::UintTy::U8) => output.push_str("u8"),
327 ty::TyUint(ast::UintTy::U16) => output.push_str("u16"),
328 ty::TyUint(ast::UintTy::U32) => output.push_str("u32"),
329 ty::TyUint(ast::UintTy::U64) => output.push_str("u64"),
330 ty::TyUint(ast::UintTy::U128) => output.push_str("u128"),
331 ty::TyFloat(ast::FloatTy::F32) => output.push_str("f32"),
332 ty::TyFloat(ast::FloatTy::F64) => output.push_str("f64"),
333 ty::TyAdt(adt_def, substs) => {
334 self.push_def_path(adt_def.did, output);
335 self.push_type_params(substs, iter::empty(), output);
337 ty::TyTuple(component_types, _) => {
339 for &component_type in component_types {
340 self.push_type_name(component_type, output);
341 output.push_str(", ");
343 if !component_types.is_empty() {
349 ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
352 hir::MutImmutable => output.push_str("const "),
353 hir::MutMutable => output.push_str("mut "),
356 self.push_type_name(inner_type, output);
358 ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
360 if mutbl == hir::MutMutable {
361 output.push_str("mut ");
364 self.push_type_name(inner_type, output);
366 ty::TyArray(inner_type, len) => {
368 self.push_type_name(inner_type, output);
369 write!(output, "; {}", len).unwrap();
372 ty::TySlice(inner_type) => {
374 self.push_type_name(inner_type, output);
377 ty::TyDynamic(ref trait_data, ..) => {
378 if let Some(principal) = trait_data.principal() {
379 self.push_def_path(principal.def_id(), output);
380 self.push_type_params(principal.skip_binder().substs,
381 trait_data.projection_bounds(),
385 ty::TyFnDef(.., sig) |
386 ty::TyFnPtr(sig) => {
387 if sig.unsafety() == hir::Unsafety::Unsafe {
388 output.push_str("unsafe ");
392 if abi != ::abi::Abi::Rust {
393 output.push_str("extern \"");
394 output.push_str(abi.name());
395 output.push_str("\" ");
398 output.push_str("fn(");
400 let sig = self.tcx.erase_late_bound_regions_and_normalize(&sig);
402 if !sig.inputs().is_empty() {
403 for ¶meter_type in sig.inputs() {
404 self.push_type_name(parameter_type, output);
405 output.push_str(", ");
412 if !sig.inputs().is_empty() {
413 output.push_str(", ...");
415 output.push_str("...");
421 if !sig.output().is_nil() {
422 output.push_str(" -> ");
423 self.push_type_name(sig.output(), output);
426 ty::TyClosure(def_id, ref closure_substs) => {
427 self.push_def_path(def_id, output);
428 let generics = self.tcx.item_generics(self.tcx.closure_base_def_id(def_id));
429 let substs = closure_substs.substs.truncate_to(self.tcx, generics);
430 self.push_type_params(substs, iter::empty(), output);
434 ty::TyProjection(..) |
437 bug!("DefPathBasedNames: Trying to create type name for \
438 unexpected type: {:?}", t);
443 pub fn push_def_path(&self,
445 output: &mut String) {
446 let def_path = self.tcx.def_path(def_id);
449 if !(self.omit_local_crate_name && def_id.is_local()) {
450 output.push_str(&self.tcx.crate_name(def_path.krate).as_str());
451 output.push_str("::");
454 // foo::bar::ItemName::
455 for part in self.tcx.def_path(def_id).data {
456 if self.omit_disambiguators {
457 write!(output, "{}::", part.data.as_interned_str()).unwrap();
459 write!(output, "{}[{}]::",
460 part.data.as_interned_str(),
461 part.disambiguator).unwrap();
470 fn push_type_params<I>(&self,
471 substs: &Substs<'tcx>,
474 where I: Iterator<Item=ty::PolyExistentialProjection<'tcx>>
476 let mut projections = projections.peekable();
477 if substs.types().next().is_none() && projections.peek().is_none() {
483 for type_parameter in substs.types() {
484 self.push_type_name(type_parameter, output);
485 output.push_str(", ");
488 for projection in projections {
489 let projection = projection.skip_binder();
490 let name = &projection.item_name.as_str();
491 output.push_str(name);
492 output.push_str("=");
493 self.push_type_name(projection.ty, output);
494 output.push_str(", ");
503 pub fn push_instance_as_string(&self,
504 instance: Instance<'tcx>,
505 output: &mut String) {
506 self.push_def_path(instance.def_id(), output);
507 self.push_type_params(instance.substs, iter::empty(), output);