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