Skip to main content

charon_driver/frontend/types/
mir.rs

1//! Copies of the relevant `MIR` types. MIR represents a rust (function) body as a CFG. It's a
2//! semantically rich representation that contains no high-level control-flow operations like loops
3//! or patterns; instead the control flow is entirely described by gotos and switches on integer
4//! values.
5use crate::frontend::prelude::*;
6use rustc_middle::{mir, ty};
7
8sinto_reexport!(rustc_abi::FieldIdx);
9
10impl<S> SInto<S, u64> for rustc_middle::mir::interpret::AllocId {
11    fn sinto(&self, _: &S) -> u64 {
12        self.0.get()
13    }
14}
15
16pub fn local_names(body: &mir::Body<'_>) -> rustc_index::IndexVec<mir::Local, Option<String>> {
17    let mut names = rustc_index::IndexVec::from_elem(None, &body.local_decls);
18    for info in &body.var_debug_info {
19        if let mir::VarDebugInfoContents::Place(place) = info.value
20            && place.projection.is_empty()
21        {
22            names[place.local].get_or_insert_with(|| info.name.to_string());
23        }
24    }
25    names
26}
27
28/// Enumerates the kinds of Mir bodies. TODO: use const generics
29/// instead of an open list of types.
30pub mod mir_kinds {
31    #[derive(Debug, Copy, Clone)]
32    pub struct Optimized;
33
34    #[derive(Debug, Copy, Clone)]
35    pub struct CTFE;
36
37    /// MIR of unknown origin. `body()` returns `None`; this is used to get the bodies provided via
38    /// `from_mir` but not attempt to get MIR for functions etc.
39    #[derive(Debug, Copy, Clone)]
40    pub struct Unknown;
41
42    pub use rustc::*;
43    mod rustc {
44        use super::*;
45        use rustc_middle::mir::Body;
46        use rustc_middle::ty::TyCtxt;
47        use rustc_span::def_id::DefId;
48
49        pub trait IsMirKind: Clone + std::fmt::Debug {
50            // CPS to deal with stealable bodies cleanly.
51            fn get_mir<'tcx, T>(
52                tcx: TyCtxt<'tcx>,
53                id: DefId,
54                f: impl FnOnce(&Body<'tcx>) -> T,
55            ) -> Option<T>;
56        }
57
58        impl IsMirKind for Optimized {
59            fn get_mir<'tcx, T>(
60                tcx: TyCtxt<'tcx>,
61                id: DefId,
62                f: impl FnOnce(&Body<'tcx>) -> T,
63            ) -> Option<T> {
64                tcx.is_mir_available(id).then(|| f(tcx.optimized_mir(id)))
65            }
66        }
67
68        impl IsMirKind for CTFE {
69            fn get_mir<'tcx, T>(
70                tcx: TyCtxt<'tcx>,
71                id: DefId,
72                f: impl FnOnce(&Body<'tcx>) -> T,
73            ) -> Option<T> {
74                (!tcx.is_trivial_const(id)).then(|| f(tcx.mir_for_ctfe(id)))
75            }
76        }
77
78        impl IsMirKind for Unknown {
79            fn get_mir<'tcx, T>(
80                _tcx: TyCtxt<'tcx>,
81                _id: DefId,
82                _f: impl FnOnce(&Body<'tcx>) -> T,
83            ) -> Option<T> {
84                None
85            }
86        }
87    }
88}
89
90pub use mir_kinds::IsMirKind;
91
92/// The contents of `Operand::Const`.
93#[derive(Debug, Clone)]
94pub struct ConstOperand<'tcx> {
95    pub span: Span,
96    pub ty: Ty<'tcx>,
97    pub kind: ConstOperandKind<'tcx>,
98}
99
100#[derive(Debug, Clone)]
101pub enum ConstOperandKind<'tcx> {
102    /// An evaluated constant represented as an expression.
103    Value(ConstantExpr<'tcx>),
104    /// Part of a MIR body that was promoted to be a constant. May not be evaluatable because of
105    /// generics.
106    /// It's a reference to the `DefId` of the constant. Note that rustc does not give a `DefId` to
107    /// promoted constants, but we do in the frontend.
108    Promoted(ItemRef<'tcx>),
109}
110
111impl<'tcx, S: UnderOwnerState<'tcx>> SInto<S, ConstOperand<'tcx>> for mir::ConstOperand<'tcx> {
112    fn sinto(&self, s: &S) -> ConstOperand<'tcx> {
113        let kind = translate_mir_const(s, self.span, self.const_);
114        ConstOperand {
115            span: self.span.sinto(s),
116            ty: self.const_.ty().sinto(s),
117            kind,
118        }
119    }
120}
121
122/// Translate a MIR constant.
123fn translate_mir_const<'tcx, S: UnderOwnerState<'tcx>>(
124    s: &S,
125    span: rustc_span::Span,
126    konst: mir::Const<'tcx>,
127) -> ConstOperandKind<'tcx> {
128    use ConstOperandKind::{Promoted, Value};
129    use rustc_middle::mir::Const;
130    let tcx = s.base().tcx;
131    match konst {
132        Const::Val(const_value, ty) => {
133            let src = ConstSource::Value(const_value, ty);
134            Value(
135                read_const(s, span, src, ReadMode::Structured).unwrap_or_else(|| {
136                    ConstantExpr::new(ConstantExprKind::Todo("ConstEvalVal".into()), ty.sinto(s))
137                }),
138            )
139        }
140        Const::Ty(_ty, c) => Value(c.sinto(s)),
141        Const::Unevaluated(ucv, _) => {
142            match ucv.promoted {
143                Some(promoted) => {
144                    let def_id = ucv.def.sinto(s).make_promoted_child(s, promoted);
145                    let item = ItemRef::translate_from_frontend_def_id(s, def_id, ucv.args);
146                    assert!(item.in_trait.is_none());
147                    Promoted(item)
148                }
149                None => {
150                    let ucv = ucv.shrink(tcx);
151                    // We go through a `ty::Const`. This loses info that `ValTree`s don't capture
152                    // such as data in padding bytes.
153                    let val =
154                        ty::Const::new(tcx, ty::ConstKind::Alias(ty::IsRigid::No, ucv)).sinto(s);
155                    Value(val)
156                }
157            }
158        }
159    }
160}