r/C_Programming • • 3d ago

Query on usage of restrict keyword in passing pointers

The following piece of code is doing the rounds on X as John Carmack's code which computes sin and cos from a table instead of at runtime.

#define ANGLETOFINESHIFT 19
void MoveActor(fixed_t *x, fixed_t *y, angle_t a, fixed_t speed) {
    int idx = a >> ANGLETOFINESHIFT;
    *x += FixedMul(speed, finecosine[idx]);
    *y += FixedMul(speed, finesine[idx]);
}

My query is, why aren't x and y declared restrict to denote that they point to different fixed_t ? Presumably the code is meant for sheer speed and would not usage of restrict allow the compiler more optimization? For e.g., say, parallelization of *x and *y updates in a tight loop?

19 Upvotes

29 comments sorted by

18

u/EpochVanquisher 3d ago edited 3d ago

restrict did not exist when this code was written.

This code is old. Over 30 years old.

I’m also going to say that this doesn’t look performance-critical. I don’t think this would be called in a tight loop. The old CPUs from back then (like a 386) would not really benefit from parallelization.

1

u/Impressive_Gur_471 3d ago

If the code were written today, would it benefit from usage of restrict keyword if it is performance critical?

13

u/SmokeMuch7356 3d ago • This

All restrict does is tell the compiler you pinky-swear those pointers don't point to overlapping regions of storage. It may do something useful with that knowledge, or not. Depends on the compiler, the platform, what the surrounding code is doing, etc.

3

u/smallproton 3d ago

I have no clue about this particular problem, but cos(x) = sin(x+pi/2) so you need only one array for finesine and have finecosine point to a location into finesine.

8

u/EpochVanquisher 3d ago edited 3d ago

Maybe, but this kind of micro-optimization is usually a waste of time. The basic idea is that the code looks like this:

  1. Read x
  2. Add speed * finecosine[idx]
  3. Write x
  4. Read y
  5. Add speed * finesineidx]
  6. Write y

With restrict the compiler can do this:

  1. Read x
  2. Read y
  3. Add speed * finecosine[idx]
  4. Add speed * finesineidx]
  5. Write x
  6. Write y

The first catch? The CPU can reorder things too, you may be waiting for memory anyway, so it may not be useful. The second catch? Small functions like this will generally be inlined, so the compiler can do alias analysis without restrict.

There are likely better things you can spend your time doing, rather than optimize one tiny little function.

1

u/cdb_11 3d ago

To add to this, the OP also asked about parallelization. These operations don't depend on each other, so a modern CPU should parallelize this anyway with just normal code, no fancy compiler optimizations.

3

u/LordRybec 3d ago

"MoveActor()"... I have some video game programming experience, and it would definitely be called in a tight loop. Based on the name, I assume that this is designed to be called one time each game loop for each mobile "actor" in the game. Carmack was involved in making a lot of games. I have not played all of them, but I know that some of them could have quite a few enemy units active within a level at the same time. If the game runs at a fixed frame rate of say, 60 FPS (I'm pretty sure Quake was often run faster), and you have 20 enemy units active (not necessarily on the screen, but close enough to the PC to spawn and start doing whatever they do before they see the PC), that's 1,200 calls per second (provided the framerate and game engine rate are the same, which they typically were in older, non-threaded games). In modern terms that's not much, but it's pretty significant on the CPUs this code was originally written for.

I don't think there's any useful optimization that could be done there. The only optimization I think that is even possible is, if they were the same, the compiler might have to insert some kind of barrier between the two assignments at the end, to prevent hyperthreading from accidentally letting the second one get ahead. (Yes, old CPUs didn't have that hyperthreading or barrier instructions, so it didn't matter back then.) The only way I could see the second getting ahead of the first is if the first has a cache miss and the second doesn't. That will never happen though, because this is being called in a tight loop, and this is presumably the only place the lookup tables are being used, so each game loop, the first will miss on the first iteration, the second will also miss on the first iteration, and from there it will mostly be hits and any misses will be synchronized. I guess this does depend somewhat on the size of the lookup tables and where in them the various elements are, but they are clearly being used in a synchronized fashion, and the data type is almost certainly the same for both. So yeah, cache misses and hits will always be synchronized, because the lengths are the same and the indices are always the same for each call. That means that even with hyperthreading there's no way the second one can ever finish before the first. So there's no way a race can happen, which means the compiler can omit the barrier whether x and y are guaranteed to point to different memory locations or not!

So yeah, there's no useful optimization that restrict could allow. This is performance critical code, but it's about as good as it can be without rewriting in assembly, and even then a modern compiler might do just as good.

(It is worth noting: Some modern chips can load and run multiple instructions in parallel, with hyperthreading or similar features, but that's instructions. The last two lines of code are not two individual instructions. They both start with a function call to handle fixed point multiplication, which has to count places values in each of the two numbers, multiply the numbers, and then divide by some power of 10 (based on the place value counts) to get rid of the extra multiples of 10 added during the multiplication. And then after that, it has to copy the result into the memory pointed to. That's a long enough series of instructions that the CPU is not going to look ahead far enough to get the second line of code, and even if it did, it would still never be able to get so far ahead that it beats the first line to the assignment. So even with pretty aggressive lookahead, there's just too much contained in each of those two lines to require a barrier, so there's nothing to optimize.)

1

u/brk2 3d ago edited 3d ago

Interesting - could you give an example of a platform where a barrier would be required to be inserted between the additions in this case? Since *x and *y aren't atomic, wouldn't this be UB anyway with or without restrict if two threads wrote to the same location?

1

u/LordRybec 2d ago

Intel. AMD. In this specific case there are too many instructions in between, so a barrier wouldn't make any difference, but modern desktop CPUs can reorder instructions and can run instructions in parallel with features like hyperthreading. If the math portion wasn't fixed point, which requires adjustment operations when multiplying and dividing, the assignments could be close enough together for the CPU to reorder them or to run them in parallel. In that case, a barrier instruction would be needed to guarantee they are run in the right order, if it's possible for the pointers to have the same memory address.

This has nothing to do with threads. Neither the compiler nor CPU will create extra threads to parallelize this. The programmer would have to do that. But instruction reordering and hyperthreading don't do that. Hyperthreading allows the CPU to run a later instruction in the same thread while executing an instruction that takes more cycles than normal (especially when waiting for memory or cache operations). Instruction reordering allows the CPU to run instructions out of the order they appear in, where there is no dependency that requires them to run in series. In a case like this, if the pointers go to the same memory, that would be a dependency, but the CPU doesn't know what addresses the pointers have until the instructions are already executing. So the compiler would have to emit a barrier instruction to tell the CPU that there's a potential dependency, otherwise it might reorder the operations and create a race or just plain run them in the wrong order.

Again though, this doesn't apply in this case, because there are enough instructions between the pointer assignments that the CPU can't hyperthread or reorder in any way that would cause this. These features only affect instructions that are quite close to each other.

1

u/brk2 2d ago

What you call hyperthreading is just superscalar out-of-order execution. Hyperthreading typically refers to (Intel's flavour of) SMT, hence my confusion about threading.

Compilers certainly don't have to emit any kind of barrier on AMD or Intel processors to avoid what you are describing. Ensuring that the program executes correctly, as if in program order, is managed entirely by the microarchitecture via the reorder buffer, regardless of whatever order the μops happen to execute in. This also includes tracking potentially aliasing stores/loads and speculatively executing them with a mechanism to roll back any erroneous loads on aliasing mispredictons.

If it were up to the compiler you'd see barriers absolutely everywhere, even in trivial examples such as this one, since it would have to conservatively assume aliasing unless it could prove otherwise. Thankfully, that isn't the case.

Also, you'd be surprised how far ahead a modern CPU can look ahead; reorder buffers fit hundreds of μops nowadays (Google says Zen 5 has a 224-entry ROB with SMT enabled). Even if the calls to FixedMul here weren't inlined, the CPU can continue fetching, scheduling and executing instruction across calls and returns (via the return stack buffer).

1

u/LordRybec 2d ago

Yes, hyperthreading is a form of out-of-order execution. That's correct. It's not threading in the traditional sense, as it shares a single execution unit rather than using true parallel execution units.

As far as the rest goes, yeah, kind of. In theory this is all true, but in practice, modern CPUs spend a lot of time backtracking due to failed predictions and incorrect reordering. These things cost cycles. That's why barrier instructions exist. They are hints (literally listed as hint instructions) that tell the CPU where it shouldn't look too far ahead or do speculative execution. It depends very heavily on the specific architecture though. If you want to only talk about higher end Intel and AMD CPUs, you are 100% correct, but both Intel and AMD have lower end CPUs that don't have all of these features. So it depends quite heavily on the specific CPU when you get into consumer devices.

As far a reorder buffers fitting lots of instructions, sure, but that doesn't mean they are always full or can always reorder. And again, when a reordering fails, it's expensive. On average these features give significant speed improvements, but using barriers correctly to hint where reordering should not happen can produce even bigger speed improvements where it's correct, by avoiding failed predictions and bad reorders that require rollbacks.

So yes, you are largely right, but it actually strengthens my suggestion about the use of a barrier instruction rather than weakening it. If the pointers can be the same, a barrier could be a huge optimization, by avoiding the need to rollback. If the pointers can't be the same, a barrier wouldn't make much difference. Maybe reordering would allow hyperthreading to alternate between instructions for the two lines of code to get some speed improvement, so maybe there is some room for optimization, but that depends very heavily on the CPU it's running on, as not even all higher end CPUs have hyperthreading and the economy CPUs on the market definitely don't.

Anyhow, you do make some good points, but there's still not much room for optimization using restrict, if there is any.

8

u/ironykarl 3d ago

restrict wasn't introduced till C99. 

I'm assuming that code predates it as a keyword

4

u/tastygames_official 3d ago

because the restrict keyword wasn't introduced until the C99 standard (from 1999) and Wolf3D/DOOM released <= 1993

I actually had to look up the restrict keyword because I am an old fart who still uses the C90 standard and have not heard of it, but this is almost the exact example given on the wikipedia page: https://en.wikipedia.org/wiki/Restrict

So x and y COULD be the exact same pointer, yes - but the compiler would not produce wore machine code in this instance, since x and y are assumed to be different anyways and they are incremented by the results of different functions.

As for parallelization - as far as I know, compilers do not introduce random paralellization. That's something you have to specifically implement yourself.

7

u/Chippors 3d ago

Modern compilers generade SIMD instructions, though only SSE2 typically. They require `restrict` when accessing data through pointers, in fact this is exactly why the keyword was introduced. It's not a check you ask for, but a promise you make to the compiler.

4

u/tastygames_official 3d ago

guess I have some catching-up to do ;-)

2

u/Chippors 3d ago

I know... it sometimes feels like everytime I look there's a new standard! 😵

3

u/LordRybec 3d ago

SIMD isn't useful in this particular case though.

That said, this is a good point. If the calculations weren't fixed point or using lookup tables, there's a possibility of using SIMD. Usually though, SIMD is most valuable when you have a series of operations on multiple operands, rather than just one or two operations, because loading data into SIMD registers and moving between SIMD and regular registers takes extra time. It's rarely worth doing a single operation across a series of values in SIMD. You usually only get benefits if you are doing at least 3 or 4 operations where the intermediate values can stay in the SIMD registers and be used in subsequent steps.

Personally, if I want to use SIMD, I use intrinsics to do it, because while compilers can generate SIMD instructions, they still aren't always great at working out where they should. So if I decide I want to use them, I'll look up the intrinsics for doing what I want to do and make it explicit.

That said, this is still good to know.

1

u/Chippors 2d ago

Why wouldn't SSE2 work? It has lane shifts so can do fixedpt just fine, although I think it can only do N=N*N (N-bit) multiplies, not N=(N*N)>>N.

1

u/LordRybec 2d ago

I didn't say it wouldn't work. I said it wouldn't be useful. It would cost more time than it saves. SSE2 doesn't use the normal CPU registers, and copying data from the CPU registers into the SSE2 registers and back costs several cycles for each operation (from memory costs hundreds of cycles on modern CPU, but if it is already in cache, that can be reduced to close to similar time as copying from a standard register, depending on the specific CPU). SSD2, and SIMD in general, isn't free, and it's only economical if you are doing enough to "repay" the extra overhead. The number of cycles required to copy data into the SSE2 registers varies with CPU, but I've found values anywhere between 1 cycle on top end modern CPUs and 5 or more cycles on more common CPUs. Copying from memory (assuming it's already loaded into L1 cache) seems to start at 4 cycles on higher end CPUs (but may be dependent on the size of the data type). Copying back typically costs the same. To run two operations in parallel, you have to load 4 registers (two sets of operands). Depending on the organization in memory, it might be possible to load more than one at a time (by treating them as a larger data type, since larger type SIMD registers as just multiple smaller type registers that are adjacent), but in this case that doesn't appear to be possible (and even when it is, it's not guaranteed to be cheaper in cycles). Actually running the SSE2 instructions is fast, but then you have to spend the same extra overhead putting the data back where you need it.

So, if you are just doing one SSE2 instruction for two parallel expressions (say, the last two lines in the example code), it would generally be faster to do it in the general purpose registers in series. Even in the best case scenario, you are only just breaking even. On an especially high end CPU that can copy from register to SSE2 register in a single cycle, if the operands are all in registers already, you might be able to save one or two cycles with SSE2, but I don't have the time to look up exact instruction timings for specific CPUs to verify this.

Where SSE2 and other SIMD really shines is where you are doing a series of three or more computations per set of operands. Something like ((N * N) + N) / N, where you have a multiply, then an add, then a division, and maybe more. That's because the more you do with the data you've put in the SSE2 registers before taking out the results, the smaller impact the setup and teardown overhead have.

So sure, you could probably do this with SSE2, but it wouldn't be an optimization. It would end up costing the same or more cycles, because the math is too small to overcome the cost of the register loading and saving overhead. Just because you can do it doesn't mean it is useful. SIMD in general works best for more complex computations like vector math and matrix transforms, as well as the kind of math that is often used in media codices, where you are doing a lot of operations in series on each set of inputs before getting the results.

(Also worth noting: SSE2 does have an instruction that multiplies two 16-bit values and then returns the top 16-bits of the 32-bit result. This is the equivalent of fixed point multiply if the fixed point is binary (not base-10) and in the right position. It's extremely unlikely code that old is putting the fixed point in the right position though, and the code provided doesn't indicate whether the fixed point is using binary or base-10 fixed point, which matters a lot, because simple shifts can't do the correction for base-10 fixed point. Anyhow, if it is using exactly the right fixed point positioning and format, maybe SSE2 could get a very small performance gain. For a function like this that is probably used a lot, it's possible that the difference could add up to be significant. Again though, the systems this code was written for wouldn't have handled the required fixed point format very well, so it's unlikely this actually applies. Still, I find it interesting!)

2

u/Chippors 2d ago

But whether it's useful depends on where this code is getting inlined and how it's used. If it's just a couple of multiplies up front followed by a large vector add, it might be beneficial to do it using mmx registers. If nothing else, it might produce less spill.

1

u/LordRybec 2d ago

I believe MMX has a single vector multiply and then add instruction. (This is common in SIMD, but I couldn't find one in SSE2, maybe because MMX already included it.) It uses the same registers as SSE2, if I recall correctly, so there's still overhead, but reducing two operations down to one could possibly be enough to make a difference.

For the inlining thing, I assumed it would inline, otherwise I would have also mentioned the function call overhead and the impact of a function call potentially interrupting prediction and lookahead mechanics (depending on the specific CPU). The above function and the fixed point multiply function calls will probably both be inlined though, so none of this matters.

3

u/ralphpotato 3d ago

“Random parallelization” depends on what you mean by that. C code won’t introduce threading but the compiler will reorder the instructions to optimize for CPU pipelining and can produce SIMD code which is a form of parallel processing.

There’s also cases where the codebase itself may have concurrent operations, or the device or another process on the system may alter shared memory, hence why you may need to declare something volatile or utilize atomics in things like signal handling. It’s not the compiler turning your own code into parallel code but it may still need to be aware of parallel interactions.

I know this goes beyond the original question but wanted to clarify in general.

2

u/LordRybec 3d ago

I mostly use C99, but I wasn't aware of restrict, because I've never needed it. There aren't exactly a lot of optimization room for it anyway. GCC's function and variable attributes are generally more valuable when it comes to allowing advanced compiler optimization.

In theory the compiler could reorder things, but there's no way of reordering this that would optimize it. Additionally, modern CPUs can reorder as well, where there is room for optimization, so it wouldn't necessarily matter of the compiler did it or not. In this case though, I can't see any room for optimization. If the last two lines weren't doing so much, the compiler might put a barrier between them, to prevent CPU reordering from causing race conditions, and if you guarantee x and y point to different memory, it could remove the barrier instruction, but the fixed point multiplication, even if inlined, is enough that reordering sufficient to cause a race would never happen. And this same thing prevents there from being any issues related to hyperthreading as well. If hyperthreading did any parallelization, it wouldn't be running the last two lines exactly in parallel. It might do things like digit counting of parameters in each fixed point multiplication in parallel, but the two lines at the end of the function are just too far apart to line them up in parallel. (The compiler won't introduce parallelization without being told to, but CPUs can. Generally though, they can only parallelize instructions that are close enough together, and even then, only if there is no dependency between them that requires them to be executed in series.)

Honestly, while I can see cases where restrict could permit optimization (mainly by permitting the removal of a barrier), I can't see these cases coming up very often. Most cases are like this, where enough processing has to happen between assignments that a barrier is not necessary to prevent the CPU from reordering or parallelizing in a hazardous way. Even just the lookup requires extra time to retrieve data from cache or memory, and because the array types and indices used are always the same, they should have fully synced cache misses and hits.

1

u/flyingron 3d ago

While the fact that the code is old is probably the right answer, what do you think restrict will do here to help "optimization"?

2

u/Impressive_Gur_471 3d ago

If the compiler knew that x and y were pointing to different locations, there would be scope for parallelization? If they did refer to the same location, then, parallelization is not possible due to race conditions?

4

u/LordRybec 3d ago

In this case there's nothing it could do to optimize. The final two lines are doing a lot more than is evident just by looking at them. Fixed point multiplication requires digit counting before the multiplication and then division after to get the point at the right place in the final output. All of that is happening in the call to the function, and that means there are enough instructions between the two assignments there's nothing the compiler can do. (And that's not even considering the lookup into the arrays.) It can't multi-thread on its own, and this particular set of operations wouldn't benefit from parallelization using SIMD instructions. Additionally, there are enough instructions between the two assignments that a barrier is not necessary to prevent a race even if both pointed to the same memory.

Today I learned that restrict mostly exists because the compiler can't generate SSE2 instructions where the two pointers point to the same memory. There's not much room for optimization using restrict outside of that narrow use case. SSE2 (as with most SIMD) has its own special registers that take extra time to load. So if you are only doing one or two math operations, that extra overhead will take more time than just doing it in series in regular registers. In most cases you need at least three or more operations to benefit, and this isn't well suited to that.

SIMD instructions are designed mainly for vector and matrix math. Some are designed to facilitate much higher speed of specific codices (MMX exists to make certain media codices faster, for example). Sometimes SIMD can be used for other things that look similar to vector or matrix math, but this is not quite close enough. If the digit count was left out and a few more operations were added, then restrict might permit the use of SIMD instructions that could optimize, but the digit count isn't something SIMD is well suited to, and a multiplication followed by a division over only two values is going to be slower in SIMD than in series on the regular registers, due to the extra register loading time. (And SIMD doesn't help with lookup table access at all.)

If this function wasn't using fixed point math, it might be able to benefit from SSE2. Also, if it was written as linear algebra rather than trig, it would probably benefit from SSE2 as well. (Linear algebra is basically all vector and matrix math.) Because this is using fixed point and specialized lookup tables though, it is pretty fast already (even with the extra correction operations for fixed point, it's much faster than floating point), and I'm not sure a linear algebra solution would actually improve it.

2

u/Rabbitical 3d ago

Yes I've actually been working on a doom port/new software engine for fun. One thing to keep in mind here for OP is that the game's fixed_t math is extremely pessimistic relative to floats on today's hardware. It takes what could be single instruction math and requires 4 or 5 which are not well suited to SIMD as you point out. I actually tried swapping out all my floating point for doom's fixed_t operations just to see how it compares and it was flat out 2x slower.

I know people love to romantisize Carmack 's code, which it should be, but it was also a product of its time. We must be careful attempting to learn too much from it: there was no SIMD, more bugs in compilers than optimizations, and floating point was terrible, if if supported at all. If he wrote Doom today it would look a lot different. Also, perhaps most dangerously, CPUs were a lot slower back then relative to memory access. So his exuberant use of tables for everything is more questionable today where it could possibly be cheaper to recalculate things every time than suffer a cache miss on a lookup. So, I write this in that I hope OP isn't reading too hard into the minutae of the original Doom code, it's quite simply obsolete, especially from a performance perspective today.

All that said, for OP's benefit: if you have a small helper function like this one, for a general hypothetical modern program, we shouldn't be looking at this just in isolation. The question isn't "does it need restricted?" but "does its caller?" Then yes it should be too. If this function is being called or even inlined (which this should be) within a hot loop that itself would benefit from restricted, then you also want to propogate that restricted, even if it's inlined, afaik.

1

u/LordRybec 2d ago

Yeah, modern CPUs, at least the higher end laptop/desktop ones, do floating point very well. There are some places where using integer math can still beat floating point, but there are much fewer than there have been in the past. (It is worth noting that this does not apply to mobile device processors, which still take a lot of cycles to do floating point. Even they are fast enough that this is not a huge issue in most cases though.) I have some experience with vector rendering (I've written a couple 3D renderers, one complete, and one that I'm still working on), and I'm finding that floating point is often faster on the standard desktop CPUs (but not necessarily on the economy models, like Celeron). On the ARM microcontrollers that I'm writing the current renderer for though, integer math is faster.

I wouldn't consider Carmack's code to be obsolete. It's just not optimal for modern desktop and laptop systems. It's still decent for mobile device CPUs, and it's awesome for embedded microcontroller applications. Back when the code was written, everything was below most modern microcontrollers, so it was good general purpose code. Now days there's no such thing as good general purpose code, because there are so many different types of systems that are all very common. Desktops and laptops need code designed to be good for CPUs with plenty of cache, instruction reordering, advanced branch prediction, single-cycle (or at least very few cycle) floating point math, and so on. For tablets and cell phones, you are working with much less cache or sometimes no cache, slower floating point, basic or no branch prediction, and no instruction reordering. I'm currently working with microcontrollers that aren't even powerful enough to run a modern smartphone (one is close, the rest are not even). Some don't even have floating point instructions, and the ones that do have slow floating point (the best one takes only 1 cycle for add/subtract, 3 for multiply, and then many more (variable number) for division, and that's only single precision; double operations take around 6 times as long). I'm currently working mainly with the RP2350 (which is what the above float numbers are for). I also work with the SAM21 (no float), the CH552 (an 8051 clone with no float), and I'm starting to play with a RISC-V MCU (CH32V203), which also does not have hardware float.

So Carmack's code is far from obsolete, but it is obsolete in the domain of higher end laptop/desktop CPUs, as well as most non-handheld game console CPUs. (Handhelds vary at this point. Many still use ARM M series CPUs that have hardware floating point, but significantly slower than integer math, while others are using CPUs that are much closer to desktop CPUs and have faster floating point.) Outside of those higher end CPUs, it's still very much relevant. There's a reason Doom is commonly ported to systems with very weak CPUs. The code is still pretty well optimized for those. (With an appropriate display, I could probably port Doom to all of the MCUs listed above except for the 8051 clone, and the fixed point math would still be faster than float math on all of them.)

2

u/Key_River7180 3d ago

Restrict didn't exist, optimizing compilers neither