Skip to content

Commit 917c89e

Browse files
committed
Optimize lvalue reads from Value::ByVal and Value::ByValPair
1 parent 91409f1 commit 917c89e

File tree

3 files changed

+100
-5
lines changed

3 files changed

+100
-5
lines changed

src/error.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ pub enum EvalError<'tcx> {
6565
Panic,
6666
NeedsRfc(String),
6767
NotConst(String),
68+
ReadFromReturnPointer,
6869
}
6970

7071
pub type EvalResult<'tcx, T = ()> = Result<T, EvalError<'tcx>>;
@@ -162,6 +163,8 @@ impl<'tcx> Error for EvalError<'tcx> {
162163
"this feature needs an rfc before being allowed inside constants",
163164
EvalError::NotConst(_) =>
164165
"this feature is not compatible with constant evaluation",
166+
EvalError::ReadFromReturnPointer =>
167+
"tried to read from the return pointer",
165168
}
166169
}
167170

src/eval_context.rs

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -807,7 +807,7 @@ impl<'a, 'tcx> EvalContext<'a, 'tcx> {
807807
Ok(())
808808
}
809809

810-
fn type_is_fat_ptr(&self, ty: Ty<'tcx>) -> bool {
810+
pub(super) fn type_is_fat_ptr(&self, ty: Ty<'tcx>) -> bool {
811811
match ty.sty {
812812
ty::TyRawPtr(ref tam) |
813813
ty::TyRef(_, ref tam) => !self.type_is_sized(tam.ty),
@@ -868,6 +868,14 @@ impl<'a, 'tcx> EvalContext<'a, 'tcx> {
868868
pub fn get_field_ty(&self, ty: Ty<'tcx>, field_index: usize) -> EvalResult<'tcx, Ty<'tcx>> {
869869
match ty.sty {
870870
ty::TyAdt(adt_def, _) if adt_def.is_box() => self.get_fat_field(ty.boxed_ty(), field_index),
871+
ty::TyAdt(adt_def, substs) if adt_def.is_enum() => {
872+
use rustc::ty::layout::Layout::*;
873+
match *self.type_layout(ty)? {
874+
RawNullablePointer { nndiscr, .. } |
875+
StructWrappedNullablePointer { nndiscr, .. } => Ok(adt_def.variants[nndiscr as usize].fields[field_index].ty(self.tcx, substs)),
876+
_ => Err(EvalError::Unimplemented(format!("get_field_ty can't handle enum type: {:?}, {:?}", ty, ty.sty))),
877+
}
878+
}
871879
ty::TyAdt(adt_def, substs) => {
872880
Ok(adt_def.struct_variant().fields[field_index].ty(self.tcx, substs))
873881
}
@@ -876,6 +884,9 @@ impl<'a, 'tcx> EvalContext<'a, 'tcx> {
876884

877885
ty::TyRef(_, ref tam) |
878886
ty::TyRawPtr(ref tam) => self.get_fat_field(tam.ty, field_index),
887+
888+
ty::TyArray(ref inner, _) => Ok(inner),
889+
879890
_ => Err(EvalError::Unimplemented(format!("can't handle type: {:?}, {:?}", ty, ty.sty))),
880891
}
881892
}
@@ -902,14 +913,17 @@ impl<'a, 'tcx> EvalContext<'a, 'tcx> {
902913
}
903914
}
904915

905-
pub fn get_field_count(&self, ty: Ty<'tcx>) -> EvalResult<'tcx, usize> {
916+
pub fn get_field_count(&self, ty: Ty<'tcx>) -> EvalResult<'tcx, u64> {
906917
let layout = self.type_layout(ty)?;
907918

908919
use rustc::ty::layout::Layout::*;
909920
match *layout {
910-
Univariant { ref variant, .. } => Ok(variant.offsets.len()),
921+
Univariant { ref variant, .. } => Ok(variant.offsets.len() as u64),
911922
FatPointer { .. } => Ok(2),
912-
StructWrappedNullablePointer { ref nonnull, .. } => Ok(nonnull.offsets.len()),
923+
StructWrappedNullablePointer { ref nonnull, .. } => Ok(nonnull.offsets.len() as u64),
924+
Vector { count , .. } |
925+
Array { count, .. } => Ok(count),
926+
Scalar { .. } => Ok(0),
913927
_ => {
914928
let msg = format!("can't handle type: {:?}, with layout: {:?}", ty, layout);
915929
Err(EvalError::Unimplemented(msg))

src/lvalue.rs

Lines changed: 79 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,63 @@ impl<'tcx> Global<'tcx> {
126126
}
127127

128128
impl<'a, 'tcx> EvalContext<'a, 'tcx> {
129+
/// Reads a value from the lvalue without going through the intermediate step of obtaining
130+
/// a `miri::Lvalue`
131+
pub fn try_read_lvalue(&mut self, lvalue: &mir::Lvalue<'tcx>) -> EvalResult<'tcx, Option<Value>> {
132+
use rustc::mir::Lvalue::*;
133+
match *lvalue {
134+
// Might allow this in the future, right now there's no way to do this from Rust code anyway
135+
Local(mir::RETURN_POINTER) => Err(EvalError::ReadFromReturnPointer),
136+
// Directly reading a local will always succeed
137+
Local(local) => self.frame().get_local(local).map(Some),
138+
// Directly reading a static will always succeed
139+
Static(ref static_) => {
140+
let instance = ty::Instance::mono(self.tcx, static_.def_id);
141+
let cid = GlobalId { instance, promoted: None };
142+
Ok(Some(self.globals.get(&cid).expect("global not cached").value))
143+
},
144+
Projection(ref proj) => self.try_read_lvalue_projection(proj),
145+
}
146+
}
147+
148+
fn try_read_lvalue_projection(&mut self, proj: &mir::LvalueProjection<'tcx>) -> EvalResult<'tcx, Option<Value>> {
149+
use rustc::mir::ProjectionElem::*;
150+
let base = match self.try_read_lvalue(&proj.base)? {
151+
Some(base) => base,
152+
None => return Ok(None),
153+
};
154+
let base_ty = self.lvalue_ty(&proj.base);
155+
match proj.elem {
156+
Field(field, _) => match (field.index(), base) {
157+
// the only field of a struct
158+
(0, Value::ByVal(val)) => Ok(Some(Value::ByVal(val))),
159+
// split fat pointers, 2 element tuples, ...
160+
(0...1, Value::ByValPair(a, b)) if self.get_field_count(base_ty)? == 2 => {
161+
let val = [a, b][field.index()];
162+
Ok(Some(Value::ByVal(val)))
163+
},
164+
// the only field of a struct is a fat pointer
165+
(0, Value::ByValPair(..)) => Ok(Some(base)),
166+
_ => Ok(None),
167+
},
168+
// The NullablePointer cases should work fine, need to take care for normal enums
169+
Downcast(..) |
170+
Subslice { .. } |
171+
// reading index 0 or index 1 from a ByVal or ByVal pair could be optimized
172+
ConstantIndex { .. } | Index(_) |
173+
// No way to optimize this projection any better than the normal lvalue path
174+
Deref => Ok(None),
175+
}
176+
}
177+
129178
pub(super) fn eval_and_read_lvalue(&mut self, lvalue: &mir::Lvalue<'tcx>) -> EvalResult<'tcx, Value> {
130179
let ty = self.lvalue_ty(lvalue);
180+
// Shortcut for things like accessing a fat pointer's field,
181+
// which would otherwise (in the `eval_lvalue` path) require moving a `ByValPair` to memory
182+
// and returning an `Lvalue::Ptr` to it
183+
if let Some(val) = self.try_read_lvalue(lvalue)? {
184+
return Ok(val);
185+
}
131186
let lvalue = self.eval_lvalue(lvalue)?;
132187

133188
if ty.is_never() {
@@ -233,7 +288,30 @@ impl<'a, 'tcx> EvalContext<'a, 'tcx> {
233288
_ => bug!("field access on non-product type: {:?}", base_layout),
234289
};
235290

236-
let (base_ptr, base_extra) = self.force_allocation(base)?.to_ptr_and_extra();
291+
// Do not allocate in trivial cases
292+
let (base_ptr, base_extra) = match base {
293+
Lvalue::Ptr { ptr, extra } => (ptr, extra),
294+
Lvalue::Local { frame, local } => match self.stack[frame].get_local(local)? {
295+
// in case the type has a single field, just return the value
296+
Value::ByVal(_) if self.get_field_count(base_ty).map(|c| c == 1).unwrap_or(false) => {
297+
assert_eq!(offset.bytes(), 0, "ByVal can only have 1 non zst field with offset 0");
298+
return Ok(base);
299+
},
300+
Value::ByRef(_) |
301+
Value::ByValPair(..) |
302+
Value::ByVal(_) => self.force_allocation(base)?.to_ptr_and_extra(),
303+
},
304+
Lvalue::Global(cid) => match self.globals.get(&cid).expect("uncached global").value {
305+
// in case the type has a single field, just return the value
306+
Value::ByVal(_) if self.get_field_count(base_ty).map(|c| c == 1).unwrap_or(false) => {
307+
assert_eq!(offset.bytes(), 0, "ByVal can only have 1 non zst field with offset 0");
308+
return Ok(base);
309+
},
310+
Value::ByRef(_) |
311+
Value::ByValPair(..) |
312+
Value::ByVal(_) => self.force_allocation(base)?.to_ptr_and_extra(),
313+
},
314+
};
237315

238316
let offset = match base_extra {
239317
LvalueExtra::Vtable(tab) => {

0 commit comments

Comments
 (0)