Skip to main content

tvm_tirx/ir/transform/
core.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//! Passes. A [`Pass`] transforms an [`IRModule`] under the current [`PassContext`], which decides
21//! the passes that run and the instruments that observe them; [`ModulePass`] wraps a function and
22//! [`Sequential`] runs passes in order.
23
24// tvm-ffi-stubgen(file): mod(missing_docs = allow)
25// `custom_new` reserves `new` for the checked `transform.PassContext`; the generated `from_fields`
26// allocates the fields as given.
27// tvm-ffi-stubgen(object): transform.PassContext(custom_new)
28// tvm-ffi-stubgen(field): transform.PassInfo.opt_level(type = i32)
29// tvm-ffi-stubgen(field): transform.PassContext.opt_level(type = i32)
30// Names the hand-written wrappers use: the import section keeps them even when no generated block
31// does.
32// tvm-ffi-stubgen(import): crate::ir::module::IRModule
33// tvm-ffi-stubgen(import): crate::ir::support
34// tvm-ffi-stubgen(import): tvm_ffi::IntoArg
35// tvm-ffi-stubgen(import): std::borrow::Borrow
36
37// tvm-ffi-stubgen(begin): import-section
38use crate::ir::module::IRModule;
39use crate::ir::support;
40use std::borrow::Borrow;
41use std::ops::Deref;
42use tvm_ffi::Any;
43use tvm_ffi::Array;
44use tvm_ffi::IntoArg;
45use tvm_ffi::Map;
46use tvm_ffi::Object;
47use tvm_ffi::ObjectArc;
48use tvm_ffi::Result;
49use tvm_ffi::String;
50use tvm_ffi::cached_field_getter;
51// tvm-ffi-stubgen(end)
52
53/// A transformation of an [`IRModule`], with a name and an optimization level ([`PassInfo`]).
54///
55/// [`run`](Self::run) applies it under the current [`PassContext`].
56///
57/// # Examples
58///
59/// ```
60/// use tvm_tirx::ir::transform::{ModulePass, Pass, PassContext, PassInfo, PassInstrument};
61/// use tvm_tirx::ir::transform::Sequential;
62/// use tvm_tirx::ir::{DictAttrs, IRModule, IntImm};
63/// use tvm_tirx::tvm_ffi::Map;
64///
65/// let mark = |name: &'static str| {
66///     let pass = move |module: IRModule, _ctx| module.with_attr(name, IntImm::bool(true));
67///     ModulePass::new(pass, PassInfo::new(0, name))
68/// };
69///
70/// let info = PassInfo::new(0, "pipeline");
71/// let pipeline = Pass::from(Sequential::new([mark("a"), mark("b")], info));
72/// let ctx = PassContext::new(2, &[], &["b"], &[], None)?;
73/// let _scope = ctx.enter()?;
74/// let empty = IRModule::new(Map::new(), DictAttrs::new(Map::new()), Map::new())?;
75/// let module = pipeline.run(empty)?;
76/// assert!(module.get_attr("a")?.is_some() && module.get_attr("b")?.is_none());
77/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
78/// ```
79// tvm-ffi-stubgen(begin): object/transform.Pass
80#[allow(missing_docs)]
81#[repr(C)]
82#[derive(tvm_ffi::derive::ObjectRef, Clone)]
83pub struct Pass {
84    data_: ObjectArc<PassObj>,
85}
86
87/// The object behind [`Pass`].
88// Opaque: no metadata of its own: total_size is unknown. Fields are read through the C ABI getters.
89#[allow(missing_docs)]
90#[repr(C)]
91#[derive(tvm_ffi::derive::Object)]
92#[object(type_key = "transform.Pass")]
93pub struct PassObj {
94    base_: Object,
95}
96// tvm-ffi-stubgen(end)
97
98impl Pass {
99    /// Return the name and optimization level of the pass (`transform.Info`).
100    pub fn info(&self) -> Result<PassInfo> {
101        tvm_ffi::cached_global_func!("transform.Info").call_tuple((self,))?.try_into()
102    }
103
104    /// Run the pass on `module`, which it consumes, under the current pass context
105    /// (`transform.RunPass`).
106    ///
107    /// An instrument's `should_run` hook may skip the pass, unless the context requires it.
108    pub fn run(&self, module: impl IntoArg<IRModule>) -> Result<IRModule> {
109        let module = tvm_ffi::rvalue_ref::RValueRef::new(module.into_owned());
110        tvm_ffi::cached_global_func!("transform.RunPass")
111            .call_packed(&[tvm_ffi::AnyView::from(self), tvm_ffi::AnyView::from(&module)])?
112            .try_into()
113    }
114}
115
116/// The name `name` and optimization level `opt_level` of a pass, by which a [`PassContext`]
117/// requires, disables or skips it.
118// tvm-ffi-stubgen(begin): object/transform.PassInfo
119#[allow(missing_docs)]
120#[repr(C)]
121#[derive(tvm_ffi::derive::ObjectRef, Clone)]
122pub struct PassInfo {
123    data_: ObjectArc<PassInfoObj>,
124}
125
126/// The object behind [`PassInfo`].
127// Complete: reflected fields fill [24, 48) exactly (alignment padding [28, 32)).
128#[allow(missing_docs)]
129#[repr(C)]
130#[derive(tvm_ffi::derive::Object)]
131#[object(type_key = "transform.PassInfo", final, immutable)]
132pub struct PassInfoObj {
133    base_: Object,
134    pub opt_level: i32,
135    pub name: String,
136}
137
138const _: () = {
139    assert!(::core::mem::size_of::<PassInfoObj>() == 48);
140    assert!(::core::mem::align_of::<PassInfoObj>() == 8);
141};
142
143#[allow(missing_docs)]
144impl PassInfoObj {
145    pub(crate) fn new(opt_level: i32, name: String) -> Self {
146        let base_ = Object::new();
147        Self { base_, opt_level, name }
148    }
149}
150
151#[allow(missing_docs)]
152impl PassInfo {
153    /// Create a `PassInfo` from its field values.
154    pub fn new(opt_level: i32, name: impl Into<String>) -> Self {
155        let obj = PassInfoObj::new(opt_level, name.into());
156        Self { data_: ObjectArc::new(obj) }
157    }
158}
159// tvm-ffi-stubgen(end)
160
161// `PassInfo::new` above has the semantics of the native `transform.PassInfo`, which only stores
162// its fields.
163
164/// A pass that applies a function to the whole module.
165// tvm-ffi-stubgen(begin): object/transform.ModulePass
166#[allow(missing_docs)]
167#[repr(C)]
168#[derive(tvm_ffi::derive::ObjectRef, Clone)]
169pub struct ModulePass {
170    data_: ObjectArc<ModulePassObj>,
171}
172
173/// The object behind [`ModulePass`].
174// Opaque: parent 'transform.Pass' is opaque (layout-unknown). Fields are read through the C ABI getters.
175#[allow(missing_docs)]
176#[repr(C)]
177#[derive(tvm_ffi::derive::Object)]
178#[object(type_key = "transform.ModulePass", final, immutable)]
179pub struct ModulePassObj {
180    base_: PassObj,
181}
182
183impl Deref for ModulePassObj {
184    type Target = PassObj;
185    fn deref(&self) -> &PassObj {
186        &self.base_
187    }
188}
189
190#[allow(missing_docs)]
191impl ModulePassObj {
192    pub fn pass_info(&self) -> Result<PassInfo> {
193        cached_field_getter!(ModulePassObj, "pass_info").get(self)
194    }
195}
196
197tvm_ffi::impl_object_ref_upcast!(ModulePass => Pass);
198// tvm-ffi-stubgen(end)
199
200impl ModulePass {
201    /// Create a pass that applies `pass_func` to the module it runs on, which `pass_func` receives
202    /// by value with the pass context (`transform.MakeModulePass`).
203    ///
204    /// The pass may run on any thread, so `pass_func` is `Send + Sync`.
205    pub fn new(
206        pass_func: impl Fn(IRModule, PassContext) -> Result<IRModule> + Send + Sync + 'static,
207        pass_info: impl IntoArg<PassInfo>,
208    ) -> Self {
209        let pass_func = tvm_ffi::Function::from_typed(
210            move |module: tvm_ffi::rvalue_ref::RValueRef<IRModule>, ctx: PassContext| {
211                pass_func(module.into_inner(), ctx)
212            },
213        );
214        support::infallible(
215            tvm_ffi::cached_global_func!("transform.MakeModulePass")
216                .call_tuple((&pass_func, pass_info.into_arg().borrow()))
217                .and_then(|any| any.try_into()),
218        )
219    }
220}
221
222/// A pass that runs a list of passes in order, skipping the ones the current [`PassContext`] does
223/// not enable.
224// tvm-ffi-stubgen(begin): object/transform.Sequential
225#[allow(missing_docs)]
226#[repr(C)]
227#[derive(tvm_ffi::derive::ObjectRef, Clone)]
228pub struct Sequential {
229    data_: ObjectArc<SequentialObj>,
230}
231
232/// The object behind [`Sequential`].
233// Opaque: parent 'transform.Pass' is opaque (layout-unknown). Fields are read through the C ABI getters.
234#[allow(missing_docs)]
235#[repr(C)]
236#[derive(tvm_ffi::derive::Object)]
237#[object(type_key = "transform.Sequential", final, immutable)]
238pub struct SequentialObj {
239    base_: PassObj,
240}
241
242impl Deref for SequentialObj {
243    type Target = PassObj;
244    fn deref(&self) -> &PassObj {
245        &self.base_
246    }
247}
248
249#[allow(missing_docs)]
250impl SequentialObj {
251    pub fn pass_info(&self) -> Result<PassInfo> {
252        cached_field_getter!(SequentialObj, "pass_info").get(self)
253    }
254
255    pub fn passes(&self) -> Result<Array<Pass>> {
256        cached_field_getter!(SequentialObj, "passes").get(self)
257    }
258}
259
260tvm_ffi::impl_object_ref_upcast!(Sequential => Pass);
261// tvm-ffi-stubgen(end)
262
263impl Sequential {
264    /// Create a pass named by `pass_info` that runs `passes` in order; a pipeline with only a name
265    /// takes `PassInfo::new(0, name)`.
266    ///
267    /// It skips the passes the current pass context disables, and those whose level exceeds the
268    /// context's `opt_level` unless the context requires them.
269    pub fn new(
270        passes: impl IntoIterator<Item = impl IntoArg<Pass>>,
271        pass_info: impl IntoArg<PassInfo>,
272    ) -> Self {
273        let passes = passes.into_iter().map(IntoArg::into_owned).collect::<Array<Pass>>();
274        let pass_info = pass_info.into_arg();
275        let pass_info: &PassInfo = pass_info.borrow();
276        support::infallible(
277            tvm_ffi::cached_global_func!("transform.Sequential")
278                .call_tuple((&passes, pass_info.opt_level, &pass_info.name))
279                .and_then(|any| any.try_into()),
280        )
281    }
282}
283
284/// The settings passes run under: the optimization level `opt_level`, the passes in
285/// `required_pass` and `disabled_pass`, the configuration options `config` and the
286/// `instruments`.
287///
288/// [`enter`](Self::enter) makes it the current context of the thread.
289// tvm-ffi-stubgen(begin): object/transform.PassContext
290#[allow(missing_docs)]
291#[repr(C)]
292#[derive(tvm_ffi::derive::ObjectRef, Clone)]
293pub struct PassContext {
294    data_: ObjectArc<PassContextObj>,
295}
296
297/// The object behind [`PassContext`].
298// Complete: reflected fields fill [24, 64) exactly (alignment padding [28, 32)).
299#[allow(missing_docs)]
300#[repr(C)]
301#[derive(tvm_ffi::derive::Object)]
302#[object(type_key = "transform.PassContext", final)]
303pub struct PassContextObj {
304    base_: Object,
305    pub opt_level: i32,
306    pub required_pass: Array<String>,
307    pub disabled_pass: Array<String>,
308    pub config: Map<String, Any>,
309    pub instruments: Array<PassInstrument>,
310}
311
312const _: () = {
313    assert!(::core::mem::size_of::<PassContextObj>() == 64);
314    assert!(::core::mem::align_of::<PassContextObj>() == 8);
315};
316
317#[allow(missing_docs)]
318impl PassContextObj {
319    pub(crate) fn new(
320        opt_level: i32,
321        required_pass: Array<String>,
322        disabled_pass: Array<String>,
323        config: Map<String, Any>,
324        instruments: Array<PassInstrument>,
325    ) -> Self {
326        let base_ = Object::new();
327        Self { base_, opt_level, required_pass, disabled_pass, config, instruments }
328    }
329}
330
331#[allow(missing_docs)]
332impl PassContext {
333    /// Create a `PassContext` from its field values.
334    pub fn from_fields(
335        opt_level: i32,
336        required_pass: impl Into<Array<String>>,
337        disabled_pass: impl Into<Array<String>>,
338        config: impl Into<Map<String, Any>>,
339        instruments: impl Into<Array<PassInstrument>>,
340    ) -> Self {
341        let obj = PassContextObj::new(
342            opt_level,
343            required_pass.into(),
344            disabled_pass.into(),
345            config.into(),
346            instruments.into(),
347        );
348        Self { data_: ObjectArc::new(obj) }
349    }
350}
351// tvm-ffi-stubgen(end)
352
353impl PassContext {
354    /// Create a pass context with `config` checked and converted to the registered option types;
355    /// `None` is the empty configuration (`transform.PassContext`).
356    ///
357    /// A pass in `disabled_pass`, or above `opt_level` and not in `required_pass`, is skipped.
358    ///
359    /// # Errors
360    ///
361    /// Returns an `AttributeError` if `config` has an option that is not registered or a `None`
362    /// value, or the error of converting a value to its option type.
363    pub fn new(
364        opt_level: i32,
365        required_pass: &[&str],
366        disabled_pass: &[&str],
367        instruments: &[PassInstrument],
368        config: impl Into<Option<Map<String, Any>>>,
369    ) -> Result<Self> {
370        let required_pass = required_pass.iter().copied().map(String::from).collect::<Array<_>>();
371        let disabled_pass = disabled_pass.iter().copied().map(String::from).collect::<Array<_>>();
372        let instruments = instruments.iter().cloned().collect::<Array<PassInstrument>>();
373        tvm_ffi::cached_global_func!("transform.PassContext")
374            .call_tuple((opt_level, &required_pass, &disabled_pass, &instruments, config.into()))?
375            .try_into()
376    }
377
378    /// Return the innermost pass context in effect on this thread, or the default one when there is
379    /// none (`transform.GetCurrentPassContext`).
380    pub fn current() -> Result<Self> {
381        tvm_ffi::cached_global_func!("transform.GetCurrentPassContext").call_tuple(())?.try_into()
382    }
383
384    /// Make this the current pass context until the returned [`PassContextScope`] is dropped
385    /// (`transform.EnterPassContext`, `transform.ExitPassContext`).
386    ///
387    /// # Errors
388    ///
389    /// Returns the error of an instrument's `enter_pass_ctx` hook; the instruments entered before
390    /// it are exited, and the context's instruments are cleared.
391    pub fn enter(&self) -> Result<PassContextScope> {
392        tvm_ffi::cached_global_func!("transform.EnterPassContext").call_tuple((self,))?;
393        Ok(PassContextScope(self.clone(), crate::ThreadBound::default()))
394    }
395
396    /// Replace the instruments with `instruments`, exiting the old ones and entering the new ones
397    /// (`transform.OverrideInstruments`).
398    ///
399    /// # Errors
400    ///
401    /// Returns the error of an old instrument's `exit_pass_ctx` hook or a new one's
402    /// `enter_pass_ctx` hook, after which the context has no instruments.
403    pub fn override_instruments(
404        &self,
405        instruments: impl IntoIterator<Item = impl IntoArg<PassInstrument>>,
406    ) -> Result<()> {
407        let instruments =
408            instruments.into_iter().map(IntoArg::into_owned).collect::<Array<PassInstrument>>();
409        tvm_ffi::cached_global_func!("transform.OverrideInstruments")
410            .call_tuple((self, &instruments))?;
411        Ok(())
412    }
413
414    /// Return the registered configuration options, each with its metadata such as its `type`
415    /// (`transform.ListConfigs`).
416    pub fn list_configs() -> Result<Map<String, Map<String, String>>> {
417        tvm_ffi::cached_global_func!("transform.ListConfigs").call_tuple(())?.try_into()
418    }
419}
420
421/// A scope in which a pass context is the current one, returned by [`PassContext::enter`].
422///
423/// The entered contexts are a stack of the thread: a scope stays on its thread, and the innermost
424/// scope is dropped first.
425///
426/// # Examples
427///
428/// ```
429/// use tvm_tirx::ir::transform::{PassContext, PassInstrument};
430///
431/// let outer = PassContext::new(3, &[], &[], &[], None)?;
432/// let inner = PassContext::new(1, &[], &[], &[], None)?;
433/// let outer_scope = outer.enter()?;
434/// let inner_scope = inner.enter()?;
435/// assert_eq!(PassContext::current()?.opt_level, 1);
436///
437/// drop(inner_scope);
438/// assert_eq!(PassContext::current()?.opt_level, 3);
439/// drop(outer_scope);
440/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
441/// ```
442///
443/// A scope cannot move to another thread:
444///
445/// ```compile_fail
446/// fn send<T: Send>() {}
447/// send::<tvm_tirx::ir::transform::PassContextScope>();
448/// ```
449#[must_use = "the pass context is exited when the scope is dropped"]
450pub struct PassContextScope(PassContext, crate::ThreadBound);
451
452impl Drop for PassContextScope {
453    fn drop(&mut self) {
454        // A destructor cannot report the error, and exiting the innermost context does not fail.
455        let _ = tvm_ffi::cached_global_func!("transform.ExitPassContext").call_tuple((&self.0,));
456    }
457}
458
459/// The base of instruments, which a [`PassContext`] calls around each pass it runs, such as to
460/// trace or time them.
461// tvm-ffi-stubgen(begin): object/transform.PassInstrument
462#[allow(missing_docs)]
463#[repr(C)]
464#[derive(tvm_ffi::derive::ObjectRef, Clone)]
465pub struct PassInstrument {
466    data_: ObjectArc<PassInstrumentObj>,
467}
468
469/// The object behind [`PassInstrument`].
470// Opaque: bytes [40, 48) of [24, 48) are not accounted for by reflected fields. Fields are read through the C ABI getters.
471#[allow(missing_docs)]
472#[repr(C)]
473#[derive(tvm_ffi::derive::Object)]
474#[object(type_key = "transform.PassInstrument", immutable)]
475pub struct PassInstrumentObj {
476    base_: Object,
477}
478
479#[allow(missing_docs)]
480impl PassInstrumentObj {
481    pub fn name(&self) -> Result<String> {
482        cached_field_getter!(PassInstrumentObj, "name").get(self)
483    }
484}
485// tvm-ffi-stubgen(end)
486
487/// Create a pass that logs `header` and the module, which it returns unchanged
488/// (`transform.PrintIR`).
489pub fn print_ir(header: &str) -> Result<Pass> {
490    tvm_ffi::cached_global_func!("transform.PrintIR")
491        .call_tuple((String::from(header),))?
492        .try_into()
493}