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::{self, RegionEscape, 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>,
102 sig: &ty::Binder<ty::FnSig<'tcx>>,
106 let sig = ty::erase_late_bound_regions(cx.tcx(), sig);
107 assert!(!sig.variadic); // rust fns are never variadic
109 let mut atys: Vec<Type> = Vec::new();
111 // First, munge the inputs, if this has the `rust-call` ABI.
112 let inputs = untuple_arguments_if_necessary(cx, sig.inputs.as_slice(), abi);
114 // Arg 0: Output pointer.
115 // (if the output type is non-immediate)
116 let lloutputtype = match sig.output {
117 ty::FnConverging(output) => {
118 let use_out_pointer = return_uses_outptr(cx, output);
119 let lloutputtype = arg_type_of(cx, output);
120 // Use the output as the actual return value if it's immediate.
122 atys.push(lloutputtype.ptr_to());
124 } else if return_type_is_void(cx, output) {
130 ty::FnDiverging => Type::void(cx)
133 // Arg 1: Environment
134 match llenvironment_type {
136 Some(llenvironment_type) => atys.push(llenvironment_type),
139 // ... then explicit args.
140 let input_tys = inputs.iter().map(|&arg_ty| type_of_explicit_arg(cx, arg_ty));
141 atys.extend(input_tys);
143 Type::func(&atys[], &lloutputtype)
146 // Given a function type and a count of ty params, construct an llvm type
147 pub fn type_of_fn_from_ty<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, fty: Ty<'tcx>) -> Type {
149 ty::ty_bare_fn(_, ref f) => {
150 // FIXME(#19925) once fn item types are
151 // zero-sized, we'll need to do something here
152 if f.abi == abi::Rust || f.abi == abi::RustCall {
153 type_of_rust_fn(cx, None, &f.sig, f.abi)
155 foreign::lltype_for_foreign_fn(cx, fty)
159 cx.sess().bug("type_of_fn_from_ty given non-closure, non-bare-fn")
164 // A "sizing type" is an LLVM type, the size and alignment of which are
165 // guaranteed to be equivalent to what you would get out of `type_of()`. It's
168 // (1) It may be cheaper to compute the sizing type than the full type if all
169 // you're interested in is the size and/or alignment;
171 // (2) It won't make any recursive calls to determine the structure of the
172 // type behind pointers. This can help prevent infinite loops for
173 // recursive types. For example, enum types rely on this behavior.
175 pub fn sizing_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
176 match cx.llsizingtypes().borrow().get(&t).cloned() {
181 let llsizingty = match t.sty {
182 _ if !lltype_is_sized(cx.tcx(), t) => {
183 cx.sess().bug(&format!("trying to take the sizing type of {}, an unsized type",
184 ppaux::ty_to_string(cx.tcx(), t))[])
187 ty::ty_bool => Type::bool(cx),
188 ty::ty_char => Type::char(cx),
189 ty::ty_int(t) => Type::int_from_ty(cx, t),
190 ty::ty_uint(t) => Type::uint_from_ty(cx, t),
191 ty::ty_float(t) => Type::float_from_ty(cx, t),
193 ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty, ..}) | ty::ty_ptr(ty::mt{ty, ..}) => {
194 if type_is_sized(cx.tcx(), ty) {
197 Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false)
201 ty::ty_bare_fn(..) => Type::i8p(cx),
203 ty::ty_vec(ty, Some(size)) => {
204 let llty = sizing_type_of(cx, ty);
205 let size = size as u64;
206 ensure_array_fits_in_address_space(cx, llty, size, t);
207 Type::array(&llty, size)
210 ty::ty_tup(ref tys) if tys.is_empty() => {
214 ty::ty_tup(..) | ty::ty_enum(..) | ty::ty_unboxed_closure(..) => {
215 let repr = adt::represent_type(cx, t);
216 adt::sizing_type_of(cx, &*repr, false)
219 ty::ty_struct(..) => {
220 if ty::type_is_simd(cx.tcx(), t) {
221 let llet = type_of(cx, ty::simd_type(cx.tcx(), t));
222 let n = ty::simd_size(cx.tcx(), t) as u64;
223 ensure_array_fits_in_address_space(cx, llet, n, t);
224 Type::vector(&llet, n)
226 let repr = adt::represent_type(cx, t);
227 adt::sizing_type_of(cx, &*repr, false)
232 Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false)
235 ty::ty_projection(..) | ty::ty_infer(..) | ty::ty_param(..) | ty::ty_err(..) => {
236 cx.sess().bug(&format!("fictitious type {} in sizing_type_of()",
237 ppaux::ty_to_string(cx.tcx(), t))[])
239 ty::ty_vec(_, None) | ty::ty_trait(..) | ty::ty_str => panic!("unreachable")
242 cx.llsizingtypes().borrow_mut().insert(t, llsizingty);
246 pub fn arg_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
247 if ty::type_is_bool(t) {
254 // NB: If you update this, be sure to update `sizing_type_of()` as well.
255 pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
256 fn type_of_unsize_info<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
257 // It is possible to end up here with a sized type. This happens with a
258 // struct which might be unsized, but is monomorphised to a sized type.
259 // In this case we'll fake a fat pointer with no unsize info (we use 0).
260 // However, its still a fat pointer, so we need some type use.
261 if type_is_sized(cx.tcx(), t) {
262 return Type::i8p(cx);
265 match unsized_part_of_type(cx.tcx(), t).sty {
266 ty::ty_str | ty::ty_vec(..) => Type::uint_from_ty(cx, ast::TyUs),
267 ty::ty_trait(_) => Type::vtable_ptr(cx),
268 _ => panic!("Unexpected type returned from unsized_part_of_type : {}",
274 match cx.lltypes().borrow().get(&t) {
275 Some(&llty) => return llty,
279 debug!("type_of {} {:?}", t.repr(cx.tcx()), t.sty);
281 assert!(!t.has_escaping_regions());
283 // Replace any typedef'd types with their equivalent non-typedef
284 // type. This ensures that all LLVM nominal types that contain
285 // Rust types are defined as the same LLVM types. If we don't do
286 // this then, e.g. `Option<{myfield: bool}>` would be a different
287 // type than `Option<myrec>`.
288 let t_norm = normalize_ty(cx.tcx(), t);
291 let llty = type_of(cx, t_norm);
292 debug!("--> normalized {} {:?} to {} {:?} llty={}",
295 t_norm.repr(cx.tcx()),
297 cx.tn().type_to_string(llty));
298 cx.lltypes().borrow_mut().insert(t, llty);
302 let mut llty = match t.sty {
303 ty::ty_bool => Type::bool(cx),
304 ty::ty_char => Type::char(cx),
305 ty::ty_int(t) => Type::int_from_ty(cx, t),
306 ty::ty_uint(t) => Type::uint_from_ty(cx, t),
307 ty::ty_float(t) => Type::float_from_ty(cx, t),
308 ty::ty_enum(did, ref substs) => {
309 // Only create the named struct, but don't fill it in. We
310 // fill it in *after* placing it into the type cache. This
311 // avoids creating more than one copy of the enum when one
312 // of the enum's variants refers to the enum itself.
313 let repr = adt::represent_type(cx, t);
314 let tps = substs.types.get_slice(subst::TypeSpace);
315 let name = llvm_type_name(cx, an_enum, did, tps);
316 adt::incomplete_type_of(cx, &*repr, &name[])
318 ty::ty_unboxed_closure(did, _, ref substs) => {
319 // Only create the named struct, but don't fill it in. We
320 // fill it in *after* placing it into the type cache.
321 let repr = adt::represent_type(cx, t);
322 // Unboxed closures can have substitutions in all spaces
323 // inherited from their environment, so we use entire
324 // contents of the VecPerParamSpace to to construct the llvm
326 let name = llvm_type_name(cx, an_unboxed_closure, did, substs.types.as_slice());
327 adt::incomplete_type_of(cx, &*repr, &name[])
330 ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty, ..}) | ty::ty_ptr(ty::mt{ty, ..}) => {
333 // This means we get a nicer name in the output (str is always
335 cx.tn().find_type("str_slice").unwrap()
337 ty::ty_trait(..) => Type::opaque_trait(cx),
338 _ if !type_is_sized(cx.tcx(), ty) => {
339 let p_ty = type_of(cx, ty).ptr_to();
340 Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, ty)], false)
342 _ => type_of(cx, ty).ptr_to(),
346 ty::ty_vec(ty, Some(size)) => {
347 let size = size as u64;
348 let llty = type_of(cx, ty);
349 ensure_array_fits_in_address_space(cx, llty, size, t);
350 Type::array(&llty, size)
352 ty::ty_vec(ty, None) => {
356 ty::ty_trait(..) => {
357 Type::opaque_trait_data(cx)
360 ty::ty_str => Type::i8(cx),
362 ty::ty_bare_fn(..) => {
363 type_of_fn_from_ty(cx, t).ptr_to()
365 ty::ty_tup(ref tys) if tys.is_empty() => Type::nil(cx),
367 let repr = adt::represent_type(cx, t);
368 adt::type_of(cx, &*repr)
370 ty::ty_struct(did, ref substs) => {
371 if ty::type_is_simd(cx.tcx(), t) {
372 let llet = type_of(cx, ty::simd_type(cx.tcx(), t));
373 let n = ty::simd_size(cx.tcx(), t) as u64;
374 ensure_array_fits_in_address_space(cx, llet, n, t);
375 Type::vector(&llet, n)
377 // Only create the named struct, but don't fill it in. We fill it
378 // in *after* placing it into the type cache. This prevents
379 // infinite recursion with recursive struct types.
380 let repr = adt::represent_type(cx, t);
381 let tps = substs.types.get_slice(subst::TypeSpace);
382 let name = llvm_type_name(cx, a_struct, did, tps);
383 adt::incomplete_type_of(cx, &*repr, &name[])
387 ty::ty_open(t) => match t.sty {
388 ty::ty_struct(..) => {
389 let p_ty = type_of(cx, t).ptr_to();
390 Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false)
392 ty::ty_vec(ty, None) => {
393 let p_ty = type_of(cx, ty).ptr_to();
394 Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false)
397 let p_ty = Type::i8p(cx);
398 Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false)
400 ty::ty_trait(..) => Type::opaque_trait(cx),
401 _ => cx.sess().bug(&format!("ty_open with sized type: {}",
402 ppaux::ty_to_string(cx.tcx(), t))[])
405 ty::ty_infer(..) => cx.sess().bug("type_of with ty_infer"),
406 ty::ty_projection(..) => cx.sess().bug("type_of with ty_projection"),
407 ty::ty_param(..) => cx.sess().bug("type_of with ty_param"),
408 ty::ty_err(..) => cx.sess().bug("type_of with ty_err"),
411 debug!("--> mapped t={} {:?} to llty={}",
414 cx.tn().type_to_string(llty));
416 cx.lltypes().borrow_mut().insert(t, llty);
418 // If this was an enum or struct, fill in the type now.
420 ty::ty_enum(..) | ty::ty_struct(..) | ty::ty_unboxed_closure(..)
421 if !ty::type_is_simd(cx.tcx(), t) => {
422 let repr = adt::represent_type(cx, t);
423 adt::finish_type_of(cx, &*repr, &mut llty);
431 pub fn align_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>)
432 -> machine::llalign {
433 let llty = sizing_type_of(cx, t);
434 machine::llalign_of_min(cx, llty)
437 // Want refinements! (Or case classes, I guess
445 pub fn llvm_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
450 let name = match what {
451 a_struct => "struct",
453 an_unboxed_closure => return "closure".to_string(),
456 let base = ty::item_path_str(cx.tcx(), did);
457 let strings: Vec<String> = tps.iter().map(|t| t.repr(cx.tcx())).collect();
458 let tstr = if strings.is_empty() {
461 format!("{}<{:?}>", base, strings)
465 format!("{}.{}", name, tstr)
467 format!("{}.{}[{}{}]", name, tstr, "#", did.krate)
471 pub fn type_of_dtor<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, self_ty: Ty<'tcx>) -> Type {
472 let self_ty = type_of(ccx, self_ty).ptr_to();
473 Type::func(&[self_ty], &Type::void(ccx))