SConstruct revision 5990
1# -*- mode:python -*-
2
3# Copyright (c) 2009 The Hewlett-Packard Development Company
4# Copyright (c) 2004-2005 The Regents of The University of Michigan
5# All rights reserved.
6#
7# Redistribution and use in source and binary forms, with or without
8# modification, are permitted provided that the following conditions are
9# met: redistributions of source code must retain the above copyright
10# notice, this list of conditions and the following disclaimer;
11# redistributions in binary form must reproduce the above copyright
12# notice, this list of conditions and the following disclaimer in the
13# documentation and/or other materials provided with the distribution;
14# neither the name of the copyright holders nor the names of its
15# contributors may be used to endorse or promote products derived from
16# this software without specific prior written permission.
17#
18# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29#
30# Authors: Steve Reinhardt
31#          Nathan Binkert
32
33###################################################
34#
35# SCons top-level build description (SConstruct) file.
36#
37# While in this directory ('m5'), just type 'scons' to build the default
38# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
39# to build some other configuration (e.g., 'build/ALPHA_FS/m5.opt' for
40# the optimized full-system version).
41#
42# You can build M5 in a different directory as long as there is a
43# 'build/<CONFIG>' somewhere along the target path.  The build system
44# expects that all configs under the same build directory are being
45# built for the same host system.
46#
47# Examples:
48#
49#   The following two commands are equivalent.  The '-u' option tells
50#   scons to search up the directory tree for this SConstruct file.
51#   % cd <path-to-src>/m5 ; scons build/ALPHA_FS/m5.debug
52#   % cd <path-to-src>/m5/build/ALPHA_FS; scons -u m5.debug
53#
54#   The following two commands are equivalent and demonstrate building
55#   in a directory outside of the source tree.  The '-C' option tells
56#   scons to chdir to the specified directory to find this SConstruct
57#   file.
58#   % cd <path-to-src>/m5 ; scons /local/foo/build/ALPHA_FS/m5.debug
59#   % cd /local/foo/build/ALPHA_FS; scons -C <path-to-src>/m5 m5.debug
60#
61# You can use 'scons -H' to print scons options.  If you're in this
62# 'm5' directory (or use -u or -C to tell scons where to find this
63# file), you can use 'scons -h' to print all the M5-specific build
64# options as well.
65#
66###################################################
67
68# Check for recent-enough Python and SCons versions.
69try:
70    # Really old versions of scons only take two options for the
71    # function, so check once without the revision and once with the
72    # revision, the first instance will fail for stuff other than
73    # 0.98, and the second will fail for 0.98.0
74    EnsureSConsVersion(0, 98)
75    EnsureSConsVersion(0, 98, 1)
76except SystemExit, e:
77    print """
78For more details, see:
79    http://m5sim.org/wiki/index.php/Compiling_M5
80"""
81    raise
82
83# We ensure the python version early because we have stuff that
84# requires python 2.4
85try:
86    EnsurePythonVersion(2, 4)
87except SystemExit, e:
88    print """
89You can use a non-default installation of the Python interpreter by
90either (1) rearranging your PATH so that scons finds the non-default
91'python' first or (2) explicitly invoking an alternative interpreter
92on the scons script.
93
94For more details, see:
95    http://m5sim.org/wiki/index.php/Using_a_non-default_Python_installation
96"""
97    raise
98
99import os
100import re
101import subprocess
102import sys
103
104from os import mkdir, environ
105from os.path import abspath, basename, dirname, expanduser, normpath
106from os.path import exists,  isdir, isfile
107from os.path import join as joinpath, split as splitpath
108
109import SCons
110import SCons.Node
111
112def read_command(cmd, **kwargs):
113    """run the command cmd, read the results and return them
114    this is sorta like `cmd` in shell"""
115    from subprocess import Popen, PIPE, STDOUT
116
117    if isinstance(cmd, str):
118        cmd = cmd.split()
119
120    no_exception = 'exception' in kwargs
121    exception = kwargs.pop('exception', None)
122    
123    kwargs.setdefault('shell', False)
124    kwargs.setdefault('stdout', PIPE)
125    kwargs.setdefault('stderr', STDOUT)
126    kwargs.setdefault('close_fds', True)
127    try:
128        subp = Popen(cmd, **kwargs)
129    except Exception, e:
130        if no_exception:
131            return exception
132        raise
133
134    return subp.communicate()[0]
135
136# helper function: compare arrays or strings of version numbers.
137# E.g., compare_version((1,3,25), (1,4,1)')
138# returns -1, 0, 1 if v1 is <, ==, > v2
139def compare_versions(v1, v2):
140    def make_version_list(v):
141        if isinstance(v, (list,tuple)):
142            return v
143        elif isinstance(v, str):
144            return map(lambda x: int(re.match('\d+', x).group()), v.split('.'))
145        else:
146            raise TypeError
147
148    v1 = make_version_list(v1)
149    v2 = make_version_list(v2)
150    # Compare corresponding elements of lists
151    for n1,n2 in zip(v1, v2):
152        if n1 < n2: return -1
153        if n1 > n2: return  1
154    # all corresponding values are equal... see if one has extra values
155    if len(v1) < len(v2): return -1
156    if len(v1) > len(v2): return  1
157    return 0
158
159########################################################################
160#
161# Set up the base build environment.
162#
163########################################################################
164use_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'PATH', 'RANLIB' ])
165
166use_env = {}
167for key,val in os.environ.iteritems():
168    if key in use_vars or key.startswith("M5"):
169        use_env[key] = val
170
171env = Environment(ENV=use_env)
172env.root = Dir(".")          # The current directory (where this file lives).
173env.srcdir = Dir("src")      # The source directory
174
175########################################################################
176#
177# Mercurial Stuff.
178#
179# If the M5 directory is a mercurial repository, we should do some
180# extra things.
181#
182########################################################################
183
184hgdir = env.root.Dir(".hg")
185
186mercurial_style_message = """
187You're missing the M5 style hook.
188Please install the hook so we can ensure that all code fits a common style.
189
190All you'd need to do is add the following lines to your repository .hg/hgrc
191or your personal .hgrc
192----------------
193
194[extensions]
195style = %s/util/style.py
196
197[hooks]
198pretxncommit.style = python:style.check_whitespace
199""" % (env.root)
200
201mercurial_bin_not_found = """
202Mercurial binary cannot be found, unfortunately this means that we
203cannot easily determine the version of M5 that you are running and
204this makes error messages more difficult to collect.  Please consider
205installing mercurial if you choose to post an error message
206"""
207
208mercurial_lib_not_found = """
209Mercurial libraries cannot be found, ignoring style hook
210If you are actually a M5 developer, please fix this and
211run the style hook. It is important.
212"""
213
214hg_info = "Unknown"
215if hgdir.exists():
216    # 1) Grab repository revision if we know it.
217    cmd = "hg id -n -i -t -b"
218    try:
219        hg_info = read_command(cmd, cwd=env.root.abspath).strip()
220    except OSError:
221        print mercurial_bin_not_found
222
223    # 2) Ensure that the style hook is in place.
224    try:
225        ui = None
226        if ARGUMENTS.get('IGNORE_STYLE') != 'True':
227            from mercurial import ui
228            ui = ui.ui()
229    except ImportError:
230        print mercurial_lib_not_found
231
232    if ui is not None:
233        ui.readconfig(hgdir.File('hgrc').abspath)
234        style_hook = ui.config('hooks', 'pretxncommit.style', None)
235
236        if not style_hook:
237            print mercurial_style_message
238            sys.exit(1)
239else:
240    print ".hg directory not found"
241env['HG_INFO'] = hg_info
242
243###################################################
244#
245# Figure out which configurations to set up based on the path(s) of
246# the target(s).
247#
248###################################################
249
250# Find default configuration & binary.
251Default(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
252
253# helper function: find last occurrence of element in list
254def rfind(l, elt, offs = -1):
255    for i in range(len(l)+offs, 0, -1):
256        if l[i] == elt:
257            return i
258    raise ValueError, "element not found"
259
260# Each target must have 'build' in the interior of the path; the
261# directory below this will determine the build parameters.  For
262# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
263# recognize that ALPHA_SE specifies the configuration because it
264# follow 'build' in the bulid path.
265
266# Generate absolute paths to targets so we can see where the build dir is
267if COMMAND_LINE_TARGETS:
268    # Ask SCons which directory it was invoked from
269    launch_dir = GetLaunchDir()
270    # Make targets relative to invocation directory
271    abs_targets = [ normpath(joinpath(launch_dir, str(x))) for x in \
272                    COMMAND_LINE_TARGETS]
273else:
274    # Default targets are relative to root of tree
275    abs_targets = [ normpath(joinpath(ROOT, str(x))) for x in \
276                    DEFAULT_TARGETS]
277
278
279# Generate a list of the unique build roots and configs that the
280# collected targets reference.
281variant_paths = []
282build_root = None
283for t in abs_targets:
284    path_dirs = t.split('/')
285    try:
286        build_top = rfind(path_dirs, 'build', -2)
287    except:
288        print "Error: no non-leaf 'build' dir found on target path", t
289        Exit(1)
290    this_build_root = joinpath('/',*path_dirs[:build_top+1])
291    if not build_root:
292        build_root = this_build_root
293    else:
294        if this_build_root != build_root:
295            print "Error: build targets not under same build root\n"\
296                  "  %s\n  %s" % (build_root, this_build_root)
297            Exit(1)
298    variant_path = joinpath('/',*path_dirs[:build_top+2])
299    if variant_path not in variant_paths:
300        variant_paths.append(variant_path)
301
302# Make sure build_root exists (might not if this is the first build there)
303if not isdir(build_root):
304    mkdir(build_root)
305
306Export('env')
307
308env.SConsignFile(joinpath(build_root, "sconsign"))
309
310# Default duplicate option is to use hard links, but this messes up
311# when you use emacs to edit a file in the target dir, as emacs moves
312# file to file~ then copies to file, breaking the link.  Symbolic
313# (soft) links work better.
314env.SetOption('duplicate', 'soft-copy')
315
316#
317# Set up global sticky variables... these are common to an entire build
318# tree (not specific to a particular build like ALPHA_SE)
319#
320
321# Variable validators & converters for global sticky variables
322def PathListMakeAbsolute(val):
323    if not val:
324        return val
325    f = lambda p: abspath(expanduser(p))
326    return ':'.join(map(f, val.split(':')))
327
328def PathListAllExist(key, val, env):
329    if not val:
330        return
331    paths = val.split(':')
332    for path in paths:
333        if not isdir(path):
334            raise SCons.Errors.UserError("Path does not exist: '%s'" % path)
335
336global_sticky_vars_file = joinpath(build_root, 'variables.global')
337
338global_sticky_vars = Variables(global_sticky_vars_file, args=ARGUMENTS)
339
340global_sticky_vars.AddVariables(
341    ('CC', 'C compiler', environ.get('CC', env['CC'])),
342    ('CXX', 'C++ compiler', environ.get('CXX', env['CXX'])),
343    ('BATCH', 'Use batch pool for build and tests', False),
344    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
345    ('EXTRAS', 'Add Extra directories to the compilation', '',
346     PathListAllExist, PathListMakeAbsolute)
347    )    
348
349# base help text
350help_text = '''
351Usage: scons [scons options] [build options] [target(s)]
352
353Global sticky options:
354'''
355
356help_text += global_sticky_vars.GenerateHelpText(env)
357
358# Update env with values from ARGUMENTS & file global_sticky_vars_file
359global_sticky_vars.Update(env)
360
361# Save sticky variable settings back to current variables file
362global_sticky_vars.Save(global_sticky_vars_file, env)
363
364# Parse EXTRAS variable to build list of all directories where we're
365# look for sources etc.  This list is exported as base_dir_list.
366base_dir = env.srcdir.abspath
367if env['EXTRAS']:
368    extras_dir_list = env['EXTRAS'].split(':')
369else:
370    extras_dir_list = []
371
372Export('base_dir')
373Export('extras_dir_list')
374
375# M5_PLY is used by isa_parser.py to find the PLY package.
376env.Append(ENV = { 'M5_PLY' : str(Dir('ext/ply')) })
377
378CXX_version = read_command([env['CXX'],'--version'], exception=False)
379CXX_V = read_command([env['CXX'],'-V'], exception=False)
380
381env['GCC'] = CXX_version and CXX_version.find('g++') >= 0
382env['SUNCC'] = CXX_V and CXX_V.find('Sun C++') >= 0
383env['ICC'] = CXX_V and CXX_V.find('Intel') >= 0
384if env['GCC'] + env['SUNCC'] + env['ICC'] > 1:
385    print 'Error: How can we have two at the same time?'
386    Exit(1)
387
388# Set up default C++ compiler flags
389if env['GCC']:
390    env.Append(CCFLAGS='-pipe')
391    env.Append(CCFLAGS='-fno-strict-aliasing')
392    env.Append(CCFLAGS=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
393    env.Append(CXXFLAGS='-Wno-deprecated')
394elif env['ICC']:
395    pass #Fix me... add warning flags once we clean up icc warnings
396elif env['SUNCC']:
397    env.Append(CCFLAGS='-Qoption ccfe')
398    env.Append(CCFLAGS='-features=gcc')
399    env.Append(CCFLAGS='-features=extensions')
400    env.Append(CCFLAGS='-library=stlport4')
401    env.Append(CCFLAGS='-xar')
402    #env.Append(CCFLAGS='-instances=semiexplicit')
403else:
404    print 'Error: Don\'t know what compiler options to use for your compiler.'
405    print '       Please fix SConstruct and src/SConscript and try again.'
406    Exit(1)
407
408# Do this after we save setting back, or else we'll tack on an
409# extra 'qdo' every time we run scons.
410if env['BATCH']:
411    env['CC']     = env['BATCH_CMD'] + ' ' + env['CC']
412    env['CXX']    = env['BATCH_CMD'] + ' ' + env['CXX']
413    env['AS']     = env['BATCH_CMD'] + ' ' + env['AS']
414    env['AR']     = env['BATCH_CMD'] + ' ' + env['AR']
415    env['RANLIB'] = env['BATCH_CMD'] + ' ' + env['RANLIB']
416
417if sys.platform == 'cygwin':
418    # cygwin has some header file issues...
419    env.Append(CCFLAGS=Split("-Wno-uninitialized"))
420env.Append(CPPPATH=[Dir('ext/dnet')])
421
422# Check for SWIG
423if not env.has_key('SWIG'):
424    print 'Error: SWIG utility not found.'
425    print '       Please install (see http://www.swig.org) and retry.'
426    Exit(1)
427
428# Check for appropriate SWIG version
429swig_version = read_command(('swig', '-version'), exception='').split()
430# First 3 words should be "SWIG Version x.y.z"
431if len(swig_version) < 3 or \
432        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
433    print 'Error determining SWIG version.'
434    Exit(1)
435
436min_swig_version = '1.3.28'
437if compare_versions(swig_version[2], min_swig_version) < 0:
438    print 'Error: SWIG version', min_swig_version, 'or newer required.'
439    print '       Installed version:', swig_version[2]
440    Exit(1)
441
442# Set up SWIG flags & scanner
443swig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
444env.Append(SWIGFLAGS=swig_flags)
445
446# filter out all existing swig scanners, they mess up the dependency
447# stuff for some reason
448scanners = []
449for scanner in env['SCANNERS']:
450    skeys = scanner.skeys
451    if skeys == '.i':
452        continue
453
454    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
455        continue
456
457    scanners.append(scanner)
458
459# add the new swig scanner that we like better
460from SCons.Scanner import ClassicCPP as CPPScanner
461swig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
462scanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
463
464# replace the scanners list that has what we want
465env['SCANNERS'] = scanners
466
467# Add a custom Check function to the Configure context so that we can
468# figure out if the compiler adds leading underscores to global
469# variables.  This is needed for the autogenerated asm files that we
470# use for embedding the python code.
471def CheckLeading(context):
472    context.Message("Checking for leading underscore in global variables...")
473    # 1) Define a global variable called x from asm so the C compiler
474    #    won't change the symbol at all.
475    # 2) Declare that variable.
476    # 3) Use the variable
477    #
478    # If the compiler prepends an underscore, this will successfully
479    # link because the external symbol 'x' will be called '_x' which
480    # was defined by the asm statement.  If the compiler does not
481    # prepend an underscore, this will not successfully link because
482    # '_x' will have been defined by assembly, while the C portion of
483    # the code will be trying to use 'x'
484    ret = context.TryLink('''
485        asm(".globl _x; _x: .byte 0");
486        extern int x;
487        int main() { return x; }
488        ''', extension=".c")
489    context.env.Append(LEADING_UNDERSCORE=ret)
490    context.Result(ret)
491    return ret
492
493# Platform-specific configuration.  Note again that we assume that all
494# builds under a given build root run on the same host platform.
495conf = Configure(env,
496                 conf_dir = joinpath(build_root, '.scons_config'),
497                 log_file = joinpath(build_root, 'scons_config.log'),
498                 custom_tests = { 'CheckLeading' : CheckLeading })
499
500# Check for leading underscores.  Don't really need to worry either
501# way so don't need to check the return code.
502conf.CheckLeading()
503
504# Check if we should compile a 64 bit binary on Mac OS X/Darwin
505try:
506    import platform
507    uname = platform.uname()
508    if uname[0] == 'Darwin' and compare_versions(uname[2], '9.0.0') >= 0:
509        if int(read_command('sysctl -n hw.cpu64bit_capable')[0]):
510            env.Append(CCFLAGS='-arch x86_64')
511            env.Append(CFLAGS='-arch x86_64')
512            env.Append(LINKFLAGS='-arch x86_64')
513            env.Append(ASFLAGS='-arch x86_64')
514except:
515    pass
516
517# Recent versions of scons substitute a "Null" object for Configure()
518# when configuration isn't necessary, e.g., if the "--help" option is
519# present.  Unfortuantely this Null object always returns false,
520# breaking all our configuration checks.  We replace it with our own
521# more optimistic null object that returns True instead.
522if not conf:
523    def NullCheck(*args, **kwargs):
524        return True
525
526    class NullConf:
527        def __init__(self, env):
528            self.env = env
529        def Finish(self):
530            return self.env
531        def __getattr__(self, mname):
532            return NullCheck
533
534    conf = NullConf(env)
535
536# Find Python include and library directories for embedding the
537# interpreter.  For consistency, we will use the same Python
538# installation used to run scons (and thus this script).  If you want
539# to link in an alternate version, see above for instructions on how
540# to invoke scons with a different copy of the Python interpreter.
541from distutils import sysconfig
542
543py_getvar = sysconfig.get_config_var
544
545py_version = 'python' + py_getvar('VERSION')
546
547py_general_include = sysconfig.get_python_inc()
548py_platform_include = sysconfig.get_python_inc(plat_specific=True)
549py_includes = [ py_general_include ]
550if py_platform_include != py_general_include:
551    py_includes.append(py_platform_include)
552
553py_lib_path = []
554# add the prefix/lib/pythonX.Y/config dir, but only if there is no
555# shared library in prefix/lib/.
556if not py_getvar('Py_ENABLE_SHARED'):
557    py_lib_path.append('-L' + py_getvar('LIBPL'))
558
559py_libs = []
560for lib in py_getvar('LIBS').split() + py_getvar('SYSLIBS').split():
561    if lib not in py_libs:
562        py_libs.append(lib)
563py_libs.append('-l' + py_version)
564
565env.Append(CPPPATH=py_includes)
566env.Append(LIBPATH=py_lib_path)
567#env.Append(LIBS=py_libs)
568
569# verify that this stuff works
570if not conf.CheckHeader('Python.h', '<>'):
571    print "Error: can't find Python.h header in", py_includes
572    Exit(1)
573
574for lib in py_libs:
575    assert lib.startswith('-l')
576    lib = lib[2:]
577    if not conf.CheckLib(lib):
578        print "Error: can't find library %s required by python" % lib
579        Exit(1)
580
581# On Solaris you need to use libsocket for socket ops
582if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
583   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
584       print "Can't find library with socket calls (e.g. accept())"
585       Exit(1)
586
587# Check for zlib.  If the check passes, libz will be automatically
588# added to the LIBS environment variable.
589if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
590    print 'Error: did not find needed zlib compression library '\
591          'and/or zlib.h header file.'
592    print '       Please install zlib and try again.'
593    Exit(1)
594
595# Check for <fenv.h> (C99 FP environment control)
596have_fenv = conf.CheckHeader('fenv.h', '<>')
597if not have_fenv:
598    print "Warning: Header file <fenv.h> not found."
599    print "         This host has no IEEE FP rounding mode control."
600
601######################################################################
602#
603# Check for mysql.
604#
605mysql_config = WhereIs('mysql_config')
606have_mysql = bool(mysql_config)
607
608# Check MySQL version.
609if have_mysql:
610    mysql_version = read_command(mysql_config + ' --version')
611    min_mysql_version = '4.1'
612    if compare_versions(mysql_version, min_mysql_version) < 0:
613        print 'Warning: MySQL', min_mysql_version, 'or newer required.'
614        print '         Version', mysql_version, 'detected.'
615        have_mysql = False
616
617# Set up mysql_config commands.
618if have_mysql:
619    mysql_config_include = mysql_config + ' --include'
620    if os.system(mysql_config_include + ' > /dev/null') != 0:
621        # older mysql_config versions don't support --include, use
622        # --cflags instead
623        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
624    # This seems to work in all versions
625    mysql_config_libs = mysql_config + ' --libs'
626
627######################################################################
628#
629# Finish the configuration
630#
631env = conf.Finish()
632
633######################################################################
634#
635# Collect all non-global variables
636#
637
638Export('env')
639
640# Define the universe of supported ISAs
641all_isa_list = [ ]
642Export('all_isa_list')
643
644# Define the universe of supported CPU models
645all_cpu_list = [ ]
646default_cpus = [ ]
647Export('all_cpu_list', 'default_cpus')
648
649# Sticky variables get saved in the variables file so they persist from
650# one invocation to the next (unless overridden, in which case the new
651# value becomes sticky).
652sticky_vars = Variables(args=ARGUMENTS)
653Export('sticky_vars')
654
655# Non-sticky variables only apply to the current build.
656nonsticky_vars = Variables(args=ARGUMENTS)
657Export('nonsticky_vars')
658
659# Walk the tree and execute all SConsopts scripts that wil add to the
660# above variables
661for bdir in [ base_dir ] + extras_dir_list:
662    for root, dirs, files in os.walk(bdir):
663        if 'SConsopts' in files:
664            print "Reading", joinpath(root, 'SConsopts')
665            SConscript(joinpath(root, 'SConsopts'))
666
667all_isa_list.sort()
668all_cpu_list.sort()
669default_cpus.sort()
670
671sticky_vars.AddVariables(
672    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
673    BoolVariable('FULL_SYSTEM', 'Full-system support', False),
674    ListVariable('CPU_MODELS', 'CPU models', default_cpus, all_cpu_list),
675    BoolVariable('NO_FAST_ALLOC', 'Disable fast object allocator', False),
676    BoolVariable('FAST_ALLOC_DEBUG', 'Enable fast object allocator debugging',
677                 False),
678    BoolVariable('FAST_ALLOC_STATS', 'Enable fast object allocator statistics',
679                 False),
680    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
681                 False),
682    BoolVariable('SS_COMPATIBLE_FP',
683                 'Make floating-point results compatible with SimpleScalar',
684                 False),
685    BoolVariable('USE_SSE2',
686                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
687                 False),
688    BoolVariable('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
689    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
690    BoolVariable('USE_CHECKER', 'Use checker for detailed CPU models', False),
691    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
692    )
693
694nonsticky_vars.AddVariables(
695    BoolVariable('update_ref', 'Update test reference outputs', False)
696    )
697
698# These variables get exported to #defines in config/*.hh (see src/SConscript).
699env.ExportVariables = ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
700                       'USE_MYSQL', 'NO_FAST_ALLOC', 'FAST_ALLOC_DEBUG', \
701                       'FAST_ALLOC_STATS', 'SS_COMPATIBLE_FP', \
702                       'USE_CHECKER', 'TARGET_ISA', 'CP_ANNOTATE']
703
704###################################################
705#
706# Define a SCons builder for configuration flag headers.
707#
708###################################################
709
710# This function generates a config header file that #defines the
711# variable symbol to the current variable setting (0 or 1).  The source
712# operands are the name of the variable and a Value node containing the
713# value of the variable.
714def build_config_file(target, source, env):
715    (variable, value) = [s.get_contents() for s in source]
716    f = file(str(target[0]), 'w')
717    print >> f, '#define', variable, value
718    f.close()
719    return None
720
721# Generate the message to be printed when building the config file.
722def build_config_file_string(target, source, env):
723    (variable, value) = [s.get_contents() for s in source]
724    return "Defining %s as %s in %s." % (variable, value, target[0])
725
726# Combine the two functions into a scons Action object.
727config_action = Action(build_config_file, build_config_file_string)
728
729# The emitter munges the source & target node lists to reflect what
730# we're really doing.
731def config_emitter(target, source, env):
732    # extract variable name from Builder arg
733    variable = str(target[0])
734    # True target is config header file
735    target = joinpath('config', variable.lower() + '.hh')
736    val = env[variable]
737    if isinstance(val, bool):
738        # Force value to 0/1
739        val = int(val)
740    elif isinstance(val, str):
741        val = '"' + val + '"'
742
743    # Sources are variable name & value (packaged in SCons Value nodes)
744    return ([target], [Value(variable), Value(val)])
745
746config_builder = Builder(emitter = config_emitter, action = config_action)
747
748env.Append(BUILDERS = { 'ConfigFile' : config_builder })
749
750# libelf build is shared across all configs in the build root.
751env.SConscript('ext/libelf/SConscript',
752               variant_dir = joinpath(build_root, 'libelf'))
753
754# gzstream build is shared across all configs in the build root.
755env.SConscript('ext/gzstream/SConscript',
756               variant_dir = joinpath(build_root, 'gzstream'))
757
758###################################################
759#
760# This function is used to set up a directory with switching headers
761#
762###################################################
763
764env['ALL_ISA_LIST'] = all_isa_list
765def make_switching_dir(dname, switch_headers, env):
766    # Generate the header.  target[0] is the full path of the output
767    # header to generate.  'source' is a dummy variable, since we get the
768    # list of ISAs from env['ALL_ISA_LIST'].
769    def gen_switch_hdr(target, source, env):
770        fname = str(target[0])
771        bname = basename(fname)
772        f = open(fname, 'w')
773        f.write('#include "arch/isa_specific.hh"\n')
774        cond = '#if'
775        for isa in all_isa_list:
776            f.write('%s THE_ISA == %s_ISA\n#include "%s/%s/%s"\n'
777                    % (cond, isa.upper(), dname, isa, bname))
778            cond = '#elif'
779        f.write('#else\n#error "THE_ISA not set"\n#endif\n')
780        f.close()
781        return 0
782
783    # String to print when generating header
784    def gen_switch_hdr_string(target, source, env):
785        return "Generating switch header " + str(target[0])
786
787    # Build SCons Action object. 'varlist' specifies env vars that this
788    # action depends on; when env['ALL_ISA_LIST'] changes these actions
789    # should get re-executed.
790    switch_hdr_action = Action(gen_switch_hdr, gen_switch_hdr_string,
791                               varlist=['ALL_ISA_LIST'])
792
793    # Instantiate actions for each header
794    for hdr in switch_headers:
795        env.Command(hdr, [], switch_hdr_action)
796Export('make_switching_dir')
797
798###################################################
799#
800# Define build environments for selected configurations.
801#
802###################################################
803
804# rename base env
805base_env = env
806
807for variant_path in variant_paths:
808    print "Building in", variant_path
809
810    # Make a copy of the build-root environment to use for this config.
811    env = base_env.Clone()
812    env['BUILDDIR'] = variant_path
813
814    # variant_dir is the tail component of build path, and is used to
815    # determine the build parameters (e.g., 'ALPHA_SE')
816    (build_root, variant_dir) = splitpath(variant_path)
817
818    # Set env variables according to the build directory config.
819    sticky_vars.files = []
820    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
821    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
822    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
823    current_vars_file = joinpath(build_root, 'variables', variant_dir)
824    if isfile(current_vars_file):
825        sticky_vars.files.append(current_vars_file)
826        print "Using saved variables file %s" % current_vars_file
827    else:
828        # Build dir-specific variables file doesn't exist.
829
830        # Make sure the directory is there so we can create it later
831        opt_dir = dirname(current_vars_file)
832        if not isdir(opt_dir):
833            mkdir(opt_dir)
834
835        # Get default build variables from source tree.  Variables are
836        # normally determined by name of $VARIANT_DIR, but can be
837        # overriden by 'default=' arg on command line.
838        default_vars_file = joinpath('build_opts',
839                                     ARGUMENTS.get('default', variant_dir))
840        if isfile(default_vars_file):
841            sticky_vars.files.append(default_vars_file)
842            print "Variables file %s not found,\n  using defaults in %s" \
843                  % (current_vars_file, default_vars_file)
844        else:
845            print "Error: cannot find variables file %s or %s" \
846                  % (current_vars_file, default_vars_file)
847            Exit(1)
848
849    # Apply current variable settings to env
850    sticky_vars.Update(env)
851    nonsticky_vars.Update(env)
852
853    help_text += "\nSticky variables for %s:\n" % variant_dir \
854                 + sticky_vars.GenerateHelpText(env) \
855                 + "\nNon-sticky variables for %s:\n" % variant_dir \
856                 + nonsticky_vars.GenerateHelpText(env)
857
858    # Process variable settings.
859
860    if not have_fenv and env['USE_FENV']:
861        print "Warning: <fenv.h> not available; " \
862              "forcing USE_FENV to False in", variant_dir + "."
863        env['USE_FENV'] = False
864
865    if not env['USE_FENV']:
866        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
867        print "         FP results may deviate slightly from other platforms."
868
869    if env['EFENCE']:
870        env.Append(LIBS=['efence'])
871
872    if env['USE_MYSQL']:
873        if not have_mysql:
874            print "Warning: MySQL not available; " \
875                  "forcing USE_MYSQL to False in", variant_dir + "."
876            env['USE_MYSQL'] = False
877        else:
878            print "Compiling in", variant_dir, "with MySQL support."
879            env.ParseConfig(mysql_config_libs)
880            env.ParseConfig(mysql_config_include)
881
882    # Save sticky variable settings back to current variables file
883    sticky_vars.Save(current_vars_file, env)
884
885    if env['USE_SSE2']:
886        env.Append(CCFLAGS='-msse2')
887
888    # The src/SConscript file sets up the build rules in 'env' according
889    # to the configured variables.  It returns a list of environments,
890    # one for each variant build (debug, opt, etc.)
891    envList = SConscript('src/SConscript', variant_dir = variant_path,
892                         exports = 'env')
893
894    # Set up the regression tests for each build.
895    for e in envList:
896        SConscript('tests/SConscript',
897                   variant_dir = joinpath(variant_path, 'tests', e.Label),
898                   exports = { 'env' : e }, duplicate = False)
899
900Help(help_text)
901