[libc-commits] [libc] [libc][string] Optimize stpncpy() with strnlen() and inline_memcpy() (PR #246447)
via libc-commits
libc-commits at lists.llvm.org
Thu Nov 26 08:47:18 PST 2026
llvmorg-github-actions[bot] wrote:
<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-libc
Author: Kuan-Wei Chiu (visitorckw)
<details>
<summary>Changes</summary>
The current stpncpy implementation copies characters using a byte by byte loop before padding trailing null bytes with inline_bzero. Replace the copy loop with internal::strnlen and inline_memcpy to leverage vectorized string and memory operations, matching strncpy.
In a microbenchmark copying a 512 byte string into a 1024 byte buffer, this reduces execution time by about 83%, or 6.1x faster.
---
Full diff: https://github.com/llvm/llvm-project/pull/246447.diff
2 Files Affected:
- (modified) libc/src/string/CMakeLists.txt (+2)
- (modified) libc/src/string/stpncpy.cpp (+12-6)
``````````diff
diff --git a/libc/src/string/CMakeLists.txt b/libc/src/string/CMakeLists.txt
index 4427e59961039..d97e90016d57a 100644
--- a/libc/src/string/CMakeLists.txt
+++ b/libc/src/string/CMakeLists.txt
@@ -92,6 +92,8 @@ add_entrypoint_object(
stpncpy.h
DEPENDS
.memory_utils.inline_bzero
+ .memory_utils.inline_memcpy
+ .string_utils
)
add_entrypoint_object(
diff --git a/libc/src/string/stpncpy.cpp b/libc/src/string/stpncpy.cpp
index 47bf4c6e86fba..99ddeb4f7654f 100644
--- a/libc/src/string/stpncpy.cpp
+++ b/libc/src/string/stpncpy.cpp
@@ -1,17 +1,24 @@
-//===-- Implementation of stpncpy -----------------------------------------===//
+//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
+///
+/// \file
+/// Implementation of stpncpy.
+///
+//===----------------------------------------------------------------------===//
#include "src/string/stpncpy.h"
+
+#include "src/__support/common.h"
#include "src/__support/macros/config.h"
#include "src/__support/macros/null_check.h"
#include "src/string/memory_utils/inline_bzero.h"
-
-#include "src/__support/common.h"
+#include "src/string/memory_utils/inline_memcpy.h"
+#include "src/string/string_utils.h"
namespace LIBC_NAMESPACE_DECL {
@@ -22,10 +29,9 @@ LLVM_LIBC_FUNCTION(char *, stpncpy,
LIBC_CRASH_ON_NULLPTR(dest);
LIBC_CRASH_ON_NULLPTR(src);
}
- size_t i;
+ size_t i = internal::strnlen(src, n);
// Copy up until \0 is found.
- for (i = 0; i < n && src[i] != '\0'; ++i)
- dest[i] = src[i];
+ inline_memcpy(dest, src, i);
// When n>strlen(src), n-strlen(src) \0 are appended.
if (n > i)
inline_bzero(dest + i, n - i);
``````````
</details>
https://github.com/llvm/llvm-project/pull/246447
More information about the libc-commits
mailing list