Skip to content

Commit 8bd3c1b

Browse files
committed
[JSC] Inline string === "constant"
https://bugs.webkit.org/show_bug.cgi?id=327641 rdar://190087771 Reviewed by Sosuke Suzuki. This patch optimizes string === "constant" in FTL. When "constant" is <= 16 length and it is 8bit, we extract string's data, checking length and do inlined comparison as they are small enough to check. We do is BitOr(BitXor(slice0, "constant"), BitXor(slice1, "string")) we use BitXor since this is efficient compared to Equal() which requires cmp and cset. In addition, in ARM64, we add B3 lowering rule which detects the above sequence and converts them to ccmp and cmp chain. Tests: JSTests/stress/string-strict-equal-short-constant.js Source/JavaScriptCore/b3/testb3_1.cpp Source/JavaScriptCore/b3/testb3_8.cpp * JSTests/stress/string-strict-equal-short-constant-stale-8bit-substring.js: Added. (test): * JSTests/stress/string-strict-equal-short-constant.js: Added. (shouldBe): (test0): (test1): (test2): (test3): (test4): (test5): (test6): (test7): (test8): (test9): (test10): (test11): (test12): (test13): (test14): (test15): (test16): (test17): (keyword): (flatten): (candidates): (equalsByCharacter): (untyped): (notDouble): * Source/JavaScriptCore/assembler/MacroAssemblerARM64.h: (JSC::MacroAssemblerARM64::setOnFlags): * Source/JavaScriptCore/b3/B3LowerToAir.cpp: * Source/JavaScriptCore/b3/air/AirOpcode.opcodes: * Source/JavaScriptCore/b3/testb3.h: * Source/JavaScriptCore/b3/testb3_1.cpp: (run): * Source/JavaScriptCore/b3/testb3_8.cpp: (checkUsesXorOrCompareChain): (testXorOrCompareChain32): (testXorOrCompareChain64): (testXorOrCompareChainZExt64): (testXorOrCompareChainBitImmediate32): (testXorOrCompareChainBranch64): (testXorOrCompareChainBranchEqualZero32): (testXorOrCompareChainSharedLeaf32): (testXorOrCompareChainLoads64): * Source/JavaScriptCore/ftl/FTLLowerDFGToB3.cpp: (JSC::FTL::DFG::LowerDFGToB3::compileCompareStrictEq): Canonical link: https://commits.webkit.org/323912@main
1 parent 753a935 commit 8bd3c1b

9 files changed

Lines changed: 669 additions & 5 deletions
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
// A substring rope caches its base's 8-bit flag, but atomizing the base can swap in an equal 16-bit StringImpl.
2+
3+
function test(s) { return s === "abcde"; }
4+
noInline(test);
5+
6+
const warmBase = "abcdeXYZWVUTSRQPONMLKJIHGFEDCBA".split("").join("");
7+
warmBase.indexOf("#");
8+
const warmWide = "\u3042" + warmBase;
9+
warmWide.indexOf("#");
10+
const warm = [
11+
"abcde", "abcdf", warmBase.slice(0, 5), warmBase.slice(1, 6), warmWide.slice(1, 6),
12+
"xyz", warmBase.slice(0, 4) + "e",
13+
];
14+
const expected = [true, false, true, false, true, false, true];
15+
for (let i = 0; i < testLoopCount * 20; ++i) {
16+
const index = i % warm.length;
17+
if (test(warm[index]) !== expected[index])
18+
throw new Error("bad result for " + JSON.stringify(warm[index]));
19+
}
20+
21+
let content = "abcde";
22+
for (let i = 0; i < 75; ++i)
23+
content += String.fromCharCode(102 + ((i * 7) % 20));
24+
content.indexOf("#");
25+
26+
const sub = content.slice(0, 5);
27+
28+
const wide16 = ["", ("\u3042" + content).replace("\u3042", "")].join("");
29+
const object = {};
30+
object[wide16] = 1;
31+
object[content] = 2;
32+
33+
for (let i = 0; i < testLoopCount; ++i) {
34+
if (test(sub) !== true)
35+
throw new Error("substring of a base swapped to a 16-bit atom compared unequal");
36+
}
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
function shouldBe(actual, expected, string, atom) {
2+
if (actual !== expected)
3+
throw new Error("bad value: " + actual + " expected " + expected + " for " + JSON.stringify(string) + " === " + JSON.stringify(atom));
4+
}
5+
6+
const atoms = [
7+
"", "a", "if", "var", "this", "while", "return", "default", "function",
8+
"abcdefghi", "instanceof", "abcdefghijk", "abcdefghijkl", "abcdefghijklm",
9+
"abcdefghijklmn", "abcdefghijklmno", "abcdefghijklmnop", "abcdefghijklmnopq",
10+
];
11+
12+
function test0(s) { return s === ""; }
13+
function test1(s) { return s === "a"; }
14+
function test2(s) { return s === "if"; }
15+
function test3(s) { return s === "var"; }
16+
function test4(s) { return s === "this"; }
17+
function test5(s) { return s === "while"; }
18+
function test6(s) { return s === "return"; }
19+
function test7(s) { return s === "default"; }
20+
function test8(s) { return s === "function"; }
21+
function test9(s) { return "abcdefghi" === s; }
22+
function test10(s) { return s === "instanceof"; }
23+
function test11(s) { return s === "abcdefghijk"; }
24+
function test12(s) { return s === "abcdefghijkl"; }
25+
function test13(s) { return s === "abcdefghijklm"; }
26+
function test14(s) { return s === "abcdefghijklmn"; }
27+
function test15(s) { return s === "abcdefghijklmno"; }
28+
function test16(s) { return s === "abcdefghijklmnop"; }
29+
function test17(s) { return s === "abcdefghijklmnopq"; }
30+
const tests = [test0, test1, test2, test3, test4, test5, test6, test7, test8, test9, test10, test11, test12, test13, test14, test15, test16, test17];
31+
for (const test of tests)
32+
noInline(test);
33+
34+
function keyword(id) {
35+
switch (id.length) {
36+
case 5:
37+
return id === "while" || id === "break" || id === "catch" || id === "throw" || id === "const";
38+
default:
39+
return false;
40+
}
41+
}
42+
noInline(keyword);
43+
44+
function flatten(string) {
45+
string.indexOf("#");
46+
return string;
47+
}
48+
49+
const source8 = flatten(" " + atoms.join(" ") + " ");
50+
const source16 = flatten("\u3042" + source8);
51+
52+
function candidates(atom) {
53+
const result = [];
54+
for (const source of [source8, source16]) {
55+
const index = source.indexOf(" " + atom + " ") + 1;
56+
result.push([source.slice(index, index + atom.length), true]);
57+
}
58+
result.push([atom.split("").join(""), true]);
59+
if (atom.length) {
60+
const half = atom.length >> 1;
61+
result.push([atom.slice(0, half) + atom.slice(half), true]);
62+
result.push([flatten("\u3042" + atom + " ").slice(1, 1 + atom.length), true]);
63+
for (let i = 0; i < atom.length; ++i) {
64+
const mutated = atom.slice(0, i) + String.fromCharCode(atom.charCodeAt(i) ^ 1) + atom.slice(i + 1);
65+
result.push([mutated, false]);
66+
const wide = flatten("\u3042" + mutated + " ");
67+
result.push([wide.slice(1, 1 + atom.length), false]);
68+
const narrow = flatten("_" + mutated + " ");
69+
result.push([narrow.slice(1, 1 + atom.length), false]);
70+
}
71+
result.push([atom.slice(1), false]);
72+
result.push([source8.slice(2, 2 + atom.length + 1), false]);
73+
}
74+
result.push([atom + "x", false]);
75+
result.push([flatten("y" + atom + "x").slice(1), false]);
76+
return result;
77+
}
78+
79+
function equalsByCharacter(a, b) {
80+
if (a.length !== b.length)
81+
return false;
82+
for (let i = 0; i < a.length; ++i) {
83+
if (a.charCodeAt(i) !== b.charCodeAt(i))
84+
return false;
85+
}
86+
return true;
87+
}
88+
noDFG(equalsByCharacter);
89+
90+
const cases = atoms.map(candidates);
91+
const keywords = ["while", "break", "catch", "throw", "const"];
92+
const keywordCandidates = [...keywords, "whilf", "count", "const ", "wh", "xyzzy"];
93+
const keywordSource = flatten("." + keywordCandidates.join(".") + ".");
94+
const keywordSlices = keywordCandidates.map(word => {
95+
const index = keywordSource.indexOf("." + word + ".") + 1;
96+
return keywordSource.slice(index, index + word.length);
97+
});
98+
99+
function untyped(value) { return value === "while"; }
100+
noInline(untyped);
101+
function notDouble(value) { return "abcdefghij" === value; }
102+
noInline(notDouble);
103+
104+
const whileSource = flatten(".while.whilf.");
105+
const untypedValues = [
106+
[whileSource.slice(1, 6), true], [whileSource.slice(7, 12), false], ["wh" + "ile".split("").join(""), true],
107+
[flatten("\u3042while").slice(1), true], ["while", true], [42, false], [4.2, false], [undefined, false],
108+
[null, false], [{}, false], [Symbol(), false], [true, false], [10n, false],
109+
];
110+
const abcSource = flatten(".abcdefghij.abcdefghik.");
111+
const notDoubleValues = [
112+
[abcSource.slice(1, 11), true], [abcSource.slice(12, 22), false], ["abcde" + "fghij".split("").join(""), true],
113+
[flatten("\u3042abcdefghij").slice(1), true], ["abcdefghij", true], [42, false], [undefined, false],
114+
[null, false], [{}, false], [Symbol(), false], [false, false],
115+
];
116+
117+
for (let iteration = 0; iteration < testLoopCount; ++iteration) {
118+
for (let i = 0; i < tests.length; ++i) {
119+
const [string, expected] = cases[i][iteration % cases[i].length];
120+
shouldBe(tests[i](string), expected, string, atoms[i]);
121+
const other = cases[(i + 1) % tests.length];
122+
const otherString = other[iteration % other.length][0];
123+
shouldBe(tests[i](otherString), equalsByCharacter(otherString, atoms[i]), otherString, atoms[i]);
124+
}
125+
const index = iteration % keywordCandidates.length;
126+
shouldBe(keyword(keywordSlices[index]), keywords.includes(keywordCandidates[index]), keywordSlices[index], "keyword");
127+
128+
const [untypedValue, untypedExpected] = untypedValues[iteration % untypedValues.length];
129+
shouldBe(untyped(untypedValue), untypedExpected, String(untypedValue), "while");
130+
const [notDoubleValue, notDoubleExpected] = notDoubleValues[iteration % notDoubleValues.length];
131+
shouldBe(notDouble(notDoubleValue), notDoubleExpected, String(notDoubleValue), "abcdefghij");
132+
}

‎Source/JavaScriptCore/assembler/MacroAssemblerARM64.h‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5736,6 +5736,11 @@ class MacroAssemblerARM64 : public AbstractMacroAssembler<Assembler> {
57365736
return Jump(makeBranch(cond));
57375737
}
57385738

5739+
void setOnFlags(RelationalCondition cond, RegisterID dest)
5740+
{
5741+
m_assembler.cset<32>(dest, ARM64Condition(cond));
5742+
}
5743+
57395744
void test32(ResultCondition cond, RegisterID src, RegisterID mask, RegisterID dest)
57405745
{
57415746
m_assembler.tst<32>(src, mask);

‎Source/JavaScriptCore/b3/B3LowerToAir.cpp‎

Lines changed: 145 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2887,6 +2887,141 @@ class LowerToAir {
28872887
dataLogLnIf(B3LowerToAirInternal::verbose, " ccmp optimization successful!");
28882888
return true;
28892889
}
2890+
2891+
// A BitOr tree of BitXor leaves is zero exactly when every leaf's operands are equal, so it can be
2892+
// tested as cmp + ccmp chain instead of materializing the eor/orr tree.
2893+
bool collectXorOrChain(Value* value, Vector<Value*, 8>& leaves, Vector<Value*, 16>& internals)
2894+
{
2895+
// Each of the at most maxCompareChainSize + 1 leaves can carry a ZExt32, so this bounds both the
2896+
// node count and the recursion depth on long left-deep BitOr chains.
2897+
static constexpr unsigned maxNodes = 3 * (maxCompareChainSize + 1);
2898+
if (internals.size() >= maxNodes)
2899+
return false;
2900+
if (!value->type().isInt() || !canBeInternal(value))
2901+
return false;
2902+
internals.append(value);
2903+
switch (value->opcode()) {
2904+
case BitXor:
2905+
if (leaves.size() > maxCompareChainSize)
2906+
return false;
2907+
leaves.append(value);
2908+
return true;
2909+
case ZExt32:
2910+
return collectXorOrChain(value->child(0), leaves, internals);
2911+
case BitOr:
2912+
return collectXorOrChain(value->child(0), leaves, internals) && collectXorOrChain(value->child(1), leaves, internals);
2913+
default:
2914+
return false;
2915+
}
2916+
}
2917+
2918+
// On success, the flags satisfy Equal if value is zero and NotEqual otherwise.
2919+
bool tryAppendXorOrChainCompare(Value* value)
2920+
{
2921+
if (value->opcode() != BitOr)
2922+
return false;
2923+
2924+
Vector<Value*, 8> leaves;
2925+
Vector<Value*, 16> internals;
2926+
if (!collectXorOrChain(value, leaves, internals))
2927+
return false;
2928+
2929+
auto operands = [](Value* leaf) -> std::pair<Value*, Value*> {
2930+
if (leaf->child(0)->hasInt() && !leaf->child(1)->hasInt())
2931+
return { leaf->child(1), leaf->child(0) };
2932+
return { leaf->child(0), leaf->child(1) };
2933+
};
2934+
2935+
// cmp takes a much wider immediate than ccmp, so start with a constant only cmp can encode.
2936+
auto needsCompareImmediate = [&](Value* leaf) {
2937+
Value* right = operands(leaf).second;
2938+
return imm(right) && !isValidConditionalCompareImmediate(right->asInt());
2939+
};
2940+
if (!needsCompareImmediate(leaves[0])) {
2941+
for (unsigned i = 1; i < leaves.size(); ++i) {
2942+
if (needsCompareImmediate(leaves[i])) {
2943+
std::swap(leaves[0], leaves[i]);
2944+
break;
2945+
}
2946+
}
2947+
}
2948+
2949+
auto compareImmediate = [&](unsigned index) -> Arg {
2950+
Value* right = operands(leaves[index]).second;
2951+
Type type = leaves[index]->type();
2952+
if (!index) {
2953+
if (Arg rightImm = imm(right); rightImm && isValidForm(compareOnFlagsOpcodeForType(type), Arg::Tmp, Arg::Imm))
2954+
return rightImm;
2955+
return { };
2956+
}
2957+
if (right->hasInt() && isValidConditionalCompareImmediate(right->asInt()) && isValidForm(compareConditionallyOnFlagsOpcodeForType(type), Arg::Tmp, Arg::Imm, Arg::Imm, Arg::RelCond))
2958+
return imm(right);
2959+
return { };
2960+
};
2961+
2962+
// The cmp/ccmp chain saves one instruction per leaf over eor/orr + tst, but eor also encodes
2963+
// bitmask immediates, which cmp and ccmp would have to materialize into a register first.
2964+
unsigned extraMaterializations = 0;
2965+
for (unsigned i = 0; i < leaves.size(); ++i) {
2966+
Value* right = operands(leaves[i]).second;
2967+
if (!right->hasInt() || compareImmediate(i))
2968+
continue;
2969+
bool is32Bit = leaves[i]->type() == Int32;
2970+
uint64_t bits = is32Bit ? static_cast<uint32_t>(right->asInt()) : static_cast<uint64_t>(right->asInt());
2971+
if (!(is32Bit ? Arg::isValidBitImmForm(right->asInt()) : Arg::isValidBitImm64Form(right->asInt())))
2972+
continue;
2973+
unsigned halfwords = is32Bit ? 2 : 4;
2974+
unsigned zeroHalfwords = 0;
2975+
unsigned onesHalfwords = 0;
2976+
for (unsigned j = 0; j < halfwords; ++j) {
2977+
uint16_t halfword = static_cast<uint16_t>(bits >> (16 * j));
2978+
zeroHalfwords += !halfword;
2979+
onesHalfwords += halfword == 0xffff;
2980+
}
2981+
extraMaterializations += std::max(1u, halfwords - std::max(zeroHalfwords, onesHalfwords));
2982+
}
2983+
if (extraMaterializations >= leaves.size())
2984+
return false;
2985+
2986+
for (Value* internal : internals)
2987+
commitInternal(internal);
2988+
2989+
auto [firstLeft, firstRight] = operands(leaves[0]);
2990+
if (Arg rightImm = compareImmediate(0))
2991+
append(compareOnFlagsOpcodeForType(leaves[0]->type()), tmp(firstLeft), rightImm);
2992+
else
2993+
append(compareOnFlagsOpcodeForType(leaves[0]->type()), tmp(firstLeft), tmp(firstRight));
2994+
2995+
Arg mismatchFlags = imm(nzcvForCondition(MacroAssembler::NotEqual));
2996+
for (unsigned i = 1; i < leaves.size(); ++i) {
2997+
auto [left, right] = operands(leaves[i]);
2998+
Air::Opcode ccmpOpcode = compareConditionallyOnFlagsOpcodeForType(leaves[i]->type());
2999+
if (Arg rightImm = compareImmediate(i))
3000+
append(ccmpOpcode, tmp(left), rightImm, mismatchFlags, Arg::relCond(MacroAssembler::Equal));
3001+
else
3002+
append(ccmpOpcode, tmp(left), tmp(right), mismatchFlags, Arg::relCond(MacroAssembler::Equal));
3003+
}
3004+
return true;
3005+
}
3006+
3007+
bool tryEmitXorOrChainBranch(Value* branchValue)
3008+
{
3009+
Value* condition = branchValue->child(0);
3010+
MacroAssembler::RelationalCondition branchCondition = MacroAssembler::NotEqual;
3011+
Value* comparison = nullptr;
3012+
if ((condition->opcode() == Equal || condition->opcode() == NotEqual) && condition->child(1)->isInt(0)) {
3013+
if (condition->opcode() == Equal)
3014+
branchCondition = MacroAssembler::Equal;
3015+
comparison = condition;
3016+
condition = condition->child(0);
3017+
}
3018+
3019+
if (!tryAppendXorOrChainCompare(condition))
3020+
return false;
3021+
commitInternal(comparison);
3022+
append(Air::BranchOnFlags, Arg::relCond(branchCondition));
3023+
return true;
3024+
}
28903025
#endif // CPU(ARM64)
28913026

28923027
Inst createBranch(Value* value, bool inverted = false)
@@ -5943,7 +6078,14 @@ class LowerToAir {
59436078
appendCAS(m_value->child(0), m_value->opcode() == NotEqual);
59446079
return;
59456080
}
5946-
6081+
6082+
#if CPU(ARM64)
6083+
if (m_value->child(1)->isInt(0) && tryAppendXorOrChainCompare(m_value->child(0))) {
6084+
append(Air::SetOnFlags, Arg::relCond(m_value->opcode() == Equal ? MacroAssembler::Equal : MacroAssembler::NotEqual), tmp(m_value));
6085+
return;
6086+
}
6087+
#endif
6088+
59476089
m_insts.last().append(createCompare(m_value));
59486090
return;
59496091
}
@@ -6474,6 +6616,8 @@ class LowerToAir {
64746616
#if CPU(ARM64)
64756617
if (tryEmitConditionalCompareChain(m_value))
64766618
return;
6619+
if (tryEmitXorOrChainBranch(m_value))
6620+
return;
64776621
#endif
64786622

64796623
Value* branchChild = m_value->child(0);

‎Source/JavaScriptCore/b3/air/AirOpcode.opcodes‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1550,6 +1550,10 @@ arm64: CompareConditionallyOnFlagsFloat U:F:32, U:F:32, U:G:8, U:G:8 /effects
15501550
arm64: CompareConditionallyOnFlagsDouble U:F:64, U:F:64, U:G:8, U:G:8 /effects
15511551
Tmp, Tmp, Imm, RelCond
15521552

1553+
# Materializes a condition of the flags set by a preceding CompareOnFlags / ccmp chain (ARM64 cset).
1554+
arm64: SetOnFlags U:G:32, ZD:G:32 /effects
1555+
RelCond, Tmp
1556+
15531557
# Note that branches have some logic in AirOptimizeBlockOrder.cpp. If you add new branches, please make sure
15541558
# you opt them into the block order optimizations.
15551559

‎Source/JavaScriptCore/b3/testb3.h‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1542,6 +1542,14 @@ void testCCmpNegatedOr32(int32_t, int32_t);
15421542
void testCCmpMixedWidth32And64(int32_t, int64_t, int32_t);
15431543
void testCCmpMixedWidth64And32(int64_t, int32_t);
15441544
void testCCmpChainRollback(int32_t, int32_t, int32_t, int32_t, int32_t, int32_t);
1545+
void testXorOrCompareChain32(B3::Opcode, int32_t, int32_t, int32_t, int32_t);
1546+
void testXorOrCompareChain64(B3::Opcode, int64_t, int64_t, int64_t);
1547+
void testXorOrCompareChainZExt64(int64_t, int32_t);
1548+
void testXorOrCompareChainBitImmediate32(int32_t, int32_t);
1549+
void testXorOrCompareChainBranch64(int64_t, int64_t, int64_t, int64_t);
1550+
void testXorOrCompareChainBranchEqualZero32(int32_t, int32_t, int32_t, int32_t);
1551+
void testXorOrCompareChainSharedLeaf32(int32_t, int32_t, int32_t, int32_t);
1552+
void testXorOrCompareChainLoads64(unsigned, unsigned);
15451553

15461554
// ARM64 fccmp tests (floating-point conditional compare)
15471555
void testFCCmpAndDouble(double, double, double, double);

0 commit comments

Comments
 (0)