5 use syntax::source_map::{self, Span, DUMMY_SP};
6 use rustc::hir::def_id::DefId;
7 use rustc::hir::def::Def;
9 use rustc::ty::layout::{
10 self, Size, Align, HasDataLayout, LayoutOf, TyLayout
12 use rustc::ty::subst::{Subst, Substs};
13 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
14 use rustc::ty::query::TyCtxtAt;
15 use rustc_data_structures::indexed_vec::IndexVec;
16 use rustc::mir::interpret::{
18 GlobalId, Scalar, FrameInfo, AllocId,
19 EvalResult, EvalErrorKind,
20 truncate, sign_extend,
22 use rustc_data_structures::fx::FxHashMap;
25 Immediate, Operand, MemPlace, MPlaceTy, Place, PlaceTy, ScalarMaybeUndef,
29 pub struct EvalContext<'a, 'mir, 'tcx: 'a + 'mir, M: Machine<'a, 'mir, 'tcx>> {
30 /// Stores the `Machine` instance.
33 /// The results of the type checker, from rustc.
34 pub tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
36 /// Bounds in scope for polymorphic evaluations.
37 pub(crate) param_env: ty::ParamEnv<'tcx>,
39 /// The virtual memory system.
40 pub(crate) memory: Memory<'a, 'mir, 'tcx, M>,
42 /// The virtual call stack.
43 pub(crate) stack: Vec<Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>>,
45 /// A cache for deduplicating vtables
46 pub(super) vtables: FxHashMap<(Ty<'tcx>, Option<ty::PolyExistentialTraitRef<'tcx>>), AllocId>,
51 pub struct Frame<'mir, 'tcx: 'mir, Tag=(), Extra=()> {
52 ////////////////////////////////////////////////////////////////////////////////
53 // Function and callsite information
54 ////////////////////////////////////////////////////////////////////////////////
55 /// The MIR for the function called on this frame.
56 pub mir: &'mir mir::Mir<'tcx>,
58 /// The def_id and substs of the current function
59 pub instance: ty::Instance<'tcx>,
61 /// The span of the call site.
62 pub span: source_map::Span,
64 ////////////////////////////////////////////////////////////////////////////////
65 // Return place and locals
66 ////////////////////////////////////////////////////////////////////////////////
67 /// Work to perform when returning from this function
68 pub return_to_block: StackPopCleanup,
70 /// The location where the result of the current stack frame should be written to,
71 /// and its layout in the caller.
72 pub return_place: Option<PlaceTy<'tcx, Tag>>,
74 /// The list of locals for this stack frame, stored in order as
75 /// `[return_ptr, arguments..., variables..., temporaries...]`.
76 /// The locals are stored as `Option<Value>`s.
77 /// `None` represents a local that is currently dead, while a live local
78 /// can either directly contain `Scalar` or refer to some part of an `Allocation`.
79 pub locals: IndexVec<mir::Local, LocalValue<Tag>>,
80 pub local_layouts: IndexVec<mir::Local, Cell<Option<TyLayout<'tcx>>>>,
82 ////////////////////////////////////////////////////////////////////////////////
83 // Current position within the function
84 ////////////////////////////////////////////////////////////////////////////////
85 /// The block that is currently executed (or will be executed after the above call stacks
87 pub block: mir::BasicBlock,
89 /// The index of the currently evaluated statement.
92 /// Extra data for the machine
96 #[derive(Clone, Debug, Eq, PartialEq, Hash)]
97 pub enum StackPopCleanup {
98 /// Jump to the next block in the caller, or cause UB if None (that's a function
99 /// that may never return). Also store layout of return place so
100 /// we can validate it at that layout.
101 Goto(Option<mir::BasicBlock>),
102 /// Just do nohing: Used by Main and for the box_alloc hook in miri.
103 /// `cleanup` says whether locals are deallocated. Static computation
104 /// wants them leaked to intern what they need (and just throw away
105 /// the entire `ecx` when it is done).
106 None { cleanup: bool },
109 // State of a local variable
110 #[derive(Copy, Clone, PartialEq, Eq, Hash)]
111 pub enum LocalValue<Tag=(), Id=AllocId> {
113 // Mostly for convenience, we re-use the `Operand` type here.
114 // This is an optimization over just always having a pointer here;
115 // we can thus avoid doing an allocation when the local just stores
116 // immediate values *and* never has its address taken.
117 Live(Operand<Tag, Id>),
120 impl<'tcx, Tag> LocalValue<Tag> {
121 pub fn access(&self) -> EvalResult<'tcx, &Operand<Tag>> {
123 LocalValue::Dead => err!(DeadLocal),
124 LocalValue::Live(ref val) => Ok(val),
128 pub fn access_mut(&mut self) -> EvalResult<'tcx, &mut Operand<Tag>> {
130 LocalValue::Dead => err!(DeadLocal),
131 LocalValue::Live(ref mut val) => Ok(val),
136 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> HasDataLayout
137 for EvalContext<'a, 'mir, 'tcx, M>
140 fn data_layout(&self) -> &layout::TargetDataLayout {
141 &self.tcx.data_layout
145 impl<'a, 'mir, 'tcx, M> layout::HasTyCtxt<'tcx> for EvalContext<'a, 'mir, 'tcx, M>
146 where M: Machine<'a, 'mir, 'tcx>
149 fn tcx<'d>(&'d self) -> TyCtxt<'d, 'tcx, 'tcx> {
154 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> LayoutOf
155 for EvalContext<'a, 'mir, 'tcx, M>
158 type TyLayout = EvalResult<'tcx, TyLayout<'tcx>>;
161 fn layout_of(&self, ty: Ty<'tcx>) -> Self::TyLayout {
162 self.tcx.layout_of(self.param_env.and(ty))
163 .map_err(|layout| EvalErrorKind::Layout(layout).into())
167 impl<'a, 'mir, 'tcx: 'mir, M: Machine<'a, 'mir, 'tcx>> EvalContext<'a, 'mir, 'tcx, M> {
169 tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
170 param_env: ty::ParamEnv<'tcx>,
177 memory: Memory::new(tcx),
179 vtables: FxHashMap::default(),
184 pub fn memory(&self) -> &Memory<'a, 'mir, 'tcx, M> {
189 pub fn memory_mut(&mut self) -> &mut Memory<'a, 'mir, 'tcx, M> {
194 pub fn stack(&self) -> &[Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>] {
199 pub fn cur_frame(&self) -> usize {
200 assert!(self.stack.len() > 0);
205 pub fn frame(&self) -> &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
206 self.stack.last().expect("no call frames exist")
210 pub fn frame_mut(&mut self) -> &mut Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra> {
211 self.stack.last_mut().expect("no call frames exist")
215 pub(super) fn mir(&self) -> &'mir mir::Mir<'tcx> {
219 pub(super) fn subst_and_normalize_erasing_regions<T: TypeFoldable<'tcx>>(
222 ) -> EvalResult<'tcx, T> {
223 match self.stack.last() {
224 Some(frame) => Ok(self.tcx.subst_and_normalize_erasing_regions(
225 frame.instance.substs,
229 None => if substs.needs_subst() {
230 err!(TooGeneric).into()
237 pub(super) fn resolve(
240 substs: &'tcx Substs<'tcx>
241 ) -> EvalResult<'tcx, ty::Instance<'tcx>> {
242 trace!("resolve: {:?}, {:#?}", def_id, substs);
243 trace!("param_env: {:#?}", self.param_env);
244 let substs = self.subst_and_normalize_erasing_regions(substs)?;
245 trace!("substs: {:#?}", substs);
246 ty::Instance::resolve(
251 ).ok_or_else(|| EvalErrorKind::TooGeneric.into())
254 pub fn type_is_sized(&self, ty: Ty<'tcx>) -> bool {
255 ty.is_sized(self.tcx, self.param_env)
258 pub fn type_is_freeze(&self, ty: Ty<'tcx>) -> bool {
259 ty.is_freeze(*self.tcx, self.param_env, DUMMY_SP)
264 instance: ty::InstanceDef<'tcx>,
265 ) -> EvalResult<'tcx, &'tcx mir::Mir<'tcx>> {
266 // do not continue if typeck errors occurred (can only occur in local crate)
267 let did = instance.def_id();
269 && self.tcx.has_typeck_tables(did)
270 && self.tcx.typeck_tables_of(did).tainted_by_errors
272 return err!(TypeckError);
274 trace!("load mir {:?}", instance);
276 ty::InstanceDef::Item(def_id) => {
277 self.tcx.maybe_optimized_mir(def_id).ok_or_else(||
278 EvalErrorKind::NoMirFor(self.tcx.item_path_str(def_id)).into()
281 _ => Ok(self.tcx.instance_mir(instance)),
285 pub fn monomorphize_in_frame<T: TypeFoldable<'tcx> + Subst<'tcx>>(
288 ) -> EvalResult<'tcx, T> {
289 match self.stack.last() {
290 Some(frame) => Ok(self.monomorphize(t, frame.instance.substs)),
291 None => if t.needs_subst() {
292 err!(TooGeneric).into()
299 pub fn monomorphize<T: TypeFoldable<'tcx> + Subst<'tcx>>(
302 substs: &'tcx Substs<'tcx>
304 // miri doesn't care about lifetimes, and will choke on some crazy ones
305 // let's simply get rid of them
306 let substituted = t.subst(*self.tcx, substs);
307 self.tcx.normalize_erasing_regions(ty::ParamEnv::reveal_all(), substituted)
310 pub fn layout_of_local(
312 frame: &Frame<'mir, 'tcx, M::PointerTag, M::FrameExtra>,
314 ) -> EvalResult<'tcx, TyLayout<'tcx>> {
315 let cell = &frame.local_layouts[local];
316 if cell.get().is_none() {
317 let local_ty = frame.mir.local_decls[local].ty;
318 let local_ty = self.monomorphize(local_ty, frame.instance.substs);
319 let layout = self.layout_of(local_ty)?;
320 cell.set(Some(layout));
323 Ok(cell.get().unwrap())
326 pub fn str_to_immediate(&mut self, s: &str) -> EvalResult<'tcx, Immediate<M::PointerTag>> {
327 let ptr = self.memory.allocate_static_bytes(s.as_bytes()).with_default_tag();
328 Ok(Immediate::new_slice(Scalar::Ptr(ptr), s.len() as u64, self))
331 /// Return the actual dynamic size and alignment of the place at the given type.
332 /// Only the "meta" (metadata) part of the place matters.
333 /// This can fail to provide an answer for extern types.
334 pub(super) fn size_and_align_of(
336 metadata: Option<Scalar<M::PointerTag>>,
337 layout: TyLayout<'tcx>,
338 ) -> EvalResult<'tcx, Option<(Size, Align)>> {
339 if !layout.is_unsized() {
340 return Ok(Some((layout.size, layout.align.abi)));
342 match layout.ty.sty {
343 ty::Adt(..) | ty::Tuple(..) => {
344 // First get the size of all statically known fields.
345 // Don't use type_of::sizing_type_of because that expects t to be sized,
346 // and it also rounds up to alignment, which we want to avoid,
347 // as the unsized field's alignment could be smaller.
348 assert!(!layout.ty.is_simd());
349 trace!("DST layout: {:?}", layout);
351 let sized_size = layout.fields.offset(layout.fields.count() - 1);
352 let sized_align = layout.align.abi;
354 "DST {} statically sized prefix size: {:?} align: {:?}",
360 // Recurse to get the size of the dynamically sized field (must be
361 // the last field). Can't have foreign types here, how would we
362 // adjust alignment and size for them?
363 let field = layout.field(self, layout.fields.count() - 1)?;
364 let (unsized_size, unsized_align) = match self.size_and_align_of(metadata, field)? {
365 Some(size_and_align) => size_and_align,
367 // A field with extern type. If this field is at offset 0, we behave
368 // like the underlying extern type.
369 // FIXME: Once we have made decisions for how to handle size and alignment
370 // of `extern type`, this should be adapted. It is just a temporary hack
371 // to get some code to work that probably ought to work.
372 if sized_size == Size::ZERO {
375 bug!("Fields cannot be extern types, unless they are at offset 0")
380 // FIXME (#26403, #27023): We should be adding padding
381 // to `sized_size` (to accommodate the `unsized_align`
382 // required of the unsized field that follows) before
383 // summing it with `sized_size`. (Note that since #26403
384 // is unfixed, we do not yet add the necessary padding
385 // here. But this is where the add would go.)
387 // Return the sum of sizes and max of aligns.
388 let size = sized_size + unsized_size;
390 // Choose max of two known alignments (combined value must
391 // be aligned according to more restrictive of the two).
392 let align = sized_align.max(unsized_align);
394 // Issue #27023: must add any necessary padding to `size`
395 // (to make it a multiple of `align`) before returning it.
397 // Namely, the returned size should be, in C notation:
399 // `size + ((size & (align-1)) ? align : 0)`
401 // emulated via the semi-standard fast bit trick:
403 // `(size + (align-1)) & -align`
405 Ok(Some((size.align_to(align), align)))
408 let vtable = metadata.expect("dyn trait fat ptr must have vtable").to_ptr()?;
409 // the second entry in the vtable is the dynamic size of the object.
410 Ok(Some(self.read_size_and_align_from_vtable(vtable)?))
413 ty::Slice(_) | ty::Str => {
414 let len = metadata.expect("slice fat ptr must have vtable").to_usize(self)?;
415 let elem = layout.field(self, 0)?;
416 Ok(Some((elem.size * len, elem.align.abi)))
423 _ => bug!("size_and_align_of::<{:?}> not supported", layout.ty),
427 pub fn size_and_align_of_mplace(
429 mplace: MPlaceTy<'tcx, M::PointerTag>
430 ) -> EvalResult<'tcx, Option<(Size, Align)>> {
431 self.size_and_align_of(mplace.meta, mplace.layout)
434 pub fn push_stack_frame(
436 instance: ty::Instance<'tcx>,
437 span: source_map::Span,
438 mir: &'mir mir::Mir<'tcx>,
439 return_place: Option<PlaceTy<'tcx, M::PointerTag>>,
440 return_to_block: StackPopCleanup,
441 ) -> EvalResult<'tcx> {
442 if self.stack.len() > 1 { // FIXME should be "> 0", printing topmost frame crashes rustc...
443 info!("PAUSING({}) {}", self.cur_frame(), self.frame().instance);
445 ::log_settings::settings().indentation += 1;
447 // first push a stack frame so we have access to the local substs
448 let extra = M::stack_push(self)?;
449 self.stack.push(Frame {
451 block: mir::START_BLOCK,
454 // empty local array, we fill it in below, after we are inside the stack frame and
455 // all methods actually know about the frame
456 locals: IndexVec::new(),
457 local_layouts: IndexVec::from_elem_n(Default::default(), mir.local_decls.len()),
464 // don't allocate at all for trivial constants
465 if mir.local_decls.len() > 1 {
466 // We put some marker immediate into the locals that we later want to initialize.
467 // This can be anything except for LocalValue::Dead -- because *that* is the
468 // value we use for things that we know are initially dead.
470 LocalValue::Live(Operand::Immediate(Immediate::Scalar(ScalarMaybeUndef::Undef)));
471 let mut locals = IndexVec::from_elem(dummy, &mir.local_decls);
472 // Return place is handled specially by the `eval_place` functions, and the
473 // entry in `locals` should never be used. Make it dead, to be sure.
474 locals[mir::RETURN_PLACE] = LocalValue::Dead;
475 // Now mark those locals as dead that we do not want to initialize
476 match self.tcx.describe_def(instance.def_id()) {
477 // statics and constants don't have `Storage*` statements, no need to look for them
478 Some(Def::Static(..)) | Some(Def::Const(..)) | Some(Def::AssociatedConst(..)) => {},
480 trace!("push_stack_frame: {:?}: num_bbs: {}", span, mir.basic_blocks().len());
481 for block in mir.basic_blocks() {
482 for stmt in block.statements.iter() {
483 use rustc::mir::StatementKind::{StorageDead, StorageLive};
486 StorageDead(local) => {
487 locals[local] = LocalValue::Dead;
495 // Finally, properly initialize all those that still have the dummy value
496 for (idx, local) in locals.iter_enumerated_mut() {
498 LocalValue::Live(_) => {
499 // This needs to be peoperly initialized.
500 let layout = self.layout_of_local(self.frame(), idx)?;
501 *local = LocalValue::Live(self.uninit_operand(layout)?);
503 LocalValue::Dead => {
509 self.frame_mut().locals = locals;
512 if self.stack.len() > 1 { // FIXME no check should be needed, but some instances ICE
513 info!("ENTERING({}) {}", self.cur_frame(), self.frame().instance);
516 if self.stack.len() > self.tcx.sess.const_eval_stack_frame_limit {
517 err!(StackFrameLimitReached)
523 pub(super) fn pop_stack_frame(&mut self) -> EvalResult<'tcx> {
524 if self.stack.len() > 1 { // FIXME no check should be needed, but some instances ICE
525 info!("LEAVING({}) {}", self.cur_frame(), self.frame().instance);
527 ::log_settings::settings().indentation -= 1;
528 let frame = self.stack.pop().expect(
529 "tried to pop a stack frame, but there were none",
531 M::stack_pop(self, frame.extra)?;
532 // Abort early if we do not want to clean up: We also avoid validation in that case,
533 // because this is CTFE and the final value will be thoroughly validated anyway.
534 match frame.return_to_block {
535 StackPopCleanup::Goto(_) => {},
536 StackPopCleanup::None { cleanup } => {
538 assert!(self.stack.is_empty(), "only the topmost frame should ever be leaked");
539 // Leak the locals, skip validation.
544 // Deallocate all locals that are backed by an allocation.
545 for local in frame.locals {
546 self.deallocate_local(local)?;
548 // Validate the return value. Do this after deallocating so that we catch dangling
550 if let Some(return_place) = frame.return_place {
551 if M::enforce_validity(self) {
552 // Data got changed, better make sure it matches the type!
553 // It is still possible that the return place held invalid data while
554 // the function is running, but that's okay because nobody could have
555 // accessed that same data from the "outside" to observe any broken
556 // invariant -- that is, unless a function somehow has a ptr to
557 // its return place... but the way MIR is currently generated, the
558 // return place is always a local and then this cannot happen.
559 self.validate_operand(
560 self.place_to_op(return_place)?,
567 // Uh, that shouldn't happen... the function did not intend to return
568 return err!(Unreachable);
570 // Jump to new block -- *after* validation so that the spans make more sense.
571 match frame.return_to_block {
572 StackPopCleanup::Goto(block) => {
573 self.goto_block(block)?;
575 StackPopCleanup::None { .. } => {}
578 if self.stack.len() > 1 { // FIXME should be "> 0", printing topmost frame crashes rustc...
579 info!("CONTINUING({}) {}", self.cur_frame(), self.frame().instance);
585 /// Mark a storage as live, killing the previous content and returning it.
586 /// Remember to deallocate that!
590 ) -> EvalResult<'tcx, LocalValue<M::PointerTag>> {
591 assert!(local != mir::RETURN_PLACE, "Cannot make return place live");
592 trace!("{:?} is now live", local);
594 let layout = self.layout_of_local(self.frame(), local)?;
595 let init = LocalValue::Live(self.uninit_operand(layout)?);
596 // StorageLive *always* kills the value that's currently stored
597 Ok(mem::replace(&mut self.frame_mut().locals[local], init))
600 /// Returns the old value of the local.
601 /// Remember to deallocate that!
602 pub fn storage_dead(&mut self, local: mir::Local) -> LocalValue<M::PointerTag> {
603 assert!(local != mir::RETURN_PLACE, "Cannot make return place dead");
604 trace!("{:?} is now dead", local);
606 mem::replace(&mut self.frame_mut().locals[local], LocalValue::Dead)
609 pub(super) fn deallocate_local(
611 local: LocalValue<M::PointerTag>,
612 ) -> EvalResult<'tcx> {
613 // FIXME: should we tell the user that there was a local which was never written to?
614 if let LocalValue::Live(Operand::Indirect(MemPlace { ptr, .. })) = local {
615 trace!("deallocating local");
616 let ptr = ptr.to_ptr()?;
617 self.memory.dump_alloc(ptr.alloc_id);
618 self.memory.deallocate_local(ptr)?;
623 pub fn const_eval_raw(
626 ) -> EvalResult<'tcx, MPlaceTy<'tcx, M::PointerTag>> {
627 let param_env = if self.tcx.is_static(gid.instance.def_id()).is_some() {
628 ty::ParamEnv::reveal_all()
632 // We use `const_eval_raw` here, and get an unvalidated result. That is okay:
633 // Our result will later be validated anyway, and there seems no good reason
634 // to have to fail early here. This is also more consistent with
635 // `Memory::get_static_alloc` which has to use `const_eval_raw` to avoid cycles.
636 let val = self.tcx.const_eval_raw(param_env.and(gid)).map_err(|err| {
638 ErrorHandled::Reported => EvalErrorKind::ReferencedConstant,
639 ErrorHandled::TooGeneric => EvalErrorKind::TooGeneric,
642 self.raw_const_to_mplace(val)
645 pub fn dump_place(&self, place: Place<M::PointerTag>) {
647 if !log_enabled!(::log::Level::Trace) {
651 Place::Local { frame, local } => {
652 let mut allocs = Vec::new();
653 let mut msg = format!("{:?}", local);
654 if frame != self.cur_frame() {
655 write!(msg, " ({} frames up)", self.cur_frame() - frame).unwrap();
657 write!(msg, ":").unwrap();
659 match self.stack[frame].locals[local].access() {
661 if let EvalErrorKind::DeadLocal = err.kind {
662 write!(msg, " is dead").unwrap();
664 panic!("Failed to access local: {:?}", err);
667 Ok(Operand::Indirect(mplace)) => {
668 let (ptr, align) = mplace.to_scalar_ptr_align();
670 Scalar::Ptr(ptr) => {
671 write!(msg, " by align({}) ref:", align.bytes()).unwrap();
672 allocs.push(ptr.alloc_id);
674 ptr => write!(msg, " by integral ref: {:?}", ptr).unwrap(),
677 Ok(Operand::Immediate(Immediate::Scalar(val))) => {
678 write!(msg, " {:?}", val).unwrap();
679 if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val {
680 allocs.push(ptr.alloc_id);
683 Ok(Operand::Immediate(Immediate::ScalarPair(val1, val2))) => {
684 write!(msg, " ({:?}, {:?})", val1, val2).unwrap();
685 if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val1 {
686 allocs.push(ptr.alloc_id);
688 if let ScalarMaybeUndef::Scalar(Scalar::Ptr(ptr)) = val2 {
689 allocs.push(ptr.alloc_id);
695 self.memory.dump_allocs(allocs);
697 Place::Ptr(mplace) => {
699 Scalar::Ptr(ptr) => {
700 trace!("by align({}) ref:", mplace.align.bytes());
701 self.memory.dump_alloc(ptr.alloc_id);
703 ptr => trace!(" integral by ref: {:?}", ptr),
709 pub fn generate_stacktrace(&self, explicit_span: Option<Span>) -> Vec<FrameInfo<'tcx>> {
710 let mut last_span = None;
711 let mut frames = Vec::new();
712 for &Frame { instance, span, mir, block, stmt, .. } in self.stack().iter().rev() {
713 // make sure we don't emit frames that are duplicates of the previous
714 if explicit_span == Some(span) {
715 last_span = Some(span);
718 if let Some(last) = last_span {
723 last_span = Some(span);
725 let block = &mir.basic_blocks()[block];
726 let source_info = if stmt < block.statements.len() {
727 block.statements[stmt].source_info
729 block.terminator().source_info
731 let lint_root = match mir.source_scope_local_data {
732 mir::ClearCrossCrate::Set(ref ivs) => Some(ivs[source_info.scope].lint_root),
733 mir::ClearCrossCrate::Clear => None,
735 frames.push(FrameInfo { call_site: span, instance, lint_root });
737 trace!("generate stacktrace: {:#?}, {:?}", frames, explicit_span);
742 pub fn sign_extend(&self, value: u128, ty: TyLayout<'_>) -> u128 {
743 assert!(ty.abi.is_signed());
744 sign_extend(value, ty.size)
748 pub fn truncate(&self, value: u128, ty: TyLayout<'_>) -> u128 {
749 truncate(value, ty.size)