Skip to content

Core.declare_global is hoisted out of if/else at the top level #59755

@xal-0

Description

@xal-0

Found by @christiangnrd in JuliaMath/BFloat16s.jl#111.

Notice how without assigning the result of the if/else to a variable, the Core.declare_global isn't executed unless the condition is true (1.12 behaviour):

  o  | Version 1.13.0-DEV.1272 (2025-10-06)
 o o | Commit 406027e7212 (0 days old master)
julia> Meta.@lower if cond()
           global x
           1
       end
:($(Expr(:thunk, CodeInfo(
1 ─ %1 = Main.cond
│   %2 =   dynamic (%1)()
└──      goto #3 if not %2
    @ none within `unknown scope`
   ┌ @ REPL[1]:2 within `macro expansion`
2 ─│        builtin Core.declare_global(Main, :x, false)
│  │      $(Expr(:latestworld))
└──│      return 1
3 ─│      return nothing
   └
))))

If we set a variable to the result of the expression, the Core.declare_global happens unconditionally:

julia> Meta.@lower y = if cond()
           global x
           1
       end
:($(Expr(:thunk, CodeInfo(
1 ─         builtin Core.declare_global(Main, :x, false)
│         $(Expr(:latestworld))
│           builtin Core.declare_global(Main, :y, true)
│         $(Expr(:latestworld))
│   %5  = Main.cond
│   %6  =   dynamic (%5)()
└──       goto #3 if not %6
    @ none within `unknown scope`
   ┌ @ REPL[2]:3 within `macro expansion`
2 ─│       @_2 = 1
└──│       goto #4
3 ─│       @_2 = nothing
4 ┄│ %11 = @_2
│  │ %12 =   builtin Core.get_binding_type(Main, :y)
│  │       #s2 = %11
│  │ %14 = #s2
│  │ %15 =   builtin %14 isa %12
└──│       goto #6 if not %15
5 ─│       goto #7
6 ─│ %18 = #s2
└──│       #s2 = Base.convert(%12, %18)
7 ┄│ %20 = #s2
│  │         builtin Core.setglobal!(Main, :y, %20)
└──│       return %11
   └
))))

Introduced by #58279.

Metadata

Metadata

Assignees

No one assigned

    Labels

    compiler:loweringSyntax lowering (compiler front end, 2nd stage)regressionRegression in behavior compared to a previous version

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions