Merged
feat(ir): Replace SourceLocation with ir::Span #3135
lidongshengAdd on May 10
feat(ir): Replace SourceLocation with ir::Span #3135
Merged
lidongshengAdd on May 10
Total: 62 files changed+1355-884
@@ -103,6 +103,7 @@ public:
103 static const DataType FP8; // 8-bit floating point (backward compatibility alias)103 static const DataType FP8; // 8-bit floating point (backward compatibility alias)
104 static const DataType FP16; // 16-bit floating point (IEEE 754 half precision)104 static const DataType FP16; // 16-bit floating point (IEEE 754 half precision)
105 static const DataType FP32; // 32-bit floating point (IEEE 754 single precision)105 static const DataType FP32; // 32-bit floating point (IEEE 754 single precision)
106+ static const DataType FP64; // 64-bit floating point (IEEE 754 double precision)
106 static const DataType BF16; // 16-bit brain floating point107 static const DataType BF16; // 16-bit brain floating point
107 static const DataType HF4; // 4-bit Hisilicon float108 static const DataType HF4; // 4-bit Hisilicon float
108 static const DataType HF8; // 8-bit Hisilicon float109 static const DataType HF8; // 8-bit Hisilicon float
@@ -154,6 +155,7 @@ public:
154 return 32;155 return 32;
155 case kUInt64Code:156 case kUInt64Code:
156 case kInt64Code:157 case kInt64Code:
158+ case kFp64Code:
157 case kIndexCode:159 case kIndexCode:
158 return 64;160 return 64;
159 default:161 default:
@@ -201,6 +203,8 @@ public:
201 return "fp16";203 return "fp16";
202 case kFp32Code:204 case kFp32Code:
203 return "fp32";205 return "fp32";
206+ case kFp64Code:
207+ return "fp64";
204 case kBf16Code:208 case kBf16Code:
205 return "bfloat16";209 return "bfloat16";
206 case kHf4Code:210 case kHf4Code:
@@ -339,6 +343,7 @@ inline constexpr DataType DataType::FP8E5M2 = DataType(kFp8e5m2Code);
339inline constexpr DataType DataType::FP8 = DataType(kFp8Code);343inline constexpr DataType DataType::FP8 = DataType(kFp8Code);
340inline constexpr DataType DataType::FP16 = DataType(kFp16Code);344inline constexpr DataType DataType::FP16 = DataType(kFp16Code);
341inline constexpr DataType DataType::FP32 = DataType(kFp32Code);345inline constexpr DataType DataType::FP32 = DataType(kFp32Code);
346+inline constexpr DataType DataType::FP64 = DataType(kFp64Code);
342inline constexpr DataType DataType::BF16 = DataType(kBf16Code);347inline constexpr DataType DataType::BF16 = DataType(kBf16Code);
343inline constexpr DataType DataType::HF4 = DataType(kHf4Code);348inline constexpr DataType DataType::HF4 = DataType(kHf4Code);
344inline constexpr DataType DataType::HF8 = DataType(kHf8Code);349inline constexpr DataType DataType::HF8 = DataType(kHf8Code);
@@ -393,6 +398,8 @@ inline std::string DTypeToString(const DataType& dtype)
393 return "FP16";398 return "FP16";
394 if (dtype == DataType::FP32)399 if (dtype == DataType::FP32)
395 return "FP32";400 return "FP32";
401+ if (dtype == DataType::FP64)
402+ return "FP64";
396 if (dtype == DataType::BF16)403 if (dtype == DataType::BF16)
397 return "BF16";404 return "BF16";
398 if (dtype == DataType::HF4)405 if (dtype == DataType::HF4)
@@ -545,7 +545,7 @@ inline std::string FormatLogMessage(const char* fmt, ...)
545#define LOG_EVENT_F(fmt, args...) LOG_F(EVENT, fmt, ##args)545#define LOG_EVENT_F(fmt, args...) LOG_F(EVENT, fmt, ##args)
546 546 
547/**547/**
548- * \brief Helper class for CHECK, INTERNAL_CHECK, UNREACHABLE, and INTERNAL_UNREACHABLE macros548+ * \brief Helper class for IRCHECK, INTERNAL_CHECK, UNREACHABLE, and INTERNAL_UNREACHABLE macros
549 *549 *
550 * This class collects error messages via operator<< and throws550 * This class collects error messages via operator<< and throws
551 * an exception on destruction if the check condition failed.551 * an exception on destruction if the check condition failed.
@@ -555,7 +555,7 @@ inline std::string FormatLogMessage(const char* fmt, ...)
555template <typename ExceptionType>555template <typename ExceptionType>
556class FatalLogger;556class FatalLogger;
557 557 
558-// Specialization for conditional checks (CHECK, INTERNAL_CHECK)558+// Specialization for conditional checks (IRCHECK, INTERNAL_CHECK)
559template <typename ExceptionType>559template <typename ExceptionType>
560class FatalLogger {560class FatalLogger {
561private:561private:
@@ -592,10 +592,10 @@ public:
592/**592/**
593 * \brief Check a condition and throw ValueError if it fails593 * \brief Check a condition and throw ValueError if it fails
594 *594 *
595- * Usage: CHECK(condition) << "error message";595+ * Usage: IRCHECK(condition) << "error message";
596 */596 */
597-#define CHECK(expr) \597+#define IRCHECK(expr) \
598- if (!(expr)) \598+ if (!(expr)) \
599 pypto::FatalLogger<pypto::ir::ValueError>(#expr, __FILE__, __LINE__)599 pypto::FatalLogger<pypto::ir::ValueError>(#expr, __FILE__, __LINE__)
600 600 
601/**601/**
@@ -630,5 +630,5 @@ public:
630 if (!!(expr)) \630 if (!!(expr)) \
631 ; \631 ; \
632 else \632 else \
633- pypto::FatalLogger<pypto::ir::InternalError>(#expr, span.filename_.c_str(), span.beginLine_)633+ pypto::FatalLogger<pypto::ir::InternalError>(#expr, span.Filename().c_str(), span.BeginLine())
634} // namespace pypto634} // namespace pypto
@@ -88,6 +88,9 @@ enum class ObjectKind {
88 BreakStmt,88 BreakStmt,
89 ContinueStmt,89 ContinueStmt,
90 90 
91+ ScalarOpStmt,
92+ TensorOpStmt,
93+ 
91 // Type kinds94 // Type kinds
92 UnknownType,95 UnknownType,
93 MemRefType,96 MemRefType,
@@ -96,6 +99,7 @@ enum class ObjectKind {
96 ShapedType,99 ShapedType,
97 TensorType,100 TensorType,
98 TileType,101 TileType,
102+ TokenType,
99 TupleType,103 TupleType,
100 104 
101 // Other IR node kinds105 // Other IR node kinds
@@ -123,8 +123,8 @@ public:
123 [[nodiscard]] std::type_index GetAttrType(const std::string& key, const Span& span = Span::Unknown()) const123 [[nodiscard]] std::type_index GetAttrType(const std::string& key, const Span& span = Span::Unknown()) const
124 {124 {
125 auto it = attrs_.find(key);125 auto it = attrs_.find(key);
126- CHECK(it != attrs_.end()) << "Attribute '" << key << "' not found in operator '" << name_ << "'"126+ IRCHECK(it != attrs_.end()) << "Attribute '" << key << "' not found in operator '" << name_ << "'"
127- << " at " << span.ToString();127+ << " at " << span.ToString();
128 return it->second;128 return it->second;
129 }129 }
130 130 
@@ -86,6 +86,8 @@ DEFINE_KIND_TRAIT(EvalStmt, ObjectKind::EvalStmt)
86DEFINE_KIND_TRAIT(WhileStmt, ObjectKind::WhileStmt)86DEFINE_KIND_TRAIT(WhileStmt, ObjectKind::WhileStmt)
87DEFINE_KIND_TRAIT(BreakStmt, ObjectKind::BreakStmt)87DEFINE_KIND_TRAIT(BreakStmt, ObjectKind::BreakStmt)
88DEFINE_KIND_TRAIT(ContinueStmt, ObjectKind::ContinueStmt)88DEFINE_KIND_TRAIT(ContinueStmt, ObjectKind::ContinueStmt)
89+DEFINE_KIND_TRAIT(ScalarOpStmt, ObjectKind::ScalarOpStmt)
90+DEFINE_KIND_TRAIT(TensorOpStmt, ObjectKind::TensorOpStmt)
89 91 
90// Type types92// Type types
91DEFINE_KIND_TRAIT(UnknownType, ObjectKind::UnknownType)93DEFINE_KIND_TRAIT(UnknownType, ObjectKind::UnknownType)
@@ -96,6 +98,7 @@ DEFINE_KIND_TRAIT(TileType, ObjectKind::TileType)
96DEFINE_KIND_TRAIT(TupleType, ObjectKind::TupleType)98DEFINE_KIND_TRAIT(TupleType, ObjectKind::TupleType)
97DEFINE_KIND_TRAIT(MemRefType, ObjectKind::MemRefType)99DEFINE_KIND_TRAIT(MemRefType, ObjectKind::MemRefType)
98DEFINE_KIND_TRAIT(PtrType, ObjectKind::PtrType)100DEFINE_KIND_TRAIT(PtrType, ObjectKind::PtrType)
101+DEFINE_KIND_TRAIT(TokenType, ObjectKind::TokenType)
99 102 
100// Other IR node types103// Other IR node types
101DEFINE_KIND_TRAIT(Function, ObjectKind::Function)104DEFINE_KIND_TRAIT(Function, ObjectKind::Function)
@@ -113,11 +116,11 @@ DEFINE_KIND_TRAIT(GlobalVar, ObjectKind::GlobalVar)
113// Stmt base class - matches any statement kind116// Stmt base class - matches any statement kind
114template <>117template <>
115struct KindTrait<Stmt> {118struct KindTrait<Stmt> {
116- static constexpr ObjectKind kinds[] = {ObjectKind::AssignStmt, ObjectKind::IfStmt, ObjectKind::YieldStmt,119+ static constexpr ObjectKind kinds[] = {
117- ObjectKind::ReturnStmt, ObjectKind::ForStmt, ObjectKind::WhileStmt,120+ ObjectKind::AssignStmt, ObjectKind::IfStmt, ObjectKind::YieldStmt, ObjectKind::ReturnStmt,
118- ObjectKind::SeqStmts, ObjectKind::EvalStmt, ObjectKind::BreakStmt,121+ ObjectKind::ForStmt, ObjectKind::WhileStmt, ObjectKind::SeqStmts, ObjectKind::EvalStmt,
119- ObjectKind::ContinueStmt};122+ ObjectKind::BreakStmt, ObjectKind::ContinueStmt, ObjectKind::ScalarOpStmt, ObjectKind::TensorOpStmt};
120- static constexpr size_t count = 10;123+ static constexpr size_t count = 12;
121};124};
122 125 
123// Expr base class - matches any expression kind126// Expr base class - matches any expression kind
@@ -163,7 +166,8 @@ struct KindTrait<UnaryExpr> {
163template <>166template <>
164struct KindTrait<Type> {167struct KindTrait<Type> {
165 static constexpr ObjectKind kinds[] = {ObjectKind::UnknownType, ObjectKind::ScalarType, ObjectKind::ShapedType,168 static constexpr ObjectKind kinds[] = {ObjectKind::UnknownType, ObjectKind::ScalarType, ObjectKind::ShapedType,
166- ObjectKind::TensorType, ObjectKind::TileType, ObjectKind::TupleType};169+ ObjectKind::TensorType, ObjectKind::TileType, ObjectKind::TupleType,
170+ ObjectKind::TokenType};
167 static constexpr size_t count = sizeof(kinds) / sizeof(ObjectKind);171 static constexpr size_t count = sizeof(kinds) / sizeof(ObjectKind);
168};172};
169 173 
@@ -41,8 +41,8 @@ inline DataType GetScalarDtype(const ExprPtr& expr, const Span& span = Span::Unk
41 // Note: Must use dynamic_pointer_cast here because this header is included before41 // Note: Must use dynamic_pointer_cast here because this header is included before
42 // the TypePtr overload of As<> is defined in kind_traits.h42 // the TypePtr overload of As<> is defined in kind_traits.h
43 auto scalarType = std::dynamic_pointer_cast<const ScalarType>(expr->GetType());43 auto scalarType = std::dynamic_pointer_cast<const ScalarType>(expr->GetType());
44- CHECK(scalarType) << "Expression must be Var with ScalarType, got " << expr->TypeName() << " with type "44+ IRCHECK(scalarType) << "Expression must be Var with ScalarType, got " << expr->TypeName() << " with type "
45- << expr->GetType()->TypeName() << " at " << span.ToString();45+ << expr->GetType()->TypeName() << " at " << span.ToString();
46 return scalarType->dtype_;46 return scalarType->dtype_;
47}47}
48 48 
@@ -62,8 +62,8 @@ inline ScalarCategory GetNumericCategory(
62 if (dtype.IsInt()) {62 if (dtype.IsInt()) {
63 return ScalarCategory::INT;63 return ScalarCategory::INT;
64 }64 }
65- CHECK(false) << "Operator '" << opName << "' requires numeric scalar dtype, got " << dtype.ToString() << " at "65+ IRCHECK(false) << "Operator '" << opName << "' requires numeric scalar dtype, got " << dtype.ToString() << " at "
66- << span.ToString();66+ << span.ToString();
67 return ScalarCategory::INT; // unreachable, suppress compiler warning67 return ScalarCategory::INT; // unreachable, suppress compiler warning
68}68}
69 69 
@@ -71,14 +71,14 @@ inline DataType PromoteSameCategoryDtype(
71 const DataType& leftDtype, const DataType& rightDtype, const std::string& opName,71 const DataType& leftDtype, const DataType& rightDtype, const std::string& opName,
72 const Span& span = Span::Unknown())72 const Span& span = Span::Unknown())
73{73{
74- CHECK(!IsBoolDtype(leftDtype) && !IsBoolDtype(rightDtype))74+ IRCHECK(!IsBoolDtype(leftDtype) && !IsBoolDtype(rightDtype))
75 << "Operator '" << opName << "' does not accept bool dtype"75 << "Operator '" << opName << "' does not accept bool dtype"
76 << " at " << span.ToString();76 << " at " << span.ToString();
77 auto leftCategory = GetNumericCategory(leftDtype, opName, span);77 auto leftCategory = GetNumericCategory(leftDtype, opName, span);
78 auto rightCategory = GetNumericCategory(rightDtype, opName, span);78 auto rightCategory = GetNumericCategory(rightDtype, opName, span);
79- CHECK(leftCategory == rightCategory) << "Operator '" << opName << "' requires same numeric dtype category, got "79+ IRCHECK(leftCategory == rightCategory)
80- << leftDtype.ToString() << " and " << rightDtype.ToString() << " at "80+ << "Operator '" << opName << "' requires same numeric dtype category, got " << leftDtype.ToString() << " and "
81- << span.ToString();81+ << rightDtype.ToString() << " at " << span.ToString();
82 size_t leftBits = leftDtype.GetBit();82 size_t leftBits = leftDtype.GetBit();
83 size_t rightBits = rightDtype.GetBit();83 size_t rightBits = rightDtype.GetBit();
84 if (leftBits > rightBits) {84 if (leftBits > rightBits) {
@@ -119,7 +119,7 @@ inline BinaryOperands PromoteIntBinaryOperands(
119{119{
120 DataType leftDtype = GetScalarDtype(left, span);120 DataType leftDtype = GetScalarDtype(left, span);
121 DataType rightDtype = GetScalarDtype(right, span);121 DataType rightDtype = GetScalarDtype(right, span);
122- CHECK(leftDtype.IsInt() && rightDtype.IsInt())122+ IRCHECK(leftDtype.IsInt() && rightDtype.IsInt())
123 << "Operator '" << opName << "' requires integer dtype, got " << leftDtype.ToString() << " and "123 << "Operator '" << opName << "' requires integer dtype, got " << leftDtype.ToString() << " and "
124 << rightDtype.ToString() << " at " << span.ToString();124 << rightDtype.ToString() << " at " << span.ToString();
125 DataType promotedDtype = PromoteSameCategoryDtype(leftDtype, rightDtype, opName, span);125 DataType promotedDtype = PromoteSameCategoryDtype(leftDtype, rightDtype, opName, span);
@@ -251,8 +251,8 @@ inline ExprPtr MakeNeg(const ExprPtr& operand, const Span& span = Span::Unknown(
251inline ExprPtr MakeBitNot(const ExprPtr& operand, const Span& span = Span::Unknown())251inline ExprPtr MakeBitNot(const ExprPtr& operand, const Span& span = Span::Unknown())
252{252{
253 DataType dtype = GetScalarDtype(operand, span);253 DataType dtype = GetScalarDtype(operand, span);
254- CHECK(dtype.IsInt()) << "Operator 'bit_not' requires integer dtype, got " << dtype.ToString() << " at "254+ IRCHECK(dtype.IsInt()) << "Operator 'bit_not' requires integer dtype, got " << dtype.ToString() << " at "
255- << span.ToString();255+ << span.ToString();
256 return std::make_shared<BitNot>(operand, dtype, span);256 return std::make_shared<BitNot>(operand, dtype, span);
257}257}
258 258 
@@ -23,6 +23,8 @@
23namespace pypto {23namespace pypto {
24namespace ir {24namespace ir {
25 25 
26+class SpanImpl;
27+ 
26/**28/**
27 * \brief Represents a source code location span29 * \brief Represents a source code location span
28 *30 *
@@ -36,11 +38,15 @@ namespace ir {
36 */38 */
37class Span {39class Span {
38public:40public:
39- const std::string filename_; ///< Source filename41+ Span();
40- const int beginLine_; ///< Beginning line number (1-indexed)42+ 
41- const int beginColumn_; ///< Beginning column number (1-indexed)43+ Span(const Span& other);
42- const int endLine_; ///< Ending line number (1-indexed), -1 means unknown44+ 
43- const int endColumn_; ///< Ending column number (1-indexed), -1 means unknown45+ Span& operator=(const Span& other);
46+ 
47+ Span(Span&& other);
48+ 
49+ Span& operator=(Span&& other);
44 50 
45 /**51 /**
46 * \brief Construct a source span52 * \brief Construct a source span
@@ -51,21 +57,62 @@ public:
51 * \param endLine End line (1-indexed), -1 means unknown57 * \param endLine End line (1-indexed), -1 means unknown
52 * \param endColumn End column (1-indexed), -1 means unknown58 * \param endColumn End column (1-indexed), -1 means unknown
53 */59 */
54- Span(std::string file, int beginLine, int beginColumn, int endLine = -1, int endColumn = -1);60+ Span(const std::string& file, int beginLine, int beginColumn, int endLine = -1, int endColumn = -1);
61+ 
62+ ~Span();
63+ 
64+ /**
65+ * \brief Get the source filename
66+ *
67+ * \return Source filename
68+ */
69+ const std::string& Filename() const;
70+ 
71+ /**
72+ * \brief Get the beginning line number (1-indexed)
73+ *
74+ * \return Beginning line number
75+ */
76+ int BeginLine() const;
77+ 
78+ /**
79+ * \brief Get the beginning column number (1-indexed)
80+ *
81+ * \return Beginning column number
82+ */
83+ int BeginColumn() const;
84+ 
85+ /**
86+ * \brief Get the ending line number (1-indexed)
87+ *
88+ * \return Ending line number
89+ */
90+ int EndLine() const;
91+ 
92+ /**
93+ * \brief Get the ending column number (1-indexed)
94+ *
95+ * \return Ending column number
96+ */
97+ int EndColumn() const;
55 98 
56 /**99 /**
57 * \brief Convert span to string representation100 * \brief Convert span to string representation
58 *101 *
59 * \return String in format "filename:begin_line:begin_column"102 * \return String in format "filename:begin_line:begin_column"
60 */103 */
61- [[nodiscard]] std::string ToString() const;104+ std::string ToString() const;
62 105 
63 /**106 /**
64 * \brief Check if the span is valid (has valid line/column numbers)107 * \brief Check if the span is valid (has valid line/column numbers)
65 *108 *
66 * \return true if all line/column numbers are positive109 * \return true if all line/column numbers are positive
67 */110 */
68- static bool IsUnknown(const Span& span);111+ bool IsUnknown() const
112+ {
113+ static Span unknown = Unknown();
114+ return impl_ == unknown.impl_;
115+ }
69 116 
70 /**117 /**
71 * \brief Create an unknown/invalid span118 * \brief Create an unknown/invalid span
@@ -73,6 +120,15 @@ public:
73 * \return Span with empty filename and invalid coordinates120 * \return Span with empty filename and invalid coordinates
74 */121 */
75 static Span& Unknown();122 static Span& Unknown();
123+ 
124+ static void SetCurrent(const Span& span);
125+ 
126+ static Span& Current();
127+ 
128+ static void ClearCurrent() { SetCurrent(Unknown()); }
129+ 
130+private:
131+ SpanImpl* impl_;
76};132};
77 133 
78} // namespace ir134} // namespace ir
@@ -493,12 +493,19 @@ using EvalStmtPtr = std::shared_ptr<const EvalStmt>;
493 */493 */
494class BreakStmt : public Stmt {494class BreakStmt : public Stmt {
495public:495public:
496+ std::vector<ExprPtr> value_;
497+ 
498+ BreakStmt(std::vector<ExprPtr> value, Span span) : Stmt(std::move(span)), value_(std::move(value)) {}
496 explicit BreakStmt(Span span) : Stmt(std::move(span)) {}499 explicit BreakStmt(Span span) : Stmt(std::move(span)) {}
497 500 
498 [[nodiscard]] ObjectKind GetKind() const override { return ObjectKind::BreakStmt; }501 [[nodiscard]] ObjectKind GetKind() const override { return ObjectKind::BreakStmt; }
499 [[nodiscard]] std::string TypeName() const override { return "BreakStmt"; }502 [[nodiscard]] std::string TypeName() const override { return "BreakStmt"; }
500 503 
501- static constexpr auto GetFieldDescriptors() { return Stmt::GetFieldDescriptors(); }504+ static constexpr auto GetFieldDescriptors()
505+ {
506+ return std::tuple_cat(
507+ Stmt::GetFieldDescriptors(), std::make_tuple(reflection::UsualField(&BreakStmt::value_, "value")));
508+ }
502};509};
503 510 
504using BreakStmtPtr = std::shared_ptr<const BreakStmt>;511using BreakStmtPtr = std::shared_ptr<const BreakStmt>;
@@ -510,15 +517,101 @@ using BreakStmtPtr = std::shared_ptr<const BreakStmt>;
510 */517 */
511class ContinueStmt : public Stmt {518class ContinueStmt : public Stmt {
512public:519public:
520+ std::vector<ExprPtr> value_;
521+ 
522+ ContinueStmt(std::vector<ExprPtr> value, Span span) : Stmt(std::move(span)), value_(std::move(value)) {}
513 explicit ContinueStmt(Span span) : Stmt(std::move(span)) {}523 explicit ContinueStmt(Span span) : Stmt(std::move(span)) {}
514 524 
515 [[nodiscard]] ObjectKind GetKind() const override { return ObjectKind::ContinueStmt; }525 [[nodiscard]] ObjectKind GetKind() const override { return ObjectKind::ContinueStmt; }
516 [[nodiscard]] std::string TypeName() const override { return "ContinueStmt"; }526 [[nodiscard]] std::string TypeName() const override { return "ContinueStmt"; }
517 527 
518- static constexpr auto GetFieldDescriptors() { return Stmt::GetFieldDescriptors(); }528+ static constexpr auto GetFieldDescriptors()
529+ {
530+ return std::tuple_cat(
531+ Stmt::GetFieldDescriptors(), std::make_tuple(reflection::UsualField(&ContinueStmt::value_, "value")));
532+ }
519};533};
520 534 
521using ContinueStmtPtr = std::shared_ptr<const ContinueStmt>;535using ContinueStmtPtr = std::shared_ptr<const ContinueStmt>;
522 536 
537+class ScalarOpStmt : public Stmt {
538+public:
539+ VarPtr result_;
540+ VarPtr result_token_;
541+ std::string opcode_;
542+ std::vector<ExprPtr> args_;
543+ 
544+ ScalarOpStmt(VarPtr result, VarPtr result_token, std::string opcode, std::vector<ExprPtr> args, Span span)
545+ : Stmt(std::move(span)),
546+ result_(std::move(result)),
547+ result_token_(std::move(result_token)),
548+ opcode_(std::move(opcode)),
549+ args_(std::move(args))
550+ {}
551+ 
552+ [[nodiscard]] ObjectKind GetKind() const override { return ObjectKind::ScalarOpStmt; }
553+ [[nodiscard]] std::string TypeName() const override { return "ScalarOpStmt"; }
554+ 
555+ /**
556+ * \brief Get field descriptors for reflection-based visitation
557+ *
558+ * \return Tuple of field descriptors (var and value as DEF and USUAL fields)
559+ */
560+ static constexpr auto GetFieldDescriptors()
561+ {
562+ auto newFields = std::make_tuple(
563+ reflection::DefField(&ScalarOpStmt::result_, "result"),
564+ reflection::UsualField(&ScalarOpStmt::result_token_, "result_token"),
565+ reflection::UsualField(&ScalarOpStmt::opcode_, "opcode"),
566+ reflection::UsualField(&ScalarOpStmt::args_, "args"));
567+ return std::tuple_cat(Stmt::GetFieldDescriptors(), newFields);
568+ }
569+};
570+ 
571+using ScalarOpStmtPtr = std::shared_ptr<const ScalarOpStmt>;
572+ 
573+class TensorOpStmt : public Stmt {
574+public:
575+ std::vector<VarPtr> result_;
576+ VarPtr result_token_;
577+ std::string opcode_;
578+ std::vector<ExprPtr> args_;
579+ std::vector<ExprPtr> tokens_;
580+ std::vector<std::pair<std::string, std::any>> attrs_;
581+ 
582+ TensorOpStmt(
583+ std::vector<VarPtr> result, VarPtr result_token, std::string opcode, std::vector<ExprPtr> args,
584+ std::vector<ExprPtr> tokens, std::vector<std::pair<std::string, std::any>> attrs, Span span)
585+ : Stmt(std::move(span)),
586+ result_(std::move(result)),
587+ result_token_(std::move(result_token)),
588+ opcode_(std::move(opcode)),
589+ args_(std::move(args)),
590+ tokens_(std::move(tokens)),
591+ attrs_(std::move(attrs))
592+ {}
593+ 
594+ [[nodiscard]] ObjectKind GetKind() const override { return ObjectKind::TensorOpStmt; }
595+ [[nodiscard]] std::string TypeName() const override { return "TensorOpStmt"; }
596+ 
597+ /**
598+ * \brief Get field descriptors for reflection-based visitation
599+ *
600+ * \return Tuple of field descriptors (var and value as DEF and USUAL fields)
601+ */
602+ static constexpr auto GetFieldDescriptors()
603+ {
604+ auto newFields = std::make_tuple(
605+ reflection::DefField(&TensorOpStmt::result_, "result"),
606+ reflection::UsualField(&TensorOpStmt::result_token_, "result_token"),
607+ reflection::UsualField(&TensorOpStmt::opcode_, "opcode"),
608+ reflection::UsualField(&TensorOpStmt::args_, "args"),
609+ reflection::UsualField(&TensorOpStmt::tokens_, "tokens"),
610+ reflection::UsualField(&TensorOpStmt::attrs_, "attrs"));
611+ return std::tuple_cat(Stmt::GetFieldDescriptors(), newFields);
612+ }
613+};
614+ 
615+using TensorOpStmtPtr = std::shared_ptr<const TensorOpStmt>;
523} // namespace ir616} // namespace ir
524} // namespace pypto617} // namespace pypto
@@ -190,6 +190,8 @@ protected:
190 virtual R VisitStmt_(const EvalStmtPtr& op, Args... args) = 0;190 virtual R VisitStmt_(const EvalStmtPtr& op, Args... args) = 0;
191 virtual R VisitStmt_(const BreakStmtPtr& op, Args... args) = 0;191 virtual R VisitStmt_(const BreakStmtPtr& op, Args... args) = 0;
192 virtual R VisitStmt_(const ContinueStmtPtr& op, Args... args) = 0;192 virtual R VisitStmt_(const ContinueStmtPtr& op, Args... args) = 0;
193+ virtual R VisitStmt_(const TensorOpStmtPtr& op, Args... args) = 0;
194+ virtual R VisitStmt_(const ScalarOpStmtPtr& op, Args... args) = 0;
193 virtual R VisitStmt_(const StmtPtr& op, Args... args) = 0;195 virtual R VisitStmt_(const StmtPtr& op, Args... args) = 0;
194};196};
195 197 
@@ -213,6 +215,8 @@ R StmtFunctor<R, Args...>::VisitStmt(const StmtPtr& stmt, Args... args)
213 STMT_FUNCTOR_DISPATCH(EvalStmt);215 STMT_FUNCTOR_DISPATCH(EvalStmt);
214 STMT_FUNCTOR_DISPATCH(BreakStmt);216 STMT_FUNCTOR_DISPATCH(BreakStmt);
215 STMT_FUNCTOR_DISPATCH(ContinueStmt);217 STMT_FUNCTOR_DISPATCH(ContinueStmt);
218+ STMT_FUNCTOR_DISPATCH(ScalarOpStmt);
219+ STMT_FUNCTOR_DISPATCH(TensorOpStmt);
216 220 
217 // Should never reach here if all types are handled221 // Should never reach here if all types are handled
218 throw TypeError("Unknown statement type in StmtFunctor::VisitStmt");222 throw TypeError("Unknown statement type in StmtFunctor::VisitStmt");
@@ -100,6 +100,8 @@ protected:
100 StmtPtr VisitStmt_(const EvalStmtPtr& op) override;100 StmtPtr VisitStmt_(const EvalStmtPtr& op) override;
101 StmtPtr VisitStmt_(const BreakStmtPtr& op) override;101 StmtPtr VisitStmt_(const BreakStmtPtr& op) override;
102 StmtPtr VisitStmt_(const ContinueStmtPtr& op) override;102 StmtPtr VisitStmt_(const ContinueStmtPtr& op) override;
103+ StmtPtr VisitStmt_(const ScalarOpStmtPtr& op) override;
104+ StmtPtr VisitStmt_(const TensorOpStmtPtr& op) override;
103 StmtPtr VisitStmt_(const StmtPtr& op) override;105 StmtPtr VisitStmt_(const StmtPtr& op) override;
104 106 
105 /// Override to handle ALL binary expressions (Add, Sub, Mul, ...) in one method.107 /// Override to handle ALL binary expressions (Add, Sub, Mul, ...) in one method.
@@ -103,6 +103,8 @@ protected:
103 void VisitStmt_(const EvalStmtPtr& op) override;103 void VisitStmt_(const EvalStmtPtr& op) override;
104 void VisitStmt_(const BreakStmtPtr& op) override;104 void VisitStmt_(const BreakStmtPtr& op) override;
105 void VisitStmt_(const ContinueStmtPtr& op) override;105 void VisitStmt_(const ContinueStmtPtr& op) override;
106+ void VisitStmt_(const TensorOpStmtPtr& op) override;
107+ void VisitStmt_(const ScalarOpStmtPtr& op) override;
106 void VisitStmt_(const StmtPtr& op) override;108 void VisitStmt_(const StmtPtr& op) override;
107 109 
108 /// Override to handle ALL binary expressions (Add, Sub, Mul, ...) in one method.110 /// Override to handle ALL binary expressions (Add, Sub, Mul, ...) in one method.
@@ -240,6 +240,9 @@ using ShapedTypePtr = std::shared_ptr<const ShapedType>;
240 */240 */
241class TensorType : public ShapedType {241class TensorType : public ShapedType {
242public:242public:
243+ std::vector<ExprPtr> validShape; ///< Valid shape dimensions (symbolic or constant)
244+ TensorLayout layout; ///< Tensor layout
245+ 
243 /**246 /**
244 * \brief Create a tensor type without memory reference247 * \brief Create a tensor type without memory reference
245 *248 *
@@ -272,7 +275,13 @@ public:
272 [[nodiscard]] ObjectKind GetKind() const override { return ObjectKind::TensorType; }275 [[nodiscard]] ObjectKind GetKind() const override { return ObjectKind::TensorType; }
273 [[nodiscard]] std::string TypeName() const override { return "TensorType"; }276 [[nodiscard]] std::string TypeName() const override { return "TensorType"; }
274 277 
275- static constexpr auto GetFieldDescriptors() { return ShapedType::GetFieldDescriptors(); }278+ static constexpr auto GetFieldDescriptors()
279+ {
280+ auto newFields = std::make_tuple(
281+ reflection::UsualField(&TensorType::validShape, "valid_shape"),
282+ reflection::UsualField(&TensorType::layout, "layout"));
283+ return std::tuple_cat(ShapedType::GetFieldDescriptors(), newFields);
284+ }
276};285};
277 286 
278using TensorTypePtr = std::shared_ptr<const TensorType>;287using TensorTypePtr = std::shared_ptr<const TensorType>;
@@ -441,5 +450,35 @@ inline PtrTypePtr GetPtrType()
441 return ptr_type;450 return ptr_type;
442}451}
443 452 
453+/**
454+ * \brief Token type representation
455+ *
456+ * Represents an opaque token value used for side-effect ordering.
457+ * Tokens carry no data and are only used to establish dependencies
458+ * between operations.
459+ */
460+class TokenType : public Type {
461+public:
462+ TokenType() = default;
463+ 
464+ [[nodiscard]] ObjectKind GetKind() const override { return ObjectKind::TokenType; }
465+ [[nodiscard]] std::string TypeName() const override { return "Token"; }
466+ 
467+ static constexpr auto GetFieldDescriptors() { return Type::GetFieldDescriptors(); }
468+};
469+ 
470+using TokenTypePtr = std::shared_ptr<const TokenType>;
471+ 
472+/**
473+ * @brief Get a shared pointer to the singleton TokenType instance
474+ *
475+ * @return Shared pointer to TokenType
476+ */
477+inline TokenTypePtr GetTokenType()
478+{
479+ static const auto token_type = std::make_shared<TokenType>();
480+ return token_type;
481+}
482+ 
444} // namespace ir483} // namespace ir
445} // namespace pypto484} // namespace pypto
@@ -23,11 +23,13 @@
23#include <optional>23#include <optional>
24#include "tilefwk/tensor.h"24#include "tilefwk/tensor.h"
25#include "tilefwk/symbolic_scalar.h"25#include "tilefwk/symbolic_scalar.h"
26+#include "ir/span.h"
27+ 
28+using namespace pypto;
26 29 
27namespace npu::tile_fwk {30namespace npu::tile_fwk {
28// Forward declaration for types used in this file31// Forward declaration for types used in this file
29class Function;32class Function;
30-struct SourceLocation;
31} // namespace npu::tile_fwk33} // namespace npu::tile_fwk
32 34 
33// Helper macros to count arguments35// Helper macros to count arguments
@@ -213,7 +215,7 @@ private:
213 std::set<int, std::greater<>> unrollTimes_;215 std::set<int, std::greater<>> unrollTimes_;
214 std::unordered_set<int> visited_;216 std::unordered_set<int> visited_;
215 std::unordered_set<int> customUnrollTimes_;217 std::unordered_set<int> customUnrollTimes_;
216- std::shared_ptr<SourceLocation> location_;218+ ir::Span span_;
217 219 
218 void GenDefaultUnrollTimes(const std::set<int>& unrollList);220 void GenDefaultUnrollTimes(const std::set<int>& unrollList);
219};221};
@@ -16,7 +16,7 @@
16#ifndef CODEGEN_COMMON_H16#ifndef CODEGEN_COMMON_H
17#define CODEGEN_COMMON_H17#define CODEGEN_COMMON_H
18 18 
19-#include <iostream>19+#include <map>
20 20 
21#include "interface/utils/common.h"21#include "interface/utils/common.h"
22#include "tilefwk/data_type.h"22#include "tilefwk/data_type.h"
@@ -433,7 +433,7 @@ inline const std::string& LogFile() { return ConfigManager::Instance().LogFile()
433inline Status SetPassStrategy(const std::string s)433inline Status SetPassStrategy(const std::string s)
434{434{
435 SetHostConfig(KEY_STRATEGY, s);435 SetHostConfig(KEY_STRATEGY, s);
436- return true;436+ return SUCCESS;
437}437}
438 438 
439inline std::string GetPassStrategy() { return GetHostConfig(KEY_STRATEGY, "OOO"); }439inline std::string GetPassStrategy() { return GetHostConfig(KEY_STRATEGY, "OOO"); }
@@ -1526,7 +1526,7 @@ void Function::UpdateTensorDataUsage(Operation& op)
1526 1526 
1527Operation& Function::AddRawOperation(1527Operation& Function::AddRawOperation(
1528 const Opcode opCode, const LogicalTensors& iOperands, const LogicalTensors& oOperands, bool updateTensorMap,1528 const Opcode opCode, const LogicalTensors& iOperands, const LogicalTensors& oOperands, bool updateTensorMap,
1529- const SourceLocationPtr& sourceLocation)1529+ const ir::Span& span)
1530{1530{
1531 if (IsFunctionTypeAndGraphType(FunctionType::STATIC, {GraphType::EXECUTE_GRAPH, GraphType::BLOCK_GRAPH})) {1531 if (IsFunctionTypeAndGraphType(FunctionType::STATIC, {GraphType::EXECUTE_GRAPH, GraphType::BLOCK_GRAPH})) {
1532 updateTensorMap = false;1532 updateTensorMap = false;
@@ -1545,8 +1545,9 @@ Operation& Function::AddRawOperation(
1545 } else {1545 } else {
1546 operations_.back()->SetScopeId(-1);1546 operations_.back()->SetScopeId(-1);
1547 }1547 }
1548- if (sourceLocation != nullptr) {1548+ 
1549- operations_.back()->SetLocation(sourceLocation);1549+ if (!span.IsUnknown()) {
1550+ operations_.back()->SetSpan(span);
1550 }1551 }
1551 return *operations_.back();1552 return *operations_.back();
1552}1553}
@@ -1773,8 +1774,9 @@ void Function::CreateFromIncast(
1773 const std::shared_ptr<LogicalTensor>& symbol, const std::shared_ptr<LogicalTensor>& newIncast,1774 const std::shared_ptr<LogicalTensor>& symbol, const std::shared_ptr<LogicalTensor>& newIncast,
1774 const std::shared_ptr<LogicalTensor>& originIncast)1775 const std::shared_ptr<LogicalTensor>& originIncast)
1775{1776{
1776- DEFINE_SOURCE_LOCATION();1777+ ir::Span::SetCurrent(ir::Span(__FILE__, __LINE__, 0));
1777 auto& incastOp = AddOperation(Opcode::OP_VIEW, {symbol}, {newIncast});1778 auto& incastOp = AddOperation(Opcode::OP_VIEW, {symbol}, {newIncast});
1779+ ir::Span::ClearCurrent();
1778 incastOp.SetAttr(OpAttributeKey::isGlobalInput, true);1780 incastOp.SetAttr(OpAttributeKey::isGlobalInput, true);
1779 1781 
1780 auto validShape = originIncast->GetDynValidShape();1782 auto validShape = originIncast->GetDynValidShape();
@@ -1844,8 +1846,7 @@ LogicalTensors Function::MakeIncasts(const std::shared_ptr<TensorSlotScope>& sco
1844 const auto& sameRawIncasts = incastWithSameRaw[rawIncast->rawmagic];1846 const auto& sameRawIncasts = incastWithSameRaw[rawIncast->rawmagic];
1845 1847 
1846 std::vector<int64_t> zeroOffset(rawIncast->rawshape.size(), 0);1848 std::vector<int64_t> zeroOffset(rawIncast->rawshape.size(), 0);
1847- auto inArgument =1849+ auto inArgument = std::make_shared<LogicalTensor>(Parent(), rawIncast, zeroOffset, rawIncast->rawshape);
1848- std::make_shared<LogicalTensor>(Parent(), rawIncast, zeroOffset, rawIncast->rawshape);
1849 inArgumentList.push_back(inArgument);1850 inArgumentList.push_back(inArgument);
1850 1851 
1851 auto incastSymbol = CreateIncastTensor(inArgument);1852 auto incastSymbol = CreateIncastTensor(inArgument);
@@ -1948,8 +1949,7 @@ LogicalTensors Function::MakeOutcasts(const std::shared_ptr<TensorSlotScope>& sc
1948 auto rawBuf = std::make_shared<LogicalTensor>(1949 auto rawBuf = std::make_shared<LogicalTensor>(
1949 *this, rawOutcast->datatype, rawOutcast->rawshape, rawOutcast->GetDynRawShape(),1950 *this, rawOutcast->datatype, rawOutcast->rawshape, rawOutcast->GetDynRawShape(),
1950 rawToOutcast[rawOutcast]->Format(), "OUTCAST_LOCAL_BUF" + std::to_string(idx));1951 rawToOutcast[rawOutcast]->Format(), "OUTCAST_LOCAL_BUF" + std::to_string(idx));
1951- auto outArgument =1952+ auto outArgument = std::make_shared<LogicalTensor>(Parent(), rawOutcast, nonOffsets, rawOutcast->rawshape);
1952- std::make_shared<LogicalTensor>(Parent(), rawOutcast, nonOffsets, rawOutcast->rawshape);
1953 rawSymbol->tensor->UpdateDynRawShape(rawOutcast->GetDynRawShape());1953 rawSymbol->tensor->UpdateDynRawShape(rawOutcast->GetDynRawShape());
1954 rawBuf->tensor->UpdateDynRawShape(rawOutcast->GetDynRawShape());1954 rawBuf->tensor->UpdateDynRawShape(rawOutcast->GetDynRawShape());
1955 Parent().tensorMap_.Insert(outArgument);1955 Parent().tensorMap_.Insert(outArgument);
@@ -2015,7 +2015,6 @@ LogicalTensors Function::MakeOutcasts(const std::shared_ptr<TensorSlotScope>& sc
2015 }2015 }
2016 auto consumers = iOperand[i]->GetConsumers(); // deep copy2016 auto consumers = iOperand[i]->GetConsumers(); // deep copy
2017 for (auto consumer : consumers) {2017 for (auto consumer : consumers) {
2018- DEFINE_SOURCE_LOCATION();
2019 for (size_t j = 0; j < consumer->GetIOperands().size(); j++) {2018 for (size_t j = 0; j < consumer->GetIOperands().size(); j++) {
2020 if (consumer->GetInputOperand(j) == iOperand[i]) {2019 if (consumer->GetInputOperand(j) == iOperand[i]) {
2021 consumer->ReplaceIOperand(j, rawSymbol);2020 consumer->ReplaceIOperand(j, rawSymbol);
@@ -2026,8 +2025,9 @@ LogicalTensors Function::MakeOutcasts(const std::shared_ptr<TensorSlotScope>& sc
2026 scope->partialUpdateOutcastDict[rawSymbol] = partitalAssemble;2025 scope->partialUpdateOutcastDict[rawSymbol] = partitalAssemble;
2027 }2026 }
2028 } else {2027 } else {
2029- DEFINE_SOURCE_LOCATION();2028+ ir::Span::SetCurrent(ir::Span(__FILE__, __LINE__, 0));
2030 auto& assembleOp = AddOperation(Opcode::OP_ASSEMBLE, {iOperand[i]}, oOperand);2029 auto& assembleOp = AddOperation(Opcode::OP_ASSEMBLE, {iOperand[i]}, oOperand);
2030+ ir::Span::ClearCurrent();
2031 assembleOp.SetOpAttribute(std::make_shared<AssembleOpAttribute>(2031 assembleOp.SetOpAttribute(std::make_shared<AssembleOpAttribute>(
2032 newOutcastOffsets[i], SymbolicScalar::FromConcrete(newOutcastOffsets[i])));2032 newOutcastOffsets[i], SymbolicScalar::FromConcrete(newOutcastOffsets[i])));
2033 }2033 }
@@ -2159,9 +2159,9 @@ Json Function::DumpJson(bool useTable)
2159 funcJson["_mg_vec_parallel_lb"] = paramConfigs_.mgVecParallelLb;2159 funcJson["_mg_vec_parallel_lb"] = paramConfigs_.mgVecParallelLb;
2160 funcJson["_total_subgraph_count"] = totalSubGraphCount_;2160 funcJson["_total_subgraph_count"] = totalSubGraphCount_;
2161 funcJson["_ooo_preschedule_method"] = paramConfigs_.OoOPreScheduleMethod;2161 funcJson["_ooo_preschedule_method"] = paramConfigs_.OoOPreScheduleMethod;
2162- if (sourceLocation_ != nullptr) {2162+ if (!span_.IsUnknown()) {
2163- funcJson["file"] = sourceLocation_->GetFileName();2163+ funcJson["file"] = span_.Filename();
2164- funcJson["line"] = sourceLocation_->GetLineno();2164+ funcJson["line"] = span_.BeginLine();
2165 }2165 }
2166 2166 
2167 if (useTable) {2167 if (useTable) {
@@ -564,7 +564,7 @@ public:
564 const bool updateTensorMap = true);564 const bool updateTensorMap = true);
565 Operation& AddRawOperation(565 Operation& AddRawOperation(
566 const Opcode opCode, const LogicalTensors& iOperands, const LogicalTensors& oOperands,566 const Opcode opCode, const LogicalTensors& iOperands, const LogicalTensors& oOperands,
567- bool updateTensorMap = true, const SourceLocationPtr& sourceLocation = nullptr);567+ bool updateTensorMap = true, const ir::Span& span = ir::Span::Unknown());
568 568 
569 std::map<std::shared_ptr<RawTensor>, std::shared_ptr<RawTensor>> outIncastLinkMap; // 记录outcast 共享地址的 incast569 std::map<std::shared_ptr<RawTensor>, std::shared_ptr<RawTensor>> outIncastLinkMap; // 记录outcast 共享地址的 incast
570 void SetSameMemId(const LogicalTensorPtr& operand, LogicalTensorPtr& dst);570 void SetSameMemId(const LogicalTensorPtr& operand, LogicalTensorPtr& dst);
@@ -865,19 +865,20 @@ public:
865 void GetTensorDataRefreshIO(const GetTensorDataIODescDict& descDict);865 void GetTensorDataRefreshIO(const GetTensorDataIODescDict& descDict);
866 void UpdateTensorDataUsage(Operation& op);866 void UpdateTensorDataUsage(Operation& op);
867 867 
868- void SetSourceLocation(std::shared_ptr<SourceLocation> sourceLocation) { sourceLocation_ = sourceLocation; }868+ void SetSpan(ir::Span& span) { span_ = span; }
869 869 
870- std::shared_ptr<SourceLocation> GetSourceLocation() const { return sourceLocation_; }870+ ir::Span& GetSpan() { return span_; }
871 void CleanRedundantOutCast();871 void CleanRedundantOutCast();
872 872 
873 void SetHiddenFunction(bool hiddenFunction) { hiddenFunction_ = hiddenFunction; }873 void SetHiddenFunction(bool hiddenFunction) { hiddenFunction_ = hiddenFunction; }
874 bool IsHiddenFunction() const { return hiddenFunction_; }874 bool IsHiddenFunction() const { return hiddenFunction_; }
875 875 
876- const std::unordered_set<std::string> &LoopIdxNameList() { return loopIdxNameList_; }876+ const std::unordered_set<std::string>& LoopIdxNameList() { return loopIdxNameList_; }
877- bool InsertLoopIdxNameList(const std::string &idxName);877+ bool InsertLoopIdxNameList(const std::string& idxName);
878 878 
879 void SetMaxCVCoreUsage(std::pair<uint32_t, uint32_t> maxCVCores) { maxCVCoreUsage_ = maxCVCores; }879 void SetMaxCVCoreUsage(std::pair<uint32_t, uint32_t> maxCVCores) { maxCVCoreUsage_ = maxCVCores; }
880 std::pair<uint32_t, uint32_t> GetMaxCVCoreUsage() { return maxCVCoreUsage_; }880 std::pair<uint32_t, uint32_t> GetMaxCVCoreUsage() { return maxCVCoreUsage_; }
881+ 
881private:882private:
882 int functionMagic_{-1};883 int functionMagic_{-1};
883 std::string funcMagicName_; // Function name884 std::string funcMagicName_; // Function name
@@ -936,7 +937,7 @@ private:
936 static bool enableMagicLookupRecord_;937 static bool enableMagicLookupRecord_;
937 static std::map<std::pair<int, int>, std::set<Operation*, LogicalTensor::CompareOp>> tensorAndSubgraphToProducer_;938 static std::map<std::pair<int, int>, std::set<Operation*, LogicalTensor::CompareOp>> tensorAndSubgraphToProducer_;
938 std::shared_ptr<Tensor> getTensorDataOutcast_;939 std::shared_ptr<Tensor> getTensorDataOutcast_;
939- std::shared_ptr<SourceLocation> sourceLocation_;940+ ir::Span span_;
940 bool hiddenFunction_{false};941 bool hiddenFunction_{false};
941 942 
942private:943private:
@@ -154,9 +154,10 @@ std::string ExecuteOperationContext::Dump() const
154 std::stringstream ss;154 std::stringstream ss;
155 ss << "func: " << frame->func->GetRawName() << "\n";155 ss << "func: " << frame->func->GetRawName() << "\n";
156 156 
157- if (auto loc = op->GetLocation(); loc) {157+ auto span = op->GetSpan();
158- ss << "filename: " << loc->GetFileName() << "\n";158+ if (!span.IsUnknown()) {
159- ss << "lineno: " << loc->GetLineno() << "\n";159+ ss << "filename: " << span.Filename() << "\n";
160+ ss << "lineno: " << span.BeginLine() << "\n";
160 }161 }
161 162 
162 auto printType = [&](auto& viewList) {163 auto printType = [&](auto& viewList) {
@@ -31,6 +31,13 @@
31namespace pypto {31namespace pypto {
32namespace ir {32namespace ir {
33 33 
34+static Span combine_span(const Span& begin_span, const Span& end_span)
35+{
36+ return Span(
37+ begin_span.Filename(), begin_span.BeginLine(), begin_span.BeginColumn(), end_span.EndLine(),
38+ end_span.EndColumn());
39+}
40+ 
34// ========== IRBuilder Implementation ==========41// ========== IRBuilder Implementation ==========
35 42 
36IRBuilder::IRBuilder() = default;43IRBuilder::IRBuilder() = default;
@@ -75,14 +82,11 @@ FunctionPtr IRBuilder::EndFunction(const Span& end_span)
75 StmtPtr body = (stmts.size() == 1) ? stmts[0] : std::make_shared<SeqStmts>(stmts, end_span);82 StmtPtr body = (stmts.size() == 1) ? stmts[0] : std::make_shared<SeqStmts>(stmts, end_span);
76 83 
77 // Combine begin and end spans84 // Combine begin and end spans
78- const Span& begin_span = func_ctx->GetBeginSpan();85+ auto new_span = combine_span(func_ctx->GetBeginSpan(), end_span);
79- Span combined_span(
80- begin_span.filename_, begin_span.beginLine_, begin_span.beginColumn_, end_span.beginLine_,
81- end_span.beginColumn_);
82 86 
83 // Create function87 // Create function
84 auto func = std::make_shared<Function>(88 auto func = std::make_shared<Function>(
85- func_ctx->GetName(), func_ctx->GetParams(), func_ctx->GetReturnTypes(), body, combined_span,89+ func_ctx->GetName(), func_ctx->GetParams(), func_ctx->GetReturnTypes(), body, new_span,
86 func_ctx->GetFuncType());90 func_ctx->GetFuncType());
87 91 
88 // Pop context92 // Pop context
@@ -138,15 +142,12 @@ StmtPtr IRBuilder::EndForLoop(const Span& end_span)
138 StmtPtr body = (stmts.size() == 1) ? stmts[0] : std::make_shared<SeqStmts>(stmts, end_span);142 StmtPtr body = (stmts.size() == 1) ? stmts[0] : std::make_shared<SeqStmts>(stmts, end_span);
139 143 
140 // Combine begin and end spans144 // Combine begin and end spans
141- const Span& begin_span = loop_ctx->GetBeginSpan();145+ auto new_span = combine_span(loop_ctx->GetBeginSpan(), end_span);
142- Span combined_span(
143- begin_span.filename_, begin_span.beginLine_, begin_span.beginColumn_, end_span.beginLine_,
144- end_span.beginColumn_);
145 146 
146 // Create for statement147 // Create for statement
147 auto for_stmt = std::make_shared<ForStmt>(148 auto for_stmt = std::make_shared<ForStmt>(
148 loop_ctx->GetLoopVar(), loop_ctx->GetStart(), loop_ctx->GetStop(), loop_ctx->GetStep(), loop_ctx->GetIterArgs(),149 loop_ctx->GetLoopVar(), loop_ctx->GetStart(), loop_ctx->GetStop(), loop_ctx->GetStep(), loop_ctx->GetIterArgs(),
149- body, loop_ctx->GetReturnVars(), combined_span);150+ body, loop_ctx->GetReturnVars(), new_span);
150 151 
151 // Pop context152 // Pop context
152 context_stack_.pop_back();153 context_stack_.pop_back();
@@ -211,14 +212,11 @@ StmtPtr IRBuilder::EndWhileLoop(const Span& end_span)
211 StmtPtr body = (stmts.size() == 1) ? stmts[0] : std::make_shared<SeqStmts>(stmts, end_span);212 StmtPtr body = (stmts.size() == 1) ? stmts[0] : std::make_shared<SeqStmts>(stmts, end_span);
212 213 
213 // Combine begin and end spans214 // Combine begin and end spans
214- const Span& begin_span = loop_ctx->GetBeginSpan();215+ auto new_span = combine_span(loop_ctx->GetBeginSpan(), end_span);
215- Span combined_span(
216- begin_span.filename_, begin_span.beginLine_, begin_span.beginColumn_, end_span.beginLine_,
217- end_span.beginColumn_);
218 216 
219 // Create while statement217 // Create while statement
220 auto while_stmt = std::make_shared<WhileStmt>(218 auto while_stmt = std::make_shared<WhileStmt>(
221- loop_ctx->GetCondition(), loop_ctx->GetIterArgs(), body, loop_ctx->GetReturnVars(), combined_span);219+ loop_ctx->GetCondition(), loop_ctx->GetIterArgs(), body, loop_ctx->GetReturnVars(), new_span);
222 220 
223 // Pop context221 // Pop context
224 context_stack_.pop_back();222 context_stack_.pop_back();
@@ -235,8 +233,8 @@ StmtPtr IRBuilder::EndWhileLoop(const Span& end_span)
235 233 
236void IRBuilder::BeginIf(const ExprPtr& condition, const Span& span)234void IRBuilder::BeginIf(const ExprPtr& condition, const Span& span)
237{235{
238- CHECK(!context_stack_.empty()) << "Cannot begin if statement: not inside a function or another valid context at "236+ IRCHECK(!context_stack_.empty()) << "Cannot begin if statement: not inside a function or another valid context at "
239- << span.ToString();237+ << span.ToString();
240 context_stack_.push_back(std::make_unique<IfStmtContext>(condition, span));238 context_stack_.push_back(std::make_unique<IfStmtContext>(condition, span));
241}239}
242 240 
@@ -245,7 +243,7 @@ void IRBuilder::BeginElse(const Span& span)
245 ValidateInIf("BeginElse");243 ValidateInIf("BeginElse");
246 244 
247 auto* if_ctx = static_cast<IfStmtContext*>(CurrentContext());245 auto* if_ctx = static_cast<IfStmtContext*>(CurrentContext());
248- CHECK(!if_ctx->InElseBranch()) << "Cannot begin else branch: already in else branch at " << span.ToString();246+ IRCHECK(!if_ctx->InElseBranch()) << "Cannot begin else branch: already in else branch at " << span.ToString();
249 247 
250 if_ctx->BeginElseBranch();248 if_ctx->BeginElseBranch();
251}249}
@@ -276,14 +274,11 @@ StmtPtr IRBuilder::EndIf(const Span& end_span)
276 }274 }
277 275 
278 // Combine begin and end spans276 // Combine begin and end spans
279- const Span& begin_span = if_ctx->GetBeginSpan();277+ auto new_span = combine_span(if_ctx->GetBeginSpan(), end_span);
280- Span combined_span(
281- begin_span.filename_, begin_span.beginLine_, begin_span.beginColumn_, end_span.beginLine_,
282- end_span.beginColumn_);
283 278 
284 // Create if statement279 // Create if statement
285 auto if_stmt =280 auto if_stmt =
286- std::make_shared<IfStmt>(if_ctx->GetCondition(), then_body, else_body, if_ctx->GetReturnVars(), combined_span);281+ std::make_shared<IfStmt>(if_ctx->GetCondition(), then_body, else_body, if_ctx->GetReturnVars(), new_span);
287 282 
288 // Pop context283 // Pop context
289 context_stack_.pop_back();284 context_stack_.pop_back();
@@ -322,13 +317,10 @@ ProgramPtr IRBuilder::EndProgram(const Span& end_span)
322 auto* prog_ctx = static_cast<ProgramContext*>(CurrentContext());317 auto* prog_ctx = static_cast<ProgramContext*>(CurrentContext());
323 318 
324 // Combine begin and end spans319 // Combine begin and end spans
325- const Span& begin_span = prog_ctx->GetBeginSpan();320+ auto new_span = combine_span(prog_ctx->GetBeginSpan(), end_span);
326- Span combined_span(
327- begin_span.filename_, begin_span.beginLine_, begin_span.beginColumn_, end_span.beginLine_,
328- end_span.beginColumn_);
329 321 
330 // Create program from functions vector322 // Create program from functions vector
331- auto program = std::make_shared<Program>(prog_ctx->GetFunctions(), prog_ctx->GetName(), combined_span);323+ auto program = std::make_shared<Program>(prog_ctx->GetFunctions(), prog_ctx->GetName(), new_span);
332 324 
333 // Pop context325 // Pop context
334 context_stack_.pop_back();326 context_stack_.pop_back();
@@ -454,29 +446,29 @@ T* IRBuilder::GetCurrentContextAs()
454 446 
455void IRBuilder::ValidateInFunction(const std::string& operation)447void IRBuilder::ValidateInFunction(const std::string& operation)
456{448{
457- CHECK(InFunction()) << operation << " can only be called inside a function context";449+ IRCHECK(InFunction()) << operation << " can only be called inside a function context";
458- CHECK(CurrentContext()->GetType() == BuildContext::Type::FUNCTION)450+ IRCHECK(CurrentContext()->GetType() == BuildContext::Type::FUNCTION)
459 << operation << " must be called directly in function context, not nested";451 << operation << " must be called directly in function context, not nested";
460}452}
461 453 
462void IRBuilder::ValidateInLoop(const std::string& operation)454void IRBuilder::ValidateInLoop(const std::string& operation)
463{455{
464- CHECK(InLoop()) << operation << " can only be called inside a for loop context";456+ IRCHECK(InLoop()) << operation << " can only be called inside a for loop context";
465}457}
466 458 
467void IRBuilder::ValidateInIf(const std::string& operation)459void IRBuilder::ValidateInIf(const std::string& operation)
468{460{
469- CHECK(InIf()) << operation << " can only be called inside an if statement context";461+ IRCHECK(InIf()) << operation << " can only be called inside an if statement context";
470}462}
471 463 
472void IRBuilder::ValidateInWhileLoop(const std::string& operation)464void IRBuilder::ValidateInWhileLoop(const std::string& operation)
473{465{
474- CHECK(InWhileLoop()) << operation << " can only be called inside a while loop context";466+ IRCHECK(InWhileLoop()) << operation << " can only be called inside a while loop context";
475}467}
476 468 
477void IRBuilder::ValidateInProgram(const std::string& operation)469void IRBuilder::ValidateInProgram(const std::string& operation)
478{470{
479- CHECK(InProgram()) << operation << " can only be called inside a program context";471+ IRCHECK(InProgram()) << operation << " can only be called inside a program context";
480}472}
481 473 
482void ProgramContext::AddFunction(const FunctionPtr& func)474void ProgramContext::AddFunction(const FunctionPtr& func)
@@ -14,31 +14,165 @@
14 14 
15#include <sstream>15#include <sstream>
16#include <string>16#include <string>
17-#include <utility>17+#include <unordered_set>
18+#include <mutex>
19+#include <atomic>
18 20 
19namespace pypto {21namespace pypto {
20namespace ir {22namespace ir {
21 23 
22-Span::Span(std::string filename, int beginLine, int beginColumn, int endLine, int endColumn)24+class SpanImpl {
23- : filename_(std::move(filename)),25+public:
24- beginLine_(beginLine),26+ const std::string filename_; ///< Source filename
25- beginColumn_(beginColumn),27+ const int beginLine_; ///< Beginning line number (1-indexed)
26- endLine_(endLine),28+ const int beginColumn_; ///< Beginning column number (1-indexed)
27- endColumn_(endColumn)29+ const int endLine_; ///< Ending line number (1-indexed), -1 means unknown
28-{}30+ const int endColumn_; ///< Ending column number (1-indexed), -1 means unknown
31+ 
32+ static SpanImpl* Create(const std::string& filename, int beginLine, int beginColumn, int endLine, int endColumn);
33+ 
34+ void Put();
35+ void Get() { refcnt++; }
36+ 
37+private:
38+ std::atomic_int refcnt{1};
39+ SpanImpl(const std::string& filename, int beginLine, int beginColumn, int endLine, int endColumn)
40+ : filename_(filename),
41+ beginLine_(beginLine),
42+ beginColumn_(beginColumn),
43+ endLine_(endLine),
44+ endColumn_(endColumn)
45+ {}
46+};
47+ 
48+struct SpanImplHash {
49+ std::size_t operator()(SpanImpl* span) const
50+ {
51+ auto combine = [](std::size_t seed, std::size_t hash) -> std::size_t {
52+ return seed ^ (hash + 0x9e3779b9 + (seed << 6) + (seed >> 2));
53+ };
54+ std::size_t h = std::hash<std::string>()(span->filename_);
55+ h = combine(h, span->beginLine_);
56+ h = combine(h, span->beginColumn_);
57+ h = combine(h, span->endLine_);
58+ h = combine(h, span->endColumn_);
59+ return h;
60+ }
61+};
62+ 
63+struct SpanImplEqual {
64+ bool operator()(SpanImpl* a, SpanImpl* b) const
65+ {
66+ return a->filename_ == b->filename_ && a->beginLine_ == b->beginLine_ && a->endLine_ == b->endLine_ &&
67+ a->beginColumn_ == b->beginColumn_ && a->endColumn_ == b->endColumn_;
68+ }
69+};
70+ 
71+static std::unordered_set<SpanImpl*, SpanImplHash, SpanImplEqual> registry;
72+static std::mutex mutex;
73+ 
74+SpanImpl* SpanImpl::Create(const std::string& filename, int beginLine, int beginColumn, int endLine, int endColumn)
75+{
76+ auto span_ptr = new SpanImpl(filename, beginLine, beginColumn, endLine, endColumn);
77+ std::unique_lock lock(mutex);
78+ auto it = registry.find(span_ptr);
79+ if (it != registry.end()) {
80+ (*it)->refcnt++;
81+ lock.unlock();
82+ delete span_ptr;
83+ return *it;
84+ }
85+ registry.insert(span_ptr);
86+ return span_ptr;
87+}
88+ 
89+void SpanImpl::Put()
90+{
91+ std::unique_lock lock(mutex);
92+ if (--refcnt == 0) {
93+ registry.erase(this);
94+ lock.unlock();
95+ delete this;
96+ }
97+}
98+ 
99+Span::Span(const Span& other)
100+{
101+ impl_ = other.impl_;
102+ impl_->Get();
103+}
104+ 
105+Span::Span()
106+{
107+ impl_ = Unknown().impl_;
108+ impl_->Get();
109+}
110+ 
111+Span& Span::operator=(const Span& other)
112+{
113+ if (this != &other) {
114+ impl_->Put();
115+ impl_ = other.impl_;
116+ impl_->Get();
117+ }
118+ return *this;
119+}
120+ 
121+Span::Span(Span&& other)
122+{
123+ impl_ = other.impl_;
124+ impl_->Get();
125+ other = Unknown();
126+}
127+ 
128+Span& Span::operator=(Span&& other)
129+{
130+ if (this != &other) {
131+ impl_->Put();
132+ impl_ = other.impl_;
133+ impl_->Get();
134+ other = Unknown();
135+ }
136+ return *this;
137+}
138+ 
139+Span::Span(const std::string& file, int beginLine, int beginColumn, int endLine, int endColumn)
140+{
141+ impl_ = SpanImpl::Create(file, beginLine, beginColumn, endLine, endColumn);
142+}
143+ 
144+Span::~Span() { impl_->Put(); }
145+ 
146+const std::string& Span::Filename() const { return impl_->filename_; }
147+ 
148+int Span::BeginLine() const { return impl_->beginLine_; }
149+ 
150+int Span::BeginColumn() const { return impl_->beginColumn_; }
151+ 
152+int Span::EndLine() const { return impl_->endLine_; }
153+ 
154+int Span::EndColumn() const { return impl_->endColumn_; }
29 155 
30std::string Span::ToString() const156std::string Span::ToString() const
31{157{
32 std::ostringstream oss;158 std::ostringstream oss;
33- oss << filename_ << ":" << beginLine_ << ":" << beginColumn_;159+ oss << impl_->filename_ << ":" << impl_->beginLine_ << ":" << impl_->beginColumn_;
34 return oss.str();160 return oss.str();
35}161}
36 162 
37-static Span kUnknownSpan = Span("", -1, -1, -1, -1);163+Span& Span::Unknown()
164+{
165+ static Span span = Span("", -1, -1, -1, -1);
166+ return span;
167+}
38 168 
39-bool Span::IsUnknown(const Span& span) { return &span == &kUnknownSpan; }169+void Span::SetCurrent(const Span& span) { Current() = span; }
40 170 
41-Span& Span::Unknown() { return kUnknownSpan; }171+Span& Span::Current()
172+{
173+ static Span span = Unknown();
174+ return span;
175+}
42 176 
43} // namespace ir177} // namespace ir
44} // namespace pypto178} // namespace pypto
@@ -605,6 +605,92 @@ StmtPtr IRMutator::VisitStmt_(const BreakStmtPtr& op) { return op; }
605 605 
606StmtPtr IRMutator::VisitStmt_(const ContinueStmtPtr& op) { return op; }606StmtPtr IRMutator::VisitStmt_(const ContinueStmtPtr& op) { return op; }
607 607 
608+StmtPtr IRMutator::VisitStmt_(const ScalarOpStmtPtr& op)
609+{
610+ bool changed = false;
611+ 
612+ INTERNAL_CHECK_SPAN(op->result_, op->span_) << "ScalarOpStmt has null result";
613+ auto new_result = As<Var>(ExprFunctor<ExprPtr>::VisitExpr(op->result_));
614+ if (new_result.get() != op->result_.get()) {
615+ changed = true;
616+ }
617+ INTERNAL_CHECK_SPAN(new_result, op->span_) << "ScalarOpStmt result mutated to null";
618+ 
619+ INTERNAL_CHECK_SPAN(op->result_token_, op->span_) << "ScalarOpStmt has null result_token";
620+ auto new_token = As<Var>(ExprFunctor<ExprPtr>::VisitExpr(op->result_token_));
621+ if (new_token.get() != op->result_token_.get()) {
622+ changed = true;
623+ }
624+ INTERNAL_CHECK_SPAN(new_token, op->span_) << "ScalarOpStmt result_token mutated to null";
625+ std::vector<ExprPtr> new_args;
626+ for (size_t i = 0; i < op->args_.size(); ++i) {
627+ INTERNAL_CHECK_SPAN(op->args_[i], op->span_) << "ScalarOpStmt has null arg at index " << i;
628+ auto new_arg = ExprFunctor<ExprPtr>::VisitExpr(op->args_[i]);
629+ if (new_arg.get() != op->args_[i].get()) {
630+ changed = true;
631+ }
632+ INTERNAL_CHECK_SPAN(new_arg, op->span_) << "ScalarOpStmt arg at index " << i << " mutated to null";
633+ new_args.push_back(new_arg);
634+ }
635+ if (changed) {
636+ return std::make_shared<const ScalarOpStmt>(
637+ std::move(new_result), std::move(new_token), std::move(op->opcode_), std::move(new_args), op->span_);
638+ }
639+ return op;
640+}
641+ 
642+StmtPtr IRMutator::VisitStmt_(const TensorOpStmtPtr& op)
643+{
644+ bool changed = false;
645+ 
646+ std::vector<VarPtr> new_results;
647+ for (size_t i = 0; i < op->result_.size(); ++i) {
648+ INTERNAL_CHECK_SPAN(op->result_[i], op->span_) << "TensorOpStmt has null result at index " << i;
649+ auto new_result = ExprFunctor<ExprPtr>::VisitExpr(op->result_[i]);
650+ if (new_result.get() != op->result_[i].get()) {
651+ changed = true;
652+ }
653+ INTERNAL_CHECK_SPAN(new_result, op->span_) << "TensorOpStmt result at index " << i << " mutated to null";
654+ new_results.push_back(As<Var>(new_result));
655+ }
656+ 
657+ INTERNAL_CHECK_SPAN(op->result_token_, op->span_) << "TensorOpStmt has null result_token";
658+ auto new_token = As<Var>(ExprFunctor<ExprPtr>::VisitExpr(op->result_token_));
659+ if (new_token.get() != op->result_token_.get()) {
660+ changed = true;
661+ }
662+ INTERNAL_CHECK_SPAN(new_token, op->span_) << "TensorOpStmt result_token mutated to null";
663+ 
664+ std::vector<ExprPtr> new_args;
665+ for (size_t i = 0; i < op->args_.size(); ++i) {
666+ INTERNAL_CHECK_SPAN(op->args_[i], op->span_) << "TensorOpStmt has null arg at index " << i;
667+ auto new_arg = ExprFunctor<ExprPtr>::VisitExpr(op->args_[i]);
668+ if (new_arg.get() != op->args_[i].get()) {
669+ changed = true;
670+ }
671+ INTERNAL_CHECK_SPAN(new_arg, op->span_) << "TensorOpStmt arg at index " << i << " mutated to null";
672+ new_args.push_back(new_arg);
673+ }
674+ 
675+ std::vector<ExprPtr> new_tokens;
676+ for (size_t i = 0; i < op->tokens_.size(); ++i) {
677+ INTERNAL_CHECK_SPAN(op->tokens_[i], op->span_) << "TensorOpStmt has null token at index " << i;
678+ auto new_tok = ExprFunctor<ExprPtr>::VisitExpr(op->tokens_[i]);
679+ if (new_tok.get() != op->tokens_[i].get()) {
680+ changed = true;
681+ }
682+ INTERNAL_CHECK_SPAN(new_tok, op->span_) << "TensorOpStmt token at index " << i << " mutated to null";
683+ new_tokens.push_back(new_tok);
684+ }
685+ 
686+ if (changed) {
687+ return std::make_shared<const TensorOpStmt>(
688+ std::move(new_results), std::move(new_token), std::move(op->opcode_), std::move(new_args),
689+ std::move(new_tokens), std::move(op->attrs_), op->span_);
690+ }
691+ return op;
692+}
693+ 
608StmtPtr IRMutator::VisitStmt_(const StmtPtr& op) { return op; }694StmtPtr IRMutator::VisitStmt_(const StmtPtr& op) { return op; }
609 695 
610} // namespace ir696} // namespace ir
@@ -227,6 +227,8 @@ protected:
227 void VisitStmt_(const EvalStmtPtr& op) override;227 void VisitStmt_(const EvalStmtPtr& op) override;
228 void VisitStmt_(const BreakStmtPtr& op) override;228 void VisitStmt_(const BreakStmtPtr& op) override;
229 void VisitStmt_(const ContinueStmtPtr& op) override;229 void VisitStmt_(const ContinueStmtPtr& op) override;
230+ void VisitStmt_(const TensorOpStmtPtr& op) override;
231+ void VisitStmt_(const ScalarOpStmtPtr& op) override;
230 void VisitStmt_(const StmtPtr& op) override;232 void VisitStmt_(const StmtPtr& op) override;
231 233 
232 // Function and program visitors234 // Function and program visitors
@@ -354,6 +356,10 @@ std::string IRPrinter::Print(const TypePtr& type)
354 return prefix_ + ".Ptr";356 return prefix_ + ".Ptr";
355 }357 }
356 358 
359+ if (auto token_type = As<TokenType>(type)) {
360+ return prefix_ + ".Token";
361+ }
362+ 
357 return prefix_ + ".Unknown";363 return prefix_ + ".Unknown";
358}364}
359 365 
@@ -725,14 +731,110 @@ void IRPrinter::VisitStmt_(const EvalStmtPtr& op)
725 731 
726void IRPrinter::VisitStmt_(const BreakStmtPtr& op)732void IRPrinter::VisitStmt_(const BreakStmtPtr& op)
727{733{
728- (void)op;
729 stream_ << "break";734 stream_ << "break";
735+ for (size_t i = 0; i < op->value_.size(); ++i) {
736+ stream_ << (i == 0 ? " " : ", ");
737+ VisitExpr(op->value_[i]);
738+ }
730}739}
731 740 
732void IRPrinter::VisitStmt_(const ContinueStmtPtr& op)741void IRPrinter::VisitStmt_(const ContinueStmtPtr& op)
733{742{
734- (void)op;
735 stream_ << "continue";743 stream_ << "continue";
744+ for (size_t i = 0; i < op->value_.size(); ++i) {
745+ stream_ << (i == 0 ? " " : ", ");
746+ VisitExpr(op->value_[i]);
747+ }
748+}
749+ 
750+void IRPrinter::VisitStmt_(const TensorOpStmtPtr& op)
751+{
752+ // res [, res_token] = opcode(args, tokens=[], attrs=[])
753+ if (op->result_.size() == 1) {
754+ VisitExpr(op->result_[0]);
755+ } else {
756+ stream_ << "[";
757+ for (size_t i = 0; i < op->result_.size(); ++i) {
758+ if (i > 0)
759+ stream_ << ", ";
760+ VisitExpr(op->result_[i]);
761+ }
762+ stream_ << "]";
763+ }
764+ if (op->result_token_) {
765+ stream_ << ", ";
766+ VisitExpr(op->result_token_);
767+ }
768+ stream_ << " = " << op->opcode_ << "(";
769+ for (size_t i = 0; i < op->args_.size(); ++i) {
770+ if (i > 0)
771+ stream_ << ", ";
772+ VisitExpr(op->args_[i]);
773+ }
774+ if (!op->tokens_.empty()) {
775+ stream_ << ", tokens=[";
776+ for (size_t i = 0; i < op->tokens_.size(); ++i) {
777+ if (i > 0)
778+ stream_ << ", ";
779+ VisitExpr(op->tokens_[i]);
780+ }
781+ stream_ << "]";
782+ }
783+ 
784+ auto printValue = [&](const std::string& key, const std::any& value) {
785+ stream_ << key << "=";
786+ if (value.type() == typeid(int)) {
787+ stream_ << AnyCast<int>(value);
788+ } else if (value.type() == typeid(double)) {
789+ stream_ << FormatFloatLiteral(AnyCast<double>(value));
790+ } else if (value.type() == typeid(float)) {
791+ stream_ << FormatFloatLiteral(static_cast<double>(AnyCast<float>(value)));
792+ } else if (value.type() == typeid(bool)) {
793+ stream_ << (AnyCast<bool>(value) ? "True" : "False");
794+ } else if (value.type() == typeid(std::string)) {
795+ stream_ << std::quoted(AnyCast<std::string>(value));
796+ } else if (value.type() == typeid(ExprPtr)) {
797+ VisitExpr(AnyCast<ExprPtr>(value));
798+ } else if (value.type() == typeid(std::vector<ExprPtr>)) {
799+ auto valueExpr = AnyCast<std::vector<ExprPtr>>(value);
800+ stream_ << "[";
801+ for (size_t i = 0; i < valueExpr.size(); ++i) {
802+ if (i > 0)
803+ stream_ << ", ";
804+ VisitExpr(valueExpr[i]);
805+ }
806+ stream_ << "]";
807+ } else {
808+ INTERNAL_CHECK(false) << "Unsupported function attrs value type: " << DemangleTypeName(value.type().name());
809+ }
810+ };
811+ if (!op->attrs_.empty()) {
812+ stream_ << ", attrs=[";
813+ for (size_t i = 0; i < op->attrs_.size(); ++i) {
814+ if (i > 0)
815+ stream_ << ", ";
816+ printValue(op->attrs_[i].first, op->attrs_[i].second);
817+ }
818+ stream_ << "]";
819+ }
820+ stream_ << ")";
821+}
822+ 
823+void IRPrinter::VisitStmt_(const ScalarOpStmtPtr& op)
824+{
825+ // res [, res_token] = opcode(args)
826+ VisitExpr(op->result_);
827+ if (op->result_token_) {
828+ stream_ << ", ";
829+ VisitExpr(op->result_token_);
830+ }
831+ stream_ << " = " << op->opcode_ << "(";
832+ for (size_t i = 0; i < op->args_.size(); ++i) {
833+ if (i > 0)
834+ stream_ << ", ";
835+ VisitExpr(op->args_[i]);
836+ }
837+ stream_ << ")";
736}838}
737 839 
738void IRPrinter::VisitStmt_(const StmtPtr& op) { stream_ << op->TypeName(); }840void IRPrinter::VisitStmt_(const StmtPtr& op) { stream_ << op->TypeName(); }
@@ -247,6 +247,10 @@ void IRVisitor::VisitStmt_(const BreakStmtPtr&) {}
247 247 
248void IRVisitor::VisitStmt_(const ContinueStmtPtr&) {}248void IRVisitor::VisitStmt_(const ContinueStmtPtr&) {}
249 249 
250+void IRVisitor::VisitStmt_(const ScalarOpStmtPtr&) {}
251+ 
252+void IRVisitor::VisitStmt_(const TensorOpStmtPtr&) {}
253+ 
250void IRVisitor::VisitStmt_(const StmtPtr&) {}254void IRVisitor::VisitStmt_(const StmtPtr&) {}
251 255 
252} // namespace ir256} // namespace ir
@@ -217,7 +217,7 @@ Operation::Operation(
217 217 
218 if (function_->IsGraphType({GraphType::TENSOR_GRAPH, GraphType::TILE_GRAPH})) {218 if (function_->IsGraphType({GraphType::TENSOR_GRAPH, GraphType::TILE_GRAPH})) {
219 SetSemanticLabel(config::GetSemanticLabel());219 SetSemanticLabel(config::GetSemanticLabel());
220- location_ = SourceLocation::GetLocation();220+ SetSpan(ir::Span::Current());
221 }221 }
222 222 
223 for (auto& input : GetIOperands()) {223 for (auto& input : GetIOperands()) {
@@ -412,10 +412,9 @@ void Operation::DumpLocationJson(Json& opDump) const
412 jlabel["lineno"] = semanticLabel_->lineno;412 jlabel["lineno"] = semanticLabel_->lineno;
413 opDump["semantic_label"] = jlabel;413 opDump["semantic_label"] = jlabel;
414 }414 }
415- if (location_ && config::GetPlatformConfig(KEY_DUMP_SOURCE_LOCATION, 0)) {415+ if (!span_.IsUnknown() && config::GetPlatformConfig(KEY_DUMP_SOURCE_LOCATION, 0)) {
416- opDump["file"] = location_->GetFileName();416+ opDump["file"] = span_.Filename();
417- opDump["line"] = location_->GetLineno();417+ opDump["line"] = span_.BeginLine();
418- opDump["backtrace"] = location_->GetBacktrace();
419 }418 }
420}419}
421 420 
@@ -541,8 +540,7 @@ void Operation::LoadLocationFromJson(const Json& opDump)
541 jlabel["label"].get<std::string>(), jlabel["filename"].get<std::string>(), jlabel["lineno"].get<int>());540 jlabel["label"].get<std::string>(), jlabel["filename"].get<std::string>(), jlabel["lineno"].get<int>());
542 }541 }
543 if (opDump.count("file")) {542 if (opDump.count("file")) {
544- location_ = std::make_shared<SourceLocation>(543+ span_ = ir::Span(opDump["file"].get<std::string>(), opDump["line"].get<int>(), 0);
545- opDump["file"].get<std::string>(), opDump["line"].get<int>(), opDump["backtrace"].get<std::string>());
546 }544 }
547}545}
548 546 
@@ -658,8 +656,8 @@ std::string Operation::DumpSSA(const std::string& prefix) const
658{656{
659 std::ostringstream oss;657 std::ostringstream oss;
660 658 
661- if (location_) {659+ if (!span_.IsUnknown()) {
662- oss << prefix << "/* " << location_->ToString() << " */\n";660+ oss << prefix << "/* " << span_.ToString() << " */\n";
663 }661 }
664 662 
665 if (GetCommentList().size() != 0) {663 if (GetCommentList().size() != 0) {
@@ -32,11 +32,12 @@
32#include "opcode.h"32#include "opcode.h"
33#include "attribute.h"33#include "attribute.h"
34#include "attr_holder.h"34#include "attr_holder.h"
35-#include "interface/utils/source_location.h"
36#include "interface/tensor/logical_tensor.h"35#include "interface/tensor/logical_tensor.h"
37#include "operation_common.h"36#include "operation_common.h"
37+#include "ir/core.h"
38 38 
39using Json = nlohmann::json;39using Json = nlohmann::json;
40+using namespace pypto;
40 41 
41namespace npu::tile_fwk {42namespace npu::tile_fwk {
42constexpr size_t NON_GROUP = -1;43constexpr size_t NON_GROUP = -1;
@@ -567,13 +568,15 @@ public:
567 }568 }
568 void UpdateSubgraphID(int subgraphID) { subgraphID_ = subgraphID; }569 void UpdateSubgraphID(int subgraphID) { subgraphID_ = subgraphID; }
569 // HashOrder attribute setters/getters using attribute mechanism570 // HashOrder attribute setters/getters using attribute mechanism
570- void SetHashOrderInfo(const std::string& hashOrderKey, const std::string& countKey,571+ void SetHashOrderInfo(
571- const std::string& hashOrder, size_t subgraphCount) {572+ const std::string& hashOrderKey, const std::string& countKey, const std::string& hashOrder,
573+ size_t subgraphCount)
574+ {
572 SetAttr(hashOrderKey, hashOrder);575 SetAttr(hashOrderKey, hashOrder);
573 SetAttr(countKey, static_cast<int64_t>(subgraphCount));576 SetAttr(countKey, static_cast<int64_t>(subgraphCount));
574 }577 }
575- std::pair<std::string, size_t> GetHashOrderInfo(const std::string& hashOrderKey,578+ std::pair<std::string, size_t> GetHashOrderInfo(const std::string& hashOrderKey, const std::string& countKey) const
576- const std::string& countKey) const {579+ {
577 std::string hashOrder;580 std::string hashOrder;
578 int64_t count = 0;581 int64_t count = 0;
579 GetAttr(hashOrderKey, hashOrder);582 GetAttr(hashOrderKey, hashOrder);
@@ -649,8 +652,8 @@ public:
649 const std::vector<int>& GetOOpAttrOffsets() const { return oOpAttrOffset; }652 const std::vector<int>& GetOOpAttrOffsets() const { return oOpAttrOffset; }
650 653 
651 std::vector<std::reference_wrapper<SymbolicScalar>> GetDynamicAttributeList();654 std::vector<std::reference_wrapper<SymbolicScalar>> GetDynamicAttributeList();
652- SourceLocationPtr GetLocation() const { return location_; }655+ const ir::Span& GetSpan() const { return span_; }
653- void SetLocation(SourceLocationPtr location) { location_ = location; }656+ void SetSpan(ir::Span span) { span_ = span; }
654 const std::vector<std::string>& GetCommentList() const { return commentList_; }657 const std::vector<std::string>& GetCommentList() const { return commentList_; }
655 std::vector<std::string>& GetCommentList() { return commentList_; }658 std::vector<std::string>& GetCommentList() { return commentList_; }
656 659 
@@ -672,7 +675,7 @@ private:
672 mutable size_t groupID_{NON_GROUP};675 mutable size_t groupID_{NON_GROUP};
673 bool isDeleted_{false};676 bool isDeleted_{false};
674 677 
675- SourceLocationPtr location_{nullptr};678+ ir::Span span_;
676 std::shared_ptr<SemanticLabel> semanticLabel_;679 std::shared_ptr<SemanticLabel> semanticLabel_;
677 Function* function_;680 Function* function_;
678 681 
@@ -21,20 +21,19 @@
21#include "tilefwk/tensor.h"21#include "tilefwk/tensor.h"
22#include "interface/tensor/logical_tensor.h"22#include "interface/tensor/logical_tensor.h"
23#include "interface/operation/opcode.h"23#include "interface/operation/opcode.h"
24-#include "interface/utils/source_location.h"
25#include "tilefwk/error_code.h"24#include "tilefwk/error_code.h"
26#include "tilefwk/platform.h"25#include "tilefwk/platform.h"
26+#include "ir/span.h"
27 27 
28namespace npu::tile_fwk {28namespace npu::tile_fwk {
29#define CALL(n, ...) Tensor##n(__VA_ARGS__)29#define CALL(n, ...) Tensor##n(__VA_ARGS__)
30#define RETURN_CALL(n, ...) return Tensor##n(__VA_ARGS__)30#define RETURN_CALL(n, ...) return Tensor##n(__VA_ARGS__)
31 31 
32-#define CHECK_OP(cond) \32+#define CHECK_OP(cond) \
33- (cond) ? 0 : \33+ (cond) ? 0 : \
34- npu::tile_fwk::Error(__func__, __FILE__, __LINE__) = \34+ npu::tile_fwk::Error(__func__, __FILE__, __LINE__) = \
35- npu::tile_fwk::ErrorMessage() \35+ npu::tile_fwk::ErrorMessage() << "CHECK FAILED: " #cond << "\n" \
36- << "CHECK FAILED: " #cond << "\n" \36+ << "location: " << pypto::ir::Span::Current().ToString() << "\n"
37- << "location: " << npu::tile_fwk::SourceLocation::GetLocationString() << "\n"
38 37 
39constexpr int32_t NUM_VALUE_0 = 0;38constexpr int32_t NUM_VALUE_0 = 0;
40constexpr int32_t NUM_VALUE_1 = 1;39constexpr int32_t NUM_VALUE_1 = 1;
@@ -142,7 +141,9 @@ enum class AIVCore;
142class OpSyncQueue {141class OpSyncQueue {
143public:142public:
144 OpSyncQueue() {}143 OpSyncQueue() {}
145- OpSyncQueue(PipeType pipeId, PipeType trigPipeId, CoreType coreType, CoreType tirgCoreType, int evid, AIVCore setAivCore, AIVCore waitAivCore)144+ OpSyncQueue(
145+ PipeType pipeId, PipeType trigPipeId, CoreType coreType, CoreType tirgCoreType, int evid, AIVCore setAivCore,
146+ AIVCore waitAivCore)
146 : pipeId_(pipeId),147 : pipeId_(pipeId),
147 trigPipeId_(trigPipeId),148 trigPipeId_(trigPipeId),
148 coreType_(coreType),149 coreType_(coreType),
@@ -82,7 +82,7 @@ void RecordFunc::RecordDynFuncInner(
82 82 
83 dynFunc_ = Program::GetInstance().GetCurrentFunction();83 dynFunc_ = Program::GetInstance().GetCurrentFunction();
84 dynFunc_->SetUnderDynamicFunction(true);84 dynFunc_->SetUnderDynamicFunction(true);
85- dynFunc_->SetSourceLocation(SourceLocation::GetLocation());85+ dynFunc_->SetSpan(ir::Span::Current());
86 86 
87 std::shared_ptr<DyndevFunctionAttribute> attr = std::make_shared<DyndevFunctionAttribute>();87 std::shared_ptr<DyndevFunctionAttribute> attr = std::make_shared<DyndevFunctionAttribute>();
88 attr->startArgsInputTensorList = startArgsInputTensorList;88 attr->startArgsInputTensorList = startArgsInputTensorList;
@@ -228,14 +228,15 @@ RecordLoopFunc::RecordLoopFunc(
228 if (parallel_) {228 if (parallel_) {
229 for (auto& rlf : Program::GetInstance().GetLoopStack()) {229 for (auto& rlf : Program::GetInstance().GetLoopStack()) {
230 if (rlf.get().Getparallel()) {230 if (rlf.get().Getparallel()) {
231- FE_ASSERT(FeError::INVALID_OPERATION, !rlf.get().Getparallel()) << "The parallel attribute value does not allow nesting";231+ FE_ASSERT(FeError::INVALID_OPERATION, !rlf.get().Getparallel())
232+ << "The parallel attribute value does not allow nesting";
232 }233 }
233 }234 }
234 }235 }
235 Program::GetInstance().GetLoopStack().emplace_back(*this);236 Program::GetInstance().GetLoopStack().emplace_back(*this);
236 237 
237 GenDefaultUnrollTimes(unrollList);238 GenDefaultUnrollTimes(unrollList);
238- location_ = SourceLocation::GetLocation();239+ span_ = ir::Span::Current();
239}240}
240 241 
241RecordLoopFunc::~RecordLoopFunc() { Program::GetInstance().GetLoopStack().pop_back(); }242RecordLoopFunc::~RecordLoopFunc() { Program::GetInstance().GetLoopStack().pop_back(); }
@@ -283,7 +284,7 @@ void RecordLoopFunc::BeginLoopFunction()
283 auto attr =284 auto attr =
284 std::make_shared<DynloopFunctionAttribute>(iterName_, *range, *loopRange_, submitBeforeLoop_, parallel_);285 std::make_shared<DynloopFunctionAttribute>(iterName_, *range, *loopRange_, submitBeforeLoop_, parallel_);
285 currentLoopFunc_->SetDynloopAttribute(attr);286 currentLoopFunc_->SetDynloopAttribute(attr);
286- currentLoopFunc_->SetSourceLocation(location_);287+ currentLoopFunc_->SetSpan(span_);
287}288}
288 289 
289void RecordLoopFunc::EndLoopFunction()290void RecordLoopFunc::EndLoopFunction()
@@ -396,7 +397,7 @@ void RecordLoopFunc::IterationBegin()
396 Program::GetInstance().GetTensorSlotManager()->Checkpoint();397 Program::GetInstance().GetTensorSlotManager()->Checkpoint();
397 Program::GetInstance().BeginFunction(curPathFuncName_, FunctionType::DYNAMIC_LOOP_PATH);398 Program::GetInstance().BeginFunction(curPathFuncName_, FunctionType::DYNAMIC_LOOP_PATH);
398 auto loopPathFunc = Program::GetInstance().GetCurrentFunction();399 auto loopPathFunc = Program::GetInstance().GetCurrentFunction();
399- loopPathFunc->SetSourceLocation(location_);400+ loopPathFunc->SetSpan(span_);
400 GetLoopAttr()->IterationBegin();401 GetLoopAttr()->IterationBegin();
401}402}
402 403 
@@ -50,7 +50,6 @@ public:
50 50 
51class LogicalTensor : public AttrHolder {51class LogicalTensor : public AttrHolder {
52public:52public:
53- 
54 std::shared_ptr<RawTensor> tensor;53 std::shared_ptr<RawTensor> tensor;
55 Offset offset;54 Offset offset;
56 Shape shape;55 Shape shape;
@@ -74,12 +73,12 @@ public:
74 LogicalTensor(73 LogicalTensor(
75 Function& function, DataType t, Shape tshape, std::vector<SymbolicScalar> tValidShape,74 Function& function, DataType t, Shape tshape, std::vector<SymbolicScalar> tValidShape,
76 TileOpFormat tformat = TileOpFormat::TILEOP_ND, std::string tname = "");75 TileOpFormat tformat = TileOpFormat::TILEOP_ND, std::string tname = "");
77- LogicalTensor(76+ LogicalTensor(Function& function, std::shared_ptr<RawTensor> rawTensor, Offset toffset, Shape tshape);
78- Function& function, std::shared_ptr<RawTensor> rawTensor, Offset toffset, Shape tshape);
79 LogicalTensor(77 LogicalTensor(
80 Function& function, std::shared_ptr<RawTensor> rawTensor, Offset toffset, Shape tshape,78 Function& function, std::shared_ptr<RawTensor> rawTensor, Offset toffset, Shape tshape,
81 std::vector<SymbolicScalar> tValidShape);79 std::vector<SymbolicScalar> tValidShape);
82- LogicalTensor(LogicalTensor&&) = default;80+ 
81+ LogicalTensor(LogicalTensor&&) = delete;
83 LogicalTensor(const LogicalTensor&) = default;82 LogicalTensor(const LogicalTensor&) = default;
84 LogicalTensor& operator=(LogicalTensor&&) = delete;83 LogicalTensor& operator=(LogicalTensor&&) = delete;
85 LogicalTensor& operator=(const LogicalTensor&) = delete;84 LogicalTensor& operator=(const LogicalTensor&) = delete;
@@ -18,11 +18,8 @@
18#include <sys/time.h>18#include <sys/time.h>
19#include <cstring>19#include <cstring>
20#include <algorithm>20#include <algorithm>
21-#include <memory>
22-#include <map>
23#include <vector>21#include <vector>
24#include <string>22#include <string>
25-#include <iostream>
26#include <sstream>23#include <sstream>
27#include <unordered_map>24#include <unordered_map>
28#include <functional>25#include <functional>
@@ -30,11 +27,9 @@
30#include <set>27#include <set>
31 28 
32#include "tilefwk/error.h"29#include "tilefwk/error.h"
33-#include "securec.h"
34#include "tilefwk/symbolic_scalar.h"30#include "tilefwk/symbolic_scalar.h"
35 31 
36namespace npu::tile_fwk {32namespace npu::tile_fwk {
37-using Status = uint32_t;
38 33 
39#ifdef __clang__34#ifdef __clang__
40#define __NO_UBSAN __attribute__((no_sanitize("unsigned-integer-overflow")))35#define __NO_UBSAN __attribute__((no_sanitize("unsigned-integer-overflow")))
@@ -42,9 +37,12 @@ using Status = uint32_t;
42#define __NO_UBSAN37#define __NO_UBSAN
43#endif38#endif
44 39 
45-#define SUCCESS 040+enum Status : uint32_t {
46-#define FAILED 141+ SUCCESS = 0,
47-#define WARNING 242+ FAILED = 1,
43+ WARNING = 2,
44+};
45+ 
48#define CACHELINE_SIZE_FOR_B64 6446#define CACHELINE_SIZE_FOR_B64 64
49 47 
50constexpr uint32_t DIST_COMM_GROUP_NUM = 2;48constexpr uint32_t DIST_COMM_GROUP_NUM = 2;
@@ -558,4 +556,4 @@ enum class PaddingMode : int64_t { NO_PADDING = 0, PADDING_OUTER = 1, PADDING_IN
558std::string SafeExecCommandWithOutput(const std::vector<std::string>& args);556std::string SafeExecCommandWithOutput(const std::vector<std::string>& args);
559 557 
560int SafeExecCommand(const std::vector<std::string>& args);558int SafeExecCommand(const std::vector<std::string>& args);
561-} // namespace npu::tile_fwk559+} // namespace npu::tile_fwk
@@ -17,7 +17,6 @@
17 17 
18#include <sys/cdefs.h>18#include <sys/cdefs.h>
19#include <cstdint>19#include <cstdint>
20-#include "source_location.h"
21 20 
22namespace npu::tile_fwk {21namespace npu::tile_fwk {
23class OperatorChecker {22class OperatorChecker {
@@ -34,7 +33,7 @@ private:
34};33};
35 34 
36struct OperatorTracer {35struct OperatorTracer {
37- OperatorTracer(const void* lr) : loc(lr)36+ OperatorTracer(const void*)
38 {37 {
39 if (IsCheckerEnabled()) {38 if (IsCheckerEnabled()) {
40 checker.PreCheck();39 checker.PreCheck();
@@ -46,7 +45,6 @@ struct OperatorTracer {
46 checker.PostCheck();45 checker.PostCheck();
47 }46 }
48 OperatorChecker checker;47 OperatorChecker checker;
49- SourceLocationHelper loc;
50 48 
51 bool IsCheckerEnabled() const;49 bool IsCheckerEnabled() const;
52};50};
@@ -1,134 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file source_location.cpp
13- * \brief
14- */
15- 
16-#include "source_location.h"
17-#include "interface/utils/common.h"
18- 
19-#include <dlfcn.h>
20-#include <cstdint>
21-#include <cstring>
22-#include <cstdio>
23-#include <map>
24-#include <memory>
25-#include <sstream>
26-#include <iostream>
27-#include <vector>
28-#include <unordered_set>
29- 
30-namespace npu::tile_fwk {
31- 
32-static std::map<std::pair<std::string, uint64_t>, std::vector<uint64_t>> BuildDlMap(const std::unordered_set<uint64_t>& pcSet)
33-{
34- Dl_info dlinfo;
35- std::map<std::pair<std::string, uint64_t>, std::vector<uint64_t>> dlMap;
36- for (auto pc : pcSet) {
37- if (dladdr((void*)pc, &dlinfo) != 0) {
38- dlMap[{dlinfo.dli_fname, (uint64_t)dlinfo.dli_fbase}].push_back(pc);
39- }
40- }
41- return dlMap;
42-}
43- 
44-static std::vector<std::string> BuildAddr2LineArgs(
45- const std::string& elfName, const std::vector<uint64_t>& pcs, uint64_t baseAddr)
46-{
47- std::vector<std::string> args = {"addr2line", "-i", "-p", "-e", elfName};
48- for (auto pc : pcs) {
49- std::stringstream ss;
50- ss << std::hex << (pc - (intptr_t)baseAddr);
51- args.push_back(ss.str());
52- }
53- return args;
54-}
55- 
56-static bool ParseLineInfo(const std::string& lineStr, std::string& fname, int& lineno)
57-{
58- if (lineStr.empty()) {
59- return false;
60- }
61- size_t colonPos = lineStr.find(":");
62- if (colonPos != std::string::npos) {
63- fname = lineStr.substr(0, colonPos);
64- long parsedLineno = strtol(lineStr.substr(colonPos + 1).c_str(), nullptr, 10);
65- lineno = static_cast<int>(parsedLineno);
66- return true;
67- } else {
68- fname = lineStr;
69- lineno = 0;
70- return true;
71- }
72-}
73- 
74-static void SetFallbackLocation(std::string& fname, int& lineno, const std::string& elfName, uint64_t pc, uint64_t baseAddr)
75-{
76- std::stringstream os;
77- os << elfName << "(+" << std::hex << pc - (intptr_t)baseAddr << ")";
78- fname = os.str();
79- lineno = 0;
80-}
81- 
82-void SourceLocation::Init() const
83-{
84- std::lock_guard<std::mutex> lock(mutex);
85- if (pcSet.empty()) {
86- return;
87- }
88- 
89- auto dlMap = BuildDlMap(pcSet);
90- pcSet.clear();
91- 
92- for (auto& [info, pcs] : dlMap) {
93- auto args = BuildAddr2LineArgs(info.first, pcs, info.second);
94- std::string output = SafeExecCommandWithOutput(args);
95- std::istringstream iss(output);
96- std::string lineStr;
97- 
98- for (auto pc : pcs) {
99- if (!std::getline(iss, lineStr)) {
100- SetFallbackLocation(locMap[pc]->fname_, locMap[pc]->lineno_, info.first, pc, info.second);
101- continue;
102- }
103- 
104- if (lineStr.find("inlined by") != std::string::npos && !std::getline(iss, lineStr)) {
105- lineStr.clear();
106- }
107- 
108- if (!ParseLineInfo(lineStr, locMap[pc]->fname_, locMap[pc]->lineno_)) {
109- SetFallbackLocation(locMap[pc]->fname_, locMap[pc]->lineno_, info.first, pc, info.second);
110- }
111- }
112- }
113-}
114- 
115-int SourceLocation::GetLineno() const
116-{
117- Init();
118- return lineno_;
119-}
120- 
121-const std::string& SourceLocation::GetFileName() const
122-{
123- Init();
124- return fname_;
125-}
126- 
127-const std::string& SourceLocation::GetBacktrace() const { return backtrace_; }
128- 
129-bool SourceLocation::isCppMode_ = false;
130-std::mutex SourceLocation::mutex;
131-std::stack<std::shared_ptr<SourceLocation>> SourceLocation::callStack;
132-std::unordered_set<uint64_t> SourceLocation::pcSet;
133-std::unordered_map<uint64_t, std::shared_ptr<SourceLocation>> SourceLocation::locMap;
134-} // namespace npu::tile_fwk
@@ -1,114 +0,0 @@
1-/**
2- * Copyright (c) 2025 Huawei Technologies Co., Ltd.
3- * This program is free software, you can redistribute it and/or modify it under the terms and conditions of
4- * CANN Open Software License Agreement Version 2.0 (the "License").
5- * Please refer to the License for details. You may not use this file except in compliance with the License.
6- * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
7- * INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8- * See LICENSE in the root of the software repository for the full text of the License.
9- */
10- 
11-/*!
12- * \file source_location.h
13- * \brief
14- */
15- 
16-#pragma once
17- 
18-#include <cstdint>
19-#include <memory>
20-#include <string>
21-#include <stack>
22-#include <mutex>
23-#include <unordered_map>
24-#include <unordered_set>
25- 
26-namespace npu::tile_fwk {
27- 
28-class SourceLocation {
29-public:
30- SourceLocation() = default;
31- SourceLocation(const std::string& fname, int lineno) : fname_(fname), lineno_(lineno) {}
32- SourceLocation(const std::string& fname, int lineno, const std::string& backtrace)
33- : fname_(fname), lineno_(lineno), backtrace_(backtrace)
34- {}
35- explicit SourceLocation(uint64_t pc) : fname_("??"), lineno_(-1), pc_(pc){};
36- 
37- int GetLineno() const;
38- const std::string& GetFileName() const;
39- const std::string& GetBacktrace() const;
40- std::string ToString() const { return GetFileName() + ":" + std::to_string(GetLineno()); }
41- 
42-public:
43- static void SetLocation(const void* pc) { callStack.push(GetLocation(reinterpret_cast<uint64_t>(pc))); }
44- static void SetLocation(std::shared_ptr<SourceLocation> loc) { callStack.push(loc); }
45- static void SetLocation(const std::string& fname, int lineno)
46- {
47- callStack.push(std::make_shared<SourceLocation>(fname, lineno));
48- }
49- static void SetLocation(const std::string& fname, int lineno, const std::string& backtrace)
50- {
51- callStack.push(std::make_shared<SourceLocation>(fname, lineno, backtrace));
52- }
53- static void ClearLocation() { callStack.pop(); }
54- static auto GetLocation() { return callStack.size() > 0 ? callStack.top() : nullptr; }
55- static std::string GetLocationString()
56- {
57- auto loc = GetLocation();
58- if (loc) {
59- return loc->ToString();
60- }
61- return "??:0:0";
62- }
63- 
64- static void SetCppMode(bool val) { isCppMode_ = val; }
65- static bool IsCppMode() { return isCppMode_; }
66- 
67-private:
68- static std::shared_ptr<SourceLocation> GetLocation(uint64_t pc)
69- {
70- std::lock_guard<std::mutex> lock(mutex);
71- if (locMap.find(pc) != locMap.end()) {
72- return locMap[pc];
73- }
74- auto loc = std::make_shared<SourceLocation>(pc);
75- locMap[pc] = loc;
76- pcSet.insert(pc);
77- return loc;
78- }
79- 
80- void Init() const;
81- 
82-private:
83- mutable std::string fname_;
84- mutable int lineno_;
85- std::string backtrace_;
86- uint64_t pc_;
87- static bool isCppMode_;
88- static std::mutex mutex;
89- static std::stack<std::shared_ptr<SourceLocation>> callStack;
90- static std::unordered_set<uint64_t> pcSet;
91- static std::unordered_map<uint64_t, std::shared_ptr<SourceLocation>> locMap;
92-};
93- 
94-using SourceLocationPtr = std::shared_ptr<SourceLocation>;
95- 
96-struct SourceLocationHelper {
97- // lr is return address, we need find caller address, minus 4 here
98- SourceLocationHelper(const void* lr)
99- {
100- if (SourceLocation::IsCppMode()) {
101- SourceLocation::SetLocation(static_cast<const uint8_t*>(lr) - 4);
102- }
103- }
104- ~SourceLocationHelper()
105- {
106- if (SourceLocation::IsCppMode()) {
107- SourceLocation::ClearLocation();
108- }
109- }
110-};
111- 
112-#define DEFINE_SOURCE_LOCATION() auto __loc = SourceLocationHelper(__builtin_return_address(0))
113- 
114-} // namespace npu::tile_fwk
@@ -365,9 +365,9 @@ static void BuildRootFuncKeyDict(DyndevFunctionAttribute* attr)
365static std::string BuildControlFlowCallee(Function* func, int ident)365static std::string BuildControlFlowCallee(Function* func, int ident)
366{366{
367 std::ostringstream oss;367 std::ostringstream oss;
368- auto loc = func->GetSourceLocation();368+ auto span = func->GetSpan();
369- if (loc) {369+ if (!span.IsUnknown()) {
370- oss << std::string(ident, ' ') << "// " << loc->ToString() << "\n";370+ oss << std::string(ident, ' ') << "// " << span.ToString() << "\n";
371 }371 }
372 oss << std::string(ident, ' ') << "// "372 oss << std::string(ident, ' ') << "// "
373 << "#name: " << func->GetRawName() << " #hash: " << func->GetFunctionHash()373 << "#name: " << func->GetRawName() << " #hash: " << func->GetFunctionHash()
@@ -1081,9 +1081,9 @@ static void CompileDyndevFunction(Function* function, FunctionCache& cache, [[ma
1081 std::string kernelPath;1081 std::string kernelPath;
1082#ifdef BUILD_WITH_CANN1082#ifdef BUILD_WITH_CANN
1083 bool enableCompile = (config::GetRuntimeOption<int64_t>(CFG_RUN_MODE) == CFG_RUN_MODE_NPU ||1083 bool enableCompile = (config::GetRuntimeOption<int64_t>(CFG_RUN_MODE) == CFG_RUN_MODE_NPU ||
1084- ((config::GetSimConfig(KEY_ACCURACY_LEVEL, 2) == 2) &&1084+ ((config::GetSimConfig(KEY_ACCURACY_LEVEL, 2) == 2) &&
1085- config::GetRuntimeOption<int64_t>(CFG_RUN_MODE) == CFG_RUN_MODE_SIM)) &&1085+ config::GetRuntimeOption<int64_t>(CFG_RUN_MODE) == CFG_RUN_MODE_SIM)) &&
1086- config::GetHostOption<int64_t>(COMPILE_STAGE) != CS_CODEGEN_INSTRUCTION;1086+ config::GetHostOption<int64_t>(COMPILE_STAGE) != CS_CODEGEN_INSTRUCTION;
1087 if (enableCompile) {1087 if (enableCompile) {
1088 if (IsLiteNPU(Platform::Instance().GetSoc().GetNPUArch())) {1088 if (IsLiteNPU(Platform::Instance().GetSoc().GetNPUArch())) {
1089 FindLiteNPUKernel(leafDict, kernelPath);1089 FindLiteNPUKernel(leafDict, kernelPath);
@@ -31,10 +31,7 @@ namespace {
31const char* kExtractPassLogScriptName = "extract_pass_log.py";31const char* kExtractPassLogScriptName = "extract_pass_log.py";
32const char* kExtractPassLogScriptInSource = "tools/scripts/extract_pass_log.py";32const char* kExtractPassLogScriptInSource = "tools/scripts/extract_pass_log.py";
33 33 
34-bool IsFileAccessible(const std::string& path)34+bool IsFileAccessible(const std::string& path) { return !path.empty() && access(path.c_str(), F_OK) == 0; }
35-{
36- return !path.empty() && access(path.c_str(), F_OK) == 0;
37-}
38 35 
39std::string ResolveExtractPassLogScriptPath()36std::string ResolveExtractPassLogScriptPath()
40{37{
@@ -69,15 +66,14 @@ std::string EscapeShellArg(const std::string& arg)
69// 入参为Operation对象66// 入参为Operation对象
70std::string GetFormatBacktrace(const Operation& op)67std::string GetFormatBacktrace(const Operation& op)
71{68{
72- auto location = op.GetLocation();69+ auto span = op.GetSpan();
73- if (!location) {70+ if (!span.IsUnknown()) {
74 return "";71 return "";
75 }72 }
76 73 
77 std::ostringstream oss;74 std::ostringstream oss;
78 oss << "[FuncMagic:" << op.BelongTo()->GetFuncMagic() << "]"75 oss << "[FuncMagic:" << op.BelongTo()->GetFuncMagic() << "]"
79- << "[OpMagic:" << op.opmagic << "]"76+ << "[OpMagic:" << op.opmagic << "].";
80- << "[Backtrace]:" << location->SourceLocation::GetBacktrace() << ".";
81 return oss.str();77 return oss.str();
82}78}
83 79 
@@ -115,9 +111,8 @@ void ExtractPassLogByFunction(const Function& function)
115 const std::string scriptPath = ResolveExtractPassLogScriptPath();111 const std::string scriptPath = ResolveExtractPassLogScriptPath();
116 if (scriptPath.empty()) {112 if (scriptPath.empty()) {
117 APASS_LOG_WARN_F(113 APASS_LOG_WARN_F(
118- Elements::Function,114+ Elements::Function, "%s not found under install(%s/scripts), or source(%s).", kExtractPassLogScriptName,
119- "%s not found under install(%s/scripts), or source(%s).",115+ GetCurrentSharedLibPath().c_str(), kExtractPassLogScriptInSource);
120- kExtractPassLogScriptName, GetCurrentSharedLibPath().c_str(), kExtractPassLogScriptInSource);
121 return;116 return;
122 }117 }
123 118 
@@ -129,9 +124,7 @@ void ExtractPassLogByFunction(const Function& function)
129 EscapeShellArg(functionName) + " -o " + EscapeShellArg(outputDir) + " --silentmode";124 EscapeShellArg(functionName) + " -o " + EscapeShellArg(outputDir) + " --silentmode";
130 int ret = std::system(command.c_str());125 int ret = std::system(command.c_str());
131 if (ret != 0) {126 if (ret != 0) {
132- APASS_LOG_WARN_F(127+ APASS_LOG_WARN_F(Elements::Function, "extract_pass_log.py failed(ret=%d), command: %s.", ret, command.c_str());
133- Elements::Function, "extract_pass_log.py failed(ret=%d), command: %s.",
134- ret, command.c_str());
135 }128 }
136}129}
137 130 
@@ -107,7 +107,8 @@ Status MergeViewAssembleUtils::AppendMergedViewOperations(Function& function)
107 APASS_LOG_ERROR_F(Elements::Function, "Failed to create ViewOpAttribute.");107 APASS_LOG_ERROR_F(Elements::Function, "Failed to create ViewOpAttribute.");
108 return FAILED;108 return FAILED;
109 }109 }
110- auto& mergedViewOp = function.AddRawOperation(Opcode::OP_VIEW, {viewOp.input}, {viewOp.output}, true, viewOp.sourceLocation);110+ auto& mergedViewOp =
111+ function.AddRawOperation(Opcode::OP_VIEW, {viewOp.input}, {viewOp.output}, true, viewOp.span);
111 mergedViewOp.SetScopeInfo(viewOp.scopeInfo);112 mergedViewOp.SetScopeInfo(viewOp.scopeInfo);
112 mergedViewOp.SetOpAttribute(attr);113 mergedViewOp.SetOpAttribute(attr);
113 // 继承op_attr_copy_in_mode属性114 // 继承op_attr_copy_in_mode属性
@@ -127,7 +128,8 @@ Status MergeViewAssembleUtils::AppendMergedAssembleOperations(Function& function
127 if (!attr) {128 if (!attr) {
128 return FAILED;129 return FAILED;
129 }130 }
130- auto& mergedAssembleOp = function.AddRawOperation(Opcode::OP_ASSEMBLE, {assembleOp.input}, {assembleOp.output}, true, assembleOp.sourceLocation);131+ auto& mergedAssembleOp = function.AddRawOperation(
132+ Opcode::OP_ASSEMBLE, {assembleOp.input}, {assembleOp.output}, true, assembleOp.span);
131 mergedAssembleOp.SetScopeInfo(assembleOp.scopeInfo);133 mergedAssembleOp.SetScopeInfo(assembleOp.scopeInfo);
132 mergedAssembleOp.SetOpAttribute(attr);134 mergedAssembleOp.SetOpAttribute(attr);
133 newOps_.push_back(&mergedAssembleOp);135 newOps_.push_back(&mergedAssembleOp);
@@ -147,21 +149,22 @@ Status MergeViewAssembleUtils::CleanUp(Function& function)
147 return SUCCESS;149 return SUCCESS;
148}150}
149 151 
150-SourceLocationPtr MergeViewAssembleUtils::GetFirstSourceLocation(const std::vector<Operation *> &chain) {152+ir::Span MergeViewAssembleUtils::GetFirstSpan(const std::vector<Operation*>& chain)
151- SourceLocationPtr firstSourceLocation = nullptr;153+{
152- for (auto *op : chain) {154+ ir::Span firstSpan;
153- auto loc = op->GetLocation();155+ for (auto* op : chain) {
154- if (loc != nullptr) {156+ auto loc = op->GetSpan();
155- firstSourceLocation = loc;157+ if (!loc.IsUnknown()) {
158+ firstSpan = loc;
156 break;159 break;
157 }160 }
158 }161 }
159- return firstSourceLocation;162+ return firstSpan;
160}163}
161 164 
162-Operation::ScopeInfo MergeViewAssembleUtils::GetChainScopeInfo(const std::vector<Operation*> &chain)165+Operation::ScopeInfo MergeViewAssembleUtils::GetChainScopeInfo(const std::vector<Operation*>& chain)
163{166{
164- for (auto *op : chain) {167+ for (auto* op : chain) {
165 if (op->GetScopeId() != -1) {168 if (op->GetScopeId() != -1) {
166 return op->GetScopeInfo();169 return op->GetScopeInfo();
167 }170 }
@@ -169,8 +172,8 @@ Operation::ScopeInfo MergeViewAssembleUtils::GetChainScopeInfo(const std::vector
169 return Operation::ScopeInfo();172 return Operation::ScopeInfo();
170}173}
171 174 
172-Status MergeViewAssembleUtils::MergeViewChain(Function& function, Operation& operation, std::vector<Operation*>& chain,175+Status MergeViewAssembleUtils::MergeViewChain(
173- int effectiveScopeId)176+ Function& function, Operation& operation, std::vector<Operation*>& chain, int effectiveScopeId)
174{177{
175 auto viewOpAttribute = std::dynamic_pointer_cast<ViewOpAttribute>(operation.GetOpAttribute());178 auto viewOpAttribute = std::dynamic_pointer_cast<ViewOpAttribute>(operation.GetOpAttribute());
176 // 1. 初始化操作链179 // 1. 初始化操作链
@@ -284,12 +287,12 @@ Status MergeViewAssembleUtils::ProcessChainEnd(Function& function, std::vector<O
284 if (status != SUCCESS) {287 if (status != SUCCESS) {
285 return status;288 return status;
286 }289 }
287- // 获取链路上第一个非空的sourceLocation290+ // 获取链路上第一个非空的span
288- SourceLocationPtr firstSourceLocation = GetFirstSourceLocation(chain);291+ ir::Span firstSpan = GetFirstSpan(chain);
289 Operation::ScopeInfo chainScopeInfo = GetChainScopeInfo(chain);292 Operation::ScopeInfo chainScopeInfo = GetChainScopeInfo(chain);
290 // 记录合并操作293 // 记录合并操作
291- RecordMergedViewOperation(endOp, startTensor, endTensor, newOffset, newDynOffset, newDynValidShape,294+ RecordMergedViewOperation(
292- firstSourceLocation, chainScopeInfo);295+ endOp, startTensor, endTensor, newOffset, newDynOffset, newDynValidShape, firstSpan, chainScopeInfo);
293 296 
294 // 清理链尾297 // 清理链尾
295 endOp->oOperand.clear();298 endOp->oOperand.clear();
@@ -341,7 +344,7 @@ void MergeViewAssembleUtils::RecordMergedViewOperation(
341 Operation* lastViewOp, const std::shared_ptr<LogicalTensor>& startTensor,344 Operation* lastViewOp, const std::shared_ptr<LogicalTensor>& startTensor,
342 const std::shared_ptr<LogicalTensor>& endTensor, const std::vector<int64_t>& newOffset,345 const std::shared_ptr<LogicalTensor>& endTensor, const std::vector<int64_t>& newOffset,
343 const std::vector<SymbolicScalar>& newDynOffset, const std::vector<SymbolicScalar>& newDynValidShape,346 const std::vector<SymbolicScalar>& newDynOffset, const std::vector<SymbolicScalar>& newDynValidShape,
344- const SourceLocationPtr &sourceLocation, const Operation::ScopeInfo &scopeInfo)347+ const ir::Span& span, const Operation::ScopeInfo& scopeInfo)
345{348{
346 // 获取最后一个VIEW的属性349 // 获取最后一个VIEW的属性
347 auto lastViewAttr = std::dynamic_pointer_cast<ViewOpAttribute>(lastViewOp->GetOpAttribute());350 auto lastViewAttr = std::dynamic_pointer_cast<ViewOpAttribute>(lastViewOp->GetOpAttribute());
@@ -356,7 +359,7 @@ void MergeViewAssembleUtils::RecordMergedViewOperation(
356 // 记录合并op359 // 记录合并op
357 viewOpToAppend_.emplace_back(ViewOp{360 viewOpToAppend_.emplace_back(ViewOp{
358 startTensor, endTensor, newOffset, newDynOffset, newDynValidShape, lastViewAttr->GetTo(), hasCopyInMode,361 startTensor, endTensor, newOffset, newDynOffset, newDynValidShape, lastViewAttr->GetTo(), hasCopyInMode,
359- std::move(copyInModeValue), sourceLocation, scopeInfo});362+ std::move(copyInModeValue), span, scopeInfo});
360}363}
361 364 
362Status MergeViewAssembleUtils::MergeAssembleChain(365Status MergeViewAssembleUtils::MergeAssembleChain(
@@ -376,8 +379,8 @@ Status MergeViewAssembleUtils::MergeAssembleChain(
376 if (assembleWithoutAssembleConsumer_.count(operation.opmagic) == 0) {379 if (assembleWithoutAssembleConsumer_.count(operation.opmagic) == 0) {
377 auto consumers = function.FindConsumers(operation);380 auto consumers = function.FindConsumers(operation);
378 chainEnd = consumers.empty();381 chainEnd = consumers.empty();
379- Status status = ProcessAssembleConsumers(function, consumers, chain, chainEnd, hasAssembleConsumer,382+ Status status =
380- effectiveScopeId);383+ ProcessAssembleConsumers(function, consumers, chain, chainEnd, hasAssembleConsumer, effectiveScopeId);
381 if (status != SUCCESS) {384 if (status != SUCCESS) {
382 return status;385 return status;
383 }386 }
@@ -453,11 +456,11 @@ Status MergeViewAssembleUtils::ProcessAssembleChainEnd(
453 }456 }
454 // 计算合并offset457 // 计算合并offset
455 auto [newOffset, newDynOffset] = CalculateAssembleOffsets(chain, startTensor->offset.size());458 auto [newOffset, newDynOffset] = CalculateAssembleOffsets(chain, startTensor->offset.size());
456- // 获取链路上第一个非空的sourceLocation459+ // 获取链路上第一个非空的span
457- SourceLocationPtr firstSourceLocation = GetFirstSourceLocation(chain);460+ ir::Span firstSpan = GetFirstSpan(chain);
458 Operation::ScopeInfo chainScopeInfo = GetChainScopeInfo(chain);461 Operation::ScopeInfo chainScopeInfo = GetChainScopeInfo(chain);
459 // 4. 记录并清理462 // 4. 记录并清理
460- RecordAssembleOperation(startTensor, endTensor, newOffset, newDynOffset, firstSourceLocation, chainScopeInfo);463+ RecordAssembleOperation(startTensor, endTensor, newOffset, newDynOffset, firstSpan, chainScopeInfo);
461 function.GetTensorMap().Erase(endTensor);464 function.GetTensorMap().Erase(endTensor);
462 operation.SetAsDeleted();465 operation.SetAsDeleted();
463 466 
@@ -495,10 +498,10 @@ std::pair<std::vector<int64_t>, std::vector<SymbolicScalar>> MergeViewAssembleUt
495 498 
496void MergeViewAssembleUtils::RecordAssembleOperation(499void MergeViewAssembleUtils::RecordAssembleOperation(
497 const std::shared_ptr<LogicalTensor>& input, const std::shared_ptr<LogicalTensor>& output,500 const std::shared_ptr<LogicalTensor>& input, const std::shared_ptr<LogicalTensor>& output,
498- const std::vector<int64_t>& offset, const std::vector<SymbolicScalar>& dynOffset,501+ const std::vector<int64_t>& offset, const std::vector<SymbolicScalar>& dynOffset, const ir::Span& span,
499- const SourceLocationPtr &sourceLocation, const Operation::ScopeInfo &scopeInfo)502+ const Operation::ScopeInfo& scopeInfo)
500{503{
501- assembleOpToAppend_.emplace_back(AssembleOp{input, output, offset, dynOffset, sourceLocation, scopeInfo});504+ assembleOpToAppend_.emplace_back(AssembleOp{input, output, offset, dynOffset, span, scopeInfo});
502}505}
503 506 
504Status MergeViewAssembleUtils::EraseRedundantAssemble(Function& function) const507Status MergeViewAssembleUtils::EraseRedundantAssemble(Function& function) const
@@ -35,7 +35,7 @@ public:
35 MemoryType toType = MemoryType::MEM_UNKNOWN;35 MemoryType toType = MemoryType::MEM_UNKNOWN;
36 bool hasCopyInMode; // 是否有copy_in_mode属性36 bool hasCopyInMode; // 是否有copy_in_mode属性
37 npu::tile_fwk::Any copyInModeValue; // copy_in_mode属性值37 npu::tile_fwk::Any copyInModeValue; // copy_in_mode属性值
38- SourceLocationPtr sourceLocation; // 链路最早操作的sourceLocation38+ ir::Span span; // 链路最早操作的span
39 Operation::ScopeInfo scopeInfo;39 Operation::ScopeInfo scopeInfo;
40 };40 };
41 struct AssembleOp {41 struct AssembleOp {
@@ -43,7 +43,7 @@ public:
43 std::shared_ptr<LogicalTensor> output;43 std::shared_ptr<LogicalTensor> output;
44 std::vector<int64_t> offset;44 std::vector<int64_t> offset;
45 std::vector<SymbolicScalar> dynOffset;45 std::vector<SymbolicScalar> dynOffset;
46- SourceLocationPtr sourceLocation; // 链路最早操作的sourceLocation46+ ir::Span span; // 链路最早操作的span
47 Operation::ScopeInfo scopeInfo;47 Operation::ScopeInfo scopeInfo;
48 };48 };
49 49 
@@ -60,8 +60,8 @@ public:
60 * @param chain the list of operations in the view chain.60 * @param chain the list of operations in the view chain.
61 * @return Status indicating success or failed.61 * @return Status indicating success or failed.
62 */62 */
63- Status MergeViewChain(Function& function, Operation& operation, std::vector<Operation*>& chain,63+ Status MergeViewChain(
64- int effectiveScopeId = -1);64+ Function& function, Operation& operation, std::vector<Operation*>& chain, int effectiveScopeId = -1);
65 65 
66 void InitOperationChain(Operation& operation, std::vector<Operation*>& chain);66 void InitOperationChain(Operation& operation, std::vector<Operation*>& chain);
67 67 
@@ -107,7 +107,7 @@ public:
107 Operation* lastViewOp, const std::shared_ptr<LogicalTensor>& startTensor,107 Operation* lastViewOp, const std::shared_ptr<LogicalTensor>& startTensor,
108 const std::shared_ptr<LogicalTensor>& endTensor, const std::vector<int64_t>& newOffset,108 const std::shared_ptr<LogicalTensor>& endTensor, const std::vector<int64_t>& newOffset,
109 const std::vector<SymbolicScalar>& newDynOffset, const std::vector<SymbolicScalar>& newDynValidShape,109 const std::vector<SymbolicScalar>& newDynOffset, const std::vector<SymbolicScalar>& newDynValidShape,
110- const SourceLocationPtr &sourceLocation, const Operation::ScopeInfo &scopeInfo);110+ const ir::Span& span, const Operation::ScopeInfo& scopeInfo);
111 111 
112 // Assemble chain processing methods112 // Assemble chain processing methods
113 /**113 /**
@@ -118,8 +118,8 @@ public:
118 * @param chain the list of operations in the assemble chain.118 * @param chain the list of operations in the assemble chain.
119 * @return Status indicating success or failed.119 * @return Status indicating success or failed.
120 */120 */
121- Status MergeAssembleChain(Function& function, Operation& operation, std::vector<Operation*>& chain,121+ Status MergeAssembleChain(
122- int effectiveScopeId = -1);122+ Function& function, Operation& operation, std::vector<Operation*>& chain, int effectiveScopeId = -1);
123 123 
124 void InitAssembleChain(Operation& operation, std::vector<Operation*>& chain);124 void InitAssembleChain(Operation& operation, std::vector<Operation*>& chain);
125 125 
@@ -144,13 +144,13 @@ public:
144 144 
145 void RecordAssembleOperation(145 void RecordAssembleOperation(
146 const std::shared_ptr<LogicalTensor>& input, const std::shared_ptr<LogicalTensor>& output,146 const std::shared_ptr<LogicalTensor>& input, const std::shared_ptr<LogicalTensor>& output,
147- const std::vector<int64_t>& offset, const std::vector<SymbolicScalar>& dynOffset,147+ const std::vector<int64_t>& offset, const std::vector<SymbolicScalar>& dynOffset, const ir::Span& span,
148- const SourceLocationPtr &sourceLocation, const Operation::ScopeInfo &scopeInfo);148+ const Operation::ScopeInfo& scopeInfo);
149 149 
150 // Common methods150 // Common methods
151 Status Initialize();151 Status Initialize();
152- static SourceLocationPtr GetFirstSourceLocation(const std::vector<Operation *> &chain);152+ static ir::Span GetFirstSpan(const std::vector<Operation*>& chain);
153- static Operation::ScopeInfo GetChainScopeInfo(const std::vector<Operation*> &chain);153+ static Operation::ScopeInfo GetChainScopeInfo(const std::vector<Operation*>& chain);
154 154 
155 // Processing methods155 // Processing methods
156 Status ProcessOperations(Function& function);156 Status ProcessOperations(Function& function);
@@ -18,7 +18,6 @@
18#include "interface/function/function.h"18#include "interface/function/function.h"
19#include "interface/tensor/raw_tensor.h"19#include "interface/tensor/raw_tensor.h"
20#include "interface/tensor/logical_tensor.h"20#include "interface/tensor/logical_tensor.h"
21-#include "interface/utils/source_location.h"
22#include "tilefwk/tilefwk.h"21#include "tilefwk/tilefwk.h"
23#include "interface/inner/tilefwk.h"22#include "interface/inner/tilefwk.h"
24#include "interface/program/program.h"23#include "interface/program/program.h"
@@ -196,11 +195,12 @@ Status ExpandFunction::Expandfunction(Function& function) const
196 if (op->GetOpcode() == Opcode::OP_PRINT) {195 if (op->GetOpcode() == Opcode::OP_PRINT) {
197 continue;196 continue;
198 }197 }
199- SourceLocation::SetLocation(op->GetLocation());
200 if (kNotNeedExpandOps.count(op->GetOpcode())) {198 if (kNotNeedExpandOps.count(op->GetOpcode())) {
201 ProcessForNotExpandOp(function, *op);199 ProcessForNotExpandOp(function, *op);
202 continue;200 continue;
203 }201 }
202+ 
203+ ir::Span::SetCurrent(op->GetSpan());
204 config::SetSemanticLabel(op->GetSemanticLabel());204 config::SetSemanticLabel(op->GetSemanticLabel());
205 size_t opListPreSize = function.Operations(false).size();205 size_t opListPreSize = function.Operations(false).size();
206 if (ExpandOperation(function, *op) != SUCCESS) {206 if (ExpandOperation(function, *op) != SUCCESS) {
@@ -214,19 +214,18 @@ Status ExpandFunction::Expandfunction(Function& function) const
214 newOp.CopyAttrFrom(*op, OP_EMUOP_PREFIX);214 newOp.CopyAttrFrom(*op, OP_EMUOP_PREFIX);
215 }215 }
216 }216 }
217- SourceLocation::ClearLocation();217+ ir::Span::ClearCurrent();
218 }218 }
219 function.expandFunctionAccelerate = false;219 function.expandFunctionAccelerate = false;
220 return SUCCESS;220 return SUCCESS;
221}221}
222 222 
223-Status ExpandFunction::ExpandOperation(Function &function, Operation &op) const{223+Status ExpandFunction::ExpandOperation(Function& function, Operation& op) const
224- const auto &info = op.GetScopeInfo();224+{
225+ const auto& info = op.GetScopeInfo();
225 std::vector<int64_t> scopeVec = {226 std::vector<int64_t> scopeVec = {
226- static_cast<int64_t>(info.scopeId),227+ static_cast<int64_t>(info.scopeId), static_cast<int64_t>(info.allowParallelMerge),
227- static_cast<int64_t>(info.allowParallelMerge),228+ static_cast<int64_t>(info.allowCrossScopeMerge)};
228- static_cast<int64_t>(info.allowCrossScopeMerge)
229- };
230 config::SetPassOption(SG_SET_SCOPE, scopeVec);229 config::SetPassOption(SG_SET_SCOPE, scopeVec);
231 ExpandOperationInto(function, op.GetTileShape(), op.GetOpcode(), op.GetIOperands(), op.GetOOperands(), op);230 ExpandOperationInto(function, op.GetTileShape(), op.GetOpcode(), op.GetIOperands(), op.GetOOperands(), op);
232 config::SetPassOption(SG_SET_SCOPE, std::vector<int64_t>{-1, 0, 0});231 config::SetPassOption(SG_SET_SCOPE, std::vector<int64_t>{-1, 0, 0});
@@ -249,30 +249,28 @@ void GenerateMoveOp::SetL0C2L1CopyAttr(
249 op.SetAttribute(OpAttributeKey::localCopyLocalMode, static_cast<int64_t>(copyMode));249 op.SetAttribute(OpAttributeKey::localCopyLocalMode, static_cast<int64_t>(copyMode));
250}250}
251 251 
252-void GenerateMoveOp::SetL0C2UBCopyAttr(Operation &op, const Shape &realShape,252+void GenerateMoveOp::SetL0C2UBCopyAttr(
253- const std::vector<OpImmediate> &fromOffset,253+ Operation& op, const Shape& realShape, const std::vector<OpImmediate>& fromOffset,
254- const std::vector<OpImmediate> &toOffset, Matrix::CopyMode copyMode) const {254+ const std::vector<OpImmediate>& toOffset, Matrix::CopyMode copyMode) const
255+{
255 std::vector<SymbolicScalar> validShape;256 std::vector<SymbolicScalar> validShape;
256 for (auto dim : realShape) {257 for (auto dim : realShape) {
257 SymbolicScalar scal = SymbolicScalar(dim);258 SymbolicScalar scal = SymbolicScalar(dim);
258 validShape.push_back(scal);259 validShape.push_back(scal);
259 }260 }
260 auto copyAttr = std::make_shared<CopyOpAttribute>(261 auto copyAttr = std::make_shared<CopyOpAttribute>(
261- fromOffset,262+ fromOffset, op.oOperand.front()->GetMemoryTypeOriginal(), OpImmediate::Specified(realShape),
262- op.oOperand.front()->GetMemoryTypeOriginal(),263+ OpImmediate::Specified(op.iOperand.front()->tensor->GetDynRawShape()), OpImmediate::Specified(validShape));
263- OpImmediate::Specified(realShape),
264- OpImmediate::Specified(op.iOperand.front()->tensor->GetDynRawShape()),
265- OpImmediate::Specified(validShape)
266- );
267 copyAttr->SetToOffset(toOffset);264 copyAttr->SetToOffset(toOffset);
268 op.SetOpAttribute(copyAttr);265 op.SetOpAttribute(copyAttr);
269 op.SetAttribute(OpAttributeKey::isCube, true);266 op.SetAttribute(OpAttributeKey::isCube, true);
270 op.SetAttribute(OpAttributeKey::localCopyLocalMode, static_cast<int64_t>(copyMode));267 op.SetAttribute(OpAttributeKey::localCopyLocalMode, static_cast<int64_t>(copyMode));
271}268}
272 269 
273-void GenerateMoveOp::SetUB2L1CopyAttr(Operation &op, const Shape &copyShape,270+void GenerateMoveOp::SetUB2L1CopyAttr(
274- const std::vector<OpImmediate> &fromOffset,271+ Operation& op, const Shape& copyShape, const std::vector<OpImmediate>& fromOffset,
275- const std::vector<OpImmediate> &toOffset, Matrix::CopyMode copyMode) const {272+ const std::vector<OpImmediate>& toOffset, Matrix::CopyMode copyMode) const
273+{
276 // 实际搬运的 shape 转换为 validShape274 // 实际搬运的 shape 转换为 validShape
277 std::vector<SymbolicScalar> validShape;275 std::vector<SymbolicScalar> validShape;
278 for (auto dim : copyShape) {276 for (auto dim : copyShape) {
@@ -281,11 +279,11 @@ void GenerateMoveOp::SetUB2L1CopyAttr(Operation &op, const Shape &copyShape,
281 }279 }
282 // 创建 CopyOpAttribute280 // 创建 CopyOpAttribute
283 auto copyAttr = std::make_shared<CopyOpAttribute>(281 auto copyAttr = std::make_shared<CopyOpAttribute>(
284- fromOffset, // fromOffset282+ fromOffset, // fromOffset
285- op.oOperand.front()->GetMemoryTypeOriginal(), // to (L1)283+ op.oOperand.front()->GetMemoryTypeOriginal(), // to (L1)
286- OpImmediate::Specified(copyShape), // shape (实际搬运的 shape)284+ OpImmediate::Specified(copyShape), // shape (实际搬运的 shape)
287 OpImmediate::Specified(op.iOperand.front()->tensor->GetDynRawShape()), // rawShape (srcValidShape)285 OpImmediate::Specified(op.iOperand.front()->tensor->GetDynRawShape()), // rawShape (srcValidShape)
288- OpImmediate::Specified(validShape) // toDynValidShape (dstValidShape)286+ OpImmediate::Specified(validShape) // toDynValidShape (dstValidShape)
289 );287 );
290 copyAttr->SetToOffset(toOffset);288 copyAttr->SetToOffset(toOffset);
291 op.SetOpAttribute(copyAttr);289 op.SetOpAttribute(copyAttr);
@@ -308,7 +306,7 @@ Status GenerateMoveOp::SetOpcodeByMemPath(Operation& op, MemoryType from, Memory
308 return SUCCESS;306 return SUCCESS;
309}307}
310 308 
311-void GenerateMoveOp::CreateMoveOpForAssemble(Function &function, Operation &op) const309+void GenerateMoveOp::CreateMoveOpForAssemble(Function& function, Operation& op) const
312{310{
313 auto assembleOpAttribute = dynamic_cast<AssembleOpAttribute*>(op.GetOpAttribute().get());311 auto assembleOpAttribute = dynamic_cast<AssembleOpAttribute*>(op.GetOpAttribute().get());
314 auto ASSEMBLE_in = op.iOperand.front();312 auto ASSEMBLE_in = op.iOperand.front();
@@ -324,8 +322,8 @@ void GenerateMoveOp::CreateMoveOpForAssemble(Function &function, Operation &op)
324 }322 }
325 if (inputMemtype == MemoryType::MEM_L0C && outputMemtype == MemoryType::MEM_UB) {323 if (inputMemtype == MemoryType::MEM_L0C && outputMemtype == MemoryType::MEM_UB) {
326 SetOpcodeByMemPath(op, inputMemtype, outputMemtype);324 SetOpcodeByMemPath(op, inputMemtype, outputMemtype);
327- SetL0C2UBCopyAttr(op, op.GetIOperands()[0]->GetShape(),325+ SetL0C2UBCopyAttr(
328- OpImmediate::Specified(ZERO_OFFSET),326+ op, op.GetIOperands()[0]->GetShape(), OpImmediate::Specified(ZERO_OFFSET),
329 OpImmediate::Specified(assembleOpAttribute->GetToTensorOffset()), Matrix::CopyMode::INSERT);327 OpImmediate::Specified(assembleOpAttribute->GetToTensorOffset()), Matrix::CopyMode::INSERT);
330 return;328 return;
331 }329 }
@@ -373,8 +371,8 @@ Status GenerateMoveOp::CreateMoveOpForConvert(Function& function, Operation& op)
373 OpImmediate::Specified(ZERO_OFFSET), Matrix::CopyMode::MOVE);371 OpImmediate::Specified(ZERO_OFFSET), Matrix::CopyMode::MOVE);
374 }372 }
375 if (op.GetOpcode() == Opcode::OP_L0C_COPY_UB) {373 if (op.GetOpcode() == Opcode::OP_L0C_COPY_UB) {
376- SetL0C2UBCopyAttr(op, op.GetOOperands()[0]->GetShape(),374+ SetL0C2UBCopyAttr(
377- OpImmediate::Specified(ZERO_OFFSET),375+ op, op.GetOOperands()[0]->GetShape(), OpImmediate::Specified(ZERO_OFFSET),
378 OpImmediate::Specified(ZERO_OFFSET), Matrix::CopyMode::MOVE);376 OpImmediate::Specified(ZERO_OFFSET), Matrix::CopyMode::MOVE);
379 op.SetAttribute(OpAttributeKey::isCube, true);377 op.SetAttribute(OpAttributeKey::isCube, true);
380 }378 }
@@ -403,7 +401,7 @@ void GenerateMoveOp::ProcessUB2L1(Function& function, Operation& op) const
403 ubNzTensor->SetMemoryTypeBoth(MemoryType::MEM_UB);401 ubNzTensor->SetMemoryTypeBoth(MemoryType::MEM_UB);
404 // 插入UB2UB节点(ND2NZ)402 // 插入UB2UB节点(ND2NZ)
405 auto& ub2ub = function.AddRawOperation(Opcode::OP_UB_COPY_ND2NZ, {inputTensor}, {ubNzTensor});403 auto& ub2ub = function.AddRawOperation(Opcode::OP_UB_COPY_ND2NZ, {inputTensor}, {ubNzTensor});
406- ub2ub.SetLocation(op.GetLocation());404+ ub2ub.SetSpan(op.GetSpan());
407 ub2ub.SetScopeInfo(op.GetScopeInfo());405 ub2ub.SetScopeInfo(op.GetScopeInfo());
408 ub2ub.UpdateSubgraphID(op.GetSubgraphID());406 ub2ub.UpdateSubgraphID(op.GetSubgraphID());
409 407 
@@ -484,16 +482,15 @@ Status GenerateMoveOp::ProcessL1CopyInConv(Operation& op) const
484 auto viewAttr = std::dynamic_pointer_cast<ViewOpAttribute>(producerOp->GetOpAttribute());482 auto viewAttr = std::dynamic_pointer_cast<ViewOpAttribute>(producerOp->GetOpAttribute());
485 if (viewAttr == nullptr) {483 if (viewAttr == nullptr) {
486 APASS_LOG_ERROR_F(484 APASS_LOG_ERROR_F(
487- Elements::Operation, "L1_COPY_IN_CONV op[%d]: VIEW producer[%d] has null ViewOpAttribute.",485+ Elements::Operation, "L1_COPY_IN_CONV op[%d]: VIEW producer[%d] has null ViewOpAttribute.", op.GetOpMagic(),
488- op.GetOpMagic(), producerOp->GetOpMagic());486+ producerOp->GetOpMagic());
489 return FAILED;487 return FAILED;
490 }488 }
491 489 
492 // 3. 将 VIEW 的 fromOffset 累加到 L1_COPY_IN_CONV 的 CopyOpAttribute 的 fromOffset490 // 3. 将 VIEW 的 fromOffset 累加到 L1_COPY_IN_CONV 的 CopyOpAttribute 的 fromOffset
493 auto copyAttr = std::dynamic_pointer_cast<CopyOpAttribute>(op.GetOpAttribute());491 auto copyAttr = std::dynamic_pointer_cast<CopyOpAttribute>(op.GetOpAttribute());
494 if (copyAttr == nullptr) {492 if (copyAttr == nullptr) {
495- APASS_LOG_ERROR_F(493+ APASS_LOG_ERROR_F(Elements::Operation, "L1_COPY_IN_CONV op[%d]: CopyOpAttribute is null.", op.GetOpMagic());
496- Elements::Operation, "L1_COPY_IN_CONV op[%d]: CopyOpAttribute is null.", op.GetOpMagic());
497 return FAILED;494 return FAILED;
498 }495 }
499 std::vector<OpImmediate> curFromOffset = copyAttr->GetFromOffset();496 std::vector<OpImmediate> curFromOffset = copyAttr->GetFromOffset();
@@ -513,8 +510,7 @@ Status GenerateMoveOp::ProcessL1CopyInConv(Operation& op) const
513 copyAttr->SetFromOffset(OpImmediate::Specified(ret));510 copyAttr->SetFromOffset(OpImmediate::Specified(ret));
514 } else {511 } else {
515 APASS_LOG_ERROR_F(512 APASS_LOG_ERROR_F(
516- Elements::Operation,513+ Elements::Operation, "L1_COPY_IN_CONV op[%d]: fromOffset size mismatch, cur size=%zu, view size=%zu.",
517- "L1_COPY_IN_CONV op[%d]: fromOffset size mismatch, cur size=%zu, view size=%zu.",
518 op.GetOpMagic(), curFromOffsetScalar.size(), viewOffsetScalar.size());514 op.GetOpMagic(), curFromOffsetScalar.size(), viewOffsetScalar.size());
519 return FAILED;515 return FAILED;
520 }516 }
@@ -554,22 +550,20 @@ Status GenerateMoveOp::ProcessL0CCopyOutConv(Operation& op) const
554 // 3. 将 ASSEMBLE 的 toOffset 累加到 L0C_COPY_OUT_CONV 的 toOffset550 // 3. 将 ASSEMBLE 的 toOffset 累加到 L0C_COPY_OUT_CONV 的 toOffset
555 auto copyAttr = std::dynamic_pointer_cast<CopyOpAttribute>(op.GetOpAttribute());551 auto copyAttr = std::dynamic_pointer_cast<CopyOpAttribute>(op.GetOpAttribute());
556 if (copyAttr == nullptr) {552 if (copyAttr == nullptr) {
557- APASS_LOG_ERROR_F(553+ APASS_LOG_ERROR_F(Elements::Operation, "L0C_COPY_OUT_CONV op[%d]: CopyOpAttribute is null.", op.GetOpMagic());
558- Elements::Operation, "L0C_COPY_OUT_CONV op[%d]: CopyOpAttribute is null.", op.GetOpMagic());
559 return FAILED;554 return FAILED;
560 }555 }
561 std::vector<OpImmediate> curToOffset = copyAttr->GetToOffset();556 std::vector<OpImmediate> curToOffset = copyAttr->GetToOffset();
562 557 
563 // 如果当前 offset 为空,直接使用 ASSEMBLE 的 offset558 // 如果当前 offset 为空,直接使用 ASSEMBLE 的 offset
564 if (curToOffset.empty()) {559 if (curToOffset.empty()) {
565- copyAttr->SetToOffset(OpImmediate::Specified(560+ copyAttr->SetToOffset(
566- TensorOffset(assembleAttr->GetToOffset(), assembleAttr->GetToDynOffset())));561+ OpImmediate::Specified(TensorOffset(assembleAttr->GetToOffset(), assembleAttr->GetToDynOffset())));
567 } else {562 } else {
568 // 使用 TensorOffset::Add 进行累加563 // 使用 TensorOffset::Add 进行累加
569 std::vector<SymbolicScalar> curToOffsetScalar = OpImmediate::ToSpecified(curToOffset);564 std::vector<SymbolicScalar> curToOffsetScalar = OpImmediate::ToSpecified(curToOffset);
570 std::vector<SymbolicScalar> assembleOffsetScalar = OpImmediate::ToSpecified(565 std::vector<SymbolicScalar> assembleOffsetScalar = OpImmediate::ToSpecified(
571- OpImmediate::Specified(566+ OpImmediate::Specified(TensorOffset(assembleAttr->GetToOffset(), assembleAttr->GetToDynOffset())));
572- TensorOffset(assembleAttr->GetToOffset(), assembleAttr->GetToDynOffset())));
573 567 
574 // 尺寸检查568 // 尺寸检查
575 if (curToOffsetScalar.size() == assembleOffsetScalar.size()) {569 if (curToOffsetScalar.size() == assembleOffsetScalar.size()) {
@@ -578,8 +572,8 @@ Status GenerateMoveOp::ProcessL0CCopyOutConv(Operation& op) const
578 } else {572 } else {
579 APASS_LOG_ERROR_F(573 APASS_LOG_ERROR_F(
580 Elements::Operation,574 Elements::Operation,
581- "L0C_COPY_OUT_CONV op[%d]: toOffset size mismatch, cur size=%zu, assemble size=%zu.",575+ "L0C_COPY_OUT_CONV op[%d]: toOffset size mismatch, cur size=%zu, assemble size=%zu.", op.GetOpMagic(),
582- op.GetOpMagic(), curToOffsetScalar.size(), assembleOffsetScalar.size());576+ curToOffsetScalar.size(), assembleOffsetScalar.size());
583 return FAILED;577 return FAILED;
584 }578 }
585 }579 }
@@ -616,8 +610,7 @@ Status GenerateMoveOp::ProcessDuplicateOp(Operation& op) const
616 newOffset.push_back(OpImmediate::Specified(SymbolicScalar(0)));610 newOffset.push_back(OpImmediate::Specified(SymbolicScalar(0)));
617 }611 }
618 op.SetOpAttribute(std::make_shared<CopyOpAttribute>(612 op.SetOpAttribute(std::make_shared<CopyOpAttribute>(
619- op.iOperand.front()->GetMemoryTypeOriginal(), newOffset,613+ op.iOperand.front()->GetMemoryTypeOriginal(), newOffset, OpImmediate::Specified(op.iOperand.front()->shape),
620- OpImmediate::Specified(op.iOperand.front()->shape),
621 OpImmediate::Specified(op.oOperand.front()->tensor->GetDynRawShape())));614 OpImmediate::Specified(op.oOperand.front()->tensor->GetDynRawShape())));
622 return SUCCESS;615 return SUCCESS;
623}616}
@@ -39,11 +39,9 @@ Status RemoveUnalignedReshape::RunOnFunction(Function& function)
39 GraphUtils::CopyDynStatus(a.output, a.input);39 GraphUtils::CopyDynStatus(a.output, a.input);
40 auto& newCopyOut = function.AddRawOperation(Opcode::OP_COPY_OUT, {a.input}, {a.output});40 auto& newCopyOut = function.AddRawOperation(Opcode::OP_COPY_OUT, {a.input}, {a.output});
41 newOps.push_back(&newCopyOut);41 newOps.push_back(&newCopyOut);
42- newCopyOut.SetOpAttribute(42+ newCopyOut.SetOpAttribute(std::make_shared<CopyOpAttribute>(
43- std::make_shared<CopyOpAttribute>(43+ a.from, OpImmediate::Specified(a.toOffset), OpImmediate::Specified(newCopyOut.iOperand.front()->shape),
44- a.from, OpImmediate::Specified(a.toOffset),44+ OpImmediate::Specified(newCopyOut.oOperand.front()->tensor->GetDynRawShape())));
45- OpImmediate::Specified(newCopyOut.iOperand.front()->shape),
46- OpImmediate::Specified(newCopyOut.oOperand.front()->tensor->GetDynRawShape())));
47 auto producerOp = *(a.input->GetProducers().begin());45 auto producerOp = *(a.input->GetProducers().begin());
48 newCopyOut.UpdateSubgraphID(producerOp->GetSubgraphID());46 newCopyOut.UpdateSubgraphID(producerOp->GetSubgraphID());
49 APASS_LOG_INFO_F(47 APASS_LOG_INFO_F(
@@ -54,12 +52,10 @@ Status RemoveUnalignedReshape::RunOnFunction(Function& function)
54 GraphUtils::CopyDynStatus(b.input, b.output);52 GraphUtils::CopyDynStatus(b.input, b.output);
55 auto& newCopyIn = function.AddRawOperation(Opcode::OP_COPY_IN, {b.input}, {b.output});53 auto& newCopyIn = function.AddRawOperation(Opcode::OP_COPY_IN, {b.input}, {b.output});
56 newOps.push_back(&newCopyIn);54 newOps.push_back(&newCopyIn);
57- newCopyIn.SetOpAttribute(55+ newCopyIn.SetOpAttribute(std::make_shared<CopyOpAttribute>(
58- std::make_shared<CopyOpAttribute>(56+ OpImmediate::Specified(b.fromOffset), b.to, OpImmediate::Specified(newCopyIn.oOperand.front()->shape),
59- OpImmediate::Specified(b.fromOffset), b.to,57+ OpImmediate::Specified(newCopyIn.iOperand.front()->tensor->GetDynRawShape()),
60- OpImmediate::Specified(newCopyIn.oOperand.front()->shape),58+ OpImmediate::Specified(newCopyIn.iOperand.front()->GetDynValidShape())));
61- OpImmediate::Specified(newCopyIn.iOperand.front()->tensor->GetDynRawShape()),
62- OpImmediate::Specified(newCopyIn.iOperand.front()->GetDynValidShape())));
63 auto consumerOp = *(b.output->GetConsumers().begin());59 auto consumerOp = *(b.output->GetConsumers().begin());
64 newCopyIn.UpdateSubgraphID(consumerOp->GetSubgraphID());60 newCopyIn.UpdateSubgraphID(consumerOp->GetSubgraphID());
65 APASS_LOG_INFO_F(61 APASS_LOG_INFO_F(
@@ -72,7 +68,7 @@ Status RemoveUnalignedReshape::RunOnFunction(Function& function)
72 return FAILED;68 return FAILED;
73 }69 }
74 }70 }
75- 71+ 
76 APASS_LOG_INFO_F(Elements::Function, "===> End RemoveUnalignedReshape.");72 APASS_LOG_INFO_F(Elements::Function, "===> End RemoveUnalignedReshape.");
77 return SUCCESS;73 return SUCCESS;
78}74}
@@ -83,12 +79,11 @@ LogicalTensorPtr RemoveUnalignedReshape::InsertIOTensor(
83{79{
84 (void)op;80 (void)op;
85 if (rawIO.count(ioTensor->tensor->rawmagic) == 0) {81 if (rawIO.count(ioTensor->tensor->rawmagic) == 0) {
86- auto reshapeRawTensor =82+ auto reshapeRawTensor = std::make_shared<RawTensor>(ioTensor->Datatype(), ioTensor->shape, ioTensor->Format());
87- std::make_shared<RawTensor>(ioTensor->Datatype(), ioTensor->shape, ioTensor->Format());
88 rawIO.insert({ioTensor->tensor->rawmagic, reshapeRawTensor});83 rawIO.insert({ioTensor->tensor->rawmagic, reshapeRawTensor});
89 }84 }
90- auto newReshapeIO = std::make_shared<LogicalTensor>(85+ auto newReshapeIO =
91- function, rawIO[ioTensor->tensor->rawmagic], ioTensor->offset, ioTensor->shape);86+ std::make_shared<LogicalTensor>(function, rawIO[ioTensor->tensor->rawmagic], ioTensor->offset, ioTensor->shape);
92 newReshapeIO->SetMemoryTypeBoth(MemoryType::MEM_DEVICE_DDR, true);87 newReshapeIO->SetMemoryTypeBoth(MemoryType::MEM_DEVICE_DDR, true);
93 function.GetTensorMap().Insert(newReshapeIO);88 function.GetTensorMap().Insert(newReshapeIO);
94 return newReshapeIO;89 return newReshapeIO;
@@ -179,12 +174,15 @@ void RemoveUnalignedReshape::ReplaceDynUnalignedReshapeOpsForUB(Function& functi
179 174 
180 for (const auto& dim : changedDims) {175 for (const auto& dim : changedDims) {
181 if ((size_t)dim >= outDynValidShape.size()) {176 if ((size_t)dim >= outDynValidShape.size()) {
182- APASS_LOG_WARN_F(Elements::Operation, "The dynValidShape of output[%d] of op[%d] has no [%ld] index.",177+ APASS_LOG_WARN_F(
178+ Elements::Operation, "The dynValidShape of output[%d] of op[%d] has no [%ld] index.",
183 output->GetMagic(), op.GetOpMagic(), static_cast<long>(dim));179 output->GetMagic(), op.GetOpMagic(), static_cast<long>(dim));
184 break;180 break;
185 } else if (!outDynValidShape[dim].IsImmediate()) {181 } else if (!outDynValidShape[dim].IsImmediate()) {
186- auto tmpWorkSpaceIn = std::make_shared<LogicalTensor>(function, input->Datatype(), input->shape, input->Format());182+ auto tmpWorkSpaceIn =
187- auto tmpWorkSpaceOut = std::make_shared<LogicalTensor>(function, input->Datatype(), output->shape, output->Format());183+ std::make_shared<LogicalTensor>(function, input->Datatype(), input->shape, input->Format());
184+ auto tmpWorkSpaceOut =
185+ std::make_shared<LogicalTensor>(function, input->Datatype(), output->shape, output->Format());
188 186 
189 tmpWorkSpaceIn->SetMemoryTypeBoth(MemoryType::MEM_DEVICE_DDR, true);187 tmpWorkSpaceIn->SetMemoryTypeBoth(MemoryType::MEM_DEVICE_DDR, true);
190 tmpWorkSpaceIn->UpdateDynValidShape(inDynValidShape);188 tmpWorkSpaceIn->UpdateDynValidShape(inDynValidShape);
@@ -201,20 +199,19 @@ void RemoveUnalignedReshape::ReplaceDynUnalignedReshapeOpsForUB(Function& functi
201 reshapeCopyOutOp.UpdateSubgraphID(op.GetSubgraphID());199 reshapeCopyOutOp.UpdateSubgraphID(op.GetSubgraphID());
202 reshapeCopyInOp.UpdateSubgraphID(op.GetSubgraphID());200 reshapeCopyInOp.UpdateSubgraphID(op.GetSubgraphID());
203 201 
204- reshapeCopyOutOp.SetOpAttribute(202+ reshapeCopyOutOp.SetOpAttribute(std::make_shared<CopyOpAttribute>(
205- std::make_shared<CopyOpAttribute>(203+ MemoryType::MEM_UB, OpImmediate::Specified(std::vector<SymbolicScalar>(input->shape.size(), 0)),
206- MemoryType::MEM_UB, OpImmediate::Specified(std::vector<SymbolicScalar>(input->shape.size(), 0)),204+ OpImmediate::Specified(input->shape), OpImmediate::Specified(input->tensor->GetDynRawShape()),
207- OpImmediate::Specified(input->shape), OpImmediate::Specified(input->tensor->GetDynRawShape()),205+ OpImmediate::Specified(input->GetDynValidShape())));
208- OpImmediate::Specified(input->GetDynValidShape())));
209 206 
210- reshapeCopyInOp.SetOpAttribute(207+ reshapeCopyInOp.SetOpAttribute(std::make_shared<CopyOpAttribute>(
211- std::make_shared<CopyOpAttribute>(208+ OpImmediate::Specified(std::vector<SymbolicScalar>(output->shape.size(), 0)),
212- OpImmediate::Specified(std::vector<SymbolicScalar>(output->shape.size(), 0)),209+ MemoryType::MEM_DEVICE_DDR, OpImmediate::Specified(output->shape),
213- MemoryType::MEM_DEVICE_DDR, OpImmediate::Specified(output->shape),210+ OpImmediate::Specified(output->tensor->GetDynRawShape()),
214- OpImmediate::Specified(output->tensor->GetDynRawShape()),211+ OpImmediate::Specified(output->GetDynValidShape())));
215- OpImmediate::Specified(output->GetDynValidShape())));
216 212 
217- APASS_LOG_INFO_F(Elements::Operation, "Reshape op %d is replaceed by reshapeCopyOutOp %d and reshapeCopyInOp %d.",213+ APASS_LOG_INFO_F(
214+ Elements::Operation, "Reshape op %d is replaceed by reshapeCopyOutOp %d and reshapeCopyInOp %d.",
218 op.opmagic, reshapeCopyOutOp.opmagic, reshapeCopyInOp.opmagic);215 op.opmagic, reshapeCopyOutOp.opmagic, reshapeCopyInOp.opmagic);
219 processedReshapeOps.insert(op.GetOpMagic());216 processedReshapeOps.insert(op.GetOpMagic());
220 function.EraseOperations(true, false);217 function.EraseOperations(true, false);
@@ -223,8 +220,9 @@ void RemoveUnalignedReshape::ReplaceDynUnalignedReshapeOpsForUB(Function& functi
223 }220 }
224}221}
225 222 
226-Operation* RemoveUnalignedReshape::CopyBranchBetweenCopyOut2Reshape(Function& function,223+Operation* RemoveUnalignedReshape::CopyBranchBetweenCopyOut2Reshape(
227- const std::vector<std::pair<Operation*, LogicalTensorPtr>>& toCopyProducerTensor, const int& consumerIndex) 224+ Function& function, const std::vector<std::pair<Operation*, LogicalTensorPtr>>& toCopyProducerTensor,
225+ const int& consumerIndex)
228{226{
229 bool canToCopy = false;227 bool canToCopy = false;
230 Operation* branchOp = nullptr;228 Operation* branchOp = nullptr;
@@ -266,7 +264,7 @@ Operation* RemoveUnalignedReshape::CopyBranchBetweenCopyOut2Reshape(Function& fu
266}264}
267 265 
268LogicalTensorPtr RemoveUnalignedReshape::HandleNoOrMultiCopyOutInProducer(266LogicalTensorPtr RemoveUnalignedReshape::HandleNoOrMultiCopyOutInProducer(
269- Function& function, Operation& op, bool& checkOverUbSize) 267+ Function& function, Operation& op, bool& checkOverUbSize)
270{268{
271 auto input = op.GetIOperands().front();269 auto input = op.GetIOperands().front();
272 auto copyShape = input->GetShape();270 auto copyShape = input->GetShape();
@@ -274,17 +272,16 @@ LogicalTensorPtr RemoveUnalignedReshape::HandleNoOrMultiCopyOutInProducer(
274 auto copyDynShape = input->GetDynValidShape();272 auto copyDynShape = input->GetDynValidShape();
275 Offset offset(copyShape.size(), 0);273 Offset offset(copyShape.size(), 0);
276 274 
277- LogicalTensor copyInOutput(function, input->Datatype(), copyShape);275+ auto copyInOutputPtr = std::make_shared<LogicalTensor>(function, input->Datatype(), copyShape);
278- copyInOutput.SetMemoryTypeBoth(MemoryType::MEM_UB, true);276+ copyInOutputPtr->SetMemoryTypeBoth(MemoryType::MEM_UB, true);
279- auto copyInOutputPtr = std::make_shared<LogicalTensor>(std::move(copyInOutput));
280 // 为copy到Ub的Tensor进行32B对齐277 // 为copy到Ub的Tensor进行32B对齐
281 AlignmentUtils::ProcessLastDim32BAlignedOnUB(copyInOutputPtr);278 AlignmentUtils::ProcessLastDim32BAlignedOnUB(copyInOutputPtr);
282- 279+ 
283 // 要copy到UB的Tensor,进行32B对齐之后判断是否超UB280 // 要copy到UB的Tensor,进行32B对齐之后判断是否超UB
284 const int UB_SIZE_THRESHOLD = static_cast<int>(Platform::Instance().GetDie().GetMemoryLimit(MemoryType::MEM_UB));281 const int UB_SIZE_THRESHOLD = static_cast<int>(Platform::Instance().GetDie().GetMemoryLimit(MemoryType::MEM_UB));
285 if (copyInOutputPtr->GetDataSize() > UB_SIZE_THRESHOLD) {282 if (copyInOutputPtr->GetDataSize() > UB_SIZE_THRESHOLD) {
286- APASS_LOG_WARN_F(Elements::Tensor, 283+ APASS_LOG_WARN_F(
287- "Tensor [%d] can not copy to UB, tensor size [%ld] exceeds the UB size [%d] limit.",284+ Elements::Tensor, "Tensor [%d] can not copy to UB, tensor size [%ld] exceeds the UB size [%d] limit.",
288 input->magic, input->GetDataSize(), UB_SIZE_THRESHOLD);285 input->magic, input->GetDataSize(), UB_SIZE_THRESHOLD);
289 checkOverUbSize = true;286 checkOverUbSize = true;
290 return nullptr;287 return nullptr;
@@ -296,9 +293,8 @@ LogicalTensorPtr RemoveUnalignedReshape::HandleNoOrMultiCopyOutInProducer(
296 OpImmediate::Specified(copyRawShape), OpImmediate::Specified(copyDynShape)));293 OpImmediate::Specified(copyRawShape), OpImmediate::Specified(copyDynShape)));
297 copyInOp.UpdateSubgraphID(op.GetSubgraphID());294 copyInOp.UpdateSubgraphID(op.GetSubgraphID());
298 295 
299- LogicalTensor copyOutOutput(function, input->Datatype(), copyShape);296+ auto copyOutOutputPtr = std::make_shared<LogicalTensor>(function, input->Datatype(), copyShape);
300- copyOutOutput.SetMemoryTypeBoth(MemoryType::MEM_DEVICE_DDR, true);297+ copyOutOutputPtr->SetMemoryTypeBoth(MemoryType::MEM_DEVICE_DDR, true);
301- auto copyOutOutputPtr = std::make_shared<LogicalTensor>(std::move(copyOutOutput));
302 auto& copyOutOp = function.AddOperation(Opcode::OP_COPY_OUT, {copyInOutputPtr}, {copyOutOutputPtr});298 auto& copyOutOp = function.AddOperation(Opcode::OP_COPY_OUT, {copyInOutputPtr}, {copyOutOutputPtr});
303 newOps.push_back(&copyOutOp);299 newOps.push_back(&copyOutOp);
304 copyOutOp.SetOpAttribute(std::make_shared<CopyOpAttribute>(300 copyOutOp.SetOpAttribute(std::make_shared<CopyOpAttribute>(
@@ -310,7 +306,7 @@ LogicalTensorPtr RemoveUnalignedReshape::HandleNoOrMultiCopyOutInProducer(
310 return copyOutOutputPtr;306 return copyOutOutputPtr;
311}307}
312 308 
313-int RemoveUnalignedReshape::FindConsumerIndex(LogicalTensorPtr input, Operation* consumerOp) 309+int RemoveUnalignedReshape::FindConsumerIndex(LogicalTensorPtr input, Operation* consumerOp)
314{310{
315 int index = 0;311 int index = 0;
316 for (auto con : input->GetConsumers()) {312 for (auto con : input->GetConsumers()) {
@@ -323,8 +319,8 @@ int RemoveUnalignedReshape::FindConsumerIndex(LogicalTensorPtr input, Operation*
323}319}
324 320 
325void RemoveUnalignedReshape::GetPathBetweenSingleCopyOutAndReshape(321void RemoveUnalignedReshape::GetPathBetweenSingleCopyOutAndReshape(
326- Operation* op, std::vector<std::pair<Operation*, LogicalTensorPtr>>& toCopyProducerTensor,322+ Operation* op, std::vector<std::pair<Operation*, LogicalTensorPtr>>& toCopyProducerTensor, bool& findCopyOut,
327- bool& findCopyOut, bool& needToCopy, int& index) 323+ bool& needToCopy, int& index)
328{324{
329 for (auto input : op->GetIOperands()) {325 for (auto input : op->GetIOperands()) {
330 auto producers = input->GetProducers();326 auto producers = input->GetProducers();
@@ -359,10 +355,11 @@ void RemoveUnalignedReshape::GetPathBetweenSingleCopyOutAndReshape(
359 }355 }
360}356}
361 357 
362-void RemoveUnalignedReshape::InsertReshapeCopy(Function& function, Operation& op) {358+void RemoveUnalignedReshape::InsertReshapeCopy(Function& function, Operation& op)
359+{
363 auto input = op.GetIOperands().front();360 auto input = op.GetIOperands().front();
364 auto output = op.GetOOperands().front();361 auto output = op.GetOOperands().front();
365- //进行处理前判断,防止误修改362+ // 进行处理前判断,防止误修改
366 std::vector<Operation*> copyOutOps;363 std::vector<Operation*> copyOutOps;
367 Operation* copyOutOp = nullptr;364 Operation* copyOutOp = nullptr;
368 std::vector<std::pair<Operation*, LogicalTensorPtr>> toCopyProducerTensor;365 std::vector<std::pair<Operation*, LogicalTensorPtr>> toCopyProducerTensor;
@@ -370,7 +367,7 @@ void RemoveUnalignedReshape::InsertReshapeCopy(Function& function, Operation& op
370 bool findCopyOut = false;367 bool findCopyOut = false;
371 bool needToCopy = false;368 bool needToCopy = false;
372 bool checkOverUbSize = false;369 bool checkOverUbSize = false;
373- //index表示copyout到reshape之间,有多个消费者的Tensor的第几个消费者是包含需要处理的reshape的370+ // index表示copyout到reshape之间,有多个消费者的Tensor的第几个消费者是包含需要处理的reshape的
374 FindAllProducerCopyOuts(input, copyOutOps);371 FindAllProducerCopyOuts(input, copyOutOps);
375 if (copyOutOps.empty() || copyOutOps.size() > 1) {372 if (copyOutOps.empty() || copyOutOps.size() > 1) {
376 auto newReshapeIo = HandleNoOrMultiCopyOutInProducer(function, op, checkOverUbSize);373 auto newReshapeIo = HandleNoOrMultiCopyOutInProducer(function, op, checkOverUbSize);
@@ -386,7 +383,7 @@ void RemoveUnalignedReshape::InsertReshapeCopy(Function& function, Operation& op
386 HandleNoCopyInConsumer(function, op, output, copyInOps, checkOverUbSize);383 HandleNoCopyInConsumer(function, op, output, copyInOps, checkOverUbSize);
387 }384 }
388 385 
389- //进行处理386+ // 进行处理
390 if (!checkOverUbSize) {387 if (!checkOverUbSize) {
391 if (needToCopy) {388 if (needToCopy) {
392 copyOutOp = CopyBranchBetweenCopyOut2Reshape(function, toCopyProducerTensor, index);389 copyOutOp = CopyBranchBetweenCopyOut2Reshape(function, toCopyProducerTensor, index);
@@ -394,7 +391,9 @@ void RemoveUnalignedReshape::InsertReshapeCopy(Function& function, Operation& op
394 ProcessCopyOutOfDDRReshape(function, op, copyOutOp);391 ProcessCopyOutOfDDRReshape(function, op, copyOutOp);
395 ProcessCopyInOfDDRReshape(function, op, copyInOps);392 ProcessCopyInOfDDRReshape(function, op, copyInOps);
396 } else {393 } else {
397- APASS_LOG_WARN_F(Elements::Tensor, "Reshape[%d] on GM had processed failed, "394+ APASS_LOG_WARN_F(
395+ Elements::Tensor,
396+ "Reshape[%d] on GM had processed failed, "
398 "because the size of input[%d] or output[%d] of reshape[%d] exceeded ub if copy to ub.",397 "because the size of input[%d] or output[%d] of reshape[%d] exceeded ub if copy to ub.",
399 op.GetOpMagic(), input->GetMagic(), output->GetMagic(), op.GetOpMagic());398 op.GetOpMagic(), input->GetMagic(), output->GetMagic(), op.GetOpMagic());
400 }399 }
@@ -431,9 +430,8 @@ void RemoveUnalignedReshape::HandleNoCopyInConsumer(
431 Function& function, Operation& op, LogicalTensorPtr output, std::vector<Operation*>& copyInOps,430 Function& function, Operation& op, LogicalTensorPtr output, std::vector<Operation*>& copyInOps,
432 bool& checkOverUbSize)431 bool& checkOverUbSize)
433{432{
434- LogicalTensor newCopyinTensor(function, output->Datatype(), output->GetShape());433+ auto newCopyinTensorPtr = std::make_shared<LogicalTensor>(function, output->Datatype(), output->GetShape());
435- newCopyinTensor.SetMemoryTypeBoth(MemoryType::MEM_UB, true);434+ newCopyinTensorPtr->SetMemoryTypeBoth(MemoryType::MEM_UB, true);
436- auto newCopyinTensorPtr = std::make_shared<LogicalTensor>(std::move(newCopyinTensor));
437 AlignmentUtils::ProcessLastDim32BAlignedOnUB(newCopyinTensorPtr);435 AlignmentUtils::ProcessLastDim32BAlignedOnUB(newCopyinTensorPtr);
438 436 
439 // 要copy到UB的Tensor,进行32B对齐之后判断是否超UB437 // 要copy到UB的Tensor,进行32B对齐之后判断是否超UB
@@ -450,22 +448,20 @@ void RemoveUnalignedReshape::HandleNoCopyInConsumer(
450 auto& newCopyInOp = function.AddOperation(Opcode::OP_COPY_IN, {output}, {newCopyinTensorPtr});448 auto& newCopyInOp = function.AddOperation(Opcode::OP_COPY_IN, {output}, {newCopyinTensorPtr});
451 newOps.push_back(&newCopyInOp);449 newOps.push_back(&newCopyInOp);
452 newCopyInOp.UpdateSubgraphID(op.GetSubgraphID());450 newCopyInOp.UpdateSubgraphID(op.GetSubgraphID());
453- newCopyInOp.SetOpAttribute(451+ newCopyInOp.SetOpAttribute(std::make_shared<CopyOpAttribute>(
454- std::make_shared<CopyOpAttribute>(452+ OpImmediate::Specified(std::vector<SymbolicScalar>(output->GetShape().size(), 0)), MemoryType::MEM_UB,
455- OpImmediate::Specified(std::vector<SymbolicScalar>(output->GetShape().size(), 0)), MemoryType::MEM_UB,453+ OpImmediate::Specified(output->GetShape()), OpImmediate::Specified(output->tensor->GetDynRawShape()),
456- OpImmediate::Specified(output->GetShape()), OpImmediate::Specified(output->tensor->GetDynRawShape()),454+ OpImmediate::Specified(output->GetDynValidShape())));
457- OpImmediate::Specified(output->GetDynValidShape())));455+ 
458- LogicalTensor newCopyoutTensor(function, output->Datatype(), output->GetShape());456+ auto newCopyoutTensorPtr = std::make_shared<LogicalTensor>(function, output->Datatype(), output->GetShape());
459- newCopyoutTensor.SetMemoryTypeBoth(MemoryType::MEM_DEVICE_DDR, true);457+ newCopyoutTensorPtr->SetMemoryTypeBoth(MemoryType::MEM_DEVICE_DDR, true);
460- auto newCopyoutTensorPtr = std::make_shared<LogicalTensor>(std::move(newCopyoutTensor));
461 auto& newCopyOutOp = function.AddOperation(Opcode::OP_COPY_OUT, {newCopyinTensorPtr}, {newCopyoutTensorPtr});458 auto& newCopyOutOp = function.AddOperation(Opcode::OP_COPY_OUT, {newCopyinTensorPtr}, {newCopyoutTensorPtr});
462 newOps.push_back(&newCopyOutOp);459 newOps.push_back(&newCopyOutOp);
463 newCopyOutOp.UpdateSubgraphID(op.GetSubgraphID());460 newCopyOutOp.UpdateSubgraphID(op.GetSubgraphID());
464- newCopyOutOp.SetOpAttribute(461+ newCopyOutOp.SetOpAttribute(std::make_shared<CopyOpAttribute>(
465- std::make_shared<CopyOpAttribute>(462+ MemoryType::MEM_UB, OpImmediate::Specified(std::vector<SymbolicScalar>(output->GetShape().size(), 0)),
466- MemoryType::MEM_UB, OpImmediate::Specified(std::vector<SymbolicScalar>(output->GetShape().size(), 0)),463+ OpImmediate::Specified(output->GetShape()), OpImmediate::Specified(output->tensor->GetDynRawShape()),
467- OpImmediate::Specified(output->GetShape()), OpImmediate::Specified(output->tensor->GetDynRawShape()),464+ OpImmediate::Specified(output->GetDynValidShape())));
468- OpImmediate::Specified(output->GetDynValidShape())));
469 auto consumers = output->GetConsumers();465 auto consumers = output->GetConsumers();
470 std::vector<Operation*> reshapeConsumers;466 std::vector<Operation*> reshapeConsumers;
471 for (auto& consumer : consumers) {467 for (auto& consumer : consumers) {
@@ -493,10 +489,11 @@ void RemoveUnalignedReshape::ProcessCopyOutOfDDRReshape(Function& function, Oper
493 copyOutOp->SetOpCode(Opcode::OP_RESHAPE_COPY_OUT);489 copyOutOp->SetOpCode(Opcode::OP_RESHAPE_COPY_OUT);
494 } else if (copyOutInputMemType != MemoryType::MEM_UB && copyOutOutputMemType == MemoryType::MEM_DEVICE_DDR) {490 } else if (copyOutInputMemType != MemoryType::MEM_UB && copyOutOutputMemType == MemoryType::MEM_DEVICE_DDR) {
495 // copyOutInput(NOTUB) -- COPYOUT -- copyOutOutput(DDR) -- reshape491 // copyOutInput(NOTUB) -- COPYOUT -- copyOutOutput(DDR) -- reshape
496- // copyOutInput(NOTUB) -- COPYOUT -- copyOutOutput(DDR) -- COPYIN -- newTensor(UB) -- RESHAPECOPYOUT -- newTensor2(DDR) -- reshape492+ // copyOutInput(NOTUB) -- COPYOUT -- copyOutOutput(DDR) -- COPYIN -- newTensor(UB) -- RESHAPECOPYOUT --
497- LogicalTensor newTensor(function, copyOutOutput->Datatype(), copyOutOutput->GetShape());493+ // newTensor2(DDR) -- reshape
498- newTensor.SetMemoryTypeBoth(MemoryType::MEM_UB, true);494+ auto newTensorPtr =
499- auto newTensorPtr = std::make_shared<LogicalTensor>(std::move(newTensor));495+ std::make_shared<LogicalTensor>(function, copyOutOutput->Datatype(), copyOutOutput->GetShape());
496+ newTensorPtr->SetMemoryTypeBoth(MemoryType::MEM_UB, true);
500 AlignmentUtils::ProcessLastDim32BAlignedOnUB(newTensorPtr);497 AlignmentUtils::ProcessLastDim32BAlignedOnUB(newTensorPtr);
501 // 要copy到UB的Tensor,在copy之前,进行32B对齐之后判断超UB498 // 要copy到UB的Tensor,在copy之前,进行32B对齐之后判断超UB
502 const size_t UB_SIZE_THRESHOLD = Platform::Instance().GetDie().GetMemoryLimit(MemoryType::MEM_UB);499 const size_t UB_SIZE_THRESHOLD = Platform::Instance().GetDie().GetMemoryLimit(MemoryType::MEM_UB);
@@ -512,26 +509,24 @@ void RemoveUnalignedReshape::ProcessCopyOutOfDDRReshape(Function& function, Oper
512 auto& reshapeCopyInOp = function.AddOperation(Opcode::OP_COPY_IN, {copyOutOutput}, {newTensorPtr});509 auto& reshapeCopyInOp = function.AddOperation(Opcode::OP_COPY_IN, {copyOutOutput}, {newTensorPtr});
513 newOps.push_back(&reshapeCopyInOp);510 newOps.push_back(&reshapeCopyInOp);
514 reshapeCopyInOp.UpdateSubgraphID(op.GetSubgraphID());511 reshapeCopyInOp.UpdateSubgraphID(op.GetSubgraphID());
515- reshapeCopyInOp.SetOpAttribute(512+ reshapeCopyInOp.SetOpAttribute(std::make_shared<CopyOpAttribute>(
516- std::make_shared<CopyOpAttribute>(513+ OpImmediate::Specified(std::vector<SymbolicScalar>(copyOutOutput->GetShape().size(), 0)),
517- OpImmediate::Specified(std::vector<SymbolicScalar>(copyOutOutput->GetShape().size(), 0)),514+ MemoryType::MEM_UB, OpImmediate::Specified(copyOutOutput->GetShape()),
518- MemoryType::MEM_UB, OpImmediate::Specified(copyOutOutput->GetShape()),515+ OpImmediate::Specified(copyOutOutput->tensor->GetDynRawShape()),
519- OpImmediate::Specified(copyOutOutput->tensor->GetDynRawShape()),516+ OpImmediate::Specified(copyOutOutput->GetDynValidShape())));
520- OpImmediate::Specified(copyOutOutput->GetDynValidShape())));
521 517 
522- LogicalTensor newTensor2(function, copyOutOutput->Datatype(), copyOutOutput->GetShape());518+ auto newTensor2Ptr =
523- newTensor2.SetMemoryTypeBoth(MemoryType::MEM_DEVICE_DDR, true);519+ std::make_shared<LogicalTensor>(function, copyOutOutput->Datatype(), copyOutOutput->GetShape());
524- auto newTensor2Ptr = std::make_shared<LogicalTensor>(std::move(newTensor2));520+ newTensor2Ptr->SetMemoryTypeBoth(MemoryType::MEM_DEVICE_DDR, true);
525 auto& newCopyOutOp = function.AddOperation(Opcode::OP_RESHAPE_COPY_OUT, {newTensorPtr}, {newTensor2Ptr});521 auto& newCopyOutOp = function.AddOperation(Opcode::OP_RESHAPE_COPY_OUT, {newTensorPtr}, {newTensor2Ptr});
526 newOps.push_back(&newCopyOutOp);522 newOps.push_back(&newCopyOutOp);
527 newCopyOutOp.UpdateSubgraphID(op.GetSubgraphID());523 newCopyOutOp.UpdateSubgraphID(op.GetSubgraphID());
528- newCopyOutOp.SetOpAttribute(524+ newCopyOutOp.SetOpAttribute(std::make_shared<CopyOpAttribute>(
529- std::make_shared<CopyOpAttribute>(525+ MemoryType::MEM_UB,
530- MemoryType::MEM_UB,526+ OpImmediate::Specified(std::vector<SymbolicScalar>(copyOutOutput->GetShape().size(), 0)),
531- OpImmediate::Specified(std::vector<SymbolicScalar>(copyOutOutput->GetShape().size(), 0)),527+ OpImmediate::Specified(copyOutOutput->GetShape()),
532- OpImmediate::Specified(copyOutOutput->GetShape()),528+ OpImmediate::Specified(copyOutOutput->tensor->GetDynRawShape()),
533- OpImmediate::Specified(copyOutOutput->tensor->GetDynRawShape()),529+ OpImmediate::Specified(copyOutOutput->GetDynValidShape())));
534- OpImmediate::Specified(copyOutOutput->GetDynValidShape())));
535 530 
536 copyOutOutput->RemoveConsumer(&op);531 copyOutOutput->RemoveConsumer(&op);
537 op.ReplaceInput(newTensor2Ptr, copyOutOutput);532 op.ReplaceInput(newTensor2Ptr, copyOutOutput);
@@ -565,37 +560,45 @@ void RemoveUnalignedReshape::ProcessCopyInOfDDRReshape(
565 // reshape -- copyInInput(DDR) -- COPYIN -- copyInOutout(NOTUB)560 // reshape -- copyInInput(DDR) -- COPYIN -- copyInOutout(NOTUB)
566 // reshape -- copyInInput(DDR) -- RESHAPECOPYIN -- newTensor(UB) -- COPYOUT -- newTensor2(DDR) -- COPYIN561 // reshape -- copyInInput(DDR) -- RESHAPECOPYIN -- newTensor(UB) -- COPYOUT -- newTensor2(DDR) -- COPYIN
567 // --copyInOutout(NOTUB)562 // --copyInOutout(NOTUB)
568- LogicalTensor newTensor(function, copyInInput->Datatype(), copyInInput->GetShape());563+ auto newTensorPtr =
569- newTensor.SetMemoryTypeBoth(MemoryType::MEM_UB, true);564+ std::make_shared<LogicalTensor>(function, copyInInput->Datatype(), copyInInput->GetShape());
570- auto newTensorPtr = std::make_shared<LogicalTensor>(std::move(newTensor));565+ newTensorPtr->SetMemoryTypeBoth(MemoryType::MEM_UB, true);
571 AlignmentUtils::ProcessLastDim32BAlignedOnUB(newTensorPtr);566 AlignmentUtils::ProcessLastDim32BAlignedOnUB(newTensorPtr);
572 567 
573 // 要copy到UB的Tensor,在copy之前,进行32B对齐之后判断超UB568 // 要copy到UB的Tensor,在copy之前,进行32B对齐之后判断超UB
574 const size_t UB_SIZE_THRESHOLD = Platform::Instance().GetDie().GetMemoryLimit(MemoryType::MEM_UB);569 const size_t UB_SIZE_THRESHOLD = Platform::Instance().GetDie().GetMemoryLimit(MemoryType::MEM_UB);
575 if (static_cast<size_t>(newTensorPtr->GetDataSize()) > UB_SIZE_THRESHOLD) {570 if (static_cast<size_t>(newTensorPtr->GetDataSize()) > UB_SIZE_THRESHOLD) {
576- APASS_LOG_WARN_F(Elements::Tensor, "The size[%ld] of copyTensor[%d] from input of copyin op[%d] should not exceed %zu after padding. Consider reducing its size.",571+ APASS_LOG_WARN_F(
577- newTensorPtr->GetDataSize(), newTensorPtr->GetMagic(), copyInOp->GetOpMagic(), UB_SIZE_THRESHOLD);572+ Elements::Tensor,
573+ "The size[%ld] of copyTensor[%d] from input of copyin op[%d] should not exceed %zu after "
574+ "padding. Consider reducing its size.",
575+ newTensorPtr->GetDataSize(), newTensorPtr->GetMagic(), copyInOp->GetOpMagic(),
576+ UB_SIZE_THRESHOLD);
578 return;577 return;
579 }578 }
580 579 
581- auto& reshapeCopyInOp = function.AddOperation(Opcode::OP_RESHAPE_COPY_IN, {copyInInput}, {newTensorPtr});580+ auto& reshapeCopyInOp =
581+ function.AddOperation(Opcode::OP_RESHAPE_COPY_IN, {copyInInput}, {newTensorPtr});
582 newOps.push_back(&reshapeCopyInOp);582 newOps.push_back(&reshapeCopyInOp);
583 reshapeCopyInOp.UpdateSubgraphID(op.GetSubgraphID());583 reshapeCopyInOp.UpdateSubgraphID(op.GetSubgraphID());
584 reshapeCopyInOp.SetOpAttribute(std::make_shared<CopyOpAttribute>(584 reshapeCopyInOp.SetOpAttribute(std::make_shared<CopyOpAttribute>(
585- OpImmediate::Specified(std::vector<SymbolicScalar>(copyInInput->GetShape().size(), 0)),585+ OpImmediate::Specified(std::vector<SymbolicScalar>(copyInInput->GetShape().size(), 0)),
586- MemoryType::MEM_UB, OpImmediate::Specified(copyInInput->GetShape()),586+ MemoryType::MEM_UB, OpImmediate::Specified(copyInInput->GetShape()),
587- OpImmediate::Specified(copyInInput->tensor->GetDynRawShape()), OpImmediate::Specified(copyInInput->GetDynValidShape())));587+ OpImmediate::Specified(copyInInput->tensor->GetDynRawShape()),
588+ OpImmediate::Specified(copyInInput->GetDynValidShape())));
588 589 
589- LogicalTensor newTensor2(function, copyInInput->Datatype(), copyInInput->GetShape());590+ auto newTensor2Ptr =
590- newTensor2.SetMemoryTypeBoth(MemoryType::MEM_DEVICE_DDR, true);591+ std::make_shared<LogicalTensor>(function, copyInInput->Datatype(), copyInInput->GetShape());
591- auto newTensor2Ptr = std::make_shared<LogicalTensor>(std::move(newTensor2));592+ newTensor2Ptr->SetMemoryTypeBoth(MemoryType::MEM_DEVICE_DDR, true);
592 auto& newCopyOutOp = function.AddOperation(Opcode::OP_COPY_OUT, {newTensorPtr}, {newTensor2Ptr});593 auto& newCopyOutOp = function.AddOperation(Opcode::OP_COPY_OUT, {newTensorPtr}, {newTensor2Ptr});
593 newOps.push_back(&newCopyOutOp);594 newOps.push_back(&newCopyOutOp);
594 newCopyOutOp.UpdateSubgraphID(op.GetSubgraphID());595 newCopyOutOp.UpdateSubgraphID(op.GetSubgraphID());
595- newCopyOutOp.SetOpAttribute(std::make_shared<CopyOpAttribute>(MemoryType::MEM_UB,596+ newCopyOutOp.SetOpAttribute(std::make_shared<CopyOpAttribute>(
596- OpImmediate::Specified(std::vector<SymbolicScalar>(copyInInput->GetShape().size(), 0)),597+ MemoryType::MEM_UB,
597- OpImmediate::Specified(copyInInput->GetShape()), OpImmediate::Specified(copyInInput->tensor->GetDynRawShape()),598+ OpImmediate::Specified(std::vector<SymbolicScalar>(copyInInput->GetShape().size(), 0)),
598- OpImmediate::Specified(copyInInput->GetDynValidShape())));599+ OpImmediate::Specified(copyInInput->GetShape()),
600+ OpImmediate::Specified(copyInInput->tensor->GetDynRawShape()),
601+ OpImmediate::Specified(copyInInput->GetDynValidShape())));
599 602 
600 copyInInput->RemoveConsumer(copyInOp);603 copyInInput->RemoveConsumer(copyInOp);
601 copyInOp->ReplaceInput(newTensor2Ptr, copyInInput);604 copyInOp->ReplaceInput(newTensor2Ptr, copyInInput);
@@ -695,7 +695,9 @@ LogicalTensorPtr ReplaceTensor::FindReplaceSource(
695 return visited.at(&op);695 return visited.at(&op);
696 }696 }
697 auto inplaceIdx = op.GetIntAttribute(OpAttributeKey::inplaceIdx);697 auto inplaceIdx = op.GetIntAttribute(OpAttributeKey::inplaceIdx);
698- ASSERT(OperationErr::OP_INVALID_OPERAND_COUNT, inplaceIdx >= 0 && inplaceIdx < static_cast<int>(op.GetIOperands().size()));698+ ASSERT(
699+ OperationErr::OP_INVALID_OPERAND_COUNT,
700+ inplaceIdx >= 0 && inplaceIdx < static_cast<int>(op.GetIOperands().size()));
699 auto inplaceIOperand = op.GetInputOperand(inplaceIdx);701 auto inplaceIOperand = op.GetInputOperand(inplaceIdx);
700 LogicalTensorPtr res = nullptr;702 LogicalTensorPtr res = nullptr;
701 for (auto producer : inplaceIOperand->GetProducers()) {703 for (auto producer : inplaceIOperand->GetProducers()) {
@@ -756,7 +758,7 @@ Status ReplaceTensor::RefactorViewConnectForReplace(Function& function)
756 auto& nop = function.AddRawOperation(Opcode::OP_NOP, {iOperand, oOperand}, {nopOutput});758 auto& nop = function.AddRawOperation(Opcode::OP_NOP, {iOperand, oOperand}, {nopOutput});
757 nop.SetAttribute(OpAttributeKey::inplaceIdx, 0); // 期望上设成任何一个都可以,因为来源一致759 nop.SetAttribute(OpAttributeKey::inplaceIdx, 0); // 期望上设成任何一个都可以,因为来源一致
758 nop.UpdateSubgraphID(op->GetSubgraphID());760 nop.UpdateSubgraphID(op->GetSubgraphID());
759- auto consumers = oOperand->GetConsumers(); // deep copy761+ auto consumers = oOperand->GetConsumers(); // deep copy
760 for (auto consumer : consumers) {762 for (auto consumer : consumers) {
761 if (consumer->GetOpcode() == Opcode::OP_NOP || !consumer->HasAttribute(OpAttributeKey::inplaceIdx)) {763 if (consumer->GetOpcode() == Opcode::OP_NOP || !consumer->HasAttribute(OpAttributeKey::inplaceIdx)) {
762 continue;764 continue;
@@ -879,9 +881,9 @@ Status ReplaceTensor::InsertCopyUBOp(Function& function, Operation* needInsertCo
879 auto copyDynShape = input->GetDynValidShape();881 auto copyDynShape = input->GetDynValidShape();
880 Offset offset(copyShape.size(), 0);882 Offset offset(copyShape.size(), 0);
881 883 
882- LogicalTensor copyOutOutput(function, input->Datatype(), copyShape);884+ auto copyOutOutputPtr = std::make_shared<LogicalTensor>(function, input->Datatype(), copyShape);
883- copyOutOutput.SetMemoryTypeBoth(MemoryType::MEM_DEVICE_DDR, true);885+ copyOutOutputPtr->SetMemoryTypeBoth(MemoryType::MEM_DEVICE_DDR, true);
884- auto copyOutOutputPtr = std::make_shared<LogicalTensor>(std::move(copyOutOutput));886+ 
885 auto& copyOutOp = function.AddOperation(Opcode::OP_COPY_OUT, {input}, {copyOutOutputPtr});887 auto& copyOutOp = function.AddOperation(Opcode::OP_COPY_OUT, {input}, {copyOutOutputPtr});
886 888 
887 copyOutOp.SetOpAttribute(std::make_shared<CopyOpAttribute>(889 copyOutOp.SetOpAttribute(std::make_shared<CopyOpAttribute>(
@@ -889,9 +891,8 @@ Status ReplaceTensor::InsertCopyUBOp(Function& function, Operation* needInsertCo
889 OpImmediate::Specified(copyRawShape), OpImmediate::Specified(copyDynShape)));891 OpImmediate::Specified(copyRawShape), OpImmediate::Specified(copyDynShape)));
890 copyOutOp.UpdateSubgraphID(needInsertCopyAssOp->GetSubgraphID());892 copyOutOp.UpdateSubgraphID(needInsertCopyAssOp->GetSubgraphID());
891 893 
892- LogicalTensor copyInOutput(function, input->Datatype(), copyShape);894+ auto copyInOutputPtr = std::make_shared<LogicalTensor>(function, input->Datatype(), copyShape);
893- copyInOutput.SetMemoryTypeBoth(MemoryType::MEM_UB, true);895+ copyInOutputPtr->SetMemoryTypeBoth(MemoryType::MEM_UB, true);
894- auto copyInOutputPtr = std::make_shared<LogicalTensor>(std::move(copyInOutput));
895 auto& copyInOp = function.AddOperation(Opcode::OP_COPY_IN, {copyOutOutputPtr}, {copyInOutputPtr});896 auto& copyInOp = function.AddOperation(Opcode::OP_COPY_IN, {copyOutOutputPtr}, {copyInOutputPtr});
896 copyInOp.SetOpAttribute(std::make_shared<CopyOpAttribute>(897 copyInOp.SetOpAttribute(std::make_shared<CopyOpAttribute>(
897 OpImmediate::Specified(offset), input->GetMemoryTypeOriginal(), OpImmediate::Specified(copyShape),898 OpImmediate::Specified(offset), input->GetMemoryTypeOriginal(), OpImmediate::Specified(copyShape),
@@ -912,23 +913,24 @@ Status ReplaceTensor::InsertCopyDDROp(Function& function, Operation* needInsertC
912 auto copyDynShape = input->GetDynValidShape();913 auto copyDynShape = input->GetDynValidShape();
913 Offset offset(copyShape.size(), 0);914 Offset offset(copyShape.size(), 0);
914 Offset inOffset = input->GetOffset();915 Offset inOffset = input->GetOffset();
915- auto &inOp = *(input)->GetProducers().begin();916+ auto& inOp = *(input)->GetProducers().begin();
916 if (needInsertCopyAssOp->GetOpcode() == Opcode::OP_RESHAPE && inOp->GetOpcode() == Opcode::OP_VIEW) {917 if (needInsertCopyAssOp->GetOpcode() == Opcode::OP_RESHAPE && inOp->GetOpcode() == Opcode::OP_VIEW) {
917 auto viewOpAttr = std::dynamic_pointer_cast<ViewOpAttribute>(inOp->GetOpAttribute());918 auto viewOpAttr = std::dynamic_pointer_cast<ViewOpAttribute>(inOp->GetOpAttribute());
918 inOffset = viewOpAttr->GetFrom();919 inOffset = viewOpAttr->GetFrom();
919 }920 }
920- LogicalTensor copyInOutput(function, input->Datatype(), copyShape);921+ 
921- copyInOutput.SetMemoryTypeBoth(MemoryType::MEM_UB, true);922+ auto copyInOutputPtr = std::make_shared<LogicalTensor>(function, input->Datatype(), copyShape);
923+ copyInOutputPtr->SetMemoryTypeBoth(MemoryType::MEM_UB, true);
922 const int UB_SIZE_THRESHOLD = static_cast<int>(Platform::Instance().GetDie().GetMemoryLimit(MemoryType::MEM_UB));924 const int UB_SIZE_THRESHOLD = static_cast<int>(Platform::Instance().GetDie().GetMemoryLimit(MemoryType::MEM_UB));
923- auto memType = copyInOutput.GetMemoryTypeOriginal();925+ auto memType = copyInOutputPtr->GetMemoryTypeOriginal();
924- if ((memType == MemoryType::MEM_UB) && (copyInOutput.GetDataSize() > UB_SIZE_THRESHOLD)) {926+ if ((memType == MemoryType::MEM_UB) && (copyInOutputPtr->GetDataSize() > UB_SIZE_THRESHOLD)) {
925- APASS_LOG_ERROR_F(Elements::Tensor, 927+ APASS_LOG_ERROR_F(
926- "Tensor [%d] can not copy to UB, tensor size [%ld] exceeds the UB size [%d] limit.", input->magic, 928+ Elements::Tensor, "Tensor [%d] can not copy to UB, tensor size [%ld] exceeds the UB size [%d] limit.",
927- input->GetDataSize(), UB_SIZE_THRESHOLD);929+ input->magic, input->GetDataSize(), UB_SIZE_THRESHOLD);
928 return FAILED;930 return FAILED;
929 }931 }
930- auto copyInOutputPtr = std::make_shared<LogicalTensor>(std::move(copyInOutput));932+ 
931- //为copy到Ub的Tensor进行32B对齐933+ // 为copy到Ub的Tensor进行32B对齐
932 AlignmentUtils::ProcessLastDim32BAlignedOnUB(copyInOutputPtr);934 AlignmentUtils::ProcessLastDim32BAlignedOnUB(copyInOutputPtr);
933 auto& copyInOp = function.AddOperation(Opcode::OP_COPY_IN, {input}, {copyInOutputPtr});935 auto& copyInOp = function.AddOperation(Opcode::OP_COPY_IN, {input}, {copyInOutputPtr});
934 copyInOp.SetOpAttribute(std::make_shared<CopyOpAttribute>(936 copyInOp.SetOpAttribute(std::make_shared<CopyOpAttribute>(
@@ -936,9 +938,8 @@ Status ReplaceTensor::InsertCopyDDROp(Function& function, Operation* needInsertC
936 OpImmediate::Specified(copyRawShape), OpImmediate::Specified(copyDynShape)));938 OpImmediate::Specified(copyRawShape), OpImmediate::Specified(copyDynShape)));
937 copyInOp.UpdateSubgraphID(needInsertCopyAssOp->GetSubgraphID());939 copyInOp.UpdateSubgraphID(needInsertCopyAssOp->GetSubgraphID());
938 940 
939- LogicalTensor copyOutOutput(function, input->Datatype(), copyShape);941+ auto copyOutOutputPtr = std::make_shared<LogicalTensor>(function, input->Datatype(), copyShape);
940- copyOutOutput.SetMemoryTypeBoth(MemoryType::MEM_DEVICE_DDR, true);942+ copyOutOutputPtr->SetMemoryTypeBoth(MemoryType::MEM_DEVICE_DDR, true);
941- auto copyOutOutputPtr = std::make_shared<LogicalTensor>(std::move(copyOutOutput));
942 auto& copyOutOp = function.AddOperation(Opcode::OP_COPY_OUT, {copyInOutputPtr}, {copyOutOutputPtr});943 auto& copyOutOp = function.AddOperation(Opcode::OP_COPY_OUT, {copyInOutputPtr}, {copyOutOutputPtr});
943 copyOutOp.SetOpAttribute(std::make_shared<CopyOpAttribute>(944 copyOutOp.SetOpAttribute(std::make_shared<CopyOpAttribute>(
944 MemoryType::MEM_UB, OpImmediate::Specified(offset), OpImmediate::Specified(copyShape),945 MemoryType::MEM_UB, OpImmediate::Specified(offset), OpImmediate::Specified(copyShape),
@@ -958,7 +959,7 @@ Status ReplaceTensor::FindNeedToCopyAssemble(
958 visitedAssOps.insert(op.GetOpMagic());959 visitedAssOps.insert(op.GetOpMagic());
959 auto assembleIn = op.GetIOperands()[0];960 auto assembleIn = op.GetIOperands()[0];
960 auto producers = assembleIn->GetProducers();961 auto producers = assembleIn->GetProducers();
961- auto &inOp = *(assembleIn)->GetProducers().begin();962+ auto& inOp = *(assembleIn)->GetProducers().begin();
962 if ((!producers.empty()) && (*producers.begin())->GetOpcode() == Opcode::OP_TRANSPOSE_MOVEOUT) {963 if ((!producers.empty()) && (*producers.begin())->GetOpcode() == Opcode::OP_TRANSPOSE_MOVEOUT) {
963 return FAILED;964 return FAILED;
964 }965 }
@@ -987,12 +988,13 @@ Status ReplaceTensor::FindNeedToCopyAssemble(
987 return SUCCESS;988 return SUCCESS;
988}989}
989 990 
990-bool ReplaceTensor::isBoundTensor(LogicalTensorPtr &curTensor) {991+bool ReplaceTensor::isBoundTensor(LogicalTensorPtr& curTensor)
992+{
991 std::set<int> boundTensorIDs;993 std::set<int> boundTensorIDs;
992- for (auto &inOp : curTensor->GetProducers()) {994+ for (auto& inOp : curTensor->GetProducers()) {
993 boundTensorIDs.insert(inOp->GetSubgraphID());995 boundTensorIDs.insert(inOp->GetSubgraphID());
994 }996 }
995- for (auto &outOp : curTensor->GetConsumers()) {997+ for (auto& outOp : curTensor->GetConsumers()) {
996 boundTensorIDs.insert(outOp->GetSubgraphID());998 boundTensorIDs.insert(outOp->GetSubgraphID());
997 }999 }
998 if (boundTensorIDs.size() > 1) {1000 if (boundTensorIDs.size() > 1) {
@@ -1002,12 +1004,11 @@ bool ReplaceTensor::isBoundTensor(LogicalTensorPtr &curTensor) {
1002}1004}
1003 1005 
1004Status ReplaceTensor::FindNeedToCopyReshape(1006Status ReplaceTensor::FindNeedToCopyReshape(
1005- std::unordered_set<Operation*>& needInsertCopyAssOps, std::unordered_set<int>& visitedReshapeOps,1007+ std::unordered_set<Operation*>& needInsertCopyAssOps, std::unordered_set<int>& visitedReshapeOps, Operation& op,
1006- Operation& op, Function &function)1008+ Function& function)
1007{1009{
1008 visitedReshapeOps.insert(op.GetOpMagic());1010 visitedReshapeOps.insert(op.GetOpMagic());
1009- if (op.GetIOperands()[0]->tensor->GetRawShapeSize() > 0 &&1011+ if (op.GetIOperands()[0]->tensor->GetRawShapeSize() > 0 && op.GetOOperands()[0]->tensor->GetRawShapeSize() > 0 &&
1010- op.GetOOperands()[0]->tensor->GetRawShapeSize() > 0 &&
1011 op.GetIOperands()[0]->tensor->GetRawShapeSize() != op.GetOOperands()[0]->tensor->GetRawShapeSize()) {1012 op.GetIOperands()[0]->tensor->GetRawShapeSize() != op.GetOOperands()[0]->tensor->GetRawShapeSize()) {
1012 needInsertCopyAssOps.insert(&op);1013 needInsertCopyAssOps.insert(&op);
1013 return SUCCESS;1014 return SUCCESS;
@@ -1015,15 +1016,15 @@ Status ReplaceTensor::FindNeedToCopyReshape(
1015 auto producerOps = op.ProducerOps();1016 auto producerOps = op.ProducerOps();
1016 auto consumerOps = op.ConsumerOps();1017 auto consumerOps = op.ConsumerOps();
1017 for (auto producesOp : producerOps) {1018 for (auto producesOp : producerOps) {
1018- if (producesOp->GetOpcode() == Opcode::OP_VIEW &&1019+ if (producesOp->GetOpcode() == Opcode::OP_VIEW && isBoundTensor(op.GetOOperands().front()) &&
1019- isBoundTensor(op.GetOOperands().front()) &&
1020 !isBoundTensor(producesOp->GetIOperands().front()) &&1020 !isBoundTensor(producesOp->GetIOperands().front()) &&
1021 !function.IsFromInCast(producesOp->GetIOperands().front())) {1021 !function.IsFromInCast(producesOp->GetIOperands().front())) {
1022 needInsertCopyAssOps.insert(&op);1022 needInsertCopyAssOps.insert(&op);
1023 }1023 }
1024 }1024 }
1025 for (auto consumerOp : consumerOps) {1025 for (auto consumerOp : consumerOps) {
1026- if (consumerOp->GetOpcode() == Opcode::OP_ASSEMBLE && consumerOp->GetIOperands()[0]->GetMemoryTypeOriginal() == MemoryType::MEM_UB) {1026+ if (consumerOp->GetOpcode() == Opcode::OP_ASSEMBLE &&
1027+ consumerOp->GetIOperands()[0]->GetMemoryTypeOriginal() == MemoryType::MEM_UB) {
1027 needInsertCopyAssOps.insert(consumerOp);1028 needInsertCopyAssOps.insert(consumerOp);
1028 }1029 }
1029 }1030 }
@@ -98,7 +98,8 @@ Status DuplicateOp::ProcessGatherIn(Function& function, Operation& operation, st
98 return FAILED;98 return FAILED;
99 }99 }
100 consumer->ReplaceInput(dst, oOperand);100 consumer->ReplaceInput(dst, oOperand);
101- auto& newOp = function.AddRawOperation(Opcode::OP_GATHER_IN_L1, operation.GetIOperands(), {dst}, true, operation.GetLocation());101+ auto& newOp = function.AddRawOperation(
102+ Opcode::OP_GATHER_IN_L1, operation.GetIOperands(), {dst}, true, operation.GetSpan());
102 newOp.SetScopeInfo(operation.GetScopeInfo());103 newOp.SetScopeInfo(operation.GetScopeInfo());
103 newOp.SetAttribute(OpAttributeKey::startOffset, operation.GetIntAttribute(OpAttributeKey::startOffset));104 newOp.SetAttribute(OpAttributeKey::startOffset, operation.GetIntAttribute(OpAttributeKey::startOffset));
104 newOps.push_back(&newOp);105 newOps.push_back(&newOp);
@@ -118,7 +119,8 @@ Status DuplicateOp::ProcessView(Function& function, Operation& operation, std::v
118 for (const auto& oOperand : operation.oOperand) {119 for (const auto& oOperand : operation.oOperand) {
119 if (oOperand == nullptr) {120 if (oOperand == nullptr) {
120 APASS_LOG_ERROR_F(121 APASS_LOG_ERROR_F(
121- Elements::Operation, "Null output operand detected while iterating over the output operands of the operation [%d].%s",122+ Elements::Operation,
123+ "Null output operand detected while iterating over the output operands of the operation [%d].%s",
122 operation.opmagic, GetFormatBacktrace(operation).c_str());124 operation.opmagic, GetFormatBacktrace(operation).c_str());
123 return FAILED;125 return FAILED;
124 }126 }
@@ -129,7 +131,8 @@ Status DuplicateOp::ProcessView(Function& function, Operation& operation, std::v
129 for (auto& consumer : consumers) {131 for (auto& consumer : consumers) {
130 if (consumer == nullptr) {132 if (consumer == nullptr) {
131 APASS_LOG_ERROR_F(133 APASS_LOG_ERROR_F(
132- Elements::Tensor, "Null consumer detected while iterating over the consumers of the output operand [%d].",134+ Elements::Tensor,
135+ "Null consumer detected while iterating over the consumers of the output operand [%d].",
133 oOperand->magic);136 oOperand->magic);
134 return FAILED;137 return FAILED;
135 }138 }
@@ -142,7 +145,7 @@ Status DuplicateOp::ProcessView(Function& function, Operation& operation, std::v
142 return FAILED;145 return FAILED;
143 }146 }
144 consumer->ReplaceInput(dst, oOperand);147 consumer->ReplaceInput(dst, oOperand);
145- auto& newOp = function.AddRawOperation(Opcode::OP_VIEW, {iOperand}, {dst}, true, operation.GetLocation());148+ auto& newOp = function.AddRawOperation(Opcode::OP_VIEW, {iOperand}, {dst}, true, operation.GetSpan());
146 newOp.SetScopeInfo(operation.GetScopeInfo());149 newOp.SetScopeInfo(operation.GetScopeInfo());
147 auto oriViewAttr = dynamic_cast<ViewOpAttribute*>(operation.GetOpAttribute().get());150 auto oriViewAttr = dynamic_cast<ViewOpAttribute*>(operation.GetOpAttribute().get());
148 if (oriViewAttr != nullptr) {151 if (oriViewAttr != nullptr) {
@@ -22,12 +22,12 @@ namespace tile_fwk {
22void InsertOpForViewAssemble::InsertViewAssemble(Function& function, Operation* viewOp, Operation* assembleOp)22void InsertOpForViewAssemble::InsertViewAssemble(Function& function, Operation* viewOp, Operation* assembleOp)
23{23{
24 auto& moveOutTensorPtr = viewOp->GetOOperands()[0];24 auto& moveOutTensorPtr = viewOp->GetOOperands()[0];
25- LogicalTensor ddrTensor(function, moveOutTensorPtr->Datatype(), moveOutTensorPtr->GetShape());25+ LogicalTensorPtr ddrTensorPtr =
26- ddrTensor.SetMemoryTypeBoth(MemoryType::MEM_DEVICE_DDR, true);26+ std::make_shared<LogicalTensor>(function, moveOutTensorPtr->Datatype(), moveOutTensorPtr->GetShape());
27- LogicalTensor moveInTensor(function, moveOutTensorPtr->Datatype(), moveOutTensorPtr->GetShape());27+ ddrTensorPtr->SetMemoryTypeBoth(MemoryType::MEM_DEVICE_DDR, true);
28- moveInTensor.SetMemoryTypeBoth(moveOutTensorPtr->GetMemoryTypeOriginal(), true);28+ LogicalTensorPtr moveInTensorPtr =
29- LogicalTensorPtr ddrTensorPtr = std::make_shared<LogicalTensor>(std::move(ddrTensor));29+ std::make_shared<LogicalTensor>(function, moveOutTensorPtr->Datatype(), moveOutTensorPtr->GetShape());
30- LogicalTensorPtr moveInTensorPtr = std::make_shared<LogicalTensor>(std::move(moveInTensor));30+ moveInTensorPtr->SetMemoryTypeBoth(moveOutTensorPtr->GetMemoryTypeOriginal(), true);
31 std::vector<int64_t> offset(moveOutTensorPtr->GetShape().size(), 0);31 std::vector<int64_t> offset(moveOutTensorPtr->GetShape().size(), 0);
32 std::vector<SymbolicScalar> dynOffset(moveOutTensorPtr->GetShape().size(), 0);32 std::vector<SymbolicScalar> dynOffset(moveOutTensorPtr->GetShape().size(), 0);
33 Operation& assemble = function.AddRawOperation(Opcode::OP_ASSEMBLE, {moveOutTensorPtr}, {ddrTensorPtr});33 Operation& assemble = function.AddRawOperation(Opcode::OP_ASSEMBLE, {moveOutTensorPtr}, {ddrTensorPtr});
@@ -25,30 +25,6 @@ namespace ir {
25 25 
26class IRCoreExtTest : public testing::Test {};26class IRCoreExtTest : public testing::Test {};
27 27 
28-// ============================================================================
29-// Span Constructor Tests
30-// ============================================================================
31- 
32-TEST_F(IRCoreExtTest, TestSpanConstructor)
33-{
34- Span sp("test.py", 1, 2, 3, 4);
35- ASSERT_EQ(sp.filename_, "test.py");
36- ASSERT_EQ(sp.beginLine_, 1);
37- ASSERT_EQ(sp.beginColumn_, 2);
38- ASSERT_EQ(sp.endLine_, 3);
39- ASSERT_EQ(sp.endColumn_, 4);
40-}
41- 
42-TEST_F(IRCoreExtTest, TestSpanUnknown)
43-{
44- Span sp = Span::Unknown();
45- ASSERT_EQ(sp.filename_, "");
46- ASSERT_EQ(sp.beginLine_, -1);
47- ASSERT_EQ(sp.beginColumn_, -1);
48- ASSERT_EQ(sp.endLine_, -1);
49- ASSERT_EQ(sp.endColumn_, -1);
50-}
51- 
52// ============================================================================28// ============================================================================
53// Span::to_string Tests29// Span::to_string Tests
54// ============================================================================30// ============================================================================
@@ -84,6 +84,7 @@ TEST(CoreDTypeTest, TestToString)
84 ASSERT_EQ(DataType::FP8.ToString(), "fp8e4m3fn");84 ASSERT_EQ(DataType::FP8.ToString(), "fp8e4m3fn");
85 ASSERT_EQ(DataType::FP16.ToString(), "fp16");85 ASSERT_EQ(DataType::FP16.ToString(), "fp16");
86 ASSERT_EQ(DataType::FP32.ToString(), "fp32");86 ASSERT_EQ(DataType::FP32.ToString(), "fp32");
87+ ASSERT_EQ(DataType::FP64.ToString(), "fp64");
87 ASSERT_EQ(DataType::BF16.ToString(), "bfloat16");88 ASSERT_EQ(DataType::BF16.ToString(), "bfloat16");
88 ASSERT_EQ(DataType::HF4.ToString(), "hf4");89 ASSERT_EQ(DataType::HF4.ToString(), "hf4");
89 ASSERT_EQ(DataType::HF8.ToString(), "hf8");90 ASSERT_EQ(DataType::HF8.ToString(), "hf8");
@@ -10,7 +10,7 @@
10 10 
11/*!11/*!
12 * \file test_ir.cpp12 * \file test_ir.cpp
13- * \brief Unit tests ported from Python test_ir.py — string representations, CHECK macros, and structural comparison13+ * \brief Unit tests ported from Python test_ir.py — string representations, IRCHECK macros, and structural comparison
14 */14 */
15 15 
16#include "gtest/gtest.h"16#include "gtest/gtest.h"
@@ -41,14 +41,14 @@ namespace ir {
41static TypePtr Scalar(DataType dt) { return std::make_shared<ScalarType>(dt); }41static TypePtr Scalar(DataType dt) { return std::make_shared<ScalarType>(dt); }
42 42 
43// ============================================================================43// ============================================================================
44-// CHECK / INTERNAL_CHECK Tests44+// IRCHECK / INTERNAL_CHECK Tests
45// ============================================================================45// ============================================================================
46 46 
47class IRCheckTest : public testing::Test {};47class IRCheckTest : public testing::Test {};
48 48 
49-TEST_F(IRCheckTest, TestCheckPass) { CHECK(true) << "should not throw"; }49+TEST_F(IRCheckTest, TestCheckPass) { IRCHECK(true) << "should not throw"; }
50 50 
51-TEST_F(IRCheckTest, TestCheckFail) { ASSERT_THROW(CHECK(false) << "test check message", ValueError); }51+TEST_F(IRCheckTest, TestCheckFail) { ASSERT_THROW(IRCHECK(false) << "test check message", ValueError); }
52 52 
53TEST_F(IRCheckTest, TestInternalCheckPass) { INTERNAL_CHECK(true) << "should not throw"; }53TEST_F(IRCheckTest, TestInternalCheckPass) { INTERNAL_CHECK(true) << "should not throw"; }
54 54 
@@ -143,6 +143,22 @@ TEST_F(IRMutatorTest, TestIdentityAllStmts)
143 143 
144 auto cont = std::make_shared<ContinueStmt>(Sp());144 auto cont = std::make_shared<ContinueStmt>(Sp());
145 EXPECT_EQ(m.VisitStmt(cont).get(), cont.get());145 EXPECT_EQ(m.VisitStmt(cont).get(), cont.get());
146+ 
147+ // ScalarOpStmt
148+ auto scalarRes = std::make_shared<Var>("res", Scalar(DataType::INT32), Sp());
149+ auto scalarTok = std::make_shared<Var>("tok", Scalar(DataType::INT32), Sp());
150+ auto scalarArg = std::make_shared<ConstInt>(1, DataType::INT32, Sp());
151+ auto scalarOp = std::make_shared<ScalarOpStmt>(scalarRes, scalarTok, "add", std::vector<ExprPtr>{scalarArg}, Sp());
152+ EXPECT_EQ(m.VisitStmt(scalarOp).get(), scalarOp.get());
153+ 
154+ // TensorOpStmt
155+ auto tensorRes = std::make_shared<Var>("res", Scalar(DataType::INT32), Sp());
156+ auto tensorTok = std::make_shared<Var>("tok", Scalar(DataType::INT32), Sp());
157+ auto tensorArg = std::make_shared<ConstInt>(1, DataType::INT32, Sp());
158+ auto tensorOp = std::make_shared<TensorOpStmt>(
159+ std::vector<VarPtr>{tensorRes}, tensorTok, "matmul", std::vector<ExprPtr>{tensorArg}, std::vector<ExprPtr>{},
160+ std::vector<std::pair<std::string, std::any>>{}, Sp());
161+ EXPECT_EQ(m.VisitStmt(tensorOp).get(), tensorOp.get());
146}162}
147 163 
148TEST_F(IRMutatorTest, TestIdentityFunctionAndProgram)164TEST_F(IRMutatorTest, TestIdentityFunctionAndProgram)
@@ -247,5 +263,37 @@ TEST_F(IRMutatorTest, TestRewriteAllUnaryExpr)
247#undef DEFINE_UNARY_EXPR263#undef DEFINE_UNARY_EXPR
248}264}
249 265 
266+TEST_F(IRMutatorTest, TestRewriteScalarOpStmt)
267+{
268+ ConstRewriter m;
269+ auto res = std::make_shared<Var>("res", Scalar(DataType::INT32), Sp());
270+ auto tok = std::make_shared<Var>("tok", Scalar(DataType::INT32), Sp());
271+ auto val42 = std::make_shared<ConstInt>(42, DataType::INT32, Sp());
272+ auto stmt = std::make_shared<ScalarOpStmt>(res, tok, "add", std::vector<ExprPtr>{val42}, Sp());
273+ auto result = m.VisitStmt(stmt);
274+ EXPECT_NE(result.get(), stmt.get());
275+ auto mutated = std::dynamic_pointer_cast<const ScalarOpStmt>(result);
276+ EXPECT_NE(mutated, nullptr);
277+ auto newArg = std::dynamic_pointer_cast<const ConstInt>(mutated->args_[0]);
278+ EXPECT_EQ(newArg->value_, 99);
279+}
280+ 
281+TEST_F(IRMutatorTest, TestRewriteTensorOpStmt)
282+{
283+ ConstRewriter m;
284+ auto res = std::make_shared<Var>("res", Scalar(DataType::INT32), Sp());
285+ auto tok = std::make_shared<Var>("tok", Scalar(DataType::INT32), Sp());
286+ auto val42 = std::make_shared<ConstInt>(42, DataType::INT32, Sp());
287+ auto stmt = std::make_shared<TensorOpStmt>(
288+ std::vector<VarPtr>{res}, tok, "matmul", std::vector<ExprPtr>{val42}, std::vector<ExprPtr>{},
289+ std::vector<std::pair<std::string, std::any>>{}, Sp());
290+ auto result = m.VisitStmt(stmt);
291+ EXPECT_NE(result.get(), stmt.get());
292+ auto mutated = std::dynamic_pointer_cast<const TensorOpStmt>(result);
293+ EXPECT_NE(mutated, nullptr);
294+ auto newArg = std::dynamic_pointer_cast<const ConstInt>(mutated->args_[0]);
295+ EXPECT_EQ(newArg->value_, 99);
296+}
297+ 
250} // namespace ir298} // namespace ir
251} // namespace pypto299} // namespace pypto
@@ -575,5 +575,57 @@ TEST_F(IRPrinterTest, TestPrintIfWithEmptySeqStmtsBody)
575 std::string::npos);575 std::string::npos);
576}576}
577 577 
578+// ============================================================================
579+// ScalarOpStmt and TensorOpStmt printing
580+// ============================================================================
581+ 
582+TEST_F(IRPrinterTest, TestPrintScalarOpStmt)
583+{
584+ auto res = Var_("res");
585+ auto tok = Var_("tok");
586+ auto arg = std::make_shared<ConstInt>(1, DataType::INT32, Sp());
587+ auto stmt = std::make_shared<ScalarOpStmt>(res, tok, "add", std::vector<ExprPtr>{arg}, Sp());
588+ auto str = Print(stmt);
589+ EXPECT_EQ(str, "res, tok = add(1)");
590+}
591+ 
592+TEST_F(IRPrinterTest, TestPrintTensorOpStmt)
593+{
594+ auto res = Var_("res");
595+ auto tok = Var_("tok");
596+ auto arg = std::make_shared<ConstInt>(1, DataType::INT32, Sp());
597+ auto stmt = std::make_shared<TensorOpStmt>(
598+ std::vector<VarPtr>{res}, tok, "matmul", std::vector<ExprPtr>{arg}, std::vector<ExprPtr>{},
599+ std::vector<std::pair<std::string, std::any>>{}, Sp());
600+ auto str = Print(stmt);
601+ EXPECT_EQ(str, "res, tok = matmul(1)");
602+}
603+ 
604+TEST_F(IRPrinterTest, TestPrintTensorOpStmtMultiResult)
605+{
606+ auto r1 = Var_("r1");
607+ auto r2 = Var_("r2");
608+ auto tok = Var_("tok");
609+ auto arg = std::make_shared<ConstInt>(1, DataType::INT32, Sp());
610+ auto stmt = std::make_shared<TensorOpStmt>(
611+ std::vector<VarPtr>{r1, r2}, tok, "split", std::vector<ExprPtr>{arg}, std::vector<ExprPtr>{},
612+ std::vector<std::pair<std::string, std::any>>{}, Sp());
613+ auto str = Print(stmt);
614+ EXPECT_EQ(str, "[r1, r2], tok = split(1)");
615+}
616+ 
617+TEST_F(IRPrinterTest, TestPrintTensorOpStmtWithTokensAndAttrs)
618+{
619+ auto res = Var_("res");
620+ auto tok = Var_("tok");
621+ auto arg = std::make_shared<ConstInt>(1, DataType::INT32, Sp());
622+ auto t1 = Var_("t1");
623+ auto stmt = std::make_shared<TensorOpStmt>(
624+ std::vector<VarPtr>{res}, tok, "op", std::vector<ExprPtr>{arg}, std::vector<ExprPtr>{t1},
625+ std::vector<std::pair<std::string, std::any>>{{"axis", 0}}, Sp());
626+ auto str = Print(stmt);
627+ EXPECT_EQ(str, "res, tok = op(1, tokens=[t1], attrs=[axis=0])");
628+}
629+ 
578} // namespace ir630} // namespace ir
579} // namespace pypto631} // namespace pypto
@@ -105,36 +105,6 @@ TEST(ProgramTest, ProgramKindAndTypeName)
105 ASSERT_EQ(prog->TypeName(), "Program");105 ASSERT_EQ(prog->TypeName(), "Program");
106}106}
107 107 
108-// ============================================================================
109-// Core / Span Tests (core.cpp)
110-// ============================================================================
111- 
112-TEST(SpanTest, Construction)
113-{
114- Span span("file.py", 10, 5);
115- ASSERT_EQ(span.filename_, "file.py");
116- ASSERT_EQ(span.beginLine_, 10);
117- ASSERT_EQ(span.beginColumn_, 5);
118- ASSERT_EQ(span.endLine_, -1);
119- ASSERT_EQ(span.endColumn_, -1);
120-}
121- 
122-TEST(SpanTest, ConstructionWithEndPos)
123-{
124- Span span("file.py", 10, 5, 20, 15);
125- ASSERT_EQ(span.endLine_, 20);
126- ASSERT_EQ(span.endColumn_, 15);
127-}
128- 
129-TEST(SpanTest, ToString)
130-{
131- Span span("file.py", 10, 5);
132- auto str = span.ToString();
133- ASSERT_NE(str.find("file.py"), std::string::npos);
134- ASSERT_NE(str.find("10"), std::string::npos);
135- ASSERT_NE(str.find("5"), std::string::npos);
136-}
137- 
138// ============================================================================108// ============================================================================
139// Expr Tests (expr.cpp)109// Expr Tests (expr.cpp)
140// ============================================================================110// ============================================================================
@@ -83,8 +83,8 @@ TEST(ScalarExprBasicTest, TestConstIntWithSpan)
83 Span span("test.py", 10, 5);83 Span span("test.py", 10, 5);
84 auto constInt = std::make_shared<ConstInt>(42, DataType::INT32, span);84 auto constInt = std::make_shared<ConstInt>(42, DataType::INT32, span);
85 ASSERT_NE(constInt, nullptr);85 ASSERT_NE(constInt, nullptr);
86- ASSERT_EQ(constInt->span_.filename_, "test.py");86+ ASSERT_EQ(constInt->span_.Filename(), "test.py");
87- ASSERT_EQ(constInt->span_.beginLine_, 10);87+ ASSERT_EQ(constInt->span_.BeginLine(), 10);
88}88}
89 89 
90// ============================================================================90// ============================================================================
@@ -178,8 +178,8 @@ TEST(ScalarExprBasicTest, TestConstBoolWithSpan)
178 Span span("test.py", 20, 10);178 Span span("test.py", 20, 10);
179 auto constBool = std::make_shared<ConstBool>(true, span);179 auto constBool = std::make_shared<ConstBool>(true, span);
180 ASSERT_NE(constBool, nullptr);180 ASSERT_NE(constBool, nullptr);
181- ASSERT_EQ(constBool->span_.filename_, "test.py");181+ ASSERT_EQ(constBool->span_.Filename(), "test.py");
182- ASSERT_EQ(constBool->span_.beginLine_, 20);182+ ASSERT_EQ(constBool->span_.BeginLine(), 20);
183}183}
184 184 
185// ============================================================================185// ============================================================================
@@ -18,7 +18,6 @@
18#include <memory>18#include <memory>
19#include <string>19#include <string>
20 20 
21-#include "ir/core.h"
22#include "ir/scalar_expr.h"21#include "ir/scalar_expr.h"
23 22 
24namespace pypto {23namespace pypto {
@@ -29,11 +28,11 @@ TEST(IRCoreTest, TestSpanBasic)
29 // Test basic Span functionality28 // Test basic Span functionality
30 Span span("test.py", 10, 5, 10, 15);29 Span span("test.py", 10, 5, 10, 15);
31 30 
32- ASSERT_EQ(span.filename_, "test.py");31+ ASSERT_EQ(span.Filename(), "test.py");
33- ASSERT_EQ(span.beginLine_, 10);32+ ASSERT_EQ(span.BeginLine(), 10);
34- ASSERT_EQ(span.beginColumn_, 5);33+ ASSERT_EQ(span.BeginColumn(), 5);
35- ASSERT_EQ(span.endLine_, 10);34+ ASSERT_EQ(span.EndLine(), 10);
36- ASSERT_EQ(span.endColumn_, 15);35+ ASSERT_EQ(span.EndColumn(), 15);
37}36}
38 37 
39TEST(IRCoreTest, TestSpanToString)38TEST(IRCoreTest, TestSpanToString)
@@ -47,36 +46,14 @@ TEST(IRCoreTest, TestSpanToString)
47 ASSERT_TRUE(str.find("test.py") != std::string::npos || str.find("10") != std::string::npos);46 ASSERT_TRUE(str.find("test.py") != std::string::npos || str.find("10") != std::string::npos);
48}47}
49 48 
50-TEST(IRCoreTest, TestSpanMultiline)
51-{
52- // Test Span spanning multiple lines
53- Span span("file.py", 5, 10, 8, 20);
54- 
55- ASSERT_EQ(span.beginLine_, 5);
56- ASSERT_EQ(span.endLine_, 8);
57- ASSERT_EQ(span.beginColumn_, 10);
58- ASSERT_EQ(span.endColumn_, 20);
59-}
60- 
61-TEST(IRCoreTest, TestSpanSingleCharacter)
62-{
63- // Test Span for a single character
64- Span span("file.py", 5, 10, 5, 11);
65- 
66- ASSERT_EQ(span.beginLine_, 5);
67- ASSERT_EQ(span.endLine_, 5);
68- ASSERT_EQ(span.beginColumn_, 10);
69- ASSERT_EQ(span.endColumn_, 11);
70-}
71- 
72TEST(IRCoreTest, TestIRNodeBasic)49TEST(IRCoreTest, TestIRNodeBasic)
73{50{
74 // Test basic IRNode functionality via ConstInt (IRNode is now abstract)51 // Test basic IRNode functionality via ConstInt (IRNode is now abstract)
75 Span span("test.py", 1, 0, 1, 10);52 Span span("test.py", 1, 0, 1, 10);
76 auto node = std::make_shared<ConstInt>(42, DataType::INT32, span);53 auto node = std::make_shared<ConstInt>(42, DataType::INT32, span);
77 54 
78- ASSERT_EQ(node->span_.filename_, span.filename_);55+ ASSERT_EQ(node->span_.Filename(), span.Filename());
79- ASSERT_EQ(node->span_.beginLine_, span.beginLine_);56+ ASSERT_EQ(node->span_.BeginLine(), span.BeginLine());
80}57}
81 58 
82TEST(IRCoreTest, TestIRNodeTypeName)59TEST(IRCoreTest, TestIRNodeTypeName)
@@ -100,22 +77,9 @@ TEST(IRCoreTest, TestMultipleIRNodes)
100 auto node2 = std::make_shared<ConstInt>(2, DataType::INT32, span2);77 auto node2 = std::make_shared<ConstInt>(2, DataType::INT32, span2);
101 auto node3 = std::make_shared<ConstInt>(3, DataType::INT32, span3);78 auto node3 = std::make_shared<ConstInt>(3, DataType::INT32, span3);
102 79 
103- ASSERT_EQ(node1->span_.filename_, "file1.py");80+ ASSERT_EQ(node1->span_.Filename(), "file1.py");
104- ASSERT_EQ(node2->span_.filename_, "file2.py");81+ ASSERT_EQ(node2->span_.Filename(), "file2.py");
105- ASSERT_EQ(node3->span_.filename_, "file3.py");82+ ASSERT_EQ(node3->span_.Filename(), "file3.py");
106-}
107- 
108-TEST(IRCoreTest, TestSpanCopy)
109-{
110- // Test copying Span objects
111- Span original("test.py", 10, 5, 10, 15);
112- Span copy = original;
113- 
114- ASSERT_EQ(copy.filename_, original.filename_);
115- ASSERT_EQ(copy.beginLine_, original.beginLine_);
116- ASSERT_EQ(copy.beginColumn_, original.beginColumn_);
117- ASSERT_EQ(copy.endLine_, original.endLine_);
118- ASSERT_EQ(copy.endColumn_, original.endColumn_);
119}83}
120 84 
121TEST(IRCoreTest, TestSpanComparison)85TEST(IRCoreTest, TestSpanComparison)
@@ -126,11 +90,8 @@ TEST(IRCoreTest, TestSpanComparison)
126 Span span3("test.py", 20, 5, 20, 15);90 Span span3("test.py", 20, 5, 20, 15);
127 91 
128 // Same location92 // Same location
129- ASSERT_EQ(span1.filename_, span2.filename_);93+ ASSERT_EQ(span1.BeginLine(), span2.BeginLine());
130- ASSERT_EQ(span1.beginLine_, span2.beginLine_);94+ ASSERT_NE(span1.BeginLine(), span3.BeginLine());
131- 
132- // Different location
133- ASSERT_NE(span1.beginLine_, span3.beginLine_);
134}95}
135 96 
136TEST(IRCoreTest, TestIRNodeSharedPtr)97TEST(IRCoreTest, TestIRNodeSharedPtr)
@@ -141,27 +102,7 @@ TEST(IRCoreTest, TestIRNodeSharedPtr)
141 102 
142 ASSERT_NE(node, nullptr);103 ASSERT_NE(node, nullptr);
143 ASSERT_EQ(node->TypeName(), "ConstInt");104 ASSERT_EQ(node->TypeName(), "ConstInt");
144- ASSERT_EQ(node->span_.filename_, "test.py");105+ ASSERT_EQ(node->span_.Filename(), "test.py");
145-}
146- 
147-TEST(IRCoreTest, TestSpanZeroPosition)
148-{
149- // Test Span with zero line and column
150- Span span("test.py", 0, 0, 0, 1);
151- 
152- ASSERT_EQ(span.beginLine_, 0);
153- ASSERT_EQ(span.beginColumn_, 0);
154-}
155- 
156-TEST(IRCoreTest, TestSpanLargePosition)
157-{
158- // Test Span with large line and column numbers
159- Span span("test.py", 10000, 500, 10001, 600);
160- 
161- ASSERT_EQ(span.beginLine_, 10000);
162- ASSERT_EQ(span.beginColumn_, 500);
163- ASSERT_EQ(span.endLine_, 10001);
164- ASSERT_EQ(span.endColumn_, 600);
165}106}
166 107 
167} // namespace ir108} // namespace ir
@@ -50,6 +50,8 @@ public:
50 void VisitExpr_(const MemRefPtr&) override { visited.push_back("MemRef"); }50 void VisitExpr_(const MemRefPtr&) override { visited.push_back("MemRef"); }
51 void VisitStmt_(const BreakStmtPtr&) override { visited.push_back("BreakStmt"); }51 void VisitStmt_(const BreakStmtPtr&) override { visited.push_back("BreakStmt"); }
52 void VisitStmt_(const ContinueStmtPtr&) override { visited.push_back("ContinueStmt"); }52 void VisitStmt_(const ContinueStmtPtr&) override { visited.push_back("ContinueStmt"); }
53+ void VisitStmt_(const TensorOpStmtPtr&) override { visited.push_back("TensorOpStmt"); }
54+ void VisitStmt_(const ScalarOpStmtPtr&) override { visited.push_back("ScalarOpStmt"); }
53};55};
54 56 
55// ============================================================================57// ============================================================================
@@ -263,6 +265,30 @@ TEST_F(IRVisitorTest, TestVisitContinueStmt)
263 ASSERT_EQ(v.visited.back(), "ContinueStmt");265 ASSERT_EQ(v.visited.back(), "ContinueStmt");
264}266}
265 267 
268+TEST_F(IRVisitorTest, TestVisitScalarOpStmt)
269+{
270+ TestVisitor v;
271+ auto result = std::make_shared<Var>("res", Scalar(DataType::INT32), Sp());
272+ auto token = std::make_shared<Var>("tok", Scalar(DataType::INT32), Sp());
273+ auto arg = std::make_shared<ConstInt>(1, DataType::INT32, Sp());
274+ auto stmt = std::make_shared<ScalarOpStmt>(result, token, "add", std::vector<ExprPtr>{arg}, Sp());
275+ v.VisitStmt(stmt);
276+ ASSERT_EQ(v.visited.back(), "ScalarOpStmt");
277+}
278+ 
279+TEST_F(IRVisitorTest, TestVisitTensorOpStmt)
280+{
281+ TestVisitor v;
282+ auto result = std::make_shared<Var>("res", Scalar(DataType::INT32), Sp());
283+ auto token = std::make_shared<Var>("tok", Scalar(DataType::INT32), Sp());
284+ auto arg = std::make_shared<ConstInt>(1, DataType::INT32, Sp());
285+ auto stmt = std::make_shared<TensorOpStmt>(
286+ std::vector<VarPtr>{result}, token, "matmul", std::vector<ExprPtr>{arg}, std::vector<ExprPtr>{},
287+ std::vector<std::pair<std::string, std::any>>{}, Sp());
288+ v.VisitStmt(stmt);
289+ ASSERT_EQ(v.visited.back(), "TensorOpStmt");
290+}
291+ 
266// ============================================================================292// ============================================================================
267// Program and Function visitors293// Program and Function visitors
268// ============================================================================294// ============================================================================
@@ -92,9 +92,8 @@ TEST_F(TestDuplicateOpPass, DuplicateViewUTest1)
92 92 
93 auto& viewOp = currFunctionPtr->AddOperation(Opcode::OP_VIEW, {inCast}, {ubTensor});93 auto& viewOp = currFunctionPtr->AddOperation(Opcode::OP_VIEW, {inCast}, {ubTensor});
94 auto& tensorOffset = inCast->GetTensorOffset();94 auto& tensorOffset = inCast->GetTensorOffset();
95- viewOp.SetOpAttribute(95+ viewOp.SetOpAttribute(std::make_shared<ViewOpAttribute>(
96- std::make_shared<ViewOpAttribute>(96+ tensorOffset.GetOffset(), tensorOffset.GetDynOffset(), ubTensor->GetDynValidShape()));
97- tensorOffset.GetOffset(), tensorOffset.GetDynOffset(), ubTensor->GetDynValidShape()));
98 currFunctionPtr->AddOperation(Opcode::OP_EXP, {ubTensor}, {outCast});97 currFunctionPtr->AddOperation(Opcode::OP_EXP, {ubTensor}, {outCast});
99 98 
100 currFunctionPtr->inCasts_.push_back(inCast);99 currFunctionPtr->inCasts_.push_back(inCast);
@@ -144,14 +143,12 @@ TEST_F(TestDuplicateOpPass, DuplicateViewUTest2)
144 143 
145 auto& viewOp = currFunctionPtr->AddOperation(Opcode::OP_VIEW, {inCast}, {ubTensor});144 auto& viewOp = currFunctionPtr->AddOperation(Opcode::OP_VIEW, {inCast}, {ubTensor});
146 auto& tensorOffset = inCast->GetTensorOffset();145 auto& tensorOffset = inCast->GetTensorOffset();
147- viewOp.SetOpAttribute(146+ viewOp.SetOpAttribute(std::make_shared<ViewOpAttribute>(
148- std::make_shared<ViewOpAttribute>(147+ tensorOffset.GetOffset(), tensorOffset.GetDynOffset(), ubTensor->GetDynValidShape()));
149- tensorOffset.GetOffset(), tensorOffset.GetDynOffset(), ubTensor->GetDynValidShape()));
150 auto& viewOp1 = currFunctionPtr->AddOperation(Opcode::OP_VIEW, {ubTensor}, {outCast2});148 auto& viewOp1 = currFunctionPtr->AddOperation(Opcode::OP_VIEW, {ubTensor}, {outCast2});
151 auto& tensorOffset1 = ubTensor->GetTensorOffset();149 auto& tensorOffset1 = ubTensor->GetTensorOffset();
152- viewOp1.SetOpAttribute(150+ viewOp1.SetOpAttribute(std::make_shared<ViewOpAttribute>(
153- std::make_shared<ViewOpAttribute>(151+ tensorOffset1.GetOffset(), tensorOffset1.GetDynOffset(), outCast2->GetDynValidShape()));
154- tensorOffset1.GetOffset(), tensorOffset1.GetDynOffset(), outCast2->GetDynValidShape()));
155 auto& sqrtOp = currFunctionPtr->AddOperation(Opcode::OP_SQRT, {ubTensor}, {outCast3});152 auto& sqrtOp = currFunctionPtr->AddOperation(Opcode::OP_SQRT, {ubTensor}, {outCast3});
156 auto& expOp = currFunctionPtr->AddOperation(Opcode::OP_EXP, {ubTensor}, {outCast1});153 auto& expOp = currFunctionPtr->AddOperation(Opcode::OP_EXP, {ubTensor}, {outCast1});
157 154 
@@ -218,14 +215,12 @@ TEST_F(TestDuplicateOpPass, DuplicateViewUTest3)
218 auto outCast3 = std::make_shared<LogicalTensor>(*currFunctionPtr, DT_FP32, shape2);215 auto outCast3 = std::make_shared<LogicalTensor>(*currFunctionPtr, DT_FP32, shape2);
219 auto& viewOp = currFunctionPtr->AddOperation(Opcode::OP_VIEW, {inCast}, {ubTensor1});216 auto& viewOp = currFunctionPtr->AddOperation(Opcode::OP_VIEW, {inCast}, {ubTensor1});
220 auto& tensorOffset = inCast->GetTensorOffset();217 auto& tensorOffset = inCast->GetTensorOffset();
221- viewOp.SetOpAttribute(218+ viewOp.SetOpAttribute(std::make_shared<ViewOpAttribute>(
222- std::make_shared<ViewOpAttribute>(219+ tensorOffset.GetOffset(), tensorOffset.GetDynOffset(), ubTensor1->GetDynValidShape()));
223- tensorOffset.GetOffset(), tensorOffset.GetDynOffset(), ubTensor1->GetDynValidShape()));
224 auto& viewOp1 = currFunctionPtr->AddOperation(Opcode::OP_VIEW, {inCast}, {ubTensor2});220 auto& viewOp1 = currFunctionPtr->AddOperation(Opcode::OP_VIEW, {inCast}, {ubTensor2});
225 auto& tensorOffset1 = inCast->GetTensorOffset();221 auto& tensorOffset1 = inCast->GetTensorOffset();
226- viewOp1.SetOpAttribute(222+ viewOp1.SetOpAttribute(std::make_shared<ViewOpAttribute>(
227- std::make_shared<ViewOpAttribute>(223+ tensorOffset1.GetOffset(), tensorOffset1.GetDynOffset(), ubTensor2->GetDynValidShape()));
228- tensorOffset1.GetOffset(), tensorOffset1.GetDynOffset(), ubTensor2->GetDynValidShape()));
229 auto& div1 = currFunctionPtr->AddOperation(Opcode::OP_DIV, {ubTensor1, ubTensor1}, {outCast1});224 auto& div1 = currFunctionPtr->AddOperation(Opcode::OP_DIV, {ubTensor1, ubTensor1}, {outCast1});
230 auto& div2 = currFunctionPtr->AddOperation(Opcode::OP_DIV, {ubTensor1, ubTensor2}, {outCast2});225 auto& div2 = currFunctionPtr->AddOperation(Opcode::OP_DIV, {ubTensor1, ubTensor2}, {outCast2});
231 auto& div3 = currFunctionPtr->AddOperation(Opcode::OP_DIV, {ubTensor2, ubTensor2}, {outCast3});226 auto& div3 = currFunctionPtr->AddOperation(Opcode::OP_DIV, {ubTensor2, ubTensor2}, {outCast3});
@@ -380,9 +375,8 @@ TEST_F(TestDuplicateOpPass, DuplicateGatherInUTest2)
380 auto& expOp = currFunctionPtr->AddOperation(Opcode::OP_EXP, {ubTensor}, {outCast1});375 auto& expOp = currFunctionPtr->AddOperation(Opcode::OP_EXP, {ubTensor}, {outCast1});
381 auto& viewOp = currFunctionPtr->AddOperation(Opcode::OP_VIEW, {ubTensor}, {outCast2});376 auto& viewOp = currFunctionPtr->AddOperation(Opcode::OP_VIEW, {ubTensor}, {outCast2});
382 auto& tensorOffset1 = ubTensor->GetTensorOffset();377 auto& tensorOffset1 = ubTensor->GetTensorOffset();
383- viewOp.SetOpAttribute(378+ viewOp.SetOpAttribute(std::make_shared<ViewOpAttribute>(
384- std::make_shared<ViewOpAttribute>(379+ tensorOffset1.GetOffset(), tensorOffset1.GetDynOffset(), outCast2->GetDynValidShape()));
385- tensorOffset1.GetOffset(), tensorOffset1.GetDynOffset(), outCast2->GetDynValidShape()));
386 auto& sqrtOp = currFunctionPtr->AddOperation(Opcode::OP_SQRT, {ubTensor}, {outCast3});380 auto& sqrtOp = currFunctionPtr->AddOperation(Opcode::OP_SQRT, {ubTensor}, {outCast3});
387 381 
388 currFunctionPtr->inCasts_.push_back(inCast);382 currFunctionPtr->inCasts_.push_back(inCast);
@@ -631,7 +625,7 @@ TEST_F(TestDuplicateOpPass, DuplicateViewGatherInUTest2)
631 auto& viewOp = currFunctionPtr->AddOperation(Opcode::OP_VIEW, {ubTensor0}, {ubTensor1});625 auto& viewOp = currFunctionPtr->AddOperation(Opcode::OP_VIEW, {ubTensor0}, {ubTensor1});
632 auto& tensorOffset1 = ubTensor0->GetTensorOffset();626 auto& tensorOffset1 = ubTensor0->GetTensorOffset();
633 viewOp.SetOpAttribute(std::make_shared<ViewOpAttribute>(627 viewOp.SetOpAttribute(std::make_shared<ViewOpAttribute>(
634- tensorOffset1.GetOffset(), tensorOffset1.GetDynOffset(), ubTensor1->GetDynValidShape()));628+ tensorOffset1.GetOffset(), tensorOffset1.GetDynOffset(), ubTensor1->GetDynValidShape()));
635 ubTensor1->UpdateDynValidShape({SymbolicScalar(kNumEight), SymbolicScalar(kNumExpFour)});629 ubTensor1->UpdateDynValidShape({SymbolicScalar(kNumEight), SymbolicScalar(kNumExpFour)});
636 auto& gatherin1 =630 auto& gatherin1 =
637 currFunctionPtr->AddOperation(Opcode::OP_GATHER_IN_L1, {ubTensor1, offsets2, blockTable2}, {ubTensor2});631 currFunctionPtr->AddOperation(Opcode::OP_GATHER_IN_L1, {ubTensor1, offsets2, blockTable2}, {ubTensor2});
@@ -689,7 +683,7 @@ TEST_F(TestDuplicateOpPass, DuplicateViewGatherInUTest3)
689 auto& viewOp = currFunctionPtr->AddOperation(Opcode::OP_VIEW, {inCast}, {ubTensor0});683 auto& viewOp = currFunctionPtr->AddOperation(Opcode::OP_VIEW, {inCast}, {ubTensor0});
690 auto& tensorOffset1 = inCast->GetTensorOffset();684 auto& tensorOffset1 = inCast->GetTensorOffset();
691 viewOp.SetOpAttribute(std::make_shared<ViewOpAttribute>(685 viewOp.SetOpAttribute(std::make_shared<ViewOpAttribute>(
692- tensorOffset1.GetOffset(), tensorOffset1.GetDynOffset(), ubTensor0->GetDynValidShape()));686+ tensorOffset1.GetOffset(), tensorOffset1.GetDynOffset(), ubTensor0->GetDynValidShape()));
693 ubTensor0->UpdateDynValidShape({SymbolicScalar(kNumEight), SymbolicScalar(kNumExpFour)});687 ubTensor0->UpdateDynValidShape({SymbolicScalar(kNumEight), SymbolicScalar(kNumExpFour)});
694 auto& gatherin =688 auto& gatherin =
695 currFunctionPtr->AddOperation(Opcode::OP_GATHER_IN_L1, {ubTensor0, offsets, blockTable}, {ubTensor1});689 currFunctionPtr->AddOperation(Opcode::OP_GATHER_IN_L1, {ubTensor0, offsets, blockTable}, {ubTensor1});
@@ -697,7 +691,7 @@ TEST_F(TestDuplicateOpPass, DuplicateViewGatherInUTest3)
697 auto& viewOp1 = currFunctionPtr->AddOperation(Opcode::OP_VIEW, {ubTensor1}, {ubTensor2});691 auto& viewOp1 = currFunctionPtr->AddOperation(Opcode::OP_VIEW, {ubTensor1}, {ubTensor2});
698 auto& tensorOffset2 = ubTensor1->GetTensorOffset();692 auto& tensorOffset2 = ubTensor1->GetTensorOffset();
699 viewOp1.SetOpAttribute(std::make_shared<ViewOpAttribute>(693 viewOp1.SetOpAttribute(std::make_shared<ViewOpAttribute>(
700- tensorOffset1.GetOffset(), tensorOffset2.GetDynOffset(), ubTensor2->GetDynValidShape()));694+ tensorOffset1.GetOffset(), tensorOffset2.GetDynOffset(), ubTensor2->GetDynValidShape()));
701 695 
702 currFunctionPtr->AddOperation(Opcode::OP_EXP, {ubTensor2}, {outCast2});696 currFunctionPtr->AddOperation(Opcode::OP_EXP, {ubTensor2}, {outCast2});
703 currFunctionPtr->AddOperation(Opcode::OP_SQRT, {ubTensor2}, {outCast1});697 currFunctionPtr->AddOperation(Opcode::OP_SQRT, {ubTensor2}, {outCast1});
@@ -761,7 +755,8 @@ TEST_F(TestDuplicateOpPass, TestCheck1)
761 currFunctionPtr->AddOperation(Opcode::OP_EXP, {tensor3}, {outcast3});755 currFunctionPtr->AddOperation(Opcode::OP_EXP, {tensor3}, {outcast3});
762 currFunctionPtr->AddOperation(Opcode::OP_SQRT, {tensor1}, {tensor2});756 currFunctionPtr->AddOperation(Opcode::OP_SQRT, {tensor1}, {tensor2});
763 currFunctionPtr->AddOperation(Opcode::OP_SQRT, {tensor1}, {outcast1});757 currFunctionPtr->AddOperation(Opcode::OP_SQRT, {tensor1}, {outcast1});
764- auto& gatherinOp = currFunctionPtr->AddOperation(Opcode::OP_GATHER_IN_L1, {tensor2, offsets, blockTable}, {tensor3});758+ auto& gatherinOp =
759+ currFunctionPtr->AddOperation(Opcode::OP_GATHER_IN_L1, {tensor2, offsets, blockTable}, {tensor3});
765 gatherinOp.SetAttribute(OpAttributeKey::startOffset, i);760 gatherinOp.SetAttribute(OpAttributeKey::startOffset, i);
766 currFunctionPtr->inCasts_.push_back(incast);761 currFunctionPtr->inCasts_.push_back(incast);
767 currFunctionPtr->outCasts_.push_back(outcast1);762 currFunctionPtr->outCasts_.push_back(outcast1);
@@ -884,9 +879,8 @@ TEST_F(TestDuplicateOpPass, TestCheck4)
884 auto tensor1 = std::make_shared<LogicalTensor>(*currFunctionPtr, DT_FP32, shape);879 auto tensor1 = std::make_shared<LogicalTensor>(*currFunctionPtr, DT_FP32, shape);
885 auto& viewOp = currFunctionPtr->AddOperation(Opcode::OP_VIEW, {incast}, {tensor1});880 auto& viewOp = currFunctionPtr->AddOperation(Opcode::OP_VIEW, {incast}, {tensor1});
886 auto& tensorOffset = incast->GetTensorOffset();881 auto& tensorOffset = incast->GetTensorOffset();
887- viewOp.SetOpAttribute(882+ viewOp.SetOpAttribute(std::make_shared<ViewOpAttribute>(
888- std::make_shared<ViewOpAttribute>(883+ tensorOffset.GetOffset(), tensorOffset.GetDynOffset(), tensor1->GetDynValidShape()));
889- tensorOffset.GetOffset(), tensorOffset.GetDynOffset(), tensor1->GetDynValidShape()));
890 currFunctionPtr->AddOperation(Opcode::OP_EXP, {tensor1}, {outcast1});884 currFunctionPtr->AddOperation(Opcode::OP_EXP, {tensor1}, {outcast1});
891 currFunctionPtr->AddOperation(Opcode::OP_EXP, {tensor1}, {outcast2});885 currFunctionPtr->AddOperation(Opcode::OP_EXP, {tensor1}, {outcast2});
892 currFunctionPtr->inCasts_.push_back(incast);886 currFunctionPtr->inCasts_.push_back(incast);
@@ -937,13 +931,13 @@ TEST_F(TestDuplicateOpPass, GatherIn_OOperandNull)
937}931}
938 932 
939/*933/*
940-TestSourceLocation934+TestSpan
941inCast{16,16}->gatherIn->ubTensor{16,16}->sqrt->outCast1{16,16}935inCast{16,16}->gatherIn->ubTensor{16,16}->sqrt->outCast1{16,16}
942 ->sqrt->outCast2{16,16}936 ->sqrt->outCast2{16,16}
943inCast{16,16}->gatherIn->ubTensor{16,16}->sqrt->outCast1{16,16}937inCast{16,16}->gatherIn->ubTensor{16,16}->sqrt->outCast1{16,16}
944 ->gatherIn->ubTensor'{16,16}->sqrt->outCast2{16,16}938 ->gatherIn->ubTensor'{16,16}->sqrt->outCast2{16,16}
945*/939*/
946-TEST_F(TestDuplicateOpPass, TestSourceLocation)940+TEST_F(TestDuplicateOpPass, TestSpan)
947{941{
948 auto currFunctionPtr =942 auto currFunctionPtr =
949 std::make_shared<Function>(Program::GetInstance(), "TestDuplicateView", "TestDuplicateView", nullptr);943 std::make_shared<Function>(Program::GetInstance(), "TestDuplicateView", "TestDuplicateView", nullptr);
@@ -951,7 +945,7 @@ TEST_F(TestDuplicateOpPass, TestSourceLocation)
951 int64_t i = 0;945 int64_t i = 0;
952 // Prepare the graph946 // Prepare the graph
953 std::vector<int64_t> shape = {kNumExpFour, kNumExpFour};947 std::vector<int64_t> shape = {kNumExpFour, kNumExpFour};
954- auto sourceLocation = std::make_shared<SourceLocation>("gatherIn", kNumOne);948+ auto span = ir::Span("gatherIn", kNumOne, 0);
955 auto inCast = std::make_shared<LogicalTensor>(*currFunctionPtr, DT_FP32, shape);949 auto inCast = std::make_shared<LogicalTensor>(*currFunctionPtr, DT_FP32, shape);
956 inCast->UpdateDynValidShape({SymbolicScalar(kNumExpFour), SymbolicScalar(kNumExpFour)});950 inCast->UpdateDynValidShape({SymbolicScalar(kNumExpFour), SymbolicScalar(kNumExpFour)});
957 auto ubTensor = std::make_shared<LogicalTensor>(*currFunctionPtr, DT_FP32, shape);951 auto ubTensor = std::make_shared<LogicalTensor>(*currFunctionPtr, DT_FP32, shape);
@@ -962,7 +956,7 @@ TEST_F(TestDuplicateOpPass, TestSourceLocation)
962 auto blockTable = CreateGatherInAuxTensor(*currFunctionPtr, kNumOne);956 auto blockTable = CreateGatherInAuxTensor(*currFunctionPtr, kNumOne);
963 957 
964 auto& gatherIn = currFunctionPtr->AddRawOperation(958 auto& gatherIn = currFunctionPtr->AddRawOperation(
965- Opcode::OP_GATHER_IN_L1, {inCast, offsets, blockTable}, {ubTensor}, true, sourceLocation);959+ Opcode::OP_GATHER_IN_L1, {inCast, offsets, blockTable}, {ubTensor}, true, span);
966 gatherIn.SetAttribute(OpAttributeKey::startOffset, i);960 gatherIn.SetAttribute(OpAttributeKey::startOffset, i);
967 gatherIn.SetScopeId(1);961 gatherIn.SetScopeId(1);
968 currFunctionPtr->AddOperation(Opcode::OP_SQRT, {ubTensor}, {outCast1});962 currFunctionPtr->AddOperation(Opcode::OP_SQRT, {ubTensor}, {outCast1});
@@ -979,10 +973,10 @@ TEST_F(TestDuplicateOpPass, TestSourceLocation)
979 973 
980 for (auto& op : currFunctionPtr->Operations()) {974 for (auto& op : currFunctionPtr->Operations()) {
981 if (op.GetOpcode() == Opcode::OP_GATHER_IN_L1) {975 if (op.GetOpcode() == Opcode::OP_GATHER_IN_L1) {
982- EXPECT_EQ(op.GetLocation()->lineno_, kNumOne);976+ EXPECT_EQ(op.GetSpan().BeginLine(), kNumOne);
983 EXPECT_EQ(op.GetScopeId(), 1);977 EXPECT_EQ(op.GetScopeId(), 1);
984 }978 }
985 }979 }
986}980}
987} // namespace tile_fwk981} // namespace tile_fwk
988-} // namespace npu982+} // namespace npu
@@ -928,30 +928,29 @@ TEST_F(MergeViewAssembleTest, TestPreCheck)
928}928}
929 929 
930/*930/*
931-TestSourceLocation931+TestSpan
932inCast{16,16}->view->ubTensor1{8,4}->assemble->ubTensor2{8,4}->assemble->outCast{8,4}932inCast{16,16}->view->ubTensor1{8,4}->assemble->ubTensor2{8,4}->assemble->outCast{8,4}
933inCast{16,16}->view->ubTensor1{8,4}->assemble->outCast{8,4}933inCast{16,16}->view->ubTensor1{8,4}->assemble->outCast{8,4}
934*/934*/
935-TEST_F(MergeViewAssembleTest, TestSourceLocation)935+TEST_F(MergeViewAssembleTest, TestSpan)
936{936{
937- auto currFunctionPtr =937+ auto currFunctionPtr = std::make_shared<Function>(Program::GetInstance(), "TestSpan", "TestSpan", nullptr);
938- std::make_shared<Function>(Program::GetInstance(), "TestSourceLocation", "TestSourceLocation", nullptr);
939 EXPECT_TRUE(currFunctionPtr != nullptr);938 EXPECT_TRUE(currFunctionPtr != nullptr);
940 939 
941 std::vector<int64_t> shape1 = {16, 16};940 std::vector<int64_t> shape1 = {16, 16};
942 std::vector<int64_t> shape2 = {8, 4};941 std::vector<int64_t> shape2 = {8, 4};
943- auto sourceLocation1 = std::make_shared<SourceLocation>("view", NUM1);942+ auto span1 = ir::Span("view", NUM1, 0);
944- auto sourceLocation2 = std::make_shared<SourceLocation>("view", NUM2);943+ auto span2 = ir::Span("view", NUM2, 0);
945 auto inCast = std::make_shared<LogicalTensor>(*currFunctionPtr, DT_FP32, shape1);944 auto inCast = std::make_shared<LogicalTensor>(*currFunctionPtr, DT_FP32, shape1);
946 auto ubTensor1 = std::make_shared<LogicalTensor>(*currFunctionPtr, DT_FP32, shape2);945 auto ubTensor1 = std::make_shared<LogicalTensor>(*currFunctionPtr, DT_FP32, shape2);
947 auto ubTensor2 = std::make_shared<LogicalTensor>(*currFunctionPtr, DT_FP32, shape2);946 auto ubTensor2 = std::make_shared<LogicalTensor>(*currFunctionPtr, DT_FP32, shape2);
948 auto outCast = std::make_shared<LogicalTensor>(*currFunctionPtr, DT_FP32, shape2);947 auto outCast = std::make_shared<LogicalTensor>(*currFunctionPtr, DT_FP32, shape2);
949 948 
950- auto& viewOp = currFunctionPtr->AddRawOperation(Opcode::OP_VIEW, {inCast}, {ubTensor1}, true, sourceLocation1);949+ auto& viewOp = currFunctionPtr->AddRawOperation(Opcode::OP_VIEW, {inCast}, {ubTensor1}, true, span1);
951 auto viewAttribute = std::make_shared<ViewOpAttribute>(std::vector<int64_t>{0, 0});950 auto viewAttribute = std::make_shared<ViewOpAttribute>(std::vector<int64_t>{0, 0});
952 viewAttribute->SetToType(MemoryType::MEM_UB);951 viewAttribute->SetToType(MemoryType::MEM_UB);
953 viewOp.SetOpAttribute(viewAttribute);952 viewOp.SetOpAttribute(viewAttribute);
954- currFunctionPtr->AddRawOperation(Opcode::OP_ASSEMBLE, {ubTensor1}, {ubTensor2}, true, sourceLocation2);953+ currFunctionPtr->AddRawOperation(Opcode::OP_ASSEMBLE, {ubTensor1}, {ubTensor2}, true, span2);
955 currFunctionPtr->AddRawOperation(Opcode::OP_ASSEMBLE, {ubTensor2}, {outCast});954 currFunctionPtr->AddRawOperation(Opcode::OP_ASSEMBLE, {ubTensor2}, {outCast});
956 955 
957 currFunctionPtr->inCasts_.push_back(inCast);956 currFunctionPtr->inCasts_.push_back(inCast);
@@ -961,10 +960,10 @@ TEST_F(MergeViewAssembleTest, TestSourceLocation)
961 EXPECT_EQ(status, SUCCESS);960 EXPECT_EQ(status, SUCCESS);
962 for (auto& op : currFunctionPtr->Operations()) {961 for (auto& op : currFunctionPtr->Operations()) {
963 if (op.GetOpcode() == Opcode::OP_ASSEMBLE) {962 if (op.GetOpcode() == Opcode::OP_ASSEMBLE) {
964- EXPECT_EQ(op.GetLocation()->lineno_, NUM2);963+ EXPECT_EQ(op.GetSpan().BeginLine(), NUM2);
965 }964 }
966 if (op.GetOpcode() == Opcode::OP_VIEW) {965 if (op.GetOpcode() == Opcode::OP_VIEW) {
967- EXPECT_EQ(op.GetLocation()->lineno_, NUM1);966+ EXPECT_EQ(op.GetSpan().BeginLine(), NUM1);
968 }967 }
969 }968 }
970}969}
@@ -974,12 +973,11 @@ TEST_F(MergeViewAssembleTest, ViewChainSameScopeIdsShouldMerge)
974 Program program;973 Program program;
975 std::string funcMagicName = "test_view_same_scope";974 std::string funcMagicName = "test_view_same_scope";
976 std::string funcRawName = "test_view_same_scope_raw";975 std::string funcRawName = "test_view_same_scope_raw";
977- std::unique_ptr<Function> function =976+ std::unique_ptr<Function> function = std::make_unique<Function>(program, funcMagicName, funcRawName, nullptr);
978- std::make_unique<Function>(program, funcMagicName, funcRawName, nullptr);
979 auto rawTensor = std::make_shared<RawTensor>(977 auto rawTensor = std::make_shared<RawTensor>(
980 DataType::DT_FP32, std::vector<int64_t>{10, 10}, TileOpFormat::TILEOP_ND, "input_tensor");978 DataType::DT_FP32, std::vector<int64_t>{10, 10}, TileOpFormat::TILEOP_ND, "input_tensor");
981- std::shared_ptr<LogicalTensor> inputTensor = std::make_shared<LogicalTensor>(979+ std::shared_ptr<LogicalTensor> inputTensor =
982- *function, rawTensor, std::vector<int64_t>{0, 0}, std::vector<int64_t>{10, 10});980+ std::make_shared<LogicalTensor>(*function, rawTensor, std::vector<int64_t>{0, 0}, std::vector<int64_t>{10, 10});
983 const_cast<std::vector<std::shared_ptr<LogicalTensor>>&>(function->GetIncast()).push_back(inputTensor);981 const_cast<std::vector<std::shared_ptr<LogicalTensor>>&>(function->GetIncast()).push_back(inputTensor);
984 982 
985 // VIEW1(scopeId=1) -> VIEW2(scopeId=1), should merge983 // VIEW1(scopeId=1) -> VIEW2(scopeId=1), should merge
@@ -1019,12 +1017,11 @@ TEST_F(MergeViewAssembleTest, ViewChainMixedDefaultAndValidScopeIdShouldMerge)
1019 Program program;1017 Program program;
1020 std::string funcMagicName = "test_view_mixed_scope";1018 std::string funcMagicName = "test_view_mixed_scope";
1021 std::string funcRawName = "test_view_mixed_scope_raw";1019 std::string funcRawName = "test_view_mixed_scope_raw";
1022- std::unique_ptr<Function> function =1020+ std::unique_ptr<Function> function = std::make_unique<Function>(program, funcMagicName, funcRawName, nullptr);
1023- std::make_unique<Function>(program, funcMagicName, funcRawName, nullptr);
1024 auto rawTensor = std::make_shared<RawTensor>(1021 auto rawTensor = std::make_shared<RawTensor>(
1025 DataType::DT_FP32, std::vector<int64_t>{10, 10}, TileOpFormat::TILEOP_ND, "input_tensor");1022 DataType::DT_FP32, std::vector<int64_t>{10, 10}, TileOpFormat::TILEOP_ND, "input_tensor");
1026- std::shared_ptr<LogicalTensor> inputTensor = std::make_shared<LogicalTensor>(1023+ std::shared_ptr<LogicalTensor> inputTensor =
1027- *function, rawTensor, std::vector<int64_t>{0, 0}, std::vector<int64_t>{10, 10});1024+ std::make_shared<LogicalTensor>(*function, rawTensor, std::vector<int64_t>{0, 0}, std::vector<int64_t>{10, 10});
1028 const_cast<std::vector<std::shared_ptr<LogicalTensor>>&>(function->GetIncast()).push_back(inputTensor);1025 const_cast<std::vector<std::shared_ptr<LogicalTensor>>&>(function->GetIncast()).push_back(inputTensor);
1029 1026 
1030 // VIEW1(scopeId=-1, default) -> VIEW2(scopeId=1), should merge and inherit scopeId=11027 // VIEW1(scopeId=-1, default) -> VIEW2(scopeId=1), should merge and inherit scopeId=1
@@ -1120,12 +1117,12 @@ TEST_F(MergeViewAssembleTest, TestInferShapeAfterMergeView)
1120 1117 
1121 std::vector<int64_t> shape = {8, 16};1118 std::vector<int64_t> shape = {8, 16};
1122 std::vector<SymbolicScalar> inputDynValidShape = {SymbolicScalar("Input_0_Dim_0"), SymbolicScalar("Input_0_Dim_1")};1119 std::vector<SymbolicScalar> inputDynValidShape = {SymbolicScalar("Input_0_Dim_0"), SymbolicScalar("Input_0_Dim_1")};
1123- 1120+ 
1124 auto rawTensor = std::make_shared<RawTensor>(DataType::DT_FP32, shape, TileOpFormat::TILEOP_ND, "inputTensor");1121 auto rawTensor = std::make_shared<RawTensor>(DataType::DT_FP32, shape, TileOpFormat::TILEOP_ND, "inputTensor");
1125 auto input = std::make_shared<LogicalTensor>(*function, rawTensor, std::vector<int64_t>{0, 0}, shape);1122 auto input = std::make_shared<LogicalTensor>(*function, rawTensor, std::vector<int64_t>{0, 0}, shape);
1126 input->UpdateDynValidShape(inputDynValidShape);1123 input->UpdateDynValidShape(inputDynValidShape);
1127 const_cast<std::vector<std::shared_ptr<LogicalTensor>>&>(function->GetIncast()).push_back(input);1124 const_cast<std::vector<std::shared_ptr<LogicalTensor>>&>(function->GetIncast()).push_back(input);
1128- 1125+ 
1129 auto tensor1 = std::make_shared<LogicalTensor>(*function, DataType::DT_FP32, shape);1126 auto tensor1 = std::make_shared<LogicalTensor>(*function, DataType::DT_FP32, shape);
1130 auto tensor2 = std::make_shared<LogicalTensor>(*function, DataType::DT_FP32, shape);1127 auto tensor2 = std::make_shared<LogicalTensor>(*function, DataType::DT_FP32, shape);
1131 auto outCast = std::make_shared<LogicalTensor>(*function, DataType::DT_FP32, shape);1128 auto outCast = std::make_shared<LogicalTensor>(*function, DataType::DT_FP32, shape);
@@ -1159,9 +1156,9 @@ TEST_F(MergeViewAssembleTest, TestInferShapeAfterMergeView)
1159 1156 
1160/*1157/*
1161TestInferShapeAfterMergeAssemble1158TestInferShapeAfterMergeAssemble
1162-input{8,16} with DynValidShape -> view -> tensor0{8,16} -> assemble1 -> tensor1{8,16} -> assemble2 -> tensor2{8,16} -> exp -> output{8,16}1159+input{8,16} with DynValidShape -> view -> tensor0{8,16} -> assemble1 -> tensor1{8,16} -> assemble2 -> tensor2{8,16} ->
1163-After merge: input -> view -> tensor0 -> mergedAssemble -> tensor2 -> exp -> output1160+exp -> output{8,16} After merge: input -> view -> tensor0 -> mergedAssemble -> tensor2 -> exp -> output Verify
1164-Verify mergedAssemble output tensor has correct DynValidShape1161+mergedAssemble output tensor has correct DynValidShape
1165*/1162*/
1166TEST_F(MergeViewAssembleTest, TestInferShapeAfterMergeAssemble)1163TEST_F(MergeViewAssembleTest, TestInferShapeAfterMergeAssemble)
1167{1164{
@@ -1171,12 +1168,13 @@ TEST_F(MergeViewAssembleTest, TestInferShapeAfterMergeAssemble)
1171 std::unique_ptr<Function> function = std::make_unique<Function>(program, funcMagicName, funcRawName, nullptr);1168 std::unique_ptr<Function> function = std::make_unique<Function>(program, funcMagicName, funcRawName, nullptr);
1172 1169 
1173 std::vector<int64_t> shape = {8, 16};1170 std::vector<int64_t> shape = {8, 16};
1174- std::vector<SymbolicScalar> tensorDynValidShape = {SymbolicScalar("Input_0_Dim_0"), SymbolicScalar("Input_0_Dim_1")};1171+ std::vector<SymbolicScalar> tensorDynValidShape = {
1175- 1172+ SymbolicScalar("Input_0_Dim_0"), SymbolicScalar("Input_0_Dim_1")};
1173+ 
1176 auto rawTensor = std::make_shared<RawTensor>(DataType::DT_FP32, shape, TileOpFormat::TILEOP_ND, "inputTensor");1174 auto rawTensor = std::make_shared<RawTensor>(DataType::DT_FP32, shape, TileOpFormat::TILEOP_ND, "inputTensor");
1177 auto input = std::make_shared<LogicalTensor>(*function, rawTensor, std::vector<int64_t>{0, 0}, shape);1175 auto input = std::make_shared<LogicalTensor>(*function, rawTensor, std::vector<int64_t>{0, 0}, shape);
1178 const_cast<std::vector<std::shared_ptr<LogicalTensor>>&>(function->GetIncast()).push_back(input);1176 const_cast<std::vector<std::shared_ptr<LogicalTensor>>&>(function->GetIncast()).push_back(input);
1179- 1177+ 
1180 auto tensor0 = std::make_shared<LogicalTensor>(*function, DataType::DT_FP32, shape);1178 auto tensor0 = std::make_shared<LogicalTensor>(*function, DataType::DT_FP32, shape);
1181 tensor0->UpdateDynValidShape(tensorDynValidShape);1179 tensor0->UpdateDynValidShape(tensorDynValidShape);
1182 auto tensor1 = std::make_shared<LogicalTensor>(*function, DataType::DT_FP32, shape);1180 auto tensor1 = std::make_shared<LogicalTensor>(*function, DataType::DT_FP32, shape);
@@ -163,7 +163,7 @@ TEST_F(TestSetHeuristicTileShapes, TestPythonJsonGeneration)
163 163 
164 TileShape::Current().SetCubeTile({64, 64}, {64, 64}, {64, 64});164 TileShape::Current().SetCubeTile({64, 64}, {64, 64}, {64, 64});
165 currFunctionPtr->SetGraphType(GraphType::TILE_GRAPH);165 currFunctionPtr->SetGraphType(GraphType::TILE_GRAPH);
166- SourceLocation::SetLocation("noexist.cpp", 1);166+ ir::Span::SetCurrent(ir::Span("noexist.cpp", 1, 0));
167 auto& add_op = currFunctionPtr->AddOperation(Opcode::OP_A_MUL_B, {inputA, inputB}, {outputC});167 auto& add_op = currFunctionPtr->AddOperation(Opcode::OP_A_MUL_B, {inputA, inputB}, {outputC});
168 add_op.tileShape_.SetCubeTile({64, 64}, {64, 64}, {64, 64});168 add_op.tileShape_.SetCubeTile({64, 64}, {64, 64}, {64, 64});
169 169 
@@ -84,7 +84,7 @@ def set_source_location(level: int = 1, filename=None, lineno=None):
84 frame = sys._getframe(level + 1)84 frame = sys._getframe(level + 1)
85 filename = frame.f_code.co_filename85 filename = frame.f_code.co_filename
86 lineno = frame.f_lineno86 lineno = frame.f_lineno
87- pypto_impl.SetLocation(filename, lineno, "")87+ pypto_impl.SetSpan(filename, lineno)
88 _source_location_depth += 188 _source_location_depth += 1
89 89 
90 90 
@@ -92,7 +92,7 @@ def clear_source_location():
92 global _source_location_depth92 global _source_location_depth
93 _source_location_depth -= 193 _source_location_depth -= 1
94 if _source_location_depth == 0:94 if _source_location_depth == 0:
95- pypto_impl.ClearLocation()95+ pypto_impl.ClearSpan()
96 96 
97 97 
98def source_location(func):98def source_location(func):
@@ -28,6 +28,7 @@ __all__ = [
28 "TensorType",28 "TensorType",
29 "TupleType",29 "TupleType",
30 "PtrType",30 "PtrType",
31+ "TokenType",
31 "DataType",32 "DataType",
32 33 
33 "FunctionType",34 "FunctionType",
@@ -97,6 +98,7 @@ from ..pypto_impl.ir import (
97 TensorType,98 TensorType,
98 TupleType,99 TupleType,
99 PtrType,100 PtrType,
101+ TokenType,
100)102)
101 103 
102# --- Data types ---104# --- Data types ---
@@ -199,7 +201,9 @@ FP8E4M3FN = DataType.FP8E4M3FN
199FP8E5M2 = DataType.FP8E5M2201FP8E5M2 = DataType.FP8E5M2
200FP16 = DataType.FP16202FP16 = DataType.FP16
201FP32 = DataType.FP32203FP32 = DataType.FP32
204+FP64 = DataType.FP64
202BF16 = DataType.BF16205BF16 = DataType.BF16
206+FP64 = DataType.FP64
203HF4 = DataType.HF4207HF4 = DataType.HF4
204HF8 = DataType.HF8208HF8 = DataType.HF8
205INDEX = DataType.INDEX209INDEX = DataType.INDEX
@@ -327,10 +327,10 @@ def SetTensorData(value: SymbolicScalar,
327 offset: List[SymbolicScalar], dst: Tensor): ...327 offset: List[SymbolicScalar], dst: Tensor): ...
328 328 
329 329 
330-def SetLocation(fname: str, lineno: int, backtrace: str) -> None: ...330+def SetSpan(fname: str, lineno: int) -> None: ...
331 331 
332 332 
333-def ClearLocation() -> None: ...333+def ClearSpan() -> None: ...
334 334 
335 335 
336class DeviceTensorData:336class DeviceTensorData:
@@ -7,7 +7,7 @@
7# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.7# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
8# See LICENSE in the root of the software repository for the full text of the License.8# See LICENSE in the root of the software repository for the full text of the License.
9# -----------------------------------------------------------------------------------------------------------9# -----------------------------------------------------------------------------------------------------------
10-from typing import Final, List, Optional, Sequence, overload10+from typing import Final, List, Any, Optional, Sequence, overload
11import enum11import enum
12 12 
13 13 
@@ -31,7 +31,9 @@ class DataType:
31 FP8E5M2: DataType # 8-bit floating point (IEEE 754 e5m2 format)31 FP8E5M2: DataType # 8-bit floating point (IEEE 754 e5m2 format)
32 FP16: DataType # 16-bit floating point (IEEE 754 half precision)32 FP16: DataType # 16-bit floating point (IEEE 754 half precision)
33 FP32: DataType # 32-bit floating point (IEEE 754 single precision)33 FP32: DataType # 32-bit floating point (IEEE 754 single precision)
34+ FP64: DataType # 64-bit floating point (IEEE 754 double precision)
34 BF16: DataType # 16-bit brain floating point35 BF16: DataType # 16-bit brain floating point
36+ FP64: DataType # 64-bit floating point (IEEE 754 double precision)
35 HF4: DataType # 4-bit Hisilicon float37 HF4: DataType # 4-bit Hisilicon float
36 HF8: DataType # 8-bit Hisilicon float38 HF8: DataType # 8-bit Hisilicon float
37 INDEX: DataType # Machine-word integer for index computations (loop vars, dims, valid shapes)39 INDEX: DataType # Machine-word integer for index computations (loop vars, dims, valid shapes)
@@ -142,8 +144,7 @@ class Span:
142 end_column: Ending column (1-indexed, -1 means unknown)144 end_column: Ending column (1-indexed, -1 means unknown)
143 """145 """
144 146 
145- @staticmethod147+ def is_unknown(self) -> bool:
146- def is_unknown(span: Span) -> bool:
147 """Check if the span is unknown.148 """Check if the span is unknown.
148 149 
149 Returns:150 Returns:
@@ -834,6 +835,17 @@ class PtrType(Type):
834 ...835 ...
835 836 
836 837 
838+class TokenType(Type):
839+ """Opaque token type for side-effect ordering."""
840+ 
841+ def __init__(self) -> None: ...
842+ 
843+ @staticmethod
844+ def get() -> TokenType:
845+ """Get the singleton TokenType instance."""
846+ ...
847+ 
848+ 
837class Var(Expr):849class Var(Expr):
838 """Variable reference expression."""850 """Variable reference expression."""
839 851 
@@ -1350,6 +1362,7 @@ class EvalStmt(Stmt):
1350class BreakStmt(Stmt):1362class BreakStmt(Stmt):
1351 """Break statement: break."""1363 """Break statement: break."""
1352 1364 
1365+ @overload
1353 def __init__(self, span: Span) -> None:1366 def __init__(self, span: Span) -> None:
1354 """Create a break statement.1367 """Create a break statement.
1355 1368 
@@ -1357,10 +1370,20 @@ class BreakStmt(Stmt):
1357 span: Source location1370 span: Source location
1358 """1371 """
1359 1372 
1373+ @overload
1374+ def __init__(self, operands: list[Expr], span: Span) -> None:
1375+ """Create a break statement with operands.
1376+ 
1377+ Args:
1378+ operands: Operands to break
1379+ span: Source location
1380+ """
1381+ 
1360 1382 
1361class ContinueStmt(Stmt):1383class ContinueStmt(Stmt):
1362 """Continue statement: continue."""1384 """Continue statement: continue."""
1363 1385 
1386+ @overload
1364 def __init__(self, span: Span) -> None:1387 def __init__(self, span: Span) -> None:
1365 """Create a continue statement.1388 """Create a continue statement.
1366 1389 
@@ -1368,6 +1391,78 @@ class ContinueStmt(Stmt):
1368 span: Source location1391 span: Source location
1369 """1392 """
1370 1393 
1394+ @overload
1395+ def __init__(self, operands: list[Expr], span: Span) -> None:
1396+ """Create a continue statement.
1397+ 
1398+ Args:
1399+ operands: Operands to continue
1400+ span: Source location
1401+ """
1402+ 
1403+ 
1404+class ScalarOpStmt(Stmt):
1405+ """Scalar operation statement"""
1406+ 
1407+ result: Final[Var]
1408+ """Result expression."""
1409+ 
1410+ result_token: Final[Var]
1411+ """Second operand."""
1412+ 
1413+ opcode: Final[str]
1414+ """Scalar operation."""
1415+ 
1416+ args: Final[list[Expr]]
1417+ """Operands to the operation."""
1418+ 
1419+ def __init__(self, result: Var, result_token: Var, opcode: str, args: list[Expr], span: Span) -> None:
1420+ """Create a scalar operation statement.
1421+ 
1422+ Args:
1423+ result: Result expression
1424+ result_token: Second operand
1425+ opcode: Scalar operation
1426+ args: Operands to the operation
1427+ span: Source location
1428+ """
1429+ 
1430+ 
1431+class TensorOpStmt(Stmt):
1432+ """Tensor operation statement"""
1433+ 
1434+ result: Final[list[Var]]
1435+ """Result expression."""
1436+ 
1437+ result_token: Final[Var]
1438+ """Second operand."""
1439+ 
1440+ opcode: Final[str]
1441+ """Tensor operation."""
1442+ 
1443+ args: Final[list[Expr]]
1444+ """Operands to the operation."""
1445+ 
1446+ tokens: Final[list[Expr]]
1447+ """Tokens (can be empty)."""
1448+ 
1449+ attrs: Final[dict[str, Any]]
1450+ """Attributes (key-value metadata)."""
1451+ 
1452+ def __init__(self, result: list[Var], result_token: Var, opcode: str, args: list[Expr],
1453+ tokens: list[Expr], attrs: dict[str, Any], span: Span) -> None:
1454+ """Create a tensor operation statement.
1455+ 
1456+ Args:
1457+ result: Result expression
1458+ result_token: Second operand
1459+ opcode: Tensor operation
1460+ args: Operands to the operation
1461+ tokens: Tokens (can be empty)
1462+ attrs: Attributes (key-value metadata)
1463+ span: Source location
1464+ """
1465+ 
1371 1466 
1372class Function(IRNode):1467class Function(IRNode):
1373 """Function definition with name, parameters, return types, and body."""1468 """Function definition with name, parameters, return types, and body."""
@@ -206,15 +206,9 @@ void bind_controller_utils(py::module& m)
206 m.def("BytesOf", [](DataType t) { return BytesOf(t); });206 m.def("BytesOf", [](DataType t) { return BytesOf(t); });
207 m.def("Reset", []() { Program::GetInstance().Reset(); });207 m.def("Reset", []() { Program::GetInstance().Reset(); });
208 m.def(208 m.def(
209- "SetLocation", [](const std::string& fname, int lineno) { SourceLocation::SetLocation(fname, lineno); },209+ "SetSpan", [](const std::string& fname, int lineno) { ir::Span::SetCurrent(ir::Span(fname, lineno, 0)); },
210 py::arg("fname"), py::arg("lineno"));210 py::arg("fname"), py::arg("lineno"));
211- m.def(211+ m.def("ClearSpan", &ir::Span::ClearCurrent);
212- "SetLocation",
213- [](const std::string& fname, int lineno, std::string& backtrace) {
214- SourceLocation::SetLocation(fname, lineno, backtrace);
215- },
216- py::arg("fname"), py::arg("lineno"), py::arg("backtrace"));
217- m.def("ClearLocation", &SourceLocation::ClearLocation);
218}212}
219 213 
220npu::tile_fwk::Any ConvertPyList(const std::string& key, const py::list& lst)214npu::tile_fwk::Any ConvertPyList(const std::string& key, const py::list& lst)
@@ -250,7 +244,7 @@ static bool IsFuncHashOrderFormat(const std::string& key)
250 }244 }
251 size_t underscore_pos = key.find('_');245 size_t underscore_pos = key.find('_');
252 if (underscore_pos == std::string::npos || underscore_pos == 4) {246 if (underscore_pos == std::string::npos || underscore_pos == 4) {
253- return false; // No underscore or underscore right after "func"247+ return false; // No underscore or underscore right after "func"
254 }248 }
255 // Check that magic part (between "func" and "_") is all digits249 // Check that magic part (between "func" and "_") is all digits
256 for (size_t i = 4; i < underscore_pos; ++i) {250 for (size_t i = 4; i < underscore_pos; ++i) {
@@ -268,9 +262,7 @@ static bool IsFuncHashOrderFormat(const std::string& key)
268}262}
269 263 
270static void SplitByFuncAndLabel(264static void SplitByFuncAndLabel(
271- const py::dict& dict_value,265+ const py::dict& dict_value, std::map<std::string, int64_t>& func_map, std::map<std::string, int64_t>& label_map)
272- std::map<std::string, int64_t>& func_map,
273- std::map<std::string, int64_t>& label_map)
274{266{
275 for (auto dict_item : dict_value) {267 for (auto dict_item : dict_value) {
276 if (py::isinstance<py::str>(dict_item.first)) {268 if (py::isinstance<py::str>(dict_item.first)) {
@@ -303,8 +295,7 @@ static void ClassifyKeys(const py::dict& dict_value, bool& has_int, bool& has_st
303}295}
304 296 
305static void HandleStrOnlyKeys(297static void HandleStrOnlyKeys(
306- const std::string& key, const py::dict& dict_value,298+ const std::string& key, const py::dict& dict_value, bool has_func, bool has_label,
307- bool has_func, bool has_label,
308 std::map<std::string, npu::tile_fwk::Any>& cpp_values)299 std::map<std::string, npu::tile_fwk::Any>& cpp_values)
309{300{
310 cpp_values[key] = std::map<int64_t, int64_t>();301 cpp_values[key] = std::map<int64_t, int64_t>();
@@ -329,8 +320,7 @@ static void HandleStrOnlyKeys(
329}320}
330 321 
331static void HandleMixedKeys(322static void HandleMixedKeys(
332- const std::string& key, const py::dict& dict_value,323+ const std::string& key, const py::dict& dict_value, std::map<std::string, npu::tile_fwk::Any>& cpp_values)
333- std::map<std::string, npu::tile_fwk::Any>& cpp_values)
334{324{
335 std::map<int64_t, int64_t> int_map;325 std::map<int64_t, int64_t> int_map;
336 std::map<std::string, int64_t> func_map, label_map;326 std::map<std::string, int64_t> func_map, label_map;
@@ -561,8 +551,5 @@ void bind_controller(py::module& m)
561 bind_controller_utils(m);551 bind_controller_utils(m);
562 bind_controller_scope(m);552 bind_controller_scope(m);
563 bind_controller_scope_classes(m);553 bind_controller_scope_classes(m);
564- 
565- // disable cpp mode
566- SourceLocation::SetCppMode(false);
567}554}
568} // namespace pypto555} // namespace pypto
@@ -48,6 +48,7 @@ void BindDType(py::module& m)
48 .def_readonly_static("FP8E5M2", &ir::DataType::FP8E5M2)48 .def_readonly_static("FP8E5M2", &ir::DataType::FP8E5M2)
49 .def_readonly_static("FP16", &ir::DataType::FP16)49 .def_readonly_static("FP16", &ir::DataType::FP16)
50 .def_readonly_static("FP32", &ir::DataType::FP32)50 .def_readonly_static("FP32", &ir::DataType::FP32)
51+ .def_readonly_static("FP64", &ir::DataType::FP64)
51 .def_readonly_static("BF16", &ir::DataType::BF16)52 .def_readonly_static("BF16", &ir::DataType::BF16)
52 .def_readonly_static("HF4", &ir::DataType::HF4)53 .def_readonly_static("HF4", &ir::DataType::HF4)
53 .def_readonly_static("HF8", &ir::DataType::HF8)54 .def_readonly_static("HF8", &ir::DataType::HF8)
@@ -71,15 +72,15 @@ void BindSpan(py::module& m)
71 .def(72 .def(
72 py::init<std::string, int, int, int, int>(), py::arg("filename"), py::arg("begin_line"),73 py::init<std::string, int, int, int, int>(), py::arg("filename"), py::arg("begin_line"),
73 py::arg("begin_column"), py::arg("end_line") = -1, py::arg("end_column") = -1, "Create a source span")74 py::arg("begin_column"), py::arg("end_line") = -1, py::arg("end_column") = -1, "Create a source span")
74- .def_static("is_unknown", &ir::Span::IsUnknown, "Check if the span is unknown")75+ .def("is_unknown", &ir::Span::IsUnknown, "Check if the span is unknown")
75 .def_static("unknown", &ir::Span::Unknown, "Create an unknown span", py::return_value_policy::reference)76 .def_static("unknown", &ir::Span::Unknown, "Create an unknown span", py::return_value_policy::reference)
76 .def("__repr__", &ir::Span::ToString)77 .def("__repr__", &ir::Span::ToString)
77 .def("__str__", &ir::Span::ToString)78 .def("__str__", &ir::Span::ToString)
78- .def_readonly("filename", &ir::Span::filename_, "Source filename")79+ .def_property_readonly("filename", &ir::Span::Filename, "Source filename")
79- .def_readonly("begin_line", &ir::Span::beginLine_, "Beginning line (1-indexed)")80+ .def_property_readonly("begin_line", &ir::Span::BeginLine, "Beginning line (1-indexed)")
80- .def_readonly("begin_column", &ir::Span::beginColumn_, "Beginning column (1-indexed)")81+ .def_property_readonly("begin_column", &ir::Span::BeginColumn, "Beginning column (1-indexed)")
81- .def_readonly("end_line", &ir::Span::endLine_, "Ending line (1-indexed)")82+ .def_property_readonly("end_line", &ir::Span::EndLine, "Ending line (1-indexed)")
82- .def_readonly("end_column", &ir::Span::endColumn_, "Ending column (1-indexed)");83+ .def_property_readonly("end_column", &ir::Span::EndColumn, "Ending column (1-indexed)");
83}84}
84 85 
85// Helper to bind a single field using reflection86// Helper to bind a single field using reflection
@@ -243,6 +244,76 @@ void BindExpr(py::module& m)
243 // clang-format on244 // clang-format on
244}245}
245 246 
247+std::any ConvertAttr(const py::object& attr)
248+{
249+ if (py::isinstance<DataType>(attr)) {
250+ return py::cast<DataType>(attr);
251+ } else if (py::isinstance<MemorySpace>(attr)) {
252+ return py::cast<MemorySpace>(attr);
253+ } else if (py::isinstance<TensorLayout>(attr)) {
254+ return py::cast<TensorLayout>(attr);
255+ } else if (py::isinstance<bool>(attr)) {
256+ return py::cast<bool>(attr);
257+ } else if (py::isinstance<py::int_>(attr)) {
258+ return py::cast<int>(attr);
259+ } else if (py::isinstance<py::str>(attr)) {
260+ return py::cast<std::string>(attr);
261+ } else if (py::isinstance<py::float_>(attr)) {
262+ return py::cast<double>(attr);
263+ } else if (py::isinstance<ExprPtr>(attr)) {
264+ return py::cast<ExprPtr>(attr);
265+ } else {
266+ throw TypeError("Unsupported attr type");
267+ }
268+}
269+ 
270+std::any ConvertListAttr(const py::list& list)
271+{
272+ if (list.empty()) {
273+ return std::any();
274+ }
275+ auto item0 = list[0];
276+ if (py::isinstance<ExprPtr>(item0)) {
277+ std::vector<ExprPtr> ret;
278+ for (auto item : list) {
279+ ret.push_back(py::cast<ExprPtr>(item));
280+ }
281+ return ret;
282+ } else if (py::isinstance<std::string>(item0)) {
283+ std::vector<std::string> ret;
284+ for (auto item : list) {
285+ ret.push_back(py::cast<std::string>(item));
286+ }
287+ return ret;
288+ } else if (py::isinstance<py::int_>(item0)) {
289+ std::vector<int> ret;
290+ for (auto item : list) {
291+ ret.push_back(py::cast<int>(item));
292+ }
293+ return ret;
294+ } else {
295+ throw TypeError("Unsupported list attr");
296+ }
297+}
298+ 
299+std::vector<std::pair<std::string, std::any>> ConvertAttrDict(const py::dict& attrs)
300+{
301+ std::vector<std::pair<std::string, std::any>> kwargs;
302+ for (auto item : attrs) {
303+ std::string key = py::cast<std::string>(item.first);
304+ std::any value;
305+ if (py::isinstance<py::list>(item.second)) {
306+ value = ConvertListAttr(py::cast<py::list>(item.second));
307+ } else {
308+ value = ConvertAttr(py::cast<py::object>(item.second));
309+ }
310+ if (value.has_value()) {
311+ kwargs.emplace_back(key, value);
312+ }
313+ }
314+ return kwargs;
315+}
316+ 
246void BindStmt(py::module& m)317void BindStmt(py::module& m)
247{318{
248 // clang-format off319 // clang-format off
@@ -327,14 +398,39 @@ void BindStmt(py::module& m)
327 398 
328 auto break_stmt = py::class_<BreakStmt, Stmt, std::shared_ptr<BreakStmt>>(m, "BreakStmt",399 auto break_stmt = py::class_<BreakStmt, Stmt, std::shared_ptr<BreakStmt>>(m, "BreakStmt",
329 "Break statement: break")400 "Break statement: break")
330- .def(py::init<const Span&>(), py::arg("span"), "Create a break statement");401+ .def(py::init<const Span&>(), py::arg("span"), "Create a break statement")
402+ .def(py::init<const std::vector<ExprPtr>&, const Span&>(),
403+ py::arg("operands"), py::arg("span"),
404+ "Create a break statement with operands");
331 BindFields<BreakStmt>(break_stmt);405 BindFields<BreakStmt>(break_stmt);
332 406 
333 auto continue_stmt = py::class_<ContinueStmt, Stmt, std::shared_ptr<ContinueStmt>>(m, "ContinueStmt",407 auto continue_stmt = py::class_<ContinueStmt, Stmt, std::shared_ptr<ContinueStmt>>(m, "ContinueStmt",
334 "Continue statement: continue")408 "Continue statement: continue")
335- .def(py::init<const Span&>(), py::arg("span"), "Create a continue statement");409+ .def(py::init<const Span&>(), py::arg("span"), "Create a continue statement")
410+ .def(py::init<const std::vector<ExprPtr>&, const Span&>(),
411+ py::arg("operands"), py::arg("span"),
412+ "Create a continue statement with operands");
336 BindFields<ContinueStmt>(continue_stmt);413 BindFields<ContinueStmt>(continue_stmt);
337 414 
415+ auto scalarop_stmt = py::class_<ScalarOpStmt, Stmt, std::shared_ptr<ScalarOpStmt>>(m, "ScalarOpStmt",
416+ "Scalar operation statement: result, result_token = opcode(args, tokens)")
417+ .def(py::init<VarPtr, VarPtr, std::string, const std::vector<ExprPtr>&, const Span&>(),
418+ py::arg("result"), py::arg("result_token"), py::arg("opcode"), py::arg("args"), py::arg("span"),
419+ "Create a scalar operation statement");
420+ BindFields<ScalarOpStmt>(scalarop_stmt);
421+ 
422+ auto tensorop_stmt = py::class_<TensorOpStmt, Stmt, std::shared_ptr<TensorOpStmt>>(m, "TensorOpStmt",
423+ "Tensor operation statement: results, result_token = opcode(args, attrs, tokens)")
424+ .def(py::init([](std::vector<VarPtr> results, VarPtr result_token, std::string opcode,
425+ std::vector<ExprPtr> args, const std::vector<ExprPtr>& tokens, py::dict attrs, Span span){
426+ auto attr_list = ConvertAttrDict(attrs);
427+ return std::make_shared<TensorOpStmt>(results, result_token, opcode, args, tokens, attr_list, span);
428+ }),
429+ py::arg("results"), py::arg("result_token"), py::arg("opcode"), py::arg("args"),
430+ py::arg("tokens"), py::arg("attrs"), py::arg("span"),
431+ "Create a tensor operation statement");
432+ BindFields<TensorOpStmt>(tensorop_stmt);
433+ 
338 auto function = py::class_<Function, IRNode, std::shared_ptr<Function>>(m, "Function",434 auto function = py::class_<Function, IRNode, std::shared_ptr<Function>>(m, "Function",
339 "Function definition with name, parameters, return types, and body")435 "Function definition with name, parameters, return types, and body")
340 .def(py::init<std::string, std::vector<VarPtr>&, std::vector<TypePtr>&, StmtPtr, Span, FunctionType>(),436 .def(py::init<std::string, std::vector<VarPtr>&, std::vector<TypePtr>&, StmtPtr, Span, FunctionType>(),
@@ -434,6 +530,8 @@ void BindTypeClass(py::module& m)
434 .def_readonly("types", &TupleType::types_);530 .def_readonly("types", &TupleType::types_);
435 531 
436 py::class_<PtrType, Type, std::shared_ptr<PtrType>>(m, "PtrType", "Pointer type").def(py::init<>());532 py::class_<PtrType, Type, std::shared_ptr<PtrType>>(m, "PtrType", "Pointer type").def(py::init<>());
533+ 
534+ py::class_<TokenType, Type, std::shared_ptr<TokenType>>(m, "TokenType", "Opaque token type").def(py::init<>());
437}535}
438} // namespace ir536} // namespace ir
439 537 
@@ -168,7 +168,5 @@ void bind_pass(py::module& m)
168 bind_pass_default_config(m);168 bind_pass_default_config(m);
169 bind_pass_config(m);169 bind_pass_config(m);
170 bind_pass_configs(m);170 bind_pass_configs(m);
171- // disable cpp mode
172- SourceLocation::SetCppMode(false);
173}171}
174} // namespace pypto172} // namespace pypto
@@ -48,6 +48,7 @@ def test_dtypes():
48 (ir.FP8E5M2, 8, False, False, True, "fp8e5m2", "unknown"),48 (ir.FP8E5M2, 8, False, False, True, "fp8e5m2", "unknown"),
49 (ir.FP16, 16, False, False, True, "fp16", "half"),49 (ir.FP16, 16, False, False, True, "fp16", "half"),
50 (ir.FP32, 32, False, False, True, "fp32", "float"),50 (ir.FP32, 32, False, False, True, "fp32", "float"),
51+ (ir.FP64, 64, False, False, True, "fp64", "double"),
51 (ir.BF16, 16, False, False, True, "bfloat16", "bfloat16"),52 (ir.BF16, 16, False, False, True, "bfloat16", "bfloat16"),
52 (ir.HF4, 4, False, False, True, "hf4", "unknown"),53 (ir.HF4, 4, False, False, True, "hf4", "unknown"),
53 (ir.HF8, 8, False, False, True, "hf8", "unknown"),54 (ir.HF8, 8, False, False, True, "hf8", "unknown"),
@@ -65,7 +66,7 @@ def test_span():
65 assert span.begin_column == 266 assert span.begin_column == 2
66 assert span.end_line == 367 assert span.end_line == 3
67 assert span.end_column == 468 assert span.end_column == 4
68- assert not ir.Span.is_unknown(span)69+ assert not span.is_unknown()
69 70 
70 span = ir.Span("span", 1, 2)71 span = ir.Span("span", 1, 2)
71 assert span.filename == "span"72 assert span.filename == "span"
@@ -73,7 +74,7 @@ def test_span():
73 assert span.begin_column == 274 assert span.begin_column == 2
74 assert span.end_line == -175 assert span.end_line == -1
75 assert span.end_column == -176 assert span.end_column == -1
76- assert not ir.Span.is_unknown(span)77+ assert not span.is_unknown()
77 78 
78 79 
79def test_logging(capfd):80def test_logging(capfd):
@@ -139,6 +140,10 @@ def test_basic_types():
139 pt = ir.PtrType()140 pt = ir.PtrType()
140 assert str(pt) == "ir.Ptr"141 assert str(pt) == "ir.Ptr"
141 142 
143+ # TokenType
144+ tt3 = ir.TokenType()
145+ assert str(tt3) == "ir.Token"
146+ 
142 147 
143def test_basic_expr():148def test_basic_expr():
144 span = ir.Span("test", 1, 1)149 span = ir.Span("test", 1, 1)