For what it’s worth, there’s a currently open PR specifically trying to fix cases like this right now under active development: perform inference using optimizer-derived type information by aviatesk · Pull Request #56687 · JuliaLang/julia · GitHub
The idea is that after things like type inference and dead code elimination, the compiler can go back to a very early point in the pipeline and use knowledge it learned later to say
ah,
x
s type never changes and can’t be lexically modified anywhere in the program, so it’s okay to just letg
return0
instead of forcing it to go through aBox
I’m pretty optimistic this can work. Specifically check out the tests the PR adds showing it can correctly infer return types in very similar functions: julia/Compiler/test/inference.jl at b775f2008d944c376f4f3f9f48ff2a096eb66a74 · JuliaLang/julia · GitHub
These tests are already passing.