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.
11 use back
::link
::exported_name
;
14 use middle
::def_id
::DefId
;
15 use middle
::infer
::normalize_associated_type
;
17 use middle
::subst
::{Subst, Substs}
;
18 use middle
::ty
::fold
::{TypeFolder, TypeFoldable}
;
19 use trans
::attributes
;
20 use trans
::base
::{trans_enum_variant, push_ctxt, get_item_val}
;
21 use trans
::base
::trans_fn
;
26 use middle
::ty
::{self, Ty}
;
28 use rustc
::front
::map
as hir_map
;
36 use std
::hash
::{Hasher, Hash, SipHasher}
;
38 pub fn monomorphic_fn
<'a
, 'tcx
>(ccx
: &CrateContext
<'a
, 'tcx
>,
40 psubsts
: &'tcx subst
::Substs
<'tcx
>,
41 ref_id
: Option
<ast
::NodeId
>)
42 -> (ValueRef
, Ty
<'tcx
>, bool
) {
43 debug
!("monomorphic_fn(\
51 assert
!(!psubsts
.types
.needs_infer() && !psubsts
.types
.has_param_types());
53 // we can only monomorphize things in this crate (or inlined into it)
54 let fn_node_id
= ccx
.tcx().map
.as_local_node_id(fn_id
).unwrap();
56 let _icx
= push_ctxt("monomorphic_fn");
58 let hash_id
= MonoId
{
60 params
: &psubsts
.types
63 let item_ty
= ccx
.tcx().lookup_item_type(fn_id
).ty
;
65 debug
!("monomorphic_fn about to subst into {:?}", item_ty
);
66 let mono_ty
= apply_param_substs(ccx
.tcx(), psubsts
, &item_ty
);
67 debug
!("mono_ty = {:?} (post-substitution)", mono_ty
);
69 match ccx
.monomorphized().borrow().get(&hash_id
) {
71 debug
!("leaving monomorphic fn {}",
72 ccx
.tcx().item_path_str(fn_id
));
73 return (val
, mono_ty
, false);
78 debug
!("monomorphic_fn(\
87 let map_node
= errors
::expect(
88 ccx
.sess().diagnostic(),
89 ccx
.tcx().map
.find(fn_node_id
),
91 format
!("while monomorphizing {:?}, couldn't find it in \
92 the item map (may have attempted to monomorphize \
93 an item defined in a different crate?)",
97 if let hir_map
::NodeForeignItem(_
) = map_node
{
98 let abi
= ccx
.tcx().map
.get_foreign_abi(fn_node_id
);
99 if abi
!= Abi
::RustIntrinsic
&& abi
!= Abi
::PlatformIntrinsic
{
100 // Foreign externs don't have to be monomorphized.
101 return (get_item_val(ccx
, fn_node_id
), mono_ty
, true);
105 ccx
.stats().n_monos
.set(ccx
.stats().n_monos
.get() + 1);
109 let mut monomorphizing
= ccx
.monomorphizing().borrow_mut();
110 depth
= match monomorphizing
.get(&fn_id
) {
111 Some(&d
) => d
, None
=> 0
114 debug
!("monomorphic_fn: depth for fn_id={:?} is {:?}", fn_id
, depth
+1);
116 // Random cut-off -- code that needs to instantiate the same function
117 // recursively more than thirty times can probably safely be assumed
118 // to be causing an infinite expansion.
119 if depth
> ccx
.sess().recursion_limit
.get() {
120 ccx
.sess().span_fatal(ccx
.tcx().map
.span(fn_node_id
),
121 "reached the recursion limit during monomorphization");
124 monomorphizing
.insert(fn_id
, depth
+ 1);
129 let mut state
= SipHasher
::new();
130 hash_id
.hash(&mut state
);
131 mono_ty
.hash(&mut state
);
133 hash
= format
!("h{}", state
.finish());
134 let path
= ccx
.tcx().map
.def_path_from_id(fn_node_id
);
135 exported_name(path
, &hash
[..])
138 debug
!("monomorphize_fn mangled to {}", s
);
140 // This shouldn't need to option dance.
141 let mut hash_id
= Some(hash_id
);
142 let mut mk_lldecl
= |abi
: Abi
| {
143 let lldecl
= if abi
!= Abi
::Rust
{
144 foreign
::decl_rust_fn_with_foreign_abi(ccx
, mono_ty
, &s
)
146 // FIXME(nagisa): perhaps needs a more fine grained selection? See
147 // setup_lldecl below.
148 declare
::define_internal_rust_fn(ccx
, &s
, mono_ty
)
151 ccx
.monomorphized().borrow_mut().insert(hash_id
.take().unwrap(), lldecl
);
154 let setup_lldecl
= |lldecl
, attrs
: &[ast
::Attribute
]| {
155 base
::update_linkage(ccx
, lldecl
, None
, base
::OriginalTranslation
);
156 attributes
::from_fn_attrs(ccx
, attrs
, lldecl
);
158 let is_first
= !ccx
.available_monomorphizations().borrow().contains(&s
);
160 ccx
.available_monomorphizations().borrow_mut().insert(s
.clone());
163 let trans_everywhere
= attr
::requests_inline(attrs
);
164 if trans_everywhere
&& !is_first
{
165 llvm
::SetLinkage(lldecl
, llvm
::AvailableExternallyLinkage
);
168 // If `true`, then `lldecl` should be given a function body.
169 // Otherwise, it should be left as a declaration of an external
170 // function, with no definition in the current compilation unit.
171 trans_everywhere
|| is_first
174 let lldecl
= match map_node
{
175 hir_map
::NodeItem(i
) => {
178 node
: hir
::ItemFn(ref decl
, _
, _
, abi
, _
, ref body
),
181 let d
= mk_lldecl(abi
);
182 let needs_body
= setup_lldecl(d
, &i
.attrs
);
184 if abi
!= Abi
::Rust
{
185 foreign
::trans_rust_fn_with_foreign_abi(
186 ccx
, &decl
, &body
, &[], d
, psubsts
, fn_node_id
,
202 ccx
.sess().bug("Can't monomorphize this kind of item")
206 hir_map
::NodeVariant(v
) => {
207 let variant
= inlined_variant_def(ccx
, fn_node_id
);
208 assert_eq
!(v
.node
.name
, variant
.name
);
209 let d
= mk_lldecl(Abi
::Rust
);
210 attributes
::inline(d
, attributes
::InlineAttr
::Hint
);
211 trans_enum_variant(ccx
, fn_node_id
, Disr
::from(variant
.disr_val
), psubsts
, d
);
214 hir_map
::NodeImplItem(impl_item
) => {
215 match impl_item
.node
{
216 hir
::ImplItemKind
::Method(ref sig
, ref body
) => {
217 let d
= mk_lldecl(Abi
::Rust
);
218 let needs_body
= setup_lldecl(d
, &impl_item
.attrs
);
231 ccx
.sess().bug(&format
!("can't monomorphize a {:?}",
236 hir_map
::NodeTraitItem(trait_item
) => {
237 match trait_item
.node
{
238 hir
::MethodTraitItem(ref sig
, Some(ref body
)) => {
239 let d
= mk_lldecl(Abi
::Rust
);
240 let needs_body
= setup_lldecl(d
, &trait_item
.attrs
);
253 ccx
.sess().bug(&format
!("can't monomorphize a {:?}",
258 hir_map
::NodeStructCtor(struct_def
) => {
259 let d
= mk_lldecl(Abi
::Rust
);
260 attributes
::inline(d
, attributes
::InlineAttr
::Hint
);
261 if struct_def
.is_struct() {
262 panic
!("ast-mapped struct didn't have a ctor id")
264 base
::trans_tuple_struct(ccx
,
271 // Ugh -- but this ensures any new variants won't be forgotten
272 hir_map
::NodeForeignItem(..) |
273 hir_map
::NodeLifetime(..) |
274 hir_map
::NodeTyParam(..) |
275 hir_map
::NodeExpr(..) |
276 hir_map
::NodeStmt(..) |
277 hir_map
::NodeBlock(..) |
278 hir_map
::NodePat(..) |
279 hir_map
::NodeLocal(..) => {
280 ccx
.sess().bug(&format
!("can't monomorphize a {:?}",
285 ccx
.monomorphizing().borrow_mut().insert(fn_id
, depth
);
287 debug
!("leaving monomorphic fn {}", ccx
.tcx().item_path_str(fn_id
));
288 (lldecl
, mono_ty
, true)
291 #[derive(PartialEq, Eq, Hash, Debug)]
292 pub struct MonoId
<'tcx
> {
294 pub params
: &'tcx subst
::VecPerParamSpace
<Ty
<'tcx
>>
297 /// Monomorphizes a type from the AST by first applying the in-scope
298 /// substitutions and then normalizing any associated types.
299 pub fn apply_param_substs
<'tcx
,T
>(tcx
: &ty
::ctxt
<'tcx
>,
300 param_substs
: &Substs
<'tcx
>,
303 where T
: TypeFoldable
<'tcx
>
305 let substituted
= value
.subst(tcx
, param_substs
);
306 normalize_associated_type(tcx
, &substituted
)
310 /// Returns the normalized type of a struct field
311 pub fn field_ty
<'tcx
>(tcx
: &ty
::ctxt
<'tcx
>,
312 param_substs
: &Substs
<'tcx
>,
313 f
: ty
::FieldDef
<'tcx
>)
316 normalize_associated_type(tcx
, &f
.ty(tcx
, param_substs
))