tvm_tirx/lib.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//! The TIRx compiler in Rust: its IR objects over TVM FFI, and the definition of new types,
21//! operators and passes that extend it.
22//!
23//! The modules:
24//!
25//! - [`ir`]: the IR shared by every dialect, with the primitive expressions in [`ir::prim`] and
26//! the pass infrastructure in [`ir::transform`].
27//! - [`tirx`]: tensor programs: functions, tensor types, layouts, tile instructions, passes and
28//! analyses.
29//! - [`sym`]: symbolic integer analysis.
30//! - [`target`]: compilation targets.
31//! - [`backend`]: backend objects, such as the attributes of CUDA instructions.
32//! - [`runtime`]: runtime objects and queries, and tensor allocation.
33//! - [`codegen`]: compiling IR modules into runtime modules.
34//! - [`script`]: printing IR objects as TVMScript.
35//!
36//! # Using the crate
37//!
38//! The crate links `libtvm_tirx_compiler`, which the build script finds through
39//! `tvm-tirx-config --libdir`; `tvm-tirx-config` and `tvm-ffi-config` must be on `PATH` when the
40//! crate is built. Many of its APIs call global functions of that library, as
41//! [`target::Target::new`] calls `target.Target`, and any global function can also be called
42//! through [`tvm_ffi::Function::get_global`]. A program that calls them only through `tvm_ffi`,
43//! without an API of this crate, must link the library itself
44//! (`tvm-tirx-config --libs compiler`).
45//!
46//! ```
47//! use tvm_tirx::target::Target;
48//! use tvm_tirx::tvm_ffi::{Function, String};
49//!
50//! let target = Target::new("llvm")?;
51//! assert_eq!(target.kind.name()?, "llvm");
52//!
53//! let same = Function::get_global("target.Target")?.call_tuple((String::from("llvm"),))?;
54//! assert_eq!(Target::try_from(same)?.kind.name()?, "llvm");
55//! # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
56//! ```
57//!
58//! A handle such as [`ir::Expr`] is a reference-counted pointer to its object, [`ir::ExprObj`], so
59//! cloning it does not copy the IR. A constructor `new` checks its arguments and fills in defaults,
60//! and returns a `Result` when a check can fail; `from_fields` stores the fields as given.
61//!
62//! # Defining operators and types
63//!
64//! Operators and types are defined in a [`tvm_ffi::static_init_block!`], which runs when the
65//! program or library loads: an operator by an [`ir::OpDef`] chain, a type by
66//! [`tvm_ffi::rs_object`] and [`ir::register_type`].
67//!
68//! ```standalone_crate
69//! use tvm_tirx::ir::op_attr::CALL_EFFECT_KIND;
70//! use tvm_tirx::ir::sig::{self, IntExpr};
71//! use tvm_tirx::ir::{register_type, CallEffectKind, CallObj, Op, OpDef, Type};
72//! use tvm_tirx::tvm_ffi::{self, Result};
73//! # use tvm_tirx::ir::TypeObj;
74//! # use tvm_tirx::tvm_ffi::{rs_object, ObjectRefCore};
75//! # #[rs_object(type_key = "my_ext.PairType", final, immutable)]
76//! # pub struct PairTypeObj { base_: TypeObj, pub first: Type, pub second: Type }
77//! # #[derive(Clone, tvm_ffi::derive::ObjectRef)]
78//! # #[object_ref(parent = Type)]
79//! # pub struct PairType {
80//! # data_: tvm_ffi::ObjectArc<PairTypeObj>,
81//! # }
82//!
83//! fn index_type(call: &CallObj) -> Result<Type> {
84//! Ok(call.args[0].ty.clone())
85//! }
86//!
87//! tvm_ffi::static_init_block! {
88//! OpDef::new("my_ext.clamp", "Clamp an index to the range `[0, bound)`.")
89//! .signature((
90//! sig::arg::<IntExpr>("index", "The index."),
91//! sig::arg::<IntExpr>("bound", "The exclusive upper bound."),
92//! ))
93//! .set_infer_type(index_type)
94//! .set_attr(CALL_EFFECT_KIND, CallEffectKind::Pure);
95//! register_type::<PairType>()?;
96//! }
97//!
98//! let clamp = Op::get("my_ext.clamp")?;
99//! # Ok::<(), tvm_ffi::Error>(())
100//! ```
101//!
102//! A type extends [`ir::TypeObj`]; its fields are reflected, so Python and the TVMScript printer
103//! see them. The generated code names `tvm_ffi`, which `use tvm_tirx::tvm_ffi` brings into scope.
104//!
105//! ```standalone_crate
106//! use tvm_tirx::ir::{PrimType, Type, TypeObj, UNKNOWN_LOC};
107//! use tvm_tirx::tvm_ffi::{self, rs_object, IntoArg, ObjectRefCore};
108//!
109//! #[rs_object(type_key = "my_ext.PairType", final, immutable)]
110//! pub struct PairTypeObj {
111//! base_: TypeObj,
112//! pub first: Type,
113//! pub second: Type,
114//! #[reflect(seq_hash_ignore)]
115//! pub note: tvm_ffi::String,
116//! }
117//!
118//! #[derive(Clone, tvm_ffi::derive::ObjectRef)]
119//! #[object_ref(parent = Type)]
120//! pub struct PairType {
121//! data_: tvm_ffi::ObjectArc<PairTypeObj>,
122//! }
123//!
124//! impl PairType {
125//! pub fn new(first: impl IntoArg<Type>, second: impl IntoArg<Type>) -> Self {
126//! let (first, second) = (first.into_owned(), second.into_owned());
127//! Self::from_object(PairTypeObj::new(TypeObj::new(UNKNOWN_LOC.into()), first, second, ""))
128//! }
129//! }
130//!
131//! fn main() {
132//! let pair = PairType::new(PrimType::int(32), PrimType::float(32));
133//! let ty: Type = pair.into();
134//! assert!(ty.downcast_ref::<PairTypeObj>().is_some());
135//! }
136//! ```
137//!
138//! # The library Python loads
139//!
140//! The crate is also built as `libtvm_tirx_rust`, which `import tvm_tirx` loads, so Python uses the
141//! operators and types the crate defines as it uses the native ones. A `cdylib` of operators of its
142//! own, such as `examples/define_ir.rs`, registers them when Python loads it; a crate it depends on
143//! but never names is not linked in, so name it, as `use my_ops as _;` does.
144//!
145//! # Generated code
146//!
147//! The code between `// tvm-ffi-stubgen(begin)` and `// tvm-ffi-stubgen(end)` is generated, and
148//! the rest is hand-written. Regenerate it with the `tvm-ffi-stubgen` of `3rdparty/tvm-ffi` after
149//! rebuilding `libtvm_tirx_compiler` (`--check` only reports stale blocks):
150//!
151//! ```bash
152//! tvm-ffi-stubgen rust/tvm-tirx/src --target rust --dlls build/lib/libtvm_tirx_compiler.so
153//! ```
154//!
155//! # Tests
156//!
157//! Build `libtvm_tirx_compiler` first. The tests of `src/<path>.rs` are in `tests/<path>.rs`:
158//!
159//! ```bash
160//! uv run --no-sync cargo test --manifest-path rust/Cargo.toml
161//! ```
162
163#![warn(missing_docs)]
164
165pub mod backend;
166pub mod codegen;
167pub mod ir;
168mod r#macro;
169pub mod runtime;
170pub mod script;
171pub mod sym;
172pub mod target;
173pub mod tirx;
174
175pub use tvm_ffi;
176
177// The errors of the static init blocks of every library built on the crate, which
178// `import tvm_tirx` raises for `libtvm_tirx_rust`: `__tvm_ffi_tirx_register_ir`, the TVM FFI
179// function `tirx_register_ir` of the library as `tvm_ffi.load_module` loads it. The module keeps
180// the symbol, which `#[no_mangle]` exports from wherever it is, out of the crate's documentation.
181#[doc(hidden)]
182pub mod exports {
183 tvm_ffi::tvm_ffi_dll_export_typed_func!(tirx_register_ir, tvm_ffi::run_static_init_blocks);
184}
185
186// The crate reaches `libtvm_tirx_compiler` through the FFI registry, so a linker that drops
187// unreferenced libraries (`--as-needed`) would drop the library the build script links, and its
188// registrations would never run. Each TIRx shared library exports a `<library>_link_anchor`
189// function that does nothing, defined in the `link_anchor.cc` of its sources (for the compiler,
190// `src/ir/link_anchor.cc`) and declared by whoever references it. The static below holds the
191// anchor's address: a relocation against the symbol in the object of this module, which costs
192// nothing at run time and is what makes the linker keep the library.
193//
194// A program pulls in only the objects of the crate it references, so the static keeps the
195// library only when the object of this module is pulled. It is, because the objects of the crate
196// reference one another densely and `sym::analyzer` references `ExitOnDrop::new` below. The test
197// binaries rely on the same mechanism and fail at their first registry lookup if that changes. A
198// program that uses the registry only through `tvm_ffi` itself, without calling a wrapper, must
199// keep the library by other means, such as the linker arguments `tvm-tirx-config --libs compiler`
200// prints.
201unsafe extern "C" {
202 fn tvm_tirx_compiler_link_anchor() -> i32;
203}
204
205#[used]
206static TVM_TIRX_COMPILER_LINK_ANCHOR: unsafe extern "C" fn() -> i32 = tvm_tirx_compiler_link_anchor;
207
208/// Makes a scope guard neither `Send` nor `Sync`: the native scopes keep their state per thread,
209/// or in an object that is not synchronized, so a scope must end on the thread that opened it.
210pub(crate) type ThreadBound = std::marker::PhantomData<*const ()>;
211
212/// Calls a native exit function when dropped: the end of a scope a native enter function opened.
213pub(crate) struct ExitOnDrop(tvm_ffi::Function, ThreadBound);
214
215impl ExitOnDrop {
216 pub(crate) fn new(exit: tvm_ffi::Function) -> Self {
217 Self(exit, ThreadBound::default())
218 }
219}
220
221impl Drop for ExitOnDrop {
222 fn drop(&mut self) {
223 // A destructor cannot report the error, and the native exit functions do not fail.
224 let _ = self.0.call_packed(&[]);
225 }
226}