SConstruct revision 11401
1955SN/A# -*- mode:python -*-
2955SN/A
312230Sgiacomo.travaglini@arm.com# Copyright (c) 2013, 2015 ARM Limited
49812Sandreas.hansson@arm.com# All rights reserved.
59812Sandreas.hansson@arm.com#
69812Sandreas.hansson@arm.com# The license below extends only to copyright in the software and shall
79812Sandreas.hansson@arm.com# not be construed as granting a license to any other intellectual
89812Sandreas.hansson@arm.com# property including but not limited to intellectual property relating
99812Sandreas.hansson@arm.com# to a hardware implementation of the functionality of the software
109812Sandreas.hansson@arm.com# licensed hereunder.  You may use the software subject to the license
119812Sandreas.hansson@arm.com# terms below provided that you ensure that this notice is replicated
129812Sandreas.hansson@arm.com# unmodified and in its entirety in all distributions of the software,
139812Sandreas.hansson@arm.com# modified or unmodified, in source code or in binary form.
149812Sandreas.hansson@arm.com#
157816Ssteve.reinhardt@amd.com# Copyright (c) 2011 Advanced Micro Devices, Inc.
165871Snate@binkert.org# Copyright (c) 2009 The Hewlett-Packard Development Company
171762SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
18955SN/A# All rights reserved.
19955SN/A#
20955SN/A# Redistribution and use in source and binary forms, with or without
21955SN/A# modification, are permitted provided that the following conditions are
22955SN/A# met: redistributions of source code must retain the above copyright
23955SN/A# notice, this list of conditions and the following disclaimer;
24955SN/A# redistributions in binary form must reproduce the above copyright
25955SN/A# notice, this list of conditions and the following disclaimer in the
26955SN/A# documentation and/or other materials provided with the distribution;
27955SN/A# neither the name of the copyright holders nor the names of its
28955SN/A# contributors may be used to endorse or promote products derived from
29955SN/A# this software without specific prior written permission.
30955SN/A#
31955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
41955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
422665Ssaidi@eecs.umich.edu#
432665Ssaidi@eecs.umich.edu# Authors: Steve Reinhardt
445863Snate@binkert.org#          Nathan Binkert
45955SN/A
46955SN/A###################################################
47955SN/A#
48955SN/A# SCons top-level build description (SConstruct) file.
49955SN/A#
508878Ssteve.reinhardt@amd.com# While in this directory ('gem5'), just type 'scons' to build the default
512632Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
528878Ssteve.reinhardt@amd.com# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
532632Sstever@eecs.umich.edu# the optimized full-system version).
54955SN/A#
558878Ssteve.reinhardt@amd.com# You can build gem5 in a different directory as long as there is a
562632Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
572761Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
582632Sstever@eecs.umich.edu# built for the same host system.
592632Sstever@eecs.umich.edu#
602632Sstever@eecs.umich.edu# Examples:
612761Sstever@eecs.umich.edu#
622761Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
632761Sstever@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
648878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
658878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
662761Sstever@eecs.umich.edu#
672761Sstever@eecs.umich.edu#   The following two commands are equivalent and demonstrate building
682761Sstever@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
692761Sstever@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
702761Sstever@eecs.umich.edu#   file.
718878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
728878Ssteve.reinhardt@amd.com#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
732632Sstever@eecs.umich.edu#
742632Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
758878Ssteve.reinhardt@amd.com# 'gem5' directory (or use -u or -C to tell scons where to find this
768878Ssteve.reinhardt@amd.com# file), you can use 'scons -h' to print all the gem5-specific build
772632Sstever@eecs.umich.edu# options as well.
78955SN/A#
79955SN/A###################################################
80955SN/A
8112563Sgabeblack@google.com# Check for recent-enough Python and SCons versions.
8212563Sgabeblack@google.comtry:
836654Snate@binkert.org    # Really old versions of scons only take two options for the
8410196SCurtis.Dunham@arm.com    # function, so check once without the revision and once with the
85955SN/A    # revision, the first instance will fail for stuff other than
865396Ssaidi@eecs.umich.edu    # 0.98, and the second will fail for 0.98.0
8711401Sandreas.sandberg@arm.com    EnsureSConsVersion(0, 98)
885863Snate@binkert.org    EnsureSConsVersion(0, 98, 1)
895863Snate@binkert.orgexcept SystemExit, e:
904202Sbinkertn@umich.edu    print """
915863Snate@binkert.orgFor more details, see:
925863Snate@binkert.org    http://gem5.org/Dependencies
935863Snate@binkert.org"""
945863Snate@binkert.org    raise
95955SN/A
966654Snate@binkert.org# We ensure the python version early because because python-config
975273Sstever@gmail.com# requires python 2.5
985871Snate@binkert.orgtry:
995273Sstever@gmail.com    EnsurePythonVersion(2, 5)
1006654Snate@binkert.orgexcept SystemExit, e:
1015396Ssaidi@eecs.umich.edu    print """
1028120Sgblack@eecs.umich.eduYou can use a non-default installation of the Python interpreter by
1038120Sgblack@eecs.umich.edurearranging your PATH so that scons finds the non-default 'python' and
1048120Sgblack@eecs.umich.edu'python-config' first.
1058120Sgblack@eecs.umich.edu
1068120Sgblack@eecs.umich.eduFor more details, see:
1078120Sgblack@eecs.umich.edu    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1088120Sgblack@eecs.umich.edu"""
1098120Sgblack@eecs.umich.edu    raise
1108879Ssteve.reinhardt@amd.com
1118879Ssteve.reinhardt@amd.com# Global Python includes
1128879Ssteve.reinhardt@amd.comimport itertools
1138879Ssteve.reinhardt@amd.comimport os
1148879Ssteve.reinhardt@amd.comimport re
1158879Ssteve.reinhardt@amd.comimport shutil
1168879Ssteve.reinhardt@amd.comimport subprocess
1178879Ssteve.reinhardt@amd.comimport sys
1188879Ssteve.reinhardt@amd.com
1198879Ssteve.reinhardt@amd.comfrom os import mkdir, environ
1208879Ssteve.reinhardt@amd.comfrom os.path import abspath, basename, dirname, expanduser, normpath
1218879Ssteve.reinhardt@amd.comfrom os.path import exists,  isdir, isfile
1228879Ssteve.reinhardt@amd.comfrom os.path import join as joinpath, split as splitpath
1238120Sgblack@eecs.umich.edu
1248120Sgblack@eecs.umich.edu# SCons includes
1258120Sgblack@eecs.umich.eduimport SCons
1268120Sgblack@eecs.umich.eduimport SCons.Node
1278120Sgblack@eecs.umich.edu
1288120Sgblack@eecs.umich.eduextra_python_paths = [
1298120Sgblack@eecs.umich.edu    Dir('src/python').srcnode().abspath, # gem5 includes
1308120Sgblack@eecs.umich.edu    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1318120Sgblack@eecs.umich.edu    ]
1328120Sgblack@eecs.umich.edu
1338120Sgblack@eecs.umich.edusys.path[1:1] = extra_python_paths
1348120Sgblack@eecs.umich.edu
1358120Sgblack@eecs.umich.edufrom m5.util import compareVersions, readCommand
1368120Sgblack@eecs.umich.edufrom m5.util.terminal import get_termcap
1378879Ssteve.reinhardt@amd.com
1388879Ssteve.reinhardt@amd.comhelp_texts = {
1398879Ssteve.reinhardt@amd.com    "options" : "",
1408879Ssteve.reinhardt@amd.com    "global_vars" : "",
14110458Sandreas.hansson@arm.com    "local_vars" : ""
14210458Sandreas.hansson@arm.com}
14310458Sandreas.hansson@arm.com
1448879Ssteve.reinhardt@amd.comExport("help_texts")
1458879Ssteve.reinhardt@amd.com
1468879Ssteve.reinhardt@amd.com
1478879Ssteve.reinhardt@amd.com# There's a bug in scons in that (1) by default, the help texts from
1489227Sandreas.hansson@arm.com# AddOption() are supposed to be displayed when you type 'scons -h'
1499227Sandreas.hansson@arm.com# and (2) you can override the help displayed by 'scons -h' using the
15012063Sgabeblack@google.com# Help() function, but these two features are incompatible: once
15112063Sgabeblack@google.com# you've overridden the help text using Help(), there's no way to get
15212063Sgabeblack@google.com# at the help texts from AddOptions.  See:
1538879Ssteve.reinhardt@amd.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1548879Ssteve.reinhardt@amd.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1558879Ssteve.reinhardt@amd.com# This hack lets us extract the help text from AddOptions and
1568879Ssteve.reinhardt@amd.com# re-inject it via Help().  Ideally someday this bug will be fixed and
15710453SAndrew.Bardsley@arm.com# we can just use AddOption directly.
15810453SAndrew.Bardsley@arm.comdef AddLocalOption(*args, **kwargs):
15910453SAndrew.Bardsley@arm.com    col_width = 30
16010456SCurtis.Dunham@arm.com
16110456SCurtis.Dunham@arm.com    help = "  " + ", ".join(args)
16210456SCurtis.Dunham@arm.com    if "help" in kwargs:
16310457Sandreas.hansson@arm.com        length = len(help)
16410457Sandreas.hansson@arm.com        if length >= col_width:
16511342Sandreas.hansson@arm.com            help += "\n" + " " * col_width
16611342Sandreas.hansson@arm.com        else:
1678120Sgblack@eecs.umich.edu            help += " " * (col_width - length)
16812063Sgabeblack@google.com        help += kwargs["help"]
16912563Sgabeblack@google.com    help_texts["options"] += help + "\n"
17012063Sgabeblack@google.com
17112063Sgabeblack@google.com    AddOption(*args, **kwargs)
1725871Snate@binkert.org
1735871Snate@binkert.orgAddLocalOption('--colors', dest='use_colors', action='store_true',
1746121Snate@binkert.org               help="Add color to abbreviated scons output")
1755871Snate@binkert.orgAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1765871Snate@binkert.org               help="Don't add color to abbreviated scons output")
1779926Sstan.czerniawski@arm.comAddLocalOption('--with-cxx-config', dest='with_cxx_config',
17812243Sgabeblack@google.com               action='store_true',
1791533SN/A               help="Build with support for C++-based configuration")
18012246Sgabeblack@google.comAddLocalOption('--default', dest='default', type='string', action='store',
18112246Sgabeblack@google.com               help='Override which build_opts file to use for defaults')
18212246Sgabeblack@google.comAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
18312246Sgabeblack@google.com               help='Disable style checking hooks')
1849239Sandreas.hansson@arm.comAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1859239Sandreas.hansson@arm.com               help='Disable Link-Time Optimization for fast')
1869239Sandreas.hansson@arm.comAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1879239Sandreas.hansson@arm.com               help='Update test reference outputs')
18812563Sgabeblack@google.comAddLocalOption('--verbose', dest='verbose', action='store_true',
1899239Sandreas.hansson@arm.com               help='Print full tool command lines')
1909239Sandreas.hansson@arm.comAddLocalOption('--without-python', dest='without_python',
191955SN/A               action='store_true',
192955SN/A               help='Build without Python configuration support')
1932632Sstever@eecs.umich.eduAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1942632Sstever@eecs.umich.edu               action='store_true',
195955SN/A               help='Disable linking against tcmalloc')
196955SN/AAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
197955SN/A               help='Build with Undefined Behavior Sanitizer if available')
198955SN/AAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1998878Ssteve.reinhardt@amd.com               help='Build with Address Sanitizer if available')
200955SN/A
2012632Sstever@eecs.umich.edutermcap = get_termcap(GetOption('use_colors'))
2022632Sstever@eecs.umich.edu
2032632Sstever@eecs.umich.edu########################################################################
2042632Sstever@eecs.umich.edu#
2052632Sstever@eecs.umich.edu# Set up the main build environment.
2062632Sstever@eecs.umich.edu#
2072632Sstever@eecs.umich.edu########################################################################
2088268Ssteve.reinhardt@amd.com
2098268Ssteve.reinhardt@amd.com# export TERM so that clang reports errors in color
2108268Ssteve.reinhardt@amd.comuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
2118268Ssteve.reinhardt@amd.com                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
2128268Ssteve.reinhardt@amd.com                 'PYTHONPATH', 'RANLIB', 'SWIG', 'TERM' ])
2138268Ssteve.reinhardt@amd.com
2148268Ssteve.reinhardt@amd.comuse_prefixes = [
2152632Sstever@eecs.umich.edu    "ASAN_",           # address sanitizer symbolizer path and settings
2162632Sstever@eecs.umich.edu    "CCACHE_",         # ccache (caching compiler wrapper) configuration
2172632Sstever@eecs.umich.edu    "CCC_",            # clang static analyzer configuration
2182632Sstever@eecs.umich.edu    "DISTCC_",         # distcc (distributed compiler wrapper) configuration
2198268Ssteve.reinhardt@amd.com    "INCLUDE_SERVER_", # distcc pump server settings
2202632Sstever@eecs.umich.edu    "M5",              # M5 configuration (e.g., path to kernels)
2218268Ssteve.reinhardt@amd.com    ]
2228268Ssteve.reinhardt@amd.com
2238268Ssteve.reinhardt@amd.comuse_env = {}
2248268Ssteve.reinhardt@amd.comfor key,val in sorted(os.environ.iteritems()):
2253718Sstever@eecs.umich.edu    if key in use_vars or \
2262634Sstever@eecs.umich.edu            any([key.startswith(prefix) for prefix in use_prefixes]):
2272634Sstever@eecs.umich.edu        use_env[key] = val
2285863Snate@binkert.org
2292638Sstever@eecs.umich.edu# Tell scons to avoid implicit command dependencies to avoid issues
2308268Ssteve.reinhardt@amd.com# with the param wrappes being compiled twice (see
2312632Sstever@eecs.umich.edu# http://scons.tigris.org/issues/show_bug.cgi?id=2811)
2322632Sstever@eecs.umich.edumain = Environment(ENV=use_env, IMPLICIT_COMMAND_DEPENDENCIES=0)
2332632Sstever@eecs.umich.edumain.Decider('MD5-timestamp')
2342632Sstever@eecs.umich.edumain.root = Dir(".")         # The current directory (where this file lives).
23512563Sgabeblack@google.commain.srcdir = Dir("src")     # The source directory
2361858SN/A
2373716Sstever@eecs.umich.edumain_dict_keys = main.Dictionary().keys()
2382638Sstever@eecs.umich.edu
2392638Sstever@eecs.umich.edu# Check that we have a C/C++ compiler
2402638Sstever@eecs.umich.eduif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2412638Sstever@eecs.umich.edu    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
24212563Sgabeblack@google.com    Exit(1)
24312563Sgabeblack@google.com
2442638Sstever@eecs.umich.edu# Check that swig is present
2455863Snate@binkert.orgif not 'SWIG' in main_dict_keys:
2465863Snate@binkert.org    print "swig is not installed (package swig on Ubuntu and RedHat)"
2475863Snate@binkert.org    Exit(1)
248955SN/A
2495341Sstever@gmail.com# add useful python code PYTHONPATH so it can be used by subprocesses
2505341Sstever@gmail.com# as well
2515863Snate@binkert.orgmain.AppendENVPath('PYTHONPATH', extra_python_paths)
2527756SAli.Saidi@ARM.com
2535341Sstever@gmail.com########################################################################
2546121Snate@binkert.org#
2554494Ssaidi@eecs.umich.edu# Mercurial Stuff.
2566121Snate@binkert.org#
2571105SN/A# If the gem5 directory is a mercurial repository, we should do some
2582667Sstever@eecs.umich.edu# extra things.
2592667Sstever@eecs.umich.edu#
2602667Sstever@eecs.umich.edu########################################################################
2612667Sstever@eecs.umich.edu
2626121Snate@binkert.orghgdir = main.root.Dir(".hg")
2632667Sstever@eecs.umich.edu
2645341Sstever@gmail.commercurial_style_message = """
2655863Snate@binkert.orgYou're missing the gem5 style hook, which automatically checks your code
2665341Sstever@gmail.comagainst the gem5 style rules on hg commit and qrefresh commands.  This
2675341Sstever@gmail.comscript will now install the hook in your .hg/hgrc file.
2685341Sstever@gmail.comPress enter to continue, or ctrl-c to abort: """
2698120Sgblack@eecs.umich.edu
2705341Sstever@gmail.commercurial_style_upgrade_message = """
2718120Sgblack@eecs.umich.eduYour Mercurial style hooks are not up-to-date. This script will now
2725341Sstever@gmail.comtry to automatically update them. A backup of your hgrc will be saved
2738120Sgblack@eecs.umich.eduin .hg/hgrc.old.
2746121Snate@binkert.orgPress enter to continue, or ctrl-c to abort: """
2756121Snate@binkert.org
2769396Sandreas.hansson@arm.commercurial_style_hook = """
2775397Ssaidi@eecs.umich.edu# The following lines were automatically added by gem5/SConstruct
2785397Ssaidi@eecs.umich.edu# to provide the gem5 style-checking hooks
2797727SAli.Saidi@ARM.com[extensions]
2808268Ssteve.reinhardt@amd.comhgstyle = %s/util/hgstyle.py
2816168Snate@binkert.org
2825341Sstever@gmail.com[hooks]
2838120Sgblack@eecs.umich.edupretxncommit.style = python:hgstyle.check_style
2848120Sgblack@eecs.umich.edupre-qrefresh.style = python:hgstyle.check_style
2858120Sgblack@eecs.umich.edu# End of SConstruct additions
2866814Sgblack@eecs.umich.edu
2875863Snate@binkert.org""" % (main.root.abspath)
2888120Sgblack@eecs.umich.edu
2895341Sstever@gmail.commercurial_lib_not_found = """
2905863Snate@binkert.orgMercurial libraries cannot be found, ignoring style hook.  If
2918268Ssteve.reinhardt@amd.comyou are a gem5 developer, please fix this and run the style
2926121Snate@binkert.orghook. It is important.
2936121Snate@binkert.org"""
2948268Ssteve.reinhardt@amd.com
2955742Snate@binkert.org# Check for style hook and prompt for installation if it's not there.
2965742Snate@binkert.org# Skip this if --ignore-style was specified, there's no .hg dir to
2975341Sstever@gmail.com# install a hook in, or there's no interactive terminal to prompt.
2985742Snate@binkert.orgif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2995742Snate@binkert.org    style_hook = True
3005341Sstever@gmail.com    style_hooks = tuple()
3016017Snate@binkert.org    hgrc = hgdir.File('hgrc')
3026121Snate@binkert.org    hgrc_old = hgdir.File('hgrc.old')
3036017Snate@binkert.org    try:
30412158Sandreas.sandberg@arm.com        from mercurial import ui
30512158Sandreas.sandberg@arm.com        ui = ui.ui()
30612158Sandreas.sandberg@arm.com        ui.readconfig(hgrc.abspath)
3078120Sgblack@eecs.umich.edu        style_hooks = (ui.config('hooks', 'pretxncommit.style', None),
3087756SAli.Saidi@ARM.com                       ui.config('hooks', 'pre-qrefresh.style', None))
3097756SAli.Saidi@ARM.com        style_hook = all(style_hooks)
3107756SAli.Saidi@ARM.com        style_extension = ui.config('extensions', 'style', None)
3117756SAli.Saidi@ARM.com    except ImportError:
3127816Ssteve.reinhardt@amd.com        print mercurial_lib_not_found
3137816Ssteve.reinhardt@amd.com
3147816Ssteve.reinhardt@amd.com    if "python:style.check_style" in style_hooks:
3157816Ssteve.reinhardt@amd.com        # Try to upgrade the style hooks
3167816Ssteve.reinhardt@amd.com        print mercurial_style_upgrade_message
31711979Sgabeblack@google.com        # continue unless user does ctrl-c/ctrl-d etc.
3187816Ssteve.reinhardt@amd.com        try:
3197816Ssteve.reinhardt@amd.com            raw_input()
3207816Ssteve.reinhardt@amd.com        except:
3217816Ssteve.reinhardt@amd.com            print "Input exception, exiting scons.\n"
3227756SAli.Saidi@ARM.com            sys.exit(1)
3237756SAli.Saidi@ARM.com        shutil.copyfile(hgrc.abspath, hgrc_old.abspath)
3249227Sandreas.hansson@arm.com        re_style_hook = re.compile(r"^([^=#]+)\.style\s*=\s*([^#\s]+).*")
3259227Sandreas.hansson@arm.com        re_style_extension = re.compile("style\s*=\s*([^#\s]+).*")
3269227Sandreas.hansson@arm.com        with open(hgrc_old.abspath, 'r') as old, \
3279227Sandreas.hansson@arm.com             open(hgrc.abspath, 'w') as new:
3289590Sandreas@sandberg.pp.se
3299590Sandreas@sandberg.pp.se            for l in old:
3309590Sandreas@sandberg.pp.se                m_hook = re_style_hook.match(l)
3319590Sandreas@sandberg.pp.se                m_ext = re_style_extension.match(l)
3329590Sandreas@sandberg.pp.se                if m_hook:
3339590Sandreas@sandberg.pp.se                    hook, check = m_hook.groups()
3346654Snate@binkert.org                    if check != "python:style.check_style":
3356654Snate@binkert.org                        print "Warning: %s.style is using a non-default " \
3365871Snate@binkert.org                            "checker: %s" % (hook, check)
3376121Snate@binkert.org                    if hook not in ("pretxncommit", "pre-qrefresh"):
3388946Sandreas.hansson@arm.com                        print "Warning: Updating unknown style hook: %s" % hook
3399419Sandreas.hansson@arm.com
34012563Sgabeblack@google.com                    l = "%s.style = python:hgstyle.check_style\n" % hook
3413918Ssaidi@eecs.umich.edu                elif m_ext and m_ext.group(1) == style_extension:
3423918Ssaidi@eecs.umich.edu                    l = "hgstyle = %s/util/hgstyle.py\n" % main.root.abspath
3431858SN/A
3449556Sandreas.hansson@arm.com                new.write(l)
3459556Sandreas.hansson@arm.com    elif not style_hook:
3469556Sandreas.hansson@arm.com        print mercurial_style_message,
3479556Sandreas.hansson@arm.com        # continue unless user does ctrl-c/ctrl-d etc.
34811294Sandreas.hansson@arm.com        try:
34911294Sandreas.hansson@arm.com            raw_input()
35011294Sandreas.hansson@arm.com        except:
35111294Sandreas.hansson@arm.com            print "Input exception, exiting scons.\n"
35210878Sandreas.hansson@arm.com            sys.exit(1)
35310878Sandreas.hansson@arm.com        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
35411811Sbaz21@cam.ac.uk        print "Adding style hook to", hgrc_path, "\n"
35511811Sbaz21@cam.ac.uk        try:
35611811Sbaz21@cam.ac.uk            with open(hgrc_path, 'a') as f:
35711982Sgabeblack@google.com                f.write(mercurial_style_hook)
35811982Sgabeblack@google.com        except:
35911982Sgabeblack@google.com            print "Error updating", hgrc_path
36011982Sgabeblack@google.com            sys.exit(1)
36111992Sgabeblack@google.com
36211982Sgabeblack@google.com
36311982Sgabeblack@google.com###################################################
36412305Sgabeblack@google.com#
36512305Sgabeblack@google.com# Figure out which configurations to set up based on the path(s) of
36612305Sgabeblack@google.com# the target(s).
36712305Sgabeblack@google.com#
36812305Sgabeblack@google.com###################################################
36912305Sgabeblack@google.com
37012305Sgabeblack@google.com# Find default configuration & binary.
3719556Sandreas.hansson@arm.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
37212563Sgabeblack@google.com
37312563Sgabeblack@google.com# helper function: find last occurrence of element in list
37412563Sgabeblack@google.comdef rfind(l, elt, offs = -1):
37512563Sgabeblack@google.com    for i in range(len(l)+offs, 0, -1):
3769556Sandreas.hansson@arm.com        if l[i] == elt:
37712563Sgabeblack@google.com            return i
37812563Sgabeblack@google.com    raise ValueError, "element not found"
3799556Sandreas.hansson@arm.com
38012563Sgabeblack@google.com# Take a list of paths (or SCons Nodes) and return a list with all
38112563Sgabeblack@google.com# paths made absolute and ~-expanded.  Paths will be interpreted
38212563Sgabeblack@google.com# relative to the launch directory unless a different root is provided
38312563Sgabeblack@google.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
38412563Sgabeblack@google.com    return [abspath(joinpath(root, expanduser(str(p))))
38512563Sgabeblack@google.com            for p in path_list]
38612563Sgabeblack@google.com
38712563Sgabeblack@google.com# Each target must have 'build' in the interior of the path; the
3889556Sandreas.hansson@arm.com# directory below this will determine the build parameters.  For
3899556Sandreas.hansson@arm.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3906121Snate@binkert.org# recognize that ALPHA_SE specifies the configuration because it
39111500Sandreas.hansson@arm.com# follow 'build' in the build path.
39210238Sandreas.hansson@arm.com
39310878Sandreas.hansson@arm.com# The funky assignment to "[:]" is needed to replace the list contents
3949420Sandreas.hansson@arm.com# in place rather than reassign the symbol to a new list, which
39511500Sandreas.hansson@arm.com# doesn't work (obviously!).
39612563Sgabeblack@google.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
39712563Sgabeblack@google.com
3989420Sandreas.hansson@arm.com# Generate a list of the unique build roots and configs that the
3999420Sandreas.hansson@arm.com# collected targets reference.
4009420Sandreas.hansson@arm.comvariant_paths = []
4019420Sandreas.hansson@arm.combuild_root = None
40212063Sgabeblack@google.comfor t in BUILD_TARGETS:
40312063Sgabeblack@google.com    path_dirs = t.split('/')
40412063Sgabeblack@google.com    try:
40512063Sgabeblack@google.com        build_top = rfind(path_dirs, 'build', -2)
40612063Sgabeblack@google.com    except:
40712063Sgabeblack@google.com        print "Error: no non-leaf 'build' dir found on target path", t
40812063Sgabeblack@google.com        Exit(1)
40912063Sgabeblack@google.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
41012063Sgabeblack@google.com    if not build_root:
41112063Sgabeblack@google.com        build_root = this_build_root
41212063Sgabeblack@google.com    else:
41312063Sgabeblack@google.com        if this_build_root != build_root:
41412063Sgabeblack@google.com            print "Error: build targets not under same build root\n"\
41512063Sgabeblack@google.com                  "  %s\n  %s" % (build_root, this_build_root)
41612063Sgabeblack@google.com            Exit(1)
41712063Sgabeblack@google.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
41812063Sgabeblack@google.com    if variant_path not in variant_paths:
41912063Sgabeblack@google.com        variant_paths.append(variant_path)
42012063Sgabeblack@google.com
42112063Sgabeblack@google.com# Make sure build_root exists (might not if this is the first build there)
42212063Sgabeblack@google.comif not isdir(build_root):
42312063Sgabeblack@google.com    mkdir(build_root)
42410264Sandreas.hansson@arm.commain['BUILDROOT'] = build_root
42510264Sandreas.hansson@arm.com
42610264Sandreas.hansson@arm.comExport('main')
42710264Sandreas.hansson@arm.com
42811925Sgabeblack@google.commain.SConsignFile(joinpath(build_root, "sconsign"))
42911925Sgabeblack@google.com
43011500Sandreas.hansson@arm.com# Default duplicate option is to use hard links, but this messes up
43110264Sandreas.hansson@arm.com# when you use emacs to edit a file in the target dir, as emacs moves
43211500Sandreas.hansson@arm.com# file to file~ then copies to file, breaking the link.  Symbolic
43311500Sandreas.hansson@arm.com# (soft) links work better.
43411500Sandreas.hansson@arm.commain.SetOption('duplicate', 'soft-copy')
43511500Sandreas.hansson@arm.com
43610866Sandreas.hansson@arm.com#
43711500Sandreas.hansson@arm.com# Set up global sticky variables... these are common to an entire build
43812563Sgabeblack@google.com# tree (not specific to a particular build like ALPHA_SE)
43912563Sgabeblack@google.com#
44012563Sgabeblack@google.com
44112563Sgabeblack@google.comglobal_vars_file = joinpath(build_root, 'variables.global')
44212563Sgabeblack@google.com
44312563Sgabeblack@google.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
44410264Sandreas.hansson@arm.com
44510457Sandreas.hansson@arm.comglobal_vars.AddVariables(
44610457Sandreas.hansson@arm.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
44710457Sandreas.hansson@arm.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
44810457Sandreas.hansson@arm.com    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
44910457Sandreas.hansson@arm.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
45012563Sgabeblack@google.com    ('BATCH', 'Use batch pool for build and tests', False),
45112563Sgabeblack@google.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
45212563Sgabeblack@google.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
45310457Sandreas.hansson@arm.com    ('EXTRAS', 'Add extra directories to the compilation', '')
45412063Sgabeblack@google.com    )
45512063Sgabeblack@google.com
45612063Sgabeblack@google.com# Update main environment with values from ARGUMENTS & global_vars_file
45712563Sgabeblack@google.comglobal_vars.Update(main)
45812563Sgabeblack@google.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
45912563Sgabeblack@google.com
46012563Sgabeblack@google.com# Save sticky variable settings back to current variables file
46112563Sgabeblack@google.comglobal_vars.Save(global_vars_file, main)
46212563Sgabeblack@google.com
46312063Sgabeblack@google.com# Parse EXTRAS variable to build list of all directories where we're
46412063Sgabeblack@google.com# look for sources etc.  This list is exported as extras_dir_list.
46510238Sandreas.hansson@arm.combase_dir = main.srcdir.abspath
46610238Sandreas.hansson@arm.comif main['EXTRAS']:
46710238Sandreas.hansson@arm.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
46812063Sgabeblack@google.comelse:
46910238Sandreas.hansson@arm.com    extras_dir_list = []
47010238Sandreas.hansson@arm.com
47110416Sandreas.hansson@arm.comExport('base_dir')
47210238Sandreas.hansson@arm.comExport('extras_dir_list')
4739227Sandreas.hansson@arm.com
47410238Sandreas.hansson@arm.com# the ext directory should be on the #includes path
47510416Sandreas.hansson@arm.commain.Append(CPPPATH=[Dir('ext')])
47610416Sandreas.hansson@arm.com
4779227Sandreas.hansson@arm.comdef strip_build_path(path, env):
4789590Sandreas@sandberg.pp.se    path = str(path)
4799590Sandreas@sandberg.pp.se    variant_base = env['BUILDROOT'] + os.path.sep
4809590Sandreas@sandberg.pp.se    if path.startswith(variant_base):
48111497SMatteo.Andreozzi@arm.com        path = path[len(variant_base):]
48211497SMatteo.Andreozzi@arm.com    elif path.startswith('build/'):
48311497SMatteo.Andreozzi@arm.com        path = path[6:]
48411497SMatteo.Andreozzi@arm.com    return path
48512304Sgabeblack@google.com
48612304Sgabeblack@google.com# Generate a string of the form:
48712304Sgabeblack@google.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
48812304Sgabeblack@google.com# to print while building.
48912304Sgabeblack@google.comclass Transform(object):
49012304Sgabeblack@google.com    # all specific color settings should be here and nowhere else
49112304Sgabeblack@google.com    tool_color = termcap.Normal
49212304Sgabeblack@google.com    pfx_color = termcap.Yellow
49312304Sgabeblack@google.com    srcs_color = termcap.Yellow + termcap.Bold
49412304Sgabeblack@google.com    arrow_color = termcap.Blue + termcap.Bold
49512304Sgabeblack@google.com    tgts_color = termcap.Yellow + termcap.Bold
49612304Sgabeblack@google.com
49712304Sgabeblack@google.com    def __init__(self, tool, max_sources=99):
49812304Sgabeblack@google.com        self.format = self.tool_color + (" [%8s] " % tool) \
49912304Sgabeblack@google.com                      + self.pfx_color + "%s" \
50012304Sgabeblack@google.com                      + self.srcs_color + "%s" \
50112304Sgabeblack@google.com                      + self.arrow_color + " -> " \
50212304Sgabeblack@google.com                      + self.tgts_color + "%s" \
50312304Sgabeblack@google.com                      + termcap.Normal
5048737Skoansin.tan@gmail.com        self.max_sources = max_sources
50510878Sandreas.hansson@arm.com
50611500Sandreas.hansson@arm.com    def __call__(self, target, source, env, for_signature=None):
5079420Sandreas.hansson@arm.com        # truncate source list according to max_sources param
5088737Skoansin.tan@gmail.com        source = source[0:self.max_sources]
50910106SMitch.Hayenga@arm.com        def strip(f):
5108737Skoansin.tan@gmail.com            return strip_build_path(str(f), env)
5118737Skoansin.tan@gmail.com        if len(source) > 0:
51210878Sandreas.hansson@arm.com            srcs = map(strip, source)
51312563Sgabeblack@google.com        else:
51412563Sgabeblack@google.com            srcs = ['']
5158737Skoansin.tan@gmail.com        tgts = map(strip, target)
5168737Skoansin.tan@gmail.com        # surprisingly, os.path.commonprefix is a dumb char-by-char string
51712563Sgabeblack@google.com        # operation that has nothing to do with paths.
5188737Skoansin.tan@gmail.com        com_pfx = os.path.commonprefix(srcs + tgts)
5198737Skoansin.tan@gmail.com        com_pfx_len = len(com_pfx)
52011294Sandreas.hansson@arm.com        if com_pfx:
5219556Sandreas.hansson@arm.com            # do some cleanup and sanity checking on common prefix
5229556Sandreas.hansson@arm.com            if com_pfx[-1] == ".":
5239556Sandreas.hansson@arm.com                # prefix matches all but file extension: ok
52411294Sandreas.hansson@arm.com                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
52510278SAndreas.Sandberg@ARM.com                com_pfx = com_pfx[0:-1]
52610278SAndreas.Sandberg@ARM.com            elif com_pfx[-1] == "/":
52710278SAndreas.Sandberg@ARM.com                # common prefix is directory path: OK
52810278SAndreas.Sandberg@ARM.com                pass
52910278SAndreas.Sandberg@ARM.com            else:
53010278SAndreas.Sandberg@ARM.com                src0_len = len(srcs[0])
5319556Sandreas.hansson@arm.com                tgt0_len = len(tgts[0])
5329590Sandreas@sandberg.pp.se                if src0_len == com_pfx_len:
5339590Sandreas@sandberg.pp.se                    # source is a substring of target, OK
5349420Sandreas.hansson@arm.com                    pass
5359846Sandreas.hansson@arm.com                elif tgt0_len == com_pfx_len:
5369846Sandreas.hansson@arm.com                    # target is a substring of source, need to back up to
5379846Sandreas.hansson@arm.com                    # avoid empty string on RHS of arrow
5389846Sandreas.hansson@arm.com                    sep_idx = com_pfx.rfind(".")
5398946Sandreas.hansson@arm.com                    if sep_idx != -1:
54011811Sbaz21@cam.ac.uk                        com_pfx = com_pfx[0:sep_idx]
54111811Sbaz21@cam.ac.uk                    else:
54211811Sbaz21@cam.ac.uk                        com_pfx = ''
54311811Sbaz21@cam.ac.uk                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
54412304Sgabeblack@google.com                    # still splitting at file extension: ok
54512304Sgabeblack@google.com                    pass
54612304Sgabeblack@google.com                else:
54712304Sgabeblack@google.com                    # probably a fluke; ignore it
54812304Sgabeblack@google.com                    com_pfx = ''
54912304Sgabeblack@google.com        # recalculate length in case com_pfx was modified
55012304Sgabeblack@google.com        com_pfx_len = len(com_pfx)
55112304Sgabeblack@google.com        def fmt(files):
55212304Sgabeblack@google.com            f = map(lambda s: s[com_pfx_len:], files)
55312304Sgabeblack@google.com            return ', '.join(f)
55412304Sgabeblack@google.com        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
55512304Sgabeblack@google.com
55612304Sgabeblack@google.comExport('Transform')
55712304Sgabeblack@google.com
55812304Sgabeblack@google.com# enable the regression script to use the termcap
55912304Sgabeblack@google.commain['TERMCAP'] = termcap
5603918Ssaidi@eecs.umich.edu
56112563Sgabeblack@google.comif GetOption('verbose'):
56212563Sgabeblack@google.com    def MakeAction(action, string, *args, **kwargs):
56312563Sgabeblack@google.com        return Action(action, *args, **kwargs)
56412563Sgabeblack@google.comelse:
5659068SAli.Saidi@ARM.com    MakeAction = Action
56612563Sgabeblack@google.com    main['CCCOMSTR']        = Transform("CC")
56712563Sgabeblack@google.com    main['CXXCOMSTR']       = Transform("CXX")
5689068SAli.Saidi@ARM.com    main['ASCOMSTR']        = Transform("AS")
56912563Sgabeblack@google.com    main['SWIGCOMSTR']      = Transform("SWIG")
57012563Sgabeblack@google.com    main['ARCOMSTR']        = Transform("AR", 0)
57112563Sgabeblack@google.com    main['LINKCOMSTR']      = Transform("LINK", 0)
57212563Sgabeblack@google.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
57312563Sgabeblack@google.com    main['M4COMSTR']        = Transform("M4")
57412563Sgabeblack@google.com    main['SHCCCOMSTR']      = Transform("SHCC")
57512563Sgabeblack@google.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
57612563Sgabeblack@google.comExport('MakeAction')
5773918Ssaidi@eecs.umich.edu
5783918Ssaidi@eecs.umich.edu# Initialize the Link-Time Optimization (LTO) flags
5796157Snate@binkert.orgmain['LTO_CCFLAGS'] = []
5806157Snate@binkert.orgmain['LTO_LDFLAGS'] = []
5816157Snate@binkert.org
5826157Snate@binkert.org# According to the readme, tcmalloc works best if the compiler doesn't
5835397Ssaidi@eecs.umich.edu# assume that we're using the builtin malloc and friends. These flags
5845397Ssaidi@eecs.umich.edu# are compiler-specific, so we need to set them after we detect which
5856121Snate@binkert.org# compiler we're using.
5866121Snate@binkert.orgmain['TCMALLOC_CCFLAGS'] = []
5876121Snate@binkert.org
5886121Snate@binkert.orgCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5896121Snate@binkert.orgCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5906121Snate@binkert.org
5915397Ssaidi@eecs.umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5921851SN/Amain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5931851SN/Aif main['GCC'] + main['CLANG'] > 1:
5947739Sgblack@eecs.umich.edu    print 'Error: How can we have two at the same time?'
595955SN/A    Exit(1)
5969396Sandreas.hansson@arm.com
5979396Sandreas.hansson@arm.com# Set up default C++ compiler flags
5989396Sandreas.hansson@arm.comif main['GCC'] or main['CLANG']:
5999396Sandreas.hansson@arm.com    # As gcc and clang share many flags, do the common parts here
6009396Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-pipe'])
6019396Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
60212563Sgabeblack@google.com    # Enable -Wall and -Wextra and then disable the few warnings that
60312563Sgabeblack@google.com    # we consistently violate
60412563Sgabeblack@google.com    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
60512563Sgabeblack@google.com                         '-Wno-sign-compare', '-Wno-unused-parameter'])
6069396Sandreas.hansson@arm.com    # We always compile using C++11
6079396Sandreas.hansson@arm.com    main.Append(CXXFLAGS=['-std=c++11'])
6089396Sandreas.hansson@arm.comelse:
6099396Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6109396Sandreas.hansson@arm.com    print "Don't know what compiler options to use for your compiler."
6119396Sandreas.hansson@arm.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
61212563Sgabeblack@google.com    print termcap.Yellow + '       version:' + termcap.Normal,
61312563Sgabeblack@google.com    if not CXX_version:
61412563Sgabeblack@google.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
61512563Sgabeblack@google.com               termcap.Normal
61612563Sgabeblack@google.com    else:
6179477Sandreas.hansson@arm.com        print CXX_version.replace('\n', '<nl>')
6189477Sandreas.hansson@arm.com    print "       If you're trying to use a compiler other than GCC"
6199477Sandreas.hansson@arm.com    print "       or clang, there appears to be something wrong with your"
6209477Sandreas.hansson@arm.com    print "       environment."
6219477Sandreas.hansson@arm.com    print "       "
6229477Sandreas.hansson@arm.com    print "       If you are trying to use a compiler other than those listed"
6239477Sandreas.hansson@arm.com    print "       above you will need to ease fix SConstruct and "
6249477Sandreas.hansson@arm.com    print "       src/SConscript to support that compiler."
6259477Sandreas.hansson@arm.com    Exit(1)
6269477Sandreas.hansson@arm.com
6279477Sandreas.hansson@arm.comif main['GCC']:
6289477Sandreas.hansson@arm.com    # Check for a supported version of gcc. >= 4.7 is chosen for its
6299477Sandreas.hansson@arm.com    # level of c++11 support. See
6309477Sandreas.hansson@arm.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
63112563Sgabeblack@google.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
63212563Sgabeblack@google.com    if compareVersions(gcc_version, "4.7") < 0:
63312563Sgabeblack@google.com        print 'Error: gcc version 4.7 or newer required.'
6349396Sandreas.hansson@arm.com        print '       Installed version:', gcc_version
6352667Sstever@eecs.umich.edu        Exit(1)
63610710Sandreas.hansson@arm.com
63710710Sandreas.hansson@arm.com    main['GCC_VERSION'] = gcc_version
63810710Sandreas.hansson@arm.com
63911811Sbaz21@cam.ac.uk    # gcc from version 4.8 and above generates "rep; ret" instructions
64011811Sbaz21@cam.ac.uk    # to avoid performance penalties on certain AMD chips. Older
64111811Sbaz21@cam.ac.uk    # assemblers detect this as an error, "Error: expecting string
64211811Sbaz21@cam.ac.uk    # instruction after `rep'"
64311811Sbaz21@cam.ac.uk    if compareVersions(gcc_version, "4.8") > 0:
64411811Sbaz21@cam.ac.uk        as_version_raw = readCommand([main['AS'], '-v', '/dev/null'],
64510710Sandreas.hansson@arm.com                                     exception=False).split()
64610710Sandreas.hansson@arm.com
64710710Sandreas.hansson@arm.com        # version strings may contain extra distro-specific
64810710Sandreas.hansson@arm.com        # qualifiers, so play it safe and keep only what comes before
64910384SCurtis.Dunham@arm.com        # the first hyphen
6509986Sandreas@sandberg.pp.se        as_version = as_version_raw[-1].split('-')[0] if as_version_raw \
6519986Sandreas@sandberg.pp.se            else None
6529986Sandreas@sandberg.pp.se
6539986Sandreas@sandberg.pp.se        if not as_version or compareVersions(as_version, "2.23") < 0:
6549986Sandreas@sandberg.pp.se            print termcap.Yellow + termcap.Bold + \
6559986Sandreas@sandberg.pp.se                'Warning: This combination of gcc and binutils have' + \
6569986Sandreas@sandberg.pp.se                ' known incompatibilities.\n' + \
6579986Sandreas@sandberg.pp.se                '         If you encounter build problems, please update ' + \
6589986Sandreas@sandberg.pp.se                'binutils to 2.23.' + \
6599986Sandreas@sandberg.pp.se                termcap.Normal
6609986Sandreas@sandberg.pp.se
6619986Sandreas@sandberg.pp.se    # Make sure we warn if the user has requested to compile with the
6629986Sandreas@sandberg.pp.se    # Undefined Benahvior Sanitizer and this version of gcc does not
6639986Sandreas@sandberg.pp.se    # support it.
6649986Sandreas@sandberg.pp.se    if GetOption('with_ubsan') and \
6659986Sandreas@sandberg.pp.se            compareVersions(gcc_version, '4.9') < 0:
6669986Sandreas@sandberg.pp.se        print termcap.Yellow + termcap.Bold + \
6679986Sandreas@sandberg.pp.se            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
6689986Sandreas@sandberg.pp.se            termcap.Normal
6699986Sandreas@sandberg.pp.se
6702638Sstever@eecs.umich.edu    # Add the appropriate Link-Time Optimization (LTO) flags
6712638Sstever@eecs.umich.edu    # unless LTO is explicitly turned off. Note that these flags
6726121Snate@binkert.org    # are only used by the fast target.
6733716Sstever@eecs.umich.edu    if not GetOption('no_lto'):
6745522Snate@binkert.org        # Pass the LTO flag when compiling to produce GIMPLE
6759986Sandreas@sandberg.pp.se        # output, we merely create the flags here and only append
6769986Sandreas@sandberg.pp.se        # them later
6779986Sandreas@sandberg.pp.se        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
6785522Snate@binkert.org
6795227Ssaidi@eecs.umich.edu        # Use the same amount of jobs for LTO as we are running
6805227Ssaidi@eecs.umich.edu        # scons with
6815227Ssaidi@eecs.umich.edu        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
6825227Ssaidi@eecs.umich.edu
6836654Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
6846654Snate@binkert.org                                  '-fno-builtin-realloc', '-fno-builtin-free'])
6857769SAli.Saidi@ARM.com
6867769SAli.Saidi@ARM.comelif main['CLANG']:
6877769SAli.Saidi@ARM.com    # Check for a supported version of clang, >= 3.1 is needed to
6887769SAli.Saidi@ARM.com    # support similar features as gcc 4.7. See
6895227Ssaidi@eecs.umich.edu    # http://clang.llvm.org/cxx_status.html for details
6905227Ssaidi@eecs.umich.edu    clang_version_re = re.compile(".* version (\d+\.\d+)")
6915227Ssaidi@eecs.umich.edu    clang_version_match = clang_version_re.search(CXX_version)
6925204Sstever@gmail.com    if (clang_version_match):
6935204Sstever@gmail.com        clang_version = clang_version_match.groups()[0]
6945204Sstever@gmail.com        if compareVersions(clang_version, "3.1") < 0:
6955204Sstever@gmail.com            print 'Error: clang version 3.1 or newer required.'
6965204Sstever@gmail.com            print '       Installed version:', clang_version
6975204Sstever@gmail.com            Exit(1)
6985204Sstever@gmail.com    else:
6995204Sstever@gmail.com        print 'Error: Unable to determine clang version.'
7005204Sstever@gmail.com        Exit(1)
7015204Sstever@gmail.com
7025204Sstever@gmail.com    # clang has a few additional warnings that we disable, extraneous
7035204Sstever@gmail.com    # parantheses are allowed due to Ruby's printing of the AST,
7045204Sstever@gmail.com    # finally self assignments are allowed as the generated CPU code
7055204Sstever@gmail.com    # is relying on this
7065204Sstever@gmail.com    main.Append(CCFLAGS=['-Wno-parentheses',
7075204Sstever@gmail.com                         '-Wno-self-assign',
7085204Sstever@gmail.com                         # Some versions of libstdc++ (4.8?) seem to
7096121Snate@binkert.org                         # use struct hash and class hash
7105204Sstever@gmail.com                         # interchangeably.
7117727SAli.Saidi@ARM.com                         '-Wno-mismatched-tags',
7127727SAli.Saidi@ARM.com                         ])
71312563Sgabeblack@google.com
7147727SAli.Saidi@ARM.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
7157727SAli.Saidi@ARM.com
71611988Sandreas.sandberg@arm.com    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
71711988Sandreas.sandberg@arm.com    # opposed to libstdc++, as the later is dated.
71810453SAndrew.Bardsley@arm.com    if sys.platform == "darwin":
71910453SAndrew.Bardsley@arm.com        main.Append(CXXFLAGS=['-stdlib=libc++'])
72010453SAndrew.Bardsley@arm.com        main.Append(LIBS=['c++'])
72110453SAndrew.Bardsley@arm.com
72210453SAndrew.Bardsley@arm.comelse:
72310453SAndrew.Bardsley@arm.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
72410453SAndrew.Bardsley@arm.com    print "Don't know what compiler options to use for your compiler."
72510453SAndrew.Bardsley@arm.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
72610453SAndrew.Bardsley@arm.com    print termcap.Yellow + '       version:' + termcap.Normal,
72710453SAndrew.Bardsley@arm.com    if not CXX_version:
72810160Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
72910453SAndrew.Bardsley@arm.com               termcap.Normal
73010453SAndrew.Bardsley@arm.com    else:
73110453SAndrew.Bardsley@arm.com        print CXX_version.replace('\n', '<nl>')
73210453SAndrew.Bardsley@arm.com    print "       If you're trying to use a compiler other than GCC"
73310453SAndrew.Bardsley@arm.com    print "       or clang, there appears to be something wrong with your"
73410453SAndrew.Bardsley@arm.com    print "       environment."
73510453SAndrew.Bardsley@arm.com    print "       "
73610453SAndrew.Bardsley@arm.com    print "       If you are trying to use a compiler other than those listed"
7379812Sandreas.hansson@arm.com    print "       above you will need to ease fix SConstruct and "
73810453SAndrew.Bardsley@arm.com    print "       src/SConscript to support that compiler."
73910453SAndrew.Bardsley@arm.com    Exit(1)
74010453SAndrew.Bardsley@arm.com
74110453SAndrew.Bardsley@arm.com# Set up common yacc/bison flags (needed for Ruby)
74210453SAndrew.Bardsley@arm.commain['YACCFLAGS'] = '-d'
74310453SAndrew.Bardsley@arm.commain['YACCHXXFILESUFFIX'] = '.hh'
74410453SAndrew.Bardsley@arm.com
74510453SAndrew.Bardsley@arm.com# Do this after we save setting back, or else we'll tack on an
74610453SAndrew.Bardsley@arm.com# extra 'qdo' every time we run scons.
74710453SAndrew.Bardsley@arm.comif main['BATCH']:
74810453SAndrew.Bardsley@arm.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
74910453SAndrew.Bardsley@arm.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
7507727SAli.Saidi@ARM.com    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
75110453SAndrew.Bardsley@arm.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
75210453SAndrew.Bardsley@arm.com    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
75312563Sgabeblack@google.com
75412563Sgabeblack@google.comif sys.platform == 'cygwin':
75512563Sgabeblack@google.com    # cygwin has some header file issues...
75610453SAndrew.Bardsley@arm.com    main.Append(CCFLAGS=["-Wno-uninitialized"])
7573118Sstever@eecs.umich.edu
75810453SAndrew.Bardsley@arm.com# Check for the protobuf compiler
75910453SAndrew.Bardsley@arm.comprotoc_version = readCommand([main['PROTOC'], '--version'],
76012563Sgabeblack@google.com                             exception='').split()
76110453SAndrew.Bardsley@arm.com
7623118Sstever@eecs.umich.edu# First two words should be "libprotoc x.y.z"
7633483Ssaidi@eecs.umich.eduif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
7643494Ssaidi@eecs.umich.edu    print termcap.Yellow + termcap.Bold + \
7653494Ssaidi@eecs.umich.edu        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
76612563Sgabeblack@google.com        '         Please install protobuf-compiler for tracing support.' + \
7673483Ssaidi@eecs.umich.edu        termcap.Normal
7683483Ssaidi@eecs.umich.edu    main['PROTOC'] = False
7693053Sstever@eecs.umich.eduelse:
7703053Sstever@eecs.umich.edu    # Based on the availability of the compress stream wrappers,
7713918Ssaidi@eecs.umich.edu    # require 2.1.0
77212563Sgabeblack@google.com    min_protoc_version = '2.1.0'
77312563Sgabeblack@google.com    if compareVersions(protoc_version[1], min_protoc_version) < 0:
77412563Sgabeblack@google.com        print termcap.Yellow + termcap.Bold + \
7753053Sstever@eecs.umich.edu            'Warning: protoc version', min_protoc_version, \
7763053Sstever@eecs.umich.edu            'or newer required.\n' + \
7779396Sandreas.hansson@arm.com            '         Installed version:', protoc_version[1], \
7789396Sandreas.hansson@arm.com            termcap.Normal
7799396Sandreas.hansson@arm.com        main['PROTOC'] = False
7809396Sandreas.hansson@arm.com    else:
7819396Sandreas.hansson@arm.com        # Attempt to determine the appropriate include path and
7829396Sandreas.hansson@arm.com        # library path using pkg-config, that means we also need to
7839396Sandreas.hansson@arm.com        # check for pkg-config. Note that it is possible to use
7849396Sandreas.hansson@arm.com        # protobuf without the involvement of pkg-config. Later on we
7859396Sandreas.hansson@arm.com        # check go a library config check and at that point the test
7869477Sandreas.hansson@arm.com        # will fail if libprotobuf cannot be found.
7879396Sandreas.hansson@arm.com        if readCommand(['pkg-config', '--version'], exception=''):
78812563Sgabeblack@google.com            try:
78912563Sgabeblack@google.com                # Attempt to establish what linking flags to add for protobuf
79012563Sgabeblack@google.com                # using pkg-config
79112563Sgabeblack@google.com                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
7929396Sandreas.hansson@arm.com            except:
7937840Snate@binkert.org                print termcap.Yellow + termcap.Bold + \
7947865Sgblack@eecs.umich.edu                    'Warning: pkg-config could not get protobuf flags.' + \
7957865Sgblack@eecs.umich.edu                    termcap.Normal
7967865Sgblack@eecs.umich.edu
7977865Sgblack@eecs.umich.edu# Check for SWIG
7987865Sgblack@eecs.umich.eduif not main.has_key('SWIG'):
7997840Snate@binkert.org    print 'Error: SWIG utility not found.'
8009900Sandreas@sandberg.pp.se    print '       Please install (see http://www.swig.org) and retry.'
8019900Sandreas@sandberg.pp.se    Exit(1)
8029900Sandreas@sandberg.pp.se
8039900Sandreas@sandberg.pp.se# Check for appropriate SWIG version
80410456SCurtis.Dunham@arm.comswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
80510456SCurtis.Dunham@arm.com# First 3 words should be "SWIG Version x.y.z"
80610456SCurtis.Dunham@arm.comif len(swig_version) < 3 or \
80710456SCurtis.Dunham@arm.com        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
80810456SCurtis.Dunham@arm.com    print 'Error determining SWIG version.'
80910456SCurtis.Dunham@arm.com    Exit(1)
81012563Sgabeblack@google.com
81112563Sgabeblack@google.commin_swig_version = '2.0.4'
81212563Sgabeblack@google.comif compareVersions(swig_version[2], min_swig_version) < 0:
81312563Sgabeblack@google.com    print 'Error: SWIG version', min_swig_version, 'or newer required.'
8149045SAli.Saidi@ARM.com    print '       Installed version:', swig_version[2]
81511235Sandreas.sandberg@arm.com    Exit(1)
81611235Sandreas.sandberg@arm.com
81711235Sandreas.sandberg@arm.com# Check for known incompatibilities. The standard library shipped with
81811235Sandreas.sandberg@arm.com# gcc >= 4.9 does not play well with swig versions prior to 3.0
81911235Sandreas.sandberg@arm.comif main['GCC'] and compareVersions(gcc_version, '4.9') >= 0 and \
82012485Sjang.hanhwi@gmail.com        compareVersions(swig_version[2], '3.0') < 0:
82112485Sjang.hanhwi@gmail.com    print termcap.Yellow + termcap.Bold + \
82212485Sjang.hanhwi@gmail.com        'Warning: This combination of gcc and swig have' + \
82311235Sandreas.sandberg@arm.com        ' known incompatibilities.\n' + \
82411811Sbaz21@cam.ac.uk        '         If you encounter build problems, please update ' + \
82512485Sjang.hanhwi@gmail.com        'swig to 3.0 or later.' + \
82611811Sbaz21@cam.ac.uk        termcap.Normal
82711811Sbaz21@cam.ac.uk
82811811Sbaz21@cam.ac.uk# Set up SWIG flags & scanner
82911235Sandreas.sandberg@arm.comswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
83011235Sandreas.sandberg@arm.commain.Append(SWIGFLAGS=swig_flags)
83111235Sandreas.sandberg@arm.com
83212563Sgabeblack@google.com# Check for 'timeout' from GNU coreutils. If present, regressions will
83312563Sgabeblack@google.com# be run with a time limit. We require version 8.13 since we rely on
83412563Sgabeblack@google.com# support for the '--foreground' option.
83511235Sandreas.sandberg@arm.comtimeout_lines = readCommand(['timeout', '--version'],
8367840Snate@binkert.org                            exception='').splitlines()
83712563Sgabeblack@google.com# Get the first line and tokenize it
8387840Snate@binkert.orgtimeout_version = timeout_lines[0].split() if timeout_lines else []
8391858SN/Amain['TIMEOUT'] =  timeout_version and \
8401858SN/A    compareVersions(timeout_version[-1], '8.13') >= 0
8411858SN/A
84212563Sgabeblack@google.com# filter out all existing swig scanners, they mess up the dependency
84312563Sgabeblack@google.com# stuff for some reason
8441858SN/Ascanners = []
84512230Sgiacomo.travaglini@arm.comfor scanner in main['SCANNERS']:
84612230Sgiacomo.travaglini@arm.com    skeys = scanner.skeys
84712230Sgiacomo.travaglini@arm.com    if skeys == '.i':
84812230Sgiacomo.travaglini@arm.com        continue
84912563Sgabeblack@google.com
85012563Sgabeblack@google.com    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
85112563Sgabeblack@google.com        continue
85212230Sgiacomo.travaglini@arm.com
8539903Sandreas.hansson@arm.com    scanners.append(scanner)
8549903Sandreas.hansson@arm.com
8559903Sandreas.hansson@arm.com# add the new swig scanner that we like better
8569903Sandreas.hansson@arm.comfrom SCons.Scanner import ClassicCPP as CPPScanner
85710841Sandreas.sandberg@arm.comswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
8589651SAndreas.Sandberg@ARM.comscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
85912563Sgabeblack@google.com
86012563Sgabeblack@google.com# replace the scanners list that has what we want
8619651SAndreas.Sandberg@ARM.commain['SCANNERS'] = scanners
86212056Sgabeblack@google.com
86312056Sgabeblack@google.com# Add a custom Check function to test for structure members.
86412056Sgabeblack@google.comdef CheckMember(context, include, decl, member, include_quotes="<>"):
86512563Sgabeblack@google.com    context.Message("Checking for member %s in %s..." %
86612056Sgabeblack@google.com                    (member, decl))
86710841Sandreas.sandberg@arm.com    text = """
86810841Sandreas.sandberg@arm.com#include %(header)s
86910841Sandreas.sandberg@arm.comint main(){
87010841Sandreas.sandberg@arm.com  %(decl)s test;
87110841Sandreas.sandberg@arm.com  (void)test.%(member)s;
87210841Sandreas.sandberg@arm.com  return 0;
8739651SAndreas.Sandberg@ARM.com};
8749651SAndreas.Sandberg@ARM.com""" % { "header" : include_quotes[0] + include + include_quotes[1],
8759651SAndreas.Sandberg@ARM.com        "decl" : decl,
8769651SAndreas.Sandberg@ARM.com        "member" : member,
8779651SAndreas.Sandberg@ARM.com        }
8789651SAndreas.Sandberg@ARM.com
87912563Sgabeblack@google.com    ret = context.TryCompile(text, extension=".cc")
8809651SAndreas.Sandberg@ARM.com    context.Result(ret)
8819651SAndreas.Sandberg@ARM.com    return ret
88210841Sandreas.sandberg@arm.com
88312563Sgabeblack@google.com# Platform-specific configuration.  Note again that we assume that all
88412563Sgabeblack@google.com# builds under a given build root run on the same host platform.
88510841Sandreas.sandberg@arm.comconf = Configure(main,
88610841Sandreas.sandberg@arm.com                 conf_dir = joinpath(build_root, '.scons_config'),
88710841Sandreas.sandberg@arm.com                 log_file = joinpath(build_root, 'scons_config.log'),
88810860Sandreas.sandberg@arm.com                 custom_tests = {
88910841Sandreas.sandberg@arm.com        'CheckMember' : CheckMember,
89010841Sandreas.sandberg@arm.com        })
89110841Sandreas.sandberg@arm.com
89210841Sandreas.sandberg@arm.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
89310841Sandreas.sandberg@arm.comtry:
89412563Sgabeblack@google.com    import platform
89510841Sandreas.sandberg@arm.com    uname = platform.uname()
89610841Sandreas.sandberg@arm.com    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
89710841Sandreas.sandberg@arm.com        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
89810841Sandreas.sandberg@arm.com            main.Append(CCFLAGS=['-arch', 'x86_64'])
89910841Sandreas.sandberg@arm.com            main.Append(CFLAGS=['-arch', 'x86_64'])
9009651SAndreas.Sandberg@ARM.com            main.Append(LINKFLAGS=['-arch', 'x86_64'])
9019651SAndreas.Sandberg@ARM.com            main.Append(ASFLAGS=['-arch', 'x86_64'])
9029986Sandreas@sandberg.pp.seexcept:
9039986Sandreas@sandberg.pp.se    pass
9049986Sandreas@sandberg.pp.se
9059986Sandreas@sandberg.pp.se# Recent versions of scons substitute a "Null" object for Configure()
9069986Sandreas@sandberg.pp.se# when configuration isn't necessary, e.g., if the "--help" option is
9079986Sandreas@sandberg.pp.se# present.  Unfortuantely this Null object always returns false,
9085863Snate@binkert.org# breaking all our configuration checks.  We replace it with our own
9095863Snate@binkert.org# more optimistic null object that returns True instead.
9105863Snate@binkert.orgif not conf:
9115863Snate@binkert.org    def NullCheck(*args, **kwargs):
9126121Snate@binkert.org        return True
9131858SN/A
9145863Snate@binkert.org    class NullConf:
9155863Snate@binkert.org        def __init__(self, env):
9165863Snate@binkert.org            self.env = env
9175863Snate@binkert.org        def Finish(self):
9185863Snate@binkert.org            return self.env
9192139SN/A        def __getattr__(self, mname):
9204202Sbinkertn@umich.edu            return NullCheck
92111308Santhony.gutierrez@amd.com
9224202Sbinkertn@umich.edu    conf = NullConf(main)
92311308Santhony.gutierrez@amd.com
9242139SN/A# Cache build files in the supplied directory.
9256994Snate@binkert.orgif main['M5_BUILD_CACHE']:
9266994Snate@binkert.org    print 'Using build cache located at', main['M5_BUILD_CACHE']
9276994Snate@binkert.org    CacheDir(main['M5_BUILD_CACHE'])
9286994Snate@binkert.org
9296994Snate@binkert.orgif not GetOption('without_python'):
9306994Snate@binkert.org    # Find Python include and library directories for embedding the
9316994Snate@binkert.org    # interpreter. We rely on python-config to resolve the appropriate
9326994Snate@binkert.org    # includes and linker flags. ParseConfig does not seem to understand
93310319SAndreas.Sandberg@ARM.com    # the more exotic linker flags such as -Xlinker and -export-dynamic so
9346994Snate@binkert.org    # we add them explicitly below. If you want to link in an alternate
9356994Snate@binkert.org    # version of python, see above for instructions on how to invoke
9366994Snate@binkert.org    # scons with the appropriate PATH set.
9376994Snate@binkert.org    #
9386994Snate@binkert.org    # First we check if python2-config exists, else we use python-config
9396994Snate@binkert.org    python_config = readCommand(['which', 'python2-config'],
9406994Snate@binkert.org                                exception='').strip()
9416994Snate@binkert.org    if not os.path.exists(python_config):
9426994Snate@binkert.org        python_config = readCommand(['which', 'python-config'],
9436994Snate@binkert.org                                    exception='').strip()
9446994Snate@binkert.org    py_includes = readCommand([python_config, '--includes'],
9452155SN/A                              exception='').split()
9465863Snate@binkert.org    # Strip the -I from the include folders before adding them to the
9471869SN/A    # CPPPATH
9481869SN/A    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
9495863Snate@binkert.org
9505863Snate@binkert.org    # Read the linker flags and split them into libraries and other link
9514202Sbinkertn@umich.edu    # flags. The libraries are added later through the call the CheckLib.
9526108Snate@binkert.org    py_ld_flags = readCommand([python_config, '--ldflags'],
9536108Snate@binkert.org        exception='').split()
9546108Snate@binkert.org    py_libs = []
9556108Snate@binkert.org    for lib in py_ld_flags:
9569219Spower.jg@gmail.com         if not lib.startswith('-l'):
9579219Spower.jg@gmail.com             main.Append(LINKFLAGS=[lib])
9589219Spower.jg@gmail.com         else:
9599219Spower.jg@gmail.com             lib = lib[2:]
9609219Spower.jg@gmail.com             if lib not in py_libs:
9619219Spower.jg@gmail.com                 py_libs.append(lib)
9629219Spower.jg@gmail.com
9639219Spower.jg@gmail.com    # verify that this stuff works
9644202Sbinkertn@umich.edu    if not conf.CheckHeader('Python.h', '<>'):
9655863Snate@binkert.org        print "Error: can't find Python.h header in", py_includes
96610135SCurtis.Dunham@arm.com        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
96712563Sgabeblack@google.com        Exit(1)
9685742Snate@binkert.org
9698268Ssteve.reinhardt@amd.com    for lib in py_libs:
97012563Sgabeblack@google.com        if not conf.CheckLib(lib):
9718268Ssteve.reinhardt@amd.com            print "Error: can't find library %s required by python" % lib
9725742Snate@binkert.org            Exit(1)
9735341Sstever@gmail.com
9748474Sgblack@eecs.umich.edu# On Solaris you need to use libsocket for socket ops
97512563Sgabeblack@google.comif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
9765342Sstever@gmail.com   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
9774202Sbinkertn@umich.edu       print "Can't find library with socket calls (e.g. accept())"
9784202Sbinkertn@umich.edu       Exit(1)
97911308Santhony.gutierrez@amd.com
9804202Sbinkertn@umich.edu# Check for zlib.  If the check passes, libz will be automatically
9815863Snate@binkert.org# added to the LIBS environment variable.
9825863Snate@binkert.orgif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
98311308Santhony.gutierrez@amd.com    print 'Error: did not find needed zlib compression library '\
9846994Snate@binkert.org          'and/or zlib.h header file.'
9856994Snate@binkert.org    print '       Please install zlib and try again.'
98610319SAndreas.Sandberg@ARM.com    Exit(1)
9875863Snate@binkert.org
9885863Snate@binkert.org# If we have the protobuf compiler, also make sure we have the
9895863Snate@binkert.org# development libraries. If the check passes, libprotobuf will be
9905863Snate@binkert.org# automatically added to the LIBS environment variable. After
9915863Snate@binkert.org# this, we can use the HAVE_PROTOBUF flag to determine if we have
9925863Snate@binkert.org# got both protoc and libprotobuf available.
9935863Snate@binkert.orgmain['HAVE_PROTOBUF'] = main['PROTOC'] and \
9945863Snate@binkert.org    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
9957840Snate@binkert.org                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
9965863Snate@binkert.org
99712230Sgiacomo.travaglini@arm.com# If we have the compiler but not the library, print another warning.
99812230Sgiacomo.travaglini@arm.comif main['PROTOC'] and not main['HAVE_PROTOBUF']:
99912230Sgiacomo.travaglini@arm.com    print termcap.Yellow + termcap.Bold + \
100012230Sgiacomo.travaglini@arm.com        'Warning: did not find protocol buffer library and/or headers.\n' + \
100112230Sgiacomo.travaglini@arm.com    '       Please install libprotobuf-dev for tracing support.' + \
100212056Sgabeblack@google.com    termcap.Normal
100312056Sgabeblack@google.com
100412056Sgabeblack@google.com# Check for librt.
100511308Santhony.gutierrez@amd.comhave_posix_clock = \
10069219Spower.jg@gmail.com    conf.CheckLibWithHeader(None, 'time.h', 'C',
10079219Spower.jg@gmail.com                            'clock_nanosleep(0,0,NULL,NULL);') or \
100811235Sandreas.sandberg@arm.com    conf.CheckLibWithHeader('rt', 'time.h', 'C',
100911235Sandreas.sandberg@arm.com                            'clock_nanosleep(0,0,NULL,NULL);')
10101869SN/A
10111858SN/Ahave_posix_timers = \
10125863Snate@binkert.org    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
101311308Santhony.gutierrez@amd.com                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
101412061Sjason@lowepower.com
101512230Sgiacomo.travaglini@arm.comif not GetOption('without_tcmalloc'):
101612230Sgiacomo.travaglini@arm.com    if conf.CheckLib('tcmalloc'):
10171858SN/A        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
1018955SN/A    elif conf.CheckLib('tcmalloc_minimal'):
1019955SN/A        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
10201869SN/A    else:
10211869SN/A        print termcap.Yellow + termcap.Bold + \
10221869SN/A              "You can get a 12% performance improvement by "\
10231869SN/A              "installing tcmalloc (libgoogle-perftools-dev package "\
10241869SN/A              "on Ubuntu or RedHat)." + termcap.Normal
10255863Snate@binkert.org
10265863Snate@binkert.org
10275863Snate@binkert.org# Detect back trace implementations. The last implementation in the
10281869SN/A# list will be used by default.
10295863Snate@binkert.orgbacktrace_impls = [ "none" ]
10301869SN/A
103112563Sgabeblack@google.comif conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
10321869SN/A                           'backtrace_symbols_fd((void*)0, 0, 0);'):
10331869SN/A    backtrace_impls.append("glibc")
10341869SN/A
10351869SN/Aif backtrace_impls[-1] == "none":
10368483Sgblack@eecs.umich.edu    default_backtrace_impl = "none"
10371869SN/A    print termcap.Yellow + termcap.Bold + \
10381869SN/A        "No suitable back trace implementation found." + \
10391869SN/A        termcap.Normal
10401869SN/A
10415863Snate@binkert.orgif not have_posix_clock:
10425863Snate@binkert.org    print "Can't find library for POSIX clocks."
10431869SN/A
10445863Snate@binkert.org# Check for <fenv.h> (C99 FP environment control)
10455863Snate@binkert.orghave_fenv = conf.CheckHeader('fenv.h', '<>')
10463356Sbinkertn@umich.eduif not have_fenv:
10473356Sbinkertn@umich.edu    print "Warning: Header file <fenv.h> not found."
10483356Sbinkertn@umich.edu    print "         This host has no IEEE FP rounding mode control."
10493356Sbinkertn@umich.edu
10503356Sbinkertn@umich.edu# Check if we should enable KVM-based hardware virtualization. The API
10514781Snate@binkert.org# we rely on exists since version 2.6.36 of the kernel, but somehow
10525863Snate@binkert.org# the KVM_API_VERSION does not reflect the change. We test for one of
10535863Snate@binkert.org# the types as a fall back.
10541869SN/Ahave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
10551869SN/Aif not have_kvm:
10561869SN/A    print "Info: Compatible header file <linux/kvm.h> not found, " \
10576121Snate@binkert.org        "disabling KVM support."
10581869SN/A
105911982Sgabeblack@google.com# x86 needs support for xsave. We test for the structure here since we
106011982Sgabeblack@google.com# won't be able to run new tests by the time we know which ISA we're
106111982Sgabeblack@google.com# targeting.
106211982Sgabeblack@google.comhave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
106311982Sgabeblack@google.com                                    '#include <linux/kvm.h>') != 0
106411982Sgabeblack@google.com
106511982Sgabeblack@google.com# Check if the requested target ISA is compatible with the host
106611982Sgabeblack@google.comdef is_isa_kvm_compatible(isa):
106711982Sgabeblack@google.com    try:
106811982Sgabeblack@google.com        import platform
106911982Sgabeblack@google.com        host_isa = platform.machine()
107011982Sgabeblack@google.com    except:
107111982Sgabeblack@google.com        print "Warning: Failed to determine host ISA."
107211982Sgabeblack@google.com        return False
107311982Sgabeblack@google.com
107411982Sgabeblack@google.com    if not have_posix_timers:
107511982Sgabeblack@google.com        print "Warning: Can not enable KVM, host seems to lack support " \
107611982Sgabeblack@google.com            "for POSIX timers"
107711982Sgabeblack@google.com        return False
107811982Sgabeblack@google.com
107911982Sgabeblack@google.com    if isa == "arm":
108011982Sgabeblack@google.com        return host_isa in ( "armv7l", "aarch64" )
108111982Sgabeblack@google.com    elif isa == "x86":
108211982Sgabeblack@google.com        if host_isa != "x86_64":
108311982Sgabeblack@google.com            return False
108411982Sgabeblack@google.com
108511978Sgabeblack@google.com        if not have_kvm_xsave:
108611978Sgabeblack@google.com            print "KVM on x86 requires xsave support in kernel headers."
108712034Sgabeblack@google.com            return False
108811978Sgabeblack@google.com
108911978Sgabeblack@google.com        return True
109011978Sgabeblack@google.com    else:
109112034Sgabeblack@google.com        return False
109211978Sgabeblack@google.com
109311978Sgabeblack@google.com
109410915Sandreas.sandberg@arm.com# Check if the exclude_host attribute is available. We want this to
109511986Sandreas.sandberg@arm.com# get accurate instruction counts in KVM.
109611986Sandreas.sandberg@arm.commain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
10971869SN/A    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
10981869SN/A
109912015Sgabeblack@google.com
110012015Sgabeblack@google.com######################################################################
110112015Sgabeblack@google.com#
110212015Sgabeblack@google.com# Finish the configuration
11033546Sgblack@eecs.umich.edu#
11043546Sgblack@eecs.umich.edumain = conf.Finish()
11053546Sgblack@eecs.umich.edu
110612015Sgabeblack@google.com######################################################################
110712015Sgabeblack@google.com#
110812015Sgabeblack@google.com# Collect all non-global variables
110912015Sgabeblack@google.com#
111012015Sgabeblack@google.com
111112015Sgabeblack@google.com# Define the universe of supported ISAs
111212015Sgabeblack@google.comall_isa_list = [ ]
111312563Sgabeblack@google.comall_gpu_isa_list = [ ]
11143546Sgblack@eecs.umich.eduExport('all_isa_list')
111512015Sgabeblack@google.comExport('all_gpu_isa_list')
111612015Sgabeblack@google.com
111710196SCurtis.Dunham@arm.comclass CpuModel(object):
111812015Sgabeblack@google.com    '''The CpuModel class encapsulates everything the ISA parser needs to
111912015Sgabeblack@google.com    know about a particular CPU model.'''
112012015Sgabeblack@google.com
112112015Sgabeblack@google.com    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
112212015Sgabeblack@google.com    dict = {}
112312015Sgabeblack@google.com
112412015Sgabeblack@google.com    # Constructor.  Automatically adds models to CpuModel.dict.
112512015Sgabeblack@google.com    def __init__(self, name, default=False):
112612015Sgabeblack@google.com        self.name = name           # name of model
112712015Sgabeblack@google.com
112812015Sgabeblack@google.com        # This cpu is enabled by default
11293546Sgblack@eecs.umich.edu        self.default = default
11303546Sgblack@eecs.umich.edu
11313546Sgblack@eecs.umich.edu        # Add self to dict
1132955SN/A        if name in CpuModel.dict:
1133955SN/A            raise AttributeError, "CpuModel '%s' already registered" % name
1134955SN/A        CpuModel.dict[name] = self
1135955SN/A
11365863Snate@binkert.orgExport('CpuModel')
113710135SCurtis.Dunham@arm.com
113812563Sgabeblack@google.com# Sticky variables get saved in the variables file so they persist from
11395343Sstever@gmail.com# one invocation to the next (unless overridden, in which case the new
11405343Sstever@gmail.com# value becomes sticky).
11416121Snate@binkert.orgsticky_vars = Variables(args=ARGUMENTS)
11425863Snate@binkert.orgExport('sticky_vars')
11434773Snate@binkert.org
11445863Snate@binkert.org# Sticky variables that should be exported
11452632Sstever@eecs.umich.eduexport_vars = []
11465863Snate@binkert.orgExport('export_vars')
11472023SN/A
11485863Snate@binkert.org# For Ruby
11495863Snate@binkert.orgall_protocols = []
11505863Snate@binkert.orgExport('all_protocols')
11515863Snate@binkert.orgprotocol_dirs = []
11525863Snate@binkert.orgExport('protocol_dirs')
11535863Snate@binkert.orgslicc_includes = []
11545863Snate@binkert.orgExport('slicc_includes')
11555863Snate@binkert.org
115610135SCurtis.Dunham@arm.com# Walk the tree and execute all SConsopts scripts that wil add to the
115712563Sgabeblack@google.com# above variables
115812034Sgabeblack@google.comif GetOption('verbose'):
115912034Sgabeblack@google.com    print "Reading SConsopts"
116012034Sgabeblack@google.comfor bdir in [ base_dir ] + extras_dir_list:
11612632Sstever@eecs.umich.edu    if not isdir(bdir):
11625863Snate@binkert.org        print "Error: directory '%s' does not exist" % bdir
11632023SN/A        Exit(1)
11642632Sstever@eecs.umich.edu    for root, dirs, files in os.walk(bdir):
11655863Snate@binkert.org        if 'SConsopts' in files:
11665342Sstever@gmail.com            if GetOption('verbose'):
11675863Snate@binkert.org                print "Reading", joinpath(root, 'SConsopts')
11682632Sstever@eecs.umich.edu            SConscript(joinpath(root, 'SConsopts'))
11695863Snate@binkert.org
11705863Snate@binkert.orgall_isa_list.sort()
11718267Ssteve.reinhardt@amd.comall_gpu_isa_list.sort()
11728120Sgblack@eecs.umich.edu
11738267Ssteve.reinhardt@amd.comsticky_vars.AddVariables(
11748267Ssteve.reinhardt@amd.com    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
11758267Ssteve.reinhardt@amd.com    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
11768267Ssteve.reinhardt@amd.com    ListVariable('CPU_MODELS', 'CPU models',
11778267Ssteve.reinhardt@amd.com                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
11788267Ssteve.reinhardt@amd.com                 sorted(CpuModel.dict.keys())),
11798267Ssteve.reinhardt@amd.com    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
11808267Ssteve.reinhardt@amd.com                 False),
11818267Ssteve.reinhardt@amd.com    BoolVariable('SS_COMPATIBLE_FP',
11825863Snate@binkert.org                 'Make floating-point results compatible with SimpleScalar',
118312563Sgabeblack@google.com                 False),
118412563Sgabeblack@google.com    BoolVariable('USE_SSE2',
11852632Sstever@eecs.umich.edu                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
118612563Sgabeblack@google.com                 False),
118712563Sgabeblack@google.com    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
118812563Sgabeblack@google.com    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
11892632Sstever@eecs.umich.edu    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
11901888SN/A    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
11915863Snate@binkert.org    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
11925863Snate@binkert.org    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
11931858SN/A                  all_protocols),
11948120Sgblack@eecs.umich.edu    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
11958120Sgblack@eecs.umich.edu                 backtrace_impls[-1], backtrace_impls)
11967756SAli.Saidi@ARM.com    )
11972598SN/A
11985863Snate@binkert.org# These variables get exported to #defines in config/*.hh (see src/SConscript).
11991858SN/Aexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
12001858SN/A                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'PROTOCOL',
120112563Sgabeblack@google.com                'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST']
120212563Sgabeblack@google.com
12031858SN/A###################################################
12041858SN/A#
12051858SN/A# Define a SCons builder for configuration flag headers.
120612563Sgabeblack@google.com#
120712563Sgabeblack@google.com###################################################
120812563Sgabeblack@google.com
12091858SN/A# This function generates a config header file that #defines the
121012230Sgiacomo.travaglini@arm.com# variable symbol to the current variable setting (0 or 1).  The source
121112563Sgabeblack@google.com# operands are the name of the variable and a Value node containing the
121212563Sgabeblack@google.com# value of the variable.
121312230Sgiacomo.travaglini@arm.comdef build_config_file(target, source, env):
121412230Sgiacomo.travaglini@arm.com    (variable, value) = [s.get_contents() for s in source]
121512230Sgiacomo.travaglini@arm.com    f = file(str(target[0]), 'w')
121612230Sgiacomo.travaglini@arm.com    print >> f, '#define', variable, value
121712230Sgiacomo.travaglini@arm.com    f.close()
12181858SN/A    return None
12191858SN/A
12201858SN/A# Combine the two functions into a scons Action object.
12219651SAndreas.Sandberg@ARM.comconfig_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
12229651SAndreas.Sandberg@ARM.com
122312563Sgabeblack@google.com# The emitter munges the source & target node lists to reflect what
122412563Sgabeblack@google.com# we're really doing.
12259651SAndreas.Sandberg@ARM.comdef config_emitter(target, source, env):
12269651SAndreas.Sandberg@ARM.com    # extract variable name from Builder arg
122712563Sgabeblack@google.com    variable = str(target[0])
122812563Sgabeblack@google.com    # True target is config header file
12299651SAndreas.Sandberg@ARM.com    target = joinpath('config', variable.lower() + '.hh')
12309651SAndreas.Sandberg@ARM.com    val = env[variable]
123112056Sgabeblack@google.com    if isinstance(val, bool):
123212056Sgabeblack@google.com        # Force value to 0/1
123312563Sgabeblack@google.com        val = int(val)
123412056Sgabeblack@google.com    elif isinstance(val, str):
123512056Sgabeblack@google.com        val = '"' + val + '"'
123611798Santhony.gutierrez@amd.com
123711798Santhony.gutierrez@amd.com    # Sources are variable name & value (packaged in SCons Value nodes)
123811798Santhony.gutierrez@amd.com    return ([target], [Value(variable), Value(val)])
12399986Sandreas@sandberg.pp.se
12409986Sandreas@sandberg.pp.seconfig_builder = Builder(emitter = config_emitter, action = config_action)
12419986Sandreas@sandberg.pp.se
124212563Sgabeblack@google.commain.Append(BUILDERS = { 'ConfigFile' : config_builder })
124312563Sgabeblack@google.com
124412563Sgabeblack@google.com# libelf build is shared across all configs in the build root.
12459986Sandreas@sandberg.pp.semain.SConscript('ext/libelf/SConscript',
12465863Snate@binkert.org                variant_dir = joinpath(build_root, 'libelf'))
12475863Snate@binkert.org
12481869SN/A# iostream3 build is shared across all configs in the build root.
12491965SN/Amain.SConscript('ext/iostream3/SConscript',
12507739Sgblack@eecs.umich.edu                variant_dir = joinpath(build_root, 'iostream3'))
12511965SN/A
12522761Sstever@eecs.umich.edu# libfdt build is shared across all configs in the build root.
12535863Snate@binkert.orgmain.SConscript('ext/libfdt/SConscript',
12541869SN/A                variant_dir = joinpath(build_root, 'libfdt'))
125510196SCurtis.Dunham@arm.com
12561869SN/A# fputils build is shared across all configs in the build root.
12578120Sgblack@eecs.umich.edumain.SConscript('ext/fputils/SConscript',
12588120Sgblack@eecs.umich.edu                variant_dir = joinpath(build_root, 'fputils'))
12598120Sgblack@eecs.umich.edu
12608120Sgblack@eecs.umich.edu# DRAMSim2 build is shared across all configs in the build root.
12618120Sgblack@eecs.umich.edumain.SConscript('ext/dramsim2/SConscript',
12628120Sgblack@eecs.umich.edu                variant_dir = joinpath(build_root, 'dramsim2'))
12638120Sgblack@eecs.umich.edu
12648120Sgblack@eecs.umich.edu# DRAMPower build is shared across all configs in the build root.
12658120Sgblack@eecs.umich.edumain.SConscript('ext/drampower/SConscript',
12668120Sgblack@eecs.umich.edu                variant_dir = joinpath(build_root, 'drampower'))
12678120Sgblack@eecs.umich.edu
12688120Sgblack@eecs.umich.edu# nomali build is shared across all configs in the build root.
1269main.SConscript('ext/nomali/SConscript',
1270                variant_dir = joinpath(build_root, 'nomali'))
1271
1272###################################################
1273#
1274# This function is used to set up a directory with switching headers
1275#
1276###################################################
1277
1278main['ALL_ISA_LIST'] = all_isa_list
1279main['ALL_GPU_ISA_LIST'] = all_gpu_isa_list
1280all_isa_deps = {}
1281def make_switching_dir(dname, switch_headers, env):
1282    # Generate the header.  target[0] is the full path of the output
1283    # header to generate.  'source' is a dummy variable, since we get the
1284    # list of ISAs from env['ALL_ISA_LIST'].
1285    def gen_switch_hdr(target, source, env):
1286        fname = str(target[0])
1287        isa = env['TARGET_ISA'].lower()
1288        try:
1289            f = open(fname, 'w')
1290            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1291            f.close()
1292        except IOError:
1293            print "Failed to create %s" % fname
1294            raise
1295
1296    # Build SCons Action object. 'varlist' specifies env vars that this
1297    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1298    # should get re-executed.
1299    switch_hdr_action = MakeAction(gen_switch_hdr,
1300                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1301
1302    # Instantiate actions for each header
1303    for hdr in switch_headers:
1304        env.Command(hdr, [], switch_hdr_action)
1305
1306    isa_target = Dir('.').up().name.lower().replace('_', '-')
1307    env['PHONY_BASE'] = '#'+isa_target
1308    all_isa_deps[isa_target] = None
1309
1310Export('make_switching_dir')
1311
1312def make_gpu_switching_dir(dname, switch_headers, env):
1313    # Generate the header.  target[0] is the full path of the output
1314    # header to generate.  'source' is a dummy variable, since we get the
1315    # list of ISAs from env['ALL_ISA_LIST'].
1316    def gen_switch_hdr(target, source, env):
1317        fname = str(target[0])
1318
1319        isa = env['TARGET_GPU_ISA'].lower()
1320
1321        try:
1322            f = open(fname, 'w')
1323            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1324            f.close()
1325        except IOError:
1326            print "Failed to create %s" % fname
1327            raise
1328
1329    # Build SCons Action object. 'varlist' specifies env vars that this
1330    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1331    # should get re-executed.
1332    switch_hdr_action = MakeAction(gen_switch_hdr,
1333                          Transform("GENERATE"), varlist=['ALL_ISA_GPU_LIST'])
1334
1335    # Instantiate actions for each header
1336    for hdr in switch_headers:
1337        env.Command(hdr, [], switch_hdr_action)
1338
1339Export('make_gpu_switching_dir')
1340
1341# all-isas -> all-deps -> all-environs -> all_targets
1342main.Alias('#all-isas', [])
1343main.Alias('#all-deps', '#all-isas')
1344
1345# Dummy target to ensure all environments are created before telling
1346# SCons what to actually make (the command line arguments).  We attach
1347# them to the dependence graph after the environments are complete.
1348ORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
1349def environsComplete(target, source, env):
1350    for t in ORIG_BUILD_TARGETS:
1351        main.Depends('#all-targets', t)
1352
1353# Each build/* switching_dir attaches its *-environs target to #all-environs.
1354main.Append(BUILDERS = {'CompleteEnvirons' :
1355                        Builder(action=MakeAction(environsComplete, None))})
1356main.CompleteEnvirons('#all-environs', [])
1357
1358def doNothing(**ignored): pass
1359main.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
1360
1361# The final target to which all the original targets ultimately get attached.
1362main.Dummy('#all-targets', '#all-environs')
1363BUILD_TARGETS[:] = ['#all-targets']
1364
1365###################################################
1366#
1367# Define build environments for selected configurations.
1368#
1369###################################################
1370
1371for variant_path in variant_paths:
1372    if not GetOption('silent'):
1373        print "Building in", variant_path
1374
1375    # Make a copy of the build-root environment to use for this config.
1376    env = main.Clone()
1377    env['BUILDDIR'] = variant_path
1378
1379    # variant_dir is the tail component of build path, and is used to
1380    # determine the build parameters (e.g., 'ALPHA_SE')
1381    (build_root, variant_dir) = splitpath(variant_path)
1382
1383    # Set env variables according to the build directory config.
1384    sticky_vars.files = []
1385    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1386    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1387    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1388    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1389    if isfile(current_vars_file):
1390        sticky_vars.files.append(current_vars_file)
1391        if not GetOption('silent'):
1392            print "Using saved variables file %s" % current_vars_file
1393    else:
1394        # Build dir-specific variables file doesn't exist.
1395
1396        # Make sure the directory is there so we can create it later
1397        opt_dir = dirname(current_vars_file)
1398        if not isdir(opt_dir):
1399            mkdir(opt_dir)
1400
1401        # Get default build variables from source tree.  Variables are
1402        # normally determined by name of $VARIANT_DIR, but can be
1403        # overridden by '--default=' arg on command line.
1404        default = GetOption('default')
1405        opts_dir = joinpath(main.root.abspath, 'build_opts')
1406        if default:
1407            default_vars_files = [joinpath(build_root, 'variables', default),
1408                                  joinpath(opts_dir, default)]
1409        else:
1410            default_vars_files = [joinpath(opts_dir, variant_dir)]
1411        existing_files = filter(isfile, default_vars_files)
1412        if existing_files:
1413            default_vars_file = existing_files[0]
1414            sticky_vars.files.append(default_vars_file)
1415            print "Variables file %s not found,\n  using defaults in %s" \
1416                  % (current_vars_file, default_vars_file)
1417        else:
1418            print "Error: cannot find variables file %s or " \
1419                  "default file(s) %s" \
1420                  % (current_vars_file, ' or '.join(default_vars_files))
1421            Exit(1)
1422
1423    # Apply current variable settings to env
1424    sticky_vars.Update(env)
1425
1426    help_texts["local_vars"] += \
1427        "Build variables for %s:\n" % variant_dir \
1428                 + sticky_vars.GenerateHelpText(env)
1429
1430    # Process variable settings.
1431
1432    if not have_fenv and env['USE_FENV']:
1433        print "Warning: <fenv.h> not available; " \
1434              "forcing USE_FENV to False in", variant_dir + "."
1435        env['USE_FENV'] = False
1436
1437    if not env['USE_FENV']:
1438        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1439        print "         FP results may deviate slightly from other platforms."
1440
1441    if env['EFENCE']:
1442        env.Append(LIBS=['efence'])
1443
1444    if env['USE_KVM']:
1445        if not have_kvm:
1446            print "Warning: Can not enable KVM, host seems to lack KVM support"
1447            env['USE_KVM'] = False
1448        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1449            print "Info: KVM support disabled due to unsupported host and " \
1450                "target ISA combination"
1451            env['USE_KVM'] = False
1452
1453    # Warn about missing optional functionality
1454    if env['USE_KVM']:
1455        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1456            print "Warning: perf_event headers lack support for the " \
1457                "exclude_host attribute. KVM instruction counts will " \
1458                "be inaccurate."
1459
1460    # Save sticky variable settings back to current variables file
1461    sticky_vars.Save(current_vars_file, env)
1462
1463    if env['USE_SSE2']:
1464        env.Append(CCFLAGS=['-msse2'])
1465
1466    # The src/SConscript file sets up the build rules in 'env' according
1467    # to the configured variables.  It returns a list of environments,
1468    # one for each variant build (debug, opt, etc.)
1469    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1470
1471def pairwise(iterable):
1472    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1473    a, b = itertools.tee(iterable)
1474    b.next()
1475    return itertools.izip(a, b)
1476
1477# Create false dependencies so SCons will parse ISAs, establish
1478# dependencies, and setup the build Environments serially. Either
1479# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1480# greater than 1. It appears to be standard race condition stuff; it
1481# doesn't always fail, but usually, and the behaviors are different.
1482# Every time I tried to remove this, builds would fail in some
1483# creative new way. So, don't do that. You'll want to, though, because
1484# tests/SConscript takes a long time to make its Environments.
1485for t1, t2 in pairwise(sorted(all_isa_deps.iterkeys())):
1486    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1487    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1488
1489# base help text
1490Help('''
1491Usage: scons [scons options] [build variables] [target(s)]
1492
1493Extra scons options:
1494%(options)s
1495
1496Global build variables:
1497%(global_vars)s
1498
1499%(local_vars)s
1500''' % help_texts)
1501