Issue 24332 - Improve downcast to final classes
Summary: Improve downcast to final classes
Status: NEW
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: All All
: P1 enhancement
Assignee: No Owner
URL:
Keywords: industry, performance
Depends on:
Blocks:
 
Reported: 2024-01-11 22:56 UTC by Walter Bright
Modified: 2024-01-13 00:12 UTC (History)
1 user (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Walter Bright 2024-01-11 22:56:46 UTC
deadalnix writes:

class A {}
final class B : A {}

auto foo(A a) {
    return cast(B) a;
}

This generates a call into the runtime, making things completely opaque to the optimizer. The algorithm used by the runtime is linear. But there is a dumb constant time solution. because B is final, a is either an instance of B, or it is not (as in, it cannot be an instance of a subclass of B). Therefore, we expect the codegen to look like the following instead:

auto foo(A a) {
    return typeid(a) is typeid(B) ? a : null;
}

This obviously won't compile but you get the idea. Not only this is constant time, but very simple too, and visible to the optimizer, which means the check can be folded by the opitimizer after other transforms, for instance inlining.

https://forum.dlang.org/post/hteuczyclxajakrisxjd@forum.dlang.org

Here we go: https://github.com/snazzy-d/sdc/blob/master/test/llvm/downcast.d

Except the interface part.
Comment 1 Walter Bright 2024-01-13 00:12:57 UTC
See https://github.com/dlang/dmd/pull/16027 for partial implementation (without inlining)