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