HaxeFoundation / HaxeFoundation/haxe

[analyzer] optimize `if (new Something() != null) {...}`

Open
#6,386 0 comments 0 reactions 1 assignee Claimed by @Simn View on GitHub
enhancement feature-analyzer
Dominant language
Haxe
Stars
6.9k
Forks
715
Avg merge
2d 2h
Merged PRs (30d)
11

Description

Consider this example:

```haxe
class Test {
inline function new() {}
inline function f() trace("hi");

static function main() {
var test = new Test();
if (test != null)
test.f();
}
}
```

Currently this generates:
```js
Test.main = function() {
if(new Test() != null) {
console.log("hi");
}
};
```

Obviously the Test allocation here is redundant (since it's pure) and the check is always `true`, so this could be optimized away to just `console.log("hi")`.

Of course when hand-written this code is stupid, but it can occur with some complex macro-generation and it would be nice to have it optimized.

@Simn mentioned that we could rewrite the condition to `{new Test(); true;}` (or `false` in case of `== null`), so it's further optimized and the allocation is eliminated. I tried to add the case to `optimize_binop`, but that didn't help: the block was introduced but never optimized away. I'm not sure how to proceed here and creating this issue so we don't forget :)

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.