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