clzsi2.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. //===-- clzsi2.c - Implement __clzsi2 -------------------------------------===//
  2. //
  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
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements __clzsi2 for the compiler_rt library.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "int_lib.h"
  13. // Returns: the number of leading 0-bits
  14. // Precondition: a != 0
  15. COMPILER_RT_ABI int __clzsi2(si_int a) {
  16. su_int x = (su_int)a;
  17. si_int t = ((x & 0xFFFF0000) == 0) << 4; // if (x is small) t = 16 else 0
  18. x >>= 16 - t; // x = [0 - 0xFFFF]
  19. su_int r = t; // r = [0, 16]
  20. // return r + clz(x)
  21. t = ((x & 0xFF00) == 0) << 3;
  22. x >>= 8 - t; // x = [0 - 0xFF]
  23. r += t; // r = [0, 8, 16, 24]
  24. // return r + clz(x)
  25. t = ((x & 0xF0) == 0) << 2;
  26. x >>= 4 - t; // x = [0 - 0xF]
  27. r += t; // r = [0, 4, 8, 12, 16, 20, 24, 28]
  28. // return r + clz(x)
  29. t = ((x & 0xC) == 0) << 1;
  30. x >>= 2 - t; // x = [0 - 3]
  31. r += t; // r = [0 - 30] and is even
  32. // return r + clz(x)
  33. // switch (x)
  34. // {
  35. // case 0:
  36. // return r + 2;
  37. // case 1:
  38. // return r + 1;
  39. // case 2:
  40. // case 3:
  41. // return r;
  42. // }
  43. return r + ((2 - x) & -((x & 2) == 0));
  44. }