Skip to content

Commit 36f90ba

Browse files
authored
Merge pull request #21319 from JuliaLang/jb/fix21311
fix #21311, inlining `_apply` reordering evaluations
2 parents 12f6747 + a27ce01 commit 36f90ba

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

base/inference.jl

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4491,6 +4491,8 @@ function inlining_pass(e::Expr, sv::InferenceState, stmts, ins)
44914491
if f === _apply
44924492
na = length(e.args)
44934493
newargs = Vector{Any}(na-2)
4494+
newstmts = Any[]
4495+
effect_free_upto = 0
44944496
for i = 3:na
44954497
aarg = e.args[i]
44964498
argt = exprtype(aarg, sv.src, sv.mod)
@@ -4507,14 +4509,25 @@ function inlining_pass(e::Expr, sv::InferenceState, stmts, ins)
45074509
newargs[i-2] = Any[ QuoteNode(x) for x in aarg ]
45084510
elseif isa(t, DataType) && t.name === Tuple.name && !isvatuple(t) &&
45094511
length(t.parameters) <= sv.params.MAX_TUPLE_SPLAT
4512+
for k = (effect_free_upto+1):(i-3)
4513+
as = newargs[k]
4514+
for kk = 1:length(as)
4515+
ak = as[kk]
4516+
if !effect_free(ak, sv.src, sv.mod, true)
4517+
tmpv = newvar!(sv, widenconst(exprtype(ak, sv.src, sv.mod)))
4518+
push!(newstmts, Expr(:(=), tmpv, ak))
4519+
as[kk] = tmpv
4520+
end
4521+
end
4522+
end
4523+
effect_free_upto = i-3
45104524
if effect_free(aarg, sv.src, sv.mod, true)
45114525
# apply(f,t::(x,y)) => f(t[1],t[2])
45124526
tmpv = aarg
45134527
else
45144528
# apply(f,t::(x,y)) => tmp=t; f(tmp[1],tmp[2])
45154529
tmpv = newvar!(sv, t)
4516-
insert!(stmts, ins, Expr(:(=), tmpv, aarg))
4517-
ins += 1
4530+
push!(newstmts, Expr(:(=), tmpv, aarg))
45184531
end
45194532
tp = t.parameters
45204533
newargs[i-2] = Any[ mk_getfield(tmpv,j,tp[j]) for j=1:length(tp) ]
@@ -4523,6 +4536,8 @@ function inlining_pass(e::Expr, sv::InferenceState, stmts, ins)
45234536
return e
45244537
end
45254538
end
4539+
splice!(stmts, ins:ins-1, newstmts)
4540+
ins += length(newstmts)
45264541
e.args = [Any[e.args[2]]; newargs...]
45274542

45284543
# now try to inline the simplified call

test/inline.jl

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,3 +93,21 @@ end
9393
let (src, _) = code_typed(g21074, ())[1]
9494
@test src.code[1] == Expr(:return, 1)
9595
end
96+
97+
# issue #21311
98+
counter21311 = Ref(0)
99+
@noinline function update21311!(x)
100+
counter21311[] += 1
101+
x[] = counter21311[]
102+
return x
103+
end
104+
@noinline map21311(t::Tuple{Any}) = (update21311!(t[1]),)
105+
@inline map21311(t::Tuple) = (update21311!(t[1]), map21311(Base.tail(t))...)
106+
function read21311()
107+
xs = Ref(1), Ref(1)
108+
map21311(xs)
109+
return xs[1]
110+
end
111+
let a = read21311()
112+
@test a[] == 1
113+
end

0 commit comments

Comments
 (0)