SConstruct revision 5342
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
4955SN/A# All rights reserved.
5955SN/A#
6955SN/A# Redistribution and use in source and binary forms, with or without
7955SN/A# modification, are permitted provided that the following conditions are
8955SN/A# met: redistributions of source code must retain the above copyright
9955SN/A# notice, this list of conditions and the following disclaimer;
10955SN/A# redistributions in binary form must reproduce the above copyright
11955SN/A# notice, this list of conditions and the following disclaimer in the
12955SN/A# documentation and/or other materials provided with the distribution;
13955SN/A# neither the name of the copyright holders nor the names of its
14955SN/A# contributors may be used to endorse or promote products derived from
15955SN/A# this software without specific prior written permission.
16955SN/A#
17955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28955SN/A#
29955SN/A# Authors: Steve Reinhardt
30955SN/A
31955SN/A###################################################
32955SN/A#
332632Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
342632Sstever@eecs.umich.edu#
352632Sstever@eecs.umich.edu# While in this directory ('m5'), just type 'scons' to build the default
362632Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
37955SN/A# to build some other configuration (e.g., 'build/ALPHA_FS/m5.opt' for
382632Sstever@eecs.umich.edu# the optimized full-system version).
392632Sstever@eecs.umich.edu#
402632Sstever@eecs.umich.edu# You can build M5 in a different directory as long as there is a
412632Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
422632Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
432632Sstever@eecs.umich.edu# built for the same host system.
442632Sstever@eecs.umich.edu#
452632Sstever@eecs.umich.edu# Examples:
462632Sstever@eecs.umich.edu#
472632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
482632Sstever@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
492632Sstever@eecs.umich.edu#   % cd <path-to-src>/m5 ; scons build/ALPHA_FS/m5.debug
502632Sstever@eecs.umich.edu#   % cd <path-to-src>/m5/build/ALPHA_FS; scons -u m5.debug
512632Sstever@eecs.umich.edu#
522632Sstever@eecs.umich.edu#   The following two commands are equivalent and demonstrate building
532632Sstever@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
542632Sstever@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
552632Sstever@eecs.umich.edu#   file.
562632Sstever@eecs.umich.edu#   % cd <path-to-src>/m5 ; scons /local/foo/build/ALPHA_FS/m5.debug
572632Sstever@eecs.umich.edu#   % cd /local/foo/build/ALPHA_FS; scons -C <path-to-src>/m5 m5.debug
58955SN/A#
59955SN/A# You can use 'scons -H' to print scons options.  If you're in this
60955SN/A# 'm5' directory (or use -u or -C to tell scons where to find this
61955SN/A# file), you can use 'scons -h' to print all the M5-specific build
62955SN/A# options as well.
63955SN/A#
64955SN/A###################################################
651858SN/A
661858SN/Aimport sys
672632Sstever@eecs.umich.eduimport os
681852SN/A
69955SN/Afrom os.path import isdir, isfile, join as joinpath
70955SN/A
71955SN/Aimport SCons
722632Sstever@eecs.umich.edu
732632Sstever@eecs.umich.edu# Check for recent-enough Python and SCons versions.  If your system's
74955SN/A# default installation of Python is not recent enough, you can use a
751533SN/A# non-default installation of the Python interpreter by either (1)
762632Sstever@eecs.umich.edu# rearranging your PATH so that scons finds the non-default 'python'
771533SN/A# first or (2) explicitly invoking an alternative interpreter on the
78955SN/A# scons script, e.g., "/usr/local/bin/python2.4 `which scons` [args]".
79955SN/AEnsurePythonVersion(2,4)
802632Sstever@eecs.umich.edu
812632Sstever@eecs.umich.edu# Import subprocess after we check the version since it doesn't exist in
82955SN/A# Python < 2.4.
83955SN/Aimport subprocess
84955SN/A
85955SN/A# Ironically, SCons 0.96 dies if you give EnsureSconsVersion a
862632Sstever@eecs.umich.edu# 3-element version number.
87955SN/Amin_scons_version = (0,96,91)
882632Sstever@eecs.umich.edutry:
89955SN/A    EnsureSConsVersion(*min_scons_version)
90955SN/Aexcept:
912632Sstever@eecs.umich.edu    print "Error checking current SCons version."
922632Sstever@eecs.umich.edu    print "SCons", ".".join(map(str,min_scons_version)), "or greater required."
932632Sstever@eecs.umich.edu    Exit(2)
942632Sstever@eecs.umich.edu
952632Sstever@eecs.umich.edu
962632Sstever@eecs.umich.edu# The absolute path to the current directory (where this file lives).
972632Sstever@eecs.umich.eduROOT = Dir('.').abspath
982632Sstever@eecs.umich.edu
992632Sstever@eecs.umich.edu# Path to the M5 source tree.
1002632Sstever@eecs.umich.eduSRCDIR = joinpath(ROOT, 'src')
1012632Sstever@eecs.umich.edu
1022632Sstever@eecs.umich.edu# tell python where to find m5 python code
1032632Sstever@eecs.umich.edusys.path.append(joinpath(ROOT, 'src/python'))
1042632Sstever@eecs.umich.edu
1052632Sstever@eecs.umich.edudef check_style_hook(ui):
1062632Sstever@eecs.umich.edu    ui.readconfig(joinpath(ROOT, '.hg', 'hgrc'))
1072632Sstever@eecs.umich.edu    style_hook = ui.config('hooks', 'pretxncommit.style', None)
1082634Sstever@eecs.umich.edu
1092634Sstever@eecs.umich.edu    if not style_hook:
1102632Sstever@eecs.umich.edu        print """\
1112634Sstever@eecs.umich.eduYou're missing the M5 style hook.
1122632Sstever@eecs.umich.eduPlease install the hook so we can ensure that all code fits a common style.
1132632Sstever@eecs.umich.edu
1142632Sstever@eecs.umich.eduAll you'd need to do is add the following lines to your repository .hg/hgrc
1152632Sstever@eecs.umich.eduor your personal .hgrc
1162632Sstever@eecs.umich.edu----------------
1172632Sstever@eecs.umich.edu
1181858SN/A[extensions]
1192634Sstever@eecs.umich.edustyle = %s/util/style.py
1202634Sstever@eecs.umich.edu
1212634Sstever@eecs.umich.edu[hooks]
1222634Sstever@eecs.umich.edupretxncommit.style = python:style.check_whitespace
1232634Sstever@eecs.umich.edu""" % (ROOT)
1242634Sstever@eecs.umich.edu        sys.exit(1)
125955SN/A
126955SN/Aif ARGUMENTS.get('IGNORE_STYLE') != 'True' and isdir(joinpath(ROOT, '.hg')):
127955SN/A    try:
128955SN/A        from mercurial import ui
129955SN/A        check_style_hook(ui.ui())
130955SN/A    except ImportError:
131955SN/A        pass
132955SN/A
1331858SN/A###################################################
1341858SN/A#
1352632Sstever@eecs.umich.edu# Figure out which configurations to set up based on the path(s) of
136955SN/A# the target(s).
1371858SN/A#
1381105SN/A###################################################
1391869SN/A
1401869SN/A# Find default configuration & binary.
1411869SN/ADefault(os.environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
1421869SN/A
1431869SN/A# helper function: find last occurrence of element in list
1441065SN/Adef rfind(l, elt, offs = -1):
1452632Sstever@eecs.umich.edu    for i in range(len(l)+offs, 0, -1):
1462632Sstever@eecs.umich.edu        if l[i] == elt:
147955SN/A            return i
1481858SN/A    raise ValueError, "element not found"
1491858SN/A
1501858SN/A# helper function: compare dotted version numbers.
1511858SN/A# E.g., compare_version('1.3.25', '1.4.1')
1521851SN/A# returns -1, 0, 1 if v1 is <, ==, > v2
1531851SN/Adef compare_versions(v1, v2):
1541858SN/A    # Convert dotted strings to lists
1552632Sstever@eecs.umich.edu    v1 = map(int, v1.split('.'))
156955SN/A    v2 = map(int, v2.split('.'))
1571858SN/A    # Compare corresponding elements of lists
1581858SN/A    for n1,n2 in zip(v1, v2):
1591858SN/A        if n1 < n2: return -1
1601858SN/A        if n1 > n2: return  1
1611858SN/A    # all corresponding values are equal... see if one has extra values
1621858SN/A    if len(v1) < len(v2): return -1
1631858SN/A    if len(v1) > len(v2): return  1
1641858SN/A    return 0
1651858SN/A
1661858SN/A# Each target must have 'build' in the interior of the path; the
1671858SN/A# directory below this will determine the build parameters.  For
1681858SN/A# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
1691859SN/A# recognize that ALPHA_SE specifies the configuration because it
1701858SN/A# follow 'build' in the bulid path.
1711858SN/A
1721858SN/A# Generate absolute paths to targets so we can see where the build dir is
1731859SN/Aif COMMAND_LINE_TARGETS:
1741859SN/A    # Ask SCons which directory it was invoked from
1751862SN/A    launch_dir = GetLaunchDir()
1761862SN/A    # Make targets relative to invocation directory
1771862SN/A    abs_targets = map(lambda x: os.path.normpath(joinpath(launch_dir, str(x))),
1781862SN/A                      COMMAND_LINE_TARGETS)
1791859SN/Aelse:
1801859SN/A    # Default targets are relative to root of tree
1811963SN/A    abs_targets = map(lambda x: os.path.normpath(joinpath(ROOT, str(x))),
1821963SN/A                      DEFAULT_TARGETS)
1831859SN/A
1841859SN/A
1851859SN/A# Generate a list of the unique build roots and configs that the
1861859SN/A# collected targets reference.
1871859SN/Abuild_paths = []
1881859SN/Abuild_root = None
1891859SN/Afor t in abs_targets:
1901859SN/A    path_dirs = t.split('/')
1911862SN/A    try:
1921859SN/A        build_top = rfind(path_dirs, 'build', -2)
1931859SN/A    except:
1941859SN/A        print "Error: no non-leaf 'build' dir found on target path", t
1951858SN/A        Exit(1)
1961858SN/A    this_build_root = joinpath('/',*path_dirs[:build_top+1])
1972139SN/A    if not build_root:
1982139SN/A        build_root = this_build_root
1992139SN/A    else:
2002155SN/A        if this_build_root != build_root:
2012623SN/A            print "Error: build targets not under same build root\n"\
2022623SN/A                  "  %s\n  %s" % (build_root, this_build_root)
2032155SN/A            Exit(1)
2041869SN/A    build_path = joinpath('/',*path_dirs[:build_top+2])
2051869SN/A    if build_path not in build_paths:
2061869SN/A        build_paths.append(build_path)
2071869SN/A
2081869SN/A# Make sure build_root exists (might not if this is the first build there)
2092139SN/Aif not isdir(build_root):
2101869SN/A    os.mkdir(build_root)
2112508SN/A
2122508SN/A###################################################
2132508SN/A#
2142508SN/A# Set up the default build environment.  This environment is copied
2152508SN/A# and modified according to each selected configuration.
2161869SN/A#
2171869SN/A###################################################
2181869SN/A
2191869SN/Aenv = Environment(ENV = os.environ,  # inherit user's environment vars
2201869SN/A                  ROOT = ROOT,
2211869SN/A                  SRCDIR = SRCDIR)
2221869SN/A
2231869SN/AExport('env')
2241965SN/A
2251965SN/Aenv.SConsignFile(joinpath(build_root,"sconsign"))
2261965SN/A
2271869SN/A# Default duplicate option is to use hard links, but this messes up
2281869SN/A# when you use emacs to edit a file in the target dir, as emacs moves
2291869SN/A# file to file~ then copies to file, breaking the link.  Symbolic
2301869SN/A# (soft) links work better.
2311884SN/Aenv.SetOption('duplicate', 'soft-copy')
2321884SN/A
2331884SN/A# I waffle on this setting... it does avoid a few painful but
2341869SN/A# unnecessary builds, but it also seems to make trivial builds take
2351858SN/A# noticeably longer.
2361869SN/Aif False:
2371869SN/A    env.TargetSignatures('content')
2381869SN/A
2391869SN/A#
2401869SN/A# Set up global sticky options... these are common to an entire build
2411858SN/A# tree (not specific to a particular build like ALPHA_SE)
2421869SN/A#
2431869SN/A
2441869SN/A# Option validators & converters for global sticky options
2451869SN/Adef PathListMakeAbsolute(val):
2461869SN/A    if not val:
2471869SN/A        return val
2481869SN/A    f = lambda p: os.path.abspath(os.path.expanduser(p))
2491869SN/A    return ':'.join(map(f, val.split(':')))
2501869SN/A
2511869SN/Adef PathListAllExist(key, val, env):
2521858SN/A    if not val:
253955SN/A        return
254955SN/A    paths = val.split(':')
2551869SN/A    for path in paths:
2561869SN/A        if not isdir(path):
2571869SN/A            raise SCons.Errors.UserError("Path does not exist: '%s'" % path)
2581869SN/A
2591869SN/Aglobal_sticky_opts_file = joinpath(build_root, 'options.global')
2601869SN/A
2611869SN/Aglobal_sticky_opts = Options(global_sticky_opts_file, args=ARGUMENTS)
2621869SN/A
2631869SN/Aglobal_sticky_opts.AddOptions(
2641869SN/A    ('CC', 'C compiler', os.environ.get('CC', env['CC'])),
2651869SN/A    ('CXX', 'C++ compiler', os.environ.get('CXX', env['CXX'])),
2661869SN/A    ('EXTRAS', 'Add Extra directories to the compilation', '',
2671869SN/A     PathListAllExist, PathListMakeAbsolute)
2681869SN/A    )    
2691869SN/A
2701869SN/A
2711869SN/A# base help text
2721869SN/Ahelp_text = '''
2731869SN/AUsage: scons [scons options] [build options] [target(s)]
2741869SN/A
2751869SN/A'''
2761869SN/A
2771869SN/Ahelp_text += "Global sticky options:\n" \
2781869SN/A             + global_sticky_opts.GenerateHelpText(env)
2791869SN/A
2801869SN/A# Update env with values from ARGUMENTS & file global_sticky_opts_file
2811869SN/Aglobal_sticky_opts.Update(env)
2821869SN/A
2831869SN/A# Save sticky option settings back to current options file
2841869SN/Aglobal_sticky_opts.Save(global_sticky_opts_file, env)
2851869SN/A
2861869SN/A# Parse EXTRAS option to build list of all directories where we're
2871869SN/A# look for sources etc.  This list is exported as base_dir_list.
2881869SN/Abase_dir_list = [ROOT]
2891869SN/Aif env['EXTRAS']:
2901869SN/A    base_dir_list += env['EXTRAS'].split(':')
2911869SN/A
2921869SN/AExport('base_dir_list')
2931869SN/A
2942634Sstever@eecs.umich.edu# M5_PLY is used by isa_parser.py to find the PLY package.
2952634Sstever@eecs.umich.eduenv.Append(ENV = { 'M5_PLY' : str(Dir('ext/ply')) })
2962634Sstever@eecs.umich.eduenv['GCC'] = False
2972634Sstever@eecs.umich.eduenv['SUNCC'] = False
2982634Sstever@eecs.umich.eduenv['ICC'] = False
2992634Sstever@eecs.umich.eduenv['GCC'] = subprocess.Popen(env['CXX'] + ' --version', shell=True,
3001869SN/A        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
3011869SN/A        close_fds=True).communicate()[0].find('GCC') >= 0
302955SN/Aenv['SUNCC'] = subprocess.Popen(env['CXX'] + ' -V', shell=True,
303955SN/A        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
304955SN/A        close_fds=True).communicate()[0].find('Sun C++') >= 0
305955SN/Aenv['ICC'] = subprocess.Popen(env['CXX'] + ' -V', shell=True,
3061858SN/A        stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
3071858SN/A        close_fds=True).communicate()[0].find('Intel') >= 0
3081858SN/Aif env['GCC'] + env['SUNCC'] + env['ICC'] > 1:
3092634Sstever@eecs.umich.edu    print 'Error: How can we have two at the same time?'
3102634Sstever@eecs.umich.edu    Exit(1)
3112634Sstever@eecs.umich.edu
3122634Sstever@eecs.umich.edu
3132634Sstever@eecs.umich.edu# Set up default C++ compiler flags
3142634Sstever@eecs.umich.eduif env['GCC']:
3152634Sstever@eecs.umich.edu    env.Append(CCFLAGS='-pipe')
3162634Sstever@eecs.umich.edu    env.Append(CCFLAGS='-fno-strict-aliasing')
3172634Sstever@eecs.umich.edu    env.Append(CCFLAGS=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
3182634Sstever@eecs.umich.eduelif env['ICC']:
3192598SN/A    pass #Fix me... add warning flags once we clean up icc warnings
3202632Sstever@eecs.umich.eduelif env['SUNCC']:
3212632Sstever@eecs.umich.edu    env.Append(CCFLAGS='-Qoption ccfe')
3222632Sstever@eecs.umich.edu    env.Append(CCFLAGS='-features=gcc')
3232632Sstever@eecs.umich.edu    env.Append(CCFLAGS='-features=extensions')
3242632Sstever@eecs.umich.edu    env.Append(CCFLAGS='-library=stlport4')
3252634Sstever@eecs.umich.edu    env.Append(CCFLAGS='-xar')
3262634Sstever@eecs.umich.edu#    env.Append(CCFLAGS='-instances=semiexplicit')
3272023SN/Aelse:
3282632Sstever@eecs.umich.edu    print 'Error: Don\'t know what compiler options to use for your compiler.'
3292632Sstever@eecs.umich.edu    print '       Please fix SConstruct and src/SConscript and try again.'
3302632Sstever@eecs.umich.edu    Exit(1)
3312632Sstever@eecs.umich.edu
3322632Sstever@eecs.umich.eduif sys.platform == 'cygwin':
3332632Sstever@eecs.umich.edu    # cygwin has some header file issues...
3342632Sstever@eecs.umich.edu    env.Append(CCFLAGS=Split("-Wno-uninitialized"))
3352632Sstever@eecs.umich.eduenv.Append(CPPPATH=[Dir('ext/dnet')])
3362632Sstever@eecs.umich.edu
3372632Sstever@eecs.umich.edu# Check for SWIG
3382632Sstever@eecs.umich.eduif not env.has_key('SWIG'):
3392023SN/A    print 'Error: SWIG utility not found.'
3402632Sstever@eecs.umich.edu    print '       Please install (see http://www.swig.org) and retry.'
3412632Sstever@eecs.umich.edu    Exit(1)
3421889SN/A
3431889SN/A# Check for appropriate SWIG version
3442632Sstever@eecs.umich.eduswig_version = os.popen('swig -version').read().split()
3452632Sstever@eecs.umich.edu# First 3 words should be "SWIG Version x.y.z"
3462632Sstever@eecs.umich.eduif len(swig_version) < 3 or \
3472632Sstever@eecs.umich.edu        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
3482632Sstever@eecs.umich.edu    print 'Error determining SWIG version.'
3492632Sstever@eecs.umich.edu    Exit(1)
3502632Sstever@eecs.umich.edu
3512632Sstever@eecs.umich.edumin_swig_version = '1.3.28'
3522632Sstever@eecs.umich.eduif compare_versions(swig_version[2], min_swig_version) < 0:
3532632Sstever@eecs.umich.edu    print 'Error: SWIG version', min_swig_version, 'or newer required.'
3542632Sstever@eecs.umich.edu    print '       Installed version:', swig_version[2]
3552632Sstever@eecs.umich.edu    Exit(1)
3562632Sstever@eecs.umich.edu
3572632Sstever@eecs.umich.edu# Set up SWIG flags & scanner
3581888SN/Aswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
3591888SN/Aenv.Append(SWIGFLAGS=swig_flags)
3601869SN/A
3611869SN/A# filter out all existing swig scanners, they mess up the dependency
3621858SN/A# stuff for some reason
3632598SN/Ascanners = []
3642598SN/Afor scanner in env['SCANNERS']:
3652598SN/A    skeys = scanner.skeys
3662598SN/A    if skeys == '.i':
3672598SN/A        continue
3681858SN/A
3691858SN/A    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
3701858SN/A        continue
3711858SN/A
3721858SN/A    scanners.append(scanner)
3731858SN/A
3741858SN/A# add the new swig scanner that we like better
3751858SN/Afrom SCons.Scanner import ClassicCPP as CPPScanner
3761858SN/Aswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
3771871SN/Ascanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
3781858SN/A
3791858SN/A# replace the scanners list that has what we want
3801858SN/Aenv['SCANNERS'] = scanners
3811858SN/A
3821858SN/A# Platform-specific configuration.  Note again that we assume that all
3831858SN/A# builds under a given build root run on the same host platform.
3841858SN/Aconf = Configure(env,
3851858SN/A                 conf_dir = joinpath(build_root, '.scons_config'),
3861858SN/A                 log_file = joinpath(build_root, 'scons_config.log'))
3871858SN/A
3881858SN/A# Check if we should compile a 64 bit binary on Mac OS X/Darwin
3891859SN/Atry:
3901859SN/A    import platform
3911869SN/A    uname = platform.uname()
3921888SN/A    if uname[0] == 'Darwin' and compare_versions(uname[2], '9.0.0') >= 0:
3932632Sstever@eecs.umich.edu        if int(subprocess.Popen('sysctl -n hw.cpu64bit_capable', shell=True,
3941869SN/A               stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
3951884SN/A               close_fds=True).communicate()[0][0]):
3961884SN/A            env.Append(CCFLAGS='-arch x86_64')
3971884SN/A            env.Append(CFLAGS='-arch x86_64')
3981884SN/A            env.Append(LINKFLAGS='-arch x86_64')
3991884SN/A            env.Append(ASFLAGS='-arch x86_64')
4001884SN/A            env['OSX64bit'] = True
4011965SN/Aexcept:
4021965SN/A    pass
4031965SN/A
404955SN/A# Recent versions of scons substitute a "Null" object for Configure()
4051869SN/A# when configuration isn't necessary, e.g., if the "--help" option is
4061869SN/A# present.  Unfortuantely this Null object always returns false,
4072632Sstever@eecs.umich.edu# breaking all our configuration checks.  We replace it with our own
4081869SN/A# more optimistic null object that returns True instead.
4091869SN/Aif not conf:
4101869SN/A    def NullCheck(*args, **kwargs):
4112632Sstever@eecs.umich.edu        return True
4122632Sstever@eecs.umich.edu
4132632Sstever@eecs.umich.edu    class NullConf:
4142632Sstever@eecs.umich.edu        def __init__(self, env):
415955SN/A            self.env = env
4162598SN/A        def Finish(self):
4172598SN/A            return self.env
418955SN/A        def __getattr__(self, mname):
419955SN/A            return NullCheck
420955SN/A
4211530SN/A    conf = NullConf(env)
422955SN/A
423955SN/A# Find Python include and library directories for embedding the
424955SN/A# interpreter.  For consistency, we will use the same Python
425# installation used to run scons (and thus this script).  If you want
426# to link in an alternate version, see above for instructions on how
427# to invoke scons with a different copy of the Python interpreter.
428
429# Get brief Python version name (e.g., "python2.4") for locating
430# include & library files
431py_version_name = 'python' + sys.version[:3]
432
433# include path, e.g. /usr/local/include/python2.4
434py_header_path = joinpath(sys.exec_prefix, 'include', py_version_name)
435env.Append(CPPPATH = py_header_path)
436# verify that it works
437if not conf.CheckHeader('Python.h', '<>'):
438    print "Error: can't find Python.h header in", py_header_path
439    Exit(1)
440
441# add library path too if it's not in the default place
442py_lib_path = None
443if sys.exec_prefix != '/usr':
444    py_lib_path = joinpath(sys.exec_prefix, 'lib')
445elif sys.platform == 'cygwin':
446    # cygwin puts the .dll in /bin for some reason
447    py_lib_path = '/bin'
448if py_lib_path:
449    env.Append(LIBPATH = py_lib_path)
450    print 'Adding', py_lib_path, 'to LIBPATH for', py_version_name
451if not conf.CheckLib(py_version_name):
452    print "Error: can't find Python library", py_version_name
453    Exit(1)
454
455# On Solaris you need to use libsocket for socket ops
456if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
457   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
458       print "Can't find library with socket calls (e.g. accept())"
459       Exit(1)
460
461# Check for zlib.  If the check passes, libz will be automatically
462# added to the LIBS environment variable.
463if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
464    print 'Error: did not find needed zlib compression library '\
465          'and/or zlib.h header file.'
466    print '       Please install zlib and try again.'
467    Exit(1)
468
469# Check for <fenv.h> (C99 FP environment control)
470have_fenv = conf.CheckHeader('fenv.h', '<>')
471if not have_fenv:
472    print "Warning: Header file <fenv.h> not found."
473    print "         This host has no IEEE FP rounding mode control."
474
475# Check for mysql.
476mysql_config = WhereIs('mysql_config')
477have_mysql = mysql_config != None
478
479# Check MySQL version.
480if have_mysql:
481    mysql_version = os.popen(mysql_config + ' --version').read()
482    min_mysql_version = '4.1'
483    if compare_versions(mysql_version, min_mysql_version) < 0:
484        print 'Warning: MySQL', min_mysql_version, 'or newer required.'
485        print '         Version', mysql_version, 'detected.'
486        have_mysql = False
487
488# Set up mysql_config commands.
489if have_mysql:
490    mysql_config_include = mysql_config + ' --include'
491    if os.system(mysql_config_include + ' > /dev/null') != 0:
492        # older mysql_config versions don't support --include, use
493        # --cflags instead
494        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
495    # This seems to work in all versions
496    mysql_config_libs = mysql_config + ' --libs'
497
498env = conf.Finish()
499
500# Define the universe of supported ISAs
501all_isa_list = [ ]
502Export('all_isa_list')
503
504# Define the universe of supported CPU models
505all_cpu_list = [ ]
506default_cpus = [ ]
507Export('all_cpu_list', 'default_cpus')
508
509# Sticky options get saved in the options file so they persist from
510# one invocation to the next (unless overridden, in which case the new
511# value becomes sticky).
512sticky_opts = Options(args=ARGUMENTS)
513Export('sticky_opts')
514
515# Non-sticky options only apply to the current build.
516nonsticky_opts = Options(args=ARGUMENTS)
517Export('nonsticky_opts')
518
519# Walk the tree and execute all SConsopts scripts that wil add to the
520# above options
521for base_dir in base_dir_list:
522    for root, dirs, files in os.walk(base_dir):
523        if 'SConsopts' in files:
524            print "Reading", joinpath(root, 'SConsopts')
525            SConscript(joinpath(root, 'SConsopts'))
526
527all_isa_list.sort()
528all_cpu_list.sort()
529default_cpus.sort()
530
531sticky_opts.AddOptions(
532    EnumOption('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
533    BoolOption('FULL_SYSTEM', 'Full-system support', False),
534    # There's a bug in scons 0.96.1 that causes ListOptions with list
535    # values (more than one value) not to be able to be restored from
536    # a saved option file.  If this causes trouble then upgrade to
537    # scons 0.96.90 or later.
538    ListOption('CPU_MODELS', 'CPU models', default_cpus, all_cpu_list),
539    BoolOption('NO_FAST_ALLOC', 'Disable fast object allocator', False),
540    BoolOption('EFENCE', 'Link with Electric Fence malloc debugger',
541               False),
542    BoolOption('SS_COMPATIBLE_FP',
543               'Make floating-point results compatible with SimpleScalar',
544               False),
545    BoolOption('USE_SSE2',
546               'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
547               False),
548    BoolOption('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
549    BoolOption('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
550    BoolOption('USE_CHECKER', 'Use checker for detailed CPU models', False),
551    BoolOption('BATCH', 'Use batch pool for build and tests', False),
552    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
553    ('PYTHONHOME',
554     'Override the default PYTHONHOME for this system (use with caution)',
555     '%s:%s' % (sys.prefix, sys.exec_prefix)),
556    )
557
558nonsticky_opts.AddOptions(
559    BoolOption('update_ref', 'Update test reference outputs', False)
560    )
561
562# These options get exported to #defines in config/*.hh (see src/SConscript).
563env.ExportOptions = ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
564                     'USE_MYSQL', 'NO_FAST_ALLOC', 'SS_COMPATIBLE_FP', \
565                     'USE_CHECKER', 'PYTHONHOME', 'TARGET_ISA']
566
567# Define a handy 'no-op' action
568def no_action(target, source, env):
569    return 0
570
571env.NoAction = Action(no_action, None)
572
573###################################################
574#
575# Define a SCons builder for configuration flag headers.
576#
577###################################################
578
579# This function generates a config header file that #defines the
580# option symbol to the current option setting (0 or 1).  The source
581# operands are the name of the option and a Value node containing the
582# value of the option.
583def build_config_file(target, source, env):
584    (option, value) = [s.get_contents() for s in source]
585    f = file(str(target[0]), 'w')
586    print >> f, '#define', option, value
587    f.close()
588    return None
589
590# Generate the message to be printed when building the config file.
591def build_config_file_string(target, source, env):
592    (option, value) = [s.get_contents() for s in source]
593    return "Defining %s as %s in %s." % (option, value, target[0])
594
595# Combine the two functions into a scons Action object.
596config_action = Action(build_config_file, build_config_file_string)
597
598# The emitter munges the source & target node lists to reflect what
599# we're really doing.
600def config_emitter(target, source, env):
601    # extract option name from Builder arg
602    option = str(target[0])
603    # True target is config header file
604    target = joinpath('config', option.lower() + '.hh')
605    val = env[option]
606    if isinstance(val, bool):
607        # Force value to 0/1
608        val = int(val)
609    elif isinstance(val, str):
610        val = '"' + val + '"'
611
612    # Sources are option name & value (packaged in SCons Value nodes)
613    return ([target], [Value(option), Value(val)])
614
615config_builder = Builder(emitter = config_emitter, action = config_action)
616
617env.Append(BUILDERS = { 'ConfigFile' : config_builder })
618
619###################################################
620#
621# Define a SCons builder for copying files.  This is used by the
622# Python zipfile code in src/python/SConscript, but is placed up here
623# since it's potentially more generally applicable.
624#
625###################################################
626
627copy_builder = Builder(action = Copy("$TARGET", "$SOURCE"))
628
629env.Append(BUILDERS = { 'CopyFile' : copy_builder })
630
631###################################################
632#
633# Define a simple SCons builder to concatenate files.
634#
635# Used to append the Python zip archive to the executable.
636#
637###################################################
638
639concat_builder = Builder(action = Action(['cat $SOURCES > $TARGET',
640                                          'chmod +x $TARGET']))
641
642env.Append(BUILDERS = { 'Concat' : concat_builder })
643
644
645# libelf build is shared across all configs in the build root.
646env.SConscript('ext/libelf/SConscript',
647               build_dir = joinpath(build_root, 'libelf'),
648               exports = 'env')
649
650###################################################
651#
652# This function is used to set up a directory with switching headers
653#
654###################################################
655
656env['ALL_ISA_LIST'] = all_isa_list
657def make_switching_dir(dirname, switch_headers, env):
658    # Generate the header.  target[0] is the full path of the output
659    # header to generate.  'source' is a dummy variable, since we get the
660    # list of ISAs from env['ALL_ISA_LIST'].
661    def gen_switch_hdr(target, source, env):
662        fname = str(target[0])
663        basename = os.path.basename(fname)
664        f = open(fname, 'w')
665        f.write('#include "arch/isa_specific.hh"\n')
666        cond = '#if'
667        for isa in all_isa_list:
668            f.write('%s THE_ISA == %s_ISA\n#include "%s/%s/%s"\n'
669                    % (cond, isa.upper(), dirname, isa, basename))
670            cond = '#elif'
671        f.write('#else\n#error "THE_ISA not set"\n#endif\n')
672        f.close()
673        return 0
674
675    # String to print when generating header
676    def gen_switch_hdr_string(target, source, env):
677        return "Generating switch header " + str(target[0])
678
679    # Build SCons Action object. 'varlist' specifies env vars that this
680    # action depends on; when env['ALL_ISA_LIST'] changes these actions
681    # should get re-executed.
682    switch_hdr_action = Action(gen_switch_hdr, gen_switch_hdr_string,
683                               varlist=['ALL_ISA_LIST'])
684
685    # Instantiate actions for each header
686    for hdr in switch_headers:
687        env.Command(hdr, [], switch_hdr_action)
688Export('make_switching_dir')
689
690###################################################
691#
692# Define build environments for selected configurations.
693#
694###################################################
695
696# rename base env
697base_env = env
698
699for build_path in build_paths:
700    print "Building in", build_path
701    env['BUILDDIR'] = build_path
702
703    # build_dir is the tail component of build path, and is used to
704    # determine the build parameters (e.g., 'ALPHA_SE')
705    (build_root, build_dir) = os.path.split(build_path)
706    # Make a copy of the build-root environment to use for this config.
707    env = base_env.Copy()
708
709    # Set env options according to the build directory config.
710    sticky_opts.files = []
711    # Options for $BUILD_ROOT/$BUILD_DIR are stored in
712    # $BUILD_ROOT/options/$BUILD_DIR so you can nuke
713    # $BUILD_ROOT/$BUILD_DIR without losing your options settings.
714    current_opts_file = joinpath(build_root, 'options', build_dir)
715    if isfile(current_opts_file):
716        sticky_opts.files.append(current_opts_file)
717        print "Using saved options file %s" % current_opts_file
718    else:
719        # Build dir-specific options file doesn't exist.
720
721        # Make sure the directory is there so we can create it later
722        opt_dir = os.path.dirname(current_opts_file)
723        if not isdir(opt_dir):
724            os.mkdir(opt_dir)
725
726        # Get default build options from source tree.  Options are
727        # normally determined by name of $BUILD_DIR, but can be
728        # overriden by 'default=' arg on command line.
729        default_opts_file = joinpath('build_opts',
730                                     ARGUMENTS.get('default', build_dir))
731        if isfile(default_opts_file):
732            sticky_opts.files.append(default_opts_file)
733            print "Options file %s not found,\n  using defaults in %s" \
734                  % (current_opts_file, default_opts_file)
735        else:
736            print "Error: cannot find options file %s or %s" \
737                  % (current_opts_file, default_opts_file)
738            Exit(1)
739
740    # Apply current option settings to env
741    sticky_opts.Update(env)
742    nonsticky_opts.Update(env)
743
744    help_text += "\nSticky options for %s:\n" % build_dir \
745                 + sticky_opts.GenerateHelpText(env) \
746                 + "\nNon-sticky options for %s:\n" % build_dir \
747                 + nonsticky_opts.GenerateHelpText(env)
748
749    # Process option settings.
750
751    if not have_fenv and env['USE_FENV']:
752        print "Warning: <fenv.h> not available; " \
753              "forcing USE_FENV to False in", build_dir + "."
754        env['USE_FENV'] = False
755
756    if not env['USE_FENV']:
757        print "Warning: No IEEE FP rounding mode control in", build_dir + "."
758        print "         FP results may deviate slightly from other platforms."
759
760    if env['EFENCE']:
761        env.Append(LIBS=['efence'])
762
763    if env['USE_MYSQL']:
764        if not have_mysql:
765            print "Warning: MySQL not available; " \
766                  "forcing USE_MYSQL to False in", build_dir + "."
767            env['USE_MYSQL'] = False
768        else:
769            print "Compiling in", build_dir, "with MySQL support."
770            env.ParseConfig(mysql_config_libs)
771            env.ParseConfig(mysql_config_include)
772
773    # Save sticky option settings back to current options file
774    sticky_opts.Save(current_opts_file, env)
775
776    # Do this after we save setting back, or else we'll tack on an
777    # extra 'qdo' every time we run scons.
778    if env['BATCH']:
779        env['CC']  = env['BATCH_CMD'] + ' ' + env['CC']
780        env['CXX'] = env['BATCH_CMD'] + ' ' + env['CXX']
781
782    if env['USE_SSE2']:
783        env.Append(CCFLAGS='-msse2')
784
785    # The src/SConscript file sets up the build rules in 'env' according
786    # to the configured options.  It returns a list of environments,
787    # one for each variant build (debug, opt, etc.)
788    envList = SConscript('src/SConscript', build_dir = build_path,
789                         exports = 'env')
790
791    # Set up the regression tests for each build.
792    for e in envList:
793        SConscript('tests/SConscript',
794                   build_dir = joinpath(build_path, 'tests', e.Label),
795                   exports = { 'env' : e }, duplicate = False)
796
797Help(help_text)
798
799
800###################################################
801#
802# Let SCons do its thing.  At this point SCons will use the defined
803# build environments to build the requested targets.
804#
805###################################################
806
807