]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/matches/mod.rs
Remove useless references/dereferences
[rust.git] / compiler / rustc_mir_build / src / build / matches / mod.rs
1 //! Code related to match expressions. These are sufficiently complex to
2 //! warrant their own module and submodules. :) This main module includes the
3 //! high-level algorithm, the submodules contain the details.
4 //!
5 //! This also includes code for pattern bindings in `let` statements and
6 //! function parameters.
7
8 use crate::build::scope::DropKind;
9 use crate::build::ForGuard::{self, OutsideGuard, RefWithinGuard};
10 use crate::build::{BlockAnd, BlockAndExtension, Builder};
11 use crate::build::{GuardFrame, GuardFrameLocal, LocalsForNode};
12 use crate::thir::{self, *};
13 use rustc_data_structures::{
14     fx::{FxHashSet, FxIndexMap},
15     stack::ensure_sufficient_stack,
16 };
17 use rustc_hir::HirId;
18 use rustc_index::bit_set::BitSet;
19 use rustc_middle::middle::region;
20 use rustc_middle::mir::*;
21 use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, Ty};
22 use rustc_span::symbol::Symbol;
23 use rustc_span::Span;
24 use rustc_target::abi::VariantIdx;
25 use smallvec::{smallvec, SmallVec};
26
27 // helper functions, broken out by category:
28 mod simplify;
29 mod test;
30 mod util;
31
32 use std::borrow::Borrow;
33 use std::convert::TryFrom;
34 use std::mem;
35
36 impl<'a, 'tcx> Builder<'a, 'tcx> {
37     /// Generates MIR for a `match` expression.
38     ///
39     /// The MIR that we generate for a match looks like this.
40     ///
41     /// ```text
42     /// [ 0. Pre-match ]
43     ///        |
44     /// [ 1. Evaluate Scrutinee (expression being matched on) ]
45     /// [ (fake read of scrutinee) ]
46     ///        |
47     /// [ 2. Decision tree -- check discriminants ] <--------+
48     ///        |                                             |
49     ///        | (once a specific arm is chosen)             |
50     ///        |                                             |
51     /// [pre_binding_block]                           [otherwise_block]
52     ///        |                                             |
53     /// [ 3. Create "guard bindings" for arm ]               |
54     /// [ (create fake borrows) ]                            |
55     ///        |                                             |
56     /// [ 4. Execute guard code ]                            |
57     /// [ (read fake borrows) ] --(guard is false)-----------+
58     ///        |
59     ///        | (guard results in true)
60     ///        |
61     /// [ 5. Create real bindings and execute arm ]
62     ///        |
63     /// [ Exit match ]
64     /// ```
65     ///
66     /// All of the different arms have been stacked on top of each other to
67     /// simplify the diagram. For an arm with no guard the blocks marked 3 and
68     /// 4 and the fake borrows are omitted.
69     ///
70     /// We generate MIR in the following steps:
71     ///
72     /// 1. Evaluate the scrutinee and add the fake read of it ([Builder::lower_scrutinee]).
73     /// 2. Create the decision tree ([Builder::lower_match_tree]).
74     /// 3. Determine the fake borrows that are needed from the places that were
75     ///    matched against and create the required temporaries for them
76     ///    ([Builder::calculate_fake_borrows]).
77     /// 4. Create everything else: the guards and the arms ([Builder::lower_match_arms]).
78     ///
79     /// ## False edges
80     ///
81     /// We don't want to have the exact structure of the decision tree be
82     /// visible through borrow checking. False edges ensure that the CFG as
83     /// seen by borrow checking doesn't encode this. False edges are added:
84     ///
85     /// * From each pre-binding block to the next pre-binding block.
86     /// * From each otherwise block to the next pre-binding block.
87     crate fn match_expr(
88         &mut self,
89         destination: Place<'tcx>,
90         span: Span,
91         mut block: BasicBlock,
92         scrutinee: &Expr<'_, 'tcx>,
93         arms: &[Arm<'_, 'tcx>],
94     ) -> BlockAnd<()> {
95         let scrutinee_span = scrutinee.span;
96         let scrutinee_place =
97             unpack!(block = self.lower_scrutinee(block, scrutinee, scrutinee_span,));
98
99         let mut arm_candidates = self.create_match_candidates(scrutinee_place, &arms);
100
101         let match_has_guard = arms.iter().any(|arm| arm.guard.is_some());
102         let mut candidates =
103             arm_candidates.iter_mut().map(|(_, candidate)| candidate).collect::<Vec<_>>();
104
105         let fake_borrow_temps =
106             self.lower_match_tree(block, scrutinee_span, match_has_guard, &mut candidates);
107
108         self.lower_match_arms(
109             destination,
110             scrutinee_place,
111             scrutinee_span,
112             arm_candidates,
113             self.source_info(span),
114             fake_borrow_temps,
115         )
116     }
117
118     /// Evaluate the scrutinee and add the fake read of it.
119     fn lower_scrutinee(
120         &mut self,
121         mut block: BasicBlock,
122         scrutinee: &Expr<'_, 'tcx>,
123         scrutinee_span: Span,
124     ) -> BlockAnd<Place<'tcx>> {
125         let scrutinee_place = unpack!(block = self.as_place(block, scrutinee));
126         // Matching on a `scrutinee_place` with an uninhabited type doesn't
127         // generate any memory reads by itself, and so if the place "expression"
128         // contains unsafe operations like raw pointer dereferences or union
129         // field projections, we wouldn't know to require an `unsafe` block
130         // around a `match` equivalent to `std::intrinsics::unreachable()`.
131         // See issue #47412 for this hole being discovered in the wild.
132         //
133         // HACK(eddyb) Work around the above issue by adding a dummy inspection
134         // of `scrutinee_place`, specifically by applying `ReadForMatch`.
135         //
136         // NOTE: ReadForMatch also checks that the scrutinee is initialized.
137         // This is currently needed to not allow matching on an uninitialized,
138         // uninhabited value. If we get never patterns, those will check that
139         // the place is initialized, and so this read would only be used to
140         // check safety.
141         let cause_matched_place = FakeReadCause::ForMatchedPlace;
142         let source_info = self.source_info(scrutinee_span);
143         self.cfg.push_fake_read(block, source_info, cause_matched_place, scrutinee_place);
144
145         block.and(scrutinee_place)
146     }
147
148     /// Create the initial `Candidate`s for a `match` expression.
149     fn create_match_candidates<'pat>(
150         &mut self,
151         scrutinee: Place<'tcx>,
152         arms: &'pat [Arm<'pat, 'tcx>],
153     ) -> Vec<(&'pat Arm<'pat, 'tcx>, Candidate<'pat, 'tcx>)> {
154         // Assemble a list of candidates: there is one candidate per pattern,
155         // which means there may be more than one candidate *per arm*.
156         arms.iter()
157             .map(|arm| {
158                 let arm_has_guard = arm.guard.is_some();
159                 let arm_candidate = Candidate::new(scrutinee, &arm.pattern, arm_has_guard);
160                 (arm, arm_candidate)
161             })
162             .collect()
163     }
164
165     /// Create the decision tree for the match expression, starting from `block`.
166     ///
167     /// Modifies `candidates` to store the bindings and type ascriptions for
168     /// that candidate.
169     ///
170     /// Returns the places that need fake borrows because we bind or test them.
171     fn lower_match_tree<'pat>(
172         &mut self,
173         block: BasicBlock,
174         scrutinee_span: Span,
175         match_has_guard: bool,
176         candidates: &mut [&mut Candidate<'pat, 'tcx>],
177     ) -> Vec<(Place<'tcx>, Local)> {
178         // The set of places that we are creating fake borrows of. If there are
179         // no match guards then we don't need any fake borrows, so don't track
180         // them.
181         let mut fake_borrows = if match_has_guard { Some(FxHashSet::default()) } else { None };
182
183         let mut otherwise = None;
184
185         // This will generate code to test scrutinee_place and
186         // branch to the appropriate arm block
187         self.match_candidates(scrutinee_span, block, &mut otherwise, candidates, &mut fake_borrows);
188
189         if let Some(otherwise_block) = otherwise {
190             // See the doc comment on `match_candidates` for why we may have an
191             // otherwise block. Match checking will ensure this is actually
192             // unreachable.
193             let source_info = self.source_info(scrutinee_span);
194             self.cfg.terminate(otherwise_block, source_info, TerminatorKind::Unreachable);
195         }
196
197         // Link each leaf candidate to the `pre_binding_block` of the next one.
198         let mut previous_candidate: Option<&mut Candidate<'_, '_>> = None;
199
200         for candidate in candidates {
201             candidate.visit_leaves(|leaf_candidate| {
202                 if let Some(ref mut prev) = previous_candidate {
203                     prev.next_candidate_pre_binding_block = leaf_candidate.pre_binding_block;
204                 }
205                 previous_candidate = Some(leaf_candidate);
206             });
207         }
208
209         if let Some(ref borrows) = fake_borrows {
210             self.calculate_fake_borrows(borrows, scrutinee_span)
211         } else {
212             Vec::new()
213         }
214     }
215
216     /// Lower the bindings, guards and arm bodies of a `match` expression.
217     ///
218     /// The decision tree should have already been created
219     /// (by [Builder::lower_match_tree]).
220     ///
221     /// `outer_source_info` is the SourceInfo for the whole match.
222     fn lower_match_arms(
223         &mut self,
224         destination: Place<'tcx>,
225         scrutinee_place: Place<'tcx>,
226         scrutinee_span: Span,
227         arm_candidates: Vec<(&'_ Arm<'_, 'tcx>, Candidate<'_, 'tcx>)>,
228         outer_source_info: SourceInfo,
229         fake_borrow_temps: Vec<(Place<'tcx>, Local)>,
230     ) -> BlockAnd<()> {
231         let arm_end_blocks: Vec<_> = arm_candidates
232             .into_iter()
233             .map(|(arm, candidate)| {
234                 debug!("lowering arm {:?}\ncandidate = {:?}", arm, candidate);
235
236                 let arm_source_info = self.source_info(arm.span);
237                 let arm_scope = (arm.scope, arm_source_info);
238                 self.in_scope(arm_scope, arm.lint_level, |this| {
239                     let scope = this.declare_bindings(
240                         None,
241                         arm.span,
242                         &arm.pattern,
243                         ArmHasGuard(arm.guard.is_some()),
244                         Some((Some(&scrutinee_place), scrutinee_span)),
245                     );
246
247                     let arm_block = this.bind_pattern(
248                         outer_source_info,
249                         candidate,
250                         arm.guard.as_ref(),
251                         &fake_borrow_temps,
252                         scrutinee_span,
253                         Some(arm.span),
254                         Some(arm.scope),
255                     );
256
257                     if let Some(source_scope) = scope {
258                         this.source_scope = source_scope;
259                     }
260
261                     this.expr_into_dest(destination, arm_block, &arm.body)
262                 })
263             })
264             .collect();
265
266         // all the arm blocks will rejoin here
267         let end_block = self.cfg.start_new_block();
268
269         for arm_block in arm_end_blocks {
270             self.cfg.goto(unpack!(arm_block), outer_source_info, end_block);
271         }
272
273         self.source_scope = outer_source_info.scope;
274
275         end_block.unit()
276     }
277
278     /// Binds the variables and ascribes types for a given `match` arm or
279     /// `let` binding.
280     ///
281     /// Also check if the guard matches, if it's provided.
282     /// `arm_scope` should be `Some` if and only if this is called for a
283     /// `match` arm.
284     fn bind_pattern(
285         &mut self,
286         outer_source_info: SourceInfo,
287         candidate: Candidate<'_, 'tcx>,
288         guard: Option<&Guard<'_, 'tcx>>,
289         fake_borrow_temps: &Vec<(Place<'tcx>, Local)>,
290         scrutinee_span: Span,
291         arm_span: Option<Span>,
292         arm_scope: Option<region::Scope>,
293     ) -> BasicBlock {
294         if candidate.subcandidates.is_empty() {
295             // Avoid generating another `BasicBlock` when we only have one
296             // candidate.
297             self.bind_and_guard_matched_candidate(
298                 candidate,
299                 &[],
300                 guard,
301                 fake_borrow_temps,
302                 scrutinee_span,
303                 arm_span,
304                 true,
305             )
306         } else {
307             // It's helpful to avoid scheduling drops multiple times to save
308             // drop elaboration from having to clean up the extra drops.
309             //
310             // If we are in a `let` then we only schedule drops for the first
311             // candidate.
312             //
313             // If we're in a `match` arm then we could have a case like so:
314             //
315             // Ok(x) | Err(x) if return => { /* ... */ }
316             //
317             // In this case we don't want a drop of `x` scheduled when we
318             // return: it isn't bound by move until right before enter the arm.
319             // To handle this we instead unschedule it's drop after each time
320             // we lower the guard.
321             let target_block = self.cfg.start_new_block();
322             let mut schedule_drops = true;
323             // We keep a stack of all of the bindings and type asciptions
324             // from the parent candidates that we visit, that also need to
325             // be bound for each candidate.
326             traverse_candidate(
327                 candidate,
328                 &mut Vec::new(),
329                 &mut |leaf_candidate, parent_bindings| {
330                     if let Some(arm_scope) = arm_scope {
331                         self.clear_top_scope(arm_scope);
332                     }
333                     let binding_end = self.bind_and_guard_matched_candidate(
334                         leaf_candidate,
335                         parent_bindings,
336                         guard,
337                         &fake_borrow_temps,
338                         scrutinee_span,
339                         arm_span,
340                         schedule_drops,
341                     );
342                     if arm_scope.is_none() {
343                         schedule_drops = false;
344                     }
345                     self.cfg.goto(binding_end, outer_source_info, target_block);
346                 },
347                 |inner_candidate, parent_bindings| {
348                     parent_bindings.push((inner_candidate.bindings, inner_candidate.ascriptions));
349                     inner_candidate.subcandidates.into_iter()
350                 },
351                 |parent_bindings| {
352                     parent_bindings.pop();
353                 },
354             );
355
356             target_block
357         }
358     }
359
360     pub(super) fn expr_into_pattern(
361         &mut self,
362         mut block: BasicBlock,
363         irrefutable_pat: Pat<'tcx>,
364         initializer: &Expr<'_, 'tcx>,
365     ) -> BlockAnd<()> {
366         match *irrefutable_pat.kind {
367             // Optimize the case of `let x = ...` to write directly into `x`
368             PatKind::Binding { mode: BindingMode::ByValue, var, subpattern: None, .. } => {
369                 let place =
370                     self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard, true);
371                 unpack!(block = self.expr_into_dest(place, block, initializer));
372
373                 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
374                 let source_info = self.source_info(irrefutable_pat.span);
375                 self.cfg.push_fake_read(block, source_info, FakeReadCause::ForLet, place);
376
377                 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
378                 block.unit()
379             }
380
381             // Optimize the case of `let x: T = ...` to write directly
382             // into `x` and then require that `T == typeof(x)`.
383             //
384             // Weirdly, this is needed to prevent the
385             // `intrinsic-move-val.rs` test case from crashing. That
386             // test works with uninitialized values in a rather
387             // dubious way, so it may be that the test is kind of
388             // broken.
389             PatKind::AscribeUserType {
390                 subpattern:
391                     Pat {
392                         kind:
393                             box PatKind::Binding {
394                                 mode: BindingMode::ByValue,
395                                 var,
396                                 subpattern: None,
397                                 ..
398                             },
399                         ..
400                     },
401                 ascription:
402                     thir::pattern::Ascription { user_ty: pat_ascription_ty, variance: _, user_ty_span },
403             } => {
404                 let place =
405                     self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard, true);
406                 unpack!(block = self.expr_into_dest(place, block, initializer));
407
408                 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
409                 let pattern_source_info = self.source_info(irrefutable_pat.span);
410                 let cause_let = FakeReadCause::ForLet;
411                 self.cfg.push_fake_read(block, pattern_source_info, cause_let, place);
412
413                 let ty_source_info = self.source_info(user_ty_span);
414                 let user_ty = pat_ascription_ty.user_ty(
415                     &mut self.canonical_user_type_annotations,
416                     place.ty(&self.local_decls, self.tcx).ty,
417                     ty_source_info.span,
418                 );
419                 self.cfg.push(
420                     block,
421                     Statement {
422                         source_info: ty_source_info,
423                         kind: StatementKind::AscribeUserType(
424                             box (place, user_ty),
425                             // We always use invariant as the variance here. This is because the
426                             // variance field from the ascription refers to the variance to use
427                             // when applying the type to the value being matched, but this
428                             // ascription applies rather to the type of the binding. e.g., in this
429                             // example:
430                             //
431                             // ```
432                             // let x: T = <expr>
433                             // ```
434                             //
435                             // We are creating an ascription that defines the type of `x` to be
436                             // exactly `T` (i.e., with invariance). The variance field, in
437                             // contrast, is intended to be used to relate `T` to the type of
438                             // `<expr>`.
439                             ty::Variance::Invariant,
440                         ),
441                     },
442                 );
443
444                 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
445                 block.unit()
446             }
447
448             _ => {
449                 let place = unpack!(block = self.as_place(block, initializer));
450                 self.place_into_pattern(block, irrefutable_pat, place, true)
451             }
452         }
453     }
454
455     crate fn place_into_pattern(
456         &mut self,
457         block: BasicBlock,
458         irrefutable_pat: Pat<'tcx>,
459         initializer: Place<'tcx>,
460         set_match_place: bool,
461     ) -> BlockAnd<()> {
462         let mut candidate = Candidate::new(initializer, &irrefutable_pat, false);
463
464         let fake_borrow_temps =
465             self.lower_match_tree(block, irrefutable_pat.span, false, &mut [&mut candidate]);
466
467         // For matches and function arguments, the place that is being matched
468         // can be set when creating the variables. But the place for
469         // let PATTERN = ... might not even exist until we do the assignment.
470         // so we set it here instead.
471         if set_match_place {
472             let mut candidate_ref = &candidate;
473             while let Some(next) = {
474                 for binding in &candidate_ref.bindings {
475                     let local = self.var_local_id(binding.var_id, OutsideGuard);
476
477                     if let Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
478                         VarBindingForm { opt_match_place: Some((ref mut match_place, _)), .. },
479                     )))) = self.local_decls[local].local_info
480                     {
481                         *match_place = Some(initializer);
482                     } else {
483                         bug!("Let binding to non-user variable.")
484                     }
485                 }
486                 // All of the subcandidates should bind the same locals, so we
487                 // only visit the first one.
488                 candidate_ref.subcandidates.get(0)
489             } {
490                 candidate_ref = next;
491             }
492         }
493
494         self.bind_pattern(
495             self.source_info(irrefutable_pat.span),
496             candidate,
497             None,
498             &fake_borrow_temps,
499             irrefutable_pat.span,
500             None,
501             None,
502         )
503         .unit()
504     }
505
506     /// Declares the bindings of the given patterns and returns the visibility
507     /// scope for the bindings in these patterns, if such a scope had to be
508     /// created. NOTE: Declaring the bindings should always be done in their
509     /// drop scope.
510     crate fn declare_bindings(
511         &mut self,
512         mut visibility_scope: Option<SourceScope>,
513         scope_span: Span,
514         pattern: &Pat<'tcx>,
515         has_guard: ArmHasGuard,
516         opt_match_place: Option<(Option<&Place<'tcx>>, Span)>,
517     ) -> Option<SourceScope> {
518         debug!("declare_bindings: pattern={:?}", pattern);
519         self.visit_primary_bindings(
520             &pattern,
521             UserTypeProjections::none(),
522             &mut |this, mutability, name, mode, var, span, ty, user_ty| {
523                 if visibility_scope.is_none() {
524                     visibility_scope =
525                         Some(this.new_source_scope(scope_span, LintLevel::Inherited, None));
526                 }
527                 let source_info = SourceInfo { span, scope: this.source_scope };
528                 let visibility_scope = visibility_scope.unwrap();
529                 this.declare_binding(
530                     source_info,
531                     visibility_scope,
532                     mutability,
533                     name,
534                     mode,
535                     var,
536                     ty,
537                     user_ty,
538                     has_guard,
539                     opt_match_place.map(|(x, y)| (x.cloned(), y)),
540                     pattern.span,
541                 );
542             },
543         );
544         visibility_scope
545     }
546
547     crate fn storage_live_binding(
548         &mut self,
549         block: BasicBlock,
550         var: HirId,
551         span: Span,
552         for_guard: ForGuard,
553         schedule_drop: bool,
554     ) -> Place<'tcx> {
555         let local_id = self.var_local_id(var, for_guard);
556         let source_info = self.source_info(span);
557         self.cfg.push(block, Statement { source_info, kind: StatementKind::StorageLive(local_id) });
558         let region_scope = self.region_scope_tree.var_scope(var.local_id);
559         if schedule_drop {
560             self.schedule_drop(span, region_scope, local_id, DropKind::Storage);
561         }
562         Place::from(local_id)
563     }
564
565     crate fn schedule_drop_for_binding(&mut self, var: HirId, span: Span, for_guard: ForGuard) {
566         let local_id = self.var_local_id(var, for_guard);
567         let region_scope = self.region_scope_tree.var_scope(var.local_id);
568         self.schedule_drop(span, region_scope, local_id, DropKind::Value);
569     }
570
571     /// Visit all of the primary bindings in a patterns, that is, visit the
572     /// leftmost occurrence of each variable bound in a pattern. A variable
573     /// will occur more than once in an or-pattern.
574     pub(super) fn visit_primary_bindings(
575         &mut self,
576         pattern: &Pat<'tcx>,
577         pattern_user_ty: UserTypeProjections,
578         f: &mut impl FnMut(
579             &mut Self,
580             Mutability,
581             Symbol,
582             BindingMode,
583             HirId,
584             Span,
585             Ty<'tcx>,
586             UserTypeProjections,
587         ),
588     ) {
589         debug!(
590             "visit_primary_bindings: pattern={:?} pattern_user_ty={:?}",
591             pattern, pattern_user_ty
592         );
593         match *pattern.kind {
594             PatKind::Binding {
595                 mutability,
596                 name,
597                 mode,
598                 var,
599                 ty,
600                 ref subpattern,
601                 is_primary,
602                 ..
603             } => {
604                 if is_primary {
605                     f(self, mutability, name, mode, var, pattern.span, ty, pattern_user_ty.clone());
606                 }
607                 if let Some(subpattern) = subpattern.as_ref() {
608                     self.visit_primary_bindings(subpattern, pattern_user_ty, f);
609                 }
610             }
611
612             PatKind::Array { ref prefix, ref slice, ref suffix }
613             | PatKind::Slice { ref prefix, ref slice, ref suffix } => {
614                 let from = u64::try_from(prefix.len()).unwrap();
615                 let to = u64::try_from(suffix.len()).unwrap();
616                 for subpattern in prefix {
617                     self.visit_primary_bindings(subpattern, pattern_user_ty.clone().index(), f);
618                 }
619                 for subpattern in slice {
620                     self.visit_primary_bindings(
621                         subpattern,
622                         pattern_user_ty.clone().subslice(from, to),
623                         f,
624                     );
625                 }
626                 for subpattern in suffix {
627                     self.visit_primary_bindings(subpattern, pattern_user_ty.clone().index(), f);
628                 }
629             }
630
631             PatKind::Constant { .. } | PatKind::Range { .. } | PatKind::Wild => {}
632
633             PatKind::Deref { ref subpattern } => {
634                 self.visit_primary_bindings(subpattern, pattern_user_ty.deref(), f);
635             }
636
637             PatKind::AscribeUserType {
638                 ref subpattern,
639                 ascription: thir::pattern::Ascription { ref user_ty, user_ty_span, variance: _ },
640             } => {
641                 // This corresponds to something like
642                 //
643                 // ```
644                 // let A::<'a>(_): A<'static> = ...;
645                 // ```
646                 //
647                 // Note that the variance doesn't apply here, as we are tracking the effect
648                 // of `user_ty` on any bindings contained with subpattern.
649                 let annotation = CanonicalUserTypeAnnotation {
650                     span: user_ty_span,
651                     user_ty: user_ty.user_ty,
652                     inferred_ty: subpattern.ty,
653                 };
654                 let projection = UserTypeProjection {
655                     base: self.canonical_user_type_annotations.push(annotation),
656                     projs: Vec::new(),
657                 };
658                 let subpattern_user_ty = pattern_user_ty.push_projection(&projection, user_ty_span);
659                 self.visit_primary_bindings(subpattern, subpattern_user_ty, f)
660             }
661
662             PatKind::Leaf { ref subpatterns } => {
663                 for subpattern in subpatterns {
664                     let subpattern_user_ty = pattern_user_ty.clone().leaf(subpattern.field);
665                     debug!("visit_primary_bindings: subpattern_user_ty={:?}", subpattern_user_ty);
666                     self.visit_primary_bindings(&subpattern.pattern, subpattern_user_ty, f);
667                 }
668             }
669
670             PatKind::Variant { adt_def, substs: _, variant_index, ref subpatterns } => {
671                 for subpattern in subpatterns {
672                     let subpattern_user_ty =
673                         pattern_user_ty.clone().variant(adt_def, variant_index, subpattern.field);
674                     self.visit_primary_bindings(&subpattern.pattern, subpattern_user_ty, f);
675                 }
676             }
677             PatKind::Or { ref pats } => {
678                 // In cases where we recover from errors the primary bindings
679                 // may not all be in the leftmost subpattern. For example in
680                 // `let (x | y) = ...`, the primary binding of `y` occurs in
681                 // the right subpattern
682                 for subpattern in pats {
683                     self.visit_primary_bindings(subpattern, pattern_user_ty.clone(), f);
684                 }
685             }
686         }
687     }
688 }
689
690 #[derive(Debug)]
691 struct Candidate<'pat, 'tcx> {
692     /// [`Span`] of the original pattern that gave rise to this candidate.
693     span: Span,
694
695     /// Whether this `Candidate` has a guard.
696     has_guard: bool,
697
698     /// All of these must be satisfied...
699     match_pairs: SmallVec<[MatchPair<'pat, 'tcx>; 1]>,
700
701     /// ...these bindings established...
702     bindings: Vec<Binding<'tcx>>,
703
704     /// ...and these types asserted...
705     ascriptions: Vec<Ascription<'tcx>>,
706
707     /// ...and if this is non-empty, one of these subcandidates also has to match...
708     subcandidates: Vec<Candidate<'pat, 'tcx>>,
709
710     /// ...and the guard must be evaluated; if it's `false` then branch to `otherwise_block`.
711     otherwise_block: Option<BasicBlock>,
712
713     /// The block before the `bindings` have been established.
714     pre_binding_block: Option<BasicBlock>,
715     /// The pre-binding block of the next candidate.
716     next_candidate_pre_binding_block: Option<BasicBlock>,
717 }
718
719 impl<'tcx, 'pat> Candidate<'pat, 'tcx> {
720     fn new(place: Place<'tcx>, pattern: &'pat Pat<'tcx>, has_guard: bool) -> Self {
721         Candidate {
722             span: pattern.span,
723             has_guard,
724             match_pairs: smallvec![MatchPair { place, pattern }],
725             bindings: Vec::new(),
726             ascriptions: Vec::new(),
727             subcandidates: Vec::new(),
728             otherwise_block: None,
729             pre_binding_block: None,
730             next_candidate_pre_binding_block: None,
731         }
732     }
733
734     /// Visit the leaf candidates (those with no subcandidates) contained in
735     /// this candidate.
736     fn visit_leaves<'a>(&'a mut self, mut visit_leaf: impl FnMut(&'a mut Self)) {
737         traverse_candidate(
738             self,
739             &mut (),
740             &mut move |c, _| visit_leaf(c),
741             move |c, _| c.subcandidates.iter_mut(),
742             |_| {},
743         );
744     }
745 }
746
747 /// A depth-first traversal of the `Candidate` and all of its recursive
748 /// subcandidates.
749 fn traverse_candidate<'pat, 'tcx: 'pat, C, T, I>(
750     candidate: C,
751     context: &mut T,
752     visit_leaf: &mut impl FnMut(C, &mut T),
753     get_children: impl Copy + Fn(C, &mut T) -> I,
754     complete_children: impl Copy + Fn(&mut T),
755 ) where
756     C: Borrow<Candidate<'pat, 'tcx>>,
757     I: Iterator<Item = C>,
758 {
759     if candidate.borrow().subcandidates.is_empty() {
760         visit_leaf(candidate, context)
761     } else {
762         for child in get_children(candidate, context) {
763             traverse_candidate(child, context, visit_leaf, get_children, complete_children);
764         }
765         complete_children(context)
766     }
767 }
768
769 #[derive(Clone, Debug)]
770 struct Binding<'tcx> {
771     span: Span,
772     source: Place<'tcx>,
773     name: Symbol,
774     var_id: HirId,
775     var_ty: Ty<'tcx>,
776     mutability: Mutability,
777     binding_mode: BindingMode,
778 }
779
780 /// Indicates that the type of `source` must be a subtype of the
781 /// user-given type `user_ty`; this is basically a no-op but can
782 /// influence region inference.
783 #[derive(Clone, Debug)]
784 struct Ascription<'tcx> {
785     span: Span,
786     source: Place<'tcx>,
787     user_ty: PatTyProj<'tcx>,
788     variance: ty::Variance,
789 }
790
791 #[derive(Clone, Debug)]
792 crate struct MatchPair<'pat, 'tcx> {
793     // this place...
794     place: Place<'tcx>,
795
796     // ... must match this pattern.
797     pattern: &'pat Pat<'tcx>,
798 }
799
800 /// See [`Test`] for more.
801 #[derive(Clone, Debug, PartialEq)]
802 enum TestKind<'tcx> {
803     /// Test what enum variant a value is.
804     Switch {
805         /// The enum type being tested.
806         adt_def: &'tcx ty::AdtDef,
807         /// The set of variants that we should create a branch for. We also
808         /// create an additional "otherwise" case.
809         variants: BitSet<VariantIdx>,
810     },
811
812     /// Test what value an integer, `bool`, or `char` has.
813     SwitchInt {
814         /// The type of the value that we're testing.
815         switch_ty: Ty<'tcx>,
816         /// The (ordered) set of values that we test for.
817         ///
818         /// For integers and `char`s we create a branch to each of the values in
819         /// `options`, as well as an "otherwise" branch for all other values, even
820         /// in the (rare) case that `options` is exhaustive.
821         ///
822         /// For `bool` we always generate two edges, one for `true` and one for
823         /// `false`.
824         options: FxIndexMap<&'tcx ty::Const<'tcx>, u128>,
825     },
826
827     /// Test for equality with value, possibly after an unsizing coercion to
828     /// `ty`,
829     Eq {
830         value: &'tcx ty::Const<'tcx>,
831         // Integer types are handled by `SwitchInt`, and constants with ADT
832         // types are converted back into patterns, so this can only be `&str`,
833         // `&[T]`, `f32` or `f64`.
834         ty: Ty<'tcx>,
835     },
836
837     /// Test whether the value falls within an inclusive or exclusive range
838     Range(PatRange<'tcx>),
839
840     /// Test that the length of the slice is equal to `len`.
841     Len { len: u64, op: BinOp },
842 }
843
844 /// A test to perform to determine which [`Candidate`] matches a value.
845 ///
846 /// [`Test`] is just the test to perform; it does not include the value
847 /// to be tested.
848 #[derive(Debug)]
849 crate struct Test<'tcx> {
850     span: Span,
851     kind: TestKind<'tcx>,
852 }
853
854 /// `ArmHasGuard` is a wrapper around a boolean flag. It indicates whether
855 /// a match arm has a guard expression attached to it.
856 #[derive(Copy, Clone, Debug)]
857 crate struct ArmHasGuard(crate bool);
858
859 ///////////////////////////////////////////////////////////////////////////
860 // Main matching algorithm
861
862 impl<'a, 'tcx> Builder<'a, 'tcx> {
863     /// The main match algorithm. It begins with a set of candidates
864     /// `candidates` and has the job of generating code to determine
865     /// which of these candidates, if any, is the correct one. The
866     /// candidates are sorted such that the first item in the list
867     /// has the highest priority. When a candidate is found to match
868     /// the value, we will set and generate a branch to the appropriate
869     /// pre-binding block.
870     ///
871     /// If we find that *NONE* of the candidates apply, we branch to the
872     /// `otherwise_block`, setting it to `Some` if required. In principle, this
873     /// means that the input list was not exhaustive, though at present we
874     /// sometimes are not smart enough to recognize all exhaustive inputs.
875     ///
876     /// It might be surprising that the input can be non-exhaustive.
877     /// Indeed, initially, it is not, because all matches are
878     /// exhaustive in Rust. But during processing we sometimes divide
879     /// up the list of candidates and recurse with a non-exhaustive
880     /// list. This is important to keep the size of the generated code
881     /// under control. See [`Builder::test_candidates`] for more details.
882     ///
883     /// If `fake_borrows` is `Some`, then places which need fake borrows
884     /// will be added to it.
885     ///
886     /// For an example of a case where we set `otherwise_block`, even for an
887     /// exhaustive match, consider:
888     ///
889     /// ```
890     /// match x {
891     ///     (true, true) => (),
892     ///     (_, false) => (),
893     ///     (false, true) => (),
894     /// }
895     /// ```
896     ///
897     /// For this match, we check if `x.0` matches `true` (for the first
898     /// arm). If it doesn't match, we check `x.1`. If `x.1` is `true` we check
899     /// if `x.0` matches `false` (for the third arm). In the (impossible at
900     /// runtime) case when `x.0` is now `true`, we branch to
901     /// `otherwise_block`.
902     fn match_candidates<'pat>(
903         &mut self,
904         span: Span,
905         start_block: BasicBlock,
906         otherwise_block: &mut Option<BasicBlock>,
907         candidates: &mut [&mut Candidate<'pat, 'tcx>],
908         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
909     ) {
910         debug!(
911             "matched_candidate(span={:?}, candidates={:?}, start_block={:?}, otherwise_block={:?})",
912             span, candidates, start_block, otherwise_block,
913         );
914
915         // Start by simplifying candidates. Once this process is complete, all
916         // the match pairs which remain require some form of test, whether it
917         // be a switch or pattern comparison.
918         let mut split_or_candidate = false;
919         for candidate in &mut *candidates {
920             split_or_candidate |= self.simplify_candidate(candidate);
921         }
922
923         ensure_sufficient_stack(|| {
924             if split_or_candidate {
925                 // At least one of the candidates has been split into subcandidates.
926                 // We need to change the candidate list to include those.
927                 let mut new_candidates = Vec::new();
928
929                 for candidate in candidates {
930                     candidate.visit_leaves(|leaf_candidate| new_candidates.push(leaf_candidate));
931                 }
932                 self.match_simplified_candidates(
933                     span,
934                     start_block,
935                     otherwise_block,
936                     &mut *new_candidates,
937                     fake_borrows,
938                 );
939             } else {
940                 self.match_simplified_candidates(
941                     span,
942                     start_block,
943                     otherwise_block,
944                     candidates,
945                     fake_borrows,
946                 );
947             }
948         });
949     }
950
951     fn match_simplified_candidates(
952         &mut self,
953         span: Span,
954         start_block: BasicBlock,
955         otherwise_block: &mut Option<BasicBlock>,
956         candidates: &mut [&mut Candidate<'_, 'tcx>],
957         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
958     ) {
959         // The candidates are sorted by priority. Check to see whether the
960         // higher priority candidates (and hence at the front of the slice)
961         // have satisfied all their match pairs.
962         let fully_matched = candidates.iter().take_while(|c| c.match_pairs.is_empty()).count();
963         debug!("match_candidates: {:?} candidates fully matched", fully_matched);
964         let (matched_candidates, unmatched_candidates) = candidates.split_at_mut(fully_matched);
965
966         let block = if !matched_candidates.is_empty() {
967             let otherwise_block =
968                 self.select_matched_candidates(matched_candidates, start_block, fake_borrows);
969
970             if let Some(last_otherwise_block) = otherwise_block {
971                 last_otherwise_block
972             } else {
973                 // Any remaining candidates are unreachable.
974                 if unmatched_candidates.is_empty() {
975                     return;
976                 }
977                 self.cfg.start_new_block()
978             }
979         } else {
980             start_block
981         };
982
983         // If there are no candidates that still need testing, we're
984         // done. Since all matches are exhaustive, execution should
985         // never reach this point.
986         if unmatched_candidates.is_empty() {
987             let source_info = self.source_info(span);
988             if let Some(otherwise) = *otherwise_block {
989                 self.cfg.goto(block, source_info, otherwise);
990             } else {
991                 *otherwise_block = Some(block);
992             }
993             return;
994         }
995
996         // Test for the remaining candidates.
997         self.test_candidates_with_or(
998             span,
999             unmatched_candidates,
1000             block,
1001             otherwise_block,
1002             fake_borrows,
1003         );
1004     }
1005
1006     /// Link up matched candidates.
1007     ///
1008     /// For example, if we have something like this:
1009     ///
1010     /// ```rust
1011     /// ...
1012     /// Some(x) if cond1 => ...
1013     /// Some(x) => ...
1014     /// Some(x) if cond2 => ...
1015     /// ...
1016     /// ```
1017     ///
1018     /// We generate real edges from:
1019     ///
1020     /// * `start_block` to the [pre-binding block] of the first pattern,
1021     /// * the [otherwise block] of the first pattern to the second pattern,
1022     /// * the [otherwise block] of the third pattern to a block with an
1023     ///   [`Unreachable` terminator](TerminatorKind::Unreachable).
1024     ///
1025     /// In addition, we add fake edges from the otherwise blocks to the
1026     /// pre-binding block of the next candidate in the original set of
1027     /// candidates.
1028     ///
1029     /// [pre-binding block]: Candidate::pre_binding_block
1030     /// [otherwise block]: Candidate::otherwise_block
1031     fn select_matched_candidates(
1032         &mut self,
1033         matched_candidates: &mut [&mut Candidate<'_, 'tcx>],
1034         start_block: BasicBlock,
1035         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1036     ) -> Option<BasicBlock> {
1037         debug_assert!(
1038             !matched_candidates.is_empty(),
1039             "select_matched_candidates called with no candidates",
1040         );
1041         debug_assert!(
1042             matched_candidates.iter().all(|c| c.subcandidates.is_empty()),
1043             "subcandidates should be empty in select_matched_candidates",
1044         );
1045
1046         // Insert a borrows of prefixes of places that are bound and are
1047         // behind a dereference projection.
1048         //
1049         // These borrows are taken to avoid situations like the following:
1050         //
1051         // match x[10] {
1052         //     _ if { x = &[0]; false } => (),
1053         //     y => (), // Out of bounds array access!
1054         // }
1055         //
1056         // match *x {
1057         //     // y is bound by reference in the guard and then by copy in the
1058         //     // arm, so y is 2 in the arm!
1059         //     y if { y == 1 && (x = &2) == () } => y,
1060         //     _ => 3,
1061         // }
1062         if let Some(fake_borrows) = fake_borrows {
1063             for Binding { source, .. } in
1064                 matched_candidates.iter().flat_map(|candidate| &candidate.bindings)
1065             {
1066                 if let Some(i) =
1067                     source.projection.iter().rposition(|elem| elem == ProjectionElem::Deref)
1068                 {
1069                     let proj_base = &source.projection[..i];
1070
1071                     fake_borrows.insert(Place {
1072                         local: source.local,
1073                         projection: self.tcx.intern_place_elems(proj_base),
1074                     });
1075                 }
1076             }
1077         }
1078
1079         let fully_matched_with_guard = matched_candidates
1080             .iter()
1081             .position(|c| !c.has_guard)
1082             .unwrap_or(matched_candidates.len() - 1);
1083
1084         let (reachable_candidates, unreachable_candidates) =
1085             matched_candidates.split_at_mut(fully_matched_with_guard + 1);
1086
1087         let mut next_prebinding = start_block;
1088
1089         for candidate in reachable_candidates.iter_mut() {
1090             assert!(candidate.otherwise_block.is_none());
1091             assert!(candidate.pre_binding_block.is_none());
1092             candidate.pre_binding_block = Some(next_prebinding);
1093             if candidate.has_guard {
1094                 // Create the otherwise block for this candidate, which is the
1095                 // pre-binding block for the next candidate.
1096                 next_prebinding = self.cfg.start_new_block();
1097                 candidate.otherwise_block = Some(next_prebinding);
1098             }
1099         }
1100
1101         debug!(
1102             "match_candidates: add pre_binding_blocks for unreachable {:?}",
1103             unreachable_candidates,
1104         );
1105         for candidate in unreachable_candidates {
1106             assert!(candidate.pre_binding_block.is_none());
1107             candidate.pre_binding_block = Some(self.cfg.start_new_block());
1108         }
1109
1110         reachable_candidates.last_mut().unwrap().otherwise_block
1111     }
1112
1113     /// Tests a candidate where there are only or-patterns left to test, or
1114     /// forwards to [Builder::test_candidates].
1115     ///
1116     /// Given a pattern `(P | Q, R | S)` we (in principle) generate a CFG like
1117     /// so:
1118     ///
1119     /// ```text
1120     /// [ start ]
1121     ///      |
1122     /// [ match P, Q ]
1123     ///      |
1124     ///      +----------------------------------------+------------------------------------+
1125     ///      |                                        |                                    |
1126     ///      V                                        V                                    V
1127     /// [ P matches ]                           [ Q matches ]                        [ otherwise ]
1128     ///      |                                        |                                    |
1129     ///      V                                        V                                    |
1130     /// [ match R, S ]                          [ match R, S ]                             |
1131     ///      |                                        |                                    |
1132     ///      +--------------+------------+            +--------------+------------+        |
1133     ///      |              |            |            |              |            |        |
1134     ///      V              V            V            V              V            V        |
1135     /// [ R matches ] [ S matches ] [otherwise ] [ R matches ] [ S matches ] [otherwise ]  |
1136     ///      |              |            |            |              |            |        |
1137     ///      +--------------+------------|------------+--------------+            |        |
1138     ///      |                           |                                        |        |
1139     ///      |                           +----------------------------------------+--------+
1140     ///      |                           |
1141     ///      V                           V
1142     /// [ Success ]                 [ Failure ]
1143     /// ```
1144     ///
1145     /// In practice there are some complications:
1146     ///
1147     /// * If there's a guard, then the otherwise branch of the first match on
1148     ///   `R | S` goes to a test for whether `Q` matches, and the control flow
1149     ///   doesn't merge into a single success block until after the guard is
1150     ///   tested.
1151     /// * If neither `P` or `Q` has any bindings or type ascriptions and there
1152     ///   isn't a match guard, then we create a smaller CFG like:
1153     ///
1154     /// ```text
1155     ///     ...
1156     ///      +---------------+------------+
1157     ///      |               |            |
1158     /// [ P matches ] [ Q matches ] [ otherwise ]
1159     ///      |               |            |
1160     ///      +---------------+            |
1161     ///      |                           ...
1162     /// [ match R, S ]
1163     ///      |
1164     ///     ...
1165     /// ```
1166     fn test_candidates_with_or(
1167         &mut self,
1168         span: Span,
1169         candidates: &mut [&mut Candidate<'_, 'tcx>],
1170         block: BasicBlock,
1171         otherwise_block: &mut Option<BasicBlock>,
1172         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1173     ) {
1174         let (first_candidate, remaining_candidates) = candidates.split_first_mut().unwrap();
1175
1176         // All of the or-patterns have been sorted to the end, so if the first
1177         // pattern is an or-pattern we only have or-patterns.
1178         match *first_candidate.match_pairs[0].pattern.kind {
1179             PatKind::Or { .. } => (),
1180             _ => {
1181                 self.test_candidates(span, candidates, block, otherwise_block, fake_borrows);
1182                 return;
1183             }
1184         }
1185
1186         let match_pairs = mem::take(&mut first_candidate.match_pairs);
1187         first_candidate.pre_binding_block = Some(block);
1188
1189         let mut otherwise = None;
1190         for match_pair in match_pairs {
1191             if let PatKind::Or { ref pats } = *match_pair.pattern.kind {
1192                 let or_span = match_pair.pattern.span;
1193                 let place = match_pair.place;
1194
1195                 first_candidate.visit_leaves(|leaf_candidate| {
1196                     self.test_or_pattern(
1197                         leaf_candidate,
1198                         &mut otherwise,
1199                         pats,
1200                         or_span,
1201                         place,
1202                         fake_borrows,
1203                     );
1204                 });
1205             } else {
1206                 bug!("Or-patterns should have been sorted to the end");
1207             }
1208         }
1209
1210         let remainder_start = otherwise.unwrap_or_else(|| self.cfg.start_new_block());
1211
1212         self.match_candidates(
1213             span,
1214             remainder_start,
1215             otherwise_block,
1216             remaining_candidates,
1217             fake_borrows,
1218         )
1219     }
1220
1221     fn test_or_pattern<'pat>(
1222         &mut self,
1223         candidate: &mut Candidate<'pat, 'tcx>,
1224         otherwise: &mut Option<BasicBlock>,
1225         pats: &'pat [Pat<'tcx>],
1226         or_span: Span,
1227         place: Place<'tcx>,
1228         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1229     ) {
1230         debug!("test_or_pattern:\ncandidate={:#?}\npats={:#?}", candidate, pats);
1231         let mut or_candidates: Vec<_> =
1232             pats.iter().map(|pat| Candidate::new(place, pat, candidate.has_guard)).collect();
1233         let mut or_candidate_refs: Vec<_> = or_candidates.iter_mut().collect();
1234         let otherwise = if candidate.otherwise_block.is_some() {
1235             &mut candidate.otherwise_block
1236         } else {
1237             otherwise
1238         };
1239         self.match_candidates(
1240             or_span,
1241             candidate.pre_binding_block.unwrap(),
1242             otherwise,
1243             &mut or_candidate_refs,
1244             fake_borrows,
1245         );
1246         candidate.subcandidates = or_candidates;
1247         self.merge_trivial_subcandidates(candidate, self.source_info(or_span));
1248     }
1249
1250     /// Try to merge all of the subcandidates of the given candidate into one.
1251     /// This avoids exponentially large CFGs in cases like `(1 | 2, 3 | 4, ...)`.
1252     fn merge_trivial_subcandidates(
1253         &mut self,
1254         candidate: &mut Candidate<'_, 'tcx>,
1255         source_info: SourceInfo,
1256     ) {
1257         if candidate.subcandidates.is_empty() || candidate.has_guard {
1258             // FIXME(or_patterns; matthewjasper) Don't give up if we have a guard.
1259             return;
1260         }
1261
1262         let mut can_merge = true;
1263
1264         // Not `Iterator::all` because we don't want to short-circuit.
1265         for subcandidate in &mut candidate.subcandidates {
1266             self.merge_trivial_subcandidates(subcandidate, source_info);
1267
1268             // FIXME(or_patterns; matthewjasper) Try to be more aggressive here.
1269             can_merge &= subcandidate.subcandidates.is_empty()
1270                 && subcandidate.bindings.is_empty()
1271                 && subcandidate.ascriptions.is_empty();
1272         }
1273
1274         if can_merge {
1275             let any_matches = self.cfg.start_new_block();
1276             for subcandidate in mem::take(&mut candidate.subcandidates) {
1277                 let or_block = subcandidate.pre_binding_block.unwrap();
1278                 self.cfg.goto(or_block, source_info, any_matches);
1279             }
1280             candidate.pre_binding_block = Some(any_matches);
1281         }
1282     }
1283
1284     /// This is the most subtle part of the matching algorithm. At
1285     /// this point, the input candidates have been fully simplified,
1286     /// and so we know that all remaining match-pairs require some
1287     /// sort of test. To decide what test to perform, we take the highest
1288     /// priority candidate (the first one in the list, as of January 2021)
1289     /// and extract the first match-pair from the list. From this we decide
1290     /// what kind of test is needed using [`Builder::test`], defined in the
1291     /// [`test` module](mod@test).
1292     ///
1293     /// *Note:* taking the first match pair is somewhat arbitrary, and
1294     /// we might do better here by choosing more carefully what to
1295     /// test.
1296     ///
1297     /// For example, consider the following possible match-pairs:
1298     ///
1299     /// 1. `x @ Some(P)` -- we will do a [`Switch`] to decide what variant `x` has
1300     /// 2. `x @ 22` -- we will do a [`SwitchInt`] to decide what value `x` has
1301     /// 3. `x @ 3..5` -- we will do a [`Range`] test to decide what range `x` falls in
1302     /// 4. etc.
1303     ///
1304     /// [`Switch`]: TestKind::Switch
1305     /// [`SwitchInt`]: TestKind::SwitchInt
1306     /// [`Range`]: TestKind::Range
1307     ///
1308     /// Once we know what sort of test we are going to perform, this
1309     /// test may also help us winnow down our candidates. So we walk over
1310     /// the candidates (from high to low priority) and check. This
1311     /// gives us, for each outcome of the test, a transformed list of
1312     /// candidates. For example, if we are testing `x.0`'s variant,
1313     /// and we have a candidate `(x.0 @ Some(v), x.1 @ 22)`,
1314     /// then we would have a resulting candidate of `((x.0 as Some).0 @ v, x.1 @ 22)`.
1315     /// Note that the first match-pair is now simpler (and, in fact, irrefutable).
1316     ///
1317     /// But there may also be candidates that the test just doesn't
1318     /// apply to. The classical example involves wildcards:
1319     ///
1320     /// ```
1321     /// # let (x, y, z) = (true, true, true);
1322     /// match (x, y, z) {
1323     ///     (true, _, true) => true,    // (0)
1324     ///     (_, true, _) => true,       // (1)
1325     ///     (false, false, _) => false, // (2)
1326     ///     (true, _, false) => false,  // (3)
1327     /// }
1328     /// ```
1329     ///
1330     /// In that case, after we test on `x`, there are 2 overlapping candidate
1331     /// sets:
1332     ///
1333     /// - If the outcome is that `x` is true, candidates 0, 1, and 3
1334     /// - If the outcome is that `x` is false, candidates 1 and 2
1335     ///
1336     /// Here, the traditional "decision tree" method would generate 2
1337     /// separate code-paths for the 2 separate cases.
1338     ///
1339     /// In some cases, this duplication can create an exponential amount of
1340     /// code. This is most easily seen by noticing that this method terminates
1341     /// with precisely the reachable arms being reachable - but that problem
1342     /// is trivially NP-complete:
1343     ///
1344     /// ```rust
1345     ///     match (var0, var1, var2, var3, ...) {
1346     ///         (true, _, _, false, true, ...) => false,
1347     ///         (_, true, true, false, _, ...) => false,
1348     ///         (false, _, false, false, _, ...) => false,
1349     ///         ...
1350     ///         _ => true
1351     ///     }
1352     /// ```
1353     ///
1354     /// Here the last arm is reachable only if there is an assignment to
1355     /// the variables that does not match any of the literals. Therefore,
1356     /// compilation would take an exponential amount of time in some cases.
1357     ///
1358     /// That kind of exponential worst-case might not occur in practice, but
1359     /// our simplistic treatment of constants and guards would make it occur
1360     /// in very common situations - for example [#29740]:
1361     ///
1362     /// ```rust
1363     /// match x {
1364     ///     "foo" if foo_guard => ...,
1365     ///     "bar" if bar_guard => ...,
1366     ///     "baz" if baz_guard => ...,
1367     ///     ...
1368     /// }
1369     /// ```
1370     ///
1371     /// [#29740]: https://github.com/rust-lang/rust/issues/29740
1372     ///
1373     /// Here we first test the match-pair `x @ "foo"`, which is an [`Eq` test].
1374     ///
1375     /// [`Eq` test]: TestKind::Eq
1376     ///
1377     /// It might seem that we would end up with 2 disjoint candidate
1378     /// sets, consisting of the first candidate or the other two, but our
1379     /// algorithm doesn't reason about `"foo"` being distinct from the other
1380     /// constants; it considers the latter arms to potentially match after
1381     /// both outcomes, which obviously leads to an exponential number
1382     /// of tests.
1383     ///
1384     /// To avoid these kinds of problems, our algorithm tries to ensure
1385     /// the amount of generated tests is linear. When we do a k-way test,
1386     /// we return an additional "unmatched" set alongside the obvious `k`
1387     /// sets. When we encounter a candidate that would be present in more
1388     /// than one of the sets, we put it and all candidates below it into the
1389     /// "unmatched" set. This ensures these `k+1` sets are disjoint.
1390     ///
1391     /// After we perform our test, we branch into the appropriate candidate
1392     /// set and recurse with `match_candidates`. These sub-matches are
1393     /// obviously non-exhaustive - as we discarded our otherwise set - so
1394     /// we set their continuation to do `match_candidates` on the
1395     /// "unmatched" set (which is again non-exhaustive).
1396     ///
1397     /// If you apply this to the above test, you basically wind up
1398     /// with an if-else-if chain, testing each candidate in turn,
1399     /// which is precisely what we want.
1400     ///
1401     /// In addition to avoiding exponential-time blowups, this algorithm
1402     /// also has the nice property that each guard and arm is only generated
1403     /// once.
1404     fn test_candidates<'pat, 'b, 'c>(
1405         &mut self,
1406         span: Span,
1407         mut candidates: &'b mut [&'c mut Candidate<'pat, 'tcx>],
1408         block: BasicBlock,
1409         otherwise_block: &mut Option<BasicBlock>,
1410         fake_borrows: &mut Option<FxHashSet<Place<'tcx>>>,
1411     ) {
1412         // extract the match-pair from the highest priority candidate
1413         let match_pair = &candidates.first().unwrap().match_pairs[0];
1414         let mut test = self.test(match_pair);
1415         let match_place = match_pair.place;
1416
1417         // most of the time, the test to perform is simply a function
1418         // of the main candidate; but for a test like SwitchInt, we
1419         // may want to add cases based on the candidates that are
1420         // available
1421         match test.kind {
1422             TestKind::SwitchInt { switch_ty, ref mut options } => {
1423                 for candidate in candidates.iter() {
1424                     if !self.add_cases_to_switch(&match_place, candidate, switch_ty, options) {
1425                         break;
1426                     }
1427                 }
1428             }
1429             TestKind::Switch { adt_def: _, ref mut variants } => {
1430                 for candidate in candidates.iter() {
1431                     if !self.add_variants_to_switch(&match_place, candidate, variants) {
1432                         break;
1433                     }
1434                 }
1435             }
1436             _ => {}
1437         }
1438
1439         // Insert a Shallow borrow of any places that is switched on.
1440         if let Some(fb) = fake_borrows {
1441             fb.insert(match_place);
1442         }
1443
1444         // perform the test, branching to one of N blocks. For each of
1445         // those N possible outcomes, create a (initially empty)
1446         // vector of candidates. Those are the candidates that still
1447         // apply if the test has that particular outcome.
1448         debug!("match_candidates: test={:?} match_pair={:?}", test, match_pair);
1449         let mut target_candidates: Vec<Vec<&mut Candidate<'pat, 'tcx>>> = vec![];
1450         target_candidates.resize_with(test.targets(), Default::default);
1451
1452         let total_candidate_count = candidates.len();
1453
1454         // Sort the candidates into the appropriate vector in
1455         // `target_candidates`. Note that at some point we may
1456         // encounter a candidate where the test is not relevant; at
1457         // that point, we stop sorting.
1458         while let Some(candidate) = candidates.first_mut() {
1459             if let Some(idx) = self.sort_candidate(&match_place, &test, candidate) {
1460                 let (candidate, rest) = candidates.split_first_mut().unwrap();
1461                 target_candidates[idx].push(candidate);
1462                 candidates = rest;
1463             } else {
1464                 break;
1465             }
1466         }
1467         // at least the first candidate ought to be tested
1468         assert!(total_candidate_count > candidates.len());
1469         debug!("tested_candidates: {}", total_candidate_count - candidates.len());
1470         debug!("untested_candidates: {}", candidates.len());
1471
1472         // HACK(matthewjasper) This is a closure so that we can let the test
1473         // create its blocks before the rest of the match. This currently
1474         // improves the speed of llvm when optimizing long string literal
1475         // matches
1476         let make_target_blocks = move |this: &mut Self| -> Vec<BasicBlock> {
1477             // The block that we should branch to if none of the
1478             // `target_candidates` match. This is either the block where we
1479             // start matching the untested candidates if there are any,
1480             // otherwise it's the `otherwise_block`.
1481             let remainder_start = &mut None;
1482             let remainder_start =
1483                 if candidates.is_empty() { &mut *otherwise_block } else { remainder_start };
1484
1485             // For each outcome of test, process the candidates that still
1486             // apply. Collect a list of blocks where control flow will
1487             // branch if one of the `target_candidate` sets is not
1488             // exhaustive.
1489             let target_blocks: Vec<_> = target_candidates
1490                 .into_iter()
1491                 .map(|mut candidates| {
1492                     if !candidates.is_empty() {
1493                         let candidate_start = this.cfg.start_new_block();
1494                         this.match_candidates(
1495                             span,
1496                             candidate_start,
1497                             remainder_start,
1498                             &mut *candidates,
1499                             fake_borrows,
1500                         );
1501                         candidate_start
1502                     } else {
1503                         *remainder_start.get_or_insert_with(|| this.cfg.start_new_block())
1504                     }
1505                 })
1506                 .collect();
1507
1508             if !candidates.is_empty() {
1509                 let remainder_start = remainder_start.unwrap_or_else(|| this.cfg.start_new_block());
1510                 this.match_candidates(
1511                     span,
1512                     remainder_start,
1513                     otherwise_block,
1514                     candidates,
1515                     fake_borrows,
1516                 );
1517             };
1518
1519             target_blocks
1520         };
1521
1522         self.perform_test(block, match_place, &test, make_target_blocks);
1523     }
1524
1525     /// Determine the fake borrows that are needed from a set of places that
1526     /// have to be stable across match guards.
1527     ///
1528     /// Returns a list of places that need a fake borrow and the temporary
1529     /// that's used to store the fake borrow.
1530     ///
1531     /// Match exhaustiveness checking is not able to handle the case where the
1532     /// place being matched on is mutated in the guards. We add "fake borrows"
1533     /// to the guards that prevent any mutation of the place being matched.
1534     /// There are a some subtleties:
1535     ///
1536     /// 1. Borrowing `*x` doesn't prevent assigning to `x`. If `x` is a shared
1537     ///    reference, the borrow isn't even tracked. As such we have to add fake
1538     ///    borrows of any prefixes of a place
1539     /// 2. We don't want `match x { _ => (), }` to conflict with mutable
1540     ///    borrows of `x`, so we only add fake borrows for places which are
1541     ///    bound or tested by the match.
1542     /// 3. We don't want the fake borrows to conflict with `ref mut` bindings,
1543     ///    so we use a special BorrowKind for them.
1544     /// 4. The fake borrows may be of places in inactive variants, so it would
1545     ///    be UB to generate code for them. They therefore have to be removed
1546     ///    by a MIR pass run after borrow checking.
1547     fn calculate_fake_borrows<'b>(
1548         &mut self,
1549         fake_borrows: &'b FxHashSet<Place<'tcx>>,
1550         temp_span: Span,
1551     ) -> Vec<(Place<'tcx>, Local)> {
1552         let tcx = self.tcx;
1553
1554         debug!("add_fake_borrows fake_borrows = {:?}", fake_borrows);
1555
1556         let mut all_fake_borrows = Vec::with_capacity(fake_borrows.len());
1557
1558         // Insert a Shallow borrow of the prefixes of any fake borrows.
1559         for place in fake_borrows {
1560             let mut cursor = place.projection.as_ref();
1561             while let [proj_base @ .., elem] = cursor {
1562                 cursor = proj_base;
1563
1564                 if let ProjectionElem::Deref = elem {
1565                     // Insert a shallow borrow after a deref. For other
1566                     // projections the borrow of prefix_cursor will
1567                     // conflict with any mutation of base.
1568                     all_fake_borrows.push(PlaceRef { local: place.local, projection: proj_base });
1569                 }
1570             }
1571
1572             all_fake_borrows.push(place.as_ref());
1573         }
1574
1575         // Deduplicate and ensure a deterministic order.
1576         all_fake_borrows.sort();
1577         all_fake_borrows.dedup();
1578
1579         debug!("add_fake_borrows all_fake_borrows = {:?}", all_fake_borrows);
1580
1581         all_fake_borrows
1582             .into_iter()
1583             .map(|matched_place_ref| {
1584                 let matched_place = Place {
1585                     local: matched_place_ref.local,
1586                     projection: tcx.intern_place_elems(matched_place_ref.projection),
1587                 };
1588                 let fake_borrow_deref_ty = matched_place.ty(&self.local_decls, tcx).ty;
1589                 let fake_borrow_ty = tcx.mk_imm_ref(tcx.lifetimes.re_erased, fake_borrow_deref_ty);
1590                 let fake_borrow_temp =
1591                     self.local_decls.push(LocalDecl::new(fake_borrow_ty, temp_span));
1592
1593                 (matched_place, fake_borrow_temp)
1594             })
1595             .collect()
1596     }
1597 }
1598
1599 ///////////////////////////////////////////////////////////////////////////
1600 // Pat binding - used for `let` and function parameters as well.
1601
1602 impl<'a, 'tcx> Builder<'a, 'tcx> {
1603     /// Initializes each of the bindings from the candidate by
1604     /// moving/copying/ref'ing the source as appropriate. Tests the guard, if
1605     /// any, and then branches to the arm. Returns the block for the case where
1606     /// the guard succeeds.
1607     ///
1608     /// Note: we do not check earlier that if there is a guard,
1609     /// there cannot be move bindings. We avoid a use-after-move by only
1610     /// moving the binding once the guard has evaluated to true (see below).
1611     fn bind_and_guard_matched_candidate<'pat>(
1612         &mut self,
1613         candidate: Candidate<'pat, 'tcx>,
1614         parent_bindings: &[(Vec<Binding<'tcx>>, Vec<Ascription<'tcx>>)],
1615         guard: Option<&Guard<'_, 'tcx>>,
1616         fake_borrows: &Vec<(Place<'tcx>, Local)>,
1617         scrutinee_span: Span,
1618         arm_span: Option<Span>,
1619         schedule_drops: bool,
1620     ) -> BasicBlock {
1621         debug!("bind_and_guard_matched_candidate(candidate={:?})", candidate);
1622
1623         debug_assert!(candidate.match_pairs.is_empty());
1624
1625         let candidate_source_info = self.source_info(candidate.span);
1626
1627         let mut block = candidate.pre_binding_block.unwrap();
1628
1629         if candidate.next_candidate_pre_binding_block.is_some() {
1630             let fresh_block = self.cfg.start_new_block();
1631             self.false_edges(
1632                 block,
1633                 fresh_block,
1634                 candidate.next_candidate_pre_binding_block,
1635                 candidate_source_info,
1636             );
1637             block = fresh_block;
1638         }
1639
1640         self.ascribe_types(
1641             block,
1642             parent_bindings
1643                 .iter()
1644                 .flat_map(|(_, ascriptions)| ascriptions)
1645                 .chain(&candidate.ascriptions),
1646         );
1647
1648         // rust-lang/rust#27282: The `autoref` business deserves some
1649         // explanation here.
1650         //
1651         // The intent of the `autoref` flag is that when it is true,
1652         // then any pattern bindings of type T will map to a `&T`
1653         // within the context of the guard expression, but will
1654         // continue to map to a `T` in the context of the arm body. To
1655         // avoid surfacing this distinction in the user source code
1656         // (which would be a severe change to the language and require
1657         // far more revision to the compiler), when `autoref` is true,
1658         // then any occurrence of the identifier in the guard
1659         // expression will automatically get a deref op applied to it.
1660         //
1661         // So an input like:
1662         //
1663         // ```
1664         // let place = Foo::new();
1665         // match place { foo if inspect(foo)
1666         //     => feed(foo), ...  }
1667         // ```
1668         //
1669         // will be treated as if it were really something like:
1670         //
1671         // ```
1672         // let place = Foo::new();
1673         // match place { Foo { .. } if { let tmp1 = &place; inspect(*tmp1) }
1674         //     => { let tmp2 = place; feed(tmp2) }, ... }
1675         //
1676         // And an input like:
1677         //
1678         // ```
1679         // let place = Foo::new();
1680         // match place { ref mut foo if inspect(foo)
1681         //     => feed(foo), ...  }
1682         // ```
1683         //
1684         // will be treated as if it were really something like:
1685         //
1686         // ```
1687         // let place = Foo::new();
1688         // match place { Foo { .. } if { let tmp1 = & &mut place; inspect(*tmp1) }
1689         //     => { let tmp2 = &mut place; feed(tmp2) }, ... }
1690         // ```
1691         //
1692         // In short, any pattern binding will always look like *some*
1693         // kind of `&T` within the guard at least in terms of how the
1694         // MIR-borrowck views it, and this will ensure that guard
1695         // expressions cannot mutate their the match inputs via such
1696         // bindings. (It also ensures that guard expressions can at
1697         // most *copy* values from such bindings; non-Copy things
1698         // cannot be moved via pattern bindings in guard expressions.)
1699         //
1700         // ----
1701         //
1702         // Implementation notes (under assumption `autoref` is true).
1703         //
1704         // To encode the distinction above, we must inject the
1705         // temporaries `tmp1` and `tmp2`.
1706         //
1707         // There are two cases of interest: binding by-value, and binding by-ref.
1708         //
1709         // 1. Binding by-value: Things are simple.
1710         //
1711         //    * Establishing `tmp1` creates a reference into the
1712         //      matched place. This code is emitted by
1713         //      bind_matched_candidate_for_guard.
1714         //
1715         //    * `tmp2` is only initialized "lazily", after we have
1716         //      checked the guard. Thus, the code that can trigger
1717         //      moves out of the candidate can only fire after the
1718         //      guard evaluated to true. This initialization code is
1719         //      emitted by bind_matched_candidate_for_arm.
1720         //
1721         // 2. Binding by-reference: Things are tricky.
1722         //
1723         //    * Here, the guard expression wants a `&&` or `&&mut`
1724         //      into the original input. This means we need to borrow
1725         //      the reference that we create for the arm.
1726         //    * So we eagerly create the reference for the arm and then take a
1727         //      reference to that.
1728         if let Some(guard) = guard {
1729             let tcx = self.tcx;
1730             let bindings = parent_bindings
1731                 .iter()
1732                 .flat_map(|(bindings, _)| bindings)
1733                 .chain(&candidate.bindings);
1734
1735             self.bind_matched_candidate_for_guard(block, schedule_drops, bindings.clone());
1736             let guard_frame = GuardFrame {
1737                 locals: bindings.map(|b| GuardFrameLocal::new(b.var_id, b.binding_mode)).collect(),
1738             };
1739             debug!("entering guard building context: {:?}", guard_frame);
1740             self.guard_context.push(guard_frame);
1741
1742             let re_erased = tcx.lifetimes.re_erased;
1743             let scrutinee_source_info = self.source_info(scrutinee_span);
1744             for &(place, temp) in fake_borrows {
1745                 let borrow = Rvalue::Ref(re_erased, BorrowKind::Shallow, place);
1746                 self.cfg.push_assign(block, scrutinee_source_info, Place::from(temp), borrow);
1747             }
1748
1749             let (guard_span, (post_guard_block, otherwise_post_guard_block)) = match guard {
1750                 Guard::If(e) => {
1751                     let source_info = self.source_info(e.span);
1752                     (e.span, self.test_bool(block, e, source_info))
1753                 }
1754                 Guard::IfLet(pat, scrutinee) => {
1755                     let scrutinee_span = scrutinee.span;
1756                     let scrutinee_place =
1757                         unpack!(block = self.lower_scrutinee(block, scrutinee, scrutinee_span));
1758                     let mut guard_candidate = Candidate::new(scrutinee_place, &pat, false);
1759                     let wildcard = Pat::wildcard_from_ty(pat.ty);
1760                     let mut otherwise_candidate = Candidate::new(scrutinee_place, &wildcard, false);
1761                     let fake_borrow_temps = self.lower_match_tree(
1762                         block,
1763                         pat.span,
1764                         false,
1765                         &mut [&mut guard_candidate, &mut otherwise_candidate],
1766                     );
1767                     self.declare_bindings(
1768                         None,
1769                         pat.span.to(arm_span.unwrap()),
1770                         pat,
1771                         ArmHasGuard(false),
1772                         Some((Some(&scrutinee_place), scrutinee.span)),
1773                     );
1774                     let post_guard_block = self.bind_pattern(
1775                         self.source_info(pat.span),
1776                         guard_candidate,
1777                         None,
1778                         &fake_borrow_temps,
1779                         scrutinee.span,
1780                         None,
1781                         None,
1782                     );
1783                     let otherwise_post_guard_block = otherwise_candidate.pre_binding_block.unwrap();
1784                     (scrutinee_span, (post_guard_block, otherwise_post_guard_block))
1785                 }
1786             };
1787             let source_info = self.source_info(guard_span);
1788             let guard_end = self.source_info(tcx.sess.source_map().end_point(guard_span));
1789             let guard_frame = self.guard_context.pop().unwrap();
1790             debug!("Exiting guard building context with locals: {:?}", guard_frame);
1791
1792             for &(_, temp) in fake_borrows {
1793                 let cause = FakeReadCause::ForMatchGuard;
1794                 self.cfg.push_fake_read(post_guard_block, guard_end, cause, Place::from(temp));
1795             }
1796
1797             let otherwise_block = candidate.otherwise_block.unwrap_or_else(|| {
1798                 let unreachable = self.cfg.start_new_block();
1799                 self.cfg.terminate(unreachable, source_info, TerminatorKind::Unreachable);
1800                 unreachable
1801             });
1802             let outside_scope = self.cfg.start_new_block();
1803             self.exit_top_scope(otherwise_post_guard_block, outside_scope, source_info);
1804             self.false_edges(
1805                 outside_scope,
1806                 otherwise_block,
1807                 candidate.next_candidate_pre_binding_block,
1808                 source_info,
1809             );
1810
1811             // We want to ensure that the matched candidates are bound
1812             // after we have confirmed this candidate *and* any
1813             // associated guard; Binding them on `block` is too soon,
1814             // because that would be before we've checked the result
1815             // from the guard.
1816             //
1817             // But binding them on the arm is *too late*, because
1818             // then all of the candidates for a single arm would be
1819             // bound in the same place, that would cause a case like:
1820             //
1821             // ```rust
1822             // match (30, 2) {
1823             //     (mut x, 1) | (2, mut x) if { true } => { ... }
1824             //     ...                                 // ^^^^^^^ (this is `arm_block`)
1825             // }
1826             // ```
1827             //
1828             // would yield a `arm_block` something like:
1829             //
1830             // ```
1831             // StorageLive(_4);        // _4 is `x`
1832             // _4 = &mut (_1.0: i32);  // this is handling `(mut x, 1)` case
1833             // _4 = &mut (_1.1: i32);  // this is handling `(2, mut x)` case
1834             // ```
1835             //
1836             // and that is clearly not correct.
1837             let by_value_bindings = parent_bindings
1838                 .iter()
1839                 .flat_map(|(bindings, _)| bindings)
1840                 .chain(&candidate.bindings)
1841                 .filter(|binding| matches!(binding.binding_mode, BindingMode::ByValue));
1842             // Read all of the by reference bindings to ensure that the
1843             // place they refer to can't be modified by the guard.
1844             for binding in by_value_bindings.clone() {
1845                 let local_id = self.var_local_id(binding.var_id, RefWithinGuard);
1846                 let cause = FakeReadCause::ForGuardBinding;
1847                 self.cfg.push_fake_read(post_guard_block, guard_end, cause, Place::from(local_id));
1848             }
1849             assert!(schedule_drops, "patterns with guards must schedule drops");
1850             self.bind_matched_candidate_for_arm_body(post_guard_block, true, by_value_bindings);
1851
1852             post_guard_block
1853         } else {
1854             // (Here, it is not too early to bind the matched
1855             // candidate on `block`, because there is no guard result
1856             // that we have to inspect before we bind them.)
1857             self.bind_matched_candidate_for_arm_body(
1858                 block,
1859                 schedule_drops,
1860                 parent_bindings
1861                     .iter()
1862                     .flat_map(|(bindings, _)| bindings)
1863                     .chain(&candidate.bindings),
1864             );
1865             block
1866         }
1867     }
1868
1869     /// Append `AscribeUserType` statements onto the end of `block`
1870     /// for each ascription
1871     fn ascribe_types<'b>(
1872         &mut self,
1873         block: BasicBlock,
1874         ascriptions: impl IntoIterator<Item = &'b Ascription<'tcx>>,
1875     ) where
1876         'tcx: 'b,
1877     {
1878         for ascription in ascriptions {
1879             let source_info = self.source_info(ascription.span);
1880
1881             debug!(
1882                 "adding user ascription at span {:?} of place {:?} and {:?}",
1883                 source_info.span, ascription.source, ascription.user_ty,
1884             );
1885
1886             let user_ty = ascription.user_ty.clone().user_ty(
1887                 &mut self.canonical_user_type_annotations,
1888                 ascription.source.ty(&self.local_decls, self.tcx).ty,
1889                 source_info.span,
1890             );
1891             self.cfg.push(
1892                 block,
1893                 Statement {
1894                     source_info,
1895                     kind: StatementKind::AscribeUserType(
1896                         box (ascription.source, user_ty),
1897                         ascription.variance,
1898                     ),
1899                 },
1900             );
1901         }
1902     }
1903
1904     fn bind_matched_candidate_for_guard<'b>(
1905         &mut self,
1906         block: BasicBlock,
1907         schedule_drops: bool,
1908         bindings: impl IntoIterator<Item = &'b Binding<'tcx>>,
1909     ) where
1910         'tcx: 'b,
1911     {
1912         debug!("bind_matched_candidate_for_guard(block={:?})", block);
1913
1914         // Assign each of the bindings. Since we are binding for a
1915         // guard expression, this will never trigger moves out of the
1916         // candidate.
1917         let re_erased = self.tcx.lifetimes.re_erased;
1918         for binding in bindings {
1919             debug!("bind_matched_candidate_for_guard(binding={:?})", binding);
1920             let source_info = self.source_info(binding.span);
1921
1922             // For each pattern ident P of type T, `ref_for_guard` is
1923             // a reference R: &T pointing to the location matched by
1924             // the pattern, and every occurrence of P within a guard
1925             // denotes *R.
1926             let ref_for_guard = self.storage_live_binding(
1927                 block,
1928                 binding.var_id,
1929                 binding.span,
1930                 RefWithinGuard,
1931                 schedule_drops,
1932             );
1933             match binding.binding_mode {
1934                 BindingMode::ByValue => {
1935                     let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, binding.source);
1936                     self.cfg.push_assign(block, source_info, ref_for_guard, rvalue);
1937                 }
1938                 BindingMode::ByRef(borrow_kind) => {
1939                     let value_for_arm = self.storage_live_binding(
1940                         block,
1941                         binding.var_id,
1942                         binding.span,
1943                         OutsideGuard,
1944                         schedule_drops,
1945                     );
1946
1947                     let rvalue = Rvalue::Ref(re_erased, borrow_kind, binding.source);
1948                     self.cfg.push_assign(block, source_info, value_for_arm, rvalue);
1949                     let rvalue = Rvalue::Ref(re_erased, BorrowKind::Shared, value_for_arm);
1950                     self.cfg.push_assign(block, source_info, ref_for_guard, rvalue);
1951                 }
1952             }
1953         }
1954     }
1955
1956     fn bind_matched_candidate_for_arm_body<'b>(
1957         &mut self,
1958         block: BasicBlock,
1959         schedule_drops: bool,
1960         bindings: impl IntoIterator<Item = &'b Binding<'tcx>>,
1961     ) where
1962         'tcx: 'b,
1963     {
1964         debug!("bind_matched_candidate_for_arm_body(block={:?})", block);
1965
1966         let re_erased = self.tcx.lifetimes.re_erased;
1967         // Assign each of the bindings. This may trigger moves out of the candidate.
1968         for binding in bindings {
1969             let source_info = self.source_info(binding.span);
1970             let local = self.storage_live_binding(
1971                 block,
1972                 binding.var_id,
1973                 binding.span,
1974                 OutsideGuard,
1975                 schedule_drops,
1976             );
1977             if schedule_drops {
1978                 self.schedule_drop_for_binding(binding.var_id, binding.span, OutsideGuard);
1979             }
1980             let rvalue = match binding.binding_mode {
1981                 BindingMode::ByValue => Rvalue::Use(self.consume_by_copy_or_move(binding.source)),
1982                 BindingMode::ByRef(borrow_kind) => {
1983                     Rvalue::Ref(re_erased, borrow_kind, binding.source)
1984                 }
1985             };
1986             self.cfg.push_assign(block, source_info, local, rvalue);
1987         }
1988     }
1989
1990     /// Each binding (`ref mut var`/`ref var`/`mut var`/`var`, where the bound
1991     /// `var` has type `T` in the arm body) in a pattern maps to 2 locals. The
1992     /// first local is a binding for occurrences of `var` in the guard, which
1993     /// will have type `&T`. The second local is a binding for occurrences of
1994     /// `var` in the arm body, which will have type `T`.
1995     fn declare_binding(
1996         &mut self,
1997         source_info: SourceInfo,
1998         visibility_scope: SourceScope,
1999         mutability: Mutability,
2000         name: Symbol,
2001         mode: BindingMode,
2002         var_id: HirId,
2003         var_ty: Ty<'tcx>,
2004         user_ty: UserTypeProjections,
2005         has_guard: ArmHasGuard,
2006         opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
2007         pat_span: Span,
2008     ) {
2009         debug!(
2010             "declare_binding(var_id={:?}, name={:?}, mode={:?}, var_ty={:?}, \
2011              visibility_scope={:?}, source_info={:?})",
2012             var_id, name, mode, var_ty, visibility_scope, source_info
2013         );
2014
2015         let tcx = self.tcx;
2016         let debug_source_info = SourceInfo { span: source_info.span, scope: visibility_scope };
2017         let binding_mode = match mode {
2018             BindingMode::ByValue => ty::BindingMode::BindByValue(mutability),
2019             BindingMode::ByRef(_) => ty::BindingMode::BindByReference(mutability),
2020         };
2021         debug!("declare_binding: user_ty={:?}", user_ty);
2022         let local = LocalDecl::<'tcx> {
2023             mutability,
2024             ty: var_ty,
2025             user_ty: if user_ty.is_empty() { None } else { Some(box user_ty) },
2026             source_info,
2027             internal: false,
2028             is_block_tail: None,
2029             local_info: Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
2030                 VarBindingForm {
2031                     binding_mode,
2032                     // hypothetically, `visit_primary_bindings` could try to unzip
2033                     // an outermost hir::Ty as we descend, matching up
2034                     // idents in pat; but complex w/ unclear UI payoff.
2035                     // Instead, just abandon providing diagnostic info.
2036                     opt_ty_info: None,
2037                     opt_match_place,
2038                     pat_span,
2039                 },
2040             )))),
2041         };
2042         let for_arm_body = self.local_decls.push(local);
2043         self.var_debug_info.push(VarDebugInfo {
2044             name,
2045             source_info: debug_source_info,
2046             value: VarDebugInfoContents::Place(for_arm_body.into()),
2047         });
2048         let locals = if has_guard.0 {
2049             let ref_for_guard = self.local_decls.push(LocalDecl::<'tcx> {
2050                 // This variable isn't mutated but has a name, so has to be
2051                 // immutable to avoid the unused mut lint.
2052                 mutability: Mutability::Not,
2053                 ty: tcx.mk_imm_ref(tcx.lifetimes.re_erased, var_ty),
2054                 user_ty: None,
2055                 source_info,
2056                 internal: false,
2057                 is_block_tail: None,
2058                 local_info: Some(box LocalInfo::User(ClearCrossCrate::Set(
2059                     BindingForm::RefForGuard,
2060                 ))),
2061             });
2062             self.var_debug_info.push(VarDebugInfo {
2063                 name,
2064                 source_info: debug_source_info,
2065                 value: VarDebugInfoContents::Place(ref_for_guard.into()),
2066             });
2067             LocalsForNode::ForGuard { ref_for_guard, for_arm_body }
2068         } else {
2069             LocalsForNode::One(for_arm_body)
2070         };
2071         debug!("declare_binding: vars={:?}", locals);
2072         self.var_indices.insert(var_id, locals);
2073     }
2074 }