//===----------------------------------------------------------------------===//
//
// Part of libcu++, the C++ Standard Library for your entire system,
// under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES.
//
//===----------------------------------------------------------------------===//

// MIT License
//
// Modifications Copyright (C) 2026 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#ifndef _CUDA_STD_CTIME
#define _CUDA_STD_CTIME

#include <cuda/std/detail/__config>

#if defined(_CCCL_IMPLICIT_SYSTEM_HEADER_GCC)
#  pragma GCC system_header
#elif defined(_CCCL_IMPLICIT_SYSTEM_HEADER_CLANG)
#  pragma clang system_header
#elif defined(_CCCL_IMPLICIT_SYSTEM_HEADER_MSVC)
#  pragma system_header
#endif // no system header

#include <cuda/std/__host_stdlib/time.h>

#if _CCCL_CUDA_COMPILATION()
#  include <cuda/__ptx/instructions/get_sreg.h>
#endif // _CCCL_CUDA_COMPILATION()

// NOTE(HIP/AMD): _LIBCUDACXX_HIP_TSC_CLOCKRATE /
// _LIBCUDACXX_HIP_TSC_NANOSECONDS_PER_CYCLE used by
// __cccl_time_impl_device() / __cccl_timespec_get_impl_device() are
// supplied transitively by <cuda/std/detail/__config> ->
// <libhipcxx/__amd/hip_tsc_clockrate.h> on HIP.

// NOTE(HIP/AMD): Under hipRTC, including host <time.h> drags in host <stddef.h>
// on the JIT include path, which redefines max_align_t / byte (already provided
// by cuda::std's <cstddef>) and breaks compilation. Under the new upstream model,
// __host_stdlib/time.h is only included when not freestanding, and _CCCL_FREESTANDING()
// is true for hipRTC (no host stdlib), so the problematic include is skipped automatically.
#include <cuda/std/__cccl/prologue.h>

// NOTE(HIP/AMD): clock_t is already provided in the global namespace by the HIP
// runtime headers under hipRTC, so _CCCL_HOSTJIT() (which is false for hipRTC)
// correctly skips the clock_t definition here (the `using ::clock_t` below picks it up).
#if _CCCL_FREESTANDING()
#  define TIME_UTC 1

#  if _CCCL_HOSTJIT()
using clock_t = long long int;
#  endif // _CCCL_HOSTJIT()
using time_t = long long int;

struct timespec
{
  ::time_t tv_sec;
  long tv_nsec;
};
#endif // _CCCL_FREESTANDING()

_CCCL_BEGIN_NAMESPACE_CUDA_STD

using ::clock_t;
using ::size_t;
using ::time_t;
using ::timespec;

// clock

[[nodiscard]] _CCCL_API inline clock_t clock() noexcept
{
#if _CCCL_HOSTJIT() // host-side `clock` is not supported in freestanding
  NV_IF_ELSE_TARGET(
    NV_IS_HOST,
    (::cuda::std::terminate();),
#  if _CCCL_HIP_COMPILATION()
    // NOTE(HIP/AMD): use clock64() (per-CU performance counter, raw cycles)
    // rather than wall_clock64() (TSC) so the unit semantics match NVIDIA's
    // get_sreg_clock64() — both return per-multiprocessor cycle counts.
    (return static_cast<clock_t>(clock64());))
#  else
    (return static_cast<clock_t>(::cuda::ptx::get_sreg_clock64());))
#  endif
#else // ^^^ _CCCL_HOSTJIT() ^^^ / vvv !_CCCL_HOSTJIT() vvv
  NV_IF_ELSE_TARGET(
    NV_IS_HOST,
    (return ::clock();),
#  if _CCCL_HIP_COMPILATION()
    // NOTE(HIP/AMD): use clock64() (per-CU performance counter, raw cycles)
    // rather than wall_clock64() (TSC) so the unit semantics match NVIDIA's
    // get_sreg_clock64() — both return per-multiprocessor cycle counts.
    (return static_cast<clock_t>(clock64());))
#  else
    (return static_cast<clock_t>(::cuda::ptx::get_sreg_clock64());))
#  endif
#endif // !_CCCL_HOSTJIT()
}

// difftime

[[nodiscard]] _CCCL_API constexpr double difftime(time_t __end, time_t __start) noexcept
{
  return static_cast<double>(__end - __start);
}

// time

#if _CCCL_CUDA_COMPILATION() || _CCCL_HIP_COMPILATION()
[[nodiscard]] _CCCL_DEVICE_API inline time_t __cccl_time_impl_device(time_t* __v) noexcept
{
#  if defined(__HIP_DEVICE_COMPILE__)
  // NOTE(HIP/AMD): wall_clock64() returns TSC cycles, not nanoseconds. The TSC
  // clock rate (cycles/sec) is arch-dependent and defined as
  // _LIBCUDACXX_HIP_TSC_CLOCKRATE in <cuda/std/detail/libcxx/include/__config>
  // (e.g. 25 MHz on gfx908/gfx90a, 100 MHz on gfx940/gfx950 and most other
  // architectures). Both that macro and wall_clock64() are only available in
  // the HIP device pass, so this branch is gated on __HIP_DEVICE_COMPILE__.
  const auto __t = static_cast<time_t>(wall_clock64() / _LIBCUDACXX_HIP_TSC_CLOCKRATE);
#  elif _CCCL_HIP_COMPILATION()
  // Host pass on hipcc: this device function body is parsed but never
  // codegen'd, so a stub return suffices.
  const time_t __t = 0;
#  else
  const auto __t = static_cast<time_t>(::cuda::ptx::get_sreg_globaltimer() / 1'000'000'000);
#  endif
  if (__v != nullptr)
  {
    *__v = __t;
  }
  return __t;
}
#endif // _CCCL_CUDA_COMPILATION() || _CCCL_HIP_COMPILATION()

_CCCL_API inline time_t time(time_t* __v) noexcept
{
#if _CCCL_HOSTJIT() // host-side `time` is not supported in freestanding
  NV_IF_ELSE_TARGET(NV_IS_HOST, (::cuda::std::terminate();), (return ::cuda::std::__cccl_time_impl_device(__v);))
#else // ^^^ _CCCL_HOSTJIT() ^^^ / vvv !_CCCL_HOSTJIT() vvv
  NV_IF_ELSE_TARGET(NV_IS_HOST, (return ::time(__v);), (return ::cuda::std::__cccl_time_impl_device(__v);))
#endif // !_CCCL_HOSTJIT()
}

#if !defined(__ANDROID_API__) || __ANDROID_API__ >= 29

// timespec_get

#  if _CCCL_CUDA_COMPILATION() || _CCCL_HIP_COMPILATION()
[[nodiscard]] _CCCL_DEVICE_API inline int __cccl_timespec_get_impl_device(timespec* __ts, int __base) noexcept
{
  if (__ts == nullptr || __base != TIME_UTC)
  {
    return 0;
  }
#    if defined(__HIP_DEVICE_COMPILE__)
  // NOTE(HIP/AMD): wall_clock64() returns TSC cycles, not nanoseconds.
  // Convert with the arch-dependent TSC rate (see __cccl_time_impl_device):
  //   tv_sec  = cycles / CLOCKRATE
  //   tv_nsec = (cycles % CLOCKRATE) * NANOSECONDS_PER_CYCLE
  // Both _LIBCUDACXX_HIP_TSC_CLOCKRATE and
  // _LIBCUDACXX_HIP_TSC_NANOSECONDS_PER_CYCLE are only defined in the HIP
  // device pass.
  const auto __t = wall_clock64();
  __ts->tv_sec   = static_cast<time_t>(__t / _LIBCUDACXX_HIP_TSC_CLOCKRATE);
  __ts->tv_nsec  = static_cast<long>((__t % _LIBCUDACXX_HIP_TSC_CLOCKRATE)
                                     * _LIBCUDACXX_HIP_TSC_NANOSECONDS_PER_CYCLE);
#    elif _CCCL_HIP_COMPILATION()
  // Host pass on hipcc: this device function body is parsed but never
  // codegen'd, so a stub suffices.
  __ts->tv_sec  = 0;
  __ts->tv_nsec = 0;
#    else
  const auto __t = ::cuda::ptx::get_sreg_globaltimer();
  __ts->tv_sec   = static_cast<time_t>(__t / 1'000'000'000);
  __ts->tv_nsec  = static_cast<long>(__t % 1'000'000'000);
#    endif
  return __base;
}
#  endif // _CCCL_CUDA_COMPILATION() || _CCCL_HIP_COMPILATION()

[[nodiscard]] _CCCL_API inline int timespec_get(timespec* __ts, int __base) noexcept
{
#  if _CCCL_HOSTJIT() // host-side `timespec_get` is not supported in freestanding
  NV_IF_ELSE_TARGET(
    NV_IS_HOST, (::cuda::std::terminate();), (return ::cuda::std::__cccl_timespec_get_impl_device(__ts, __base);))
#  else // ^^^ _CCCL_HOSTJIT() ^^^ / vvv !_CCCL_HOSTJIT() vvv
  NV_IF_ELSE_TARGET(NV_IS_HOST,
                    (return ::timespec_get(__ts, __base);),
                    (return ::cuda::std::__cccl_timespec_get_impl_device(__ts, __base);))
#  endif // !_CCCL_HOSTJIT()
}

#endif // !defined(__ANDROID_API__) || __ANDROID_API__ >= 29

_CCCL_END_NAMESPACE_CUDA_STD

#include <cuda/std/__cccl/epilogue.h>

#endif // _CUDA_STD_CTIME
