Studying compilers course, I am left wondering why use registers at all.
It is often the case that the caller or callee must save the register value and then restore it.
In a way they always end up using the stack anyway. Is creating additional complexity by using registers really worth it?
Excuse my ignorance.
Update: Please, I know that registers are faster than RAM and other types of cache. My main concern is that one has to “save” the value that is in the register and the “restore” it to the register afterwards. In both cases we are accessing some kind of cache. Would it not be better to use cache in the first place?
In the speed/latency hierarchy, registers are fastest (usually zero cycle latency), L1 cache is next (typically 1 or more cycles of latency), and then it goes downhill rapidly after that. So in general register accesses are “free” whereas there is always some cost involved in memory accesses, even when that access is cached.
Saving and restoring registers typically only happens (a) at the begin/end of a function call or context switch, or (b) when the compiler runs out of registers for temporary variables and needs to “spill” one or more registers back to memory. In general, well-optimised code will keep the majority of frequently accessed (“hot”) variables in registers, at least within the innermost loop(s) of a function.