]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/type_of.rs
auto merge of #19628 : jbranchaud/rust/add-string-as-string-doctest, r=steveklabnik
[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::{mod, 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                                  inputs: &[Ty<'tcx>],
103                                  output: ty::FnOutput<'tcx>,
104                                  abi: abi::Abi)
105                                  -> Type {
106     let mut atys: Vec<Type> = Vec::new();
107
108     // First, munge the inputs, if this has the `rust-call` ABI.
109     let inputs = untuple_arguments_if_necessary(cx, inputs, abi);
110
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.
118             if use_out_pointer {
119                 atys.push(lloutputtype.ptr_to());
120                 Type::void(cx)
121             } else if return_type_is_void(cx, output) {
122                 Type::void(cx)
123             } else {
124                 lloutputtype
125             }
126         }
127         ty::FnDiverging => Type::void(cx)
128     };
129
130     // Arg 1: Environment
131     match llenvironment_type {
132         None => {}
133         Some(llenvironment_type) => atys.push(llenvironment_type),
134     }
135
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);
139
140     Type::func(atys.as_slice(), &lloutputtype)
141 }
142
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 {
145     match fty.sty {
146         ty::ty_closure(ref f) => {
147             type_of_rust_fn(cx,
148                             Some(Type::i8p(cx)),
149                             f.sig.inputs.as_slice(),
150                             f.sig.output,
151                             f.abi)
152         }
153         ty::ty_bare_fn(ref f) => {
154             if f.abi == abi::Rust || f.abi == abi::RustCall {
155                 type_of_rust_fn(cx,
156                                 None,
157                                 f.sig.inputs.as_slice(),
158                                 f.sig.output,
159                                 f.abi)
160             } else {
161                 foreign::lltype_for_foreign_fn(cx, fty)
162             }
163         }
164         _ => {
165             cx.sess().bug("type_of_fn_from_ty given non-closure, non-bare-fn")
166         }
167     }
168 }
169
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
172 // useful because:
173 //
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;
176 //
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.
180
181 pub fn sizing_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
182     match cx.llsizingtypes().borrow().get(&t).cloned() {
183         Some(t) => return t,
184         None => ()
185     }
186
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())
191         }
192
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),
198
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) {
201                 Type::i8p(cx)
202             } else {
203                 Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false)
204             }
205         }
206
207         ty::ty_bare_fn(..) => Type::i8p(cx),
208         ty::ty_closure(..) => Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false),
209
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)
215         }
216
217         ty::ty_tup(ref tys) if tys.is_empty() => {
218             Type::nil(cx)
219         }
220
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)
224         }
225
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)
232             } else {
233                 let repr = adt::represent_type(cx, t);
234                 adt::sizing_type_of(cx, &*repr, false)
235             }
236         }
237
238         ty::ty_open(_) => {
239             Type::struct_(cx, &[Type::i8p(cx), Type::i8p(cx)], false)
240         }
241
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())
245         }
246         ty::ty_vec(_, None) | ty::ty_trait(..) | ty::ty_str => panic!("unreachable")
247     };
248
249     cx.llsizingtypes().borrow_mut().insert(t, llsizingty);
250     llsizingty
251 }
252
253 pub fn arg_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> Type {
254     if ty::type_is_bool(t) {
255         Type::i1(cx)
256     } else {
257         type_of(cx, t)
258     }
259 }
260
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);
270         }
271
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 : {}",
276                        t.repr(cx.tcx()))
277         }
278     }
279
280     // Check the cache.
281     match cx.lltypes().borrow().get(&t) {
282         Some(&llty) => return llty,
283         None => ()
284     }
285
286     debug!("type_of {} {}", t.repr(cx.tcx()), t.sty);
287
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);
294
295     if t != t_norm {
296         let llty = type_of(cx, t_norm);
297         debug!("--> normalized {} {} to {} {} llty={}",
298                 t.repr(cx.tcx()),
299                 t,
300                 t_norm.repr(cx.tcx()),
301                 t_norm,
302                 cx.tn().type_to_string(llty));
303         cx.lltypes().borrow_mut().insert(t, llty);
304         return llty;
305     }
306
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())
322       }
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
330           // name
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())
333       }
334
335       ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty, ..}) | ty::ty_ptr(ty::mt{ty, ..}) => {
336           match ty.sty {
337               ty::ty_str => {
338                   // This means we get a nicer name in the output (str is always
339                   // unsized).
340                   cx.tn().find_type("str_slice").unwrap()
341               }
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)
346               }
347               _ => type_of(cx, ty).ptr_to(),
348           }
349       }
350
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)
356       }
357       ty::ty_vec(ty, None) => {
358           type_of(cx, ty)
359       }
360
361       ty::ty_trait(..) => {
362           Type::opaque_trait_data(cx)
363       }
364
365       ty::ty_str => Type::i8(cx),
366
367       ty::ty_bare_fn(_) => {
368           type_of_fn_from_ty(cx, t).ptr_to()
369       }
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)
373       }
374       ty::ty_tup(ref tys) if tys.is_empty() => Type::nil(cx),
375       ty::ty_tup(..) => {
376           let repr = adt::represent_type(cx, t);
377           adt::type_of(cx, &*repr)
378       }
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)
385           } else {
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())
393           }
394       }
395
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)
400           }
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)
404           }
405           ty::ty_str => {
406               let p_ty = Type::i8p(cx);
407               Type::struct_(cx, &[p_ty, type_of_unsize_info(cx, t)], false)
408           }
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())
412       },
413
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"),
417     };
418
419     debug!("--> mapped t={} {} to llty={}",
420             t.repr(cx.tcx()),
421             t,
422             cx.tn().type_to_string(llty));
423
424     cx.lltypes().borrow_mut().insert(t, llty);
425
426     // If this was an enum or struct, fill in the type now.
427     match t.sty {
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);
432         }
433         _ => ()
434     }
435
436     return llty;
437 }
438
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)
443 }
444
445 // Want refinements! (Or case classes, I guess
446 pub enum named_ty {
447     a_struct,
448     an_enum,
449     an_unboxed_closure,
450 }
451
452 impl Copy for named_ty {}
453
454 pub fn llvm_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
455                                 what: named_ty,
456                                 did: ast::DefId,
457                                 tps: &[Ty<'tcx>])
458                                 -> String {
459     let name = match what {
460         a_struct => "struct",
461         an_enum => "enum",
462         an_unboxed_closure => return "closure".to_string(),
463     };
464
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() {
468         base
469     } else {
470         format!("{}<{}>", base, strings)
471     };
472
473     if did.krate == 0 {
474         format!("{}.{}", name, tstr)
475     } else {
476         format!("{}.{}[{}{}]", name, tstr, "#", did.krate)
477     }
478 }
479
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))
483 }