SConstruct revision 11342:a4d19e7cd26d
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2013, 2015 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
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# 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)
100955SN/Aexcept SystemExit, e:
101955SN/A    print """
1022632Sstever@eecs.umich.eduYou can use a non-default installation of the Python interpreter by
1032632Sstever@eecs.umich.edurearranging your PATH so that scons finds the non-default 'python' and
104955SN/A'python-config' first.
105955SN/A
106955SN/AFor more details, see:
107955SN/A    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1082632Sstever@eecs.umich.edu"""
109955SN/A    raise
1102632Sstever@eecs.umich.edu
1112632Sstever@eecs.umich.edu# Global Python includes
1122632Sstever@eecs.umich.eduimport itertools
1132632Sstever@eecs.umich.eduimport os
1142632Sstever@eecs.umich.eduimport re
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')
1854202Sbinkertn@umich.eduAddLocalOption('--update-ref', dest='update_ref', action='store_true',
186955SN/A               help='Update test reference outputs')
1873643Ssaidi@eecs.umich.eduAddLocalOption('--verbose', dest='verbose', action='store_true',
1883643Ssaidi@eecs.umich.edu               help='Print full tool command lines')
1893643Ssaidi@eecs.umich.eduAddLocalOption('--without-python', dest='without_python',
1903643Ssaidi@eecs.umich.edu               action='store_true',
1913643Ssaidi@eecs.umich.edu               help='Build without Python configuration support')
1923643Ssaidi@eecs.umich.eduAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1933643Ssaidi@eecs.umich.edu               action='store_true',
1943643Ssaidi@eecs.umich.edu               help='Disable linking against tcmalloc')
1953716Sstever@eecs.umich.eduAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1961105SN/A               help='Build with Undefined Behavior Sanitizer if available')
1972667Sstever@eecs.umich.eduAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1982667Sstever@eecs.umich.edu               help='Build with Address Sanitizer if available')
1992667Sstever@eecs.umich.edu
2002667Sstever@eecs.umich.edutermcap = get_termcap(GetOption('use_colors'))
2012667Sstever@eecs.umich.edu
2022667Sstever@eecs.umich.edu########################################################################
2031869SN/A#
2041869SN/A# Set up the main build environment.
2051869SN/A#
2061869SN/A########################################################################
2071869SN/A
2081065SN/A# export TERM so that clang reports errors in color
2092632Sstever@eecs.umich.eduuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
2102632Sstever@eecs.umich.edu                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
2113918Ssaidi@eecs.umich.edu                 'PYTHONPATH', 'RANLIB', 'SWIG', 'TERM' ])
2123918Ssaidi@eecs.umich.edu
2133940Ssaidi@eecs.umich.eduuse_prefixes = [
2143918Ssaidi@eecs.umich.edu    "ASAN_",           # address sanitizer symbolizer path and settings
2153918Ssaidi@eecs.umich.edu    "CCACHE_",         # ccache (caching compiler wrapper) configuration
2163918Ssaidi@eecs.umich.edu    "CCC_",            # clang static analyzer configuration
2173918Ssaidi@eecs.umich.edu    "DISTCC_",         # distcc (distributed compiler wrapper) configuration
2183918Ssaidi@eecs.umich.edu    "INCLUDE_SERVER_", # distcc pump server settings
2193918Ssaidi@eecs.umich.edu    "M5",              # M5 configuration (e.g., path to kernels)
2203940Ssaidi@eecs.umich.edu    ]
2213940Ssaidi@eecs.umich.edu
2223940Ssaidi@eecs.umich.eduuse_env = {}
2233942Ssaidi@eecs.umich.edufor key,val in sorted(os.environ.iteritems()):
2243940Ssaidi@eecs.umich.edu    if key in use_vars or \
2253918Ssaidi@eecs.umich.edu            any([key.startswith(prefix) for prefix in use_prefixes]):
2263918Ssaidi@eecs.umich.edu        use_env[key] = val
227955SN/A
2281858SN/A# Tell scons to avoid implicit command dependencies to avoid issues
2293918Ssaidi@eecs.umich.edu# with the param wrappes being compiled twice (see
2303918Ssaidi@eecs.umich.edu# http://scons.tigris.org/issues/show_bug.cgi?id=2811)
2313918Ssaidi@eecs.umich.edumain = Environment(ENV=use_env, IMPLICIT_COMMAND_DEPENDENCIES=0)
2323918Ssaidi@eecs.umich.edumain.Decider('MD5-timestamp')
2333940Ssaidi@eecs.umich.edumain.root = Dir(".")         # The current directory (where this file lives).
2343940Ssaidi@eecs.umich.edumain.srcdir = Dir("src")     # The source directory
2353918Ssaidi@eecs.umich.edu
2363918Ssaidi@eecs.umich.edumain_dict_keys = main.Dictionary().keys()
2373918Ssaidi@eecs.umich.edu
2383918Ssaidi@eecs.umich.edu# Check that we have a C/C++ compiler
2393918Ssaidi@eecs.umich.eduif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2403918Ssaidi@eecs.umich.edu    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2413918Ssaidi@eecs.umich.edu    Exit(1)
2423918Ssaidi@eecs.umich.edu
2433918Ssaidi@eecs.umich.edu# Check that swig is present
2443940Ssaidi@eecs.umich.eduif not 'SWIG' in main_dict_keys:
2453918Ssaidi@eecs.umich.edu    print "swig is not installed (package swig on Ubuntu and RedHat)"
2463918Ssaidi@eecs.umich.edu    Exit(1)
2471851SN/A
2481851SN/A# add useful python code PYTHONPATH so it can be used by subprocesses
2491858SN/A# as well
2502632Sstever@eecs.umich.edumain.AppendENVPath('PYTHONPATH', extra_python_paths)
251955SN/A
2523053Sstever@eecs.umich.edu########################################################################
2533053Sstever@eecs.umich.edu#
2543053Sstever@eecs.umich.edu# Mercurial Stuff.
2553053Sstever@eecs.umich.edu#
2563053Sstever@eecs.umich.edu# If the gem5 directory is a mercurial repository, we should do some
2573053Sstever@eecs.umich.edu# extra things.
2583053Sstever@eecs.umich.edu#
2593053Sstever@eecs.umich.edu########################################################################
2603053Sstever@eecs.umich.edu
2613053Sstever@eecs.umich.eduhgdir = main.root.Dir(".hg")
2623053Sstever@eecs.umich.edu
2633053Sstever@eecs.umich.edumercurial_style_message = """
2643053Sstever@eecs.umich.eduYou're missing the gem5 style hook, which automatically checks your code
2653053Sstever@eecs.umich.eduagainst the gem5 style rules on hg commit and qrefresh commands.  This
2663053Sstever@eecs.umich.eduscript will now install the hook in your .hg/hgrc file.
2673053Sstever@eecs.umich.eduPress enter to continue, or ctrl-c to abort: """
2683053Sstever@eecs.umich.edu
2693053Sstever@eecs.umich.edumercurial_style_hook = """
2703053Sstever@eecs.umich.edu# The following lines were automatically added by gem5/SConstruct
2712667Sstever@eecs.umich.edu# to provide the gem5 style-checking hooks
2722667Sstever@eecs.umich.edu[extensions]
2732667Sstever@eecs.umich.edustyle = %s/util/style.py
2742667Sstever@eecs.umich.edu
2752667Sstever@eecs.umich.edu[hooks]
2762667Sstever@eecs.umich.edupretxncommit.style = python:style.check_style
2772667Sstever@eecs.umich.edupre-qrefresh.style = python:style.check_style
2782667Sstever@eecs.umich.edu# End of SConstruct additions
2792667Sstever@eecs.umich.edu
2802667Sstever@eecs.umich.edu""" % (main.root.abspath)
2812667Sstever@eecs.umich.edu
2822667Sstever@eecs.umich.edumercurial_lib_not_found = """
2832638Sstever@eecs.umich.eduMercurial libraries cannot be found, ignoring style hook.  If
2842638Sstever@eecs.umich.eduyou are a gem5 developer, please fix this and run the style
2852638Sstever@eecs.umich.eduhook. It is important.
2863716Sstever@eecs.umich.edu"""
2873716Sstever@eecs.umich.edu
2881858SN/A# Check for style hook and prompt for installation if it's not there.
2893118Sstever@eecs.umich.edu# Skip this if --ignore-style was specified, there's no .hg dir to
2903118Sstever@eecs.umich.edu# install a hook in, or there's no interactive terminal to prompt.
2913118Sstever@eecs.umich.eduif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2923118Sstever@eecs.umich.edu    style_hook = True
2933118Sstever@eecs.umich.edu    try:
2943118Sstever@eecs.umich.edu        from mercurial import ui
2953118Sstever@eecs.umich.edu        ui = ui.ui()
2963118Sstever@eecs.umich.edu        ui.readconfig(hgdir.File('hgrc').abspath)
2973118Sstever@eecs.umich.edu        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2983118Sstever@eecs.umich.edu                     ui.config('hooks', 'pre-qrefresh.style', None)
2993118Sstever@eecs.umich.edu    except ImportError:
3003716Sstever@eecs.umich.edu        print mercurial_lib_not_found
3013118Sstever@eecs.umich.edu
3023118Sstever@eecs.umich.edu    if not style_hook:
3033118Sstever@eecs.umich.edu        print mercurial_style_message,
3043118Sstever@eecs.umich.edu        # continue unless user does ctrl-c/ctrl-d etc.
3053118Sstever@eecs.umich.edu        try:
3063118Sstever@eecs.umich.edu            raw_input()
3073118Sstever@eecs.umich.edu        except:
3083118Sstever@eecs.umich.edu            print "Input exception, exiting scons.\n"
3093118Sstever@eecs.umich.edu            sys.exit(1)
3103716Sstever@eecs.umich.edu        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
3113118Sstever@eecs.umich.edu        print "Adding style hook to", hgrc_path, "\n"
3123118Sstever@eecs.umich.edu        try:
3133118Sstever@eecs.umich.edu            hgrc = open(hgrc_path, 'a')
3143118Sstever@eecs.umich.edu            hgrc.write(mercurial_style_hook)
3153118Sstever@eecs.umich.edu            hgrc.close()
3163118Sstever@eecs.umich.edu        except:
3173118Sstever@eecs.umich.edu            print "Error updating", hgrc_path
3183118Sstever@eecs.umich.edu            sys.exit(1)
3193118Sstever@eecs.umich.edu
3203118Sstever@eecs.umich.edu
3213483Ssaidi@eecs.umich.edu###################################################
3223494Ssaidi@eecs.umich.edu#
3233494Ssaidi@eecs.umich.edu# Figure out which configurations to set up based on the path(s) of
3243483Ssaidi@eecs.umich.edu# the target(s).
3253483Ssaidi@eecs.umich.edu#
3263483Ssaidi@eecs.umich.edu###################################################
3273053Sstever@eecs.umich.edu
3283053Sstever@eecs.umich.edu# Find default configuration & binary.
3293918Ssaidi@eecs.umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
3303053Sstever@eecs.umich.edu
3313053Sstever@eecs.umich.edu# helper function: find last occurrence of element in list
3323053Sstever@eecs.umich.edudef rfind(l, elt, offs = -1):
3333053Sstever@eecs.umich.edu    for i in range(len(l)+offs, 0, -1):
3343053Sstever@eecs.umich.edu        if l[i] == elt:
3351858SN/A            return i
3361858SN/A    raise ValueError, "element not found"
3371858SN/A
3381858SN/A# Take a list of paths (or SCons Nodes) and return a list with all
3391858SN/A# paths made absolute and ~-expanded.  Paths will be interpreted
3401858SN/A# relative to the launch directory unless a different root is provided
3411859SN/Adef makePathListAbsolute(path_list, root=GetLaunchDir()):
3421858SN/A    return [abspath(joinpath(root, expanduser(str(p))))
3431858SN/A            for p in path_list]
3441858SN/A
3451859SN/A# Each target must have 'build' in the interior of the path; the
3461859SN/A# directory below this will determine the build parameters.  For
3471862SN/A# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3483053Sstever@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
3493053Sstever@eecs.umich.edu# follow 'build' in the build path.
3503053Sstever@eecs.umich.edu
3513053Sstever@eecs.umich.edu# The funky assignment to "[:]" is needed to replace the list contents
3521859SN/A# in place rather than reassign the symbol to a new list, which
3531859SN/A# doesn't work (obviously!).
3541859SN/ABUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3551859SN/A
3561859SN/A# Generate a list of the unique build roots and configs that the
3571859SN/A# collected targets reference.
3581859SN/Avariant_paths = []
3591859SN/Abuild_root = None
3601862SN/Afor t in BUILD_TARGETS:
3611859SN/A    path_dirs = t.split('/')
3621859SN/A    try:
3631859SN/A        build_top = rfind(path_dirs, 'build', -2)
3641858SN/A    except:
3651858SN/A        print "Error: no non-leaf 'build' dir found on target path", t
3662139SN/A        Exit(1)
3674202Sbinkertn@umich.edu    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3684202Sbinkertn@umich.edu    if not build_root:
3692139SN/A        build_root = this_build_root
3702155SN/A    else:
3714202Sbinkertn@umich.edu        if this_build_root != build_root:
3724202Sbinkertn@umich.edu            print "Error: build targets not under same build root\n"\
3734202Sbinkertn@umich.edu                  "  %s\n  %s" % (build_root, this_build_root)
3742155SN/A            Exit(1)
3751869SN/A    variant_path = joinpath('/',*path_dirs[:build_top+2])
3761869SN/A    if variant_path not in variant_paths:
3771869SN/A        variant_paths.append(variant_path)
3781869SN/A
3794202Sbinkertn@umich.edu# Make sure build_root exists (might not if this is the first build there)
3804202Sbinkertn@umich.eduif not isdir(build_root):
3814202Sbinkertn@umich.edu    mkdir(build_root)
3824202Sbinkertn@umich.edumain['BUILDROOT'] = build_root
3834202Sbinkertn@umich.edu
3844202Sbinkertn@umich.eduExport('main')
3854202Sbinkertn@umich.edu
3864202Sbinkertn@umich.edumain.SConsignFile(joinpath(build_root, "sconsign"))
3874202Sbinkertn@umich.edu
3884202Sbinkertn@umich.edu# Default duplicate option is to use hard links, but this messes up
3894202Sbinkertn@umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
3904202Sbinkertn@umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
3914202Sbinkertn@umich.edu# (soft) links work better.
3924202Sbinkertn@umich.edumain.SetOption('duplicate', 'soft-copy')
3934202Sbinkertn@umich.edu
3944202Sbinkertn@umich.edu#
3951869SN/A# Set up global sticky variables... these are common to an entire build
3964202Sbinkertn@umich.edu# tree (not specific to a particular build like ALPHA_SE)
3971869SN/A#
3982508SN/A
3992508SN/Aglobal_vars_file = joinpath(build_root, 'variables.global')
4002508SN/A
4012508SN/Aglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
4024202Sbinkertn@umich.edu
4031869SN/Aglobal_vars.AddVariables(
4041869SN/A    ('CC', 'C compiler', environ.get('CC', main['CC'])),
4051869SN/A    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
4061869SN/A    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
4071869SN/A    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
4081869SN/A    ('BATCH', 'Use batch pool for build and tests', False),
4091965SN/A    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
4101965SN/A    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
4111965SN/A    ('EXTRAS', 'Add extra directories to the compilation', '')
4121869SN/A    )
4131869SN/A
4142733Sktlim@umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
4151869SN/Aglobal_vars.Update(main)
4161884SN/Ahelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
4171884SN/A
4183356Sbinkertn@umich.edu# Save sticky variable settings back to current variables file
4193356Sbinkertn@umich.eduglobal_vars.Save(global_vars_file, main)
4203356Sbinkertn@umich.edu
4213356Sbinkertn@umich.edu# Parse EXTRAS variable to build list of all directories where we're
4221869SN/A# look for sources etc.  This list is exported as extras_dir_list.
4231858SN/Abase_dir = main.srcdir.abspath
4241869SN/Aif main['EXTRAS']:
4251869SN/A    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
4261869SN/Aelse:
4271858SN/A    extras_dir_list = []
4282761Sstever@eecs.umich.edu
4291869SN/AExport('base_dir')
4302733Sktlim@umich.eduExport('extras_dir_list')
4313584Ssaidi@eecs.umich.edu
4321869SN/A# the ext directory should be on the #includes path
4331869SN/Amain.Append(CPPPATH=[Dir('ext')])
4341869SN/A
4351869SN/Adef strip_build_path(path, env):
4361869SN/A    path = str(path)
4371869SN/A    variant_base = env['BUILDROOT'] + os.path.sep
4381858SN/A    if path.startswith(variant_base):
439955SN/A        path = path[len(variant_base):]
440955SN/A    elif path.startswith('build/'):
4411869SN/A        path = path[6:]
4421869SN/A    return path
4431869SN/A
4441869SN/A# Generate a string of the form:
4451869SN/A#   common/path/prefix/src1, src2 -> tgt1, tgt2
4461869SN/A# to print while building.
4471869SN/Aclass Transform(object):
4481869SN/A    # all specific color settings should be here and nowhere else
4491869SN/A    tool_color = termcap.Normal
4501869SN/A    pfx_color = termcap.Yellow
4511869SN/A    srcs_color = termcap.Yellow + termcap.Bold
4521869SN/A    arrow_color = termcap.Blue + termcap.Bold
4531869SN/A    tgts_color = termcap.Yellow + termcap.Bold
4541869SN/A
4551869SN/A    def __init__(self, tool, max_sources=99):
4561869SN/A        self.format = self.tool_color + (" [%8s] " % tool) \
4571869SN/A                      + self.pfx_color + "%s" \
4581869SN/A                      + self.srcs_color + "%s" \
4591869SN/A                      + self.arrow_color + " -> " \
4601869SN/A                      + self.tgts_color + "%s" \
4611869SN/A                      + termcap.Normal
4621869SN/A        self.max_sources = max_sources
4631869SN/A
4641869SN/A    def __call__(self, target, source, env, for_signature=None):
4651869SN/A        # truncate source list according to max_sources param
4661869SN/A        source = source[0:self.max_sources]
4671869SN/A        def strip(f):
4681869SN/A            return strip_build_path(str(f), env)
4691869SN/A        if len(source) > 0:
4703716Sstever@eecs.umich.edu            srcs = map(strip, source)
4713356Sbinkertn@umich.edu        else:
4723356Sbinkertn@umich.edu            srcs = ['']
4733356Sbinkertn@umich.edu        tgts = map(strip, target)
4743356Sbinkertn@umich.edu        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4753356Sbinkertn@umich.edu        # operation that has nothing to do with paths.
4763356Sbinkertn@umich.edu        com_pfx = os.path.commonprefix(srcs + tgts)
4773356Sbinkertn@umich.edu        com_pfx_len = len(com_pfx)
4781869SN/A        if com_pfx:
4791869SN/A            # do some cleanup and sanity checking on common prefix
4801869SN/A            if com_pfx[-1] == ".":
4811869SN/A                # prefix matches all but file extension: ok
4821869SN/A                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4831869SN/A                com_pfx = com_pfx[0:-1]
4841869SN/A            elif com_pfx[-1] == "/":
4852655Sstever@eecs.umich.edu                # common prefix is directory path: OK
4862655Sstever@eecs.umich.edu                pass
4872655Sstever@eecs.umich.edu            else:
4882655Sstever@eecs.umich.edu                src0_len = len(srcs[0])
4892655Sstever@eecs.umich.edu                tgt0_len = len(tgts[0])
4902655Sstever@eecs.umich.edu                if src0_len == com_pfx_len:
4912655Sstever@eecs.umich.edu                    # source is a substring of target, OK
4922655Sstever@eecs.umich.edu                    pass
4932655Sstever@eecs.umich.edu                elif tgt0_len == com_pfx_len:
4942655Sstever@eecs.umich.edu                    # target is a substring of source, need to back up to
4952655Sstever@eecs.umich.edu                    # avoid empty string on RHS of arrow
4962655Sstever@eecs.umich.edu                    sep_idx = com_pfx.rfind(".")
4972655Sstever@eecs.umich.edu                    if sep_idx != -1:
4982655Sstever@eecs.umich.edu                        com_pfx = com_pfx[0:sep_idx]
4992655Sstever@eecs.umich.edu                    else:
5002655Sstever@eecs.umich.edu                        com_pfx = ''
5012655Sstever@eecs.umich.edu                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
5022655Sstever@eecs.umich.edu                    # still splitting at file extension: ok
5032655Sstever@eecs.umich.edu                    pass
5042655Sstever@eecs.umich.edu                else:
5052655Sstever@eecs.umich.edu                    # probably a fluke; ignore it
5062655Sstever@eecs.umich.edu                    com_pfx = ''
5072655Sstever@eecs.umich.edu        # recalculate length in case com_pfx was modified
5082655Sstever@eecs.umich.edu        com_pfx_len = len(com_pfx)
5092655Sstever@eecs.umich.edu        def fmt(files):
5102655Sstever@eecs.umich.edu            f = map(lambda s: s[com_pfx_len:], files)
5112634Sstever@eecs.umich.edu            return ', '.join(f)
5122634Sstever@eecs.umich.edu        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
5132634Sstever@eecs.umich.edu
5142634Sstever@eecs.umich.eduExport('Transform')
5152634Sstever@eecs.umich.edu
5162634Sstever@eecs.umich.edu# enable the regression script to use the termcap
5172638Sstever@eecs.umich.edumain['TERMCAP'] = termcap
5182638Sstever@eecs.umich.edu
5193716Sstever@eecs.umich.eduif GetOption('verbose'):
5202638Sstever@eecs.umich.edu    def MakeAction(action, string, *args, **kwargs):
5212638Sstever@eecs.umich.edu        return Action(action, *args, **kwargs)
5221869SN/Aelse:
5231869SN/A    MakeAction = Action
5243546Sgblack@eecs.umich.edu    main['CCCOMSTR']        = Transform("CC")
5253546Sgblack@eecs.umich.edu    main['CXXCOMSTR']       = Transform("CXX")
5263546Sgblack@eecs.umich.edu    main['ASCOMSTR']        = Transform("AS")
5273546Sgblack@eecs.umich.edu    main['SWIGCOMSTR']      = Transform("SWIG")
5284202Sbinkertn@umich.edu    main['ARCOMSTR']        = Transform("AR", 0)
5293546Sgblack@eecs.umich.edu    main['LINKCOMSTR']      = Transform("LINK", 0)
5303546Sgblack@eecs.umich.edu    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
5313546Sgblack@eecs.umich.edu    main['M4COMSTR']        = Transform("M4")
5323546Sgblack@eecs.umich.edu    main['SHCCCOMSTR']      = Transform("SHCC")
5333546Sgblack@eecs.umich.edu    main['SHCXXCOMSTR']     = Transform("SHCXX")
5343546Sgblack@eecs.umich.eduExport('MakeAction')
5353546Sgblack@eecs.umich.edu
5363546Sgblack@eecs.umich.edu# Initialize the Link-Time Optimization (LTO) flags
5373546Sgblack@eecs.umich.edumain['LTO_CCFLAGS'] = []
5383546Sgblack@eecs.umich.edumain['LTO_LDFLAGS'] = []
5394202Sbinkertn@umich.edu
5403546Sgblack@eecs.umich.edu# According to the readme, tcmalloc works best if the compiler doesn't
5413546Sgblack@eecs.umich.edu# assume that we're using the builtin malloc and friends. These flags
5423546Sgblack@eecs.umich.edu# are compiler-specific, so we need to set them after we detect which
5433546Sgblack@eecs.umich.edu# compiler we're using.
5443546Sgblack@eecs.umich.edumain['TCMALLOC_CCFLAGS'] = []
5453546Sgblack@eecs.umich.edu
5463546Sgblack@eecs.umich.eduCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5473546Sgblack@eecs.umich.eduCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5483546Sgblack@eecs.umich.edu
5493546Sgblack@eecs.umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5503546Sgblack@eecs.umich.edumain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5513546Sgblack@eecs.umich.eduif main['GCC'] + main['CLANG'] > 1:
5523546Sgblack@eecs.umich.edu    print 'Error: How can we have two at the same time?'
5533546Sgblack@eecs.umich.edu    Exit(1)
5543546Sgblack@eecs.umich.edu
5553546Sgblack@eecs.umich.edu# Set up default C++ compiler flags
5563546Sgblack@eecs.umich.eduif main['GCC'] or main['CLANG']:
5573546Sgblack@eecs.umich.edu    # As gcc and clang share many flags, do the common parts here
5583546Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-pipe'])
5593546Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5604202Sbinkertn@umich.edu    # Enable -Wall and -Wextra and then disable the few warnings that
5613546Sgblack@eecs.umich.edu    # we consistently violate
5623546Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
5633546Sgblack@eecs.umich.edu                         '-Wno-sign-compare', '-Wno-unused-parameter'])
564955SN/A    # We always compile using C++11
565955SN/A    main.Append(CXXFLAGS=['-std=c++11'])
566955SN/Aelse:
567955SN/A    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5681858SN/A    print "Don't know what compiler options to use for your compiler."
5691858SN/A    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5701858SN/A    print termcap.Yellow + '       version:' + termcap.Normal,
5712632Sstever@eecs.umich.edu    if not CXX_version:
5722632Sstever@eecs.umich.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5732632Sstever@eecs.umich.edu               termcap.Normal
5742632Sstever@eecs.umich.edu    else:
5752632Sstever@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
5762634Sstever@eecs.umich.edu    print "       If you're trying to use a compiler other than GCC"
5772638Sstever@eecs.umich.edu    print "       or clang, there appears to be something wrong with your"
5782023SN/A    print "       environment."
5792632Sstever@eecs.umich.edu    print "       "
5802632Sstever@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
5812632Sstever@eecs.umich.edu    print "       above you will need to ease fix SConstruct and "
5822632Sstever@eecs.umich.edu    print "       src/SConscript to support that compiler."
5832632Sstever@eecs.umich.edu    Exit(1)
5843716Sstever@eecs.umich.edu
5852632Sstever@eecs.umich.eduif main['GCC']:
5862632Sstever@eecs.umich.edu    # Check for a supported version of gcc. >= 4.7 is chosen for its
5872632Sstever@eecs.umich.edu    # level of c++11 support. See
5882632Sstever@eecs.umich.edu    # http://gcc.gnu.org/projects/cxx0x.html for details.
5892632Sstever@eecs.umich.edu    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5902023SN/A    if compareVersions(gcc_version, "4.7") < 0:
5912632Sstever@eecs.umich.edu        print 'Error: gcc version 4.7 or newer required.'
5922632Sstever@eecs.umich.edu        print '       Installed version:', gcc_version
5931889SN/A        Exit(1)
5941889SN/A
5952632Sstever@eecs.umich.edu    main['GCC_VERSION'] = gcc_version
5962632Sstever@eecs.umich.edu
5972632Sstever@eecs.umich.edu    # gcc from version 4.8 and above generates "rep; ret" instructions
5982632Sstever@eecs.umich.edu    # to avoid performance penalties on certain AMD chips. Older
5993716Sstever@eecs.umich.edu    # assemblers detect this as an error, "Error: expecting string
6003716Sstever@eecs.umich.edu    # instruction after `rep'"
6012632Sstever@eecs.umich.edu    if compareVersions(gcc_version, "4.8") > 0:
6022632Sstever@eecs.umich.edu        as_version_raw = readCommand([main['AS'], '-v', '/dev/null'],
6032632Sstever@eecs.umich.edu                                     exception=False).split()
6042632Sstever@eecs.umich.edu
6052632Sstever@eecs.umich.edu        # version strings may contain extra distro-specific
6062632Sstever@eecs.umich.edu        # qualifiers, so play it safe and keep only what comes before
6072632Sstever@eecs.umich.edu        # the first hyphen
6082632Sstever@eecs.umich.edu        as_version = as_version_raw[-1].split('-')[0] if as_version_raw \
6091888SN/A            else None
6101888SN/A
6111869SN/A        if not as_version or compareVersions(as_version, "2.23") < 0:
6121869SN/A            print termcap.Yellow + termcap.Bold + \
6131858SN/A                'Warning: This combination of gcc and binutils have' + \
6142598SN/A                ' known incompatibilities.\n' + \
6152598SN/A                '         If you encounter build problems, please update ' + \
6162598SN/A                'binutils to 2.23.' + \
6172598SN/A                termcap.Normal
6182598SN/A
6191858SN/A    # Make sure we warn if the user has requested to compile with the
6201858SN/A    # Undefined Benahvior Sanitizer and this version of gcc does not
6211858SN/A    # support it.
6221858SN/A    if GetOption('with_ubsan') and \
6231858SN/A            compareVersions(gcc_version, '4.9') < 0:
6241858SN/A        print termcap.Yellow + termcap.Bold + \
6251858SN/A            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
6261858SN/A            termcap.Normal
6271858SN/A
6281871SN/A    # Add the appropriate Link-Time Optimization (LTO) flags
6291858SN/A    # unless LTO is explicitly turned off. Note that these flags
6301858SN/A    # are only used by the fast target.
6311858SN/A    if not GetOption('no_lto'):
6321858SN/A        # Pass the LTO flag when compiling to produce GIMPLE
6331858SN/A        # output, we merely create the flags here and only append
6341858SN/A        # them later
6351858SN/A        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
6361858SN/A
6371858SN/A        # Use the same amount of jobs for LTO as we are running
6381858SN/A        # scons with
6391858SN/A        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
6401859SN/A
6411859SN/A    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
6421869SN/A                                  '-fno-builtin-realloc', '-fno-builtin-free'])
6431888SN/A
6442632Sstever@eecs.umich.eduelif main['CLANG']:
6451869SN/A    # Check for a supported version of clang, >= 3.1 is needed to
6461884SN/A    # support similar features as gcc 4.7. See
6471884SN/A    # http://clang.llvm.org/cxx_status.html for details
6481884SN/A    clang_version_re = re.compile(".* version (\d+\.\d+)")
6491884SN/A    clang_version_match = clang_version_re.search(CXX_version)
6501884SN/A    if (clang_version_match):
6511884SN/A        clang_version = clang_version_match.groups()[0]
6521965SN/A        if compareVersions(clang_version, "3.1") < 0:
6531965SN/A            print 'Error: clang version 3.1 or newer required.'
6541965SN/A            print '       Installed version:', clang_version
6552761Sstever@eecs.umich.edu            Exit(1)
6561869SN/A    else:
6571869SN/A        print 'Error: Unable to determine clang version.'
6582632Sstever@eecs.umich.edu        Exit(1)
6592667Sstever@eecs.umich.edu
6601869SN/A    # clang has a few additional warnings that we disable, extraneous
6611869SN/A    # parantheses are allowed due to Ruby's printing of the AST,
6622929Sktlim@umich.edu    # finally self assignments are allowed as the generated CPU code
6632929Sktlim@umich.edu    # is relying on this
6643716Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wno-parentheses',
6652929Sktlim@umich.edu                         '-Wno-self-assign',
666955SN/A                         # Some versions of libstdc++ (4.8?) seem to
6672598SN/A                         # use struct hash and class hash
6682598SN/A                         # interchangeably.
6693546Sgblack@eecs.umich.edu                         '-Wno-mismatched-tags',
670955SN/A                         ])
671955SN/A
672955SN/A    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
6731530SN/A
674955SN/A    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
675955SN/A    # opposed to libstdc++, as the later is dated.
676955SN/A    if sys.platform == "darwin":
677        main.Append(CXXFLAGS=['-stdlib=libc++'])
678        main.Append(LIBS=['c++'])
679
680else:
681    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
682    print "Don't know what compiler options to use for your compiler."
683    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
684    print termcap.Yellow + '       version:' + termcap.Normal,
685    if not CXX_version:
686        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
687               termcap.Normal
688    else:
689        print CXX_version.replace('\n', '<nl>')
690    print "       If you're trying to use a compiler other than GCC"
691    print "       or clang, there appears to be something wrong with your"
692    print "       environment."
693    print "       "
694    print "       If you are trying to use a compiler other than those listed"
695    print "       above you will need to ease fix SConstruct and "
696    print "       src/SConscript to support that compiler."
697    Exit(1)
698
699# Set up common yacc/bison flags (needed for Ruby)
700main['YACCFLAGS'] = '-d'
701main['YACCHXXFILESUFFIX'] = '.hh'
702
703# Do this after we save setting back, or else we'll tack on an
704# extra 'qdo' every time we run scons.
705if main['BATCH']:
706    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
707    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
708    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
709    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
710    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
711
712if sys.platform == 'cygwin':
713    # cygwin has some header file issues...
714    main.Append(CCFLAGS=["-Wno-uninitialized"])
715
716# Check for the protobuf compiler
717protoc_version = readCommand([main['PROTOC'], '--version'],
718                             exception='').split()
719
720# First two words should be "libprotoc x.y.z"
721if len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
722    print termcap.Yellow + termcap.Bold + \
723        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
724        '         Please install protobuf-compiler for tracing support.' + \
725        termcap.Normal
726    main['PROTOC'] = False
727else:
728    # Based on the availability of the compress stream wrappers,
729    # require 2.1.0
730    min_protoc_version = '2.1.0'
731    if compareVersions(protoc_version[1], min_protoc_version) < 0:
732        print termcap.Yellow + termcap.Bold + \
733            'Warning: protoc version', min_protoc_version, \
734            'or newer required.\n' + \
735            '         Installed version:', protoc_version[1], \
736            termcap.Normal
737        main['PROTOC'] = False
738    else:
739        # Attempt to determine the appropriate include path and
740        # library path using pkg-config, that means we also need to
741        # check for pkg-config. Note that it is possible to use
742        # protobuf without the involvement of pkg-config. Later on we
743        # check go a library config check and at that point the test
744        # will fail if libprotobuf cannot be found.
745        if readCommand(['pkg-config', '--version'], exception=''):
746            try:
747                # Attempt to establish what linking flags to add for protobuf
748                # using pkg-config
749                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
750            except:
751                print termcap.Yellow + termcap.Bold + \
752                    'Warning: pkg-config could not get protobuf flags.' + \
753                    termcap.Normal
754
755# Check for SWIG
756if not main.has_key('SWIG'):
757    print 'Error: SWIG utility not found.'
758    print '       Please install (see http://www.swig.org) and retry.'
759    Exit(1)
760
761# Check for appropriate SWIG version
762swig_version = readCommand([main['SWIG'], '-version'], exception='').split()
763# First 3 words should be "SWIG Version x.y.z"
764if len(swig_version) < 3 or \
765        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
766    print 'Error determining SWIG version.'
767    Exit(1)
768
769min_swig_version = '2.0.4'
770if compareVersions(swig_version[2], min_swig_version) < 0:
771    print 'Error: SWIG version', min_swig_version, 'or newer required.'
772    print '       Installed version:', swig_version[2]
773    Exit(1)
774
775# Check for known incompatibilities. The standard library shipped with
776# gcc >= 4.9 does not play well with swig versions prior to 3.0
777if main['GCC'] and compareVersions(gcc_version, '4.9') >= 0 and \
778        compareVersions(swig_version[2], '3.0') < 0:
779    print termcap.Yellow + termcap.Bold + \
780        'Warning: This combination of gcc and swig have' + \
781        ' known incompatibilities.\n' + \
782        '         If you encounter build problems, please update ' + \
783        'swig to 3.0 or later.' + \
784        termcap.Normal
785
786# Set up SWIG flags & scanner
787swig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
788main.Append(SWIGFLAGS=swig_flags)
789
790# Check for 'timeout' from GNU coreutils. If present, regressions will
791# be run with a time limit. We require version 8.13 since we rely on
792# support for the '--foreground' option.
793timeout_lines = readCommand(['timeout', '--version'],
794                            exception='').splitlines()
795# Get the first line and tokenize it
796timeout_version = timeout_lines[0].split() if timeout_lines else []
797main['TIMEOUT'] =  timeout_version and \
798    compareVersions(timeout_version[-1], '8.13') >= 0
799
800# filter out all existing swig scanners, they mess up the dependency
801# stuff for some reason
802scanners = []
803for scanner in main['SCANNERS']:
804    skeys = scanner.skeys
805    if skeys == '.i':
806        continue
807
808    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
809        continue
810
811    scanners.append(scanner)
812
813# add the new swig scanner that we like better
814from SCons.Scanner import ClassicCPP as CPPScanner
815swig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
816scanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
817
818# replace the scanners list that has what we want
819main['SCANNERS'] = scanners
820
821# Add a custom Check function to test for structure members.
822def CheckMember(context, include, decl, member, include_quotes="<>"):
823    context.Message("Checking for member %s in %s..." %
824                    (member, decl))
825    text = """
826#include %(header)s
827int main(){
828  %(decl)s test;
829  (void)test.%(member)s;
830  return 0;
831};
832""" % { "header" : include_quotes[0] + include + include_quotes[1],
833        "decl" : decl,
834        "member" : member,
835        }
836
837    ret = context.TryCompile(text, extension=".cc")
838    context.Result(ret)
839    return ret
840
841# Platform-specific configuration.  Note again that we assume that all
842# builds under a given build root run on the same host platform.
843conf = Configure(main,
844                 conf_dir = joinpath(build_root, '.scons_config'),
845                 log_file = joinpath(build_root, 'scons_config.log'),
846                 custom_tests = {
847        'CheckMember' : CheckMember,
848        })
849
850# Check if we should compile a 64 bit binary on Mac OS X/Darwin
851try:
852    import platform
853    uname = platform.uname()
854    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
855        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
856            main.Append(CCFLAGS=['-arch', 'x86_64'])
857            main.Append(CFLAGS=['-arch', 'x86_64'])
858            main.Append(LINKFLAGS=['-arch', 'x86_64'])
859            main.Append(ASFLAGS=['-arch', 'x86_64'])
860except:
861    pass
862
863# Recent versions of scons substitute a "Null" object for Configure()
864# when configuration isn't necessary, e.g., if the "--help" option is
865# present.  Unfortuantely this Null object always returns false,
866# breaking all our configuration checks.  We replace it with our own
867# more optimistic null object that returns True instead.
868if not conf:
869    def NullCheck(*args, **kwargs):
870        return True
871
872    class NullConf:
873        def __init__(self, env):
874            self.env = env
875        def Finish(self):
876            return self.env
877        def __getattr__(self, mname):
878            return NullCheck
879
880    conf = NullConf(main)
881
882# Cache build files in the supplied directory.
883if main['M5_BUILD_CACHE']:
884    print 'Using build cache located at', main['M5_BUILD_CACHE']
885    CacheDir(main['M5_BUILD_CACHE'])
886
887if not GetOption('without_python'):
888    # Find Python include and library directories for embedding the
889    # interpreter. We rely on python-config to resolve the appropriate
890    # includes and linker flags. ParseConfig does not seem to understand
891    # the more exotic linker flags such as -Xlinker and -export-dynamic so
892    # we add them explicitly below. If you want to link in an alternate
893    # version of python, see above for instructions on how to invoke
894    # scons with the appropriate PATH set.
895    #
896    # First we check if python2-config exists, else we use python-config
897    python_config = readCommand(['which', 'python2-config'],
898                                exception='').strip()
899    if not os.path.exists(python_config):
900        python_config = readCommand(['which', 'python-config'],
901                                    exception='').strip()
902    py_includes = readCommand([python_config, '--includes'],
903                              exception='').split()
904    # Strip the -I from the include folders before adding them to the
905    # CPPPATH
906    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
907
908    # Read the linker flags and split them into libraries and other link
909    # flags. The libraries are added later through the call the CheckLib.
910    py_ld_flags = readCommand([python_config, '--ldflags'],
911        exception='').split()
912    py_libs = []
913    for lib in py_ld_flags:
914         if not lib.startswith('-l'):
915             main.Append(LINKFLAGS=[lib])
916         else:
917             lib = lib[2:]
918             if lib not in py_libs:
919                 py_libs.append(lib)
920
921    # verify that this stuff works
922    if not conf.CheckHeader('Python.h', '<>'):
923        print "Error: can't find Python.h header in", py_includes
924        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
925        Exit(1)
926
927    for lib in py_libs:
928        if not conf.CheckLib(lib):
929            print "Error: can't find library %s required by python" % lib
930            Exit(1)
931
932# On Solaris you need to use libsocket for socket ops
933if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
934   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
935       print "Can't find library with socket calls (e.g. accept())"
936       Exit(1)
937
938# Check for zlib.  If the check passes, libz will be automatically
939# added to the LIBS environment variable.
940if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
941    print 'Error: did not find needed zlib compression library '\
942          'and/or zlib.h header file.'
943    print '       Please install zlib and try again.'
944    Exit(1)
945
946# If we have the protobuf compiler, also make sure we have the
947# development libraries. If the check passes, libprotobuf will be
948# automatically added to the LIBS environment variable. After
949# this, we can use the HAVE_PROTOBUF flag to determine if we have
950# got both protoc and libprotobuf available.
951main['HAVE_PROTOBUF'] = main['PROTOC'] and \
952    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
953                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
954
955# If we have the compiler but not the library, print another warning.
956if main['PROTOC'] and not main['HAVE_PROTOBUF']:
957    print termcap.Yellow + termcap.Bold + \
958        'Warning: did not find protocol buffer library and/or headers.\n' + \
959    '       Please install libprotobuf-dev for tracing support.' + \
960    termcap.Normal
961
962# Check for librt.
963have_posix_clock = \
964    conf.CheckLibWithHeader(None, 'time.h', 'C',
965                            'clock_nanosleep(0,0,NULL,NULL);') or \
966    conf.CheckLibWithHeader('rt', 'time.h', 'C',
967                            'clock_nanosleep(0,0,NULL,NULL);')
968
969have_posix_timers = \
970    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
971                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
972
973if not GetOption('without_tcmalloc'):
974    if conf.CheckLib('tcmalloc'):
975        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
976    elif conf.CheckLib('tcmalloc_minimal'):
977        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
978    else:
979        print termcap.Yellow + termcap.Bold + \
980              "You can get a 12% performance improvement by "\
981              "installing tcmalloc (libgoogle-perftools-dev package "\
982              "on Ubuntu or RedHat)." + termcap.Normal
983
984
985# Detect back trace implementations. The last implementation in the
986# list will be used by default.
987backtrace_impls = [ "none" ]
988
989if conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
990                           'backtrace_symbols_fd((void*)0, 0, 0);'):
991    backtrace_impls.append("glibc")
992
993if backtrace_impls[-1] == "none":
994    default_backtrace_impl = "none"
995    print termcap.Yellow + termcap.Bold + \
996        "No suitable back trace implementation found." + \
997        termcap.Normal
998
999if not have_posix_clock:
1000    print "Can't find library for POSIX clocks."
1001
1002# Check for <fenv.h> (C99 FP environment control)
1003have_fenv = conf.CheckHeader('fenv.h', '<>')
1004if not have_fenv:
1005    print "Warning: Header file <fenv.h> not found."
1006    print "         This host has no IEEE FP rounding mode control."
1007
1008# Check if we should enable KVM-based hardware virtualization. The API
1009# we rely on exists since version 2.6.36 of the kernel, but somehow
1010# the KVM_API_VERSION does not reflect the change. We test for one of
1011# the types as a fall back.
1012have_kvm = conf.CheckHeader('linux/kvm.h', '<>')
1013if not have_kvm:
1014    print "Info: Compatible header file <linux/kvm.h> not found, " \
1015        "disabling KVM support."
1016
1017# x86 needs support for xsave. We test for the structure here since we
1018# won't be able to run new tests by the time we know which ISA we're
1019# targeting.
1020have_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
1021                                    '#include <linux/kvm.h>') != 0
1022
1023# Check if the requested target ISA is compatible with the host
1024def is_isa_kvm_compatible(isa):
1025    try:
1026        import platform
1027        host_isa = platform.machine()
1028    except:
1029        print "Warning: Failed to determine host ISA."
1030        return False
1031
1032    if not have_posix_timers:
1033        print "Warning: Can not enable KVM, host seems to lack support " \
1034            "for POSIX timers"
1035        return False
1036
1037    if isa == "arm":
1038        return host_isa in ( "armv7l", "aarch64" )
1039    elif isa == "x86":
1040        if host_isa != "x86_64":
1041            return False
1042
1043        if not have_kvm_xsave:
1044            print "KVM on x86 requires xsave support in kernel headers."
1045            return False
1046
1047        return True
1048    else:
1049        return False
1050
1051
1052# Check if the exclude_host attribute is available. We want this to
1053# get accurate instruction counts in KVM.
1054main['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
1055    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
1056
1057
1058######################################################################
1059#
1060# Finish the configuration
1061#
1062main = conf.Finish()
1063
1064######################################################################
1065#
1066# Collect all non-global variables
1067#
1068
1069# Define the universe of supported ISAs
1070all_isa_list = [ ]
1071all_gpu_isa_list = [ ]
1072Export('all_isa_list')
1073Export('all_gpu_isa_list')
1074
1075class CpuModel(object):
1076    '''The CpuModel class encapsulates everything the ISA parser needs to
1077    know about a particular CPU model.'''
1078
1079    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
1080    dict = {}
1081
1082    # Constructor.  Automatically adds models to CpuModel.dict.
1083    def __init__(self, name, default=False):
1084        self.name = name           # name of model
1085
1086        # This cpu is enabled by default
1087        self.default = default
1088
1089        # Add self to dict
1090        if name in CpuModel.dict:
1091            raise AttributeError, "CpuModel '%s' already registered" % name
1092        CpuModel.dict[name] = self
1093
1094Export('CpuModel')
1095
1096# Sticky variables get saved in the variables file so they persist from
1097# one invocation to the next (unless overridden, in which case the new
1098# value becomes sticky).
1099sticky_vars = Variables(args=ARGUMENTS)
1100Export('sticky_vars')
1101
1102# Sticky variables that should be exported
1103export_vars = []
1104Export('export_vars')
1105
1106# For Ruby
1107all_protocols = []
1108Export('all_protocols')
1109protocol_dirs = []
1110Export('protocol_dirs')
1111slicc_includes = []
1112Export('slicc_includes')
1113
1114# Walk the tree and execute all SConsopts scripts that wil add to the
1115# above variables
1116if GetOption('verbose'):
1117    print "Reading SConsopts"
1118for bdir in [ base_dir ] + extras_dir_list:
1119    if not isdir(bdir):
1120        print "Error: directory '%s' does not exist" % bdir
1121        Exit(1)
1122    for root, dirs, files in os.walk(bdir):
1123        if 'SConsopts' in files:
1124            if GetOption('verbose'):
1125                print "Reading", joinpath(root, 'SConsopts')
1126            SConscript(joinpath(root, 'SConsopts'))
1127
1128all_isa_list.sort()
1129all_gpu_isa_list.sort()
1130
1131sticky_vars.AddVariables(
1132    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
1133    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
1134    ListVariable('CPU_MODELS', 'CPU models',
1135                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
1136                 sorted(CpuModel.dict.keys())),
1137    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
1138                 False),
1139    BoolVariable('SS_COMPATIBLE_FP',
1140                 'Make floating-point results compatible with SimpleScalar',
1141                 False),
1142    BoolVariable('USE_SSE2',
1143                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
1144                 False),
1145    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
1146    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
1147    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
1148    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
1149    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
1150    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1151                  all_protocols),
1152    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
1153                 backtrace_impls[-1], backtrace_impls)
1154    )
1155
1156# These variables get exported to #defines in config/*.hh (see src/SConscript).
1157export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
1158                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'PROTOCOL',
1159                'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST']
1160
1161###################################################
1162#
1163# Define a SCons builder for configuration flag headers.
1164#
1165###################################################
1166
1167# This function generates a config header file that #defines the
1168# variable symbol to the current variable setting (0 or 1).  The source
1169# operands are the name of the variable and a Value node containing the
1170# value of the variable.
1171def build_config_file(target, source, env):
1172    (variable, value) = [s.get_contents() for s in source]
1173    f = file(str(target[0]), 'w')
1174    print >> f, '#define', variable, value
1175    f.close()
1176    return None
1177
1178# Combine the two functions into a scons Action object.
1179config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1180
1181# The emitter munges the source & target node lists to reflect what
1182# we're really doing.
1183def config_emitter(target, source, env):
1184    # extract variable name from Builder arg
1185    variable = str(target[0])
1186    # True target is config header file
1187    target = joinpath('config', variable.lower() + '.hh')
1188    val = env[variable]
1189    if isinstance(val, bool):
1190        # Force value to 0/1
1191        val = int(val)
1192    elif isinstance(val, str):
1193        val = '"' + val + '"'
1194
1195    # Sources are variable name & value (packaged in SCons Value nodes)
1196    return ([target], [Value(variable), Value(val)])
1197
1198config_builder = Builder(emitter = config_emitter, action = config_action)
1199
1200main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1201
1202# libelf build is shared across all configs in the build root.
1203main.SConscript('ext/libelf/SConscript',
1204                variant_dir = joinpath(build_root, 'libelf'))
1205
1206# iostream3 build is shared across all configs in the build root.
1207main.SConscript('ext/iostream3/SConscript',
1208                variant_dir = joinpath(build_root, 'iostream3'))
1209
1210# libfdt build is shared across all configs in the build root.
1211main.SConscript('ext/libfdt/SConscript',
1212                variant_dir = joinpath(build_root, 'libfdt'))
1213
1214# fputils build is shared across all configs in the build root.
1215main.SConscript('ext/fputils/SConscript',
1216                variant_dir = joinpath(build_root, 'fputils'))
1217
1218# DRAMSim2 build is shared across all configs in the build root.
1219main.SConscript('ext/dramsim2/SConscript',
1220                variant_dir = joinpath(build_root, 'dramsim2'))
1221
1222# DRAMPower build is shared across all configs in the build root.
1223main.SConscript('ext/drampower/SConscript',
1224                variant_dir = joinpath(build_root, 'drampower'))
1225
1226# nomali build is shared across all configs in the build root.
1227main.SConscript('ext/nomali/SConscript',
1228                variant_dir = joinpath(build_root, 'nomali'))
1229
1230###################################################
1231#
1232# This function is used to set up a directory with switching headers
1233#
1234###################################################
1235
1236main['ALL_ISA_LIST'] = all_isa_list
1237main['ALL_GPU_ISA_LIST'] = all_gpu_isa_list
1238all_isa_deps = {}
1239def make_switching_dir(dname, switch_headers, env):
1240    # Generate the header.  target[0] is the full path of the output
1241    # header to generate.  'source' is a dummy variable, since we get the
1242    # list of ISAs from env['ALL_ISA_LIST'].
1243    def gen_switch_hdr(target, source, env):
1244        fname = str(target[0])
1245        isa = env['TARGET_ISA'].lower()
1246        try:
1247            f = open(fname, 'w')
1248            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1249            f.close()
1250        except IOError:
1251            print "Failed to create %s" % fname
1252            raise
1253
1254    # Build SCons Action object. 'varlist' specifies env vars that this
1255    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1256    # should get re-executed.
1257    switch_hdr_action = MakeAction(gen_switch_hdr,
1258                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1259
1260    # Instantiate actions for each header
1261    for hdr in switch_headers:
1262        env.Command(hdr, [], switch_hdr_action)
1263
1264    isa_target = Dir('.').up().name.lower().replace('_', '-')
1265    env['PHONY_BASE'] = '#'+isa_target
1266    all_isa_deps[isa_target] = None
1267
1268Export('make_switching_dir')
1269
1270def make_gpu_switching_dir(dname, switch_headers, env):
1271    # Generate the header.  target[0] is the full path of the output
1272    # header to generate.  'source' is a dummy variable, since we get the
1273    # list of ISAs from env['ALL_ISA_LIST'].
1274    def gen_switch_hdr(target, source, env):
1275        fname = str(target[0])
1276
1277        isa = env['TARGET_GPU_ISA'].lower()
1278
1279        try:
1280            f = open(fname, 'w')
1281            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1282            f.close()
1283        except IOError:
1284            print "Failed to create %s" % fname
1285            raise
1286
1287    # Build SCons Action object. 'varlist' specifies env vars that this
1288    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1289    # should get re-executed.
1290    switch_hdr_action = MakeAction(gen_switch_hdr,
1291                          Transform("GENERATE"), varlist=['ALL_ISA_GPU_LIST'])
1292
1293    # Instantiate actions for each header
1294    for hdr in switch_headers:
1295        env.Command(hdr, [], switch_hdr_action)
1296
1297Export('make_gpu_switching_dir')
1298
1299# all-isas -> all-deps -> all-environs -> all_targets
1300main.Alias('#all-isas', [])
1301main.Alias('#all-deps', '#all-isas')
1302
1303# Dummy target to ensure all environments are created before telling
1304# SCons what to actually make (the command line arguments).  We attach
1305# them to the dependence graph after the environments are complete.
1306ORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
1307def environsComplete(target, source, env):
1308    for t in ORIG_BUILD_TARGETS:
1309        main.Depends('#all-targets', t)
1310
1311# Each build/* switching_dir attaches its *-environs target to #all-environs.
1312main.Append(BUILDERS = {'CompleteEnvirons' :
1313                        Builder(action=MakeAction(environsComplete, None))})
1314main.CompleteEnvirons('#all-environs', [])
1315
1316def doNothing(**ignored): pass
1317main.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
1318
1319# The final target to which all the original targets ultimately get attached.
1320main.Dummy('#all-targets', '#all-environs')
1321BUILD_TARGETS[:] = ['#all-targets']
1322
1323###################################################
1324#
1325# Define build environments for selected configurations.
1326#
1327###################################################
1328
1329for variant_path in variant_paths:
1330    if not GetOption('silent'):
1331        print "Building in", variant_path
1332
1333    # Make a copy of the build-root environment to use for this config.
1334    env = main.Clone()
1335    env['BUILDDIR'] = variant_path
1336
1337    # variant_dir is the tail component of build path, and is used to
1338    # determine the build parameters (e.g., 'ALPHA_SE')
1339    (build_root, variant_dir) = splitpath(variant_path)
1340
1341    # Set env variables according to the build directory config.
1342    sticky_vars.files = []
1343    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1344    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1345    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1346    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1347    if isfile(current_vars_file):
1348        sticky_vars.files.append(current_vars_file)
1349        if not GetOption('silent'):
1350            print "Using saved variables file %s" % current_vars_file
1351    else:
1352        # Build dir-specific variables file doesn't exist.
1353
1354        # Make sure the directory is there so we can create it later
1355        opt_dir = dirname(current_vars_file)
1356        if not isdir(opt_dir):
1357            mkdir(opt_dir)
1358
1359        # Get default build variables from source tree.  Variables are
1360        # normally determined by name of $VARIANT_DIR, but can be
1361        # overridden by '--default=' arg on command line.
1362        default = GetOption('default')
1363        opts_dir = joinpath(main.root.abspath, 'build_opts')
1364        if default:
1365            default_vars_files = [joinpath(build_root, 'variables', default),
1366                                  joinpath(opts_dir, default)]
1367        else:
1368            default_vars_files = [joinpath(opts_dir, variant_dir)]
1369        existing_files = filter(isfile, default_vars_files)
1370        if existing_files:
1371            default_vars_file = existing_files[0]
1372            sticky_vars.files.append(default_vars_file)
1373            print "Variables file %s not found,\n  using defaults in %s" \
1374                  % (current_vars_file, default_vars_file)
1375        else:
1376            print "Error: cannot find variables file %s or " \
1377                  "default file(s) %s" \
1378                  % (current_vars_file, ' or '.join(default_vars_files))
1379            Exit(1)
1380
1381    # Apply current variable settings to env
1382    sticky_vars.Update(env)
1383
1384    help_texts["local_vars"] += \
1385        "Build variables for %s:\n" % variant_dir \
1386                 + sticky_vars.GenerateHelpText(env)
1387
1388    # Process variable settings.
1389
1390    if not have_fenv and env['USE_FENV']:
1391        print "Warning: <fenv.h> not available; " \
1392              "forcing USE_FENV to False in", variant_dir + "."
1393        env['USE_FENV'] = False
1394
1395    if not env['USE_FENV']:
1396        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1397        print "         FP results may deviate slightly from other platforms."
1398
1399    if env['EFENCE']:
1400        env.Append(LIBS=['efence'])
1401
1402    if env['USE_KVM']:
1403        if not have_kvm:
1404            print "Warning: Can not enable KVM, host seems to lack KVM support"
1405            env['USE_KVM'] = False
1406        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1407            print "Info: KVM support disabled due to unsupported host and " \
1408                "target ISA combination"
1409            env['USE_KVM'] = False
1410
1411    # Warn about missing optional functionality
1412    if env['USE_KVM']:
1413        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1414            print "Warning: perf_event headers lack support for the " \
1415                "exclude_host attribute. KVM instruction counts will " \
1416                "be inaccurate."
1417
1418    # Save sticky variable settings back to current variables file
1419    sticky_vars.Save(current_vars_file, env)
1420
1421    if env['USE_SSE2']:
1422        env.Append(CCFLAGS=['-msse2'])
1423
1424    # The src/SConscript file sets up the build rules in 'env' according
1425    # to the configured variables.  It returns a list of environments,
1426    # one for each variant build (debug, opt, etc.)
1427    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1428
1429def pairwise(iterable):
1430    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1431    a, b = itertools.tee(iterable)
1432    b.next()
1433    return itertools.izip(a, b)
1434
1435# Create false dependencies so SCons will parse ISAs, establish
1436# dependencies, and setup the build Environments serially. Either
1437# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1438# greater than 1. It appears to be standard race condition stuff; it
1439# doesn't always fail, but usually, and the behaviors are different.
1440# Every time I tried to remove this, builds would fail in some
1441# creative new way. So, don't do that. You'll want to, though, because
1442# tests/SConscript takes a long time to make its Environments.
1443for t1, t2 in pairwise(sorted(all_isa_deps.iterkeys())):
1444    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1445    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1446
1447# base help text
1448Help('''
1449Usage: scons [scons options] [build variables] [target(s)]
1450
1451Extra scons options:
1452%(options)s
1453
1454Global build variables:
1455%(global_vars)s
1456
1457%(local_vars)s
1458''' % help_texts)
1459