File: input_image_bounds_check.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 (67 lines) | stat: -rw-r--r-- 1,694 bytes parent folder | download | duplicates (4)
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
66
67
#include "Halide.h"
#include <stdio.h>

// This tests out-of-bounds reads from an input image

using namespace Halide;

// Custom error handler. If we don't define this, it'll just print out
// an error message and quit
bool error_occurred = false;
void halide_error(JITUserContext *, const char *msg) {
    printf("%s\n", msg);
    error_occurred = true;
}

int main(int argc, char **argv) {
    Buffer<float> input(19);
    for (int i = 0; i < 19; i++) {
        input(i) = i;
    }
    Var x;
    Func f;
    f(x) = input(x) * 2;

    f.jit_handlers().custom_error = halide_error;

    // One easy way to read out of bounds
    f.realize({23});

    if (!error_occurred) {
        printf("There should have been an out-of-bounds error\n");
        return 1;
    }
    error_occurred = false;

    // Another more subtle way to read out of bounds used to be due to
    // bounds expansion when vectorizing. This used to be an
    // out-of-bounds error, but now isn't! Hooray!
    Func g, h;
    g(x) = input(x) * 2;
    h(x) = g(x);
    g.compute_root().vectorize(x, 4);

    h.jit_handlers().custom_error = halide_error;
    h.realize({18});

    if (error_occurred) {
        printf("There should not have been an out-of-bounds error\n");
        return 1;
    }

    // But if we try to make the input smaller than the vector width, it
    // still won't work.
    Buffer<float> small_input(3);
    Func i;
    i(x) = small_input(x);
    i.vectorize(x, 4);
    i.jit_handlers().custom_error = halide_error;
    i.realize({4});
    if (!error_occurred) {
        printf("There should have been an out-of-bounds error\n");
        return 1;
    }

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