diff --git a/phpunit/code/declared-scalar-property-read-final.php b/phpunit/code/declared-scalar-property-read-final.php new file mode 100644 index 00000000..2df87dc1 --- /dev/null +++ b/phpunit/code/declared-scalar-property-read-final.php @@ -0,0 +1,17 @@ +ratio * $this->count; + } +} + +function declared_scalar_read_final(DeclaredScalarFinalBox $box): float +{ + return $box->ratio + $box->count; +} diff --git a/phpunit/code/declared-scalar-property-read-hooked-subclass.php b/phpunit/code/declared-scalar-property-read-hooked-subclass.php new file mode 100644 index 00000000..5739a410 --- /dev/null +++ b/phpunit/code/declared-scalar-property-read-hooked-subclass.php @@ -0,0 +1,18 @@ + 42; + } +} + +function declared_scalar_read_hooked(DeclaredScalarHookedBase $box): int +{ + return $box->count; +} diff --git a/phpunit/code/declared-scalar-property-read-loop.php b/phpunit/code/declared-scalar-property-read-loop.php new file mode 100644 index 00000000..b68668f8 --- /dev/null +++ b/phpunit/code/declared-scalar-property-read-loop.php @@ -0,0 +1,15 @@ +count; + } + return $total; + } +} diff --git a/phpunit/code/declared-scalar-property-read-narrowed.php b/phpunit/code/declared-scalar-property-read-narrowed.php new file mode 100644 index 00000000..512add6f --- /dev/null +++ b/phpunit/code/declared-scalar-property-read-narrowed.php @@ -0,0 +1,14 @@ +count; + } + return -1; +} diff --git a/phpunit/code/declared-scalar-property-read-nullable.php b/phpunit/code/declared-scalar-property-read-nullable.php new file mode 100644 index 00000000..ebd668e2 --- /dev/null +++ b/phpunit/code/declared-scalar-property-read-nullable.php @@ -0,0 +1,11 @@ +count; +} diff --git a/phpunit/code/declared-scalar-property-read-open.php b/phpunit/code/declared-scalar-property-read-open.php new file mode 100644 index 00000000..38b1d28f --- /dev/null +++ b/phpunit/code/declared-scalar-property-read-open.php @@ -0,0 +1,11 @@ +count; +} diff --git a/phpunit/code/declared-scalar-property-read-readonly-arith.php b/phpunit/code/declared-scalar-property-read-readonly-arith.php new file mode 100644 index 00000000..516a6b24 --- /dev/null +++ b/phpunit/code/declared-scalar-property-read-readonly-arith.php @@ -0,0 +1,15 @@ +width < $box->height ? $box->width / 2.0 : $box->height / 2.0; +} diff --git a/phpunit/code/declared-scalar-property-read-readonly.php b/phpunit/code/declared-scalar-property-read-readonly.php new file mode 100644 index 00000000..f0505dab --- /dev/null +++ b/phpunit/code/declared-scalar-property-read-readonly.php @@ -0,0 +1,13 @@ +count; +} diff --git a/phpunit/code/declared-scalar-property-read-subclass.php b/phpunit/code/declared-scalar-property-read-subclass.php new file mode 100644 index 00000000..9409069d --- /dev/null +++ b/phpunit/code/declared-scalar-property-read-subclass.php @@ -0,0 +1,16 @@ +count; +} diff --git a/phpunit/src/DeclaredScalarPropertyReadTest.php b/phpunit/src/DeclaredScalarPropertyReadTest.php new file mode 100644 index 00000000..8718ffb6 --- /dev/null +++ b/phpunit/src/DeclaredScalarPropertyReadTest.php @@ -0,0 +1,156 @@ +addFiles([$testFile]); + $compiler->prepareFile($testFile); + $compiler->convertFile($testFile); + + return TYPEPHP_ROOT_PATH . '/build/phpunit/code/' . basename($file, '.php') . '.cc'; + } + + public function testFinalClassReceiverUsesTypedOffsetRead(): void + { + try { + $outputFile = $this->compileCode('declared-scalar-property-read-final.php'); + } catch (TestError $e) { + $this->fail($e->getMessage()); + } + + $code = file_get_contents($outputFile); + $this->assertStringContainsString('attrInt(get_persistent_prop(', $code); + $this->assertStringContainsString('attrFloat(get_persistent_prop(', $code); + $this->assertStringContainsString('this_.attrInt(', $code); + $this->assertStringContainsString('this_.attrFloat(', $code); + $this->assertStringNotContainsString('attr(get_persistent_prop(', $code); + } + + public function testNonFinalReceiverWithoutSubclassesUsesTypedOffsetRead(): void + { + try { + $outputFile = $this->compileCode('declared-scalar-property-read-open.php'); + } catch (TestError $e) { + $this->fail($e->getMessage()); + } + + $code = file_get_contents($outputFile); + $this->assertStringContainsString('attrInt(get_persistent_prop(', $code); + $this->assertStringNotContainsString('attr(get_persistent_prop(', $code); + } + + public function testSubclassRedeclaringThePropertyKeepsTypedOffsetRead(): void + { + try { + $outputFile = $this->compileCode('declared-scalar-property-read-subclass.php'); + } catch (TestError $e) { + $this->fail($e->getMessage()); + } + + $code = file_get_contents($outputFile); + $this->assertStringContainsString('attrInt(get_persistent_prop(', $code); + $this->assertStringNotContainsString('attr(get_persistent_prop(', $code); + } + + public function testSubclassAddingAPropertyHookFallsBackToVariantRead(): void + { + try { + $outputFile = $this->compileCode('declared-scalar-property-read-hooked-subclass.php'); + } catch (TestError $e) { + $this->fail($e->getMessage()); + } + + $code = file_get_contents($outputFile); + $this->assertStringContainsString('attr(get_persistent_prop(', $code); + $this->assertStringNotContainsString('attrInt(get_persistent_prop(', $code); + } + + public function testLoopReadHoistsBeforeTheTypedOffsetFallback(): void + { + try { + $outputFile = $this->compileCode('declared-scalar-property-read-loop.php'); + } catch (TestError $e) { + $this->fail($e->getMessage()); + } + + $code = file_get_contents($outputFile); + $this->assertStringContainsString( + 'php::Int &_object_prop_this___count = this_.attrInt(', + $code + ); + } + + public function testNullablePropertyKeepsVariantRead(): void + { + try { + $outputFile = $this->compileCode('declared-scalar-property-read-nullable.php'); + } catch (TestError $e) { + $this->fail($e->getMessage()); + } + + $code = file_get_contents($outputFile); + $this->assertStringContainsString('attr(get_persistent_prop(', $code); + $this->assertStringNotContainsString('attrInt(get_persistent_prop(', $code); + } + + public function testReadonlyPropertyKeepsCheckedRead(): void + { + try { + $outputFile = $this->compileCode('declared-scalar-property-read-readonly.php'); + } catch (TestError $e) { + $this->fail($e->getMessage()); + } + + $code = file_get_contents($outputFile); + $this->assertStringContainsString('typephp_read_property_scoped(', $code); + $this->assertStringNotContainsString('attrInt(get_persistent_prop(', $code); + } + + public function testReadonlyPropertyKeepsTheConversionOnArithmetic(): void + { + try { + $outputFile = $this->compileCode('declared-scalar-property-read-readonly-arith.php'); + } catch (TestError $e) { + $this->fail($e->getMessage()); + } + + $code = file_get_contents($outputFile); + // The read is materialized as a Variant, so the division still has to + // be converted instead of being treated as an already native float. + $this->assertStringContainsString('typephp_read_property_scoped(', $code); + $this->assertStringContainsString('php::toFloat(((tmp_var_', $code); + $this->assertStringNotContainsString('attrFloat(get_persistent_prop(', $code); + } + + public function testNarrowedMixedReceiverKeepsVariantRead(): void + { + try { + $outputFile = $this->compileCode('declared-scalar-property-read-narrowed.php'); + } catch (TestError $e) { + $this->fail($e->getMessage()); + } + + $code = file_get_contents($outputFile); + $this->assertStringContainsString('attr(get_persistent_prop(', $code); + $this->assertStringNotContainsString('attrInt(get_persistent_prop(', $code); + } +} diff --git a/phpunit/src/MatchExpressionCodegenTest.php b/phpunit/src/MatchExpressionCodegenTest.php index 3e285621..0a369921 100644 --- a/phpunit/src/MatchExpressionCodegenTest.php +++ b/phpunit/src/MatchExpressionCodegenTest.php @@ -90,7 +90,10 @@ public function testMatchArmPropertyReadConvertsAtTypedBoundary(): void { $fnCode = $this->extractFunction('php_testmatcharmpropertyread'); self::assertStringContainsString('[&]() -> php::Int {', $fnCode); - self::assertStringContainsString('php::toInt(obj.attr(', $fnCode); + // The arm already reads the slot as an int, so the conversion happens + // at the lambda boundary instead of around the property fetch. + self::assertStringContainsString('obj.attrInt(get_persistent_prop(', $fnCode); + self::assertStringContainsString('php::toInt([&]() -> php::Int {', $fnCode); $ternaryCode = $this->extractFunction('php_testmatcharmternarypropertyread'); self::assertStringContainsString('[&]() -> php::Int {', $ternaryCode); diff --git a/phpunit/src/NativePropertyTest.php b/phpunit/src/NativePropertyTest.php index 435fcb58..2d8d845d 100644 --- a/phpunit/src/NativePropertyTest.php +++ b/phpunit/src/NativePropertyTest.php @@ -164,7 +164,9 @@ public function testUnsetObjectDisablesPropertySlotsButKeepsNativeMethodCall(): $code = file_get_contents($outputFile); $this->assertStringNotContainsString('_object_prop_object__value', $code); - $this->assertStringContainsString('object.attr(', $code); + // The receiver is unstable, so the slot is re-read through the typed + // accessor instead of being hoisted into a long-lived reference. + $this->assertStringContainsString('object.attrInt(', $code); $this->assertStringContainsString('php_nativemethodunsetkeepsoptimization__read(object)', $code); } @@ -252,20 +254,20 @@ public function testNativePropertyWritesAndCompoundAssignsConvertLoweredVariantS } $code = file_get_contents($outputFile); - $this->assertStringContainsString('_object_prop_this___number += (php::toInt(', $code); - $this->assertStringContainsString('_object_prop_this___amount += (php::toFloat(', $code); - $this->assertStringContainsString('typephp_static_int_ref(_typephp_static_property_0().direct_ptr()) += (php::toInt(', $code); - $this->assertStringContainsString('typephp_static_float_ref(_typephp_static_property_1().direct_ptr()) += (php::toFloat(', $code); + $this->assertStringContainsString('_object_prop_this___number += (source.attrInt(', $code); + $this->assertStringContainsString('_object_prop_this___amount += (source.attrFloat(', $code); + $this->assertStringContainsString('typephp_static_int_ref(_typephp_static_property_0().direct_ptr()) += (source.attrInt(', $code); + $this->assertStringContainsString('typephp_static_float_ref(_typephp_static_property_1().direct_ptr()) += (source.attrFloat(', $code); $this->assertStringContainsString('typephp_static_int_ref(_typephp_static_property_0().direct_ptr()) *= (1.5);', $code); $this->assertStringContainsString('typephp_static_int_ref(_typephp_static_property_0().direct_ptr()) /= (0.5);', $code); - $this->assertStringContainsString('typephp_static_int_ref(_typephp_static_property_0().direct_ptr()) *= (php::toFloat(', $code); - $this->assertStringContainsString('typephp_static_int_ref(_typephp_static_property_0().direct_ptr()) /= (php::toFloat(', $code); + $this->assertStringContainsString('typephp_static_int_ref(_typephp_static_property_0().direct_ptr()) *= (source.attrFloat(', $code); + $this->assertStringContainsString('typephp_static_int_ref(_typephp_static_property_0().direct_ptr()) /= (source.attrFloat(', $code); $this->assertStringNotContainsString('php::toInt(1.5)', $code); $this->assertStringNotContainsString('php::toInt(0.5)', $code); - $this->assertMatchesRegularExpression('/_object_prop_this___number = php::toInt\(\(\(tmp_var_\d+\) \+ \(1L+\)\)\);/', $code); - $this->assertMatchesRegularExpression('/_object_prop_this___amount = php::toFloat\(\(\(tmp_var_\d+\) \+ \(0\.5\)\)\);/', $code); - $this->assertStringContainsString('_object_prop_this___number = php::toInt(-(source.attr(', $code); - $this->assertMatchesRegularExpression('/_object_prop_this___number = php::toInt\(\(php::toBool\(cond\)\) \? \(source\.attr\(.+?\) : \(0L+\)\);/', $code); + $this->assertMatchesRegularExpression('/_object_prop_this___number = \(\(tmp_var_\d+\) \+ \(1L+\)\);/', $code); + $this->assertMatchesRegularExpression('/_object_prop_this___amount = \(\(tmp_var_\d+\) \+ \(0\.5\)\);/', $code); + $this->assertStringContainsString('_object_prop_this___number = -(source.attrInt(', $code); + $this->assertMatchesRegularExpression('/_object_prop_this___number = \(php::toBool\(cond\)\) \? \(source\.attrInt\(.+?\)\) : \(0L+\);/', $code); $this->assertMatchesRegularExpression('/_object_prop_this___number = php::toInt\(tmp_var_\d+\);/', $code); } diff --git a/phpunit/src/ReadonlyTypedPropertyReadTest.php b/phpunit/src/ReadonlyTypedPropertyReadTest.php index d48f3a99..6e5fe11a 100644 --- a/phpunit/src/ReadonlyTypedPropertyReadTest.php +++ b/phpunit/src/ReadonlyTypedPropertyReadTest.php @@ -41,7 +41,9 @@ public function testReadonlyScalarReadsRestoreDeclaredStorageType(): void // initialized from it directly. $this->assertStringContainsString('php::toInt(typephp_read_property_scoped(this_,', $code); $this->assertStringContainsString('php::toFloat(typephp_read_property_scoped(this_,', $code); - $this->assertStringContainsString('switch (tmp_var_0)', $code); + // The read keeps its Variant storage, so the discriminant compares + // through PHP's loose equality instead of a native switch. + $this->assertStringContainsString('php::equals(tmp_var_0, 0LL)', $code); // Readonly properties stay out of the hoisted scalar reference path. $this->assertStringNotContainsString('_object_prop_this___status', $code); $this->assertStringNotContainsString('_object_prop_this___ratio', $code); diff --git a/src/Parser/PropertyAccessTrait.php b/src/Parser/PropertyAccessTrait.php index 88d717ec..a7ecb9b4 100644 --- a/src/Parser/PropertyAccessTrait.php +++ b/src/Parser/PropertyAccessTrait.php @@ -1329,21 +1329,66 @@ protected function parsePropertyFetch(Expr\PropertyFetch $expr): string $def = $declared; } } - if ($def && $this->usesNativeScalarStorage($def->type)) { + // Resolve the declaration before the hoisting path runs. Without this, + // an ordinary variable receiver has no definition here and skips + // hoisting entirely, which turns a stable slot reference into a fresh + // offset lookup on every read. + // + // Only a plain int/float declaration qualifies. Bool and string keep + // their previous lowering, and a readonly or hooked property keeps its + // own path: the readonly branch reads through the dynamic value source, + // so materializing its result as a native scalar while the temporary + // stays a Variant would drop the conversion the surrounding expression + // still needs. + $scalarDef = $def; + if ($scalarDef === null && $property instanceof Node\Identifier) { + $declared = $this->findReadablePropertyDefinition($expr); + if ($declared !== null + && !$declared->isReadonly() + && $declared->getter === null + && $declared->setter === null + && !$declared->virtual + && ($declared->type === Type::INT || $declared->type === Type::FLOAT)) { + $scalarDef = $declared; + } + } + if ($scalarDef && $this->usesNativeScalarStorage($scalarDef->type)) { $propName = $this->parseIdentifier($property); $typedFetch = $this->emitNativeInstancePropertyTypedFetch( $expr, $objectVar, $propName, $id, - $def, + $scalarDef, $getProperty, ); if ($typedFetch !== null) { - $expr->setAttribute(self::ATTR_LOWERED_TYPE, $def->type); + // A readonly read keeps the dynamic value source and is + // materialized as a Variant, so advertising a native scalar + // type would strip the conversion the surrounding expression + // still needs. + if (!$scalarDef->isReadonly()) { + $expr->setAttribute(self::ATTR_LOWERED_TYPE, $scalarDef->type); + } return $typedFetch; } } + // Falls back after the hoisting path: a hoisted slot reference is + // cheaper than re-resolving the offset on every read, so the typed + // fetch must get the first chance to claim a stable receiver. + if ($property instanceof Node\Identifier) { + $scalarRead = $this->emitDeclaredScalarPropertyRead( + $expr, + $objectVar, + $objectName, + $this->parseIdentifier($property), + $scalarDef, + $update, + ); + if ($scalarRead !== null) { + return $scalarRead; + } + } if ($def) { $this->setNativePropertyValueSource($expr, self::NATIVE_PROPERTY_VALUE_DYNAMIC); } @@ -1437,6 +1482,118 @@ protected function emitPropertyHookSetterCall(Expr\PropertyFetch $expr, string $ return $this->parseMethodCall($call); } + /** + * Lower a read of a declared scalar property to its zval slot. + * + * `attr(offset, AttrMode::Get)` materializes a Variant for every read, + * including the refcount traffic and the temporary that follows. When the + * property is stored as a plain zval scalar, the typed accessor reads the + * same slot without boxing, which removes that cost from hot loops. + * + * The receiver's property offset must not move across the inheritance + * chain, which `isPropertyOffsetStable()` proves; both `$this` and typed + * object variables qualify. Readonly properties keep the Zend + * initialization check, nullable properties may hold null (which the typed + * accessors reject), and hooks require their own lowering, so all three + * keep the existing path. + */ + private function emitDeclaredScalarPropertyRead( + Expr\PropertyFetch $expr, + string $objectVar, + string $objectName, + string $propName, + ?PropertyDef $def, + bool $update, + ): ?string { + if ($def === null) { + $def = $this->findReadablePropertyDefinition($expr); + } + if ($def === null + || $update + || $def->isReadonly() + || $def->nullable + || $def->isStatic() + || $def->getter !== null + || $def->setter !== null + || $def->virtual) { + return null; + } + if ($def->type !== Type::INT && $def->type !== Type::FLOAT) { + return null; + } + if (!$this->usesNativeScalarStorage($def->type)) { + return null; + } + if ($objectVar === 'this_') { + // A trait method compiles before it knows the using class, so the + // offset cannot be resolved for `$this` there. + if ($this->classDef?->trait) { + return null; + } + $receiverClass = $this->getFullClassName(); + } elseif ($this->isTypedObject($objectName)) { + // A proven runtime class does not imply object storage: a `mixed` + // parameter narrowed by instanceof keeps Variant storage, and only + // Object exposes the typed accessors. + if ($this->getVarType($objectName) !== Type::OBJECT) { + return null; + } + $receiverClass = $this->getObjectType($objectName); + } else { + return null; + } + if ($receiverClass === '' + || $this->isNativeObjectClass($receiverClass) + || !$this->isPropertyOffsetStable($receiverClass, $propName)) { + return null; + } + $accessor = $def->type === Type::INT ? 'attrInt' : 'attrFloat'; + $this->setNativePropertyValueSource($expr, self::NATIVE_PROPERTY_VALUE_VAR); + $expr->setAttribute(self::ATTR_LOWERED_TYPE, $def->type); + return $objectVar . '.' . $accessor + . '(' . $this->getPropertyOffset($receiverClass, $propName) . ')'; + } + + /** + * Prove that `$class::$prop` keeps one zval slot for every subclass. + * + * Zend reuses the parent's slot when a child redeclares a non-private + * property, so the declaring class offset stays valid for subclass + * instances. A child that adds a property hook the parent does not have is + * the exception: Zend resets the parent slot to IS_UNDEF and moves the + * child to a fresh offset, which would make the parent offset read the + * wrong slot. Unknown classes stay on the Variant path. + */ + private function isPropertyOffsetStable(string $class, string $prop): bool + { + if (!$this->hasClass($class)) { + return false; + } + if ($this->isFinalClass($class)) { + return true; + } + $pending = $this->classSubClasses[strtolower(ltrim($class, '\\'))] ?? []; + $visited = []; + while ($pending !== []) { + $sub = array_shift($pending); + if (isset($visited[$sub])) { + continue; + } + $visited[$sub] = true; + $subDef = $this->getClassDef($sub); + if ($subDef !== null && $subDef->hasProperty($prop)) { + $property = $subDef->getProperty($prop); + if ($property->getter !== null || $property->setter !== null || $property->virtual) { + return false; + } + } + foreach ($this->classSubClasses[$sub] ?? [] as $grandChild) { + $pending[] = $grandChild; + } + } + return true; + } + private function emitNativeInstancePropertyTypedFetch( Expr\PropertyFetch $expr, string $objectVar, diff --git a/tests/compiler/object_property/declared-scalar-read-default-initialization.phpt b/tests/compiler/object_property/declared-scalar-read-default-initialization.phpt new file mode 100644 index 00000000..be931233 --- /dev/null +++ b/tests/compiler/object_property/declared-scalar-read-default-initialization.phpt @@ -0,0 +1,27 @@ +--TEST-- +declared scalar properties without defaults read as zero through typed receivers +--FILE-- +count; +} + +function main(): void +{ + $box = new DefaultScalarBox(); + var_dump(readCount($box)); + var_dump($box->count); + var_dump($box->ratio); +} +?> +--EXPECT-- +int(0) +int(0) +float(0) diff --git a/tests/compiler/object_property/declared-scalar-read-final-class.phpt b/tests/compiler/object_property/declared-scalar-read-final-class.phpt new file mode 100644 index 00000000..f2b2262c --- /dev/null +++ b/tests/compiler/object_property/declared-scalar-read-final-class.phpt @@ -0,0 +1,36 @@ +--TEST-- +final class public int and float properties read through typed receivers +--FILE-- +ratio + $this->count; + } +} + +function accumulate(ScalarBox $box, int $iterations): float +{ + $sum = 0.0; + for ($i = 0; $i < $iterations; $i++) { + $sum += $box->ratio + $box->count; + } + return $sum; +} + +function main(): void +{ + $box = new ScalarBox(); + $box->count = 7; + $box->ratio = 1.5; + var_dump(accumulate($box, 10)); + var_dump($box->total()); +} +?> +--EXPECT-- +float(85) +float(8.5) diff --git a/tests/compiler/object_property/declared-scalar-read-narrowed-mixed.phpt b/tests/compiler/object_property/declared-scalar-read-narrowed-mixed.phpt new file mode 100644 index 00000000..cb4f6222 --- /dev/null +++ b/tests/compiler/object_property/declared-scalar-read-narrowed-mixed.phpt @@ -0,0 +1,26 @@ +--TEST-- +instanceof narrowed mixed receivers keep the Variant property read +--FILE-- +count; + } + return -1; +} + +function main(): void +{ + var_dump(readCount(new NarrowedScalarBox())); + var_dump(readCount(new stdClass())); +} +?> +--EXPECT-- +int(3) +int(-1) diff --git a/tests/compiler/object_property/declared-scalar-read-nullable.phpt b/tests/compiler/object_property/declared-scalar-read-nullable.phpt new file mode 100644 index 00000000..0302926e --- /dev/null +++ b/tests/compiler/object_property/declared-scalar-read-nullable.phpt @@ -0,0 +1,28 @@ +--TEST-- +nullable declared scalar properties keep returning null instead of a typed read +--FILE-- +count; +} + +function main(): void +{ + $box = new NullableScalarBox(); + var_dump(readCount($box)); + $box->count = 42; + var_dump(readCount($box)); + $box->count = null; + var_dump(readCount($box)); +} +?> +--EXPECT-- +NULL +int(42) +NULL diff --git a/tests/compiler/object_property/declared-scalar-read-subclass-redeclare.phpt b/tests/compiler/object_property/declared-scalar-read-subclass-redeclare.phpt new file mode 100644 index 00000000..6368071e --- /dev/null +++ b/tests/compiler/object_property/declared-scalar-read-subclass-redeclare.phpt @@ -0,0 +1,37 @@ +--TEST-- +a subclass redeclaring a scalar property reuses the parent slot +--FILE-- +count; + } +} + +class ChildScalarBox extends BaseScalarBox +{ + public int $count = 2; +} + +function readCount(BaseScalarBox $box): int +{ + return $box->count; +} + +function main(): void +{ + var_dump((new BaseScalarBox())->own()); + var_dump(readCount(new ChildScalarBox())); + $box = new ChildScalarBox(); + $box->count = 5; + var_dump(readCount($box)); +} +?> +--EXPECT-- +int(1) +int(2) +int(5)