]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/monomorphize.rs
6f2dbc182b04f3000852d8196b3af4cbbef87bd5
[rust.git] / src / librustc / middle / trans / monomorphize.rs
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.
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
12 use back::link::mangle_exported_name;
13 use driver::session;
14 use lib::llvm::ValueRef;
15 use middle::trans::base::{set_llvm_fn_attrs, set_inline_hint};
16 use middle::trans::base::{trans_enum_variant, push_ctxt, get_item_val};
17 use middle::trans::base::{trans_fn, decl_internal_rust_fn};
18 use middle::trans::base;
19 use middle::trans::common::*;
20 use middle::trans::meth;
21 use middle::trans::intrinsic;
22 use middle::ty;
23 use middle::typeck;
24 use util::ppaux::Repr;
25
26 use syntax::abi;
27 use syntax::ast;
28 use syntax::ast_map;
29 use syntax::ast_util::local_def;
30
31 pub fn monomorphic_fn(ccx: &CrateContext,
32                       fn_id: ast::DefId,
33                       real_substs: &ty::substs,
34                       vtables: Option<typeck::vtable_res>,
35                       self_vtables: Option<typeck::vtable_param_res>,
36                       ref_id: Option<ast::NodeId>)
37     -> (ValueRef, bool) {
38     debug!("monomorphic_fn(\
39             fn_id={}, \
40             real_substs={}, \
41             vtables={}, \
42             self_vtable={}, \
43             ref_id={:?})",
44            fn_id.repr(ccx.tcx()),
45            real_substs.repr(ccx.tcx()),
46            vtables.repr(ccx.tcx()),
47            self_vtables.repr(ccx.tcx()),
48            ref_id);
49
50     assert!(real_substs.tps.iter().all(|t| !ty::type_needs_infer(*t)));
51     let _icx = push_ctxt("monomorphic_fn");
52     let mut must_cast = false;
53
54     let psubsts = @param_substs {
55         tys: real_substs.tps.clone(),
56         vtables: vtables,
57         self_ty: real_substs.self_ty.clone(),
58         self_vtables: self_vtables
59     };
60
61     for s in real_substs.tps.iter() { assert!(!ty::type_has_params(*s)); }
62     for s in psubsts.tys.iter() { assert!(!ty::type_has_params(*s)); }
63
64     let hash_id = make_mono_id(ccx, fn_id, &*psubsts);
65     if hash_id.params.iter().any(
66                 |p| match *p { mono_precise(_, _) => false, _ => true }) {
67         must_cast = true;
68     }
69
70     debug!("monomorphic_fn(\
71             fn_id={}, \
72             psubsts={}, \
73             hash_id={:?})",
74            fn_id.repr(ccx.tcx()),
75            psubsts.repr(ccx.tcx()),
76            hash_id);
77
78     match ccx.monomorphized.borrow().find(&hash_id) {
79         Some(&val) => {
80             debug!("leaving monomorphic fn {}",
81             ty::item_path_str(ccx.tcx(), fn_id));
82             return (val, must_cast);
83         }
84         None => ()
85     }
86
87     let tpt = ty::lookup_item_type(ccx.tcx(), fn_id);
88     let llitem_ty = tpt.ty;
89
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;
93
94     let map_node = session::expect(
95         ccx.sess(),
96         ccx.tcx.map.find(fn_id.node),
97         || format!("while monomorphizing {:?}, couldn't find it in the \
98                     item map (may have attempted to monomorphize an item \
99                     defined in a different crate?)", fn_id));
100
101     match map_node {
102         ast_map::NodeForeignItem(_) => {
103             if ccx.tcx.map.get_foreign_abi(fn_id.node) != abi::RustIntrinsic {
104                 // Foreign externs don't have to be monomorphized.
105                 return (get_item_val(ccx, fn_id.node), true);
106             }
107         }
108         ast_map::NodeTraitMethod(method) => {
109             match *method {
110                 ast::Provided(m) => {
111                     // If this is a static provided method, indicate that
112                     // and stash the number of params on the method.
113                     if m.explicit_self.node == ast::SelfStatic {
114                         is_static_provided = Some(m.generics.ty_params.len());
115                     }
116                 }
117                 _ => {}
118             }
119         }
120         _ => {}
121     }
122
123     debug!("monomorphic_fn about to subst into {}", llitem_ty.repr(ccx.tcx()));
124     let mono_ty = match is_static_provided {
125         None => ty::subst_tps(ccx.tcx(), psubsts.tys.as_slice(),
126                               psubsts.self_ty, llitem_ty),
127         Some(num_method_ty_params) => {
128             // Static default methods are a little unfortunate, in
129             // that the "internal" and "external" type of them differ.
130             // Internally, the method body can refer to Self, but the
131             // externally visable type of the method has a type param
132             // inserted in between the trait type params and the
133             // method type params. The substs that we are given are
134             // the proper substs *internally* to the method body, so
135             // we have to use those when compiling it.
136             //
137             // In order to get the proper substitution to use on the
138             // type of the method, we pull apart the substitution and
139             // stick a substitution for the self type in.
140             // This is a bit unfortunate.
141
142             let idx = psubsts.tys.len() - num_method_ty_params;
143             let substs = psubsts.tys.slice(0, idx) +
144                 &[psubsts.self_ty.unwrap()] + psubsts.tys.tailn(idx);
145             debug!("static default: changed substitution to {}",
146                    substs.repr(ccx.tcx()));
147
148             ty::subst_tps(ccx.tcx(), substs, None, llitem_ty)
149         }
150     };
151
152     let f = match ty::get(mono_ty).sty {
153         ty::ty_bare_fn(ref f) => {
154             assert!(f.abi == abi::Rust || f.abi == abi::RustIntrinsic);
155             f
156         }
157         _ => fail!("expected bare rust fn or an intrinsic")
158     };
159
160     ccx.stats.n_monos.set(ccx.stats.n_monos.get() + 1);
161
162     let depth;
163     {
164         let mut monomorphizing = ccx.monomorphizing.borrow_mut();
165         depth = match monomorphizing.find(&fn_id) {
166             Some(&d) => d, None => 0
167         };
168
169         // Random cut-off -- code that needs to instantiate the same function
170         // recursively more than thirty times can probably safely be assumed
171         // to be causing an infinite expansion.
172         if depth > ccx.sess().recursion_limit.get() {
173             ccx.sess().span_fatal(ccx.tcx.map.span(fn_id.node),
174                 "reached the recursion limit during monomorphization");
175         }
176
177         monomorphizing.insert(fn_id, depth + 1);
178     }
179
180     let s = ccx.tcx.map.with_path(fn_id.node, |path| {
181         mangle_exported_name(ccx, path, mono_ty, fn_id.node)
182     });
183     debug!("monomorphize_fn mangled to {}", s);
184
185     let mk_lldecl = || {
186         let lldecl = decl_internal_rust_fn(ccx, false,
187                                            f.sig.inputs.as_slice(),
188                                            f.sig.output, s);
189         ccx.monomorphized.borrow_mut().insert(hash_id, lldecl);
190         lldecl
191     };
192
193     let lldecl = match map_node {
194         ast_map::NodeItem(i) => {
195             match *i {
196               ast::Item {
197                   node: ast::ItemFn(decl, _, _, _, body),
198                   ..
199               } => {
200                   let d = mk_lldecl();
201                   set_llvm_fn_attrs(i.attrs.as_slice(), d);
202                   trans_fn(ccx, decl, body, d, Some(psubsts), fn_id.node, []);
203                   d
204               }
205               _ => {
206                 ccx.sess().bug("Can't monomorphize this kind of item")
207               }
208             }
209         }
210         ast_map::NodeForeignItem(i) => {
211             let simple = intrinsic::get_simple_intrinsic(ccx, i);
212             match simple {
213                 Some(decl) => decl,
214                 None => {
215                     let d = mk_lldecl();
216                     intrinsic::trans_intrinsic(ccx, d, i, psubsts, ref_id);
217                     d
218                 }
219             }
220         }
221         ast_map::NodeVariant(v) => {
222             let parent = ccx.tcx.map.get_parent(fn_id.node);
223             let tvs = ty::enum_variants(ccx.tcx(), local_def(parent));
224             let this_tv = *tvs.iter().find(|tv| { tv.id.node == fn_id.node}).unwrap();
225             let d = mk_lldecl();
226             set_inline_hint(d);
227             match v.node.kind {
228                 ast::TupleVariantKind(ref args) => {
229                     trans_enum_variant(ccx,
230                                        parent,
231                                        v,
232                                        args.as_slice(),
233                                        this_tv.disr_val,
234                                        Some(psubsts),
235                                        d);
236                 }
237                 ast::StructVariantKind(_) =>
238                     ccx.sess().bug("can't monomorphize struct variants"),
239             }
240             d
241         }
242         ast_map::NodeMethod(mth) => {
243             let d = mk_lldecl();
244             set_llvm_fn_attrs(mth.attrs.as_slice(), d);
245             trans_fn(ccx, mth.decl, mth.body, d, Some(psubsts), mth.id, []);
246             d
247         }
248         ast_map::NodeTraitMethod(method) => {
249             match *method {
250                 ast::Provided(mth) => {
251                     let d = mk_lldecl();
252                     set_llvm_fn_attrs(mth.attrs.as_slice(), d);
253                     trans_fn(ccx, mth.decl, mth.body, d, Some(psubsts), mth.id, []);
254                     d
255                 }
256                 _ => {
257                     ccx.sess().bug(format!("can't monomorphize a {:?}",
258                                            map_node))
259                 }
260             }
261         }
262         ast_map::NodeStructCtor(struct_def) => {
263             let d = mk_lldecl();
264             set_inline_hint(d);
265             base::trans_tuple_struct(ccx,
266                                      struct_def.fields.as_slice(),
267                                      struct_def.ctor_id.expect("ast-mapped tuple struct \
268                                                                 didn't have a ctor id"),
269                                      Some(psubsts),
270                                      d);
271             d
272         }
273
274         // Ugh -- but this ensures any new variants won't be forgotten
275         ast_map::NodeExpr(..) |
276         ast_map::NodeStmt(..) |
277         ast_map::NodeArg(..) |
278         ast_map::NodeBlock(..) |
279         ast_map::NodeLocal(..) => {
280             ccx.sess().bug(format!("can't monomorphize a {:?}", map_node))
281         }
282     };
283
284     ccx.monomorphizing.borrow_mut().insert(fn_id, depth);
285
286     debug!("leaving monomorphic fn {}", ty::item_path_str(ccx.tcx(), fn_id));
287     (lldecl, must_cast)
288 }
289
290 pub fn make_mono_id(ccx: &CrateContext,
291                     item: ast::DefId,
292                     substs: &param_substs) -> mono_id {
293     // FIXME (possibly #5801): Need a lot of type hints to get
294     // .collect() to work.
295     let substs_iter = substs.self_ty.iter().chain(substs.tys.iter());
296     let precise_param_ids: Vec<(ty::t, Option<@Vec<mono_id> >)> = match substs.vtables {
297       Some(vts) => {
298         debug!("make_mono_id vtables={} substs={}",
299                vts.repr(ccx.tcx()), substs.tys.repr(ccx.tcx()));
300         let vts_iter = substs.self_vtables.iter().chain(vts.iter());
301         vts_iter.zip(substs_iter).map(|(vtable, subst)| {
302             let v = vtable.iter().map(|vt| meth::vtable_id(ccx, vt)).collect::<Vec<_>>();
303             (*subst, if !v.is_empty() { Some(@v) } else { None })
304         }).collect()
305       }
306       None => substs_iter.map(|subst| (*subst, None::<@Vec<mono_id> >)).collect()
307     };
308
309
310     let param_ids = precise_param_ids.iter().map(|x| {
311         let (a, b) = *x;
312         mono_precise(a, b)
313     }).collect();
314     @mono_id_ {def: item, params: param_ids}
315 }