]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/adt.rs
fd38ec39bb1bba0d312cb5949fca12765c5184e4
[rust.git] / src / librustc / middle / 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 /*!
12  * # Representation of Algebraic Data Types
13  *
14  * This module determines how to represent enums, structs, and tuples
15  * based on their monomorphized types; it is responsible both for
16  * choosing a representation and translating basic operations on
17  * values of those types.
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  * - Using smaller integer types for discriminants.
33  *
34  * - Store nested enums' discriminants in the same word.  Rather, if
35  *   some variants start with enums, and those enums representations
36  *   have unused alignment padding between discriminant and body, the
37  *   outer enum's discriminant can be stored there and those variants
38  *   can start at offset 0.  Kind of fancy, and might need work to
39  *   make copies of the inner enum type cooperate, but it could help
40  *   with `Option` or `Result` wrapped around another enum.
41  *
42  * - Tagged pointers would be neat, but given that any type can be
43  *   used unboxed and any field can have pointers (including mutable)
44  *   taken to it, implementing them for Rust seems difficult.
45  */
46
47 use std::container::Map;
48 use std::libc::c_ulonglong;
49 use std::option::{Option, Some, None};
50
51 use lib::llvm::{ValueRef, True, IntEQ, IntNE};
52 use middle::trans::_match;
53 use middle::trans::build::*;
54 use middle::trans::common::*;
55 use middle::trans::machine;
56 use middle::trans::type_of;
57 use middle::ty;
58 use syntax::ast;
59 use util::ppaux::ty_to_str;
60
61 use middle::trans::type_::Type;
62
63
64 /// Representations.
65 pub enum Repr {
66     /// C-like enums; basically an int.
67     CEnum(int, int), // discriminant range
68     /**
69      * Single-case variants, and structs/tuples/records.
70      *
71      * Structs with destructors need a dynamic destroyedness flag to
72      * avoid running the destructor too many times; this is included
73      * in the `Struct` if present.
74      */
75     Univariant(Struct, bool),
76     /**
77      * General-case enums: for each case there is a struct, and they
78      * all start with a field for the discriminant.
79      */
80     General(~[Struct]),
81     /**
82      * Two cases distinguished by a nullable pointer: the case with discriminant
83      * `nndiscr` is represented by the struct `nonnull`, where the `ptrfield`th
84      * field is known to be nonnull due to its type; if that field is null, then
85      * it represents the other case, which is inhabited by at most one value
86      * (and all other fields are undefined/unused).
87      *
88      * For example, `std::option::Option` instantiated at a safe pointer type
89      * is represented such that `None` is a null pointer and `Some` is the
90      * identity function.
91      */
92     NullablePointer{ nonnull: Struct, nndiscr: int, ptrfield: uint,
93                      nullfields: ~[ty::t] }
94 }
95
96 /// For structs, and struct-like parts of anything fancier.
97 pub struct Struct {
98     size: u64,
99     align: u64,
100     packed: bool,
101     fields: ~[ty::t]
102 }
103
104 /**
105  * Convenience for `represent_type`.  There should probably be more or
106  * these, for places in trans where the `ty::t` isn't directly
107  * available.
108  */
109 pub fn represent_node(bcx: block, node: ast::node_id) -> @Repr {
110     represent_type(bcx.ccx(), node_id_type(bcx, node))
111 }
112
113 /// Decides how to represent a given type.
114 pub fn represent_type(cx: &mut CrateContext, t: ty::t) -> @Repr {
115     debug!("Representing: %s", ty_to_str(cx.tcx, t));
116     match cx.adt_reprs.find(&t) {
117         Some(repr) => return *repr,
118         None => { }
119     }
120     let repr = @represent_type_uncached(cx, t);
121     debug!("Represented as: %?", repr)
122     cx.adt_reprs.insert(t, repr);
123     return repr;
124 }
125
126 fn represent_type_uncached(cx: &mut CrateContext, t: ty::t) -> Repr {
127     match ty::get(t).sty {
128         ty::ty_tup(ref elems) => {
129             return Univariant(mk_struct(cx, *elems, false), false)
130         }
131         ty::ty_struct(def_id, ref substs) => {
132             let fields = ty::lookup_struct_fields(cx.tcx, def_id);
133             let mut ftys = do fields.map |field| {
134                 ty::lookup_field_type(cx.tcx, def_id, field.id, substs)
135             };
136             let packed = ty::lookup_packed(cx.tcx, def_id);
137             let dtor = ty::ty_dtor(cx.tcx, def_id).has_drop_flag();
138             if dtor { ftys.push(ty::mk_bool()); }
139
140             return Univariant(mk_struct(cx, ftys, packed), dtor)
141         }
142         ty::ty_enum(def_id, ref substs) => {
143             struct Case { discr: int, tys: ~[ty::t] };
144             impl Case {
145                 fn is_zerolen(&self, cx: &mut CrateContext) -> bool {
146                     mk_struct(cx, self.tys, false).size == 0
147                 }
148                 fn find_ptr(&self) -> Option<uint> {
149                     self.tys.iter().position(|&ty| mono_data_classify(ty) == MonoNonNull)
150                 }
151             }
152
153             let cases = do ty::enum_variants(cx.tcx, def_id).map |vi| {
154                 let arg_tys = do vi.args.map |&raw_ty| {
155                     ty::subst(cx.tcx, substs, raw_ty)
156                 };
157                 Case { discr: vi.disr_val, tys: arg_tys }
158             };
159
160             if cases.len() == 0 {
161                 // Uninhabitable; represent as unit
162                 return Univariant(mk_struct(cx, [], false), false);
163             }
164
165             if cases.iter().all(|c| c.tys.len() == 0) {
166                 // All bodies empty -> intlike
167                 let discrs = cases.map(|c| c.discr);
168                 return CEnum(*discrs.iter().min().unwrap(), *discrs.iter().max().unwrap());
169             }
170
171             if cases.len() == 1 {
172                 // Equivalent to a struct/tuple/newtype.
173                 assert_eq!(cases[0].discr, 0);
174                 return Univariant(mk_struct(cx, cases[0].tys, false), false)
175             }
176
177             // Since there's at least one
178             // non-empty body, explicit discriminants should have
179             // been rejected by a checker before this point.
180             if !cases.iter().enumerate().all(|(i,c)| c.discr == (i as int)) {
181                 cx.sess.bug(fmt!("non-C-like enum %s with specified \
182                                   discriminants",
183                                  ty::item_path_str(cx.tcx, def_id)))
184             }
185
186             if cases.len() == 2 {
187                 let mut discr = 0;
188                 while discr < 2 {
189                     if cases[1 - discr].is_zerolen(cx) {
190                         match cases[discr].find_ptr() {
191                             Some(ptrfield) => {
192                                 return NullablePointer {
193                                     nndiscr: discr,
194                                     nonnull: mk_struct(cx,
195                                                        cases[discr].tys,
196                                                        false),
197                                     ptrfield: ptrfield,
198                                     nullfields: cases[1 - discr].tys.clone()
199                                 }
200                             }
201                             None => { }
202                         }
203                     }
204                     discr += 1;
205                 }
206             }
207
208             // The general case.
209             let discr = ~[ty::mk_int()];
210             return General(cases.map(|c| mk_struct(cx, discr + c.tys, false)))
211         }
212         _ => cx.sess.bug("adt::represent_type called on non-ADT type")
213     }
214 }
215
216 fn mk_struct(cx: &mut CrateContext, tys: &[ty::t], packed: bool) -> Struct {
217     let lltys = tys.map(|&ty| type_of::sizing_type_of(cx, ty));
218     let llty_rec = Type::struct_(lltys, packed);
219     Struct {
220         size: machine::llsize_of_alloc(cx, llty_rec) /*bad*/as u64,
221         align: machine::llalign_of_min(cx, llty_rec) /*bad*/as u64,
222         packed: packed,
223         fields: tys.to_owned(),
224     }
225 }
226
227 /**
228  * Returns the fields of a struct for the given representation.
229  * All nominal types are LLVM structs, in order to be able to use
230  * forward-declared opaque types to prevent circularity in `type_of`.
231  */
232 pub fn fields_of(cx: &mut CrateContext, r: &Repr) -> ~[Type] {
233     generic_fields_of(cx, r, false)
234 }
235 /// Like `fields_of`, but for `type_of::sizing_type_of` (q.v.).
236 pub fn sizing_fields_of(cx: &mut CrateContext, r: &Repr) -> ~[Type] {
237     generic_fields_of(cx, r, true)
238 }
239 fn generic_fields_of(cx: &mut CrateContext, r: &Repr, sizing: bool) -> ~[Type] {
240     match *r {
241         CEnum(*) => ~[Type::enum_discrim(cx)],
242         Univariant(ref st, _dtor) => struct_llfields(cx, st, sizing),
243         NullablePointer{ nonnull: ref st, _ } => struct_llfields(cx, st, sizing),
244         General(ref sts) => {
245             // To get "the" type of a general enum, we pick the case
246             // with the largest alignment (so it will always align
247             // correctly in containing structures) and pad it out.
248             assert!(sts.len() >= 1);
249             let mut most_aligned = None;
250             let mut largest_align = 0;
251             let mut largest_size = 0;
252             for sts.iter().advance |st| {
253                 if largest_size < st.size {
254                     largest_size = st.size;
255                 }
256                 if largest_align < st.align {
257                     // Clang breaks ties by size; it is unclear if
258                     // that accomplishes anything important.
259                     largest_align = st.align;
260                     most_aligned = Some(st);
261                 }
262             }
263             let most_aligned = most_aligned.get();
264             let padding = largest_size - most_aligned.size;
265
266             struct_llfields(cx, most_aligned, sizing)
267                 + &[Type::array(&Type::i8(), padding)]
268         }
269     }
270 }
271
272 fn struct_llfields(cx: &mut CrateContext, st: &Struct, sizing: bool) -> ~[Type] {
273     if sizing {
274         st.fields.map(|&ty| type_of::sizing_type_of(cx, ty))
275     } else {
276         st.fields.map(|&ty| type_of::type_of(cx, ty))
277     }
278 }
279
280 /**
281  * Obtain a representation of the discriminant sufficient to translate
282  * destructuring; this may or may not involve the actual discriminant.
283  *
284  * This should ideally be less tightly tied to `_match`.
285  */
286 pub fn trans_switch(bcx: block, r: &Repr, scrutinee: ValueRef)
287     -> (_match::branch_kind, Option<ValueRef>) {
288     match *r {
289         CEnum(*) | General(*) => {
290             (_match::switch, Some(trans_get_discr(bcx, r, scrutinee)))
291         }
292         NullablePointer{ nonnull: ref nonnull, nndiscr, ptrfield, _ } => {
293             (_match::switch, Some(nullable_bitdiscr(bcx, nonnull, nndiscr, ptrfield, scrutinee)))
294         }
295         Univariant(*) => {
296             (_match::single, None)
297         }
298     }
299 }
300
301
302
303 /// Obtain the actual discriminant of a value.
304 pub fn trans_get_discr(bcx: block, r: &Repr, scrutinee: ValueRef)
305     -> ValueRef {
306     match *r {
307         CEnum(min, max) => load_discr(bcx, scrutinee, min, max),
308         Univariant(*) => C_int(bcx.ccx(), 0),
309         General(ref cases) => load_discr(bcx, scrutinee, 0,
310                                          (cases.len() - 1) as int),
311         NullablePointer{ nonnull: ref nonnull, nndiscr, ptrfield, _ } => {
312             ZExt(bcx, nullable_bitdiscr(bcx, nonnull, nndiscr, ptrfield, scrutinee),
313                  Type::enum_discrim(bcx.ccx()))
314         }
315     }
316 }
317
318 fn nullable_bitdiscr(bcx: block, nonnull: &Struct, nndiscr: int, ptrfield: uint,
319                      scrutinee: ValueRef) -> ValueRef {
320     let cmp = if nndiscr == 0 { IntEQ } else { IntNE };
321     let llptr = Load(bcx, GEPi(bcx, scrutinee, [0, ptrfield]));
322     let llptrty = type_of::type_of(bcx.ccx(), nonnull.fields[ptrfield]);
323     ICmp(bcx, cmp, llptr, C_null(llptrty))
324 }
325
326 /// Helper for cases where the discriminant is simply loaded.
327 fn load_discr(bcx: block, scrutinee: ValueRef, min: int, max: int)
328     -> ValueRef {
329     let ptr = GEPi(bcx, scrutinee, [0, 0]);
330     if max + 1 == min {
331         // i.e., if the range is everything.  The lo==hi case would be
332         // rejected by the LLVM verifier (it would mean either an
333         // empty set, which is impossible, or the entire range of the
334         // type, which is pointless).
335         Load(bcx, ptr)
336     } else {
337         // llvm::ConstantRange can deal with ranges that wrap around,
338         // so an overflow on (max + 1) is fine.
339         LoadRangeAssert(bcx, ptr, min as c_ulonglong,
340                         (max + 1) as c_ulonglong,
341                         /* signed: */ True)
342     }
343 }
344
345 /**
346  * Yield information about how to dispatch a case of the
347  * discriminant-like value returned by `trans_switch`.
348  *
349  * This should ideally be less tightly tied to `_match`.
350  */
351 pub fn trans_case(bcx: block, r: &Repr, discr: int) -> _match::opt_result {
352     match *r {
353         CEnum(*) => {
354             _match::single_result(rslt(bcx, C_int(bcx.ccx(), discr)))
355         }
356         Univariant(*) => {
357             bcx.ccx().sess.bug("no cases for univariants or structs")
358         }
359         General(*) => {
360             _match::single_result(rslt(bcx, C_int(bcx.ccx(), discr)))
361         }
362         NullablePointer{ _ } => {
363             assert!(discr == 0 || discr == 1);
364             _match::single_result(rslt(bcx, C_i1(discr != 0)))
365         }
366     }
367 }
368
369 /**
370  * Begin initializing a new value of the given case of the given
371  * representation.  The fields, if any, should then be initialized via
372  * `trans_field_ptr`.
373  */
374 pub fn trans_start_init(bcx: block, r: &Repr, val: ValueRef, discr: int) {
375     match *r {
376         CEnum(min, max) => {
377             assert!(min <= discr && discr <= max);
378             Store(bcx, C_int(bcx.ccx(), discr), GEPi(bcx, val, [0, 0]))
379         }
380         Univariant(ref st, true) => {
381             assert_eq!(discr, 0);
382             Store(bcx, C_bool(true),
383                   GEPi(bcx, val, [0, st.fields.len() - 1]))
384         }
385         Univariant(*) => {
386             assert_eq!(discr, 0);
387         }
388         General(*) => {
389             Store(bcx, C_int(bcx.ccx(), discr), GEPi(bcx, val, [0, 0]))
390         }
391         NullablePointer{ nonnull: ref nonnull, nndiscr, ptrfield, _ } => {
392             if discr != nndiscr {
393                 let llptrptr = GEPi(bcx, val, [0, ptrfield]);
394                 let llptrty = type_of::type_of(bcx.ccx(), nonnull.fields[ptrfield]);
395                 Store(bcx, C_null(llptrty), llptrptr)
396             }
397         }
398     }
399 }
400
401 /**
402  * The number of fields in a given case; for use when obtaining this
403  * information from the type or definition is less convenient.
404  */
405 pub fn num_args(r: &Repr, discr: int) -> uint {
406     match *r {
407         CEnum(*) => 0,
408         Univariant(ref st, dtor) => {
409             assert_eq!(discr, 0);
410             st.fields.len() - (if dtor { 1 } else { 0 })
411         }
412         General(ref cases) => cases[discr as uint].fields.len() - 1,
413         NullablePointer{ nonnull: ref nonnull, nndiscr, nullfields: ref nullfields, _ } => {
414             if discr == nndiscr { nonnull.fields.len() } else { nullfields.len() }
415         }
416     }
417 }
418
419 /// Access a field, at a point when the value's case is known.
420 pub fn trans_field_ptr(bcx: block, r: &Repr, val: ValueRef, discr: int,
421                        ix: uint) -> ValueRef {
422     // Note: if this ever needs to generate conditionals (e.g., if we
423     // decide to do some kind of cdr-coding-like non-unique repr
424     // someday), it will need to return a possibly-new bcx as well.
425     match *r {
426         CEnum(*) => {
427             bcx.ccx().sess.bug("element access in C-like enum")
428         }
429         Univariant(ref st, _dtor) => {
430             assert_eq!(discr, 0);
431             struct_field_ptr(bcx, st, val, ix, false)
432         }
433         General(ref cases) => {
434             struct_field_ptr(bcx, &cases[discr as uint], val, ix + 1, true)
435         }
436         NullablePointer{ nonnull: ref nonnull, nullfields: ref nullfields, nndiscr, _ } => {
437             if (discr == nndiscr) {
438                 struct_field_ptr(bcx, nonnull, val, ix, false)
439             } else {
440                 // The unit-like case might have a nonzero number of unit-like fields.
441                 // (e.g., Result or Either with () as one side.)
442                 let ty = type_of::type_of(bcx.ccx(), nullfields[ix]);
443                 assert_eq!(machine::llsize_of_alloc(bcx.ccx(), ty), 0);
444                 // The contents of memory at this pointer can't matter, but use
445                 // the value that's "reasonable" in case of pointer comparison.
446                 PointerCast(bcx, val, ty.ptr_to())
447             }
448         }
449     }
450 }
451
452 fn struct_field_ptr(bcx: block, st: &Struct, val: ValueRef, ix: uint,
453               needs_cast: bool) -> ValueRef {
454     let ccx = bcx.ccx();
455
456     let val = if needs_cast {
457         let fields = do st.fields.map |&ty| {
458             type_of::type_of(ccx, ty)
459         };
460         let real_ty = Type::struct_(fields, st.packed);
461         PointerCast(bcx, val, real_ty.ptr_to())
462     } else {
463         val
464     };
465
466     GEPi(bcx, val, [0, ix])
467 }
468
469 /// Access the struct drop flag, if present.
470 pub fn trans_drop_flag_ptr(bcx: block, r: &Repr, val: ValueRef) -> ValueRef {
471     match *r {
472         Univariant(ref st, true) => GEPi(bcx, val, [0, st.fields.len() - 1]),
473         _ => bcx.ccx().sess.bug("tried to get drop flag of non-droppable type")
474     }
475 }
476
477 /**
478  * Construct a constant value, suitable for initializing a
479  * GlobalVariable, given a case and constant values for its fields.
480  * Note that this may have a different LLVM type (and different
481  * alignment!) from the representation's `type_of`, so it needs a
482  * pointer cast before use.
483  *
484  * The LLVM type system does not directly support unions, and only
485  * pointers can be bitcast, so a constant (and, by extension, the
486  * GlobalVariable initialized by it) will have a type that can vary
487  * depending on which case of an enum it is.
488  *
489  * To understand the alignment situation, consider `enum E { V64(u64),
490  * V32(u32, u32) }` on win32.  The type has 8-byte alignment to
491  * accommodate the u64, but `V32(x, y)` would have LLVM type `{i32,
492  * i32, i32}`, which is 4-byte aligned.
493  *
494  * Currently the returned value has the same size as the type, but
495  * this could be changed in the future to avoid allocating unnecessary
496  * space after values of shorter-than-maximum cases.
497  */
498 pub fn trans_const(ccx: &mut CrateContext, r: &Repr, discr: int,
499                    vals: &[ValueRef]) -> ValueRef {
500     match *r {
501         CEnum(min, max) => {
502             assert_eq!(vals.len(), 0);
503             assert!(min <= discr && discr <= max);
504             C_int(ccx, discr)
505         }
506         Univariant(ref st, _dro) => {
507             assert_eq!(discr, 0);
508             C_struct(build_const_struct(ccx, st, vals))
509         }
510         General(ref cases) => {
511             let case = &cases[discr as uint];
512             let max_sz = cases.iter().transform(|x| x.size).max().unwrap();
513             let discr_ty = C_int(ccx, discr);
514             let contents = build_const_struct(ccx, case,
515                                               ~[discr_ty] + vals);
516             C_struct(contents + &[padding(max_sz - case.size)])
517         }
518         NullablePointer{ nonnull: ref nonnull, nndiscr, ptrfield, _ } => {
519             if discr == nndiscr {
520                 C_struct(build_const_struct(ccx, nonnull, vals))
521             } else {
522                 assert_eq!(vals.len(), 0);
523                 let vals = do nonnull.fields.iter().enumerate().transform |(i, &ty)| {
524                     let llty = type_of::sizing_type_of(ccx, ty);
525                     if i == ptrfield { C_null(llty) } else { C_undef(llty) }
526                 }.collect::<~[ValueRef]>();
527                 C_struct(build_const_struct(ccx, nonnull, vals))
528             }
529         }
530     }
531 }
532
533 /**
534  * Building structs is a little complicated, because we might need to
535  * insert padding if a field's value is less aligned than its type.
536  *
537  * Continuing the example from `trans_const`, a value of type `(u32,
538  * E)` should have the `E` at offset 8, but if that field's
539  * initializer is 4-byte aligned then simply translating the tuple as
540  * a two-element struct will locate it at offset 4, and accesses to it
541  * will read the wrong memory.
542  */
543 fn build_const_struct(ccx: &mut CrateContext, st: &Struct, vals: &[ValueRef])
544     -> ~[ValueRef] {
545     assert_eq!(vals.len(), st.fields.len());
546
547     let mut offset = 0;
548     let mut cfields = ~[];
549     for st.fields.iter().enumerate().advance |(i, &ty)| {
550         let llty = type_of::sizing_type_of(ccx, ty);
551         let type_align = machine::llalign_of_min(ccx, llty)
552             /*bad*/as u64;
553         let val_align = machine::llalign_of_min(ccx, val_ty(vals[i]))
554             /*bad*/as u64;
555         let target_offset = roundup(offset, type_align);
556         offset = roundup(offset, val_align);
557         if (offset != target_offset) {
558             cfields.push(padding(target_offset - offset));
559             offset = target_offset;
560         }
561         let val = if is_undef(vals[i]) {
562             let wrapped = C_struct([vals[i]]);
563             assert!(!is_undef(wrapped));
564             wrapped
565         } else {
566             vals[i]
567         };
568         cfields.push(val);
569         offset += machine::llsize_of_alloc(ccx, llty) as u64
570     }
571
572     return cfields;
573 }
574
575 fn padding(size: u64) -> ValueRef {
576     C_undef(Type::array(&Type::i8(), size))
577 }
578
579 // XXX this utility routine should be somewhere more general
580 #[inline]
581 fn roundup(x: u64, a: u64) -> u64 { ((x + (a - 1)) / a) * a }
582
583 /// Get the discriminant of a constant value.  (Not currently used.)
584 pub fn const_get_discrim(ccx: &mut CrateContext, r: &Repr, val: ValueRef)
585     -> int {
586     match *r {
587         CEnum(*) => const_to_int(val) as int,
588         Univariant(*) => 0,
589         General(*) => const_to_int(const_get_elt(ccx, val, [0])) as int,
590         NullablePointer{ nndiscr, ptrfield, _ } => {
591             if is_null(const_struct_field(ccx, val, ptrfield)) { 1 - nndiscr } else { nndiscr }
592         }
593     }
594 }
595
596 /**
597  * Extract a field of a constant value, as appropriate for its
598  * representation.
599  *
600  * (Not to be confused with `common::const_get_elt`, which operates on
601  * raw LLVM-level structs and arrays.)
602  */
603 pub fn const_get_field(ccx: &mut CrateContext, r: &Repr, val: ValueRef,
604                        _discr: int, ix: uint) -> ValueRef {
605     match *r {
606         CEnum(*) => ccx.sess.bug("element access in C-like enum const"),
607         Univariant(*) => const_struct_field(ccx, val, ix),
608         General(*) => const_struct_field(ccx, val, ix + 1),
609         NullablePointer{ _ } => const_struct_field(ccx, val, ix)
610     }
611 }
612
613 /// Extract field of struct-like const, skipping our alignment padding.
614 fn const_struct_field(ccx: &mut CrateContext, val: ValueRef, ix: uint)
615     -> ValueRef {
616     // Get the ix-th non-undef element of the struct.
617     let mut real_ix = 0; // actual position in the struct
618     let mut ix = ix; // logical index relative to real_ix
619     let mut field;
620     loop {
621         loop {
622             field = const_get_elt(ccx, val, [real_ix]);
623             if !is_undef(field) {
624                 break;
625             }
626             real_ix = real_ix + 1;
627         }
628         if ix == 0 {
629             return field;
630         }
631         ix = ix - 1;
632         real_ix = real_ix + 1;
633     }
634 }
635
636 /// Is it safe to bitcast a value to the one field of its one variant?
637 pub fn is_newtypeish(r: &Repr) -> bool {
638     match *r {
639         Univariant(ref st, false) => st.fields.len() == 1,
640         _ => false
641     }
642 }