// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
// SPDX-FileCopyrightText: Copyright Contributors to the Kokkos project

/// \file Kokkos_Serial.hpp
/// \brief Declaration and definition of Kokkos::Serial device.

#ifndef KOKKOS_IMPL_PUBLIC_INCLUDE
#include <Kokkos_Macros.hpp>
static_assert(false,
              "Including non-public Kokkos header files is not allowed.");
#endif
#ifndef KOKKOS_SERIAL_HPP
#define KOKKOS_SERIAL_HPP

#include <Kokkos_Macros.hpp>
#if defined(KOKKOS_ENABLE_SERIAL)

#include <cstddef>
#include <iosfwd>
#include <iterator>
#include <mutex>
#include <thread>
#include <Kokkos_Core_fwd.hpp>
#include <Kokkos_Layout.hpp>
#include <Kokkos_HostSpace.hpp>
#include <Kokkos_ScratchSpace.hpp>
#include <Kokkos_MemoryTraits.hpp>
#include <impl/Kokkos_HostThreadTeam.hpp>
#include <impl/Kokkos_FunctorAnalysis.hpp>
#include <impl/Kokkos_Tools.hpp>
#include <impl/Kokkos_HostSharedPtr.hpp>
#include <impl/Kokkos_InitializationSettings.hpp>

namespace Kokkos {

namespace Impl {
class SerialInternal {
 public:
  SerialInternal();
  ~SerialInternal();

  SerialInternal(SerialInternal const&)            = delete;
  SerialInternal& operator=(SerialInternal const&) = delete;

  std::mutex m_instance_mutex;

  static HostSharedPtr<SerialInternal> default_instance;
  static std::vector<SerialInternal*> all_instances;
  static std::mutex all_instances_mutex;

  void fence(const std::string& name);

  // Resize thread team data scratch memory
  void resize_thread_team_data(size_t pool_reduce_bytes,
                               size_t team_reduce_bytes,
                               size_t team_shared_bytes,
                               size_t thread_local_bytes);

  HostThreadTeamData m_thread_team_data;
};
}  // namespace Impl

struct NewInstance {
  explicit NewInstance() = default;
};

/// \class Serial
/// \brief Kokkos device for non-parallel execution
///
/// A "device" represents a parallel execution model.  It tells Kokkos
/// how to parallelize the execution of kernels in a parallel_for or
/// parallel_reduce.  For example, the Threads device uses
/// C++11 threads on a CPU, the OpenMP device uses the OpenMP language
/// extensions, and the Cuda device uses NVIDIA's CUDA programming
/// model.  The Serial device executes "parallel" kernels
/// sequentially.  This is useful if you really do not want to use
/// threads, or if you want to explore different combinations of MPI
/// and shared-memory parallel programming models.
class Serial {
 public:
  //! \name Type declarations that all Kokkos devices must provide.
  //@{

  //! Tag this class as an execution space:
  using execution_space = Serial;
  //! This device's preferred memory space.
  using memory_space = Kokkos::HostSpace;
  //! The index_type alias best suited for this device.
  using index_type = memory_space::index_type;
  //! The size_type alias best suited for this device.
  using size_type = memory_space::size_type;
  //! This execution space preferred device_type
  using device_type = Kokkos::Device<execution_space, memory_space>;

  //! This device's preferred array layout.
  using array_layout = LayoutRight;

  /// \brief  Scratch memory space
  using scratch_memory_space = ScratchMemorySpace<Kokkos::Serial>;

  //@}

  KOKKOS_DEFAULTED_FUNCTION Serial(const Serial&) = default;
  KOKKOS_FUNCTION Serial(Serial&& other) noexcept
      : Serial(static_cast<const Serial&>(other)) {}
  KOKKOS_DEFAULTED_FUNCTION Serial& operator=(const Serial&) = default;
  KOKKOS_FUNCTION Serial& operator=(Serial&& other) noexcept {
    return *this = static_cast<const Serial&>(other);
  }
  ~Serial();
  Serial();

  explicit Serial(NewInstance);

  /// \brief Wait until all dispatched functors complete.
  ///
  /// The parallel_for or parallel_reduce dispatch of a functor may
  /// return asynchronously, before the functor completes.  This
  /// method does not return until all dispatched functors on this
  /// device have completed.
  static void impl_static_fence(const std::string& name) {
#ifdef KOKKOS_ENABLE_ATOMICS_BYPASS
    auto fence = []() {};
#else
    auto fence = []() {
      std::lock_guard<std::mutex> lock_all_instances(
          Impl::SerialInternal::all_instances_mutex);
      for (auto* instance_ptr : Impl::SerialInternal::all_instances) {
        std::lock_guard<std::mutex> lock_instance(
            instance_ptr->m_instance_mutex);
      }
    };
#endif
    if (Kokkos::Tools::profileLibraryLoaded()) {
      Kokkos::Tools::Experimental::Impl::profile_fence_event<Kokkos::Serial>(
          name,
          Kokkos::Tools::Experimental::SpecialSynchronizationCases::
              GlobalDeviceSynchronization,
          fence);  // TODO: correct device ID
    } else {
      fence();
    }
#ifndef KOKKOS_ENABLE_ATOMICS_BYPASS
    Kokkos::memory_fence();
#endif
  }

  void fence(const std::string& name =
                 "Kokkos::Serial::fence: Unnamed Instance Fence") const {
    this->impl_internal_space_instance()->fence(name);
  }

  /** \brief  Return the maximum amount of concurrency.  */
  int concurrency() const { return 1; }

  //! Print configuration information to the given output stream.
  void print_configuration(std::ostream& os, bool verbose = false) const;

  static void impl_initialize(InitializationSettings const&);

  //! Free any resources being consumed by the device.
  static void impl_finalize();

  //--------------------------------------------------------------------------

  inline static int impl_thread_pool_size(int = 0) { return 1; }
  KOKKOS_INLINE_FUNCTION static int impl_thread_pool_rank() { return 0; }

  //--------------------------------------------------------------------------

  KOKKOS_INLINE_FUNCTION static unsigned impl_hardware_thread_id() {
    return impl_thread_pool_rank();
  }
  inline static unsigned impl_max_hardware_threads() {
    return impl_thread_pool_size(0);
  }

  uint32_t impl_instance_id() const noexcept { return 1; }

  static const char* name();

  Impl::SerialInternal* impl_internal_space_instance() const {
    return m_space_instance.get();
  }

 private:
  Kokkos::Impl::HostSharedPtr<Impl::SerialInternal> m_space_instance;
  friend bool operator==(Serial const& lhs, Serial const& rhs) {
    return lhs.impl_internal_space_instance() ==
           rhs.impl_internal_space_instance();
  }
  friend bool operator!=(Serial const& lhs, Serial const& rhs) {
    return !(lhs == rhs);
  }
  //--------------------------------------------------------------------------
};

namespace Tools {
namespace Experimental {
template <>
struct DeviceTypeTraits<Serial> {
  static constexpr DeviceType id = DeviceType::Serial;
  static int device_id(const Serial&) { return 0; }
};
}  // namespace Experimental
}  // namespace Tools
}  // namespace Kokkos

/*--------------------------------------------------------------------------*/
/*--------------------------------------------------------------------------*/

namespace Kokkos {
namespace Impl {

template <>
struct MemorySpaceAccess<Kokkos::Serial::memory_space,
                         Kokkos::Serial::scratch_memory_space> {
  enum : bool { assignable = false };
  enum : bool { accessible = true };
};

}  // namespace Impl
}  // namespace Kokkos

namespace Kokkos::Experimental::Impl {
// Create new instance of Serial execution space for each partition, ignoring
// weights
template <class T>
std::vector<Serial> impl_partition_space(const Serial&,
                                         const std::vector<T>& weights) {
  std::vector<Serial> instances;
  instances.reserve(weights.size());
  std::generate_n(std::back_inserter(instances), weights.size(),
                  []() { return Serial(NewInstance{}); });

  return instances;
}
}  // namespace Kokkos::Experimental::Impl

#include <Serial/Kokkos_Serial_Parallel_Range.hpp>
#include <Serial/Kokkos_Serial_Parallel_MDRange.hpp>
#include <Serial/Kokkos_Serial_Parallel_Team.hpp>
#include <Serial/Kokkos_Serial_UniqueToken.hpp>

#endif  // defined( KOKKOS_ENABLE_SERIAL )
#endif  /* #define KOKKOS_SERIAL_HPP */
