Working with IR in Rust#

The tvm-tirx crate lets a Rust function read, build, and rewrite TIRx IR. The function can receive a program written in TVMScript and return the result, and nothing is converted or copied along the way. This guide covers:

  • TVM-FFI object system: how IR nodes are represented and used in Rust.

  • Structural utilities: walk, map, and compare programs.

  • Visitors and mutators: keep state and control the traversal.

  • Constraint-aware traversal: use the facts that hold at each node.

Note

The runnable code in this guide is under examples/ir_guides in the repository.

Setting Up#

The examples are packaged as tirx_ir_guide_examples under examples/ir_guides. When cargo is available, installing the package builds the Rust crate in rust/ into a library; CMakeLists.txt and pyproject.toml in the same directory show how. The crate depends on the tvm-tirx crate of this checkout, so install TIRx from the same source tree. We install without build isolation to build against that installation instead of fetching one from PyPI:

pip install scikit-build-core
pip install --no-build-isolation -e examples/ir_guides

A static_init_block! at the end of the crate registers each example as a global function under tirx_ir_guide_examples.rust:

tvm_ffi::Function::register_global_typed(
    "tirx_ir_guide_examples.rust.construct",
    construct,
    "Build x * 2 + 1.",
)?;

The package’s tirx_ir_guide_examples.rust module loads the library and exposes these functions, so Python calls them by name. The driver working_with_ir_in_rust.py calls each example this way and prints the result.

The object system examples take no arguments: each builds its own IR in Rust. The later sections receive the add_one function from Quick Start, written in TVMScript:

from tvm_tirx.script import tirx as T

n = T.dynamic("n")


@T.function
def add_one(A: T.Tensor((n,), T.float32), B: T.Tensor((n,), T.float32)):
    for i in range(n):
        B[i] = A[i] + 1
import tirx_ir_guide_examples.rust

tirx_ir_guide_examples.rust.construct()
tirx_ir_guide_examples.rust.written_tensors(add_one)

TVM-FFI Object System#

Every TIRx IR node is a TVM-FFI object. Rust IRs are typically built as enums and matched with match, which works well when every node type is known in advance. TIRx is designed for dynamic extension instead: a library can add a new node type, for example a new statement for a hardware feature, and existing code keeps working on programs that contain it. Generic utilities such as walking, rewriting, comparing, and printing work on every node through its registered fields.

TVM-FFI objects also work across languages. Python, C++, and Rust share the same native, immutable, reference-counted objects, so a program moves between them without conversion.

We designed the TVM-FFI object system to be ergonomic in Rust. The key constructs are:

Construct

Purpose

Constructors, expression operators

Build expressions with ordinary Rust operators

FooObj / Foo

Underlying object and its named managed reference: read fields directly, clone cheaply

.into()

Convert to a parent type

.downcast()

Convert to a child type, with a checked Result

match_any!

Branch on the node type

#[dispatch]

Write one method per node type; the attribute generates the match

The subsections below introduce each construct.

Constructing Objects#

We build IR with constructors and ordinary Rust operators. Writing x * 2 + 1 as nested constructor calls would bury the expression, so the crate lets us write it as we would in Rust. Let’s build it:

fn x_times_2_plus_1() -> Result<(PrimVar, PrimExpr)> {
    let x = PrimVar::new("x", PrimType::int(32), UNKNOWN_LOC);
    let expr = (&x * 2 + 1).try_into()?;
    Ok((x, expr))
}

fn construct() -> Result<tvm_ffi::String> {
    let (_, expr) = x_times_2_plus_1()?;
    script(&expr)
}

The output is:

x * 2 + 1

PrimVar::new takes a name, a primitive type, and a source location; UNKNOWN_LOC means there is none. The operators * and + build IR directly from x, and the literals 2 and 1 become constants of its type.

The operators take a PrimExpr, an expression whose type is a PrimType. x is a PrimVar, a variable of a primitive type, because a plain Var may have any type: it takes part in arithmetic only after downcast_ref::<PrimVar>() or downcast::<PrimVar>() checks it, and &var + 1 does not compile.

An operator can still fail, for example on mismatched types, so ExprResult carries the first error along, much like a chain of Results. The standard .try_into() conversion extracts a PrimExpr, and ? passes an error on. script prints the node as TVMScript.

We now have an expression; next, let’s see what kind of Rust value it is.

Objects and Managed References#

Every node type comes as a pair: an underlying object and a named managed reference. The top of x * 2 + 1 is an addition, so let’s convert the expression to Add with try_into, which the next subsection explains, and read its two operands:

fn objects() -> Result<Strings> {
    let (_, expr) = x_times_2_plus_1()?;
    let add: Add = expr.try_into()?;
    let alias = add.clone();
    Ok(lines([
        format!("a = {}", script(&add.a)?.as_str()),
        format!("b = {}", script(&add.b)?.as_str()),
        format!("same object: {}", alias.same_as(&add)),
    ]))
}

The output is:

a = x * 2
b = 1
same object: true

alias is the same object as add: clone copies only the managed reference, and same_as compares identity, like Arc::ptr_eq.

AddObj is the underlying object: the struct that holds the fields. Add is a named managed reference to it: an owning, reference-counted smart pointer, like Arc<AddObj>, so cloning it is cheap. Functions take and return managed references, and a managed reference dereferences to its object, so fields read as ordinary struct fields: add.a.

We define a separate named type Add instead of using a plain pointer to AddObj because the named type carries the interface: constructors, methods, conversions to parent types, and the traits that let it pass through TVM-FFI functions. It can also impose additional constraints on the underlying object that the object alone does not express.

This is the newtype pattern. Simplified from the crate, the pair is:

#[repr(C)]
#[derive(Object)]
#[object(type_key = "prim.Add", immutable)]
pub struct AddObj {
    base_: ExprObj,
    pub a: PrimExpr,
    pub b: PrimExpr,
}

#[repr(C)]
#[derive(ObjectRef, Clone)]
pub struct Add {
    data_: ObjectArc<AddObj>,
}

Rust has no inheritance; instead, #[repr(C)] puts the parent’s object, ExprObj, first in AddObj, so every addition is also an expression. Add implements Deref to AddObj, which is why add.a works. AddObj has the same memory layout as the native object, so add.a is a direct field read.

Nodes are immutable. As with data behind an Arc, a managed reference gives read access only; to change a node, we build a new one.

We reached Add with a cast; next, let’s look at casts on their own.

Casts#

Casts move a managed reference up and down the type hierarchy. A function that takes any expression wants an Expr, while reading the operands needs an Add. .into() converts to a parent type through From/Into and cannot fail. .try_into(), or T::try_from, converts to a child type: it checks the node’s actual type and fails with a TypeError naming both types, ready for ?. try_from(&value) borrows and clones only on success.

fn casts() -> Result<Strings> {
    let (_, expr) = x_times_2_plus_1()?;
    let add: Add = expr.try_into()?;
    let value: Expr = add.into();
    let again = Add::try_from(&value)?;
    let mut out = vec![format!("back to Add: {}", script(&again)?.as_str())];
    // A wrong guess is a `TypeError` naming both types.
    if let Err(err) = Mul::try_from(&value) {
        out.push(format!("as Mul: {}", err.message()));
    }
    Ok(lines(out))
}

The output is:

back to Add: x * 2 + 1
as Mul: Cannot convert from type `prim.Add` to `prim.Mul`

value is an Expr again, but the node behind it is still an addition, so the cast back to Add succeeds.

What if we guess wrong? The cast to Mul fails with a TypeError that names both type keys: the actual type prim.Add and the requested prim.Mul.

Note

To try several types in turn, value.downcast::<Add>() takes the reference and hands it back unchanged in Err, as Box<dyn Any>::downcast does in the standard library. For read-only inspection, value.downcast_ref::<Add>() returns Option<&Add> without consuming or cloning the reference. Any and AnyView provide the same borrowed downcast.

Casting to one type at a time gets tedious when a node can be one of many; that is what matching is for.

Matching Node Types#

match_any! branches on the actual type of a node, as match does on an enum. Let’s print an expression with explicit parentheses by matching each node and recursing into its operands:

fn describe(expr: &PrimExpr) -> Result<String> {
    let text = match_any! {
        expr {
            Add(ref add) => format!("({} + {})", describe(&add.a)?, describe(&add.b)?),
            Mul(ref mul) => format!("({} * {})", describe(&mul.a)?, describe(&mul.b)?),
            Var(ref var) => var.name.as_str().to_owned(),
            IntImm(ref imm) => imm.value.to_string(),
            _ => "<other>".to_owned(),
        }
    };
    Ok(text)
}

We call it on x * 2 + 1 and on x - 1:

fn matching() -> Result<Strings> {
    let (x, expr) = x_times_2_plus_1()?;
    let difference = (&x - 1).try_into()?;
    Ok(lines([describe(&expr)?, describe(&difference)?]))
}

The output is:

((x * 2) + 1)
<other>

Each arm of the match pairs a pattern with code; here each pattern names an object type and borrows the matching node with ref. The first matching arm runs. The AddObj and MulObj arms recurse into the operands, the VarObj and IntImmObj arms end the recursion, and x - 1 falls to the _ arm because describe has no arm for subtraction.

The catch-all arm keeps existing code working as node types are added. The set of node types is open, like a #[non_exhaustive] enum from another crate, so the match needs a _ arm. A function handles the types it knows, and _ lets programs with new types pass through.

Note

Obj(ref node) borrows the underlying object without incrementing its reference count. describe converts expr to an AnyView. An owning arm such as Add(add) still produces a managed reference. match_any! also works on Any and AnyView values, including tensors, shapes, and typed arrays. Plain values such as integers take the _ arm in this example.

describe puts parentheses around every operation. To add them only where they are needed, each node needs to know whether it is nested, so let’s give each node type its own method that takes that context.

Dispatching on Node Types#

A common need in a compiler is to dispatch over many kinds of IR nodes: run different logic depending on which kind a value is. match_any! provides the machinery, and #[dispatch] makes such dispatchers simpler to build: write one method per node type, and the attribute generates the match that picks between them. Let’s print additions with parentheses only where they nest:

struct Printer;

#[dispatch(print, (AnyView<'_>, bool), String)]
impl Printer {
    fn print_add(&self, add: &Add, nested: bool) -> String {
        let text = format!("{} + {}", self.show(&add.a, true), self.show(&add.b, true));
        if nested { format!("({text})") } else { text }
    }

    fn print_var(&self, var: &Var) -> String {
        var.name.as_str().to_owned()
    }

    fn print_imm(&self, imm: &IntImm) -> String {
        imm.value.to_string()
    }

    fn show(&self, expr: &PrimExpr, nested: bool) -> String {
        let text = self.dispatch(AnyView::from(expr), nested);
        text.unwrap_or_else(|| "<other>".to_owned())
    }
}

We print x + 1 + 2:

fn print() -> Result<tvm_ffi::String> {
    let x = PrimVar::new("x", PrimType::int(32), UNKNOWN_LOC);
    let expr = (&x + 1 + 2).try_into()?;
    Ok(Printer.show(&expr, false).into())
}

The output is:

(x + 1) + 2

The #[dispatch(print, (AnyView<'_>, bool), String)] attribute makes the print_* methods handlers and generates dispatch(value, nested) -> Option<String>. The first element of the tuple is the value to match; the rest are passed to the handlers. print_add passes nested = true to its operands, so the inner addition gets parentheses and the outer one does not. show is an ordinary method: it calls dispatch and turns None, which means no handler matched, into "<other>".

The attribute is sugar for a match. Simplified, #[dispatch] generates a match_any! and a Dispatcher implementation:

impl Printer {
    pub fn dispatch(&self, value: AnyView<'_>, nested: bool) -> Option<String> {
        match_any! {
            value {
                Add(ref node) => Some(self.print_add(node, nested).into()),
                Var(ref node) => Some(self.print_var(node).into()),
                IntImm(ref node) => Some(self.print_imm(node).into()),
                _ => None,
            }
        }
    }
}

impl Dispatcher<(AnyView<'_>, bool), Option<String>> for &Printer {
    fn dispatch_tuple(self, (value, nested): (AnyView<'_>, bool)) -> Option<String> {
        Printer::dispatch(self, value, nested)
    }
}

Each handler becomes one arm, in source order, and its parameter type selects the nodes it matches. The attribute appends _ => None, so a type without a handler returns None instead of failing. The Dispatcher implementation lets generic code call the same match through one trait.

A handler takes only the arguments it needs. It receives the matched value and a leading prefix of the remaining arguments, in declaration order: print_add takes nested, while print_var and print_imm omit it.

The structural utilities below accept the same kind of dispatcher: walk, visit, map, and mutate each call the dispatcher on the nodes they reach. The prefix only names the methods; the utility that calls the dispatcher decides what happens to the result.

Structural Utilities#

The structural utilities are part of TVM-FFI, and the tvm_ffi crate, re-exported as tvm_tirx::tvm_ffi, provides them in Rust: structural_walk, structural_map, structural_visit, and structural_mutate. They work on every node through its registered fields and keep definitions and uses consistent. Each piece takes a Rust form:

Piece

Rust form

Nodes a callback receives

Selected by the type of the callback’s parameter

Walk callback result

WalkResult, or Result<WalkResult> to use ?

Traversal order

A required argument, WalkOrder::PreOrder or PostOrder

Result of a map

An Any, converted back with try_into

Definition region kind

A trailing DefRegionKind parameter

Errors

Result values

Structural equality

structural_equal, and structural_hash consistent with it

Structural Walk#

A walk calls our callback on each node of the type it asks for. Let’s find the tensors that add_one writes:

fn written_tensors(func: Function) -> Result<Strings> {
    let mut writes = Vec::new();
    let on_store = |store: TensorStore| -> Result<WalkResult> {
        let dest = Var::try_from(&store.dest)?;
        writes.push(dest.name.clone());
        Ok(WalkResult::Advance)
    };
    tvm_ffi::structural_walk(&func, on_store, WalkOrder::PostOrder)?;
    Ok(writes.into_iter().collect())
}

The output is:

['B']

on_store takes a TensorStore, so the walk calls it only on stores. Strings is our alias for Array<tvm_ffi::String>, which Python receives as a list of strings.

WalkResult::Advance continues into the node’s children, Skip does not descend into them, and Interrupt stops the whole walk.

The parameter list of a callback decides what it receives:

Callback

Receives

|store: TensorStore|

Each write, as a managed reference.

|store: &TensorStore|

Each write, borrowed in place, without changing its reference count.

|value: AnyView<'_>|

Every value the walk reaches.

|var: Var, kind: DefRegionKind|

Each variable, with its definition region kind.

(on_loop, on_store)

A tuple of callbacks, tried in order; only the first one whose type matches a node runs. Tuples hold up to 12 callbacks and can be nested.

WalkResult::InterruptWith stops the walk and returns a value, which lets a walk search for a node:

fn first_write(func: Function) -> Result<Option<TensorStore>> {
    let find_write = |store: TensorStore| WalkResult::InterruptWith(store.into());
    let found = tvm_ffi::structural_walk(&func, find_write, WalkOrder::PostOrder)?;
    match found {
        Some(interrupt) => Ok(Some(interrupt.value.clone().try_into()?)),
        None => Ok(None),
    }
}

Python prints the dest.name of the store it receives. The output is:

B

structural_walk returns Ok(Some(interrupt)) when a callback stops it, with the payload in interrupt.value, and Ok(None) otherwise.

A walk also accepts a #[dispatch] struct, which keeps state across node types. #[dispatch(walk, (AnyView<'_>, DefRegionKind), Result<WalkResult>)] matches the arguments and result of a walk callback. Let’s count the variables and additions:

#[derive(Default)]
struct Counter {
    vars: usize,
    adds: usize,
}

#[dispatch(walk, (AnyView<'_>, DefRegionKind), Result<WalkResult>)]
impl Counter {
    fn walk_var(&mut self, _var: &Var, _kind: DefRegionKind) -> Result<WalkResult> {
        self.vars += 1;
        Ok(WalkResult::Advance)
    }

    fn walk_add(&mut self, _add: &Add) -> Result<WalkResult> {
        self.adds += 1;
        Ok(WalkResult::Advance)
    }
}

We walk x * 2 + 1 with it, visiting each node before its children:

fn count() -> Result<tvm_ffi::String> {
    let (_, expr) = x_times_2_plus_1()?;
    let mut counter = Counter::default();
    tvm_ffi::structural_walk(&expr, &mut counter, WalkOrder::PreOrder)?;
    Ok(format!("variables: {}, additions: {}", counter.vars, counter.adds).into())
}

The output is:

variables: 1, additions: 1

Node types without a handler fall back to the default traversal: the dispatcher returns None, and the walk continues into their children, so new types pass through. Here the multiplication and the constants have no handler, and the walk still reaches x inside the multiplication.

Definitions and Uses#

A callback receives the definition region kind when it takes a DefRegionKind as its last parameter. This walk lists the definition sites of add_one:

fn definitions(func: Function) -> Result<Strings> {
    let mut sites = Vec::new();
    let show_definition = |var: Var, kind: DefRegionKind| {
        if kind != DefRegionKind::None {
            sites.push(format!("{} {:?}", var.name.as_str(), kind));
        }
        WalkResult::Advance
    };
    tvm_ffi::structural_walk(&func, show_definition, WalkOrder::PreOrder)?;
    Ok(sites.iter().map(tvm_ffi::String::from).collect())
}

The output is:

A Pattern
n Pattern
B Pattern
n Pattern
i Simple

DefRegionKind::None marks a use site; Pattern and Simple are the two kinds of definition site. A parameter is a Pattern definition: everything inside it is defined there, including the n in its shape. The loop variable i is a Simple definition: only the variable itself is defined. structural_map callbacks take the same trailing parameter.

Structural Map#

A map callback returns the replacement for its node. Let’s specialize add_one for n = 128, with n passed in from Python:

fn specialize(func: Function, n: Var, value: i64) -> Result<Function> {
    let specialize_var = |var: Var| -> Result<Expr> {
        if var.same_as(&n) {
            let ty = PrimType::try_from(&var.ty)?;
            return Ok(make_const(ty, value)?.into());
        }
        Ok(var.into())
    };
    tvm_ffi::structural_map(func, specialize_var, WalkOrder::PostOrder)?.try_into()
}

The output is:

from __future__ import annotations

# from tvm_tirx.script import tirx as T

@T.function
def add_one(A: T.Tensor((128,), T.float32), B: T.Tensor((128,), T.float32)):
    for i in range(128):
        B[i] = A[i] + T.float32(1.0)

make_const builds the constant 128 with the type of n, and every other variable is returned as it is. structural_map takes ownership of the managed reference we pass and returns the new root as an Any; Python still holds add_one, which is unchanged.

Structural Equality#

structural_equal compares two values by structure and content rather than by identity, and returns a Result because a node may not support the comparison. Let’s specialize add_one twice and compare the results:

fn compare_specialized(func: Function, n: Var) -> Result<Array<bool>> {
    let first = specialize(func.clone(), n.clone(), 128)?;
    let second = specialize(func, n, 128)?;
    let equal = tvm_ffi::structural_equal(&first, &second)?;
    Ok([first.same_as(&second), equal].into_iter().collect())
}

The output is:

[False, True]

The two functions are different objects, so same_as is false, but they are structurally equal.

Visitors and Mutators in Rust#

A walk callback sees one node at a time. Some traversals need context around a node’s children, such as the loops that enclose a write. A visitor or mutator callback takes control of the recursion into its node’s children: it decides when to descend, so it can set up state before and restore it after. State lives on a #[dispatch] struct, as in Structural Walk, with visit_* methods for structural_visit and mutate_* methods for structural_mutate.

Let’s record the loops around each write:

#[derive(Default)]
struct LoopNest {
    loops: Vec<String>,
    writes: Vec<String>,
}

#[dispatch(visit, (AnyView<'_>, &mut StructuralVisitorView<'_, Self>), Result<Option<VisitInterrupt>>)]
impl LoopNest {
    fn visit_for(
        &mut self,
        loop_: &For,
        visitor: &mut StructuralVisitorView<'_, Self>,
    ) -> Result<Option<VisitInterrupt>> {
        self.loops.push(loop_.var.name.as_str().to_owned());
        let result = visitor.default_visit(self, loop_);
        self.loops.pop();
        result
    }

    fn visit_store(&mut self, store: &TensorStore) -> Result<Option<VisitInterrupt>> {
        let loops = self.loops.join(", ");
        let write = format!("{} inside [{}]", script(&store.dest)?.as_str(), loops);
        self.writes.push(write);
        Ok(None)
    }
}

fn loops_around_writes(func: Function) -> Result<Strings> {
    let mut visitor = LoopNest::default();
    tvm_ffi::structural_visit(&func, &mut visitor)?;
    assert!(visitor.loops.is_empty());
    Ok(visitor.writes.iter().map(tvm_ffi::String::from).collect())
}

The output is:

['B inside [i]']

visit_for pushes the loop variable, visits the loop’s children with visitor.default_visit(self, loop_), then pops the variable. Returning the result passes an interrupt or error from a child back to the caller. visit_store records the write and does not descend further. The trailing StructuralVisitorView also provides visit(self, child) for a selected child and def_region_kind() for the current node.

A mutator works the same way and returns the replacement for each node. Let’s reverse the loop by replacing each use of i with n - 1 - i:

#[derive(Default)]
struct ReverseLoops {
    reversed_index: HashMap<ObjectIdentity, Expr>,
}

#[dispatch(mutate, (MutationView<'_>, &mut StructuralMutatorView<'_, Self>), Result<UnchangedOr<Any>>)]
impl ReverseLoops {
    fn mutate_for(
        &mut self,
        value: MutationView<'_, For>,
        mutator: &mut StructuralMutatorView<'_, Self>,
    ) -> Result<UnchangedOr<Any>> {
        let index = (&value.end - 1 - &value.var).try_into()?;
        self.reversed_index.insert(ObjectIdentity::of(&value.var), index);
        mutator.default_mutate(self, value)
    }

    fn mutate_var(
        &mut self,
        var: Var,
        mutator: &mut StructuralMutatorView<'_, Self>,
    ) -> Result<UnchangedOr<Any>> {
        let is_use = mutator.def_region_kind() == DefRegionKind::None;
        Ok(match self.reversed_index.get(&ObjectIdentity::of(&var)) {
            Some(index) if is_use => index.clone().into(),
            _ => Unchanged.into(),
        })
    }
}

fn reverse_loops(func: Function) -> Result<Function> {
    tvm_ffi::structural_mutate(func, ReverseLoops::default())?.try_into()
}

The output is:

from __future__ import annotations

# from tvm_tirx.script import tirx as T

@T.function
def add_one[n](A: T.Tensor((n,), T.float32), B: T.Tensor((n,), T.float32)):
    for i in range(n):
        B[n - 1 - i] = A[n - 1 - i] + T.float32(1.0)

mutate_for records the replacement for its loop variable, then mutator.default_mutate(self, value) rewrites the loop’s children through the same struct, so mutate_var sees the replacement before any use of i. Mutate handlers return Result<UnchangedOr<Any>>, the same type that default_mutate returns, so mutate_for returns its result directly. mutate_var returns the new index with .into(), or Unchanged to keep the variable.

A mutate handler receives its node as a MutationView, here MutationView<'_, For>. We read the loop’s fields through it, as with value.end and value.var, and pass it on to default_mutate, which may then update the loop in place instead of copying it. Only a node that nothing else holds is updated in place, so add_one, still held by Python, stays unchanged.

Note

mutate_var replaces i only where def_region_kind() is None, so the loop’s own i stays a variable. ObjectIdentity keys the map by object identity, so only this loop’s i matches.

Constraint-Aware Traversal#

Many rewrites depend on facts that hold at a point in the program: the range of a loop variable, or the condition of an enclosing branch. Collecting these facts by hand at every node would repeat the same bookkeeping in every pass. The tvm_tirx::tirx module provides constraint-aware versions of the four structural utilities, which collect the facts for us and hand them to our callbacks as a ConstraintContext:

Utility

Facts reach the callback as

structural_walk_with_constraint_context

A &ConstraintContext parameter

structural_map_with_constraint_context

A &ConstraintContext parameter

structural_visit_with_constraint_context

visitor.base().constraints()

structural_mutate_with_constraint_context

mutator.base().constraints()

Compilers often insert bounds checks to stay safe, such as the if i // 4 < n below. Here the loop already guarantees the condition, so the check only costs time on every iteration:

@T.function
def add_one_guarded(A: T.Tensor((n, 4), T.float32), B: T.Tensor((n, 4), T.float32)):
    for i in range(n * 4):
        if i // 4 < n:
            B[i // 4, i % 4] = A[i // 4, i % 4] + 1

A walk can check whether each condition is provable from the facts at that point:

fn proven_guards(func: Function) -> Result<Array<bool>> {
    let analyzer = Analyzer::new();
    let mut proven = Vec::new();
    structural_walk_with_constraint_context(
        &func,
        |branch: &If, constraints: &ConstraintContext| -> Result<WalkResult> {
            analyzer.sync_constraint_context(constraints)?;
            proven.push(analyzer.can_prove(&branch.condition, ProofStrength::Default)?);
            Ok(WalkResult::Advance)
        },
        WalkOrder::PreOrder,
    )?;
    Ok(proven.into_iter().collect())
}

The output is:

[True]

The walk passes each if together with the facts that hold there: the loop’s range, and that the loop runs. sync_constraint_context hands those facts to the analyzer, which then proves the condition. The branch’s own condition is not a fact at the if itself, only inside it.

A map with the same callback shape removes the check by returning the branch body in place of the if:

fn remove_redundant_guards(func: Function) -> Result<Function> {
    let analyzer = Analyzer::new();
    structural_map_with_constraint_context(
        func,
        |branch: If, constraints: &ConstraintContext| -> Result<UnchangedOr<Any>> {
            analyzer.sync_constraint_context(constraints)?;
            Ok(if analyzer.can_prove(&branch.condition, ProofStrength::Default)? {
                branch.then_case.clone().into()
            } else {
                Unchanged.into()
            })
        },
        WalkOrder::PreOrder,
    )?
    .try_into()
}

The output is:

from __future__ import annotations

# from tvm_tirx.script import tirx as T

@T.function
def add_one_guarded[n](A: T.Tensor((n, 4), T.float32), B: T.Tensor((n, 4), T.float32)):
    for i in range(n * 4):
        B[i // 4, i % 4] = A[i // 4, i % 4] + T.float32(1.0)

Returning Unchanged keeps an if the analyzer cannot prove. In pre-order, the map then continues into the children of the value it returned.

The visit and mutate versions give the same facts to stateful traversals. A handler reads them with visitor.base().constraints() or mutator.base().constraints(), and default_visit or default_mutate collects the facts of the children as it descends.

Note

A callback reads the context but must not add facts to it. The ConstraintContext it receives follows the traversal; call snapshot() to keep the facts at one point, or to_array() for the individual facts.

With fields, typed callbacks, and the structural utilities, a Rust function works with the same IR that Python builds and prints, so an analysis or a transformation can move between the two languages one function at a time.

Quick Reference#

Construct

What it does

match_any!

Branches on the node type; the first matching arm runs

.downcast(), downcast_ref

Downcasts to one type, as a managed reference in a Result or a borrowed object in an Option

.into()

Upcasts a managed reference to a parent type

PrimVar::new, expression operators, .try_into()?

Creates a node; builds an expression with operators

structural_walk(&func, callbacks, WalkOrder::PreOrder)

Walks with typed callbacks that return WalkResult

structural_map(func, callbacks, order)

Rebuilds with replacements and returns an Any

A trailing DefRegionKind parameter

Receives the definition region kind

structural_equal(&a, &b)

Compares by structure

#[dispatch](prefix, (First, Args...), Ret)

Generates dispatch, a match_any! over the prefix_* methods of a struct

structural_visit, structural_mutate

Traverse with a dispatcher whose handlers control descent

StructuralVisitorView, StructuralMutatorView

Recurse with the same dispatcher and current definition region

structural_walk_with_constraint_context and the map, visit, and mutate versions

Traverse with the facts that hold at each node

static_init_block!, Function::register_global_typed

Registers Rust functions as global functions