# Copyright 1999-2026 Gentoo Authors
# Distributed under the terms of the GNU General Public License v2

EAPI=8

ROCM_VERSION=${PV}
PYTHON_COMPAT=( python3_{10..15} python3_13t )

inherit check-reqs cmake flag-o-matic multiprocessing python-r1 rocm

DESCRIPTION="High Performance Composable Kernel for AMD GPUs"
HOMEPAGE="https://github.com/ROCm/composable_kernel"
SRC_URI="https://github.com/ROCm/rocm-libraries/releases/download/therock-${PV%.0}/composablekernel.tar.gz -> ${P}.tar.gz"
S="${WORKDIR}/composablekernel"

LICENSE="MIT"
SLOT="0/$(ver_cut 1-2)"
KEYWORDS="~amd64"

IUSE="debug profiler"
REQUIRED_USE="${ROCM_REQUIRED_USE} ${PYTHON_REQUIRED_USE}"
# upstream only adds test/ without MIOPEN_REQ_LIBS_ONLY, which is always set below
RESTRICT="test"

RDEPEND="
	dev-util/hip:${SLOT}
	${PYTHON_DEPS}
"

DEPEND="${RDEPEND}"

BDEPEND="
	dev-build/rocm-cmake
"

# ~3GB of RAM per compile job
ck_jobs() {
	local jobs=$(get_makeopts_jobs)
	local mem_kb=$(awk '/^MemAvailable:/ {print $2}' /proc/meminfo || die)
	local max_jobs=$(( mem_kb / (3 * 1024 * 1024) ))
	max_jobs=$(( max_jobs < 1 ? 1 : max_jobs ))
	echo $(( jobs < max_jobs ? jobs : max_jobs ))
}

ck_check-reqs() {
	[[ ${MERGE_TYPE} == binary ]] && return

	targets=($AMDGPU_TARGETS)
	if [[ ${#targets[@]} -gt 1 ]]; then
		ewarn "composable-kernel will be compiled for multiple GPU architectures,"
		ewarn "which will take a significant amount of time."
		ewarn "Please consider setting AMDGPU_TARGETS USE_EXPAND variable to a single architecture."
	fi

	# src_configure limits the compile jobs to the available memory
	local CHECKREQS_MEMORY=3072M
	check-reqs_${EBUILD_PHASE_FUNC}
}

pkg_pretend() {
	ck_check-reqs
}

pkg_setup() {
	ck_check-reqs
}

src_prepare() {
	# libc++: device headers use std::map without including <map>
	sed -e "/^#pragma once/a #include <map>" -i include/ck/utility/common_header.hpp || die

	# don't build examples
	cmake_comment_add_subdirectory example

	# Flag -amdgpu-early-inline-all explodes memory consumption
	# https://github.com/llvm/llvm-project/issues/86332
	sed -e "/-amdgpu-early-inline-all/d" -e "/-amdgpu-function-calls/d" -i CMakeLists.txt || die

	# build ckprofiler with MIOPEN_REQ_LIBS_ONLY if requested
	sed -e "s/^\(    if (NOT MIOPEN_REQ_LIBS_ONLY AND NOT HIPTENSOR_REQ_LIBS_ONLY\))$/\1 OR CK_USE_PROFILER)/" \
		-i CMakeLists.txt || die

	cmake_src_prepare
}

src_configure() {
	rocm_use_clang

	if ! use debug; then
		append-cflags "-DNDEBUG"
		append-cxxflags "-DNDEBUG"
		CMAKE_BUILD_TYPE="Release"
	else
		CMAKE_BUILD_TYPE="Debug"
	fi

	local mycmakeargs=(
		-DCMAKE_SKIP_RPATH=ON
		-DBUILD_DEV=OFF
		-DGPU_TARGETS="$(get_amdgpu_flags)"
		-DCMAKE_INSTALL_PREFIX="${EPREFIX}/usr"
		-DBUILD_TESTING=OFF
		-DCK_USE_PROFILER=$(usex profiler ON OFF)
		-DCK_PARALLEL_COMPILE_JOBS=$(ck_jobs)
		# adds clang-tidy targets when clang-tidy is found
		-DENABLE_CLANG_CPP_CHECKS=OFF

		# Builds 2x less files, but faster.
		# See https://github.com/ROCm/TheRock/blob/5cb6abaa43ad664c85a99ac37bd4d3abf9b6260e/ml-libs/CMakeLists.txt#L37
		-DMIOPEN_REQ_LIBS_ONLY=ON
		-DCMAKE_DISABLE_FIND_PACKAGE_Git=ON
		-Wno-dev
	)

	# rocminfo call during configuration; should not happen
	# Bug: https://github.com/ROCm/composable_kernel/issues/2994
	rocm_add_sandbox -w
	addpredict /dev/random

	cmake_src_configure
}

src_install() {
	cmake_src_install

	# shellcheck disable=SC2329
	installation() {
		python_domodule python/ck4inductor

		# package-data of pyproject.toml, which only builds through setuptools
		shopt -s globstar
		package_data=(
			include/ck/**/*.hpp
			include/ck_tile/**/*.hpp
			include/ck_tile/**/*.inc
			library/src/tensor_operation_instance/gpu/gemm_universal/**/*.hpp
			library/src/tensor_operation_instance/gpu/gemm_universal_batched/**/*.hpp
			library/src/tensor_operation_instance/gpu/batched_gemm/**/*wmma_universal*.cpp
			library/include/ck/library/tensor_operation_instance/gpu/grouped_conv_fwd/**/*.hpp
		)
		shopt -u globstar

		inst_path="${D}$(python_get_sitedir)/ck4inductor"
		for file in "${package_data[@]}"; do
			location="${inst_path}/$(dirname "$file")"
			mkdir -p "${location}" || die
			cp "${file}" "${location}" || die
		done
	}
	python_foreach_impl installation
}