Fix count params macro.
[bertos.git] / bertos / cfg / compiler.h
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * Copyright 2003, 2004, 2005 Develer S.r.l. (http://www.develer.com/)
30  * Copyright 2001, 2002, 2003 Bernie Innocenti <bernie@codewiz.org>
31  *
32  * -->
33  *
34  * \brief Additional support macros for compiler independance
35  *
36  * \author Bernie Innocenti <bernie@codewiz.org>
37  */
38
39 #ifndef BERTOS_COMPILER_H
40 #define BERTOS_COMPILER_H
41
42 #include <cpu/detect.h>
43
44
45 #if defined __GNUC__ && defined __GNUC_MINOR__
46         #define GNUC_PREREQ(maj, min) \
47                 ((__GNUC__ << 16) + __GNUC_MINOR__ >= ((maj) << 16) + (min))
48 #else
49         #define GNUC_PREREQ(maj, min) 0
50 #endif
51
52 /* Some CW versions do not allow enabling C99 from the settings panel. */
53 #if defined(__MWERKS__)
54         #pragma c99 on
55 #endif
56
57 #if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
58         #define COMPILER_C99      1
59 #else
60         #define COMPILER_C99      0
61 #endif
62
63
64 /** Concatenate two different preprocessor tokens (allowing macros to expand) */
65 #define PP_CAT(x,y)         PP_CAT__(x,y)
66 #define PP_CAT__(x,y)       x ## y
67 #define PP_CAT3(x,y,z)      PP_CAT(PP_CAT(x,y),z)
68 #define PP_CAT4(x,y,z,w)    PP_CAT(PP_CAT3(x,y,z),w)
69 #define PP_CAT5(x,y,z,w,j)  PP_CAT(PP_CAT4(x,y,z,w),j)
70
71 /** String-ize a token (allowing macros to expand) */
72 #define PP_STRINGIZE(x)     PP_STRINGIZE__(x)
73 #define PP_STRINGIZE__(x)   #x
74
75
76 /**
77  */
78 #if COMPILER_C99
79         #define COUNT_PARMS2(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _, ...) _
80         #define COUNT_PARMS(...) \
81                         COUNT_PARMS2(11 , ## __VA_ARGS__, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
82
83         /**
84          * usage:
85          * #define foo_init(...) PP_CAT(foo_init_, COUNT_PARMS(__VA_ARGS__)) (__VA_ARGS__)
86          */
87
88 #else
89         #define COUNT_PARMS2(_0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _, ...) _
90         #define COUNT_PARMS(args...) \
91                         COUNT_PARMS2(11 , ## args, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
92
93         /**
94          * usage:
95          * #define foo_init(args...) PP_CAT(foo_init_, COUNT_PARMS(args)) (args)
96          */
97
98 #endif
99
100 #if defined(__IAR_SYSTEMS_ICC) || defined(__IAR_SYSTEMS_ICC__)
101
102         #pragma language=extended
103
104         #if CPU_ARM
105
106                 #define COMPILER_VARIADIC_MACROS 1
107
108                 #define INTERRUPT(x)  __irq __arm void x (void)
109                 #define INLINE        static inline
110
111                 /* Include some standard C89/C99 stuff */
112                 #include <stddef.h>
113                 #include <stdint.h>
114                 #include <stdbool.h>
115
116         #elif CPU_I196
117
118                 // IAR has size_t as built-in type, but does not define this symbol.
119                 #define _SIZE_T_DEFINED
120
121                 #define INTERRUPT(x)  interrupt [x]
122                 #define REGISTER      shortad
123                 #define INLINE        /* unsupported */
124
125                 /*
126                  * Imported from <longjmp.h>. Unfortunately, we can't just include
127                  * this header because it typedefs jmp_buf to be an array of chars.
128                  * This would allow the compiler to place the buffer on an odd address.
129                  * The CPU _should_ be able to perform word accesses to
130                  * unaligned data, but there are *BUGS* in the 80196KC with
131                  * some combinations of opcodes and addressing modes. One of
132                  * these, "ST SP,[?GR]+" is used in the longjmp() implementation
133                  * provided by the IAR compiler ANSI C library. When ?GR contains
134                  * an odd address, surprisingly the CPU will copy the high order
135                  * byte of the source operand (SP) in the low order byte of the
136                  * destination operand (the memory location pointed to by ?GR).
137                  *
138                  * We also need to replace the library setjmp()/longjmp() with
139                  * our own versions because the IAR implementation "forgets" to
140                  * save the contents of local registers (?LR).
141                  */
142                 struct _JMP_BUF
143                 {
144                         void *sp;           /* Stack pointer */
145                         void *return_addr;  /* Return address */
146                         int lr[6];          /* 6 local registers */
147                 };
148
149                 typedef struct _JMP_BUF jmp_buf[1];
150
151                 int setjmp(jmp_buf env);
152                 void longjmp(jmp_buf env, int val);
153
154                 /* Fake bool support */
155                 #define true (1==1)
156                 #define false (1!=1)
157                 typedef unsigned char bool;
158
159         #else
160                 #error Unsupported CPU
161         #endif
162
163 #elif defined(_MSC_VER) /* Win32 emulation support */
164
165         /* MSVC doesn't provide <stdbool.h>. */
166         #ifndef __cplusplus
167                 #define true (1==1)
168                 #define false (1!=1)
169                 typedef int bool;
170         #endif /* !__cplusplus */
171
172         /* These C99 functions are oddly named in MSVCRT32.lib */
173         #define snprintf _snprintf
174         #define vsnprintf _vsnprintf
175
176         /* MSVC doesn't support C99's __func__, but has a similar extension. */
177         #define __func__ __FUNCTION__
178
179         /* MSVC doesn't support C99's inline keyword */
180         #ifndef __cplusplus
181                 #define INLINE __inline
182         #endif
183
184 #elif defined(__GNUC__)
185
186         /* Compiler features */
187         #define COMPILER_VARIADIC_MACROS 1 /* Even in C++ */
188         #define COMPILER_TYPEOF 1
189         #define COMPILER_STATEMENT_EXPRESSIONS 1
190
191         /* GCC attributes */
192         #define FORMAT(type,fmt,first)  __attribute__((__format__(type, fmt, first)))
193         #define NORETURN                __attribute__((__noreturn__))
194         #define UNUSED_ARG(type,arg)    __attribute__((__unused__)) type arg
195         #define UNUSED_VAR(type,name)   __attribute__((__unused__)) type name
196         #define USED_VAR(type,name)     __attribute__((__used__)) type name
197         #define INLINE                  static inline __attribute__((__always_inline__))
198         #define NOINLINE                __attribute__((noinline))
199         #define LIKELY(x)               __builtin_expect(!!(x), 1)
200         #define UNLIKELY(x)             __builtin_expect(!!(x), 0)
201         #define PURE_FUNC               __attribute__((pure))
202         #define CONST_FUNC              __attribute__((const))
203         #define UNUSED_FUNC             __attribute__((unused))
204         #define USED_FUNC               __attribute__((__used__))
205         #define RESTRICT                __restrict__
206         #define MUST_CHECK              __attribute__((warn_unused_result))
207         #define PACKED                  __attribute__((packed))
208         #if CPU_ARM | CPU_CM3
209                 #define NAKED           __attribute__((naked))
210         #else
211                 #define NAKED
212         #endif
213
214         /**
215          * Force compiler to realod context variable.
216          */
217         #define MEMORY_BARRIER           asm volatile ("" : : : "memory")
218
219         #if GNUC_PREREQ(3,1)
220                 #define DEPRECATED  __attribute__((__deprecated__))
221         #endif
222
223         #if GNUC_PREREQ(4,5)
224                 #define UNREACHABLE() __builtin_unreachable()
225         #endif
226
227         #ifndef __cplusplus
228                 #define ASSERT_TYPE_EQUAL(var1, var2) \
229                         STATIC_ASSERT(__builtin_types_compatible_p(typeof(var1), typeof(var2)))
230                 #define ASSERT_TYPE_IS(var, type) \
231                         STATIC_ASSERT(__builtin_types_compatible_p(typeof(var), type))
232         #endif
233
234         /* Include some standard C89/C99 stuff */
235         #include <stddef.h>
236         #include <stdint.h>
237         #include <stdbool.h>
238         #if !CPU_AVR
239         #include <sys/types.h> /* for ssize_t */
240         #endif
241
242         #ifndef __cplusplus
243                 /*
244                  * Disallow some C++ keywords as identifiers in C programs,
245                  * for improved portability.
246                  */
247                 #pragma GCC poison new delete class template typename
248                 #pragma GCC poison private protected public operator
249                 #pragma GCC poison friend mutable using namespace
250                 #pragma GCC poison cin cout cerr clog
251         #endif
252
253
254
255 #elif defined(__MWERKS__)
256
257         /* Compiler features */
258         #define COMPILER_VARIADIC_MACROS 1
259         #define COMPILER_TYPEOF 1
260         #define COMPILER_STATEMENT_EXPRESSIONS 1
261
262         #define typeof __typeof__
263
264         #define UNUSED_ARG(type,arg)    type
265
266         #include <stddef.h>
267         #include <stdint.h>
268         #include <stdbool.h>
269
270         // CodeWarrior has size_t as built-in type, but does not define this symbol.
271         #define _SIZE_T_DEFINED
272
273 #else
274         #error unknown compiler
275 #endif
276
277
278 /* Defaults for compiler extensions. */
279
280 /**
281  * \def COMPILER_VARIADIC_MACROS
282  * Support for macros with variable arguments.
283  */
284 #ifndef COMPILER_VARIADIC_MACROS
285 #define COMPILER_VARIADIC_MACROS (COMPILER_C99 != 0)
286 #endif
287
288 /**
289  * \def COMPILER_TYPEOF
290  * Support for dynamic type identification.
291  */
292 #ifndef COMPILER_TYPEOF
293 #define COMPILER_TYPEOF 0
294 #endif
295
296 /**
297  * \def COMPILER_STATEMENT_EXPRESSIONS
298  * Support for statement expressions.
299  */
300 #ifndef COMPILER_STATEMENT_EXPRESSIONS
301 #define COMPILER_STATEMENT_EXPRESSIONS 0
302 #endif
303
304 /* A few defaults for missing compiler features. */
305 #ifndef INLINE
306 #define INLINE                 static inline
307 #endif
308 #ifndef NOINLINE
309 #define NOINLINE               /* nothing */
310 #endif
311 #ifndef NORETURN
312 #define NORETURN               /* nothing */
313 #endif
314 #ifndef FORMAT
315 #define FORMAT(type,fmt,first) /* nothing */
316 #endif
317 #ifndef DEPRECATED
318 #define DEPRECATED             /* nothing */
319 #endif
320 #ifndef UNUSED_ARG
321 #define UNUSED_ARG(type,arg)   type arg
322 #endif
323 #ifndef UNUSED_VAR
324 #define UNUSED_VAR(type,name)  type name
325 #endif
326 #ifndef USED_VAR
327 #define USED_VAR(type,name)    type name
328 #endif
329 #ifndef REGISTER
330 #define REGISTER               /* nothing */
331 #endif
332 #ifndef LIKELY
333 #define LIKELY(x)              x
334 #endif
335 #ifndef UNLIKELY
336 #define UNLIKELY(x)            x
337 #endif
338 #ifndef PURE_FUNC
339 #define PURE_FUNC              /* nothing */
340 #endif
341 #ifndef CONST_FUNC
342 #define CONST_FUNC             /* nothing */
343 #endif
344 #ifndef UNUSED_FUNC
345 #define UNUSED_FUNC            /* nothing */
346 #endif
347 #ifndef USED_FUNC
348 #define USED_FUNC              /* nothing */
349 #endif
350 #ifndef RESTRICT
351 #define RESTRICT               /* nothing */
352 #endif
353 #ifndef MUST_CHECK
354 #define MUST_CHECK             /* nothing */
355 #endif
356 #ifndef PACKED
357 #define PACKED                 /* nothing */
358 #endif
359 #ifndef MEMORY_BARRIER
360 #define MEMORY_BARRIER         /* nothing */
361 #warning No memory barrier defined for select compiler. If you use the kernel check it.
362 #endif
363 #ifndef UNREACHABLE
364 #define UNREACHABLE() for (;;)
365 #endif
366
367
368 /* Misc definitions */
369 #ifndef NULL
370 #define NULL  (void *)0
371 #endif
372 #ifndef EOF
373 #define EOF   (-1)
374 #endif
375
376 /* Support for hybrid C/C++ applications. */
377 #ifdef __cplusplus
378         #define EXTERN_C        extern "C"
379         #define EXTERN_C_BEGIN  extern "C" {
380         #define EXTERN_C_END    }
381         #define EXTERN_CONST    extern const
382         #define CONST_CAST(TYPE,EXPR)   (const_cast<TYPE>(EXPR))
383 #else
384         #define EXTERN_C        extern
385         #define EXTERN_C_BEGIN  /* nothing */
386         #define EXTERN_C_END    /* nothing */
387         #define EXTERN_CONST    const
388         #define CONST_CAST(TYPE,EXPR)   ((TYPE)(EXPR)) /* FIXME: How can we suppress the warning in C? */
389 #endif
390
391
392 #if defined(_MSC_VER) \
393         || ((defined(__IAR_SYSTEMS_ICC) || defined(__IAR_SYSTEMS_ICC__)) && CPU_I196)
394         /**
395          * \name ISO C99 fixed-size types
396          *
397          * These should be in <stdint.h>, but a few compilers lack them.
398          * \{
399          */
400         typedef signed char         int8_t;
401         typedef unsigned char       uint8_t;
402         typedef short int           int16_t;
403         typedef unsigned short int  uint16_t;
404         typedef long int            int32_t; /* _WIN64 safe */
405         typedef unsigned long int   uint32_t; /* _WIN64 safe */
406
407         #ifdef _MSC_VER
408                 typedef __int64              int64_t;
409                 typedef unsigned __int64     uint64_t;
410         #else
411                 typedef long long            int64_t;
412                 typedef unsigned long long   uint64_t;
413         #endif
414         /* \} */
415 #else
416         /* This is the standard location. */
417         #include <stdint.h>
418 #endif
419
420 #if CPU_AVR_ATMEGA8
421         /*
422          * The ATmega8 has a very small Flash, so we can't afford
423          * to link in support routines for 32bit integer arithmetic.
424          */
425         typedef int16_t ticks_t;  /**< Type for time expressed in ticks. */
426         typedef int16_t mtime_t;  /**< Type for time expressed in milliseconds. */
427         typedef int16_t utime_t;  /**< Type for time expressed in microseconds. */
428         #define SIZEOF_MTIME_T (16 / CPU_BITS_PER_CHAR)
429         #define SIZEOF_UTIME_T (16 / CPU_BITS_PER_CHAR)
430         #define MTIME_INFINITE 0x7FFFL
431 #else
432         typedef int32_t ticks_t;  /**< Type for time expressed in ticks. */
433
434         typedef int32_t utime_t;  /**< Type for time expressed in microseconds. */
435         #define SIZEOF_UTIME_T (32 / CPU_BITS_PER_CHAR)
436
437         #ifndef DEVLIB_MTIME_DEFINED
438                 #define DEVLIB_MTIME_DEFINED 1 /* Resolve conflict with <os/hptime.h> */
439                 typedef int32_t mtime_t;  /**< Type for time expressed in milliseconds. */
440                 #define SIZEOF_MTIME_T (32 / CPU_BITS_PER_CHAR)
441                 #define MTIME_INFINITE 0x7FFFFFFFL
442         #endif
443 #endif
444
445 /** Bulk storage large enough for both pointers or integers. */
446 typedef void * iptr_t;
447
448 /** Bulk storage large enough for both pointers to constants or integers. */
449 typedef const void * const_iptr_t;
450
451 typedef unsigned char sigbit_t;  /**< Type for signal bits. */
452 typedef unsigned char sigmask_t; /**< Type for signal masks. */
453
454
455 /**
456  * \name Standard type definitions.
457  *
458  * These should be in <sys/types.h> or <stddef.h>, but many compilers
459  * and C libraries lack them.
460  *
461  * We check for some common definitions to avoid redefinitions:
462  *
463  *    glibc, avr-libc: _SIZE_T_DEFINED, __ssize_t_defined
464  *    Darwin libc:     _BSD_SIZE_T_DEFINED_, _SIZE_T
465  *    IAR ARM:         _SIZE_T
466  *
467  * \{
468  */
469 #if !(defined(size_t) || defined(_SIZE_T_DEFINED) || defined(_BSD_SIZE_T_DEFINED_) \
470         || defined(_SIZE_T))
471         #if CPU_X86
472                 /* 32bit or 64bit (32bit for _WIN64). */
473                 typedef unsigned long size_t;
474         #else
475                 #error Unknown CPU
476         #endif
477 #endif
478
479 #if !(defined(ssize_t) || defined(_SSIZE_T) || defined(__ssize_t_defined))
480         #if CPU_X86
481                 /* 32bit or 64bit (32bit for _WIN64). */
482                 typedef long ssize_t;
483         #elif CPU_ARM || CPU_CM3
484                 typedef int ssize_t;
485         #elif CPU_AVR
486                 /* 16bit (missing in avr-libc's sys/types.h). */
487                 typedef int ssize_t;
488         #else
489                 #error Unknown CPU
490         #endif
491 #endif
492 /*\}*/
493
494
495 /**
496  * \name Types for hardware registers.
497  *
498  * Only use these types for registers whose contents can
499  * be changed asynchronously by external hardware.
500  *
501  * \{
502  */
503 #if CPU_DSP56K
504         /* Registers can be accessed only through 16-bit pointers */
505         typedef volatile uint16_t  reg16_t;
506 #else
507         typedef volatile uint8_t   reg8_t;
508         typedef volatile uint16_t  reg16_t;
509         typedef volatile uint32_t  reg32_t;
510 #endif
511 /*\}*/
512
513
514 /* Quasi-ANSI macros */
515 #ifndef offsetof
516         /**
517          * Return the byte offset of the member \a m in struct \a s.
518          *
519          * \note This macro should be defined in "stddef.h" and is sometimes
520          *       compiler-specific (g++ has a builtin for it).
521          */
522         #define offsetof(s,m)  (size_t)&(((s *)0)->m)
523 #endif
524 #ifndef countof
525         /**
526          * Count the number of elements in the static array \a a.
527          *
528          * \note This macro is non-standard, but implements a very common idiom
529          */
530         #define countof(a)  (sizeof(a) / sizeof(*(a)))
531 #endif
532 #ifndef alignof
533         /**
534          * Return the alignment in memory of a generic data type.
535          *
536          * \note We need to worry about alignment when allocating memory that
537          * will be used later by unknown objects (e.g., malloc()) or, more
538          * generally, whenever creating generic container types.
539          */
540         #define alignof(type) offsetof(struct { char c; type member; }, member)
541 #endif
542
543 /**
544  * Cast a member of a structure out to the containing structure.
545  *
546  * \param ptr     the pointer to the member.
547  * \param type    the type of the container struct this is embedded in.
548  * \param member  the name of the member within the struct.
549  */
550 #if COMPILER_TYPEOF && COMPILER_STATEMENT_EXPRESSIONS
551         #define containerof(ptr, type, member) ({ \
552                 typeof( ((type *)0)->member ) *_mptr = (ptr); /* type check */ \
553                 (type *)(void *)((char *)_mptr - offsetof(type, member)); \
554         })
555 #else
556         #define containerof(ptr, type, member) \
557                 ( (type *)(void *)((char *)(ptr) - offsetof(type, member)) )
558 #endif
559
560 /** Issue a compilation error if the \a condition is false */
561 #define STATIC_ASSERT(condition)  \
562         UNUSED_VAR(extern char, STATIC_ASSERTION_FAILED__[(condition) ? 1 : -1])
563
564 #ifndef ASSERT_TYPE_EQUAL
565         /** Ensure two variables have the same type. */
566         #define ASSERT_TYPE_EQUAL(var1, var2)  \
567                         do { (void)(&(var1) == &(var2)); } while(0)
568 #endif
569
570 #ifndef ASSERT_TYPE_IS
571         /** Ensure variable is of specified type. */
572         #define ASSERT_TYPE_IS(var, type)  \
573                         do { (void)(&(var) == (type *)0); } while(0)
574 #endif
575
576 #endif /* BERTOS_COMPILER_H */