Irrational optimized away?

I found this a little interesting. It seems that the add operation has been optimized away for irrational. How does it do that?

julia> koo(v) = v + 10
koo (generic function with 1 method)

julia> @code_llvm koo(1)

;  @ REPL[1]:1 within `koo'
define i64 @julia_koo_12177(i64) {
; ┌ @ int.jl:53 within `+'
   %1 = add i64 %0, 10
; └
  ret i64 %1

julia> @code_llvm koo(π)

;  @ REPL[1]:1 within `koo'
define double @julia_koo_12184() {
  ret double 0x402A487ED5110B46

Each Irrational has its own type so the function is specialized on each one so yes, this is correct.

1 Like

Does the magic sit inside the compiler? If I create my own type then I can’t do the same, can I?

There’s nothing special about the type in the compiler, it’s all just a consequence of its definition. Irrational has a type parameter which is the symbol of the constant, and no fields. There is a different Irrational type for each symbol, and a unique singleton instance of that type. You can define the same thing yourself.


The StaticNumbers package lets you do this for any number.

julia> using StaticNumbers

julia> @code_llvm koo(static(32))

;  @ REPL[11]:1 within `koo'
define i64 @julia_koo_12291() {
  ret i64 42

However, In most situations Julia’s built-in constant-folding is enough.