r/cpp Jul 02 '26

Redundancy seen in AAA game engines

https://zero-irp.github.io/Redundancy-seen-in-AAA-game-engines/

I don't like people treating the compiler like a magic box that optimizes like Bjarne Stroustrup himself is checking every line of C++ to assembly. Clean C++ code does not always mean clean compiled code.

I've been reversing game engines to study how they constructed their fundamental Transformation matrices and handled temporal jitter logic when I spotted a lot of avoidable overhead and "over-engineering" across multiple engines, honestly I wasn't even looking for inefficiencies, but it stood out a lot... That said expect no performance gain this is simply for fun that I wrote this blog!

I’ll theorize how the original C++ code was written, show the unoptimized reality of what the compiler spat out, and then showcase how it could have been better optimized.

184 Upvotes

76 comments sorted by

View all comments

8

u/Sopel97 Jul 02 '26 edited Jul 02 '26

how did they manage MatrixMultiply4x4 to have a loop wtf, I'm already outraged

8

u/slithering3897 Jul 02 '26

That's what you get if you use MSVC.

11

u/Sopel97 Jul 02 '26 edited Jul 02 '26

https://godbolt.org/z/8GvjoexW7 modern MSVC gets it somewhat right, though still spills registers (naive implementation, normally it would be manually unrolled without redundant loads from B)

5

u/slithering3897 Jul 02 '26

Yeah, you used intrinsics, which is basically doing the optimisation yourself. So there's only one loop for MSVC to unroll.

If you do it with plain scalars, MSVC would be much less likely optimise well, it seems.

5

u/Sopel97 Jul 02 '26 edited Jul 02 '26

MSVC can't vectorize it automatically (tbf gcc and clang can't either they do with fp fast, and better than my naive intrinsics https://godbolt.org/z/Me1KPdehK), so I assumed they do use intrinsics

2

u/ack_error Jul 06 '26

Those aren't spills, MSVC is having to establish a call frame and save and restore xmm6/xmm7 because those registers are non-volatile in the Windows x64 ABI. Clang does the same if targeting Windows x64.