Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions include/tvm/tir/stmt.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -681,6 +681,40 @@ class AllocateConst : public Stmt {
TVM_DEFINE_OBJECT_REF_METHODS(AllocateConst, Stmt, AllocateConstNode);
};

/*! \brief Declare a buffer that can be used in the body */
class DeclBufferNode : public StmtNode {
public:
/*! \brief The buffer being declared */
Buffer buffer;
/*! \brief The body to be executed */
Stmt body;

void VisitAttrs(AttrVisitor* v) {
v->Visit("buffer", &buffer);
v->Visit("body", &body);
v->Visit("span", &span);
}

bool SEqualReduce(const DeclBufferNode* other, SEqualReducer equal) const {
return equal(buffer, other->buffer) && equal(body, other->body);
}

void SHashReduce(SHashReducer hash_reduce) const {
hash_reduce(buffer);
hash_reduce(body);
}

static constexpr const char* _type_key = "tir.DeclBuffer";
TVM_DECLARE_FINAL_OBJECT_INFO(DeclBufferNode, StmtNode);
};

/*! \brief Managed reference to DeclBufferNode */
class DeclBuffer : public Stmt {
public:
TVM_DLL DeclBuffer(Buffer buffer, Stmt body, Span span = Span());
TVM_DEFINE_OBJECT_REF_METHODS(DeclBuffer, Stmt, DeclBufferNode);
};

/*!
* \brief The container of seq statement.
* Represent a sequence of statements.
Expand Down
4 changes: 4 additions & 0 deletions include/tvm/tir/stmt_functor.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,6 +89,7 @@ class StmtFunctor<R(const Stmt& n, Args... args)> {
virtual R VisitStmt_(const WhileNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const AllocateNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const AllocateConstNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const DeclBufferNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const StoreNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const BufferStoreNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const BufferRealizeNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
Expand DownExpand Up@@ -116,6 +117,7 @@ class StmtFunctor<R(const Stmt& n, Args... args)> {
IR_STMT_FUNCTOR_DISPATCH(WhileNode);
IR_STMT_FUNCTOR_DISPATCH(AllocateNode);
IR_STMT_FUNCTOR_DISPATCH(AllocateConstNode);
IR_STMT_FUNCTOR_DISPATCH(DeclBufferNode);
IR_STMT_FUNCTOR_DISPATCH(StoreNode);
IR_STMT_FUNCTOR_DISPATCH(AssertStmtNode);
IR_STMT_FUNCTOR_DISPATCH(ProducerStoreNode);
Expand DownExpand Up@@ -159,6 +161,7 @@ class TVM_DLL StmtVisitor : protected StmtFunctor<void(const Stmt&)> {
void VisitStmt_(const WhileNode* op) override;
void VisitStmt_(const AllocateNode* op) override;
void VisitStmt_(const AllocateConstNode* op) override;
void VisitStmt_(const DeclBufferNode* op) override;
void VisitStmt_(const StoreNode* op) override;
void VisitStmt_(const BufferStoreNode* op) override;
void VisitStmt_(const BufferRealizeNode* op) override;
Expand DownExpand Up@@ -260,6 +263,7 @@ class TVM_DLL StmtMutator : protected StmtFunctor<Stmt(const Stmt&)> {
Stmt VisitStmt_(const WhileNode* op) override;
Stmt VisitStmt_(const AllocateNode* op) override;
Stmt VisitStmt_(const AllocateConstNode* op) override;
Stmt VisitStmt_(const DeclBufferNode* op) override;
Stmt VisitStmt_(const StoreNode* op) override;
Stmt VisitStmt_(const BufferStoreNode* op) override;
Stmt VisitStmt_(const BufferRealizeNode* op) override;
Expand Down
12 changes: 12 additions & 0 deletions python/tvm/script/tir/__init__.pyi
Original file line numberDiff line numberDiff line change
Expand Up@@ -187,6 +187,18 @@ def match_buffer(
buffer_type: str = "default",
axis_separators: Optional[List[int]] = None,
) -> Buffer: ...
def decl_buffer(
shape: Sequence[Union[PrimExpr, int]],
dtype: str = "float32",
data: Var = None,
strides: Optional[Sequence[int]] = None,
elem_offset: Optional[int] = None,
scope: str = "global",
align: int = -1,
offset_factor: int = 0,
buffer_type: str = "default",
axis_separators: Optional[List[int]] = None,
) -> Buffer: ...
def buffer_decl(
shape: Sequence[Union[PrimExpr, int]],
dtype: str = "float32",
Expand Down
81 changes: 81 additions & 0 deletions python/tvm/script/tir/scope_handler.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -224,6 +224,87 @@ def setup_buffer(data, dtype, shape, annotations: dict = None, span: Span = None
context.update_symbol(name, self.buffer, node)


@register
class DeclBuffer(WithScopeHandler):
"""Special Stmt decl_buffer(shape, dtype, data, strides, elem_offset, scope, align,
offset_factor, buffer_type, axis_separators)
Example
-------
.. code-block:: python
A = T.decl_buffer((128, 128), dtype="float32")
"""

def __init__(self):
def decl_buffer(
shape,
dtype="float32",
data=None,
strides=None,
elem_offset=None,
scope="global",
align=-1,
offset_factor=0,
buffer_type="default",
axis_separators=None,
span=None,
):
return tvm.tir.DeclBuffer(self.buffer, self.body, span=span)

super().__init__(decl_buffer, concise_scope=True, def_symbol=True)

def enter_scope(
self,
node: synr.ast.Node,
context: ContextMaintainer,
arg_list: List[Any],
span: synr.ast.Span,
):
# define buffer vars in symbol table
if isinstance(node, synr.ast.With):
vars = WithScopeHandler.get_optional_vars(node, context)
if len(vars) != 1:
context.report_error(f"Unexpected number of vars: 1 vs. {len(vars)}", node.span)
name = vars[0].id.name
var_span = vars[0].id.span
elif isinstance(node, synr.ast.Assign):
if len(node.lhs) != 1:
context.report_error(f"Unexpected number of vars: 1 vs. {len(node.lhs)}", node.span)
name = node.lhs[0].id.name
var_span = node.lhs[0].id.span
else:
raise Exception("Internal Bug")

def setup_buffer(
shape,
dtype,
data,
strides,
elem_offset,
scope,
align,
offset_factor,
buffer_type,
axis_separators,
span: Span = None,
):
self.buffer = tvm.tir.decl_buffer(
shape=shape,
dtype=dtype,
data=data,
strides=strides,
elem_offset=elem_offset,
scope=scope,
data_alignment=align,
offset_factor=offset_factor,
buffer_type=buffer_type,
axis_separators=axis_separators,
span=span,
)

setup_buffer(*arg_list, span=tvm_span_from_synr(var_span))
context.update_symbol(name, self.buffer, node)


@register
class LaunchThread(WithScopeHandler):
"""With scope handler T.launch_thread(env_var, extent)"""
Expand Down
1 change: 1 addition & 0 deletions python/tvm/tir/__init__.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,6 +36,7 @@
Allocate,
AllocateConst,
AttrStmt,
DeclBuffer,
)

from .stmt import ProducerRealize, SeqStmt
Expand Down
20 changes: 20 additions & 0 deletions python/tvm/tir/stmt.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -377,6 +377,26 @@ def __init__(self, buffer_var, dtype, extents, data_or_idx, body, annotations=No
)


@tvm._ffi.register_object("tir.DeclBuffer")
class DeclBuffer(Stmt):
"""DeclBuffer node.

Parameters
----------
buffer: Buffer
The buffer being declared.

body: Stmt
The body statement to be executed.

span: Optional[Span]
The location of this DeclBuffer in the source code.
"""

def __init__(self, buffer, body, span=None):
self.__init_handle_by_constructor__(_ffi_api.DeclBuffer, buffer, body, span)


@tvm._ffi.register_object("tir.AttrStmt")
class AttrStmt(Stmt):
"""AttrStmt node.
Expand Down
1 change: 1 addition & 0 deletions src/printer/text_printer.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -353,6 +353,7 @@ class TIRTextPrinter : public StmtFunctor<Doc(const Stmt&)>,
Doc VisitStmt_(const ProducerRealizeNode* op) override;
Doc VisitStmt_(const AllocateNode* op) override;
Doc VisitStmt_(const AllocateConstNode* op) override;
Doc VisitStmt_(const DeclBufferNode* op) override;
Doc VisitStmt_(const IfThenElseNode* op) override;
Doc VisitStmt_(const SeqStmtNode* op) override;
Doc VisitStmt_(const EvaluateNode* op) override;
Expand Down
12 changes: 12 additions & 0 deletions src/printer/tir_text_printer.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -557,6 +557,18 @@ Doc TIRTextPrinter::VisitStmt_(const AllocateConstNode* op) {
return doc;
}

Doc TIRTextPrinter::VisitStmt_(const DeclBufferNode* op) {
Doc doc;
doc << AllocBuf(op->buffer) << " = decl_buffer(" << Print(op->buffer->data) << ", "
<< PrintDType(op->buffer->dtype) << ", " << Print(op->buffer->shape) << ")" << Doc::NewLine();
if (op->body->IsInstance<SeqStmtNode>()) {
doc << PrintBody(op->body);
} else {
doc << ";" << Doc::NewLine() << Print(op->body);
}
return doc;
}

Doc TIRTextPrinter::VisitStmt_(const IfThenElseNode* op) {
Doc doc;
doc << "if " << Print(op->condition) << PrintBody(op->then_case);
Expand Down
19 changes: 19 additions & 0 deletions src/printer/tvmscript_printer.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,6 +245,7 @@ class TVMScriptPrinter : public StmtFunctor<Doc(const Stmt&)>,
Doc VisitStmt_(const BufferRealizeNode* op) override;
Doc VisitStmt_(const AllocateNode* op) override;
Doc VisitStmt_(const AllocateConstNode* op) override;
Doc VisitStmt_(const DeclBufferNode* op) override;
Doc VisitStmt_(const IfThenElseNode* op) override;
Doc VisitStmt_(const SeqStmtNode* op) override;
Doc VisitStmt_(const ForNode* op) override;
Expand DownExpand Up@@ -1161,6 +1162,24 @@ Doc TVMScriptPrinter::VisitStmt_(const AllocateConstNode* alloc) {
return doc;
}

Doc TVMScriptPrinter::VisitStmt_(const DeclBufferNode* op) {
const Buffer& buffer = op->buffer;
buf_not_in_headers_.insert(buffer.get());
Doc buffer_name = Print(op->buffer);
Doc func_call;
func_call << tir_prefix_ << ".decl_buffer(" << memo_buf_decl_.at(buffer) << ")";

Doc doc;
if (current_num_ != num_child_ - 1) {
doc << "with " << func_call << " as " << buffer_name << ":";
doc << Doc::Indent(4, Doc::NewLine() << PrintBody(op->body));
} else {
doc << buffer_name << " = " << func_call << Doc::NewLine();
doc << PrintBody(op->body);
}
return doc;
}

Doc TVMScriptPrinter::VisitStmt_(const IfThenElseNode* op) {
Doc doc;
doc << "if " << Print(op->condition) << ":";
Expand Down
2 changes: 2 additions & 0 deletions src/target/source/codegen_c.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -661,6 +661,8 @@ void CodeGenC::VisitStmt_(const AllocateConstNode* op) {
this->PrintStmt(op->body);
}

void CodeGenC::VisitStmt_(const DeclBufferNode* op) { this->PrintStmt(op->body); }

void CodeGenC::VisitExpr_(const LoadNode* op, std::ostream& os) { // NOLINT(*)
LOG(FATAL) << "Unexpected deprecated LoadNode. Use BufferLoadNode instead.";
}
Expand Down
1 change: 1 addition & 0 deletions src/target/source/codegen_c.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -166,6 +166,7 @@ class CodeGenC : public ExprFunctor<void(const PrimExpr&, std::ostream&)>,
void VisitStmt_(const EvaluateNode* op) override;
void VisitStmt_(const SeqStmtNode* op) override;
void VisitStmt_(const AllocateConstNode* op) override;
void VisitStmt_(const DeclBufferNode* op) override;

/*!
* \brief Print expr representing the thread tag
Expand Down
23 changes: 23 additions & 0 deletions src/tir/ir/stmt.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -508,6 +508,29 @@ TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
p->Print(op->body);
});

// DeclBuffer
DeclBuffer::DeclBuffer(Buffer buffer, Stmt body, Span span) {
ObjectPtr<DeclBufferNode> node = make_object<DeclBufferNode>();
node->buffer = std::move(buffer);
node->body = std::move(body);
node->span = std::move(span);
data_ = std::move(node);
}

TVM_REGISTER_GLOBAL("tir.DeclBuffer").set_body_typed([](Buffer buffer, Stmt body, Span span) {
return DeclBuffer(buffer, body, span);
});

TVM_REGISTER_NODE_TYPE(DeclBufferNode);

TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
.set_dispatch<DeclBufferNode>([](const ObjectRef& node, ReprPrinter* p) {
auto* op = static_cast<const DeclBufferNode*>(node.get());
p->PrintIndent();
p->stream << "decl_buffer " << op->buffer << "\n";
p->stream << op->body;
});

// ProducerRealize
ProducerRealize::ProducerRealize(DataProducer producer, Region bounds, PrimExpr condition,
Stmt body, String storage_scope, Span span) {
Expand Down
14 changes: 14 additions & 0 deletions src/tir/ir/stmt_functor.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,6 +63,8 @@ void StmtVisitor::VisitStmt_(const AllocateConstNode* op) {
this->VisitStmt(op->body);
}

void StmtVisitor::VisitStmt_(const DeclBufferNode* op) { this->VisitStmt(op->body); }

void StmtVisitor::VisitStmt_(const StoreNode* op) {
LOG(FATAL) << "Unexpected use of deprecated StoreNode. Please use BufferStoreNode instead.";
}
Expand DownExpand Up@@ -336,6 +338,18 @@ Stmt StmtMutator::VisitStmt_(const AllocateConstNode* op) {
}
}

Stmt StmtMutator::VisitStmt_(const DeclBufferNode* op) {
Stmt body = this->VisitStmt(op->body);

if (body.same_as(op->body)) {
return GetRef<Stmt>(op);
} else {
auto n = CopyOnWrite(op);
n->body = std::move(body);
return Stmt(n);
}
}

Stmt StmtMutator::VisitStmt_(const IfThenElseNode* op) {
PrimExpr condition = this->VisitExpr(op->condition);
Stmt then_case = this->VisitStmt(op->then_case);
Expand Down
6 changes: 4 additions & 2 deletions tests/cpp/ir_functor_test.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -181,6 +181,7 @@ TEST(IRF, StmtVisitor) {
DataType dtype = DataType::Float(32);
Var buf_var("b", PointerType(PrimType(dtype)));
Buffer buffer = decl_buffer({16});
body = DeclBuffer(buffer, std::move(body));
BufferRegion buffer_region(buffer, {Range::FromMinExtent(x + 1, 1)});
MatchBufferRegion match_buffer_region(decl_buffer({1}), buffer_region);

Expand DownExpand Up@@ -309,6 +310,7 @@ TEST(IRF, StmtMutator) {
DataType dtype = DataType::Float(32);
Var buf_var("b", PointerType(PrimType(dtype)));
Buffer buffer = decl_buffer({16});
body = DeclBuffer(buffer, std::move(body));
BufferRegion buffer_region(buffer, {Range::FromMinExtent(x + 1, 1)});
MatchBufferRegion match_buffer_region(decl_buffer({1}), buffer_region);
// construct block and block_realize
Expand All@@ -318,8 +320,8 @@ TEST(IRF, StmtMutator) {
body = v(std::move(block_realize));
// the body should be changed
Block new_block = body.as<BlockRealizeNode>()->block;
ICHECK(new_block->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->init.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->body.as<DeclBufferNode>()->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->init.as<DeclBufferNode>()->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->reads[0]->region[0]->min.same_as(x));
ICHECK(new_block->writes[0]->region[0]->min.same_as(x));
ICHECK(new_block->match_buffers[0]->source->region[0]->min.same_as(x));
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
[TIR] Add DeclBuffer IR node and functors by vinx13 · Pull Request #12300 · apache/tvm · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions include/tvm/tir/stmt.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -681,6 +681,40 @@ class AllocateConst : public Stmt {
TVM_DEFINE_OBJECT_REF_METHODS(AllocateConst, Stmt, AllocateConstNode);
};

/*! \brief Declare a buffer that can be used in the body */
class DeclBufferNode : public StmtNode {
public:
/*! \brief The buffer being declared */
Buffer buffer;
/*! \brief The body to be executed */
Stmt body;

void VisitAttrs(AttrVisitor* v) {
v->Visit("buffer", &buffer);
v->Visit("body", &body);
v->Visit("span", &span);
}

bool SEqualReduce(const DeclBufferNode* other, SEqualReducer equal) const {
return equal(buffer, other->buffer) && equal(body, other->body);
}

void SHashReduce(SHashReducer hash_reduce) const {
hash_reduce(buffer);
hash_reduce(body);
}

static constexpr const char* _type_key = "tir.DeclBuffer";
TVM_DECLARE_FINAL_OBJECT_INFO(DeclBufferNode, StmtNode);
};

/*! \brief Managed reference to DeclBufferNode */
class DeclBuffer : public Stmt {
public:
TVM_DLL DeclBuffer(Buffer buffer, Stmt body, Span span = Span());
TVM_DEFINE_OBJECT_REF_METHODS(DeclBuffer, Stmt, DeclBufferNode);
};

/*!
* \brief The container of seq statement.
* Represent a sequence of statements.
Expand Down
4 changes: 4 additions & 0 deletions include/tvm/tir/stmt_functor.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,6 +89,7 @@ class StmtFunctor<R(const Stmt& n, Args... args)> {
virtual R VisitStmt_(const WhileNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const AllocateNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const AllocateConstNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const DeclBufferNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const StoreNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const BufferStoreNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const BufferRealizeNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
Expand DownExpand Up@@ -116,6 +117,7 @@ class StmtFunctor<R(const Stmt& n, Args... args)> {
IR_STMT_FUNCTOR_DISPATCH(WhileNode);
IR_STMT_FUNCTOR_DISPATCH(AllocateNode);
IR_STMT_FUNCTOR_DISPATCH(AllocateConstNode);
IR_STMT_FUNCTOR_DISPATCH(DeclBufferNode);
IR_STMT_FUNCTOR_DISPATCH(StoreNode);
IR_STMT_FUNCTOR_DISPATCH(AssertStmtNode);
IR_STMT_FUNCTOR_DISPATCH(ProducerStoreNode);
Expand DownExpand Up@@ -159,6 +161,7 @@ class TVM_DLL StmtVisitor : protected StmtFunctor<void(const Stmt&)> {
void VisitStmt_(const WhileNode* op) override;
void VisitStmt_(const AllocateNode* op) override;
void VisitStmt_(const AllocateConstNode* op) override;
void VisitStmt_(const DeclBufferNode* op) override;
void VisitStmt_(const StoreNode* op) override;
void VisitStmt_(const BufferStoreNode* op) override;
void VisitStmt_(const BufferRealizeNode* op) override;
Expand DownExpand Up@@ -260,6 +263,7 @@ class TVM_DLL StmtMutator : protected StmtFunctor<Stmt(const Stmt&)> {
Stmt VisitStmt_(const WhileNode* op) override;
Stmt VisitStmt_(const AllocateNode* op) override;
Stmt VisitStmt_(const AllocateConstNode* op) override;
Stmt VisitStmt_(const DeclBufferNode* op) override;
Stmt VisitStmt_(const StoreNode* op) override;
Stmt VisitStmt_(const BufferStoreNode* op) override;
Stmt VisitStmt_(const BufferRealizeNode* op) override;
Expand Down
12 changes: 12 additions & 0 deletions python/tvm/script/tir/__init__.pyi
Original file line numberDiff line numberDiff line change
Expand Up@@ -187,6 +187,18 @@ def match_buffer(
buffer_type: str = "default",
axis_separators: Optional[List[int]] = None,
) -> Buffer: ...
def decl_buffer(
shape: Sequence[Union[PrimExpr, int]],
dtype: str = "float32",
data: Var = None,
strides: Optional[Sequence[int]] = None,
elem_offset: Optional[int] = None,
scope: str = "global",
align: int = -1,
offset_factor: int = 0,
buffer_type: str = "default",
axis_separators: Optional[List[int]] = None,
) -> Buffer: ...
def buffer_decl(
shape: Sequence[Union[PrimExpr, int]],
dtype: str = "float32",
Expand Down
81 changes: 81 additions & 0 deletions python/tvm/script/tir/scope_handler.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -224,6 +224,87 @@ def setup_buffer(data, dtype, shape, annotations: dict = None, span: Span = None
context.update_symbol(name, self.buffer, node)


@register
class DeclBuffer(WithScopeHandler):
"""Special Stmt decl_buffer(shape, dtype, data, strides, elem_offset, scope, align,
offset_factor, buffer_type, axis_separators)
Example
-------
.. code-block:: python
A = T.decl_buffer((128, 128), dtype="float32")
"""

def __init__(self):
def decl_buffer(
shape,
dtype="float32",
data=None,
strides=None,
elem_offset=None,
scope="global",
align=-1,
offset_factor=0,
buffer_type="default",
axis_separators=None,
span=None,
):
return tvm.tir.DeclBuffer(self.buffer, self.body, span=span)

super().__init__(decl_buffer, concise_scope=True, def_symbol=True)

def enter_scope(
self,
node: synr.ast.Node,
context: ContextMaintainer,
arg_list: List[Any],
span: synr.ast.Span,
):
# define buffer vars in symbol table
if isinstance(node, synr.ast.With):
vars = WithScopeHandler.get_optional_vars(node, context)
if len(vars) != 1:
context.report_error(f"Unexpected number of vars: 1 vs. {len(vars)}", node.span)
name = vars[0].id.name
var_span = vars[0].id.span
elif isinstance(node, synr.ast.Assign):
if len(node.lhs) != 1:
context.report_error(f"Unexpected number of vars: 1 vs. {len(node.lhs)}", node.span)
name = node.lhs[0].id.name
var_span = node.lhs[0].id.span
else:
raise Exception("Internal Bug")

def setup_buffer(
shape,
dtype,
data,
strides,
elem_offset,
scope,
align,
offset_factor,
buffer_type,
axis_separators,
span: Span = None,
):
self.buffer = tvm.tir.decl_buffer(
shape=shape,
dtype=dtype,
data=data,
strides=strides,
elem_offset=elem_offset,
scope=scope,
data_alignment=align,
offset_factor=offset_factor,
buffer_type=buffer_type,
axis_separators=axis_separators,
span=span,
)

setup_buffer(*arg_list, span=tvm_span_from_synr(var_span))
context.update_symbol(name, self.buffer, node)


@register
class LaunchThread(WithScopeHandler):
"""With scope handler T.launch_thread(env_var, extent)"""
Expand Down
1 change: 1 addition & 0 deletions python/tvm/tir/__init__.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,6 +36,7 @@
Allocate,
AllocateConst,
AttrStmt,
DeclBuffer,
)

from .stmt import ProducerRealize, SeqStmt
Expand Down
20 changes: 20 additions & 0 deletions python/tvm/tir/stmt.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -377,6 +377,26 @@ def __init__(self, buffer_var, dtype, extents, data_or_idx, body, annotations=No
)


@tvm._ffi.register_object("tir.DeclBuffer")
class DeclBuffer(Stmt):
"""DeclBuffer node.

Parameters
----------
buffer: Buffer
The buffer being declared.

body: Stmt
The body statement to be executed.

span: Optional[Span]
The location of this DeclBuffer in the source code.
"""

def __init__(self, buffer, body, span=None):
self.__init_handle_by_constructor__(_ffi_api.DeclBuffer, buffer, body, span)


@tvm._ffi.register_object("tir.AttrStmt")
class AttrStmt(Stmt):
"""AttrStmt node.
Expand Down
1 change: 1 addition & 0 deletions src/printer/text_printer.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -353,6 +353,7 @@ class TIRTextPrinter : public StmtFunctor<Doc(const Stmt&)>,
Doc VisitStmt_(const ProducerRealizeNode* op) override;
Doc VisitStmt_(const AllocateNode* op) override;
Doc VisitStmt_(const AllocateConstNode* op) override;
Doc VisitStmt_(const DeclBufferNode* op) override;
Doc VisitStmt_(const IfThenElseNode* op) override;
Doc VisitStmt_(const SeqStmtNode* op) override;
Doc VisitStmt_(const EvaluateNode* op) override;
Expand Down
12 changes: 12 additions & 0 deletions src/printer/tir_text_printer.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -557,6 +557,18 @@ Doc TIRTextPrinter::VisitStmt_(const AllocateConstNode* op) {
return doc;
}

Doc TIRTextPrinter::VisitStmt_(const DeclBufferNode* op) {
Doc doc;
doc << AllocBuf(op->buffer) << " = decl_buffer(" << Print(op->buffer->data) << ", "
<< PrintDType(op->buffer->dtype) << ", " << Print(op->buffer->shape) << ")" << Doc::NewLine();
if (op->body->IsInstance<SeqStmtNode>()) {
doc << PrintBody(op->body);
} else {
doc << ";" << Doc::NewLine() << Print(op->body);
}
return doc;
}

Doc TIRTextPrinter::VisitStmt_(const IfThenElseNode* op) {
Doc doc;
doc << "if " << Print(op->condition) << PrintBody(op->then_case);
Expand Down
19 changes: 19 additions & 0 deletions src/printer/tvmscript_printer.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,6 +245,7 @@ class TVMScriptPrinter : public StmtFunctor<Doc(const Stmt&)>,
Doc VisitStmt_(const BufferRealizeNode* op) override;
Doc VisitStmt_(const AllocateNode* op) override;
Doc VisitStmt_(const AllocateConstNode* op) override;
Doc VisitStmt_(const DeclBufferNode* op) override;
Doc VisitStmt_(const IfThenElseNode* op) override;
Doc VisitStmt_(const SeqStmtNode* op) override;
Doc VisitStmt_(const ForNode* op) override;
Expand DownExpand Up@@ -1161,6 +1162,24 @@ Doc TVMScriptPrinter::VisitStmt_(const AllocateConstNode* alloc) {
return doc;
}

Doc TVMScriptPrinter::VisitStmt_(const DeclBufferNode* op) {
const Buffer& buffer = op->buffer;
buf_not_in_headers_.insert(buffer.get());
Doc buffer_name = Print(op->buffer);
Doc func_call;
func_call << tir_prefix_ << ".decl_buffer(" << memo_buf_decl_.at(buffer) << ")";

Doc doc;
if (current_num_ != num_child_ - 1) {
doc << "with " << func_call << " as " << buffer_name << ":";
doc << Doc::Indent(4, Doc::NewLine() << PrintBody(op->body));
} else {
doc << buffer_name << " = " << func_call << Doc::NewLine();
doc << PrintBody(op->body);
}
return doc;
}

Doc TVMScriptPrinter::VisitStmt_(const IfThenElseNode* op) {
Doc doc;
doc << "if " << Print(op->condition) << ":";
Expand Down
2 changes: 2 additions & 0 deletions src/target/source/codegen_c.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -661,6 +661,8 @@ void CodeGenC::VisitStmt_(const AllocateConstNode* op) {
this->PrintStmt(op->body);
}

void CodeGenC::VisitStmt_(const DeclBufferNode* op) { this->PrintStmt(op->body); }

void CodeGenC::VisitExpr_(const LoadNode* op, std::ostream& os) { // NOLINT(*)
LOG(FATAL) << "Unexpected deprecated LoadNode. Use BufferLoadNode instead.";
}
Expand Down
1 change: 1 addition & 0 deletions src/target/source/codegen_c.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -166,6 +166,7 @@ class CodeGenC : public ExprFunctor<void(const PrimExpr&, std::ostream&)>,
void VisitStmt_(const EvaluateNode* op) override;
void VisitStmt_(const SeqStmtNode* op) override;
void VisitStmt_(const AllocateConstNode* op) override;
void VisitStmt_(const DeclBufferNode* op) override;

/*!
* \brief Print expr representing the thread tag
Expand Down
23 changes: 23 additions & 0 deletions src/tir/ir/stmt.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -508,6 +508,29 @@ TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
p->Print(op->body);
});

// DeclBuffer
DeclBuffer::DeclBuffer(Buffer buffer, Stmt body, Span span) {
ObjectPtr<DeclBufferNode> node = make_object<DeclBufferNode>();
node->buffer = std::move(buffer);
node->body = std::move(body);
node->span = std::move(span);
data_ = std::move(node);
}

TVM_REGISTER_GLOBAL("tir.DeclBuffer").set_body_typed([](Buffer buffer, Stmt body, Span span) {
return DeclBuffer(buffer, body, span);
});

TVM_REGISTER_NODE_TYPE(DeclBufferNode);

TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
.set_dispatch<DeclBufferNode>([](const ObjectRef& node, ReprPrinter* p) {
auto* op = static_cast<const DeclBufferNode*>(node.get());
p->PrintIndent();
p->stream << "decl_buffer " << op->buffer << "\n";
p->stream << op->body;
});

// ProducerRealize
ProducerRealize::ProducerRealize(DataProducer producer, Region bounds, PrimExpr condition,
Stmt body, String storage_scope, Span span) {
Expand Down
14 changes: 14 additions & 0 deletions src/tir/ir/stmt_functor.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,6 +63,8 @@ void StmtVisitor::VisitStmt_(const AllocateConstNode* op) {
this->VisitStmt(op->body);
}

void StmtVisitor::VisitStmt_(const DeclBufferNode* op) { this->VisitStmt(op->body); }

void StmtVisitor::VisitStmt_(const StoreNode* op) {
LOG(FATAL) << "Unexpected use of deprecated StoreNode. Please use BufferStoreNode instead.";
}
Expand DownExpand Up@@ -336,6 +338,18 @@ Stmt StmtMutator::VisitStmt_(const AllocateConstNode* op) {
}
}

Stmt StmtMutator::VisitStmt_(const DeclBufferNode* op) {
Stmt body = this->VisitStmt(op->body);

if (body.same_as(op->body)) {
return GetRef<Stmt>(op);
} else {
auto n = CopyOnWrite(op);
n->body = std::move(body);
return Stmt(n);
}
}

Stmt StmtMutator::VisitStmt_(const IfThenElseNode* op) {
PrimExpr condition = this->VisitExpr(op->condition);
Stmt then_case = this->VisitStmt(op->then_case);
Expand Down
6 changes: 4 additions & 2 deletions tests/cpp/ir_functor_test.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -181,6 +181,7 @@ TEST(IRF, StmtVisitor) {
DataType dtype = DataType::Float(32);
Var buf_var("b", PointerType(PrimType(dtype)));
Buffer buffer = decl_buffer({16});
body = DeclBuffer(buffer, std::move(body));
BufferRegion buffer_region(buffer, {Range::FromMinExtent(x + 1, 1)});
MatchBufferRegion match_buffer_region(decl_buffer({1}), buffer_region);

Expand DownExpand Up@@ -309,6 +310,7 @@ TEST(IRF, StmtMutator) {
DataType dtype = DataType::Float(32);
Var buf_var("b", PointerType(PrimType(dtype)));
Buffer buffer = decl_buffer({16});
body = DeclBuffer(buffer, std::move(body));
BufferRegion buffer_region(buffer, {Range::FromMinExtent(x + 1, 1)});
MatchBufferRegion match_buffer_region(decl_buffer({1}), buffer_region);
// construct block and block_realize
Expand All@@ -318,8 +320,8 @@ TEST(IRF, StmtMutator) {
body = v(std::move(block_realize));
// the body should be changed
Block new_block = body.as<BlockRealizeNode>()->block;
ICHECK(new_block->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->init.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->body.as<DeclBufferNode>()->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->init.as<DeclBufferNode>()->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->reads[0]->region[0]->min.same_as(x));
ICHECK(new_block->writes[0]->region[0]->min.same_as(x));
ICHECK(new_block->match_buffers[0]->source->region[0]->min.same_as(x));
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [TIR] Add DeclBuffer IR node and functors by vinx13 · Pull Request #12300 · apache/tvm · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions include/tvm/tir/stmt.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -681,6 +681,40 @@ class AllocateConst : public Stmt {
TVM_DEFINE_OBJECT_REF_METHODS(AllocateConst, Stmt, AllocateConstNode);
};

/*! \brief Declare a buffer that can be used in the body */
class DeclBufferNode : public StmtNode {
public:
/*! \brief The buffer being declared */
Buffer buffer;
/*! \brief The body to be executed */
Stmt body;

void VisitAttrs(AttrVisitor* v) {
v->Visit("buffer", &buffer);
v->Visit("body", &body);
v->Visit("span", &span);
}

bool SEqualReduce(const DeclBufferNode* other, SEqualReducer equal) const {
return equal(buffer, other->buffer) && equal(body, other->body);
}

void SHashReduce(SHashReducer hash_reduce) const {
hash_reduce(buffer);
hash_reduce(body);
}

static constexpr const char* _type_key = "tir.DeclBuffer";
TVM_DECLARE_FINAL_OBJECT_INFO(DeclBufferNode, StmtNode);
};

/*! \brief Managed reference to DeclBufferNode */
class DeclBuffer : public Stmt {
public:
TVM_DLL DeclBuffer(Buffer buffer, Stmt body, Span span = Span());
TVM_DEFINE_OBJECT_REF_METHODS(DeclBuffer, Stmt, DeclBufferNode);
};

/*!
* \brief The container of seq statement.
* Represent a sequence of statements.
Expand Down
4 changes: 4 additions & 0 deletions include/tvm/tir/stmt_functor.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,6 +89,7 @@ class StmtFunctor<R(const Stmt& n, Args... args)> {
virtual R VisitStmt_(const WhileNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const AllocateNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const AllocateConstNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const DeclBufferNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const StoreNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const BufferStoreNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const BufferRealizeNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
Expand DownExpand Up@@ -116,6 +117,7 @@ class StmtFunctor<R(const Stmt& n, Args... args)> {
IR_STMT_FUNCTOR_DISPATCH(WhileNode);
IR_STMT_FUNCTOR_DISPATCH(AllocateNode);
IR_STMT_FUNCTOR_DISPATCH(AllocateConstNode);
IR_STMT_FUNCTOR_DISPATCH(DeclBufferNode);
IR_STMT_FUNCTOR_DISPATCH(StoreNode);
IR_STMT_FUNCTOR_DISPATCH(AssertStmtNode);
IR_STMT_FUNCTOR_DISPATCH(ProducerStoreNode);
Expand DownExpand Up@@ -159,6 +161,7 @@ class TVM_DLL StmtVisitor : protected StmtFunctor<void(const Stmt&)> {
void VisitStmt_(const WhileNode* op) override;
void VisitStmt_(const AllocateNode* op) override;
void VisitStmt_(const AllocateConstNode* op) override;
void VisitStmt_(const DeclBufferNode* op) override;
void VisitStmt_(const StoreNode* op) override;
void VisitStmt_(const BufferStoreNode* op) override;
void VisitStmt_(const BufferRealizeNode* op) override;
Expand DownExpand Up@@ -260,6 +263,7 @@ class TVM_DLL StmtMutator : protected StmtFunctor<Stmt(const Stmt&)> {
Stmt VisitStmt_(const WhileNode* op) override;
Stmt VisitStmt_(const AllocateNode* op) override;
Stmt VisitStmt_(const AllocateConstNode* op) override;
Stmt VisitStmt_(const DeclBufferNode* op) override;
Stmt VisitStmt_(const StoreNode* op) override;
Stmt VisitStmt_(const BufferStoreNode* op) override;
Stmt VisitStmt_(const BufferRealizeNode* op) override;
Expand Down
12 changes: 12 additions & 0 deletions python/tvm/script/tir/__init__.pyi
Original file line numberDiff line numberDiff line change
Expand Up@@ -187,6 +187,18 @@ def match_buffer(
buffer_type: str = "default",
axis_separators: Optional[List[int]] = None,
) -> Buffer: ...
def decl_buffer(
shape: Sequence[Union[PrimExpr, int]],
dtype: str = "float32",
data: Var = None,
strides: Optional[Sequence[int]] = None,
elem_offset: Optional[int] = None,
scope: str = "global",
align: int = -1,
offset_factor: int = 0,
buffer_type: str = "default",
axis_separators: Optional[List[int]] = None,
) -> Buffer: ...
def buffer_decl(
shape: Sequence[Union[PrimExpr, int]],
dtype: str = "float32",
Expand Down
81 changes: 81 additions & 0 deletions python/tvm/script/tir/scope_handler.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -224,6 +224,87 @@ def setup_buffer(data, dtype, shape, annotations: dict = None, span: Span = None
context.update_symbol(name, self.buffer, node)


@register
class DeclBuffer(WithScopeHandler):
"""Special Stmt decl_buffer(shape, dtype, data, strides, elem_offset, scope, align,
offset_factor, buffer_type, axis_separators)
Example
-------
.. code-block:: python
A = T.decl_buffer((128, 128), dtype="float32")
"""

def __init__(self):
def decl_buffer(
shape,
dtype="float32",
data=None,
strides=None,
elem_offset=None,
scope="global",
align=-1,
offset_factor=0,
buffer_type="default",
axis_separators=None,
span=None,
):
return tvm.tir.DeclBuffer(self.buffer, self.body, span=span)

super().__init__(decl_buffer, concise_scope=True, def_symbol=True)

def enter_scope(
self,
node: synr.ast.Node,
context: ContextMaintainer,
arg_list: List[Any],
span: synr.ast.Span,
):
# define buffer vars in symbol table
if isinstance(node, synr.ast.With):
vars = WithScopeHandler.get_optional_vars(node, context)
if len(vars) != 1:
context.report_error(f"Unexpected number of vars: 1 vs. {len(vars)}", node.span)
name = vars[0].id.name
var_span = vars[0].id.span
elif isinstance(node, synr.ast.Assign):
if len(node.lhs) != 1:
context.report_error(f"Unexpected number of vars: 1 vs. {len(node.lhs)}", node.span)
name = node.lhs[0].id.name
var_span = node.lhs[0].id.span
else:
raise Exception("Internal Bug")

def setup_buffer(
shape,
dtype,
data,
strides,
elem_offset,
scope,
align,
offset_factor,
buffer_type,
axis_separators,
span: Span = None,
):
self.buffer = tvm.tir.decl_buffer(
shape=shape,
dtype=dtype,
data=data,
strides=strides,
elem_offset=elem_offset,
scope=scope,
data_alignment=align,
offset_factor=offset_factor,
buffer_type=buffer_type,
axis_separators=axis_separators,
span=span,
)

setup_buffer(*arg_list, span=tvm_span_from_synr(var_span))
context.update_symbol(name, self.buffer, node)


@register
class LaunchThread(WithScopeHandler):
"""With scope handler T.launch_thread(env_var, extent)"""
Expand Down
1 change: 1 addition & 0 deletions python/tvm/tir/__init__.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,6 +36,7 @@
Allocate,
AllocateConst,
AttrStmt,
DeclBuffer,
)

from .stmt import ProducerRealize, SeqStmt
Expand Down
20 changes: 20 additions & 0 deletions python/tvm/tir/stmt.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -377,6 +377,26 @@ def __init__(self, buffer_var, dtype, extents, data_or_idx, body, annotations=No
)


@tvm._ffi.register_object("tir.DeclBuffer")
class DeclBuffer(Stmt):
"""DeclBuffer node.

Parameters
----------
buffer: Buffer
The buffer being declared.

body: Stmt
The body statement to be executed.

span: Optional[Span]
The location of this DeclBuffer in the source code.
"""

def __init__(self, buffer, body, span=None):
self.__init_handle_by_constructor__(_ffi_api.DeclBuffer, buffer, body, span)


@tvm._ffi.register_object("tir.AttrStmt")
class AttrStmt(Stmt):
"""AttrStmt node.
Expand Down
1 change: 1 addition & 0 deletions src/printer/text_printer.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -353,6 +353,7 @@ class TIRTextPrinter : public StmtFunctor<Doc(const Stmt&)>,
Doc VisitStmt_(const ProducerRealizeNode* op) override;
Doc VisitStmt_(const AllocateNode* op) override;
Doc VisitStmt_(const AllocateConstNode* op) override;
Doc VisitStmt_(const DeclBufferNode* op) override;
Doc VisitStmt_(const IfThenElseNode* op) override;
Doc VisitStmt_(const SeqStmtNode* op) override;
Doc VisitStmt_(const EvaluateNode* op) override;
Expand Down
12 changes: 12 additions & 0 deletions src/printer/tir_text_printer.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -557,6 +557,18 @@ Doc TIRTextPrinter::VisitStmt_(const AllocateConstNode* op) {
return doc;
}

Doc TIRTextPrinter::VisitStmt_(const DeclBufferNode* op) {
Doc doc;
doc << AllocBuf(op->buffer) << " = decl_buffer(" << Print(op->buffer->data) << ", "
<< PrintDType(op->buffer->dtype) << ", " << Print(op->buffer->shape) << ")" << Doc::NewLine();
if (op->body->IsInstance<SeqStmtNode>()) {
doc << PrintBody(op->body);
} else {
doc << ";" << Doc::NewLine() << Print(op->body);
}
return doc;
}

Doc TIRTextPrinter::VisitStmt_(const IfThenElseNode* op) {
Doc doc;
doc << "if " << Print(op->condition) << PrintBody(op->then_case);
Expand Down
19 changes: 19 additions & 0 deletions src/printer/tvmscript_printer.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,6 +245,7 @@ class TVMScriptPrinter : public StmtFunctor<Doc(const Stmt&)>,
Doc VisitStmt_(const BufferRealizeNode* op) override;
Doc VisitStmt_(const AllocateNode* op) override;
Doc VisitStmt_(const AllocateConstNode* op) override;
Doc VisitStmt_(const DeclBufferNode* op) override;
Doc VisitStmt_(const IfThenElseNode* op) override;
Doc VisitStmt_(const SeqStmtNode* op) override;
Doc VisitStmt_(const ForNode* op) override;
Expand DownExpand Up@@ -1161,6 +1162,24 @@ Doc TVMScriptPrinter::VisitStmt_(const AllocateConstNode* alloc) {
return doc;
}

Doc TVMScriptPrinter::VisitStmt_(const DeclBufferNode* op) {
const Buffer& buffer = op->buffer;
buf_not_in_headers_.insert(buffer.get());
Doc buffer_name = Print(op->buffer);
Doc func_call;
func_call << tir_prefix_ << ".decl_buffer(" << memo_buf_decl_.at(buffer) << ")";

Doc doc;
if (current_num_ != num_child_ - 1) {
doc << "with " << func_call << " as " << buffer_name << ":";
doc << Doc::Indent(4, Doc::NewLine() << PrintBody(op->body));
} else {
doc << buffer_name << " = " << func_call << Doc::NewLine();
doc << PrintBody(op->body);
}
return doc;
}

Doc TVMScriptPrinter::VisitStmt_(const IfThenElseNode* op) {
Doc doc;
doc << "if " << Print(op->condition) << ":";
Expand Down
2 changes: 2 additions & 0 deletions src/target/source/codegen_c.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -661,6 +661,8 @@ void CodeGenC::VisitStmt_(const AllocateConstNode* op) {
this->PrintStmt(op->body);
}

void CodeGenC::VisitStmt_(const DeclBufferNode* op) { this->PrintStmt(op->body); }

void CodeGenC::VisitExpr_(const LoadNode* op, std::ostream& os) { // NOLINT(*)
LOG(FATAL) << "Unexpected deprecated LoadNode. Use BufferLoadNode instead.";
}
Expand Down
1 change: 1 addition & 0 deletions src/target/source/codegen_c.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -166,6 +166,7 @@ class CodeGenC : public ExprFunctor<void(const PrimExpr&, std::ostream&)>,
void VisitStmt_(const EvaluateNode* op) override;
void VisitStmt_(const SeqStmtNode* op) override;
void VisitStmt_(const AllocateConstNode* op) override;
void VisitStmt_(const DeclBufferNode* op) override;

/*!
* \brief Print expr representing the thread tag
Expand Down
23 changes: 23 additions & 0 deletions src/tir/ir/stmt.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -508,6 +508,29 @@ TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
p->Print(op->body);
});

// DeclBuffer
DeclBuffer::DeclBuffer(Buffer buffer, Stmt body, Span span) {
ObjectPtr<DeclBufferNode> node = make_object<DeclBufferNode>();
node->buffer = std::move(buffer);
node->body = std::move(body);
node->span = std::move(span);
data_ = std::move(node);
}

TVM_REGISTER_GLOBAL("tir.DeclBuffer").set_body_typed([](Buffer buffer, Stmt body, Span span) {
return DeclBuffer(buffer, body, span);
});

TVM_REGISTER_NODE_TYPE(DeclBufferNode);

TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
.set_dispatch<DeclBufferNode>([](const ObjectRef& node, ReprPrinter* p) {
auto* op = static_cast<const DeclBufferNode*>(node.get());
p->PrintIndent();
p->stream << "decl_buffer " << op->buffer << "\n";
p->stream << op->body;
});

// ProducerRealize
ProducerRealize::ProducerRealize(DataProducer producer, Region bounds, PrimExpr condition,
Stmt body, String storage_scope, Span span) {
Expand Down
14 changes: 14 additions & 0 deletions src/tir/ir/stmt_functor.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,6 +63,8 @@ void StmtVisitor::VisitStmt_(const AllocateConstNode* op) {
this->VisitStmt(op->body);
}

void StmtVisitor::VisitStmt_(const DeclBufferNode* op) { this->VisitStmt(op->body); }

void StmtVisitor::VisitStmt_(const StoreNode* op) {
LOG(FATAL) << "Unexpected use of deprecated StoreNode. Please use BufferStoreNode instead.";
}
Expand DownExpand Up@@ -336,6 +338,18 @@ Stmt StmtMutator::VisitStmt_(const AllocateConstNode* op) {
}
}

Stmt StmtMutator::VisitStmt_(const DeclBufferNode* op) {
Stmt body = this->VisitStmt(op->body);

if (body.same_as(op->body)) {
return GetRef<Stmt>(op);
} else {
auto n = CopyOnWrite(op);
n->body = std::move(body);
return Stmt(n);
}
}

Stmt StmtMutator::VisitStmt_(const IfThenElseNode* op) {
PrimExpr condition = this->VisitExpr(op->condition);
Stmt then_case = this->VisitStmt(op->then_case);
Expand Down
6 changes: 4 additions & 2 deletions tests/cpp/ir_functor_test.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -181,6 +181,7 @@ TEST(IRF, StmtVisitor) {
DataType dtype = DataType::Float(32);
Var buf_var("b", PointerType(PrimType(dtype)));
Buffer buffer = decl_buffer({16});
body = DeclBuffer(buffer, std::move(body));
BufferRegion buffer_region(buffer, {Range::FromMinExtent(x + 1, 1)});
MatchBufferRegion match_buffer_region(decl_buffer({1}), buffer_region);

Expand DownExpand Up@@ -309,6 +310,7 @@ TEST(IRF, StmtMutator) {
DataType dtype = DataType::Float(32);
Var buf_var("b", PointerType(PrimType(dtype)));
Buffer buffer = decl_buffer({16});
body = DeclBuffer(buffer, std::move(body));
BufferRegion buffer_region(buffer, {Range::FromMinExtent(x + 1, 1)});
MatchBufferRegion match_buffer_region(decl_buffer({1}), buffer_region);
// construct block and block_realize
Expand All@@ -318,8 +320,8 @@ TEST(IRF, StmtMutator) {
body = v(std::move(block_realize));
// the body should be changed
Block new_block = body.as<BlockRealizeNode>()->block;
ICHECK(new_block->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->init.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->body.as<DeclBufferNode>()->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->init.as<DeclBufferNode>()->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->reads[0]->region[0]->min.same_as(x));
ICHECK(new_block->writes[0]->region[0]->min.same_as(x));
ICHECK(new_block->match_buffers[0]->source->region[0]->min.same_as(x));
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [TIR] Add DeclBuffer IR node and functors by vinx13 · Pull Request #12300 · apache/tvm · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions include/tvm/tir/stmt.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -681,6 +681,40 @@ class AllocateConst : public Stmt {
TVM_DEFINE_OBJECT_REF_METHODS(AllocateConst, Stmt, AllocateConstNode);
};

/*! \brief Declare a buffer that can be used in the body */
class DeclBufferNode : public StmtNode {
public:
/*! \brief The buffer being declared */
Buffer buffer;
/*! \brief The body to be executed */
Stmt body;

void VisitAttrs(AttrVisitor* v) {
v->Visit("buffer", &buffer);
v->Visit("body", &body);
v->Visit("span", &span);
}

bool SEqualReduce(const DeclBufferNode* other, SEqualReducer equal) const {
return equal(buffer, other->buffer) && equal(body, other->body);
}

void SHashReduce(SHashReducer hash_reduce) const {
hash_reduce(buffer);
hash_reduce(body);
}

static constexpr const char* _type_key = "tir.DeclBuffer";
TVM_DECLARE_FINAL_OBJECT_INFO(DeclBufferNode, StmtNode);
};

/*! \brief Managed reference to DeclBufferNode */
class DeclBuffer : public Stmt {
public:
TVM_DLL DeclBuffer(Buffer buffer, Stmt body, Span span = Span());
TVM_DEFINE_OBJECT_REF_METHODS(DeclBuffer, Stmt, DeclBufferNode);
};

/*!
* \brief The container of seq statement.
* Represent a sequence of statements.
Expand Down
4 changes: 4 additions & 0 deletions include/tvm/tir/stmt_functor.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,6 +89,7 @@ class StmtFunctor<R(const Stmt& n, Args... args)> {
virtual R VisitStmt_(const WhileNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const AllocateNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const AllocateConstNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const DeclBufferNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const StoreNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const BufferStoreNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const BufferRealizeNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
Expand DownExpand Up@@ -116,6 +117,7 @@ class StmtFunctor<R(const Stmt& n, Args... args)> {
IR_STMT_FUNCTOR_DISPATCH(WhileNode);
IR_STMT_FUNCTOR_DISPATCH(AllocateNode);
IR_STMT_FUNCTOR_DISPATCH(AllocateConstNode);
IR_STMT_FUNCTOR_DISPATCH(DeclBufferNode);
IR_STMT_FUNCTOR_DISPATCH(StoreNode);
IR_STMT_FUNCTOR_DISPATCH(AssertStmtNode);
IR_STMT_FUNCTOR_DISPATCH(ProducerStoreNode);
Expand DownExpand Up@@ -159,6 +161,7 @@ class TVM_DLL StmtVisitor : protected StmtFunctor<void(const Stmt&)> {
void VisitStmt_(const WhileNode* op) override;
void VisitStmt_(const AllocateNode* op) override;
void VisitStmt_(const AllocateConstNode* op) override;
void VisitStmt_(const DeclBufferNode* op) override;
void VisitStmt_(const StoreNode* op) override;
void VisitStmt_(const BufferStoreNode* op) override;
void VisitStmt_(const BufferRealizeNode* op) override;
Expand DownExpand Up@@ -260,6 +263,7 @@ class TVM_DLL StmtMutator : protected StmtFunctor<Stmt(const Stmt&)> {
Stmt VisitStmt_(const WhileNode* op) override;
Stmt VisitStmt_(const AllocateNode* op) override;
Stmt VisitStmt_(const AllocateConstNode* op) override;
Stmt VisitStmt_(const DeclBufferNode* op) override;
Stmt VisitStmt_(const StoreNode* op) override;
Stmt VisitStmt_(const BufferStoreNode* op) override;
Stmt VisitStmt_(const BufferRealizeNode* op) override;
Expand Down
12 changes: 12 additions & 0 deletions python/tvm/script/tir/__init__.pyi
Original file line numberDiff line numberDiff line change
Expand Up@@ -187,6 +187,18 @@ def match_buffer(
buffer_type: str = "default",
axis_separators: Optional[List[int]] = None,
) -> Buffer: ...
def decl_buffer(
shape: Sequence[Union[PrimExpr, int]],
dtype: str = "float32",
data: Var = None,
strides: Optional[Sequence[int]] = None,
elem_offset: Optional[int] = None,
scope: str = "global",
align: int = -1,
offset_factor: int = 0,
buffer_type: str = "default",
axis_separators: Optional[List[int]] = None,
) -> Buffer: ...
def buffer_decl(
shape: Sequence[Union[PrimExpr, int]],
dtype: str = "float32",
Expand Down
81 changes: 81 additions & 0 deletions python/tvm/script/tir/scope_handler.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -224,6 +224,87 @@ def setup_buffer(data, dtype, shape, annotations: dict = None, span: Span = None
context.update_symbol(name, self.buffer, node)


@register
class DeclBuffer(WithScopeHandler):
"""Special Stmt decl_buffer(shape, dtype, data, strides, elem_offset, scope, align,
offset_factor, buffer_type, axis_separators)
Example
-------
.. code-block:: python
A = T.decl_buffer((128, 128), dtype="float32")
"""

def __init__(self):
def decl_buffer(
shape,
dtype="float32",
data=None,
strides=None,
elem_offset=None,
scope="global",
align=-1,
offset_factor=0,
buffer_type="default",
axis_separators=None,
span=None,
):
return tvm.tir.DeclBuffer(self.buffer, self.body, span=span)

super().__init__(decl_buffer, concise_scope=True, def_symbol=True)

def enter_scope(
self,
node: synr.ast.Node,
context: ContextMaintainer,
arg_list: List[Any],
span: synr.ast.Span,
):
# define buffer vars in symbol table
if isinstance(node, synr.ast.With):
vars = WithScopeHandler.get_optional_vars(node, context)
if len(vars) != 1:
context.report_error(f"Unexpected number of vars: 1 vs. {len(vars)}", node.span)
name = vars[0].id.name
var_span = vars[0].id.span
elif isinstance(node, synr.ast.Assign):
if len(node.lhs) != 1:
context.report_error(f"Unexpected number of vars: 1 vs. {len(node.lhs)}", node.span)
name = node.lhs[0].id.name
var_span = node.lhs[0].id.span
else:
raise Exception("Internal Bug")

def setup_buffer(
shape,
dtype,
data,
strides,
elem_offset,
scope,
align,
offset_factor,
buffer_type,
axis_separators,
span: Span = None,
):
self.buffer = tvm.tir.decl_buffer(
shape=shape,
dtype=dtype,
data=data,
strides=strides,
elem_offset=elem_offset,
scope=scope,
data_alignment=align,
offset_factor=offset_factor,
buffer_type=buffer_type,
axis_separators=axis_separators,
span=span,
)

setup_buffer(*arg_list, span=tvm_span_from_synr(var_span))
context.update_symbol(name, self.buffer, node)


@register
class LaunchThread(WithScopeHandler):
"""With scope handler T.launch_thread(env_var, extent)"""
Expand Down
1 change: 1 addition & 0 deletions python/tvm/tir/__init__.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,6 +36,7 @@
Allocate,
AllocateConst,
AttrStmt,
DeclBuffer,
)

from .stmt import ProducerRealize, SeqStmt
Expand Down
20 changes: 20 additions & 0 deletions python/tvm/tir/stmt.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -377,6 +377,26 @@ def __init__(self, buffer_var, dtype, extents, data_or_idx, body, annotations=No
)


@tvm._ffi.register_object("tir.DeclBuffer")
class DeclBuffer(Stmt):
"""DeclBuffer node.

Parameters
----------
buffer: Buffer
The buffer being declared.

body: Stmt
The body statement to be executed.

span: Optional[Span]
The location of this DeclBuffer in the source code.
"""

def __init__(self, buffer, body, span=None):
self.__init_handle_by_constructor__(_ffi_api.DeclBuffer, buffer, body, span)


@tvm._ffi.register_object("tir.AttrStmt")
class AttrStmt(Stmt):
"""AttrStmt node.
Expand Down
1 change: 1 addition & 0 deletions src/printer/text_printer.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -353,6 +353,7 @@ class TIRTextPrinter : public StmtFunctor<Doc(const Stmt&)>,
Doc VisitStmt_(const ProducerRealizeNode* op) override;
Doc VisitStmt_(const AllocateNode* op) override;
Doc VisitStmt_(const AllocateConstNode* op) override;
Doc VisitStmt_(const DeclBufferNode* op) override;
Doc VisitStmt_(const IfThenElseNode* op) override;
Doc VisitStmt_(const SeqStmtNode* op) override;
Doc VisitStmt_(const EvaluateNode* op) override;
Expand Down
12 changes: 12 additions & 0 deletions src/printer/tir_text_printer.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -557,6 +557,18 @@ Doc TIRTextPrinter::VisitStmt_(const AllocateConstNode* op) {
return doc;
}

Doc TIRTextPrinter::VisitStmt_(const DeclBufferNode* op) {
Doc doc;
doc << AllocBuf(op->buffer) << " = decl_buffer(" << Print(op->buffer->data) << ", "
<< PrintDType(op->buffer->dtype) << ", " << Print(op->buffer->shape) << ")" << Doc::NewLine();
if (op->body->IsInstance<SeqStmtNode>()) {
doc << PrintBody(op->body);
} else {
doc << ";" << Doc::NewLine() << Print(op->body);
}
return doc;
}

Doc TIRTextPrinter::VisitStmt_(const IfThenElseNode* op) {
Doc doc;
doc << "if " << Print(op->condition) << PrintBody(op->then_case);
Expand Down
19 changes: 19 additions & 0 deletions src/printer/tvmscript_printer.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,6 +245,7 @@ class TVMScriptPrinter : public StmtFunctor<Doc(const Stmt&)>,
Doc VisitStmt_(const BufferRealizeNode* op) override;
Doc VisitStmt_(const AllocateNode* op) override;
Doc VisitStmt_(const AllocateConstNode* op) override;
Doc VisitStmt_(const DeclBufferNode* op) override;
Doc VisitStmt_(const IfThenElseNode* op) override;
Doc VisitStmt_(const SeqStmtNode* op) override;
Doc VisitStmt_(const ForNode* op) override;
Expand DownExpand Up@@ -1161,6 +1162,24 @@ Doc TVMScriptPrinter::VisitStmt_(const AllocateConstNode* alloc) {
return doc;
}

Doc TVMScriptPrinter::VisitStmt_(const DeclBufferNode* op) {
const Buffer& buffer = op->buffer;
buf_not_in_headers_.insert(buffer.get());
Doc buffer_name = Print(op->buffer);
Doc func_call;
func_call << tir_prefix_ << ".decl_buffer(" << memo_buf_decl_.at(buffer) << ")";

Doc doc;
if (current_num_ != num_child_ - 1) {
doc << "with " << func_call << " as " << buffer_name << ":";
doc << Doc::Indent(4, Doc::NewLine() << PrintBody(op->body));
} else {
doc << buffer_name << " = " << func_call << Doc::NewLine();
doc << PrintBody(op->body);
}
return doc;
}

Doc TVMScriptPrinter::VisitStmt_(const IfThenElseNode* op) {
Doc doc;
doc << "if " << Print(op->condition) << ":";
Expand Down
2 changes: 2 additions & 0 deletions src/target/source/codegen_c.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -661,6 +661,8 @@ void CodeGenC::VisitStmt_(const AllocateConstNode* op) {
this->PrintStmt(op->body);
}

void CodeGenC::VisitStmt_(const DeclBufferNode* op) { this->PrintStmt(op->body); }

void CodeGenC::VisitExpr_(const LoadNode* op, std::ostream& os) { // NOLINT(*)
LOG(FATAL) << "Unexpected deprecated LoadNode. Use BufferLoadNode instead.";
}
Expand Down
1 change: 1 addition & 0 deletions src/target/source/codegen_c.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -166,6 +166,7 @@ class CodeGenC : public ExprFunctor<void(const PrimExpr&, std::ostream&)>,
void VisitStmt_(const EvaluateNode* op) override;
void VisitStmt_(const SeqStmtNode* op) override;
void VisitStmt_(const AllocateConstNode* op) override;
void VisitStmt_(const DeclBufferNode* op) override;

/*!
* \brief Print expr representing the thread tag
Expand Down
23 changes: 23 additions & 0 deletions src/tir/ir/stmt.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -508,6 +508,29 @@ TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
p->Print(op->body);
});

// DeclBuffer
DeclBuffer::DeclBuffer(Buffer buffer, Stmt body, Span span) {
ObjectPtr<DeclBufferNode> node = make_object<DeclBufferNode>();
node->buffer = std::move(buffer);
node->body = std::move(body);
node->span = std::move(span);
data_ = std::move(node);
}

TVM_REGISTER_GLOBAL("tir.DeclBuffer").set_body_typed([](Buffer buffer, Stmt body, Span span) {
return DeclBuffer(buffer, body, span);
});

TVM_REGISTER_NODE_TYPE(DeclBufferNode);

TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
.set_dispatch<DeclBufferNode>([](const ObjectRef& node, ReprPrinter* p) {
auto* op = static_cast<const DeclBufferNode*>(node.get());
p->PrintIndent();
p->stream << "decl_buffer " << op->buffer << "\n";
p->stream << op->body;
});

// ProducerRealize
ProducerRealize::ProducerRealize(DataProducer producer, Region bounds, PrimExpr condition,
Stmt body, String storage_scope, Span span) {
Expand Down
14 changes: 14 additions & 0 deletions src/tir/ir/stmt_functor.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,6 +63,8 @@ void StmtVisitor::VisitStmt_(const AllocateConstNode* op) {
this->VisitStmt(op->body);
}

void StmtVisitor::VisitStmt_(const DeclBufferNode* op) { this->VisitStmt(op->body); }

void StmtVisitor::VisitStmt_(const StoreNode* op) {
LOG(FATAL) << "Unexpected use of deprecated StoreNode. Please use BufferStoreNode instead.";
}
Expand DownExpand Up@@ -336,6 +338,18 @@ Stmt StmtMutator::VisitStmt_(const AllocateConstNode* op) {
}
}

Stmt StmtMutator::VisitStmt_(const DeclBufferNode* op) {
Stmt body = this->VisitStmt(op->body);

if (body.same_as(op->body)) {
return GetRef<Stmt>(op);
} else {
auto n = CopyOnWrite(op);
n->body = std::move(body);
return Stmt(n);
}
}

Stmt StmtMutator::VisitStmt_(const IfThenElseNode* op) {
PrimExpr condition = this->VisitExpr(op->condition);
Stmt then_case = this->VisitStmt(op->then_case);
Expand Down
6 changes: 4 additions & 2 deletions tests/cpp/ir_functor_test.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -181,6 +181,7 @@ TEST(IRF, StmtVisitor) {
DataType dtype = DataType::Float(32);
Var buf_var("b", PointerType(PrimType(dtype)));
Buffer buffer = decl_buffer({16});
body = DeclBuffer(buffer, std::move(body));
BufferRegion buffer_region(buffer, {Range::FromMinExtent(x + 1, 1)});
MatchBufferRegion match_buffer_region(decl_buffer({1}), buffer_region);

Expand DownExpand Up@@ -309,6 +310,7 @@ TEST(IRF, StmtMutator) {
DataType dtype = DataType::Float(32);
Var buf_var("b", PointerType(PrimType(dtype)));
Buffer buffer = decl_buffer({16});
body = DeclBuffer(buffer, std::move(body));
BufferRegion buffer_region(buffer, {Range::FromMinExtent(x + 1, 1)});
MatchBufferRegion match_buffer_region(decl_buffer({1}), buffer_region);
// construct block and block_realize
Expand All@@ -318,8 +320,8 @@ TEST(IRF, StmtMutator) {
body = v(std::move(block_realize));
// the body should be changed
Block new_block = body.as<BlockRealizeNode>()->block;
ICHECK(new_block->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->init.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->body.as<DeclBufferNode>()->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->init.as<DeclBufferNode>()->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->reads[0]->region[0]->min.same_as(x));
ICHECK(new_block->writes[0]->region[0]->min.same_as(x));
ICHECK(new_block->match_buffers[0]->source->region[0]->min.same_as(x));
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' [TIR] Add DeclBuffer IR node and functors by vinx13 · Pull Request #12300 · apache/tvm · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions include/tvm/tir/stmt.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -681,6 +681,40 @@ class AllocateConst : public Stmt {
TVM_DEFINE_OBJECT_REF_METHODS(AllocateConst, Stmt, AllocateConstNode);
};

/*! \brief Declare a buffer that can be used in the body */
class DeclBufferNode : public StmtNode {
public:
/*! \brief The buffer being declared */
Buffer buffer;
/*! \brief The body to be executed */
Stmt body;

void VisitAttrs(AttrVisitor* v) {
v->Visit("buffer", &buffer);
v->Visit("body", &body);
v->Visit("span", &span);
}

bool SEqualReduce(const DeclBufferNode* other, SEqualReducer equal) const {
return equal(buffer, other->buffer) && equal(body, other->body);
}

void SHashReduce(SHashReducer hash_reduce) const {
hash_reduce(buffer);
hash_reduce(body);
}

static constexpr const char* _type_key = "tir.DeclBuffer";
TVM_DECLARE_FINAL_OBJECT_INFO(DeclBufferNode, StmtNode);
};

/*! \brief Managed reference to DeclBufferNode */
class DeclBuffer : public Stmt {
public:
TVM_DLL DeclBuffer(Buffer buffer, Stmt body, Span span = Span());
TVM_DEFINE_OBJECT_REF_METHODS(DeclBuffer, Stmt, DeclBufferNode);
};

/*!
* \brief The container of seq statement.
* Represent a sequence of statements.
Expand Down
4 changes: 4 additions & 0 deletions include/tvm/tir/stmt_functor.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,6 +89,7 @@ class StmtFunctor<R(const Stmt& n, Args... args)> {
virtual R VisitStmt_(const WhileNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const AllocateNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const AllocateConstNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const DeclBufferNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const StoreNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const BufferStoreNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const BufferRealizeNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
Expand DownExpand Up@@ -116,6 +117,7 @@ class StmtFunctor<R(const Stmt& n, Args... args)> {
IR_STMT_FUNCTOR_DISPATCH(WhileNode);
IR_STMT_FUNCTOR_DISPATCH(AllocateNode);
IR_STMT_FUNCTOR_DISPATCH(AllocateConstNode);
IR_STMT_FUNCTOR_DISPATCH(DeclBufferNode);
IR_STMT_FUNCTOR_DISPATCH(StoreNode);
IR_STMT_FUNCTOR_DISPATCH(AssertStmtNode);
IR_STMT_FUNCTOR_DISPATCH(ProducerStoreNode);
Expand DownExpand Up@@ -159,6 +161,7 @@ class TVM_DLL StmtVisitor : protected StmtFunctor<void(const Stmt&)> {
void VisitStmt_(const WhileNode* op) override;
void VisitStmt_(const AllocateNode* op) override;
void VisitStmt_(const AllocateConstNode* op) override;
void VisitStmt_(const DeclBufferNode* op) override;
void VisitStmt_(const StoreNode* op) override;
void VisitStmt_(const BufferStoreNode* op) override;
void VisitStmt_(const BufferRealizeNode* op) override;
Expand DownExpand Up@@ -260,6 +263,7 @@ class TVM_DLL StmtMutator : protected StmtFunctor<Stmt(const Stmt&)> {
Stmt VisitStmt_(const WhileNode* op) override;
Stmt VisitStmt_(const AllocateNode* op) override;
Stmt VisitStmt_(const AllocateConstNode* op) override;
Stmt VisitStmt_(const DeclBufferNode* op) override;
Stmt VisitStmt_(const StoreNode* op) override;
Stmt VisitStmt_(const BufferStoreNode* op) override;
Stmt VisitStmt_(const BufferRealizeNode* op) override;
Expand Down
12 changes: 12 additions & 0 deletions python/tvm/script/tir/__init__.pyi
Original file line numberDiff line numberDiff line change
Expand Up@@ -187,6 +187,18 @@ def match_buffer(
buffer_type: str = "default",
axis_separators: Optional[List[int]] = None,
) -> Buffer: ...
def decl_buffer(
shape: Sequence[Union[PrimExpr, int]],
dtype: str = "float32",
data: Var = None,
strides: Optional[Sequence[int]] = None,
elem_offset: Optional[int] = None,
scope: str = "global",
align: int = -1,
offset_factor: int = 0,
buffer_type: str = "default",
axis_separators: Optional[List[int]] = None,
) -> Buffer: ...
def buffer_decl(
shape: Sequence[Union[PrimExpr, int]],
dtype: str = "float32",
Expand Down
81 changes: 81 additions & 0 deletions python/tvm/script/tir/scope_handler.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -224,6 +224,87 @@ def setup_buffer(data, dtype, shape, annotations: dict = None, span: Span = None
context.update_symbol(name, self.buffer, node)


@register
class DeclBuffer(WithScopeHandler):
"""Special Stmt decl_buffer(shape, dtype, data, strides, elem_offset, scope, align,
offset_factor, buffer_type, axis_separators)
Example
-------
.. code-block:: python
A = T.decl_buffer((128, 128), dtype="float32")
"""

def __init__(self):
def decl_buffer(
shape,
dtype="float32",
data=None,
strides=None,
elem_offset=None,
scope="global",
align=-1,
offset_factor=0,
buffer_type="default",
axis_separators=None,
span=None,
):
return tvm.tir.DeclBuffer(self.buffer, self.body, span=span)

super().__init__(decl_buffer, concise_scope=True, def_symbol=True)

def enter_scope(
self,
node: synr.ast.Node,
context: ContextMaintainer,
arg_list: List[Any],
span: synr.ast.Span,
):
# define buffer vars in symbol table
if isinstance(node, synr.ast.With):
vars = WithScopeHandler.get_optional_vars(node, context)
if len(vars) != 1:
context.report_error(f"Unexpected number of vars: 1 vs. {len(vars)}", node.span)
name = vars[0].id.name
var_span = vars[0].id.span
elif isinstance(node, synr.ast.Assign):
if len(node.lhs) != 1:
context.report_error(f"Unexpected number of vars: 1 vs. {len(node.lhs)}", node.span)
name = node.lhs[0].id.name
var_span = node.lhs[0].id.span
else:
raise Exception("Internal Bug")

def setup_buffer(
shape,
dtype,
data,
strides,
elem_offset,
scope,
align,
offset_factor,
buffer_type,
axis_separators,
span: Span = None,
):
self.buffer = tvm.tir.decl_buffer(
shape=shape,
dtype=dtype,
data=data,
strides=strides,
elem_offset=elem_offset,
scope=scope,
data_alignment=align,
offset_factor=offset_factor,
buffer_type=buffer_type,
axis_separators=axis_separators,
span=span,
)

setup_buffer(*arg_list, span=tvm_span_from_synr(var_span))
context.update_symbol(name, self.buffer, node)


@register
class LaunchThread(WithScopeHandler):
"""With scope handler T.launch_thread(env_var, extent)"""
Expand Down
1 change: 1 addition & 0 deletions python/tvm/tir/__init__.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,6 +36,7 @@
Allocate,
AllocateConst,
AttrStmt,
DeclBuffer,
)

from .stmt import ProducerRealize, SeqStmt
Expand Down
20 changes: 20 additions & 0 deletions python/tvm/tir/stmt.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -377,6 +377,26 @@ def __init__(self, buffer_var, dtype, extents, data_or_idx, body, annotations=No
)


@tvm._ffi.register_object("tir.DeclBuffer")
class DeclBuffer(Stmt):
"""DeclBuffer node.

Parameters
----------
buffer: Buffer
The buffer being declared.

body: Stmt
The body statement to be executed.

span: Optional[Span]
The location of this DeclBuffer in the source code.
"""

def __init__(self, buffer, body, span=None):
self.__init_handle_by_constructor__(_ffi_api.DeclBuffer, buffer, body, span)


@tvm._ffi.register_object("tir.AttrStmt")
class AttrStmt(Stmt):
"""AttrStmt node.
Expand Down
1 change: 1 addition & 0 deletions src/printer/text_printer.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -353,6 +353,7 @@ class TIRTextPrinter : public StmtFunctor<Doc(const Stmt&)>,
Doc VisitStmt_(const ProducerRealizeNode* op) override;
Doc VisitStmt_(const AllocateNode* op) override;
Doc VisitStmt_(const AllocateConstNode* op) override;
Doc VisitStmt_(const DeclBufferNode* op) override;
Doc VisitStmt_(const IfThenElseNode* op) override;
Doc VisitStmt_(const SeqStmtNode* op) override;
Doc VisitStmt_(const EvaluateNode* op) override;
Expand Down
12 changes: 12 additions & 0 deletions src/printer/tir_text_printer.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -557,6 +557,18 @@ Doc TIRTextPrinter::VisitStmt_(const AllocateConstNode* op) {
return doc;
}

Doc TIRTextPrinter::VisitStmt_(const DeclBufferNode* op) {
Doc doc;
doc << AllocBuf(op->buffer) << " = decl_buffer(" << Print(op->buffer->data) << ", "
<< PrintDType(op->buffer->dtype) << ", " << Print(op->buffer->shape) << ")" << Doc::NewLine();
if (op->body->IsInstance<SeqStmtNode>()) {
doc << PrintBody(op->body);
} else {
doc << ";" << Doc::NewLine() << Print(op->body);
}
return doc;
}

Doc TIRTextPrinter::VisitStmt_(const IfThenElseNode* op) {
Doc doc;
doc << "if " << Print(op->condition) << PrintBody(op->then_case);
Expand Down
19 changes: 19 additions & 0 deletions src/printer/tvmscript_printer.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,6 +245,7 @@ class TVMScriptPrinter : public StmtFunctor<Doc(const Stmt&)>,
Doc VisitStmt_(const BufferRealizeNode* op) override;
Doc VisitStmt_(const AllocateNode* op) override;
Doc VisitStmt_(const AllocateConstNode* op) override;
Doc VisitStmt_(const DeclBufferNode* op) override;
Doc VisitStmt_(const IfThenElseNode* op) override;
Doc VisitStmt_(const SeqStmtNode* op) override;
Doc VisitStmt_(const ForNode* op) override;
Expand DownExpand Up@@ -1161,6 +1162,24 @@ Doc TVMScriptPrinter::VisitStmt_(const AllocateConstNode* alloc) {
return doc;
}

Doc TVMScriptPrinter::VisitStmt_(const DeclBufferNode* op) {
const Buffer& buffer = op->buffer;
buf_not_in_headers_.insert(buffer.get());
Doc buffer_name = Print(op->buffer);
Doc func_call;
func_call << tir_prefix_ << ".decl_buffer(" << memo_buf_decl_.at(buffer) << ")";

Doc doc;
if (current_num_ != num_child_ - 1) {
doc << "with " << func_call << " as " << buffer_name << ":";
doc << Doc::Indent(4, Doc::NewLine() << PrintBody(op->body));
} else {
doc << buffer_name << " = " << func_call << Doc::NewLine();
doc << PrintBody(op->body);
}
return doc;
}

Doc TVMScriptPrinter::VisitStmt_(const IfThenElseNode* op) {
Doc doc;
doc << "if " << Print(op->condition) << ":";
Expand Down
2 changes: 2 additions & 0 deletions src/target/source/codegen_c.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -661,6 +661,8 @@ void CodeGenC::VisitStmt_(const AllocateConstNode* op) {
this->PrintStmt(op->body);
}

void CodeGenC::VisitStmt_(const DeclBufferNode* op) { this->PrintStmt(op->body); }

void CodeGenC::VisitExpr_(const LoadNode* op, std::ostream& os) { // NOLINT(*)
LOG(FATAL) << "Unexpected deprecated LoadNode. Use BufferLoadNode instead.";
}
Expand Down
1 change: 1 addition & 0 deletions src/target/source/codegen_c.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -166,6 +166,7 @@ class CodeGenC : public ExprFunctor<void(const PrimExpr&, std::ostream&)>,
void VisitStmt_(const EvaluateNode* op) override;
void VisitStmt_(const SeqStmtNode* op) override;
void VisitStmt_(const AllocateConstNode* op) override;
void VisitStmt_(const DeclBufferNode* op) override;

/*!
* \brief Print expr representing the thread tag
Expand Down
23 changes: 23 additions & 0 deletions src/tir/ir/stmt.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -508,6 +508,29 @@ TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
p->Print(op->body);
});

// DeclBuffer
DeclBuffer::DeclBuffer(Buffer buffer, Stmt body, Span span) {
ObjectPtr<DeclBufferNode> node = make_object<DeclBufferNode>();
node->buffer = std::move(buffer);
node->body = std::move(body);
node->span = std::move(span);
data_ = std::move(node);
}

TVM_REGISTER_GLOBAL("tir.DeclBuffer").set_body_typed([](Buffer buffer, Stmt body, Span span) {
return DeclBuffer(buffer, body, span);
});

TVM_REGISTER_NODE_TYPE(DeclBufferNode);

TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
.set_dispatch<DeclBufferNode>([](const ObjectRef& node, ReprPrinter* p) {
auto* op = static_cast<const DeclBufferNode*>(node.get());
p->PrintIndent();
p->stream << "decl_buffer " << op->buffer << "\n";
p->stream << op->body;
});

// ProducerRealize
ProducerRealize::ProducerRealize(DataProducer producer, Region bounds, PrimExpr condition,
Stmt body, String storage_scope, Span span) {
Expand Down
14 changes: 14 additions & 0 deletions src/tir/ir/stmt_functor.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,6 +63,8 @@ void StmtVisitor::VisitStmt_(const AllocateConstNode* op) {
this->VisitStmt(op->body);
}

void StmtVisitor::VisitStmt_(const DeclBufferNode* op) { this->VisitStmt(op->body); }

void StmtVisitor::VisitStmt_(const StoreNode* op) {
LOG(FATAL) << "Unexpected use of deprecated StoreNode. Please use BufferStoreNode instead.";
}
Expand DownExpand Up@@ -336,6 +338,18 @@ Stmt StmtMutator::VisitStmt_(const AllocateConstNode* op) {
}
}

Stmt StmtMutator::VisitStmt_(const DeclBufferNode* op) {
Stmt body = this->VisitStmt(op->body);

if (body.same_as(op->body)) {
return GetRef<Stmt>(op);
} else {
auto n = CopyOnWrite(op);
n->body = std::move(body);
return Stmt(n);
}
}

Stmt StmtMutator::VisitStmt_(const IfThenElseNode* op) {
PrimExpr condition = this->VisitExpr(op->condition);
Stmt then_case = this->VisitStmt(op->then_case);
Expand Down
6 changes: 4 additions & 2 deletions tests/cpp/ir_functor_test.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -181,6 +181,7 @@ TEST(IRF, StmtVisitor) {
DataType dtype = DataType::Float(32);
Var buf_var("b", PointerType(PrimType(dtype)));
Buffer buffer = decl_buffer({16});
body = DeclBuffer(buffer, std::move(body));
BufferRegion buffer_region(buffer, {Range::FromMinExtent(x + 1, 1)});
MatchBufferRegion match_buffer_region(decl_buffer({1}), buffer_region);

Expand DownExpand Up@@ -309,6 +310,7 @@ TEST(IRF, StmtMutator) {
DataType dtype = DataType::Float(32);
Var buf_var("b", PointerType(PrimType(dtype)));
Buffer buffer = decl_buffer({16});
body = DeclBuffer(buffer, std::move(body));
BufferRegion buffer_region(buffer, {Range::FromMinExtent(x + 1, 1)});
MatchBufferRegion match_buffer_region(decl_buffer({1}), buffer_region);
// construct block and block_realize
Expand All@@ -318,8 +320,8 @@ TEST(IRF, StmtMutator) {
body = v(std::move(block_realize));
// the body should be changed
Block new_block = body.as<BlockRealizeNode>()->block;
ICHECK(new_block->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->init.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->body.as<DeclBufferNode>()->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->init.as<DeclBufferNode>()->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->reads[0]->region[0]->min.same_as(x));
ICHECK(new_block->writes[0]->region[0]->min.same_as(x));
ICHECK(new_block->match_buffers[0]->source->region[0]->min.same_as(x));
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [TIR] Add DeclBuffer IR node and functors by vinx13 · Pull Request #12300 · apache/tvm · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions include/tvm/tir/stmt.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -681,6 +681,40 @@ class AllocateConst : public Stmt {
TVM_DEFINE_OBJECT_REF_METHODS(AllocateConst, Stmt, AllocateConstNode);
};

/*! \brief Declare a buffer that can be used in the body */
class DeclBufferNode : public StmtNode {
public:
/*! \brief The buffer being declared */
Buffer buffer;
/*! \brief The body to be executed */
Stmt body;

void VisitAttrs(AttrVisitor* v) {
v->Visit("buffer", &buffer);
v->Visit("body", &body);
v->Visit("span", &span);
}

bool SEqualReduce(const DeclBufferNode* other, SEqualReducer equal) const {
return equal(buffer, other->buffer) && equal(body, other->body);
}

void SHashReduce(SHashReducer hash_reduce) const {
hash_reduce(buffer);
hash_reduce(body);
}

static constexpr const char* _type_key = "tir.DeclBuffer";
TVM_DECLARE_FINAL_OBJECT_INFO(DeclBufferNode, StmtNode);
};

/*! \brief Managed reference to DeclBufferNode */
class DeclBuffer : public Stmt {
public:
TVM_DLL DeclBuffer(Buffer buffer, Stmt body, Span span = Span());
TVM_DEFINE_OBJECT_REF_METHODS(DeclBuffer, Stmt, DeclBufferNode);
};

/*!
* \brief The container of seq statement.
* Represent a sequence of statements.
Expand Down
4 changes: 4 additions & 0 deletions include/tvm/tir/stmt_functor.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,6 +89,7 @@ class StmtFunctor<R(const Stmt& n, Args... args)> {
virtual R VisitStmt_(const WhileNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const AllocateNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const AllocateConstNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const DeclBufferNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const StoreNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const BufferStoreNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const BufferRealizeNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
Expand DownExpand Up@@ -116,6 +117,7 @@ class StmtFunctor<R(const Stmt& n, Args... args)> {
IR_STMT_FUNCTOR_DISPATCH(WhileNode);
IR_STMT_FUNCTOR_DISPATCH(AllocateNode);
IR_STMT_FUNCTOR_DISPATCH(AllocateConstNode);
IR_STMT_FUNCTOR_DISPATCH(DeclBufferNode);
IR_STMT_FUNCTOR_DISPATCH(StoreNode);
IR_STMT_FUNCTOR_DISPATCH(AssertStmtNode);
IR_STMT_FUNCTOR_DISPATCH(ProducerStoreNode);
Expand DownExpand Up@@ -159,6 +161,7 @@ class TVM_DLL StmtVisitor : protected StmtFunctor<void(const Stmt&)> {
void VisitStmt_(const WhileNode* op) override;
void VisitStmt_(const AllocateNode* op) override;
void VisitStmt_(const AllocateConstNode* op) override;
void VisitStmt_(const DeclBufferNode* op) override;
void VisitStmt_(const StoreNode* op) override;
void VisitStmt_(const BufferStoreNode* op) override;
void VisitStmt_(const BufferRealizeNode* op) override;
Expand DownExpand Up@@ -260,6 +263,7 @@ class TVM_DLL StmtMutator : protected StmtFunctor<Stmt(const Stmt&)> {
Stmt VisitStmt_(const WhileNode* op) override;
Stmt VisitStmt_(const AllocateNode* op) override;
Stmt VisitStmt_(const AllocateConstNode* op) override;
Stmt VisitStmt_(const DeclBufferNode* op) override;
Stmt VisitStmt_(const StoreNode* op) override;
Stmt VisitStmt_(const BufferStoreNode* op) override;
Stmt VisitStmt_(const BufferRealizeNode* op) override;
Expand Down
12 changes: 12 additions & 0 deletions python/tvm/script/tir/__init__.pyi
Original file line numberDiff line numberDiff line change
Expand Up@@ -187,6 +187,18 @@ def match_buffer(
buffer_type: str = "default",
axis_separators: Optional[List[int]] = None,
) -> Buffer: ...
def decl_buffer(
shape: Sequence[Union[PrimExpr, int]],
dtype: str = "float32",
data: Var = None,
strides: Optional[Sequence[int]] = None,
elem_offset: Optional[int] = None,
scope: str = "global",
align: int = -1,
offset_factor: int = 0,
buffer_type: str = "default",
axis_separators: Optional[List[int]] = None,
) -> Buffer: ...
def buffer_decl(
shape: Sequence[Union[PrimExpr, int]],
dtype: str = "float32",
Expand Down
81 changes: 81 additions & 0 deletions python/tvm/script/tir/scope_handler.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -224,6 +224,87 @@ def setup_buffer(data, dtype, shape, annotations: dict = None, span: Span = None
context.update_symbol(name, self.buffer, node)


@register
class DeclBuffer(WithScopeHandler):
"""Special Stmt decl_buffer(shape, dtype, data, strides, elem_offset, scope, align,
offset_factor, buffer_type, axis_separators)
Example
-------
.. code-block:: python
A = T.decl_buffer((128, 128), dtype="float32")
"""

def __init__(self):
def decl_buffer(
shape,
dtype="float32",
data=None,
strides=None,
elem_offset=None,
scope="global",
align=-1,
offset_factor=0,
buffer_type="default",
axis_separators=None,
span=None,
):
return tvm.tir.DeclBuffer(self.buffer, self.body, span=span)

super().__init__(decl_buffer, concise_scope=True, def_symbol=True)

def enter_scope(
self,
node: synr.ast.Node,
context: ContextMaintainer,
arg_list: List[Any],
span: synr.ast.Span,
):
# define buffer vars in symbol table
if isinstance(node, synr.ast.With):
vars = WithScopeHandler.get_optional_vars(node, context)
if len(vars) != 1:
context.report_error(f"Unexpected number of vars: 1 vs. {len(vars)}", node.span)
name = vars[0].id.name
var_span = vars[0].id.span
elif isinstance(node, synr.ast.Assign):
if len(node.lhs) != 1:
context.report_error(f"Unexpected number of vars: 1 vs. {len(node.lhs)}", node.span)
name = node.lhs[0].id.name
var_span = node.lhs[0].id.span
else:
raise Exception("Internal Bug")

def setup_buffer(
shape,
dtype,
data,
strides,
elem_offset,
scope,
align,
offset_factor,
buffer_type,
axis_separators,
span: Span = None,
):
self.buffer = tvm.tir.decl_buffer(
shape=shape,
dtype=dtype,
data=data,
strides=strides,
elem_offset=elem_offset,
scope=scope,
data_alignment=align,
offset_factor=offset_factor,
buffer_type=buffer_type,
axis_separators=axis_separators,
span=span,
)

setup_buffer(*arg_list, span=tvm_span_from_synr(var_span))
context.update_symbol(name, self.buffer, node)


@register
class LaunchThread(WithScopeHandler):
"""With scope handler T.launch_thread(env_var, extent)"""
Expand Down
1 change: 1 addition & 0 deletions python/tvm/tir/__init__.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,6 +36,7 @@
Allocate,
AllocateConst,
AttrStmt,
DeclBuffer,
)

from .stmt import ProducerRealize, SeqStmt
Expand Down
20 changes: 20 additions & 0 deletions python/tvm/tir/stmt.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -377,6 +377,26 @@ def __init__(self, buffer_var, dtype, extents, data_or_idx, body, annotations=No
)


@tvm._ffi.register_object("tir.DeclBuffer")
class DeclBuffer(Stmt):
"""DeclBuffer node.

Parameters
----------
buffer: Buffer
The buffer being declared.

body: Stmt
The body statement to be executed.

span: Optional[Span]
The location of this DeclBuffer in the source code.
"""

def __init__(self, buffer, body, span=None):
self.__init_handle_by_constructor__(_ffi_api.DeclBuffer, buffer, body, span)


@tvm._ffi.register_object("tir.AttrStmt")
class AttrStmt(Stmt):
"""AttrStmt node.
Expand Down
1 change: 1 addition & 0 deletions src/printer/text_printer.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -353,6 +353,7 @@ class TIRTextPrinter : public StmtFunctor<Doc(const Stmt&)>,
Doc VisitStmt_(const ProducerRealizeNode* op) override;
Doc VisitStmt_(const AllocateNode* op) override;
Doc VisitStmt_(const AllocateConstNode* op) override;
Doc VisitStmt_(const DeclBufferNode* op) override;
Doc VisitStmt_(const IfThenElseNode* op) override;
Doc VisitStmt_(const SeqStmtNode* op) override;
Doc VisitStmt_(const EvaluateNode* op) override;
Expand Down
12 changes: 12 additions & 0 deletions src/printer/tir_text_printer.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -557,6 +557,18 @@ Doc TIRTextPrinter::VisitStmt_(const AllocateConstNode* op) {
return doc;
}

Doc TIRTextPrinter::VisitStmt_(const DeclBufferNode* op) {
Doc doc;
doc << AllocBuf(op->buffer) << " = decl_buffer(" << Print(op->buffer->data) << ", "
<< PrintDType(op->buffer->dtype) << ", " << Print(op->buffer->shape) << ")" << Doc::NewLine();
if (op->body->IsInstance<SeqStmtNode>()) {
doc << PrintBody(op->body);
} else {
doc << ";" << Doc::NewLine() << Print(op->body);
}
return doc;
}

Doc TIRTextPrinter::VisitStmt_(const IfThenElseNode* op) {
Doc doc;
doc << "if " << Print(op->condition) << PrintBody(op->then_case);
Expand Down
19 changes: 19 additions & 0 deletions src/printer/tvmscript_printer.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,6 +245,7 @@ class TVMScriptPrinter : public StmtFunctor<Doc(const Stmt&)>,
Doc VisitStmt_(const BufferRealizeNode* op) override;
Doc VisitStmt_(const AllocateNode* op) override;
Doc VisitStmt_(const AllocateConstNode* op) override;
Doc VisitStmt_(const DeclBufferNode* op) override;
Doc VisitStmt_(const IfThenElseNode* op) override;
Doc VisitStmt_(const SeqStmtNode* op) override;
Doc VisitStmt_(const ForNode* op) override;
Expand DownExpand Up@@ -1161,6 +1162,24 @@ Doc TVMScriptPrinter::VisitStmt_(const AllocateConstNode* alloc) {
return doc;
}

Doc TVMScriptPrinter::VisitStmt_(const DeclBufferNode* op) {
const Buffer& buffer = op->buffer;
buf_not_in_headers_.insert(buffer.get());
Doc buffer_name = Print(op->buffer);
Doc func_call;
func_call << tir_prefix_ << ".decl_buffer(" << memo_buf_decl_.at(buffer) << ")";

Doc doc;
if (current_num_ != num_child_ - 1) {
doc << "with " << func_call << " as " << buffer_name << ":";
doc << Doc::Indent(4, Doc::NewLine() << PrintBody(op->body));
} else {
doc << buffer_name << " = " << func_call << Doc::NewLine();
doc << PrintBody(op->body);
}
return doc;
}

Doc TVMScriptPrinter::VisitStmt_(const IfThenElseNode* op) {
Doc doc;
doc << "if " << Print(op->condition) << ":";
Expand Down
2 changes: 2 additions & 0 deletions src/target/source/codegen_c.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -661,6 +661,8 @@ void CodeGenC::VisitStmt_(const AllocateConstNode* op) {
this->PrintStmt(op->body);
}

void CodeGenC::VisitStmt_(const DeclBufferNode* op) { this->PrintStmt(op->body); }

void CodeGenC::VisitExpr_(const LoadNode* op, std::ostream& os) { // NOLINT(*)
LOG(FATAL) << "Unexpected deprecated LoadNode. Use BufferLoadNode instead.";
}
Expand Down
1 change: 1 addition & 0 deletions src/target/source/codegen_c.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -166,6 +166,7 @@ class CodeGenC : public ExprFunctor<void(const PrimExpr&, std::ostream&)>,
void VisitStmt_(const EvaluateNode* op) override;
void VisitStmt_(const SeqStmtNode* op) override;
void VisitStmt_(const AllocateConstNode* op) override;
void VisitStmt_(const DeclBufferNode* op) override;

/*!
* \brief Print expr representing the thread tag
Expand Down
23 changes: 23 additions & 0 deletions src/tir/ir/stmt.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -508,6 +508,29 @@ TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
p->Print(op->body);
});

// DeclBuffer
DeclBuffer::DeclBuffer(Buffer buffer, Stmt body, Span span) {
ObjectPtr<DeclBufferNode> node = make_object<DeclBufferNode>();
node->buffer = std::move(buffer);
node->body = std::move(body);
node->span = std::move(span);
data_ = std::move(node);
}

TVM_REGISTER_GLOBAL("tir.DeclBuffer").set_body_typed([](Buffer buffer, Stmt body, Span span) {
return DeclBuffer(buffer, body, span);
});

TVM_REGISTER_NODE_TYPE(DeclBufferNode);

TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
.set_dispatch<DeclBufferNode>([](const ObjectRef& node, ReprPrinter* p) {
auto* op = static_cast<const DeclBufferNode*>(node.get());
p->PrintIndent();
p->stream << "decl_buffer " << op->buffer << "\n";
p->stream << op->body;
});

// ProducerRealize
ProducerRealize::ProducerRealize(DataProducer producer, Region bounds, PrimExpr condition,
Stmt body, String storage_scope, Span span) {
Expand Down
14 changes: 14 additions & 0 deletions src/tir/ir/stmt_functor.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,6 +63,8 @@ void StmtVisitor::VisitStmt_(const AllocateConstNode* op) {
this->VisitStmt(op->body);
}

void StmtVisitor::VisitStmt_(const DeclBufferNode* op) { this->VisitStmt(op->body); }

void StmtVisitor::VisitStmt_(const StoreNode* op) {
LOG(FATAL) << "Unexpected use of deprecated StoreNode. Please use BufferStoreNode instead.";
}
Expand DownExpand Up@@ -336,6 +338,18 @@ Stmt StmtMutator::VisitStmt_(const AllocateConstNode* op) {
}
}

Stmt StmtMutator::VisitStmt_(const DeclBufferNode* op) {
Stmt body = this->VisitStmt(op->body);

if (body.same_as(op->body)) {
return GetRef<Stmt>(op);
} else {
auto n = CopyOnWrite(op);
n->body = std::move(body);
return Stmt(n);
}
}

Stmt StmtMutator::VisitStmt_(const IfThenElseNode* op) {
PrimExpr condition = this->VisitExpr(op->condition);
Stmt then_case = this->VisitStmt(op->then_case);
Expand Down
6 changes: 4 additions & 2 deletions tests/cpp/ir_functor_test.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -181,6 +181,7 @@ TEST(IRF, StmtVisitor) {
DataType dtype = DataType::Float(32);
Var buf_var("b", PointerType(PrimType(dtype)));
Buffer buffer = decl_buffer({16});
body = DeclBuffer(buffer, std::move(body));
BufferRegion buffer_region(buffer, {Range::FromMinExtent(x + 1, 1)});
MatchBufferRegion match_buffer_region(decl_buffer({1}), buffer_region);

Expand DownExpand Up@@ -309,6 +310,7 @@ TEST(IRF, StmtMutator) {
DataType dtype = DataType::Float(32);
Var buf_var("b", PointerType(PrimType(dtype)));
Buffer buffer = decl_buffer({16});
body = DeclBuffer(buffer, std::move(body));
BufferRegion buffer_region(buffer, {Range::FromMinExtent(x + 1, 1)});
MatchBufferRegion match_buffer_region(decl_buffer({1}), buffer_region);
// construct block and block_realize
Expand All@@ -318,8 +320,8 @@ TEST(IRF, StmtMutator) {
body = v(std::move(block_realize));
// the body should be changed
Block new_block = body.as<BlockRealizeNode>()->block;
ICHECK(new_block->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->init.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->body.as<DeclBufferNode>()->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->init.as<DeclBufferNode>()->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->reads[0]->region[0]->min.same_as(x));
ICHECK(new_block->writes[0]->region[0]->min.same_as(x));
ICHECK(new_block->match_buffers[0]->source->region[0]->min.same_as(x));
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' [TIR] Add DeclBuffer IR node and functors by vinx13 · Pull Request #12300 · apache/tvm · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions include/tvm/tir/stmt.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -681,6 +681,40 @@ class AllocateConst : public Stmt {
TVM_DEFINE_OBJECT_REF_METHODS(AllocateConst, Stmt, AllocateConstNode);
};

/*! \brief Declare a buffer that can be used in the body */
class DeclBufferNode : public StmtNode {
public:
/*! \brief The buffer being declared */
Buffer buffer;
/*! \brief The body to be executed */
Stmt body;

void VisitAttrs(AttrVisitor* v) {
v->Visit("buffer", &buffer);
v->Visit("body", &body);
v->Visit("span", &span);
}

bool SEqualReduce(const DeclBufferNode* other, SEqualReducer equal) const {
return equal(buffer, other->buffer) && equal(body, other->body);
}

void SHashReduce(SHashReducer hash_reduce) const {
hash_reduce(buffer);
hash_reduce(body);
}

static constexpr const char* _type_key = "tir.DeclBuffer";
TVM_DECLARE_FINAL_OBJECT_INFO(DeclBufferNode, StmtNode);
};

/*! \brief Managed reference to DeclBufferNode */
class DeclBuffer : public Stmt {
public:
TVM_DLL DeclBuffer(Buffer buffer, Stmt body, Span span = Span());
TVM_DEFINE_OBJECT_REF_METHODS(DeclBuffer, Stmt, DeclBufferNode);
};

/*!
* \brief The container of seq statement.
* Represent a sequence of statements.
Expand Down
4 changes: 4 additions & 0 deletions include/tvm/tir/stmt_functor.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,6 +89,7 @@ class StmtFunctor<R(const Stmt& n, Args... args)> {
virtual R VisitStmt_(const WhileNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const AllocateNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const AllocateConstNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const DeclBufferNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const StoreNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const BufferStoreNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const BufferRealizeNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
Expand DownExpand Up@@ -116,6 +117,7 @@ class StmtFunctor<R(const Stmt& n, Args... args)> {
IR_STMT_FUNCTOR_DISPATCH(WhileNode);
IR_STMT_FUNCTOR_DISPATCH(AllocateNode);
IR_STMT_FUNCTOR_DISPATCH(AllocateConstNode);
IR_STMT_FUNCTOR_DISPATCH(DeclBufferNode);
IR_STMT_FUNCTOR_DISPATCH(StoreNode);
IR_STMT_FUNCTOR_DISPATCH(AssertStmtNode);
IR_STMT_FUNCTOR_DISPATCH(ProducerStoreNode);
Expand DownExpand Up@@ -159,6 +161,7 @@ class TVM_DLL StmtVisitor : protected StmtFunctor<void(const Stmt&)> {
void VisitStmt_(const WhileNode* op) override;
void VisitStmt_(const AllocateNode* op) override;
void VisitStmt_(const AllocateConstNode* op) override;
void VisitStmt_(const DeclBufferNode* op) override;
void VisitStmt_(const StoreNode* op) override;
void VisitStmt_(const BufferStoreNode* op) override;
void VisitStmt_(const BufferRealizeNode* op) override;
Expand DownExpand Up@@ -260,6 +263,7 @@ class TVM_DLL StmtMutator : protected StmtFunctor<Stmt(const Stmt&)> {
Stmt VisitStmt_(const WhileNode* op) override;
Stmt VisitStmt_(const AllocateNode* op) override;
Stmt VisitStmt_(const AllocateConstNode* op) override;
Stmt VisitStmt_(const DeclBufferNode* op) override;
Stmt VisitStmt_(const StoreNode* op) override;
Stmt VisitStmt_(const BufferStoreNode* op) override;
Stmt VisitStmt_(const BufferRealizeNode* op) override;
Expand Down
12 changes: 12 additions & 0 deletions python/tvm/script/tir/__init__.pyi
Original file line numberDiff line numberDiff line change
Expand Up@@ -187,6 +187,18 @@ def match_buffer(
buffer_type: str = "default",
axis_separators: Optional[List[int]] = None,
) -> Buffer: ...
def decl_buffer(
shape: Sequence[Union[PrimExpr, int]],
dtype: str = "float32",
data: Var = None,
strides: Optional[Sequence[int]] = None,
elem_offset: Optional[int] = None,
scope: str = "global",
align: int = -1,
offset_factor: int = 0,
buffer_type: str = "default",
axis_separators: Optional[List[int]] = None,
) -> Buffer: ...
def buffer_decl(
shape: Sequence[Union[PrimExpr, int]],
dtype: str = "float32",
Expand Down
81 changes: 81 additions & 0 deletions python/tvm/script/tir/scope_handler.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -224,6 +224,87 @@ def setup_buffer(data, dtype, shape, annotations: dict = None, span: Span = None
context.update_symbol(name, self.buffer, node)


@register
class DeclBuffer(WithScopeHandler):
"""Special Stmt decl_buffer(shape, dtype, data, strides, elem_offset, scope, align,
offset_factor, buffer_type, axis_separators)
Example
-------
.. code-block:: python
A = T.decl_buffer((128, 128), dtype="float32")
"""

def __init__(self):
def decl_buffer(
shape,
dtype="float32",
data=None,
strides=None,
elem_offset=None,
scope="global",
align=-1,
offset_factor=0,
buffer_type="default",
axis_separators=None,
span=None,
):
return tvm.tir.DeclBuffer(self.buffer, self.body, span=span)

super().__init__(decl_buffer, concise_scope=True, def_symbol=True)

def enter_scope(
self,
node: synr.ast.Node,
context: ContextMaintainer,
arg_list: List[Any],
span: synr.ast.Span,
):
# define buffer vars in symbol table
if isinstance(node, synr.ast.With):
vars = WithScopeHandler.get_optional_vars(node, context)
if len(vars) != 1:
context.report_error(f"Unexpected number of vars: 1 vs. {len(vars)}", node.span)
name = vars[0].id.name
var_span = vars[0].id.span
elif isinstance(node, synr.ast.Assign):
if len(node.lhs) != 1:
context.report_error(f"Unexpected number of vars: 1 vs. {len(node.lhs)}", node.span)
name = node.lhs[0].id.name
var_span = node.lhs[0].id.span
else:
raise Exception("Internal Bug")

def setup_buffer(
shape,
dtype,
data,
strides,
elem_offset,
scope,
align,
offset_factor,
buffer_type,
axis_separators,
span: Span = None,
):
self.buffer = tvm.tir.decl_buffer(
shape=shape,
dtype=dtype,
data=data,
strides=strides,
elem_offset=elem_offset,
scope=scope,
data_alignment=align,
offset_factor=offset_factor,
buffer_type=buffer_type,
axis_separators=axis_separators,
span=span,
)

setup_buffer(*arg_list, span=tvm_span_from_synr(var_span))
context.update_symbol(name, self.buffer, node)


@register
class LaunchThread(WithScopeHandler):
"""With scope handler T.launch_thread(env_var, extent)"""
Expand Down
1 change: 1 addition & 0 deletions python/tvm/tir/__init__.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,6 +36,7 @@
Allocate,
AllocateConst,
AttrStmt,
DeclBuffer,
)

from .stmt import ProducerRealize, SeqStmt
Expand Down
20 changes: 20 additions & 0 deletions python/tvm/tir/stmt.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -377,6 +377,26 @@ def __init__(self, buffer_var, dtype, extents, data_or_idx, body, annotations=No
)


@tvm._ffi.register_object("tir.DeclBuffer")
class DeclBuffer(Stmt):
"""DeclBuffer node.

Parameters
----------
buffer: Buffer
The buffer being declared.

body: Stmt
The body statement to be executed.

span: Optional[Span]
The location of this DeclBuffer in the source code.
"""

def __init__(self, buffer, body, span=None):
self.__init_handle_by_constructor__(_ffi_api.DeclBuffer, buffer, body, span)


@tvm._ffi.register_object("tir.AttrStmt")
class AttrStmt(Stmt):
"""AttrStmt node.
Expand Down
1 change: 1 addition & 0 deletions src/printer/text_printer.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -353,6 +353,7 @@ class TIRTextPrinter : public StmtFunctor<Doc(const Stmt&)>,
Doc VisitStmt_(const ProducerRealizeNode* op) override;
Doc VisitStmt_(const AllocateNode* op) override;
Doc VisitStmt_(const AllocateConstNode* op) override;
Doc VisitStmt_(const DeclBufferNode* op) override;
Doc VisitStmt_(const IfThenElseNode* op) override;
Doc VisitStmt_(const SeqStmtNode* op) override;
Doc VisitStmt_(const EvaluateNode* op) override;
Expand Down
12 changes: 12 additions & 0 deletions src/printer/tir_text_printer.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -557,6 +557,18 @@ Doc TIRTextPrinter::VisitStmt_(const AllocateConstNode* op) {
return doc;
}

Doc TIRTextPrinter::VisitStmt_(const DeclBufferNode* op) {
Doc doc;
doc << AllocBuf(op->buffer) << " = decl_buffer(" << Print(op->buffer->data) << ", "
<< PrintDType(op->buffer->dtype) << ", " << Print(op->buffer->shape) << ")" << Doc::NewLine();
if (op->body->IsInstance<SeqStmtNode>()) {
doc << PrintBody(op->body);
} else {
doc << ";" << Doc::NewLine() << Print(op->body);
}
return doc;
}

Doc TIRTextPrinter::VisitStmt_(const IfThenElseNode* op) {
Doc doc;
doc << "if " << Print(op->condition) << PrintBody(op->then_case);
Expand Down
19 changes: 19 additions & 0 deletions src/printer/tvmscript_printer.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,6 +245,7 @@ class TVMScriptPrinter : public StmtFunctor<Doc(const Stmt&)>,
Doc VisitStmt_(const BufferRealizeNode* op) override;
Doc VisitStmt_(const AllocateNode* op) override;
Doc VisitStmt_(const AllocateConstNode* op) override;
Doc VisitStmt_(const DeclBufferNode* op) override;
Doc VisitStmt_(const IfThenElseNode* op) override;
Doc VisitStmt_(const SeqStmtNode* op) override;
Doc VisitStmt_(const ForNode* op) override;
Expand DownExpand Up@@ -1161,6 +1162,24 @@ Doc TVMScriptPrinter::VisitStmt_(const AllocateConstNode* alloc) {
return doc;
}

Doc TVMScriptPrinter::VisitStmt_(const DeclBufferNode* op) {
const Buffer& buffer = op->buffer;
buf_not_in_headers_.insert(buffer.get());
Doc buffer_name = Print(op->buffer);
Doc func_call;
func_call << tir_prefix_ << ".decl_buffer(" << memo_buf_decl_.at(buffer) << ")";

Doc doc;
if (current_num_ != num_child_ - 1) {
doc << "with " << func_call << " as " << buffer_name << ":";
doc << Doc::Indent(4, Doc::NewLine() << PrintBody(op->body));
} else {
doc << buffer_name << " = " << func_call << Doc::NewLine();
doc << PrintBody(op->body);
}
return doc;
}

Doc TVMScriptPrinter::VisitStmt_(const IfThenElseNode* op) {
Doc doc;
doc << "if " << Print(op->condition) << ":";
Expand Down
2 changes: 2 additions & 0 deletions src/target/source/codegen_c.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -661,6 +661,8 @@ void CodeGenC::VisitStmt_(const AllocateConstNode* op) {
this->PrintStmt(op->body);
}

void CodeGenC::VisitStmt_(const DeclBufferNode* op) { this->PrintStmt(op->body); }

void CodeGenC::VisitExpr_(const LoadNode* op, std::ostream& os) { // NOLINT(*)
LOG(FATAL) << "Unexpected deprecated LoadNode. Use BufferLoadNode instead.";
}
Expand Down
1 change: 1 addition & 0 deletions src/target/source/codegen_c.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -166,6 +166,7 @@ class CodeGenC : public ExprFunctor<void(const PrimExpr&, std::ostream&)>,
void VisitStmt_(const EvaluateNode* op) override;
void VisitStmt_(const SeqStmtNode* op) override;
void VisitStmt_(const AllocateConstNode* op) override;
void VisitStmt_(const DeclBufferNode* op) override;

/*!
* \brief Print expr representing the thread tag
Expand Down
23 changes: 23 additions & 0 deletions src/tir/ir/stmt.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -508,6 +508,29 @@ TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
p->Print(op->body);
});

// DeclBuffer
DeclBuffer::DeclBuffer(Buffer buffer, Stmt body, Span span) {
ObjectPtr<DeclBufferNode> node = make_object<DeclBufferNode>();
node->buffer = std::move(buffer);
node->body = std::move(body);
node->span = std::move(span);
data_ = std::move(node);
}

TVM_REGISTER_GLOBAL("tir.DeclBuffer").set_body_typed([](Buffer buffer, Stmt body, Span span) {
return DeclBuffer(buffer, body, span);
});

TVM_REGISTER_NODE_TYPE(DeclBufferNode);

TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
.set_dispatch<DeclBufferNode>([](const ObjectRef& node, ReprPrinter* p) {
auto* op = static_cast<const DeclBufferNode*>(node.get());
p->PrintIndent();
p->stream << "decl_buffer " << op->buffer << "\n";
p->stream << op->body;
});

// ProducerRealize
ProducerRealize::ProducerRealize(DataProducer producer, Region bounds, PrimExpr condition,
Stmt body, String storage_scope, Span span) {
Expand Down
14 changes: 14 additions & 0 deletions src/tir/ir/stmt_functor.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,6 +63,8 @@ void StmtVisitor::VisitStmt_(const AllocateConstNode* op) {
this->VisitStmt(op->body);
}

void StmtVisitor::VisitStmt_(const DeclBufferNode* op) { this->VisitStmt(op->body); }

void StmtVisitor::VisitStmt_(const StoreNode* op) {
LOG(FATAL) << "Unexpected use of deprecated StoreNode. Please use BufferStoreNode instead.";
}
Expand DownExpand Up@@ -336,6 +338,18 @@ Stmt StmtMutator::VisitStmt_(const AllocateConstNode* op) {
}
}

Stmt StmtMutator::VisitStmt_(const DeclBufferNode* op) {
Stmt body = this->VisitStmt(op->body);

if (body.same_as(op->body)) {
return GetRef<Stmt>(op);
} else {
auto n = CopyOnWrite(op);
n->body = std::move(body);
return Stmt(n);
}
}

Stmt StmtMutator::VisitStmt_(const IfThenElseNode* op) {
PrimExpr condition = this->VisitExpr(op->condition);
Stmt then_case = this->VisitStmt(op->then_case);
Expand Down
6 changes: 4 additions & 2 deletions tests/cpp/ir_functor_test.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -181,6 +181,7 @@ TEST(IRF, StmtVisitor) {
DataType dtype = DataType::Float(32);
Var buf_var("b", PointerType(PrimType(dtype)));
Buffer buffer = decl_buffer({16});
body = DeclBuffer(buffer, std::move(body));
BufferRegion buffer_region(buffer, {Range::FromMinExtent(x + 1, 1)});
MatchBufferRegion match_buffer_region(decl_buffer({1}), buffer_region);

Expand DownExpand Up@@ -309,6 +310,7 @@ TEST(IRF, StmtMutator) {
DataType dtype = DataType::Float(32);
Var buf_var("b", PointerType(PrimType(dtype)));
Buffer buffer = decl_buffer({16});
body = DeclBuffer(buffer, std::move(body));
BufferRegion buffer_region(buffer, {Range::FromMinExtent(x + 1, 1)});
MatchBufferRegion match_buffer_region(decl_buffer({1}), buffer_region);
// construct block and block_realize
Expand All@@ -318,8 +320,8 @@ TEST(IRF, StmtMutator) {
body = v(std::move(block_realize));
// the body should be changed
Block new_block = body.as<BlockRealizeNode>()->block;
ICHECK(new_block->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->init.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->body.as<DeclBufferNode>()->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->init.as<DeclBufferNode>()->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->reads[0]->region[0]->min.same_as(x));
ICHECK(new_block->writes[0]->region[0]->min.same_as(x));
ICHECK(new_block->match_buffers[0]->source->region[0]->min.same_as(x));
Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); [TIR] Add DeclBuffer IR node and functors by vinx13 · Pull Request #12300 · apache/tvm · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions include/tvm/tir/stmt.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -681,6 +681,40 @@ class AllocateConst : public Stmt {
TVM_DEFINE_OBJECT_REF_METHODS(AllocateConst, Stmt, AllocateConstNode);
};

/*! \brief Declare a buffer that can be used in the body */
class DeclBufferNode : public StmtNode {
public:
/*! \brief The buffer being declared */
Buffer buffer;
/*! \brief The body to be executed */
Stmt body;

void VisitAttrs(AttrVisitor* v) {
v->Visit("buffer", &buffer);
v->Visit("body", &body);
v->Visit("span", &span);
}

bool SEqualReduce(const DeclBufferNode* other, SEqualReducer equal) const {
return equal(buffer, other->buffer) && equal(body, other->body);
}

void SHashReduce(SHashReducer hash_reduce) const {
hash_reduce(buffer);
hash_reduce(body);
}

static constexpr const char* _type_key = "tir.DeclBuffer";
TVM_DECLARE_FINAL_OBJECT_INFO(DeclBufferNode, StmtNode);
};

/*! \brief Managed reference to DeclBufferNode */
class DeclBuffer : public Stmt {
public:
TVM_DLL DeclBuffer(Buffer buffer, Stmt body, Span span = Span());
TVM_DEFINE_OBJECT_REF_METHODS(DeclBuffer, Stmt, DeclBufferNode);
};

/*!
* \brief The container of seq statement.
* Represent a sequence of statements.
Expand Down
4 changes: 4 additions & 0 deletions include/tvm/tir/stmt_functor.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -89,6 +89,7 @@ class StmtFunctor<R(const Stmt& n, Args... args)> {
virtual R VisitStmt_(const WhileNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const AllocateNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const AllocateConstNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const DeclBufferNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const StoreNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const BufferStoreNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
virtual R VisitStmt_(const BufferRealizeNode* op, Args... args) STMT_FUNCTOR_DEFAULT;
Expand DownExpand Up@@ -116,6 +117,7 @@ class StmtFunctor<R(const Stmt& n, Args... args)> {
IR_STMT_FUNCTOR_DISPATCH(WhileNode);
IR_STMT_FUNCTOR_DISPATCH(AllocateNode);
IR_STMT_FUNCTOR_DISPATCH(AllocateConstNode);
IR_STMT_FUNCTOR_DISPATCH(DeclBufferNode);
IR_STMT_FUNCTOR_DISPATCH(StoreNode);
IR_STMT_FUNCTOR_DISPATCH(AssertStmtNode);
IR_STMT_FUNCTOR_DISPATCH(ProducerStoreNode);
Expand DownExpand Up@@ -159,6 +161,7 @@ class TVM_DLL StmtVisitor : protected StmtFunctor<void(const Stmt&)> {
void VisitStmt_(const WhileNode* op) override;
void VisitStmt_(const AllocateNode* op) override;
void VisitStmt_(const AllocateConstNode* op) override;
void VisitStmt_(const DeclBufferNode* op) override;
void VisitStmt_(const StoreNode* op) override;
void VisitStmt_(const BufferStoreNode* op) override;
void VisitStmt_(const BufferRealizeNode* op) override;
Expand DownExpand Up@@ -260,6 +263,7 @@ class TVM_DLL StmtMutator : protected StmtFunctor<Stmt(const Stmt&)> {
Stmt VisitStmt_(const WhileNode* op) override;
Stmt VisitStmt_(const AllocateNode* op) override;
Stmt VisitStmt_(const AllocateConstNode* op) override;
Stmt VisitStmt_(const DeclBufferNode* op) override;
Stmt VisitStmt_(const StoreNode* op) override;
Stmt VisitStmt_(const BufferStoreNode* op) override;
Stmt VisitStmt_(const BufferRealizeNode* op) override;
Expand Down
12 changes: 12 additions & 0 deletions python/tvm/script/tir/__init__.pyi
Original file line numberDiff line numberDiff line change
Expand Up@@ -187,6 +187,18 @@ def match_buffer(
buffer_type: str = "default",
axis_separators: Optional[List[int]] = None,
) -> Buffer: ...
def decl_buffer(
shape: Sequence[Union[PrimExpr, int]],
dtype: str = "float32",
data: Var = None,
strides: Optional[Sequence[int]] = None,
elem_offset: Optional[int] = None,
scope: str = "global",
align: int = -1,
offset_factor: int = 0,
buffer_type: str = "default",
axis_separators: Optional[List[int]] = None,
) -> Buffer: ...
def buffer_decl(
shape: Sequence[Union[PrimExpr, int]],
dtype: str = "float32",
Expand Down
81 changes: 81 additions & 0 deletions python/tvm/script/tir/scope_handler.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -224,6 +224,87 @@ def setup_buffer(data, dtype, shape, annotations: dict = None, span: Span = None
context.update_symbol(name, self.buffer, node)


@register
class DeclBuffer(WithScopeHandler):
"""Special Stmt decl_buffer(shape, dtype, data, strides, elem_offset, scope, align,
offset_factor, buffer_type, axis_separators)
Example
-------
.. code-block:: python
A = T.decl_buffer((128, 128), dtype="float32")
"""

def __init__(self):
def decl_buffer(
shape,
dtype="float32",
data=None,
strides=None,
elem_offset=None,
scope="global",
align=-1,
offset_factor=0,
buffer_type="default",
axis_separators=None,
span=None,
):
return tvm.tir.DeclBuffer(self.buffer, self.body, span=span)

super().__init__(decl_buffer, concise_scope=True, def_symbol=True)

def enter_scope(
self,
node: synr.ast.Node,
context: ContextMaintainer,
arg_list: List[Any],
span: synr.ast.Span,
):
# define buffer vars in symbol table
if isinstance(node, synr.ast.With):
vars = WithScopeHandler.get_optional_vars(node, context)
if len(vars) != 1:
context.report_error(f"Unexpected number of vars: 1 vs. {len(vars)}", node.span)
name = vars[0].id.name
var_span = vars[0].id.span
elif isinstance(node, synr.ast.Assign):
if len(node.lhs) != 1:
context.report_error(f"Unexpected number of vars: 1 vs. {len(node.lhs)}", node.span)
name = node.lhs[0].id.name
var_span = node.lhs[0].id.span
else:
raise Exception("Internal Bug")

def setup_buffer(
shape,
dtype,
data,
strides,
elem_offset,
scope,
align,
offset_factor,
buffer_type,
axis_separators,
span: Span = None,
):
self.buffer = tvm.tir.decl_buffer(
shape=shape,
dtype=dtype,
data=data,
strides=strides,
elem_offset=elem_offset,
scope=scope,
data_alignment=align,
offset_factor=offset_factor,
buffer_type=buffer_type,
axis_separators=axis_separators,
span=span,
)

setup_buffer(*arg_list, span=tvm_span_from_synr(var_span))
context.update_symbol(name, self.buffer, node)


@register
class LaunchThread(WithScopeHandler):
"""With scope handler T.launch_thread(env_var, extent)"""
Expand Down
1 change: 1 addition & 0 deletions python/tvm/tir/__init__.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -36,6 +36,7 @@
Allocate,
AllocateConst,
AttrStmt,
DeclBuffer,
)

from .stmt import ProducerRealize, SeqStmt
Expand Down
20 changes: 20 additions & 0 deletions python/tvm/tir/stmt.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -377,6 +377,26 @@ def __init__(self, buffer_var, dtype, extents, data_or_idx, body, annotations=No
)


@tvm._ffi.register_object("tir.DeclBuffer")
class DeclBuffer(Stmt):
"""DeclBuffer node.

Parameters
----------
buffer: Buffer
The buffer being declared.

body: Stmt
The body statement to be executed.

span: Optional[Span]
The location of this DeclBuffer in the source code.
"""

def __init__(self, buffer, body, span=None):
self.__init_handle_by_constructor__(_ffi_api.DeclBuffer, buffer, body, span)


@tvm._ffi.register_object("tir.AttrStmt")
class AttrStmt(Stmt):
"""AttrStmt node.
Expand Down
1 change: 1 addition & 0 deletions src/printer/text_printer.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -353,6 +353,7 @@ class TIRTextPrinter : public StmtFunctor<Doc(const Stmt&)>,
Doc VisitStmt_(const ProducerRealizeNode* op) override;
Doc VisitStmt_(const AllocateNode* op) override;
Doc VisitStmt_(const AllocateConstNode* op) override;
Doc VisitStmt_(const DeclBufferNode* op) override;
Doc VisitStmt_(const IfThenElseNode* op) override;
Doc VisitStmt_(const SeqStmtNode* op) override;
Doc VisitStmt_(const EvaluateNode* op) override;
Expand Down
12 changes: 12 additions & 0 deletions src/printer/tir_text_printer.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -557,6 +557,18 @@ Doc TIRTextPrinter::VisitStmt_(const AllocateConstNode* op) {
return doc;
}

Doc TIRTextPrinter::VisitStmt_(const DeclBufferNode* op) {
Doc doc;
doc << AllocBuf(op->buffer) << " = decl_buffer(" << Print(op->buffer->data) << ", "
<< PrintDType(op->buffer->dtype) << ", " << Print(op->buffer->shape) << ")" << Doc::NewLine();
if (op->body->IsInstance<SeqStmtNode>()) {
doc << PrintBody(op->body);
} else {
doc << ";" << Doc::NewLine() << Print(op->body);
}
return doc;
}

Doc TIRTextPrinter::VisitStmt_(const IfThenElseNode* op) {
Doc doc;
doc << "if " << Print(op->condition) << PrintBody(op->then_case);
Expand Down
19 changes: 19 additions & 0 deletions src/printer/tvmscript_printer.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,6 +245,7 @@ class TVMScriptPrinter : public StmtFunctor<Doc(const Stmt&)>,
Doc VisitStmt_(const BufferRealizeNode* op) override;
Doc VisitStmt_(const AllocateNode* op) override;
Doc VisitStmt_(const AllocateConstNode* op) override;
Doc VisitStmt_(const DeclBufferNode* op) override;
Doc VisitStmt_(const IfThenElseNode* op) override;
Doc VisitStmt_(const SeqStmtNode* op) override;
Doc VisitStmt_(const ForNode* op) override;
Expand DownExpand Up@@ -1161,6 +1162,24 @@ Doc TVMScriptPrinter::VisitStmt_(const AllocateConstNode* alloc) {
return doc;
}

Doc TVMScriptPrinter::VisitStmt_(const DeclBufferNode* op) {
const Buffer& buffer = op->buffer;
buf_not_in_headers_.insert(buffer.get());
Doc buffer_name = Print(op->buffer);
Doc func_call;
func_call << tir_prefix_ << ".decl_buffer(" << memo_buf_decl_.at(buffer) << ")";

Doc doc;
if (current_num_ != num_child_ - 1) {
doc << "with " << func_call << " as " << buffer_name << ":";
doc << Doc::Indent(4, Doc::NewLine() << PrintBody(op->body));
} else {
doc << buffer_name << " = " << func_call << Doc::NewLine();
doc << PrintBody(op->body);
}
return doc;
}

Doc TVMScriptPrinter::VisitStmt_(const IfThenElseNode* op) {
Doc doc;
doc << "if " << Print(op->condition) << ":";
Expand Down
2 changes: 2 additions & 0 deletions src/target/source/codegen_c.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -661,6 +661,8 @@ void CodeGenC::VisitStmt_(const AllocateConstNode* op) {
this->PrintStmt(op->body);
}

void CodeGenC::VisitStmt_(const DeclBufferNode* op) { this->PrintStmt(op->body); }

void CodeGenC::VisitExpr_(const LoadNode* op, std::ostream& os) { // NOLINT(*)
LOG(FATAL) << "Unexpected deprecated LoadNode. Use BufferLoadNode instead.";
}
Expand Down
1 change: 1 addition & 0 deletions src/target/source/codegen_c.h
Original file line numberDiff line numberDiff line change
Expand Up@@ -166,6 +166,7 @@ class CodeGenC : public ExprFunctor<void(const PrimExpr&, std::ostream&)>,
void VisitStmt_(const EvaluateNode* op) override;
void VisitStmt_(const SeqStmtNode* op) override;
void VisitStmt_(const AllocateConstNode* op) override;
void VisitStmt_(const DeclBufferNode* op) override;

/*!
* \brief Print expr representing the thread tag
Expand Down
23 changes: 23 additions & 0 deletions src/tir/ir/stmt.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -508,6 +508,29 @@ TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
p->Print(op->body);
});

// DeclBuffer
DeclBuffer::DeclBuffer(Buffer buffer, Stmt body, Span span) {
ObjectPtr<DeclBufferNode> node = make_object<DeclBufferNode>();
node->buffer = std::move(buffer);
node->body = std::move(body);
node->span = std::move(span);
data_ = std::move(node);
}

TVM_REGISTER_GLOBAL("tir.DeclBuffer").set_body_typed([](Buffer buffer, Stmt body, Span span) {
return DeclBuffer(buffer, body, span);
});

TVM_REGISTER_NODE_TYPE(DeclBufferNode);

TVM_STATIC_IR_FUNCTOR(ReprPrinter, vtable)
.set_dispatch<DeclBufferNode>([](const ObjectRef& node, ReprPrinter* p) {
auto* op = static_cast<const DeclBufferNode*>(node.get());
p->PrintIndent();
p->stream << "decl_buffer " << op->buffer << "\n";
p->stream << op->body;
});

// ProducerRealize
ProducerRealize::ProducerRealize(DataProducer producer, Region bounds, PrimExpr condition,
Stmt body, String storage_scope, Span span) {
Expand Down
14 changes: 14 additions & 0 deletions src/tir/ir/stmt_functor.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -63,6 +63,8 @@ void StmtVisitor::VisitStmt_(const AllocateConstNode* op) {
this->VisitStmt(op->body);
}

void StmtVisitor::VisitStmt_(const DeclBufferNode* op) { this->VisitStmt(op->body); }

void StmtVisitor::VisitStmt_(const StoreNode* op) {
LOG(FATAL) << "Unexpected use of deprecated StoreNode. Please use BufferStoreNode instead.";
}
Expand DownExpand Up@@ -336,6 +338,18 @@ Stmt StmtMutator::VisitStmt_(const AllocateConstNode* op) {
}
}

Stmt StmtMutator::VisitStmt_(const DeclBufferNode* op) {
Stmt body = this->VisitStmt(op->body);

if (body.same_as(op->body)) {
return GetRef<Stmt>(op);
} else {
auto n = CopyOnWrite(op);
n->body = std::move(body);
return Stmt(n);
}
}

Stmt StmtMutator::VisitStmt_(const IfThenElseNode* op) {
PrimExpr condition = this->VisitExpr(op->condition);
Stmt then_case = this->VisitStmt(op->then_case);
Expand Down
6 changes: 4 additions & 2 deletions tests/cpp/ir_functor_test.cc
Original file line numberDiff line numberDiff line change
Expand Up@@ -181,6 +181,7 @@ TEST(IRF, StmtVisitor) {
DataType dtype = DataType::Float(32);
Var buf_var("b", PointerType(PrimType(dtype)));
Buffer buffer = decl_buffer({16});
body = DeclBuffer(buffer, std::move(body));
BufferRegion buffer_region(buffer, {Range::FromMinExtent(x + 1, 1)});
MatchBufferRegion match_buffer_region(decl_buffer({1}), buffer_region);

Expand DownExpand Up@@ -309,6 +310,7 @@ TEST(IRF, StmtMutator) {
DataType dtype = DataType::Float(32);
Var buf_var("b", PointerType(PrimType(dtype)));
Buffer buffer = decl_buffer({16});
body = DeclBuffer(buffer, std::move(body));
BufferRegion buffer_region(buffer, {Range::FromMinExtent(x + 1, 1)});
MatchBufferRegion match_buffer_region(decl_buffer({1}), buffer_region);
// construct block and block_realize
Expand All@@ -318,8 +320,8 @@ TEST(IRF, StmtMutator) {
body = v(std::move(block_realize));
// the body should be changed
Block new_block = body.as<BlockRealizeNode>()->block;
ICHECK(new_block->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->init.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->body.as<DeclBufferNode>()->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->init.as<DeclBufferNode>()->body.as<AllocateNode>()->extents[1].same_as(x));
ICHECK(new_block->reads[0]->region[0]->min.same_as(x));
ICHECK(new_block->writes[0]->region[0]->min.same_as(x));
ICHECK(new_block->match_buffers[0]->source->region[0]->min.same_as(x));
Expand Down
Loading