Can Julia exploit constant propagation?

Say we have a function like,

function f_with_const_arg( arr, C ) 
  for iter=1:length(arr)
  #[...Something happens...and C is used but not modified...]
  end
end

Can Julia codegenerate functions with instructions with a constant argument ? I’m assuming this is not the case since Julia stores functions based on the types of arguments.

If the value is a compile-time constant, then the compiler will use this to generate more efficient code. However, here C is likely just some value, and yes the compiler makes a function per type, not per constant value.

One way to get around this is to use a value type, Val{C}, in which case the value of C is compile-time information which the compiler can use. However, you don’t want to overuse this because you can end up with dynamic dispatch if you’re not careful.

That said, if the arguments are all constant immutables (with no pointers/arrays) and the function’s output only depends on the inputs, I believe Base.@pure will make use of the constant?

Don’t use a constant in type parameter unless absolutely necessary. There are of course cases where compiling a function for a specific constant value is useful but that’s usually not the case. From the generic description in your comment julia (or llvm) should be able to figure out that the same value is used across loops and hoist some operations out of the loop. You need to be more specific on the type of operation you are doing in order to determine if generating functions based on constant values is useful for your case.

3 Likes