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