Skip to content

Commit b92d6a6

Browse files
committed
Extend first-character filter to support some rope strings
https://bugs.webkit.org/show_bug.cgi?id=328389 rdar://190653722 Reviewed by Yusuke Suzuki. The first-character filter added in 317836@main lets DFG and FTL quickly bail out when a regex mismatches on the 0th byte, without calling into C++. This patch extends that to two new scenarios: 1. DFG and FTL can now read the first byte of 8-bit substring ropes; previously, any rope access would require an operation call. This doesn't cover 16-bit strings or concatenation ropes. 2. DFG RegExpMatchFast now references the first-character table at codegen time for known regexes. Previously RegExpMatchFast always lowered to an operation call. FTL already had to know how to read substring ropes in order to do string switch lowering, so this patch pulls out that logic into a shared helper. Altogether this patch speeds up lexer-style code which tries a chain of anchored patterns on successive slices. Test: regexp-anchored-first-char-filter-substring-rope.js * Source/JavaScriptCore/dfg/DFGSpeculativeJIT.cpp: (JSC::DFG::SpeculativeJIT::compileRegExpMatchFast): (JSC::DFG::SpeculativeJIT::emitSwitchStringOnString): * Source/JavaScriptCore/dfg/DFGSpeculativeJIT64.cpp: (JSC::DFG::SpeculativeJIT::emitRegExpAnchoredFirstCharacterFilterGuards): * Source/JavaScriptCore/ftl/FTLLowerDFGToB3.cpp: (JSC::FTL::DFG::LowerDFGToB3::compileCompareStrictEq): * JSTests/stress/regexp-anchored-first-char-filter-substring-rope.js: Added. (shouldBe): (match): (check): (i.re.lastIndex.i.100.0.valueOf): (k.lastIndexes.push.k.0.valueOf): (exec): (classify.scan): (classify): Canonical link: https://commits.webkit.org/324726@main
1 parent adc1832 commit b92d6a6

4 files changed

Lines changed: 219 additions & 20 deletions

File tree

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
// Anchored first-character filter on substring-rope inputs (slice()/substring()), including
2+
// String.prototype.match with a RegExp known only after inlining.
3+
4+
function shouldBe(actual, expected) {
5+
if (actual !== expected)
6+
throw new Error("bad value: " + actual + " expected: " + expected);
7+
}
8+
9+
function match(re, s) {
10+
var m = s.match(re);
11+
return m === null ? null : m[0];
12+
}
13+
14+
var base = "";
15+
for (var i = 0; i < 2000; ++i)
16+
base += "foo 0x1F ~\n";
17+
base.charCodeAt(0); // Resolve it, so slices are substring ropes.
18+
var base16 = "foo ☃\n".repeat(2000);
19+
20+
for (var i = 0; i < testLoopCount; ++i) {
21+
var offset = (i % 1000) * 11;
22+
shouldBe(match(/^foo/, base.slice(offset)), "foo");
23+
shouldBe(match(/^0x\w+/, base.substring(offset + 4)), "0x1F");
24+
shouldBe(match(/^#/, base.slice(offset + 9)), null); // filtered
25+
shouldBe(/^~/.test(base.slice(offset + 9)), true);
26+
shouldBe(/^0x/.exec(base.slice(offset)), null); // filtered
27+
28+
// Concatenation ropes and 16-bit substrings are not read in place, but must still be right.
29+
shouldBe(match(/^~/, base.slice(offset + 9) + base), "~");
30+
shouldBe(match(/^foo/, base16.slice((i % 1000) * 6)), "foo");
31+
shouldBe(match(/^foo/, base16.slice((i % 1000) * 6 + 4)), null);
32+
}
33+
34+
// The match filter must leave a non-int32 lastIndex to the operation (reading it is observable).
35+
// The fresh literal reaches s.match() through an inlined helper with no branch in between, so DFG
36+
// can only choose its filter at codegen time.
37+
var valueOfCalls = 0;
38+
var lastIndexes = [];
39+
for (var k = 0; k < 100; ++k)
40+
lastIndexes.push(k ? 0 : { valueOf() { ++valueOfCalls; return 0; } });
41+
for (var i = 0; i < testLoopCount; ++i) {
42+
var r = /^a/;
43+
r.lastIndex = lastIndexes[i % 100];
44+
shouldBe(match(r, "b"), null);
45+
}
46+
shouldBe(valueOfCalls, Math.ceil(testLoopCount / 100));
47+
48+
// A substring rope's base can change width after the rope is created: atomizing an 8-bit base can swap in an
49+
// existing 16-bit atom with the same (Latin-1) content. The filter must use the base's current width.
50+
(function () {
51+
var length = 3000; // Longer than maxLengthForOnStackResolve, so the 16-bit slice keys a 16-bit atom.
52+
var wide = "☃" + "o".repeat(length);
53+
wide.charCodeAt(0); // Resolve it, so the slice shares its 16-bit buffer instead of copying and narrowing.
54+
var key16 = wide.slice(1);
55+
var object = { };
56+
object[key16] = 1;
57+
var base8 = "o".repeat(length);
58+
base8.charCodeAt(0);
59+
var slice = base8.slice(1);
60+
function exec(s) { return /^o/.exec(s) !== null; }
61+
for (var i = 0; i < testLoopCount; ++i) {
62+
shouldBe(exec(base8.slice(1 + (i % 7))), true);
63+
shouldBe(match(/^o/, base8.slice(1 + (i % 7))), "o");
64+
}
65+
object[base8] = 2; // base8 now holds the 16-bit atom; `slice` still says 8-bit.
66+
shouldBe(exec(slice), true);
67+
shouldBe(match(/^o/, slice), "o");
68+
})();
69+
70+
// The filter must read at the substring's offset: here base[offset] can begin a match but base[0] cannot.
71+
var hashed = "#" + "foo bar\n".repeat(500);
72+
hashed.charCodeAt(0);
73+
for (var i = 0; i < testLoopCount; ++i) {
74+
var offset = 1 + (i % 400) * 8;
75+
shouldBe(match(/^foo/, hashed.slice(offset)), "foo");
76+
shouldBe(/^#/.test(hashed.slice(offset)), false);
77+
}
78+
79+
// String.prototype.match on substring-rope input, through a lexer-style chain of anchored literals passed to a
80+
// nested helper. (Here DFG strength-reduces the match to the filtered exec form; the codegen-time RegExpMatchFast
81+
// filter is covered by the lastIndex test above.)
82+
function classify(str) {
83+
function scan(s, re) { return s.match(re); }
84+
var m;
85+
if (m = scan(str, /^#/))
86+
return "comment";
87+
else if (m = scan(str, /^0x[0-9a-fA-F]+/))
88+
return m[0];
89+
else if (m = scan(str, /^[a-z]+/))
90+
return m[0];
91+
return null;
92+
}
93+
for (var i = 0; i < testLoopCount; ++i) {
94+
var offset = (i % 1000) * 11;
95+
shouldBe(classify(base.slice(offset)), "foo");
96+
shouldBe(classify(base.slice(offset + 4)), "0x1F");
97+
shouldBe(classify(base.slice(offset + 9)), null);
98+
}
99+
100+
// The filter must not outlive a .compile() of the RegExp it baked in. Keep this last: a .compile() fires the
101+
// realm's RegExp-recompiled watchpoint, after which newly compiled code gets no filter at all.
102+
var re = /^a/;
103+
function check(s) { return s.match(re) !== null; }
104+
for (var i = 0; i < testLoopCount; ++i)
105+
shouldBe(check("b"), false);
106+
re.compile("^b");
107+
shouldBe(check("b"), true);

‎Source/JavaScriptCore/dfg/DFGSpeculativeJIT.cpp‎

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12833,11 +12833,12 @@ void SpeculativeJIT::emitSwitchStringOnString(Node* node, SwitchData* data, GPRR
1283312833
isRopeCases.link(this);
1283412834
JumpList notReadableInPlace;
1283512835
notReadableInPlace.append(branchTest64(Zero, tempGPR, TrustedImm64(JSRopeString::isSubstringInPointer)));
12836-
notReadableInPlace.append(branchTest64(Zero, tempGPR, TrustedImm64(JSRopeString::is8BitInPointer)));
1283712836

1283812837
load64(Address(stringGPR, JSRopeString::offsetOfFiber1Lower()), tempGPR);
1283912838
and64(TrustedImm64(JSRopeString::CompactFibers::addressMask), tempGPR);
1284012839
loadPtr(Address(tempGPR, JSString::offsetOfValue()), tempGPR);
12840+
// The base's current impl decides the width; the rope's cached is8BitInPointer can be stale.
12841+
notReadableInPlace.append(branchTest32(Zero, Address(tempGPR, StringImpl::flagsOffset()), TrustedImm32(StringImpl::flagIs8Bit())));
1284112842

1284212843
load32(Address(stringGPR, JSRopeString::offsetOfFiber2Lower()), lengthGPR);
1284312844
loadPtr(Address(tempGPR, StringImpl::dataOffset()), tempGPR);
@@ -13757,6 +13758,40 @@ void SpeculativeJIT::compileRegExpMatchFast(Node* node)
1375713758
speculateRegExpObject(node->child2(), baseGPR);
1375813759
speculateString(node->child3(), argumentGPR);
1375913760

13761+
// Anchored non-global non-sticky match fast-fail; tests input[0]. Strength reduction normally turns
13762+
// this node into RegExpExecNonGlobalOrSticky, which has the same filter, but it can miss a RegExp
13763+
// that only becomes visible after later phases (e.g. a literal passed into an inlined helper).
13764+
if (const auto* localBitmap = m_graph.tryGetConstantRegExpFirstCharacterBitmap(node->child2().node(), FirstCharacterFilterPosition::AtStart)) {
13765+
GPRTemporary result(this);
13766+
GPRTemporary scratch1(this);
13767+
GPRTemporary scratch2(this);
13768+
GPRReg resultGPR = result.gpr();
13769+
GPRReg scratch1GPR = scratch1.gpr();
13770+
GPRReg scratch2GPR = scratch2.gpr();
13771+
13772+
// baseGPR/argumentGPR/globalObjectGPR are preserved across flushRegisters for the slow-path
13773+
// operation call; the scratch registers are free to clobber.
13774+
flushRegisters();
13775+
13776+
JumpList slowCases;
13777+
JumpList doneCases;
13778+
13779+
// Reading a non-int32 lastIndex may be observable, so leave that to the operation.
13780+
load64(Address(baseGPR, RegExpObject::offsetOfLastIndex()), scratch1GPR);
13781+
slowCases.append(branchIfNotInt32(scratch1GPR));
13782+
emitRegExpAnchoredFirstCharacterFilterGuards(localBitmap->storageBytes().data(), argumentGPR, scratch1GPR, scratch2GPR, resultGPR, slowCases);
13783+
13784+
move(TrustedImm64(JSValue::encode(jsNull())), resultGPR);
13785+
doneCases.append(jump());
13786+
13787+
slowCases.link(this);
13788+
callOperation(operationRegExpMatchFastString, resultGPR, globalObjectGPR, baseGPR, argumentGPR);
13789+
13790+
doneCases.link(this);
13791+
jsValueResult(resultGPR, node);
13792+
return;
13793+
}
13794+
1376013795
flushRegisters();
1376113796
GPRFlushedCallResult result(this);
1376213797
GPRReg resultGPR = result.gpr();

‎Source/JavaScriptCore/dfg/DFGSpeculativeJIT64.cpp‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9752,15 +9752,32 @@ void SpeculativeJIT::emitRegExpAnchoredFirstCharacterFilterGuards(const uint8_t*
97529752
{
97539753
ASSERT(noOverlap(argumentGPR, scratch1GPR, scratch2GPR, scratch3GPR));
97549754

9755-
// The string must be a resolved 8-bit string.
9755+
// The string must be an 8-bit resolved string or a substring rope of an 8-bit base (which is always resolved).
97569756
loadPtr(Address(argumentGPR, JSString::offsetOfValue()), scratch1GPR);
9757-
slowCases.append(branchIfRopeStringImpl(scratch1GPR));
9757+
Jump isRope = branchIfRopeStringImpl(scratch1GPR);
97589758
slowCases.append(branchTest32(Zero, Address(scratch1GPR, StringImpl::flagsOffset()), TrustedImm32(StringImpl::flagIs8Bit())));
97599759

97609760
// An anchored pattern that reaches here cannot match empty, so delegate an empty string.
97619761
slowCases.append(branchTest32(Zero, Address(scratch1GPR, StringImpl::lengthMemoryOffset())));
97629762

97639763
loadPtr(Address(scratch1GPR, StringImpl::dataOffset()), scratch1GPR);
9764+
Jump haveCharacters = jump();
9765+
9766+
// Reading a substring rope in place avoids resolving it, matching what the operation would do.
9767+
isRope.link(this);
9768+
slowCases.append(branchTest64(Zero, scratch1GPR, TrustedImm64(JSRopeString::isSubstringInPointer)));
9769+
slowCases.append(branchTest32(Zero, Address(argumentGPR, JSRopeString::offsetOfLength())));
9770+
load64(Address(argumentGPR, JSRopeString::offsetOfFiber1Lower()), scratch1GPR);
9771+
and64(TrustedImm64(JSRopeString::CompactFibers::addressMask), scratch1GPR);
9772+
loadPtr(Address(scratch1GPR, JSString::offsetOfValue()), scratch1GPR);
9773+
// Take the width from the base's current impl, not the rope's cached is8BitInPointer: atomizing the base can
9774+
// swap in an existing atom of the other width after the rope was created.
9775+
slowCases.append(branchTest32(Zero, Address(scratch1GPR, StringImpl::flagsOffset()), TrustedImm32(StringImpl::flagIs8Bit())));
9776+
loadPtr(Address(scratch1GPR, StringImpl::dataOffset()), scratch1GPR);
9777+
load32(Address(argumentGPR, JSRopeString::offsetOfFiber2Lower()), scratch2GPR);
9778+
addPtr(scratch2GPR, scratch1GPR);
9779+
9780+
haveCharacters.link(this);
97649781
load8(Address(scratch1GPR), scratch2GPR);
97659782
emitFirstCharacterBitmapMatch(bitmap, scratch2GPR, scratch1GPR, scratch3GPR, slowCases);
97669783
}

‎Source/JavaScriptCore/ftl/FTLLowerDFGToB3.cpp‎

Lines changed: 57 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -19351,6 +19351,26 @@ IGNORE_CLANG_WARNINGS_END
1935119351
setJSValue(result);
1935219352
}
1935319353

19354+
// For a JSRopeString known to be a substring rope: the current StringImpl of its base (which is always resolved)
19355+
// and the substring's offset into it. Callers must check that impl's width rather than the rope's cached
19356+
// is8BitInPointer, since atomizing the base can swap in an existing atom of the other width after the rope was
19357+
// created. For an 8-bit impl, the first character is at StringImpl_data + offset.
19358+
std::pair<LValue, LValue> substringRopeBaseImplAndOffset(LValue rope)
19359+
{
19360+
LValue packedLengthAndBaseLower = m_out.load64(rope, m_heaps.JSRopeString_fiber1);
19361+
LValue packedBaseUpperAndOffset = m_out.load64(rope, m_heaps.JSRopeString_fiber2);
19362+
LValue substringBase = m_out.bitOr(
19363+
m_out.lShr(packedLengthAndBaseLower, m_out.constInt32(32)),
19364+
m_out.shl(m_out.bitAnd(packedBaseUpperAndOffset, m_out.constInt64(0xffff)), m_out.constInt32(32)));
19365+
LValue substringOffset = m_out.lShr(packedBaseUpperAndOffset, m_out.constInt32(16));
19366+
return { m_out.loadPtr(substringBase, m_heaps.JSString_value), substringOffset };
19367+
}
19368+
19369+
LValue isNot8BitStringImpl(LValue stringImpl)
19370+
{
19371+
return m_out.testIsZero32(m_out.load32(stringImpl, m_heaps.StringImpl_hashAndFlags), m_out.constInt32(StringImpl::flagIs8Bit()));
19372+
}
19373+
1935419374
// Nonzero iff `character` (0..255) might begin a match per the first-character `bitmap`.
1935519375
LValue firstCharacterBitmapContains(LValue character, const uint8_t* bitmap)
1935619376
{
@@ -19378,12 +19398,17 @@ IGNORE_CLANG_WARNINGS_END
1937819398
LBasicBlock isStringCase = knownString ? nullptr : m_out.newBlock();
1937919399
LBasicBlock check8Bit = m_out.newBlock();
1938019400
LBasicBlock checkLength = m_out.newBlock();
19401+
LBasicBlock resolvedCase = m_out.newBlock();
19402+
LBasicBlock ropeCase = m_out.newBlock();
19403+
LBasicBlock substringCheck8Bit = m_out.newBlock();
19404+
LBasicBlock substringCheckLength = m_out.newBlock();
19405+
LBasicBlock substringCase = m_out.newBlock();
1938119406
LBasicBlock filterCase = m_out.newBlock();
1938219407

1938319408
if (!knownString)
1938419409
emitFirstCharacterGuardStringCheck(argument, argumentEdge, isCellCase, isStringCase, check8Bit, operationCase);
1938519410

19386-
m_out.branch(isRopeString(argument, argumentEdge), rarely(operationCase), usually(check8Bit));
19411+
m_out.branch(isRopeString(argument, argumentEdge), rarely(ropeCase), usually(check8Bit));
1938719412

1938819413
m_out.appendTo(check8Bit, checkLength);
1938919414
LValue stringImpl = m_out.loadPtr(argument, m_heaps.JSString_value);
@@ -19394,12 +19419,36 @@ IGNORE_CLANG_WARNINGS_END
1939419419
rarely(operationCase), usually(checkLength));
1939519420

1939619421
// An anchored pattern that reaches here cannot match empty, so delegate an empty string.
19397-
m_out.appendTo(checkLength, filterCase);
19398-
m_out.branch(m_out.equal(m_out.load32(stringImpl, m_heaps.StringImpl_length), m_out.int32Zero), rarely(operationCase), usually(filterCase));
19422+
m_out.appendTo(checkLength, resolvedCase);
19423+
m_out.branch(m_out.equal(m_out.load32(stringImpl, m_heaps.StringImpl_length), m_out.int32Zero), rarely(operationCase), usually(resolvedCase));
1939919424

19400-
m_out.appendTo(filterCase, noMatchCase);
19425+
m_out.appendTo(resolvedCase, ropeCase);
1940119426
LValue stringData = m_out.loadPtr(stringImpl, m_heaps.StringImpl_data);
19402-
LValue character = m_out.load8ZeroExt32(m_out.baseIndex(m_heaps.characters8, stringData, m_out.constIntPtr(0)));
19427+
ValueFromBlock resolvedCharacter = m_out.anchor(m_out.load8ZeroExt32(m_out.baseIndex(m_heaps.characters8, stringData, m_out.constIntPtr(0))));
19428+
m_out.jump(filterCase);
19429+
19430+
// A substring rope (what slice() and substring() produce) is readable in place through its base, just
19431+
// as the operation would read it, so there is no need to delegate it. Other ropes still are.
19432+
m_out.appendTo(ropeCase, substringCheck8Bit);
19433+
LValue fiber0 = m_out.loadPtr(argument, m_heaps.JSRopeString_fiber0);
19434+
m_out.branch(
19435+
m_out.testIsZeroPtr(fiber0, m_out.constIntPtr(JSRopeString::isSubstringInPointer)),
19436+
unsure(operationCase), unsure(substringCheck8Bit));
19437+
19438+
m_out.appendTo(substringCheck8Bit, substringCheckLength);
19439+
auto [baseImpl, substringOffset] = substringRopeBaseImplAndOffset(argument);
19440+
m_out.branch(isNot8BitStringImpl(baseImpl), unsure(operationCase), unsure(substringCheckLength));
19441+
19442+
m_out.appendTo(substringCheckLength, substringCase);
19443+
m_out.branch(m_out.equal(m_out.load32NonNegative(argument, m_heaps.JSRopeString_length), m_out.int32Zero), rarely(operationCase), usually(substringCase));
19444+
19445+
m_out.appendTo(substringCase, filterCase);
19446+
LValue substringCharacters = m_out.add(m_out.loadPtr(baseImpl, m_heaps.StringImpl_data), substringOffset);
19447+
ValueFromBlock substringCharacter = m_out.anchor(m_out.load8ZeroExt32(m_out.baseIndex(m_heaps.characters8, substringCharacters, m_out.constIntPtr(0))));
19448+
m_out.jump(filterCase);
19449+
19450+
m_out.appendTo(filterCase, noMatchCase);
19451+
LValue character = m_out.phi(Int32, resolvedCharacter, substringCharacter);
1940319452
m_out.branch(firstCharacterBitmapContains(character, bitmap), unsure(operationCase), unsure(noMatchCase));
1940419453
}
1940519454

@@ -24229,20 +24278,11 @@ IGNORE_CLANG_WARNINGS_END
2422924278
unsure(concatRopeBlock), unsure(isSubstringBlock));
2423024279

2423124280
m_out.appendTo(isSubstringBlock, substringBlock);
24232-
m_out.branch(
24233-
m_out.testIsZeroPtr(fiber0, m_out.constIntPtr(JSRopeString::is8BitInPointer)),
24234-
unsure(concatRopeBlock), unsure(substringBlock));
24281+
auto [baseImpl, substringOffset] = substringRopeBaseImplAndOffset(string);
24282+
m_out.branch(isNot8BitStringImpl(baseImpl), unsure(concatRopeBlock), unsure(substringBlock));
2423524283

2423624284
m_out.appendTo(substringBlock, concatRopeBlock);
24237-
LValue packedLengthAndBaseLower = m_out.load64(string, m_heaps.JSRopeString_fiber1);
24238-
LValue packedBaseUpperAndOffset = m_out.load64(string, m_heaps.JSRopeString_fiber2);
24239-
LValue substringBase = m_out.bitOr(
24240-
m_out.lShr(packedLengthAndBaseLower, m_out.constInt32(32)),
24241-
m_out.shl(m_out.bitAnd(packedBaseUpperAndOffset, m_out.constInt64(0xffff)), m_out.constInt32(32)));
24242-
LValue substringOffset = m_out.lShr(packedBaseUpperAndOffset, m_out.constInt32(16));
24243-
LValue baseImpl = m_out.loadPtr(substringBase, m_heaps.JSString_value);
24244-
ValueFromBlock substringBuffer = m_out.anchor(
24245-
m_out.add(m_out.loadPtr(baseImpl, m_heaps.StringImpl_data), substringOffset));
24285+
ValueFromBlock substringBuffer = m_out.anchor(m_out.add(m_out.loadPtr(baseImpl, m_heaps.StringImpl_data), substringOffset));
2424624286
ValueFromBlock substringLength = m_out.anchor(m_out.load32NonNegative(string, m_heaps.JSRopeString_length));
2424724287
m_out.jump(binarySwitchBlock);
2424824288

0 commit comments

Comments
 (0)