Skip to content

Commit 7578100

Browse files
committed
Support most constant kinds in custom mir
1 parent a982541 commit 7578100

File tree

6 files changed

+170
-78
lines changed

6 files changed

+170
-78
lines changed

compiler/rustc_mir_build/src/build/custom/parse.rs

+8-5
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ macro_rules! parse_by_kind {
2323
(
2424
$self:ident,
2525
$expr_id:expr,
26+
$expr_name:pat,
2627
$expected:literal,
2728
$(
2829
@call($name:literal, $args:ident) => $call_expr:expr,
@@ -33,6 +34,8 @@ macro_rules! parse_by_kind {
3334
) => {{
3435
let expr_id = $self.preparse($expr_id);
3536
let expr = &$self.thir[expr_id];
37+
debug!("Trying to parse {:?} as {}", expr.kind, $expected);
38+
let $expr_name = expr;
3639
match &expr.kind {
3740
$(
3841
ExprKind::Call { ty, fun: _, args: $args, .. } if {
@@ -137,26 +140,26 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> {
137140
/// This allows us to easily parse the basic blocks declarations, local declarations, and
138141
/// basic block definitions in order.
139142
pub fn parse_body(&mut self, expr_id: ExprId) -> PResult<()> {
140-
let body = parse_by_kind!(self, expr_id, "whole body",
143+
let body = parse_by_kind!(self, expr_id, _, "whole body",
141144
ExprKind::Block { block } => self.thir[*block].expr.unwrap(),
142145
);
143-
let (block_decls, rest) = parse_by_kind!(self, body, "body with block decls",
146+
let (block_decls, rest) = parse_by_kind!(self, body, _, "body with block decls",
144147
ExprKind::Block { block } => {
145148
let block = &self.thir[*block];
146149
(&block.stmts, block.expr.unwrap())
147150
},
148151
);
149152
self.parse_block_decls(block_decls.iter().copied())?;
150153

151-
let (local_decls, rest) = parse_by_kind!(self, rest, "body with local decls",
154+
let (local_decls, rest) = parse_by_kind!(self, rest, _, "body with local decls",
152155
ExprKind::Block { block } => {
153156
let block = &self.thir[*block];
154157
(&block.stmts, block.expr.unwrap())
155158
},
156159
);
157160
self.parse_local_decls(local_decls.iter().copied())?;
158161

159-
let block_defs = parse_by_kind!(self, rest, "body with block defs",
162+
let block_defs = parse_by_kind!(self, rest, _, "body with block defs",
160163
ExprKind::Block { block } => &self.thir[*block].stmts,
161164
);
162165
for (i, block_def) in block_defs.iter().enumerate() {
@@ -223,7 +226,7 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> {
223226
}
224227

225228
fn parse_block_def(&self, expr_id: ExprId) -> PResult<BasicBlockData<'tcx>> {
226-
let block = parse_by_kind!(self, expr_id, "basic block",
229+
let block = parse_by_kind!(self, expr_id, _, "basic block",
227230
ExprKind::Block { block } => &self.thir[*block],
228231
);
229232

compiler/rustc_mir_build/src/build/custom/parse/instruction.rs

+17-7
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use super::{parse_by_kind, PResult, ParseCtxt};
44

55
impl<'tcx, 'body> ParseCtxt<'tcx, 'body> {
66
pub fn parse_statement(&self, expr_id: ExprId) -> PResult<StatementKind<'tcx>> {
7-
parse_by_kind!(self, expr_id, "statement",
7+
parse_by_kind!(self, expr_id, _, "statement",
88
@call("mir_retag", args) => {
99
Ok(StatementKind::Retag(RetagKind::Default, Box::new(self.parse_place(args[0])?)))
1010
},
@@ -20,7 +20,7 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> {
2020
}
2121

2222
pub fn parse_terminator(&self, expr_id: ExprId) -> PResult<TerminatorKind<'tcx>> {
23-
parse_by_kind!(self, expr_id, "terminator",
23+
parse_by_kind!(self, expr_id, _, "terminator",
2424
@call("mir_return", _args) => {
2525
Ok(TerminatorKind::Return)
2626
},
@@ -31,7 +31,7 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> {
3131
}
3232

3333
fn parse_rvalue(&self, expr_id: ExprId) -> PResult<Rvalue<'tcx>> {
34-
parse_by_kind!(self, expr_id, "rvalue",
34+
parse_by_kind!(self, expr_id, _, "rvalue",
3535
ExprKind::Borrow { borrow_kind, arg } => Ok(
3636
Rvalue::Ref(self.tcx.lifetimes.re_erased, *borrow_kind, self.parse_place(*arg)?)
3737
),
@@ -43,14 +43,24 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> {
4343
}
4444

4545
fn parse_operand(&self, expr_id: ExprId) -> PResult<Operand<'tcx>> {
46-
parse_by_kind!(self, expr_id, "operand",
46+
parse_by_kind!(self, expr_id, expr, "operand",
4747
@call("mir_move", args) => self.parse_place(args[0]).map(Operand::Move),
48+
ExprKind::Literal { .. }
49+
| ExprKind::NamedConst { .. }
50+
| ExprKind::NonHirLiteral { .. }
51+
| ExprKind::ZstLiteral { .. }
52+
| ExprKind::ConstParam { .. }
53+
| ExprKind::ConstBlock { .. } => {
54+
Ok(Operand::Constant(Box::new(
55+
crate::build::expr::as_constant::as_constant_inner(expr, |_| None, self.tcx)
56+
)))
57+
},
4858
_ => self.parse_place(expr_id).map(Operand::Copy),
4959
)
5060
}
5161

5262
fn parse_place(&self, expr_id: ExprId) -> PResult<Place<'tcx>> {
53-
parse_by_kind!(self, expr_id, "place",
63+
parse_by_kind!(self, expr_id, _, "place",
5464
ExprKind::Deref { arg } => Ok(
5565
self.parse_place(*arg)?.project_deeper(&[PlaceElem::Deref], self.tcx)
5666
),
@@ -59,13 +69,13 @@ impl<'tcx, 'body> ParseCtxt<'tcx, 'body> {
5969
}
6070

6171
fn parse_local(&self, expr_id: ExprId) -> PResult<Local> {
62-
parse_by_kind!(self, expr_id, "local",
72+
parse_by_kind!(self, expr_id, _, "local",
6373
ExprKind::VarRef { id } => Ok(self.local_map[id]),
6474
)
6575
}
6676

6777
fn parse_block(&self, expr_id: ExprId) -> PResult<BasicBlock> {
68-
parse_by_kind!(self, expr_id, "basic block",
78+
parse_by_kind!(self, expr_id, _, "basic block",
6979
ExprKind::VarRef { id } => Ok(self.block_map[id]),
7080
)
7181
}

compiler/rustc_mir_build/src/build/expr/as_constant.rs

+71-66
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@ use rustc_middle::mir::interpret::{
88
};
99
use rustc_middle::mir::*;
1010
use rustc_middle::thir::*;
11-
use rustc_middle::ty::{self, CanonicalUserTypeAnnotation, TyCtxt};
11+
use rustc_middle::ty::{
12+
self, CanonicalUserType, CanonicalUserTypeAnnotation, TyCtxt, UserTypeAnnotationIndex,
13+
};
1214
use rustc_span::DUMMY_SP;
1315
use rustc_target::abi::Size;
1416

@@ -19,84 +21,87 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
1921
let this = self;
2022
let tcx = this.tcx;
2123
let Expr { ty, temp_lifetime: _, span, ref kind } = *expr;
22-
match *kind {
24+
match kind {
2325
ExprKind::Scope { region_scope: _, lint_level: _, value } => {
24-
this.as_constant(&this.thir[value])
25-
}
26-
ExprKind::Literal { lit, neg } => {
27-
let literal =
28-
match lit_to_mir_constant(tcx, LitToConstInput { lit: &lit.node, ty, neg }) {
29-
Ok(c) => c,
30-
Err(LitToConstError::Reported(guar)) => {
31-
ConstantKind::Ty(tcx.const_error_with_guaranteed(ty, guar))
32-
}
33-
Err(LitToConstError::TypeError) => {
34-
bug!("encountered type error in `lit_to_mir_constant")
35-
}
36-
};
37-
38-
Constant { span, user_ty: None, literal }
26+
this.as_constant(&this.thir[*value])
3927
}
40-
ExprKind::NonHirLiteral { lit, ref user_ty } => {
41-
let user_ty = user_ty.as_ref().map(|user_ty| {
42-
this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
28+
_ => as_constant_inner(
29+
expr,
30+
|user_ty| {
31+
Some(this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
4332
span,
4433
user_ty: user_ty.clone(),
4534
inferred_ty: ty,
46-
})
47-
});
48-
let literal = ConstantKind::Val(ConstValue::Scalar(Scalar::Int(lit)), ty);
35+
}))
36+
},
37+
tcx,
38+
),
39+
}
40+
}
41+
}
4942

50-
Constant { span, user_ty: user_ty, literal }
51-
}
52-
ExprKind::ZstLiteral { ref user_ty } => {
53-
let user_ty = user_ty.as_ref().map(|user_ty| {
54-
this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
55-
span,
56-
user_ty: user_ty.clone(),
57-
inferred_ty: ty,
58-
})
59-
});
60-
let literal = ConstantKind::Val(ConstValue::ZeroSized, ty);
43+
pub fn as_constant_inner<'tcx>(
44+
expr: &Expr<'tcx>,
45+
push_cuta: impl FnMut(&Box<CanonicalUserType<'tcx>>) -> Option<UserTypeAnnotationIndex>,
46+
tcx: TyCtxt<'tcx>,
47+
) -> Constant<'tcx> {
48+
let Expr { ty, temp_lifetime: _, span, ref kind } = *expr;
49+
match *kind {
50+
ExprKind::Literal { lit, neg } => {
51+
let literal =
52+
match lit_to_mir_constant(tcx, LitToConstInput { lit: &lit.node, ty, neg }) {
53+
Ok(c) => c,
54+
Err(LitToConstError::Reported(guar)) => {
55+
ConstantKind::Ty(tcx.const_error_with_guaranteed(ty, guar))
56+
}
57+
Err(LitToConstError::TypeError) => {
58+
bug!("encountered type error in `lit_to_mir_constant")
59+
}
60+
};
6161

62-
Constant { span, user_ty: user_ty, literal }
63-
}
64-
ExprKind::NamedConst { def_id, substs, ref user_ty } => {
65-
let user_ty = user_ty.as_ref().map(|user_ty| {
66-
this.canonical_user_type_annotations.push(CanonicalUserTypeAnnotation {
67-
span,
68-
user_ty: user_ty.clone(),
69-
inferred_ty: ty,
70-
})
71-
});
62+
Constant { span, user_ty: None, literal }
63+
}
64+
ExprKind::NonHirLiteral { lit, ref user_ty } => {
65+
let user_ty = user_ty.as_ref().map(push_cuta).flatten();
7266

73-
let uneval =
74-
mir::UnevaluatedConst::new(ty::WithOptConstParam::unknown(def_id), substs);
75-
let literal = ConstantKind::Unevaluated(uneval, ty);
67+
let literal = ConstantKind::Val(ConstValue::Scalar(Scalar::Int(lit)), ty);
7668

77-
Constant { user_ty, span, literal }
78-
}
79-
ExprKind::ConstParam { param, def_id: _ } => {
80-
let const_param = tcx.mk_const(param, expr.ty);
81-
let literal = ConstantKind::Ty(const_param);
69+
Constant { span, user_ty: user_ty, literal }
70+
}
71+
ExprKind::ZstLiteral { ref user_ty } => {
72+
let user_ty = user_ty.as_ref().map(push_cuta).flatten();
8273

83-
Constant { user_ty: None, span, literal }
84-
}
85-
ExprKind::ConstBlock { did: def_id, substs } => {
86-
let uneval =
87-
mir::UnevaluatedConst::new(ty::WithOptConstParam::unknown(def_id), substs);
88-
let literal = ConstantKind::Unevaluated(uneval, ty);
74+
let literal = ConstantKind::Val(ConstValue::ZeroSized, ty);
8975

90-
Constant { user_ty: None, span, literal }
91-
}
92-
ExprKind::StaticRef { alloc_id, ty, .. } => {
93-
let const_val = ConstValue::Scalar(Scalar::from_pointer(alloc_id.into(), &tcx));
94-
let literal = ConstantKind::Val(const_val, ty);
76+
Constant { span, user_ty: user_ty, literal }
77+
}
78+
ExprKind::NamedConst { def_id, substs, ref user_ty } => {
79+
let user_ty = user_ty.as_ref().map(push_cuta).flatten();
9580

96-
Constant { span, user_ty: None, literal }
97-
}
98-
_ => span_bug!(span, "expression is not a valid constant {:?}", kind),
81+
let uneval = mir::UnevaluatedConst::new(ty::WithOptConstParam::unknown(def_id), substs);
82+
let literal = ConstantKind::Unevaluated(uneval, ty);
83+
84+
Constant { user_ty, span, literal }
85+
}
86+
ExprKind::ConstParam { param, def_id: _ } => {
87+
let const_param = tcx.mk_const(ty::ConstKind::Param(param), expr.ty);
88+
let literal = ConstantKind::Ty(const_param);
89+
90+
Constant { user_ty: None, span, literal }
91+
}
92+
ExprKind::ConstBlock { did: def_id, substs } => {
93+
let uneval = mir::UnevaluatedConst::new(ty::WithOptConstParam::unknown(def_id), substs);
94+
let literal = ConstantKind::Unevaluated(uneval, ty);
95+
96+
Constant { user_ty: None, span, literal }
97+
}
98+
ExprKind::StaticRef { alloc_id, ty, .. } => {
99+
let const_val = ConstValue::Scalar(Scalar::from_pointer(alloc_id.into(), &tcx));
100+
let literal = ConstantKind::Val(const_val, ty);
101+
102+
Constant { span, user_ty: None, literal }
99103
}
104+
_ => span_bug!(span, "expression is not a valid constant {:?}", kind),
100105
}
101106
}
102107

library/core/src/intrinsics/mir.rs

+29
Original file line numberDiff line numberDiff line change
@@ -151,6 +151,13 @@ pub macro __internal_extract_let {
151151
let $var $(: $ty)?;
152152
::core::intrinsics::mir::__internal_extract_let!($($rest)*);
153153
},
154+
// Due to #86730, we have to handle const blocks separately
155+
(
156+
let $var:ident $(: $ty:ty)? = const $block:block; $($rest:tt)*
157+
) => {
158+
let $var $(: $ty)?;
159+
::core::intrinsics::mir::__internal_extract_let!($($rest)*);
160+
},
154161
// Otherwise, output nothing
155162
(
156163
$stmt:stmt; $($rest:tt)*
@@ -218,6 +225,28 @@ pub macro __internal_remove_let {
218225
}
219226
}
220227
)},
228+
// Due to #86730 , we have to handle const blocks separately
229+
(
230+
{
231+
{
232+
$($already_parsed:tt)*
233+
}
234+
{
235+
let $var:ident $(: $ty:ty)? = const $block:block;
236+
$($rest:tt)*
237+
}
238+
}
239+
) => { ::core::intrinsics::mir::__internal_remove_let!(
240+
{
241+
{
242+
$($already_parsed)*
243+
$var = const $block;
244+
}
245+
{
246+
$($rest)*
247+
}
248+
}
249+
)},
221250
// Otherwise, keep going
222251
(
223252
{
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// MIR for `consts` after built
2+
3+
fn consts() -> () {
4+
let mut _0: (); // return place in scope 0 at $DIR/consts.rs:10:27: 10:27
5+
let mut _1: u8; // in scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL
6+
let mut _2: i8; // in scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL
7+
let mut _3: u32; // in scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL
8+
let mut _4: i32; // in scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL
9+
let mut _5: fn() {consts::<10>}; // in scope 0 at $SRC_DIR/core/src/intrinsics/mir.rs:LL:COL
10+
11+
bb0: {
12+
_1 = const 5_u8; // scope 0 at $DIR/consts.rs:+0:1: +0:26
13+
_2 = const _; // scope 0 at $DIR/consts.rs:+0:1: +0:26
14+
_3 = const C; // scope 0 at $DIR/consts.rs:+0:1: +0:26
15+
_4 = const _; // scope 0 at $DIR/consts.rs:+0:1: +0:26
16+
_5 = consts::<10>; // scope 0 at $DIR/consts.rs:+0:1: +0:26
17+
// mir::Constant
18+
// + span: $DIR/consts.rs:16:18: 16:30
19+
// + literal: Const { ty: fn() {consts::<10>}, val: Value(<ZST>) }
20+
return; // scope 0 at $DIR/consts.rs:+0:1: +0:26
21+
}
22+
}
+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
#![feature(custom_mir, core_intrinsics, inline_const)]
2+
3+
extern crate core;
4+
use core::intrinsics::mir::*;
5+
6+
const D: i32 = 5;
7+
8+
// EMIT_MIR consts.consts.built.after.mir
9+
#[custom_mir(dialect = "built")]
10+
fn consts<const C: u32>() {
11+
mir!({
12+
let _a = 5_u8;
13+
let _b = const { 5_i8 };
14+
let _c = C;
15+
let _d = D;
16+
let _e = consts::<10>;
17+
Return()
18+
})
19+
}
20+
21+
fn main() {
22+
consts::<5>();
23+
}

0 commit comments

Comments
 (0)