SConstruct revision 6113
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
4955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
5955SN/A# All rights reserved.
6955SN/A#
7955SN/A# Redistribution and use in source and binary forms, with or without
8955SN/A# modification, are permitted provided that the following conditions are
9955SN/A# met: redistributions of source code must retain the above copyright
10955SN/A# notice, this list of conditions and the following disclaimer;
11955SN/A# redistributions in binary form must reproduce the above copyright
12955SN/A# notice, this list of conditions and the following disclaimer in the
13955SN/A# documentation and/or other materials provided with the distribution;
14955SN/A# neither the name of the copyright holders nor the names of its
15955SN/A# contributors may be used to endorse or promote products derived from
16955SN/A# this software without specific prior written permission.
17955SN/A#
18955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
282665Ssaidi@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
292665Ssaidi@eecs.umich.edu#
30955SN/A# Authors: Steve Reinhardt
31955SN/A#          Nathan Binkert
32955SN/A
33955SN/A###################################################
34955SN/A#
352632Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
362632Sstever@eecs.umich.edu#
372632Sstever@eecs.umich.edu# While in this directory ('m5'), just type 'scons' to build the default
382632Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
39955SN/A# to build some other configuration (e.g., 'build/ALPHA_FS/m5.opt' for
402632Sstever@eecs.umich.edu# the optimized full-system version).
412632Sstever@eecs.umich.edu#
422761Sstever@eecs.umich.edu# You can build M5 in a different directory as long as there is a
432632Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
442632Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
452632Sstever@eecs.umich.edu# built for the same host system.
462761Sstever@eecs.umich.edu#
472761Sstever@eecs.umich.edu# Examples:
482761Sstever@eecs.umich.edu#
492632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
502632Sstever@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
512761Sstever@eecs.umich.edu#   % cd <path-to-src>/m5 ; scons build/ALPHA_FS/m5.debug
522761Sstever@eecs.umich.edu#   % cd <path-to-src>/m5/build/ALPHA_FS; scons -u m5.debug
532761Sstever@eecs.umich.edu#
542761Sstever@eecs.umich.edu#   The following two commands are equivalent and demonstrate building
552761Sstever@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
562632Sstever@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
572632Sstever@eecs.umich.edu#   file.
582632Sstever@eecs.umich.edu#   % cd <path-to-src>/m5 ; scons /local/foo/build/ALPHA_FS/m5.debug
592632Sstever@eecs.umich.edu#   % cd /local/foo/build/ALPHA_FS; scons -C <path-to-src>/m5 m5.debug
602632Sstever@eecs.umich.edu#
612632Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
622632Sstever@eecs.umich.edu# 'm5' directory (or use -u or -C to tell scons where to find this
63955SN/A# file), you can use 'scons -h' to print all the M5-specific build
64955SN/A# options as well.
65955SN/A#
66955SN/A###################################################
67955SN/A
68955SN/A# Check for recent-enough Python and SCons versions.
69955SN/Atry:
702656Sstever@eecs.umich.edu    # Really old versions of scons only take two options for the
712656Sstever@eecs.umich.edu    # function, so check once without the revision and once with the
722656Sstever@eecs.umich.edu    # revision, the first instance will fail for stuff other than
732656Sstever@eecs.umich.edu    # 0.98, and the second will fail for 0.98.0
742656Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98)
752656Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98, 1)
762656Sstever@eecs.umich.eduexcept SystemExit, e:
772653Sstever@eecs.umich.edu    print """
782653Sstever@eecs.umich.eduFor more details, see:
792653Sstever@eecs.umich.edu    http://m5sim.org/wiki/index.php/Compiling_M5
802653Sstever@eecs.umich.edu"""
812653Sstever@eecs.umich.edu    raise
822653Sstever@eecs.umich.edu
832653Sstever@eecs.umich.edu# We ensure the python version early because we have stuff that
842653Sstever@eecs.umich.edu# requires python 2.4
852653Sstever@eecs.umich.edutry:
862653Sstever@eecs.umich.edu    EnsurePythonVersion(2, 4)
872653Sstever@eecs.umich.eduexcept SystemExit, e:
881852SN/A    print """
89955SN/AYou can use a non-default installation of the Python interpreter by
90955SN/Aeither (1) rearranging your PATH so that scons finds the non-default
91955SN/A'python' first or (2) explicitly invoking an alternative interpreter
922632Sstever@eecs.umich.eduon the scons script.
932632Sstever@eecs.umich.edu
94955SN/AFor more details, see:
951533SN/A    http://m5sim.org/wiki/index.php/Using_a_non-default_Python_installation
962632Sstever@eecs.umich.edu"""
971533SN/A    raise
98955SN/A
99955SN/Aimport os
1002632Sstever@eecs.umich.eduimport re
1012632Sstever@eecs.umich.eduimport subprocess
102955SN/Aimport sys
103955SN/A
104955SN/Afrom os import mkdir, environ
105955SN/Afrom os.path import abspath, basename, dirname, expanduser, normpath
1062632Sstever@eecs.umich.edufrom os.path import exists,  isdir, isfile
107955SN/Afrom os.path import join as joinpath, split as splitpath
1082632Sstever@eecs.umich.edu
109955SN/Aimport SCons
110955SN/Aimport SCons.Node
1112632Sstever@eecs.umich.edu
1122632Sstever@eecs.umich.edudef read_command(cmd, **kwargs):
1132632Sstever@eecs.umich.edu    """run the command cmd, read the results and return them
1142632Sstever@eecs.umich.edu    this is sorta like `cmd` in shell"""
1152632Sstever@eecs.umich.edu    from subprocess import Popen, PIPE, STDOUT
1162632Sstever@eecs.umich.edu
1172632Sstever@eecs.umich.edu    if isinstance(cmd, str):
1182632Sstever@eecs.umich.edu        cmd = cmd.split()
1192632Sstever@eecs.umich.edu
1202632Sstever@eecs.umich.edu    no_exception = 'exception' in kwargs
1212632Sstever@eecs.umich.edu    exception = kwargs.pop('exception', None)
1222632Sstever@eecs.umich.edu    
1232632Sstever@eecs.umich.edu    kwargs.setdefault('shell', False)
1242632Sstever@eecs.umich.edu    kwargs.setdefault('stdout', PIPE)
1252632Sstever@eecs.umich.edu    kwargs.setdefault('stderr', STDOUT)
1262632Sstever@eecs.umich.edu    kwargs.setdefault('close_fds', True)
1272632Sstever@eecs.umich.edu    try:
1282634Sstever@eecs.umich.edu        subp = Popen(cmd, **kwargs)
1292634Sstever@eecs.umich.edu    except Exception, e:
1302632Sstever@eecs.umich.edu        if no_exception:
1312638Sstever@eecs.umich.edu            return exception
1322632Sstever@eecs.umich.edu        raise
1332632Sstever@eecs.umich.edu
1342632Sstever@eecs.umich.edu    return subp.communicate()[0]
1352632Sstever@eecs.umich.edu
1362632Sstever@eecs.umich.edu# helper function: compare arrays or strings of version numbers.
1372632Sstever@eecs.umich.edu# E.g., compare_version((1,3,25), (1,4,1)')
1381858SN/A# returns -1, 0, 1 if v1 is <, ==, > v2
1392638Sstever@eecs.umich.edudef compare_versions(v1, v2):
1402638Sstever@eecs.umich.edu    def make_version_list(v):
1412638Sstever@eecs.umich.edu        if isinstance(v, (list,tuple)):
1422638Sstever@eecs.umich.edu            return v
1432638Sstever@eecs.umich.edu        elif isinstance(v, str):
1442638Sstever@eecs.umich.edu            return map(lambda x: int(re.match('\d+', x).group()), v.split('.'))
1452638Sstever@eecs.umich.edu        else:
1462638Sstever@eecs.umich.edu            raise TypeError
1472634Sstever@eecs.umich.edu
1482634Sstever@eecs.umich.edu    v1 = make_version_list(v1)
1492634Sstever@eecs.umich.edu    v2 = make_version_list(v2)
150955SN/A    # Compare corresponding elements of lists
151955SN/A    for n1,n2 in zip(v1, v2):
152955SN/A        if n1 < n2: return -1
153955SN/A        if n1 > n2: return  1
154955SN/A    # all corresponding values are equal... see if one has extra values
155955SN/A    if len(v1) < len(v2): return -1
156955SN/A    if len(v1) > len(v2): return  1
157955SN/A    return 0
1581858SN/A
1591858SN/A########################################################################
1602632Sstever@eecs.umich.edu#
161955SN/A# Set up the base build environment.
1622776Sstever@eecs.umich.edu#
1631105SN/A########################################################################
1642667Sstever@eecs.umich.eduuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH', 'PATH',
1652667Sstever@eecs.umich.edu                 'RANLIB' ])
1662667Sstever@eecs.umich.edu
1672667Sstever@eecs.umich.eduuse_env = {}
1682667Sstever@eecs.umich.edufor key,val in os.environ.iteritems():
1692667Sstever@eecs.umich.edu    if key in use_vars or key.startswith("M5"):
1701869SN/A        use_env[key] = val
1711869SN/A
1721869SN/Aenv = Environment(ENV=use_env)
1731869SN/Aenv.root = Dir(".")          # The current directory (where this file lives).
1741869SN/Aenv.srcdir = Dir("src")      # The source directory
1751065SN/A
1762632Sstever@eecs.umich.edu########################################################################
1772632Sstever@eecs.umich.edu#
178955SN/A# Mercurial Stuff.
1791858SN/A#
1801858SN/A# If the M5 directory is a mercurial repository, we should do some
1811858SN/A# extra things.
1821858SN/A#
1831851SN/A########################################################################
1841851SN/A
1851858SN/Ahgdir = env.root.Dir(".hg")
1862632Sstever@eecs.umich.edu
187955SN/Amercurial_style_message = """
1882656Sstever@eecs.umich.eduYou're missing the M5 style hook.
1892656Sstever@eecs.umich.eduPlease install the hook so we can ensure that all code fits a common style.
1902656Sstever@eecs.umich.edu
1912656Sstever@eecs.umich.eduAll you'd need to do is add the following lines to your repository .hg/hgrc
1922656Sstever@eecs.umich.eduor your personal .hgrc
1932656Sstever@eecs.umich.edu----------------
1942656Sstever@eecs.umich.edu
1952656Sstever@eecs.umich.edu[extensions]
1962656Sstever@eecs.umich.edustyle = %s/util/style.py
1972656Sstever@eecs.umich.edu
1982656Sstever@eecs.umich.edu[hooks]
1992656Sstever@eecs.umich.edupretxncommit.style = python:style.check_whitespace
2002656Sstever@eecs.umich.edu""" % (env.root)
2012656Sstever@eecs.umich.edu
2022656Sstever@eecs.umich.edumercurial_bin_not_found = """
2032656Sstever@eecs.umich.eduMercurial binary cannot be found, unfortunately this means that we
2042655Sstever@eecs.umich.educannot easily determine the version of M5 that you are running and
2052667Sstever@eecs.umich.eduthis makes error messages more difficult to collect.  Please consider
2062667Sstever@eecs.umich.eduinstalling mercurial if you choose to post an error message
2072667Sstever@eecs.umich.edu"""
2082667Sstever@eecs.umich.edu
2092667Sstever@eecs.umich.edumercurial_lib_not_found = """
2102667Sstever@eecs.umich.eduMercurial libraries cannot be found, ignoring style hook
2112667Sstever@eecs.umich.eduIf you are actually a M5 developer, please fix this and
2122667Sstever@eecs.umich.edurun the style hook. It is important.
2132667Sstever@eecs.umich.edu"""
2142667Sstever@eecs.umich.edu
2152667Sstever@eecs.umich.eduhg_info = "Unknown"
2162667Sstever@eecs.umich.eduif hgdir.exists():
2172667Sstever@eecs.umich.edu    # 1) Grab repository revision if we know it.
2182655Sstever@eecs.umich.edu    cmd = "hg id -n -i -t -b"
2191858SN/A    try:
2201858SN/A        hg_info = read_command(cmd, cwd=env.root.abspath).strip()
2212638Sstever@eecs.umich.edu    except OSError:
2222638Sstever@eecs.umich.edu        print mercurial_bin_not_found
2232638Sstever@eecs.umich.edu
2242638Sstever@eecs.umich.edu    # 2) Ensure that the style hook is in place.
2252638Sstever@eecs.umich.edu    try:
2261858SN/A        ui = None
2271858SN/A        if ARGUMENTS.get('IGNORE_STYLE') != 'True':
2281858SN/A            from mercurial import ui
2291858SN/A            ui = ui.ui()
2301858SN/A    except ImportError:
2311858SN/A        print mercurial_lib_not_found
2321858SN/A
2331859SN/A    if ui is not None:
2341858SN/A        ui.readconfig(hgdir.File('hgrc').abspath)
2351858SN/A        style_hook = ui.config('hooks', 'pretxncommit.style', None)
2361858SN/A
2371859SN/A        if not style_hook:
2381859SN/A            print mercurial_style_message
2391862SN/A            sys.exit(1)
2401862SN/Aelse:
2411862SN/A    print ".hg directory not found"
2421862SN/Aenv['HG_INFO'] = hg_info
2431859SN/A
2441859SN/A###################################################
2451963SN/A#
2461963SN/A# Figure out which configurations to set up based on the path(s) of
2471859SN/A# the target(s).
2481859SN/A#
2491859SN/A###################################################
2501859SN/A
2511859SN/A# Find default configuration & binary.
2521859SN/ADefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
2531859SN/A
2541859SN/A# helper function: find last occurrence of element in list
2551862SN/Adef rfind(l, elt, offs = -1):
2561859SN/A    for i in range(len(l)+offs, 0, -1):
2571859SN/A        if l[i] == elt:
2581859SN/A            return i
2591858SN/A    raise ValueError, "element not found"
2601858SN/A
2612139SN/A# Each target must have 'build' in the interior of the path; the
2622139SN/A# directory below this will determine the build parameters.  For
2632139SN/A# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2642155SN/A# recognize that ALPHA_SE specifies the configuration because it
2652623SN/A# follow 'build' in the bulid path.
2662817Sksewell@umich.edu
2672792Sktlim@umich.edu# Generate absolute paths to targets so we can see where the build dir is
2682155SN/Aif COMMAND_LINE_TARGETS:
2691869SN/A    # Ask SCons which directory it was invoked from
2701869SN/A    launch_dir = GetLaunchDir()
2711869SN/A    # Make targets relative to invocation directory
2721869SN/A    abs_targets = [ normpath(joinpath(launch_dir, str(x))) for x in \
2731869SN/A                    COMMAND_LINE_TARGETS]
2742139SN/Aelse:
2751869SN/A    # Default targets are relative to root of tree
2762508SN/A    abs_targets = [ normpath(joinpath(env.root.abspath, str(x))) for x in \
2772508SN/A                    DEFAULT_TARGETS]
2782508SN/A
2792508SN/A
2802635Sstever@eecs.umich.edu# Generate a list of the unique build roots and configs that the
2812635Sstever@eecs.umich.edu# collected targets reference.
2821869SN/Avariant_paths = []
2831869SN/Abuild_root = None
2841869SN/Afor t in abs_targets:
2851869SN/A    path_dirs = t.split('/')
2861869SN/A    try:
2871869SN/A        build_top = rfind(path_dirs, 'build', -2)
2881869SN/A    except:
2891869SN/A        print "Error: no non-leaf 'build' dir found on target path", t
2901965SN/A        Exit(1)
2911965SN/A    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2921965SN/A    if not build_root:
2931869SN/A        build_root = this_build_root
2941869SN/A    else:
2952733Sktlim@umich.edu        if this_build_root != build_root:
2961869SN/A            print "Error: build targets not under same build root\n"\
2971884SN/A                  "  %s\n  %s" % (build_root, this_build_root)
2981884SN/A            Exit(1)
2991884SN/A    variant_path = joinpath('/',*path_dirs[:build_top+2])
3001869SN/A    if variant_path not in variant_paths:
3011858SN/A        variant_paths.append(variant_path)
3021869SN/A
3031869SN/A# Make sure build_root exists (might not if this is the first build there)
3041869SN/Aif not isdir(build_root):
3052953Sktlim@umich.edu    mkdir(build_root)
3062953Sktlim@umich.edu
3071869SN/AExport('env')
3081869SN/A
3091858SN/Aenv.SConsignFile(joinpath(build_root, "sconsign"))
3102761Sstever@eecs.umich.edu
3111869SN/A# Default duplicate option is to use hard links, but this messes up
3122733Sktlim@umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
3132733Sktlim@umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
3141869SN/A# (soft) links work better.
3151869SN/Aenv.SetOption('duplicate', 'soft-copy')
3161869SN/A
3171869SN/A#
3181869SN/A# Set up global sticky variables... these are common to an entire build
3191869SN/A# tree (not specific to a particular build like ALPHA_SE)
3201858SN/A#
321955SN/A
322955SN/A# Variable validators & converters for global sticky variables
3231869SN/Adef PathListMakeAbsolute(val):
3241869SN/A    if not val:
3251869SN/A        return val
3261869SN/A    f = lambda p: abspath(expanduser(p))
3271869SN/A    return ':'.join(map(f, val.split(':')))
3281869SN/A
3291869SN/Adef PathListAllExist(key, val, env):
3301869SN/A    if not val:
3311869SN/A        return
3321869SN/A    paths = val.split(':')
3331869SN/A    for path in paths:
3341869SN/A        if not isdir(path):
3351869SN/A            raise SCons.Errors.UserError("Path does not exist: '%s'" % path)
3361869SN/A
3371869SN/Aglobal_sticky_vars_file = joinpath(build_root, 'variables.global')
3381869SN/A
3391869SN/Aglobal_sticky_vars = Variables(global_sticky_vars_file, args=ARGUMENTS)
3401869SN/A
3411869SN/Aglobal_sticky_vars.AddVariables(
3421869SN/A    ('CC', 'C compiler', environ.get('CC', env['CC'])),
3431869SN/A    ('CXX', 'C++ compiler', environ.get('CXX', env['CXX'])),
3441869SN/A    ('BATCH', 'Use batch pool for build and tests', False),
3451869SN/A    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3461869SN/A    ('EXTRAS', 'Add Extra directories to the compilation', '',
3471869SN/A     PathListAllExist, PathListMakeAbsolute)
3481869SN/A    )    
3491869SN/A
3501869SN/A# base help text
3511869SN/Ahelp_text = '''
3521869SN/AUsage: scons [scons options] [build options] [target(s)]
3531869SN/A
3541869SN/AGlobal sticky options:
3551869SN/A'''
3561869SN/A
3571869SN/Ahelp_text += global_sticky_vars.GenerateHelpText(env)
3581869SN/A
3591869SN/A# Update env with values from ARGUMENTS & file global_sticky_vars_file
3601869SN/Aglobal_sticky_vars.Update(env)
3611869SN/A
3622655Sstever@eecs.umich.edu# Save sticky variable settings back to current variables file
3632655Sstever@eecs.umich.eduglobal_sticky_vars.Save(global_sticky_vars_file, env)
3642655Sstever@eecs.umich.edu
3652655Sstever@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
3662655Sstever@eecs.umich.edu# look for sources etc.  This list is exported as base_dir_list.
3672655Sstever@eecs.umich.edubase_dir = env.srcdir.abspath
3682655Sstever@eecs.umich.eduif env['EXTRAS']:
3692655Sstever@eecs.umich.edu    extras_dir_list = env['EXTRAS'].split(':')
3702655Sstever@eecs.umich.eduelse:
3712655Sstever@eecs.umich.edu    extras_dir_list = []
3722655Sstever@eecs.umich.edu
3732655Sstever@eecs.umich.eduExport('base_dir')
3742655Sstever@eecs.umich.eduExport('extras_dir_list')
3752655Sstever@eecs.umich.edu
3762655Sstever@eecs.umich.edu# the ext directory should be on the #includes path
3772655Sstever@eecs.umich.eduenv.Append(CPPPATH=[Dir('ext')])
3782655Sstever@eecs.umich.edu
3792655Sstever@eecs.umich.edu# M5_PLY is used by isa_parser.py to find the PLY package.
3802655Sstever@eecs.umich.eduenv.Append(ENV = { 'M5_PLY' : Dir('ext/ply').abspath })
3812655Sstever@eecs.umich.edu
3822655Sstever@eecs.umich.eduCXX_version = read_command([env['CXX'],'--version'], exception=False)
3832655Sstever@eecs.umich.eduCXX_V = read_command([env['CXX'],'-V'], exception=False)
3842655Sstever@eecs.umich.edu
3852655Sstever@eecs.umich.eduenv['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3862655Sstever@eecs.umich.eduenv['SUNCC'] = CXX_V and CXX_V.find('Sun C++') >= 0
3872655Sstever@eecs.umich.eduenv['ICC'] = CXX_V and CXX_V.find('Intel') >= 0
3882634Sstever@eecs.umich.eduif env['GCC'] + env['SUNCC'] + env['ICC'] > 1:
3892634Sstever@eecs.umich.edu    print 'Error: How can we have two at the same time?'
3902634Sstever@eecs.umich.edu    Exit(1)
3912634Sstever@eecs.umich.edu
3922634Sstever@eecs.umich.edu# Set up default C++ compiler flags
3932634Sstever@eecs.umich.eduif env['GCC']:
3942638Sstever@eecs.umich.edu    env.Append(CCFLAGS='-pipe')
3952638Sstever@eecs.umich.edu    env.Append(CCFLAGS='-fno-strict-aliasing')
3962638Sstever@eecs.umich.edu    env.Append(CCFLAGS=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
3972638Sstever@eecs.umich.edu    env.Append(CXXFLAGS='-Wno-deprecated')
3982638Sstever@eecs.umich.eduelif env['ICC']:
3991869SN/A    pass #Fix me... add warning flags once we clean up icc warnings
4001869SN/Aelif env['SUNCC']:
401955SN/A    env.Append(CCFLAGS='-Qoption ccfe')
402955SN/A    env.Append(CCFLAGS='-features=gcc')
403955SN/A    env.Append(CCFLAGS='-features=extensions')
404955SN/A    env.Append(CCFLAGS='-library=stlport4')
4051858SN/A    env.Append(CCFLAGS='-xar')
4061858SN/A    #env.Append(CCFLAGS='-instances=semiexplicit')
4071858SN/Aelse:
4082632Sstever@eecs.umich.edu    print 'Error: Don\'t know what compiler options to use for your compiler.'
4092632Sstever@eecs.umich.edu    print '       Please fix SConstruct and src/SConscript and try again.'
4102632Sstever@eecs.umich.edu    Exit(1)
4112632Sstever@eecs.umich.edu
4122632Sstever@eecs.umich.edu# Do this after we save setting back, or else we'll tack on an
4132634Sstever@eecs.umich.edu# extra 'qdo' every time we run scons.
4142638Sstever@eecs.umich.eduif env['BATCH']:
4152023SN/A    env['CC']     = env['BATCH_CMD'] + ' ' + env['CC']
4162632Sstever@eecs.umich.edu    env['CXX']    = env['BATCH_CMD'] + ' ' + env['CXX']
4172632Sstever@eecs.umich.edu    env['AS']     = env['BATCH_CMD'] + ' ' + env['AS']
4182632Sstever@eecs.umich.edu    env['AR']     = env['BATCH_CMD'] + ' ' + env['AR']
4192632Sstever@eecs.umich.edu    env['RANLIB'] = env['BATCH_CMD'] + ' ' + env['RANLIB']
4202632Sstever@eecs.umich.edu
4212632Sstever@eecs.umich.eduif sys.platform == 'cygwin':
4222632Sstever@eecs.umich.edu    # cygwin has some header file issues...
4232632Sstever@eecs.umich.edu    env.Append(CCFLAGS=Split("-Wno-uninitialized"))
4242632Sstever@eecs.umich.edu
4252632Sstever@eecs.umich.edu# Check for SWIG
4262632Sstever@eecs.umich.eduif not env.has_key('SWIG'):
4272023SN/A    print 'Error: SWIG utility not found.'
4282632Sstever@eecs.umich.edu    print '       Please install (see http://www.swig.org) and retry.'
4292632Sstever@eecs.umich.edu    Exit(1)
4301889SN/A
4311889SN/A# Check for appropriate SWIG version
4322632Sstever@eecs.umich.eduswig_version = read_command(('swig', '-version'), exception='').split()
4332632Sstever@eecs.umich.edu# First 3 words should be "SWIG Version x.y.z"
4342632Sstever@eecs.umich.eduif len(swig_version) < 3 or \
4352632Sstever@eecs.umich.edu        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
4362632Sstever@eecs.umich.edu    print 'Error determining SWIG version.'
4372632Sstever@eecs.umich.edu    Exit(1)
4382632Sstever@eecs.umich.edu
4392632Sstever@eecs.umich.edumin_swig_version = '1.3.28'
4402632Sstever@eecs.umich.eduif compare_versions(swig_version[2], min_swig_version) < 0:
4412632Sstever@eecs.umich.edu    print 'Error: SWIG version', min_swig_version, 'or newer required.'
4422632Sstever@eecs.umich.edu    print '       Installed version:', swig_version[2]
4432632Sstever@eecs.umich.edu    Exit(1)
4442632Sstever@eecs.umich.edu
4452632Sstever@eecs.umich.edu# Set up SWIG flags & scanner
4461888SN/Aswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
4471888SN/Aenv.Append(SWIGFLAGS=swig_flags)
4481869SN/A
4491869SN/A# filter out all existing swig scanners, they mess up the dependency
4501858SN/A# stuff for some reason
4512598SN/Ascanners = []
4522598SN/Afor scanner in env['SCANNERS']:
4532598SN/A    skeys = scanner.skeys
4542598SN/A    if skeys == '.i':
4552598SN/A        continue
4561858SN/A
4571858SN/A    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
4581858SN/A        continue
4591858SN/A
4601858SN/A    scanners.append(scanner)
4611858SN/A
4621858SN/A# add the new swig scanner that we like better
4631858SN/Afrom SCons.Scanner import ClassicCPP as CPPScanner
4641858SN/Aswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
4651871SN/Ascanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
4661858SN/A
4671858SN/A# replace the scanners list that has what we want
4681858SN/Aenv['SCANNERS'] = scanners
4691858SN/A
4701858SN/A# Add a custom Check function to the Configure context so that we can
4711858SN/A# figure out if the compiler adds leading underscores to global
4721858SN/A# variables.  This is needed for the autogenerated asm files that we
4731858SN/A# use for embedding the python code.
4741858SN/Adef CheckLeading(context):
4751858SN/A    context.Message("Checking for leading underscore in global variables...")
4761858SN/A    # 1) Define a global variable called x from asm so the C compiler
4771859SN/A    #    won't change the symbol at all.
4781859SN/A    # 2) Declare that variable.
4791869SN/A    # 3) Use the variable
4801888SN/A    #
4812632Sstever@eecs.umich.edu    # If the compiler prepends an underscore, this will successfully
4821869SN/A    # link because the external symbol 'x' will be called '_x' which
4831884SN/A    # was defined by the asm statement.  If the compiler does not
4841884SN/A    # prepend an underscore, this will not successfully link because
4851884SN/A    # '_x' will have been defined by assembly, while the C portion of
4861884SN/A    # the code will be trying to use 'x'
4871884SN/A    ret = context.TryLink('''
4881884SN/A        asm(".globl _x; _x: .byte 0");
4891965SN/A        extern int x;
4901965SN/A        int main() { return x; }
4911965SN/A        ''', extension=".c")
4922761Sstever@eecs.umich.edu    context.env.Append(LEADING_UNDERSCORE=ret)
4931869SN/A    context.Result(ret)
4941869SN/A    return ret
4952632Sstever@eecs.umich.edu
4962667Sstever@eecs.umich.edu# Platform-specific configuration.  Note again that we assume that all
4971869SN/A# builds under a given build root run on the same host platform.
4981869SN/Aconf = Configure(env,
4992929Sktlim@umich.edu                 conf_dir = joinpath(build_root, '.scons_config'),
5002929Sktlim@umich.edu                 log_file = joinpath(build_root, 'scons_config.log'),
5012929Sktlim@umich.edu                 custom_tests = { 'CheckLeading' : CheckLeading })
5022929Sktlim@umich.edu
503955SN/A# Check for leading underscores.  Don't really need to worry either
5042598SN/A# way so don't need to check the return code.
5052598SN/Aconf.CheckLeading()
506955SN/A
507955SN/A# Check if we should compile a 64 bit binary on Mac OS X/Darwin
508955SN/Atry:
5091530SN/A    import platform
510955SN/A    uname = platform.uname()
511955SN/A    if uname[0] == 'Darwin' and compare_versions(uname[2], '9.0.0') >= 0:
512955SN/A        if int(read_command('sysctl -n hw.cpu64bit_capable')[0]):
513            env.Append(CCFLAGS='-arch x86_64')
514            env.Append(CFLAGS='-arch x86_64')
515            env.Append(LINKFLAGS='-arch x86_64')
516            env.Append(ASFLAGS='-arch x86_64')
517except:
518    pass
519
520# Recent versions of scons substitute a "Null" object for Configure()
521# when configuration isn't necessary, e.g., if the "--help" option is
522# present.  Unfortuantely this Null object always returns false,
523# breaking all our configuration checks.  We replace it with our own
524# more optimistic null object that returns True instead.
525if not conf:
526    def NullCheck(*args, **kwargs):
527        return True
528
529    class NullConf:
530        def __init__(self, env):
531            self.env = env
532        def Finish(self):
533            return self.env
534        def __getattr__(self, mname):
535            return NullCheck
536
537    conf = NullConf(env)
538
539# Find Python include and library directories for embedding the
540# interpreter.  For consistency, we will use the same Python
541# installation used to run scons (and thus this script).  If you want
542# to link in an alternate version, see above for instructions on how
543# to invoke scons with a different copy of the Python interpreter.
544from distutils import sysconfig
545
546py_getvar = sysconfig.get_config_var
547
548py_version = 'python' + py_getvar('VERSION')
549
550py_general_include = sysconfig.get_python_inc()
551py_platform_include = sysconfig.get_python_inc(plat_specific=True)
552py_includes = [ py_general_include ]
553if py_platform_include != py_general_include:
554    py_includes.append(py_platform_include)
555
556py_lib_path = [ py_getvar('LIBDIR') ]
557# add the prefix/lib/pythonX.Y/config dir, but only if there is no
558# shared library in prefix/lib/.
559if not py_getvar('Py_ENABLE_SHARED'):
560    py_lib_path.append('-L' + py_getvar('LIBPL'))
561
562py_libs = []
563for lib in py_getvar('LIBS').split() + py_getvar('SYSLIBS').split():
564    if lib not in py_libs:
565        py_libs.append(lib)
566py_libs.append('-l' + py_version)
567
568env.Append(CPPPATH=py_includes)
569env.Append(LIBPATH=py_lib_path)
570
571# verify that this stuff works
572if not conf.CheckHeader('Python.h', '<>'):
573    print "Error: can't find Python.h header in", py_includes
574    Exit(1)
575
576for lib in py_libs:
577    assert lib.startswith('-l')
578    lib = lib[2:]
579    if not conf.CheckLib(lib):
580        print "Error: can't find library %s required by python" % lib
581        Exit(1)
582
583# On Solaris you need to use libsocket for socket ops
584if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
585   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
586       print "Can't find library with socket calls (e.g. accept())"
587       Exit(1)
588
589# Check for zlib.  If the check passes, libz will be automatically
590# added to the LIBS environment variable.
591if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
592    print 'Error: did not find needed zlib compression library '\
593          'and/or zlib.h header file.'
594    print '       Please install zlib and try again.'
595    Exit(1)
596
597# Check for <fenv.h> (C99 FP environment control)
598have_fenv = conf.CheckHeader('fenv.h', '<>')
599if not have_fenv:
600    print "Warning: Header file <fenv.h> not found."
601    print "         This host has no IEEE FP rounding mode control."
602
603######################################################################
604#
605# Check for mysql.
606#
607mysql_config = WhereIs('mysql_config')
608have_mysql = bool(mysql_config)
609
610# Check MySQL version.
611if have_mysql:
612    mysql_version = read_command(mysql_config + ' --version')
613    min_mysql_version = '4.1'
614    if compare_versions(mysql_version, min_mysql_version) < 0:
615        print 'Warning: MySQL', min_mysql_version, 'or newer required.'
616        print '         Version', mysql_version, 'detected.'
617        have_mysql = False
618
619# Set up mysql_config commands.
620if have_mysql:
621    mysql_config_include = mysql_config + ' --include'
622    if os.system(mysql_config_include + ' > /dev/null') != 0:
623        # older mysql_config versions don't support --include, use
624        # --cflags instead
625        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
626    # This seems to work in all versions
627    mysql_config_libs = mysql_config + ' --libs'
628
629######################################################################
630#
631# Finish the configuration
632#
633env = conf.Finish()
634
635######################################################################
636#
637# Collect all non-global variables
638#
639
640Export('env')
641
642# Define the universe of supported ISAs
643all_isa_list = [ ]
644Export('all_isa_list')
645
646# Define the universe of supported CPU models
647all_cpu_list = [ ]
648default_cpus = [ ]
649Export('all_cpu_list', 'default_cpus')
650
651# Sticky variables get saved in the variables file so they persist from
652# one invocation to the next (unless overridden, in which case the new
653# value becomes sticky).
654sticky_vars = Variables(args=ARGUMENTS)
655Export('sticky_vars')
656
657# Sticky variables that should be exported
658export_vars = []
659Export('export_vars')
660
661# Non-sticky variables only apply to the current build.
662nonsticky_vars = Variables(args=ARGUMENTS)
663Export('nonsticky_vars')
664
665# Walk the tree and execute all SConsopts scripts that wil add to the
666# above variables
667for bdir in [ base_dir ] + extras_dir_list:
668    for root, dirs, files in os.walk(bdir):
669        if 'SConsopts' in files:
670            print "Reading", joinpath(root, 'SConsopts')
671            SConscript(joinpath(root, 'SConsopts'))
672
673all_isa_list.sort()
674all_cpu_list.sort()
675default_cpus.sort()
676
677sticky_vars.AddVariables(
678    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
679    BoolVariable('FULL_SYSTEM', 'Full-system support', False),
680    ListVariable('CPU_MODELS', 'CPU models', default_cpus, all_cpu_list),
681    BoolVariable('NO_FAST_ALLOC', 'Disable fast object allocator', False),
682    BoolVariable('FAST_ALLOC_DEBUG', 'Enable fast object allocator debugging',
683                 False),
684    BoolVariable('FAST_ALLOC_STATS', 'Enable fast object allocator statistics',
685                 False),
686    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
687                 False),
688    BoolVariable('SS_COMPATIBLE_FP',
689                 'Make floating-point results compatible with SimpleScalar',
690                 False),
691    BoolVariable('USE_SSE2',
692                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
693                 False),
694    BoolVariable('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
695    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
696    BoolVariable('USE_CHECKER', 'Use checker for detailed CPU models', False),
697    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
698    )
699
700nonsticky_vars.AddVariables(
701    BoolVariable('update_ref', 'Update test reference outputs', False)
702    )
703
704# These variables get exported to #defines in config/*.hh (see src/SConscript).
705export_vars += ['FULL_SYSTEM', 'USE_FENV', 'USE_MYSQL',
706                'NO_FAST_ALLOC', 'FAST_ALLOC_DEBUG', 'FAST_ALLOC_STATS',
707                'SS_COMPATIBLE_FP', 'USE_CHECKER', 'TARGET_ISA', 'CP_ANNOTATE']
708
709###################################################
710#
711# Define a SCons builder for configuration flag headers.
712#
713###################################################
714
715# This function generates a config header file that #defines the
716# variable symbol to the current variable setting (0 or 1).  The source
717# operands are the name of the variable and a Value node containing the
718# value of the variable.
719def build_config_file(target, source, env):
720    (variable, value) = [s.get_contents() for s in source]
721    f = file(str(target[0]), 'w')
722    print >> f, '#define', variable, value
723    f.close()
724    return None
725
726# Generate the message to be printed when building the config file.
727def build_config_file_string(target, source, env):
728    (variable, value) = [s.get_contents() for s in source]
729    return "Defining %s as %s in %s." % (variable, value, target[0])
730
731# Combine the two functions into a scons Action object.
732config_action = Action(build_config_file, build_config_file_string)
733
734# The emitter munges the source & target node lists to reflect what
735# we're really doing.
736def config_emitter(target, source, env):
737    # extract variable name from Builder arg
738    variable = str(target[0])
739    # True target is config header file
740    target = joinpath('config', variable.lower() + '.hh')
741    val = env[variable]
742    if isinstance(val, bool):
743        # Force value to 0/1
744        val = int(val)
745    elif isinstance(val, str):
746        val = '"' + val + '"'
747
748    # Sources are variable name & value (packaged in SCons Value nodes)
749    return ([target], [Value(variable), Value(val)])
750
751config_builder = Builder(emitter = config_emitter, action = config_action)
752
753env.Append(BUILDERS = { 'ConfigFile' : config_builder })
754
755# libelf build is shared across all configs in the build root.
756env.SConscript('ext/libelf/SConscript',
757               variant_dir = joinpath(build_root, 'libelf'))
758
759# gzstream build is shared across all configs in the build root.
760env.SConscript('ext/gzstream/SConscript',
761               variant_dir = joinpath(build_root, 'gzstream'))
762
763###################################################
764#
765# This function is used to set up a directory with switching headers
766#
767###################################################
768
769env['ALL_ISA_LIST'] = all_isa_list
770def make_switching_dir(dname, switch_headers, env):
771    # Generate the header.  target[0] is the full path of the output
772    # header to generate.  'source' is a dummy variable, since we get the
773    # list of ISAs from env['ALL_ISA_LIST'].
774    def gen_switch_hdr(target, source, env):
775        fname = str(target[0])
776        bname = basename(fname)
777        f = open(fname, 'w')
778        f.write('#include "arch/isa_specific.hh"\n')
779        cond = '#if'
780        for isa in all_isa_list:
781            f.write('%s THE_ISA == %s_ISA\n#include "%s/%s/%s"\n'
782                    % (cond, isa.upper(), dname, isa, bname))
783            cond = '#elif'
784        f.write('#else\n#error "THE_ISA not set"\n#endif\n')
785        f.close()
786        return 0
787
788    # String to print when generating header
789    def gen_switch_hdr_string(target, source, env):
790        return "Generating switch header " + str(target[0])
791
792    # Build SCons Action object. 'varlist' specifies env vars that this
793    # action depends on; when env['ALL_ISA_LIST'] changes these actions
794    # should get re-executed.
795    switch_hdr_action = Action(gen_switch_hdr, gen_switch_hdr_string,
796                               varlist=['ALL_ISA_LIST'])
797
798    # Instantiate actions for each header
799    for hdr in switch_headers:
800        env.Command(hdr, [], switch_hdr_action)
801Export('make_switching_dir')
802
803###################################################
804#
805# Define build environments for selected configurations.
806#
807###################################################
808
809# rename base env
810base_env = env
811
812for variant_path in variant_paths:
813    print "Building in", variant_path
814
815    # Make a copy of the build-root environment to use for this config.
816    env = base_env.Clone()
817    env['BUILDDIR'] = variant_path
818
819    # variant_dir is the tail component of build path, and is used to
820    # determine the build parameters (e.g., 'ALPHA_SE')
821    (build_root, variant_dir) = splitpath(variant_path)
822
823    # Set env variables according to the build directory config.
824    sticky_vars.files = []
825    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
826    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
827    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
828    current_vars_file = joinpath(build_root, 'variables', variant_dir)
829    if isfile(current_vars_file):
830        sticky_vars.files.append(current_vars_file)
831        print "Using saved variables file %s" % current_vars_file
832    else:
833        # Build dir-specific variables file doesn't exist.
834
835        # Make sure the directory is there so we can create it later
836        opt_dir = dirname(current_vars_file)
837        if not isdir(opt_dir):
838            mkdir(opt_dir)
839
840        # Get default build variables from source tree.  Variables are
841        # normally determined by name of $VARIANT_DIR, but can be
842        # overriden by 'default=' arg on command line.
843        default_vars_file = joinpath('build_opts',
844                                     ARGUMENTS.get('default', variant_dir))
845        if isfile(default_vars_file):
846            sticky_vars.files.append(default_vars_file)
847            print "Variables file %s not found,\n  using defaults in %s" \
848                  % (current_vars_file, default_vars_file)
849        else:
850            print "Error: cannot find variables file %s or %s" \
851                  % (current_vars_file, default_vars_file)
852            Exit(1)
853
854    # Apply current variable settings to env
855    sticky_vars.Update(env)
856    nonsticky_vars.Update(env)
857
858    help_text += "\nSticky variables for %s:\n" % variant_dir \
859                 + sticky_vars.GenerateHelpText(env) \
860                 + "\nNon-sticky variables for %s:\n" % variant_dir \
861                 + nonsticky_vars.GenerateHelpText(env)
862
863    # Process variable settings.
864
865    if not have_fenv and env['USE_FENV']:
866        print "Warning: <fenv.h> not available; " \
867              "forcing USE_FENV to False in", variant_dir + "."
868        env['USE_FENV'] = False
869
870    if not env['USE_FENV']:
871        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
872        print "         FP results may deviate slightly from other platforms."
873
874    if env['EFENCE']:
875        env.Append(LIBS=['efence'])
876
877    if env['USE_MYSQL']:
878        if not have_mysql:
879            print "Warning: MySQL not available; " \
880                  "forcing USE_MYSQL to False in", variant_dir + "."
881            env['USE_MYSQL'] = False
882        else:
883            print "Compiling in", variant_dir, "with MySQL support."
884            env.ParseConfig(mysql_config_libs)
885            env.ParseConfig(mysql_config_include)
886
887    # Save sticky variable settings back to current variables file
888    sticky_vars.Save(current_vars_file, env)
889
890    if env['USE_SSE2']:
891        env.Append(CCFLAGS='-msse2')
892
893    # The src/SConscript file sets up the build rules in 'env' according
894    # to the configured variables.  It returns a list of environments,
895    # one for each variant build (debug, opt, etc.)
896    envList = SConscript('src/SConscript', variant_dir = variant_path,
897                         exports = 'env')
898
899    # Set up the regression tests for each build.
900    for e in envList:
901        SConscript('tests/SConscript',
902                   variant_dir = joinpath(variant_path, 'tests', e.Label),
903                   exports = { 'env' : e }, duplicate = False)
904
905Help(help_text)
906