File: custom_lowering_pass.cpp

package info (click to toggle)
halide 21.0.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 55,752 kB
  • sloc: cpp: 289,334; ansic: 22,751; python: 7,486; makefile: 4,299; sh: 2,508; java: 1,549; javascript: 282; pascal: 207; xml: 127; asm: 9
file content (65 lines) | stat: -rw-r--r-- 1,806 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include "Halide.h"
#include <stdio.h>

// This file demonstrates two example custom lowering passes. The
// first just makes sure the IR passes some test, and doesn't modify
// it. The second actually changes the IR in some useful way.

using namespace Halide;
using namespace Halide::Internal;

// Verify that all floating point divisions by constants have been
// converted to float multiplication.
class CheckForFloatDivision : public IRMutator {
    using IRMutator::visit;

    Expr visit(const Div *op) override {
        if (op->type.is_float() && is_const(op->b)) {
            std::cerr << "Found floating-point division by constant: " << Expr(op) << "\n";
            exit(1);
        }
        return op;
    }
};

// A mutator that injects code that counts floating point multiplies,
// and an extern function that it calls out to for the accounting.
int multiply_count = 0;
extern "C" HALIDE_EXPORT_SYMBOL float record_float_mul(float arg) {
    multiply_count++;
    return arg;
}
HalideExtern_1(float, record_float_mul, float);

class CountMultiplies : public IRMutator {
    using IRMutator::visit;

    Expr visit(const Mul *op) override {
        Expr expr = IRMutator::visit(op);
        if (op->type.is_float()) {
            expr = record_float_mul(expr);
        }
        return expr;
    }
};

int main(int argc, char **argv) {
    Func f;
    Var x;

    f(x) = x / 2.4f + x / sin(x) + x * sin(x);
    f.add_custom_lowering_pass(new CheckForFloatDivision);
    f.add_custom_lowering_pass(new CountMultiplies);

    const int size = 10;
    f.realize({size});

    if (multiply_count != size * 2) {
        printf("The multiplies weren't all counted. Got %d instead of %d\n",
               multiply_count, size);
        return 1;
    }

    printf("Success!\n");
    return 0;
}