julia icon indicating copy to clipboard operation
julia copied to clipboard

`@noinline` confuses `@code_typed` reporting wrong return type when return value is unused.

Open NHDaly opened this issue 1 year ago • 5 comments

Just a small bug in the @code_typed information for a function that calls a no-inlined callee (with side effects), whose return value is unused:

julia> @noinline f() = (println(); true)
f (generic function with 1 method)

julia> f1(x) = (f(); return x+1)
f1 (generic function with 1 method)

julia> @code_typed f1(10)
CodeInfo(
1 ─      invoke Main.f()::Any
│   %2 = Base.add_int(x, 1)::Int64
└──      return %2
) => Int64

The incorrect line is: invoke Main.f()::Any. This should instead be: invoke Main.f()::Bool.

Of course, since the return value is unused, this isn't very consequential, but it confused me as a red herring for a bit in a more complicated scenario earlier today.

Finally, it's worth noting that the compiler does know the true return type, since @code_llvm shows it return an i8:

julia> @code_llvm f1(10)
; Function Signature: f1(Int64)
;  @ REPL[16]:1 within `f1`
define i64 @julia_f1_2311(i64 signext %"x::Int64") #0 {
top:
  %0 = call i8 @j_f_2314()
; ┌ @ int.jl:87 within `+`
   %1 = add i64 %"x::Int64", 1
; └
  ret i64 %1
}

NHDaly avatar Jan 05 '24 22:01 NHDaly

This behavior is deliberate. Inference widens the result of return type inference to Any when it detects that the callee's return value isn't being used in the caller context. This strategy avoids having to add a backedge from the caller to the callee when the callee isn't inlined. While I agree with you that it might not be immediately obvious, tools like @code_warntype are designed not to issue warnings in such cases.

aviatesk avatar Jan 06 '24 06:01 aviatesk

I also ran into this a while ago. Maybe in cases like this, we should print it without the ::Any to avoid confusion or something?

MasonProtter avatar Jan 07 '24 16:01 MasonProtter

thanks for the explanation, @aviatesk, makes sense!

+1 @MasonProtter that's a great suggestion. I think that would definitely satisfy my request. 👍 Does that seem doable?

NHDaly avatar Jan 09 '24 15:01 NHDaly

Yeah, I believe it's feasible:) If you decide to tackle the implementation, examining the implementation of code_warntype could be beneficial. It is designed to alter warnings about the return type depending on the used-ness of the corresponding SSA-value.

aviatesk avatar Jan 09 '24 15:01 aviatesk

Hi! Should I take a look at something like https://github.com/JuliaLang/julia/blob/931f6de4ca739b5d7a333e941e43ccdc0f5a4051/stdlib/InteractiveUtils/src/codeview.jl#L78 but for typed IR instead of SSA-IR?

xlxs4 avatar May 13 '24 22:05 xlxs4