]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans_item.rs
Rollup merge of #41578 - arielb1:missing-adjustment, r=eddyb
[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 asm;
18 use attributes;
19 use base;
20 use consts;
21 use context::CrateContext;
22 use common;
23 use declare;
24 use llvm;
25 use monomorphize::Instance;
26 use rustc::dep_graph::DepNode;
27 use rustc::hir;
28 use rustc::hir::def_id::DefId;
29 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
30 use rustc::ty::subst::Substs;
31 use syntax::ast::{self, NodeId};
32 use syntax::attr;
33 use syntax_pos::Span;
34 use syntax_pos::symbol::Symbol;
35 use type_of;
36 use std::fmt::Write;
37 use std::iter;
38
39 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
40 pub enum TransItem<'tcx> {
41     Fn(Instance<'tcx>),
42     Static(NodeId),
43     GlobalAsm(NodeId),
44 }
45
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.
51     GloballyShared,
52
53     /// Each codegen unit containing a reference to the given TransItem will
54     /// have its own private copy of the function (with internal linkage).
55     LocalCopy,
56 }
57
58 impl<'a, 'tcx> TransItem<'tcx> {
59
60     pub fn define(&self, ccx: &CrateContext<'a, 'tcx>) {
61         debug!("BEGIN IMPLEMENTING '{} ({})' in cgu {}",
62                   self.to_string(ccx.tcx()),
63                   self.to_raw_string(),
64                   ccx.codegen_unit().name());
65
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
74         // particular set.
75
76         match *self {
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. */ },
84                         Err(err) => {
85                             err.report(ccx.tcx(), item.span, "static");
86                         }
87                     };
88                 } else {
89                     span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
90                 }
91             }
92             TransItem::GlobalAsm(node_id) => {
93                 let item = ccx.tcx().hir.expect_item(node_id);
94                 if let hir::ItemGlobalAsm(ref ga) = item.node {
95                     asm::trans_global_asm(ccx, ga);
96                 } else {
97                     span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
98                 }
99             }
100             TransItem::Fn(instance) => {
101                 let _task = ccx.tcx().dep_graph.in_task(
102                     DepNode::TransCrateItem(instance.def_id())); // (*)
103
104                 base::trans_instance(&ccx, instance);
105             }
106         }
107
108         debug!("END IMPLEMENTING '{} ({})' in cgu {}",
109                self.to_string(ccx.tcx()),
110                self.to_raw_string(),
111                ccx.codegen_unit().name());
112     }
113
114     pub fn predefine(&self,
115                      ccx: &CrateContext<'a, 'tcx>,
116                      linkage: llvm::Linkage) {
117         debug!("BEGIN PREDEFINING '{} ({})' in cgu {}",
118                self.to_string(ccx.tcx()),
119                self.to_raw_string(),
120                ccx.codegen_unit().name());
121
122         let symbol_name = self.symbol_name(ccx.tcx());
123
124         debug!("symbol {}", &symbol_name);
125
126         match *self {
127             TransItem::Static(node_id) => {
128                 TransItem::predefine_static(ccx, node_id, linkage, &symbol_name);
129             }
130             TransItem::Fn(instance) => {
131                 TransItem::predefine_fn(ccx, instance, linkage, &symbol_name);
132             }
133             TransItem::GlobalAsm(..) => {}
134         }
135
136         debug!("END PREDEFINING '{} ({})' in cgu {}",
137                self.to_string(ccx.tcx()),
138                self.to_raw_string(),
139                ccx.codegen_unit().name());
140     }
141
142     fn predefine_static(ccx: &CrateContext<'a, 'tcx>,
143                         node_id: ast::NodeId,
144                         linkage: llvm::Linkage,
145                         symbol_name: &str) {
146         let def_id = ccx.tcx().hir.local_def_id(node_id);
147         let instance = Instance::mono(ccx.tcx(), def_id);
148         let ty = common::instance_ty(ccx.shared(), &instance);
149         let llty = type_of::type_of(ccx, ty);
150
151         let g = declare::define_global(ccx, symbol_name, llty).unwrap_or_else(|| {
152             ccx.sess().span_fatal(ccx.tcx().hir.span(node_id),
153                 &format!("symbol `{}` is already defined", symbol_name))
154         });
155
156         unsafe { llvm::LLVMRustSetLinkage(g, linkage) };
157
158         ccx.instances().borrow_mut().insert(instance, g);
159         ccx.statics().borrow_mut().insert(g, def_id);
160     }
161
162     fn predefine_fn(ccx: &CrateContext<'a, 'tcx>,
163                     instance: Instance<'tcx>,
164                     linkage: llvm::Linkage,
165                     symbol_name: &str) {
166         assert!(!instance.substs.needs_infer() &&
167                 !instance.substs.has_param_types());
168
169         let mono_ty = common::instance_ty(ccx.shared(), &instance);
170         let attrs = instance.def.attrs(ccx.tcx());
171         let lldecl = declare::declare_fn(ccx, symbol_name, mono_ty);
172         unsafe { llvm::LLVMRustSetLinkage(lldecl, linkage) };
173         base::set_link_section(ccx, lldecl, &attrs);
174         if linkage == llvm::Linkage::LinkOnceODRLinkage ||
175             linkage == llvm::Linkage::WeakODRLinkage {
176             llvm::SetUniqueComdat(ccx.llmod(), lldecl);
177         }
178
179         debug!("predefine_fn: mono_ty = {:?} instance = {:?}", mono_ty, instance);
180         if common::is_inline_instance(ccx.tcx(), &instance) {
181             attributes::inline(lldecl, attributes::InlineAttr::Hint);
182         }
183         attributes::from_fn_attrs(ccx, &attrs, lldecl);
184
185         ccx.instances().borrow_mut().insert(instance, lldecl);
186     }
187
188     pub fn symbol_name(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> ty::SymbolName {
189         match *self {
190             TransItem::Fn(instance) => tcx.symbol_name(instance),
191             TransItem::Static(node_id) => {
192                 let def_id = tcx.hir.local_def_id(node_id);
193                 tcx.symbol_name(Instance::mono(tcx, def_id))
194             }
195             TransItem::GlobalAsm(node_id) => {
196                 let def_id = tcx.hir.local_def_id(node_id);
197                 ty::SymbolName {
198                     name: Symbol::intern(&format!("global_asm_{:?}", def_id)).as_str()
199                 }
200             }
201         }
202     }
203
204     pub fn local_span(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<Span> {
205         match *self {
206             TransItem::Fn(Instance { def, .. }) => {
207                 tcx.hir.as_local_node_id(def.def_id())
208             }
209             TransItem::Static(node_id) |
210             TransItem::GlobalAsm(node_id) => {
211                 Some(node_id)
212             }
213         }.map(|node_id| tcx.hir.span(node_id))
214     }
215
216     pub fn instantiation_mode(&self,
217                               tcx: TyCtxt<'a, 'tcx, 'tcx>)
218                               -> InstantiationMode {
219         match *self {
220             TransItem::Fn(ref instance) => {
221                 if self.explicit_linkage(tcx).is_none() &&
222                     common::requests_inline(tcx, instance)
223                 {
224                     InstantiationMode::LocalCopy
225                 } else {
226                     InstantiationMode::GloballyShared
227                 }
228             }
229             TransItem::Static(..) => InstantiationMode::GloballyShared,
230             TransItem::GlobalAsm(..) => InstantiationMode::GloballyShared,
231         }
232     }
233
234     pub fn is_generic_fn(&self) -> bool {
235         match *self {
236             TransItem::Fn(ref instance) => {
237                 instance.substs.types().next().is_some()
238             }
239             TransItem::Static(..) |
240             TransItem::GlobalAsm(..) => false,
241         }
242     }
243
244     pub fn explicit_linkage(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<llvm::Linkage> {
245         let def_id = match *self {
246             TransItem::Fn(ref instance) => instance.def_id(),
247             TransItem::Static(node_id) => tcx.hir.local_def_id(node_id),
248             TransItem::GlobalAsm(..) => return None,
249         };
250
251         let attributes = tcx.get_attrs(def_id);
252         if let Some(name) = attr::first_attr_value_str_by_name(&attributes, "linkage") {
253             if let Some(linkage) = base::llvm_linkage_by_name(&name.as_str()) {
254                 Some(linkage)
255             } else {
256                 let span = tcx.hir.span_if_local(def_id);
257                 if let Some(span) = span {
258                     tcx.sess.span_fatal(span, "invalid linkage specified")
259                 } else {
260                     tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
261                 }
262             }
263         } else {
264             None
265         }
266     }
267
268     pub fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> String {
269         let hir_map = &tcx.hir;
270
271         return match *self {
272             TransItem::Fn(instance) => {
273                 to_string_internal(tcx, "fn ", instance)
274             },
275             TransItem::Static(node_id) => {
276                 let def_id = hir_map.local_def_id(node_id);
277                 let instance = Instance::new(def_id, tcx.intern_substs(&[]));
278                 to_string_internal(tcx, "static ", instance)
279             },
280             TransItem::GlobalAsm(..) => {
281                 "global_asm".to_string()
282             }
283         };
284
285         fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
286                                         prefix: &str,
287                                         instance: Instance<'tcx>)
288                                         -> String {
289             let mut result = String::with_capacity(32);
290             result.push_str(prefix);
291             let printer = DefPathBasedNames::new(tcx, false, false);
292             printer.push_instance_as_string(instance, &mut result);
293             result
294         }
295     }
296
297     pub fn to_raw_string(&self) -> String {
298         match *self {
299             TransItem::Fn(instance) => {
300                 format!("Fn({:?}, {})",
301                          instance.def,
302                          instance.substs.as_ptr() as usize)
303             }
304             TransItem::Static(id) => {
305                 format!("Static({:?})", id)
306             }
307             TransItem::GlobalAsm(id) => {
308                 format!("GlobalAsm({:?})", id)
309             }
310         }
311     }
312 }
313
314
315 //=-----------------------------------------------------------------------------
316 // TransItem String Keys
317 //=-----------------------------------------------------------------------------
318
319 // The code below allows for producing a unique string key for a trans item.
320 // These keys are used by the handwritten auto-tests, so they need to be
321 // predictable and human-readable.
322 //
323 // Note: A lot of this could looks very similar to what's already in the
324 //       ppaux module. It would be good to refactor things so we only have one
325 //       parameterizable implementation for printing types.
326
327 /// Same as `unique_type_name()` but with the result pushed onto the given
328 /// `output` parameter.
329 pub struct DefPathBasedNames<'a, 'tcx: 'a> {
330     tcx: TyCtxt<'a, 'tcx, 'tcx>,
331     omit_disambiguators: bool,
332     omit_local_crate_name: bool,
333 }
334
335 impl<'a, 'tcx> DefPathBasedNames<'a, 'tcx> {
336     pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
337                omit_disambiguators: bool,
338                omit_local_crate_name: bool)
339                -> Self {
340         DefPathBasedNames {
341             tcx: tcx,
342             omit_disambiguators: omit_disambiguators,
343             omit_local_crate_name: omit_local_crate_name,
344         }
345     }
346
347     pub fn push_type_name(&self, t: Ty<'tcx>, output: &mut String) {
348         match t.sty {
349             ty::TyBool              => output.push_str("bool"),
350             ty::TyChar              => output.push_str("char"),
351             ty::TyStr               => output.push_str("str"),
352             ty::TyNever             => output.push_str("!"),
353             ty::TyInt(ast::IntTy::Is)    => output.push_str("isize"),
354             ty::TyInt(ast::IntTy::I8)    => output.push_str("i8"),
355             ty::TyInt(ast::IntTy::I16)   => output.push_str("i16"),
356             ty::TyInt(ast::IntTy::I32)   => output.push_str("i32"),
357             ty::TyInt(ast::IntTy::I64)   => output.push_str("i64"),
358             ty::TyInt(ast::IntTy::I128)   => output.push_str("i128"),
359             ty::TyUint(ast::UintTy::Us)   => output.push_str("usize"),
360             ty::TyUint(ast::UintTy::U8)   => output.push_str("u8"),
361             ty::TyUint(ast::UintTy::U16)  => output.push_str("u16"),
362             ty::TyUint(ast::UintTy::U32)  => output.push_str("u32"),
363             ty::TyUint(ast::UintTy::U64)  => output.push_str("u64"),
364             ty::TyUint(ast::UintTy::U128)  => output.push_str("u128"),
365             ty::TyFloat(ast::FloatTy::F32) => output.push_str("f32"),
366             ty::TyFloat(ast::FloatTy::F64) => output.push_str("f64"),
367             ty::TyAdt(adt_def, substs) => {
368                 self.push_def_path(adt_def.did, output);
369                 self.push_type_params(substs, iter::empty(), output);
370             },
371             ty::TyTuple(component_types, _) => {
372                 output.push('(');
373                 for &component_type in component_types {
374                     self.push_type_name(component_type, output);
375                     output.push_str(", ");
376                 }
377                 if !component_types.is_empty() {
378                     output.pop();
379                     output.pop();
380                 }
381                 output.push(')');
382             },
383             ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
384                 output.push('*');
385                 match mutbl {
386                     hir::MutImmutable => output.push_str("const "),
387                     hir::MutMutable => output.push_str("mut "),
388                 }
389
390                 self.push_type_name(inner_type, output);
391             },
392             ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
393                 output.push('&');
394                 if mutbl == hir::MutMutable {
395                     output.push_str("mut ");
396                 }
397
398                 self.push_type_name(inner_type, output);
399             },
400             ty::TyArray(inner_type, len) => {
401                 output.push('[');
402                 self.push_type_name(inner_type, output);
403                 write!(output, "; {}", len).unwrap();
404                 output.push(']');
405             },
406             ty::TySlice(inner_type) => {
407                 output.push('[');
408                 self.push_type_name(inner_type, output);
409                 output.push(']');
410             },
411             ty::TyDynamic(ref trait_data, ..) => {
412                 if let Some(principal) = trait_data.principal() {
413                     self.push_def_path(principal.def_id(), output);
414                     self.push_type_params(principal.skip_binder().substs,
415                         trait_data.projection_bounds(),
416                         output);
417                 }
418             },
419             ty::TyFnDef(.., sig) |
420             ty::TyFnPtr(sig) => {
421                 if sig.unsafety() == hir::Unsafety::Unsafe {
422                     output.push_str("unsafe ");
423                 }
424
425                 let abi = sig.abi();
426                 if abi != ::abi::Abi::Rust {
427                     output.push_str("extern \"");
428                     output.push_str(abi.name());
429                     output.push_str("\" ");
430                 }
431
432                 output.push_str("fn(");
433
434                 let sig = self.tcx.erase_late_bound_regions_and_normalize(&sig);
435
436                 if !sig.inputs().is_empty() {
437                     for &parameter_type in sig.inputs() {
438                         self.push_type_name(parameter_type, output);
439                         output.push_str(", ");
440                     }
441                     output.pop();
442                     output.pop();
443                 }
444
445                 if sig.variadic {
446                     if !sig.inputs().is_empty() {
447                         output.push_str(", ...");
448                     } else {
449                         output.push_str("...");
450                     }
451                 }
452
453                 output.push(')');
454
455                 if !sig.output().is_nil() {
456                     output.push_str(" -> ");
457                     self.push_type_name(sig.output(), output);
458                 }
459             },
460             ty::TyClosure(def_id, ref closure_substs) => {
461                 self.push_def_path(def_id, output);
462                 let generics = self.tcx.generics_of(self.tcx.closure_base_def_id(def_id));
463                 let substs = closure_substs.substs.truncate_to(self.tcx, generics);
464                 self.push_type_params(substs, iter::empty(), output);
465             }
466             ty::TyError |
467             ty::TyInfer(_) |
468             ty::TyProjection(..) |
469             ty::TyParam(_) |
470             ty::TyAnon(..) => {
471                 bug!("DefPathBasedNames: Trying to create type name for \
472                                          unexpected type: {:?}", t);
473             }
474         }
475     }
476
477     pub fn push_def_path(&self,
478                          def_id: DefId,
479                          output: &mut String) {
480         let def_path = self.tcx.def_path(def_id);
481
482         // some_crate::
483         if !(self.omit_local_crate_name && def_id.is_local()) {
484             output.push_str(&self.tcx.crate_name(def_path.krate).as_str());
485             output.push_str("::");
486         }
487
488         // foo::bar::ItemName::
489         for part in self.tcx.def_path(def_id).data {
490             if self.omit_disambiguators {
491                 write!(output, "{}::", part.data.as_interned_str()).unwrap();
492             } else {
493                 write!(output, "{}[{}]::",
494                        part.data.as_interned_str(),
495                        part.disambiguator).unwrap();
496             }
497         }
498
499         // remove final "::"
500         output.pop();
501         output.pop();
502     }
503
504     fn push_type_params<I>(&self,
505                             substs: &Substs<'tcx>,
506                             projections: I,
507                             output: &mut String)
508         where I: Iterator<Item=ty::PolyExistentialProjection<'tcx>>
509     {
510         let mut projections = projections.peekable();
511         if substs.types().next().is_none() && projections.peek().is_none() {
512             return;
513         }
514
515         output.push('<');
516
517         for type_parameter in substs.types() {
518             self.push_type_name(type_parameter, output);
519             output.push_str(", ");
520         }
521
522         for projection in projections {
523             let projection = projection.skip_binder();
524             let name = &projection.item_name.as_str();
525             output.push_str(name);
526             output.push_str("=");
527             self.push_type_name(projection.ty, output);
528             output.push_str(", ");
529         }
530
531         output.pop();
532         output.pop();
533
534         output.push('>');
535     }
536
537     pub fn push_instance_as_string(&self,
538                                    instance: Instance<'tcx>,
539                                    output: &mut String) {
540         self.push_def_path(instance.def_id(), output);
541         self.push_type_params(instance.substs, iter::empty(), output);
542     }
543 }