/****************************************************************************/
/*	Copyright (c) 2009, Bendor Research Pty. Ltd. All rights reserved.		*/
/*	This software is released under the GNU General Public License, version	*/
/*	3, with the exemptions that 1) the header files installed by this 	 	*/
/*	package can be included in closed-source code and 2) the libraries		*/
/*	built by this package can be statically linked into a closed-source 	*/
/*	binary. See the file LICENSE for the details.							*/
/*	This software is provided "AS IS", without any warranty or guarantee.	*/
/*	By using this software you acknowledge that neither Bendor Research nor	*/
/*	any of its personnel or affiliates can be held liable for any damages,	*/
/*	including, but not limited to, loss of business, loss of money, loss of */
/*	life, loss of reputation, arising out of this software being faulty or	*/
/*	not performing as advertised, even if Bendor Research was aware of such	*/
/*	faults in the software. You use this software at your own risk, any and */
/*	all liabilities that arise out of your using this software are strictly	*/
/*	yours.																	*/
/****************************************************************************/

#include <chips/ARM/func.h>

/*
*	32-bit base-2 logarithm
*
*	The function uses the classic restoring algorithm. It works as
*	follows:
*
*	A = 1;
*	R = 0;
*
*	for ( i = 1 ; i < 32 ; i++ ) {
*
*		T = A + A >> i;
*
*		if ( T <= X ) {
*
*			A = T;
*			R = R + table[ i ];
*		}
*	}
*
*	return R;
*
*	where table[x] is log2( 1 + 1 / ( 1 << x ) )
*
*	In order to be as precise as possible, A, X, R and T are 64-bit, with the
*	radix point after the second most significant bit. Note that the function
*	itself uses a 32-bit interface, only the internal stuff is 64 bit.
*
*	The argument to the function is the fractional part of X, and it is
*	assumed that the integer part of X is 1. That is, the number of which
*	the logarithm calculated is 1.r0. Since the result falls into (1,0] the
*	returned value is simply a fraction.
*/

	afunc	log32
	stmdb	sp!,{r4-r10}
	mov		r12,#1
	mov		r1,#0
	mov		r2,#0
	mov		r3,#1
	ldr		r5,table
0:
	ldmia	r5!,{r6-r10}
	movs	r4,r1,lsr r3
	adcs	r4,r4,r1
	addccs	r4,r4,r12,ror r3
	bcs		1f
	cmp		r0,r4
	movcs	r1,r4
	addcs	r2,r2,r6
1:
	add		r3,r3,#1
	movs	r4,r1,lsr r3
	adcs	r4,r4,r1
	addccs	r4,r4,r12,ror r3
	bcs		1f
	cmp		r0,r4
	movcs	r1,r4
	addcs	r2,r2,r7
1:
	add		r3,r3,#1
	movs	r4,r1,lsr r3
	adcs	r4,r4,r1
	addccs	r4,r4,r12,ror r3
	bcs		1f
	cmp		r0,r4
	movcs	r1,r4
	addcs	r2,r2,r8
1:
	add		r3,r3,#1
	movs	r4,r1,lsr r3
	adcs	r4,r4,r1
	addccs	r4,r4,r12,ror r3
	bcs		1f
	cmp		r0,r4
	movcs	r1,r4
	addcs	r2,r2,r9
1:
	add		r3,r3,#1
2:
	movs	r4,r1,lsr r3
	adcs	r4,r4,r1
	addccs	r4,r4,r12,ror r3
	bcs		1f
	cmp		r0,r4
	movcs	r1,r4
	addcs	r2,r2,r10
1:
	add		r3,r3,#1
	cmp		r3,#31
	bcc		0b
	ldreq	r10,[r5]
	beq		2b
	mov		r0,r2
	ldmia	sp!,{r4-r10}
	bx		lr
table:
	.word	_blm_logtable

