#include "knn.cuh"

#include <iostream>

__global__ void compute_nearest_neighbors(const int* histo_tab,
                                        const size_t histo_pitch,
                                        const float* clusters,
                                        const size_t cluster_pitch,
                                        int* results,
                                        const size_t tiles_number)
{
    size_t x = threadIdx.x;
    size_t tile_index = blockIdx.x;

    if (x >= 256 || tile_index >= tiles_number)
        return;

    __shared__ float cluster_distances[16];

    for (auto y = 0; x == 0 && y < 16; y++)
        cluster_distances[y] = 0;

    __syncthreads();

    int value = *(histo_tab + tile_index * histo_pitch / sizeof(int) + x);

    for (auto y = 0; y < 16; y++)
    {
        float cluster_value = *(clusters + y * cluster_pitch / sizeof(float) + x);

        // Euclidean distance
        float local_distance = (cluster_value - value) * (cluster_value - value);

        atomicAdd(cluster_distances + y, local_distance);
    }

    __syncthreads();

    if (x != 0)
        return;

    auto result_ptr = results + tile_index;
    *result_ptr = 0;
    for (int i = 1; i < 16; i++)
    {
        if (cluster_distances[*result_ptr] > cluster_distances[i])
            *result_ptr = i;
    }
}

int* k_nearest_neighbors(const int* histo_tab, const float* clusters, const size_t tiles_number)
{
    cudaError_t rc = cudaSuccess;

    int* cuda_histo_tab;
    size_t cuda_histo_tab_pitch;
    auto tile_byte_size = 256 * sizeof(int);

    rc = cudaMallocPitch(&cuda_histo_tab, &cuda_histo_tab_pitch, tile_byte_size, tiles_number);
    if (rc)
    {
        std::cout << "Could not allocate memory for tiles histogram"
            << "on the device when computing nearest_neighbors\n";
        exit(EXIT_FAILURE);
    }

    rc = cudaMemcpy2D(cuda_histo_tab, cuda_histo_tab_pitch, histo_tab, tile_byte_size,
                        tile_byte_size, tiles_number, cudaMemcpyHostToDevice);
    if (rc)
    {
        std::cout << "Could not copy memory for tiles histogram"
            << "on the device when computing nearest_neighbors\n";
        exit(EXIT_FAILURE);
    }


    float* cuda_clusters;
    size_t cuda_clusters_pitch;
    auto cluster_byte_size = 256 * sizeof(float);

    rc = cudaMallocPitch(&cuda_clusters, &cuda_clusters_pitch, cluster_byte_size, 16);
    if (rc)
    {
        std::cout << "Could not allocate memory for clusters"
            << "on the device when computing nearest neighbors\n";
        exit(EXIT_FAILURE);
    }

    rc = cudaMemcpy2D(cuda_clusters, cuda_clusters_pitch, clusters, cluster_byte_size,
                        cluster_byte_size, 16, cudaMemcpyHostToDevice);
    if (rc)
    {
        std::cout << "Could not copy memory for clusters"
            << "on the device when computing nearest neighbors\n";
        exit(EXIT_FAILURE);
    }

    int* result;

    rc = cudaMalloc(&result, sizeof(int) * tiles_number);
    if (rc)
    {
        std::cout << "Could not allocate memory for nearest neighbors result"
            << "on the device when computing nearest neighbors\n";
        exit(EXIT_FAILURE);
    }

    dim3 block_dim(256, 16);
    compute_nearest_neighbors<<<tiles_number, 256>>>(cuda_histo_tab, cuda_histo_tab_pitch,
        cuda_clusters, cuda_clusters_pitch, result, tiles_number);


    int* output = (int*) malloc(sizeof(int) * tiles_number);
    rc = cudaMemcpy(output, result, sizeof(int) * tiles_number, cudaMemcpyDeviceToHost);

    cudaFree(cuda_clusters);
    cudaFree(result);

    return output;
}

	.file	"tmpxft_00212488_00000000-6_knn.cudafe1.cpp"
	.text
#APP
	.globl _ZSt21ios_base_library_initv

#NO_APP
	.type	_ZL26__cudaUnregisterBinaryUtilv, @function
_ZL26__cudaUnregisterBinaryUtilv:
.LFB3638:
	.cfi_startproc
	endbr64
	movq	_ZL20__cudaFatCubinHandle(%rip), %rdi
	jmp	__cudaUnregisterFatBinary@PLT
	.cfi_endproc
.LFE3638:
	.size	_ZL26__cudaUnregisterBinaryUtilv, .-_ZL26__cudaUnregisterBinaryUtilv
	.globl	_Z54__device_stub__Z25compute_nearest_neighborsPKimPKfmPimPKimPKfmPim
	.type	_Z54__device_stub__Z25compute_nearest_neighborsPKimPKfmPimPKimPKfmPim, @function
_Z54__device_stub__Z25compute_nearest_neighborsPKimPKfmPimPKimPKfmPim:
.LFB3660:
	.cfi_startproc
	endbr64
	subq	$184, %rsp
	.cfi_def_cfa_offset 192
	movq	%rdi, 40(%rsp)
	leaq	72(%rsp), %rdi
	movq	%rsi, 32(%rsp)
	leaq	84(%rsp), %rsi
	movq	%rdx, 24(%rsp)
	leaq	56(%rsp), %rdx
	movq	%rcx, 16(%rsp)
	leaq	64(%rsp), %rcx
	movq	%r8, 8(%rsp)
	movq	%r9, (%rsp)
	movq	%fs:40, %rax
	movq	%rax, 168(%rsp)
	xorl	%eax, %eax
	leaq	40(%rsp), %rax
	movl	$1, 80(%rsp)
	movq	%rax, 120(%rsp)
	leaq	32(%rsp), %rax
	movq	%rax, 128(%rsp)
	leaq	24(%rsp), %rax
	movq	%rax, 136(%rsp)
	leaq	16(%rsp), %rax
	movq	%rax, 144(%rsp)
	leaq	8(%rsp), %rax
	movq	%rax, 152(%rsp)
	movq	%rsp, %rax
	movq	%rax, 160(%rsp)
	movabsq	$4294967297, %rax
	movq	%rax, 72(%rsp)
	movq	%rax, 84(%rsp)
	movl	$1, 92(%rsp)
	call	__cudaPopCallConfiguration@PLT
	testl	%eax, %eax
	jne	.L2
	pushq	64(%rsp)
	.cfi_def_cfa_offset 200
	leaq	_Z25compute_nearest_neighborsPKimPKfmPim(%rip), %rdi
	pushq	64(%rsp)
	.cfi_def_cfa_offset 208
	movq	100(%rsp), %rcx
	movl	108(%rsp), %r8d
	movq	88(%rsp), %rsi
	movl	96(%rsp), %edx
	leaq	136(%rsp), %r9
	call	cudaLaunchKernel@PLT
	popq	%rax
	.cfi_def_cfa_offset 200
	popq	%rdx
	.cfi_def_cfa_offset 192
.L2:
	movq	168(%rsp), %rax
	subq	%fs:40, %rax
	je	.L4
	call	__stack_chk_fail@PLT
.L4:
	addq	$184, %rsp
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
.LFE3660:
	.size	_Z54__device_stub__Z25compute_nearest_neighborsPKimPKfmPimPKimPKfmPim, .-_Z54__device_stub__Z25compute_nearest_neighborsPKimPKfmPimPKimPKfmPim
	.globl	_Z25compute_nearest_neighborsPKimPKfmPim
	.type	_Z25compute_nearest_neighborsPKimPKfmPim, @function
_Z25compute_nearest_neighborsPKimPKfmPim:
.LFB3661:
	.cfi_startproc
	endbr64
	jmp	_Z54__device_stub__Z25compute_nearest_neighborsPKimPKfmPimPKimPKfmPim
	.cfi_endproc
.LFE3661:
	.size	_Z25compute_nearest_neighborsPKimPKfmPim, .-_Z25compute_nearest_neighborsPKimPKfmPim
	.section	.rodata.str1.1,"aMS",@progbits,1
.LC0:
	.string	"Could not allocate memory for tiles histogram"
.LC1:
	.string	"on the device when computing nearest_neighbors\n"
.LC2:
	.string	"Could not copy memory for tiles histogram"
.LC3:
	.string	"Could not allocate memory for clusters"
.LC4:
	.string	"on the device when computing nearest neighbors\n"
.LC5:
	.string	"Could not copy memory for clusters"
.LC6:
	.string	"Could not allocate memory for nearest neighbors result"
	.text
	.globl	_Z19k_nearest_neighborsPKiPKfm
	.type	_Z19k_nearest_neighborsPKiPKfm, @function
_Z19k_nearest_neighborsPKiPKfm:
.LFB3635:
	.cfi_startproc
	endbr64
	pushq	%r12
	.cfi_def_cfa_offset 16
	.cfi_offset 12, -16
	movq	%rdx, %rcx
	movq	%rdi, %r12
	pushq	%rbp
	.cfi_def_cfa_offset 24
	.cfi_offset 6, -24
	movq	%rsi, %rbp
	pushq	%rbx
	.cfi_def_cfa_offset 32
	.cfi_offset 3, -32
	movq	%rdx, %rbx
	movl	$1024, %edx
	subq	$80, %rsp
	.cfi_def_cfa_offset 112
	movq	%fs:40, %rax
	movq	%rax, 72(%rsp)
	xorl	%eax, %eax
	leaq	16(%rsp), %rsi
	leaq	8(%rsp), %rdi
	call	cudaMallocPitch@PLT
	leaq	.LC0(%rip), %rsi
	testl	%eax, %eax
	jne	.L17
	pushq	%rsi
	.cfi_def_cfa_offset 120
	movl	$1024, %r8d
	movq	%rbx, %r9
	movl	$1024, %ecx
	pushq	$1
	.cfi_def_cfa_offset 128
	movq	32(%rsp), %rsi
	movq	%r12, %rdx
	movq	24(%rsp), %rdi
	call	cudaMemcpy2D@PLT
	popq	%rdi
	.cfi_def_cfa_offset 120
	popq	%r8
	.cfi_def_cfa_offset 112
	testl	%eax, %eax
	je	.L10
	leaq	.LC2(%rip), %rsi
.L17:
	leaq	_ZSt4cout(%rip), %rdi
	call	_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc@PLT
	leaq	.LC1(%rip), %rsi
	movq	%rax, %rdi
.L18:
	call	_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc@PLT
	movl	$1, %edi
	call	exit@PLT
.L10:
	leaq	32(%rsp), %rsi
	leaq	24(%rsp), %rdi
	movl	$16, %ecx
	movl	$1024, %edx
	call	cudaMallocPitch@PLT
	leaq	.LC3(%rip), %rsi
	testl	%eax, %eax
	jne	.L19
	pushq	%rax
	.cfi_def_cfa_offset 120
	movl	$1024, %ecx
	movq	%rbp, %rdx
	movl	$16, %r9d
	pushq	$1
	.cfi_def_cfa_offset 128
	movq	48(%rsp), %rsi
	movl	$1024, %r8d
	movq	40(%rsp), %rdi
	call	cudaMemcpy2D@PLT
	popq	%rdx
	.cfi_def_cfa_offset 120
	leaq	.LC5(%rip), %rsi
	popq	%rcx
	.cfi_def_cfa_offset 112
	testl	%eax, %eax
	jne	.L19
	leaq	0(,%rbx,4), %rbp
	leaq	40(%rsp), %rdi
	movq	%rbp, %rsi
	call	cudaMalloc@PLT
	testl	%eax, %eax
	je	.L13
	leaq	.LC6(%rip), %rsi
.L19:
	leaq	_ZSt4cout(%rip), %rdi
	call	_ZStlsISt11char_traitsIcEERSt13basic_ostreamIcT_ES5_PKc@PLT
	leaq	.LC4(%rip), %rsi
	movq	%rax, %rdi
	jmp	.L18
.L13:
	movl	%ebx, 48(%rsp)
	movl	$16777217, %edx
	xorl	%r9d, %r9d
	xorl	%r8d, %r8d
	movabsq	$4294967297, %rax
	salq	$8, %rdx
	movl	$1, %ecx
	movq	%rax, 52(%rsp)
	movq	48(%rsp), %rdi
	movl	56(%rsp), %esi
	call	__cudaPushCallConfiguration@PLT
	testl	%eax, %eax
	jne	.L14
	movq	40(%rsp), %r8
	movq	32(%rsp), %rcx
	movq	%rbx, %r9
	movq	24(%rsp), %rdx
	movq	16(%rsp), %rsi
	movq	8(%rsp), %rdi
	call	_Z54__device_stub__Z25compute_nearest_neighborsPKimPKfmPimPKimPKfmPim
.L14:
	movq	%rbp, %rdi
	call	malloc@PLT
	movq	40(%rsp), %rsi
	movl	$2, %ecx
	movq	%rbp, %rdx
	movq	%rax, %rdi
	movq	%rax, %rbx
	call	cudaMemcpy@PLT
	movq	24(%rsp), %rdi
	call	cudaFree@PLT
	movq	40(%rsp), %rdi
	call	cudaFree@PLT
	movq	72(%rsp), %rax
	subq	%fs:40, %rax
	je	.L15
	call	__stack_chk_fail@PLT
.L15:
	addq	$80, %rsp
	.cfi_def_cfa_offset 32
	movq	%rbx, %rax
	popq	%rbx
	.cfi_def_cfa_offset 24
	popq	%rbp
	.cfi_def_cfa_offset 16
	popq	%r12
	.cfi_def_cfa_offset 8
	ret
	.cfi_endproc
.LFE3635:
	.size	_Z19k_nearest_neighborsPKiPKfm, .-_Z19k_nearest_neighborsPKiPKfm
	.section	.rodata.str1.1
.LC7:
	.string	"_Z25compute_nearest_neighborsPKimPKfmPim"
	.section	.text.startup,"ax",@progbits
	.type	_ZL24__sti____cudaRegisterAllv, @function
_ZL24__sti____cudaRegisterAllv:
.LFB3663:
	.cfi_startproc
	endbr64
	pushq	%rax
	.cfi_def_cfa_offset 16
	leaq	_ZL15__fatDeviceText(%rip), %rdi
	call	__cudaRegisterFatBinary@PLT
	pushq	$0
	.cfi_def_cfa_offset 24
	xorl	%r9d, %r9d
	orl	$-1, %r8d
	pushq	$0
	.cfi_def_cfa_offset 32
	leaq	.LC7(%rip), %rdx
	movq	%rax, %rdi
	leaq	_Z25compute_nearest_neighborsPKimPKfmPim(%rip), %rsi
	pushq	$0
	.cfi_def_cfa_offset 40
	movq	%rdx, %rcx
	pushq	$0
	.cfi_def_cfa_offset 48
	movq	%rax, _ZL20__cudaFatCubinHandle(%rip)
	call	__cudaRegisterFunction@PLT
	movq	_ZL20__cudaFatCubinHandle(%rip), %rdi
	addq	$32, %rsp
	.cfi_def_cfa_offset 16
	call	__cudaRegisterFatBinaryEnd@PLT
	leaq	_ZL26__cudaUnregisterBinaryUtilv(%rip), %rdi
	popq	%rdx
	.cfi_def_cfa_offset 8
	jmp	atexit@PLT
	.cfi_endproc
.LFE3663:
	.size	_ZL24__sti____cudaRegisterAllv, .-_ZL24__sti____cudaRegisterAllv
	.section	.init_array,"aw"
	.align 8
	.quad	_ZL24__sti____cudaRegisterAllv
	.section	.nvFatBinSegment,"aw"
	.align 8
	.type	_ZL15__fatDeviceText, @object
	.size	_ZL15__fatDeviceText, 24
_ZL15__fatDeviceText:
	.long	1180844977
	.long	1
	.quad	fatbinData
	.quad	0
	.local	_ZL20__cudaFatCubinHandle
	.comm	_ZL20__cudaFatCubinHandle,8,8
	.ident	"GCC: (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0"
	.section	.note.GNU-stack,"",@progbits
	.section	.note.gnu.property,"a"
	.align 8
	.long	1f - 0f
	.long	4f - 1f
	.long	5
0:
	.string	"GNU"
1:
	.align 8
	.long	0xc0000002
	.long	3f - 2f
2:
	.long	0x3
3:
	.align 8
4:

#pragma once
#include <hip/hip_runtime.h>


int* k_nearest_neighbors(const int* histo_tab, const float* clusters, const size_t tiles_number);

	.text
	.file	"knn.hip"
	.type	__hip_cuid_,@object             # @__hip_cuid_
	.bss
	.globl	__hip_cuid_
__hip_cuid_:
	.byte	0                               # 0x0
	.size	__hip_cuid_, 1

	.ident	"AMD clang version 18.0.0git (https://github.com/RadeonOpenCompute/llvm-project roc-6.3.2 25012 e5bf7e55c91490b07c49d8960fa7983d864936c4)"
	.section	".note.GNU-stack","",@progbits
	.addrsig
	.addrsig_sym __hip_cuid_

	.text
	.p2alignl 7, 3214868480
	.fill 96, 4, 3214868480
	.type	__hip_cuid_,@object             ; @__hip_cuid_
	.section	.bss,"aw",@nobits
	.globl	__hip_cuid_
__hip_cuid_:
	.byte	0                               ; 0x0
	.size	__hip_cuid_, 1

	.ident	"AMD clang version 18.0.0git (https://github.com/RadeonOpenCompute/llvm-project roc-6.3.2 25012 e5bf7e55c91490b07c49d8960fa7983d864936c4)"
	.section	".note.GNU-stack","",@progbits
	.addrsig
	.addrsig_sym __hip_cuid_
	.amdgcn_target "amdgcn-amd-amdhsa--gfx1100"
	.amdgpu_metadata
---
amdhsa.kernels:  []
amdhsa.target:   amdgcn-amd-amdhsa--gfx1100
amdhsa.version:
  - 1
  - 2
...

	.end_amdgpu_metadata
