1use crate::def_ids::type_ids;
4use crate::analysis::dataflow::{call_read, call_write, pointer_copy};
5use crate::analysis::dataflow::pointer_flow::{self, trace_source_arg};
6use crate::util::mir_utils;
7use crate::analysis::dataflow::call_summary::VerifierCallSemantics;
8use crate::analysis::dataflow::call_summary::pointer_semantics;
9use crate::contract::PropertyKind;
10use std::collections::{HashMap, HashSet};
11
12use rustc_hir::{Safety, def::DefKind, def_id::DefId};
13use rustc_middle::{
14 mir::{
15 BasicBlock, Body, Local, LocalDecls, Operand, Place, ProjectionElem, Rvalue, StatementKind,
16 TerminatorKind,
17 },
18 ty::{self, AssocKind, TyCtxt, TyKind},
19};
20
21use crate::analysis::alias::{FieldOrigin, resolve_any_field_origin, resolve_self_field_origin};
22use crate::util::fn_info::is_externally_reachable;
23use crate::{
24 util::def_use::{PlaceBaseKey, PlaceKey},
25 util::mir_scan::get_fn_safety,
26};
27
28pub(crate) use crate::util::mir_utils::{operand_mir_place, operand_place};
30use crate::util::mir_utils::{blocks_reachable_after_call, rvalue_any_place_matching};
32
33#[derive(Clone, Copy, Debug, Eq, PartialEq)]
36pub(crate) enum HazardKind {
37 SharedView,
38 UniqueView,
39}
40
41#[derive(Clone, Copy, Debug, Eq, PartialEq)]
42pub(crate) enum AliasProducer {
43 View(HazardKind, usize),
44 OwnershipTransfer(usize),
45 ReadMemory(usize),
46 CopyMemory(usize),
47}
48
49#[derive(Clone, Copy, Debug, Eq, PartialEq)]
50enum RawAccessKind {
51 Read,
52 Write,
53}
54
55#[derive(Clone, Debug)]
56struct LocalCallsite<'tcx> {
57 pub caller: DefId,
58 pub block: BasicBlock,
59 pub args: Vec<Operand<'tcx>>,
60 pub destination: Option<Local>,
61}
62
63#[derive(Clone, Debug, PartialEq, Eq)]
64pub(crate) enum HazardCheck {
65 Safe(String),
66 Violation(String),
67 Inconclusive,
68}
69
70pub(crate) fn alias_producer(tcx: TyCtxt<'_>, callee: DefId) -> Option<AliasProducer> {
73 if let Some(source_arg) = ownership_transfer_source_arg(tcx, callee) {
74 return Some(AliasProducer::OwnershipTransfer(source_arg));
75 }
76 if let Some(source_arg) = share_transfer_source_arg(tcx, callee) {
77 return Some(AliasProducer::OwnershipTransfer(source_arg));
78 }
79 if let Some(flow) = pointer_copy::copy_flow(tcx, callee) {
80 return Some(AliasProducer::CopyMemory(flow.source_arg));
81 }
82 if let Some(source_arg) = call_read::read_source_arg(tcx, callee) {
83 return Some(AliasProducer::ReadMemory(source_arg));
84 }
85 raw_pointer_view_from_mir(tcx, callee)
86 .map(|(kind, source_arg)| AliasProducer::View(kind, source_arg))
87}
88
89fn share_transfer_source_arg(tcx: TyCtxt<'_>, callee: DefId) -> Option<usize> {
90 if !matches!(tcx.def_kind(callee), DefKind::Fn | DefKind::AssocFn) {
91 return None;
92 }
93 let sig = tcx.fn_sig(callee).skip_binder();
94 if !matches!(sig.output().skip_binder().kind(), ty::Adt(..))
95 || !sig.inputs().skip_binder().iter().any(|ty| matches!(ty.kind(), ty::RawPtr(..)))
96 {
97 return None;
98 }
99 crate::contract::json::ref_count_share_arg_indices(tcx, callee).into_iter().next()
100}
101
102pub(crate) fn reconstructed_owner(tcx: TyCtxt<'_>, callee: DefId) -> Option<(usize, DefId)> {
103 if !matches!(tcx.def_kind(callee), DefKind::Fn | DefKind::AssocFn) {
104 return None;
105 }
106 let sig = tcx.fn_sig(callee).skip_binder();
107 let output = sig.output().skip_binder();
108 let ty::Adt(adt, _) = output.kind() else {
109 return None;
110 };
111 if !sig.inputs().skip_binder().iter().any(|ty| matches!(ty.kind(), ty::RawPtr(..))) {
112 return None;
113 }
114 let AliasProducer::OwnershipTransfer(source) = alias_producer(tcx, callee)? else {
115 return None;
116 };
117 Some((source, adt.did()))
118}
119
120fn raw_pointer_view_from_mir(tcx: TyCtxt<'_>, callee: DefId) -> Option<(HazardKind, usize)> {
123 if !tcx.is_mir_available(callee) {
124 return None;
125 }
126 let body = tcx.optimized_mir(callee);
127 let kind = match body.local_decls[rustc_middle::mir::RETURN_PLACE].ty.kind() {
128 ty::Ref(_, _, ty::Mutability::Not) => HazardKind::SharedView,
129 ty::Ref(_, _, ty::Mutability::Mut) => HazardKind::UniqueView,
130 _ => return None,
131 };
132 let source_arg = trace_returned_ref(
133 tcx,
134 body,
135 rustc_middle::mir::RETURN_PLACE,
136 &mut HashSet::new(),
137 5,
138 )?;
139 let inputs = tcx.fn_sig(callee).skip_binder().inputs().skip_binder();
140 if !matches!(inputs.get(source_arg)?.kind(), ty::RawPtr(..)) {
141 return None;
142 }
143 Some((kind, source_arg))
144}
145
146pub(crate) fn pointer_result_source_arg(tcx: TyCtxt<'_>, callee: DefId) -> Option<usize> {
147 if !tcx.is_mir_available(callee) {
148 return None;
149 }
150 let body = tcx.optimized_mir(callee);
151 let result = rustc_middle::mir::RETURN_PLACE;
152 match body.local_decls[result].ty.kind() {
153 ty::Ref(..) => trace_returned_ref(tcx, body, result, &mut HashSet::new(), 5),
154 ty::RawPtr(..) => trace_source_arg(tcx, body, result, &mut HashSet::new(), 5),
155 _ => None,
156 }
157}
158
159fn ownership_transfer_source_arg(tcx: TyCtxt<'_>, callee: DefId) -> Option<usize> {
160 let output = tcx.fn_sig(callee).skip_binder().output().skip_binder();
161 let ty::Adt(..) = output.kind() else {
162 return None;
163 };
164 let invariants =
165 crate::contract::type_invariants::build_type_invariants_for_ty(tcx, callee, output);
166 let mut paths: Vec<_> = invariants
167 .iter()
168 .filter(|invariant| invariant.kind() == Some(PropertyKind::Owning))
169 .filter_map(|invariant| invariant.target_place()?.plain_field_path())
170 .collect();
171 paths.extend(crate::contract::annotation::owning_field_paths_from_annotation(tcx, output));
172 let opaque_source = if tcx.is_mir_available(callee) {
173 None
174 } else {
175 opaque_ownership_source_arg(tcx, callee)
176 };
177 let mut source = None;
178 for path in &paths {
179 let candidate = if tcx.is_mir_available(callee) {
180 trace_owned_field(
181 tcx,
182 tcx.optimized_mir(callee),
183 rustc_middle::mir::RETURN_PLACE,
184 path,
185 &mut HashSet::new(),
186 5,
187 )?
188 } else {
189 opaque_source?
190 };
191 let inputs = tcx.fn_sig(callee).skip_binder().inputs().skip_binder();
192 if !matches!(inputs.get(candidate)?.kind(), ty::RawPtr(..)) {
193 return None;
194 }
195 if source.is_some_and(|old| old != candidate) {
196 return None;
197 }
198 source = Some(candidate);
199 }
200 source
201}
202
203fn opaque_ownership_source_arg(tcx: TyCtxt<'_>, callee: DefId) -> Option<usize> {
204 let contracts = crate::contract::json::get_std_contracts_from_json(tcx, callee)?;
205 let has_transfer_hazard = contracts.iter().any(|alias| {
206 alias.tag == "Alias"
207 && alias.kind.as_deref() == Some("hazard")
208 && alias.args.first().is_some_and(|source| {
209 contracts.iter().any(|owning| {
210 owning.tag == "Owning" && owning.args.first() == Some(source)
211 })
212 })
213 });
214 if !has_transfer_hazard {
215 return None;
216 }
217 let inputs = tcx.fn_sig(callee).skip_binder().inputs().skip_binder();
218 let mut raw_args = inputs.iter().enumerate().filter_map(|(index, ty)| {
219 matches!(ty.kind(), ty::RawPtr(..)).then_some(index)
220 });
221 let source_arg = raw_args.next()?;
222 raw_args.next().is_none().then_some(source_arg)
223}
224
225fn trace_owned_field<'tcx>(
226 tcx: TyCtxt<'tcx>,
227 body: &Body<'tcx>,
228 local: Local,
229 path: &[usize],
230 seen: &mut HashSet<(Local, Vec<usize>)>,
231 depth: usize,
232) -> Option<usize> {
233 if !seen.insert((local, path.to_vec())) {
234 return None;
235 }
236 if path.is_empty() && matches!(body.local_decls[local].ty.kind(), ty::RawPtr(..)) {
237 return trace_source_arg(tcx, body, local, &mut HashSet::new(), depth);
238 }
239 let mut source = None;
240 for data in body.basic_blocks.iter() {
241 for stmt in &data.statements {
242 let StatementKind::Assign(assign) = &stmt.kind else {
243 continue;
244 };
245 let (dest, value) = &**assign;
246 if dest.local != local || !dest.projection.is_empty() {
247 continue;
248 }
249 let candidate = match value {
250 Rvalue::Aggregate(_, operands) if !path.is_empty() => {
251 let source_local = operands.iter().nth(path[0]).and_then(operand_local)?;
252 trace_owned_field(tcx, body, source_local, &path[1..], &mut seen.clone(), depth)
253 }
254 Rvalue::Aggregate(_, operands) => {
255 let mut source = None;
256 for operand in operands {
257 let Some(candidate) = operand_local(operand).and_then(|source_local| {
258 trace_owned_field(
259 tcx,
260 body,
261 source_local,
262 path,
263 &mut seen.clone(),
264 depth,
265 )
266 }) else {
267 continue;
268 };
269 if source.is_some_and(|old| old != candidate) {
270 return None;
271 }
272 source = Some(candidate);
273 }
274 source
275 }
276 Rvalue::Use(operand, _) => operand_local(operand).and_then(|source_local| {
277 trace_owned_field(tcx, body, source_local, path, &mut seen.clone(), depth)
278 }),
279 Rvalue::Cast(_, operand, _) if path.is_empty() => {
280 let source_local = operand_local(operand)?;
281 trace_source_arg(tcx, body, source_local, &mut HashSet::new(), depth)
282 }
283 _ => None,
284 }?;
285 if source.is_some_and(|old| old != candidate) {
286 return None;
287 }
288 source = Some(candidate);
289 }
290 if let TerminatorKind::Call {
291 func,
292 args,
293 destination,
294 ..
295 } = &data.terminator().kind
296 && destination.local == local
297 && destination.projection.is_empty()
298 {
299 if depth == 0 {
300 return None;
301 }
302 let callee = mir_utils::dep_callee_def_id(func)?;
303 if !tcx.is_mir_available(callee) {
304 return None;
305 }
306 let callee_body = tcx.optimized_mir(callee);
307 let arg_index = trace_owned_field(
308 tcx,
309 callee_body,
310 rustc_middle::mir::RETURN_PLACE,
311 path,
312 &mut HashSet::new(),
313 depth - 1,
314 )?;
315 let source_local = args.get(arg_index).and_then(|arg| operand_local(&arg.node))?;
316 let candidate =
317 trace_source_arg(tcx, body, source_local, &mut HashSet::new(), depth)?;
318 if source.is_some_and(|old| old != candidate) {
319 return None;
320 }
321 source = Some(candidate);
322 }
323 }
324 source
325}
326
327fn trace_returned_ref<'tcx>(
328 tcx: TyCtxt<'tcx>,
329 body: &Body<'tcx>,
330 local: Local,
331 seen: &mut HashSet<Local>,
332 depth: usize,
333) -> Option<usize> {
334 if !seen.insert(local) {
335 return None;
336 }
337 let index = local.as_usize();
338 if index > 0 && index <= body.arg_count
339 && matches!(body.local_decls[local].ty.kind(), ty::Ref(..))
340 {
341 return Some(index - 1);
342 }
343 let mut source = None;
344 for data in body.basic_blocks.iter() {
345 for stmt in &data.statements {
346 let StatementKind::Assign(assign) = &stmt.kind else {
347 continue;
348 };
349 let (dest, value) = &**assign;
350 if dest.local != local || !dest.projection.is_empty() {
351 continue;
352 }
353 let candidate = match value {
354 Rvalue::Ref(_, _, place)
355 if place.projection.first() == Some(&ProjectionElem::Deref) =>
356 {
357 trace_source_arg(tcx, body, place.local, &mut HashSet::new(), 4)
358 .or_else(|| {
359 matches!(body.local_decls[place.local].ty.kind(), ty::Ref(..))
360 .then(|| trace_returned_ref(tcx, body, place.local, &mut seen.clone(), depth))
361 .flatten()
362 })
363 }
364 Rvalue::Use(operand, _) => operand_local(operand)
365 .and_then(|local| trace_returned_ref(tcx, body, local, &mut seen.clone(), depth)),
366 _ => None,
367 }?;
368 if source.is_some_and(|old| old != candidate) {
369 return None;
370 }
371 source = Some(candidate);
372 }
373 if depth > 0
374 && let TerminatorKind::Call { func, args, destination, .. } = &data.terminator().kind
375 && destination.local == local
376 && destination.projection.is_empty()
377 {
378 let callee = mir_utils::dep_callee_def_id(func)?;
379 if !tcx.is_mir_available(callee) {
380 return None;
381 }
382 let callee_body = tcx.optimized_mir(callee);
383 let arg_index = trace_returned_ref(
384 tcx,
385 callee_body,
386 rustc_middle::mir::RETURN_PLACE,
387 &mut HashSet::new(),
388 depth - 1,
389 )?;
390 let arg_local = args.get(arg_index).and_then(|arg| operand_local(&arg.node))?;
391 let candidate = match body.local_decls[arg_local].ty.kind() {
392 ty::Ref(..) => trace_returned_ref(tcx, body, arg_local, &mut seen.clone(), depth - 1),
393 ty::RawPtr(..) => trace_source_arg(tcx, body, arg_local, &mut HashSet::new(), depth - 1),
394 _ => None,
395 }?;
396 if source.is_some_and(|old| old != candidate) {
397 return None;
398 }
399 source = Some(candidate);
400 }
401 }
402 source
403}
404
405fn operand_local(operand: &Operand<'_>) -> Option<Local> {
406 match operand {
407 Operand::Copy(place) | Operand::Move(place) if place.projection.is_empty() => {
408 Some(place.local)
409 }
410 _ => None,
411 }
412}
413
414pub(crate) fn alias_proved_for_param_local(
417 tcx: TyCtxt<'_>,
418 caller: DefId,
419 local_index: usize,
420 kind: HazardKind,
421) -> HazardCheck {
422 let body = tcx.optimized_mir(caller);
423 let ty = body.local_decls[Local::from_usize(local_index)].ty;
424 match ty.kind() {
425 ty::Ref(_, _, ty::Mutability::Mut) => HazardCheck::Safe(
426 "returned view reinterprets a &mut param; no hidden raw-pointer conflict".into(),
427 ),
428 ty::Ref(_, _, ty::Mutability::Not) => {
429 if kind == HazardKind::UniqueView {
430 HazardCheck::Violation(
431 "shared reference origin cannot safely produce a unique mut view".into(),
432 )
433 } else {
434 HazardCheck::Safe(
435 "returned shared view tied to shared reference; no shared alias conflict"
436 .into(),
437 )
438 }
439 }
440 _ if !matches!(ty.kind(), ty::RawPtr(..))
441 && local_index >= 1
442 && local_index <= body.arg_count =>
443 {
444 HazardCheck::Safe(
445 "returned view derives from an owned parameter; no external alias risk".into(),
446 )
447 }
448 _ => HazardCheck::Inconclusive,
449 }
450}
451
452pub(crate) fn is_origin_a_reference(tcx: TyCtxt<'_>, caller: DefId, origin: &PlaceKey) -> bool {
453 let body = tcx.optimized_mir(caller);
454 let PlaceBaseKey::Local(mut local) = origin.base else {
455 return false;
456 };
457 if let ty::Ref(..) = body.local_decls[Local::from_usize(local)].ty.kind() {
458 return true;
459 }
460 let (resolved, _) = crate::analysis::alias::tree::AliasTree::build(tcx, caller)
461 .resolve_local_to_root(Local::from_usize(local));
462 if resolved >= 1 && resolved <= body.arg_count {
463 local = resolved;
464 }
465 matches!(
466 body.local_decls[Local::from_usize(local)].ty.kind(),
467 ty::Ref(..)
468 )
469}
470
471pub(crate) fn resolve_param_origin(
477 tcx: TyCtxt<'_>,
478 caller: DefId,
479 origin: &PlaceKey,
480) -> Option<usize> {
481 let body = tcx.optimized_mir(caller);
482 if let PlaceBaseKey::Local(local) = origin.base {
483 if local >= 1 && local <= body.arg_count {
484 return Some(local);
485 }
486 let (resolved, _fields) = crate::analysis::alias::tree::AliasTree::build(tcx, caller)
487 .resolve_local_to_root(Local::from_usize(local));
488 if resolved >= 1 && resolved <= body.arg_count {
489 return Some(resolved);
490 }
491 }
492 None
493}
494
495fn param_index_of_origin(tcx: TyCtxt<'_>, caller: DefId, origin: &PlaceKey) -> Option<usize> {
502 let PlaceBaseKey::Local(local) = origin.base else {
503 return None;
504 };
505 if !origin.fields.is_empty() {
506 return None;
507 }
508 let body = tcx.optimized_mir(caller);
509 if local == 0 || local > body.arg_count {
510 return None;
511 }
512 let ty = body.local_decls[Local::from_usize(local)].ty;
513 matches!(ty.kind(), TyKind::RawPtr(..)).then_some(local - 1)
514}
515
516pub(crate) fn destination_flows_to_return(
519 tcx: TyCtxt<'_>,
520 caller: DefId,
521 destination: Option<Local>,
522) -> bool {
523 let Some(destination) = destination else {
524 return false;
525 };
526 if destination.as_usize() == 0 {
527 return true;
528 }
529 let body = tcx.optimized_mir(caller);
530 if body.local_decls[Local::from_usize(0)].ty == body.local_decls[destination].ty {
531 return true;
532 }
533 let mut aliases: HashMap<Local, PlaceKey> = HashMap::new();
534 aliases.insert(
535 destination,
536 PlaceKey {
537 base: PlaceBaseKey::Local(destination.as_usize()),
538 fields: Vec::new(),
539 },
540 );
541 for block in body.basic_blocks.iter() {
542 for statement in &block.statements {
543 let StatementKind::Assign(assign) = &statement.kind else {
544 continue;
545 };
546 let (target, rvalue) = assign.as_ref();
547 if target.local.as_usize() == 0
548 && rvalue_mentions_local(rvalue, destination, &aliases) {
549 return true;
550 }
551 if rvalue_mentions_local(rvalue, destination, &aliases) {
552 aliases.insert(target.local, aliases[&destination].clone());
553 }
554 }
555 }
556 false
557}
558
559pub(crate) fn self_field_origin(
560 tcx: TyCtxt<'_>,
561 caller: DefId,
562 place: &PlaceKey,
563) -> Option<FieldOrigin> {
564 let PlaceBaseKey::Local(local) = place.base else {
565 return None;
566 };
567 resolve_self_field_origin(tcx, caller, local, &place.fields)
568}
569
570pub(crate) fn any_struct_field_origin(
571 tcx: TyCtxt<'_>,
572 caller: DefId,
573 place: &PlaceKey,
574) -> Option<FieldOrigin> {
575 let PlaceBaseKey::Local(local) = place.base else {
576 return None;
577 };
578 if place.fields.is_empty() {
579 return None;
580 }
581 resolve_any_field_origin(tcx, caller, local, &place.fields)
582}
583
584fn self_borrow_mutability(
588 tcx: TyCtxt<'_>,
589 def_id: DefId,
590 self_local: Local,
591) -> Option<ty::Mutability> {
592 let body = tcx.optimized_mir(def_id);
593 match body.local_decls[self_local].ty.kind() {
594 TyKind::Ref(_, _, m) => Some(*m),
595 _ => None,
596 }
597}
598
599pub(crate) fn escaped_self_field_violation(
600 tcx: TyCtxt<'_>,
601 current: DefId,
602 origin: &FieldOrigin,
603) -> Option<String> {
604 if public_raw_field(tcx, origin) {
605 return Some(format!(
606 "returned view escapes while raw field `{}` is public",
607 origin.field_name
608 ));
609 }
610 let current_self = self_borrow_mutability(tcx, current, Local::from_usize(1));
611 for impl_def_id in impls_for_struct(tcx, origin.struct_def_id) {
612 for item in tcx.associated_item_def_ids(impl_def_id) {
613 if *item == current {
614 continue;
615 }
616 if !matches!(tcx.def_kind(*item), DefKind::Fn | DefKind::AssocFn) {
617 continue;
618 }
619 if get_fn_safety(tcx, *item) == Safety::Unsafe {
620 continue;
621 }
622 let Some(assoc) = tcx.opt_associated_item(*item) else {
623 continue;
624 };
625 if !matches!(assoc.kind, AssocKind::Fn { has_self: true, .. }) {
626 continue;
627 }
628 if !tcx.is_mir_available(*item) {
629 continue;
630 }
631 if let Some(reason) =
632 check_fn_against_field(tcx, *item, origin, current_self, Local::from_usize(1))
633 {
634 return Some(reason);
635 }
636 }
637 }
638 for (fn_def_id, param_locals) in free_fns_for_struct(tcx, origin.struct_def_id) {
642 if fn_def_id == current {
643 continue;
644 }
645 if get_fn_safety(tcx, fn_def_id) == Safety::Unsafe {
646 continue;
647 }
648 if !tcx.is_mir_available(fn_def_id) {
649 continue;
650 }
651 for param_local in param_locals {
652 if let Some(reason) =
653 check_fn_against_field(tcx, fn_def_id, origin, current_self, param_local)
654 {
655 return Some(reason);
656 }
657 }
658 }
659 None
660}
661
662fn check_fn_against_field(
668 tcx: TyCtxt<'_>,
669 item: DefId,
670 origin: &FieldOrigin,
671 current_self: Option<ty::Mutability>,
672 self_local: Local,
673) -> Option<String> {
674 let item_self = self_borrow_mutability(tcx, item, self_local);
675 if method_writes_self_field(tcx, item, self_local, origin.field_index) {
676 if current_self.is_none() || item_self.is_none() {
677 return None;
678 }
679 if let (Some(ty::Mutability::Not), Some(ty::Mutability::Mut)) = (current_self, item_self) {
680 return None;
681 }
682 return Some(format!(
683 "safe fn `{}` writes through raw field `{}`",
684 tcx.def_path_str(item),
685 origin.field_name
686 ));
687 }
688 if method_exposes_self_field(tcx, item, self_local, origin.field_index) {
689 if current_self.is_none() || item_self.is_none() {
690 return None;
691 }
692 if let (Some(ty::Mutability::Not), Some(ty::Mutability::Mut)) = (current_self, item_self) {
693 return None;
694 }
695 if let (Some(ty::Mutability::Mut), Some(ty::Mutability::Mut)) = (current_self, item_self) {
696 return None;
697 }
698 return Some(format!(
699 "safe fn `{}` exposes raw field `{}`",
700 tcx.def_path_str(item),
701 origin.field_name
702 ));
703 }
704 None
705}
706
707fn public_raw_field(tcx: TyCtxt<'_>, origin: &FieldOrigin) -> bool {
708 let adt = tcx.adt_def(origin.struct_def_id);
709 let Some(field) = adt.all_fields().nth(origin.field_index) else {
710 return false;
711 };
712 field.vis.is_public()
713}
714
715fn impls_for_struct(tcx: TyCtxt<'_>, struct_def_id: DefId) -> Vec<DefId> {
716 let mut impls = tcx
717 .inherent_impls(struct_def_id).to_vec();
718
719 for item_id in tcx.hir_crate_items(()).free_items() {
720 let item = tcx.hir_item(item_id);
721 let rustc_hir::ItemKind::Impl(impl_details) = &item.kind else {
722 continue;
723 };
724 let rustc_hir::TyKind::Path(rustc_hir::QPath::Resolved(_, path)) =
725 &impl_details.self_ty.kind
726 else {
727 continue;
728 };
729 let rustc_hir::def::Res::Def(_, def_id) = path.res else {
730 continue;
731 };
732 if def_id != struct_def_id {
733 continue;
734 }
735 let impl_def_id = item_id.owner_id.to_def_id();
736 if !impls.contains(&impl_def_id) {
737 impls.push(impl_def_id);
738 }
739 }
740
741 impls
742}
743
744fn free_fns_for_struct(tcx: TyCtxt<'_>, struct_def_id: DefId) -> Vec<(DefId, Vec<Local>)> {
749 let Some(struct_local) = struct_def_id.as_local() else {
750 return Vec::new();
751 };
752 let struct_module = tcx.parent_module_from_def_id(struct_local);
753 let mut fns = Vec::new();
754 for item_id in tcx.hir_crate_items(()).free_items() {
755 let item = tcx.hir_item(item_id);
756 let rustc_hir::ItemKind::Fn { .. } = &item.kind else {
757 continue;
758 };
759 let fn_def_id = item_id.owner_id.to_def_id();
760 let Some(fn_local) = fn_def_id.as_local() else {
761 continue;
762 };
763 if tcx.parent_module_from_def_id(fn_local) != struct_module {
764 continue;
765 }
766 let param_locals = struct_ref_param_locals(tcx, fn_def_id, struct_def_id);
767 if !param_locals.is_empty() {
768 fns.push((fn_def_id, param_locals));
769 }
770 }
771 fns
772}
773
774fn struct_ref_param_locals(tcx: TyCtxt<'_>, def_id: DefId, struct_def_id: DefId) -> Vec<Local> {
777 let body = tcx.optimized_mir(def_id);
778 (1..=body.arg_count)
779 .filter_map(|i| {
780 let local = Local::from_usize(i);
781 match body.local_decls[local].ty.kind() {
782 TyKind::Ref(_, pointee, _) => match pointee.kind() {
783 TyKind::Adt(adt_def, _) => (adt_def.did() == struct_def_id).then_some(local),
784 _ => None,
785 },
786 _ => None,
787 }
788 })
789 .collect()
790}
791
792fn method_writes_self_field(
795 tcx: TyCtxt<'_>,
796 method: DefId,
797 self_local: Local,
798 field_index: usize,
799) -> bool {
800 let body = tcx.optimized_mir(method);
801 let tree = crate::analysis::alias::tree::AliasTree::build(tcx, method);
802 let origin = self_field_key(self_local, field_index);
803
804 for block in body.basic_blocks.iter() {
805 for statement in &block.statements {
806 let StatementKind::Assign(assign) = &statement.kind else {
807 continue;
808 };
809 let (target, _) = assign.as_ref();
810 if place_is_raw_access_to_origin(target, &origin, &tree, &body.local_decls)
811 || place_raw_accesses_self_field(tcx, method, target, self_local, field_index)
812 {
813 return true;
814 }
815 }
816
817 let Some(terminator) = &block.terminator else {
818 continue;
819 };
820 if terminator_writes_origin(tcx, &terminator.kind, &origin, &tree) {
821 return true;
822 }
823 }
824
825 false
826}
827
828fn place_raw_accesses_self_field(
831 tcx: TyCtxt<'_>,
832 method: DefId,
833 place: &Place<'_>,
834 self_local: Local,
835 field_index: usize,
836) -> bool {
837 let body = tcx.optimized_mir(method);
838 let has_raw_deref = place.projection.iter().any(|projection| {
839 if let ProjectionElem::Deref = projection {
840 matches!(
841 body.local_decls[place.local].ty.kind(),
842 TyKind::RawPtr(_, _)
843 )
844 } else {
845 false
846 }
847 });
848 if !has_raw_deref {
849 return false;
850 }
851 local_traces_to_self_field(
852 tcx,
853 method,
854 place.local,
855 self_local,
856 field_index,
857 &mut HashSet::new(),
858 )
859}
860
861fn local_traces_to_self_field(
864 tcx: TyCtxt<'_>,
865 method: DefId,
866 local: Local,
867 self_local: Local,
868 field_index: usize,
869 seen: &mut HashSet<Local>,
870) -> bool {
871 if !seen.insert(local) {
872 return false;
873 }
874 let body = tcx.optimized_mir(method);
875 for block in body.basic_blocks.iter() {
876 for statement in &block.statements {
877 let StatementKind::Assign(assign) = &statement.kind else {
878 continue;
879 };
880 let (target, rvalue) = assign.as_ref();
881 if target.local != local {
882 continue;
883 }
884 let Some(source) = mir_utils::rvalue_source_place(rvalue) else {
885 continue;
886 };
887 let source_key = PlaceKey::from_mir_place(source);
888 if source_key.base == PlaceBaseKey::Local(self_local.as_usize())
889 && source_key.fields.first() == Some(&field_index)
890 {
891 return true;
892 }
893 if source_key.fields.is_empty()
894 && local_traces_to_self_field(
895 tcx,
896 method,
897 source.local,
898 self_local,
899 field_index,
900 seen,
901 )
902 {
903 return true;
904 }
905 }
906 }
907 seen.remove(&local);
908 false
909}
910
911fn method_exposes_self_field(
915 tcx: TyCtxt<'_>,
916 method: DefId,
917 self_local: Local,
918 field_index: usize,
919) -> bool {
920 let body = tcx.optimized_mir(method);
921
922 let self_ty = body.local_decls[self_local].ty;
923 if !matches!(self_ty.kind(), TyKind::Ref(_, _, _)) {
924 return false;
925 }
926
927 let ret_ty = body.local_decls[Local::from_usize(0)].ty;
928 if !mir_utils::type_contains_raw_ptr(tcx, ret_ty) {
929 return false;
930 }
931
932 let tree = crate::analysis::alias::tree::AliasTree::build(tcx, method);
933 let origin = self_field_key(self_local, field_index);
934
935 for block in body.basic_blocks.iter() {
936 for statement in &block.statements {
937 let StatementKind::Assign(assign) = &statement.kind else {
938 continue;
939 };
940 let (target, rvalue) = assign.as_ref();
941 if target.local.as_usize() == 0 && rvalue_mentions_origin(rvalue, &origin, &tree) {
942 return true;
943 }
944 }
945 }
946
947 false
948}
949
950fn rvalue_mentions_origin(
951 rvalue: &Rvalue<'_>,
952 origin: &PlaceKey,
953 tree: &crate::analysis::alias::tree::AliasTree,
954) -> bool {
955 rvalue_any_place_matching(rvalue, &mut |place| {
956 let key = PlaceKey::from_mir_place(place);
957 let resolved = if key.fields.is_empty() {
958 let (root, fields) = tree.resolve_local_to_root(place.local);
959 PlaceKey::from_origin(root, fields)
960 } else {
961 key
962 };
963 resolved.overlaps(origin)
964 })
965}
966
967fn self_field_key(self_local: Local, field_index: usize) -> PlaceKey {
969 PlaceKey {
970 base: PlaceBaseKey::Local(self_local.as_usize()),
971 fields: vec![field_index],
972 }
973}
974
975fn rvalue_mentions_local(
976 rvalue: &Rvalue<'_>,
977 local: Local,
978 aliases: &HashMap<Local, PlaceKey>,
979) -> bool {
980 mir_utils::rvalue_any_place_matching(rvalue, &mut |place| {
981 let has_deref = place
984 .projection
985 .iter()
986 .any(|p| matches!(p, ProjectionElem::Deref));
987 !has_deref && (place.local == local || aliases.contains_key(&place.local))
988 })
989}
990
991fn raw_access_conflicts(kind: HazardKind, access: RawAccessKind) -> bool {
994 match kind {
995 HazardKind::SharedView => access == RawAccessKind::Write,
996 HazardKind::UniqueView => true,
997 }
998}
999
1000pub(crate) fn local_hazard_violation(
1001 tcx: TyCtxt<'_>,
1002 caller: DefId,
1003 call_block: BasicBlock,
1004 destination: Option<Local>,
1005 origins: &[PlaceKey],
1006 kind: HazardKind,
1007 view_len_place: Option<PlaceKey>,
1008) -> Option<String> {
1009 local_hazard_violation_with(
1010 tcx,
1011 caller,
1012 call_block,
1013 destination,
1014 origins,
1015 kind,
1016 false,
1017 view_len_place,
1018 )
1019}
1020
1021#[allow(clippy::too_many_arguments)]
1022fn local_hazard_violation_with(
1023 tcx: TyCtxt<'_>,
1024 caller: DefId,
1025 call_block: BasicBlock,
1026 destination: Option<Local>,
1027 origins: &[PlaceKey],
1028 kind: HazardKind,
1029 strict_call_escape: bool,
1030 view_len_place: Option<PlaceKey>,
1031) -> Option<String> {
1032 let body = tcx.optimized_mir(caller);
1033 let tree = crate::analysis::alias::tree::AliasTree::build(tcx, caller);
1034 let mut origins = origins.to_vec();
1035 expand_origin_aliases(&tree, &mut origins);
1036 let mut hazard_locals: HashSet<Local> = destination.into_iter().collect();
1037 expand_hazard_alias_locals(tcx, caller, &mut hazard_locals);
1038 origins.retain(|origin| !origin.local().is_some_and(|l| hazard_locals.contains(&l)));
1039 let vec_owners = find_as_ptr_receivers(tcx, caller, &origins, &tree, true);
1040 let reachable = blocks_reachable_after_call(tcx, caller, call_block);
1041
1042 for (block_index, block) in reverse_postorder_blocks(body) {
1043 if !reachable.contains(&block_index) {
1044 continue;
1045 }
1046 for (stmt_index, statement) in block.statements.iter().enumerate() {
1047 match &statement.kind {
1048 StatementKind::StorageDead(local) => {
1049 hazard_locals.remove(local);
1050 }
1051 StatementKind::Assign(assign) => {
1052 let (target, rvalue) = assign.as_ref();
1053 if rvalue_mentions_any_local(rvalue, &hazard_locals) {
1054 let target_ty = body.local_decls[target.local].ty;
1055 if matches!(
1056 target_ty.kind(),
1057 TyKind::Ref(_, _, _) | TyKind::RawPtr(_, _)
1058 ) {
1059 hazard_locals.insert(target.local);
1060 }
1061 }
1062 if !hazard_locals.is_empty()
1063 && !hazard_locals.contains(&target.local)
1064 && raw_access_conflicts(kind, RawAccessKind::Write)
1065 && place_is_raw_access_to_any_origin(
1066 target,
1067 &origins,
1068 &tree,
1069 &body.local_decls,
1070 )
1071 && hazard_used_after_statement(
1072 tcx,
1073 caller,
1074 block_index,
1075 stmt_index,
1076 &hazard_locals,
1077 )
1078 {
1079 return Some(format!(
1080 "raw write through original pointer after {:?} view creation",
1081 kind
1082 ));
1083 }
1084 if !hazard_locals.is_empty()
1085 && !hazard_locals.contains(&target.local)
1086 && raw_access_conflicts(kind, RawAccessKind::Read)
1087 && !mir_utils::rvalue_source_place(rvalue)
1088 .is_some_and(|place| hazard_locals.contains(&place.local))
1089 && !rvalue_reads_like_view(rvalue, tcx, caller, &origins, &tree)
1090 && rvalue_reads_any_origin(rvalue, &origins, &tree, &body.local_decls)
1091 && hazard_used_after_statement(
1092 tcx,
1093 caller,
1094 block_index,
1095 stmt_index,
1096 &hazard_locals,
1097 )
1098 {
1099 return Some(format!(
1100 "raw read through original pointer after {:?} view creation",
1101 kind
1102 ));
1103 }
1104 }
1105 _ => {}
1106 }
1107 }
1108
1109 if !hazard_locals.is_empty() {
1110 let Some(terminator) = &block.terminator else {
1111 continue;
1112 };
1113 if origins
1114 .iter()
1115 .any(|origin| terminator_writes_origin(tcx, &terminator.kind, origin, &tree))
1116 && hazard_used_after_block(tcx, caller, block_index, &hazard_locals)
1117 {
1118 return Some(format!(
1119 "raw write call through original pointer after {:?} view creation",
1120 kind
1121 ));
1122 }
1123 if kind == HazardKind::UniqueView
1124 && !vec_owners.is_empty()
1125 && terminator_invalidates_vec_owner(tcx, caller, &terminator.kind, &vec_owners, &tree)
1126 && hazard_used_after_block(tcx, caller, block_index, &hazard_locals)
1127 {
1128 return Some(
1129 "Vec may reallocate while a raw-derived mutable view is still live".to_string(),
1130 );
1131 }
1132 if strict_call_escape
1133 && block_index != call_block
1134 && !terminator_is_benign_origin_use(tcx, &terminator.kind)
1135 && origins
1136 .iter()
1137 .any(|origin| terminator_uses_origin(&terminator.kind, origin, &tree))
1138 && hazard_used_after_block(tcx, caller, block_index, &hazard_locals)
1139 {
1140 return Some(format!(
1141 "raw pointer escapes to another call while the {:?} view is live",
1142 kind
1143 ));
1144 }
1145 if view_len_place.is_some()
1146 && let TerminatorKind::Call {
1147 func,
1148 args,
1149 destination: call_dest,
1150 ..
1151 } = &terminator.kind
1152 {
1153 let callee = mir_utils::dep_callee_def_id(func);
1154 if let Some((_, source_arg)) =
1155 callee.and_then(|id| raw_pointer_view_from_mir(tcx, id))
1156 && let Some(ptr_place) = args
1157 .get(source_arg)
1158 .and_then(|arg| operand_place(&arg.node))
1159 {
1160 let offset_eq = is_ptr_add_offset_eq(
1161 tcx,
1162 caller,
1163 &ptr_place,
1164 view_len_place.as_ref().unwrap(),
1165 );
1166 let from_add = is_ptr_from_ptr_add(tcx, caller, &ptr_place);
1167 if offset_eq || from_add {
1168 hazard_locals.insert(call_dest.local);
1169 continue;
1170 }
1171 }
1172 }
1173 }
1174 }
1175
1176 None
1177}
1178
1179fn reverse_postorder_blocks<'a, 'tcx>(
1180 body: &'a rustc_middle::mir::Body<'tcx>,
1181) -> impl Iterator<Item = (BasicBlock, &'a rustc_middle::mir::BasicBlockData<'tcx>)> {
1182 rustc_middle::mir::traversal::reverse_postorder(body)
1183}
1184
1185pub(crate) fn live_locals_at(
1191 tcx: TyCtxt<'_>,
1192 caller: DefId,
1193 call_block: BasicBlock,
1194 stmt_index: usize,
1195 seed_params: bool,
1196 track_moves: bool,
1197) -> HashSet<Local> {
1198 let body = tcx.optimized_mir(caller);
1199 let mut live: HashSet<Local> = if seed_params {
1203 (1..=body.arg_count).map(Local::from_usize).collect()
1204 } else {
1205 HashSet::new()
1206 };
1207 for (block, data) in reverse_postorder_blocks(body) {
1208 let reached = block == call_block;
1209 for (i, statement) in data.statements.iter().enumerate() {
1210 if reached && i >= stmt_index {
1211 break;
1212 }
1213 match &statement.kind {
1214 StatementKind::StorageLive(local) => {
1215 live.insert(*local);
1216 }
1217 StatementKind::StorageDead(local) => {
1218 live.remove(local);
1219 }
1220 StatementKind::Assign(assign) if track_moves => {
1221 let (_, rvalue) = &**assign;
1224 if let rustc_middle::mir::Rvalue::Use(operand, ..) = rvalue
1225 && let Operand::Move(place) = operand {
1226 live.remove(&place.local);
1227 }
1228 }
1229 _ => {}
1230 }
1231 }
1232 if reached {
1233 break;
1234 }
1235 if track_moves
1238 && let TerminatorKind::Call { args, .. } = &data.terminator().kind {
1239 for arg in args {
1240 if let Operand::Move(place) = &arg.node {
1241 live.remove(&place.local);
1242 }
1243 }
1244 }
1245 }
1246 live
1247}
1248
1249fn expand_origin_aliases(
1250 tree: &crate::analysis::alias::tree::AliasTree,
1251 origins: &mut Vec<PlaceKey>,
1252) {
1253 let mut changed = true;
1254 while changed {
1255 changed = false;
1256 for node in &tree.nodes {
1257 let local_key = PlaceKey {
1258 base: PlaceBaseKey::Local(node.local.as_usize()),
1259 fields: Vec::new(),
1260 };
1261 let (root, fields) = tree.resolve_local_to_root(node.local);
1262 let alias = PlaceKey::from_origin(root, fields);
1263 let related = origins.iter().any(|origin| {
1264 local_key.overlaps(origin)
1265 || origin.overlaps(&local_key)
1266 || alias.overlaps(origin)
1267 || origin.overlaps(&alias)
1268 });
1269 if !related {
1270 continue;
1271 }
1272 if !origins.contains(&local_key) {
1273 origins.push(local_key);
1274 changed = true;
1275 }
1276 if !origins.contains(&alias) {
1277 origins.push(alias);
1278 changed = true;
1279 }
1280 }
1281 }
1282}
1283
1284fn expand_hazard_alias_locals(tcx: TyCtxt<'_>, caller: DefId, hazard_locals: &mut HashSet<Local>) {
1285 let body = tcx.optimized_mir(caller);
1286 let mut changed = true;
1287 while changed {
1288 changed = false;
1289 for block in body.basic_blocks.iter() {
1290 for statement in &block.statements {
1291 let StatementKind::Assign(assign) = &statement.kind else {
1292 continue;
1293 };
1294 let (target, rvalue) = assign.as_ref();
1295 if rvalue_mentions_any_local(rvalue, hazard_locals)
1296 && hazard_locals.insert(target.local)
1297 {
1298 changed = true;
1299 }
1300 }
1301 }
1302 }
1303}
1304
1305fn rvalue_mentions_any_local(rvalue: &Rvalue<'_>, locals: &HashSet<Local>) -> bool {
1306 rvalue_any_place_matching(rvalue, &mut |place| locals.contains(&place.local))
1307}
1308
1309fn hazard_used_after_statement(
1310 tcx: TyCtxt<'_>,
1311 caller: DefId,
1312 block: BasicBlock,
1313 stmt_index: usize,
1314 hazard_locals: &HashSet<Local>,
1315) -> bool {
1316 let body = tcx.optimized_mir(caller);
1317 let data = &body.basic_blocks[block];
1318 for statement in data.statements.iter().skip(stmt_index + 1) {
1319 if statement_uses_any_local(statement, hazard_locals) {
1320 return true;
1321 }
1322 }
1323 let terminator = data.terminator();
1324 if terminator_uses_any_local(&terminator.kind, hazard_locals) {
1325 return true;
1326 }
1327 hazard_used_after_block(tcx, caller, block, hazard_locals)
1328}
1329
1330fn hazard_used_after_block(
1331 tcx: TyCtxt<'_>,
1332 caller: DefId,
1333 start: BasicBlock,
1334 hazard_locals: &HashSet<Local>,
1335) -> bool {
1336 let body = tcx.optimized_mir(caller);
1337 let mut seen = HashSet::new();
1338 let mut stack: Vec<_> = body.basic_blocks[start].terminator().successors().collect();
1339
1340 while let Some(block) = stack.pop() {
1341 if !seen.insert(block) {
1342 continue;
1343 }
1344 let data = &body.basic_blocks[block];
1345 for statement in &data.statements {
1346 if statement_uses_any_local(statement, hazard_locals) {
1347 return true;
1348 }
1349 }
1350 let terminator = data.terminator();
1351 if terminator_uses_any_local(&terminator.kind, hazard_locals) {
1352 return true;
1353 }
1354 stack.extend(terminator.successors());
1355 }
1356
1357 false
1358}
1359
1360fn statement_uses_any_local(
1361 statement: &rustc_middle::mir::Statement<'_>,
1362 locals: &HashSet<Local>,
1363) -> bool {
1364 let StatementKind::Assign(assign) = &statement.kind else {
1365 return false;
1366 };
1367 let (target, rvalue) = assign.as_ref();
1368 locals.contains(&target.local) || rvalue_mentions_any_local(rvalue, locals)
1369}
1370
1371fn terminator_uses_any_local(terminator: &TerminatorKind<'_>, locals: &HashSet<Local>) -> bool {
1372 match terminator {
1373 TerminatorKind::Call { args, .. } => args.iter().any(|arg| match &arg.node {
1374 Operand::Copy(place) | Operand::Move(place) => locals.contains(&place.local),
1375 Operand::Constant(_) => false,
1376 Operand::RuntimeChecks(_) => false,
1377 }),
1378 TerminatorKind::SwitchInt { discr, .. } | TerminatorKind::Assert { cond: discr, .. } => {
1379 match discr {
1380 Operand::Copy(place) | Operand::Move(place) => locals.contains(&place.local),
1381 Operand::Constant(_) => false,
1382 Operand::RuntimeChecks(_) => false,
1383 }
1384 }
1385 TerminatorKind::Drop { place, .. } => locals.contains(&place.local),
1386 _ => false,
1387 }
1388}
1389
1390fn resolve_mir_place_tree(
1393 tree: &crate::analysis::alias::tree::AliasTree,
1394 place: &Place<'_>,
1395) -> PlaceKey {
1396 let fields = PlaceKey::from_mir_place(place).fields;
1397 let (root, root_fields) = resolve_via_tree(tree, place.local, &fields);
1398 PlaceKey::from_origin(root, root_fields)
1399}
1400
1401fn resolve_place_key_tree(
1404 tree: &crate::analysis::alias::tree::AliasTree,
1405 place: &Place<'_>,
1406) -> PlaceKey {
1407 if tree.tag_of(place.local).is_some() {
1408 let (root, fields) = tree.resolve_local_to_root(place.local);
1409 PlaceKey::from_origin(root, fields)
1410 } else {
1411 PlaceKey::from_mir_place(place)
1412 }
1413}
1414
1415fn place_is_raw_access_to_any_origin(
1416 place: &Place<'_>,
1417 origins: &[PlaceKey],
1418 tree: &crate::analysis::alias::tree::AliasTree,
1419 local_decls: &LocalDecls<'_>,
1420) -> bool {
1421 origins
1422 .iter()
1423 .any(|origin| place_is_raw_access_to_origin(place, origin, tree, local_decls))
1424}
1425
1426fn place_is_raw_access_to_origin(
1427 place: &Place<'_>,
1428 origin: &PlaceKey,
1429 tree: &crate::analysis::alias::tree::AliasTree,
1430 local_decls: &LocalDecls<'_>,
1431) -> bool {
1432 let local = place.local;
1433 let has_raw_deref = place.projection.iter().any(|projection| {
1434 if let ProjectionElem::Deref = projection {
1435 matches!(local_decls[local].ty.kind(), TyKind::RawPtr(_, _))
1436 } else {
1437 false
1438 }
1439 });
1440 if !has_raw_deref {
1441 return false;
1442 }
1443 let pointer = resolve_place_key_tree(tree, place);
1444 pointer.overlaps(origin)
1445}
1446
1447fn rvalue_reads_like_view(
1448 rvalue: &Rvalue<'_>,
1449 tcx: TyCtxt<'_>,
1450 caller: DefId,
1451 origins: &[PlaceKey],
1452 tree: &crate::analysis::alias::tree::AliasTree,
1453) -> bool {
1454 let Some(place) = mir_utils::rvalue_source_place(rvalue) else {
1455 return false;
1456 };
1457 if !place
1458 .projection
1459 .iter()
1460 .any(|p| matches!(p, ProjectionElem::Deref))
1461 {
1462 return false;
1463 }
1464 let pointer = resolve_place_key_tree(tree, place);
1465 if !origins.iter().any(|origin| pointer.overlaps(origin)) {
1466 return false;
1467 }
1468 is_origin_a_reference(tcx, caller, &pointer)
1469}
1470
1471fn rvalue_reads_any_origin(
1472 rvalue: &Rvalue<'_>,
1473 origins: &[PlaceKey],
1474 tree: &crate::analysis::alias::tree::AliasTree,
1475 local_decls: &LocalDecls<'_>,
1476) -> bool {
1477 rvalue_any_place_matching(rvalue, &mut |place| {
1478 place_is_raw_access_to_any_origin(place, origins, tree, local_decls)
1479 })
1480}
1481
1482fn terminator_writes_origin<'tcx>(
1483 tcx: TyCtxt<'tcx>,
1484 terminator: &TerminatorKind<'tcx>,
1485 origin: &PlaceKey,
1486 tree: &crate::analysis::alias::tree::AliasTree,
1487) -> bool {
1488 let TerminatorKind::Call { func, args, .. } = terminator else {
1489 return false;
1490 };
1491 let callee = mir_utils::dep_callee_def_id(func);
1492 if !crate::def_ids::is_ptr_write(tcx, callee) {
1493 return false;
1494 }
1495 let Some(arg0) = args.first() else {
1496 return false;
1497 };
1498 let Some(place) = operand_mir_place(&arg0.node) else {
1499 return false;
1500 };
1501 resolve_mir_place_tree(tree, place).overlaps(origin)
1502}
1503
1504fn terminator_uses_origin<'tcx>(
1505 terminator: &TerminatorKind<'tcx>,
1506 origin: &PlaceKey,
1507 tree: &crate::analysis::alias::tree::AliasTree,
1508) -> bool {
1509 let TerminatorKind::Call { args, .. } = terminator else {
1510 return false;
1511 };
1512 args.iter().any(|arg| {
1513 let Some(place) = operand_mir_place(&arg.node) else {
1514 return false;
1515 };
1516 resolve_mir_place_tree(tree, place).overlaps(origin)
1517 })
1518}
1519
1520fn terminator_is_benign_origin_use<'tcx>(
1521 tcx: TyCtxt<'tcx>,
1522 terminator: &TerminatorKind<'tcx>,
1523) -> bool {
1524 let TerminatorKind::Call { func, .. } = terminator else {
1525 return true;
1526 };
1527 pointer_semantics::is_benign_origin_use(tcx, mir_utils::dep_callee_def_id(
1528 func,
1529 ))
1530}
1531
1532fn terminator_invalidates_vec_owner<'tcx>(
1533 tcx: TyCtxt<'tcx>,
1534 caller: DefId,
1535 terminator: &TerminatorKind<'tcx>,
1536 owners: &[PlaceKey],
1537 tree: &crate::analysis::alias::tree::AliasTree,
1538) -> bool {
1539 let TerminatorKind::Call { func, args, .. } = terminator else {
1540 return false;
1541 };
1542 let writes = call_write::callsite_write_args(&VerifierCallSemantics, tcx, caller, func);
1543 args.iter().enumerate().any(|(index, arg)| {
1544 if !writes.as_ref().is_none_or(|writes| writes.contains(&index)) {
1545 return false;
1546 }
1547 let Some(place) = operand_mir_place(&arg.node) else {
1548 return false;
1549 };
1550 let ty = place.ty(tcx.optimized_mir(caller), tcx).ty;
1551 let TyKind::Ref(_, inner, rustc_middle::mir::Mutability::Mut) = ty.kind() else {
1552 return false;
1553 };
1554 if !inner
1555 .ty_adt_def()
1556 .is_some_and(|adt| type_ids::is_std_vec(adt.did()))
1557 {
1558 return false;
1559 }
1560 let arg = resolve_mir_place_tree(tree, place);
1561 owners
1562 .iter()
1563 .any(|owner| arg.overlaps(owner) || owner.overlaps(&arg))
1564 })
1565}
1566
1567fn find_as_ptr_receivers(
1568 tcx: TyCtxt<'_>,
1569 caller: DefId,
1570 origins: &[PlaceKey],
1571 tree: &crate::analysis::alias::tree::AliasTree,
1572 check_alias_dest: bool,
1573) -> Vec<PlaceKey> {
1574 let body = tcx.optimized_mir(caller);
1575 let mut result = Vec::new();
1576 for block in body.basic_blocks.iter() {
1577 let Some(terminator) = &block.terminator else {
1578 continue;
1579 };
1580 let TerminatorKind::Call {
1581 func,
1582 args,
1583 destination,
1584 ..
1585 } = &terminator.kind
1586 else {
1587 continue;
1588 };
1589 if !pointer_flow::return_traces_first_arg(tcx, mir_utils::dep_callee_def_id(func)) {
1590 continue;
1591 }
1592 let destination_key = PlaceKey {
1593 base: PlaceBaseKey::Local(destination.local.as_usize()),
1594 fields: Vec::new(),
1595 };
1596 let dest_overlaps = || {
1597 origins
1598 .iter()
1599 .any(|origin| destination_key.overlaps(origin))
1600 || (check_alias_dest
1601 && tree.tag_of(destination.local).is_some_and(|_| {
1602 let (root, fields) = tree.resolve_local_to_root(destination.local);
1603 let alias = PlaceKey::from_origin(root, fields);
1604 origins.iter().any(|o| alias.overlaps(o))
1605 }))
1606 };
1607 if !dest_overlaps() {
1608 continue;
1609 }
1610 let Some(receiver) = args.first() else {
1611 continue;
1612 };
1613 let Some(place) = operand_mir_place(&receiver.node) else {
1614 continue;
1615 };
1616 let resolved = resolve_mir_place_tree(tree, place);
1617 if !result.contains(&resolved) {
1618 result.push(resolved);
1619 }
1620 }
1621 result
1622}
1623
1624fn is_ptr_add_offset_eq(
1625 tcx: TyCtxt<'_>,
1626 caller: DefId,
1627 ptr_place: &PlaceKey,
1628 view_len: &PlaceKey,
1629) -> bool {
1630 let body = tcx.optimized_mir(caller);
1631 let tree = crate::analysis::alias::tree::AliasTree::build(tcx, caller);
1632 let view_len_root = view_len.local().map(|l| tree.resolve_local_to_root(l));
1633 for (_bb, data) in body.basic_blocks.iter_enumerated() {
1634 if let TerminatorKind::Call {
1635 func,
1636 args,
1637 destination,
1638 ..
1639 } = &data.terminator().kind
1640 {
1641 let ptr_key = PlaceKey::from_mir_place(destination);
1642 if ptr_key != *ptr_place {
1643 continue;
1644 }
1645 if mir_utils::dep_callee_def_id(func)
1646 .and_then(|callee| {
1647 crate::analysis::dataflow::pointer_offset::pointer_offset_direction(tcx, callee)
1648 })
1649 == Some(crate::analysis::dataflow::pointer_offset::PointerOffsetDirection::Forward)
1650 && args.len() >= 2
1651 && let Some(offset_place) = operand_place(&args[1].node) {
1652 let offset_root = offset_place.local().map(|l| tree.resolve_local_to_root(l));
1653 return offset_root == view_len_root;
1654 }
1655 }
1656 }
1657 false
1658}
1659
1660fn is_ptr_from_ptr_add(tcx: TyCtxt<'_>, caller: DefId, ptr_place: &PlaceKey) -> bool {
1661 let body = tcx.optimized_mir(caller);
1662 for (_bb, data) in body.basic_blocks.iter_enumerated() {
1663 if let TerminatorKind::Call {
1664 func, destination, ..
1665 } = &data.terminator().kind
1666 {
1667 let ptr_key = PlaceKey::from_mir_place(destination);
1668 if ptr_key != *ptr_place {
1669 continue;
1670 }
1671 return mir_utils::dep_callee_def_id(func)
1672 .and_then(|callee| {
1673 crate::analysis::dataflow::pointer_offset::pointer_offset_direction(tcx, callee)
1674 })
1675 == Some(crate::analysis::dataflow::pointer_offset::PointerOffsetDirection::Forward);
1676 }
1677 }
1678 false
1679}
1680
1681pub(crate) fn ownership_transfer_violation(
1684 tcx: TyCtxt<'_>,
1685 caller: DefId,
1686 call_block: BasicBlock,
1687 destination: Option<Local>,
1688 origin_place: &PlaceKey,
1689) -> Option<String> {
1690 let body = tcx.optimized_mir(caller);
1691 let reachable = blocks_reachable_after_call(tcx, caller, call_block);
1692
1693 let origins = places_holding_transferred_pointer(tcx, caller, call_block, origin_place);
1694
1695 if let Some(reason) = pre_existing_view_on_origin(tcx, caller, call_block, &reachable, &origins)
1696 {
1697 return Some(reason);
1698 }
1699
1700 let start = match &body.basic_blocks[call_block].terminator().kind {
1701 TerminatorKind::Call {
1702 target: Some(target),
1703 ..
1704 } => *target,
1705 _ => return None,
1706 };
1707
1708 let mut entry_states: HashMap<(BasicBlock, Vec<usize>), Vec<PlaceKey>> = HashMap::new();
1709 let mut worklist = vec![(start, origins, destination.into_iter().collect::<HashSet<_>>())];
1710
1711 while let Some((block_index, incoming, mut owners)) = worklist.pop() {
1712 let mut owner_key: Vec<_> = owners.iter().map(|local| local.as_usize()).collect();
1713 owner_key.sort_unstable();
1714 let state_key = (block_index, owner_key);
1715 let mut live_origins = match entry_states.get_mut(&state_key) {
1716 Some(known) => {
1717 let mut changed = false;
1718 for origin in &incoming {
1719 if !known.contains(origin) {
1720 known.push(origin.clone());
1721 changed = true;
1722 }
1723 }
1724 if !changed {
1725 continue;
1726 }
1727 known.clone()
1728 }
1729 None => {
1730 entry_states.insert(state_key, incoming.clone());
1731 incoming
1732 }
1733 };
1734
1735 let block = &body.basic_blocks[block_index];
1736 for statement in &block.statements {
1737 match &statement.kind {
1738 StatementKind::Assign(assign) => {
1739 let (target, rvalue) = assign.as_ref();
1740 let transfers_owner = match rvalue {
1741 Rvalue::Use(Operand::Move(source) | Operand::Copy(source), ..)
1742 if source.projection.is_empty() && owners.contains(&source.local) =>
1743 {
1744 true
1745 }
1746 _ => false,
1747 };
1748 if target.projection.is_empty() {
1749 owners.remove(&target.local);
1750 if transfers_owner {
1751 owners.insert(target.local);
1752 }
1753 }
1754 if let Rvalue::Use(Operand::Move(source), ..) = rvalue {
1755 owners.remove(&source.local);
1756 }
1757 let target_key = PlaceKey::from_mir_place(target);
1758 let is_deref_to_pointee = target_key.fields.is_empty()
1759 && target
1760 .projection
1761 .iter()
1762 .any(|p| matches!(p, ProjectionElem::Deref));
1763 if !is_deref_to_pointee {
1764 live_origins.retain(|origin| !place_key_is_prefix_of(&target_key, origin));
1765 }
1766 if place_is_raw_access_to_live_origin(target, &live_origins)
1767 || rvalue_any_place_matching(rvalue, &mut |place| {
1768 place_is_raw_access_to_live_origin(place, &live_origins)
1769 })
1770 {
1771 return Some(
1772 "raw pointer reused after ownership was transferred to an owning value"
1773 .into(),
1774 );
1775 }
1776 let copies_origin = rvalue_copies_live_origin_value(rvalue, &live_origins);
1777 kill_strongly_updated_origins(&body.local_decls, target, &mut live_origins);
1778 if copies_origin
1779 && !target
1780 .projection
1781 .iter()
1782 .any(|projection| matches!(projection, ProjectionElem::Deref))
1783 {
1784 let target_key = PlaceKey::from_mir_place(target);
1785 if !live_origins.contains(&target_key) {
1786 live_origins.push(target_key);
1787 }
1788 }
1789 }
1790 StatementKind::StorageDead(local) => {
1791 owners.remove(local);
1792 live_origins
1793 .retain(|origin| origin.base != PlaceBaseKey::Local(local.as_usize()));
1794 }
1795 _ => {}
1796 }
1797 }
1798
1799 let Some(terminator) = &block.terminator else {
1800 continue;
1801 };
1802 if terminator_uses_live_origin(&terminator.kind, &live_origins) {
1803 return Some(
1804 "raw pointer passed to another call after ownership was transferred".into(),
1805 );
1806 }
1807 if let TerminatorKind::Call {
1808 func,
1809 args,
1810 destination: call_destination,
1811 ..
1812 } = &terminator.kind
1813 {
1814 let callee = mir_utils::dep_callee_def_id(func);
1815 let escaped = args.iter().enumerate().any(|(index, arg)| {
1818 let Operand::Move(place) = &arg.node else {
1819 return false;
1820 };
1821 place.projection.is_empty()
1822 && owners.contains(&place.local)
1823 && callee.is_some_and(|did| pointer_semantics::returns_undropped_arg(tcx, did, index))
1824 });
1825 for arg in args {
1826 if let Operand::Move(place) = &arg.node {
1827 owners.remove(&place.local);
1828 }
1829 }
1830 if escaped {
1831 live_origins.clear();
1832 }
1833 owners.remove(&call_destination.local);
1834 kill_strongly_updated_origins(&body.local_decls, call_destination, &mut live_origins);
1835 }
1836 if live_origins.is_empty() {
1837 continue;
1838 }
1839 for successor in terminator.successors() {
1840 worklist.push((successor, live_origins.clone(), owners.clone()));
1841 }
1842 }
1843
1844 None
1845}
1846
1847fn places_holding_transferred_pointer(
1848 tcx: TyCtxt<'_>,
1849 caller: DefId,
1850 call_block: BasicBlock,
1851 origin_place: &PlaceKey,
1852) -> Vec<PlaceKey> {
1853 let body = tcx.optimized_mir(caller);
1854 let mut holders = vec![origin_place.clone()];
1855 let mut killed: HashSet<Local> = HashSet::new();
1856 let mut block_index = call_block;
1857
1858 loop {
1859 let block = &body.basic_blocks[block_index];
1860 for statement in block.statements.iter().rev() {
1861 let StatementKind::Assign(assign) = &statement.kind else {
1862 continue;
1863 };
1864 let (target, rvalue) = assign.as_ref();
1865 if target
1866 .projection
1867 .iter()
1868 .any(|projection| matches!(projection, ProjectionElem::Deref))
1869 {
1870 continue;
1871 }
1872 let target_key = PlaceKey::from_mir_place(target);
1873 let target_defines_holder =
1874 !killed.contains(&target.local) && holders.iter().any(|h| target_key.overlaps(h));
1875
1876 let source_place = mir_utils::rvalue_source_place(rvalue);
1877
1878 if target_defines_holder {
1879 if let Some(source) = source_place
1880 && !killed.contains(&source.local)
1881 {
1882 let source_key = PlaceKey::from_mir_place(source);
1883 for holder in holders.clone() {
1884 if let Some(spliced) =
1885 splice_holder_fields(&target_key, &holder, &source_key)
1886 && !holders.contains(&spliced)
1887 {
1888 holders.push(spliced);
1889 }
1890 }
1891 }
1892 } else if let Some(source) = source_place
1893 && !killed.contains(&target.local)
1894 && !source
1895 .projection
1896 .iter()
1897 .any(|projection| matches!(projection, ProjectionElem::Deref))
1898 {
1899 let source_key = PlaceKey::from_mir_place(source);
1900 if holders.iter().any(|h| source_key.overlaps(h)) && !holders.contains(&target_key)
1901 {
1902 holders.push(target_key.clone());
1903 }
1904 }
1905 killed.insert(target.local);
1906 }
1907
1908 let predecessors = &body.basic_blocks.predecessors()[block_index];
1909 if predecessors.len() != 1 {
1910 break;
1911 }
1912 block_index = predecessors[0];
1913 let terminator = body.basic_blocks[block_index].terminator();
1914 if let TerminatorKind::Call {
1915 func,
1916 args,
1917 destination: call_destination,
1918 ..
1919 } = &terminator.kind
1920 {
1921 let destination_key = PlaceKey::from_mir_place(call_destination);
1922 if !killed.contains(&call_destination.local)
1923 && holders.iter().any(|h| destination_key.overlaps(h))
1924 && pointer_flow::return_traces_first_arg(tcx, mir_utils::dep_callee_def_id(func))
1925 && let Some(arg) = args.first()
1926 && let Operand::Copy(place) | Operand::Move(place) = &arg.node
1927 && !killed.contains(&place.local)
1928 {
1929 let key = PlaceKey::from_mir_place(place);
1930 if !holders.contains(&key) {
1931 holders.push(key);
1932 }
1933 }
1934 killed.insert(call_destination.local);
1935 }
1936 }
1937
1938 holders
1939}
1940
1941fn splice_holder_fields(
1942 target: &PlaceKey,
1943 holder: &PlaceKey,
1944 source: &PlaceKey,
1945) -> Option<PlaceKey> {
1946 if !place_key_is_prefix_of(target, holder) {
1947 return None;
1948 }
1949 let mut fields = source.fields.clone();
1950 fields.extend_from_slice(&holder.fields[target.fields.len()..]);
1951 Some(PlaceKey {
1952 base: source.base.clone(),
1953 fields,
1954 })
1955}
1956
1957fn kill_strongly_updated_origins(
1958 local_decls: &LocalDecls<'_>,
1959 target: &Place<'_>,
1960 live_origins: &mut Vec<PlaceKey>,
1961) {
1962 let deref_count = target
1963 .projection
1964 .iter()
1965 .filter(|p| matches!(p, ProjectionElem::Deref))
1966 .count();
1967 if deref_count == 0 {
1968 let target_key = PlaceKey::from_mir_place(target);
1969 live_origins.retain(|origin| !place_key_is_prefix_of(&target_key, origin));
1970 return;
1971 }
1972 if deref_count == 1 && matches!(target.projection[0], ProjectionElem::Deref) {
1973 let ty = local_decls[target.local].ty;
1974 if matches!(ty.kind(), ty::Ref(_, _, ty::Mutability::Mut)) {
1975 let target_key = PlaceKey::from_mir_place(target);
1976 live_origins.retain(|origin| !place_key_is_prefix_of(&target_key, origin));
1977 }
1978 }
1979}
1980
1981fn place_key_is_prefix_of(prefix: &PlaceKey, place: &PlaceKey) -> bool {
1982 prefix.base == place.base
1983 && prefix.fields.len() <= place.fields.len()
1984 && place.fields[..prefix.fields.len()] == prefix.fields[..]
1985}
1986
1987fn place_is_raw_access_to_live_origin(place: &Place<'_>, live_origins: &[PlaceKey]) -> bool {
1988 if !place
1989 .projection
1990 .iter()
1991 .any(|projection| matches!(projection, ProjectionElem::Deref))
1992 {
1993 return false;
1994 }
1995 let key = PlaceKey::from_mir_place(place);
1996 live_origins.iter().any(|origin| key.overlaps(origin))
1997}
1998
1999fn rvalue_copies_live_origin_value(rvalue: &Rvalue<'_>, live_origins: &[PlaceKey]) -> bool {
2000 let Some(place) = mir_utils::rvalue_source_place(rvalue) else {
2001 return false;
2002 };
2003 if place
2004 .projection
2005 .iter()
2006 .any(|projection| matches!(projection, ProjectionElem::Deref))
2007 {
2008 return false;
2009 }
2010 let key = PlaceKey::from_mir_place(place);
2011 live_origins.iter().any(|origin| key.overlaps(origin))
2012}
2013
2014fn terminator_uses_live_origin(kind: &TerminatorKind<'_>, live_origins: &[PlaceKey]) -> bool {
2015 let TerminatorKind::Call { args, .. } = kind else {
2016 return false;
2017 };
2018 args.iter().any(|arg| {
2019 let Some(place) = operand_mir_place(&arg.node) else {
2020 return false;
2021 };
2022 let key = PlaceKey::from_mir_place(place);
2023 live_origins.iter().any(|origin| key.overlaps(origin))
2024 })
2025}
2026
2027fn pre_existing_view_on_origin(
2028 tcx: TyCtxt<'_>,
2029 caller: DefId,
2030 call_block: BasicBlock,
2031 reachable_after: &HashSet<BasicBlock>,
2032 origin_holders: &[PlaceKey],
2033) -> Option<String> {
2034 let body = tcx.optimized_mir(caller);
2035 let tree = crate::analysis::alias::tree::AliasTree::build(tcx, caller);
2036
2037 let holder_origins: Vec<(usize, Vec<usize>)> = origin_holders
2038 .iter()
2039 .flat_map(|h| {
2040 if let PlaceBaseKey::Local(l) = h.base {
2041 let resolved = resolve_via_tree(&tree, Local::from_usize(l), &h.fields);
2042 if resolved.0 == 1 && !resolved.1.is_empty() {
2043 Some(resolved)
2044 } else {
2045 None
2046 }
2047 } else {
2048 None
2049 }
2050 })
2051 .collect();
2052
2053 for (bb, data) in body.basic_blocks.iter_enumerated() {
2054 if reachable_after.contains(&bb) || bb == call_block {
2055 continue;
2056 }
2057 let terminator = data.terminator();
2058 if let TerminatorKind::Call { func, args, .. } = &terminator.kind {
2059 let callee_name = mir_utils::call_name(tcx, func);
2060 if mir_utils::dep_callee_def_id(func)
2061 .and_then(|callee| pointer_flow::nonnull_ref_return(tcx, callee))
2062 .is_some()
2063 && let Some(arg) = args.first()
2064 && let Some(place) = operand_mir_place(&arg.node)
2065 {
2066 let arg_resolved = resolve_via_tree(
2067 &tree,
2068 place.local,
2069 &PlaceKey::from_mir_place(place).fields,
2070 );
2071 if arg_resolved.0 == 1
2072 && !arg_resolved.1.is_empty()
2073 && holder_origins
2074 .iter()
2075 .any(|(h, hf)| *h == arg_resolved.0 && *hf == arg_resolved.1)
2076 {
2077 return Some(format!(
2078 "pre-existing view from {} aliases the ownership-transferred pointer",
2079 callee_name,
2080 ));
2081 }
2082 }
2083 }
2084
2085 for statement in &data.statements {
2086 let StatementKind::Assign(assign) = &statement.kind else {
2087 continue;
2088 };
2089 let (_target, rvalue) = assign.as_ref();
2090 let src_place: Option<&Place<'_>> = match rvalue {
2091 Rvalue::Ref(_, _, place) => Some(place),
2092 Rvalue::Cast(
2093 rustc_middle::mir::CastKind::PtrToPtr,
2094 Operand::Copy(place) | Operand::Move(place),
2095 _,
2096 ) => Some(place),
2097 _ => None,
2098 };
2099 let Some(place) = src_place else {
2100 continue;
2101 };
2102 if !place
2103 .projection
2104 .iter()
2105 .any(|p| matches!(p, ProjectionElem::Deref))
2106 {
2107 continue;
2108 }
2109 let resolved =
2110 resolve_via_tree(&tree, place.local, &PlaceKey::from_mir_place(place).fields);
2111 if resolved.0 == 1
2112 && !resolved.1.is_empty()
2113 && holder_origins
2114 .iter()
2115 .any(|(h, hf)| *h == resolved.0 && *hf == resolved.1)
2116 {
2117 return Some(
2118 "pre-existing &*raw_ptr view aliases the ownership-transferred pointer".into(),
2119 );
2120 }
2121 }
2122 }
2123 None
2124}
2125
2126fn resolve_via_tree(
2130 tree: &crate::analysis::alias::tree::AliasTree,
2131 local: Local,
2132 fields: &[usize],
2133) -> (usize, Vec<usize>) {
2134 if !fields.is_empty() {
2135 return (local.as_usize(), fields.to_vec());
2136 }
2137 tree.resolve_local_to_root(local)
2138}
2139
2140pub(crate) fn private_fn_callsite_delegation(
2143 tcx: TyCtxt<'_>,
2144 caller: DefId,
2145 origin: &PlaceKey,
2146 kind: HazardKind,
2147) -> Option<String> {
2148 let param_index = param_index_of_origin(tcx, caller, origin)?;
2149 if is_externally_reachable(tcx, caller) {
2150 return None;
2151 }
2152 for site in local_callsites(tcx, caller) {
2153 let mut origins = callsite_arg_origins(tcx, site.caller, &site.args, param_index);
2154 if origins.is_empty() {
2155 continue;
2156 }
2157 let tree = crate::analysis::alias::tree::AliasTree::build(tcx, site.caller);
2158 let extra = find_as_ptr_receivers(tcx, site.caller, &origins, &tree, false);
2159 for place in extra {
2160 if !origins.contains(&place) {
2161 origins.push(place);
2162 }
2163 }
2164 if let Some(reason) = local_hazard_violation_with(
2165 tcx,
2166 site.caller,
2167 site.block,
2168 site.destination,
2169 &origins,
2170 kind,
2171 true,
2172 None,
2173 ) {
2174 return Some(format!(
2175 "call site `{}` conflicts with the returned view: {reason}",
2176 tcx.def_path_str(site.caller)
2177 ));
2178 }
2179 }
2180 None
2181}
2182
2183fn local_callsites(tcx: TyCtxt<'_>, callee: DefId) -> Vec<LocalCallsite<'_>> {
2184 let mut sites = Vec::new();
2185 for def_id in tcx.mir_keys(()) {
2186 let def_id = def_id.to_def_id();
2187 if def_id == callee {
2188 continue;
2189 }
2190 if !matches!(tcx.def_kind(def_id), DefKind::Fn | DefKind::AssocFn) {
2191 continue;
2192 }
2193 if !tcx.is_mir_available(def_id) {
2194 continue;
2195 }
2196 let body = tcx.optimized_mir(def_id);
2197 for (block, data) in body.basic_blocks.iter_enumerated() {
2198 let Some(terminator) = &data.terminator else {
2199 continue;
2200 };
2201 let TerminatorKind::Call {
2202 func,
2203 args,
2204 destination,
2205 ..
2206 } = &terminator.kind
2207 else {
2208 continue;
2209 };
2210 let Some(target) = mir_utils::dep_callee_def_id(func) else {
2211 continue;
2212 };
2213 if target != callee {
2214 continue;
2215 }
2216 sites.push(LocalCallsite {
2217 caller: def_id,
2218 block,
2219 args: args.iter().map(|arg| arg.node.clone()).collect(),
2220 destination: Some(destination.local),
2221 });
2222 }
2223 }
2224 sites
2225}
2226
2227fn callsite_arg_origins(
2228 tcx: TyCtxt<'_>,
2229 caller: DefId,
2230 args: &[Operand<'_>],
2231 param_index: usize,
2232) -> Vec<PlaceKey> {
2233 let Some(arg) = args.get(param_index) else {
2234 return Vec::new();
2235 };
2236 let Some(place) = (match arg {
2237 Operand::Copy(place) | Operand::Move(place) => Some(PlaceKey::from_mir_place(place)),
2238 _ => None,
2239 }) else {
2240 return Vec::new();
2241 };
2242 let tree = crate::analysis::alias::tree::AliasTree::build(tcx, caller);
2243 let mut origins = vec![place.clone()];
2244 if let Some(local) = place.local()
2245 && tree.tag_of(local).is_some()
2246 {
2247 let (root, fields) = tree.resolve_local_to_root(local);
2248 let alias = PlaceKey::from_origin(root, fields);
2249 if !origins.contains(&alias) {
2250 origins.push(alias);
2251 }
2252 }
2253 origins
2254}