/**
* Copyright (c) 2026 Huawei Technologies Co., Ltd.
* This program is free software, you can redistribute it and/or modify it under the terms and conditions of
* CANN Open Software License Agreement Version 2.0 (the "License").
* Please refer to the License for details. You may not use this file except in compliance with the License.
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
* See LICENSE in the root of the software repository for the full text of the License.
*/

/* !
 * \file log.asc
 * \brief 演示SIMT编程模式下使用assert抛出错误,以及通过ASCENDC_CHECK宏捕获错误
 */

#include <iostream>
#include <iterator>
#include <vector>
#include "asc_assert.h"
#include "acl/acl.h"
#include "asc_simt.h"

// [核心] ASCENDC_CHECK宏:用于捕获并打印ACL错误信息
#define ASCENDC_CHECK(expr) do {      \
        aclError ret = (expr);      \
        if (ret != ACL_SUCCESS) {     \
            fprintf(stderr,     \
            "Ascend Error: %s:%d code=%d %s\n",     \
            __FILE__, __LINE__,     \
            ret, aclGetRecentErrMsg());     \
        }     \
    } while(0)

/**
 * @brief Kernel函数:演示assert抛出错误
 */
__global__ void add_custom(float* x, float* y, float* z, uint64_t total_length)
{
    int32_t idx = blockIdx.x * blockDim.x + threadIdx.x;

    if (idx >= total_length) {
        return;
    }
    
    // assert抛出错误:仅thread 0触发断言,避免所有线程都打印
    if (idx == 0) {
        assert(total_length < 100 && "Total length exceeds expected limit!");
    }
    
    z[idx] = x[idx] + y[idx];
}

/**
 * @brief Host端Kernel调用函数
 */
void run_kernel(std::vector<float>& x, std::vector<float>& y, uint64_t total_length)
{
    size_t total_byte_size = x.size() * sizeof(float);
    int32_t device_id = 0;
    aclrtStream stream = nullptr;

    uint8_t* x_host = reinterpret_cast<uint8_t *>(x.data());
    uint8_t* y_host = reinterpret_cast<uint8_t *>(y.data());
    
    float* x_device = nullptr;
    float* y_device = nullptr;
    float* z_device = nullptr;
    
    aclInit(nullptr);
    aclrtSetDevice(device_id);
    aclrtCreateStream(&stream);
    
    aclrtMalloc((void **)&x_device, total_byte_size, ACL_MEM_MALLOC_HUGE_FIRST);
    aclrtMalloc((void **)&y_device, total_byte_size, ACL_MEM_MALLOC_HUGE_FIRST);
    aclrtMalloc((void **)&z_device, total_byte_size, ACL_MEM_MALLOC_HUGE_FIRST);
    
    aclrtMemcpy(x_device, total_byte_size, x_host, total_byte_size, ACL_MEMCPY_HOST_TO_DEVICE);
    aclrtMemcpy(y_device, total_byte_size, y_host, total_byte_size, ACL_MEMCPY_HOST_TO_DEVICE);
    
    uint32_t blocks_per_grid = 48;
    uint32_t threads_per_block = 256;
    uint32_t dyn_ubuf_size = 0;
    
    add_custom<<<blocks_per_grid, threads_per_block, dyn_ubuf_size, stream>>>(x_device, y_device, z_device, total_length);

    // [核心] 使用ASCENDC_CHECK宏捕获Kernel执行错误(包括assert触发的错误)
    ASCENDC_CHECK(aclrtGetLastError(ACL_RT_THREAD_LEVEL));
    ASCENDC_CHECK(aclrtSynchronizeDevice());

    aclrtSynchronizeStream(stream);

    const char* err = aclGetRecentErrMsg();
    if (err != nullptr) {
        fprintf(stderr, "[ERROR] %s\n", err);
    }

    aclrtFree(x_device);
    aclrtFree(y_device);
    aclrtFree(z_device);

    aclrtDestroyStream(stream);
    aclrtResetDevice(device_id);
    aclFinalize();
}

/**
 * @brief 主函数:构造输入数据使assert触发,验证错误捕获
 */
int32_t main(int32_t argc, char* argv[])
{
    constexpr uint32_t in_shape = 48 * 256;
    
    std::vector<float> x(in_shape);
    for (uint32_t i = 0; i < in_shape; i++) {
        x[i] = i * 1.1f;
    }

    std::vector<float> y(in_shape);
    for (uint32_t i = 0; i < in_shape; i++) {
        y[i] = i + 3.4f;
    }

    std::cout << "[INFO] Input shape: " << in_shape << std::endl;
    std::cout << "[INFO] Launching kernel with assert(total_length < 100)..." << std::endl;

    // 调用Kernel(assert会触发,ASCENDC_CHECK宏捕获错误)
    run_kernel(x, y, in_shape);

    std::cout << "[INFO] Execution completed. Check for error messages above." << std::endl;
    
    return 0;
}