In lesson 129 Ruby ran instructions: every time opt_mult runs, it checks whether both sides are Integers and Integer#* is still the original, and only then multiplies. A method called a million times asks those questions a million times. Since Ruby 4.0, CRuby has a second compiler for such methods: ZJIT, a just-in-time compiler. Once a method is hot, ZJIT turns its instructions into machine code for the processor – code that has answered most of those questions in advance.
ZJIT is new and experimental: in Ruby 4.0.0 it is faster than the interpreter but not yet as fast as YJIT, the JIT that came before it, and the Ruby team aims to make it ready for production in Ruby 4.1. It is not in this page, either: ZJIT writes x86-64 or arm64 machine code, and this Ruby runs as WebAssembly.
puts RUBY_DESCRIPTION
p defined?(RubyVM::ZJIT)nil – this Ruby has no ZJIT. (On your computer, ruby --zjit adds +ZJIT to the description.) So this lesson takes ZJIT apart into its steps and builds each one as a small Ruby model that runs here, on this Ruby's real instructions.
1. Counting calls
ZJIT compiles whole methods; YJIT compiles small pieces as it meets them. Which methods? Every call of a method adds 1 to a counter in its instruction sequence. At call 25, CRuby swaps some instructions for zjit_* twins that profile: zjit_opt_mult does what opt_mult does and also notes the classes of both operands. At call 30 ZJIT compiles the method, and from then on the machine code runs. Both numbers are options: --zjit-call-threshold (30) and --zjit-num-profiles (5). A TracePoint can count calls the same way:
# A model of how CRuby counts calls (vm.c) and ZJIT profiles
def watch(name)
call_threshold = 30 # --zjit-call-threshold
num_profiles = 5 # --zjit-num-profiles
calls = 0
seen = Hash.new { |hash, param| hash[param] = [] }
trace = TracePoint.new(:call) do |tp|
next unless tp.method_id == name
calls += 1
puts "call #{calls}: profiling starts" if calls == call_threshold - num_profiles
if calls >= call_threshold - num_profiles && calls < call_threshold
tp.parameters.each { |_, param| seen[param] << tp.binding.local_variable_get(param).class }
end
puts "call #{calls}: compiling #{name}" if calls == call_threshold
end
trace.enable { yield }
seen.transform_values(&:uniq)
end
def area(w, h) = w * h
watch(:area) { 40.times { |i| area(i, 3) } }Five calls were profiled, and every time both values were Integers – that is all ZJIT knows about area when it compiles it. (The model notes the classes of the parameters; ZJIT notes the operands of instructions such as opt_mult, opt_lt or opt_aref – here these are the same values.)
2. From YARV to HIR
Instructions work on a stack: getlocal pushes, opt_mult pops two values and pushes the result. ZJIT first translates them into its HIR (high-level intermediate representation), which has no stack: every value has a name of its own – v1, v2 … – given exactly once (static single assignment, SSA), so every instruction names the values it uses. Nothing is assumed yet: * is a plain method call, SendWithoutBlock. The model translates the few instructions it knows:
# A small model of ZJIT's first step: YARV in, HIR out.
# Each value gets a name of its own, v1, v2 ... - the stack is gone.
def to_hir(meth)
iseq = RubyVM::InstructionSequence.of(meth).to_a
locals = iseq[10]
hir = []
value = ->(*insn) { name = "v#{hir.size + 1}"; hir << [name, *insn]; name }
params = locals.map { |local| value.(:Param, local) }
stack = []
iseq.last.grep(Array).each do |insn, *operands|
case insn
when :getlocal_WC_0 then stack << params[locals.size - operands[0] + 2]
when :putobject_INT2FIX_0_ then stack << value.(:Const, 0)
when :putobject_INT2FIX_1_ then stack << value.(:Const, 1)
when :putobject then stack << value.(:Const, operands[0])
when :opt_plus, :opt_minus, :opt_mult, :opt_lt
right = stack.pop
left = stack.pop
stack << value.(:SendWithoutBlock, left, operands[0][:mid], right)
when :leave then hir << [nil, :Return, stack.pop]
else hir << [nil, :NotInThisModel, insn]
end
end
hir
end
def show_hir(hir)
hir.each do |dst, op, *args|
shown = args.map { |arg| arg.is_a?(String) ? arg : arg.inspect }
puts "#{"#{dst} = " if dst}#{op} #{shown.join(", ")}"
end
nil
end
def bill(price, count) = price * count + 2
show_hir to_hir(method(:bill))v3 is price * count, v5 is v3 + v4 – the stack is gone. (getlocal_WC_0's operand counts from the frame's ep, lesson 130: three env slots come first, so the last local is 3 – hence locals.size - operands[0] + 2.)
3. Specializing with the profile
Now ZJIT's optimizer runs its passes: type_specialize, inline, optimize_c_calls, fold_constants, eliminate_dead_code and a few more. The first one uses the profile. For a method a + 1 whose a was only ever an Integer, this is ZJIT's real HIR (from its own tests, shortened):
v14:Fixnum[1] = Const Value(1) PatchPoint MethodRedefined(Integer, +) v24:Fixnum = GuardType v9, Fixnum v25:Fixnum = FixnumAdd v24, v14 Return v25
GuardType v9, Fixnumchecks at run time what the profile only suggested: isaa Fixnum? ThenFixnumAddadds two machine words – no method lookup, no call.v14is the constant 1. Its type is certain, so it needs no guard.- The type after each name (
v25:Fixnum) is what ZJIT knows about the value. The result ofFixnumAddis a Fixnum too, so a later+onv25needs no guard either.
And when a guard fails – someone calls area(1.5, 2)? Then the code takes a side exit: it rebuilds the frame the interpreter expects and hands over at that very instruction. The method still works; only this call is slow. Here is the model's HIR runner, with an area specialized by hand:
# Running HIR: when a GuardType fails, the interpreter takes over
def fixnum_op(name) = { :+ => :FixnumAdd, :- => :FixnumSub, :* => :FixnumMult }[name]
def run_hir(hir, meth, *args)
fixnum = ->(v) { v.is_a?(Integer) && v.bit_length <= 0.size * 8 - 2 }
values = {}
params = args.dup
hir.each do |dst, op, *ops|
case op
when :Param then values[dst] = params.shift
when :Const then values[dst] = ops[0]
when :GuardType
unless fixnum.(values[ops[0]])
puts "side exit at #{ops[0]} = #{values[ops[0]].inspect}: back to the interpreter"
return meth.(*args)
end
when :FixnumAdd then values[dst] = values[ops[0]] + values[ops[1]]
when :FixnumSub then values[dst] = values[ops[0]] - values[ops[1]]
when :FixnumMult then values[dst] = values[ops[0]] * values[ops[1]]
when :SendWithoutBlock then values[dst] = values[ops[0]].public_send(ops[1], values[ops[2]])
when :Return then return values[ops[0]]
end
end
end
fast_area = [
["v1", :Param, :w], ["v2", :Param, :h],
[nil, :GuardType, "v1", :Fixnum], [nil, :GuardType, "v2", :Fixnum],
["v3", :FixnumMult, "v1", "v2"], [nil, :Return, "v3"]
]
show_hir fast_area
p run_hir(fast_area, method(:area), 6, 7)
p run_hir(fast_area, method(:area), 1.5, 2)The guard caught 1.5, and the interpreter computed 3.0 – the right answer, the slow way. A JIT bets on the profile; a side exit loses the bet gracefully.
And PatchPoint MethodRedefined(Integer, +)? That check costs nothing at run time: ZJIT notes that this code assumes the original Integer#+. Whoever redefines it makes CRuby call rb_zjit_bop_redefined, the code is thrown away, and with Warning[:performance] = true Ruby says so: Redefining 'Integer#+' disables interpreter and JIT optimizations. Thanks to that promise ZJIT may even fold 1 + 2 + 3 into the constant 6 – the very thing the YARV compiler in lesson 129 could not risk. Last, ZJIT lowers HIR to LIR (low-level IR: registers and memory) and writes the machine code.
- Counting calls:
zjit_compile:536in vm.c – profiling fromrb_zjit_profile_threshold, compiling atrb_zjit_call_threshold; the defaults 30 and 5 inoptions.rs:10. - What is profiled:
profile_insn:61–opt_plus,opt_lt,opt_aref, instance variables and more. - The passes in order:
Function::optimize:4367. A profile turned into a guard:try_inline_fixnum_op:536withlikely_a, coerce_to:2515– the model'sknownin Rust. - The HIR above:
test_replace_guard_if_known_fixnum:571;1 + 2 + 3folded to 6:test_fold_fixnum_add:94. - A redefinition throws compiled code away:
rb_zjit_bop_redefined:2372in vm.c, beside the warning.
ruby --zjit -e 'p RubyVM::ZJIT.enabled?' prints true. ruby --zjit --zjit-stats yourscript.rb prints at the end what ZJIT compiled and how it went; ruby --help lists the options.specialize(hir, profile), the heart of type_specialize in the model. Go through the HIR once and keep in known what you learn: a Param whose profile is exactly [Integer] is probably a Fixnum (:param, it needs a guard), a Const holding an Integer certainly is (:sure). A SendWithoutBlock of +, - or * (fixnum_op gives the HIR name) with two known operands becomes a GuardType for each operand that is only :param, followed by the Fixnum instruction – and its result is :sure. Everything else stays as it is. For area with { w: [Integer], h: [Integer] } you get exactly fast_area; with w: [Integer, Float] nothing changes.def specialize(hir, profile)
known = {} # value => :param (needs a GuardType) or :sure
hir.flat_map do |dst, op, *args|
# remember Params and Consts in known; a Send of + - * on two
# known values becomes GuardTypes and the Fixnum instruction
[[dst, op, *args]]
end
end
show_hir specialize(to_hir(method(:area)), { w: [Integer], h: [Integer] })