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.
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.
11 //! # Representation of Algebraic Data Types
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.)
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.
23 //! Having everything in one place will enable improvements to data
24 //! structure representation; possibilities include:
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
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.
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.
44 pub use self::Repr::*;
48 use llvm::{ValueRef, True, IntEQ, IntNE};
49 use back::abi::FAT_PTR_ADDR;
51 use middle::ty::{self, Ty};
55 use syntax::attr::IntType;
59 use trans::cleanup::CleanupMethods;
62 use trans::debuginfo::DebugLoc;
64 use trans::monomorphize;
65 use trans::type_::Type;
68 type Hint = attr::ReprAttr;
70 // Representation of the context surrounding an unsized type. I want
71 // to be able to track the drop flags that are injected by trans.
72 #[derive(Clone, Copy, PartialEq, Debug)]
73 pub struct TypeContext {
75 needs_drop_flag: bool,
79 pub fn prefix(&self) -> Type { self.prefix }
80 pub fn needs_drop_flag(&self) -> bool { self.needs_drop_flag }
82 fn direct(t: Type) -> TypeContext {
83 TypeContext { prefix: t, needs_drop_flag: false }
85 fn may_need_drop_flag(t: Type, needs_drop_flag: bool) -> TypeContext {
86 TypeContext { prefix: t, needs_drop_flag: needs_drop_flag }
88 pub fn to_string(self) -> String {
89 let TypeContext { prefix, needs_drop_flag } = self;
90 format!("TypeContext {{ prefix: {}, needs_drop_flag: {} }}",
91 prefix.to_string(), needs_drop_flag)
96 #[derive(Eq, PartialEq, Debug)]
98 /// C-like enums; basically an int.
99 CEnum(IntType, Disr, Disr), // discriminant range (signedness based on the IntType)
100 /// Single-case variants, and structs/tuples/records.
102 /// Structs with destructors need a dynamic destroyedness flag to
103 /// avoid running the destructor too many times; this is included
104 /// in the `Struct` if present.
105 /// (The flag if nonzero, represents the initialization value to use;
106 /// if zero, then use no flag at all.)
107 Univariant(Struct<'tcx>, u8),
108 /// General-case enums: for each case there is a struct, and they
109 /// all start with a field for the discriminant.
111 /// Types with destructors need a dynamic destroyedness flag to
112 /// avoid running the destructor too many times; the last argument
113 /// indicates whether such a flag is present.
114 /// (The flag, if nonzero, represents the initialization value to use;
115 /// if zero, then use no flag at all.)
116 General(IntType, Vec<Struct<'tcx>>, u8),
117 /// Two cases distinguished by a nullable pointer: the case with discriminant
118 /// `nndiscr` must have single field which is known to be nonnull due to its type.
119 /// The other case is known to be zero sized. Hence we represent the enum
120 /// as simply a nullable pointer: if not null it indicates the `nndiscr` variant,
121 /// otherwise it indicates the other case.
125 nullfields: Vec<Ty<'tcx>>
127 /// Two cases distinguished by a nullable pointer: the case with discriminant
128 /// `nndiscr` is represented by the struct `nonnull`, where the `discrfield`th
129 /// field is known to be nonnull due to its type; if that field is null, then
130 /// it represents the other case, which is inhabited by at most one value
131 /// (and all other fields are undefined/unused).
133 /// For example, `std::option::Option` instantiated at a safe pointer type
134 /// is represented such that `None` is a null pointer and `Some` is the
135 /// identity function.
136 StructWrappedNullablePointer {
137 nonnull: Struct<'tcx>,
139 discrfield: DiscrField,
140 nullfields: Vec<Ty<'tcx>>,
144 /// For structs, and struct-like parts of anything fancier.
145 #[derive(Eq, PartialEq, Debug)]
146 pub struct Struct<'tcx> {
147 // If the struct is DST, then the size and alignment do not take into
148 // account the unsized fields of the struct.
153 pub fields: Vec<Ty<'tcx>>,
156 /// Convenience for `represent_type`. There should probably be more or
157 /// these, for places in trans where the `Ty` isn't directly
159 pub fn represent_node<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
160 node: ast::NodeId) -> Rc<Repr<'tcx>> {
161 represent_type(bcx.ccx(), node_id_type(bcx, node))
164 /// Decides how to represent a given type.
165 pub fn represent_type<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
168 debug!("Representing: {}", t);
169 match cx.adt_reprs().borrow().get(&t) {
170 Some(repr) => return repr.clone(),
174 let repr = Rc::new(represent_type_uncached(cx, t));
175 debug!("Represented as: {:?}", repr);
176 cx.adt_reprs().borrow_mut().insert(t, repr.clone());
180 const fn repeat_u8_as_u32(val: u8) -> u32 {
181 (val as u32) << 24 | (val as u32) << 16 | (val as u32) << 8 | val as u32
184 const fn repeat_u8_as_u64(val: u8) -> u64 {
185 (repeat_u8_as_u32(val) as u64) << 32 | repeat_u8_as_u32(val) as u64
188 /// `DTOR_NEEDED_HINT` is a stack-local hint that just means
189 /// "we do not know whether the destructor has run or not; check the
190 /// drop-flag embedded in the value itself."
191 pub const DTOR_NEEDED_HINT: u8 = 0x3d;
193 /// `DTOR_MOVED_HINT` is a stack-local hint that means "this value has
194 /// definitely been moved; you do not need to run its destructor."
196 /// (However, for now, such values may still end up being explicitly
197 /// zeroed by the generated code; this is the distinction between
198 /// `datum::DropFlagInfo::ZeroAndMaintain` versus
199 /// `datum::DropFlagInfo::DontZeroJustUse`.)
200 pub const DTOR_MOVED_HINT: u8 = 0x2d;
202 pub const DTOR_NEEDED: u8 = 0xd4;
203 pub const DTOR_NEEDED_U32: u32 = repeat_u8_as_u32(DTOR_NEEDED);
204 pub const DTOR_NEEDED_U64: u64 = repeat_u8_as_u64(DTOR_NEEDED);
206 pub fn dtor_needed_usize(ccx: &CrateContext) -> usize {
207 match &ccx.tcx().sess.target.target.target_pointer_width[..] {
208 "32" => DTOR_NEEDED_U32 as usize,
209 "64" => DTOR_NEEDED_U64 as usize,
210 tws => panic!("Unsupported target word size for int: {}", tws),
214 pub const DTOR_DONE: u8 = 0x1d;
215 pub const DTOR_DONE_U32: u32 = repeat_u8_as_u32(DTOR_DONE);
216 pub const DTOR_DONE_U64: u64 = repeat_u8_as_u64(DTOR_DONE);
218 pub fn dtor_done_usize(ccx: &CrateContext) -> usize {
219 match &ccx.tcx().sess.target.target.target_pointer_width[..] {
220 "32" => DTOR_DONE_U32 as usize,
221 "64" => DTOR_DONE_U64 as usize,
222 tws => panic!("Unsupported target word size for int: {}", tws),
226 fn dtor_to_init_u8(dtor: bool) -> u8 {
227 if dtor { DTOR_NEEDED } else { 0 }
230 pub trait GetDtorType<'tcx> { fn dtor_type(&self) -> Ty<'tcx>; }
231 impl<'tcx> GetDtorType<'tcx> for ty::ctxt<'tcx> {
232 fn dtor_type(&self) -> Ty<'tcx> { self.types.u8 }
235 fn dtor_active(flag: u8) -> bool {
239 fn represent_type_uncached<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
240 t: Ty<'tcx>) -> Repr<'tcx> {
242 ty::TyTuple(ref elems) => {
243 Univariant(mk_struct(cx, &elems[..], false, t), 0)
245 ty::TyStruct(def, substs) => {
246 let mut ftys = def.struct_variant().fields.iter().map(|field| {
247 monomorphize::field_ty(cx.tcx(), substs, field)
248 }).collect::<Vec<_>>();
249 let packed = cx.tcx().lookup_packed(def.did);
250 let dtor = def.dtor_kind().has_drop_flag();
252 ftys.push(cx.tcx().dtor_type());
255 Univariant(mk_struct(cx, &ftys[..], packed, t), dtor_to_init_u8(dtor))
257 ty::TyClosure(_, ref substs) => {
258 Univariant(mk_struct(cx, &substs.upvar_tys, false, t), 0)
260 ty::TyEnum(def, substs) => {
261 let cases = get_cases(cx.tcx(), def, substs);
262 let hint = *cx.tcx().lookup_repr_hints(def.did).get(0)
263 .unwrap_or(&attr::ReprAny);
265 let dtor = def.dtor_kind().has_drop_flag();
267 if cases.is_empty() {
268 // Uninhabitable; represent as unit
269 // (Typechecking will reject discriminant-sizing attrs.)
270 assert_eq!(hint, attr::ReprAny);
271 let ftys = if dtor { vec!(cx.tcx().dtor_type()) } else { vec!() };
272 return Univariant(mk_struct(cx, &ftys[..], false, t),
273 dtor_to_init_u8(dtor));
276 if !dtor && cases.iter().all(|c| c.tys.is_empty()) {
277 // All bodies empty -> intlike
278 let discrs: Vec<u64> = cases.iter().map(|c| c.discr).collect();
279 let bounds = IntBounds {
280 ulo: *discrs.iter().min().unwrap(),
281 uhi: *discrs.iter().max().unwrap(),
282 slo: discrs.iter().map(|n| *n as i64).min().unwrap(),
283 shi: discrs.iter().map(|n| *n as i64).max().unwrap()
285 return mk_cenum(cx, hint, &bounds);
288 // Since there's at least one
289 // non-empty body, explicit discriminants should have
290 // been rejected by a checker before this point.
291 if !cases.iter().enumerate().all(|(i,c)| c.discr == (i as Disr)) {
292 cx.sess().bug(&format!("non-C-like enum {} with specified \
294 cx.tcx().item_path_str(def.did)));
297 if cases.len() == 1 {
298 // Equivalent to a struct/tuple/newtype.
299 // (Typechecking will reject discriminant-sizing attrs.)
300 assert_eq!(hint, attr::ReprAny);
301 let mut ftys = cases[0].tys.clone();
302 if dtor { ftys.push(cx.tcx().dtor_type()); }
303 return Univariant(mk_struct(cx, &ftys[..], false, t),
304 dtor_to_init_u8(dtor));
307 if !dtor && cases.len() == 2 && hint == attr::ReprAny {
308 // Nullable pointer optimization
311 if cases[1 - discr].is_zerolen(cx, t) {
312 let st = mk_struct(cx, &cases[discr].tys,
314 match cases[discr].find_ptr(cx) {
315 Some(ref df) if df.len() == 1 && st.fields.len() == 1 => {
316 return RawNullablePointer {
317 nndiscr: discr as Disr,
319 nullfields: cases[1 - discr].tys.clone()
322 Some(mut discrfield) => {
324 discrfield.reverse();
325 return StructWrappedNullablePointer {
326 nndiscr: discr as Disr,
328 discrfield: discrfield,
329 nullfields: cases[1 - discr].tys.clone()
340 assert!((cases.len() - 1) as i64 >= 0);
341 let bounds = IntBounds { ulo: 0, uhi: (cases.len() - 1) as u64,
342 slo: 0, shi: (cases.len() - 1) as i64 };
343 let min_ity = range_to_inttype(cx, hint, &bounds);
345 // Create the set of structs that represent each variant
346 // Use the minimum integer type we figured out above
347 let fields : Vec<_> = cases.iter().map(|c| {
348 let mut ftys = vec!(ty_of_inttype(cx.tcx(), min_ity));
349 ftys.push_all(&c.tys);
350 if dtor { ftys.push(cx.tcx().dtor_type()); }
351 mk_struct(cx, &ftys, false, t)
355 // Check to see if we should use a different type for the
356 // discriminant. If the overall alignment of the type is
357 // the same as the first field in each variant, we can safely use
358 // an alignment-sized type.
359 // We increase the size of the discriminant to avoid LLVM copying
360 // padding when it doesn't need to. This normally causes unaligned
361 // load/stores and excessive memcpy/memset operations. By using a
362 // bigger integer size, LLVM can be sure about it's contents and
363 // won't be so conservative.
364 // This check is needed to avoid increasing the size of types when
365 // the alignment of the first field is smaller than the overall
366 // alignment of the type.
367 let (_, align) = union_size_and_align(&fields);
368 let mut use_align = true;
370 // Get the first non-zero-sized field
371 let field = st.fields.iter().skip(1).filter(|ty| {
372 let t = type_of::sizing_type_of(cx, **ty);
373 machine::llsize_of_real(cx, t) != 0 ||
374 // This case is only relevant for zero-sized types with large alignment
375 machine::llalign_of_min(cx, t) != 1
378 if let Some(field) = field {
379 let field_align = type_of::align_of(cx, *field);
380 if field_align != align {
386 let ity = if use_align {
387 // Use the overall alignment
389 1 => attr::UnsignedInt(ast::TyU8),
390 2 => attr::UnsignedInt(ast::TyU16),
391 4 => attr::UnsignedInt(ast::TyU32),
392 8 if machine::llalign_of_min(cx, Type::i64(cx)) == 8 =>
393 attr::UnsignedInt(ast::TyU64),
394 _ => min_ity // use min_ity as a fallback
400 let fields : Vec<_> = cases.iter().map(|c| {
401 let mut ftys = vec!(ty_of_inttype(cx.tcx(), ity));
402 ftys.push_all(&c.tys);
403 if dtor { ftys.push(cx.tcx().dtor_type()); }
404 mk_struct(cx, &ftys[..], false, t)
407 ensure_enum_fits_in_address_space(cx, &fields[..], t);
409 General(ity, fields, dtor_to_init_u8(dtor))
411 _ => cx.sess().bug(&format!("adt::represent_type called on non-ADT type: {}", t))
415 // this should probably all be in ty
421 /// This represents the (GEP) indices to follow to get to the discriminant field
422 pub type DiscrField = Vec<usize>;
424 fn find_discr_field_candidate<'tcx>(tcx: &ty::ctxt<'tcx>,
426 mut path: DiscrField) -> Option<DiscrField> {
428 // Fat &T/&mut T/Box<T> i.e. T is [T], str, or Trait
429 ty::TyRef(_, ty::TypeAndMut { ty, .. }) | ty::TyBox(ty) if !type_is_sized(tcx, ty) => {
430 path.push(FAT_PTR_ADDR);
434 // Regular thin pointer: &T/&mut T/Box<T>
435 ty::TyRef(..) | ty::TyBox(..) => Some(path),
437 // Functions are just pointers
438 ty::TyBareFn(..) => Some(path),
440 // Is this the NonZero lang item wrapping a pointer or integer type?
441 ty::TyStruct(def, substs) if Some(def.did) == tcx.lang_items.non_zero() => {
442 let nonzero_fields = &def.struct_variant().fields;
443 assert_eq!(nonzero_fields.len(), 1);
444 let field_ty = monomorphize::field_ty(tcx, substs, &nonzero_fields[0]);
446 ty::TyRawPtr(ty::TypeAndMut { ty, .. }) if !type_is_sized(tcx, ty) => {
447 path.push_all(&[0, FAT_PTR_ADDR]);
450 ty::TyRawPtr(..) | ty::TyInt(..) | ty::TyUint(..) => {
458 // Perhaps one of the fields of this struct is non-zero
459 // let's recurse and find out
460 ty::TyStruct(def, substs) => {
461 for (j, field) in def.struct_variant().fields.iter().enumerate() {
462 let field_ty = monomorphize::field_ty(tcx, substs, field);
463 if let Some(mut fpath) = find_discr_field_candidate(tcx, field_ty, path.clone()) {
471 // Perhaps one of the upvars of this struct is non-zero
472 // Let's recurse and find out!
473 ty::TyClosure(_, ref substs) => {
474 for (j, &ty) in substs.upvar_tys.iter().enumerate() {
475 if let Some(mut fpath) = find_discr_field_candidate(tcx, ty, path.clone()) {
483 // Can we use one of the fields in this tuple?
484 ty::TyTuple(ref tys) => {
485 for (j, &ty) in tys.iter().enumerate() {
486 if let Some(mut fpath) = find_discr_field_candidate(tcx, ty, path.clone()) {
494 // Is this a fixed-size array of something non-zero
495 // with at least one element?
496 ty::TyArray(ety, d) if d > 0 => {
497 if let Some(mut vpath) = find_discr_field_candidate(tcx, ety, path) {
505 // Anything else is not a pointer
510 impl<'tcx> Case<'tcx> {
511 fn is_zerolen<'a>(&self, cx: &CrateContext<'a, 'tcx>, scapegoat: Ty<'tcx>) -> bool {
512 mk_struct(cx, &self.tys, false, scapegoat).size == 0
515 fn find_ptr<'a>(&self, cx: &CrateContext<'a, 'tcx>) -> Option<DiscrField> {
516 for (i, &ty) in self.tys.iter().enumerate() {
517 if let Some(mut path) = find_discr_field_candidate(cx.tcx(), ty, vec![]) {
526 fn get_cases<'tcx>(tcx: &ty::ctxt<'tcx>,
527 adt: ty::AdtDef<'tcx>,
528 substs: &subst::Substs<'tcx>)
530 adt.variants.iter().map(|vi| {
531 let field_tys = vi.fields.iter().map(|field| {
532 monomorphize::field_ty(tcx, substs, field)
534 Case { discr: vi.disr_val, tys: field_tys }
538 fn mk_struct<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
539 tys: &[Ty<'tcx>], packed: bool,
542 let sized = tys.iter().all(|&ty| type_is_sized(cx.tcx(), ty));
543 let lltys : Vec<Type> = if sized {
544 tys.iter().map(|&ty| type_of::sizing_type_of(cx, ty)).collect()
546 tys.iter().filter(|&ty| type_is_sized(cx.tcx(), *ty))
547 .map(|&ty| type_of::sizing_type_of(cx, ty)).collect()
550 ensure_struct_fits_in_address_space(cx, &lltys[..], packed, scapegoat);
552 let llty_rec = Type::struct_(cx, &lltys[..], packed);
554 size: machine::llsize_of_alloc(cx, llty_rec),
555 align: machine::llalign_of_min(cx, llty_rec),
558 fields: tys.to_vec(),
570 fn mk_cenum<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
571 hint: Hint, bounds: &IntBounds)
573 let it = range_to_inttype(cx, hint, bounds);
575 attr::SignedInt(_) => CEnum(it, bounds.slo as Disr, bounds.shi as Disr),
576 attr::UnsignedInt(_) => CEnum(it, bounds.ulo, bounds.uhi)
580 fn range_to_inttype(cx: &CrateContext, hint: Hint, bounds: &IntBounds) -> IntType {
581 debug!("range_to_inttype: {:?} {:?}", hint, bounds);
582 // Lists of sizes to try. u64 is always allowed as a fallback.
583 #[allow(non_upper_case_globals)]
584 const choose_shortest: &'static [IntType] = &[
585 attr::UnsignedInt(ast::TyU8), attr::SignedInt(ast::TyI8),
586 attr::UnsignedInt(ast::TyU16), attr::SignedInt(ast::TyI16),
587 attr::UnsignedInt(ast::TyU32), attr::SignedInt(ast::TyI32)];
588 #[allow(non_upper_case_globals)]
589 const at_least_32: &'static [IntType] = &[
590 attr::UnsignedInt(ast::TyU32), attr::SignedInt(ast::TyI32)];
594 attr::ReprInt(span, ity) => {
595 if !bounds_usable(cx, ity, bounds) {
596 cx.sess().span_bug(span, "representation hint insufficient for discriminant range")
600 attr::ReprExtern => {
601 attempts = match &cx.sess().target.target.arch[..] {
602 // WARNING: the ARM EABI has two variants; the one corresponding to `at_least_32`
603 // appears to be used on Linux and NetBSD, but some systems may use the variant
604 // corresponding to `choose_shortest`. However, we don't run on those yet...?
605 "arm" => at_least_32,
610 attempts = choose_shortest;
612 attr::ReprPacked => {
613 cx.tcx().sess.bug("range_to_inttype: found ReprPacked on an enum");
616 cx.tcx().sess.bug("range_to_inttype: found ReprSimd on an enum");
619 for &ity in attempts {
620 if bounds_usable(cx, ity, bounds) {
624 return attr::UnsignedInt(ast::TyU64);
627 pub fn ll_inttype(cx: &CrateContext, ity: IntType) -> Type {
629 attr::SignedInt(t) => Type::int_from_ty(cx, t),
630 attr::UnsignedInt(t) => Type::uint_from_ty(cx, t)
634 fn bounds_usable(cx: &CrateContext, ity: IntType, bounds: &IntBounds) -> bool {
635 debug!("bounds_usable: {:?} {:?}", ity, bounds);
637 attr::SignedInt(_) => {
638 let lllo = C_integral(ll_inttype(cx, ity), bounds.slo as u64, true);
639 let llhi = C_integral(ll_inttype(cx, ity), bounds.shi as u64, true);
640 bounds.slo == const_to_int(lllo) as i64 && bounds.shi == const_to_int(llhi) as i64
642 attr::UnsignedInt(_) => {
643 let lllo = C_integral(ll_inttype(cx, ity), bounds.ulo, false);
644 let llhi = C_integral(ll_inttype(cx, ity), bounds.uhi, false);
645 bounds.ulo == const_to_uint(lllo) as u64 && bounds.uhi == const_to_uint(llhi) as u64
650 pub fn ty_of_inttype<'tcx>(tcx: &ty::ctxt<'tcx>, ity: IntType) -> Ty<'tcx> {
652 attr::SignedInt(t) => tcx.mk_mach_int(t),
653 attr::UnsignedInt(t) => tcx.mk_mach_uint(t)
657 // LLVM doesn't like types that don't fit in the address space
658 fn ensure_struct_fits_in_address_space<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
661 scapegoat: Ty<'tcx>) {
663 for &llty in fields {
664 // Invariant: offset < ccx.obj_size_bound() <= 1<<61
666 let type_align = machine::llalign_of_min(ccx, llty);
667 offset = roundup(offset, type_align);
669 // type_align is a power-of-2, so still offset < ccx.obj_size_bound()
670 // llsize_of_alloc(ccx, llty) is also less than ccx.obj_size_bound()
671 // so the sum is less than 1<<62 (and therefore can't overflow).
672 offset += machine::llsize_of_alloc(ccx, llty);
674 if offset >= ccx.obj_size_bound() {
675 ccx.report_overbig_object(scapegoat);
680 fn union_size_and_align(sts: &[Struct]) -> (machine::llsize, machine::llalign) {
681 let size = sts.iter().map(|st| st.size).max().unwrap();
682 let align = sts.iter().map(|st| st.align).max().unwrap();
683 (roundup(size, align), align)
686 fn ensure_enum_fits_in_address_space<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
688 scapegoat: Ty<'tcx>) {
689 let (total_size, _) = union_size_and_align(fields);
691 if total_size >= ccx.obj_size_bound() {
692 ccx.report_overbig_object(scapegoat);
697 /// LLVM-level types are a little complicated.
699 /// C-like enums need to be actual ints, not wrapped in a struct,
700 /// because that changes the ABI on some platforms (see issue #10308).
702 /// For nominal types, in some cases, we need to use LLVM named structs
703 /// and fill in the actual contents in a second pass to prevent
704 /// unbounded recursion; see also the comments in `trans::type_of`.
705 pub fn type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, r: &Repr<'tcx>) -> Type {
706 let c = generic_type_of(cx, r, None, false, false, false);
707 assert!(!c.needs_drop_flag);
712 // Pass dst=true if the type you are passing is a DST. Yes, we could figure
713 // this out, but if you call this on an unsized type without realising it, you
714 // are going to get the wrong type (it will not include the unsized parts of it).
715 pub fn sizing_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
716 r: &Repr<'tcx>, dst: bool) -> Type {
717 let c = generic_type_of(cx, r, None, true, dst, false);
718 assert!(!c.needs_drop_flag);
721 pub fn sizing_type_context_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
722 r: &Repr<'tcx>, dst: bool) -> TypeContext {
723 generic_type_of(cx, r, None, true, dst, true)
725 pub fn incomplete_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
726 r: &Repr<'tcx>, name: &str) -> Type {
727 let c = generic_type_of(cx, r, Some(name), false, false, false);
728 assert!(!c.needs_drop_flag);
731 pub fn finish_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
732 r: &Repr<'tcx>, llty: &mut Type) {
734 CEnum(..) | General(..) | RawNullablePointer { .. } => { }
735 Univariant(ref st, _) | StructWrappedNullablePointer { nonnull: ref st, .. } =>
736 llty.set_struct_body(&struct_llfields(cx, st, false, false),
741 fn generic_type_of<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
746 delay_drop_flag: bool) -> TypeContext {
747 debug!("adt::generic_type_of r: {:?} name: {:?} sizing: {} dst: {} delay_drop_flag: {}",
748 r, name, sizing, dst, delay_drop_flag);
750 CEnum(ity, _, _) => TypeContext::direct(ll_inttype(cx, ity)),
751 RawNullablePointer { nnty, .. } =>
752 TypeContext::direct(type_of::sizing_type_of(cx, nnty)),
753 StructWrappedNullablePointer { nonnull: ref st, .. } => {
757 Type::struct_(cx, &struct_llfields(cx, st, sizing, dst),
761 assert_eq!(sizing, false);
762 TypeContext::direct(Type::named_struct(cx, name))
766 Univariant(ref st, dtor_needed) => {
767 let dtor_needed = dtor_needed != 0;
770 let mut fields = struct_llfields(cx, st, sizing, dst);
771 if delay_drop_flag && dtor_needed {
774 TypeContext::may_need_drop_flag(
775 Type::struct_(cx, &fields,
777 delay_drop_flag && dtor_needed)
780 // Hypothesis: named_struct's can never need a
781 // drop flag. (... needs validation.)
782 assert_eq!(sizing, false);
783 TypeContext::direct(Type::named_struct(cx, name))
787 General(ity, ref sts, dtor_needed) => {
788 let dtor_needed = dtor_needed != 0;
789 // We need a representation that has:
790 // * The alignment of the most-aligned field
791 // * The size of the largest variant (rounded up to that alignment)
792 // * No alignment padding anywhere any variant has actual data
793 // (currently matters only for enums small enough to be immediate)
794 // * The discriminant in an obvious place.
796 // So we start with the discriminant, pad it up to the alignment with
797 // more of its own type, then use alignment-sized ints to get the rest
800 // FIXME #10604: this breaks when vector types are present.
801 let (size, align) = union_size_and_align(&sts[..]);
802 let align_s = align as u64;
803 assert_eq!(size % align_s, 0);
804 let align_units = size / align_s - 1;
806 let discr_ty = ll_inttype(cx, ity);
807 let discr_size = machine::llsize_of_alloc(cx, discr_ty);
808 let fill_ty = match align_s {
809 1 => Type::array(&Type::i8(cx), align_units),
810 2 => Type::array(&Type::i16(cx), align_units),
811 4 => Type::array(&Type::i32(cx), align_units),
812 8 if machine::llalign_of_min(cx, Type::i64(cx)) == 8 =>
813 Type::array(&Type::i64(cx), align_units),
814 a if a.count_ones() == 1 => Type::array(&Type::vector(&Type::i32(cx), a / 4),
816 _ => panic!("unsupported enum alignment: {}", align)
818 assert_eq!(machine::llalign_of_min(cx, fill_ty), align);
819 assert_eq!(align_s % discr_size, 0);
820 let mut fields: Vec<Type> =
822 Type::array(&discr_ty, align_s / discr_size - 1),
823 fill_ty].iter().cloned().collect();
824 if delay_drop_flag && dtor_needed {
829 TypeContext::may_need_drop_flag(
830 Type::struct_(cx, &fields[..], false),
831 delay_drop_flag && dtor_needed)
834 let mut llty = Type::named_struct(cx, name);
835 llty.set_struct_body(&fields[..], false);
836 TypeContext::may_need_drop_flag(
838 delay_drop_flag && dtor_needed)
845 fn struct_llfields<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, st: &Struct<'tcx>,
846 sizing: bool, dst: bool) -> Vec<Type> {
848 st.fields.iter().filter(|&ty| !dst || type_is_sized(cx.tcx(), *ty))
849 .map(|&ty| type_of::sizing_type_of(cx, ty)).collect()
851 st.fields.iter().map(|&ty| type_of::in_memory_type_of(cx, ty)).collect()
855 /// Obtain a representation of the discriminant sufficient to translate
856 /// destructuring; this may or may not involve the actual discriminant.
858 /// This should ideally be less tightly tied to `_match`.
859 pub fn trans_switch<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
860 r: &Repr<'tcx>, scrutinee: ValueRef)
861 -> (_match::BranchKind, Option<ValueRef>) {
863 CEnum(..) | General(..) |
864 RawNullablePointer { .. } | StructWrappedNullablePointer { .. } => {
865 (_match::Switch, Some(trans_get_discr(bcx, r, scrutinee, None)))
868 // N.B.: Univariant means <= 1 enum variants (*not* == 1 variants).
869 (_match::Single, None)
874 pub fn is_discr_signed<'tcx>(r: &Repr<'tcx>) -> bool {
876 CEnum(ity, _, _) => ity.is_signed(),
877 General(ity, _, _) => ity.is_signed(),
878 Univariant(..) => false,
879 RawNullablePointer { .. } => false,
880 StructWrappedNullablePointer { .. } => false,
884 /// Obtain the actual discriminant of a value.
885 pub fn trans_get_discr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>,
886 scrutinee: ValueRef, cast_to: Option<Type>)
888 debug!("trans_get_discr r: {:?}", r);
890 CEnum(ity, min, max) => load_discr(bcx, ity, scrutinee, min, max),
891 General(ity, ref cases, _) => {
892 let ptr = StructGEP(bcx, scrutinee, 0);
893 load_discr(bcx, ity, ptr, 0, (cases.len() - 1) as Disr)
895 Univariant(..) => C_u8(bcx.ccx(), 0),
896 RawNullablePointer { nndiscr, nnty, .. } => {
897 let cmp = if nndiscr == 0 { IntEQ } else { IntNE };
898 let llptrty = type_of::sizing_type_of(bcx.ccx(), nnty);
899 ICmp(bcx, cmp, Load(bcx, scrutinee), C_null(llptrty), DebugLoc::None)
901 StructWrappedNullablePointer { nndiscr, ref discrfield, .. } => {
902 struct_wrapped_nullable_bitdiscr(bcx, nndiscr, discrfield, scrutinee)
907 Some(llty) => if is_discr_signed(r) { SExt(bcx, val, llty) } else { ZExt(bcx, val, llty) }
911 fn struct_wrapped_nullable_bitdiscr(bcx: Block, nndiscr: Disr, discrfield: &DiscrField,
912 scrutinee: ValueRef) -> ValueRef {
913 let llptrptr = GEPi(bcx, scrutinee, &discrfield[..]);
914 let llptr = Load(bcx, llptrptr);
915 let cmp = if nndiscr == 0 { IntEQ } else { IntNE };
916 ICmp(bcx, cmp, llptr, C_null(val_ty(llptr)), DebugLoc::None)
919 /// Helper for cases where the discriminant is simply loaded.
920 fn load_discr(bcx: Block, ity: IntType, ptr: ValueRef, min: Disr, max: Disr)
922 let llty = ll_inttype(bcx.ccx(), ity);
923 assert_eq!(val_ty(ptr), llty.ptr_to());
924 let bits = machine::llbitsize_of_real(bcx.ccx(), llty);
926 let bits = bits as usize;
927 let mask = (!0u64 >> (64 - bits)) as Disr;
928 // For a (max) discr of -1, max will be `-1 as usize`, which overflows.
929 // However, that is fine here (it would still represent the full range),
930 if (max.wrapping_add(1)) & mask == min & mask {
931 // i.e., if the range is everything. The lo==hi case would be
932 // rejected by the LLVM verifier (it would mean either an
933 // empty set, which is impossible, or the entire range of the
934 // type, which is pointless).
937 // llvm::ConstantRange can deal with ranges that wrap around,
938 // so an overflow on (max + 1) is fine.
939 LoadRangeAssert(bcx, ptr, min, (max.wrapping_add(1)), /* signed: */ True)
943 /// Yield information about how to dispatch a case of the
944 /// discriminant-like value returned by `trans_switch`.
946 /// This should ideally be less tightly tied to `_match`.
947 pub fn trans_case<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr, discr: Disr)
948 -> _match::OptResult<'blk, 'tcx> {
950 CEnum(ity, _, _) => {
951 _match::SingleResult(Result::new(bcx, C_integral(ll_inttype(bcx.ccx(), ity),
952 discr as u64, true)))
954 General(ity, _, _) => {
955 _match::SingleResult(Result::new(bcx, C_integral(ll_inttype(bcx.ccx(), ity),
956 discr as u64, true)))
959 bcx.ccx().sess().bug("no cases for univariants or structs")
961 RawNullablePointer { .. } |
962 StructWrappedNullablePointer { .. } => {
963 assert!(discr == 0 || discr == 1);
964 _match::SingleResult(Result::new(bcx, C_bool(bcx.ccx(), discr != 0)))
969 /// Set the discriminant for a new value of the given case of the given
971 pub fn trans_set_discr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>,
972 val: ValueRef, discr: Disr) {
974 CEnum(ity, min, max) => {
975 assert_discr_in_range(ity, min, max, discr);
976 Store(bcx, C_integral(ll_inttype(bcx.ccx(), ity), discr as u64, true),
979 General(ity, ref cases, dtor) => {
980 if dtor_active(dtor) {
981 let ptr = trans_field_ptr(bcx, r, val, discr,
982 cases[discr as usize].fields.len() - 2);
983 Store(bcx, C_u8(bcx.ccx(), DTOR_NEEDED), ptr);
985 Store(bcx, C_integral(ll_inttype(bcx.ccx(), ity), discr as u64, true),
986 StructGEP(bcx, val, 0));
988 Univariant(ref st, dtor) => {
989 assert_eq!(discr, 0);
990 if dtor_active(dtor) {
991 Store(bcx, C_u8(bcx.ccx(), DTOR_NEEDED),
992 StructGEP(bcx, val, st.fields.len() - 1));
995 RawNullablePointer { nndiscr, nnty, ..} => {
996 if discr != nndiscr {
997 let llptrty = type_of::sizing_type_of(bcx.ccx(), nnty);
998 Store(bcx, C_null(llptrty), val);
1001 StructWrappedNullablePointer { nndiscr, ref discrfield, .. } => {
1002 if discr != nndiscr {
1003 let llptrptr = GEPi(bcx, val, &discrfield[..]);
1004 let llptrty = val_ty(llptrptr).element_type();
1005 Store(bcx, C_null(llptrty), llptrptr);
1011 fn assert_discr_in_range(ity: IntType, min: Disr, max: Disr, discr: Disr) {
1013 attr::UnsignedInt(_) => assert!(min <= discr && discr <= max),
1014 attr::SignedInt(_) => assert!(min as i64 <= discr as i64 && discr as i64 <= max as i64)
1018 /// The number of fields in a given case; for use when obtaining this
1019 /// information from the type or definition is less convenient.
1020 pub fn num_args(r: &Repr, discr: Disr) -> usize {
1023 Univariant(ref st, dtor) => {
1024 assert_eq!(discr, 0);
1025 st.fields.len() - (if dtor_active(dtor) { 1 } else { 0 })
1027 General(_, ref cases, dtor) => {
1028 cases[discr as usize].fields.len() - 1 - (if dtor_active(dtor) { 1 } else { 0 })
1030 RawNullablePointer { nndiscr, ref nullfields, .. } => {
1031 if discr == nndiscr { 1 } else { nullfields.len() }
1033 StructWrappedNullablePointer { ref nonnull, nndiscr,
1034 ref nullfields, .. } => {
1035 if discr == nndiscr { nonnull.fields.len() } else { nullfields.len() }
1040 /// Access a field, at a point when the value's case is known.
1041 pub fn trans_field_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, r: &Repr<'tcx>,
1042 val: ValueRef, discr: Disr, ix: usize) -> ValueRef {
1043 // Note: if this ever needs to generate conditionals (e.g., if we
1044 // decide to do some kind of cdr-coding-like non-unique repr
1045 // someday), it will need to return a possibly-new bcx as well.
1048 bcx.ccx().sess().bug("element access in C-like enum")
1050 Univariant(ref st, _dtor) => {
1051 assert_eq!(discr, 0);
1052 struct_field_ptr(bcx, st, val, ix, false)
1054 General(_, ref cases, _) => {
1055 struct_field_ptr(bcx, &cases[discr as usize], val, ix + 1, true)
1057 RawNullablePointer { nndiscr, ref nullfields, .. } |
1058 StructWrappedNullablePointer { nndiscr, ref nullfields, .. } if discr != nndiscr => {
1059 // The unit-like case might have a nonzero number of unit-like fields.
1060 // (e.d., Result of Either with (), as one side.)
1061 let ty = type_of::type_of(bcx.ccx(), nullfields[ix]);
1062 assert_eq!(machine::llsize_of_alloc(bcx.ccx(), ty), 0);
1063 // The contents of memory at this pointer can't matter, but use
1064 // the value that's "reasonable" in case of pointer comparison.
1065 PointerCast(bcx, val, ty.ptr_to())
1067 RawNullablePointer { nndiscr, nnty, .. } => {
1069 assert_eq!(discr, nndiscr);
1070 let ty = type_of::type_of(bcx.ccx(), nnty);
1071 PointerCast(bcx, val, ty.ptr_to())
1073 StructWrappedNullablePointer { ref nonnull, nndiscr, .. } => {
1074 assert_eq!(discr, nndiscr);
1075 struct_field_ptr(bcx, nonnull, val, ix, false)
1080 pub fn struct_field_ptr<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, st: &Struct<'tcx>, val: ValueRef,
1081 ix: usize, needs_cast: bool) -> ValueRef {
1082 let val = if needs_cast {
1083 let ccx = bcx.ccx();
1084 let fields = st.fields.iter().map(|&ty| type_of::type_of(ccx, ty)).collect::<Vec<_>>();
1085 let real_ty = Type::struct_(ccx, &fields[..], st.packed);
1086 PointerCast(bcx, val, real_ty.ptr_to())
1091 StructGEP(bcx, val, ix)
1094 pub fn fold_variants<'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
1098 -> Block<'blk, 'tcx> where
1099 F: FnMut(Block<'blk, 'tcx>, &Struct<'tcx>, ValueRef) -> Block<'blk, 'tcx>,
1103 Univariant(ref st, _) => {
1106 General(ity, ref cases, _) => {
1107 let ccx = bcx.ccx();
1109 // See the comments in trans/base.rs for more information (inside
1110 // iter_structural_ty), but the gist here is that if the enum's
1111 // discriminant is *not* in the range that we're expecting (in which
1112 // case we'll take the fall-through branch on the switch
1113 // instruction) then we can't just optimize this to an Unreachable
1116 // Currently we still have filling drop, so this means that the drop
1117 // glue for enums may be called when the enum has been paved over
1118 // with the "I've been dropped" value. In this case the default
1119 // branch of the switch instruction will actually be taken at
1120 // runtime, so the basic block isn't actually unreachable, so we
1121 // need to make it do something with defined behavior. In this case
1122 // we just return early from the function.
1123 let ret_void_cx = fcx.new_temp_block("enum-variant-iter-ret-void");
1124 RetVoid(ret_void_cx, DebugLoc::None);
1126 let discr_val = trans_get_discr(bcx, r, value, None);
1127 let llswitch = Switch(bcx, discr_val, ret_void_cx.llbb, cases.len());
1128 let bcx_next = fcx.new_temp_block("enum-variant-iter-next");
1130 for (discr, case) in cases.iter().enumerate() {
1131 let mut variant_cx = fcx.new_temp_block(
1132 &format!("enum-variant-iter-{}", &discr.to_string())
1134 let rhs_val = C_integral(ll_inttype(ccx, ity), discr as u64, true);
1135 AddCase(llswitch, rhs_val, variant_cx.llbb);
1137 let fields = case.fields.iter().map(|&ty|
1138 type_of::type_of(bcx.ccx(), ty)).collect::<Vec<_>>();
1139 let real_ty = Type::struct_(ccx, &fields[..], case.packed);
1140 let variant_value = PointerCast(variant_cx, value, real_ty.ptr_to());
1142 variant_cx = f(variant_cx, case, variant_value);
1143 Br(variant_cx, bcx_next.llbb, DebugLoc::None);
1152 /// Access the struct drop flag, if present.
1153 pub fn trans_drop_flag_ptr<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1156 -> datum::DatumBlock<'blk, 'tcx, datum::Expr>
1158 let tcx = bcx.tcx();
1159 let ptr_ty = bcx.tcx().mk_imm_ptr(tcx.dtor_type());
1161 Univariant(ref st, dtor) if dtor_active(dtor) => {
1162 let flag_ptr = StructGEP(bcx, val, st.fields.len() - 1);
1163 datum::immediate_rvalue_bcx(bcx, flag_ptr, ptr_ty).to_expr_datumblock()
1165 General(_, _, dtor) if dtor_active(dtor) => {
1167 let custom_cleanup_scope = fcx.push_custom_cleanup_scope();
1168 let scratch = unpack_datum!(bcx, datum::lvalue_scratch_datum(
1169 bcx, tcx.dtor_type(), "drop_flag",
1170 cleanup::CustomScope(custom_cleanup_scope), (), |_, bcx, _| bcx
1172 bcx = fold_variants(bcx, r, val, |variant_cx, st, value| {
1173 let ptr = struct_field_ptr(variant_cx, st, value, (st.fields.len() - 1), false);
1174 datum::Datum::new(ptr, ptr_ty, datum::Lvalue::new("adt::trans_drop_flag_ptr"))
1175 .store_to(variant_cx, scratch.val)
1177 let expr_datum = scratch.to_expr_datum();
1178 fcx.pop_custom_cleanup_scope(custom_cleanup_scope);
1179 datum::DatumBlock::new(bcx, expr_datum)
1181 _ => bcx.ccx().sess().bug("tried to get drop flag of non-droppable type")
1185 /// Construct a constant value, suitable for initializing a
1186 /// GlobalVariable, given a case and constant values for its fields.
1187 /// Note that this may have a different LLVM type (and different
1188 /// alignment!) from the representation's `type_of`, so it needs a
1189 /// pointer cast before use.
1191 /// The LLVM type system does not directly support unions, and only
1192 /// pointers can be bitcast, so a constant (and, by extension, the
1193 /// GlobalVariable initialized by it) will have a type that can vary
1194 /// depending on which case of an enum it is.
1196 /// To understand the alignment situation, consider `enum E { V64(u64),
1197 /// V32(u32, u32) }` on Windows. The type has 8-byte alignment to
1198 /// accommodate the u64, but `V32(x, y)` would have LLVM type `{i32,
1199 /// i32, i32}`, which is 4-byte aligned.
1201 /// Currently the returned value has the same size as the type, but
1202 /// this could be changed in the future to avoid allocating unnecessary
1203 /// space after values of shorter-than-maximum cases.
1204 pub fn trans_const<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, r: &Repr<'tcx>, discr: Disr,
1205 vals: &[ValueRef]) -> ValueRef {
1207 CEnum(ity, min, max) => {
1208 assert_eq!(vals.len(), 0);
1209 assert_discr_in_range(ity, min, max, discr);
1210 C_integral(ll_inttype(ccx, ity), discr as u64, true)
1212 General(ity, ref cases, _) => {
1213 let case = &cases[discr as usize];
1214 let (max_sz, _) = union_size_and_align(&cases[..]);
1215 let lldiscr = C_integral(ll_inttype(ccx, ity), discr as u64, true);
1216 let mut f = vec![lldiscr];
1218 let mut contents = build_const_struct(ccx, case, &f[..]);
1219 contents.push_all(&[padding(ccx, max_sz - case.size)]);
1220 C_struct(ccx, &contents[..], false)
1222 Univariant(ref st, _dro) => {
1223 assert!(discr == 0);
1224 let contents = build_const_struct(ccx, st, vals);
1225 C_struct(ccx, &contents[..], st.packed)
1227 RawNullablePointer { nndiscr, nnty, .. } => {
1228 if discr == nndiscr {
1229 assert_eq!(vals.len(), 1);
1232 C_null(type_of::sizing_type_of(ccx, nnty))
1235 StructWrappedNullablePointer { ref nonnull, nndiscr, .. } => {
1236 if discr == nndiscr {
1237 C_struct(ccx, &build_const_struct(ccx,
1242 let vals = nonnull.fields.iter().map(|&ty| {
1243 // Always use null even if it's not the `discrfield`th
1244 // field; see #8506.
1245 C_null(type_of::sizing_type_of(ccx, ty))
1246 }).collect::<Vec<ValueRef>>();
1247 C_struct(ccx, &build_const_struct(ccx,
1256 /// Compute struct field offsets relative to struct begin.
1257 fn compute_struct_field_offsets<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1258 st: &Struct<'tcx>) -> Vec<u64> {
1259 let mut offsets = vec!();
1262 for &ty in &st.fields {
1263 let llty = type_of::sizing_type_of(ccx, ty);
1265 let type_align = type_of::align_of(ccx, ty);
1266 offset = roundup(offset, type_align);
1268 offsets.push(offset);
1269 offset += machine::llsize_of_alloc(ccx, llty);
1271 assert_eq!(st.fields.len(), offsets.len());
1275 /// Building structs is a little complicated, because we might need to
1276 /// insert padding if a field's value is less aligned than its type.
1278 /// Continuing the example from `trans_const`, a value of type `(u32,
1279 /// E)` should have the `E` at offset 8, but if that field's
1280 /// initializer is 4-byte aligned then simply translating the tuple as
1281 /// a two-element struct will locate it at offset 4, and accesses to it
1282 /// will read the wrong memory.
1283 fn build_const_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1284 st: &Struct<'tcx>, vals: &[ValueRef])
1286 assert_eq!(vals.len(), st.fields.len());
1288 let target_offsets = compute_struct_field_offsets(ccx, st);
1290 // offset of current value
1292 let mut cfields = Vec::new();
1293 for (&val, target_offset) in vals.iter().zip(target_offsets) {
1295 let val_align = machine::llalign_of_min(ccx, val_ty(val));
1296 offset = roundup(offset, val_align);
1298 if offset != target_offset {
1299 cfields.push(padding(ccx, target_offset - offset));
1300 offset = target_offset;
1302 assert!(!is_undef(val));
1304 offset += machine::llsize_of_alloc(ccx, val_ty(val));
1307 assert!(st.sized && offset <= st.size);
1308 if offset != st.size {
1309 cfields.push(padding(ccx, st.size - offset));
1315 fn padding(ccx: &CrateContext, size: u64) -> ValueRef {
1316 C_undef(Type::array(&Type::i8(ccx), size))
1319 // FIXME this utility routine should be somewhere more general
1321 fn roundup(x: u64, a: u32) -> u64 { let a = a as u64; ((x + (a - 1)) / a) * a }
1323 /// Get the discriminant of a constant value.
1324 pub fn const_get_discrim(ccx: &CrateContext, r: &Repr, val: ValueRef) -> Disr {
1326 CEnum(ity, _, _) => {
1328 attr::SignedInt(..) => const_to_int(val) as Disr,
1329 attr::UnsignedInt(..) => const_to_uint(val) as Disr
1332 General(ity, _, _) => {
1334 attr::SignedInt(..) => const_to_int(const_get_elt(ccx, val, &[0])) as Disr,
1335 attr::UnsignedInt(..) => const_to_uint(const_get_elt(ccx, val, &[0])) as Disr
1338 Univariant(..) => 0,
1339 RawNullablePointer { .. } | StructWrappedNullablePointer { .. } => {
1340 ccx.sess().bug("const discrim access of non c-like enum")
1345 /// Extract a field of a constant value, as appropriate for its
1348 /// (Not to be confused with `common::const_get_elt`, which operates on
1349 /// raw LLVM-level structs and arrays.)
1350 pub fn const_get_field(ccx: &CrateContext, r: &Repr, val: ValueRef,
1351 _discr: Disr, ix: usize) -> ValueRef {
1353 CEnum(..) => ccx.sess().bug("element access in C-like enum const"),
1354 Univariant(..) => const_struct_field(ccx, val, ix),
1355 General(..) => const_struct_field(ccx, val, ix + 1),
1356 RawNullablePointer { .. } => {
1360 StructWrappedNullablePointer{ .. } => const_struct_field(ccx, val, ix)
1364 /// Extract field of struct-like const, skipping our alignment padding.
1365 fn const_struct_field(ccx: &CrateContext, val: ValueRef, ix: usize) -> ValueRef {
1366 // Get the ix-th non-undef element of the struct.
1367 let mut real_ix = 0; // actual position in the struct
1368 let mut ix = ix; // logical index relative to real_ix
1372 field = const_get_elt(ccx, val, &[real_ix]);
1373 if !is_undef(field) {
1376 real_ix = real_ix + 1;
1382 real_ix = real_ix + 1;