]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/expr/as_place.rs
Auto merge of #77893 - petertodd:2020-impl-default-for-phantompinned, r=dtolnay
[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_middle::middle::region;
8 use rustc_middle::mir::AssertKind::BoundsCheck;
9 use rustc_middle::mir::*;
10 use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty, TyCtxt, Variance};
11 use rustc_span::Span;
12
13 use rustc_index::vec::Idx;
14
15 /// `PlaceBuilder` is used to create places during MIR construction. It allows you to "build up" a
16 /// place by pushing more and more projections onto the end, and then convert the final set into a
17 /// place using the `into_place` method.
18 ///
19 /// This is used internally when building a place for an expression like `a.b.c`. The fields `b`
20 /// and `c` can be progressively pushed onto the place builder that is created when converting `a`.
21 #[derive(Clone)]
22 struct PlaceBuilder<'tcx> {
23     local: Local,
24     projection: Vec<PlaceElem<'tcx>>,
25 }
26
27 impl<'tcx> PlaceBuilder<'tcx> {
28     fn into_place(self, tcx: TyCtxt<'tcx>) -> Place<'tcx> {
29         Place { local: self.local, projection: tcx.intern_place_elems(&self.projection) }
30     }
31
32     fn field(self, f: Field, ty: Ty<'tcx>) -> Self {
33         self.project(PlaceElem::Field(f, ty))
34     }
35
36     fn deref(self) -> Self {
37         self.project(PlaceElem::Deref)
38     }
39
40     fn index(self, index: Local) -> Self {
41         self.project(PlaceElem::Index(index))
42     }
43
44     fn project(mut self, elem: PlaceElem<'tcx>) -> Self {
45         self.projection.push(elem);
46         self
47     }
48 }
49
50 impl<'tcx> From<Local> for PlaceBuilder<'tcx> {
51     fn from(local: Local) -> Self {
52         Self { local, projection: Vec::new() }
53     }
54 }
55
56 impl<'a, 'tcx> Builder<'a, 'tcx> {
57     /// Compile `expr`, yielding a place that we can move from etc.
58     ///
59     /// WARNING: Any user code might:
60     /// * Invalidate any slice bounds checks performed.
61     /// * Change the address that this `Place` refers to.
62     /// * Modify the memory that this place refers to.
63     /// * Invalidate the memory that this place refers to, this will be caught
64     ///   by borrow checking.
65     ///
66     /// Extra care is needed if any user code is allowed to run between calling
67     /// this method and using it, as is the case for `match` and index
68     /// expressions.
69     crate fn as_place<M>(&mut self, mut block: BasicBlock, expr: M) -> BlockAnd<Place<'tcx>>
70     where
71         M: Mirror<'tcx, Output = Expr<'tcx>>,
72     {
73         let place_builder = unpack!(block = self.as_place_builder(block, expr));
74         block.and(place_builder.into_place(self.hir.tcx()))
75     }
76
77     /// This is used when constructing a compound `Place`, so that we can avoid creating
78     /// intermediate `Place` values until we know the full set of projections.
79     fn as_place_builder<M>(&mut self, block: BasicBlock, expr: M) -> BlockAnd<PlaceBuilder<'tcx>>
80     where
81         M: Mirror<'tcx, Output = Expr<'tcx>>,
82     {
83         let expr = self.hir.mirror(expr);
84         self.expr_as_place(block, expr, Mutability::Mut, None)
85     }
86
87     /// Compile `expr`, yielding a place that we can move from etc.
88     /// Mutability note: The caller of this method promises only to read from the resulting
89     /// place. The place itself may or may not be mutable:
90     /// * If this expr is a place expr like a.b, then we will return that place.
91     /// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
92     crate fn as_read_only_place<M>(
93         &mut self,
94         mut block: BasicBlock,
95         expr: M,
96     ) -> BlockAnd<Place<'tcx>>
97     where
98         M: Mirror<'tcx, Output = Expr<'tcx>>,
99     {
100         let place_builder = unpack!(block = self.as_read_only_place_builder(block, expr));
101         block.and(place_builder.into_place(self.hir.tcx()))
102     }
103
104     /// This is used when constructing a compound `Place`, so that we can avoid creating
105     /// intermediate `Place` values until we know the full set of projections.
106     /// Mutability note: The caller of this method promises only to read from the resulting
107     /// place. The place itself may or may not be mutable:
108     /// * If this expr is a place expr like a.b, then we will return that place.
109     /// * Otherwise, a temporary is created: in that event, it will be an immutable temporary.
110     fn as_read_only_place_builder<M>(
111         &mut self,
112         block: BasicBlock,
113         expr: M,
114     ) -> BlockAnd<PlaceBuilder<'tcx>>
115     where
116         M: Mirror<'tcx, Output = Expr<'tcx>>,
117     {
118         let expr = self.hir.mirror(expr);
119         self.expr_as_place(block, expr, Mutability::Not, None)
120     }
121
122     fn expr_as_place(
123         &mut self,
124         mut block: BasicBlock,
125         expr: Expr<'tcx>,
126         mutability: Mutability,
127         fake_borrow_temps: Option<&mut Vec<Local>>,
128     ) -> BlockAnd<PlaceBuilder<'tcx>> {
129         debug!("expr_as_place(block={:?}, expr={:?}, mutability={:?})", block, expr, mutability);
130
131         let this = self;
132         let expr_span = expr.span;
133         let source_info = this.source_info(expr_span);
134         match expr.kind {
135             ExprKind::Scope { region_scope, lint_level, value } => {
136                 this.in_scope((region_scope, source_info), lint_level, |this| {
137                     let value = this.hir.mirror(value);
138                     this.expr_as_place(block, value, mutability, fake_borrow_temps)
139                 })
140             }
141             ExprKind::Field { lhs, name } => {
142                 let lhs = this.hir.mirror(lhs);
143                 let place_builder =
144                     unpack!(block = this.expr_as_place(block, lhs, mutability, fake_borrow_temps,));
145                 block.and(place_builder.field(name, expr.ty))
146             }
147             ExprKind::Deref { arg } => {
148                 let arg = this.hir.mirror(arg);
149                 let place_builder =
150                     unpack!(block = this.expr_as_place(block, arg, mutability, fake_borrow_temps,));
151                 block.and(place_builder.deref())
152             }
153             ExprKind::Index { lhs, index } => this.lower_index_expression(
154                 block,
155                 lhs,
156                 index,
157                 mutability,
158                 fake_borrow_temps,
159                 expr.temp_lifetime,
160                 expr_span,
161                 source_info,
162             ),
163             ExprKind::UpvarRef { closure_def_id, var_hir_id } => {
164                 let capture = this
165                     .hir
166                     .typeck_results
167                     .closure_captures
168                     .get(&closure_def_id)
169                     .and_then(|captures| captures.get_full(&var_hir_id));
170
171                 if capture.is_none() {
172                     if !this.hir.tcx().features().capture_disjoint_fields {
173                         bug!(
174                             "No associated capture found for {:?} even though \
175                             capture_disjoint_fields isn't enabled",
176                             expr.kind
177                         )
178                     }
179                     // FIXME(project-rfc-2229#24): Handle this case properly
180                 }
181
182                 // Unwrap until the FIXME has been resolved
183                 let (capture_index, _, upvar_id) = capture.unwrap();
184                 this.lower_closure_capture(block, capture_index, *upvar_id)
185             }
186
187             ExprKind::VarRef { id } => {
188                 let place_builder = if this.is_bound_var_in_guard(id) {
189                     let index = this.var_local_id(id, RefWithinGuard);
190                     PlaceBuilder::from(index).deref()
191                 } else {
192                     let index = this.var_local_id(id, OutsideGuard);
193                     PlaceBuilder::from(index)
194                 };
195                 block.and(place_builder)
196             }
197
198             ExprKind::PlaceTypeAscription { source, user_ty } => {
199                 let source = this.hir.mirror(source);
200                 let place_builder = unpack!(
201                     block = this.expr_as_place(block, source, mutability, fake_borrow_temps,)
202                 );
203                 if let Some(user_ty) = user_ty {
204                     let annotation_index =
205                         this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
206                             span: source_info.span,
207                             user_ty,
208                             inferred_ty: expr.ty,
209                         });
210
211                     let place = place_builder.clone().into_place(this.hir.tcx());
212                     this.cfg.push(
213                         block,
214                         Statement {
215                             source_info,
216                             kind: StatementKind::AscribeUserType(
217                                 box (
218                                     place,
219                                     UserTypeProjection { base: annotation_index, projs: vec![] },
220                                 ),
221                                 Variance::Invariant,
222                             ),
223                         },
224                     );
225                 }
226                 block.and(place_builder)
227             }
228             ExprKind::ValueTypeAscription { source, user_ty } => {
229                 let source = this.hir.mirror(source);
230                 let temp =
231                     unpack!(block = this.as_temp(block, source.temp_lifetime, source, mutability));
232                 if let Some(user_ty) = user_ty {
233                     let annotation_index =
234                         this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
235                             span: source_info.span,
236                             user_ty,
237                             inferred_ty: expr.ty,
238                         });
239                     this.cfg.push(
240                         block,
241                         Statement {
242                             source_info,
243                             kind: StatementKind::AscribeUserType(
244                                 box (
245                                     Place::from(temp),
246                                     UserTypeProjection { base: annotation_index, projs: vec![] },
247                                 ),
248                                 Variance::Invariant,
249                             ),
250                         },
251                     );
252                 }
253                 block.and(PlaceBuilder::from(temp))
254             }
255
256             ExprKind::Array { .. }
257             | ExprKind::Tuple { .. }
258             | ExprKind::Adt { .. }
259             | ExprKind::Closure { .. }
260             | ExprKind::Unary { .. }
261             | ExprKind::Binary { .. }
262             | ExprKind::LogicalOp { .. }
263             | ExprKind::Box { .. }
264             | ExprKind::Cast { .. }
265             | ExprKind::Use { .. }
266             | ExprKind::NeverToAny { .. }
267             | ExprKind::Pointer { .. }
268             | ExprKind::Repeat { .. }
269             | ExprKind::Borrow { .. }
270             | ExprKind::AddressOf { .. }
271             | ExprKind::Match { .. }
272             | ExprKind::Loop { .. }
273             | ExprKind::Block { .. }
274             | ExprKind::Assign { .. }
275             | ExprKind::AssignOp { .. }
276             | ExprKind::Break { .. }
277             | ExprKind::Continue { .. }
278             | ExprKind::Return { .. }
279             | ExprKind::Literal { .. }
280             | ExprKind::ConstBlock { .. }
281             | ExprKind::StaticRef { .. }
282             | ExprKind::InlineAsm { .. }
283             | ExprKind::LlvmInlineAsm { .. }
284             | ExprKind::Yield { .. }
285             | ExprKind::ThreadLocalRef(_)
286             | ExprKind::Call { .. } => {
287                 // these are not places, so we need to make a temporary.
288                 debug_assert!(!matches!(Category::of(&expr.kind), Some(Category::Place)));
289                 let temp =
290                     unpack!(block = this.as_temp(block, expr.temp_lifetime, expr, mutability));
291                 block.and(PlaceBuilder::from(temp))
292             }
293         }
294     }
295
296     /// Lower a closure/generator capture by representing it as a field
297     /// access within the desugared closure/generator.
298     ///
299     /// `capture_index` is the index of the capture within the desugared
300     /// closure/generator.
301     fn lower_closure_capture(
302         &mut self,
303         block: BasicBlock,
304         capture_index: usize,
305         upvar_id: ty::UpvarId,
306     )  -> BlockAnd<PlaceBuilder<'tcx>> {
307         let closure_ty = self
308             .hir
309             .typeck_results()
310             .node_type(self.hir.tcx().hir().local_def_id_to_hir_id(upvar_id.closure_expr_id));
311
312         // Captures are represented using fields inside a structure.
313         // This represents accessing self in the closure structure
314         let mut place_builder = PlaceBuilder::from(Local::new(1));
315
316         // In case of Fn/FnMut closures we must deref to access the fields
317         // Generators are considered FnOnce, so we ignore this step for them.
318         if let ty::Closure(_, closure_substs) = closure_ty.kind() {
319             match self.hir.infcx().closure_kind(closure_substs).unwrap() {
320                 ty::ClosureKind::Fn | ty::ClosureKind::FnMut => {
321                     place_builder = place_builder.deref();
322                 }
323                 ty::ClosureKind::FnOnce => {}
324             }
325         }
326
327         let substs = match closure_ty.kind() {
328             ty::Closure(_, substs) => ty::UpvarSubsts::Closure(substs),
329             ty::Generator(_, substs, _) => ty::UpvarSubsts::Generator(substs),
330             _ => bug!("Lowering capture for non-closure type {:?}", closure_ty)
331         };
332
333         // Access the capture by accessing the field within the Closure struct.
334         //
335         // We must have inferred the capture types since we are building MIR, therefore
336         // it's safe to call `upvar_tys` and we can unwrap here because
337         // we know that the capture exists and is the `capture_index`-th capture.
338         let var_ty = substs.upvar_tys().nth(capture_index).unwrap();
339         place_builder = place_builder.field(Field::new(capture_index), var_ty);
340
341         // If the variable is captured via ByRef(Immutable/Mutable) Borrow,
342         // we need to deref it
343         match self.hir.typeck_results.upvar_capture(upvar_id) {
344             ty::UpvarCapture::ByRef(_) => {
345                 block.and(place_builder.deref())
346             }
347             ty::UpvarCapture::ByValue(_) => block.and(place_builder),
348         }
349     }
350
351     /// Lower an index expression
352     ///
353     /// This has two complications;
354     ///
355     /// * We need to do a bounds check.
356     /// * We need to ensure that the bounds check can't be invalidated using an
357     ///   expression like `x[1][{x = y; 2}]`. We use fake borrows here to ensure
358     ///   that this is the case.
359     fn lower_index_expression(
360         &mut self,
361         mut block: BasicBlock,
362         base: ExprRef<'tcx>,
363         index: ExprRef<'tcx>,
364         mutability: Mutability,
365         fake_borrow_temps: Option<&mut Vec<Local>>,
366         temp_lifetime: Option<region::Scope>,
367         expr_span: Span,
368         source_info: SourceInfo,
369     ) -> BlockAnd<PlaceBuilder<'tcx>> {
370         let lhs = self.hir.mirror(base);
371
372         let base_fake_borrow_temps = &mut Vec::new();
373         let is_outermost_index = fake_borrow_temps.is_none();
374         let fake_borrow_temps = fake_borrow_temps.unwrap_or(base_fake_borrow_temps);
375
376         let base_place =
377             unpack!(block = self.expr_as_place(block, lhs, mutability, Some(fake_borrow_temps),));
378
379         // Making this a *fresh* temporary means we do not have to worry about
380         // the index changing later: Nothing will ever change this temporary.
381         // The "retagging" transformation (for Stacked Borrows) relies on this.
382         let idx = unpack!(block = self.as_temp(block, temp_lifetime, index, Mutability::Not,));
383
384         block = self.bounds_check(
385             block,
386             base_place.clone().into_place(self.hir.tcx()),
387             idx,
388             expr_span,
389             source_info,
390         );
391
392         if is_outermost_index {
393             self.read_fake_borrows(block, fake_borrow_temps, source_info)
394         } else {
395             self.add_fake_borrows_of_base(
396                 &base_place,
397                 block,
398                 fake_borrow_temps,
399                 expr_span,
400                 source_info,
401             );
402         }
403
404         block.and(base_place.index(idx))
405     }
406
407     fn bounds_check(
408         &mut self,
409         block: BasicBlock,
410         slice: Place<'tcx>,
411         index: Local,
412         expr_span: Span,
413         source_info: SourceInfo,
414     ) -> BasicBlock {
415         let usize_ty = self.hir.usize_ty();
416         let bool_ty = self.hir.bool_ty();
417         // bounds check:
418         let len = self.temp(usize_ty, expr_span);
419         let lt = self.temp(bool_ty, expr_span);
420
421         // len = len(slice)
422         self.cfg.push_assign(block, source_info, len, Rvalue::Len(slice));
423         // lt = idx < len
424         self.cfg.push_assign(
425             block,
426             source_info,
427             lt,
428             Rvalue::BinaryOp(BinOp::Lt, Operand::Copy(Place::from(index)), Operand::Copy(len)),
429         );
430         let msg = BoundsCheck { len: Operand::Move(len), index: Operand::Copy(Place::from(index)) };
431         // assert!(lt, "...")
432         self.assert(block, Operand::Move(lt), true, msg, expr_span)
433     }
434
435     fn add_fake_borrows_of_base(
436         &mut self,
437         base_place: &PlaceBuilder<'tcx>,
438         block: BasicBlock,
439         fake_borrow_temps: &mut Vec<Local>,
440         expr_span: Span,
441         source_info: SourceInfo,
442     ) {
443         let tcx = self.hir.tcx();
444         let place_ty =
445             Place::ty_from(base_place.local, &base_place.projection, &self.local_decls, tcx);
446         if let ty::Slice(_) = place_ty.ty.kind() {
447             // We need to create fake borrows to ensure that the bounds
448             // check that we just did stays valid. Since we can't assign to
449             // unsized values, we only need to ensure that none of the
450             // pointers in the base place are modified.
451             for (idx, elem) in base_place.projection.iter().enumerate().rev() {
452                 match elem {
453                     ProjectionElem::Deref => {
454                         let fake_borrow_deref_ty = Place::ty_from(
455                             base_place.local,
456                             &base_place.projection[..idx],
457                             &self.local_decls,
458                             tcx,
459                         )
460                         .ty;
461                         let fake_borrow_ty =
462                             tcx.mk_imm_ref(tcx.lifetimes.re_erased, fake_borrow_deref_ty);
463                         let fake_borrow_temp =
464                             self.local_decls.push(LocalDecl::new(fake_borrow_ty, expr_span));
465                         let projection = tcx.intern_place_elems(&base_place.projection[..idx]);
466                         self.cfg.push_assign(
467                             block,
468                             source_info,
469                             fake_borrow_temp.into(),
470                             Rvalue::Ref(
471                                 tcx.lifetimes.re_erased,
472                                 BorrowKind::Shallow,
473                                 Place { local: base_place.local, projection },
474                             ),
475                         );
476                         fake_borrow_temps.push(fake_borrow_temp);
477                     }
478                     ProjectionElem::Index(_) => {
479                         let index_ty = Place::ty_from(
480                             base_place.local,
481                             &base_place.projection[..idx],
482                             &self.local_decls,
483                             tcx,
484                         );
485                         match index_ty.ty.kind() {
486                             // The previous index expression has already
487                             // done any index expressions needed here.
488                             ty::Slice(_) => break,
489                             ty::Array(..) => (),
490                             _ => bug!("unexpected index base"),
491                         }
492                     }
493                     ProjectionElem::Field(..)
494                     | ProjectionElem::Downcast(..)
495                     | ProjectionElem::ConstantIndex { .. }
496                     | ProjectionElem::Subslice { .. } => (),
497                 }
498             }
499         }
500     }
501
502     fn read_fake_borrows(
503         &mut self,
504         bb: BasicBlock,
505         fake_borrow_temps: &mut Vec<Local>,
506         source_info: SourceInfo,
507     ) {
508         // All indexes have been evaluated now, read all of the
509         // fake borrows so that they are live across those index
510         // expressions.
511         for temp in fake_borrow_temps {
512             self.cfg.push_fake_read(bb, source_info, FakeReadCause::ForIndex, Place::from(*temp));
513         }
514     }
515 }