1 // Copyright 2012 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 use back::link::exported_name;
13 use lib::llvm::ValueRef;
15 use middle::subst::Subst;
16 use middle::trans::base::{set_llvm_fn_attrs, set_inline_hint};
17 use middle::trans::base::{trans_enum_variant, push_ctxt, get_item_val};
18 use middle::trans::base::{trans_fn, decl_internal_rust_fn};
19 use middle::trans::base;
20 use middle::trans::common::*;
21 use middle::trans::intrinsic;
24 use util::ppaux::Repr;
29 use syntax::ast_util::local_def;
30 use std::hash::{sip, Hash};
32 pub fn monomorphic_fn(ccx: &CrateContext,
34 real_substs: &subst::Substs,
35 vtables: typeck::vtable_res,
36 self_vtables: Option<typeck::vtable_param_res>,
37 ref_id: Option<ast::NodeId>)
39 debug!("monomorphic_fn(\
45 fn_id.repr(ccx.tcx()),
46 real_substs.repr(ccx.tcx()),
47 vtables.repr(ccx.tcx()),
48 self_vtables.repr(ccx.tcx()),
51 assert!(real_substs.tps.iter().all(|t| {
52 !ty::type_needs_infer(*t) && !ty::type_has_params(*t)
55 let _icx = push_ctxt("monomorphic_fn");
57 let substs_iter = real_substs.self_ty.iter().chain(real_substs.tps.iter());
58 let param_ids: Vec<ty::t> = substs_iter.map(|t| *t).collect();
59 let hash_id = MonoId {
64 match ccx.monomorphized.borrow().find(&hash_id) {
66 debug!("leaving monomorphic fn {}",
67 ty::item_path_str(ccx.tcx(), fn_id));
73 let psubsts = param_substs {
74 substs: (*real_substs).clone(),
76 self_vtables: self_vtables
79 debug!("monomorphic_fn(\
83 fn_id.repr(ccx.tcx()),
84 psubsts.repr(ccx.tcx()),
87 let tpt = ty::lookup_item_type(ccx.tcx(), fn_id);
88 let llitem_ty = tpt.ty;
90 // We need to do special handling of the substitutions if we are
91 // calling a static provided method. This is sort of unfortunate.
92 let mut is_static_provided = None;
94 let map_node = session::expect(
96 ccx.tcx.map.find(fn_id.node),
98 format!("while monomorphizing {:?}, couldn't find it in \
99 the item map (may have attempted to monomorphize \
100 an item defined in a different crate?)",
105 ast_map::NodeForeignItem(_) => {
106 if ccx.tcx.map.get_foreign_abi(fn_id.node) != abi::RustIntrinsic {
107 // Foreign externs don't have to be monomorphized.
108 return (get_item_val(ccx, fn_id.node), true);
111 ast_map::NodeTraitMethod(method) => {
113 ast::Provided(m) => {
114 // If this is a static provided method, indicate that
115 // and stash the number of params on the method.
116 if m.explicit_self.node == ast::SelfStatic {
117 is_static_provided = Some(m.generics.ty_params.len());
126 debug!("monomorphic_fn about to subst into {}", llitem_ty.repr(ccx.tcx()));
127 let mono_ty = match is_static_provided {
128 None => llitem_ty.subst(ccx.tcx(), real_substs),
129 Some(num_method_ty_params) => {
130 // Static default methods are a little unfortunate, in
131 // that the "internal" and "external" type of them differ.
132 // Internally, the method body can refer to Self, but the
133 // externally visible type of the method has a type param
134 // inserted in between the trait type params and the
135 // method type params. The substs that we are given are
136 // the proper substs *internally* to the method body, so
137 // we have to use those when compiling it.
139 // In order to get the proper substitution to use on the
140 // type of the method, we pull apart the substitution and
141 // stick a substitution for the self type in.
142 // This is a bit unfortunate.
144 let idx = real_substs.tps.len() - num_method_ty_params;
145 let mut tps = Vec::new();
146 tps.push_all(real_substs.tps.slice(0, idx));
147 tps.push(real_substs.self_ty.unwrap());
148 tps.push_all(real_substs.tps.tailn(idx));
150 let substs = subst::Substs { regions: subst::ErasedRegions,
154 debug!("static default: changed substitution to {}",
155 substs.repr(ccx.tcx()));
157 llitem_ty.subst(ccx.tcx(), &substs)
161 ccx.stats.n_monos.set(ccx.stats.n_monos.get() + 1);
165 let mut monomorphizing = ccx.monomorphizing.borrow_mut();
166 depth = match monomorphizing.find(&fn_id) {
167 Some(&d) => d, None => 0
170 // Random cut-off -- code that needs to instantiate the same function
171 // recursively more than thirty times can probably safely be assumed
172 // to be causing an infinite expansion.
173 if depth > ccx.sess().recursion_limit.get() {
174 ccx.sess().span_fatal(ccx.tcx.map.span(fn_id.node),
175 "reached the recursion limit during monomorphization");
178 monomorphizing.insert(fn_id, depth + 1);
181 let s = ccx.tcx.map.with_path(fn_id.node, |path| {
182 let mut state = sip::SipState::new();
183 hash_id.hash(&mut state);
184 mono_ty.hash(&mut state);
187 format!("h{}", state.result()).as_slice(),
188 ccx.link_meta.crateid.version_or_default())
190 debug!("monomorphize_fn mangled to {}", s);
192 // This shouldn't need to option dance.
193 let mut hash_id = Some(hash_id);
195 let lldecl = decl_internal_rust_fn(ccx, mono_ty, s.as_slice());
196 ccx.monomorphized.borrow_mut().insert(hash_id.take_unwrap(), lldecl);
200 let lldecl = match map_node {
201 ast_map::NodeItem(i) => {
204 node: ast::ItemFn(ref decl, _, _, _, ref body),
208 set_llvm_fn_attrs(i.attrs.as_slice(), d);
209 trans_fn(ccx, &**decl, &**body, d, &psubsts, fn_id.node, []);
213 ccx.sess().bug("Can't monomorphize this kind of item")
217 ast_map::NodeForeignItem(i) => {
218 let simple = intrinsic::get_simple_intrinsic(ccx, &*i);
223 intrinsic::trans_intrinsic(ccx, d, &*i, &psubsts, ref_id);
228 ast_map::NodeVariant(v) => {
229 let parent = ccx.tcx.map.get_parent(fn_id.node);
230 let tvs = ty::enum_variants(ccx.tcx(), local_def(parent));
231 let this_tv = tvs.iter().find(|tv| { tv.id.node == fn_id.node}).unwrap();
235 ast::TupleVariantKind(ref args) => {
236 trans_enum_variant(ccx,
244 ast::StructVariantKind(_) =>
245 ccx.sess().bug("can't monomorphize struct variants"),
249 ast_map::NodeMethod(mth) => {
251 set_llvm_fn_attrs(mth.attrs.as_slice(), d);
252 trans_fn(ccx, &*mth.decl, &*mth.body, d, &psubsts, mth.id, []);
255 ast_map::NodeTraitMethod(method) => {
257 ast::Provided(mth) => {
259 set_llvm_fn_attrs(mth.attrs.as_slice(), d);
260 trans_fn(ccx, &*mth.decl, &*mth.body, d, &psubsts, mth.id, []);
264 ccx.sess().bug(format!("can't monomorphize a {:?}",
265 map_node).as_slice())
269 ast_map::NodeStructCtor(struct_def) => {
272 base::trans_tuple_struct(ccx,
273 struct_def.fields.as_slice(),
274 struct_def.ctor_id.expect("ast-mapped tuple struct \
275 didn't have a ctor id"),
281 // Ugh -- but this ensures any new variants won't be forgotten
282 ast_map::NodeLifetime(..) |
283 ast_map::NodeExpr(..) |
284 ast_map::NodeStmt(..) |
285 ast_map::NodeArg(..) |
286 ast_map::NodeBlock(..) |
287 ast_map::NodePat(..) |
288 ast_map::NodeLocal(..) => {
289 ccx.sess().bug(format!("can't monomorphize a {:?}",
290 map_node).as_slice())
294 ccx.monomorphizing.borrow_mut().insert(fn_id, depth);
296 debug!("leaving monomorphic fn {}", ty::item_path_str(ccx.tcx(), fn_id));
300 // Used to identify cached monomorphized functions and vtables
301 #[deriving(PartialEq, Eq, Hash)]
302 pub struct MonoParamId {
306 #[deriving(PartialEq, Eq, Hash)]
309 pub params: Vec<ty::t>
312 pub fn make_vtable_id(_ccx: &CrateContext,
313 origin: &typeck::vtable_origin)
316 &typeck::vtable_static(impl_id, ref substs, _) => {
319 params: substs.tps.iter().map(|subst| *subst).collect()
323 // can't this be checked at the callee?
324 _ => fail!("make_vtable_id needs vtable_static")