]> git.lizzy.rs Git - rust.git/blob - src/librustc_target/abi/mod.rs
27a4292543ad65352c6047aecba0c504b0e9ac65
[rust.git] / src / librustc_target / abi / mod.rs
1 // Copyright 2017 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 pub use self::Integer::*;
12 pub use self::Primitive::*;
13
14 use spec::Target;
15
16 use std::fmt;
17 use std::ops::{Add, Deref, Sub, Mul, AddAssign, Range, RangeInclusive};
18
19 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
20 use rustc_serialize::{Decodable, Decoder};
21
22 pub mod call;
23
24 /// Parsed [Data layout](http://llvm.org/docs/LangRef.html#data-layout)
25 /// for a target, which contains everything needed to compute layouts.
26 pub struct TargetDataLayout {
27     pub endian: Endian,
28     pub i1_align: AbiAndPrefAlign,
29     pub i8_align: AbiAndPrefAlign,
30     pub i16_align: AbiAndPrefAlign,
31     pub i32_align: AbiAndPrefAlign,
32     pub i64_align: AbiAndPrefAlign,
33     pub i128_align: AbiAndPrefAlign,
34     pub f32_align: AbiAndPrefAlign,
35     pub f64_align: AbiAndPrefAlign,
36     pub pointer_size: Size,
37     pub pointer_align: AbiAndPrefAlign,
38     pub aggregate_align: AbiAndPrefAlign,
39
40     /// Alignments for vector types.
41     pub vector_align: Vec<(Size, AbiAndPrefAlign)>,
42
43     pub instruction_address_space: u32,
44 }
45
46 impl Default for TargetDataLayout {
47     /// Creates an instance of `TargetDataLayout`.
48     fn default() -> TargetDataLayout {
49         let align = |bits| Align::from_bits(bits).unwrap();
50         TargetDataLayout {
51             endian: Endian::Big,
52             i1_align: AbiAndPrefAlign::new(align(8)),
53             i8_align: AbiAndPrefAlign::new(align(8)),
54             i16_align: AbiAndPrefAlign::new(align(16)),
55             i32_align: AbiAndPrefAlign::new(align(32)),
56             i64_align: AbiAndPrefAlign { abi: align(32), pref: align(64) },
57             i128_align: AbiAndPrefAlign { abi: align(32), pref: align(64) },
58             f32_align: AbiAndPrefAlign::new(align(32)),
59             f64_align: AbiAndPrefAlign::new(align(64)),
60             pointer_size: Size::from_bits(64),
61             pointer_align: AbiAndPrefAlign::new(align(64)),
62             aggregate_align: AbiAndPrefAlign { abi: align(0), pref: align(64) },
63             vector_align: vec![
64                 (Size::from_bits(64), AbiAndPrefAlign::new(align(64))),
65                 (Size::from_bits(128), AbiAndPrefAlign::new(align(128))),
66             ],
67             instruction_address_space: 0,
68         }
69     }
70 }
71
72 impl TargetDataLayout {
73     pub fn parse(target: &Target) -> Result<TargetDataLayout, String> {
74         // Parse an address space index from a string.
75         let parse_address_space = |s: &str, cause: &str| {
76             s.parse::<u32>().map_err(|err| {
77                 format!("invalid address space `{}` for `{}` in \"data-layout\": {}",
78                         s, cause, err)
79             })
80         };
81
82         // Parse a bit count from a string.
83         let parse_bits = |s: &str, kind: &str, cause: &str| {
84             s.parse::<u64>().map_err(|err| {
85                 format!("invalid {} `{}` for `{}` in \"data-layout\": {}",
86                         kind, s, cause, err)
87             })
88         };
89
90         // Parse a size string.
91         let size = |s: &str, cause: &str| {
92             parse_bits(s, "size", cause).map(Size::from_bits)
93         };
94
95         // Parse an alignment string.
96         let align = |s: &[&str], cause: &str| {
97             if s.is_empty() {
98                 return Err(format!("missing alignment for `{}` in \"data-layout\"", cause));
99             }
100             let align_from_bits = |bits| {
101                 Align::from_bits(bits).map_err(|err| {
102                     format!("invalid alignment for `{}` in \"data-layout\": {}",
103                             cause, err)
104                 })
105             };
106             let abi = parse_bits(s[0], "alignment", cause)?;
107             let pref = s.get(1).map_or(Ok(abi), |pref| parse_bits(pref, "alignment", cause))?;
108             Ok(AbiAndPrefAlign {
109                 abi: align_from_bits(abi)?,
110                 pref: align_from_bits(pref)?,
111             })
112         };
113
114         let mut dl = TargetDataLayout::default();
115         let mut i128_align_src = 64;
116         for spec in target.data_layout.split('-') {
117             match spec.split(':').collect::<Vec<_>>()[..] {
118                 ["e"] => dl.endian = Endian::Little,
119                 ["E"] => dl.endian = Endian::Big,
120                 [p] if p.starts_with("P") => {
121                     dl.instruction_address_space = parse_address_space(&p[1..], "P")?
122                 }
123                 ["a", ref a..] => dl.aggregate_align = align(a, "a")?,
124                 ["f32", ref a..] => dl.f32_align = align(a, "f32")?,
125                 ["f64", ref a..] => dl.f64_align = align(a, "f64")?,
126                 [p @ "p", s, ref a..] | [p @ "p0", s, ref a..] => {
127                     dl.pointer_size = size(s, p)?;
128                     dl.pointer_align = align(a, p)?;
129                 }
130                 [s, ref a..] if s.starts_with("i") => {
131                     let bits = match s[1..].parse::<u64>() {
132                         Ok(bits) => bits,
133                         Err(_) => {
134                             size(&s[1..], "i")?; // For the user error.
135                             continue;
136                         }
137                     };
138                     let a = align(a, s)?;
139                     match bits {
140                         1 => dl.i1_align = a,
141                         8 => dl.i8_align = a,
142                         16 => dl.i16_align = a,
143                         32 => dl.i32_align = a,
144                         64 => dl.i64_align = a,
145                         _ => {}
146                     }
147                     if bits >= i128_align_src && bits <= 128 {
148                         // Default alignment for i128 is decided by taking the alignment of
149                         // largest-sized i{64...128}.
150                         i128_align_src = bits;
151                         dl.i128_align = a;
152                     }
153                 }
154                 [s, ref a..] if s.starts_with("v") => {
155                     let v_size = size(&s[1..], "v")?;
156                     let a = align(a, s)?;
157                     if let Some(v) = dl.vector_align.iter_mut().find(|v| v.0 == v_size) {
158                         v.1 = a;
159                         continue;
160                     }
161                     // No existing entry, add a new one.
162                     dl.vector_align.push((v_size, a));
163                 }
164                 _ => {} // Ignore everything else.
165             }
166         }
167
168         // Perform consistency checks against the Target information.
169         let endian_str = match dl.endian {
170             Endian::Little => "little",
171             Endian::Big => "big"
172         };
173         if endian_str != target.target_endian {
174             return Err(format!("inconsistent target specification: \"data-layout\" claims \
175                                 architecture is {}-endian, while \"target-endian\" is `{}`",
176                                endian_str, target.target_endian));
177         }
178
179         if dl.pointer_size.bits().to_string() != target.target_pointer_width {
180             return Err(format!("inconsistent target specification: \"data-layout\" claims \
181                                 pointers are {}-bit, while \"target-pointer-width\" is `{}`",
182                                dl.pointer_size.bits(), target.target_pointer_width));
183         }
184
185         Ok(dl)
186     }
187
188     /// Return exclusive upper bound on object size.
189     ///
190     /// The theoretical maximum object size is defined as the maximum positive `isize` value.
191     /// This ensures that the `offset` semantics remain well-defined by allowing it to correctly
192     /// index every address within an object along with one byte past the end, along with allowing
193     /// `isize` to store the difference between any two pointers into an object.
194     ///
195     /// The upper bound on 64-bit currently needs to be lower because LLVM uses a 64-bit integer
196     /// to represent object size in bits. It would need to be 1 << 61 to account for this, but is
197     /// currently conservatively bounded to 1 << 47 as that is enough to cover the current usable
198     /// address space on 64-bit ARMv8 and x86_64.
199     pub fn obj_size_bound(&self) -> u64 {
200         match self.pointer_size.bits() {
201             16 => 1 << 15,
202             32 => 1 << 31,
203             64 => 1 << 47,
204             bits => panic!("obj_size_bound: unknown pointer bit size {}", bits)
205         }
206     }
207
208     pub fn ptr_sized_integer(&self) -> Integer {
209         match self.pointer_size.bits() {
210             16 => I16,
211             32 => I32,
212             64 => I64,
213             bits => panic!("ptr_sized_integer: unknown pointer bit size {}", bits)
214         }
215     }
216
217     pub fn vector_align(&self, vec_size: Size) -> AbiAndPrefAlign {
218         for &(size, align) in &self.vector_align {
219             if size == vec_size {
220                 return align;
221             }
222         }
223         // Default to natural alignment, which is what LLVM does.
224         // That is, use the size, rounded up to a power of 2.
225         AbiAndPrefAlign::new(Align::from_bytes(vec_size.bytes().next_power_of_two()).unwrap())
226     }
227 }
228
229 pub trait HasDataLayout {
230     fn data_layout(&self) -> &TargetDataLayout;
231 }
232
233 impl HasDataLayout for TargetDataLayout {
234     fn data_layout(&self) -> &TargetDataLayout {
235         self
236     }
237 }
238
239 /// Endianness of the target, which must match cfg(target-endian).
240 #[derive(Copy, Clone, PartialEq)]
241 pub enum Endian {
242     Little,
243     Big
244 }
245
246 /// Size of a type in bytes.
247 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
248 pub struct Size {
249     raw: u64
250 }
251
252 impl Size {
253     pub const ZERO: Size = Self::from_bytes(0);
254
255     #[inline]
256     pub fn from_bits(bits: u64) -> Size {
257         // Avoid potential overflow from `bits + 7`.
258         Size::from_bytes(bits / 8 + ((bits % 8) + 7) / 8)
259     }
260
261     #[inline]
262     pub const fn from_bytes(bytes: u64) -> Size {
263         Size {
264             raw: bytes
265         }
266     }
267
268     #[inline]
269     pub fn bytes(self) -> u64 {
270         self.raw
271     }
272
273     #[inline]
274     pub fn bits(self) -> u64 {
275         self.bytes().checked_mul(8).unwrap_or_else(|| {
276             panic!("Size::bits: {} bytes in bits doesn't fit in u64", self.bytes())
277         })
278     }
279
280     #[inline]
281     pub fn align_to(self, align: Align) -> Size {
282         let mask = align.bytes() - 1;
283         Size::from_bytes((self.bytes() + mask) & !mask)
284     }
285
286     #[inline]
287     pub fn is_aligned(self, align: Align) -> bool {
288         let mask = align.bytes() - 1;
289         self.bytes() & mask == 0
290     }
291
292     #[inline]
293     pub fn checked_add<C: HasDataLayout>(self, offset: Size, cx: &C) -> Option<Size> {
294         let dl = cx.data_layout();
295
296         let bytes = self.bytes().checked_add(offset.bytes())?;
297
298         if bytes < dl.obj_size_bound() {
299             Some(Size::from_bytes(bytes))
300         } else {
301             None
302         }
303     }
304
305     #[inline]
306     pub fn checked_mul<C: HasDataLayout>(self, count: u64, cx: &C) -> Option<Size> {
307         let dl = cx.data_layout();
308
309         let bytes = self.bytes().checked_mul(count)?;
310         if bytes < dl.obj_size_bound() {
311             Some(Size::from_bytes(bytes))
312         } else {
313             None
314         }
315     }
316 }
317
318 // Panicking addition, subtraction and multiplication for convenience.
319 // Avoid during layout computation, return `LayoutError` instead.
320
321 impl Add for Size {
322     type Output = Size;
323     #[inline]
324     fn add(self, other: Size) -> Size {
325         Size::from_bytes(self.bytes().checked_add(other.bytes()).unwrap_or_else(|| {
326             panic!("Size::add: {} + {} doesn't fit in u64", self.bytes(), other.bytes())
327         }))
328     }
329 }
330
331 impl Sub for Size {
332     type Output = Size;
333     #[inline]
334     fn sub(self, other: Size) -> Size {
335         Size::from_bytes(self.bytes().checked_sub(other.bytes()).unwrap_or_else(|| {
336             panic!("Size::sub: {} - {} would result in negative size", self.bytes(), other.bytes())
337         }))
338     }
339 }
340
341 impl Mul<Size> for u64 {
342     type Output = Size;
343     #[inline]
344     fn mul(self, size: Size) -> Size {
345         size * self
346     }
347 }
348
349 impl Mul<u64> for Size {
350     type Output = Size;
351     #[inline]
352     fn mul(self, count: u64) -> Size {
353         match self.bytes().checked_mul(count) {
354             Some(bytes) => Size::from_bytes(bytes),
355             None => {
356                 panic!("Size::mul: {} * {} doesn't fit in u64", self.bytes(), count)
357             }
358         }
359     }
360 }
361
362 impl AddAssign for Size {
363     #[inline]
364     fn add_assign(&mut self, other: Size) {
365         *self = *self + other;
366     }
367 }
368
369 /// Alignment of a type in bytes (always a power of two).
370 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, RustcEncodable, RustcDecodable)]
371 pub struct Align {
372     pow2: u8,
373 }
374
375 impl Align {
376     pub fn from_bits(bits: u64) -> Result<Align, String> {
377         Align::from_bytes(Size::from_bits(bits).bytes())
378     }
379
380     pub fn from_bytes(align: u64) -> Result<Align, String> {
381         // Treat an alignment of 0 bytes like 1-byte alignment.
382         if align == 0 {
383             return Ok(Align { pow2: 0 });
384         }
385
386         let mut bytes = align;
387         let mut pow2: u8 = 0;
388         while (bytes & 1) == 0 {
389             pow2 += 1;
390             bytes >>= 1;
391         }
392         if bytes != 1 {
393             return Err(format!("`{}` is not a power of 2", align));
394         }
395         if pow2 > 29 {
396             return Err(format!("`{}` is too large", align));
397         }
398
399         Ok(Align { pow2 })
400     }
401
402     pub fn bytes(self) -> u64 {
403         1 << self.pow2
404     }
405
406     pub fn bits(self) -> u64 {
407         self.bytes() * 8
408     }
409
410     /// Compute the best alignment possible for the given offset
411     /// (the largest power of two that the offset is a multiple of).
412     ///
413     /// NB: for an offset of `0`, this happens to return `2^64`.
414     pub fn max_for_offset(offset: Size) -> Align {
415         Align {
416             pow2: offset.bytes().trailing_zeros() as u8,
417         }
418     }
419
420     /// Lower the alignment, if necessary, such that the given offset
421     /// is aligned to it (the offset is a multiple of the alignment).
422     pub fn restrict_for_offset(self, offset: Size) -> Align {
423         self.min(Align::max_for_offset(offset))
424     }
425 }
426
427 /// A pair of aligments, ABI-mandated and preferred.
428 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug, RustcEncodable, RustcDecodable)]
429 pub struct AbiAndPrefAlign {
430     pub abi: Align,
431     pub pref: Align,
432 }
433
434 impl AbiAndPrefAlign {
435     pub fn new(align: Align) -> AbiAndPrefAlign {
436         AbiAndPrefAlign {
437             abi: align,
438             pref: align,
439         }
440     }
441
442     pub fn min(self, other: AbiAndPrefAlign) -> AbiAndPrefAlign {
443         AbiAndPrefAlign {
444             abi: self.abi.min(other.abi),
445             pref: self.pref.min(other.pref),
446         }
447     }
448
449     pub fn max(self, other: AbiAndPrefAlign) -> AbiAndPrefAlign {
450         AbiAndPrefAlign {
451             abi: self.abi.max(other.abi),
452             pref: self.pref.max(other.pref),
453         }
454     }
455 }
456
457 /// Integers, also used for enum discriminants.
458 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
459 pub enum Integer {
460     I8,
461     I16,
462     I32,
463     I64,
464     I128,
465 }
466
467 impl Integer {
468     pub fn size(self) -> Size {
469         match self {
470             I8 => Size::from_bytes(1),
471             I16 => Size::from_bytes(2),
472             I32 => Size::from_bytes(4),
473             I64  => Size::from_bytes(8),
474             I128  => Size::from_bytes(16),
475         }
476     }
477
478     pub fn align<C: HasDataLayout>(self, cx: &C) -> AbiAndPrefAlign {
479         let dl = cx.data_layout();
480
481         match self {
482             I8 => dl.i8_align,
483             I16 => dl.i16_align,
484             I32 => dl.i32_align,
485             I64 => dl.i64_align,
486             I128 => dl.i128_align,
487         }
488     }
489
490     /// Find the smallest Integer type which can represent the signed value.
491     pub fn fit_signed(x: i128) -> Integer {
492         match x {
493             -0x0000_0000_0000_0080..=0x0000_0000_0000_007f => I8,
494             -0x0000_0000_0000_8000..=0x0000_0000_0000_7fff => I16,
495             -0x0000_0000_8000_0000..=0x0000_0000_7fff_ffff => I32,
496             -0x8000_0000_0000_0000..=0x7fff_ffff_ffff_ffff => I64,
497             _ => I128
498         }
499     }
500
501     /// Find the smallest Integer type which can represent the unsigned value.
502     pub fn fit_unsigned(x: u128) -> Integer {
503         match x {
504             0..=0x0000_0000_0000_00ff => I8,
505             0..=0x0000_0000_0000_ffff => I16,
506             0..=0x0000_0000_ffff_ffff => I32,
507             0..=0xffff_ffff_ffff_ffff => I64,
508             _ => I128,
509         }
510     }
511
512     /// Find the smallest integer with the given alignment.
513     pub fn for_align<C: HasDataLayout>(cx: &C, wanted: Align) -> Option<Integer> {
514         let dl = cx.data_layout();
515
516         for &candidate in &[I8, I16, I32, I64, I128] {
517             if wanted == candidate.align(dl).abi && wanted.bytes() == candidate.size().bytes() {
518                 return Some(candidate);
519             }
520         }
521         None
522     }
523
524     /// Find the largest integer with the given alignment or less.
525     pub fn approximate_align<C: HasDataLayout>(cx: &C, wanted: Align) -> Integer {
526         let dl = cx.data_layout();
527
528         // FIXME(eddyb) maybe include I128 in the future, when it works everywhere.
529         for &candidate in &[I64, I32, I16] {
530             if wanted >= candidate.align(dl).abi && wanted.bytes() >= candidate.size().bytes() {
531                 return candidate;
532             }
533         }
534         I8
535     }
536 }
537
538
539 #[derive(Clone, PartialEq, Eq, RustcEncodable, RustcDecodable, Hash, Copy,
540          PartialOrd, Ord)]
541 pub enum FloatTy {
542     F32,
543     F64,
544 }
545
546 impl fmt::Debug for FloatTy {
547     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
548         fmt::Display::fmt(self, f)
549     }
550 }
551
552 impl fmt::Display for FloatTy {
553     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
554         write!(f, "{}", self.ty_to_string())
555     }
556 }
557
558 impl FloatTy {
559     pub fn ty_to_string(self) -> &'static str {
560         match self {
561             FloatTy::F32 => "f32",
562             FloatTy::F64 => "f64",
563         }
564     }
565
566     pub fn bit_width(self) -> usize {
567         match self {
568             FloatTy::F32 => 32,
569             FloatTy::F64 => 64,
570         }
571     }
572 }
573
574 /// Fundamental unit of memory access and layout.
575 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
576 pub enum Primitive {
577     /// The `bool` is the signedness of the `Integer` type.
578     ///
579     /// One would think we would not care about such details this low down,
580     /// but some ABIs are described in terms of C types and ISAs where the
581     /// integer arithmetic is done on {sign,zero}-extended registers, e.g.
582     /// a negative integer passed by zero-extension will appear positive in
583     /// the callee, and most operations on it will produce the wrong values.
584     Int(Integer, bool),
585     Float(FloatTy),
586     Pointer
587 }
588
589 impl<'a, 'tcx> Primitive {
590     pub fn size<C: HasDataLayout>(self, cx: &C) -> Size {
591         let dl = cx.data_layout();
592
593         match self {
594             Int(i, _) => i.size(),
595             Float(FloatTy::F32) => Size::from_bits(32),
596             Float(FloatTy::F64) => Size::from_bits(64),
597             Pointer => dl.pointer_size
598         }
599     }
600
601     pub fn align<C: HasDataLayout>(self, cx: &C) -> AbiAndPrefAlign {
602         let dl = cx.data_layout();
603
604         match self {
605             Int(i, _) => i.align(dl),
606             Float(FloatTy::F32) => dl.f32_align,
607             Float(FloatTy::F64) => dl.f64_align,
608             Pointer => dl.pointer_align
609         }
610     }
611
612     pub fn is_float(self) -> bool {
613         match self {
614             Float(_) => true,
615             _ => false
616         }
617     }
618
619     pub fn is_int(self) -> bool {
620         match self {
621             Int(..) => true,
622             _ => false,
623         }
624     }
625 }
626
627 /// Information about one scalar component of a Rust type.
628 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
629 pub struct Scalar {
630     pub value: Primitive,
631
632     /// Inclusive wrap-around range of valid values, that is, if
633     /// start > end, it represents `start..=max_value()`,
634     /// followed by `0..=end`.
635     ///
636     /// That is, for an i8 primitive, a range of `254..=2` means following
637     /// sequence:
638     ///
639     ///    254 (-2), 255 (-1), 0, 1, 2
640     ///
641     /// This is intended specifically to mirror LLVM’s `!range` metadata,
642     /// semantics.
643     // FIXME(eddyb) always use the shortest range, e.g. by finding
644     // the largest space between two consecutive valid values and
645     // taking everything else as the (shortest) valid range.
646     pub valid_range: RangeInclusive<u128>,
647 }
648
649 impl Scalar {
650     pub fn is_bool(&self) -> bool {
651         if let Int(I8, _) = self.value {
652             self.valid_range == (0..=1)
653         } else {
654             false
655         }
656     }
657
658     /// Returns the valid range as a `x..y` range.
659     ///
660     /// If `x` and `y` are equal, the range is full, not empty.
661     pub fn valid_range_exclusive<C: HasDataLayout>(&self, cx: &C) -> Range<u128> {
662         // For a (max) value of -1, max will be `-1 as usize`, which overflows.
663         // However, that is fine here (it would still represent the full range),
664         // i.e., if the range is everything.
665         let bits = self.value.size(cx).bits();
666         assert!(bits <= 128);
667         let mask = !0u128 >> (128 - bits);
668         let start = *self.valid_range.start();
669         let end = *self.valid_range.end();
670         assert_eq!(start, start & mask);
671         assert_eq!(end, end & mask);
672         start..(end.wrapping_add(1) & mask)
673     }
674 }
675
676 /// Describes how the fields of a type are located in memory.
677 #[derive(PartialEq, Eq, Hash, Debug)]
678 pub enum FieldPlacement {
679     /// All fields start at no offset. The `usize` is the field count.
680     ///
681     /// In the case of primitives the number of fields is `0`.
682     Union(usize),
683
684     /// Array/vector-like placement, with all fields of identical types.
685     Array {
686         stride: Size,
687         count: u64
688     },
689
690     /// Struct-like placement, with precomputed offsets.
691     ///
692     /// Fields are guaranteed to not overlap, but note that gaps
693     /// before, between and after all the fields are NOT always
694     /// padding, and as such their contents may not be discarded.
695     /// For example, enum variants leave a gap at the start,
696     /// where the discriminant field in the enum layout goes.
697     Arbitrary {
698         /// Offsets for the first byte of each field,
699         /// ordered to match the source definition order.
700         /// This vector does not go in increasing order.
701         // FIXME(eddyb) use small vector optimization for the common case.
702         offsets: Vec<Size>,
703
704         /// Maps source order field indices to memory order indices,
705         /// depending how fields were permuted.
706         // FIXME(camlorn) also consider small vector  optimization here.
707         memory_index: Vec<u32>
708     }
709 }
710
711 impl FieldPlacement {
712     pub fn count(&self) -> usize {
713         match *self {
714             FieldPlacement::Union(count) => count,
715             FieldPlacement::Array { count, .. } => {
716                 let usize_count = count as usize;
717                 assert_eq!(usize_count as u64, count);
718                 usize_count
719             }
720             FieldPlacement::Arbitrary { ref offsets, .. } => offsets.len()
721         }
722     }
723
724     pub fn offset(&self, i: usize) -> Size {
725         match *self {
726             FieldPlacement::Union(_) => Size::ZERO,
727             FieldPlacement::Array { stride, count } => {
728                 let i = i as u64;
729                 assert!(i < count);
730                 stride * i
731             }
732             FieldPlacement::Arbitrary { ref offsets, .. } => offsets[i]
733         }
734     }
735
736     pub fn memory_index(&self, i: usize) -> usize {
737         match *self {
738             FieldPlacement::Union(_) |
739             FieldPlacement::Array { .. } => i,
740             FieldPlacement::Arbitrary { ref memory_index, .. } => {
741                 let r = memory_index[i];
742                 assert_eq!(r as usize as u32, r);
743                 r as usize
744             }
745         }
746     }
747
748     /// Get source indices of the fields by increasing offsets.
749     #[inline]
750     pub fn index_by_increasing_offset<'a>(&'a self) -> impl Iterator<Item=usize>+'a {
751         let mut inverse_small = [0u8; 64];
752         let mut inverse_big = vec![];
753         let use_small = self.count() <= inverse_small.len();
754
755         // We have to write this logic twice in order to keep the array small.
756         if let FieldPlacement::Arbitrary { ref memory_index, .. } = *self {
757             if use_small {
758                 for i in 0..self.count() {
759                     inverse_small[memory_index[i] as usize] = i as u8;
760                 }
761             } else {
762                 inverse_big = vec![0; self.count()];
763                 for i in 0..self.count() {
764                     inverse_big[memory_index[i] as usize] = i as u32;
765                 }
766             }
767         }
768
769         (0..self.count()).map(move |i| {
770             match *self {
771                 FieldPlacement::Union(_) |
772                 FieldPlacement::Array { .. } => i,
773                 FieldPlacement::Arbitrary { .. } => {
774                     if use_small { inverse_small[i] as usize }
775                     else { inverse_big[i] as usize }
776                 }
777             }
778         })
779     }
780 }
781
782 /// Describes how values of the type are passed by target ABIs,
783 /// in terms of categories of C types there are ABI rules for.
784 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
785 pub enum Abi {
786     Uninhabited,
787     Scalar(Scalar),
788     ScalarPair(Scalar, Scalar),
789     Vector {
790         element: Scalar,
791         count: u64
792     },
793     Aggregate {
794         /// If true, the size is exact, otherwise it's only a lower bound.
795         sized: bool,
796     }
797 }
798
799 impl Abi {
800     /// Returns true if the layout corresponds to an unsized type.
801     pub fn is_unsized(&self) -> bool {
802         match *self {
803             Abi::Uninhabited |
804             Abi::Scalar(_) |
805             Abi::ScalarPair(..) |
806             Abi::Vector { .. } => false,
807             Abi::Aggregate { sized } => !sized
808         }
809     }
810
811     /// Returns true if this is a single signed integer scalar
812     pub fn is_signed(&self) -> bool {
813         match *self {
814             Abi::Scalar(ref scal) => match scal.value {
815                 Primitive::Int(_, signed) => signed,
816                 _ => false,
817             },
818             _ => false,
819         }
820     }
821
822     /// Returns true if this is an uninhabited type
823     pub fn is_uninhabited(&self) -> bool {
824         match *self {
825             Abi::Uninhabited => true,
826             _ => false,
827         }
828     }
829 }
830
831 newtype_index! {
832     pub struct VariantIdx { .. }
833 }
834
835 #[derive(PartialEq, Eq, Hash, Debug)]
836 pub enum Variants {
837     /// Single enum variants, structs/tuples, unions, and all non-ADTs.
838     Single {
839         index: VariantIdx,
840     },
841
842     /// General-case enums: for each case there is a struct, and they all have
843     /// all space reserved for the tag, and their first field starts
844     /// at a non-0 offset, after where the tag would go.
845     Tagged {
846         tag: Scalar,
847         variants: IndexVec<VariantIdx, LayoutDetails>,
848     },
849
850     /// Multiple cases distinguished by a niche (values invalid for a type):
851     /// the variant `dataful_variant` contains a niche at an arbitrary
852     /// offset (field 0 of the enum), which for a variant with discriminant
853     /// `d` is set to `(d - niche_variants.start).wrapping_add(niche_start)`.
854     ///
855     /// For example, `Option<(usize, &T)>`  is represented such that
856     /// `None` has a null pointer for the second tuple field, and
857     /// `Some` is the identity function (with a non-null reference).
858     NicheFilling {
859         dataful_variant: VariantIdx,
860         niche_variants: RangeInclusive<VariantIdx>,
861         niche: Scalar,
862         niche_start: u128,
863         variants: IndexVec<VariantIdx, LayoutDetails>,
864     }
865 }
866
867 #[derive(PartialEq, Eq, Hash, Debug)]
868 pub struct LayoutDetails {
869     pub variants: Variants,
870     pub fields: FieldPlacement,
871     pub abi: Abi,
872     pub align: AbiAndPrefAlign,
873     pub size: Size
874 }
875
876 impl LayoutDetails {
877     pub fn scalar<C: HasDataLayout>(cx: &C, scalar: Scalar) -> Self {
878         let size = scalar.value.size(cx);
879         let align = scalar.value.align(cx);
880         LayoutDetails {
881             variants: Variants::Single { index: VariantIdx::new(0) },
882             fields: FieldPlacement::Union(0),
883             abi: Abi::Scalar(scalar),
884             size,
885             align,
886         }
887     }
888 }
889
890 /// The details of the layout of a type, alongside the type itself.
891 /// Provides various type traversal APIs (e.g. recursing into fields).
892 ///
893 /// Note that the details are NOT guaranteed to always be identical
894 /// to those obtained from `layout_of(ty)`, as we need to produce
895 /// layouts for which Rust types do not exist, such as enum variants
896 /// or synthetic fields of enums (i.e. discriminants) and fat pointers.
897 #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
898 pub struct TyLayout<'a, Ty> {
899     pub ty: Ty,
900     pub details: &'a LayoutDetails
901 }
902
903 impl<'a, Ty> Deref for TyLayout<'a, Ty> {
904     type Target = &'a LayoutDetails;
905     fn deref(&self) -> &&'a LayoutDetails {
906         &self.details
907     }
908 }
909
910 pub trait LayoutOf {
911     type Ty;
912     type TyLayout;
913
914     fn layout_of(&self, ty: Self::Ty) -> Self::TyLayout;
915 }
916
917 pub trait TyLayoutMethods<'a, C: LayoutOf<Ty = Self>>: Sized {
918     fn for_variant(
919         this: TyLayout<'a, Self>,
920         cx: &C,
921         variant_index: VariantIdx,
922     ) -> TyLayout<'a, Self>;
923     fn field(this: TyLayout<'a, Self>, cx: &C, i: usize) -> C::TyLayout;
924 }
925
926 impl<'a, Ty> TyLayout<'a, Ty> {
927     pub fn for_variant<C>(self, cx: &C, variant_index: VariantIdx) -> Self
928     where Ty: TyLayoutMethods<'a, C>, C: LayoutOf<Ty = Ty> {
929         Ty::for_variant(self, cx, variant_index)
930     }
931     pub fn field<C>(self, cx: &C, i: usize) -> C::TyLayout
932     where Ty: TyLayoutMethods<'a, C>, C: LayoutOf<Ty = Ty> {
933         Ty::field(self, cx, i)
934     }
935 }
936
937 impl<'a, Ty> TyLayout<'a, Ty> {
938     /// Returns true if the layout corresponds to an unsized type.
939     pub fn is_unsized(&self) -> bool {
940         self.abi.is_unsized()
941     }
942
943     /// Returns true if the type is a ZST and not unsized.
944     pub fn is_zst(&self) -> bool {
945         match self.abi {
946             Abi::Scalar(_) |
947             Abi::ScalarPair(..) |
948             Abi::Vector { .. } => false,
949             Abi::Uninhabited => self.size.bytes() == 0,
950             Abi::Aggregate { sized } => sized && self.size.bytes() == 0
951         }
952     }
953 }