SConstruct revision 12061:0225580779db
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2013, 2015, 2016 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
683918Ssaidi@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
694202Sbinkertn@umich.edu#   scons to chdir to the specified directory to find this SConstruct
704678Snate@binkert.org#   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)
894781Snate@binkert.orgexcept 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# We ensure the python version early because because python-config
971533SN/A# requires python 2.5
983716Sstever@eecs.umich.edutry:
991533SN/A    EnsurePythonVersion(2, 5)
1004678Snate@binkert.orgexcept SystemExit, e:
1014678Snate@binkert.org    print """
1024678Snate@binkert.orgYou can use a non-default installation of the Python interpreter by
1034678Snate@binkert.orgrearranging your PATH so that scons finds the non-default 'python' and
1044678Snate@binkert.org'python-config' first.
1054678Snate@binkert.org
1064678Snate@binkert.orgFor more details, see:
1074678Snate@binkert.org    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1084678Snate@binkert.org"""
1094678Snate@binkert.org    raise
1104678Snate@binkert.org
1114678Snate@binkert.org# Global Python includes
1124678Snate@binkert.orgimport itertools
1134678Snate@binkert.orgimport os
1144678Snate@binkert.orgimport re
1154678Snate@binkert.orgimport shutil
1164678Snate@binkert.orgimport subprocess
1174678Snate@binkert.orgimport sys
1184678Snate@binkert.org
1194678Snate@binkert.orgfrom os import mkdir, environ
1204678Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1214678Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1224678Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1234678Snate@binkert.org
1244678Snate@binkert.org# SCons includes
1254678Snate@binkert.orgimport SCons
1264678Snate@binkert.orgimport SCons.Node
1274678Snate@binkert.org
128955SN/Aextra_python_paths = [
129955SN/A    Dir('src/python').srcnode().abspath, # gem5 includes
1302632Sstever@eecs.umich.edu    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1312632Sstever@eecs.umich.edu    ]
132955SN/A
133955SN/Asys.path[1:1] = extra_python_paths
134955SN/A
135955SN/Afrom m5.util import compareVersions, readCommand
1362632Sstever@eecs.umich.edufrom m5.util.terminal import get_termcap
137955SN/A
1382632Sstever@eecs.umich.eduhelp_texts = {
1392632Sstever@eecs.umich.edu    "options" : "",
1402632Sstever@eecs.umich.edu    "global_vars" : "",
1412632Sstever@eecs.umich.edu    "local_vars" : ""
1422632Sstever@eecs.umich.edu}
1432632Sstever@eecs.umich.edu
1442632Sstever@eecs.umich.eduExport("help_texts")
1453053Sstever@eecs.umich.edu
1463053Sstever@eecs.umich.edu
1473053Sstever@eecs.umich.edu# There's a bug in scons in that (1) by default, the help texts from
1483053Sstever@eecs.umich.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1493053Sstever@eecs.umich.edu# and (2) you can override the help displayed by 'scons -h' using the
1503053Sstever@eecs.umich.edu# Help() function, but these two features are incompatible: once
1513053Sstever@eecs.umich.edu# you've overridden the help text using Help(), there's no way to get
1523053Sstever@eecs.umich.edu# at the help texts from AddOptions.  See:
1533053Sstever@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1543053Sstever@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1553053Sstever@eecs.umich.edu# This hack lets us extract the help text from AddOptions and
1563053Sstever@eecs.umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1573053Sstever@eecs.umich.edu# we can just use AddOption directly.
1583053Sstever@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1593053Sstever@eecs.umich.edu    col_width = 30
1603053Sstever@eecs.umich.edu
1612632Sstever@eecs.umich.edu    help = "  " + ", ".join(args)
1622632Sstever@eecs.umich.edu    if "help" in kwargs:
1632632Sstever@eecs.umich.edu        length = len(help)
1642632Sstever@eecs.umich.edu        if length >= col_width:
1652632Sstever@eecs.umich.edu            help += "\n" + " " * col_width
1662632Sstever@eecs.umich.edu        else:
1673718Sstever@eecs.umich.edu            help += " " * (col_width - length)
1683718Sstever@eecs.umich.edu        help += kwargs["help"]
1693718Sstever@eecs.umich.edu    help_texts["options"] += help + "\n"
1703718Sstever@eecs.umich.edu
1713718Sstever@eecs.umich.edu    AddOption(*args, **kwargs)
1723718Sstever@eecs.umich.edu
1733718Sstever@eecs.umich.eduAddLocalOption('--colors', dest='use_colors', action='store_true',
1743718Sstever@eecs.umich.edu               help="Add color to abbreviated scons output")
1753718Sstever@eecs.umich.eduAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1763718Sstever@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1773718Sstever@eecs.umich.eduAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1783718Sstever@eecs.umich.edu               action='store_true',
1793718Sstever@eecs.umich.edu               help="Build with support for C++-based configuration")
1802634Sstever@eecs.umich.eduAddLocalOption('--default', dest='default', type='string', action='store',
1812634Sstever@eecs.umich.edu               help='Override which build_opts file to use for defaults')
1822632Sstever@eecs.umich.eduAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1832638Sstever@eecs.umich.edu               help='Disable style checking hooks')
1842632Sstever@eecs.umich.eduAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1852632Sstever@eecs.umich.edu               help='Disable Link-Time Optimization for fast')
1862632Sstever@eecs.umich.eduAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1872632Sstever@eecs.umich.edu               help='Update test reference outputs')
1882632Sstever@eecs.umich.eduAddLocalOption('--verbose', dest='verbose', action='store_true',
1892632Sstever@eecs.umich.edu               help='Print full tool command lines')
1901858SN/AAddLocalOption('--without-python', dest='without_python',
1913716Sstever@eecs.umich.edu               action='store_true',
1922638Sstever@eecs.umich.edu               help='Build without Python configuration support')
1932638Sstever@eecs.umich.eduAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1942638Sstever@eecs.umich.edu               action='store_true',
1952638Sstever@eecs.umich.edu               help='Disable linking against tcmalloc')
1962638Sstever@eecs.umich.eduAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1972638Sstever@eecs.umich.edu               help='Build with Undefined Behavior Sanitizer if available')
1982638Sstever@eecs.umich.eduAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1993716Sstever@eecs.umich.edu               help='Build with Address Sanitizer if available')
2002634Sstever@eecs.umich.edu
2012634Sstever@eecs.umich.edutermcap = get_termcap(GetOption('use_colors'))
202955SN/A
203955SN/A########################################################################
204955SN/A#
205955SN/A# Set up the main build environment.
206955SN/A#
207955SN/A########################################################################
208955SN/A
209955SN/A# export TERM so that clang reports errors in color
2101858SN/Ause_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
2111858SN/A                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
2122632Sstever@eecs.umich.edu                 'PYTHONPATH', 'RANLIB', 'TERM' ])
213955SN/A
2144781Snate@binkert.orguse_prefixes = [
2153643Ssaidi@eecs.umich.edu    "ASAN_",           # address sanitizer symbolizer path and settings
2163643Ssaidi@eecs.umich.edu    "CCACHE_",         # ccache (caching compiler wrapper) configuration
2173643Ssaidi@eecs.umich.edu    "CCC_",            # clang static analyzer configuration
2183643Ssaidi@eecs.umich.edu    "DISTCC_",         # distcc (distributed compiler wrapper) configuration
2193643Ssaidi@eecs.umich.edu    "INCLUDE_SERVER_", # distcc pump server settings
2203643Ssaidi@eecs.umich.edu    "M5",              # M5 configuration (e.g., path to kernels)
2213643Ssaidi@eecs.umich.edu    ]
2224494Ssaidi@eecs.umich.edu
2234494Ssaidi@eecs.umich.eduuse_env = {}
2243716Sstever@eecs.umich.edufor key,val in sorted(os.environ.iteritems()):
2251105SN/A    if key in use_vars or \
2262667Sstever@eecs.umich.edu            any([key.startswith(prefix) for prefix in use_prefixes]):
2272667Sstever@eecs.umich.edu        use_env[key] = val
2282667Sstever@eecs.umich.edu
2292667Sstever@eecs.umich.edu# Tell scons to avoid implicit command dependencies to avoid issues
2302667Sstever@eecs.umich.edu# with the param wrappes being compiled twice (see
2312667Sstever@eecs.umich.edu# http://scons.tigris.org/issues/show_bug.cgi?id=2811)
2321869SN/Amain = Environment(ENV=use_env, IMPLICIT_COMMAND_DEPENDENCIES=0)
2331869SN/Amain.Decider('MD5-timestamp')
2341869SN/Amain.root = Dir(".")         # The current directory (where this file lives).
2351869SN/Amain.srcdir = Dir("src")     # The source directory
2361869SN/A
2371065SN/Amain_dict_keys = main.Dictionary().keys()
2382632Sstever@eecs.umich.edu
2392632Sstever@eecs.umich.edu# Check that we have a C/C++ compiler
2403918Ssaidi@eecs.umich.eduif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2413918Ssaidi@eecs.umich.edu    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2423940Ssaidi@eecs.umich.edu    Exit(1)
2434781Snate@binkert.org
2444781Snate@binkert.org# add useful python code PYTHONPATH so it can be used by subprocesses
2453918Ssaidi@eecs.umich.edu# as well
2464781Snate@binkert.orgmain.AppendENVPath('PYTHONPATH', extra_python_paths)
2474781Snate@binkert.org
2483918Ssaidi@eecs.umich.edu########################################################################
2494781Snate@binkert.org#
2504781Snate@binkert.org# Mercurial Stuff.
2513940Ssaidi@eecs.umich.edu#
2523942Ssaidi@eecs.umich.edu# If the gem5 directory is a mercurial repository, we should do some
2533940Ssaidi@eecs.umich.edu# extra things.
2543918Ssaidi@eecs.umich.edu#
2553918Ssaidi@eecs.umich.edu########################################################################
256955SN/A
2571858SN/Ahgdir = main.root.Dir(".hg")
2583918Ssaidi@eecs.umich.edu
2593918Ssaidi@eecs.umich.edu
2603918Ssaidi@eecs.umich.edustyle_message = """
2613918Ssaidi@eecs.umich.eduYou're missing the gem5 style hook, which automatically checks your code
2623940Ssaidi@eecs.umich.eduagainst the gem5 style rules on %s.
2633940Ssaidi@eecs.umich.eduThis script will now install the hook in your %s.
2643918Ssaidi@eecs.umich.eduPress enter to continue, or ctrl-c to abort: """
2653918Ssaidi@eecs.umich.edu
2663918Ssaidi@eecs.umich.edumercurial_style_message = """
2673918Ssaidi@eecs.umich.eduYou're missing the gem5 style hook, which automatically checks your code
2683918Ssaidi@eecs.umich.eduagainst the gem5 style rules on hg commit and qrefresh commands.
2693918Ssaidi@eecs.umich.eduThis script will now install the hook in your .hg/hgrc file.
2703918Ssaidi@eecs.umich.eduPress enter to continue, or ctrl-c to abort: """
2713918Ssaidi@eecs.umich.edu
2723918Ssaidi@eecs.umich.edugit_style_message = """
2733940Ssaidi@eecs.umich.eduYou're missing the gem5 style or commit message hook. These hooks help
2743918Ssaidi@eecs.umich.eduto ensure that your code follows gem5's style rules on git commit.
2753918Ssaidi@eecs.umich.eduThis script will now install the hook in your .git/hooks/ directory.
2761851SN/APress enter to continue, or ctrl-c to abort: """
2771851SN/A
2781858SN/Amercurial_style_upgrade_message = """
2792632Sstever@eecs.umich.eduYour Mercurial style hooks are not up-to-date. This script will now
280955SN/Atry to automatically update them. A backup of your hgrc will be saved
2813053Sstever@eecs.umich.eduin .hg/hgrc.old.
2823053Sstever@eecs.umich.eduPress enter to continue, or ctrl-c to abort: """
2833053Sstever@eecs.umich.edu
2843053Sstever@eecs.umich.edumercurial_style_hook = """
2853053Sstever@eecs.umich.edu# The following lines were automatically added by gem5/SConstruct
2863053Sstever@eecs.umich.edu# to provide the gem5 style-checking hooks
2873053Sstever@eecs.umich.edu[extensions]
2883053Sstever@eecs.umich.eduhgstyle = %s/util/hgstyle.py
2893053Sstever@eecs.umich.edu
2904742Sstever@eecs.umich.edu[hooks]
2914742Sstever@eecs.umich.edupretxncommit.style = python:hgstyle.check_style
2923053Sstever@eecs.umich.edupre-qrefresh.style = python:hgstyle.check_style
2933053Sstever@eecs.umich.edu# End of SConstruct additions
2943053Sstever@eecs.umich.edu
2953053Sstever@eecs.umich.edu""" % (main.root.abspath)
2963053Sstever@eecs.umich.edu
2973053Sstever@eecs.umich.edumercurial_lib_not_found = """
2983053Sstever@eecs.umich.eduMercurial libraries cannot be found, ignoring style hook.  If
2993053Sstever@eecs.umich.eduyou are a gem5 developer, please fix this and run the style
3003053Sstever@eecs.umich.eduhook. It is important.
3012667Sstever@eecs.umich.edu"""
3024554Sbinkertn@umich.edu
3034554Sbinkertn@umich.edu# Check for style hook and prompt for installation if it's not there.
3042667Sstever@eecs.umich.edu# Skip this if --ignore-style was specified, there's no interactive
3054554Sbinkertn@umich.edu# terminal to prompt, or no recognized revision control system can be
3064554Sbinkertn@umich.edu# found.
3074554Sbinkertn@umich.eduignore_style = GetOption('ignore_style') or not sys.stdin.isatty()
3084554Sbinkertn@umich.edu
3094554Sbinkertn@umich.edu# Try wire up Mercurial to the style hooks
3104554Sbinkertn@umich.eduif not ignore_style and hgdir.exists():
3114554Sbinkertn@umich.edu    style_hook = True
3124781Snate@binkert.org    style_hooks = tuple()
3134554Sbinkertn@umich.edu    hgrc = hgdir.File('hgrc')
3144554Sbinkertn@umich.edu    hgrc_old = hgdir.File('hgrc.old')
3152667Sstever@eecs.umich.edu    try:
3164554Sbinkertn@umich.edu        from mercurial import ui
3174554Sbinkertn@umich.edu        ui = ui.ui()
3184554Sbinkertn@umich.edu        ui.readconfig(hgrc.abspath)
3194554Sbinkertn@umich.edu        style_hooks = (ui.config('hooks', 'pretxncommit.style', None),
3202667Sstever@eecs.umich.edu                       ui.config('hooks', 'pre-qrefresh.style', None))
3214554Sbinkertn@umich.edu        style_hook = all(style_hooks)
3222667Sstever@eecs.umich.edu        style_extension = ui.config('extensions', 'style', None)
3234554Sbinkertn@umich.edu    except ImportError:
3244554Sbinkertn@umich.edu        print mercurial_lib_not_found
3252667Sstever@eecs.umich.edu
3262638Sstever@eecs.umich.edu    if "python:style.check_style" in style_hooks:
3272638Sstever@eecs.umich.edu        # Try to upgrade the style hooks
3282638Sstever@eecs.umich.edu        print mercurial_style_upgrade_message
3293716Sstever@eecs.umich.edu        # continue unless user does ctrl-c/ctrl-d etc.
3303716Sstever@eecs.umich.edu        try:
3311858SN/A            raw_input()
3323118Sstever@eecs.umich.edu        except:
3333118Sstever@eecs.umich.edu            print "Input exception, exiting scons.\n"
3343118Sstever@eecs.umich.edu            sys.exit(1)
3353118Sstever@eecs.umich.edu        shutil.copyfile(hgrc.abspath, hgrc_old.abspath)
3363118Sstever@eecs.umich.edu        re_style_hook = re.compile(r"^([^=#]+)\.style\s*=\s*([^#\s]+).*")
3373118Sstever@eecs.umich.edu        re_style_extension = re.compile("style\s*=\s*([^#\s]+).*")
3383118Sstever@eecs.umich.edu        old, new = open(hgrc_old.abspath, 'r'), open(hgrc.abspath, 'w')
3393118Sstever@eecs.umich.edu        for l in old:
3403118Sstever@eecs.umich.edu            m_hook = re_style_hook.match(l)
3413118Sstever@eecs.umich.edu            m_ext = re_style_extension.match(l)
3423118Sstever@eecs.umich.edu            if m_hook:
3433716Sstever@eecs.umich.edu                hook, check = m_hook.groups()
3443118Sstever@eecs.umich.edu                if check != "python:style.check_style":
3453118Sstever@eecs.umich.edu                    print "Warning: %s.style is using a non-default " \
3463118Sstever@eecs.umich.edu                        "checker: %s" % (hook, check)
3473118Sstever@eecs.umich.edu                if hook not in ("pretxncommit", "pre-qrefresh"):
3483118Sstever@eecs.umich.edu                    print "Warning: Updating unknown style hook: %s" % hook
3493118Sstever@eecs.umich.edu
3503118Sstever@eecs.umich.edu                l = "%s.style = python:hgstyle.check_style\n" % hook
3513118Sstever@eecs.umich.edu            elif m_ext and m_ext.group(1) == style_extension:
3523118Sstever@eecs.umich.edu                l = "hgstyle = %s/util/hgstyle.py\n" % main.root.abspath
3533716Sstever@eecs.umich.edu
3543118Sstever@eecs.umich.edu            new.write(l)
3553118Sstever@eecs.umich.edu    elif not style_hook:
3563118Sstever@eecs.umich.edu        print mercurial_style_message,
3573118Sstever@eecs.umich.edu        # continue unless user does ctrl-c/ctrl-d etc.
3583118Sstever@eecs.umich.edu        try:
3593118Sstever@eecs.umich.edu            raw_input()
3603118Sstever@eecs.umich.edu        except:
3613118Sstever@eecs.umich.edu            print "Input exception, exiting scons.\n"
3623118Sstever@eecs.umich.edu            sys.exit(1)
3633118Sstever@eecs.umich.edu        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
3643483Ssaidi@eecs.umich.edu        print "Adding style hook to", hgrc_path, "\n"
3653494Ssaidi@eecs.umich.edu        try:
3663494Ssaidi@eecs.umich.edu            with open(hgrc_path, 'a') as f:
3673483Ssaidi@eecs.umich.edu                f.write(mercurial_style_hook)
3683483Ssaidi@eecs.umich.edu        except:
3693483Ssaidi@eecs.umich.edu            print "Error updating", hgrc_path
3703053Sstever@eecs.umich.edu            sys.exit(1)
3713053Sstever@eecs.umich.edu
3723918Ssaidi@eecs.umich.edudef install_git_style_hooks():
3733053Sstever@eecs.umich.edu    try:
3743053Sstever@eecs.umich.edu        gitdir = Dir(readCommand(
3753053Sstever@eecs.umich.edu            ["git", "rev-parse", "--git-dir"]).strip("\n"))
3763053Sstever@eecs.umich.edu    except Exception, e:
3773053Sstever@eecs.umich.edu        print "Warning: Failed to find git repo directory: %s" % e
3781858SN/A        return
3791858SN/A
3801858SN/A    git_hooks = gitdir.Dir("hooks")
3811858SN/A    def hook_exists(hook_name):
3821858SN/A        hook = git_hooks.File(hook_name)
3831858SN/A        return hook.exists()
3841859SN/A
3851858SN/A    def hook_install(hook_name, script):
3861858SN/A        hook = git_hooks.File(hook_name)
3871858SN/A        if hook.exists():
3881859SN/A            print "Warning: Can't install %s, hook already exists." % hook_name
3891859SN/A            return
3901862SN/A
3913053Sstever@eecs.umich.edu        if hook.islink():
3923053Sstever@eecs.umich.edu            print "Warning: Removing broken symlink for hook %s." % hook_name
3933053Sstever@eecs.umich.edu            os.unlink(hook.get_abspath())
3943053Sstever@eecs.umich.edu
3951859SN/A        if not git_hooks.exists():
3961859SN/A            mkdir(git_hooks.get_abspath())
3971859SN/A            git_hooks.clear()
3981859SN/A
3991859SN/A        abs_symlink_hooks = git_hooks.islink() and \
4001859SN/A            os.path.isabs(os.readlink(git_hooks.get_abspath()))
4011859SN/A
4021859SN/A        # Use a relative symlink if the hooks live in the source directory,
4031862SN/A        # and the hooks directory is not a symlink to an absolute path.
4041859SN/A        if hook.is_under(main.root) and not abs_symlink_hooks:
4051859SN/A            script_path = os.path.relpath(
4061859SN/A                os.path.realpath(script.get_abspath()),
4071858SN/A                os.path.realpath(hook.Dir(".").get_abspath()))
4081858SN/A        else:
4092139SN/A            script_path = script.get_abspath()
4104202Sbinkertn@umich.edu
4114202Sbinkertn@umich.edu        try:
4122139SN/A            os.symlink(script_path, hook.get_abspath())
4132155SN/A        except:
4144202Sbinkertn@umich.edu            print "Error updating git %s hook" % hook_name
4154202Sbinkertn@umich.edu            raise
4164202Sbinkertn@umich.edu
4172155SN/A    if hook_exists("pre-commit") and hook_exists("commit-msg"):
4181869SN/A        return
4191869SN/A
4201869SN/A    print git_style_message,
4211869SN/A    try:
4224202Sbinkertn@umich.edu        raw_input()
4234202Sbinkertn@umich.edu    except:
4244202Sbinkertn@umich.edu        print "Input exception, exiting scons.\n"
4254202Sbinkertn@umich.edu        sys.exit(1)
4264202Sbinkertn@umich.edu
4274202Sbinkertn@umich.edu    git_style_script = File("util/git-pre-commit.py")
4284202Sbinkertn@umich.edu    git_msg_script = File("ext/git-commit-msg")
4294202Sbinkertn@umich.edu
4304202Sbinkertn@umich.edu    hook_install("pre-commit", git_style_script)
4314202Sbinkertn@umich.edu    hook_install("commit-msg", git_msg_script)
4324202Sbinkertn@umich.edu
4334202Sbinkertn@umich.edu# Try to wire up git to the style hooks
4344202Sbinkertn@umich.eduif not ignore_style and main.root.Entry(".git").exists():
4354202Sbinkertn@umich.edu    install_git_style_hooks()
4364202Sbinkertn@umich.edu
4374202Sbinkertn@umich.edu###################################################
4384773Snate@binkert.org#
4394775Snate@binkert.org# Figure out which configurations to set up based on the path(s) of
4404775Snate@binkert.org# the target(s).
4414773Snate@binkert.org#
4424773Snate@binkert.org###################################################
4434773Snate@binkert.org
4444773Snate@binkert.org# Find default configuration & binary.
4454773Snate@binkert.orgDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
4464773Snate@binkert.org
4471869SN/A# helper function: find last occurrence of element in list
4484202Sbinkertn@umich.edudef rfind(l, elt, offs = -1):
4491869SN/A    for i in range(len(l)+offs, 0, -1):
4502508SN/A        if l[i] == elt:
4512508SN/A            return i
4522508SN/A    raise ValueError, "element not found"
4532508SN/A
4544202Sbinkertn@umich.edu# Take a list of paths (or SCons Nodes) and return a list with all
4551869SN/A# paths made absolute and ~-expanded.  Paths will be interpreted
4561869SN/A# relative to the launch directory unless a different root is provided
4571869SN/Adef makePathListAbsolute(path_list, root=GetLaunchDir()):
4581869SN/A    return [abspath(joinpath(root, expanduser(str(p))))
4591869SN/A            for p in path_list]
4601869SN/A
4611965SN/A# Each target must have 'build' in the interior of the path; the
4621965SN/A# directory below this will determine the build parameters.  For
4631965SN/A# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
4641869SN/A# recognize that ALPHA_SE specifies the configuration because it
4651869SN/A# follow 'build' in the build path.
4662733Sktlim@umich.edu
4671869SN/A# The funky assignment to "[:]" is needed to replace the list contents
4681884SN/A# in place rather than reassign the symbol to a new list, which
4691884SN/A# doesn't work (obviously!).
4703356Sbinkertn@umich.eduBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
4713356Sbinkertn@umich.edu
4723356Sbinkertn@umich.edu# Generate a list of the unique build roots and configs that the
4734773Snate@binkert.org# collected targets reference.
4744773Snate@binkert.orgvariant_paths = []
4754773Snate@binkert.orgbuild_root = None
4761869SN/Afor t in BUILD_TARGETS:
4771858SN/A    path_dirs = t.split('/')
4781869SN/A    try:
4791869SN/A        build_top = rfind(path_dirs, 'build', -2)
4801869SN/A    except:
4811858SN/A        print "Error: no non-leaf 'build' dir found on target path", t
4822761Sstever@eecs.umich.edu        Exit(1)
4831869SN/A    this_build_root = joinpath('/',*path_dirs[:build_top+1])
4842733Sktlim@umich.edu    if not build_root:
4853584Ssaidi@eecs.umich.edu        build_root = this_build_root
4861869SN/A    else:
4871869SN/A        if this_build_root != build_root:
4881869SN/A            print "Error: build targets not under same build root\n"\
4891869SN/A                  "  %s\n  %s" % (build_root, this_build_root)
4901869SN/A            Exit(1)
4911869SN/A    variant_path = joinpath('/',*path_dirs[:build_top+2])
4921858SN/A    if variant_path not in variant_paths:
493955SN/A        variant_paths.append(variant_path)
494955SN/A
4951869SN/A# Make sure build_root exists (might not if this is the first build there)
4961869SN/Aif not isdir(build_root):
4971869SN/A    mkdir(build_root)
4981869SN/Amain['BUILDROOT'] = build_root
4991869SN/A
5001869SN/AExport('main')
5011869SN/A
5021869SN/Amain.SConsignFile(joinpath(build_root, "sconsign"))
5031869SN/A
5041869SN/A# Default duplicate option is to use hard links, but this messes up
5051869SN/A# when you use emacs to edit a file in the target dir, as emacs moves
5061869SN/A# file to file~ then copies to file, breaking the link.  Symbolic
5071869SN/A# (soft) links work better.
5081869SN/Amain.SetOption('duplicate', 'soft-copy')
5091869SN/A
5101869SN/A#
5111869SN/A# Set up global sticky variables... these are common to an entire build
5121869SN/A# tree (not specific to a particular build like ALPHA_SE)
5131869SN/A#
5141869SN/A
5151869SN/Aglobal_vars_file = joinpath(build_root, 'variables.global')
5161869SN/A
5171869SN/Aglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
5181869SN/A
5191869SN/Aglobal_vars.AddVariables(
5201869SN/A    ('CC', 'C compiler', environ.get('CC', main['CC'])),
5211869SN/A    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
5221869SN/A    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
5231869SN/A    ('BATCH', 'Use batch pool for build and tests', False),
5243716Sstever@eecs.umich.edu    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
5253356Sbinkertn@umich.edu    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
5263356Sbinkertn@umich.edu    ('EXTRAS', 'Add extra directories to the compilation', '')
5273356Sbinkertn@umich.edu    )
5283356Sbinkertn@umich.edu
5293356Sbinkertn@umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
5303356Sbinkertn@umich.eduglobal_vars.Update(main)
5314781Snate@binkert.orghelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
5321869SN/A
5331869SN/A# Save sticky variable settings back to current variables file
5341869SN/Aglobal_vars.Save(global_vars_file, main)
5351869SN/A
5361869SN/A# Parse EXTRAS variable to build list of all directories where we're
5371869SN/A# look for sources etc.  This list is exported as extras_dir_list.
5381869SN/Abase_dir = main.srcdir.abspath
5392655Sstever@eecs.umich.eduif main['EXTRAS']:
5402655Sstever@eecs.umich.edu    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
5412655Sstever@eecs.umich.eduelse:
5422655Sstever@eecs.umich.edu    extras_dir_list = []
5432655Sstever@eecs.umich.edu
5442655Sstever@eecs.umich.eduExport('base_dir')
5452655Sstever@eecs.umich.eduExport('extras_dir_list')
5462655Sstever@eecs.umich.edu
5472655Sstever@eecs.umich.edu# the ext directory should be on the #includes path
5482655Sstever@eecs.umich.edumain.Append(CPPPATH=[Dir('ext')])
5492655Sstever@eecs.umich.edu
5502655Sstever@eecs.umich.edudef strip_build_path(path, env):
5512655Sstever@eecs.umich.edu    path = str(path)
5522655Sstever@eecs.umich.edu    variant_base = env['BUILDROOT'] + os.path.sep
5532655Sstever@eecs.umich.edu    if path.startswith(variant_base):
5542655Sstever@eecs.umich.edu        path = path[len(variant_base):]
5552655Sstever@eecs.umich.edu    elif path.startswith('build/'):
5562655Sstever@eecs.umich.edu        path = path[6:]
5572655Sstever@eecs.umich.edu    return path
5582655Sstever@eecs.umich.edu
5592655Sstever@eecs.umich.edu# Generate a string of the form:
5602655Sstever@eecs.umich.edu#   common/path/prefix/src1, src2 -> tgt1, tgt2
5612655Sstever@eecs.umich.edu# to print while building.
5622655Sstever@eecs.umich.educlass Transform(object):
5632655Sstever@eecs.umich.edu    # all specific color settings should be here and nowhere else
5642655Sstever@eecs.umich.edu    tool_color = termcap.Normal
5652634Sstever@eecs.umich.edu    pfx_color = termcap.Yellow
5662634Sstever@eecs.umich.edu    srcs_color = termcap.Yellow + termcap.Bold
5672634Sstever@eecs.umich.edu    arrow_color = termcap.Blue + termcap.Bold
5682634Sstever@eecs.umich.edu    tgts_color = termcap.Yellow + termcap.Bold
5692634Sstever@eecs.umich.edu
5702634Sstever@eecs.umich.edu    def __init__(self, tool, max_sources=99):
5712638Sstever@eecs.umich.edu        self.format = self.tool_color + (" [%8s] " % tool) \
5722638Sstever@eecs.umich.edu                      + self.pfx_color + "%s" \
5733716Sstever@eecs.umich.edu                      + self.srcs_color + "%s" \
5742638Sstever@eecs.umich.edu                      + self.arrow_color + " -> " \
5752638Sstever@eecs.umich.edu                      + self.tgts_color + "%s" \
5761869SN/A                      + termcap.Normal
5771869SN/A        self.max_sources = max_sources
5783546Sgblack@eecs.umich.edu
5793546Sgblack@eecs.umich.edu    def __call__(self, target, source, env, for_signature=None):
5803546Sgblack@eecs.umich.edu        # truncate source list according to max_sources param
5813546Sgblack@eecs.umich.edu        source = source[0:self.max_sources]
5824202Sbinkertn@umich.edu        def strip(f):
5833546Sgblack@eecs.umich.edu            return strip_build_path(str(f), env)
5843546Sgblack@eecs.umich.edu        if len(source) > 0:
5853546Sgblack@eecs.umich.edu            srcs = map(strip, source)
5863546Sgblack@eecs.umich.edu        else:
5873546Sgblack@eecs.umich.edu            srcs = ['']
5884781Snate@binkert.org        tgts = map(strip, target)
5894781Snate@binkert.org        # surprisingly, os.path.commonprefix is a dumb char-by-char string
5904781Snate@binkert.org        # operation that has nothing to do with paths.
5914781Snate@binkert.org        com_pfx = os.path.commonprefix(srcs + tgts)
5924781Snate@binkert.org        com_pfx_len = len(com_pfx)
5934781Snate@binkert.org        if com_pfx:
5944781Snate@binkert.org            # do some cleanup and sanity checking on common prefix
5954781Snate@binkert.org            if com_pfx[-1] == ".":
5964781Snate@binkert.org                # prefix matches all but file extension: ok
5974781Snate@binkert.org                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
5984781Snate@binkert.org                com_pfx = com_pfx[0:-1]
5994781Snate@binkert.org            elif com_pfx[-1] == "/":
6003546Sgblack@eecs.umich.edu                # common prefix is directory path: OK
6013546Sgblack@eecs.umich.edu                pass
6023546Sgblack@eecs.umich.edu            else:
6034781Snate@binkert.org                src0_len = len(srcs[0])
6043546Sgblack@eecs.umich.edu                tgt0_len = len(tgts[0])
6053546Sgblack@eecs.umich.edu                if src0_len == com_pfx_len:
6063546Sgblack@eecs.umich.edu                    # source is a substring of target, OK
6073546Sgblack@eecs.umich.edu                    pass
6083546Sgblack@eecs.umich.edu                elif tgt0_len == com_pfx_len:
6093546Sgblack@eecs.umich.edu                    # target is a substring of source, need to back up to
6103546Sgblack@eecs.umich.edu                    # avoid empty string on RHS of arrow
6113546Sgblack@eecs.umich.edu                    sep_idx = com_pfx.rfind(".")
6123546Sgblack@eecs.umich.edu                    if sep_idx != -1:
6133546Sgblack@eecs.umich.edu                        com_pfx = com_pfx[0:sep_idx]
6144202Sbinkertn@umich.edu                    else:
6153546Sgblack@eecs.umich.edu                        com_pfx = ''
6163546Sgblack@eecs.umich.edu                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
6173546Sgblack@eecs.umich.edu                    # still splitting at file extension: ok
618955SN/A                    pass
619955SN/A                else:
620955SN/A                    # probably a fluke; ignore it
621955SN/A                    com_pfx = ''
6221858SN/A        # recalculate length in case com_pfx was modified
6231858SN/A        com_pfx_len = len(com_pfx)
6241858SN/A        def fmt(files):
6252632Sstever@eecs.umich.edu            f = map(lambda s: s[com_pfx_len:], files)
6262632Sstever@eecs.umich.edu            return ', '.join(f)
6274773Snate@binkert.org        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
6284773Snate@binkert.org
6292632Sstever@eecs.umich.eduExport('Transform')
6302632Sstever@eecs.umich.edu
6312632Sstever@eecs.umich.edu# enable the regression script to use the termcap
6322634Sstever@eecs.umich.edumain['TERMCAP'] = termcap
6332638Sstever@eecs.umich.edu
6342023SN/Aif GetOption('verbose'):
6352632Sstever@eecs.umich.edu    def MakeAction(action, string, *args, **kwargs):
6362632Sstever@eecs.umich.edu        return Action(action, *args, **kwargs)
6372632Sstever@eecs.umich.eduelse:
6382632Sstever@eecs.umich.edu    MakeAction = Action
6392632Sstever@eecs.umich.edu    main['CCCOMSTR']        = Transform("CC")
6403716Sstever@eecs.umich.edu    main['CXXCOMSTR']       = Transform("CXX")
6412632Sstever@eecs.umich.edu    main['ASCOMSTR']        = Transform("AS")
6422632Sstever@eecs.umich.edu    main['ARCOMSTR']        = Transform("AR", 0)
6432632Sstever@eecs.umich.edu    main['LINKCOMSTR']      = Transform("LINK", 0)
6442632Sstever@eecs.umich.edu    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
6452632Sstever@eecs.umich.edu    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
6462023SN/A    main['M4COMSTR']        = Transform("M4")
6472632Sstever@eecs.umich.edu    main['SHCCCOMSTR']      = Transform("SHCC")
6482632Sstever@eecs.umich.edu    main['SHCXXCOMSTR']     = Transform("SHCXX")
6491889SN/AExport('MakeAction')
6501889SN/A
6512632Sstever@eecs.umich.edu# Initialize the Link-Time Optimization (LTO) flags
6522632Sstever@eecs.umich.edumain['LTO_CCFLAGS'] = []
6532632Sstever@eecs.umich.edumain['LTO_LDFLAGS'] = []
6542632Sstever@eecs.umich.edu
6553716Sstever@eecs.umich.edu# According to the readme, tcmalloc works best if the compiler doesn't
6563716Sstever@eecs.umich.edu# assume that we're using the builtin malloc and friends. These flags
6572632Sstever@eecs.umich.edu# are compiler-specific, so we need to set them after we detect which
6582632Sstever@eecs.umich.edu# compiler we're using.
6592632Sstever@eecs.umich.edumain['TCMALLOC_CCFLAGS'] = []
6602632Sstever@eecs.umich.edu
6612632Sstever@eecs.umich.eduCXX_version = readCommand([main['CXX'],'--version'], exception=False)
6622632Sstever@eecs.umich.eduCXX_V = readCommand([main['CXX'],'-V'], exception=False)
6632632Sstever@eecs.umich.edu
6642632Sstever@eecs.umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
6651888SN/Amain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
6661888SN/Aif main['GCC'] + main['CLANG'] > 1:
6671869SN/A    print 'Error: How can we have two at the same time?'
6681869SN/A    Exit(1)
6691858SN/A
6702598SN/A# Set up default C++ compiler flags
6712598SN/Aif main['GCC'] or main['CLANG']:
6722598SN/A    # As gcc and clang share many flags, do the common parts here
6732598SN/A    main.Append(CCFLAGS=['-pipe'])
6742598SN/A    main.Append(CCFLAGS=['-fno-strict-aliasing'])
6751858SN/A    # Enable -Wall and -Wextra and then disable the few warnings that
6761858SN/A    # we consistently violate
6771858SN/A    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
6781858SN/A                         '-Wno-sign-compare', '-Wno-unused-parameter'])
6791858SN/A    # We always compile using C++11
6801858SN/A    main.Append(CXXFLAGS=['-std=c++11'])
6811858SN/A    if sys.platform.startswith('freebsd'):
6821858SN/A        main.Append(CCFLAGS=['-I/usr/local/include'])
6831858SN/A        main.Append(CXXFLAGS=['-I/usr/local/include'])
6841871SN/A
6851858SN/A    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
6861858SN/A    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
6871858SN/A    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
6881858SN/A    shared_partial_flags = ['-r', '-nostdlib']
6891858SN/A    main.Append(PSHLINKFLAGS=shared_partial_flags)
6901858SN/A    main.Append(PLINKFLAGS=shared_partial_flags)
6911858SN/Aelse:
6921858SN/A    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6931858SN/A    print "Don't know what compiler options to use for your compiler."
6941858SN/A    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6951858SN/A    print termcap.Yellow + '       version:' + termcap.Normal,
6961859SN/A    if not CXX_version:
6971859SN/A        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6981869SN/A               termcap.Normal
6991888SN/A    else:
7002632Sstever@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
7011869SN/A    print "       If you're trying to use a compiler other than GCC"
7021884SN/A    print "       or clang, there appears to be something wrong with your"
7031884SN/A    print "       environment."
7041884SN/A    print "       "
7051884SN/A    print "       If you are trying to use a compiler other than those listed"
7061884SN/A    print "       above you will need to ease fix SConstruct and "
7071884SN/A    print "       src/SConscript to support that compiler."
7081965SN/A    Exit(1)
7091965SN/A
7101965SN/Aif main['GCC']:
7112761Sstever@eecs.umich.edu    # Check for a supported version of gcc. >= 4.8 is chosen for its
7121869SN/A    # level of c++11 support. See
7131869SN/A    # http://gcc.gnu.org/projects/cxx0x.html for details.
7142632Sstever@eecs.umich.edu    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
7152667Sstever@eecs.umich.edu    if compareVersions(gcc_version, "4.8") < 0:
7161869SN/A        print 'Error: gcc version 4.8 or newer required.'
7171869SN/A        print '       Installed version:', gcc_version
7182929Sktlim@umich.edu        Exit(1)
7192929Sktlim@umich.edu
7203716Sstever@eecs.umich.edu    main['GCC_VERSION'] = gcc_version
7212929Sktlim@umich.edu
722955SN/A    # gcc from version 4.8 and above generates "rep; ret" instructions
7232598SN/A    # to avoid performance penalties on certain AMD chips. Older
7242598SN/A    # assemblers detect this as an error, "Error: expecting string
7253546Sgblack@eecs.umich.edu    # instruction after `rep'"
726955SN/A    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
727955SN/A                                  '-o', '/dev/null'],
728955SN/A                                 exception=False).split()
7291530SN/A
730955SN/A    # version strings may contain extra distro-specific
731955SN/A    # qualifiers, so play it safe and keep only what comes before
732955SN/A    # the first hyphen
733    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
734
735    if not as_version or compareVersions(as_version, "2.23") < 0:
736        print termcap.Yellow + termcap.Bold + \
737            'Warning: This combination of gcc and binutils have' + \
738            ' known incompatibilities.\n' + \
739            '         If you encounter build problems, please update ' + \
740            'binutils to 2.23.' + \
741            termcap.Normal
742
743    # Make sure we warn if the user has requested to compile with the
744    # Undefined Benahvior Sanitizer and this version of gcc does not
745    # support it.
746    if GetOption('with_ubsan') and \
747            compareVersions(gcc_version, '4.9') < 0:
748        print termcap.Yellow + termcap.Bold + \
749            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
750            termcap.Normal
751
752    # Add the appropriate Link-Time Optimization (LTO) flags
753    # unless LTO is explicitly turned off. Note that these flags
754    # are only used by the fast target.
755    if not GetOption('no_lto'):
756        # Pass the LTO flag when compiling to produce GIMPLE
757        # output, we merely create the flags here and only append
758        # them later
759        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
760
761        # Use the same amount of jobs for LTO as we are running
762        # scons with
763        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
764
765    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
766                                  '-fno-builtin-realloc', '-fno-builtin-free'])
767
768    # add option to check for undeclared overrides
769    if compareVersions(gcc_version, "5.0") > 0:
770        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
771
772elif main['CLANG']:
773    # Check for a supported version of clang, >= 3.1 is needed to
774    # support similar features as gcc 4.8. See
775    # http://clang.llvm.org/cxx_status.html for details
776    clang_version_re = re.compile(".* version (\d+\.\d+)")
777    clang_version_match = clang_version_re.search(CXX_version)
778    if (clang_version_match):
779        clang_version = clang_version_match.groups()[0]
780        if compareVersions(clang_version, "3.1") < 0:
781            print 'Error: clang version 3.1 or newer required.'
782            print '       Installed version:', clang_version
783            Exit(1)
784    else:
785        print 'Error: Unable to determine clang version.'
786        Exit(1)
787
788    # clang has a few additional warnings that we disable, extraneous
789    # parantheses are allowed due to Ruby's printing of the AST,
790    # finally self assignments are allowed as the generated CPU code
791    # is relying on this
792    main.Append(CCFLAGS=['-Wno-parentheses',
793                         '-Wno-self-assign',
794                         # Some versions of libstdc++ (4.8?) seem to
795                         # use struct hash and class hash
796                         # interchangeably.
797                         '-Wno-mismatched-tags',
798                         ])
799
800    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
801
802    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
803    # opposed to libstdc++, as the later is dated.
804    if sys.platform == "darwin":
805        main.Append(CXXFLAGS=['-stdlib=libc++'])
806        main.Append(LIBS=['c++'])
807
808    # On FreeBSD we need libthr.
809    if sys.platform.startswith('freebsd'):
810        main.Append(LIBS=['thr'])
811
812else:
813    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
814    print "Don't know what compiler options to use for your compiler."
815    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
816    print termcap.Yellow + '       version:' + termcap.Normal,
817    if not CXX_version:
818        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
819               termcap.Normal
820    else:
821        print CXX_version.replace('\n', '<nl>')
822    print "       If you're trying to use a compiler other than GCC"
823    print "       or clang, there appears to be something wrong with your"
824    print "       environment."
825    print "       "
826    print "       If you are trying to use a compiler other than those listed"
827    print "       above you will need to ease fix SConstruct and "
828    print "       src/SConscript to support that compiler."
829    Exit(1)
830
831# Set up common yacc/bison flags (needed for Ruby)
832main['YACCFLAGS'] = '-d'
833main['YACCHXXFILESUFFIX'] = '.hh'
834
835# Do this after we save setting back, or else we'll tack on an
836# extra 'qdo' every time we run scons.
837if main['BATCH']:
838    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
839    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
840    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
841    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
842    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
843
844if sys.platform == 'cygwin':
845    # cygwin has some header file issues...
846    main.Append(CCFLAGS=["-Wno-uninitialized"])
847
848# Check for the protobuf compiler
849protoc_version = readCommand([main['PROTOC'], '--version'],
850                             exception='').split()
851
852# First two words should be "libprotoc x.y.z"
853if len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
854    print termcap.Yellow + termcap.Bold + \
855        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
856        '         Please install protobuf-compiler for tracing support.' + \
857        termcap.Normal
858    main['PROTOC'] = False
859else:
860    # Based on the availability of the compress stream wrappers,
861    # require 2.1.0
862    min_protoc_version = '2.1.0'
863    if compareVersions(protoc_version[1], min_protoc_version) < 0:
864        print termcap.Yellow + termcap.Bold + \
865            'Warning: protoc version', min_protoc_version, \
866            'or newer required.\n' + \
867            '         Installed version:', protoc_version[1], \
868            termcap.Normal
869        main['PROTOC'] = False
870    else:
871        # Attempt to determine the appropriate include path and
872        # library path using pkg-config, that means we also need to
873        # check for pkg-config. Note that it is possible to use
874        # protobuf without the involvement of pkg-config. Later on we
875        # check go a library config check and at that point the test
876        # will fail if libprotobuf cannot be found.
877        if readCommand(['pkg-config', '--version'], exception=''):
878            try:
879                # Attempt to establish what linking flags to add for protobuf
880                # using pkg-config
881                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
882            except:
883                print termcap.Yellow + termcap.Bold + \
884                    'Warning: pkg-config could not get protobuf flags.' + \
885                    termcap.Normal
886
887
888# Check for 'timeout' from GNU coreutils. If present, regressions will
889# be run with a time limit. We require version 8.13 since we rely on
890# support for the '--foreground' option.
891if sys.platform.startswith('freebsd'):
892    timeout_lines = readCommand(['gtimeout', '--version'],
893                                exception='').splitlines()
894else:
895    timeout_lines = readCommand(['timeout', '--version'],
896                                exception='').splitlines()
897# Get the first line and tokenize it
898timeout_version = timeout_lines[0].split() if timeout_lines else []
899main['TIMEOUT'] =  timeout_version and \
900    compareVersions(timeout_version[-1], '8.13') >= 0
901
902# Add a custom Check function to test for structure members.
903def CheckMember(context, include, decl, member, include_quotes="<>"):
904    context.Message("Checking for member %s in %s..." %
905                    (member, decl))
906    text = """
907#include %(header)s
908int main(){
909  %(decl)s test;
910  (void)test.%(member)s;
911  return 0;
912};
913""" % { "header" : include_quotes[0] + include + include_quotes[1],
914        "decl" : decl,
915        "member" : member,
916        }
917
918    ret = context.TryCompile(text, extension=".cc")
919    context.Result(ret)
920    return ret
921
922# Platform-specific configuration.  Note again that we assume that all
923# builds under a given build root run on the same host platform.
924conf = Configure(main,
925                 conf_dir = joinpath(build_root, '.scons_config'),
926                 log_file = joinpath(build_root, 'scons_config.log'),
927                 custom_tests = {
928        'CheckMember' : CheckMember,
929        })
930
931# Check if we should compile a 64 bit binary on Mac OS X/Darwin
932try:
933    import platform
934    uname = platform.uname()
935    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
936        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
937            main.Append(CCFLAGS=['-arch', 'x86_64'])
938            main.Append(CFLAGS=['-arch', 'x86_64'])
939            main.Append(LINKFLAGS=['-arch', 'x86_64'])
940            main.Append(ASFLAGS=['-arch', 'x86_64'])
941except:
942    pass
943
944# Recent versions of scons substitute a "Null" object for Configure()
945# when configuration isn't necessary, e.g., if the "--help" option is
946# present.  Unfortuantely this Null object always returns false,
947# breaking all our configuration checks.  We replace it with our own
948# more optimistic null object that returns True instead.
949if not conf:
950    def NullCheck(*args, **kwargs):
951        return True
952
953    class NullConf:
954        def __init__(self, env):
955            self.env = env
956        def Finish(self):
957            return self.env
958        def __getattr__(self, mname):
959            return NullCheck
960
961    conf = NullConf(main)
962
963# Cache build files in the supplied directory.
964if main['M5_BUILD_CACHE']:
965    print 'Using build cache located at', main['M5_BUILD_CACHE']
966    CacheDir(main['M5_BUILD_CACHE'])
967
968main['USE_PYTHON'] = not GetOption('without_python')
969if main['USE_PYTHON']:
970    # Find Python include and library directories for embedding the
971    # interpreter. We rely on python-config to resolve the appropriate
972    # includes and linker flags. ParseConfig does not seem to understand
973    # the more exotic linker flags such as -Xlinker and -export-dynamic so
974    # we add them explicitly below. If you want to link in an alternate
975    # version of python, see above for instructions on how to invoke
976    # scons with the appropriate PATH set.
977    #
978    # First we check if python2-config exists, else we use python-config
979    python_config = readCommand(['which', 'python2-config'],
980                                exception='').strip()
981    if not os.path.exists(python_config):
982        python_config = readCommand(['which', 'python-config'],
983                                    exception='').strip()
984    py_includes = readCommand([python_config, '--includes'],
985                              exception='').split()
986    # Strip the -I from the include folders before adding them to the
987    # CPPPATH
988    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
989
990    # Read the linker flags and split them into libraries and other link
991    # flags. The libraries are added later through the call the CheckLib.
992    py_ld_flags = readCommand([python_config, '--ldflags'],
993        exception='').split()
994    py_libs = []
995    for lib in py_ld_flags:
996         if not lib.startswith('-l'):
997             main.Append(LINKFLAGS=[lib])
998         else:
999             lib = lib[2:]
1000             if lib not in py_libs:
1001                 py_libs.append(lib)
1002
1003    # verify that this stuff works
1004    if not conf.CheckHeader('Python.h', '<>'):
1005        print "Error: can't find Python.h header in", py_includes
1006        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
1007        Exit(1)
1008
1009    for lib in py_libs:
1010        if not conf.CheckLib(lib):
1011            print "Error: can't find library %s required by python" % lib
1012            Exit(1)
1013
1014# On Solaris you need to use libsocket for socket ops
1015if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
1016   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
1017       print "Can't find library with socket calls (e.g. accept())"
1018       Exit(1)
1019
1020# Check for zlib.  If the check passes, libz will be automatically
1021# added to the LIBS environment variable.
1022if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
1023    print 'Error: did not find needed zlib compression library '\
1024          'and/or zlib.h header file.'
1025    print '       Please install zlib and try again.'
1026    Exit(1)
1027
1028# If we have the protobuf compiler, also make sure we have the
1029# development libraries. If the check passes, libprotobuf will be
1030# automatically added to the LIBS environment variable. After
1031# this, we can use the HAVE_PROTOBUF flag to determine if we have
1032# got both protoc and libprotobuf available.
1033main['HAVE_PROTOBUF'] = main['PROTOC'] and \
1034    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
1035                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
1036
1037# If we have the compiler but not the library, print another warning.
1038if main['PROTOC'] and not main['HAVE_PROTOBUF']:
1039    print termcap.Yellow + termcap.Bold + \
1040        'Warning: did not find protocol buffer library and/or headers.\n' + \
1041    '       Please install libprotobuf-dev for tracing support.' + \
1042    termcap.Normal
1043
1044# Check for librt.
1045have_posix_clock = \
1046    conf.CheckLibWithHeader(None, 'time.h', 'C',
1047                            'clock_nanosleep(0,0,NULL,NULL);') or \
1048    conf.CheckLibWithHeader('rt', 'time.h', 'C',
1049                            'clock_nanosleep(0,0,NULL,NULL);')
1050
1051have_posix_timers = \
1052    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
1053                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
1054
1055if not GetOption('without_tcmalloc'):
1056    if conf.CheckLib('tcmalloc'):
1057        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
1058    elif conf.CheckLib('tcmalloc_minimal'):
1059        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
1060    else:
1061        print termcap.Yellow + termcap.Bold + \
1062              "You can get a 12% performance improvement by "\
1063              "installing tcmalloc (libgoogle-perftools-dev package "\
1064              "on Ubuntu or RedHat)." + termcap.Normal
1065
1066
1067# Detect back trace implementations. The last implementation in the
1068# list will be used by default.
1069backtrace_impls = [ "none" ]
1070
1071if conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
1072                           'backtrace_symbols_fd((void*)0, 0, 0);'):
1073    backtrace_impls.append("glibc")
1074elif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
1075                           'backtrace_symbols_fd((void*)0, 0, 0);'):
1076    # NetBSD and FreeBSD need libexecinfo.
1077    backtrace_impls.append("glibc")
1078    main.Append(LIBS=['execinfo'])
1079
1080if backtrace_impls[-1] == "none":
1081    default_backtrace_impl = "none"
1082    print termcap.Yellow + termcap.Bold + \
1083        "No suitable back trace implementation found." + \
1084        termcap.Normal
1085
1086if not have_posix_clock:
1087    print "Can't find library for POSIX clocks."
1088
1089# Check for <fenv.h> (C99 FP environment control)
1090have_fenv = conf.CheckHeader('fenv.h', '<>')
1091if not have_fenv:
1092    print "Warning: Header file <fenv.h> not found."
1093    print "         This host has no IEEE FP rounding mode control."
1094
1095# Check if we should enable KVM-based hardware virtualization. The API
1096# we rely on exists since version 2.6.36 of the kernel, but somehow
1097# the KVM_API_VERSION does not reflect the change. We test for one of
1098# the types as a fall back.
1099have_kvm = conf.CheckHeader('linux/kvm.h', '<>')
1100if not have_kvm:
1101    print "Info: Compatible header file <linux/kvm.h> not found, " \
1102        "disabling KVM support."
1103
1104# Check if the TUN/TAP driver is available.
1105have_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
1106if not have_tuntap:
1107    print "Info: Compatible header file <linux/if_tun.h> not found."
1108
1109# x86 needs support for xsave. We test for the structure here since we
1110# won't be able to run new tests by the time we know which ISA we're
1111# targeting.
1112have_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
1113                                    '#include <linux/kvm.h>') != 0
1114
1115# Check if the requested target ISA is compatible with the host
1116def is_isa_kvm_compatible(isa):
1117    try:
1118        import platform
1119        host_isa = platform.machine()
1120    except:
1121        print "Warning: Failed to determine host ISA."
1122        return False
1123
1124    if not have_posix_timers:
1125        print "Warning: Can not enable KVM, host seems to lack support " \
1126            "for POSIX timers"
1127        return False
1128
1129    if isa == "arm":
1130        return host_isa in ( "armv7l", "aarch64" )
1131    elif isa == "x86":
1132        if host_isa != "x86_64":
1133            return False
1134
1135        if not have_kvm_xsave:
1136            print "KVM on x86 requires xsave support in kernel headers."
1137            return False
1138
1139        return True
1140    else:
1141        return False
1142
1143
1144# Check if the exclude_host attribute is available. We want this to
1145# get accurate instruction counts in KVM.
1146main['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
1147    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
1148
1149
1150######################################################################
1151#
1152# Finish the configuration
1153#
1154main = conf.Finish()
1155
1156######################################################################
1157#
1158# Collect all non-global variables
1159#
1160
1161# Define the universe of supported ISAs
1162all_isa_list = [ ]
1163all_gpu_isa_list = [ ]
1164Export('all_isa_list')
1165Export('all_gpu_isa_list')
1166
1167class CpuModel(object):
1168    '''The CpuModel class encapsulates everything the ISA parser needs to
1169    know about a particular CPU model.'''
1170
1171    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
1172    dict = {}
1173
1174    # Constructor.  Automatically adds models to CpuModel.dict.
1175    def __init__(self, name, default=False):
1176        self.name = name           # name of model
1177
1178        # This cpu is enabled by default
1179        self.default = default
1180
1181        # Add self to dict
1182        if name in CpuModel.dict:
1183            raise AttributeError, "CpuModel '%s' already registered" % name
1184        CpuModel.dict[name] = self
1185
1186Export('CpuModel')
1187
1188# Sticky variables get saved in the variables file so they persist from
1189# one invocation to the next (unless overridden, in which case the new
1190# value becomes sticky).
1191sticky_vars = Variables(args=ARGUMENTS)
1192Export('sticky_vars')
1193
1194# Sticky variables that should be exported
1195export_vars = []
1196Export('export_vars')
1197
1198# For Ruby
1199all_protocols = []
1200Export('all_protocols')
1201protocol_dirs = []
1202Export('protocol_dirs')
1203slicc_includes = []
1204Export('slicc_includes')
1205
1206# Walk the tree and execute all SConsopts scripts that wil add to the
1207# above variables
1208if GetOption('verbose'):
1209    print "Reading SConsopts"
1210for bdir in [ base_dir ] + extras_dir_list:
1211    if not isdir(bdir):
1212        print "Error: directory '%s' does not exist" % bdir
1213        Exit(1)
1214    for root, dirs, files in os.walk(bdir):
1215        if 'SConsopts' in files:
1216            if GetOption('verbose'):
1217                print "Reading", joinpath(root, 'SConsopts')
1218            SConscript(joinpath(root, 'SConsopts'))
1219
1220all_isa_list.sort()
1221all_gpu_isa_list.sort()
1222
1223sticky_vars.AddVariables(
1224    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
1225    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
1226    ListVariable('CPU_MODELS', 'CPU models',
1227                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
1228                 sorted(CpuModel.dict.keys())),
1229    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
1230                 False),
1231    BoolVariable('SS_COMPATIBLE_FP',
1232                 'Make floating-point results compatible with SimpleScalar',
1233                 False),
1234    BoolVariable('USE_SSE2',
1235                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
1236                 False),
1237    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
1238    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
1239    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
1240    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
1241    BoolVariable('USE_TUNTAP',
1242                 'Enable using a tap device to bridge to the host network',
1243                 have_tuntap),
1244    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
1245    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1246                  all_protocols),
1247    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
1248                 backtrace_impls[-1], backtrace_impls)
1249    )
1250
1251# These variables get exported to #defines in config/*.hh (see src/SConscript).
1252export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
1253                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
1254                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST']
1255
1256###################################################
1257#
1258# Define a SCons builder for configuration flag headers.
1259#
1260###################################################
1261
1262# This function generates a config header file that #defines the
1263# variable symbol to the current variable setting (0 or 1).  The source
1264# operands are the name of the variable and a Value node containing the
1265# value of the variable.
1266def build_config_file(target, source, env):
1267    (variable, value) = [s.get_contents() for s in source]
1268    f = file(str(target[0]), 'w')
1269    print >> f, '#define', variable, value
1270    f.close()
1271    return None
1272
1273# Combine the two functions into a scons Action object.
1274config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1275
1276# The emitter munges the source & target node lists to reflect what
1277# we're really doing.
1278def config_emitter(target, source, env):
1279    # extract variable name from Builder arg
1280    variable = str(target[0])
1281    # True target is config header file
1282    target = joinpath('config', variable.lower() + '.hh')
1283    val = env[variable]
1284    if isinstance(val, bool):
1285        # Force value to 0/1
1286        val = int(val)
1287    elif isinstance(val, str):
1288        val = '"' + val + '"'
1289
1290    # Sources are variable name & value (packaged in SCons Value nodes)
1291    return ([target], [Value(variable), Value(val)])
1292
1293config_builder = Builder(emitter = config_emitter, action = config_action)
1294
1295main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1296
1297###################################################
1298#
1299# Builders for static and shared partially linked object files.
1300#
1301###################################################
1302
1303partial_static_builder = Builder(action=SCons.Defaults.LinkAction,
1304                                 src_suffix='$OBJSUFFIX',
1305                                 src_builder=['StaticObject', 'Object'],
1306                                 LINKFLAGS='$PLINKFLAGS',
1307                                 LIBS='')
1308
1309def partial_shared_emitter(target, source, env):
1310    for tgt in target:
1311        tgt.attributes.shared = 1
1312    return (target, source)
1313partial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
1314                                 emitter=partial_shared_emitter,
1315                                 src_suffix='$SHOBJSUFFIX',
1316                                 src_builder='SharedObject',
1317                                 SHLINKFLAGS='$PSHLINKFLAGS',
1318                                 LIBS='')
1319
1320main.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
1321                         'PartialStatic' : partial_static_builder })
1322
1323# builds in ext are shared across all configs in the build root.
1324ext_dir = abspath(joinpath(str(main.root), 'ext'))
1325ext_build_dirs = []
1326for root, dirs, files in os.walk(ext_dir):
1327    if 'SConscript' in files:
1328        build_dir = os.path.relpath(root, ext_dir)
1329        ext_build_dirs.append(build_dir)
1330        main.SConscript(joinpath(root, 'SConscript'),
1331                        variant_dir=joinpath(build_root, build_dir))
1332
1333main.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
1334
1335###################################################
1336#
1337# This builder and wrapper method are used to set up a directory with
1338# switching headers. Those are headers which are in a generic location and
1339# that include more specific headers from a directory chosen at build time
1340# based on the current build settings.
1341#
1342###################################################
1343
1344def build_switching_header(target, source, env):
1345    path = str(target[0])
1346    subdir = str(source[0])
1347    dp, fp = os.path.split(path)
1348    dp = os.path.relpath(os.path.realpath(dp),
1349                         os.path.realpath(env['BUILDDIR']))
1350    with open(path, 'w') as hdr:
1351        print >>hdr, '#include "%s/%s/%s"' % (dp, subdir, fp)
1352
1353switching_header_action = MakeAction(build_switching_header,
1354                                     Transform('GENERATE'))
1355
1356switching_header_builder = Builder(action=switching_header_action,
1357                                   source_factory=Value,
1358                                   single_source=True)
1359
1360main.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
1361
1362def switching_headers(self, headers, source):
1363    for header in headers:
1364        self.SwitchingHeader(header, source)
1365
1366main.AddMethod(switching_headers, 'SwitchingHeaders')
1367
1368# all-isas -> all-deps -> all-environs -> all_targets
1369main.Alias('#all-isas', [])
1370main.Alias('#all-deps', '#all-isas')
1371
1372# Dummy target to ensure all environments are created before telling
1373# SCons what to actually make (the command line arguments).  We attach
1374# them to the dependence graph after the environments are complete.
1375ORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
1376def environsComplete(target, source, env):
1377    for t in ORIG_BUILD_TARGETS:
1378        main.Depends('#all-targets', t)
1379
1380# Each build/* switching_dir attaches its *-environs target to #all-environs.
1381main.Append(BUILDERS = {'CompleteEnvirons' :
1382                        Builder(action=MakeAction(environsComplete, None))})
1383main.CompleteEnvirons('#all-environs', [])
1384
1385def doNothing(**ignored): pass
1386main.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
1387
1388# The final target to which all the original targets ultimately get attached.
1389main.Dummy('#all-targets', '#all-environs')
1390BUILD_TARGETS[:] = ['#all-targets']
1391
1392###################################################
1393#
1394# Define build environments for selected configurations.
1395#
1396###################################################
1397
1398def variant_name(path):
1399    return os.path.basename(path).lower().replace('_', '-')
1400main['variant_name'] = variant_name
1401main['VARIANT_NAME'] = '${variant_name(BUILDDIR)}'
1402
1403for variant_path in variant_paths:
1404    if not GetOption('silent'):
1405        print "Building in", variant_path
1406
1407    # Make a copy of the build-root environment to use for this config.
1408    env = main.Clone()
1409    env['BUILDDIR'] = variant_path
1410
1411    # variant_dir is the tail component of build path, and is used to
1412    # determine the build parameters (e.g., 'ALPHA_SE')
1413    (build_root, variant_dir) = splitpath(variant_path)
1414
1415    # Set env variables according to the build directory config.
1416    sticky_vars.files = []
1417    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1418    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1419    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1420    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1421    if isfile(current_vars_file):
1422        sticky_vars.files.append(current_vars_file)
1423        if not GetOption('silent'):
1424            print "Using saved variables file %s" % current_vars_file
1425    elif variant_dir in ext_build_dirs:
1426        # Things in ext are built without a variant directory.
1427        continue
1428    else:
1429        # Build dir-specific variables file doesn't exist.
1430
1431        # Make sure the directory is there so we can create it later
1432        opt_dir = dirname(current_vars_file)
1433        if not isdir(opt_dir):
1434            mkdir(opt_dir)
1435
1436        # Get default build variables from source tree.  Variables are
1437        # normally determined by name of $VARIANT_DIR, but can be
1438        # overridden by '--default=' arg on command line.
1439        default = GetOption('default')
1440        opts_dir = joinpath(main.root.abspath, 'build_opts')
1441        if default:
1442            default_vars_files = [joinpath(build_root, 'variables', default),
1443                                  joinpath(opts_dir, default)]
1444        else:
1445            default_vars_files = [joinpath(opts_dir, variant_dir)]
1446        existing_files = filter(isfile, default_vars_files)
1447        if existing_files:
1448            default_vars_file = existing_files[0]
1449            sticky_vars.files.append(default_vars_file)
1450            print "Variables file %s not found,\n  using defaults in %s" \
1451                  % (current_vars_file, default_vars_file)
1452        else:
1453            print "Error: cannot find variables file %s or " \
1454                  "default file(s) %s" \
1455                  % (current_vars_file, ' or '.join(default_vars_files))
1456            Exit(1)
1457
1458    # Apply current variable settings to env
1459    sticky_vars.Update(env)
1460
1461    help_texts["local_vars"] += \
1462        "Build variables for %s:\n" % variant_dir \
1463                 + sticky_vars.GenerateHelpText(env)
1464
1465    # Process variable settings.
1466
1467    if not have_fenv and env['USE_FENV']:
1468        print "Warning: <fenv.h> not available; " \
1469              "forcing USE_FENV to False in", variant_dir + "."
1470        env['USE_FENV'] = False
1471
1472    if not env['USE_FENV']:
1473        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1474        print "         FP results may deviate slightly from other platforms."
1475
1476    if env['EFENCE']:
1477        env.Append(LIBS=['efence'])
1478
1479    if env['USE_KVM']:
1480        if not have_kvm:
1481            print "Warning: Can not enable KVM, host seems to lack KVM support"
1482            env['USE_KVM'] = False
1483        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1484            print "Info: KVM support disabled due to unsupported host and " \
1485                "target ISA combination"
1486            env['USE_KVM'] = False
1487
1488    if env['USE_TUNTAP']:
1489        if not have_tuntap:
1490            print "Warning: Can't connect EtherTap with a tap device."
1491            env['USE_TUNTAP'] = False
1492
1493    if env['BUILD_GPU']:
1494        env.Append(CPPDEFINES=['BUILD_GPU'])
1495
1496    # Warn about missing optional functionality
1497    if env['USE_KVM']:
1498        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1499            print "Warning: perf_event headers lack support for the " \
1500                "exclude_host attribute. KVM instruction counts will " \
1501                "be inaccurate."
1502
1503    # Save sticky variable settings back to current variables file
1504    sticky_vars.Save(current_vars_file, env)
1505
1506    if env['USE_SSE2']:
1507        env.Append(CCFLAGS=['-msse2'])
1508
1509    # The src/SConscript file sets up the build rules in 'env' according
1510    # to the configured variables.  It returns a list of environments,
1511    # one for each variant build (debug, opt, etc.)
1512    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1513
1514def pairwise(iterable):
1515    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1516    a, b = itertools.tee(iterable)
1517    b.next()
1518    return itertools.izip(a, b)
1519
1520variant_names = [variant_name(path) for path in variant_paths]
1521
1522# Create false dependencies so SCons will parse ISAs, establish
1523# dependencies, and setup the build Environments serially. Either
1524# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1525# greater than 1. It appears to be standard race condition stuff; it
1526# doesn't always fail, but usually, and the behaviors are different.
1527# Every time I tried to remove this, builds would fail in some
1528# creative new way. So, don't do that. You'll want to, though, because
1529# tests/SConscript takes a long time to make its Environments.
1530for t1, t2 in pairwise(sorted(variant_names)):
1531    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1532    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1533
1534# base help text
1535Help('''
1536Usage: scons [scons options] [build variables] [target(s)]
1537
1538Extra scons options:
1539%(options)s
1540
1541Global build variables:
1542%(global_vars)s
1543
1544%(local_vars)s
1545''' % help_texts)
1546