Constant propagation of function of type

Suppose I have a function

function f(args...)
     X = g(typeof(args))
     # do stuff with X and args..
end

The function g is fairly complicated (performs a recursive walk of a tuple type-type), but ultimately it is pure and returns another type X. Assuming that the type of args is inferred, can I count on the compiler to constant prop the computation of X away so that it does not appear in the compiled code? Or will this only work for very simple g?

Usually I would expect this to work, but it depends on exactly what your g is. I’d suggest you try it. If it doesn’t work, provide more details and people can try to help.

2 Likes

As a test of whether the compiler is doing what you expect or not, you might consider writing a @generated function and comparing the output/performance/lowered code of the two functions. The way that I think about @generated functions, which is probably not the most informed or correct, is this template:

@generated function f(x::X, y::Y, [...]) where{X, Y, [...]}
  # functions and operations with only type information:
  Z = some_types_only_function(X, Y, [other_types...])
  W = other_types_only_function([...])
  quote
    # "normal" information available here, as well as $Z, $W, etc.
    [...] #stuff 
  end
end

Maybe this would be a useful tool to explore?

1 Like

Assuming that the type of args is inferred, can I count on the compiler to constant prop the computation of X away so that it does not appear in the compiled code?

Generally yes for things that are specialized on (like types). Use Cthulhu to see what the compiler is actually doing with your code.

1 Like