SConstruct revision 9396
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
11210196SCurtis.Dunham@arm.comimport SCons
113955SN/Aimport SCons.Node
1145396Ssaidi@eecs.umich.edu
1155863Snate@binkert.orgextra_python_paths = [
1165863Snate@binkert.org    Dir('src/python').srcnode().abspath, # gem5 includes
1174202Sbinkertn@umich.edu    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
1215863Snate@binkert.org
122955SN/Afrom m5.util import compareVersions, readCommand
1236654Snate@binkert.orgfrom m5.util.terminal import get_termcap
1245273Sstever@gmail.com
1255871Snate@binkert.orghelp_texts = {
1265273Sstever@gmail.com    "options" : "",
1276655Snate@binkert.org    "global_vars" : "",
1288878Ssteve.reinhardt@amd.com    "local_vars" : ""
1296655Snate@binkert.org}
1306655Snate@binkert.org
1319219Spower.jg@gmail.comExport("help_texts")
1326655Snate@binkert.org
1335871Snate@binkert.org
1346654Snate@binkert.org# There's a bug in scons in that (1) by default, the help texts from
1358947Sandreas.hansson@arm.com# AddOption() are supposed to be displayed when you type 'scons -h'
1365396Ssaidi@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
1448120Sgblack@eecs.umich.edu# 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"
1578879Ssteve.reinhardt@amd.com
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',
1718120Sgblack@eecs.umich.edu               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#
1798879Ssteve.reinhardt@amd.com# Set up the main build environment.
1809227Sandreas.hansson@arm.com#
1819227Sandreas.hansson@arm.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' ])
1858879Ssteve.reinhardt@amd.com
18610453SAndrew.Bardsley@arm.comuse_env = {}
18710453SAndrew.Bardsley@arm.comfor key,val in os.environ.iteritems():
18810453SAndrew.Bardsley@arm.com    if key in use_vars or key.startswith("M5"):
18910456SCurtis.Dunham@arm.com        use_env[key] = val
19010456SCurtis.Dunham@arm.com
19110456SCurtis.Dunham@arm.commain = Environment(ENV=use_env)
19210457Sandreas.hansson@arm.commain.Decider('MD5-timestamp')
19310457Sandreas.hansson@arm.commain.root = Dir(".")         # The current directory (where this file lives).
1948120Sgblack@eecs.umich.edumain.srcdir = Dir("src")     # The source directory
1958947Sandreas.hansson@arm.com
1967816Ssteve.reinhardt@amd.commain_dict_keys = main.Dictionary().keys()
1975871Snate@binkert.org
1985871Snate@binkert.org# Check that we have a C/C++ compiler
1996121Snate@binkert.orgif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2005871Snate@binkert.org    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2015871Snate@binkert.org    Exit(1)
2029926Sstan.czerniawski@arm.com
2039926Sstan.czerniawski@arm.com# Check that swig is present
2049119Sandreas.hansson@arm.comif not 'SWIG' in main_dict_keys:
20510068Sandreas.hansson@arm.com    print "swig is not installed (package swig on Ubuntu and RedHat)"
20610068Sandreas.hansson@arm.com    Exit(1)
207955SN/A
2089416SAndreas.Sandberg@ARM.com# add useful python code PYTHONPATH so it can be used by subprocesses
2099416SAndreas.Sandberg@ARM.com# as well
2109416SAndreas.Sandberg@ARM.commain.AppendENVPath('PYTHONPATH', extra_python_paths)
2119416SAndreas.Sandberg@ARM.com
2129416SAndreas.Sandberg@ARM.com########################################################################
2139416SAndreas.Sandberg@ARM.com#
2149416SAndreas.Sandberg@ARM.com# Mercurial Stuff.
2155871Snate@binkert.org#
2165871Snate@binkert.org# If the gem5 directory is a mercurial repository, we should do some
2179416SAndreas.Sandberg@ARM.com# extra things.
2189416SAndreas.Sandberg@ARM.com#
2195871Snate@binkert.org########################################################################
220955SN/A
2216121Snate@binkert.orghgdir = main.root.Dir(".hg")
2228881Smarc.orr@gmail.com
2236121Snate@binkert.orgmercurial_style_message = """
2246121Snate@binkert.orgYou're missing the gem5 style hook, which automatically checks your code
2251533SN/Aagainst the gem5 style rules on hg commit and qrefresh commands.  This
2269239Sandreas.hansson@arm.comscript will now install the hook in your .hg/hgrc file.
2279239Sandreas.hansson@arm.comPress enter to continue, or ctrl-c to abort: """
2289239Sandreas.hansson@arm.com
2299239Sandreas.hansson@arm.commercurial_style_hook = """
2309239Sandreas.hansson@arm.com# The following lines were automatically added by gem5/SConstruct
2319239Sandreas.hansson@arm.com# to provide the gem5 style-checking hooks
2329239Sandreas.hansson@arm.com[extensions]
2339239Sandreas.hansson@arm.comstyle = %s/util/style.py
2349239Sandreas.hansson@arm.com
2359239Sandreas.hansson@arm.com[hooks]
2369239Sandreas.hansson@arm.compretxncommit.style = python:style.check_style
2379239Sandreas.hansson@arm.compre-qrefresh.style = python:style.check_style
2386655Snate@binkert.org# End of SConstruct additions
2396655Snate@binkert.org
2406655Snate@binkert.org""" % (main.root.abspath)
2416655Snate@binkert.org
2425871Snate@binkert.orgmercurial_lib_not_found = """
2435871Snate@binkert.orgMercurial libraries cannot be found, ignoring style hook.  If
2445863Snate@binkert.orgyou are a gem5 developer, please fix this and run the style
2455871Snate@binkert.orghook. It is important.
2468878Ssteve.reinhardt@amd.com"""
2475871Snate@binkert.org
2485871Snate@binkert.org# Check for style hook and prompt for installation if it's not there.
2495871Snate@binkert.org# Skip this if --ignore-style was specified, there's no .hg dir to
2505863Snate@binkert.org# install a hook in, or there's no interactive terminal to prompt.
2516121Snate@binkert.orgif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2525863Snate@binkert.org    style_hook = True
2535871Snate@binkert.org    try:
2548336Ssteve.reinhardt@amd.com        from mercurial import ui
2558336Ssteve.reinhardt@amd.com        ui = ui.ui()
2568336Ssteve.reinhardt@amd.com        ui.readconfig(hgdir.File('hgrc').abspath)
2578336Ssteve.reinhardt@amd.com        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2584678Snate@binkert.org                     ui.config('hooks', 'pre-qrefresh.style', None)
2598336Ssteve.reinhardt@amd.com    except ImportError:
2608336Ssteve.reinhardt@amd.com        print mercurial_lib_not_found
2618336Ssteve.reinhardt@amd.com
2624678Snate@binkert.org    if not style_hook:
2634678Snate@binkert.org        print mercurial_style_message,
2644678Snate@binkert.org        # continue unless user does ctrl-c/ctrl-d etc.
2654678Snate@binkert.org        try:
2667827Snate@binkert.org            raw_input()
2677827Snate@binkert.org        except:
2688336Ssteve.reinhardt@amd.com            print "Input exception, exiting scons.\n"
2694678Snate@binkert.org            sys.exit(1)
2708336Ssteve.reinhardt@amd.com        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
2718336Ssteve.reinhardt@amd.com        print "Adding style hook to", hgrc_path, "\n"
2728336Ssteve.reinhardt@amd.com        try:
2738336Ssteve.reinhardt@amd.com            hgrc = open(hgrc_path, 'a')
2748336Ssteve.reinhardt@amd.com            hgrc.write(mercurial_style_hook)
2758336Ssteve.reinhardt@amd.com            hgrc.close()
2765871Snate@binkert.org        except:
2775871Snate@binkert.org            print "Error updating", hgrc_path
2788336Ssteve.reinhardt@amd.com            sys.exit(1)
2798336Ssteve.reinhardt@amd.com
2808336Ssteve.reinhardt@amd.com
2818336Ssteve.reinhardt@amd.com###################################################
2828336Ssteve.reinhardt@amd.com#
2835871Snate@binkert.org# Figure out which configurations to set up based on the path(s) of
2848336Ssteve.reinhardt@amd.com# the target(s).
2858336Ssteve.reinhardt@amd.com#
2868336Ssteve.reinhardt@amd.com###################################################
2878336Ssteve.reinhardt@amd.com
2888336Ssteve.reinhardt@amd.com# Find default configuration & binary.
2894678Snate@binkert.orgDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
2905871Snate@binkert.org
2914678Snate@binkert.org# helper function: find last occurrence of element in list
2928336Ssteve.reinhardt@amd.comdef rfind(l, elt, offs = -1):
2938336Ssteve.reinhardt@amd.com    for i in range(len(l)+offs, 0, -1):
2948336Ssteve.reinhardt@amd.com        if l[i] == elt:
2958336Ssteve.reinhardt@amd.com            return i
2968336Ssteve.reinhardt@amd.com    raise ValueError, "element not found"
2978336Ssteve.reinhardt@amd.com
2988336Ssteve.reinhardt@amd.com# Take a list of paths (or SCons Nodes) and return a list with all
2998336Ssteve.reinhardt@amd.com# paths made absolute and ~-expanded.  Paths will be interpreted
3008336Ssteve.reinhardt@amd.com# relative to the launch directory unless a different root is provided
3018336Ssteve.reinhardt@amd.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
3028336Ssteve.reinhardt@amd.com    return [abspath(joinpath(root, expanduser(str(p))))
3038336Ssteve.reinhardt@amd.com            for p in path_list]
3048336Ssteve.reinhardt@amd.com
3058336Ssteve.reinhardt@amd.com# Each target must have 'build' in the interior of the path; the
3068336Ssteve.reinhardt@amd.com# directory below this will determine the build parameters.  For
3078336Ssteve.reinhardt@amd.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3088336Ssteve.reinhardt@amd.com# recognize that ALPHA_SE specifies the configuration because it
3095871Snate@binkert.org# follow 'build' in the build path.
3106121Snate@binkert.org
311955SN/A# The funky assignment to "[:]" is needed to replace the list contents
312955SN/A# in place rather than reassign the symbol to a new list, which
3132632Sstever@eecs.umich.edu# doesn't work (obviously!).
3142632Sstever@eecs.umich.eduBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
315955SN/A
316955SN/A# Generate a list of the unique build roots and configs that the
317955SN/A# collected targets reference.
318955SN/Avariant_paths = []
3198878Ssteve.reinhardt@amd.combuild_root = None
320955SN/Afor t in BUILD_TARGETS:
3212632Sstever@eecs.umich.edu    path_dirs = t.split('/')
3222632Sstever@eecs.umich.edu    try:
3232632Sstever@eecs.umich.edu        build_top = rfind(path_dirs, 'build', -2)
3242632Sstever@eecs.umich.edu    except:
3252632Sstever@eecs.umich.edu        print "Error: no non-leaf 'build' dir found on target path", t
3262632Sstever@eecs.umich.edu        Exit(1)
3272632Sstever@eecs.umich.edu    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3288268Ssteve.reinhardt@amd.com    if not build_root:
3298268Ssteve.reinhardt@amd.com        build_root = this_build_root
3308268Ssteve.reinhardt@amd.com    else:
3318268Ssteve.reinhardt@amd.com        if this_build_root != build_root:
3328268Ssteve.reinhardt@amd.com            print "Error: build targets not under same build root\n"\
3338268Ssteve.reinhardt@amd.com                  "  %s\n  %s" % (build_root, this_build_root)
3348268Ssteve.reinhardt@amd.com            Exit(1)
3352632Sstever@eecs.umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
3362632Sstever@eecs.umich.edu    if variant_path not in variant_paths:
3372632Sstever@eecs.umich.edu        variant_paths.append(variant_path)
3382632Sstever@eecs.umich.edu
3398268Ssteve.reinhardt@amd.com# Make sure build_root exists (might not if this is the first build there)
3402632Sstever@eecs.umich.eduif not isdir(build_root):
3418268Ssteve.reinhardt@amd.com    mkdir(build_root)
3428268Ssteve.reinhardt@amd.commain['BUILDROOT'] = build_root
3438268Ssteve.reinhardt@amd.com
3448268Ssteve.reinhardt@amd.comExport('main')
3453718Sstever@eecs.umich.edu
3462634Sstever@eecs.umich.edumain.SConsignFile(joinpath(build_root, "sconsign"))
3472634Sstever@eecs.umich.edu
3485863Snate@binkert.org# Default duplicate option is to use hard links, but this messes up
3492638Sstever@eecs.umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
3508268Ssteve.reinhardt@amd.com# file to file~ then copies to file, breaking the link.  Symbolic
3512632Sstever@eecs.umich.edu# (soft) links work better.
3522632Sstever@eecs.umich.edumain.SetOption('duplicate', 'soft-copy')
3532632Sstever@eecs.umich.edu
3542632Sstever@eecs.umich.edu#
3552632Sstever@eecs.umich.edu# Set up global sticky variables... these are common to an entire build
3561858SN/A# tree (not specific to a particular build like ALPHA_SE)
3573716Sstever@eecs.umich.edu#
3582638Sstever@eecs.umich.edu
3592638Sstever@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
3602638Sstever@eecs.umich.edu
3612638Sstever@eecs.umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3622638Sstever@eecs.umich.edu
3632638Sstever@eecs.umich.eduglobal_vars.AddVariables(
3642638Sstever@eecs.umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3655863Snate@binkert.org    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3665863Snate@binkert.org    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
3675863Snate@binkert.org    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
368955SN/A    ('BATCH', 'Use batch pool for build and tests', False),
3695341Sstever@gmail.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3705341Sstever@gmail.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
3715863Snate@binkert.org    ('EXTRAS', 'Add extra directories to the compilation', '')
3727756SAli.Saidi@ARM.com    )
3735341Sstever@gmail.com
3746121Snate@binkert.org# Update main environment with values from ARGUMENTS & global_vars_file
3754494Ssaidi@eecs.umich.eduglobal_vars.Update(main)
3766121Snate@binkert.orghelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3771105SN/A
3782667Sstever@eecs.umich.edu# Save sticky variable settings back to current variables file
3792667Sstever@eecs.umich.eduglobal_vars.Save(global_vars_file, main)
3802667Sstever@eecs.umich.edu
3812667Sstever@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
3826121Snate@binkert.org# look for sources etc.  This list is exported as extras_dir_list.
3832667Sstever@eecs.umich.edubase_dir = main.srcdir.abspath
3845341Sstever@gmail.comif main['EXTRAS']:
3855863Snate@binkert.org    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
3865341Sstever@gmail.comelse:
3875341Sstever@gmail.com    extras_dir_list = []
3885341Sstever@gmail.com
3898120Sgblack@eecs.umich.eduExport('base_dir')
3905341Sstever@gmail.comExport('extras_dir_list')
3918120Sgblack@eecs.umich.edu
3925341Sstever@gmail.com# the ext directory should be on the #includes path
3938120Sgblack@eecs.umich.edumain.Append(CPPPATH=[Dir('ext')])
3946121Snate@binkert.org
3956121Snate@binkert.orgdef strip_build_path(path, env):
3968980Ssteve.reinhardt@amd.com    path = str(path)
3979396Sandreas.hansson@arm.com    variant_base = env['BUILDROOT'] + os.path.sep
3985397Ssaidi@eecs.umich.edu    if path.startswith(variant_base):
3995397Ssaidi@eecs.umich.edu        path = path[len(variant_base):]
4007727SAli.Saidi@ARM.com    elif path.startswith('build/'):
4018268Ssteve.reinhardt@amd.com        path = path[6:]
4026168Snate@binkert.org    return path
4035341Sstever@gmail.com
4048120Sgblack@eecs.umich.edu# Generate a string of the form:
4058120Sgblack@eecs.umich.edu#   common/path/prefix/src1, src2 -> tgt1, tgt2
4068120Sgblack@eecs.umich.edu# to print while building.
4076814Sgblack@eecs.umich.educlass Transform(object):
4085863Snate@binkert.org    # all specific color settings should be here and nowhere else
4098120Sgblack@eecs.umich.edu    tool_color = termcap.Normal
4105341Sstever@gmail.com    pfx_color = termcap.Yellow
4115863Snate@binkert.org    srcs_color = termcap.Yellow + termcap.Bold
4128268Ssteve.reinhardt@amd.com    arrow_color = termcap.Blue + termcap.Bold
4136121Snate@binkert.org    tgts_color = termcap.Yellow + termcap.Bold
4146121Snate@binkert.org
4158268Ssteve.reinhardt@amd.com    def __init__(self, tool, max_sources=99):
4165742Snate@binkert.org        self.format = self.tool_color + (" [%8s] " % tool) \
4175742Snate@binkert.org                      + self.pfx_color + "%s" \
4185341Sstever@gmail.com                      + self.srcs_color + "%s" \
4195742Snate@binkert.org                      + self.arrow_color + " -> " \
4205742Snate@binkert.org                      + self.tgts_color + "%s" \
4215341Sstever@gmail.com                      + termcap.Normal
4226017Snate@binkert.org        self.max_sources = max_sources
4236121Snate@binkert.org
4246017Snate@binkert.org    def __call__(self, target, source, env, for_signature=None):
4257816Ssteve.reinhardt@amd.com        # truncate source list according to max_sources param
4267756SAli.Saidi@ARM.com        source = source[0:self.max_sources]
4277756SAli.Saidi@ARM.com        def strip(f):
4287756SAli.Saidi@ARM.com            return strip_build_path(str(f), env)
4297756SAli.Saidi@ARM.com        if len(source) > 0:
4307756SAli.Saidi@ARM.com            srcs = map(strip, source)
4317756SAli.Saidi@ARM.com        else:
4327756SAli.Saidi@ARM.com            srcs = ['']
4337756SAli.Saidi@ARM.com        tgts = map(strip, target)
4347816Ssteve.reinhardt@amd.com        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4357816Ssteve.reinhardt@amd.com        # operation that has nothing to do with paths.
4367816Ssteve.reinhardt@amd.com        com_pfx = os.path.commonprefix(srcs + tgts)
4377816Ssteve.reinhardt@amd.com        com_pfx_len = len(com_pfx)
4387816Ssteve.reinhardt@amd.com        if com_pfx:
4397816Ssteve.reinhardt@amd.com            # do some cleanup and sanity checking on common prefix
4407816Ssteve.reinhardt@amd.com            if com_pfx[-1] == ".":
4417816Ssteve.reinhardt@amd.com                # prefix matches all but file extension: ok
4427816Ssteve.reinhardt@amd.com                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4437816Ssteve.reinhardt@amd.com                com_pfx = com_pfx[0:-1]
4447756SAli.Saidi@ARM.com            elif com_pfx[-1] == "/":
4457816Ssteve.reinhardt@amd.com                # common prefix is directory path: OK
4467816Ssteve.reinhardt@amd.com                pass
4477816Ssteve.reinhardt@amd.com            else:
4487816Ssteve.reinhardt@amd.com                src0_len = len(srcs[0])
4497816Ssteve.reinhardt@amd.com                tgt0_len = len(tgts[0])
4507816Ssteve.reinhardt@amd.com                if src0_len == com_pfx_len:
4517816Ssteve.reinhardt@amd.com                    # source is a substring of target, OK
4527816Ssteve.reinhardt@amd.com                    pass
4537816Ssteve.reinhardt@amd.com                elif tgt0_len == com_pfx_len:
4547816Ssteve.reinhardt@amd.com                    # target is a substring of source, need to back up to
4557816Ssteve.reinhardt@amd.com                    # avoid empty string on RHS of arrow
4567816Ssteve.reinhardt@amd.com                    sep_idx = com_pfx.rfind(".")
4577816Ssteve.reinhardt@amd.com                    if sep_idx != -1:
4587816Ssteve.reinhardt@amd.com                        com_pfx = com_pfx[0:sep_idx]
4597816Ssteve.reinhardt@amd.com                    else:
4607816Ssteve.reinhardt@amd.com                        com_pfx = ''
4617816Ssteve.reinhardt@amd.com                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4627816Ssteve.reinhardt@amd.com                    # still splitting at file extension: ok
4637816Ssteve.reinhardt@amd.com                    pass
4647816Ssteve.reinhardt@amd.com                else:
4657816Ssteve.reinhardt@amd.com                    # probably a fluke; ignore it
4667816Ssteve.reinhardt@amd.com                    com_pfx = ''
4677816Ssteve.reinhardt@amd.com        # recalculate length in case com_pfx was modified
4687816Ssteve.reinhardt@amd.com        com_pfx_len = len(com_pfx)
4697816Ssteve.reinhardt@amd.com        def fmt(files):
4707816Ssteve.reinhardt@amd.com            f = map(lambda s: s[com_pfx_len:], files)
4717816Ssteve.reinhardt@amd.com            return ', '.join(f)
4727816Ssteve.reinhardt@amd.com        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
4737816Ssteve.reinhardt@amd.com
4747816Ssteve.reinhardt@amd.comExport('Transform')
4757816Ssteve.reinhardt@amd.com
4767816Ssteve.reinhardt@amd.com# enable the regression script to use the termcap
4777816Ssteve.reinhardt@amd.commain['TERMCAP'] = termcap
4787816Ssteve.reinhardt@amd.com
4797816Ssteve.reinhardt@amd.comif GetOption('verbose'):
4807816Ssteve.reinhardt@amd.com    def MakeAction(action, string, *args, **kwargs):
4817816Ssteve.reinhardt@amd.com        return Action(action, *args, **kwargs)
4827816Ssteve.reinhardt@amd.comelse:
4837816Ssteve.reinhardt@amd.com    MakeAction = Action
4847816Ssteve.reinhardt@amd.com    main['CCCOMSTR']        = Transform("CC")
4857816Ssteve.reinhardt@amd.com    main['CXXCOMSTR']       = Transform("CXX")
4867816Ssteve.reinhardt@amd.com    main['ASCOMSTR']        = Transform("AS")
4877816Ssteve.reinhardt@amd.com    main['SWIGCOMSTR']      = Transform("SWIG")
4887816Ssteve.reinhardt@amd.com    main['ARCOMSTR']        = Transform("AR", 0)
4897816Ssteve.reinhardt@amd.com    main['LINKCOMSTR']      = Transform("LINK", 0)
4907816Ssteve.reinhardt@amd.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
4917816Ssteve.reinhardt@amd.com    main['M4COMSTR']        = Transform("M4")
4927816Ssteve.reinhardt@amd.com    main['SHCCCOMSTR']      = Transform("SHCC")
4937816Ssteve.reinhardt@amd.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
4947816Ssteve.reinhardt@amd.comExport('MakeAction')
4957816Ssteve.reinhardt@amd.com
4967816Ssteve.reinhardt@amd.com# Initialize the Link-Time Optimization (LTO) flags
4977816Ssteve.reinhardt@amd.commain['LTO_CCFLAGS'] = []
4987816Ssteve.reinhardt@amd.commain['LTO_LDFLAGS'] = []
4997816Ssteve.reinhardt@amd.com
5007816Ssteve.reinhardt@amd.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5017816Ssteve.reinhardt@amd.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5027816Ssteve.reinhardt@amd.com
5037816Ssteve.reinhardt@amd.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5047816Ssteve.reinhardt@amd.commain['SUNCC'] = CXX_V and CXX_V.find('Sun C++') >= 0
5057816Ssteve.reinhardt@amd.commain['ICC'] = CXX_V and CXX_V.find('Intel') >= 0
5068947Sandreas.hansson@arm.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5078947Sandreas.hansson@arm.comif main['GCC'] + main['SUNCC'] + main['ICC'] + main['CLANG'] > 1:
5087756SAli.Saidi@ARM.com    print 'Error: How can we have two at the same time?'
5098120Sgblack@eecs.umich.edu    Exit(1)
5107756SAli.Saidi@ARM.com
5117756SAli.Saidi@ARM.com# Set up default C++ compiler flags
5127756SAli.Saidi@ARM.comif main['GCC']:
5137756SAli.Saidi@ARM.com    main.Append(CCFLAGS=['-pipe'])
5147816Ssteve.reinhardt@amd.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5157816Ssteve.reinhardt@amd.com    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5167816Ssteve.reinhardt@amd.com    # Read the GCC version to check for versions with bugs
5177816Ssteve.reinhardt@amd.com    # Note CCVERSION doesn't work here because it is run with the CC
5187816Ssteve.reinhardt@amd.com    # before we override it from the command line
5197816Ssteve.reinhardt@amd.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5207816Ssteve.reinhardt@amd.com    main['GCC_VERSION'] = gcc_version
5217816Ssteve.reinhardt@amd.com    if not compareVersions(gcc_version, '4.4.1') or \
5227816Ssteve.reinhardt@amd.com       not compareVersions(gcc_version, '4.4.2'):
5237816Ssteve.reinhardt@amd.com        print 'Info: Tree vectorizer in GCC 4.4.1 & 4.4.2 is buggy, disabling.'
5247756SAli.Saidi@ARM.com        main.Append(CCFLAGS=['-fno-tree-vectorize'])
5257756SAli.Saidi@ARM.com    # c++0x support in gcc is useful already from 4.4, see
5269227Sandreas.hansson@arm.com    # http://gcc.gnu.org/projects/cxx0x.html for details
5279227Sandreas.hansson@arm.com    if compareVersions(gcc_version, '4.4') >= 0:
5289227Sandreas.hansson@arm.com        main.Append(CXXFLAGS=['-std=c++0x'])
5299227Sandreas.hansson@arm.com
5309590Sandreas@sandberg.pp.se    # LTO support is only really working properly from 4.6 and beyond
5319590Sandreas@sandberg.pp.se    if compareVersions(gcc_version, '4.6') >= 0:
5329590Sandreas@sandberg.pp.se        # Add the appropriate Link-Time Optimization (LTO) flags
5339590Sandreas@sandberg.pp.se        # unless LTO is explicitly turned off. Note that these flags
5349590Sandreas@sandberg.pp.se        # are only used by the fast target.
5359590Sandreas@sandberg.pp.se        if not GetOption('no_lto'):
5366654Snate@binkert.org            # Pass the LTO flag when compiling to produce GIMPLE
5376654Snate@binkert.org            # output, we merely create the flags here and only append
5385871Snate@binkert.org            # them later/
5396121Snate@binkert.org            main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
5408946Sandreas.hansson@arm.com
5419419Sandreas.hansson@arm.com            # Use the same amount of jobs for LTO as we are running
5423940Ssaidi@eecs.umich.edu            # scons with, we hardcode the use of the linker plugin
5433918Ssaidi@eecs.umich.edu            # which requires either gold or GNU ld >= 2.21
5443918Ssaidi@eecs.umich.edu            main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs'),
5451858SN/A                                   '-fuse-linker-plugin']
5469556Sandreas.hansson@arm.com
5479556Sandreas.hansson@arm.comelif main['ICC']:
5489556Sandreas.hansson@arm.com    pass #Fix me... add warning flags once we clean up icc warnings
5499556Sandreas.hansson@arm.comelif main['SUNCC']:
5509556Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-Qoption ccfe'])
5519556Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-features=gcc'])
5529556Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-features=extensions'])
5539556Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-library=stlport4'])
5549556Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-xar'])
5559556Sandreas.hansson@arm.com    #main.Append(CCFLAGS=['-instances=semiexplicit'])
5569556Sandreas.hansson@arm.comelif main['CLANG']:
5579556Sandreas.hansson@arm.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
5589556Sandreas.hansson@arm.com    clang_version_match = clang_version_re.match(CXX_version)
5599556Sandreas.hansson@arm.com    if (clang_version_match):
5609556Sandreas.hansson@arm.com        clang_version = clang_version_match.groups()[0]
5619556Sandreas.hansson@arm.com        if compareVersions(clang_version, "2.9") < 0:
5629556Sandreas.hansson@arm.com            print 'Error: clang version 2.9 or newer required.'
5639556Sandreas.hansson@arm.com            print '       Installed version:', clang_version
5649556Sandreas.hansson@arm.com            Exit(1)
5659556Sandreas.hansson@arm.com    else:
5669556Sandreas.hansson@arm.com        print 'Error: Unable to determine clang version.'
5679556Sandreas.hansson@arm.com        Exit(1)
5689556Sandreas.hansson@arm.com
5699556Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-pipe'])
5709556Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5719556Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5729556Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-Wno-tautological-compare'])
5739556Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-Wno-self-assign'])
5749556Sandreas.hansson@arm.com    # Ruby makes frequent use of extraneous parantheses in the printing
5759556Sandreas.hansson@arm.com    # of if-statements
5769556Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-Wno-parentheses'])
5779556Sandreas.hansson@arm.com
5786121Snate@binkert.org    # clang 2.9 does not play well with c++0x as it ships with C++
57910238Sandreas.hansson@arm.com    # headers that produce errors, this was fixed in 3.0
58010238Sandreas.hansson@arm.com    if compareVersions(clang_version, "3") >= 0:
58110238Sandreas.hansson@arm.com        main.Append(CXXFLAGS=['-std=c++0x'])
58210238Sandreas.hansson@arm.comelse:
5839420Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
58410238Sandreas.hansson@arm.com    print "Don't know what compiler options to use for your compiler."
58510238Sandreas.hansson@arm.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5869420Sandreas.hansson@arm.com    print termcap.Yellow + '       version:' + termcap.Normal,
5879420Sandreas.hansson@arm.com    if not CXX_version:
5889420Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5899420Sandreas.hansson@arm.com               termcap.Normal
5909420Sandreas.hansson@arm.com    else:
59110264Sandreas.hansson@arm.com        print CXX_version.replace('\n', '<nl>')
59210264Sandreas.hansson@arm.com    print "       If you're trying to use a compiler other than GCC, ICC, SunCC,"
59310264Sandreas.hansson@arm.com    print "       or clang, there appears to be something wrong with your"
59410264Sandreas.hansson@arm.com    print "       environment."
59510264Sandreas.hansson@arm.com    print "       "
59610264Sandreas.hansson@arm.com    print "       If you are trying to use a compiler other than those listed"
59710264Sandreas.hansson@arm.com    print "       above you will need to ease fix SConstruct and "
59810264Sandreas.hansson@arm.com    print "       src/SConscript to support that compiler."
59910264Sandreas.hansson@arm.com    Exit(1)
60010264Sandreas.hansson@arm.com
60110264Sandreas.hansson@arm.com# Set up common yacc/bison flags (needed for Ruby)
60210264Sandreas.hansson@arm.commain['YACCFLAGS'] = '-d'
60310264Sandreas.hansson@arm.commain['YACCHXXFILESUFFIX'] = '.hh'
60410264Sandreas.hansson@arm.com
60510264Sandreas.hansson@arm.com# Do this after we save setting back, or else we'll tack on an
60610264Sandreas.hansson@arm.com# extra 'qdo' every time we run scons.
60710457Sandreas.hansson@arm.comif main['BATCH']:
60810457Sandreas.hansson@arm.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
60910457Sandreas.hansson@arm.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
61010457Sandreas.hansson@arm.com    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
61110457Sandreas.hansson@arm.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
61210457Sandreas.hansson@arm.com    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
61310457Sandreas.hansson@arm.com
61410457Sandreas.hansson@arm.comif sys.platform == 'cygwin':
61510457Sandreas.hansson@arm.com    # cygwin has some header file issues...
61610238Sandreas.hansson@arm.com    main.Append(CCFLAGS=["-Wno-uninitialized"])
61710238Sandreas.hansson@arm.com
61810238Sandreas.hansson@arm.com# Check for the protobuf compiler
61910238Sandreas.hansson@arm.comprotoc_version = readCommand([main['PROTOC'], '--version'],
62010238Sandreas.hansson@arm.com                             exception='').split()
62110238Sandreas.hansson@arm.com
62210416Sandreas.hansson@arm.com# First two words should be "libprotoc x.y.z"
62310238Sandreas.hansson@arm.comif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6249227Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + \
62510238Sandreas.hansson@arm.com        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
62610416Sandreas.hansson@arm.com        '         Please install protobuf-compiler for tracing support.' + \
62710416Sandreas.hansson@arm.com        termcap.Normal
6289227Sandreas.hansson@arm.com    main['PROTOC'] = False
6299590Sandreas@sandberg.pp.seelse:
6309590Sandreas@sandberg.pp.se    # Determine the appropriate include path and library path using
6319590Sandreas@sandberg.pp.se    # pkg-config, that means we also need to check for pkg-config
6328737Skoansin.tan@gmail.com    if not readCommand(['pkg-config', '--version'], exception=''):
63310238Sandreas.hansson@arm.com        print 'Error: pkg-config not found. Please install and retry.'
63410238Sandreas.hansson@arm.com        Exit(1)
6359420Sandreas.hansson@arm.com
6368737Skoansin.tan@gmail.com    main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
63710106SMitch.Hayenga@arm.com
6388737Skoansin.tan@gmail.com    # Based on the availability of the compress stream wrappers,
6398737Skoansin.tan@gmail.com    # require 2.1.0
64010238Sandreas.hansson@arm.com    min_protoc_version = '2.1.0'
64110238Sandreas.hansson@arm.com    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6428737Skoansin.tan@gmail.com        print 'Error: protoc version', min_protoc_version, 'or newer required.'
6438737Skoansin.tan@gmail.com        print '       Installed version:', protoc_version[1]
6448737Skoansin.tan@gmail.com        Exit(1)
6458737Skoansin.tan@gmail.com
6468737Skoansin.tan@gmail.com# Check for SWIG
6478737Skoansin.tan@gmail.comif not main.has_key('SWIG'):
6489556Sandreas.hansson@arm.com    print 'Error: SWIG utility not found.'
6499556Sandreas.hansson@arm.com    print '       Please install (see http://www.swig.org) and retry.'
6509556Sandreas.hansson@arm.com    Exit(1)
6519556Sandreas.hansson@arm.com
6529556Sandreas.hansson@arm.com# Check for appropriate SWIG version
6539556Sandreas.hansson@arm.comswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
6549556Sandreas.hansson@arm.com# First 3 words should be "SWIG Version x.y.z"
6559556Sandreas.hansson@arm.comif len(swig_version) < 3 or \
65610278SAndreas.Sandberg@ARM.com        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
65710278SAndreas.Sandberg@ARM.com    print 'Error determining SWIG version.'
65810278SAndreas.Sandberg@ARM.com    Exit(1)
65910278SAndreas.Sandberg@ARM.com
66010278SAndreas.Sandberg@ARM.commin_swig_version = '1.3.34'
66110278SAndreas.Sandberg@ARM.comif compareVersions(swig_version[2], min_swig_version) < 0:
6629556Sandreas.hansson@arm.com    print 'Error: SWIG version', min_swig_version, 'or newer required.'
6639590Sandreas@sandberg.pp.se    print '       Installed version:', swig_version[2]
6649590Sandreas@sandberg.pp.se    Exit(1)
6659420Sandreas.hansson@arm.com
6669846Sandreas.hansson@arm.com# Set up SWIG flags & scanner
6679846Sandreas.hansson@arm.comswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
6689846Sandreas.hansson@arm.commain.Append(SWIGFLAGS=swig_flags)
6699846Sandreas.hansson@arm.com
6708946Sandreas.hansson@arm.com# filter out all existing swig scanners, they mess up the dependency
6713918Ssaidi@eecs.umich.edu# stuff for some reason
6729068SAli.Saidi@ARM.comscanners = []
6739068SAli.Saidi@ARM.comfor scanner in main['SCANNERS']:
6749068SAli.Saidi@ARM.com    skeys = scanner.skeys
6759068SAli.Saidi@ARM.com    if skeys == '.i':
6769068SAli.Saidi@ARM.com        continue
6779068SAli.Saidi@ARM.com
6789068SAli.Saidi@ARM.com    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
6799068SAli.Saidi@ARM.com        continue
6809068SAli.Saidi@ARM.com
6819419Sandreas.hansson@arm.com    scanners.append(scanner)
6829068SAli.Saidi@ARM.com
6839068SAli.Saidi@ARM.com# add the new swig scanner that we like better
6849068SAli.Saidi@ARM.comfrom SCons.Scanner import ClassicCPP as CPPScanner
6859068SAli.Saidi@ARM.comswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
6869068SAli.Saidi@ARM.comscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
6879068SAli.Saidi@ARM.com
6883918Ssaidi@eecs.umich.edu# replace the scanners list that has what we want
6893918Ssaidi@eecs.umich.edumain['SCANNERS'] = scanners
6906157Snate@binkert.org
6916157Snate@binkert.org# Add a custom Check function to the Configure context so that we can
6926157Snate@binkert.org# figure out if the compiler adds leading underscores to global
6936157Snate@binkert.org# variables.  This is needed for the autogenerated asm files that we
6945397Ssaidi@eecs.umich.edu# use for embedding the python code.
6955397Ssaidi@eecs.umich.edudef CheckLeading(context):
6966121Snate@binkert.org    context.Message("Checking for leading underscore in global variables...")
6976121Snate@binkert.org    # 1) Define a global variable called x from asm so the C compiler
6986121Snate@binkert.org    #    won't change the symbol at all.
6996121Snate@binkert.org    # 2) Declare that variable.
7006121Snate@binkert.org    # 3) Use the variable
7016121Snate@binkert.org    #
7025397Ssaidi@eecs.umich.edu    # If the compiler prepends an underscore, this will successfully
7031851SN/A    # link because the external symbol 'x' will be called '_x' which
7041851SN/A    # was defined by the asm statement.  If the compiler does not
7057739Sgblack@eecs.umich.edu    # prepend an underscore, this will not successfully link because
706955SN/A    # '_x' will have been defined by assembly, while the C portion of
7079396Sandreas.hansson@arm.com    # the code will be trying to use 'x'
7089396Sandreas.hansson@arm.com    ret = context.TryLink('''
7099396Sandreas.hansson@arm.com        asm(".globl _x; _x: .byte 0");
7109396Sandreas.hansson@arm.com        extern int x;
7119396Sandreas.hansson@arm.com        int main() { return x; }
7129396Sandreas.hansson@arm.com        ''', extension=".c")
7139396Sandreas.hansson@arm.com    context.env.Append(LEADING_UNDERSCORE=ret)
7149396Sandreas.hansson@arm.com    context.Result(ret)
7159396Sandreas.hansson@arm.com    return ret
7169396Sandreas.hansson@arm.com
7179396Sandreas.hansson@arm.com# Test for the presence of C++11 static asserts. If the compiler lacks
7189396Sandreas.hansson@arm.com# support for static asserts, base/compiler.hh enables a macro that
7199396Sandreas.hansson@arm.com# removes any static asserts in the code.
7209396Sandreas.hansson@arm.comdef CheckStaticAssert(context):
7219396Sandreas.hansson@arm.com    context.Message("Checking for C++11 static_assert support...")
7229396Sandreas.hansson@arm.com    ret = context.TryCompile('''
7239477Sandreas.hansson@arm.com        static_assert(1, "This assert is always true");
7249477Sandreas.hansson@arm.com        ''', extension=".cc")
7259477Sandreas.hansson@arm.com    context.env.Append(HAVE_STATIC_ASSERT=ret)
7269477Sandreas.hansson@arm.com    context.Result(ret)
7279477Sandreas.hansson@arm.com    return ret
7289477Sandreas.hansson@arm.com
7299477Sandreas.hansson@arm.com# Platform-specific configuration.  Note again that we assume that all
7309477Sandreas.hansson@arm.com# builds under a given build root run on the same host platform.
7319477Sandreas.hansson@arm.comconf = Configure(main,
7329477Sandreas.hansson@arm.com                 conf_dir = joinpath(build_root, '.scons_config'),
7339477Sandreas.hansson@arm.com                 log_file = joinpath(build_root, 'scons_config.log'),
7349477Sandreas.hansson@arm.com                 custom_tests = { 'CheckLeading' : CheckLeading,
7359477Sandreas.hansson@arm.com                                  'CheckStaticAssert' : CheckStaticAssert,
7369477Sandreas.hansson@arm.com                                })
7379477Sandreas.hansson@arm.com
7389477Sandreas.hansson@arm.com# Check for leading underscores.  Don't really need to worry either
7399477Sandreas.hansson@arm.com# way so don't need to check the return code.
7409477Sandreas.hansson@arm.comconf.CheckLeading()
7419477Sandreas.hansson@arm.com
7429477Sandreas.hansson@arm.com# Check for C++11 features we want to use if they exist
7439477Sandreas.hansson@arm.comconf.CheckStaticAssert()
7449477Sandreas.hansson@arm.com
7459396Sandreas.hansson@arm.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
7463053Sstever@eecs.umich.edutry:
7476121Snate@binkert.org    import platform
7483053Sstever@eecs.umich.edu    uname = platform.uname()
7493053Sstever@eecs.umich.edu    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
7503053Sstever@eecs.umich.edu        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
7513053Sstever@eecs.umich.edu            main.Append(CCFLAGS=['-arch', 'x86_64'])
7523053Sstever@eecs.umich.edu            main.Append(CFLAGS=['-arch', 'x86_64'])
7539072Sandreas.hansson@arm.com            main.Append(LINKFLAGS=['-arch', 'x86_64'])
7543053Sstever@eecs.umich.edu            main.Append(ASFLAGS=['-arch', 'x86_64'])
7554742Sstever@eecs.umich.eduexcept:
7564742Sstever@eecs.umich.edu    pass
7573053Sstever@eecs.umich.edu
7583053Sstever@eecs.umich.edu# Recent versions of scons substitute a "Null" object for Configure()
7593053Sstever@eecs.umich.edu# when configuration isn't necessary, e.g., if the "--help" option is
76010181SCurtis.Dunham@arm.com# present.  Unfortuantely this Null object always returns false,
7616654Snate@binkert.org# breaking all our configuration checks.  We replace it with our own
7623053Sstever@eecs.umich.edu# more optimistic null object that returns True instead.
7633053Sstever@eecs.umich.eduif not conf:
7643053Sstever@eecs.umich.edu    def NullCheck(*args, **kwargs):
7653053Sstever@eecs.umich.edu        return True
76610425Sandreas.hansson@arm.com
76710425Sandreas.hansson@arm.com    class NullConf:
76810425Sandreas.hansson@arm.com        def __init__(self, env):
76910425Sandreas.hansson@arm.com            self.env = env
77010425Sandreas.hansson@arm.com        def Finish(self):
77110425Sandreas.hansson@arm.com            return self.env
77210425Sandreas.hansson@arm.com        def __getattr__(self, mname):
77310425Sandreas.hansson@arm.com            return NullCheck
77410425Sandreas.hansson@arm.com
77510425Sandreas.hansson@arm.com    conf = NullConf(main)
77610425Sandreas.hansson@arm.com
7772667Sstever@eecs.umich.edu# Find Python include and library directories for embedding the
7784554Sbinkertn@umich.edu# interpreter.  For consistency, we will use the same Python
7796121Snate@binkert.org# installation used to run scons (and thus this script).  If you want
7802667Sstever@eecs.umich.edu# to link in an alternate version, see above for instructions on how
78110384SCurtis.Dunham@arm.com# to invoke scons with a different copy of the Python interpreter.
78210384SCurtis.Dunham@arm.comfrom distutils import sysconfig
78310384SCurtis.Dunham@arm.com
78410384SCurtis.Dunham@arm.compy_getvar = sysconfig.get_config_var
78510384SCurtis.Dunham@arm.com
7864554Sbinkertn@umich.edupy_debug = getattr(sys, 'pydebug', False)
7874554Sbinkertn@umich.edupy_version = 'python' + py_getvar('VERSION') + (py_debug and "_d" or "")
7884554Sbinkertn@umich.edu
7896121Snate@binkert.orgpy_general_include = sysconfig.get_python_inc()
7904554Sbinkertn@umich.edupy_platform_include = sysconfig.get_python_inc(plat_specific=True)
7914554Sbinkertn@umich.edupy_includes = [ py_general_include ]
7924554Sbinkertn@umich.eduif py_platform_include != py_general_include:
7934781Snate@binkert.org    py_includes.append(py_platform_include)
7944554Sbinkertn@umich.edu
7954554Sbinkertn@umich.edupy_lib_path = [ py_getvar('LIBDIR') ]
7962667Sstever@eecs.umich.edu# add the prefix/lib/pythonX.Y/config dir, but only if there is no
7974554Sbinkertn@umich.edu# shared library in prefix/lib/.
7984554Sbinkertn@umich.eduif not py_getvar('Py_ENABLE_SHARED'):
7994554Sbinkertn@umich.edu    py_lib_path.append(py_getvar('LIBPL'))
8004554Sbinkertn@umich.edu
8012667Sstever@eecs.umich.edupy_libs = []
8024554Sbinkertn@umich.edufor lib in py_getvar('LIBS').split() + py_getvar('SYSLIBS').split():
8032667Sstever@eecs.umich.edu    if not lib.startswith('-l'):
8044554Sbinkertn@umich.edu        # Python requires some special flags to link (e.g. -framework
8056121Snate@binkert.org        # common on OS X systems), assume appending preserves order
8062667Sstever@eecs.umich.edu        main.Append(LINKFLAGS=[lib])
8075522Snate@binkert.org    else:
8085522Snate@binkert.org        lib = lib[2:]
8095522Snate@binkert.org        if lib not in py_libs:
8105522Snate@binkert.org            py_libs.append(lib)
8115522Snate@binkert.orgpy_libs.append(py_version)
8125522Snate@binkert.org
8135522Snate@binkert.orgmain.Append(CPPPATH=py_includes)
8145522Snate@binkert.orgmain.Append(LIBPATH=py_lib_path)
8155522Snate@binkert.org
8165522Snate@binkert.org# Cache build files in the supplied directory.
8175522Snate@binkert.orgif main['M5_BUILD_CACHE']:
8185522Snate@binkert.org    print 'Using build cache located at', main['M5_BUILD_CACHE']
8195522Snate@binkert.org    CacheDir(main['M5_BUILD_CACHE'])
8205522Snate@binkert.org
8215522Snate@binkert.org
8225522Snate@binkert.org# verify that this stuff works
8235522Snate@binkert.orgif not conf.CheckHeader('Python.h', '<>'):
8245522Snate@binkert.org    print "Error: can't find Python.h header in", py_includes
8255522Snate@binkert.org    print "Install Python headers (package python-dev on Ubuntu and RedHat)"
8265522Snate@binkert.org    Exit(1)
8275522Snate@binkert.org
8285522Snate@binkert.orgfor lib in py_libs:
8295522Snate@binkert.org    if not conf.CheckLib(lib):
8305522Snate@binkert.org        print "Error: can't find library %s required by python" % lib
8315522Snate@binkert.org        Exit(1)
8325522Snate@binkert.org
8339986Sandreas@sandberg.pp.se# On Solaris you need to use libsocket for socket ops
8349986Sandreas@sandberg.pp.seif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
8359986Sandreas@sandberg.pp.se   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
8369986Sandreas@sandberg.pp.se       print "Can't find library with socket calls (e.g. accept())"
8379986Sandreas@sandberg.pp.se       Exit(1)
8389986Sandreas@sandberg.pp.se
8399986Sandreas@sandberg.pp.se# Check for zlib.  If the check passes, libz will be automatically
8409986Sandreas@sandberg.pp.se# added to the LIBS environment variable.
8419986Sandreas@sandberg.pp.seif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
8429986Sandreas@sandberg.pp.se    print 'Error: did not find needed zlib compression library '\
8439986Sandreas@sandberg.pp.se          'and/or zlib.h header file.'
8449986Sandreas@sandberg.pp.se    print '       Please install zlib and try again.'
8459986Sandreas@sandberg.pp.se    Exit(1)
8469986Sandreas@sandberg.pp.se
8479986Sandreas@sandberg.pp.se# If we have the protobuf compiler, also make sure we have the
8489986Sandreas@sandberg.pp.se# development libraries. If the check passes, libprotobuf will be
8499986Sandreas@sandberg.pp.se# automatically added to the LIBS environment variable. After
8509986Sandreas@sandberg.pp.se# this, we can use the HAVE_PROTOBUF flag to determine if we have
8519986Sandreas@sandberg.pp.se# got both protoc and libprotobuf available.
8529986Sandreas@sandberg.pp.semain['HAVE_PROTOBUF'] = main['PROTOC'] and \
8532638Sstever@eecs.umich.edu    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
8542638Sstever@eecs.umich.edu                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
8556121Snate@binkert.org
8563716Sstever@eecs.umich.edu# If we have the compiler but not the library, treat it as an error.
8575522Snate@binkert.orgif main['PROTOC'] and not main['HAVE_PROTOBUF']:
8589986Sandreas@sandberg.pp.se    print 'Error: did not find protocol buffer library and/or headers.'
8599986Sandreas@sandberg.pp.se    print '       Please install libprotobuf-dev and try again.'
8609986Sandreas@sandberg.pp.se    Exit(1)
8619986Sandreas@sandberg.pp.se
8625522Snate@binkert.org# Check for librt.
8635522Snate@binkert.orghave_posix_clock = \
8645522Snate@binkert.org    conf.CheckLibWithHeader(None, 'time.h', 'C',
8655522Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);') or \
8661858SN/A    conf.CheckLibWithHeader('rt', 'time.h', 'C',
8675227Ssaidi@eecs.umich.edu                            'clock_nanosleep(0,0,NULL,NULL);')
8685227Ssaidi@eecs.umich.edu
8695227Ssaidi@eecs.umich.eduif conf.CheckLib('tcmalloc_minimal'):
8705227Ssaidi@eecs.umich.edu    have_tcmalloc = True
8716654Snate@binkert.orgelse:
8726654Snate@binkert.org    have_tcmalloc = False
8737769SAli.Saidi@ARM.com    print termcap.Yellow + termcap.Bold + \
8747769SAli.Saidi@ARM.com          "You can get a 12% performance improvement by installing tcmalloc "\
8757769SAli.Saidi@ARM.com          "(libgoogle-perftools-dev package on Ubuntu or RedHat)." + \
8767769SAli.Saidi@ARM.com          termcap.Normal
8775227Ssaidi@eecs.umich.edu
8785227Ssaidi@eecs.umich.eduif not have_posix_clock:
8795227Ssaidi@eecs.umich.edu    print "Can't find library for POSIX clocks."
8805204Sstever@gmail.com
8815204Sstever@gmail.com# Check for <fenv.h> (C99 FP environment control)
8825204Sstever@gmail.comhave_fenv = conf.CheckHeader('fenv.h', '<>')
8835204Sstever@gmail.comif not have_fenv:
8845204Sstever@gmail.com    print "Warning: Header file <fenv.h> not found."
8855204Sstever@gmail.com    print "         This host has no IEEE FP rounding mode control."
8865204Sstever@gmail.com
8875204Sstever@gmail.com######################################################################
8885204Sstever@gmail.com#
8895204Sstever@gmail.com# Finish the configuration
8905204Sstever@gmail.com#
8915204Sstever@gmail.commain = conf.Finish()
8925204Sstever@gmail.com
8935204Sstever@gmail.com######################################################################
8945204Sstever@gmail.com#
8955204Sstever@gmail.com# Collect all non-global variables
8965204Sstever@gmail.com#
8976121Snate@binkert.org
8985204Sstever@gmail.com# Define the universe of supported ISAs
8997727SAli.Saidi@ARM.comall_isa_list = [ ]
9007727SAli.Saidi@ARM.comExport('all_isa_list')
9017727SAli.Saidi@ARM.com
9027727SAli.Saidi@ARM.comclass CpuModel(object):
9037727SAli.Saidi@ARM.com    '''The CpuModel class encapsulates everything the ISA parser needs to
90410453SAndrew.Bardsley@arm.com    know about a particular CPU model.'''
90510453SAndrew.Bardsley@arm.com
90610453SAndrew.Bardsley@arm.com    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
90710453SAndrew.Bardsley@arm.com    dict = {}
90810453SAndrew.Bardsley@arm.com    list = []
90910453SAndrew.Bardsley@arm.com    defaults = []
91010453SAndrew.Bardsley@arm.com
91110453SAndrew.Bardsley@arm.com    # Constructor.  Automatically adds models to CpuModel.dict.
91210453SAndrew.Bardsley@arm.com    def __init__(self, name, filename, includes, strings, default=False):
91310453SAndrew.Bardsley@arm.com        self.name = name           # name of model
91410453SAndrew.Bardsley@arm.com        self.filename = filename   # filename for output exec code
91510160Sandreas.hansson@arm.com        self.includes = includes   # include files needed in exec file
91610453SAndrew.Bardsley@arm.com        # The 'strings' dict holds all the per-CPU symbols we can
91710453SAndrew.Bardsley@arm.com        # substitute into templates etc.
91810453SAndrew.Bardsley@arm.com        self.strings = strings
91910453SAndrew.Bardsley@arm.com
92010453SAndrew.Bardsley@arm.com        # This cpu is enabled by default
92110453SAndrew.Bardsley@arm.com        self.default = default
92210453SAndrew.Bardsley@arm.com
92310453SAndrew.Bardsley@arm.com        # Add self to dict
9249812Sandreas.hansson@arm.com        if name in CpuModel.dict:
92510453SAndrew.Bardsley@arm.com            raise AttributeError, "CpuModel '%s' already registered" % name
92610453SAndrew.Bardsley@arm.com        CpuModel.dict[name] = self
92710453SAndrew.Bardsley@arm.com        CpuModel.list.append(name)
92810453SAndrew.Bardsley@arm.com
92910453SAndrew.Bardsley@arm.comExport('CpuModel')
93010453SAndrew.Bardsley@arm.com
93110453SAndrew.Bardsley@arm.com# Sticky variables get saved in the variables file so they persist from
93210453SAndrew.Bardsley@arm.com# one invocation to the next (unless overridden, in which case the new
93310453SAndrew.Bardsley@arm.com# value becomes sticky).
93410453SAndrew.Bardsley@arm.comsticky_vars = Variables(args=ARGUMENTS)
93510453SAndrew.Bardsley@arm.comExport('sticky_vars')
93610453SAndrew.Bardsley@arm.com
9377727SAli.Saidi@ARM.com# Sticky variables that should be exported
93810453SAndrew.Bardsley@arm.comexport_vars = []
93910453SAndrew.Bardsley@arm.comExport('export_vars')
94010453SAndrew.Bardsley@arm.com
94110453SAndrew.Bardsley@arm.com# For Ruby
94210453SAndrew.Bardsley@arm.comall_protocols = []
9433118Sstever@eecs.umich.eduExport('all_protocols')
94410453SAndrew.Bardsley@arm.comprotocol_dirs = []
94510453SAndrew.Bardsley@arm.comExport('protocol_dirs')
94610453SAndrew.Bardsley@arm.comslicc_includes = []
94710453SAndrew.Bardsley@arm.comExport('slicc_includes')
9483118Sstever@eecs.umich.edu
9493483Ssaidi@eecs.umich.edu# Walk the tree and execute all SConsopts scripts that wil add to the
9503494Ssaidi@eecs.umich.edu# above variables
9513494Ssaidi@eecs.umich.eduif not GetOption('verbose'):
9523483Ssaidi@eecs.umich.edu    print "Reading SConsopts"
9533483Ssaidi@eecs.umich.edufor bdir in [ base_dir ] + extras_dir_list:
9543483Ssaidi@eecs.umich.edu    if not isdir(bdir):
9553053Sstever@eecs.umich.edu        print "Error: directory '%s' does not exist" % bdir
9563053Sstever@eecs.umich.edu        Exit(1)
9573918Ssaidi@eecs.umich.edu    for root, dirs, files in os.walk(bdir):
9583053Sstever@eecs.umich.edu        if 'SConsopts' in files:
9593053Sstever@eecs.umich.edu            if GetOption('verbose'):
9603053Sstever@eecs.umich.edu                print "Reading", joinpath(root, 'SConsopts')
9613053Sstever@eecs.umich.edu            SConscript(joinpath(root, 'SConsopts'))
9623053Sstever@eecs.umich.edu
9639396Sandreas.hansson@arm.comall_isa_list.sort()
9649396Sandreas.hansson@arm.com
9659396Sandreas.hansson@arm.comsticky_vars.AddVariables(
9669396Sandreas.hansson@arm.com    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
9679396Sandreas.hansson@arm.com    ListVariable('CPU_MODELS', 'CPU models',
9689396Sandreas.hansson@arm.com                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
9699396Sandreas.hansson@arm.com                 sorted(CpuModel.list)),
9709396Sandreas.hansson@arm.com    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
9719396Sandreas.hansson@arm.com                 False),
9729477Sandreas.hansson@arm.com    BoolVariable('SS_COMPATIBLE_FP',
9739396Sandreas.hansson@arm.com                 'Make floating-point results compatible with SimpleScalar',
9749477Sandreas.hansson@arm.com                 False),
9759477Sandreas.hansson@arm.com    BoolVariable('USE_SSE2',
9769477Sandreas.hansson@arm.com                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
9779477Sandreas.hansson@arm.com                 False),
9789396Sandreas.hansson@arm.com    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
9797840Snate@binkert.org    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
9807865Sgblack@eecs.umich.edu    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
9817865Sgblack@eecs.umich.edu    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
9827865Sgblack@eecs.umich.edu                  all_protocols),
9837865Sgblack@eecs.umich.edu    )
9847865Sgblack@eecs.umich.edu
9857840Snate@binkert.org# These variables get exported to #defines in config/*.hh (see src/SConscript).
9869900Sandreas@sandberg.pp.seexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP',
9879900Sandreas@sandberg.pp.se                'TARGET_ISA', 'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'PROTOCOL',
9889900Sandreas@sandberg.pp.se                'HAVE_STATIC_ASSERT', 'HAVE_PROTOBUF']
9899900Sandreas@sandberg.pp.se
99010456SCurtis.Dunham@arm.com###################################################
99110456SCurtis.Dunham@arm.com#
99210456SCurtis.Dunham@arm.com# Define a SCons builder for configuration flag headers.
99310456SCurtis.Dunham@arm.com#
99410456SCurtis.Dunham@arm.com###################################################
99510456SCurtis.Dunham@arm.com
99610456SCurtis.Dunham@arm.com# This function generates a config header file that #defines the
99710456SCurtis.Dunham@arm.com# variable symbol to the current variable setting (0 or 1).  The source
99810456SCurtis.Dunham@arm.com# operands are the name of the variable and a Value node containing the
99910456SCurtis.Dunham@arm.com# value of the variable.
10009045SAli.Saidi@ARM.comdef build_config_file(target, source, env):
10017840Snate@binkert.org    (variable, value) = [s.get_contents() for s in source]
10027840Snate@binkert.org    f = file(str(target[0]), 'w')
10037840Snate@binkert.org    print >> f, '#define', variable, value
10041858SN/A    f.close()
10051858SN/A    return None
10061858SN/A
10071858SN/A# Combine the two functions into a scons Action object.
10081858SN/Aconfig_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
10091858SN/A
10109903Sandreas.hansson@arm.com# The emitter munges the source & target node lists to reflect what
10119903Sandreas.hansson@arm.com# we're really doing.
10129903Sandreas.hansson@arm.comdef config_emitter(target, source, env):
10139903Sandreas.hansson@arm.com    # extract variable name from Builder arg
10149903Sandreas.hansson@arm.com    variable = str(target[0])
10159903Sandreas.hansson@arm.com    # True target is config header file
10169651SAndreas.Sandberg@ARM.com    target = joinpath('config', variable.lower() + '.hh')
10179903Sandreas.hansson@arm.com    val = env[variable]
10189651SAndreas.Sandberg@ARM.com    if isinstance(val, bool):
10199651SAndreas.Sandberg@ARM.com        # Force value to 0/1
10209651SAndreas.Sandberg@ARM.com        val = int(val)
10219651SAndreas.Sandberg@ARM.com    elif isinstance(val, str):
10229651SAndreas.Sandberg@ARM.com        val = '"' + val + '"'
10239657Sandreas.sandberg@arm.com
10249883Sandreas@sandberg.pp.se    # Sources are variable name & value (packaged in SCons Value nodes)
10259651SAndreas.Sandberg@ARM.com    return ([target], [Value(variable), Value(val)])
10269651SAndreas.Sandberg@ARM.com
10279651SAndreas.Sandberg@ARM.comconfig_builder = Builder(emitter = config_emitter, action = config_action)
10289651SAndreas.Sandberg@ARM.com
10299651SAndreas.Sandberg@ARM.commain.Append(BUILDERS = { 'ConfigFile' : config_builder })
10309651SAndreas.Sandberg@ARM.com
10319651SAndreas.Sandberg@ARM.com# libelf build is shared across all configs in the build root.
10329651SAndreas.Sandberg@ARM.commain.SConscript('ext/libelf/SConscript',
10339651SAndreas.Sandberg@ARM.com                variant_dir = joinpath(build_root, 'libelf'))
10349651SAndreas.Sandberg@ARM.com
10359651SAndreas.Sandberg@ARM.com# gzstream build is shared across all configs in the build root.
10369986Sandreas@sandberg.pp.semain.SConscript('ext/gzstream/SConscript',
10379986Sandreas@sandberg.pp.se                variant_dir = joinpath(build_root, 'gzstream'))
10389986Sandreas@sandberg.pp.se
10399986Sandreas@sandberg.pp.se###################################################
10409986Sandreas@sandberg.pp.se#
10419986Sandreas@sandberg.pp.se# This function is used to set up a directory with switching headers
10425863Snate@binkert.org#
10435863Snate@binkert.org###################################################
10445863Snate@binkert.org
10455863Snate@binkert.orgmain['ALL_ISA_LIST'] = all_isa_list
10466121Snate@binkert.orgdef make_switching_dir(dname, switch_headers, env):
10471858SN/A    # Generate the header.  target[0] is the full path of the output
10485863Snate@binkert.org    # header to generate.  'source' is a dummy variable, since we get the
10495863Snate@binkert.org    # list of ISAs from env['ALL_ISA_LIST'].
10505863Snate@binkert.org    def gen_switch_hdr(target, source, env):
10515863Snate@binkert.org        fname = str(target[0])
10525863Snate@binkert.org        f = open(fname, 'w')
10532139SN/A        isa = env['TARGET_ISA'].lower()
10544202Sbinkertn@umich.edu        print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
10554202Sbinkertn@umich.edu        f.close()
10562139SN/A
10576994Snate@binkert.org    # Build SCons Action object. 'varlist' specifies env vars that this
10586994Snate@binkert.org    # action depends on; when env['ALL_ISA_LIST'] changes these actions
10596994Snate@binkert.org    # should get re-executed.
10606994Snate@binkert.org    switch_hdr_action = MakeAction(gen_switch_hdr,
10616994Snate@binkert.org                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
10626994Snate@binkert.org
10636994Snate@binkert.org    # Instantiate actions for each header
10646994Snate@binkert.org    for hdr in switch_headers:
106510319SAndreas.Sandberg@ARM.com        env.Command(hdr, [], switch_hdr_action)
10666994Snate@binkert.orgExport('make_switching_dir')
10676994Snate@binkert.org
10686994Snate@binkert.org###################################################
10696994Snate@binkert.org#
10706994Snate@binkert.org# Define build environments for selected configurations.
10716994Snate@binkert.org#
10726994Snate@binkert.org###################################################
10736994Snate@binkert.org
10746994Snate@binkert.orgfor variant_path in variant_paths:
10756994Snate@binkert.org    print "Building in", variant_path
10766994Snate@binkert.org
10772155SN/A    # Make a copy of the build-root environment to use for this config.
10785863Snate@binkert.org    env = main.Clone()
10791869SN/A    env['BUILDDIR'] = variant_path
10801869SN/A
10815863Snate@binkert.org    # variant_dir is the tail component of build path, and is used to
10825863Snate@binkert.org    # determine the build parameters (e.g., 'ALPHA_SE')
10834202Sbinkertn@umich.edu    (build_root, variant_dir) = splitpath(variant_path)
10846108Snate@binkert.org
10856108Snate@binkert.org    # Set env variables according to the build directory config.
10866108Snate@binkert.org    sticky_vars.files = []
10876108Snate@binkert.org    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
10889219Spower.jg@gmail.com    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
10899219Spower.jg@gmail.com    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
10909219Spower.jg@gmail.com    current_vars_file = joinpath(build_root, 'variables', variant_dir)
10919219Spower.jg@gmail.com    if isfile(current_vars_file):
10929219Spower.jg@gmail.com        sticky_vars.files.append(current_vars_file)
10939219Spower.jg@gmail.com        print "Using saved variables file %s" % current_vars_file
10949219Spower.jg@gmail.com    else:
10959219Spower.jg@gmail.com        # Build dir-specific variables file doesn't exist.
10964202Sbinkertn@umich.edu
10975863Snate@binkert.org        # Make sure the directory is there so we can create it later
109810135SCurtis.Dunham@arm.com        opt_dir = dirname(current_vars_file)
10998474Sgblack@eecs.umich.edu        if not isdir(opt_dir):
11005742Snate@binkert.org            mkdir(opt_dir)
11018268Ssteve.reinhardt@amd.com
11028268Ssteve.reinhardt@amd.com        # Get default build variables from source tree.  Variables are
11038268Ssteve.reinhardt@amd.com        # normally determined by name of $VARIANT_DIR, but can be
11045742Snate@binkert.org        # overridden by '--default=' arg on command line.
11055341Sstever@gmail.com        default = GetOption('default')
11068474Sgblack@eecs.umich.edu        opts_dir = joinpath(main.root.abspath, 'build_opts')
11078474Sgblack@eecs.umich.edu        if default:
11085342Sstever@gmail.com            default_vars_files = [joinpath(build_root, 'variables', default),
11094202Sbinkertn@umich.edu                                  joinpath(opts_dir, default)]
11104202Sbinkertn@umich.edu        else:
11114202Sbinkertn@umich.edu            default_vars_files = [joinpath(opts_dir, variant_dir)]
11125863Snate@binkert.org        existing_files = filter(isfile, default_vars_files)
11135863Snate@binkert.org        if existing_files:
11146994Snate@binkert.org            default_vars_file = existing_files[0]
11156994Snate@binkert.org            sticky_vars.files.append(default_vars_file)
111610319SAndreas.Sandberg@ARM.com            print "Variables file %s not found,\n  using defaults in %s" \
11175863Snate@binkert.org                  % (current_vars_file, default_vars_file)
11185863Snate@binkert.org        else:
11195863Snate@binkert.org            print "Error: cannot find variables file %s or " \
11205863Snate@binkert.org                  "default file(s) %s" \
11215863Snate@binkert.org                  % (current_vars_file, ' or '.join(default_vars_files))
11225863Snate@binkert.org            Exit(1)
11235863Snate@binkert.org
11245863Snate@binkert.org    # Apply current variable settings to env
11257840Snate@binkert.org    sticky_vars.Update(env)
11265863Snate@binkert.org
11275952Ssaidi@eecs.umich.edu    help_texts["local_vars"] += \
11289651SAndreas.Sandberg@ARM.com        "Build variables for %s:\n" % variant_dir \
11299219Spower.jg@gmail.com                 + sticky_vars.GenerateHelpText(env)
11309219Spower.jg@gmail.com
11311869SN/A    # Process variable settings.
11321858SN/A
11335863Snate@binkert.org    if not have_fenv and env['USE_FENV']:
11349420Sandreas.hansson@arm.com        print "Warning: <fenv.h> not available; " \
11359986Sandreas@sandberg.pp.se              "forcing USE_FENV to False in", variant_dir + "."
11369986Sandreas@sandberg.pp.se        env['USE_FENV'] = False
11371858SN/A
1138955SN/A    if not env['USE_FENV']:
1139955SN/A        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
11401869SN/A        print "         FP results may deviate slightly from other platforms."
11411869SN/A
11421869SN/A    if env['EFENCE']:
11431869SN/A        env.Append(LIBS=['efence'])
11441869SN/A
11455863Snate@binkert.org    # Save sticky variable settings back to current variables file
11465863Snate@binkert.org    sticky_vars.Save(current_vars_file, env)
11475863Snate@binkert.org
11481869SN/A    if env['USE_SSE2']:
11495863Snate@binkert.org        env.Append(CCFLAGS=['-msse2'])
11501869SN/A
11515863Snate@binkert.org    if have_tcmalloc:
11521869SN/A        env.Append(LIBS=['tcmalloc_minimal'])
11531869SN/A
11541869SN/A    # The src/SConscript file sets up the build rules in 'env' according
11551869SN/A    # to the configured variables.  It returns a list of environments,
11568483Sgblack@eecs.umich.edu    # one for each variant build (debug, opt, etc.)
11571869SN/A    envList = SConscript('src/SConscript', variant_dir = variant_path,
11581869SN/A                         exports = 'env')
11591869SN/A
11601869SN/A    # Set up the regression tests for each build.
11615863Snate@binkert.org    for e in envList:
11625863Snate@binkert.org        SConscript('tests/SConscript',
11631869SN/A                   variant_dir = joinpath(variant_path, 'tests', e.Label),
11645863Snate@binkert.org                   exports = { 'env' : e }, duplicate = False)
11655863Snate@binkert.org
11663356Sbinkertn@umich.edu# base help text
11673356Sbinkertn@umich.eduHelp('''
11683356Sbinkertn@umich.eduUsage: scons [scons options] [build variables] [target(s)]
11693356Sbinkertn@umich.edu
11703356Sbinkertn@umich.eduExtra scons options:
11714781Snate@binkert.org%(options)s
11725863Snate@binkert.org
11735863Snate@binkert.orgGlobal build variables:
11741869SN/A%(global_vars)s
11751869SN/A
11761869SN/A%(local_vars)s
11776121Snate@binkert.org''' % help_texts)
11781869SN/A