	.file	"switch_context_x86_64.s"
	.text
	.global	__cs_switch_context
	.type	__cs_switch_context, @function

.align 16
__cs_switch_context:
        # Parameter List (in order)
        # rdi = pointer to continuation (should hold value of target stack will be filled with this continuation)

        # Return
        # rax = continuation that returned control back to the caller (null if fallthrough)

        ############### Save State ###############
        # Make space on the stack
        leaq -0x38(%rsp), %rsp
        # Store calee saved general registers.
        movq %r12, 0x00(%rsp)
        movq %r13, 0x08(%rsp)
        movq %r14, 0x10(%rsp)
        movq %r15, 0x18(%rsp)
        movq %rbx, 0x20(%rsp)
        movq %rbp, 0x28(%rsp)
        # Store MMX control- and status-word
        stmxcsr 0x30(%rsp)
        # Store x87 control-word
        fnstcw 0x34(%rsp)
        ############### Save State ###############

        # Perform change to new stack.
        # Keep old stack as result from this function
        movq %rsp, %rax
        # switch to new stack pointer
        movq %rdi, %rsp

        ############ Restore State  ############
        # restore calee saved general registers
        movq 0x00(%rsp), %r12
        movq 0x08(%rsp), %r13
        movq 0x10(%rsp), %r14
        movq 0x18(%rsp), %r15
        movq 0x20(%rsp), %rbx
        movq 0x28(%rsp), %rbp
        # restore MMX control- and status-word
        ldmxcsr 0x30(%rsp)
        # restore x87 control-word
        fldcw 0x34(%rsp)
        # Free space on the stack
        leaq 0x38(%rsp), %rsp
        ############ Restore State  ############

        # Return the context we came from as a continuation.
        # rax has already the correct value
        ret
