Resubmitting to obtain a review from Sashiko.
Changes in v2:
- Reduced verbosity of code comments and commit messages.
- In patch 3/6, renamed _M_target_if to _M_fast_target and other small
simplifications.
-- >8 --
The DFS precheck added in r17-4554-gded7c4e851228c walks the
non-consuming prefix of the NFA and checks assertions at each start
position. Most of that work is common to all positions.
If the initial attempt fails and the search can advance, walk the NFA
once to collect candidate first match states. Skip a later position if
none of those states accepts its character. Cache that decision on
demand for 8-bit character types. The filter works in both DFS and BFS.
At later positions, match_prev_avail rules out non-multiline ^. The walk
assumes all other assertions succeed; the executor checks them when it
tries a position. If the walk reaches an accept state or a backreference
before consuming input, try every remaining position, including the end.
A backreference after the first consuming state does not disable the
filter.
Removing the precheck from _M_search_from_first also removes it from
the initial attempt and lookahead subsearches. The new filter's state
is local to _M_search, so the layout of _Executor is unchanged.
Benchmark (regex-benchmark's cpp/benchmark.cpp, i.e. sregex_token_iterator
over its 6.8 MB input-text.txt, median of 9 interleaved runs pinned to
one core, x86_64; master includes the old precheck):
master -O2 patch -O2 master -O3 patch -O3
Email 280.88 ms 240.70 ms 274.27 ms 237.15 ms
URI 233.36 ms 205.35 ms 232.38 ms 200.50 ms
IP 161.54 ms 9.92 ms 148.96 ms 9.29 ms
The IP pattern can only start with a digit, so almost every position is
rejected. The Email and URI patterns can start with any word character,
so most positions still enter the executor.
Calling regex_search separately on each of the file's 206K lines, where
the once-per-call cost of computing the filter matters more:
master -O2 patch -O2 master -O3 patch -O3
Email 293.13 ms 286.93 ms 289.24 ms 282.82 ms
URI 242.05 ms 240.63 ms 242.09 ms 236.94 ms
IP 159.92 ms 84.12 ms 172.57 ms 81.28 ms
PR libstdc++/126274
libstdc++-v3/ChangeLog:
* include/bits/regex_executor.h (_Executor::_M_search_from_first):
Remove _M_maybe_start_match precheck.
(_Executor::_M_maybe_start_match): Remove.
(_Executor::_M_first_states): Declare.
* include/bits/regex_executor.tcc (_Executor::_M_search): After
trying the initial position, skip start positions rejected by a
first-character filter.
(_Executor::_M_first_states): Define.
(_Executor::_M_maybe_start_match): Remove.
Assisted-by: Claude Opus 5.5
---
libstdc++-v3/include/bits/regex_executor.h | 24 +-
libstdc++-v3/include/bits/regex_executor.tcc | 230 +++++++++++--------
2 files changed, 132 insertions(+), 122 deletions(-)
diff --git a/libstdc++-v3/include/bits/regex_executor.h
b/libstdc++-v3/include/bits/regex_executor.h
index 51de0f52113..0e15d722ca6 100644
--- a/libstdc++-v3/include/bits/regex_executor.h
+++ b/libstdc++-v3/include/bits/regex_executor.h
@@ -108,28 +108,6 @@ _GLIBCXX_BEGIN_INLINE_ABI_NAMESPACE(_V2)
_M_search_from_first()
{
_M_current = _M_begin;
- // Fast reject for DFS prefix search. regex_search and
- // regex_token_iterator try the pattern at each possible starting
- // position. If the regex can only start with a digit, running the full
- // DFS executor at a space, letter, or punctuation character only builds
- // frames to discover the first match state rejects that character.
- //
- // Example: for the IPv4 pattern
- // (?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9])\.){3}...
- // a current input character of 'x' cannot match any first consuming
- // state. _M_maybe_start_match returns false and this starting position
- // is skipped. At '2' it returns true, because at least one branch
- // might match, so the normal executor still decides the complete
- // result.
- //
- // This is intentionally disabled for backreferences. Pruning the
- // search space for DFS reduces the number of frames we build and the
- // time to find an actual match.
- if (_M_search_mode == _Search_mode::_Dfs
- && !_M_nfa._M_has_backref
- && _M_current != _M_end
- && !_M_maybe_start_match(_M_start, 0))
- return false;
return _M_main(_Match_mode::_Prefix);
}
@@ -202,7 +180,7 @@ _GLIBCXX_BEGIN_INLINE_ABI_NAMESPACE(_V2)
_M_main_dfs(_Match_mode __match_mode);
bool
- _M_maybe_start_match(_StateIdT, size_t);
+ _M_first_states(_GLIBCXX_STD_C::vector<_StateIdT>&) const;
bool
_M_main_bfs(_Match_mode __match_mode);
diff --git a/libstdc++-v3/include/bits/regex_executor.tcc
b/libstdc++-v3/include/bits/regex_executor.tcc
index d4f7a2a4bd5..97787a0e565 100644
--- a/libstdc++-v3/include/bits/regex_executor.tcc
+++ b/libstdc++-v3/include/bits/regex_executor.tcc
@@ -40,18 +40,145 @@ namespace __detail
bool _Executor<_BiIter, _Alloc, _TraitsT>::
_M_search()
{
+ // The initial position can satisfy ^ even in non-multiline mode.
if (_M_search_from_first())
return true;
if (_M_flags & regex_constants::match_continuous)
return false;
_M_flags |= regex_constants::match_prev_avail;
- while (_M_begin != _M_end)
+ if (_M_begin == _M_end)
+ return false;
+
+ _GLIBCXX_STD_C::vector<_StateIdT> __first;
+ if (!_M_first_states(__first))
{
- ++_M_begin;
- if (_M_search_from_first())
+ // No filter; try every remaining position.
+ while (_M_begin != _M_end)
+ {
+ ++_M_begin;
+ if (_M_search_from_first())
+ return true;
+ }
+ return false;
+ }
+
+ // The filter rules out empty matches, so we can skip _M_end. With
+ // no candidate states, we can skip the scan altogether.
+ if (__first.empty())
+ return false;
+
+ auto __can_start = [this, &__first](_CharT __c) {
+ for (_StateIdT __i : __first)
+ if (_M_nfa[__i]._M_matches(__c))
return true;
+ return false;
+ };
+
+ // For 8-bit characters, cache __can_start per character value.
+ if constexpr (sizeof(_CharT) == 1 && __CHAR_BIT__ == 8
+ && is_integral<_CharT>::value
+ && !is_same<_CharT, bool>::value)
+ {
+ using _UCharT = typename make_unsigned<_CharT>::type;
+ // -1 = unknown, 0 = reject, 1 = accept. Fill on demand to avoid
+ // testing values absent from the input; uncached bracket matches
+ // can be expensive.
+ signed char __table[256];
+ __builtin_memset(__table, -1, sizeof(__table));
+ while (++_M_begin != _M_end)
+ {
+ const _CharT __c = *_M_begin;
+ signed char& __slot = __table[static_cast<_UCharT>(__c)];
+ if (__slot < 0)
+ __slot = __can_start(__c);
+ if (__slot && _M_search_from_first())
+ return true;
+ }
+ return false;
}
- return false;
+ else
+ {
+ while (++_M_begin != _M_end)
+ if (__can_start(*_M_begin) && _M_search_from_first())
+ return true;
+ return false;
+ }
+ }
+
+ // Collect candidate first match states by walking the NFA from _M_start
+ // without consuming input. At the positions being filtered,
+ // match_prev_avail is set, so a non-multiline ^ always fails. Assume all
+ // other assertions succeed to keep every possible first match state.
+ //
+ // Return false if the walk reaches an accept state (an empty match may be
+ // possible) or a backreference (which depends on captures). On success,
+ // an empty __first means no remaining position can match.
+ template<typename _BiIter, typename _Alloc, typename _TraitsT>
+ bool _Executor<_BiIter, _Alloc, _TraitsT>::
+ _M_first_states(_GLIBCXX_STD_C::vector<_StateIdT>& __first) const
+ {
+ const bool __multiline = _M_match_multiline();
+
+ // Every NFA cycle passes through a repeat state, so we can defer
+ // allocating the visited bitmap and the stack until the first
+ // alternative or repeat state. States before it aren't marked
+ // visited, but revisiting them via a back edge just leads back to
+ // that state, which is marked.
+ _GLIBCXX_STD_C::vector<bool> __visited;
+ _GLIBCXX_STD_C::vector<_StateIdT> __stack;
+ _StateIdT __i = _M_start;
+ while (true)
+ {
+ if (__i == _S_invalid_state_id
+ || (!__visited.empty() && __visited[__i]))
+ {
+ if (__stack.empty())
+ break;
+ __i = __stack.back();
+ __stack.pop_back();
+ continue;
+ }
+
+ const auto& __state = _M_nfa[__i];
+ _StateIdT __next = __state._M_next;
+ switch (__state._M_opcode())
+ {
+ case _S_opcode_alternative:
+ case _S_opcode_repeat:
+ if (__visited.empty())
+ {
+ __visited.resize(_M_nfa.size());
+ // Avoid repeated reallocation, which is significant when
+ // searching many short strings.
+ __stack.reserve(8);
+ __first.reserve(8);
+ }
+ __stack.push_back(__state._M_alt);
+ break;
+ case _S_opcode_match:
+ __first.push_back(__i);
+ __next = _S_invalid_state_id;
+ break;
+ case _S_opcode_line_begin_assertion:
+ if (!__multiline)
+ __next = _S_invalid_state_id;
+ break;
+ case _S_opcode_subexpr_begin:
+ case _S_opcode_subexpr_end:
+ case _S_opcode_line_end_assertion:
+ case _S_opcode_word_boundary:
+ case _S_opcode_subexpr_lookahead:
+ case _S_opcode_dummy:
+ break;
+ default: // accept, backref
+ return false;
+ }
+
+ if (!__visited.empty())
+ __visited[__i] = true;
+ __i = __next;
+ }
+ return true;
}
enum _ExecutorFrameOpcode : unsigned char
@@ -169,101 +296,6 @@ namespace __detail
return _M_has_sol;
}
- // Return whether a prefix search at _M_current might still match after
- // looking only through the non-consuming front of the NFA.
- //
- // This is not a general implementation. It is deliberately small and
- // conservative: when it reaches a construct whose first consuming character
- // is hard to know cheaply, it returns true and lets the normal executor run.
- // The important fast paths are the common negative cases.
- //
- // Examples:
- // * Pattern "[0-9]+" at input 'x': the first _S_opcode_match rejects 'x',
- // so a full DFS search would only allocate/pop frames to fail. Return
- // false and let regex_search advance the starting position.
- //
- // * Pattern "[01]?[0-9]" at input '9': the optional [01] branch rejects,
- // but the skip branch can consume '9'. Return true and let DFS decide
- // the full match.
- //
- // * Pattern "foo|bar" at input 'b': one alternative rejects, the other can
- // start with 'b'. Return true.
- template<typename _BiIter, typename _Alloc, typename _TraitsT>
- bool _Executor<_BiIter, _Alloc, _TraitsT>::
- _M_maybe_start_match(_StateIdT __i, size_t __depth)
- {
- // Depth is bounded by the NFA size so epsilon cycles cannot make the
- // precheck recurse forever. Hitting the bound means "unknown", not
- // "no match", so stay conservative and run the real executor. This is
- // important for patterns such as "(a*)*" where epsilon paths can cycle
- // before a consuming state is reached.
- if (__depth > _M_nfa.size())
- return true;
-
- // An invalid edge is a real dead end for the explored path.
- if (__i == _S_invalid_state_id)
- return false;
-
- const auto& __state = _M_nfa[__i];
- switch (__state._M_opcode())
- {
- case _S_opcode_match:
- return __state._M_matches(*_M_current);
-
- case _S_opcode_accept:
- // Empty matches are possible, so the full executor must decide.
- return true;
-
- case _S_opcode_subexpr_begin:
- case _S_opcode_subexpr_end:
- case _S_opcode_dummy:
- // Captures and dummy states do not consume input, so they cannot
- // affect the first-character decision. Continue along the only
- // successor.
- return _M_maybe_start_match(__state._M_next, __depth + 1);
-
- case _S_opcode_line_begin_assertion:
- // Assertions do not consume characters, but they can reject the
- // current position. For "^abc" at a non-begin position, there is no
- // need to run DFS merely to discover that ^ fails.
- return _M_at_begin()
- && _M_maybe_start_match(__state._M_next, __depth + 1);
-
- case _S_opcode_line_end_assertion:
- // Same idea for "$": if the assertion does not hold here, this
- // starting position cannot match via this path.
- return _M_at_end()
- && _M_maybe_start_match(__state._M_next, __depth + 1);
-
- case _S_opcode_word_boundary:
- // Word-boundary assertions are also checked before the first
- // consuming state. For "\bfoo" in the middle of "xfoo", this path
- // rejects before testing 'f'.
- return _M_word_boundary() == !__state._M_neg
- && _M_maybe_start_match(__state._M_next, __depth + 1);
-
- case _S_opcode_alternative:
- // A branch might match if either arm can start with *_M_current.
- // Example: "foo|bar" at 'b' rejects the "foo" arm but keeps the
- // search because the "bar" arm is viable.
- return _M_maybe_start_match(__state._M_alt, __depth + 1)
- || _M_maybe_start_match(__state._M_next, __depth + 1);
-
- case _S_opcode_repeat:
- // Repeats can either enter the body or skip to the exit, so inspect
- // both paths. This matters for constructs such as "[01]?[0-9]": at
- // '9' the optional first digit can be skipped, while at 'x' both
- // paths reject.
- return _M_maybe_start_match(__state._M_alt, __depth + 1)
- || _M_maybe_start_match(__state._M_next, __depth + 1);
-
- case _S_opcode_backref:
- case _S_opcode_subexpr_lookahead:
- default:
- return true;
- }
- }
-
// ------------------------------------------------------------
//
// BFS mode:
--
2.56.1