Skip to main content

rustc_mir_transform/
validate.rs

1//! Validates the MIR to ensure that invariants are upheld.
2
3use rustc_abi::{ExternAbi, FIRST_VARIANT, Size};
4use rustc_data_structures::fx::{FxHashMap, FxHashSet};
5use rustc_hir::attrs::InlineAttr;
6use rustc_hir::attrs::lang_items::LangItem;
7use rustc_index::IndexVec;
8use rustc_index::bit_set::DenseBitSet;
9use rustc_infer::infer::TyCtxtInferExt;
10use rustc_infer::traits::{Obligation, ObligationCause};
11use rustc_middle::mir::coverage::CoverageKind;
12use rustc_middle::mir::visit::{MutatingUseContext, NonUseContext, PlaceContext, Visitor};
13use rustc_middle::mir::*;
14use rustc_middle::ty::adjustment::PointerCoercion;
15use rustc_middle::ty::print::with_no_trimmed_paths;
16use rustc_middle::ty::{
17    self, InstanceKind, ScalarInt, Ty, TyCtxt, TypeVisitableExt, Unnormalized, Upcast, Variance,
18};
19use rustc_middle::{bug, span_bug};
20use rustc_mir_dataflow::debuginfo::debuginfo_locals;
21use rustc_trait_selection::traits::ObligationCtxt;
22
23use crate::PassPolicy;
24use crate::util::{self, most_packed_projection};
25
26#[derive(Copy, Clone, Debug, PartialEq, Eq)]
27enum EdgeKind {
28    Unwind,
29    Normal,
30}
31
32pub(super) struct Validator {
33    /// Describes at which point in the pipeline this validation is happening.
34    pub when: String,
35}
36
37impl<'tcx> crate::MirPass<'tcx> for Validator {
38    fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
39        // FIXME(JakobDegen): These bodies never instantiated in codegend anyway, so it's not
40        // terribly important that they pass the validator. However, I think other passes might
41        // still see them, in which case they might be surprised. It would probably be better if we
42        // didn't put this through the MIR pipeline at all.
43        if matches!(body.source.instance, InstanceKind::Intrinsic(..) | InstanceKind::Virtual(..)) {
44            return;
45        }
46        let def_id = body.source.def_id();
47        let typing_env = body.typing_env(tcx);
48        let can_unwind = if body.phase <= MirPhase::Runtime(RuntimePhase::Initial) {
49            // In this case `AbortUnwindingCalls` haven't yet been executed.
50            true
51        } else if !tcx.def_kind(def_id).is_fn_like() {
52            true
53        } else {
54            let body_ty = tcx.type_of(def_id).skip_binder();
55            let body_abi = match body_ty.kind() {
56                ty::FnDef(..) => body_ty.fn_sig(tcx).abi(),
57                ty::Closure(..) => ExternAbi::RustCall,
58                ty::CoroutineClosure(..) => ExternAbi::RustCall,
59                ty::Coroutine(..) => ExternAbi::Rust,
60                // No need to do MIR validation on error bodies
61                ty::Error(_) => return,
62                _ => span_bug!(body.span, "unexpected body ty: {body_ty}"),
63            };
64
65            ty::layout::fn_can_unwind(tcx, Some(def_id), body_abi)
66        };
67
68        let mut cfg_checker = CfgChecker {
69            when: &self.when,
70            body,
71            tcx,
72            unwind_edge_count: 0,
73            reachable_blocks: traversal::reachable_as_bitset(body),
74            value_cache: FxHashSet::default(),
75            can_unwind,
76        };
77        cfg_checker.visit_body(body);
78        cfg_checker.check_cleanup_control_flow();
79
80        // Also run the TypeChecker.
81        for (location, msg) in validate_types(tcx, typing_env, body, body) {
82            cfg_checker.fail(location, msg);
83        }
84
85        // Ensure that debuginfo records are not emitted for locals that are not in debuginfo.
86        for (location, msg) in validate_debuginfos(body) {
87            cfg_checker.fail(location, msg);
88        }
89
90        if let MirPhase::Runtime(_) = body.phase
91            && let ty::InstanceKind::Item(_) = body.source.instance
92            && body.has_free_regions()
93        {
94            cfg_checker.fail(
95                Location::START,
96                format!("Free regions in optimized {} MIR", body.phase.name()),
97            );
98        }
99    }
100
101    fn policy(&self, _sess: &rustc_session::Session) -> PassPolicy {
102        PassPolicy::optional_non_optimization(true)
103    }
104}
105
106/// This checker covers basic properties of the control-flow graph, (dis)allowed statements and terminators.
107/// Everything checked here must be stable under substitution of generic parameters. In other words,
108/// this is about the *structure* of the MIR, not the *contents*.
109///
110/// Everything that depends on types, or otherwise can be affected by generic parameters,
111/// must be checked in `TypeChecker`.
112struct CfgChecker<'a, 'tcx> {
113    when: &'a str,
114    body: &'a Body<'tcx>,
115    tcx: TyCtxt<'tcx>,
116    unwind_edge_count: usize,
117    reachable_blocks: DenseBitSet<BasicBlock>,
118    value_cache: FxHashSet<u128>,
119    // If `false`, then the MIR must not contain `UnwindAction::Continue` or
120    // `TerminatorKind::Resume`.
121    can_unwind: bool,
122}
123
124impl<'a, 'tcx> CfgChecker<'a, 'tcx> {
125    #[track_caller]
126    fn fail(&self, location: Location, msg: impl AsRef<str>) {
127        // We might see broken MIR when other errors have already occurred.
128        if self.tcx.dcx().has_errors().is_none() {
129            span_bug!(
130                self.body.source_info(location).span,
131                "broken MIR in {:?} ({}) at {:?}:\n{}",
132                self.body.source.instance,
133                self.when,
134                location,
135                msg.as_ref(),
136            );
137        }
138    }
139
140    fn check_edge(&mut self, location: Location, bb: BasicBlock, edge_kind: EdgeKind) {
141        if bb == START_BLOCK {
142            self.fail(location, "start block must not have predecessors")
143        }
144        if let Some(bb) = self.body.basic_blocks.get(bb) {
145            let src = self.body.basic_blocks.get(location.block).unwrap();
146            match (src.is_cleanup, bb.is_cleanup, edge_kind) {
147                // Non-cleanup blocks can jump to non-cleanup blocks along non-unwind edges
148                (false, false, EdgeKind::Normal) => {}
149                // Cleanup blocks can jump to cleanup blocks along non-unwind edges
150                (true, true, EdgeKind::Normal) => {}
151                // Non-cleanup blocks can jump to cleanup blocks along unwind edges
152                (false, true, EdgeKind::Unwind) => {
153                    self.unwind_edge_count += 1;
154                }
155                // All other jumps are invalid
156                _ => self.fail(
157                    location,
158                    format!(
159                        "{:?} edge to {:?} violates unwind invariants (cleanup {:?} -> {:?})",
160                        edge_kind, bb, src.is_cleanup, bb.is_cleanup,
161                    ),
162                ),
163            }
164        } else {
165            self.fail(location, format!("encountered jump to invalid basic block {bb:?}"))
166        }
167    }
168
169    fn check_cleanup_control_flow(&self) {
170        if self.unwind_edge_count <= 1 {
171            return;
172        }
173        let doms = self.body.basic_blocks.dominators();
174        let mut post_contract_node = FxHashMap::default();
175        // Reusing the allocation across invocations of the closure
176        let mut dom_path = vec![];
177        let mut get_post_contract_node = |mut bb| {
178            let root = loop {
179                if let Some(root) = post_contract_node.get(&bb) {
180                    break *root;
181                }
182                let parent = doms.immediate_dominator(bb).unwrap();
183                dom_path.push(bb);
184                if !self.body.basic_blocks[parent].is_cleanup {
185                    break bb;
186                }
187                bb = parent;
188            };
189            for bb in dom_path.drain(..) {
190                post_contract_node.insert(bb, root);
191            }
192            root
193        };
194
195        let mut parent = IndexVec::from_elem(None, &self.body.basic_blocks);
196        for (bb, bb_data) in self.body.basic_blocks.iter_enumerated() {
197            if !bb_data.is_cleanup || !self.reachable_blocks.contains(bb) {
198                continue;
199            }
200            let bb = get_post_contract_node(bb);
201            for s in bb_data.terminator().successors() {
202                let s = get_post_contract_node(s);
203                if s == bb {
204                    continue;
205                }
206                let parent = &mut parent[bb];
207                match parent {
208                    None => {
209                        *parent = Some(s);
210                    }
211                    Some(e) if *e == s => (),
212                    Some(e) => self.fail(
213                        Location { block: bb, statement_index: 0 },
214                        format!(
215                            "Cleanup control flow violation: The blocks dominated by {:?} have edges to both {:?} and {:?}",
216                            bb,
217                            s,
218                            *e
219                        )
220                    ),
221                }
222            }
223        }
224
225        // Check for cycles
226        let mut stack = FxHashSet::default();
227        for (mut bb, parent) in parent.iter_enumerated_mut() {
228            stack.clear();
229            stack.insert(bb);
230            loop {
231                let Some(parent) = parent.take() else { break };
232                let no_cycle = stack.insert(parent);
233                if !no_cycle {
234                    self.fail(
235                        Location { block: bb, statement_index: 0 },
236                        format!(
237                            "Cleanup control flow violation: Cycle involving edge {bb:?} -> {parent:?}",
238                        ),
239                    );
240                    break;
241                }
242                bb = parent;
243            }
244        }
245    }
246
247    fn check_unwind_edge(&mut self, location: Location, unwind: UnwindAction) {
248        let is_cleanup = self.body.basic_blocks[location.block].is_cleanup;
249        match unwind {
250            UnwindAction::Cleanup(unwind) => {
251                if is_cleanup {
252                    self.fail(location, "`UnwindAction::Cleanup` in cleanup block");
253                }
254                self.check_edge(location, unwind, EdgeKind::Unwind);
255            }
256            UnwindAction::Continue => {
257                if is_cleanup {
258                    self.fail(location, "`UnwindAction::Continue` in cleanup block");
259                }
260
261                if !self.can_unwind {
262                    self.fail(location, "`UnwindAction::Continue` in no-unwind function");
263                }
264            }
265            UnwindAction::Terminate(UnwindTerminateReason::InCleanup) => {
266                if !is_cleanup {
267                    self.fail(
268                        location,
269                        "`UnwindAction::Terminate(InCleanup)` in a non-cleanup block",
270                    );
271                }
272            }
273            // These are allowed everywhere.
274            UnwindAction::Unreachable | UnwindAction::Terminate(UnwindTerminateReason::Abi) => (),
275        }
276    }
277
278    fn is_critical_call_edge(&self, target: Option<BasicBlock>, unwind: UnwindAction) -> bool {
279        let Some(target) = target else { return false };
280        matches!(unwind, UnwindAction::Cleanup(_) | UnwindAction::Terminate(_))
281            && self.body.basic_blocks.predecessors()[target].len() > 1
282    }
283}
284
285impl<'a, 'tcx> Visitor<'tcx> for CfgChecker<'a, 'tcx> {
286    fn visit_local(&mut self, local: Local, _context: PlaceContext, location: Location) {
287        if self.body.local_decls.get(local).is_none() {
288            self.fail(
289                location,
290                format!("local {local:?} has no corresponding declaration in `body.local_decls`"),
291            );
292        }
293    }
294
295    fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
296        match &statement.kind {
297            StatementKind::AscribeUserType(..) => {
298                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
299                    self.fail(
300                        location,
301                        "`AscribeUserType` should have been removed after drop lowering phase",
302                    );
303                }
304            }
305            StatementKind::FakeRead(..) => {
306                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
307                    self.fail(
308                        location,
309                        "`FakeRead` should have been removed after drop lowering phase",
310                    );
311                }
312            }
313            StatementKind::SetDiscriminant { .. } => {
314                if self.body.phase < MirPhase::Runtime(RuntimePhase::Initial) {
315                    self.fail(location, "`SetDiscriminant`is not allowed until deaggregation");
316                }
317            }
318            StatementKind::Coverage(kind) => {
319                if self.body.phase >= MirPhase::Analysis(AnalysisPhase::PostCleanup)
320                    && let CoverageKind::BlockMarker { .. } | CoverageKind::SpanMarker { .. } = kind
321                {
322                    self.fail(
323                        location,
324                        format!("{kind:?} should have been removed after analysis"),
325                    );
326                }
327            }
328            StatementKind::Assign(..)
329            | StatementKind::StorageLive(_)
330            | StatementKind::StorageDead(_)
331            | StatementKind::Intrinsic(_)
332            | StatementKind::ConstEvalCounter
333            | StatementKind::PlaceMention(..)
334            | StatementKind::BackwardIncompatibleDropHint { .. }
335            | StatementKind::Nop => {}
336        }
337
338        self.super_statement(statement, location);
339    }
340
341    fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
342        match &terminator.kind {
343            TerminatorKind::Goto { target } => {
344                self.check_edge(location, *target, EdgeKind::Normal);
345            }
346            TerminatorKind::SwitchInt { targets, discr: _ } => {
347                for (_, target) in targets.iter() {
348                    self.check_edge(location, target, EdgeKind::Normal);
349                }
350                self.check_edge(location, targets.otherwise(), EdgeKind::Normal);
351
352                self.value_cache.clear();
353                self.value_cache.extend(targets.iter().map(|(value, _)| value));
354                let has_duplicates = targets.iter().len() != self.value_cache.len();
355                if has_duplicates {
356                    self.fail(
357                        location,
358                        format!(
359                            "duplicated values in `SwitchInt` terminator: {:?}",
360                            terminator.kind,
361                        ),
362                    );
363                }
364            }
365            TerminatorKind::Drop { target, unwind, drop, .. } => {
366                self.check_edge(location, *target, EdgeKind::Normal);
367                self.check_unwind_edge(location, *unwind);
368                if let Some(drop) = drop {
369                    self.check_edge(location, *drop, EdgeKind::Normal);
370                    if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
371                        self.fail(
372                            location,
373                            "`async drop` should have been removed after drop elaboration",
374                        );
375                    }
376                }
377            }
378            TerminatorKind::Call { func, args, .. }
379            | TerminatorKind::TailCall { func, args, .. } => {
380                // FIXME(explicit_tail_calls): refactor this & add tail-call specific checks
381                if let TerminatorKind::Call { target, unwind, destination, .. } = terminator.kind {
382                    if let Some(target) = target {
383                        self.check_edge(location, target, EdgeKind::Normal);
384                    }
385                    self.check_unwind_edge(location, unwind);
386
387                    // The code generation assumes that there are no critical call edges. The
388                    // assumption is used to simplify inserting code that should be executed along
389                    // the return edge from the call. FIXME(tmiasko): Since this is a strictly code
390                    // generation concern, the code generation should be responsible for handling
391                    // it.
392                    if self.body.phase >= MirPhase::Runtime(RuntimePhase::Optimized)
393                        && self.is_critical_call_edge(target, unwind)
394                    {
395                        self.fail(
396                            location,
397                            format!(
398                                "encountered critical edge in `Call` terminator {:?}",
399                                terminator.kind,
400                            ),
401                        );
402                    }
403
404                    // The call destination place and Operand::Move place used as an argument might
405                    // be passed by a reference to the callee. Consequently they cannot be packed.
406                    if most_packed_projection(self.tcx, &self.body.local_decls, destination)
407                        .is_some()
408                    {
409                        // This is bad! The callee will expect the memory to be aligned.
410                        self.fail(
411                            location,
412                            format!(
413                                "encountered packed place in `Call` terminator destination: {:?}",
414                                terminator.kind,
415                            ),
416                        );
417                    }
418                }
419
420                for arg in args {
421                    if let Operand::Move(place) = &arg.node {
422                        if most_packed_projection(self.tcx, &self.body.local_decls, *place)
423                            .is_some()
424                        {
425                            // This is bad! The callee will expect the memory to be aligned.
426                            self.fail(
427                                location,
428                                format!(
429                                    "encountered `Move` of a packed place in `Call` terminator: {:?}",
430                                    terminator.kind,
431                                ),
432                            );
433                        }
434                    }
435                }
436
437                if let ty::FnDef(did, ..) = *func.ty(&self.body.local_decls, self.tcx).kind()
438                    && self.body.phase >= MirPhase::Runtime(RuntimePhase::Optimized)
439                    && matches!(self.tcx.codegen_fn_attrs(did).inline, InlineAttr::Force { .. })
440                {
441                    self.fail(location, "`#[rustc_force_inline]`-annotated function not inlined");
442                }
443            }
444            TerminatorKind::Assert { target, unwind, .. } => {
445                self.check_edge(location, *target, EdgeKind::Normal);
446                self.check_unwind_edge(location, *unwind);
447            }
448            TerminatorKind::Yield { resume, drop, .. } => {
449                if self.body.coroutine.is_none() {
450                    self.fail(location, "`Yield` cannot appear outside coroutine bodies");
451                }
452                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
453                    self.fail(location, "`Yield` should have been replaced by coroutine lowering");
454                }
455                self.check_edge(location, *resume, EdgeKind::Normal);
456                if let Some(drop) = drop {
457                    self.check_edge(location, *drop, EdgeKind::Normal);
458                }
459            }
460            TerminatorKind::FalseEdge { real_target, imaginary_target } => {
461                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
462                    self.fail(
463                        location,
464                        "`FalseEdge` should have been removed after drop elaboration",
465                    );
466                }
467                self.check_edge(location, *real_target, EdgeKind::Normal);
468                self.check_edge(location, *imaginary_target, EdgeKind::Normal);
469            }
470            TerminatorKind::FalseUnwind { real_target, unwind } => {
471                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
472                    self.fail(
473                        location,
474                        "`FalseUnwind` should have been removed after drop elaboration",
475                    );
476                }
477                self.check_edge(location, *real_target, EdgeKind::Normal);
478                self.check_unwind_edge(location, *unwind);
479            }
480            TerminatorKind::InlineAsm { targets, unwind, .. } => {
481                for &target in targets {
482                    self.check_edge(location, target, EdgeKind::Normal);
483                }
484                self.check_unwind_edge(location, *unwind);
485            }
486            TerminatorKind::CoroutineDrop => {
487                if self.body.coroutine.is_none() {
488                    self.fail(location, "`CoroutineDrop` cannot appear outside coroutine bodies");
489                }
490                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
491                    self.fail(
492                        location,
493                        "`CoroutineDrop` should have been replaced by coroutine lowering",
494                    );
495                }
496            }
497            TerminatorKind::UnwindResume => {
498                let bb = location.block;
499                if !self.body.basic_blocks[bb].is_cleanup {
500                    self.fail(location, "Cannot `UnwindResume` from non-cleanup basic block")
501                }
502                if !self.can_unwind {
503                    self.fail(location, "Cannot `UnwindResume` in a function that cannot unwind")
504                }
505            }
506            TerminatorKind::UnwindTerminate(_) => {
507                let bb = location.block;
508                if !self.body.basic_blocks[bb].is_cleanup {
509                    self.fail(location, "Cannot `UnwindTerminate` from non-cleanup basic block")
510                }
511            }
512            TerminatorKind::Return => {
513                let bb = location.block;
514                if self.body.basic_blocks[bb].is_cleanup {
515                    self.fail(location, "Cannot `Return` from cleanup basic block")
516                }
517            }
518            TerminatorKind::Unreachable => {}
519        }
520
521        self.super_terminator(terminator, location);
522    }
523
524    fn visit_source_scope(&mut self, scope: SourceScope) {
525        if self.body.source_scopes.get(scope).is_none() {
526            self.tcx.dcx().span_bug(
527                self.body.span,
528                format!(
529                    "broken MIR in {:?} ({}):\ninvalid source scope {:?}",
530                    self.body.source.instance, self.when, scope,
531                ),
532            );
533        }
534    }
535}
536
537/// A faster version of the validation pass that only checks those things which may break when
538/// instantiating any generic parameters.
539///
540/// `caller_body` is used to detect cycles in MIR inlining and MIR validation before
541/// `optimized_mir` is available.
542pub(super) fn validate_types<'tcx>(
543    tcx: TyCtxt<'tcx>,
544    typing_env: ty::TypingEnv<'tcx>,
545    body: &Body<'tcx>,
546    caller_body: &Body<'tcx>,
547) -> Vec<(Location, String)> {
548    let mut type_checker = TypeChecker { body, caller_body, tcx, typing_env, failures: Vec::new() };
549    // The type checker formats a bunch of strings with type names in it, but these strings
550    // are not always going to be encountered on the error path since the inliner also uses
551    // the validator, and there are certain kinds of inlining (even for valid code) that
552    // can cause validation errors (mostly around where clauses and rigid projections).
553    with_no_trimmed_paths!({
554        type_checker.visit_body(body);
555    });
556    type_checker.failures
557}
558
559struct TypeChecker<'a, 'tcx> {
560    body: &'a Body<'tcx>,
561    caller_body: &'a Body<'tcx>,
562    tcx: TyCtxt<'tcx>,
563    typing_env: ty::TypingEnv<'tcx>,
564    failures: Vec<(Location, String)>,
565}
566
567impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
568    fn fail(&mut self, location: Location, msg: impl Into<String>) {
569        self.failures.push((location, msg.into()));
570    }
571
572    /// Check if src can be assigned into dest.
573    /// This is not precise, it will accept some incorrect assignments.
574    fn mir_assign_valid_types(&self, src: Ty<'tcx>, dest: Ty<'tcx>) -> bool {
575        // Fast path before we normalize.
576        if src == dest {
577            // Equal types, all is good.
578            return true;
579        }
580
581        // We sometimes have to use `defining_opaque_types` for subtyping
582        // to succeed here and figuring out how exactly that should work
583        // is annoying. It is harmless enough to just not validate anything
584        // in that case. We still check this after analysis as all opaque
585        // types have been revealed at this point.
586        if (src, dest).has_opaque_types() {
587            return true;
588        }
589
590        // After borrowck subtyping should be fully explicit via
591        // `Subtype` projections.
592        let variance = if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
593            Variance::Invariant
594        } else {
595            Variance::Covariant
596        };
597
598        crate::util::relate_types(self.tcx, self.typing_env, variance, src, dest)
599    }
600
601    /// Check that the given predicate definitely holds in the param-env of this MIR body.
602    fn predicate_must_hold_modulo_regions(
603        &self,
604        pred: impl Upcast<TyCtxt<'tcx>, ty::Predicate<'tcx>>,
605    ) -> bool {
606        let pred: ty::Predicate<'tcx> = pred.upcast(self.tcx);
607
608        // We sometimes have to use `defining_opaque_types` for predicates
609        // to succeed here and figuring out how exactly that should work
610        // is annoying. It is harmless enough to just not validate anything
611        // in that case. We still check this after analysis as all opaque
612        // types have been revealed at this point.
613        if pred.has_opaque_types() {
614            return true;
615        }
616
617        let (infcx, param_env) = self.tcx.infer_ctxt().build_with_typing_env(self.typing_env);
618        let ocx = ObligationCtxt::new(&infcx);
619        ocx.register_obligation(Obligation::new(
620            self.tcx,
621            ObligationCause::dummy(),
622            param_env,
623            pred,
624        ));
625        ocx.evaluate_obligations_error_on_ambiguity().no_errors()
626    }
627}
628
629impl<'a, 'tcx> Visitor<'tcx> for TypeChecker<'a, 'tcx> {
630    fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
631        // This check is somewhat expensive, so only run it when -Zvalidate-mir is passed.
632        if self.tcx.sess.opts.unstable_opts.validate_mir
633            && self.body.phase < MirPhase::Runtime(RuntimePhase::Initial)
634        {
635            // `Operand::Copy` is only supposed to be used with `Copy` types.
636            if let Operand::Copy(place) = operand {
637                let ty = place.ty(&self.body.local_decls, self.tcx).ty;
638
639                if !self.tcx.type_is_copy_modulo_regions(self.typing_env, ty) {
640                    self.fail(location, format!("`Operand::Copy` with non-`Copy` type {ty}"));
641                }
642            }
643        }
644
645        self.super_operand(operand, location);
646    }
647
648    fn visit_projection_elem(
649        &mut self,
650        place_ref: PlaceRef<'tcx>,
651        elem: PlaceElem<'tcx>,
652        context: PlaceContext,
653        location: Location,
654    ) {
655        match elem {
656            ProjectionElem::Deref
657                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) =>
658            {
659                let base_ty = place_ref.ty(&self.body.local_decls, self.tcx).ty;
660
661                if base_ty.is_box() {
662                    self.fail(location, format!("{base_ty} dereferenced after ElaborateBoxDerefs"))
663                }
664            }
665            ProjectionElem::Field(f, ty) => {
666                let parent_ty = place_ref.ty(&self.body.local_decls, self.tcx);
667                let fail_out_of_bounds = |this: &mut Self, location| {
668                    this.fail(location, format!("Out of bounds field {f:?} for {parent_ty:?}"));
669                };
670                let check_equal = |this: &mut Self, location, f_ty| {
671                    if !this.mir_assign_valid_types(ty, f_ty) {
672                        this.fail(
673                            location,
674                            format!(
675                                "Field projection `{place_ref:?}.{f:?}` specified type `{ty}`, but actual type is `{f_ty}`"
676                            )
677                        )
678                    }
679                };
680
681                let kind = match parent_ty.ty.kind() {
682                    &ty::Alias(_, ty::AliasTy { kind: ty::Opaque { def_id }, args, .. }) => {
683                        self.tcx.type_of(def_id).instantiate(self.tcx, args).skip_norm_wip().kind()
684                    }
685                    kind => kind,
686                };
687
688                match kind {
689                    ty::Tuple(fields) => {
690                        let Some(f_ty) = fields.get(f.as_usize()) else {
691                            fail_out_of_bounds(self, location);
692                            return;
693                        };
694                        check_equal(self, location, *f_ty);
695                    }
696                    // Debug info is allowed to project into pattern types
697                    ty::Pat(base, _) => check_equal(self, location, *base),
698                    ty::Adt(adt_def, args) => {
699                        // see <https://github.com/rust-lang/rust/blob/7601adcc764d42c9f2984082b49948af652df986/compiler/rustc_middle/src/ty/layout.rs#L861-L864>
700                        if self.tcx.is_lang_item(adt_def.did(), LangItem::DynMetadata) {
701                            self.fail(
702                                location,
703                                format!(
704                                    "You can't project to field {f:?} of `DynMetadata` because \
705                                     layout is weird and thinks it doesn't have fields."
706                                ),
707                            );
708                        }
709
710                        if adt_def.repr().simd() || adt_def.repr().scalable() {
711                            self.fail(
712                                location,
713                                format!(
714                                    "Projecting into SIMD type {adt_def:?} is banned by MCP#838"
715                                ),
716                            );
717                        }
718
719                        let var = parent_ty.variant_index.unwrap_or(FIRST_VARIANT);
720                        let Some(field) = adt_def.variant(var).fields.get(f) else {
721                            fail_out_of_bounds(self, location);
722                            return;
723                        };
724                        check_equal(self, location, field.ty(self.tcx, args).skip_norm_wip());
725                    }
726                    ty::Closure(_, args) => {
727                        let args = args.as_closure();
728                        let Some(&f_ty) = args.upvar_tys().get(f.as_usize()) else {
729                            fail_out_of_bounds(self, location);
730                            return;
731                        };
732                        check_equal(self, location, f_ty);
733                    }
734                    ty::CoroutineClosure(_, args) => {
735                        let args = args.as_coroutine_closure();
736                        let Some(&f_ty) = args.upvar_tys().get(f.as_usize()) else {
737                            fail_out_of_bounds(self, location);
738                            return;
739                        };
740                        check_equal(self, location, f_ty);
741                    }
742                    &ty::Coroutine(def_id, args) => {
743                        let f_ty = if let Some(var) = parent_ty.variant_index {
744                            // If we're currently validating an inlined copy of this body,
745                            // then it will no longer be parameterized over the original
746                            // args of the coroutine. Otherwise, we prefer to use this body
747                            // since we may be in the process of computing this MIR in the
748                            // first place.
749                            let layout = if def_id == self.caller_body.source.def_id() {
750                                self.caller_body
751                                    .coroutine_layout_raw()
752                                    .or_else(|| self.tcx.coroutine_layout(def_id, args).ok())
753                            } else if self.tcx.needs_coroutine_by_move_body_def_id(def_id)
754                                && let ty::ClosureKind::FnOnce =
755                                    args.as_coroutine().kind_ty().to_opt_closure_kind().unwrap()
756                                && self.caller_body.source.def_id()
757                                    == self.tcx.coroutine_by_move_body_def_id(def_id)
758                            {
759                                // Same if this is the by-move body of a coroutine-closure.
760                                self.caller_body.coroutine_layout_raw()
761                            } else {
762                                self.tcx.coroutine_layout(def_id, args).ok()
763                            };
764
765                            let Some(layout) = layout else {
766                                self.fail(
767                                    location,
768                                    format!("No coroutine layout for {parent_ty:?}"),
769                                );
770                                return;
771                            };
772
773                            let Some(&local) = layout.variant_fields[var].get(f) else {
774                                fail_out_of_bounds(self, location);
775                                return;
776                            };
777
778                            let Some(f_ty) = layout.field_tys.get(local) else {
779                                self.fail(
780                                    location,
781                                    format!("Out of bounds local {local:?} for {parent_ty:?}"),
782                                );
783                                return;
784                            };
785
786                            ty::EarlyBinder::bind(self.tcx, f_ty.ty)
787                                .instantiate(self.tcx, args)
788                                .skip_norm_wip()
789                        } else if let Some(&f_ty) = args.as_coroutine().upvar_tys().get(f.index()) {
790                            f_ty
791                        } else {
792                            fail_out_of_bounds(self, location);
793                            return;
794                        };
795
796                        check_equal(self, location, f_ty);
797                    }
798                    _ => {
799                        self.fail(location, format!("{:?} does not have fields", parent_ty.ty));
800                    }
801                }
802            }
803            ProjectionElem::Index(index) => {
804                let indexed_ty = place_ref.ty(&self.body.local_decls, self.tcx).ty;
805                match indexed_ty.kind() {
806                    ty::Array(_, _) | ty::Slice(_) => {}
807                    _ => self.fail(location, format!("{indexed_ty:?} cannot be indexed")),
808                }
809
810                let index_ty = self.body.local_decls[index].ty;
811                if index_ty != self.tcx.types.usize {
812                    self.fail(location, format!("bad index ({index_ty} != usize)"))
813                }
814            }
815            ProjectionElem::ConstantIndex { offset, min_length, from_end } => {
816                let indexed_ty = place_ref.ty(&self.body.local_decls, self.tcx).ty;
817                match indexed_ty.kind() {
818                    ty::Array(_, _) => {
819                        if from_end {
820                            self.fail(location, "arrays should not be indexed from end");
821                        }
822                    }
823                    ty::Slice(_) => {}
824                    _ => self.fail(location, format!("{indexed_ty:?} cannot be indexed")),
825                }
826
827                if from_end {
828                    if offset > min_length {
829                        self.fail(
830                            location,
831                            format!(
832                                "constant index with offset -{offset} out of bounds of min length {min_length}"
833                            ),
834                        );
835                    }
836                } else {
837                    if offset >= min_length {
838                        self.fail(
839                            location,
840                            format!(
841                                "constant index with offset {offset} out of bounds of min length {min_length}"
842                            ),
843                        );
844                    }
845                }
846            }
847            ProjectionElem::Subslice { from, to, from_end } => {
848                let indexed_ty = place_ref.ty(&self.body.local_decls, self.tcx).ty;
849                match indexed_ty.kind() {
850                    ty::Array(_, _) => {
851                        if from_end {
852                            self.fail(location, "arrays should not be subsliced from end");
853                        }
854                    }
855                    ty::Slice(_) => {
856                        if !from_end {
857                            self.fail(location, "slices should be subsliced from end");
858                        }
859                    }
860                    _ => self.fail(location, format!("{indexed_ty:?} cannot be indexed")),
861                }
862
863                if !from_end && from > to {
864                    self.fail(location, "backwards subslice {from}..{to}");
865                }
866            }
867            ProjectionElem::OpaqueCast(ty)
868                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) =>
869            {
870                self.fail(
871                    location,
872                    format!("explicit opaque type cast to `{ty}` after `PostAnalysisNormalize`"),
873                )
874            }
875            ProjectionElem::UnwrapUnsafeBinder(unwrapped_ty) => {
876                let binder_ty = place_ref.ty(&self.body.local_decls, self.tcx);
877                let ty::UnsafeBinder(binder_ty) = *binder_ty.ty.kind() else {
878                    self.fail(
879                        location,
880                        format!("WrapUnsafeBinder does not produce a ty::UnsafeBinder"),
881                    );
882                    return;
883                };
884                let binder_inner_ty = self.tcx.instantiate_bound_regions_with_erased(*binder_ty);
885                if !self.mir_assign_valid_types(unwrapped_ty, binder_inner_ty) {
886                    self.fail(
887                        location,
888                        format!(
889                            "Cannot unwrap unsafe binder {binder_ty:?} into type {unwrapped_ty}"
890                        ),
891                    );
892                }
893            }
894            _ => {}
895        }
896        self.super_projection_elem(place_ref, elem, context, location);
897    }
898
899    fn visit_var_debug_info(&mut self, debuginfo: &VarDebugInfo<'tcx>) {
900        if let Some(VarDebugInfoFragment { ty, ref projection }) = debuginfo.composite {
901            if ty.is_union() || ty.is_enum() {
902                self.fail(
903                    START_BLOCK.start_location(),
904                    format!("invalid type {ty} in debuginfo for {:?}", debuginfo.name),
905                );
906            }
907            if projection.is_empty() {
908                self.fail(
909                    START_BLOCK.start_location(),
910                    format!("invalid empty projection in debuginfo for {:?}", debuginfo.name),
911                );
912            }
913            if projection.iter().any(|p| !matches!(p, PlaceElem::Field(..))) {
914                self.fail(
915                    START_BLOCK.start_location(),
916                    format!(
917                        "illegal projection {:?} in debuginfo for {:?}",
918                        projection, debuginfo.name
919                    ),
920                );
921            }
922        }
923        match debuginfo.value {
924            VarDebugInfoContents::Const(_) => {}
925            VarDebugInfoContents::Place(place) => {
926                if place.projection.iter().any(|p| !p.can_use_in_debuginfo()) {
927                    self.fail(
928                        START_BLOCK.start_location(),
929                        format!("illegal place {:?} in debuginfo for {:?}", place, debuginfo.name),
930                    );
931                }
932            }
933        }
934        self.super_var_debug_info(debuginfo);
935    }
936
937    fn visit_place(&mut self, place: &Place<'tcx>, cntxt: PlaceContext, location: Location) {
938        // Set off any `bug!`s in the type computation code
939        let _ = place.ty(&self.body.local_decls, self.tcx);
940
941        if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial)
942            && place.projection.len() > 1
943            && cntxt != PlaceContext::NonUse(NonUseContext::VarDebugInfo)
944            && place.projection[1..].contains(&ProjectionElem::Deref)
945        {
946            self.fail(
947                location,
948                format!("place {place:?} has deref as a later projection (it is only permitted as the first projection)"),
949            );
950        }
951
952        // Ensure all downcast projections are followed by field projections.
953        let mut projections_iter = place.projection.iter();
954        while let Some(proj) = projections_iter.next() {
955            if matches!(proj, ProjectionElem::Downcast(..)) {
956                if !matches!(projections_iter.next(), Some(ProjectionElem::Field(..))) {
957                    self.fail(
958                        location,
959                        format!(
960                            "place {place:?} has `Downcast` projection not followed by `Field`"
961                        ),
962                    );
963                }
964            }
965        }
966
967        if let ClearCrossCrate::Set(LocalInfo::DerefTemp) =
968            self.body.local_decls[place.local].local_info
969            && !place.is_indirect_first_projection()
970        {
971            if cntxt != PlaceContext::MutatingUse(MutatingUseContext::Store)
972                || place.as_local().is_none()
973            {
974                self.fail(
975                    location,
976                    format!("`DerefTemp` locals must only be dereferenced or directly assigned to"),
977                );
978            }
979        }
980
981        if self.body.phase < MirPhase::Runtime(RuntimePhase::Initial)
982            && let Some(i) = place
983                .projection
984                .iter()
985                .position(|elem| matches!(elem, ProjectionElem::Subslice { .. }))
986            && let Some(tail) = place.projection.get(i + 1..)
987            && tail.iter().any(|elem| {
988                matches!(
989                    elem,
990                    ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. }
991                )
992            })
993        {
994            self.fail(
995                location,
996                format!("place {place:?} has `ConstantIndex` or `Subslice` after `Subslice`"),
997            );
998        }
999
1000        self.super_place(place, cntxt, location);
1001    }
1002
1003    fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
1004        macro_rules! check_kinds {
1005            ($t:expr, $text:literal, $typat:pat) => {
1006                if !matches!(($t).kind(), $typat) {
1007                    self.fail(location, format!($text, $t));
1008                }
1009            };
1010        }
1011        match rvalue {
1012            Rvalue::Use(_, _) => {}
1013            Rvalue::CopyForDeref(_) => {
1014                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
1015                    self.fail(location, "`CopyForDeref` should have been removed in runtime MIR");
1016                }
1017            }
1018            Rvalue::Aggregate(kind, fields) => match **kind {
1019                AggregateKind::Tuple => {}
1020                AggregateKind::Array(dest) => {
1021                    for src in fields {
1022                        if !self.mir_assign_valid_types(src.ty(self.body, self.tcx), dest) {
1023                            self.fail(location, "array field has the wrong type");
1024                        }
1025                    }
1026                }
1027                AggregateKind::Adt(def_id, idx, args, _, Some(field)) => {
1028                    let adt_def = self.tcx.adt_def(def_id);
1029                    assert!(adt_def.is_union());
1030                    assert_eq!(idx, FIRST_VARIANT);
1031                    let dest_ty = self.tcx.normalize_erasing_regions(
1032                        self.typing_env,
1033                        adt_def.non_enum_variant().fields[field].ty(self.tcx, args),
1034                    );
1035                    if let [field] = fields.raw.as_slice() {
1036                        let src_ty = field.ty(self.body, self.tcx);
1037                        if !self.mir_assign_valid_types(src_ty, dest_ty) {
1038                            self.fail(location, "union field has the wrong type");
1039                        }
1040                    } else {
1041                        self.fail(location, "unions should have one initialized field");
1042                    }
1043                }
1044                AggregateKind::Adt(def_id, idx, args, _, None) => {
1045                    let adt_def = self.tcx.adt_def(def_id);
1046                    assert!(!adt_def.is_union());
1047                    let variant = &adt_def.variants()[idx];
1048                    if variant.fields.len() != fields.len() {
1049                        self.fail(location, format!(
1050                            "adt {def_id:?} has the wrong number of initialized fields, expected {}, found {}",
1051                            fields.len(),
1052                            variant.fields.len(),
1053                        ));
1054                    }
1055                    for (src, dest) in std::iter::zip(fields, &variant.fields) {
1056                        let dest_ty = self
1057                            .tcx
1058                            .normalize_erasing_regions(self.typing_env, dest.ty(self.tcx, args));
1059                        if !self.mir_assign_valid_types(src.ty(self.body, self.tcx), dest_ty) {
1060                            self.fail(location, "adt field has the wrong type");
1061                        }
1062                    }
1063                }
1064                AggregateKind::Closure(_, args) => {
1065                    let upvars = args.as_closure().upvar_tys();
1066                    if upvars.len() != fields.len() {
1067                        self.fail(location, "closure has the wrong number of initialized fields");
1068                    }
1069                    for (src, dest) in std::iter::zip(fields, upvars) {
1070                        if !self.mir_assign_valid_types(src.ty(self.body, self.tcx), dest) {
1071                            self.fail(location, "closure field has the wrong type");
1072                        }
1073                    }
1074                }
1075                AggregateKind::Coroutine(_, args) => {
1076                    let upvars = args.as_coroutine().upvar_tys();
1077                    if upvars.len() != fields.len() {
1078                        self.fail(location, "coroutine has the wrong number of initialized fields");
1079                    }
1080                    for (src, dest) in std::iter::zip(fields, upvars) {
1081                        if !self.mir_assign_valid_types(src.ty(self.body, self.tcx), dest) {
1082                            self.fail(location, "coroutine field has the wrong type");
1083                        }
1084                    }
1085                }
1086                AggregateKind::CoroutineClosure(_, args) => {
1087                    let upvars = args.as_coroutine_closure().upvar_tys();
1088                    if upvars.len() != fields.len() {
1089                        self.fail(
1090                            location,
1091                            "coroutine-closure has the wrong number of initialized fields",
1092                        );
1093                    }
1094                    for (src, dest) in std::iter::zip(fields, upvars) {
1095                        if !self.mir_assign_valid_types(src.ty(self.body, self.tcx), dest) {
1096                            self.fail(location, "coroutine-closure field has the wrong type");
1097                        }
1098                    }
1099                }
1100                AggregateKind::RawPtr(pointee_ty, mutability) => {
1101                    if !matches!(self.body.phase, MirPhase::Runtime(_)) {
1102                        // It would probably be fine to support this in earlier phases, but at the
1103                        // time of writing it's only ever introduced from intrinsic lowering, so
1104                        // earlier things just `bug!` on it.
1105                        self.fail(location, "RawPtr should be in runtime MIR only");
1106                    }
1107
1108                    if let [data_ptr, metadata] = fields.raw.as_slice() {
1109                        let data_ptr_ty = data_ptr.ty(self.body, self.tcx);
1110                        let metadata_ty = metadata.ty(self.body, self.tcx);
1111                        if let ty::RawPtr(in_pointee, in_mut) = data_ptr_ty.kind() {
1112                            if *in_mut != mutability {
1113                                self.fail(location, "input and output mutability must match");
1114                            }
1115
1116                            // FIXME: check `Thin` instead of `Sized`
1117                            if !in_pointee.is_sized(self.tcx, self.typing_env) {
1118                                self.fail(location, "input pointer must be thin");
1119                            }
1120                        } else {
1121                            self.fail(
1122                                location,
1123                                "first operand to raw pointer aggregate must be a raw pointer",
1124                            );
1125                        }
1126
1127                        // FIXME: Check metadata more generally
1128                        if pointee_ty.is_slice() {
1129                            if !self.mir_assign_valid_types(metadata_ty, self.tcx.types.usize) {
1130                                self.fail(location, "slice metadata must be usize");
1131                            }
1132                        } else if pointee_ty.is_sized(self.tcx, self.typing_env) {
1133                            if metadata_ty != self.tcx.types.unit {
1134                                self.fail(location, "metadata for pointer-to-thin must be unit");
1135                            }
1136                        }
1137                    } else {
1138                        self.fail(location, "raw pointer aggregate must have 2 fields");
1139                    }
1140                }
1141            },
1142            Rvalue::Ref(_, BorrowKind::Fake(_), _) => {
1143                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
1144                    self.fail(
1145                        location,
1146                        "`Assign` statement with a `Fake` borrow should have been removed in runtime MIR",
1147                    );
1148                }
1149            }
1150            Rvalue::Ref(..) | Rvalue::Reborrow(..) => {}
1151            Rvalue::BinaryOp(op, vals) => {
1152                use BinOp::*;
1153                let a = vals.0.ty(&self.body.local_decls, self.tcx);
1154                let b = vals.1.ty(&self.body.local_decls, self.tcx);
1155                if crate::util::binop_right_homogeneous(*op) {
1156                    if let Eq | Lt | Le | Ne | Ge | Gt = op {
1157                        // The function pointer types can have lifetimes
1158                        if !self.mir_assign_valid_types(a, b) {
1159                            self.fail(
1160                                location,
1161                                format!("Cannot {op:?} compare incompatible types {a} and {b}"),
1162                            );
1163                        }
1164                    } else if a != b {
1165                        self.fail(
1166                            location,
1167                            format!("Cannot perform binary op {op:?} on unequal types {a} and {b}"),
1168                        );
1169                    }
1170                }
1171
1172                match op {
1173                    Offset => {
1174                        check_kinds!(a, "Cannot offset non-pointer type {:?}", ty::RawPtr(..));
1175                        if b != self.tcx.types.isize && b != self.tcx.types.usize {
1176                            self.fail(location, format!("Cannot offset by non-isize type {b}"));
1177                        }
1178                    }
1179                    Eq | Lt | Le | Ne | Ge | Gt => {
1180                        for x in [a, b] {
1181                            check_kinds!(
1182                                x,
1183                                "Cannot {op:?} compare type {:?}",
1184                                ty::Bool
1185                                    | ty::Char
1186                                    | ty::Int(..)
1187                                    | ty::Uint(..)
1188                                    | ty::Float(..)
1189                                    | ty::RawPtr(..)
1190                                    | ty::FnPtr(..)
1191                            )
1192                        }
1193                    }
1194                    Cmp => {
1195                        for x in [a, b] {
1196                            check_kinds!(
1197                                x,
1198                                "Cannot three-way compare non-integer type {:?}",
1199                                ty::Char | ty::Uint(..) | ty::Int(..)
1200                            )
1201                        }
1202                    }
1203                    AddUnchecked | AddWithOverflow | SubUnchecked | SubWithOverflow
1204                    | MulUnchecked | MulWithOverflow | Shl | ShlUnchecked | Shr | ShrUnchecked => {
1205                        for x in [a, b] {
1206                            check_kinds!(
1207                                x,
1208                                "Cannot {op:?} non-integer type {:?}",
1209                                ty::Uint(..) | ty::Int(..)
1210                            )
1211                        }
1212                    }
1213                    BitAnd | BitOr | BitXor => {
1214                        for x in [a, b] {
1215                            check_kinds!(
1216                                x,
1217                                "Cannot perform bitwise op {op:?} on type {:?}",
1218                                ty::Uint(..) | ty::Int(..) | ty::Bool
1219                            )
1220                        }
1221                    }
1222                    Add | Sub | Mul | Div | Rem => {
1223                        for x in [a, b] {
1224                            check_kinds!(
1225                                x,
1226                                "Cannot perform arithmetic {op:?} on type {:?}",
1227                                ty::Uint(..) | ty::Int(..) | ty::Float(..)
1228                            )
1229                        }
1230                    }
1231                }
1232            }
1233            Rvalue::UnaryOp(op, operand) => {
1234                let a = operand.ty(&self.body.local_decls, self.tcx);
1235                match op {
1236                    UnOp::Neg => {
1237                        check_kinds!(a, "Cannot negate type {:?}", ty::Int(..) | ty::Float(..))
1238                    }
1239                    UnOp::Not => {
1240                        check_kinds!(
1241                            a,
1242                            "Cannot binary not type {:?}",
1243                            ty::Int(..) | ty::Uint(..) | ty::Bool
1244                        );
1245                    }
1246                    UnOp::PtrMetadata => {
1247                        check_kinds!(
1248                            a,
1249                            "Cannot PtrMetadata non-pointer non-reference type {:?}",
1250                            ty::RawPtr(..) | ty::Ref(..)
1251                        );
1252                    }
1253                }
1254            }
1255            Rvalue::Cast(kind, operand, target_type) => {
1256                let op_ty = operand.ty(self.body, self.tcx);
1257                match kind {
1258                    // FIXME: Add Checks for these
1259                    CastKind::PointerWithExposedProvenance | CastKind::PointerExposeProvenance => {}
1260                    CastKind::PointerCoercion(PointerCoercion::ReifyFnPointer(_), _) => {
1261                        // FIXME: check signature compatibility.
1262                        check_kinds!(
1263                            op_ty,
1264                            "CastKind::{kind:?} input must be a fn item, not {:?}",
1265                            ty::FnDef(..)
1266                        );
1267                        check_kinds!(
1268                            target_type,
1269                            "CastKind::{kind:?} output must be a fn pointer, not {:?}",
1270                            ty::FnPtr(..)
1271                        );
1272                    }
1273                    CastKind::PointerCoercion(PointerCoercion::UnsafeFnPointer, _) => {
1274                        // FIXME: check safety and signature compatibility.
1275                        check_kinds!(
1276                            op_ty,
1277                            "CastKind::{kind:?} input must be a fn pointer, not {:?}",
1278                            ty::FnPtr(..)
1279                        );
1280                        check_kinds!(
1281                            target_type,
1282                            "CastKind::{kind:?} output must be a fn pointer, not {:?}",
1283                            ty::FnPtr(..)
1284                        );
1285                    }
1286                    CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(..), _) => {
1287                        // FIXME: check safety, captures, and signature compatibility.
1288                        check_kinds!(
1289                            op_ty,
1290                            "CastKind::{kind:?} input must be a closure, not {:?}",
1291                            ty::Closure(..)
1292                        );
1293                        check_kinds!(
1294                            target_type,
1295                            "CastKind::{kind:?} output must be a fn pointer, not {:?}",
1296                            ty::FnPtr(..)
1297                        );
1298                    }
1299                    CastKind::PointerCoercion(PointerCoercion::MutToConstPointer, _) => {
1300                        // FIXME: check same pointee?
1301                        check_kinds!(
1302                            op_ty,
1303                            "CastKind::{kind:?} input must be a raw mut pointer, not {:?}",
1304                            ty::RawPtr(_, Mutability::Mut)
1305                        );
1306                        check_kinds!(
1307                            target_type,
1308                            "CastKind::{kind:?} output must be a raw const pointer, not {:?}",
1309                            ty::RawPtr(_, Mutability::Not)
1310                        );
1311                        if self.body.phase >= MirPhase::Analysis(AnalysisPhase::PostCleanup) {
1312                            self.fail(location, format!("After borrowck, MIR disallows {kind:?}"));
1313                        }
1314                    }
1315                    CastKind::PointerCoercion(PointerCoercion::ArrayToPointer, _) => {
1316                        // FIXME: Check pointee types
1317                        check_kinds!(
1318                            op_ty,
1319                            "CastKind::{kind:?} input must be a raw pointer, not {:?}",
1320                            ty::RawPtr(..)
1321                        );
1322                        check_kinds!(
1323                            target_type,
1324                            "CastKind::{kind:?} output must be a raw pointer, not {:?}",
1325                            ty::RawPtr(..)
1326                        );
1327                        if self.body.phase >= MirPhase::Analysis(AnalysisPhase::PostCleanup) {
1328                            self.fail(location, format!("After borrowck, MIR disallows {kind:?}"));
1329                        }
1330                    }
1331                    CastKind::PointerCoercion(PointerCoercion::Unsize, _) => {
1332                        // Pointers being unsize coerced should at least implement
1333                        // `CoerceUnsized`.
1334                        if !self.predicate_must_hold_modulo_regions(ty::TraitRef::new(
1335                            self.tcx,
1336                            self.tcx.require_lang_item(
1337                                LangItem::CoerceUnsized,
1338                                self.body.source_info(location).span,
1339                            ),
1340                            [op_ty, *target_type],
1341                        )) {
1342                            self.fail(location, format!("Unsize coercion, but `{op_ty}` isn't coercible to `{target_type}`"));
1343                        }
1344                    }
1345                    CastKind::IntToInt | CastKind::IntToFloat => {
1346                        let input_valid = op_ty.is_integral() || op_ty.is_char() || op_ty.is_bool();
1347                        let target_valid = target_type.is_numeric() || target_type.is_char();
1348                        if !input_valid || !target_valid {
1349                            self.fail(
1350                                location,
1351                                format!("Wrong cast kind {kind:?} for the type {op_ty}"),
1352                            );
1353                        }
1354                    }
1355                    CastKind::FnPtrToPtr => {
1356                        check_kinds!(
1357                            op_ty,
1358                            "CastKind::{kind:?} input must be a fn pointer, not {:?}",
1359                            ty::FnPtr(..)
1360                        );
1361                        check_kinds!(
1362                            target_type,
1363                            "CastKind::{kind:?} output must be a raw pointer, not {:?}",
1364                            ty::RawPtr(..)
1365                        );
1366                    }
1367                    CastKind::PtrToPtr => {
1368                        check_kinds!(
1369                            op_ty,
1370                            "CastKind::{kind:?} input must be a raw pointer, not {:?}",
1371                            ty::RawPtr(..)
1372                        );
1373                        check_kinds!(
1374                            target_type,
1375                            "CastKind::{kind:?} output must be a raw pointer, not {:?}",
1376                            ty::RawPtr(..)
1377                        );
1378                    }
1379                    CastKind::FloatToFloat | CastKind::FloatToInt => {
1380                        if !op_ty.is_floating_point() || !target_type.is_numeric() {
1381                            self.fail(
1382                                location,
1383                                format!(
1384                                    "Trying to cast non 'Float' as {kind:?} into {target_type:?}"
1385                                ),
1386                            );
1387                        }
1388                    }
1389                    CastKind::Transmute | CastKind::BoxDerefTransmute => {
1390                        // Unlike `mem::transmute`, a MIR `Transmute` is well-formed
1391                        // for any two `Sized` types, just potentially UB to run.
1392
1393                        if !self
1394                            .tcx
1395                            .normalize_erasing_regions(
1396                                self.typing_env,
1397                                Unnormalized::new_wip(op_ty),
1398                            )
1399                            .is_sized(self.tcx, self.typing_env)
1400                        {
1401                            self.fail(
1402                                location,
1403                                format!("Cannot transmute from non-`Sized` type {op_ty}"),
1404                            );
1405                        }
1406                        if !self
1407                            .tcx
1408                            .normalize_erasing_regions(
1409                                self.typing_env,
1410                                Unnormalized::new_wip(*target_type),
1411                            )
1412                            .is_sized(self.tcx, self.typing_env)
1413                        {
1414                            self.fail(
1415                                location,
1416                                format!("Cannot transmute to non-`Sized` type {target_type:?}"),
1417                            );
1418                        }
1419
1420                        if matches!(kind, CastKind::BoxDerefTransmute) {
1421                            if !target_type.is_raw_ptr() {
1422                                self.fail(
1423                                    location,
1424                                    format!(
1425                                        "Cannot BoxDerefTransmute to non-pointer type {target_type}"
1426                                    ),
1427                                );
1428                            }
1429                        }
1430                    }
1431                    CastKind::Subtype => {
1432                        if !util::sub_types(self.tcx, self.typing_env, op_ty, *target_type) {
1433                            self.fail(
1434                                location,
1435                                format!("Failed subtyping {op_ty} and {target_type}"),
1436                            )
1437                        }
1438                    }
1439                }
1440            }
1441            Rvalue::Repeat(_, _)
1442            | Rvalue::ThreadLocalRef(_)
1443            | Rvalue::RawPtr(_, _)
1444            | Rvalue::Discriminant(_) => {}
1445
1446            Rvalue::WrapUnsafeBinder(op, ty) => {
1447                let unwrapped_ty = op.ty(self.body, self.tcx);
1448                let ty::UnsafeBinder(binder_ty) = *ty.kind() else {
1449                    self.fail(
1450                        location,
1451                        format!("WrapUnsafeBinder does not produce a ty::UnsafeBinder"),
1452                    );
1453                    return;
1454                };
1455                let binder_inner_ty = self.tcx.instantiate_bound_regions_with_erased(*binder_ty);
1456                if !self.mir_assign_valid_types(unwrapped_ty, binder_inner_ty) {
1457                    self.fail(
1458                        location,
1459                        format!("Cannot wrap {unwrapped_ty} into unsafe binder {binder_ty:?}"),
1460                    );
1461                }
1462            }
1463        }
1464        self.super_rvalue(rvalue, location);
1465    }
1466
1467    fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
1468        match &statement.kind {
1469            StatementKind::Assign((dest, rvalue)) => {
1470                // LHS and RHS of the assignment must have the same type.
1471                let left_ty = dest.ty(&self.body.local_decls, self.tcx).ty;
1472                let right_ty = rvalue.ty(&self.body.local_decls, self.tcx);
1473
1474                if !self.mir_assign_valid_types(right_ty, left_ty) {
1475                    self.fail(
1476                        location,
1477                        format!(
1478                            "encountered `{:?}` with incompatible types:\n\
1479                            left-hand side has type: {}\n\
1480                            right-hand side has type: {}",
1481                            statement.kind, left_ty, right_ty,
1482                        ),
1483                    );
1484                }
1485
1486                if let Some(local) = dest.as_local()
1487                    && let ClearCrossCrate::Set(LocalInfo::DerefTemp) =
1488                        self.body.local_decls[local].local_info
1489                    && !matches!(rvalue, Rvalue::CopyForDeref(_))
1490                {
1491                    self.fail(location, "assignment to a `DerefTemp` must use `CopyForDeref`")
1492                }
1493            }
1494            StatementKind::AscribeUserType(..) => {
1495                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
1496                    self.fail(
1497                        location,
1498                        "`AscribeUserType` should have been removed after drop lowering phase",
1499                    );
1500                }
1501            }
1502            StatementKind::FakeRead(..) => {
1503                if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
1504                    self.fail(
1505                        location,
1506                        "`FakeRead` should have been removed after drop lowering phase",
1507                    );
1508                }
1509            }
1510            StatementKind::Intrinsic(NonDivergingIntrinsic::Assume(op)) => {
1511                let ty = op.ty(&self.body.local_decls, self.tcx);
1512                if !ty.is_bool() {
1513                    self.fail(
1514                        location,
1515                        format!("`assume` argument must be `bool`, but got: `{ty}`"),
1516                    );
1517                }
1518            }
1519            StatementKind::Intrinsic(NonDivergingIntrinsic::CopyNonOverlapping(
1520                CopyNonOverlapping { src, dst, count },
1521            )) => {
1522                let src_ty = src.ty(&self.body.local_decls, self.tcx);
1523                let op_src_ty = if let Some(src_deref) = src_ty.builtin_deref(true) {
1524                    src_deref
1525                } else {
1526                    self.fail(
1527                        location,
1528                        format!("Expected src to be ptr in copy_nonoverlapping, got: {src_ty}"),
1529                    );
1530                    return;
1531                };
1532                let dst_ty = dst.ty(&self.body.local_decls, self.tcx);
1533                let op_dst_ty = if let Some(dst_deref) = dst_ty.builtin_deref(true) {
1534                    dst_deref
1535                } else {
1536                    self.fail(
1537                        location,
1538                        format!("Expected dst to be ptr in copy_nonoverlapping, got: {dst_ty}"),
1539                    );
1540                    return;
1541                };
1542                // since CopyNonOverlapping is parametrized by 1 type,
1543                // we only need to check that they are equal and not keep an extra parameter.
1544                if !self.mir_assign_valid_types(op_src_ty, op_dst_ty) {
1545                    self.fail(location, format!("bad arg ({op_src_ty} != {op_dst_ty})"));
1546                }
1547
1548                let op_cnt_ty = count.ty(&self.body.local_decls, self.tcx);
1549                if op_cnt_ty != self.tcx.types.usize {
1550                    self.fail(location, format!("bad arg ({op_cnt_ty} != usize)"))
1551                }
1552            }
1553            StatementKind::SetDiscriminant { place, .. } => {
1554                if self.body.phase < MirPhase::Runtime(RuntimePhase::Initial) {
1555                    self.fail(location, "`SetDiscriminant`is not allowed until deaggregation");
1556                }
1557                let pty = place.ty(&self.body.local_decls, self.tcx).ty;
1558                if !matches!(
1559                    pty.kind(),
1560                    ty::Adt(..)
1561                        | ty::Coroutine(..)
1562                        | ty::Alias(_, ty::AliasTy { kind: ty::Opaque { .. }, .. })
1563                ) {
1564                    self.fail(
1565                        location,
1566                        format!(
1567                            "`SetDiscriminant` is only allowed on ADTs and coroutines, not {pty}"
1568                        ),
1569                    );
1570                }
1571            }
1572            StatementKind::StorageLive(_)
1573            | StatementKind::StorageDead(_)
1574            | StatementKind::Coverage(_)
1575            | StatementKind::ConstEvalCounter
1576            | StatementKind::PlaceMention(..)
1577            | StatementKind::BackwardIncompatibleDropHint { .. }
1578            | StatementKind::Nop => {}
1579        }
1580
1581        self.super_statement(statement, location);
1582    }
1583
1584    fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
1585        match &terminator.kind {
1586            TerminatorKind::SwitchInt { targets, discr } => {
1587                let switch_ty = discr.ty(&self.body.local_decls, self.tcx);
1588
1589                let target_width = self.tcx.sess.target.pointer_width;
1590
1591                let size = Size::from_bits(match switch_ty.kind() {
1592                    ty::Uint(uint) => uint.normalize(target_width).bit_width().unwrap(),
1593                    ty::Int(int) => int.normalize(target_width).bit_width().unwrap(),
1594                    ty::Char => 32,
1595                    ty::Bool => 1,
1596                    other => bug!("unhandled type: {:?}", other),
1597                });
1598
1599                for (value, _) in targets.iter() {
1600                    if ScalarInt::try_from_uint(value, size).is_none() {
1601                        self.fail(
1602                            location,
1603                            format!("the value {value:#x} is not a proper {switch_ty}"),
1604                        )
1605                    }
1606                }
1607            }
1608            TerminatorKind::Call { func, .. } | TerminatorKind::TailCall { func, .. } => {
1609                let func_ty = func.ty(&self.body.local_decls, self.tcx);
1610                match func_ty.kind() {
1611                    ty::FnPtr(..) | ty::FnDef(..) => {}
1612                    _ => self.fail(
1613                        location,
1614                        format!(
1615                            "encountered non-callable type {func_ty} in `{}` terminator",
1616                            terminator.kind.name()
1617                        ),
1618                    ),
1619                }
1620
1621                if let TerminatorKind::TailCall { .. } = terminator.kind {
1622                    // FIXME(explicit_tail_calls): implement tail-call specific checks here (such
1623                    // as signature matching, forbidding closures, etc)
1624                }
1625            }
1626            TerminatorKind::Assert { cond, .. } => {
1627                let cond_ty = cond.ty(&self.body.local_decls, self.tcx);
1628                if cond_ty != self.tcx.types.bool {
1629                    self.fail(
1630                        location,
1631                        format!(
1632                            "encountered non-boolean condition of type {cond_ty} in `Assert` terminator"
1633                        ),
1634                    );
1635                }
1636            }
1637            TerminatorKind::Goto { .. }
1638            | TerminatorKind::Drop { .. }
1639            | TerminatorKind::Yield { .. }
1640            | TerminatorKind::FalseEdge { .. }
1641            | TerminatorKind::FalseUnwind { .. }
1642            | TerminatorKind::InlineAsm { .. }
1643            | TerminatorKind::CoroutineDrop
1644            | TerminatorKind::UnwindResume
1645            | TerminatorKind::UnwindTerminate(_)
1646            | TerminatorKind::Return
1647            | TerminatorKind::Unreachable => {}
1648        }
1649
1650        self.super_terminator(terminator, location);
1651    }
1652
1653    fn visit_local_decl(&mut self, local: Local, local_decl: &LocalDecl<'tcx>) {
1654        if let ClearCrossCrate::Set(LocalInfo::DerefTemp) = local_decl.local_info {
1655            if self.body.phase >= MirPhase::Runtime(RuntimePhase::Initial) {
1656                self.fail(
1657                    START_BLOCK.start_location(),
1658                    "`DerefTemp` should have been removed in runtime MIR",
1659                );
1660            } else if local_decl.ty.builtin_deref(true).is_none() {
1661                self.fail(
1662                    START_BLOCK.start_location(),
1663                    "`DerefTemp` should only be used for dereferenceable types",
1664                )
1665            }
1666        }
1667
1668        self.super_local_decl(local, local_decl);
1669    }
1670}
1671
1672pub(super) fn validate_debuginfos<'tcx>(body: &Body<'tcx>) -> Vec<(Location, String)> {
1673    let mut debuginfo_checker =
1674        DebuginfoChecker { debuginfo_locals: debuginfo_locals(body), failures: Vec::new() };
1675    debuginfo_checker.visit_body(body);
1676    debuginfo_checker.failures
1677}
1678
1679struct DebuginfoChecker {
1680    debuginfo_locals: DenseBitSet<Local>,
1681    failures: Vec<(Location, String)>,
1682}
1683
1684impl<'tcx> Visitor<'tcx> for DebuginfoChecker {
1685    fn visit_statement_debuginfo(
1686        &mut self,
1687        stmt_debuginfo: &StmtDebugInfo<'tcx>,
1688        location: Location,
1689    ) {
1690        let local = match stmt_debuginfo {
1691            StmtDebugInfo::AssignRef(local, _) | StmtDebugInfo::InvalidAssign(local) => *local,
1692        };
1693        if !self.debuginfo_locals.contains(local) {
1694            self.failures.push((location, format!("{local:?} is not in debuginfo")));
1695        }
1696    }
1697}