Locking register usage for a certain section of code
<p>Let's consider a situation where we are writing in C code. When the compiler encounters a function call, my understanding is that it does the following:</p>

<ul>
<li>Push <em>all</em> registers onto the stack</li>
<li>Jump to new function, do stuff in there</li>
<li>Pop old context off the stack back into the registers.</li>
</ul>

<p>Now, some processors have 1 working register, some 32, some more than that. I'm mostly concerned with the larger number of registers. If my processor has 32 registers, the compiler will need to emit 32 push and pop instructions, just as base overhead for a function call. It would be nice if I could trade some compilation flexibility[1] in the function for less push and pop instructions. That is to say, I would like a way that I could tell the compiler "For function <code>foo()</code>, only use 4 registers. This would imply that the compiler would only need to push/pop 4 registers before jumping to <code>foo()</code>.</p>

<p>I realize this is pretty silly to worry about on a modern PC, but I am thinking more for a low speed embedded system where you might be servicing an interrupt very quickly, or calling a simple function over and over. I also realize this could very quickly become an architecture dependant feature. Processors that use a "Source Source -> Dest" instruction set (Like ARM), as opposed to an accumulator (Like Freescale/NXP HC08) might have some lower limit on the number of registers we allow functions to use.</p>

<p>I do know the compiler uses tricks like inlining small functions to increase speed, and I realize I could inform most compilers to not generate the push/pop code and just hand code it myself in assembly, but my question focuses on instructing the compiler to do this from "C-Land".</p>

<p>My question is, are there compilers that allow this? Is this even necessary with optimizing compilers (do they already do this)? </p>

<p>[1] Compilation flexibility: By reducing the number of registers available to the compiler to use in a function body, you are restricting it's flexibility, and it might need to utilize the stack more since it can't just use another register.</p>