RFR: Remove redundant null checks [v5]

Maurizio Cimadamore mcimadamore at openjdk.org
Fri Jan 23 10:13:15 UTC 2026


On Fri, 23 Jan 2026 02:27:07 GMT, Vicente Romero <vromero at openjdk.org> wrote:

>> some of the null checks javac generates are redundant and can be removed
>
> Vicente Romero has updated the pull request incrementally with one additional commit since the last revision:
> 
>   adding more tests

src/jdk.compiler/share/classes/com/sun/tools/javac/comp/NullChecksWriter.java line 218:

> 216: 
> 217:     public void visitTypeCast(JCTypeCast tree) {
> 218:         if (tree.expr instanceof JCTypeCast otherTypeCast && tree.strict && otherTypeCast.strict) {

I think we need to generalize this a bit. E.g. this code will correctly remove double casts. But I think we need to have a global visitor flag saying whether the last thing we visited was already use-site checked (e.g. provablyStrict) -- and then omit any further use site check if that flag is set.

E.g. say we have:


(String!)otherClass.m();


Where `OtherClass::m` is


String! m() { ... }


In this case, after the method call, we know we're already strict because:
* the method is in this compilation unit, so we know the result value will be checked
* the method is in a different compilation unit, so we know we'll get a use site check there

So, emitting a cast at that point is not very useful. We've already checked that thing.

(In fact, thinking more, if use-site checks are enabled, field access and method calls are _always_ eagerly checked -- which should mean that any inner expression is always at the level of strictness it says it is?)

-------------

PR Review Comment: https://git.openjdk.org/valhalla/pull/1947#discussion_r2720572797


More information about the valhalla-dev mailing list