ctzsi2.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* ===-- ctzsi2.c - Implement __ctzsi2 -------------------------------------===
  2. *
  3. * The LLVM Compiler Infrastructure
  4. *
  5. * This file is dual licensed under the MIT and the University of Illinois Open
  6. * Source Licenses. See LICENSE.TXT for details.
  7. *
  8. * ===----------------------------------------------------------------------===
  9. *
  10. * This file implements __ctzsi2 for the compiler_rt library.
  11. *
  12. * ===----------------------------------------------------------------------===
  13. */
  14. #include "int_lib.h"
  15. /* Returns: the number of trailing 0-bits */
  16. /* Precondition: a != 0 */
  17. COMPILER_RT_ABI si_int
  18. __ctzsi2(si_int a)
  19. {
  20. su_int x = (su_int)a;
  21. si_int t = ((x & 0x0000FFFF) == 0) << 4; /* if (x has no small bits) t = 16 else 0 */
  22. x >>= t; /* x = [0 - 0xFFFF] + higher garbage bits */
  23. su_int r = t; /* r = [0, 16] */
  24. /* return r + ctz(x) */
  25. t = ((x & 0x00FF) == 0) << 3;
  26. x >>= t; /* x = [0 - 0xFF] + higher garbage bits */
  27. r += t; /* r = [0, 8, 16, 24] */
  28. /* return r + ctz(x) */
  29. t = ((x & 0x0F) == 0) << 2;
  30. x >>= t; /* x = [0 - 0xF] + higher garbage bits */
  31. r += t; /* r = [0, 4, 8, 12, 16, 20, 24, 28] */
  32. /* return r + ctz(x) */
  33. t = ((x & 0x3) == 0) << 1;
  34. x >>= t;
  35. x &= 3; /* x = [0 - 3] */
  36. r += t; /* r = [0 - 30] and is even */
  37. /* return r + ctz(x) */
  38. /* The branch-less return statement below is equivalent
  39. * to the following switch statement:
  40. * switch (x)
  41. * {
  42. * case 0:
  43. * return r + 2;
  44. * case 2:
  45. * return r + 1;
  46. * case 1:
  47. * case 3:
  48. * return r;
  49. * }
  50. */
  51. return r + ((2 - (x >> 1)) & -((x & 1) == 0));
  52. }