1 //===-- Implementation of memmove -----------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "src/string/memmove.h"
10 #include "src/__support/common.h"
11 #include "src/stdlib/abs_utils.h"
12 #include "src/string/memcpy.h"
13 #include <stddef.h> // size_t, ptrdiff_t
14 #include <unistd.h> // ssize_t
15 
16 namespace __llvm_libc {
17 
18 // src_m and dest_m might be the beginning or end.
19 static inline void move_byte(unsigned char *dest_m, const unsigned char *src_m,
20                              size_t count, ssize_t direction) {
21   for (ssize_t offset = 0; count; --count, offset += direction)
22     dest_m[offset] = src_m[offset];
23 }
24 
25 LLVM_LIBC_FUNCTION(void *, memmove,
26                    (void *dest, const void *src, size_t count)) {
27   unsigned char *dest_c = reinterpret_cast<unsigned char *>(dest);
28   const unsigned char *src_c = reinterpret_cast<const unsigned char *>(src);
29 
30   // If the distance between src_c and dest_c is equal to or greater
31   // than count (integer_abs(src_c - dest_c) >= count), they would not overlap.
32   // e.g.   greater     equal       overlapping
33   //        [12345678]  [12345678]  [12345678]
34   // src_c: [_ab_____]  [_ab_____]  [_ab_____]
35   // dest_c:[_____yz_]  [___yz___]  [__yz____]
36 
37   // Use memcpy if src_c and dest_c do not overlap.
38   if (__llvm_libc::integer_abs(src_c - dest_c) >= static_cast<ptrdiff_t>(count))
39     return __llvm_libc::memcpy(dest_c, src_c, count);
40 
41   // Overlap cases.
42   // If dest_c starts before src_c (dest_c < src_c), copy forward(pointer add 1)
43   // from beginning to end.
44   // If dest_c starts after src_c (dest_c > src_c), copy backward(pointer add
45   // -1) from end to beginning.
46   // If dest_c and src_c start at the same address (dest_c == src_c),
47   // just return dest.
48   // e.g.    forward      backward
49   //             *-->        <--*
50   // src_c : [___abcde_]  [_abcde___]
51   // dest_c: [_abc--___]  [___--cde_]
52 
53   // TODO: Optimize `move_byte(...)` function.
54   if (dest_c < src_c)
55     move_byte(dest_c, src_c, count, /*pointer add*/ 1);
56   if (dest_c > src_c)
57     move_byte(dest_c + count - 1, src_c + count - 1, count, /*pointer add*/ -1);
58   return dest;
59 }
60 
61 } // namespace __llvm_libc
62