]> git.proxmox.com Git - rustc.git/blob - src/librustc_trans/trans/monomorphize.rs
Imported Upstream version 1.6.0+dfsg1
[rustc.git] / src / librustc_trans / trans / monomorphize.rs
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.
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 use back::link::exported_name;
12 use session;
13 use llvm::ValueRef;
14 use llvm;
15 use middle::def_id::DefId;
16 use middle::infer::normalize_associated_type;
17 use middle::subst;
18 use middle::subst::{Subst, Substs};
19 use middle::ty::fold::{TypeFolder, TypeFoldable};
20 use trans::attributes;
21 use trans::base::{trans_enum_variant, push_ctxt, get_item_val};
22 use trans::base::trans_fn;
23 use trans::base;
24 use trans::common::*;
25 use trans::declare;
26 use trans::foreign;
27 use middle::ty::{self, HasTypeFlags, Ty};
28 use rustc::front::map as hir_map;
29
30 use rustc_front::hir;
31
32 use syntax::abi;
33 use syntax::ast;
34 use syntax::attr;
35 use std::hash::{Hasher, Hash, SipHasher};
36
37 pub fn monomorphic_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
38 fn_id: DefId,
39 psubsts: &'tcx subst::Substs<'tcx>,
40 ref_id: Option<ast::NodeId>)
41 -> (ValueRef, Ty<'tcx>, bool) {
42 debug!("monomorphic_fn(\
43 fn_id={:?}, \
44 real_substs={:?}, \
45 ref_id={:?})",
46 fn_id,
47 psubsts,
48 ref_id);
49
50 assert!(!psubsts.types.needs_infer() && !psubsts.types.has_param_types());
51
52 // we can only monomorphize things in this crate (or inlined into it)
53 let fn_node_id = ccx.tcx().map.as_local_node_id(fn_id).unwrap();
54
55 let _icx = push_ctxt("monomorphic_fn");
56
57 let hash_id = MonoId {
58 def: fn_id,
59 params: &psubsts.types
60 };
61
62 let item_ty = ccx.tcx().lookup_item_type(fn_id).ty;
63
64 debug!("monomorphic_fn about to subst into {:?}", item_ty);
65 let mono_ty = apply_param_substs(ccx.tcx(), psubsts, &item_ty);
66 debug!("mono_ty = {:?} (post-substitution)", mono_ty);
67
68 match ccx.monomorphized().borrow().get(&hash_id) {
69 Some(&val) => {
70 debug!("leaving monomorphic fn {}",
71 ccx.tcx().item_path_str(fn_id));
72 return (val, mono_ty, false);
73 }
74 None => ()
75 }
76
77 debug!("monomorphic_fn(\
78 fn_id={:?}, \
79 psubsts={:?}, \
80 hash_id={:?})",
81 fn_id,
82 psubsts,
83 hash_id);
84
85
86 let map_node = session::expect(
87 ccx.sess(),
88 ccx.tcx().map.find(fn_node_id),
89 || {
90 format!("while monomorphizing {:?}, couldn't find it in \
91 the item map (may have attempted to monomorphize \
92 an item defined in a different crate?)",
93 fn_id)
94 });
95
96 if let hir_map::NodeForeignItem(_) = map_node {
97 let abi = ccx.tcx().map.get_foreign_abi(fn_node_id);
98 if abi != abi::RustIntrinsic && abi != abi::PlatformIntrinsic {
99 // Foreign externs don't have to be monomorphized.
100 return (get_item_val(ccx, fn_node_id), mono_ty, true);
101 }
102 }
103
104 ccx.stats().n_monos.set(ccx.stats().n_monos.get() + 1);
105
106 let depth;
107 {
108 let mut monomorphizing = ccx.monomorphizing().borrow_mut();
109 depth = match monomorphizing.get(&fn_id) {
110 Some(&d) => d, None => 0
111 };
112
113 debug!("monomorphic_fn: depth for fn_id={:?} is {:?}", fn_id, depth+1);
114
115 // Random cut-off -- code that needs to instantiate the same function
116 // recursively more than thirty times can probably safely be assumed
117 // to be causing an infinite expansion.
118 if depth > ccx.sess().recursion_limit.get() {
119 ccx.sess().span_fatal(ccx.tcx().map.span(fn_node_id),
120 "reached the recursion limit during monomorphization");
121 }
122
123 monomorphizing.insert(fn_id, depth + 1);
124 }
125
126 let hash;
127 let s = {
128 let mut state = SipHasher::new();
129 hash_id.hash(&mut state);
130 mono_ty.hash(&mut state);
131
132 hash = format!("h{}", state.finish());
133 let path = ccx.tcx().map.def_path_from_id(fn_node_id);
134 exported_name(path, &hash[..])
135 };
136
137 debug!("monomorphize_fn mangled to {}", s);
138
139 // This shouldn't need to option dance.
140 let mut hash_id = Some(hash_id);
141 let mut mk_lldecl = |abi: abi::Abi| {
142 let lldecl = if abi != abi::Rust {
143 foreign::decl_rust_fn_with_foreign_abi(ccx, mono_ty, &s)
144 } else {
145 // FIXME(nagisa): perhaps needs a more fine grained selection? See
146 // setup_lldecl below.
147 declare::define_internal_rust_fn(ccx, &s, mono_ty)
148 };
149
150 ccx.monomorphized().borrow_mut().insert(hash_id.take().unwrap(), lldecl);
151 lldecl
152 };
153 let setup_lldecl = |lldecl, attrs: &[ast::Attribute]| {
154 base::update_linkage(ccx, lldecl, None, base::OriginalTranslation);
155 attributes::from_fn_attrs(ccx, attrs, lldecl);
156
157 let is_first = !ccx.available_monomorphizations().borrow().contains(&s);
158 if is_first {
159 ccx.available_monomorphizations().borrow_mut().insert(s.clone());
160 }
161
162 let trans_everywhere = attr::requests_inline(attrs);
163 if trans_everywhere && !is_first {
164 llvm::SetLinkage(lldecl, llvm::AvailableExternallyLinkage);
165 }
166
167 // If `true`, then `lldecl` should be given a function body.
168 // Otherwise, it should be left as a declaration of an external
169 // function, with no definition in the current compilation unit.
170 trans_everywhere || is_first
171 };
172
173 let lldecl = match map_node {
174 hir_map::NodeItem(i) => {
175 match *i {
176 hir::Item {
177 node: hir::ItemFn(ref decl, _, _, abi, _, ref body),
178 ..
179 } => {
180 let d = mk_lldecl(abi);
181 let needs_body = setup_lldecl(d, &i.attrs);
182 if needs_body {
183 if abi != abi::Rust {
184 foreign::trans_rust_fn_with_foreign_abi(
185 ccx, &**decl, &**body, &[], d, psubsts, fn_node_id,
186 Some(&hash[..]));
187 } else {
188 trans_fn(ccx, &**decl, &**body, d, psubsts, fn_node_id, &[]);
189 }
190 }
191
192 d
193 }
194 _ => {
195 ccx.sess().bug("Can't monomorphize this kind of item")
196 }
197 }
198 }
199 hir_map::NodeVariant(v) => {
200 let variant = inlined_variant_def(ccx, fn_node_id);
201 assert_eq!(v.node.name, variant.name);
202 let d = mk_lldecl(abi::Rust);
203 attributes::inline(d, attributes::InlineAttr::Hint);
204 trans_enum_variant(ccx, fn_node_id, variant.disr_val, psubsts, d);
205 d
206 }
207 hir_map::NodeImplItem(impl_item) => {
208 match impl_item.node {
209 hir::ImplItemKind::Method(ref sig, ref body) => {
210 let d = mk_lldecl(abi::Rust);
211 let needs_body = setup_lldecl(d, &impl_item.attrs);
212 if needs_body {
213 trans_fn(ccx,
214 &sig.decl,
215 body,
216 d,
217 psubsts,
218 impl_item.id,
219 &[]);
220 }
221 d
222 }
223 _ => {
224 ccx.sess().bug(&format!("can't monomorphize a {:?}",
225 map_node))
226 }
227 }
228 }
229 hir_map::NodeTraitItem(trait_item) => {
230 match trait_item.node {
231 hir::MethodTraitItem(ref sig, Some(ref body)) => {
232 let d = mk_lldecl(abi::Rust);
233 let needs_body = setup_lldecl(d, &trait_item.attrs);
234 if needs_body {
235 trans_fn(ccx, &sig.decl, body, d,
236 psubsts, trait_item.id, &[]);
237 }
238 d
239 }
240 _ => {
241 ccx.sess().bug(&format!("can't monomorphize a {:?}",
242 map_node))
243 }
244 }
245 }
246 hir_map::NodeStructCtor(struct_def) => {
247 let d = mk_lldecl(abi::Rust);
248 attributes::inline(d, attributes::InlineAttr::Hint);
249 if struct_def.is_struct() {
250 panic!("ast-mapped struct didn't have a ctor id")
251 }
252 base::trans_tuple_struct(ccx,
253 struct_def.id(),
254 psubsts,
255 d);
256 d
257 }
258
259 // Ugh -- but this ensures any new variants won't be forgotten
260 hir_map::NodeForeignItem(..) |
261 hir_map::NodeLifetime(..) |
262 hir_map::NodeTyParam(..) |
263 hir_map::NodeExpr(..) |
264 hir_map::NodeStmt(..) |
265 hir_map::NodeBlock(..) |
266 hir_map::NodePat(..) |
267 hir_map::NodeLocal(..) => {
268 ccx.sess().bug(&format!("can't monomorphize a {:?}",
269 map_node))
270 }
271 };
272
273 ccx.monomorphizing().borrow_mut().insert(fn_id, depth);
274
275 debug!("leaving monomorphic fn {}", ccx.tcx().item_path_str(fn_id));
276 (lldecl, mono_ty, true)
277 }
278
279 #[derive(PartialEq, Eq, Hash, Debug)]
280 pub struct MonoId<'tcx> {
281 pub def: DefId,
282 pub params: &'tcx subst::VecPerParamSpace<Ty<'tcx>>
283 }
284
285 /// Monomorphizes a type from the AST by first applying the in-scope
286 /// substitutions and then normalizing any associated types.
287 pub fn apply_param_substs<'tcx,T>(tcx: &ty::ctxt<'tcx>,
288 param_substs: &Substs<'tcx>,
289 value: &T)
290 -> T
291 where T : TypeFoldable<'tcx> + HasTypeFlags
292 {
293 let substituted = value.subst(tcx, param_substs);
294 normalize_associated_type(tcx, &substituted)
295 }
296
297
298 /// Returns the normalized type of a struct field
299 pub fn field_ty<'tcx>(tcx: &ty::ctxt<'tcx>,
300 param_substs: &Substs<'tcx>,
301 f: ty::FieldDef<'tcx>)
302 -> Ty<'tcx>
303 {
304 normalize_associated_type(tcx, &f.ty(tcx, param_substs))
305 }