Skip to content

Commit 04138bf

Browse files
authored
Support "Functor-like" code_typed invocation (JuliaLang#57911)
This lets you easily inspect IR associated with "Functor-like" methods: ```julia julia> (f::Foo)(offset::Float64) = f.x + f.y + offset julia> code_typed((Foo, Float64)) 1-element Vector{Any}: CodeInfo( 1 ─ %1 = Base.getfield(f, :x)::Int64 │ %2 = Base.getfield(f, :y)::Int64 │ %3 = Base.add_int(%1, %2)::Int64 │ %4 = Base.sitofp(Float64, %3)::Float64 │ %5 = Base.add_float(%4, offset)::Float64 └── return %5 ) => Float64 ``` This is just a small convenience over `code_typed_by_type`, but I'm in support of it (even though it technically changes the meaning of, e.g., `code_typed((1, 2))` which without this PR inspects `(::Tuple{Int,Int})(::Vararg{Any})` We should probably update all of our reflection machinery (`code_llvm`, `code_lowered`, `methodinstance`, etc.) to support this "non-arg0" style as well, but I wanted to open this first to make sure folks like it.
1 parent 958d758 commit 04138bf

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

base/reflection.jl

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -211,8 +211,31 @@ julia> code_typed(+, (Float64, Float64))
211211
1 ─ %1 = Base.add_float(x, y)::Float64
212212
└── return %1
213213
) => Float64
214+
215+
julia> code_typed((typeof(-), Float64, Float64))
216+
1-element Vector{Any}:
217+
CodeInfo(
218+
1 ─ %1 = Base.sub_float(x, y)::Float64
219+
└── return %1
220+
) => Float64
221+
222+
julia> code_typed((Type{Int}, UInt8))
223+
1-element Vector{Any}:
224+
CodeInfo(
225+
1 ─ %1 = Core.zext_int(Core.Int64, x)::Int64
226+
└── return %1
227+
) => Int64
228+
229+
julia> code_typed((Returns{Int64},))
230+
1-element Vector{Any}:
231+
CodeInfo(
232+
1 ─ %1 = builtin Base.getfield(obj, :value)::Int64
233+
└── return %1
234+
) => Int64
214235
```
215236
"""
237+
function code_typed end
238+
216239
function code_typed(@nospecialize(f), @nospecialize(types=default_tt(f)); kwargs...)
217240
if isa(f, Core.OpaqueClosure)
218241
return code_typed_opaque_closure(f, types; kwargs...)
@@ -221,6 +244,12 @@ function code_typed(@nospecialize(f), @nospecialize(types=default_tt(f)); kwargs
221244
return code_typed_by_type(tt; kwargs...)
222245
end
223246

247+
# support 'functor'-like queries, such as `(::Foo)(::Int, ::Int)` via `code_typed((Foo, Int, Int))`
248+
function code_typed(@nospecialize(argtypes::Union{Tuple,Type{<:Tuple}}); kwargs...)
249+
tt = to_tuple_type(argtypes)
250+
return code_typed_by_type(tt; kwargs...)
251+
end
252+
224253
# returns argument tuple type which is supposed to be used for `code_typed` and its family;
225254
# if there is a single method this functions returns the method argument signature,
226255
# otherwise returns `Tuple` that doesn't match with any signature

0 commit comments

Comments
 (0)