The convention when a function is going to use a saved register is to save the contents of that register to the stack in case the caller (if there's one? the main function doesn't have one) had been using this register too and to restore the contents right before returning. Is this convention always obeyed? In the case of a really simple program, with just a main function and no other function calls, would the compiler prefer to optimize and disobey the convention, which means no saving before using the saved register? Of course, a convention is not a rule so i was wondering in which situations can these not be followed?


Calling conventions may be called "convention", but they are rules. The reason they are called "convention" is because each compiler uses a different one, once a convention was chosen - it acts as rules.

Regarding the particular case of "main", it's being called by the operating system, so convention must be obyed.

  • $\begingroup$ But depending on the case, sometimes it's preferable to use temporary registers rather than saved registers or the other way around. So why would the compiler choose a single convention: "caller saved" or "callee saved"? As for the "main" example, essentially if a saved register is used there, the main function should save the contents of the saved registers to the stack in case the OS had something useful placed there? $\endgroup$ – Some1 Apr 8 at 5:18
  • $\begingroup$ Every convention has caller/callee saved registers. Conventions differ by the way of passing parameters to functions, the identity of caller/callee registers, where the return value is stored and more (I recommend reading about the variations on wikipedia). The convention a compiler uses is sets by what the compiler programmers believe to be the best match most often. Yes, the main needs to do so. $\endgroup$ – Adi Peled Apr 8 at 6:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.