xref: /aosp_15_r20/external/coreboot/payloads/libpayload/libc/libgcc.c (revision b9411a12aaaa7e1e6a6fb7c5e057f44ee179a49c)
1 /*
2  *
3  * Copyright 2015 Google Inc.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * Alternatively, this software may be distributed under the terms of the
17  * GNU General Public License ("GPL") version 2 as published by the Free
18  * Software Foundation.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #include <libpayload.h>
34 
35 /*
36  * Provide platform-independent backend implementation for __builtin_clz() in
37  * <libpayload.h> in case GCC does not have an assembly version for this arch.
38  */
39 
40 int __clzsi2(u32 a);
__clzsi2(u32 a)41 int __clzsi2(u32 a)
42 {
43 	static const u8 four_bit_table[] = {
44 		[0x0] = 4, [0x1] = 3, [0x2] = 2, [0x3] = 2,
45 		[0x4] = 1, [0x5] = 1, [0x6] = 1, [0x7] = 1,
46 		[0x8] = 0, [0x9] = 0, [0xa] = 0, [0xb] = 0,
47 		[0xc] = 0, [0xd] = 0, [0xe] = 0, [0xf] = 0,
48 	};
49 	int r = 0;
50 
51 	if (!(a & (0xffff << 16))) {
52 		r += 16;
53 		a <<= 16;
54 	}
55 
56 	if (!(a & (0xff << 24))) {
57 		r += 8;
58 		a <<= 8;
59 	}
60 
61 	if (!(a & (0xf << 28))) {
62 		r += 4;
63 		a <<= 4;
64 	}
65 
66 	return r + four_bit_table[a >> 28];
67 }
68