xref: /petsc/config/BuildSystem/config/types.py (revision bcab024551cbaaaa7f49e357634a3584f91cb6d5)
1import config.base
2
3import os
4import re
5
6class Configure(config.base.Configure):
7  def __init__(self, framework):
8    config.base.Configure.__init__(self, framework)
9    self.headerPrefix = ''
10    self.substPrefix  = ''
11    self.sizes = {}
12    self.c99_complex = 0
13    self.cxx_complex = 0
14    return
15
16  def setupHelp(self, help):
17    import nargs
18    help.addArgument('Types', '-known-endian=<big or little>', nargs.Arg(None, None, 'Are bytes stored in big or little endian?'))
19    help.addArgument('Visibility', '-with-visibility=<bool>', nargs.Arg(None, 0, 'Use compiler visibility flags to limit symbol visibility'))
20    return
21
22  def setupDependencies(self, framework):
23    config.base.Configure.setupDependencies(self, framework)
24    self.compilers = framework.require('config.compilers', self)
25    self.headers   = framework.require('config.headers', self)
26    return
27
28  def check(self, typeName, defaultType = None, includes = []):
29    '''Checks that "typeName" exists, and if not defines it to "defaultType" if given'''
30    self.framework.log.write('Checking for type: '+typeName+'\n')
31    include = '''
32#include <sys/types.h>
33#if STDC_HEADERS
34#include <stdlib.h>
35#include <stddef.h>
36%s
37#endif
38    ''' % ('\n'.join(['#include<%s>' % inc for inc in includes]))
39    found = self.checkCompile(include,typeName+' a;')
40    if not found and defaultType:
41      self.addTypedef(defaultType, typeName)
42    else:
43      self.framework.log.write(typeName+' found\n')
44    return found
45
46  def check_siginfo_t(self):
47    '''Checks if siginfo_t exists in signal.h. This check is for windows, and C89 check.'''
48    if self.check('siginfo_t', includes = ['signal.h']):
49      self.addDefine('HAVE_SIGINFO_T',1)
50    return
51
52  def check__int64(self):
53    '''Checks if __int64 exists. This is primarily for windows.'''
54    if self.check('__int64'):
55      self.addDefine('HAVE___INT64',1)
56    return
57
58  def checkSizeTypes(self):
59    '''Checks for types associated with sizes, such as size_t.'''
60    self.check('size_t', 'int')
61    return
62
63  def checkIntegerTypes(self):
64    '''Checks for types associated with integers, such as int32_t.'''
65    self.check('int32_t', 'int')
66    return
67
68  def checkFileTypes(self):
69    '''Checks for types associated with files, such as mode_t, off_t, etc.'''
70    self.check('mode_t', 'int')
71    self.check('off_t', 'int')
72    return
73
74  def checkPID(self):
75    '''Checks for pid_t, and defines it if necessary'''
76    return self.check('pid_t', 'int')
77
78  def checkUID(self):
79    '''Checks for uid_t and gid_t, and defines them if necessary'''
80    if self.outputPreprocess('#include <sys/types.h>').find('uid_t') < 0:
81      self.addDefine('uid_t', 'int')
82      self.addDefine('gid_t', 'int')
83    return
84
85  def checkSignal(self):
86    '''Checks the return type of signal() and defines RETSIGTYPE to that type name'''
87    includes = '''
88#include <sys/types.h>
89#include <signal.h>
90#ifdef signal
91#undef signal
92#endif
93#ifdef __cplusplus
94extern "C" void (*signal (int, void(*)(int)))(int);
95#else
96void (*signal())();
97#endif
98    '''
99    if self.checkCompile(includes, ''):
100      returnType = 'void'
101    else:
102      returnType = 'int'
103    self.addDefine('RETSIGTYPE', returnType)
104    return
105
106  def checkC99Complex(self):
107    '''Check for complex numbers in in C99 std
108       Note that since PETSc source code uses _Complex we test specifically for that, not complex'''
109    includes = '#include <complex.h>\n'
110    body     = 'double _Complex x;\n x = I;\n'
111    if not self.checkCompile(includes, body): return    # checkLink can succeed even if checkCompile fails
112    if self.checkLink(includes, body):
113      self.addDefine('HAVE_C99_COMPLEX', 1)
114      self.c99_complex = 1
115    return
116
117  def checkCxxComplex(self):
118    '''Check for complex numbers in namespace std'''
119    self.pushLanguage('C++')
120    includes = '#include <complex>\n'
121    body     = 'std::complex<double> x;\n'
122    if self.checkLink(includes, body):
123      self.addDefine('HAVE_CXX_COMPLEX', 1)
124      self.cxx_complex = 1
125    self.popLanguage()
126    return
127
128  def checkFortranStar(self):
129    '''Checks whether integer*4, etc. is handled in Fortran, and if not defines MISSING_FORTRANSTAR'''
130    self.pushLanguage('FC')
131    body = '        integer*4 i\n        real*8 d\n'
132    if not self.checkCompile('', body):
133      self.addDefine('MISSING_FORTRANSTAR', 1)
134    self.popLanguage()
135    return
136
137# reverse of the above - but more standard thing to do for F90 compilers
138  def checkFortranKind(self):
139    '''Checks whether selected_int_kind etc work USE_FORTRANKIND'''
140    self.pushLanguage('FC')
141    body = '''
142        integer(kind=selected_int_kind(10)) i
143        real(kind=selected_real_kind(10)) d
144'''
145    if self.checkCompile('', body):
146      self.addDefine('USE_FORTRANKIND', 1)
147    self.popLanguage()
148    return
149
150  def checkConst(self):
151    '''Checks for working const, and if not found defines it to empty string'''
152    body = '''
153    /* Ultrix mips cc rejects this.  */
154    typedef int charset[2]; const charset x;
155    /* SunOS 4.1.1 cc rejects this.  */
156    char const *const *ccp;
157    char **p;
158    /* NEC SVR4.0.2 mips cc rejects this.  */
159    struct point {int x, y;};
160    static struct point const zero = {0,0};
161    /* AIX XL C 1.02.0.0 rejects this.
162    It does not let you subtract one const X* pointer from another in an arm
163    of an if-expression whose if-part is not a constant expression */
164    const char *g = "string";
165    ccp = &g + (g ? g-g : 0);
166    /* HPUX 7.0 cc rejects these. */
167    ++ccp;
168    p = (char**) ccp;
169    ccp = (char const *const *) p;
170    /* This section avoids unused variable warnings */
171    if (zero.x);
172    if (x[0]);
173    { /* SCO 3.2v4 cc rejects this.  */
174      char *t;
175      char const *s = 0 ? (char *) 0 : (char const *) 0;
176
177      *t++ = 0;
178      if (*s);
179    }
180    { /* Someone thinks the Sun supposedly-ANSI compiler will reject this.  */
181      int x[] = {25, 17};
182      const int *foo = &x[0];
183      ++foo;
184    }
185    { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */
186      typedef const int *iptr;
187      iptr p = 0;
188      ++p;
189    }
190    { /* AIX XL C 1.02.0.0 rejects this saying
191      "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */
192      struct s { int j; const int *ap[3]; };
193      struct s *b; b->j = 5;
194    }
195    { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */
196      const int foo = 10;
197
198      /* Get rid of unused variable warning */
199      if (foo);
200    }
201    '''
202    if not self.checkCompile('', body):
203      self.addDefine('const', '')
204    return
205
206  def checkEndian(self):
207    '''If the machine is big endian, defines WORDS_BIGENDIAN'''
208    if 'known-endian' in self.framework.argDB:
209      endian = self.framework.argDB['known-endian']
210    else:
211      # See if sys/param.h defines the BYTE_ORDER macro
212      includes = '#include <sys/types.h>\n#ifdef HAVE_SYS_PARAM_H\n  #include <sys/param.h>\n#endif\n'
213      body     = '''
214#if !BYTE_ORDER || !BIG_ENDIAN || !LITTLE_ENDIAN
215  bogus endian macros
216#endif
217      '''
218      if self.checkCompile(includes, body):
219        # It does, so check whether it is defined to BIG_ENDIAN or not
220        body = '''
221#if BYTE_ORDER != BIG_ENDIAN
222  not big endian
223#endif
224        '''
225        if self.checkCompile(includes, body):
226          endian = 'big'
227        else:
228          endian = 'little'
229      else:
230        if not self.framework.argDB['with-batch']:
231          body = '''
232          /* Are we little or big endian?  From Harbison&Steele. */
233          union
234          {
235            long l;
236            char c[sizeof(long)];
237          } u;
238          u.l = 1;
239          exit(u.c[sizeof(long) - 1] == 1);
240          '''
241          self.pushLanguage('C')
242          if self.checkRun('#include <stdlib.h>\n', body, defaultArg = 'isLittleEndian'):
243            endian = 'little'
244          else:
245            endian = 'big'
246          self.popLanguage()
247        else:
248          self.framework.addBatchBody(['{',
249                                       '  union {long l; char c[sizeof(long)];} u;',
250                                       '  u.l = 1;',
251                                       '  fprintf(output, " \'--known-endian=%s\',\\n", (u.c[sizeof(long) - 1] == 1) ? "big" : "little");',
252                                       '}'])
253          # Dummy value
254          endian = 'little'
255    if endian == 'big':
256      self.addDefine('WORDS_BIGENDIAN', 1)
257    return
258
259  def checkSizeof(self, typeName, otherInclude = None):
260    '''Determines the size of type "typeName", and defines SIZEOF_"typeName" to be the size'''
261    self.framework.log.write('Checking for size of type: '+typeName+'\n')
262    filename = 'conftestval'
263    includes = '''
264#include <sys/types.h>
265#if STDC_HEADERS
266#include <stdlib.h>
267#include <stdio.h>
268#include <stddef.h>
269#endif\n'''
270    mpiFix = '''
271#define MPICH_IGNORE_CXX_SEEK
272#define MPICH_SKIP_MPICXX 1
273#define OMPI_SKIP_MPICXX 1\n'''
274    if otherInclude:
275      if otherInclude == 'mpi.h':
276        includes += mpiFix
277      includes += '#include <'+otherInclude+'>\n'
278    body     = 'FILE *f = fopen("'+filename+'", "w");\n\nif (!f) exit(1);\nfprintf(f, "%lu\\n", (unsigned long)sizeof('+typeName+'));\n'
279    typename = typeName.replace(' ', '-').replace('*', 'p')
280    if not 'known-sizeof-'+typename in self.framework.argDB:
281      if not self.framework.argDB['with-batch']:
282        self.pushLanguage('C')
283        if self.checkRun(includes, body) and os.path.exists(filename):
284          f    = file(filename)
285          size = int(f.read())
286          f.close()
287          os.remove(filename)
288        elif not typename == 'long-long':
289          msg = 'Cannot run executable to determine size of '+typeName+'. If this machine uses a batch system \nto submit jobs you will need to configure using ./configure with the additional option  --with-batch.\n Otherwise there is problem with the compilers. Can you compile and run code with your C/C++ (and maybe Fortran) compilers?\n'
290          raise RuntimeError(msg)
291        else:
292          self.framework.log.write('Compiler does not support long long\n')
293          size = 0
294        self.popLanguage()
295      else:
296        self.framework.addBatchInclude(['#include <stdlib.h>', '#include <stdio.h>', '#include <sys/types.h>'])
297        if otherInclude:
298          if otherInclude == 'mpi.h':
299            self.framework.addBatchInclude(mpiFix)
300          self.framework.addBatchInclude('#include <'+otherInclude+'>')
301        self.framework.addBatchBody('fprintf(output, "  \'--known-sizeof-'+typename+'=%d\',\\n", sizeof('+typeName+'));')
302        # dummy value
303        size = 4
304    else:
305      size = self.framework.argDB['known-sizeof-'+typename]
306    self.sizes['known-sizeof-'+typename] = int(size)
307    self.addDefine('SIZEOF_'+typeName.replace(' ', '_').replace('*', 'p').upper(), size)
308    return size
309
310  def checkBitsPerByte(self):
311    '''Determine the nubmer of bits per byte and define BITS_PER_BYTE'''
312    filename = 'conftestval'
313    includes = '''
314#if STDC_HEADERS
315#include <stdlib.h>
316#include <stdio.h>
317#endif\n'''
318    body     = 'FILE *f = fopen("'+filename+'", "w");\n'+'''
319    char val[2];
320    int i = 0;
321
322    if (!f) exit(1);
323    val[0]=\'\\1\';
324    val[1]=\'\\0\';
325    while(val[0]) {val[0] <<= 1; i++;}
326    fprintf(f, "%d\\n", i);\n
327    '''
328    if 'known-bits-per-byte' in self.framework.argDB:
329      bits = self.framework.argDB['known-bits-per-byte']
330    elif not self.framework.argDB['with-batch']:
331      if self.checkRun(includes, body) and os.path.exists(filename):
332        f    = file(filename)
333        bits = int(f.read())
334        f.close()
335        os.remove(filename)
336      else:
337         msg = 'Cannot run executable to determine bits per bit. If this machine uses a batch system \nto submit jobs you will need to configure using ./configure with the additional option  --with-batch.\n Otherwise there is problem with the compilers. Can you compile and run code with your C/C++ (and maybe Fortran) compilers?\n'
338         raise RuntimeError(msg)
339    else:
340      self.framework.addBatchBody(['{',
341                                   '  int i = 0;',
342                                   '  char val[2];',
343                                   '  val[0]=\'\\1\';',
344                                   '  val[1]=\'\\0\';',
345                                   '  while(val[0]) {val[0] <<= 1; i++;}',
346                                   '  fprintf(output, "  \'--known-bits-per-byte=%d\',\\n", i);',
347                                   '}'])
348      # dummy value
349      bits = 8
350
351    self.bits_per_byte = int(bits)
352    self.addDefine('BITS_PER_BYTE', bits)
353    return
354
355
356  def checkVisibility(self):
357    if self.framework.argDB['with-visibility']:
358      if not self.checkCompile('','__attribute__((visibility ("default"))) int foo(void);'):
359        raise RuntimeError('Cannot use visibility attributes')
360      self.addDefine('USE_VISIBILITY',1)
361
362  def configure(self):
363    self.executeTest(self.check_siginfo_t)
364    self.executeTest(self.check__int64)
365    self.executeTest(self.checkSizeTypes)
366    self.executeTest(self.checkFileTypes)
367    self.executeTest(self.checkIntegerTypes)
368    self.executeTest(self.checkPID)
369    self.executeTest(self.checkUID)
370    self.executeTest(self.checkSignal)
371    self.executeTest(self.checkC99Complex)
372    if hasattr(self.compilers, 'CXX'):
373      self.executeTest(self.checkCxxComplex)
374    if hasattr(self.compilers, 'FC'):
375      #self.executeTest(self.checkFortranStar)
376      self.executeTest(self.checkFortranKind)
377    self.executeTest(self.checkConst)
378    self.executeTest(self.checkEndian)
379    map(lambda type: self.executeTest(self.checkSizeof, type), ['char','void *', 'short', 'int', 'long', 'long long', 'float', 'double', 'size_t'])
380    self.executeTest(self.checkBitsPerByte)
381    self.executeTest(self.checkVisibility)
382    return
383