SConstruct revision 9419
1955SN/A# -*- mode:python -*-
2955SN/A
39812Sandreas.hansson@arm.com# Copyright (c) 2011 Advanced Micro Devices, Inc.
49812Sandreas.hansson@arm.com# Copyright (c) 2009 The Hewlett-Packard Development Company
59812Sandreas.hansson@arm.com# Copyright (c) 2004-2005 The Regents of The University of Michigan
69812Sandreas.hansson@arm.com# All rights reserved.
79812Sandreas.hansson@arm.com#
89812Sandreas.hansson@arm.com# Redistribution and use in source and binary forms, with or without
99812Sandreas.hansson@arm.com# modification, are permitted provided that the following conditions are
109812Sandreas.hansson@arm.com# met: redistributions of source code must retain the above copyright
119812Sandreas.hansson@arm.com# notice, this list of conditions and the following disclaimer;
129812Sandreas.hansson@arm.com# redistributions in binary form must reproduce the above copyright
139812Sandreas.hansson@arm.com# notice, this list of conditions and the following disclaimer in the
149812Sandreas.hansson@arm.com# documentation and/or other materials provided with the distribution;
157816Ssteve.reinhardt@amd.com# neither the name of the copyright holders nor the names of its
165871Snate@binkert.org# contributors may be used to endorse or promote products derived from
171762SN/A# this software without specific prior written permission.
18955SN/A#
19955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30955SN/A#
31955SN/A# Authors: Steve Reinhardt
32955SN/A#          Nathan Binkert
33955SN/A
34955SN/A###################################################
35955SN/A#
36955SN/A# SCons top-level build description (SConstruct) file.
37955SN/A#
38955SN/A# While in this directory ('gem5'), just type 'scons' to build the default
39955SN/A# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
40955SN/A# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
41955SN/A# the optimized full-system version).
422665Ssaidi@eecs.umich.edu#
432665Ssaidi@eecs.umich.edu# You can build gem5 in a different directory as long as there is a
445863Snate@binkert.org# 'build/<CONFIG>' somewhere along the target path.  The build system
45955SN/A# expects that all configs under the same build directory are being
46955SN/A# built for the same host system.
47955SN/A#
48955SN/A# Examples:
49955SN/A#
508878Ssteve.reinhardt@amd.com#   The following two commands are equivalent.  The '-u' option tells
512632Sstever@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
528878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
532632Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
54955SN/A#
558878Ssteve.reinhardt@amd.com#   The following two commands are equivalent and demonstrate building
562632Sstever@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
572761Sstever@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
582632Sstever@eecs.umich.edu#   file.
592632Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
602632Sstever@eecs.umich.edu#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
612761Sstever@eecs.umich.edu#
622761Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
632761Sstever@eecs.umich.edu# 'gem5' directory (or use -u or -C to tell scons where to find this
648878Ssteve.reinhardt@amd.com# file), you can use 'scons -h' to print all the gem5-specific build
658878Ssteve.reinhardt@amd.com# options as well.
662761Sstever@eecs.umich.edu#
672761Sstever@eecs.umich.edu###################################################
682761Sstever@eecs.umich.edu
692761Sstever@eecs.umich.edu# Check for recent-enough Python and SCons versions.
702761Sstever@eecs.umich.edutry:
718878Ssteve.reinhardt@amd.com    # Really old versions of scons only take two options for the
728878Ssteve.reinhardt@amd.com    # function, so check once without the revision and once with the
732632Sstever@eecs.umich.edu    # revision, the first instance will fail for stuff other than
742632Sstever@eecs.umich.edu    # 0.98, and the second will fail for 0.98.0
758878Ssteve.reinhardt@amd.com    EnsureSConsVersion(0, 98)
768878Ssteve.reinhardt@amd.com    EnsureSConsVersion(0, 98, 1)
772632Sstever@eecs.umich.eduexcept SystemExit, e:
78955SN/A    print """
79955SN/AFor more details, see:
80955SN/A    http://gem5.org/Dependencies
815863Snate@binkert.org"""
825863Snate@binkert.org    raise
835863Snate@binkert.org
845863Snate@binkert.org# We ensure the python version early because we have stuff that
855863Snate@binkert.org# requires python 2.4
865863Snate@binkert.orgtry:
875863Snate@binkert.org    EnsurePythonVersion(2, 4)
885863Snate@binkert.orgexcept SystemExit, e:
895863Snate@binkert.org    print """
905863Snate@binkert.orgYou can use a non-default installation of the Python interpreter by
915863Snate@binkert.orgeither (1) rearranging your PATH so that scons finds the non-default
928878Ssteve.reinhardt@amd.com'python' first or (2) explicitly invoking an alternative interpreter
935863Snate@binkert.orgon the scons script.
945863Snate@binkert.org
955863Snate@binkert.orgFor more details, see:
969812Sandreas.hansson@arm.com    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
979812Sandreas.hansson@arm.com"""
985863Snate@binkert.org    raise
999812Sandreas.hansson@arm.com
1005863Snate@binkert.org# Global Python includes
1015863Snate@binkert.orgimport os
1025863Snate@binkert.orgimport re
1039812Sandreas.hansson@arm.comimport subprocess
1049812Sandreas.hansson@arm.comimport sys
1055863Snate@binkert.org
1065863Snate@binkert.orgfrom os import mkdir, environ
1078878Ssteve.reinhardt@amd.comfrom os.path import abspath, basename, dirname, expanduser, normpath
1085863Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1095863Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1105863Snate@binkert.org
1116654Snate@binkert.org# SCons includes
112955SN/Aimport SCons
1135396Ssaidi@eecs.umich.eduimport SCons.Node
1145863Snate@binkert.org
1155863Snate@binkert.orgextra_python_paths = [
1164202Sbinkertn@umich.edu    Dir('src/python').srcnode().abspath, # gem5 includes
1175863Snate@binkert.org    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1185863Snate@binkert.org    ]
1195863Snate@binkert.org
1205863Snate@binkert.orgsys.path[1:1] = extra_python_paths
121955SN/A
1226654Snate@binkert.orgfrom m5.util import compareVersions, readCommand
1235273Sstever@gmail.comfrom m5.util.terminal import get_termcap
1245871Snate@binkert.org
1255273Sstever@gmail.comhelp_texts = {
1266655Snate@binkert.org    "options" : "",
1278878Ssteve.reinhardt@amd.com    "global_vars" : "",
1286655Snate@binkert.org    "local_vars" : ""
1296655Snate@binkert.org}
1309219Spower.jg@gmail.com
1316655Snate@binkert.orgExport("help_texts")
1325871Snate@binkert.org
1336654Snate@binkert.org
1348947Sandreas.hansson@arm.com# There's a bug in scons in that (1) by default, the help texts from
1355396Ssaidi@eecs.umich.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1368120Sgblack@eecs.umich.edu# and (2) you can override the help displayed by 'scons -h' using the
1378120Sgblack@eecs.umich.edu# Help() function, but these two features are incompatible: once
1388120Sgblack@eecs.umich.edu# you've overridden the help text using Help(), there's no way to get
1398120Sgblack@eecs.umich.edu# at the help texts from AddOptions.  See:
1408120Sgblack@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1418120Sgblack@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1428120Sgblack@eecs.umich.edu# This hack lets us extract the help text from AddOptions and
1438120Sgblack@eecs.umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1448879Ssteve.reinhardt@amd.com# we can just use AddOption directly.
1458879Ssteve.reinhardt@amd.comdef AddLocalOption(*args, **kwargs):
1468879Ssteve.reinhardt@amd.com    col_width = 30
1478879Ssteve.reinhardt@amd.com
1488879Ssteve.reinhardt@amd.com    help = "  " + ", ".join(args)
1498879Ssteve.reinhardt@amd.com    if "help" in kwargs:
1508879Ssteve.reinhardt@amd.com        length = len(help)
1518879Ssteve.reinhardt@amd.com        if length >= col_width:
1528879Ssteve.reinhardt@amd.com            help += "\n" + " " * col_width
1538879Ssteve.reinhardt@amd.com        else:
1548879Ssteve.reinhardt@amd.com            help += " " * (col_width - length)
1558879Ssteve.reinhardt@amd.com        help += kwargs["help"]
1568879Ssteve.reinhardt@amd.com    help_texts["options"] += help + "\n"
1578120Sgblack@eecs.umich.edu
1588120Sgblack@eecs.umich.edu    AddOption(*args, **kwargs)
1598120Sgblack@eecs.umich.edu
1608120Sgblack@eecs.umich.eduAddLocalOption('--colors', dest='use_colors', action='store_true',
1618120Sgblack@eecs.umich.edu               help="Add color to abbreviated scons output")
1628120Sgblack@eecs.umich.eduAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1638120Sgblack@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1648120Sgblack@eecs.umich.eduAddLocalOption('--default', dest='default', type='string', action='store',
1658120Sgblack@eecs.umich.edu               help='Override which build_opts file to use for defaults')
1668120Sgblack@eecs.umich.eduAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1678120Sgblack@eecs.umich.edu               help='Disable style checking hooks')
1688120Sgblack@eecs.umich.eduAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1698120Sgblack@eecs.umich.edu               help='Disable Link-Time Optimization for fast')
1708120Sgblack@eecs.umich.eduAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1718879Ssteve.reinhardt@amd.com               help='Update test reference outputs')
1728879Ssteve.reinhardt@amd.comAddLocalOption('--verbose', dest='verbose', action='store_true',
1738879Ssteve.reinhardt@amd.com               help='Print full tool command lines')
1748879Ssteve.reinhardt@amd.com
1758879Ssteve.reinhardt@amd.comtermcap = get_termcap(GetOption('use_colors'))
1768879Ssteve.reinhardt@amd.com
1778879Ssteve.reinhardt@amd.com########################################################################
1788879Ssteve.reinhardt@amd.com#
1799227Sandreas.hansson@arm.com# Set up the main build environment.
1809227Sandreas.hansson@arm.com#
1818879Ssteve.reinhardt@amd.com########################################################################
1828879Ssteve.reinhardt@amd.comuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
1838879Ssteve.reinhardt@amd.com                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PYTHONPATH',
1848879Ssteve.reinhardt@amd.com                 'RANLIB', 'SWIG' ])
1858120Sgblack@eecs.umich.edu
1868947Sandreas.hansson@arm.comuse_prefixes = [
1877816Ssteve.reinhardt@amd.com    "M5",           # M5 configuration (e.g., path to kernels)
1885871Snate@binkert.org    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
1895871Snate@binkert.org    "CCACHE_",      # ccache (caching compiler wrapper) configuration
1906121Snate@binkert.org    "CCC_",         # clang static analyzer configuration
1915871Snate@binkert.org    ]
1925871Snate@binkert.org
1939119Sandreas.hansson@arm.comuse_env = {}
1949396Sandreas.hansson@arm.comfor key,val in os.environ.iteritems():
1959396Sandreas.hansson@arm.com    if key in use_vars or \
196955SN/A            any([key.startswith(prefix) for prefix in use_prefixes]):
1979416SAndreas.Sandberg@ARM.com        use_env[key] = val
1989416SAndreas.Sandberg@ARM.com
1999416SAndreas.Sandberg@ARM.commain = Environment(ENV=use_env)
2009416SAndreas.Sandberg@ARM.commain.Decider('MD5-timestamp')
2019416SAndreas.Sandberg@ARM.commain.root = Dir(".")         # The current directory (where this file lives).
2029416SAndreas.Sandberg@ARM.commain.srcdir = Dir("src")     # The source directory
2039416SAndreas.Sandberg@ARM.com
2045871Snate@binkert.orgmain_dict_keys = main.Dictionary().keys()
2055871Snate@binkert.org
2069416SAndreas.Sandberg@ARM.com# Check that we have a C/C++ compiler
2079416SAndreas.Sandberg@ARM.comif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2085871Snate@binkert.org    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
209955SN/A    Exit(1)
2106121Snate@binkert.org
2118881Smarc.orr@gmail.com# Check that swig is present
2126121Snate@binkert.orgif not 'SWIG' in main_dict_keys:
2136121Snate@binkert.org    print "swig is not installed (package swig on Ubuntu and RedHat)"
2141533SN/A    Exit(1)
2159239Sandreas.hansson@arm.com
2169239Sandreas.hansson@arm.com# add useful python code PYTHONPATH so it can be used by subprocesses
2179239Sandreas.hansson@arm.com# as well
2189239Sandreas.hansson@arm.commain.AppendENVPath('PYTHONPATH', extra_python_paths)
2199239Sandreas.hansson@arm.com
2209239Sandreas.hansson@arm.com########################################################################
2219239Sandreas.hansson@arm.com#
2229239Sandreas.hansson@arm.com# Mercurial Stuff.
2239239Sandreas.hansson@arm.com#
2249239Sandreas.hansson@arm.com# If the gem5 directory is a mercurial repository, we should do some
2259239Sandreas.hansson@arm.com# extra things.
2269239Sandreas.hansson@arm.com#
2276655Snate@binkert.org########################################################################
2286655Snate@binkert.org
2296655Snate@binkert.orghgdir = main.root.Dir(".hg")
2306655Snate@binkert.org
2315871Snate@binkert.orgmercurial_style_message = """
2325871Snate@binkert.orgYou're missing the gem5 style hook, which automatically checks your code
2335863Snate@binkert.orgagainst the gem5 style rules on hg commit and qrefresh commands.  This
2345871Snate@binkert.orgscript will now install the hook in your .hg/hgrc file.
2358878Ssteve.reinhardt@amd.comPress enter to continue, or ctrl-c to abort: """
2365871Snate@binkert.org
2375871Snate@binkert.orgmercurial_style_hook = """
2385871Snate@binkert.org# The following lines were automatically added by gem5/SConstruct
2395863Snate@binkert.org# to provide the gem5 style-checking hooks
2406121Snate@binkert.org[extensions]
2415863Snate@binkert.orgstyle = %s/util/style.py
2425871Snate@binkert.org
2438336Ssteve.reinhardt@amd.com[hooks]
2448336Ssteve.reinhardt@amd.compretxncommit.style = python:style.check_style
2458336Ssteve.reinhardt@amd.compre-qrefresh.style = python:style.check_style
2468336Ssteve.reinhardt@amd.com# End of SConstruct additions
2474678Snate@binkert.org
2488336Ssteve.reinhardt@amd.com""" % (main.root.abspath)
2498336Ssteve.reinhardt@amd.com
2508336Ssteve.reinhardt@amd.commercurial_lib_not_found = """
2514678Snate@binkert.orgMercurial libraries cannot be found, ignoring style hook.  If
2524678Snate@binkert.orgyou are a gem5 developer, please fix this and run the style
2534678Snate@binkert.orghook. It is important.
2544678Snate@binkert.org"""
2557827Snate@binkert.org
2567827Snate@binkert.org# Check for style hook and prompt for installation if it's not there.
2578336Ssteve.reinhardt@amd.com# Skip this if --ignore-style was specified, there's no .hg dir to
2584678Snate@binkert.org# install a hook in, or there's no interactive terminal to prompt.
2598336Ssteve.reinhardt@amd.comif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2608336Ssteve.reinhardt@amd.com    style_hook = True
2618336Ssteve.reinhardt@amd.com    try:
2628336Ssteve.reinhardt@amd.com        from mercurial import ui
2638336Ssteve.reinhardt@amd.com        ui = ui.ui()
2648336Ssteve.reinhardt@amd.com        ui.readconfig(hgdir.File('hgrc').abspath)
2655871Snate@binkert.org        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2665871Snate@binkert.org                     ui.config('hooks', 'pre-qrefresh.style', None)
2678336Ssteve.reinhardt@amd.com    except ImportError:
2688336Ssteve.reinhardt@amd.com        print mercurial_lib_not_found
2698336Ssteve.reinhardt@amd.com
2708336Ssteve.reinhardt@amd.com    if not style_hook:
2718336Ssteve.reinhardt@amd.com        print mercurial_style_message,
2725871Snate@binkert.org        # continue unless user does ctrl-c/ctrl-d etc.
2738336Ssteve.reinhardt@amd.com        try:
2748336Ssteve.reinhardt@amd.com            raw_input()
2758336Ssteve.reinhardt@amd.com        except:
2768336Ssteve.reinhardt@amd.com            print "Input exception, exiting scons.\n"
2778336Ssteve.reinhardt@amd.com            sys.exit(1)
2784678Snate@binkert.org        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
2795871Snate@binkert.org        print "Adding style hook to", hgrc_path, "\n"
2804678Snate@binkert.org        try:
2818336Ssteve.reinhardt@amd.com            hgrc = open(hgrc_path, 'a')
2828336Ssteve.reinhardt@amd.com            hgrc.write(mercurial_style_hook)
2838336Ssteve.reinhardt@amd.com            hgrc.close()
2848336Ssteve.reinhardt@amd.com        except:
2858336Ssteve.reinhardt@amd.com            print "Error updating", hgrc_path
2868336Ssteve.reinhardt@amd.com            sys.exit(1)
2878336Ssteve.reinhardt@amd.com
2888336Ssteve.reinhardt@amd.com
2898336Ssteve.reinhardt@amd.com###################################################
2908336Ssteve.reinhardt@amd.com#
2918336Ssteve.reinhardt@amd.com# Figure out which configurations to set up based on the path(s) of
2928336Ssteve.reinhardt@amd.com# the target(s).
2938336Ssteve.reinhardt@amd.com#
2948336Ssteve.reinhardt@amd.com###################################################
2958336Ssteve.reinhardt@amd.com
2968336Ssteve.reinhardt@amd.com# Find default configuration & binary.
2978336Ssteve.reinhardt@amd.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
2985871Snate@binkert.org
2996121Snate@binkert.org# helper function: find last occurrence of element in list
300955SN/Adef rfind(l, elt, offs = -1):
301955SN/A    for i in range(len(l)+offs, 0, -1):
3022632Sstever@eecs.umich.edu        if l[i] == elt:
3032632Sstever@eecs.umich.edu            return i
304955SN/A    raise ValueError, "element not found"
305955SN/A
306955SN/A# Take a list of paths (or SCons Nodes) and return a list with all
307955SN/A# paths made absolute and ~-expanded.  Paths will be interpreted
3088878Ssteve.reinhardt@amd.com# relative to the launch directory unless a different root is provided
309955SN/Adef makePathListAbsolute(path_list, root=GetLaunchDir()):
3102632Sstever@eecs.umich.edu    return [abspath(joinpath(root, expanduser(str(p))))
3112632Sstever@eecs.umich.edu            for p in path_list]
3122632Sstever@eecs.umich.edu
3132632Sstever@eecs.umich.edu# Each target must have 'build' in the interior of the path; the
3142632Sstever@eecs.umich.edu# directory below this will determine the build parameters.  For
3152632Sstever@eecs.umich.edu# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3162632Sstever@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
3178268Ssteve.reinhardt@amd.com# follow 'build' in the build path.
3188268Ssteve.reinhardt@amd.com
3198268Ssteve.reinhardt@amd.com# The funky assignment to "[:]" is needed to replace the list contents
3208268Ssteve.reinhardt@amd.com# in place rather than reassign the symbol to a new list, which
3218268Ssteve.reinhardt@amd.com# doesn't work (obviously!).
3228268Ssteve.reinhardt@amd.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3238268Ssteve.reinhardt@amd.com
3242632Sstever@eecs.umich.edu# Generate a list of the unique build roots and configs that the
3252632Sstever@eecs.umich.edu# collected targets reference.
3262632Sstever@eecs.umich.eduvariant_paths = []
3272632Sstever@eecs.umich.edubuild_root = None
3288268Ssteve.reinhardt@amd.comfor t in BUILD_TARGETS:
3292632Sstever@eecs.umich.edu    path_dirs = t.split('/')
3308268Ssteve.reinhardt@amd.com    try:
3318268Ssteve.reinhardt@amd.com        build_top = rfind(path_dirs, 'build', -2)
3328268Ssteve.reinhardt@amd.com    except:
3338268Ssteve.reinhardt@amd.com        print "Error: no non-leaf 'build' dir found on target path", t
3343718Sstever@eecs.umich.edu        Exit(1)
3352634Sstever@eecs.umich.edu    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3362634Sstever@eecs.umich.edu    if not build_root:
3375863Snate@binkert.org        build_root = this_build_root
3382638Sstever@eecs.umich.edu    else:
3398268Ssteve.reinhardt@amd.com        if this_build_root != build_root:
3402632Sstever@eecs.umich.edu            print "Error: build targets not under same build root\n"\
3412632Sstever@eecs.umich.edu                  "  %s\n  %s" % (build_root, this_build_root)
3422632Sstever@eecs.umich.edu            Exit(1)
3432632Sstever@eecs.umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
3442632Sstever@eecs.umich.edu    if variant_path not in variant_paths:
3451858SN/A        variant_paths.append(variant_path)
3463716Sstever@eecs.umich.edu
3472638Sstever@eecs.umich.edu# Make sure build_root exists (might not if this is the first build there)
3482638Sstever@eecs.umich.eduif not isdir(build_root):
3492638Sstever@eecs.umich.edu    mkdir(build_root)
3502638Sstever@eecs.umich.edumain['BUILDROOT'] = build_root
3512638Sstever@eecs.umich.edu
3522638Sstever@eecs.umich.eduExport('main')
3532638Sstever@eecs.umich.edu
3545863Snate@binkert.orgmain.SConsignFile(joinpath(build_root, "sconsign"))
3555863Snate@binkert.org
3565863Snate@binkert.org# Default duplicate option is to use hard links, but this messes up
357955SN/A# when you use emacs to edit a file in the target dir, as emacs moves
3585341Sstever@gmail.com# file to file~ then copies to file, breaking the link.  Symbolic
3595341Sstever@gmail.com# (soft) links work better.
3605863Snate@binkert.orgmain.SetOption('duplicate', 'soft-copy')
3617756SAli.Saidi@ARM.com
3625341Sstever@gmail.com#
3636121Snate@binkert.org# Set up global sticky variables... these are common to an entire build
3644494Ssaidi@eecs.umich.edu# tree (not specific to a particular build like ALPHA_SE)
3656121Snate@binkert.org#
3661105SN/A
3672667Sstever@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
3682667Sstever@eecs.umich.edu
3692667Sstever@eecs.umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3702667Sstever@eecs.umich.edu
3716121Snate@binkert.orgglobal_vars.AddVariables(
3722667Sstever@eecs.umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3735341Sstever@gmail.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3745863Snate@binkert.org    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
3755341Sstever@gmail.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
3765341Sstever@gmail.com    ('BATCH', 'Use batch pool for build and tests', False),
3775341Sstever@gmail.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3788120Sgblack@eecs.umich.edu    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
3795341Sstever@gmail.com    ('EXTRAS', 'Add extra directories to the compilation', '')
3808120Sgblack@eecs.umich.edu    )
3815341Sstever@gmail.com
3828120Sgblack@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
3836121Snate@binkert.orgglobal_vars.Update(main)
3846121Snate@binkert.orghelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3858980Ssteve.reinhardt@amd.com
3869396Sandreas.hansson@arm.com# Save sticky variable settings back to current variables file
3875397Ssaidi@eecs.umich.eduglobal_vars.Save(global_vars_file, main)
3885397Ssaidi@eecs.umich.edu
3897727SAli.Saidi@ARM.com# Parse EXTRAS variable to build list of all directories where we're
3908268Ssteve.reinhardt@amd.com# look for sources etc.  This list is exported as extras_dir_list.
3916168Snate@binkert.orgbase_dir = main.srcdir.abspath
3925341Sstever@gmail.comif main['EXTRAS']:
3938120Sgblack@eecs.umich.edu    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
3948120Sgblack@eecs.umich.eduelse:
3958120Sgblack@eecs.umich.edu    extras_dir_list = []
3966814Sgblack@eecs.umich.edu
3975863Snate@binkert.orgExport('base_dir')
3988120Sgblack@eecs.umich.eduExport('extras_dir_list')
3995341Sstever@gmail.com
4005863Snate@binkert.org# the ext directory should be on the #includes path
4018268Ssteve.reinhardt@amd.commain.Append(CPPPATH=[Dir('ext')])
4026121Snate@binkert.org
4036121Snate@binkert.orgdef strip_build_path(path, env):
4048268Ssteve.reinhardt@amd.com    path = str(path)
4055742Snate@binkert.org    variant_base = env['BUILDROOT'] + os.path.sep
4065742Snate@binkert.org    if path.startswith(variant_base):
4075341Sstever@gmail.com        path = path[len(variant_base):]
4085742Snate@binkert.org    elif path.startswith('build/'):
4095742Snate@binkert.org        path = path[6:]
4105341Sstever@gmail.com    return path
4116017Snate@binkert.org
4126121Snate@binkert.org# Generate a string of the form:
4136017Snate@binkert.org#   common/path/prefix/src1, src2 -> tgt1, tgt2
4147816Ssteve.reinhardt@amd.com# to print while building.
4157756SAli.Saidi@ARM.comclass Transform(object):
4167756SAli.Saidi@ARM.com    # all specific color settings should be here and nowhere else
4177756SAli.Saidi@ARM.com    tool_color = termcap.Normal
4187756SAli.Saidi@ARM.com    pfx_color = termcap.Yellow
4197756SAli.Saidi@ARM.com    srcs_color = termcap.Yellow + termcap.Bold
4207756SAli.Saidi@ARM.com    arrow_color = termcap.Blue + termcap.Bold
4217756SAli.Saidi@ARM.com    tgts_color = termcap.Yellow + termcap.Bold
4227756SAli.Saidi@ARM.com
4237816Ssteve.reinhardt@amd.com    def __init__(self, tool, max_sources=99):
4247816Ssteve.reinhardt@amd.com        self.format = self.tool_color + (" [%8s] " % tool) \
4257816Ssteve.reinhardt@amd.com                      + self.pfx_color + "%s" \
4267816Ssteve.reinhardt@amd.com                      + self.srcs_color + "%s" \
4277816Ssteve.reinhardt@amd.com                      + self.arrow_color + " -> " \
4287816Ssteve.reinhardt@amd.com                      + self.tgts_color + "%s" \
4297816Ssteve.reinhardt@amd.com                      + termcap.Normal
4307816Ssteve.reinhardt@amd.com        self.max_sources = max_sources
4317816Ssteve.reinhardt@amd.com
4327816Ssteve.reinhardt@amd.com    def __call__(self, target, source, env, for_signature=None):
4337756SAli.Saidi@ARM.com        # truncate source list according to max_sources param
4347816Ssteve.reinhardt@amd.com        source = source[0:self.max_sources]
4357816Ssteve.reinhardt@amd.com        def strip(f):
4367816Ssteve.reinhardt@amd.com            return strip_build_path(str(f), env)
4377816Ssteve.reinhardt@amd.com        if len(source) > 0:
4387816Ssteve.reinhardt@amd.com            srcs = map(strip, source)
4397816Ssteve.reinhardt@amd.com        else:
4407816Ssteve.reinhardt@amd.com            srcs = ['']
4417816Ssteve.reinhardt@amd.com        tgts = map(strip, target)
4427816Ssteve.reinhardt@amd.com        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4437816Ssteve.reinhardt@amd.com        # operation that has nothing to do with paths.
4447816Ssteve.reinhardt@amd.com        com_pfx = os.path.commonprefix(srcs + tgts)
4457816Ssteve.reinhardt@amd.com        com_pfx_len = len(com_pfx)
4467816Ssteve.reinhardt@amd.com        if com_pfx:
4477816Ssteve.reinhardt@amd.com            # do some cleanup and sanity checking on common prefix
4487816Ssteve.reinhardt@amd.com            if com_pfx[-1] == ".":
4497816Ssteve.reinhardt@amd.com                # prefix matches all but file extension: ok
4507816Ssteve.reinhardt@amd.com                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4517816Ssteve.reinhardt@amd.com                com_pfx = com_pfx[0:-1]
4527816Ssteve.reinhardt@amd.com            elif com_pfx[-1] == "/":
4537816Ssteve.reinhardt@amd.com                # common prefix is directory path: OK
4547816Ssteve.reinhardt@amd.com                pass
4557816Ssteve.reinhardt@amd.com            else:
4567816Ssteve.reinhardt@amd.com                src0_len = len(srcs[0])
4577816Ssteve.reinhardt@amd.com                tgt0_len = len(tgts[0])
4587816Ssteve.reinhardt@amd.com                if src0_len == com_pfx_len:
4597816Ssteve.reinhardt@amd.com                    # source is a substring of target, OK
4607816Ssteve.reinhardt@amd.com                    pass
4617816Ssteve.reinhardt@amd.com                elif tgt0_len == com_pfx_len:
4627816Ssteve.reinhardt@amd.com                    # target is a substring of source, need to back up to
4637816Ssteve.reinhardt@amd.com                    # avoid empty string on RHS of arrow
4647816Ssteve.reinhardt@amd.com                    sep_idx = com_pfx.rfind(".")
4657816Ssteve.reinhardt@amd.com                    if sep_idx != -1:
4667816Ssteve.reinhardt@amd.com                        com_pfx = com_pfx[0:sep_idx]
4677816Ssteve.reinhardt@amd.com                    else:
4687816Ssteve.reinhardt@amd.com                        com_pfx = ''
4697816Ssteve.reinhardt@amd.com                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4707816Ssteve.reinhardt@amd.com                    # still splitting at file extension: ok
4717816Ssteve.reinhardt@amd.com                    pass
4727816Ssteve.reinhardt@amd.com                else:
4737816Ssteve.reinhardt@amd.com                    # probably a fluke; ignore it
4747816Ssteve.reinhardt@amd.com                    com_pfx = ''
4757816Ssteve.reinhardt@amd.com        # recalculate length in case com_pfx was modified
4767816Ssteve.reinhardt@amd.com        com_pfx_len = len(com_pfx)
4777816Ssteve.reinhardt@amd.com        def fmt(files):
4787816Ssteve.reinhardt@amd.com            f = map(lambda s: s[com_pfx_len:], files)
4797816Ssteve.reinhardt@amd.com            return ', '.join(f)
4807816Ssteve.reinhardt@amd.com        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
4817816Ssteve.reinhardt@amd.com
4827816Ssteve.reinhardt@amd.comExport('Transform')
4837816Ssteve.reinhardt@amd.com
4847816Ssteve.reinhardt@amd.com# enable the regression script to use the termcap
4857816Ssteve.reinhardt@amd.commain['TERMCAP'] = termcap
4867816Ssteve.reinhardt@amd.com
4877816Ssteve.reinhardt@amd.comif GetOption('verbose'):
4887816Ssteve.reinhardt@amd.com    def MakeAction(action, string, *args, **kwargs):
4897816Ssteve.reinhardt@amd.com        return Action(action, *args, **kwargs)
4907816Ssteve.reinhardt@amd.comelse:
4917816Ssteve.reinhardt@amd.com    MakeAction = Action
4927816Ssteve.reinhardt@amd.com    main['CCCOMSTR']        = Transform("CC")
4937816Ssteve.reinhardt@amd.com    main['CXXCOMSTR']       = Transform("CXX")
4947816Ssteve.reinhardt@amd.com    main['ASCOMSTR']        = Transform("AS")
4958947Sandreas.hansson@arm.com    main['SWIGCOMSTR']      = Transform("SWIG")
4968947Sandreas.hansson@arm.com    main['ARCOMSTR']        = Transform("AR", 0)
4977756SAli.Saidi@ARM.com    main['LINKCOMSTR']      = Transform("LINK", 0)
4988120Sgblack@eecs.umich.edu    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
4997756SAli.Saidi@ARM.com    main['M4COMSTR']        = Transform("M4")
5007756SAli.Saidi@ARM.com    main['SHCCCOMSTR']      = Transform("SHCC")
5017756SAli.Saidi@ARM.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
5027756SAli.Saidi@ARM.comExport('MakeAction')
5037816Ssteve.reinhardt@amd.com
5047816Ssteve.reinhardt@amd.com# Initialize the Link-Time Optimization (LTO) flags
5057816Ssteve.reinhardt@amd.commain['LTO_CCFLAGS'] = []
5067816Ssteve.reinhardt@amd.commain['LTO_LDFLAGS'] = []
5077816Ssteve.reinhardt@amd.com
5087816Ssteve.reinhardt@amd.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5097816Ssteve.reinhardt@amd.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5107816Ssteve.reinhardt@amd.com
5117816Ssteve.reinhardt@amd.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5127816Ssteve.reinhardt@amd.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5137756SAli.Saidi@ARM.comif main['GCC'] + main['CLANG'] > 1:
5147756SAli.Saidi@ARM.com    print 'Error: How can we have two at the same time?'
5159227Sandreas.hansson@arm.com    Exit(1)
5169227Sandreas.hansson@arm.com
5179227Sandreas.hansson@arm.com# Set up default C++ compiler flags
5189227Sandreas.hansson@arm.comif main['GCC']:
5199590Sandreas@sandberg.pp.se    main.Append(CCFLAGS=['-pipe'])
5209590Sandreas@sandberg.pp.se    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5219590Sandreas@sandberg.pp.se    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5229590Sandreas@sandberg.pp.se    # Read the GCC version to check for versions with bugs
5239590Sandreas@sandberg.pp.se    # Note CCVERSION doesn't work here because it is run with the CC
5249590Sandreas@sandberg.pp.se    # before we override it from the command line
5256654Snate@binkert.org    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5266654Snate@binkert.org    main['GCC_VERSION'] = gcc_version
5275871Snate@binkert.org    if not compareVersions(gcc_version, '4.4.1') or \
5286121Snate@binkert.org       not compareVersions(gcc_version, '4.4.2'):
5298946Sandreas.hansson@arm.com        print 'Info: Tree vectorizer in GCC 4.4.1 & 4.4.2 is buggy, disabling.'
5309419Sandreas.hansson@arm.com        main.Append(CCFLAGS=['-fno-tree-vectorize'])
5313940Ssaidi@eecs.umich.edu    # c++0x support in gcc is useful already from 4.4, see
5323918Ssaidi@eecs.umich.edu    # http://gcc.gnu.org/projects/cxx0x.html for details
5333918Ssaidi@eecs.umich.edu    if compareVersions(gcc_version, '4.4') >= 0:
5341858SN/A        main.Append(CXXFLAGS=['-std=c++0x'])
5359556Sandreas.hansson@arm.com
5369556Sandreas.hansson@arm.com    # LTO support is only really working properly from 4.6 and beyond
5379556Sandreas.hansson@arm.com    if compareVersions(gcc_version, '4.6') >= 0:
5389556Sandreas.hansson@arm.com        # Add the appropriate Link-Time Optimization (LTO) flags
5399556Sandreas.hansson@arm.com        # unless LTO is explicitly turned off. Note that these flags
5409556Sandreas.hansson@arm.com        # are only used by the fast target.
5419556Sandreas.hansson@arm.com        if not GetOption('no_lto'):
5429556Sandreas.hansson@arm.com            # Pass the LTO flag when compiling to produce GIMPLE
5439556Sandreas.hansson@arm.com            # output, we merely create the flags here and only append
5449556Sandreas.hansson@arm.com            # them later/
5459556Sandreas.hansson@arm.com            main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
5469556Sandreas.hansson@arm.com
5479556Sandreas.hansson@arm.com            # Use the same amount of jobs for LTO as we are running
5489556Sandreas.hansson@arm.com            # scons with, we hardcode the use of the linker plugin
5499556Sandreas.hansson@arm.com            # which requires either gold or GNU ld >= 2.21
5509556Sandreas.hansson@arm.com            main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs'),
5519556Sandreas.hansson@arm.com                                   '-fuse-linker-plugin']
5529556Sandreas.hansson@arm.com
5539556Sandreas.hansson@arm.comelif main['CLANG']:
5549556Sandreas.hansson@arm.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
5559556Sandreas.hansson@arm.com    clang_version_match = clang_version_re.match(CXX_version)
5569556Sandreas.hansson@arm.com    if (clang_version_match):
5579556Sandreas.hansson@arm.com        clang_version = clang_version_match.groups()[0]
5589556Sandreas.hansson@arm.com        if compareVersions(clang_version, "2.9") < 0:
5599556Sandreas.hansson@arm.com            print 'Error: clang version 2.9 or newer required.'
5609556Sandreas.hansson@arm.com            print '       Installed version:', clang_version
5619556Sandreas.hansson@arm.com            Exit(1)
5629556Sandreas.hansson@arm.com    else:
5639556Sandreas.hansson@arm.com        print 'Error: Unable to determine clang version.'
5649556Sandreas.hansson@arm.com        Exit(1)
5659556Sandreas.hansson@arm.com
5669556Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-pipe'])
5676121Snate@binkert.org    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5689420Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5699420Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-Wno-tautological-compare'])
5709420Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-Wno-self-assign'])
5719420Sandreas.hansson@arm.com    # Ruby makes frequent use of extraneous parantheses in the printing
5729420Sandreas.hansson@arm.com    # of if-statements
5739420Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-Wno-parentheses'])
5749420Sandreas.hansson@arm.com
5759420Sandreas.hansson@arm.com    # clang 2.9 does not play well with c++0x as it ships with C++
5769420Sandreas.hansson@arm.com    # headers that produce errors, this was fixed in 3.0
5779420Sandreas.hansson@arm.com    if compareVersions(clang_version, "3") >= 0:
5789420Sandreas.hansson@arm.com        main.Append(CXXFLAGS=['-std=c++0x'])
5797618SAli.Saidi@arm.comelse:
5807618SAli.Saidi@arm.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5817618SAli.Saidi@arm.com    print "Don't know what compiler options to use for your compiler."
5827739Sgblack@eecs.umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5839227Sandreas.hansson@arm.com    print termcap.Yellow + '       version:' + termcap.Normal,
5849227Sandreas.hansson@arm.com    if not CXX_version:
5859227Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5869227Sandreas.hansson@arm.com               termcap.Normal
5879227Sandreas.hansson@arm.com    else:
5889227Sandreas.hansson@arm.com        print CXX_version.replace('\n', '<nl>')
5899227Sandreas.hansson@arm.com    print "       If you're trying to use a compiler other than GCC"
5909227Sandreas.hansson@arm.com    print "       or clang, there appears to be something wrong with your"
5919227Sandreas.hansson@arm.com    print "       environment."
5929227Sandreas.hansson@arm.com    print "       "
5939227Sandreas.hansson@arm.com    print "       If you are trying to use a compiler other than those listed"
5949227Sandreas.hansson@arm.com    print "       above you will need to ease fix SConstruct and "
5959227Sandreas.hansson@arm.com    print "       src/SConscript to support that compiler."
5969227Sandreas.hansson@arm.com    Exit(1)
5979227Sandreas.hansson@arm.com
5989227Sandreas.hansson@arm.com# Set up common yacc/bison flags (needed for Ruby)
5999227Sandreas.hansson@arm.commain['YACCFLAGS'] = '-d'
6009227Sandreas.hansson@arm.commain['YACCHXXFILESUFFIX'] = '.hh'
6019590Sandreas@sandberg.pp.se
6029590Sandreas@sandberg.pp.se# Do this after we save setting back, or else we'll tack on an
6039590Sandreas@sandberg.pp.se# extra 'qdo' every time we run scons.
6048737Skoansin.tan@gmail.comif main['BATCH']:
6059420Sandreas.hansson@arm.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
6069420Sandreas.hansson@arm.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
6079420Sandreas.hansson@arm.com    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
6088737Skoansin.tan@gmail.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
6098737Skoansin.tan@gmail.com    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
6108737Skoansin.tan@gmail.com
6118737Skoansin.tan@gmail.comif sys.platform == 'cygwin':
6128737Skoansin.tan@gmail.com    # cygwin has some header file issues...
6138737Skoansin.tan@gmail.com    main.Append(CCFLAGS=["-Wno-uninitialized"])
6148737Skoansin.tan@gmail.com
6158737Skoansin.tan@gmail.com# Check for the protobuf compiler
6168737Skoansin.tan@gmail.comprotoc_version = readCommand([main['PROTOC'], '--version'],
6178737Skoansin.tan@gmail.com                             exception='').split()
6188737Skoansin.tan@gmail.com
6198737Skoansin.tan@gmail.com# First two words should be "libprotoc x.y.z"
6209556Sandreas.hansson@arm.comif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6219556Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + \
6229556Sandreas.hansson@arm.com        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
6239556Sandreas.hansson@arm.com        '         Please install protobuf-compiler for tracing support.' + \
6249556Sandreas.hansson@arm.com        termcap.Normal
6259556Sandreas.hansson@arm.com    main['PROTOC'] = False
6269556Sandreas.hansson@arm.comelse:
6279556Sandreas.hansson@arm.com    # Determine the appropriate include path and library path using
6289556Sandreas.hansson@arm.com    # pkg-config, that means we also need to check for pkg-config
6299556Sandreas.hansson@arm.com    if not readCommand(['pkg-config', '--version'], exception=''):
6309590Sandreas@sandberg.pp.se        print 'Error: pkg-config not found. Please install and retry.'
6319590Sandreas@sandberg.pp.se        Exit(1)
6329420Sandreas.hansson@arm.com
6339420Sandreas.hansson@arm.com    main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
6349420Sandreas.hansson@arm.com
6359420Sandreas.hansson@arm.com    # Based on the availability of the compress stream wrappers,
6369420Sandreas.hansson@arm.com    # require 2.1.0
6379420Sandreas.hansson@arm.com    min_protoc_version = '2.1.0'
6389420Sandreas.hansson@arm.com    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6399420Sandreas.hansson@arm.com        print 'Error: protoc version', min_protoc_version, 'or newer required.'
6409420Sandreas.hansson@arm.com        print '       Installed version:', protoc_version[1]
6419420Sandreas.hansson@arm.com        Exit(1)
6428946Sandreas.hansson@arm.com
6433918Ssaidi@eecs.umich.edu# Check for SWIG
6449068SAli.Saidi@ARM.comif not main.has_key('SWIG'):
6459068SAli.Saidi@ARM.com    print 'Error: SWIG utility not found.'
6469068SAli.Saidi@ARM.com    print '       Please install (see http://www.swig.org) and retry.'
6479068SAli.Saidi@ARM.com    Exit(1)
6489068SAli.Saidi@ARM.com
6499068SAli.Saidi@ARM.com# Check for appropriate SWIG version
6509068SAli.Saidi@ARM.comswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
6519068SAli.Saidi@ARM.com# First 3 words should be "SWIG Version x.y.z"
6529068SAli.Saidi@ARM.comif len(swig_version) < 3 or \
6539419Sandreas.hansson@arm.com        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
6549068SAli.Saidi@ARM.com    print 'Error determining SWIG version.'
6559068SAli.Saidi@ARM.com    Exit(1)
6569068SAli.Saidi@ARM.com
6579068SAli.Saidi@ARM.commin_swig_version = '1.3.34'
6589068SAli.Saidi@ARM.comif compareVersions(swig_version[2], min_swig_version) < 0:
6599068SAli.Saidi@ARM.com    print 'Error: SWIG version', min_swig_version, 'or newer required.'
6603918Ssaidi@eecs.umich.edu    print '       Installed version:', swig_version[2]
6613918Ssaidi@eecs.umich.edu    Exit(1)
6626157Snate@binkert.org
6636157Snate@binkert.org# Set up SWIG flags & scanner
6646157Snate@binkert.orgswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
6656157Snate@binkert.orgmain.Append(SWIGFLAGS=swig_flags)
6665397Ssaidi@eecs.umich.edu
6675397Ssaidi@eecs.umich.edu# filter out all existing swig scanners, they mess up the dependency
6686121Snate@binkert.org# stuff for some reason
6696121Snate@binkert.orgscanners = []
6706121Snate@binkert.orgfor scanner in main['SCANNERS']:
6716121Snate@binkert.org    skeys = scanner.skeys
6726121Snate@binkert.org    if skeys == '.i':
6736121Snate@binkert.org        continue
6745397Ssaidi@eecs.umich.edu
6751851SN/A    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
6761851SN/A        continue
6777739Sgblack@eecs.umich.edu
678955SN/A    scanners.append(scanner)
6799396Sandreas.hansson@arm.com
6809396Sandreas.hansson@arm.com# add the new swig scanner that we like better
6819396Sandreas.hansson@arm.comfrom SCons.Scanner import ClassicCPP as CPPScanner
6829396Sandreas.hansson@arm.comswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
6839396Sandreas.hansson@arm.comscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
6849396Sandreas.hansson@arm.com
6859396Sandreas.hansson@arm.com# replace the scanners list that has what we want
6869396Sandreas.hansson@arm.commain['SCANNERS'] = scanners
6879396Sandreas.hansson@arm.com
6889396Sandreas.hansson@arm.com# Add a custom Check function to the Configure context so that we can
6899396Sandreas.hansson@arm.com# figure out if the compiler adds leading underscores to global
6909396Sandreas.hansson@arm.com# variables.  This is needed for the autogenerated asm files that we
6919396Sandreas.hansson@arm.com# use for embedding the python code.
6929396Sandreas.hansson@arm.comdef CheckLeading(context):
6939396Sandreas.hansson@arm.com    context.Message("Checking for leading underscore in global variables...")
6949396Sandreas.hansson@arm.com    # 1) Define a global variable called x from asm so the C compiler
6959477Sandreas.hansson@arm.com    #    won't change the symbol at all.
6969477Sandreas.hansson@arm.com    # 2) Declare that variable.
6979477Sandreas.hansson@arm.com    # 3) Use the variable
6989477Sandreas.hansson@arm.com    #
6999477Sandreas.hansson@arm.com    # If the compiler prepends an underscore, this will successfully
7009477Sandreas.hansson@arm.com    # link because the external symbol 'x' will be called '_x' which
7019477Sandreas.hansson@arm.com    # was defined by the asm statement.  If the compiler does not
7029477Sandreas.hansson@arm.com    # prepend an underscore, this will not successfully link because
7039477Sandreas.hansson@arm.com    # '_x' will have been defined by assembly, while the C portion of
7049477Sandreas.hansson@arm.com    # the code will be trying to use 'x'
7059477Sandreas.hansson@arm.com    ret = context.TryLink('''
7069477Sandreas.hansson@arm.com        asm(".globl _x; _x: .byte 0");
7079477Sandreas.hansson@arm.com        extern int x;
7089477Sandreas.hansson@arm.com        int main() { return x; }
7099477Sandreas.hansson@arm.com        ''', extension=".c")
7109477Sandreas.hansson@arm.com    context.env.Append(LEADING_UNDERSCORE=ret)
7119477Sandreas.hansson@arm.com    context.Result(ret)
7129477Sandreas.hansson@arm.com    return ret
7139477Sandreas.hansson@arm.com
7149477Sandreas.hansson@arm.com# Test for the presence of C++11 static asserts. If the compiler lacks
7159477Sandreas.hansson@arm.com# support for static asserts, base/compiler.hh enables a macro that
7169477Sandreas.hansson@arm.com# removes any static asserts in the code.
7179396Sandreas.hansson@arm.comdef CheckStaticAssert(context):
7183053Sstever@eecs.umich.edu    context.Message("Checking for C++11 static_assert support...")
7196121Snate@binkert.org    ret = context.TryCompile('''
7203053Sstever@eecs.umich.edu        static_assert(1, "This assert is always true");
7213053Sstever@eecs.umich.edu        ''', extension=".cc")
7223053Sstever@eecs.umich.edu    context.env.Append(HAVE_STATIC_ASSERT=ret)
7233053Sstever@eecs.umich.edu    context.Result(ret)
7243053Sstever@eecs.umich.edu    return ret
7259072Sandreas.hansson@arm.com
7263053Sstever@eecs.umich.edu# Platform-specific configuration.  Note again that we assume that all
7274742Sstever@eecs.umich.edu# builds under a given build root run on the same host platform.
7284742Sstever@eecs.umich.educonf = Configure(main,
7293053Sstever@eecs.umich.edu                 conf_dir = joinpath(build_root, '.scons_config'),
7303053Sstever@eecs.umich.edu                 log_file = joinpath(build_root, 'scons_config.log'),
7313053Sstever@eecs.umich.edu                 custom_tests = { 'CheckLeading' : CheckLeading,
7328960Ssteve.reinhardt@amd.com                                  'CheckStaticAssert' : CheckStaticAssert,
7336654Snate@binkert.org                                })
7343053Sstever@eecs.umich.edu
7353053Sstever@eecs.umich.edu# Check for leading underscores.  Don't really need to worry either
7363053Sstever@eecs.umich.edu# way so don't need to check the return code.
7373053Sstever@eecs.umich.educonf.CheckLeading()
7389740SAli.Saidi@ARM.com
7399585Sandreas@sandberg.pp.se# Check for C++11 features we want to use if they exist
7409740SAli.Saidi@ARM.comconf.CheckStaticAssert()
7419585Sandreas@sandberg.pp.se
7429585Sandreas@sandberg.pp.se# Check if we should compile a 64 bit binary on Mac OS X/Darwin
7439585Sandreas@sandberg.pp.setry:
7449585Sandreas@sandberg.pp.se    import platform
7459585Sandreas@sandberg.pp.se    uname = platform.uname()
7469585Sandreas@sandberg.pp.se    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
7472667Sstever@eecs.umich.edu        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
7484554Sbinkertn@umich.edu            main.Append(CCFLAGS=['-arch', 'x86_64'])
7496121Snate@binkert.org            main.Append(CFLAGS=['-arch', 'x86_64'])
7502667Sstever@eecs.umich.edu            main.Append(LINKFLAGS=['-arch', 'x86_64'])
7514554Sbinkertn@umich.edu            main.Append(ASFLAGS=['-arch', 'x86_64'])
7524554Sbinkertn@umich.eduexcept:
7534554Sbinkertn@umich.edu    pass
7546121Snate@binkert.org
7554554Sbinkertn@umich.edu# Recent versions of scons substitute a "Null" object for Configure()
7564554Sbinkertn@umich.edu# when configuration isn't necessary, e.g., if the "--help" option is
7574554Sbinkertn@umich.edu# present.  Unfortuantely this Null object always returns false,
7584781Snate@binkert.org# breaking all our configuration checks.  We replace it with our own
7594554Sbinkertn@umich.edu# more optimistic null object that returns True instead.
7604554Sbinkertn@umich.eduif not conf:
7612667Sstever@eecs.umich.edu    def NullCheck(*args, **kwargs):
7624554Sbinkertn@umich.edu        return True
7634554Sbinkertn@umich.edu
7644554Sbinkertn@umich.edu    class NullConf:
7654554Sbinkertn@umich.edu        def __init__(self, env):
7662667Sstever@eecs.umich.edu            self.env = env
7674554Sbinkertn@umich.edu        def Finish(self):
7682667Sstever@eecs.umich.edu            return self.env
7694554Sbinkertn@umich.edu        def __getattr__(self, mname):
7706121Snate@binkert.org            return NullCheck
7712667Sstever@eecs.umich.edu
7725522Snate@binkert.org    conf = NullConf(main)
7735522Snate@binkert.org
7745522Snate@binkert.org# Find Python include and library directories for embedding the
7755522Snate@binkert.org# interpreter.  For consistency, we will use the same Python
7765522Snate@binkert.org# installation used to run scons (and thus this script).  If you want
7775522Snate@binkert.org# to link in an alternate version, see above for instructions on how
7785522Snate@binkert.org# to invoke scons with a different copy of the Python interpreter.
7795522Snate@binkert.orgfrom distutils import sysconfig
7805522Snate@binkert.org
7815522Snate@binkert.orgpy_getvar = sysconfig.get_config_var
7825522Snate@binkert.org
7835522Snate@binkert.orgpy_debug = getattr(sys, 'pydebug', False)
7845522Snate@binkert.orgpy_version = 'python' + py_getvar('VERSION') + (py_debug and "_d" or "")
7855522Snate@binkert.org
7865522Snate@binkert.orgpy_general_include = sysconfig.get_python_inc()
7875522Snate@binkert.orgpy_platform_include = sysconfig.get_python_inc(plat_specific=True)
7885522Snate@binkert.orgpy_includes = [ py_general_include ]
7895522Snate@binkert.orgif py_platform_include != py_general_include:
7905522Snate@binkert.org    py_includes.append(py_platform_include)
7915522Snate@binkert.org
7925522Snate@binkert.orgpy_lib_path = [ py_getvar('LIBDIR') ]
7935522Snate@binkert.org# add the prefix/lib/pythonX.Y/config dir, but only if there is no
7945522Snate@binkert.org# shared library in prefix/lib/.
7955522Snate@binkert.orgif not py_getvar('Py_ENABLE_SHARED'):
7965522Snate@binkert.org    py_lib_path.append(py_getvar('LIBPL'))
7975522Snate@binkert.org
7982638Sstever@eecs.umich.edupy_libs = []
7992638Sstever@eecs.umich.edufor lib in py_getvar('LIBS').split() + py_getvar('SYSLIBS').split():
8006121Snate@binkert.org    if not lib.startswith('-l'):
8013716Sstever@eecs.umich.edu        # Python requires some special flags to link (e.g. -framework
8025522Snate@binkert.org        # common on OS X systems), assume appending preserves order
8039420Sandreas.hansson@arm.com        main.Append(LINKFLAGS=[lib])
8045522Snate@binkert.org    else:
8055522Snate@binkert.org        lib = lib[2:]
8065522Snate@binkert.org        if lib not in py_libs:
8075522Snate@binkert.org            py_libs.append(lib)
8081858SN/Apy_libs.append(py_version)
8095227Ssaidi@eecs.umich.edu
8105227Ssaidi@eecs.umich.edumain.Append(CPPPATH=py_includes)
8115227Ssaidi@eecs.umich.edumain.Append(LIBPATH=py_lib_path)
8125227Ssaidi@eecs.umich.edu
8136654Snate@binkert.org# Cache build files in the supplied directory.
8146654Snate@binkert.orgif main['M5_BUILD_CACHE']:
8157769SAli.Saidi@ARM.com    print 'Using build cache located at', main['M5_BUILD_CACHE']
8167769SAli.Saidi@ARM.com    CacheDir(main['M5_BUILD_CACHE'])
8177769SAli.Saidi@ARM.com
8187769SAli.Saidi@ARM.com
8195227Ssaidi@eecs.umich.edu# verify that this stuff works
8205227Ssaidi@eecs.umich.eduif not conf.CheckHeader('Python.h', '<>'):
8215227Ssaidi@eecs.umich.edu    print "Error: can't find Python.h header in", py_includes
8225204Sstever@gmail.com    print "Install Python headers (package python-dev on Ubuntu and RedHat)"
8235204Sstever@gmail.com    Exit(1)
8245204Sstever@gmail.com
8255204Sstever@gmail.comfor lib in py_libs:
8265204Sstever@gmail.com    if not conf.CheckLib(lib):
8275204Sstever@gmail.com        print "Error: can't find library %s required by python" % lib
8285204Sstever@gmail.com        Exit(1)
8295204Sstever@gmail.com
8305204Sstever@gmail.com# On Solaris you need to use libsocket for socket ops
8315204Sstever@gmail.comif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
8325204Sstever@gmail.com   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
8335204Sstever@gmail.com       print "Can't find library with socket calls (e.g. accept())"
8345204Sstever@gmail.com       Exit(1)
8355204Sstever@gmail.com
8365204Sstever@gmail.com# Check for zlib.  If the check passes, libz will be automatically
8375204Sstever@gmail.com# added to the LIBS environment variable.
8385204Sstever@gmail.comif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
8396121Snate@binkert.org    print 'Error: did not find needed zlib compression library '\
8405204Sstever@gmail.com          'and/or zlib.h header file.'
8417727SAli.Saidi@ARM.com    print '       Please install zlib and try again.'
8427727SAli.Saidi@ARM.com    Exit(1)
8437727SAli.Saidi@ARM.com
8447727SAli.Saidi@ARM.com# If we have the protobuf compiler, also make sure we have the
8457727SAli.Saidi@ARM.com# development libraries. If the check passes, libprotobuf will be
8469812Sandreas.hansson@arm.com# automatically added to the LIBS environment variable. After
8479812Sandreas.hansson@arm.com# this, we can use the HAVE_PROTOBUF flag to determine if we have
8489812Sandreas.hansson@arm.com# got both protoc and libprotobuf available.
8499812Sandreas.hansson@arm.commain['HAVE_PROTOBUF'] = main['PROTOC'] and \
8509812Sandreas.hansson@arm.com    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
8519812Sandreas.hansson@arm.com                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
8529812Sandreas.hansson@arm.com
8539812Sandreas.hansson@arm.com# If we have the compiler but not the library, treat it as an error.
8549812Sandreas.hansson@arm.comif main['PROTOC'] and not main['HAVE_PROTOBUF']:
8559812Sandreas.hansson@arm.com    print 'Error: did not find protocol buffer library and/or headers.'
8569812Sandreas.hansson@arm.com    print '       Please install libprotobuf-dev and try again.'
8579812Sandreas.hansson@arm.com    Exit(1)
8589812Sandreas.hansson@arm.com
8599812Sandreas.hansson@arm.com# Check for librt.
8609812Sandreas.hansson@arm.comhave_posix_clock = \
8619812Sandreas.hansson@arm.com    conf.CheckLibWithHeader(None, 'time.h', 'C',
8629812Sandreas.hansson@arm.com                            'clock_nanosleep(0,0,NULL,NULL);') or \
8639812Sandreas.hansson@arm.com    conf.CheckLibWithHeader('rt', 'time.h', 'C',
8649812Sandreas.hansson@arm.com                            'clock_nanosleep(0,0,NULL,NULL);')
8659812Sandreas.hansson@arm.com
8669812Sandreas.hansson@arm.comif conf.CheckLib('tcmalloc_minimal'):
8679812Sandreas.hansson@arm.com    have_tcmalloc = True
8689812Sandreas.hansson@arm.comelse:
8699812Sandreas.hansson@arm.com    have_tcmalloc = False
8707727SAli.Saidi@ARM.com    print termcap.Yellow + termcap.Bold + \
8715863Snate@binkert.org          "You can get a 12% performance improvement by installing tcmalloc "\
8723118Sstever@eecs.umich.edu          "(libgoogle-perftools-dev package on Ubuntu or RedHat)." + \
8735863Snate@binkert.org          termcap.Normal
8749239Sandreas.hansson@arm.com
8753118Sstever@eecs.umich.eduif not have_posix_clock:
8763118Sstever@eecs.umich.edu    print "Can't find library for POSIX clocks."
8775863Snate@binkert.org
8785863Snate@binkert.org# Check for <fenv.h> (C99 FP environment control)
8795863Snate@binkert.orghave_fenv = conf.CheckHeader('fenv.h', '<>')
8805863Snate@binkert.orgif not have_fenv:
8813118Sstever@eecs.umich.edu    print "Warning: Header file <fenv.h> not found."
8823483Ssaidi@eecs.umich.edu    print "         This host has no IEEE FP rounding mode control."
8833494Ssaidi@eecs.umich.edu
8843494Ssaidi@eecs.umich.edu######################################################################
8853483Ssaidi@eecs.umich.edu#
8863483Ssaidi@eecs.umich.edu# Finish the configuration
8873483Ssaidi@eecs.umich.edu#
8883053Sstever@eecs.umich.edumain = conf.Finish()
8893053Sstever@eecs.umich.edu
8903918Ssaidi@eecs.umich.edu######################################################################
8913053Sstever@eecs.umich.edu#
8923053Sstever@eecs.umich.edu# Collect all non-global variables
8933053Sstever@eecs.umich.edu#
8943053Sstever@eecs.umich.edu
8953053Sstever@eecs.umich.edu# Define the universe of supported ISAs
8969396Sandreas.hansson@arm.comall_isa_list = [ ]
8979396Sandreas.hansson@arm.comExport('all_isa_list')
8989396Sandreas.hansson@arm.com
8999396Sandreas.hansson@arm.comclass CpuModel(object):
9009396Sandreas.hansson@arm.com    '''The CpuModel class encapsulates everything the ISA parser needs to
9019396Sandreas.hansson@arm.com    know about a particular CPU model.'''
9029396Sandreas.hansson@arm.com
9039396Sandreas.hansson@arm.com    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
9049396Sandreas.hansson@arm.com    dict = {}
9059477Sandreas.hansson@arm.com    list = []
9069396Sandreas.hansson@arm.com    defaults = []
9079477Sandreas.hansson@arm.com
9089477Sandreas.hansson@arm.com    # Constructor.  Automatically adds models to CpuModel.dict.
9099477Sandreas.hansson@arm.com    def __init__(self, name, filename, includes, strings, default=False):
9109477Sandreas.hansson@arm.com        self.name = name           # name of model
9119396Sandreas.hansson@arm.com        self.filename = filename   # filename for output exec code
9127840Snate@binkert.org        self.includes = includes   # include files needed in exec file
9137865Sgblack@eecs.umich.edu        # The 'strings' dict holds all the per-CPU symbols we can
9147865Sgblack@eecs.umich.edu        # substitute into templates etc.
9157865Sgblack@eecs.umich.edu        self.strings = strings
9167865Sgblack@eecs.umich.edu
9177865Sgblack@eecs.umich.edu        # This cpu is enabled by default
9187840Snate@binkert.org        self.default = default
9199591Sandreas@sandberg.pp.se
9209591Sandreas@sandberg.pp.se        # Add self to dict
9219591Sandreas@sandberg.pp.se        if name in CpuModel.dict:
9229590Sandreas@sandberg.pp.se            raise AttributeError, "CpuModel '%s' already registered" % name
9239590Sandreas@sandberg.pp.se        CpuModel.dict[name] = self
9249045SAli.Saidi@ARM.com        CpuModel.list.append(name)
9259045SAli.Saidi@ARM.com
9269071Sandreas.hansson@arm.comExport('CpuModel')
9279071Sandreas.hansson@arm.com
9289045SAli.Saidi@ARM.com# Sticky variables get saved in the variables file so they persist from
9297840Snate@binkert.org# one invocation to the next (unless overridden, in which case the new
9307840Snate@binkert.org# value becomes sticky).
9317840Snate@binkert.orgsticky_vars = Variables(args=ARGUMENTS)
9321858SN/AExport('sticky_vars')
9331858SN/A
9341858SN/A# Sticky variables that should be exported
9351858SN/Aexport_vars = []
9361858SN/AExport('export_vars')
9371858SN/A
9389651SAndreas.Sandberg@ARM.com# For Ruby
9399651SAndreas.Sandberg@ARM.comall_protocols = []
9409651SAndreas.Sandberg@ARM.comExport('all_protocols')
9419651SAndreas.Sandberg@ARM.comprotocol_dirs = []
9429651SAndreas.Sandberg@ARM.comExport('protocol_dirs')
9439651SAndreas.Sandberg@ARM.comslicc_includes = []
9449651SAndreas.Sandberg@ARM.comExport('slicc_includes')
9459651SAndreas.Sandberg@ARM.com
9469651SAndreas.Sandberg@ARM.com# Walk the tree and execute all SConsopts scripts that wil add to the
9479657Sandreas.sandberg@arm.com# above variables
9489651SAndreas.Sandberg@ARM.comif not GetOption('verbose'):
9499651SAndreas.Sandberg@ARM.com    print "Reading SConsopts"
9509651SAndreas.Sandberg@ARM.comfor bdir in [ base_dir ] + extras_dir_list:
9519651SAndreas.Sandberg@ARM.com    if not isdir(bdir):
9529651SAndreas.Sandberg@ARM.com        print "Error: directory '%s' does not exist" % bdir
9539651SAndreas.Sandberg@ARM.com        Exit(1)
9549651SAndreas.Sandberg@ARM.com    for root, dirs, files in os.walk(bdir):
9559651SAndreas.Sandberg@ARM.com        if 'SConsopts' in files:
9569651SAndreas.Sandberg@ARM.com            if GetOption('verbose'):
9579651SAndreas.Sandberg@ARM.com                print "Reading", joinpath(root, 'SConsopts')
9589651SAndreas.Sandberg@ARM.com            SConscript(joinpath(root, 'SConsopts'))
9595863Snate@binkert.org
9605863Snate@binkert.orgall_isa_list.sort()
9615863Snate@binkert.org
9625863Snate@binkert.orgsticky_vars.AddVariables(
9636121Snate@binkert.org    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
9641858SN/A    ListVariable('CPU_MODELS', 'CPU models',
9655863Snate@binkert.org                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
9665863Snate@binkert.org                 sorted(CpuModel.list)),
9675863Snate@binkert.org    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
9685863Snate@binkert.org                 False),
9695863Snate@binkert.org    BoolVariable('SS_COMPATIBLE_FP',
9702139SN/A                 'Make floating-point results compatible with SimpleScalar',
9714202Sbinkertn@umich.edu                 False),
9724202Sbinkertn@umich.edu    BoolVariable('USE_SSE2',
9732139SN/A                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
9746994Snate@binkert.org                 False),
9756994Snate@binkert.org    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
9766994Snate@binkert.org    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
9776994Snate@binkert.org    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
9786994Snate@binkert.org    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
9796994Snate@binkert.org                  all_protocols),
9806994Snate@binkert.org    )
9816994Snate@binkert.org
9826994Snate@binkert.org# These variables get exported to #defines in config/*.hh (see src/SConscript).
9836994Snate@binkert.orgexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP',
9846994Snate@binkert.org                'TARGET_ISA', 'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'PROTOCOL',
9856994Snate@binkert.org                'HAVE_STATIC_ASSERT', 'HAVE_PROTOBUF']
9866994Snate@binkert.org
9876994Snate@binkert.org###################################################
9886994Snate@binkert.org#
9896994Snate@binkert.org# Define a SCons builder for configuration flag headers.
9906994Snate@binkert.org#
9916994Snate@binkert.org###################################################
9926994Snate@binkert.org
9936994Snate@binkert.org# This function generates a config header file that #defines the
9946994Snate@binkert.org# variable symbol to the current variable setting (0 or 1).  The source
9956994Snate@binkert.org# operands are the name of the variable and a Value node containing the
9966994Snate@binkert.org# value of the variable.
9976994Snate@binkert.orgdef build_config_file(target, source, env):
9986994Snate@binkert.org    (variable, value) = [s.get_contents() for s in source]
9996994Snate@binkert.org    f = file(str(target[0]), 'w')
10006994Snate@binkert.org    print >> f, '#define', variable, value
10016994Snate@binkert.org    f.close()
10022155SN/A    return None
10035863Snate@binkert.org
10041869SN/A# Combine the two functions into a scons Action object.
10051869SN/Aconfig_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
10065863Snate@binkert.org
10075863Snate@binkert.org# The emitter munges the source & target node lists to reflect what
10084202Sbinkertn@umich.edu# we're really doing.
10096108Snate@binkert.orgdef config_emitter(target, source, env):
10106108Snate@binkert.org    # extract variable name from Builder arg
10116108Snate@binkert.org    variable = str(target[0])
10126108Snate@binkert.org    # True target is config header file
10139219Spower.jg@gmail.com    target = joinpath('config', variable.lower() + '.hh')
10149219Spower.jg@gmail.com    val = env[variable]
10159219Spower.jg@gmail.com    if isinstance(val, bool):
10169219Spower.jg@gmail.com        # Force value to 0/1
10179219Spower.jg@gmail.com        val = int(val)
10189219Spower.jg@gmail.com    elif isinstance(val, str):
10199219Spower.jg@gmail.com        val = '"' + val + '"'
10209219Spower.jg@gmail.com
10214202Sbinkertn@umich.edu    # Sources are variable name & value (packaged in SCons Value nodes)
10225863Snate@binkert.org    return ([target], [Value(variable), Value(val)])
10238474Sgblack@eecs.umich.edu
10248474Sgblack@eecs.umich.educonfig_builder = Builder(emitter = config_emitter, action = config_action)
10255742Snate@binkert.org
10268268Ssteve.reinhardt@amd.commain.Append(BUILDERS = { 'ConfigFile' : config_builder })
10278268Ssteve.reinhardt@amd.com
10288268Ssteve.reinhardt@amd.com# libelf build is shared across all configs in the build root.
10295742Snate@binkert.orgmain.SConscript('ext/libelf/SConscript',
10305341Sstever@gmail.com                variant_dir = joinpath(build_root, 'libelf'))
10318474Sgblack@eecs.umich.edu
10328474Sgblack@eecs.umich.edu# gzstream build is shared across all configs in the build root.
10335342Sstever@gmail.commain.SConscript('ext/gzstream/SConscript',
10344202Sbinkertn@umich.edu                variant_dir = joinpath(build_root, 'gzstream'))
10354202Sbinkertn@umich.edu
10364202Sbinkertn@umich.edu###################################################
10375863Snate@binkert.org#
10385863Snate@binkert.org# This function is used to set up a directory with switching headers
10396994Snate@binkert.org#
10406994Snate@binkert.org###################################################
10416994Snate@binkert.org
10425863Snate@binkert.orgmain['ALL_ISA_LIST'] = all_isa_list
10435863Snate@binkert.orgdef make_switching_dir(dname, switch_headers, env):
10445863Snate@binkert.org    # Generate the header.  target[0] is the full path of the output
10455863Snate@binkert.org    # header to generate.  'source' is a dummy variable, since we get the
10465863Snate@binkert.org    # list of ISAs from env['ALL_ISA_LIST'].
10475863Snate@binkert.org    def gen_switch_hdr(target, source, env):
10485863Snate@binkert.org        fname = str(target[0])
10495863Snate@binkert.org        f = open(fname, 'w')
10507840Snate@binkert.org        isa = env['TARGET_ISA'].lower()
10515863Snate@binkert.org        print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
10525952Ssaidi@eecs.umich.edu        f.close()
10539651SAndreas.Sandberg@ARM.com
10549219Spower.jg@gmail.com    # Build SCons Action object. 'varlist' specifies env vars that this
10559219Spower.jg@gmail.com    # action depends on; when env['ALL_ISA_LIST'] changes these actions
10561869SN/A    # should get re-executed.
10571858SN/A    switch_hdr_action = MakeAction(gen_switch_hdr,
10585863Snate@binkert.org                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
10599420Sandreas.hansson@arm.com
10609420Sandreas.hansson@arm.com    # Instantiate actions for each header
10611858SN/A    for hdr in switch_headers:
1062955SN/A        env.Command(hdr, [], switch_hdr_action)
1063955SN/AExport('make_switching_dir')
10641869SN/A
10651869SN/A###################################################
10661869SN/A#
10671869SN/A# Define build environments for selected configurations.
10681869SN/A#
10695863Snate@binkert.org###################################################
10705863Snate@binkert.org
10715863Snate@binkert.orgfor variant_path in variant_paths:
10721869SN/A    print "Building in", variant_path
10735863Snate@binkert.org
10741869SN/A    # Make a copy of the build-root environment to use for this config.
10755863Snate@binkert.org    env = main.Clone()
10761869SN/A    env['BUILDDIR'] = variant_path
10771869SN/A
10781869SN/A    # variant_dir is the tail component of build path, and is used to
10791869SN/A    # determine the build parameters (e.g., 'ALPHA_SE')
10808483Sgblack@eecs.umich.edu    (build_root, variant_dir) = splitpath(variant_path)
10811869SN/A
10821869SN/A    # Set env variables according to the build directory config.
10831869SN/A    sticky_vars.files = []
10841869SN/A    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
10855863Snate@binkert.org    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
10865863Snate@binkert.org    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
10871869SN/A    current_vars_file = joinpath(build_root, 'variables', variant_dir)
10885863Snate@binkert.org    if isfile(current_vars_file):
10895863Snate@binkert.org        sticky_vars.files.append(current_vars_file)
10903356Sbinkertn@umich.edu        print "Using saved variables file %s" % current_vars_file
10913356Sbinkertn@umich.edu    else:
10923356Sbinkertn@umich.edu        # Build dir-specific variables file doesn't exist.
10933356Sbinkertn@umich.edu
10943356Sbinkertn@umich.edu        # Make sure the directory is there so we can create it later
10954781Snate@binkert.org        opt_dir = dirname(current_vars_file)
10965863Snate@binkert.org        if not isdir(opt_dir):
10975863Snate@binkert.org            mkdir(opt_dir)
10981869SN/A
10991869SN/A        # Get default build variables from source tree.  Variables are
11001869SN/A        # normally determined by name of $VARIANT_DIR, but can be
11016121Snate@binkert.org        # overridden by '--default=' arg on command line.
11021869SN/A        default = GetOption('default')
11032638Sstever@eecs.umich.edu        opts_dir = joinpath(main.root.abspath, 'build_opts')
11046121Snate@binkert.org        if default:
11056121Snate@binkert.org            default_vars_files = [joinpath(build_root, 'variables', default),
11062638Sstever@eecs.umich.edu                                  joinpath(opts_dir, default)]
11075749Scws3k@cs.virginia.edu        else:
11086121Snate@binkert.org            default_vars_files = [joinpath(opts_dir, variant_dir)]
11096121Snate@binkert.org        existing_files = filter(isfile, default_vars_files)
11105749Scws3k@cs.virginia.edu        if existing_files:
11119537Satgutier@umich.edu            default_vars_file = existing_files[0]
11129537Satgutier@umich.edu            sticky_vars.files.append(default_vars_file)
11139537Satgutier@umich.edu            print "Variables file %s not found,\n  using defaults in %s" \
11149537Satgutier@umich.edu                  % (current_vars_file, default_vars_file)
11151869SN/A        else:
11161869SN/A            print "Error: cannot find variables file %s or " \
11173546Sgblack@eecs.umich.edu                  "default file(s) %s" \
11183546Sgblack@eecs.umich.edu                  % (current_vars_file, ' or '.join(default_vars_files))
11193546Sgblack@eecs.umich.edu            Exit(1)
11203546Sgblack@eecs.umich.edu
11216121Snate@binkert.org    # Apply current variable settings to env
11225863Snate@binkert.org    sticky_vars.Update(env)
11233546Sgblack@eecs.umich.edu
11243546Sgblack@eecs.umich.edu    help_texts["local_vars"] += \
11253546Sgblack@eecs.umich.edu        "Build variables for %s:\n" % variant_dir \
11263546Sgblack@eecs.umich.edu                 + sticky_vars.GenerateHelpText(env)
11274781Snate@binkert.org
11284781Snate@binkert.org    # Process variable settings.
11296658Snate@binkert.org
11306658Snate@binkert.org    if not have_fenv and env['USE_FENV']:
11314781Snate@binkert.org        print "Warning: <fenv.h> not available; " \
11323546Sgblack@eecs.umich.edu              "forcing USE_FENV to False in", variant_dir + "."
11333546Sgblack@eecs.umich.edu        env['USE_FENV'] = False
11343546Sgblack@eecs.umich.edu
11353546Sgblack@eecs.umich.edu    if not env['USE_FENV']:
11367756SAli.Saidi@ARM.com        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
11377816Ssteve.reinhardt@amd.com        print "         FP results may deviate slightly from other platforms."
11383546Sgblack@eecs.umich.edu
11393546Sgblack@eecs.umich.edu    if env['EFENCE']:
11403546Sgblack@eecs.umich.edu        env.Append(LIBS=['efence'])
11413546Sgblack@eecs.umich.edu
11424202Sbinkertn@umich.edu    # Save sticky variable settings back to current variables file
11433546Sgblack@eecs.umich.edu    sticky_vars.Save(current_vars_file, env)
11443546Sgblack@eecs.umich.edu
11453546Sgblack@eecs.umich.edu    if env['USE_SSE2']:
1146955SN/A        env.Append(CCFLAGS=['-msse2'])
1147955SN/A
1148955SN/A    if have_tcmalloc:
1149955SN/A        env.Append(LIBS=['tcmalloc_minimal'])
11505863Snate@binkert.org
11515863Snate@binkert.org    # The src/SConscript file sets up the build rules in 'env' according
11525343Sstever@gmail.com    # to the configured variables.  It returns a list of environments,
11535343Sstever@gmail.com    # one for each variant build (debug, opt, etc.)
11546121Snate@binkert.org    envList = SConscript('src/SConscript', variant_dir = variant_path,
11555863Snate@binkert.org                         exports = 'env')
11564773Snate@binkert.org
11575863Snate@binkert.org    # Set up the regression tests for each build.
11582632Sstever@eecs.umich.edu    for e in envList:
11595863Snate@binkert.org        SConscript('tests/SConscript',
11602023SN/A                   variant_dir = joinpath(variant_path, 'tests', e.Label),
11615863Snate@binkert.org                   exports = { 'env' : e }, duplicate = False)
11625863Snate@binkert.org
11635863Snate@binkert.org# base help text
11645863Snate@binkert.orgHelp('''
11655863Snate@binkert.orgUsage: scons [scons options] [build variables] [target(s)]
11665863Snate@binkert.org
11675863Snate@binkert.orgExtra scons options:
11685863Snate@binkert.org%(options)s
11695863Snate@binkert.org
11702632Sstever@eecs.umich.eduGlobal build variables:
11715863Snate@binkert.org%(global_vars)s
11722023SN/A
11732632Sstever@eecs.umich.edu%(local_vars)s
11745863Snate@binkert.org''' % help_texts)
11755342Sstever@gmail.com