// Copyright 2020 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

#include "textflag.h"
#include "abi_riscv64.h"

// Set the x_crosscall2_ptr C function pointer variable point to crosscall2.
// It's such a pointer chain: _crosscall2_ptr -> x_crosscall2_ptr -> crosscall2
// Use a local trampoline, to avoid taking the address of a dynamically exported
// function.
TEXT ·set_crosscall2(SB),NOSPLIT,$0-0
	MOV	_crosscall2_ptr(SB), X7
	MOV	$crosscall2_trampoline<>(SB), X8
	MOV	X8, (X7)
	RET

TEXT crosscall2_trampoline<>(SB),NOSPLIT,$0-0
	JMP	crosscall2(SB)

// Called by C code generated by cmd/cgo.
// func crosscall2(fn, a unsafe.Pointer, n int32, ctxt uintptr)
// Saves C callee-saved registers and calls cgocallback with three arguments.
// fn is the PC of a func(a unsafe.Pointer) function.
TEXT crosscall2(SB),NOSPLIT|NOFRAME,$0
	/*
	 * Push arguments for fn (X10, X11, X13), along with all callee-save
	 * registers. Note that at procedure entry the first argument is at
	 * 8(X2).
	 */
	ADD	$(-8*29), X2
	MOV	X10, (8*1)(X2) // fn unsafe.Pointer
	MOV	X11, (8*2)(X2) // a unsafe.Pointer
	MOV	X13, (8*3)(X2) // ctxt uintptr

	SAVE_GPR((8*4))
	MOV	X1, (8*16)(X2)
	SAVE_FPR((8*17))

	// Initialize Go ABI environment
	CALL	runtime·load_g(SB)
	CALL	runtime·cgocallback(SB)

	RESTORE_GPR((8*4))
	MOV	(8*16)(X2), X1
	RESTORE_FPR((8*17))

	ADD	$(8*29), X2

	RET
