[libc-commits] [libc] [libc][NFC] Clean up regex tables, headers, and CMake deps (PR #243759)

Jeff Bailey via libc-commits libc-commits at lists.llvm.org
Wed Nov 18 00:16:22 PST 2026


https://github.com/kaladron updated https://github.com/llvm/llvm-project/pull/243759

>From 756d63879c6da13c5bca89e33e25b77d337e1f8b Mon Sep 17 00:00:00 2001
From: Jeff Bailey <jbailey at raspberryginger.com>
Date: Tue, 17 Nov 2026 23:08:07 +0000
Subject: [PATCH] [libc][NFC] Clean up regex tables, headers, and CMake deps

Integer-only baremetal targets cannot rely on floating-point helpers
just to size a hash table, and PIE builds should keep constant lookup
tables in shared read-only memory rather than dirtying copy-on-write
.data.rel.ro pages with dynamic relocations at startup.  In addition,
subarchive builds linking regcomp or regexec without regfree miss
operator delete because collect_object_file_deps skips header
libraries, and POSIX requires <regex.h> to export size_t directly.

Switch ExprPool::max_hashtable_nodes() to integer 7/10 arithmetic and
store inline class names in pure .rodata tables behind a [[nodiscard]]
add_posix_class helper, avoiding both 32-byte copies and raw nullable
pointers while shrinking regex_parser.cpp.o by 725 bytes at -O2 and
775 bytes at -Os with zero relocations.  Export size_t in regex.yaml,
add direct libc.src.__support.CPP.new dependencies, clear preg before
delete so teardown never exposes a dangling pointer, and tighten
internal assert and static_assert guards.

Compliance: Henry Spencer spencer_tests.txt 268/456 Bool/Err (+0) and
84/456 Full Pos (+0); AT&T testregex 399/400 ERE Bool/Err (+0), 401/473
All Bool/Err (+0), and 18/465 Full Pos (+0); zero regressions.

Assisted-by: Automated tooling, human reviewed.
---
 libc/include/regex.yaml                       |  1 +
 libc/src/__support/regex/CMakeLists.txt       |  9 ++-
 libc/src/__support/regex/regex_ast.h          |  4 ++
 libc/src/__support/regex/regex_charclass.h    | 58 ++++++++++++-------
 libc/src/__support/regex/regex_expr_pool.cpp  | 14 +++--
 libc/src/__support/regex/regex_expr_pool.h    | 18 +++---
 libc/src/__support/regex/regex_matcher.cpp    |  1 +
 libc/src/__support/regex/regex_matcher.h      |  2 +-
 libc/src/__support/regex/regex_parser.cpp     | 17 +++---
 libc/src/regex/CMakeLists.txt                 |  1 +
 libc/src/regex/regfree.cpp                    |  3 +-
 .../test/src/__support/regex/matcher_test.cpp | 13 +++++
 12 files changed, 92 insertions(+), 49 deletions(-)

diff --git a/libc/include/regex.yaml b/libc/include/regex.yaml
index baa7e39c9dd10d..8fe77257f07be6 100644
--- a/libc/include/regex.yaml
+++ b/libc/include/regex.yaml
@@ -44,6 +44,7 @@ types:
   - type_name: regex_t
   - type_name: regmatch_t
   - type_name: regoff_t
+  - type_name: size_t
 enums: []
 objects: []
 functions:
diff --git a/libc/src/__support/regex/CMakeLists.txt b/libc/src/__support/regex/CMakeLists.txt
index 7189298399ca88..a7c7dd66f5824b 100644
--- a/libc/src/__support/regex/CMakeLists.txt
+++ b/libc/src/__support/regex/CMakeLists.txt
@@ -9,10 +9,12 @@ add_object_library(
     libc.hdr.limits_macros
     libc.hdr.regex_macros
     libc.hdr.stdint_proxy
+    libc.hdr.types.size_t
     libc.src.__support.checked_ptr
     libc.src.__support.CPP.algorithm
     libc.src.__support.CPP.array
     libc.src.__support.CPP.bitset
+    libc.src.__support.CPP.new
     libc.src.__support.CPP.optional
     libc.src.__support.CPP.span
     libc.src.__support.CPP.unique_ptr
@@ -20,7 +22,6 @@ add_object_library(
     libc.src.__support.error_or
     libc.src.__support.hash
     libc.src.__support.libc_assert
-    libc.src.__support.macros.config
 )
 
 add_header_library(
@@ -43,10 +44,10 @@ add_object_library(
     .regex_expr_pool
     .regex_internal
     libc.hdr.regex_macros
-    libc.src.__support.common
     libc.src.__support.CPP.string_view
     libc.src.__support.error_or
     libc.src.__support.libc_assert
+    libc.src.__support.macros.attributes
 )
 
 add_object_library(
@@ -60,9 +61,12 @@ add_object_library(
     .regex_expr_pool
     libc.hdr.limits_macros
     libc.hdr.regex_macros
+    libc.hdr.stdint_proxy
+    libc.hdr.types.size_t
     libc.src.__support.checked_ptr
     libc.src.__support.CPP.array
     libc.src.__support.CPP.bitset
+    libc.src.__support.CPP.new
     libc.src.__support.CPP.optional
     libc.src.__support.CPP.span
     libc.src.__support.CPP.string_view
@@ -71,5 +75,4 @@ add_object_library(
     libc.src.__support.error_or
     libc.src.__support.libc_assert
     libc.src.__support.macros.attributes
-    libc.src.__support.macros.config
 )
diff --git a/libc/src/__support/regex/regex_ast.h b/libc/src/__support/regex/regex_ast.h
index 83af439fe97e1a..a7d9847efcbbee 100644
--- a/libc/src/__support/regex/regex_ast.h
+++ b/libc/src/__support/regex/regex_ast.h
@@ -35,6 +35,10 @@ inline constexpr uint16_t REPEAT_INF = 0xFFFF;
 /// Compile-time guard against nested repetition bombs (e.g. (a{255}){255});
 /// ExprPool::MAX_NODE_LIMIT bounds lazy runtime state growth.
 inline constexpr uint16_t MAX_REPEAT_EXPANSION = 32768;
+static_assert(MAX_REPEAT_EXPANSION < REPEAT_INF,
+              "MAX_REPEAT_EXPANSION must leave headroom below REPEAT_INF");
+static_assert(RE_DUP_MAX < REPEAT_INF,
+              "RE_DUP_MAX must not collide with REPEAT_INF");
 
 /// One bit per possible byte value (2^CHAR_BIT = 256), allowing O(1)
 /// membership tests for wildcards and bracket expressions.
diff --git a/libc/src/__support/regex/regex_charclass.h b/libc/src/__support/regex/regex_charclass.h
index 3563df1d3a4c2e..5fac0115c4c1d5 100644
--- a/libc/src/__support/regex/regex_charclass.h
+++ b/libc/src/__support/regex/regex_charclass.h
@@ -14,9 +14,10 @@
 #ifndef LLVM_LIBC_SRC___SUPPORT_REGEX_REGEX_CHARCLASS_H
 #define LLVM_LIBC_SRC___SUPPORT_REGEX_REGEX_CHARCLASS_H
 
+#include "hdr/stdint_proxy.h"
+#include "hdr/types/size_t.h"
 #include "src/__support/CPP/array.h"
 #include "src/__support/CPP/bitset.h"
-#include "src/__support/CPP/optional.h"
 #include "src/__support/CPP/string_view.h"
 #include "src/__support/ctype_utils.h"
 #include "src/__support/macros/attributes.h"
@@ -27,8 +28,20 @@ namespace LIBC_NAMESPACE_DECL {
 namespace regex {
 
 struct PosixClassEntry {
-  cpp::string_view name;
-  ByteSet set;
+  static constexpr size_t MAX_NAME_LEN = 7;
+
+  cpp::array<char, MAX_NAME_LEN> name{};
+  uint8_t len = 0;
+  ByteSet set{};
+
+  template <size_t N>
+  LIBC_INLINE constexpr PosixClassEntry(const char (&s)[N], const ByteSet &bs)
+      : len(static_cast<uint8_t>(N - 1)), set(bs) {
+    static_assert(N - 1 <= MAX_NAME_LEN, "POSIX class name exceeds buffer");
+    // Evaluated only at compile time; inline_memcpy is not constexpr.
+    for (size_t i = 0; i < N - 1; ++i)
+      name[i] = s[i];
+  }
 };
 
 template <typename Pred>
@@ -40,20 +53,16 @@ LIBC_INLINE constexpr ByteSet make_class_set(Pred pred) {
   return bs;
 }
 
-LIBC_INLINE constexpr ByteSet digit_class_set() {
-  return make_class_set([](char c) { return internal::isdigit(c); });
-}
+LIBC_INLINE_VAR constexpr ByteSet DIGIT_CLASS_SET =
+    make_class_set([](char c) { return internal::isdigit(c); });
 
-LIBC_INLINE constexpr ByteSet space_class_set() {
-  return make_class_set([](char c) { return internal::isspace(c); });
-}
+LIBC_INLINE_VAR constexpr ByteSet SPACE_CLASS_SET =
+    make_class_set([](char c) { return internal::isspace(c); });
 
-LIBC_INLINE constexpr ByteSet word_class_set() {
-  return make_class_set(
-      [](char c) { return internal::isalnum(c) || c == '_'; });
-}
+LIBC_INLINE_VAR constexpr ByteSet WORD_CLASS_SET =
+    make_class_set([](char c) { return internal::isalnum(c) || c == '_'; });
 
-LIBC_INLINE constexpr cpp::array<PosixClassEntry, 12> POSIX_CLASSES = {{
+LIBC_INLINE_VAR constexpr cpp::array<PosixClassEntry, 12> POSIX_CLASSES = {{
     {"alnum", make_class_set([](char c) { return internal::isalnum(c); })},
     {"alpha", make_class_set([](char c) { return internal::isalpha(c); })},
     {"blank", make_class_set([](char c) { return c == ' ' || c == '\t'; })},
@@ -61,7 +70,7 @@ LIBC_INLINE constexpr cpp::array<PosixClassEntry, 12> POSIX_CLASSES = {{
        const unsigned ch = static_cast<unsigned char>(c);
        return ch < 0x20 || ch == 0x7F;
      })},
-    {"digit", digit_class_set()},
+    {"digit", DIGIT_CLASS_SET},
     {"graph", make_class_set([](char c) { return internal::isgraph(c); })},
     {"lower", make_class_set([](char c) { return internal::islower(c); })},
     {"print", make_class_set([](char c) {
@@ -71,7 +80,7 @@ LIBC_INLINE constexpr cpp::array<PosixClassEntry, 12> POSIX_CLASSES = {{
     {"punct", make_class_set([](char c) {
        return !internal::isalnum(c) && internal::isgraph(c);
      })},
-    {"space", space_class_set()},
+    {"space", SPACE_CLASS_SET},
     {"upper", make_class_set([](char c) { return internal::isupper(c); })},
     {"xdigit", make_class_set([](char c) {
        return internal::isdigit(c) || (c >= 'a' && c <= 'f') ||
@@ -79,12 +88,17 @@ LIBC_INLINE constexpr cpp::array<PosixClassEntry, 12> POSIX_CLASSES = {{
      })},
 }};
 
-LIBC_INLINE constexpr cpp::optional<ByteSet>
-lookup_posix_class(cpp::string_view name) {
-  for (const auto &entry : POSIX_CLASSES)
-    if (entry.name == name)
-      return entry.set;
-  return cpp::nullopt;
+/// Unions the named POSIX character class into \p out.
+/// Returns false if \p name is not a recognized POSIX class name.
+[[nodiscard]] LIBC_INLINE constexpr bool add_posix_class(cpp::string_view name,
+                                                         ByteSet &out) {
+  for (const auto &entry : POSIX_CLASSES) {
+    if (cpp::string_view(entry.name.data(), entry.len) == name) {
+      out |= entry.set;
+      return true;
+    }
+  }
+  return false;
 }
 
 } // namespace regex
diff --git a/libc/src/__support/regex/regex_expr_pool.cpp b/libc/src/__support/regex/regex_expr_pool.cpp
index 22652c15041d53..976d2596cab223 100644
--- a/libc/src/__support/regex/regex_expr_pool.cpp
+++ b/libc/src/__support/regex/regex_expr_pool.cpp
@@ -26,7 +26,7 @@ namespace regex {
 namespace {
 
 // Hash an Expr node for hash-consing.
-uint32_t hash_expr(const Expr &e) {
+uint32_t hash_expr(const Expr e) {
   // Initialise HashState with a constant seed. The specific value (0x12345678)
   // is an arbitrary placeholder; HashState immediately mixes this seed with
   // high-entropy constants (derived from aHash) to produce a strong hash, while
@@ -38,6 +38,9 @@ uint32_t hash_expr(const Expr &e) {
   } key = {static_cast<uint64_t>(e.kind), 0};
   static_assert(sizeof(HashKey) == 2 * sizeof(uint64_t));
   switch (e.kind) {
+  case ExprKind::EmptySet:
+  case ExprKind::EmptyStr:
+    break;
   case ExprKind::Literal:
     key.payload = static_cast<uint8_t>(e.ch);
     break;
@@ -58,8 +61,6 @@ uint32_t hash_expr(const Expr &e) {
   case ExprKind::Alt:
     key.payload = (static_cast<uint64_t>(e.bin.left) << 32) | e.bin.right;
     break;
-  default:
-    break;
   }
   hasher.update(&key, sizeof(key));
   uint64_t h = hasher.finish();
@@ -121,7 +122,7 @@ bool ExprPool::ensure_initialized() {
   return true;
 }
 
-ExprId &ExprPool::find_bucket(cpp::span<ExprId> table, const Expr &e) const {
+ExprId &ExprPool::find_bucket(cpp::span<ExprId> table, const Expr e) const {
   for (ExprId &slot : BucketProber(table, e.hash)) {
     if (slot == INVALID_EXPR_ID)
       return slot;
@@ -129,6 +130,7 @@ ExprId &ExprPool::find_bucket(cpp::span<ExprId> table, const Expr &e) const {
     if (cand.hash == e.hash && cand == e)
       return slot;
   }
+  LIBC_ASSERT(false);
   __builtin_unreachable();
 }
 
@@ -228,6 +230,8 @@ ErrorOr<ExprId> ExprPool::make_byte_set(const ByteSet &bs) {
     if (bs.test(b)) {
       ++count;
       last_bit = b;
+      if (count > 1)
+        break;
     }
   }
   if (count == 0)
@@ -418,7 +422,7 @@ ErrorOr<ExprId> coalesce_repeat_pair(ExprId a, ExprId b, ExprPool &pool) {
   // Undo make_repeat normalizations: R -> [1,1], EmptyStr -> [0,0], and
   // Star(R) -> [0,REPEAT_INF].
   auto get_interval = [&](ExprId id,
-                          const Expr &e) -> cpp::optional<RepeatInterval> {
+                          const Expr e) -> cpp::optional<RepeatInterval> {
     if (e.kind == ExprKind::Repeat && e.rep.body == body)
       return RepeatInterval{e.rep.min, e.rep.max};
     if (e.kind == ExprKind::Star && e.body == body)
diff --git a/libc/src/__support/regex/regex_expr_pool.h b/libc/src/__support/regex/regex_expr_pool.h
index ea253f126afb74..2bb2dfe0067874 100644
--- a/libc/src/__support/regex/regex_expr_pool.h
+++ b/libc/src/__support/regex/regex_expr_pool.h
@@ -14,6 +14,7 @@
 #ifndef LLVM_LIBC_SRC___SUPPORT_REGEX_REGEX_EXPR_POOL_H
 #define LLVM_LIBC_SRC___SUPPORT_REGEX_REGEX_EXPR_POOL_H
 
+#include "hdr/types/size_t.h"
 #include "src/__support/CPP/array.h"
 #include "src/__support/CPP/span.h"
 #include "src/__support/CPP/unique_ptr.h"
@@ -21,7 +22,6 @@
 #include "src/__support/libc_assert.h"
 #include "src/__support/macros/config.h"
 #include "src/__support/regex/regex_ast.h"
-#include <stddef.h>
 
 namespace LIBC_NAMESPACE_DECL {
 namespace regex {
@@ -57,9 +57,10 @@ class ExprPool {
   static constexpr size_t INITIAL_HASH_CAPACITY = 64;
   /// Scaling factor used when growing dynamic pool arrays and hash tables.
   static constexpr size_t GROWTH_FACTOR = 2;
-  /// Grow the hash table when occupancy reaches 70% to keep linear-probing
-  /// chains short.
-  static constexpr double MAX_LOAD_FACTOR = 0.7;
+  /// Grow the hash table when occupancy reaches 70% (7 / 10) to keep
+  /// linear-probing chains short without floating-point arithmetic.
+  static constexpr size_t MAX_LOAD_NUMERATOR = 7;
+  static constexpr size_t MAX_LOAD_DENOMINATOR = 10;
 
   /// Directory of allocated blocks.
   cpp::unique_ptr<cpp::unique_ptr<Block>[]> blocks;
@@ -86,9 +87,8 @@ class ExprPool {
   }
 
   /// Maximum number of nodes the current hash table can hold before rehashing.
-  size_t max_hashtable_nodes() const {
-    return static_cast<size_t>(static_cast<double>(hashtable_capacity) *
-                               MAX_LOAD_FACTOR);
+  constexpr size_t max_hashtable_nodes() const {
+    return (hashtable_capacity * MAX_LOAD_NUMERATOR) / MAX_LOAD_DENOMINATOR;
   }
 
   /// Single choke point mapping a 1-based ExprId to its 2D block/node slot.
@@ -98,7 +98,7 @@ class ExprPool {
     return blocks[idx / NODES_PER_BLOCK]->nodes[idx % NODES_PER_BLOCK];
   }
 
-  ExprId &find_bucket(cpp::span<ExprId> table, const Expr &e) const;
+  ExprId &find_bucket(cpp::span<ExprId> table, Expr e) const;
   bool ensure_initialized();
   bool allocate_block();
   bool grow_hashtable();
@@ -119,6 +119,8 @@ class ExprPool {
   /// exhaustion during compilation of highly complex or maliciously crafted
   /// regular expressions.
   static constexpr size_t MAX_NODE_LIMIT = 10000;
+  static_assert(MAX_NODE_LIMIT < UINT32_MAX,
+                "MAX_NODE_LIMIT must fit in 32-bit ExprId");
 
   constexpr ExprPool() = default;
   // The implicit move operations would move the arrays, but copy their sizes,
diff --git a/libc/src/__support/regex/regex_matcher.cpp b/libc/src/__support/regex/regex_matcher.cpp
index 54f3770b9ba9a5..4809e93154eb75 100644
--- a/libc/src/__support/regex/regex_matcher.cpp
+++ b/libc/src/__support/regex/regex_matcher.cpp
@@ -135,6 +135,7 @@ ErrorOr<ExprId> derivative(ExprId id, char c, ExprPool &pool,
     return pool.make_concat(*d_body, *tail);
   }
   }
+  LIBC_ASSERT(false);
   __builtin_unreachable();
 }
 
diff --git a/libc/src/__support/regex/regex_matcher.h b/libc/src/__support/regex/regex_matcher.h
index 110633c66ef65c..100c4c9dda44a7 100644
--- a/libc/src/__support/regex/regex_matcher.h
+++ b/libc/src/__support/regex/regex_matcher.h
@@ -15,8 +15,8 @@
 #define LLVM_LIBC_SRC___SUPPORT_REGEX_REGEX_MATCHER_H
 
 #include "src/__support/CPP/string_view.h"
-#include "src/__support/common.h"
 #include "src/__support/error_or.h"
+#include "src/__support/macros/attributes.h"
 #include "src/__support/macros/config.h"
 #include "src/__support/regex/regex_ast.h"
 #include "src/__support/regex/regex_expr_pool.h"
diff --git a/libc/src/__support/regex/regex_parser.cpp b/libc/src/__support/regex/regex_parser.cpp
index 2ba1816a0a57bd..9072fba5440380 100644
--- a/libc/src/__support/regex/regex_parser.cpp
+++ b/libc/src/__support/regex/regex_parser.cpp
@@ -133,10 +133,8 @@ ErrorOr<ExprId> parse_bracket_expr(cpp::string_view &rem, int cflags,
       rem.remove_prefix(delim_pos + 2);
       if (name == "<" || name == ">")
         return Error(REG_BADPAT);
-      cpp::optional<ByteSet> opt = lookup_posix_class(name);
-      if (!opt.has_value())
+      if (!add_posix_class(name, bs))
         return Error(REG_ECTYPE);
-      bs |= *opt;
       if (rem.starts_with('-') && !rem.starts_with("-]"))
         return Error(REG_ERANGE);
       continue;
@@ -266,18 +264,18 @@ ErrorOr<ExprId> parse_quantified_atom(cpp::string_view &rem, int cflags,
     case 'd':
     case 's':
     case 'w': {
-      const ByteSet bs = (c == 'd')   ? digit_class_set()
-                         : (c == 's') ? space_class_set()
-                                      : word_class_set();
+      const ByteSet &bs = (c == 'd')   ? DIGIT_CLASS_SET
+                          : (c == 's') ? SPACE_CLASS_SET
+                                       : WORD_CLASS_SET;
       atom = pool.make_byte_set(bs);
       break;
     }
     case 'D':
     case 'S':
     case 'W': {
-      ByteSet bs = (c == 'D')   ? digit_class_set()
-                   : (c == 'S') ? space_class_set()
-                                : word_class_set();
+      ByteSet bs = (c == 'D')   ? DIGIT_CLASS_SET
+                   : (c == 'S') ? SPACE_CLASS_SET
+                                : WORD_CLASS_SET;
       bs.flip();
       bs.reset(0);
       if (cflags & REG_NEWLINE)
@@ -414,6 +412,7 @@ struct ParsedAtomStack {
   }
 
   ExprId pop() {
+    LIBC_ASSERT(count > 0);
     --count;
     return atoms[count];
   }
diff --git a/libc/src/regex/CMakeLists.txt b/libc/src/regex/CMakeLists.txt
index 99b47218a3f19c..99ba22ff954655 100644
--- a/libc/src/regex/CMakeLists.txt
+++ b/libc/src/regex/CMakeLists.txt
@@ -11,6 +11,7 @@ add_entrypoint_object(
     libc.src.__support.CPP.string_view
     libc.src.__support.error_or
     libc.src.__support.macros.null_check
+    libc.src.__support.regex.regex_expr_pool
     libc.src.__support.regex.regex_internal
     libc.src.__support.regex.regex_parser
 )
diff --git a/libc/src/regex/regfree.cpp b/libc/src/regex/regfree.cpp
index 9aa64aafd770f7..1b561135985155 100644
--- a/libc/src/regex/regfree.cpp
+++ b/libc/src/regex/regfree.cpp
@@ -23,9 +23,10 @@ namespace LIBC_NAMESPACE_DECL {
 
 LLVM_LIBC_FUNCTION(void, regfree, (regex_t * preg)) {
   LIBC_CRASH_ON_NULLPTR(preg);
-  delete static_cast<regex::RegexInternal *>(preg->__internal);
+  auto *internal = static_cast<regex::RegexInternal *>(preg->__internal);
   preg->__internal = nullptr;
   preg->re_nsub = 0;
+  delete internal;
 }
 
 } // namespace LIBC_NAMESPACE_DECL
diff --git a/libc/test/src/__support/regex/matcher_test.cpp b/libc/test/src/__support/regex/matcher_test.cpp
index 0eb717be4dca68..42ab4f0eba842d 100644
--- a/libc/test/src/__support/regex/matcher_test.cpp
+++ b/libc/test/src/__support/regex/matcher_test.cpp
@@ -480,6 +480,19 @@ TEST(LlvmLibcRegexMatcherTest, BracketMatchingAndRanges) {
   ASSERT_TRUE(multi_class.has_value());
   EXPECT_EQ(match(pool, *multi_class, "Hello World"), MatchResult::Match);
   EXPECT_EQ(match(pool, *multi_class, "Hello1World"), MatchResult::NoMatch);
+
+  // Equivalent bracket permutations deduplicate to the same ByteSet ExprId.
+  {
+    ExprPool dedup_pool;
+    ErrorOr<ExprId> cls_ab =
+        parse_ere("[[:alpha:][:blank:]]", REG_EXTENDED, dedup_pool);
+    ErrorOr<ExprId> cls_ba =
+        parse_ere("[[:blank:][:alpha:]]", REG_EXTENDED, dedup_pool);
+    ASSERT_TRUE(cls_ab.has_value());
+    ASSERT_TRUE(cls_ba.has_value());
+    EXPECT_EQ(*cls_ab, *cls_ba);
+    EXPECT_EQ(dedup_pool.num_byte_sets(), size_t(1));
+  }
 }
 
 TEST(LlvmLibcRegexMatcherTest, PoolExhaustionPropagation) {



More information about the libc-commits mailing list