Skip to content

Commit 4b172cc

Browse files
committed
Auto merge of #68118 - skinny121:eager_lit_eval, r=varkor
perf: Eagerly convert literals to consts Previousely even literal constants were being converted to an `Unevaluted` constant for evaluation later. This seems unecessary as no more information is needed to be able to convert the literal to a mir constant. Hopefully this will also minimise the performance impact of #67717, as far less constant evaluations are needed.
2 parents 8a87b94 + 583a4fc commit 4b172cc

File tree

19 files changed

+173
-115
lines changed

19 files changed

+173
-115
lines changed

src/librustc/dep_graph/dep_node.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@
5252
use crate::hir::map::DefPathHash;
5353
use crate::ich::{Fingerprint, StableHashingContext};
5454
use crate::mir;
55-
use crate::mir::interpret::GlobalId;
55+
use crate::mir::interpret::{GlobalId, LitToConstInput};
5656
use crate::traits;
5757
use crate::traits::query::{
5858
CanonicalPredicateGoal, CanonicalProjectionGoal, CanonicalTyGoal,

src/librustc/mir/interpret/mod.rs

+20-1
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ use crate::mir;
119119
use crate::ty::codec::TyDecoder;
120120
use crate::ty::layout::{self, Size};
121121
use crate::ty::subst::GenericArgKind;
122-
use crate::ty::{self, Instance, TyCtxt};
122+
use crate::ty::{self, Instance, Ty, TyCtxt};
123123
use byteorder::{BigEndian, LittleEndian, ReadBytesExt, WriteBytesExt};
124124
use rustc_data_structures::fx::FxHashMap;
125125
use rustc_data_structures::sync::{HashMapExt, Lock};
@@ -131,6 +131,7 @@ use std::fmt;
131131
use std::io;
132132
use std::num::NonZeroU32;
133133
use std::sync::atomic::{AtomicU32, Ordering};
134+
use syntax::ast::LitKind;
134135

135136
/// Uniquely identifies one of the following:
136137
/// - A constant
@@ -147,6 +148,24 @@ pub struct GlobalId<'tcx> {
147148
pub promoted: Option<mir::Promoted>,
148149
}
149150

151+
/// Input argument for `tcx.lit_to_const`.
152+
#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, HashStable)]
153+
pub struct LitToConstInput<'tcx> {
154+
/// The absolute value of the resultant constant.
155+
pub lit: &'tcx LitKind,
156+
/// The type of the constant.
157+
pub ty: Ty<'tcx>,
158+
/// If the constant is negative.
159+
pub neg: bool,
160+
}
161+
162+
/// Error type for `tcx.lit_to_const`.
163+
#[derive(Copy, Clone, Debug, Eq, PartialEq, HashStable)]
164+
pub enum LitToConstError {
165+
UnparseableFloat,
166+
Reported,
167+
}
168+
150169
#[derive(Copy, Clone, Eq, Hash, Ord, PartialEq, PartialOrd, Debug)]
151170
pub struct AllocId(pub u64);
152171

src/librustc/query/mod.rs

+8-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use crate::dep_graph::{DepKind, DepNode, RecoverKey, SerializedDepNodeIndex};
22
use crate::mir;
3-
use crate::mir::interpret::GlobalId;
3+
use crate::mir::interpret::{GlobalId, LitToConstInput};
44
use crate::traits;
55
use crate::traits::query::{
66
CanonicalPredicateGoal, CanonicalProjectionGoal, CanonicalTyGoal,
@@ -518,6 +518,13 @@ rustc_queries! {
518518
no_force
519519
desc { "get a &core::panic::Location referring to a span" }
520520
}
521+
522+
query lit_to_const(
523+
key: LitToConstInput<'tcx>
524+
) -> Result<&'tcx ty::Const<'tcx>, LitToConstError> {
525+
no_force
526+
desc { "converting literal to const" }
527+
}
521528
}
522529

523530
TypeChecking {

src/librustc/ty/query/keys.rs

+10
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,16 @@ impl<'tcx> Key for mir::interpret::GlobalId<'tcx> {
5252
}
5353
}
5454

55+
impl<'tcx> Key for mir::interpret::LitToConstInput<'tcx> {
56+
fn query_crate(&self) -> CrateNum {
57+
LOCAL_CRATE
58+
}
59+
60+
fn default_span(&self, _tcx: TyCtxt<'_>) -> Span {
61+
DUMMY_SP
62+
}
63+
}
64+
5565
impl Key for CrateNum {
5666
fn query_crate(&self) -> CrateNum {
5767
*self

src/librustc/ty/query/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ use crate::middle::stability::{self, DeprecationEntry};
1515
use crate::mir;
1616
use crate::mir::interpret::GlobalId;
1717
use crate::mir::interpret::{ConstEvalRawResult, ConstEvalResult};
18+
use crate::mir::interpret::{LitToConstError, LitToConstInput};
1819
use crate::mir::mono::CodegenUnit;
1920
use crate::session::config::{EntryFnType, OptLevel, OutputFilenames, SymbolManglingVersion};
2021
use crate::session::CrateDisambiguator;

src/librustc_mir/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -62,5 +62,5 @@ pub fn provide(providers: &mut Providers<'_>) {
6262
providers.destructure_const = |tcx, param_env_and_value| {
6363
let (param_env, value) = param_env_and_value.into_parts();
6464
const_eval::destructure_const(tcx, param_env, value)
65-
}
65+
};
6666
}

src/librustc_mir_build/hair/constant.rs

+33-24
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,15 @@
1-
use rustc::mir::interpret::{ConstValue, Scalar};
2-
use rustc::ty::{self, layout::Size, ParamEnv, Ty, TyCtxt};
1+
use rustc::mir::interpret::{
2+
truncate, Allocation, ConstValue, LitToConstError, LitToConstInput, Scalar,
3+
};
4+
use rustc::ty::{self, layout::Size, ParamEnv, TyCtxt};
35
use rustc_span::symbol::Symbol;
46
use syntax::ast;
57

6-
#[derive(PartialEq)]
7-
crate enum LitToConstError {
8-
UnparseableFloat,
9-
Reported,
10-
}
11-
128
crate fn lit_to_const<'tcx>(
13-
lit: &'tcx ast::LitKind,
149
tcx: TyCtxt<'tcx>,
15-
ty: Ty<'tcx>,
16-
neg: bool,
10+
lit_input: LitToConstInput<'tcx>,
1711
) -> Result<&'tcx ty::Const<'tcx>, LitToConstError> {
18-
use syntax::ast::*;
12+
let LitToConstInput { lit, ty, neg } = lit_input;
1913

2014
let trunc = |n| {
2115
let param_ty = ParamEnv::reveal_all().and(ty);
@@ -26,35 +20,50 @@ crate fn lit_to_const<'tcx>(
2620
Ok(ConstValue::Scalar(Scalar::from_uint(result, width)))
2721
};
2822

29-
use rustc::mir::interpret::*;
3023
let lit = match *lit {
31-
LitKind::Str(ref s, _) => {
24+
ast::LitKind::Str(ref s, _) => {
3225
let s = s.as_str();
3326
let allocation = Allocation::from_byte_aligned_bytes(s.as_bytes());
3427
let allocation = tcx.intern_const_alloc(allocation);
3528
ConstValue::Slice { data: allocation, start: 0, end: s.len() }
3629
}
37-
LitKind::ByteStr(ref data) => {
38-
let id = tcx.allocate_bytes(data);
39-
ConstValue::Scalar(Scalar::Ptr(id.into()))
30+
ast::LitKind::ByteStr(ref data) => {
31+
if let ty::Ref(_, ref_ty, _) = ty.kind {
32+
match ref_ty.kind {
33+
ty::Slice(_) => {
34+
let allocation = Allocation::from_byte_aligned_bytes(data as &Vec<u8>);
35+
let allocation = tcx.intern_const_alloc(allocation);
36+
ConstValue::Slice { data: allocation, start: 0, end: data.len() }
37+
}
38+
ty::Array(_, _) => {
39+
let id = tcx.allocate_bytes(data);
40+
ConstValue::Scalar(Scalar::Ptr(id.into()))
41+
}
42+
_ => {
43+
bug!("bytestring should have type of either &[u8] or &[u8; _], not {}", ty)
44+
}
45+
}
46+
} else {
47+
bug!("bytestring should have type of either &[u8] or &[u8; _], not {}", ty)
48+
}
4049
}
41-
LitKind::Byte(n) => ConstValue::Scalar(Scalar::from_uint(n, Size::from_bytes(1))),
42-
LitKind::Int(n, _) if neg => {
50+
ast::LitKind::Byte(n) => ConstValue::Scalar(Scalar::from_uint(n, Size::from_bytes(1))),
51+
ast::LitKind::Int(n, _) if neg => {
4352
let n = n as i128;
4453
let n = n.overflowing_neg().0;
4554
trunc(n as u128)?
4655
}
47-
LitKind::Int(n, _) => trunc(n)?,
48-
LitKind::Float(n, _) => {
56+
ast::LitKind::Int(n, _) => trunc(n)?,
57+
ast::LitKind::Float(n, _) => {
4958
let fty = match ty.kind {
5059
ty::Float(fty) => fty,
5160
_ => bug!(),
5261
};
5362
parse_float(n, fty, neg).map_err(|_| LitToConstError::UnparseableFloat)?
5463
}
55-
LitKind::Bool(b) => ConstValue::Scalar(Scalar::from_bool(b)),
56-
LitKind::Char(c) => ConstValue::Scalar(Scalar::from_char(c)),
57-
LitKind::Err(_) => unreachable!(),
64+
ast::LitKind::Bool(b) => ConstValue::Scalar(Scalar::from_bool(b)),
65+
ast::LitKind::Char(c) => ConstValue::Scalar(Scalar::from_char(c)),
66+
ast::LitKind::Err(_) => return Err(LitToConstError::Reported),
5867
};
5968
Ok(tcx.mk_const(ty::Const { val: ty::ConstKind::Value(lit), ty }))
6069
}

src/librustc_mir_build/hair/cx/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55
use crate::hair::util::UserAnnotatedTyHelpers;
66
use crate::hair::*;
77

8-
use crate::hair::constant::{lit_to_const, LitToConstError};
98
use rustc::infer::InferCtxt;
109
use rustc::middle::region;
10+
use rustc::mir::interpret::{LitToConstError, LitToConstInput};
1111
use rustc::ty::layout::VariantIdx;
1212
use rustc::ty::subst::Subst;
1313
use rustc::ty::subst::{GenericArg, InternalSubsts};
@@ -136,7 +136,7 @@ impl<'a, 'tcx> Cx<'a, 'tcx> {
136136
) -> &'tcx ty::Const<'tcx> {
137137
trace!("const_eval_literal: {:#?}, {:?}, {:?}, {:?}", lit, ty, sp, neg);
138138

139-
match lit_to_const(lit, self.tcx, ty, neg) {
139+
match self.tcx.at(sp).lit_to_const(LitToConstInput { lit, ty, neg }) {
140140
Ok(c) => c,
141141
Err(LitToConstError::UnparseableFloat) => {
142142
// FIXME(#31407) this is only necessary because float parsing is buggy

src/librustc_mir_build/hair/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use rustc_hir as hir;
1616
use rustc_hir::def_id::DefId;
1717
use rustc_span::Span;
1818

19-
mod constant;
19+
crate mod constant;
2020
crate mod cx;
2121

2222
crate mod pattern;

src/librustc_mir_build/hair/pattern/mod.rs

+22-27
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,10 @@ mod const_to_pat;
66

77
pub(crate) use self::check_match::check_match;
88

9-
use crate::hair::constant::*;
109
use crate::hair::util::UserAnnotatedTyHelpers;
1110

1211
use rustc::mir::interpret::{get_slice_bytes, sign_extend, ConstValue, ErrorHandled};
12+
use rustc::mir::interpret::{LitToConstError, LitToConstInput};
1313
use rustc::mir::UserTypeProjection;
1414
use rustc::mir::{BorrowKind, Field, Mutability};
1515
use rustc::ty::layout::VariantIdx;
@@ -822,35 +822,30 @@ impl<'a, 'tcx> PatCtxt<'a, 'tcx> {
822822
/// which would overflow if we tried to evaluate `128_i8` and then negate
823823
/// afterwards.
824824
fn lower_lit(&mut self, expr: &'tcx hir::Expr<'tcx>) -> PatKind<'tcx> {
825-
match expr.kind {
826-
hir::ExprKind::Lit(ref lit) => {
827-
let ty = self.tables.expr_ty(expr);
828-
match lit_to_const(&lit.node, self.tcx, ty, false) {
829-
Ok(val) => *self.const_to_pat(val, expr.hir_id, lit.span).kind,
830-
Err(LitToConstError::UnparseableFloat) => {
831-
self.errors.push(PatternError::FloatBug);
832-
PatKind::Wild
833-
}
834-
Err(LitToConstError::Reported) => PatKind::Wild,
825+
if let hir::ExprKind::Path(ref qpath) = expr.kind {
826+
*self.lower_path(qpath, expr.hir_id, expr.span).kind
827+
} else {
828+
let (lit, neg) = match expr.kind {
829+
hir::ExprKind::Lit(ref lit) => (lit, false),
830+
hir::ExprKind::Unary(hir::UnOp::UnNeg, ref expr) => {
831+
let lit = match expr.kind {
832+
hir::ExprKind::Lit(ref lit) => lit,
833+
_ => span_bug!(expr.span, "not a literal: {:?}", expr),
834+
};
835+
(lit, true)
835836
}
836-
}
837-
hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
838-
hir::ExprKind::Unary(hir::UnOp::UnNeg, ref expr) => {
839-
let ty = self.tables.expr_ty(expr);
840-
let lit = match expr.kind {
841-
hir::ExprKind::Lit(ref lit) => lit,
842-
_ => span_bug!(expr.span, "not a literal: {:?}", expr),
843-
};
844-
match lit_to_const(&lit.node, self.tcx, ty, true) {
845-
Ok(val) => *self.const_to_pat(val, expr.hir_id, lit.span).kind,
846-
Err(LitToConstError::UnparseableFloat) => {
847-
self.errors.push(PatternError::FloatBug);
848-
PatKind::Wild
849-
}
850-
Err(LitToConstError::Reported) => PatKind::Wild,
837+
_ => span_bug!(expr.span, "not a literal: {:?}", expr),
838+
};
839+
840+
let lit_input = LitToConstInput { lit: &lit.node, ty: self.tables.expr_ty(expr), neg };
841+
match self.tcx.at(expr.span).lit_to_const(lit_input) {
842+
Ok(val) => *self.const_to_pat(val, expr.hir_id, lit.span).kind,
843+
Err(LitToConstError::UnparseableFloat) => {
844+
self.errors.push(PatternError::FloatBug);
845+
PatKind::Wild
851846
}
847+
Err(LitToConstError::Reported) => PatKind::Wild,
852848
}
853-
_ => span_bug!(expr.span, "not a literal: {:?}", expr),
854849
}
855850
}
856851
}

src/librustc_mir_build/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -22,5 +22,6 @@ use rustc::ty::query::Providers;
2222

2323
pub fn provide(providers: &mut Providers<'_>) {
2424
providers.check_match = hair::pattern::check_match;
25+
providers.lit_to_const = hair::constant::lit_to_const;
2526
providers.mir_built = build::mir_built;
2627
}

src/librustc_typeck/astconv.rs

+27-13
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// ignore-tidy-filelength FIXME(#67418) Split up this file.
12
//! Conversion from AST representation of types to the `ty.rs` representation.
23
//! The main routine here is `ast_ty_to_ty()`; each use is parameterized by an
34
//! instance of `AstConv`.
@@ -37,6 +38,7 @@ use std::collections::BTreeSet;
3738
use std::iter;
3839
use std::slice;
3940

41+
use rustc::mir::interpret::LitToConstInput;
4042
use rustc_error_codes::*;
4143

4244
#[derive(Debug)]
@@ -2699,17 +2701,28 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
26992701
let tcx = self.tcx();
27002702
let def_id = tcx.hir().local_def_id(ast_const.hir_id);
27012703

2702-
let mut const_ = ty::Const {
2703-
val: ty::ConstKind::Unevaluated(
2704-
def_id,
2705-
InternalSubsts::identity_for_item(tcx, def_id),
2706-
None,
2707-
),
2708-
ty,
2704+
let expr = &tcx.hir().body(ast_const.body).value;
2705+
2706+
let lit_input = match expr.kind {
2707+
hir::ExprKind::Lit(ref lit) => Some(LitToConstInput { lit: &lit.node, ty, neg: false }),
2708+
hir::ExprKind::Unary(hir::UnOp::UnNeg, ref expr) => match expr.kind {
2709+
hir::ExprKind::Lit(ref lit) => {
2710+
Some(LitToConstInput { lit: &lit.node, ty, neg: true })
2711+
}
2712+
_ => None,
2713+
},
2714+
_ => None,
27092715
};
27102716

2711-
let expr = &tcx.hir().body(ast_const.body).value;
2712-
if let Some(def_id) = self.const_param_def_id(expr) {
2717+
if let Some(lit_input) = lit_input {
2718+
// If an error occurred, ignore that it's a literal and leave reporting the error up to
2719+
// mir.
2720+
if let Ok(c) = tcx.at(expr.span).lit_to_const(lit_input) {
2721+
return c;
2722+
}
2723+
}
2724+
2725+
let kind = if let Some(def_id) = self.const_param_def_id(expr) {
27132726
// Find the name and index of the const parameter by indexing the generics of the
27142727
// parent item and construct a `ParamConst`.
27152728
let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
@@ -2718,10 +2731,11 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
27182731
let generics = tcx.generics_of(item_def_id);
27192732
let index = generics.param_def_id_to_index[&tcx.hir().local_def_id(hir_id)];
27202733
let name = tcx.hir().name(hir_id);
2721-
const_.val = ty::ConstKind::Param(ty::ParamConst::new(index, name));
2722-
}
2723-
2724-
tcx.mk_const(const_)
2734+
ty::ConstKind::Param(ty::ParamConst::new(index, name))
2735+
} else {
2736+
ty::ConstKind::Unevaluated(def_id, InternalSubsts::identity_for_item(tcx, def_id), None)
2737+
};
2738+
tcx.mk_const(ty::Const { val: kind, ty })
27252739
}
27262740

27272741
pub fn impl_trait_ty_to_ty(

0 commit comments

Comments
 (0)