SConstruct revision 5227
1# -*- mode:python -*-
2
3# Copyright (c) 2004-2005 The Regents of The University of Michigan
4# All rights reserved.
5#
6# Redistribution and use in source and binary forms, with or without
7# modification, are permitted provided that the following conditions are
8# met: redistributions of source code must retain the above copyright
9# notice, this list of conditions and the following disclaimer;
10# redistributions in binary form must reproduce the above copyright
11# notice, this list of conditions and the following disclaimer in the
12# documentation and/or other materials provided with the distribution;
13# neither the name of the copyright holders nor the names of its
14# contributors may be used to endorse or promote products derived from
15# this software without specific prior written permission.
16#
17# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28#
29# Authors: Steve Reinhardt
30
31###################################################
32#
33# SCons top-level build description (SConstruct) file.
34#
35# While in this directory ('m5'), just type 'scons' to build the default
36# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
37# to build some other configuration (e.g., 'build/ALPHA_FS/m5.opt' for
38# the optimized full-system version).
39#
40# You can build M5 in a different directory as long as there is a
41# 'build/<CONFIG>' somewhere along the target path.  The build system
42# expects that all configs under the same build directory are being
43# built for the same host system.
44#
45# Examples:
46#
47#   The following two commands are equivalent.  The '-u' option tells
48#   scons to search up the directory tree for this SConstruct file.
49#   % cd <path-to-src>/m5 ; scons build/ALPHA_FS/m5.debug
50#   % cd <path-to-src>/m5/build/ALPHA_FS; scons -u m5.debug
51#
52#   The following two commands are equivalent and demonstrate building
53#   in a directory outside of the source tree.  The '-C' option tells
54#   scons to chdir to the specified directory to find this SConstruct
55#   file.
56#   % cd <path-to-src>/m5 ; scons /local/foo/build/ALPHA_FS/m5.debug
57#   % cd /local/foo/build/ALPHA_FS; scons -C <path-to-src>/m5 m5.debug
58#
59# You can use 'scons -H' to print scons options.  If you're in this
60# 'm5' directory (or use -u or -C to tell scons where to find this
61# file), you can use 'scons -h' to print all the M5-specific build
62# options as well.
63#
64###################################################
65
66import sys
67import os
68
69from os.path import isdir, join as joinpath
70
71# Check for recent-enough Python and SCons versions.  If your system's
72# default installation of Python is not recent enough, you can use a
73# non-default installation of the Python interpreter by either (1)
74# rearranging your PATH so that scons finds the non-default 'python'
75# first or (2) explicitly invoking an alternative interpreter on the
76# scons script, e.g., "/usr/local/bin/python2.4 `which scons` [args]".
77EnsurePythonVersion(2,4)
78
79# Import subprocess after we check the version since it doesn't exist in
80# Python < 2.4.
81import subprocess
82
83# Ironically, SCons 0.96 dies if you give EnsureSconsVersion a
84# 3-element version number.
85min_scons_version = (0,96,91)
86try:
87    EnsureSConsVersion(*min_scons_version)
88except:
89    print "Error checking current SCons version."
90    print "SCons", ".".join(map(str,min_scons_version)), "or greater required."
91    Exit(2)
92
93
94# The absolute path to the current directory (where this file lives).
95ROOT = Dir('.').abspath
96
97# Path to the M5 source tree.
98SRCDIR = joinpath(ROOT, 'src')
99
100# tell python where to find m5 python code
101sys.path.append(joinpath(ROOT, 'src/python'))
102
103def check_style_hook(ui):
104    ui.readconfig(joinpath(ROOT, '.hg', 'hgrc'))
105    style_hook = ui.config('hooks', 'pretxncommit.style', None)
106
107    if not style_hook:
108        print """\
109You're missing the M5 style hook.
110Please install the hook so we can ensure that all code fits a common style.
111
112All you'd need to do is add the following lines to your repository .hg/hgrc
113or your personal .hgrc
114----------------
115
116[extensions]
117style = %s/util/style.py
118
119[hooks]
120pretxncommit.style = python:style.check_whitespace
121""" % (ROOT)
122        sys.exit(1)
123
124if ARGUMENTS.get('IGNORE_STYLE') != 'True' and isdir(joinpath(ROOT, '.hg')):
125    try:
126        from mercurial import ui
127        check_style_hook(ui.ui())
128    except ImportError:
129        pass
130
131###################################################
132#
133# Figure out which configurations to set up based on the path(s) of
134# the target(s).
135#
136###################################################
137
138# Find default configuration & binary.
139Default(os.environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
140
141# helper function: find last occurrence of element in list
142def rfind(l, elt, offs = -1):
143    for i in range(len(l)+offs, 0, -1):
144        if l[i] == elt:
145            return i
146    raise ValueError, "element not found"
147
148# helper function: compare dotted version numbers.
149# E.g., compare_version('1.3.25', '1.4.1')
150# returns -1, 0, 1 if v1 is <, ==, > v2
151def compare_versions(v1, v2):
152    # Convert dotted strings to lists
153    v1 = map(int, v1.split('.'))
154    v2 = map(int, v2.split('.'))
155    # Compare corresponding elements of lists
156    for n1,n2 in zip(v1, v2):
157        if n1 < n2: return -1
158        if n1 > n2: return  1
159    # all corresponding values are equal... see if one has extra values
160    if len(v1) < len(v2): return -1
161    if len(v1) > len(v2): return  1
162    return 0
163
164# Each target must have 'build' in the interior of the path; the
165# directory below this will determine the build parameters.  For
166# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
167# recognize that ALPHA_SE specifies the configuration because it
168# follow 'build' in the bulid path.
169
170# Generate absolute paths to targets so we can see where the build dir is
171if COMMAND_LINE_TARGETS:
172    # Ask SCons which directory it was invoked from
173    launch_dir = GetLaunchDir()
174    # Make targets relative to invocation directory
175    abs_targets = map(lambda x: os.path.normpath(joinpath(launch_dir, str(x))),
176                      COMMAND_LINE_TARGETS)
177else:
178    # Default targets are relative to root of tree
179    abs_targets = map(lambda x: os.path.normpath(joinpath(ROOT, str(x))),
180                      DEFAULT_TARGETS)
181
182
183# Generate a list of the unique build roots and configs that the
184# collected targets reference.
185build_paths = []
186build_root = None
187for t in abs_targets:
188    path_dirs = t.split('/')
189    try:
190        build_top = rfind(path_dirs, 'build', -2)
191    except:
192        print "Error: no non-leaf 'build' dir found on target path", t
193        Exit(1)
194    this_build_root = joinpath('/',*path_dirs[:build_top+1])
195    if not build_root:
196        build_root = this_build_root
197    else:
198        if this_build_root != build_root:
199            print "Error: build targets not under same build root\n"\
200                  "  %s\n  %s" % (build_root, this_build_root)
201            Exit(1)
202    build_path = joinpath('/',*path_dirs[:build_top+2])
203    if build_path not in build_paths:
204        build_paths.append(build_path)
205
206###################################################
207#
208# Set up the default build environment.  This environment is copied
209# and modified according to each selected configuration.
210#
211###################################################
212
213env = Environment(ENV = os.environ,  # inherit user's environment vars
214                  ROOT = ROOT,
215                  SRCDIR = SRCDIR)
216
217#Parse CC/CXX early so that we use the correct compiler for
218# to test for dependencies/versions/libraries/includes
219if ARGUMENTS.get('CC', None):
220    env['CC'] = ARGUMENTS.get('CC')
221
222if ARGUMENTS.get('CXX', None):
223    env['CXX'] = ARGUMENTS.get('CXX')
224
225Export('env')
226
227env.SConsignFile(joinpath(build_root,"sconsign"))
228
229# Default duplicate option is to use hard links, but this messes up
230# when you use emacs to edit a file in the target dir, as emacs moves
231# file to file~ then copies to file, breaking the link.  Symbolic
232# (soft) links work better.
233env.SetOption('duplicate', 'soft-copy')
234
235# I waffle on this setting... it does avoid a few painful but
236# unnecessary builds, but it also seems to make trivial builds take
237# noticeably longer.
238if False:
239    env.TargetSignatures('content')
240
241# M5_PLY is used by isa_parser.py to find the PLY package.
242env.Append(ENV = { 'M5_PLY' : str(Dir('ext/ply')) })
243env['GCC'] = False
244env['SUNCC'] = False
245env['ICC'] = False
246env['GCC'] = subprocess.Popen(env['CXX'] + ' --version', shell=True,
247        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
248        close_fds=True).communicate()[0].find('GCC') >= 0
249env['SUNCC'] = subprocess.Popen(env['CXX'] + ' -V', shell=True,
250        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
251        close_fds=True).communicate()[0].find('Sun C++') >= 0
252env['ICC'] = subprocess.Popen(env['CXX'] + ' -V', shell=True,
253        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
254        close_fds=True).communicate()[0].find('Intel') >= 0
255if env['GCC'] + env['SUNCC'] + env['ICC'] > 1:
256    print 'Error: How can we have two at the same time?'
257    Exit(1)
258
259
260# Set up default C++ compiler flags
261if env['GCC']:
262    env.Append(CCFLAGS='-pipe')
263    env.Append(CCFLAGS='-fno-strict-aliasing')
264    env.Append(CCFLAGS=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
265elif env['ICC']:
266    pass #Fix me... add warning flags once we clean up icc warnings
267elif env['SUNCC']:
268    env.Append(CCFLAGS='-Qoption ccfe')
269    env.Append(CCFLAGS='-features=gcc')
270    env.Append(CCFLAGS='-features=extensions')
271    env.Append(CCFLAGS='-library=stlport4')
272    env.Append(CCFLAGS='-xar')
273#    env.Append(CCFLAGS='-instances=semiexplicit')
274else:
275    print 'Error: Don\'t know what compiler options to use for your compiler.'
276    print '       Please fix SConstruct and src/SConscript and try again.'
277    Exit(1)
278
279if sys.platform == 'cygwin':
280    # cygwin has some header file issues...
281    env.Append(CCFLAGS=Split("-Wno-uninitialized"))
282env.Append(CPPPATH=[Dir('ext/dnet')])
283
284# Check for SWIG
285if not env.has_key('SWIG'):
286    print 'Error: SWIG utility not found.'
287    print '       Please install (see http://www.swig.org) and retry.'
288    Exit(1)
289
290# Check for appropriate SWIG version
291swig_version = os.popen('swig -version').read().split()
292# First 3 words should be "SWIG Version x.y.z"
293if len(swig_version) < 3 or \
294        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
295    print 'Error determining SWIG version.'
296    Exit(1)
297
298min_swig_version = '1.3.28'
299if compare_versions(swig_version[2], min_swig_version) < 0:
300    print 'Error: SWIG version', min_swig_version, 'or newer required.'
301    print '       Installed version:', swig_version[2]
302    Exit(1)
303
304# Set up SWIG flags & scanner
305swig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
306env.Append(SWIGFLAGS=swig_flags)
307
308# filter out all existing swig scanners, they mess up the dependency
309# stuff for some reason
310scanners = []
311for scanner in env['SCANNERS']:
312    skeys = scanner.skeys
313    if skeys == '.i':
314        continue
315
316    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
317        continue
318
319    scanners.append(scanner)
320
321# add the new swig scanner that we like better
322from SCons.Scanner import ClassicCPP as CPPScanner
323swig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
324scanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
325
326# replace the scanners list that has what we want
327env['SCANNERS'] = scanners
328
329# Platform-specific configuration.  Note again that we assume that all
330# builds under a given build root run on the same host platform.
331conf = Configure(env,
332                 conf_dir = joinpath(build_root, '.scons_config'),
333                 log_file = joinpath(build_root, 'scons_config.log'))
334
335# Check if we should compile a 64 bit binary on Mac OS X/Darwin
336try:
337    import platform
338    uname = platform.uname()
339    if uname[0] == 'Darwin' and compare_versions(uname[2], '9.0.0') >= 0:
340        if int(subprocess.Popen('sysctl -n hw.cpu64bit_capable', shell=True,
341               stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
342               close_fds=True).communicate()[0][0]):
343            env.Append(CCFLAGS='-arch x86_64')
344            env.Append(CFLAGS='-arch x86_64')
345            env.Append(LINKFLAGS='-arch x86_64')
346            env.Append(ASFLAGS='-arch x86_64')
347except:
348    pass
349
350# Recent versions of scons substitute a "Null" object for Configure()
351# when configuration isn't necessary, e.g., if the "--help" option is
352# present.  Unfortuantely this Null object always returns false,
353# breaking all our configuration checks.  We replace it with our own
354# more optimistic null object that returns True instead.
355if not conf:
356    def NullCheck(*args, **kwargs):
357        return True
358
359    class NullConf:
360        def __init__(self, env):
361            self.env = env
362        def Finish(self):
363            return self.env
364        def __getattr__(self, mname):
365            return NullCheck
366
367    conf = NullConf(env)
368
369# Find Python include and library directories for embedding the
370# interpreter.  For consistency, we will use the same Python
371# installation used to run scons (and thus this script).  If you want
372# to link in an alternate version, see above for instructions on how
373# to invoke scons with a different copy of the Python interpreter.
374
375# Get brief Python version name (e.g., "python2.4") for locating
376# include & library files
377py_version_name = 'python' + sys.version[:3]
378
379# include path, e.g. /usr/local/include/python2.4
380py_header_path = joinpath(sys.exec_prefix, 'include', py_version_name)
381env.Append(CPPPATH = py_header_path)
382# verify that it works
383if not conf.CheckHeader('Python.h', '<>'):
384    print "Error: can't find Python.h header in", py_header_path
385    Exit(1)
386
387# add library path too if it's not in the default place
388py_lib_path = None
389if sys.exec_prefix != '/usr':
390    py_lib_path = joinpath(sys.exec_prefix, 'lib')
391elif sys.platform == 'cygwin':
392    # cygwin puts the .dll in /bin for some reason
393    py_lib_path = '/bin'
394if py_lib_path:
395    env.Append(LIBPATH = py_lib_path)
396    print 'Adding', py_lib_path, 'to LIBPATH for', py_version_name
397if not conf.CheckLib(py_version_name):
398    print "Error: can't find Python library", py_version_name
399    Exit(1)
400
401# On Solaris you need to use libsocket for socket ops
402if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
403   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
404       print "Can't find library with socket calls (e.g. accept())"
405       Exit(1)
406
407# Check for zlib.  If the check passes, libz will be automatically
408# added to the LIBS environment variable.
409if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
410    print 'Error: did not find needed zlib compression library '\
411          'and/or zlib.h header file.'
412    print '       Please install zlib and try again.'
413    Exit(1)
414
415# Check for <fenv.h> (C99 FP environment control)
416have_fenv = conf.CheckHeader('fenv.h', '<>')
417if not have_fenv:
418    print "Warning: Header file <fenv.h> not found."
419    print "         This host has no IEEE FP rounding mode control."
420
421# Check for mysql.
422mysql_config = WhereIs('mysql_config')
423have_mysql = mysql_config != None
424
425# Check MySQL version.
426if have_mysql:
427    mysql_version = os.popen(mysql_config + ' --version').read()
428    min_mysql_version = '4.1'
429    if compare_versions(mysql_version, min_mysql_version) < 0:
430        print 'Warning: MySQL', min_mysql_version, 'or newer required.'
431        print '         Version', mysql_version, 'detected.'
432        have_mysql = False
433
434# Set up mysql_config commands.
435if have_mysql:
436    mysql_config_include = mysql_config + ' --include'
437    if os.system(mysql_config_include + ' > /dev/null') != 0:
438        # older mysql_config versions don't support --include, use
439        # --cflags instead
440        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
441    # This seems to work in all versions
442    mysql_config_libs = mysql_config + ' --libs'
443
444env = conf.Finish()
445
446# Define the universe of supported ISAs
447all_isa_list = [ ]
448Export('all_isa_list')
449
450# Define the universe of supported CPU models
451all_cpu_list = [ ]
452default_cpus = [ ]
453Export('all_cpu_list', 'default_cpus')
454
455# Sticky options get saved in the options file so they persist from
456# one invocation to the next (unless overridden, in which case the new
457# value becomes sticky).
458sticky_opts = Options(args=ARGUMENTS)
459Export('sticky_opts')
460
461# Non-sticky options only apply to the current build.
462nonsticky_opts = Options(args=ARGUMENTS)
463Export('nonsticky_opts')
464
465# Walk the tree and execute all SConsopts scripts that wil add to the
466# above options
467for root, dirs, files in os.walk('.'):
468    if 'SConsopts' in files:
469        SConscript(os.path.join(root, 'SConsopts'))
470
471all_isa_list.sort()
472all_cpu_list.sort()
473default_cpus.sort()
474
475def ExtraPathValidator(key, val, env):
476    if not val:
477        return
478    paths = val.split(':')
479    for path in paths:
480        path = os.path.expanduser(path)
481        if not isdir(path):
482            raise AttributeError, "Invalid path: '%s'" % path
483
484sticky_opts.AddOptions(
485    EnumOption('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
486    BoolOption('FULL_SYSTEM', 'Full-system support', False),
487    # There's a bug in scons 0.96.1 that causes ListOptions with list
488    # values (more than one value) not to be able to be restored from
489    # a saved option file.  If this causes trouble then upgrade to
490    # scons 0.96.90 or later.
491    ListOption('CPU_MODELS', 'CPU models', default_cpus, all_cpu_list),
492    BoolOption('NO_FAST_ALLOC', 'Disable fast object allocator', False),
493    BoolOption('EFENCE', 'Link with Electric Fence malloc debugger',
494               False),
495    BoolOption('SS_COMPATIBLE_FP',
496               'Make floating-point results compatible with SimpleScalar',
497               False),
498    BoolOption('USE_SSE2',
499               'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
500               False),
501    BoolOption('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
502    BoolOption('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
503    BoolOption('USE_CHECKER', 'Use checker for detailed CPU models', False),
504    ('CC', 'C compiler', os.environ.get('CC', env['CC'])),
505    ('CXX', 'C++ compiler', os.environ.get('CXX', env['CXX'])),
506    BoolOption('BATCH', 'Use batch pool for build and tests', False),
507    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
508    ('PYTHONHOME',
509     'Override the default PYTHONHOME for this system (use with caution)',
510     '%s:%s' % (sys.prefix, sys.exec_prefix)),
511    ('EXTRAS', 'Add Extra directories to the compilation', '',
512     ExtraPathValidator)
513    )
514
515nonsticky_opts.AddOptions(
516    BoolOption('update_ref', 'Update test reference outputs', False)
517    )
518
519# These options get exported to #defines in config/*.hh (see src/SConscript).
520env.ExportOptions = ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
521                     'USE_MYSQL', 'NO_FAST_ALLOC', 'SS_COMPATIBLE_FP', \
522                     'USE_CHECKER', 'PYTHONHOME', 'TARGET_ISA']
523
524# Define a handy 'no-op' action
525def no_action(target, source, env):
526    return 0
527
528env.NoAction = Action(no_action, None)
529
530###################################################
531#
532# Define a SCons builder for configuration flag headers.
533#
534###################################################
535
536# This function generates a config header file that #defines the
537# option symbol to the current option setting (0 or 1).  The source
538# operands are the name of the option and a Value node containing the
539# value of the option.
540def build_config_file(target, source, env):
541    (option, value) = [s.get_contents() for s in source]
542    f = file(str(target[0]), 'w')
543    print >> f, '#define', option, value
544    f.close()
545    return None
546
547# Generate the message to be printed when building the config file.
548def build_config_file_string(target, source, env):
549    (option, value) = [s.get_contents() for s in source]
550    return "Defining %s as %s in %s." % (option, value, target[0])
551
552# Combine the two functions into a scons Action object.
553config_action = Action(build_config_file, build_config_file_string)
554
555# The emitter munges the source & target node lists to reflect what
556# we're really doing.
557def config_emitter(target, source, env):
558    # extract option name from Builder arg
559    option = str(target[0])
560    # True target is config header file
561    target = joinpath('config', option.lower() + '.hh')
562    val = env[option]
563    if isinstance(val, bool):
564        # Force value to 0/1
565        val = int(val)
566    elif isinstance(val, str):
567        val = '"' + val + '"'
568
569    # Sources are option name & value (packaged in SCons Value nodes)
570    return ([target], [Value(option), Value(val)])
571
572config_builder = Builder(emitter = config_emitter, action = config_action)
573
574env.Append(BUILDERS = { 'ConfigFile' : config_builder })
575
576###################################################
577#
578# Define a SCons builder for copying files.  This is used by the
579# Python zipfile code in src/python/SConscript, but is placed up here
580# since it's potentially more generally applicable.
581#
582###################################################
583
584copy_builder = Builder(action = Copy("$TARGET", "$SOURCE"))
585
586env.Append(BUILDERS = { 'CopyFile' : copy_builder })
587
588###################################################
589#
590# Define a simple SCons builder to concatenate files.
591#
592# Used to append the Python zip archive to the executable.
593#
594###################################################
595
596concat_builder = Builder(action = Action(['cat $SOURCES > $TARGET',
597                                          'chmod +x $TARGET']))
598
599env.Append(BUILDERS = { 'Concat' : concat_builder })
600
601
602# base help text
603help_text = '''
604Usage: scons [scons options] [build options] [target(s)]
605
606'''
607
608# libelf build is shared across all configs in the build root.
609env.SConscript('ext/libelf/SConscript',
610               build_dir = joinpath(build_root, 'libelf'),
611               exports = 'env')
612
613###################################################
614#
615# This function is used to set up a directory with switching headers
616#
617###################################################
618
619env['ALL_ISA_LIST'] = all_isa_list
620def make_switching_dir(dirname, switch_headers, env):
621    # Generate the header.  target[0] is the full path of the output
622    # header to generate.  'source' is a dummy variable, since we get the
623    # list of ISAs from env['ALL_ISA_LIST'].
624    def gen_switch_hdr(target, source, env):
625        fname = str(target[0])
626        basename = os.path.basename(fname)
627        f = open(fname, 'w')
628        f.write('#include "arch/isa_specific.hh"\n')
629        cond = '#if'
630        for isa in all_isa_list:
631            f.write('%s THE_ISA == %s_ISA\n#include "%s/%s/%s"\n'
632                    % (cond, isa.upper(), dirname, isa, basename))
633            cond = '#elif'
634        f.write('#else\n#error "THE_ISA not set"\n#endif\n')
635        f.close()
636        return 0
637
638    # String to print when generating header
639    def gen_switch_hdr_string(target, source, env):
640        return "Generating switch header " + str(target[0])
641
642    # Build SCons Action object. 'varlist' specifies env vars that this
643    # action depends on; when env['ALL_ISA_LIST'] changes these actions
644    # should get re-executed.
645    switch_hdr_action = Action(gen_switch_hdr, gen_switch_hdr_string,
646                               varlist=['ALL_ISA_LIST'])
647
648    # Instantiate actions for each header
649    for hdr in switch_headers:
650        env.Command(hdr, [], switch_hdr_action)
651Export('make_switching_dir')
652
653###################################################
654#
655# Define build environments for selected configurations.
656#
657###################################################
658
659# rename base env
660base_env = env
661
662for build_path in build_paths:
663    print "Building in", build_path
664    env['BUILDDIR'] = build_path
665
666    # build_dir is the tail component of build path, and is used to
667    # determine the build parameters (e.g., 'ALPHA_SE')
668    (build_root, build_dir) = os.path.split(build_path)
669    # Make a copy of the build-root environment to use for this config.
670    env = base_env.Copy()
671
672    # Set env options according to the build directory config.
673    sticky_opts.files = []
674    # Options for $BUILD_ROOT/$BUILD_DIR are stored in
675    # $BUILD_ROOT/options/$BUILD_DIR so you can nuke
676    # $BUILD_ROOT/$BUILD_DIR without losing your options settings.
677    current_opts_file = joinpath(build_root, 'options', build_dir)
678    if os.path.isfile(current_opts_file):
679        sticky_opts.files.append(current_opts_file)
680        print "Using saved options file %s" % current_opts_file
681    else:
682        # Build dir-specific options file doesn't exist.
683
684        # Make sure the directory is there so we can create it later
685        opt_dir = os.path.dirname(current_opts_file)
686        if not os.path.isdir(opt_dir):
687            os.mkdir(opt_dir)
688
689        # Get default build options from source tree.  Options are
690        # normally determined by name of $BUILD_DIR, but can be
691        # overriden by 'default=' arg on command line.
692        default_opts_file = joinpath('build_opts',
693                                     ARGUMENTS.get('default', build_dir))
694        if os.path.isfile(default_opts_file):
695            sticky_opts.files.append(default_opts_file)
696            print "Options file %s not found,\n  using defaults in %s" \
697                  % (current_opts_file, default_opts_file)
698        else:
699            print "Error: cannot find options file %s or %s" \
700                  % (current_opts_file, default_opts_file)
701            Exit(1)
702
703    # Apply current option settings to env
704    sticky_opts.Update(env)
705    nonsticky_opts.Update(env)
706
707    help_text += "Sticky options for %s:\n" % build_dir \
708                 + sticky_opts.GenerateHelpText(env) \
709                 + "\nNon-sticky options for %s:\n" % build_dir \
710                 + nonsticky_opts.GenerateHelpText(env)
711
712    # Process option settings.
713
714    if not have_fenv and env['USE_FENV']:
715        print "Warning: <fenv.h> not available; " \
716              "forcing USE_FENV to False in", build_dir + "."
717        env['USE_FENV'] = False
718
719    if not env['USE_FENV']:
720        print "Warning: No IEEE FP rounding mode control in", build_dir + "."
721        print "         FP results may deviate slightly from other platforms."
722
723    if env['EFENCE']:
724        env.Append(LIBS=['efence'])
725
726    if env['USE_MYSQL']:
727        if not have_mysql:
728            print "Warning: MySQL not available; " \
729                  "forcing USE_MYSQL to False in", build_dir + "."
730            env['USE_MYSQL'] = False
731        else:
732            print "Compiling in", build_dir, "with MySQL support."
733            env.ParseConfig(mysql_config_libs)
734            env.ParseConfig(mysql_config_include)
735
736    # Save sticky option settings back to current options file
737    sticky_opts.Save(current_opts_file, env)
738
739    # Do this after we save setting back, or else we'll tack on an
740    # extra 'qdo' every time we run scons.
741    if env['BATCH']:
742        env['CC']  = env['BATCH_CMD'] + ' ' + env['CC']
743        env['CXX'] = env['BATCH_CMD'] + ' ' + env['CXX']
744
745    if env['USE_SSE2']:
746        env.Append(CCFLAGS='-msse2')
747
748    # The src/SConscript file sets up the build rules in 'env' according
749    # to the configured options.  It returns a list of environments,
750    # one for each variant build (debug, opt, etc.)
751    envList = SConscript('src/SConscript', build_dir = build_path,
752                         exports = 'env')
753
754    # Set up the regression tests for each build.
755    for e in envList:
756        SConscript('tests/SConscript',
757                   build_dir = joinpath(build_path, 'tests', e.Label),
758                   exports = { 'env' : e }, duplicate = False)
759
760Help(help_text)
761
762
763###################################################
764#
765# Let SCons do its thing.  At this point SCons will use the defined
766# build environments to build the requested targets.
767#
768###################################################
769
770