]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/matches/mod.rs
Rollup merge of #57312 - Mendess2526:master, r=Centril
[rust.git] / src / librustc_mir / build / matches / mod.rs
1 //! Code related to match expressions. These are sufficiently complex
2 //! to warrant their own module and submodules. :) This main module
3 //! includes the high-level algorithm, the submodules contain the
4 //! details.
5
6 use build::scope::{CachedBlock, DropKind};
7 use build::ForGuard::{self, OutsideGuard, RefWithinGuard, ValWithinGuard};
8 use build::{BlockAnd, BlockAndExtension, Builder};
9 use build::{GuardFrame, GuardFrameLocal, LocalsForNode};
10 use hair::*;
11 use rustc::mir::*;
12 use rustc::ty::{self, Ty};
13 use rustc::ty::layout::VariantIdx;
14 use rustc_data_structures::bit_set::BitSet;
15 use rustc_data_structures::fx::FxHashMap;
16 use syntax::ast::{Name, NodeId};
17 use syntax_pos::Span;
18
19 // helper functions, broken out by category:
20 mod simplify;
21 mod test;
22 mod util;
23
24 use std::convert::TryFrom;
25
26 /// ArmHasGuard is isomorphic to a boolean flag. It indicates whether
27 /// a match arm has a guard expression attached to it.
28 #[derive(Copy, Clone, Debug)]
29 pub(crate) struct ArmHasGuard(pub bool);
30
31 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
32     pub fn match_expr(
33         &mut self,
34         destination: &Place<'tcx>,
35         span: Span,
36         mut block: BasicBlock,
37         discriminant: ExprRef<'tcx>,
38         arms: Vec<Arm<'tcx>>,
39     ) -> BlockAnd<()> {
40         let tcx = self.hir.tcx();
41         let discriminant_span = discriminant.span();
42         let discriminant_place = unpack!(block = self.as_place(block, discriminant));
43
44         // Matching on a `discriminant_place` with an uninhabited type doesn't
45         // generate any memory reads by itself, and so if the place "expression"
46         // contains unsafe operations like raw pointer dereferences or union
47         // field projections, we wouldn't know to require an `unsafe` block
48         // around a `match` equivalent to `std::intrinsics::unreachable()`.
49         // See issue #47412 for this hole being discovered in the wild.
50         //
51         // HACK(eddyb) Work around the above issue by adding a dummy inspection
52         // of `discriminant_place`, specifically by applying `ReadForMatch`.
53         //
54         // NOTE: ReadForMatch also checks that the discriminant is initialized.
55         // This is currently needed to not allow matching on an uninitialized,
56         // uninhabited value. If we get never patterns, those will check that
57         // the place is initialized, and so this read would only be used to
58         // check safety.
59
60         let source_info = self.source_info(discriminant_span);
61         self.cfg.push(block, Statement {
62             source_info,
63             kind: StatementKind::FakeRead(
64                 FakeReadCause::ForMatchedPlace,
65                 discriminant_place.clone(),
66             ),
67         });
68
69         let mut arm_blocks = ArmBlocks {
70             blocks: arms.iter().map(|_| self.cfg.start_new_block()).collect(),
71         };
72
73         // Get the arm bodies and their scopes, while declaring bindings.
74         let arm_bodies: Vec<_> = arms.iter()
75             .map(|arm| {
76                 // BUG: use arm lint level
77                 let body = self.hir.mirror(arm.body.clone());
78                 let scope = self.declare_bindings(
79                     None,
80                     body.span,
81                     LintLevel::Inherited,
82                     &arm.patterns[..],
83                     ArmHasGuard(arm.guard.is_some()),
84                     Some((Some(&discriminant_place), discriminant_span)),
85                 );
86                 (body, scope.unwrap_or(self.source_scope))
87             })
88             .collect();
89
90         // create binding start block for link them by false edges
91         let candidate_count = arms.iter().map(|c| c.patterns.len()).sum::<usize>();
92         let pre_binding_blocks: Vec<_> = (0..=candidate_count)
93             .map(|_| self.cfg.start_new_block())
94             .collect();
95
96         let mut has_guard = false;
97
98         // assemble a list of candidates: there is one candidate per
99         // pattern, which means there may be more than one candidate
100         // *per arm*. These candidates are kept sorted such that the
101         // highest priority candidate comes first in the list.
102         // (i.e., same order as in source)
103
104         let candidates: Vec<_> = arms.iter()
105             .enumerate()
106             .flat_map(|(arm_index, arm)| {
107                 arm.patterns
108                     .iter()
109                     .enumerate()
110                     .map(move |(pat_index, pat)| (arm_index, pat_index, pat, arm.guard.clone()))
111             })
112             .zip(
113                 pre_binding_blocks
114                     .iter()
115                     .zip(pre_binding_blocks.iter().skip(1)),
116             )
117             .map(
118                 |(
119                     (arm_index, pat_index, pattern, guard),
120                     (pre_binding_block, next_candidate_pre_binding_block)
121                 )| {
122                     has_guard |= guard.is_some();
123
124                     // One might ask: why not build up the match pair such that it
125                     // matches via `borrowed_input_temp.deref()` instead of
126                     // using the `discriminant_place` directly, as it is doing here?
127                     //
128                     // The basic answer is that if you do that, then you end up with
129                     // accceses to a shared borrow of the input and that conflicts with
130                     // any arms that look like e.g.
131                     //
132                     // match Some(&4) {
133                     //     ref mut foo => {
134                     //         ... /* mutate `foo` in arm body */ ...
135                     //     }
136                     // }
137                     //
138                     // (Perhaps we could further revise the MIR
139                     //  construction here so that it only does a
140                     //  shared borrow at the outset and delays doing
141                     //  the mutable borrow until after the pattern is
142                     //  matched *and* the guard (if any) for the arm
143                     //  has been run.)
144
145                     Candidate {
146                         span: pattern.span,
147                         match_pairs: vec![MatchPair::new(discriminant_place.clone(), pattern)],
148                         bindings: vec![],
149                         ascriptions: vec![],
150                         guard,
151                         arm_index,
152                         pat_index,
153                         pre_binding_block: *pre_binding_block,
154                         next_candidate_pre_binding_block: *next_candidate_pre_binding_block,
155                     }
156                 },
157             )
158             .collect();
159
160         let outer_source_info = self.source_info(span);
161         self.cfg.terminate(
162             *pre_binding_blocks.last().unwrap(),
163             outer_source_info,
164             TerminatorKind::Unreachable,
165         );
166
167         // Maps a place to the kind of Fake borrow that we want to perform on
168         // it: either Shallow or Shared, depending on whether the place is
169         // bound in the match, or just switched on.
170         // If there are no match guards then we don't need any fake borrows,
171         // so don't track them.
172         let mut fake_borrows = if has_guard && tcx.generate_borrow_of_any_match_input() {
173             Some(FxHashMap::default())
174         } else {
175             None
176         };
177
178         let pre_binding_blocks: Vec<_> = candidates
179             .iter()
180             .map(|cand| (cand.pre_binding_block, cand.span))
181             .collect();
182
183         // this will generate code to test discriminant_place and
184         // branch to the appropriate arm block
185         let otherwise = self.match_candidates(
186             discriminant_span,
187             &mut arm_blocks,
188             candidates,
189             block,
190             &mut fake_borrows,
191         );
192
193         if !otherwise.is_empty() {
194             // All matches are exhaustive. However, because some matches
195             // only have exponentially-large exhaustive decision trees, we
196             // sometimes generate an inexhaustive decision tree.
197             //
198             // In that case, the inexhaustive tips of the decision tree
199             // can't be reached - terminate them with an `unreachable`.
200             let source_info = self.source_info(span);
201
202             let mut otherwise = otherwise;
203             otherwise.sort();
204             otherwise.dedup(); // variant switches can introduce duplicate target blocks
205             for block in otherwise {
206                 self.cfg
207                     .terminate(block, source_info, TerminatorKind::Unreachable);
208             }
209         }
210
211         if let Some(fake_borrows) = fake_borrows {
212             self.add_fake_borrows(&pre_binding_blocks, fake_borrows, source_info, block);
213         }
214
215         // all the arm blocks will rejoin here
216         let end_block = self.cfg.start_new_block();
217
218         let outer_source_info = self.source_info(span);
219         for (arm_index, (body, source_scope)) in arm_bodies.into_iter().enumerate() {
220             let mut arm_block = arm_blocks.blocks[arm_index];
221             // Re-enter the source scope we created the bindings in.
222             self.source_scope = source_scope;
223             unpack!(arm_block = self.into(destination, arm_block, body));
224             self.cfg.terminate(
225                 arm_block,
226                 outer_source_info,
227                 TerminatorKind::Goto { target: end_block },
228             );
229         }
230         self.source_scope = outer_source_info.scope;
231
232         end_block.unit()
233     }
234
235     pub(super) fn expr_into_pattern(
236         &mut self,
237         mut block: BasicBlock,
238         irrefutable_pat: Pattern<'tcx>,
239         initializer: ExprRef<'tcx>,
240     ) -> BlockAnd<()> {
241         match *irrefutable_pat.kind {
242             // Optimize the case of `let x = ...` to write directly into `x`
243             PatternKind::Binding {
244                 mode: BindingMode::ByValue,
245                 var,
246                 subpattern: None,
247                 ..
248             } => {
249                 let place =
250                     self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard);
251                 unpack!(block = self.into(&place, block, initializer));
252
253
254                 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
255                 let source_info = self.source_info(irrefutable_pat.span);
256                 self.cfg.push(
257                     block,
258                     Statement {
259                         source_info,
260                         kind: StatementKind::FakeRead(FakeReadCause::ForLet, place),
261                     },
262                 );
263
264                 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
265                 block.unit()
266             }
267
268             // Optimize the case of `let x: T = ...` to write directly
269             // into `x` and then require that `T == typeof(x)`.
270             //
271             // Weirdly, this is needed to prevent the
272             // `intrinsic-move-val.rs` test case from crashing. That
273             // test works with uninitialized values in a rather
274             // dubious way, so it may be that the test is kind of
275             // broken.
276             PatternKind::AscribeUserType {
277                 subpattern: Pattern {
278                     kind: box PatternKind::Binding {
279                         mode: BindingMode::ByValue,
280                         var,
281                         subpattern: None,
282                         ..
283                     },
284                     ..
285                 },
286                 user_ty: pat_ascription_ty,
287                 user_ty_span,
288             } => {
289                 let place =
290                     self.storage_live_binding(block, var, irrefutable_pat.span, OutsideGuard);
291                 unpack!(block = self.into(&place, block, initializer));
292
293                 // Inject a fake read, see comments on `FakeReadCause::ForLet`.
294                 let pattern_source_info = self.source_info(irrefutable_pat.span);
295                 self.cfg.push(
296                     block,
297                     Statement {
298                         source_info: pattern_source_info,
299                         kind: StatementKind::FakeRead(FakeReadCause::ForLet, place.clone()),
300                     },
301                 );
302
303                 let ty_source_info = self.source_info(user_ty_span);
304                 let user_ty = box pat_ascription_ty.user_ty(
305                     &mut self.canonical_user_type_annotations, ty_source_info.span
306                 );
307                 self.cfg.push(
308                     block,
309                     Statement {
310                         source_info: ty_source_info,
311                         kind: StatementKind::AscribeUserType(
312                             place,
313                             ty::Variance::Invariant,
314                             user_ty,
315                         ),
316                     },
317                 );
318
319                 self.schedule_drop_for_binding(var, irrefutable_pat.span, OutsideGuard);
320                 block.unit()
321             }
322             _ => {
323                 let place = unpack!(block = self.as_place(block, initializer));
324                 self.place_into_pattern(block, irrefutable_pat, &place, true)
325             }
326         }
327     }
328
329     pub fn place_into_pattern(
330         &mut self,
331         block: BasicBlock,
332         irrefutable_pat: Pattern<'tcx>,
333         initializer: &Place<'tcx>,
334         set_match_place: bool,
335     ) -> BlockAnd<()> {
336         // create a dummy candidate
337         let mut candidate = Candidate {
338             span: irrefutable_pat.span,
339             match_pairs: vec![MatchPair::new(initializer.clone(), &irrefutable_pat)],
340             bindings: vec![],
341             ascriptions: vec![],
342             guard: None,
343
344             // since we don't call `match_candidates`, next fields is unused
345             arm_index: 0,
346             pat_index: 0,
347             pre_binding_block: block,
348             next_candidate_pre_binding_block: block,
349         };
350
351         // Simplify the candidate. Since the pattern is irrefutable, this should
352         // always convert all match-pairs into bindings.
353         self.simplify_candidate(&mut candidate);
354
355         if !candidate.match_pairs.is_empty() {
356             span_bug!(
357                 candidate.match_pairs[0].pattern.span,
358                 "match pairs {:?} remaining after simplifying \
359                  irrefutable pattern",
360                 candidate.match_pairs
361             );
362         }
363
364         // for matches and function arguments, the place that is being matched
365         // can be set when creating the variables. But the place for
366         // let PATTERN = ... might not even exist until we do the assignment.
367         // so we set it here instead
368         if set_match_place {
369             for binding in &candidate.bindings {
370                 let local = self.var_local_id(binding.var_id, OutsideGuard);
371
372                 if let Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
373                     opt_match_place: Some((ref mut match_place, _)),
374                     ..
375                 }))) = self.local_decls[local].is_user_variable
376                 {
377                     *match_place = Some(initializer.clone());
378                 } else {
379                     bug!("Let binding to non-user variable.")
380                 }
381             }
382         }
383
384         self.ascribe_types(block, &candidate.ascriptions);
385
386         // now apply the bindings, which will also declare the variables
387         self.bind_matched_candidate_for_arm_body(block, &candidate.bindings);
388
389         block.unit()
390     }
391
392     /// Declares the bindings of the given patterns and returns the visibility
393     /// scope for the bindings in these patterns, if such a scope had to be
394     /// created. NOTE: Declaring the bindings should always be done in their
395     /// drop scope.
396     pub fn declare_bindings(
397         &mut self,
398         mut visibility_scope: Option<SourceScope>,
399         scope_span: Span,
400         lint_level: LintLevel,
401         patterns: &[Pattern<'tcx>],
402         has_guard: ArmHasGuard,
403         opt_match_place: Option<(Option<&Place<'tcx>>, Span)>,
404     ) -> Option<SourceScope> {
405         assert!(
406             !(visibility_scope.is_some() && lint_level.is_explicit()),
407             "can't have both a visibility and a lint scope at the same time"
408         );
409         let mut scope = self.source_scope;
410         let num_patterns = patterns.len();
411         debug!("declare_bindings: patterns={:?}", patterns);
412         self.visit_bindings(
413             &patterns[0],
414             UserTypeProjections::none(),
415             &mut |this, mutability, name, mode, var, span, ty, user_ty| {
416                 if visibility_scope.is_none() {
417                     visibility_scope =
418                         Some(this.new_source_scope(scope_span, LintLevel::Inherited, None));
419                     // If we have lints, create a new source scope
420                     // that marks the lints for the locals. See the comment
421                     // on the `source_info` field for why this is needed.
422                     if lint_level.is_explicit() {
423                         scope = this.new_source_scope(scope_span, lint_level, None);
424                     }
425                 }
426                 let source_info = SourceInfo { span, scope };
427                 let visibility_scope = visibility_scope.unwrap();
428                 this.declare_binding(
429                     source_info,
430                     visibility_scope,
431                     mutability,
432                     name,
433                     mode,
434                     num_patterns,
435                     var,
436                     ty,
437                     user_ty,
438                     has_guard,
439                     opt_match_place.map(|(x, y)| (x.cloned(), y)),
440                     patterns[0].span,
441                 );
442             },
443         );
444         visibility_scope
445     }
446
447     pub fn storage_live_binding(
448         &mut self,
449         block: BasicBlock,
450         var: NodeId,
451         span: Span,
452         for_guard: ForGuard,
453     ) -> Place<'tcx> {
454         let local_id = self.var_local_id(var, for_guard);
455         let source_info = self.source_info(span);
456         self.cfg.push(
457             block,
458             Statement {
459                 source_info,
460                 kind: StatementKind::StorageLive(local_id),
461             },
462         );
463         let place = Place::Local(local_id);
464         let var_ty = self.local_decls[local_id].ty;
465         let hir_id = self.hir.tcx().hir().node_to_hir_id(var);
466         let region_scope = self.hir.region_scope_tree.var_scope(hir_id.local_id);
467         self.schedule_drop(span, region_scope, &place, var_ty, DropKind::Storage);
468         place
469     }
470
471     pub fn schedule_drop_for_binding(&mut self, var: NodeId, span: Span, for_guard: ForGuard) {
472         let local_id = self.var_local_id(var, for_guard);
473         let var_ty = self.local_decls[local_id].ty;
474         let hir_id = self.hir.tcx().hir().node_to_hir_id(var);
475         let region_scope = self.hir.region_scope_tree.var_scope(hir_id.local_id);
476         self.schedule_drop(
477             span,
478             region_scope,
479             &Place::Local(local_id),
480             var_ty,
481             DropKind::Value {
482                 cached_block: CachedBlock::default(),
483             },
484         );
485     }
486
487     pub(super) fn visit_bindings(
488         &mut self,
489         pattern: &Pattern<'tcx>,
490         pattern_user_ty: UserTypeProjections<'tcx>,
491         f: &mut impl FnMut(
492             &mut Self,
493             Mutability,
494             Name,
495             BindingMode,
496             NodeId,
497             Span,
498             Ty<'tcx>,
499             UserTypeProjections<'tcx>,
500         ),
501     ) {
502         debug!("visit_bindings: pattern={:?} pattern_user_ty={:?}", pattern, pattern_user_ty);
503         match *pattern.kind {
504             PatternKind::Binding {
505                 mutability,
506                 name,
507                 mode,
508                 var,
509                 ty,
510                 ref subpattern,
511                 ..
512             } => {
513                 f(self, mutability, name, mode, var, pattern.span, ty, pattern_user_ty.clone());
514                 if let Some(subpattern) = subpattern.as_ref() {
515                     self.visit_bindings(subpattern, pattern_user_ty, f);
516                 }
517             }
518             PatternKind::Array {
519                 ref prefix,
520                 ref slice,
521                 ref suffix,
522             }
523             | PatternKind::Slice {
524                 ref prefix,
525                 ref slice,
526                 ref suffix,
527             } => {
528                 let from = u32::try_from(prefix.len()).unwrap();
529                 let to = u32::try_from(suffix.len()).unwrap();
530                 for subpattern in prefix {
531                     self.visit_bindings(subpattern, pattern_user_ty.clone().index(), f);
532                 }
533                 for subpattern in slice {
534                     self.visit_bindings(subpattern, pattern_user_ty.clone().subslice(from, to), f);
535                 }
536                 for subpattern in suffix {
537                     self.visit_bindings(subpattern, pattern_user_ty.clone().index(), f);
538                 }
539             }
540             PatternKind::Constant { .. } | PatternKind::Range { .. } | PatternKind::Wild => {}
541             PatternKind::Deref { ref subpattern } => {
542                 self.visit_bindings(subpattern, pattern_user_ty.deref(), f);
543             }
544             PatternKind::AscribeUserType { ref subpattern, ref user_ty, user_ty_span } => {
545                 // This corresponds to something like
546                 //
547                 // ```
548                 // let A::<'a>(_): A<'static> = ...;
549                 // ```
550                 let annotation = (user_ty_span, user_ty.base);
551                 let projection = UserTypeProjection {
552                     base: self.canonical_user_type_annotations.push(annotation),
553                     projs: user_ty.projs.clone(),
554                 };
555                 let subpattern_user_ty = pattern_user_ty.push_projection(&projection, user_ty_span);
556                 self.visit_bindings(subpattern, subpattern_user_ty, f)
557             }
558
559             PatternKind::Leaf { ref subpatterns } => {
560                 for subpattern in subpatterns {
561                     let subpattern_user_ty = pattern_user_ty.clone().leaf(subpattern.field);
562                     debug!("visit_bindings: subpattern_user_ty={:?}", subpattern_user_ty);
563                     self.visit_bindings(&subpattern.pattern, subpattern_user_ty, f);
564                 }
565             }
566
567             PatternKind::Variant { adt_def, substs: _, variant_index, ref subpatterns } => {
568                 for subpattern in subpatterns {
569                     let subpattern_user_ty = pattern_user_ty.clone().variant(
570                         adt_def, variant_index, subpattern.field);
571                     self.visit_bindings(&subpattern.pattern, subpattern_user_ty, f);
572                 }
573             }
574         }
575     }
576 }
577
578 /// List of blocks for each arm (and potentially other metadata in the
579 /// future).
580 struct ArmBlocks {
581     blocks: Vec<BasicBlock>,
582 }
583
584 #[derive(Clone, Debug)]
585 pub struct Candidate<'pat, 'tcx: 'pat> {
586     // span of the original pattern that gave rise to this candidate
587     span: Span,
588
589     // all of these must be satisfied...
590     match_pairs: Vec<MatchPair<'pat, 'tcx>>,
591
592     // ...these bindings established...
593     bindings: Vec<Binding<'tcx>>,
594
595     // ...these types asserted...
596     ascriptions: Vec<Ascription<'tcx>>,
597
598     // ...and the guard must be evaluated...
599     guard: Option<Guard<'tcx>>,
600
601     // ...and then we branch to arm with this index.
602     arm_index: usize,
603
604     // ...and the blocks for add false edges between candidates
605     pre_binding_block: BasicBlock,
606     next_candidate_pre_binding_block: BasicBlock,
607
608     // This uniquely identifies this candidate *within* the arm.
609     pat_index: usize,
610 }
611
612 #[derive(Clone, Debug)]
613 struct Binding<'tcx> {
614     span: Span,
615     source: Place<'tcx>,
616     name: Name,
617     var_id: NodeId,
618     var_ty: Ty<'tcx>,
619     mutability: Mutability,
620     binding_mode: BindingMode<'tcx>,
621 }
622
623 /// Indicates that the type of `source` must be a subtype of the
624 /// user-given type `user_ty`; this is basically a no-op but can
625 /// influence region inference.
626 #[derive(Clone, Debug)]
627 struct Ascription<'tcx> {
628     span: Span,
629     source: Place<'tcx>,
630     user_ty: PatternTypeProjection<'tcx>,
631 }
632
633 #[derive(Clone, Debug)]
634 pub struct MatchPair<'pat, 'tcx: 'pat> {
635     // this place...
636     place: Place<'tcx>,
637
638     // ... must match this pattern.
639     pattern: &'pat Pattern<'tcx>,
640
641     // HACK(eddyb) This is used to toggle whether a Slice pattern
642     // has had its length checked. This is only necessary because
643     // the "rest" part of the pattern right now has type &[T] and
644     // as such, it requires an Rvalue::Slice to be generated.
645     // See RFC 495 / issue #23121 for the eventual (proper) solution.
646     slice_len_checked: bool,
647 }
648
649 #[derive(Clone, Debug, PartialEq)]
650 enum TestKind<'tcx> {
651     // test the branches of enum
652     Switch {
653         adt_def: &'tcx ty::AdtDef,
654         variants: BitSet<VariantIdx>,
655     },
656
657     // test the branches of enum
658     SwitchInt {
659         switch_ty: Ty<'tcx>,
660         options: Vec<u128>,
661         indices: FxHashMap<ty::Const<'tcx>, usize>,
662     },
663
664     // test for equality
665     Eq {
666         value: ty::Const<'tcx>,
667         ty: Ty<'tcx>,
668     },
669
670     // test whether the value falls within an inclusive or exclusive range
671     Range(PatternRange<'tcx>),
672
673     // test length of the slice is equal to len
674     Len {
675         len: u64,
676         op: BinOp,
677     },
678 }
679
680 #[derive(Debug)]
681 pub struct Test<'tcx> {
682     span: Span,
683     kind: TestKind<'tcx>,
684 }
685
686 ///////////////////////////////////////////////////////////////////////////
687 // Main matching algorithm
688
689 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
690     /// The main match algorithm. It begins with a set of candidates
691     /// `candidates` and has the job of generating code to determine
692     /// which of these candidates, if any, is the correct one. The
693     /// candidates are sorted such that the first item in the list
694     /// has the highest priority. When a candidate is found to match
695     /// the value, we will generate a branch to the appropriate
696     /// block found in `arm_blocks`.
697     ///
698     /// The return value is a list of "otherwise" blocks. These are
699     /// points in execution where we found that *NONE* of the
700     /// candidates apply.  In principle, this means that the input
701     /// list was not exhaustive, though at present we sometimes are
702     /// not smart enough to recognize all exhaustive inputs.
703     ///
704     /// It might be surprising that the input can be inexhaustive.
705     /// Indeed, initially, it is not, because all matches are
706     /// exhaustive in Rust. But during processing we sometimes divide
707     /// up the list of candidates and recurse with a non-exhaustive
708     /// list. This is important to keep the size of the generated code
709     /// under control. See `test_candidates` for more details.
710     ///
711     /// If `add_fake_borrows` is true, then places which need fake borrows
712     /// will be added to it.
713     fn match_candidates<'pat>(
714         &mut self,
715         span: Span,
716         arm_blocks: &mut ArmBlocks,
717         mut candidates: Vec<Candidate<'pat, 'tcx>>,
718         mut block: BasicBlock,
719         fake_borrows: &mut Option<FxHashMap<Place<'tcx>, BorrowKind>>,
720     ) -> Vec<BasicBlock> {
721         debug!(
722             "matched_candidate(span={:?}, block={:?}, candidates={:?})",
723             span, block, candidates
724         );
725
726         // Start by simplifying candidates. Once this process is
727         // complete, all the match pairs which remain require some
728         // form of test, whether it be a switch or pattern comparison.
729         for candidate in &mut candidates {
730             self.simplify_candidate(candidate);
731         }
732
733         // The candidates are sorted by priority. Check to see
734         // whether the higher priority candidates (and hence at
735         // the front of the vec) have satisfied all their match
736         // pairs.
737         let fully_matched = candidates
738             .iter()
739             .take_while(|c| c.match_pairs.is_empty())
740             .count();
741         debug!(
742             "match_candidates: {:?} candidates fully matched",
743             fully_matched
744         );
745         let mut unmatched_candidates = candidates.split_off(fully_matched);
746
747         // Insert a *Shared* borrow of any places that are bound.
748         if let Some(fake_borrows) = fake_borrows {
749             for Binding { source, .. }
750                 in candidates.iter().flat_map(|candidate| &candidate.bindings)
751             {
752                 fake_borrows.insert(source.clone(), BorrowKind::Shared);
753             }
754         }
755
756         let fully_matched_with_guard = candidates.iter().take_while(|c| c.guard.is_some()).count();
757
758         let unreachable_candidates = if fully_matched_with_guard + 1 < candidates.len() {
759             candidates.split_off(fully_matched_with_guard + 1)
760         } else {
761             vec![]
762         };
763
764         for candidate in candidates {
765             // If so, apply any bindings, test the guard (if any), and
766             // branch to the arm.
767             if let Some(b) = self.bind_and_guard_matched_candidate(block, arm_blocks, candidate) {
768                 block = b;
769             } else {
770                 // if None is returned, then any remaining candidates
771                 // are unreachable (at least not through this path).
772                 // Link them with false edges.
773                 debug!(
774                     "match_candidates: add false edges for unreachable {:?} and unmatched {:?}",
775                     unreachable_candidates, unmatched_candidates
776                 );
777                 for candidate in unreachable_candidates {
778                     let source_info = self.source_info(candidate.span);
779                     let target = self.cfg.start_new_block();
780                     if let Some(otherwise) =
781                         self.bind_and_guard_matched_candidate(target, arm_blocks, candidate)
782                     {
783                         self.cfg
784                             .terminate(otherwise, source_info, TerminatorKind::Unreachable);
785                     }
786                 }
787
788                 if unmatched_candidates.is_empty() {
789                     return vec![];
790                 } else {
791                     let target = self.cfg.start_new_block();
792                     return self.match_candidates(
793                         span,
794                         arm_blocks,
795                         unmatched_candidates,
796                         target,
797                         &mut None,
798                     );
799                 }
800             }
801         }
802
803         // If there are no candidates that still need testing, we're done.
804         // Since all matches are exhaustive, execution should never reach this point.
805         if unmatched_candidates.is_empty() {
806             return vec![block];
807         }
808
809         // Test candidates where possible.
810         let (otherwise, tested_candidates) =
811             self.test_candidates(span, arm_blocks, &unmatched_candidates, block, fake_borrows);
812
813         // If the target candidates were exhaustive, then we are done.
814         // But for borrowck continue build decision tree.
815
816         // If all candidates were sorted into `target_candidates` somewhere, then
817         // the initial set was inexhaustive.
818         let untested_candidates = unmatched_candidates.split_off(tested_candidates);
819         if untested_candidates.len() == 0 {
820             return otherwise;
821         }
822
823         // Otherwise, let's process those remaining candidates.
824         let join_block = self.join_otherwise_blocks(span, otherwise);
825         self.match_candidates(span, arm_blocks, untested_candidates, join_block, &mut None)
826     }
827
828     fn join_otherwise_blocks(&mut self, span: Span, mut otherwise: Vec<BasicBlock>) -> BasicBlock {
829         let source_info = self.source_info(span);
830         otherwise.sort();
831         otherwise.dedup(); // variant switches can introduce duplicate target blocks
832         if otherwise.len() == 1 {
833             otherwise[0]
834         } else {
835             let join_block = self.cfg.start_new_block();
836             for block in otherwise {
837                 self.cfg.terminate(
838                     block,
839                     source_info,
840                     TerminatorKind::Goto { target: join_block },
841                 );
842             }
843             join_block
844         }
845     }
846
847     /// This is the most subtle part of the matching algorithm.  At
848     /// this point, the input candidates have been fully simplified,
849     /// and so we know that all remaining match-pairs require some
850     /// sort of test. To decide what test to do, we take the highest
851     /// priority candidate (last one in the list) and extract the
852     /// first match-pair from the list. From this we decide what kind
853     /// of test is needed using `test`, defined in the `test` module.
854     ///
855     /// *Note:* taking the first match pair is somewhat arbitrary, and
856     /// we might do better here by choosing more carefully what to
857     /// test.
858     ///
859     /// For example, consider the following possible match-pairs:
860     ///
861     /// 1. `x @ Some(P)` -- we will do a `Switch` to decide what variant `x` has
862     /// 2. `x @ 22` -- we will do a `SwitchInt`
863     /// 3. `x @ 3..5` -- we will do a range test
864     /// 4. etc.
865     ///
866     /// Once we know what sort of test we are going to perform, this
867     /// test may also help us with other candidates. So we walk over
868     /// the candidates (from high to low priority) and check. This
869     /// gives us, for each outcome of the test, a transformed list of
870     /// candidates.  For example, if we are testing the current
871     /// variant of `x.0`, and we have a candidate `{x.0 @ Some(v), x.1
872     /// @ 22}`, then we would have a resulting candidate of `{(x.0 as
873     /// Some).0 @ v, x.1 @ 22}`. Note that the first match-pair is now
874     /// simpler (and, in fact, irrefutable).
875     ///
876     /// But there may also be candidates that the test just doesn't
877     /// apply to. The classical example involves wildcards:
878     ///
879     /// ```
880     /// # let (x, y, z) = (true, true, true);
881     /// match (x, y, z) {
882     ///     (true, _, true) => true,    // (0)
883     ///     (_, true, _) => true,       // (1)
884     ///     (false, false, _) => false, // (2)
885     ///     (true, _, false) => false,  // (3)
886     /// }
887     /// ```
888     ///
889     /// In that case, after we test on `x`, there are 2 overlapping candidate
890     /// sets:
891     ///
892     /// - If the outcome is that `x` is true, candidates 0, 1, and 3
893     /// - If the outcome is that `x` is false, candidates 1 and 2
894     ///
895     /// Here, the traditional "decision tree" method would generate 2
896     /// separate code-paths for the 2 separate cases.
897     ///
898     /// In some cases, this duplication can create an exponential amount of
899     /// code. This is most easily seen by noticing that this method terminates
900     /// with precisely the reachable arms being reachable - but that problem
901     /// is trivially NP-complete:
902     ///
903     /// ```rust
904     ///     match (var0, var1, var2, var3, ..) {
905     ///         (true, _, _, false, true, ...) => false,
906     ///         (_, true, true, false, _, ...) => false,
907     ///         (false, _, false, false, _, ...) => false,
908     ///         ...
909     ///         _ => true
910     ///     }
911     /// ```
912     ///
913     /// Here the last arm is reachable only if there is an assignment to
914     /// the variables that does not match any of the literals. Therefore,
915     /// compilation would take an exponential amount of time in some cases.
916     ///
917     /// That kind of exponential worst-case might not occur in practice, but
918     /// our simplistic treatment of constants and guards would make it occur
919     /// in very common situations - for example #29740:
920     ///
921     /// ```rust
922     /// match x {
923     ///     "foo" if foo_guard => ...,
924     ///     "bar" if bar_guard => ...,
925     ///     "baz" if baz_guard => ...,
926     ///     ...
927     /// }
928     /// ```
929     ///
930     /// Here we first test the match-pair `x @ "foo"`, which is an `Eq` test.
931     ///
932     /// It might seem that we would end up with 2 disjoint candidate
933     /// sets, consisting of the first candidate or the other 3, but our
934     /// algorithm doesn't reason about "foo" being distinct from the other
935     /// constants; it considers the latter arms to potentially match after
936     /// both outcomes, which obviously leads to an exponential amount
937     /// of tests.
938     ///
939     /// To avoid these kinds of problems, our algorithm tries to ensure
940     /// the amount of generated tests is linear. When we do a k-way test,
941     /// we return an additional "unmatched" set alongside the obvious `k`
942     /// sets. When we encounter a candidate that would be present in more
943     /// than one of the sets, we put it and all candidates below it into the
944     /// "unmatched" set. This ensures these `k+1` sets are disjoint.
945     ///
946     /// After we perform our test, we branch into the appropriate candidate
947     /// set and recurse with `match_candidates`. These sub-matches are
948     /// obviously inexhaustive - as we discarded our otherwise set - so
949     /// we set their continuation to do `match_candidates` on the
950     /// "unmatched" set (which is again inexhaustive).
951     ///
952     /// If you apply this to the above test, you basically wind up
953     /// with an if-else-if chain, testing each candidate in turn,
954     /// which is precisely what we want.
955     ///
956     /// In addition to avoiding exponential-time blowups, this algorithm
957     /// also has nice property that each guard and arm is only generated
958     /// once.
959     fn test_candidates<'pat>(
960         &mut self,
961         span: Span,
962         arm_blocks: &mut ArmBlocks,
963         candidates: &[Candidate<'pat, 'tcx>],
964         block: BasicBlock,
965         fake_borrows: &mut Option<FxHashMap<Place<'tcx>, BorrowKind>>,
966     ) -> (Vec<BasicBlock>, usize) {
967         // extract the match-pair from the highest priority candidate
968         let match_pair = &candidates.first().unwrap().match_pairs[0];
969         let mut test = self.test(match_pair);
970
971         // most of the time, the test to perform is simply a function
972         // of the main candidate; but for a test like SwitchInt, we
973         // may want to add cases based on the candidates that are
974         // available
975         match test.kind {
976             TestKind::SwitchInt {
977                 switch_ty,
978                 ref mut options,
979                 ref mut indices,
980             } => {
981                 for candidate in candidates.iter() {
982                     if !self.add_cases_to_switch(
983                         &match_pair.place,
984                         candidate,
985                         switch_ty,
986                         options,
987                         indices,
988                     ) {
989                         break;
990                     }
991                 }
992             }
993             TestKind::Switch {
994                 adt_def: _,
995                 ref mut variants,
996             } => {
997                 for candidate in candidates.iter() {
998                     if !self.add_variants_to_switch(&match_pair.place, candidate, variants) {
999                         break;
1000                     }
1001                 }
1002             }
1003             _ => {}
1004         }
1005
1006         // Insert a Shallow borrow of any places that is switched on.
1007         fake_borrows.as_mut().map(|fb| {
1008             fb.entry(match_pair.place.clone()).or_insert(BorrowKind::Shallow)
1009         });
1010
1011         // perform the test, branching to one of N blocks. For each of
1012         // those N possible outcomes, create a (initially empty)
1013         // vector of candidates. Those are the candidates that still
1014         // apply if the test has that particular outcome.
1015         debug!(
1016             "match_candidates: test={:?} match_pair={:?}",
1017             test, match_pair
1018         );
1019         let target_blocks = self.perform_test(block, &match_pair.place, &test);
1020         let mut target_candidates = vec![vec![]; target_blocks.len()];
1021
1022         // Sort the candidates into the appropriate vector in
1023         // `target_candidates`. Note that at some point we may
1024         // encounter a candidate where the test is not relevant; at
1025         // that point, we stop sorting.
1026         let tested_candidates = candidates
1027             .iter()
1028             .take_while(|c| {
1029                 self.sort_candidate(&match_pair.place, &test, c, &mut target_candidates)
1030             })
1031             .count();
1032         assert!(tested_candidates > 0); // at least the last candidate ought to be tested
1033         debug!("tested_candidates: {}", tested_candidates);
1034         debug!(
1035             "untested_candidates: {}",
1036             candidates.len() - tested_candidates
1037         );
1038
1039         // For each outcome of test, process the candidates that still
1040         // apply. Collect a list of blocks where control flow will
1041         // branch if one of the `target_candidate` sets is not
1042         // exhaustive.
1043         let otherwise: Vec<_> = target_blocks
1044             .into_iter()
1045             .zip(target_candidates)
1046             .flat_map(|(target_block, target_candidates)| {
1047                 self.match_candidates(
1048                     span,
1049                     arm_blocks,
1050                     target_candidates,
1051                     target_block,
1052                     fake_borrows,
1053                 )
1054             })
1055             .collect();
1056
1057         (otherwise, tested_candidates)
1058     }
1059
1060     /// Initializes each of the bindings from the candidate by
1061     /// moving/copying/ref'ing the source as appropriate. Tests the
1062     /// guard, if any, and then branches to the arm. Returns the block
1063     /// for the case where the guard fails.
1064     ///
1065     /// Note: we check earlier that if there is a guard, there cannot
1066     /// be move bindings.  This isn't really important for the
1067     /// self-consistency of this fn, but the reason for it should be
1068     /// clear: after we've done the assignments, if there were move
1069     /// bindings, further tests would be a use-after-move (which would
1070     /// in turn be detected by the borrowck code that runs on the
1071     /// MIR).
1072     fn bind_and_guard_matched_candidate<'pat>(
1073         &mut self,
1074         mut block: BasicBlock,
1075         arm_blocks: &mut ArmBlocks,
1076         candidate: Candidate<'pat, 'tcx>,
1077     ) -> Option<BasicBlock> {
1078         debug!(
1079             "bind_and_guard_matched_candidate(block={:?}, candidate={:?})",
1080             block, candidate
1081         );
1082
1083         debug_assert!(candidate.match_pairs.is_empty());
1084
1085         self.ascribe_types(block, &candidate.ascriptions);
1086
1087         let arm_block = arm_blocks.blocks[candidate.arm_index];
1088         let candidate_source_info = self.source_info(candidate.span);
1089
1090         self.cfg.terminate(
1091             block,
1092             candidate_source_info,
1093             TerminatorKind::Goto {
1094                 target: candidate.pre_binding_block,
1095             },
1096         );
1097
1098         block = self.cfg.start_new_block();
1099         self.cfg.terminate(
1100             candidate.pre_binding_block,
1101             candidate_source_info,
1102             TerminatorKind::FalseEdges {
1103                 real_target: block,
1104                 imaginary_targets: vec![candidate.next_candidate_pre_binding_block],
1105             },
1106         );
1107
1108         // rust-lang/rust#27282: The `autoref` business deserves some
1109         // explanation here.
1110         //
1111         // The intent of the `autoref` flag is that when it is true,
1112         // then any pattern bindings of type T will map to a `&T`
1113         // within the context of the guard expression, but will
1114         // continue to map to a `T` in the context of the arm body. To
1115         // avoid surfacing this distinction in the user source code
1116         // (which would be a severe change to the language and require
1117         // far more revision to the compiler), when `autoref` is true,
1118         // then any occurrence of the identifier in the guard
1119         // expression will automatically get a deref op applied to it.
1120         //
1121         // So an input like:
1122         //
1123         // ```
1124         // let place = Foo::new();
1125         // match place { foo if inspect(foo)
1126         //     => feed(foo), ...  }
1127         // ```
1128         //
1129         // will be treated as if it were really something like:
1130         //
1131         // ```
1132         // let place = Foo::new();
1133         // match place { Foo { .. } if { let tmp1 = &place; inspect(*tmp1) }
1134         //     => { let tmp2 = place; feed(tmp2) }, ... }
1135         //
1136         // And an input like:
1137         //
1138         // ```
1139         // let place = Foo::new();
1140         // match place { ref mut foo if inspect(foo)
1141         //     => feed(foo), ...  }
1142         // ```
1143         //
1144         // will be treated as if it were really something like:
1145         //
1146         // ```
1147         // let place = Foo::new();
1148         // match place { Foo { .. } if { let tmp1 = & &mut place; inspect(*tmp1) }
1149         //     => { let tmp2 = &mut place; feed(tmp2) }, ... }
1150         // ```
1151         //
1152         // In short, any pattern binding will always look like *some*
1153         // kind of `&T` within the guard at least in terms of how the
1154         // MIR-borrowck views it, and this will ensure that guard
1155         // expressions cannot mutate their the match inputs via such
1156         // bindings. (It also ensures that guard expressions can at
1157         // most *copy* values from such bindings; non-Copy things
1158         // cannot be moved via pattern bindings in guard expressions.)
1159         //
1160         // ----
1161         //
1162         // Implementation notes (under assumption `autoref` is true).
1163         //
1164         // To encode the distinction above, we must inject the
1165         // temporaries `tmp1` and `tmp2`.
1166         //
1167         // There are two cases of interest: binding by-value, and binding by-ref.
1168         //
1169         // 1. Binding by-value: Things are simple.
1170         //
1171         //    * Establishing `tmp1` creates a reference into the
1172         //      matched place. This code is emitted by
1173         //      bind_matched_candidate_for_guard.
1174         //
1175         //    * `tmp2` is only initialized "lazily", after we have
1176         //      checked the guard. Thus, the code that can trigger
1177         //      moves out of the candidate can only fire after the
1178         //      guard evaluated to true. This initialization code is
1179         //      emitted by bind_matched_candidate_for_arm.
1180         //
1181         // 2. Binding by-reference: Things are tricky.
1182         //
1183         //    * Here, the guard expression wants a `&&` or `&&mut`
1184         //      into the original input. This means we need to borrow
1185         //      a reference that we do not immediately have at hand
1186         //      (because all we have is the places associated with the
1187         //      match input itself; it is up to us to create a place
1188         //      holding a `&` or `&mut` that we can then borrow).
1189
1190         let autoref = self.hir
1191             .tcx()
1192             .all_pat_vars_are_implicit_refs_within_guards();
1193         if let Some(guard) = candidate.guard {
1194             if autoref {
1195                 self.bind_matched_candidate_for_guard(
1196                     block,
1197                     candidate.pat_index,
1198                     &candidate.bindings,
1199                 );
1200                 let guard_frame = GuardFrame {
1201                     locals: candidate
1202                         .bindings
1203                         .iter()
1204                         .map(|b| GuardFrameLocal::new(b.var_id, b.binding_mode))
1205                         .collect(),
1206                 };
1207                 debug!("Entering guard building context: {:?}", guard_frame);
1208                 self.guard_context.push(guard_frame);
1209             } else {
1210                 self.bind_matched_candidate_for_arm_body(block, &candidate.bindings);
1211             }
1212
1213             // the block to branch to if the guard fails; if there is no
1214             // guard, this block is simply unreachable
1215             let guard = match guard {
1216                 Guard::If(e) => self.hir.mirror(e),
1217             };
1218             let source_info = self.source_info(guard.span);
1219             let cond = unpack!(block = self.as_local_operand(block, guard));
1220             if autoref {
1221                 let guard_frame = self.guard_context.pop().unwrap();
1222                 debug!(
1223                     "Exiting guard building context with locals: {:?}",
1224                     guard_frame
1225                 );
1226             }
1227
1228             let false_edge_block = self.cfg.start_new_block();
1229
1230             // We want to ensure that the matched candidates are bound
1231             // after we have confirmed this candidate *and* any
1232             // associated guard; Binding them on `block` is too soon,
1233             // because that would be before we've checked the result
1234             // from the guard.
1235             //
1236             // But binding them on `arm_block` is *too late*, because
1237             // then all of the candidates for a single arm would be
1238             // bound in the same place, that would cause a case like:
1239             //
1240             // ```rust
1241             // match (30, 2) {
1242             //     (mut x, 1) | (2, mut x) if { true } => { ... }
1243             //     ...                                 // ^^^^^^^ (this is `arm_block`)
1244             // }
1245             // ```
1246             //
1247             // would yield a `arm_block` something like:
1248             //
1249             // ```
1250             // StorageLive(_4);        // _4 is `x`
1251             // _4 = &mut (_1.0: i32);  // this is handling `(mut x, 1)` case
1252             // _4 = &mut (_1.1: i32);  // this is handling `(2, mut x)` case
1253             // ```
1254             //
1255             // and that is clearly not correct.
1256             let post_guard_block = self.cfg.start_new_block();
1257             self.cfg.terminate(
1258                 block,
1259                 source_info,
1260                 TerminatorKind::if_(self.hir.tcx(), cond, post_guard_block, false_edge_block),
1261             );
1262
1263             if autoref {
1264                 self.bind_matched_candidate_for_arm_body(post_guard_block, &candidate.bindings);
1265             }
1266
1267             self.cfg.terminate(
1268                 post_guard_block,
1269                 source_info,
1270                 TerminatorKind::Goto { target: arm_block },
1271             );
1272
1273             let otherwise = self.cfg.start_new_block();
1274
1275             self.cfg.terminate(
1276                 false_edge_block,
1277                 source_info,
1278                 TerminatorKind::FalseEdges {
1279                     real_target: otherwise,
1280                     imaginary_targets: vec![candidate.next_candidate_pre_binding_block],
1281                 },
1282             );
1283             Some(otherwise)
1284         } else {
1285             // (Here, it is not too early to bind the matched
1286             // candidate on `block`, because there is no guard result
1287             // that we have to inspect before we bind them.)
1288             self.bind_matched_candidate_for_arm_body(block, &candidate.bindings);
1289             self.cfg.terminate(
1290                 block,
1291                 candidate_source_info,
1292                 TerminatorKind::Goto { target: arm_block },
1293             );
1294             None
1295         }
1296     }
1297
1298     /// Append `AscribeUserType` statements onto the end of `block`
1299     /// for each ascription
1300     fn ascribe_types<'pat>(
1301         &mut self,
1302         block: BasicBlock,
1303         ascriptions: &[Ascription<'tcx>],
1304     ) {
1305         for ascription in ascriptions {
1306             let source_info = self.source_info(ascription.span);
1307
1308             debug!(
1309                 "adding user ascription at span {:?} of place {:?} and {:?}",
1310                 source_info.span,
1311                 ascription.source,
1312                 ascription.user_ty,
1313             );
1314
1315             let user_ty = box ascription.user_ty.clone().user_ty(
1316                 &mut self.canonical_user_type_annotations, source_info.span
1317             );
1318             self.cfg.push(
1319                 block,
1320                 Statement {
1321                     source_info,
1322                     kind: StatementKind::AscribeUserType(
1323                         ascription.source.clone(),
1324                         ty::Variance::Covariant,
1325                         user_ty,
1326                     ),
1327                 },
1328             );
1329         }
1330     }
1331
1332     // Only called when all_pat_vars_are_implicit_refs_within_guards,
1333     // and thus all code/comments assume we are in that context.
1334     fn bind_matched_candidate_for_guard(
1335         &mut self,
1336         block: BasicBlock,
1337         pat_index: usize,
1338         bindings: &[Binding<'tcx>],
1339     ) {
1340         debug!(
1341             "bind_matched_candidate_for_guard(block={:?}, pat_index={:?}, bindings={:?})",
1342             block, pat_index, bindings
1343         );
1344
1345         // Assign each of the bindings. Since we are binding for a
1346         // guard expression, this will never trigger moves out of the
1347         // candidate.
1348         let re_empty = self.hir.tcx().types.re_empty;
1349         for binding in bindings {
1350             let source_info = self.source_info(binding.span);
1351
1352             // For each pattern ident P of type T, `ref_for_guard` is
1353             // a reference R: &T pointing to the location matched by
1354             // the pattern, and every occurrence of P within a guard
1355             // denotes *R.
1356             let ref_for_guard =
1357                 self.storage_live_binding(block, binding.var_id, binding.span, RefWithinGuard);
1358             // Question: Why schedule drops if bindings are all
1359             // shared-&'s?  Answer: Because schedule_drop_for_binding
1360             // also emits StorageDead's for those locals.
1361             self.schedule_drop_for_binding(binding.var_id, binding.span, RefWithinGuard);
1362             match binding.binding_mode {
1363                 BindingMode::ByValue => {
1364                     let rvalue = Rvalue::Ref(re_empty, BorrowKind::Shared, binding.source.clone());
1365                     self.cfg
1366                         .push_assign(block, source_info, &ref_for_guard, rvalue);
1367                 }
1368                 BindingMode::ByRef(region, borrow_kind) => {
1369                     // Tricky business: For `ref id` and `ref mut id`
1370                     // patterns, we want `id` within the guard to
1371                     // correspond to a temp of type `& &T` or `& &mut
1372                     // T` (i.e., a "borrow of a borrow") that is
1373                     // implicitly dereferenced.
1374                     //
1375                     // To borrow a borrow, we need that inner borrow
1376                     // to point to. So, create a temp for the inner
1377                     // borrow, and then take a reference to it.
1378                     //
1379                     // Note: the temp created here is *not* the one
1380                     // used by the arm body itself. This eases
1381                     // observing two-phase borrow restrictions.
1382                     let val_for_guard = self.storage_live_binding(
1383                         block,
1384                         binding.var_id,
1385                         binding.span,
1386                         ValWithinGuard(pat_index),
1387                     );
1388                     self.schedule_drop_for_binding(
1389                         binding.var_id,
1390                         binding.span,
1391                         ValWithinGuard(pat_index),
1392                     );
1393
1394                     // rust-lang/rust#27282: We reuse the two-phase
1395                     // borrow infrastructure so that the mutable
1396                     // borrow (whose mutabilty is *unusable* within
1397                     // the guard) does not conflict with the implicit
1398                     // borrow of the whole match input. See additional
1399                     // discussion on rust-lang/rust#49870.
1400                     let borrow_kind = match borrow_kind {
1401                         BorrowKind::Shared
1402                         | BorrowKind::Shallow
1403                         | BorrowKind::Unique => borrow_kind,
1404                         BorrowKind::Mut { .. } => BorrowKind::Mut {
1405                             allow_two_phase_borrow: true,
1406                         },
1407                     };
1408                     let rvalue = Rvalue::Ref(region, borrow_kind, binding.source.clone());
1409                     self.cfg
1410                         .push_assign(block, source_info, &val_for_guard, rvalue);
1411                     let rvalue = Rvalue::Ref(region, BorrowKind::Shared, val_for_guard);
1412                     self.cfg
1413                         .push_assign(block, source_info, &ref_for_guard, rvalue);
1414                 }
1415             }
1416         }
1417     }
1418
1419     fn bind_matched_candidate_for_arm_body(
1420         &mut self,
1421         block: BasicBlock,
1422         bindings: &[Binding<'tcx>],
1423     ) {
1424         debug!(
1425             "bind_matched_candidate_for_arm_body(block={:?}, bindings={:?}",
1426             block, bindings
1427         );
1428
1429         // Assign each of the bindings. This may trigger moves out of the candidate.
1430         for binding in bindings {
1431             let source_info = self.source_info(binding.span);
1432             let local =
1433                 self.storage_live_binding(block, binding.var_id, binding.span, OutsideGuard);
1434             self.schedule_drop_for_binding(binding.var_id, binding.span, OutsideGuard);
1435             let rvalue = match binding.binding_mode {
1436                 BindingMode::ByValue => {
1437                     Rvalue::Use(self.consume_by_copy_or_move(binding.source.clone()))
1438                 }
1439                 BindingMode::ByRef(region, borrow_kind) => {
1440                     Rvalue::Ref(region, borrow_kind, binding.source.clone())
1441                 }
1442             };
1443             self.cfg.push_assign(block, source_info, &local, rvalue);
1444         }
1445     }
1446
1447     /// Each binding (`ref mut var`/`ref var`/`mut var`/`var`, where
1448     /// the bound `var` has type `T` in the arm body) in a pattern
1449     /// maps to `2+N` locals. The first local is a binding for
1450     /// occurrences of `var` in the guard, which will all have type
1451     /// `&T`. The N locals are bindings for the `T` that is referenced
1452     /// by the first local; they are not used outside of the
1453     /// guard. The last local is a binding for occurrences of `var` in
1454     /// the arm body, which will have type `T`.
1455     ///
1456     /// The reason we have N locals rather than just 1 is to
1457     /// accommodate rust-lang/rust#51348: If the arm has N candidate
1458     /// patterns, then in general they can correspond to distinct
1459     /// parts of the matched data, and we want them to be distinct
1460     /// temps in order to simplify checks performed by our internal
1461     /// leveraging of two-phase borrows).
1462     fn declare_binding(
1463         &mut self,
1464         source_info: SourceInfo,
1465         visibility_scope: SourceScope,
1466         mutability: Mutability,
1467         name: Name,
1468         mode: BindingMode,
1469         num_patterns: usize,
1470         var_id: NodeId,
1471         var_ty: Ty<'tcx>,
1472         user_ty: UserTypeProjections<'tcx>,
1473         has_guard: ArmHasGuard,
1474         opt_match_place: Option<(Option<Place<'tcx>>, Span)>,
1475         pat_span: Span,
1476     ) {
1477         debug!(
1478             "declare_binding(var_id={:?}, name={:?}, mode={:?}, var_ty={:?}, \
1479              visibility_scope={:?}, source_info={:?})",
1480             var_id, name, mode, var_ty, visibility_scope, source_info
1481         );
1482
1483         let tcx = self.hir.tcx();
1484         let binding_mode = match mode {
1485             BindingMode::ByValue => ty::BindingMode::BindByValue(mutability.into()),
1486             BindingMode::ByRef { .. } => ty::BindingMode::BindByReference(mutability.into()),
1487         };
1488         debug!("declare_binding: user_ty={:?}", user_ty);
1489         let local = LocalDecl::<'tcx> {
1490             mutability,
1491             ty: var_ty,
1492             user_ty,
1493             name: Some(name),
1494             source_info,
1495             visibility_scope,
1496             internal: false,
1497             is_block_tail: None,
1498             is_user_variable: Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm {
1499                 binding_mode,
1500                 // hypothetically, `visit_bindings` could try to unzip
1501                 // an outermost hir::Ty as we descend, matching up
1502                 // idents in pat; but complex w/ unclear UI payoff.
1503                 // Instead, just abandon providing diagnostic info.
1504                 opt_ty_info: None,
1505                 opt_match_place,
1506                 pat_span,
1507             }))),
1508         };
1509         let for_arm_body = self.local_decls.push(local.clone());
1510         let locals = if has_guard.0 && tcx.all_pat_vars_are_implicit_refs_within_guards() {
1511             let mut vals_for_guard = Vec::with_capacity(num_patterns);
1512             for _ in 0..num_patterns {
1513                 let val_for_guard_idx = self.local_decls.push(LocalDecl {
1514                     // This variable isn't mutated but has a name, so has to be
1515                     // immutable to avoid the unused mut lint.
1516                     mutability: Mutability::Not,
1517                     ..local.clone()
1518                 });
1519                 vals_for_guard.push(val_for_guard_idx);
1520             }
1521             let ref_for_guard = self.local_decls.push(LocalDecl::<'tcx> {
1522                 // See previous comment.
1523                 mutability: Mutability::Not,
1524                 ty: tcx.mk_imm_ref(tcx.types.re_empty, var_ty),
1525                 user_ty: UserTypeProjections::none(),
1526                 name: Some(name),
1527                 source_info,
1528                 visibility_scope,
1529                 // FIXME: should these secretly injected ref_for_guard's be marked as `internal`?
1530                 internal: false,
1531                 is_block_tail: None,
1532                 is_user_variable: Some(ClearCrossCrate::Set(BindingForm::RefForGuard)),
1533             });
1534             LocalsForNode::ForGuard {
1535                 vals_for_guard,
1536                 ref_for_guard,
1537                 for_arm_body,
1538             }
1539         } else {
1540             LocalsForNode::One(for_arm_body)
1541         };
1542         debug!("declare_binding: vars={:?}", locals);
1543         self.var_indices.insert(var_id, locals);
1544     }
1545
1546     // Determine the fake borrows that are needed to ensure that the place
1547     // will evaluate to the same thing until an arm has been chosen.
1548     fn add_fake_borrows<'pat>(
1549         &mut self,
1550         pre_binding_blocks: &[(BasicBlock, Span)],
1551         fake_borrows: FxHashMap<Place<'tcx>, BorrowKind>,
1552         source_info: SourceInfo,
1553         start_block: BasicBlock,
1554     ) {
1555         let tcx = self.hir.tcx();
1556
1557         debug!("add_fake_borrows pre_binding_blocks = {:?}, fake_borrows = {:?}",
1558                pre_binding_blocks, fake_borrows);
1559
1560         let mut all_fake_borrows = Vec::with_capacity(fake_borrows.len());
1561
1562         // Insert a Shallow borrow of the prefixes of any fake borrows.
1563         for (place, borrow_kind) in fake_borrows
1564         {
1565             {
1566                 let mut prefix_cursor = &place;
1567                 while let Place::Projection(box Projection { base, elem }) = prefix_cursor {
1568                     if let ProjectionElem::Deref = elem {
1569                         // Insert a shallow borrow after a deref. For other
1570                         // projections the borrow of prefix_cursor will
1571                         // conflict with any mutation of base.
1572                         all_fake_borrows.push((base.clone(), BorrowKind::Shallow));
1573                     }
1574                     prefix_cursor = base;
1575                 }
1576             }
1577
1578             all_fake_borrows.push((place, borrow_kind));
1579         }
1580
1581         // Deduplicate and ensure a deterministic order.
1582         all_fake_borrows.sort();
1583         all_fake_borrows.dedup();
1584
1585         debug!("add_fake_borrows all_fake_borrows = {:?}", all_fake_borrows);
1586
1587         // Add fake borrows to the start of the match and reads of them before
1588         // the start of each arm.
1589         let mut borrowed_input_temps = Vec::with_capacity(all_fake_borrows.len());
1590
1591         for (matched_place, borrow_kind) in all_fake_borrows {
1592             let borrowed_input =
1593                 Rvalue::Ref(tcx.types.re_empty, borrow_kind, matched_place.clone());
1594             let borrowed_input_ty = borrowed_input.ty(&self.local_decls, tcx);
1595             let borrowed_input_temp = self.temp(borrowed_input_ty, source_info.span);
1596             self.cfg.push_assign(
1597                 start_block,
1598                 source_info,
1599                 &borrowed_input_temp,
1600                 borrowed_input
1601             );
1602             borrowed_input_temps.push(borrowed_input_temp);
1603         }
1604
1605         // FIXME: This could be a lot of reads (#fake borrows * #patterns).
1606         // The false edges that we currently generate would allow us to only do
1607         // this on the last Candidate, but it's possible that there might not be
1608         // so many false edges in the future, so we read for all Candidates for
1609         // now.
1610         // Another option would be to make our own block and add our own false
1611         // edges to it.
1612         if tcx.emit_read_for_match() {
1613             for &(pre_binding_block, span) in pre_binding_blocks {
1614                 let pattern_source_info = self.source_info(span);
1615                 for temp in &borrowed_input_temps {
1616                     self.cfg.push(pre_binding_block, Statement {
1617                         source_info: pattern_source_info,
1618                         kind: StatementKind::FakeRead(
1619                             FakeReadCause::ForMatchGuard,
1620                             temp.clone(),
1621                         ),
1622                     });
1623                 }
1624             }
1625         }
1626     }
1627 }