* 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.
*/
#include "codegen/codegen_base.h"
#include <cmath>
#include <cstdint>
#include <iomanip>
#include <limits>
#include <sstream>
#include <string>
#include "core/dtype.h"
#include "core/error.h"
#include "core/logging.h"
#include "ir/expr.h"
#include "ir/kind_traits.h"
#include "ir/scalar_expr.h"
#include "ir/scalar_expr_ops.h"
#include "ir/type.h"
namespace pypto {
namespace codegen {
using namespace pypto::ir;
std::string FormatIntCLiteral(int64_t value, const ir::DataType& dtype)
{
if (dtype.IsUnsignedInt() && value < 0) {
return std::to_string(static_cast<uint64_t>(value)) + "uLL";
}
return std::to_string(value);
}
namespace {
constexpr double kMaxFixedMagnitude = 1e16;
bool ExactlyEqual(double lhs, double rhs) { return !std::islessgreater(lhs, rhs); }
}
std::string FormatFloatCLiteral(double value)
{
std::ostringstream oss;
if (!std::isfinite(value)) {
oss << value;
return oss.str();
}
if (ExactlyEqual(value, std::floor(value)) && std::fabs(value) < kMaxFixedMagnitude) {
oss << std::fixed << std::setprecision(1) << value;
return oss.str();
}
for (int precision = std::numeric_limits<double>::digits10; precision < std::numeric_limits<double>::max_digits10;
++precision) {
std::ostringstream candidate;
candidate << std::setprecision(precision) << value;
double parsed = 0.0;
std::istringstream(candidate.str()) >> parsed;
if (ExactlyEqual(parsed, value)) {
return candidate.str();
}
}
oss << std::setprecision(std::numeric_limits<double>::max_digits10) << value;
return oss.str();
}
}
}