]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/type_of.rs
use slicing sugar
[rust.git] / src / librustc_trans / trans / type_of.rs
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.
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 #![allow(non_camel_case_types)]
12
13 pub use self::named_ty::*;
14
15 use middle::subst;
16 use trans::adt;
17 use trans::common::*;
18 use trans::foreign;
19 use trans::machine;
20 use middle::ty::{self, RegionEscape, Ty};
21 use util::ppaux;
22 use util::ppaux::Repr;
23
24 use trans::type_::Type;
25
26 use std::num::Int;
27 use syntax::abi;
28 use syntax::ast;
29
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>,
32                                                 llet: Type,
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) }
39     }
40 }
41
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)
45 }
46
47 pub fn return_uses_outptr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
48                                     ty: Ty<'tcx>) -> bool {
49     !type_is_immediate(ccx, ty)
50 }
51
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) {
56         llty.ptr_to()
57     } else {
58         llty
59     }
60 }
61
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>,
66                                                 inputs: &[Ty<'tcx>],
67                                                 abi: abi::Abi)
68                                                 -> Vec<Ty<'tcx>> {
69     if abi != abi::RustCall {
70         return inputs.iter().map(|x| (*x).clone()).collect()
71     }
72
73     if inputs.len() == 0 {
74         return Vec::new()
75     }
76
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);
81         }
82     }
83
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);
89             }
90         }
91         _ => {
92             ccx.tcx().sess.bug("argument to function with \"rust-call\" ABI \
93                                 is neither a tuple nor unit")
94         }
95     }
96
97     result
98 }
99
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>>,
103                                  abi: abi::Abi)
104                                  -> Type
105 {
106     let sig = ty::erase_late_bound_regions(cx.tcx(), sig);
107     assert!(!sig.variadic); // rust fns are never variadic
108
109     let mut atys: Vec<Type> = Vec::new();
110
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);
113
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.
121             if use_out_pointer {
122                 atys.push(lloutputtype.ptr_to());
123                 Type::void(cx)
124             } else if return_type_is_void(cx, output) {
125                 Type::void(cx)
126             } else {
127                 lloutputtype
128             }
129         }
130         ty::FnDiverging => Type::void(cx)
131     };
132
133     // Arg 1: Environment
134     match llenvironment_type {
135         None => {}
136         Some(llenvironment_type) => atys.push(llenvironment_type),
137     }
138
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);
142
143     Type::func(&atys[], &lloutputtype)
144 }
145
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 {
148     match fty.sty {
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)
154             } else {
155                 foreign::lltype_for_foreign_fn(cx, fty)
156             }
157         }
158         _ => {
159             cx.sess().bug("type_of_fn_from_ty given non-closure, non-bare-fn")
160         }
161     }
162 }
163
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
166 // useful because:
167 //
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;
170 //
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.
174
175 pub fn sizing_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
176     match cx.llsizingtypes().borrow().get(&t).cloned() {
177         Some(t) => return t,
178         None => ()
179     }
180
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))[])
185         }
186
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),
192
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) {
195                 Type::i8p(cx)
196             } else {
197                 Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false)
198             }
199         }
200
201         ty::ty_bare_fn(..) => Type::i8p(cx),
202
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)
208         }
209
210         ty::ty_tup(ref tys) if tys.is_empty() => {
211             Type::nil(cx)
212         }
213
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)
217         }
218
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)
225             } else {
226                 let repr = adt::represent_type(cx, t);
227                 adt::sizing_type_of(cx, &*repr, false)
228             }
229         }
230
231         ty::ty_open(_) => {
232             Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false)
233         }
234
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))[])
238         }
239         ty::ty_vec(_, None) | ty::ty_trait(..) | ty::ty_str => panic!("unreachable")
240     };
241
242     cx.llsizingtypes().borrow_mut().insert(t, llsizingty);
243     llsizingty
244 }
245
246 pub fn arg_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
247     if ty::type_is_bool(t) {
248         Type::i1(cx)
249     } else {
250         type_of(cx, t)
251     }
252 }
253
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);
263         }
264
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 : {}",
269                        t.repr(cx.tcx()))
270         }
271     }
272
273     // Check the cache.
274     match cx.lltypes().borrow().get(&t) {
275         Some(&llty) => return llty,
276         None => ()
277     }
278
279     debug!("type_of {} {:?}", t.repr(cx.tcx()), t.sty);
280
281     assert!(!t.has_escaping_regions());
282
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);
289
290     if t != t_norm {
291         let llty = type_of(cx, t_norm);
292         debug!("--> normalized {} {:?} to {} {:?} llty={}",
293                 t.repr(cx.tcx()),
294                 t,
295                 t_norm.repr(cx.tcx()),
296                 t_norm,
297                 cx.tn().type_to_string(llty));
298         cx.lltypes().borrow_mut().insert(t, llty);
299         return llty;
300     }
301
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[])
317       }
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
325           // name
326           let name = llvm_type_name(cx, an_unboxed_closure, did, substs.types.as_slice());
327           adt::incomplete_type_of(cx, &*repr, &name[])
328       }
329
330       ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty, ..}) | ty::ty_ptr(ty::mt{ty, ..}) => {
331           match ty.sty {
332               ty::ty_str => {
333                   // This means we get a nicer name in the output (str is always
334                   // unsized).
335                   cx.tn().find_type("str_slice").unwrap()
336               }
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)
341               }
342               _ => type_of(cx, ty).ptr_to(),
343           }
344       }
345
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)
351       }
352       ty::ty_vec(ty, None) => {
353           type_of(cx, ty)
354       }
355
356       ty::ty_trait(..) => {
357           Type::opaque_trait_data(cx)
358       }
359
360       ty::ty_str => Type::i8(cx),
361
362       ty::ty_bare_fn(..) => {
363           type_of_fn_from_ty(cx, t).ptr_to()
364       }
365       ty::ty_tup(ref tys) if tys.is_empty() => Type::nil(cx),
366       ty::ty_tup(..) => {
367           let repr = adt::represent_type(cx, t);
368           adt::type_of(cx, &*repr)
369       }
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)
376           } else {
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[])
384           }
385       }
386
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)
391           }
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)
395           }
396           ty::ty_str => {
397               let p_ty = Type::i8p(cx);
398               Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false)
399           }
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))[])
403       },
404
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"),
409     };
410
411     debug!("--> mapped t={} {:?} to llty={}",
412             t.repr(cx.tcx()),
413             t,
414             cx.tn().type_to_string(llty));
415
416     cx.lltypes().borrow_mut().insert(t, llty);
417
418     // If this was an enum or struct, fill in the type now.
419     match t.sty {
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);
424         }
425         _ => ()
426     }
427
428     return llty;
429 }
430
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)
435 }
436
437 // Want refinements! (Or case classes, I guess
438 #[derive(Copy)]
439 pub enum named_ty {
440     a_struct,
441     an_enum,
442     an_unboxed_closure,
443 }
444
445 pub fn llvm_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
446                                 what: named_ty,
447                                 did: ast::DefId,
448                                 tps: &[Ty<'tcx>])
449                                 -> String {
450     let name = match what {
451         a_struct => "struct",
452         an_enum => "enum",
453         an_unboxed_closure => return "closure".to_string(),
454     };
455
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() {
459         base
460     } else {
461         format!("{}<{:?}>", base, strings)
462     };
463
464     if did.krate == 0 {
465         format!("{}.{}", name, tstr)
466     } else {
467         format!("{}.{}[{}{}]", name, tstr, "#", did.krate)
468     }
469 }
470
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))
474 }