What is the state of the registers after a function call?

时间:2015-06-30 13:42:20

标签: c++ c assembly

I have limited knowledge in assembly, but I can at least read through it and match with the corresponding C or C++ code. I can see that the function arguments are passed either by pushing them to the stack or by registers, and the function body uses some registers to do its operations. But it also seems to use the same registers that were used in the caller. Does this mean that the caller has no guarantee that the state of the registers will be the same after a function call? What if the whole body of the function is unknown during compilation? How does the compiler deal with this?

2 个答案:

答案 0 :(得分:3)

编译器生成的汇编代码遵循一些calling convention。调用约定通常指定

  • 如何将参数传递给函数
  • 返回值如何从被调用函数传递给调用者
  • 哪些寄存器应保存在函数调用中并且可以修改

如果调用的所有函数都遵循相同的调用约定,则不会出现使用相同寄存器的问题。

答案 1 :(得分:2)

As the comments allude to, the fact is that there is no standard for this. It is left entirely to the implementors of the particular c++ compiler you are using.

A more explicit question, like this: "when compiling on version N of compiler A with compiler options B, calling a function signature of C, for target CPU D, using ABI E, what are the guarantees vis-a-vis register preservation?"

In which case an expert (or the manual) on that particular toolset can answer.

As you can probably infer, for any kind of industrial-strength project, it's the wrong question to ask, because as your compiler evolves the answer will change, and you don't want that fact to impact the reliability of your program.

It's a good question, because it's nice to know what the compiler is doing under the hood - it aids learning.

But on the whole, the golden rule is to express clear uncomplicated logic to the compiler in your program, and allow the compiler to handle the details of turning that logic into optimised machine code, at which modern compilers are excellent.