From 64b2005c0d9ff5bfff0e86d05c4bc182db902b9f Mon Sep 17 00:00:00 2001 From: Shuhei Kadowaki <40514306+aviatesk@users.noreply.github.com> Date: Thu, 23 Nov 2023 17:02:21 +0900 Subject: [PATCH] optimize cached sources (#518) Otherwise we will see sources with complicated CFG for semi-concrete calls. For the absolute consistency with the base compiler, we should do the round-trip through `jl_compress_ir` to `jl_uncompress_ir` to `inflate_ir`, but we can achieve the (theoretically) same effect by doing `CC.compact!(CC.cfg_simplify!(ir))`. --- src/interpreter.jl | 19 ++++++++++++++----- test/test_Cthulhu.jl | 18 ++++++++++++++++++ 2 files changed, 32 insertions(+), 5 deletions(-) diff --git a/src/interpreter.jl b/src/interpreter.jl index be512048..55e94911 100644 --- a/src/interpreter.jl +++ b/src/interpreter.jl @@ -159,10 +159,15 @@ function CC.finish(state::InferenceState, interp::CthulhuInterpreter) return res end -function create_cthulhu_source(@nospecialize(x), effects::Effects) - isa(x, OptimizationState) || return x - ir = x.ir::IRCode - return OptimizedSource(ir, x.src, x.src.inlineable, effects) +function create_cthulhu_source(@nospecialize(opt), effects::Effects) + isa(opt, OptimizationState) || return opt + # get the (theoretically) same effect as the jl_compress_ir -> jl_uncompress_ir -> inflate_ir round-trip + @static if VERSION ≥ v"1.9-" + ir = CC.compact!(CC.cfg_simplify!(CC.copy(opt.ir::IRCode))) + else + ir = CC.copy(opt.ir::IRCode) + end + return OptimizedSource(ir, opt.src, opt.src.inlineable, effects) end @static if VERSION ≥ v"1.9-" @@ -253,7 +258,11 @@ end @static if VERSION ≥ v"1.11.0-DEV.737" function CC.finish!(interp::CthulhuInterpreter, caller::InferenceState) result = caller.result - result.src = create_cthulhu_source(result.src, result.ipo_effects) + opt = result.src + result.src = create_cthulhu_source(opt, result.ipo_effects) + if opt isa CC.OptimizationState + CC.ir_to_codeinf!(opt) + end return nothing end else diff --git a/test/test_Cthulhu.jl b/test/test_Cthulhu.jl index cc175b94..b1f15302 100644 --- a/test/test_Cthulhu.jl +++ b/test/test_Cthulhu.jl @@ -1015,4 +1015,22 @@ end @test String(take!(io)) == ":toplevel(::Float64)::Float64" end +@static if VERSION ≥ v"1.9" +@inline countvars50037(bitflags::Int, var::Int) = bitflags >> 0 +let (interp, mi) = Cthulhu.mkinterp((Int,)) do var::Int + countvars50037(1, var) + end + key = nothing + for (mi, codeinst) in interp.opt + if mi.def.name === :countvars50037 + key = mi + break + end + end + codeinst = interp.opt[key] + inferred = @atomic :monotonic codeinst.inferred + @test length(inferred.ir.cfg.blocks) == 1 +end +end + end # module test_Cthulhu