xref: /petsc/config/BuildSystem/config/compilerFlags.py (revision f4f49eeac7efa77fffa46b7ff95a3ed169f659ed)
1import config.base
2import re
3import os
4
5class Configure(config.base.Configure):
6  def __init__(self, framework):
7    config.base.Configure.__init__(self, framework)
8    self.headerPrefix = ''
9    self.substPrefix  = ''
10    self.version = {}
11    self.rejected = {}
12    self.text = ''
13    return
14
15  def __str__(self):
16    return self.text
17
18  def setupHelp(self, help):
19    import nargs
20    help.addArgument('Compiler Flags', '-optionsModule=<module name>', nargs.Arg(None, 'config.compilerOptions', 'The Python module used to determine compiler options and versions'))
21    help.addArgument('Compiler Flags', '-with-debugging=<bool>', nargs.ArgBool(None, 1, 'Specify debugging version of libraries'))
22    help.addArgument('Compiler Flags', '-C_VERSION=<string>',   nargs.Arg(None, 'Unknown', 'The version of the C compiler'))
23    help.addArgument('Compiler Flags', '-CXX_VERSION=<string>', nargs.Arg(None, 'Unknown', 'The version of the C++ compiler'))
24    help.addArgument('Compiler Flags', '-FC_VERSION=<string>',  nargs.Arg(None, 'Unknown', 'The version of the Fortran compiler'))
25    help.addArgument('Compiler Flags', '-CUDA_VERSION=<string>',nargs.Arg(None, 'Unknown', 'The version of the CUDA compiler'))
26    help.addArgument('Compiler Flags', '-HIP_VERSION=<string>',nargs.Arg(None, 'Unknown', 'The version of the HIP compiler'))
27    help.addArgument('Compiler Flags', '-SYCL_VERSION=<string>',nargs.Arg(None, 'Unknown', 'The version of the SYCL compiler'))
28    help.addArgument('Compiler Flags', '-COPTFLAGS=<string>',   nargs.Arg(None, None, 'Override the debugging/optimization flags for the C compiler'))
29    help.addArgument('Compiler Flags', '-CXXOPTFLAGS=<string>', nargs.Arg(None, None, 'Override the debugging/optimization flags for the C++ compiler'))
30    help.addArgument('Compiler Flags', '-FOPTFLAGS=<string>',   nargs.Arg(None, None, 'Override the debugging/optimization flags for the Fortran compiler'))
31    help.addArgument('Compiler Flags', '-CUDAOPTFLAGS=<string>',   nargs.Arg(None, None, 'Override the debugging/optimization flags for the CUDA compiler'))
32    help.addArgument('Compiler Flags', '-HIPOPTFLAGS=<string>',   nargs.Arg(None, None, 'Override the debugging/optimization flags for the HIP compiler'))
33    help.addArgument('Compiler Flags', '-SYCLOPTFLAGS=<string>',   nargs.Arg(None, None, 'Override the debugging/optimization flags for the SYCL compiler'))
34    help.addArgument('Compiler Flags', '-with-gcov=<bool>', nargs.ArgBool(None, value=None, help='Specify that GNUs coverage tool gcov is used', deprecated='--with-coverage'))
35    return
36
37  def setupDependencies(self, framework):
38    config.base.Configure.setupDependencies(self, framework)
39    self.setCompilers = framework.require('config.setCompilers', self)
40    return
41
42  def getOptionalFlagsName(self, language, compilerOnly = 0):
43    if language == 'C':
44      flagsArg = 'COPTFLAGS'
45    elif language == 'Cxx':
46      if compilerOnly:
47        flagsArg = 'CXX_CXXOPTFLAGS'
48      else:
49        flagsArg = 'CXXOPTFLAGS'
50    elif language == 'FC':
51      flagsArg = 'FOPTFLAGS'
52    elif language == 'CUDA':
53      flagsArg = 'CUDAOPTFLAGS'
54    elif language == 'HIP':
55      flagsArg = 'HIPOPTFLAGS'
56    elif language == 'SYCL':
57      flagsArg = 'SYCLOPTFLAGS'
58    else:
59      raise RuntimeError('Unknown language: '+language)
60    return flagsArg
61
62  def findOptFlags(self, flags):
63    if isinstance(flags, str):
64      flags = flags.split()
65
66    return [f for f in flags if f.startswith('-g') or f.startswith('-O') or f in {'-fast'}]
67
68  def hasOptFlags(self,flags):
69    return len(self.findOptFlags(flags)) > 0
70
71  def getOptionsObject(self):
72    '''Get a configure object which will return default options for each compiler'''
73    options = None
74    try:
75      mod     = __import__(self.argDB['optionsModule'], locals(), globals(), ['CompilerOptions'])
76      options = mod.CompilerOptions(self.framework)
77      options.setup()
78    except ImportError:
79      self.logPrint('ERROR: Failed to load user options module '+str(self.argDB['optionsModule']))
80    return options
81
82  def configureCompilerFlags(self):
83    '''Get the default compiler flags'''
84    self.debugging = self.argDB['with-debugging']
85    bopts = ['']
86    if self.debugging:
87      bopts.append('g')
88    else:
89      bopts.append('O')
90
91    options = self.getOptionsObject()
92    if not options:
93      return
94    options.saveLog()
95    for language, compiler in [('C', 'CC'), ('Cxx', 'CXX'), ('FC', 'FC'), ('CUDA', 'CUDAC'), ('HIP', 'HIPC'), ('SYCL', 'SYCLC')]:
96      if not hasattr(self.setCompilers, compiler):
97        continue
98      self.setCompilers.pushLanguage(language)
99      flagsName = config.base.Configure.getCompilerFlagsName(language)
100      try:
101        self.version[language] = self.argDB[language.upper()+'_VERSION']
102        if self.version[language] == 'Unknown':
103          self.version[language] = options.getCompilerVersion(language, self.setCompilers.getCompiler())
104      except RuntimeError:
105        pass
106      self.rejected[language] = []
107      for bopt in bopts:
108        userflags = 0
109        if bopt in ['g','O'] and self.getOptionalFlagsName(language) in self.argDB: # check --COPTFLAGS etc
110          # treat user supplied options as single option - as it could include options separated by spaces '-tp k8-64'
111          flags = [self.argDB[self.getOptionalFlagsName(language)]]
112          userflags = 1
113        elif bopt in ['g','O'] and self.hasOptFlags(getattr(self.setCompilers,flagsName)): # check --CFLAGS etc
114          self.logPrint('Optimization options found in '+flagsName+ '. Skipping setting defaults')
115          flags = []
116        elif bopt == '' and flagsName in self.argDB:
117          self.logPrint('Ignoring default options which were overridden using --'+flagsName+ ' ' + self.argDB[flagsName])
118          flags = []
119        else:
120          flags = options.getCompilerFlags(language, self.setCompilers.getCompiler(), bopt)
121
122        for testFlag in flags:
123          if isinstance(testFlag, (tuple, list)):
124            testFlag = ' '.join(testFlag)
125          self.logPrint('Trying '+language+' compiler flag '+testFlag)
126          try:
127            self.setCompilers.addCompilerFlag(testFlag)
128          except RuntimeError:
129            if userflags:
130              raise RuntimeError('User provided flags for language '+language+' with '+self.getOptionalFlagsName(language)+': '+self.argDB[self.getOptionalFlagsName(language)]+' are not correct for the compiler')
131            self.logPrint('Rejected '+language+' compiler flag '+testFlag)
132            self.rejected[language].append(testFlag)
133      self.setCompilers.popLanguage()
134    return
135
136  def outputCompilerMacros(self):
137    '''Cannot use the regular outputCompile because it swallows the output into the -o file'''
138    command = self.getCompilerCmd()
139    if self.compilerDefines: self.framework.outputHeader(self.compilerDefines)
140    self.framework.outputCHeader(self.compilerFixes)
141    f = open(self.compilerSource, 'w')
142    f.close()
143    try:
144      command = command + ' -E -dM '
145      start = command.find('-o ')
146      end = start + 3 + command[start+3:].find(' ')
147      command = command[:start-1]+command[end:]
148      (out, err, ret) = Configure.executeShellCommand(command, log = self.log)
149      if out.find('__AVX2__') > -1 and out.find('__FMA__') > -1:
150        self.text = self.text + 'Intel instruction sets utilizable by compiler:\n'
151        self.text = self.text + '  AVX2\n'
152      if out.find('__AVX512__') > -1:
153        self.text = self.text + '  AVX512\n'
154    except:
155      pass
156    for filename in [self.compilerDefines, self.compilerFixes, self.compilerSource, self.compilerObj]:
157      if os.path.isfile(filename): os.remove(filename)
158
159  def checkCompilerMacros(self):
160    '''Save the list of CPP macros defined by the C and C++ compiler, does not work for all compilers'''
161    '''The values will depends on the flags passed to the compiler'''
162    self.outputCompilerMacros()
163    if hasattr(self.setCompilers, 'CXX'):
164      with self.Language('Cxx'):
165        self.outputCompilerMacros()
166    return
167
168  def checkIntelHardwareSupport(self):
169    '''Use Linux/macOS commands to determine what operations the hardware supports'''
170    try:
171      (out, err, ret) = Configure.executeShellCommand('lscpu', log = self.log)
172    except:
173      try:
174        (out, err, ret) = Configure.executeShellCommand('sysctl -a', log = self.log)
175        if out.find('hw.optional.avx2_0: 1') > -1 and out.find('hw.optional.fma: 1') > -1:
176          self.text = self.text + 'Intel instruction sets found on CPU:\n'
177          self.text = self.text + '  AVX2\n'
178        if out.find('hw.optional.avx512f: 1') > -1:
179          self.text = self.text + '  AVX512\n'
180      except:
181        pass
182    return
183
184  def configure(self):
185    self.executeTest(self.configureCompilerFlags)
186    self.executeTest(self.checkIntelHardwareSupport)
187    self.executeTest(self.checkCompilerMacros)
188    return
189