2006/08/11(金)MIPSの場合

というわけで,MIPSで平方根を求めるプログラム.fmulとfdivが,それぞれ乗算,除算に相当しています.

.globl main
.globl fmul
.globl fdiv

.globl fsqr

main:
	li $v0,5
	syscall
	add $a0,$zero,$v0	# a0 : jousuu
	jal fsqr		# $v0 = fsqr($a0)
	nop
	add $a0, $zero, $v0
	li $v0, 1
	syscall
	nop
	li $v0, 0
	syscall			# exit
	nop			

fsqr:
	addi $sp, $sp, -24
	sw $ra, 20($sp)
	sw $s0, 16($sp)
	sw $s1, 12($sp)
	sw $s2, 8($sp)
	sw $s3, 4($sp)
	sw $s4, 0($sp)

	# init
	addi $s0, $zero, 1	# x
	sll $s0, $s0, 16
	add $s1, $zero, $a0	# y
#	addi $s2, $zero, 2
	addi $s3, $zero, 20	# i
	addi $s4, $zero, 2	#
	sll $s4, $s4, 16

_fsqr:
	add $a0, $zero, $s0	# $s2 = x / 2
	add $a1, $zero, $s4
	jal fdiv
	add $s2, $zero, $v0

#	add $a0, $zero, $s0	# $v1 = x * 2
#	add $a1, $zero, $s4
	jal fmul
	add $a1, $zero, $v0

	add $a0, $zero, $s1	# $s5 = y / $v1 = y / (x * 2)
	jal fdiv

	add $s0, $s2, $v0

	addi $s3, $s3, -1
	bne $s3, $zero, _fsqr
	add $v0, $zero, $s0

	lw $s4, 0($sp)
	lw $s3, 4($sp)
	lw $s2, 8($sp)
	lw $s1, 12($sp)
	lw $s0, 16($sp)
	lw $ra, 20($sp)
	addi $sp, $sp, 20

	jr $ra

fmul:
	# init
	add $t1, $zero, $a0
	add $t2, $zero, $a1
	addi $t3, $zero, 1
	addi $t4, $zero, 1
	sll $t4, $t4, 16

	add $v0, $zero, $zero
	add $v1, $zero, $zero

	addi $t0, $zero, 16
_fmul1:
	and $t5, $t2, $t3
	beq $t5, $zero, _fmul2
	add $v0, $v0, $a0
_fmul2:
	and $t5, $t2, $t4
	beq $t5, $zero, _fmul3
	add $v1, $v1, $t1
_fmul3:
	srl $t2, $t2, 1
	srl $v0, $v0, 1
	sll $t1, $t1, 1
	addi $t0, $t0, -1
	bne $t0, $zero, _fmul1

	add $v0, $v0, $v1
	jr $ra

fdiv:
	# init
	add $v0, $zero, $zero
	add $v1, $zero, $zero
	addi $t0, $zero, 48
	addi $t1, $zero, 1
	sll $t1, $t1, 31
	beq $zero, $zero, _fdiv2

_fdiv1:
	srl $t1, $t1, 1
	sll $v0, $v0, 1
	sll $v1, $v1, 1
_fdiv2:
	and $t2, $t1, $a0
	beq $t2, $zero, _fdiv3
	addi $v1, $v1, 1
_fdiv3:
	slt $t2, $v1, $a1
	bne $t2, $zero, _fdiv4
	sub $v1, $v1, $a1
	addi $v0, $v0, 1
_fdiv4:
	addi $t0, $t0, -1
	bne $t0, $zero, _fdiv1

	jr $ra