Skip to content

Commit 4dea335

Browse files
ondrejmirtesclaude
andcommitted
Return the call's own member from TypeCombinatorCache memo hits
A memoized result that was a member of a union or intersection operand (remove(int|string, string) returning the union's `int`, removeNull() of `T|null` returning `T`) was handed to every later structurally equal call, which then got the first call's member instead of its own — an object the PHP implementation, which does not memoize, never returns there. Like operand results, such results are now marked in the memo slot's alignment bits, and a hit returns the member of the new call's operands with the recorded member's structural hash; a result whose hash is not unique among the operands' members, or that is also an operand, is not memoized. The header comment claimed the memo only shares what TypeCombinator itself shares, which did not hold for members; it now says what is shared and what is not. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018Fdg8n3eEi4ZoXa4dA2k4A
1 parent d015636 commit 4dea335

2 files changed

Lines changed: 201 additions & 20 deletions

File tree

‎turbo-ext/src/TypeCombinatorCache.cpp‎

Lines changed: 158 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -16,16 +16,26 @@
1616
* call sites, and every place in the analyser comparing Type objects by identity
1717
* - a proxy for "the same reference" that only holds while equal values stay
1818
* distinct objects - then narrowed or resolved types it never meant to
19-
* (phpstan/phpstan#15151). The memo only hands one result to the structurally
20-
* equal argument tuples of the same operation, which is the sharing
21-
* TypeCombinator itself produces when it returns an operand.
19+
* (phpstan/phpstan#15151).
2220
*
23-
* A result that IS one of the operands is not shared at all: TypeCombinator
24-
* hands back the operand of the call at hand (union() of one type, remove() of
25-
* nothing), and callers test that identity (ArrayType::setExistingOffsetValueType()
26-
* treats `union(...) === $this->itemType` as "nothing was written"). Such an
27-
* entry records the operand's position instead, and a hit returns the operand
28-
* at that position of the new call — the object the PHP implementation returns.
21+
* The memo does hand one result object of its own to all the structurally
22+
* equal argument tuples of the same operation, where the PHP implementation
23+
* computes a fresh object per call — and the objects nested in the shared
24+
* result (a new union's members, say) are the ones of the call that computed
25+
* it. That sharing is what memoization is; nothing compares such results by
26+
* identity with the ones of other calls.
27+
*
28+
* A result that IS one of the operands, or a member of a union or intersection
29+
* operand, is never shared: TypeCombinator hands back that object of the call
30+
* at hand (union() of one type, remove() of nothing, removeNull() of `T|null`
31+
* returning the `T` member), and callers test that identity
32+
* (ArrayType::setExistingOffsetValueType() treats `union(...) === $this->itemType`
33+
* as "nothing was written"). An operand result records the operand's position
34+
* instead, and a hit returns the operand at that position of the new call; a
35+
* member result is marked as one, and a hit returns the member of the new
36+
* call's operands with the recorded member's structural hash (unique among
37+
* all the operands' members, or the call is not memoized) — in both cases the
38+
* object the PHP implementation returns.
2939
*
3040
* Two structures back this:
3141
*
@@ -59,7 +69,10 @@
5969
*/
6070

6171
#include "support.h"
72+
#include "TypeTraits.h"
73+
#include "generated/IntersectionType.h"
6274
#include "generated/TypeCombinatorCache.h"
75+
#include "generated/UnionType.h"
6376
#include "zv.h"
6477

6578
#include <Zend/zend_weakrefs.h>
@@ -109,8 +122,9 @@ struct Hash128
109122
/* An occupied memo slot borrows its result; result == NULL marks an empty
110123
* slot, result == MEMO_TOMBSTONE a deleted one (the probe chain must stay
111124
* intact, so deletion cannot empty a slot). A result that was an operand of
112-
* the call carries the operand's position + 1 in the pointer's alignment bits
113-
* (0 = a result of its own); the slot stays 24 bytes. */
125+
* the call carries the operand's position + 1 in the pointer's alignment bits,
126+
* a result that was a member of an operand MEMO_MEMBER_TAG (0 = a result of
127+
* its own); the slot stays 24 bytes. */
114128
struct MemoSlot
115129
{
116130
Hash128 key;
@@ -119,11 +133,12 @@ struct MemoSlot
119133

120134
#define MEMO_TOMBSTONE ((zend_object *) 1)
121135

122-
/* The alignment bits of a zend_object pointer: operand positions up to this
123-
* count fit next to the pointer; a call returning a later operand is not
124-
* memoized. */
136+
/* The alignment bits of a zend_object pointer: the highest value marks a
137+
* member result, operand positions up to the count below it fit next to the
138+
* pointer; a call returning a later operand is not memoized. */
125139
static constexpr uintptr_t MEMO_OPERAND_TAG_MASK = alignof(zend_object) - 1;
126-
static constexpr uint32_t MEMO_OPERAND_POSITIONS_LIMIT = (uint32_t) MEMO_OPERAND_TAG_MASK;
140+
static constexpr uintptr_t MEMO_MEMBER_TAG = MEMO_OPERAND_TAG_MASK;
141+
static constexpr uint32_t MEMO_OPERAND_POSITIONS_LIMIT = (uint32_t) MEMO_MEMBER_TAG - 1;
127142
static_assert(MEMO_OPERAND_POSITIONS_LIMIT >= 3, "zend_object pointers must leave alignment bits for the operand position");
128143

129144
static zend_always_inline zend_object *memoSlotObject(const zend_object *result)
@@ -388,6 +403,107 @@ static bool hashObject(zend_object *obj, Hash128 &out, uint32_t depth)
388403

389404
/* }}} */
390405

406+
/* {{{ member results */
407+
408+
/* The members of a union or intersection argument (the declared $types
409+
* slot, borrowed), NULL for any other argument */
410+
static zval *argumentMembers(zval *arg)
411+
{
412+
zend_object *obj = Z_OBJ_P(arg);
413+
uint32_t slot;
414+
if (instanceof_function(obj->ce, pt_ce_union_type)) {
415+
slot = ptdecl::UnionType::slot::types;
416+
} else if (instanceof_function(obj->ce, pt_ce_intersection_type)) {
417+
slot = ptdecl::IntersectionType::slot::types;
418+
} else {
419+
return NULL;
420+
}
421+
zval *members = OBJ_PROP_NUM(obj, slot);
422+
return Z_TYPE_P(members) == IS_ARRAY ? members : NULL;
423+
}
424+
425+
/* The structural hash of an argument's member; false when it has none (not
426+
* a structurally hashed object, or too deep) */
427+
static bool memberHash(zval *member, Hash128 &out)
428+
{
429+
ZVAL_DEREF(member);
430+
if (Z_TYPE_P(member) != IS_OBJECT || cePlan(Z_OBJCE_P(member)).kind != CE_STRUCTURAL) return false;
431+
return hashObject(Z_OBJ_P(member), out, 0);
432+
}
433+
434+
/* Whether the computed result is a member of a union or intersection
435+
* argument, and if so whether a structurally equal call can find the member
436+
* it has to return again: the result is a member exactly once, and no other
437+
* member of any argument hashes like it. isMember false = not a member (the
438+
* result may still be memoized); findable false = do not memoize. */
439+
static void classifyMemberResult(zend_object *result, zval *args, uint32_t argc, bool &isMember, bool &findable)
440+
{
441+
isMember = false;
442+
findable = false;
443+
uint32_t occurrences = 0;
444+
for (uint32_t i = 0; i < argc; i++) {
445+
zval *arg = &args[i];
446+
ZVAL_DEREF(arg);
447+
zval *members = argumentMembers(arg);
448+
if (members == NULL) continue;
449+
for (zv::ArrayEntry entry : zv::ArrRef(members)) {
450+
zval *member = entry.value().deref().raw();
451+
if (Z_TYPE_P(member) == IS_OBJECT && Z_OBJ_P(member) == result) {
452+
occurrences++;
453+
}
454+
}
455+
}
456+
if (occurrences == 0) return;
457+
isMember = true;
458+
if (occurrences > 1) return;
459+
460+
zval resultZv;
461+
ZVAL_OBJ(&resultZv, result);
462+
Hash128 resultHash;
463+
if (!memberHash(&resultZv, resultHash)) return;
464+
uint32_t sameHash = 0;
465+
for (uint32_t i = 0; i < argc; i++) {
466+
zval *arg = &args[i];
467+
ZVAL_DEREF(arg);
468+
zval *members = argumentMembers(arg);
469+
if (members == NULL) continue;
470+
for (zv::ArrayEntry entry : zv::ArrRef(members)) {
471+
Hash128 h;
472+
if (!memberHash(entry.value().raw(), h)) continue;
473+
if (h.a == resultHash.a && h.b == resultHash.b) {
474+
sameHash++;
475+
}
476+
}
477+
}
478+
findable = sameHash == 1;
479+
}
480+
481+
/* The member of this call's union or intersection arguments hashing like
482+
* the recorded member result of a structurally equal call (borrowed), NULL
483+
* when there is none */
484+
static zval *findMemberResult(zend_object *recorded, zval *args, uint32_t argc)
485+
{
486+
zval recordedZv;
487+
ZVAL_OBJ(&recordedZv, recorded);
488+
Hash128 recordedHash;
489+
if (!memberHash(&recordedZv, recordedHash)) return NULL;
490+
for (uint32_t i = 0; i < argc; i++) {
491+
zval *arg = &args[i];
492+
ZVAL_DEREF(arg);
493+
zval *members = argumentMembers(arg);
494+
if (members == NULL) continue;
495+
for (zv::ArrayEntry entry : zv::ArrRef(members)) {
496+
zval *member = entry.value().deref().raw();
497+
Hash128 h;
498+
if (!memberHash(member, h)) continue;
499+
if (h.a == recordedHash.a && h.b == recordedHash.b) return member;
500+
}
501+
}
502+
return NULL;
503+
}
504+
505+
/* }}} */
506+
391507
/* {{{ RecursionGuard
392508
393509
* While RecursionGuard::$context is non-empty, run()/runOnObjectIdentity() short-circuit
@@ -587,16 +703,24 @@ class TypeCombinatorCache
587703
MemoSlot *slot = memoLookup(key);
588704
if (slot != NULL) {
589705
uintptr_t operandTag = (uintptr_t) slot->result & MEMO_OPERAND_TAG_MASK;
590-
if (operandTag != 0) {
706+
if (operandTag == MEMO_MEMBER_TAG) {
707+
/* the member of this call's operands, found by the recorded
708+
* member's hash (unique when the entry was made); computed
709+
* afresh should it be missing */
710+
zval *member = findMemberResult(memoSlotObject(slot->result), args, argc);
711+
if (EXPECTED(member != NULL)) return zv::Val::copyOf(zv::Ref(member));
712+
memoizable = false;
713+
} else if (operandTag != 0) {
591714
/* every argument hashed above is an object */
592715
zval *operand = &args[operandTag - 1];
593716
ZVAL_DEREF(operand);
594717
return zv::Val::copyOf(zv::Ref(operand));
718+
} else {
719+
GC_ADDREF(slot->result);
720+
zval hit;
721+
ZVAL_OBJ(&hit, slot->result);
722+
return zv::Val::adopt(hit);
595723
}
596-
GC_ADDREF(slot->result);
597-
zval hit;
598-
ZVAL_OBJ(&hit, slot->result);
599-
return zv::Val::adopt(hit);
600724
}
601725
}
602726

@@ -619,6 +743,20 @@ class TypeCombinatorCache
619743
operandTag = (uintptr_t) i + 1;
620744
}
621745
}
746+
if (memoizable) {
747+
/* a member of a union or intersection operand is recorded as one;
748+
* a member that is also an operand, or that a structurally equal
749+
* call could not find again unambiguously, is not memoized */
750+
bool isMember, findable;
751+
classifyMemberResult(Z_OBJ_P(result.raw()), args, argc, isMember, findable);
752+
if (isMember) {
753+
if (operandTag != 0 || !findable) {
754+
memoizable = false;
755+
} else {
756+
operandTag = MEMO_MEMBER_TAG;
757+
}
758+
}
759+
}
622760

623761
if (memoizable && pt_memo_count < MEMO_ENTRIES_LIMIT) {
624762
/* Fresh lookup: the callback re-enters these operations for nested

‎turbo-ext/tests/type-family.php‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8377,6 +8377,49 @@ public function getTypes(): array
83778377
$r["combinator $method $argsName"] = $misuse(static fn () => \PHPStan\Type\TypeCombinator::$method(...$args));
83788378
}
83798379
}
8380+
// the identity of TypeCombinator results with the memo on (the PHP
8381+
// TypeCombinatorCache delegates without memoizing): a result that is an
8382+
// operand or a member of an operand is that object of the call at hand,
8383+
// never the one of an earlier structurally equal call (a result of its
8384+
// own is shared between structurally equal calls by design, so the two
8385+
// results are not compared with each other)
8386+
$cacheEnabledProperty = new \ReflectionProperty(\PHPStan\Type\TypeCombinator::class, 'cacheEnabled');
8387+
$cacheEnabledBefore = $cacheEnabledProperty->getValue();
8388+
$cacheEnabledProperty->setValue(null, true);
8389+
try {
8390+
$memoUnion = static fn () => new \PHPStan\Type\UnionType([new \PHPStan\Type\IntegerType(), new \PHPStan\Type\StringType()]);
8391+
$memoNullable = static fn () => new \PHPStan\Type\UnionType([new \PHPStan\Type\ObjectType(\stdClass::class), new \PHPStan\Type\NullType()]);
8392+
$memoIntersection = static fn () => new \PHPStan\Type\IntersectionType([new \PHPStan\Type\StringType(), new \PHPStan\Type\Accessory\AccessoryNonEmptyStringType()]);
8393+
$memoDuplicate = static fn () => new \PHPStan\Type\UnionType([new \PHPStan\Type\ObjectType(\stdClass::class), new \PHPStan\Type\ObjectType(\Exception::class)]);
8394+
foreach ([
8395+
'remove member' => [$memoUnion, static fn (\PHPStan\Type\Type $a) => \PHPStan\Type\TypeCombinator::remove($a, new \PHPStan\Type\StringType())],
8396+
'removeNull member' => [$memoNullable, static fn (\PHPStan\Type\Type $a) => \PHPStan\Type\TypeCombinator::removeNull($a)],
8397+
'intersect member' => [$memoUnion, static fn (\PHPStan\Type\Type $a) => \PHPStan\Type\TypeCombinator::intersect($a, new \PHPStan\Type\IntegerType())],
8398+
'intersect member reversed' => [$memoUnion, static fn (\PHPStan\Type\Type $a) => \PHPStan\Type\TypeCombinator::intersect(new \PHPStan\Type\IntegerType(), $a)],
8399+
'union operand' => [$memoUnion, static fn (\PHPStan\Type\Type $a) => \PHPStan\Type\TypeCombinator::union($a, new \PHPStan\Type\IntegerType())],
8400+
'union of members' => [$memoUnion, static fn (\PHPStan\Type\Type $a) => \PHPStan\Type\TypeCombinator::union($a->getTypes()[0], $a->getTypes()[1])],
8401+
'intersect intersection member' => [$memoIntersection, static fn (\PHPStan\Type\Type $a) => \PHPStan\Type\TypeCombinator::intersect($a, new \PHPStan\Type\StringType())],
8402+
'remove from duplicate-free union' => [$memoDuplicate, static fn (\PHPStan\Type\Type $a) => \PHPStan\Type\TypeCombinator::remove($a, new \PHPStan\Type\ObjectType(\Exception::class))],
8403+
] as $memoName => [$memoArgument, $memoOperation]) {
8404+
$firstArgument = $memoArgument();
8405+
$secondArgument = $memoArgument();
8406+
$first = $memoOperation($firstArgument);
8407+
$second = $memoOperation($secondArgument);
8408+
$identities = static fn (\PHPStan\Type\Type $result, \PHPStan\Type\Type $argument): array => [
8409+
'argument' => $result === $argument,
8410+
'members' => $argument instanceof \PHPStan\Type\UnionType || $argument instanceof \PHPStan\Type\IntersectionType ? array_map(static fn (\PHPStan\Type\Type $member): bool => $member === $result, $argument->getTypes()) : null,
8411+
];
8412+
$r["memo $memoName"] = [
8413+
$view($first),
8414+
$identities($first, $firstArgument),
8415+
$identities($second, $secondArgument),
8416+
$identities($second, $firstArgument),
8417+
];
8418+
}
8419+
} finally {
8420+
$cacheEnabledProperty->setValue(null, $cacheEnabledBefore);
8421+
}
8422+
83808423
// countConstantArrayValueTypes() hands each element to TypeTraverser::map(Type $type, ...)
83818424
foreach (['string' => 'x', 'object' => new \stdClass()] as $elementName => $element) {
83828425
$r["combinator countConstantArrayValueTypes $elementName"] = $misuse(static fn () => \PHPStan\Type\TypeCombinator::countConstantArrayValueTypes([new \PHPStan\Type\IntegerType(), $element]));

0 commit comments

Comments
 (0)