Merged
feat(pypto_pro): Support pypto_pro SIMT #5341
wuzhongxinAdd on Aug 7
feat(pypto_pro): Support pypto_pro SIMT #5341
Merged
wuzhongxinAdd on Aug 7
Total: 57 files changed+4022-536
@@ -9,12 +9,16 @@
9 */9 */
10 10 
11#pragma once11#pragma once
12+#include <algorithm>
13+#include <any>
14+#include <cstdint>
12#include <memory>15#include <memory>
13#include <string>16#include <string>
14#include <tuple>17#include <tuple>
15#include <utility>18#include <utility>
16#include <vector>19#include <vector>
17 20 
21+#include "core/any_cast.h"
18#include "ir/core.h"22#include "ir/core.h"
19#include "ir/expr.h"23#include "ir/expr.h"
20#include "ir/reflection/field_traits.h"24#include "ir/reflection/field_traits.h"
@@ -24,6 +28,8 @@
24namespace pypto {28namespace pypto {
25namespace ir {29namespace ir {
26 30 
31+inline constexpr char kMaxThreadsAttr[] = "max_threads";
32+ 
27/**33/**
28 * \brief Function type classification34 * \brief Function type classification
29 *35 *
@@ -31,18 +37,24 @@ namespace ir {
31 * - Opaque: Unspecified (default)37 * - Opaque: Unspecified (default)
32 * - Orchestration: Runs on host/AICPU for control flow and dependency analysis38 * - Orchestration: Runs on host/AICPU for control flow and dependency analysis
33 * - InCore: Sub-graph on specific AICore39 * - InCore: Sub-graph on specific AICore
40+ * - Helper: Scalar helper callable from a kernel
41+ * - SimtVF: A5 SIMT vector
42+ * function launched from an AIV kernel
43+ * - SimtCallee: A5 SIMT helper callable from a SimtVF or another SimtCallee
34 */44 */
35enum class FunctionType : uint8_t {45enum class FunctionType : uint8_t {
36 OPAQUE = 0, ///< Default: unspecified function type46 OPAQUE = 0, ///< Default: unspecified function type
37 ORCHESTRATION = 1, ///< Host/AICPU control and coordination47 ORCHESTRATION = 1, ///< Host/AICPU control and coordination
38 IN_CORE = 2, ///< AICore sub-graph execution48 IN_CORE = 2, ///< AICore sub-graph execution
39- HELPER = 3 ///< Scalar helper function callable from kernels49+ HELPER = 3, ///< Scalar helper function callable from kernels
50+ SIMT_VF = 4, ///< A5 SIMT vector function launched from an AIV kernel
51+ SIMT_CALLEE = 5 ///< A5 SIMT helper callable from SIMT functions
40};52};
41 53 
42/**54/**
43 * \brief Convert FunctionType to string55 * \brief Convert FunctionType to string
44 * \param type The function type56 * \param type The function type
45- * \return String representation ("Opaque", "Orchestration", or "InCore")57+ * \return String representation
46 */58 */
47inline std::string FunctionTypeToString(FunctionType type)59inline std::string FunctionTypeToString(FunctionType type)
48{60{
@@ -55,6 +67,10 @@ inline std::string FunctionTypeToString(FunctionType type)
55 return "InCore";67 return "InCore";
56 case FunctionType::HELPER:68 case FunctionType::HELPER:
57 return "Helper";69 return "Helper";
70+ case FunctionType::SIMT_VF:
71+ return "SimtVF";
72+ case FunctionType::SIMT_CALLEE:
73+ return "SimtCallee";
58 default:74 default:
59 return "Unknown";75 return "Unknown";
60 }76 }
@@ -76,6 +92,10 @@ inline FunctionType StringToFunctionType(const std::string& str)
76 return FunctionType::IN_CORE;92 return FunctionType::IN_CORE;
77 } else if (str == "Helper") {93 } else if (str == "Helper") {
78 return FunctionType::HELPER;94 return FunctionType::HELPER;
95+ } else if (str == "SimtVF") {
96+ return FunctionType::SIMT_VF;
97+ } else if (str == "SimtCallee") {
98+ return FunctionType::SIMT_CALLEE;
79 } else {99 } else {
80 throw std::invalid_argument("Unknown FunctionType: " + str);100 throw std::invalid_argument("Unknown FunctionType: " + str);
81 }101 }
@@ -105,13 +125,17 @@ public:
105 * \param body Function body statement (use SeqStmts for multiple statements)125 * \param body Function body statement (use SeqStmts for multiple statements)
106 * \param span Source location126 * \param span Source location
107 * \param type Function type (default: Opaque)127 * \param type Function type (default: Opaque)
128+ * \param entry Whether this is the program entry function
129+ * \param attrs Function attributes
108 */130 */
109 Function(std::string name, std::vector<VarPtr> params, std::vector<TypePtr> returnTypes, StmtPtr body, Span span,131 Function(std::string name, std::vector<VarPtr> params, std::vector<TypePtr> returnTypes, StmtPtr body, Span span,
110- FunctionType type = FunctionType::OPAQUE, bool entry = false)132+ FunctionType type = FunctionType::OPAQUE, bool entry = false,
133+ std::vector<std::pair<std::string, std::any>> attrs = {})
111 : IRNode(std::move(span)),134 : IRNode(std::move(span)),
112 name_(std::move(name)),135 name_(std::move(name)),
113 funcType_(type),136 funcType_(type),
114 entry_(entry),137 entry_(entry),
138+ attrs_(std::move(attrs)),
115 params_(std::move(params)),139 params_(std::move(params)),
116 returnTypes_(std::move(returnTypes)),140 returnTypes_(std::move(returnTypes)),
117 body_(SeqStmts::Wrap(body, span))141 body_(SeqStmts::Wrap(body, span))
@@ -125,8 +149,8 @@ public:
125 /**149 /**
126 * \brief Get field descriptors for reflection-based visitation150 * \brief Get field descriptors for reflection-based visitation
127 *151 *
128- * \return Tuple of field descriptors (params as DEF field, func_type, return_types and body as USUAL152+ * \return Tuple of field descriptors (params as DEF field, func_type, entry, attrs, return_types and body
129- * fields, name as an IGNORE field)153+ * as USUAL fields, name as an IGNORE field)
130 */154 */
131 static constexpr auto GetFieldDescriptors()155 static constexpr auto GetFieldDescriptors()
132 {156 {
@@ -134,18 +158,37 @@ public:
134 std::make_tuple(reflection::DefField(&Function::params_, "params"),158 std::make_tuple(reflection::DefField(&Function::params_, "params"),
135 reflection::UsualField(&Function::funcType_, "func_type"),159 reflection::UsualField(&Function::funcType_, "func_type"),
136 reflection::UsualField(&Function::entry_, "entry"),160 reflection::UsualField(&Function::entry_, "entry"),
161+ reflection::UsualField(&Function::attrs_, "attrs"),
137 reflection::UsualField(&Function::returnTypes_, "return_types"),162 reflection::UsualField(&Function::returnTypes_, "return_types"),
138 reflection::UsualField(&Function::body_, "body"),163 reflection::UsualField(&Function::body_, "body"),
139 reflection::IgnoreField(&Function::name_, "name")));164 reflection::IgnoreField(&Function::name_, "name")));
140 }165 }
141 166 
167+ /// Get a typed attribute value (returns default_value if key not found)
168+ template <typename T>
169+ [[nodiscard]] T GetAttr(const std::string& key, const T& default_value = T{}) const
170+ {
171+ for (const auto& [k, v] : attrs_) {
172+ if (k == key)
173+ return AnyCast<T>(v, "function attr key: " + key);
174+ }
175+ return default_value;
176+ }
177+ 
178+ /// Check if an attribute exists
179+ [[nodiscard]] bool HasAttr(const std::string& key) const
180+ {
181+ return std::any_of(attrs_.begin(), attrs_.end(), [&key](const auto& pair) { return pair.first == key; });
182+ }
183+ 
142public:184public:
143- std::string name_; // Function name185+ std::string name_; // Function name
144- FunctionType funcType_; // Function type (incore, or opaque)186+ FunctionType funcType_; // Function type (incore, or opaque)
145- bool entry_{false}; // Whether this is the program entry function187+ bool entry_{false}; // Whether this is the program entry function
146- std::vector<VarPtr> params_; // Parameter variables188+ std::vector<std::pair<std::string, std::any>> attrs_; // Function attributes
147- std::vector<TypePtr> returnTypes_; // Return types189+ std::vector<VarPtr> params_; // Parameter variables
148- SeqStmtsPtr body_; // Function body statement190+ std::vector<TypePtr> returnTypes_; // Return types
191+ SeqStmtsPtr body_; // Function body statement
149};192};
150 193 
151using FunctionPtr = std::shared_ptr<const Function>;194using FunctionPtr = std::shared_ptr<const Function>;
@@ -118,6 +118,12 @@ public:
118 [[nodiscard]] std::string GetTypeString(const ir::DataType& dtype) const override;118 [[nodiscard]] std::string GetTypeString(const ir::DataType& dtype) const override;
119 /// True when currently generating code inside a VF section (CCE __VEC_SCOPE__).119 /// True when currently generating code inside a VF section (CCE __VEC_SCOPE__).
120 [[nodiscard]] bool IsInVFSection() const { return in_vf_section_; }120 [[nodiscard]] bool IsInVFSection() const { return in_vf_section_; }
121+ /// True when emitting an A5 `__simt_vf__` or `__simt_callee__` body.
122+ [[nodiscard]] bool IsInSimtContext() const
123+ {
124+ return current_function_type_ == ir::FunctionType::SIMT_VF ||
125+ current_function_type_ == ir::FunctionType::SIMT_CALLEE;
126+ }
121 int GetTileOffsetCounter() { return tile_offset_counter_++; }127 int GetTileOffsetCounter() { return tile_offset_counter_++; }
122 /// Resolve a VF tile expr (plain tile or `tile[offset]`) to its `__ubuf__` pointer, typed as the128 /// Resolve a VF tile expr (plain tile or `tile[offset]`) to its `__ubuf__` pointer, typed as the
123 /// tile element and hoisted before `__VEC_SCOPE__`. A `tile[offset]` load reuses the rvalue129 /// tile element and hoisted before `__VEC_SCOPE__`. A `tile[offset]` load reuses the rvalue
@@ -416,8 +422,11 @@ private:
416 * scalars and target-specific declarations.422 * scalars and target-specific declarations.
417 */423 */
418 void GenerateSinglePrologue(const ir::FunctionPtr& func, bool has_cross_sync);424 void GenerateSinglePrologue(const ir::FunctionPtr& func, bool has_cross_sync);
425+ std::string BuildSimtFunctionSignature(const ir::FunctionPtr& func);
426+ void GenerateSimtFunction(const ir::FunctionPtr& func);
427+ std::string GenerateSimtCalleeCall(const ir::CallPtr& op, const ir::FunctionPtr& callee);
419 void PreScanKernel(const ir::FunctionPtr& kernel_func);428 void PreScanKernel(const ir::FunctionPtr& kernel_func);
420- void PrepareBodyGeneration();429+ void ResetFunctionGenerationState();
421 430 
422 bool DetectCrossCoreSyncOps(const ir::StmtPtr& stmt);431 bool DetectCrossCoreSyncOps(const ir::StmtPtr& stmt);
423 432 
@@ -553,13 +562,15 @@ private:
553 std::map<std::string, std::string> tiling_headers_; ///< Tiling struct headers (filename -> content)562 std::map<std::string, std::string> tiling_headers_; ///< Tiling struct headers (filename -> content)
554 std::map<std::string, StructDefinition> struct_definitions_; ///< Struct type name ->definition563 std::map<std::string, StructDefinition> struct_definitions_; ///< Struct type name ->definition
555 564 
556- CodeEmitter emitter_; ///< Code emitter for structured output565+ CodeEmitter emitter_; ///< Code emitter for structured output
557- CodeContext context_; ///< Context for variable tracking566+ CodeContext context_; ///< Context for variable tracking
558- TypeConverter type_converter_; ///< Type converter567+ TypeConverter type_converter_; ///< Type converter
559- const backend::Backend* backend_; ///< CCE backend instance (for op info, core type)568+ const backend::Backend* backend_; ///< CCE backend instance (for op info, core type)
560- std::string arch_ = "a3"; ///< Target architecture ("a2", "a3", "a5")569+ std::string arch_ = "a3"; ///< Target architecture ("a2", "a3", "a5")
561- const ir::SectionKind target_; ///< Fixed Cube/Vector target for this generator570+ const ir::SectionKind target_; ///< Fixed Cube/Vector target for this generator
562- bool in_vf_section_ = false; ///< True only while emitting a nested VF section571+ bool in_vf_section_ = false; ///< True only while emitting a nested VF section
572+ ir::FunctionType current_function_type_ = ir::FunctionType::OPAQUE;
573+ std::map<std::string, ir::FunctionPtr> simt_callees_;
563 std::unordered_map<std::string, std::string> tensor_to_pointer_; ///< Tensor var name ->raw pointer expression574 std::unordered_map<std::string, std::string> tensor_to_pointer_; ///< Tensor var name ->raw pointer expression
564 std::map<std::string, TensorDef> tensor_defs_; ///< Prescan: cce var name ->TensorDef (for make_tensor views)575 std::map<std::string, TensorDef> tensor_defs_; ///< Prescan: cce var name ->TensorDef (for make_tensor views)
565 std::map<std::string, std::string> tile_addresses_; ///< tile_name ->TASSIGN address expression576 std::map<std::string, std::string> tile_addresses_; ///< tile_name ->TASSIGN address expression
@@ -185,7 +185,7 @@ FunctionPtr IRBuilder::EndFunction(const Span& end_span)
185 185 
186 // Create function186 // Create function
187 auto func = std::make_shared<Function>(func_ctx->GetName(), func_ctx->GetParams(), func_ctx->GetReturnTypes(), body,187 auto func = std::make_shared<Function>(func_ctx->GetName(), func_ctx->GetParams(), func_ctx->GetReturnTypes(), body,
188- combinedSpan, func_ctx->GetFuncType());188+ combinedSpan, func_ctx->GetFuncType(), false, func_ctx->GetAttrs());
189 189 
190 // Pop context190 // Pop context
191 context_stack_.pop_back();191 context_stack_.pop_back();
@@ -159,6 +159,15 @@ TypePtr DeduceGetValType([[maybe_unused]] const std::vector<ExprPtr>& args,
159 return std::make_shared<ScalarType>(tensor_type->dtype_);159 return std::make_shared<ScalarType>(tensor_type->dtype_);
160}160}
161 161 
162+TypePtr DeduceTileValidShapeType(const std::vector<ExprPtr>& args,
163+ const std::vector<std::pair<std::string, std::any>>& kwargs)
164+{
165+ CHECK(args.size() == 1 && As<TileType>(args[0]->GetType())) << "block.tile_valid_shape requires one Tile argument";
166+ int axis = GetOpKwarg<int>(kwargs, "axis", 0);
167+ CHECK(axis >= 0 && axis <= 1) << "block.tile_valid_shape axis must be in [0, 1]";
168+ return std::make_shared<ScalarType>(DataType(DataType::UINT32));
169+}
170+ 
162TypePtr DeduceSetValType([[maybe_unused]] const std::vector<ExprPtr>& args,171TypePtr DeduceSetValType([[maybe_unused]] const std::vector<ExprPtr>& args,
163 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)172 [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs)
164{173{
@@ -262,6 +271,13 @@ REGISTER_OP("block.getval")
262 return DeduceGetValType(args, kwargs);271 return DeduceGetValType(args, kwargs);
263 });272 });
264 273 
274+REGISTER_OP("block.tile_valid_shape")
275+ .set_op_category("BlockOp")
276+ .set_description("Read one runtime valid-shape dimension of a Tile")
277+ .add_argument("tile", "Input tile")
278+ .set_attr<int>("axis")
279+ .f_deduce_type(DeduceTileValidShapeType);
280+ 
265REGISTER_OP("block.setval")281REGISTER_OP("block.setval")
266 .set_op_category("BlockOp")282 .set_op_category("BlockOp")
267 .set_description("Write a scalar value to a tile or tensor at offset")283 .set_description("Write a scalar value to a tile or tensor at offset")
@@ -0,0 +1,167 @@
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+/**
12+ * @file simt_ops.cpp
13+ * \brief SIMT context and launch operations used by PyPTO Pro's A5 direct-CCE path.
14+ */
15+ 
16+#include <any>
17+#include <cstddef>
18+#include <cstdint>
19+#include <memory>
20+#include <string>
21+#include <utility>
22+#include <vector>
23+ 
24+#include "core/dtype.h"
25+#include "core/logging.h"
26+#include "ir/expr.h"
27+#include "ir/kind_traits.h"
28+#include "ir/memref.h"
29+#include "ir/op_registry.h"
30+#include "ir/scalar_expr.h"
31+#include "ir/type.h"
32+#include "ir/type_inference.h"
33+ 
34+namespace pypto {
35+namespace ir {
36+ 
37+namespace {
38+ 
39+TypePtr DeduceSimtContextComponentType(const std::vector<ExprPtr>& args,
40+ const std::vector<std::pair<std::string, std::any>>& kwargs)
41+{
42+ CHECK(args.empty()) << "SIMT context operations do not accept positional arguments";
43+ int axis = GetOpKwarg<int>(kwargs, "axis", 0);
44+ CHECK(axis >= 0 && axis <= 2) << "SIMT context axis must be in [0, 2]";
45+ return std::make_shared<ScalarType>(DataType(DataType::UINT32));
46+}
47+ 
48+TypePtr DeduceSimtLinearThreadIdxType(const std::vector<ExprPtr>& args,
49+ const std::vector<std::pair<std::string, std::any>>& kwargs)
50+{
51+ CHECK(args.empty()) << "SIMT builtin scalar operations do not accept positional arguments";
52+ CHECK(kwargs.empty()) << "SIMT builtin scalar operations do not accept keyword arguments";
53+ return std::make_shared<ScalarType>(DataType(DataType::UINT32));
54+}
55+ 
56+TypePtr DeduceSimtWarpSizeType(const std::vector<ExprPtr>& args,
57+ const std::vector<std::pair<std::string, std::any>>& kwargs)
58+{
59+ CHECK(args.empty()) << "simt.warp_size does not accept positional arguments";
60+ CHECK(kwargs.empty()) << "simt.warp_size does not accept keyword arguments";
61+ return std::make_shared<ScalarType>(DataType(DataType::INT32));
62+}
63+ 
64+TypePtr DeduceSimtLaunchType(const std::vector<ExprPtr>& args,
65+ const std::vector<std::pair<std::string, std::any>>& kwargs)
66+{
67+ CHECK(args.size() >= 3) << "simt.launch requires three launch dimensions";
68+ int64_t total_threads = 1;
69+ for (std::size_t i = 0; i < 3; ++i) {
70+ auto dim_type = As<ScalarType>(args[i]->GetType());
71+ CHECK(dim_type && dim_type->dtype_.IsInt() && dim_type->dtype_ != DataType(DataType::BOOL))
72+ << "simt.launch dimensions must be non-bool integer scalars";
73+ auto dim = As<ConstInt>(args[i]);
74+ CHECK(dim && dim->value_ > 0 && dim->value_ <= 2048)
75+ << "simt.launch dimensions must be compile-time integers in [1, 2048]";
76+ total_threads *= dim->value_;
77+ }
78+ CHECK(total_threads <= 2048) << "simt.launch total thread count must not exceed 2048";
79+ int max_threads = GetOpKwarg<int>(kwargs, "max_threads");
80+ CHECK(max_threads >= 1 && max_threads <= 2048) << "simt.launch max_threads must be in [1, 2048]";
81+ CHECK(total_threads <= max_threads) << "simt.launch threads " << total_threads << " exceed callee max_threads "
82+ << max_threads;
83+ for (std::size_t i = 3; i < args.size(); ++i) {
84+ auto arg_type = args[i]->GetType();
85+ if (auto tile_type = As<TileType>(arg_type)) {
86+ CHECK(tile_type->shape_.size() == 2) << "simt.launch Tile argument must have a two-dimensional shape";
87+ CHECK(As<Var>(args[i]) != nullptr) << "simt.launch Tile argument must be a Var";
88+ for (const auto& dim : tile_type->shape_) {
89+ CHECK(As<ConstInt>(dim) != nullptr) << "simt.launch Tile argument must have a static shape";
90+ }
91+ CHECK(tile_type->dtype_.GetBit() >= 8) << "simt.launch Tile argument has a sub-byte element dtype";
92+ CHECK(tile_type->memref_.has_value()) << "simt.launch Tile argument has no memory reference";
93+ CHECK((*tile_type->memref_)->memorySpace_ == MemorySpace::Vec)
94+ << "simt.launch Tile argument must be a Vec-memory Tile";
95+ CHECK(tile_type->hardwareInfo_.has_value() && tile_type->hardwareInfo_->blayout == TileLayout::row_major &&
96+ tile_type->hardwareInfo_->slayout == TileLayout::none_box)
97+ << "simt.launch Tile argument must be an ND Vec Tile";
98+ } else if (auto tensor_type = As<TensorType>(arg_type)) {
99+ CHECK(!tensor_type->shape_.empty()) << "simt.launch Tensor argument must have a non-empty shape";
100+ for (const auto& dim : tensor_type->shape_) {
101+ CHECK(As<ConstInt>(dim) != nullptr) << "simt.launch Tensor argument must have a static shape";
102+ }
103+ CHECK(tensor_type->dtype_.GetBit() >= 8) << "simt.launch Tensor argument has a sub-byte element dtype";
104+ CHECK(tensor_type->tensor_view_.has_value() && tensor_type->tensor_view_->layout == TensorLayout::ND)
105+ << "simt.launch Tensor argument must use ND layout";
106+ CHECK(As<Var>(args[i]) != nullptr) << "simt.launch Tensor argument must be a Var";
107+ } else {
108+ CHECK(As<ScalarType>(arg_type)) << "simt.launch supports only Tile, Tensor, and scalar arguments";
109+ }
110+ }
111+ return GetUnknownType();
112+}
113+ 
114+} // namespace
115+ 
116+REGISTER_OP("simt.thread_idx")
117+ .set_op_category("SimtOp")
118+ .set_description("Read one component of the native SIMT thread index")
119+ .no_argument()
120+ .set_attr<int>("axis")
121+ .f_deduce_type(DeduceSimtContextComponentType);
122+ 
123+REGISTER_OP("simt.block_dim")
124+ .set_op_category("SimtOp")
125+ .set_description("Read one component of the native SIMT block dimensions")
126+ .no_argument()
127+ .set_attr<int>("axis")
128+ .f_deduce_type(DeduceSimtContextComponentType);
129+ 
130+REGISTER_OP("simt.block_idx")
131+ .set_op_category("SimtOp")
132+ .set_description("Read one component of the native SIMT block index")
133+ .no_argument()
134+ .set_attr<int>("axis")
135+ .f_deduce_type(DeduceSimtContextComponentType);
136+ 
137+REGISTER_OP("simt.grid_dim")
138+ .set_op_category("SimtOp")
139+ .set_description("Read one component of the native SIMT grid dimensions")
140+ .no_argument()
141+ .set_attr<int>("axis")
142+ .f_deduce_type(DeduceSimtContextComponentType);
143+ 
144+REGISTER_OP("simt.linear_thread_idx")
145+ .set_op_category("SimtOp")
146+ .set_description("Read the x-major flattened thread index within the current block")
147+ .no_argument()
148+ .f_deduce_type(DeduceSimtLinearThreadIdxType);
149+ 
150+REGISTER_OP("simt.warp_size")
151+ .set_op_category("SimtOp")
152+ .set_description("Read the native SIMT warp size")
153+ .no_argument()
154+ .f_deduce_type(DeduceSimtWarpSizeType);
155+ 
156+REGISTER_OP("simt.launch")
157+ .set_op_category("SimtOp")
158+ .set_description("Launch a SIMT vector function from an AIV kernel")
159+ .add_argument("threads_x", "Compile-time X dimension")
160+ .add_argument("threads_y", "Compile-time Y dimension")
161+ .add_argument("threads_z", "Compile-time Z dimension")
162+ .set_attr<std::string>("callee")
163+ .set_attr<int>("max_threads")
164+ .f_deduce_type(DeduceSimtLaunchType);
165+ 
166+} // namespace ir
167+} // namespace pypto
@@ -144,7 +144,7 @@ public:
144 144 
145 // Create the new function with versioned parameters145 // Create the new function with versioned parameters
146 return std::make_shared<Function>(func->name_, new_params_, func->returnTypes_, new_body, func->span_,146 return std::make_shared<Function>(func->name_, new_params_, func->returnTypes_, new_body, func->span_,
147- func->funcType_, func->entry_);147+ func->funcType_, func->entry_, func->attrs_);
148 }148 }
149 149 
150protected:150protected:
@@ -160,7 +160,7 @@ FunctionPtr IRMutator::VisitFunction(const FunctionPtr& func)
160 return func;160 return func;
161 }161 }
162 return std::make_shared<const Function>(func->name_, func->params_, func->returnTypes_, std::move(new_body),162 return std::make_shared<const Function>(func->name_, func->params_, func->returnTypes_, std::move(new_body),
163- func->span_, func->funcType_, func->entry_);163+ func->span_, func->funcType_, func->entry_, func->attrs_);
164}164}
165 165 
166ExprPtr IRMutator::VisitExpr(const ExprPtr& expr) { return ExprFunctor<ExprPtr>::VisitExpr(expr); }166ExprPtr IRMutator::VisitExpr(const ExprPtr& expr) { return ExprFunctor<ExprPtr>::VisitExpr(expr); }
@@ -229,7 +229,7 @@ Pass Canonicalize()
229 if (body == func->body_)229 if (body == func->body_)
230 return func;230 return func;
231 return std::make_shared<const Function>(func->name_, func->params_, func->returnTypes_, body, func->span_,231 return std::make_shared<const Function>(func->name_, func->params_, func->returnTypes_, body, func->span_,
232- func->funcType_, func->entry_);232+ func->funcType_, func->entry_, func->attrs_);
233 },233 },
234 "Canonicalize");234 "Canonicalize");
235}235}
@@ -247,7 +247,7 @@ Pass InferTokenPass()
247 if (inferredBody == func->body_)247 if (inferredBody == func->body_)
248 return func;248 return func;
249 return std::make_shared<const Function>(func->name_, func->params_, func->returnTypes_, inferredBody,249 return std::make_shared<const Function>(func->name_, func->params_, func->returnTypes_, inferredBody,
250- func->span_, func->funcType_, func->entry_);250+ func->span_, func->funcType_, func->entry_, func->attrs_);
251 },251 },
252 "InferTokenPass");252 "InferTokenPass");
253}253}
@@ -286,7 +286,7 @@ Pass MergeStmtsIntoIf()
286 if (mergedBody == func->body_)286 if (mergedBody == func->body_)
287 return func;287 return func;
288 return std::make_shared<const Function>(func->name_, func->params_, func->returnTypes_, mergedBody,288 return std::make_shared<const Function>(func->name_, func->params_, func->returnTypes_, mergedBody,
289- func->span_, func->funcType_, func->entry_);289+ func->span_, func->funcType_, func->entry_, func->attrs_);
290 },290 },
291 "MergeStmtsIntoIf");291 "MergeStmtsIntoIf");
292}292}
@@ -1093,9 +1093,14 @@ void IRPrinter::VisitFunctionBody(const StmtPtr& body)
1093void IRPrinter::VisitFunction(const FunctionPtr& func)1093void IRPrinter::VisitFunction(const FunctionPtr& func)
1094{1094{
1095 // Print decorator1095 // Print decorator
1096- stream_ << GetIndent() << "@" << prefix_ << ".function";1096+ if (func->funcType_ == FunctionType::SIMT_VF || func->funcType_ == FunctionType::SIMT_CALLEE) {
1097- if (func->funcType_ != FunctionType::OPAQUE) {1097+ stream_ << GetIndent() << "@" << prefix_ << ".simt.function(type=" << prefix_ << ".FunctionType."
1098- stream_ << "(type=" << prefix_ << ".FunctionType." << FunctionTypeToString(func->funcType_) << ")";1098+ << FunctionTypeToString(func->funcType_) << ")";
1099+ } else {
1100+ stream_ << GetIndent() << "@" << prefix_ << ".function";
1101+ if (func->funcType_ != FunctionType::OPAQUE) {
1102+ stream_ << "(type=" << prefix_ << ".FunctionType." << FunctionTypeToString(func->funcType_) << ")";
1103+ }
1099 }1104 }
1100 stream_ << "\n";1105 stream_ << "\n";
1101 1106 
@@ -1688,6 +1688,9 @@ static std::string MakeGetValCodegenCCE(const ir::CallPtr& op, codegen::CodegenB
1688 if (ir::As<ir::TileType>(first_type)) {1688 if (ir::As<ir::TileType>(first_type)) {
1689 std::string tile = codegen.GetExprAsCode(op->args_[0]);1689 std::string tile = codegen.GetExprAsCode(op->args_[0]);
1690 std::string offset = codegen.GetExprAsCode(op->args_[1]);1690 std::string offset = codegen.GetExprAsCode(op->args_[1]);
1691+ if (codegen.IsInSimtContext()) {
1692+ return tile + "[" + offset + "]";
1693+ }
1691 return tile + ".GetValue(" + offset + ")";1694 return tile + ".GetValue(" + offset + ")";
1692 }1695 }
1693 1696 
@@ -1714,6 +1717,10 @@ static std::string MakeSetValCodegenCCE(const ir::CallPtr& op, codegen::CodegenB
1714 std::string tile = codegen.GetExprAsCode(op->args_[0]);1717 std::string tile = codegen.GetExprAsCode(op->args_[0]);
1715 std::string offset = codegen.GetExprAsCode(op->args_[1]);1718 std::string offset = codegen.GetExprAsCode(op->args_[1]);
1716 std::string value = codegen.GetExprAsCode(op->args_[2]);1719 std::string value = codegen.GetExprAsCode(op->args_[2]);
1720+ if (codegen.IsInSimtContext()) {
1721+ codegen.Emit(tile + "[" + offset + "] = " + value + ";");
1722+ return "";
1723+ }
1717 codegen.Emit(tile + ".SetValue(" + offset + ", " + value + ");");1724 codegen.Emit(tile + ".SetValue(" + offset + ", " + value + ");");
1718 return "";1725 return "";
1719 }1726 }
@@ -1733,6 +1740,20 @@ static std::string MakeSetValCodegenCCE(const ir::CallPtr& op, codegen::CodegenB
1733 return "";1740 return "";
1734}1741}
1735 1742 
1743+static std::string MakeTileValidShapeCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
1744+{
1745+ auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
1746+ CHECK(op->args_.size() == 1 && ir::As<ir::TileType>(op->args_[0]->GetType()))
1747+ << "block.tile_valid_shape requires one Tile argument";
1748+ int axis = op->GetKwarg<int>("axis");
1749+ CHECK(axis >= 0 && axis <= 1) << "block.tile_valid_shape axis must be in [0, 1]";
1750+ 
1751+ if (codegen.IsInSimtContext()) {
1752+ return codegen.GetExprAsCode(op->args_[0]) + (axis == 0 ? "__valid_row" : "__valid_col");
1753+ }
1754+ return codegen.GetExprAsCode(op->args_[0]) + (axis == 0 ? ".GetValidRow()" : ".GetValidCol()");
1755+}
1756+ 
1736// getval/setval use the "block." IR namespace like every other explicit-output1757// getval/setval use the "block." IR namespace like every other explicit-output
1737// block op (block.add, block.matmul, ...). This keeps codegen dispatch (keyed on1758// block op (block.add, block.matmul, ...). This keeps codegen dispatch (keyed on
1738// op->name_) and the parser's auto_mutex pipe lookup (get_op_pipe -> "block.<name>")1759// op->name_) and the parser's auto_mutex pipe lookup (get_op_pipe -> "block.<name>")
@@ -1745,6 +1766,10 @@ REGISTER_BACKEND_OP(BackendCCE, "block.setval")
1745 .set_pipe(ir::PipeType::S)1766 .set_pipe(ir::PipeType::S)
1746 .f_codegen([](const ir::CallPtr& op, codegen::CodegenBase& codegen) { return MakeSetValCodegenCCE(op, codegen); });1767 .f_codegen([](const ir::CallPtr& op, codegen::CodegenBase& codegen) { return MakeSetValCodegenCCE(op, codegen); });
1747 1768 
1769+REGISTER_BACKEND_OP(BackendCCE, "block.tile_valid_shape")
1770+ .set_pipe(ir::PipeType::S)
1771+ .f_codegen(MakeTileValidShapeCodegenCCE);
1772+ 
1748// ============================================================================1773// ============================================================================
1749// block.subview - tile/tensor sub-view with offset and new shape.1774// block.subview - tile/tensor sub-view with offset and new shape.
1750//1775//
@@ -0,0 +1,140 @@
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+/**
12+ * @file backend_cce_simt_ops.cpp
13+ * \brief Direct CCE lowering for the A5 SIMT context and launch operations.
14+ */
15+ 
16+#include <cstddef>
17+#include <cstdint>
18+#include <sstream>
19+#include <string>
20+ 
21+#include "backend/backend_cce.h"
22+#include "backend/common/backend.h"
23+#include "codegen/cce/cce_codegen.h"
24+#include "codegen/codegen_base.h"
25+#include "core/dtype.h"
26+#include "core/logging.h"
27+#include "ir/expr.h"
28+#include "ir/kind_traits.h"
29+#include "ir/pipe.h"
30+#include "ir/scalar_expr.h"
31+ 
32+namespace pypto {
33+namespace backend {
34+ 
35+namespace {
36+ 
37+const char* GetSimtAxisName(int axis)
38+{
39+ constexpr const char* axis_names[] = {"x", "y", "z"};
40+ return axis_names[axis];
41+}
42+ 
43+std::string MakeSimtContextComponentCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base,
44+ const char* op_name, const char* context_name)
45+{
46+ auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
47+ CHECK(codegen.IsInSimtContext()) << op_name << " reached CCE codegen outside a SIMT function";
48+ return std::string(context_name) + "." + GetSimtAxisName(op->GetKwarg<int>("axis"));
49+}
50+ 
51+std::string MakeSimtThreadIdxCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
52+{
53+ return MakeSimtContextComponentCodegenCCE(op, codegen_base, "simt.thread_idx", "threadIdx");
54+}
55+ 
56+std::string MakeSimtBlockDimCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
57+{
58+ return MakeSimtContextComponentCodegenCCE(op, codegen_base, "simt.block_dim", "blockDim");
59+}
60+ 
61+std::string MakeSimtBlockIdxCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
62+{
63+ return MakeSimtContextComponentCodegenCCE(op, codegen_base, "simt.block_idx", "blockIdx");
64+}
65+ 
66+std::string MakeSimtGridDimCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
67+{
68+ return MakeSimtContextComponentCodegenCCE(op, codegen_base, "simt.grid_dim", "gridDim");
69+}
70+ 
71+std::string MakeSimtLinearThreadIdxCodegenCCE([[maybe_unused]] const ir::CallPtr& op,
72+ codegen::CodegenBase& codegen_base)
73+{
74+ auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
75+ CHECK(codegen.IsInSimtContext()) << "simt.linear_thread_idx reached CCE codegen outside a SIMT function";
76+ return "(threadIdx.x + threadIdx.y * blockDim.x + threadIdx.z * blockDim.x * blockDim.y)";
77+}
78+ 
79+std::string MakeSimtWarpSizeCodegenCCE([[maybe_unused]] const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
80+{
81+ auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
82+ CHECK(codegen.IsInSimtContext()) << "simt.warp_size reached CCE codegen outside a SIMT function";
83+ return "warpSize";
84+}
85+ 
86+std::string MakeSimtLaunchCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base)
87+{
88+ auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base);
89+ CHECK(!codegen.IsInSimtContext()) << "Nested simt.launch is not supported";
90+ CHECK(codegen.GetTarget() == ir::SectionKind::Vector) << "simt.launch requires the Vector target";
91+ CHECK(codegen.GetArch() == "a5") << "simt.launch currently requires arch='a5'";
92+ int64_t thread_dims[3] = {};
93+ for (size_t i = 0; i < 3; ++i) {
94+ auto dim = ir::As<ir::ConstInt>(op->args_[i]);
95+ thread_dims[i] = dim->value_;
96+ }
97+ 
98+ std::ostringstream call;
99+ call << "cce::async_invoke<" << op->GetKwarg<std::string>("callee") << ">(cce::dim3{" << thread_dims[0] << ", "
100+ << thread_dims[1] << ", " << thread_dims[2] << "}";
101+ for (size_t i = 3; i < op->args_.size(); ++i) {
102+ auto arg_type = op->args_[i]->GetType();
103+ auto tile_type = ir::As<ir::TileType>(arg_type);
104+ if (tile_type != nullptr) {
105+ std::string tile = codegen.GetExprAsCode(op->args_[i]);
106+ call << ", (__ubuf__ " << tile_type->dtype_.ToCTypeString() << "*)" << tile << ".data()";
107+ call << ", (uint32_t)" << tile << ".GetValidRow(), (uint32_t)" << tile << ".GetValidCol()";
108+ } else if (auto tensor_type = ir::As<ir::TensorType>(arg_type)) {
109+ auto tensor_var = ir::As<ir::Var>(op->args_[i]);
110+ std::string tensor_name = codegen.GetVarName(tensor_var);
111+ call << ", (__gm__ " << tensor_type->dtype_.ToCTypeString() << "*)" << codegen.GetPointer(tensor_name);
112+ } else {
113+ call << ", " << codegen.GetExprAsCode(op->args_[i]);
114+ }
115+ }
116+ call << ");";
117+ codegen.Emit(call.str());
118+ return "";
119+}
120+ 
121+} // namespace
122+ 
123+REGISTER_BACKEND_OP(BackendCCE, "simt.thread_idx").set_pipe(ir::PipeType::S).f_codegen(MakeSimtThreadIdxCodegenCCE);
124+ 
125+REGISTER_BACKEND_OP(BackendCCE, "simt.block_dim").set_pipe(ir::PipeType::S).f_codegen(MakeSimtBlockDimCodegenCCE);
126+ 
127+REGISTER_BACKEND_OP(BackendCCE, "simt.block_idx").set_pipe(ir::PipeType::S).f_codegen(MakeSimtBlockIdxCodegenCCE);
128+ 
129+REGISTER_BACKEND_OP(BackendCCE, "simt.grid_dim").set_pipe(ir::PipeType::S).f_codegen(MakeSimtGridDimCodegenCCE);
130+ 
131+REGISTER_BACKEND_OP(BackendCCE, "simt.linear_thread_idx")
132+ .set_pipe(ir::PipeType::S)
133+ .f_codegen(MakeSimtLinearThreadIdxCodegenCCE);
134+ 
135+REGISTER_BACKEND_OP(BackendCCE, "simt.warp_size").set_pipe(ir::PipeType::S).f_codegen(MakeSimtWarpSizeCodegenCCE);
136+ 
137+REGISTER_BACKEND_OP(BackendCCE, "simt.launch").set_pipe(ir::PipeType::V).f_codegen(MakeSimtLaunchCodegenCCE);
138+ 
139+} // namespace backend
140+} // namespace pypto
@@ -20,6 +20,7 @@
20#include <set>20#include <set>
21#include <sstream>21#include <sstream>
22#include <string>22#include <string>
23+#include <unordered_set>
23#include <utility>24#include <utility>
24#include <vector>25#include <vector>
25 26 
@@ -452,27 +453,167 @@ private:
452 453 
453void CCECodegen::PreScanKernel(const ir::FunctionPtr& kernel_func)454void CCECodegen::PreScanKernel(const ir::FunctionPtr& kernel_func)
454{455{
455- var_read_names_.clear();
456 CollectVarReadNames(kernel_func->body_, var_read_names_);456 CollectVarReadNames(kernel_func->body_, var_read_names_);
457- 
458- mutex_pipes_.clear();
459 CollectMutexPipeInfo(kernel_func->body_);457 CollectMutexPipeInfo(kernel_func->body_);
460}458}
461 459 
462-void CCECodegen::PrepareBodyGeneration()460+void CCECodegen::ResetFunctionGenerationState()
463{461{
462+ context_.Clear();
463+ tensor_to_pointer_.clear();
464+ tensor_defs_.clear();
465+ tile_addresses_.clear();
466+ emitted_tile_types_.clear();
467+ emitted_tile_aliases_.clear();
468+ 
469+ var_read_names_.clear();
470+ var_read_counts_.clear();
471+ mutex_pipes_.clear();
472+ 
473+ current_target_var_.clear();
474+ current_expr_value_.clear();
475+ current_tuple_.reset();
476+ current_stmt_span_ = ir::Span::Unknown();
477+ current_expr_span_ = ir::Span::Unknown();
478+ 
464 tuple_var_to_make_tuple_.clear();479 tuple_var_to_make_tuple_.clear();
465 tuple_backing_arr_.clear();480 tuple_backing_arr_.clear();
466 loop_target_stack_.clear();481 loop_target_stack_.clear();
467 yield_buffer_.clear();482 yield_buffer_.clear();
483+ 
484+ vf_tile_ptrs_.clear();
485+ section_hoisted_decls_.clear();
486+ vf_reg_hoisted_decls_.clear();
487+ reg_tensor_vars_.clear();
488+ mask_reg_vars_.clear();
489+ addr_reg_vars_.clear();
490+ tile_offset_counter_ = 0;
491+ vf_tile_ptr_counter_ = 0;
492+ in_vf_section_ = false;
493+ current_function_type_ = ir::FunctionType::OPAQUE;
468}494}
469 495 
496+std::string CCECodegen::BuildSimtFunctionSignature(const ir::FunctionPtr& func)
497+{
498+ std::ostringstream sig;
499+ if (func->funcType_ == ir::FunctionType::SIMT_VF) {
500+ CHECK(func->HasAttr(ir::kMaxThreadsAttr)) << "SIMT function '" << func->name_ << "' has no max_threads";
501+ sig << "__simt_vf__ __launch_bounds__(" << func->GetAttr<int>(ir::kMaxThreadsAttr) << ") inline void ";
502+ } else {
503+ CHECK(func->returnTypes_.size() <= 1) << "SIMT callee '" << func->name_ << "' has multiple return values";
504+ if (func->returnTypes_.empty()) {
505+ sig << "__simt_callee__ inline void ";
506+ } else {
507+ auto return_type = ir::As<ir::ScalarType>(func->returnTypes_[0]);
508+ CHECK(return_type != nullptr) << "SIMT callee '" << func->name_ << "' must return a scalar or void";
509+ sig << "__simt_callee__ inline " << return_type->dtype_.ToCTypeString() << " ";
510+ }
511+ }
512+ sig << func->name_ << "(";
513+ bool first = true;
514+ for (const auto& param : func->params_) {
515+ if (!first) {
516+ sig << ", ";
517+ }
518+ first = false;
519+ std::string param_name = context_.SanitizeName(param);
520+ if (auto scalar_type = ir::As<ir::ScalarType>(param->GetType())) {
521+ sig << scalar_type->dtype_.ToCTypeString() << " " << param_name;
522+ } else if (auto tensor_type = ir::As<ir::TensorType>(param->GetType())) {
523+ sig << "__gm__ " << tensor_type->dtype_.ToCTypeString() << "* " << param_name;
524+ RegisterPointer(param_name, param_name);
525+ } else if (auto tile_type = ir::As<ir::TileType>(param->GetType())) {
526+ sig << "__ubuf__ " << tile_type->dtype_.ToCTypeString() << "* " << param_name;
527+ sig << ", uint32_t " << param_name << "__valid_row";
528+ sig << ", uint32_t " << param_name << "__valid_col";
529+ } else {
530+ CHECK(false) << "SIMT function '" << func->name_
531+ << "' supports only TensorType, TileType, and ScalarType parameters";
532+ }
533+ context_.RegisterVar(param, param_name);
534+ }
535+ sig << ")";
536+ return sig.str();
537+}
538+ 
539+void CCECodegen::GenerateSimtFunction(const ir::FunctionPtr& func)
540+{
541+ CHECK(func != nullptr &&
542+ (func->funcType_ == ir::FunctionType::SIMT_VF || func->funcType_ == ir::FunctionType::SIMT_CALLEE))
543+ << "GenerateSimtFunction expects a SIMT_VF or SIMT_CALLEE function";
544+ 
545+ ResetFunctionGenerationState();
546+ PreScanKernel(func);
547+ current_function_type_ = func->funcType_;
548+ 
549+ emitter_.EmitLine(BuildSimtFunctionSignature(func));
550+ emitter_.EmitLine("{");
551+ emitter_.IncreaseIndent();
552+ 
553+ try {
554+ GenerateBody(func);
555+ } catch (...) {
556+ current_function_type_ = ir::FunctionType::OPAQUE;
557+ throw;
558+ }
559+ current_function_type_ = ir::FunctionType::OPAQUE;
560+ emitter_.EmitLine("");
561+}
562+ 
563+namespace {
564+ 
565+class SimtCalleeCallCollector : public ir::IRVisitor {
566+public:
567+ using ir::IRVisitor::VisitExpr_;
568+ 
569+ std::vector<std::string> calls_;
570+ 
571+ void VisitExpr_(const ir::CallPtr& op) override
572+ {
573+ calls_.push_back(op->name_);
574+ ir::IRVisitor::VisitExpr_(op);
575+ }
576+};
577+ 
578+std::vector<ir::FunctionPtr> OrderSimtCallees(const std::map<std::string, ir::FunctionPtr>& callees)
579+{
580+ std::unordered_set<std::string> active;
581+ std::unordered_set<std::string> ordered_names;
582+ std::vector<ir::FunctionPtr> ordered;
583+ 
584+ std::function<void(const ir::FunctionPtr&)> visit = [&](const ir::FunctionPtr& func) {
585+ if (ordered_names.find(func->name_) != ordered_names.end()) {
586+ return;
587+ }
588+ CHECK(active.insert(func->name_).second)
589+ << "Recursive SIMT callee call involving '" << func->name_ << "' is not supported";
590+ SimtCalleeCallCollector collector;
591+ collector.VisitStmt(func->body_);
592+ for (const auto& name : collector.calls_) {
593+ auto it = callees.find(name);
594+ if (it != callees.end()) {
595+ visit(it->second);
596+ }
597+ }
598+ active.erase(func->name_);
599+ ordered_names.insert(func->name_);
600+ ordered.push_back(func);
601+ };
602+ 
603+ for (const auto& entry : callees) {
604+ visit(entry.second);
605+ }
606+ return ordered;
607+}
608+ 
609+} // namespace
610+ 
470std::string CCECodegen::GenerateSingle(const ir::ProgramPtr& program, const std::string& arch)611std::string CCECodegen::GenerateSingle(const ir::ProgramPtr& program, const std::string& arch)
471{612{
472 CHECK(program != nullptr) << "Cannot generate code for null program";613 CHECK(program != nullptr) << "Cannot generate code for null program";
473 614 
615+ ResetFunctionGenerationState();
474 arch_ = arch;616 arch_ = arch;
475- in_vf_section_ = false;
476 617 
477 // Capture the tuple/struct field-name side table from the entry program (may be null).618 // Capture the tuple/struct field-name side table from the entry program (may be null).
478 // Passes below rebuild the Program (dropping this annotation), but the TupleType pointers619 // Passes below rebuild the Program (dropping this annotation), but the TupleType pointers
@@ -485,8 +626,18 @@ std::string CCECodegen::GenerateSingle(const ir::ProgramPtr& program, const std:
485 ir::ProgramPtr ssa_program = ir::pass::ConvertToSSA()(program);626 ir::ProgramPtr ssa_program = ir::pass::ConvertToSSA()(program);
486 627 
487 ir::FunctionPtr kernel_func;628 ir::FunctionPtr kernel_func;
629+ std::vector<ir::FunctionPtr> simt_funcs;
630+ simt_callees_.clear();
488 for (const auto& func_entry : ssa_program->functions_) {631 for (const auto& func_entry : ssa_program->functions_) {
489 const auto& func = func_entry.second;632 const auto& func = func_entry.second;
633+ if (func->funcType_ == ir::FunctionType::SIMT_VF) {
634+ simt_funcs.push_back(func);
635+ continue;
636+ }
637+ if (func->funcType_ == ir::FunctionType::SIMT_CALLEE) {
638+ simt_callees_[func->name_] = func;
639+ continue;
640+ }
490 if (func->funcType_ == ir::FunctionType::ORCHESTRATION) {641 if (func->funcType_ == ir::FunctionType::ORCHESTRATION) {
491 continue;642 continue;
492 }643 }
@@ -495,22 +646,30 @@ std::string CCECodegen::GenerateSingle(const ir::ProgramPtr& program, const std:
495 }646 }
496 }647 }
497 CHECK(kernel_func != nullptr) << "No kernel function found in program";648 CHECK(kernel_func != nullptr) << "No kernel function found in program";
649+ if (!simt_funcs.empty() || !simt_callees_.empty()) {
650+ CHECK(target_ == ir::SectionKind::Vector) << "SIMT functions can only be generated for the Vector target";
651+ CHECK(arch_ == "a5") << "SIMT direct CCE generation currently requires arch='a5'";
652+ }
498 653 
499 emitter_.Clear();654 emitter_.Clear();
500- context_.Clear();
501- tensor_to_pointer_.clear();
502 tiling_headers_.clear();655 tiling_headers_.clear();
503 struct_definitions_.clear();656 struct_definitions_.clear();
504 657 
505- PreScanKernel(kernel_func);
506- 
507 // Detect cross-core sync (a5 uses hardware sync, not ffts)658 // Detect cross-core sync (a5 uses hardware sync, not ffts)
508 bool has_cross_sync = DetectCrossCoreSyncOps(kernel_func->body_);659 bool has_cross_sync = DetectCrossCoreSyncOps(kernel_func->body_);
509 bool needs_ffts = has_cross_sync && (arch_ != "a5");660 bool needs_ffts = has_cross_sync && (arch_ != "a5");
510 661 
662+ for (const auto& simt_callee : OrderSimtCallees(simt_callees_)) {
663+ GenerateSimtFunction(simt_callee);
664+ }
665+ for (const auto& simt_func : simt_funcs) {
666+ GenerateSimtFunction(simt_func);
667+ }
668+ 
669+ ResetFunctionGenerationState();
670+ PreScanKernel(kernel_func);
511 RegisterTilingStructTypes(kernel_func);671 RegisterTilingStructTypes(kernel_func);
512 GenerateSinglePrologue(kernel_func, needs_ffts);672 GenerateSinglePrologue(kernel_func, needs_ffts);
513- PrepareBodyGeneration();
514 try {673 try {
515 GenerateBody(kernel_func);674 GenerateBody(kernel_func);
516 } catch (const npu::tile_fwk::Error& e) {675 } catch (const npu::tile_fwk::Error& e) {
@@ -1066,21 +1225,31 @@ void CCECodegen::VisitStmt_(const ir::EvalStmtPtr& op)
1066 INTERNAL_CHECK(op != nullptr) << "Internal error: null EvalStmt";1225 INTERNAL_CHECK(op != nullptr) << "Internal error: null EvalStmt";
1067 INTERNAL_CHECK(op->expr_ != nullptr) << "Internal error: EvalStmt has null expression";1226 INTERNAL_CHECK(op->expr_ != nullptr) << "Internal error: EvalStmt has null expression";
1068 1227 
1069- // EvalStmt: evaluate expression for side effects (e.g., sync operations)1228+ // Backend side-effect ops emit their statements while visiting the expression. A direct
1070- // Sync ops (set_flag, wait_flag, pipe_barrier) are registered with f_codegen_cce1229+ // SimtCallee call instead returns its call text, which must be emitted here. Results from
1071- // and will be invoked via VisitExpr_(Call). Cross-core sync redundancy is1230+ // all other evaluation expressions are intentionally discarded.
1072- // checked inside the per-op codegen handler (Make{Set,Wait}CrossCoreCodegenCCE).1231+ auto call = ir::As<ir::Call>(op->expr_);
1232+ bool is_simt_callee_call = IsInSimtContext() && call != nullptr &&
1233+ simt_callees_.find(call->name_) != simt_callees_.end();
1234+ current_expr_value_ = "";
1073 VisitExpr(op->expr_);1235 VisitExpr(op->expr_);
1236+ if (is_simt_callee_call && !current_expr_value_.empty()) {
1237+ emitter_.EmitLine(current_expr_value_ + ";");
1238+ }
1239+ current_expr_value_ = "";
1074}1240}
1075 1241 
1076void CCECodegen::VisitStmt_(const ir::ReturnStmtPtr& op)1242void CCECodegen::VisitStmt_(const ir::ReturnStmtPtr& op)
1077{1243{
1078 INTERNAL_CHECK(op != nullptr) << "Internal error: null ReturnStmt";1244 INTERNAL_CHECK(op != nullptr) << "Internal error: null ReturnStmt";
1079- // A ReturnStmt reaching codegen is a kernel-level return. Emit a native C++ return so the1245+ CHECK(op->value_.size() <= 1) << "ReturnStmt must contain at most one value";
1080- // function exits immediately, matching Python's return semantics.1246+ if (op->value_.empty()) {
1081- // Kernel functions are void, so return values are discarded.1247+ emitter_.EmitLine("return;");
1082- emitter_.EmitLine("return;");1248+ } else {
1083- current_expr_value_ = "";1249+ CHECK(ir::As<ir::ScalarType>(op->value_[0]->GetType()) != nullptr) << "ReturnStmt value must be a scalar";
1250+ emitter_.EmitLine("return " + GetExprAsCode(op->value_[0]) + ";");
1251+ }
1252+ current_expr_value_.clear();
1084}1253}
1085 1254 
1086void CCECodegen::VisitStmt_(const ir::YieldStmtPtr& op)1255void CCECodegen::VisitStmt_(const ir::YieldStmtPtr& op)
@@ -1882,10 +2051,50 @@ std::string CCECodegen::ComputeIRBasedOffset(const ir::TensorTypePtr& tensor_typ
1882// Call Expression Visitor (uses operator registry codegen functions)2051// Call Expression Visitor (uses operator registry codegen functions)
1883// ========================================================================2052// ========================================================================
1884 2053 
2054+std::string CCECodegen::GenerateSimtCalleeCall(const ir::CallPtr& op, const ir::FunctionPtr& callee)
2055+{
2056+ CHECK(op->args_.size() == callee->params_.size())
2057+ << "SIMT callee '" << callee->name_ << "' expects " << callee->params_.size() << " arguments, got "
2058+ << op->args_.size();
2059+ 
2060+ std::ostringstream call;
2061+ call << callee->name_ << "(";
2062+ bool first = true;
2063+ auto append = [&](const std::string& value) {
2064+ if (!first) {
2065+ call << ", ";
2066+ }
2067+ first = false;
2068+ call << value;
2069+ };
2070+ 
2071+ for (size_t i = 0; i < op->args_.size(); ++i) {
2072+ const auto& actual = op->args_[i];
2073+ append(GetExprAsCode(actual));
2074+ if (ir::As<ir::TileType>(callee->params_[i]->GetType())) {
2075+ auto actual_var = ir::As<ir::Var>(actual);
2076+ CHECK(actual_var != nullptr) << "SIMT Tile callee arguments must be named Tile variables";
2077+ std::string actual_name = context_.SanitizeName(actual_var);
2078+ append(actual_name + "__valid_row");
2079+ append(actual_name + "__valid_col");
2080+ }
2081+ }
2082+ call << ")";
2083+ return call.str();
2084+}
2085+ 
1885void CCECodegen::VisitExpr_(const ir::CallPtr& op)2086void CCECodegen::VisitExpr_(const ir::CallPtr& op)
1886{2087{
1887 INTERNAL_CHECK(op != nullptr) << "Internal error: null Call";2088 INTERNAL_CHECK(op != nullptr) << "Internal error: null Call";
1888 2089 
2090+ if (IsInSimtContext()) {
2091+ auto simt_callee = simt_callees_.find(op->name_);
2092+ if (simt_callee != simt_callees_.end()) {
2093+ current_expr_value_ = GenerateSimtCalleeCall(op, simt_callee->second);
2094+ return;
2095+ }
2096+ }
2097+ 
1889 CHECK(backend_ != nullptr) << "CCE backend must not be null";2098 CHECK(backend_ != nullptr) << "CCE backend must not be null";
1890 const auto* op_info = backend_->GetOpInfo(op->name_);2099 const auto* op_info = backend_->GetOpInfo(op->name_);
1891 CHECK(op_info != nullptr) << "Unknown call '" << op->name_ << "' reached CCE codegen; helper calls must be inlined";2100 CHECK(op_info != nullptr) << "Unknown call '" << op->name_ << "' reached CCE codegen; helper calls must be inlined";
@@ -137,7 +137,7 @@ Pass pass::AggressiveDCE()
137 }137 }
138 auto newBody = std::make_shared<ir::SeqStmts>(std::move(newStmts), func->body_->span_);138 auto newBody = std::make_shared<ir::SeqStmts>(std::move(newStmts), func->body_->span_);
139 return std::make_shared<ir::Function>(func->name_, func->params_, func->returnTypes_, newBody, func->span_,139 return std::make_shared<ir::Function>(func->name_, func->params_, func->returnTypes_, newBody, func->span_,
140- func->funcType_, func->entry_);140+ func->funcType_, func->entry_, func->attrs_);
141 },141 },
142 "AggressiveDCE");142 "AggressiveDCE");
143}143}
@@ -165,6 +165,36 @@ TEST_F(BlockOpsMemoryTest, MakeTile_WithLayoutKwargs_ReturnsTileType)
165 EXPECT_EQ(rt->dtype_, DataType::FP16);165 EXPECT_EQ(rt->dtype_, DataType::FP16);
166}166}
167 167 
168+// ============================================================================
169+// memory.cpp: block.tile_valid_shape
170+// ============================================================================
171+TEST_F(BlockOpsMemoryTest, TileValidShape_ReturnsUint32)
172+{
173+ auto& reg = OpRegistry::GetInstance();
174+ auto tile = MakeTileVar("tile", {16, 32}, DataType::FP16);
175+ auto call = reg.Create("block.tile_valid_shape", {tile}, std::vector<std::pair<std::string, std::any>>{{"axis", 1}},
176+ Sp());
177+ auto rt = As<ScalarType>(call->GetType());
178+ ASSERT_NE(rt, nullptr);
179+ EXPECT_EQ(rt->dtype_, DataType::UINT32);
180+}
181+ 
182+TEST_F(BlockOpsMemoryTest, TileValidShape_RejectsInvalidAxis)
183+{
184+ auto& reg = OpRegistry::GetInstance();
185+ EXPECT_THROW((void)reg.Create("block.tile_valid_shape", {MakeTileVar("tile", {16, 32}, DataType::FP16)},
186+ std::vector<std::pair<std::string, std::any>>{{"axis", 2}}, Sp()),
187+ npu::tile_fwk::Error);
188+}
189+ 
190+TEST_F(BlockOpsMemoryTest, TileValidShape_RejectsNonTile)
191+{
192+ auto& reg = OpRegistry::GetInstance();
193+ EXPECT_THROW((void)reg.Create("block.tile_valid_shape", {MakeScalarVar("value", DataType::INT32)},
194+ std::vector<std::pair<std::string, std::any>>{{"axis", 0}}, Sp()),
195+ npu::tile_fwk::Error);
196+}
197+ 
168// ============================================================================198// ============================================================================
169// memory.cpp: block.getval, block.setval199// memory.cpp: block.getval, block.setval
170// ============================================================================200// ============================================================================
@@ -0,0 +1,117 @@
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+/**
12+ * @file test_simt_ops.cpp
13+ * \brief Type-deduction tests for the SIMT operation registry.
14+ */
15+ 
16+#include "gtest/gtest.h"
17+ 
18+#include <any>
19+#include <cstddef>
20+#include <memory>
21+#include <string>
22+#include <utility>
23+#include <vector>
24+ 
25+#include "core/dtype.h"
26+#include "ir/kind_traits.h"
27+#include "ir/op_registry.h"
28+#include "ir/scalar_expr.h"
29+#include "ir/type.h"
30+#include "test_op_helpers.h"
31+#include "tilefwk/error.h"
32+ 
33+namespace pypto {
34+namespace ir {
35+ 
36+using namespace test_helpers;
37+ 
38+using Kwargs = std::vector<std::pair<std::string, std::any>>;
39+ 
40+TEST(SimtOpsTest, ContextAndBuiltinScalarTypes)
41+{
42+ auto& registry = OpRegistry::GetInstance();
43+ const std::vector<std::string> context_ops = {"simt.thread_idx", "simt.block_dim", "simt.block_idx",
44+ "simt.grid_dim"};
45+ 
46+ for (std::size_t axis = 0; axis < context_ops.size(); ++axis) {
47+ auto call = registry.Create(context_ops[axis], {}, Kwargs{{"axis", static_cast<int>(axis % 3)}}, Sp());
48+ auto type = As<ScalarType>(call->GetType());
49+ ASSERT_NE(type, nullptr);
50+ EXPECT_EQ(type->dtype_, DataType::UINT32);
51+ }
52+ 
53+ auto linear = registry.Create("simt.linear_thread_idx", {}, Sp());
54+ auto linear_type = As<ScalarType>(linear->GetType());
55+ ASSERT_NE(linear_type, nullptr);
56+ EXPECT_EQ(linear_type->dtype_, DataType::UINT32);
57+ 
58+ auto warp = registry.Create("simt.warp_size", {}, Sp());
59+ auto warp_type = As<ScalarType>(warp->GetType());
60+ ASSERT_NE(warp_type, nullptr);
61+ EXPECT_EQ(warp_type->dtype_, DataType::INT32);
62+}
63+ 
64+TEST(SimtOpsTest, LaunchType)
65+{
66+ auto& registry = OpRegistry::GetInstance();
67+ auto scalar = MakeScalarVar("count", DataType::UINT32);
68+ 
69+ std::vector<ExprPtr> launch_args = {
70+ std::make_shared<ConstInt>(8, DataType::INT64, Sp()),
71+ std::make_shared<ConstInt>(4, DataType::INT64, Sp()),
72+ std::make_shared<ConstInt>(8, DataType::INT64, Sp()),
73+ scalar,
74+ };
75+ auto launch = registry.Create("simt.launch", launch_args,
76+ Kwargs{{"callee", std::string("simt_entry")}, {"max_threads", 256}}, Sp());
77+ 
78+ EXPECT_EQ(launch->GetType(), GetUnknownType());
79+}
80+ 
81+TEST(SimtOpsTest, RejectsInvalidContextAxisAndLaunchBounds)
82+{
83+ auto& registry = OpRegistry::GetInstance();
84+ EXPECT_THROW((void)registry.Create("simt.thread_idx", {}, Kwargs{{"axis", 3}}, Sp()), npu::tile_fwk::Error);
85+ 
86+ std::vector<ExprPtr> too_many_threads = {
87+ std::make_shared<ConstInt>(2048, DataType::INT64, Sp()),
88+ std::make_shared<ConstInt>(2, DataType::INT64, Sp()),
89+ std::make_shared<ConstInt>(1, DataType::INT64, Sp()),
90+ };
91+ EXPECT_THROW((void)registry.Create("simt.launch", too_many_threads,
92+ Kwargs{{"callee", std::string("simt_entry")}, {"max_threads", 2048}}, Sp()),
93+ npu::tile_fwk::Error);
94+}
95+ 
96+TEST(SimtOpsTest, RejectsInvalidLaunchArgumentAbi)
97+{
98+ auto& registry = OpRegistry::GetInstance();
99+ auto invalid_tensor = MakeTensorVar("tensor", {256}, DataType::FP32);
100+ std::vector<ExprPtr> tensor_args = {
101+ std::make_shared<ConstInt>(1, DataType::INT64, Sp()),
102+ std::make_shared<ConstInt>(1, DataType::INT64, Sp()),
103+ std::make_shared<ConstInt>(1, DataType::INT64, Sp()),
104+ invalid_tensor,
105+ };
106+ EXPECT_THROW((void)registry.Create("simt.launch", tensor_args,
107+ Kwargs{{"callee", std::string("simt_entry")}, {"max_threads", 1}}, Sp()),
108+ npu::tile_fwk::Error);
109+ 
110+ auto invalid_tile = MakeTileVar("tile", {1, 256}, DataType::FP32);
111+ std::vector<ExprPtr> tile_args = {tensor_args[0], tensor_args[1], tensor_args[2], invalid_tile};
112+ EXPECT_THROW((void)registry.Create("simt.launch", tile_args,
113+ Kwargs{{"callee", std::string("simt_entry")}, {"max_threads", 1}}, Sp()),
114+ npu::tile_fwk::Error);
115+}
116+} // namespace ir
117+} // namespace pypto
@@ -17,6 +17,7 @@
17 17 
18#include <cstdint>18#include <cstdint>
19#include <memory>19#include <memory>
20+#include <optional>
20#include <string>21#include <string>
21#include <utility>22#include <utility>
22#include <vector>23#include <vector>
@@ -38,12 +39,17 @@ static Span Sp() { return Span("test", 1, 1); }
38 39 
39class PassesTest : public testing::Test {40class PassesTest : public testing::Test {
40protected:41protected:
41- FunctionPtr MakeFunction(const std::string& name, int64_t value)42+ FunctionPtr MakeFunction(const std::string& name, int64_t value, FunctionType func_type = FunctionType::OPAQUE,
43+ std::optional<int> max_threads = std::nullopt)
42 {44 {
43 auto x = std::make_shared<Var>("x", Scalar(DataType::INT32), Sp());45 auto x = std::make_shared<Var>("x", Scalar(DataType::INT32), Sp());
44 auto body = std::make_shared<AssignStmt>(x, std::make_shared<ConstInt>(value, DataType::INT32, Sp()), Sp());46 auto body = std::make_shared<AssignStmt>(x, std::make_shared<ConstInt>(value, DataType::INT32, Sp()), Sp());
47+ std::vector<std::pair<std::string, std::any>> attrs;
48+ if (max_threads.has_value()) {
49+ attrs.emplace_back(kMaxThreadsAttr, *max_threads);
50+ }
45 return std::make_shared<Function>(name, std::vector<VarPtr>{x}, std::vector<TypePtr>{Scalar(DataType::INT32)},51 return std::make_shared<Function>(name, std::vector<VarPtr>{x}, std::vector<TypePtr>{Scalar(DataType::INT32)},
46- body, Sp());52+ body, Sp(), func_type, false, std::move(attrs));
47 }53 }
48 54 
49 ProgramPtr MakeSimpleProgram()55 ProgramPtr MakeSimpleProgram()
@@ -248,10 +254,15 @@ TEST_F(PassesTest, TestPassPipelineRun)
248 return prog;254 return prog;
249 },255 },
250 "Counter2"));256 "Counter2"));
251- auto prog = MakeSimpleProgram();257+ auto function = MakeFunction("f", 1, FunctionType::SIMT_VF, 256);
258+ auto prog = std::make_shared<Program>(std::vector<FunctionPtr>{function}, "prog", Sp());
252 auto result = pipeline.Run(prog);259 auto result = pipeline.Run(prog);
253- EXPECT_NE(result, nullptr);260+ ASSERT_NE(result, nullptr);
254 EXPECT_EQ(call_count, 2);261 EXPECT_EQ(call_count, 2);
262+ auto result_function = result->GetFunction("f");
263+ ASSERT_NE(result_function, nullptr);
264+ ASSERT_TRUE(result_function->HasAttr(kMaxThreadsAttr));
265+ EXPECT_EQ(result_function->GetAttr<int>(kMaxThreadsAttr), 256);
255}266}
256 267 
257} // namespace ir268} // namespace ir
@@ -458,6 +458,33 @@ TEST_F(IRPrinterTest, TestPrintProgram)
458 EXPECT_NE(progStr.find("f2"), std::string::npos);458 EXPECT_NE(progStr.find("f2"), std::string::npos);
459}459}
460 460 
461+TEST_F(IRPrinterTest, TestPrintSimtFunctionDecorators)
462+{
463+ auto body = std::make_shared<ReturnStmt>(Sp());
464+ auto simt_function = std::make_shared<Function>(
465+ "entry", std::vector<VarPtr>{}, std::vector<TypePtr>{}, body, Sp(), FunctionType::SIMT_VF, false,
466+ std::vector<std::pair<std::string, std::any>>{{kMaxThreadsAttr, 256}});
467+ auto unbounded_simt_function = std::make_shared<Function>(
468+ "unbounded", std::vector<VarPtr>{}, std::vector<TypePtr>{}, body, Sp(), FunctionType::SIMT_VF);
469+ auto simt_callee = std::make_shared<Function>("helper", std::vector<VarPtr>{}, std::vector<TypePtr>{}, body, Sp(),
470+ FunctionType::SIMT_CALLEE);
471+ 
472+ auto function_str = Print(simt_function);
473+ auto unbounded_function_str = Print(unbounded_simt_function);
474+ auto callee_str = Print(simt_callee);
475+ 
476+ EXPECT_NE(function_str.find("@ir.simt.function"), std::string::npos);
477+ EXPECT_NE(function_str.find("ir.FunctionType.SimtVF"), std::string::npos);
478+ EXPECT_EQ(function_str.find("max_threads"), std::string::npos);
479+ EXPECT_NE(function_str.find("def entry()"), std::string::npos);
480+ EXPECT_NE(unbounded_function_str.find("@ir.simt.function"), std::string::npos);
481+ EXPECT_NE(unbounded_function_str.find("ir.FunctionType.SimtVF"), std::string::npos);
482+ EXPECT_EQ(unbounded_function_str.find("max_threads"), std::string::npos);
483+ EXPECT_NE(callee_str.find("@ir.simt.function"), std::string::npos);
484+ EXPECT_NE(callee_str.find("ir.FunctionType.SimtCallee"), std::string::npos);
485+ EXPECT_NE(callee_str.find("def helper()"), std::string::npos);
486+}
487+ 
461// ============================================================================488// ============================================================================
462// Control flow with SeqStmts body489// Control flow with SeqStmts body
463// ============================================================================490// ============================================================================
@@ -685,6 +685,23 @@ TEST_F(IRStructEqExprTest, TestFunctionReturnTypesElementMismatch)
685 EXPECT_FALSE(structural_equal(Node(f1), Node(f2)));685 EXPECT_FALSE(structural_equal(Node(f1), Node(f2)));
686}686}
687 687 
688+TEST_F(IRStructEqExprTest, TestFunctionMaxThreadsMismatch)
689+{
690+ auto body = std::make_shared<YieldStmt>(std::vector<ExprPtr>{}, Sp());
691+ auto f128 = std::make_shared<Function>("f", std::vector<VarPtr>{}, std::vector<TypePtr>{}, body, Sp(),
692+ FunctionType::SIMT_VF, false,
693+ std::vector<std::pair<std::string, std::any>>{{kMaxThreadsAttr, 128}});
694+ auto f256 = std::make_shared<Function>("f", std::vector<VarPtr>{}, std::vector<TypePtr>{}, body, Sp(),
695+ FunctionType::SIMT_VF, false,
696+ std::vector<std::pair<std::string, std::any>>{{kMaxThreadsAttr, 256}});
697+ auto unbounded = std::make_shared<Function>("f", std::vector<VarPtr>{}, std::vector<TypePtr>{}, body, Sp(),
698+ FunctionType::SIMT_VF);
699+ 
700+ EXPECT_FALSE(structural_equal(Node(f128), Node(f256)));
701+ EXPECT_FALSE(structural_equal(Node(f128), Node(unbounded)));
702+ EXPECT_THROW(assert_structural_equal(Node(f128), Node(f256)), npu::tile_fwk::Error);
703+}
704+ 
688// ============================================================================705// ============================================================================
689// IterArg vector size mismatch706// IterArg vector size mismatch
690// ============================================================================707// ============================================================================
@@ -313,6 +313,26 @@ TEST_F(IRStructHashTest, TestHashFunction)
313 EXPECT_EQ(structural_hash(Node(f1)), structural_hash(Node(f2)));313 EXPECT_EQ(structural_hash(Node(f1)), structural_hash(Node(f2)));
314}314}
315 315 
316+TEST_F(IRStructHashTest, TestHashFunctionMaxThreads)
317+{
318+ auto body = std::make_shared<YieldStmt>(std::vector<ExprPtr>{}, Sp());
319+ auto f128a = std::make_shared<Function>("f", std::vector<VarPtr>{}, std::vector<TypePtr>{}, body, Sp(),
320+ FunctionType::SIMT_VF, false,
321+ std::vector<std::pair<std::string, std::any>>{{kMaxThreadsAttr, 128}});
322+ auto f128b = std::make_shared<Function>("f", std::vector<VarPtr>{}, std::vector<TypePtr>{}, body, Sp(),
323+ FunctionType::SIMT_VF, false,
324+ std::vector<std::pair<std::string, std::any>>{{kMaxThreadsAttr, 128}});
325+ auto f256 = std::make_shared<Function>("f", std::vector<VarPtr>{}, std::vector<TypePtr>{}, body, Sp(),
326+ FunctionType::SIMT_VF, false,
327+ std::vector<std::pair<std::string, std::any>>{{kMaxThreadsAttr, 256}});
328+ auto unbounded = std::make_shared<Function>("f", std::vector<VarPtr>{}, std::vector<TypePtr>{}, body, Sp(),
329+ FunctionType::SIMT_VF);
330+ 
331+ EXPECT_EQ(structural_hash(Node(f128a)), structural_hash(Node(f128b)));
332+ EXPECT_NE(structural_hash(Node(f128a)), structural_hash(Node(f256)));
333+ EXPECT_NE(structural_hash(Node(f128a)), structural_hash(Node(unbounded)));
334+}
335+ 
316TEST_F(IRStructHashTest, TestHashProgram)336TEST_F(IRStructHashTest, TestHashProgram)
317{337{
318 auto x = std::make_shared<Var>("x", Scalar(DataType::INT32), Sp());338 auto x = std::make_shared<Var>("x", Scalar(DataType::INT32), Sp());
@@ -379,6 +379,26 @@ TEST(CCECodegenTest, ClearsTupleBackingArraysBetweenGenerations)
379 EXPECT_NE(second.find("int64_t values"), std::string::npos);379 EXPECT_NE(second.find("int64_t values"), std::string::npos);
380}380}
381 381 
382+TEST(CCECodegenTest, ClearsTileTypeStateBetweenGenerations)
383+{
384+ auto tile_type = std::make_shared<const ir::TileType>(std::vector<int64_t>{16, 16}, ir::DataType::FP16,
385+ std::optional<ir::MemRefPtr>(std::nullopt),
386+ std::optional<ir::TileView>(std::nullopt));
387+ auto tile = MakeVar("tile", tile_type);
388+ auto make_tile = std::make_shared<const ir::Call>("block.make_tile", std::vector<ir::ExprPtr>{}, tile_type,
389+ ir::Span::Unknown());
390+ auto body = std::make_shared<const ir::AssignStmt>(tile, make_tile, ir::Span::Unknown());
391+ auto program = MakeProgram(body);
392+ 
393+ CCECodegen codegen(ir::SectionKind::Vector);
394+ auto first = codegen.GenerateSingle(program, "a5");
395+ auto second = codegen.GenerateSingle(program, "a5");
396+ 
397+ constexpr const char* tile_type_declaration = "using tile_Type = ";
398+ EXPECT_NE(first.find(tile_type_declaration), std::string::npos);
399+ EXPECT_NE(second.find(tile_type_declaration), std::string::npos);
400+}
401+ 
382TEST(CCECodegenTest, MaterializesHomogeneousTileTuple)402TEST(CCECodegenTest, MaterializesHomogeneousTileTuple)
383{403{
384 auto index_type = std::make_shared<const ir::ScalarType>(ir::DataType::INT64);404 auto index_type = std::make_shared<const ir::ScalarType>(ir::DataType::INT64);
@@ -718,6 +738,33 @@ TEST(CCECodegenTest, HoistsDynamicVFLoopBoundAsUint16)
718 EXPECT_NE(generated.find("for (uint16_t i_0 = 0; i_0 < i_0_ub; i_0 += 1)"), std::string::npos);738 EXPECT_NE(generated.find("for (uint16_t i_0 = 0; i_0 < i_0_ub; i_0 += 1)"), std::string::npos);
719}739}
720 740 
741+TEST(CCECodegenTest, EmitsKernelTileValidShapeGetters)
742+{
743+ auto tile_type = std::make_shared<const ir::TileType>(std::vector<int64_t>{16, 32}, ir::DataType::FP16,
744+ std::optional<ir::MemRefPtr>(std::nullopt),
745+ std::optional<ir::TileView>(std::nullopt));
746+ auto u32 = std::make_shared<const ir::ScalarType>(ir::DataType::UINT32);
747+ auto tile = MakeVar("tile", tile_type);
748+ auto make_tile = std::make_shared<const ir::Call>("block.make_tile", std::vector<ir::ExprPtr>{}, tile_type,
749+ ir::Span::Unknown());
750+ auto valid_shape = [&](int axis) {
751+ return std::make_shared<const ir::Call>("block.tile_valid_shape", std::vector<ir::ExprPtr>{tile},
752+ std::vector<std::pair<std::string, std::any>>{{"axis", axis}}, u32,
753+ ir::Span::Unknown());
754+ };
755+ auto body = std::make_shared<const ir::SeqStmts>(
756+ std::vector<ir::StmtPtr>{
757+ std::make_shared<const ir::AssignStmt>(tile, make_tile, ir::Span::Unknown()),
758+ std::make_shared<const ir::AssignStmt>(MakeVar("rows", u32), valid_shape(0), ir::Span::Unknown()),
759+ std::make_shared<const ir::AssignStmt>(MakeVar("cols", u32), valid_shape(1), ir::Span::Unknown()),
760+ },
761+ ir::Span::Unknown());
762+ CCECodegen codegen(ir::SectionKind::Vector);
763+ std::string generated = codegen.GenerateSingle(MakeProgram(body), "a5");
764+ EXPECT_NE(generated.find(".GetValidRow()"), std::string::npos);
765+ EXPECT_NE(generated.find(".GetValidCol()"), std::string::npos);
766+}
767+ 
721TEST(CCECodegenTest, ComputesIRBasedOffsetAndRejectsRankMismatch)768TEST(CCECodegenTest, ComputesIRBasedOffsetAndRejectsRankMismatch)
722{769{
723 auto tensor_type = std::make_shared<const ir::TensorType>(std::vector<int64_t>{2, 3, 4}, ir::DataType::FP16,770 auto tensor_type = std::make_shared<const ir::TensorType>(std::vector<int64_t>{2, 3, 4}, ir::DataType::FP16,
@@ -0,0 +1,328 @@
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+/**
12+ * @file test_cce_simt_codegen.cpp
13+ * \brief End-to-end CCE codegen tests for SIMT functions, callees, context operations, and launch.
14+ */
15+ 
16+#include "gtest/gtest.h"
17+ 
18+#include <any>
19+#include <cstddef>
20+#include <cstdint>
21+#include <memory>
22+#include <optional>
23+#include <string>
24+#include <utility>
25+#include <vector>
26+ 
27+#include "codegen/cce/cce_codegen.h"
28+#include "core/dtype.h"
29+#include "ir/expr.h"
30+#include "ir/function.h"
31+#include "ir/memref.h"
32+#include "ir/program.h"
33+#include "ir/scalar_expr.h"
34+#include "ir/stmt.h"
35+#include "ir/type.h"
36+#include "tilefwk/error.h"
37+ 
38+namespace pypto {
39+namespace codegen {
40+namespace {
41+ 
42+using Kwargs = std::vector<std::pair<std::string, std::any>>;
43+ 
44+ir::Span Sp() { return ir::Span::Unknown(); }
45+ 
46+ir::ExprPtr ConstInt(int64_t value) { return std::make_shared<const ir::ConstInt>(value, ir::DataType::INT64, Sp()); }
47+ 
48+ir::TypePtr Scalar(ir::DataType dtype) { return std::make_shared<const ir::ScalarType>(dtype); }
49+ 
50+ir::VarPtr Var(const std::string& name, const ir::TypePtr& type)
51+{
52+ return std::make_shared<const ir::Var>(name, type, Sp());
53+}
54+ 
55+ir::TileTypePtr MakeSimtTileType()
56+{
57+ auto memref = std::make_shared<const ir::MemRef>(ir::MemorySpace::Vec, ConstInt(0), 1024);
58+ return std::make_shared<const ir::TileType>(
59+ std::vector<int64_t>{1, 256}, ir::DataType::FP32, std::optional<ir::MemRefPtr>(memref),
60+ std::optional<ir::TileView>(std::nullopt), std::optional<ir::HardwareInfo>(ir::HardwareInfo{}));
61+}
62+ 
63+ir::TensorTypePtr MakeSimtTensorType(const std::string& name)
64+{
65+ auto ptr = Var(name + "_base", std::make_shared<const ir::PtrType>(ir::DataType::FP32));
66+ ir::TensorView view({}, ir::TensorLayout::ND, ptr);
67+ return std::make_shared<const ir::TensorType>(std::vector<int64_t>{256}, ir::DataType::FP32,
68+ std::optional<ir::MemRefPtr>(std::nullopt),
69+ std::optional<ir::TensorView>(view));
70+}
71+ 
72+ir::CallPtr Call(const std::string& name, std::vector<ir::ExprPtr> args, const ir::TypePtr& type)
73+{
74+ return std::make_shared<const ir::Call>(name, std::move(args), type, Sp());
75+}
76+ 
77+ir::CallPtr Call(const std::string& name, std::vector<ir::ExprPtr> args, Kwargs kwargs, const ir::TypePtr& type)
78+{
79+ return std::make_shared<const ir::Call>(name, std::move(args), std::move(kwargs), type, Sp());
80+}
81+ 
82+ir::StmtPtr Eval(const ir::ExprPtr& expr) { return std::make_shared<const ir::EvalStmt>(expr, Sp()); }
83+ 
84+ir::StmtPtr Assign(const ir::VarPtr& var, const ir::ExprPtr& value)
85+{
86+ return std::make_shared<const ir::AssignStmt>(var, value, Sp());
87+}
88+ 
89+ir::StmtPtr Seq(std::vector<ir::StmtPtr> stmts) { return std::make_shared<const ir::SeqStmts>(std::move(stmts), Sp()); }
90+ 
91+std::string FindLineContaining(const std::string& text, const std::string& needle)
92+{
93+ auto pos = text.find(needle);
94+ if (pos == std::string::npos) {
95+ return "";
96+ }
97+ auto line_begin = text.rfind('\n', pos);
98+ line_begin = line_begin == std::string::npos ? 0 : line_begin + 1;
99+ auto line_end = text.find('\n', pos);
100+ return text.substr(line_begin, line_end - line_begin);
101+}
102+ 
103+std::size_t CountOccurrences(const std::string& text, const std::string& needle)
104+{
105+ std::size_t count = 0;
106+ std::size_t pos = 0;
107+ while ((pos = text.find(needle, pos)) != std::string::npos) {
108+ ++count;
109+ pos += needle.size();
110+ }
111+ return count;
112+}
113+ 
114+ir::FunctionPtr MakeScalarAddCallee(const ir::TypePtr& fp32)
115+{
116+ auto value = Var("value", fp32);
117+ auto delta = Var("delta", fp32);
118+ auto sum = std::make_shared<const ir::Add>(value, delta, ir::DataType::FP32, Sp());
119+ auto body = std::make_shared<const ir::ReturnStmt>(std::vector<ir::ExprPtr>{sum}, Sp());
120+ return std::make_shared<const ir::Function>("add_scalar", std::vector<ir::VarPtr>{value, delta},
121+ std::vector<ir::TypePtr>{fp32}, body, Sp(),
122+ ir::FunctionType::SIMT_CALLEE);
123+}
124+ 
125+ir::FunctionPtr MakeStoreCallee(const ir::TileTypePtr& tile_type, const ir::TypePtr& u32, const ir::TypePtr& fp32)
126+{
127+ auto tile = Var("tile", tile_type);
128+ auto index = Var("index", u32);
129+ auto value = Var("value", fp32);
130+ auto store = Call("block.setval", {tile, index, value}, ir::GetUnknownType());
131+ auto body = Seq({Eval(store), std::make_shared<const ir::ReturnStmt>(Sp())});
132+ return std::make_shared<const ir::Function>("store_scalar", std::vector<ir::VarPtr>{tile, index, value},
133+ std::vector<ir::TypePtr>{}, body, Sp(), ir::FunctionType::SIMT_CALLEE);
134+}
135+ 
136+ir::FunctionPtr MakeApplyCallee(const ir::TileTypePtr& tile_type, const ir::TypePtr& u32, const ir::TypePtr& fp32)
137+{
138+ auto tile = Var("tile", tile_type);
139+ auto index = Var("index", u32);
140+ auto delta = Var("delta", fp32);
141+ auto value = Var("value", fp32);
142+ auto updated = Var("updated", fp32);
143+ auto load = Call("block.getval", {tile, index}, fp32);
144+ auto add = Call("add_scalar", {value, delta}, fp32);
145+ auto store = Call("store_scalar", {tile, index, updated}, ir::GetUnknownType());
146+ auto body = Seq({Assign(value, load), Assign(updated, add), Eval(store),
147+ std::make_shared<const ir::ReturnStmt>(std::vector<ir::ExprPtr>{updated}, Sp())});
148+ return std::make_shared<const ir::Function>("apply_scalar", std::vector<ir::VarPtr>{tile, index, delta},
149+ std::vector<ir::TypePtr>{fp32}, body, Sp(),
150+ ir::FunctionType::SIMT_CALLEE);
151+}
152+ 
153+ir::FunctionPtr MakeSimtEntry(const ir::TileTypePtr& tile_type, const ir::TensorTypePtr& tensor_type,
154+ const ir::TypePtr& u32, const ir::TypePtr& i32, const ir::TypePtr& fp32)
155+{
156+ auto tile = Var("tile", tile_type);
157+ auto tensor = Var("tensor", tensor_type);
158+ auto count = Var("count", u32);
159+ auto delta = Var("delta", fp32);
160+ auto thread_x = Var("thread_x", u32);
161+ auto block_y = Var("block_y", u32);
162+ auto block_z = Var("block_z", u32);
163+ auto grid_x = Var("grid_x", u32);
164+ auto tid = Var("tid", u32);
165+ auto warp = Var("warp", i32);
166+ auto rows = Var("rows", u32);
167+ auto cols = Var("cols", u32);
168+ auto updated = Var("updated", fp32);
169+ 
170+ auto context_call = [&](const std::string& name, int axis) { return Call(name, {}, Kwargs{{"axis", axis}}, u32); };
171+ auto body = Seq({
172+ Assign(thread_x, context_call("simt.thread_idx", 0)),
173+ Assign(block_y, context_call("simt.block_dim", 1)),
174+ Assign(block_z, context_call("simt.block_idx", 2)),
175+ Assign(grid_x, context_call("simt.grid_dim", 0)),
176+ Assign(tid, Call("simt.linear_thread_idx", {}, u32)),
177+ Assign(warp, Call("simt.warp_size", {}, i32)),
178+ Assign(rows, Call("block.tile_valid_shape", {tile}, Kwargs{{"axis", 0}}, u32)),
179+ Assign(cols, Call("block.tile_valid_shape", {tile}, Kwargs{{"axis", 1}}, u32)),
180+ Assign(updated, Call("apply_scalar", {tile, tid, delta}, fp32)),
181+ Eval(Call("block.setval", {tensor, tid, updated}, ir::GetUnknownType())),
182+ });
183+ return std::make_shared<const ir::Function>(
184+ "simt_entry", std::vector<ir::VarPtr>{tile, tensor, count, delta}, std::vector<ir::TypePtr>{}, body, Sp(),
185+ ir::FunctionType::SIMT_VF, false, std::vector<std::pair<std::string, std::any>>{{ir::kMaxThreadsAttr, 256}});
186+}
187+ 
188+ir::ProgramPtr MakeSimtProgram()
189+{
190+ auto u32 = Scalar(ir::DataType::UINT32);
191+ auto i32 = Scalar(ir::DataType::INT32);
192+ auto fp32 = Scalar(ir::DataType::FP32);
193+ auto tile_type = MakeSimtTileType();
194+ auto tensor_type = MakeSimtTensorType("tensor");
195+ 
196+ auto tensor = Var("tensor", tensor_type);
197+ auto count = Var("count", u32);
198+ auto delta = Var("delta", fp32);
199+ auto tile = Var("tile", tile_type);
200+ auto make_tile = Call("block.make_tile", {}, tile_type);
201+ auto launch = Call("simt.launch", {ConstInt(8), ConstInt(4), ConstInt(8), tile, tensor, count, delta},
202+ Kwargs{{"callee", std::string("simt_entry")}, {"max_threads", 256}}, ir::GetUnknownType());
203+ auto kernel_body = Seq({Assign(tile, make_tile), Eval(launch)});
204+ auto kernel = std::make_shared<const ir::Function>("kernel", std::vector<ir::VarPtr>{tensor, count, delta},
205+ std::vector<ir::TypePtr>{}, kernel_body, Sp(),
206+ ir::FunctionType::IN_CORE, true);
207+ 
208+ std::vector<ir::FunctionPtr> functions = {MakeScalarAddCallee(fp32), MakeStoreCallee(tile_type, u32, fp32),
209+ MakeApplyCallee(tile_type, u32, fp32),
210+ MakeSimtEntry(tile_type, tensor_type, u32, i32, fp32), kernel};
211+ return std::make_shared<const ir::Program>(std::move(functions), "simt_program", Sp());
212+}
213+ 
214+ir::ProgramPtr MakeSimtCalleeNameCollisionProgram()
215+{
216+ auto i32 = Scalar(ir::DataType::INT32);
217+ auto callee_body = std::make_shared<const ir::ReturnStmt>(Sp());
218+ auto callee = std::make_shared<const ir::Function>("get_subblock_idx", std::vector<ir::VarPtr>{},
219+ std::vector<ir::TypePtr>{}, callee_body, Sp(),
220+ ir::FunctionType::SIMT_CALLEE);
221+ 
222+ auto simt_body = Eval(Call("get_subblock_idx", {}, ir::GetUnknownType()));
223+ auto simt_entry = std::make_shared<const ir::Function>(
224+ "collision_entry", std::vector<ir::VarPtr>{}, std::vector<ir::TypePtr>{}, simt_body, Sp(),
225+ ir::FunctionType::SIMT_VF, false, std::vector<std::pair<std::string, std::any>>{{ir::kMaxThreadsAttr, 32}});
226+ 
227+ auto subblock_idx = Var("subblock_idx", i32);
228+ auto backend_call = Call("get_subblock_idx", {}, i32);
229+ auto launch = Call("simt.launch", {ConstInt(32), ConstInt(1), ConstInt(1)},
230+ Kwargs{{"callee", std::string("collision_entry")}, {"max_threads", 32}}, ir::GetUnknownType());
231+ auto kernel_body = Seq({Assign(subblock_idx, backend_call), Eval(backend_call), Eval(launch)});
232+ auto kernel = std::make_shared<const ir::Function>("kernel", std::vector<ir::VarPtr>{}, std::vector<ir::TypePtr>{},
233+ kernel_body, Sp(), ir::FunctionType::IN_CORE, true);
234+ 
235+ return std::make_shared<const ir::Program>(std::vector<ir::FunctionPtr>{callee, simt_entry, kernel},
236+ "simt_callee_name_collision", Sp());
237+}
238+ 
239+} // namespace
240+ 
241+TEST(CCESimtCodegenTest, GeneratesContextCalleesMemoryAccessAndLaunch)
242+{
243+ CCECodegen codegen(ir::SectionKind::Vector);
244+ std::string generated = codegen.GenerateSingle(MakeSimtProgram(), "a5");
245+ 
246+ auto add_pos = generated.find("__simt_callee__ inline float add_scalar(");
247+ auto store_pos = generated.find("__simt_callee__ inline void store_scalar(");
248+ auto apply_pos = generated.find("__simt_callee__ inline float apply_scalar(");
249+ auto entry_pos = generated.find("__simt_vf__ __launch_bounds__(256) inline void simt_entry(");
250+ ASSERT_NE(add_pos, std::string::npos);
251+ ASSERT_NE(store_pos, std::string::npos);
252+ ASSERT_NE(apply_pos, std::string::npos);
253+ ASSERT_NE(entry_pos, std::string::npos);
254+ EXPECT_LT(add_pos, apply_pos);
255+ EXPECT_LT(store_pos, apply_pos);
256+ EXPECT_LT(apply_pos, entry_pos);
257+ 
258+ auto store_signature = FindLineContaining(generated, "__simt_callee__ inline void store_scalar(");
259+ auto apply_signature = FindLineContaining(generated, "__simt_callee__ inline float apply_scalar(");
260+ auto entry_signature = FindLineContaining(generated, "__simt_vf__ __launch_bounds__(256) inline void simt_entry(");
261+ ASSERT_FALSE(store_signature.empty());
262+ ASSERT_FALSE(apply_signature.empty());
263+ ASSERT_FALSE(entry_signature.empty());
264+ EXPECT_NE(store_signature.find("__ubuf__ float*"), std::string::npos);
265+ EXPECT_NE(store_signature.find("__valid_row"), std::string::npos);
266+ EXPECT_NE(store_signature.find("__valid_col"), std::string::npos);
267+ EXPECT_NE(apply_signature.find("__ubuf__ float*"), std::string::npos);
268+ EXPECT_NE(entry_signature.find("__gm__ float*"), std::string::npos);
269+ 
270+ EXPECT_NE(generated.find("threadIdx.x"), std::string::npos);
271+ EXPECT_NE(generated.find("blockDim.y"), std::string::npos);
272+ EXPECT_NE(generated.find("blockIdx.z"), std::string::npos);
273+ EXPECT_NE(generated.find("gridDim.x"), std::string::npos);
274+ EXPECT_NE(generated.find("threadIdx.y * blockDim.x"), std::string::npos);
275+ EXPECT_NE(generated.find("warpSize"), std::string::npos);
276+ 
277+ auto store_function = generated.substr(store_pos, apply_pos - store_pos);
278+ auto apply_function = generated.substr(apply_pos, entry_pos - apply_pos);
279+ auto entry_function_end = generated.find("__aicore__ inline void kernel_impl_vector(", entry_pos);
280+ ASSERT_NE(entry_function_end, std::string::npos);
281+ auto entry_function = generated.substr(entry_pos, entry_function_end - entry_pos);
282+ EXPECT_NE(store_function.find("] ="), std::string::npos);
283+ EXPECT_EQ(store_function.find(".SetValue("), std::string::npos);
284+ EXPECT_NE(apply_function.find("["), std::string::npos);
285+ EXPECT_EQ(apply_function.find(".GetValue("), std::string::npos);
286+ EXPECT_NE(apply_function.find("store_scalar("), std::string::npos);
287+ EXPECT_NE(entry_function.find("apply_scalar("), std::string::npos);
288+ EXPECT_NE(entry_function.find("*((__gm__ float*)"), std::string::npos);
289+ 
290+ auto launch_line = FindLineContaining(generated, "cce::async_invoke<simt_entry>");
291+ ASSERT_FALSE(launch_line.empty());
292+ EXPECT_NE(launch_line.find("cce::dim3{8, 4, 8}"), std::string::npos);
293+ EXPECT_EQ(CountOccurrences(launch_line, "(__ubuf__ float*)"), 1u);
294+ EXPECT_EQ(CountOccurrences(launch_line, ".data()"), 1u);
295+ EXPECT_EQ(CountOccurrences(launch_line, ".GetValidRow()"), 1u);
296+ EXPECT_EQ(CountOccurrences(launch_line, ".GetValidCol()"), 1u);
297+ EXPECT_EQ(CountOccurrences(launch_line, "(__gm__ float*)"), 1u);
298+ EXPECT_EQ(generated.find("pipe_barrier(PIPE_ALL);"), std::string::npos);
299+ EXPECT_NE(generated.find("__aicore__ inline void kernel_impl_vector("), std::string::npos);
300+}
301+ 
302+TEST(CCESimtCodegenTest, RejectsUnsupportedTargetAndArchitecture)
303+{
304+ CCECodegen cube_codegen(ir::SectionKind::Cube);
305+ EXPECT_THROW((void)cube_codegen.GenerateSingle(MakeSimtProgram(), "a5"), npu::tile_fwk::Error);
306+ 
307+ CCECodegen vector_codegen(ir::SectionKind::Vector);
308+ EXPECT_THROW((void)vector_codegen.GenerateSingle(MakeSimtProgram(), "a3"), npu::tile_fwk::Error);
309+}
310+ 
311+TEST(CCESimtCodegenTest, DoesNotInterceptOrdinaryKernelCallsWithMatchingCalleeName)
312+{
313+ CCECodegen codegen(ir::SectionKind::Vector);
314+ std::string generated = codegen.GenerateSingle(MakeSimtCalleeNameCollisionProgram(), "a5");
315+ 
316+ auto entry_pos = generated.find("__simt_vf__ __launch_bounds__(32) inline void collision_entry(");
317+ auto kernel_pos = generated.find("__aicore__ inline void kernel_impl_vector(");
318+ ASSERT_NE(entry_pos, std::string::npos);
319+ ASSERT_NE(kernel_pos, std::string::npos);
320+ 
321+ auto entry_function = generated.substr(entry_pos, kernel_pos - entry_pos);
322+ auto kernel_function = generated.substr(kernel_pos);
323+ EXPECT_EQ(CountOccurrences(entry_function, "get_subblock_idx();"), 1u);
324+ EXPECT_EQ(CountOccurrences(kernel_function, "(int32_t)(get_subblockid())"), 1u);
325+}
326+ 
327+} // namespace codegen
328+} // namespace pypto
@@ -853,12 +853,16 @@ class FunctionType(enum.IntEnum):
853 - Orchestration: Host/AICPU control and coordination853 - Orchestration: Host/AICPU control and coordination
854 - InCore: AICore sub-graph execution854 - InCore: AICore sub-graph execution
855 - Helper: Scalar helper function callable from kernels855 - Helper: Scalar helper function callable from kernels
856+ - SimtVF: A5 SIMT vector function launched from an AIV kernel
857+ - SimtCallee: A5 helper callable from SIMT functions
856 """858 """
857 859 
858 Opaque = ...860 Opaque = ...
859 Orchestration = ...861 Orchestration = ...
860 InCore = ...862 InCore = ...
861 Helper = ...863 Helper = ...
864+ SimtVF = ...
865+ SimtCallee = ...
862 866 
863 867 
864class PtrType(Type):868class PtrType(Type):
@@ -1574,7 +1578,13 @@ class Function(IRNode):
1574 """Function name."""1578 """Function name."""
1575 1579 
1576 func_type: Final[FunctionType]1580 func_type: Final[FunctionType]
1577- """Function type (Opaque, Orchestration, InCore, AIC, AIV, or Group)."""1581+ """Function type (Opaque, Orchestration, InCore, Helper, SimtVF, or SimtCallee)."""
1582+ 
1583+ entry: Final[bool]
1584+ """Whether this is the program entry function."""
1585+ 
1586+ attrs: Final[dict[str, object]]
1587+ """Function attributes (key-value metadata)."""
1578 1588 
1579 params: Final[list[Var]]1589 params: Final[list[Var]]
1580 """Parameter variables."""1590 """Parameter variables."""
@@ -1585,6 +1595,14 @@ class Function(IRNode):
1585 body: Final[SeqStmts]1595 body: Final[SeqStmts]
1586 """Function body statement (use SeqStmts for multiple statements)."""1596 """Function body statement (use SeqStmts for multiple statements)."""
1587 1597 
1598+ def has_attr(self, key: str) -> bool:
1599+ """Check whether a function attribute exists."""
1600+ ...
1601+ 
1602+ def get_attr(self, key: str, default_value: int = 0) -> int:
1603+ """Get an integer function attribute."""
1604+ ...
1605+ 
1588 def __init__(1606 def __init__(
1589 self,1607 self,
1590 name: str,1608 name: str,
@@ -1593,6 +1611,8 @@ class Function(IRNode):
1593 body: Stmt,1611 body: Stmt,
1594 span: Span,1612 span: Span,
1595 type: FunctionType = FunctionType.Opaque,1613 type: FunctionType = FunctionType.Opaque,
1614+ entry: bool = False,
1615+ attrs: dict[str, object] | None = None,
1596 ) -> None:1616 ) -> None:
1597 """Create a function definition.1617 """Create a function definition.
1598 1618 
@@ -1603,6 +1623,8 @@ class Function(IRNode):
1603 body: Function body statement (use SeqStmts for multiple statements)1623 body: Function body statement (use SeqStmts for multiple statements)
1604 span: Source location1624 span: Source location
1605 type: Function type (default: Opaque)1625 type: Function type (default: Opaque)
1626+ entry: Whether this is the program entry function
1627+ attrs: Function attributes (key-value metadata)
1606 """1628 """
1607 1629 
1608 def __str__(self) -> str:1630 def __str__(self) -> str:
@@ -22,6 +22,7 @@ __all__ = [
22 "tensor",22 "tensor",
23 "ptr",23 "ptr",
24 "scalar",24 "scalar",
25+ "simt",
25]26]
26 27 
27 28 
@@ -29,5 +30,6 @@ from . import block_ops as block
29from . import debug_ops as debug30from . import debug_ops as debug
30from . import ptr_ops as ptr31from . import ptr_ops as ptr
31from . import scalar_ops as scalar32from . import scalar_ops as scalar
33+from . import simt_ops as simt
32from . import system_ops as system34from . import system_ops as system
33from . import tensor_ops as tensor35from . import tensor_ops as tensor
@@ -0,0 +1,213 @@
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+"""IR builders and parse handlers used by the PyPTO Pro SIMT frontend."""
13+ 
14+from __future__ import annotations
15+ 
16+import ast
17+from collections.abc import Sequence
18+from typing import Any
19+ 
20+from pypto.pypto_impl import ir as _ir_core
21+from pypto.pypto_impl.ir import Call, Expr, Function, Span
22+ 
23+from .._utils import _get_span_or_capture, _normalize_expr
24+from ._op_registry import op_impl
25+ 
26+_DIM3_FIELDS = ("x", "y", "z")
27+ 
28+ 
29+def _make_dim3_components(op_name: str, span: Span) -> list[Call]:
30+ return [_ir_core.create_op_call(op_name, [], {"axis": axis}, span) for axis in range(len(_DIM3_FIELDS))]
31+ 
32+ 
33+def _make_dim3_context(op_name: str, span: Span | None = None) -> Expr:
34+ """Build a three-component SIMT context tuple."""
35+ actual_span = _get_span_or_capture(span)
36+ return _ir_core.MakeTuple(_make_dim3_components(op_name, actual_span), actual_span)
37+ 
38+ 
39+def linear_thread_idx(span: Span | None = None) -> Call:
40+ """Return the x-major flattened thread index within the current block."""
41+ actual_span = _get_span_or_capture(span)
42+ return _ir_core.create_op_call("simt.linear_thread_idx", [], {}, actual_span)
43+ 
44+ 
45+def warp_size(span: Span | None = None) -> Call:
46+ """Return the target SIMT warp size."""
47+ actual_span = _get_span_or_capture(span)
48+ return _ir_core.create_op_call("simt.warp_size", [], {}, actual_span)
49+ 
50+ 
51+def launch(
52+ callee: Function,
53+ *,
54+ threads: int | Expr | tuple[int | Expr, ...],
55+ args: Sequence[Expr],
56+ span: Span | None = None,
57+) -> Call:
58+ """Build a SIMT launch call.
59+ 
60+ Normal DSL source is parsed specially so the callee Function is retained in
61+ the enclosing Program. This builder is primarily useful for direct IR tests.
62+ """
63+ actual_span = _get_span_or_capture(span)
64+ thread_dims = list(threads) if isinstance(threads, tuple) else [threads]
65+ if not 1 <= len(thread_dims) <= 3:
66+ raise ValueError("SIMT launch threads must contain one to three dimensions")
67+ thread_dims.extend([1] * (3 - len(thread_dims)))
68+ normalized_dims = [_normalize_expr(dim, actual_span) for dim in thread_dims]
69+ return _ir_core.create_op_call(
70+ "simt.launch",
71+ [*normalized_dims, *args],
72+ {"callee": callee.name, "max_threads": callee.get_attr("max_threads")},
73+ actual_span,
74+ )
75+ 
76+ 
77+def _validate_simt_body_op(parser: Any, call: ast.Call, _kwargs: dict[str, Any]) -> None:
78+ """Validate the common source constraints of a SIMT body operation."""
79+ from pypto_pro.language.parser.diagnostics import ParserSyntaxError
80+ 
81+ span = parser.span_tracker.get_span(call)
82+ op_name = parser._extract_op_name(call.func)
83+ if parser._current_func_type not in (_ir_core.FunctionType.SimtVF, _ir_core.FunctionType.SimtCallee):
84+ raise ParserSyntaxError(
85+ f"pl.{op_name}() can only be used inside a SIMT function",
86+ span=span,
87+ hint="Move SIMT-context-dependent logic into @pl.simt.function.",
88+ )
89+ if call.args:
90+ raise ParserSyntaxError(f"pl.{op_name}() does not accept positional arguments", span=span)
91+ if call.keywords:
92+ raise ParserSyntaxError(f"pl.{op_name}() does not accept keyword arguments", span=span)
93+ 
94+ 
95+def _parse_dim3_context(parser: Any, call: ast.Call, op_name: str) -> Expr:
96+ """Parse a SIMT context query as an IR named tuple."""
97+ _validate_simt_body_op(parser, call, {})
98+ span = parser.span_tracker.get_span(call)
99+ return parser.make_named_tuple(_make_dim3_components(op_name, span), _DIM3_FIELDS, span)
100+ 
101+ 
102+@op_impl("simt.thread_idx")
103+def _parse_thread_idx(parser: Any, call: ast.Call) -> Expr:
104+ return _parse_dim3_context(parser, call, "simt.thread_idx")
105+ 
106+ 
107+@op_impl("simt.block_dim")
108+def _parse_block_dim(parser: Any, call: ast.Call) -> Expr:
109+ return _parse_dim3_context(parser, call, "simt.block_dim")
110+ 
111+ 
112+@op_impl("simt.block_idx")
113+def _parse_block_idx(parser: Any, call: ast.Call) -> Expr:
114+ return _parse_dim3_context(parser, call, "simt.block_idx")
115+ 
116+ 
117+@op_impl("simt.grid_dim")
118+def _parse_grid_dim(parser: Any, call: ast.Call) -> Expr:
119+ return _parse_dim3_context(parser, call, "simt.grid_dim")
120+ 
121+ 
122+@op_impl("simt.linear_thread_idx")
123+def _parse_linear_thread_idx(parser: Any, call: ast.Call) -> Expr:
124+ _validate_simt_body_op(parser, call, {})
125+ span = parser.span_tracker.get_span(call)
126+ return linear_thread_idx(span)
127+ 
128+ 
129+@op_impl("simt.warp_size")
130+def _parse_warp_size(parser: Any, call: ast.Call) -> Expr:
131+ _validate_simt_body_op(parser, call, {})
132+ span = parser.span_tracker.get_span(call)
133+ return warp_size(span)
134+ 
135+ 
136+@op_impl("simt.launch")
137+def _parse_simt_launch(parser: Any, call: ast.Call) -> Expr:
138+ """Parse ``pl.simt.launch(callee, threads=..., args=(...))``."""
139+ from pypto_pro.language.parser.diagnostics import ParserSyntaxError, ParserTypeError
140+ 
141+ span = parser.span_tracker.get_span(call)
142+ if parser._current_func_type in (_ir_core.FunctionType.SimtVF, _ir_core.FunctionType.SimtCallee):
143+ raise ParserSyntaxError("Nested pl.simt.launch() is not supported", span=span)
144+ if parser.target != _ir_core.SectionKind.Vector:
145+ raise ParserSyntaxError(
146+ "pl.simt.launch() must appear inside 'with pl.section_vector():'",
147+ span=span,
148+ hint="SIMT vector functions execute on AIV and cannot be launched from Cube or shared kernel code.",
149+ )
150+ if len(call.args) != 1 or not isinstance(call.args[0], ast.Name):
151+ raise ParserSyntaxError(
152+ "pl.simt.launch() requires one SIMT function name as its positional argument",
153+ span=span,
154+ hint="Use: pl.simt.launch(my_simt_func, threads=256, args=(out, n))",
155+ )
156+ 
157+ keyword_nodes: dict[str, ast.expr] = {}
158+ for keyword in call.keywords:
159+ if keyword.arg is None or keyword.arg not in ("threads", "args") or keyword.arg in keyword_nodes:
160+ raise ParserSyntaxError(
161+ "pl.simt.launch() accepts exactly the 'threads' and 'args' keyword arguments",
162+ span=span,
163+ hint="Use: pl.simt.launch(my_simt_func, threads=256, args=(out, n))",
164+ )
165+ keyword_nodes[keyword.arg] = keyword.value
166+ if set(keyword_nodes) != {"threads", "args"}:
167+ raise ParserSyntaxError(
168+ "pl.simt.launch() requires both threads= and args=",
169+ span=span,
170+ hint="Use: pl.simt.launch(my_simt_func, threads=256, args=(out, n))",
171+ )
172+ 
173+ from pypto_pro.language.parser.decorator import get_simt_max_threads, is_simt_function
174+ 
175+ local_name = call.args[0].id
176+ callee_template = parser.expr_evaluator.closure_vars.get(local_name)
177+ if (
178+ not callable(callee_template)
179+ or not is_simt_function(callee_template)
180+ or get_simt_max_threads(callee_template) is None
181+ ):
182+ raise ParserTypeError(
183+ f"'{local_name}' is not a launchable @pl.simt.function",
184+ span=parser.span_tracker.get_span(call.args[0]),
185+ )
186+ 
187+ threads_node = keyword_nodes["threads"]
188+ if isinstance(threads_node, ast.Tuple):
189+ if not 1 <= len(threads_node.elts) <= 3:
190+ raise ParserSyntaxError(
191+ "pl.simt.launch() threads tuple must contain one to three dimensions",
192+ span=parser.span_tracker.get_span(threads_node),
193+ hint="Use threads=N, threads=(x, y), or threads=(x, y, z).",
194+ )
195+ thread_dims = list(threads_node.elts)
196+ else:
197+ thread_dims = [threads_node]
198+ thread_dims = [parser.parse_expression(dim) for dim in thread_dims]
199+ 
200+ args_node = keyword_nodes["args"]
201+ if not isinstance(args_node, ast.Tuple):
202+ raise ParserSyntaxError(
203+ "pl.simt.launch() args must be a tuple",
204+ span=parser.span_tracker.get_span(args_node),
205+ hint="Use args=(out, n); remember the trailing comma for a one-element tuple.",
206+ )
207+ launch_args = [parser.parse_expression(arg) for arg in args_node.elts]
208+ callee = parser._instantiate_simt_function(local_name, callee_template, launch_args, args_node.elts, span)
209+ parser._validate_simt_function_arguments(callee, launch_args, args_node.elts, span)
210+ try:
211+ return launch(callee, threads=tuple(thread_dims), args=launch_args, span=span)
212+ except RuntimeError as error:
213+ raise ParserTypeError(str(error), span=span) from error
@@ -26,6 +26,7 @@ __all__ = [
26 "DYNAMIC",26 "DYNAMIC",
27 "STATIC",27 "STATIC",
28 "system",28 "system",
29+ "simt",
29 "mutex",30 "mutex",
30 "TileType",31 "TileType",
31 "make_tile",32 "make_tile",
@@ -364,6 +365,7 @@ from ._api import (
364 trap,365 trap,
365 xor,366 xor,
366)367)
368+from ._simt_api import Simt as simt # noqa: N813
367from ._vf_api import Vf369from ._vf_api import Vf
368from .parser.decorator import function, inline, program, vector_function370from .parser.decorator import function, inline, program, vector_function
369from .parser.text_parser import loads, loads_program, parse, parse_program371from .parser.text_parser import loads, loads_program, parse, parse_program
@@ -0,0 +1,92 @@
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+"""Python API declarations for the PyPTO Pro SIMT namespace (``pl.simt.*``).
13+ 
14+These declarations exist so that:
15+- IDE "Go to Definition" works for every ``pl.simt.xxx`` call
16+- Python catches typos at import time
17+- Type checkers can validate argument types
18+- Docstrings document the user-facing calling convention
19+ 
20+None of these functions are meant to be called at runtime. Inside a PyPTO
21+kernel the AST parser intercepts every ``pl.simt.xxx`` call before Python executes
22+it. Outside a kernel, calling a declaration raises ``RuntimeError``.
23+"""
24+ 
25+from __future__ import annotations
26+ 
27+from typing import Any, Callable
28+ 
29+from ._api import Scalar, _api_decl
30+ 
31+ 
32+class Simt:
33+ """SIMT namespace (``pl.simt.*``).
34+ 
35+ Provides SIMT context queries (thread_idx, block_dim, ...), launch, and
36+ the ``function`` decorator for defining SIMT VF functions.
37+ """
38+ 
39+ @staticmethod
40+ def function(fn: Callable | None = None, *, max_threads: int | None = None) -> Callable:
41+ """Mark a callable for delayed SIMT parsing at its call site.
42+ 
43+ Args:
44+ fn: Python function to decorate (when used without parentheses).
45+ max_threads: Launch bound for SIMT VF functions. When provided, the
46+ function is launchable via ``pl.simt.launch()``. When omitted,
47+ the function is a SIMT callee helper.
48+ """
49+ from .parser.decorator import simt_function
50+ 
51+ return simt_function(fn, max_threads=max_threads)
52+ 
53+ @staticmethod
54+ @_api_decl
55+ def thread_idx() -> Any:
56+ """Return the current thread coordinates within its thread block."""
57+ 
58+ @staticmethod
59+ @_api_decl
60+ def block_dim() -> Any:
61+ """Return the dimensions of the current thread block."""
62+ 
63+ @staticmethod
64+ @_api_decl
65+ def block_idx() -> Any:
66+ """Return the current block coordinates within the outer kernel grid."""
67+ 
68+ @staticmethod
69+ @_api_decl
70+ def grid_dim() -> Any:
71+ """Return the dimensions of the outer kernel grid."""
72+ 
73+ @staticmethod
74+ @_api_decl
75+ def linear_thread_idx() -> Scalar:
76+ """Return the x-major flattened thread index within the current block."""
77+ 
78+ @staticmethod
79+ @_api_decl
80+ def warp_size() -> Scalar:
81+ """Return the target SIMT warp size."""
82+ 
83+ @staticmethod
84+ @_api_decl
85+ def launch(callee: Any, *, threads: int | tuple[int, ...], args: tuple[Any, ...]) -> None:
86+ """Launch a SIMT function from a Vector section.
87+ 
88+ Args:
89+ callee: Launchable function defined with ``@pl.simt.function(max_threads=...)``.
90+ threads: One- to three-dimensional compile-time thread configuration.
91+ args: Scalar, Tensor, and Tile arguments passed to ``callee``.
92+ """
@@ -25,7 +25,7 @@ from ..typing._tiling import ArrayFieldInfo, get_tiling_fields, is_tiling_class
25from ..typing.shape import _ShapePolicy25from ..typing.shape import _ShapePolicy
26from ._assignment_parser import AssignmentParserMixin26from ._assignment_parser import AssignmentParserMixin
27from ._buffer_parser import BufferParserMixin27from ._buffer_parser import BufferParserMixin
28-from ._call_parser import CallParserMixin, _infer_return_types_from_body28+from ._call_parser import CallParserMixin, _check_type_compatible
29from ._control_flow_parser import ControlFlowParserMixin, validate_single_tail_return29from ._control_flow_parser import ControlFlowParserMixin, validate_single_tail_return
30from ._expr_evaluator import ExprEvaluator30from ._expr_evaluator import ExprEvaluator
31from ._expression_parser import ExpressionParserMixin31from ._expression_parser import ExpressionParserMixin
@@ -50,6 +50,32 @@ def _snake_visit_name(node: ast.AST) -> str:
50 return f"visit_{''.join(chars)}"50 return f"visit_{''.join(chars)}"
51 51 
52 52 
53+def _infer_return_types_from_body(body: ir.Stmt) -> list[ir.Type] | None:
54+ """Extract return types from the first value-returning ReturnStmt in a function body.
55+ 
56+ Recurses into control-flow bodies so a helper that returns a value from a branch,
57+ while an earlier branch does a void return, still resolves its result type.
58+ """
59+ if isinstance(body, ir.ReturnStmt):
60+ if body.value:
61+ return [value.type for value in body.value]
62+ return None
63+ if isinstance(body, ir.SeqStmts):
64+ for stmt in body.stmts:
65+ result = _infer_return_types_from_body(stmt)
66+ if result is not None:
67+ return result
68+ if isinstance(body, ir.IfStmt):
69+ for branch in (body.then_body, body.else_body):
70+ if branch is not None:
71+ result = _infer_return_types_from_body(branch)
72+ if result is not None:
73+ return result
74+ if isinstance(body, (ir.ForStmt, ir.WhileStmt)):
75+ return _infer_return_types_from_body(body.body)
76+ return None
77+ 
78+ 
53class ASTParser(79class ASTParser(
54 AssignmentParserMixin,80 AssignmentParserMixin,
55 ControlFlowParserMixin,81 ControlFlowParserMixin,
@@ -113,6 +139,8 @@ class ASTParser(
113 # Python IR wrapper and can be reused by an unrelated expression.139 # Python IR wrapper and can be reused by an unrelated expression.
114 self._tile_mutex_meta: dict[ir.Expr, tuple] = {}140 self._tile_mutex_meta: dict[ir.Expr, tuple] = {}
115 self.scope_manager = ScopeManager(strict_ssa=strict_ssa, tile_mutex_meta=self._tile_mutex_meta)141 self.scope_manager = ScopeManager(strict_ssa=strict_ssa, tile_mutex_meta=self._tile_mutex_meta)
142+ self._tilingkey_consts = tilingkey_consts
143+ self._datatype_consts = datatype_consts
116 # Concrete tilingkey field values (per launch key) are injected as closure constants144 # Concrete tilingkey field values (per launch key) are injected as closure constants
117 # so the parser folds field references (e.g. NeedAttnMask) to ConstInt — no template145 # so the parser folds field references (e.g. NeedAttnMask) to ConstInt — no template
118 # params reach the IR. Field values win over any same-named closure var.146 # params reach the IR. Field values win over any same-named closure var.
@@ -156,6 +184,8 @@ class ASTParser(
156 self.inline_func_cache: dict[int, Any] = {}184 self.inline_func_cache: dict[int, Any] = {}
157 self.inline_call_stack: list[int] = []185 self.inline_call_stack: list[int] = []
158 self.inline_counter: int = 0186 self.inline_counter: int = 0
187+ self.simt_func_cache: dict[int, ir.Function] = {}
188+ self.simt_call_stack: list[int] = []
159 # Nested vector helpers share the outermost VF section.189 # Nested vector helpers share the outermost VF section.
160 self.inline_vf_depth: int = 0190 self.inline_vf_depth: int = 0
161 191 
@@ -175,10 +205,10 @@ class ASTParser(
175 # GetItemExpr alias semantics; every other MakeTuple is immutable.205 # GetItemExpr alias semantics; every other MakeTuple is immutable.
176 self._struct_array_tuples: set[ir.MakeTuple] = set()206 self._struct_array_tuples: set[ir.MakeTuple] = set()
177 207 
178- # Maps tile expr id -> [row_expr, col_expr] for tiles that had208+ # Maps tile expressions to parser-tracked [row, col] valid shapes from
179- # set_validshape called on them at parse time. Consumed by209+ # explicit set_validshape calls. This metadata is used to clamp subviews;
180- # _parse_slice_subscript to clamp sub-view valid_shape.210+ # public tile.valid_shape reads are represented by block.tile_valid_shape.
181- self._tile_valid_shape: dict[int, list] = {}211+ self._tile_valid_shape: dict[ir.Expr, list] = {}
182 212 
183 # MakeTuples that already have an emitted assignment anchor. Keeping the213 # MakeTuples that already have an emitted assignment anchor. Keeping the
184 # Expr objects themselves alive is required: a Python wrapper's id() can214 # Expr objects themselves alive is required: a Python wrapper's id() can
@@ -236,10 +266,11 @@ class ASTParser(
236 return ir.TensorType(param_type.shape, param_type.dtype, param_type.memref, tv)266 return ir.TensorType(param_type.shape, param_type.dtype, param_type.memref, tv)
237 267 
238 def record_tile_valid_shape(self, tile_expr: ir.Expr, valid_shape) -> None:268 def record_tile_valid_shape(self, tile_expr: ir.Expr, valid_shape) -> None:
239- self._tile_valid_shape[id(tile_expr)] = list(valid_shape.elements)269+ elements = valid_shape.elements if isinstance(valid_shape, ir.MakeTuple) else valid_shape
270+ self._tile_valid_shape[tile_expr] = list(elements)
240 271 
241 def get_tile_valid_shape(self, tile_expr: ir.Expr):272 def get_tile_valid_shape(self, tile_expr: ir.Expr):
242- return self._tile_valid_shape.get(id(tile_expr))273+ return self._tile_valid_shape.get(tile_expr)
243 274 
244 def set_void_return_mode(self, context: str, allow_early_return: bool = False) -> None:275 def set_void_return_mode(self, context: str, allow_early_return: bool = False) -> None:
245 """Configure void-only return mode for this parser.276 """Configure void-only return mode for this parser.
@@ -275,6 +306,7 @@ class ASTParser(
275 func_def: ast.FunctionDef,306 func_def: ast.FunctionDef,
276 func_type: ir.FunctionType = ir.FunctionType.Opaque,307 func_type: ir.FunctionType = ir.FunctionType.Opaque,
277 is_vector_function: bool = False,308 is_vector_function: bool = False,
309+ callsite_param_types: dict[str, ir.Type] | None = None,
278 ) -> ir.Function:310 ) -> ir.Function:
279 """Parse function definition and build IR.311 """Parse function definition and build IR.
280 312 
@@ -285,9 +317,18 @@ class ASTParser(
285 implicit ``ir.SectionKind.VF`` section scope (for317 implicit ``ir.SectionKind.VF`` section scope (for
286 ``@pl.vector_function`` decorated functions).318 ``@pl.vector_function`` decorated functions).
287 319 
320+ callsite_param_types: Concrete parameter types supplied while parsing
321+ a SIMT function at its call site.
322+ 
288 Returns:323 Returns:
289 IR Function object324 IR Function object
290 """325 """
326+ if callsite_param_types is not None and func_type not in (
327+ ir.FunctionType.SimtVF,
328+ ir.FunctionType.SimtCallee,
329+ ):
330+ raise ValueError("callsite_param_types is only supported for SIMT functions")
331+ 
291 func_name = func_def.name332 func_name = func_def.name
292 func_span = self.span_tracker.get_span(func_def)333 func_span = self.span_tracker.get_span(func_def)
293 334 
@@ -327,21 +368,11 @@ class ASTParser(
327 self._validate_tiling_params(args_to_process, func_def)368 self._validate_tiling_params(args_to_process, func_def)
328 369 
329 self._anchored_make_tuples.clear()370 self._anchored_make_tuples.clear()
330- has_policy_return = self.type_resolver.annotation_has_shape_policy(func_def.returns)
331 371 
332 with self.builder.function(func_name, func_span, func_type=func_type) as f:372 with self.builder.function(func_name, func_span, func_type=func_type) as f:
333 for arg in args_to_process:373 for arg in args_to_process:
334- self._parse_function_param(arg, f)374+ callsite_type = callsite_param_types.get(arg.arg) if callsite_param_types is not None else None
335- 375+ self._parse_function_param(arg, f, callsite_type)
336- # Parse return type (skip `-> None`)
337- if (
338- func_def.returns
339- and not has_policy_return
340- and not (isinstance(func_def.returns, ast.Constant) and func_def.returns.value is None)
341- ):
342- # tuple[...] resolves to a single TupleType, matching a `return a, b`
343- # body (one MakeTuple expr), so a tuple return is one return type.
344- f.return_type(self.type_resolver.resolve_type(func_def.returns))
345 376 
346 # Give closure tuples a function-entry array-materialization anchor.377 # Give closure tuples a function-entry array-materialization anchor.
347 self._hoist_closure_tuples()378 self._hoist_closure_tuples()
@@ -367,22 +398,38 @@ class ASTParser(
367 398 
368 self.scope_manager.exit_scope()399 self.scope_manager.exit_scope()
369 result = f.get_result()400 result = f.get_result()
370- if has_policy_return and func_def.returns is not None:401+ inferred = (_infer_return_types_from_body(result.body) if result.body else None) or []
371- inferred = _infer_return_types_from_body(result.body) if result.body else None402+ if func_def.returns is not None:
372- if inferred is None:403+ # tuple[...] resolves to a single TupleType, matching a `return a, b`
404+ # body (one MakeTuple expr), so a tuple return is one return type.
405+ annotated_return_types = [self.type_resolver.resolve_type(func_def.returns)]
406+ 
407+ return_span = self.span_tracker.get_span(func_def.returns)
408+ if len(annotated_return_types) != len(inferred):
373 raise ParserTypeError(409 raise ParserTypeError(
374- f"Function '{func_name}' has a shape-policy return annotation but no returned value",410+ f"Return annotation for '{func_name}' expects "
375- span=func_span,411+ f"{len(annotated_return_types)} value(s), got {len(inferred)}",
412+ span=return_span,
376 )413 )
377- self.type_resolver.validate_policy_return_types(func_def.returns, inferred)414+ for annotated, actual in zip(annotated_return_types, inferred):
378- result = ir.Function(415+ _check_type_compatible(
379- result.name,416+ annotated,
380- list(result.params),417+ actual,
381- inferred,418+ what="Return",
382- result.body,419+ name=func_name,
383- result.span,420+ span=return_span,
384- result.func_type,421+ )
385- )422+ 
423+ result = ir.Function(
424+ result.name,
425+ list(result.params),
426+ inferred,
427+ result.body,
428+ result.span,
429+ result.func_type,
430+ result.entry,
431+ dict(result.attrs),
432+ )
386 return result433 return result
387 434 
388 def parse_statement(self, stmt: ast.stmt) -> None:435 def parse_statement(self, stmt: ast.stmt) -> None:
@@ -515,13 +562,13 @@ class ASTParser(
515 hint="Move the tiling parameter to the last position",562 hint="Move the tiling parameter to the last position",
516 )563 )
517 564 
518- def _parse_function_param(self, arg: ast.arg, f: Any) -> None:565+ def _parse_function_param(self, arg: ast.arg, f: Any, callsite_type: ir.Type | None = None) -> None:
519 """Parse a single function parameter and register it in scope or tiling registry."""566 """Parse a single function parameter and register it in scope or tiling registry."""
520 param_name = arg.arg567 param_name = arg.arg
521 param_span = self.span_tracker.get_span(arg)568 param_span = self.span_tracker.get_span(arg)
522 569 
523 # 1) tiling-class annotation: always expand via the tiling path (even if a570 # 1) tiling-class annotation: always expand via the tiling path (even if a
524- # call-site-inferred type exists for this name).571+ # call-site type exists for this name).
525 tiling_cls = self.resolve_tiling_class(arg.annotation) if arg.annotation else None572 tiling_cls = self.resolve_tiling_class(arg.annotation) if arg.annotation else None
526 if tiling_cls is not None:573 if tiling_cls is not None:
527 fields = get_tiling_fields(tiling_cls)574 fields = get_tiling_fields(tiling_cls)
@@ -545,7 +592,21 @@ class ASTParser(
545 self.scope_manager.define_var(param_name, tiling_var, allow_redef=True)592 self.scope_manager.define_var(param_name, tiling_var, allow_redef=True)
546 return593 return
547 594 
548- # 2) Annotation only (decorator path: no call site to infer from).595+ # 2) A call-site type is available for delayed SIMT function parsing.
596+ if callsite_type is not None:
597+ if arg.annotation is not None:
598+ annotated_type = self.type_resolver.resolve_param_type(
599+ arg.annotation, parameter_name=param_name
600+ )
601+ _check_type_compatible(
602+ annotated_type, callsite_type, what="SIMT parameter", name=param_name, span=param_span
603+ )
604+ param_type = self._attach_ptr_to_tensor_type(param_name, callsite_type, param_span)
605+ param_var = f.param(param_name, param_type, param_span)
606+ self.scope_manager.define_var(param_name, param_var, allow_redef=True)
607+ return
608+ 
609+ # 3) Annotation-only path for eagerly parsed functions.
549 if arg.annotation is None:610 if arg.annotation is None:
550 raise ParserTypeError(611 raise ParserTypeError(
551 f"Parameter '{param_name}' missing type annotation",612 f"Parameter '{param_name}' missing type annotation",
@@ -19,6 +19,7 @@ import logging
19from typing import Any, Callable19from typing import Any, Callable
20 20 
21from pypto.pypto_impl import ir21from pypto.pypto_impl import ir
22+from pypto_pro.ir._utils import _is_int
22from pypto_pro.ir.op._op_registry import _OP_REGISTRY23from pypto_pro.ir.op._op_registry import _OP_REGISTRY
23from pypto_pro.ir.op.block_ops import block_ir_op24from pypto_pro.ir.op.block_ops import block_ir_op
24 25 
@@ -179,32 +180,42 @@ def _check_type_compatible(annotated: ir.Type, actual: ir.Type, *, what: str, na
179 )180 )
180 181 
181 182 
182-def _infer_return_types_from_body(body: ir.Stmt) -> list[ir.Type] | None:183+def _validate_simt_parameters(func: ir.Function, role: str) -> None:
183- """Extract return types from the first value-returning ReturnStmt in a function body.184+ """Validate the common native CCE ABI accepted by SIMT functions."""
184- 185+ for param in func.params:
185- Recurses into control-flow bodies (if/for) so a helper that returns a value from186+ if not isinstance(param.type, (ir.ScalarType, ir.TensorType, ir.TileType)):
186- a branch — while an earlier branch does a void `return` (e.g. `return None` on a187+ raise ParserTypeError(
187- compile-time-dead path) — still resolves its result type.188+ f"{role} parameter '{param.name}' must be a scalar, pl.Tensor, or pl.Tile, got {param.type}",
188- """189+ span=param.span,
189- if isinstance(body, ir.ReturnStmt):190+ hint="Ptr, Tuple, and tiling parameters are not supported.",
190- if body.value:191+ )
191- return [v.type for v in body.value]192+ if isinstance(param.type, ir.TensorType):
192- return None193+ if param.type.dtype.get_bit() < 8:
193- if isinstance(body, ir.SeqStmts):194+ raise ParserTypeError(
194- for s in body.stmts:195+ f"{role} Tensor parameter '{param.name}' uses an unsupported sub-byte dtype",
195- result = _infer_return_types_from_body(s)196+ span=param.span,
196- if result is not None:197+ hint="Use a byte-addressable Tensor element type such as pl.DT_UINT8 or wider.",
197- return result198+ )
198- if isinstance(body, ir.IfStmt):199+ tensor_view = param.type.tensor_view
199- for branch in (body.then_body, body.else_body):200+ if tensor_view is None or tensor_view.layout != ir.TensorLayout.ND:
200- if branch is not None:201+ raise ParserTypeError(
201- result = _infer_return_types_from_body(branch)202+ f"{role} Tensor parameter '{param.name}' requires ND layout",
202- if result is not None:203+ span=param.span,
203- return result204+ hint="Use pl.Tensor[[shape], dtype] or specify pl.ND explicitly.",
204- if isinstance(body, ir.ForStmt):205+ )
205- return _infer_return_types_from_body(body.body)206+ if isinstance(param.type, ir.TileType):
206- return None207+ if len(param.type.shape) != 2 or not all(isinstance(dim, ir.ConstInt) for dim in param.type.shape):
207- 208+ raise ParserTypeError(
209+ f"{role} Tile parameter '{param.name}' must have a static two-dimensional shape",
210+ span=param.span,
211+ hint="Use an annotation such as pl.Tile[[1, 256], pl.DT_FP32].",
212+ )
213+ if param.type.dtype.get_bit() < 8:
214+ raise ParserTypeError(
215+ f"{role} Tile parameter '{param.name}' uses an unsupported sub-byte dtype",
216+ span=param.span,
217+ hint="Use a byte-addressable Tile element type such as pl.DT_UINT8 or wider.",
218+ )
208 219 
209class CallParserMixin:220class CallParserMixin:
210 """Mixin containing call and operation parsing methods for ``ASTParser``."""221 """Mixin containing call and operation parsing methods for ``ASTParser``."""
@@ -641,6 +652,8 @@ class CallParserMixin:
641 """Determine the pipe for auto_mutex from op_name and tile memory spaces."""652 """Determine the pipe for auto_mutex from op_name and tile memory spaces."""
642 from ._op_pipeline import get_move_pipe, get_op_pipe, get_store_pipe653 from ._op_pipeline import get_move_pipe, get_op_pipe, get_store_pipe
643 654 
655+ if op_name == "simt.launch":
656+ return ir.PipeType.V
644 if op_name == "move":657 if op_name == "move":
645 dst_mem = tilerefs[0].memory if tilerefs[0] else None658 dst_mem = tilerefs[0].memory if tilerefs[0] else None
646 src_mem = tilerefs[1].memory if len(tilerefs) > 1 and tilerefs[1] else None659 src_mem = tilerefs[1].memory if len(tilerefs) > 1 and tilerefs[1] else None
@@ -710,7 +723,7 @@ class CallParserMixin:
710 """Return True if the VF op's dst(s) are MaskReg (not RegTensor)."""723 """Return True if the VF op's dst(s) are MaskReg (not RegTensor)."""
711 return op_name in cls._VF_MASK_DST_OPS724 return op_name in cls._VF_MASK_DST_OPS
712 725 
713- def parse_call(self, call: ast.Call) -> ir.Expr:726+ def parse_call(self, call: ast.Call) -> Any:
714 """Parse function call.727 """Parse function call.
715 728 
716 Args:729 Args:
@@ -756,8 +769,6 @@ class CallParserMixin:
756 return op_func(self, call)769 return op_func(self, call)
757 770 
758 resolved = self.expr_evaluator.closure_vars.get(func_name)771 resolved = self.expr_evaluator.closure_vars.get(func_name)
759- if isinstance(resolved, ir.Function):
760- return self._parse_external_function_call(func_name, resolved, call)
761 if callable(resolved) and not isinstance(resolved, type):772 if callable(resolved) and not isinstance(resolved, type):
762 return self._implicit_func_call(func_name, resolved, call)773 return self._implicit_func_call(func_name, resolved, call)
763 774 
@@ -767,7 +778,7 @@ class CallParserMixin:
767 hint="Use pl.* operations, self.method() for cross-function calls, or call an inline Python helper by name",778 hint="Use pl.* operations, self.method() for cross-function calls, or call an inline Python helper by name",
768 )779 )
769 780 
770- def parse_op_call(self, call: ast.Call) -> ir.Expr:781+ def parse_op_call(self, call: ast.Call) -> Any:
771 """Parse operation call like pl.tensor.create_tensor() or pl.add().782 """Parse operation call like pl.tensor.create_tensor() or pl.add().
772 783 
773 Args:784 Args:
@@ -776,11 +787,12 @@ class CallParserMixin:
776 Returns:787 Returns:
777 IR expression from operation788 IR expression from operation
778 """789 """
790+ op_name = self._extract_op_name(call.func)
791+ 
779 result = self._route_ir_node_method(call)792 result = self._route_ir_node_method(call)
780 if result is not None:793 if result is not None:
781 return result794 return result
782 795 
783- op_name = self._extract_op_name(call.func)
784 span = self.span_tracker.get_span(call)796 span = self.span_tracker.get_span(call)
785 if op_name is None:797 if op_name is None:
786 raise UnsupportedFeatureError(798 raise UnsupportedFeatureError(
@@ -798,6 +810,17 @@ class CallParserMixin:
798 "constexpr is not allowed in for/while/with/break/continue/return or as a standalone statement",810 "constexpr is not allowed in for/while/with/break/continue/return or as a standalone statement",
799 )811 )
800 812 
813+ if self._current_func_type in (ir.FunctionType.SimtVF, ir.FunctionType.SimtCallee) and not op_name.startswith(
814+ "simt."
815+ ):
816+ raise UnsupportedFeatureError(
817+ f"Operation '{op_name}' is not supported inside a SIMT function",
818+ span=span,
819+ hint=(
820+ "The current SIMT slice supports SIMT context queries, scalar expressions, restricted "
821+ "loops, and scalar Tensor/Tile accesses."
822+ ),
823+ )
801 if self._auto_mutex and not op_name.startswith("vf."):824 if self._auto_mutex and not op_name.startswith("vf."):
802 self._emit_auto_mutex(op_name, call, span)825 self._emit_auto_mutex(op_name, call, span)
803 826 
@@ -926,6 +949,162 @@ class CallParserMixin:
926 op = ir.Op(func_name)949 op = ir.Op(func_name)
927 return self._make_call_with_return_type(op, args, ext_func.return_types, span)950 return self._make_call_with_return_type(op, args, ext_func.return_types, span)
928 951 
952+ def _parse_simt_template_call(self, local_name: str, fn: Callable, call: ast.Call) -> ir.Expr:
953+ """Instantiate and call one helper @pl.simt.function template."""
954+ span = self.span_tracker.get_span(call)
955+ if call.keywords or any(isinstance(arg, ast.Starred) for arg in call.args):
956+ raise ParserSyntaxError(
957+ "Helper @pl.simt.function calls accept positional arguments only",
958+ span=span,
959+ )
960+ args = [self.parse_expression(arg) for arg in call.args]
961+ callee = self._instantiate_simt_function(local_name, fn, args, call.args, span)
962+ self._validate_simt_function_arguments(callee, args, call.args, span)
963+ return self._make_call_with_return_type(ir.Op(callee.name), args, callee.return_types, span)
964+ 
965+ def _instantiate_simt_function(
966+ self,
967+ local_name: str,
968+ fn: Callable,
969+ args: list[ir.Expr],
970+ arg_nodes: list[ast.expr],
971+ span,
972+ ) -> ir.Function:
973+ """Parse a marked SIMT callable once its actual argument types are known."""
974+ from ._ast_parser import ASTParser
975+ from .decorator import get_simt_max_threads
976+ 
977+ max_threads = get_simt_max_threads(fn)
978+ launchable = max_threads is not None
979+ if launchable:
980+ if not _is_int(max_threads):
981+ raise TypeError("max_threads must be an integer")
982+ if not 1 <= max_threads <= 2048:
983+ raise ValueError("max_threads must be in the range [1, 2048]")
984+ 
985+ cached = self.simt_func_cache.get(id(fn))
986+ if cached is not None:
987+ self._register_simt_external(cached, span)
988+ return cached
989+ if id(fn) in self.simt_call_stack:
990+ raise ParserSyntaxError(
991+ f"Recursive helper @pl.simt.function call involving '{fn.__name__}' is not supported",
992+ span=span,
993+ )
994+ 
995+ source_file, source_lines, line_offset, col_offset, func_def = self._retrieve_function_source(
996+ local_name,
997+ fn,
998+ span,
999+ "@pl.simt.function",
1000+ )
1001+ func_args = func_def.args
1002+ if (
1003+ func_args.posonlyargs
1004+ or func_args.vararg is not None
1005+ or func_args.kwarg is not None
1006+ or func_args.kwonlyargs
1007+ or func_args.defaults
1008+ or func_args.kw_defaults
1009+ ):
1010+ raise ParserSyntaxError(
1011+ f"SIMT function '{fn.__name__}' only supports required positional parameters",
1012+ span=span,
1013+ )
1014+ params = list(func_args.args)
1015+ if len(args) != len(params):
1016+ role = "SIMT function" if launchable else "SIMT callee"
1017+ raise ParserTypeError(
1018+ f"{role} '{fn.__name__}' expects {len(params)} argument(s), got {len(args)}",
1019+ span=span,
1020+ )
1021+ 
1022+ func_type = ir.FunctionType.SimtVF if launchable else ir.FunctionType.SimtCallee
1023+ role = "SIMT function" if launchable else "SIMT helper"
1024+ parser = ASTParser(
1025+ source_file,
1026+ source_lines,
1027+ ir.SectionKind.Vector,
1028+ line_offset,
1029+ col_offset,
1030+ global_vars=self.global_vars,
1031+ closure_vars=self._build_function_closure(fn),
1032+ debug_info=self.debug_info,
1033+ tilingkey_consts=self._tilingkey_consts,
1034+ datatype_consts=self._datatype_consts,
1035+ void_return_only=launchable,
1036+ void_return_context="@pl.simt.function(max_threads=...)",
1037+ allow_early_return=True,
1038+ )
1039+ parser.external_funcs = self.external_funcs
1040+ parser.simt_func_cache = self.simt_func_cache
1041+ parser.simt_call_stack = self.simt_call_stack
1042+ 
1043+ self.simt_call_stack.append(id(fn))
1044+ try:
1045+ parsed = parser.parse_function(
1046+ func_def,
1047+ func_type=func_type,
1048+ callsite_param_types={param.arg: actual.type for param, actual in zip(params, args)},
1049+ )
1050+ 
1051+ _validate_simt_parameters(parsed, role)
1052+ if launchable:
1053+ result = ir.Function(
1054+ parsed.name,
1055+ list(parsed.params),
1056+ list(parsed.return_types),
1057+ parsed.body,
1058+ parsed.span,
1059+ func_type,
1060+ parsed.entry,
1061+ {"max_threads": max_threads},
1062+ )
1063+ else:
1064+ result = parsed
1065+ self._register_simt_external(result, span)
1066+ self.simt_func_cache[id(fn)] = result
1067+ finally:
1068+ self.simt_call_stack.pop()
1069+ 
1070+ return result
1071+ 
1072+ def _validate_simt_function_arguments(
1073+ self,
1074+ callee: ir.Function,
1075+ args: list[ir.Expr],
1076+ arg_nodes: list[ast.expr],
1077+ span,
1078+ ) -> None:
1079+ """Validate call-site arguments against an instantiated SIMT signature."""
1080+ if len(args) != len(callee.params):
1081+ raise ParserTypeError(
1082+ f"SIMT function '{callee.name}' expects {len(callee.params)} argument(s), got {len(args)}",
1083+ span=span,
1084+ )
1085+ for param, actual, actual_node in zip(callee.params, args, arg_nodes):
1086+ _check_type_compatible(
1087+ param.type,
1088+ actual.type,
1089+ what="SIMT parameter",
1090+ name=param.name,
1091+ span=self.span_tracker.get_span(actual_node),
1092+ )
1093+ 
1094+ def _register_simt_external(self, func: ir.Function, span) -> None:
1095+ """Register one instantiated SIMT function in the enclosing Program."""
1096+ if func.name in self.global_vars:
1097+ raise ParserSyntaxError(
1098+ f"SIMT function '{func.name}' conflicts with an internal program function",
1099+ span=span,
1100+ )
1101+ if func.name in self.external_funcs and self.external_funcs[func.name] is not func:
1102+ raise ParserSyntaxError(
1103+ f"Conflicting external functions with name '{func.name}'",
1104+ span=span,
1105+ )
1106+ self.external_funcs[func.name] = func
1107+ 
929 def _inline_template(self, func_name: str, fn: Callable, span) -> _InlineFunctionTemplate:1108 def _inline_template(self, func_name: str, fn: Callable, span) -> _InlineFunctionTemplate:
930 template = self.inline_func_cache.get(id(fn))1109 template = self.inline_func_cache.get(id(fn))
931 if template is not None:1110 if template is not None:
@@ -996,7 +1175,26 @@ class CallParserMixin:
996 return bound1175 return bound
997 1176 
998 def _implicit_func_call(self, func_name: str, fn: Callable, call: ast.Call) -> ir.Expr | None:1177 def _implicit_func_call(self, func_name: str, fn: Callable, call: ast.Call) -> ir.Expr | None:
999- """Expand a Python helper body directly into the caller's IR builder."""1178+ """Expand a Python helper body directly into the caller's IR builder.
1179+ 
1180+ For SIMT functions, routes to ``_parse_simt_template_call`` instead of
1181+ inlining. For regular callables, expands the body directly.
1182+ """
1183+ from .decorator import get_simt_max_threads, is_simt_function
1184+ 
1185+ if is_simt_function(fn):
1186+ if self._current_func_type in (ir.FunctionType.SimtVF, ir.FunctionType.SimtCallee):
1187+ if get_simt_max_threads(fn) is not None:
1188+ raise ParserTypeError(
1189+ f"SIMT helper '{func_name}' must be decorated with @pl.simt.function without max_threads",
1190+ span=self.span_tracker.get_span(call),
1191+ )
1192+ return self._parse_simt_template_call(func_name, fn, call)
1193+ raise ParserSyntaxError(
1194+ f"@pl.simt.function '{func_name}' must be invoked through pl.simt.launch()",
1195+ span=self.span_tracker.get_span(call),
1196+ )
1197+ 
1000 span = self.span_tracker.get_span(call)1198 span = self.span_tracker.get_span(call)
1001 template = self._inline_template(func_name, fn, span)1199 template = self._inline_template(func_name, fn, span)
1002 if self.inline_vf_depth != 0 and not template.is_vector_function:1200 if self.inline_vf_depth != 0 and not template.is_vector_function:
@@ -1214,7 +1412,14 @@ class CallParserMixin:
1214 # 1. Build unique_refs: scan args for slot.tile mutex refs, dedup by slot,1412 # 1. Build unique_refs: scan args for slot.tile mutex refs, dedup by slot,
1215 # then drop Acc tiles when a phase-aware matmul/store carries the1413 # then drop Acc tiles when a phase-aware matmul/store carries the
1216 # unit_flag (the hardware handshake replaces the software mutex there).1414 # unit_flag (the hardware handshake replaces the software mutex there).
1217- tilerefs = [self._try_resolve_tileref(arg) for arg in call.args]1415+ if op_name == "simt.launch":
1416+ args_node = next((kw.value for kw in call.keywords if kw.arg == "args"), None)
1417+ if not isinstance(args_node, ast.Tuple):
1418+ return
1419+ scan_args = args_node.elts
1420+ else:
1421+ scan_args = call.args
1422+ tilerefs = [self._try_resolve_tileref(arg) for arg in scan_args]
1218 unique_refs = []1423 unique_refs = []
1219 seen = set()1424 seen = set()
1220 for tref in tilerefs:1425 for tref in tilerefs:
@@ -17,7 +17,7 @@ from typing import Any
17from pypto.pypto_impl import ir17from pypto.pypto_impl import ir
18from pypto.pypto_impl.ir import DataType18from pypto.pypto_impl.ir import DataType
19 19 
20-from .diagnostics import ParserSyntaxError, UnsupportedFeatureError20+from .diagnostics import ParserSyntaxError, ParserTypeError, UnsupportedFeatureError
21 21 
22 22 
23def _is_bare_return(stmt: ast.Return) -> bool:23def _is_bare_return(stmt: ast.Return) -> bool:
@@ -327,28 +327,29 @@ class ControlFlowParserMixin:
327 )327 )
328 328 
329 if _is_bare_return(stmt):329 if _is_bare_return(stmt):
330- # `return None` is identical to a bare `return`; treat it as a void
331- # return so a helper can early-exit on a compile-time-dead branch
332- # (e.g. `if constInfo.is_tnd: return None`) that inlining later drops.
333 self.builder.return_stmt(None, span)330 self.builder.return_stmt(None, span)
334 return331 return
335 332 
336- if self._void_return_only:333+ if self._current_func_type == ir.FunctionType.SimtCallee:
337- raise ParserSyntaxError(334+ return_expr = self.parse_expression(stmt.value)
338- f"{self._void_return_context} only supports bare return or return None; "335+ if not isinstance(return_expr.type, ir.ScalarType):
339- "returning values is not supported.",336+ raise ParserTypeError(
340- span=span,337+ "A helper @pl.simt.function must return None or one scalar value",
341- hint=(338+ span=span,
342- "Do not write `return <value>`; only use `return` or `return None`. "339+ hint="Return Tile/Tensor data through an input parameter; return scalar results directly.",
343- "Pass output Tensor/Tile/buffer parameters for data results."340+ )
344- ),341+ else:
345- )342+ if self._void_return_only:
346- 343+ raise ParserSyntaxError(
347- # A tuple return (`return a, b`) is parsed as a single MakeTuple344+ f"{self._void_return_context} only supports bare return or return None; "
348- # expression via parse_tuple_literal, so the ReturnStmt always carries345+ "returning values is not supported.",
349- # exactly one value. Downstream inlining lowers it to `target = MakeTuple(...)`346+ span=span,
350- # and backend codegen resolves the tuple via tuple_var_to_make_tuple_.347+ hint=(
351- return_expr = self.parse_expression(stmt.value)348+ "Do not write `return <value>`; only use `return` or `return None`. "
349+ "Pass output Tensor/Tile/buffer parameters for data results."
350+ ),
351+ )
352+ return_expr = self.parse_expression(stmt.value)
352 self.builder.return_stmt([return_expr], span)353 self.builder.return_stmt([return_expr], span)
353 354 
354 def parse_break(self, stmt: ast.Break) -> None:355 def parse_break(self, stmt: ast.Break) -> None:
@@ -789,7 +789,7 @@ class ExpressionParserMixin:
789 return expr789 return expr
790 790 
791 def lower_attr_access(self, base: ir.Expr, field_name: str, span: ir.Span):791 def lower_attr_access(self, base: ir.Expr, field_name: str, span: ir.Span):
792- """Lower attribute read ``base.field`` to ``GetItemExpr(base, index)``.792+ """Lower attribute read ``base.field`` to its named tuple element.
793 793 
794 Resolves the field index from the base's named TupleType and records the794 Resolves the field index from the base's named TupleType and records the
795 type's field names in ``IRDebugInfo``. When *base* is a parse-time795 type's field names in ``IRDebugInfo``. When *base* is a parse-time
@@ -894,6 +894,11 @@ class ExpressionParserMixin:
894 def parse_subscript(self, subscript: ast.Subscript) -> ir.Expr:894 def parse_subscript(self, subscript: ast.Subscript) -> ir.Expr:
895 span = self.span_tracker.get_span(subscript)895 span = self.span_tracker.get_span(subscript)
896 896 
897+ if isinstance(subscript.value, ast.Attribute) and subscript.value.attr == "valid_shape":
898+ base_expr = self.parse_expression(subscript.value.value)
899+ if isinstance(base_expr, ir.Expr) and isinstance(base_expr.type, ir.TileType):
900+ return self._parse_tile_valid_shape_subscript(base_expr, subscript.slice, span)
901+ 
897 if isinstance(subscript.value, ast.Attribute) and subscript.value.attr == "shape":902 if isinstance(subscript.value, ast.Attribute) and subscript.value.attr == "shape":
898 base_expr = self.parse_expression(subscript.value.value)903 base_expr = self.parse_expression(subscript.value.value)
899 if isinstance(base_expr, ir.Expr) and isinstance(base_expr.type, ir.TensorType):904 if isinstance(base_expr, ir.Expr) and isinstance(base_expr.type, ir.TensorType):
@@ -1196,6 +1201,33 @@ class ExpressionParserMixin:
1196 )1201 )
1197 return tensor_type.shape[axis]1202 return tensor_type.shape[axis]
1198 1203 
1204+ def _parse_tile_valid_shape_subscript(
1205+ self,
1206+ base_expr: ir.Expr,
1207+ index_node: ast.expr,
1208+ span: ir.Span,
1209+ ) -> ir.Expr:
1210+ """Parse a runtime ``tile.valid_shape[axis]`` query."""
1211+ success, axis = self.expr_evaluator.try_eval_expr(index_node)
1212+ if not success or type(axis) is not int:
1213+ raise ParserSyntaxError(
1214+ "tile.valid_shape index must be a compile-time integer",
1215+ span=span,
1216+ hint="Use tile.valid_shape[0] or tile.valid_shape[1].",
1217+ )
1218+ 
1219+ rank = len(base_expr.type.shape)
1220+ original_axis = axis
1221+ if axis < 0:
1222+ axis += rank
1223+ if axis < 0 or axis >= rank:
1224+ raise ParserTypeError(
1225+ f"valid_shape index {original_axis} out of range for Tile rank {rank}",
1226+ span=span,
1227+ )
1228+ 
1229+ return ir.create_op_call("block.tile_valid_shape", [base_expr], {"axis": axis}, span)
1230+ 
1199 def _parse_scalar_subscript_index(1231 def _parse_scalar_subscript_index(
1200 self,1232 self,
1201 container_expr: ir.Expr,1233 container_expr: ir.Expr,
@@ -1281,6 +1313,13 @@ class ExpressionParserMixin:
1281 hint="Use pl.load/pl.store with offset lists for tensor access",1313 hint="Use pl.load/pl.store with offset lists for tensor access",
1282 )1314 )
1283 1315 
1316+ if self._current_func_type in (ir.FunctionType.SimtVF, ir.FunctionType.SimtCallee):
1317+ raise UnsupportedFeatureError(
1318+ "Tile subview is not supported inside a SIMT function",
1319+ span=span,
1320+ hint="Access the Tile directly with tile[row, col].",
1321+ )
1322+ 
1284 # VF section: tile slice 'tile[a:b, c:d]' is not supported.1323 # VF section: tile slice 'tile[a:b, c:d]' is not supported.
1285 # Use load_align(tile, [row, col]) / store_align(tile, ..., [row, col]) instead.1324 # Use load_align(tile, [row, col]) / store_align(tile, ..., [row, col]) instead.
1286 if self.inline_vf_depth > 0:1325 if self.inline_vf_depth > 0:
@@ -294,69 +294,6 @@ class TypeResolver:
294 return contains_policy(annotation)294 return contains_policy(annotation)
295 return False295 return False
296 296 
297- def validate_policy_return_types(
298- self,
299- type_node: ast.expr,
300- actual_types: list[ir.Type],
301- ) -> None:
302- """Validate policy-bearing return annotations against concrete returned types."""
303- success, annotation = self.expr_evaluator.try_eval_expr(type_node)
304- if not success:
305- raise ParserTypeError(
306- f"Cannot evaluate return annotation: {ast.unparse(type_node)}",
307- span=self._get_span(type_node),
308- )
309- 
310- origin = typing.get_origin(annotation)
311- expected_items = list(typing.get_args(annotation)) if origin is tuple else [annotation]
312- actual_items = actual_types
313- if origin is tuple and len(actual_types) == 1 and isinstance(actual_types[0], ir.TupleType):
314- actual_items = list(actual_types[0].types)
315- if len(expected_items) != len(actual_items):
316- raise ParserTypeError(
317- f"Return annotation expects {len(expected_items)} value(s), got {len(actual_items)}",
318- span=self._get_span(type_node),
319- )
320- 
321- from pypto_pro.language.typing.tensor import Tensor
322- from pypto_pro.runtime.shape_policy import FixedDim
323- 
324- for return_index, (expected, actual) in enumerate(zip(expected_items, actual_items)):
325- if not isinstance(expected, Tensor):
326- continue
327- if not isinstance(actual, ir.TensorType):
328- raise ParserTypeError(
329- f"Return value {return_index} must be a Tensor, got {type(actual).__name__}",
330- span=self._get_span(type_node),
331- )
332- if expected.dtype != actual.dtype:
333- raise ParserTypeError(
334- f"Return value {return_index} dtype mismatch: expected {expected.dtype}, got {actual.dtype}",
335- span=self._get_span(type_node),
336- )
337- shape_spec, rank_matches, explicit_rank = self._resolve_shape_spec_and_rank(
338- f"return[{return_index}]",
339- return_index,
340- expected.shape,
341- actual,
342- self._get_span(type_node),
343- )
344- if not rank_matches:
345- raise ParserTypeError(
346- f"Return value {return_index} rank mismatch for annotation {expected.shape}",
347- span=self._get_span(type_node),
348- )
349- explicit_rank = len(shape_spec.dimensions) - (1 if shape_spec.has_ellipsis else 0)
350- for axis, dimension in enumerate(shape_spec.dimensions[:explicit_rank]):
351- if not isinstance(dimension, FixedDim):
352- continue
353- actual_dim = actual.shape[axis]
354- if not isinstance(actual_dim, ir.ConstInt) or actual_dim.value != dimension.value:
355- raise ParserTypeError(
356- f"Return value {return_index} axis {axis} must be fixed at {dimension.value}, got {actual_dim}",
357- span=self._get_span(type_node),
358- )
359- 
360 def validate_policy_parameter_type(297 def validate_policy_parameter_type(
361 self,298 self,
362 type_node: ast.expr,299 type_node: ast.expr,
@@ -559,6 +559,33 @@ def function(
559 return _decorator(fn)559 return _decorator(fn)
560 560 
561 561 
562+_SIMT_FUNCTION_MARKER = "_pypto_simt_function"
563+_SIMT_MAX_THREADS_ATTR = "_pypto_simt_max_threads"
564+ 
565+ 
566+def simt_function(fn: Callable | None = None, *, max_threads: int | None = None) -> Callable:
567+ """Mark a callable for delayed SIMT parsing at its call site."""
568+ if fn is None and max_threads is None:
569+ raise TypeError("@pl.simt.function requires max_threads or a directly decorated function")
570+ 
571+ def decorate(func: Callable) -> Callable:
572+ setattr(func, _SIMT_FUNCTION_MARKER, True)
573+ setattr(func, _SIMT_MAX_THREADS_ATTR, max_threads)
574+ return func
575+ 
576+ return decorate(fn) if fn is not None else decorate
577+ 
578+ 
579+def is_simt_function(fn: Callable) -> bool:
580+ """Return whether *fn* is marked as a SIMT function template."""
581+ return bool(getattr(fn, _SIMT_FUNCTION_MARKER, False))
582+ 
583+ 
584+def get_simt_max_threads(fn: Callable) -> int | None:
585+ """Return the launch bound recorded by @pl.simt.function."""
586+ return getattr(fn, _SIMT_MAX_THREADS_ATTR, None)
587+ 
588+ 
562def inline(fn: Callable) -> Callable:589def inline(fn: Callable) -> Callable:
563 """Deprecated: @pl.inline has been removed. Use @pl.fn or pass as an annotated callable."""590 """Deprecated: @pl.inline has been removed. Use @pl.fn or pass as an annotated callable."""
564 import warnings591 import warnings
@@ -346,13 +346,16 @@ def _pl_dtype_to_torch(dtype: DataType):
346 346 
347 347 
348def _get_kernel_ir_function(prog):348def _get_kernel_ir_function(prog):
349- """Return the entry-like IR function used to emit the CCE kernel body."""349+ """Return the Opaque IR function that serves as the kernel entry."""
350 from pypto.pypto_impl.ir import FunctionType350 from pypto.pypto_impl.ir import FunctionType
351 351 
352 for f in prog.functions.values():352 for f in prog.functions.values():
353- if f.func_type not in (FunctionType.Helper, FunctionType.Orchestration):353+ if f.func_type == FunctionType.Opaque:
354 return f354 return f
355- return next(iter(prog.functions.values()))355+ raise RuntimeError(
356+ f"No Opaque kernel entry function found in program '{prog.name}' "
357+ f"(functions: {list(prog.functions)})"
358+ )
356 359 
357 360 
358def _extract_param_specs(prog) -> list[ParamSpec]:361def _extract_param_specs(prog) -> list[ParamSpec]:
@@ -1383,6 +1383,8 @@ void BindProgram(py::module_& ir)
1383 .value("Orchestration", FunctionType::ORCHESTRATION, "Host/AICPU control and coordination")1383 .value("Orchestration", FunctionType::ORCHESTRATION, "Host/AICPU control and coordination")
1384 .value("InCore", FunctionType::IN_CORE, "AICore sub-graph execution")1384 .value("InCore", FunctionType::IN_CORE, "AICore sub-graph execution")
1385 .value("Helper", FunctionType::HELPER, "Scalar helper callable from kernels (generates func.call)")1385 .value("Helper", FunctionType::HELPER, "Scalar helper callable from kernels (generates func.call)")
1386+ .value("SimtVF", FunctionType::SIMT_VF, "A5 SIMT vector function launched from an AIV kernel")
1387+ .value("SimtCallee", FunctionType::SIMT_CALLEE, "A5 helper callable from SIMT functions")
1386 .export_values();1388 .export_values();
1387 1389 
1388 // Function - const shared_ptr1390 // Function - const shared_ptr
@@ -1390,19 +1392,30 @@ void BindProgram(py::module_& ir)
1390 ir, "Function", py::dynamic_attr(), "Function definition with name, parameters, return types, and body");1392 ir, "Function", py::dynamic_attr(), "Function definition with name, parameters, return types, and body");
1391 function_class.def(1393 function_class.def(
1392 py::init([](const std::string& name, const py::list& params, const std::vector<TypePtr>& return_types,1394 py::init([](const std::string& name, const py::list& params, const std::vector<TypePtr>& return_types,
1393- const StmtPtr& body, const Span& span, FunctionType type, bool entry) -> std::shared_ptr<Function> {1395+ const StmtPtr& body, const Span& span, FunctionType type, bool entry,
1396+ const py::object& attrs) -> std::shared_ptr<Function> {
1394 std::vector<VarPtr> param_vars;1397 std::vector<VarPtr> param_vars;
1395 param_vars.reserve(py::len(params));1398 param_vars.reserve(py::len(params));
1396 for (auto item : params) {1399 for (auto item : params) {
1397 param_vars.push_back(py::cast<VarPtr>(item));1400 param_vars.push_back(py::cast<VarPtr>(item));
1398 }1401 }
1399- return std::make_shared<Function>(name, std::move(param_vars), return_types, body, span, type, entry);1402+ py::dict attr_dict;
1403+ if (!attrs.is_none()) {
1404+ attr_dict = attrs.cast<py::dict>();
1405+ }
1406+ auto attr_list = ConvertAttrDict(attr_dict);
1407+ return std::make_shared<Function>(name, std::move(param_vars), return_types, body, span, type, entry,
1408+ std::move(attr_list));
1400 }),1409 }),
1401 py::arg("name"), py::arg("params"), py::arg("return_types"), py::arg("body"), py::arg("span"),1410 py::arg("name"), py::arg("params"), py::arg("return_types"), py::arg("body"), py::arg("span"),
1402- py::arg("type") = FunctionType::OPAQUE, py::arg("entry") = false, "Create a function definition");1411+ py::arg("type") = FunctionType::OPAQUE, py::arg("entry") = false, py::arg("attrs") = py::none(),
1412+ "Create a function definition");
1403 BindFields<Function>(function_class);1413 BindFields<Function>(function_class);
1404 function_class.def(1414 function_class.def(
1405 "__str__", [](const std::shared_ptr<Function>& self) { return TextDump(self); }, "IR text representation");1415 "__str__", [](const std::shared_ptr<Function>& self) { return TextDump(self); }, "IR text representation");
1416+ function_class.def("has_attr", &Function::HasAttr, py::arg("key"), "Check whether a function attribute exists");
1417+ function_class.def("get_attr", &Function::GetAttr<int>, py::arg("key"), py::arg("default_value") = 0,
1418+ "Get an integer function attribute");
1406 1419 
1407 // IRDebugInfo - compilation-session side table for tuple/struct field names.1420 // IRDebugInfo - compilation-session side table for tuple/struct field names.
1408 auto debug_info_class = py::class_<IRDebugInfo, std::shared_ptr<IRDebugInfo>>(1421 auto debug_info_class = py::class_<IRDebugInfo, std::shared_ptr<IRDebugInfo>>(
@@ -0,0 +1,84 @@
1+# coding: utf-8
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+"""A5 system test for multiple distinct SimtVF definitions and launches."""
12+ 
13+import os
14+ 
15+import pypto_pro.language as pl
16+import pytest
17+import torch
18+ 
19+ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
20+ST_DEVICE = f"npu:{ST_DEVICE_ID}"
21+THREADS = 256
22+TILE_BYTES = THREADS * 4
23+ 
24+ 
25+def _require_a5():
26+ try:
27+ torch.npu.set_device(ST_DEVICE)
28+ except RuntimeError as exc:
29+ pytest.skip(f"NPU unavailable: {exc}")
30+ name = torch.npu.get_device_name()
31+ if "Ascend950" not in name:
32+ pytest.skip(f"Current device is {name}, not A5 (Ascend950). Skip.")
33+ 
34+ 
35+@pl.simt.function(max_threads=THREADS)
36+def add_inplace(data: pl.Tile[[1, THREADS], pl.DT_FP32], delta: pl.DT_FP32):
37+ tid = pl.simt.linear_thread_idx()
38+ data[0, tid] = data[0, tid] + delta
39+ 
40+ 
41+@pl.simt.function(max_threads=THREADS)
42+def mul_inplace(data: pl.Tile[[1, THREADS], pl.DT_FP32], scale: pl.DT_FP32):
43+ tid = pl.simt.linear_thread_idx()
44+ data[0, tid] = data[0, tid] * scale
45+ 
46+ 
47+@pl.jit(arch="a5")
48+def simt_multiple_functions(
49+ x: pl.Tensor[[1, THREADS], pl.DT_FP32],
50+ out: pl.Tensor[[1, THREADS], pl.DT_FP32],
51+ delta: pl.DT_FP32,
52+ scale: pl.DT_FP32,
53+):
54+ tile_type = pl.TileType(shape=[1, THREADS], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec)
55+ data = pl.make_tile(tile_type, addr=0x0000, size=TILE_BYTES)
56+ with pl.section_vector():
57+ pl.load(data, x, [0, 0])
58+ pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
59+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
60+ pl.simt.launch(add_inplace, threads=THREADS, args=(data, delta))
61+ pl.simt.launch(mul_inplace, threads=THREADS, args=(data, scale))
62+ pl.system.sync_src(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
63+ pl.system.sync_dst(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
64+ pl.store(out, data, [0, 0])
65+ 
66+ 
67+@pytest.mark.soc("950")
68+def test_multiple_functions():
69+ _require_a5()
70+ 
71+ delta = 1.25
72+ scale = 2.5
73+ x = torch.arange(THREADS, dtype=torch.float32).reshape(1, THREADS).to(ST_DEVICE)
74+ out = torch.empty_like(x)
75+ 
76+ simt_multiple_functions(x, out, delta, scale)
77+ torch.npu.synchronize()
78+ 
79+ expected = (x.cpu() + delta) * scale
80+ torch.testing.assert_close(out.cpu(), expected, rtol=0, atol=0)
81+ 
82+ 
83+if __name__ == "__main__":
84+ test_multiple_functions()
@@ -0,0 +1,83 @@
1+# coding: utf-8
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+"""A5 system test for an explicitly synchronized SIMD -> SIMT -> SIMD pipeline."""
12+ 
13+import os
14+ 
15+import pypto_pro.language as pl
16+import pytest
17+import torch
18+ 
19+ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
20+ST_DEVICE = f"npu:{ST_DEVICE_ID}"
21+THREADS = 256
22+TILE_BYTES = THREADS * 4
23+ 
24+ 
25+def _require_a5():
26+ try:
27+ torch.npu.set_device(ST_DEVICE)
28+ except RuntimeError as exc:
29+ pytest.skip(f"NPU unavailable: {exc}")
30+ name = torch.npu.get_device_name()
31+ if "Ascend950" not in name:
32+ pytest.skip(f"Current device is {name}, not A5 (Ascend950). Skip.")
33+ 
34+ 
35+@pl.simt.function(max_threads=THREADS)
36+def simt_add_inplace(data: pl.Tile[[1, THREADS], pl.DT_FP32], delta: pl.DT_FP32):
37+ tid = pl.simt.linear_thread_idx()
38+ data[0, tid] = data[0, tid] + delta
39+ 
40+ 
41+@pl.jit(arch="a5")
42+def simd_simt_pipeline(
43+ x: pl.Tensor[[1, THREADS], pl.DT_FP32],
44+ out: pl.Tensor[[1, THREADS], pl.DT_FP32],
45+ pre_scale: pl.DT_FP32,
46+ delta: pl.DT_FP32,
47+ post_scale: pl.DT_FP32,
48+):
49+ tile_type = pl.TileType(shape=[1, THREADS], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec)
50+ src = pl.make_tile(tile_type, addr=0x0000, size=TILE_BYTES)
51+ simt_data = pl.make_tile(tile_type, addr=0x0400, size=TILE_BYTES)
52+ result = pl.make_tile(tile_type, addr=0x0800, size=TILE_BYTES)
53+ with pl.section_vector():
54+ pl.load(src, x, [0, 0])
55+ pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
56+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
57+ pl.muls(simt_data, src, pre_scale)
58+ pl.simt.launch(simt_add_inplace, threads=THREADS, args=(simt_data, delta))
59+ pl.muls(result, simt_data, post_scale)
60+ pl.system.sync_src(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=3)
61+ pl.system.sync_dst(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=3)
62+ pl.store(out, result, [0, 0])
63+ 
64+ 
65+@pytest.mark.soc("950")
66+def test_simd_simt_pipeline():
67+ _require_a5()
68+ 
69+ pre_scale = 2.0
70+ delta = 1.25
71+ post_scale = 0.5
72+ x = torch.arange(THREADS, dtype=torch.float32).reshape(1, THREADS).to(ST_DEVICE)
73+ out = torch.empty_like(x)
74+ 
75+ simd_simt_pipeline(x, out, pre_scale, delta, post_scale)
76+ torch.npu.synchronize()
77+ 
78+ expected = (x.cpu() * pre_scale + delta) * post_scale
79+ torch.testing.assert_close(out.cpu(), expected, rtol=0, atol=0)
80+ 
81+ 
82+if __name__ == "__main__":
83+ test_simd_simt_pipeline()
@@ -0,0 +1,108 @@
1+# coding: utf-8
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+"""A5 system test for scalar, void, and nested SIMT callees."""
12+ 
13+import os
14+ 
15+import pypto_pro.language as pl
16+import pytest
17+import torch
18+ 
19+ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
20+ST_DEVICE = f"npu:{ST_DEVICE_ID}"
21+THREADS = 32
22+TILE_BYTES = THREADS * 4
23+ 
24+ 
25+def _require_a5():
26+ try:
27+ torch.npu.set_device(ST_DEVICE)
28+ except RuntimeError as exc:
29+ pytest.skip(f"NPU unavailable: {exc}")
30+ name = torch.npu.get_device_name()
31+ if "Ascend950" not in name:
32+ pytest.skip(f"Current device is {name}, not A5 (Ascend950). Skip.")
33+ 
34+ 
35+@pl.simt.function
36+def affine(value: pl.DT_FP32, scale: pl.DT_FP32, delta: pl.DT_FP32) -> pl.DT_FP32:
37+ return value * scale + delta
38+ 
39+ 
40+@pl.simt.function
41+def store_value(
42+ dst: pl.Tile[[1, THREADS], pl.DT_FP32],
43+ index: pl.DT_UINT32,
44+ value: pl.DT_FP32,
45+):
46+ dst[0, index] = value
47+ 
48+ 
49+@pl.simt.function
50+def transform_one(
51+ dst: pl.Tile[[1, THREADS], pl.DT_FP32],
52+ src: pl.Tile[[1, THREADS], pl.DT_FP32],
53+ index: pl.DT_UINT32,
54+ scale: pl.DT_FP32,
55+ delta: pl.DT_FP32,
56+):
57+ value = affine(src[0, index], scale, delta)
58+ store_value(dst, index, value)
59+ 
60+ 
61+@pl.simt.function(max_threads=THREADS)
62+def transform_tile(
63+ dst: pl.Tile[[1, THREADS], pl.DT_FP32],
64+ src: pl.Tile[[1, THREADS], pl.DT_FP32],
65+ scale: pl.DT_FP32,
66+ delta: pl.DT_FP32,
67+):
68+ tid = pl.simt.linear_thread_idx()
69+ transform_one(dst, src, tid, scale, delta)
70+ 
71+ 
72+@pl.jit(arch="a5")
73+def simt_callee_kernel(
74+ x: pl.Tensor[[1, THREADS], pl.DT_FP32],
75+ out: pl.Tensor[[1, THREADS], pl.DT_FP32],
76+ scale: pl.DT_FP32,
77+ delta: pl.DT_FP32,
78+):
79+ tile_type = pl.TileType(shape=[1, THREADS], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec)
80+ src = pl.make_tile(tile_type, addr=0x0000, size=TILE_BYTES)
81+ dst = pl.make_tile(tile_type, addr=0x0080, size=TILE_BYTES)
82+ with pl.section_vector():
83+ pl.load(src, x, [0, 0])
84+ pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
85+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
86+ pl.simt.launch(transform_tile, threads=THREADS, args=(dst, src, scale, delta))
87+ pl.system.sync_src(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
88+ pl.system.sync_dst(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
89+ pl.store(out, dst, [0, 0])
90+ 
91+ 
92+@pytest.mark.soc("950")
93+def test_simt_callee():
94+ _require_a5()
95+ 
96+ scale = 1.5
97+ delta = -2.0
98+ x = torch.arange(THREADS, dtype=torch.float32).reshape(1, THREADS).to(ST_DEVICE)
99+ out = torch.empty_like(x)
100+ 
101+ simt_callee_kernel(x, out, scale, delta)
102+ torch.npu.synchronize()
103+ 
104+ torch.testing.assert_close(out.cpu(), x.cpu() * scale + delta, rtol=0, atol=0)
105+ 
106+ 
107+if __name__ == "__main__":
108+ test_simt_callee()
@@ -0,0 +1,74 @@
1+# coding: utf-8
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+"""A5 end-to-end test for a one-dimensional SIMT launch."""
12+ 
13+import os
14+ 
15+import pypto_pro.language as pl
16+import pytest
17+import torch
18+ 
19+ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
20+ST_DEVICE = f"npu:{ST_DEVICE_ID}"
21+THREADS = 256
22+TILE_BYTES = THREADS * 4
23+ 
24+ 
25+def _require_a5():
26+ try:
27+ torch.npu.set_device(ST_DEVICE)
28+ except RuntimeError as exc:
29+ pytest.skip(f"NPU unavailable: {exc}")
30+ name = torch.npu.get_device_name()
31+ if "Ascend950" not in name:
32+ pytest.skip(f"Current device is {name}, not A5 (Ascend950). Skip.")
33+ 
34+ 
35+@pl.simt.function(max_threads=THREADS)
36+def add_1d(data: pl.Tile[[1, THREADS], pl.DT_FP32], delta: pl.DT_FP32):
37+ tid = pl.simt.thread_idx().x
38+ data[0, tid] = data[0, tid] + delta
39+ 
40+ 
41+@pl.jit(arch="a5")
42+def simt_1d_launch(
43+ x: pl.Tensor[[1, THREADS], pl.DT_FP32],
44+ out: pl.Tensor[[1, THREADS], pl.DT_FP32],
45+ delta: pl.DT_FP32,
46+):
47+ tile_type = pl.TileType(shape=[1, THREADS], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec)
48+ data = pl.make_tile(tile_type, addr=0x0000, size=TILE_BYTES)
49+ with pl.section_vector():
50+ pl.load(data, x, [0, 0])
51+ pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
52+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
53+ pl.simt.launch(add_1d, threads=THREADS, args=(data, delta))
54+ pl.system.sync_src(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
55+ pl.system.sync_dst(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
56+ pl.store(out, data, [0, 0])
57+ 
58+ 
59+@pytest.mark.soc("950")
60+def test_1d_launch():
61+ _require_a5()
62+ 
63+ delta = 2.5
64+ x = torch.arange(THREADS, dtype=torch.float32).reshape(1, THREADS).to(ST_DEVICE)
65+ out = torch.empty_like(x)
66+ 
67+ simt_1d_launch(x, out, delta)
68+ torch.npu.synchronize()
69+ 
70+ torch.testing.assert_close(out.cpu(), x.cpu() + delta, rtol=0, atol=0)
71+ 
72+ 
73+if __name__ == "__main__":
74+ test_1d_launch()
@@ -0,0 +1,77 @@
1+# coding: utf-8
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+"""A5 end-to-end test for a two-dimensional SIMT launch."""
12+ 
13+import os
14+ 
15+import pypto_pro.language as pl
16+import pytest
17+import torch
18+ 
19+ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
20+ST_DEVICE = f"npu:{ST_DEVICE_ID}"
21+THREADS_X = 16
22+THREADS_Y = 16
23+THREADS = THREADS_X * THREADS_Y
24+TILE_BYTES = THREADS * 4
25+ 
26+ 
27+def _require_a5():
28+ try:
29+ torch.npu.set_device(ST_DEVICE)
30+ except RuntimeError as exc:
31+ pytest.skip(f"NPU unavailable: {exc}")
32+ name = torch.npu.get_device_name()
33+ if "Ascend950" not in name:
34+ pytest.skip(f"Current device is {name}, not A5 (Ascend950). Skip.")
35+ 
36+ 
37+@pl.simt.function(max_threads=THREADS)
38+def add_2d(data: pl.Tile[[1, THREADS], pl.DT_FP32], delta: pl.DT_FP32):
39+ thread = pl.simt.thread_idx()
40+ tid = thread.x + thread.y * THREADS_X
41+ data[0, tid] = data[0, tid] + delta
42+ 
43+ 
44+@pl.jit(arch="a5")
45+def simt_2d_launch(
46+ x: pl.Tensor[[1, THREADS], pl.DT_FP32],
47+ out: pl.Tensor[[1, THREADS], pl.DT_FP32],
48+ delta: pl.DT_FP32,
49+):
50+ tile_type = pl.TileType(shape=[1, THREADS], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec)
51+ data = pl.make_tile(tile_type, addr=0x0000, size=TILE_BYTES)
52+ with pl.section_vector():
53+ pl.load(data, x, [0, 0])
54+ pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
55+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
56+ pl.simt.launch(add_2d, threads=(THREADS_X, THREADS_Y), args=(data, delta))
57+ pl.system.sync_src(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
58+ pl.system.sync_dst(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
59+ pl.store(out, data, [0, 0])
60+ 
61+ 
62+@pytest.mark.soc("950")
63+def test_2d_launch():
64+ _require_a5()
65+ 
66+ delta = 1.5
67+ x = torch.arange(THREADS, dtype=torch.float32).reshape(1, THREADS).to(ST_DEVICE)
68+ out = torch.empty_like(x)
69+ 
70+ simt_2d_launch(x, out, delta)
71+ torch.npu.synchronize()
72+ 
73+ torch.testing.assert_close(out.cpu(), x.cpu() + delta, rtol=0, atol=0)
74+ 
75+ 
76+if __name__ == "__main__":
77+ test_2d_launch()
@@ -0,0 +1,78 @@
1+# coding: utf-8
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+"""A5 end-to-end test for a three-dimensional SIMT launch."""
12+ 
13+import os
14+ 
15+import pypto_pro.language as pl
16+import pytest
17+import torch
18+ 
19+ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
20+ST_DEVICE = f"npu:{ST_DEVICE_ID}"
21+THREADS_X = 8
22+THREADS_Y = 4
23+THREADS_Z = 8
24+THREADS = THREADS_X * THREADS_Y * THREADS_Z
25+TILE_BYTES = THREADS * 4
26+ 
27+ 
28+def _require_a5():
29+ try:
30+ torch.npu.set_device(ST_DEVICE)
31+ except RuntimeError as exc:
32+ pytest.skip(f"NPU unavailable: {exc}")
33+ name = torch.npu.get_device_name()
34+ if "Ascend950" not in name:
35+ pytest.skip(f"Current device is {name}, not A5 (Ascend950). Skip.")
36+ 
37+ 
38+@pl.simt.function(max_threads=THREADS)
39+def add_3d(data: pl.Tile[[1, THREADS], pl.DT_FP32], delta: pl.DT_FP32):
40+ thread = pl.simt.thread_idx()
41+ tid = thread.x + thread.y * THREADS_X + thread.z * THREADS_X * THREADS_Y
42+ data[0, tid] = data[0, tid] + delta
43+ 
44+ 
45+@pl.jit(arch="a5")
46+def simt_3d_launch(
47+ x: pl.Tensor[[1, THREADS], pl.DT_FP32],
48+ out: pl.Tensor[[1, THREADS], pl.DT_FP32],
49+ delta: pl.DT_FP32,
50+):
51+ tile_type = pl.TileType(shape=[1, THREADS], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec)
52+ data = pl.make_tile(tile_type, addr=0x0000, size=TILE_BYTES)
53+ with pl.section_vector():
54+ pl.load(data, x, [0, 0])
55+ pl.system.sync_src(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
56+ pl.system.sync_dst(set_pipe=pl.PipeType.MTE2, wait_pipe=pl.PipeType.V, event_id=0)
57+ pl.simt.launch(add_3d, threads=(THREADS_X, THREADS_Y, THREADS_Z), args=(data, delta))
58+ pl.system.sync_src(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
59+ pl.system.sync_dst(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=1)
60+ pl.store(out, data, [0, 0])
61+ 
62+ 
63+@pytest.mark.soc("950")
64+def test_3d_launch():
65+ _require_a5()
66+ 
67+ delta = 0.75
68+ x = torch.arange(THREADS, dtype=torch.float32).reshape(1, THREADS).to(ST_DEVICE)
69+ out = torch.empty_like(x)
70+ 
71+ simt_3d_launch(x, out, delta)
72+ torch.npu.synchronize()
73+ 
74+ torch.testing.assert_close(out.cpu(), x.cpu() + delta, rtol=0, atol=0)
75+ 
76+ 
77+if __name__ == "__main__":
78+ test_3d_launch()
@@ -0,0 +1,74 @@
1+# coding: utf-8
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+"""A5 ST: simt.launch with auto_mutex — no manual sync_src/sync_dst needed.
12+ 
13+Uses make_tile_group(mutex_ids=[0]) so auto_mutex inserts mutex_lock(PIPE_V) /
14+mutex_unlock(PIPE_V) around load, simt.launch, and store automatically.
15+"""
16+ 
17+import os
18+ 
19+import pypto_pro.language as pl
20+import pytest
21+import torch
22+ 
23+ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
24+ST_DEVICE = f"npu:{ST_DEVICE_ID}"
25+THREADS = 256
26+TILE_BYTES = THREADS * 4
27+ 
28+ 
29+def _require_a5():
30+ try:
31+ torch.npu.set_device(ST_DEVICE)
32+ except RuntimeError as exc:
33+ pytest.skip(f"NPU unavailable: {exc}")
34+ name = torch.npu.get_device_name()
35+ if "Ascend950" not in name:
36+ pytest.skip(f"Current device is {name}, not A5 (Ascend950). Skip.")
37+ 
38+ 
39+@pl.simt.function(max_threads=THREADS)
40+def auto_mutex_add(data: pl.Tile[[1, THREADS], pl.DT_FP32], delta: pl.DT_FP32):
41+ tid = pl.simt.linear_thread_idx()
42+ data[0, tid] = data[0, tid] + delta
43+ 
44+ 
45+@pl.jit(arch="a5")
46+def simt_auto_mutex_kernel(
47+ x: pl.Tensor[[1, THREADS], pl.DT_FP32],
48+ out: pl.Tensor[[1, THREADS], pl.DT_FP32],
49+ delta: pl.DT_FP32,
50+):
51+ tile_type = pl.TileType(shape=[1, THREADS], dtype=pl.DT_FP32, target_memory=pl.MemorySpace.Vec)
52+ data = pl.make_tile_group(type=tile_type, addrs=0x0000, mutex_ids=[0])
53+ with pl.section_vector():
54+ pl.load(data.current(), x, [0, 0])
55+ pl.simt.launch(auto_mutex_add, threads=THREADS, args=(data.current(), delta))
56+ pl.store(out, data.current(), [0, 0])
57+ 
58+ 
59+@pytest.mark.soc("950")
60+def test_auto_mutex_launch():
61+ _require_a5()
62+ 
63+ delta = 3.5
64+ x = torch.arange(THREADS, dtype=torch.float32).reshape(1, THREADS).to(ST_DEVICE)
65+ out = torch.empty_like(x)
66+ 
67+ simt_auto_mutex_kernel(x, out, delta)
68+ torch.npu.synchronize()
69+ 
70+ torch.testing.assert_close(out.cpu(), x.cpu() + delta, rtol=0, atol=0)
71+ 
72+ 
73+if __name__ == "__main__":
74+ test_auto_mutex_launch()
@@ -0,0 +1,68 @@
1+# coding: utf-8
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+"""A5 end-to-end test for launching a SIMT function on multiple AIV cores."""
12+ 
13+import os
14+ 
15+import pypto_pro.language as pl
16+import pytest
17+import torch
18+ 
19+ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
20+ST_DEVICE = f"npu:{ST_DEVICE_ID}"
21+GRID_BLOCKS = 4
22+THREADS = 64
23+TILE_BYTES = THREADS * 4
24+ 
25+ 
26+def _require_a5():
27+ try:
28+ torch.npu.set_device(ST_DEVICE)
29+ except RuntimeError as exc:
30+ pytest.skip(f"NPU unavailable: {exc}")
31+ name = torch.npu.get_device_name()
32+ if "Ascend950" not in name:
33+ pytest.skip(f"Current device is {name}, not A5 (Ascend950). Skip.")
34+ 
35+ 
36+@pl.simt.function(max_threads=THREADS)
37+def write_multicore_result(dst: pl.Tile[[1, THREADS], pl.DT_UINT32]):
38+ tid = pl.simt.linear_thread_idx()
39+ core_id = pl.simt.block_idx().x
40+ dst[0, tid] = core_id * THREADS + tid
41+ 
42+ 
43+@pl.jit(arch="a5")
44+def simt_multicore(out: pl.Tensor[[GRID_BLOCKS, THREADS], pl.DT_UINT32]):
45+ tile_type = pl.TileType(shape=[1, THREADS], dtype=pl.DT_UINT32, target_memory=pl.MemorySpace.Vec)
46+ dst = pl.make_tile(tile_type, addr=0x0000, size=TILE_BYTES)
47+ with pl.section_vector():
48+ core_id = pl.get_block_idx()
49+ pl.simt.launch(write_multicore_result, threads=THREADS, args=(dst,))
50+ pl.system.sync_src(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=0)
51+ pl.system.sync_dst(set_pipe=pl.PipeType.V, wait_pipe=pl.PipeType.MTE3, event_id=0)
52+ pl.store(out, dst, [core_id, 0])
53+ 
54+ 
55+@pytest.mark.soc("950")
56+def test_multicore():
57+ _require_a5()
58+ 
59+ out = torch.empty((GRID_BLOCKS, THREADS), dtype=torch.int32).to(torch.uint32).to(ST_DEVICE)
60+ simt_multicore[None, GRID_BLOCKS](out)
61+ torch.npu.synchronize()
62+ 
63+ expected = torch.arange(GRID_BLOCKS * THREADS, dtype=torch.int64).reshape(GRID_BLOCKS, THREADS)
64+ torch.testing.assert_close(out.cpu().to(torch.int64), expected, rtol=0, atol=0)
65+ 
66+ 
67+if __name__ == "__main__":
68+ test_multicore()
@@ -0,0 +1,77 @@
1+# coding: utf-8
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+"""A5 end-to-end test for direct SIMT GM Tensor access."""
12+ 
13+import os
14+ 
15+import pypto_pro.language as pl
16+import pytest
17+import torch
18+ 
19+ST_DEVICE_ID = int(os.environ.get("TILE_FWK_DEVICE_ID", 0))
20+ST_DEVICE = f"npu:{ST_DEVICE_ID}"
21+THREADS = 256
22+ 
23+ 
24+def _require_a5():
25+ try:
26+ torch.npu.set_device(ST_DEVICE)
27+ except RuntimeError as exc:
28+ pytest.skip(f"NPU unavailable: {exc}")
29+ name = torch.npu.get_device_name()
30+ if "Ascend950" not in name:
31+ pytest.skip(f"Current device is {name}, not A5 (Ascend950). Skip.")
32+ 
33+ 
34+@pl.simt.function(max_threads=THREADS)
35+def gm_add(
36+ dst: pl.Tensor[[1, THREADS], pl.DT_FP32],
37+ src: pl.Tensor[[1, THREADS], pl.DT_FP32],
38+ n: pl.DT_UINT32,
39+ delta: pl.DT_FP32,
40+):
41+ tid = pl.simt.linear_thread_idx()
42+ if tid < n:
43+ dst[0, tid] = src[0, tid] + delta
44+ 
45+ 
46+@pl.jit(arch="a5")
47+def simt_gm_add(
48+ x: pl.Tensor[[1, THREADS], pl.DT_FP32],
49+ out: pl.Tensor[[1, THREADS], pl.DT_FP32],
50+ n: pl.DT_UINT32,
51+ delta: pl.DT_FP32,
52+):
53+ with pl.section_vector():
54+ pl.simt.launch(gm_add, threads=THREADS, args=(out, x, n, delta))
55+ 
56+ 
57+@pytest.mark.soc("950")
58+@pytest.mark.parametrize("n", [0, 193, THREADS])
59+def test_gm_tensor_access(n):
60+ _require_a5()
61+ 
62+ delta = 1.5
63+ sentinel = -7.0
64+ x = torch.arange(THREADS, dtype=torch.float32).reshape(1, THREADS).to(ST_DEVICE)
65+ out = torch.full_like(x, sentinel)
66+ 
67+ simt_gm_add(x, out, n, delta)
68+ torch.npu.synchronize()
69+ 
70+ expected = torch.full((1, THREADS), sentinel, dtype=torch.float32)
71+ expected[:, :n] = x.cpu()[:, :n] + delta
72+ torch.testing.assert_close(out.cpu(), expected, rtol=0, atol=0)
73+ 
74+ 
75+if __name__ == "__main__":
76+ for active_threads in (0, 193, THREADS):
77+ test_gm_tensor_access(active_threads)