xref: /illumos-gate/usr/src/tools/smatch/src/validation/integer-const-expr.c (revision f52943a93040563107b95bccb9db87d9971ef47d)
1 extern void *malloc(unsigned long);
2 
3 static inline __attribute__((__const__)) unsigned squarec(unsigned n)
4 {
5         return n*n;
6 }
7 
8 static inline unsigned square(unsigned n)
9 {
10         return n*n;
11 }
12 
13 static inline unsigned long long bignum(void)
14 {
15         return 1000000000000ULL;
16 }
17 
18 static inline __attribute__((__const__)) unsigned long long bignumc(void)
19 {
20         return 1000000000000ULL;
21 }
22 
23 // test if x is an integer constant expression [C99,C11 6.6p6]
24 #define ICE_P(x) \
25     (__builtin_types_compatible_p(typeof(0?((void*)((long)(x)*0l)):(int*)1),int*))
26 
27 #define CHX_P(X)	__builtin_choose_expr(ICE_P(X), 1, 0)
28 #define CST_P(X)	__builtin_constant_p(ICE_P(X))
29 
30 #define TEST(R, X)	_Static_assert(ICE_P(X) == R, "ICE_P(" #X ") => " #R);	\
31 			_Static_assert(ICE_P(ICE_P(X)), "ICE_P2(" #X ")");	\
32 			_Static_assert(CHX_P(X) == R, "CHX_P(" #X ") => " #R);	\
33 			_Static_assert(CST_P(X) == 1, "CST_P(" #X ")")
34 
35 int main(int argc, char *argv[])
36 {
37         char fla[3];
38         char vla[argc++];
39         char **p, **q;
40         int x = 5, y = 8;
41         void *v;
42 
43         p = &argv[3];
44         q = &argv[6];
45 
46         TEST(1, 4);
47         TEST(1, sizeof(long));
48         TEST(1, 5ull - 3u);
49         TEST(1, 3.2);
50         TEST(1, sizeof(fla));
51 
52         TEST(0, square(2));
53         TEST(0, square(argc));
54         TEST(0, squarec(2));
55         TEST(0, squarec(argc));
56         TEST(0, 1+argc-argc);
57         TEST(0, 1+argc+argc+1-argc-argc);
58         TEST(0, bignum() - 1);
59         TEST(0, 0*bignum());
60         TEST(0, 0*bignumc());
61         TEST(0, sizeof(vla));
62         TEST(0, p);
63         TEST(0, p < q);
64         TEST(0, p++);
65         TEST(0, main);
66         TEST(0, malloc(8));
67         TEST(0, v = malloc(8));
68         TEST(0, v);
69         TEST(0, x++);
70         TEST(0, y++);
71         TEST(0, (3, 2, 1));
72         TEST(0, ({x++; 0; }));
73         TEST(0, ({square(y--); 0; }));
74         TEST(0, (square(x), 3));
75         TEST(0, (squarec(x), 3));
76         TEST(0, ({squarec(x); 3;}));
77         TEST(0, ({squarec(x);}));
78 
79         return 0;
80 }
81 
82 /*
83  * check-name: integer-const-expr
84  * check-command: sparse -Wno-vla $file
85  */
86