Saxon-EE sometimes optimizes a call to a user-defined function by inlining the function body (that is, replacing the function call with the body of the called function.) It is possible for this to be done before the called function is type-checked. When this happens (which will typically be when the call is a forwards reference), any code that is needed to convert the result of the called function to its declared type (for example, atomization) is not added, with the result that the function call can fail at run-time with a ClassCastException (for example, casting a node to an atomic value).
A patch is being created for Saxon 9.2. The effect of the patch is to type-check all functions before optimizing any of them, rather than doing type-checking followed by optimization as a single operation, one function at a time. The patch affects modules XSLStylesheet and XSLTFunction (both in open-source Saxon-HE code). I have not investigated whether the same problem can occur in Saxon 9.1; the particular stylesheet demonstrating the problem works correctly in 9.1, but this could be by chance.