From 53a7af73d59a9932bff8b11cf00e2edfa5e624d2 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 08:44:41 +0000 Subject: [PATCH 1/5] Share common subexpressions in the generated source kernels only build takes a cse keyword (default false) and only the :source kernels and coefficient functions pass cse = true. Common-subexpression elimination also hoists numeric literals, which turns a literal power u^2 into a libm NaNMath.pow call: 25 to 45 percent slower nonlinear residual and Jacobian assembly in benchmark case (iii). Tests check that the nonlinear and coefficient kernels keep literal_pow and that the CSE'd sources agree with the plain code generator. Agent-Harness: Claude Code 2.1.318 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/kernels.jl | 18 ++++++---- test/Kernels/kernels.jl | 73 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 83 insertions(+), 8 deletions(-) diff --git a/src/kernels.jl b/src/kernels.jl index d738a4e7..ff0d0eb0 100644 --- a/src/kernels.jl +++ b/src/kernels.jl @@ -5,8 +5,11 @@ kernel_slots(s, test) = (s.U, s.G, s.Ud, test.V, test.W, s.X, s.T, s.N, s.P) # `expression = Val(true)` returns the generated `Expr` instead of the compiled function. `build_function` tests # `expression == Val{true}`, the type, so the instance is converted. -build(ex, slots, ::Val{E}) where {E} = Symbolics.build_function(ex, slots...; expression = Val{E}, expression_module = @__MODULE__) -compile(ex, slots; expression = Val(false)) = build(ex, slots, expression) +# `cse` shares repeated subexpressions, which pays for the long manufactured sources. It also hoists numeric literals +# into temporaries, so `u^2` becomes a slow `NaNMath.pow(u, 2)` call instead of `literal_pow`: only the `:source` +# kernels use it, which are evaluated once per quadrature point and not per shape function. +build(ex, slots, ::Val{E}; cse = false) where {E} = Symbolics.build_function(ex, slots...; expression = Val{E}, cse, expression_module = @__MODULE__) +compile(ex, slots; expression = Val(false), cse = false) = build(ex, slots, expression; cse) "The first unevaluated `Differential` call in `ex`, or `nothing`." function find_differential(ex) @@ -79,14 +82,14 @@ hessian_slots(s) = hasproperty(s, :H) && s.H !== nothing ? collect(Num, s.H) : N # A tuple-valued function of `slots`, allocation-free with `Vec` and tuple arguments. Constant entries are # compiled as `Float64`, constant zeros as `zero`. -function compile_tuple(exs, slots; zero = 0.0, expression = Val(false)) +function compile_tuple(exs, slots; zero = 0.0, expression = Val(false), cse = false) entries = map(exs) do ex x = Symbolics.unwrap(ex) SU.isconst(x) || return x value = SU.unwrap_const(x) return iszero(value) ? zero : Float64(value) end - return build(SU.Code.MakeTuple(entries), slots, expression) + return build(SU.Code.MakeTuple(entries), slots, expression; cse) end function compile_tangent(ex, s, slots; expression = Val(false)) @@ -122,10 +125,11 @@ function compile_coeffs(kind, ex, s, test; expression = Val(false)) end isequal(Symbolics.expand(ex - linear), 0) || return nothing any(e -> depends(e, [s.U; s.G; s.Ud; H; w]), exs) && return nothing - cell || return compile_tuple(exs, (s.X, s.T, s.N, s.P); zero = StructuralZero(), expression) + cse = kind === :source + cell || return compile_tuple(exs, (s.X, s.T, s.N, s.P); zero = StructuralZero(), expression, cse) dim2 = length(s.X)^2 fields = Tuple(b for b in eachindex(s.U) if depends(ex, H[((b - 1) * dim2 + 1):min(b * dim2, length(H))])) - return CellCoeffs(compile_tuple(exs, (s.X, s.T, s.N, s.P, test.hK); zero = StructuralZero(), expression), fields) + return CellCoeffs(compile_tuple(exs, (s.X, s.T, s.N, s.P, test.hK); zero = StructuralZero(), expression, cse), fields) end # `f` is compiled only when the driver will call it: without `coeffs`, or for `:nonlinear` terms. @@ -140,7 +144,7 @@ function kernel(eq, kind, piece, integrand, wf::WeakForm; coeffs = true, express ) ) tangent = kind === :nonlinear ? compile_tangent(integrand, s, slots; expression) : nothing - f = c === nothing ? compile(integrand, slots; expression) : nothing + f = c === nothing ? compile(integrand, slots; expression, cse = kind === :source) : nothing return KernelSpec(eq, kind, piece, f, tangent, c) end diff --git a/test/Kernels/kernels.jl b/test/Kernels/kernels.jl index 4c5f0324..df062ac0 100644 --- a/test/Kernels/kernels.jl +++ b/test/Kernels/kernels.jl @@ -2,7 +2,7 @@ # differences, every KernelSpec is concrete, and calls with the driver's slot types do not allocate. import FiniteElementMethod using FiniteElementMethod: weak_form, emit_kernels, emit_dirichlet, WeakForm, VolumeTerm, FacetTerm, TestSlots, - StructuralZero, emit_strong + StructuralZero, emit_strong, build using Ferrite: Vec using Symbolics using Test @@ -223,3 +223,74 @@ end end @test worst ≤ 1.0e-13 end + +# The name of the function a generated call applies: Symbolics embeds the function objects. +callee_name(x) = x isa Expr && x.head === :call ? (x.args[1] isa Function ? nameof(x.args[1]) : x.args[1]) : nothing +# Calls of `^` or `NaNMath.pow` in a generated `Expr` whose exponent is a temporary bound to a number, which is what +# common-subexpression elimination makes of a literal exponent (`literal_pow` becomes a libm `pow` call). +function hoisted_exponents(ex) + numbers = Set{Symbol}() + found = Any[] + walk(x) = x + function walk(x::Expr) + x.head === :(=) && x.args[1] isa Symbol && x.args[2] isa Number && push!(numbers, x.args[1]) + powers = callee_name(x) in (:^, :pow) + powers && length(x.args) == 3 && x.args[3] isa Symbol && push!(found, x) + foreach(walk, x.args) + return x + end + walk(ex) + return [call for call in found if call.args[3] in numbers] +end +count_calls(ex, name) = ex isa Expr ? (callee_name(ex) === name) + sum(a -> count_calls(a, name), ex.args; init = 0) : 0 + +@testset "only the source kernels share subexpressions: a literal power stays a literal_pow" begin + for (name, case) in ("(iii)" => case_iii, "two-field" => two_field) + kernels = emit_kernels(weak_form(case()); expression = Val(true)) + @test any(k -> k.kind === :nonlinear, kernels) + for k in kernels, ex in (k.f, k.tangent, k.coeffs) + ex === nothing && continue + k.kind === :source && continue + @test isempty(hoisted_exponents(ex)) + end + # not vacuous: the squares are there, as `literal_pow` calls + powers = sum(count_calls(ex, :literal_pow) for k in kernels if k.kind === :nonlinear for ex in (k.f, k.tangent) if ex !== nothing) + @test powers > 0 + end + @variables ξ η + squares = ξ^2 * η + 2 * ξ * η + ξ^2 + @test isempty(hoisted_exponents(build(squares, (ξ, η), Val(true)))) + @test !isempty(hoisted_exponents(build(squares, (ξ, η), Val(true); cse = true))) # the hazard the default avoids +end + +@testset "common-subexpression elimination of a source agrees with the plain code generator" begin + @variables ξ η τ p1 p2 + slots = (ξ, η, τ, p1, p2) + plain(ex) = Symbolics.build_function(ex, slots...; expression = Val(false), cse = false, expression_module = FiniteElementMethod) + manufactured = exp(-τ) * sum(1:8) do j + sin((1 + 0.3j) * ξ + τ) * cos((1 + 0.2j) * η) * exp(-0.05j * ξ * η) * (1 + ξ^2 * η)^(0.5 + 0.1j) + end + long = expand_derivatives(Differential(τ)(manufactured) - Differential(ξ)(Differential(ξ)(manufactured)) - Differential(η)(Differential(η)(manufactured))) + zoo = ( + "ordinary" => sin(π * ξ) * sin(π * η) * exp(-τ) + 1, + "long" => long, + "parameters and time" => p1 * (ξ * η + τ)^2 + p2 * sin(ξ * τ) / (1 + η^2) - (ξ * η + τ)^2, + "squares" => (1 - ξ)^2 * sin(τ)^2 + η^2 * cos(ξ * η)^2 + (1 - η)^2 * p1^2 * exp(-ξ^2), + ) + for (name, ex) in zoo + cse, reference = build(ex, slots, Val(false); cse = true), plain(ex) + for _ in 1:20 + point = (0.5 + rand(), 0.5 + rand(), rand(), 0.5 + rand(), 0.5 + rand()) + @test isapprox(cse(point...), reference(point...); rtol = 1.0e-12) + end + end + # through the emitters: a long source gives the same value as the symbolic integrand + an = analyse([Dt(U) ~ Dx(k * Dx(U)) + Dy(k * Dy(U)) + sum(j -> sin(j * x + t) * cos(j * y)^2 * exp(-j * x * y) * (1 + x^2 * y)^(0.5 + 0.1j), 1:4)], BC[]; depvars = [U], t, sivs = [x, y], params = [k, α, β, h]) + wf = weak_form(an) + args = random_args(an) + for kernel in emit_kernels(wf; coeffs = false) + kernel.kind === :source || continue + term = only(filter(term -> term.eq == kernel.eq && term.kind === :source, wf.volume)) + @test isapprox(kernel.f(args...), symbolic_value(term.integrand, wf, args); rtol = 1.0e-12) + end +end From 42a13d026f79b15a6175fb6ca2fb57c9f3a012e8 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 08:51:49 +0000 Subject: [PATCH 2/5] Inline numeric literal temporaries of the CSE'd sources Common-subexpression elimination hoists literals into temporaries, which turns u^2 into a NaNMath.pow call (2x slower on a polynomial source). build substitutes the literal temporaries back and restores literal_pow before compiling. Tests check that no kernel, source or not, has a pow call on a hoisted exponent. Agent-Harness: Claude Code 2.1.318 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/kernels.jl | 38 +++++++++++++++++++++++++++++++++++--- test/Kernels/kernels.jl | 21 +++++++++++++++------ 2 files changed, 50 insertions(+), 9 deletions(-) diff --git a/src/kernels.jl b/src/kernels.jl index ff0d0eb0..1ed22e57 100644 --- a/src/kernels.jl +++ b/src/kernels.jl @@ -6,9 +6,41 @@ kernel_slots(s, test) = (s.U, s.G, s.Ud, test.V, test.W, s.X, s.T, s.N, s.P) # `expression = Val(true)` returns the generated `Expr` instead of the compiled function. `build_function` tests # `expression == Val{true}`, the type, so the instance is converted. # `cse` shares repeated subexpressions, which pays for the long manufactured sources. It also hoists numeric literals -# into temporaries, so `u^2` becomes a slow `NaNMath.pow(u, 2)` call instead of `literal_pow`: only the `:source` -# kernels use it, which are evaluated once per quadrature point and not per shape function. -build(ex, slots, ::Val{E}; cse = false) where {E} = Symbolics.build_function(ex, slots...; expression = Val{E}, cse, expression_module = @__MODULE__) +# into temporaries, so `u^2` becomes a libm `NaNMath.pow(u, 2)` call instead of `literal_pow`, 2× to 10× slower on a +# polynomial source and 25 to 45 percent on the nonlinear residual and Jacobian: `inline_literals` puts the literals back. +# Only the `:source` kernels use `cse`, which are evaluated once per quadrature point and not per shape function. +function build(ex, slots, ::Val{E}; cse = false) where {E} + cse || return Symbolics.build_function(ex, slots...; expression = Val{E}, expression_module = @__MODULE__) + code = Symbolics.build_function(ex, slots...; expression = Val{true}, cse, expression_module = @__MODULE__) + code = inline_literals(code) + return E ? code : RuntimeGeneratedFunctions.RuntimeGeneratedFunction(@__MODULE__, @__MODULE__, code) +end + +# The numeric temporaries `var"##cse#k" = 2` that are assigned once, substituted into their uses and dropped, and +# `NaNMath.pow(x, 2)` with an integer literal exponent back as `Base.literal_pow(^, x, Val(2))`. +function inline_literals(code) + literals = Dict{Symbol, Union{Number, Missing}}() + collect_literals!(literals, code) + filter!(p -> !ismissing(p.second), literals) + return substitute_literals(code, literals) +end +collect_literals!(literals, x) = nothing +function collect_literals!(literals, ex::Expr) + if ex.head === :(=) && ex.args[1] isa Symbol + literals[ex.args[1]] = haskey(literals, ex.args[1]) || !(ex.args[2] isa Number) ? missing : ex.args[2] + end + foreach(arg -> collect_literals!(literals, arg), ex.args) + return nothing +end +substitute_literals(x, literals) = x isa Symbol ? get(literals, x, x) : x +function substitute_literals(ex::Expr, literals) + isliteral(arg) = arg isa Expr && arg.head === :(=) && haskey(literals, arg.args[1]) + args = Any[substitute_literals(arg, literals) for arg in ex.args if !isliteral(arg)] + if ex.head === :call && length(args) == 3 && args[1] isa Function && nameof(args[1]) === :pow && args[3] isa Integer + return Expr(:call, Base.literal_pow, ^, args[2], Expr(:call, Val, args[3])) + end + return Expr(ex.head, args...) +end compile(ex, slots; expression = Val(false), cse = false) = build(ex, slots, expression; cse) "The first unevaluated `Differential` call in `ex`, or `nothing`." diff --git a/test/Kernels/kernels.jl b/test/Kernels/kernels.jl index df062ac0..29dfd5f2 100644 --- a/test/Kernels/kernels.jl +++ b/test/Kernels/kernels.jl @@ -224,8 +224,12 @@ end @test worst ≤ 1.0e-13 end -# The name of the function a generated call applies: Symbolics embeds the function objects. -callee_name(x) = x isa Expr && x.head === :call ? (x.args[1] isa Function ? nameof(x.args[1]) : x.args[1]) : nothing +# The name of the function a generated call applies: Symbolics embeds function objects and global references. +function callee_name(x) + x isa Expr && x.head === :call || return nothing + callee = x.args[1] + return callee isa Function ? nameof(callee) : callee isa GlobalRef ? callee.name : callee +end # Calls of `^` or `NaNMath.pow` in a generated `Expr` whose exponent is a temporary bound to a number, which is what # common-subexpression elimination makes of a literal exponent (`literal_pow` becomes a libm `pow` call). function hoisted_exponents(ex) @@ -244,13 +248,12 @@ function hoisted_exponents(ex) end count_calls(ex, name) = ex isa Expr ? (callee_name(ex) === name) + sum(a -> count_calls(a, name), ex.args; init = 0) : 0 -@testset "only the source kernels share subexpressions: a literal power stays a literal_pow" begin +@testset "no kernel turns a literal power into a pow call on a hoisted exponent" begin for (name, case) in ("(iii)" => case_iii, "two-field" => two_field) kernels = emit_kernels(weak_form(case()); expression = Val(true)) @test any(k -> k.kind === :nonlinear, kernels) for k in kernels, ex in (k.f, k.tangent, k.coeffs) ex === nothing && continue - k.kind === :source && continue @test isempty(hoisted_exponents(ex)) end # not vacuous: the squares are there, as `literal_pow` calls @@ -259,8 +262,11 @@ count_calls(ex, name) = ex isa Expr ? (callee_name(ex) === name) + sum(a -> coun end @variables ξ η squares = ξ^2 * η + 2 * ξ * η + ξ^2 - @test isempty(hoisted_exponents(build(squares, (ξ, η), Val(true)))) - @test !isempty(hoisted_exponents(build(squares, (ξ, η), Val(true); cse = true))) # the hazard the default avoids + for cse in (false, true) + code = build(squares, (ξ, η), Val(true); cse) + @test isempty(hoisted_exponents(code)) + @test count_calls(code, :literal_pow) > 0 + end end @testset "common-subexpression elimination of a source agrees with the plain code generator" begin @@ -284,6 +290,9 @@ end @test isapprox(cse(point...), reference(point...); rtol = 1.0e-12) end end + # it does share: the long source evaluates fewer sin calls + shared, plain_code = build(long, slots, Val(true); cse = true), Symbolics.build_function(long, slots...; expression = Val{true}, cse = false, expression_module = FiniteElementMethod) + @test count_calls(shared, :sin) < count_calls(plain_code, :sin) # through the emitters: a long source gives the same value as the symbolic integrand an = analyse([Dt(U) ~ Dx(k * Dx(U)) + Dy(k * Dy(U)) + sum(j -> sin(j * x + t) * cos(j * y)^2 * exp(-j * x * y) * (1 + x^2 * y)^(0.5 + 0.1j), 1:4)], BC[]; depvars = [U], t, sivs = [x, y], params = [k, α, β, h]) wf = weak_form(an) From 2ce089059a05fa768bcdde47e94a697be8f99671 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 09:08:05 +0000 Subject: [PATCH 3/5] Keep the branches of a guarded source lazy cse hoists the calls in both branches of an ifelse in front of the conditional, so a guarded registered function or sqrt can throw where the plain code never reaches it. Sources containing ifelse compile without cse. Agent-Harness: Claude Code 2.1.318 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/kernels.jl | 13 +++++++++++-- test/Kernels/kernels.jl | 18 ++++++++++++++++++ 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/kernels.jl b/src/kernels.jl index 1ed22e57..8a7610fc 100644 --- a/src/kernels.jl +++ b/src/kernels.jl @@ -16,6 +16,15 @@ function build(ex, slots, ::Val{E}; cse = false) where {E} return E ? code : RuntimeGeneratedFunctions.RuntimeGeneratedFunction(@__MODULE__, @__MODULE__, code) end +# `ifelse` compiles to a conditional whose branches are lazy, and `cse` would hoist the calls of both in front of it, +# so a guarded `sqrt` or registered function can throw where it would not have been reached. +function has_ifelse(ex) + ex = Symbolics.unwrap(ex) + SU.iscall(ex) || return false + SU.operation(ex) === ifelse && return true + return any(has_ifelse, SU.arguments(ex)) +end + # The numeric temporaries `var"##cse#k" = 2` that are assigned once, substituted into their uses and dropped, and # `NaNMath.pow(x, 2)` with an integer literal exponent back as `Base.literal_pow(^, x, Val(2))`. function inline_literals(code) @@ -157,7 +166,7 @@ function compile_coeffs(kind, ex, s, test; expression = Val(false)) end isequal(Symbolics.expand(ex - linear), 0) || return nothing any(e -> depends(e, [s.U; s.G; s.Ud; H; w]), exs) && return nothing - cse = kind === :source + cse = kind === :source && !has_ifelse(ex) cell || return compile_tuple(exs, (s.X, s.T, s.N, s.P); zero = StructuralZero(), expression, cse) dim2 = length(s.X)^2 fields = Tuple(b for b in eachindex(s.U) if depends(ex, H[((b - 1) * dim2 + 1):min(b * dim2, length(H))])) @@ -176,7 +185,7 @@ function kernel(eq, kind, piece, integrand, wf::WeakForm; coeffs = true, express ) ) tangent = kind === :nonlinear ? compile_tangent(integrand, s, slots; expression) : nothing - f = c === nothing ? compile(integrand, slots; expression, cse = kind === :source) : nothing + f = c === nothing ? compile(integrand, slots; expression, cse = kind === :source && !has_ifelse(integrand)) : nothing return KernelSpec(eq, kind, piece, f, tangent, c) end diff --git a/test/Kernels/kernels.jl b/test/Kernels/kernels.jl index 29dfd5f2..867cc00e 100644 --- a/test/Kernels/kernels.jl +++ b/test/Kernels/kernels.jl @@ -303,3 +303,21 @@ end @test isapprox(kernel.f(args...), symbolic_value(term.integrand, wf, args); rtol = 1.0e-12) end end + +guarded_root(z) = sqrt(z) +@register_symbolic guarded_root(z) + +@testset "a guarded source keeps its conditional branches lazy" begin + guarded = ifelse(x > 0, guarded_root(x), 0.0) + 2 * ifelse(x > 0, guarded_root(x), 0.0) * y + an = analyse([Dt(U) ~ Dx(k * Dx(U)) + Dy(k * Dy(U)) + guarded], BC[]; depvars = [U], t, sivs = [x, y], params = [k, α, β, h]) + X = Vec(-1.0, 0.3) + for kernel in emit_kernels(weak_form(an)), kind in (:source,) + kernel.kind === kind || continue + @test all(c -> c isa StructuralZero || iszero(c), kernel.coeffs(X, 0.0, Vec(1.0, 0.0), [2.0, 3.0, 0.5, 1.5])) + end + for kernel in emit_kernels(weak_form(an); coeffs = false) + kernel.kind === :source || continue + args = random_args(an) + @test kernel.f(args[1:5]..., X, args[7:9]...) == 0.0 + end +end From ad3f0b232b685c7c32d2caf48e1e6b78b6631c12 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 09:10:50 +0000 Subject: [PATCH 4/5] Rewrite only NaNMath.pow into literal_pow The rewrite matched any function named pow; it now matches the NaNMath.pow function itself, so a registered user function that is called pow keeps its meaning. Agent-Harness: Claude Code 2.1.318 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/kernels.jl | 4 +++- test/Kernels/kernels.jl | 12 ++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/kernels.jl b/src/kernels.jl index 8a7610fc..25bca517 100644 --- a/src/kernels.jl +++ b/src/kernels.jl @@ -25,6 +25,8 @@ function has_ifelse(ex) return any(has_ifelse, SU.arguments(ex)) end +is_nanmath_pow(f) = f === Symbolics.NaNMath.pow || f == GlobalRef(Symbolics.NaNMath, :pow) + # The numeric temporaries `var"##cse#k" = 2` that are assigned once, substituted into their uses and dropped, and # `NaNMath.pow(x, 2)` with an integer literal exponent back as `Base.literal_pow(^, x, Val(2))`. function inline_literals(code) @@ -45,7 +47,7 @@ substitute_literals(x, literals) = x isa Symbol ? get(literals, x, x) : x function substitute_literals(ex::Expr, literals) isliteral(arg) = arg isa Expr && arg.head === :(=) && haskey(literals, arg.args[1]) args = Any[substitute_literals(arg, literals) for arg in ex.args if !isliteral(arg)] - if ex.head === :call && length(args) == 3 && args[1] isa Function && nameof(args[1]) === :pow && args[3] isa Integer + if ex.head === :call && length(args) == 3 && is_nanmath_pow(args[1]) && args[3] isa Integer return Expr(:call, Base.literal_pow, ^, args[2], Expr(:call, Val, args[3])) end return Expr(ex.head, args...) diff --git a/test/Kernels/kernels.jl b/test/Kernels/kernels.jl index 867cc00e..8750c06e 100644 --- a/test/Kernels/kernels.jl +++ b/test/Kernels/kernels.jl @@ -321,3 +321,15 @@ guarded_root(z) = sqrt(z) @test kernel.f(args[1:5]..., X, args[7:9]...) == 0.0 end end + +module Custom + pow(x, y) = x + y +end +@register_symbolic Custom.pow(x, y) + +@testset "only NaNMath.pow is rewritten into literal_pow" begin + @variables ξ + ex = Custom.pow(ξ, 2) + ξ^2 * Custom.pow(ξ, 3) + f = build(ex, (ξ,), Val(false); cse = true) + @test f(3.0) == Custom.pow(3.0, 2) + 3.0^2 * Custom.pow(3.0, 3) +end From 90f930aae7cfc653dd136c90f81e4cd3dec7f7b4 Mon Sep 17 00:00:00 2001 From: t Date: Thu, 5 Nov 2026 09:44:51 +0000 Subject: [PATCH 5/5] Emit x^n for the restored literal powers Base.literal_pow and NaNMath.pow are not public, which the QA group's explicit-imports check rejects. A call x^2 on a literal integer lowers to literal_pow by itself, and NaNMath.pow is recognised by its name and parent module. Agent-Harness: Claude Code 2.1.318 Agent-Model: claude-sonnet-5-5 Agent-Session: 43e03fde-3384-4386-bae9-03e81f19ba7c Agent-Review: unreviewed Co-authored-by: Claude Code --- src/kernels.jl | 9 ++++++--- test/Kernels/kernels.jl | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/kernels.jl b/src/kernels.jl index 25bca517..ac996aa5 100644 --- a/src/kernels.jl +++ b/src/kernels.jl @@ -25,10 +25,13 @@ function has_ifelse(ex) return any(has_ifelse, SU.arguments(ex)) end -is_nanmath_pow(f) = f === Symbolics.NaNMath.pow || f == GlobalRef(Symbolics.NaNMath, :pow) +function is_nanmath_pow(f) + f isa GlobalRef && return f.name === :pow && nameof(f.mod) === :NaNMath + return f isa Function && nameof(f) === :pow && nameof(parentmodule(f)) === :NaNMath +end # The numeric temporaries `var"##cse#k" = 2` that are assigned once, substituted into their uses and dropped, and -# `NaNMath.pow(x, 2)` with an integer literal exponent back as `Base.literal_pow(^, x, Val(2))`. +# `NaNMath.pow(x, 2)` with an integer literal exponent back as `x^2`, which lowers to `literal_pow`. function inline_literals(code) literals = Dict{Symbol, Union{Number, Missing}}() collect_literals!(literals, code) @@ -48,7 +51,7 @@ function substitute_literals(ex::Expr, literals) isliteral(arg) = arg isa Expr && arg.head === :(=) && haskey(literals, arg.args[1]) args = Any[substitute_literals(arg, literals) for arg in ex.args if !isliteral(arg)] if ex.head === :call && length(args) == 3 && is_nanmath_pow(args[1]) && args[3] isa Integer - return Expr(:call, Base.literal_pow, ^, args[2], Expr(:call, Val, args[3])) + return Expr(:call, :^, args[2], args[3]) end return Expr(ex.head, args...) end diff --git a/test/Kernels/kernels.jl b/test/Kernels/kernels.jl index 8750c06e..bc3afd53 100644 --- a/test/Kernels/kernels.jl +++ b/test/Kernels/kernels.jl @@ -265,7 +265,7 @@ count_calls(ex, name) = ex isa Expr ? (callee_name(ex) === name) + sum(a -> coun for cse in (false, true) code = build(squares, (ξ, η), Val(true); cse) @test isempty(hoisted_exponents(code)) - @test count_calls(code, :literal_pow) > 0 + @test count_calls(code, :literal_pow) + count_calls(code, :^) > 0 end end