popcount.hpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. //---------------------------------------------------------------------------//
  2. // Copyright (c) 2013-2014 Kyle Lutz <kyle.r.lutz@gmail.com>
  3. //
  4. // Distributed under the Boost Software License, Version 1.0
  5. // See accompanying file LICENSE_1_0.txt or copy at
  6. // http://www.boost.org/LICENSE_1_0.txt
  7. //
  8. // See http://boostorg.github.com/compute for more information.
  9. //---------------------------------------------------------------------------//
  10. #ifndef BOOST_COMPUTE_FUNCTIONAL_POPCOUNT_HPP
  11. #define BOOST_COMPUTE_FUNCTIONAL_POPCOUNT_HPP
  12. #include <boost/compute/function.hpp>
  13. #include <boost/compute/type_traits/type_name.hpp>
  14. namespace boost {
  15. namespace compute {
  16. /// Returns the number of non-zero bits in \p x.
  17. ///
  18. /// \see_opencl_ref{popcount}
  19. template<class T>
  20. class popcount : public function<T(T)>
  21. {
  22. public:
  23. popcount()
  24. : function<T(T)>("boost_popcount")
  25. {
  26. std::stringstream s;
  27. s << "inline " << type_name<T>() << " boost_popcount"
  28. << "(const " << type_name<T>() << " x)\n"
  29. << "{\n"
  30. // use built-in popcount if opencl 1.2 is supported
  31. << "#if __OPENCL_VERSION__ >= 120\n"
  32. << " return popcount(x);\n"
  33. // fallback to generic popcount() implementation
  34. << "#else\n"
  35. << " " << type_name<T>() << " count = 0;\n"
  36. << " for(" << type_name<T>() << " i = 0; i < sizeof(i) * CHAR_BIT; i++){\n"
  37. << " if(x & (" << type_name<T>() << ") 1 << i){\n"
  38. << " count++;\n"
  39. << " }\n"
  40. << " }\n"
  41. << " return count;\n"
  42. << "#endif\n"
  43. << "}\n";
  44. this->set_source(s.str());
  45. }
  46. };
  47. } // end compute namespace
  48. } // end boost namespace
  49. #endif // BOOST_COMPUTE_FUNCTIONAL_POPCOUNT_HPP