]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/expr/as_place.rs
Remove useless references/dereferences
[rust.git] / compiler / rustc_mir_build / src / build / expr / as_place.rs
1 //! See docs in build/expr/mod.rs
2
3 use crate::build::expr::category::Category;
4 use crate::build::ForGuard::{OutsideGuard, RefWithinGuard};
5 use crate::build::{BlockAnd, BlockAndExtension, Builder};
6 use crate::thir::*;
7 use rustc_hir::def_id::DefId;
8 use rustc_hir::HirId;
9 use rustc_middle::hir::place::ProjectionKind as HirProjectionKind;
10 use rustc_middle::middle::region;
11 use rustc_middle::mir::AssertKind::BoundsCheck;
12 use rustc_middle::mir::*;
13 use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, TyCtxt, Variance};
14 use rustc_span::Span;
15 use rustc_target::abi::VariantIdx;
16
17 use rustc_index::vec::Idx;
18
19 /// The "outermost" place that holds this value.
20 #[derive(Copy, Clone)]
21 crate enum PlaceBase {
22     /// Denotes the start of a `Place`.
23     Local(Local),
24
25     /// When building place for an expression within a closure, the place might start off a
26     /// captured path. When `capture_disjoint_fields` is enabled, we might not know the capture
27     /// index (within the desugared closure) of the captured path until most of the projections
28     /// are applied. We use `PlaceBase::Upvar` to keep track of the root variable off of which the
29     /// captured path starts, the closure the capture belongs to and the trait the closure
30     /// implements.
31     ///
32     /// Once we have figured out the capture index, we can convert the place builder to start from
33     /// `PlaceBase::Local`.
34     ///
35     /// Consider the following example
36     /// ```rust
37     /// let t = (10, (10, (10, 10)));
38     ///
39     /// let c = || {
40     ///     println!("{}", t.0.0.0);
41     /// };
42     /// ```
43     /// Here the THIR expression for `t.0.0.0` will be something like
44     ///
45     /// ```
46     /// * Field(0)
47     ///     * Field(0)
48     ///         * Field(0)
49     ///             * UpvarRef(t)
50     /// ```
51     ///
52     /// When `capture_disjoint_fields` is enabled, `t.0.0.0` is captured and we won't be able to
53     /// figure out that it is captured until all the `Field` projections are applied.
54     Upvar {
55         /// HirId of the upvar
56         var_hir_id: HirId,
57         /// DefId of the closure
58         closure_def_id: DefId,
59         /// The trait closure implements, `Fn`, `FnMut`, `FnOnce`
60         closure_kind: ty::ClosureKind,
61     },
62 }
63
64 /// `PlaceBuilder` is used to create places during MIR construction. It allows you to "build up" a
65 /// place by pushing more and more projections onto the end, and then convert the final set into a
66 /// place using the `into_place` method.
67 ///
68 /// This is used internally when building a place for an expression like `a.b.c`. The fields `b`
69 /// and `c` can be progressively pushed onto the place builder that is created when converting `a`.
70 #[derive(Clone)]
71 crate struct PlaceBuilder<'tcx> {
72     base: PlaceBase,
73     projection: Vec<PlaceElem<'tcx>>,
74 }
75
76 /// Given a list of MIR projections, convert them to list of HIR ProjectionKind.
77 /// The projections are truncated to represent a path that might be captured by a
78 /// closure/generator. This implies the vector returned from this function doesn't contain
79 /// ProjectionElems `Downcast`, `ConstantIndex`, `Index`, or `Subslice` because those will never be
80 /// part of a path that is captued by a closure. We stop applying projections once we see the first
81 /// projection that isn't captured by a closure.
82 fn convert_to_hir_projections_and_truncate_for_capture<'tcx>(
83     mir_projections: &[PlaceElem<'tcx>],
84 ) -> Vec<HirProjectionKind> {
85     let mut hir_projections = Vec::new();
86
87     for mir_projection in mir_projections {
88         let hir_projection = match mir_projection {
89             ProjectionElem::Deref => HirProjectionKind::Deref,
90             ProjectionElem::Field(field, _) => {
91                 // We will never encouter this for multivariant enums,
92                 // read the comment for `Downcast`.
93                 HirProjectionKind::Field(field.index() as u32, VariantIdx::new(0))
94             }
95             ProjectionElem::Downcast(..) => {
96                 // This projections exist only for enums that have
97                 // multiple variants. Since such enums that are captured
98                 // completely, we can stop here.
99                 break;
100             }
101             ProjectionElem::Index(..)
102             | ProjectionElem::ConstantIndex { .. }
103             | ProjectionElem::Subslice { .. } => {
104                 // We don't capture array-access projections.
105                 // We can stop here as arrays are captured completely.
106                 break;
107             }
108         };
109
110         hir_projections.push(hir_projection);
111     }
112
113     hir_projections
114 }
115
116 /// Return true if the `proj_possible_ancestor` represents an ancestor path
117 /// to `proj_capture` or `proj_possible_ancestor` is same as `proj_capture`,
118 /// assuming they both start off of the same root variable.
119 ///
120 /// **Note:** It's the caller's responsibility to ensure that both lists of projections
121 ///           start off of the same root variable.
122 ///
123 /// Eg: 1. `foo.x` which is represented using `projections=[Field(x)]` is an ancestor of
124 ///        `foo.x.y` which is represented using `projections=[Field(x), Field(y)]`.
125 ///        Note both `foo.x` and `foo.x.y` start off of the same root variable `foo`.
126 ///     2. Since we only look at the projections here function will return `bar.x` as an a valid
127 ///        ancestor of `foo.x.y`. It's the caller's responsibility to ensure that both projections
128 ///        list are being applied to the same root variable.
129 fn is_ancestor_or_same_capture(
130     proj_possible_ancestor: &Vec<HirProjectionKind>,
131     proj_capture: &[HirProjectionKind],
132 ) -> bool {
133     // We want to make sure `is_ancestor_or_same_capture("x.0.0", "x.0")` to return false.
134     // Therefore we can't just check if all projections are same in the zipped iterator below.
135     if proj_possible_ancestor.len() > proj_capture.len() {
136         return false;
137     }
138
139     proj_possible_ancestor.iter().zip(proj_capture).all(|(a, b)| a == b)
140 }
141
142 /// Computes the index of a capture within the desugared closure provided the closure's
143 /// `closure_min_captures` and the capture's index of the capture in the
144 /// `ty::MinCaptureList` of the root variable `var_hir_id`.
145 fn compute_capture_idx<'tcx>(
146     closure_min_captures: &ty::RootVariableMinCaptureList<'tcx>,
147     var_hir_id: HirId,
148     root_var_idx: usize,
149 ) -> usize {
150     let mut res = 0;
151     for (var_id, capture_list) in closure_min_captures {
152         if *var_id == var_hir_id {
153             res += root_var_idx;
154             break;
155         } else {
156             res += capture_list.len();
157         }
158     }
159
160     res
161 }
162
163 /// Given a closure, returns the index of a capture within the desugared closure struct and the
164 /// `ty::CapturedPlace` which is the ancestor of the Place represented using the `var_hir_id`
165 /// and `projection`.
166 ///
167 /// Note there will be at most one ancestor for any given Place.
168 ///
169 /// Returns None, when the ancestor is not found.
170 fn find_capture_matching_projections<'a, 'tcx>(
171     typeck_results: &'a ty::TypeckResults<'tcx>,
172     var_hir_id: HirId,
173     closure_def_id: DefId,
174     projections: &[PlaceElem<'tcx>],
175 ) -> Option<(usize, &'a ty::CapturedPlace<'tcx>)> {
176     let closure_min_captures = typeck_results.closure_min_captures.get(&closure_def_id)?;
177     let root_variable_min_captures = closure_min_captures.get(&var_hir_id)?;
178
179     let hir_projections = convert_to_hir_projections_and_truncate_for_capture(projections);
180
181     // If an ancestor is found, `idx` is the index within the list of captured places
182     // for root variable `var_hir_id` and `capture` is the `ty::CapturedPlace` itself.
183     let (idx, capture) = root_variable_min_captures.iter().enumerate().find(|(_, capture)| {
184         let possible_ancestor_proj_kinds =
185             capture.place.projections.iter().map(|proj| proj.kind).collect();
186         is_ancestor_or_same_capture(&possible_ancestor_proj_kinds, &hir_projections)
187     })?;
188
189     // Convert index to be from the presepective of the entire closure_min_captures map
190     // instead of just the root variable capture list
191     Some((compute_capture_idx(closure_min_captures, var_hir_id, idx), capture))
192 }
193
194 /// Takes a PlaceBuilder and resolves the upvar (if any) within it, so that the
195 /// `PlaceBuilder` now starts from `PlaceBase::Local`.
196 ///
197 /// Returns a Result with the error being the HirId of the Upvar that was not found.
198 fn to_upvars_resolved_place_builder<'a, 'tcx>(
199     from_builder: PlaceBuilder<'tcx>,
200     tcx: TyCtxt<'tcx>,
201     typeck_results: &'a ty::TypeckResults<'tcx>,
202 ) -> Result<PlaceBuilder<'tcx>, HirId> {
203     match from_builder.base {
204         PlaceBase::Local(_) => Ok(from_builder),
205         PlaceBase::Upvar { var_hir_id, closure_def_id, closure_kind } => {
206             // Captures are represented using fields inside a structure.
207             // This represents accessing self in the closure structure
208             let mut upvar_resolved_place_builder = PlaceBuilder::from(Local::new(1));
209             match closure_kind {
210                 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => {
211                     upvar_resolved_place_builder = upvar_resolved_place_builder.deref();
212                 }
213                 ty::ClosureKind::FnOnce => {}
214             }
215
216             let (capture_index, capture) = if let Some(capture_details) =
217                 find_capture_matching_projections(
218                     typeck_results,
219                     var_hir_id,
220                     closure_def_id,
221                     &from_builder.projection,
222                 ) {
223                 capture_details
224             } else {
225                 if !tcx.features().capture_disjoint_fields {
226                     bug!(
227                         "No associated capture found for {:?}[{:#?}] even though \
228                             capture_disjoint_fields isn't enabled",
229                         var_hir_id,
230                         from_builder.projection
231                     )
232                 } else {
233                     // FIXME(project-rfc-2229#24): Handle this case properly
234                     debug!(
235                         "No associated capture found for {:?}[{:#?}]",
236                         var_hir_id, from_builder.projection,
237                     );
238                 }
239                 return Err(var_hir_id);
240             };
241
242             let closure_ty = typeck_results
243                 .node_type(tcx.hir().local_def_id_to_hir_id(closure_def_id.expect_local()));
244
245             let substs = match closure_ty.kind() {
246                 ty::Closure(_, substs) => ty::UpvarSubsts::Closure(substs),
247                 ty::Generator(_, substs, _) => ty::UpvarSubsts::Generator(substs),
248                 _ => bug!("Lowering capture for non-closure type {:?}", closure_ty),
249             };
250
251             // Access the capture by accessing the field within the Closure struct.
252             //
253             // We must have inferred the capture types since we are building MIR, therefore
254             // it's safe to call `tuple_element_ty` and we can unwrap here because
255             // we know that the capture exists and is the `capture_index`-th capture.
256             let var_ty = substs.tupled_upvars_ty().tuple_element_ty(capture_index).unwrap();
257
258             upvar_resolved_place_builder =
259                 upvar_resolved_place_builder.field(Field::new(capture_index), var_ty);
260
261             // If the variable is captured via ByRef(Immutable/Mutable) Borrow,
262             // we need to deref it
263             upvar_resolved_place_builder = match capture.info.capture_kind {
264                 ty::UpvarCapture::ByRef(_) => upvar_resolved_place_builder.deref(),
265                 ty::UpvarCapture::ByValue(_) => upvar_resolved_place_builder,
266             };
267
268             let next_projection = capture.place.projections.len();
269             let mut curr_projections = from_builder.projection;
270
271             // We used some of the projections to build the capture itself,
272             // now we apply the remaining to the upvar resolved place.
273             upvar_resolved_place_builder
274                 .projection
275                 .extend(curr_projections.drain(next_projection..));
276
277             Ok(upvar_resolved_place_builder)
278         }
279     }
280 }
281
282 impl<'tcx> PlaceBuilder<'tcx> {
283     crate fn into_place<'a>(
284         self,
285         tcx: TyCtxt<'tcx>,
286         typeck_results: &'a ty::TypeckResults<'tcx>,
287     ) -> Place<'tcx> {
288         if let PlaceBase::Local(local) = self.base {
289             Place { local, projection: tcx.intern_place_elems(&self.projection) }
290         } else {
291             self.expect_upvars_resolved(tcx, typeck_results).into_place(tcx, typeck_results)
292         }
293     }
294
295     fn expect_upvars_resolved<'a>(
296         self,
297         tcx: TyCtxt<'tcx>,
298         typeck_results: &'a ty::TypeckResults<'tcx>,
299     ) -> PlaceBuilder<'tcx> {
300         to_upvars_resolved_place_builder(self, tcx, typeck_results).unwrap()
301     }
302
303     crate fn base(&self) -> PlaceBase {
304         self.base
305     }
306
307     crate fn field(self, f: Field, ty: Ty<'tcx>) -> Self {
308         self.project(PlaceElem::Field(f, ty))
309     }
310
311     fn deref(self) -> Self {
312         self.project(PlaceElem::Deref)
313     }
314
315     fn index(self, index: Local) -> Self {
316         self.project(PlaceElem::Index(index))
317     }
318
319     fn project(mut self, elem: PlaceElem<'tcx>) -> Self {
320         self.projection.push(elem);
321         self
322     }
323 }
324
325 impl<'tcx> From<Local> for PlaceBuilder<'tcx> {
326     fn from(local: Local) -> Self {
327         Self { base: PlaceBase::Local(local), projection: Vec::new() }
328     }
329 }
330
331 impl<'tcx> From<PlaceBase> for PlaceBuilder<'tcx> {
332     fn from(base: PlaceBase) -> Self {
333         Self { base, projection: Vec::new() }
334     }
335 }
336
337 impl<'a, 'tcx> Builder<'a, 'tcx> {
338     /// Compile `expr`, yielding a place that we can move from etc.
339     ///
340     /// WARNING: Any user code might:
341     /// * Invalidate any slice bounds checks performed.
342     /// * Change the address that this `Place` refers to.
343     /// * Modify the memory that this place refers to.
344     /// * Invalidate the memory that this place refers to, this will be caught
345     ///   by borrow checking.
346     ///
347     /// Extra care is needed if any user code is allowed to run between calling
348     /// this method and using it, as is the case for `match` and index
349     /// expressions.
350     crate fn as_place(
351         &mut self,
352         mut block: BasicBlock,
353         expr: &Expr<'_, 'tcx>,
354     ) -> BlockAnd<Place<'tcx>> {
355         let place_builder = unpack!(block = self.as_place_builder(block, expr));
356         block.and(place_builder.into_place(self.tcx, self.typeck_results))
357     }
358
359     /// This is used when constructing a compound `Place`, so that we can avoid creating
360     /// intermediate `Place` values until we know the full set of projections.
361     crate fn as_place_builder(
362         &mut self,
363         block: BasicBlock,
364         expr: &Expr<'_, 'tcx>,
365     ) -> BlockAnd<PlaceBuilder<'tcx>> {
366         self.expr_as_place(block, expr, Mutability::Mut, None)
367     }
368
369     /// Compile `expr`, yielding a place that we can move from etc.
370     /// Mutability note: The caller of this method promises only to read from the resulting
371     /// place. The place itself may or may not be mutable:
372     /// * If this expr is a place expr like a.b, then we will return that place.
373     /// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
374     crate fn as_read_only_place(
375         &mut self,
376         mut block: BasicBlock,
377         expr: &Expr<'_, 'tcx>,
378     ) -> BlockAnd<Place<'tcx>> {
379         let place_builder = unpack!(block = self.as_read_only_place_builder(block, expr));
380         block.and(place_builder.into_place(self.tcx, self.typeck_results))
381     }
382
383     /// This is used when constructing a compound `Place`, so that we can avoid creating
384     /// intermediate `Place` values until we know the full set of projections.
385     /// Mutability note: The caller of this method promises only to read from the resulting
386     /// place. The place itself may or may not be mutable:
387     /// * If this expr is a place expr like a.b, then we will return that place.
388     /// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
389     fn as_read_only_place_builder(
390         &mut self,
391         block: BasicBlock,
392         expr: &Expr<'_, 'tcx>,
393     ) -> BlockAnd<PlaceBuilder<'tcx>> {
394         self.expr_as_place(block, expr, Mutability::Not, None)
395     }
396
397     fn expr_as_place(
398         &mut self,
399         mut block: BasicBlock,
400         expr: &Expr<'_, 'tcx>,
401         mutability: Mutability,
402         fake_borrow_temps: Option<&mut Vec<Local>>,
403     ) -> BlockAnd<PlaceBuilder<'tcx>> {
404         debug!("expr_as_place(block={:?}, expr={:?}, mutability={:?})", block, expr, mutability);
405
406         let this = self;
407         let expr_span = expr.span;
408         let source_info = this.source_info(expr_span);
409         match expr.kind {
410             ExprKind::Scope { region_scope, lint_level, value } => {
411                 this.in_scope((region_scope, source_info), lint_level, |this| {
412                     this.expr_as_place(block, value, mutability, fake_borrow_temps)
413                 })
414             }
415             ExprKind::Field { lhs, name } => {
416                 let place_builder =
417                     unpack!(block = this.expr_as_place(block, lhs, mutability, fake_borrow_temps,));
418                 block.and(place_builder.field(name, expr.ty))
419             }
420             ExprKind::Deref { arg } => {
421                 let place_builder =
422                     unpack!(block = this.expr_as_place(block, arg, mutability, fake_borrow_temps,));
423                 block.and(place_builder.deref())
424             }
425             ExprKind::Index { lhs, index } => this.lower_index_expression(
426                 block,
427                 lhs,
428                 index,
429                 mutability,
430                 fake_borrow_temps,
431                 expr.temp_lifetime,
432                 expr_span,
433                 source_info,
434             ),
435             ExprKind::UpvarRef { closure_def_id, var_hir_id } => {
436                 let upvar_id = ty::UpvarId::new(var_hir_id, closure_def_id.expect_local());
437                 this.lower_captured_upvar(block, upvar_id)
438             }
439
440             ExprKind::VarRef { id } => {
441                 let place_builder = if this.is_bound_var_in_guard(id) {
442                     let index = this.var_local_id(id, RefWithinGuard);
443                     PlaceBuilder::from(index).deref()
444                 } else {
445                     let index = this.var_local_id(id, OutsideGuard);
446                     PlaceBuilder::from(index)
447                 };
448                 block.and(place_builder)
449             }
450
451             ExprKind::PlaceTypeAscription { source, user_ty } => {
452                 let place_builder = unpack!(
453                     block = this.expr_as_place(block, source, mutability, fake_borrow_temps,)
454                 );
455                 if let Some(user_ty) = user_ty {
456                     let annotation_index =
457                         this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
458                             span: source_info.span,
459                             user_ty,
460                             inferred_ty: expr.ty,
461                         });
462
463                     let place = place_builder.clone().into_place(this.tcx, this.typeck_results);
464                     this.cfg.push(
465                         block,
466                         Statement {
467                             source_info,
468                             kind: StatementKind::AscribeUserType(
469                                 box (
470                                     place,
471                                     UserTypeProjection { base: annotation_index, projs: vec![] },
472                                 ),
473                                 Variance::Invariant,
474                             ),
475                         },
476                     );
477                 }
478                 block.and(place_builder)
479             }
480             ExprKind::ValueTypeAscription { source, user_ty } => {
481                 let temp =
482                     unpack!(block = this.as_temp(block, source.temp_lifetime, source, mutability));
483                 if let Some(user_ty) = user_ty {
484                     let annotation_index =
485                         this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
486                             span: source_info.span,
487                             user_ty,
488                             inferred_ty: expr.ty,
489                         });
490                     this.cfg.push(
491                         block,
492                         Statement {
493                             source_info,
494                             kind: StatementKind::AscribeUserType(
495                                 box (
496                                     Place::from(temp),
497                                     UserTypeProjection { base: annotation_index, projs: vec![] },
498                                 ),
499                                 Variance::Invariant,
500                             ),
501                         },
502                     );
503                 }
504                 block.and(PlaceBuilder::from(temp))
505             }
506
507             ExprKind::Array { .. }
508             | ExprKind::Tuple { .. }
509             | ExprKind::Adt { .. }
510             | ExprKind::Closure { .. }
511             | ExprKind::Unary { .. }
512             | ExprKind::Binary { .. }
513             | ExprKind::LogicalOp { .. }
514             | ExprKind::Box { .. }
515             | ExprKind::Cast { .. }
516             | ExprKind::Use { .. }
517             | ExprKind::NeverToAny { .. }
518             | ExprKind::Pointer { .. }
519             | ExprKind::Repeat { .. }
520             | ExprKind::Borrow { .. }
521             | ExprKind::AddressOf { .. }
522             | ExprKind::Match { .. }
523             | ExprKind::If { .. }
524             | ExprKind::Loop { .. }
525             | ExprKind::Block { .. }
526             | ExprKind::Assign { .. }
527             | ExprKind::AssignOp { .. }
528             | ExprKind::Break { .. }
529             | ExprKind::Continue { .. }
530             | ExprKind::Return { .. }
531             | ExprKind::Literal { .. }
532             | ExprKind::ConstBlock { .. }
533             | ExprKind::StaticRef { .. }
534             | ExprKind::InlineAsm { .. }
535             | ExprKind::LlvmInlineAsm { .. }
536             | ExprKind::Yield { .. }
537             | ExprKind::ThreadLocalRef(_)
538             | ExprKind::Call { .. } => {
539                 // these are not places, so we need to make a temporary.
540                 debug_assert!(!matches!(Category::of(&expr.kind), Some(Category::Place)));
541                 let temp =
542                     unpack!(block = this.as_temp(block, expr.temp_lifetime, expr, mutability));
543                 block.and(PlaceBuilder::from(temp))
544             }
545         }
546     }
547
548     /// Lower a captured upvar. Note we might not know the actual capture index,
549     /// so we create a place starting from `PlaceBase::Upvar`, which will be resolved
550     /// once all projections that allow us to indentify a capture have been applied.
551     fn lower_captured_upvar(
552         &mut self,
553         block: BasicBlock,
554         upvar_id: ty::UpvarId,
555     ) -> BlockAnd<PlaceBuilder<'tcx>> {
556         let closure_ty = self
557             .typeck_results
558             .node_type(self.tcx.hir().local_def_id_to_hir_id(upvar_id.closure_expr_id));
559
560         let closure_kind = if let ty::Closure(_, closure_substs) = closure_ty.kind() {
561             self.infcx.closure_kind(closure_substs).unwrap()
562         } else {
563             // Generators are considered FnOnce.
564             ty::ClosureKind::FnOnce
565         };
566
567         block.and(PlaceBuilder::from(PlaceBase::Upvar {
568             var_hir_id: upvar_id.var_path.hir_id,
569             closure_def_id: upvar_id.closure_expr_id.to_def_id(),
570             closure_kind,
571         }))
572     }
573
574     /// Lower an index expression
575     ///
576     /// This has two complications;
577     ///
578     /// * We need to do a bounds check.
579     /// * We need to ensure that the bounds check can't be invalidated using an
580     ///   expression like `x[1][{x = y; 2}]`. We use fake borrows here to ensure
581     ///   that this is the case.
582     fn lower_index_expression(
583         &mut self,
584         mut block: BasicBlock,
585         base: &Expr<'_, 'tcx>,
586         index: &Expr<'_, 'tcx>,
587         mutability: Mutability,
588         fake_borrow_temps: Option<&mut Vec<Local>>,
589         temp_lifetime: Option<region::Scope>,
590         expr_span: Span,
591         source_info: SourceInfo,
592     ) -> BlockAnd<PlaceBuilder<'tcx>> {
593         let base_fake_borrow_temps = &mut Vec::new();
594         let is_outermost_index = fake_borrow_temps.is_none();
595         let fake_borrow_temps = fake_borrow_temps.unwrap_or(base_fake_borrow_temps);
596
597         let mut base_place =
598             unpack!(block = self.expr_as_place(block, base, mutability, Some(fake_borrow_temps),));
599
600         // Making this a *fresh* temporary means we do not have to worry about
601         // the index changing later: Nothing will ever change this temporary.
602         // The "retagging" transformation (for Stacked Borrows) relies on this.
603         let idx = unpack!(block = self.as_temp(block, temp_lifetime, index, Mutability::Not,));
604
605         block = self.bounds_check(
606             block,
607             base_place.clone().into_place(self.tcx, self.typeck_results),
608             idx,
609             expr_span,
610             source_info,
611         );
612
613         if is_outermost_index {
614             self.read_fake_borrows(block, fake_borrow_temps, source_info)
615         } else {
616             base_place = base_place.expect_upvars_resolved(self.tcx, self.typeck_results);
617             self.add_fake_borrows_of_base(
618                 &base_place,
619                 block,
620                 fake_borrow_temps,
621                 expr_span,
622                 source_info,
623             );
624         }
625
626         block.and(base_place.index(idx))
627     }
628
629     fn bounds_check(
630         &mut self,
631         block: BasicBlock,
632         slice: Place<'tcx>,
633         index: Local,
634         expr_span: Span,
635         source_info: SourceInfo,
636     ) -> BasicBlock {
637         let usize_ty = self.tcx.types.usize;
638         let bool_ty = self.tcx.types.bool;
639         // bounds check:
640         let len = self.temp(usize_ty, expr_span);
641         let lt = self.temp(bool_ty, expr_span);
642
643         // len = len(slice)
644         self.cfg.push_assign(block, source_info, len, Rvalue::Len(slice));
645         // lt = idx < len
646         self.cfg.push_assign(
647             block,
648             source_info,
649             lt,
650             Rvalue::BinaryOp(
651                 BinOp::Lt,
652                 box (Operand::Copy(Place::from(index)), Operand::Copy(len)),
653             ),
654         );
655         let msg = BoundsCheck { len: Operand::Move(len), index: Operand::Copy(Place::from(index)) };
656         // assert!(lt, "...")
657         self.assert(block, Operand::Move(lt), true, msg, expr_span)
658     }
659
660     fn add_fake_borrows_of_base(
661         &mut self,
662         base_place: &PlaceBuilder<'tcx>,
663         block: BasicBlock,
664         fake_borrow_temps: &mut Vec<Local>,
665         expr_span: Span,
666         source_info: SourceInfo,
667     ) {
668         let tcx = self.tcx;
669         let local = match base_place.base {
670             PlaceBase::Local(local) => local,
671             PlaceBase::Upvar { .. } => bug!("Expected PlacseBase::Local found Upvar"),
672         };
673
674         let place_ty = Place::ty_from(local, &base_place.projection, &self.local_decls, tcx);
675         if let ty::Slice(_) = place_ty.ty.kind() {
676             // We need to create fake borrows to ensure that the bounds
677             // check that we just did stays valid. Since we can't assign to
678             // unsized values, we only need to ensure that none of the
679             // pointers in the base place are modified.
680             for (idx, elem) in base_place.projection.iter().enumerate().rev() {
681                 match elem {
682                     ProjectionElem::Deref => {
683                         let fake_borrow_deref_ty = Place::ty_from(
684                             local,
685                             &base_place.projection[..idx],
686                             &self.local_decls,
687                             tcx,
688                         )
689                         .ty;
690                         let fake_borrow_ty =
691                             tcx.mk_imm_ref(tcx.lifetimes.re_erased, fake_borrow_deref_ty);
692                         let fake_borrow_temp =
693                             self.local_decls.push(LocalDecl::new(fake_borrow_ty, expr_span));
694                         let projection = tcx.intern_place_elems(&base_place.projection[..idx]);
695                         self.cfg.push_assign(
696                             block,
697                             source_info,
698                             fake_borrow_temp.into(),
699                             Rvalue::Ref(
700                                 tcx.lifetimes.re_erased,
701                                 BorrowKind::Shallow,
702                                 Place { local, projection },
703                             ),
704                         );
705                         fake_borrow_temps.push(fake_borrow_temp);
706                     }
707                     ProjectionElem::Index(_) => {
708                         let index_ty = Place::ty_from(
709                             local,
710                             &base_place.projection[..idx],
711                             &self.local_decls,
712                             tcx,
713                         );
714                         match index_ty.ty.kind() {
715                             // The previous index expression has already
716                             // done any index expressions needed here.
717                             ty::Slice(_) => break,
718                             ty::Array(..) => (),
719                             _ => bug!("unexpected index base"),
720                         }
721                     }
722                     ProjectionElem::Field(..)
723                     | ProjectionElem::Downcast(..)
724                     | ProjectionElem::ConstantIndex { .. }
725                     | ProjectionElem::Subslice { .. } => (),
726                 }
727             }
728         }
729     }
730
731     fn read_fake_borrows(
732         &mut self,
733         bb: BasicBlock,
734         fake_borrow_temps: &mut Vec<Local>,
735         source_info: SourceInfo,
736     ) {
737         // All indexes have been evaluated now, read all of the
738         // fake borrows so that they are live across those index
739         // expressions.
740         for temp in fake_borrow_temps {
741             self.cfg.push_fake_read(bb, source_info, FakeReadCause::ForIndex, Place::from(*temp));
742         }
743     }
744 }