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[], &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.0.inputs.as_slice(),
153 ty::ty_bare_fn(_, ref f) => {
154 // FIXME(#19925) once fn item types are
155 // zero-sized, we'll need to do something here
156 if f.abi == abi::Rust || f.abi == abi::RustCall {
159 f.sig.0.inputs.as_slice(),
163 foreign::lltype_for_foreign_fn(cx, fty)
167 cx.sess().bug("type_of_fn_from_ty given non-closure, non-bare-fn")
172 // A "sizing type" is an LLVM type, the size and alignment of which are
173 // guaranteed to be equivalent to what you would get out of `type_of()`. It's
176 // (1) It may be cheaper to compute the sizing type than the full type if all
177 // you're interested in is the size and/or alignment;
179 // (2) It won't make any recursive calls to determine the structure of the
180 // type behind pointers. This can help prevent infinite loops for
181 // recursive types. For example, enum types rely on this behavior.
183 pub fn sizing_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
184 match cx.llsizingtypes().borrow().get(&t).cloned() {
189 let llsizingty = match t.sty {
190 _ if !lltype_is_sized(cx.tcx(), t) => {
191 cx.sess().bug(format!("trying to take the sizing type of {}, an unsized type",
192 ppaux::ty_to_string(cx.tcx(), t))[])
195 ty::ty_bool => Type::bool(cx),
196 ty::ty_char => Type::char(cx),
197 ty::ty_int(t) => Type::int_from_ty(cx, t),
198 ty::ty_uint(t) => Type::uint_from_ty(cx, t),
199 ty::ty_float(t) => Type::float_from_ty(cx, t),
201 ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty, ..}) | ty::ty_ptr(ty::mt{ty, ..}) => {
202 if type_is_sized(cx.tcx(), ty) {
205 Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false)
209 ty::ty_bare_fn(..) => Type::i8p(cx),
210 ty::ty_closure(..) => Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false),
212 ty::ty_vec(ty, Some(size)) => {
213 let llty = sizing_type_of(cx, ty);
214 let size = size as u64;
215 ensure_array_fits_in_address_space(cx, llty, size, t);
216 Type::array(&llty, size)
219 ty::ty_tup(ref tys) if tys.is_empty() => {
223 ty::ty_tup(..) | ty::ty_enum(..) | ty::ty_unboxed_closure(..) => {
224 let repr = adt::represent_type(cx, t);
225 adt::sizing_type_of(cx, &*repr, false)
228 ty::ty_struct(..) => {
229 if ty::type_is_simd(cx.tcx(), t) {
230 let llet = type_of(cx, ty::simd_type(cx.tcx(), t));
231 let n = ty::simd_size(cx.tcx(), t) as u64;
232 ensure_array_fits_in_address_space(cx, llet, n, t);
233 Type::vector(&llet, n)
235 let repr = adt::represent_type(cx, t);
236 adt::sizing_type_of(cx, &*repr, false)
241 Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false)
244 ty::ty_projection(..) | ty::ty_infer(..) | ty::ty_param(..) | ty::ty_err(..) => {
245 cx.sess().bug(format!("fictitious type {} in sizing_type_of()",
246 ppaux::ty_to_string(cx.tcx(), t))[])
248 ty::ty_vec(_, None) | ty::ty_trait(..) | ty::ty_str => panic!("unreachable")
251 cx.llsizingtypes().borrow_mut().insert(t, llsizingty);
255 pub fn arg_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
256 if ty::type_is_bool(t) {
263 // NB: If you update this, be sure to update `sizing_type_of()` as well.
264 pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
265 fn type_of_unsize_info<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
266 // It is possible to end up here with a sized type. This happens with a
267 // struct which might be unsized, but is monomorphised to a sized type.
268 // In this case we'll fake a fat pointer with no unsize info (we use 0).
269 // However, its still a fat pointer, so we need some type use.
270 if type_is_sized(cx.tcx(), t) {
271 return Type::i8p(cx);
274 match unsized_part_of_type(cx.tcx(), t).sty {
275 ty::ty_str | ty::ty_vec(..) => Type::uint_from_ty(cx, ast::TyU),
276 ty::ty_trait(_) => Type::vtable_ptr(cx),
277 _ => panic!("Unexpected type returned from unsized_part_of_type : {}",
283 match cx.lltypes().borrow().get(&t) {
284 Some(&llty) => return llty,
288 debug!("type_of {} {}", t.repr(cx.tcx()), t.sty);
290 // Replace any typedef'd types with their equivalent non-typedef
291 // type. This ensures that all LLVM nominal types that contain
292 // Rust types are defined as the same LLVM types. If we don't do
293 // this then, e.g. `Option<{myfield: bool}>` would be a different
294 // type than `Option<myrec>`.
295 let t_norm = ty::normalize_ty(cx.tcx(), t);
298 let llty = type_of(cx, t_norm);
299 debug!("--> normalized {} {} to {} {} llty={}",
302 t_norm.repr(cx.tcx()),
304 cx.tn().type_to_string(llty));
305 cx.lltypes().borrow_mut().insert(t, llty);
309 let mut llty = match t.sty {
310 ty::ty_bool => Type::bool(cx),
311 ty::ty_char => Type::char(cx),
312 ty::ty_int(t) => Type::int_from_ty(cx, t),
313 ty::ty_uint(t) => Type::uint_from_ty(cx, t),
314 ty::ty_float(t) => Type::float_from_ty(cx, t),
315 ty::ty_enum(did, ref substs) => {
316 // Only create the named struct, but don't fill it in. We
317 // fill it in *after* placing it into the type cache. This
318 // avoids creating more than one copy of the enum when one
319 // of the enum's variants refers to the enum itself.
320 let repr = adt::represent_type(cx, t);
321 let tps = substs.types.get_slice(subst::TypeSpace);
322 let name = llvm_type_name(cx, an_enum, did, tps);
323 adt::incomplete_type_of(cx, &*repr, name[])
325 ty::ty_unboxed_closure(did, _, ref substs) => {
326 // Only create the named struct, but don't fill it in. We
327 // fill it in *after* placing it into the type cache.
328 let repr = adt::represent_type(cx, t);
329 // Unboxed closures can have substitutions in all spaces
330 // inherited from their environment, so we use entire
331 // contents of the VecPerParamSpace to to construct the llvm
333 let name = llvm_type_name(cx, an_unboxed_closure, did, substs.types.as_slice());
334 adt::incomplete_type_of(cx, &*repr, name[])
337 ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty, ..}) | ty::ty_ptr(ty::mt{ty, ..}) => {
340 // This means we get a nicer name in the output (str is always
342 cx.tn().find_type("str_slice").unwrap()
344 ty::ty_trait(..) => Type::opaque_trait(cx),
345 _ if !type_is_sized(cx.tcx(), ty) => {
346 let p_ty = type_of(cx, ty).ptr_to();
347 Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, ty)], false)
349 _ => type_of(cx, ty).ptr_to(),
353 ty::ty_vec(ty, Some(size)) => {
354 let size = size as u64;
355 let llty = type_of(cx, ty);
356 ensure_array_fits_in_address_space(cx, llty, size, t);
357 Type::array(&llty, size)
359 ty::ty_vec(ty, None) => {
363 ty::ty_trait(..) => {
364 Type::opaque_trait_data(cx)
367 ty::ty_str => Type::i8(cx),
369 ty::ty_bare_fn(..) => {
370 type_of_fn_from_ty(cx, t).ptr_to()
372 ty::ty_closure(_) => {
373 let fn_ty = type_of_fn_from_ty(cx, t).ptr_to();
374 Type::struct_(cx, &[fn_ty, Type::i8p(cx)], false)
376 ty::ty_tup(ref tys) if tys.is_empty() => Type::nil(cx),
378 let repr = adt::represent_type(cx, t);
379 adt::type_of(cx, &*repr)
381 ty::ty_struct(did, ref substs) => {
382 if ty::type_is_simd(cx.tcx(), t) {
383 let llet = type_of(cx, ty::simd_type(cx.tcx(), t));
384 let n = ty::simd_size(cx.tcx(), t) as u64;
385 ensure_array_fits_in_address_space(cx, llet, n, t);
386 Type::vector(&llet, n)
388 // Only create the named struct, but don't fill it in. We fill it
389 // in *after* placing it into the type cache. This prevents
390 // infinite recursion with recursive struct types.
391 let repr = adt::represent_type(cx, t);
392 let tps = substs.types.get_slice(subst::TypeSpace);
393 let name = llvm_type_name(cx, a_struct, did, tps);
394 adt::incomplete_type_of(cx, &*repr, name[])
398 ty::ty_open(t) => match t.sty {
399 ty::ty_struct(..) => {
400 let p_ty = type_of(cx, t).ptr_to();
401 Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false)
403 ty::ty_vec(ty, None) => {
404 let p_ty = type_of(cx, ty).ptr_to();
405 Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false)
408 let p_ty = Type::i8p(cx);
409 Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false)
411 ty::ty_trait(..) => Type::opaque_trait(cx),
412 _ => cx.sess().bug(format!("ty_open with sized type: {}",
413 ppaux::ty_to_string(cx.tcx(), t))[])
416 ty::ty_infer(..) => cx.sess().bug("type_of with ty_infer"),
417 ty::ty_projection(..) => cx.sess().bug("type_of with ty_projection"),
418 ty::ty_param(..) => cx.sess().bug("type_of with ty_param"),
419 ty::ty_err(..) => cx.sess().bug("type_of with ty_err"),
422 debug!("--> mapped t={} {} to llty={}",
425 cx.tn().type_to_string(llty));
427 cx.lltypes().borrow_mut().insert(t, llty);
429 // If this was an enum or struct, fill in the type now.
431 ty::ty_enum(..) | ty::ty_struct(..) | ty::ty_unboxed_closure(..)
432 if !ty::type_is_simd(cx.tcx(), t) => {
433 let repr = adt::represent_type(cx, t);
434 adt::finish_type_of(cx, &*repr, &mut llty);
442 pub fn align_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>)
443 -> machine::llalign {
444 let llty = sizing_type_of(cx, t);
445 machine::llalign_of_min(cx, llty)
448 // Want refinements! (Or case classes, I guess
456 pub fn llvm_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
461 let name = match what {
462 a_struct => "struct",
464 an_unboxed_closure => return "closure".to_string(),
467 let base = ty::item_path_str(cx.tcx(), did);
468 let strings: Vec<String> = tps.iter().map(|t| t.repr(cx.tcx())).collect();
469 let tstr = if strings.is_empty() {
472 format!("{}<{}>", base, strings)
476 format!("{}.{}", name, tstr)
478 format!("{}.{}[{}{}]", name, tstr, "#", did.krate)
482 pub fn type_of_dtor<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, self_ty: Ty<'tcx>) -> Type {
483 let self_ty = type_of(ccx, self_ty).ptr_to();
484 Type::func(&[self_ty], &Type::void(ccx))