SConstruct revision 11500
1955SN/A# -*- mode:python -*-
2955SN/A
312230Sgiacomo.travaglini@arm.com# Copyright (c) 2013, 2015, 2016 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
14813421Sciro.santilli@arm.com# AddOption() are supposed to be displayed when you type 'scons -h'
14913421Sciro.santilli@arm.com# and (2) you can override the help displayed by 'scons -h' using the
1509227Sandreas.hansson@arm.com# Help() function, but these two features are incompatible: once
1519227Sandreas.hansson@arm.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:
15312063Sgabeblack@google.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
15412063Sgabeblack@google.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
1578879Ssteve.reinhardt@amd.com# we can just use AddOption directly.
1588879Ssteve.reinhardt@amd.comdef AddLocalOption(*args, **kwargs):
15910453SAndrew.Bardsley@arm.com    col_width = 30
16010453SAndrew.Bardsley@arm.com
16110453SAndrew.Bardsley@arm.com    help = "  " + ", ".join(args)
16210456SCurtis.Dunham@arm.com    if "help" in kwargs:
16310456SCurtis.Dunham@arm.com        length = len(help)
16410456SCurtis.Dunham@arm.com        if length >= col_width:
16510457Sandreas.hansson@arm.com            help += "\n" + " " * col_width
16610457Sandreas.hansson@arm.com        else:
16711342Sandreas.hansson@arm.com            help += " " * (col_width - length)
16811342Sandreas.hansson@arm.com        help += kwargs["help"]
1698120Sgblack@eecs.umich.edu    help_texts["options"] += help + "\n"
17012063Sgabeblack@google.com
17112563Sgabeblack@google.com    AddOption(*args, **kwargs)
17212063Sgabeblack@google.com
17312063Sgabeblack@google.comAddLocalOption('--colors', dest='use_colors', action='store_true',
1745871Snate@binkert.org               help="Add color to abbreviated scons output")
1755871Snate@binkert.orgAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1766121Snate@binkert.org               help="Don't add color to abbreviated scons output")
1775871Snate@binkert.orgAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1785871Snate@binkert.org               action='store_true',
1799926Sstan.czerniawski@arm.com               help="Build with support for C++-based configuration")
18012243Sgabeblack@google.comAddLocalOption('--default', dest='default', type='string', action='store',
1811533SN/A               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')
18412246Sgabeblack@google.comAddLocalOption('--no-lto', dest='no_lto', action='store_true',
18512246Sgabeblack@google.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')
1889239Sandreas.hansson@arm.comAddLocalOption('--verbose', dest='verbose', action='store_true',
1899239Sandreas.hansson@arm.com               help='Print full tool command lines')
19012563Sgabeblack@google.comAddLocalOption('--without-python', dest='without_python',
1919239Sandreas.hansson@arm.com               action='store_true',
1929239Sandreas.hansson@arm.com               help='Build without Python configuration support')
193955SN/AAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
194955SN/A               action='store_true',
1952632Sstever@eecs.umich.edu               help='Disable linking against tcmalloc')
1962632Sstever@eecs.umich.eduAddLocalOption('--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',
199955SN/A               help='Build with Address Sanitizer if available')
200955SN/A
2018878Ssteve.reinhardt@amd.comtermcap = get_termcap(GetOption('use_colors'))
202955SN/A
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########################################################################
2082632Sstever@eecs.umich.edu
2092632Sstever@eecs.umich.edu# 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 = [
2158268Ssteve.reinhardt@amd.com    "ASAN_",           # address sanitizer symbolizer path and settings
2168268Ssteve.reinhardt@amd.com    "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
2192632Sstever@eecs.umich.edu    "INCLUDE_SERVER_", # distcc pump server settings
2202632Sstever@eecs.umich.edu    "M5",              # M5 configuration (e.g., path to kernels)
2218268Ssteve.reinhardt@amd.com    ]
2222632Sstever@eecs.umich.edu
2238268Ssteve.reinhardt@amd.comuse_env = {}
2248268Ssteve.reinhardt@amd.comfor key,val in sorted(os.environ.iteritems()):
2258268Ssteve.reinhardt@amd.com    if key in use_vars or \
2268268Ssteve.reinhardt@amd.com            any([key.startswith(prefix) for prefix in use_prefixes]):
2273718Sstever@eecs.umich.edu        use_env[key] = val
2282634Sstever@eecs.umich.edu
2292634Sstever@eecs.umich.edu# Tell scons to avoid implicit command dependencies to avoid issues
2305863Snate@binkert.org# with the param wrappes being compiled twice (see
2312638Sstever@eecs.umich.edu# http://scons.tigris.org/issues/show_bug.cgi?id=2811)
2328268Ssteve.reinhardt@amd.commain = 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).
2352632Sstever@eecs.umich.edumain.srcdir = Dir("src")     # The source directory
2362632Sstever@eecs.umich.edu
23712563Sgabeblack@google.commain_dict_keys = main.Dictionary().keys()
2381858SN/A
2393716Sstever@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)"
2422638Sstever@eecs.umich.edu    Exit(1)
2432638Sstever@eecs.umich.edu
24412563Sgabeblack@google.com# Check that swig is present
24512563Sgabeblack@google.comif not 'SWIG' in main_dict_keys:
2462638Sstever@eecs.umich.edu    print "swig is not installed (package swig on Ubuntu and RedHat)"
2475863Snate@binkert.org    Exit(1)
2485863Snate@binkert.org
2495863Snate@binkert.org# add useful python code PYTHONPATH so it can be used by subprocesses
250955SN/A# as well
2515341Sstever@gmail.commain.AppendENVPath('PYTHONPATH', extra_python_paths)
2525341Sstever@gmail.com
2535863Snate@binkert.org########################################################################
2547756SAli.Saidi@ARM.com#
2555341Sstever@gmail.com# Mercurial Stuff.
2566121Snate@binkert.org#
2574494Ssaidi@eecs.umich.edu# If the gem5 directory is a mercurial repository, we should do some
2586121Snate@binkert.org# extra things.
2591105SN/A#
2602667Sstever@eecs.umich.edu########################################################################
2612667Sstever@eecs.umich.edu
2622667Sstever@eecs.umich.eduhgdir = main.root.Dir(".hg")
2632667Sstever@eecs.umich.edu
2646121Snate@binkert.org
2652667Sstever@eecs.umich.edustyle_message = """
2665341Sstever@gmail.comYou're missing the gem5 style hook, which automatically checks your code
2675863Snate@binkert.orgagainst the gem5 style rules on %s.
2685341Sstever@gmail.comThis script will now install the hook in your %s.
2695341Sstever@gmail.comPress enter to continue, or ctrl-c to abort: """
2705341Sstever@gmail.com
2718120Sgblack@eecs.umich.edumercurial_style_message = style_message % ("hg commit and qrefresh commands",
2725341Sstever@gmail.com                                           ".hg/hgrc file")
2738120Sgblack@eecs.umich.edugit_style_message = style_message % ("'git commit'",
2745341Sstever@gmail.com                                     ".git/hooks/ directory")
2758120Sgblack@eecs.umich.edu
2766121Snate@binkert.orgmercurial_style_upgrade_message = """
2776121Snate@binkert.orgYour Mercurial style hooks are not up-to-date. This script will now
2789396Sandreas.hansson@arm.comtry to automatically update them. A backup of your hgrc will be saved
2795397Ssaidi@eecs.umich.eduin .hg/hgrc.old.
2805397Ssaidi@eecs.umich.eduPress enter to continue, or ctrl-c to abort: """
2817727SAli.Saidi@ARM.com
2828268Ssteve.reinhardt@amd.commercurial_style_hook = """
2836168Snate@binkert.org# The following lines were automatically added by gem5/SConstruct
2845341Sstever@gmail.com# to provide the gem5 style-checking hooks
2858120Sgblack@eecs.umich.edu[extensions]
2868120Sgblack@eecs.umich.eduhgstyle = %s/util/hgstyle.py
2878120Sgblack@eecs.umich.edu
2886814Sgblack@eecs.umich.edu[hooks]
2895863Snate@binkert.orgpretxncommit.style = python:hgstyle.check_style
2908120Sgblack@eecs.umich.edupre-qrefresh.style = python:hgstyle.check_style
2915341Sstever@gmail.com# End of SConstruct additions
2925863Snate@binkert.org
2938268Ssteve.reinhardt@amd.com""" % (main.root.abspath)
2946121Snate@binkert.org
2956121Snate@binkert.orgmercurial_lib_not_found = """
2968268Ssteve.reinhardt@amd.comMercurial libraries cannot be found, ignoring style hook.  If
2975742Snate@binkert.orgyou are a gem5 developer, please fix this and run the style
2985742Snate@binkert.orghook. It is important.
2995341Sstever@gmail.com"""
3005742Snate@binkert.org
3015742Snate@binkert.org# Check for style hook and prompt for installation if it's not there.
3025341Sstever@gmail.com# Skip this if --ignore-style was specified, there's no interactive
3036017Snate@binkert.org# terminal to prompt, or no recognized revision control system can be
3046121Snate@binkert.org# found.
3056017Snate@binkert.orgignore_style = GetOption('ignore_style') or not sys.stdin.isatty()
30612158Sandreas.sandberg@arm.com
30712158Sandreas.sandberg@arm.com# Try wire up Mercurial to the style hooks
30812158Sandreas.sandberg@arm.comif not ignore_style and hgdir.exists():
3098120Sgblack@eecs.umich.edu    style_hook = True
3107756SAli.Saidi@ARM.com    style_hooks = tuple()
3117756SAli.Saidi@ARM.com    hgrc = hgdir.File('hgrc')
3127756SAli.Saidi@ARM.com    hgrc_old = hgdir.File('hgrc.old')
3137756SAli.Saidi@ARM.com    try:
3147816Ssteve.reinhardt@amd.com        from mercurial import ui
3157816Ssteve.reinhardt@amd.com        ui = ui.ui()
3167816Ssteve.reinhardt@amd.com        ui.readconfig(hgrc.abspath)
3177816Ssteve.reinhardt@amd.com        style_hooks = (ui.config('hooks', 'pretxncommit.style', None),
3187816Ssteve.reinhardt@amd.com                       ui.config('hooks', 'pre-qrefresh.style', None))
31911979Sgabeblack@google.com        style_hook = all(style_hooks)
3207816Ssteve.reinhardt@amd.com        style_extension = ui.config('extensions', 'style', None)
3217816Ssteve.reinhardt@amd.com    except ImportError:
3227816Ssteve.reinhardt@amd.com        print mercurial_lib_not_found
3237816Ssteve.reinhardt@amd.com
3247756SAli.Saidi@ARM.com    if "python:style.check_style" in style_hooks:
3257756SAli.Saidi@ARM.com        # Try to upgrade the style hooks
3269227Sandreas.hansson@arm.com        print mercurial_style_upgrade_message
3279227Sandreas.hansson@arm.com        # continue unless user does ctrl-c/ctrl-d etc.
3289227Sandreas.hansson@arm.com        try:
3299227Sandreas.hansson@arm.com            raw_input()
3309590Sandreas@sandberg.pp.se        except:
3319590Sandreas@sandberg.pp.se            print "Input exception, exiting scons.\n"
3329590Sandreas@sandberg.pp.se            sys.exit(1)
3339590Sandreas@sandberg.pp.se        shutil.copyfile(hgrc.abspath, hgrc_old.abspath)
3349590Sandreas@sandberg.pp.se        re_style_hook = re.compile(r"^([^=#]+)\.style\s*=\s*([^#\s]+).*")
3359590Sandreas@sandberg.pp.se        re_style_extension = re.compile("style\s*=\s*([^#\s]+).*")
3366654Snate@binkert.org        old, new = open(hgrc_old.abspath, 'r'), open(hgrc.abspath, 'w')
3376654Snate@binkert.org        for l in old:
3385871Snate@binkert.org            m_hook = re_style_hook.match(l)
3396121Snate@binkert.org            m_ext = re_style_extension.match(l)
3408946Sandreas.hansson@arm.com            if m_hook:
3419419Sandreas.hansson@arm.com                hook, check = m_hook.groups()
34212563Sgabeblack@google.com                if check != "python:style.check_style":
3433918Ssaidi@eecs.umich.edu                    print "Warning: %s.style is using a non-default " \
3443918Ssaidi@eecs.umich.edu                        "checker: %s" % (hook, check)
3451858SN/A                if hook not in ("pretxncommit", "pre-qrefresh"):
3469556Sandreas.hansson@arm.com                    print "Warning: Updating unknown style hook: %s" % hook
3479556Sandreas.hansson@arm.com
3489556Sandreas.hansson@arm.com                l = "%s.style = python:hgstyle.check_style\n" % hook
3499556Sandreas.hansson@arm.com            elif m_ext and m_ext.group(1) == style_extension:
35011294Sandreas.hansson@arm.com                l = "hgstyle = %s/util/hgstyle.py\n" % main.root.abspath
35111294Sandreas.hansson@arm.com
35211294Sandreas.hansson@arm.com            new.write(l)
35311294Sandreas.hansson@arm.com    elif not style_hook:
35410878Sandreas.hansson@arm.com        print mercurial_style_message,
35510878Sandreas.hansson@arm.com        # continue unless user does ctrl-c/ctrl-d etc.
35611811Sbaz21@cam.ac.uk        try:
35711811Sbaz21@cam.ac.uk            raw_input()
35811811Sbaz21@cam.ac.uk        except:
35911982Sgabeblack@google.com            print "Input exception, exiting scons.\n"
36011982Sgabeblack@google.com            sys.exit(1)
36111982Sgabeblack@google.com        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
36213421Sciro.santilli@arm.com        print "Adding style hook to", hgrc_path, "\n"
36313421Sciro.santilli@arm.com        try:
36411982Sgabeblack@google.com            with open(hgrc_path, 'a') as f:
36511992Sgabeblack@google.com                f.write(mercurial_style_hook)
36611982Sgabeblack@google.com        except:
36711982Sgabeblack@google.com            print "Error updating", hgrc_path
36812305Sgabeblack@google.com            sys.exit(1)
36912305Sgabeblack@google.com
37012305Sgabeblack@google.comdef install_git_style_hooks():
37112305Sgabeblack@google.com    try:
37212305Sgabeblack@google.com        gitdir = Dir(readCommand(
37312305Sgabeblack@google.com            ["git", "rev-parse", "--git-dir"]).strip("\n"))
37412305Sgabeblack@google.com    except Exception, e:
3759556Sandreas.hansson@arm.com        print "Warning: Failed to find git repo directory: %s" % e
37612563Sgabeblack@google.com        return
37712563Sgabeblack@google.com
37812563Sgabeblack@google.com    git_hooks = gitdir.Dir("hooks")
37912563Sgabeblack@google.com    git_pre_commit_hook = git_hooks.File("pre-commit")
3809556Sandreas.hansson@arm.com    git_style_script = File("util/git-pre-commit.py")
38112563Sgabeblack@google.com
38212563Sgabeblack@google.com    if git_pre_commit_hook.exists():
3839556Sandreas.hansson@arm.com        return
38412563Sgabeblack@google.com
38512563Sgabeblack@google.com    print git_style_message,
38612563Sgabeblack@google.com    try:
38712563Sgabeblack@google.com        raw_input()
38812563Sgabeblack@google.com    except:
38912563Sgabeblack@google.com        print "Input exception, exiting scons.\n"
39012563Sgabeblack@google.com        sys.exit(1)
39112563Sgabeblack@google.com
3929556Sandreas.hansson@arm.com    if not git_hooks.exists():
3939556Sandreas.hansson@arm.com        mkdir(git_hooks.get_abspath())
3946121Snate@binkert.org
39511500Sandreas.hansson@arm.com    # Use a relative symlink if the hooks live in the source directory
39610238Sandreas.hansson@arm.com    if git_pre_commit_hook.is_under(main.root):
39710878Sandreas.hansson@arm.com        script_path = os.path.relpath(
3989420Sandreas.hansson@arm.com            git_style_script.get_abspath(),
39911500Sandreas.hansson@arm.com            git_pre_commit_hook.Dir(".").get_abspath())
40012563Sgabeblack@google.com    else:
40112563Sgabeblack@google.com        script_path = git_style_script.get_abspath()
4029420Sandreas.hansson@arm.com
4039420Sandreas.hansson@arm.com    try:
4049420Sandreas.hansson@arm.com        os.symlink(script_path, git_pre_commit_hook.get_abspath())
4059420Sandreas.hansson@arm.com    except:
40612063Sgabeblack@google.com        print "Error updating git pre-commit hook"
40712063Sgabeblack@google.com        raise
40812063Sgabeblack@google.com
40912063Sgabeblack@google.com# Try to wire up git to the style hooks
41012063Sgabeblack@google.comif not ignore_style and main.root.Entry(".git").exists():
41112063Sgabeblack@google.com    install_git_style_hooks()
41212063Sgabeblack@google.com
41312063Sgabeblack@google.com###################################################
41412063Sgabeblack@google.com#
41512063Sgabeblack@google.com# Figure out which configurations to set up based on the path(s) of
41612063Sgabeblack@google.com# the target(s).
41712063Sgabeblack@google.com#
41812063Sgabeblack@google.com###################################################
41912063Sgabeblack@google.com
42012063Sgabeblack@google.com# Find default configuration & binary.
42112063Sgabeblack@google.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
42212063Sgabeblack@google.com
42312063Sgabeblack@google.com# helper function: find last occurrence of element in list
42412063Sgabeblack@google.comdef rfind(l, elt, offs = -1):
42512063Sgabeblack@google.com    for i in range(len(l)+offs, 0, -1):
42612063Sgabeblack@google.com        if l[i] == elt:
42712063Sgabeblack@google.com            return i
42810457Sandreas.hansson@arm.com    raise ValueError, "element not found"
42910457Sandreas.hansson@arm.com
43010457Sandreas.hansson@arm.com# Take a list of paths (or SCons Nodes) and return a list with all
43110457Sandreas.hansson@arm.com# paths made absolute and ~-expanded.  Paths will be interpreted
43210457Sandreas.hansson@arm.com# relative to the launch directory unless a different root is provided
43312563Sgabeblack@google.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
43412563Sgabeblack@google.com    return [abspath(joinpath(root, expanduser(str(p))))
43512563Sgabeblack@google.com            for p in path_list]
43610457Sandreas.hansson@arm.com
43712063Sgabeblack@google.com# Each target must have 'build' in the interior of the path; the
43812063Sgabeblack@google.com# directory below this will determine the build parameters.  For
43912063Sgabeblack@google.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
44012563Sgabeblack@google.com# recognize that ALPHA_SE specifies the configuration because it
44112563Sgabeblack@google.com# follow 'build' in the build path.
44212563Sgabeblack@google.com
44312563Sgabeblack@google.com# The funky assignment to "[:]" is needed to replace the list contents
44412563Sgabeblack@google.com# in place rather than reassign the symbol to a new list, which
44512563Sgabeblack@google.com# doesn't work (obviously!).
44612063Sgabeblack@google.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
44712063Sgabeblack@google.com
44810238Sandreas.hansson@arm.com# Generate a list of the unique build roots and configs that the
44910238Sandreas.hansson@arm.com# collected targets reference.
45010238Sandreas.hansson@arm.comvariant_paths = []
45112063Sgabeblack@google.combuild_root = None
45210238Sandreas.hansson@arm.comfor t in BUILD_TARGETS:
45310238Sandreas.hansson@arm.com    path_dirs = t.split('/')
45410416Sandreas.hansson@arm.com    try:
45510238Sandreas.hansson@arm.com        build_top = rfind(path_dirs, 'build', -2)
4569227Sandreas.hansson@arm.com    except:
45710238Sandreas.hansson@arm.com        print "Error: no non-leaf 'build' dir found on target path", t
45810416Sandreas.hansson@arm.com        Exit(1)
45910416Sandreas.hansson@arm.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
4609227Sandreas.hansson@arm.com    if not build_root:
4619590Sandreas@sandberg.pp.se        build_root = this_build_root
4629590Sandreas@sandberg.pp.se    else:
4639590Sandreas@sandberg.pp.se        if this_build_root != build_root:
46412304Sgabeblack@google.com            print "Error: build targets not under same build root\n"\
46512304Sgabeblack@google.com                  "  %s\n  %s" % (build_root, this_build_root)
46612304Sgabeblack@google.com            Exit(1)
46712688Sgiacomo.travaglini@arm.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
46812688Sgiacomo.travaglini@arm.com    if variant_path not in variant_paths:
46912688Sgiacomo.travaglini@arm.com        variant_paths.append(variant_path)
47013020Sshunhsingou@google.com
47112304Sgabeblack@google.com# Make sure build_root exists (might not if this is the first build there)
47212688Sgiacomo.travaglini@arm.comif not isdir(build_root):
47312688Sgiacomo.travaglini@arm.com    mkdir(build_root)
47413020Sshunhsingou@google.commain['BUILDROOT'] = build_root
47512304Sgabeblack@google.com
47612304Sgabeblack@google.comExport('main')
47712304Sgabeblack@google.com
47812304Sgabeblack@google.commain.SConsignFile(joinpath(build_root, "sconsign"))
47912688Sgiacomo.travaglini@arm.com
48012688Sgiacomo.travaglini@arm.com# Default duplicate option is to use hard links, but this messes up
48112688Sgiacomo.travaglini@arm.com# when you use emacs to edit a file in the target dir, as emacs moves
48212304Sgabeblack@google.com# file to file~ then copies to file, breaking the link.  Symbolic
4838737Skoansin.tan@gmail.com# (soft) links work better.
48410878Sandreas.hansson@arm.commain.SetOption('duplicate', 'soft-copy')
48511500Sandreas.hansson@arm.com
4869420Sandreas.hansson@arm.com#
4878737Skoansin.tan@gmail.com# Set up global sticky variables... these are common to an entire build
48810106SMitch.Hayenga@arm.com# tree (not specific to a particular build like ALPHA_SE)
4898737Skoansin.tan@gmail.com#
4908737Skoansin.tan@gmail.com
49110878Sandreas.hansson@arm.comglobal_vars_file = joinpath(build_root, 'variables.global')
49212563Sgabeblack@google.com
49312563Sgabeblack@google.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
4948737Skoansin.tan@gmail.com
4958737Skoansin.tan@gmail.comglobal_vars.AddVariables(
49612563Sgabeblack@google.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
4978737Skoansin.tan@gmail.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
4988737Skoansin.tan@gmail.com    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
49911294Sandreas.hansson@arm.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
5009556Sandreas.hansson@arm.com    ('BATCH', 'Use batch pool for build and tests', False),
5019556Sandreas.hansson@arm.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
5029556Sandreas.hansson@arm.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
50311294Sandreas.hansson@arm.com    ('EXTRAS', 'Add extra directories to the compilation', '')
50410278SAndreas.Sandberg@ARM.com    )
50510278SAndreas.Sandberg@ARM.com
50610278SAndreas.Sandberg@ARM.com# Update main environment with values from ARGUMENTS & global_vars_file
50710278SAndreas.Sandberg@ARM.comglobal_vars.Update(main)
50810278SAndreas.Sandberg@ARM.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
50910278SAndreas.Sandberg@ARM.com
5109556Sandreas.hansson@arm.com# Save sticky variable settings back to current variables file
5119590Sandreas@sandberg.pp.seglobal_vars.Save(global_vars_file, main)
5129590Sandreas@sandberg.pp.se
5139420Sandreas.hansson@arm.com# Parse EXTRAS variable to build list of all directories where we're
5149846Sandreas.hansson@arm.com# look for sources etc.  This list is exported as extras_dir_list.
5159846Sandreas.hansson@arm.combase_dir = main.srcdir.abspath
5169846Sandreas.hansson@arm.comif main['EXTRAS']:
5179846Sandreas.hansson@arm.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
5188946Sandreas.hansson@arm.comelse:
51911811Sbaz21@cam.ac.uk    extras_dir_list = []
52011811Sbaz21@cam.ac.uk
52111811Sbaz21@cam.ac.ukExport('base_dir')
52211811Sbaz21@cam.ac.ukExport('extras_dir_list')
52312304Sgabeblack@google.com
52412304Sgabeblack@google.com# the ext directory should be on the #includes path
52512304Sgabeblack@google.commain.Append(CPPPATH=[Dir('ext')])
52612304Sgabeblack@google.com
52713020Sshunhsingou@google.comdef strip_build_path(path, env):
52813020Sshunhsingou@google.com    path = str(path)
52912304Sgabeblack@google.com    variant_base = env['BUILDROOT'] + os.path.sep
53012304Sgabeblack@google.com    if path.startswith(variant_base):
53113020Sshunhsingou@google.com        path = path[len(variant_base):]
53213020Sshunhsingou@google.com    elif path.startswith('build/'):
53312304Sgabeblack@google.com        path = path[6:]
53412304Sgabeblack@google.com    return path
53513020Sshunhsingou@google.com
53613020Sshunhsingou@google.com# Generate a string of the form:
53712304Sgabeblack@google.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
53812304Sgabeblack@google.com# to print while building.
5393918Ssaidi@eecs.umich.educlass Transform(object):
54012563Sgabeblack@google.com    # all specific color settings should be here and nowhere else
54112563Sgabeblack@google.com    tool_color = termcap.Normal
54212563Sgabeblack@google.com    pfx_color = termcap.Yellow
54312563Sgabeblack@google.com    srcs_color = termcap.Yellow + termcap.Bold
5449068SAli.Saidi@ARM.com    arrow_color = termcap.Blue + termcap.Bold
54512563Sgabeblack@google.com    tgts_color = termcap.Yellow + termcap.Bold
54612563Sgabeblack@google.com
5479068SAli.Saidi@ARM.com    def __init__(self, tool, max_sources=99):
54812563Sgabeblack@google.com        self.format = self.tool_color + (" [%8s] " % tool) \
54912563Sgabeblack@google.com                      + self.pfx_color + "%s" \
55012563Sgabeblack@google.com                      + self.srcs_color + "%s" \
55112563Sgabeblack@google.com                      + self.arrow_color + " -> " \
55212563Sgabeblack@google.com                      + self.tgts_color + "%s" \
55312563Sgabeblack@google.com                      + termcap.Normal
55412563Sgabeblack@google.com        self.max_sources = max_sources
55512563Sgabeblack@google.com
5563918Ssaidi@eecs.umich.edu    def __call__(self, target, source, env, for_signature=None):
5573918Ssaidi@eecs.umich.edu        # truncate source list according to max_sources param
5586157Snate@binkert.org        source = source[0:self.max_sources]
5596157Snate@binkert.org        def strip(f):
5606157Snate@binkert.org            return strip_build_path(str(f), env)
5616157Snate@binkert.org        if len(source) > 0:
5625397Ssaidi@eecs.umich.edu            srcs = map(strip, source)
5635397Ssaidi@eecs.umich.edu        else:
5646121Snate@binkert.org            srcs = ['']
5656121Snate@binkert.org        tgts = map(strip, target)
5666121Snate@binkert.org        # surprisingly, os.path.commonprefix is a dumb char-by-char string
5676121Snate@binkert.org        # operation that has nothing to do with paths.
5686121Snate@binkert.org        com_pfx = os.path.commonprefix(srcs + tgts)
5696121Snate@binkert.org        com_pfx_len = len(com_pfx)
5705397Ssaidi@eecs.umich.edu        if com_pfx:
5711851SN/A            # do some cleanup and sanity checking on common prefix
5721851SN/A            if com_pfx[-1] == ".":
5737739Sgblack@eecs.umich.edu                # prefix matches all but file extension: ok
574955SN/A                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
5759396Sandreas.hansson@arm.com                com_pfx = com_pfx[0:-1]
5769396Sandreas.hansson@arm.com            elif com_pfx[-1] == "/":
5779396Sandreas.hansson@arm.com                # common prefix is directory path: OK
5789396Sandreas.hansson@arm.com                pass
5799396Sandreas.hansson@arm.com            else:
5809396Sandreas.hansson@arm.com                src0_len = len(srcs[0])
58112563Sgabeblack@google.com                tgt0_len = len(tgts[0])
58212563Sgabeblack@google.com                if src0_len == com_pfx_len:
58312563Sgabeblack@google.com                    # source is a substring of target, OK
58412563Sgabeblack@google.com                    pass
5859396Sandreas.hansson@arm.com                elif tgt0_len == com_pfx_len:
5869396Sandreas.hansson@arm.com                    # target is a substring of source, need to back up to
5879396Sandreas.hansson@arm.com                    # avoid empty string on RHS of arrow
5889396Sandreas.hansson@arm.com                    sep_idx = com_pfx.rfind(".")
5899396Sandreas.hansson@arm.com                    if sep_idx != -1:
5909396Sandreas.hansson@arm.com                        com_pfx = com_pfx[0:sep_idx]
59112563Sgabeblack@google.com                    else:
59212563Sgabeblack@google.com                        com_pfx = ''
59312563Sgabeblack@google.com                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
59412563Sgabeblack@google.com                    # still splitting at file extension: ok
59512563Sgabeblack@google.com                    pass
5969477Sandreas.hansson@arm.com                else:
5979477Sandreas.hansson@arm.com                    # probably a fluke; ignore it
5989477Sandreas.hansson@arm.com                    com_pfx = ''
5999477Sandreas.hansson@arm.com        # recalculate length in case com_pfx was modified
6009477Sandreas.hansson@arm.com        com_pfx_len = len(com_pfx)
6019477Sandreas.hansson@arm.com        def fmt(files):
6029477Sandreas.hansson@arm.com            f = map(lambda s: s[com_pfx_len:], files)
6039477Sandreas.hansson@arm.com            return ', '.join(f)
6049477Sandreas.hansson@arm.com        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
6059477Sandreas.hansson@arm.com
6069477Sandreas.hansson@arm.comExport('Transform')
6079477Sandreas.hansson@arm.com
6089477Sandreas.hansson@arm.com# enable the regression script to use the termcap
6099477Sandreas.hansson@arm.commain['TERMCAP'] = termcap
61012563Sgabeblack@google.com
61112563Sgabeblack@google.comif GetOption('verbose'):
61212563Sgabeblack@google.com    def MakeAction(action, string, *args, **kwargs):
6139396Sandreas.hansson@arm.com        return Action(action, *args, **kwargs)
6142667Sstever@eecs.umich.eduelse:
61510710Sandreas.hansson@arm.com    MakeAction = Action
61610710Sandreas.hansson@arm.com    main['CCCOMSTR']        = Transform("CC")
61710710Sandreas.hansson@arm.com    main['CXXCOMSTR']       = Transform("CXX")
61811811Sbaz21@cam.ac.uk    main['ASCOMSTR']        = Transform("AS")
61911811Sbaz21@cam.ac.uk    main['SWIGCOMSTR']      = Transform("SWIG")
62011811Sbaz21@cam.ac.uk    main['ARCOMSTR']        = Transform("AR", 0)
62111811Sbaz21@cam.ac.uk    main['LINKCOMSTR']      = Transform("LINK", 0)
62211811Sbaz21@cam.ac.uk    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
62311811Sbaz21@cam.ac.uk    main['M4COMSTR']        = Transform("M4")
62410710Sandreas.hansson@arm.com    main['SHCCCOMSTR']      = Transform("SHCC")
62510710Sandreas.hansson@arm.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
62610710Sandreas.hansson@arm.comExport('MakeAction')
62710710Sandreas.hansson@arm.com
62810384SCurtis.Dunham@arm.com# Initialize the Link-Time Optimization (LTO) flags
6299986Sandreas@sandberg.pp.semain['LTO_CCFLAGS'] = []
6309986Sandreas@sandberg.pp.semain['LTO_LDFLAGS'] = []
6319986Sandreas@sandberg.pp.se
6329986Sandreas@sandberg.pp.se# According to the readme, tcmalloc works best if the compiler doesn't
6339986Sandreas@sandberg.pp.se# assume that we're using the builtin malloc and friends. These flags
6349986Sandreas@sandberg.pp.se# are compiler-specific, so we need to set them after we detect which
6359986Sandreas@sandberg.pp.se# compiler we're using.
6369986Sandreas@sandberg.pp.semain['TCMALLOC_CCFLAGS'] = []
6379986Sandreas@sandberg.pp.se
6389986Sandreas@sandberg.pp.seCXX_version = readCommand([main['CXX'],'--version'], exception=False)
6399986Sandreas@sandberg.pp.seCXX_V = readCommand([main['CXX'],'-V'], exception=False)
6409986Sandreas@sandberg.pp.se
6419986Sandreas@sandberg.pp.semain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
6429986Sandreas@sandberg.pp.semain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
6439986Sandreas@sandberg.pp.seif main['GCC'] + main['CLANG'] > 1:
6449986Sandreas@sandberg.pp.se    print 'Error: How can we have two at the same time?'
6459986Sandreas@sandberg.pp.se    Exit(1)
6469986Sandreas@sandberg.pp.se
6479986Sandreas@sandberg.pp.se# Set up default C++ compiler flags
6489986Sandreas@sandberg.pp.seif main['GCC'] or main['CLANG']:
6492638Sstever@eecs.umich.edu    # As gcc and clang share many flags, do the common parts here
6502638Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-pipe'])
6516121Snate@binkert.org    main.Append(CCFLAGS=['-fno-strict-aliasing'])
6523716Sstever@eecs.umich.edu    # Enable -Wall and -Wextra and then disable the few warnings that
6535522Snate@binkert.org    # we consistently violate
6549986Sandreas@sandberg.pp.se    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
6559986Sandreas@sandberg.pp.se                         '-Wno-sign-compare', '-Wno-unused-parameter'])
6569986Sandreas@sandberg.pp.se    # We always compile using C++11
6575522Snate@binkert.org    main.Append(CXXFLAGS=['-std=c++11'])
6585227Ssaidi@eecs.umich.eduelse:
6595227Ssaidi@eecs.umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6605227Ssaidi@eecs.umich.edu    print "Don't know what compiler options to use for your compiler."
6615227Ssaidi@eecs.umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6626654Snate@binkert.org    print termcap.Yellow + '       version:' + termcap.Normal,
6636654Snate@binkert.org    if not CXX_version:
6647769SAli.Saidi@ARM.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6657769SAli.Saidi@ARM.com               termcap.Normal
6667769SAli.Saidi@ARM.com    else:
6677769SAli.Saidi@ARM.com        print CXX_version.replace('\n', '<nl>')
6685227Ssaidi@eecs.umich.edu    print "       If you're trying to use a compiler other than GCC"
6695227Ssaidi@eecs.umich.edu    print "       or clang, there appears to be something wrong with your"
6705227Ssaidi@eecs.umich.edu    print "       environment."
6715204Sstever@gmail.com    print "       "
6725204Sstever@gmail.com    print "       If you are trying to use a compiler other than those listed"
6735204Sstever@gmail.com    print "       above you will need to ease fix SConstruct and "
6745204Sstever@gmail.com    print "       src/SConscript to support that compiler."
6755204Sstever@gmail.com    Exit(1)
6765204Sstever@gmail.com
6775204Sstever@gmail.comif main['GCC']:
6785204Sstever@gmail.com    # Check for a supported version of gcc. >= 4.8 is chosen for its
6795204Sstever@gmail.com    # level of c++11 support. See
6805204Sstever@gmail.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
6815204Sstever@gmail.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
6825204Sstever@gmail.com    if compareVersions(gcc_version, "4.8") < 0:
6835204Sstever@gmail.com        print 'Error: gcc version 4.8 or newer required.'
6845204Sstever@gmail.com        print '       Installed version:', gcc_version
6855204Sstever@gmail.com        Exit(1)
6865204Sstever@gmail.com
6875204Sstever@gmail.com    main['GCC_VERSION'] = gcc_version
6886121Snate@binkert.org
6895204Sstever@gmail.com    # gcc from version 4.8 and above generates "rep; ret" instructions
6907727SAli.Saidi@ARM.com    # to avoid performance penalties on certain AMD chips. Older
6917727SAli.Saidi@ARM.com    # assemblers detect this as an error, "Error: expecting string
69212563Sgabeblack@google.com    # instruction after `rep'"
6937727SAli.Saidi@ARM.com    as_version_raw = readCommand([main['AS'], '-v', '/dev/null'],
6947727SAli.Saidi@ARM.com                                 exception=False).split()
69511988Sandreas.sandberg@arm.com
69611988Sandreas.sandberg@arm.com    # version strings may contain extra distro-specific
69710453SAndrew.Bardsley@arm.com    # qualifiers, so play it safe and keep only what comes before
69810453SAndrew.Bardsley@arm.com    # the first hyphen
69910453SAndrew.Bardsley@arm.com    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
70010453SAndrew.Bardsley@arm.com
70110453SAndrew.Bardsley@arm.com    if not as_version or compareVersions(as_version, "2.23") < 0:
70210453SAndrew.Bardsley@arm.com        print termcap.Yellow + termcap.Bold + \
70310453SAndrew.Bardsley@arm.com            'Warning: This combination of gcc and binutils have' + \
70410453SAndrew.Bardsley@arm.com            ' known incompatibilities.\n' + \
70510453SAndrew.Bardsley@arm.com            '         If you encounter build problems, please update ' + \
70610453SAndrew.Bardsley@arm.com            'binutils to 2.23.' + \
70710160Sandreas.hansson@arm.com            termcap.Normal
70810453SAndrew.Bardsley@arm.com
70910453SAndrew.Bardsley@arm.com    # Make sure we warn if the user has requested to compile with the
71010453SAndrew.Bardsley@arm.com    # Undefined Benahvior Sanitizer and this version of gcc does not
71110453SAndrew.Bardsley@arm.com    # support it.
71210453SAndrew.Bardsley@arm.com    if GetOption('with_ubsan') and \
71310453SAndrew.Bardsley@arm.com            compareVersions(gcc_version, '4.9') < 0:
71410453SAndrew.Bardsley@arm.com        print termcap.Yellow + termcap.Bold + \
71510453SAndrew.Bardsley@arm.com            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
7169812Sandreas.hansson@arm.com            termcap.Normal
71710453SAndrew.Bardsley@arm.com
71810453SAndrew.Bardsley@arm.com    # Add the appropriate Link-Time Optimization (LTO) flags
71910453SAndrew.Bardsley@arm.com    # unless LTO is explicitly turned off. Note that these flags
72010453SAndrew.Bardsley@arm.com    # are only used by the fast target.
72110453SAndrew.Bardsley@arm.com    if not GetOption('no_lto'):
72210453SAndrew.Bardsley@arm.com        # Pass the LTO flag when compiling to produce GIMPLE
72310453SAndrew.Bardsley@arm.com        # output, we merely create the flags here and only append
72410453SAndrew.Bardsley@arm.com        # them later
72510453SAndrew.Bardsley@arm.com        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
72610453SAndrew.Bardsley@arm.com
72710453SAndrew.Bardsley@arm.com        # Use the same amount of jobs for LTO as we are running
72810453SAndrew.Bardsley@arm.com        # scons with
7297727SAli.Saidi@ARM.com        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
73010453SAndrew.Bardsley@arm.com
73110453SAndrew.Bardsley@arm.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
73212790Smatteo.fusi@bsc.es                                  '-fno-builtin-realloc', '-fno-builtin-free'])
73312790Smatteo.fusi@bsc.es
73412790Smatteo.fusi@bsc.es    # add option to check for undeclared overrides
73512790Smatteo.fusi@bsc.es    if compareVersions(gcc_version, "5.0") > 0:
73612790Smatteo.fusi@bsc.es        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
73712790Smatteo.fusi@bsc.es
73812790Smatteo.fusi@bsc.eselif main['CLANG']:
73910453SAndrew.Bardsley@arm.com    # Check for a supported version of clang, >= 3.1 is needed to
7403118Sstever@eecs.umich.edu    # support similar features as gcc 4.8. See
74110453SAndrew.Bardsley@arm.com    # http://clang.llvm.org/cxx_status.html for details
74210453SAndrew.Bardsley@arm.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
74312563Sgabeblack@google.com    clang_version_match = clang_version_re.search(CXX_version)
74410453SAndrew.Bardsley@arm.com    if (clang_version_match):
7453118Sstever@eecs.umich.edu        clang_version = clang_version_match.groups()[0]
7463483Ssaidi@eecs.umich.edu        if compareVersions(clang_version, "3.1") < 0:
7473494Ssaidi@eecs.umich.edu            print 'Error: clang version 3.1 or newer required.'
7483494Ssaidi@eecs.umich.edu            print '       Installed version:', clang_version
74912563Sgabeblack@google.com            Exit(1)
7503483Ssaidi@eecs.umich.edu    else:
7513483Ssaidi@eecs.umich.edu        print 'Error: Unable to determine clang version.'
7523053Sstever@eecs.umich.edu        Exit(1)
7533053Sstever@eecs.umich.edu
7543918Ssaidi@eecs.umich.edu    # clang has a few additional warnings that we disable, extraneous
75512563Sgabeblack@google.com    # parantheses are allowed due to Ruby's printing of the AST,
75612563Sgabeblack@google.com    # finally self assignments are allowed as the generated CPU code
75712563Sgabeblack@google.com    # is relying on this
7583053Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wno-parentheses',
7593053Sstever@eecs.umich.edu                         '-Wno-self-assign',
7609396Sandreas.hansson@arm.com                         # Some versions of libstdc++ (4.8?) seem to
7619396Sandreas.hansson@arm.com                         # use struct hash and class hash
7629396Sandreas.hansson@arm.com                         # interchangeably.
7639396Sandreas.hansson@arm.com                         '-Wno-mismatched-tags',
7649396Sandreas.hansson@arm.com                         ])
7659396Sandreas.hansson@arm.com
7669396Sandreas.hansson@arm.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
7679396Sandreas.hansson@arm.com
7689396Sandreas.hansson@arm.com    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
76912920Sgabeblack@google.com    # opposed to libstdc++, as the later is dated.
77012920Sgabeblack@google.com    if sys.platform == "darwin":
77112920Sgabeblack@google.com        main.Append(CXXFLAGS=['-stdlib=libc++'])
77212920Sgabeblack@google.com        main.Append(LIBS=['c++'])
7739477Sandreas.hansson@arm.com
7749396Sandreas.hansson@arm.comelse:
77512563Sgabeblack@google.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
77612563Sgabeblack@google.com    print "Don't know what compiler options to use for your compiler."
77712563Sgabeblack@google.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
77812563Sgabeblack@google.com    print termcap.Yellow + '       version:' + termcap.Normal,
7799396Sandreas.hansson@arm.com    if not CXX_version:
7807840Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
7817865Sgblack@eecs.umich.edu               termcap.Normal
7827865Sgblack@eecs.umich.edu    else:
7837865Sgblack@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
7847865Sgblack@eecs.umich.edu    print "       If you're trying to use a compiler other than GCC"
7857865Sgblack@eecs.umich.edu    print "       or clang, there appears to be something wrong with your"
7867840Snate@binkert.org    print "       environment."
7879900Sandreas@sandberg.pp.se    print "       "
7889900Sandreas@sandberg.pp.se    print "       If you are trying to use a compiler other than those listed"
7899900Sandreas@sandberg.pp.se    print "       above you will need to ease fix SConstruct and "
7909900Sandreas@sandberg.pp.se    print "       src/SConscript to support that compiler."
79110456SCurtis.Dunham@arm.com    Exit(1)
79210456SCurtis.Dunham@arm.com
79310456SCurtis.Dunham@arm.com# Set up common yacc/bison flags (needed for Ruby)
79410456SCurtis.Dunham@arm.commain['YACCFLAGS'] = '-d'
79510456SCurtis.Dunham@arm.commain['YACCHXXFILESUFFIX'] = '.hh'
79610456SCurtis.Dunham@arm.com
79712563Sgabeblack@google.com# Do this after we save setting back, or else we'll tack on an
79812563Sgabeblack@google.com# extra 'qdo' every time we run scons.
79912563Sgabeblack@google.comif main['BATCH']:
80012563Sgabeblack@google.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
8019045SAli.Saidi@ARM.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
80211235Sandreas.sandberg@arm.com    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
80311235Sandreas.sandberg@arm.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
80411235Sandreas.sandberg@arm.com    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
80511235Sandreas.sandberg@arm.com
80611235Sandreas.sandberg@arm.comif sys.platform == 'cygwin':
80712485Sjang.hanhwi@gmail.com    # cygwin has some header file issues...
80812485Sjang.hanhwi@gmail.com    main.Append(CCFLAGS=["-Wno-uninitialized"])
80912485Sjang.hanhwi@gmail.com
81011235Sandreas.sandberg@arm.com# Check for the protobuf compiler
81111811Sbaz21@cam.ac.ukprotoc_version = readCommand([main['PROTOC'], '--version'],
81212485Sjang.hanhwi@gmail.com                             exception='').split()
81311811Sbaz21@cam.ac.uk
81411811Sbaz21@cam.ac.uk# First two words should be "libprotoc x.y.z"
81511811Sbaz21@cam.ac.ukif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
81611235Sandreas.sandberg@arm.com    print termcap.Yellow + termcap.Bold + \
81711235Sandreas.sandberg@arm.com        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
81811235Sandreas.sandberg@arm.com        '         Please install protobuf-compiler for tracing support.' + \
81912563Sgabeblack@google.com        termcap.Normal
82012563Sgabeblack@google.com    main['PROTOC'] = False
82112563Sgabeblack@google.comelse:
82211235Sandreas.sandberg@arm.com    # Based on the availability of the compress stream wrappers,
8237840Snate@binkert.org    # require 2.1.0
82412563Sgabeblack@google.com    min_protoc_version = '2.1.0'
8257840Snate@binkert.org    if compareVersions(protoc_version[1], min_protoc_version) < 0:
8261858SN/A        print termcap.Yellow + termcap.Bold + \
8271858SN/A            'Warning: protoc version', min_protoc_version, \
8281858SN/A            'or newer required.\n' + \
82912563Sgabeblack@google.com            '         Installed version:', protoc_version[1], \
83012563Sgabeblack@google.com            termcap.Normal
8311858SN/A        main['PROTOC'] = False
83212230Sgiacomo.travaglini@arm.com    else:
83312230Sgiacomo.travaglini@arm.com        # Attempt to determine the appropriate include path and
83412230Sgiacomo.travaglini@arm.com        # library path using pkg-config, that means we also need to
83512230Sgiacomo.travaglini@arm.com        # check for pkg-config. Note that it is possible to use
83612563Sgabeblack@google.com        # protobuf without the involvement of pkg-config. Later on we
83712563Sgabeblack@google.com        # check go a library config check and at that point the test
83812563Sgabeblack@google.com        # will fail if libprotobuf cannot be found.
83912230Sgiacomo.travaglini@arm.com        if readCommand(['pkg-config', '--version'], exception=''):
8409903Sandreas.hansson@arm.com            try:
8419903Sandreas.hansson@arm.com                # Attempt to establish what linking flags to add for protobuf
8429903Sandreas.hansson@arm.com                # using pkg-config
8439903Sandreas.hansson@arm.com                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
84410841Sandreas.sandberg@arm.com            except:
8459651SAndreas.Sandberg@ARM.com                print termcap.Yellow + termcap.Bold + \
84612563Sgabeblack@google.com                    'Warning: pkg-config could not get protobuf flags.' + \
84712563Sgabeblack@google.com                    termcap.Normal
8489651SAndreas.Sandberg@ARM.com
84912056Sgabeblack@google.com# Check for SWIG
85012056Sgabeblack@google.comif not main.has_key('SWIG'):
85112056Sgabeblack@google.com    print 'Error: SWIG utility not found.'
85212563Sgabeblack@google.com    print '       Please install (see http://www.swig.org) and retry.'
85312056Sgabeblack@google.com    Exit(1)
85410841Sandreas.sandberg@arm.com
85510841Sandreas.sandberg@arm.com# Check for appropriate SWIG version
85610841Sandreas.sandberg@arm.comswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
85710841Sandreas.sandberg@arm.com# First 3 words should be "SWIG Version x.y.z"
85810841Sandreas.sandberg@arm.comif len(swig_version) < 3 or \
85910841Sandreas.sandberg@arm.com        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
8609651SAndreas.Sandberg@ARM.com    print 'Error determining SWIG version.'
8619651SAndreas.Sandberg@ARM.com    Exit(1)
8629651SAndreas.Sandberg@ARM.com
8639651SAndreas.Sandberg@ARM.commin_swig_version = '2.0.4'
8649651SAndreas.Sandberg@ARM.comif compareVersions(swig_version[2], min_swig_version) < 0:
8659651SAndreas.Sandberg@ARM.com    print 'Error: SWIG version', min_swig_version, 'or newer required.'
86612563Sgabeblack@google.com    print '       Installed version:', swig_version[2]
8679651SAndreas.Sandberg@ARM.com    Exit(1)
8689651SAndreas.Sandberg@ARM.com
86910841Sandreas.sandberg@arm.com# Check for known incompatibilities. The standard library shipped with
87012563Sgabeblack@google.com# gcc >= 4.9 does not play well with swig versions prior to 3.0
87112563Sgabeblack@google.comif main['GCC'] and compareVersions(gcc_version, '4.9') >= 0 and \
87210841Sandreas.sandberg@arm.com        compareVersions(swig_version[2], '3.0') < 0:
87310841Sandreas.sandberg@arm.com    print termcap.Yellow + termcap.Bold + \
87410841Sandreas.sandberg@arm.com        'Warning: This combination of gcc and swig have' + \
87510860Sandreas.sandberg@arm.com        ' known incompatibilities.\n' + \
87610841Sandreas.sandberg@arm.com        '         If you encounter build problems, please update ' + \
87710841Sandreas.sandberg@arm.com        'swig to 3.0 or later.' + \
87810841Sandreas.sandberg@arm.com        termcap.Normal
87910841Sandreas.sandberg@arm.com
88010841Sandreas.sandberg@arm.com# Set up SWIG flags & scanner
88112563Sgabeblack@google.comswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
88210841Sandreas.sandberg@arm.commain.Append(SWIGFLAGS=swig_flags)
88310841Sandreas.sandberg@arm.com
88410841Sandreas.sandberg@arm.com# Check for 'timeout' from GNU coreutils. If present, regressions will
88510841Sandreas.sandberg@arm.com# be run with a time limit. We require version 8.13 since we rely on
88610841Sandreas.sandberg@arm.com# support for the '--foreground' option.
8879651SAndreas.Sandberg@ARM.comtimeout_lines = readCommand(['timeout', '--version'],
8889651SAndreas.Sandberg@ARM.com                            exception='').splitlines()
8899986Sandreas@sandberg.pp.se# Get the first line and tokenize it
8909986Sandreas@sandberg.pp.setimeout_version = timeout_lines[0].split() if timeout_lines else []
8919986Sandreas@sandberg.pp.semain['TIMEOUT'] =  timeout_version and \
8929986Sandreas@sandberg.pp.se    compareVersions(timeout_version[-1], '8.13') >= 0
8939986Sandreas@sandberg.pp.se
8949986Sandreas@sandberg.pp.se# filter out all existing swig scanners, they mess up the dependency
8955863Snate@binkert.org# stuff for some reason
8965863Snate@binkert.orgscanners = []
8975863Snate@binkert.orgfor scanner in main['SCANNERS']:
8985863Snate@binkert.org    skeys = scanner.skeys
8996121Snate@binkert.org    if skeys == '.i':
9001858SN/A        continue
9015863Snate@binkert.org
9025863Snate@binkert.org    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
9035863Snate@binkert.org        continue
9045863Snate@binkert.org
9055863Snate@binkert.org    scanners.append(scanner)
9062139SN/A
9074202Sbinkertn@umich.edu# add the new swig scanner that we like better
90811308Santhony.gutierrez@amd.comfrom SCons.Scanner import ClassicCPP as CPPScanner
9094202Sbinkertn@umich.eduswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
91011308Santhony.gutierrez@amd.comscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
9112139SN/A
9126994Snate@binkert.org# replace the scanners list that has what we want
9136994Snate@binkert.orgmain['SCANNERS'] = scanners
9146994Snate@binkert.org
9156994Snate@binkert.org# Add a custom Check function to test for structure members.
9166994Snate@binkert.orgdef CheckMember(context, include, decl, member, include_quotes="<>"):
9176994Snate@binkert.org    context.Message("Checking for member %s in %s..." %
9186994Snate@binkert.org                    (member, decl))
9196994Snate@binkert.org    text = """
92010319SAndreas.Sandberg@ARM.com#include %(header)s
9216994Snate@binkert.orgint main(){
9226994Snate@binkert.org  %(decl)s test;
9236994Snate@binkert.org  (void)test.%(member)s;
9246994Snate@binkert.org  return 0;
9256994Snate@binkert.org};
9266994Snate@binkert.org""" % { "header" : include_quotes[0] + include + include_quotes[1],
9276994Snate@binkert.org        "decl" : decl,
9286994Snate@binkert.org        "member" : member,
9296994Snate@binkert.org        }
9306994Snate@binkert.org
9316994Snate@binkert.org    ret = context.TryCompile(text, extension=".cc")
9322155SN/A    context.Result(ret)
9335863Snate@binkert.org    return ret
9341869SN/A
9351869SN/A# Platform-specific configuration.  Note again that we assume that all
9365863Snate@binkert.org# builds under a given build root run on the same host platform.
9375863Snate@binkert.orgconf = Configure(main,
9384202Sbinkertn@umich.edu                 conf_dir = joinpath(build_root, '.scons_config'),
9396108Snate@binkert.org                 log_file = joinpath(build_root, 'scons_config.log'),
9406108Snate@binkert.org                 custom_tests = {
9416108Snate@binkert.org        'CheckMember' : CheckMember,
9426108Snate@binkert.org        })
9439219Spower.jg@gmail.com
9449219Spower.jg@gmail.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
9459219Spower.jg@gmail.comtry:
9469219Spower.jg@gmail.com    import platform
9479219Spower.jg@gmail.com    uname = platform.uname()
9489219Spower.jg@gmail.com    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
9499219Spower.jg@gmail.com        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
9509219Spower.jg@gmail.com            main.Append(CCFLAGS=['-arch', 'x86_64'])
9514202Sbinkertn@umich.edu            main.Append(CFLAGS=['-arch', 'x86_64'])
9525863Snate@binkert.org            main.Append(LINKFLAGS=['-arch', 'x86_64'])
95310135SCurtis.Dunham@arm.com            main.Append(ASFLAGS=['-arch', 'x86_64'])
95412563Sgabeblack@google.comexcept:
9555742Snate@binkert.org    pass
9568268Ssteve.reinhardt@amd.com
95712563Sgabeblack@google.com# Recent versions of scons substitute a "Null" object for Configure()
9588268Ssteve.reinhardt@amd.com# when configuration isn't necessary, e.g., if the "--help" option is
9595742Snate@binkert.org# present.  Unfortuantely this Null object always returns false,
9605341Sstever@gmail.com# breaking all our configuration checks.  We replace it with our own
9618474Sgblack@eecs.umich.edu# more optimistic null object that returns True instead.
96212563Sgabeblack@google.comif not conf:
9635342Sstever@gmail.com    def NullCheck(*args, **kwargs):
9644202Sbinkertn@umich.edu        return True
9654202Sbinkertn@umich.edu
96611308Santhony.gutierrez@amd.com    class NullConf:
9674202Sbinkertn@umich.edu        def __init__(self, env):
9685863Snate@binkert.org            self.env = env
9695863Snate@binkert.org        def Finish(self):
97011308Santhony.gutierrez@amd.com            return self.env
9716994Snate@binkert.org        def __getattr__(self, mname):
9726994Snate@binkert.org            return NullCheck
97310319SAndreas.Sandberg@ARM.com
9745863Snate@binkert.org    conf = NullConf(main)
9755863Snate@binkert.org
9765863Snate@binkert.org# Cache build files in the supplied directory.
9775863Snate@binkert.orgif main['M5_BUILD_CACHE']:
9785863Snate@binkert.org    print 'Using build cache located at', main['M5_BUILD_CACHE']
9795863Snate@binkert.org    CacheDir(main['M5_BUILD_CACHE'])
9805863Snate@binkert.org
9815863Snate@binkert.orgif not GetOption('without_python'):
9827840Snate@binkert.org    # Find Python include and library directories for embedding the
9835863Snate@binkert.org    # interpreter. We rely on python-config to resolve the appropriate
98412230Sgiacomo.travaglini@arm.com    # includes and linker flags. ParseConfig does not seem to understand
98512230Sgiacomo.travaglini@arm.com    # the more exotic linker flags such as -Xlinker and -export-dynamic so
98612230Sgiacomo.travaglini@arm.com    # we add them explicitly below. If you want to link in an alternate
98712230Sgiacomo.travaglini@arm.com    # version of python, see above for instructions on how to invoke
98812230Sgiacomo.travaglini@arm.com    # scons with the appropriate PATH set.
98912056Sgabeblack@google.com    #
99012056Sgabeblack@google.com    # First we check if python2-config exists, else we use python-config
99112056Sgabeblack@google.com    python_config = readCommand(['which', 'python2-config'],
99211308Santhony.gutierrez@amd.com                                exception='').strip()
9939219Spower.jg@gmail.com    if not os.path.exists(python_config):
9949219Spower.jg@gmail.com        python_config = readCommand(['which', 'python-config'],
99511235Sandreas.sandberg@arm.com                                    exception='').strip()
99611235Sandreas.sandberg@arm.com    py_includes = readCommand([python_config, '--includes'],
9971869SN/A                              exception='').split()
9981858SN/A    # Strip the -I from the include folders before adding them to the
9995863Snate@binkert.org    # CPPPATH
100011308Santhony.gutierrez@amd.com    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
100112061Sjason@lowepower.com
100212920Sgabeblack@google.com    # Read the linker flags and split them into libraries and other link
100312920Sgabeblack@google.com    # flags. The libraries are added later through the call the CheckLib.
10041858SN/A    py_ld_flags = readCommand([python_config, '--ldflags'],
1005955SN/A        exception='').split()
1006955SN/A    py_libs = []
10071869SN/A    for lib in py_ld_flags:
10081869SN/A         if not lib.startswith('-l'):
10091869SN/A             main.Append(LINKFLAGS=[lib])
10101869SN/A         else:
10111869SN/A             lib = lib[2:]
10125863Snate@binkert.org             if lib not in py_libs:
10135863Snate@binkert.org                 py_libs.append(lib)
10145863Snate@binkert.org
10151869SN/A    # verify that this stuff works
10165863Snate@binkert.org    if not conf.CheckHeader('Python.h', '<>'):
10171869SN/A        print "Error: can't find Python.h header in", py_includes
101812563Sgabeblack@google.com        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
10191869SN/A        Exit(1)
10201869SN/A
10211869SN/A    for lib in py_libs:
10221869SN/A        if not conf.CheckLib(lib):
10238483Sgblack@eecs.umich.edu            print "Error: can't find library %s required by python" % lib
10241869SN/A            Exit(1)
10251869SN/A
10261869SN/A# On Solaris you need to use libsocket for socket ops
10271869SN/Aif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
10285863Snate@binkert.org   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
10295863Snate@binkert.org       print "Can't find library with socket calls (e.g. accept())"
10301869SN/A       Exit(1)
10315863Snate@binkert.org
10325863Snate@binkert.org# Check for zlib.  If the check passes, libz will be automatically
10333356Sbinkertn@umich.edu# added to the LIBS environment variable.
10343356Sbinkertn@umich.eduif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
10353356Sbinkertn@umich.edu    print 'Error: did not find needed zlib compression library '\
10363356Sbinkertn@umich.edu          'and/or zlib.h header file.'
10373356Sbinkertn@umich.edu    print '       Please install zlib and try again.'
10384781Snate@binkert.org    Exit(1)
10395863Snate@binkert.org
10405863Snate@binkert.org# If we have the protobuf compiler, also make sure we have the
10411869SN/A# development libraries. If the check passes, libprotobuf will be
10421869SN/A# automatically added to the LIBS environment variable. After
10431869SN/A# this, we can use the HAVE_PROTOBUF flag to determine if we have
10446121Snate@binkert.org# got both protoc and libprotobuf available.
10451869SN/Amain['HAVE_PROTOBUF'] = main['PROTOC'] and \
104611982Sgabeblack@google.com    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
104711982Sgabeblack@google.com                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
104811982Sgabeblack@google.com
104911982Sgabeblack@google.com# If we have the compiler but not the library, print another warning.
105011982Sgabeblack@google.comif main['PROTOC'] and not main['HAVE_PROTOBUF']:
105111982Sgabeblack@google.com    print termcap.Yellow + termcap.Bold + \
105211982Sgabeblack@google.com        'Warning: did not find protocol buffer library and/or headers.\n' + \
105311982Sgabeblack@google.com    '       Please install libprotobuf-dev for tracing support.' + \
105411982Sgabeblack@google.com    termcap.Normal
105511982Sgabeblack@google.com
105611982Sgabeblack@google.com# Check for librt.
105711982Sgabeblack@google.comhave_posix_clock = \
105811982Sgabeblack@google.com    conf.CheckLibWithHeader(None, 'time.h', 'C',
105911982Sgabeblack@google.com                            'clock_nanosleep(0,0,NULL,NULL);') or \
106011982Sgabeblack@google.com    conf.CheckLibWithHeader('rt', 'time.h', 'C',
106111982Sgabeblack@google.com                            'clock_nanosleep(0,0,NULL,NULL);')
106211982Sgabeblack@google.com
106311982Sgabeblack@google.comhave_posix_timers = \
106411982Sgabeblack@google.com    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
106511982Sgabeblack@google.com                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
106611982Sgabeblack@google.com
106711982Sgabeblack@google.comif not GetOption('without_tcmalloc'):
106811982Sgabeblack@google.com    if conf.CheckLib('tcmalloc'):
106911982Sgabeblack@google.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
107011982Sgabeblack@google.com    elif conf.CheckLib('tcmalloc_minimal'):
107111982Sgabeblack@google.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
107211978Sgabeblack@google.com    else:
107311978Sgabeblack@google.com        print termcap.Yellow + termcap.Bold + \
107412034Sgabeblack@google.com              "You can get a 12% performance improvement by "\
107511978Sgabeblack@google.com              "installing tcmalloc (libgoogle-perftools-dev package "\
107611978Sgabeblack@google.com              "on Ubuntu or RedHat)." + termcap.Normal
107711978Sgabeblack@google.com
107812034Sgabeblack@google.com
107911978Sgabeblack@google.com# Detect back trace implementations. The last implementation in the
108011978Sgabeblack@google.com# list will be used by default.
108110915Sandreas.sandberg@arm.combacktrace_impls = [ "none" ]
108211986Sandreas.sandberg@arm.com
108311986Sandreas.sandberg@arm.comif conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
10841869SN/A                           'backtrace_symbols_fd((void*)0, 0, 0);'):
10851869SN/A    backtrace_impls.append("glibc")
108612015Sgabeblack@google.com
108712015Sgabeblack@google.comif backtrace_impls[-1] == "none":
108812015Sgabeblack@google.com    default_backtrace_impl = "none"
108912015Sgabeblack@google.com    print termcap.Yellow + termcap.Bold + \
10903546Sgblack@eecs.umich.edu        "No suitable back trace implementation found." + \
10913546Sgblack@eecs.umich.edu        termcap.Normal
10923546Sgblack@eecs.umich.edu
109312015Sgabeblack@google.comif not have_posix_clock:
109412015Sgabeblack@google.com    print "Can't find library for POSIX clocks."
109512015Sgabeblack@google.com
109612015Sgabeblack@google.com# Check for <fenv.h> (C99 FP environment control)
109712015Sgabeblack@google.comhave_fenv = conf.CheckHeader('fenv.h', '<>')
109812015Sgabeblack@google.comif not have_fenv:
109912015Sgabeblack@google.com    print "Warning: Header file <fenv.h> not found."
110012563Sgabeblack@google.com    print "         This host has no IEEE FP rounding mode control."
11013546Sgblack@eecs.umich.edu
110212015Sgabeblack@google.com# Check if we should enable KVM-based hardware virtualization. The API
110312015Sgabeblack@google.com# we rely on exists since version 2.6.36 of the kernel, but somehow
110410196SCurtis.Dunham@arm.com# the KVM_API_VERSION does not reflect the change. We test for one of
110512015Sgabeblack@google.com# the types as a fall back.
110612015Sgabeblack@google.comhave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
110712015Sgabeblack@google.comif not have_kvm:
110812015Sgabeblack@google.com    print "Info: Compatible header file <linux/kvm.h> not found, " \
110912015Sgabeblack@google.com        "disabling KVM support."
111012015Sgabeblack@google.com
111112015Sgabeblack@google.com# x86 needs support for xsave. We test for the structure here since we
111212015Sgabeblack@google.com# won't be able to run new tests by the time we know which ISA we're
111312015Sgabeblack@google.com# targeting.
111412015Sgabeblack@google.comhave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
111512015Sgabeblack@google.com                                    '#include <linux/kvm.h>') != 0
11163546Sgblack@eecs.umich.edu
11173546Sgblack@eecs.umich.edu# Check if the requested target ISA is compatible with the host
11183546Sgblack@eecs.umich.edudef is_isa_kvm_compatible(isa):
1119955SN/A    try:
1120955SN/A        import platform
1121955SN/A        host_isa = platform.machine()
1122955SN/A    except:
11235863Snate@binkert.org        print "Warning: Failed to determine host ISA."
112410135SCurtis.Dunham@arm.com        return False
112512563Sgabeblack@google.com
11265343Sstever@gmail.com    if not have_posix_timers:
11275343Sstever@gmail.com        print "Warning: Can not enable KVM, host seems to lack support " \
11286121Snate@binkert.org            "for POSIX timers"
11295863Snate@binkert.org        return False
11304773Snate@binkert.org
11315863Snate@binkert.org    if isa == "arm":
11322632Sstever@eecs.umich.edu        return host_isa in ( "armv7l", "aarch64" )
11335863Snate@binkert.org    elif isa == "x86":
11342023SN/A        if host_isa != "x86_64":
11355863Snate@binkert.org            return False
11365863Snate@binkert.org
11375863Snate@binkert.org        if not have_kvm_xsave:
11385863Snate@binkert.org            print "KVM on x86 requires xsave support in kernel headers."
11395863Snate@binkert.org            return False
11405863Snate@binkert.org
11415863Snate@binkert.org        return True
11425863Snate@binkert.org    else:
114310135SCurtis.Dunham@arm.com        return False
114412563Sgabeblack@google.com
114512034Sgabeblack@google.com
114612034Sgabeblack@google.com# Check if the exclude_host attribute is available. We want this to
114712034Sgabeblack@google.com# get accurate instruction counts in KVM.
11482632Sstever@eecs.umich.edumain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
11495863Snate@binkert.org    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
11502023SN/A
11512632Sstever@eecs.umich.edu
11525863Snate@binkert.org######################################################################
11535342Sstever@gmail.com#
11545863Snate@binkert.org# Finish the configuration
11552632Sstever@eecs.umich.edu#
11565863Snate@binkert.orgmain = conf.Finish()
11575863Snate@binkert.org
11588267Ssteve.reinhardt@amd.com######################################################################
11598120Sgblack@eecs.umich.edu#
11608267Ssteve.reinhardt@amd.com# Collect all non-global variables
11618267Ssteve.reinhardt@amd.com#
11628267Ssteve.reinhardt@amd.com
11638267Ssteve.reinhardt@amd.com# Define the universe of supported ISAs
11648267Ssteve.reinhardt@amd.comall_isa_list = [ ]
11658267Ssteve.reinhardt@amd.comall_gpu_isa_list = [ ]
11668267Ssteve.reinhardt@amd.comExport('all_isa_list')
11678267Ssteve.reinhardt@amd.comExport('all_gpu_isa_list')
11688267Ssteve.reinhardt@amd.com
11695863Snate@binkert.orgclass CpuModel(object):
117012563Sgabeblack@google.com    '''The CpuModel class encapsulates everything the ISA parser needs to
117112563Sgabeblack@google.com    know about a particular CPU model.'''
11722632Sstever@eecs.umich.edu
117312563Sgabeblack@google.com    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
117412563Sgabeblack@google.com    dict = {}
117512563Sgabeblack@google.com
11762632Sstever@eecs.umich.edu    # Constructor.  Automatically adds models to CpuModel.dict.
11771888SN/A    def __init__(self, name, default=False):
11785863Snate@binkert.org        self.name = name           # name of model
11795863Snate@binkert.org
11801858SN/A        # This cpu is enabled by default
11818120Sgblack@eecs.umich.edu        self.default = default
11828120Sgblack@eecs.umich.edu
11837756SAli.Saidi@ARM.com        # Add self to dict
11842598SN/A        if name in CpuModel.dict:
11855863Snate@binkert.org            raise AttributeError, "CpuModel '%s' already registered" % name
11861858SN/A        CpuModel.dict[name] = self
11871858SN/A
118812563Sgabeblack@google.comExport('CpuModel')
118912563Sgabeblack@google.com
11901858SN/A# Sticky variables get saved in the variables file so they persist from
11911858SN/A# one invocation to the next (unless overridden, in which case the new
11921858SN/A# value becomes sticky).
119312563Sgabeblack@google.comsticky_vars = Variables(args=ARGUMENTS)
119412563Sgabeblack@google.comExport('sticky_vars')
119512563Sgabeblack@google.com
11961858SN/A# Sticky variables that should be exported
119712230Sgiacomo.travaglini@arm.comexport_vars = []
119812563Sgabeblack@google.comExport('export_vars')
119912563Sgabeblack@google.com
120012230Sgiacomo.travaglini@arm.com# For Ruby
120112230Sgiacomo.travaglini@arm.comall_protocols = []
120212230Sgiacomo.travaglini@arm.comExport('all_protocols')
120312230Sgiacomo.travaglini@arm.comprotocol_dirs = []
120412230Sgiacomo.travaglini@arm.comExport('protocol_dirs')
12051858SN/Aslicc_includes = []
12061858SN/AExport('slicc_includes')
12071858SN/A
12089651SAndreas.Sandberg@ARM.com# Walk the tree and execute all SConsopts scripts that wil add to the
12099651SAndreas.Sandberg@ARM.com# above variables
121012563Sgabeblack@google.comif GetOption('verbose'):
121112563Sgabeblack@google.com    print "Reading SConsopts"
12129651SAndreas.Sandberg@ARM.comfor bdir in [ base_dir ] + extras_dir_list:
12139651SAndreas.Sandberg@ARM.com    if not isdir(bdir):
121412563Sgabeblack@google.com        print "Error: directory '%s' does not exist" % bdir
121512563Sgabeblack@google.com        Exit(1)
12169651SAndreas.Sandberg@ARM.com    for root, dirs, files in os.walk(bdir):
12179651SAndreas.Sandberg@ARM.com        if 'SConsopts' in files:
121812056Sgabeblack@google.com            if GetOption('verbose'):
121912056Sgabeblack@google.com                print "Reading", joinpath(root, 'SConsopts')
122012563Sgabeblack@google.com            SConscript(joinpath(root, 'SConsopts'))
122112056Sgabeblack@google.com
122212056Sgabeblack@google.comall_isa_list.sort()
122311798Santhony.gutierrez@amd.comall_gpu_isa_list.sort()
122411798Santhony.gutierrez@amd.com
122511798Santhony.gutierrez@amd.comsticky_vars.AddVariables(
12269986Sandreas@sandberg.pp.se    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
12279986Sandreas@sandberg.pp.se    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
12289986Sandreas@sandberg.pp.se    ListVariable('CPU_MODELS', 'CPU models',
122912563Sgabeblack@google.com                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
123012563Sgabeblack@google.com                 sorted(CpuModel.dict.keys())),
123112563Sgabeblack@google.com    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
12329986Sandreas@sandberg.pp.se                 False),
12335863Snate@binkert.org    BoolVariable('SS_COMPATIBLE_FP',
12345863Snate@binkert.org                 'Make floating-point results compatible with SimpleScalar',
12351869SN/A                 False),
12361965SN/A    BoolVariable('USE_SSE2',
12377739Sgblack@eecs.umich.edu                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
12381965SN/A                 False),
12392761Sstever@eecs.umich.edu    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
12405863Snate@binkert.org    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
12411869SN/A    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
124210196SCurtis.Dunham@arm.com    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
12431869SN/A    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
12448120Sgblack@eecs.umich.edu    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
12458120Sgblack@eecs.umich.edu                  all_protocols),
12468120Sgblack@eecs.umich.edu    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
12478120Sgblack@eecs.umich.edu                 backtrace_impls[-1], backtrace_impls)
12488120Sgblack@eecs.umich.edu    )
12498120Sgblack@eecs.umich.edu
12508120Sgblack@eecs.umich.edu# These variables get exported to #defines in config/*.hh (see src/SConscript).
12518120Sgblack@eecs.umich.eduexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
12528120Sgblack@eecs.umich.edu                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'PROTOCOL',
12538120Sgblack@eecs.umich.edu                'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST']
12548120Sgblack@eecs.umich.edu
12558120Sgblack@eecs.umich.edu###################################################
1256#
1257# Define a SCons builder for configuration flag headers.
1258#
1259###################################################
1260
1261# This function generates a config header file that #defines the
1262# variable symbol to the current variable setting (0 or 1).  The source
1263# operands are the name of the variable and a Value node containing the
1264# value of the variable.
1265def build_config_file(target, source, env):
1266    (variable, value) = [s.get_contents() for s in source]
1267    f = file(str(target[0]), 'w')
1268    print >> f, '#define', variable, value
1269    f.close()
1270    return None
1271
1272# Combine the two functions into a scons Action object.
1273config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1274
1275# The emitter munges the source & target node lists to reflect what
1276# we're really doing.
1277def config_emitter(target, source, env):
1278    # extract variable name from Builder arg
1279    variable = str(target[0])
1280    # True target is config header file
1281    target = joinpath('config', variable.lower() + '.hh')
1282    val = env[variable]
1283    if isinstance(val, bool):
1284        # Force value to 0/1
1285        val = int(val)
1286    elif isinstance(val, str):
1287        val = '"' + val + '"'
1288
1289    # Sources are variable name & value (packaged in SCons Value nodes)
1290    return ([target], [Value(variable), Value(val)])
1291
1292config_builder = Builder(emitter = config_emitter, action = config_action)
1293
1294main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1295
1296# libelf build is shared across all configs in the build root.
1297main.SConscript('ext/libelf/SConscript',
1298                variant_dir = joinpath(build_root, 'libelf'))
1299
1300# iostream3 build is shared across all configs in the build root.
1301main.SConscript('ext/iostream3/SConscript',
1302                variant_dir = joinpath(build_root, 'iostream3'))
1303
1304# libfdt build is shared across all configs in the build root.
1305main.SConscript('ext/libfdt/SConscript',
1306                variant_dir = joinpath(build_root, 'libfdt'))
1307
1308# fputils build is shared across all configs in the build root.
1309main.SConscript('ext/fputils/SConscript',
1310                variant_dir = joinpath(build_root, 'fputils'))
1311
1312# DRAMSim2 build is shared across all configs in the build root.
1313main.SConscript('ext/dramsim2/SConscript',
1314                variant_dir = joinpath(build_root, 'dramsim2'))
1315
1316# DRAMPower build is shared across all configs in the build root.
1317main.SConscript('ext/drampower/SConscript',
1318                variant_dir = joinpath(build_root, 'drampower'))
1319
1320# nomali build is shared across all configs in the build root.
1321main.SConscript('ext/nomali/SConscript',
1322                variant_dir = joinpath(build_root, 'nomali'))
1323
1324###################################################
1325#
1326# This function is used to set up a directory with switching headers
1327#
1328###################################################
1329
1330main['ALL_ISA_LIST'] = all_isa_list
1331main['ALL_GPU_ISA_LIST'] = all_gpu_isa_list
1332all_isa_deps = {}
1333def make_switching_dir(dname, switch_headers, env):
1334    # Generate the header.  target[0] is the full path of the output
1335    # header to generate.  'source' is a dummy variable, since we get the
1336    # list of ISAs from env['ALL_ISA_LIST'].
1337    def gen_switch_hdr(target, source, env):
1338        fname = str(target[0])
1339        isa = env['TARGET_ISA'].lower()
1340        try:
1341            f = open(fname, 'w')
1342            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1343            f.close()
1344        except IOError:
1345            print "Failed to create %s" % fname
1346            raise
1347
1348    # Build SCons Action object. 'varlist' specifies env vars that this
1349    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1350    # should get re-executed.
1351    switch_hdr_action = MakeAction(gen_switch_hdr,
1352                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1353
1354    # Instantiate actions for each header
1355    for hdr in switch_headers:
1356        env.Command(hdr, [], switch_hdr_action)
1357
1358    isa_target = Dir('.').up().name.lower().replace('_', '-')
1359    env['PHONY_BASE'] = '#'+isa_target
1360    all_isa_deps[isa_target] = None
1361
1362Export('make_switching_dir')
1363
1364def make_gpu_switching_dir(dname, switch_headers, env):
1365    # Generate the header.  target[0] is the full path of the output
1366    # header to generate.  'source' is a dummy variable, since we get the
1367    # list of ISAs from env['ALL_ISA_LIST'].
1368    def gen_switch_hdr(target, source, env):
1369        fname = str(target[0])
1370
1371        isa = env['TARGET_GPU_ISA'].lower()
1372
1373        try:
1374            f = open(fname, 'w')
1375            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1376            f.close()
1377        except IOError:
1378            print "Failed to create %s" % fname
1379            raise
1380
1381    # Build SCons Action object. 'varlist' specifies env vars that this
1382    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1383    # should get re-executed.
1384    switch_hdr_action = MakeAction(gen_switch_hdr,
1385                          Transform("GENERATE"), varlist=['ALL_ISA_GPU_LIST'])
1386
1387    # Instantiate actions for each header
1388    for hdr in switch_headers:
1389        env.Command(hdr, [], switch_hdr_action)
1390
1391Export('make_gpu_switching_dir')
1392
1393# all-isas -> all-deps -> all-environs -> all_targets
1394main.Alias('#all-isas', [])
1395main.Alias('#all-deps', '#all-isas')
1396
1397# Dummy target to ensure all environments are created before telling
1398# SCons what to actually make (the command line arguments).  We attach
1399# them to the dependence graph after the environments are complete.
1400ORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
1401def environsComplete(target, source, env):
1402    for t in ORIG_BUILD_TARGETS:
1403        main.Depends('#all-targets', t)
1404
1405# Each build/* switching_dir attaches its *-environs target to #all-environs.
1406main.Append(BUILDERS = {'CompleteEnvirons' :
1407                        Builder(action=MakeAction(environsComplete, None))})
1408main.CompleteEnvirons('#all-environs', [])
1409
1410def doNothing(**ignored): pass
1411main.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
1412
1413# The final target to which all the original targets ultimately get attached.
1414main.Dummy('#all-targets', '#all-environs')
1415BUILD_TARGETS[:] = ['#all-targets']
1416
1417###################################################
1418#
1419# Define build environments for selected configurations.
1420#
1421###################################################
1422
1423for variant_path in variant_paths:
1424    if not GetOption('silent'):
1425        print "Building in", variant_path
1426
1427    # Make a copy of the build-root environment to use for this config.
1428    env = main.Clone()
1429    env['BUILDDIR'] = variant_path
1430
1431    # variant_dir is the tail component of build path, and is used to
1432    # determine the build parameters (e.g., 'ALPHA_SE')
1433    (build_root, variant_dir) = splitpath(variant_path)
1434
1435    # Set env variables according to the build directory config.
1436    sticky_vars.files = []
1437    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1438    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1439    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1440    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1441    if isfile(current_vars_file):
1442        sticky_vars.files.append(current_vars_file)
1443        if not GetOption('silent'):
1444            print "Using saved variables file %s" % current_vars_file
1445    else:
1446        # Build dir-specific variables file doesn't exist.
1447
1448        # Make sure the directory is there so we can create it later
1449        opt_dir = dirname(current_vars_file)
1450        if not isdir(opt_dir):
1451            mkdir(opt_dir)
1452
1453        # Get default build variables from source tree.  Variables are
1454        # normally determined by name of $VARIANT_DIR, but can be
1455        # overridden by '--default=' arg on command line.
1456        default = GetOption('default')
1457        opts_dir = joinpath(main.root.abspath, 'build_opts')
1458        if default:
1459            default_vars_files = [joinpath(build_root, 'variables', default),
1460                                  joinpath(opts_dir, default)]
1461        else:
1462            default_vars_files = [joinpath(opts_dir, variant_dir)]
1463        existing_files = filter(isfile, default_vars_files)
1464        if existing_files:
1465            default_vars_file = existing_files[0]
1466            sticky_vars.files.append(default_vars_file)
1467            print "Variables file %s not found,\n  using defaults in %s" \
1468                  % (current_vars_file, default_vars_file)
1469        else:
1470            print "Error: cannot find variables file %s or " \
1471                  "default file(s) %s" \
1472                  % (current_vars_file, ' or '.join(default_vars_files))
1473            Exit(1)
1474
1475    # Apply current variable settings to env
1476    sticky_vars.Update(env)
1477
1478    help_texts["local_vars"] += \
1479        "Build variables for %s:\n" % variant_dir \
1480                 + sticky_vars.GenerateHelpText(env)
1481
1482    # Process variable settings.
1483
1484    if not have_fenv and env['USE_FENV']:
1485        print "Warning: <fenv.h> not available; " \
1486              "forcing USE_FENV to False in", variant_dir + "."
1487        env['USE_FENV'] = False
1488
1489    if not env['USE_FENV']:
1490        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1491        print "         FP results may deviate slightly from other platforms."
1492
1493    if env['EFENCE']:
1494        env.Append(LIBS=['efence'])
1495
1496    if env['USE_KVM']:
1497        if not have_kvm:
1498            print "Warning: Can not enable KVM, host seems to lack KVM support"
1499            env['USE_KVM'] = False
1500        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1501            print "Info: KVM support disabled due to unsupported host and " \
1502                "target ISA combination"
1503            env['USE_KVM'] = False
1504
1505    # Warn about missing optional functionality
1506    if env['USE_KVM']:
1507        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1508            print "Warning: perf_event headers lack support for the " \
1509                "exclude_host attribute. KVM instruction counts will " \
1510                "be inaccurate."
1511
1512    # Save sticky variable settings back to current variables file
1513    sticky_vars.Save(current_vars_file, env)
1514
1515    if env['USE_SSE2']:
1516        env.Append(CCFLAGS=['-msse2'])
1517
1518    # The src/SConscript file sets up the build rules in 'env' according
1519    # to the configured variables.  It returns a list of environments,
1520    # one for each variant build (debug, opt, etc.)
1521    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1522
1523def pairwise(iterable):
1524    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1525    a, b = itertools.tee(iterable)
1526    b.next()
1527    return itertools.izip(a, b)
1528
1529# Create false dependencies so SCons will parse ISAs, establish
1530# dependencies, and setup the build Environments serially. Either
1531# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1532# greater than 1. It appears to be standard race condition stuff; it
1533# doesn't always fail, but usually, and the behaviors are different.
1534# Every time I tried to remove this, builds would fail in some
1535# creative new way. So, don't do that. You'll want to, though, because
1536# tests/SConscript takes a long time to make its Environments.
1537for t1, t2 in pairwise(sorted(all_isa_deps.iterkeys())):
1538    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1539    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1540
1541# base help text
1542Help('''
1543Usage: scons [scons options] [build variables] [target(s)]
1544
1545Extra scons options:
1546%(options)s
1547
1548Global build variables:
1549%(global_vars)s
1550
1551%(local_vars)s
1552''' % help_texts)
1553