1 //! See docs in build/expr/mod.rs
3 use crate::build::expr::category::Category;
4 use crate::build::ForGuard::{OutsideGuard, RefWithinGuard};
5 use crate::build::{BlockAnd, BlockAndExtension, Builder};
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};
13 use rustc_index::vec::Idx;
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.
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`.
22 struct PlaceBuilder<'tcx> {
24 projection: Vec<PlaceElem<'tcx>>,
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) }
32 fn field(self, f: Field, ty: Ty<'tcx>) -> Self {
33 self.project(PlaceElem::Field(f, ty))
36 fn deref(self) -> Self {
37 self.project(PlaceElem::Deref)
40 fn index(self, index: Local) -> Self {
41 self.project(PlaceElem::Index(index))
44 fn project(mut self, elem: PlaceElem<'tcx>) -> Self {
45 self.projection.push(elem);
50 impl<'tcx> From<Local> for PlaceBuilder<'tcx> {
51 fn from(local: Local) -> Self {
52 Self { local, projection: Vec::new() }
56 impl<'a, 'tcx> Builder<'a, 'tcx> {
57 /// Compile `expr`, yielding a place that we can move from etc.
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.
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
69 crate fn as_place<M>(&mut self, mut block: BasicBlock, expr: M) -> BlockAnd<Place<'tcx>>
71 M: Mirror<'tcx, Output = Expr<'tcx>>,
73 let place_builder = unpack!(block = self.as_place_builder(block, expr));
74 block.and(place_builder.into_place(self.hir.tcx()))
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>>
81 M: Mirror<'tcx, Output = Expr<'tcx>>,
83 let expr = self.hir.mirror(expr);
84 self.expr_as_place(block, expr, Mutability::Mut, None)
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>(
94 mut block: BasicBlock,
96 ) -> BlockAnd<Place<'tcx>>
98 M: Mirror<'tcx, Output = Expr<'tcx>>,
100 let place_builder = unpack!(block = self.as_read_only_place_builder(block, expr));
101 block.and(place_builder.into_place(self.hir.tcx()))
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>(
114 ) -> BlockAnd<PlaceBuilder<'tcx>>
116 M: Mirror<'tcx, Output = Expr<'tcx>>,
118 let expr = self.hir.mirror(expr);
119 self.expr_as_place(block, expr, Mutability::Not, None)
124 mut block: BasicBlock,
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);
132 let expr_span = expr.span;
133 let source_info = this.source_info(expr_span);
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)
141 ExprKind::Field { lhs, name } => {
142 let lhs = this.hir.mirror(lhs);
144 unpack!(block = this.expr_as_place(block, lhs, mutability, fake_borrow_temps,));
145 block.and(place_builder.field(name, expr.ty))
147 ExprKind::Deref { arg } => {
148 let arg = this.hir.mirror(arg);
150 unpack!(block = this.expr_as_place(block, arg, mutability, fake_borrow_temps,));
151 block.and(place_builder.deref())
153 ExprKind::Index { lhs, index } => this.lower_index_expression(
163 ExprKind::UpvarRef { closure_def_id, var_hir_id } => {
168 .get(&closure_def_id)
169 .and_then(|captures| captures.get_full(&var_hir_id));
171 if capture.is_none() {
172 if !this.hir.tcx().features().capture_disjoint_fields {
174 "No associated capture found for {:?} even though \
175 capture_disjoint_fields isn't enabled",
179 // FIXME(project-rfc-2229#24): Handle this case properly
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)
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()
192 let index = this.var_local_id(id, OutsideGuard);
193 PlaceBuilder::from(index)
195 block.and(place_builder)
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,)
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,
208 inferred_ty: expr.ty,
211 let place = place_builder.clone().into_place(this.hir.tcx());
216 kind: StatementKind::AscribeUserType(
219 UserTypeProjection { base: annotation_index, projs: vec![] },
226 block.and(place_builder)
228 ExprKind::ValueTypeAscription { source, user_ty } => {
229 let source = this.hir.mirror(source);
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,
237 inferred_ty: expr.ty,
243 kind: StatementKind::AscribeUserType(
246 UserTypeProjection { base: annotation_index, projs: vec![] },
253 block.and(PlaceBuilder::from(temp))
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)));
290 unpack!(block = this.as_temp(block, expr.temp_lifetime, expr, mutability));
291 block.and(PlaceBuilder::from(temp))
296 /// Lower a closure/generator capture by representing it as a field
297 /// access within the desugared closure/generator.
299 /// `capture_index` is the index of the capture within the desugared
300 /// closure/generator.
301 fn lower_closure_capture(
304 capture_index: usize,
305 upvar_id: ty::UpvarId,
306 ) -> BlockAnd<PlaceBuilder<'tcx>> {
307 let closure_ty = self
310 .node_type(self.hir.tcx().hir().local_def_id_to_hir_id(upvar_id.closure_expr_id));
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));
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();
323 ty::ClosureKind::FnOnce => {}
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)
333 // Access the capture by accessing the field within the Closure struct.
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);
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())
347 ty::UpvarCapture::ByValue(_) => block.and(place_builder),
351 /// Lower an index expression
353 /// This has two complications;
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(
361 mut block: BasicBlock,
363 index: ExprRef<'tcx>,
364 mutability: Mutability,
365 fake_borrow_temps: Option<&mut Vec<Local>>,
366 temp_lifetime: Option<region::Scope>,
368 source_info: SourceInfo,
369 ) -> BlockAnd<PlaceBuilder<'tcx>> {
370 let lhs = self.hir.mirror(base);
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);
377 unpack!(block = self.expr_as_place(block, lhs, mutability, Some(fake_borrow_temps),));
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,));
384 block = self.bounds_check(
386 base_place.clone().into_place(self.hir.tcx()),
392 if is_outermost_index {
393 self.read_fake_borrows(block, fake_borrow_temps, source_info)
395 self.add_fake_borrows_of_base(
404 block.and(base_place.index(idx))
413 source_info: SourceInfo,
415 let usize_ty = self.hir.usize_ty();
416 let bool_ty = self.hir.bool_ty();
418 let len = self.temp(usize_ty, expr_span);
419 let lt = self.temp(bool_ty, expr_span);
422 self.cfg.push_assign(block, source_info, len, Rvalue::Len(slice));
424 self.cfg.push_assign(
428 Rvalue::BinaryOp(BinOp::Lt, Operand::Copy(Place::from(index)), Operand::Copy(len)),
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)
435 fn add_fake_borrows_of_base(
437 base_place: &PlaceBuilder<'tcx>,
439 fake_borrow_temps: &mut Vec<Local>,
441 source_info: SourceInfo,
443 let tcx = self.hir.tcx();
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() {
453 ProjectionElem::Deref => {
454 let fake_borrow_deref_ty = Place::ty_from(
456 &base_place.projection[..idx],
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(
469 fake_borrow_temp.into(),
471 tcx.lifetimes.re_erased,
473 Place { local: base_place.local, projection },
476 fake_borrow_temps.push(fake_borrow_temp);
478 ProjectionElem::Index(_) => {
479 let index_ty = Place::ty_from(
481 &base_place.projection[..idx],
485 match index_ty.ty.kind() {
486 // The previous index expression has already
487 // done any index expressions needed here.
488 ty::Slice(_) => break,
490 _ => bug!("unexpected index base"),
493 ProjectionElem::Field(..)
494 | ProjectionElem::Downcast(..)
495 | ProjectionElem::ConstantIndex { .. }
496 | ProjectionElem::Subslice { .. } => (),
502 fn read_fake_borrows(
505 fake_borrow_temps: &mut Vec<Local>,
506 source_info: SourceInfo,
508 // All indexes have been evaluated now, read all of the
509 // fake borrows so that they are live across those index
511 for temp in fake_borrow_temps {
512 self.cfg.push_fake_read(bb, source_info, FakeReadCause::ForIndex, Place::from(*temp));