1848b8605Smrg"""gallium
2848b8605Smrg
3848b8605SmrgFrontend-tool for Gallium3D architecture.
4848b8605Smrg
5848b8605Smrg"""
6848b8605Smrg
7848b8605Smrg#
8848b8605Smrg# Copyright 2008 VMware, Inc.
9848b8605Smrg# All Rights Reserved.
10848b8605Smrg#
11848b8605Smrg# Permission is hereby granted, free of charge, to any person obtaining a
12848b8605Smrg# copy of this software and associated documentation files (the
13848b8605Smrg# "Software"), to deal in the Software without restriction, including
14848b8605Smrg# without limitation the rights to use, copy, modify, merge, publish,
15848b8605Smrg# distribute, sub license, and/or sell copies of the Software, and to
16848b8605Smrg# permit persons to whom the Software is furnished to do so, subject to
17848b8605Smrg# the following conditions:
18848b8605Smrg#
19848b8605Smrg# The above copyright notice and this permission notice (including the
20848b8605Smrg# next paragraph) shall be included in all copies or substantial portions
21848b8605Smrg# of the Software.
22848b8605Smrg#
23848b8605Smrg# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
24848b8605Smrg# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25848b8605Smrg# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
26848b8605Smrg# IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
27848b8605Smrg# ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
28848b8605Smrg# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
29848b8605Smrg# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30848b8605Smrg#
31848b8605Smrg
32b8e80941Smrgfrom __future__ import print_function
33848b8605Smrg
34848b8605Smrgimport distutils.version
35848b8605Smrgimport os
36848b8605Smrgimport os.path
37848b8605Smrgimport re
38848b8605Smrgimport subprocess
39b8e80941Smrgimport platform as host_platform
40848b8605Smrgimport sys
41848b8605Smrgimport tempfile
42848b8605Smrg
43848b8605Smrgimport SCons.Action
44848b8605Smrgimport SCons.Builder
45848b8605Smrgimport SCons.Scanner
46848b8605Smrg
47848b8605Smrg
48848b8605Smrgdef symlink(target, source, env):
49848b8605Smrg    target = str(target[0])
50848b8605Smrg    source = str(source[0])
51848b8605Smrg    if os.path.islink(target) or os.path.exists(target):
52848b8605Smrg        os.remove(target)
53848b8605Smrg    os.symlink(os.path.basename(source), target)
54848b8605Smrg
55848b8605Smrgdef install(env, source, subdir):
56848b8605Smrg    target_dir = os.path.join(env.Dir('#.').srcnode().abspath, env['build_dir'], subdir)
57848b8605Smrg    return env.Install(target_dir, source)
58848b8605Smrg
59848b8605Smrgdef install_program(env, source):
60848b8605Smrg    return install(env, source, 'bin')
61848b8605Smrg
62848b8605Smrgdef install_shared_library(env, sources, version = ()):
63848b8605Smrg    targets = []
64848b8605Smrg    install_dir = os.path.join(env.Dir('#.').srcnode().abspath, env['build_dir'])
65848b8605Smrg    version = tuple(map(str, version))
66848b8605Smrg    if env['SHLIBSUFFIX'] == '.dll':
67848b8605Smrg        dlls = env.FindIxes(sources, 'SHLIBPREFIX', 'SHLIBSUFFIX')
68848b8605Smrg        targets += install(env, dlls, 'bin')
69848b8605Smrg        libs = env.FindIxes(sources, 'LIBPREFIX', 'LIBSUFFIX')
70848b8605Smrg        targets += install(env, libs, 'lib')
71848b8605Smrg    else:
72848b8605Smrg        for source in sources:
73848b8605Smrg            target_dir =  os.path.join(install_dir, 'lib')
74848b8605Smrg            target_name = '.'.join((str(source),) + version)
75848b8605Smrg            last = env.InstallAs(os.path.join(target_dir, target_name), source)
76848b8605Smrg            targets += last
77848b8605Smrg            while len(version):
78848b8605Smrg                version = version[:-1]
79848b8605Smrg                target_name = '.'.join((str(source),) + version)
80848b8605Smrg                action = SCons.Action.Action(symlink, "  Symlinking $TARGET ...")
81848b8605Smrg                last = env.Command(os.path.join(target_dir, target_name), last, action)
82848b8605Smrg                targets += last
83848b8605Smrg    return targets
84848b8605Smrg
85848b8605Smrg
86b8e80941Smrgdef msvc2013_compat(env):
87b8e80941Smrg    if env['gcc']:
88b8e80941Smrg        env.Append(CCFLAGS = [
89b8e80941Smrg            '-Werror=vla',
90b8e80941Smrg            '-Werror=pointer-arith',
91b8e80941Smrg        ])
92b8e80941Smrg
93b8e80941Smrg
94b8e80941Smrgdef unit_test(env, test_name, program_target, args=None):
95b8e80941Smrg    env.InstallProgram(program_target)
96b8e80941Smrg
97b8e80941Smrg    cmd = [program_target[0].abspath]
98b8e80941Smrg    if args is not None:
99b8e80941Smrg        cmd += args
100b8e80941Smrg    cmd = ' '.join(cmd)
101b8e80941Smrg
102b8e80941Smrg    # http://www.scons.org/wiki/UnitTests
103b8e80941Smrg    action = SCons.Action.Action(cmd, "  Running $SOURCE ...")
104b8e80941Smrg    alias = env.Alias(test_name, program_target, action)
105b8e80941Smrg    env.AlwaysBuild(alias)
106b8e80941Smrg    env.Depends('check', alias)
107848b8605Smrg
108848b8605Smrg
109848b8605Smrgdef num_jobs():
110848b8605Smrg    try:
111848b8605Smrg        return int(os.environ['NUMBER_OF_PROCESSORS'])
112848b8605Smrg    except (ValueError, KeyError):
113848b8605Smrg        pass
114848b8605Smrg
115848b8605Smrg    try:
116848b8605Smrg        return os.sysconf('SC_NPROCESSORS_ONLN')
117848b8605Smrg    except (ValueError, OSError, AttributeError):
118848b8605Smrg        pass
119848b8605Smrg
120848b8605Smrg    try:
121848b8605Smrg        return int(os.popen2("sysctl -n hw.ncpu")[1].read())
122848b8605Smrg    except ValueError:
123848b8605Smrg        pass
124848b8605Smrg
125848b8605Smrg    return 1
126848b8605Smrg
127848b8605Smrg
128848b8605Smrgdef check_cc(env, cc, expr, cpp_opt = '-E'):
129848b8605Smrg    # Invoke C-preprocessor to determine whether the specified expression is
130848b8605Smrg    # true or not.
131848b8605Smrg
132848b8605Smrg    sys.stdout.write('Checking for %s ... ' % cc)
133848b8605Smrg
134848b8605Smrg    source = tempfile.NamedTemporaryFile(suffix='.c', delete=False)
135848b8605Smrg    source.write('#if !(%s)\n#error\n#endif\n' % expr)
136848b8605Smrg    source.close()
137848b8605Smrg
138b8e80941Smrg    # sys.stderr.write('%r %s %s\n' % (env['CC'], cpp_opt, source.name));
139b8e80941Smrg
140b8e80941Smrg    pipe = SCons.Action._subproc(env, env.Split(env['CC']) + [cpp_opt, source.name],
141848b8605Smrg                                 stdin = 'devnull',
142848b8605Smrg                                 stderr = 'devnull',
143848b8605Smrg                                 stdout = 'devnull')
144848b8605Smrg    result = pipe.wait() == 0
145848b8605Smrg
146848b8605Smrg    os.unlink(source.name)
147848b8605Smrg
148848b8605Smrg    sys.stdout.write(' %s\n' % ['no', 'yes'][int(bool(result))])
149848b8605Smrg    return result
150848b8605Smrg
151b8e80941Smrgdef check_header(env, header):
152b8e80941Smrg    '''Check if the header exist'''
153b8e80941Smrg
154b8e80941Smrg    conf = SCons.Script.Configure(env)
155b8e80941Smrg    have_header = False
156b8e80941Smrg
157b8e80941Smrg    if conf.CheckHeader(header):
158b8e80941Smrg        have_header = True
159b8e80941Smrg
160b8e80941Smrg    env = conf.Finish()
161b8e80941Smrg    return have_header
162b8e80941Smrg
163b8e80941Smrgdef check_functions(env, functions):
164b8e80941Smrg    '''Check if all of the functions exist'''
165b8e80941Smrg
166b8e80941Smrg    conf = SCons.Script.Configure(env)
167b8e80941Smrg    have_functions = True
168b8e80941Smrg
169b8e80941Smrg    for function in functions:
170b8e80941Smrg        if not conf.CheckFunc(function):
171b8e80941Smrg            have_functions = False
172b8e80941Smrg
173b8e80941Smrg    env = conf.Finish()
174b8e80941Smrg    return have_functions
175b8e80941Smrg
176b8e80941Smrgdef check_prog(env, prog):
177b8e80941Smrg    """Check whether this program exists."""
178b8e80941Smrg
179b8e80941Smrg    sys.stdout.write('Checking for %s ... ' % prog)
180b8e80941Smrg
181b8e80941Smrg    result = env.Detect(prog)
182b8e80941Smrg
183b8e80941Smrg    sys.stdout.write(' %s\n' % ['no', 'yes'][int(bool(result))])
184b8e80941Smrg    return result
185b8e80941Smrg
186848b8605Smrg
187848b8605Smrgdef generate(env):
188848b8605Smrg    """Common environment generation code"""
189848b8605Smrg
190848b8605Smrg    # Tell tools which machine to compile for
191848b8605Smrg    env['TARGET_ARCH'] = env['machine']
192848b8605Smrg    env['MSVS_ARCH'] = env['machine']
193848b8605Smrg
194848b8605Smrg    # Toolchain
195848b8605Smrg    platform = env['platform']
196848b8605Smrg    env.Tool(env['toolchain'])
197848b8605Smrg
198848b8605Smrg    # Allow override compiler and specify additional flags from environment
199b8e80941Smrg    if 'CC' in os.environ:
200848b8605Smrg        env['CC'] = os.environ['CC']
201b8e80941Smrg    if 'CFLAGS' in os.environ:
202848b8605Smrg        env['CCFLAGS'] += SCons.Util.CLVar(os.environ['CFLAGS'])
203b8e80941Smrg    if 'CXX' in os.environ:
204848b8605Smrg        env['CXX'] = os.environ['CXX']
205b8e80941Smrg    if 'CXXFLAGS' in os.environ:
206848b8605Smrg        env['CXXFLAGS'] += SCons.Util.CLVar(os.environ['CXXFLAGS'])
207b8e80941Smrg    if 'LDFLAGS' in os.environ:
208848b8605Smrg        env['LINKFLAGS'] += SCons.Util.CLVar(os.environ['LDFLAGS'])
209848b8605Smrg
210848b8605Smrg    # Detect gcc/clang not by executable name, but through pre-defined macros
211848b8605Smrg    # as autoconf does, to avoid drawing wrong conclusions when using tools
212848b8605Smrg    # that overrice CC/CXX like scan-build.
213b8e80941Smrg    env['gcc_compat'] = 0
214848b8605Smrg    env['clang'] = 0
215848b8605Smrg    env['msvc'] = 0
216b8e80941Smrg    if host_platform.system() == 'Windows':
217848b8605Smrg        env['msvc'] = check_cc(env, 'MSVC', 'defined(_MSC_VER)', '/E')
218848b8605Smrg    if not env['msvc']:
219b8e80941Smrg        env['gcc_compat'] = check_cc(env, 'GCC', 'defined(__GNUC__)')
220b8e80941Smrg    env['clang'] = check_cc(env, 'Clang', '__clang__')
221b8e80941Smrg    env['gcc'] = env['gcc_compat'] and not env['clang']
222848b8605Smrg    env['suncc'] = env['platform'] == 'sunos' and os.path.basename(env['CC']) == 'cc'
223848b8605Smrg    env['icc'] = 'icc' == os.path.basename(env['CC'])
224848b8605Smrg
225848b8605Smrg    # shortcuts
226848b8605Smrg    machine = env['machine']
227848b8605Smrg    platform = env['platform']
228848b8605Smrg    x86 = env['machine'] == 'x86'
229848b8605Smrg    ppc = env['machine'] == 'ppc'
230b8e80941Smrg    gcc_compat = env['gcc_compat']
231848b8605Smrg    msvc = env['msvc']
232848b8605Smrg    suncc = env['suncc']
233848b8605Smrg    icc = env['icc']
234848b8605Smrg
235848b8605Smrg    # Determine whether we are cross compiling; in particular, whether we need
236848b8605Smrg    # to compile code generators with a different compiler as the target code.
237b8e80941Smrg    hosthost_platform = host_platform.system().lower()
238b8e80941Smrg    if hosthost_platform.startswith('cygwin'):
239b8e80941Smrg        hosthost_platform = 'cygwin'
240b8e80941Smrg    host_machine = os.environ.get('PROCESSOR_ARCHITEW6432', os.environ.get('PROCESSOR_ARCHITECTURE', host_platform.machine()))
241848b8605Smrg    host_machine = {
242848b8605Smrg        'x86': 'x86',
243848b8605Smrg        'i386': 'x86',
244848b8605Smrg        'i486': 'x86',
245848b8605Smrg        'i586': 'x86',
246848b8605Smrg        'i686': 'x86',
247848b8605Smrg        'ppc' : 'ppc',
248848b8605Smrg        'AMD64': 'x86_64',
249848b8605Smrg        'x86_64': 'x86_64',
250848b8605Smrg    }.get(host_machine, 'generic')
251b8e80941Smrg    env['crosscompile'] = platform != hosthost_platform
252848b8605Smrg    if machine == 'x86_64' and host_machine != 'x86_64':
253848b8605Smrg        env['crosscompile'] = True
254848b8605Smrg    env['hostonly'] = False
255848b8605Smrg
256848b8605Smrg    # Backwards compatability with the debug= profile= options
257848b8605Smrg    if env['build'] == 'debug':
258848b8605Smrg        if not env['debug']:
259b8e80941Smrg            print('scons: warning: debug option is deprecated and will be removed eventually; use instead')
260b8e80941Smrg            print('')
261b8e80941Smrg            print(' scons build=release')
262b8e80941Smrg            print('')
263848b8605Smrg            env['build'] = 'release'
264848b8605Smrg        if env['profile']:
265b8e80941Smrg            print('scons: warning: profile option is deprecated and will be removed eventually; use instead')
266b8e80941Smrg            print('')
267b8e80941Smrg            print(' scons build=profile')
268b8e80941Smrg            print('')
269848b8605Smrg            env['build'] = 'profile'
270848b8605Smrg    if False:
271848b8605Smrg        # Enforce SConscripts to use the new build variable
272848b8605Smrg        env.popitem('debug')
273848b8605Smrg        env.popitem('profile')
274848b8605Smrg    else:
275848b8605Smrg        # Backwards portability with older sconscripts
276848b8605Smrg        if env['build'] in ('debug', 'checked'):
277848b8605Smrg            env['debug'] = True
278848b8605Smrg            env['profile'] = False
279848b8605Smrg        if env['build'] == 'profile':
280848b8605Smrg            env['debug'] = False
281848b8605Smrg            env['profile'] = True
282848b8605Smrg        if env['build'] == 'release':
283848b8605Smrg            env['debug'] = False
284848b8605Smrg            env['profile'] = False
285848b8605Smrg
286848b8605Smrg    # Put build output in a separate dir, which depends on the current
287848b8605Smrg    # configuration. See also http://www.scons.org/wiki/AdvancedBuildExample
288848b8605Smrg    build_topdir = 'build'
289848b8605Smrg    build_subdir = env['platform']
290848b8605Smrg    if env['embedded']:
291848b8605Smrg        build_subdir =  'embedded-' + build_subdir
292848b8605Smrg    if env['machine'] != 'generic':
293848b8605Smrg        build_subdir += '-' + env['machine']
294848b8605Smrg    if env['build'] != 'release':
295848b8605Smrg        build_subdir += '-' +  env['build']
296848b8605Smrg    build_dir = os.path.join(build_topdir, build_subdir)
297848b8605Smrg    # Place the .sconsign file in the build dir too, to avoid issues with
298848b8605Smrg    # different scons versions building the same source file
299848b8605Smrg    env['build_dir'] = build_dir
300848b8605Smrg    env.SConsignFile(os.path.join(build_dir, '.sconsign'))
301848b8605Smrg    if 'SCONS_CACHE_DIR' in os.environ:
302b8e80941Smrg        print('scons: Using build cache in %s.' % (os.environ['SCONS_CACHE_DIR'],))
303848b8605Smrg        env.CacheDir(os.environ['SCONS_CACHE_DIR'])
304848b8605Smrg    env['CONFIGUREDIR'] = os.path.join(build_dir, 'conf')
305848b8605Smrg    env['CONFIGURELOG'] = os.path.join(os.path.abspath(build_dir), 'config.log')
306848b8605Smrg
307848b8605Smrg    # Parallel build
308848b8605Smrg    if env.GetOption('num_jobs') <= 1:
309848b8605Smrg        env.SetOption('num_jobs', num_jobs())
310848b8605Smrg
311b8e80941Smrg    # Speed up dependency checking.  See
312b8e80941Smrg    # - https://github.com/SCons/scons/wiki/GoFastButton
313b8e80941Smrg    # - https://bugs.freedesktop.org/show_bug.cgi?id=109443
314b8e80941Smrg
315b8e80941Smrg    # Scons version string has consistently been in this format:
316b8e80941Smrg    # MajorVersion.MinorVersion.Patch[.alpha/beta.yyyymmdd]
317b8e80941Smrg    # so this formula should cover all versions regardless of type
318b8e80941Smrg    # stable, alpha or beta.
319b8e80941Smrg    # For simplicity alpha and beta flags are removed.
320b8e80941Smrg
321b8e80941Smrg    scons_version = distutils.version.StrictVersion('.'.join(SCons.__version__.split('.')[:3]))
322b8e80941Smrg    if scons_version < distutils.version.StrictVersion('3.0.2') or \
323b8e80941Smrg       scons_version > distutils.version.StrictVersion('3.0.4'):
324b8e80941Smrg        env.Decider('MD5-timestamp')
325848b8605Smrg    env.SetOption('max_drift', 60)
326848b8605Smrg
327848b8605Smrg    # C preprocessor options
328848b8605Smrg    cppdefines = []
329b8e80941Smrg    cppdefines += [
330b8e80941Smrg        '__STDC_CONSTANT_MACROS',
331b8e80941Smrg        '__STDC_FORMAT_MACROS',
332b8e80941Smrg        '__STDC_LIMIT_MACROS',
333b8e80941Smrg        'HAVE_NO_AUTOCONF',
334b8e80941Smrg    ]
335848b8605Smrg    if env['build'] in ('debug', 'checked'):
336848b8605Smrg        cppdefines += ['DEBUG']
337848b8605Smrg    else:
338848b8605Smrg        cppdefines += ['NDEBUG']
339848b8605Smrg    if env['build'] == 'profile':
340848b8605Smrg        cppdefines += ['PROFILE']
341848b8605Smrg    if env['platform'] in ('posix', 'linux', 'freebsd', 'darwin'):
342848b8605Smrg        cppdefines += [
343848b8605Smrg            '_POSIX_SOURCE',
344848b8605Smrg            ('_POSIX_C_SOURCE', '199309L'),
345848b8605Smrg            '_SVID_SOURCE',
346848b8605Smrg            '_BSD_SOURCE',
347848b8605Smrg            '_GNU_SOURCE',
348b8e80941Smrg            '_DEFAULT_SOURCE',
349848b8605Smrg        ]
350848b8605Smrg        if env['platform'] == 'darwin':
351848b8605Smrg            cppdefines += [
352848b8605Smrg                '_DARWIN_C_SOURCE',
353848b8605Smrg                'GLX_USE_APPLEGL',
354848b8605Smrg                'GLX_DIRECT_RENDERING',
355b8e80941Smrg                'BUILDING_MESA',
356848b8605Smrg            ]
357848b8605Smrg        else:
358848b8605Smrg            cppdefines += [
359848b8605Smrg                'GLX_DIRECT_RENDERING',
360848b8605Smrg                'GLX_INDIRECT_RENDERING',
361848b8605Smrg            ]
362b8e80941Smrg
363b8e80941Smrg        if check_header(env, 'xlocale.h'):
364b8e80941Smrg            cppdefines += ['HAVE_XLOCALE_H']
365b8e80941Smrg
366b8e80941Smrg        if check_header(env, 'endian.h'):
367b8e80941Smrg            cppdefines += ['HAVE_ENDIAN_H']
368b8e80941Smrg
369b8e80941Smrg        if check_functions(env, ['strtod_l', 'strtof_l']):
370b8e80941Smrg            cppdefines += ['HAVE_STRTOD_L']
371b8e80941Smrg
372b8e80941Smrg        if check_functions(env, ['timespec_get']):
373b8e80941Smrg            cppdefines += ['HAVE_TIMESPEC_GET']
374b8e80941Smrg
375848b8605Smrg    if platform == 'windows':
376848b8605Smrg        cppdefines += [
377848b8605Smrg            'WIN32',
378848b8605Smrg            '_WINDOWS',
379848b8605Smrg            #'_UNICODE',
380848b8605Smrg            #'UNICODE',
381848b8605Smrg            # http://msdn.microsoft.com/en-us/library/aa383745.aspx
382848b8605Smrg            ('_WIN32_WINNT', '0x0601'),
383848b8605Smrg            ('WINVER', '0x0601'),
384848b8605Smrg        ]
385848b8605Smrg        if gcc_compat:
386848b8605Smrg            cppdefines += [('__MSVCRT_VERSION__', '0x0700')]
387848b8605Smrg        if msvc:
388848b8605Smrg            cppdefines += [
389848b8605Smrg                'VC_EXTRALEAN',
390848b8605Smrg                '_USE_MATH_DEFINES',
391848b8605Smrg                '_CRT_SECURE_NO_WARNINGS',
392848b8605Smrg                '_CRT_SECURE_NO_DEPRECATE',
393848b8605Smrg                '_SCL_SECURE_NO_WARNINGS',
394848b8605Smrg                '_SCL_SECURE_NO_DEPRECATE',
395848b8605Smrg                '_ALLOW_KEYWORD_MACROS',
396b8e80941Smrg                '_HAS_EXCEPTIONS=0', # Tell C++ STL to not use exceptions
397848b8605Smrg            ]
398848b8605Smrg        if env['build'] in ('debug', 'checked'):
399848b8605Smrg            cppdefines += ['_DEBUG']
400848b8605Smrg    if platform == 'windows':
401848b8605Smrg        cppdefines += ['PIPE_SUBSYSTEM_WINDOWS_USER']
402848b8605Smrg    if env['embedded']:
403848b8605Smrg        cppdefines += ['PIPE_SUBSYSTEM_EMBEDDED']
404848b8605Smrg    env.Append(CPPDEFINES = cppdefines)
405848b8605Smrg
406848b8605Smrg    # C compiler options
407848b8605Smrg    cflags = [] # C
408848b8605Smrg    cxxflags = [] # C++
409848b8605Smrg    ccflags = [] # C & C++
410848b8605Smrg    if gcc_compat:
411848b8605Smrg        if env['build'] == 'debug':
412848b8605Smrg            ccflags += ['-O0']
413848b8605Smrg        else:
414848b8605Smrg            ccflags += ['-O3']
415848b8605Smrg        if env['gcc']:
416848b8605Smrg            # gcc's builtin memcmp is slower than glibc's
417848b8605Smrg            # http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43052
418848b8605Smrg            ccflags += ['-fno-builtin-memcmp']
419848b8605Smrg        # Work around aliasing bugs - developers should comment this out
420848b8605Smrg        ccflags += ['-fno-strict-aliasing']
421848b8605Smrg        ccflags += ['-g']
422b8e80941Smrg        if env['build'] in ('checked', 'profile') or env['asan']:
423848b8605Smrg            # See http://code.google.com/p/jrfonseca/wiki/Gprof2Dot#Which_options_should_I_pass_to_gcc_when_compiling_for_profiling?
424848b8605Smrg            ccflags += [
425848b8605Smrg                '-fno-omit-frame-pointer',
426848b8605Smrg            ]
427848b8605Smrg            if env['gcc']:
428848b8605Smrg                ccflags += ['-fno-optimize-sibling-calls']
429848b8605Smrg        if env['machine'] == 'x86':
430848b8605Smrg            ccflags += [
431848b8605Smrg                '-m32',
432848b8605Smrg                #'-march=pentium4',
433848b8605Smrg            ]
434b8e80941Smrg            if platform != 'haiku':
435848b8605Smrg                # NOTE: We need to ensure stack is realigned given that we
436848b8605Smrg                # produce shared objects, and have no control over the stack
437848b8605Smrg                # alignment policy of the application. Therefore we need
438848b8605Smrg                # -mstackrealign ore -mincoming-stack-boundary=2.
439848b8605Smrg                #
440848b8605Smrg                # XXX: We could have SSE without -mstackrealign if we always used
441848b8605Smrg                # __attribute__((force_align_arg_pointer)), but that's not
442848b8605Smrg                # always the case.
443848b8605Smrg                ccflags += [
444848b8605Smrg                    '-mstackrealign', # ensure stack is aligned
445b8e80941Smrg                    '-msse', '-msse2', # enable SIMD intrinsics
446b8e80941Smrg                    '-mfpmath=sse', # generate SSE floating-point arithmetic
447848b8605Smrg                ]
448848b8605Smrg            if platform in ['windows', 'darwin']:
449848b8605Smrg                # Workaround http://gcc.gnu.org/bugzilla/show_bug.cgi?id=37216
450848b8605Smrg                ccflags += ['-fno-common']
451848b8605Smrg            if platform in ['haiku']:
452848b8605Smrg                # Make optimizations compatible with Pentium or higher on Haiku
453848b8605Smrg                ccflags += [
454848b8605Smrg                    '-mstackrealign', # ensure stack is aligned
455848b8605Smrg                    '-march=i586', # Haiku target is Pentium
456848b8605Smrg                    '-mtune=i686' # use i686 where we can
457848b8605Smrg                ]
458848b8605Smrg        if env['machine'] == 'x86_64':
459848b8605Smrg            ccflags += ['-m64']
460848b8605Smrg            if platform == 'darwin':
461848b8605Smrg                ccflags += ['-fno-common']
462848b8605Smrg        if env['platform'] not in ('cygwin', 'haiku', 'windows'):
463848b8605Smrg            ccflags += ['-fvisibility=hidden']
464848b8605Smrg        # See also:
465848b8605Smrg        # - http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
466848b8605Smrg        ccflags += [
467848b8605Smrg            '-Wall',
468848b8605Smrg            '-Wno-long-long',
469848b8605Smrg            '-fmessage-length=0', # be nice to Eclipse
470848b8605Smrg        ]
471848b8605Smrg        cflags += [
472848b8605Smrg            '-Wmissing-prototypes',
473848b8605Smrg            '-std=gnu99',
474848b8605Smrg        ]
475848b8605Smrg    if icc:
476848b8605Smrg        cflags += [
477848b8605Smrg            '-std=gnu99',
478848b8605Smrg        ]
479848b8605Smrg    if msvc:
480848b8605Smrg        # See also:
481848b8605Smrg        # - http://msdn.microsoft.com/en-us/library/19z1t1wy.aspx
482848b8605Smrg        # - cl /?
483848b8605Smrg        if env['build'] == 'debug':
484848b8605Smrg            ccflags += [
485848b8605Smrg              '/Od', # disable optimizations
486848b8605Smrg              '/Oi', # enable intrinsic functions
487848b8605Smrg            ]
488848b8605Smrg        else:
489848b8605Smrg            ccflags += [
490848b8605Smrg                '/O2', # optimize for speed
491848b8605Smrg            ]
492848b8605Smrg        if env['build'] == 'release':
493b8e80941Smrg            if not env['clang']:
494b8e80941Smrg                ccflags += [
495b8e80941Smrg                    '/GL', # enable whole program optimization
496b8e80941Smrg                ]
497848b8605Smrg        else:
498848b8605Smrg            ccflags += [
499848b8605Smrg                '/Oy-', # disable frame pointer omission
500848b8605Smrg            ]
501848b8605Smrg        ccflags += [
502848b8605Smrg            '/W3', # warning level
503b8e80941Smrg            '/wd4018', # signed/unsigned mismatch
504b8e80941Smrg            '/wd4056', # overflow in floating-point constant arithmetic
505848b8605Smrg            '/wd4244', # conversion from 'type1' to 'type2', possible loss of data
506b8e80941Smrg            '/wd4267', # 'var' : conversion from 'size_t' to 'type', possible loss of data
507848b8605Smrg            '/wd4305', # truncation from 'type1' to 'type2'
508b8e80941Smrg            '/wd4351', # new behavior: elements of array 'array' will be default initialized
509b8e80941Smrg            '/wd4756', # overflow in constant arithmetic
510848b8605Smrg            '/wd4800', # forcing value to bool 'true' or 'false' (performance warning)
511848b8605Smrg            '/wd4996', # disable deprecated POSIX name warnings
512848b8605Smrg        ]
513b8e80941Smrg        if env['clang']:
514b8e80941Smrg            ccflags += [
515b8e80941Smrg                '-Wno-microsoft-enum-value', # enumerator value is not representable in underlying type 'int'
516b8e80941Smrg            ]
517848b8605Smrg        if env['machine'] == 'x86':
518848b8605Smrg            ccflags += [
519b8e80941Smrg                '/arch:SSE2', # use the SSE2 instructions (default since MSVC 2012)
520848b8605Smrg            ]
521848b8605Smrg        if platform == 'windows':
522848b8605Smrg            ccflags += [
523848b8605Smrg                # TODO
524848b8605Smrg            ]
525848b8605Smrg        # Automatic pdb generation
526848b8605Smrg        # See http://scons.tigris.org/issues/show_bug.cgi?id=1656
527848b8605Smrg        env.EnsureSConsVersion(0, 98, 0)
528848b8605Smrg        env['PDB'] = '${TARGET.base}.pdb'
529848b8605Smrg    env.Append(CCFLAGS = ccflags)
530848b8605Smrg    env.Append(CFLAGS = cflags)
531848b8605Smrg    env.Append(CXXFLAGS = cxxflags)
532848b8605Smrg
533848b8605Smrg    if env['platform'] == 'windows' and msvc:
534848b8605Smrg        # Choose the appropriate MSVC CRT
535848b8605Smrg        # http://msdn.microsoft.com/en-us/library/2kzt1wy3.aspx
536848b8605Smrg        if env['build'] in ('debug', 'checked'):
537848b8605Smrg            env.Append(CCFLAGS = ['/MTd'])
538848b8605Smrg            env.Append(SHCCFLAGS = ['/LDd'])
539848b8605Smrg        else:
540848b8605Smrg            env.Append(CCFLAGS = ['/MT'])
541848b8605Smrg            env.Append(SHCCFLAGS = ['/LD'])
542848b8605Smrg
543848b8605Smrg    # Static code analysis
544848b8605Smrg    if env['analyze']:
545848b8605Smrg        if env['msvc']:
546848b8605Smrg            # http://msdn.microsoft.com/en-us/library/ms173498.aspx
547848b8605Smrg            env.Append(CCFLAGS = [
548848b8605Smrg                '/analyze',
549848b8605Smrg                #'/analyze:log', '${TARGET.base}.xml',
550b8e80941Smrg                '/wd28251', # Inconsistent annotation for function
551848b8605Smrg            ])
552848b8605Smrg        if env['clang']:
553848b8605Smrg            # scan-build will produce more comprehensive output
554848b8605Smrg            env.Append(CCFLAGS = ['--analyze'])
555848b8605Smrg
556b8e80941Smrg    # https://github.com/google/sanitizers/wiki/AddressSanitizer
557b8e80941Smrg    if env['asan']:
558b8e80941Smrg        if gcc_compat:
559b8e80941Smrg            env.Append(CCFLAGS = [
560b8e80941Smrg                '-fsanitize=address',
561b8e80941Smrg            ])
562b8e80941Smrg            env.Append(LINKFLAGS = [
563b8e80941Smrg                '-fsanitize=address',
564b8e80941Smrg            ])
565b8e80941Smrg
566848b8605Smrg    # Assembler options
567848b8605Smrg    if gcc_compat:
568848b8605Smrg        if env['machine'] == 'x86':
569848b8605Smrg            env.Append(ASFLAGS = ['-m32'])
570848b8605Smrg        if env['machine'] == 'x86_64':
571848b8605Smrg            env.Append(ASFLAGS = ['-m64'])
572848b8605Smrg
573848b8605Smrg    # Linker options
574848b8605Smrg    linkflags = []
575848b8605Smrg    shlinkflags = []
576848b8605Smrg    if gcc_compat:
577848b8605Smrg        if env['machine'] == 'x86':
578848b8605Smrg            linkflags += ['-m32']
579848b8605Smrg        if env['machine'] == 'x86_64':
580848b8605Smrg            linkflags += ['-m64']
581848b8605Smrg        if env['platform'] not in ('darwin'):
582848b8605Smrg            shlinkflags += [
583848b8605Smrg                '-Wl,-Bsymbolic',
584848b8605Smrg            ]
585848b8605Smrg        # Handle circular dependencies in the libraries
586848b8605Smrg        if env['platform'] in ('darwin'):
587848b8605Smrg            pass
588848b8605Smrg        else:
589848b8605Smrg            env['_LIBFLAGS'] = '-Wl,--start-group ' + env['_LIBFLAGS'] + ' -Wl,--end-group'
590848b8605Smrg        if env['platform'] == 'windows':
591b8e80941Smrg            linkflags += [
592b8e80941Smrg                '-Wl,--nxcompat', # DEP
593b8e80941Smrg                '-Wl,--dynamicbase', # ASLR
594b8e80941Smrg            ]
595848b8605Smrg            # Avoid depending on gcc runtime DLLs
596848b8605Smrg            linkflags += ['-static-libgcc']
597848b8605Smrg            if 'w64' in env['CC'].split('-'):
598848b8605Smrg                linkflags += ['-static-libstdc++']
599848b8605Smrg            # Handle the @xx symbol munging of DLL exports
600848b8605Smrg            shlinkflags += ['-Wl,--enable-stdcall-fixup']
601848b8605Smrg            #shlinkflags += ['-Wl,--kill-at']
602848b8605Smrg    if msvc:
603b8e80941Smrg        if env['build'] == 'release' and not env['clang']:
604848b8605Smrg            # enable Link-time Code Generation
605848b8605Smrg            linkflags += ['/LTCG']
606848b8605Smrg            env.Append(ARFLAGS = ['/LTCG'])
607848b8605Smrg    if platform == 'windows' and msvc:
608848b8605Smrg        # See also:
609848b8605Smrg        # - http://msdn2.microsoft.com/en-us/library/y0zzbyt4.aspx
610848b8605Smrg        linkflags += [
611848b8605Smrg            '/fixed:no',
612848b8605Smrg            '/incremental:no',
613b8e80941Smrg            '/dynamicbase', # ASLR
614b8e80941Smrg            '/nxcompat', # DEP
615848b8605Smrg        ]
616848b8605Smrg    env.Append(LINKFLAGS = linkflags)
617848b8605Smrg    env.Append(SHLINKFLAGS = shlinkflags)
618848b8605Smrg
619848b8605Smrg    # We have C++ in several libraries, so always link with the C++ compiler
620848b8605Smrg    if gcc_compat:
621848b8605Smrg        env['LINK'] = env['CXX']
622848b8605Smrg
623848b8605Smrg    # Default libs
624848b8605Smrg    libs = []
625848b8605Smrg    if env['platform'] in ('darwin', 'freebsd', 'linux', 'posix', 'sunos'):
626848b8605Smrg        libs += ['m', 'pthread', 'dl']
627848b8605Smrg    if env['platform'] in ('linux',):
628848b8605Smrg        libs += ['rt']
629848b8605Smrg    if env['platform'] in ('haiku'):
630848b8605Smrg        libs += ['root', 'be', 'network', 'translation']
631848b8605Smrg    env.Append(LIBS = libs)
632848b8605Smrg
633848b8605Smrg    # OpenMP
634848b8605Smrg    if env['openmp']:
635848b8605Smrg        if env['msvc']:
636848b8605Smrg            env.Append(CCFLAGS = ['/openmp'])
637848b8605Smrg            # When building openmp release VS2008 link.exe crashes with LNK1103 error.
638848b8605Smrg            # Workaround: overwrite PDB flags with empty value as it isn't required anyways
639848b8605Smrg            if env['build'] == 'release':
640848b8605Smrg                env['PDB'] = ''
641848b8605Smrg        if env['gcc']:
642848b8605Smrg            env.Append(CCFLAGS = ['-fopenmp'])
643848b8605Smrg            env.Append(LIBS = ['gomp'])
644848b8605Smrg
645848b8605Smrg    # Load tools
646848b8605Smrg    env.Tool('lex')
647b8e80941Smrg    if env['msvc']:
648b8e80941Smrg        env.Append(LEXFLAGS = [
649b8e80941Smrg            # Force flex to use const keyword in prototypes, as relies on
650b8e80941Smrg            # __cplusplus or __STDC__ macro to determine whether it's safe to
651b8e80941Smrg            # use const keyword, but MSVC never defines __STDC__ unless we
652b8e80941Smrg            # disable all MSVC extensions.
653b8e80941Smrg            '-DYY_USE_CONST=',
654b8e80941Smrg        ])
655b8e80941Smrg        # Flex relies on __STDC_VERSION__>=199901L to decide when to include
656b8e80941Smrg        # C99 inttypes.h.  We always have inttypes.h available with MSVC
657b8e80941Smrg        # (either the one bundled with MSVC 2013, or the one we bundle
658b8e80941Smrg        # ourselves), but we can't just define __STDC_VERSION__ without
659b8e80941Smrg        # breaking stuff, as MSVC doesn't fully support C99.  There's also no
660b8e80941Smrg        # way to premptively include stdint.
661b8e80941Smrg        env.Append(CCFLAGS = ['-FIinttypes.h'])
662b8e80941Smrg    if host_platform.system() == 'Windows':
663b8e80941Smrg        # Prefer winflexbison binaries, as not only they are easier to install
664b8e80941Smrg        # (no additional dependencies), but also better Windows support.
665b8e80941Smrg        if check_prog(env, 'win_flex'):
666b8e80941Smrg            env["LEX"] = 'win_flex'
667b8e80941Smrg            env.Append(LEXFLAGS = [
668b8e80941Smrg                # windows compatibility (uses <io.h> instead of <unistd.h> and
669b8e80941Smrg                # _isatty, _fileno functions)
670b8e80941Smrg                '--wincompat'
671b8e80941Smrg            ])
672b8e80941Smrg
673848b8605Smrg    env.Tool('yacc')
674b8e80941Smrg    if host_platform.system() == 'Windows':
675b8e80941Smrg        if check_prog(env, 'win_bison'):
676b8e80941Smrg            env["YACC"] = 'win_bison'
677b8e80941Smrg
678848b8605Smrg    if env['llvm']:
679848b8605Smrg        env.Tool('llvm')
680848b8605Smrg
681848b8605Smrg    # Custom builders and methods
682848b8605Smrg    env.Tool('custom')
683b8e80941Smrg    env.AddMethod(install_program, 'InstallProgram')
684b8e80941Smrg    env.AddMethod(install_shared_library, 'InstallSharedLibrary')
685b8e80941Smrg    env.AddMethod(msvc2013_compat, 'MSVC2013Compat')
686b8e80941Smrg    env.AddMethod(unit_test, 'UnitTest')
687848b8605Smrg
688b8e80941Smrg    env.PkgCheckModules('X11', ['x11', 'xext', 'xdamage >= 1.1', 'xfixes', 'glproto >= 1.4.13', 'dri2proto >= 2.8'])
689848b8605Smrg    env.PkgCheckModules('XCB', ['x11-xcb', 'xcb-glx >= 1.8.1', 'xcb-dri2 >= 1.8'])
690848b8605Smrg    env.PkgCheckModules('XF86VIDMODE', ['xxf86vm'])
691b8e80941Smrg    env.PkgCheckModules('DRM', ['libdrm >= 2.4.75'])
692b8e80941Smrg
693b8e80941Smrg    if not os.path.exists("src/util/format_srgb.c"):
694b8e80941Smrg        print("Checking for Python Mako module (>= 0.8.0)... ", end='')
695b8e80941Smrg        try:
696b8e80941Smrg            import mako
697b8e80941Smrg        except ImportError:
698b8e80941Smrg            print("no")
699b8e80941Smrg            exit(1)
700b8e80941Smrg        if distutils.version.StrictVersion(mako.__version__) < distutils.version.StrictVersion('0.8.0'):
701b8e80941Smrg            print("no")
702b8e80941Smrg            exit(1)
703b8e80941Smrg        print("yes")
704b8e80941Smrg
705b8e80941Smrg    if env['x11']:
706b8e80941Smrg        env.Append(CPPPATH = env['X11_CPPPATH'])
707848b8605Smrg
708848b8605Smrg    env['dri'] = env['x11'] and env['drm']
709848b8605Smrg
710848b8605Smrg    # for debugging
711848b8605Smrg    #print env.Dump()
712848b8605Smrg
713848b8605Smrg
714848b8605Smrgdef exists(env):
715848b8605Smrg    return 1
716