]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_middle/src/mir/visit.rs
Merge commit '63734fcdd718cca089f84c42f3a42c0096cfd431' into sync_cg_clif-2022-05-15
[rust.git] / compiler / rustc_middle / src / mir / visit.rs
1 //! # The MIR Visitor
2 //!
3 //! ## Overview
4 //!
5 //! There are two visitors, one for immutable and one for mutable references,
6 //! but both are generated by the following macro. The code is written according
7 //! to the following conventions:
8 //!
9 //! - introduce a `visit_foo` and a `super_foo` method for every MIR type
10 //! - `visit_foo`, by default, calls `super_foo`
11 //! - `super_foo`, by default, destructures the `foo` and calls `visit_foo`
12 //!
13 //! This allows you as a user to override `visit_foo` for types are
14 //! interested in, and invoke (within that method) call
15 //! `self.super_foo` to get the default behavior. Just as in an OO
16 //! language, you should never call `super` methods ordinarily except
17 //! in that circumstance.
18 //!
19 //! For the most part, we do not destructure things external to the
20 //! MIR, e.g., types, spans, etc, but simply visit them and stop. This
21 //! avoids duplication with other visitors like `TypeFoldable`.
22 //!
23 //! ## Updating
24 //!
25 //! The code is written in a very deliberate style intended to minimize
26 //! the chance of things being overlooked. You'll notice that we always
27 //! use pattern matching to reference fields and we ensure that all
28 //! matches are exhaustive.
29 //!
30 //! For example, the `super_basic_block_data` method begins like this:
31 //!
32 //! ```ignore (pseudo-rust)
33 //! fn super_basic_block_data(&mut self,
34 //!                           block: BasicBlock,
35 //!                           data: & $($mutability)? BasicBlockData<'tcx>) {
36 //!     let BasicBlockData {
37 //!         statements,
38 //!         terminator,
39 //!         is_cleanup: _
40 //!     } = *data;
41 //!
42 //!     for statement in statements {
43 //!         self.visit_statement(block, statement);
44 //!     }
45 //!
46 //!     ...
47 //! }
48 //! ```
49 //!
50 //! Here we used `let BasicBlockData { <fields> } = *data` deliberately,
51 //! rather than writing `data.statements` in the body. This is because if one
52 //! adds a new field to `BasicBlockData`, one will be forced to revise this code,
53 //! and hence one will (hopefully) invoke the correct visit methods (if any).
54 //!
55 //! For this to work, ALL MATCHES MUST BE EXHAUSTIVE IN FIELDS AND VARIANTS.
56 //! That means you never write `..` to skip over fields, nor do you write `_`
57 //! to skip over variants in a `match`.
58 //!
59 //! The only place that `_` is acceptable is to match a field (or
60 //! variant argument) that does not require visiting, as in
61 //! `is_cleanup` above.
62
63 use crate::mir::*;
64 use crate::ty::subst::SubstsRef;
65 use crate::ty::{CanonicalUserTypeAnnotation, Ty};
66 use rustc_span::Span;
67
68 macro_rules! make_mir_visitor {
69     ($visitor_trait_name:ident, $($mutability:ident)?) => {
70         pub trait $visitor_trait_name<'tcx> {
71             // Override these, and call `self.super_xxx` to revert back to the
72             // default behavior.
73
74             fn visit_body(
75                 &mut self,
76                 body: &$($mutability)? Body<'tcx>,
77             ) {
78                 self.super_body(body);
79             }
80
81             fn visit_basic_block_data(&mut self,
82                                       block: BasicBlock,
83                                       data: & $($mutability)? BasicBlockData<'tcx>) {
84                 self.super_basic_block_data(block, data);
85             }
86
87             fn visit_source_scope_data(&mut self,
88                                            scope_data: & $($mutability)? SourceScopeData<'tcx>) {
89                 self.super_source_scope_data(scope_data);
90             }
91
92             fn visit_statement(&mut self,
93                                statement: & $($mutability)? Statement<'tcx>,
94                                location: Location) {
95                 self.super_statement(statement, location);
96             }
97
98             fn visit_assign(&mut self,
99                             place: & $($mutability)? Place<'tcx>,
100                             rvalue: & $($mutability)? Rvalue<'tcx>,
101                             location: Location) {
102                 self.super_assign(place, rvalue, location);
103             }
104
105             fn visit_terminator(&mut self,
106                                 terminator: & $($mutability)? Terminator<'tcx>,
107                                 location: Location) {
108                 self.super_terminator(terminator, location);
109             }
110
111             fn visit_assert_message(&mut self,
112                                     msg: & $($mutability)? AssertMessage<'tcx>,
113                                     location: Location) {
114                 self.super_assert_message(msg, location);
115             }
116
117             fn visit_rvalue(&mut self,
118                             rvalue: & $($mutability)? Rvalue<'tcx>,
119                             location: Location) {
120                 self.super_rvalue(rvalue, location);
121             }
122
123             fn visit_operand(&mut self,
124                              operand: & $($mutability)? Operand<'tcx>,
125                              location: Location) {
126                 self.super_operand(operand, location);
127             }
128
129             fn visit_ascribe_user_ty(&mut self,
130                                      place: & $($mutability)? Place<'tcx>,
131                                      variance: & $($mutability)? ty::Variance,
132                                      user_ty: & $($mutability)? UserTypeProjection,
133                                      location: Location) {
134                 self.super_ascribe_user_ty(place, variance, user_ty, location);
135             }
136
137             fn visit_coverage(&mut self,
138                               coverage: & $($mutability)? Coverage,
139                               location: Location) {
140                 self.super_coverage(coverage, location);
141             }
142
143             fn visit_retag(&mut self,
144                            kind: & $($mutability)? RetagKind,
145                            place: & $($mutability)? Place<'tcx>,
146                            location: Location) {
147                 self.super_retag(kind, place, location);
148             }
149
150             fn visit_place(&mut self,
151                             place: & $($mutability)? Place<'tcx>,
152                             context: PlaceContext,
153                             location: Location) {
154                 self.super_place(place, context, location);
155             }
156
157             visit_place_fns!($($mutability)?);
158
159             fn visit_constant(&mut self,
160                               constant: & $($mutability)? Constant<'tcx>,
161                               location: Location) {
162                 self.super_constant(constant, location);
163             }
164
165             // The macro results in a false positive of sorts, where &mut Span
166             // is fine, but &Span is not; just allow the lint.
167             #[allow(rustc::pass_by_value)]
168             fn visit_span(&mut self,
169                           span: & $($mutability)? Span) {
170                 self.super_span(span);
171             }
172
173             fn visit_source_info(&mut self,
174                                  source_info: & $($mutability)? SourceInfo) {
175                 self.super_source_info(source_info);
176             }
177
178             fn visit_ty(&mut self,
179                         ty: $(& $mutability)? Ty<'tcx>,
180                         _: TyContext) {
181                 self.super_ty(ty);
182             }
183
184             fn visit_user_type_projection(
185                 &mut self,
186                 ty: & $($mutability)? UserTypeProjection,
187             ) {
188                 self.super_user_type_projection(ty);
189             }
190
191             fn visit_user_type_annotation(
192                 &mut self,
193                 index: UserTypeAnnotationIndex,
194                 ty: & $($mutability)? CanonicalUserTypeAnnotation<'tcx>,
195             ) {
196                 self.super_user_type_annotation(index, ty);
197             }
198
199             fn visit_region(&mut self,
200                             region: $(& $mutability)? ty::Region<'tcx>,
201                             _: Location) {
202                 self.super_region(region);
203             }
204
205             fn visit_const(&mut self,
206                            constant: $(& $mutability)? ty::Const<'tcx>,
207                            _: Location) {
208                 self.super_const(constant);
209             }
210
211             fn visit_substs(&mut self,
212                             substs: & $($mutability)? SubstsRef<'tcx>,
213                             _: Location) {
214                 self.super_substs(substs);
215             }
216
217             fn visit_local_decl(&mut self,
218                                 local: Local,
219                                 local_decl: & $($mutability)? LocalDecl<'tcx>) {
220                 self.super_local_decl(local, local_decl);
221             }
222
223             fn visit_var_debug_info(&mut self,
224                                     var_debug_info: & $($mutability)* VarDebugInfo<'tcx>) {
225                 self.super_var_debug_info(var_debug_info);
226             }
227
228             #[allow(rustc::pass_by_value)]
229             fn visit_local(&mut self,
230                             _local: & $($mutability)? Local,
231                             _context: PlaceContext,
232                             _location: Location) {
233             }
234
235             #[allow(rustc::pass_by_value)]
236             fn visit_source_scope(&mut self,
237                                       scope: & $($mutability)? SourceScope) {
238                 self.super_source_scope(scope);
239             }
240
241             // The `super_xxx` methods comprise the default behavior and are
242             // not meant to be overridden.
243
244             fn super_body(
245                 &mut self,
246                 body: &$($mutability)? Body<'tcx>,
247             ) {
248                 let span = body.span;
249                 if let Some(gen) = &$($mutability)? body.generator {
250                     if let Some(yield_ty) = $(& $mutability)? gen.yield_ty {
251                         self.visit_ty(
252                             yield_ty,
253                             TyContext::YieldTy(SourceInfo::outermost(span))
254                         );
255                     }
256                 }
257
258                 // for best performance, we want to use an iterator rather
259                 // than a for-loop, to avoid calling `body::Body::invalidate` for
260                 // each basic block.
261                 #[cfg_attr(not(bootstrap), allow(unused_macro_rules))]
262                 macro_rules! basic_blocks {
263                     (mut) => (body.basic_blocks_mut().iter_enumerated_mut());
264                     () => (body.basic_blocks().iter_enumerated());
265                 }
266                 for (bb, data) in basic_blocks!($($mutability)?) {
267                     self.visit_basic_block_data(bb, data);
268                 }
269
270                 for scope in &$($mutability)? body.source_scopes {
271                     self.visit_source_scope_data(scope);
272                 }
273
274                 self.visit_ty(
275                     $(& $mutability)? body.return_ty(),
276                     TyContext::ReturnTy(SourceInfo::outermost(body.span))
277                 );
278
279                 for local in body.local_decls.indices() {
280                     self.visit_local_decl(local, & $($mutability)? body.local_decls[local]);
281                 }
282
283                 #[cfg_attr(not(bootstrap), allow(unused_macro_rules))]
284                 macro_rules! type_annotations {
285                     (mut) => (body.user_type_annotations.iter_enumerated_mut());
286                     () => (body.user_type_annotations.iter_enumerated());
287                 }
288
289                 for (index, annotation) in type_annotations!($($mutability)?) {
290                     self.visit_user_type_annotation(
291                         index, annotation
292                     );
293                 }
294
295                 for var_debug_info in &$($mutability)? body.var_debug_info {
296                     self.visit_var_debug_info(var_debug_info);
297                 }
298
299                 self.visit_span(&$($mutability)? body.span);
300
301                 for const_ in &$($mutability)? body.required_consts {
302                     let location = START_BLOCK.start_location();
303                     self.visit_constant(const_, location);
304                 }
305             }
306
307             fn super_basic_block_data(&mut self,
308                                       block: BasicBlock,
309                                       data: & $($mutability)? BasicBlockData<'tcx>) {
310                 let BasicBlockData {
311                     statements,
312                     terminator,
313                     is_cleanup: _
314                 } = data;
315
316                 let mut index = 0;
317                 for statement in statements {
318                     let location = Location { block, statement_index: index };
319                     self.visit_statement(statement, location);
320                     index += 1;
321                 }
322
323                 if let Some(terminator) = terminator {
324                     let location = Location { block, statement_index: index };
325                     self.visit_terminator(terminator, location);
326                 }
327             }
328
329             fn super_source_scope_data(
330                 &mut self,
331                 scope_data: & $($mutability)? SourceScopeData<'tcx>,
332             ) {
333                 let SourceScopeData {
334                     span,
335                     parent_scope,
336                     inlined,
337                     inlined_parent_scope,
338                     local_data: _,
339                 } = scope_data;
340
341                 self.visit_span(span);
342                 if let Some(parent_scope) = parent_scope {
343                     self.visit_source_scope(parent_scope);
344                 }
345                 if let Some((callee, callsite_span)) = inlined {
346                     let location = START_BLOCK.start_location();
347
348                     self.visit_span(callsite_span);
349
350                     let ty::Instance { def: callee_def, substs: callee_substs } = callee;
351                     match callee_def {
352                         ty::InstanceDef::Item(_def_id) => {}
353
354                         ty::InstanceDef::Intrinsic(_def_id) |
355                         ty::InstanceDef::VtableShim(_def_id) |
356                         ty::InstanceDef::ReifyShim(_def_id) |
357                         ty::InstanceDef::Virtual(_def_id, _) |
358                         ty::InstanceDef::ClosureOnceShim { call_once: _def_id, track_caller: _ } |
359                         ty::InstanceDef::DropGlue(_def_id, None) => {}
360
361                         ty::InstanceDef::FnPtrShim(_def_id, ty) |
362                         ty::InstanceDef::DropGlue(_def_id, Some(ty)) |
363                         ty::InstanceDef::CloneShim(_def_id, ty) => {
364                             // FIXME(eddyb) use a better `TyContext` here.
365                             self.visit_ty($(& $mutability)? *ty, TyContext::Location(location));
366                         }
367                     }
368                     self.visit_substs(callee_substs, location);
369                 }
370                 if let Some(inlined_parent_scope) = inlined_parent_scope {
371                     self.visit_source_scope(inlined_parent_scope);
372                 }
373             }
374
375             fn super_statement(&mut self,
376                                statement: & $($mutability)? Statement<'tcx>,
377                                location: Location) {
378                 let Statement {
379                     source_info,
380                     kind,
381                 } = statement;
382
383                 self.visit_source_info(source_info);
384                 match kind {
385                     StatementKind::Assign(
386                         box(ref $($mutability)? place, ref $($mutability)? rvalue)
387                     ) => {
388                         self.visit_assign(place, rvalue, location);
389                     }
390                     StatementKind::FakeRead(box (_, place)) => {
391                         self.visit_place(
392                             place,
393                             PlaceContext::NonMutatingUse(NonMutatingUseContext::Inspect),
394                             location
395                         );
396                     }
397                     StatementKind::SetDiscriminant { place, .. } => {
398                         self.visit_place(
399                             place,
400                             PlaceContext::MutatingUse(MutatingUseContext::SetDiscriminant),
401                             location
402                         );
403                     }
404                     StatementKind::Deinit(place) => {
405                         self.visit_place(
406                             place,
407                             PlaceContext::MutatingUse(MutatingUseContext::Deinit),
408                             location
409                         )
410                     }
411                     StatementKind::StorageLive(local) => {
412                         self.visit_local(
413                             local,
414                             PlaceContext::NonUse(NonUseContext::StorageLive),
415                             location
416                         );
417                     }
418                     StatementKind::StorageDead(local) => {
419                         self.visit_local(
420                             local,
421                             PlaceContext::NonUse(NonUseContext::StorageDead),
422                             location
423                         );
424                     }
425                     StatementKind::Retag(kind, place) => {
426                         self.visit_retag(kind, place, location);
427                     }
428                     StatementKind::AscribeUserType(
429                         box(ref $($mutability)? place, ref $($mutability)? user_ty),
430                         variance
431                     ) => {
432                         self.visit_ascribe_user_ty(place, variance, user_ty, location);
433                     }
434                     StatementKind::Coverage(coverage) => {
435                         self.visit_coverage(
436                             coverage,
437                             location
438                         )
439                     }
440                     StatementKind::CopyNonOverlapping(box crate::mir::CopyNonOverlapping{
441                       ref $($mutability)? src,
442                       ref $($mutability)? dst,
443                       ref $($mutability)? count,
444                     }) => {
445                       self.visit_operand(src, location);
446                       self.visit_operand(dst, location);
447                       self.visit_operand(count, location)
448                     }
449                     StatementKind::Nop => {}
450                 }
451             }
452
453             fn super_assign(&mut self,
454                             place: &$($mutability)? Place<'tcx>,
455                             rvalue: &$($mutability)? Rvalue<'tcx>,
456                             location: Location) {
457                 self.visit_place(
458                     place,
459                     PlaceContext::MutatingUse(MutatingUseContext::Store),
460                     location
461                 );
462                 self.visit_rvalue(rvalue, location);
463             }
464
465             fn super_terminator(&mut self,
466                                 terminator: &$($mutability)? Terminator<'tcx>,
467                                 location: Location) {
468                 let Terminator { source_info, kind } = terminator;
469
470                 self.visit_source_info(source_info);
471                 match kind {
472                     TerminatorKind::Goto { .. } |
473                     TerminatorKind::Resume |
474                     TerminatorKind::Abort |
475                     TerminatorKind::GeneratorDrop |
476                     TerminatorKind::Unreachable |
477                     TerminatorKind::FalseEdge { .. } |
478                     TerminatorKind::FalseUnwind { .. } => {
479                     }
480
481                     TerminatorKind::Return => {
482                         // `return` logically moves from the return place `_0`. Note that the place
483                         // cannot be changed by any visitor, though.
484                         let $($mutability)? local = RETURN_PLACE;
485                         self.visit_local(
486                             & $($mutability)? local,
487                             PlaceContext::NonMutatingUse(NonMutatingUseContext::Move),
488                             location,
489                         );
490
491                         assert_eq!(
492                             local,
493                             RETURN_PLACE,
494                             "`MutVisitor` tried to mutate return place of `return` terminator"
495                         );
496                     }
497
498                     TerminatorKind::SwitchInt {
499                         discr,
500                         switch_ty,
501                         targets: _
502                     } => {
503                         self.visit_operand(discr, location);
504                         self.visit_ty($(& $mutability)? *switch_ty, TyContext::Location(location));
505                     }
506
507                     TerminatorKind::Drop {
508                         place,
509                         target: _,
510                         unwind: _,
511                     } => {
512                         self.visit_place(
513                             place,
514                             PlaceContext::MutatingUse(MutatingUseContext::Drop),
515                             location
516                         );
517                     }
518
519                     TerminatorKind::DropAndReplace {
520                         place,
521                         value,
522                         target: _,
523                         unwind: _,
524                     } => {
525                         self.visit_place(
526                             place,
527                             PlaceContext::MutatingUse(MutatingUseContext::Drop),
528                             location
529                         );
530                         self.visit_operand(value, location);
531                     }
532
533                     TerminatorKind::Call {
534                         func,
535                         args,
536                         destination,
537                         cleanup: _,
538                         from_hir_call: _,
539                         fn_span: _
540                     } => {
541                         self.visit_operand(func, location);
542                         for arg in args {
543                             self.visit_operand(arg, location);
544                         }
545                         if let Some((destination, _)) = destination {
546                             self.visit_place(
547                                 destination,
548                                 PlaceContext::MutatingUse(MutatingUseContext::Call),
549                                 location
550                             );
551                         }
552                     }
553
554                     TerminatorKind::Assert {
555                         cond,
556                         expected: _,
557                         msg,
558                         target: _,
559                         cleanup: _,
560                     } => {
561                         self.visit_operand(cond, location);
562                         self.visit_assert_message(msg, location);
563                     }
564
565                     TerminatorKind::Yield {
566                         value,
567                         resume: _,
568                         resume_arg,
569                         drop: _,
570                     } => {
571                         self.visit_operand(value, location);
572                         self.visit_place(
573                             resume_arg,
574                             PlaceContext::MutatingUse(MutatingUseContext::Yield),
575                             location,
576                         );
577                     }
578
579                     TerminatorKind::InlineAsm {
580                         template: _,
581                         operands,
582                         options: _,
583                         line_spans: _,
584                         destination: _,
585                         cleanup: _,
586                     } => {
587                         for op in operands {
588                             match op {
589                                 InlineAsmOperand::In { value, .. } => {
590                                     self.visit_operand(value, location);
591                                 }
592                                 InlineAsmOperand::Out { place: Some(place), .. } => {
593                                     self.visit_place(
594                                         place,
595                                         PlaceContext::MutatingUse(MutatingUseContext::AsmOutput),
596                                         location,
597                                     );
598                                 }
599                                 InlineAsmOperand::InOut { in_value, out_place, .. } => {
600                                     self.visit_operand(in_value, location);
601                                     if let Some(out_place) = out_place {
602                                         self.visit_place(
603                                             out_place,
604                                             PlaceContext::MutatingUse(MutatingUseContext::AsmOutput),
605                                             location,
606                                         );
607                                     }
608                                 }
609                                 InlineAsmOperand::Const { value }
610                                 | InlineAsmOperand::SymFn { value } => {
611                                     self.visit_constant(value, location);
612                                 }
613                                 InlineAsmOperand::Out { place: None, .. }
614                                 | InlineAsmOperand::SymStatic { def_id: _ } => {}
615                             }
616                         }
617                     }
618                 }
619             }
620
621             fn super_assert_message(&mut self,
622                                     msg: & $($mutability)? AssertMessage<'tcx>,
623                                     location: Location) {
624                 use crate::mir::AssertKind::*;
625                 match msg {
626                     BoundsCheck { len, index } => {
627                         self.visit_operand(len, location);
628                         self.visit_operand(index, location);
629                     }
630                     Overflow(_, l, r) => {
631                         self.visit_operand(l, location);
632                         self.visit_operand(r, location);
633                     }
634                     OverflowNeg(op) | DivisionByZero(op) | RemainderByZero(op) => {
635                         self.visit_operand(op, location);
636                     }
637                     ResumedAfterReturn(_) | ResumedAfterPanic(_) => {
638                         // Nothing to visit
639                     }
640                 }
641             }
642
643             fn super_rvalue(&mut self,
644                             rvalue: & $($mutability)? Rvalue<'tcx>,
645                             location: Location) {
646                 match rvalue {
647                     Rvalue::Use(operand) => {
648                         self.visit_operand(operand, location);
649                     }
650
651                     Rvalue::Repeat(value, _) => {
652                         self.visit_operand(value, location);
653                     }
654
655                     Rvalue::ThreadLocalRef(_) => {}
656
657                     Rvalue::Ref(r, bk, path) => {
658                         self.visit_region($(& $mutability)? *r, location);
659                         let ctx = match bk {
660                             BorrowKind::Shared => PlaceContext::NonMutatingUse(
661                                 NonMutatingUseContext::SharedBorrow
662                             ),
663                             BorrowKind::Shallow => PlaceContext::NonMutatingUse(
664                                 NonMutatingUseContext::ShallowBorrow
665                             ),
666                             BorrowKind::Unique => PlaceContext::NonMutatingUse(
667                                 NonMutatingUseContext::UniqueBorrow
668                             ),
669                             BorrowKind::Mut { .. } =>
670                                 PlaceContext::MutatingUse(MutatingUseContext::Borrow),
671                         };
672                         self.visit_place(path, ctx, location);
673                     }
674
675                     Rvalue::AddressOf(m, path) => {
676                         let ctx = match m {
677                             Mutability::Mut => PlaceContext::MutatingUse(
678                                 MutatingUseContext::AddressOf
679                             ),
680                             Mutability::Not => PlaceContext::NonMutatingUse(
681                                 NonMutatingUseContext::AddressOf
682                             ),
683                         };
684                         self.visit_place(path, ctx, location);
685                     }
686
687                     Rvalue::Len(path) => {
688                         self.visit_place(
689                             path,
690                             PlaceContext::NonMutatingUse(NonMutatingUseContext::Inspect),
691                             location
692                         );
693                     }
694
695                     Rvalue::Cast(_cast_kind, operand, ty) => {
696                         self.visit_operand(operand, location);
697                         self.visit_ty($(& $mutability)? *ty, TyContext::Location(location));
698                     }
699
700                     Rvalue::BinaryOp(_bin_op, box(lhs, rhs))
701                     | Rvalue::CheckedBinaryOp(_bin_op, box(lhs, rhs)) => {
702                         self.visit_operand(lhs, location);
703                         self.visit_operand(rhs, location);
704                     }
705
706                     Rvalue::UnaryOp(_un_op, op) => {
707                         self.visit_operand(op, location);
708                     }
709
710                     Rvalue::Discriminant(place) => {
711                         self.visit_place(
712                             place,
713                             PlaceContext::NonMutatingUse(NonMutatingUseContext::Inspect),
714                             location
715                         );
716                     }
717
718                     Rvalue::NullaryOp(_op, ty) => {
719                         self.visit_ty($(& $mutability)? *ty, TyContext::Location(location));
720                     }
721
722                     Rvalue::Aggregate(kind, operands) => {
723                         let kind = &$($mutability)? **kind;
724                         match kind {
725                             AggregateKind::Array(ty) => {
726                                 self.visit_ty($(& $mutability)? *ty, TyContext::Location(location));
727                             }
728                             AggregateKind::Tuple => {
729                             }
730                             AggregateKind::Adt(
731                                 _adt_def,
732                                 _variant_index,
733                                 substs,
734                                 _user_substs,
735                                 _active_field_index
736                             ) => {
737                                 self.visit_substs(substs, location);
738                             }
739                             AggregateKind::Closure(
740                                 _,
741                                 closure_substs
742                             ) => {
743                                 self.visit_substs(closure_substs, location);
744                             }
745                             AggregateKind::Generator(
746                                 _,
747                                 generator_substs,
748                                 _movability,
749                             ) => {
750                                 self.visit_substs(generator_substs, location);
751                             }
752                         }
753
754                         for operand in operands {
755                             self.visit_operand(operand, location);
756                         }
757                     }
758
759                     Rvalue::ShallowInitBox(operand, ty) => {
760                         self.visit_operand(operand, location);
761                         self.visit_ty($(& $mutability)? *ty, TyContext::Location(location));
762                     }
763                 }
764             }
765
766             fn super_operand(&mut self,
767                              operand: & $($mutability)? Operand<'tcx>,
768                              location: Location) {
769                 match operand {
770                     Operand::Copy(place) => {
771                         self.visit_place(
772                             place,
773                             PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy),
774                             location
775                         );
776                     }
777                     Operand::Move(place) => {
778                         self.visit_place(
779                             place,
780                             PlaceContext::NonMutatingUse(NonMutatingUseContext::Move),
781                             location
782                         );
783                     }
784                     Operand::Constant(constant) => {
785                         self.visit_constant(constant, location);
786                     }
787                 }
788             }
789
790             fn super_ascribe_user_ty(&mut self,
791                                      place: & $($mutability)? Place<'tcx>,
792                                      _variance: & $($mutability)? ty::Variance,
793                                      user_ty: & $($mutability)? UserTypeProjection,
794                                      location: Location) {
795                 self.visit_place(
796                     place,
797                     PlaceContext::NonUse(NonUseContext::AscribeUserTy),
798                     location
799                 );
800                 self.visit_user_type_projection(user_ty);
801             }
802
803             fn super_coverage(&mut self,
804                               _coverage: & $($mutability)? Coverage,
805                               _location: Location) {
806             }
807
808             fn super_retag(&mut self,
809                            _kind: & $($mutability)? RetagKind,
810                            place: & $($mutability)? Place<'tcx>,
811                            location: Location) {
812                 self.visit_place(
813                     place,
814                     PlaceContext::MutatingUse(MutatingUseContext::Retag),
815                     location,
816                 );
817             }
818
819             fn super_local_decl(&mut self,
820                                 local: Local,
821                                 local_decl: & $($mutability)? LocalDecl<'tcx>) {
822                 let LocalDecl {
823                     mutability: _,
824                     ty,
825                     user_ty,
826                     source_info,
827                     internal: _,
828                     local_info: _,
829                     is_block_tail: _,
830                 } = local_decl;
831
832                 self.visit_ty($(& $mutability)? *ty, TyContext::LocalDecl {
833                     local,
834                     source_info: *source_info,
835                 });
836                 if let Some(user_ty) = user_ty {
837                     for (user_ty, _) in & $($mutability)? user_ty.contents {
838                         self.visit_user_type_projection(user_ty);
839                     }
840                 }
841                 self.visit_source_info(source_info);
842             }
843
844             fn super_var_debug_info(&mut self,
845                                     var_debug_info: & $($mutability)? VarDebugInfo<'tcx>) {
846                 let VarDebugInfo {
847                     name: _,
848                     source_info,
849                     value,
850                 } = var_debug_info;
851
852                 self.visit_source_info(source_info);
853                 let location = START_BLOCK.start_location();
854                 match value {
855                     VarDebugInfoContents::Const(c) => self.visit_constant(c, location),
856                     VarDebugInfoContents::Place(place) =>
857                         self.visit_place(
858                             place,
859                             PlaceContext::NonUse(NonUseContext::VarDebugInfo),
860                             location
861                         ),
862                 }
863             }
864
865             #[allow(rustc::pass_by_value)]
866             fn super_source_scope(&mut self,
867                                       _scope: & $($mutability)? SourceScope) {
868             }
869
870             fn super_constant(&mut self,
871                               constant: & $($mutability)? Constant<'tcx>,
872                               location: Location) {
873                 let Constant {
874                     span,
875                     user_ty,
876                     literal,
877                 } = constant;
878
879                 self.visit_span(span);
880                 drop(user_ty); // no visit method for this
881                 match literal {
882                     ConstantKind::Ty(ct) => self.visit_const($(& $mutability)? *ct, location),
883                     ConstantKind::Val(_, ty) => self.visit_ty($(& $mutability)? *ty, TyContext::Location(location)),
884                 }
885             }
886
887             // The macro results in a false positive of sorts, where &mut Span
888             // is fine, but &Span is not; just allow the lint.
889             #[allow(rustc::pass_by_value)]
890             fn super_span(&mut self, _span: & $($mutability)? Span) {
891             }
892
893             fn super_source_info(&mut self, source_info: & $($mutability)? SourceInfo) {
894                 let SourceInfo {
895                     span,
896                     scope,
897                 } = source_info;
898
899                 self.visit_span(span);
900                 self.visit_source_scope(scope);
901             }
902
903             fn super_user_type_projection(
904                 &mut self,
905                 _ty: & $($mutability)? UserTypeProjection,
906             ) {
907             }
908
909             fn super_user_type_annotation(
910                 &mut self,
911                 _index: UserTypeAnnotationIndex,
912                 ty: & $($mutability)? CanonicalUserTypeAnnotation<'tcx>,
913             ) {
914                 self.visit_span(& $($mutability)? ty.span);
915                 self.visit_ty($(& $mutability)? ty.inferred_ty, TyContext::UserTy(ty.span));
916             }
917
918             fn super_ty(&mut self, _ty: $(& $mutability)? Ty<'tcx>) {
919             }
920
921             fn super_region(&mut self, _region: $(& $mutability)? ty::Region<'tcx>) {
922             }
923
924             fn super_const(&mut self, _const: $(& $mutability)? ty::Const<'tcx>) {
925             }
926
927             fn super_substs(&mut self, _substs: & $($mutability)? SubstsRef<'tcx>) {
928             }
929
930             // Convenience methods
931
932             fn visit_location(
933                 &mut self,
934                 body: &$($mutability)? Body<'tcx>,
935                 location: Location
936             ) {
937                 #[cfg_attr(not(bootstrap), allow(unused_macro_rules))]
938                 macro_rules! basic_blocks {
939                     (mut) => (body.basic_blocks_mut());
940                     () => (body.basic_blocks());
941                 }
942                 let basic_block = & $($mutability)? basic_blocks!($($mutability)?)[location.block];
943                 if basic_block.statements.len() == location.statement_index {
944                     if let Some(ref $($mutability)? terminator) = basic_block.terminator {
945                         self.visit_terminator(terminator, location)
946                     }
947                 } else {
948                     let statement = & $($mutability)?
949                         basic_block.statements[location.statement_index];
950                     self.visit_statement(statement, location)
951                 }
952             }
953         }
954     }
955 }
956
957 macro_rules! visit_place_fns {
958     (mut) => {
959         fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
960
961         fn super_place(
962             &mut self,
963             place: &mut Place<'tcx>,
964             context: PlaceContext,
965             location: Location,
966         ) {
967             self.visit_local(&mut place.local, context, location);
968
969             if let Some(new_projection) = self.process_projection(&place.projection, location) {
970                 place.projection = self.tcx().intern_place_elems(&new_projection);
971             }
972         }
973
974         fn process_projection<'a>(
975             &mut self,
976             projection: &'a [PlaceElem<'tcx>],
977             location: Location,
978         ) -> Option<Vec<PlaceElem<'tcx>>> {
979             let mut projection = Cow::Borrowed(projection);
980
981             for i in 0..projection.len() {
982                 if let Some(&elem) = projection.get(i) {
983                     if let Some(elem) = self.process_projection_elem(elem, location) {
984                         // This converts the borrowed projection into `Cow::Owned(_)` and returns a
985                         // clone of the projection so we can mutate and reintern later.
986                         let vec = projection.to_mut();
987                         vec[i] = elem;
988                     }
989                 }
990             }
991
992             match projection {
993                 Cow::Borrowed(_) => None,
994                 Cow::Owned(vec) => Some(vec),
995             }
996         }
997
998         fn process_projection_elem(
999             &mut self,
1000             elem: PlaceElem<'tcx>,
1001             location: Location,
1002         ) -> Option<PlaceElem<'tcx>> {
1003             match elem {
1004                 PlaceElem::Index(local) => {
1005                     let mut new_local = local;
1006                     self.visit_local(
1007                         &mut new_local,
1008                         PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy),
1009                         location,
1010                     );
1011
1012                     if new_local == local { None } else { Some(PlaceElem::Index(new_local)) }
1013                 }
1014                 PlaceElem::Field(field, ty) => {
1015                     let mut new_ty = ty;
1016                     self.visit_ty(&mut new_ty, TyContext::Location(location));
1017                     if ty != new_ty { Some(PlaceElem::Field(field, new_ty)) } else { None }
1018                 }
1019                 PlaceElem::Deref
1020                 | PlaceElem::ConstantIndex { .. }
1021                 | PlaceElem::Subslice { .. }
1022                 | PlaceElem::Downcast(..) => None,
1023             }
1024         }
1025     };
1026
1027     () => {
1028         fn visit_projection(
1029             &mut self,
1030             place_ref: PlaceRef<'tcx>,
1031             context: PlaceContext,
1032             location: Location,
1033         ) {
1034             self.super_projection(place_ref, context, location);
1035         }
1036
1037         fn visit_projection_elem(
1038             &mut self,
1039             local: Local,
1040             proj_base: &[PlaceElem<'tcx>],
1041             elem: PlaceElem<'tcx>,
1042             context: PlaceContext,
1043             location: Location,
1044         ) {
1045             self.super_projection_elem(local, proj_base, elem, context, location);
1046         }
1047
1048         fn super_place(&mut self, place: &Place<'tcx>, context: PlaceContext, location: Location) {
1049             let mut context = context;
1050
1051             if !place.projection.is_empty() {
1052                 if context.is_use() {
1053                     // ^ Only change the context if it is a real use, not a "use" in debuginfo.
1054                     context = if context.is_mutating_use() {
1055                         PlaceContext::MutatingUse(MutatingUseContext::Projection)
1056                     } else {
1057                         PlaceContext::NonMutatingUse(NonMutatingUseContext::Projection)
1058                     };
1059                 }
1060             }
1061
1062             self.visit_local(&place.local, context, location);
1063
1064             self.visit_projection(place.as_ref(), context, location);
1065         }
1066
1067         fn super_projection(
1068             &mut self,
1069             place_ref: PlaceRef<'tcx>,
1070             context: PlaceContext,
1071             location: Location,
1072         ) {
1073             // FIXME: Use PlaceRef::iter_projections, once that exists.
1074             let mut cursor = place_ref.projection;
1075             while let &[ref proj_base @ .., elem] = cursor {
1076                 cursor = proj_base;
1077                 self.visit_projection_elem(place_ref.local, cursor, elem, context, location);
1078             }
1079         }
1080
1081         fn super_projection_elem(
1082             &mut self,
1083             _local: Local,
1084             _proj_base: &[PlaceElem<'tcx>],
1085             elem: PlaceElem<'tcx>,
1086             _context: PlaceContext,
1087             location: Location,
1088         ) {
1089             match elem {
1090                 ProjectionElem::Field(_field, ty) => {
1091                     self.visit_ty(ty, TyContext::Location(location));
1092                 }
1093                 ProjectionElem::Index(local) => {
1094                     self.visit_local(
1095                         &local,
1096                         PlaceContext::NonMutatingUse(NonMutatingUseContext::Copy),
1097                         location,
1098                     );
1099                 }
1100                 ProjectionElem::Deref
1101                 | ProjectionElem::Subslice { from: _, to: _, from_end: _ }
1102                 | ProjectionElem::ConstantIndex { offset: _, min_length: _, from_end: _ }
1103                 | ProjectionElem::Downcast(_, _) => {}
1104             }
1105         }
1106     };
1107 }
1108
1109 make_mir_visitor!(Visitor,);
1110 make_mir_visitor!(MutVisitor, mut);
1111
1112 pub trait MirVisitable<'tcx> {
1113     fn apply(&self, location: Location, visitor: &mut dyn Visitor<'tcx>);
1114 }
1115
1116 impl<'tcx> MirVisitable<'tcx> for Statement<'tcx> {
1117     fn apply(&self, location: Location, visitor: &mut dyn Visitor<'tcx>) {
1118         visitor.visit_statement(self, location)
1119     }
1120 }
1121
1122 impl<'tcx> MirVisitable<'tcx> for Terminator<'tcx> {
1123     fn apply(&self, location: Location, visitor: &mut dyn Visitor<'tcx>) {
1124         visitor.visit_terminator(self, location)
1125     }
1126 }
1127
1128 impl<'tcx> MirVisitable<'tcx> for Option<Terminator<'tcx>> {
1129     fn apply(&self, location: Location, visitor: &mut dyn Visitor<'tcx>) {
1130         visitor.visit_terminator(self.as_ref().unwrap(), location)
1131     }
1132 }
1133
1134 /// Extra information passed to `visit_ty` and friends to give context
1135 /// about where the type etc appears.
1136 #[derive(Debug)]
1137 pub enum TyContext {
1138     LocalDecl {
1139         /// The index of the local variable we are visiting.
1140         local: Local,
1141
1142         /// The source location where this local variable was declared.
1143         source_info: SourceInfo,
1144     },
1145
1146     /// The inferred type of a user type annotation.
1147     UserTy(Span),
1148
1149     /// The return type of the function.
1150     ReturnTy(SourceInfo),
1151
1152     YieldTy(SourceInfo),
1153
1154     /// A type found at some location.
1155     Location(Location),
1156 }
1157
1158 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1159 pub enum NonMutatingUseContext {
1160     /// Being inspected in some way, like loading a len.
1161     Inspect,
1162     /// Consumed as part of an operand.
1163     Copy,
1164     /// Consumed as part of an operand.
1165     Move,
1166     /// Shared borrow.
1167     SharedBorrow,
1168     /// Shallow borrow.
1169     ShallowBorrow,
1170     /// Unique borrow.
1171     UniqueBorrow,
1172     /// AddressOf for *const pointer.
1173     AddressOf,
1174     /// Used as base for another place, e.g., `x` in `x.y`. Will not mutate the place.
1175     /// For example, the projection `x.y` is not marked as a mutation in these cases:
1176     /// ```ignore (illustrative)
1177     /// z = x.y;
1178     /// f(&x.y);
1179     /// ```
1180     Projection,
1181 }
1182
1183 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1184 pub enum MutatingUseContext {
1185     /// Appears as LHS of an assignment.
1186     Store,
1187     /// Appears on `SetDiscriminant`
1188     SetDiscriminant,
1189     /// Appears on `Deinit`
1190     Deinit,
1191     /// Output operand of an inline assembly block.
1192     AsmOutput,
1193     /// Destination of a call.
1194     Call,
1195     /// Destination of a yield.
1196     Yield,
1197     /// Being dropped.
1198     Drop,
1199     /// Mutable borrow.
1200     Borrow,
1201     /// AddressOf for *mut pointer.
1202     AddressOf,
1203     /// Used as base for another place, e.g., `x` in `x.y`. Could potentially mutate the place.
1204     /// For example, the projection `x.y` is marked as a mutation in these cases:
1205     /// ```ignore (illustrative)
1206     /// x.y = ...;
1207     /// f(&mut x.y);
1208     /// ```
1209     Projection,
1210     /// Retagging, a "Stacked Borrows" shadow state operation
1211     Retag,
1212 }
1213
1214 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1215 pub enum NonUseContext {
1216     /// Starting a storage live range.
1217     StorageLive,
1218     /// Ending a storage live range.
1219     StorageDead,
1220     /// User type annotation assertions for NLL.
1221     AscribeUserTy,
1222     /// The data of a user variable, for debug info.
1223     VarDebugInfo,
1224 }
1225
1226 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
1227 pub enum PlaceContext {
1228     NonMutatingUse(NonMutatingUseContext),
1229     MutatingUse(MutatingUseContext),
1230     NonUse(NonUseContext),
1231 }
1232
1233 impl PlaceContext {
1234     /// Returns `true` if this place context represents a drop.
1235     #[inline]
1236     pub fn is_drop(&self) -> bool {
1237         matches!(self, PlaceContext::MutatingUse(MutatingUseContext::Drop))
1238     }
1239
1240     /// Returns `true` if this place context represents a borrow.
1241     pub fn is_borrow(&self) -> bool {
1242         matches!(
1243             self,
1244             PlaceContext::NonMutatingUse(
1245                 NonMutatingUseContext::SharedBorrow
1246                     | NonMutatingUseContext::ShallowBorrow
1247                     | NonMutatingUseContext::UniqueBorrow
1248             ) | PlaceContext::MutatingUse(MutatingUseContext::Borrow)
1249         )
1250     }
1251
1252     /// Returns `true` if this place context represents a storage live or storage dead marker.
1253     #[inline]
1254     pub fn is_storage_marker(&self) -> bool {
1255         matches!(
1256             self,
1257             PlaceContext::NonUse(NonUseContext::StorageLive | NonUseContext::StorageDead)
1258         )
1259     }
1260
1261     /// Returns `true` if this place context represents a use that potentially changes the value.
1262     #[inline]
1263     pub fn is_mutating_use(&self) -> bool {
1264         matches!(self, PlaceContext::MutatingUse(..))
1265     }
1266
1267     /// Returns `true` if this place context represents a use.
1268     #[inline]
1269     pub fn is_use(&self) -> bool {
1270         !matches!(self, PlaceContext::NonUse(..))
1271     }
1272
1273     /// Returns `true` if this place context represents an assignment statement.
1274     pub fn is_place_assignment(&self) -> bool {
1275         matches!(
1276             self,
1277             PlaceContext::MutatingUse(
1278                 MutatingUseContext::Store
1279                     | MutatingUseContext::Call
1280                     | MutatingUseContext::AsmOutput,
1281             )
1282         )
1283     }
1284 }