Merged
feat(pypto_pro): Sync pypto_pro newest code #4967
wuzhongxinAdd on Jul 20
feat(pypto_pro): Sync pypto_pro newest code #4967
Merged
Merged fromwuzhongxin/cann_pyptosyncintocann/pyptomaster
Total: 30 files changed+1467-1122
| @@ -158,7 +158,9 @@ PYPTO_DECLARE_ENUM(MergeMode, ZEROING, MERGING) | |||
| 158 | 158 | ||
| 159 | PYPTO_DECLARE_ENUM(ReduceMode, SUM, MAX, MIN) | 159 | PYPTO_DECLARE_ENUM(ReduceMode, SUM, MAX, MIN) |
| 160 | 160 | ||
| 161 | -PYPTO_DECLARE_ENUM(CompareMode, EQ, NE, LT, GT, LE, GE) | 161 | +PYPTO_DECLARE_ENUM(CompareMode, EQ, NE, LT, LE, GT, GE) |
| 162 | + | ||
| 163 | +PYPTO_DECLARE_ENUM(CmpMode, EQ, NE, LT, LE, GT, GE) | ||
| 162 | 164 | ||
| 163 | PYPTO_DECLARE_ENUM(DuplicatePos, LOWEST, HIGHEST) | 165 | PYPTO_DECLARE_ENUM(DuplicatePos, LOWEST, HIGHEST) |
| 164 | 166 | ||
| @@ -191,10 +193,6 @@ PYPTO_DECLARE_ENUM(IndexOrder, INCREASE_ORDER, DECREASE_ORDER) | |||
| 191 | PYPTO_DECLARE_ENUM(MemBarMode, VST_VLD, VLD_VST, VST_VST, VST_LD, VST_ST, VLD_ST, ST_VLD, ST_VST, LD_VST, VV_ALL, | 193 | PYPTO_DECLARE_ENUM(MemBarMode, VST_VLD, VLD_VST, VST_VST, VST_LD, VST_ST, VLD_ST, ST_VLD, ST_VST, LD_VST, VV_ALL, |
| 192 | VS_ALL, SV_ALL) | 194 | VS_ALL, SV_ALL) |
| 193 | 195 | ||
| 194 | -PYPTO_DECLARE_ENUM(MaskLoadDist, NORM, US, DS) | ||
| 195 | - | ||
| 196 | -PYPTO_DECLARE_ENUM(MaskStoreDist, NORM, PK) | ||
| 197 | - | ||
| 198 | } // namespace ir | 196 | } // namespace ir |
| 199 | } // namespace pypto | 197 | } // namespace pypto |
| 200 | 198 | ||
| @@ -59,7 +59,6 @@ std::string ComputeStrideBasedOffset(codegen::CCECodegen& codegen, const ir::Mak | |||
| 59 | bool IsNZTensorType(const ir::TensorTypePtr& tensor_type); | 59 | bool IsNZTensorType(const ir::TensorTypePtr& tensor_type); |
| 60 | int64_t GetNZInnerCols(const ir::DataType& dtype, | 60 | int64_t GetNZInnerCols(const ir::DataType& dtype, |
| 61 | const std::string& error_prefix = "CCE NZ tensor lowering does not support dtype "); | 61 | const std::string& error_prefix = "CCE NZ tensor lowering does not support dtype "); |
| 62 | -std::string GetCmpModeEnum(int cmp_type); | ||
| 63 | void ValidateStoreNZPreconditions(const std::string& op_name, const ir::ExprPtr& src_expr, | 62 | void ValidateStoreNZPreconditions(const std::string& op_name, const ir::ExprPtr& src_expr, |
| 64 | const ir::MakeTuplePtr& offsets, const ir::TensorTypePtr& dst_tensor_type); | 63 | const ir::MakeTuplePtr& offsets, const ir::TensorTypePtr& dst_tensor_type); |
| 65 | 64 | ||
| @@ -147,6 +147,9 @@ public: | |||
| 147 | return "0x0"; | 147 | return "0x0"; |
| 148 | } | 148 | } |
| 149 | 149 | ||
| 150 | + /** \brief Set the base address of a tile variable (for subview offset registration). */ | ||
| 151 | + void SetTileAddress(const std::string& tile_name, const std::string& addr) { tile_addresses_[tile_name] = addr; } | ||
| 152 | + | ||
| 150 | /** \brief Register valid-shape C++ code strings for a tile at emit-time. | 153 | /** \brief Register valid-shape C++ code strings for a tile at emit-time. |
| 151 | * | 154 | * |
| 152 | * Called from set_validshape codegen when each SetValidShape line is emitted. | 155 | * Called from set_validshape codegen when each SetValidShape line is emitted. |
| @@ -223,6 +226,14 @@ public: | |||
| 223 | */ | 226 | */ |
| 224 | [[nodiscard]] bool HasPointer(const std::string& var_name) const; | 227 | [[nodiscard]] bool HasPointer(const std::string& var_name) const; |
| 225 | 228 | ||
| 229 | + /** | ||
| 230 | + * \brief Check whether a tile address (TASSIGN) has been registered. | ||
| 231 | + * | ||
| 232 | + * Distinguishes a tile with a known base address from one that needs to be | ||
| 233 | + * resolved via .data() or memref. | ||
| 234 | + */ | ||
| 235 | + [[nodiscard]] bool HasTileAddress(const std::string& tile_name) const; | ||
| 236 | + | ||
| 226 | /** | 237 | /** |
| 227 | * \brief Record that the named C++ variable holds a value of the given | 238 | * \brief Record that the named C++ variable holds a value of the given |
| 228 | * struct type (e.g. "CubeCtx_slot_0" ->"CubeCtx"). Used so dynamic | 239 | * struct type (e.g. "CubeCtx_slot_0" ->"CubeCtx"). Used so dynamic |
| @@ -671,12 +682,10 @@ private: | |||
| 671 | // are propagated in VisitStmt_(ForStmtPtr). | 682 | // are propagated in VisitStmt_(ForStmtPtr). |
| 672 | std::map<std::string, ir::MakeTuplePtr> tuple_var_to_make_tuple_; | 683 | std::map<std::string, ir::MakeTuplePtr> tuple_var_to_make_tuple_; |
| 673 | 684 | ||
| 674 | - // Tuple variable names whose homogeneous MakeTuple assignment emitted a C++ | 685 | + // Homogeneous MakeTuple object -> its first materialized C++ backing array. |
| 675 | - // backing array. Tuple array identity is scoped to the assignment variable, | 686 | + // Parser constant propagation can replace tuple Vars with their MakeTuple, so |
| 676 | - // not the MakeTuple expression, which may be shared by multiple inline sites. | 687 | + // array identity must follow the IR object rather than a particular Var name. |
| 677 | - std::set<std::string> tuple_vars_with_dyn_array_; | 688 | + std::map<const ir::MakeTuple*, std::string> tuple_backing_arr_; |
| 678 | - | ||
| 679 | - int dyn_arr_counter_ = 0; | ||
| 680 | 689 | ||
| 681 | /** | 690 | /** |
| 682 | * \brief Whether all element types of a tuple are structurally identical. | 691 | * \brief Whether all element types of a tuple are structurally identical. |
| @@ -698,7 +707,7 @@ private: | |||
| 698 | */ | 707 | */ |
| 699 | std::vector<std::string> CollectTupleElemNames(const ir::ExprPtr& tuple_value); | 708 | std::vector<std::string> CollectTupleElemNames(const ir::ExprPtr& tuple_value); |
| 700 | std::string BuildDynamicTupleArrayDecl(const ir::TypePtr& elem_type, const std::vector<std::string>& elem_names, | 709 | std::string BuildDynamicTupleArrayDecl(const ir::TypePtr& elem_type, const std::vector<std::string>& elem_names, |
| 701 | - const std::string& arr_name, bool allow_struct_tuple) const; | 710 | + const std::string& arr_name) const; |
| 702 | 711 | ||
| 703 | /// Emit-time valid-shape map: tile C++ name -> (row code, col code). | 712 | /// Emit-time valid-shape map: tile C++ name -> (row code, col code). |
| 704 | /// Populated when set_validshape is emitted; consumed by the following load or store. | 713 | /// Populated when set_validshape is emitted; consumed by the following load or store. |
| @@ -43,32 +43,26 @@ GetItemExpr::GetItemExpr(ExprPtr value, ExprPtr slice, Span span) | |||
| 43 | CHECK(slice_) << "GetItemExpr requires a non-null slice"; | 43 | CHECK(slice_) << "GetItemExpr requires a non-null slice"; |
| 44 | 44 | ||
| 45 | auto value_type = value_->GetType(); | 45 | auto value_type = value_->GetType(); |
| 46 | - if (auto tile_type = As<TileType>(value_type)) { | ||
| 47 | - type_ = tile_type; | ||
| 48 | - return; | ||
| 49 | - } | ||
| 50 | 46 | ||
| 51 | - if (auto tuple_type = As<TupleType>(value_type)) { | 47 | + auto tuple_type = As<TupleType>(value_type); |
| 52 | - if (auto const_idx = As<ConstInt>(slice_)) { | 48 | + CHECK(tuple_type) << "GetItemExpr requires value to have TupleType, got " << value_type->TypeName(); |
| 53 | - int index = static_cast<int>(const_idx->value_); | 49 | + |
| 54 | - CHECK(index >= 0 && index < static_cast<int>(tuple_type->types_.size())) | 50 | + if (auto const_idx = As<ConstInt>(slice_)) { |
| 55 | - << "GetItemExpr index " << index << " out of bounds for tuple with " << tuple_type->types_.size() | 51 | + int index = static_cast<int>(const_idx->value_); |
| 56 | - << " elements"; | 52 | + CHECK(index >= 0 && index < static_cast<int>(tuple_type->types_.size())) |
| 57 | - type_ = tuple_type->types_[index]; | 53 | + << "GetItemExpr index " << index << " out of bounds for tuple with " << tuple_type->types_.size() |
| 58 | - } else { | 54 | + << " elements"; |
| 59 | - CHECK(!tuple_type->types_.empty()) << "GetItemExpr: cannot index into an empty tuple"; | 55 | + type_ = tuple_type->types_[index]; |
| 60 | - const auto& first = tuple_type->types_[0]; | 56 | + } else { |
| 61 | - for (size_t i = 1; i < tuple_type->types_.size(); ++i) { | 57 | + CHECK(!tuple_type->types_.empty()) << "GetItemExpr: cannot index into an empty tuple"; |
| 62 | - CHECK(structural_equal(first, tuple_type->types_[i])) | 58 | + const auto& first = tuple_type->types_[0]; |
| 63 | - << "GetItemExpr with dynamic index requires all tuple elements to have the same type, " | 59 | + for (size_t i = 1; i < tuple_type->types_.size(); ++i) { |
| 64 | - << "but element 0 and element " << i << " differ"; | 60 | + CHECK(structural_equal(first, tuple_type->types_[i])) |
| 65 | - } | 61 | + << "GetItemExpr with dynamic index requires all tuple elements to have the same type, " |
| 66 | - type_ = first; | 62 | + << "but element 0 and element " << i << " differ"; |
| 67 | } | 63 | } |
| 68 | - return; | 64 | + type_ = first; |
| 69 | } | 65 | } |
| 70 | - | ||
| 71 | - CHECK(false) << "GetItemExpr requires value to have TupleType or TileType, got " << value_type->TypeName(); | ||
| 72 | } | 66 | } |
| 73 | 67 | ||
| 74 | } // namespace ir | 68 | } // namespace ir |
| @@ -263,5 +263,40 @@ REGISTER_OP("block.setval") | |||
| 263 | [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | 263 | [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { |
| 264 | return DeduceSetValType(args, kwargs); | 264 | return DeduceSetValType(args, kwargs); |
| 265 | }); | 265 | }); |
| 266 | + | ||
| 267 | +// ============================================================================ | ||
| 268 | +// block.subview — Tile/Tensor sub-view with offset and new shape | ||
| 269 | +// ============================================================================ | ||
| 270 | + | ||
| 271 | +TypePtr DeduceSubViewType([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 272 | + [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) | ||
| 273 | +{ | ||
| 274 | + // args: [container, offset, valid_shape] | ||
| 275 | + // Type deduction uses the container's original shape (preserving row_stride). | ||
| 276 | + // The valid_shape argument is consumed by codegen to auto-emit SetValidShape. | ||
| 277 | + CHECK(args.size() == 3) << "block.subview requires exactly 3 arguments (container, offset, valid_shape), but got " | ||
| 278 | + << args.size(); | ||
| 279 | + | ||
| 280 | + auto container_type = args[0]->GetType(); | ||
| 281 | + | ||
| 282 | + if (auto tile_type = As<TileType>(container_type)) { | ||
| 283 | + return std::make_shared<TileType>(tile_type->shape_, tile_type->dtype_, tile_type->memref_); | ||
| 284 | + } | ||
| 285 | + | ||
| 286 | + CHECK(false) << "block.subview requires first argument to be TileType, but got " << container_type->TypeName(); | ||
| 287 | + return nullptr; | ||
| 288 | +} | ||
| 289 | + | ||
| 290 | +REGISTER_OP("block.subview") | ||
| 291 | + .set_op_category("BlockOp") | ||
| 292 | + .set_description("Create a sub-view of a tile with offset and valid_shape") | ||
| 293 | + .add_argument("container", "Input tile (TileType)") | ||
| 294 | + .add_argument("offset", "Linear element offset (ScalarType with integer dtype)") | ||
| 295 | + .add_argument("valid_shape", "Sub-window dimensions (MakeTuple)") | ||
| 296 | + .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | ||
| 297 | + [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | ||
| 298 | + return DeduceSubViewType(args, kwargs); | ||
| 299 | + }); | ||
| 300 | + | ||
| 266 | } // namespace ir | 301 | } // namespace ir |
| 267 | } // namespace pypto | 302 | } // namespace pypto |
| @@ -452,7 +452,7 @@ REGISTER_OP("block.cmp") | |||
| 452 | .add_argument("out", "Pre-allocated output tile (TileType)") | 452 | .add_argument("out", "Pre-allocated output tile (TileType)") |
| 453 | .add_argument("lhs", "Left tile (TileType)") | 453 | .add_argument("lhs", "Left tile (TileType)") |
| 454 | .add_argument("rhs", "Right tile (TileType)") | 454 | .add_argument("rhs", "Right tile (TileType)") |
| 455 | - .set_attr<int>("cmp_type") | 455 | + .set_attr<int>("cmp_mode") |
| 456 | .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | 456 | .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, |
| 457 | [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | 457 | [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { |
| 458 | return DeduceBlockOutBinaryTile(args, kwargs, "block.cmp"); | 458 | return DeduceBlockOutBinaryTile(args, kwargs, "block.cmp"); |
| @@ -464,7 +464,7 @@ REGISTER_OP("block.cmps") | |||
| 464 | .add_argument("out", "Pre-allocated output tile (TileType)") | 464 | .add_argument("out", "Pre-allocated output tile (TileType)") |
| 465 | .add_argument("tile", "Input tile (TileType)") | 465 | .add_argument("tile", "Input tile (TileType)") |
| 466 | .add_argument("scalar", "Scalar comparand (ScalarType)") | 466 | .add_argument("scalar", "Scalar comparand (ScalarType)") |
| 467 | - .set_attr<int>("cmp_type") | 467 | + .set_attr<int>("cmp_mode") |
| 468 | .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, | 468 | .f_deduce_type([]([[maybe_unused]] const std::vector<ExprPtr>& args, |
| 469 | [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { | 469 | [[maybe_unused]] const std::vector<std::pair<std::string, std::any>>& kwargs) { |
| 470 | return DeduceBlockOutBinaryScalar(args, kwargs, "block.cmps"); | 470 | return DeduceBlockOutBinaryScalar(args, kwargs, "block.cmps"); |
| @@ -110,7 +110,7 @@ REGISTER_OP("vf.full") | |||
| 110 | // Data transfer | 110 | // Data transfer |
| 111 | REGISTER_OP("vf.load_align") | 111 | REGISTER_OP("vf.load_align") |
| 112 | .set_op_category("VFOp") | 112 | .set_op_category("VFOp") |
| 113 | - .set_description("Unified vlds load (dist/post_update via kwargs)") | 113 | + .set_description("Unified vlds/plds load (MaskReg dst via dist kwarg, RegTensor dst via dist kwarg)") |
| 114 | .add_argument("dst", "Destination register") | 114 | .add_argument("dst", "Destination register") |
| 115 | .add_argument("src", "Source UB pointer") | 115 | .add_argument("src", "Source UB pointer") |
| 116 | .add_argument("offset", "Element offset or post-update stride") | 116 | .add_argument("offset", "Element offset or post-update stride") |
| @@ -123,7 +123,8 @@ REGISTER_OP("vf.load_align") | |||
| 123 | 123 | ||
| 124 | REGISTER_OP("vf.store_align") | 124 | REGISTER_OP("vf.store_align") |
| 125 | .set_op_category("VFOp") | 125 | .set_op_category("VFOp") |
| 126 | - .set_description("Store aligned data from register to UB") | 126 | + .set_description( |
| 127 | + "Store aligned data from register to UB (MaskReg src via dist kwarg → psts/pst, RegTensor src → vsts/vst)") | ||
| 127 | .add_argument("dst", "Destination UB pointer") | 128 | .add_argument("dst", "Destination UB pointer") |
| 128 | .add_argument("src", "Source register") | 129 | .add_argument("src", "Source register") |
| 129 | .add_argument("mask", "Mask register") | 130 | .add_argument("mask", "Mask register") |
| @@ -400,11 +401,12 @@ REGISTER_OP("vf.leaky_relu") | |||
| 400 | 401 | ||
| 401 | REGISTER_OP("vf.interleave") | 402 | REGISTER_OP("vf.interleave") |
| 402 | .set_op_category("VFOp") | 403 | .set_op_category("VFOp") |
| 403 | - .set_description("Interleave two registers") | 404 | + .set_description("Interleave two registers (vintlv for RegTensor, pintlv for MaskReg)") |
| 404 | .add_argument("dst0", "Destination register 0") | 405 | .add_argument("dst0", "Destination register 0") |
| 405 | .add_argument("dst1", "Destination register 1") | 406 | .add_argument("dst1", "Destination register 1") |
| 406 | .add_argument("src0", "Source register 0") | 407 | .add_argument("src0", "Source register 0") |
| 407 | .add_argument("src1", "Source register 1") | 408 | .add_argument("src1", "Source register 1") |
| 409 | + .set_attr<DataType>("dtype") | ||
| 408 | .f_deduce_type(DeduceVFFromDstArg); | 410 | .f_deduce_type(DeduceVFFromDstArg); |
| 409 | 411 | ||
| 410 | REGISTER_OP("vf.pair_reduce_sum") | 412 | REGISTER_OP("vf.pair_reduce_sum") |
| @@ -457,7 +459,7 @@ REGISTER_OP("vf.mul_dst_add") | |||
| 457 | 459 | ||
| 458 | REGISTER_OP("vf.pack") | 460 | REGISTER_OP("vf.pack") |
| 459 | .set_op_category("VFOp") | 461 | .set_op_category("VFOp") |
| 460 | - .set_description("Pack/narrow data type (e.g. u16->u8)") | 462 | + .set_description("Pack/narrow data type (e.g. u16->u8). vpack for RegTensor, ppack for MaskReg.") |
| 461 | .add_argument("dst", "Destination register") | 463 | .add_argument("dst", "Destination register") |
| 462 | .add_argument("src", "Source register") | 464 | .add_argument("src", "Source register") |
| 463 | .set_attr<int>("part") | 465 | .set_attr<int>("part") |
| @@ -465,7 +467,7 @@ REGISTER_OP("vf.pack") | |||
| 465 | 467 | ||
| 466 | REGISTER_OP("vf.unpack") | 468 | REGISTER_OP("vf.unpack") |
| 467 | .set_op_category("VFOp") | 469 | .set_op_category("VFOp") |
| 468 | - .set_description("Unpack/widen data type (e.g. u8->u16)") | 470 | + .set_description("Unpack/widen data type (e.g. u8->u16). vunpack for RegTensor, punpack for MaskReg.") |
| 469 | .add_argument("dst", "Destination register") | 471 | .add_argument("dst", "Destination register") |
| 470 | .add_argument("src", "Source register") | 472 | .add_argument("src", "Source register") |
| 471 | .set_attr<int>("part") | 473 | .set_attr<int>("part") |
| @@ -559,11 +561,12 @@ REGISTER_OP("vf.astype") | |||
| 559 | 561 | ||
| 560 | REGISTER_OP("vf.de_interleave") | 562 | REGISTER_OP("vf.de_interleave") |
| 561 | .set_op_category("VFOp") | 563 | .set_op_category("VFOp") |
| 562 | - .set_description("De-interleave") | 564 | + .set_description("De-interleave (vdintlv for RegTensor, pdintlv for MaskReg)") |
| 563 | .add_argument("dst0", "Destination register 0") | 565 | .add_argument("dst0", "Destination register 0") |
| 564 | .add_argument("dst1", "Destination register 1") | 566 | .add_argument("dst1", "Destination register 1") |
| 565 | .add_argument("src0", "Source register 0") | 567 | .add_argument("src0", "Source register 0") |
| 566 | .add_argument("src1", "Source register 1") | 568 | .add_argument("src1", "Source register 1") |
| 569 | + .set_attr<DataType>("dtype") | ||
| 567 | .f_deduce_type(DeduceVFFromDstArg); | 570 | .f_deduce_type(DeduceVFFromDstArg); |
| 568 | 571 | ||
| 569 | REGISTER_OP("vf.select") | 572 | REGISTER_OP("vf.select") |
| @@ -808,117 +811,14 @@ REGISTER_OP("vf.muls_cast") | |||
| 808 | .set_attr<int>("layout") | 811 | .set_attr<int>("layout") |
| 809 | .f_deduce_type(DeduceVFFromDstArg); | 812 | .f_deduce_type(DeduceVFFromDstArg); |
| 810 | 813 | ||
| 811 | -REGISTER_OP("vf.mask_and") | 814 | +// mask_and/or/xor/not/mov/sel/pack/unpack/interleave/deinterleave have been |
| 812 | - .set_op_category("VFOp") | 815 | +// merged into their unified counterparts (and_, or_, ..., move, select, |
| 813 | - .set_description("Mask register bitwise AND") | 816 | +// pack, unpack, interleave, de_interleave). The Python parser redirects |
| 814 | - .add_argument("dst", "Destination mask register") | 817 | +// vf.mask_* calls to the unified IR op via _VF_OP_NAME_MAP. |
| 815 | - .add_argument("src0", "Source mask register 0") | ||
| 816 | - .add_argument("src1", "Source mask register 1") | ||
| 817 | - .add_argument("mask", "Predicate mask register") | ||
| 818 | - .f_deduce_type(DeduceVFUnknownType); | ||
| 819 | 818 | ||
| 820 | -REGISTER_OP("vf.mask_or") | 819 | +// vf.mask_load/mask_store/mask_store_unalign IR registrations removed — |
| 821 | - .set_op_category("VFOp") | 820 | +// the parser redirects these to vf.load_align/vf.store_align/vf.store_unalign |
| 822 | - .set_description("Mask register bitwise OR") | 821 | +// which dispatch via IsMaskRegVar (matching AscendC's function-overloading model). |
| 823 | - .add_argument("dst", "Destination mask register") | ||
| 824 | - .add_argument("src0", "Source mask register 0") | ||
| 825 | - .add_argument("src1", "Source mask register 1") | ||
| 826 | - .add_argument("mask", "Predicate mask register") | ||
| 827 | - .f_deduce_type(DeduceVFUnknownType); | ||
| 828 | - | ||
| 829 | -REGISTER_OP("vf.mask_xor") | ||
| 830 | - .set_op_category("VFOp") | ||
| 831 | - .set_description("Mask register bitwise XOR") | ||
| 832 | - .add_argument("dst", "Destination mask register") | ||
| 833 | - .add_argument("src0", "Source mask register 0") | ||
| 834 | - .add_argument("src1", "Source mask register 1") | ||
| 835 | - .add_argument("mask", "Predicate mask register") | ||
| 836 | - .f_deduce_type(DeduceVFUnknownType); | ||
| 837 | - | ||
| 838 | -REGISTER_OP("vf.mask_not") | ||
| 839 | - .set_op_category("VFOp") | ||
| 840 | - .set_description("Mask register bitwise NOT") | ||
| 841 | - .add_argument("dst", "Destination mask register") | ||
| 842 | - .add_argument("src", "Source mask register") | ||
| 843 | - .add_argument("mask", "Predicate mask register") | ||
| 844 | - .f_deduce_type(DeduceVFUnknownType); | ||
| 845 | - | ||
| 846 | -REGISTER_OP("vf.mask_mov") | ||
| 847 | - .set_op_category("VFOp") | ||
| 848 | - .set_description("Mask register move") | ||
| 849 | - .add_argument("dst", "Destination mask register") | ||
| 850 | - .add_argument("src", "Source mask register") | ||
| 851 | - .add_argument("mask", "Predicate mask register") | ||
| 852 | - .f_deduce_type(DeduceVFUnknownType); | ||
| 853 | - | ||
| 854 | -REGISTER_OP("vf.mask_sel") | ||
| 855 | - .set_op_category("VFOp") | ||
| 856 | - .set_description("Mask register select") | ||
| 857 | - .add_argument("dst", "Destination mask register") | ||
| 858 | - .add_argument("src0", "Source mask register 0") | ||
| 859 | - .add_argument("src1", "Source mask register 1") | ||
| 860 | - .add_argument("mask", "Selector mask register") | ||
| 861 | - .f_deduce_type(DeduceVFUnknownType); | ||
| 862 | - | ||
| 863 | -REGISTER_OP("vf.mask_pack") | ||
| 864 | - .set_op_category("VFOp") | ||
| 865 | - .set_description("Mask pack (ppack)") | ||
| 866 | - .add_argument("dst", "Destination mask register") | ||
| 867 | - .add_argument("src", "Source mask register") | ||
| 868 | - .set_attr<int>("half") | ||
| 869 | - .f_deduce_type(DeduceVFUnknownType); | ||
| 870 | - | ||
| 871 | -REGISTER_OP("vf.mask_unpack") | ||
| 872 | - .set_op_category("VFOp") | ||
| 873 | - .set_description("Mask unpack (punpack)") | ||
| 874 | - .add_argument("dst", "Destination mask register") | ||
| 875 | - .add_argument("src", "Source mask register") | ||
| 876 | - .set_attr<int>("half") | ||
| 877 | - .f_deduce_type(DeduceVFUnknownType); | ||
| 878 | - | ||
| 879 | -REGISTER_OP("vf.mask_interleave") | ||
| 880 | - .set_op_category("VFOp") | ||
| 881 | - .set_description("Mask interleave (pintlv_b8/b16/b32)") | ||
| 882 | - .add_argument("dst0", "Destination mask register 0") | ||
| 883 | - .add_argument("dst1", "Destination mask register 1") | ||
| 884 | - .add_argument("src0", "Source mask register 0") | ||
| 885 | - .add_argument("src1", "Source mask register 1") | ||
| 886 | - .set_attr<DataType>("dtype") | ||
| 887 | - .f_deduce_type(DeduceVFUnknownType); | ||
| 888 | - | ||
| 889 | -REGISTER_OP("vf.mask_deinterleave") | ||
| 890 | - .set_op_category("VFOp") | ||
| 891 | - .set_description("Mask de-interleave (pdintlv_b8/b16/b32)") | ||
| 892 | - .add_argument("dst0", "Destination mask register 0") | ||
| 893 | - .add_argument("dst1", "Destination mask register 1") | ||
| 894 | - .add_argument("src0", "Source mask register 0") | ||
| 895 | - .add_argument("src1", "Source mask register 1") | ||
| 896 | - .set_attr<DataType>("dtype") | ||
| 897 | - .f_deduce_type(DeduceVFUnknownType); | ||
| 898 | - | ||
| 899 | -REGISTER_OP("vf.mask_load") | ||
| 900 | - .set_op_category("VFOp") | ||
| 901 | - .set_description("Mask load (plds, or pld when an AddrReg offset is given) — returns MaskReg") | ||
| 902 | - .add_argument("src_ptr", "Source UB pointer") | ||
| 903 | - .add_argument("offset", "Optional AddrReg offset (routes to pld)") | ||
| 904 | - .f_deduce_type(DeduceVFMaskType); | ||
| 905 | - | ||
| 906 | -REGISTER_OP("vf.mask_store") | ||
| 907 | - .set_op_category("VFOp") | ||
| 908 | - .set_description("Mask store (psts, or pst when an AddrReg offset is given)") | ||
| 909 | - .add_argument("src", "Source mask register") | ||
| 910 | - .add_argument("dst_ptr", "Destination UB pointer") | ||
| 911 | - .add_argument("mask", "Mask register") | ||
| 912 | - .add_argument("offset", "Optional AddrReg offset (routes to pst)") | ||
| 913 | - .f_deduce_type(DeduceVFUnknownType); | ||
| 914 | - | ||
| 915 | -REGISTER_OP("vf.mask_store_unalign") | ||
| 916 | - .set_op_category("VFOp") | ||
| 917 | - .set_description("Mask store unaligned (pstu)") | ||
| 918 | - .add_argument("src", "Source mask register") | ||
| 919 | - .add_argument("dst_ptr", "Destination UB pointer") | ||
| 920 | - .add_argument("mask", "Mask register") | ||
| 921 | - .f_deduce_type(DeduceVFUnknownType); | ||
| 922 | 822 | ||
| 923 | REGISTER_OP("vf.load") | 823 | REGISTER_OP("vf.load") |
| 924 | .set_op_category("VFOp") | 824 | .set_op_category("VFOp") |
| @@ -959,7 +859,8 @@ REGISTER_OP("vf.move") | |||
| 959 | .set_op_category("VFOp") | 859 | .set_op_category("VFOp") |
| 960 | .set_description("Move/copy register elements (RegTensor or MaskReg). " | 860 | .set_description("Move/copy register elements (RegTensor or MaskReg). " |
| 961 | "RegTensor: vmov with MODE_MERGING (masked) or vmov (unmasked). " | 861 | "RegTensor: vmov with MODE_MERGING (masked) or vmov (unmasked). " |
| 962 | - "MaskReg: pmov (masked) or pmov (unmasked).") | 862 | + "MaskReg: pmov (masked) or pmov (unmasked). " |
| 863 | + "Unified op: dst register kind is inferred from source operands.") | ||
| 963 | .add_argument("dst", "Destination register (RegTensor or MaskReg)") | 864 | .add_argument("dst", "Destination register (RegTensor or MaskReg)") |
| 964 | .add_argument("src", "Source register") | 865 | .add_argument("src", "Source register") |
| 965 | .add_argument("mask", "Mask register (optional)") | 866 | .add_argument("mask", "Mask register (optional)") |
| @@ -148,6 +148,17 @@ public: | |||
| 148 | } | 148 | } |
| 149 | 149 | ||
| 150 | protected: | 150 | protected: |
| 151 | + ExprPtr VisitExpr_(const MakeTuplePtr& op) override | ||
| 152 | + { | ||
| 153 | + auto it = transformed_make_tuple_cache_.find(op.get()); | ||
| 154 | + if (it != transformed_make_tuple_cache_.end()) { | ||
| 155 | + return it->second; | ||
| 156 | + } | ||
| 157 | + auto transformed = IRMutator::VisitExpr_(op); | ||
| 158 | + transformed_make_tuple_cache_.emplace(op.get(), transformed); | ||
| 159 | + return transformed; | ||
| 160 | + } | ||
| 161 | + | ||
| 151 | // Override expression visitation to replace Var with current version | 162 | // Override expression visitation to replace Var with current version |
| 152 | ExprPtr VisitExpr_(const VarPtr& op) override | 163 | ExprPtr VisitExpr_(const VarPtr& op) override |
| 153 | { | 164 | { |
| @@ -388,6 +399,7 @@ protected: | |||
| 388 | } | 399 | } |
| 389 | 400 | ||
| 390 | private: | 401 | private: |
| 402 | + std::unordered_map<const MakeTuple*, ExprPtr> transformed_make_tuple_cache_; | ||
| 391 | // Version counter per base variable name | 403 | // Version counter per base variable name |
| 392 | std::unordered_map<std::string, int> version_counter_; | 404 | std::unordered_map<std::string, int> version_counter_; |
| 393 | 405 | ||
| @@ -566,7 +566,15 @@ static std::string MakeBlockOutMoveCodegenCCE(const ir::CallPtr& op, codegen::Co | |||
| 566 | // Build template params (shared by both TEXTRACT and TMOV paths) | 566 | // Build template params (shared by both TEXTRACT and TMOV paths) |
| 567 | std::string template_params = ""; | 567 | std::string template_params = ""; |
| 568 | if (op->HasKwarg("acc_to_vec_mode")) { | 568 | if (op->HasKwarg("acc_to_vec_mode")) { |
| 569 | - template_params = ", " + GetAccToVecModeCCE(op->GetKwarg<int>("acc_to_vec_mode"), true); | 569 | + int mode_val = op->GetKwarg<int>("acc_to_vec_mode"); |
| 570 | + template_params = ", " + GetAccToVecModeCCE(mode_val, true); | ||
| 571 | + // Auto-align Acc valid_shape for DualModeSplitM (M%2==0) / DualModeSplitN (N%32==0). | ||
| 572 | + if (mode_val == 1) { | ||
| 573 | + codegen.Emit(src + ".SetValidShape((" + src + ".GetValidRow() + 1) / 2 * 2, " + src + ".GetValidCol());"); | ||
| 574 | + } else if (mode_val == 2) { | ||
| 575 | + codegen.Emit(src + ".SetValidShape(" + src + ".GetValidRow(), (" + src + | ||
| 576 | + ".GetValidCol() + 31) / 32 * 32);"); | ||
| 577 | + } | ||
| 570 | } | 578 | } |
| 571 | if (op->HasKwarg("relu_pre_mode")) { | 579 | if (op->HasKwarg("relu_pre_mode")) { |
| 572 | template_params += ", " + GetReluPreModeCCE(op->GetKwarg<int>("relu_pre_mode")); | 580 | template_params += ", " + GetReluPreModeCCE(op->GetKwarg<int>("relu_pre_mode")); |
| @@ -977,7 +985,7 @@ static std::string MakeBlockOutTransposeCodegenCCE(const ir::CallPtr& op, codege | |||
| 977 | return ""; | 985 | return ""; |
| 978 | } | 986 | } |
| 979 | 987 | ||
| 980 | -// block.cmp - args = [dst, lhs, rhs] + cmp_type kwarg | 988 | +// block.cmp - args = [dst, lhs, rhs] + cmp_mode kwarg |
| 981 | static std::string MakeBlockOutCmpCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base) | 989 | static std::string MakeBlockOutCmpCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base) |
| 982 | { | 990 | { |
| 983 | auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base); | 991 | auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base); |
| @@ -985,12 +993,13 @@ static std::string MakeBlockOutCmpCodegenCCE(const ir::CallPtr& op, codegen::Cod | |||
| 985 | std::string dst = codegen.GetExprAsCode(op->args_[0]); | 993 | std::string dst = codegen.GetExprAsCode(op->args_[0]); |
| 986 | std::string lhs = codegen.GetExprAsCode(op->args_[1]); | 994 | std::string lhs = codegen.GetExprAsCode(op->args_[1]); |
| 987 | std::string rhs = codegen.GetExprAsCode(op->args_[2]); | 995 | std::string rhs = codegen.GetExprAsCode(op->args_[2]); |
| 988 | - int cmp_type = op->GetKwarg<int>("cmp_type"); | 996 | + int cmp_mode = op->GetKwarg<int>("cmp_mode"); |
| 989 | - codegen.Emit("TCMP(" + dst + ", " + lhs + ", " + rhs + ", " + cce::GetCmpModeEnum(cmp_type) + ");"); | 997 | + codegen.Emit("TCMP(" + dst + ", " + lhs + ", " + rhs + ", " + ir::EnumToString(static_cast<ir::CmpMode>(cmp_mode)) + |
| 998 | + ");"); | ||
| 990 | return ""; | 999 | return ""; |
| 991 | } | 1000 | } |
| 992 | 1001 | ||
| 993 | -// block.cmps - args = [dst, tile, scalar] + cmp_type kwarg | 1002 | +// block.cmps - args = [dst, tile, scalar] + cmp_mode kwarg |
| 994 | static std::string MakeBlockOutCmpsCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base) | 1003 | static std::string MakeBlockOutCmpsCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base) |
| 995 | { | 1004 | { |
| 996 | auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base); | 1005 | auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base); |
| @@ -998,8 +1007,9 @@ static std::string MakeBlockOutCmpsCodegenCCE(const ir::CallPtr& op, codegen::Co | |||
| 998 | std::string dst = codegen.GetExprAsCode(op->args_[0]); | 1007 | std::string dst = codegen.GetExprAsCode(op->args_[0]); |
| 999 | std::string tile = codegen.GetExprAsCode(op->args_[1]); | 1008 | std::string tile = codegen.GetExprAsCode(op->args_[1]); |
| 1000 | std::string scalar = codegen.GetExprAsCode(op->args_[2]); | 1009 | std::string scalar = codegen.GetExprAsCode(op->args_[2]); |
| 1001 | - int cmp_type = op->GetKwarg<int>("cmp_type"); | 1010 | + int cmp_mode = op->GetKwarg<int>("cmp_mode"); |
| 1002 | - codegen.Emit("TCMPS(" + dst + ", " + tile + ", " + scalar + ", " + cce::GetCmpModeEnum(cmp_type) + ");"); | 1011 | + codegen.Emit("TCMPS(" + dst + ", " + tile + ", " + scalar + ", " + |
| 1012 | + ir::EnumToString(static_cast<ir::CmpMode>(cmp_mode)) + ");"); | ||
| 1003 | return ""; | 1013 | return ""; |
| 1004 | } | 1014 | } |
| 1005 | 1015 | ||
| @@ -1259,7 +1269,8 @@ static std::string MakeBlockOutGatherCodegenCCE(const ir::CallPtr& op, codegen:: | |||
| 1259 | 1269 | ||
| 1260 | // ============================================================================ | 1270 | // ============================================================================ |
| 1261 | // block.gathermask - args = [out, src] + kwargs(pattern_mode) | 1271 | // block.gathermask - args = [out, src] + kwargs(pattern_mode) |
| 1262 | -// Emits: TGATHER<decltype(out), decltype(src), MaskPattern::Pxxxx>(out, src) | 1272 | +// Emits: TGATHER<remove_reference_t<decltype(out)>, remove_reference_t<decltype(src)>, |
| 1273 | +// MaskPattern::Pxxxx>(out, src) | ||
| 1263 | // ============================================================================ | 1274 | // ============================================================================ |
| 1264 | static std::string MakeBlockOutGatherMaskCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base) | 1275 | static std::string MakeBlockOutGatherMaskCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base) |
| 1265 | { | 1276 | { |
| @@ -1286,8 +1297,8 @@ static std::string MakeBlockOutGatherMaskCodegenCCE(const ir::CallPtr& op, codeg | |||
| 1286 | std::string out = codegen.GetExprAsCode(op->args_[0]); | 1297 | std::string out = codegen.GetExprAsCode(op->args_[0]); |
| 1287 | std::string src = codegen.GetExprAsCode(op->args_[1]); | 1298 | std::string src = codegen.GetExprAsCode(op->args_[1]); |
| 1288 | 1299 | ||
| 1289 | - codegen.Emit("TGATHER<decltype(" + out + "), decltype(" + src + "), " + std::string(pattern_names[pattern_mode]) + | 1300 | + codegen.Emit("TGATHER<std::remove_reference_t<decltype(" + out + ")>, std::remove_reference_t<decltype(" + src + |
| 1290 | - ">(" + out + ", " + src + ");"); | 1301 | + ")>, " + std::string(pattern_names[pattern_mode]) + ">(" + out + ", " + src + ");"); |
| 1291 | return ""; | 1302 | return ""; |
| 1292 | } | 1303 | } |
| 1293 | 1304 | ||
| @@ -2202,27 +2213,29 @@ static std::string MakeBlockOutMrgsort2CCE(const ir::CallPtr& op, codegen::Codeg | |||
| 2202 | std::string src1 = codegen.GetExprAsCode(op->args_[3]); | 2213 | std::string src1 = codegen.GetExprAsCode(op->args_[3]); |
| 2203 | 2214 | ||
| 2204 | // TMRGSORT requires exhausted as a non-deducible bool template parameter. | 2215 | // TMRGSORT requires exhausted as a non-deducible bool template parameter. |
| 2205 | - // Use TMRGSORT_IMPL with decltype() to avoid spelling out all tile types explicitly. | 2216 | + // Tile-group accessors lower to array subscripts, whose decltype is Tile&; strip |
| 2217 | + // the reference before passing the types to TMRGSORT_IMPL. | ||
| 2218 | + auto tile_type = [](const std::string& expr) { return "std::remove_reference_t<decltype(" + expr + ")>"; }; | ||
| 2206 | auto emit_tmrgsort = [&](const std::string& srcs_decl, const std::string& srcs_args) { | 2219 | auto emit_tmrgsort = [&](const std::string& srcs_decl, const std::string& srcs_args) { |
| 2207 | std::ostringstream oss; | 2220 | std::ostringstream oss; |
| 2208 | oss << "MrgSortExecutedNumList executedNumList;"; | 2221 | oss << "MrgSortExecutedNumList executedNumList;"; |
| 2209 | codegen.Emit(oss.str()); | 2222 | codegen.Emit(oss.str()); |
| 2210 | oss.str(""); | 2223 | oss.str(""); |
| 2211 | - oss << "TMRGSORT_IMPL<decltype(" << dst << "), decltype(" << tmp << "), " << srcs_decl << ", " << exhausted_str | 2224 | + oss << "TMRGSORT_IMPL<" << tile_type(dst) << ", " << tile_type(tmp) << ", " << srcs_decl << ", " |
| 2212 | - << ">(" << dst << ", executedNumList, " << tmp << ", " << srcs_args << ");"; | 2225 | + << exhausted_str << ">(" << dst << ", executedNumList, " << tmp << ", " << srcs_args << ");"; |
| 2213 | codegen.Emit(oss.str()); | 2226 | codegen.Emit(oss.str()); |
| 2214 | }; | 2227 | }; |
| 2215 | 2228 | ||
| 2216 | if (num_args == 4) { | 2229 | if (num_args == 4) { |
| 2217 | - emit_tmrgsort("decltype(" + src0 + "), decltype(" + src1 + ")", src0 + ", " + src1); | 2230 | + emit_tmrgsort(tile_type(src0) + ", " + tile_type(src1), src0 + ", " + src1); |
| 2218 | } else if (num_args == 5) { | 2231 | } else if (num_args == 5) { |
| 2219 | std::string src2 = codegen.GetExprAsCode(op->args_[4]); | 2232 | std::string src2 = codegen.GetExprAsCode(op->args_[4]); |
| 2220 | - emit_tmrgsort("decltype(" + src0 + "), decltype(" + src1 + "), decltype(" + src2 + ")", | 2233 | + emit_tmrgsort(tile_type(src0) + ", " + tile_type(src1) + ", " + tile_type(src2), |
| 2221 | src0 + ", " + src1 + ", " + src2); | 2234 | src0 + ", " + src1 + ", " + src2); |
| 2222 | } else { | 2235 | } else { |
| 2223 | std::string src2 = codegen.GetExprAsCode(op->args_[4]); | 2236 | std::string src2 = codegen.GetExprAsCode(op->args_[4]); |
| 2224 | std::string src3 = codegen.GetExprAsCode(op->args_[5]); | 2237 | std::string src3 = codegen.GetExprAsCode(op->args_[5]); |
| 2225 | - emit_tmrgsort("decltype(" + src0 + "), decltype(" + src1 + "), decltype(" + src2 + "), decltype(" + src3 + ")", | 2238 | + emit_tmrgsort(tile_type(src0) + ", " + tile_type(src1) + ", " + tile_type(src2) + ", " + tile_type(src3), |
| 2226 | src0 + ", " + src1 + ", " + src2 + ", " + src3); | 2239 | src0 + ", " + src1 + ", " + src2 + ", " + src3); |
| 2227 | } | 2240 | } |
| 2228 | return ""; | 2241 | return ""; |
| @@ -922,8 +922,9 @@ static std::string MakeDebugDumpTileCodegenCCE(const ir::CallPtr& op, codegen::C | |||||||||
| 922 | std::to_string(tile_cols->value_) + ";"); | 922 | std::to_string(tile_cols->value_) + ";"); | ||||||
| 923 | codegen.Emit("cce::printf(\"=== [TPRINT Tile Window] Data Type: %s, Layout: %s, TileType: %s ===\\n\", " | 923 | codegen.Emit("cce::printf(\"=== [TPRINT Tile Window] Data Type: %s, Layout: %s, TileType: %s ===\\n\", " | ||||||
| 924 | "pto::GetDTypeName<" + | 924 | "pto::GetDTypeName<" + | ||||||
| 925 | - codegen.GetTypeString(tile_type->dtype_) + ">(), pto::GetLayoutName(decltype(" + src + | 925 | + codegen.GetTypeString(tile_type->dtype_) + | ||||||
| 926 | - ")::BFractal, decltype(" + src + ")::SFractal), \"Vec\");"); | 926 | + ">(), pto::GetLayoutName(std::remove_reference_t<decltype(" + src + | ||||||
| 927 | + ")>::BFractal, std::remove_reference_t<decltype(" + src + ")>::SFractal), \"Vec\");"); | ||||||||
| 927 | codegen.Emit("cce::printf(\" Source Shape: [%d, %d], Window Offsets: [%d, %d], Requested Shape: [%d, %d], " | 928 | codegen.Emit("cce::printf(\" Source Shape: [%d, %d], Window Offsets: [%d, %d], Requested Shape: [%d, %d], " | ||||||
| 928 | "Valid Shape: [%d, %d]\\n\", " + | 929 | "Valid Shape: [%d, %d]\\n\", " + | ||||||
| 929 | std::to_string(tile_rows->value_) + ", " + std::to_string(tile_cols->value_) + ", static_cast<int>(" + | 930 | std::to_string(tile_rows->value_) + ", " + std::to_string(tile_cols->value_) + ", static_cast<int>(" + | ||||||
| @@ -931,8 +932,8 @@ static std::string MakeDebugDumpTileCodegenCCE(const ir::CallPtr& op, codegen::C | |||||||||
| 931 | valid_row + ", " + valid_col + ");"); | 932 | valid_row + ", " + valid_col + ");"); | ||||||
| 932 | codegen.Emit("for (int " + row_idx + " = 0; " + row_idx + " < " + valid_row + "; ++" + row_idx + ") {"); | 933 | codegen.Emit("for (int " + row_idx + " = 0; " + row_idx + " < " + valid_row + "; ++" + row_idx + ") {"); | ||||||
| 933 | codegen.Emit(" for (int " + col_idx + " = 0; " + col_idx + " < " + valid_col + "; ++" + col_idx + ") {"); | 934 | codegen.Emit(" for (int " + col_idx + " = 0; " + col_idx + " < " + valid_col + "; ++" + col_idx + ") {"); | ||||||
| 934 | - codegen.Emit(" auto __debug_src_offset = pto::GetTileOffset<decltype(" + src + ")>(" + row_idx + " + (" + | 935 | + codegen.Emit(" auto __debug_src_offset = pto::GetTileOffset<std::remove_reference_t<decltype(" + src + ")>>(" + | ||||||
| 935 | - row_off + "), " + col_idx + " + (" + col_off + "));"); | 936 | + row_idx + " + (" + row_off + "), " + col_idx + " + (" + col_off + "));"); | ||||||
| 936 | codegen.Emit(" auto " + debug_val + " = " + src + ".data()[__debug_src_offset];"); | 937 | codegen.Emit(" auto " + debug_val + " = " + src + ".data()[__debug_src_offset];"); | ||||||
| 937 | codegen.Emit(" pto::PrintValue<pto::PrintFormat::Width8_Precision4>(" + debug_val + ", " + col_idx + ");"); | 938 | codegen.Emit(" pto::PrintValue<pto::PrintFormat::Width8_Precision4>(" + debug_val + ", " + col_idx + ");"); | ||||||
| 938 | codegen.Emit(" }"); | 939 | codegen.Emit(" }"); | ||||||
| @@ -1673,6 +1674,89 @@ REGISTER_BACKEND_OP(BackendCCE, "block.setval") | |||||||||
| 1673 | .set_pipe(ir::PipeType::S) | 1674 | .set_pipe(ir::PipeType::S) | ||||||
| 1674 | .f_codegen([](const ir::CallPtr& op, codegen::CodegenBase& codegen) { return MakeSetValCodegenCCE(op, codegen); }); | 1675 | .f_codegen([](const ir::CallPtr& op, codegen::CodegenBase& codegen) { return MakeSetValCodegenCCE(op, codegen); }); | ||||||
| 1675 | 1676 | ||||||||
| 1677 | +// ============================================================================ | ||||||||
| 1678 | +// block.subview - tile/tensor sub-view with offset and new shape. | ||||||||
| 1679 | +// | ||||||||
| 1680 | +// Tile in VF section: returns pointer arithmetic expression. | ||||||||
| 1681 | +// Tile in non-VF section: emits TASSIGN with new shape, returns the new tile | ||||||||
| 1682 | +// variable name. | ||||||||
| 1683 | +// ============================================================================ | ||||||||
| 1684 | +static std::string MakeBlockSubviewCodegenCCE(const ir::CallPtr& op, codegen::CodegenBase& codegen_base) | ||||||||
| 1685 | +{ | ||||||||
| 1686 | + auto& codegen = dynamic_cast<codegen::CCECodegen&>(codegen_base); | ||||||||
| 1687 | + | ||||||||
| 1688 | + std::string offset = codegen.GetExprAsCode(op->args_[1]); | ||||||||
| 1689 | + | ||||||||
| 1690 | + // VF section: pointer arithmetic, no tile descriptor needed. | ||||||||
| 1691 | + if (codegen.IsInVFSection()) { | ||||||||
| 1692 | + std::string base_ptr = codegen.GetOrCreateVFTilePtr(op->args_[0], /*is_post_update=*/false); | ||||||||
| 1693 | + return "(" + base_ptr + " + (" + offset + "))"; | ||||||||
| 1694 | + } | ||||||||
| 1695 | + | ||||||||
| 1696 | + std::string base_tile = codegen.GetExprAsCode(op->args_[0]); | ||||||||
| 1697 | + auto tile_type = ir::As<ir::TileType>(op->args_[0]->GetType()); | ||||||||
| 1698 | + int elem_bytes = std::max(1, static_cast<int>(tile_type->dtype_.GetBit() / 8)); | ||||||||
| 1699 | + | ||||||||
| 1700 | + // Resolve base address: tile_addresses_ → .data() → memref addr | ||||||||
| 1701 | + std::string base_addr; | ||||||||
| 1702 | + if (codegen.HasTileAddress(base_tile)) { | ||||||||
| 1703 | + base_addr = codegen.GetTileAddress(base_tile); | ||||||||
| 1704 | + } else if (base_tile.find('[') != std::string::npos) { | ||||||||
| 1705 | + base_addr = "(uint64_t)" + base_tile + ".data()"; | ||||||||
| 1706 | + } else { | ||||||||
| 1707 | + INTERNAL_CHECK(tile_type->memref_.has_value()) | ||||||||
| 1708 | + << "block.subview: base tile '" << base_tile << "' has no address info"; | ||||||||
| 1709 | + int64_t addr_val = codegen.GetConstIntValue((*tile_type->memref_)->addr_); | ||||||||
| 1710 | + std::ostringstream oss; | ||||||||
| 1711 | + oss << "0x" << std::hex << addr_val; | ||||||||
| 1712 | + base_addr = oss.str(); | ||||||||
| 1713 | + } | ||||||||
| 1714 | + | ||||||||
| 1715 | + // Sub-window valid_shape from args[2] (computed by parser as the intersection | ||||||||
| 1716 | + // of slice size and original valid_shape - start). | ||||||||
| 1717 | + auto shape_tuple = ir::As<ir::MakeTuple>(op->args_[2]); | ||||||||
| 1718 | + std::string vs_row = codegen.GetExprAsCode(shape_tuple->elements_[0]); | ||||||||
| 1719 | + std::string vs_col = codegen.GetExprAsCode(shape_tuple->elements_[1]); | ||||||||
🟠 High Priority 在 此问题与上一个 建议:在第 1717 行之后添加 Suggestions
![]() ![]() Incorrect? | |||||||||
| 1720 | + | ||||||||
| 1721 | + // Build type with original shape (preserves row_stride) but WITHOUT tileView_, | ||||||||
| 1722 | + // so valid_shape template params are -1 (dynamic). This is required because | ||||||||
| 1723 | + // subview calls SetValidShape at runtime, which only works when the template | ||||||||
| 1724 | + // valid_shape params are DYNAMIC (-1). | ||||||||
| 1725 | + std::vector<int64_t> dims; | ||||||||
| 1726 | + for (const auto& expr : tile_type->shape_) { | ||||||||
| 1727 | + dims.push_back(codegen.GetConstIntValue(expr)); | ||||||||
| 1728 | + } | ||||||||
| 1729 | + int64_t rows = dims.size() >= 1 ? dims[0] : 1; | ||||||||
| 1730 | + int64_t cols = dims.size() >= 2 ? dims[1] : 1; | ||||||||
| 1731 | + auto subview_type = std::make_shared<ir::TileType>(tile_type->shape_, tile_type->dtype_, tile_type->memref_); | ||||||||
| 1732 | + std::string type_str = codegen.GetTypeConverter().ConvertTileType(subview_type, rows, cols); | ||||||||
| 1733 | + | ||||||||
| 1734 | + // Sanitize base_tile into a valid C++ identifier prefix | ||||||||
| 1735 | + std::string base_tile_id = base_tile; | ||||||||
| 1736 | + for (char& c : base_tile_id) | ||||||||
| 1737 | + if (!std::isalnum(static_cast<unsigned char>(c)) && c != '_') | ||||||||
| 1738 | + c = '_'; | ||||||||
| 1739 | + std::string temp_name = codegen.GetCurrentResultTarget().empty() ? | ||||||||
| 1740 | + (base_tile_id + "_view_" + std::to_string(codegen.GetTileOffsetCounter())) : | ||||||||
| 1741 | + codegen.GetCurrentResultTarget(); | ||||||||
| 1742 | + | ||||||||
| 1743 | + // Emit: declare tile, TASSIGN offset address, then SetValidShape (must be | ||||||||
| 1744 | + // after TASSIGN — TASSIGN overwrites the constructor's valid_shape). | ||||||||
| 1745 | + std::string temp_addr = base_addr + " + (" + offset + ") * " + std::to_string(elem_bytes); | ||||||||
| 1746 | + codegen.Emit(type_str + " " + temp_name + "(" + vs_row + ", " + vs_col + "); TASSIGN(" + temp_name + ", " + | ||||||||
| 1747 | + temp_addr + "); " + temp_name + ".SetValidShape(" + vs_row + ", " + vs_col + ");"); | ||||||||
| 1748 | + codegen.SetTileAddress(temp_name, temp_addr); | ||||||||
| 1749 | + codegen.RegisterTileEmitShape(temp_name, vs_row, vs_col); | ||||||||
| 1750 | + | ||||||||
| 1751 | + return temp_name; | ||||||||
| 1752 | +} | ||||||||
| 1753 | + | ||||||||
| 1754 | +REGISTER_BACKEND_OP(BackendCCE, "block.subview") | ||||||||
| 1755 | + .set_pipe(ir::PipeType::MTE2) | ||||||||
| 1756 | + .f_codegen([](const ir::CallPtr& op, codegen::CodegenBase& codegen_base) { | ||||||||
| 1757 | + return MakeBlockSubviewCodegenCCE(op, codegen_base); | ||||||||
| 1758 | + }); | ||||||||
| 1759 | + | ||||||||
| 1676 | // ============================================================================ | 1760 | // ============================================================================ | ||||||
| 1677 | // Mutex (Buffer-ID Token) - A5 CCE Codegen | 1761 | // Mutex (Buffer-ID Token) - A5 CCE Codegen | ||||||
| 1678 | // ---------------------------------------------------------------------------- | 1762 | // ---------------------------------------------------------------------------- | ||||||
| @@ -41,6 +41,20 @@ static std::string VFEnumValueName(const char* full_name) | |||
| 41 | return sep ? std::string(sep + 1) : std::string(full_name); | 41 | return sep ? std::string(sep + 1) : std::string(full_name); |
| 42 | } | 42 | } |
| 43 | 43 | ||
| 44 | +// Returns true when the dst argument (args_[0], or args_[0]/args_[1] for 2-dst | ||
| 45 | +// ops) is a MaskReg variable. Used by unified emitters to dispatch between | ||
| 46 | +// v* (RegTensor) and p* (MaskReg) CCE intrinsics. | ||
| 47 | +static bool IsDstMaskReg(const ir::CallPtr& op, codegen::CCECodegen& codegen, size_t idx = 0) | ||
| 48 | +{ | ||
| 49 | + if (idx >= op->args_.size()) | ||
| 50 | + return false; | ||
| 51 | + auto dst_var = ir::As<ir::Var>(op->args_[idx]); | ||
| 52 | + if (dst_var) { | ||
| 53 | + return codegen.IsMaskRegVar(codegen.GetVarName(dst_var)); | ||
| 54 | + } | ||
| 55 | + return false; | ||
| 56 | +} | ||
| 57 | + | ||
| 44 | // ============================================================================ | 58 | // ============================================================================ |
| 45 | // RegTensor declaration | 59 | // RegTensor declaration |
| 46 | // ============================================================================ | 60 | // ============================================================================ |
| @@ -115,27 +115,6 @@ int64_t GetNZInnerCols(const ir::DataType& dtype, const std::string& error_prefi | |||
| 115 | throw pypto::ir::ValueError(error_prefix + dtype.ToString()); | 115 | throw pypto::ir::ValueError(error_prefix + dtype.ToString()); |
| 116 | } | 116 | } |
| 117 | 117 | ||
| 118 | -std::string GetCmpModeEnum(int cmp_type) | ||
| 119 | -{ | ||
| 120 | - switch (cmp_type) { | ||
| 121 | - case 0: | ||
| 122 | - return "CmpMode::EQ"; | ||
| 123 | - case 1: | ||
| 124 | - return "CmpMode::NE"; | ||
| 125 | - case 2: | ||
| 126 | - return "CmpMode::LT"; | ||
| 127 | - case 3: | ||
| 128 | - return "CmpMode::LE"; | ||
| 129 | - case 4: | ||
| 130 | - return "CmpMode::GT"; | ||
| 131 | - case 5: | ||
| 132 | - return "CmpMode::GE"; | ||
| 133 | - default: | ||
| 134 | - CHECK(false) << "Unsupported cmp_type for CCE codegen: " << cmp_type; | ||
| 135 | - return "CmpMode::EQ"; | ||
| 136 | - } | ||
| 137 | -} | ||
| 138 | - | ||
| 139 | static int64_t GetStaticConstIntOrThrow(const ir::ExprPtr& expr, const std::string& message) | 118 | static int64_t GetStaticConstIntOrThrow(const ir::ExprPtr& expr, const std::string& message) |
| 140 | { | 119 | { |
| 141 | auto value = ir::As<ir::ConstInt>(expr); | 120 | auto value = ir::As<ir::ConstInt>(expr); |
| @@ -552,8 +552,7 @@ void CCECodegen::PrepareBodyGeneration() | |||
| 552 | { | 552 | { |
| 553 | PreScanValidShapes(); | 553 | PreScanValidShapes(); |
| 554 | tuple_var_to_make_tuple_.clear(); | 554 | tuple_var_to_make_tuple_.clear(); |
| 555 | - tuple_vars_with_dyn_array_.clear(); | 555 | + tuple_backing_arr_.clear(); |
| 556 | - dyn_arr_counter_ = 0; | ||
| 557 | } | 556 | } |
| 558 | 557 | ||
| 559 | std::string CCECodegen::GenerateSingle(const ir::ProgramPtr& program, const std::string& arch) | 558 | std::string CCECodegen::GenerateSingle(const ir::ProgramPtr& program, const std::string& arch) |
| @@ -1327,21 +1326,18 @@ void CCECodegen::VisitStmt_(const ir::AssignStmtPtr& op) | |||
| 1327 | if (current_tuple_) { | 1326 | if (current_tuple_) { |
| 1328 | tuple_var_to_make_tuple_.emplace(var_name, current_tuple_); // first-write wins | 1327 | tuple_var_to_make_tuple_.emplace(var_name, current_tuple_); // first-write wins |
| 1329 | 1328 | ||
| 1330 | - // Emit the dynamic-index array at the MakeTuple assignment | 1329 | + // Materialize a homogeneous MakeTuple only once. Constant propagation may |
| 1331 | - // node (the stable identity shared with every use site). Gate on homogeneity: an | 1330 | + // expose this same MakeTuple through multiple tuple Vars, but all of them |
| 1332 | - // array is only valid when all elements map to the same C++ type. All element | 1331 | + // must resolve dynamic GetItem through the first backing array. |
| 1333 | - // variables (struct instances / tiles / scalars) are already in scope here, and this | 1332 | + auto make_tuple = current_tuple_; |
| 1334 | - // assignment dominates the use sites, so the array has the correct scope. The array | ||
| 1335 | - // name is the tuple var name (1:1 with the MakeTuple); SSA guarantees uniqueness. | ||
| 1336 | auto tt = ir::As<ir::TupleType>(target_var->GetType()); | 1333 | auto tt = ir::As<ir::TupleType>(target_var->GetType()); |
| 1337 | - if (tt && IsHomogeneousTuple(tt)) { | 1334 | + if (tt && IsHomogeneousTuple(tt) && tuple_backing_arr_.count(make_tuple.get()) == 0) { |
| 1338 | auto elem_names = CollectTupleElemNames(op->var_); | 1335 | auto elem_names = CollectTupleElemNames(op->var_); |
| 1339 | if (!elem_names.empty()) { | 1336 | if (!elem_names.empty()) { |
| 1340 | - std::string arr_decl = BuildDynamicTupleArrayDecl(tt->types_[0], elem_names, var_name, | 1337 | + std::string arr_decl = BuildDynamicTupleArrayDecl(tt->types_[0], elem_names, var_name); |
| 1341 | - /*allow_struct_tuple=*/true); | ||
| 1342 | if (!arr_decl.empty()) { | 1338 | if (!arr_decl.empty()) { |
| 1343 | emitter_.EmitLine(arr_decl); | 1339 | emitter_.EmitLine(arr_decl); |
| 1344 | - tuple_vars_with_dyn_array_.insert(var_name); | 1340 | + tuple_backing_arr_.emplace(make_tuple.get(), var_name); |
| 1345 | } | 1341 | } |
| 1346 | } | 1342 | } |
| 1347 | } | 1343 | } |
| @@ -1509,7 +1505,7 @@ std::vector<std::string> CCECodegen::CollectTupleElemNames(const ir::ExprPtr& tu | |||
| 1509 | 1505 | ||
| 1510 | std::string CCECodegen::BuildDynamicTupleArrayDecl(const ir::TypePtr& elem_type, | 1506 | std::string CCECodegen::BuildDynamicTupleArrayDecl(const ir::TypePtr& elem_type, |
| 1511 | const std::vector<std::string>& elem_names, | 1507 | const std::vector<std::string>& elem_names, |
| 1512 | - const std::string& arr_name, bool allow_struct_tuple) const | 1508 | + const std::string& arr_name) const |
| 1513 | { | 1509 | { |
| 1514 | if (elem_names.empty()) { | 1510 | if (elem_names.empty()) { |
| 1515 | return ""; | 1511 | return ""; |
| @@ -1529,7 +1525,7 @@ std::string CCECodegen::BuildDynamicTupleArrayDecl(const ir::TypePtr& elem_type, | |||
| 1529 | } else if (auto scalar_type = ir::As<ir::ScalarType>(elem_type)) { | 1525 | } else if (auto scalar_type = ir::As<ir::ScalarType>(elem_type)) { |
| 1530 | scalar_cast_type = scalar_type->dtype_.ToCTypeString(); | 1526 | scalar_cast_type = scalar_type->dtype_.ToCTypeString(); |
| 1531 | elem_cpp_type = "const " + scalar_cast_type; | 1527 | elem_cpp_type = "const " + scalar_cast_type; |
| 1532 | - } else if (allow_struct_tuple) { | 1528 | + } else { |
| 1533 | auto inner_tt = ir::As<ir::TupleType>(elem_type); | 1529 | auto inner_tt = ir::As<ir::TupleType>(elem_type); |
| 1534 | if (inner_tt && debug_info_ != nullptr && debug_info_->GetTupleFields(inner_tt.get()) != nullptr) { | 1530 | if (inner_tt && debug_info_ != nullptr && debug_info_->GetTupleFields(inner_tt.get()) != nullptr) { |
| 1535 | auto type_it = struct_var_to_type_name_.find(elem_names[0]); | 1531 | auto type_it = struct_var_to_type_name_.find(elem_names[0]); |
| @@ -2130,151 +2126,73 @@ void CCECodegen::VisitExpr_(const ir::GetItemExprPtr& op) | |||
| 2130 | INTERNAL_CHECK(op != nullptr) << "Internal error: null GetItemExpr"; | 2126 | INTERNAL_CHECK(op != nullptr) << "Internal error: null GetItemExpr"; |
| 2131 | 2127 | ||
| 2132 | auto value_type = op->value_->GetType(); | 2128 | auto value_type = op->value_->GetType(); |
| 2129 | + CHECK(ir::As<ir::TupleType>(value_type)) | ||
| 2130 | + << "GetItemExpr requires value to have TupleType, got " << value_type->TypeName(); | ||
| 2133 | 2131 | ||
| 2134 | - // Tuple element access. | 2132 | + auto const_idx = ir::As<ir::ConstInt>(op->slice_); |
| 2135 | - if (ir::As<ir::TupleType>(value_type)) { | 2133 | + if (const_idx != nullptr) { |
| 2136 | - auto const_idx = ir::As<ir::ConstInt>(op->slice_); | 2134 | + // Static (constant) index: VisitExpr drives current_tuple_, then VisitExpr the element. |
| 2137 | - if (const_idx != nullptr) { | 2135 | + int idx = static_cast<int>(const_idx->value_); |
| 2138 | - // Static (constant) index: VisitExpr drives current_tuple_, then VisitExpr the element. | 2136 | + INTERNAL_CHECK(idx >= 0) << "GetItemExpr negative tuple index " << idx; |
| 2139 | - int idx = static_cast<int>(const_idx->value_); | ||
| 2140 | - INTERNAL_CHECK(idx >= 0) << "GetItemExpr negative tuple index " << idx; | ||
| 2141 | 2137 | ||
| 2142 | - current_tuple_ = nullptr; | ||
| 2143 | - current_expr_value_ = ""; | ||
| 2144 | - VisitExpr(op->value_); | ||
| 2145 | - if (current_tuple_ == nullptr) { | ||
| 2146 | - // The base has no underlying MakeTuple to fold into (e.g. a tiling struct | ||
| 2147 | - // param or its array field). Field names registered in IRDebugInfo mark a | ||
| 2148 | - // struct -> emit `base.field`; their absence marks an array field (the nested | ||
| 2149 | - // TupleType of an Array[T, N]) -> emit `base[idx]`. | ||
| 2150 | - auto tuple_type = ir::As<ir::TupleType>(value_type); | ||
| 2151 | - const std::vector<std::string>* fields = debug_info_ != nullptr ? | ||
| 2152 | - debug_info_->GetTupleFields(tuple_type.get()) : | ||
| 2153 | - nullptr; | ||
| 2154 | - std::string base_code = GetExprAsCode(op->value_); | ||
| 2155 | - current_tuple_ = nullptr; | ||
| 2156 | - if (fields != nullptr) { | ||
| 2157 | - CHECK(idx < static_cast<int>(fields->size())) | ||
| 2158 | - << "GetItemExpr struct field: no field name for tuple index " << idx; | ||
| 2159 | - current_expr_value_ = base_code + "." + (*fields)[idx]; | ||
| 2160 | - } else { | ||
| 2161 | - // base_code already carries the array field name (e.g. tiling.opkind), | ||
| 2162 | - // so appending the constant index yields tiling.opkind[idx]. | ||
| 2163 | - current_expr_value_ = base_code + "[" + std::to_string(idx) + "]"; | ||
| 2164 | - } | ||
| 2165 | - return; | ||
| 2166 | - } else if (tuple_vars_with_dyn_array_.count(current_expr_value_) != 0) { | ||
| 2167 | - current_tuple_ = nullptr; | ||
| 2168 | - current_expr_value_ += "[" + std::to_string(idx) + "]"; | ||
| 2169 | - return; | ||
| 2170 | - } | ||
| 2171 | - CHECK(!current_tuple_->elements_.empty()) << "Cannot index an empty tuple at " << op->span_.ToString(); | ||
| 2172 | - INTERNAL_CHECK(idx < static_cast<int>(current_tuple_->elements_.size())) | ||
| 2173 | - << "GetItemExpr index " << idx << " out of bounds"; | ||
| 2174 | - ir::ExprPtr elem = current_tuple_->elements_[idx]; | ||
| 2175 | - | ||
| 2176 | - current_tuple_ = nullptr; | ||
| 2177 | - current_expr_value_ = ""; | ||
| 2178 | - VisitExpr(elem); // result lands in current_tuple_ (sub-tuple) or current_expr_value_ | ||
| 2179 | - return; | ||
| 2180 | - } | ||
| 2181 | - | ||
| 2182 | - // Dynamic index: a named tuple with a materialized backing array keeps its | ||
| 2183 | - // variable identity; anonymous MakeTuple expressions use a local fallback array. | ||
| 2184 | - std::string index_code = GetExprAsCode(op->slice_); | ||
| 2185 | current_tuple_ = nullptr; | 2138 | current_tuple_ = nullptr; |
| 2186 | current_expr_value_ = ""; | 2139 | current_expr_value_ = ""; |
| 2187 | VisitExpr(op->value_); | 2140 | VisitExpr(op->value_); |
| 2188 | - CHECK(current_tuple_ != nullptr) << "Dynamic tuple GetItem: cannot resolve underlying MakeTuple for " | 2141 | + if (current_tuple_ == nullptr) { |
| 2189 | - << op->value_->TypeName(); | 2142 | + // The base has no underlying MakeTuple to fold into (e.g. a tiling struct |
| 2143 | + // param or its array field). Field names registered in IRDebugInfo mark a | ||
| 2144 | + // struct -> emit `base.field`; their absence marks an array field (the nested | ||
| 2145 | + // TupleType of an Array[T, N]) -> emit `base[idx]`. | ||
| 2146 | + auto tuple_type = ir::As<ir::TupleType>(value_type); | ||
| 2147 | + const std::vector<std::string>* fields = debug_info_ != nullptr ? | ||
| 2148 | + debug_info_->GetTupleFields(tuple_type.get()) : | ||
| 2149 | + nullptr; | ||
| 2150 | + std::string base_code = GetExprAsCode(op->value_); | ||
| 2151 | + current_tuple_ = nullptr; | ||
| 2152 | + if (fields != nullptr) { | ||
| 2153 | + CHECK(idx < static_cast<int>(fields->size())) | ||
| 2154 | + << "GetItemExpr struct field: no field name for tuple index " << idx; | ||
| 2155 | + current_expr_value_ = base_code + "." + (*fields)[idx]; | ||
| 2156 | + } else { | ||
| 2157 | + // base_code already carries the array field name (e.g. tiling.opkind), | ||
| 2158 | + // so appending the constant index yields tiling.opkind[idx]. | ||
| 2159 | + current_expr_value_ = base_code + "[" + std::to_string(idx) + "]"; | ||
| 2160 | + } | ||
| 2161 | + return; | ||
| 2162 | + } | ||
| 2190 | 2163 | ||
| 2191 | - ir::MakeTuplePtr resolved_mt = current_tuple_; | 2164 | + auto arr_it = tuple_backing_arr_.find(current_tuple_.get()); |
| 2192 | - std::string arr_name; | 2165 | + if (arr_it != tuple_backing_arr_.end()) { |
| 2193 | - if (tuple_vars_with_dyn_array_.count(current_expr_value_) != 0) { | 2166 | + current_tuple_ = nullptr; |
| 2194 | - arr_name = current_expr_value_; | 2167 | + current_expr_value_ = arr_it->second + "[" + std::to_string(idx) + "]"; |
| 2168 | + return; | ||
| 2195 | } | 2169 | } |
| 2196 | - if (arr_name.empty() && !resolved_mt->elements_.empty()) { | 2170 | + CHECK(!current_tuple_->elements_.empty()) << "Cannot index an empty tuple at " << op->span_.ToString(); |
| 2197 | - // No dominating assignment materialized an array for this MakeTuple (for | 2171 | + INTERNAL_CHECK(idx < static_cast<int>(current_tuple_->elements_.size())) |
| 2198 | - // example, an anonymous tuple expression). Preserve the existing fallback | 2172 | + << "GetItemExpr index " << idx << " out of bounds"; |
| 2199 | - // by creating a local temporary array at this dynamic-index use. | 2173 | + ir::ExprPtr elem = current_tuple_->elements_[idx]; |
| 2200 | - auto elem_type = resolved_mt->elements_[0]->GetType(); | 2174 | + |
| 2201 | - std::vector<std::string> elem_names; | 2175 | + current_tuple_ = nullptr; |
| 2202 | - elem_names.reserve(resolved_mt->elements_.size()); | 2176 | + current_expr_value_ = ""; |
| 2203 | - for (size_t i = 0; i < resolved_mt->elements_.size(); ++i) { | 2177 | + VisitExpr(elem); // result lands in current_tuple_ (sub-tuple) or current_expr_value_ |
| 2204 | - elem_names.push_back(GetExprAsCode(resolved_mt->elements_[i])); | ||
| 2205 | - } | ||
| 2206 | - std::string candidate_arr_name = "_dyn_arr_" + std::to_string(dyn_arr_counter_); | ||
| 2207 | - std::string arr_decl = BuildDynamicTupleArrayDecl(elem_type, elem_names, candidate_arr_name, | ||
| 2208 | - /*allow_struct_tuple=*/false); | ||
| 2209 | - if (!arr_decl.empty()) { | ||
| 2210 | - arr_name = candidate_arr_name; | ||
| 2211 | - ++dyn_arr_counter_; | ||
| 2212 | - emitter_.EmitLine(arr_decl); | ||
| 2213 | - } | ||
| 2214 | - } | ||
| 2215 | - current_expr_value_ = arr_name + "[" + index_code + "]"; | ||
| 2216 | return; | 2178 | return; |
| 2217 | } | 2179 | } |
| 2218 | 2180 | ||
| 2219 | - // Tile element offset: slice_ is an integer expression (static or dynamic). | 2181 | + // Dynamic tuple indexing always resolves through the MakeTuple owner's |
| 2220 | - auto tile_type = ir::As<ir::TileType>(value_type); | 2182 | + // backing array. Parser anchors every anonymous MakeTuple before use. |
| 2221 | - INTERNAL_CHECK(tile_type != nullptr) << "GetItemExpr requires value to have TupleType or TileType, got " | 2183 | + std::string index_code = GetExprAsCode(op->slice_); |
| 2222 | - << value_type->TypeName(); | 2184 | + current_tuple_ = nullptr; |
| 2185 | + current_expr_value_ = ""; | ||
| 2186 | + VisitExpr(op->value_); | ||
| 2187 | + CHECK(current_tuple_ != nullptr) << "Dynamic tuple GetItem: cannot resolve underlying MakeTuple for " | ||
| 2188 | + << op->value_->TypeName(); | ||
| 2223 | 2189 | ||
| 2224 | - std::string base_tile = GetExprAsCode(op->value_); | 2190 | + ir::MakeTuplePtr resolved_mt = current_tuple_; |
| 2225 | - std::string offset_expr = GetExprAsCode(op->slice_); | 2191 | + auto arr_it = tuple_backing_arr_.find(resolved_mt.get()); |
| 2226 | - | 2192 | + CHECK(arr_it != tuple_backing_arr_.end()) |
| 2227 | - int elem_bytes = static_cast<int>(tile_type->dtype_.GetBit() / 8); | 2193 | + << "Dynamic tuple GetItem has no backing-array owner at " << op->span_.ToString(); |
| 2228 | - if (elem_bytes == 0) | 2194 | + current_expr_value_ = arr_it->second + "[" + index_code + "]"; |
| 2229 | - elem_bytes = 1; // guard sub-byte types | 2195 | + return; |
| 2230 | - | ||
| 2231 | - // VF section: typed pointer arithmetic off the section-hoisted base ptr. `vf_tile_ptr_N + offset` | ||
| 2232 | - // advances by whole elements and lets matching loads/stores skip the cast. | ||
| 2233 | - if (IsInVFSection()) { | ||
| 2234 | - std::string base_ptr = GetOrCreateVFTilePtr(op->value_, /*is_post_update=*/false); | ||
| 2235 | - current_expr_value_ = "(" + base_ptr + " + (" + offset_expr + "))"; | ||
| 2236 | - return; | ||
| 2237 | - } | ||
| 2238 | - | ||
| 2239 | - // Get base tile address ->try tile_addresses_ first, then extract from TileType memref | ||
| 2240 | - std::string base_addr; | ||
| 2241 | - auto addr_it = tile_addresses_.find(base_tile); | ||
| 2242 | - if (addr_it != tile_addresses_.end()) { | ||
| 2243 | - base_addr = addr_it->second; | ||
| 2244 | - } else if (base_tile.find('[') != std::string::npos) { | ||
| 2245 | - // Dynamically-indexed tile-group member (e.g. `_tg_foo_tiles_0[bufidx]`): the runtime | ||
| 2246 | - // buffer selected by the cursor is unknown at codegen time, so the static memref address | ||
| 2247 | - // (which only records buffer 0) would be wrong. Use the tile's runtime base via .data() | ||
| 2248 | - // so element-offset slices follow the actual double-buffer slot. | ||
| 2249 | - base_addr = "(uint64_t)" + base_tile + ".data()"; | ||
| 2250 | - } else { | ||
| 2251 | - INTERNAL_CHECK(tile_type->memref_.has_value()) | ||
| 2252 | - << "GetItemExpr: base tile '" << base_tile << "' has no address info"; | ||
| 2253 | - int64_t addr = ExtractConstInt((*tile_type->memref_)->addr_); | ||
| 2254 | - base_addr = FormatAddressHex(addr); | ||
| 2255 | - } | ||
| 2256 | - | ||
| 2257 | - // Sanitize base_tile into a valid C++ identifier prefix: replace non-alnum/underscore chars. | ||
| 2258 | - std::string base_tile_id = base_tile; | ||
| 2259 | - for (char& c : base_tile_id) { | ||
| 2260 | - if (!std::isalnum(static_cast<unsigned char>(c)) && c != '_') | ||
| 2261 | - c = '_'; | ||
| 2262 | - } | ||
| 2263 | - std::string temp_name = base_tile_id + "_eoff_" + std::to_string(tile_offset_counter_++); | ||
| 2264 | - | ||
| 2265 | - std::vector<int64_t> shape_dims = ExtractShapeDimensions(tile_type->shape_); | ||
| 2266 | - int64_t rows = shape_dims.size() >= 1 ? shape_dims[0] : 1; | ||
| 2267 | - int64_t cols = shape_dims.size() >= 2 ? shape_dims[1] : 1; | ||
| 2268 | - auto vs = ExtractValidShapeInfo(tile_type, rows, cols, [this](const ir::VarPtr& v) { return GetVarName(v); }); | ||
| 2269 | - std::string ctor_args = BuildTileCtorArgs(vs, rows, cols); | ||
| 2270 | - std::string ctor_suffix = vs.needs_ctor ? ("(" + ctor_args + ")") : ""; | ||
| 2271 | - std::string type_str = type_converter_.ConvertTileType(tile_type, rows, cols); | ||
| 2272 | - std::string temp_addr = base_addr + " + (" + offset_expr + ") * " + std::to_string(elem_bytes); | ||
| 2273 | - emitter_.EmitLine(type_str + " " + temp_name + ctor_suffix + "; " + "TASSIGN(" + temp_name + ", " + temp_addr + | ||
| 2274 | - ");"); | ||
| 2275 | - tile_addresses_[temp_name] = temp_addr; | ||
| 2276 | - | ||
| 2277 | - current_expr_value_ = temp_name; | ||
| 2278 | } | 2196 | } |
| 2279 | 2197 | ||
| 2280 | // ======================================================================== | 2198 | // ======================================================================== |
| @@ -2323,6 +2241,11 @@ bool CCECodegen::HasPointer(const std::string& var_name) const | |||
| 2323 | return tensor_to_pointer_.find(var_name) != tensor_to_pointer_.end(); | 2241 | return tensor_to_pointer_.find(var_name) != tensor_to_pointer_.end(); |
| 2324 | } | 2242 | } |
| 2325 | 2243 | ||
| 2244 | +bool CCECodegen::HasTileAddress(const std::string& tile_name) const | ||
| 2245 | +{ | ||
| 2246 | + return tile_addresses_.find(tile_name) != tile_addresses_.end(); | ||
| 2247 | +} | ||
| 2248 | + | ||
| 2326 | const TensorDef* CCECodegen::GetTensorDef(const std::string& name) const | 2249 | const TensorDef* CCECodegen::GetTensorDef(const std::string& name) const |
| 2327 | { | 2250 | { |
| 2328 | auto it = tensor_defs_.find(name); | 2251 | auto it = tensor_defs_.find(name); |
| @@ -2385,8 +2308,6 @@ void CCECodegen::VisitExpr_(const ir::CallPtr& op) | |||
| 2385 | "vf.store_unalign_post", | 2308 | "vf.store_unalign_post", |
| 2386 | "vf.store", | 2309 | "vf.store", |
| 2387 | "vf.scatter", | 2310 | "vf.scatter", |
| 2388 | - "vf.mask_store", | ||
| 2389 | - "vf.mask_store_unalign", | ||
| 2390 | "vf.store_align_pack", | 2311 | "vf.store_align_pack", |
| 2391 | "vf.store_align_intlv", | 2312 | "vf.store_align_intlv", |
| 2392 | "vf.store_align_pack_postupdate", | 2313 | "vf.store_align_pack_postupdate", |
| @@ -2408,7 +2329,9 @@ void CCECodegen::VisitExpr_(const ir::CallPtr& op) | |||
| 2408 | }; | 2329 | }; |
| 2409 | if (skip_ops.count(op->name_) == 0) { | 2330 | if (skip_ops.count(op->name_) == 0) { |
| 2410 | static const std::set<std::string> dual_dst_ops = { | 2331 | static const std::set<std::string> dual_dst_ops = { |
| 2411 | - "vf.interleave", "vf.de_interleave", "vf.mask_interleave", "vf.mask_deinterleave", "vf.mull", | 2332 | + "vf.interleave", |
| 2333 | + "vf.de_interleave", | ||
| 2334 | + "vf.mull", | ||
| 2412 | }; | 2335 | }; |
| 2413 | bool is_dual_dst = dual_dst_ops.count(op->name_) > 0; | 2336 | bool is_dual_dst = dual_dst_ops.count(op->name_) > 0; |
| 2414 | 2337 | ||
| @@ -236,6 +236,46 @@ TEST_F(BlockOpsMemoryTest, SetVal_NonScalarValue_Throws) | |||
| 236 | npu::tile_fwk::Error); | 236 | npu::tile_fwk::Error); |
| 237 | } | 237 | } |
| 238 | 238 | ||
| 239 | +// ============================================================================ | ||
| 240 | +// memory.cpp: block.subview | ||
| 241 | +// ============================================================================ | ||
| 242 | + | ||
| 243 | +TEST_F(BlockOpsMemoryTest, Subview_TilePreservesPhysicalTypeAndMemRef) | ||
| 244 | +{ | ||
| 245 | + auto& reg = OpRegistry::GetInstance(); | ||
| 246 | + auto tile = MakeTileVarWithMemRef("tile", {16, 32}, DataType::FP16, MemorySpace::Vec, 0x100, 1024); | ||
| 247 | + auto source_type = As<TileType>(tile->GetType()); | ||
| 248 | + | ||
| 249 | + auto call = reg.Create("block.subview", {tile, MakeScalarVar("offset", DataType::INT64), MakeIntTuple({8, 12})}, | ||
| 250 | + Sp()); | ||
| 251 | + | ||
| 252 | + auto result_type = As<TileType>(call->GetType()); | ||
| 253 | + ASSERT_NE(result_type, nullptr); | ||
| 254 | + EXPECT_NE(result_type.get(), source_type.get()); | ||
| 255 | + EXPECT_EQ(result_type->dtype_, source_type->dtype_); | ||
| 256 | + EXPECT_EQ(result_type->shape_, source_type->shape_); | ||
| 257 | + EXPECT_EQ(result_type->memref_, source_type->memref_); | ||
| 258 | +} | ||
| 259 | + | ||
| 260 | +TEST_F(BlockOpsMemoryTest, Subview_WrongArgCount_Throws) | ||
| 261 | +{ | ||
| 262 | + auto& reg = OpRegistry::GetInstance(); | ||
| 263 | + EXPECT_THROW((void)reg.Create( | ||
| 264 | + "block.subview", | ||
| 265 | + {MakeTileVar("tile", {16, 32}, DataType::FP16), MakeScalarVar("offset", DataType::INT64)}, Sp()), | ||
| 266 | + npu::tile_fwk::Error); | ||
| 267 | +} | ||
| 268 | + | ||
| 269 | +TEST_F(BlockOpsMemoryTest, Subview_NonTileContainer_Throws) | ||
| 270 | +{ | ||
| 271 | + auto& reg = OpRegistry::GetInstance(); | ||
| 272 | + EXPECT_THROW((void)reg.Create("block.subview", | ||
| 273 | + {MakeScalarVar("container", DataType::FP16), MakeScalarVar("offset", DataType::INT64), | ||
| 274 | + MakeIntTuple({8, 12})}, | ||
| 275 | + Sp()), | ||
| 276 | + npu::tile_fwk::Error); | ||
| 277 | +} | ||
| 278 | + | ||
| 239 | // ============================================================================ | 279 | // ============================================================================ |
| 240 | // struct_ops.cpp: struct.create, struct.set | 280 | // struct_ops.cpp: struct.create, struct.set |
| 241 | // ============================================================================ | 281 | // ============================================================================ |
| @@ -724,7 +764,7 @@ TEST_F(BlockOpsOutElemwiseTest, BlockSel_WrongArgCount_Throws) | |||
| 724 | TEST_F(BlockOpsOutElemwiseTest, BlockCmp_ThreeTiles_ReturnsOutType) | 764 | TEST_F(BlockOpsOutElemwiseTest, BlockCmp_ThreeTiles_ReturnsOutType) |
| 725 | { | 765 | { |
| 726 | auto& reg = OpRegistry::GetInstance(); | 766 | auto& reg = OpRegistry::GetInstance(); |
| 727 | - std::vector<std::pair<std::string, std::any>> kwargs = {{"cmp_type", int(0)}}; | 767 | + std::vector<std::pair<std::string, std::any>> kwargs = {{"cmp_mode", int(0)}}; |
| 728 | auto call = reg.Create("block.cmp", | 768 | auto call = reg.Create("block.cmp", |
| 729 | {MakeTileVar("o", {16, 16}, DataType::FP16), MakeTileVar("l", {16, 16}, DataType::FP16), | 769 | {MakeTileVar("o", {16, 16}, DataType::FP16), MakeTileVar("l", {16, 16}, DataType::FP16), |
| 730 | MakeTileVar("r", {16, 16}, DataType::FP16)}, | 770 | MakeTileVar("r", {16, 16}, DataType::FP16)}, |
| @@ -735,7 +775,7 @@ TEST_F(BlockOpsOutElemwiseTest, BlockCmp_ThreeTiles_ReturnsOutType) | |||
| 735 | TEST_F(BlockOpsOutElemwiseTest, BlockCmps_TileScalarOut_ReturnsOutType) | 775 | TEST_F(BlockOpsOutElemwiseTest, BlockCmps_TileScalarOut_ReturnsOutType) |
| 736 | { | 776 | { |
| 737 | auto& reg = OpRegistry::GetInstance(); | 777 | auto& reg = OpRegistry::GetInstance(); |
| 738 | - std::vector<std::pair<std::string, std::any>> kwargs = {{"cmp_type", int(1)}}; | 778 | + std::vector<std::pair<std::string, std::any>> kwargs = {{"cmp_mode", int(1)}}; |
| 739 | auto call = reg.Create("block.cmps", | 779 | auto call = reg.Create("block.cmps", |
| 740 | {MakeTileVar("o", {16, 16}, DataType::FP16), MakeTileVar("t", {16, 16}, DataType::FP16), | 780 | {MakeTileVar("o", {16, 16}, DataType::FP16), MakeTileVar("t", {16, 16}, DataType::FP16), |
| 741 | MakeScalarVar("s", DataType::FP16)}, | 781 | MakeScalarVar("s", DataType::FP16)}, |
| @@ -135,6 +135,30 @@ TEST_F(ConvertToSSAPassTest, TestVarUseRefsCurrentVersion) | |||
| 135 | EXPECT_EQ(lhs_var->name_, a1->var_->name_); | 135 | EXPECT_EQ(lhs_var->name_, a1->var_->name_); |
| 136 | } | 136 | } |
| 137 | 137 | ||
| 138 | +TEST_F(ConvertToSSAPassTest, TestSharedExpressionKeepsIdentity) | ||
| 139 | +{ | ||
| 140 | + auto x = MakeVar("x"); | ||
| 141 | + auto idx = MakeVar("idx"); | ||
| 142 | + auto tuple_anchor = MakeVar("tuple_anchor", std::make_shared<TupleType>(std::vector<TypePtr>{ | ||
| 143 | + Scalar(DataType::INT32), Scalar(DataType::INT32)})); | ||
| 144 | + auto selected = MakeVar("selected"); | ||
| 145 | + auto tuple = std::make_shared<MakeTuple>(std::vector<ExprPtr>{x, x}, Sp()); | ||
| 146 | + auto anchor_assign = std::make_shared<AssignStmt>(tuple_anchor, tuple, Sp()); | ||
| 147 | + auto get_item = std::make_shared<GetItemExpr>(tuple, idx, Sp()); | ||
| 148 | + auto selected_assign = std::make_shared<AssignStmt>(selected, get_item, Sp()); | ||
| 149 | + auto body = std::make_shared<SeqStmts>(std::vector<StmtPtr>{anchor_assign, selected_assign}, Sp()); | ||
| 150 | + | ||
| 151 | + auto result = RunPass(MakeProg(MakeFunc("f", {x, idx}, body))); | ||
| 152 | + auto seq = result->GetFunction("f")->body_; | ||
| 153 | + auto ssa_anchor = std::dynamic_pointer_cast<const AssignStmt>(seq->stmts_[0]); | ||
| 154 | + auto ssa_selected = std::dynamic_pointer_cast<const AssignStmt>(seq->stmts_[1]); | ||
| 155 | + ASSERT_NE(ssa_anchor, nullptr); | ||
| 156 | + ASSERT_NE(ssa_selected, nullptr); | ||
| 157 | + auto ssa_get_item = std::dynamic_pointer_cast<const GetItemExpr>(ssa_selected->value_); | ||
| 158 | + ASSERT_NE(ssa_get_item, nullptr); | ||
| 159 | + EXPECT_EQ(ssa_anchor->value_.get(), ssa_get_item->value_.get()); | ||
| 160 | +} | ||
| 161 | + | ||
| 138 | // ============================================================================ | 162 | // ============================================================================ |
| 139 | // If-stmt without else — creates phi for modified var | 163 | // If-stmt without else — creates phi for modified var |
| 140 | // ============================================================================ | 164 | // ============================================================================ |
| @@ -422,12 +422,12 @@ TEST(BackendCCEBlockOutOps, Cmp) | |||
| 422 | auto tile = MakeTileType(); | 422 | auto tile = MakeTileType(); |
| 423 | for (int i = 0; i <= 5; ++i) { | 423 | for (int i = 0; i <= 5; ++i) { |
| 424 | auto call = MakeCallWithKwargs("block.cmp", {MakeVar("dst", tile), MakeVar("lhs", tile), MakeVar("rhs", tile)}, | 424 | auto call = MakeCallWithKwargs("block.cmp", {MakeVar("dst", tile), MakeVar("lhs", tile), MakeVar("rhs", tile)}, |
| 425 | - {{"cmp_type", i}}); | 425 | + {{"cmp_mode", i}}); |
| 426 | auto code = RunCodegen("block.cmp", call); | 426 | auto code = RunCodegen("block.cmp", call); |
| 427 | EXPECT_CONTAINS(code, "TCMP(dst, lhs, rhs, "); | 427 | EXPECT_CONTAINS(code, "TCMP(dst, lhs, rhs, "); |
| 428 | } | 428 | } |
| 429 | auto call0 = MakeCallWithKwargs("block.cmp", {MakeVar("dst", tile), MakeVar("lhs", tile), MakeVar("rhs", tile)}, | 429 | auto call0 = MakeCallWithKwargs("block.cmp", {MakeVar("dst", tile), MakeVar("lhs", tile), MakeVar("rhs", tile)}, |
| 430 | - {{"cmp_type", 0}}); | 430 | + {{"cmp_mode", 0}}); |
| 431 | EXPECT_CONTAINS(RunCodegen("block.cmp", call0), "TCMP(dst, lhs, rhs, CmpMode::EQ);"); | 431 | EXPECT_CONTAINS(RunCodegen("block.cmp", call0), "TCMP(dst, lhs, rhs, CmpMode::EQ);"); |
| 432 | } | 432 | } |
| 433 | 433 | ||
| @@ -436,7 +436,7 @@ TEST(BackendCCEBlockOutOps, Cmps) | |||
| 436 | auto tile = MakeTileType(); | 436 | auto tile = MakeTileType(); |
| 437 | auto scal = MakeScalarType(); | 437 | auto scal = MakeScalarType(); |
| 438 | auto call = MakeCallWithKwargs("block.cmps", {MakeVar("dst", tile), MakeVar("tile", tile), MakeVar("scalar", scal)}, | 438 | auto call = MakeCallWithKwargs("block.cmps", {MakeVar("dst", tile), MakeVar("tile", tile), MakeVar("scalar", scal)}, |
| 439 | - {{"cmp_type", 4}}); | 439 | + {{"cmp_mode", 4}}); |
| 440 | EXPECT_CONTAINS(RunCodegen("block.cmps", call), "TCMPS(dst, tile, scalar, CmpMode::GT);"); | 440 | EXPECT_CONTAINS(RunCodegen("block.cmps", call), "TCMPS(dst, tile, scalar, CmpMode::GT);"); |
| 441 | } | 441 | } |
| 442 | 442 | ||
| @@ -39,6 +39,9 @@ using Kwargs = std::vector<std::pair<std::string, std::any>>; | |||
| 39 | class TestableCCECodegen : public codegen::CCECodegen { | 39 | class TestableCCECodegen : public codegen::CCECodegen { |
| 40 | public: | 40 | public: |
| 41 | std::string GetEmittedCode() const { return emitter_.GetCode(); } | 41 | std::string GetEmittedCode() const { return emitter_.GetCode(); } |
| 42 | + void SetCurrentResultTarget(std::string target) { current_target_var_ = std::move(target); } | ||
| 43 | + void SetCurrentSectionKind(std::optional<ir::SectionKind> kind) { current_section_kind_ = kind; } | ||
| 44 | + void RegisterVarName(const ir::VarPtr& var, const std::string& name) { context_.RegisterVar(var, name); } | ||
| 42 | }; | 45 | }; |
| 43 | 46 | ||
| 44 | ir::ExprPtr MakeConstInt(int64_t value, ir::DataType dtype = ir::DataType::INT64) | 47 | ir::ExprPtr MakeConstInt(int64_t value, ir::DataType dtype = ir::DataType::INT64) |
| @@ -673,6 +676,92 @@ TEST(BackendCceOpsTest, BlockSetValTensor) | |||
| 673 | EXPECT_NE(generated.find("+ 5) = 42;"), std::string::npos); | 676 | EXPECT_NE(generated.find("+ 5) = 42;"), std::string::npos); |
| 674 | } | 677 | } |
| 675 | 678 | ||
| 679 | +// ============================================================================ | ||
| 680 | +// block.subview | ||
| 681 | +// ============================================================================ | ||
| 682 | + | ||
| 683 | +TEST(BackendCceOpsTest, BlockSubviewUsesRegisteredAddressAndResultTarget) | ||
| 684 | +{ | ||
| 685 | + auto tile = MakeVar("tile", MakeTileType({16, 32}, ir::DataType::FP16, ir::MemorySpace::Vec)); | ||
| 686 | + auto call = std::make_shared<const ir::Call>( | ||
| 687 | + "block.subview", | ||
| 688 | + std::vector<ir::ExprPtr>{tile, MakeConstInt(3), MakeTuple({MakeConstInt(8), MakeConstInt(12)})}, | ||
| 689 | + tile->GetType(), ir::Span::Unknown()); | ||
| 690 | + auto* info = BackendCCE::Instance().GetOpInfo("block.subview"); | ||
| 691 | + ASSERT_NE(info, nullptr); | ||
| 692 | + EXPECT_EQ(info->pipe, ir::PipeType::MTE2); | ||
| 693 | + | ||
| 694 | + TestableCCECodegen codegen; | ||
| 695 | + codegen.SetTileAddress("tile", "0x200"); | ||
| 696 | + codegen.SetCurrentResultTarget("view"); | ||
| 697 | + EXPECT_EQ(info->codegen_func(call, codegen), "view"); | ||
| 698 | + | ||
| 699 | + auto generated = codegen.GetEmittedCode(); | ||
| 700 | + EXPECT_NE(generated.find("TASSIGN(view, 0x200 + (3) * 2)"), std::string::npos); | ||
| 701 | + EXPECT_NE(generated.find("view.SetValidShape(8, 12)"), std::string::npos); | ||
| 702 | + EXPECT_TRUE(codegen.HasTileAddress("view")); | ||
| 703 | + EXPECT_EQ(codegen.GetTileAddress("view"), "0x200 + (3) * 2"); | ||
| 704 | + auto shape = codegen.LookupTileEmitShape("view"); | ||
| 705 | + ASSERT_TRUE(shape.has_value()); | ||
| 706 | + EXPECT_EQ(shape->first, "8"); | ||
| 707 | + EXPECT_EQ(shape->second, "12"); | ||
| 708 | +} | ||
| 709 | + | ||
| 710 | +TEST(BackendCceOpsTest, BlockSubviewUsesDynamicTileGroupAddressAndGeneratedName) | ||
| 711 | +{ | ||
| 712 | + auto tile = MakeVar("tile", MakeTileType({16, 32}, ir::DataType::FP16, ir::MemorySpace::Vec)); | ||
| 713 | + auto call = std::make_shared<const ir::Call>( | ||
| 714 | + "block.subview", std::vector<ir::ExprPtr>{tile, MakeConstInt(5), MakeTuple({MakeConstInt(4), MakeConstInt(7)})}, | ||
| 715 | + tile->GetType(), ir::Span::Unknown()); | ||
| 716 | + auto* info = BackendCCE::Instance().GetOpInfo("block.subview"); | ||
| 717 | + ASSERT_NE(info, nullptr); | ||
| 718 | + | ||
| 719 | + TestableCCECodegen codegen; | ||
| 720 | + codegen.RegisterVarName(tile, "tiles[index]"); | ||
| 721 | + auto result = info->codegen_func(call, codegen); | ||
| 722 | + | ||
| 723 | + EXPECT_EQ(result, "tiles_index__view_0"); | ||
| 724 | + auto generated = codegen.GetEmittedCode(); | ||
| 725 | + EXPECT_NE(generated.find("TASSIGN(tiles_index__view_0, (uint64_t)tiles[index].data() + (5) * 2)"), | ||
| 726 | + std::string::npos); | ||
| 727 | + EXPECT_NE(generated.find("tiles_index__view_0.SetValidShape(4, 7)"), std::string::npos); | ||
| 728 | +} | ||
| 729 | + | ||
| 730 | +TEST(BackendCceOpsTest, BlockSubviewFallsBackToMemRefAddress) | ||
| 731 | +{ | ||
| 732 | + auto addr = MakeConstInt(0x180, ir::DataType::INDEX); | ||
| 733 | + auto memref = std::make_shared<const ir::MemRef>(ir::MemorySpace::Vec, addr, 1024, 0, ir::Span::Unknown()); | ||
| 734 | + auto tile_type = std::make_shared<const ir::TileType>(std::vector<int64_t>{8, 16}, ir::DataType::FP32, | ||
| 735 | + std::optional<ir::MemRefPtr>(memref), | ||
| 736 | + std::optional<ir::TileView>(std::nullopt)); | ||
| 737 | + auto tile = MakeVar("tile", tile_type); | ||
| 738 | + auto call = std::make_shared<const ir::Call>( | ||
| 739 | + "block.subview", std::vector<ir::ExprPtr>{tile, MakeConstInt(2), MakeTuple({MakeConstInt(3), MakeConstInt(5)})}, | ||
| 740 | + tile_type, ir::Span::Unknown()); | ||
| 741 | + auto* info = BackendCCE::Instance().GetOpInfo("block.subview"); | ||
| 742 | + ASSERT_NE(info, nullptr); | ||
| 743 | + | ||
| 744 | + TestableCCECodegen codegen; | ||
| 745 | + codegen.SetCurrentResultTarget("memref_view"); | ||
| 746 | + EXPECT_EQ(info->codegen_func(call, codegen), "memref_view"); | ||
| 747 | + EXPECT_NE(codegen.GetEmittedCode().find("TASSIGN(memref_view, 0x180 + (2) * 4)"), std::string::npos); | ||
| 748 | +} | ||
| 749 | + | ||
| 750 | +TEST(BackendCceOpsTest, BlockSubviewInVFSectionReturnsPointerArithmetic) | ||
| 751 | +{ | ||
| 752 | + auto tile = MakeVar("tile", MakeTileType({16, 32}, ir::DataType::FP16)); | ||
| 753 | + auto call = std::make_shared<const ir::Call>( | ||
| 754 | + "block.subview", std::vector<ir::ExprPtr>{tile, MakeConstInt(7), MakeTuple({MakeConstInt(8), MakeConstInt(8)})}, | ||
| 755 | + tile->GetType(), ir::Span::Unknown()); | ||
| 756 | + auto* info = BackendCCE::Instance().GetOpInfo("block.subview"); | ||
| 757 | + ASSERT_NE(info, nullptr); | ||
| 758 | + | ||
| 759 | + TestableCCECodegen codegen; | ||
| 760 | + codegen.SetCurrentSectionKind(ir::SectionKind::VF); | ||
| 761 | + EXPECT_EQ(info->codegen_func(call, codegen), "(vf_tile_ptr_0 + (7))"); | ||
| 762 | + EXPECT_TRUE(codegen.GetEmittedCode().empty()); | ||
| 763 | +} | ||
| 764 | + | ||
| 676 | // ============================================================================ | 765 | // ============================================================================ |
| 677 | // Sync all (HARD mode) | 766 | // Sync all (HARD mode) |
| 678 | // ============================================================================ | 767 | // ============================================================================ |
| @@ -921,7 +1010,7 @@ TEST(BackendCceOpsTest, DebugDumpTileFullAndWindow) | |||
| 921 | auto generated = RunCodegen("debug.dump_tile", window_call); | 1010 | auto generated = RunCodegen("debug.dump_tile", window_call); |
| 922 | EXPECT_NE(generated.find("[TPRINT Tile Window]"), std::string::npos); | 1011 | EXPECT_NE(generated.find("[TPRINT Tile Window]"), std::string::npos); |
| 923 | EXPECT_NE(generated.find("tile.GetValidRow() - (2)"), std::string::npos); | 1012 | EXPECT_NE(generated.find("tile.GetValidRow() - (2)"), std::string::npos); |
| 924 | - EXPECT_NE(generated.find("pto::GetTileOffset<decltype(tile)>"), std::string::npos); | 1013 | + EXPECT_NE(generated.find("pto::GetTileOffset<std::remove_reference_t<decltype(tile)>>"), std::string::npos); |
| 925 | EXPECT_NE(generated.find("pto::PrintValue<pto::PrintFormat::Width8_Precision4>"), std::string::npos); | 1014 | EXPECT_NE(generated.find("pto::PrintValue<pto::PrintFormat::Width8_Precision4>"), std::string::npos); |
| 926 | } | 1015 | } |
| 927 | 1016 | ||
| @@ -215,19 +215,6 @@ TEST(BackendCCEVFOpsTest, RegistersExpectedVectorFunctionOperations) | |||
| 215 | "vf.muls_cast", | 215 | "vf.muls_cast", |
| 216 | "vf.load", | 216 | "vf.load", |
| 217 | "vf.store", | 217 | "vf.store", |
| 218 | - "vf.mask_and", | ||
| 219 | - "vf.mask_or", | ||
| 220 | - "vf.mask_xor", | ||
| 221 | - "vf.mask_not", | ||
| 222 | - "vf.mask_mov", | ||
| 223 | - "vf.mask_sel", | ||
| 224 | - "vf.mask_pack", | ||
| 225 | - "vf.mask_unpack", | ||
| 226 | - "vf.mask_interleave", | ||
| 227 | - "vf.mask_deinterleave", | ||
| 228 | - "vf.mask_load", | ||
| 229 | - "vf.mask_store", | ||
| 230 | - "vf.mask_store_unalign", | ||
| 231 | "vf.create_addr_reg", | 218 | "vf.create_addr_reg", |
| 232 | "vf.move"}; | 219 | "vf.move"}; |
| 233 | 220 | ||
| @@ -443,7 +430,7 @@ TEST(BackendCCEVFOpsTest, EmitsCompareHistogramAndMaskConversions) | |||
| 443 | ExpectInvoke(codegen, "vf.ge", {"vcmp_ge("}, {mask, fp32, fp16, mask}); | 430 | ExpectInvoke(codegen, "vf.ge", {"vcmp_ge("}, {mask, fp32, fp16, mask}); |
| 444 | ExpectInvoke(codegen, "vf.squeeze", {"vsqz(", "MODE_NO_STORED"}, {i32, fp16, mask}, | 431 | ExpectInvoke(codegen, "vf.squeeze", {"vsqz(", "MODE_NO_STORED"}, {i32, fp16, mask}, |
| 445 | {{"gather_mode", EnumValue(ir::SqueezeMode::NO_STORE_REG)}}); | 432 | {{"gather_mode", EnumValue(ir::SqueezeMode::NO_STORE_REG)}}); |
| 446 | - ExpectInvoke(codegen, "vf.arange", {"DEC_ORDER"}, {i32, Int(3)}, | 433 | + ExpectInvoke(codegen, "vf.arange", {"vneg(", "vadds("}, {i32, Int(3)}, |
| 447 | {{"index_order", EnumValue(ir::IndexOrder::DECREASE_ORDER)}}); | 434 | {{"index_order", EnumValue(ir::IndexOrder::DECREASE_ORDER)}}); |
| 448 | ExpectInvoke(codegen, "vf.arange", {"vci(i64_b64_lo_"}, {i64, Int(5)}); | 435 | ExpectInvoke(codegen, "vf.arange", {"vci(i64_b64_lo_"}, {i64, Int(5)}); |
| 449 | ExpectInvoke(codegen, "vf.unsqueeze", {"vusqz("}, {i32, mask}); | 436 | ExpectInvoke(codegen, "vf.unsqueeze", {"vusqz("}, {i32, mask}); |
| @@ -538,18 +525,18 @@ TEST(BackendCCEVFOpsTest, EmitsMaskLogicOperations) | |||
| 538 | codegen.RegisterMaskRegVar("mask1"); | 525 | codegen.RegisterMaskRegVar("mask1"); |
| 539 | codegen.RegisterMaskRegVar("mask2"); | 526 | codegen.RegisterMaskRegVar("mask2"); |
| 540 | 527 | ||
| 541 | - ExpectInvoke(codegen, "vf.mask_and", {"pand("}, {mask0, mask1, mask2, mask0}); | 528 | + ExpectInvoke(codegen, "vf.and_", {"pand("}, {mask0, mask1, mask2, mask0}); |
| 542 | - ExpectInvoke(codegen, "vf.mask_or", {"por("}, {mask0, mask1, mask2, mask0}); | 529 | + ExpectInvoke(codegen, "vf.or_", {"por("}, {mask0, mask1, mask2, mask0}); |
| 543 | - ExpectInvoke(codegen, "vf.mask_xor", {"pxor("}, {mask0, mask1, mask2, mask0}); | 530 | + ExpectInvoke(codegen, "vf.xor", {"pxor("}, {mask0, mask1, mask2, mask0}); |
| 544 | - ExpectInvoke(codegen, "vf.mask_not", {"pnot("}, {mask0, mask1, mask2}); | 531 | + ExpectInvoke(codegen, "vf.not_", {"pnot("}, {mask0, mask1, mask2}); |
| 545 | - ExpectInvoke(codegen, "vf.mask_mov", {"pmov("}, {mask0, mask1, mask2}); | 532 | + ExpectInvoke(codegen, "vf.move", {"pmov("}, {mask0, mask1, mask2}); |
| 546 | - ExpectInvoke(codegen, "vf.mask_sel", {"psel("}, {mask0, mask1, mask2, mask0}); | 533 | + ExpectInvoke(codegen, "vf.select", {"psel("}, {mask0, mask1, mask2, mask0}); |
| 547 | - ExpectInvoke(codegen, "vf.mask_pack", {"ppack(mask0, mask1, HIGHER)"}, {mask0, mask1}, | 534 | + ExpectInvoke(codegen, "vf.pack", {"ppack(mask0, mask1, HIGHER)"}, {mask0, mask1}, |
| 548 | - {{"half", EnumValue(ir::PackPart::UPPER)}}); | 535 | + {{"part", EnumValue(ir::PackPart::UPPER)}}); |
| 549 | - ExpectInvoke(codegen, "vf.mask_unpack", {"punpack(mask0, mask1, LOWER)"}, {mask0, mask1}); | 536 | + ExpectInvoke(codegen, "vf.unpack", {"punpack(mask0, mask1, LOWER)"}, {mask0, mask1}); |
| 550 | - ExpectInvoke(codegen, "vf.mask_interleave", {"pintlv_b8("}, {mask0, mask1, mask1, mask2}, | 537 | + ExpectInvoke(codegen, "vf.interleave", {"pintlv_b8("}, {mask0, mask1, mask1, mask2}, |
| 551 | {{"dtype", ir::DataType::UINT8}}); | 538 | {{"dtype", ir::DataType::UINT8}}); |
| 552 | - ExpectInvoke(codegen, "vf.mask_deinterleave", {"pdintlv_b16("}, {mask0, mask1, mask1, mask2}, | 539 | + ExpectInvoke(codegen, "vf.de_interleave", {"pdintlv_b16("}, {mask0, mask1, mask1, mask2}, |
| 553 | {{"dtype", ir::DataType::FP16}}); | 540 | {{"dtype", ir::DataType::FP16}}); |
| 554 | } | 541 | } |
| 555 | 542 | ||
| @@ -561,17 +548,18 @@ TEST(BackendCCEVFOpsTest, EmitsMaskMemoryAndSpecialRegisterOperations) | |||
| 561 | auto mask0 = MakeVar("mask0", ir::DataType::UINT32); | 548 | auto mask0 = MakeVar("mask0", ir::DataType::UINT32); |
| 562 | auto mask1 = MakeVar("mask1", ir::DataType::UINT32); | 549 | auto mask1 = MakeVar("mask1", ir::DataType::UINT32); |
| 563 | auto addr = MakeVar("addr", ir::DataType::INT64); | 550 | auto addr = MakeVar("addr", ir::DataType::INT64); |
| 551 | + auto ureg = MakeVar("ureg", ir::DataType::UINT32); | ||
| 564 | codegen.RegisterMaskRegVar("mask0"); | 552 | codegen.RegisterMaskRegVar("mask0"); |
| 565 | codegen.RegisterMaskRegVar("mask1"); | 553 | codegen.RegisterMaskRegVar("mask1"); |
| 566 | codegen.RegisterAddrRegVar("addr"); | 554 | codegen.RegisterAddrRegVar("addr"); |
| 567 | 555 | ||
| 568 | - ExpectInvoke(codegen, "vf.mask_load", {"MaskReg loaded_mask", "plds(loaded_mask"}, {tile}, | 556 | + ExpectInvoke(codegen, "vf.load_align", {"plds(mask0"}, {mask0, tile, Int(0)}, |
| 569 | - {{"mode", EnumValue(ir::MaskLoadDist::DS)}}, "loaded_mask"); | 557 | + {{"dist", EnumValue(ir::LoadDist::DS)}}); |
| 570 | - ExpectInvoke(codegen, "vf.mask_load", {"pld(loaded_addr_mask"}, {tile, addr}, {}, "loaded_addr_mask"); | 558 | + ExpectInvoke(codegen, "vf.load_align", {"pld(mask1"}, {mask1, tile, addr}); |
| 571 | - ExpectInvoke(codegen, "vf.mask_store", {"psts(mask0"}, {mask0, tile, mask1}, | 559 | + ExpectInvoke(codegen, "vf.store_align", {"psts(mask0"}, {tile, mask0, mask1}, |
| 572 | - {{"dist", EnumValue(ir::MaskStoreDist::NORM)}}); | 560 | + {{"dist", EnumValue(ir::StoreDist::NORM)}}); |
| 573 | - ExpectInvoke(codegen, "vf.mask_store", {"pst(mask0"}, {mask0, tile, mask1, addr}); | 561 | + ExpectInvoke(codegen, "vf.store_align", {"pst(mask0"}, {tile, mask0, addr}); |
| 574 | - ExpectInvoke(codegen, "vf.mask_store_unalign", {"pstu("}, {mask0, tile, mask1}); | 562 | + ExpectInvoke(codegen, "vf.store_unalign", {"pstu("}, {tile, mask0, ureg}); |
| 575 | ExpectInvoke(codegen, "vf.mask_gen_with_reg_tensor", {"movvp(generated_mask, (RegTensor<uint16_t> &)reg, 4)"}, | 563 | ExpectInvoke(codegen, "vf.mask_gen_with_reg_tensor", {"movvp(generated_mask, (RegTensor<uint16_t> &)reg, 4)"}, |
| 576 | {reg}, {{"offset", 4}}, "generated_mask"); | 564 | {reg}, {{"offset", 4}}, "generated_mask"); |
| 577 | ExpectInvoke(codegen, "vf.get_mask_spr", {"movp_b16()"}, {}, {{"width", EnumValue(ir::MaskWidth::B16)}}, | 565 | ExpectInvoke(codegen, "vf.get_mask_spr", {"movp_b16()"}, {}, {{"width", EnumValue(ir::MaskWidth::B16)}}, |
| @@ -18,6 +18,7 @@ | |||
| 18 | #include <vector> | 18 | #include <vector> |
| 19 | 19 | ||
| 20 | #include "codegen/cce/cce_codegen.h" | 20 | #include "codegen/cce/cce_codegen.h" |
| 21 | +#include "ir/debug_info.h" | ||
| 21 | #include "ir/function.h" | 22 | #include "ir/function.h" |
| 22 | #include "ir/program.h" | 23 | #include "ir/program.h" |
| 23 | #include "ir/stmt.h" | 24 | #include "ir/stmt.h" |
| @@ -26,6 +27,11 @@ namespace pypto { | |||
| 26 | namespace codegen { | 27 | namespace codegen { |
| 27 | namespace { | 28 | namespace { |
| 28 | 29 | ||
| 30 | +class TestableCCECodegen : public CCECodegen { | ||
| 31 | +public: | ||
| 32 | + void SetDebugInfo(const ir::IRDebugInfo* debug_info) { debug_info_ = debug_info; } | ||
| 33 | +}; | ||
| 34 | + | ||
| 29 | ir::ExprPtr MakeConstInt(int64_t value) | 35 | ir::ExprPtr MakeConstInt(int64_t value) |
| 30 | { | 36 | { |
| 31 | return std::make_shared<const ir::ConstInt>(value, ir::DataType::INT64, ir::Span::Unknown()); | 37 | return std::make_shared<const ir::ConstInt>(value, ir::DataType::INT64, ir::Span::Unknown()); |
| @@ -102,6 +108,11 @@ TEST(CCECodegenHeaderTest, CoversHeaderOnlyStateAccessors) | |||
| 102 | EXPECT_EQ(codegen.GetTileOffsetCounter(), 0); | 108 | EXPECT_EQ(codegen.GetTileOffsetCounter(), 0); |
| 103 | EXPECT_EQ(codegen.GetTileOffsetCounter(), 1); | 109 | EXPECT_EQ(codegen.GetTileOffsetCounter(), 1); |
| 104 | 110 | ||
| 111 | + EXPECT_FALSE(codegen.HasTileAddress("tile_0")); | ||
| 112 | + codegen.SetTileAddress("tile_0", "0x100"); | ||
| 113 | + EXPECT_TRUE(codegen.HasTileAddress("tile_0")); | ||
| 114 | + EXPECT_EQ(codegen.GetTileAddress("tile_0"), "0x100"); | ||
| 115 | + | ||
| 105 | codegen.RecordStructVarType("ctx", "ContextType"); | 116 | codegen.RecordStructVarType("ctx", "ContextType"); |
| 106 | EXPECT_EQ(codegen.GetTensorDef("not_prescanned"), nullptr); | 117 | EXPECT_EQ(codegen.GetTensorDef("not_prescanned"), nullptr); |
| 107 | } | 118 | } |
| @@ -263,6 +274,137 @@ TEST(CCECodegenTest, UsesOneBackingArrayForDynamicAndStaticTupleReads) | |||
| 263 | EXPECT_NE(generated.find("[0]"), std::string::npos); | 274 | EXPECT_NE(generated.find("[0]"), std::string::npos); |
| 264 | } | 275 | } |
| 265 | 276 | ||
| 277 | +TEST(CCECodegenTest, SharesBackingArrayAcrossTupleAliases) | ||
| 278 | +{ | ||
| 279 | + auto scalar_type = std::make_shared<const ir::ScalarType>(ir::DataType::INT64); | ||
| 280 | + auto index = MakeVar("index", scalar_type); | ||
| 281 | + auto values = std::make_shared<const ir::MakeTuple>(std::vector<ir::ExprPtr>{MakeConstInt(11), MakeConstInt(22)}, | ||
| 282 | + ir::Span::Unknown()); | ||
| 283 | + auto first = MakeVar("first", values->GetType()); | ||
| 284 | + auto second = MakeVar("second", values->GetType()); | ||
| 285 | + auto selected = MakeVar("selected", scalar_type); | ||
| 286 | + | ||
| 287 | + auto first_assign = std::make_shared<const ir::AssignStmt>(first, values, ir::Span::Unknown()); | ||
| 288 | + auto second_assign = std::make_shared<const ir::AssignStmt>(second, first, ir::Span::Unknown()); | ||
| 289 | + auto read = std::make_shared<const ir::AssignStmt>( | ||
| 290 | + selected, std::make_shared<const ir::GetItemExpr>(second, index, ir::Span::Unknown()), ir::Span::Unknown()); | ||
| 291 | + auto body = std::make_shared<const ir::SeqStmts>(std::vector<ir::StmtPtr>{first_assign, second_assign, read}, | ||
| 292 | + ir::Span::Unknown()); | ||
| 293 | + | ||
| 294 | + CCECodegen codegen; | ||
| 295 | + auto generated = codegen.GenerateSingle(MakeProgram(body, {index}), "a5"); | ||
| 296 | + | ||
| 297 | + EXPECT_EQ(CountOccurrences(generated, "const int64_t first"), 1); | ||
| 298 | + EXPECT_EQ(generated.find("const int64_t second"), std::string::npos); | ||
| 299 | + EXPECT_NE(generated.find("first"), std::string::npos); | ||
| 300 | + EXPECT_NE(generated.find("[index"), std::string::npos); | ||
| 301 | +} | ||
| 302 | + | ||
| 303 | +TEST(CCECodegenTest, ClearsTupleBackingArraysBetweenGenerations) | ||
| 304 | +{ | ||
| 305 | + auto scalar_type = std::make_shared<const ir::ScalarType>(ir::DataType::INT64); | ||
| 306 | + auto index = MakeVar("index", scalar_type); | ||
| 307 | + auto values = std::make_shared<const ir::MakeTuple>(std::vector<ir::ExprPtr>{MakeConstInt(1), MakeConstInt(2)}, | ||
| 308 | + ir::Span::Unknown()); | ||
| 309 | + auto tuple_var = MakeVar("values", values->GetType()); | ||
| 310 | + auto selected = MakeVar("selected", scalar_type); | ||
| 311 | + auto tuple_assign = std::make_shared<const ir::AssignStmt>(tuple_var, values, ir::Span::Unknown()); | ||
| 312 | + auto read = std::make_shared<const ir::AssignStmt>( | ||
| 313 | + selected, std::make_shared<const ir::GetItemExpr>(tuple_var, index, ir::Span::Unknown()), ir::Span::Unknown()); | ||
| 314 | + auto body = std::make_shared<const ir::SeqStmts>(std::vector<ir::StmtPtr>{tuple_assign, read}, ir::Span::Unknown()); | ||
| 315 | + auto program = MakeProgram(body, {index}); | ||
| 316 | + | ||
| 317 | + CCECodegen codegen; | ||
| 318 | + auto first = codegen.GenerateSingle(program, "a5"); | ||
| 319 | + auto second = codegen.GenerateSingle(program, "a5"); | ||
| 320 | + | ||
| 321 | + EXPECT_NE(first.find("const int64_t values"), std::string::npos); | ||
| 322 | + EXPECT_NE(second.find("const int64_t values"), std::string::npos); | ||
| 323 | +} | ||
| 324 | + | ||
| 325 | +TEST(CCECodegenTest, MaterializesHomogeneousTileTuple) | ||
| 326 | +{ | ||
| 327 | + auto index_type = std::make_shared<const ir::ScalarType>(ir::DataType::INT64); | ||
| 328 | + auto index = MakeVar("index", index_type); | ||
| 329 | + auto tile_type = std::make_shared<const ir::TileType>(std::vector<int64_t>{16, 16}, ir::DataType::FP16, | ||
| 330 | + std::optional<ir::MemRefPtr>(std::nullopt), | ||
| 331 | + std::optional<ir::TileView>(std::nullopt)); | ||
| 332 | + auto tile0 = MakeVar("tile0", tile_type); | ||
| 333 | + auto tile1 = MakeVar("tile1", tile_type); | ||
| 334 | + auto make_tile0 = std::make_shared<const ir::Call>("block.make_tile", std::vector<ir::ExprPtr>{}, tile_type, | ||
| 335 | + ir::Span::Unknown()); | ||
| 336 | + auto make_tile1 = std::make_shared<const ir::Call>("block.make_tile", std::vector<ir::ExprPtr>{}, tile_type, | ||
| 337 | + ir::Span::Unknown()); | ||
| 338 | + auto values = std::make_shared<const ir::MakeTuple>(std::vector<ir::ExprPtr>{tile0, tile1}, ir::Span::Unknown()); | ||
| 339 | + auto tiles = MakeVar("tiles", values->GetType()); | ||
| 340 | + auto selected = MakeVar("selected", tile_type); | ||
| 341 | + | ||
| 342 | + auto body = std::make_shared<const ir::SeqStmts>( | ||
| 343 | + std::vector<ir::StmtPtr>{ | ||
| 344 | + std::make_shared<const ir::AssignStmt>(tile0, make_tile0, ir::Span::Unknown()), | ||
| 345 | + std::make_shared<const ir::AssignStmt>(tile1, make_tile1, ir::Span::Unknown()), | ||
| 346 | + std::make_shared<const ir::AssignStmt>(tiles, values, ir::Span::Unknown()), | ||
| 347 | + std::make_shared<const ir::AssignStmt>( | ||
| 348 | + selected, std::make_shared<const ir::GetItemExpr>(tiles, index, ir::Span::Unknown()), | ||
| 349 | + ir::Span::Unknown()), | ||
| 350 | + }, | ||
| 351 | + ir::Span::Unknown()); | ||
| 352 | + | ||
| 353 | + CCECodegen codegen; | ||
| 354 | + auto generated = codegen.GenerateSingle(MakeProgram(body, {index}), "a5"); | ||
| 355 | + | ||
| 356 | + EXPECT_NE(generated.find("tiles"), std::string::npos); | ||
| 357 | + EXPECT_NE(generated.find("[] = {tile0"), std::string::npos); | ||
| 358 | +} | ||
| 359 | + | ||
| 360 | +TEST(CCECodegenTest, HandlesStaticTupleGetItemWithoutBackingArray) | ||
| 361 | +{ | ||
| 362 | + auto tuple = std::make_shared<const ir::MakeTuple>(std::vector<ir::ExprPtr>{MakeConstInt(11), MakeConstInt(22)}, | ||
| 363 | + ir::Span::Unknown()); | ||
| 364 | + CCECodegen codegen; | ||
| 365 | + | ||
| 366 | + auto item = std::make_shared<const ir::GetItemExpr>(tuple, MakeConstInt(1), ir::Span::Unknown()); | ||
| 367 | + EXPECT_EQ(codegen.GetExprAsCode(item), "22"); | ||
| 368 | +} | ||
| 369 | + | ||
| 370 | +TEST(CCECodegenTest, EmitsArrayAccessForUnmaterializedTupleVar) | ||
| 371 | +{ | ||
| 372 | + auto scalar_type = std::make_shared<const ir::ScalarType>(ir::DataType::INT64); | ||
| 373 | + auto tuple_type = std::make_shared<const ir::TupleType>( | ||
| 374 | + std::vector<ir::TypePtr>{scalar_type, scalar_type, scalar_type}); | ||
| 375 | + auto tuple_var = MakeVar("values", tuple_type); | ||
| 376 | + auto item = std::make_shared<const ir::GetItemExpr>(tuple_var, MakeConstInt(1), ir::Span::Unknown()); | ||
| 377 | + | ||
| 378 | + CCECodegen codegen; | ||
| 379 | + EXPECT_EQ(codegen.GetExprAsCode(item), "values[1]"); | ||
| 380 | +} | ||
| 381 | + | ||
| 382 | +TEST(CCECodegenTest, EmitsFieldAccessForUnmaterializedNamedTupleVar) | ||
| 383 | +{ | ||
| 384 | + auto scalar_type = std::make_shared<const ir::ScalarType>(ir::DataType::INT64); | ||
| 385 | + auto tuple_type = std::make_shared<const ir::TupleType>(std::vector<ir::TypePtr>{scalar_type, scalar_type}); | ||
| 386 | + auto tuple_var = MakeVar("config", tuple_type); | ||
| 387 | + auto item = std::make_shared<const ir::GetItemExpr>(tuple_var, MakeConstInt(1), ir::Span::Unknown()); | ||
| 388 | + ir::IRDebugInfo debug_info; | ||
| 389 | + debug_info.RegisterTupleFields(tuple_type, {"rows", "cols"}); | ||
| 390 | + | ||
| 391 | + TestableCCECodegen codegen; | ||
| 392 | + codegen.SetDebugInfo(&debug_info); | ||
| 393 | + EXPECT_EQ(codegen.GetExprAsCode(item), "config.cols"); | ||
| 394 | +} | ||
| 395 | + | ||
| 396 | +TEST(CCECodegenTest, RejectsDynamicTupleWithoutBackingArray) | ||
| 397 | +{ | ||
| 398 | + auto scalar_type = std::make_shared<const ir::ScalarType>(ir::DataType::INT64); | ||
| 399 | + auto index = MakeVar("index", scalar_type); | ||
| 400 | + auto tuple = std::make_shared<const ir::MakeTuple>(std::vector<ir::ExprPtr>{MakeConstInt(1), MakeConstInt(2)}, | ||
| 401 | + ir::Span::Unknown()); | ||
| 402 | + auto unowned = std::make_shared<const ir::GetItemExpr>(tuple, index, ir::Span::Unknown()); | ||
| 403 | + | ||
| 404 | + CCECodegen codegen; | ||
| 405 | + EXPECT_THROW((void)codegen.GetExprAsCode(unowned), std::exception); | ||
| 406 | +} | ||
| 407 | + | ||
| 266 | TEST(CCECodegenTest, DropsUnusedIfPhiAndYieldOnlyElse) | 408 | TEST(CCECodegenTest, DropsUnusedIfPhiAndYieldOnlyElse) |
| 267 | { | 409 | { |
| 268 | auto bool_type = std::make_shared<const ir::ScalarType>(ir::DataType::BOOL); | 410 | auto bool_type = std::make_shared<const ir::ScalarType>(ir::DataType::BOOL); |
| @@ -53,6 +53,7 @@ __all__ = [ | |||
| 53 | "MergeMode", | 53 | "MergeMode", |
| 54 | "ReduceMode", | 54 | "ReduceMode", |
| 55 | "CompareMode", | 55 | "CompareMode", |
| 56 | + "CmpMode", | ||
| 56 | "DuplicatePos", | 57 | "DuplicatePos", |
| 57 | "CastLayout", | 58 | "CastLayout", |
| 58 | "VFRoundMode", | 59 | "VFRoundMode", |
| @@ -67,8 +68,6 @@ __all__ = [ | |||
| 67 | "DataCopyMode", | 68 | "DataCopyMode", |
| 68 | "IndexOrder", | 69 | "IndexOrder", |
| 69 | "MemBarMode", | 70 | "MemBarMode", |
| 70 | - "MaskLoadDist", | ||
| 71 | - "MaskStoreDist", | ||
| 72 | "ConstInt", | 71 | "ConstInt", |
| 73 | 72 | ||
| 74 | "ConstFloat", | 73 | "ConstFloat", |
| @@ -165,6 +164,7 @@ from ..pypto_impl.ir import ( | |||
| 165 | MergeMode, | 164 | MergeMode, |
| 166 | ReduceMode, | 165 | ReduceMode, |
| 167 | CompareMode, | 166 | CompareMode, |
| 167 | + CmpMode, | ||
| 168 | DuplicatePos, | 168 | DuplicatePos, |
| 169 | CastLayout, | 169 | CastLayout, |
| 170 | VFRoundMode, | 170 | VFRoundMode, |
| @@ -179,8 +179,6 @@ from ..pypto_impl.ir import ( | |||
| 179 | DataCopyMode, | 179 | DataCopyMode, |
| 180 | IndexOrder, | 180 | IndexOrder, |
| 181 | MemBarMode, | 181 | MemBarMode, |
| 182 | - MaskLoadDist, | ||
| 183 | - MaskStoreDist, | ||
| 184 | ) | 182 | ) |
| 185 | 183 | ||
| 186 | from ..pypto_impl.ir import IRBuilder, InsertPoint | 184 | from ..pypto_impl.ir import IRBuilder, InsertPoint |
| @@ -17,6 +17,7 @@ in ``call_parser.parse_op_call``. | |||
| 17 | from __future__ import annotations | 17 | from __future__ import annotations |
| 18 | 18 | ||
| 19 | import ast | 19 | import ast |
| 20 | +import enum | ||
| 20 | import os | 21 | import os |
| 21 | from collections.abc import Sequence | 22 | from collections.abc import Sequence |
| 22 | from dataclasses import dataclass | 23 | from dataclasses import dataclass |
| @@ -28,6 +29,7 @@ from pypto.pypto_impl.ir import ( | |||
| 28 | AccPhase, | 29 | AccPhase, |
| 29 | AccToVecMode, | 30 | AccToVecMode, |
| 30 | AtomicType, | 31 | AtomicType, |
| 32 | + CmpMode, | ||
| 31 | ConstInt, | 33 | ConstInt, |
| 32 | DataType, | 34 | DataType, |
| 33 | Expr, | 35 | Expr, |
| @@ -58,6 +60,13 @@ def block_ir_op(op_name: str) -> str: | |||
| 58 | return f"{_BLOCK_OP_NAMESPACE}.{op_name}" | 60 | return f"{_BLOCK_OP_NAMESPACE}.{op_name}" |
| 59 | 61 | ||
| 60 | 62 | ||
| 63 | +class FillPadMode(enum.Enum): | ||
| 64 | + """Fill-pad operating mode (lowered to different IR op names).""" | ||
| 65 | + NORMAL = 0 | ||
| 66 | + EXPAND = 1 | ||
| 67 | + INPLACE = 2 | ||
| 68 | + | ||
| 69 | + | ||
| 61 | def _compute_absolute_offsets( | 70 | def _compute_absolute_offsets( |
| 62 | tile_offsets: _ir_core.MakeTuple, | 71 | tile_offsets: _ir_core.MakeTuple, |
| 63 | tile_shape: list, | 72 | tile_shape: list, |
| @@ -133,17 +142,19 @@ def _ir_load( | |||
| 133 | offsets: Sequence[int | Expr] | _ir_core.MakeTuple, | 142 | offsets: Sequence[int | Expr] | _ir_core.MakeTuple, |
| 134 | *, | 143 | *, |
| 135 | span: Span | None = None, | 144 | span: Span | None = None, |
| 136 | - is_transpose: bool = False, | 145 | + order: list[int] | None = None, |
| 137 | - tile_dims: list[int] | None = None, | ||
| 138 | ) -> Expr: | 146 | ) -> Expr: |
| 139 | op_name = "load" | 147 | op_name = "load" |
| 140 | actual_span = span or _span() | 148 | actual_span = span or _span() |
| 141 | offsets_tuple = _to_make_tuple(offsets, actual_span) | 149 | offsets_tuple = _to_make_tuple(offsets, actual_span) |
| 142 | 150 | ||
| 151 | + tensor_ndim = len(tensor.type.shape) | ||
| 152 | + tile_ndim = len(out.type.shape) | ||
| 153 | + tile_dims, is_transpose = _resolve_order(order, tensor_ndim, tile_ndim, op_name) | ||
| 154 | + | ||
| 143 | tensor_ndim, tile_shape, tile_dims = _validate_load_operands( | 155 | tensor_ndim, tile_shape, tile_dims = _validate_load_operands( |
| 144 | out, tensor, offsets_tuple, tile_dims, op_name | 156 | out, tensor, offsets_tuple, tile_dims, op_name |
| 145 | ) | 157 | ) |
| 146 | - tile_ndim = len(tile_shape) | ||
| 147 | 158 | ||
| 148 | kwargs: dict[str, Any] = {} | 159 | kwargs: dict[str, Any] = {} |
| 149 | if is_transpose: | 160 | if is_transpose: |
| @@ -164,13 +175,16 @@ def _ir_load_tile( | |||
| 164 | tile_offsets: Sequence[int | Expr] | _ir_core.MakeTuple, | 175 | tile_offsets: Sequence[int | Expr] | _ir_core.MakeTuple, |
| 165 | *, | 176 | *, |
| 166 | span: Span | None = None, | 177 | span: Span | None = None, |
| 167 | - is_transpose: bool = False, | 178 | + order: list[int] | None = None, |
| 168 | - tile_dims: list[int] | None = None, | ||
| 169 | ) -> Expr: | 179 | ) -> Expr: |
| 170 | op_name = "load_tile" | 180 | op_name = "load_tile" |
| 171 | actual_span = span or _span() | 181 | actual_span = span or _span() |
| 172 | offsets_tuple = _to_make_tuple(tile_offsets, actual_span) | 182 | offsets_tuple = _to_make_tuple(tile_offsets, actual_span) |
| 173 | 183 | ||
| 184 | + tensor_ndim = len(tensor.type.shape) | ||
| 185 | + tile_ndim = len(out.type.shape) | ||
| 186 | + tile_dims, is_transpose = _resolve_order(order, tensor_ndim, tile_ndim, op_name) | ||
| 187 | + | ||
| 174 | tensor_ndim, tile_shape, tile_dims = _validate_load_operands( | 188 | tensor_ndim, tile_shape, tile_dims = _validate_load_operands( |
| 175 | out, | 189 | out, |
| 176 | tensor, | 190 | tensor, |
| @@ -179,7 +193,6 @@ def _ir_load_tile( | |||
| 179 | op_name, | 193 | op_name, |
| 180 | use_tile_absolute=True, | 194 | use_tile_absolute=True, |
| 181 | ) | 195 | ) |
| 182 | - tile_ndim = len(tile_shape) | ||
| 183 | 196 | ||
| 184 | abs_offsets = _compute_absolute_offsets(offsets_tuple, tile_shape, tile_dims, actual_span) | 197 | abs_offsets = _compute_absolute_offsets(offsets_tuple, tile_shape, tile_dims, actual_span) |
| 185 | # Validate offset bounds at Python frontend level | 198 | # Validate offset bounds at Python frontend level |
| @@ -704,6 +717,26 @@ def _validate_dtype(dtype: DataType | None, role: str, op_name: str) -> None: | |||
| 704 | ) | 717 | ) |
| 705 | 718 | ||
| 706 | 719 | ||
| 720 | +def _resolve_order( | ||
| 721 | + order: list[int] | None, | ||
| 722 | + tensor_ndim: int, | ||
| 723 | + tile_ndim: int, | ||
| 724 | + op_name: str, | ||
| 725 | +) -> tuple[list[int], bool]: | ||
| 726 | + """Resolve the ``order`` kwarg into ``(tile_dims, is_transpose)``. | ||
| 727 | + | ||
| 728 | + ``order`` maps each Tile dimension to a Tensor axis (absolute index). | ||
| 729 | + Ascending order means no transposition; descending order means transposition | ||
| 730 | + (DN layout). Internally we decompose into ``tile_dims`` (sorted ascending, | ||
| 731 | + consumed by C++ codegen) and ``is_transpose`` (bool, consumed by codegen). | ||
| 732 | + """ | ||
| 733 | + if order is None: | ||
| 734 | + order = list(range(tensor_ndim - tile_ndim, tensor_ndim)) | ||
| 735 | + is_transpose = len(order) >= 2 and order[0] > order[1] | ||
| 736 | + tile_dims = sorted(order) | ||
| 737 | + return tile_dims, is_transpose | ||
| 738 | + | ||
| 739 | + | ||
| 707 | def _validate_tile_dims( | 740 | def _validate_tile_dims( |
| 708 | tile_dims: list[int] | None, | 741 | tile_dims: list[int] | None, |
| 709 | tensor_ndim: int, | 742 | tensor_ndim: int, |
| @@ -808,6 +841,26 @@ def _ir_cast( | |||
| 808 | ) | 841 | ) |
| 809 | 842 | ||
| 810 | 843 | ||
| 844 | +def _ir_fillpad( | ||
| 845 | + out: Expr, | ||
| 846 | + src: Expr, | ||
| 847 | + *, | ||
| 848 | + span: Span | None = None, | ||
| 849 | + mode: FillPadMode = FillPadMode.NORMAL, | ||
| 850 | +) -> Expr: | ||
| 851 | + name = { | ||
| 852 | + FillPadMode.NORMAL: "fillpad", | ||
| 853 | + FillPadMode.EXPAND: "fillpad_expand", | ||
| 854 | + FillPadMode.INPLACE: "fillpad_inplace", | ||
| 855 | + }[mode] | ||
| 856 | + return _ir_core.create_op_call( | ||
| 857 | + block_ir_op(name), | ||
| 858 | + [out, src], | ||
| 859 | + {}, | ||
| 860 | + span or _span(), | ||
| 861 | + ) | ||
| 862 | + | ||
| 863 | + | ||
| 811 | def _ir_add_relu_cast( | 864 | def _ir_add_relu_cast( |
| 812 | out: Expr, | 865 | out: Expr, |
| 813 | lhs: Expr, | 866 | lhs: Expr, |
| @@ -844,20 +897,20 @@ def _ir_mul_cast( | |||
| 844 | return _ir_binary_cast("mul_cast", out, lhs, rhs, target_type, span=span, mode=mode) | 897 | return _ir_binary_cast("mul_cast", out, lhs, rhs, target_type, span=span, mode=mode) |
| 845 | 898 | ||
| 846 | 899 | ||
| 847 | -def _ir_cmp(out: Expr, lhs: Expr, rhs: Expr, *, span: Span | None = None, cmp_type: int | Expr = 0) -> Expr: | 900 | +def _ir_cmp(out: Expr, lhs: Expr, rhs: Expr, *, span: Span | None = None, cmp_mode: int | Expr = 0) -> Expr: |
| 848 | return _ir_core.create_op_call( | 901 | return _ir_core.create_op_call( |
| 849 | block_ir_op("cmp"), | 902 | block_ir_op("cmp"), |
| 850 | [out, lhs, rhs], | 903 | [out, lhs, rhs], |
| 851 | - {"cmp_type": _const_int_attr(cmp_type, "cmp_type")}, | 904 | + {"cmp_mode": _const_int_attr(cmp_mode, "cmp_mode")}, |
| 852 | span or _span(), | 905 | span or _span(), |
| 853 | ) | 906 | ) |
| 854 | 907 | ||
| 855 | 908 | ||
| 856 | -def _ir_cmps(out: Expr, lhs: Expr, rhs: Expr, *, span: Span | None = None, cmp_type: int | Expr = 0) -> Expr: | 909 | +def _ir_cmps(out: Expr, lhs: Expr, rhs: Expr, *, span: Span | None = None, cmp_mode: int | Expr = 0) -> Expr: |
| 857 | return _ir_core.create_op_call( | 910 | return _ir_core.create_op_call( |
| 858 | block_ir_op("cmps"), | 911 | block_ir_op("cmps"), |
| 859 | [out, lhs, rhs], | 912 | [out, lhs, rhs], |
| 860 | - {"cmp_type": _const_int_attr(cmp_type, "cmp_type")}, | 913 | + {"cmp_mode": _const_int_attr(cmp_mode, "cmp_mode")}, |
| 861 | span or _span(), | 914 | span or _span(), |
| 862 | ) | 915 | ) |
| 863 | 916 | ||
| @@ -1156,22 +1209,16 @@ def _parse_make_tile(self, call: ast.Call) -> Expr: | |||
| 1156 | return make_tile(*args, **kwargs, span=span) | 1209 | return make_tile(*args, **kwargs, span=span) |
| 1157 | 1210 | ||
| 1158 | 1211 | ||
| 1159 | -# tile_dims selects tensor axes at compile time (it drives the tensor-view strides in codegen), | ||
| 1160 | -# so it must be a compile-time constant int list. Resolve it via the strict validator, which also | ||
| 1161 | -# folds a constant list threaded through an implicit-helper parameter (e.g. tile_dims=tile_dims). | ||
| 1162 | def _resolve_tile_dims_kwarg(self, call: ast.Call, kwargs: dict) -> None: | 1212 | def _resolve_tile_dims_kwarg(self, call: ast.Call, kwargs: dict) -> None: |
| 1163 | tile_dims = self.resolve_const_int_list_kwarg(call, "tile_dims") | 1213 | tile_dims = self.resolve_const_int_list_kwarg(call, "tile_dims") |
| 1164 | if tile_dims is not None: | 1214 | if tile_dims is not None: |
| 1165 | kwargs["tile_dims"] = tile_dims | 1215 | kwargs["tile_dims"] = tile_dims |
| 1166 | 1216 | ||
| 1167 | 1217 | ||
| 1168 | -# is_transpose is a compile-time codegen attribute (consumed via GetKwarg<bool>), so it must | 1218 | +def _resolve_order_kwarg(self, call: ast.Call, kwargs: dict) -> None: |
| 1169 | -# be a compile-time constant bool. Resolve it via the strict validator, which also folds a | 1219 | + order = self.resolve_const_int_list_kwarg(call, "order") |
| 1170 | -# constant bool threaded through an implicit-helper parameter (e.g. is_transpose=flag). | 1220 | + if order is not None: |
| 1171 | -def _resolve_is_transpose_kwarg(self, call: ast.Call, kwargs: dict) -> None: | 1221 | + kwargs["order"] = order |
| 1172 | - is_transpose = self.resolve_const_bool_kwarg(call, "is_transpose") | ||
| 1173 | - if is_transpose is not None: | ||
| 1174 | - kwargs["is_transpose"] = is_transpose | ||
| 1175 | 1222 | ||
| 1176 | 1223 | ||
| 1177 | # --------------------------------------------------------------------------- | 1224 | # --------------------------------------------------------------------------- |
| @@ -1204,43 +1251,40 @@ def _ir_select(out: Expr, mask: Expr, lhs: Expr, rhs: Expr, tmp: Expr, *, span: | |||
| 1204 | return _ir_sels(out, mask, lhs, tmp, rhs, span=span) | 1251 | return _ir_sels(out, mask, lhs, tmp, rhs, span=span) |
| 1205 | 1252 | ||
| 1206 | 1253 | ||
| 1207 | -_CMP_EQ, _CMP_NE, _CMP_LT, _CMP_LE, _CMP_GT, _CMP_GE = 0, 1, 2, 3, 4, 5 | ||
| 1208 | - | ||
| 1209 | - | ||
| 1210 | def _ir_eq(out: Expr, lhs: Expr, rhs: Expr, *, span: Span | None = None) -> Expr: | 1254 | def _ir_eq(out: Expr, lhs: Expr, rhs: Expr, *, span: Span | None = None) -> Expr: |
| 1211 | if isinstance(getattr(rhs, "type", None), _ir_core.TileType): | 1255 | if isinstance(getattr(rhs, "type", None), _ir_core.TileType): |
| 1212 | - return _ir_cmp(out, lhs, rhs, span=span, cmp_type=_CMP_EQ) | 1256 | + return _ir_cmp(out, lhs, rhs, span=span, cmp_mode=CmpMode.EQ.value) |
| 1213 | - return _ir_cmps(out, lhs, rhs, span=span, cmp_type=_CMP_EQ) | 1257 | + return _ir_cmps(out, lhs, rhs, span=span, cmp_mode=CmpMode.EQ.value) |
| 1214 | 1258 | ||
| 1215 | 1259 | ||
| 1216 | def _ir_ne(out: Expr, lhs: Expr, rhs: Expr, *, span: Span | None = None) -> Expr: | 1260 | def _ir_ne(out: Expr, lhs: Expr, rhs: Expr, *, span: Span | None = None) -> Expr: |
| 1217 | if isinstance(getattr(rhs, "type", None), _ir_core.TileType): | 1261 | if isinstance(getattr(rhs, "type", None), _ir_core.TileType): |
| 1218 | - return _ir_cmp(out, lhs, rhs, span=span, cmp_type=_CMP_NE) | 1262 | + return _ir_cmp(out, lhs, rhs, span=span, cmp_mode=CmpMode.NE.value) |
| 1219 | - return _ir_cmps(out, lhs, rhs, span=span, cmp_type=_CMP_NE) | 1263 | + return _ir_cmps(out, lhs, rhs, span=span, cmp_mode=CmpMode.NE.value) |
| 1220 | 1264 | ||
| 1221 | 1265 | ||
| 1222 | def _ir_lt(out: Expr, lhs: Expr, rhs: Expr, *, span: Span | None = None) -> Expr: | 1266 | def _ir_lt(out: Expr, lhs: Expr, rhs: Expr, *, span: Span | None = None) -> Expr: |
| 1223 | if isinstance(getattr(rhs, "type", None), _ir_core.TileType): | 1267 | if isinstance(getattr(rhs, "type", None), _ir_core.TileType): |
| 1224 | - return _ir_cmp(out, lhs, rhs, span=span, cmp_type=_CMP_LT) | 1268 | + return _ir_cmp(out, lhs, rhs, span=span, cmp_mode=CmpMode.LT.value) |
| 1225 | - return _ir_cmps(out, lhs, rhs, span=span, cmp_type=_CMP_LT) | 1269 | + return _ir_cmps(out, lhs, rhs, span=span, cmp_mode=CmpMode.LT.value) |
| 1226 | 1270 | ||
| 1227 | 1271 | ||
| 1228 | def _ir_le(out: Expr, lhs: Expr, rhs: Expr, *, span: Span | None = None) -> Expr: | 1272 | def _ir_le(out: Expr, lhs: Expr, rhs: Expr, *, span: Span | None = None) -> Expr: |
| 1229 | if isinstance(getattr(rhs, "type", None), _ir_core.TileType): | 1273 | if isinstance(getattr(rhs, "type", None), _ir_core.TileType): |
| 1230 | - return _ir_cmp(out, lhs, rhs, span=span, cmp_type=_CMP_LE) | 1274 | + return _ir_cmp(out, lhs, rhs, span=span, cmp_mode=CmpMode.LE.value) |
| 1231 | - return _ir_cmps(out, lhs, rhs, span=span, cmp_type=_CMP_LE) | 1275 | + return _ir_cmps(out, lhs, rhs, span=span, cmp_mode=CmpMode.LE.value) |
| 1232 | 1276 | ||
| 1233 | 1277 | ||
| 1234 | def _ir_gt(out: Expr, lhs: Expr, rhs: Expr, *, span: Span | None = None) -> Expr: | 1278 | def _ir_gt(out: Expr, lhs: Expr, rhs: Expr, *, span: Span | None = None) -> Expr: |
| 1235 | if isinstance(getattr(rhs, "type", None), _ir_core.TileType): | 1279 | if isinstance(getattr(rhs, "type", None), _ir_core.TileType): |
| 1236 | - return _ir_cmp(out, lhs, rhs, span=span, cmp_type=_CMP_GT) | 1280 | + return _ir_cmp(out, lhs, rhs, span=span, cmp_mode=CmpMode.GT.value) |
| 1237 | - return _ir_cmps(out, lhs, rhs, span=span, cmp_type=_CMP_GT) | 1281 | + return _ir_cmps(out, lhs, rhs, span=span, cmp_mode=CmpMode.GT.value) |
| 1238 | 1282 | ||
| 1239 | 1283 | ||
| 1240 | def _ir_ge(out: Expr, lhs: Expr, rhs: Expr, *, span: Span | None = None) -> Expr: | 1284 | def _ir_ge(out: Expr, lhs: Expr, rhs: Expr, *, span: Span | None = None) -> Expr: |
| 1241 | if isinstance(getattr(rhs, "type", None), _ir_core.TileType): | 1285 | if isinstance(getattr(rhs, "type", None), _ir_core.TileType): |
| 1242 | - return _ir_cmp(out, lhs, rhs, span=span, cmp_type=_CMP_GE) | 1286 | + return _ir_cmp(out, lhs, rhs, span=span, cmp_mode=CmpMode.GE.value) |
| 1243 | - return _ir_cmps(out, lhs, rhs, span=span, cmp_type=_CMP_GE) | 1287 | + return _ir_cmps(out, lhs, rhs, span=span, cmp_mode=CmpMode.GE.value) |
| 1244 | 1288 | ||
| 1245 | 1289 | ||
| 1246 | def _ir_sum(out: Expr, src: Expr, tmp: Expr, *, span: Span | None = None, dim: int = 0) -> Expr: | 1290 | def _ir_sum(out: Expr, src: Expr, tmp: Expr, *, span: Span | None = None, dim: int = 0) -> Expr: |
| @@ -1284,6 +1328,7 @@ register_table({ | |||
| 1284 | "setval": OpSpec(builder=_ir_setval), | 1328 | "setval": OpSpec(builder=_ir_setval), |
| 1285 | "transpose": OpSpec(builder=_ir_transpose), | 1329 | "transpose": OpSpec(builder=_ir_transpose), |
| 1286 | "cast": OpSpec(builder=_ir_cast), | 1330 | "cast": OpSpec(builder=_ir_cast), |
| 1331 | + "fillpad": OpSpec(builder=_ir_fillpad), | ||
| 1287 | "add_relu_cast": OpSpec(builder=_ir_add_relu_cast), | 1332 | "add_relu_cast": OpSpec(builder=_ir_add_relu_cast), |
| 1288 | "sub_relu_cast": OpSpec(builder=_ir_sub_relu_cast), | 1333 | "sub_relu_cast": OpSpec(builder=_ir_sub_relu_cast), |
| 1289 | "mul_cast": OpSpec(builder=_ir_mul_cast), | 1334 | "mul_cast": OpSpec(builder=_ir_mul_cast), |
| @@ -1309,9 +1354,9 @@ register_table({ | |||
| 1309 | "expand_mul": OpSpec(builder=_ir_expand_mul), | 1354 | "expand_mul": OpSpec(builder=_ir_expand_mul), |
| 1310 | "expand_sub": OpSpec(builder=_ir_expand_sub), | 1355 | "expand_sub": OpSpec(builder=_ir_expand_sub), |
| 1311 | "expand_div": OpSpec(builder=_ir_expand_div), | 1356 | "expand_div": OpSpec(builder=_ir_expand_div), |
| 1312 | - # args + kwargs + tile_dims hook | 1357 | + # args + kwargs + order hook (load) / tile_dims hook (store) |
| 1313 | - "load": OpSpec(builder=_ir_load, pre_hooks=[_resolve_tile_dims_kwarg, _resolve_is_transpose_kwarg]), | 1358 | + "load": OpSpec(builder=_ir_load, pre_hooks=[_resolve_order_kwarg]), |
| 1314 | - "load_tile": OpSpec(builder=_ir_load_tile, pre_hooks=[_resolve_tile_dims_kwarg, _resolve_is_transpose_kwarg]), | 1359 | + "load_tile": OpSpec(builder=_ir_load_tile, pre_hooks=[_resolve_order_kwarg]), |
| 1315 | "store": OpSpec(builder=_ir_store, pre_hooks=[_resolve_tile_dims_kwarg]), | 1360 | "store": OpSpec(builder=_ir_store, pre_hooks=[_resolve_tile_dims_kwarg]), |
| 1316 | "store_tile": OpSpec(builder=_ir_store_tile, pre_hooks=[_resolve_tile_dims_kwarg]), | 1361 | "store_tile": OpSpec(builder=_ir_store_tile, pre_hooks=[_resolve_tile_dims_kwarg]), |
| 1317 | # kwargs only | 1362 | # kwargs only |
| @@ -1342,7 +1387,11 @@ def _parse_set_validshape(self, call: ast.Call) -> Expr: | |||
| 1342 | 1387 | ||
| 1343 | return ConstInt(0, DataType.INDEX, span) | 1388 | return ConstInt(0, DataType.INDEX, span) |
| 1344 | 1389 | ||
| 1345 | - return _ir_set_validshape(*args, **kwargs, span=span) | 1390 | + result = _ir_set_validshape(*args, **kwargs, span=span) |
| 1391 | + | ||
| 1392 | + if args and hasattr(self, 'record_tile_valid_shape') and len(args) >= 2: | ||
| 1393 | + self.record_tile_valid_shape(args[0], args[1]) | ||
| 1394 | + return result | ||
| 1346 | 1395 | ||
| 1347 | 1396 | ||
| 1348 | def _check_tile_memory_space(op_name: str, operand_name: str, expr: Expr, | 1397 | def _check_tile_memory_space(op_name: str, operand_name: str, expr: Expr, |
| @@ -88,7 +88,7 @@ __all__ = [ | |||
| 88 | "and_", "xor", "expands", | 88 | "and_", "xor", "expands", |
| 89 | # Unary element-wise | 89 | # Unary element-wise |
| 90 | "neg", "abs", "exp", "log", "sqrt", "rsqrt", "recip", "relu", | 90 | "neg", "abs", "exp", "log", "sqrt", "rsqrt", "recip", "relu", |
| 91 | - "fillpad", "fillpad_expand", "fillpad_inplace", | 91 | + "fillpad", "FillPadMode", |
| 92 | # Type conversion | 92 | # Type conversion |
| 93 | "cast", "add_relu_cast", "sub_relu_cast", "mul_cast", | 93 | "cast", "add_relu_cast", "sub_relu_cast", "mul_cast", |
| 94 | # Compare / select | 94 | # Compare / select |
| @@ -140,7 +140,7 @@ from pypto.pypto_impl.ir import ( | |||
| 140 | TilePad, | 140 | TilePad, |
| 141 | ) | 141 | ) |
| 142 | from pypto_pro.ir.op import system_ops as system | 142 | from pypto_pro.ir.op import system_ops as system |
| 143 | -from pypto_pro.ir.op.block_ops import TileType, make_tile | 143 | +from pypto_pro.ir.op.block_ops import TileType, make_tile, FillPadMode |
| 144 | from pypto.ir import ( | 144 | from pypto.ir import ( |
| 145 | ReluPreMode, | 145 | ReluPreMode, |
| 146 | AtomicType, | 146 | AtomicType, |
| @@ -159,7 +159,7 @@ from pypto.ir import ( | |||
| 159 | MaskPattern, MergeMode, ReduceMode, CompareMode, DuplicatePos, | 159 | MaskPattern, MergeMode, ReduceMode, CompareMode, DuplicatePos, |
| 160 | CastLayout, VFRoundMode, SaturateMode, BinType, HistType, | 160 | CastLayout, VFRoundMode, SaturateMode, BinType, HistType, |
| 161 | SqueezeMode, PackPart, MaskWidth, LoadDist, StoreDist, | 161 | SqueezeMode, PackPart, MaskWidth, LoadDist, StoreDist, |
| 162 | - DataCopyMode, MemBarMode, MaskLoadDist, MaskStoreDist, | 162 | + DataCopyMode, MemBarMode, IndexOrder, |
| 163 | ) | 163 | ) |
| 164 | from pypto_pro.ir.op.ptr_ops import addptr, make_ptr, make_tensor | 164 | from pypto_pro.ir.op.ptr_ops import addptr, make_ptr, make_tensor |
| 165 | from pypto_pro.ir.op.system_ops import mutex_lock as _mutex_lock, mutex_unlock as _mutex_unlock | 165 | from pypto_pro.ir.op.system_ops import mutex_lock as _mutex_lock, mutex_unlock as _mutex_unlock |
| @@ -175,7 +175,7 @@ from ._api import ( | |||
| 175 | add, sub, mul, div, maximum, minimum, | 175 | add, sub, mul, div, maximum, minimum, |
| 176 | and_, xor, expands, | 176 | and_, xor, expands, |
| 177 | neg, abs, exp, log, sqrt, rsqrt, recip, relu, | 177 | neg, abs, exp, log, sqrt, rsqrt, recip, relu, |
| 178 | - fillpad, fillpad_expand, fillpad_inplace, | 178 | + fillpad, |
| 179 | cast, add_relu_cast, sub_relu_cast, mul_cast, | 179 | cast, add_relu_cast, sub_relu_cast, mul_cast, |
| 180 | eq, ne, lt, le, gt, ge, select, | 180 | eq, ne, lt, le, gt, ge, select, |
| 181 | add_relu, sub_relu, addc, mul_add_dst, | 181 | add_relu, sub_relu, addc, mul_add_dst, |
| @@ -41,6 +41,8 @@ from pypto.ir import ( | |||
| 41 | RoundMode, | 41 | RoundMode, |
| 42 | ) | 42 | ) |
| 43 | 43 | ||
| 44 | +from pypto_pro.ir.op.block_ops import FillPadMode | ||
| 45 | + | ||
| 44 | # --------------------------------------------------------------------------- | 46 | # --------------------------------------------------------------------------- |
| 45 | # User-facing type aliases (NOT IR types) | 47 | # User-facing type aliases (NOT IR types) |
| 46 | # --------------------------------------------------------------------------- | 48 | # --------------------------------------------------------------------------- |
| @@ -79,23 +81,24 @@ def _api_decl(func): | |||
| 79 | 81 | ||
| 80 | @_api_decl | 82 | @_api_decl |
| 81 | def load(dst_tile: Tile, src_tensor: Tensor, offsets: Offset, *, | 83 | def load(dst_tile: Tile, src_tensor: Tensor, offsets: Offset, *, |
| 82 | - is_transpose: bool = False, | 84 | + order: Optional[List[int]] = None) -> None: |
| 83 | - tile_dims: Optional[List[int]] = None) -> None: | ||
| 84 | """Load data from GM Tensor into on-chip Tile by absolute element coordinates. | 85 | """Load data from GM Tensor into on-chip Tile by absolute element coordinates. |
| 85 | 86 | ||
| 86 | Args: | 87 | Args: |
| 87 | dst_tile: Destination Tile (L1 or UB only) | 88 | dst_tile: Destination Tile (L1 or UB only) |
| 88 | src_tensor: Source Tensor (global memory, from kernel parameter) | 89 | src_tensor: Source Tensor (global memory, from kernel parameter) |
| 89 | offsets: Element-level offset per axis, e.g. ``[row, col]`` or ``[b, n, sq, sk]`` | 90 | offsets: Element-level offset per axis, e.g. ``[row, col]`` or ``[b, n, sq, sk]`` |
| 90 | - is_transpose: Whether to transpose the data during load (default ``False``) | 91 | + order: Optional, mapping of Tile dimensions to Tensor axes. |
| 91 | - tile_dims: Optional, which axes of the Tensor the Tile dimensions map to | 92 | + Each element is an absolute axis index of the Tensor. |
| 93 | + Ascending order (e.g. ``[0, 1]``) loads without transposition; | ||
| 94 | + descending order (e.g. ``[1, 0]``) loads with transposition (DN layout). | ||
| 95 | + Default: last N axes ascending (N = Tile ndim), i.e. no transposition. | ||
| 92 | """ | 96 | """ |
| 93 | 97 | ||
| 94 | 98 | ||
| 95 | @_api_decl | 99 | @_api_decl |
| 96 | def load_tile(dst_tile: Tile, src_tensor: Tensor, tile_offsets: Offset, *, | 100 | def load_tile(dst_tile: Tile, src_tensor: Tensor, tile_offsets: Offset, *, |
| 97 | - is_transpose: bool = False, | 101 | + order: Optional[List[int]] = None) -> None: |
| 98 | - tile_dims: Optional[List[int]] = None) -> None: | ||
| 99 | """Load data from GM Tensor into on-chip Tile by tile-block index. | 102 | """Load data from GM Tensor into on-chip Tile by tile-block index. |
| 100 | 103 | ||
| 101 | Offsets are in tile-block units, internally multiplied by tile shape. | 104 | Offsets are in tile-block units, internally multiplied by tile shape. |
| @@ -106,8 +109,11 @@ def load_tile(dst_tile: Tile, src_tensor: Tensor, tile_offsets: Offset, *, | |||
| 106 | dst_tile: Destination Tile (L1 or UB only) | 109 | dst_tile: Destination Tile (L1 or UB only) |
| 107 | src_tensor: Source Tensor (global memory) | 110 | src_tensor: Source Tensor (global memory) |
| 108 | tile_offsets: Tile-block index, e.g. ``[tile_row, tile_col]`` | 111 | tile_offsets: Tile-block index, e.g. ``[tile_row, tile_col]`` |
| 109 | - is_transpose: Whether to transpose the data during load (default ``False``) | 112 | + order: Optional, mapping of Tile dimensions to Tensor axes. |
| 110 | - tile_dims: Optional, which axes of the Tensor the Tile dimensions map to | 113 | + Each element is an absolute axis index of the Tensor. |
| 114 | + Ascending order (e.g. ``[0, 1]``) loads without transposition; | ||
| 115 | + descending order (e.g. ``[1, 0]``) loads with transposition (DN layout). | ||
| 116 | + Default: last N axes ascending (N = Tile ndim), i.e. no transposition. | ||
| 111 | """ | 117 | """ |
| 112 | 118 | ||
| 113 | 119 | ||
| @@ -365,18 +371,16 @@ def relu(out: Tile, src: Tile) -> None: | |||
| 365 | 371 | ||
| 366 | 372 | ||
| 367 | @_api_decl | 373 | @_api_decl |
| 368 | -def fillpad(out: Tile, src: Tile) -> None: | 374 | +def fillpad(out: Tile, src: Tile, *, mode: FillPadMode = FillPadMode.NORMAL) -> None: |
| 369 | - """Fill padding region of a Tile.""" | 375 | + """Fill padding region of a Tile. |
| 370 | 376 | ||
| 371 | - | 377 | + Args: |
| 372 | -@_api_decl | 378 | + out: Destination Tile. |
| 373 | -def fillpad_expand(out: Tile, src: Tile) -> None: | 379 | + src: Source Tile. |
| 374 | - """Fill padding region (expand mode).""" | 380 | + mode: Fill mode — ``pl.FillPadMode.NORMAL`` (default, dst and src same shape), |
| 375 | - | 381 | + ``pl.FillPadMode.EXPAND`` (dst larger than src, expand fill), |
| 376 | - | 382 | + ``pl.FillPadMode.INPLACE`` (dst and src share the same address). |
| 377 | -@_api_decl | 383 | + """ |
| 378 | -def fillpad_inplace(out: Tile, src: Tile) -> None: | ||
| 379 | - """Fill padding region in-place (dst and src share the same address).""" | ||
| 380 | 384 | ||
| 381 | 385 | ||
| 382 | # --- B4. Type conversion --- | 386 | # --- B4. Type conversion --- |
| @@ -987,11 +991,18 @@ class Vf: | |||
| 987 | Args: | 991 | Args: |
| 988 | dst: Destination UB Tile pointer | 992 | dst: Destination UB Tile pointer |
| 989 | src: Source register | 993 | src: Source register |
| 990 | - mask: Predicate mask register | 994 | + mask: Predicate mask register (omitted when src is a MaskReg) |
| 991 | 995 | ||
| 992 | Kwargs: | 996 | Kwargs: |
| 993 | - dist: ``"FIRST_ELEMENT"`` to store only lane 0; ``"PACK"`` for packed store | 997 | + dist: ``pl.StoreDist.NORM`` (default), ``pl.StoreDist.NORM_B16``, |
| 994 | - mode: ``pl.MergeMode.ZEROING`` (default) or ``pl.MergeMode.MERGING`` | 998 | + ``pl.StoreDist.FIRST_ELEMENT``, ``pl.StoreDist.PACK``, |
| 999 | + ``pl.StoreDist.PACK4``, ``pl.StoreDist.INTLV`` / ``INTLV_B32`` | ||
| 1000 | + (interleaved, requires two src registers), | ||
| 1001 | + ``pl.StoreDist.PACK`` for MaskReg src (psts PK mode) | ||
| 1002 | + post_update: True to auto-advance destination address after store | ||
| 1003 | + data_copy_mode: ``pl.DataCopyMode.DATA_BLOCK_COPY`` for vsstb instruction | ||
| 1004 | + block_stride: DataBlock copy block stride | ||
| 1005 | + repeat_stride: DataBlock copy repeat stride | ||
| 995 | """ | 1006 | """ |
| 996 | 1007 | ||
| 997 | @staticmethod | 1008 | @staticmethod |
| @@ -2268,180 +2279,6 @@ class Vf: | |||
| 2268 | repeat_stride: Stride for repeated stores | 2279 | repeat_stride: Stride for repeated stores |
| 2269 | """ | 2280 | """ |
| 2270 | 2281 | ||
| 2271 | - @staticmethod | ||
| 2272 | - @_api_decl | ||
| 2273 | - def mask_and(*args, **kwargs): | ||
| 2274 | - """Mask register bitwise AND: ``dst = src0 & src1`` (pand instruction). | ||
| 2275 | - | ||
| 2276 | - Args: | ||
| 2277 | - dst: Destination mask register | ||
| 2278 | - src0: First source mask register | ||
| 2279 | - src1: Second source mask register | ||
| 2280 | - mask: Predicate mask register | ||
| 2281 | - """ | ||
| 2282 | - | ||
| 2283 | - @staticmethod | ||
| 2284 | - @_api_decl | ||
| 2285 | - def mask_or(*args, **kwargs): | ||
| 2286 | - """Mask register bitwise OR: ``dst = src0 | src1`` (por instruction). | ||
| 2287 | - | ||
| 2288 | - Args: | ||
| 2289 | - dst: Destination mask register | ||
| 2290 | - src0: First source mask register | ||
| 2291 | - src1: Second source mask register | ||
| 2292 | - mask: Predicate mask register | ||
| 2293 | - """ | ||
| 2294 | - | ||
| 2295 | - @staticmethod | ||
| 2296 | - @_api_decl | ||
| 2297 | - def mask_xor(*args, **kwargs): | ||
| 2298 | - """Mask register bitwise XOR: ``dst = src0 ^ src1`` (pxor instruction). | ||
| 2299 | - | ||
| 2300 | - Args: | ||
| 2301 | - dst: Destination mask register | ||
| 2302 | - src0: First source mask register | ||
| 2303 | - src1: Second source mask register | ||
| 2304 | - mask: Predicate mask register | ||
| 2305 | - """ | ||
| 2306 | - | ||
| 2307 | - @staticmethod | ||
| 2308 | - @_api_decl | ||
| 2309 | - def mask_not(*args, **kwargs): | ||
| 2310 | - """Mask register bitwise NOT: ``dst = ~src`` (pnot instruction). | ||
| 2311 | - | ||
| 2312 | - Args: | ||
| 2313 | - dst: Destination mask register | ||
| 2314 | - src: Source mask register | ||
| 2315 | - mask: Predicate mask register | ||
| 2316 | - """ | ||
| 2317 | - | ||
| 2318 | - @staticmethod | ||
| 2319 | - @_api_decl | ||
| 2320 | - def mask_mov(*args, **kwargs): | ||
| 2321 | - """Mask register copy: ``dst = src`` (pmov instruction). | ||
| 2322 | - | ||
| 2323 | - Args: | ||
| 2324 | - dst: Destination mask register | ||
| 2325 | - src: Source mask register | ||
| 2326 | - """ | ||
| 2327 | - | ||
| 2328 | - @staticmethod | ||
| 2329 | - @_api_decl | ||
| 2330 | - def mask_sel(*args, **kwargs): | ||
| 2331 | - """Mask select: ``dst = src0 if pred else src1`` (psel instruction). | ||
| 2332 | - | ||
| 2333 | - Args: | ||
| 2334 | - dst: Destination mask register | ||
| 2335 | - src0: First source mask register | ||
| 2336 | - src1: Second source mask register | ||
| 2337 | - pred: Predicate mask register | ||
| 2338 | - """ | ||
| 2339 | - | ||
| 2340 | - @staticmethod | ||
| 2341 | - @_api_decl | ||
| 2342 | - def mask_pack(*args, **kwargs): | ||
| 2343 | - """Mask pack: narrow mask granularity (ppack instruction). | ||
| 2344 | - | ||
| 2345 | - Args: | ||
| 2346 | - dst: Destination mask register (narrower granularity) | ||
| 2347 | - src: Source mask register | ||
| 2348 | - """ | ||
| 2349 | - | ||
| 2350 | - @staticmethod | ||
| 2351 | - @_api_decl | ||
| 2352 | - def mask_unpack(*args, **kwargs): | ||
| 2353 | - """Mask unpack: widen mask granularity (punpack instruction). | ||
| 2354 | - | ||
| 2355 | - Args: | ||
| 2356 | - dst: Destination mask register (wider granularity) | ||
| 2357 | - src: Source mask register | ||
| 2358 | - """ | ||
| 2359 | - | ||
| 2360 | - @staticmethod | ||
| 2361 | - @_api_decl | ||
| 2362 | - def mask_interleave(*args, **kwargs): | ||
| 2363 | - """Mask interleave (pintlv_b8/b16/b32 instruction). | ||
| 2364 | - | ||
| 2365 | - Interleaves bits from two source masks. | ||
| 2366 | - | ||
| 2367 | - Args: | ||
| 2368 | - dst0: First destination mask register | ||
| 2369 | - dst1: Second destination mask register | ||
| 2370 | - src0: First source mask register | ||
| 2371 | - src1: Second source mask register | ||
| 2372 | - | ||
| 2373 | - Kwargs: | ||
| 2374 | - dtype: Data type controlling interleave granularity | ||
| 2375 | - """ | ||
| 2376 | - | ||
| 2377 | - @staticmethod | ||
| 2378 | - @_api_decl | ||
| 2379 | - def mask_deinterleave(*args, **kwargs): | ||
| 2380 | - """Mask de-interleave (pdintlv_b8/b16/b32 instruction). | ||
| 2381 | - | ||
| 2382 | - Splits interleaved mask bits into even/odd halves. | ||
| 2383 | - | ||
| 2384 | - Args: | ||
| 2385 | - dst0: First destination mask register (even bits) | ||
| 2386 | - dst1: Second destination mask register (odd bits) | ||
| 2387 | - src0: First source mask register | ||
| 2388 | - src1: Second source mask register | ||
| 2389 | - | ||
| 2390 | - Kwargs: | ||
| 2391 | - dtype: Data type controlling de-interleave granularity | ||
| 2392 | - """ | ||
| 2393 | - | ||
| 2394 | - @staticmethod | ||
| 2395 | - @_api_decl | ||
| 2396 | - def mask_load(*args, **kwargs): | ||
| 2397 | - """Load a mask register from UB memory (assignment form). | ||
| 2398 | - | ||
| 2399 | - Fixed-offset form emits ``plds``; passing an AddrReg offset (from | ||
| 2400 | - ``vf.create_addr_reg``) emits ``pld``:: | ||
| 2401 | - | ||
| 2402 | - dst = vf.mask_load(src_ptr) # plds (offset 0) | ||
| 2403 | - dst = vf.mask_load(src_ptr, addr_reg) # pld (AddrReg offset) | ||
| 2404 | - | ||
| 2405 | - Args: | ||
| 2406 | - src_ptr: Source UB pointer | ||
| 2407 | - offset: Optional AddrReg offset (routes to pld); mode ∈ NORM/US/DS | ||
| 2408 | - | ||
| 2409 | - Kwargs: | ||
| 2410 | - mode: ``pl.MaskLoadDist`` value (NORM/US/DS, default US) | ||
| 2411 | - """ | ||
| 2412 | - | ||
| 2413 | - @staticmethod | ||
| 2414 | - @_api_decl | ||
| 2415 | - def mask_store(*args, **kwargs): | ||
| 2416 | - """Store a mask register to UB memory. | ||
| 2417 | - | ||
| 2418 | - Fixed-offset form emits ``psts``; passing an AddrReg offset (from | ||
| 2419 | - ``vf.create_addr_reg``) as the 4th arg emits ``pst``:: | ||
| 2420 | - | ||
| 2421 | - vf.mask_store(src_mask, dst_ptr, mask) # psts (offset 0) | ||
| 2422 | - vf.mask_store(src_mask, dst_ptr, mask, addr_reg) # pst (AddrReg offset) | ||
| 2423 | - | ||
| 2424 | - Args: | ||
| 2425 | - src: Source mask register | ||
| 2426 | - dst_ptr: Destination UB pointer | ||
| 2427 | - mask: Predicate mask register | ||
| 2428 | - offset: Optional AddrReg offset (routes to pst); dist ∈ NORM/PK | ||
| 2429 | - | ||
| 2430 | - Kwargs: | ||
| 2431 | - dist: ``pl.MaskStoreDist.NORM`` or ``pl.MaskStoreDist.PK`` (default PK) | ||
| 2432 | - """ | ||
| 2433 | - | ||
| 2434 | - @staticmethod | ||
| 2435 | - @_api_decl | ||
| 2436 | - def mask_store_unalign(*args, **kwargs): | ||
| 2437 | - """Store mask register to unaligned UB address (pstu instruction). | ||
| 2438 | - | ||
| 2439 | - Args: | ||
| 2440 | - src: Source mask register | ||
| 2441 | - dst_ptr: Destination UB pointer | ||
| 2442 | - mask: Predicate mask register | ||
| 2443 | - """ | ||
| 2444 | - | ||
| 2445 | @staticmethod | 2282 | @staticmethod |
| 2446 | @_api_decl | 2283 | @_api_decl |
| 2447 | def truncate(*args, **kwargs): | 2284 | def truncate(*args, **kwargs): |
| @@ -51,6 +51,7 @@ class AssignmentParserMixin: | |||
| 51 | # Use annotation type as override when it carries memref info | 51 | # Use annotation type as override when it carries memref info |
| 52 | annotation_type = self.type_resolver.resolve_type_if_memref(stmt.annotation) | 52 | annotation_type = self.type_resolver.resolve_type_if_memref(stmt.annotation) |
| 53 | var = self.builder.let(var_name, value_expr, var_type=annotation_type, span=span) | 53 | var = self.builder.let(var_name, value_expr, var_type=annotation_type, span=span) |
| 54 | + self._mark_make_tuple_anchor(value_expr) | ||
| 54 | self._transfer_tile_sync_metadata(var, value_expr) | 55 | self._transfer_tile_sync_metadata(var, value_expr) |
| 55 | 56 | ||
| 56 | # Register in scope | 57 | # Register in scope |
| @@ -96,12 +97,15 @@ class AssignmentParserMixin: | |||
| 96 | self._parse_struct_field_assignment(target, stmt, span) | 97 | self._parse_struct_field_assignment(target, stmt, span) |
| 97 | return | 98 | return |
| 98 | 99 | ||
| 99 | - # AssignStmt left-values are restricted to plain Vars. Field writes go through | 100 | + if isinstance(target, ast.Subscript): |
| 100 | - # struct.set (above); there is no expression-target / subscript assignment. | 101 | + self._parse_subscript_assignment(target, stmt, span) |
| 102 | + return | ||
| 103 | + | ||
| 101 | raise ParserSyntaxError( | 104 | raise ParserSyntaxError( |
| 102 | f"Unsupported assignment target: {ast.unparse(stmt)}", | 105 | f"Unsupported assignment target: {ast.unparse(stmt)}", |
| 103 | span=span, | 106 | span=span, |
| 104 | - hint="Only `var = ...`, `a.field = ...` (struct), or tuple unpacking are supported", | 107 | + hint="Only `var = ...`, `a.field = ...` (struct), `tensor[i] = ...`, " |
| 108 | + "or tuple unpacking are supported", | ||
| 105 | ) | 109 | ) |
| 106 | 110 | ||
| 107 | # Ops where dst type differs from src type — dtype kwarg is mandatory. | 111 | # Ops where dst type differs from src type — dtype kwarg is mandatory. |
| @@ -164,16 +168,28 @@ class AssignmentParserMixin: | |||
| 164 | dst_names = [target.elts[0].id, target.elts[1].id] | 168 | dst_names = [target.elts[0].id, target.elts[1].id] |
| 165 | dst_targets = [target.elts[0], target.elts[1]] | 169 | dst_targets = [target.elts[0], target.elts[1]] |
| 166 | 170 | ||
| 167 | - # Determine dtype: check explicit dtype kwarg first. | 171 | + # Parse kwargs once; dtype is taken from here (explicit) or inferred |
| 168 | - # For type-changing ops (vf.astype), dtype kwarg is mandatory because | 172 | + # from source args below. |
| 169 | - # the dst type differs from src type. | 173 | + parsed_kwargs = self.parse_op_kwargs(call) |
| 170 | - dtype_val = None | 174 | + dtype_val = parsed_kwargs.pop("dtype", None) |
| 171 | - for kw in call.keywords: | ||
| 172 | - if kw.arg == "dtype": | ||
| 173 | - dtype_val = self.resolve_single_kwarg("dtype", kw.value) | ||
| 174 | - break | ||
| 175 | 175 | ||
| 176 | - if dtype_val is None and vf_op_name in self._TYPE_CHANGING_OPS: | 176 | + # Detect MaskReg data source — reused both for the type-changing-op |
| 177 | + # dtype exemption and for dst-kind inference below. | ||
| 178 | + # Only the first positional arg is checked: it is always a data source, | ||
| 179 | + # never the predicate mask (prego), which is always the LAST positional | ||
| 180 | + # arg. Checking all args would mistake preg for a MaskReg data source | ||
| 181 | + # and wrongly declare the dst as MaskReg (e.g. vf.or_(reg_a, reg_b, preg)). | ||
| 182 | + first_arg = call.args[0] if call.args else None | ||
| 183 | + is_mask_src = ( | ||
| 184 | + isinstance(first_arg, ast.Name) | ||
| 185 | + and self.scope_manager.is_mask_reg_var(first_arg.id) | ||
| 186 | + ) | ||
| 187 | + | ||
| 188 | + # For type-changing ops (vf.astype), dtype kwarg is mandatory because | ||
| 189 | + # the dst type differs from src type. Unified ops (pack, unpack) only | ||
| 190 | + # change type for the RegTensor variant; the MaskReg variant preserves | ||
| 191 | + # the source type, so dtype= is not required when sources are MaskReg. | ||
| 192 | + if dtype_val is None and vf_op_name in self._TYPE_CHANGING_OPS and not is_mask_src: | ||
| 177 | raise ParserTypeError( | 193 | raise ParserTypeError( |
| 178 | f"vf.{vf_op_name} requires explicit dtype kwarg because dst type differs from src. " | 194 | f"vf.{vf_op_name} requires explicit dtype kwarg because dst type differs from src. " |
| 179 | f"Example: vf.{vf_op_name}(src, mask, dtype=pl.DT_FP16)", | 195 | f"Example: vf.{vf_op_name}(src, mask, dtype=pl.DT_FP16)", |
| @@ -205,28 +221,23 @@ class AssignmentParserMixin: | |||
| 205 | span=span, | 221 | span=span, |
| 206 | ) | 222 | ) |
| 207 | 223 | ||
| 208 | - # Determine whether the backend op carries `dtype` as an IR attribute. | 224 | + # Re-inject dtype into kwargs iff the backend op carries it as an IR |
| 209 | - # If so, keep the user-supplied dtype (or inject the inferred one when | 225 | + # attribute; otherwise it has already been stripped above. |
| 210 | - # not explicitly passed); otherwise strip it. | 226 | + ir_op_name = f"vf.{vf_op_name}" |
| 211 | - backend_op_name = self._VF_OP_NAME_MAP.get(vf_op_name, vf_op_name) | 227 | + if ir.is_op_registered(ir_op_name) and ir.get_op(ir_op_name).has_attr("dtype"): |
| 212 | - ir_op_name = f"vf.{backend_op_name}" | 228 | + parsed_kwargs["dtype"] = dtype_val |
| 213 | - keep_dtype = ir.is_op_registered(ir_op_name) and \ | ||
| 214 | - ir.get_op(ir_op_name).has_attr("dtype") | ||
| 215 | - parsed_kwargs = { | ||
| 216 | - k: v for k, v in self.parse_op_kwargs(call).items() | ||
| 217 | - if k != "dtype" or keep_dtype | ||
| 218 | - } | ||
| 219 | - if keep_dtype: | ||
| 220 | - parsed_kwargs.setdefault("dtype", dtype_val) | ||
| 221 | 229 | ||
| 222 | # Step 2: Declare dst variables (first definition only). For existing | 230 | # Step 2: Declare dst variables (first definition only). For existing |
| 223 | # variables, reuse them directly — do NOT create a new register, as that | 231 | # variables, reuse them directly — do NOT create a new register, as that |
| 224 | # would lose the accumulated value in self-referential ops. | 232 | # would lose the accumulated value in self-referential ops. |
| 225 | # Ops in _VF_MASK_DST_OPS produce MaskReg dst(s); declare them via | 233 | # Ops in _VF_MASK_DST_OPS produce MaskReg dst(s); declare them via |
| 226 | - # vf.create_mask. All other ops produce RegTensor dst(s); declare via | 234 | + # vf.mask_reg. Unified ops (move, interleave, etc.) infer the dst kind |
| 227 | - # vf.reg_tensor. (addc/subc carry outputs must be pre-declared by the | 235 | + # from source operands: if any source is a known MaskReg variable, the |
| 228 | - # user via vf.create_mask.) | 236 | + # dst is declared as MaskReg. (addc/subc carry outputs must be |
| 237 | + # pre-declared by the user via vf.create_mask.) | ||
| 229 | is_mask_dst = self._is_vf_mask_dst_op(vf_op_name) | 238 | is_mask_dst = self._is_vf_mask_dst_op(vf_op_name) |
| 239 | + if not is_mask_dst and vf_op_name in self._VF_UNIFIED_OPS: | ||
| 240 | + is_mask_dst = is_mask_src | ||
| 230 | decl_op = "vf.mask_reg" if is_mask_dst else "vf.reg_tensor" | 241 | decl_op = "vf.mask_reg" if is_mask_dst else "vf.reg_tensor" |
| 231 | dst_vars = [] | 242 | dst_vars = [] |
| 232 | for name, _ in zip(dst_names, dst_targets): | 243 | for name, _ in zip(dst_names, dst_targets): |
| @@ -236,6 +247,8 @@ class AssignmentParserMixin: | |||
| 236 | decl_call = ir.create_op_call(decl_op, [], {"dtype": dtype_val}, span) | 247 | decl_call = ir.create_op_call(decl_op, [], {"dtype": dtype_val}, span) |
| 237 | var = self.builder.let(name, decl_call, span=span) | 248 | var = self.builder.let(name, decl_call, span=span) |
| 238 | self.scope_manager.define_var(name, var, span=span) | 249 | self.scope_manager.define_var(name, var, span=span) |
| 250 | + if is_mask_dst: | ||
| 251 | + self.scope_manager.register_mask_reg_var(name) | ||
| 239 | dst_vars.append(var) | 252 | dst_vars.append(var) |
| 240 | else: | 253 | else: |
| 241 | dst_vars.append(existing) | 254 | dst_vars.append(existing) |
| @@ -265,6 +278,7 @@ class AssignmentParserMixin: | |||
| 265 | span=span, | 278 | span=span, |
| 266 | ) | 279 | ) |
| 267 | tuple_var = self.builder.let(f"_tuple_tmp_{self._tuple_idx_counter}", value_expr, span=span) | 280 | tuple_var = self.builder.let(f"_tuple_tmp_{self._tuple_idx_counter}", value_expr, span=span) |
| 281 | + self._mark_make_tuple_anchor(value_expr) | ||
| 268 | self._tuple_idx_counter += 1 | 282 | self._tuple_idx_counter += 1 |
| 269 | for i, elt in enumerate(target.elts): | 283 | for i, elt in enumerate(target.elts): |
| 270 | if not isinstance(elt, ast.Name): | 284 | if not isinstance(elt, ast.Name): |
| @@ -298,8 +312,14 @@ class AssignmentParserMixin: | |||
| 298 | ) | 312 | ) |
| 299 | if isinstance(value_expr, ir.Expr): | 313 | if isinstance(value_expr, ir.Expr): |
| 300 | var = self.builder.let(var_name, value_expr, span=span) | 314 | var = self.builder.let(var_name, value_expr, span=span) |
| 315 | + self._mark_make_tuple_anchor(value_expr) | ||
| 301 | self._transfer_tile_sync_metadata(var, value_expr) | 316 | self._transfer_tile_sync_metadata(var, value_expr) |
| 302 | self.scope_manager.define_var(var_name, var, span=span) | 317 | self.scope_manager.define_var(var_name, var, span=span) |
| 318 | + # Track MaskReg-producing VF ops (create_mask, update_mask, etc.) | ||
| 319 | + # so unified ops can infer dst register kind from source operands. | ||
| 320 | + vf_op = self._is_vf_op_call(stmt.value) | ||
| 321 | + if vf_op is not None and vf_op in self._VF_MASK_PRODUCING_OPS: | ||
| 322 | + self.scope_manager.register_mask_reg_var(var_name) | ||
| 303 | if self._auto_mutex: | 323 | if self._auto_mutex: |
| 304 | self._emit_auto_mutex_unlocks() | 324 | self._emit_auto_mutex_unlocks() |
| 305 | self._update_const_env(var_name, value_expr) | 325 | self._update_const_env(var_name, value_expr) |
| @@ -341,3 +361,34 @@ class AssignmentParserMixin: | |||
| 341 | ) | 361 | ) |
| 342 | call = ir.create_op_call("struct.set", [base, value_expr], {"field": field_name}, span) | 362 | call = ir.create_op_call("struct.set", [base, value_expr], {"field": field_name}, span) |
| 343 | self.builder.emit(ir.EvalStmt(call, span)) | 363 | self.builder.emit(ir.EvalStmt(call, span)) |
| 364 | + | ||
| 365 | + def _parse_subscript_assignment(self, target: ast.Subscript, stmt: ast.Assign, span: ir.Span) -> None: | ||
| 366 | + container_expr = self.parse_expression(target.value) | ||
| 367 | + container_type = container_expr.type | ||
| 368 | + if not isinstance(container_type, (ir.TileType, ir.TensorType)): | ||
| 369 | + raise ParserTypeError( | ||
| 370 | + f"Subscript assignment requires Tile or Tensor, got {type(container_type).__name__}", | ||
| 371 | + span=span, | ||
| 372 | + hint="Only Tile and Tensor support element assignment via A[i] = v", | ||
| 373 | + ) | ||
| 374 | + index_expr = self._parse_scalar_subscript_index(container_expr, target.slice, span) | ||
| 375 | + value_expr = self.parse_expression(stmt.value, nested=False) | ||
| 376 | + if not isinstance(value_expr, ir.Expr): | ||
| 377 | + raise ParserTypeError( | ||
| 378 | + f"Right-hand side of subscript assignment must be an IR expression", | ||
| 379 | + span=span, | ||
| 380 | + ) | ||
| 381 | + meta = self._tile_mutex_meta.get(container_expr) if self._auto_mutex else None | ||
| 382 | + from pypto_pro.ir.op.block_ops import _ir_setval | ||
| 383 | + setval_call = _ir_setval(container_expr, index_expr, value_expr, span=span) | ||
| 384 | + if meta is not None: | ||
| 385 | + from ._op_pipeline import get_op_pipe | ||
| 386 | + from pypto_pro.ir.op.system_ops import mutex_lock, mutex_unlock | ||
| 387 | + pipe = get_op_pipe("setval") | ||
| 388 | + buf_id_ir, mutex_ids = meta | ||
| 389 | + self.builder.emit(ir.EvalStmt( | ||
| 390 | + mutex_lock(pipe=pipe, mutex_id=buf_id_ir, mutex_ids=mutex_ids, span=span), span)) | ||
| 391 | + self.builder.emit(ir.EvalStmt(setval_call, span)) | ||
| 392 | + if meta is not None: | ||
| 393 | + self.builder.emit(ir.EvalStmt( | ||
| 394 | + mutex_unlock(pipe=pipe, mutex_id=buf_id_ir, mutex_ids=mutex_ids, span=span), span)) | ||
| @@ -163,9 +163,17 @@ class ASTParser( | |||
| 163 | # GetItemExpr alias semantics; every other MakeTuple is immutable. | 163 | # GetItemExpr alias semantics; every other MakeTuple is immutable. |
| 164 | self._struct_array_tuple_ids: set[int] = set() | 164 | self._struct_array_tuple_ids: set[int] = set() |
| 165 | 165 | ||
| 166 | - # Cache closure-level tuple constants by name/object so repeated uses of | 166 | + # Maps tile expr id -> [row_expr, col_expr] for tiles that had |
| 167 | - # the same module constant do not create duplicate MakeTuple IR nodes. | 167 | + # set_validshape called on them at parse time. Consumed by |
| 168 | - self._closure_tuple_ir_cache: dict[tuple[str, int], ir.Expr] = {} | 168 | + # _parse_slice_subscript to clamp sub-view valid_shape. |
| 169 | + self._tile_valid_shape: dict[int, list] = {} | ||
| 170 | + | ||
| 171 | + # MakeTuples that already have an emitted assignment anchor. Keeping the | ||
| 172 | + # Expr objects themselves alive is required: a Python wrapper's id() can | ||
| 173 | + # be reused while parsing, which would otherwise suppress an unrelated | ||
| 174 | + # tuple's anchor. | ||
| 175 | + self._anchored_make_tuples: set[ir.MakeTuple] = set() | ||
| 176 | + | ||
| 169 | # Cache: (tuple_var_name, index_ssa_var_name) -> phi ir.Var from _build_tuple_index_chain. | 177 | # Cache: (tuple_var_name, index_ssa_var_name) -> phi ir.Var from _build_tuple_index_chain. |
| 170 | # Applies to all tuple types (tile, tensor, event ID, etc.). | 178 | # Applies to all tuple types (tile, tensor, event ID, etc.). |
| 171 | # Prevents re-emitting an if-else chain when the same buf[idx] expression | 179 | # Prevents re-emitting an if-else chain when the same buf[idx] expression |
| @@ -173,6 +181,7 @@ class ASTParser( | |||
| 173 | self._tuple_select_cache: dict[tuple[str, int], ir.Var] = {} | 181 | self._tuple_select_cache: dict[tuple[str, int], ir.Var] = {} |
| 174 | 182 | ||
| 175 | self._auto_mutex = auto_mutex | 183 | self._auto_mutex = auto_mutex |
| 184 | + self._parsed_expr_cache: dict[ast.expr, Any] = {} | ||
| 176 | self._current_func_type = ir.FunctionType.Opaque | 185 | self._current_func_type = ir.FunctionType.Opaque |
| 177 | self._void_return_only = void_return_only | 186 | self._void_return_only = void_return_only |
| 178 | self._void_return_context = void_return_context | 187 | self._void_return_context = void_return_context |
| @@ -203,6 +212,12 @@ class ASTParser( | |||
| 203 | tv.ptr = ptr_var | 212 | tv.ptr = ptr_var |
| 204 | return ir.TensorType(param_type.shape, param_type.dtype, param_type.memref, tv) | 213 | return ir.TensorType(param_type.shape, param_type.dtype, param_type.memref, tv) |
| 205 | 214 | ||
| 215 | + def record_tile_valid_shape(self, tile_expr: ir.Expr, valid_shape) -> None: | ||
| 216 | + self._tile_valid_shape[id(tile_expr)] = list(valid_shape.elements) | ||
| 217 | + | ||
| 218 | + def get_tile_valid_shape(self, tile_expr: ir.Expr): | ||
| 219 | + return self._tile_valid_shape.get(id(tile_expr)) | ||
| 220 | + | ||
| 206 | def set_void_return_mode(self, context: str, allow_early_return: bool = False) -> None: | 221 | def set_void_return_mode(self, context: str, allow_early_return: bool = False) -> None: |
| 207 | """Configure void-only return mode for this parser. | 222 | """Configure void-only return mode for this parser. |
| 208 | 223 | ||
| @@ -297,7 +312,7 @@ class ASTParser( | |||
| 297 | 312 | ||
| 298 | self._validate_tiling_params(args_to_process, func_def) | 313 | self._validate_tiling_params(args_to_process, func_def) |
| 299 | 314 | ||
| 300 | - self._closure_tuple_ir_cache.clear() | 315 | + self._anchored_make_tuples.clear() |
| 301 | has_policy_return = self.type_resolver.annotation_has_shape_policy(func_def.returns) | 316 | has_policy_return = self.type_resolver.annotation_has_shape_policy(func_def.returns) |
| 302 | 317 | ||
| 303 | with self.builder.function(func_name, func_span, func_type=func_type) as f: | 318 | with self.builder.function(func_name, func_span, func_type=func_type) as f: |
| @@ -312,9 +327,8 @@ class ASTParser( | |||
| 312 | # body (one MakeTuple expr), so a tuple return is one return type. | 327 | # body (one MakeTuple expr), so a tuple return is one return type. |
| 313 | f.return_type(self.type_resolver.resolve_type(func_def.returns)) | 328 | f.return_type(self.type_resolver.resolve_type(func_def.returns)) |
| 314 | 329 | ||
| 315 | - # Hoist Python closure tuple variables to function entry so they become | 330 | + # Give closure tuples a function-entry array-materialization anchor. |
| 316 | - # named IR Vars rather than anonymous inline MakeTuples. | 331 | + self._hoist_closure_tuples() |
| 317 | - self._hoist_closure_tuples(func_def) | ||
| 318 | 332 | ||
| 319 | # Collect function body statements (skip docstrings) | 333 | # Collect function body statements (skip docstrings) |
| 320 | body_stmts: list[ast.stmt] = [] | 334 | body_stmts: list[ast.stmt] = [] |
| @@ -383,12 +397,18 @@ class ASTParser( | |||
| 383 | 397 | ||
| 384 | @_dispatch_statement.register | 398 | @_dispatch_statement.register |
| 385 | def _parse_augmented_assignment_statement(self, stmt: ast.AugAssign) -> None: | 399 | def _parse_augmented_assignment_statement(self, stmt: ast.AugAssign) -> None: |
| 386 | - target_load = ast.copy_location( | 400 | + if isinstance(stmt.target, ast.Subscript): |
| 387 | - type(stmt.target)( | 401 | + target_load = ast.copy_location( |
| 388 | - id=stmt.target.id, ctx=ast.Load(), | 402 | + ast.Subscript(value=stmt.target.value, slice=stmt.target.slice, ctx=ast.Load()), |
| 389 | - ) if isinstance(stmt.target, ast.Name) else stmt.target, | 403 | + stmt.target, |
| 390 | - stmt.target, | 404 | + ) |
| 391 | - ) | 405 | + elif isinstance(stmt.target, ast.Name): |
| 406 | + target_load = ast.copy_location( | ||
| 407 | + ast.Name(id=stmt.target.id, ctx=ast.Load()), | ||
| 408 | + stmt.target, | ||
| 409 | + ) | ||
| 410 | + else: | ||
| 411 | + target_load = stmt.target | ||
| 392 | equivalent = ast.Assign( | 412 | equivalent = ast.Assign( |
| 393 | targets=[stmt.target], | 413 | targets=[stmt.target], |
| 394 | value=ast.BinOp(left=target_load, op=stmt.op, right=stmt.value), | 414 | value=ast.BinOp(left=target_load, op=stmt.op, right=stmt.value), |
| @@ -521,56 +541,33 @@ class ASTParser( | |||
| 521 | param_var = f.param(param_name, param_type, param_span) | 541 | param_var = f.param(param_name, param_type, param_span) |
| 522 | self.scope_manager.define_var(param_name, param_var, allow_redef=True) | 542 | self.scope_manager.define_var(param_name, param_var, allow_redef=True) |
| 523 | 543 | ||
| 524 | - def _hoist_closure_tuples(self, func_def: ast.FunctionDef) -> None: | 544 | + def _hoist_closure_tuples(self) -> None: |
| 525 | - """Emit let-bindings for Python closure tuple/list variables at function entry. | 545 | + """Anchor convertible closure tuple/list values at function entry. |
| 526 | 546 | ||
| 527 | - Scans the function AST for Name references that resolve to Python tuples | 547 | + Name reads intentionally continue to fold through ``const_env`` to the |
| 528 | - or lists in the closure scope. For each unique variable (deduplicated by | 548 | + original MakeTuple. The emitted lets exist only to give CCE a stable |
| 529 | - Python object identity), emits an AssignStmt at the current position | 549 | + lexical location for backing-array materialization. |
| 530 | - (function entry, before body statements) and caches the resulting IR Var | ||
| 531 | - in _closure_tuple_ir_cache. Subsequent parse_name() calls return the Var | ||
| 532 | - instead of an anonymous inline MakeTuple, so the CCE codegen can | ||
| 533 | - pre-declare the dynamic array at AssignStmt time with correct scoping. | ||
| 534 | """ | 550 | """ |
| 535 | - class _NameCollector(ast.NodeVisitor): | 551 | + seen: dict[int, tuple[ir.MakeTuple, ir.Var]] = {} |
| 536 | - """Walks AST collecting Name ids, skipping nested FunctionDef bodies.""" | 552 | + span = ir.Span.unknown() |
| 537 | - | 553 | + for var_name, value in self.expr_evaluator.closure_vars.items(): |
| 538 | - def __init__(self, root_func_def: ast.FunctionDef): | 554 | + has_scope_binding = self.scope_manager.lookup_var_bounded(var_name) is not None |
| 539 | - self.root_func_def = root_func_def | 555 | + if not isinstance(value, (tuple, list)) or has_scope_binding: |
| 540 | - self.names: list[ast.Name] = [] | ||
| 541 | - | ||
| 542 | - def visit(self, node): | ||
| 543 | - if isinstance(node, ast.FunctionDef) and node is not self.root_func_def: | ||
| 544 | - return None | ||
| 545 | - method = getattr(self, _snake_visit_name(node), None) | ||
| 546 | - if method is not None: | ||
| 547 | - return method(node) | ||
| 548 | - return super().visit(node) | ||
| 549 | - | ||
| 550 | - def visit_name(self, node: ast.Name) -> None: | ||
| 551 | - self.names.append(node) | ||
| 552 | - | ||
| 553 | - def visit_function_def(self, node: ast.FunctionDef) -> None: | ||
| 554 | - self.generic_visit(node) | ||
| 555 | - | ||
| 556 | - collector = _NameCollector(func_def) | ||
| 557 | - collector.visit(func_def) | ||
| 558 | - | ||
| 559 | - seen: set[tuple[str, int]] = set() | ||
| 560 | - for name_node in collector.names: | ||
| 561 | - var_name = name_node.id | ||
| 562 | - if var_name not in self.expr_evaluator.closure_vars: | ||
| 563 | - continue | ||
| 564 | - value = self.expr_evaluator.closure_vars[var_name] | ||
| 565 | - if not isinstance(value, (tuple, list)): | ||
| 566 | continue | 556 | continue |
| 567 | if any(isinstance(v, _ShapePolicy) or v is Ellipsis for v in value): | 557 | if any(isinstance(v, _ShapePolicy) or v is Ellipsis for v in value): |
| 568 | continue | 558 | continue |
| 569 | - key = (var_name, id(value)) | 559 | + entry = seen.get(id(value)) |
| 570 | - if key in seen: | 560 | + if entry is None: |
| 571 | - continue | 561 | + try: |
| 572 | - seen.add(key) | 562 | + tuple_expr = self.expr_evaluator.python_value_to_ir(value, span) |
| 573 | - span = self.span_tracker.get_span(name_node) | 563 | + except (ParserTypeError, TypeError, ValueError): |
| 574 | - mt_expr = self.expr_evaluator.python_value_to_ir(value, span) | 564 | + continue |
| 575 | - ir_var = self.builder.let(var_name, mt_expr, span=span) | 565 | + if not isinstance(tuple_expr, ir.MakeTuple): |
| 576 | - self._closure_tuple_ir_cache[key] = ir_var | 566 | + continue |
| 567 | + tuple_var = self.builder.let(var_name, tuple_expr, span=span) | ||
| 568 | + self._anchored_make_tuples.add(tuple_expr) | ||
| 569 | + seen[id(value)] = (tuple_expr, tuple_var) | ||
| 570 | + else: | ||
| 571 | + tuple_expr, tuple_var = entry | ||
| 572 | + self.scope_manager.define_var(var_name, tuple_var, allow_redef=True) | ||
| 573 | + self.const_env[var_name] = tuple_expr | ||
| @@ -166,7 +166,6 @@ class CallParserMixin: | |||
| 166 | "add": 1, "sub": 1, "mul": 1, "div": 1, "max": 1, "min": 1, | 166 | "add": 1, "sub": 1, "mul": 1, "div": 1, "max": 1, "min": 1, |
| 167 | "and_": 1, "or_": 1, "xor": 1, "abs_sub": 1, "select": 1, | 167 | "and_": 1, "or_": 1, "xor": 1, "abs_sub": 1, "select": 1, |
| 168 | "shift_left": 1, "shift_right": 1, "prelu": 1, | 168 | "shift_left": 1, "shift_right": 1, "prelu": 1, |
| 169 | - "mask_and": 1, "mask_or": 1, "mask_xor": 1, "mask_not": 1, | ||
| 170 | "ln": 1, "log": 1, "exp": 1, "abs": 1, "not_": 1, "sqrt": 1, | 169 | "ln": 1, "log": 1, "exp": 1, "abs": 1, "not_": 1, "sqrt": 1, |
| 171 | "relu": 1, "neg": 1, "copy": 1, "pair_reduce_sum": 1, | 170 | "relu": 1, "neg": 1, "copy": 1, "pair_reduce_sum": 1, |
| 172 | "squeeze": 1, "truncate": 1, "astype": 1, "log2": 1, "log10": 1, | 171 | "squeeze": 1, "truncate": 1, "astype": 1, "log2": 1, "log10": 1, |
| @@ -174,21 +173,20 @@ class CallParserMixin: | |||
| 174 | "muls": 1, "adds": 1, "subs": 1, "mins": 1, "maxs": 1, | 173 | "muls": 1, "adds": 1, "subs": 1, "mins": 1, "maxs": 1, |
| 175 | "leaky_relu": 1, "muls_cast": 1, | 174 | "leaky_relu": 1, "muls_cast": 1, |
| 176 | "axpy": 1, "exp_sub": 1, "mul_add_dst": 1, "mul_dst_add": 1, | 175 | "axpy": 1, "exp_sub": 1, "mul_add_dst": 1, "mul_dst_add": 1, |
| 177 | - "pack": 1, "unpack": 1, "mask_pack": 1, "mask_unpack": 1, | 176 | + "pack": 1, "unpack": 1, |
| 178 | - "mask_mov": 1, "arange": 1, "unsqueeze": 1, "full": 1, | 177 | + "arange": 1, "unsqueeze": 1, "full": 1, |
| 179 | "load_align": 1, "load": 1, "load_unalign": 1, | 178 | "load_align": 1, "load": 1, "load_unalign": 1, |
| 180 | "gather": 1, | 179 | "gather": 1, |
| 181 | - "mask_sel": 1, "move": 1, | 180 | + "move": 1, |
| 182 | "eq": 1, "ne": 1, "lt": 1, "gt": 1, "le": 1, "ge": 1, | 181 | "eq": 1, "ne": 1, "lt": 1, "gt": 1, "le": 1, "ge": 1, |
| 183 | "histograms": 1, | 182 | "histograms": 1, |
| 184 | # 2 dsts | 183 | # 2 dsts |
| 185 | "interleave": 2, "de_interleave": 2, | 184 | "interleave": 2, "de_interleave": 2, |
| 186 | - "mask_interleave": 2, "mask_deinterleave": 2, | ||
| 187 | "mull": 2, | 185 | "mull": 2, |
| 188 | "addc": 2, "subc": 2, | 186 | "addc": 2, "subc": 2, |
| 189 | # 0 dst (no assignment form) | 187 | # 0 dst (no assignment form) |
| 190 | "store_align": 0, "store_unalign": 0, "store_unalign_post": 0, | 188 | "store_align": 0, "store_unalign": 0, "store_unalign_post": 0, |
| 191 | - "scatter": 0, "store": 0, "mask_store": 0, "mask_store_unalign": 0, | 189 | + "scatter": 0, "store": 0, |
| 192 | "mem_bar": 0, "clear_spr": 0, | 190 | "mem_bar": 0, "clear_spr": 0, |
| 193 | "load_unalign_pre": 0, | 191 | "load_unalign_pre": 0, |
| 194 | "store_align_pack": 0, "store_align_intlv": 0, | 192 | "store_align_pack": 0, "store_align_intlv": 0, |
| @@ -199,9 +197,24 @@ class CallParserMixin: | |||
| 199 | # declares these via vf.create_mask instead of vf.reg_tensor. | 197 | # declares these via vf.create_mask instead of vf.reg_tensor. |
| 200 | _VF_MASK_DST_OPS: frozenset[str] = frozenset({ | 198 | _VF_MASK_DST_OPS: frozenset[str] = frozenset({ |
| 201 | "eq", "ne", "lt", "gt", "le", "ge", | 199 | "eq", "ne", "lt", "gt", "le", "ge", |
| 202 | - "mask_and", "mask_or", "mask_xor", "mask_not", | 200 | + }) |
| 203 | - "mask_mov", "mask_sel", "mask_pack", "mask_unpack", | 201 | + |
| 204 | - "mask_interleave", "mask_deinterleave", | 202 | + # Ops that support both RegTensor and MaskReg dsts. When the dst is freshly |
| 203 | + # declared, its register kind is inferred from the source operands: if any | ||
| 204 | + # source argument is a known MaskReg variable, the dst is declared as | ||
| 205 | + # MaskReg; otherwise RegTensor. | ||
| 206 | + _VF_UNIFIED_OPS: frozenset[str] = frozenset({ | ||
| 207 | + "move", "and_", "or_", "xor", "not_", | ||
| 208 | + "select", "pack", "unpack", | ||
| 209 | + "interleave", "de_interleave", | ||
| 210 | + "load_align", "store_align", "store_unalign", | ||
| 211 | + }) | ||
| 212 | + | ||
| 213 | + # VF ops whose return value is a MaskReg (used by _parse_name_assignment to | ||
| 214 | + # track MaskReg variables for unified-op dst inference). | ||
| 215 | + _VF_MASK_PRODUCING_OPS: frozenset[str] = frozenset({ | ||
| 216 | + "create_mask", "update_mask", "get_mask_spr", | ||
| 217 | + "mask_gen_with_reg_tensor", | ||
| 205 | }) | 218 | }) |
| 206 | 219 | ||
| 207 | @staticmethod | 220 | @staticmethod |
| @@ -567,13 +580,13 @@ class CallParserMixin: | |||
| 567 | return | 580 | return |
| 568 | from pypto.ir import ( | 581 | from pypto.ir import ( |
| 569 | BinType, CastLayout, CompareMode, DataCopyMode, DuplicatePos, | 582 | BinType, CastLayout, CompareMode, DataCopyMode, DuplicatePos, |
| 570 | - HistType, IndexOrder, LoadDist, MaskLoadDist, MaskPattern, MaskStoreDist, | 583 | + HistType, IndexOrder, LoadDist, MaskPattern, |
| 571 | MaskWidth, MemBarMode, MergeMode, PackPart, | 584 | MaskWidth, MemBarMode, MergeMode, PackPart, |
| 572 | ReduceMode, VFRoundMode, SaturateMode, SqueezeMode, StoreDist, | 585 | ReduceMode, VFRoundMode, SaturateMode, SqueezeMode, StoreDist, |
| 573 | ) | 586 | ) |
| 574 | cls._VF_KWARG_ENUMS = { | 587 | cls._VF_KWARG_ENUMS = { |
| 575 | "pattern": (MaskPattern,), | 588 | "pattern": (MaskPattern,), |
| 576 | - "mode": (MergeMode, MemBarMode, MaskLoadDist), | 589 | + "mode": (MergeMode, MemBarMode), |
| 577 | "merge_mode": (MergeMode,), | 590 | "merge_mode": (MergeMode,), |
| 578 | "reduce_mode": (ReduceMode,), | 591 | "reduce_mode": (ReduceMode,), |
| 579 | "reduce_type": (ReduceMode,), | 592 | "reduce_type": (ReduceMode,), |
| @@ -585,10 +598,9 @@ class CallParserMixin: | |||
| 585 | "bin_type": (BinType,), | 598 | "bin_type": (BinType,), |
| 586 | "hist_type": (HistType,), | 599 | "hist_type": (HistType,), |
| 587 | "gather_mode": (SqueezeMode,), | 600 | "gather_mode": (SqueezeMode,), |
| 588 | - "half": (PackPart,), | ||
| 589 | "part": (PackPart,), | 601 | "part": (PackPart,), |
| 590 | "width": (MaskWidth,), | 602 | "width": (MaskWidth,), |
| 591 | - "dist": (LoadDist, StoreDist, MaskStoreDist), | 603 | + "dist": (LoadDist, StoreDist), |
| 592 | "data_copy_mode": (DataCopyMode,), | 604 | "data_copy_mode": (DataCopyMode,), |
| 593 | "index_order": (IndexOrder,), | 605 | "index_order": (IndexOrder,), |
| 594 | } | 606 | } |
| @@ -731,26 +743,6 @@ class CallParserMixin: | |||
| 731 | if enum_classes is not None: | 743 | if enum_classes is not None: |
| 732 | if isinstance(result, enum_classes): | 744 | if isinstance(result, enum_classes): |
| 733 | return result | 745 | return result |
| 734 | - if isinstance(result, str): | ||
| 735 | - all_members = [] | ||
| 736 | - for cls in enum_classes: | ||
| 737 | - members = getattr(cls, "__members__", None) | ||
| 738 | - if members is not None: | ||
| 739 | - all_members.extend(f"pl.{cls.__name__}.{name}" for name in members) | ||
| 740 | - else: | ||
| 741 | - try: | ||
| 742 | - all_members.extend(f"pl.{cls.__name__}.{m.name}" for m in cls) | ||
| 743 | - except TypeError: | ||
| 744 | - pass | ||
| 745 | - enum_names = ", ".join(c.__name__ for c in enum_classes) | ||
| 746 | - hint_str = ", ".join(all_members[:8]) if all_members else enum_names | ||
| 747 | - if len(all_members) > 8: | ||
| 748 | - hint_str += ", ..." | ||
| 749 | - raise ParserTypeError( | ||
| 750 | - f"VF kwarg '{key}' requires an enum value, got string \"{result}\". " | ||
| 751 | - f"Use one of: {hint_str}", | ||
| 752 | - span=self.span_tracker.get_span(value), | ||
| 753 | - ) | ||
| 754 | return result | 746 | return result |
| 755 | 747 | ||
| 756 | def resolve_const_int_list_kwarg(self, call: ast.Call, key: str) -> "list[int] | None": | 748 | def resolve_const_int_list_kwarg(self, call: ast.Call, key: str) -> "list[int] | None": |
| @@ -1123,6 +1115,7 @@ class CallParserMixin: | |||
| 1123 | return result | 1115 | return result |
| 1124 | return self.parse_list(value) | 1116 | return self.parse_list(value) |
| 1125 | 1117 | ||
| 1118 | + | ||
| 1126 | def _parse_vf_op(self, op_name: str, call: ast.Call) -> ir.Expr: | 1119 | def _parse_vf_op(self, op_name: str, call: ast.Call) -> ir.Expr: |
| 1127 | """Parse a VF API operation call: vf.{op_name}(...). | 1120 | """Parse a VF API operation call: vf.{op_name}(...). |
| 1128 | 1121 | ||
| @@ -1176,37 +1169,42 @@ class CallParserMixin: | |||
| 1176 | 1169 | ||
| 1177 | args = [self.parse_expression(arg) for arg in call.args] | 1170 | args = [self.parse_expression(arg) for arg in call.args] |
| 1178 | kwargs = self.parse_op_kwargs(call) | 1171 | kwargs = self.parse_op_kwargs(call) |
| 1179 | - backend_op_name = self._VF_OP_NAME_MAP.get(op_name, op_name) | ||
| 1180 | 1172 | ||
| 1181 | - return ir.create_op_call(f"vf.{backend_op_name}", args, kwargs, span) | 1173 | + return ir.create_op_call(f"vf.{op_name}", args, kwargs, span) |
| 1182 | 1174 | ||
| 1183 | # --- auto_mutex helpers --------------------------------------------------- | 1175 | # --- auto_mutex helpers --------------------------------------------------- |
| 1184 | 1176 | ||
| 1185 | - def _try_resolve_tileref(self, node: ast.expr): | 1177 | + def _try_resolve_tileref(self, node: ast.expr, kwarg_name: str | None = None): |
| 1186 | """Resolve a tile argument to a mutex ref. | 1178 | """Resolve a tile argument to a mutex ref. |
| 1187 | 1179 | ||
| 1188 | - Call parse_expression to obtain the IR expr, then look up sync metadata | 1180 | + Returns _MutexRef(buf_id, mutex_ids, memory, tile_id) when ``node`` |
| 1189 | - from _tile_mutex_meta. Works for both inline group accessors | 1181 | + carries tile-group mutex metadata; otherwise None. |
| 1190 | - (acc.next()) and variable-assigned tiles (cur_a). | ||
| 1191 | 1182 | ||
| 1192 | - Returns _MutexRef(buf_id, mutex_ids, memory, slot_id) or None. | 1183 | + ``kwarg_name`` distinguishes positional vs keyword args (keyword args |
| 1184 | + use ``resolve_single_kwarg``, positional args use ``parse_expression``). | ||
| 1185 | + Subscript arguments (``tile[off]``, ``buf[idx]``) alias the base's | ||
| 1186 | + buffer; their mutex metadata is propagated onto the GetItemExpr by | ||
| 1187 | + ``parse_subscript``, so the generic ``parse_expression`` path finds it. | ||
| 1193 | """ | 1188 | """ |
| 1194 | - expr = self.parse_expression(node) | 1189 | + expr = ( |
| 1190 | + self.resolve_single_kwarg(kwarg_name, node) | ||
| 1191 | + if kwarg_name is not None | ||
| 1192 | + else self.parse_expression(node) | ||
| 1193 | + ) | ||
| 1195 | if not isinstance(expr, ir.Expr): | 1194 | if not isinstance(expr, ir.Expr): |
| 1196 | return None | 1195 | return None |
| 1197 | meta = self._tile_mutex_meta.get(expr) | 1196 | meta = self._tile_mutex_meta.get(expr) |
| 1198 | - slot_id = id(expr) | ||
| 1199 | if meta is None: | 1197 | if meta is None: |
| 1200 | return None | 1198 | return None |
| 1201 | buf_id_ir, mutex_ids = meta | 1199 | buf_id_ir, mutex_ids = meta |
| 1202 | mem = expr.type.memref.memory_space_ if isinstance(expr.type, ir.TileType) and expr.type.memref else None | 1200 | mem = expr.type.memref.memory_space_ if isinstance(expr.type, ir.TileType) and expr.type.memref else None |
| 1203 | - return _MutexRef(buf_id_ir, mutex_ids, mem, slot_id) | 1201 | + return _MutexRef(buf_id_ir, mutex_ids, mem, id(expr)) |
| 1204 | 1202 | ||
| 1205 | def _emit_auto_mutex(self, op_name: str, call: ast.Call, span: ir.Span): | 1203 | def _emit_auto_mutex(self, op_name: str, call: ast.Call, span: ir.Span): |
| 1206 | """Emit mutex_lock before and mutex_unlock after a block DSL op. | 1204 | """Emit mutex_lock before and mutex_unlock after a block DSL op. |
| 1207 | 1205 | ||
| 1208 | - Scans call.args for tile-group tiles, determines the op pipe, | 1206 | + Scans positional and keyword arguments for tile-group tiles, determines the op |
| 1209 | - and emits lock/unlock per unique slot. | 1207 | + pipe, and emits lock/unlock per unique slot. |
| 1210 | Returns None -the caller still parses the op normally. | 1208 | Returns None -the caller still parses the op normally. |
| 1211 | 1209 | ||
| 1212 | Phase-aware skip on Acc tiles: when matmul/matmul_acc/store carries | 1210 | Phase-aware skip on Acc tiles: when matmul/matmul_acc/store carries |
| @@ -1234,6 +1232,11 @@ class CallParserMixin: | |||
| 1234 | # then drop Acc tiles when a phase-aware matmul/store carries the | 1232 | # then drop Acc tiles when a phase-aware matmul/store carries the |
| 1235 | # unit_flag (the hardware handshake replaces the software mutex there). | 1233 | # unit_flag (the hardware handshake replaces the software mutex there). |
| 1236 | tilerefs = [self._try_resolve_tileref(arg) for arg in call.args] | 1234 | tilerefs = [self._try_resolve_tileref(arg) for arg in call.args] |
| 1235 | + tilerefs.extend( | ||
| 1236 | + self._try_resolve_tileref(kw.value, kw.arg) | ||
| 1237 | + for kw in call.keywords | ||
| 1238 | + if kw.arg is not None | ||
| 1239 | + ) | ||
| 1237 | unique_refs = [] | 1240 | unique_refs = [] |
| 1238 | seen = set() | 1241 | seen = set() |
| 1239 | for tref in tilerefs: | 1242 | for tref in tilerefs: |
| @@ -1244,7 +1247,7 @@ class CallParserMixin: | |||
| 1244 | seen.add(tref.slot_id) | 1247 | seen.add(tref.slot_id) |
| 1245 | unique_refs.append(tref) | 1248 | unique_refs.append(tref) |
| 1246 | 1249 | ||
| 1247 | - if op_name in ("matmul", "matmul_acc", "store"): | 1250 | + if op_name in ("matmul", "matmul_acc", "store", "store_tile"): |
| 1248 | phase = None | 1251 | phase = None |
| 1249 | for kw in call.keywords: | 1252 | for kw in call.keywords: |
| 1250 | if kw.arg == "phase": | 1253 | if kw.arg == "phase": |
| @@ -1253,7 +1256,9 @@ class CallParserMixin: | |||
| 1253 | phase = resolved.value | 1256 | phase = resolved.value |
| 1254 | break | 1257 | break |
| 1255 | # STPhase/AccPhase enum: Partial/Final indicates multi-step accumulation | 1258 | # STPhase/AccPhase enum: Partial/Final indicates multi-step accumulation |
| 1256 | - if phase in (ir.STPhase.Partial, ir.STPhase.Final): | 1259 | + _phase_skip = {ir.STPhase.Partial.value, ir.STPhase.Final.value, |
| 1260 | + ir.AccPhase.Partial.value, ir.AccPhase.Final.value} | ||
| 1261 | + if phase in _phase_skip: | ||
| 1257 | unique_refs = [r for r in unique_refs if r.memory != ir.MemorySpace.Acc] | 1262 | unique_refs = [r for r in unique_refs if r.memory != ir.MemorySpace.Acc] |
| 1258 | 1263 | ||
| 1259 | if not unique_refs: | 1264 | if not unique_refs: |
| @@ -12,6 +12,7 @@ | |||
| 12 | from __future__ import annotations | 12 | from __future__ import annotations |
| 13 | 13 | ||
| 14 | import ast | 14 | import ast |
| 15 | +import logging | ||
| 15 | from typing import Any | 16 | from typing import Any |
| 16 | 17 | ||
| 17 | from pypto_pro.ir import op as ir_op | 18 | from pypto_pro.ir import op as ir_op |
| @@ -170,6 +171,8 @@ class ExpressionParserMixin: | |||
| 170 | Returns: | 171 | Returns: |
| 171 | IR expression | 172 | IR expression |
| 172 | """ | 173 | """ |
| 174 | + if expr in self._parsed_expr_cache: | ||
| 175 | + return self._parsed_expr_cache[expr] | ||
| 173 | self._current_node = expr | 176 | self._current_node = expr |
| 174 | if isinstance(expr, ast.Name): | 177 | if isinstance(expr, ast.Name): |
| 175 | result = self.parse_name(expr) | 178 | result = self.parse_name(expr) |
| @@ -203,7 +206,8 @@ class ExpressionParserMixin: | |||
| 203 | ) | 206 | ) |
| 204 | 207 | ||
| 205 | if nested: | 208 | if nested: |
| 206 | - result = self._materialize_nested_call(result, self.span_tracker.get_span(expr)) | 209 | + result = self._materialize_nested_expr(result, self.span_tracker.get_span(expr)) |
| 210 | + self._parsed_expr_cache[expr] = result | ||
| 207 | return result | 211 | return result |
| 208 | 212 | ||
| 209 | def parse_name(self, name: ast.Name) -> ir.Expr | Any: | 213 | def parse_name(self, name: ast.Name) -> ir.Expr | Any: |
| @@ -282,9 +286,27 @@ class ExpressionParserMixin: | |||
| 282 | left = self.parse_expression(binop.left) | 286 | left = self.parse_expression(binop.left) |
| 283 | right = self.parse_expression(binop.right) | 287 | right = self.parse_expression(binop.right) |
| 284 | 288 | ||
| 285 | - # Tile + offset in VF scope → GetItemExpr (pointer arithmetic) | 289 | + # Tile + offset: only supported in VF section as pointer arithmetic. |
| 290 | + # Non-VF sections require slice syntax (tile[r:r+h, c:c+w]) for sub-views. | ||
| 286 | if isinstance(binop.op, ast.Add) and isinstance(left.type, ir.TileType): | 291 | if isinstance(binop.op, ast.Add) and isinstance(left.type, ir.TileType): |
| 287 | - return ir.GetItemExpr(left, right, span) | 292 | + if self.inline_vf_depth == 0: |
| 293 | + raise ParserSyntaxError( | ||
| 294 | + "Tile + offset is not supported outside VF section; " | ||
| 295 | + "use tile[i:i+h, j:j+w] slice syntax for sub-view", | ||
| 296 | + span=span, | ||
| 297 | + hint="Replace `tile + offset` with `tile[row:row+h, :]` for offset access", | ||
| 298 | + ) | ||
| 299 | + # VF section: lower to block.subview with original shape (VF codegen | ||
| 300 | + # only uses the offset as pointer arithmetic, shape is ignored). | ||
| 301 | + from pypto_pro.ir.op.block_ops import block_ir_op | ||
| 302 | + shape_tuple = ir.MakeTuple(left.type.shape, span) | ||
| 303 | + result = ir.create_op_call( | ||
| 304 | + block_ir_op("subview"), | ||
| 305 | + [left, right, shape_tuple], | ||
| 306 | + {}, | ||
| 307 | + span, | ||
| 308 | + ) | ||
| 309 | + return result | ||
| 288 | 310 | ||
| 289 | # Raw pointer arithmetic: only `ptr + offset` is meaningful (→ pl.addptr). | 311 | # Raw pointer arithmetic: only `ptr + offset` is meaningful (→ pl.addptr). |
| 290 | # Every other operator on a pointer (-, *, /, //, %) is forbidden. | 312 | # Every other operator on a pointer (-, *, /, //, %) is forbidden. |
| @@ -711,13 +733,41 @@ class ExpressionParserMixin: | |||
| 711 | value_expr = self.parse_expression(subscript.value) | 733 | value_expr = self.parse_expression(subscript.value) |
| 712 | value_type = value_expr.type | 734 | value_type = value_expr.type |
| 713 | 735 | ||
| 714 | - if not isinstance(value_type, (ir.TileType, ir.TupleType)): | 736 | + # Tile/Tensor subscript: dispatch by index type |
| 737 | + # - Integer index (no ':') → getval (scalar access, Tile and Tensor) | ||
| 738 | + # - Slice index (has ':') → sub-view (block.subview, Tile only) | ||
| 739 | + if isinstance(value_type, (ir.TensorType, ir.TileType)): | ||
| 740 | + has_slice = isinstance(subscript.slice, ast.Slice) or ( | ||
| 741 | + isinstance(subscript.slice, ast.Tuple) | ||
| 742 | + and any(isinstance(e, ast.Slice) for e in subscript.slice.elts) | ||
| 743 | + ) | ||
| 744 | + if has_slice: | ||
| 745 | + return self._parse_slice_subscript(value_expr, subscript.slice, span) | ||
| 746 | + # All-integer index: A[i, j] → getval(A, i*cols+j) | ||
| 747 | + index_expr = self._parse_scalar_subscript_index(value_expr, subscript.slice, span) | ||
| 748 | + meta = self._tile_mutex_meta.get(value_expr) if self._auto_mutex else None | ||
| 749 | + from pypto_pro.ir.op.block_ops import _ir_getval | ||
| 750 | + result = _ir_getval(value_expr, index_expr, span=span) | ||
| 751 | + if meta is not None: | ||
| 752 | + from ._op_pipeline import get_op_pipe | ||
| 753 | + from pypto_pro.ir.op.system_ops import mutex_lock, mutex_unlock | ||
| 754 | + pipe = get_op_pipe("getval") | ||
| 755 | + buf_id_ir, mutex_ids = meta | ||
| 756 | + self.builder.emit(ir.EvalStmt( | ||
| 757 | + mutex_lock(pipe=pipe, mutex_id=buf_id_ir, mutex_ids=mutex_ids, span=span), span)) | ||
| 758 | + result = self._materialize_nested_expr(result, span) | ||
| 759 | + self.builder.emit(ir.EvalStmt( | ||
| 760 | + mutex_unlock(pipe=pipe, mutex_id=buf_id_ir, mutex_ids=mutex_ids, span=span), span)) | ||
| 761 | + return result | ||
| 762 | + | ||
| 763 | + if not isinstance(value_type, ir.TupleType): | ||
| 715 | raise ParserTypeError( | 764 | raise ParserTypeError( |
| 716 | - f"Subscript requires tuple or tile type, got {type(value_type).__name__}", | 765 | + f"Subscript requires tuple, tile, or tensor type, got {type(value_type).__name__}", |
| 717 | span=span, | 766 | span=span, |
| 718 | - hint="Only tuple types support subscript access in this context", | 767 | + hint="Subscript access is supported on Tuple, Tile, and Tensor types", |
| 719 | ) | 768 | ) |
| 720 | 769 | ||
| 770 | + # TupleType subscript: tuple[i] element access | ||
| 721 | if isinstance(subscript.slice, ast.Constant): | 771 | if isinstance(subscript.slice, ast.Constant): |
| 722 | if not isinstance(subscript.slice.value, int): | 772 | if not isinstance(subscript.slice.value, int): |
| 723 | raise ParserSyntaxError( | 773 | raise ParserSyntaxError( |
| @@ -728,12 +778,11 @@ class ExpressionParserMixin: | |||
| 728 | else: | 778 | else: |
| 729 | if isinstance(subscript.slice, ast.Tuple): | 779 | if isinstance(subscript.slice, ast.Tuple): |
| 730 | raise ParserSyntaxError( | 780 | raise ParserSyntaxError( |
| 731 | - "Multi-dimensional subscript is not supported", | 781 | + "Multi-dimensional subscript is not supported for tuples", |
| 732 | span=span, | 782 | span=span, |
| 733 | - hint="Use a scalar index like arr[0]", | 783 | + hint="Use a scalar index like tuple[0]", |
| 734 | ) | 784 | ) |
| 735 | - if isinstance(value_type, ir.TupleType): | 785 | + self._check_uniform_tuple_types(value_type, span) |
| 736 | - self._check_uniform_tuple_types(value_type, span) | ||
| 737 | 786 | ||
| 738 | index_expr = self.parse_expression(subscript.slice) | 787 | index_expr = self.parse_expression(subscript.slice) |
| 739 | if ( | 788 | if ( |
| @@ -745,22 +794,17 @@ class ExpressionParserMixin: | |||
| 745 | if 0 <= index < len(value_expr.elements): | 794 | if 0 <= index < len(value_expr.elements): |
| 746 | return value_expr.elements[index] | 795 | return value_expr.elements[index] |
| 747 | 796 | ||
| 748 | - # This GetItem could not be statically evaluated. Restore a named tuple | 797 | + # CCE resolves a non-folded GetItem through the underlying MakeTuple's |
| 749 | - # Var when folding reduced its base to that Var's MakeTuple value, so | 798 | + # backing array. struct_array stays as a Var here because it is not a |
| 750 | - # codegen retains the backing-array identity. This covers runtime indices | 799 | + # parser constant; ordinary tuples may remain folded MakeTuple values. |
| 751 | - # and static accesses that must remain dynamic, including struct arrays. | ||
| 752 | - value_expr = self._restore_tuple_var_for_unfolded_getitem(value_expr) | ||
| 753 | - value_type = value_expr.type | ||
| 754 | item_expr = ir.GetItemExpr(value_expr, index_expr, span) | 800 | item_expr = ir.GetItemExpr(value_expr, index_expr, span) |
| 755 | - # A slice of a tile aliases the tile's buffer, so carry the base's mutex | 801 | + # A subscript aliases the base's buffer, so carry the base's mutex |
| 756 | - # metadata onto the slice. auto_mutex then locks accesses to the slice on | 802 | + # metadata onto the item. auto_mutex then locks accesses to the item on |
| 757 | - # the base's buf_id; it is consumed when the slice is bound to a var (see | 803 | + # the base's buf_id; it is consumed when the item is bound to a var (see |
| 758 | - # _transfer_tile_sync_metadata). Nested slices compose: the inner slice is tagged | 804 | + # _transfer_tile_sync_metadata). |
| 759 | - # from its root here, and the outer one inherits from the (tagged) inner. | 805 | + meta = self._tile_mutex_meta.get(value_expr) |
| 760 | - if isinstance(value_type, ir.TileType): | 806 | + if meta is not None: |
| 761 | - meta = self._tile_mutex_meta.get(value_expr) | 807 | + self._tile_mutex_meta[item_expr] = meta |
| 762 | - if meta is not None: | ||
| 763 | - self._tile_mutex_meta[item_expr] = meta | ||
| 764 | return item_expr | 808 | return item_expr |
| 765 | 809 | ||
| 766 | def _is_const_expr(self, expr: Any) -> bool: | 810 | def _is_const_expr(self, expr: Any) -> bool: |
| @@ -973,17 +1017,227 @@ class ExpressionParserMixin: | |||
| 973 | ) | 1017 | ) |
| 974 | return tensor_type.shape[axis] | 1018 | return tensor_type.shape[axis] |
| 975 | 1019 | ||
| 976 | - def _materialize_nested_call(self, result, span: ir.Span): | 1020 | + def _parse_scalar_subscript_index( |
| 977 | - """Let-bind a Call result when it appears as a sub-expression. | 1021 | + self, |
| 1022 | + container_expr: ir.Expr, | ||
| 1023 | + slice_node: ast.expr, | ||
| 1024 | + span: ir.Span, | ||
| 1025 | + ) -> ir.Expr: | ||
| 1026 | + """Parse A[i, j, ...] into a linear offset expression for getval/setval. | ||
| 978 | 1027 | ||
| 979 | - Only materializes ``ir.Call`` results. All other returns (Var, ConstInt, | 1028 | + Multi-index: A[i, j] → i * N + j (row-major linearization). |
| 980 | - GetItemExpr, MakeTuple, BinaryExpr, raw closure values, etc.) pass | 1029 | + Single index: A[i] → i (only valid for 1D containers). |
| 981 | - through unchanged so existing call sites that rely on non-Call return | 1030 | + """ |
| 982 | - shapes keep working. | 1031 | + container_type = container_expr.type |
| 1032 | + shape = container_type.shape | ||
| 1033 | + | ||
| 1034 | + # Single index A[x]: only valid for 1D containers (rank 1) | ||
| 1035 | + if not isinstance(slice_node, ast.Tuple): | ||
| 1036 | + if len(shape) != 1: | ||
| 1037 | + if self.inline_vf_depth > 0: | ||
| 1038 | + raise ParserSyntaxError( | ||
| 1039 | + f"Tile[x] in VF section is not supported; use `tile + x` for pointer offset", | ||
| 1040 | + span=span, | ||
| 1041 | + hint="Replace `tile[x]` with `tile + x`", | ||
| 1042 | + ) | ||
| 1043 | + raise ParserSyntaxError( | ||
| 1044 | + f"Subscript A[x] requires 1D container, but got rank {len(shape)}; " | ||
| 1045 | + f"use {len(shape)} indices or add ':' for sub-view (Tile)", | ||
| 1046 | + span=span, | ||
| 1047 | + hint=f"Use A[i, j] for scalar access or A[x:, :] for sub-view", | ||
| 1048 | + ) | ||
| 1049 | + return self.parse_expression(slice_node) | ||
| 1050 | + | ||
| 1051 | + # A[i, j, ...] — multi-dimensional coordinate | ||
| 1052 | + elts = slice_node.elts | ||
| 1053 | + | ||
| 1054 | + if len(elts) != len(shape): | ||
| 1055 | + raise ParserTypeError( | ||
| 1056 | + f"Subscript has {len(elts)} indices but container has rank {len(shape)}", | ||
| 1057 | + span=span, | ||
| 1058 | + hint=f"Use {len(shape)} indices to match the container shape", | ||
| 1059 | + ) | ||
| 1060 | + indices = [self.parse_expression(e) for e in elts] | ||
| 1061 | + from pypto_pro.language.parser._utils import _const_int_value | ||
| 1062 | + | ||
| 1063 | + offset = indices[-1] | ||
| 1064 | + stride = shape[-1] | ||
| 1065 | + for dim in range(len(indices) - 2, -1, -1): | ||
| 1066 | + # Fold constant stride into a single ConstInt to avoid mul IR nodes | ||
| 1067 | + stride_val = _const_int_value(stride) | ||
| 1068 | + if stride_val == 1: | ||
| 1069 | + product = indices[dim] | ||
| 1070 | + else: | ||
| 1071 | + product = indices[dim] * stride | ||
| 1072 | + offset = product + offset | ||
| 1073 | + if dim > 0: | ||
| 1074 | + next_shape_val = _const_int_value(shape[dim]) | ||
| 1075 | + cur_stride_val = _const_int_value(stride) | ||
| 1076 | + if next_shape_val is not None and cur_stride_val is not None: | ||
| 1077 | + stride = ir.ConstInt(next_shape_val * cur_stride_val, DataType.INDEX, span) | ||
| 1078 | + else: | ||
| 1079 | + stride = shape[dim] * stride | ||
| 1080 | + return offset | ||
| 1081 | + | ||
| 1082 | + def _parse_slice_subscript( | ||
| 1083 | + self, | ||
| 1084 | + container_expr: ir.Expr, | ||
| 1085 | + slice_node: ast.expr, | ||
| 1086 | + span: ir.Span, | ||
| 1087 | + ) -> ir.Expr: | ||
| 1088 | + """Parse tile[r:, c:] into a block.subview op (Tile only, 2D). | ||
| 1089 | + | ||
| 1090 | + Result tile preserves the original shape (row_stride unchanged); | ||
| 1091 | + codegen auto-emits SetValidShape with the sub-window dimensions. | ||
| 1092 | + - If slice exceeds tile shape → error. | ||
| 1093 | + - If slice exceeds tile valid_shape → clamp to (valid_shape - start). | ||
| 1094 | + """ | ||
| 1095 | + container_type = container_expr.type | ||
| 1096 | + shape = container_type.shape | ||
| 1097 | + | ||
| 1098 | + if isinstance(container_type, ir.TensorType): | ||
| 1099 | + raise ParserSyntaxError( | ||
| 1100 | + "Tensor slice sub-view is not supported", | ||
| 1101 | + span=span, | ||
| 1102 | + hint="Use pl.load/pl.store with offset lists for tensor access", | ||
| 1103 | + ) | ||
| 1104 | + | ||
| 1105 | + if self.inline_vf_depth > 0: | ||
| 1106 | + logging.warning( | ||
| 1107 | + "Tile slice in VF section is lowered to pointer offset only; " | ||
| 1108 | + "shape/valid_shape are ignored. Consider using `tile + offset` instead." | ||
| 1109 | + ) | ||
| 1110 | + | ||
| 1111 | + if not isinstance(slice_node, ast.Tuple): | ||
| 1112 | + raise ParserSyntaxError( | ||
| 1113 | + "1D tile slice is not supported; use 2D slice like tile[i:i+h, j:j+w]", | ||
| 1114 | + span=span, | ||
| 1115 | + hint="Use tile[i:i+h, j:j+w] for sub-view access", | ||
| 1116 | + ) | ||
| 1117 | + | ||
| 1118 | + slices = slice_node.elts | ||
| 1119 | + if len(slices) != len(shape): | ||
| 1120 | + raise ParserTypeError( | ||
| 1121 | + f"Slice subscript has {len(slices)} dimensions but tile has rank {len(shape)}", | ||
| 1122 | + span=span, | ||
| 1123 | + hint=f"Use {len(shape)} indices to match the tile shape", | ||
| 1124 | + ) | ||
| 1125 | + | ||
| 1126 | + from pypto_pro.language.parser._utils import _const_int_value | ||
| 1127 | + | ||
| 1128 | + cols = shape[1] | ||
| 1129 | + # valid_shape for clamping: compile-time (TileType.tile_view) or runtime | ||
| 1130 | + # (set_validshape, tracked by tile var name). | ||
| 1131 | + ct_valid = None | ||
| 1132 | + tile_view = getattr(container_type, 'tile_view', None) | ||
| 1133 | + if tile_view is not None: | ||
| 1134 | + ct_valid = getattr(tile_view, 'valid_shape', None) | ||
| 1135 | + rt_valid = None | ||
| 1136 | + if isinstance(container_expr, ir.Var): | ||
| 1137 | + rt_valid = self.get_tile_valid_shape(container_expr) | ||
| 1138 | + dim_starts = [] | ||
| 1139 | + new_shape_exprs = [] | ||
| 1140 | + | ||
| 1141 | + for i, s in enumerate(slices): | ||
| 1142 | + if not isinstance(s, ast.Slice): | ||
| 1143 | + raise ParserSyntaxError( | ||
| 1144 | + f"Tile slice does not support integer index in dimension {i}", | ||
| 1145 | + span=span, | ||
| 1146 | + hint="Tile slices must use ':' for all dimensions", | ||
| 1147 | + ) | ||
| 1148 | + start = ir.ConstInt(0, DataType.INDEX, span) if s.lower is None else self.parse_expression(s.lower) | ||
| 1149 | + dim_starts.append(start) | ||
| 1150 | + start_val = _const_int_value(start) | ||
| 1151 | + | ||
| 1152 | + # Compute slice size: upper - start (upper defaults to shape[i]). | ||
| 1153 | + # Clamp upper to shape[i] (Python slice semantics): a[16:77] on a | ||
| 1154 | + # length-64 dim becomes a[16:64], not an error. | ||
| 1155 | + upper = shape[i] if s.upper is None else self.parse_expression(s.upper) | ||
| 1156 | + shape_val = _const_int_value(shape[i]) | ||
| 1157 | + upper_val = _const_int_value(upper) | ||
| 1158 | + if shape_val is not None and upper_val is not None and upper_val > shape_val: | ||
| 1159 | + upper = ir.ConstInt(shape_val, DataType.INDEX, span) | ||
| 1160 | + upper_val = shape_val | ||
| 1161 | + size = upper if start_val == 0 else upper - start | ||
| 1162 | + size_val = _const_int_value(size) | ||
| 1163 | + | ||
| 1164 | + # Check against declared shape: start must not exceed shape | ||
| 1165 | + if start_val is not None and shape_val is not None: | ||
| 1166 | + if start_val > shape_val: | ||
| 1167 | + raise ParserSyntaxError( | ||
| 1168 | + f"Tile slice start ({start_val}) exceeds shape dim {i} ({shape_val})", | ||
| 1169 | + span=span, | ||
| 1170 | + hint=f"Slice start must not exceed shape[{i}]", | ||
| 1171 | + ) | ||
| 1172 | + | ||
| 1173 | + for vs in ( | ||
| 1174 | + ct_valid[i] if ct_valid is not None and i < len(ct_valid) else None, | ||
| 1175 | + rt_valid[i] if rt_valid is not None and i < len(rt_valid) else None, | ||
| 1176 | + ): | ||
| 1177 | + if vs is None: | ||
| 1178 | + continue | ||
| 1179 | + vs_val = _const_int_value(vs) | ||
| 1180 | + if vs_val is not None and vs_val >= 0 and start_val is not None: | ||
| 1181 | + remaining = vs_val - start_val | ||
| 1182 | + if remaining < 0: | ||
| 1183 | + raise ParserSyntaxError( | ||
| 1184 | + f"Tile slice start ({start_val}) exceeds valid_shape dim {i} ({vs_val})", | ||
| 1185 | + span=span, | ||
| 1186 | + hint=f"Slice start must not exceed valid_shape[{i}]", | ||
| 1187 | + ) | ||
| 1188 | + if size_val is not None: | ||
| 1189 | + if size_val > remaining: | ||
| 1190 | + size = ir.ConstInt(remaining, DataType.INDEX, span) | ||
| 1191 | + size_val = remaining | ||
| 1192 | + else: | ||
| 1193 | + size = ir.Min(size, ir.ConstInt(remaining, DataType.INDEX, span), DataType.INDEX, span) | ||
| 1194 | + elif vs_val is None and start_val is not None: | ||
| 1195 | + # Dynamic valid_shape: emit runtime clamp min(size, vs - start) | ||
| 1196 | + remaining_expr = vs - start | ||
| 1197 | + size = ir.Min(size, remaining_expr, DataType.INDEX, span) | ||
| 1198 | + | ||
| 1199 | + new_shape_exprs.append(size) | ||
| 1200 | + | ||
| 1201 | + # Linear offset: row_start * cols + col_start | ||
| 1202 | + offset = dim_starts[0] * cols + dim_starts[1] | ||
| 1203 | + | ||
| 1204 | + from pypto_pro.ir.op.block_ops import block_ir_op | ||
| 1205 | + shape_tuple = ir.MakeTuple(new_shape_exprs, span) | ||
| 1206 | + view_expr = ir.create_op_call( | ||
| 1207 | + block_ir_op("subview"), | ||
| 1208 | + [container_expr, offset, shape_tuple], | ||
| 1209 | + {}, | ||
| 1210 | + span, | ||
| 1211 | + ) | ||
| 1212 | + | ||
| 1213 | + # Propagate tile mutex metadata for auto_mutex | ||
| 1214 | + self._transfer_tile_sync_metadata(view_expr, container_expr) | ||
| 1215 | + return view_expr | ||
| 1216 | + | ||
| 1217 | + | ||
| 1218 | + def _mark_make_tuple_anchor(self, result) -> None: | ||
| 1219 | + """Record that a MakeTuple already has an emitted assignment anchor.""" | ||
| 1220 | + if isinstance(result, ir.MakeTuple): | ||
| 1221 | + self._anchored_make_tuples.add(result) | ||
| 1222 | + | ||
| 1223 | + | ||
| 1224 | + def _materialize_nested_expr(self, result, span: ir.Span): | ||
| 1225 | + """Materialize nested Calls and anchor nested MakeTuples. | ||
| 1226 | + | ||
| 1227 | + Calls return their temporary Var as before. A MakeTuple instead keeps its | ||
| 1228 | + expression result: the temporary let is only a CCE backing-array anchor, | ||
| 1229 | + so callers can continue folding the enclosing expression. | ||
| 983 | 1230 | ||
| 984 | Skips Calls with UnknownType to avoid materializing void/sentinel | 1231 | Skips Calls with UnknownType to avoid materializing void/sentinel |
| 985 | results (e.g. nbuf.advance() void calls). | 1232 | results (e.g. nbuf.advance() void calls). |
| 986 | """ | 1233 | """ |
| 1234 | + if isinstance(result, ir.MakeTuple): | ||
| 1235 | + if result not in self._anchored_make_tuples: | ||
| 1236 | + name = f"_tuple_anchor_{self._expr_tmp_counter}" | ||
| 1237 | + self._expr_tmp_counter += 1 | ||
| 1238 | + self.builder.let(name, result, span=span) | ||
| 1239 | + self._mark_make_tuple_anchor(result) | ||
| 1240 | + return result | ||
| 987 | if not isinstance(result, ir.Call): | 1241 | if not isinstance(result, ir.Call): |
| 988 | return result | 1242 | return result |
| 989 | if isinstance(result.type, ir.UnknownType): | 1243 | if isinstance(result.type, ir.UnknownType): |
| @@ -992,6 +1246,7 @@ class ExpressionParserMixin: | |||
| 992 | self._expr_tmp_counter += 1 | 1246 | self._expr_tmp_counter += 1 |
| 993 | value = self.builder.let(name, result, span=span) | 1247 | value = self.builder.let(name, result, span=span) |
| 994 | self._transfer_tile_sync_metadata(value, result) | 1248 | self._transfer_tile_sync_metadata(value, result) |
| 1249 | + self._emit_auto_mutex_unlocks() | ||
| 995 | return value | 1250 | return value |
| 996 | 1251 | ||
| 997 | def _route_ir_node_method(self, node: ast.Call): | 1252 | def _route_ir_node_method(self, node: ast.Call): |
| @@ -35,6 +35,7 @@ class ScopeManager: | |||
| 35 | self.assignments: dict[str, int] = {} # Track assignment count per variable | 35 | self.assignments: dict[str, int] = {} # Track assignment count per variable |
| 36 | self.scope_types: list[str] = ["global"] # Track type of each scope | 36 | self.scope_types: list[str] = ["global"] # Track type of each scope |
| 37 | self.var_spans: list[dict[str, Span]] = [{}] # Track span for each variable definition | 37 | self.var_spans: list[dict[str, Span]] = [{}] # Track span for each variable definition |
| 38 | + self.mask_reg_vars: set[str] = set() # Variable names declared as MaskReg | ||
| 38 | 39 | ||
| 39 | def enter_scope(self, scope_type: str) -> None: | 40 | def enter_scope(self, scope_type: str) -> None: |
| 40 | """Enter a new scope. | 41 | """Enter a new scope. |
| @@ -71,6 +72,19 @@ class ScopeManager: | |||
| 71 | 72 | ||
| 72 | return scope_vars | 73 | return scope_vars |
| 73 | 74 | ||
| 75 | + def register_mask_reg_var(self, name: str) -> None: | ||
| 76 | + """Mark a variable as a MaskReg (mask register). | ||
| 77 | + | ||
| 78 | + Called when a variable is declared via vf.mask_reg, vf.create_mask, | ||
| 79 | + vf.update_mask, or any op whose dst is inferred to be MaskReg. | ||
| 80 | + Enables input-type-based dst inference for unified ops. | ||
| 81 | + """ | ||
| 82 | + self.mask_reg_vars.add(name) | ||
| 83 | + | ||
| 84 | + def is_mask_reg_var(self, name: str) -> bool: | ||
| 85 | + """Return True if the variable was declared as a MaskReg.""" | ||
| 86 | + return name in self.mask_reg_vars | ||
| 87 | + | ||
| 74 | def define_var(self, name: str, value: Any, allow_redef: bool = False, span: Any | None = None) -> None: | 88 | def define_var(self, name: str, value: Any, allow_redef: bool = False, span: Any | None = None) -> None: |
| 75 | """Define a variable in the current scope. | 89 | """Define a variable in the current scope. |
| 76 | 90 | ||
| @@ -607,6 +607,11 @@ def _handle_block_op(node: ast.Call, slot_to_buffer, cross_buffers, all_buffer_m | |||
| 607 | roles = _BLOCK_OP_TILE_ROLES.get(op_name) | 607 | roles = _BLOCK_OP_TILE_ROLES.get(op_name) |
| 608 | if roles is None: | 608 | if roles is None: |
| 609 | return | 609 | return |
| 610 | + if op_name == "fillpad": | ||
| 611 | + for kw in node.keywords: | ||
| 612 | + if kw.arg == "mode" and isinstance(kw.value, ast.Attribute) and kw.value.attr == "INPLACE": | ||
| 613 | + roles = _BLOCK_OP_TILE_ROLES["fillpad_inplace"] | ||
| 614 | + break | ||
| 610 | pipe = None | 615 | pipe = None |
| 611 | for argpos, arg in enumerate(node.args): | 616 | for argpos, arg in enumerate(node.args): |
| 612 | buf = _tile_arg_buffer(arg, slot_to_buffer) | 617 | buf = _tile_arg_buffer(arg, slot_to_buffer) |
| @@ -620,10 +620,18 @@ void BindTypeClass(py::module_& ir) | |||
| 620 | .value("EQ", ir::CompareMode::EQ) | 620 | .value("EQ", ir::CompareMode::EQ) |
| 621 | .value("NE", ir::CompareMode::NE) | 621 | .value("NE", ir::CompareMode::NE) |
| 622 | .value("LT", ir::CompareMode::LT) | 622 | .value("LT", ir::CompareMode::LT) |
| 623 | - .value("GT", ir::CompareMode::GT) | ||
| 624 | .value("LE", ir::CompareMode::LE) | 623 | .value("LE", ir::CompareMode::LE) |
| 624 | + .value("GT", ir::CompareMode::GT) | ||
| 625 | .value("GE", ir::CompareMode::GE); | 625 | .value("GE", ir::CompareMode::GE); |
| 626 | 626 | ||
| 627 | + py::enum_<ir::CmpMode>(ir, "CmpMode", "Comparison mode for block.cmp/cmps (isa TCMP/TCMPS)") | ||
| 628 | + .value("EQ", ir::CmpMode::EQ) | ||
| 629 | + .value("NE", ir::CmpMode::NE) | ||
| 630 | + .value("LT", ir::CmpMode::LT) | ||
| 631 | + .value("LE", ir::CmpMode::LE) | ||
| 632 | + .value("GT", ir::CmpMode::GT) | ||
| 633 | + .value("GE", ir::CmpMode::GE); | ||
| 634 | + | ||
| 627 | py::enum_<ir::DuplicatePos>(ir, "DuplicatePos", "Position for vf.full") | 635 | py::enum_<ir::DuplicatePos>(ir, "DuplicatePos", "Position for vf.full") |
| 628 | .value("LOWEST", ir::DuplicatePos::LOWEST) | 636 | .value("LOWEST", ir::DuplicatePos::LOWEST) |
| 629 | .value("HIGHEST", ir::DuplicatePos::HIGHEST); | 637 | .value("HIGHEST", ir::DuplicatePos::HIGHEST); |
| @@ -725,15 +733,6 @@ void BindTypeClass(py::module_& ir) | |||
| 725 | .value("VS_ALL", ir::MemBarMode::VS_ALL) | 733 | .value("VS_ALL", ir::MemBarMode::VS_ALL) |
| 726 | .value("SV_ALL", ir::MemBarMode::SV_ALL); | 734 | .value("SV_ALL", ir::MemBarMode::SV_ALL); |
| 727 | 735 | ||
| 728 | - py::enum_<ir::MaskLoadDist>(ir, "MaskLoadDist", "Load distribution for vf.mask_load / pld/plds") | ||
| 729 | - .value("NORM", ir::MaskLoadDist::NORM) | ||
| 730 | - .value("US", ir::MaskLoadDist::US) | ||
| 731 | - .value("DS", ir::MaskLoadDist::DS); | ||
| 732 | - | ||
| 733 | - py::enum_<ir::MaskStoreDist>(ir, "MaskStoreDist", "Store distribution for vf.mask_store / pst/psts") | ||
| 734 | - .value("NORM", ir::MaskStoreDist::NORM) | ||
| 735 | - .value("PK", ir::MaskStoreDist::PK); | ||
| 736 | - | ||
| 737 | // HardwareInfo - struct for hardware-specific tile information | 736 | // HardwareInfo - struct for hardware-specific tile information |
| 738 | py::class_<HardwareInfo>(ir, "HardwareInfo", "Hardware-specific tile information (layout, fractal, pad, compact)") | 737 | py::class_<HardwareInfo>(ir, "HardwareInfo", "Hardware-specific tile information (layout, fractal, pad, compact)") |
| 739 | .def(py::init<>(), "Create a default hardware info") | 738 | .def(py::init<>(), "Create a default hardware info") |


🟠 High Priority
在
MakeBlockSubviewCodegenCCE函数中,tile_type(第 1697 行通过ir::As<ir::TileType>获取)在第 1698 行被直接解引用调用tile_type->dtype_.GetBit(),但未检查其是否为空指针。若op->args_[0]的类型不是TileType,ir::As将返回nullptr,触发段错误。类似的,
shape_tuple(第 1717 行通过ir::As<ir::MakeTuple>获取)在第 1718 行被直接解引用访问shape_tuple->elements_[0],同样没有空指针检查。若op->args_[2]不是MakeTuple类型,也会导致崩溃。触发条件:当 IR 格式异常或上层传递了错误类型的参数时,代码生成阶段将崩溃而非给出可诊断的错误信息。同一文件中其他类似模式(如第 1707 行
INTERNAL_CHECK(tile_type->memref_.has_value()))至少对memref_做了检查,但tile_type自身和shape_tuple缺少保护。建议:在访问
tile_type成员之前添加INTERNAL_CHECK(tile_type)空指针断言;同样在第 1717 行后添加INTERNAL_CHECK(shape_tuple)断言。intelem_bytes=std::max(1,static_cast<int>(tile_type->dtype_.GetBit()/ 8));