1use std::assert_matches::assert_matches;
4use std::iter;
5
6use rustc_abi::{FIRST_VARIANT, FieldIdx, VariantIdx};
7use rustc_hir::def_id::LocalDefId;
8use rustc_middle::hir::place::{Projection as HirProjection, ProjectionKind as HirProjectionKind};
9use rustc_middle::mir::AssertKind::BoundsCheck;
10use rustc_middle::mir::*;
11use rustc_middle::thir::*;
12use rustc_middle::ty::{self, AdtDef, CanonicalUserTypeAnnotation, Ty, Variance};
13use rustc_middle::{bug, span_bug};
14use rustc_span::Span;
15use tracing::{debug, instrument, trace};
16
17use crate::builder::ForGuard::{OutsideGuard, RefWithinGuard};
18use crate::builder::expr::category::Category;
19use crate::builder::{BlockAnd, BlockAndExtension, Builder, Capture, CaptureMap};
20
21#[derive(Copy, Clone, Debug, PartialEq)]
23pub(crate) enum PlaceBase {
24 Local(Local),
26
27 Upvar {
57 var_hir_id: LocalVarId,
59 closure_def_id: LocalDefId,
61 },
62}
63
64#[derive(Clone, Debug, PartialEq)]
71pub(in crate::builder) struct PlaceBuilder<'tcx> {
72 base: PlaceBase,
73 projection: Vec<PlaceElem<'tcx>>,
74}
75
76fn convert_to_hir_projections_and_truncate_for_capture(
83 mir_projections: &[PlaceElem<'_>],
84) -> Vec<HirProjectionKind> {
85 let mut hir_projections = Vec::new();
86 let mut variant = None;
87
88 for mir_projection in mir_projections {
89 let hir_projection = match mir_projection {
90 ProjectionElem::Deref => HirProjectionKind::Deref,
91 ProjectionElem::Field(field, _) => {
92 let variant = variant.unwrap_or(FIRST_VARIANT);
93 HirProjectionKind::Field(*field, variant)
94 }
95 ProjectionElem::Downcast(.., idx) => {
96 variant = Some(*idx);
102 continue;
103 }
104 ProjectionElem::OpaqueCast(_) | ProjectionElem::Subtype(..) => continue,
106 ProjectionElem::Index(..)
107 | ProjectionElem::ConstantIndex { .. }
108 | ProjectionElem::Subslice { .. }
109 | ProjectionElem::UnwrapUnsafeBinder(_) => {
110 break;
113 }
114 };
115 variant = None;
116 hir_projections.push(hir_projection);
117 }
118
119 hir_projections
120}
121
122fn is_ancestor_or_same_capture(
136 proj_possible_ancestor: &[HirProjectionKind],
137 proj_capture: &[HirProjectionKind],
138) -> bool {
139 if proj_possible_ancestor.len() > proj_capture.len() {
142 return false;
143 }
144
145 iter::zip(proj_possible_ancestor, proj_capture).all(|(a, b)| a == b)
146}
147
148fn find_capture_matching_projections<'a, 'tcx>(
156 upvars: &'a CaptureMap<'tcx>,
157 var_hir_id: LocalVarId,
158 projections: &[PlaceElem<'tcx>],
159) -> Option<(usize, &'a Capture<'tcx>)> {
160 let hir_projections = convert_to_hir_projections_and_truncate_for_capture(projections);
161
162 upvars.get_by_key_enumerated(var_hir_id.0).find(|(_, capture)| {
163 let possible_ancestor_proj_kinds: Vec<_> =
164 capture.captured_place.place.projections.iter().map(|proj| proj.kind).collect();
165 is_ancestor_or_same_capture(&possible_ancestor_proj_kinds, &hir_projections)
166 })
167}
168
169#[instrument(level = "trace", skip(cx), ret)]
172fn to_upvars_resolved_place_builder<'tcx>(
173 cx: &Builder<'_, 'tcx>,
174 var_hir_id: LocalVarId,
175 closure_def_id: LocalDefId,
176 projection: &[PlaceElem<'tcx>],
177) -> Option<PlaceBuilder<'tcx>> {
178 let Some((capture_index, capture)) =
179 find_capture_matching_projections(&cx.upvars, var_hir_id, projection)
180 else {
181 let closure_span = cx.tcx.def_span(closure_def_id);
182 if !enable_precise_capture(closure_span) {
183 bug!(
184 "No associated capture found for {:?}[{:#?}] even though \
185 capture_disjoint_fields isn't enabled",
186 var_hir_id,
187 projection
188 )
189 } else {
190 debug!("No associated capture found for {:?}[{:#?}]", var_hir_id, projection,);
191 }
192 return None;
193 };
194
195 let capture_info = &cx.upvars[capture_index];
197
198 let mut upvar_resolved_place_builder = PlaceBuilder::from(capture_info.use_place);
199
200 trace!(?capture.captured_place, ?projection);
203 let remaining_projections = strip_prefix(
204 capture.captured_place.place.base_ty,
205 projection,
206 &capture.captured_place.place.projections,
207 );
208 upvar_resolved_place_builder.projection.extend(remaining_projections);
209
210 Some(upvar_resolved_place_builder)
211}
212
213fn strip_prefix<'a, 'tcx>(
220 mut base_ty: Ty<'tcx>,
221 projections: &'a [PlaceElem<'tcx>],
222 prefix_projections: &[HirProjection<'tcx>],
223) -> impl Iterator<Item = PlaceElem<'tcx>> + 'a {
224 let mut iter = projections
225 .iter()
226 .copied()
227 .filter(|elem| !matches!(elem, ProjectionElem::OpaqueCast(..)));
229 for projection in prefix_projections {
230 match projection.kind {
231 HirProjectionKind::Deref => {
232 assert_matches!(iter.next(), Some(ProjectionElem::Deref));
233 }
234 HirProjectionKind::Field(..) => {
235 if base_ty.is_enum() {
236 assert_matches!(iter.next(), Some(ProjectionElem::Downcast(..)));
237 }
238 assert_matches!(iter.next(), Some(ProjectionElem::Field(..)));
239 }
240 HirProjectionKind::OpaqueCast => {
241 assert_matches!(iter.next(), Some(ProjectionElem::OpaqueCast(..)));
242 }
243 HirProjectionKind::Index | HirProjectionKind::Subslice => {
244 bug!("unexpected projection kind: {:?}", projection);
245 }
246 }
247 base_ty = projection.ty;
248 }
249 iter
250}
251
252impl<'tcx> PlaceBuilder<'tcx> {
253 pub(in crate::builder) fn to_place(&self, cx: &Builder<'_, 'tcx>) -> Place<'tcx> {
254 self.try_to_place(cx).unwrap_or_else(|| match self.base {
255 PlaceBase::Local(local) => span_bug!(
256 cx.local_decls[local].source_info.span,
257 "could not resolve local: {local:#?} + {:?}",
258 self.projection
259 ),
260 PlaceBase::Upvar { var_hir_id, closure_def_id: _ } => span_bug!(
261 cx.tcx.hir().span(var_hir_id.0),
262 "could not resolve upvar: {var_hir_id:?} + {:?}",
263 self.projection
264 ),
265 })
266 }
267
268 pub(in crate::builder) fn try_to_place(&self, cx: &Builder<'_, 'tcx>) -> Option<Place<'tcx>> {
270 let resolved = self.resolve_upvar(cx);
271 let builder = resolved.as_ref().unwrap_or(self);
272 let PlaceBase::Local(local) = builder.base else { return None };
273 let projection = cx.tcx.mk_place_elems(&builder.projection);
274 Some(Place { local, projection })
275 }
276
277 pub(in crate::builder) fn resolve_upvar(
288 &self,
289 cx: &Builder<'_, 'tcx>,
290 ) -> Option<PlaceBuilder<'tcx>> {
291 let PlaceBase::Upvar { var_hir_id, closure_def_id } = self.base else {
292 return None;
293 };
294 to_upvars_resolved_place_builder(cx, var_hir_id, closure_def_id, &self.projection)
295 }
296
297 pub(crate) fn base(&self) -> PlaceBase {
298 self.base
299 }
300
301 pub(crate) fn projection(&self) -> &[PlaceElem<'tcx>] {
302 &self.projection
303 }
304
305 pub(crate) fn field(self, f: FieldIdx, ty: Ty<'tcx>) -> Self {
306 self.project(PlaceElem::Field(f, ty))
307 }
308
309 pub(crate) fn deref(self) -> Self {
310 self.project(PlaceElem::Deref)
311 }
312
313 pub(crate) fn downcast(self, adt_def: AdtDef<'tcx>, variant_index: VariantIdx) -> Self {
314 self.project(PlaceElem::Downcast(Some(adt_def.variant(variant_index).name), variant_index))
315 }
316
317 fn index(self, index: Local) -> Self {
318 self.project(PlaceElem::Index(index))
319 }
320
321 pub(crate) fn project(mut self, elem: PlaceElem<'tcx>) -> Self {
322 self.projection.push(elem);
323 self
324 }
325
326 pub(crate) fn clone_project(&self, elem: PlaceElem<'tcx>) -> Self {
328 Self {
329 base: self.base,
330 projection: Vec::from_iter(self.projection.iter().copied().chain([elem])),
331 }
332 }
333}
334
335impl<'tcx> From<Local> for PlaceBuilder<'tcx> {
336 fn from(local: Local) -> Self {
337 Self { base: PlaceBase::Local(local), projection: Vec::new() }
338 }
339}
340
341impl<'tcx> From<PlaceBase> for PlaceBuilder<'tcx> {
342 fn from(base: PlaceBase) -> Self {
343 Self { base, projection: Vec::new() }
344 }
345}
346
347impl<'tcx> From<Place<'tcx>> for PlaceBuilder<'tcx> {
348 fn from(p: Place<'tcx>) -> Self {
349 Self { base: PlaceBase::Local(p.local), projection: p.projection.to_vec() }
350 }
351}
352
353impl<'a, 'tcx> Builder<'a, 'tcx> {
354 pub(crate) fn as_place(
367 &mut self,
368 mut block: BasicBlock,
369 expr_id: ExprId,
370 ) -> BlockAnd<Place<'tcx>> {
371 let place_builder = unpack!(block = self.as_place_builder(block, expr_id));
372 block.and(place_builder.to_place(self))
373 }
374
375 pub(crate) fn as_place_builder(
378 &mut self,
379 block: BasicBlock,
380 expr_id: ExprId,
381 ) -> BlockAnd<PlaceBuilder<'tcx>> {
382 self.expr_as_place(block, expr_id, Mutability::Mut, None)
383 }
384
385 pub(crate) fn as_read_only_place(
391 &mut self,
392 mut block: BasicBlock,
393 expr_id: ExprId,
394 ) -> BlockAnd<Place<'tcx>> {
395 let place_builder = unpack!(block = self.as_read_only_place_builder(block, expr_id));
396 block.and(place_builder.to_place(self))
397 }
398
399 fn as_read_only_place_builder(
406 &mut self,
407 block: BasicBlock,
408 expr_id: ExprId,
409 ) -> BlockAnd<PlaceBuilder<'tcx>> {
410 self.expr_as_place(block, expr_id, Mutability::Not, None)
411 }
412
413 fn expr_as_place(
414 &mut self,
415 mut block: BasicBlock,
416 expr_id: ExprId,
417 mutability: Mutability,
418 fake_borrow_temps: Option<&mut Vec<Local>>,
419 ) -> BlockAnd<PlaceBuilder<'tcx>> {
420 let expr = &self.thir[expr_id];
421 debug!("expr_as_place(block={:?}, expr={:?}, mutability={:?})", block, expr, mutability);
422
423 let this = self;
424 let expr_span = expr.span;
425 let source_info = this.source_info(expr_span);
426 match expr.kind {
427 ExprKind::Scope { region_scope, lint_level, value } => {
428 this.in_scope((region_scope, source_info), lint_level, |this| {
429 this.expr_as_place(block, value, mutability, fake_borrow_temps)
430 })
431 }
432 ExprKind::Field { lhs, variant_index, name } => {
433 let lhs_expr = &this.thir[lhs];
434 let mut place_builder =
435 unpack!(block = this.expr_as_place(block, lhs, mutability, fake_borrow_temps,));
436 if let ty::Adt(adt_def, _) = lhs_expr.ty.kind() {
437 if adt_def.is_enum() {
438 place_builder = place_builder.downcast(*adt_def, variant_index);
439 }
440 }
441 block.and(place_builder.field(name, expr.ty))
442 }
443 ExprKind::Deref { arg } => {
444 let place_builder =
445 unpack!(block = this.expr_as_place(block, arg, mutability, fake_borrow_temps,));
446 block.and(place_builder.deref())
447 }
448 ExprKind::Index { lhs, index } => this.lower_index_expression(
449 block,
450 lhs,
451 index,
452 mutability,
453 fake_borrow_temps,
454 expr.temp_lifetime,
455 expr_span,
456 source_info,
457 ),
458 ExprKind::UpvarRef { closure_def_id, var_hir_id } => {
459 this.lower_captured_upvar(block, closure_def_id.expect_local(), var_hir_id)
460 }
461
462 ExprKind::VarRef { id } => {
463 let place_builder = if this.is_bound_var_in_guard(id) {
464 let index = this.var_local_id(id, RefWithinGuard);
465 PlaceBuilder::from(index).deref()
466 } else {
467 let index = this.var_local_id(id, OutsideGuard);
468 PlaceBuilder::from(index)
469 };
470 block.and(place_builder)
471 }
472
473 ExprKind::PlaceTypeAscription { source, ref user_ty, user_ty_span } => {
474 let place_builder = unpack!(
475 block = this.expr_as_place(block, source, mutability, fake_borrow_temps,)
476 );
477 if let Some(user_ty) = user_ty {
478 let ty_source_info = this.source_info(user_ty_span);
479 let annotation_index =
480 this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
481 span: user_ty_span,
482 user_ty: user_ty.clone(),
483 inferred_ty: expr.ty,
484 });
485
486 let place = place_builder.to_place(this);
487 this.cfg.push(
488 block,
489 Statement {
490 source_info: ty_source_info,
491 kind: StatementKind::AscribeUserType(
492 Box::new((
493 place,
494 UserTypeProjection { base: annotation_index, projs: vec![] },
495 )),
496 Variance::Invariant,
497 ),
498 },
499 );
500 }
501 block.and(place_builder)
502 }
503 ExprKind::ValueTypeAscription { source, ref user_ty, user_ty_span } => {
504 let source_expr = &this.thir[source];
505 let temp = unpack!(
506 block = this.as_temp(block, source_expr.temp_lifetime, source, mutability)
507 );
508 if let Some(user_ty) = user_ty {
509 let ty_source_info = this.source_info(user_ty_span);
510 let annotation_index =
511 this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
512 span: user_ty_span,
513 user_ty: user_ty.clone(),
514 inferred_ty: expr.ty,
515 });
516 this.cfg.push(
517 block,
518 Statement {
519 source_info: ty_source_info,
520 kind: StatementKind::AscribeUserType(
521 Box::new((
522 Place::from(temp),
523 UserTypeProjection { base: annotation_index, projs: vec![] },
524 )),
525 Variance::Invariant,
526 ),
527 },
528 );
529 }
530 block.and(PlaceBuilder::from(temp))
531 }
532
533 ExprKind::PlaceUnwrapUnsafeBinder { source } => {
534 let place_builder = unpack!(
535 block = this.expr_as_place(block, source, mutability, fake_borrow_temps,)
536 );
537 block.and(place_builder.project(PlaceElem::UnwrapUnsafeBinder(expr.ty)))
538 }
539 ExprKind::ValueUnwrapUnsafeBinder { source } => {
540 let source_expr = &this.thir[source];
541 let temp = unpack!(
542 block = this.as_temp(block, source_expr.temp_lifetime, source, mutability)
543 );
544 block.and(PlaceBuilder::from(temp).project(PlaceElem::UnwrapUnsafeBinder(expr.ty)))
545 }
546
547 ExprKind::Array { .. }
548 | ExprKind::Tuple { .. }
549 | ExprKind::Adt { .. }
550 | ExprKind::Closure { .. }
551 | ExprKind::Unary { .. }
552 | ExprKind::Binary { .. }
553 | ExprKind::LogicalOp { .. }
554 | ExprKind::Box { .. }
555 | ExprKind::Cast { .. }
556 | ExprKind::Use { .. }
557 | ExprKind::NeverToAny { .. }
558 | ExprKind::PointerCoercion { .. }
559 | ExprKind::Repeat { .. }
560 | ExprKind::Borrow { .. }
561 | ExprKind::RawBorrow { .. }
562 | ExprKind::Match { .. }
563 | ExprKind::If { .. }
564 | ExprKind::Loop { .. }
565 | ExprKind::Block { .. }
566 | ExprKind::Let { .. }
567 | ExprKind::Assign { .. }
568 | ExprKind::AssignOp { .. }
569 | ExprKind::Break { .. }
570 | ExprKind::Continue { .. }
571 | ExprKind::Return { .. }
572 | ExprKind::Become { .. }
573 | ExprKind::Literal { .. }
574 | ExprKind::NamedConst { .. }
575 | ExprKind::NonHirLiteral { .. }
576 | ExprKind::ZstLiteral { .. }
577 | ExprKind::ConstParam { .. }
578 | ExprKind::ConstBlock { .. }
579 | ExprKind::StaticRef { .. }
580 | ExprKind::InlineAsm { .. }
581 | ExprKind::OffsetOf { .. }
582 | ExprKind::Yield { .. }
583 | ExprKind::ThreadLocalRef(_)
584 | ExprKind::Call { .. }
585 | ExprKind::WrapUnsafeBinder { .. } => {
586 debug_assert!(!matches!(Category::of(&expr.kind), Some(Category::Place)));
588 let temp =
589 unpack!(block = this.as_temp(block, expr.temp_lifetime, expr_id, mutability));
590 block.and(PlaceBuilder::from(temp))
591 }
592 }
593 }
594
595 fn lower_captured_upvar(
599 &mut self,
600 block: BasicBlock,
601 closure_def_id: LocalDefId,
602 var_hir_id: LocalVarId,
603 ) -> BlockAnd<PlaceBuilder<'tcx>> {
604 block.and(PlaceBuilder::from(PlaceBase::Upvar { var_hir_id, closure_def_id }))
605 }
606
607 fn lower_index_expression(
616 &mut self,
617 mut block: BasicBlock,
618 base: ExprId,
619 index: ExprId,
620 mutability: Mutability,
621 fake_borrow_temps: Option<&mut Vec<Local>>,
622 temp_lifetime: TempLifetime,
623 expr_span: Span,
624 source_info: SourceInfo,
625 ) -> BlockAnd<PlaceBuilder<'tcx>> {
626 let base_fake_borrow_temps = &mut Vec::new();
627 let is_outermost_index = fake_borrow_temps.is_none();
628 let fake_borrow_temps = fake_borrow_temps.unwrap_or(base_fake_borrow_temps);
629
630 let base_place =
631 unpack!(block = self.expr_as_place(block, base, mutability, Some(fake_borrow_temps),));
632
633 let idx = unpack!(block = self.as_temp(block, temp_lifetime, index, Mutability::Not));
637
638 block = self.bounds_check(block, &base_place, idx, expr_span, source_info);
639
640 if is_outermost_index {
641 self.read_fake_borrows(block, fake_borrow_temps, source_info)
642 } else {
643 self.add_fake_borrows_of_base(
644 base_place.to_place(self),
645 block,
646 fake_borrow_temps,
647 expr_span,
648 source_info,
649 );
650 }
651
652 block.and(base_place.index(idx))
653 }
654
655 fn len_of_slice_or_array(
661 &mut self,
662 block: BasicBlock,
663 place: Place<'tcx>,
664 span: Span,
665 source_info: SourceInfo,
666 ) -> Operand<'tcx> {
667 let place_ty = place.ty(&self.local_decls, self.tcx).ty;
668 match place_ty.kind() {
669 ty::Array(_elem_ty, len_const) => {
670 self.cfg.push_fake_read(block, source_info, FakeReadCause::ForIndex, place);
676 let const_ = Const::Ty(self.tcx.types.usize, *len_const);
677 Operand::Constant(Box::new(ConstOperand { span, user_ty: None, const_ }))
678 }
679 ty::Slice(_elem_ty) => {
680 let ptr_or_ref = if let [PlaceElem::Deref] = place.projection[..]
681 && let local_ty = self.local_decls[place.local].ty
682 && local_ty.is_trivially_pure_clone_copy()
683 {
684 Operand::Copy(Place::from(place.local))
690 } else {
691 let ptr_ty = Ty::new_imm_ptr(self.tcx, place_ty);
692 let slice_ptr = self.temp(ptr_ty, span);
693 self.cfg.push_assign(
694 block,
695 source_info,
696 slice_ptr,
697 Rvalue::RawPtr(RawPtrKind::FakeForPtrMetadata, place),
698 );
699 Operand::Move(slice_ptr)
700 };
701
702 let len = self.temp(self.tcx.types.usize, span);
703 self.cfg.push_assign(
704 block,
705 source_info,
706 len,
707 Rvalue::UnaryOp(UnOp::PtrMetadata, ptr_or_ref),
708 );
709
710 Operand::Move(len)
711 }
712 _ => {
713 span_bug!(span, "len called on place of type {place_ty:?}")
714 }
715 }
716 }
717
718 fn bounds_check(
719 &mut self,
720 block: BasicBlock,
721 slice: &PlaceBuilder<'tcx>,
722 index: Local,
723 expr_span: Span,
724 source_info: SourceInfo,
725 ) -> BasicBlock {
726 let slice = slice.to_place(self);
727
728 let len = self.len_of_slice_or_array(block, slice, expr_span, source_info);
730
731 let bool_ty = self.tcx.types.bool;
733 let lt = self.temp(bool_ty, expr_span);
734 self.cfg.push_assign(
735 block,
736 source_info,
737 lt,
738 Rvalue::BinaryOp(
739 BinOp::Lt,
740 Box::new((Operand::Copy(Place::from(index)), len.to_copy())),
741 ),
742 );
743 let msg = BoundsCheck { len, index: Operand::Copy(Place::from(index)) };
744
745 self.assert(block, Operand::Move(lt), true, msg, expr_span)
747 }
748
749 fn add_fake_borrows_of_base(
750 &mut self,
751 base_place: Place<'tcx>,
752 block: BasicBlock,
753 fake_borrow_temps: &mut Vec<Local>,
754 expr_span: Span,
755 source_info: SourceInfo,
756 ) {
757 let tcx = self.tcx;
758
759 let place_ty = base_place.ty(&self.local_decls, tcx);
760 if let ty::Slice(_) = place_ty.ty.kind() {
761 for (base_place, elem) in base_place.iter_projections().rev() {
766 match elem {
767 ProjectionElem::Deref => {
768 let fake_borrow_deref_ty = base_place.ty(&self.local_decls, tcx).ty;
769 let fake_borrow_ty =
770 Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, fake_borrow_deref_ty);
771 let fake_borrow_temp =
772 self.local_decls.push(LocalDecl::new(fake_borrow_ty, expr_span));
773 let projection = tcx.mk_place_elems(base_place.projection);
774 self.cfg.push_assign(
775 block,
776 source_info,
777 fake_borrow_temp.into(),
778 Rvalue::Ref(
779 tcx.lifetimes.re_erased,
780 BorrowKind::Fake(FakeBorrowKind::Shallow),
781 Place { local: base_place.local, projection },
782 ),
783 );
784 fake_borrow_temps.push(fake_borrow_temp);
785 }
786 ProjectionElem::Index(_) => {
787 let index_ty = base_place.ty(&self.local_decls, tcx);
788 match index_ty.ty.kind() {
789 ty::Slice(_) => break,
792 ty::Array(..) => (),
793 _ => bug!("unexpected index base"),
794 }
795 }
796 ProjectionElem::Field(..)
797 | ProjectionElem::Downcast(..)
798 | ProjectionElem::OpaqueCast(..)
799 | ProjectionElem::Subtype(..)
800 | ProjectionElem::ConstantIndex { .. }
801 | ProjectionElem::Subslice { .. }
802 | ProjectionElem::UnwrapUnsafeBinder(_) => (),
803 }
804 }
805 }
806 }
807
808 fn read_fake_borrows(
809 &mut self,
810 bb: BasicBlock,
811 fake_borrow_temps: &mut Vec<Local>,
812 source_info: SourceInfo,
813 ) {
814 for temp in fake_borrow_temps {
818 self.cfg.push_fake_read(bb, source_info, FakeReadCause::ForIndex, Place::from(*temp));
819 }
820 }
821}
822
823fn enable_precise_capture(closure_span: Span) -> bool {
825 closure_span.at_least_rust_2021()
826}