1 // Copyright 2012-2014 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.
13 use rustc::hir::def_id::DefId;
14 use rustc::infer::TransNormalize;
16 use rustc::ty::subst::{Subst, Substs};
17 use rustc::ty::{self, Ty, TypeFoldable, TyCtxt};
19 use base::{push_ctxt};
24 use rustc::hir::map as hir_map;
25 use rustc::util::ppaux;
32 use trans_item::TransItem;
34 pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
36 psubsts: &'tcx subst::Substs<'tcx>)
37 -> (ValueRef, Ty<'tcx>) {
38 debug!("monomorphic_fn(fn_id={:?}, real_substs={:?})", fn_id, psubsts);
39 assert!(!psubsts.types.needs_infer() && !psubsts.types.has_param_types());
41 let _icx = push_ctxt("monomorphic_fn");
43 let instance = Instance::new(fn_id, psubsts);
45 let item_ty = ccx.tcx().lookup_item_type(fn_id).ty;
47 debug!("monomorphic_fn about to subst into {:?}", item_ty);
48 let mono_ty = apply_param_substs(ccx.tcx(), psubsts, &item_ty);
49 debug!("mono_ty = {:?} (post-substitution)", mono_ty);
51 if let Some(&val) = ccx.instances().borrow().get(&instance) {
52 debug!("leaving monomorphic fn {:?}", instance);
53 return (val, mono_ty);
55 assert!(!ccx.codegen_unit().items.contains_key(&TransItem::Fn(instance)));
58 debug!("monomorphic_fn({:?})", instance);
60 ccx.stats().n_monos.set(ccx.stats().n_monos.get() + 1);
64 let mut monomorphizing = ccx.monomorphizing().borrow_mut();
65 depth = match monomorphizing.get(&fn_id) {
66 Some(&d) => d, None => 0
69 debug!("monomorphic_fn: depth for fn_id={:?} is {:?}", fn_id, depth+1);
71 // Random cut-off -- code that needs to instantiate the same function
72 // recursively more than thirty times can probably safely be assumed
73 // to be causing an infinite expansion.
74 if depth > ccx.sess().recursion_limit.get() {
75 let error = format!("reached the recursion limit while instantiating `{}`",
77 if let Some(id) = ccx.tcx().map.as_local_node_id(fn_id) {
78 ccx.sess().span_fatal(ccx.tcx().map.span(id), &error);
80 ccx.sess().fatal(&error);
84 monomorphizing.insert(fn_id, depth + 1);
87 let symbol = ccx.symbol_map().get_or_compute(ccx.shared(),
88 TransItem::Fn(instance));
90 debug!("monomorphize_fn mangled to {}", &symbol);
91 assert!(declare::get_defined_value(ccx, &symbol).is_none());
93 // FIXME(nagisa): perhaps needs a more fine grained selection?
94 let lldecl = declare::define_internal_fn(ccx, &symbol, mono_ty);
95 // FIXME(eddyb) Doubt all extern fn should allow unwinding.
96 attributes::unwind(lldecl, true);
98 ccx.instances().borrow_mut().insert(instance, lldecl);
100 // we can only monomorphize things in this crate (or inlined into it)
101 let fn_node_id = ccx.tcx().map.as_local_node_id(fn_id).unwrap();
102 let map_node = errors::expect(
103 ccx.sess().diagnostic(),
104 ccx.tcx().map.find(fn_node_id),
106 format!("while instantiating `{}`, couldn't find it in \
107 the item map (may have attempted to monomorphize \
108 an item defined in a different crate?)",
112 hir_map::NodeItem(&hir::Item {
114 node: hir::ItemFn(..), ..
116 hir_map::NodeImplItem(&hir::ImplItem {
117 ref attrs, node: hir::ImplItemKind::Method(
118 hir::MethodSig { .. }, _), ..
120 hir_map::NodeTraitItem(&hir::TraitItem {
121 ref attrs, node: hir::MethodTraitItem(
122 hir::MethodSig { .. }, Some(_)), ..
124 let trans_item = TransItem::Fn(instance);
126 if ccx.shared().translation_items().borrow().contains_key(&trans_item) {
127 attributes::from_fn_attrs(ccx, attrs, lldecl);
128 llvm::SetLinkage(lldecl, llvm::ExternalLinkage);
131 // Normally, getting here would indicate a bug in trans::collector,
132 // since it seems to have missed a translation item. When we are
133 // translating with non-MIR based trans, however, the results of
134 // the collector are not entirely reliable since it bases its
135 // analysis on MIR. Thus, we'll instantiate the missing function
136 // privately in this codegen unit, so that things keep working.
137 ccx.stats().n_fallback_instantiations.set(ccx.stats()
138 .n_fallback_instantiations
140 trans_item.predefine(ccx, llvm::PrivateLinkage);
141 trans_item.define(ccx);
145 hir_map::NodeVariant(_) | hir_map::NodeStructCtor(_) => {
146 let disr = match map_node {
147 hir_map::NodeVariant(_) => {
148 Disr::from(inlined_variant_def(ccx, fn_node_id).disr_val)
150 hir_map::NodeStructCtor(_) => Disr(0),
153 attributes::inline(lldecl, attributes::InlineAttr::Hint);
154 attributes::set_frame_pointer_elimination(ccx, lldecl);
155 base::trans_ctor_shim(ccx, fn_node_id, disr, psubsts, lldecl);
158 _ => bug!("can't monomorphize a {:?}", map_node)
161 ccx.monomorphizing().borrow_mut().insert(fn_id, depth);
163 debug!("leaving monomorphic fn {}", ccx.tcx().item_path_str(fn_id));
167 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
168 pub struct Instance<'tcx> {
170 pub substs: &'tcx Substs<'tcx>,
173 impl<'tcx> fmt::Display for Instance<'tcx> {
174 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
175 ppaux::parameterized(f, &self.substs, self.def, ppaux::Ns::Value, &[], |_| None)
179 impl<'tcx> Instance<'tcx> {
180 pub fn new(def_id: DefId, substs: &'tcx Substs<'tcx>)
182 assert!(substs.regions.iter().all(|&r| r == ty::ReErased));
183 Instance { def: def_id, substs: substs }
185 pub fn mono<'a>(scx: &SharedCrateContext<'a, 'tcx>, def_id: DefId) -> Instance<'tcx> {
186 Instance::new(def_id, scx.empty_substs_for_def_id(def_id))
190 /// Monomorphizes a type from the AST by first applying the in-scope
191 /// substitutions and then normalizing any associated types.
192 pub fn apply_param_substs<'a, 'tcx, T>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
193 param_substs: &Substs<'tcx>,
196 where T: TransNormalize<'tcx>
198 let substituted = value.subst(tcx, param_substs);
199 tcx.normalize_associated_type(&substituted)
203 /// Returns the normalized type of a struct field
204 pub fn field_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
205 param_substs: &Substs<'tcx>,
206 f: ty::FieldDef<'tcx>)
209 tcx.normalize_associated_type(&f.ty(tcx, param_substs))