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 pub use rustc::mir::interpret::{truncate, write_target_uint, read_target_uint};
16 use rustc_data_structures::fx::{FxHashSet, FxHashMap};
18 use syntax::ast::Mutability;
21 Pointer, AllocId, Allocation, GlobalId, AllocationExtra,
22 EvalResult, Scalar, InterpError, AllocKind, PointerArithmetic,
23 Machine, AllocMap, MayLeak, ErrorHandled, CheckInAllocMsg, InboundsCheck,
26 #[derive(Debug, PartialEq, Eq, Copy, Clone, Hash)]
27 pub enum MemoryKind<T> {
28 /// Error if deallocated except during a stack pop
30 /// Error if ever deallocated
32 /// Additional memory kinds a machine wishes to distinguish from the builtin ones
36 impl<T: MayLeak> MayLeak for MemoryKind<T> {
38 fn may_leak(self) -> bool {
40 MemoryKind::Stack => false,
41 MemoryKind::Vtable => true,
42 MemoryKind::Machine(k) => k.may_leak()
47 // `Memory` has to depend on the `Machine` because some of its operations
48 // (e.g., `get`) call a `Machine` hook.
49 pub struct Memory<'a, 'mir, 'tcx: 'a + 'mir, M: Machine<'a, 'mir, 'tcx>> {
50 /// Allocations local to this instance of the miri engine. The kind
51 /// helps ensure that the same mechanism is used for allocation and
52 /// deallocation. When an allocation is not found here, it is a
53 /// static and looked up in the `tcx` for read access. Some machines may
54 /// have to mutate this map even on a read-only access to a static (because
55 /// they do pointer provenance tracking and the allocations in `tcx` have
56 /// the wrong type), so we let the machine override this type.
57 /// Either way, if the machine allows writing to a static, doing so will
58 /// create a copy of the static allocation here.
59 alloc_map: M::MemoryMap,
61 /// To be able to compare pointers with NULL, and to check alignment for accesses
62 /// to ZSTs (where pointers may dangle), we keep track of the size even for allocations
63 /// that do not exist any more.
64 dead_alloc_map: FxHashMap<AllocId, (Size, Align)>,
66 /// Extra data added by the machine.
67 pub extra: M::MemoryExtra,
69 /// Lets us implement `HasDataLayout`, which is awfully convenient.
70 pub(super) tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
73 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> HasDataLayout
74 for Memory<'a, 'mir, 'tcx, M>
77 fn data_layout(&self) -> &TargetDataLayout {
82 // FIXME: Really we shouldn't clone memory, ever. Snapshot machinery should instead
83 // carefully copy only the reachable parts.
84 impl<'a, 'mir, 'tcx, M>
87 Memory<'a, 'mir, 'tcx, M>
89 M: Machine<'a, 'mir, 'tcx, PointerTag=(), AllocExtra=(), MemoryExtra=()>,
90 M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation)>,
92 fn clone(&self) -> Self {
94 alloc_map: self.alloc_map.clone(),
95 dead_alloc_map: self.dead_alloc_map.clone(),
102 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
103 pub fn new(tcx: TyCtxtAt<'a, 'tcx, 'tcx>) -> Self {
105 alloc_map: M::MemoryMap::default(),
106 dead_alloc_map: FxHashMap::default(),
107 extra: M::MemoryExtra::default(),
112 pub fn create_fn_alloc(&mut self, instance: Instance<'tcx>) -> Pointer {
113 Pointer::from(self.tcx.alloc_map.lock().create_fn_alloc(instance))
116 pub fn allocate_static_bytes(&mut self, bytes: &[u8]) -> Pointer {
117 Pointer::from(self.tcx.allocate_bytes(bytes))
120 pub fn allocate_with(
122 alloc: Allocation<M::PointerTag, M::AllocExtra>,
123 kind: MemoryKind<M::MemoryKinds>,
125 let id = self.tcx.alloc_map.lock().reserve();
126 self.alloc_map.insert(id, (kind, alloc));
134 kind: MemoryKind<M::MemoryKinds>,
135 ) -> Pointer<M::PointerTag> {
136 let (extra, tag) = M::new_allocation(size, &self.extra, kind);
137 Pointer::from(self.allocate_with(Allocation::undef(size, align, extra), kind)).with_tag(tag)
142 ptr: Pointer<M::PointerTag>,
147 kind: MemoryKind<M::MemoryKinds>,
148 ) -> EvalResult<'tcx, Pointer<M::PointerTag>> {
149 if ptr.offset.bytes() != 0 {
150 return err!(ReallocateNonBasePtr);
153 // For simplicities' sake, we implement reallocate as "alloc, copy, dealloc".
154 // This happens so rarely, the perf advantage is outweighed by the maintenance cost.
155 let new_ptr = self.allocate(new_size, new_align, kind);
161 old_size.min(new_size),
162 /*nonoverlapping*/ true,
164 self.deallocate(ptr, Some((old_size, old_align)), kind)?;
169 /// Deallocate a local, or do nothing if that local has been made into a static
170 pub fn deallocate_local(&mut self, ptr: Pointer<M::PointerTag>) -> EvalResult<'tcx> {
171 // The allocation might be already removed by static interning.
172 // This can only really happen in the CTFE instance, not in miri.
173 if self.alloc_map.contains_key(&ptr.alloc_id) {
174 self.deallocate(ptr, None, MemoryKind::Stack)
182 ptr: Pointer<M::PointerTag>,
183 size_and_align: Option<(Size, Align)>,
184 kind: MemoryKind<M::MemoryKinds>,
185 ) -> EvalResult<'tcx> {
186 trace!("deallocating: {}", ptr.alloc_id);
188 if ptr.offset.bytes() != 0 {
189 return err!(DeallocateNonBasePtr);
192 let (alloc_kind, mut alloc) = match self.alloc_map.remove(&ptr.alloc_id) {
193 Some(alloc) => alloc,
195 // Deallocating static memory -- always an error
196 return match self.tcx.alloc_map.lock().get(ptr.alloc_id) {
197 Some(AllocKind::Function(..)) => err!(DeallocatedWrongMemoryKind(
198 "function".to_string(),
199 format!("{:?}", kind),
201 Some(AllocKind::Static(..)) |
202 Some(AllocKind::Memory(..)) => err!(DeallocatedWrongMemoryKind(
203 "static".to_string(),
204 format!("{:?}", kind),
206 None => err!(DoubleFree)
211 if alloc_kind != kind {
212 return err!(DeallocatedWrongMemoryKind(
213 format!("{:?}", alloc_kind),
214 format!("{:?}", kind),
217 if let Some((size, align)) = size_and_align {
218 if size.bytes() != alloc.bytes.len() as u64 || align != alloc.align {
219 let bytes = Size::from_bytes(alloc.bytes.len() as u64);
220 return err!(IncorrectAllocationInformation(size,
227 // Let the machine take some extra action
228 let size = Size::from_bytes(alloc.bytes.len() as u64);
229 AllocationExtra::memory_deallocated(&mut alloc, ptr, size)?;
231 // Don't forget to remember size and align of this now-dead allocation
232 let old = self.dead_alloc_map.insert(
234 (Size::from_bytes(alloc.bytes.len() as u64), alloc.align)
237 bug!("Nothing can be deallocated twice");
243 /// Checks that the pointer is aligned AND non-NULL. This supports ZSTs in two ways:
244 /// You can pass a scalar, and a `Pointer` does not have to actually still be allocated.
247 ptr: Scalar<M::PointerTag>,
248 required_align: Align
249 ) -> EvalResult<'tcx> {
250 // Check non-NULL/Undef, extract offset
251 let (offset, alloc_align) = match ptr {
252 Scalar::Ptr(ptr) => {
253 // check this is not NULL -- which we can ensure only if this is in-bounds
254 // of some (potentially dead) allocation.
255 let align = self.check_bounds_ptr(ptr, InboundsCheck::MaybeDead,
256 CheckInAllocMsg::NullPointerTest)?;
257 (ptr.offset.bytes(), align)
259 Scalar::Bits { bits, size } => {
260 assert_eq!(size as u64, self.pointer_size().bytes());
261 assert!(bits < (1u128 << self.pointer_size().bits()));
262 // check this is not NULL
264 return err!(InvalidNullPointerUsage);
266 // the "base address" is 0 and hence always aligned
267 (bits as u64, required_align)
271 if alloc_align.bytes() < required_align.bytes() {
272 return err!(AlignmentCheckFailed {
274 required: required_align,
277 if offset % required_align.bytes() == 0 {
280 let has = offset % required_align.bytes();
281 err!(AlignmentCheckFailed {
282 has: Align::from_bytes(has).unwrap(),
283 required: required_align,
288 /// Checks if the pointer is "in-bounds". Notice that a pointer pointing at the end
289 /// of an allocation (i.e., at the first *inaccessible* location) *is* considered
290 /// in-bounds! This follows C's/LLVM's rules.
291 /// If you want to check bounds before doing a memory access, better first obtain
292 /// an `Allocation` and call `check_bounds`.
293 pub fn check_bounds_ptr(
295 ptr: Pointer<M::PointerTag>,
296 liveness: InboundsCheck,
297 msg: CheckInAllocMsg,
298 ) -> EvalResult<'tcx, Align> {
299 let (allocation_size, align) = self.get_size_and_align(ptr.alloc_id, liveness)?;
300 ptr.check_in_alloc(allocation_size, msg)?;
305 /// Allocation accessors
306 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
307 /// Helper function to obtain the global (tcx) allocation for a static.
308 /// This attempts to return a reference to an existing allocation if
309 /// one can be found in `tcx`. That, however, is only possible if `tcx` and
310 /// this machine use the same pointer tag, so it is indirected through
311 /// `M::static_with_default_tag`.
314 tcx: TyCtxtAt<'a, 'tcx, 'tcx>,
315 memory_extra: &M::MemoryExtra,
316 ) -> EvalResult<'tcx, Cow<'tcx, Allocation<M::PointerTag, M::AllocExtra>>> {
317 let alloc = tcx.alloc_map.lock().get(id);
318 let def_id = match alloc {
319 Some(AllocKind::Memory(mem)) => {
320 // We got tcx memory. Let the machine figure out whether and how to
321 // turn that into memory with the right pointer tag.
322 return Ok(M::adjust_static_allocation(mem, memory_extra))
324 Some(AllocKind::Function(..)) => {
325 return err!(DerefFunctionPointer)
327 Some(AllocKind::Static(did)) => {
331 return err!(DanglingPointerDeref),
333 // We got a "lazy" static that has not been computed yet, do some work
334 trace!("static_alloc: Need to compute {:?}", def_id);
335 if tcx.is_foreign_item(def_id) {
336 return M::find_foreign_static(def_id, tcx, memory_extra);
338 let instance = Instance::mono(tcx.tcx, def_id);
343 // use the raw query here to break validation cycles. Later uses of the static will call the
345 tcx.const_eval_raw(ty::ParamEnv::reveal_all().and(gid)).map_err(|err| {
346 // no need to report anything, the const_eval call takes care of that for statics
347 assert!(tcx.is_static(def_id));
349 ErrorHandled::Reported => InterpError::ReferencedConstant.into(),
350 ErrorHandled::TooGeneric => InterpError::TooGeneric.into(),
353 let allocation = tcx.alloc_map.lock().unwrap_memory(raw_const.alloc_id);
354 // We got tcx memory. Let the machine figure out whether and how to
355 // turn that into memory with the right pointer tag.
356 M::adjust_static_allocation(allocation, memory_extra)
360 pub fn get(&self, id: AllocId) -> EvalResult<'tcx, &Allocation<M::PointerTag, M::AllocExtra>> {
361 // The error type of the inner closure here is somewhat funny. We have two
362 // ways of "erroring": An actual error, or because we got a reference from
363 // `get_static_alloc` that we can actually use directly without inserting anything anywhere.
364 // So the error type is `EvalResult<'tcx, &Allocation<M::PointerTag>>`.
365 let a = self.alloc_map.get_or(id, || {
366 let alloc = Self::get_static_alloc(id, self.tcx, &self.extra).map_err(Err)?;
368 Cow::Borrowed(alloc) => {
369 // We got a ref, cheaply return that as an "error" so that the
370 // map does not get mutated.
373 Cow::Owned(alloc) => {
374 // Need to put it into the map and return a ref to that
375 let kind = M::STATIC_KIND.expect(
376 "I got an owned allocation that I have to copy but the machine does \
377 not expect that to happen"
379 Ok((MemoryKind::Machine(kind), alloc))
383 // Now unpack that funny error type
393 ) -> EvalResult<'tcx, &mut Allocation<M::PointerTag, M::AllocExtra>> {
395 let memory_extra = &self.extra;
396 let a = self.alloc_map.get_mut_or(id, || {
397 // Need to make a copy, even if `get_static_alloc` is able
398 // to give us a cheap reference.
399 let alloc = Self::get_static_alloc(id, tcx, memory_extra)?;
400 if alloc.mutability == Mutability::Immutable {
401 return err!(ModifiedConstantMemory);
403 match M::STATIC_KIND {
404 Some(kind) => Ok((MemoryKind::Machine(kind), alloc.into_owned())),
405 None => err!(ModifiedStatic),
408 // Unpack the error type manually because type inference doesn't
409 // work otherwise (and we cannot help it because `impl Trait`)
414 if a.mutability == Mutability::Immutable {
415 return err!(ModifiedConstantMemory);
422 /// Obtain the size and alignment of an allocation, even if that allocation has been deallocated
424 /// If `liveness` is `InboundsCheck::MaybeDead`, this function always returns `Ok`
425 pub fn get_size_and_align(
428 liveness: InboundsCheck,
429 ) -> EvalResult<'static, (Size, Align)> {
430 if let Ok(alloc) = self.get(id) {
431 return Ok((Size::from_bytes(alloc.bytes.len() as u64), alloc.align));
433 // Could also be a fn ptr or extern static
434 match self.tcx.alloc_map.lock().get(id) {
435 Some(AllocKind::Function(..)) => Ok((Size::ZERO, Align::from_bytes(1).unwrap())),
436 Some(AllocKind::Static(did)) => {
437 // The only way `get` couldn't have worked here is if this is an extern static
438 assert!(self.tcx.is_foreign_item(did));
439 // Use size and align of the type
440 let ty = self.tcx.type_of(did);
441 let layout = self.tcx.layout_of(ParamEnv::empty().and(ty)).unwrap();
442 Ok((layout.size, layout.align.abi))
444 _ => match liveness {
445 InboundsCheck::MaybeDead => {
446 // Must be a deallocated pointer
447 Ok(*self.dead_alloc_map.get(&id).expect(
448 "allocation missing in dead_alloc_map"
451 InboundsCheck::Live => err!(DanglingPointerDeref),
456 pub fn get_fn(&self, ptr: Pointer<M::PointerTag>) -> EvalResult<'tcx, Instance<'tcx>> {
457 if ptr.offset.bytes() != 0 {
458 return err!(InvalidFunctionPointer);
460 trace!("reading fn ptr: {}", ptr.alloc_id);
461 match self.tcx.alloc_map.lock().get(ptr.alloc_id) {
462 Some(AllocKind::Function(instance)) => Ok(instance),
463 _ => Err(InterpError::ExecuteMemory.into()),
467 pub fn mark_immutable(&mut self, id: AllocId) -> EvalResult<'tcx> {
468 self.get_mut(id)?.mutability = Mutability::Immutable;
472 /// For debugging, print an allocation and all allocations it points to, recursively.
473 pub fn dump_alloc(&self, id: AllocId) {
474 self.dump_allocs(vec![id]);
477 fn dump_alloc_helper<Tag, Extra>(
479 allocs_seen: &mut FxHashSet<AllocId>,
480 allocs_to_print: &mut VecDeque<AllocId>,
482 alloc: &Allocation<Tag, Extra>,
487 let prefix_len = msg.len();
488 let mut relocations = vec![];
490 for i in 0..(alloc.bytes.len() as u64) {
491 let i = Size::from_bytes(i);
492 if let Some(&(_, target_id)) = alloc.relocations.get(&i) {
493 if allocs_seen.insert(target_id) {
494 allocs_to_print.push_back(target_id);
496 relocations.push((i, target_id));
498 if alloc.undef_mask.is_range_defined(i, i + Size::from_bytes(1)).is_ok() {
499 // this `as usize` is fine, since `i` came from a `usize`
500 write!(msg, "{:02x} ", alloc.bytes[i.bytes() as usize]).unwrap();
507 "{}({} bytes, alignment {}){}",
514 if !relocations.is_empty() {
516 write!(msg, "{:1$}", "", prefix_len).unwrap(); // Print spaces.
517 let mut pos = Size::ZERO;
518 let relocation_width = (self.pointer_size().bytes() - 1) * 3;
519 for (i, target_id) in relocations {
520 // this `as usize` is fine, since we can't print more chars than `usize::MAX`
521 write!(msg, "{:1$}", "", ((i - pos) * 3).bytes() as usize).unwrap();
522 let target = format!("({})", target_id);
523 // this `as usize` is fine, since we can't print more chars than `usize::MAX`
524 write!(msg, "└{0:─^1$}┘ ", target, relocation_width as usize).unwrap();
525 pos = i + self.pointer_size();
531 /// For debugging, print a list of allocations and all allocations they point to, recursively.
532 pub fn dump_allocs(&self, mut allocs: Vec<AllocId>) {
533 if !log_enabled!(::log::Level::Trace) {
538 let mut allocs_to_print = VecDeque::from(allocs);
539 let mut allocs_seen = FxHashSet::default();
541 while let Some(id) = allocs_to_print.pop_front() {
542 let msg = format!("Alloc {:<5} ", format!("{}:", id));
545 match self.alloc_map.get_or(id, || Err(())) {
546 Ok((kind, alloc)) => {
547 let extra = match kind {
548 MemoryKind::Stack => " (stack)".to_owned(),
549 MemoryKind::Vtable => " (vtable)".to_owned(),
550 MemoryKind::Machine(m) => format!(" ({:?})", m),
552 self.dump_alloc_helper(
553 &mut allocs_seen, &mut allocs_to_print,
559 match self.tcx.alloc_map.lock().get(id) {
560 Some(AllocKind::Memory(alloc)) => {
561 self.dump_alloc_helper(
562 &mut allocs_seen, &mut allocs_to_print,
563 msg, alloc, " (immutable)".to_owned()
566 Some(AllocKind::Function(func)) => {
567 trace!("{} {}", msg, func);
569 Some(AllocKind::Static(did)) => {
570 trace!("{} {:?}", msg, did);
573 trace!("{} (deallocated)", msg);
582 pub fn leak_report(&self) -> usize {
583 trace!("### LEAK REPORT ###");
584 let leaks: Vec<_> = self.alloc_map.filter_map_collect(|&id, &(kind, _)| {
585 if kind.may_leak() { None } else { Some(id) }
588 self.dump_allocs(leaks);
592 /// This is used by [priroda](https://github.com/oli-obk/priroda)
593 pub fn alloc_map(&self) -> &M::MemoryMap {
599 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
602 ptr: Scalar<M::PointerTag>,
604 ) -> EvalResult<'tcx, &[u8]> {
605 if size.bytes() == 0 {
608 let ptr = ptr.to_ptr()?;
609 self.get(ptr.alloc_id)?.get_bytes(self, ptr, size)
614 /// Interning (for CTFE)
615 impl<'a, 'mir, 'tcx, M> Memory<'a, 'mir, 'tcx, M>
617 M: Machine<'a, 'mir, 'tcx, PointerTag=(), AllocExtra=(), MemoryExtra=()>,
618 // FIXME: Working around https://github.com/rust-lang/rust/issues/24159
619 M::MemoryMap: AllocMap<AllocId, (MemoryKind<M::MemoryKinds>, Allocation)>,
621 /// mark an allocation as static and initialized, either mutable or not
622 pub fn intern_static(
625 mutability: Mutability,
626 ) -> EvalResult<'tcx> {
628 "mark_static_initialized {:?}, mutability: {:?}",
633 let (kind, mut alloc) = self.alloc_map.remove(&alloc_id).unwrap();
635 MemoryKind::Machine(_) => bug!("Static cannot refer to machine memory"),
636 MemoryKind::Stack | MemoryKind::Vtable => {},
638 // ensure llvm knows not to put this into immutable memory
639 alloc.mutability = mutability;
640 let alloc = self.tcx.intern_const_alloc(alloc);
641 self.tcx.alloc_map.lock().set_alloc_id_memory(alloc_id, alloc);
642 // recurse into inner allocations
643 for &(_, alloc) in alloc.relocations.values() {
644 // FIXME: Reusing the mutability here is likely incorrect. It is originally
645 // determined via `is_freeze`, and data is considered frozen if there is no
646 // `UnsafeCell` *immediately* in that data -- however, this search stops
647 // at references. So whenever we follow a reference, we should likely
648 // assume immutability -- and we should make sure that the compiler
649 // does not permit code that would break this!
650 if self.alloc_map.contains_key(&alloc) {
651 // Not yet interned, so proceed recursively
652 self.intern_static(alloc, mutability)?;
653 } else if self.dead_alloc_map.contains_key(&alloc) {
655 return err!(ValidationFailure(
656 "encountered dangling pointer in final constant".into(),
664 /// Reading and writing.
665 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
668 src: Scalar<M::PointerTag>,
670 dest: Scalar<M::PointerTag>,
673 nonoverlapping: bool,
674 ) -> EvalResult<'tcx> {
675 self.copy_repeatedly(src, src_align, dest, dest_align, size, 1, nonoverlapping)
678 pub fn copy_repeatedly(
680 src: Scalar<M::PointerTag>,
682 dest: Scalar<M::PointerTag>,
686 nonoverlapping: bool,
687 ) -> EvalResult<'tcx> {
688 self.check_align(src, src_align)?;
689 self.check_align(dest, dest_align)?;
690 if size.bytes() == 0 {
691 // Nothing to do for ZST, other than checking alignment and
692 // non-NULLness which already happened.
695 let src = src.to_ptr()?;
696 let dest = dest.to_ptr()?;
698 // first copy the relocations to a temporary buffer, because
699 // `get_bytes_mut` will clear the relocations, which is correct,
700 // since we don't want to keep any relocations at the target.
701 // (`get_bytes_with_undef_and_ptr` below checks that there are no
702 // relocations overlapping the edges; those would not be handled correctly).
704 let relocations = self.get(src.alloc_id)?.relocations(self, src, size);
705 if relocations.is_empty() {
706 // nothing to copy, ignore even the `length` loop
709 let mut new_relocations = Vec::with_capacity(relocations.len() * (length as usize));
711 new_relocations.extend(
714 .map(|&(offset, reloc)| {
715 // compute offset for current repetition
716 let dest_offset = dest.offset + (i * size);
718 // shift offsets from source allocation to destination allocation
719 offset + dest_offset - src.offset,
730 let tcx = self.tcx.tcx;
732 // This checks relocation edges on the src.
733 let src_bytes = self.get(src.alloc_id)?
734 .get_bytes_with_undef_and_ptr(&tcx, src, size)?
736 let dest_bytes = self.get_mut(dest.alloc_id)?
737 .get_bytes_mut(&tcx, dest, size * length)?
740 // SAFE: The above indexing would have panicked if there weren't at least `size` bytes
741 // behind `src` and `dest`. Also, we use the overlapping-safe `ptr::copy` if `src` and
742 // `dest` could possibly overlap.
743 // The pointers above remain valid even if the `HashMap` table is moved around because they
744 // point into the `Vec` storing the bytes.
746 assert_eq!(size.bytes() as usize as u64, size.bytes());
747 if src.alloc_id == dest.alloc_id {
749 if (src.offset <= dest.offset && src.offset + size > dest.offset) ||
750 (dest.offset <= src.offset && dest.offset + size > src.offset)
752 return err!(Intrinsic(
753 "copy_nonoverlapping called on overlapping ranges".to_string(),
760 dest_bytes.offset((size.bytes() * i) as isize),
761 size.bytes() as usize);
765 ptr::copy_nonoverlapping(src_bytes,
766 dest_bytes.offset((size.bytes() * i) as isize),
767 size.bytes() as usize);
772 // copy definedness to the destination
773 self.copy_undef_mask(src, dest, size, length)?;
774 // copy the relocations to the destination
775 self.get_mut(dest.alloc_id)?.relocations.insert_presorted(relocations);
782 impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> Memory<'a, 'mir, 'tcx, M> {
783 // FIXME: Add a fast version for the common, nonoverlapping case
786 src: Pointer<M::PointerTag>,
787 dest: Pointer<M::PointerTag>,
790 ) -> EvalResult<'tcx> {
791 // The bits have to be saved locally before writing to dest in case src and dest overlap.
792 assert_eq!(size.bytes() as usize as u64, size.bytes());
794 let undef_mask = &self.get(src.alloc_id)?.undef_mask;
796 // Since we are copying `size` bytes from `src` to `dest + i * size` (`for i in 0..repeat`),
797 // a naive undef mask copying algorithm would repeatedly have to read the undef mask from
798 // the source and write it to the destination. Even if we optimized the memory accesses,
799 // we'd be doing all of this `repeat` times.
800 // Therefor we precompute a compressed version of the undef mask of the source value and
801 // then write it back `repeat` times without computing any more information from the source.
803 // a precomputed cache for ranges of defined/undefined bits
804 // 0000010010001110 will become
805 // [5, 1, 2, 1, 3, 3, 1]
806 // where each element toggles the state
807 let mut ranges = smallvec::SmallVec::<[u64; 1]>::new();
808 let first = undef_mask.get(src.offset);
811 for i in 1..size.bytes() {
812 // FIXME: optimize to bitshift the current undef block's bits and read the top bit
813 if undef_mask.get(src.offset + Size::from_bytes(i)) == cur {
816 ranges.push(cur_len);
822 // now fill in all the data
823 let dest_allocation = self.get_mut(dest.alloc_id)?;
824 // an optimization where we can just overwrite an entire range of definedness bits if
825 // they are going to be uniformly `1` or `0`.
826 if ranges.is_empty() {
827 dest_allocation.undef_mask.set_range_inbounds(
829 dest.offset + size * repeat,
835 // remember to fill in the trailing bits
836 ranges.push(cur_len);
838 for mut j in 0..repeat {
840 j += dest.offset.bytes();
842 for range in &ranges {
845 dest_allocation.undef_mask.set_range_inbounds(
846 Size::from_bytes(old_j),