runtime icon indicating copy to clipboard operation
runtime copied to clipboard

Alternative versions of methods for Vectors and Matrices

Open EmptyKeys opened this issue 12 years ago • 59 comments

Would be helpful to have alternative versions of methods with "out" parameter as result. Example: this

public static Matrix CreateFromQuaternion(Quaternion quaternion) { ... }

and that

public static void CreateFromQuaternion(ref Quaternion quaternion, out Matrix result) { ... }

What do you think guys? Do you want to add that?

EmptyKeys avatar Nov 25 '14 13:11 EmptyKeys

Can you give an example where you think this is helpful? does it simplify a specific scenario?

akoeplinger avatar Nov 25 '14 13:11 akoeplinger

ref and out in this case are better for memory. Important if you are actually making some render engine etc. :)

EmptyKeys avatar Nov 25 '14 13:11 EmptyKeys

Also, in ref-out scenario, you can reuse already created and allocated matrix. In case you need a lot of quaternion-matrix conversions, It can help you save some miliseconds. Hovever, with such code as in Matrix.CreateFromQuaternion(...), I don't think memory allocation must be the point of concern in application heavily using this method.

MPolovyi avatar Nov 25 '14 16:11 MPolovyi

ref/out avoid copying the value, for large value types such as Matrix that can be quite an improvement. Not only that you don't pay the cost of the copying but the generated code is much smaller because of that.

That said, using ref/out is kind of ugly and in some cases it simply doesn't work (you can't use ref/out with properties for example). Having to extend the API with such overloads just because the JIT compiler can't handle this case properly is a rather unfortunate situation.

mikedn avatar Nov 27 '14 12:11 mikedn

The example of CreateFromQuaternion shouldn't allocate any memory as its entirely stack based?

You would pay a 64 byte copy cost if you were storing the return value rather than just using it.

Reusing a local declared vary by ref shouldn't gain much and I think things get weird when you start passing addresses of local stack variables around if not careful. (If you are storing the return its probably not hotpath as you are already caching)

benaadams avatar Feb 17 '15 19:02 benaadams

Is the proposal here to do this for all methods on these types or a subset? It would be helpful to understand what exactly is in scope and have some sample code fragments that exhibit bad codegen today so we can compare the present codegen to the codegen we would get if we made changes.

ellismg avatar Mar 24 '15 22:03 ellismg

pretty much what @mikedn said. If you want better performance ref/out methods are good candidate and should be implemented, where it makes sense ie big struct types like Matrix/Quaternion etc.

EmptyKeys avatar Mar 24 '15 23:03 EmptyKeys

For cases like public static Matrix CreateFromQuaternion(Quaternion quaternion), I can imagine how passing the argument by ref could provide different codegen that is better in some cases (since you don't have the copy the data into the callee).

However, is the rewrite of the return value to an out parameter really that helpful? I would have sort of assumed there would be some return value optimization going on.

For me, it would be helpful to see some representative samples where the codegen is unacceptable so we can understand the best way to address the issue. Is it via additional APIs? Is there something we can do to make the methods more likely to be inlined and hence data need not be copied, are there other optimizations the JIT could be doing?

I worry about creating a bunch of new APIs to address problems we don't have good samples for. How can we know if we are doing better?

ellismg avatar Mar 25 '15 00:03 ellismg

this thread and posts are like Déjà vu, it's almost surreal.

https://social.msdn.microsoft.com/Forums/en-US/e715c16b-6b02-454a-b836-d402093bd36f/end-users-shouldnt-have-to-rewrite-xna-math-functions-in-order-to-improve-performance?forum=xnaframework

Almost 9 years old thread. XNA managed to get that API correct on the end. Something changed since then in compiler for this issue?

If you can change something somewhere, which will not copy bunch of floats there and back, then we don't need this change in API. What ever solution you find is good. And if you want some good samples just try your examples for this library with ref/out (or any solution you pick) implementation and compare difference.

EmptyKeys avatar Mar 25 '15 00:03 EmptyKeys

I don't know what the jitter does but a byval Quaternion can be a single cpu register and if so, a byref would give you worse performance as it could be referenced in multiple places on multiple threads so always needs to memory backed rather than register backed.

benaadams avatar Mar 25 '15 01:03 benaadams

However, is the rewrite of the return value to an out parameter really that helpful? I would have sort of assumed there would be some return value optimization going on.

Good question, struct returns are already converted to out returns by the JIT compiler since there's no other (sane) way of returning a struct that doesn't fit in a register. And it turns out that the JIT compiler does an optimization and eliminates one of 2 copies that are normally required. For code like field = CreateFromQuaternion(...) the JIT compiler generates code that looks identical to CreateFromQuaternion(..., out field) instead of passing a pointer to a temporary and then copying the temporary to the actual destination.

The remaining issue is a copy that's performed inside CreateFromQuaternion. The matrix is normally computed in a local variable and at the end of the method the local variable is copied to the out parameter. It's difficult to avoid this copy, attempting to compute the matrix straight into the out parameter would result in a corrupted return value if an exception gets thrown during computation.

I can imagine how passing the argument by ref could provide different codegen that is better in some cases (since you don't have the copy the data into the callee).

This is something where the JIT compiler might be able to do better. I think it could always pass structs by ref and have the callee perform the copy when necessary to preserve the value semantics. In some cases the copy would simply transform into loading the necessary struct fields in registers.

I don't know what the jitter does but a byval Quaternion can be a single cpu register

Yes, it could be but it appears that currently it isn't. It's also debatable if passing a quaternion in a register actually helps. If the callee needs to call Quaternion methods that cannot be inlined then the compiler will have to spill the register to memory anyway so it can take the address for this.

XNA managed to get that API correct on the end.

That's debatable. Using ref and out for performance reasons is a workaround rather than "correct". Not to say that this shouldn't be done but don't be surprised if people will discuss this over and over again.

The way I see it: I do care about performance but I also want the code to be readable. What can be done so that one can use operator overloads (think matrix multiplication for example) and also get good performance?

mikedn avatar Mar 25 '15 08:03 mikedn

well compiler could check if struct is big (ie Matrix) and do that optimization (ref) for us, but not sure if there is any issue with this kind of behavior.

Yeah, you are right. Ref/out solution was always workaround (even for XNA), but I thought that changing API (in one small library) would be easier than changing how compiler works (for everyone).

EmptyKeys avatar Mar 25 '15 09:03 EmptyKeys

Could the (relatively new) AggressiveInlining flag be used to force the jitter to inline those methods? If SIMD code is emitted, it shouldn't bloat the generated code too much, should it?

axel-habermaier avatar Mar 25 '15 14:03 axel-habermaier

If SIMD code is emitted, it shouldn't bloat the generated code too much, should it?

I don't see SIMD code being emitted for Matrix4x4 and Quaternion.

Could the (relatively new) AggressiveInlining flag be used to force the jitter to inline those methods?

Inlining doesn't remove unnecessary copies by itself, the JIT compiler must do that as a separate optimization. As far as I can tell it doesn't do that currently:

[MethodImpl(MethodImplOptions.AggressiveInlining)]
static Matrix4x4 Create() {
    return new Matrix4x4(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16);
}
static int Main() {
    Matrix4x4 m = Create();
    return (int)m.GetDeterminant();
}

generates the following code:

...
movss    xmm2, dword ptr [@RWD48]
movss    dword ptr [rsp+80H], xmm2
lea      rcx, bword ptr [rsp+90H]
...
movss    xmm1, dword ptr [@RWD60]
call     System.Numerics.Matrix4x4:.ctor(float,float,float,float,float,float,float,float,float,float,float,float,float,float,float,float):this
movdqu   xmm0, qword ptr [rsp+90H] ; redundant copying of a Matrix4x4
movdqu   qword ptr [rsp+D0H], xmm0
movdqu   xmm0, qword ptr [rsp+A0H]
movdqu   qword ptr [rsp+E0H], xmm0
movdqu   xmm0, qword ptr [rsp+B0H]
movdqu   qword ptr [rsp+F0H], xmm0
movdqu   xmm0, qword ptr [rsp+C0H]
movdqu   qword ptr [rsp+100H], xmm0
lea      rcx, bword ptr [rsp+D0H]
call     System.Numerics.Matrix4x4:GetDeterminant():float:this

mikedn avatar Mar 25 '15 15:03 mikedn

@mikedn related? http://blogs.msdn.com/b/clrcodegeneration/archive/2014/10/31/ryujit-ctp5-getting-closer-to-shipping-and-with-better-simd-support.aspx

benaadams avatar Mar 25 '15 15:03 benaadams

@mikedn: I haven't checked, but if matrix multiplication, for instance, isn't using SIMD, then what is?

axel-habermaier avatar Mar 25 '15 15:03 axel-habermaier

Lots of comments in here so sorry if I don't address a couple.

@caroleidt and I had discussed this briefly a while back. A couple of things are problematic and prevent us from just "adding the methods":

  1. It would greatly complicate the JIT's recognition of these intrinsics, as there could be two forms for any given operation.
  2. This can be a strange pattern for new users, and might confuse some people's expectations of what ref and out are doing here. That said, this is a very common pattern for most math libraries, so I'm not too concerned that many people would be confused for long.
  3. Like someone said above, though, this would be a workaround of sorts, and we would prefer to keep the exposed surface area of the library conceptually pure and tackle the root problem itself.

Expanding on (3): We would love to tackle this problem generically, be it through better JIT support, better inlining, better heuristics, etc. Alternatively, given that the JIT already recognizes some of these operations as intrinsics (or can in the future), it may be a more pragmatic approach to simply improve the handling of these specific operations in the JIT. If this is a general problem that needs addressing though, it would be great if we could provide a general solution rather than special-case the methods in this library.

In summary, we don't plan to add explicit ref/out variations of methods at this time, but we do want to improve the performance of these methods, either through a generic solution, or through better JIT recognition on these specific types.

mellinoe avatar Mar 25 '15 19:03 mellinoe

Hi there, this issue is preventing us (for a project like SharpDX or Xenko) for switching to System.Numerics. For example, when using Matrix multiplications you really can't afford to have 64 bytes* 3 copied back and forth on the stack, so we are always doing all of our calculations by ref/out. The API should reflect that big structs passed by value is not efficient (but just convenient). Ideally we should not count on the JIT to do things like this (and basically today we can't as we have to deal with many different JIT/codegen implems out there from mobile Android, iOS, Windows...etc.)

Also, afair for SharpDX, one reason by ref methods are not ideal is because of VB limitation, as VB don't accept methods with same names that only differs by ref/out types, which is very annoying (and one reason why I didn't bother so far to support much VB)

xoofx avatar May 07 '15 09:05 xoofx

/cc @CarolEidt

joshfree avatar Oct 05 '15 20:10 joshfree

While this is especially true for Matrix, out methods for operators on vectors would also be nice to have.

operator+(..) public static void Add( ref Vector v1, ref Vector v2, out result ) ... (or vice versa out result at start shrug) { result = v1.x + v2.x; .... } public void Add( ref Vector v, out Vector result ) ... (or vice versa out result at start shrug) { result = x + v.x; .... }

Add, Subtract, Multiply, Divide ( divide implemented as * 1/val). Matrix should have Multiply (or Apply method) with similar out vectors.

Scaling can also take advantage of a full vector multiply... Vector.Multiply( ref Vector a, ref Vector b, out Matrix result ); and Matrix.Multiply( ref Matrix a, ref Matrix b, out Matrix result );

.... it's just a habit to put the result at the end...


Other useful functions

Vector { /* double or whatever appropriate base type is */ public void AddScale( Vector v, double s, out Vector result ) { result.x = x + v.x * s; result.y = y + v.y * s; result.z = z + v.z * s; result.w = w + v.w * s; } }

d3x0r avatar Oct 15 '15 11:10 d3x0r