xref: /aosp_15_r20/external/clang/test/SemaCXX/array-bounds-ptr-arith.cpp (revision 67e74705e28f6214e480b399dd47ea732279e315)
1*67e74705SXin Li // RUN: %clang_cc1 -verify -Wno-string-plus-int -Warray-bounds-pointer-arithmetic %s
2*67e74705SXin Li 
swallow(const char * x)3*67e74705SXin Li void swallow (const char *x) { (void)x; }
test_pointer_arithmetic(int n)4*67e74705SXin Li void test_pointer_arithmetic(int n) {
5*67e74705SXin Li   const char hello[] = "Hello world!"; // expected-note 2 {{declared here}}
6*67e74705SXin Li   const char *helloptr = hello;
7*67e74705SXin Li 
8*67e74705SXin Li   swallow("Hello world!" + 6); // no-warning
9*67e74705SXin Li   swallow("Hello world!" - 6); // expected-warning {{refers before the beginning of the array}}
10*67e74705SXin Li   swallow("Hello world!" + 14); // expected-warning {{refers past the end of the array}}
11*67e74705SXin Li   swallow("Hello world!" + 13); // no-warning
12*67e74705SXin Li 
13*67e74705SXin Li   swallow(hello + 6); // no-warning
14*67e74705SXin Li   swallow(hello - 6); // expected-warning {{refers before the beginning of the array}}
15*67e74705SXin Li   swallow(hello + 14); // expected-warning {{refers past the end of the array}}
16*67e74705SXin Li   swallow(hello + 13); // no-warning
17*67e74705SXin Li 
18*67e74705SXin Li   swallow(helloptr + 6); // no-warning
19*67e74705SXin Li   swallow(helloptr - 6); // no-warning
20*67e74705SXin Li   swallow(helloptr + 14); // no-warning
21*67e74705SXin Li   swallow(helloptr + 13); // no-warning
22*67e74705SXin Li 
23*67e74705SXin Li   double numbers[2]; // expected-note {{declared here}}
24*67e74705SXin Li   swallow((char*)numbers + sizeof(double)); // no-warning
25*67e74705SXin Li   swallow((char*)numbers + 60); // expected-warning {{refers past the end of the array}}
26*67e74705SXin Li 
27*67e74705SXin Li   char buffer[5]; // expected-note 2 {{declared here}}
28*67e74705SXin Li   // TODO: Add FixIt notes for adding parens around non-ptr part of arith expr
29*67e74705SXin Li   swallow(buffer + sizeof("Hello")-1); // expected-warning {{refers past the end of the array}}
30*67e74705SXin Li   swallow(buffer + (sizeof("Hello")-1)); // no-warning
31*67e74705SXin Li   if (n > 0 && n <= 6) swallow(buffer + 6 - n); // expected-warning {{refers past the end of the array}}
32*67e74705SXin Li   if (n > 0 && n <= 6) swallow(buffer + (6 - n)); // no-warning
33*67e74705SXin Li }
34