Compiler optimization inside MetaProgramming? (precompile Expression)

Hi, I have a function expression (as input), and it is greatly simplified by the time it becomes LLVM code.
How can I get the optimized simplified version back as an Expression?

Origin expression:

ex = :(
    function ab(bt)

        function a(x, y)
            t = 5
            v = y*y
            return x*2
        end;

        function b(t)
            return a(t+1, 0)
        end;

        b(bt)
    end;
)

eval(ex)

MacroTools.prettify(ex)

:(function ab(bt)
      function a(x, y)
          t = 5
          v = y * y
          return x * 2
      end
      function b(t)
          return a(t + 1, 0)
      end
      b(bt)
  end)

@code_llvm ab(5)

;  @ func_expr_simple.ipynb:2 within `ab`
define i64 @julia_ab_2973(i64 signext %0) #0 {
top:
;  @ func_expr_simple.ipynb:14 within `ab`
; ┌ @ func_expr_simple.ipynb:11 within `b`
; │┌ @ func_expr_simple.ipynb:7 within `a`
; ││┌ @ int.jl:88 within `*`
     %1 = shl i64 %0, 1
     %2 = add i64 %1, 2
; └└└
  ret i64 %2
}

How can I get an Expr where the unused variables (y, t, v) are gone, the functions (a, b) are inlined etc?

@code_typed ab(5) will give you a post-inlined code-info, that in theory you could build an AST from, but you can’t directly get an AST for the optimized code, because it doesn’t exist in AST form.

Is there a way to get the AST of optimized code with functions inlined, unused variables removed etc?

No, definitionally, because it’s not a syntax tree anymore at that point.

1 Like

What’s the latest stage when it is still a AST and how can I pull the structure from it?

Lowering to IR form is the first step in the compilation pipeline, so we never run any optimizations over the AST representation

1 Like