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
80 changes: 80 additions & 0 deletions include/tvm/ir/global_info.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/

/*!
* \file tvm/ir/global_info.h
* \brief GlobalInfo are globally static object that are referred by the IR itself.
*/

#ifndef TVM_IR_GLOBAL_INFO_H_
#define TVM_IR_GLOBAL_INFO_H_

#include "tvm/ir/expr.h"

namespace tvm {

/*!
* \brief GlobalInfo are globally static object that are referred by the IR itself.
* Base node for all global info that can appear in the IR
*/
class GlobalInfoNode : public Object {
public:
static constexpr const char* _type_key = "GlobalInfoNode";
static constexpr const bool _type_has_method_sequal_reduce = true;
static constexpr const bool _type_has_method_shash_reduce = true;
TVM_DECLARE_BASE_OBJECT_INFO(GlobalInfoNode, Object);
};

/*!
* \brief Managed reference to GlobalInfoNode.
* \sa GlobalInfoNode
*/
class GlobalInfo : public ObjectRef {
public:
TVM_DEFINE_OBJECT_REF_METHODS(GlobalInfo, ObjectRef, GlobalInfoNode);
};

/*!
* \brief A dummy global info sub-class for testing purpose.
*/
class DummyGlobalInfoNode : public GlobalInfoNode {
public:
void VisitAttrs(tvm::AttrVisitor* v) {}
static constexpr const char* _type_key = "DummyGlobalInfo";

TVM_DLL bool SEqualReduce(const DummyGlobalInfoNode* other, SEqualReducer equal) const {
return true;
}

TVM_DLL void SHashReduce(SHashReducer hash_reduce) const {}
TVM_DECLARE_FINAL_OBJECT_INFO(DummyGlobalInfoNode, GlobalInfoNode);
};

/*!
* \brief Managed reference to DummyGlobalInfoNode.
* \sa DummyGlobalInfoNode
*/
class DummyGlobalInfo : public GlobalInfo {
public:
TVM_DEFINE_OBJECT_REF_METHODS(DummyGlobalInfo, GlobalInfo, DummyGlobalInfoNode);
};

} // namespace tvm

#endif // TVM_IR_GLOBAL_INFO_H_
16 changes: 14 additions & 2 deletions include/tvm/ir/module.h
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
#include <tvm/ir/adt.h>
#include <tvm/ir/expr.h>
#include <tvm/ir/function.h>
#include <tvm/ir/global_info.h>
#include <tvm/ir/source_map.h>
#include <tvm/ir/type.h>
#include <tvm/runtime/container/array.h>
Expand Down Expand Up @@ -63,6 +64,8 @@ class IRModuleNode : public Object {
SourceMap source_map;
/* \brief Additional attributes storing meta-data about the module. */
DictAttrs attrs;
/*! \brief Globally static object that are referred by the IR itself */
Map<String, Array<GlobalInfo>> global_infos;
/*!
* \brief A map from string names to global variables that
* ensures global uniqueness.
Expand Down Expand Up @@ -151,6 +154,7 @@ class IRModuleNode : public Object {
v->Visit("global_type_var_map_", &global_type_var_map_);
v->Visit("source_map", &source_map);
v->Visit("attrs", &attrs);
v->Visit("global_infos", &global_infos);
}

TVM_DLL bool SEqualReduce(const IRModuleNode* other, SEqualReducer equal) const;
Expand Down Expand Up @@ -210,6 +214,13 @@ class IRModuleNode : public Object {
*/
TVM_DLL void UpdateTypeDef(const GlobalTypeVar& var, const TypeData& type);

/*!
* \brief Update an array of global infos in the global environment.
* \param name The name of the global info.
* \param info The new array of global infos.
*/
TVM_DLL void UpdateGlobalInfo(const String& name, const Array<GlobalInfo>& info);

/*!
* \brief Remove a function from the global environment.
* \param var The name of the global function to update.
Expand Down Expand Up @@ -359,12 +370,13 @@ class IRModule : public ObjectRef {
* \param type_definitions Type definitions in the module.
* \param import_set Set of imported files in the module.
* \param map The module source map.
* \param attrs The module attributes.
* \param attrs The module meta-data attributes.
* \param global_infos Global infos in the module.
*/
TVM_DLL explicit IRModule(Map<GlobalVar, BaseFunc> functions,
Map<GlobalTypeVar, TypeData> type_definitions = {},
std::unordered_set<String> import_set = {}, SourceMap map = {},
DictAttrs attrs = {});
DictAttrs attrs = {}, Map<String, Array<GlobalInfo>> global_infos = {});

/*! \brief default constructor */
IRModule() : IRModule(Map<GlobalVar, BaseFunc>({})) {}
Expand Down
2 changes: 2 additions & 0 deletions include/tvm/script/ir_builder/base.h
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,8 @@ class IRBuilder : public runtime::ObjectRef {
* \sa tvm::support::With
*/
static IRBuilder Current();
/*! \brief See if the current thread-local scope has an IRBuilder. */
static bool IsInScope();
/*!
* \brief Give a string name to the `obj`
* \tparam TObjectRef The type of the object to name.
Expand Down
7 changes: 7 additions & 0 deletions include/tvm/script/ir_builder/ir/frame.h
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@

#include <tvm/ir/expr.h>
#include <tvm/ir/function.h>
#include <tvm/ir/module.h>
#include <tvm/node/node.h>
#include <tvm/script/ir_builder/base.h>

Expand All @@ -45,11 +46,17 @@ class IRModuleFrameNode : public IRBuilderFrameNode {
* \note Only defined functions are in the map, while declared functions are not included.
*/
Map<GlobalVar, BaseFunc> functions;
/*! \brief IRModule's attributes. */
Map<String, ObjectRef> attrs;
/*! \brief IRModule's global_infos */
Map<String, Array<GlobalInfo>> global_infos;

void VisitAttrs(tvm::AttrVisitor* v) {
IRBuilderFrameNode::VisitAttrs(v);
v->Visit("global_vars", &global_var_map);
v->Visit("functions", &functions);
v->Visit("attrs", &attrs);
v->Visit("global_infos", &global_infos);
}

static constexpr const char* _type_key = "script.ir_builder.IRModuleFrame";
Expand Down
1 change: 1 addition & 0 deletions python/tvm/ir/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
from .container import Array, Map
from .expr import BaseExpr, GlobalVar, PrimExpr, Range, RelayExpr
from .function import BaseFunc, CallingConv
from .global_info import GlobalInfo, DummyGlobalInfo
from .memory_pools import (
ConstantMemoryPools,
ConstantPoolInfo,
Expand Down
42 changes: 42 additions & 0 deletions python/tvm/ir/global_info.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""Global Info."""
import tvm
from tvm.runtime.object import Object
from . import _ffi_api


class GlobalInfo(Object):
"""Base node for all global info that can appear in the IR"""

def __eq__(self, other):
"""Compare two struct info for structural equivalence."""
return tvm.ir.structural_equal(self, other)

def __ne__(self, other):
return not self.__eq__(other)

def same_as(self, other):
"""Overload with structural equality."""
return super().__eq__(other)


class DummyGlobalInfo(GlobalInfo):
def __init__(self) -> None:
self.__init_handle_by_constructor__(
_ffi_api.DummyGlobalInfo,
)
30 changes: 28 additions & 2 deletions python/tvm/ir/module.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class IRModule(Node, Scriptable):
Map of global var to BaseFunc
"""

def __init__(self, functions=None, type_definitions=None):
def __init__(self, functions=None, type_definitions=None, attrs=None, global_infos=None):
if functions is None:
functions = {}
elif isinstance(functions, dict):
Expand All @@ -65,7 +65,20 @@ def __init__(self, functions=None, type_definitions=None):
raise TypeError("Expect type_definitions to be Dict[GlobalTypeVar, Type]")
mapped_type_defs[k] = v
type_definitions = mapped_type_defs
self.__init_handle_by_constructor__(_ffi_api.IRModule, functions, type_definitions)

attrs = None if not attrs else attrs
if attrs is not None:
attrs = ast.literal_eval(str(attrs))
attrs = tvm.ir.make_node("DictAttrs", **attrs)
if global_infos is None:
global_infos = {}
self.__init_handle_by_constructor__(
_ffi_api.IRModule,
functions,
type_definitions,
attrs,
global_infos,
)

def __setitem__(self, var, val):
"""Add a mapping to the module.
Expand Down Expand Up @@ -140,6 +153,19 @@ def update_func(self, var, func):
"""
return _ffi_api.Module_UpdateFunction(self, var, func)

def update_global_info(self, name, global_info):
"""Update global info in the module

Parameters
----------
name: str
The name for the global info.

global_info: List[GlobalInfo]
The global info to be updated.
"""
return _ffi_api.Module_UpdateGlobalInfo(self, name, global_info)

def get_global_var(self, name):
"""Get a global variable in the function by name.

Expand Down
11 changes: 11 additions & 0 deletions python/tvm/script/ir_builder/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,17 @@ def current() -> "IRBuilder":
"""
return _ffi_api.IRBuilderCurrent() # type: ignore[attr-defined] # pylint: disable=no-member

@staticmethod
def is_in_scope() -> bool:
"""See if the current thread-local scope has an IRBuilder.

Returns
-------
bool
Whether the current thread-local scope has an IRBuilder
"""
return _ffi_api.IRBuilderIsInScope() # type: ignore[attr-defined] # pylint: disable=no-member

def get(self) -> _Object:
"""Get the constructed IR."""
return _ffi_api.IRBuilderGet(self) # type: ignore[attr-defined] # pylint: disable=no-member
Expand Down
9 changes: 8 additions & 1 deletion python/tvm/script/ir_builder/ir/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,11 @@
# under the License.
"""Package tvm.script.ir_builder.ir"""
from .frame import IRModuleFrame
from .ir import decl_function, def_function, ir_module
from .ir import (
decl_function,
def_function,
ir_module,
module_attrs,
module_global_infos,
dummy_global_info,
)
39 changes: 38 additions & 1 deletion python/tvm/script/ir_builder/ir/ir.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,11 @@
# under the License.
"""Package tvm.script.ir_builder.ir.ir"""

from tvm.ir import BaseFunc, GlobalVar
from typing import Dict, List

from tvm.ir import BaseFunc, GlobalVar, GlobalInfo, DummyGlobalInfo
from tvm.runtime import Object as tvm_Object


from . import _ffi_api
from .frame import IRModuleFrame
Expand Down Expand Up @@ -67,3 +71,36 @@ def def_function(func_name: str, func: BaseFunc) -> None:
The given function implementation
"""
return _ffi_api.DefFunction(func_name, func) # type: ignore[attr-defined] # pylint: disable=no-member


def module_attrs(attrs: Dict[str, tvm_Object]) -> None:
"""Specify the attrs of the ir_module frame.
Parameters
----------
attrs: Dict[str, Object]
The module attrs.
"""
return _ffi_api.ModuleAttrs(attrs) # type: ignore[attr-defined] # pylint: disable=no-member


def module_global_infos(global_infos: Dict[str, List[GlobalInfo]]) -> None:
"""Specify the global infos of the ir_module frame.
Parameters
----------
global_infos: Dict[str, List[GlobalInfo]]
The module global infos.
"""
return _ffi_api.ModuleGlobalInfos(global_infos) # type: ignore[attr-defined] # pylint: disable=no-member


############################### GlobalInfo ###############################


def dummy_global_info() -> DummyGlobalInfo:
"""Create a dummy global info expression.
Returns
-------
res : DummyGlobalInfo
The result dummy global info.
"""
return DummyGlobalInfo() # type: ignore[attr-defined] # pylint: disable=no-member
4 changes: 2 additions & 2 deletions python/tvm/script/parser/ir/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
# specific language governing permissions and limitations
# under the License.
"""The ir module parser"""

from ...ir_builder.ir import * # pylint: disable=redefined-builtin
from . import parser as _parser
from .entry import ir_module

__all__ = ["ir_module"]
__all__ = ["ir_module", "module_attrs", "module_global_infos", "dummy_global_info"]
Loading