ctzsi2.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. //===-- ctzsi2.c - Implement __ctzsi2 -------------------------------------===//
  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 __ctzsi2 for the compiler_rt library.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "int_lib.h"
  13. // Returns: the number of trailing 0-bits
  14. // Precondition: a != 0
  15. COMPILER_RT_ABI int __ctzsi2(si_int a) {
  16. su_int x = (su_int)a;
  17. si_int t = ((x & 0x0000FFFF) == 0)
  18. << 4; // if (x has no small bits) t = 16 else 0
  19. x >>= t; // x = [0 - 0xFFFF] + higher garbage bits
  20. su_int r = t; // r = [0, 16]
  21. // return r + ctz(x)
  22. t = ((x & 0x00FF) == 0) << 3;
  23. x >>= t; // x = [0 - 0xFF] + higher garbage bits
  24. r += t; // r = [0, 8, 16, 24]
  25. // return r + ctz(x)
  26. t = ((x & 0x0F) == 0) << 2;
  27. x >>= t; // x = [0 - 0xF] + higher garbage bits
  28. r += t; // r = [0, 4, 8, 12, 16, 20, 24, 28]
  29. // return r + ctz(x)
  30. t = ((x & 0x3) == 0) << 1;
  31. x >>= t;
  32. x &= 3; // x = [0 - 3]
  33. r += t; // r = [0 - 30] and is even
  34. // return r + ctz(x)
  35. // The branch-less return statement below is equivalent
  36. // to the following switch statement:
  37. // switch (x)
  38. // {
  39. // case 0:
  40. // return r + 2;
  41. // case 2:
  42. // return r + 1;
  43. // case 1:
  44. // case 3:
  45. // return r;
  46. // }
  47. return r + ((2 - (x >> 1)) & -((x & 1) == 0));
  48. }