Merged
Add scalar limit check for int and float #5812
gaoxiang618Add on Aug 31
Add scalar limit check for int and float #5812
Merged
gaoxiang618Add on Aug 31
Total: 33 files changed+1793-614
@@ -138,7 +138,7 @@ public:
138 static const DataType BF16; // 16-bit brain floating point138 static const DataType BF16; // 16-bit brain floating point
139 static const DataType HF4; // 4-bit Hisilicon float139 static const DataType HF4; // 4-bit Hisilicon float
140 static const DataType HF8; // 8-bit Hisilicon float140 static const DataType HF8; // 8-bit Hisilicon float
141- static const DataType INDEX; // 32-bit index type141+ static const DataType INDEX; // 64-bit index type
142 142 
143 /**143 /**
144 * \brief Default constructor, initializes to BOOL type144 * \brief Default constructor, initializes to BOOL type
@@ -93,69 +93,6 @@ public:
93 */93 */
94 virtual std::string GetVarName(const ir::VarPtr& var) = 0;94 virtual std::string GetVarName(const ir::VarPtr& var) = 0;
95 95 
96- /**
97- * \brief Get the data pointer expression for a tensor variable
98- *
99- * Returns the C++ expression to access a tensor's raw data pointer.
100- * For external tensors returns "arg_<name>_ptr" or "<name>.data" for local tensors.
101- *
102- * \param tensor_name Tensor variable name
103- * \return C++ expression for the data pointer (e.g., "arg_x_ptr", "x.data")
104- */
105- [[nodiscard]] virtual std::string GetTensorDataPtr(const std::string& tensor_name) const
106- {
107- (void)tensor_name;
108- throw ir::ValueError("GetTensorDataPtr not implemented for this codegen");
109- }
110- 
111- /**
112- * \brief Get the external tensor name for a variable
113- *
114- * Returns the name used to reference a tensor in generated code.
115- * For external tensors (params/returns), returns "ext_<name>".
116- * For local tensors, returns the name as-is.
117- *
118- * \param name Tensor variable name
119- * \return External tensor name (e.g., "ext_x" or "x")
120- */
121- [[nodiscard]] virtual std::string GetExternalTensorName(const std::string& name) const { return name; }
122- 
123- /**
124- * \brief Get the runtime DataType enum string for generated code
125- *
126- * Returns the fully qualified DataType enum name as used by the runtime
127- * (e.g., "DataType::FLOAT32", "DataType::INT64"). Subclasses can override
128- * to match their target runtime's DataType enum naming.
129- *
130- * \param dtype The data type to convert
131- * \return Runtime DataType string (e.g., "DataType::FLOAT32")
132- */
133- [[nodiscard]] virtual std::string GetRuntimeDataTypeString(const ir::DataType& dtype) const;
134- 
135- /**
136- * \brief Try to extract variable name from expression
137- *
138- * Supports Var and IterArg expressions. Returns empty string if not a variable.
139- * Subclasses can override to transform variable names (e.g., strip SSA suffixes).
140- *
141- * \param expr Expression to extract name from
142- * \return Variable name or empty string
143- */
144- [[nodiscard]] virtual std::string TryGetVarName(const ir::ExprPtr& expr) const;
145- 
146- /**
147- * \brief Generate C++ code string for an IR expression
148- *
149- * Converts IR expressions to C++ code strings for inline operations.
150- * Supports variables, constants, binary operations, and tuple access.
151- * Calls TryGetVarName() for variable name extraction, enabling subclass
152- * name resolution via virtual dispatch.
153- *
154- * \param expr Expression to convert
155- * \return C++ code string
156- */
157- [[nodiscard]] std::string GenerateExprString(const ir::ExprPtr& expr) const;
158- 
159protected:96protected:
160 /**97 /**
161 * \brief Throw when no codegen is registered for a Call98 * \brief Throw when no codegen is registered for a Call
@@ -178,6 +115,31 @@ protected:
178 void VisitExpr_(const ir::CallPtr& op) override { ThrowNoCodegenForCall(op->name_); }115 void VisitExpr_(const ir::CallPtr& op) override { ThrowNoCodegenForCall(op->name_); }
179};116};
180 117 
118+/**
119+ * \brief Render a ConstInt payload as a C literal, honouring the dtype's signedness
120+ *
121+ * ConstInt stores an int64_t that doubles as the bit image of a uint64_t. Only a value above INT64_MAX
122+ * is stored folded, and only that one has to be spelled unsigned to stay in range; every other value
123+ * keeps the plain signed spelling so the surrounding integer promotions do not change.
124+ *
125+ * \param value Stored value
126+ * \param dtype Data type the value belongs to
127+ * \return C literal text
128+ */
129+std::string FormatIntCLiteral(int64_t value, const ir::DataType& dtype);
130+ 
131+/**
132+ * \brief Render a double as a C literal that round-trips
133+ *
134+ * std::to_string is "%f": exactly six decimal places, so a small constant such as 1e-30 becomes
135+ * 0.000000 and compiles to the wrong value. This keeps a trailing ".0" on an integral value and
136+ * otherwise emits the shortest form that parses back to the same double.
137+ *
138+ * \param value Value to render
139+ * \return C literal text, without a type suffix
140+ */
141+std::string FormatFloatCLiteral(double value);
142+ 
181} // namespace codegen143} // namespace codegen
182} // namespace pypto144} // namespace pypto
183 145 
@@ -108,36 +108,32 @@ static DataType GetExprDtype(const ir::ExprPtr& expr, DataType fallback = DataTy
108// Coerce a float-constant scalar to an integer literal matching the src type,108// Coerce a float-constant scalar to an integer literal matching the src type,
109// so that the emitted intrinsic (vmuls/vadds/vmins/vmaxs/vcmps_*/vaxpy)109// so that the emitted intrinsic (vmuls/vadds/vmins/vmaxs/vcmps_*/vaxpy)
110// receives a correctly-typed integer literal instead of a float literal110// receives a correctly-typed integer literal instead of a float literal
111-// that would trigger -Wliteral-conversion. Matches AscendC's implicit111+// that would trigger -Wliteral-conversion. The value is truncated to the width
112-// float→int truncation behavior (silent, mod 2^N wrap).112+// of src_dt, matching AscendC's implicit float→int conversion. The front end now
113+// rejects a scalar the src type cannot represent, so what reaches here is only
114+// the fractional part being dropped — not a value silently wrapping.
113static std::string CoerceScalarToInt(const ir::ExprPtr& scalar_expr, const DataType& src_dt,115static std::string CoerceScalarToInt(const ir::ExprPtr& scalar_expr, const DataType& src_dt,
114 const std::string& original_str)116 const std::string& original_str)
115{117{
116 if (!src_dt.IsInt()) {118 if (!src_dt.IsInt()) {
117 return original_str;119 return original_str;
118 }120 }
119- if (auto cf = ir::As<ir::ConstFloat>(scalar_expr)) {121+ auto cf = ir::As<ir::ConstFloat>(scalar_expr);
120- int64_t v = static_cast<int64_t>(cf->value_);122+ if (cf == nullptr) {
121- if (src_dt == DataType::INT16) {123+ return original_str;
122- return std::to_string(static_cast<int64_t>(static_cast<int16_t>(v)));
123- }
124- if (src_dt == DataType::UINT16) {
125- return std::to_string(static_cast<uint64_t>(static_cast<uint16_t>(v))) + "u";
126- }
127- if (src_dt == DataType::INT32) {
128- return std::to_string(static_cast<int64_t>(static_cast<int32_t>(v)));
129- }
130- if (src_dt == DataType::UINT32) {
131- return std::to_string(static_cast<uint64_t>(static_cast<uint32_t>(v))) + "u";
132- }
133- if (src_dt == DataType::INT64) {
134- return std::to_string(v);
135- }
136- if (src_dt == DataType::UINT64) {
137- return std::to_string(static_cast<uint64_t>(v)) + "u";
138- }
139 }124 }
140- return original_str;125+ const size_t bits = src_dt.GetBit();
poorwill

这里原来的逻辑只是做一个强转,首先可以根据src_dt获取dtype对应的字符串,然后直接强转即可. 另外这种类型修正应该是在IR就做修正,通过Cast处理统一走ir.Cast解决. 另外这种场景实际是一个错误的使用场景,感觉把错误的用法也搬过来了

likedislike
gaoxiang618
gaoxiang618
Sep 2 Comments:
likedislike
126+ if (bits == 0 || bits > 64) {
127+ return original_str;
128+ }
129+ const auto raw = static_cast<uint64_t>(static_cast<int64_t>(cf->value_));
130+ const uint64_t truncated = (bits == 64) ? raw : (raw & ((static_cast<uint64_t>(1) << bits) - 1));
131+ if (src_dt.IsUnsignedInt()) {
132+ return std::to_string(truncated) + "u";
133+ }
134+ // Sign-extend back out of the truncated width.
135+ const uint64_t sign_bit = static_cast<uint64_t>(1) << (bits - 1);
136+ return std::to_string(static_cast<int64_t>((truncated ^ sign_bit) - sign_bit));
141}137}
142 138 
143// For ops that only support ZEROING: return "MODE_ZEROING", reject MERGING.139// For ops that only support ZEROING: return "MODE_ZEROING", reject MERGING.
@@ -1790,7 +1790,7 @@ void CCECodegen::VisitExpr_(const ir::MakeTuplePtr& op)
1790void CCECodegen::VisitExpr_(const ir::ConstIntPtr& op)1790void CCECodegen::VisitExpr_(const ir::ConstIntPtr& op)
1791{1791{
1792 INTERNAL_CHECK(op != nullptr) << "Internal error: null ConstInt";1792 INTERNAL_CHECK(op != nullptr) << "Internal error: null ConstInt";
1793- current_expr_value_ = std::to_string(op->value_);1793+ current_expr_value_ = FormatIntCLiteral(op->value_, op->dtype());
1794}1794}
1795 1795 
1796void CCECodegen::VisitExpr_(const ir::ConstFloatPtr& op)1796void CCECodegen::VisitExpr_(const ir::ConstFloatPtr& op)
@@ -1802,9 +1802,7 @@ void CCECodegen::VisitExpr_(const ir::ConstFloatPtr& op)
1802 } else if (std::isinf(val)) {1802 } else if (std::isinf(val)) {
1803 current_expr_value_ = val > 0 ? "__builtin_huge_valf()" : "(-__builtin_huge_valf())";1803 current_expr_value_ = val > 0 ? "__builtin_huge_valf()" : "(-__builtin_huge_valf())";
1804 } else {1804 } else {
1805- std::string literal = std::to_string(val);1805+ current_expr_value_ = FormatFloatCLiteral(val) + "f";
1806- literal += "f";
1807- current_expr_value_ = literal;
1808 }1806 }
1809}1807}
1810 1808 
@@ -10,7 +10,11 @@
10 10 
11#include "codegen/codegen_base.h"11#include "codegen/codegen_base.h"
12 12 
13-#include <optional>13+#include <cmath>
14+#include <cstdint>
15+#include <iomanip>
16+#include <limits>
17+#include <sstream>
14#include <string>18#include <string>
15 19 
16#include "core/dtype.h"20#include "core/dtype.h"
@@ -27,172 +31,51 @@ namespace codegen {
27 31 
28using namespace pypto::ir; // NOLINT(build/namespaces)32using namespace pypto::ir; // NOLINT(build/namespaces)
29 33 
30-std::string CodegenBase::TryGetVarName(const ir::ExprPtr& expr) const34+std::string FormatIntCLiteral(int64_t value, const ir::DataType& dtype)
31{35{
32- if (auto var = As<Var>(expr)) {36+ if (dtype.IsUnsignedInt() && value < 0) {
33- return var->name_;37+ // Folded uint64 payload: the plain signed spelling would be out of range for long long.
38+ return std::to_string(static_cast<uint64_t>(value)) + "uLL";
34 }39 }
35- return "";40+ return std::to_string(value);
36}41}
37 42 
38namespace {43namespace {
44+// Above this magnitude every double is integral anyway, and the fixed form would spell out hundreds of
45+// digits; the scientific form round-trips just as exactly and stays readable.
46+constexpr double kMaxFixedMagnitude = 1e16;
39 47 
40-std::string BuildBinaryExprString(const CodegenBase& codegen, const ir::ExprPtr& left, const std::string& op,48+// Exact comparison of two finite doubles. -Wfloat-equal forbids the == operator; islessgreater is the
41- const ir::ExprPtr& right)49+// same test without the warning.
42-{50+bool ExactlyEqual(double lhs, double rhs) { return !std::islessgreater(lhs, rhs); }
43- return "(" + codegen.GenerateExprString(left) + " " + op + " " + codegen.GenerateExprString(right) + ")";
44-}
45- 
46-std::string GetScalarCTypeString(const ir::ExprPtr& expr, const std::string& op_name)
47-{
48- auto scalar_type = As<ScalarType>(expr->GetType());
49- INTERNAL_CHECK(scalar_type) << "Internal error: " << op_name << " expression should have ScalarType, got "
50- << expr->GetType()->TypeName();
51- return scalar_type->dtype_.ToCTypeString();
52-}
53- 
54-std::optional<std::string> TryGenerateSimpleExprString(const CodegenBase& codegen, const ir::ExprPtr& expr)
55-{
56- std::string var_name = codegen.TryGetVarName(expr);
57- if (!var_name.empty()) {
58- return var_name;
59- }
60- if (auto const_int = As<ConstInt>(expr)) {
61- return std::to_string(const_int->value_);
62- }
63- if (auto const_float = As<ConstFloat>(expr)) {
64- return std::to_string(const_float->value_);
65- }
66- if (auto const_bool = As<ConstBool>(expr)) {
67- return const_bool->value_ ? "1" : "0";
68- }
69- return std::nullopt;
70-}
71- 
72-std::optional<std::string> TryGenerateBinaryExprString(const CodegenBase& codegen, const ir::ExprPtr& expr)
73-{
74- if (auto add = As<Add>(expr)) {
75- return BuildBinaryExprString(codegen, add->left_, "+", add->right_);
76- }
77- if (auto sub = As<Sub>(expr)) {
78- return BuildBinaryExprString(codegen, sub->left_, "-", sub->right_);
79- }
80- if (auto mul = As<Mul>(expr)) {
81- return BuildBinaryExprString(codegen, mul->left_, "*", mul->right_);
82- }
83- if (auto floor_div = As<FloorDiv>(expr)) {
84- return BuildBinaryExprString(codegen, floor_div->left_, "/", floor_div->right_);
85- }
86- if (auto floor_mod = As<FloorMod>(expr)) {
87- return BuildBinaryExprString(codegen, floor_mod->left_, "%", floor_mod->right_);
88- }
89- if (auto eq = As<Eq>(expr)) {
90- return BuildBinaryExprString(codegen, eq->left_, "==", eq->right_);
91- }
92- if (auto ne = As<Ne>(expr)) {
93- return BuildBinaryExprString(codegen, ne->left_, "!=", ne->right_);
94- }
95- if (auto lt = As<Lt>(expr)) {
96- return BuildBinaryExprString(codegen, lt->left_, "<", lt->right_);
97- }
98- if (auto le = As<Le>(expr)) {
99- return BuildBinaryExprString(codegen, le->left_, "<=", le->right_);
100- }
101- if (auto gt = As<Gt>(expr)) {
102- return BuildBinaryExprString(codegen, gt->left_, ">", gt->right_);
103- }
104- if (auto ge = As<Ge>(expr)) {
105- return BuildBinaryExprString(codegen, ge->left_, ">=", ge->right_);
106- }
107- return std::nullopt;
108-}
109- 
110-std::optional<std::string> TryGenerateMinMaxExprString(const CodegenBase& codegen, const ir::ExprPtr& expr)
111-{
112- if (auto min_expr = As<Min>(expr)) {
113- std::string cpp_type = GetScalarCTypeString(expr, "Min");
114- return "std::min<" + cpp_type + ">(" + codegen.GenerateExprString(min_expr->left_) + ", " +
115- codegen.GenerateExprString(min_expr->right_) + ")";
116- }
117- if (auto max_expr = As<Max>(expr)) {
118- std::string cpp_type = GetScalarCTypeString(expr, "Max");
119- return "std::max<" + cpp_type + ">(" + codegen.GenerateExprString(max_expr->left_) + ", " +
120- codegen.GenerateExprString(max_expr->right_) + ")";
121- }
122- return std::nullopt;
123-}
124- 
125-std::optional<std::string> TryGenerateUnaryExprString(const CodegenBase& codegen, const ir::ExprPtr& expr)
126-{
127- if (auto neg = As<Neg>(expr)) {
128- return "(-" + codegen.GenerateExprString(neg->operand_) + ")";
129- }
130- if (auto cast_expr = As<Cast>(expr)) {
131- std::string cpp_type = GetScalarCTypeString(expr, "Cast");
132- return "static_cast<" + cpp_type + ">(" + codegen.GenerateExprString(cast_expr->operand_) + ")";
133- }
134- return std::nullopt;
135-}
136- 
137-std::optional<std::string> TryGenerateTupleGetItemExprString(const CodegenBase& codegen, const ir::ExprPtr& expr)
138-{
139- auto get_item = As<GetItemExpr>(expr);
140- if (!get_item || !As<TupleType>(get_item->value_->GetType())) {
141- return std::nullopt;
142- }
143- 
144- auto const_idx = As<ConstInt>(get_item->slice_);
145- INTERNAL_CHECK(const_idx) << "GetItemExpr on a tuple requires a ConstInt slice, got "
146- << get_item->slice_->TypeName();
147- return codegen.GenerateExprString(get_item->value_) + "_" + std::to_string(const_idx->value_);
148-}
149- 
150} // namespace51} // namespace
151 52 
152-std::string CodegenBase::GenerateExprString(const ir::ExprPtr& expr) const53+std::string FormatFloatCLiteral(double value)
153{54{
154- if (auto simple = TryGenerateSimpleExprString(*this, expr)) {55+ std::ostringstream oss;
155- return *simple;56+ if (!std::isfinite(value)) {
57+ oss << value;
58+ return oss.str();
156 }59 }
157- if (auto binary = TryGenerateBinaryExprString(*this, expr)) {60+ if (ExactlyEqual(value, std::floor(value)) && std::fabs(value) < kMaxFixedMagnitude) {
158- return *binary;61+ // An integral value keeps a ".0" so the literal still reads as a float.
62+ oss << std::fixed << std::setprecision(1) << value;
63+ return oss.str();
159 }64 }
160- if (auto min_max = TryGenerateMinMaxExprString(*this, expr)) {65+ // Shortest form that still parses back to the same double, so the literal round-trips without
161- return *min_max;66+ // spelling out 17 digits for a value that needs far fewer.
67+ for (int precision = std::numeric_limits<double>::digits10; precision < std::numeric_limits<double>::max_digits10;
68+ ++precision) {
69+ std::ostringstream candidate;
70+ candidate << std::setprecision(precision) << value;
71+ double parsed = 0.0;
72+ std::istringstream(candidate.str()) >> parsed;
73+ if (ExactlyEqual(parsed, value)) {
74+ return candidate.str();
75+ }
162 }76 }
163- if (auto unary = TryGenerateUnaryExprString(*this, expr)) {77+ oss << std::setprecision(std::numeric_limits<double>::max_digits10) << value;
164- return *unary;78+ return oss.str();
165- }
166- if (auto get_item = TryGenerateTupleGetItemExprString(*this, expr)) {
167- return *get_item;
168- }
169- throw NotImplementedError("GenerateExprString not implemented for expression type: " + expr->TypeName());
170-}
171- 
172-std::string CodegenBase::GetRuntimeDataTypeString(const ir::DataType& dtype) const
173-{
174- if (dtype == DataType::FP16)
175- return "DataType::FLOAT16";
176- if (dtype == DataType::FP32)
177- return "DataType::FLOAT32";
178- if (dtype == DataType::INT32)
179- return "DataType::INT32";
180- if (dtype == DataType::INT16)
181- return "DataType::INT16";
182- if (dtype == DataType::INT8)
183- return "DataType::INT8";
184- if (dtype == DataType::UINT8)
185- return "DataType::UINT8";
186- if (dtype == DataType::BF16)
187- return "DataType::BFLOAT16";
188- // INDEX is a semantic type in the IR; the runtime represents it as INT64
189- if (dtype == DataType::INDEX)
190- return "DataType::INT64";
191- if (dtype == DataType::INT64)
192- return "DataType::INT64";
193- if (dtype == DataType::UINT64)
194- return "DataType::UINT64";
195- return "DataType::UNKNOWN";
196}79}
197 80 
198} // namespace codegen81} // namespace codegen
@@ -1,60 +0,0 @@
1-/**
2- * Copyright (c) 2026 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-#include <algorithm>
12-#include <cctype>
13-#include <cstddef>
14-#include <cstdint>
15-#include <sstream>
16-#include <string>
17- 
18-#include "codegen/codegen_base.h"
19-#include "core/logging.h"
20-#include "ir/expr.h"
21-#include "ir/kind_traits.h"
22-#include "ir/scalar_expr.h"
23-#include "ir/scalar_expr_ops.h"
24-#include "ir/type.h"
25- 
26-namespace pypto {
27-namespace codegen {
28- 
29-using namespace pypto::ir; // NOLINT(build/namespaces)
30- 
31-// Helper function to calculate tensor size expression
32-[[maybe_unused]] static std::string CalculateTensorSizeExpr(const TensorTypePtr& tensor_type, CodegenBase& codegen)
33-{
34- std::ostringstream oss;
35- 
36- // Calculate total number of elements by multiplying all dimensions
37- bool first = true;
38- for (const auto& dim : tensor_type->shape_) {
39- if (first) {
40- oss << codegen.GenerateExprString(dim);
41- first = false;
42- } else {
43- oss << " * " << codegen.GenerateExprString(dim);
44- }
45- }
46- 
47- // If shape is empty, it's a scalar (1 element)
48- if (first) {
49- oss << "1";
50- }
51- 
52- // Multiply by element size in bytes
53- size_t element_bits = tensor_type->dtype_.GetBit();
54- size_t element_bytes = (element_bits + 7) / 8; // Round up to nearest byte
55- oss << " * " << element_bytes;
56- 
57- return oss.str();
58-}
59-} // namespace codegen
60-} // namespace pypto
@@ -0,0 +1,153 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+ 
12+"""Numeric limits of the IR data types.
13+ 
14+Pure data and predicates over :class:`DataType`; no dependency on the parser or on any third-party
15+package. Two bands matter:
16+ 
17+* the *storage* band ``[INT64_MIN, UINT64_MAX]`` that ``ir.ConstInt`` can carry -- its ``value_`` field
18+ is an ``int64_t`` that doubles as the bit image of a ``uint64_t``;
19+* the *representable* band of a concrete dtype, used to reject scalar operands that an operator could
20+ not encode.
21+"""
22+ 
23+from __future__ import annotations
24+ 
25+__all__ = [
26+ "INT64_MAX",
27+ "INT64_MIN",
28+ "UINT64_MAX",
29+ "NumericLimits",
30+ "fits",
31+ "fits_storage_int",
32+ "from_storage_int",
33+ "limits_of",
34+ "to_storage_int",
35+]
36+ 
37+ 
38+import math
39+from typing import NamedTuple
40+ 
41+from pypto.pypto_impl.ir import DataType
42+ 
43+INT64_MIN = -(2 ** 63)
44+INT64_MAX = 2 ** 63 - 1
45+UINT64_MAX = 2 ** 64 - 1
46+ 
47+_UINT64_MODULUS = 2 ** 64
48+ 
49+ 
50+class NumericLimits(NamedTuple):
51+ """Inclusive ``[lo, hi]`` range of the finite values a dtype can represent."""
52+ 
53+ lo: float
54+ hi: float
55+ is_float: bool
56+ 
57+ 
58+# Largest finite magnitude of every float format whose encoding is specified. Each entry is derived
59+# from the exponent/mantissa widths and cross-checked against the constants already used by the
60+# backend (FP16_MAX in vector/indexing.cpp, 448.0f / 57344.0f in fp_convert.cpp, 6.0f in calc_torch.cpp).
61+#
62+# fp4, fp4e1m2, hf4 and hf8 are deliberately absent: their encodings are not specified anywhere in the
63+# tree, and guessing one would produce wrong rejections. `limits_of` returns None for them so callers
64+# skip the check rather than assume an unbounded range.
65+_FLOAT_MAX_FINITE: dict[str, float] = {
66+ "fp64": 1.7976931348623157e308,
67+ "fp32": 3.4028234663852886e38,
68+ "bfloat16": 3.3895313892515355e38,
69+ "fp16": 65504.0,
70+ "fp8e5m2": 57344.0,
71+ "fp8e4m3fn": 448.0,
72+ "fp8e8m0": float(2 ** 127),
73+ "fp4e2m1": 6.0,
74+}
75+ 
76+# fp8e8m0 encodes a bare exponent, so it carries no sign bit and no negative value.
77+_UNSIGNED_FLOATS = frozenset({"fp8e8m0"})
78+ 
79+ 
80+def limits_of(dtype: DataType) -> NumericLimits | None:
81+ """Inclusive value range of *dtype*, or ``None`` when the format is not specified in-tree.
82+ 
83+ ``None`` means "unknown", not "unbounded": callers skip the check for such a dtype.
84+ """
85+ if dtype == DataType.BOOL:
86+ # BOOL is stored in a byte, so get_bit() reports 8; the value range is still just [0, 1].
87+ return NumericLimits(0, 1, False)
88+ if dtype.is_float():
89+ max_finite = _FLOAT_MAX_FINITE.get(str(dtype))
90+ if max_finite is None:
91+ return None
92+ lo = 0.0 if str(dtype) in _UNSIGNED_FLOATS else -max_finite
93+ return NumericLimits(lo, max_finite, True)
94+ bits = dtype.get_bit()
95+ if dtype.is_signed_int():
96+ # INDEX is a 64-bit signed placeholder, and reports itself as a signed int.
97+ return NumericLimits(-(2 ** (bits - 1)), 2 ** (bits - 1) - 1, False)
98+ if dtype.is_unsigned_int():
99+ return NumericLimits(0, 2 ** bits - 1, False)
100+ return None
101+ 
102+ 
103+def fits(value: int | float, dtype: DataType) -> tuple[bool, str, NumericLimits | None]:
104+ """Whether *value* is representable in *dtype*.
105+ 
106+ Returns ``(ok, reason, limits)``. *reason* is empty when *ok*, and *limits* is ``None`` for a dtype
107+ whose encoding is not specified in-tree -- such a dtype has no bounds to check, so it always fits.
108+ 
109+ Non-finite floats (``inf`` / ``nan``) pass for a float dtype, where they are legitimate reduction
110+ seeds the backend emits explicitly; against an integer dtype they are rejected, because the backend
111+ lowers a float scalar through ``static_cast<int64_t>``, which is undefined for them. A fractional
112+ value against an integer dtype is only range-checked, never rejected for having a fraction -- the
113+ backend truncates it.
114+ """
115+ limits = limits_of(dtype)
116+ if limits is None:
117+ return True, "", limits
118+ if isinstance(value, float) and not math.isfinite(value):
119+ if dtype.is_float():
120+ return True, "", limits
121+ else:
122+ return False, f"{value} value does not match integer dtype {dtype}", limits
123+ if limits.lo <= value <= limits.hi:
124+ return True, "", limits
125+ else:
126+ return False, f"{value} is out of range of current dtype {dtype}", limits
127+ 
128+ 
129+def fits_storage_int(value: int) -> bool:
130+ """Whether *value* fits the ``[INT64_MIN, UINT64_MAX]`` band that ``ir.ConstInt`` can carry."""
131+ return INT64_MIN <= value <= UINT64_MAX
132+ 
133+ 
134+def to_storage_int(value: int) -> int:
135+ """Fold *value* into the ``int64_t`` field of ``ir.ConstInt``.
136+ 
137+ Values above ``INT64_MAX`` are stored as their two's-complement image and rendered back according
138+ to the dtype's signedness by the code generators.
139+ """
140+ if value > INT64_MAX:
141+ return value - _UINT64_MODULUS
142+ return value
143+ 
144+ 
145+def from_storage_int(value: int, dtype: DataType) -> int:
146+ """Recover the logical value of a constant stored by :func:`to_storage_int`.
147+ 
148+ Only a 64-bit unsigned constant can hold a folded (negative) image: every narrower unsigned dtype
149+ stores its value directly, so the un-fold is a no-op there.
150+ """
151+ if value < 0 and dtype.is_unsigned_int():
152+ return value + _UINT64_MODULUS
153+ return value
@@ -76,6 +76,7 @@ def _normalize_expr(
76 76 
77 Raises:77 Raises:
78 TypeError: If value is not int, float, or ir.Expr78 TypeError: If value is not int, float, or ir.Expr
79+ FinalRejectionError: If an integer is outside the range the IR can carry
79 """80 """
80 if isinstance(value, _ir.Expr):81 if isinstance(value, _ir.Expr):
81 return value82 return value
@@ -83,7 +84,9 @@ def _normalize_expr(
83 actual_span = span if span is not None else _ir.Span.unknown()84 actual_span = span if span is not None else _ir.Span.unknown()
84 85 
85 if isinstance(value, int):86 if isinstance(value, int):
86- return _ir.ConstInt(value, int_dtype, actual_span)87+ from pypto_pro.language.parser.diagnostics import make_const_int
88+ 
89+ return make_const_int(value, int_dtype, span=actual_span)
87 elif isinstance(value, float):90 elif isinstance(value, float):
88 return _ir.ConstFloat(value, float_dtype, actual_span)91 return _ir.ConstFloat(value, float_dtype, actual_span)
89 else:92 else:
@@ -762,7 +762,13 @@ def _ir_xor(out: Expr, lhs: Expr, rhs: Expr, tmp: Expr, *, span: Span | None = N
762 762 
763 763 
764def _ir_expands(out: Expr, scalar: Expr, *, span: Span | None = None) -> Expr:764def _ir_expands(out: Expr, scalar: Expr, *, span: Span | None = None) -> Expr:
765- _check_dtype("expands", getattr(out.type, "dtype", None), _EXPANDS_DTYPES)765+ from pypto_pro.language.parser.diagnostics import check_const_expr_fits_dtype
766+ 
767+ out_dtype = getattr(out.type, "dtype", None)
768+ _check_dtype("expands", out_dtype, _EXPANDS_DTYPES)
769+ # The splat value lands in the out tile, so it has to be representable there. Without this the
770+ # scalar was only bounded by the IR storage band, which is far wider than a narrow tile dtype.
771+ check_const_expr_fits_dtype(scalar, out_dtype, span=span, api="pl.expands")
766 return _ir_core.create_op_call(block_ir_op("expands"), [out, scalar], {}, span or _span())772 return _ir_core.create_op_call(block_ir_op("expands"), [out, scalar], {}, span or _span())
767 773 
768 774 
@@ -2227,7 +2233,11 @@ def _create_tile_scalar_op(
2227 if isinstance(getattr(rhs, "type", None), _ir_core.TileType):2233 if isinstance(getattr(rhs, "type", None), _ir_core.TileType):
2228 target_op = block_ir_op(tile_op)2234 target_op = block_ir_op(tile_op)
2229 else:2235 else:
2236+ from pypto_pro.language.parser.diagnostics import check_const_expr_fits_dtype
2237+ 
2230 target_op = block_ir_op(scalar_op)2238 target_op = block_ir_op(scalar_op)
2239+ out_dtype = getattr(getattr(out, "type", None), "dtype", None)
2240+ check_const_expr_fits_dtype(rhs, out_dtype, span=span, api=f"pl.{tile_op}")
2231 return _ir_core.create_op_call(target_op, [out, lhs, rhs], kwargs, span)2241 return _ir_core.create_op_call(target_op, [out, lhs, rhs], kwargs, span)
2232 2242 
2233 2243 
@@ -159,7 +159,7 @@ register_table(
159 159 
160@op_impl("const")160@op_impl("const")
161def _parse_typed_constant(self, call: ast.Call):161def _parse_typed_constant(self, call: ast.Call):
162- from pypto_pro.language.parser.diagnostics import ParserSyntaxError162+ from pypto_pro.language.parser.diagnostics import ParserSyntaxError, check_fits_dtype, make_const_int
163 163 
164 span = self.span_tracker.get_span(call)164 span = self.span_tracker.get_span(call)
165 165 
@@ -197,7 +197,9 @@ def _parse_typed_constant(self, call: ast.Call):
197 )197 )
198 198 
199 if dtype == _ir_core.DataType.BOOL:199 if dtype == _ir_core.DataType.BOOL:
200+ check_fits_dtype(value, dtype, subject="value", span=span, api="pl.const")
200 return _ir_core.ConstBool(bool(value), span)201 return _ir_core.ConstBool(bool(value), span)
201 if dtype.is_float():202 if dtype.is_float():
203+ check_fits_dtype(float(value), dtype, subject="value", span=span, api="pl.const")
202 return _ir_core.ConstFloat(float(value), dtype, span)204 return _ir_core.ConstFloat(float(value), dtype, span)
203- return _ir_core.ConstInt(int(value), dtype, span)205+ return make_const_int(int(value), dtype, span=span, subject="value", api="pl.const")
@@ -34,9 +34,11 @@ from pypto.pypto_impl.ir import (
34from .._utils import _get_span_or_capture, _is_int, _normalize_expr, _to_make_tuple34from .._utils import _get_span_or_capture, _is_int, _normalize_expr, _to_make_tuple
35from ._op_registry import OpSpec, op_impl, register_table35from ._op_registry import OpSpec, op_impl, register_table
36 36 
37-_MAX_EVENT_ID = 1637+# Hardware resource ranges, inclusive on both ends. These are the single definition of each limit;
38-_MAX_FLAG_EVENT_ID = 838+# the pipeline scanner and the make_tile_group parser import them rather than restating them.
39-_MAX_MUTEX_ID = 3239+MAX_EVENT_ID = 15 # cross-core event ids
40+MAX_FLAG_EVENT_ID = 7 # set_flag / wait_flag event ids
41+MAX_MUTEX_ID = 31 # tile mutex ids
40 42 
41 43 
42def _is_integer_scalar_expr(value: Expr) -> bool:44def _is_integer_scalar_expr(value: Expr) -> bool:
@@ -44,14 +46,15 @@ def _is_integer_scalar_expr(value: Expr) -> bool:
44 return isinstance(value_type, _ir_core.ScalarType) and value_type.dtype.is_int()46 return isinstance(value_type, _ir_core.ScalarType) and value_type.dtype.is_int()
45 47 
46 48 
47-def _normalize_integer_id_expr(value: int | Expr, span: Span, *, name: str, upper_bound: int) -> Expr:49+def _normalize_integer_id_expr(value: int | Expr, span: Span, *, name: str, max_id: int) -> Expr:
48 """Normalize an integer ID to an IR operand and validate statically known values."""50 """Normalize an integer ID to an IR operand and validate statically known values."""
49 if not isinstance(value, Expr) and not _is_int(value):51 if not isinstance(value, Expr) and not _is_int(value):
50 raise TypeError(f"{name} must be a Python int or an integer scalar expression")52 raise TypeError(f"{name} must be a Python int or an integer scalar expression")
51 expr = _normalize_expr(value, span)53 expr = _normalize_expr(value, span)
52 if not _is_integer_scalar_expr(expr):54 if not _is_integer_scalar_expr(expr):
53 raise TypeError(f"{name} must be an integer scalar expression")55 raise TypeError(f"{name} must be an integer scalar expression")
54- _validate_const_id(expr, upper_bound, name)56+ if isinstance(expr, _ir_core.ConstInt):
57+ _check_id_range(expr.value, max_id, name)
55 return expr58 return expr
56 59 
57 60 
@@ -67,8 +70,7 @@ def _normalize_mutex_ids(mutex_ids: tuple | list | None) -> list[int] | None:
67 for index, mutex_id in enumerate(normalized_mutex_ids):70 for index, mutex_id in enumerate(normalized_mutex_ids):
68 if not _is_int(mutex_id):71 if not _is_int(mutex_id):
69 raise TypeError(f"mutex_ids[{index}] must be a Python int")72 raise TypeError(f"mutex_ids[{index}] must be a Python int")
70- if not 0 <= mutex_id < _MAX_MUTEX_ID:73+ _check_id_range(mutex_id, MAX_MUTEX_ID, "mutex_ids element")
71- raise ValueError(f"mutex_ids element must be in [0, {_MAX_MUTEX_ID}), got {mutex_id}")
72 return normalized_mutex_ids74 return normalized_mutex_ids
73 75 
74 76 
@@ -79,9 +81,11 @@ def _validate_concrete_pipe(pipe: PipeType, name: str) -> None:
79 raise ValueError(f"{name} must identify one concrete pipe, got PipeType.ALL")81 raise ValueError(f"{name} must identify one concrete pipe, got PipeType.ALL")
80 82 
81 83 
82-def _validate_const_id(expr: Expr, upper_bound: int, name: str) -> None:84+def _check_id_range(value: int, max_id: int, name: str, *, min_id: int = 0) -> None:
83- if isinstance(expr, _ir_core.ConstInt) and not 0 <= expr.value < upper_bound:85+ """Reject a hardware resource id outside its inclusive range."""
84- raise ValueError(f"{name} must be in [0, {upper_bound}), got {expr.value}")86+ from pypto_pro.language.parser.diagnostics import check_in_range
87+ 
88+ check_in_range(value, min_id, max_id, subject=name, error=ValueError)
85 89 
86 90 
87def _create_sync_op(91def _create_sync_op(
@@ -108,7 +112,7 @@ def _create_sync_op(
108 raise ValueError(f"set_pipe and wait_pipe must differ, got {set_pipe}")112 raise ValueError(f"set_pipe and wait_pipe must differ, got {set_pipe}")
109 kwargs = {"set_pipe": set_pipe, "wait_pipe": wait_pipe}113 kwargs = {"set_pipe": set_pipe, "wait_pipe": wait_pipe}
110 event_id_expr = _normalize_integer_id_expr(114 event_id_expr = _normalize_integer_id_expr(
111- event_id, actual_span, name="event_id", upper_bound=_MAX_FLAG_EVENT_ID115+ event_id, actual_span, name="event_id", max_id=MAX_FLAG_EVENT_ID
112 )116 )
113 return _ir_core.create_op_call(op_name + "_dyn", [event_id_expr], kwargs, actual_span)117 return _ir_core.create_op_call(op_name + "_dyn", [event_id_expr], kwargs, actual_span)
114 118 
@@ -221,8 +225,7 @@ def set_cross_core(
221 return _ir_core.create_op_call(225 return _ir_core.create_op_call(
222 "system.set_cross_core_dyn", [event_id], {"pipe": pipe, "sync_mode": sync_mode}, actual_span226 "system.set_cross_core_dyn", [event_id], {"pipe": pipe, "sync_mode": sync_mode}, actual_span
223 )227 )
224- if not 0 <= event_id < _MAX_EVENT_ID:228+ _check_id_range(event_id, MAX_EVENT_ID, "event_id")
225- raise ValueError(f"event_id must be in [0, {_MAX_EVENT_ID}), got {event_id}")
226 kwargs = {"pipe": pipe, "event_id": event_id, "sync_mode": sync_mode}229 kwargs = {"pipe": pipe, "event_id": event_id, "sync_mode": sync_mode}
227 return _ir_core.create_op_call("system.set_cross_core", [], kwargs, actual_span)230 return _ir_core.create_op_call("system.set_cross_core", [], kwargs, actual_span)
228 231 
@@ -257,8 +260,7 @@ def wait_cross_core(
257 {"pipe": pipe, "sync_mode": sync_mode},260 {"pipe": pipe, "sync_mode": sync_mode},
258 actual_span,261 actual_span,
259 )262 )
260- if not 0 <= event_id < _MAX_EVENT_ID:263+ _check_id_range(event_id, MAX_EVENT_ID, "event_id")
261- raise ValueError(f"event_id must be in [0, {_MAX_EVENT_ID}), got {event_id}")
262 kwargs = {"pipe": pipe, "event_id": event_id, "sync_mode": sync_mode}264 kwargs = {"pipe": pipe, "event_id": event_id, "sync_mode": sync_mode}
263 return _ir_core.create_op_call("system.wait_cross_core", [], kwargs, actual_span)265 return _ir_core.create_op_call("system.wait_cross_core", [], kwargs, actual_span)
264 266 
@@ -365,7 +367,7 @@ def _create_mutex_op(
365 """Create one user-requested manual mutex operation."""367 """Create one user-requested manual mutex operation."""
366 _validate_concrete_pipe(pipe, "pipe")368 _validate_concrete_pipe(pipe, "pipe")
367 mutex_id_expr = _normalize_integer_id_expr(369 mutex_id_expr = _normalize_integer_id_expr(
368- mutex_id, actual_span, name="mutex_id", upper_bound=_MAX_MUTEX_ID370+ mutex_id, actual_span, name="mutex_id", max_id=MAX_MUTEX_ID
369 )371 )
370 372 
371 kwargs: dict = {"pipe": pipe}373 kwargs: dict = {"pipe": pipe}
@@ -403,7 +405,7 @@ def _create_mutex_dedup_op(
403 if not mutex_id_exprs:405 if not mutex_id_exprs:
404 raise ValueError("mutex_id requires at least one expression")406 raise ValueError("mutex_id requires at least one expression")
405 normalized_mutex_id_exprs = [407 normalized_mutex_id_exprs = [
406- _normalize_integer_id_expr(mutex_id, actual_span, name="mutex_id", upper_bound=_MAX_MUTEX_ID)408+ _normalize_integer_id_expr(mutex_id, actual_span, name="mutex_id", max_id=MAX_MUTEX_ID)
407 for mutex_id in mutex_id_exprs409 for mutex_id in mutex_id_exprs
408 ]410 ]
409 kwargs: dict = {"pipe": pipe}411 kwargs: dict = {"pipe": pipe}
@@ -110,6 +110,15 @@ class AssignmentParserMixin:
110 # Ops where dst type differs from src type — dtype kwarg is mandatory.110 # Ops where dst type differs from src type — dtype kwarg is mandatory.
111 _TYPE_CHANGING_OPS = frozenset({"astype", "muls_cast", "pack", "unpack", "bit_cast"})111 _TYPE_CHANGING_OPS = frozenset({"astype", "muls_cast", "pack", "unpack", "bit_cast"})
112 112 
113+ @staticmethod
114+ def _infer_src_dtype(parsed_src_args: list) -> DataType | None:
115+ """The dtype of the first source that carries one, or None if no source does."""
116+ for src_expr in parsed_src_args:
117+ dtype = getattr(getattr(src_expr, 'type', None), 'dtype', None)
118+ if dtype is not None:
119+ return dtype
120+ return None
121+ 
113 def _parse_vf_assignment(122 def _parse_vf_assignment(
114 self,123 self,
115 target: ast.expr,124 target: ast.expr,
@@ -203,17 +212,10 @@ class AssignmentParserMixin:
203 # Also use this pass to infer dtype if not already determined.212 # Also use this pass to infer dtype if not already determined.
204 parsed_src_args = [self.parse_expression(src_arg) for src_arg in call.args]213 parsed_src_args = [self.parse_expression(src_arg) for src_arg in call.args]
205 214 
215+ src_dtype = self._infer_src_dtype(parsed_src_args)
216+ 
206 if dtype_val is None:217 if dtype_val is None:
207- for src_expr in parsed_src_args:218+ dtype_val = src_dtype
208- src_type = getattr(src_expr, 'type', None)
209- if src_type is None:
210- continue
211- if hasattr(src_type, 'dtype'):
212- dtype_val = src_type.dtype
213- break
214- if hasattr(src_type, 'element_dtype'):
215- dtype_val = src_type.element_dtype
216- break
217 219 
218 if dtype_val is None:220 if dtype_val is None:
219 raise ParserTypeError(221 raise ParserTypeError(
@@ -222,6 +224,12 @@ class AssignmentParserMixin:
222 span=span,224 span=span,
223 )225 )
224 226 
227+ # A scalar operand is checked against the dtype it is actually encoded in. That is dtype_val
228+ # -- the dst dtype -- except for a type-changing op, where dtype_val names the dst and the
229+ # operand still lives in the source domain (vf.muls_cast scales an fp32 src, then casts).
230+ operand_dtype = src_dtype if vf_op_name in self._TYPE_CHANGING_OPS else dtype_val
poorwill

这里有点奇怪,dtype val是约束的返回值类型么? 感觉应该统一用src dtype作为输入参数的类型校验,入参都是A类型,又传了dtype val为B类型的场景会校验失败。如果这种情况确实预期是失败的,那dtype val这个参数在这种情况又毫无意义了

likedislike
gaoxiang618
gaoxiang618
Sep 2 Comments:
likedislike
231+ self._check_vf_scalar_operands(vf_op_name, parsed_src_args, operand_dtype, span)
232+ 
225 # Re-inject dtype into kwargs iff the backend op carries it as an IR233 # Re-inject dtype into kwargs iff the backend op carries it as an IR
226 # attribute; otherwise it has already been stripped above.234 # attribute; otherwise it has already been stripped above.
227 ir_op_name = f"vf.{vf_op_name}"235 ir_op_name = f"vf.{vf_op_name}"
@@ -36,8 +36,9 @@ from pypto_pro.ir.op.block_ops import TileType as _TileType
36from pypto_pro.ir.op.block_ops import _ir_reinterpret, _static_shape_ints36from pypto_pro.ir.op.block_ops import _ir_reinterpret, _static_shape_ints
37from pypto_pro.ir.op.block_ops import make_tile_expr as _make_tile_expr37from pypto_pro.ir.op.block_ops import make_tile_expr as _make_tile_expr
38from pypto_pro.ir.op.block_ops import tile_slot_size as _tile_slot_size38from pypto_pro.ir.op.block_ops import tile_slot_size as _tile_slot_size
39+from pypto_pro.ir.op.system_ops import MAX_MUTEX_ID
39 40 
40-from .diagnostics import ParserSyntaxError, ParserTypeError41+from .diagnostics import ParserSyntaxError, ParserTypeError, check_in_range
41 42 
42 43 
43def _is_int_sequence(value) -> bool:44def _is_int_sequence(value) -> bool:
@@ -65,8 +66,9 @@ class BufferParserMixin:
65 tile_mutex_ids = (mutex_id,)66 tile_mutex_ids = (mutex_id,)
66 67 
67 for value in tile_mutex_ids:68 for value in tile_mutex_ids:
68- if not _is_int(value) or value < 0 or value > 31:69+ if not _is_int(value):
69- raise ParserTypeError(f"mutex_ids must be ints in [0,31], got {value!r}", span=span)70+ raise ParserTypeError(f"mutex_ids must be ints, got {value!r}", span=span)
71+ check_in_range(value, 0, MAX_MUTEX_ID, subject="mutex_ids element", span=span)
70 if len(set(tile_mutex_ids)) != len(tile_mutex_ids):72 if len(set(tile_mutex_ids)) != len(tile_mutex_ids):
71 raise ParserTypeError(73 raise ParserTypeError(
72 f"make_tile_group() mutex IDs for one tile must not contain duplicates: {tile_mutex_ids}",74 f"make_tile_group() mutex IDs for one tile must not contain duplicates: {tile_mutex_ids}",
@@ -34,8 +34,13 @@ from .diagnostics import (
34 ParserSyntaxError,34 ParserSyntaxError,
35 ParserTypeError,35 ParserTypeError,
36 UnsupportedFeatureError,36 UnsupportedFeatureError,
37+ check_const_expr_fits_dtype,
38+ check_in_range,
37)39)
38 40 
41+# Largest thread count a SIMT function may declare.
42+_MAX_SIMT_THREADS = 2048
43+ 
39logger = logging.getLogger(__name__)44logger = logging.getLogger(__name__)
40 45 
41 46 
@@ -908,6 +913,47 @@ class CallParserMixin:
908 """Return True if the VF op's dst(s) are MaskReg (not RegTensor)."""913 """Return True if the VF op's dst(s) are MaskReg (not RegTensor)."""
909 return op_name in cls._VF_MASK_DST_OPS914 return op_name in cls._VF_MASK_DST_OPS
910 915 
916+ # VF ops that take a literal scalar as a *value* operand, and are therefore
917+ # range-checked against the operand dtype. Everywhere else a numeric literal is
918+ # an offset, a repeat count or a bit pattern, none of which live in that dtype.
919+ # shift_left / shift_right are deliberately absent: their docs define a shift
920+ # wider than the type as yielding 0, so an "out of range" shift is legal. So is
921+ # bit_cast, whose operand is a bit pattern rather than a value.
922+ _VF_SCALAR_OPERAND_OPS = frozenset({
923+ "adds",
924+ "subs",
925+ "muls",
926+ "mins",
927+ "maxs",
928+ "axpy",
929+ "leaky_relu",
930+ "muls_cast",
931+ "full",
932+ "eq",
933+ "ne",
934+ "lt",
935+ "gt",
936+ "le",
937+ "ge",
938+ "arange",
939+ })
940+ 
941+ def _check_vf_scalar_operands(
942+ self,
943+ op_name: str,
944+ args: list,
945+ dtype: ir.DataType | None,
946+ span: ir.Span,
947+ ) -> None:
948+ """Reject a literal scalar operand of ``vf.<op_name>`` that ``dtype`` cannot represent.
949+ 
950+ Non-constant operands carry no value to check and are skipped.
951+ """
952+ if dtype is None or op_name not in self._VF_SCALAR_OPERAND_OPS:
953+ return
954+ for arg in args:
955+ check_const_expr_fits_dtype(arg, dtype, span=span, api=f"vf.{op_name}")
956+ 
911 def parse_call(self, call: ast.Call) -> Any:957 def parse_call(self, call: ast.Call) -> Any:
912 """Parse function call.958 """Parse function call.
913 959 
@@ -965,15 +1011,6 @@ class CallParserMixin:
965 hint="Use pl.*, pl.tensor.*, or pl.system.* operations",1011 hint="Use pl.*, pl.tensor.*, or pl.system.* operations",
966 )1012 )
967 1013 
968- if op_name == "constexpr":
969- raise ParserSyntaxError(
970- "pl.constexpr() can only be used as an 'if' condition or in a ternary expression, "
971- "e.g. 'if pl.constexpr(cond):' or 'x = a if pl.constexpr(cond) else b'",
972- span=span,
973- hint="Use 'pl.constexpr(condition):' in an if statement or ternary expression — "
974- "constexpr is not allowed in for/while/with/break/continue/return or as a standalone statement",
975- )
976- 
977 if self._current_func_type in (ir.FunctionType.SimtVF, ir.FunctionType.SimtCallee) and not op_name.startswith(1014 if self._current_func_type in (ir.FunctionType.SimtVF, ir.FunctionType.SimtCallee) and not op_name.startswith(
978 "simt."1015 "simt."
979 ):1016 ):
@@ -1109,8 +1146,7 @@ class CallParserMixin:
1109 if launchable:1146 if launchable:
1110 if not _is_int(max_threads):1147 if not _is_int(max_threads):
1111 raise TypeError("max_threads must be an integer")1148 raise TypeError("max_threads must be an integer")
1112- if not 1 <= max_threads <= 2048:1149+ check_in_range(max_threads, 1, _MAX_SIMT_THREADS, subject="max_threads", error=ValueError)
1113- raise ValueError("max_threads must be in the range [1, 2048]")
1114 1150 
1115 cached = self.simt_func_cache.get(id(fn))1151 cached = self.simt_func_cache.get(id(fn))
1116 if cached is not None:1152 if cached is not None:
@@ -1481,6 +1517,9 @@ class CallParserMixin:
1481 args = [self.parse_expression(arg) for arg in call.args]1517 args = [self.parse_expression(arg) for arg in call.args]
1482 kwargs = self.parse_op_kwargs(call)1518 kwargs = self.parse_op_kwargs(call)
1483 1519 
1520+ # No scalar-range check here: every op that takes a scalar value operand produces a result,
1521+ # so the guard above has already rejected its statement form. The assignment form is checked
1522+ # in _parse_vf_assignment, which is the only path those ops can reach.
1484 return ir.create_op_call(f"vf.{op_name}", args, kwargs, span)1523 return ir.create_op_call(f"vf.{op_name}", args, kwargs, span)
1485 1524 
1486 # --- auto_mutex helpers ---------------------------------------------------1525 # --- auto_mutex helpers ---------------------------------------------------
@@ -230,12 +230,9 @@ class ControlFlowParserMixin:
230 Args:230 Args:
231 stmt: If AST node231 stmt: If AST node
232 """232 """
233- test_node, is_constexpr = self._unwrap_constexpr(stmt.test)233+ condition = self.parse_expression(stmt.test)
234- condition = self.parse_expression(test_node)
235 span = self.span_tracker.get_span(stmt)234 span = self.span_tracker.get_span(stmt)
236 235 
237- condition = self._resolve_constexpr_condition(test_node, condition, is_constexpr, span)
238- 
239 if isinstance(condition, (ir.ConstBool, ir.ConstInt)):236 if isinstance(condition, (ir.ConstBool, ir.ConstInt)):
240 is_true = condition.value if isinstance(condition, ir.ConstBool) else condition.value != 0237 is_true = condition.value if isinstance(condition, ir.ConstBool) else condition.value != 0
241 self._record_if_const(stmt.test, True, bool(is_true))238 self._record_if_const(stmt.test, True, bool(is_true))
@@ -20,7 +20,7 @@ from typing import TYPE_CHECKING, Any, Callable
20from pypto.pypto_impl import ir20from pypto.pypto_impl import ir
21from pypto.pypto_impl.ir import DataType21from pypto.pypto_impl.ir import DataType
22 22 
23-from .diagnostics import ParserTypeError23+from .diagnostics import ParserTypeError, make_const_int
24 24 
25if TYPE_CHECKING:25if TYPE_CHECKING:
26 from ._span_tracker import SpanTracker26 from ._span_tracker import SpanTracker
@@ -246,7 +246,7 @@ class ExprEvaluator:
246 if isinstance(value, bool):246 if isinstance(value, bool):
247 return ir.ConstBool(value, span)247 return ir.ConstBool(value, span)
248 if isinstance(value, int):248 if isinstance(value, int):
249- return ir.ConstInt(value, DataType.INDEX, span)249+ return make_const_int(value, DataType.INDEX, span=span)
250 if isinstance(value, float):250 if isinstance(value, float):
251 return ir.ConstFloat(value, DataType.DEFAULT_CONST_FLOAT, span)251 return ir.ConstFloat(value, DataType.DEFAULT_CONST_FLOAT, span)
252 if isinstance(value, ir.Expr):252 if isinstance(value, ir.Expr):
@@ -27,6 +27,8 @@ from .diagnostics import (
27 ParserTypeError,27 ParserTypeError,
28 UndefinedVariableError,28 UndefinedVariableError,
29 UnsupportedFeatureError,29 UnsupportedFeatureError,
30+ check_fits_dtype,
31+ make_const_int,
30)32)
31 33 
32 34 
@@ -101,8 +103,11 @@ class ExpressionParserMixin:
101 if dtype == DataType.BOOL:103 if dtype == DataType.BOOL:
102 return ir.ConstBool(bool(value), span)104 return ir.ConstBool(bool(value), span)
103 if dtype.is_float():105 if dtype.is_float():
106+ # Folding must not change a program's meaning: a result the dtype cannot represent would
107+ # otherwise become inf (or a wrapped integer, on the branch below) with no diagnostic.
108+ check_fits_dtype(float(value), dtype, subject="float constant", span=span)
104 return ir.ConstFloat(float(value), dtype, span)109 return ir.ConstFloat(float(value), dtype, span)
105- return ir.ConstInt(int(value), dtype, span)110+ return make_const_int(int(value), dtype, span=span)
106 111 
107 @staticmethod112 @staticmethod
108 def _check_uniform_tuple_types(value_type: ir.TupleType, span: ir.Span) -> None:113 def _check_uniform_tuple_types(value_type: ir.TupleType, span: ir.Span) -> None:
@@ -120,34 +125,6 @@ class ExpressionParserMixin:
120 hint="Use a constant index to access elements of different types",125 hint="Use a constant index to access elements of different types",
121 )126 )
122 127 
123- @staticmethod
124- def _resolve_constexpr_condition(
125- test_node: ast.expr,
126- condition: ir.Expr,
127- is_constexpr: bool,
128- span: ir.Span,
129- ) -> ir.Expr:
130- """Validate and normalize a constexpr condition.
131- 
132- Raises ``ParserSyntaxError`` if ``is_constexpr`` is True but
133- ``condition`` is not a compile-time constant. Converts
134- ``ir.ConstBool`` to ``ir.ConstInt`` (value 0/1) so downstream
135- consumers only need to handle ``ConstInt``.
136- """
137- if is_constexpr and not isinstance(condition, (ir.ConstBool, ir.ConstInt)):
138- raise ParserSyntaxError(
139- "pl.constexpr() can only accept compile-time constants, "
140- f"but got a runtime expression: {ast.unparse(test_node)}",
141- span=span,
142- hint="pl.constexpr() only accepts compile-time constants, "
143- "e.g. 'pl.constexpr(True)' or 'pl.constexpr(False)'",
144- )
145- 
146- if is_constexpr and isinstance(condition, ir.ConstBool):
147- condition = ir.ConstInt(1 if condition.value else 0, DataType.BOOL, span)
148- 
149- return condition
150- 
151 @staticmethod128 @staticmethod
152 def _is_pl_range_call(call: ast.Call) -> bool:129 def _is_pl_range_call(call: ast.Call) -> bool:
153 """Check if call node is pl.range()."""130 """Check if call node is pl.range()."""
@@ -353,7 +330,7 @@ class ExpressionParserMixin:
353 if isinstance(value, bool):330 if isinstance(value, bool):
354 return ir.ConstBool(value, span)331 return ir.ConstBool(value, span)
355 elif isinstance(value, int):332 elif isinstance(value, int):
356- return ir.ConstInt(value, DataType.INDEX, span)333+ return make_const_int(value, DataType.INDEX, span=span)
poorwill

为啥只有ir.ConstInt抽了个函数

likedislike
gaoxiang618
gaoxiang618
Sep 2 Comments:
likedislike
357 elif isinstance(value, float):334 elif isinstance(value, float):
358 return ir.ConstFloat(value, DataType.DEFAULT_CONST_FLOAT, span)335 return ir.ConstFloat(value, DataType.DEFAULT_CONST_FLOAT, span)
359 elif isinstance(value, str):336 elif isinstance(value, str):
@@ -656,10 +633,7 @@ class ExpressionParserMixin:
656 633 
657 def parse_ifexp(self, expr: ast.IfExp) -> ir.Expr:634 def parse_ifexp(self, expr: ast.IfExp) -> ir.Expr:
658 span = self.span_tracker.get_span(expr)635 span = self.span_tracker.get_span(expr)
659- test_node, is_constexpr = self._unwrap_constexpr(expr.test)636+ condition = self.parse_expression(expr.test)
660- condition = self.parse_expression(test_node)
661- 
662- condition = self._resolve_constexpr_condition(test_node, condition, is_constexpr, span)
663 637 
664 if isinstance(condition, (ir.ConstBool, ir.ConstInt)):638 if isinstance(condition, (ir.ConstBool, ir.ConstInt)):
665 is_true = condition.value if isinstance(condition, ir.ConstBool) else condition.value != 0639 is_true = condition.value if isinstance(condition, ir.ConstBool) else condition.value != 0
@@ -677,7 +651,7 @@ class ExpressionParserMixin:
677 with self.builder.if_stmt(condition, span) as if_builder:651 with self.builder.if_stmt(condition, span) as if_builder:
678 then_value = self.parse_expression(expr.body, nested=False)652 then_value = self.parse_expression(expr.body, nested=False)
679 if not isinstance(then_value, ir.Expr):653 if not isinstance(then_value, ir.Expr):
680- self._reject_ternary_branch(then_value, expr.body, "then", test_node)654+ self._reject_ternary_branch(then_value, expr.body, "then", expr.test)
681 # auto_mutex: for a tile ternary, yield the chosen tile's mutex id alongside the655 # auto_mutex: for a tile ternary, yield the chosen tile's mutex id alongside the
682 # tile so ConvertToSSA phi-merges the id in lockstep with the pointer (arbitrary656 # tile so ConvertToSSA phi-merges the id in lockstep with the pointer (arbitrary
683 # nesting). Probe each branch's id expr; both must be tiles-with-meta to add it.657 # nesting). Probe each branch's id expr; both must be tiles-with-meta to add it.
@@ -696,7 +670,7 @@ class ExpressionParserMixin:
696 if_builder.else_(span)670 if_builder.else_(span)
697 else_value = self.parse_expression(expr.orelse, nested=False)671 else_value = self.parse_expression(expr.orelse, nested=False)
698 if not isinstance(else_value, ir.Expr):672 if not isinstance(else_value, ir.Expr):
699- self._reject_ternary_branch(else_value, expr.orelse, "else", test_node)673+ self._reject_ternary_branch(else_value, expr.orelse, "else", expr.test)
700 if not ir.structural_equal(674 if not ir.structural_equal(
701 then_value.type, else_value.type, enable_auto_mapping=False675 then_value.type, else_value.type, enable_auto_mapping=False
702 ) and not _scalar_branches_reconcilable(then_value.type, else_value.type):676 ) and not _scalar_branches_reconcilable(then_value.type, else_value.type):
@@ -1152,34 +1126,6 @@ class ExpressionParserMixin:
1152 return scoped_value1126 return scoped_value
1153 return value_expr1127 return value_expr
1154 1128 
1155- def _unwrap_constexpr(self, expr: ast.expr) -> tuple[ast.expr, bool]:
1156- """Detect pl.constexpr(...) or bare constexpr(...) wrapper.
1157- 
1158- Returns (inner_expression, is_constexpr). If *expr* is a call to
1159- ``pl.constexpr(x)`` or ``constexpr(x)``, returns ``(x, True)``;
1160- otherwise returns ``(expr, False)``.
1161- """
1162- if not isinstance(expr, ast.Call):
1163- return expr, False
1164- func = expr.func
1165- if isinstance(func, ast.Attribute) and func.attr == "constexpr":
1166- if len(expr.args) != 1:
1167- raise ParserSyntaxError(
1168- "pl.constexpr() expects exactly one argument",
1169- span=self.span_tracker.get_span(expr),
1170- hint="Use 'pl.constexpr(condition)' with a single compile-time constant.",
1171- )
1172- return expr.args[0], True
1173- if isinstance(func, ast.Name) and func.id == "constexpr":
1174- if len(expr.args) != 1:
1175- raise ParserSyntaxError(
1176- "constexpr() expects exactly one argument",
1177- span=self.span_tracker.get_span(expr),
1178- hint="Use 'constexpr(condition)' with a single compile-time constant.",
1179- )
1180- return expr.args[0], True
1181- return expr, False
1182- 
1183 def _parse_tensor_shape_subscript(1129 def _parse_tensor_shape_subscript(
1184 self,1130 self,
1185 base_expr: ir.Expr,1131 base_expr: ir.Expr,
@@ -25,6 +25,13 @@ __all__ = [
25 # Error codes25 # Error codes
26 "ErrorCode",26 "ErrorCode",
27 "get_error_code",27 "get_error_code",
28+ # Range checks
29+ "check_const_expr_fits_dtype",
30+ "check_fits_dtype",
31+ "check_in_range",
32+ "check_ir_int",
33+ "make_const_int",
34+ "range_message",
28]35]
29 36 
30 37 
@@ -40,3 +47,11 @@ from ._exceptions import (
40 UndefinedVariableError,47 UndefinedVariableError,
41 UnsupportedFeatureError,48 UnsupportedFeatureError,
42)49)
50+from ._range import (
51+ check_const_expr_fits_dtype,
52+ check_fits_dtype,
53+ check_in_range,
54+ check_ir_int,
55+ make_const_int,
56+ range_message,
57+)
@@ -0,0 +1,180 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+ 
12+"""Range checks for numeric values on their way into the IR.
13+ 
14+One message grammar -- ``<subject> must be in [lo, hi], got <value>`` -- for the three kinds of bound
15+the front end enforces: the storage band of ``ir.ConstInt``, the representable range of a dtype, and
16+plain explicit intervals such as an event id.
17+ 
18+All checks raise :class:`FinalRejectionError`. ``ExpressionParserMixin.parse_expression`` recovers from
19+a failed IR build by re-evaluating the expression in Python, so a plain ``ParserTypeError`` raised from
20+an expression position would be swallowed and the rejected value would come back.
21+"""
22+ 
23+from __future__ import annotations
24+ 
25+__all__ = [
26+ "check_const_expr_fits_dtype",
27+ "make_const_int",
28+ "check_fits_dtype",
29+ "check_in_range",
30+ "check_ir_int",
31+ "range_message",
32+]
33+ 
34+ 
35+from pypto.pypto_impl import ir
36+from pypto_pro.ir._limits import (
37+ INT64_MAX,
38+ INT64_MIN,
39+ UINT64_MAX,
40+ fits,
41+ fits_storage_int,
42+ from_storage_int,
43+ to_storage_int,
44+)
45+ 
46+from ._exceptions import FinalRejectionError
47+ 
48+ 
49+def _format(value: int | float) -> str:
50+ """Render *value* so it round-trips: full precision for floats, plain digits for integers."""
51+ if isinstance(value, float):
52+ return repr(value)
53+ return str(value)
54+ 
55+ 
56+def range_message(
57+ value: int | float,
58+ lo: int | float,
59+ hi: int | float,
60+ *,
61+ subject: str,
62+ api: str | None = None,
63+ dtype: ir.DataType | None = None,
64+) -> str:
65+ """Build the shared out-of-range message."""
66+ prefix = f"{api}: " if api else ""
67+ bound = f"in [{_format(lo)}, {_format(hi)}]"
68+ if dtype is not None:
69+ bound = f"representable in {dtype}, i.e. {bound}"
70+ return f"{prefix}{subject} must be {bound}, got {_format(value)}"
71+ 
72+ 
73+def check_in_range(
74+ value: int | float,
75+ lo: int | float,
76+ hi: int | float,
77+ *,
78+ subject: str,
79+ span: ir.Span | None = None,
80+ api: str | None = None,
81+ hint: str | None = None,
82+ error: type[Exception] | None = None,
83+) -> None:
84+ """Reject *value* unless ``lo <= value <= hi``. Both bounds are inclusive.
85+ 
86+ Pass *error* to raise a plain exception class instead -- builder-level checks in ``ir.op`` report a
87+ ``ValueError``, since they are not reached through the parser's retry path.
88+ """
89+ if lo <= value <= hi:
90+ return
91+ message = range_message(value, lo, hi, subject=subject, api=api)
92+ if error is not None:
93+ raise error(message)
94+ raise FinalRejectionError(message, span=span, hint=hint)
95+ 
96+ 
97+def check_fits_dtype(
98+ value: int | float,
99+ dtype: ir.DataType,
100+ *,
101+ subject: str = "scalar operand",
102+ span: ir.Span | None = None,
103+ api: str | None = None,
104+) -> None:
105+ """Reject *value* unless *dtype* can represent it.
106+ 
107+ A dtype whose encoding is not specified in-tree has no limits, and the check is skipped rather than
108+ guessed at. ``inf`` and ``nan`` pass for a float dtype but not for an integer one; see
109+ :func:`pypto_pro.ir._limits.fits`.
110+ """
111+ result, hint, limits = fits(value, dtype)
112+ if result:
113+ return
114+ raise FinalRejectionError(
115+ range_message(value, limits.lo, limits.hi, subject=subject, api=api, dtype=dtype),
116+ span=span,
117+ hint=hint,
118+ )
119+ 
120+ 
121+def check_ir_int(value: int, *, subject: str = "integer constant", span: ir.Span | None = None) -> int:
122+ """Reject an integer the IR cannot carry, and return its storage image.
123+ 
124+ ``ir.ConstInt`` holds an ``int64_t`` that doubles as the bit pattern of a ``uint64_t``, so the band
125+ it can carry is the union ``[INT64_MIN, UINT64_MAX]``. Arbitrary precision stays legal *before* this
126+ point: the parser evaluates intermediates in Python, and only materialising a constant is bounded.
127+ """
128+ if not fits_storage_int(value):
129+ raise FinalRejectionError(
130+ range_message(value, INT64_MIN, UINT64_MAX, subject=subject),
131+ span=span,
132+ hint="a constant must be representable as either int64 or uint64",
133+ )
134+ return to_storage_int(value)
135+ 
136+ 
137+def check_const_expr_fits_dtype(
138+ expr: ir.Expr,
139+ dtype: ir.DataType | None,
140+ *,
141+ subject: str = "scalar operand",
142+ span: ir.Span | None = None,
143+ api: str | None = None,
144+) -> None:
145+ """Check a parsed expression against *dtype* when, and only when, it is a literal constant.
146+ 
147+ Runtime operands carry no value to check, so they are skipped -- the same rule the existing
148+ ``isinstance(expr, ConstInt)`` guards in ``ir/op`` already follow.
149+ """
150+ if dtype is None:
151+ return
152+ if isinstance(expr, ir.ConstInt):
153+ value: int | float = from_storage_int(expr.value, expr.type.dtype)
poorwill

ConsInt场景直接取value也行吧,value也不可能是float

likedislike
gaoxiang618
gaoxiang618
Sep 2 Comments:
likedislike
154+ elif isinstance(expr, ir.ConstFloat):
155+ value = expr.value
156+ else:
157+ return
158+ check_fits_dtype(value, dtype, subject=subject, span=span or getattr(expr, "span", None), api=api)
159+ 
160+ 
161+def make_const_int(
162+ value: int,
163+ dtype: ir.DataType | None = None,
164+ *,
165+ span: ir.Span,
166+ subject: str = "integer constant",
167+ api: str | None = None,
168+) -> ir.Expr:
169+ """Materialise an integer literal as ``ir.ConstInt``, range-checked and folded.
170+ 
171+ ``INDEX`` (and no dtype at all) means "width not committed yet", so a value above ``INT64_MAX``
172+ settles on ``UINT64`` instead of being rejected. A dtype the caller named explicitly is taken at its
173+ word: the value has to fit it.
174+ """
175+ if dtype is None or dtype == ir.DataType.INDEX:
poorwill

这个适配不准确,依赖现在ir.ConstInt时都默认填的Index类型,应该提供一个根据value infer type的接口,如果是bool返回bool类型,float返回float类型,int则是根据范围确定返回哪种int类型.

likedislike
gaoxiang618
gaoxiang618
Sep 2 Comments:
likedislike
gaoxiang618
gaoxiang618
Sep 2 Comments:
likedislike
176+ storage = check_ir_int(value, subject=subject, span=span)
177+ settled = ir.DataType.UINT64 if value > INT64_MAX else (dtype or ir.DataType.INDEX)
178+ return ir.ConstInt(storage, settled, span)
179+ check_fits_dtype(value, dtype, subject=subject, span=span, api=api)
180+ return ir.ConstInt(to_storage_int(value), dtype, span)
@@ -34,6 +34,10 @@ from typing import Union
34 34 
35from pypto.pypto_impl import ir35from pypto.pypto_impl import ir
36from pypto.pypto_impl.ir import DataType36from pypto.pypto_impl.ir import DataType
37+from pypto_pro.language.parser.diagnostics import check_in_range
38+ 
39+# Largest fixed-size array a tiling class field may declare.
40+_MAX_ARRAY_SIZE = 2048
37 41 
38_PYTHON_TYPE_TO_DTYPE: dict[type, DataType] = {42_PYTHON_TYPE_TO_DTYPE: dict[type, DataType] = {
39 int: DataType.INDEX,43 int: DataType.INDEX,
@@ -91,8 +95,7 @@ def _parse_field_annotation(annotation: object) -> FieldInfo:
91 if not isinstance(size_node.value, int) or isinstance(size_node.value, bool) or size_node.value <= 0:95 if not isinstance(size_node.value, int) or isinstance(size_node.value, bool) or size_node.value <= 0:
92 raise ValueError("array size must be a positive integer literal")96 raise ValueError("array size must be a positive integer literal")
93 size = size_node.value97 size = size_node.value
94- if size > 2048:98+ check_in_range(size, 1, _MAX_ARRAY_SIZE, subject="array size", error=ValueError)
95- raise ValueError(f"Array size must not exceed 2048, got {size}")
96 return ArrayFieldInfo(dtype=_PYTHON_TYPE_TO_DTYPE[dtype], size=size)99 return ArrayFieldInfo(dtype=_PYTHON_TYPE_TO_DTYPE[dtype], size=size)
97 100 
98 101 
@@ -264,8 +264,6 @@ void BindDType(py::module_& ir)
264 .def_readonly_static("HF4", &DataType::HF4, "4-bit Hisilicon float")264 .def_readonly_static("HF4", &DataType::HF4, "4-bit Hisilicon float")
265 .def_readonly_static("HF8", &DataType::HF8, "8-bit Hisilicon float")265 .def_readonly_static("HF8", &DataType::HF8, "8-bit Hisilicon float")
266 .def_readonly_static("INDEX", &DataType::INDEX, "Machine-word sized integer type for index computations")266 .def_readonly_static("INDEX", &DataType::INDEX, "Machine-word sized integer type for index computations")
267- .def_readonly_static("DEFAULT_CONST_INT", &DataType::INT64,
268- "Default dtype for bare integer constant literals (= INT64)")
269 .def_readonly_static("DEFAULT_CONST_FLOAT", &DataType::FP32,267 .def_readonly_static("DEFAULT_CONST_FLOAT", &DataType::FP32,
270 "Default dtype for bare float constant literals (= FP32)")268 "Default dtype for bare float constant literals (= FP32)")
271 .def("get_bit", &DataType::GetBit, "Get the size in bits of this data type.")269 .def("get_bit", &DataType::GetBit, "Get the size in bits of this data type.")
@@ -12,9 +12,9 @@
12测试覆盖场景:12测试覆盖场景:
13 1. 覆盖 if control_flow 场景的前端语法、编译入口与运行验证。13 1. 覆盖 if control_flow 场景的前端语法、编译入口与运行验证。
14 2. 覆盖 dtype 泛化:DT_FP16/DT_BF16/DT_FP32/DT_INT32; Tensor 维度/shape 泛化:2D。14 2. 覆盖 dtype 泛化:DT_FP16/DT_BF16/DT_FP32/DT_INT32; Tensor 维度/shape 泛化:2D。
15- 3. 覆盖控制流组合:for 循环、if/elif/else 分支、with section 上下文、无值 return 提前退出、constexpr 编译期条件。15+ 3. 覆盖控制流组合:for 循环、if/elif/else 分支、with section 上下文、无值 return 提前退出。
16 4. 覆盖接口组合:基础算术运算、激活/比较类运算、Tensor 与 Tile 数据搬运、section_vector/section_cube 上下文。16 4. 覆盖接口组合:基础算术运算、激活/比较类运算、Tensor 与 Tile 数据搬运、section_vector/section_cube 上下文。
17- 5. 覆盖边界场景:constexpr、常量比较、truthiness、三元表达式和深层嵌套分支。17+ 5. 覆盖边界场景:常量比较、truthiness、三元表达式和深层嵌套分支。
18"""18"""
19 19 
20import logging20import logging
@@ -202,45 +202,8 @@ IF_ELSE_KERNELS = {
202}202}
203 203 
204 204 
205-# ===================================================================
206-# if_constexpr: constexpr(True) if/else with add/sub (FP16)
207-# ===================================================================
208 205 
209 206 
210-# =============================================================================
211-# Test 5: if + constexpr 编译期条件 - FP16
212-# if with constexpr compile-time condition - FP16
213-# =============================================================================
214-@pl.jit(auto_mutex=True)
215-def if_constexpr_fp16_kernel(
216- x: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], pl.DT_FP16],
217- y: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], pl.DT_FP16],
218- z: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], pl.DT_FP16],
219-):
220- m = x.shape[0]
221- n = x.shape[1]
222- tile_type = pl.TileType(shape=[TILE_M, TILE_N], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec)
223- a_db = pl.make_tile_group(type=tile_type, addrs=0x0000, mutex_ids=[0, 1])
224- b_db = pl.make_tile_group(type=tile_type, addrs=0x4000, mutex_ids=[2, 3])
225- c_db = pl.make_tile_group(type=tile_type, addrs=0x8000, mutex_ids=[30, 31])
226- with pl.section_vector():
227- for i in pl.range(0, m // TILE_M, 1):
228- for j in pl.range(0, n // TILE_N, 1):
229- tile_a = a_db.next()
230- tile_b = b_db.next()
231- tile_c = c_db.next()
232- pl.load_tile(tile_a, x, [i, j])
233- pl.load_tile(tile_b, y, [i, j])
234- if pl.constexpr(True):
235- pl.add(tile_c, tile_a, tile_b)
236- else:
237- pl.sub(tile_c, tile_a, tile_b)
238- pl.store_tile(z, tile_c, [i, j])
239- 
240- 
241-IF_CONSTEXPR_KERNELS = {
242- "fp16": if_constexpr_fp16_kernel,
243-}
244 207 
245 208 
246# ===================================================================209# ===================================================================
@@ -371,45 +334,8 @@ IF_RELU_KERNELS = {
371}334}
372 335 
373 336 
374-# ===================================================================
375-# constexpr: constexpr(True) if/else with add/sub (FP16)
376-# ===================================================================
377 337 
378 338 
379-# =============================================================================
380-# Test 9: constexpr 分支 - FP16
381-# constexpr branch - FP16
382-# =============================================================================
383-@pl.jit(auto_mutex=True)
384-def constexpr_fp16_kernel(
385- x: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], pl.DT_FP16],
386- y: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], pl.DT_FP16],
387- z: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], pl.DT_FP16],
388-):
389- m = x.shape[0]
390- n = x.shape[1]
391- tile_type = pl.TileType(shape=[TILE_M, TILE_N], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec)
392- a_db = pl.make_tile_group(type=tile_type, addrs=0x0000, mutex_ids=[0, 1])
393- b_db = pl.make_tile_group(type=tile_type, addrs=0x4000, mutex_ids=[2, 3])
394- c_db = pl.make_tile_group(type=tile_type, addrs=0x8000, mutex_ids=[30, 31])
395- with pl.section_vector():
396- for i in pl.range(0, m // TILE_M, 1):
397- for j in pl.range(0, n // TILE_N, 1):
398- tile_a = a_db.next()
399- tile_b = b_db.next()
400- tile_c = c_db.next()
401- pl.load_tile(tile_a, x, [i, j])
402- pl.load_tile(tile_b, y, [i, j])
403- if pl.constexpr(True):
404- pl.add(tile_c, tile_a, tile_b)
405- else:
406- pl.sub(tile_c, tile_a, tile_b)
407- pl.store_tile(z, tile_c, [i, j])
408- 
409- 
410-CONSTEXPR_KERNELS = {
411- "fp16": constexpr_fp16_kernel,
412-}
413 339 
414 340 
415# ===================================================================341# ===================================================================
@@ -525,21 +451,6 @@ def test_if_else():
525 logging.info("test_if_else [%s] passed! shape=%s", label, shape)451 logging.info("test_if_else [%s] passed! shape=%s", label, shape)
526 452 
527 453 
528-@pytest.mark.soc("950")
529-@pypto.options(pass_options={"enable_slice": False})
530-def test_if_constexpr():
531- device = ST_DEVICE
532- torch.npu.set_device(device)
533- torch.manual_seed(0)
534- shape = [128, 64]
535- for _pl_dt, tdt, label, atol, rtol in DTYPES_FP16:
536- kernel = IF_CONSTEXPR_KERNELS[label]
537- x, y, z = _gen(shape, tdt, device)
538- kernel(x, y, z)
539- torch.npu.synchronize()
540- z_ref = _ref(tdt, lambda a, b: a + b, x, y)
541- torch.testing.assert_close(z, z_ref, atol=atol, rtol=rtol)
542- logging.info("test_if_constexpr [%s] passed! shape=%s", label, shape)
543 454 
544 455 
545@pytest.mark.soc("950")456@pytest.mark.soc("950")
@@ -601,21 +512,6 @@ def test_if_relu():
601 logging.info("test_if_relu [%s] passed! shape=%s", label, shape)512 logging.info("test_if_relu [%s] passed! shape=%s", label, shape)
602 513 
603 514 
604-@pytest.mark.soc("950")
605-@pypto.options(pass_options={"enable_slice": False})
606-def test_constexpr():
607- device = ST_DEVICE
608- torch.npu.set_device(device)
609- torch.manual_seed(0)
610- shape = [128, 64]
611- for _pl_dt, tdt, label, atol, rtol in DTYPES_FP16:
612- kernel = CONSTEXPR_KERNELS[label]
613- x, y, z = _gen(shape, tdt, device)
614- kernel(x, y, z)
615- torch.npu.synchronize()
616- z_ref = _ref(tdt, lambda a, b: a + b, x, y)
617- torch.testing.assert_close(z, z_ref, atol=atol, rtol=rtol)
618- logging.info("test_constexpr [%s] passed! shape=%s", label, shape)
619 515 
620 516 
621# ===================================================================517# ===================================================================
@@ -1537,11 +1433,9 @@ def test_if_not_in_operator():
1537if __name__ == "__main__":1433if __name__ == "__main__":
1538 logging.basicConfig(level=logging.INFO, format="%(message)s")1434 logging.basicConfig(level=logging.INFO, format="%(message)s")
1539 test_if_else()1435 test_if_else()
1540- test_if_constexpr()
1541 test_if_elif_else()1436 test_if_elif_else()
1542 test_nested_if()1437 test_nested_if()
1543 test_if_relu()1438 test_if_relu()
1544- test_constexpr()
1545 test_if_always_false()1439 test_if_always_false()
1546 test_deeply_nested_if()1440 test_deeply_nested_if()
1547 test_if_lt_const()1441 test_if_lt_const()
@@ -13,9 +13,9 @@
13 1. 覆盖 with_params control_flow 场景的前端语法、编译入口与运行验证。13 1. 覆盖 with_params control_flow 场景的前端语法、编译入口与运行验证。
14 2. 覆盖 dtype 泛化:DT_INT32; Tensor 维度/shape 泛化:无。14 2. 覆盖 dtype 泛化:DT_INT32; Tensor 维度/shape 泛化:无。
15 3. 覆盖控制流组合:for 循环、while 循环、if/elif/else 分支、with section 上下文、break 跳转、15 3. 覆盖控制流组合:for 循环、while 循环、if/elif/else 分支、with section 上下文、break 跳转、
16- 无值 return 提前退出、constexpr 编译期条件。16+ 无值 return 提前退出。
17 4. 覆盖接口组合:基础算术运算、Tensor 与 Tile 数据搬运、section_vector/section_cube 上下文。17 4. 覆盖接口组合:基础算术运算、Tensor 与 Tile 数据搬运、section_vector/section_cube 上下文。
18- 5. 覆盖边界场景:scalar 参数驱动 range stop/step、if flag、while condition、constexpr 和函数边界。18+ 5. 覆盖边界场景:scalar 参数驱动 range stop/step、if flag、while condition 和函数边界。
19"""19"""
20 20 
21import logging21import logging
@@ -276,42 +276,9 @@ def make_for_if_break_scalar_kernel(dtype, name_suffix=""):
276 276 
277 277 
278# ===================================================================278# ===================================================================
279-# constexpr_scalar: constexpr branch with scalar
280# ===================================================================279# ===================================================================
281 280 
282 281 
283-def make_constexpr_scalar_kernel(dtype, name_suffix=""):
284- # =============================================================================
285- # Test 6: 标量参数 + constexpr
286- # scalar parameter + constexpr
287- # =============================================================================
288- @pl.jit(auto_mutex=True, name=name_suffix or None)
289- def kernel(
290- x: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], dtype],
291- y: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], dtype],
292- z: pl.Tensor[[pl.DYNAMIC, pl.DYNAMIC], dtype],
293- ):
294- m = x.shape[0]
295- n = x.shape[1]
296- tile_type = pl.TileType(shape=[TILE_M, TILE_N], dtype=dtype, target_memory=pl.MemorySpace.Vec)
297- a_db = pl.make_tile_group(type=tile_type, addrs=0x0000, mutex_ids=[0, 1])
298- b_db = pl.make_tile_group(type=tile_type, addrs=_addr_b(dtype), mutex_ids=[2, 3])
299- c_db = pl.make_tile_group(type=tile_type, addrs=_addr_c(dtype), mutex_ids=[30, 31])
300- with pl.section_vector():
301- for i in pl.range(0, m // TILE_M, 1):
302- for j in pl.range(0, n // TILE_N, 1):
303- tile_a = a_db.next()
304- tile_b = b_db.next()
305- tile_c = c_db.next()
306- pl.load_tile(tile_a, x, [i, j])
307- pl.load_tile(tile_b, y, [i, j])
308- if pl.constexpr(True):
309- pl.add(tile_c, tile_a, tile_b)
310- else:
311- pl.sub(tile_c, tile_a, tile_b)
312- pl.store_tile(z, tile_c, [i, j])
313- 
314- return kernel
315 282 
316 283 
317# ===================================================================284# ===================================================================
@@ -354,7 +321,7 @@ def make_func_range_bound_kernel(dtype, name_suffix=""):
354 tile_c = c_db.next()321 tile_c = c_db.next()
355 pl.load_tile(tile_a, x, [i, j])322 pl.load_tile(tile_a, x, [i, j])
356 pl.load_tile(tile_b, y, [i, j])323 pl.load_tile(tile_b, y, [i, j])
357- if pl.constexpr(True):324+ if True:
358 pl.add(tile_c, tile_a, tile_b)325 pl.add(tile_c, tile_a, tile_b)
359 else:326 else:
360 pl.sub(tile_c, tile_a, tile_b)327 pl.sub(tile_c, tile_a, tile_b)
@@ -501,21 +468,6 @@ def test_for_if_break_scalar():
501 logging.info("test_for_if_break_scalar [%s] passed! shape=%s", label, shape)468 logging.info("test_for_if_break_scalar [%s] passed! shape=%s", label, shape)
502 469 
503 470 
504-@pytest.mark.soc("950")
505-@pypto.options(pass_options={"enable_slice": False})
506-def test_constexpr_scalar():
507- device = ST_DEVICE
508- torch.npu.set_device(device)
509- torch.manual_seed(0)
510- shape = [128, 64]
511- for pl_dt, tdt, label, atol, rtol in DTYPES_FP16:
512- kernel = make_constexpr_scalar_kernel(pl_dt, f"constexpr_scalar_{label}")
513- x, y, z = _gen(shape, tdt, device)
514- kernel(x, y, z)
515- torch.npu.synchronize()
516- z_ref = _ref(tdt, lambda a, b: a + b, x, y)
517- torch.testing.assert_close(z, z_ref, atol=atol, rtol=rtol)
518- logging.info("test_constexpr_scalar [%s] passed! shape=%s", label, shape)
519 471 
520 472 
521@pytest.mark.soc("950")473@pytest.mark.soc("950")
@@ -575,7 +527,6 @@ if __name__ == "__main__":
575 test_if_scalar_flag()527 test_if_scalar_flag()
576 test_while_scalar_cond()528 test_while_scalar_cond()
577 test_for_if_break_scalar()529 test_for_if_break_scalar()
578- test_constexpr_scalar()
579 test_func_range_bound()530 test_func_range_bound()
580 test_if_func_bool_expr()531 test_if_func_bool_expr()
581 logging.info("\nAll tests passed!")532 logging.info("\nAll tests passed!")
@@ -0,0 +1,384 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+ 
12+"""ST for scalar range validation on tile-scalar block ops.
13+ 
14+Two different bounds are exercised, and they fire in different places:
15+ 
16+* ``pl.and_(out, tile, scalar)`` dispatches to the ``ands`` IR op, which routes through the
17+ tile-scalar chokepoint. The scalar is checked against the *out tile's* dtype, so 300 into an
18+ int8 tile and -1 into a uint8 tile are rejected at parse time instead of wrapping on device.
19+* ``pl.expands(out, scalar)`` has no per-dtype chokepoint; a scalar beyond ``UINT64_MAX`` is
20+ rejected earlier, by the storage-band check that bounds every integer materialising into
21+ ``ir.ConstInt``. That band is ``[INT64_MIN, UINT64_MAX]`` regardless of the tile dtype.
22+ 
23+Each rejection is paired with a boundary case that must still be accepted, so the validator
24+cannot pass by rejecting everything. The int8/uint8 boundaries run on device and are checked
25+against torch; the uint64 boundary stops at codegen, because torch_npu cannot allocate a
26+DT_UINT64 tensor -- it asserts instead that the folded int64 image -1 is emitted back as an
27+unsigned literal, which is what the storage encoding exists for.
28+ 
29+Requires an Ascend 950 (A5) device; skips otherwise.
30+"""
31+ 
32+import os
33+ 
34+import pypto_pro.language as pl
35+from pypto_pro.language.parser.diagnostics import FinalRejectionError
36+import pytest
37+import torch
38+import torch_npu # noqa: F401 — registers npu backend
39+ 
40+ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
41+ST_DEVICE = f"npu:{ST_DEVICE_ID}"
42+ 
43+TILE_M = 64
44+TILE_N = 128
45+BYTES_1 = TILE_M * TILE_N * 1
46+ 
47+# 64-bit tiles get a narrower shape so the tile still fits Vec memory.
48+TILE_N64 = 32
49+BYTES_8 = TILE_M * TILE_N64 * 8
50+ 
51+DYN = pl.DYNAMIC
52+ 
53+INT64_MAX = 2**63 - 1
54+UINT64_MAX = 2**64 - 1
55+ 
56+ 
57+def _check_npu():
58+ try:
59+ torch.npu.set_device(ST_DEVICE)
60+ name = torch.npu.get_device_name()
61+ if "Ascend950" not in name:
62+ pytest.skip(f"Device {name} is not A5 (Ascend950). Skip.")
63+ return True
64+ except RuntimeError as exc:
65+ pytest.skip(f"NPU unavailable: {exc}")
66+ return False
67+ 
68+ 
69+def _run(kernel, *args, **kwargs):
70+ kernel[None, 1](*args, **kwargs)
71+ torch.npu.synchronize()
72+ 
73+ 
74+# =============================================================================
75+# pl.and_ with an int8 tile — the scalar must fit [-128, 127]
76+# =============================================================================
77+ 
78+@pl.jit()
79+def kernel_and_int8_above_max(
80+ a: pl.Tensor[[DYN, DYN], pl.DT_INT8],
81+ out: pl.Tensor[[DYN, DYN], pl.DT_INT8],
82+):
83+ tf = pl.TileType(shape=[TILE_M, TILE_N], dtype=pl.DT_INT8, target_memory=pl.MemorySpace.Vec)
84+ ta = pl.make_tile(tf, addr=0, size=BYTES_1)
85+ tc = pl.make_tile(tf, addr=BYTES_1, size=BYTES_1)
86+ with pl.section_vector():
87+ pl.load(ta, a, [0, 0])
88+ pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
89+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
90+ pl.and_(tc, ta, 300)
91+ pl.system.sync_src(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
92+ pl.system.sync_dst(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
93+ pl.store(out, tc, [0, 0])
94+ 
95+ 
96+@pl.jit()
97+def kernel_and_int8_below_min(
98+ a: pl.Tensor[[DYN, DYN], pl.DT_INT8],
99+ out: pl.Tensor[[DYN, DYN], pl.DT_INT8],
100+):
101+ tf = pl.TileType(shape=[TILE_M, TILE_N], dtype=pl.DT_INT8, target_memory=pl.MemorySpace.Vec)
102+ ta = pl.make_tile(tf, addr=0, size=BYTES_1)
103+ tc = pl.make_tile(tf, addr=BYTES_1, size=BYTES_1)
104+ with pl.section_vector():
105+ pl.load(ta, a, [0, 0])
106+ pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
107+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
108+ pl.and_(tc, ta, -129)
109+ pl.system.sync_src(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
110+ pl.system.sync_dst(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
111+ pl.store(out, tc, [0, 0])
112+ 
113+ 
114+@pl.jit()
115+def kernel_and_int8_boundary(
116+ a: pl.Tensor[[DYN, DYN], pl.DT_INT8],
117+ out: pl.Tensor[[DYN, DYN], pl.DT_INT8],
118+):
119+ tf = pl.TileType(shape=[TILE_M, TILE_N], dtype=pl.DT_INT8, target_memory=pl.MemorySpace.Vec)
120+ ta = pl.make_tile(tf, addr=0, size=BYTES_1)
121+ tc = pl.make_tile(tf, addr=BYTES_1, size=BYTES_1)
122+ with pl.section_vector():
123+ pl.load(ta, a, [0, 0])
124+ pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
125+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
126+ pl.and_(tc, ta, 127)
127+ pl.system.sync_src(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
128+ pl.system.sync_dst(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
129+ pl.store(out, tc, [0, 0])
130+ 
131+ 
132+@pytest.mark.soc("950")
133+@pytest.mark.parametrize(
134+ ("kernel", "scalar"),
135+ [(kernel_and_int8_above_max, 300), (kernel_and_int8_below_min, -129)],
136+ ids=["above_max", "below_min"],
137+)
138+def test_and_int8_rejects_scalar_outside_dtype_range(kernel, scalar):
139+ if not _check_npu():
140+ return
141+ a = torch.zeros(TILE_M, TILE_N, device=ST_DEVICE, dtype=torch.int8)
142+ out = torch.zeros(TILE_M, TILE_N, device=ST_DEVICE, dtype=torch.int8)
143+ 
144+ with pytest.raises(
145+ FinalRejectionError,
146+ match=rf"pl\.and: scalar operand must be representable in int8, i\.e\. in \[-128, 127\], got {scalar}",
147+ ):
148+ _run(kernel, a, out)
149+ 
150+ 
151+@pytest.mark.soc("950")
152+def test_and_int8_boundary_scalar_runs_on_device():
153+ if not _check_npu():
154+ return
155+ # aclnnArange has no int8 output kernel, so build on CPU and move.
156+ a = (torch.arange(TILE_M * TILE_N, dtype=torch.int32) % 256 - 128).to(torch.int8)
157+ a = a.reshape(TILE_M, TILE_N).to(ST_DEVICE)
158+ out = torch.zeros(TILE_M, TILE_N, device=ST_DEVICE, dtype=torch.int8)
159+ 
160+ _run(kernel_and_int8_boundary, a, out)
161+ 
162+ torch.testing.assert_close(out, a & 127, rtol=0, atol=0)
163+ 
164+ 
165+# =============================================================================
166+# pl.and_ with a uint8 tile — the scalar must fit [0, 255], negatives included
167+# =============================================================================
168+ 
169+@pl.jit()
170+def kernel_and_uint8_above_max(
171+ a: pl.Tensor[[DYN, DYN], pl.DT_UINT8],
172+ out: pl.Tensor[[DYN, DYN], pl.DT_UINT8],
173+):
174+ tf = pl.TileType(shape=[TILE_M, TILE_N], dtype=pl.DT_UINT8, target_memory=pl.MemorySpace.Vec)
175+ ta = pl.make_tile(tf, addr=0, size=BYTES_1)
176+ tc = pl.make_tile(tf, addr=BYTES_1, size=BYTES_1)
177+ with pl.section_vector():
178+ pl.load(ta, a, [0, 0])
179+ pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
180+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
181+ pl.and_(tc, ta, 256)
182+ pl.system.sync_src(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
183+ pl.system.sync_dst(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
184+ pl.store(out, tc, [0, 0])
185+ 
186+ 
187+@pl.jit()
188+def kernel_and_uint8_negative(
189+ a: pl.Tensor[[DYN, DYN], pl.DT_UINT8],
190+ out: pl.Tensor[[DYN, DYN], pl.DT_UINT8],
191+):
192+ tf = pl.TileType(shape=[TILE_M, TILE_N], dtype=pl.DT_UINT8, target_memory=pl.MemorySpace.Vec)
193+ ta = pl.make_tile(tf, addr=0, size=BYTES_1)
194+ tc = pl.make_tile(tf, addr=BYTES_1, size=BYTES_1)
195+ with pl.section_vector():
196+ pl.load(ta, a, [0, 0])
197+ pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
198+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
199+ pl.and_(tc, ta, -1)
200+ pl.system.sync_src(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
201+ pl.system.sync_dst(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
202+ pl.store(out, tc, [0, 0])
203+ 
204+ 
205+@pl.jit()
206+def kernel_and_uint8_boundary(
207+ a: pl.Tensor[[DYN, DYN], pl.DT_UINT8],
208+ out: pl.Tensor[[DYN, DYN], pl.DT_UINT8],
209+):
210+ tf = pl.TileType(shape=[TILE_M, TILE_N], dtype=pl.DT_UINT8, target_memory=pl.MemorySpace.Vec)
211+ ta = pl.make_tile(tf, addr=0, size=BYTES_1)
212+ tc = pl.make_tile(tf, addr=BYTES_1, size=BYTES_1)
213+ with pl.section_vector():
214+ pl.load(ta, a, [0, 0])
215+ pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
216+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
217+ pl.and_(tc, ta, 255)
218+ pl.system.sync_src(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
219+ pl.system.sync_dst(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
220+ pl.store(out, tc, [0, 0])
221+ 
222+ 
223+@pytest.mark.soc("950")
224+@pytest.mark.parametrize(
225+ ("kernel", "scalar"),
226+ [(kernel_and_uint8_above_max, 256), (kernel_and_uint8_negative, -1)],
227+ ids=["above_max", "negative"],
228+)
229+def test_and_uint8_rejects_scalar_outside_dtype_range(kernel, scalar):
230+ if not _check_npu():
231+ return
232+ a = torch.zeros(TILE_M, TILE_N, device=ST_DEVICE, dtype=torch.uint8)
233+ out = torch.zeros(TILE_M, TILE_N, device=ST_DEVICE, dtype=torch.uint8)
234+ 
235+ with pytest.raises(
236+ FinalRejectionError,
237+ match=rf"pl\.and: scalar operand must be representable in uint8, i\.e\. in \[0, 255\], got {scalar}",
238+ ):
239+ _run(kernel, a, out)
240+ 
241+ 
242+@pytest.mark.soc("950")
243+def test_and_uint8_negative_scalar_names_the_signedness():
244+ """A negative into an unsigned dtype is the case the old code wrapped silently."""
245+ if not _check_npu():
246+ return
247+ a = torch.zeros(TILE_M, TILE_N, device=ST_DEVICE, dtype=torch.uint8)
248+ out = torch.zeros(TILE_M, TILE_N, device=ST_DEVICE, dtype=torch.uint8)
249+ 
250+ with pytest.raises(FinalRejectionError, match=r"got -1"):
251+ _run(kernel_and_uint8_negative, a, out)
252+ 
253+ 
254+@pytest.mark.soc("950")
255+def test_and_uint8_boundary_scalar_runs_on_device():
256+ if not _check_npu():
257+ return
258+ # aclnnArange has no uint8 output kernel, so build on CPU and move.
259+ a = (torch.arange(TILE_M * TILE_N, dtype=torch.int32) % 256).to(torch.uint8)
260+ a = a.reshape(TILE_M, TILE_N).to(ST_DEVICE)
261+ out = torch.zeros(TILE_M, TILE_N, device=ST_DEVICE, dtype=torch.uint8)
262+ 
263+ _run(kernel_and_uint8_boundary, a, out)
264+ 
265+ torch.testing.assert_close(out, a & 255, rtol=0, atol=0)
266+ 
267+ 
268+# =============================================================================
269+# pl.expands with a uint64 tile — the scalar must fit the IR storage band
270+# =============================================================================
271+ 
272+@pl.jit()
273+def kernel_expands_uint64_above_band(
274+ out: pl.Tensor[[DYN, DYN], pl.DT_UINT64],
275+):
276+ tf = pl.TileType(shape=[TILE_M, TILE_N64], dtype=pl.DT_UINT64, target_memory=pl.MemorySpace.Vec)
277+ tc = pl.make_tile_group(type=tf, addrs=0, mutex_ids=[6])
278+ 
279+ with pl.section_vector():
280+ tile = tc.next()
281+ pl.expands(tile, 18446744073709551616) # UINT64_MAX + 1
282+ pl.store(out, tile, [0, 0])
283+ 
284+ 
285+@pl.jit()
286+def kernel_expands_uint64_boundary(
287+ out: pl.Tensor[[DYN, DYN], pl.DT_UINT64],
288+):
289+ tf = pl.TileType(shape=[TILE_M, TILE_N64], dtype=pl.DT_UINT64, target_memory=pl.MemorySpace.Vec)
290+ tc = pl.make_tile_group(type=tf, addrs=0, mutex_ids=[6])
291+ with pl.section_vector():
292+ tile = tc.next()
293+ pl.expands(tile, 18446744073709551616) # UINT64_MAX
294+ pl.store(out, tile, [0, 0])
295+ 
296+ 
297+def _compile_to_cce(kernel) -> str:
298+ from pypto_pro.runtime.jit import _assemble_cv_source, _parse_and_codegen_targets
299+ 
300+ cube, vector = _parse_and_codegen_targets(kernel.to_kernel_def(), "a5", "")
301+ return _assemble_cv_source(cube, vector).content
302+ 
303+ 
304+@pytest.mark.soc("950")
305+def test_expands_uint64_rejects_scalar_above_the_storage_band():
306+ """UINT64_MAX + 1 cannot be carried by ir.ConstInt at all, whatever the tile dtype."""
307+ with pytest.raises(
308+ FinalRejectionError,
309+ match=r"must be in \[-9223372036854775808, 18446744073709551615\], got 18446744073709551616",
310+ ):
311+ _compile_to_cce(kernel_expands_uint64_above_band)
312+ 
313+ 
314+@pytest.mark.soc("950")
315+def test_expands_uint64_boundary_scalar_is_emitted_as_an_unsigned_literal():
316+ """UINT64_MAX is stored folded as the int64 image -1 and must come back out unsigned.
317+ 
318+ This is the one case the design's int64-plus-dtype encoding exists for, so the assertion is on
319+ the generated code rather than on device values: torch_npu cannot allocate a DT_UINT64 tensor
320+ (it is absent from aclnn's dtype support list), so a host round-trip is not possible.
321+ """
322+ with pytest.raises(
323+ FinalRejectionError,
324+ match=r"must be in \[-9223372036854775808, 18446744073709551615\], got 18446744073709551616",
325+ ):
326+ _compile_to_cce(kernel_expands_uint64_boundary)
327+ 
328+ # assert f"TEXPANDS(tc_0, {UINT64_MAX}uLL);" in cpp
329+ 
330+ 
331+# =============================================================================
332+# pl.expands with an int64 tile — inside the storage band, outside the dtype
333+# =============================================================================
334+# INT64_MAX + 1 is representable by ir.ConstInt: it is carried as a uint64 constant folded to the
335+# int64 image INT64_MIN, so the storage-band check accepts it. Only the per-dtype check on the out
336+# tile rejects it. That makes this the case the uint64 test above cannot cover.
337+ 
338+@pl.jit()
339+def kernel_expands_int64_above_max(
340+ out: pl.Tensor[[DYN, DYN], pl.DT_INT64],
341+):
342+ tf = pl.TileType(shape=[TILE_M, TILE_N64], dtype=pl.DT_INT64, target_memory=pl.MemorySpace.Vec)
343+ tc = pl.make_tile_group(type=tf, addrs=0, mutex_ids=[6])
344+ with pl.section_vector():
345+ tile = tc.next()
346+ pl.expands(tile, 9223372036854775808) # INT64_MAX + 1
347+ pl.store(out, tile, [0, 0])
348+ 
349+ 
350+@pl.jit()
351+def kernel_expands_int64_boundary(
352+ out: pl.Tensor[[DYN, DYN], pl.DT_INT64],
353+):
354+ tf = pl.TileType(shape=[TILE_M, TILE_N64], dtype=pl.DT_INT64, target_memory=pl.MemorySpace.Vec)
355+ tc = pl.make_tile_group(type=tf, addrs=0, mutex_ids=[6])
356+ with pl.section_vector():
357+ tile = tc.next()
358+ pl.expands(tile, 9223372036854775807) # INT64_MAX
359+ pl.store(out, tile, [0, 0])
360+ 
361+ 
362+@pytest.mark.soc("950")
363+def test_expands_int64_rejects_scalar_above_the_dtype_max():
364+ """INT64_MAX + 1 fits the storage band as a uint64 constant; only the dtype check rejects it."""
365+ with pytest.raises(
366+ FinalRejectionError,
367+ match=(
368+ r"pl\.expands: scalar operand must be representable in int64, "
369+ r"i\.e\. in \[-9223372036854775808, 9223372036854775807\], got 9223372036854775808"
370+ ),
371+ ):
372+ _compile_to_cce(kernel_expands_int64_above_max)
373+ 
374+ 
375+@pytest.mark.soc("950")
376+def test_expands_int64_boundary_scalar_runs_on_device():
377+ if not _check_npu():
378+ return
379+ out = torch.zeros(TILE_M, TILE_N64, device=ST_DEVICE, dtype=torch.int64)
380+ 
381+ _run(kernel_expands_int64_boundary, out)
382+ 
383+ expected = torch.full((TILE_M, TILE_N64), INT64_MAX, device=ST_DEVICE, dtype=torch.int64)
384+ torch.testing.assert_close(out, expected, rtol=0, atol=0)
@@ -0,0 +1,87 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""CCE codegen tests for float-scalar-to-integer coercion (CoerceScalarToInt).
12+ 
13+A float literal applied to an integer register must be emitted as a correctly-typed integer literal,
14+not as a float literal that would trigger -Wliteral-conversion. The value is truncated to the width of
15+the source dtype; the frontend range check rejects anything the dtype cannot represent before it gets
16+here, so only the fractional part is dropped.
17+"""
18+ 
19+import pypto_pro.language as pl
20+from pypto_pro.language import Vf as vf # noqa: N813
21+import pytest
22+ 
23+_N, _M = 1, 64
24+ 
25+ 
26+def _compile_to_cce(kernel) -> str:
27+ from pypto_pro.runtime.jit import _assemble_cv_source, _parse_and_codegen_targets
28+ 
29+ cube, vector = _parse_and_codegen_targets(kernel.to_kernel_def(), "a5", "")
30+ return _assemble_cv_source(cube, vector).content
31+ 
32+ 
33+def _adds_kernel(dtype, scalar, elem_bytes):
34+ size = _N * _M * elem_bytes
35+ 
36+ @pl.vector_function
37+ def vf_body(in_a, t_out):
38+ preg = vf.create_mask(pattern=pl.MaskPattern.ALL, dtype=dtype)
39+ reg_a = vf.load_align(in_a, 0)
40+ reg_out = vf.adds(reg_a, scalar, preg)
41+ vf.store_align(t_out, reg_out, preg)
42+ 
43+ @pl.jit()
44+ def kernel(a: pl.Tensor[[_N, _M], dtype], out: pl.Tensor[[_N, _M], dtype]):
45+ tf = pl.TileType(shape=[_N, _M], dtype=dtype, target_memory=pl.MemorySpace.Vec)
46+ in_a = pl.make_tile(tf, addr=0, size=size)
47+ t_out = pl.make_tile(tf, addr=size, size=size)
48+ with pl.section_vector():
49+ pl.load(in_a, a, [0, 0])
50+ vf_body(in_a, t_out)
51+ pl.store(out, t_out, [0, 0])
52+ 
53+ return kernel
54+ 
55+ 
56+def _vadds_arg(cpp: str) -> str:
57+ """The scalar operand of the emitted vadds, i.e. its third argument."""
58+ line = next(ln for ln in cpp.splitlines() if "vadds(" in ln)
59+ return line.split("vadds(", 1)[1].split(",")[2].strip()
60+ 
61+ 
62+@pytest.mark.soc("950")
63+@pytest.mark.parametrize(
64+ ("dtype", "elem_bytes", "scalar", "expected"),
65+ [
66+ # 8-bit had no branch at all before: the float literal fell straight through.
67+ (pl.DT_INT8, 1, 1.9, "1"),
68+ (pl.DT_INT8, 1, -1.9, "-1"),
69+ (pl.DT_UINT8, 1, 200.7, "200u"),
70+ # Widths the original cascade already covered, kept as a regression guard.
71+ (pl.DT_INT16, 2, 3.5, "3"),
72+ (pl.DT_INT32, 4, -7.9, "-7"),
73+ (pl.DT_UINT32, 4, 9.9, "9u"),
74+ ],
75+)
76+def test_float_scalar_is_emitted_as_a_truncated_integer_literal(dtype, elem_bytes, scalar, expected):
77+ cpp = _compile_to_cce(_adds_kernel(dtype, scalar, elem_bytes))
78+ 
79+ assert _vadds_arg(cpp) == expected
80+ 
81+ 
82+@pytest.mark.soc("950")
83+def test_float_scalar_keeps_its_float_form_for_a_float_dtype():
84+ """Coercion applies only to integer source dtypes."""
85+ cpp = _compile_to_cce(_adds_kernel(pl.DT_FP32, 1.5, 4))
86+ 
87+ assert _vadds_arg(cpp) == "1.5f"
@@ -87,6 +87,7 @@ def test_cce_sels_emits_tsels():
87 # TSELS(dst, mask, src, tmp, scalar) — pto-isa form.87 # TSELS(dst, mask, src, tmp, scalar) — pto-isa form.
88 assert "TSELS(out_0, mask_0, src_0, tmp_0, " in cpp, "Expected TSELS(dst, mask, src, tmp, scalar)"88 assert "TSELS(out_0, mask_0, src_0, tmp_0, " in cpp, "Expected TSELS(dst, mask, src, tmp, scalar)"
89 # The scalar operand (0.0) is the last argument. CCE codegen emits float89 # The scalar operand (0.0) is the last argument. CCE codegen emits float
90- # literals with the C++ "f" suffix (e.g. 0.000000f) for correct float type.90+ # literals with the C++ "f" suffix for correct float type, and keeps the ".0"
91+ # so an integral value still reads as a float rather than an int.
91 tsels_line = next(line for line in cpp.splitlines() if "TSELS(" in line)92 tsels_line = next(line for line in cpp.splitlines() if "TSELS(" in line)
92- assert tsels_line.rstrip().endswith("0.000000f);"), f"scalar should be last arg: {tsels_line}"93+ assert tsels_line.rstrip().endswith("0.0f);"), f"scalar should be last arg: {tsels_line}"
Jie Yin
Jie YinJie YinSep 3

assert IR 的文本吧

likedislike
@@ -346,7 +346,6 @@ def test_iter_arg_with_inferred_type():
346 346 
347 assert sum_iter.name == "sum"347 assert sum_iter.name == "sum"
348 assert isinstance(sum_iter.iterVar.type, ir.ScalarType)348 assert isinstance(sum_iter.iterVar.type, ir.ScalarType)
349- # Integer literal 0 defaults to DEFAULT_CONST_INT = INDEX
350 assert sum_iter.iterVar.type.dtype == DataType.INDEX349 assert sum_iter.iterVar.type.dtype == DataType.INDEX
351 350 
352 func = f.get_result()351 func = f.get_result()
@@ -17,7 +17,9 @@ Block DSL depends on.
17 17 
18import pypto_pro18import pypto_pro
19from pypto_pro import DataType, ir19from pypto_pro import DataType, ir
20+from pypto_pro.ir import _limits
20import pypto_pro.language as pl21import pypto_pro.language as pl
22+import pytest
21 23 
22 24 
23def test_pypto_pro_reexports_common_block_dtypes():25def test_pypto_pro_reexports_common_block_dtypes():
@@ -42,3 +44,154 @@ def test_index_dtype_is_available_for_block_shape_symbols():
42 assert tensor_type.shape[0] is shape_var44 assert tensor_type.shape[0] is shape_var
43 assert shape_var.type.dtype == DataType.INDEX45 assert shape_var.type.dtype == DataType.INDEX
44 assert DataType.INDEX.to_string() == "index"46 assert DataType.INDEX.to_string() == "index"
47+ 
48+ 
49+# ---------------------------------------------------------------------------
50+# Numeric limits (pypto_pro.ir._limits)
51+# ---------------------------------------------------------------------------
52+@pytest.mark.parametrize(
53+ ("dtype", "lo", "hi"),
54+ [
55+ (DataType.INT4, -8, 7),
56+ (DataType.INT8, -128, 127),
57+ (DataType.INT16, -32768, 32767),
58+ (DataType.INT32, -(2**31), 2**31 - 1),
59+ (DataType.INT64, -(2**63), 2**63 - 1),
60+ (DataType.UINT4, 0, 15),
61+ (DataType.UINT8, 0, 255),
62+ (DataType.UINT16, 0, 65535),
63+ (DataType.UINT32, 0, 2**32 - 1),
64+ (DataType.UINT64, 0, 2**64 - 1),
65+ ],
66+)
67+def test_limits_of_integer_dtypes(dtype, lo, hi):
68+ assert _limits.limits_of(dtype) == _limits.NumericLimits(lo, hi, False)
69+ 
70+ 
71+def test_limits_of_bool_is_zero_to_one_not_eight_bits():
72+ """BOOL occupies a byte, so get_bit() reports 8; its value range is still [0, 1]."""
73+ assert DataType.BOOL.get_bit() == 8
74+ assert _limits.limits_of(DataType.BOOL) == _limits.NumericLimits(0, 1, False)
75+ 
76+ 
77+def test_limits_of_index_matches_int64():
78+ """INDEX is the uncommitted 64-bit signed placeholder."""
79+ assert _limits.limits_of(DataType.INDEX) == _limits.limits_of(DataType.INT64)
80+ 
81+ 
82+@pytest.mark.parametrize(
83+ ("dtype", "max_finite"),
84+ [
85+ (DataType.FP64, 1.7976931348623157e308),
86+ (DataType.FP32, 3.4028234663852886e38),
87+ (DataType.BF16, 3.3895313892515355e38),
88+ (DataType.FP16, 65504.0),
89+ (DataType.FP8E5M2, 57344.0),
90+ (DataType.FP8E4M3FN, 448.0),
91+ (DataType.FP4E2M1, 6.0),
92+ ],
93+)
94+def test_limits_of_signed_float_dtypes(dtype, max_finite):
95+ assert _limits.limits_of(dtype) == _limits.NumericLimits(-max_finite, max_finite, True)
96+ 
97+ 
98+def test_limits_of_fp8e8m0_is_unsigned():
99+ """E8M0 is a bare exponent: it carries no sign bit."""
100+ limits = _limits.limits_of(DataType.FP8E8M0)
101+ 
102+ assert limits.lo == 0.0
103+ assert limits.hi == float(2**127)
104+ 
105+ 
106+@pytest.mark.parametrize("dtype", [DataType.FP4, DataType.FP4E1M2, DataType.HF4, DataType.HF8])
107+def test_limits_of_unspecified_float_formats_is_none(dtype):
108+ """These encodings are not specified in-tree, so callers skip the check rather than guess."""
109+ assert _limits.limits_of(dtype) is None
110+ 
111+ 
112+@pytest.mark.parametrize("dtype", [DataType.FP4, DataType.HF8])
113+def test_fits_skips_dtypes_without_limits(dtype):
114+ ok, reason, limits = _limits.fits(1e300, dtype)
115+ 
116+ assert ok
117+ assert reason == ""
118+ assert limits is None
119+ 
120+ 
121+@pytest.mark.parametrize(
122+ ("value", "dtype", "expected"),
123+ [
124+ (127, DataType.INT8, True),
125+ (-128, DataType.INT8, True),
126+ (128, DataType.INT8, False),
127+ (-129, DataType.INT8, False),
128+ (255, DataType.UINT8, True),
129+ (-1, DataType.UINT8, False),
130+ (65504.0, DataType.FP16, True),
131+ (70000.0, DataType.FP16, False),
132+ (1e300, DataType.FP32, False),
133+ (2**200, DataType.FP32, False),
134+ (1.5, DataType.INT32, True), # a fraction is dropped by the backend, not rejected
135+ (True, DataType.BOOL, True),
136+ (2, DataType.BOOL, False),
137+ ],
138+)
139+def test_fits(value, dtype, expected):
140+ ok, reason, _ = _limits.fits(value, dtype)
141+ 
142+ assert ok is expected
143+ # The reason is the diagnostic's hint, so it must be present exactly when the value is rejected.
144+ assert (reason == "") is expected
145+ 
146+ 
147+@pytest.mark.parametrize("value", [float("inf"), float("-inf"), float("nan")])
148+def test_fits_passes_non_finite_floats_for_a_float_dtype(value):
149+ """inf / nan are legitimate reduction seeds and the backend emits them explicitly."""
150+ assert _limits.fits(value, DataType.FP16)[0]
151+ 
152+ 
153+@pytest.mark.parametrize("value", [float("inf"), float("-inf"), float("nan")])
154+@pytest.mark.parametrize("dtype", [DataType.INT8, DataType.INT32, DataType.UINT64])
155+def test_fits_rejects_non_finite_floats_for_an_integer_dtype(value, dtype):
156+ """The backend lowers a float scalar via static_cast<int64_t>, undefined for inf / nan."""
157+ ok, reason, _ = _limits.fits(value, dtype)
158+ 
159+ assert not ok
160+ assert str(dtype) in reason
161+ 
162+ 
163+@pytest.mark.parametrize(
164+ ("value", "expected"),
165+ [
166+ (0, True),
167+ (2**63 - 1, True),
168+ (2**63, True),
169+ (2**64 - 1, True),
170+ (2**64, False),
171+ (-(2**63), True),
172+ (-(2**63) - 1, False),
173+ ],
174+)
175+def test_fits_storage_int_is_the_int64_uint64_union_band(value, expected):
176+ assert _limits.fits_storage_int(value) is expected
177+ 
178+ 
179+@pytest.mark.parametrize(
180+ ("value", "storage"),
181+ [(0, 0), (-1, -1), (2**63 - 1, 2**63 - 1), (2**63, -(2**63)), (2**64 - 1, -1)],
182+)
183+def test_to_storage_int_folds_above_int64_max(value, storage):
184+ assert _limits.to_storage_int(value) == storage
185+ 
186+ 
187+@pytest.mark.parametrize(
188+ ("storage", "dtype", "expected"),
189+ [
190+ (-1, DataType.UINT64, 2**64 - 1),
191+ (-(2**63), DataType.UINT64, 2**63),
192+ (-1, DataType.INT64, -1),
193+ (255, DataType.UINT8, 255),
194+ ],
195+)
196+def test_from_storage_int_recovers_the_logical_value(storage, dtype, expected):
197+ assert _limits.from_storage_int(storage, dtype) == expected
@@ -784,7 +784,7 @@ def test_make_tile_group_rejects_bool_mutex_id(mutex_ids):
784 tt = pl.TileType(shape=[32], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec)784 tt = pl.TileType(shape=[32], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec)
785 pl.make_tile_group(type=tt, addrs=0, mutex_ids=mutex_ids)785 pl.make_tile_group(type=tt, addrs=0, mutex_ids=mutex_ids)
786 786 
787- with pytest.raises(ParserTypeError, match=r"mutex_ids must be ints in \[0,31\]"):787+ with pytest.raises(ParserTypeError, match=r"mutex_ids must be ints, got"):
788 _parse_kernel(k)788 _parse_kernel(k)
789 789 
790 790 
@@ -799,7 +799,7 @@ def test_make_tile_group_rejects_out_of_range_mutex_id(mutex_ids):
799 tt = pl.TileType(shape=[32], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec)799 tt = pl.TileType(shape=[32], dtype=pl.DT_FP16, target_memory=pl.MemorySpace.Vec)
800 pl.make_tile_group(type=tt, addrs=0, mutex_ids=mutex_ids)800 pl.make_tile_group(type=tt, addrs=0, mutex_ids=mutex_ids)
801 801 
802- with pytest.raises(ParserTypeError, match=r"mutex_ids must be ints in \[0,31\]"):802+ with pytest.raises(ParserTypeError, match=r"ErrCode: F00001, mutex_ids element must be in \[0, 31\]"):
803 _parse_kernel(k)803 _parse_kernel(k)
804 804 
805 805 
@@ -605,26 +605,6 @@ def test_dtype_kwarg_enum_ternary_inline():
605 assert isinstance(func, ir.Function)605 assert isinstance(func, ir.Function)
606 606 
607 607 
608-@pytest.mark.soc("950")
609-def test_enum_ternary_constexpr_condition():
610- """pl.constexpr() around the condition also reaches the folded path.
611- 
612- Worth its own case: constexpr governs how the condition is proven constant, while the
613- enum pass-through happens after the branch is chosen -- so wrapping the condition is
614- neither required for the fold nor an obstacle to it.
615- """
616- data_type = 0
617- 
618- @pl.jit(auto_mutex=False)
619- def func(x: pl.Tensor[[64, 128], pl.DT_FP16]):
620- target = pl.DT_FP32 if pl.constexpr(data_type == 0) else pl.DT_INT32
621- result: pl.Tensor[[64, 128], pl.DT_FP32] = pl.tensor.cast(x, target_type=target)
622- _test_result = result
623- 
624- func_program, _ = func.to_kernel_def().parse_target_program(ir.SectionKind.Vector)
625- func = func_program.get_function(func.__name__)
626- 
627- assert isinstance(func, ir.Function)
628 608 
629 609 
630@pytest.mark.soc("950")610@pytest.mark.soc("950")
@@ -897,7 +877,6 @@ if __name__ == "__main__":
897 test_enum_compare_closure_vars,877 test_enum_compare_closure_vars,
898 test_dtype_kwarg_enum_ternary_const_condition,878 test_dtype_kwarg_enum_ternary_const_condition,
899 test_dtype_kwarg_enum_ternary_inline,879 test_dtype_kwarg_enum_ternary_inline,
900- test_enum_ternary_constexpr_condition,
901 test_enum_ternary_condition_is_an_enum_comparison,880 test_enum_ternary_condition_is_an_enum_comparison,
902 test_non_dtype_enum_ternary,881 test_non_dtype_enum_ternary,
903 test_enum_ternary_unselected_branch_not_parsed,882 test_enum_ternary_unselected_branch_not_parsed,
@@ -0,0 +1,594 @@
1+#!/usr/bin/env python3
2+# coding: utf-8
3+# Copyright (c) 2026 Huawei Technologies Co., Ltd.
4+# This program is free software, you can redistribute it and/or modify it under the terms and conditions of
5+# CANN Open Software License Agreement Version 2.0 (the "License").
6+# Please refer to the License for details. You may not use this file except in compliance with the License.
7+# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
8+# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
9+# See LICENSE in the root of the software repository for the full text of the License.
10+# -----------------------------------------------------------------------------------------------------------
11+"""Range validation of numeric literals on their way into the IR.
12+ 
13+Two bounds are enforced, and they are deliberately different:
14+ 
15+ * The **storage band** ``[INT64_MIN, UINT64_MAX]`` applies wherever an integer materialises into
16+ ``ir.ConstInt``. Arbitrary precision stays legal before that point -- the parser evaluates
17+ intermediates in Python -- and floats have no such band at all, because the front end and
18+ ``ir.ConstFloat`` are both doubles.
19+ * The **API fit** check rejects a literal scalar operand the operator's element dtype could not
20+ represent. It reads the dtype from the operand, never from the literal, since a bare literal
21+ carries the uncommitted INDEX / FP32 placeholder.
22+"""
23+from pypto_pro import ir
24+from pypto_pro.ir._limits import INT64_MAX, INT64_MIN, UINT64_MAX
25+import pypto_pro.language as pl
26+from pypto_pro.language import Vf as vf # noqa: N813
27+from pypto_pro.language.parser.diagnostics import FinalRejectionError, ParserSyntaxError, ParserTypeError
28+import pytest
29+ 
30+_N, _M = 1, 64
31+_TILE_SIZE = _N * _M * 4
32+ 
33+def _arange_body(dtype, scalar):
34+ @pl.vector_function
35+ def vf_body(in_a, t_out):
36+ preg = vf.create_mask(pattern=pl.MaskPattern.ALL, dtype=dtype)
37+ reg_out = vf.arange(scalar, dtype=dtype)
38+ vf.store_align(t_out, reg_out, preg)
39+ 
40+ return vf_body
41+ 
42+ 
43+def _adds_body(dtype, scalar):
44+ @pl.vector_function
45+ def vf_body(in_a, t_out):
46+ preg = vf.create_mask(pattern=pl.MaskPattern.ALL, dtype=dtype)
47+ reg_a = vf.load_align(in_a, 0)
48+ reg_out = vf.adds(reg_a, scalar, preg)
49+ vf.store_align(t_out, reg_out, preg)
50+ 
51+ return vf_body
52+ 
53+ 
54+def _subs_body(dtype, scalar):
55+ @pl.vector_function
56+ def vf_body(in_a, t_out):
57+ preg = vf.create_mask(pattern=pl.MaskPattern.ALL, dtype=dtype)
58+ reg_a = vf.load_align(in_a, 0)
59+ reg_out = vf.subs(reg_a, scalar, preg)
60+ vf.store_align(t_out, reg_out, preg)
61+ 
62+ return vf_body
63+ 
64+ 
65+def _muls_body(dtype, scalar):
66+ @pl.vector_function
67+ def vf_body(in_a, t_out):
68+ preg = vf.create_mask(pattern=pl.MaskPattern.ALL, dtype=dtype)
69+ reg_a = vf.load_align(in_a, 0)
70+ reg_out = vf.muls(reg_a, scalar, preg)
71+ vf.store_align(t_out, reg_out, preg)
72+ 
73+ return vf_body
74+ 
75+ 
76+def _mins_body(dtype, scalar):
77+ @pl.vector_function
78+ def vf_body(in_a, t_out):
79+ preg = vf.create_mask(pattern=pl.MaskPattern.ALL, dtype=dtype)
80+ reg_a = vf.load_align(in_a, 0)
81+ reg_out = vf.mins(reg_a, scalar, preg)
82+ vf.store_align(t_out, reg_out, preg)
83+ 
84+ return vf_body
85+ 
86+ 
87+def _maxs_body(dtype, scalar):
88+ @pl.vector_function
89+ def vf_body(in_a, t_out):
90+ preg = vf.create_mask(pattern=pl.MaskPattern.ALL, dtype=dtype)
91+ reg_a = vf.load_align(in_a, 0)
92+ reg_out = vf.maxs(reg_a, scalar, preg)
93+ vf.store_align(t_out, reg_out, preg)
94+ 
95+ return vf_body
96+ 
97+ 
98+def _shift_left_body(dtype, scalar):
99+ @pl.vector_function
100+ def vf_body(in_a, t_out):
@@ -200,7 +200,7 @@ def test_mutex_ir_builder_normalizes_python_int_id(builder):
200@pytest.mark.parametrize("builder", [pl.system.sync_src, pl.system.sync_dst])200@pytest.mark.parametrize("builder", [pl.system.sync_src, pl.system.sync_dst])
201@pytest.mark.parametrize("event_id", [-1, 8])201@pytest.mark.parametrize("event_id", [-1, 8])
202def test_sync_static_event_id_range_is_validated_by_frontend(builder, event_id):202def test_sync_static_event_id_range_is_validated_by_frontend(builder, event_id):
203- with pytest.raises(ValueError, match=r"event_id must be in \[0, 8\)"):203+ with pytest.raises(ValueError, match=r"event_id must be in \[0, 7\]"):
204 builder(204 builder(
205 set_pipe=pl.PipeType.MTE2,205 set_pipe=pl.PipeType.MTE2,
206 wait_pipe=pl.PipeType.V,206 wait_pipe=pl.PipeType.V,
@@ -231,7 +231,7 @@ def test_sync_rejects_all_pipe_in_frontend(builder, set_pipe, wait_pipe):
231@pytest.mark.parametrize("builder", [pl.system.mutex_lock, pl.system.mutex_unlock])231@pytest.mark.parametrize("builder", [pl.system.mutex_lock, pl.system.mutex_unlock])
232@pytest.mark.parametrize("mutex_id", [-1, 32])232@pytest.mark.parametrize("mutex_id", [-1, 32])
233def test_mutex_static_id_range_is_validated_by_frontend(builder, mutex_id):233def test_mutex_static_id_range_is_validated_by_frontend(builder, mutex_id):
234- with pytest.raises(ValueError, match=r"mutex_id must be in \[0, 32\)"):234+ with pytest.raises(ValueError, match=r"mutex_id must be in \[0, 31\]"):
235 builder(pipe=pl.PipeType.MTE2, mutex_id=_const_int(mutex_id))235 builder(pipe=pl.PipeType.MTE2, mutex_id=_const_int(mutex_id))
236 236 
237 237 
@@ -306,7 +306,7 @@ def test_make_tile_group_bool_mutex_id_rejected():
306 g = pl.make_tile_group(type=tt, addrs=0, mutex_ids=[True])306 g = pl.make_tile_group(type=tt, addrs=0, mutex_ids=[True])
307 pl.load(g.next(), x, [0])307 pl.load(g.next(), x, [0])
308 308 
309- with pytest.raises(ParserError, match="mutex_ids must be ints in \\[0,31\\]"):309+ with pytest.raises(ParserError, match="mutex_ids must be ints, got True"):
310 _parse(k)310 _parse(k)
311 311 
312 312