Search code examples
assemblyx86operating-systemcpu-registerscontext-switch

ASM uses registers yet the CPU still has sufficient?


I have watched some tutorials on ASM programming and I am at the very beginner stage. I am interested in learning x86 ASM, having a background in C, and I did some beginner MIPS during a Computer Science course which required me to write very basic programs. I was using registers like variables, without really understanding them.

I do not understand how registers in ASM are so freely used, when I believe a CPU might only have eight general purpose registers, and even less for specific purposes.

Surely, the fact that there are numerous different programs running at the same time on a modern Windows/Linux/OSX system, the registers would quickly be occupied by other programs? Especially if numerous ASM coded programs are running, where each one wants to use the CPU's registers for different purposes...

Also, is there a limit to how many registers I can use in x86 ASM? What happens if I need more, for example in C I could create an almost infinite amount of variables.


Solution

  • Windows/Linux/OSX system, the registers would quickly be occupied by other programs?

    When an OS switches from one program to another (on the same CPU); it stores the values that the previous program had in registers (in RAM) and then loads the next program's values into registers (from RAM).

    Also, is there a limit to how many registers I can use in x86 ASM? What happens if I need more, for example in C I could create an almost infinite amount of variables.

    Yes, there's a limit (e.g. 32-bit 80x86 is limited to 7 general purpose registers, and 64-bit 80x86 is limited to 15 of them). If you create more variables then some variables just use space on the stack instead; and the compiler can move variables between the stack and registers whenever it feels like.