Skip to main content

rapx/analysis/dataflow/
pointer_copy.rs

1//! Source and destination arguments of pointer-copy calls.
2
3use rustc_hir::{def::DefKind, def_id::DefId};
4use rustc_middle::{
5    mir::{Body, Operand, StatementKind, TerminatorKind},
6    ty::{Mutability, TyCtxt, TyKind},
7};
8
9use crate::def_ids::{diagnostic_api, intrinsic_api};
10use crate::util::mir_utils::dep_callee_def_id;
11
12#[derive(Clone, Copy, Debug, Eq, PartialEq)]
13pub(crate) struct CopyFlow {
14    pub source_arg: usize,
15    pub destination_arg: usize,
16}
17
18/// The fixed argument flow of compiler and standard-library copy functions.
19pub(crate) fn direct_copy_flow(tcx: TyCtxt<'_>, callee: DefId) -> Option<CopyFlow> {
20    let intrinsic = intrinsic_api::intrinsic_name(tcx, Some(callee))
21        .is_some_and(|name| matches!(name.as_str(), "copy" | "copy_nonoverlapping"));
22    (intrinsic || diagnostic_api::is_ptr_copy(tcx, callee)).then_some(CopyFlow {
23        source_arg: 0,
24        destination_arg: 1,
25    })
26}
27
28/// Copy flow at this callee, including wrappers whose source and destination
29/// are recovered from optimized MIR.
30pub(crate) fn copy_flow(tcx: TyCtxt<'_>, callee: DefId) -> Option<CopyFlow> {
31    direct_copy_flow(tcx, callee).or_else(|| mir_copy_flow(tcx, callee))
32}
33
34fn mir_copy_flow(tcx: TyCtxt<'_>, callee: DefId) -> Option<CopyFlow> {
35    if !matches!(tcx.def_kind(callee), DefKind::Fn | DefKind::AssocFn)
36        || !tcx.is_mir_available(callee)
37    {
38        return None;
39    }
40    let sig = tcx.fn_sig(callee).skip_binder();
41    let [first, second, count] = sig.inputs().skip_binder() else {
42        return None;
43    };
44    let (TyKind::RawPtr(first_pointee, _), TyKind::RawPtr(second_pointee, _)) =
45        (first.kind(), second.kind())
46    else {
47        return None;
48    };
49    if first_pointee != second_pointee
50        || *count != tcx.types.usize
51        || sig.output().skip_binder() != tcx.types.unit
52    {
53        return None;
54    }
55
56    let body = tcx.optimized_mir(callee);
57    let mut copy_args = None;
58    for block in body.basic_blocks.iter() {
59        for statement in &block.statements {
60            if let StatementKind::Intrinsic(intrinsic) = &statement.kind
61                && let rustc_middle::mir::NonDivergingIntrinsic::CopyNonOverlapping(copy) =
62                    &**intrinsic
63            {
64                record_copy_args(body, &copy.src, &copy.dst, &copy.count, &mut copy_args)?;
65            }
66        }
67        if let TerminatorKind::Call { func, args, .. } | TerminatorKind::TailCall { func, args, .. } =
68            &block.terminator().kind
69            && let Some(id) = dep_callee_def_id(func)
70            && direct_copy_flow(tcx, id).is_some()
71            && let [src, dst, count] = &args[..]
72        {
73            record_copy_args(body, &src.node, &dst.node, &count.node, &mut copy_args)?;
74        }
75    }
76    let flow: CopyFlow = copy_args?;
77    let inputs = [first, second];
78    matches!(
79        inputs[flow.destination_arg].kind(),
80        TyKind::RawPtr(_, Mutability::Mut)
81    )
82    .then_some(flow)
83}
84
85fn record_copy_args(
86    body: &Body<'_>,
87    src: &Operand<'_>,
88    dst: &Operand<'_>,
89    count: &Operand<'_>,
90    result: &mut Option<CopyFlow>,
91) -> Option<()> {
92    let source = argument_index(body, src)?;
93    let destination = argument_index(body, dst)?;
94    if source >= 2 || destination >= 2 || source == destination || argument_index(body, count)? != 2
95    {
96        return None;
97    }
98    let candidate = CopyFlow {
99        source_arg: source,
100        destination_arg: destination,
101    };
102    if result.is_some_and(|previous| previous != candidate) {
103        return None;
104    }
105    *result = Some(candidate);
106    Some(())
107}
108
109fn argument_index(body: &Body<'_>, operand: &Operand<'_>) -> Option<usize> {
110    let (Operand::Copy(place) | Operand::Move(place)) = operand else {
111        return None;
112    };
113    if !place.projection.is_empty() {
114        return None;
115    }
116    let local = place.local.as_usize();
117    (local > 0 && local <= body.arg_count).then_some(local - 1)
118}