Edward O'Callaghan | 2bf6272 | 2009-08-05 04:02:56 +0000 | [diff] [blame] | 1 | /* ===-- clzdi2.c - Implement __clzdi2 -------------------------------------=== |
| 2 | * |
Chandler Carruth | 7a739a0 | 2019-01-19 10:56:40 +0000 | [diff] [blame] | 3 | * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. |
| 4 | * See https://llvm.org/LICENSE.txt for license information. |
| 5 | * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception |
Edward O'Callaghan | 2bf6272 | 2009-08-05 04:02:56 +0000 | [diff] [blame] | 6 | * |
| 7 | * ===----------------------------------------------------------------------=== |
| 8 | * |
| 9 | * This file implements __clzdi2 for the compiler_rt library. |
| 10 | * |
| 11 | * ===----------------------------------------------------------------------=== |
| 12 | */ |
Daniel Dunbar | b3a6901 | 2009-06-26 16:47:03 +0000 | [diff] [blame] | 13 | |
| 14 | #include "int_lib.h" |
| 15 | |
Edward O'Callaghan | 2bf6272 | 2009-08-05 04:02:56 +0000 | [diff] [blame] | 16 | /* Returns: the number of leading 0-bits */ |
Daniel Dunbar | b3a6901 | 2009-06-26 16:47:03 +0000 | [diff] [blame] | 17 | |
Kristina Brooks | d57a71d | 2018-09-18 18:56:52 +0000 | [diff] [blame] | 18 | #if !defined(__clang__) && \ |
| 19 | ((defined(__sparc__) && defined(__arch64__)) || \ |
| 20 | defined(__mips64) || \ |
| 21 | (defined(__riscv) && __SIZEOF_POINTER__ >= 8)) |
| 22 | /* On 64-bit architectures with neither a native clz instruction nor a native |
| 23 | * ctz instruction, gcc resolves __builtin_clz to __clzdi2 rather than |
| 24 | * __clzsi2, leading to infinite recursion. */ |
Jonas Devlieghere | 816aba3 | 2018-02-08 11:14:11 +0000 | [diff] [blame] | 25 | #define __builtin_clz(a) __clzsi2(a) |
| 26 | extern si_int __clzsi2(si_int); |
| 27 | #endif |
| 28 | |
Edward O'Callaghan | 2bf6272 | 2009-08-05 04:02:56 +0000 | [diff] [blame] | 29 | /* Precondition: a != 0 */ |
Daniel Dunbar | b3a6901 | 2009-06-26 16:47:03 +0000 | [diff] [blame] | 30 | |
Anton Korobeynikov | 1c5f89b | 2011-04-19 17:52:09 +0000 | [diff] [blame] | 31 | COMPILER_RT_ABI si_int |
Daniel Dunbar | b3a6901 | 2009-06-26 16:47:03 +0000 | [diff] [blame] | 32 | __clzdi2(di_int a) |
| 33 | { |
| 34 | dwords x; |
| 35 | x.all = a; |
Edward O'Callaghan | 8bf1e09 | 2009-08-09 18:41:02 +0000 | [diff] [blame] | 36 | const si_int f = -(x.s.high == 0); |
| 37 | return __builtin_clz((x.s.high & ~f) | (x.s.low & f)) + |
Daniel Dunbar | b3a6901 | 2009-06-26 16:47:03 +0000 | [diff] [blame] | 38 | (f & ((si_int)(sizeof(si_int) * CHAR_BIT))); |
| 39 | } |