]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans_item.rs
Rollup merge of #40229 - cramertj:break-to-blocks, r=nikomatsakis
[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 attributes;
18 use base;
19 use consts;
20 use context::{CrateContext, SharedCrateContext};
21 use common;
22 use declare;
23 use llvm;
24 use monomorphize::Instance;
25 use rustc::dep_graph::DepNode;
26 use rustc::hir;
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};
32 use syntax::attr;
33 use type_of;
34 use back::symbol_names;
35 use std::fmt::Write;
36 use std::iter;
37
38 #[derive(PartialEq, Eq, Clone, Copy, Debug, Hash)]
39 pub enum TransItem<'tcx> {
40     Fn(Instance<'tcx>),
41     Static(NodeId)
42 }
43
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.
49     GloballyShared,
50
51     /// Each codegen unit containing a reference to the given TransItem will
52     /// have its own private copy of the function (with internal linkage).
53     LocalCopy,
54 }
55
56 impl<'a, 'tcx> TransItem<'tcx> {
57
58     pub fn define(&self, ccx: &CrateContext<'a, 'tcx>) {
59         debug!("BEGIN IMPLEMENTING '{} ({})' in cgu {}",
60                   self.to_string(ccx.tcx()),
61                   self.to_raw_string(),
62                   ccx.codegen_unit().name());
63
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
72         // particular set.
73
74         match *self {
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. */ },
82                         Err(err) => {
83                             // FIXME: shouldn't this be a `span_err`?
84                             fatal_const_eval_err(
85                                 ccx.tcx(), &err, item.span, "static");
86                         }
87                     };
88                 } else {
89                     span_bug!(item.span, "Mismatch between hir::Item type and TransItem type")
90                 }
91             }
92             TransItem::Fn(instance) => {
93                 let _task = ccx.tcx().dep_graph.in_task(
94                     DepNode::TransCrateItem(instance.def_id())); // (*)
95
96                 base::trans_instance(&ccx, instance);
97             }
98         }
99
100         debug!("END IMPLEMENTING '{} ({})' in cgu {}",
101                self.to_string(ccx.tcx()),
102                self.to_raw_string(),
103                ccx.codegen_unit().name());
104     }
105
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());
113
114         let symbol_name = ccx.symbol_map()
115                              .get_or_compute(ccx.shared(), *self);
116
117         debug!("symbol {}", &symbol_name);
118
119         match *self {
120             TransItem::Static(node_id) => {
121                 TransItem::predefine_static(ccx, node_id, linkage, &symbol_name);
122             }
123             TransItem::Fn(instance) => {
124                 TransItem::predefine_fn(ccx, instance, linkage, &symbol_name);
125             }
126         }
127
128         debug!("END PREDEFINING '{} ({})' in cgu {}",
129                self.to_string(ccx.tcx()),
130                self.to_raw_string(),
131                ccx.codegen_unit().name());
132     }
133
134     fn predefine_static(ccx: &CrateContext<'a, 'tcx>,
135                         node_id: ast::NodeId,
136                         linkage: llvm::Linkage,
137                         symbol_name: &str) {
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);
142
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))
146         });
147
148         unsafe { llvm::LLVMRustSetLinkage(g, linkage) };
149
150         ccx.instances().borrow_mut().insert(instance, g);
151         ccx.statics().borrow_mut().insert(g, def_id);
152     }
153
154     fn predefine_fn(ccx: &CrateContext<'a, 'tcx>,
155                     instance: Instance<'tcx>,
156                     linkage: llvm::Linkage,
157                     symbol_name: &str) {
158         assert!(!instance.substs.needs_infer() &&
159                 !instance.substs.has_param_types());
160
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);
169         }
170
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);
174         }
175         attributes::from_fn_attrs(ccx, &attrs, lldecl);
176
177         ccx.instances().borrow_mut().insert(instance, lldecl);
178     }
179
180     pub fn compute_symbol_name(&self,
181                                scx: &SharedCrateContext<'a, 'tcx>) -> String {
182         match *self {
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)
187             }
188         }
189     }
190
191     pub fn instantiation_mode(&self,
192                               tcx: TyCtxt<'a, 'tcx, 'tcx>)
193                               -> InstantiationMode {
194         match *self {
195             TransItem::Fn(ref instance) => {
196                 if self.explicit_linkage(tcx).is_none() &&
197                     common::requests_inline(tcx, instance)
198                 {
199                     InstantiationMode::LocalCopy
200                 } else {
201                     InstantiationMode::GloballyShared
202                 }
203             }
204             TransItem::Static(..) => InstantiationMode::GloballyShared,
205         }
206     }
207
208     pub fn is_generic_fn(&self) -> bool {
209         match *self {
210             TransItem::Fn(ref instance) => {
211                 instance.substs.types().next().is_some()
212             }
213             TransItem::Static(..)   => false,
214         }
215     }
216
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),
221         };
222
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()) {
226                 Some(linkage)
227             } else {
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")
231                 } else {
232                     tcx.sess.fatal(&format!("invalid linkage specified: {}", name))
233                 }
234             }
235         } else {
236             None
237         }
238     }
239
240     pub fn to_string(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> String {
241         let hir_map = &tcx.hir;
242
243         return match *self {
244             TransItem::Fn(instance) => {
245                 to_string_internal(tcx, "fn ", instance)
246             },
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)
251             },
252         };
253
254         fn to_string_internal<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
255                                         prefix: &str,
256                                         instance: Instance<'tcx>)
257                                         -> String {
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);
262             result
263         }
264     }
265
266     pub fn to_raw_string(&self) -> String {
267         match *self {
268             TransItem::Fn(instance) => {
269                 format!("Fn({:?}, {})",
270                          instance.def,
271                          instance.substs.as_ptr() as usize)
272             }
273             TransItem::Static(id) => {
274                 format!("Static({:?})", id)
275             }
276         }
277     }
278 }
279
280
281 //=-----------------------------------------------------------------------------
282 // TransItem String Keys
283 //=-----------------------------------------------------------------------------
284
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.
288 //
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.
292
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,
299 }
300
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)
305                -> Self {
306         DefPathBasedNames {
307             tcx: tcx,
308             omit_disambiguators: omit_disambiguators,
309             omit_local_crate_name: omit_local_crate_name,
310         }
311     }
312
313     pub fn push_type_name(&self, t: Ty<'tcx>, output: &mut String) {
314         match t.sty {
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);
336             },
337             ty::TyTuple(component_types, _) => {
338                 output.push('(');
339                 for &component_type in component_types {
340                     self.push_type_name(component_type, output);
341                     output.push_str(", ");
342                 }
343                 if !component_types.is_empty() {
344                     output.pop();
345                     output.pop();
346                 }
347                 output.push(')');
348             },
349             ty::TyRawPtr(ty::TypeAndMut { ty: inner_type, mutbl } ) => {
350                 output.push('*');
351                 match mutbl {
352                     hir::MutImmutable => output.push_str("const "),
353                     hir::MutMutable => output.push_str("mut "),
354                 }
355
356                 self.push_type_name(inner_type, output);
357             },
358             ty::TyRef(_, ty::TypeAndMut { ty: inner_type, mutbl }) => {
359                 output.push('&');
360                 if mutbl == hir::MutMutable {
361                     output.push_str("mut ");
362                 }
363
364                 self.push_type_name(inner_type, output);
365             },
366             ty::TyArray(inner_type, len) => {
367                 output.push('[');
368                 self.push_type_name(inner_type, output);
369                 write!(output, "; {}", len).unwrap();
370                 output.push(']');
371             },
372             ty::TySlice(inner_type) => {
373                 output.push('[');
374                 self.push_type_name(inner_type, output);
375                 output.push(']');
376             },
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(),
382                         output);
383                 }
384             },
385             ty::TyFnDef(.., sig) |
386             ty::TyFnPtr(sig) => {
387                 if sig.unsafety() == hir::Unsafety::Unsafe {
388                     output.push_str("unsafe ");
389                 }
390
391                 let abi = sig.abi();
392                 if abi != ::abi::Abi::Rust {
393                     output.push_str("extern \"");
394                     output.push_str(abi.name());
395                     output.push_str("\" ");
396                 }
397
398                 output.push_str("fn(");
399
400                 let sig = self.tcx.erase_late_bound_regions_and_normalize(&sig);
401
402                 if !sig.inputs().is_empty() {
403                     for &parameter_type in sig.inputs() {
404                         self.push_type_name(parameter_type, output);
405                         output.push_str(", ");
406                     }
407                     output.pop();
408                     output.pop();
409                 }
410
411                 if sig.variadic {
412                     if !sig.inputs().is_empty() {
413                         output.push_str(", ...");
414                     } else {
415                         output.push_str("...");
416                     }
417                 }
418
419                 output.push(')');
420
421                 if !sig.output().is_nil() {
422                     output.push_str(" -> ");
423                     self.push_type_name(sig.output(), output);
424                 }
425             },
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);
431             }
432             ty::TyError |
433             ty::TyInfer(_) |
434             ty::TyProjection(..) |
435             ty::TyParam(_) |
436             ty::TyAnon(..) => {
437                 bug!("DefPathBasedNames: Trying to create type name for \
438                                          unexpected type: {:?}", t);
439             }
440         }
441     }
442
443     pub fn push_def_path(&self,
444                          def_id: DefId,
445                          output: &mut String) {
446         let def_path = self.tcx.def_path(def_id);
447
448         // some_crate::
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("::");
452         }
453
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();
458             } else {
459                 write!(output, "{}[{}]::",
460                        part.data.as_interned_str(),
461                        part.disambiguator).unwrap();
462             }
463         }
464
465         // remove final "::"
466         output.pop();
467         output.pop();
468     }
469
470     fn push_type_params<I>(&self,
471                             substs: &Substs<'tcx>,
472                             projections: I,
473                             output: &mut String)
474         where I: Iterator<Item=ty::PolyExistentialProjection<'tcx>>
475     {
476         let mut projections = projections.peekable();
477         if substs.types().next().is_none() && projections.peek().is_none() {
478             return;
479         }
480
481         output.push('<');
482
483         for type_parameter in substs.types() {
484             self.push_type_name(type_parameter, output);
485             output.push_str(", ");
486         }
487
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(", ");
495         }
496
497         output.pop();
498         output.pop();
499
500         output.push('>');
501     }
502
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);
508     }
509 }