Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the compiler generating a push/pop instruction pair?

Tags:

c

x86

assembly

sse

I compiled the code below with the VC++ 2010 compiler:

__declspec(dllexport)
unsigned int __cdecl __mm_getcsr(void) { return _mm_getcsr(); }

and the generated code was:

push ECX
    stmxcsr [ESP]
    mov EAX, [ESP]
pop ECX
retn

Why is there a push ECX/pop ECX instruction pair?

like image 933
user541686 Avatar asked Jan 14 '12 15:01

user541686


People also ask

What is the use of push and pop instructions?

Instructions that store and retrieve an item on a stack. Push enters an item on the stack, and pop retrieves an item, moving the rest of the items in the stack up one level.

What is push and pop in computer?

In computer science, a stack is an abstract data type that serves as a collection of elements, with two main operations: Push, which adds an element to the collection, and. Pop, which removes the most recently added element that was not yet removed.

What does the pop instruction do?

The pop instruction removes the 4-byte data element from the top of the hardware-supported stack into the specified operand (i.e. register or memory location). It first moves the 4 bytes located at memory location [SP] into the specified register or memory location, and then increments SP by 4.

What is push and pop Instruction in 8085?

PUSH and POP instruction in 8085 microprocessor: In the 8085 microprocessor, when the PUSH instruction is executed the stack pointer register is decremented by two and when the POP instruction is executed the stack pointer is incremented by two respectively.


2 Answers

The compiler is making room on the stack to store the MXCSR. It could have equally well done this:

sub esp,4
stmxcsr [ESP]
mov EAX, [ESP]
add esp,4
retn

But "push ecx" is probably shorter or faster.

like image 52
Robᵩ Avatar answered Nov 15 '22 06:11

Robᵩ


The push here is used to allocate 4 bytes of temporary space. [ESP] would normally point to the pushed return address, which we cannot overwrite.

ECX will be overwritten here, however, ECX is a probably a volatile register in the ABI you're targeting, so functions don't have to preserve ECX.

The reason a push/pop is used here is a space (and possibly speed) optimization.

like image 22
Maister Avatar answered Nov 15 '22 07:11

Maister