tvm_tirx/ir/transform/instrument.rs
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
20//! Pass instruments. A [`BasePassInstrument`] is a [`PassInstrument`] whose hooks are callbacks,
21//! such as Rust closures, that a [`PassContext`](super::PassContext) calls around each pass.
22
23// tvm-ffi-stubgen(file): mod(missing_docs = allow)
24// Names the hand-written wrappers use: the import section keeps them even when no generated block
25// does.
26// tvm-ffi-stubgen(import): crate::ir::module::IRModule
27// tvm-ffi-stubgen(import): crate::ir::transform::core::PassInfo
28// tvm-ffi-stubgen(import): tvm_ffi::AnyView
29// tvm-ffi-stubgen(import): tvm_ffi::Function
30// tvm-ffi-stubgen(import): tvm_ffi::Result
31// tvm-ffi-stubgen(import): tvm_ffi::String
32// tvm-ffi-stubgen(import): crate::ir::support
33
34// tvm-ffi-stubgen(begin): import-section
35use crate::ir::module::IRModule;
36use crate::ir::support;
37use crate::ir::transform::core::PassInfo;
38use crate::ir::transform::core::PassInstrument;
39use crate::ir::transform::core::PassInstrumentObj;
40use std::ops::Deref;
41use tvm_ffi::AnyView;
42use tvm_ffi::Function;
43use tvm_ffi::ObjectArc;
44use tvm_ffi::Result;
45use tvm_ffi::String;
46// tvm-ffi-stubgen(end)
47
48/// An instrument named `name` that calls the hooks it is created with: when a pass context is
49/// entered or exited, and before and after each pass.
50///
51/// # Examples
52///
53/// ```
54/// use std::sync::{Arc, Mutex};
55/// use tvm_tirx::ir::transform::{BasePassInstrument, ModulePass, Pass, PassContext, PassInfo};
56/// use tvm_tirx::ir::transform::PassInstrumentHooks;
57/// use tvm_tirx::ir::{DictAttrs, IRModule};
58/// use tvm_tirx::tvm_ffi::Map;
59///
60/// let log = Arc::new(Mutex::new(Vec::new()));
61/// let sink = log.clone();
62/// let hooks = PassInstrumentHooks {
63/// run_before_pass: Some(Box::new(move |_module, info| {
64/// Ok(sink.lock().unwrap().push(info.name.as_str().to_owned()))
65/// })),
66/// ..Default::default()
67/// };
68/// let tracer = BasePassInstrument::new("tracer", hooks);
69///
70/// let _scope = PassContext::new(2, &[], &[], &[tracer.into()], None)?.enter()?;
71/// let noop = Pass::from(ModulePass::new(|module, _ctx| Ok(module), PassInfo::new(0, "noop")));
72/// noop.run(IRModule::new(Map::new(), DictAttrs::new(Map::new()), Map::new())?)?;
73/// assert_eq!(*log.lock().unwrap(), ["noop"]);
74/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
75/// ```
76// tvm-ffi-stubgen(begin): object/transform.BasePassInstrument
77#[allow(missing_docs)]
78#[repr(C)]
79#[derive(tvm_ffi::derive::ObjectRef, Clone)]
80pub struct BasePassInstrument {
81 data_: ObjectArc<BasePassInstrumentObj>,
82}
83
84/// The object behind [`BasePassInstrument`].
85// Opaque: no metadata of its own: total_size is unknown. Fields are read through the C ABI getters.
86#[allow(missing_docs)]
87#[repr(C)]
88#[derive(tvm_ffi::derive::Object)]
89#[object(type_key = "transform.BasePassInstrument", immutable)]
90pub struct BasePassInstrumentObj {
91 base_: PassInstrumentObj,
92}
93
94impl Deref for BasePassInstrumentObj {
95 type Target = PassInstrumentObj;
96 fn deref(&self) -> &PassInstrumentObj {
97 &self.base_
98 }
99}
100
101tvm_ffi::impl_object_ref_upcast!(BasePassInstrument => PassInstrument);
102// tvm-ffi-stubgen(end)
103
104/// A hook of a [`BasePassInstrument`], called when a pass context is entered or exited.
105///
106/// It may be called from any thread, so it is `Send + Sync`; an error fails the entry or exit.
107pub type PassContextHook = Box<dyn Fn() -> Result<()> + Send + Sync>;
108
109/// A hook of a [`BasePassInstrument`], called with a module and the information of the pass to run
110/// on it; `Send + Sync` like a [`PassContextHook`].
111///
112/// An error fails the pass run.
113pub type PassHook<R> = Box<dyn Fn(IRModule, PassInfo) -> Result<R> + Send + Sync>;
114
115/// The hooks of a [`BasePassInstrument`].
116///
117/// A hook left `None` does nothing, so `..Default::default()` fills in the ones not needed.
118#[derive(Default)]
119pub struct PassInstrumentHooks {
120 /// Called when a pass context with the instrument is entered.
121 pub enter_pass_ctx: Option<PassContextHook>,
122 /// Called when a pass context with the instrument is exited.
123 pub exit_pass_ctx: Option<PassContextHook>,
124 /// Called before a pass runs on the module, to decide whether to run it; a pass the context
125 /// requires runs without asking.
126 pub should_run: Option<PassHook<bool>>,
127 /// Called before a pass runs on the module.
128 pub run_before_pass: Option<PassHook<()>>,
129 /// Called after a pass ran, with the module it returned.
130 pub run_after_pass: Option<PassHook<()>>,
131}
132
133impl BasePassInstrument {
134 /// Create the instrument `name` that calls `hooks` (`transform.PassInstrument`).
135 pub fn new(name: &str, hooks: PassInstrumentHooks) -> Self {
136 let PassInstrumentHooks {
137 enter_pass_ctx,
138 exit_pass_ctx,
139 should_run,
140 run_before_pass,
141 run_after_pass,
142 } = hooks;
143 let enter_pass_ctx = enter_pass_ctx.map(Function::from_typed);
144 let exit_pass_ctx = exit_pass_ctx.map(Function::from_typed);
145 let should_run = should_run.map(Function::from_typed);
146 let run_before_pass = run_before_pass.map(Function::from_typed);
147 let run_after_pass = run_after_pass.map(Function::from_typed);
148 support::infallible(
149 tvm_ffi::cached_global_func!("transform.PassInstrument")
150 .call_packed(&[
151 AnyView::from(&String::from(name)),
152 AnyView::from(&enter_pass_ctx),
153 AnyView::from(&exit_pass_ctx),
154 AnyView::from(&should_run),
155 AnyView::from(&run_before_pass),
156 AnyView::from(&run_after_pass),
157 ])
158 .and_then(|any| any.try_into()),
159 )
160 }
161}
162
163/// Create an instrument that times the passes, for [`render_pass_timing`]
164/// (`transform.instrument.MakePassTimingInstrument`).
165pub fn pass_timing_instrument() -> Result<BasePassInstrument> {
166 tvm_ffi::cached_global_func!("transform.instrument.MakePassTimingInstrument")
167 .call_tuple(())?
168 .try_into()
169}
170
171/// Render the pass times that a [`pass_timing_instrument`] recorded
172/// (`transform.instrument.RenderTimePassProfiles`).
173///
174/// The result has a line per pass timed on this thread, and is empty when none was.
175///
176/// # Errors
177///
178/// Returns an `InternalError` if a pass is still running, as when a pass calls it.
179pub fn render_pass_timing() -> Result<String> {
180 tvm_ffi::cached_global_func!("transform.instrument.RenderTimePassProfiles")
181 .call_tuple(())?
182 .try_into()
183}