tvm_tirx/target.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//! Compilation targets. A [`Target`] describes the device and options code is compiled for, as an
21//! instance of a registered [`TargetKind`]; it is created from a tag, a kind name or a config.
22
23// Every object registered under `target` has its block in this file.
24// tvm-ffi-stubgen(file): mod(missing_docs = allow, prefix = target)
25// `target.Target` is hand-written below: a target is built by parsing its config, never from
26// raw fields.
27// tvm-ffi-stubgen(object): target.Target(skip, ty_map = crate::target::Target)
28// Names the hand-written wrappers use: the import section keeps them even when no generated block
29// does.
30// tvm-ffi-stubgen(import): tvm_ffi::Module
31// tvm-ffi-stubgen(import): crate::ir::module::IRModule
32// tvm-ffi-stubgen(import): tvm_ffi::IntoArg
33// tvm-ffi-stubgen(import): std::borrow::Borrow
34// tvm-ffi-stubgen(import): tvm_ffi::Any
35// tvm-ffi-stubgen(import): tvm_ffi::Map
36// tvm-ffi-stubgen(import): tvm_ffi::object::ObjectRef
37
38// tvm-ffi-stubgen(begin): import-section
39use crate::ir::module::IRModule;
40use std::borrow::Borrow;
41use tvm_ffi::Any;
42use tvm_ffi::Array;
43use tvm_ffi::IntoArg;
44use tvm_ffi::Map;
45use tvm_ffi::Module;
46use tvm_ffi::Object;
47use tvm_ffi::ObjectArc;
48use tvm_ffi::Result;
49use tvm_ffi::String;
50use tvm_ffi::cached_field_getter;
51use tvm_ffi::object::ObjectRef;
52// tvm-ffi-stubgen(end)
53
54/// A compilation target: its `kind`, the `keys` that classify it, such as `cpu`, the `attrs` of
55/// its options, and an optional `host` target for the code that runs on the host. A target may come
56/// from a registered `tag`, such as `nvidia/nvidia-a100`.
57///
58/// # Examples
59///
60/// ```
61/// use tvm_tirx::target::Target;
62///
63/// let cpu = Target::new(r#"{"kind": "llvm", "mcpu": "skylake"}"#)?;
64/// assert!(cpu.as_json()?.as_str().contains(r#""keys":["cpu"]"#));
65/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
66/// ```
67#[allow(missing_docs)]
68#[repr(C)]
69#[derive(tvm_ffi::derive::ObjectRef, Clone)]
70pub struct Target {
71 data_: ObjectArc<TargetObj>,
72}
73
74/// The object behind [`Target`].
75///
76/// Complete: reflected fields fill [24, 72) exactly.
77#[allow(missing_docs)]
78#[repr(C)]
79#[derive(tvm_ffi::derive::Object)]
80#[object(type_key = "target.Target", final)]
81pub struct TargetObj {
82 base_: Object,
83 pub kind: TargetKind,
84 pub host: Option<ObjectRef>,
85 pub tag: String,
86 pub keys: Array<String>,
87 pub attrs: Map<String, Any>,
88}
89
90const _: () = {
91 assert!(::core::mem::size_of::<TargetObj>() == 72);
92 assert!(::core::mem::align_of::<TargetObj>() == 8);
93};
94
95impl Target {
96 /// Create the target that a tag (`"nvidia/nvidia-a100"`), a kind name (`"llvm"`) or a JSON
97 /// config describes (`target.Target`).
98 ///
99 /// # Errors
100 ///
101 /// Returns an error if the tag or the kind is not registered, or the JSON config is invalid.
102 pub fn new(target: &str) -> Result<Self> {
103 tvm_ffi::cached_global_func!("target.Target")
104 .call_tuple((String::from(target),))?
105 .try_into()
106 }
107
108 /// Create the target that a config map describes, such as `{"kind": "cuda", "arch": "sm_80"}`
109 /// or a `tag` with attribute overrides (`target.Target`).
110 ///
111 /// The two-target form of `target.Target`, a target with a host, is [`Target::with_host`].
112 ///
113 /// # Errors
114 ///
115 /// Returns an error if the config is invalid, as [`new`](Self::new) does.
116 pub fn from_config(config: impl Into<Map<String, Any>>) -> Result<Self> {
117 tvm_ffi::cached_global_func!("target.Target").call_tuple((&config.into(),))?.try_into()
118 }
119
120 /// Return the config map that describes the target (`target.TargetExport`).
121 pub fn export(&self) -> Result<Map<String, Any>> {
122 tvm_ffi::cached_global_func!("target.TargetExport").call_tuple((self,))?.try_into()
123 }
124
125 /// Return the target as JSON, which [`new`](Self::new) parses back (`target.TargetAsJSON`).
126 pub fn as_json(&self) -> Result<String> {
127 tvm_ffi::cached_global_func!("target.TargetAsJSON").call_tuple((self,))?.try_into()
128 }
129
130 /// Return a copy of the target with `host` as its host, or none (`target.WithHost`).
131 pub fn with_host(&self, host: Option<&Target>) -> Result<Self> {
132 tvm_ffi::cached_global_func!("target.WithHost")
133 .call_tuple((self, host.cloned()))?
134 .try_into()
135 }
136
137 /// Return the `DLDeviceType` of the devices the target runs on (`target.TargetGetDeviceType`).
138 pub fn get_target_device_type(&self) -> Result<i32> {
139 tvm_ffi::cached_global_func!("target.TargetGetDeviceType").call_tuple((self,))?.try_into()
140 }
141
142 /// Return the `feature.<name>` attribute of the target, or `None` when it has none
143 /// (`target.TargetGetFeature`).
144 pub fn feature(&self, name: &str) -> Result<Option<Any>> {
145 let value = tvm_ffi::cached_global_func!("target.TargetGetFeature")
146 .call_tuple((self, String::from(name)))?;
147 Ok((!value.is_none()).then_some(value))
148 }
149
150 /// Return the names of the registered target kinds (`target.ListTargetKinds`).
151 pub fn list_kinds() -> Result<Array<String>> {
152 tvm_ffi::cached_global_func!("target.ListTargetKinds").call_tuple(())?.try_into()
153 }
154}
155
156/// A kind of target, such as `llvm` or `cuda`: its `name`, the options it takes, and the device
157/// type and keys of its targets by default.
158// tvm-ffi-stubgen(begin): object/target.TargetKind
159#[allow(missing_docs)]
160#[repr(C)]
161#[derive(tvm_ffi::derive::ObjectRef, Clone)]
162pub struct TargetKind {
163 data_: ObjectArc<TargetKindObj>,
164}
165
166/// The object behind [`TargetKind`].
167// Opaque: bytes [56, 152) of [24, 152) are not accounted for by reflected fields. Fields are read through the C ABI getters.
168#[allow(missing_docs)]
169#[repr(C)]
170#[derive(tvm_ffi::derive::Object)]
171#[object(type_key = "target.TargetKind", final)]
172pub struct TargetKindObj {
173 base_: Object,
174}
175
176#[allow(missing_docs)]
177impl TargetKindObj {
178 pub fn name(&self) -> Result<String> {
179 cached_field_getter!(TargetKindObj, "name").get(self)
180 }
181
182 pub fn default_device_type(&self) -> Result<i64> {
183 cached_field_getter!(TargetKindObj, "default_device_type").get(self)
184 }
185
186 pub fn default_keys(&self) -> Result<Array<String>> {
187 cached_field_getter!(TargetKindObj, "default_keys").get(self)
188 }
189}
190// tvm-ffi-stubgen(end)
191
192impl TargetKind {
193 /// Return the type key of each option of the kind, by name (`target.ListTargetKindOptions`).
194 pub fn options(&self) -> Result<Map<String, String>> {
195 tvm_ffi::cached_global_func!("target.ListTargetKindOptions").call_tuple((self,))?.try_into()
196 }
197
198 /// Return the options of the kind named `kind_name`, as [`options`](Self::options) does
199 /// (`target.ListTargetKindOptionsFromName`).
200 ///
201 /// # Errors
202 ///
203 /// Returns an error if no kind is named `kind_name`.
204 pub fn options_from_name(kind_name: &str) -> Result<Map<String, String>> {
205 tvm_ffi::cached_global_func!("target.ListTargetKindOptionsFromName")
206 .call_tuple((String::from(kind_name),))?
207 .try_into()
208 }
209}
210
211/// Return the registered target tags, with their targets (`target.TargetTagListTags`).
212pub fn list_tags() -> Result<Map<String, Target>> {
213 tvm_ffi::cached_global_func!("target.TargetTagListTags").call_tuple(())?.try_into()
214}
215
216/// Register the tag `name` for the target `config` describes, replacing a previous one only if
217/// `override_`, and return that target (`target.TargetTagAddTag`).
218///
219/// # Errors
220///
221/// Returns an error if `name` is already registered and `override_` is `false`.
222///
223/// # Examples
224///
225/// ```
226/// use tvm_tirx::target::{self, Target};
227/// use tvm_tirx::tvm_ffi::{Any, Map, String};
228///
229/// let config: Map<String, Any> =
230/// [("kind".into(), Any::from(String::from("llvm")))].into_iter().collect();
231/// target::register_tag("my_ext/cpu", config, false)?;
232/// assert_eq!(Target::new("my_ext/cpu")?.kind.name()?, "llvm");
233/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
234/// ```
235pub fn register_tag(
236 name: &str,
237 config: impl Into<Map<String, Any>>,
238 override_: bool,
239) -> Result<Target> {
240 tvm_ffi::cached_global_func!("target.TargetTagAddTag")
241 .call_tuple((String::from(name), &config.into(), override_))?
242 .try_into()
243}
244
245/// Generate the code of `module` with the code generator `target.build.<kind>`, such as `llvm`,
246/// `c`, `cuda`, `cuda_host` or `nvptx`.
247///
248/// [`crate::codegen::build_module`] picks the code generator of the target kind.
249///
250/// # Errors
251///
252/// Returns an error if the code generator is not built in, or the error it raises.
253pub fn build(
254 kind: &str,
255 module: impl IntoArg<IRModule>,
256 target: impl IntoArg<Target>,
257) -> Result<Module> {
258 // The code generators are looked up by name: which ones exist depends on the build.
259 tvm_ffi::Function::get_global(&format!("target.build.{kind}"))?
260 .call_tuple((module.into_arg().borrow(), target.into_arg().borrow()))?
261 .try_into()
262}