]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/mir/place.rs
Rollup merge of #104708 - jonasspinner:fix-backoff-doc-to-match-implementation, r...
[rust.git] / compiler / rustc_codegen_ssa / src / mir / place.rs
1 use super::operand::OperandValue;
2 use super::{FunctionCx, LocalRef};
3
4 use crate::common::IntPredicate;
5 use crate::glue;
6 use crate::traits::*;
7
8 use rustc_middle::mir;
9 use rustc_middle::mir::tcx::PlaceTy;
10 use rustc_middle::ty::layout::{HasTyCtxt, LayoutOf, TyAndLayout};
11 use rustc_middle::ty::{self, Ty};
12 use rustc_target::abi::{Abi, Align, FieldsShape, Int, TagEncoding};
13 use rustc_target::abi::{VariantIdx, Variants};
14
15 #[derive(Copy, Clone, Debug)]
16 pub struct PlaceRef<'tcx, V> {
17     /// A pointer to the contents of the place.
18     pub llval: V,
19
20     /// This place's extra data if it is unsized, or `None` if null.
21     pub llextra: Option<V>,
22
23     /// The monomorphized type of this place, including variant information.
24     pub layout: TyAndLayout<'tcx>,
25
26     /// The alignment we know for this place.
27     pub align: Align,
28 }
29
30 impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> {
31     pub fn new_sized(llval: V, layout: TyAndLayout<'tcx>) -> PlaceRef<'tcx, V> {
32         assert!(layout.is_sized());
33         PlaceRef { llval, llextra: None, layout, align: layout.align.abi }
34     }
35
36     pub fn new_sized_aligned(
37         llval: V,
38         layout: TyAndLayout<'tcx>,
39         align: Align,
40     ) -> PlaceRef<'tcx, V> {
41         assert!(layout.is_sized());
42         PlaceRef { llval, llextra: None, layout, align }
43     }
44
45     // FIXME(eddyb) pass something else for the name so no work is done
46     // unless LLVM IR names are turned on (e.g. for `--emit=llvm-ir`).
47     pub fn alloca<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
48         bx: &mut Bx,
49         layout: TyAndLayout<'tcx>,
50     ) -> Self {
51         assert!(layout.is_sized(), "tried to statically allocate unsized place");
52         let tmp = bx.alloca(bx.cx().backend_type(layout), layout.align.abi);
53         Self::new_sized(tmp, layout)
54     }
55
56     /// Returns a place for an indirect reference to an unsized place.
57     // FIXME(eddyb) pass something else for the name so no work is done
58     // unless LLVM IR names are turned on (e.g. for `--emit=llvm-ir`).
59     pub fn alloca_unsized_indirect<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
60         bx: &mut Bx,
61         layout: TyAndLayout<'tcx>,
62     ) -> Self {
63         assert!(layout.is_unsized(), "tried to allocate indirect place for sized values");
64         let ptr_ty = bx.cx().tcx().mk_mut_ptr(layout.ty);
65         let ptr_layout = bx.cx().layout_of(ptr_ty);
66         Self::alloca(bx, ptr_layout)
67     }
68
69     pub fn len<Cx: ConstMethods<'tcx, Value = V>>(&self, cx: &Cx) -> V {
70         if let FieldsShape::Array { count, .. } = self.layout.fields {
71             if self.layout.is_unsized() {
72                 assert_eq!(count, 0);
73                 self.llextra.unwrap()
74             } else {
75                 cx.const_usize(count)
76             }
77         } else {
78             bug!("unexpected layout `{:#?}` in PlaceRef::len", self.layout)
79         }
80     }
81 }
82
83 impl<'a, 'tcx, V: CodegenObject> PlaceRef<'tcx, V> {
84     /// Access a field, at a point when the value's case is known.
85     pub fn project_field<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
86         self,
87         bx: &mut Bx,
88         ix: usize,
89     ) -> Self {
90         let field = self.layout.field(bx.cx(), ix);
91         let offset = self.layout.fields.offset(ix);
92         let effective_field_align = self.align.restrict_for_offset(offset);
93
94         let mut simple = || {
95             let llval = match self.layout.abi {
96                 _ if offset.bytes() == 0 => {
97                     // Unions and newtypes only use an offset of 0.
98                     // Also handles the first field of Scalar, ScalarPair, and Vector layouts.
99                     self.llval
100                 }
101                 Abi::ScalarPair(a, b)
102                     if offset == a.size(bx.cx()).align_to(b.align(bx.cx()).abi) =>
103                 {
104                     // Offset matches second field.
105                     let ty = bx.backend_type(self.layout);
106                     bx.struct_gep(ty, self.llval, 1)
107                 }
108                 Abi::Scalar(_) | Abi::ScalarPair(..) | Abi::Vector { .. } if field.is_zst() => {
109                     // ZST fields are not included in Scalar, ScalarPair, and Vector layouts, so manually offset the pointer.
110                     let byte_ptr = bx.pointercast(self.llval, bx.cx().type_i8p());
111                     bx.gep(bx.cx().type_i8(), byte_ptr, &[bx.const_usize(offset.bytes())])
112                 }
113                 Abi::Scalar(_) | Abi::ScalarPair(..) => {
114                     // All fields of Scalar and ScalarPair layouts must have been handled by this point.
115                     // Vector layouts have additional fields for each element of the vector, so don't panic in that case.
116                     bug!(
117                         "offset of non-ZST field `{:?}` does not match layout `{:#?}`",
118                         field,
119                         self.layout
120                     );
121                 }
122                 _ => {
123                     let ty = bx.backend_type(self.layout);
124                     bx.struct_gep(ty, self.llval, bx.cx().backend_field_index(self.layout, ix))
125                 }
126             };
127             PlaceRef {
128                 // HACK(eddyb): have to bitcast pointers until LLVM removes pointee types.
129                 llval: bx.pointercast(llval, bx.cx().type_ptr_to(bx.cx().backend_type(field))),
130                 llextra: if bx.cx().type_has_metadata(field.ty) { self.llextra } else { None },
131                 layout: field,
132                 align: effective_field_align,
133             }
134         };
135
136         // Simple cases, which don't need DST adjustment:
137         //   * no metadata available - just log the case
138         //   * known alignment - sized types, `[T]`, `str` or a foreign type
139         //   * packed struct - there is no alignment padding
140         match field.ty.kind() {
141             _ if self.llextra.is_none() => {
142                 debug!(
143                     "unsized field `{}`, of `{:?}` has no metadata for adjustment",
144                     ix, self.llval
145                 );
146                 return simple();
147             }
148             _ if field.is_sized() => return simple(),
149             ty::Slice(..) | ty::Str | ty::Foreign(..) => return simple(),
150             ty::Adt(def, _) => {
151                 if def.repr().packed() {
152                     // FIXME(eddyb) generalize the adjustment when we
153                     // start supporting packing to larger alignments.
154                     assert_eq!(self.layout.align.abi.bytes(), 1);
155                     return simple();
156                 }
157             }
158             _ => {}
159         }
160
161         // We need to get the pointer manually now.
162         // We do this by casting to a `*i8`, then offsetting it by the appropriate amount.
163         // We do this instead of, say, simply adjusting the pointer from the result of a GEP
164         // because the field may have an arbitrary alignment in the LLVM representation
165         // anyway.
166         //
167         // To demonstrate:
168         //
169         //     struct Foo<T: ?Sized> {
170         //         x: u16,
171         //         y: T
172         //     }
173         //
174         // The type `Foo<Foo<Trait>>` is represented in LLVM as `{ u16, { u16, u8 }}`, meaning that
175         // the `y` field has 16-bit alignment.
176
177         let meta = self.llextra;
178
179         let unaligned_offset = bx.cx().const_usize(offset.bytes());
180
181         // Get the alignment of the field
182         let (_, unsized_align) = glue::size_and_align_of_dst(bx, field.ty, meta);
183
184         // Bump the unaligned offset up to the appropriate alignment
185         let offset = round_up_const_value_to_alignment(bx, unaligned_offset, unsized_align);
186
187         debug!("struct_field_ptr: DST field offset: {:?}", offset);
188
189         // Cast and adjust pointer.
190         let byte_ptr = bx.pointercast(self.llval, bx.cx().type_i8p());
191         let byte_ptr = bx.gep(bx.cx().type_i8(), byte_ptr, &[offset]);
192
193         // Finally, cast back to the type expected.
194         let ll_fty = bx.cx().backend_type(field);
195         debug!("struct_field_ptr: Field type is {:?}", ll_fty);
196
197         PlaceRef {
198             llval: bx.pointercast(byte_ptr, bx.cx().type_ptr_to(ll_fty)),
199             llextra: self.llextra,
200             layout: field,
201             align: effective_field_align,
202         }
203     }
204
205     /// Obtain the actual discriminant of a value.
206     #[instrument(level = "trace", skip(bx))]
207     pub fn codegen_get_discr<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
208         self,
209         bx: &mut Bx,
210         cast_to: Ty<'tcx>,
211     ) -> V {
212         let cast_to_layout = bx.cx().layout_of(cast_to);
213         let cast_to_size = cast_to_layout.layout.size();
214         let cast_to = bx.cx().immediate_backend_type(cast_to_layout);
215         if self.layout.abi.is_uninhabited() {
216             return bx.cx().const_undef(cast_to);
217         }
218         let (tag_scalar, tag_encoding, tag_field) = match self.layout.variants {
219             Variants::Single { index } => {
220                 let discr_val = self
221                     .layout
222                     .ty
223                     .discriminant_for_variant(bx.cx().tcx(), index)
224                     .map_or(index.as_u32() as u128, |discr| discr.val);
225                 return bx.cx().const_uint_big(cast_to, discr_val);
226             }
227             Variants::Multiple { tag, ref tag_encoding, tag_field, .. } => {
228                 (tag, tag_encoding, tag_field)
229             }
230         };
231
232         // Read the tag/niche-encoded discriminant from memory.
233         let tag = self.project_field(bx, tag_field);
234         let tag_op = bx.load_operand(tag);
235         let tag_imm = tag_op.immediate();
236
237         // Decode the discriminant (specifically if it's niche-encoded).
238         match *tag_encoding {
239             TagEncoding::Direct => {
240                 let signed = match tag_scalar.primitive() {
241                     // We use `i1` for bytes that are always `0` or `1`,
242                     // e.g., `#[repr(i8)] enum E { A, B }`, but we can't
243                     // let LLVM interpret the `i1` as signed, because
244                     // then `i1 1` (i.e., `E::B`) is effectively `i8 -1`.
245                     Int(_, signed) => !tag_scalar.is_bool() && signed,
246                     _ => false,
247                 };
248                 bx.intcast(tag_imm, cast_to, signed)
249             }
250             TagEncoding::Niche { untagged_variant, ref niche_variants, niche_start } => {
251                 // Cast to an integer so we don't have to treat a pointer as a
252                 // special case.
253                 let (tag, tag_llty) = if tag_scalar.primitive().is_ptr() {
254                     let t = bx.type_isize();
255                     let tag = bx.ptrtoint(tag_imm, t);
256                     (tag, t)
257                 } else {
258                     (tag_imm, bx.cx().immediate_backend_type(tag_op.layout))
259                 };
260
261                 let tag_size = tag_scalar.size(bx.cx());
262                 let max_unsigned = tag_size.unsigned_int_max();
263                 let max_signed = tag_size.signed_int_max() as u128;
264                 let min_signed = max_signed + 1;
265                 let relative_max = niche_variants.end().as_u32() - niche_variants.start().as_u32();
266                 let niche_end = niche_start.wrapping_add(relative_max as u128) & max_unsigned;
267                 let range = tag_scalar.valid_range(bx.cx());
268
269                 let sle = |lhs: u128, rhs: u128| -> bool {
270                     // Signed and unsigned comparisons give the same results,
271                     // except that in signed comparisons an integer with the
272                     // sign bit set is less than one with the sign bit clear.
273                     // Toggle the sign bit to do a signed comparison.
274                     (lhs ^ min_signed) <= (rhs ^ min_signed)
275                 };
276
277                 // We have a subrange `niche_start..=niche_end` inside `range`.
278                 // If the value of the tag is inside this subrange, it's a
279                 // "niche value", an increment of the discriminant. Otherwise it
280                 // indicates the untagged variant.
281                 // A general algorithm to extract the discriminant from the tag
282                 // is:
283                 // relative_tag = tag - niche_start
284                 // is_niche = relative_tag <= (ule) relative_max
285                 // discr = if is_niche {
286                 //     cast(relative_tag) + niche_variants.start()
287                 // } else {
288                 //     untagged_variant
289                 // }
290                 // However, we will likely be able to emit simpler code.
291
292                 // Find the least and greatest values in `range`, considered
293                 // both as signed and unsigned.
294                 let (low_unsigned, high_unsigned) = if range.start <= range.end {
295                     (range.start, range.end)
296                 } else {
297                     (0, max_unsigned)
298                 };
299                 let (low_signed, high_signed) = if sle(range.start, range.end) {
300                     (range.start, range.end)
301                 } else {
302                     (min_signed, max_signed)
303                 };
304
305                 let niches_ule = niche_start <= niche_end;
306                 let niches_sle = sle(niche_start, niche_end);
307                 let cast_smaller = cast_to_size <= tag_size;
308
309                 // In the algorithm above, we can change
310                 // cast(relative_tag) + niche_variants.start()
311                 // into
312                 // cast(tag + (niche_variants.start() - niche_start))
313                 // if either the casted type is no larger than the original
314                 // type, or if the niche values are contiguous (in either the
315                 // signed or unsigned sense).
316                 let can_incr = cast_smaller || niches_ule || niches_sle;
317
318                 let data_for_boundary_niche = || -> Option<(IntPredicate, u128)> {
319                     if !can_incr {
320                         None
321                     } else if niche_start == low_unsigned {
322                         Some((IntPredicate::IntULE, niche_end))
323                     } else if niche_end == high_unsigned {
324                         Some((IntPredicate::IntUGE, niche_start))
325                     } else if niche_start == low_signed {
326                         Some((IntPredicate::IntSLE, niche_end))
327                     } else if niche_end == high_signed {
328                         Some((IntPredicate::IntSGE, niche_start))
329                     } else {
330                         None
331                     }
332                 };
333
334                 let (is_niche, tagged_discr, delta) = if relative_max == 0 {
335                     // Best case scenario: only one tagged variant. This will
336                     // likely become just a comparison and a jump.
337                     // The algorithm is:
338                     // is_niche = tag == niche_start
339                     // discr = if is_niche {
340                     //     niche_start
341                     // } else {
342                     //     untagged_variant
343                     // }
344                     let niche_start = bx.cx().const_uint_big(tag_llty, niche_start);
345                     let is_niche = bx.icmp(IntPredicate::IntEQ, tag, niche_start);
346                     let tagged_discr =
347                         bx.cx().const_uint(cast_to, niche_variants.start().as_u32() as u64);
348                     (is_niche, tagged_discr, 0)
349                 } else if let Some((predicate, constant)) = data_for_boundary_niche() {
350                     // The niche values are either the lowest or the highest in
351                     // `range`. We can avoid the first subtraction in the
352                     // algorithm.
353                     // The algorithm is now this:
354                     // is_niche = tag <= niche_end
355                     // discr = if is_niche {
356                     //     cast(tag + (niche_variants.start() - niche_start))
357                     // } else {
358                     //     untagged_variant
359                     // }
360                     // (the first line may instead be tag >= niche_start,
361                     // and may be a signed or unsigned comparison)
362                     // The arithmetic must be done before the cast, so we can
363                     // have the correct wrapping behavior. See issue #104519 for
364                     // the consequences of getting this wrong.
365                     let is_niche =
366                         bx.icmp(predicate, tag, bx.cx().const_uint_big(tag_llty, constant));
367                     let delta = (niche_variants.start().as_u32() as u128).wrapping_sub(niche_start);
368                     let incr_tag = if delta == 0 {
369                         tag
370                     } else {
371                         bx.add(tag, bx.cx().const_uint_big(tag_llty, delta))
372                     };
373
374                     let cast_tag = if cast_smaller {
375                         bx.intcast(incr_tag, cast_to, false)
376                     } else if niches_ule {
377                         bx.zext(incr_tag, cast_to)
378                     } else {
379                         bx.sext(incr_tag, cast_to)
380                     };
381
382                     (is_niche, cast_tag, 0)
383                 } else {
384                     // The special cases don't apply, so we'll have to go with
385                     // the general algorithm.
386                     let relative_discr = bx.sub(tag, bx.cx().const_uint_big(tag_llty, niche_start));
387                     let cast_tag = bx.intcast(relative_discr, cast_to, false);
388                     let is_niche = bx.icmp(
389                         IntPredicate::IntULE,
390                         relative_discr,
391                         bx.cx().const_uint(tag_llty, relative_max as u64),
392                     );
393                     (is_niche, cast_tag, niche_variants.start().as_u32() as u128)
394                 };
395
396                 let tagged_discr = if delta == 0 {
397                     tagged_discr
398                 } else {
399                     bx.add(tagged_discr, bx.cx().const_uint_big(cast_to, delta))
400                 };
401
402                 let discr = bx.select(
403                     is_niche,
404                     tagged_discr,
405                     bx.cx().const_uint(cast_to, untagged_variant.as_u32() as u64),
406                 );
407
408                 // In principle we could insert assumes on the possible range of `discr`, but
409                 // currently in LLVM this seems to be a pessimization.
410
411                 discr
412             }
413         }
414     }
415
416     /// Sets the discriminant for a new value of the given case of the given
417     /// representation.
418     pub fn codegen_set_discr<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
419         &self,
420         bx: &mut Bx,
421         variant_index: VariantIdx,
422     ) {
423         if self.layout.for_variant(bx.cx(), variant_index).abi.is_uninhabited() {
424             // We play it safe by using a well-defined `abort`, but we could go for immediate UB
425             // if that turns out to be helpful.
426             bx.abort();
427             return;
428         }
429         match self.layout.variants {
430             Variants::Single { index } => {
431                 assert_eq!(index, variant_index);
432             }
433             Variants::Multiple { tag_encoding: TagEncoding::Direct, tag_field, .. } => {
434                 let ptr = self.project_field(bx, tag_field);
435                 let to =
436                     self.layout.ty.discriminant_for_variant(bx.tcx(), variant_index).unwrap().val;
437                 bx.store(
438                     bx.cx().const_uint_big(bx.cx().backend_type(ptr.layout), to),
439                     ptr.llval,
440                     ptr.align,
441                 );
442             }
443             Variants::Multiple {
444                 tag_encoding:
445                     TagEncoding::Niche { untagged_variant, ref niche_variants, niche_start },
446                 tag_field,
447                 ..
448             } => {
449                 if variant_index != untagged_variant {
450                     let niche = self.project_field(bx, tag_field);
451                     let niche_llty = bx.cx().immediate_backend_type(niche.layout);
452                     let niche_value = variant_index.as_u32() - niche_variants.start().as_u32();
453                     let niche_value = (niche_value as u128).wrapping_add(niche_start);
454                     // FIXME(eddyb): check the actual primitive type here.
455                     let niche_llval = if niche_value == 0 {
456                         // HACK(eddyb): using `c_null` as it works on all types.
457                         bx.cx().const_null(niche_llty)
458                     } else {
459                         bx.cx().const_uint_big(niche_llty, niche_value)
460                     };
461                     OperandValue::Immediate(niche_llval).store(bx, niche);
462                 }
463             }
464         }
465     }
466
467     pub fn project_index<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
468         &self,
469         bx: &mut Bx,
470         llindex: V,
471     ) -> Self {
472         // Statically compute the offset if we can, otherwise just use the element size,
473         // as this will yield the lowest alignment.
474         let layout = self.layout.field(bx, 0);
475         let offset = if let Some(llindex) = bx.const_to_opt_uint(llindex) {
476             layout.size.checked_mul(llindex, bx).unwrap_or(layout.size)
477         } else {
478             layout.size
479         };
480
481         PlaceRef {
482             llval: bx.inbounds_gep(
483                 bx.cx().backend_type(self.layout),
484                 self.llval,
485                 &[bx.cx().const_usize(0), llindex],
486             ),
487             llextra: None,
488             layout,
489             align: self.align.restrict_for_offset(offset),
490         }
491     }
492
493     pub fn project_downcast<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
494         &self,
495         bx: &mut Bx,
496         variant_index: VariantIdx,
497     ) -> Self {
498         let mut downcast = *self;
499         downcast.layout = self.layout.for_variant(bx.cx(), variant_index);
500
501         // Cast to the appropriate variant struct type.
502         let variant_ty = bx.cx().backend_type(downcast.layout);
503         downcast.llval = bx.pointercast(downcast.llval, bx.cx().type_ptr_to(variant_ty));
504
505         downcast
506     }
507
508     pub fn project_type<Bx: BuilderMethods<'a, 'tcx, Value = V>>(
509         &self,
510         bx: &mut Bx,
511         ty: Ty<'tcx>,
512     ) -> Self {
513         let mut downcast = *self;
514         downcast.layout = bx.cx().layout_of(ty);
515
516         // Cast to the appropriate type.
517         let variant_ty = bx.cx().backend_type(downcast.layout);
518         downcast.llval = bx.pointercast(downcast.llval, bx.cx().type_ptr_to(variant_ty));
519
520         downcast
521     }
522
523     pub fn storage_live<Bx: BuilderMethods<'a, 'tcx, Value = V>>(&self, bx: &mut Bx) {
524         bx.lifetime_start(self.llval, self.layout.size);
525     }
526
527     pub fn storage_dead<Bx: BuilderMethods<'a, 'tcx, Value = V>>(&self, bx: &mut Bx) {
528         bx.lifetime_end(self.llval, self.layout.size);
529     }
530 }
531
532 impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
533     #[instrument(level = "trace", skip(self, bx))]
534     pub fn codegen_place(
535         &mut self,
536         bx: &mut Bx,
537         place_ref: mir::PlaceRef<'tcx>,
538     ) -> PlaceRef<'tcx, Bx::Value> {
539         let cx = self.cx;
540         let tcx = self.cx.tcx();
541
542         let mut base = 0;
543         let mut cg_base = match self.locals[place_ref.local] {
544             LocalRef::Place(place) => place,
545             LocalRef::UnsizedPlace(place) => bx.load_operand(place).deref(cx),
546             LocalRef::Operand(..) => {
547                 if place_ref.has_deref() {
548                     base = 1;
549                     let cg_base = self.codegen_consume(
550                         bx,
551                         mir::PlaceRef { projection: &place_ref.projection[..0], ..place_ref },
552                     );
553                     cg_base.deref(bx.cx())
554                 } else {
555                     bug!("using operand local {:?} as place", place_ref);
556                 }
557             }
558         };
559         for elem in place_ref.projection[base..].iter() {
560             cg_base = match *elem {
561                 mir::ProjectionElem::Deref => bx.load_operand(cg_base).deref(bx.cx()),
562                 mir::ProjectionElem::Field(ref field, _) => {
563                     cg_base.project_field(bx, field.index())
564                 }
565                 mir::ProjectionElem::OpaqueCast(ty) => cg_base.project_type(bx, ty),
566                 mir::ProjectionElem::Index(index) => {
567                     let index = &mir::Operand::Copy(mir::Place::from(index));
568                     let index = self.codegen_operand(bx, index);
569                     let llindex = index.immediate();
570                     cg_base.project_index(bx, llindex)
571                 }
572                 mir::ProjectionElem::ConstantIndex { offset, from_end: false, min_length: _ } => {
573                     let lloffset = bx.cx().const_usize(offset as u64);
574                     cg_base.project_index(bx, lloffset)
575                 }
576                 mir::ProjectionElem::ConstantIndex { offset, from_end: true, min_length: _ } => {
577                     let lloffset = bx.cx().const_usize(offset as u64);
578                     let lllen = cg_base.len(bx.cx());
579                     let llindex = bx.sub(lllen, lloffset);
580                     cg_base.project_index(bx, llindex)
581                 }
582                 mir::ProjectionElem::Subslice { from, to, from_end } => {
583                     let mut subslice = cg_base.project_index(bx, bx.cx().const_usize(from as u64));
584                     let projected_ty =
585                         PlaceTy::from_ty(cg_base.layout.ty).projection_ty(tcx, *elem).ty;
586                     subslice.layout = bx.cx().layout_of(self.monomorphize(projected_ty));
587
588                     if subslice.layout.is_unsized() {
589                         assert!(from_end, "slice subslices should be `from_end`");
590                         subslice.llextra = Some(bx.sub(
591                             cg_base.llextra.unwrap(),
592                             bx.cx().const_usize((from as u64) + (to as u64)),
593                         ));
594                     }
595
596                     // Cast the place pointer type to the new
597                     // array or slice type (`*[%_; new_len]`).
598                     subslice.llval = bx.pointercast(
599                         subslice.llval,
600                         bx.cx().type_ptr_to(bx.cx().backend_type(subslice.layout)),
601                     );
602
603                     subslice
604                 }
605                 mir::ProjectionElem::Downcast(_, v) => cg_base.project_downcast(bx, v),
606             };
607         }
608         debug!("codegen_place(place={:?}) => {:?}", place_ref, cg_base);
609         cg_base
610     }
611
612     pub fn monomorphized_place_ty(&self, place_ref: mir::PlaceRef<'tcx>) -> Ty<'tcx> {
613         let tcx = self.cx.tcx();
614         let place_ty = place_ref.ty(self.mir, tcx);
615         self.monomorphize(place_ty.ty)
616     }
617 }
618
619 fn round_up_const_value_to_alignment<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
620     bx: &mut Bx,
621     value: Bx::Value,
622     align: Bx::Value,
623 ) -> Bx::Value {
624     // In pseudo code:
625     //
626     //     if value & (align - 1) == 0 {
627     //         value
628     //     } else {
629     //         (value & !(align - 1)) + align
630     //     }
631     //
632     // Usually this is written without branches as
633     //
634     //     (value + align - 1) & !(align - 1)
635     //
636     // But this formula cannot take advantage of constant `value`. E.g. if `value` is known
637     // at compile time to be `1`, this expression should be optimized to `align`. However,
638     // optimization only holds if `align` is a power of two. Since the optimizer doesn't know
639     // that `align` is a power of two, it cannot perform this optimization.
640     //
641     // Instead we use
642     //
643     //     value + (-value & (align - 1))
644     //
645     // Since `align` is used only once, the expression can be optimized. For `value = 0`
646     // its optimized to `0` even in debug mode.
647     //
648     // NB: The previous version of this code used
649     //
650     //     (value + align - 1) & -align
651     //
652     // Even though `-align == !(align - 1)`, LLVM failed to optimize this even for
653     // `value = 0`. Bug report: https://bugs.llvm.org/show_bug.cgi?id=48559
654     let one = bx.const_usize(1);
655     let align_minus_1 = bx.sub(align, one);
656     let neg_value = bx.neg(value);
657     let offset = bx.and(neg_value, align_minus_1);
658     bx.add(value, offset)
659 }