1 // Copyright 2012-2013 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 #![allow(non_camel_case_types)]
13 pub use self::named_ty::*;
20 use middle::ty::{mod, Ty};
22 use util::ppaux::Repr;
24 use trans::type_::Type;
30 // LLVM doesn't like objects that are too big. Issue #17913
31 fn ensure_array_fits_in_address_space<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
33 size: machine::llsize,
34 scapegoat: Ty<'tcx>) {
35 let esz = machine::llsize_of_alloc(ccx, llet);
36 match esz.checked_mul(size) {
37 Some(n) if n < ccx.obj_size_bound() => {}
38 _ => { ccx.report_overbig_object(scapegoat) }
42 pub fn arg_is_indirect<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
43 arg_ty: Ty<'tcx>) -> bool {
44 !type_is_immediate(ccx, arg_ty)
47 pub fn return_uses_outptr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
48 ty: Ty<'tcx>) -> bool {
49 !type_is_immediate(ccx, ty)
52 pub fn type_of_explicit_arg<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
53 arg_ty: Ty<'tcx>) -> Type {
54 let llty = arg_type_of(ccx, arg_ty);
55 if arg_is_indirect(ccx, arg_ty) {
62 /// Yields the types of the "real" arguments for this function. For most
63 /// functions, these are simply the types of the arguments. For functions with
64 /// the `RustCall` ABI, however, this untuples the arguments of the function.
65 pub fn untuple_arguments_if_necessary<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
69 if abi != abi::RustCall {
70 return inputs.iter().map(|x| (*x).clone()).collect()
73 if inputs.len() == 0 {
77 let mut result = Vec::new();
78 for (i, &arg_prior_to_tuple) in inputs.iter().enumerate() {
79 if i < inputs.len() - 1 {
80 result.push(arg_prior_to_tuple);
84 match inputs[inputs.len() - 1].sty {
85 ty::ty_tup(ref tupled_arguments) => {
86 debug!("untuple_arguments_if_necessary(): untupling arguments");
87 for &tupled_argument in tupled_arguments.iter() {
88 result.push(tupled_argument);
92 ccx.tcx().sess.bug("argument to function with \"rust-call\" ABI \
93 is neither a tuple nor unit")
100 pub fn type_of_rust_fn<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
101 llenvironment_type: Option<Type>,
103 output: ty::FnOutput<'tcx>,
106 let mut atys: Vec<Type> = Vec::new();
108 // First, munge the inputs, if this has the `rust-call` ABI.
109 let inputs = untuple_arguments_if_necessary(cx, inputs, abi);
111 // Arg 0: Output pointer.
112 // (if the output type is non-immediate)
113 let lloutputtype = match output {
114 ty::FnConverging(output) => {
115 let use_out_pointer = return_uses_outptr(cx, output);
116 let lloutputtype = arg_type_of(cx, output);
117 // Use the output as the actual return value if it's immediate.
119 atys.push(lloutputtype.ptr_to());
121 } else if return_type_is_void(cx, output) {
127 ty::FnDiverging => Type::void(cx)
130 // Arg 1: Environment
131 match llenvironment_type {
133 Some(llenvironment_type) => atys.push(llenvironment_type),
136 // ... then explicit args.
137 let input_tys = inputs.iter().map(|&arg_ty| type_of_explicit_arg(cx, arg_ty));
138 atys.extend(input_tys);
140 Type::func(atys.as_slice(), &lloutputtype)
143 // Given a function type and a count of ty params, construct an llvm type
144 pub fn type_of_fn_from_ty<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, fty: Ty<'tcx>) -> Type {
146 ty::ty_closure(ref f) => {
149 f.sig.inputs.as_slice(),
153 ty::ty_bare_fn(ref f) => {
154 if f.abi == abi::Rust || f.abi == abi::RustCall {
157 f.sig.inputs.as_slice(),
161 foreign::lltype_for_foreign_fn(cx, fty)
165 cx.sess().bug("type_of_fn_from_ty given non-closure, non-bare-fn")
170 // A "sizing type" is an LLVM type, the size and alignment of which are
171 // guaranteed to be equivalent to what you would get out of `type_of()`. It's
174 // (1) It may be cheaper to compute the sizing type than the full type if all
175 // you're interested in is the size and/or alignment;
177 // (2) It won't make any recursive calls to determine the structure of the
178 // type behind pointers. This can help prevent infinite loops for
179 // recursive types. For example, enum types rely on this behavior.
181 pub fn sizing_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
182 match cx.llsizingtypes().borrow().get(&t).cloned() {
187 let llsizingty = match t.sty {
188 _ if !ty::lltype_is_sized(cx.tcx(), t) => {
189 cx.sess().bug(format!("trying to take the sizing type of {}, an unsized type",
190 ppaux::ty_to_string(cx.tcx(), t)).as_slice())
193 ty::ty_bool => Type::bool(cx),
194 ty::ty_char => Type::char(cx),
195 ty::ty_int(t) => Type::int_from_ty(cx, t),
196 ty::ty_uint(t) => Type::uint_from_ty(cx, t),
197 ty::ty_float(t) => Type::float_from_ty(cx, t),
199 ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty, ..}) | ty::ty_ptr(ty::mt{ty, ..}) => {
200 if ty::type_is_sized(cx.tcx(), ty) {
203 Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false)
207 ty::ty_bare_fn(..) => Type::i8p(cx),
208 ty::ty_closure(..) => Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false),
210 ty::ty_vec(ty, Some(size)) => {
211 let llty = sizing_type_of(cx, ty);
212 let size = size as u64;
213 ensure_array_fits_in_address_space(cx, llty, size, t);
214 Type::array(&llty, size)
217 ty::ty_tup(ref tys) if tys.is_empty() => {
221 ty::ty_tup(..) | ty::ty_enum(..) | ty::ty_unboxed_closure(..) => {
222 let repr = adt::represent_type(cx, t);
223 adt::sizing_type_of(cx, &*repr, false)
226 ty::ty_struct(..) => {
227 if ty::type_is_simd(cx.tcx(), t) {
228 let llet = type_of(cx, ty::simd_type(cx.tcx(), t));
229 let n = ty::simd_size(cx.tcx(), t) as u64;
230 ensure_array_fits_in_address_space(cx, llet, n, t);
231 Type::vector(&llet, n)
233 let repr = adt::represent_type(cx, t);
234 adt::sizing_type_of(cx, &*repr, false)
239 Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false)
242 ty::ty_infer(..) | ty::ty_param(..) | ty::ty_err(..) => {
243 cx.sess().bug(format!("fictitious type {} in sizing_type_of()",
244 ppaux::ty_to_string(cx.tcx(), t)).as_slice())
246 ty::ty_vec(_, None) | ty::ty_trait(..) | ty::ty_str => panic!("unreachable")
249 cx.llsizingtypes().borrow_mut().insert(t, llsizingty);
253 pub fn arg_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
254 if ty::type_is_bool(t) {
261 // NB: If you update this, be sure to update `sizing_type_of()` as well.
262 pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
263 fn type_of_unsize_info<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
264 // It is possible to end up here with a sized type. This happens with a
265 // struct which might be unsized, but is monomorphised to a sized type.
266 // In this case we'll fake a fat pointer with no unsize info (we use 0).
267 // However, its still a fat pointer, so we need some type use.
268 if ty::type_is_sized(cx.tcx(), t) {
269 return Type::i8p(cx);
272 match ty::unsized_part_of_type(cx.tcx(), t).sty {
273 ty::ty_str | ty::ty_vec(..) => Type::uint_from_ty(cx, ast::TyU),
274 ty::ty_trait(_) => Type::vtable_ptr(cx),
275 _ => panic!("Unexpected type returned from unsized_part_of_type : {}",
281 match cx.lltypes().borrow().get(&t) {
282 Some(&llty) => return llty,
286 debug!("type_of {} {}", t.repr(cx.tcx()), t.sty);
288 // Replace any typedef'd types with their equivalent non-typedef
289 // type. This ensures that all LLVM nominal types that contain
290 // Rust types are defined as the same LLVM types. If we don't do
291 // this then, e.g. `Option<{myfield: bool}>` would be a different
292 // type than `Option<myrec>`.
293 let t_norm = ty::normalize_ty(cx.tcx(), t);
296 let llty = type_of(cx, t_norm);
297 debug!("--> normalized {} {} to {} {} llty={}",
300 t_norm.repr(cx.tcx()),
302 cx.tn().type_to_string(llty));
303 cx.lltypes().borrow_mut().insert(t, llty);
307 let mut llty = match t.sty {
308 ty::ty_bool => Type::bool(cx),
309 ty::ty_char => Type::char(cx),
310 ty::ty_int(t) => Type::int_from_ty(cx, t),
311 ty::ty_uint(t) => Type::uint_from_ty(cx, t),
312 ty::ty_float(t) => Type::float_from_ty(cx, t),
313 ty::ty_enum(did, ref substs) => {
314 // Only create the named struct, but don't fill it in. We
315 // fill it in *after* placing it into the type cache. This
316 // avoids creating more than one copy of the enum when one
317 // of the enum's variants refers to the enum itself.
318 let repr = adt::represent_type(cx, t);
319 let tps = substs.types.get_slice(subst::TypeSpace);
320 let name = llvm_type_name(cx, an_enum, did, tps);
321 adt::incomplete_type_of(cx, &*repr, name.as_slice())
323 ty::ty_unboxed_closure(did, _, ref substs) => {
324 // Only create the named struct, but don't fill it in. We
325 // fill it in *after* placing it into the type cache.
326 let repr = adt::represent_type(cx, t);
327 // Unboxed closures can have substitutions in all spaces
328 // inherited from their environment, so we use entire
329 // contents of the VecPerParamSpace to to construct the llvm
331 let name = llvm_type_name(cx, an_unboxed_closure, did, substs.types.as_slice());
332 adt::incomplete_type_of(cx, &*repr, name.as_slice())
335 ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty, ..}) | ty::ty_ptr(ty::mt{ty, ..}) => {
338 // This means we get a nicer name in the output (str is always
340 cx.tn().find_type("str_slice").unwrap()
342 ty::ty_trait(..) => Type::opaque_trait(cx),
343 _ if !ty::type_is_sized(cx.tcx(), ty) => {
344 let p_ty = type_of(cx, ty).ptr_to();
345 Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, ty)], false)
347 _ => type_of(cx, ty).ptr_to(),
351 ty::ty_vec(ty, Some(size)) => {
352 let size = size as u64;
353 let llty = type_of(cx, ty);
354 ensure_array_fits_in_address_space(cx, llty, size, t);
355 Type::array(&llty, size)
357 ty::ty_vec(ty, None) => {
361 ty::ty_trait(..) => {
362 Type::opaque_trait_data(cx)
365 ty::ty_str => Type::i8(cx),
367 ty::ty_bare_fn(_) => {
368 type_of_fn_from_ty(cx, t).ptr_to()
370 ty::ty_closure(_) => {
371 let fn_ty = type_of_fn_from_ty(cx, t).ptr_to();
372 Type::struct_(cx, &[fn_ty, Type::i8p(cx)], false)
374 ty::ty_tup(ref tys) if tys.is_empty() => Type::nil(cx),
376 let repr = adt::represent_type(cx, t);
377 adt::type_of(cx, &*repr)
379 ty::ty_struct(did, ref substs) => {
380 if ty::type_is_simd(cx.tcx(), t) {
381 let llet = type_of(cx, ty::simd_type(cx.tcx(), t));
382 let n = ty::simd_size(cx.tcx(), t) as u64;
383 ensure_array_fits_in_address_space(cx, llet, n, t);
384 Type::vector(&llet, n)
386 // Only create the named struct, but don't fill it in. We fill it
387 // in *after* placing it into the type cache. This prevents
388 // infinite recursion with recursive struct types.
389 let repr = adt::represent_type(cx, t);
390 let tps = substs.types.get_slice(subst::TypeSpace);
391 let name = llvm_type_name(cx, a_struct, did, tps);
392 adt::incomplete_type_of(cx, &*repr, name.as_slice())
396 ty::ty_open(t) => match t.sty {
397 ty::ty_struct(..) => {
398 let p_ty = type_of(cx, t).ptr_to();
399 Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false)
401 ty::ty_vec(ty, None) => {
402 let p_ty = type_of(cx, ty).ptr_to();
403 Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false)
406 let p_ty = Type::i8p(cx);
407 Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false)
409 ty::ty_trait(..) => Type::opaque_trait(cx),
410 _ => cx.sess().bug(format!("ty_open with sized type: {}",
411 ppaux::ty_to_string(cx.tcx(), t)).as_slice())
414 ty::ty_infer(..) => cx.sess().bug("type_of with ty_infer"),
415 ty::ty_param(..) => cx.sess().bug("type_of with ty_param"),
416 ty::ty_err(..) => cx.sess().bug("type_of with ty_err"),
419 debug!("--> mapped t={} {} to llty={}",
422 cx.tn().type_to_string(llty));
424 cx.lltypes().borrow_mut().insert(t, llty);
426 // If this was an enum or struct, fill in the type now.
428 ty::ty_enum(..) | ty::ty_struct(..) | ty::ty_unboxed_closure(..)
429 if !ty::type_is_simd(cx.tcx(), t) => {
430 let repr = adt::represent_type(cx, t);
431 adt::finish_type_of(cx, &*repr, &mut llty);
439 pub fn align_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>)
440 -> machine::llalign {
441 let llty = sizing_type_of(cx, t);
442 machine::llalign_of_min(cx, llty)
445 // Want refinements! (Or case classes, I guess
452 impl Copy for named_ty {}
454 pub fn llvm_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
459 let name = match what {
460 a_struct => "struct",
462 an_unboxed_closure => return "closure".to_string(),
465 let base = ty::item_path_str(cx.tcx(), did);
466 let strings: Vec<String> = tps.iter().map(|t| t.repr(cx.tcx())).collect();
467 let tstr = if strings.is_empty() {
470 format!("{}<{}>", base, strings)
474 format!("{}.{}", name, tstr)
476 format!("{}.{}[{}{}]", name, tstr, "#", did.krate)
480 pub fn type_of_dtor<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, self_ty: Ty<'tcx>) -> Type {
481 let self_ty = type_of(ccx, self_ty).ptr_to();
482 Type::func(&[self_ty], &Type::void(ccx))