]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/adt.rs
core: Fix size_hint for signed integer Range<T> iterators
[rust.git] / src / librustc_trans / trans / adt.rs
1 // Copyright 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 //! # Representation of Algebraic Data Types
12 //!
13 //! This module determines how to represent enums, structs, and tuples
14 //! based on their monomorphized types; it is responsible both for
15 //! choosing a representation and translating basic operations on
16 //! values of those types.  (Note: exporting the representations for
17 //! debuggers is handled in debuginfo.rs, not here.)
18 //!
19 //! Note that the interface treats everything as a general case of an
20 //! enum, so structs/tuples/etc. have one pseudo-variant with
21 //! discriminant 0; i.e., as if they were a univariant enum.
22 //!
23 //! Having everything in one place will enable improvements to data
24 //! structure representation; possibilities include:
25 //!
26 //! - User-specified alignment (e.g., cacheline-aligning parts of
27 //!   concurrently accessed data structures); LLVM can't represent this
28 //!   directly, so we'd have to insert padding fields in any structure
29 //!   that might contain one and adjust GEP indices accordingly.  See
30 //!   issue #4578.
31 //!
32 //! - Store nested enums' discriminants in the same word.  Rather, if
33 //!   some variants start with enums, and those enums representations
34 //!   have unused alignment padding between discriminant and body, the
35 //!   outer enum's discriminant can be stored there and those variants
36 //!   can start at offset 0.  Kind of fancy, and might need work to
37 //!   make copies of the inner enum type cooperate, but it could help
38 //!   with `Option` or `Result` wrapped around another enum.
39 //!
40 //! - Tagged pointers would be neat, but given that any type can be
41 //!   used unboxed and any field can have pointers (including mutable)
42 //!   taken to it, implementing them for Rust seems difficult.
43
44 #![allow(unsigned_negation)]
45
46 pub use self::Repr::*;
47
48 use std::rc::Rc;
49
50 use llvm::{ValueRef, True, IntEQ, IntNE};
51 use back::abi::FAT_PTR_ADDR;
52 use middle::subst;
53 use middle::ty::{self, Ty, ClosureTyper};
54 use middle::ty::Disr;
55 use syntax::ast;
56 use syntax::attr;
57 use syntax::attr::IntType;
58 use trans::_match;
59 use trans::build::*;
60 use trans::cleanup;
61 use trans::cleanup::CleanupMethods;
62 use trans::common::*;
63 use trans::datum;
64 use trans::debuginfo::DebugLoc;
65 use trans::machine;
66 use trans::monomorphize;
67 use trans::type_::Type;
68 use trans::type_of;
69 use util::ppaux::ty_to_string;
70
71 type Hint = attr::ReprAttr;
72
73 /// Representations.
74 #[derive(Eq, PartialEq, Debug)]
75 pub enum Repr<'tcx> {
76     /// C-like enums; basically an int.
77     CEnum(IntType, Disr, Disr), // discriminant range (signedness based on the IntType)
78     /// Single-case variants, and structs/tuples/records.
79     ///
80     /// Structs with destructors need a dynamic destroyedness flag to
81     /// avoid running the destructor too many times; this is included
82     /// in the `Struct` if present.
83     /// (The flag if nonzero, represents the initialization value to use;
84     ///  if zero, then use no flag at all.)
85     Univariant(Struct<'tcx>, u8),
86     /// General-case enums: for each case there is a struct, and they
87     /// all start with a field for the discriminant.
88     ///
89     /// Types with destructors need a dynamic destroyedness flag to
90     /// avoid running the destructor too many times; the last argument
91     /// indicates whether such a flag is present.
92     /// (The flag, if nonzero, represents the initialization value to use;
93     ///  if zero, then use no flag at all.)
94     General(IntType, Vec<Struct<'tcx>>, u8),
95     /// Two cases distinguished by a nullable pointer: the case with discriminant
96     /// `nndiscr` must have single field which is known to be nonnull due to its type.
97     /// The other case is known to be zero sized. Hence we represent the enum
98     /// as simply a nullable pointer: if not null it indicates the `nndiscr` variant,
99     /// otherwise it indicates the other case.
100     RawNullablePointer {
101         nndiscr: Disr,
102         nnty: Ty<'tcx>,
103         nullfields: Vec<Ty<'tcx>>
104     },
105     /// Two cases distinguished by a nullable pointer: the case with discriminant
106     /// `nndiscr` is represented by the struct `nonnull`, where the `discrfield`th
107     /// field is known to be nonnull due to its type; if that field is null, then
108     /// it represents the other case, which is inhabited by at most one value
109     /// (and all other fields are undefined/unused).
110     ///
111     /// For example, `std::option::Option` instantiated at a safe pointer type
112     /// is represented such that `None` is a null pointer and `Some` is the
113     /// identity function.
114     StructWrappedNullablePointer {
115         nonnull: Struct<'tcx>,
116         nndiscr: Disr,
117         discrfield: DiscrField,
118         nullfields: Vec<Ty<'tcx>>,
119     }
120 }
121
122 /// For structs, and struct-like parts of anything fancier.
123 #[derive(Eq, PartialEq, Debug)]
124 pub struct Struct<'tcx> {
125     // If the struct is DST, then the size and alignment do not take into
126     // account the unsized fields of the struct.
127     pub size: u64,
128     pub align: u32,
129     pub sized: bool,
130     pub packed: bool,
131     pub fields: Vec<Ty<'tcx>>
132 }
133
134 /// Convenience for `represent_type`.  There should probably be more or
135 /// these, for places in trans where the `Ty` isn't directly
136 /// available.
137 pub fn represent_node<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
138                                   node: ast::NodeId) -> Rc<Repr<'tcx>> {
139     represent_type(bcx.ccx(), node_id_type(bcx, node))
140 }
141
142 /// Decides how to represent a given type.
143 pub fn represent_type<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
144                                 t: Ty<'tcx>) -> Rc<Repr<'tcx>> {
145     debug!("Representing: {}", ty_to_string(cx.tcx(), t));
146     match cx.adt_reprs().borrow().get(&t) {
147         Some(repr) => return repr.clone(),
148         None => {}
149     }
150
151     let repr = Rc::new(represent_type_uncached(cx, t));
152     debug!("Represented as: {:?}", repr);
153     cx.adt_reprs().borrow_mut().insert(t, repr.clone());
154     repr
155 }
156
157 macro_rules! repeat_u8_as_u32 {
158     ($name:expr) => { (($name as u32) << 24 |
159                        ($name as u32) << 16 |
160                        ($name as u32) <<  8 |
161                        ($name as u32)) }
162 }
163 macro_rules! repeat_u8_as_u64 {
164     ($name:expr) => { ((repeat_u8_as_u32!($name) as u64) << 32 |
165                        (repeat_u8_as_u32!($name) as u64)) }
166 }
167
168 pub const DTOR_NEEDED: u8 = 0xd4;
169 pub const DTOR_NEEDED_U32: u32 = repeat_u8_as_u32!(DTOR_NEEDED);
170 pub const DTOR_NEEDED_U64: u64 = repeat_u8_as_u64!(DTOR_NEEDED);
171 #[allow(dead_code)]
172 pub fn dtor_needed_usize(ccx: &CrateContext) -> usize {
173     match &ccx.tcx().sess.target.target.target_pointer_width[..] {
174         "32" => DTOR_NEEDED_U32 as usize,
175         "64" => DTOR_NEEDED_U64 as usize,
176         tws => panic!("Unsupported target word size for int: {}", tws),
177     }
178 }
179
180 pub const DTOR_DONE: u8 = 0x1d;
181 pub const DTOR_DONE_U32: u32 = repeat_u8_as_u32!(DTOR_DONE);
182 pub const DTOR_DONE_U64: u64 = repeat_u8_as_u64!(DTOR_DONE);
183 #[allow(dead_code)]
184 pub fn dtor_done_usize(ccx: &CrateContext) -> usize {
185     match &ccx.tcx().sess.target.target.target_pointer_width[..] {
186         "32" => DTOR_DONE_U32 as usize,
187         "64" => DTOR_DONE_U64 as usize,
188         tws => panic!("Unsupported target word size for int: {}", tws),
189     }
190 }
191
192 fn dtor_to_init_u8(dtor: bool) -> u8 {
193     if dtor { DTOR_NEEDED } else { 0 }
194 }
195
196 pub trait GetDtorType<'tcx> { fn dtor_type(&self) -> Ty<'tcx>; }
197 impl<'tcx> GetDtorType<'tcx> for ty::ctxt<'tcx> {
198     fn dtor_type(&self) -> Ty<'tcx> { self.types.u8 }
199 }
200
201 fn dtor_active(flag: u8) -> bool {
202     flag != 0
203 }
204
205 fn represent_type_uncached<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
206                                      t: Ty<'tcx>) -> Repr<'tcx> {
207     match t.sty {
208         ty::ty_tup(ref elems) => {
209             Univariant(mk_struct(cx, &elems[..], false, t), 0)
210         }
211         ty::ty_struct(def_id, substs) => {
212             let fields = ty::lookup_struct_fields(cx.tcx(), def_id);
213             let mut ftys = fields.iter().map(|field| {
214                 let fty = ty::lookup_field_type(cx.tcx(), def_id, field.id, substs);
215                 monomorphize::normalize_associated_type(cx.tcx(), &fty)
216             }).collect::<Vec<_>>();
217             let packed = ty::lookup_packed(cx.tcx(), def_id);
218             let dtor = ty::ty_dtor(cx.tcx(), def_id).has_drop_flag();
219             if dtor { ftys.push(cx.tcx().dtor_type()); }
220
221             Univariant(mk_struct(cx, &ftys[..], packed, t), dtor_to_init_u8(dtor))
222         }
223         ty::ty_closure(def_id, substs) => {
224             let typer = NormalizingClosureTyper::new(cx.tcx());
225             let upvars = typer.closure_upvars(def_id, substs).unwrap();
226             let upvar_types = upvars.iter().map(|u| u.ty).collect::<Vec<_>>();
227             Univariant(mk_struct(cx, &upvar_types[..], false, t), 0)
228         }
229         ty::ty_enum(def_id, substs) => {
230             let cases = get_cases(cx.tcx(), def_id, substs);
231             let hint = *ty::lookup_repr_hints(cx.tcx(), def_id).get(0)
232                 .unwrap_or(&attr::ReprAny);
233
234             let dtor = ty::ty_dtor(cx.tcx(), def_id).has_drop_flag();
235
236             if cases.is_empty() {
237                 // Uninhabitable; represent as unit
238                 // (Typechecking will reject discriminant-sizing attrs.)
239                 assert_eq!(hint, attr::ReprAny);
240                 let ftys = if dtor { vec!(cx.tcx().dtor_type()) } else { vec!() };
241                 return Univariant(mk_struct(cx, &ftys[..], false, t),
242                                   dtor_to_init_u8(dtor));
243             }
244
245             if !dtor && cases.iter().all(|c| c.tys.is_empty()) {
246                 // All bodies empty -> intlike
247                 let discrs: Vec<u64> = cases.iter().map(|c| c.discr).collect();
248                 let bounds = IntBounds {
249                     ulo: *discrs.iter().min().unwrap(),
250                     uhi: *discrs.iter().max().unwrap(),
251                     slo: discrs.iter().map(|n| *n as i64).min().unwrap(),
252                     shi: discrs.iter().map(|n| *n as i64).max().unwrap()
253                 };
254                 return mk_cenum(cx, hint, &bounds);
255             }
256
257             // Since there's at least one
258             // non-empty body, explicit discriminants should have
259             // been rejected by a checker before this point.
260             if !cases.iter().enumerate().all(|(i,c)| c.discr == (i as Disr)) {
261                 cx.sess().bug(&format!("non-C-like enum {} with specified \
262                                       discriminants",
263                                       ty::item_path_str(cx.tcx(),
264                                                         def_id)));
265             }
266
267             if cases.len() == 1 {
268                 // Equivalent to a struct/tuple/newtype.
269                 // (Typechecking will reject discriminant-sizing attrs.)
270                 assert_eq!(hint, attr::ReprAny);
271                 let mut ftys = cases[0].tys.clone();
272                 if dtor { ftys.push(cx.tcx().dtor_type()); }
273                 return Univariant(mk_struct(cx, &ftys[..], false, t),
274                                   dtor_to_init_u8(dtor));
275             }
276
277             if !dtor && cases.len() == 2 && hint == attr::ReprAny {
278                 // Nullable pointer optimization
279                 let mut discr = 0;
280                 while discr < 2 {
281                     if cases[1 - discr].is_zerolen(cx, t) {
282                         let st = mk_struct(cx, &cases[discr].tys,
283                                            false, t);
284                         match cases[discr].find_ptr(cx) {
285                             Some(ref df) if df.len() == 1 && st.fields.len() == 1 => {
286                                 return RawNullablePointer {
287                                     nndiscr: discr as Disr,
288                                     nnty: st.fields[0],
289                                     nullfields: cases[1 - discr].tys.clone()
290                                 };
291                             }
292                             Some(mut discrfield) => {
293                                 discrfield.push(0);
294                                 discrfield.reverse();
295                                 return StructWrappedNullablePointer {
296                                     nndiscr: discr as Disr,
297                                     nonnull: st,
298                                     discrfield: discrfield,
299                                     nullfields: cases[1 - discr].tys.clone()
300                                 };
301                             }
302                             None => {}
303                         }
304                     }
305                     discr += 1;
306                 }
307             }
308
309             // The general case.
310             assert!((cases.len() - 1) as i64 >= 0);
311             let bounds = IntBounds { ulo: 0, uhi: (cases.len() - 1) as u64,
312                                      slo: 0, shi: (cases.len() - 1) as i64 };
313             let min_ity = range_to_inttype(cx, hint, &bounds);
314
315             // Create the set of structs that represent each variant
316             // Use the minimum integer type we figured out above
317             let fields : Vec<_> = cases.iter().map(|c| {
318                 let mut ftys = vec!(ty_of_inttype(cx.tcx(), min_ity));
319                 ftys.push_all(&c.tys);
320                 if dtor { ftys.push(cx.tcx().dtor_type()); }
321                 mk_struct(cx, &ftys, false, t)
322             }).collect();
323
324
325             // Check to see if we should use a different type for the
326             // discriminant. If the overall alignment of the type is
327             // the same as the first field in each variant, we can safely use
328             // an alignment-sized type.
329             // We increase the size of the discriminant to avoid LLVM copying
330             // padding when it doesn't need to. This normally causes unaligned
331             // load/stores and excessive memcpy/memset operations. By using a
332             // bigger integer size, LLVM can be sure about it's contents and
333             // won't be so conservative.
334             // This check is needed to avoid increasing the size of types when
335             // the alignment of the first field is smaller than the overall
336             // alignment of the type.
337             let (_, align) = union_size_and_align(&fields);
338             let mut use_align = true;
339             for st in &fields {
340                 // Get the first non-zero-sized field
341                 let field = st.fields.iter().skip(1).filter(|ty| {
342                     let t = type_of::sizing_type_of(cx, **ty);
343                     machine::llsize_of_real(cx, t) != 0 ||
344                     // This case is only relevant for zero-sized types with large alignment
345                     machine::llalign_of_min(cx, t) != 1
346                 }).next();
347
348                 if let Some(field) = field {
349                     let field_align = type_of::align_of(cx, *field);
350                     if field_align != align {
351                         use_align = false;
352                         break;
353                     }
354                 }
355             }
356             let ity = if use_align {
357                 // Use the overall alignment
358                 match align {
359                     1 => attr::UnsignedInt(ast::TyU8),
360                     2 => attr::UnsignedInt(ast::TyU16),
361                     4 => attr::UnsignedInt(ast::TyU32),
362                     8 if machine::llalign_of_min(cx, Type::i64(cx)) == 8 =>
363                         attr::UnsignedInt(ast::TyU64),
364                     _ => min_ity // use min_ity as a fallback
365                 }
366             } else {
367                 min_ity
368             };
369
370             let fields : Vec<_> = cases.iter().map(|c| {
371                 let mut ftys = vec!(ty_of_inttype(cx.tcx(), ity));
372                 ftys.push_all(&c.tys);
373                 if dtor { ftys.push(cx.tcx().dtor_type()); }
374                 mk_struct(cx, &ftys[..], false, t)
375             }).collect();
376
377             ensure_enum_fits_in_address_space(cx, &fields[..], t);
378
379             General(ity, fields, dtor_to_init_u8(dtor))
380         }
381         _ => cx.sess().bug(&format!("adt::represent_type called on non-ADT type: {}",
382                            ty_to_string(cx.tcx(), t)))
383     }
384 }
385
386 // this should probably all be in ty
387 struct Case<'tcx> {
388     discr: Disr,
389     tys: Vec<Ty<'tcx>>
390 }
391
392 /// This represents the (GEP) indices to follow to get to the discriminant field
393 pub type DiscrField = Vec<usize>;
394
395 fn find_discr_field_candidate<'tcx>(tcx: &ty::ctxt<'tcx>,
396                                     ty: Ty<'tcx>,
397                                     mut path: DiscrField) -> Option<DiscrField> {
398     match ty.sty {
399         // Fat &T/&mut T/Box<T> i.e. T is [T], str, or Trait
400         ty::ty_rptr(_, ty::mt { ty, .. }) | ty::ty_uniq(ty) if !type_is_sized(tcx, ty) => {
401             path.push(FAT_PTR_ADDR);
402             Some(path)
403         },
404
405         // Regular thin pointer: &T/&mut T/Box<T>
406         ty::ty_rptr(..) | ty::ty_uniq(..) => Some(path),
407
408         // Functions are just pointers
409         ty::ty_bare_fn(..) => Some(path),
410
411         // Is this the NonZero lang item wrapping a pointer or integer type?
412         ty::ty_struct(did, substs) if Some(did) == tcx.lang_items.non_zero() => {
413             let nonzero_fields = ty::lookup_struct_fields(tcx, did);
414             assert_eq!(nonzero_fields.len(), 1);
415             let nonzero_field = ty::lookup_field_type(tcx, did, nonzero_fields[0].id, substs);
416             match nonzero_field.sty {
417                 ty::ty_ptr(..) | ty::ty_int(..) | ty::ty_uint(..) => {
418                     path.push(0);
419                     Some(path)
420                 },
421                 _ => None
422             }
423         },
424
425         // Perhaps one of the fields of this struct is non-zero
426         // let's recurse and find out
427         ty::ty_struct(def_id, substs) => {
428             let fields = ty::lookup_struct_fields(tcx, def_id);
429             for (j, field) in fields.iter().enumerate() {
430                 let field_ty = ty::lookup_field_type(tcx, def_id, field.id, substs);
431                 if let Some(mut fpath) = find_discr_field_candidate(tcx, field_ty, path.clone()) {
432                     fpath.push(j);
433                     return Some(fpath);
434                 }
435             }
436             None
437         },
438
439         // Can we use one of the fields in this tuple?
440         ty::ty_tup(ref tys) => {
441             for (j, &ty) in tys.iter().enumerate() {
442                 if let Some(mut fpath) = find_discr_field_candidate(tcx, ty, path.clone()) {
443                     fpath.push(j);
444                     return Some(fpath);
445                 }
446             }
447             None
448         },
449
450         // Is this a fixed-size array of something non-zero
451         // with at least one element?
452         ty::ty_vec(ety, Some(d)) if d > 0 => {
453             if let Some(mut vpath) = find_discr_field_candidate(tcx, ety, path) {
454                 vpath.push(0);
455                 Some(vpath)
456             } else {
457                 None
458             }
459         },
460
461         // Anything else is not a pointer
462         _ => None
463     }
464 }
465
466 impl<'tcx> Case<'tcx> {
467     fn is_zerolen<'a>(&self, cx: &CrateContext<'a, 'tcx>, scapegoat: Ty<'tcx>) -> bool {
468         mk_struct(cx, &self.tys, false, scapegoat).size == 0
469     }
470
471     fn find_ptr<'a>(&self, cx: &CrateContext<'a, 'tcx>) -> Option<DiscrField> {
472         for (i, &ty) in self.tys.iter().enumerate() {
473             if let Some(mut path) = find_discr_field_candidate(cx.tcx(), ty, vec![]) {
474                 path.push(i);
475                 return Some(path);
476             }
477         }
478         None
479     }
480 }
481
482 fn get_cases<'tcx>(tcx: &ty::ctxt<'tcx>,
483                    def_id: ast::DefId,
484                    substs: &subst::Substs<'tcx>)
485                    -> Vec<Case<'tcx>> {
486     ty::enum_variants(tcx, def_id).iter().map(|vi| {
487         let arg_tys = vi.args.iter().map(|&raw_ty| {
488             monomorphize::apply_param_substs(tcx, substs, &raw_ty)
489         }).collect();
490         Case { discr: vi.disr_val, tys: arg_tys }
491     }).collect()
492 }
493
494 fn mk_struct<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
495                        tys: &[Ty<'tcx>], packed: bool,
496                        scapegoat: Ty<'tcx>)
497                        -> Struct<'tcx> {
498     let sized = tys.iter().all(|&ty| type_is_sized(cx.tcx(), ty));
499     let lltys : Vec<Type> = if sized {
500         tys.iter()
501            .map(|&ty| type_of::sizing_type_of(cx, ty)).collect()
502     } else {
503         tys.iter().filter(|&ty| type_is_sized(cx.tcx(), *ty))
504            .map(|&ty| type_of::sizing_type_of(cx, ty)).collect()
505     };
506
507     ensure_struct_fits_in_address_space(cx, &lltys[..], packed, scapegoat);
508
509     let llty_rec = Type::struct_(cx, &lltys[..], packed);
510     Struct {
511         size: machine::llsize_of_alloc(cx, llty_rec),
512         align: machine::llalign_of_min(cx, llty_rec),
513         sized: sized,
514         packed: packed,
515         fields: tys.to_vec(),
516     }
517 }
518
519 #[derive(Debug)]
520 struct IntBounds {
521     slo: i64,
522     shi: i64,
523     ulo: u64,
524     uhi: u64
525 }
526
527 fn mk_cenum<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
528                       hint: Hint, bounds: &IntBounds)
529                       -> Repr<'tcx> {
530     let it = range_to_inttype(cx, hint, bounds);
531     match it {
532         attr::SignedInt(_) => CEnum(it, bounds.slo as Disr, bounds.shi as Disr),
533         attr::UnsignedInt(_) => CEnum(it, bounds.ulo, bounds.uhi)
534     }
535 }
536
537 fn range_to_inttype(cx: &CrateContext, hint: Hint, bounds: &IntBounds) -> IntType {
538     debug!("range_to_inttype: {:?} {:?}", hint, bounds);
539     // Lists of sizes to try.  u64 is always allowed as a fallback.
540     #[allow(non_upper_case_globals)]
541     const choose_shortest: &'static [IntType] = &[
542         attr::UnsignedInt(ast::TyU8), attr::SignedInt(ast::TyI8),
543         attr::UnsignedInt(ast::TyU16), attr::SignedInt(ast::TyI16),
544         attr::UnsignedInt(ast::TyU32), attr::SignedInt(ast::TyI32)];
545     #[allow(non_upper_case_globals)]
546     const at_least_32: &'static [IntType] = &[
547         attr::UnsignedInt(ast::TyU32), attr::SignedInt(ast::TyI32)];
548
549     let attempts;
550     match hint {
551         attr::ReprInt(span, ity) => {
552             if !bounds_usable(cx, ity, bounds) {
553                 cx.sess().span_bug(span, "representation hint insufficient for discriminant range")
554             }
555             return ity;
556         }
557         attr::ReprExtern => {
558             attempts = match &cx.sess().target.target.arch[..] {
559                 // WARNING: the ARM EABI has two variants; the one corresponding to `at_least_32`
560                 // appears to be used on Linux and NetBSD, but some systems may use the variant
561                 // corresponding to `choose_shortest`.  However, we don't run on those yet...?
562                 "arm" => at_least_32,
563                 _ => at_least_32,
564             }
565         }
566         attr::ReprAny => {
567             attempts = choose_shortest;
568         },
569         attr::ReprPacked => {
570             cx.tcx().sess.bug("range_to_inttype: found ReprPacked on an enum");
571         }
572     }
573     for &ity in attempts {
574         if bounds_usable(cx, ity, bounds) {
575             return ity;
576         }
577     }
578     return attr::UnsignedInt(ast::TyU64);
579 }
580
581 pub fn ll_inttype(cx: &CrateContext, ity: IntType) -> Type {
582     match ity {
583         attr::SignedInt(t) => Type::int_from_ty(cx, t),
584         attr::UnsignedInt(t) => Type::uint_from_ty(cx, t)
585     }
586 }
587
588 fn bounds_usable(cx: &CrateContext, ity: IntType, bounds: &IntBounds) -> bool {
589     debug!("bounds_usable: {:?} {:?}", ity, bounds);
590     match ity {
591         attr::SignedInt(_) => {
592             let lllo = C_integral(ll_inttype(cx, ity), bounds.slo as u64, true);
593             let llhi = C_integral(ll_inttype(cx, ity), bounds.shi as u64, true);
594             bounds.slo == const_to_int(lllo) as i64 && bounds.shi == const_to_int(llhi) as i64
595         }
596         attr::UnsignedInt(_) => {
597             let lllo = C_integral(ll_inttype(cx, ity), bounds.ulo, false);
598             let llhi = C_integral(ll_inttype(cx, ity), bounds.uhi, false);
599             bounds.ulo == const_to_uint(lllo) as u64 && bounds.uhi == const_to_uint(llhi) as u64
600         }
601     }
602 }
603
604 pub fn ty_of_inttype<'tcx>(tcx: &ty::ctxt<'tcx>, ity: IntType) -> Ty<'tcx> {
605     match ity {
606         attr::SignedInt(t) => ty::mk_mach_int(tcx, t),
607         attr::UnsignedInt(t) => ty::mk_mach_uint(tcx, t)
608     }
609 }
610
611 // LLVM doesn't like types that don't fit in the address space
612 fn ensure_struct_fits_in_address_space<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
613                                                  fields: &[Type],
614                                                  packed: bool,
615                                                  scapegoat: Ty<'tcx>) {
616     let mut offset = 0;
617     for &llty in fields {
618         // Invariant: offset < ccx.obj_size_bound() <= 1<<61
619         if !packed {
620             let type_align = machine::llalign_of_min(ccx, llty);
621             offset = roundup(offset, type_align);
622         }
623         // type_align is a power-of-2, so still offset < ccx.obj_size_bound()
624         // llsize_of_alloc(ccx, llty) is also less than ccx.obj_size_bound()
625         // so the sum is less than 1<<62 (and therefore can't overflow).
626         offset += machine::llsize_of_alloc(ccx, llty);
627
628         if offset >= ccx.obj_size_bound() {
629             ccx.report_overbig_object(scapegoat);
630         }
631     }
632 }
633
634 fn union_size_and_align(sts: &[Struct]) -> (machine::llsize, machine::llalign) {
635     let size = sts.iter().map(|st| st.size).max().unwrap();
636     let align = sts.iter().map(|st| st.align).max().unwrap();
637     (roundup(size, align), align)
638 }
639
640 fn ensure_enum_fits_in_address_space<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
641                                                fields: &[Struct],
642                                                scapegoat: Ty<'tcx>) {
643     let (total_size, _) = union_size_and_align(fields);
644
645     if total_size >= ccx.obj_size_bound() {
646         ccx.report_overbig_object(scapegoat);
647     }
648 }
649
650
651 /// LLVM-level types are a little complicated.
652 ///
653 /// C-like enums need to be actual ints, not wrapped in a struct,
654 /// because that changes the ABI on some platforms (see issue #10308).
655 ///
656 /// For nominal types, in some cases, we need to use LLVM named structs
657 /// and fill in the actual contents in a second pass to prevent
658 /// unbounded recursion; see also the comments in `trans::type_of`.
659 pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, r: &Repr<'tcx>) -> Type {
660     generic_type_of(cx, r, None, false, false)
661 }
662 // Pass dst=true if the type you are passing is a DST. Yes, we could figure
663 // this out, but if you call this on an unsized type without realising it, you
664 // are going to get the wrong type (it will not include the unsized parts of it).
665 pub fn sizing_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
666                                 r: &Repr<'tcx>, dst: bool) -> Type {
667     generic_type_of(cx, r, None, true, dst)
668 }
669 pub fn incomplete_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
670                                     r: &Repr<'tcx>, name: &str) -> Type {
671     generic_type_of(cx, r, Some(name), false, false)
672 }
673 pub fn finish_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
674                                 r: &Repr<'tcx>, llty: &mut Type) {
675     match *r {
676         CEnum(..) | General(..) | RawNullablePointer { .. } => { }
677         Univariant(ref st, _) | StructWrappedNullablePointer { nonnull: ref st, .. } =>
678             llty.set_struct_body(&struct_llfields(cx, st, false, false),
679                                  st.packed)
680     }
681 }
682
683 fn generic_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
684                              r: &Repr<'tcx>,
685                              name: Option<&str>,
686                              sizing: bool,
687                              dst: bool) -> Type {
688     match *r {
689         CEnum(ity, _, _) => ll_inttype(cx, ity),
690         RawNullablePointer { nnty, .. } => type_of::sizing_type_of(cx, nnty),
691         Univariant(ref st, _) | StructWrappedNullablePointer { nonnull: ref st, .. } => {
692             match name {
693                 None => {
694                     Type::struct_(cx, &struct_llfields(cx, st, sizing, dst),
695                                   st.packed)
696                 }
697                 Some(name) => { assert_eq!(sizing, false); Type::named_struct(cx, name) }
698             }
699         }
700         General(ity, ref sts, _) => {
701             // We need a representation that has:
702             // * The alignment of the most-aligned field
703             // * The size of the largest variant (rounded up to that alignment)
704             // * No alignment padding anywhere any variant has actual data
705             //   (currently matters only for enums small enough to be immediate)
706             // * The discriminant in an obvious place.
707             //
708             // So we start with the discriminant, pad it up to the alignment with
709             // more of its own type, then use alignment-sized ints to get the rest
710             // of the size.
711             //
712             // FIXME #10604: this breaks when vector types are present.
713             let (size, align) = union_size_and_align(&sts[..]);
714             let align_s = align as u64;
715             assert_eq!(size % align_s, 0);
716             let align_units = size / align_s - 1;
717
718             let discr_ty = ll_inttype(cx, ity);
719             let discr_size = machine::llsize_of_alloc(cx, discr_ty);
720             let fill_ty = match align_s {
721                 1 => Type::array(&Type::i8(cx), align_units),
722                 2 => Type::array(&Type::i16(cx), align_units),
723                 4 => Type::array(&Type::i32(cx), align_units),
724                 8 if machine::llalign_of_min(cx, Type::i64(cx)) == 8 =>
725                                  Type::array(&Type::i64(cx), align_units),
726                 a if a.count_ones() == 1 => Type::array(&Type::vector(&Type::i32(cx), a / 4),
727                                                               align_units),
728                 _ => panic!("unsupported enum alignment: {}", align)
729             };
730             assert_eq!(machine::llalign_of_min(cx, fill_ty), align);
731             assert_eq!(align_s % discr_size, 0);
732             let fields = [discr_ty,
733                           Type::array(&discr_ty, align_s / discr_size - 1),
734                           fill_ty];
735             match name {
736                 None => Type::struct_(cx, &fields[..], false),
737                 Some(name) => {
738                     let mut llty = Type::named_struct(cx, name);
739                     llty.set_struct_body(&fields[..], false);
740                     llty
741                 }
742             }
743         }
744     }
745 }
746
747 fn struct_llfields<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, st: &Struct<'tcx>,
748                              sizing: bool, dst: bool) -> Vec<Type> {
749     if sizing {
750         st.fields.iter().filter(|&ty| !dst || type_is_sized(cx.tcx(), *ty))
751             .map(|&ty| type_of::sizing_type_of(cx, ty)).collect()
752     } else {
753         st.fields.iter().map(|&ty| type_of::in_memory_type_of(cx, ty)).collect()
754     }
755 }
756
757 /// Obtain a representation of the discriminant sufficient to translate
758 /// destructuring; this may or may not involve the actual discriminant.
759 ///
760 /// This should ideally be less tightly tied to `_match`.
761 pub fn trans_switch<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
762                                 r: &Repr<'tcx>, scrutinee: ValueRef)
763                                 -> (_match::BranchKind, Option<ValueRef>) {
764     match *r {
765         CEnum(..) | General(..) |
766         RawNullablePointer { .. } | StructWrappedNullablePointer { .. } => {
767             (_match::Switch, Some(trans_get_discr(bcx, r, scrutinee, None)))
768         }
769         Univariant(..) => {
770             (_match::Single, None)
771         }
772     }
773 }
774
775
776
777 /// Obtain the actual discriminant of a value.
778 pub fn trans_get_discr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>,
779                                    scrutinee: ValueRef, cast_to: Option<Type>)
780     -> ValueRef {
781     let signed;
782     let val;
783     debug!("trans_get_discr r: {:?}", r);
784     match *r {
785         CEnum(ity, min, max) => {
786             val = load_discr(bcx, ity, scrutinee, min, max);
787             signed = ity.is_signed();
788         }
789         General(ity, ref cases, _) => {
790             let ptr = GEPi(bcx, scrutinee, &[0, 0]);
791             val = load_discr(bcx, ity, ptr, 0, (cases.len() - 1) as Disr);
792             signed = ity.is_signed();
793         }
794         Univariant(..) => {
795             val = C_u8(bcx.ccx(), 0);
796             signed = false;
797         }
798         RawNullablePointer { nndiscr, nnty, .. } =>  {
799             let cmp = if nndiscr == 0 { IntEQ } else { IntNE };
800             let llptrty = type_of::sizing_type_of(bcx.ccx(), nnty);
801             val = ICmp(bcx, cmp, Load(bcx, scrutinee), C_null(llptrty), DebugLoc::None);
802             signed = false;
803         }
804         StructWrappedNullablePointer { nndiscr, ref discrfield, .. } => {
805             val = struct_wrapped_nullable_bitdiscr(bcx, nndiscr, discrfield, scrutinee);
806             signed = false;
807         }
808     }
809     match cast_to {
810         None => val,
811         Some(llty) => if signed { SExt(bcx, val, llty) } else { ZExt(bcx, val, llty) }
812     }
813 }
814
815 fn struct_wrapped_nullable_bitdiscr(bcx: Block, nndiscr: Disr, discrfield: &DiscrField,
816                                     scrutinee: ValueRef) -> ValueRef {
817     let llptrptr = GEPi(bcx, scrutinee, &discrfield[..]);
818     let llptr = Load(bcx, llptrptr);
819     let cmp = if nndiscr == 0 { IntEQ } else { IntNE };
820     ICmp(bcx, cmp, llptr, C_null(val_ty(llptr)), DebugLoc::None)
821 }
822
823 /// Helper for cases where the discriminant is simply loaded.
824 fn load_discr(bcx: Block, ity: IntType, ptr: ValueRef, min: Disr, max: Disr)
825     -> ValueRef {
826     let llty = ll_inttype(bcx.ccx(), ity);
827     assert_eq!(val_ty(ptr), llty.ptr_to());
828     let bits = machine::llbitsize_of_real(bcx.ccx(), llty);
829     assert!(bits <= 64);
830     let  bits = bits as usize;
831     let mask = (!0u64 >> (64 - bits)) as Disr;
832     // For a (max) discr of -1, max will be `-1 as usize`, which overflows.
833     // However, that is fine here (it would still represent the full range),
834     if (max.wrapping_add(1)) & mask == min & mask {
835         // i.e., if the range is everything.  The lo==hi case would be
836         // rejected by the LLVM verifier (it would mean either an
837         // empty set, which is impossible, or the entire range of the
838         // type, which is pointless).
839         Load(bcx, ptr)
840     } else {
841         // llvm::ConstantRange can deal with ranges that wrap around,
842         // so an overflow on (max + 1) is fine.
843         LoadRangeAssert(bcx, ptr, min, (max.wrapping_add(1)), /* signed: */ True)
844     }
845 }
846
847 /// Yield information about how to dispatch a case of the
848 /// discriminant-like value returned by `trans_switch`.
849 ///
850 /// This should ideally be less tightly tied to `_match`.
851 pub fn trans_case<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr, discr: Disr)
852                               -> _match::OptResult<'blk, 'tcx> {
853     match *r {
854         CEnum(ity, _, _) => {
855             _match::SingleResult(Result::new(bcx, C_integral(ll_inttype(bcx.ccx(), ity),
856                                                               discr as u64, true)))
857         }
858         General(ity, _, _) => {
859             _match::SingleResult(Result::new(bcx, C_integral(ll_inttype(bcx.ccx(), ity),
860                                                               discr as u64, true)))
861         }
862         Univariant(..) => {
863             bcx.ccx().sess().bug("no cases for univariants or structs")
864         }
865         RawNullablePointer { .. } |
866         StructWrappedNullablePointer { .. } => {
867             assert!(discr == 0 || discr == 1);
868             _match::SingleResult(Result::new(bcx, C_bool(bcx.ccx(), discr != 0)))
869         }
870     }
871 }
872
873 /// Set the discriminant for a new value of the given case of the given
874 /// representation.
875 pub fn trans_set_discr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>,
876                                    val: ValueRef, discr: Disr) {
877     match *r {
878         CEnum(ity, min, max) => {
879             assert_discr_in_range(ity, min, max, discr);
880             Store(bcx, C_integral(ll_inttype(bcx.ccx(), ity), discr as u64, true),
881                   val);
882         }
883         General(ity, ref cases, dtor) => {
884             if dtor_active(dtor) {
885                 let ptr = trans_field_ptr(bcx, r, val, discr,
886                                           cases[discr as usize].fields.len() - 2);
887                 Store(bcx, C_u8(bcx.ccx(), DTOR_NEEDED as usize), ptr);
888             }
889             Store(bcx, C_integral(ll_inttype(bcx.ccx(), ity), discr as u64, true),
890                   GEPi(bcx, val, &[0, 0]));
891         }
892         Univariant(ref st, dtor) => {
893             assert_eq!(discr, 0);
894             if dtor_active(dtor) {
895                 Store(bcx, C_u8(bcx.ccx(), DTOR_NEEDED as usize),
896                     GEPi(bcx, val, &[0, st.fields.len() - 1]));
897             }
898         }
899         RawNullablePointer { nndiscr, nnty, ..} => {
900             if discr != nndiscr {
901                 let llptrty = type_of::sizing_type_of(bcx.ccx(), nnty);
902                 Store(bcx, C_null(llptrty), val);
903             }
904         }
905         StructWrappedNullablePointer { nndiscr, ref discrfield, .. } => {
906             if discr != nndiscr {
907                 let llptrptr = GEPi(bcx, val, &discrfield[..]);
908                 let llptrty = val_ty(llptrptr).element_type();
909                 Store(bcx, C_null(llptrty), llptrptr);
910             }
911         }
912     }
913 }
914
915 fn assert_discr_in_range(ity: IntType, min: Disr, max: Disr, discr: Disr) {
916     match ity {
917         attr::UnsignedInt(_) => assert!(min <= discr && discr <= max),
918         attr::SignedInt(_) => assert!(min as i64 <= discr as i64 && discr as i64 <= max as i64)
919     }
920 }
921
922 /// The number of fields in a given case; for use when obtaining this
923 /// information from the type or definition is less convenient.
924 pub fn num_args(r: &Repr, discr: Disr) -> usize {
925     match *r {
926         CEnum(..) => 0,
927         Univariant(ref st, dtor) => {
928             assert_eq!(discr, 0);
929             st.fields.len() - (if dtor_active(dtor) { 1 } else { 0 })
930         }
931         General(_, ref cases, dtor) => {
932             cases[discr as usize].fields.len() - 1 - (if dtor_active(dtor) { 1 } else { 0 })
933         }
934         RawNullablePointer { nndiscr, ref nullfields, .. } => {
935             if discr == nndiscr { 1 } else { nullfields.len() }
936         }
937         StructWrappedNullablePointer { ref nonnull, nndiscr,
938                                        ref nullfields, .. } => {
939             if discr == nndiscr { nonnull.fields.len() } else { nullfields.len() }
940         }
941     }
942 }
943
944 /// Access a field, at a point when the value's case is known.
945 pub fn trans_field_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>,
946                                    val: ValueRef, discr: Disr, ix: usize) -> ValueRef {
947     // Note: if this ever needs to generate conditionals (e.g., if we
948     // decide to do some kind of cdr-coding-like non-unique repr
949     // someday), it will need to return a possibly-new bcx as well.
950     match *r {
951         CEnum(..) => {
952             bcx.ccx().sess().bug("element access in C-like enum")
953         }
954         Univariant(ref st, _dtor) => {
955             assert_eq!(discr, 0);
956             struct_field_ptr(bcx, st, val, ix, false)
957         }
958         General(_, ref cases, _) => {
959             struct_field_ptr(bcx, &cases[discr as usize], val, ix + 1, true)
960         }
961         RawNullablePointer { nndiscr, ref nullfields, .. } |
962         StructWrappedNullablePointer { nndiscr, ref nullfields, .. } if discr != nndiscr => {
963             // The unit-like case might have a nonzero number of unit-like fields.
964             // (e.d., Result of Either with (), as one side.)
965             let ty = type_of::type_of(bcx.ccx(), nullfields[ix]);
966             assert_eq!(machine::llsize_of_alloc(bcx.ccx(), ty), 0);
967             // The contents of memory at this pointer can't matter, but use
968             // the value that's "reasonable" in case of pointer comparison.
969             PointerCast(bcx, val, ty.ptr_to())
970         }
971         RawNullablePointer { nndiscr, nnty, .. } => {
972             assert_eq!(ix, 0);
973             assert_eq!(discr, nndiscr);
974             let ty = type_of::type_of(bcx.ccx(), nnty);
975             PointerCast(bcx, val, ty.ptr_to())
976         }
977         StructWrappedNullablePointer { ref nonnull, nndiscr, .. } => {
978             assert_eq!(discr, nndiscr);
979             struct_field_ptr(bcx, nonnull, val, ix, false)
980         }
981     }
982 }
983
984 pub fn struct_field_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, st: &Struct<'tcx>, val: ValueRef,
985                                     ix: usize, needs_cast: bool) -> ValueRef {
986     let val = if needs_cast {
987         let ccx = bcx.ccx();
988         let fields = st.fields.iter().map(|&ty| type_of::type_of(ccx, ty)).collect::<Vec<_>>();
989         let real_ty = Type::struct_(ccx, &fields[..], st.packed);
990         PointerCast(bcx, val, real_ty.ptr_to())
991     } else {
992         val
993     };
994
995     GEPi(bcx, val, &[0, ix])
996 }
997
998 pub fn fold_variants<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
999                                     r: &Repr<'tcx>,
1000                                     value: ValueRef,
1001                                     mut f: F)
1002                                     -> Block<'blk, 'tcx> where
1003     F: FnMut(Block<'blk, 'tcx>, &Struct<'tcx>, ValueRef) -> Block<'blk, 'tcx>,
1004 {
1005     let fcx = bcx.fcx;
1006     match *r {
1007         Univariant(ref st, _) => {
1008             f(bcx, st, value)
1009         }
1010         General(ity, ref cases, _) => {
1011             let ccx = bcx.ccx();
1012             let unr_cx = fcx.new_temp_block("enum-variant-iter-unr");
1013             Unreachable(unr_cx);
1014
1015             let discr_val = trans_get_discr(bcx, r, value, None);
1016             let llswitch = Switch(bcx, discr_val, unr_cx.llbb, cases.len());
1017             let bcx_next = fcx.new_temp_block("enum-variant-iter-next");
1018
1019             for (discr, case) in cases.iter().enumerate() {
1020                 let mut variant_cx = fcx.new_temp_block(
1021                     &format!("enum-variant-iter-{}", &discr.to_string())
1022                 );
1023                 let rhs_val = C_integral(ll_inttype(ccx, ity), discr as u64, true);
1024                 AddCase(llswitch, rhs_val, variant_cx.llbb);
1025
1026                 let fields = case.fields.iter().map(|&ty|
1027                     type_of::type_of(bcx.ccx(), ty)).collect::<Vec<_>>();
1028                 let real_ty = Type::struct_(ccx, &fields[..], case.packed);
1029                 let variant_value = PointerCast(variant_cx, value, real_ty.ptr_to());
1030
1031                 variant_cx = f(variant_cx, case, variant_value);
1032                 Br(variant_cx, bcx_next.llbb, DebugLoc::None);
1033             }
1034
1035             bcx_next
1036         }
1037         _ => unreachable!()
1038     }
1039 }
1040
1041 /// Access the struct drop flag, if present.
1042 pub fn trans_drop_flag_ptr<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>, val: ValueRef)
1043                                        -> datum::DatumBlock<'blk, 'tcx, datum::Expr>
1044 {
1045     let tcx = bcx.tcx();
1046     let ptr_ty = ty::mk_imm_ptr(bcx.tcx(), tcx.dtor_type());
1047     match *r {
1048         Univariant(ref st, dtor) if dtor_active(dtor) => {
1049             let flag_ptr = GEPi(bcx, val, &[0, st.fields.len() - 1]);
1050             datum::immediate_rvalue_bcx(bcx, flag_ptr, ptr_ty).to_expr_datumblock()
1051         }
1052         General(_, _, dtor) if dtor_active(dtor) => {
1053             let fcx = bcx.fcx;
1054             let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1055             let scratch = unpack_datum!(bcx, datum::lvalue_scratch_datum(
1056                 bcx, tcx.dtor_type(), "drop_flag",
1057                 cleanup::CustomScope(custom_cleanup_scope), (), |_, bcx, _| bcx
1058             ));
1059             bcx = fold_variants(bcx, r, val, |variant_cx, st, value| {
1060                 let ptr = struct_field_ptr(variant_cx, st, value, (st.fields.len() - 1), false);
1061                 datum::Datum::new(ptr, ptr_ty, datum::Rvalue::new(datum::ByRef))
1062                     .store_to(variant_cx, scratch.val)
1063             });
1064             let expr_datum = scratch.to_expr_datum();
1065             fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1066             datum::DatumBlock::new(bcx, expr_datum)
1067         }
1068         _ => bcx.ccx().sess().bug("tried to get drop flag of non-droppable type")
1069     }
1070 }
1071
1072 /// Construct a constant value, suitable for initializing a
1073 /// GlobalVariable, given a case and constant values for its fields.
1074 /// Note that this may have a different LLVM type (and different
1075 /// alignment!) from the representation's `type_of`, so it needs a
1076 /// pointer cast before use.
1077 ///
1078 /// The LLVM type system does not directly support unions, and only
1079 /// pointers can be bitcast, so a constant (and, by extension, the
1080 /// GlobalVariable initialized by it) will have a type that can vary
1081 /// depending on which case of an enum it is.
1082 ///
1083 /// To understand the alignment situation, consider `enum E { V64(u64),
1084 /// V32(u32, u32) }` on Windows.  The type has 8-byte alignment to
1085 /// accommodate the u64, but `V32(x, y)` would have LLVM type `{i32,
1086 /// i32, i32}`, which is 4-byte aligned.
1087 ///
1088 /// Currently the returned value has the same size as the type, but
1089 /// this could be changed in the future to avoid allocating unnecessary
1090 /// space after values of shorter-than-maximum cases.
1091 pub fn trans_const<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, r: &Repr<'tcx>, discr: Disr,
1092                              vals: &[ValueRef]) -> ValueRef {
1093     match *r {
1094         CEnum(ity, min, max) => {
1095             assert_eq!(vals.len(), 0);
1096             assert_discr_in_range(ity, min, max, discr);
1097             C_integral(ll_inttype(ccx, ity), discr as u64, true)
1098         }
1099         General(ity, ref cases, _) => {
1100             let case = &cases[discr as usize];
1101             let (max_sz, _) = union_size_and_align(&cases[..]);
1102             let lldiscr = C_integral(ll_inttype(ccx, ity), discr as u64, true);
1103             let mut f = vec![lldiscr];
1104             f.push_all(vals);
1105             let mut contents = build_const_struct(ccx, case, &f[..]);
1106             contents.push_all(&[padding(ccx, max_sz - case.size)]);
1107             C_struct(ccx, &contents[..], false)
1108         }
1109         Univariant(ref st, _dro) => {
1110             assert!(discr == 0);
1111             let contents = build_const_struct(ccx, st, vals);
1112             C_struct(ccx, &contents[..], st.packed)
1113         }
1114         RawNullablePointer { nndiscr, nnty, .. } => {
1115             if discr == nndiscr {
1116                 assert_eq!(vals.len(), 1);
1117                 vals[0]
1118             } else {
1119                 C_null(type_of::sizing_type_of(ccx, nnty))
1120             }
1121         }
1122         StructWrappedNullablePointer { ref nonnull, nndiscr, .. } => {
1123             if discr == nndiscr {
1124                 C_struct(ccx, &build_const_struct(ccx,
1125                                                  nonnull,
1126                                                  vals),
1127                          false)
1128             } else {
1129                 let vals = nonnull.fields.iter().map(|&ty| {
1130                     // Always use null even if it's not the `discrfield`th
1131                     // field; see #8506.
1132                     C_null(type_of::sizing_type_of(ccx, ty))
1133                 }).collect::<Vec<ValueRef>>();
1134                 C_struct(ccx, &build_const_struct(ccx,
1135                                                  nonnull,
1136                                                  &vals[..]),
1137                          false)
1138             }
1139         }
1140     }
1141 }
1142
1143 /// Compute struct field offsets relative to struct begin.
1144 fn compute_struct_field_offsets<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1145                                           st: &Struct<'tcx>) -> Vec<u64> {
1146     let mut offsets = vec!();
1147
1148     let mut offset = 0;
1149     for &ty in &st.fields {
1150         let llty = type_of::sizing_type_of(ccx, ty);
1151         if !st.packed {
1152             let type_align = type_of::align_of(ccx, ty);
1153             offset = roundup(offset, type_align);
1154         }
1155         offsets.push(offset);
1156         offset += machine::llsize_of_alloc(ccx, llty);
1157     }
1158     assert_eq!(st.fields.len(), offsets.len());
1159     offsets
1160 }
1161
1162 /// Building structs is a little complicated, because we might need to
1163 /// insert padding if a field's value is less aligned than its type.
1164 ///
1165 /// Continuing the example from `trans_const`, a value of type `(u32,
1166 /// E)` should have the `E` at offset 8, but if that field's
1167 /// initializer is 4-byte aligned then simply translating the tuple as
1168 /// a two-element struct will locate it at offset 4, and accesses to it
1169 /// will read the wrong memory.
1170 fn build_const_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1171                                 st: &Struct<'tcx>, vals: &[ValueRef])
1172                                 -> Vec<ValueRef> {
1173     assert_eq!(vals.len(), st.fields.len());
1174
1175     let target_offsets = compute_struct_field_offsets(ccx, st);
1176
1177     // offset of current value
1178     let mut offset = 0;
1179     let mut cfields = Vec::new();
1180     for (&val, &target_offset) in vals.iter().zip(target_offsets.iter()) {
1181         if !st.packed {
1182             let val_align = machine::llalign_of_min(ccx, val_ty(val));
1183             offset = roundup(offset, val_align);
1184         }
1185         if offset != target_offset {
1186             cfields.push(padding(ccx, target_offset - offset));
1187             offset = target_offset;
1188         }
1189         assert!(!is_undef(val));
1190         cfields.push(val);
1191         offset += machine::llsize_of_alloc(ccx, val_ty(val));
1192     }
1193
1194     assert!(st.sized && offset <= st.size);
1195     if offset != st.size {
1196         cfields.push(padding(ccx, st.size - offset));
1197     }
1198
1199     cfields
1200 }
1201
1202 fn padding(ccx: &CrateContext, size: u64) -> ValueRef {
1203     C_undef(Type::array(&Type::i8(ccx), size))
1204 }
1205
1206 // FIXME this utility routine should be somewhere more general
1207 #[inline]
1208 fn roundup(x: u64, a: u32) -> u64 { let a = a as u64; ((x + (a - 1)) / a) * a }
1209
1210 /// Get the discriminant of a constant value.
1211 pub fn const_get_discrim(ccx: &CrateContext, r: &Repr, val: ValueRef) -> Disr {
1212     match *r {
1213         CEnum(ity, _, _) => {
1214             match ity {
1215                 attr::SignedInt(..) => const_to_int(val) as Disr,
1216                 attr::UnsignedInt(..) => const_to_uint(val) as Disr
1217             }
1218         }
1219         General(ity, _, _) => {
1220             match ity {
1221                 attr::SignedInt(..) => const_to_int(const_get_elt(ccx, val, &[0])) as Disr,
1222                 attr::UnsignedInt(..) => const_to_uint(const_get_elt(ccx, val, &[0])) as Disr
1223             }
1224         }
1225         Univariant(..) => 0,
1226         RawNullablePointer { .. } | StructWrappedNullablePointer { .. } => {
1227             ccx.sess().bug("const discrim access of non c-like enum")
1228         }
1229     }
1230 }
1231
1232 /// Extract a field of a constant value, as appropriate for its
1233 /// representation.
1234 ///
1235 /// (Not to be confused with `common::const_get_elt`, which operates on
1236 /// raw LLVM-level structs and arrays.)
1237 pub fn const_get_field(ccx: &CrateContext, r: &Repr, val: ValueRef,
1238                        _discr: Disr, ix: usize) -> ValueRef {
1239     match *r {
1240         CEnum(..) => ccx.sess().bug("element access in C-like enum const"),
1241         Univariant(..) => const_struct_field(ccx, val, ix),
1242         General(..) => const_struct_field(ccx, val, ix + 1),
1243         RawNullablePointer { .. } => {
1244             assert_eq!(ix, 0);
1245             val
1246         },
1247         StructWrappedNullablePointer{ .. } => const_struct_field(ccx, val, ix)
1248     }
1249 }
1250
1251 /// Extract field of struct-like const, skipping our alignment padding.
1252 fn const_struct_field(ccx: &CrateContext, val: ValueRef, ix: usize) -> ValueRef {
1253     // Get the ix-th non-undef element of the struct.
1254     let mut real_ix = 0; // actual position in the struct
1255     let mut ix = ix; // logical index relative to real_ix
1256     let mut field;
1257     loop {
1258         loop {
1259             field = const_get_elt(ccx, val, &[real_ix]);
1260             if !is_undef(field) {
1261                 break;
1262             }
1263             real_ix = real_ix + 1;
1264         }
1265         if ix == 0 {
1266             return field;
1267         }
1268         ix = ix - 1;
1269         real_ix = real_ix + 1;
1270     }
1271 }