Skip to content

Commit 7c7ff95

Browse files
committed
Skip repeated joins when converging nested loops
- ConvergedLoopHeads caches the warm entry it derived per loop and keeps the recorded head object when the new head equals it, so an enclosing loop's later passes bringing the same entry get the warm entry without joining it again. - A warm-started loop begins its convergence at the warm entry, skipping the first join of the initial body scope into it. - A loop whose joined entry equals the previous pass's keeps that entry instead of recomputing the same join after the convergence loop. - turbo-ext: the same in ConvergedLoopHeads and the four loop handlers. Amp-Thread-ID: https://ampcode.com/threads/T-01a17eac-1199-74a6-b3f7-dfbd8a084465
1 parent 66542f9 commit 7c7ff95

11 files changed

Lines changed: 147 additions & 37 deletions

‎src/Analyser/ConvergedLoopHeads.php‎

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -23,19 +23,45 @@ final class ConvergedLoopHeads
2323
/** @var array<int, MutatingScope> */
2424
private array $heads = [];
2525

26+
/**
27+
* The last entry each loop was warm-started from and the warm entry it gave
28+
* with the current head - an enclosing loop's later passes mostly bring the
29+
* same entry again.
30+
*
31+
* @var array<int, array{MutatingScope, MutatingScope}>
32+
*/
33+
private array $warmEntries = [];
34+
2635
public function warmStart(Node $loop, MutatingScope $entryScope): MutatingScope
2736
{
28-
$head = $this->heads[spl_object_id($loop)] ?? null;
37+
$id = spl_object_id($loop);
38+
$head = $this->heads[$id] ?? null;
2939
if ($head === null) {
3040
return $entryScope;
3141
}
3242

33-
return $entryScope->mergeWith($head);
43+
$warmEntry = $this->warmEntries[$id] ?? null;
44+
if ($warmEntry !== null && ($warmEntry[0] === $entryScope || $warmEntry[0]->equals($entryScope))) {
45+
return $warmEntry[1];
46+
}
47+
48+
$warmScope = $entryScope->mergeWith($head);
49+
$this->warmEntries[$id] = [$entryScope, $warmScope];
50+
51+
return $warmScope;
3452
}
3553

3654
public function record(Node $loop, MutatingScope $head): void
3755
{
38-
$this->heads[spl_object_id($loop)] = $head;
56+
$id = spl_object_id($loop);
57+
$previous = $this->heads[$id] ?? null;
58+
// an unchanged head keeps the warm entry derived from it
59+
if ($previous !== null && ($previous === $head || $previous->equals($head))) {
60+
return;
61+
}
62+
63+
$this->heads[$id] = $head;
64+
unset($this->warmEntries[$id]);
3965
}
4066

4167
}

‎src/Analyser/StmtHandler/DoWhileHandler.php‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,25 +69,31 @@ public function processStmt(
6969
$previousPass = null;
7070
$previousPassStorage = null;
7171
$loopHeads = null;
72+
$entryConverged = false;
7273
// the loop's entry joined with the head it converged to when walked before
7374
$loopEntryScope = $scope;
7475
if ($context->shouldConvergeLoops()) {
7576
$loopHeads = $context->getLoopHeads() ?? new ConvergedLoopHeads();
7677
// heads come from pass walks - a top-level walk converges from its own entry
7778
if (!$context->isTopLevel()) {
7879
$loopEntryScope = $loopHeads->warmStart($stmt, $scope);
80+
if ($loopEntryScope !== $scope) {
81+
$bodyScope = $loopEntryScope;
82+
}
7983
}
8084
$bodyIsReplayable = !$context->isTopLevel() || $nodeScopeResolver->isReplayableConvergenceBody($stmt, $stmt->stmts);
8185
// each pass after the first re-walks only the statements whose
8286
// entry state differs from the previous pass's (StatementsHandler::processLoopPassStmtNodes())
8387
do {
8488
$prevScope = $bodyScope;
85-
$bodyScope = $bodyScope->mergeWith($loopEntryScope);
89+
// a warm start begins at the loop's entry already
90+
$bodyScope = $bodyScope === $loopEntryScope ? $bodyScope : $bodyScope->mergeWith($loopEntryScope);
8691
if ($prevEntryScope !== null && $bodyScope->equals($prevEntryScope)) {
8792
// walking is deterministic in the entry scope - an unchanged entry
8893
// reproduces the previous pass's exit (and repeats only idempotent
8994
// merges into the final scope), so the verification walk is skipped
90-
$bodyScope = $prevScope;
95+
$bodyScope = $prevEntryScope;
96+
$entryConverged = true;
9197
break;
9298
}
9399
$prevEntryScope = $bodyScope;
@@ -137,7 +143,9 @@ public function processStmt(
137143
$count++;
138144
} while ($count < NodeScopeResolver::LOOP_SCOPE_ITERATIONS);
139145

140-
$bodyScope = $bodyScope->mergeWith($loopEntryScope);
146+
if (!$entryConverged) {
147+
$bodyScope = $bodyScope->mergeWith($loopEntryScope);
148+
}
141149
if (!$context->isTopLevel()) {
142150
$loopHeads->record($stmt, $bodyScope);
143151
}

‎src/Analyser/StmtHandler/ForHandler.php‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,7 @@ public function processStmt(
197197
}
198198

199199
$loopHeads = null;
200+
$entryConverged = false;
200201
// the loop's entry joined with the head it converged to when walked before
201202
$loopEntryScope = $initScope;
202203
$prevEntryScope = null;
@@ -208,6 +209,9 @@ public function processStmt(
208209
// heads come from pass walks - a top-level walk converges from its own entry
209210
if (!$context->isTopLevel()) {
210211
$loopEntryScope = $loopHeads->warmStart($stmt, $initScope);
212+
if ($loopEntryScope !== $initScope) {
213+
$bodyScope = $loopEntryScope;
214+
}
211215
}
212216
$count = 0;
213217
// each pass after the first re-walks only the statements whose
@@ -216,11 +220,13 @@ public function processStmt(
216220
do {
217221
$prevScope = $bodyScope;
218222
$storage = $originalStorage->duplicate();
219-
$bodyScope = $bodyScope->mergeWith($loopEntryScope);
223+
// a warm start begins at the loop's entry already
224+
$bodyScope = $bodyScope === $loopEntryScope ? $bodyScope : $bodyScope->mergeWith($loopEntryScope);
220225
if ($prevEntryScope !== null && $bodyScope->equals($prevEntryScope)) {
221226
// walking is deterministic in the entry scope - an unchanged entry
222227
// reproduces the previous pass's exit, so the verification walk is skipped
223-
$bodyScope = $prevScope;
228+
$bodyScope = $prevEntryScope;
229+
$entryConverged = true;
224230
break;
225231
}
226232
$prevEntryScope = $bodyScope;
@@ -274,7 +280,9 @@ public function processStmt(
274280
}
275281

276282
$storage = $originalStorage;
277-
$bodyScope = $bodyScope->mergeWith($loopEntryScope);
283+
if (!$entryConverged) {
284+
$bodyScope = $bodyScope->mergeWith($loopEntryScope);
285+
}
278286
if (!$context->isTopLevel()) {
279287
$loopHeads?->record($stmt, $bodyScope);
280288
}

‎src/Analyser/StmtHandler/ForeachHandler.php‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,7 @@ static function () use ($condResult, $emptyArrayType): Type {
197197
$unrolledEndScope = null;
198198
$unrolledTotalKeys = null;
199199
$loopHeads = null;
200+
$entryConverged = false;
200201
// the loop's entry joined with the head it converged to when walked before
201202
$loopEntryScope = $nonEmptyIterateeScope;
202203
if ($context->shouldConvergeLoops()) {
@@ -233,6 +234,9 @@ static function () use ($condResult, $emptyArrayType): Type {
233234
// heads come from pass walks - a top-level walk converges from its own entry
234235
if (!$context->isTopLevel()) {
235236
$loopEntryScope = $loopHeads->warmStart($stmt, $nonEmptyIterateeScope);
237+
if ($loopEntryScope !== $nonEmptyIterateeScope) {
238+
$bodyScope = $loopEntryScope;
239+
}
236240
}
237241
$count = 0;
238242
$prevEntryScope = null;
@@ -241,11 +245,13 @@ static function () use ($condResult, $emptyArrayType): Type {
241245
$bodyIsReplayable = !$context->isTopLevel() || $nodeScopeResolver->isReplayableConvergenceBody($stmt, $stmt->stmts);
242246
do {
243247
$prevScope = $bodyScope;
244-
$bodyScope = $bodyScope->mergeWith($loopEntryScope);
248+
// a warm start begins at the loop's entry already
249+
$bodyScope = $bodyScope === $loopEntryScope ? $bodyScope : $bodyScope->mergeWith($loopEntryScope);
245250
if ($prevEntryScope !== null && $bodyScope->equals($prevEntryScope)) {
246251
// walking is deterministic in the entry scope - an unchanged entry
247252
// reproduces the previous pass's exit, so the verification walk is skipped
248-
$bodyScope = $prevScope;
253+
$bodyScope = $prevEntryScope;
254+
$entryConverged = true;
249255
break;
250256
}
251257
$prevEntryScope = $bodyScope;
@@ -291,7 +297,9 @@ static function () use ($condResult, $emptyArrayType): Type {
291297
}
292298
}
293299

294-
$bodyScope = $bodyScope->mergeWith($loopEntryScope);
300+
if (!$entryConverged) {
301+
$bodyScope = $bodyScope->mergeWith($loopEntryScope);
302+
}
295303
$finalEntryScope = $bodyScope;
296304
if (!$context->isTopLevel()) {
297305
$loopHeads?->record($stmt, $finalEntryScope);

‎src/Analyser/StmtHandler/WhileHandler.php‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -95,23 +95,29 @@ public function processStmt(
9595
$previousPass = null;
9696
$previousPassStorage = null;
9797
$loopHeads = null;
98+
$entryConverged = false;
9899
// the loop's entry joined with the head it converged to when walked before
99100
$loopEntryScope = $scope;
100101
if ($context->shouldConvergeLoops()) {
101102
$loopHeads = $context->getLoopHeads() ?? new ConvergedLoopHeads();
102103
// heads come from pass walks - a top-level walk converges from its own entry
103104
if (!$context->isTopLevel()) {
104105
$loopEntryScope = $loopHeads->warmStart($stmt, $scope);
106+
if ($loopEntryScope !== $scope) {
107+
$bodyScope = $loopEntryScope;
108+
}
105109
}
106110
$count = 0;
107111
$bodyIsReplayable = !$context->isTopLevel() || $nodeScopeResolver->isReplayableConvergenceBody($stmt, $stmt->stmts);
108112
do {
109113
$prevScope = $bodyScope;
110-
$bodyScope = $bodyScope->mergeWith($loopEntryScope);
114+
// a warm start begins at the loop's entry already
115+
$bodyScope = $bodyScope === $loopEntryScope ? $bodyScope : $bodyScope->mergeWith($loopEntryScope);
111116
if ($prevEntryScope !== null && $bodyScope->equals($prevEntryScope)) {
112117
// walking is deterministic in the entry scope - an unchanged entry
113118
// reproduces the previous pass's exit, so the verification walk is skipped
114-
$bodyScope = $prevScope;
119+
$bodyScope = $prevEntryScope;
120+
$entryConverged = true;
115121
break;
116122
}
117123
$prevEntryScope = $bodyScope;
@@ -162,7 +168,9 @@ public function processStmt(
162168
} while ($count < NodeScopeResolver::LOOP_SCOPE_ITERATIONS);
163169
}
164170

165-
$bodyScope = $bodyScope->mergeWith($loopEntryScope);
171+
if (!$entryConverged) {
172+
$bodyScope = $bodyScope->mergeWith($loopEntryScope);
173+
}
166174
if (!$context->isTopLevel()) {
167175
$loopHeads?->record($stmt, $bodyScope);
168176
}

‎turbo-ext/src/ConvergedLoopHeads.cpp‎

Lines changed: 44 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -37,19 +37,56 @@ class ConvergedLoopHeads
3737
/* Mirrors warmStart(). */
3838
zv::Val warmStart(zval *loop, zval *entryScope) const
3939
{
40-
zval *head = zend_hash_index_find(Z_ARRVAL_P(OBJ_PROP_NUM(self, slots::heads)), Z_OBJ_HANDLE_P(loop));
40+
zend_ulong id = Z_OBJ_HANDLE_P(loop);
41+
zval *head = zend_hash_index_find(Z_ARRVAL_P(OBJ_PROP_NUM(self, slots::heads)), id);
4142
if (head == nullptr) return zv::Val::copyOf(zv::Ref(entryScope));
4243

43-
return pt_mutating_scope_merge_with(Z_OBJ_P(entryScope), head);
44+
zval *warmEntry = zend_hash_index_find(Z_ARRVAL_P(OBJ_PROP_NUM(self, slots::warmEntries)), id);
45+
if (warmEntry != nullptr) {
46+
zval *cachedEntry = zend_hash_index_find(Z_ARRVAL_P(warmEntry), 0);
47+
zval *cachedWarm = zend_hash_index_find(Z_ARRVAL_P(warmEntry), 1);
48+
zv::Val cachedWarmHold = zv::Val::copyOf(zv::Ref(cachedWarm));
49+
bool equal = Z_OBJ_P(cachedEntry) == Z_OBJ_P(entryScope);
50+
if (!equal && UNEXPECTED(!pt_mutating_scope_equals(Z_OBJ_P(cachedEntry), Z_OBJ_P(entryScope), equal))) return zv::Val();
51+
if (equal) return cachedWarmHold;
52+
}
53+
54+
zv::Val warmScope = pt_mutating_scope_merge_with(Z_OBJ_P(entryScope), head);
55+
if (UNEXPECTED(warmScope.isUndef())) return zv::Val();
56+
zval pair;
57+
array_init_size(&pair, 2);
58+
Z_ADDREF_P(entryScope);
59+
add_next_index_zval(&pair, entryScope);
60+
zval warmCopy;
61+
ZVAL_COPY(&warmCopy, warmScope.raw());
62+
add_next_index_zval(&pair, &warmCopy);
63+
zval *warmEntries = OBJ_PROP_NUM(self, slots::warmEntries);
64+
SEPARATE_ARRAY(warmEntries);
65+
zend_hash_index_update(Z_ARRVAL_P(warmEntries), id, &pair);
66+
67+
return warmScope;
4468
}
4569

46-
/* Mirrors record(). */
47-
void record(zval *loop, zval *head) const
70+
/* Mirrors record(); false = pending exception */
71+
[[nodiscard]] bool record(zval *loop, zval *head) const
4872
{
73+
zend_ulong id = Z_OBJ_HANDLE_P(loop);
74+
zval *previous = zend_hash_index_find(Z_ARRVAL_P(OBJ_PROP_NUM(self, slots::heads)), id);
75+
// an unchanged head keeps the warm entry derived from it
76+
if (previous != nullptr) {
77+
bool equal = Z_OBJ_P(previous) == Z_OBJ_P(head);
78+
if (!equal && UNEXPECTED(!pt_mutating_scope_equals(Z_OBJ_P(previous), Z_OBJ_P(head), equal))) return false;
79+
if (equal) return true;
80+
}
81+
4982
zval *heads = OBJ_PROP_NUM(self, slots::heads);
5083
SEPARATE_ARRAY(heads);
5184
Z_ADDREF_P(head);
52-
zend_hash_index_update(Z_ARRVAL_P(heads), Z_OBJ_HANDLE_P(loop), head);
85+
zend_hash_index_update(Z_ARRVAL_P(heads), id, head);
86+
zval *warmEntries = OBJ_PROP_NUM(self, slots::warmEntries);
87+
SEPARATE_ARRAY(warmEntries);
88+
zend_hash_index_del(Z_ARRVAL_P(warmEntries), id);
89+
return true;
5390
}
5491

5592
private:
@@ -87,10 +124,7 @@ zv::Val pt_converged_loop_heads_warm_start(zval *heads, zval *loop, zval *entryS
87124

88125
bool pt_converged_loop_heads_record(zval *heads, zval *loop, zval *head)
89126
{
90-
if (isNative(heads)) {
91-
ConvergedLoopHeads(Z_OBJ_P(heads)).record(loop, head);
92-
return true;
93-
}
127+
if (isNative(heads)) return ConvergedLoopHeads(Z_OBJ_P(heads)).record(loop, head);
94128
zv::Args argv{loop, head};
95129
zv::Val result = pt_type_call(Z_OBJ_P(heads), PT_LC("record"), 2, argv);
96130
return !result.isUndef();
@@ -119,7 +153,7 @@ PT_MINIT_REGISTRATION(pt_register_converged_loop_heads)
119153
zval *loop;
120154
zval *head;
121155
if (!zp::parse<zp::Obj, zp::Obj>(execute_data, loop, head)) RETURN_THROWS();
122-
ConvergedLoopHeads(Z_OBJ_P(ZEND_THIS)).record(loop, head);
156+
if (!ConvergedLoopHeads(Z_OBJ_P(ZEND_THIS)).record(loop, head)) RETURN_THROWS();
123157
});
124158

125159
cls.shadow(&pt_ce_converged_loop_heads);

‎turbo-ext/src/DoWhileHandler.cpp‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ class DoWhileHandler
8484
bool shouldConvergeLoops;
8585
if (UNEXPECTED(!pt_statement_context_should_converge_loops(context, shouldConvergeLoops))) return zv::Val();
8686
zv::Val loopHeads = zv::Val::null();
87+
bool entryConverged = false;
8788
// the loop's entry joined with the head it converged to when walked before
8889
zv::Val loopEntryScope = zv::Val::copyOf(zv::Ref(scope));
8990
if (shouldConvergeLoops) {
@@ -92,6 +93,7 @@ class DoWhileHandler
9293
if (!isTopLevel) {
9394
loopEntryScope = pt_converged_loop_heads_warm_start(loopHeads.raw(), stmt, scope);
9495
if (UNEXPECTED(loopEntryScope.isUndef())) return zv::Val();
96+
if (Z_OBJ_P(loopEntryScope.raw()) != Z_OBJ_P(scope)) bodyScope = zv::Val::copyOf(loopEntryScope.ref());
9597
}
9698
zval *stmts = ptsh::readNodeProperty(pt_dwh_stmts_site, stmt, PT_LC("stmts"));
9799
if (UNEXPECTED(stmts == NULL)) return zv::Val();
@@ -101,7 +103,8 @@ class DoWhileHandler
101103
// entry state differs from the previous pass's (StatementsHandler::processLoopPassStmtNodes())
102104
do {
103105
zv::Val prevScope = zv::Val::copyOf(bodyScope.ref());
104-
bodyScope = pt_mutating_scope_merge_with(Z_OBJ_P(bodyScope.raw()), loopEntryScope.raw());
106+
// a warm start begins at the loop's entry already
107+
if (Z_OBJ_P(bodyScope.raw()) != Z_OBJ_P(loopEntryScope.raw())) bodyScope = pt_mutating_scope_merge_with(Z_OBJ_P(bodyScope.raw()), loopEntryScope.raw());
105108
if (UNEXPECTED(bodyScope.isUndef())) return zv::Val();
106109
if (!prevEntryScope.isNull()) {
107110
bool equal;
@@ -110,7 +113,8 @@ class DoWhileHandler
110113
// walking is deterministic in the entry scope - an unchanged entry
111114
// reproduces the previous pass's exit (and repeats only idempotent
112115
// merges into the final scope), so the verification walk is skipped
113-
bodyScope = std::move(prevScope);
116+
bodyScope = zv::Val::copyOf(prevEntryScope.ref());
117+
entryConverged = true;
114118
break;
115119
}
116120
}
@@ -197,7 +201,7 @@ class DoWhileHandler
197201
count++;
198202
} while (count < PT_LH_LOOP_SCOPE_ITERATIONS_LIMIT);
199203

200-
bodyScope = pt_mutating_scope_merge_with(Z_OBJ_P(bodyScope.raw()), loopEntryScope.raw());
204+
if (!entryConverged) bodyScope = pt_mutating_scope_merge_with(Z_OBJ_P(bodyScope.raw()), loopEntryScope.raw());
201205
if (UNEXPECTED(bodyScope.isUndef())) return zv::Val();
202206
if (!isTopLevel && UNEXPECTED(!pt_converged_loop_heads_record(loopHeads.raw(), stmt, bodyScope.raw()))) return zv::Val();
203207
}

‎turbo-ext/src/ForHandler.cpp‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,7 @@ class ForHandler
215215
bool shouldConvergeLoops;
216216
if (UNEXPECTED(!pt_statement_context_should_converge_loops(context, shouldConvergeLoops))) return zv::Val();
217217
zv::Val loopHeads = zv::Val::null();
218+
bool entryConverged = false;
218219
// the loop's entry joined with the head it converged to when walked before
219220
zv::Val loopEntryScope = zv::Val::copyOf(initScope.ref());
220221
zv::Val prevEntryScope;
@@ -227,6 +228,7 @@ class ForHandler
227228
if (!isTopLevel) {
228229
loopEntryScope = pt_converged_loop_heads_warm_start(loopHeads.raw(), stmt, initScope.raw());
229230
if (UNEXPECTED(loopEntryScope.isUndef())) return zv::Val();
231+
if (Z_OBJ_P(loopEntryScope.raw()) != Z_OBJ_P(initScope.raw())) bodyScope = zv::Val::copyOf(loopEntryScope.ref());
230232
}
231233
zend_long count = 0;
232234
// each pass after the first re-walks only the statements whose
@@ -236,15 +238,17 @@ class ForHandler
236238
zv::Val prevScope = zv::Val::copyOf(bodyScope.ref());
237239
zv::Val storage = pt_expression_result_storage_duplicate(originalStorage);
238240
if (UNEXPECTED(storage.isUndef())) return zv::Val();
239-
bodyScope = pt_mutating_scope_merge_with(Z_OBJ_P(bodyScope.raw()), loopEntryScope.raw());
241+
// a warm start begins at the loop's entry already
242+
if (Z_OBJ_P(bodyScope.raw()) != Z_OBJ_P(loopEntryScope.raw())) bodyScope = pt_mutating_scope_merge_with(Z_OBJ_P(bodyScope.raw()), loopEntryScope.raw());
240243
if (UNEXPECTED(bodyScope.isUndef())) return zv::Val();
241244
if (!prevEntryScope.isNull()) {
242245
bool equal;
243246
if (UNEXPECTED(!ptlh::scopesEqual(bodyScope.raw(), prevEntryScope.raw(), equal))) return zv::Val();
244247
if (equal) {
245248
// walking is deterministic in the entry scope - an unchanged entry
246249
// reproduces the previous pass's exit, so the verification walk is skipped
247-
bodyScope = std::move(prevScope);
250+
bodyScope = zv::Val::copyOf(prevEntryScope.ref());
251+
entryConverged = true;
248252
break;
249253
}
250254
}
@@ -332,7 +336,7 @@ class ForHandler
332336
}
333337

334338
zval *storage = originalStorage;
335-
bodyScope = pt_mutating_scope_merge_with(Z_OBJ_P(bodyScope.raw()), loopEntryScope.raw());
339+
if (!entryConverged) bodyScope = pt_mutating_scope_merge_with(Z_OBJ_P(bodyScope.raw()), loopEntryScope.raw());
336340
if (UNEXPECTED(bodyScope.isUndef())) return zv::Val();
337341
if (!isTopLevel && !loopHeads.isNull() && UNEXPECTED(!pt_converged_loop_heads_record(loopHeads.raw(), stmt, bodyScope.raw()))) return zv::Val();
338342
zv::Val headScope = zv::Val::copyOf(bodyScope.ref());

0 commit comments

Comments
 (0)