xref: /llvm-project/libc/src/string/memcmp.cpp (revision fe953b15cf08a4d25a16bdbda23dfefb3568540b)
1 //===-- Implementation of memcmp ------------------------------------------===//
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/memcmp.h"
10 #include "src/__support/common.h"
11 #include "src/string/memory_utils/elements.h"
12 
13 #include <stddef.h> // size_t
14 
15 namespace __llvm_libc {
16 
17 static int memcmp_impl(const char *lhs, const char *rhs, size_t count) {
18 #if defined(__i386__) || defined(__x86_64__)
19   using namespace ::__llvm_libc::x86;
20 #else
21   using namespace ::__llvm_libc::scalar;
22 #endif
23 
24   if (count == 0)
25     return 0;
26   if (count == 1)
27     return ThreeWayCompare<_1>(lhs, rhs);
28   if (count == 2)
29     return ThreeWayCompare<_2>(lhs, rhs);
30   if (count == 3)
31     return ThreeWayCompare<_3>(lhs, rhs);
32   if (count <= 8)
33     return ThreeWayCompare<HeadTail<_4>>(lhs, rhs, count);
34   if (count <= 16)
35     return ThreeWayCompare<HeadTail<_8>>(lhs, rhs, count);
36   if (count <= 32)
37     return ThreeWayCompare<HeadTail<_16>>(lhs, rhs, count);
38   if (count <= 64)
39     return ThreeWayCompare<HeadTail<_32>>(lhs, rhs, count);
40   if (count <= 128)
41     return ThreeWayCompare<HeadTail<_64>>(lhs, rhs, count);
42   return ThreeWayCompare<Align<_32>::Then<Loop<_32>>>(lhs, rhs, count);
43 }
44 
45 LLVM_LIBC_FUNCTION(int, memcmp,
46                    (const void *lhs, const void *rhs, size_t count)) {
47   return memcmp_impl(static_cast<const char *>(lhs),
48                      static_cast<const char *>(rhs), count);
49 }
50 
51 } // namespace __llvm_libc
52