Skip to content

Commit 9d70d45

Browse files
authored
optimize more tuple splatting independent of length when possible (#35930)
1 parent cebd4fa commit 9d70d45

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

base/compiler/ssair/inlining.jl

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -895,6 +895,26 @@ function inline_apply!(ir::IRCode, idx::Int, sig::Signature, params::Optimizatio
895895
if arg_start > length(atypes)
896896
return nothing
897897
end
898+
ft = atypes[arg_start]
899+
if ft isa Const && ft.val === Core.tuple
900+
# if one argument is a tuple already, and the rest are empty, we can just return it
901+
# e.g. rewrite `((t::Tuple)...,)` to `t`
902+
nonempty_idx = 0
903+
for i = (arg_start + 1):length(atypes)
904+
ti = atypes[i]
905+
ti Tuple{} && continue
906+
if ti Tuple && nonempty_idx == 0
907+
nonempty_idx = i
908+
continue
909+
end
910+
nonempty_idx = 0
911+
break
912+
end
913+
if nonempty_idx != 0
914+
ir.stmts[idx] = stmt.args[nonempty_idx]
915+
return nothing
916+
end
917+
end
898918
# Try to figure out the signature of the function being called
899919
# and if rewrite_apply_exprargs can deal with this form
900920
for i = (arg_start + 1):length(atypes)
@@ -905,12 +925,6 @@ function inline_apply!(ir::IRCode, idx::Int, sig::Signature, params::Optimizatio
905925
end
906926
# Independent of whether we can inline, the above analysis allows us to rewrite
907927
# this apply call to a regular call
908-
ft = atypes[arg_start]
909-
if length(atypes) == arg_start+1 && ft isa Const && ft.val === Core.tuple && atypes[arg_start+1] Tuple
910-
# rewrite `((t::Tuple)...,)` to `t`
911-
ir.stmts[idx] = stmt.args[arg_start+1]
912-
return nothing
913-
end
914928
stmt.args, atypes = rewrite_apply_exprargs!(ir, idx, stmt.args, atypes, arg_start)
915929
has_free_typevars(ft) && return nothing
916930
f = singleton_type(ft)

test/compiler/inline.jl

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,11 @@ end
222222
f_identity_splat(t) = (t...,)
223223
@test length(code_typed(f_identity_splat, (Tuple{Int,Int},))[1][1].code) == 1
224224

225+
# splatting one tuple into (,) plus zero or more empties should reduce
226+
# this pattern appears for example in `fill_to_length`
227+
f_splat_with_empties(t) = (()..., t..., ()..., ()...)
228+
@test length(code_typed(f_splat_with_empties, (NTuple{200,UInt8},))[1][1].code) == 1
229+
225230
# check that <: can be fully eliminated
226231
struct SomeArbitraryStruct; end
227232
function f_subtype()

0 commit comments

Comments
 (0)