SConstruct revision 12230
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2013, 2015-2017 ARM Limited
4955SN/A# All rights reserved.
5955SN/A#
6955SN/A# The license below extends only to copyright in the software and shall
7955SN/A# not be construed as granting a license to any other intellectual
8955SN/A# property including but not limited to intellectual property relating
9955SN/A# to a hardware implementation of the functionality of the software
10955SN/A# licensed hereunder.  You may use the software subject to the license
11955SN/A# terms below provided that you ensure that this notice is replicated
12955SN/A# unmodified and in its entirety in all distributions of the software,
13955SN/A# modified or unmodified, in source code or in binary form.
14955SN/A#
15955SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
16955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
17955SN/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
282665Ssaidi@eecs.umich.edu# contributors may be used to endorse or promote products derived from
292665Ssaidi@eecs.umich.edu# 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
352632Sstever@eecs.umich.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
362632Sstever@eecs.umich.edu# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
372632Sstever@eecs.umich.edu# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
382632Sstever@eecs.umich.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
402632Sstever@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
412632Sstever@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
422761Sstever@eecs.umich.edu#
432632Sstever@eecs.umich.edu# Authors: Steve Reinhardt
442632Sstever@eecs.umich.edu#          Nathan Binkert
452632Sstever@eecs.umich.edu
462761Sstever@eecs.umich.edu###################################################
472761Sstever@eecs.umich.edu#
482761Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
492632Sstever@eecs.umich.edu#
502632Sstever@eecs.umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
512761Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
522761Sstever@eecs.umich.edu# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
532761Sstever@eecs.umich.edu# the optimized full-system version).
542761Sstever@eecs.umich.edu#
552761Sstever@eecs.umich.edu# 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
572632Sstever@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:
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
63955SN/A#   scons to search up the directory tree for this SConstruct file.
64955SN/A#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
65955SN/A#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
66955SN/A#
67955SN/A#   The following two commands are equivalent and demonstrate building
68955SN/A#   in a directory outside of the source tree.  The '-C' option tells
693918Ssaidi@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
703716Sstever@eecs.umich.edu#   file.
71955SN/A#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
722656Sstever@eecs.umich.edu#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
732656Sstever@eecs.umich.edu#
742656Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
752656Sstever@eecs.umich.edu# 'gem5' directory (or use -u or -C to tell scons where to find this
762656Sstever@eecs.umich.edu# file), you can use 'scons -h' to print all the gem5-specific build
772656Sstever@eecs.umich.edu# options as well.
782656Sstever@eecs.umich.edu#
792653Sstever@eecs.umich.edu###################################################
802653Sstever@eecs.umich.edu
812653Sstever@eecs.umich.edu# Check for recent-enough Python and SCons versions.
822653Sstever@eecs.umich.edutry:
832653Sstever@eecs.umich.edu    # Really old versions of scons only take two options for the
842653Sstever@eecs.umich.edu    # function, so check once without the revision and once with the
852653Sstever@eecs.umich.edu    # revision, the first instance will fail for stuff other than
862653Sstever@eecs.umich.edu    # 0.98, and the second will fail for 0.98.0
872653Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98)
882653Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98, 1)
892653Sstever@eecs.umich.eduexcept SystemExit, e:
901852SN/A    print """
91955SN/AFor more details, see:
92955SN/A    http://gem5.org/Dependencies
93955SN/A"""
943717Sstever@eecs.umich.edu    raise
953716Sstever@eecs.umich.edu
96955SN/A# pybind11 requires python 2.7
971533SN/Atry:
983716Sstever@eecs.umich.edu    EnsurePythonVersion(2, 7)
991533SN/Aexcept SystemExit, e:
100955SN/A    print """
101955SN/AYou can use a non-default installation of the Python interpreter by
1022632Sstever@eecs.umich.edurearranging your PATH so that scons finds the non-default 'python' and
1032632Sstever@eecs.umich.edu'python-config' first.
104955SN/A
105955SN/AFor more details, see:
106955SN/A    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
107955SN/A"""
1082632Sstever@eecs.umich.edu    raise
109955SN/A
1102632Sstever@eecs.umich.edu# Global Python includes
1112632Sstever@eecs.umich.eduimport itertools
1122632Sstever@eecs.umich.eduimport os
1132632Sstever@eecs.umich.eduimport re
1142632Sstever@eecs.umich.eduimport shutil
1152632Sstever@eecs.umich.eduimport subprocess
1162632Sstever@eecs.umich.eduimport sys
1173053Sstever@eecs.umich.edu
1183053Sstever@eecs.umich.edufrom os import mkdir, environ
1193053Sstever@eecs.umich.edufrom os.path import abspath, basename, dirname, expanduser, normpath
1203053Sstever@eecs.umich.edufrom os.path import exists,  isdir, isfile
1213053Sstever@eecs.umich.edufrom os.path import join as joinpath, split as splitpath
1223053Sstever@eecs.umich.edu
1233053Sstever@eecs.umich.edu# SCons includes
1243053Sstever@eecs.umich.eduimport SCons
1253053Sstever@eecs.umich.eduimport SCons.Node
1263053Sstever@eecs.umich.edu
1273053Sstever@eecs.umich.eduextra_python_paths = [
1283053Sstever@eecs.umich.edu    Dir('src/python').srcnode().abspath, # gem5 includes
1293053Sstever@eecs.umich.edu    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1303053Sstever@eecs.umich.edu    ]
1313053Sstever@eecs.umich.edu
1323053Sstever@eecs.umich.edusys.path[1:1] = extra_python_paths
1332632Sstever@eecs.umich.edu
1342632Sstever@eecs.umich.edufrom m5.util import compareVersions, readCommand
1352632Sstever@eecs.umich.edufrom m5.util.terminal import get_termcap
1362632Sstever@eecs.umich.edu
1372632Sstever@eecs.umich.eduhelp_texts = {
1382632Sstever@eecs.umich.edu    "options" : "",
1393718Sstever@eecs.umich.edu    "global_vars" : "",
1403718Sstever@eecs.umich.edu    "local_vars" : ""
1413718Sstever@eecs.umich.edu}
1423718Sstever@eecs.umich.edu
1433718Sstever@eecs.umich.eduExport("help_texts")
1443718Sstever@eecs.umich.edu
1453718Sstever@eecs.umich.edu
1463718Sstever@eecs.umich.edu# There's a bug in scons in that (1) by default, the help texts from
1473718Sstever@eecs.umich.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1483718Sstever@eecs.umich.edu# and (2) you can override the help displayed by 'scons -h' using the
1493718Sstever@eecs.umich.edu# Help() function, but these two features are incompatible: once
1503718Sstever@eecs.umich.edu# you've overridden the help text using Help(), there's no way to get
1513718Sstever@eecs.umich.edu# at the help texts from AddOptions.  See:
1522634Sstever@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1532634Sstever@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1542632Sstever@eecs.umich.edu# This hack lets us extract the help text from AddOptions and
1552638Sstever@eecs.umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1562632Sstever@eecs.umich.edu# we can just use AddOption directly.
1572632Sstever@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1582632Sstever@eecs.umich.edu    col_width = 30
1592632Sstever@eecs.umich.edu
1602632Sstever@eecs.umich.edu    help = "  " + ", ".join(args)
1612632Sstever@eecs.umich.edu    if "help" in kwargs:
1621858SN/A        length = len(help)
1633716Sstever@eecs.umich.edu        if length >= col_width:
1642638Sstever@eecs.umich.edu            help += "\n" + " " * col_width
1652638Sstever@eecs.umich.edu        else:
1662638Sstever@eecs.umich.edu            help += " " * (col_width - length)
1672638Sstever@eecs.umich.edu        help += kwargs["help"]
1682638Sstever@eecs.umich.edu    help_texts["options"] += help + "\n"
1692638Sstever@eecs.umich.edu
1702638Sstever@eecs.umich.edu    AddOption(*args, **kwargs)
1713716Sstever@eecs.umich.edu
1722634Sstever@eecs.umich.eduAddLocalOption('--colors', dest='use_colors', action='store_true',
1732634Sstever@eecs.umich.edu               help="Add color to abbreviated scons output")
174955SN/AAddLocalOption('--no-colors', dest='use_colors', action='store_false',
175955SN/A               help="Don't add color to abbreviated scons output")
176955SN/AAddLocalOption('--with-cxx-config', dest='with_cxx_config',
177955SN/A               action='store_true',
178955SN/A               help="Build with support for C++-based configuration")
179955SN/AAddLocalOption('--default', dest='default', type='string', action='store',
180955SN/A               help='Override which build_opts file to use for defaults')
181955SN/AAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1821858SN/A               help='Disable style checking hooks')
1831858SN/AAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1842632Sstever@eecs.umich.edu               help='Disable Link-Time Optimization for fast')
185955SN/AAddLocalOption('--force-lto', dest='force_lto', action='store_true',
1863643Ssaidi@eecs.umich.edu               help='Use Link-Time Optimization instead of partial linking' +
1873643Ssaidi@eecs.umich.edu                    ' when the compiler doesn\'t support using them together.')
1883643Ssaidi@eecs.umich.eduAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1893643Ssaidi@eecs.umich.edu               help='Update test reference outputs')
1903643Ssaidi@eecs.umich.eduAddLocalOption('--verbose', dest='verbose', action='store_true',
1913643Ssaidi@eecs.umich.edu               help='Print full tool command lines')
1923643Ssaidi@eecs.umich.eduAddLocalOption('--without-python', dest='without_python',
1933643Ssaidi@eecs.umich.edu               action='store_true',
1943716Sstever@eecs.umich.edu               help='Build without Python configuration support')
1951105SN/AAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1962667Sstever@eecs.umich.edu               action='store_true',
1972667Sstever@eecs.umich.edu               help='Disable linking against tcmalloc')
1982667Sstever@eecs.umich.eduAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1992667Sstever@eecs.umich.edu               help='Build with Undefined Behavior Sanitizer if available')
2002667Sstever@eecs.umich.eduAddLocalOption('--with-asan', dest='with_asan', action='store_true',
2012667Sstever@eecs.umich.edu               help='Build with Address Sanitizer if available')
2021869SN/A
2031869SN/Aif GetOption('no_lto') and GetOption('force_lto'):
2041869SN/A    print '--no-lto and --force-lto are mutually exclusive'
2051869SN/A    Exit(1)
2061869SN/A
2071065SN/Atermcap = get_termcap(GetOption('use_colors'))
2082632Sstever@eecs.umich.edu
2092632Sstever@eecs.umich.edu########################################################################
2103918Ssaidi@eecs.umich.edu#
2113918Ssaidi@eecs.umich.edu# Set up the main build environment.
2123918Ssaidi@eecs.umich.edu#
2133918Ssaidi@eecs.umich.edu########################################################################
2143918Ssaidi@eecs.umich.edu
2153918Ssaidi@eecs.umich.edu# export TERM so that clang reports errors in color
2163918Ssaidi@eecs.umich.eduuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
2173918Ssaidi@eecs.umich.edu                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
2183918Ssaidi@eecs.umich.edu                 'PYTHONPATH', 'RANLIB', 'TERM' ])
2193918Ssaidi@eecs.umich.edu
2203918Ssaidi@eecs.umich.eduuse_prefixes = [
2213918Ssaidi@eecs.umich.edu    "ASAN_",           # address sanitizer symbolizer path and settings
222955SN/A    "CCACHE_",         # ccache (caching compiler wrapper) configuration
2231858SN/A    "CCC_",            # clang static analyzer configuration
2243918Ssaidi@eecs.umich.edu    "DISTCC_",         # distcc (distributed compiler wrapper) configuration
2253918Ssaidi@eecs.umich.edu    "INCLUDE_SERVER_", # distcc pump server settings
2263918Ssaidi@eecs.umich.edu    "M5",              # M5 configuration (e.g., path to kernels)
2273918Ssaidi@eecs.umich.edu    ]
2283918Ssaidi@eecs.umich.edu
2293918Ssaidi@eecs.umich.eduuse_env = {}
2303918Ssaidi@eecs.umich.edufor key,val in sorted(os.environ.iteritems()):
2313918Ssaidi@eecs.umich.edu    if key in use_vars or \
2323918Ssaidi@eecs.umich.edu            any([key.startswith(prefix) for prefix in use_prefixes]):
2333918Ssaidi@eecs.umich.edu        use_env[key] = val
2343918Ssaidi@eecs.umich.edu
2353918Ssaidi@eecs.umich.edu# Tell scons to avoid implicit command dependencies to avoid issues
2363918Ssaidi@eecs.umich.edu# with the param wrappes being compiled twice (see
2373918Ssaidi@eecs.umich.edu# http://scons.tigris.org/issues/show_bug.cgi?id=2811)
2383918Ssaidi@eecs.umich.edumain = Environment(ENV=use_env, IMPLICIT_COMMAND_DEPENDENCIES=0)
2393918Ssaidi@eecs.umich.edumain.Decider('MD5-timestamp')
2401851SN/Amain.root = Dir(".")         # The current directory (where this file lives).
2411851SN/Amain.srcdir = Dir("src")     # The source directory
2421858SN/A
2432632Sstever@eecs.umich.edumain_dict_keys = main.Dictionary().keys()
244955SN/A
2453053Sstever@eecs.umich.edu# Check that we have a C/C++ compiler
2463053Sstever@eecs.umich.eduif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2473053Sstever@eecs.umich.edu    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2483053Sstever@eecs.umich.edu    Exit(1)
2493053Sstever@eecs.umich.edu
2503053Sstever@eecs.umich.edu# add useful python code PYTHONPATH so it can be used by subprocesses
2513053Sstever@eecs.umich.edu# as well
2523053Sstever@eecs.umich.edumain.AppendENVPath('PYTHONPATH', extra_python_paths)
2533053Sstever@eecs.umich.edu
2543053Sstever@eecs.umich.edu########################################################################
2553053Sstever@eecs.umich.edu#
2563053Sstever@eecs.umich.edu# Mercurial Stuff.
2573053Sstever@eecs.umich.edu#
2583053Sstever@eecs.umich.edu# If the gem5 directory is a mercurial repository, we should do some
2593053Sstever@eecs.umich.edu# extra things.
2603053Sstever@eecs.umich.edu#
2613053Sstever@eecs.umich.edu########################################################################
2623053Sstever@eecs.umich.edu
2633053Sstever@eecs.umich.eduhgdir = main.root.Dir(".hg")
2642667Sstever@eecs.umich.edu
2652667Sstever@eecs.umich.edu
2662667Sstever@eecs.umich.edustyle_message = """
2672667Sstever@eecs.umich.eduYou're missing the gem5 style hook, which automatically checks your code
2682667Sstever@eecs.umich.eduagainst the gem5 style rules on %s.
2692667Sstever@eecs.umich.eduThis script will now install the hook in your %s.
2702667Sstever@eecs.umich.eduPress enter to continue, or ctrl-c to abort: """
2712667Sstever@eecs.umich.edu
2722667Sstever@eecs.umich.edumercurial_style_message = """
2732667Sstever@eecs.umich.eduYou're missing the gem5 style hook, which automatically checks your code
2742667Sstever@eecs.umich.eduagainst the gem5 style rules on hg commit and qrefresh commands.
2752667Sstever@eecs.umich.eduThis script will now install the hook in your .hg/hgrc file.
2762638Sstever@eecs.umich.eduPress enter to continue, or ctrl-c to abort: """
2772638Sstever@eecs.umich.edu
2782638Sstever@eecs.umich.edugit_style_message = """
2793716Sstever@eecs.umich.eduYou're missing the gem5 style or commit message hook. These hooks help
2803716Sstever@eecs.umich.eduto ensure that your code follows gem5's style rules on git commit.
2811858SN/AThis script will now install the hook in your .git/hooks/ directory.
2823118Sstever@eecs.umich.eduPress enter to continue, or ctrl-c to abort: """
2833118Sstever@eecs.umich.edu
2843118Sstever@eecs.umich.edumercurial_style_upgrade_message = """
2853118Sstever@eecs.umich.eduYour Mercurial style hooks are not up-to-date. This script will now
2863118Sstever@eecs.umich.edutry to automatically update them. A backup of your hgrc will be saved
2873118Sstever@eecs.umich.eduin .hg/hgrc.old.
2883118Sstever@eecs.umich.eduPress enter to continue, or ctrl-c to abort: """
2893118Sstever@eecs.umich.edu
2903118Sstever@eecs.umich.edumercurial_style_hook = """
2913118Sstever@eecs.umich.edu# The following lines were automatically added by gem5/SConstruct
2923118Sstever@eecs.umich.edu# to provide the gem5 style-checking hooks
2933716Sstever@eecs.umich.edu[extensions]
2943118Sstever@eecs.umich.eduhgstyle = %s/util/hgstyle.py
2953118Sstever@eecs.umich.edu
2963118Sstever@eecs.umich.edu[hooks]
2973118Sstever@eecs.umich.edupretxncommit.style = python:hgstyle.check_style
2983118Sstever@eecs.umich.edupre-qrefresh.style = python:hgstyle.check_style
2993118Sstever@eecs.umich.edu# End of SConstruct additions
3003118Sstever@eecs.umich.edu
3013118Sstever@eecs.umich.edu""" % (main.root.abspath)
3023118Sstever@eecs.umich.edu
3033716Sstever@eecs.umich.edumercurial_lib_not_found = """
3043118Sstever@eecs.umich.eduMercurial libraries cannot be found, ignoring style hook.  If
3053118Sstever@eecs.umich.eduyou are a gem5 developer, please fix this and run the style
3063118Sstever@eecs.umich.eduhook. It is important.
3073118Sstever@eecs.umich.edu"""
3083118Sstever@eecs.umich.edu
3093118Sstever@eecs.umich.edu# Check for style hook and prompt for installation if it's not there.
3103118Sstever@eecs.umich.edu# Skip this if --ignore-style was specified, there's no interactive
3113118Sstever@eecs.umich.edu# terminal to prompt, or no recognized revision control system can be
3123118Sstever@eecs.umich.edu# found.
3133118Sstever@eecs.umich.eduignore_style = GetOption('ignore_style') or not sys.stdin.isatty()
3143483Ssaidi@eecs.umich.edu
3153494Ssaidi@eecs.umich.edu# Try wire up Mercurial to the style hooks
3163494Ssaidi@eecs.umich.eduif not ignore_style and hgdir.exists():
3173483Ssaidi@eecs.umich.edu    style_hook = True
3183483Ssaidi@eecs.umich.edu    style_hooks = tuple()
3193483Ssaidi@eecs.umich.edu    hgrc = hgdir.File('hgrc')
3203053Sstever@eecs.umich.edu    hgrc_old = hgdir.File('hgrc.old')
3213053Sstever@eecs.umich.edu    try:
3223918Ssaidi@eecs.umich.edu        from mercurial import ui
3233053Sstever@eecs.umich.edu        ui = ui.ui()
3243053Sstever@eecs.umich.edu        ui.readconfig(hgrc.abspath)
3253053Sstever@eecs.umich.edu        style_hooks = (ui.config('hooks', 'pretxncommit.style', None),
3263053Sstever@eecs.umich.edu                       ui.config('hooks', 'pre-qrefresh.style', None))
3273053Sstever@eecs.umich.edu        style_hook = all(style_hooks)
3281858SN/A        style_extension = ui.config('extensions', 'style', None)
3291858SN/A    except ImportError:
3301858SN/A        print mercurial_lib_not_found
3311858SN/A
3321858SN/A    if "python:style.check_style" in style_hooks:
3331858SN/A        # Try to upgrade the style hooks
3341859SN/A        print mercurial_style_upgrade_message
3351858SN/A        # continue unless user does ctrl-c/ctrl-d etc.
3361858SN/A        try:
3371858SN/A            raw_input()
3381859SN/A        except:
3391859SN/A            print "Input exception, exiting scons.\n"
3401862SN/A            sys.exit(1)
3413053Sstever@eecs.umich.edu        shutil.copyfile(hgrc.abspath, hgrc_old.abspath)
3423053Sstever@eecs.umich.edu        re_style_hook = re.compile(r"^([^=#]+)\.style\s*=\s*([^#\s]+).*")
3433053Sstever@eecs.umich.edu        re_style_extension = re.compile("style\s*=\s*([^#\s]+).*")
3443053Sstever@eecs.umich.edu        old, new = open(hgrc_old.abspath, 'r'), open(hgrc.abspath, 'w')
3451859SN/A        for l in old:
3461859SN/A            m_hook = re_style_hook.match(l)
3471859SN/A            m_ext = re_style_extension.match(l)
3481859SN/A            if m_hook:
3491859SN/A                hook, check = m_hook.groups()
3501859SN/A                if check != "python:style.check_style":
3511859SN/A                    print "Warning: %s.style is using a non-default " \
3521859SN/A                        "checker: %s" % (hook, check)
3531862SN/A                if hook not in ("pretxncommit", "pre-qrefresh"):
3541859SN/A                    print "Warning: Updating unknown style hook: %s" % hook
3551859SN/A
3561859SN/A                l = "%s.style = python:hgstyle.check_style\n" % hook
3571858SN/A            elif m_ext and m_ext.group(1) == style_extension:
3581858SN/A                l = "hgstyle = %s/util/hgstyle.py\n" % main.root.abspath
3592139SN/A
3602139SN/A            new.write(l)
3612139SN/A    elif not style_hook:
3622155SN/A        print mercurial_style_message,
3632623SN/A        # continue unless user does ctrl-c/ctrl-d etc.
3643583Sbinkertn@umich.edu        try:
3653583Sbinkertn@umich.edu            raw_input()
3663717Sstever@eecs.umich.edu        except:
3673583Sbinkertn@umich.edu            print "Input exception, exiting scons.\n"
3682155SN/A            sys.exit(1)
3691869SN/A        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
3701869SN/A        print "Adding style hook to", hgrc_path, "\n"
3711869SN/A        try:
3721869SN/A            with open(hgrc_path, 'a') as f:
3731869SN/A                f.write(mercurial_style_hook)
3742139SN/A        except:
3751869SN/A            print "Error updating", hgrc_path
3762508SN/A            sys.exit(1)
3772508SN/A
3782508SN/Adef install_git_style_hooks():
3792508SN/A    try:
3803685Sktlim@umich.edu        gitdir = Dir(readCommand(
3812635Sstever@eecs.umich.edu            ["git", "rev-parse", "--git-dir"]).strip("\n"))
3821869SN/A    except Exception, e:
3831869SN/A        print "Warning: Failed to find git repo directory: %s" % e
3841869SN/A        return
3851869SN/A
3861869SN/A    git_hooks = gitdir.Dir("hooks")
3871869SN/A    def hook_exists(hook_name):
3881869SN/A        hook = git_hooks.File(hook_name)
3891869SN/A        return hook.exists()
3901965SN/A
3911965SN/A    def hook_install(hook_name, script):
3921965SN/A        hook = git_hooks.File(hook_name)
3931869SN/A        if hook.exists():
3941869SN/A            print "Warning: Can't install %s, hook already exists." % hook_name
3952733Sktlim@umich.edu            return
3961869SN/A
3971884SN/A        if hook.islink():
3981884SN/A            print "Warning: Removing broken symlink for hook %s." % hook_name
3993356Sbinkertn@umich.edu            os.unlink(hook.get_abspath())
4003356Sbinkertn@umich.edu
4013356Sbinkertn@umich.edu        if not git_hooks.exists():
4023356Sbinkertn@umich.edu            mkdir(git_hooks.get_abspath())
4031869SN/A            git_hooks.clear()
4041858SN/A
4051869SN/A        abs_symlink_hooks = git_hooks.islink() and \
4061869SN/A            os.path.isabs(os.readlink(git_hooks.get_abspath()))
4071869SN/A
4081869SN/A        # Use a relative symlink if the hooks live in the source directory,
4091869SN/A        # and the hooks directory is not a symlink to an absolute path.
4101858SN/A        if hook.is_under(main.root) and not abs_symlink_hooks:
4112761Sstever@eecs.umich.edu            script_path = os.path.relpath(
4121869SN/A                os.path.realpath(script.get_abspath()),
4132733Sktlim@umich.edu                os.path.realpath(hook.Dir(".").get_abspath()))
4143584Ssaidi@eecs.umich.edu        else:
4151869SN/A            script_path = script.get_abspath()
4161869SN/A
4171869SN/A        try:
4181869SN/A            os.symlink(script_path, hook.get_abspath())
4191869SN/A        except:
4201869SN/A            print "Error updating git %s hook" % hook_name
4211858SN/A            raise
422955SN/A
423955SN/A    if hook_exists("pre-commit") and hook_exists("commit-msg"):
4241869SN/A        return
4251869SN/A
4261869SN/A    print git_style_message,
4271869SN/A    try:
4281869SN/A        raw_input()
4291869SN/A    except:
4301869SN/A        print "Input exception, exiting scons.\n"
4311869SN/A        sys.exit(1)
4321869SN/A
4331869SN/A    git_style_script = File("util/git-pre-commit.py")
4341869SN/A    git_msg_script = File("ext/git-commit-msg")
4351869SN/A
4361869SN/A    hook_install("pre-commit", git_style_script)
4371869SN/A    hook_install("commit-msg", git_msg_script)
4381869SN/A
4391869SN/A# Try to wire up git to the style hooks
4401869SN/Aif not ignore_style and main.root.Entry(".git").exists():
4411869SN/A    install_git_style_hooks()
4421869SN/A
4431869SN/A###################################################
4441869SN/A#
4451869SN/A# Figure out which configurations to set up based on the path(s) of
4461869SN/A# the target(s).
4471869SN/A#
4481869SN/A###################################################
4491869SN/A
4501869SN/A# Find default configuration & binary.
4511869SN/ADefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
4521869SN/A
4533716Sstever@eecs.umich.edu# helper function: find last occurrence of element in list
4543356Sbinkertn@umich.edudef rfind(l, elt, offs = -1):
4553356Sbinkertn@umich.edu    for i in range(len(l)+offs, 0, -1):
4563356Sbinkertn@umich.edu        if l[i] == elt:
4573356Sbinkertn@umich.edu            return i
4583356Sbinkertn@umich.edu    raise ValueError, "element not found"
4593356Sbinkertn@umich.edu
4603356Sbinkertn@umich.edu# Take a list of paths (or SCons Nodes) and return a list with all
4611869SN/A# paths made absolute and ~-expanded.  Paths will be interpreted
4621869SN/A# relative to the launch directory unless a different root is provided
4631869SN/Adef makePathListAbsolute(path_list, root=GetLaunchDir()):
4641869SN/A    return [abspath(joinpath(root, expanduser(str(p))))
4651869SN/A            for p in path_list]
4661869SN/A
4671869SN/A# Each target must have 'build' in the interior of the path; the
4682655Sstever@eecs.umich.edu# directory below this will determine the build parameters.  For
4692655Sstever@eecs.umich.edu# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
4702655Sstever@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
4712655Sstever@eecs.umich.edu# follow 'build' in the build path.
4722655Sstever@eecs.umich.edu
4732655Sstever@eecs.umich.edu# The funky assignment to "[:]" is needed to replace the list contents
4742655Sstever@eecs.umich.edu# in place rather than reassign the symbol to a new list, which
4752655Sstever@eecs.umich.edu# doesn't work (obviously!).
4762655Sstever@eecs.umich.eduBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
4772655Sstever@eecs.umich.edu
4782655Sstever@eecs.umich.edu# Generate a list of the unique build roots and configs that the
4792655Sstever@eecs.umich.edu# collected targets reference.
4802655Sstever@eecs.umich.eduvariant_paths = []
4812655Sstever@eecs.umich.edubuild_root = None
4822655Sstever@eecs.umich.edufor t in BUILD_TARGETS:
4832655Sstever@eecs.umich.edu    path_dirs = t.split('/')
4842655Sstever@eecs.umich.edu    try:
4852655Sstever@eecs.umich.edu        build_top = rfind(path_dirs, 'build', -2)
4862655Sstever@eecs.umich.edu    except:
4872655Sstever@eecs.umich.edu        print "Error: no non-leaf 'build' dir found on target path", t
4882655Sstever@eecs.umich.edu        Exit(1)
4892655Sstever@eecs.umich.edu    this_build_root = joinpath('/',*path_dirs[:build_top+1])
4902655Sstever@eecs.umich.edu    if not build_root:
4912655Sstever@eecs.umich.edu        build_root = this_build_root
4922655Sstever@eecs.umich.edu    else:
4932655Sstever@eecs.umich.edu        if this_build_root != build_root:
4942634Sstever@eecs.umich.edu            print "Error: build targets not under same build root\n"\
4952634Sstever@eecs.umich.edu                  "  %s\n  %s" % (build_root, this_build_root)
4962634Sstever@eecs.umich.edu            Exit(1)
4972634Sstever@eecs.umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
4982634Sstever@eecs.umich.edu    if variant_path not in variant_paths:
4992634Sstever@eecs.umich.edu        variant_paths.append(variant_path)
5002638Sstever@eecs.umich.edu
5012638Sstever@eecs.umich.edu# Make sure build_root exists (might not if this is the first build there)
5023716Sstever@eecs.umich.eduif not isdir(build_root):
5032638Sstever@eecs.umich.edu    mkdir(build_root)
5042638Sstever@eecs.umich.edumain['BUILDROOT'] = build_root
5051869SN/A
5061869SN/AExport('main')
5073546Sgblack@eecs.umich.edu
5083546Sgblack@eecs.umich.edumain.SConsignFile(joinpath(build_root, "sconsign"))
5093546Sgblack@eecs.umich.edu
5103546Sgblack@eecs.umich.edu# Default duplicate option is to use hard links, but this messes up
5113546Sgblack@eecs.umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
5123546Sgblack@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
5133546Sgblack@eecs.umich.edu# (soft) links work better.
5143546Sgblack@eecs.umich.edumain.SetOption('duplicate', 'soft-copy')
5153546Sgblack@eecs.umich.edu
5163546Sgblack@eecs.umich.edu#
5173546Sgblack@eecs.umich.edu# Set up global sticky variables... these are common to an entire build
5183546Sgblack@eecs.umich.edu# tree (not specific to a particular build like ALPHA_SE)
5193546Sgblack@eecs.umich.edu#
5203546Sgblack@eecs.umich.edu
5213546Sgblack@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
5223546Sgblack@eecs.umich.edu
5233546Sgblack@eecs.umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
5243546Sgblack@eecs.umich.edu
5253546Sgblack@eecs.umich.eduglobal_vars.AddVariables(
5263546Sgblack@eecs.umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
5273546Sgblack@eecs.umich.edu    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
5283546Sgblack@eecs.umich.edu    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
5293546Sgblack@eecs.umich.edu    ('BATCH', 'Use batch pool for build and tests', False),
5303546Sgblack@eecs.umich.edu    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
5313546Sgblack@eecs.umich.edu    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
5323546Sgblack@eecs.umich.edu    ('EXTRAS', 'Add extra directories to the compilation', '')
5333546Sgblack@eecs.umich.edu    )
5343546Sgblack@eecs.umich.edu
5353546Sgblack@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
5363546Sgblack@eecs.umich.eduglobal_vars.Update(main)
5373546Sgblack@eecs.umich.eduhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
5383546Sgblack@eecs.umich.edu
5393546Sgblack@eecs.umich.edu# Save sticky variable settings back to current variables file
5403546Sgblack@eecs.umich.eduglobal_vars.Save(global_vars_file, main)
5413546Sgblack@eecs.umich.edu
5423546Sgblack@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
5433546Sgblack@eecs.umich.edu# look for sources etc.  This list is exported as extras_dir_list.
5443546Sgblack@eecs.umich.edubase_dir = main.srcdir.abspath
5453546Sgblack@eecs.umich.eduif main['EXTRAS']:
5463546Sgblack@eecs.umich.edu    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
547955SN/Aelse:
548955SN/A    extras_dir_list = []
549955SN/A
550955SN/AExport('base_dir')
5511858SN/AExport('extras_dir_list')
5521858SN/A
5531858SN/A# the ext directory should be on the #includes path
5542632Sstever@eecs.umich.edumain.Append(CPPPATH=[Dir('ext')])
5552632Sstever@eecs.umich.edu
5562632Sstever@eecs.umich.edu# Add shared top-level headers
5572632Sstever@eecs.umich.edumain.Prepend(CPPPATH=Dir('include'))
5582632Sstever@eecs.umich.edu
5592634Sstever@eecs.umich.edudef strip_build_path(path, env):
5602638Sstever@eecs.umich.edu    path = str(path)
5612023SN/A    variant_base = env['BUILDROOT'] + os.path.sep
5622632Sstever@eecs.umich.edu    if path.startswith(variant_base):
5632632Sstever@eecs.umich.edu        path = path[len(variant_base):]
5642632Sstever@eecs.umich.edu    elif path.startswith('build/'):
5652632Sstever@eecs.umich.edu        path = path[6:]
5662632Sstever@eecs.umich.edu    return path
5673716Sstever@eecs.umich.edu
5682632Sstever@eecs.umich.edu# Generate a string of the form:
5692632Sstever@eecs.umich.edu#   common/path/prefix/src1, src2 -> tgt1, tgt2
5702632Sstever@eecs.umich.edu# to print while building.
5712632Sstever@eecs.umich.educlass Transform(object):
5722632Sstever@eecs.umich.edu    # all specific color settings should be here and nowhere else
5732023SN/A    tool_color = termcap.Normal
5742632Sstever@eecs.umich.edu    pfx_color = termcap.Yellow
5752632Sstever@eecs.umich.edu    srcs_color = termcap.Yellow + termcap.Bold
5761889SN/A    arrow_color = termcap.Blue + termcap.Bold
5771889SN/A    tgts_color = termcap.Yellow + termcap.Bold
5782632Sstever@eecs.umich.edu
5792632Sstever@eecs.umich.edu    def __init__(self, tool, max_sources=99):
5802632Sstever@eecs.umich.edu        self.format = self.tool_color + (" [%8s] " % tool) \
5812632Sstever@eecs.umich.edu                      + self.pfx_color + "%s" \
5823716Sstever@eecs.umich.edu                      + self.srcs_color + "%s" \
5833716Sstever@eecs.umich.edu                      + self.arrow_color + " -> " \
5842632Sstever@eecs.umich.edu                      + self.tgts_color + "%s" \
5852632Sstever@eecs.umich.edu                      + termcap.Normal
5862632Sstever@eecs.umich.edu        self.max_sources = max_sources
5872632Sstever@eecs.umich.edu
5882632Sstever@eecs.umich.edu    def __call__(self, target, source, env, for_signature=None):
5892632Sstever@eecs.umich.edu        # truncate source list according to max_sources param
5902632Sstever@eecs.umich.edu        source = source[0:self.max_sources]
5912632Sstever@eecs.umich.edu        def strip(f):
5921888SN/A            return strip_build_path(str(f), env)
5931888SN/A        if len(source) > 0:
5941869SN/A            srcs = map(strip, source)
5951869SN/A        else:
5961858SN/A            srcs = ['']
5972598SN/A        tgts = map(strip, target)
5982598SN/A        # surprisingly, os.path.commonprefix is a dumb char-by-char string
5992598SN/A        # operation that has nothing to do with paths.
6002598SN/A        com_pfx = os.path.commonprefix(srcs + tgts)
6012598SN/A        com_pfx_len = len(com_pfx)
6021858SN/A        if com_pfx:
6031858SN/A            # do some cleanup and sanity checking on common prefix
6041858SN/A            if com_pfx[-1] == ".":
6051858SN/A                # prefix matches all but file extension: ok
6061858SN/A                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
6071858SN/A                com_pfx = com_pfx[0:-1]
6081858SN/A            elif com_pfx[-1] == "/":
6091858SN/A                # common prefix is directory path: OK
6101858SN/A                pass
6111871SN/A            else:
6121858SN/A                src0_len = len(srcs[0])
6131858SN/A                tgt0_len = len(tgts[0])
6141858SN/A                if src0_len == com_pfx_len:
6151858SN/A                    # source is a substring of target, OK
6161858SN/A                    pass
6171858SN/A                elif tgt0_len == com_pfx_len:
6181858SN/A                    # target is a substring of source, need to back up to
6191858SN/A                    # avoid empty string on RHS of arrow
6201858SN/A                    sep_idx = com_pfx.rfind(".")
6211858SN/A                    if sep_idx != -1:
6221858SN/A                        com_pfx = com_pfx[0:sep_idx]
6231859SN/A                    else:
6241859SN/A                        com_pfx = ''
6251869SN/A                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
6261888SN/A                    # still splitting at file extension: ok
6272632Sstever@eecs.umich.edu                    pass
6281869SN/A                else:
6291884SN/A                    # probably a fluke; ignore it
6301884SN/A                    com_pfx = ''
6311884SN/A        # recalculate length in case com_pfx was modified
6321884SN/A        com_pfx_len = len(com_pfx)
6331884SN/A        def fmt(files):
6341884SN/A            f = map(lambda s: s[com_pfx_len:], files)
6351965SN/A            return ', '.join(f)
6361965SN/A        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
6371965SN/A
6382761Sstever@eecs.umich.eduExport('Transform')
6391869SN/A
6401869SN/A# enable the regression script to use the termcap
6412632Sstever@eecs.umich.edumain['TERMCAP'] = termcap
6422667Sstever@eecs.umich.edu
6431869SN/Aif GetOption('verbose'):
6441869SN/A    def MakeAction(action, string, *args, **kwargs):
6452929Sktlim@umich.edu        return Action(action, *args, **kwargs)
6462929Sktlim@umich.eduelse:
6473716Sstever@eecs.umich.edu    MakeAction = Action
6482929Sktlim@umich.edu    main['CCCOMSTR']        = Transform("CC")
649955SN/A    main['CXXCOMSTR']       = Transform("CXX")
6502598SN/A    main['ASCOMSTR']        = Transform("AS")
6512598SN/A    main['ARCOMSTR']        = Transform("AR", 0)
6523546Sgblack@eecs.umich.edu    main['LINKCOMSTR']      = Transform("LINK", 0)
653955SN/A    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
654955SN/A    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
655955SN/A    main['M4COMSTR']        = Transform("M4")
6561530SN/A    main['SHCCCOMSTR']      = Transform("SHCC")
657955SN/A    main['SHCXXCOMSTR']     = Transform("SHCXX")
658955SN/AExport('MakeAction')
659955SN/A
660# Initialize the Link-Time Optimization (LTO) flags
661main['LTO_CCFLAGS'] = []
662main['LTO_LDFLAGS'] = []
663
664# According to the readme, tcmalloc works best if the compiler doesn't
665# assume that we're using the builtin malloc and friends. These flags
666# are compiler-specific, so we need to set them after we detect which
667# compiler we're using.
668main['TCMALLOC_CCFLAGS'] = []
669
670CXX_version = readCommand([main['CXX'],'--version'], exception=False)
671CXX_V = readCommand([main['CXX'],'-V'], exception=False)
672
673main['GCC'] = CXX_version and CXX_version.find('g++') >= 0
674main['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
675if main['GCC'] + main['CLANG'] > 1:
676    print 'Error: How can we have two at the same time?'
677    Exit(1)
678
679# Set up default C++ compiler flags
680if main['GCC'] or main['CLANG']:
681    # As gcc and clang share many flags, do the common parts here
682    main.Append(CCFLAGS=['-pipe'])
683    main.Append(CCFLAGS=['-fno-strict-aliasing'])
684    # Enable -Wall and -Wextra and then disable the few warnings that
685    # we consistently violate
686    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
687                         '-Wno-sign-compare', '-Wno-unused-parameter'])
688    # We always compile using C++11
689    main.Append(CXXFLAGS=['-std=c++11'])
690    if sys.platform.startswith('freebsd'):
691        main.Append(CCFLAGS=['-I/usr/local/include'])
692        main.Append(CXXFLAGS=['-I/usr/local/include'])
693
694    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
695    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
696    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
697    shared_partial_flags = ['-r', '-nostdlib']
698    main.Append(PSHLINKFLAGS=shared_partial_flags)
699    main.Append(PLINKFLAGS=shared_partial_flags)
700else:
701    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
702    print "Don't know what compiler options to use for your compiler."
703    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
704    print termcap.Yellow + '       version:' + termcap.Normal,
705    if not CXX_version:
706        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
707               termcap.Normal
708    else:
709        print CXX_version.replace('\n', '<nl>')
710    print "       If you're trying to use a compiler other than GCC"
711    print "       or clang, there appears to be something wrong with your"
712    print "       environment."
713    print "       "
714    print "       If you are trying to use a compiler other than those listed"
715    print "       above you will need to ease fix SConstruct and "
716    print "       src/SConscript to support that compiler."
717    Exit(1)
718
719if main['GCC']:
720    # Check for a supported version of gcc. >= 4.8 is chosen for its
721    # level of c++11 support. See
722    # http://gcc.gnu.org/projects/cxx0x.html for details.
723    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
724    if compareVersions(gcc_version, "4.8") < 0:
725        print 'Error: gcc version 4.8 or newer required.'
726        print '       Installed version:', gcc_version
727        Exit(1)
728
729    main['GCC_VERSION'] = gcc_version
730
731    if compareVersions(gcc_version, '4.9') >= 0:
732        # Incremental linking with LTO is currently broken in gcc versions
733        # 4.9 and above. A version where everything works completely hasn't
734        # yet been identified.
735        #
736        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
737        main['BROKEN_INCREMENTAL_LTO'] = True
738    if compareVersions(gcc_version, '6.0') >= 0:
739        # gcc versions 6.0 and greater accept an -flinker-output flag which
740        # selects what type of output the linker should generate. This is
741        # necessary for incremental lto to work, but is also broken in
742        # current versions of gcc. It may not be necessary in future
743        # versions. We add it here since it might be, and as a reminder that
744        # it exists. It's excluded if lto is being forced.
745        #
746        # https://gcc.gnu.org/gcc-6/changes.html
747        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
748        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
749        if not GetOption('force_lto'):
750            main.Append(PSHLINKFLAGS='-flinker-output=rel')
751            main.Append(PLINKFLAGS='-flinker-output=rel')
752
753    # gcc from version 4.8 and above generates "rep; ret" instructions
754    # to avoid performance penalties on certain AMD chips. Older
755    # assemblers detect this as an error, "Error: expecting string
756    # instruction after `rep'"
757    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
758                                  '-o', '/dev/null'],
759                                 exception=False).split()
760
761    # version strings may contain extra distro-specific
762    # qualifiers, so play it safe and keep only what comes before
763    # the first hyphen
764    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
765
766    if not as_version or compareVersions(as_version, "2.23") < 0:
767        print termcap.Yellow + termcap.Bold + \
768            'Warning: This combination of gcc and binutils have' + \
769            ' known incompatibilities.\n' + \
770            '         If you encounter build problems, please update ' + \
771            'binutils to 2.23.' + \
772            termcap.Normal
773
774    # Make sure we warn if the user has requested to compile with the
775    # Undefined Benahvior Sanitizer and this version of gcc does not
776    # support it.
777    if GetOption('with_ubsan') and \
778            compareVersions(gcc_version, '4.9') < 0:
779        print termcap.Yellow + termcap.Bold + \
780            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
781            termcap.Normal
782
783    disable_lto = GetOption('no_lto')
784    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
785            not GetOption('force_lto'):
786        print termcap.Yellow + termcap.Bold + \
787            'Warning: Your compiler doesn\'t support incremental linking' + \
788            ' and lto at the same time, so lto is being disabled. To force' + \
789            ' lto on anyway, use the --force-lto option. That will disable' + \
790            ' partial linking.' + \
791            termcap.Normal
792        disable_lto = True
793
794    # Add the appropriate Link-Time Optimization (LTO) flags
795    # unless LTO is explicitly turned off. Note that these flags
796    # are only used by the fast target.
797    if not disable_lto:
798        # Pass the LTO flag when compiling to produce GIMPLE
799        # output, we merely create the flags here and only append
800        # them later
801        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
802
803        # Use the same amount of jobs for LTO as we are running
804        # scons with
805        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
806
807    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
808                                  '-fno-builtin-realloc', '-fno-builtin-free'])
809
810    # add option to check for undeclared overrides
811    if compareVersions(gcc_version, "5.0") > 0:
812        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
813
814elif main['CLANG']:
815    # Check for a supported version of clang, >= 3.1 is needed to
816    # support similar features as gcc 4.8. See
817    # http://clang.llvm.org/cxx_status.html for details
818    clang_version_re = re.compile(".* version (\d+\.\d+)")
819    clang_version_match = clang_version_re.search(CXX_version)
820    if (clang_version_match):
821        clang_version = clang_version_match.groups()[0]
822        if compareVersions(clang_version, "3.1") < 0:
823            print 'Error: clang version 3.1 or newer required.'
824            print '       Installed version:', clang_version
825            Exit(1)
826    else:
827        print 'Error: Unable to determine clang version.'
828        Exit(1)
829
830    # clang has a few additional warnings that we disable, extraneous
831    # parantheses are allowed due to Ruby's printing of the AST,
832    # finally self assignments are allowed as the generated CPU code
833    # is relying on this
834    main.Append(CCFLAGS=['-Wno-parentheses',
835                         '-Wno-self-assign',
836                         # Some versions of libstdc++ (4.8?) seem to
837                         # use struct hash and class hash
838                         # interchangeably.
839                         '-Wno-mismatched-tags',
840                         ])
841
842    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
843
844    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
845    # opposed to libstdc++, as the later is dated.
846    if sys.platform == "darwin":
847        main.Append(CXXFLAGS=['-stdlib=libc++'])
848        main.Append(LIBS=['c++'])
849
850    # On FreeBSD we need libthr.
851    if sys.platform.startswith('freebsd'):
852        main.Append(LIBS=['thr'])
853
854else:
855    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
856    print "Don't know what compiler options to use for your compiler."
857    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
858    print termcap.Yellow + '       version:' + termcap.Normal,
859    if not CXX_version:
860        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
861               termcap.Normal
862    else:
863        print CXX_version.replace('\n', '<nl>')
864    print "       If you're trying to use a compiler other than GCC"
865    print "       or clang, there appears to be something wrong with your"
866    print "       environment."
867    print "       "
868    print "       If you are trying to use a compiler other than those listed"
869    print "       above you will need to ease fix SConstruct and "
870    print "       src/SConscript to support that compiler."
871    Exit(1)
872
873# Set up common yacc/bison flags (needed for Ruby)
874main['YACCFLAGS'] = '-d'
875main['YACCHXXFILESUFFIX'] = '.hh'
876
877# Do this after we save setting back, or else we'll tack on an
878# extra 'qdo' every time we run scons.
879if main['BATCH']:
880    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
881    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
882    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
883    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
884    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
885
886if sys.platform == 'cygwin':
887    # cygwin has some header file issues...
888    main.Append(CCFLAGS=["-Wno-uninitialized"])
889
890# Check for the protobuf compiler
891protoc_version = readCommand([main['PROTOC'], '--version'],
892                             exception='').split()
893
894# First two words should be "libprotoc x.y.z"
895if len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
896    print termcap.Yellow + termcap.Bold + \
897        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
898        '         Please install protobuf-compiler for tracing support.' + \
899        termcap.Normal
900    main['PROTOC'] = False
901else:
902    # Based on the availability of the compress stream wrappers,
903    # require 2.1.0
904    min_protoc_version = '2.1.0'
905    if compareVersions(protoc_version[1], min_protoc_version) < 0:
906        print termcap.Yellow + termcap.Bold + \
907            'Warning: protoc version', min_protoc_version, \
908            'or newer required.\n' + \
909            '         Installed version:', protoc_version[1], \
910            termcap.Normal
911        main['PROTOC'] = False
912    else:
913        # Attempt to determine the appropriate include path and
914        # library path using pkg-config, that means we also need to
915        # check for pkg-config. Note that it is possible to use
916        # protobuf without the involvement of pkg-config. Later on we
917        # check go a library config check and at that point the test
918        # will fail if libprotobuf cannot be found.
919        if readCommand(['pkg-config', '--version'], exception=''):
920            try:
921                # Attempt to establish what linking flags to add for protobuf
922                # using pkg-config
923                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
924            except:
925                print termcap.Yellow + termcap.Bold + \
926                    'Warning: pkg-config could not get protobuf flags.' + \
927                    termcap.Normal
928
929
930# Check for 'timeout' from GNU coreutils. If present, regressions will
931# be run with a time limit. We require version 8.13 since we rely on
932# support for the '--foreground' option.
933if sys.platform.startswith('freebsd'):
934    timeout_lines = readCommand(['gtimeout', '--version'],
935                                exception='').splitlines()
936else:
937    timeout_lines = readCommand(['timeout', '--version'],
938                                exception='').splitlines()
939# Get the first line and tokenize it
940timeout_version = timeout_lines[0].split() if timeout_lines else []
941main['TIMEOUT'] =  timeout_version and \
942    compareVersions(timeout_version[-1], '8.13') >= 0
943
944# Add a custom Check function to test for structure members.
945def CheckMember(context, include, decl, member, include_quotes="<>"):
946    context.Message("Checking for member %s in %s..." %
947                    (member, decl))
948    text = """
949#include %(header)s
950int main(){
951  %(decl)s test;
952  (void)test.%(member)s;
953  return 0;
954};
955""" % { "header" : include_quotes[0] + include + include_quotes[1],
956        "decl" : decl,
957        "member" : member,
958        }
959
960    ret = context.TryCompile(text, extension=".cc")
961    context.Result(ret)
962    return ret
963
964# Platform-specific configuration.  Note again that we assume that all
965# builds under a given build root run on the same host platform.
966conf = Configure(main,
967                 conf_dir = joinpath(build_root, '.scons_config'),
968                 log_file = joinpath(build_root, 'scons_config.log'),
969                 custom_tests = {
970        'CheckMember' : CheckMember,
971        })
972
973# Check if we should compile a 64 bit binary on Mac OS X/Darwin
974try:
975    import platform
976    uname = platform.uname()
977    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
978        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
979            main.Append(CCFLAGS=['-arch', 'x86_64'])
980            main.Append(CFLAGS=['-arch', 'x86_64'])
981            main.Append(LINKFLAGS=['-arch', 'x86_64'])
982            main.Append(ASFLAGS=['-arch', 'x86_64'])
983except:
984    pass
985
986# Recent versions of scons substitute a "Null" object for Configure()
987# when configuration isn't necessary, e.g., if the "--help" option is
988# present.  Unfortuantely this Null object always returns false,
989# breaking all our configuration checks.  We replace it with our own
990# more optimistic null object that returns True instead.
991if not conf:
992    def NullCheck(*args, **kwargs):
993        return True
994
995    class NullConf:
996        def __init__(self, env):
997            self.env = env
998        def Finish(self):
999            return self.env
1000        def __getattr__(self, mname):
1001            return NullCheck
1002
1003    conf = NullConf(main)
1004
1005# Cache build files in the supplied directory.
1006if main['M5_BUILD_CACHE']:
1007    print 'Using build cache located at', main['M5_BUILD_CACHE']
1008    CacheDir(main['M5_BUILD_CACHE'])
1009
1010main['USE_PYTHON'] = not GetOption('without_python')
1011if main['USE_PYTHON']:
1012    # Find Python include and library directories for embedding the
1013    # interpreter. We rely on python-config to resolve the appropriate
1014    # includes and linker flags. ParseConfig does not seem to understand
1015    # the more exotic linker flags such as -Xlinker and -export-dynamic so
1016    # we add them explicitly below. If you want to link in an alternate
1017    # version of python, see above for instructions on how to invoke
1018    # scons with the appropriate PATH set.
1019    #
1020    # First we check if python2-config exists, else we use python-config
1021    python_config = readCommand(['which', 'python2-config'],
1022                                exception='').strip()
1023    if not os.path.exists(python_config):
1024        python_config = readCommand(['which', 'python-config'],
1025                                    exception='').strip()
1026    py_includes = readCommand([python_config, '--includes'],
1027                              exception='').split()
1028    # Strip the -I from the include folders before adding them to the
1029    # CPPPATH
1030    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
1031
1032    # Read the linker flags and split them into libraries and other link
1033    # flags. The libraries are added later through the call the CheckLib.
1034    py_ld_flags = readCommand([python_config, '--ldflags'],
1035        exception='').split()
1036    py_libs = []
1037    for lib in py_ld_flags:
1038         if not lib.startswith('-l'):
1039             main.Append(LINKFLAGS=[lib])
1040         else:
1041             lib = lib[2:]
1042             if lib not in py_libs:
1043                 py_libs.append(lib)
1044
1045    # verify that this stuff works
1046    if not conf.CheckHeader('Python.h', '<>'):
1047        print "Error: can't find Python.h header in", py_includes
1048        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
1049        Exit(1)
1050
1051    for lib in py_libs:
1052        if not conf.CheckLib(lib):
1053            print "Error: can't find library %s required by python" % lib
1054            Exit(1)
1055
1056# On Solaris you need to use libsocket for socket ops
1057if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
1058   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
1059       print "Can't find library with socket calls (e.g. accept())"
1060       Exit(1)
1061
1062# Check for zlib.  If the check passes, libz will be automatically
1063# added to the LIBS environment variable.
1064if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
1065    print 'Error: did not find needed zlib compression library '\
1066          'and/or zlib.h header file.'
1067    print '       Please install zlib and try again.'
1068    Exit(1)
1069
1070# If we have the protobuf compiler, also make sure we have the
1071# development libraries. If the check passes, libprotobuf will be
1072# automatically added to the LIBS environment variable. After
1073# this, we can use the HAVE_PROTOBUF flag to determine if we have
1074# got both protoc and libprotobuf available.
1075main['HAVE_PROTOBUF'] = main['PROTOC'] and \
1076    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
1077                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
1078
1079# If we have the compiler but not the library, print another warning.
1080if main['PROTOC'] and not main['HAVE_PROTOBUF']:
1081    print termcap.Yellow + termcap.Bold + \
1082        'Warning: did not find protocol buffer library and/or headers.\n' + \
1083    '       Please install libprotobuf-dev for tracing support.' + \
1084    termcap.Normal
1085
1086# Check for librt.
1087have_posix_clock = \
1088    conf.CheckLibWithHeader(None, 'time.h', 'C',
1089                            'clock_nanosleep(0,0,NULL,NULL);') or \
1090    conf.CheckLibWithHeader('rt', 'time.h', 'C',
1091                            'clock_nanosleep(0,0,NULL,NULL);')
1092
1093have_posix_timers = \
1094    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
1095                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
1096
1097if not GetOption('without_tcmalloc'):
1098    if conf.CheckLib('tcmalloc'):
1099        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
1100    elif conf.CheckLib('tcmalloc_minimal'):
1101        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
1102    else:
1103        print termcap.Yellow + termcap.Bold + \
1104              "You can get a 12% performance improvement by "\
1105              "installing tcmalloc (libgoogle-perftools-dev package "\
1106              "on Ubuntu or RedHat)." + termcap.Normal
1107
1108
1109# Detect back trace implementations. The last implementation in the
1110# list will be used by default.
1111backtrace_impls = [ "none" ]
1112
1113if conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
1114                           'backtrace_symbols_fd((void*)0, 0, 0);'):
1115    backtrace_impls.append("glibc")
1116elif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
1117                           'backtrace_symbols_fd((void*)0, 0, 0);'):
1118    # NetBSD and FreeBSD need libexecinfo.
1119    backtrace_impls.append("glibc")
1120    main.Append(LIBS=['execinfo'])
1121
1122if backtrace_impls[-1] == "none":
1123    default_backtrace_impl = "none"
1124    print termcap.Yellow + termcap.Bold + \
1125        "No suitable back trace implementation found." + \
1126        termcap.Normal
1127
1128if not have_posix_clock:
1129    print "Can't find library for POSIX clocks."
1130
1131# Check for <fenv.h> (C99 FP environment control)
1132have_fenv = conf.CheckHeader('fenv.h', '<>')
1133if not have_fenv:
1134    print "Warning: Header file <fenv.h> not found."
1135    print "         This host has no IEEE FP rounding mode control."
1136
1137# Check for <png.h> (libpng library needed if wanting to dump
1138# frame buffer image in png format)
1139have_png = conf.CheckHeader('png.h', '<>')
1140if not have_png:
1141    print "Warning: Header file <png.h> not found."
1142    print "         This host has no libpng library."
1143    print "         Disabling support for PNG framebuffers."
1144
1145# Check if we should enable KVM-based hardware virtualization. The API
1146# we rely on exists since version 2.6.36 of the kernel, but somehow
1147# the KVM_API_VERSION does not reflect the change. We test for one of
1148# the types as a fall back.
1149have_kvm = conf.CheckHeader('linux/kvm.h', '<>')
1150if not have_kvm:
1151    print "Info: Compatible header file <linux/kvm.h> not found, " \
1152        "disabling KVM support."
1153
1154# Check if the TUN/TAP driver is available.
1155have_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
1156if not have_tuntap:
1157    print "Info: Compatible header file <linux/if_tun.h> not found."
1158
1159# x86 needs support for xsave. We test for the structure here since we
1160# won't be able to run new tests by the time we know which ISA we're
1161# targeting.
1162have_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
1163                                    '#include <linux/kvm.h>') != 0
1164
1165# Check if the requested target ISA is compatible with the host
1166def is_isa_kvm_compatible(isa):
1167    try:
1168        import platform
1169        host_isa = platform.machine()
1170    except:
1171        print "Warning: Failed to determine host ISA."
1172        return False
1173
1174    if not have_posix_timers:
1175        print "Warning: Can not enable KVM, host seems to lack support " \
1176            "for POSIX timers"
1177        return False
1178
1179    if isa == "arm":
1180        return host_isa in ( "armv7l", "aarch64" )
1181    elif isa == "x86":
1182        if host_isa != "x86_64":
1183            return False
1184
1185        if not have_kvm_xsave:
1186            print "KVM on x86 requires xsave support in kernel headers."
1187            return False
1188
1189        return True
1190    else:
1191        return False
1192
1193
1194# Check if the exclude_host attribute is available. We want this to
1195# get accurate instruction counts in KVM.
1196main['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
1197    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
1198
1199
1200######################################################################
1201#
1202# Finish the configuration
1203#
1204main = conf.Finish()
1205
1206######################################################################
1207#
1208# Collect all non-global variables
1209#
1210
1211# Define the universe of supported ISAs
1212all_isa_list = [ ]
1213all_gpu_isa_list = [ ]
1214Export('all_isa_list')
1215Export('all_gpu_isa_list')
1216
1217class CpuModel(object):
1218    '''The CpuModel class encapsulates everything the ISA parser needs to
1219    know about a particular CPU model.'''
1220
1221    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
1222    dict = {}
1223
1224    # Constructor.  Automatically adds models to CpuModel.dict.
1225    def __init__(self, name, default=False):
1226        self.name = name           # name of model
1227
1228        # This cpu is enabled by default
1229        self.default = default
1230
1231        # Add self to dict
1232        if name in CpuModel.dict:
1233            raise AttributeError, "CpuModel '%s' already registered" % name
1234        CpuModel.dict[name] = self
1235
1236Export('CpuModel')
1237
1238# Sticky variables get saved in the variables file so they persist from
1239# one invocation to the next (unless overridden, in which case the new
1240# value becomes sticky).
1241sticky_vars = Variables(args=ARGUMENTS)
1242Export('sticky_vars')
1243
1244# Sticky variables that should be exported
1245export_vars = []
1246Export('export_vars')
1247
1248# For Ruby
1249all_protocols = []
1250Export('all_protocols')
1251protocol_dirs = []
1252Export('protocol_dirs')
1253slicc_includes = []
1254Export('slicc_includes')
1255
1256# Walk the tree and execute all SConsopts scripts that wil add to the
1257# above variables
1258if GetOption('verbose'):
1259    print "Reading SConsopts"
1260for bdir in [ base_dir ] + extras_dir_list:
1261    if not isdir(bdir):
1262        print "Error: directory '%s' does not exist" % bdir
1263        Exit(1)
1264    for root, dirs, files in os.walk(bdir):
1265        if 'SConsopts' in files:
1266            if GetOption('verbose'):
1267                print "Reading", joinpath(root, 'SConsopts')
1268            SConscript(joinpath(root, 'SConsopts'))
1269
1270all_isa_list.sort()
1271all_gpu_isa_list.sort()
1272
1273sticky_vars.AddVariables(
1274    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
1275    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
1276    ListVariable('CPU_MODELS', 'CPU models',
1277                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
1278                 sorted(CpuModel.dict.keys())),
1279    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
1280                 False),
1281    BoolVariable('SS_COMPATIBLE_FP',
1282                 'Make floating-point results compatible with SimpleScalar',
1283                 False),
1284    BoolVariable('USE_SSE2',
1285                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
1286                 False),
1287    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
1288    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
1289    BoolVariable('USE_PNG',  'Enable support for PNG images', have_png),
1290    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability',
1291                 False),
1292    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models',
1293                 have_kvm),
1294    BoolVariable('USE_TUNTAP',
1295                 'Enable using a tap device to bridge to the host network',
1296                 have_tuntap),
1297    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
1298    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1299                  all_protocols),
1300    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
1301                 backtrace_impls[-1], backtrace_impls)
1302    )
1303
1304# These variables get exported to #defines in config/*.hh (see src/SConscript).
1305export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
1306                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
1307                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST',
1308                'USE_PNG']
1309
1310###################################################
1311#
1312# Define a SCons builder for configuration flag headers.
1313#
1314###################################################
1315
1316# This function generates a config header file that #defines the
1317# variable symbol to the current variable setting (0 or 1).  The source
1318# operands are the name of the variable and a Value node containing the
1319# value of the variable.
1320def build_config_file(target, source, env):
1321    (variable, value) = [s.get_contents() for s in source]
1322    f = file(str(target[0]), 'w')
1323    print >> f, '#define', variable, value
1324    f.close()
1325    return None
1326
1327# Combine the two functions into a scons Action object.
1328config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1329
1330# The emitter munges the source & target node lists to reflect what
1331# we're really doing.
1332def config_emitter(target, source, env):
1333    # extract variable name from Builder arg
1334    variable = str(target[0])
1335    # True target is config header file
1336    target = joinpath('config', variable.lower() + '.hh')
1337    val = env[variable]
1338    if isinstance(val, bool):
1339        # Force value to 0/1
1340        val = int(val)
1341    elif isinstance(val, str):
1342        val = '"' + val + '"'
1343
1344    # Sources are variable name & value (packaged in SCons Value nodes)
1345    return ([target], [Value(variable), Value(val)])
1346
1347config_builder = Builder(emitter = config_emitter, action = config_action)
1348
1349main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1350
1351###################################################
1352#
1353# Builders for static and shared partially linked object files.
1354#
1355###################################################
1356
1357partial_static_builder = Builder(action=SCons.Defaults.LinkAction,
1358                                 src_suffix='$OBJSUFFIX',
1359                                 src_builder=['StaticObject', 'Object'],
1360                                 LINKFLAGS='$PLINKFLAGS',
1361                                 LIBS='')
1362
1363def partial_shared_emitter(target, source, env):
1364    for tgt in target:
1365        tgt.attributes.shared = 1
1366    return (target, source)
1367partial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
1368                                 emitter=partial_shared_emitter,
1369                                 src_suffix='$SHOBJSUFFIX',
1370                                 src_builder='SharedObject',
1371                                 SHLINKFLAGS='$PSHLINKFLAGS',
1372                                 LIBS='')
1373
1374main.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
1375                         'PartialStatic' : partial_static_builder })
1376
1377# builds in ext are shared across all configs in the build root.
1378ext_dir = abspath(joinpath(str(main.root), 'ext'))
1379ext_build_dirs = []
1380for root, dirs, files in os.walk(ext_dir):
1381    if 'SConscript' in files:
1382        build_dir = os.path.relpath(root, ext_dir)
1383        ext_build_dirs.append(build_dir)
1384        main.SConscript(joinpath(root, 'SConscript'),
1385                        variant_dir=joinpath(build_root, build_dir))
1386
1387main.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
1388
1389###################################################
1390#
1391# This builder and wrapper method are used to set up a directory with
1392# switching headers. Those are headers which are in a generic location and
1393# that include more specific headers from a directory chosen at build time
1394# based on the current build settings.
1395#
1396###################################################
1397
1398def build_switching_header(target, source, env):
1399    path = str(target[0])
1400    subdir = str(source[0])
1401    dp, fp = os.path.split(path)
1402    dp = os.path.relpath(os.path.realpath(dp),
1403                         os.path.realpath(env['BUILDDIR']))
1404    with open(path, 'w') as hdr:
1405        print >>hdr, '#include "%s/%s/%s"' % (dp, subdir, fp)
1406
1407switching_header_action = MakeAction(build_switching_header,
1408                                     Transform('GENERATE'))
1409
1410switching_header_builder = Builder(action=switching_header_action,
1411                                   source_factory=Value,
1412                                   single_source=True)
1413
1414main.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
1415
1416def switching_headers(self, headers, source):
1417    for header in headers:
1418        self.SwitchingHeader(header, source)
1419
1420main.AddMethod(switching_headers, 'SwitchingHeaders')
1421
1422###################################################
1423#
1424# Define build environments for selected configurations.
1425#
1426###################################################
1427
1428for variant_path in variant_paths:
1429    if not GetOption('silent'):
1430        print "Building in", variant_path
1431
1432    # Make a copy of the build-root environment to use for this config.
1433    env = main.Clone()
1434    env['BUILDDIR'] = variant_path
1435
1436    # variant_dir is the tail component of build path, and is used to
1437    # determine the build parameters (e.g., 'ALPHA_SE')
1438    (build_root, variant_dir) = splitpath(variant_path)
1439
1440    # Set env variables according to the build directory config.
1441    sticky_vars.files = []
1442    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1443    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1444    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1445    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1446    if isfile(current_vars_file):
1447        sticky_vars.files.append(current_vars_file)
1448        if not GetOption('silent'):
1449            print "Using saved variables file %s" % current_vars_file
1450    elif variant_dir in ext_build_dirs:
1451        # Things in ext are built without a variant directory.
1452        continue
1453    else:
1454        # Build dir-specific variables file doesn't exist.
1455
1456        # Make sure the directory is there so we can create it later
1457        opt_dir = dirname(current_vars_file)
1458        if not isdir(opt_dir):
1459            mkdir(opt_dir)
1460
1461        # Get default build variables from source tree.  Variables are
1462        # normally determined by name of $VARIANT_DIR, but can be
1463        # overridden by '--default=' arg on command line.
1464        default = GetOption('default')
1465        opts_dir = joinpath(main.root.abspath, 'build_opts')
1466        if default:
1467            default_vars_files = [joinpath(build_root, 'variables', default),
1468                                  joinpath(opts_dir, default)]
1469        else:
1470            default_vars_files = [joinpath(opts_dir, variant_dir)]
1471        existing_files = filter(isfile, default_vars_files)
1472        if existing_files:
1473            default_vars_file = existing_files[0]
1474            sticky_vars.files.append(default_vars_file)
1475            print "Variables file %s not found,\n  using defaults in %s" \
1476                  % (current_vars_file, default_vars_file)
1477        else:
1478            print "Error: cannot find variables file %s or " \
1479                  "default file(s) %s" \
1480                  % (current_vars_file, ' or '.join(default_vars_files))
1481            Exit(1)
1482
1483    # Apply current variable settings to env
1484    sticky_vars.Update(env)
1485
1486    help_texts["local_vars"] += \
1487        "Build variables for %s:\n" % variant_dir \
1488                 + sticky_vars.GenerateHelpText(env)
1489
1490    # Process variable settings.
1491
1492    if not have_fenv and env['USE_FENV']:
1493        print "Warning: <fenv.h> not available; " \
1494              "forcing USE_FENV to False in", variant_dir + "."
1495        env['USE_FENV'] = False
1496
1497    if not env['USE_FENV']:
1498        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1499        print "         FP results may deviate slightly from other platforms."
1500
1501    if not have_png and env['USE_PNG']:
1502        print "Warning: <png.h> not available; " \
1503              "forcing USE_PNG to False in", variant_dir + "."
1504        env['USE_PNG'] = False
1505
1506    if env['USE_PNG']:
1507        env.Append(LIBS=['png'])
1508
1509    if env['EFENCE']:
1510        env.Append(LIBS=['efence'])
1511
1512    if env['USE_KVM']:
1513        if not have_kvm:
1514            print "Warning: Can not enable KVM, host seems to lack KVM support"
1515            env['USE_KVM'] = False
1516        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1517            print "Info: KVM support disabled due to unsupported host and " \
1518                "target ISA combination"
1519            env['USE_KVM'] = False
1520
1521    if env['USE_TUNTAP']:
1522        if not have_tuntap:
1523            print "Warning: Can't connect EtherTap with a tap device."
1524            env['USE_TUNTAP'] = False
1525
1526    if env['BUILD_GPU']:
1527        env.Append(CPPDEFINES=['BUILD_GPU'])
1528
1529    # Warn about missing optional functionality
1530    if env['USE_KVM']:
1531        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1532            print "Warning: perf_event headers lack support for the " \
1533                "exclude_host attribute. KVM instruction counts will " \
1534                "be inaccurate."
1535
1536    # Save sticky variable settings back to current variables file
1537    sticky_vars.Save(current_vars_file, env)
1538
1539    if env['USE_SSE2']:
1540        env.Append(CCFLAGS=['-msse2'])
1541
1542    # The src/SConscript file sets up the build rules in 'env' according
1543    # to the configured variables.  It returns a list of environments,
1544    # one for each variant build (debug, opt, etc.)
1545    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1546
1547# base help text
1548Help('''
1549Usage: scons [scons options] [build variables] [target(s)]
1550
1551Extra scons options:
1552%(options)s
1553
1554Global build variables:
1555%(global_vars)s
1556
1557%(local_vars)s
1558''' % help_texts)
1559