tvm
Loading...
Searching...
No Matches
transform.h
Go to the documentation of this file.
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
28#ifndef TVM_IR_TRANSFORM_H_
29#define TVM_IR_TRANSFORM_H_
30
31#include <tvm/ffi/container/array.h>
32#include <tvm/ffi/function.h>
33#include <tvm/ffi/reflection/creator.h>
34#include <tvm/ffi/reflection/registry.h>
35#include <tvm/ffi/rvalue_ref.h>
36#include <tvm/ffi/string.h>
37#include <tvm/ir/module.h>
38#include <tvm/ir/with_context.h>
39
40#include <functional>
41#include <string>
42#include <type_traits>
43#include <utility>
44
45namespace tvm {
46namespace transform {
47
48class PassInfo;
49class PassContextObj;
50
64class PassContext : public ffi::ObjectRef {
65 public:
66 static constexpr bool _type_is_nullable = false;
70 explicit PassContext(ffi::UnsafeInit tag) : ffi::ObjectRef(tag) {}
74 explicit PassContext(ffi::UnsafeInit tag, ffi::ObjectPtr<PassContextObj> n);
79 const PassContextObj* operator->() const;
85
90 static PassContext Create();
96
101 TVM_TIRX_DLL static ffi::Map<ffi::String, ffi::Map<ffi::String, ffi::String>> ListConfigs();
102
109
116
127 TVM_TIRX_DLL bool InstrumentBeforePass(const IRModule& mod, const PassInfo& info) const;
128
137 void InstrumentAfterPass(const IRModule& mod, const PassInfo& info) const;
138
144 TVM_TIRX_DLL bool PassEnabled(const PassInfo& info) const;
145
152 template <typename ValueType>
153 static void RegisterConfigOption(const char* key) {
154 if constexpr (std::is_base_of_v<ffi::ObjectRef, ValueType>) {
155 // Static-init blocks may run before the cached runtime type index is initialized.
156 int32_t tindex = ValueType::ContainerType::_GetOrAllocRuntimeTypeIndex();
157 auto type_key = ffi::TypeIndexToTypeKey(tindex);
158 auto legalization = [=](ffi::Any value) -> ffi::Any {
159 if (auto opt_map = value.try_cast<ffi::Map<ffi::String, ffi::Any>>()) {
160 return ffi::reflection::ObjectCreator(type_key)(opt_map.value());
161 } else {
162 auto opt_val = value.try_cast<ValueType>();
163 if (!opt_val.has_value()) {
164 TVM_FFI_THROW(AttributeError)
165 << "Expect config " << key << " to have type " << type_key << ", but instead get "
166 << ffi::detail::AnyUnsafe::GetMismatchTypeInfo<ValueType>(value);
167 }
168 return *opt_val;
169 }
170 };
171 RegisterConfigOption(key, type_key, legalization);
172 } else {
173 // non-object type, do not support implicit conversion from map
174 std::string type_str = ffi::TypeTraits<ValueType>::TypeStr();
175 auto legalization = [=](ffi::Any value) -> ffi::Any {
176 auto opt_val = value.try_cast<ValueType>();
177 if (!opt_val.has_value()) {
178 TVM_FFI_THROW(AttributeError)
179 << "Expect config " << key << " to have type " << type_str << ", but instead get "
180 << ffi::detail::AnyUnsafe::GetMismatchTypeInfo<ValueType>(value);
181 TVM_FFI_UNREACHABLE();
182 } else {
183 return *opt_val;
184 }
185 };
186 RegisterConfigOption(key, type_str, legalization);
187 }
188 }
189
190 // accessor.
192 class Internal;
193
194 private:
195 // The entry of a pass context scope.
196 TVM_TIRX_DLL void EnterWithScope();
197 // The exit of a pass context scope.
198 TVM_TIRX_DLL void ExitWithScope();
199 // Register configuration key value type.
201 const char* key, ffi::String value_type_str,
202 ffi::TypedFunction<ffi::Any(ffi::Any)> legalization);
203
204 // Classes to get the Python `with` like syntax.
205 friend class Internal;
206 friend class With<PassContext>;
207};
208
215template <typename TConfig>
216inline TConfig PassConfigWithDefaults() {
217 static_assert(std::is_base_of_v<ffi::ObjectRef, TConfig>,
218 "Can only create ObjectRef-derived types");
219 using ContainerType = typename TConfig::ContainerType;
220 static auto finit_object = ffi::Function::GetGlobalRequired("ffi.MakeObjectFromPackedArgs");
221 ffi::AnyView packed_args[1];
222 packed_args[0] = ContainerType::RuntimeTypeIndex();
223 ffi::Any rv;
224 finit_object.CallPacked(ffi::PackedArgs(packed_args, 1), &rv);
225 return rv.cast<TConfig>();
226}
227
232class PassInfoObj : public ffi::Object {
233 public:
236
238 ffi::String name;
239
240 PassInfoObj() = default;
241
242 static void RegisterReflection() {
243 namespace refl = tvm::ffi::reflection;
244 refl::ObjectDef<PassInfoObj>()
245 .def_ro("opt_level", &PassInfoObj::opt_level)
246 .def_ro("name", &PassInfoObj::name);
247 }
248 TVM_FFI_DECLARE_OBJECT_INFO_FINAL("transform.PassInfo", PassInfoObj, ffi::Object);
249};
250
255class PassInfo : public ffi::ObjectRef {
256 public:
262 PassInfo(int opt_level, ffi::String name) {
263 auto pass_info = ffi::make_object<PassInfoObj>();
264 pass_info->opt_level = opt_level;
265 pass_info->name = std::move(name);
266 data_ = std::move(pass_info);
267 }
268
270};
271
277class PassObj : public ffi::Object {
278 public:
279 virtual ~PassObj() {}
282 virtual PassInfo Info() const = 0;
283
292 return this->operator()(std::move(mod), PassContext::Current());
293 }
294
303 virtual IRModule operator()(IRModule mod, const PassContext& pass_ctx) const = 0;
304 TVM_FFI_DECLARE_OBJECT_INFO("transform.Pass", PassObj, ffi::Object);
305};
306
307class Pass : public ffi::ObjectRef {
308 public:
325 return this->operator()(std::move(mod), PassContext::Current());
326 }
327
337
339
340 private:
341 IRModule static AssertImmutableModule(const IRModule& mod, const PassObj* node,
342 const PassContext& pass_ctx);
343};
344
353class SequentialObj : public PassObj {
354 public:
356 explicit SequentialObj(ffi::UnsafeInit tag) : pass_info(tag) {}
357 /* \brief The pass meta data.*/
359
361 tvm::ffi::Array<Pass> passes;
362
363 static void RegisterReflection() {
364 namespace refl = tvm::ffi::reflection;
365 refl::ObjectDef<SequentialObj>()
366 .def_ro("pass_info", &SequentialObj::pass_info)
367 .def_ro("passes", &SequentialObj::passes);
368 }
369
373 PassInfo Info() const override { return pass_info; }
374
386 TVM_TIRX_DLL IRModule operator()(IRModule mod, const PassContext& pass_ctx) const final;
388};
389
390class Sequential : public Pass {
391 public:
398 TVM_TIRX_DLL Sequential(ffi::Array<Pass> passes, PassInfo pass_info);
399
408 TVM_TIRX_DLL Sequential(ffi::Array<Pass> passes, ffi::String name = "sequential");
409
410 explicit Sequential(ffi::UnsafeInit tag) : Pass(tag) {}
411
412 const SequentialObj* operator->() const { return static_cast<const SequentialObj*>(get()); }
414};
415
425CreateModulePass(ffi::TypedFunction<IRModule(ffi::RValueRef<IRModule>, PassContext)> pass_func,
426 int opt_level, ffi::String name);
427
436inline Pass CreateModulePass(std::function<IRModule(IRModule, PassContext)> pass_func,
437 int opt_level, ffi::String name) {
438 ffi::TypedFunction<IRModule(ffi::RValueRef<IRModule>, PassContext)> callback =
439 [pass_func = std::move(pass_func)](ffi::RValueRef<IRModule> mod,
440 PassContext ctx) -> IRModule {
441 return pass_func(*std::move(mod), std::move(ctx));
442 };
443 return CreateModulePass(std::move(callback), opt_level, std::move(name));
444}
445
451TVM_TIRX_DLL Pass PrintIR(ffi::String header = "");
452
465TVM_TIRX_DLL ffi::Error EnrichErrorWithContext(const ffi::Error& err, const ffi::ObjectRef& root,
466 ffi::String context = "");
467
490 const ffi::Error& err, const IRModule& mod, ffi::String pass_name,
491 ffi::Optional<GlobalVar> func = ffi::Optional<GlobalVar>(std::nullopt));
492
549class PassInstrumentObj : public ffi::Object {
550 public:
552 ffi::String name;
553
555
557 virtual void EnterPassContext() const = 0;
558
560 virtual void ExitPassContext() const = 0;
561
570 virtual bool ShouldRun(const IRModule& mod, const transform::PassInfo& info) const = 0;
571
577 virtual void RunBeforePass(const IRModule& mod, const transform::PassInfo& info) const = 0;
578
584 virtual void RunAfterPass(const IRModule& mod, const transform::PassInfo& info) const = 0;
585
586 static void RegisterReflection() {
587 namespace refl = tvm::ffi::reflection;
588 refl::ObjectDef<PassInstrumentObj>().def_ro("name", &PassInstrumentObj::name);
589 }
590 TVM_FFI_DECLARE_OBJECT_INFO("transform.PassInstrument", PassInstrumentObj, ffi::Object);
591};
592
597class PassInstrument : public ffi::ObjectRef {
598 public:
600};
601
607class PassContextObj : public ffi::Object {
608 public:
610 int opt_level{2};
611
613 ffi::Array<ffi::String> required_pass;
615 ffi::Array<ffi::String> disabled_pass;
617 ffi::Map<ffi::String, Any> config;
618
620 ffi::Array<PassInstrument> instruments;
621
622 PassContextObj() = default;
623
630 template <typename T>
631 ffi::Optional<T> GetConfig(const std::string& key) const {
632 if (config.defined()) {
633 auto it = config.find(key);
634 if (it != config.end()) {
635 return (*it).second.as_or_throw<ffi::Optional<T>>();
636 }
637 }
638 return std::nullopt;
639 }
640
647 template <typename TConfig>
648 TConfig GetConfigOrDefault(const std::string& key) const {
649 auto config = GetConfig<TConfig>(key);
650 if (config.has_value()) {
651 return config.value();
652 }
653 return PassConfigWithDefaults<TConfig>();
654 }
655
656 static void RegisterReflection() {
657 namespace refl = tvm::ffi::reflection;
658 refl::ObjectDef<PassContextObj>()
659 .def_ro("opt_level", &PassContextObj::opt_level)
660 .def_ro("required_pass", &PassContextObj::required_pass)
661 .def_ro("disabled_pass", &PassContextObj::disabled_pass)
662 .def_ro("instruments", &PassContextObj::instruments)
663 .def_ro("config", &PassContextObj::config);
664 }
665 TVM_FFI_DECLARE_OBJECT_INFO_FINAL("transform.PassContext", PassContextObj, ffi::Object);
666 // Shared instances are mutated in place, so the class is mutable.
667 static constexpr bool _type_mutable = true;
668};
669
670inline PassContext::PassContext(ffi::UnsafeInit tag, ffi::ObjectPtr<PassContextObj> n)
671 : ffi::ObjectRef(tag) {
672 data_ = std::move(n);
673}
674
676 TVM_FFI_ICHECK(get() != nullptr);
677 return static_cast<const PassContextObj*>(get());
678}
679
681 TVM_FFI_ICHECK(get() != nullptr);
682 return static_cast<PassContextObj*>(get_mutable());
683}
684
686 return PassContext(ffi::UnsafeInit{}, ffi::make_object<PassContextObj>());
687}
688
689inline void PassContext::InstrumentAfterPass(const IRModule& ir_module,
690 const PassInfo& pass_info) const {
691 auto pass_ctx_node = this->operator->();
692 if (pass_ctx_node->instruments.defined()) {
693 for (PassInstrument pi : pass_ctx_node->instruments) {
694 pi->RunAfterPass(ir_module, pass_info);
695 }
696 }
697}
698
699} // namespace transform
700} // namespace tvm
701
702#endif // TVM_IR_TRANSFORM_H_
#define TVM_TIRX_DLL
Definition base.h:55
Managed reference class to IRModuleObj.
Definition module.h:292
RAII wrapper function to enter and exit a context object similar to python's with syntax.
Definition with_context.h:58
PassContextObj contains the information that a pass can rely on, such as analysis results.
Definition transform.h:607
TConfig GetConfigOrDefault(const std::string &key) const
Get a config object, constructing reflection defaults only when absent.
Definition transform.h:648
ffi::Array< PassInstrument > instruments
A list of pass instrument implementations.
Definition transform.h:620
TVM_FFI_DECLARE_OBJECT_INFO_FINAL("transform.PassContext", PassContextObj, ffi::Object)
ffi::Map< ffi::String, Any > config
Pass specific configurations.
Definition transform.h:617
ffi::Array< ffi::String > required_pass
The list of required passes.
Definition transform.h:613
int opt_level
The default optimization level.
Definition transform.h:610
static void RegisterReflection()
Definition transform.h:656
static constexpr bool _type_mutable
Definition transform.h:667
ffi::Array< ffi::String > disabled_pass
The list of disabled passes.
Definition transform.h:615
ffi::Optional< T > GetConfig(const std::string &key) const
Get a config value, returning an empty optional when the key is absent.
Definition transform.h:631
PassContext that is used to configure the pass behavior.
Definition transform.h:64
static TVM_TIRX_DLL ffi::Map< ffi::String, ffi::Map< ffi::String, ffi::String > > ListConfigs()
Get all supported configuration names and metadata, registered within the PassContext.
static constexpr bool _type_is_nullable
Definition transform.h:66
TVM_TIRX_DLL void InstrumentEnterPassContext()
Call instrument implementations' callbacks when entering PassContext. The callbacks are called in ord...
static TVM_TIRX_DLL PassContext Current()
Get the default pass context in the current scope.
static void RegisterConfigOption(const char *key)
Register a valid configuration option and its ValueType for validation.
Definition transform.h:153
TVM_TIRX_DLL void InstrumentExitPassContext()
Call instrument implementations' callbacks when exiting PassContext. The callbacks are called in orde...
friend class Internal
Definition transform.h:205
static PassContext Create()
Construct a PassContext containing the default configurations.
Definition transform.h:685
const PassContextObj * operator->() const
const accessor.
Definition transform.h:675
TVM_TIRX_DLL bool InstrumentBeforePass(const IRModule &mod, const PassInfo &info) const
Call instrument implementations' callbacks before a pass run. The callbacks are called in order,...
PassContext(ffi::UnsafeInit tag)
constructor with UnsafeInit
Definition transform.h:70
void InstrumentAfterPass(const IRModule &mod, const PassInfo &info) const
Call instrument implementations callbacks after a pass run. The callbacks are called in order,...
Definition transform.h:689
TVM_TIRX_DLL bool PassEnabled(const PassInfo &info) const
Check whether a pass is enabled.
Meta data that will be used to help optimization and analysis.
Definition transform.h:232
TVM_FFI_DECLARE_OBJECT_INFO_FINAL("transform.PassInfo", PassInfoObj, ffi::Object)
int opt_level
The minimal optimization level that this pass will be enabled.
Definition transform.h:235
static void RegisterReflection()
Definition transform.h:242
ffi::String name
The name of an optimization/analysis pass.
Definition transform.h:238
Managed reference class for PassInfoObj.
Definition transform.h:255
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(PassInfo, ffi::ObjectRef, PassInfoObj)
PassInfo(int opt_level, ffi::String name)
Constructor.
Definition transform.h:262
PassInstrumentObj forms an instrument implementation. It provides API for users to register callbacks...
Definition transform.h:549
ffi::String name
Name of this pass instrument object.
Definition transform.h:552
TVM_FFI_DECLARE_OBJECT_INFO("transform.PassInstrument", PassInstrumentObj, ffi::Object)
virtual void RunBeforePass(const IRModule &mod, const transform::PassInfo &info) const =0
Instrument before pass run. Called multiple times depend on number of passes.
virtual ~PassInstrumentObj()
Definition transform.h:554
virtual void EnterPassContext() const =0
Instrument when entering PassContext. Called once within a PassContext.
virtual void RunAfterPass(const IRModule &mod, const transform::PassInfo &info) const =0
Instrument after pass run. Called multiple time depend on number of passes.
virtual void ExitPassContext() const =0
Instrument when exiting PassContext. Called once within a PassContext.
virtual bool ShouldRun(const IRModule &mod, const transform::PassInfo &info) const =0
Determine whether to run the pass or not. Called multiple times depend on number of passes.
static void RegisterReflection()
Definition transform.h:586
Managed reference class for PassInstrumentObj.
Definition transform.h:597
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(PassInstrument, ffi::ObjectRef, PassInstrumentObj)
PassObj is the base type of different types of optimization passes. It is designed as a pure class an...
Definition transform.h:277
IRModule operator()(IRModule mod) const
Transform mod using the default PassContext in the current scope.
Definition transform.h:291
virtual IRModule operator()(IRModule mod, const PassContext &pass_ctx) const =0
Transform mod using a functor under a given pass context.
virtual ~PassObj()
Definition transform.h:279
virtual PassInfo Info() const =0
Get the pass information/meta data.
TVM_FFI_DECLARE_OBJECT_INFO("transform.Pass", PassObj, ffi::Object)
Definition transform.h:307
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(Pass, ffi::ObjectRef, PassObj)
TVM_TIRX_DLL IRModule operator()(IRModule mod, const PassContext &pass_ctx) const
Transform mod using a functor under a given pass context.
IRModule operator()(IRModule mod) const
Transform mod using the default PassContext in the current scope.
Definition transform.h:324
The SequentialObj contains a set of passes that transform programs from one AST to another semantical...
Definition transform.h:353
PassInfo Info() const override
Get the pass information/meta data.
Definition transform.h:373
PassInfo pass_info
Definition transform.h:358
SequentialObj(PassInfo pass_info)
Definition transform.h:355
TVM_FFI_DECLARE_OBJECT_INFO_FINAL("transform.Sequential", SequentialObj, PassObj)
static void RegisterReflection()
Definition transform.h:363
tvm::ffi::Array< Pass > passes
A list of passes that used to compose a sequential pass.
Definition transform.h:361
TVM_TIRX_DLL IRModule operator()(IRModule mod, const PassContext &pass_ctx) const final
Perform optimizations on a series of passes. The aforementioned typical pass manager jobs could be do...
SequentialObj(ffi::UnsafeInit tag)
Definition transform.h:356
Definition transform.h:390
const SequentialObj * operator->() const
Definition transform.h:412
TVM_TIRX_DLL Sequential(ffi::Array< Pass > passes, PassInfo pass_info)
The constructor of Sequential.
TVM_TIRX_DLL Sequential(ffi::Array< Pass > passes, ffi::String name="sequential")
The constructor of Sequential.
Sequential(ffi::UnsafeInit tag)
Definition transform.h:410
IRModule that holds the functions and type definitions.
TVM_TIRX_DLL ffi::Error EnrichPassErrorWithContext(const ffi::Error &err, const IRModule &mod, ffi::String pass_name, ffi::Optional< GlobalVar > func=ffi::Optional< GlobalVar >(std::nullopt))
Enrich a pass-time error with a TVMScript-rendered, underlined source location derived from the error...
TVM_TIRX_DLL Pass PrintIR(ffi::String header="")
A special trace pass that prints the header and IR to LOG(INFO).
TVM_TIRX_DLL Pass CreateModulePass(ffi::TypedFunction< IRModule(ffi::RValueRef< IRModule >, PassContext)> pass_func, int opt_level, ffi::String name)
Create a module pass from an owning FFI callback.
TVM_TIRX_DLL ffi::Error EnrichErrorWithContext(const ffi::Error &err, const ffi::ObjectRef &root, ffi::String context="")
Append an underlined TVMScript location from an error's visit context.
TConfig PassConfigWithDefaults()
Create a pass-config object with all default values, using the reflection defaults.
Definition transform.h:216
An object that builds and maintains block scope and StmtSref mapping for Dependence analysis.
Definition analysis.h:41
RAII wrapper function to enter and exit a context object similar to python's with syntax.