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