1 //! The memory subsystem.
3 //! Generally, we use `Pointer` to denote memory addresses. However, some operations
4 //! have a "size"-like parameter, and they take `Scalar` for the address because
5 //! if the size is 0, then the pointer can also be a (properly aligned, non-NULL)
6 //! integer. It is crucial that these operations call `check_align` *before*
7 //! short-circuiting the empty case!
9 use std::collections::VecDeque;
13 use rustc::ty::{self, Instance, ParamEnv, query::TyCtxtAt};
14 use rustc::ty::layout::{Align, TargetDataLayout, Size, HasDataLayout};
15 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
17 use syntax::ast::Mutability;
20 Pointer, AllocId, Allocation, GlobalId, AllocationExtra,
21 EvalResult, Scalar, InterpError, AllocKind, PointerArithmetic,
22 Machine, AllocMap, MayLeak, ErrorHandled, CheckInAllocMsg, InboundsCheck,
25 #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash)]
26 pub enum MemoryKind<T> {
27 /// Error if deallocated except during a stack pop
29 /// Error if ever deallocated
31 /// Additional memory kinds a machine wishes to distinguish from the builtin ones
35 impl<T: MayLeak> MayLeak for MemoryKind<T> {
37 fn may_leak(self) -> bool {
39 MemoryKind::Stack => false,
40 MemoryKind::Vtable => true,
41 MemoryKind::Machine(k) => k.may_leak()
46 // `Memory` has to depend on the `Machine` because some of its operations
47 // (e.g., `get`) call a `Machine` hook.
48 pub struct Memory<'a, 'mir, 'tcx: 'a + 'mir, M: Machine<'a, 'mir, 'tcx>> {
49 /// Allocations local to this instance of the miri engine. The kind
50 /// helps ensure that the same mechanism is used for allocation and
51 /// deallocation. When an allocation is not found here, it is a
52 /// static and looked up in the `tcx` for read access. Some machines may
53 /// have to mutate this map even on a read-only access to a static (because
54 /// they do pointer provenance tracking and the allocations in `tcx` have
55 /// the wrong type), so we let the machine override this type.
56 /// Either way, if the machine allows writing to a static, doing so will
57 /// create a copy of the static allocation here.
58 alloc_map: M::MemoryMap,
60 /// To be able to compare pointers with NULL, and to check alignment for accesses
61 /// to ZSTs (where pointers may dangle), we keep track of the size even for allocations
62 /// that do not exist any more.
63 dead_alloc_map: FxHashMap<AllocId, (Size, Align)>,
65 /// Extra data added by the machine.
66 pub extra: M::MemoryExtra,
68 /// Lets us implement `HasDataLayout`, which is awfully convenient.
69 pub(super) tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
72 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> HasDataLayout
73 for Memory<'a, 'mir, 'tcx, M>
76 fn data_layout(&self) -> &TargetDataLayout {
81 // FIXME: Really we shouldn't clone memory, ever. Snapshot machinery should instead
82 // carefully copy only the reachable parts.
83 impl<'a, 'mir, 'tcx, M>
86 Memory<'a, 'mir, 'tcx, M>
88 M: Machine<'a, 'mir, 'tcx, PointerTag=(), AllocExtra=(), MemoryExtra=()>,
89 M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation)>,
91 fn clone(&self) -> Self {
93 alloc_map: self.alloc_map.clone(),
94 dead_alloc_map: self.dead_alloc_map.clone(),
101 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
102 pub fn new(tcx: TyCtxtAt<'a, 'tcx, 'tcx>) -> Self {
104 alloc_map: M::MemoryMap::default(),
105 dead_alloc_map: FxHashMap::default(),
106 extra: M::MemoryExtra::default(),
111 pub fn create_fn_alloc(&mut self, instance: Instance<'tcx>) -> Pointer {
112 Pointer::from(self.tcx.alloc_map.lock().create_fn_alloc(instance))
115 pub fn allocate_static_bytes(&mut self, bytes: &[u8]) -> Pointer {
116 Pointer::from(self.tcx.allocate_bytes(bytes))
119 pub fn allocate_with(
121 alloc: Allocation<M::PointerTag, M::AllocExtra>,
122 kind: MemoryKind<M::MemoryKinds>,
124 let id = self.tcx.alloc_map.lock().reserve();
125 self.alloc_map.insert(id, (kind, alloc));
133 kind: MemoryKind<M::MemoryKinds>,
134 ) -> Pointer<M::PointerTag> {
135 let (extra, tag) = M::new_allocation(size, &self.extra, kind);
136 Pointer::from(self.allocate_with(Allocation::undef(size, align, extra), kind)).with_tag(tag)
141 ptr: Pointer<M::PointerTag>,
146 kind: MemoryKind<M::MemoryKinds>,
147 ) -> EvalResult<'tcx, Pointer<M::PointerTag>> {
148 if ptr.offset.bytes() != 0 {
149 return err!(ReallocateNonBasePtr);
152 // For simplicities' sake, we implement reallocate as "alloc, copy, dealloc".
153 // This happens so rarely, the perf advantage is outweighed by the maintenance cost.
154 let new_ptr = self.allocate(new_size, new_align, kind);
160 old_size.min(new_size),
161 /*nonoverlapping*/ true,
163 self.deallocate(ptr, Some((old_size, old_align)), kind)?;
168 /// Deallocate a local, or do nothing if that local has been made into a static
169 pub fn deallocate_local(&mut self, ptr: Pointer<M::PointerTag>) -> EvalResult<'tcx> {
170 // The allocation might be already removed by static interning.
171 // This can only really happen in the CTFE instance, not in miri.
172 if self.alloc_map.contains_key(&ptr.alloc_id) {
173 self.deallocate(ptr, None, MemoryKind::Stack)
181 ptr: Pointer<M::PointerTag>,
182 size_and_align: Option<(Size, Align)>,
183 kind: MemoryKind<M::MemoryKinds>,
184 ) -> EvalResult<'tcx> {
185 trace!("deallocating: {}", ptr.alloc_id);
187 if ptr.offset.bytes() != 0 {
188 return err!(DeallocateNonBasePtr);
191 let (alloc_kind, mut alloc) = match self.alloc_map.remove(&ptr.alloc_id) {
192 Some(alloc) => alloc,
194 // Deallocating static memory -- always an error
195 return match self.tcx.alloc_map.lock().get(ptr.alloc_id) {
196 Some(AllocKind::Function(..)) => err!(DeallocatedWrongMemoryKind(
197 "function".to_string(),
198 format!("{:?}", kind),
200 Some(AllocKind::Static(..)) |
201 Some(AllocKind::Memory(..)) => err!(DeallocatedWrongMemoryKind(
202 "static".to_string(),
203 format!("{:?}", kind),
205 None => err!(DoubleFree)
210 if alloc_kind != kind {
211 return err!(DeallocatedWrongMemoryKind(
212 format!("{:?}", alloc_kind),
213 format!("{:?}", kind),
216 if let Some((size, align)) = size_and_align {
217 if size.bytes() != alloc.bytes.len() as u64 || align != alloc.align {
218 let bytes = Size::from_bytes(alloc.bytes.len() as u64);
219 return err!(IncorrectAllocationInformation(size,
226 // Let the machine take some extra action
227 let size = Size::from_bytes(alloc.bytes.len() as u64);
228 AllocationExtra::memory_deallocated(&mut alloc, ptr, size)?;
230 // Don't forget to remember size and align of this now-dead allocation
231 let old = self.dead_alloc_map.insert(
233 (Size::from_bytes(alloc.bytes.len() as u64), alloc.align)
236 bug!("Nothing can be deallocated twice");
242 /// Checks that the pointer is aligned AND non-NULL. This supports ZSTs in two ways:
243 /// You can pass a scalar, and a `Pointer` does not have to actually still be allocated.
246 ptr: Scalar<M::PointerTag>,
247 required_align: Align
248 ) -> EvalResult<'tcx> {
249 // Check non-NULL/Undef, extract offset
250 let (offset, alloc_align) = match ptr.to_bits_or_ptr(self.pointer_size(), self) {
252 // check this is not NULL -- which we can ensure only if this is in-bounds
253 // of some (potentially dead) allocation.
254 let align = self.check_bounds_ptr(ptr, InboundsCheck::MaybeDead,
255 CheckInAllocMsg::NullPointerTest)?;
256 (ptr.offset.bytes(), align)
259 // check this is not NULL
261 return err!(InvalidNullPointerUsage);
263 // the "base address" is 0 and hence always aligned
264 (data as u64, required_align)
268 if alloc_align.bytes() < required_align.bytes() {
269 return err!(AlignmentCheckFailed {
271 required: required_align,
274 if offset % required_align.bytes() == 0 {
277 let has = offset % required_align.bytes();
278 err!(AlignmentCheckFailed {
279 has: Align::from_bytes(has).unwrap(),
280 required: required_align,
285 /// Checks if the pointer is "in-bounds". Notice that a pointer pointing at the end
286 /// of an allocation (i.e., at the first *inaccessible* location) *is* considered
287 /// in-bounds! This follows C's/LLVM's rules.
288 /// If you want to check bounds before doing a memory access, better first obtain
289 /// an `Allocation` and call `check_bounds`.
290 pub fn check_bounds_ptr(
292 ptr: Pointer<M::PointerTag>,
293 liveness: InboundsCheck,
294 msg: CheckInAllocMsg,
295 ) -> EvalResult<'tcx, Align> {
296 let (allocation_size, align) = self.get_size_and_align(ptr.alloc_id, liveness)?;
297 ptr.check_in_alloc(allocation_size, msg)?;
302 /// Allocation accessors
303 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
304 /// Helper function to obtain the global (tcx) allocation for a static.
305 /// This attempts to return a reference to an existing allocation if
306 /// one can be found in `tcx`. That, however, is only possible if `tcx` and
307 /// this machine use the same pointer tag, so it is indirected through
308 /// `M::static_with_default_tag`.
311 tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
312 memory_extra: &M::MemoryExtra,
313 ) -> EvalResult<'tcx, Cow<'tcx, Allocation<M::PointerTag, M::AllocExtra>>> {
314 let alloc = tcx.alloc_map.lock().get(id);
315 let def_id = match alloc {
316 Some(AllocKind::Memory(mem)) => {
317 // We got tcx memory. Let the machine figure out whether and how to
318 // turn that into memory with the right pointer tag.
319 return Ok(M::adjust_static_allocation(mem, memory_extra))
321 Some(AllocKind::Function(..)) => {
322 return err!(DerefFunctionPointer)
324 Some(AllocKind::Static(did)) => {
328 return err!(DanglingPointerDeref),
330 // We got a "lazy" static that has not been computed yet, do some work
331 trace!("static_alloc: Need to compute {:?}", def_id);
332 if tcx.is_foreign_item(def_id) {
333 return M::find_foreign_static(def_id, tcx, memory_extra);
335 let instance = Instance::mono(tcx.tcx, def_id);
340 // use the raw query here to break validation cycles. Later uses of the static will call the
342 tcx.const_eval_raw(ty::ParamEnv::reveal_all().and(gid)).map_err(|err| {
343 // no need to report anything, the const_eval call takes care of that for statics
344 assert!(tcx.is_static(def_id));
346 ErrorHandled::Reported => InterpError::ReferencedConstant.into(),
347 ErrorHandled::TooGeneric => InterpError::TooGeneric.into(),
350 let allocation = tcx.alloc_map.lock().unwrap_memory(raw_const.alloc_id);
351 // We got tcx memory. Let the machine figure out whether and how to
352 // turn that into memory with the right pointer tag.
353 M::adjust_static_allocation(allocation, memory_extra)
357 pub fn get(&self, id: AllocId) -> EvalResult<'tcx, &Allocation<M::PointerTag, M::AllocExtra>> {
358 // The error type of the inner closure here is somewhat funny. We have two
359 // ways of "erroring": An actual error, or because we got a reference from
360 // `get_static_alloc` that we can actually use directly without inserting anything anywhere.
361 // So the error type is `EvalResult<'tcx, &Allocation<M::PointerTag>>`.
362 let a = self.alloc_map.get_or(id, || {
363 let alloc = Self::get_static_alloc(id, self.tcx, &self.extra).map_err(Err)?;
365 Cow::Borrowed(alloc) => {
366 // We got a ref, cheaply return that as an "error" so that the
367 // map does not get mutated.
370 Cow::Owned(alloc) => {
371 // Need to put it into the map and return a ref to that
372 let kind = M::STATIC_KIND.expect(
373 "I got an owned allocation that I have to copy but the machine does \
374 not expect that to happen"
376 Ok((MemoryKind::Machine(kind), alloc))
380 // Now unpack that funny error type
390 ) -> EvalResult<'tcx, &mut Allocation<M::PointerTag, M::AllocExtra>> {
392 let memory_extra = &self.extra;
393 let a = self.alloc_map.get_mut_or(id, || {
394 // Need to make a copy, even if `get_static_alloc` is able
395 // to give us a cheap reference.
396 let alloc = Self::get_static_alloc(id, tcx, memory_extra)?;
397 if alloc.mutability == Mutability::Immutable {
398 return err!(ModifiedConstantMemory);
400 match M::STATIC_KIND {
401 Some(kind) => Ok((MemoryKind::Machine(kind), alloc.into_owned())),
402 None => err!(ModifiedStatic),
405 // Unpack the error type manually because type inference doesn't
406 // work otherwise (and we cannot help it because `impl Trait`)
411 if a.mutability == Mutability::Immutable {
412 return err!(ModifiedConstantMemory);
419 /// Obtain the size and alignment of an allocation, even if that allocation has been deallocated
421 /// If `liveness` is `InboundsCheck::MaybeDead`, this function always returns `Ok`
422 pub fn get_size_and_align(
425 liveness: InboundsCheck,
426 ) -> EvalResult<'static, (Size, Align)> {
427 if let Ok(alloc) = self.get(id) {
428 return Ok((Size::from_bytes(alloc.bytes.len() as u64), alloc.align));
430 // Could also be a fn ptr or extern static
431 match self.tcx.alloc_map.lock().get(id) {
432 Some(AllocKind::Function(..)) => Ok((Size::ZERO, Align::from_bytes(1).unwrap())),
433 Some(AllocKind::Static(did)) => {
434 // The only way `get` couldn't have worked here is if this is an extern static
435 assert!(self.tcx.is_foreign_item(did));
436 // Use size and align of the type
437 let ty = self.tcx.type_of(did);
438 let layout = self.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap();
439 Ok((layout.size, layout.align.abi))
441 _ => match liveness {
442 InboundsCheck::MaybeDead => {
443 // Must be a deallocated pointer
444 Ok(*self.dead_alloc_map.get(&id).expect(
445 "allocation missing in dead_alloc_map"
448 InboundsCheck::Live => err!(DanglingPointerDeref),
453 pub fn get_fn(&self, ptr: Pointer<M::PointerTag>) -> EvalResult<'tcx, Instance<'tcx>> {
454 if ptr.offset.bytes() != 0 {
455 return err!(InvalidFunctionPointer);
457 trace!("reading fn ptr: {}", ptr.alloc_id);
458 match self.tcx.alloc_map.lock().get(ptr.alloc_id) {
459 Some(AllocKind::Function(instance)) => Ok(instance),
460 _ => Err(InterpError::ExecuteMemory.into()),
464 pub fn mark_immutable(&mut self, id: AllocId) -> EvalResult<'tcx> {
465 self.get_mut(id)?.mutability = Mutability::Immutable;
469 /// For debugging, print an allocation and all allocations it points to, recursively.
470 pub fn dump_alloc(&self, id: AllocId) {
471 self.dump_allocs(vec![id]);
474 fn dump_alloc_helper<Tag, Extra>(
476 allocs_seen: &mut FxHashSet<AllocId>,
477 allocs_to_print: &mut VecDeque<AllocId>,
479 alloc: &Allocation<Tag, Extra>,
484 let prefix_len = msg.len();
485 let mut relocations = vec![];
487 for i in 0..(alloc.bytes.len() as u64) {
488 let i = Size::from_bytes(i);
489 if let Some(&(_, target_id)) = alloc.relocations.get(&i) {
490 if allocs_seen.insert(target_id) {
491 allocs_to_print.push_back(target_id);
493 relocations.push((i, target_id));
495 if alloc.undef_mask.is_range_defined(i, i + Size::from_bytes(1)).is_ok() {
496 // this `as usize` is fine, since `i` came from a `usize`
497 write!(msg, "{:02x} ", alloc.bytes[i.bytes() as usize]).unwrap();
504 "{}({} bytes, alignment {}){}",
511 if !relocations.is_empty() {
513 write!(msg, "{:1$}", "", prefix_len).unwrap(); // Print spaces.
514 let mut pos = Size::ZERO;
515 let relocation_width = (self.pointer_size().bytes() - 1) * 3;
516 for (i, target_id) in relocations {
517 // this `as usize` is fine, since we can't print more chars than `usize::MAX`
518 write!(msg, "{:1$}", "", ((i - pos) * 3).bytes() as usize).unwrap();
519 let target = format!("({})", target_id);
520 // this `as usize` is fine, since we can't print more chars than `usize::MAX`
521 write!(msg, "└{0:─^1$}┘ ", target, relocation_width as usize).unwrap();
522 pos = i + self.pointer_size();
528 /// For debugging, print a list of allocations and all allocations they point to, recursively.
529 pub fn dump_allocs(&self, mut allocs: Vec<AllocId>) {
530 if !log_enabled!(::log::Level::Trace) {
535 let mut allocs_to_print = VecDeque::from(allocs);
536 let mut allocs_seen = FxHashSet::default();
538 while let Some(id) = allocs_to_print.pop_front() {
539 let msg = format!("Alloc {:<5} ", format!("{}:", id));
542 match self.alloc_map.get_or(id, || Err(())) {
543 Ok((kind, alloc)) => {
544 let extra = match kind {
545 MemoryKind::Stack => " (stack)".to_owned(),
546 MemoryKind::Vtable => " (vtable)".to_owned(),
547 MemoryKind::Machine(m) => format!(" ({:?})", m),
549 self.dump_alloc_helper(
550 &mut allocs_seen, &mut allocs_to_print,
556 match self.tcx.alloc_map.lock().get(id) {
557 Some(AllocKind::Memory(alloc)) => {
558 self.dump_alloc_helper(
559 &mut allocs_seen, &mut allocs_to_print,
560 msg, alloc, " (immutable)".to_owned()
563 Some(AllocKind::Function(func)) => {
564 trace!("{} {}", msg, func);
566 Some(AllocKind::Static(did)) => {
567 trace!("{} {:?}", msg, did);
570 trace!("{} (deallocated)", msg);
579 pub fn leak_report(&self) -> usize {
580 trace!("### LEAK REPORT ###");
581 let leaks: Vec<_> = self.alloc_map.filter_map_collect(|&id, &(kind, _)| {
582 if kind.may_leak() { None } else { Some(id) }
585 self.dump_allocs(leaks);
589 /// This is used by [priroda](https://github.com/oli-obk/priroda)
590 pub fn alloc_map(&self) -> &M::MemoryMap {
596 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
599 ptr: Scalar<M::PointerTag>,
601 ) -> EvalResult<'tcx, &[u8]> {
602 if size.bytes() == 0 {
605 let ptr = ptr.to_ptr()?;
606 self.get(ptr.alloc_id)?.get_bytes(self, ptr, size)
611 /// Interning (for CTFE)
612 impl<'a, 'mir, 'tcx, M> Memory<'a, 'mir, 'tcx, M>
614 M: Machine<'a, 'mir, 'tcx, PointerTag=(), AllocExtra=(), MemoryExtra=()>,
615 // FIXME: Working around https://github.com/rust-lang/rust/issues/24159
616 M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation)>,
618 /// mark an allocation as static and initialized, either mutable or not
619 pub fn intern_static(
622 mutability: Mutability,
623 ) -> EvalResult<'tcx> {
625 "mark_static_initialized {:?}, mutability: {:?}",
630 let (kind, mut alloc) = self.alloc_map.remove(&alloc_id).unwrap();
632 MemoryKind::Machine(_) => bug!("Static cannot refer to machine memory"),
633 MemoryKind::Stack | MemoryKind::Vtable => {},
635 // ensure llvm knows not to put this into immutable memory
636 alloc.mutability = mutability;
637 let alloc = self.tcx.intern_const_alloc(alloc);
638 self.tcx.alloc_map.lock().set_alloc_id_memory(alloc_id, alloc);
639 // recurse into inner allocations
640 for &(_, alloc) in alloc.relocations.values() {
641 // FIXME: Reusing the mutability here is likely incorrect. It is originally
642 // determined via `is_freeze`, and data is considered frozen if there is no
643 // `UnsafeCell` *immediately* in that data -- however, this search stops
644 // at references. So whenever we follow a reference, we should likely
645 // assume immutability -- and we should make sure that the compiler
646 // does not permit code that would break this!
647 if self.alloc_map.contains_key(&alloc) {
648 // Not yet interned, so proceed recursively
649 self.intern_static(alloc, mutability)?;
650 } else if self.dead_alloc_map.contains_key(&alloc) {
652 return err!(ValidationFailure(
653 "encountered dangling pointer in final constant".into(),
661 /// Reading and writing.
662 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
665 src: Scalar<M::PointerTag>,
667 dest: Scalar<M::PointerTag>,
670 nonoverlapping: bool,
671 ) -> EvalResult<'tcx> {
672 self.copy_repeatedly(src, src_align, dest, dest_align, size, 1, nonoverlapping)
675 pub fn copy_repeatedly(
677 src: Scalar<M::PointerTag>,
679 dest: Scalar<M::PointerTag>,
683 nonoverlapping: bool,
684 ) -> EvalResult<'tcx> {
685 self.check_align(src, src_align)?;
686 self.check_align(dest, dest_align)?;
687 if size.bytes() == 0 {
688 // Nothing to do for ZST, other than checking alignment and
689 // non-NULLness which already happened.
692 let src = src.to_ptr()?;
693 let dest = dest.to_ptr()?;
695 // first copy the relocations to a temporary buffer, because
696 // `get_bytes_mut` will clear the relocations, which is correct,
697 // since we don't want to keep any relocations at the target.
698 // (`get_bytes_with_undef_and_ptr` below checks that there are no
699 // relocations overlapping the edges; those would not be handled correctly).
701 let relocations = self.get(src.alloc_id)?.relocations(self, src, size);
702 if relocations.is_empty() {
703 // nothing to copy, ignore even the `length` loop
706 let mut new_relocations = Vec::with_capacity(relocations.len() * (length as usize));
708 new_relocations.extend(
711 .map(|&(offset, reloc)| {
712 // compute offset for current repetition
713 let dest_offset = dest.offset + (i * size);
715 // shift offsets from source allocation to destination allocation
716 offset + dest_offset - src.offset,
727 let tcx = self.tcx.tcx;
729 // This checks relocation edges on the src.
730 let src_bytes = self.get(src.alloc_id)?
731 .get_bytes_with_undef_and_ptr(&tcx, src, size)?
733 let dest_bytes = self.get_mut(dest.alloc_id)?
734 .get_bytes_mut(&tcx, dest, size * length)?
737 // SAFE: The above indexing would have panicked if there weren't at least `size` bytes
738 // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
739 // `dest` could possibly overlap.
740 // The pointers above remain valid even if the `HashMap` table is moved around because they
741 // point into the `Vec` storing the bytes.
743 assert_eq!(size.bytes() as usize as u64, size.bytes());
744 if src.alloc_id == dest.alloc_id {
746 if (src.offset <= dest.offset && src.offset + size > dest.offset) ||
747 (dest.offset <= src.offset && dest.offset + size > src.offset)
749 return err!(Intrinsic(
750 "copy_nonoverlapping called on overlapping ranges".to_string(),
757 dest_bytes.offset((size.bytes() * i) as isize),
758 size.bytes() as usize);
762 ptr::copy_nonoverlapping(src_bytes,
763 dest_bytes.offset((size.bytes() * i) as isize),
764 size.bytes() as usize);
769 // copy definedness to the destination
770 self.copy_undef_mask(src, dest, size, length)?;
771 // copy the relocations to the destination
772 self.get_mut(dest.alloc_id)?.relocations.insert_presorted(relocations);
779 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
780 // FIXME: Add a fast version for the common, nonoverlapping case
783 src: Pointer<M::PointerTag>,
784 dest: Pointer<M::PointerTag>,
787 ) -> EvalResult<'tcx> {
788 // The bits have to be saved locally before writing to dest in case src and dest overlap.
789 assert_eq!(size.bytes() as usize as u64, size.bytes());
791 let undef_mask = &self.get(src.alloc_id)?.undef_mask;
793 // Since we are copying `size` bytes from `src` to `dest + i * size` (`for i in 0..repeat`),
794 // a naive undef mask copying algorithm would repeatedly have to read the undef mask from
795 // the source and write it to the destination. Even if we optimized the memory accesses,
796 // we'd be doing all of this `repeat` times.
797 // Therefor we precompute a compressed version of the undef mask of the source value and
798 // then write it back `repeat` times without computing any more information from the source.
800 // a precomputed cache for ranges of defined/undefined bits
801 // 0000010010001110 will become
802 // [5, 1, 2, 1, 3, 3, 1]
803 // where each element toggles the state
804 let mut ranges = smallvec::SmallVec::<[u64; 1]>::new();
805 let first = undef_mask.get(src.offset);
808 for i in 1..size.bytes() {
809 // FIXME: optimize to bitshift the current undef block's bits and read the top bit
810 if undef_mask.get(src.offset + Size::from_bytes(i)) == cur {
813 ranges.push(cur_len);
819 // now fill in all the data
820 let dest_allocation = self.get_mut(dest.alloc_id)?;
821 // an optimization where we can just overwrite an entire range of definedness bits if
822 // they are going to be uniformly `1` or `0`.
823 if ranges.is_empty() {
824 dest_allocation.undef_mask.set_range_inbounds(
826 dest.offset + size * repeat,
832 // remember to fill in the trailing bits
833 ranges.push(cur_len);
835 for mut j in 0..repeat {
837 j += dest.offset.bytes();
839 for range in &ranges {
842 dest_allocation.undef_mask.set_range_inbounds(
843 Size::from_bytes(old_j),