SConstruct revision 13713
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2013, 2015-2017 ARM Limited
4955SN/A# All rights reserved.
5955SN/A#
6955SN/A# The license below extends only to copyright in the software and shall
7955SN/A# not be construed as granting a license to any other intellectual
8955SN/A# property including but not limited to intellectual property relating
9955SN/A# to a hardware implementation of the functionality of the software
10955SN/A# licensed hereunder.  You may use the software subject to the license
11955SN/A# terms below provided that you ensure that this notice is replicated
12955SN/A# unmodified and in its entirety in all distributions of the software,
13955SN/A# modified or unmodified, in source code or in binary form.
14955SN/A#
15955SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
16955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
17955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
18955SN/A# All rights reserved.
19955SN/A#
20955SN/A# Redistribution and use in source and binary forms, with or without
21955SN/A# modification, are permitted provided that the following conditions are
22955SN/A# met: redistributions of source code must retain the above copyright
23955SN/A# notice, this list of conditions and the following disclaimer;
24955SN/A# redistributions in binary form must reproduce the above copyright
25955SN/A# notice, this list of conditions and the following disclaimer in the
26955SN/A# documentation and/or other materials provided with the distribution;
27955SN/A# neither the name of the copyright holders nor the names of its
282665Ssaidi@eecs.umich.edu# contributors may be used to endorse or promote products derived from
292665Ssaidi@eecs.umich.edu# this software without specific prior written permission.
30955SN/A#
31955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
352632Sstever@eecs.umich.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
362632Sstever@eecs.umich.edu# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
372632Sstever@eecs.umich.edu# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
382632Sstever@eecs.umich.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
402632Sstever@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
412632Sstever@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
422761Sstever@eecs.umich.edu#
432632Sstever@eecs.umich.edu# Authors: Steve Reinhardt
442632Sstever@eecs.umich.edu#          Nathan Binkert
452632Sstever@eecs.umich.edu
462761Sstever@eecs.umich.edu###################################################
472761Sstever@eecs.umich.edu#
482761Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
492632Sstever@eecs.umich.edu#
502632Sstever@eecs.umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
512761Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
522761Sstever@eecs.umich.edu# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
532761Sstever@eecs.umich.edu# the optimized full-system version).
542761Sstever@eecs.umich.edu#
552761Sstever@eecs.umich.edu# You can build gem5 in a different directory as long as there is a
562632Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
572632Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
582632Sstever@eecs.umich.edu# built for the same host system.
592632Sstever@eecs.umich.edu#
602632Sstever@eecs.umich.edu# Examples:
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
63955SN/A#   scons to search up the directory tree for this SConstruct file.
64955SN/A#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
65955SN/A#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
66955SN/A#
67955SN/A#   The following two commands are equivalent and demonstrate building
685396Ssaidi@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
705342Sstever@gmail.com#   file.
71955SN/A#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
725273Sstever@gmail.com#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
735273Sstever@gmail.com#
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#
792656Sstever@eecs.umich.edu###################################################
802656Sstever@eecs.umich.edu
812653Sstever@eecs.umich.edufrom __future__ import print_function
825227Ssaidi@eecs.umich.edu
835227Ssaidi@eecs.umich.edu# Global Python includes
845227Ssaidi@eecs.umich.eduimport itertools
855227Ssaidi@eecs.umich.eduimport os
865396Ssaidi@eecs.umich.eduimport re
875396Ssaidi@eecs.umich.eduimport shutil
885396Ssaidi@eecs.umich.eduimport subprocess
895396Ssaidi@eecs.umich.eduimport sys
905396Ssaidi@eecs.umich.edu
915396Ssaidi@eecs.umich.edufrom os import mkdir, environ
925396Ssaidi@eecs.umich.edufrom os.path import abspath, basename, dirname, expanduser, normpath
935396Ssaidi@eecs.umich.edufrom os.path import exists,  isdir, isfile
945396Ssaidi@eecs.umich.edufrom os.path import join as joinpath, split as splitpath
955396Ssaidi@eecs.umich.edufrom re import match
965396Ssaidi@eecs.umich.edu
975396Ssaidi@eecs.umich.edu# SCons includes
985396Ssaidi@eecs.umich.eduimport SCons
995396Ssaidi@eecs.umich.eduimport SCons.Node
1005396Ssaidi@eecs.umich.edu
1015396Ssaidi@eecs.umich.edufrom m5.util import compareVersions, readCommand
1025396Ssaidi@eecs.umich.edu
1035396Ssaidi@eecs.umich.eduhelp_texts = {
1045396Ssaidi@eecs.umich.edu    "options" : "",
1055396Ssaidi@eecs.umich.edu    "global_vars" : "",
1065396Ssaidi@eecs.umich.edu    "local_vars" : ""
1075396Ssaidi@eecs.umich.edu}
1085396Ssaidi@eecs.umich.edu
1095396Ssaidi@eecs.umich.eduExport("help_texts")
1105396Ssaidi@eecs.umich.edu
1115396Ssaidi@eecs.umich.edu
1125396Ssaidi@eecs.umich.edu# There's a bug in scons in that (1) by default, the help texts from
1135396Ssaidi@eecs.umich.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1145396Ssaidi@eecs.umich.edu# and (2) you can override the help displayed by 'scons -h' using the
1155396Ssaidi@eecs.umich.edu# Help() function, but these two features are incompatible: once
1165396Ssaidi@eecs.umich.edu# you've overridden the help text using Help(), there's no way to get
1175396Ssaidi@eecs.umich.edu# at the help texts from AddOptions.  See:
1185396Ssaidi@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1195396Ssaidi@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1205396Ssaidi@eecs.umich.edu# This hack lets us extract the help text from AddOptions and
1215396Ssaidi@eecs.umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1225396Ssaidi@eecs.umich.edu# we can just use AddOption directly.
1235396Ssaidi@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1245396Ssaidi@eecs.umich.edu    col_width = 30
1255396Ssaidi@eecs.umich.edu
1265396Ssaidi@eecs.umich.edu    help = "  " + ", ".join(args)
1275396Ssaidi@eecs.umich.edu    if "help" in kwargs:
1285396Ssaidi@eecs.umich.edu        length = len(help)
1295396Ssaidi@eecs.umich.edu        if length >= col_width:
1305396Ssaidi@eecs.umich.edu            help += "\n" + " " * col_width
1315396Ssaidi@eecs.umich.edu        else:
1325396Ssaidi@eecs.umich.edu            help += " " * (col_width - length)
1335396Ssaidi@eecs.umich.edu        help += kwargs["help"]
1345396Ssaidi@eecs.umich.edu    help_texts["options"] += help + "\n"
1355396Ssaidi@eecs.umich.edu
1365396Ssaidi@eecs.umich.edu    AddOption(*args, **kwargs)
1375396Ssaidi@eecs.umich.edu
1385396Ssaidi@eecs.umich.eduAddLocalOption('--colors', dest='use_colors', action='store_true',
1395396Ssaidi@eecs.umich.edu               help="Add color to abbreviated scons output")
1405396Ssaidi@eecs.umich.eduAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1415396Ssaidi@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1425396Ssaidi@eecs.umich.eduAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1435396Ssaidi@eecs.umich.edu               action='store_true',
1445396Ssaidi@eecs.umich.edu               help="Build with support for C++-based configuration")
1455396Ssaidi@eecs.umich.eduAddLocalOption('--default', dest='default', type='string', action='store',
1465396Ssaidi@eecs.umich.edu               help='Override which build_opts file to use for defaults')
1475396Ssaidi@eecs.umich.eduAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1485396Ssaidi@eecs.umich.edu               help='Disable style checking hooks')
1495396Ssaidi@eecs.umich.eduAddLocalOption('--gold-linker', dest='gold_linker', action='store_true',
1504781Snate@binkert.org               help='Use the gold linker')
1511852SN/AAddLocalOption('--no-lto', dest='no_lto', action='store_true',
152955SN/A               help='Disable Link-Time Optimization for fast')
153955SN/AAddLocalOption('--force-lto', dest='force_lto', action='store_true',
154955SN/A               help='Use Link-Time Optimization instead of partial linking' +
1553717Sstever@eecs.umich.edu                    ' when the compiler doesn\'t support using them together.')
1563716Sstever@eecs.umich.eduAddLocalOption('--update-ref', dest='update_ref', action='store_true',
157955SN/A               help='Update test reference outputs')
1581533SN/AAddLocalOption('--verbose', dest='verbose', action='store_true',
1593716Sstever@eecs.umich.edu               help='Print full tool command lines')
1601533SN/AAddLocalOption('--without-python', dest='without_python',
1614678Snate@binkert.org               action='store_true',
1624678Snate@binkert.org               help='Build without Python configuration support')
1634678Snate@binkert.orgAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1644678Snate@binkert.org               action='store_true',
1654678Snate@binkert.org               help='Disable linking against tcmalloc')
1664678Snate@binkert.orgAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1674678Snate@binkert.org               help='Build with Undefined Behavior Sanitizer if available')
1684678Snate@binkert.orgAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1694678Snate@binkert.org               help='Build with Address Sanitizer if available')
1704678Snate@binkert.org
1714678Snate@binkert.orgif GetOption('no_lto') and GetOption('force_lto'):
1724678Snate@binkert.org    print('--no-lto and --force-lto are mutually exclusive')
1734678Snate@binkert.org    Exit(1)
1744678Snate@binkert.org
1754678Snate@binkert.org########################################################################
1764678Snate@binkert.org#
1774678Snate@binkert.org# Set up the main build environment.
1784678Snate@binkert.org#
1794678Snate@binkert.org########################################################################
1804678Snate@binkert.org
1814678Snate@binkert.orgmain = Environment()
1824973Ssaidi@eecs.umich.edu
1834678Snate@binkert.orgfrom gem5_scons import Transform
1844678Snate@binkert.orgfrom gem5_scons.util import get_termcap
1854678Snate@binkert.orgtermcap = get_termcap()
1864678Snate@binkert.org
1874678Snate@binkert.orgmain_dict_keys = main.Dictionary().keys()
1884678Snate@binkert.org
189955SN/A# Check that we have a C/C++ compiler
190955SN/Aif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
1912632Sstever@eecs.umich.edu    print("No C++ compiler installed (package g++ on Ubuntu and RedHat)")
1922632Sstever@eecs.umich.edu    Exit(1)
193955SN/A
194955SN/A###################################################
195955SN/A#
196955SN/A# Figure out which configurations to set up based on the path(s) of
1972632Sstever@eecs.umich.edu# the target(s).
198955SN/A#
1992632Sstever@eecs.umich.edu###################################################
2002632Sstever@eecs.umich.edu
2012632Sstever@eecs.umich.edu# Find default configuration & binary.
2022632Sstever@eecs.umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
2032632Sstever@eecs.umich.edu
2042632Sstever@eecs.umich.edu# helper function: find last occurrence of element in list
2052632Sstever@eecs.umich.edudef rfind(l, elt, offs = -1):
2062632Sstever@eecs.umich.edu    for i in range(len(l)+offs, 0, -1):
2072632Sstever@eecs.umich.edu        if l[i] == elt:
2082632Sstever@eecs.umich.edu            return i
2092632Sstever@eecs.umich.edu    raise ValueError, "element not found"
2102632Sstever@eecs.umich.edu
2112632Sstever@eecs.umich.edu# Take a list of paths (or SCons Nodes) and return a list with all
2123718Sstever@eecs.umich.edu# paths made absolute and ~-expanded.  Paths will be interpreted
2133718Sstever@eecs.umich.edu# relative to the launch directory unless a different root is provided
2143718Sstever@eecs.umich.edudef makePathListAbsolute(path_list, root=GetLaunchDir()):
2153718Sstever@eecs.umich.edu    return [abspath(joinpath(root, expanduser(str(p))))
2163718Sstever@eecs.umich.edu            for p in path_list]
2173718Sstever@eecs.umich.edu
2183718Sstever@eecs.umich.edu# Each target must have 'build' in the interior of the path; the
2193718Sstever@eecs.umich.edu# directory below this will determine the build parameters.  For
2203718Sstever@eecs.umich.edu# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2213718Sstever@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
2223718Sstever@eecs.umich.edu# follow 'build' in the build path.
2233718Sstever@eecs.umich.edu
2243718Sstever@eecs.umich.edu# The funky assignment to "[:]" is needed to replace the list contents
2252634Sstever@eecs.umich.edu# in place rather than reassign the symbol to a new list, which
2262634Sstever@eecs.umich.edu# doesn't work (obviously!).
2272632Sstever@eecs.umich.eduBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
2282638Sstever@eecs.umich.edu
2292632Sstever@eecs.umich.edu# Generate a list of the unique build roots and configs that the
2302632Sstever@eecs.umich.edu# collected targets reference.
2312632Sstever@eecs.umich.eduvariant_paths = []
2322632Sstever@eecs.umich.edubuild_root = None
2332632Sstever@eecs.umich.edufor t in BUILD_TARGETS:
2342632Sstever@eecs.umich.edu    path_dirs = t.split('/')
2351858SN/A    try:
2363716Sstever@eecs.umich.edu        build_top = rfind(path_dirs, 'build', -2)
2372638Sstever@eecs.umich.edu    except:
2382638Sstever@eecs.umich.edu        print("Error: no non-leaf 'build' dir found on target path", t)
2392638Sstever@eecs.umich.edu        Exit(1)
2402638Sstever@eecs.umich.edu    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2412638Sstever@eecs.umich.edu    if not build_root:
2422638Sstever@eecs.umich.edu        build_root = this_build_root
2432638Sstever@eecs.umich.edu    else:
2443716Sstever@eecs.umich.edu        if this_build_root != build_root:
2452634Sstever@eecs.umich.edu            print("Error: build targets not under same build root\n"
2462634Sstever@eecs.umich.edu                  "  %s\n  %s" % (build_root, this_build_root))
247955SN/A            Exit(1)
2485341Sstever@gmail.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
2495341Sstever@gmail.com    if variant_path not in variant_paths:
2505341Sstever@gmail.com        variant_paths.append(variant_path)
2515341Sstever@gmail.com
252955SN/A# Make sure build_root exists (might not if this is the first build there)
253955SN/Aif not isdir(build_root):
254955SN/A    mkdir(build_root)
255955SN/Amain['BUILDROOT'] = build_root
256955SN/A
257955SN/AExport('main')
258955SN/A
2591858SN/Amain.SConsignFile(joinpath(build_root, "sconsign"))
2601858SN/A
2612632Sstever@eecs.umich.edu# Default duplicate option is to use hard links, but this messes up
262955SN/A# when you use emacs to edit a file in the target dir, as emacs moves
2634494Ssaidi@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
2644494Ssaidi@eecs.umich.edu# (soft) links work better.
2653716Sstever@eecs.umich.edumain.SetOption('duplicate', 'soft-copy')
2661105SN/A
2672667Sstever@eecs.umich.edu#
2682667Sstever@eecs.umich.edu# Set up global sticky variables... these are common to an entire build
2692667Sstever@eecs.umich.edu# tree (not specific to a particular build like ALPHA_SE)
2702667Sstever@eecs.umich.edu#
2712667Sstever@eecs.umich.edu
2722667Sstever@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
2731869SN/A
2741869SN/Aglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
2751869SN/A
2761869SN/Aglobal_vars.AddVariables(
2771869SN/A    ('CC', 'C compiler', environ.get('CC', main['CC'])),
2781065SN/A    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
2795341Sstever@gmail.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
2805341Sstever@gmail.com    ('BATCH', 'Use batch pool for build and tests', False),
2815341Sstever@gmail.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
2825341Sstever@gmail.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
2835341Sstever@gmail.com    ('EXTRAS', 'Add extra directories to the compilation', '')
2845341Sstever@gmail.com    )
2855341Sstever@gmail.com
2865341Sstever@gmail.com# Update main environment with values from ARGUMENTS & global_vars_file
2875341Sstever@gmail.comglobal_vars.Update(main)
2885341Sstever@gmail.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
2895341Sstever@gmail.com
2905341Sstever@gmail.com# Save sticky variable settings back to current variables file
2915341Sstever@gmail.comglobal_vars.Save(global_vars_file, main)
2925341Sstever@gmail.com
2935341Sstever@gmail.com# Parse EXTRAS variable to build list of all directories where we're
2945341Sstever@gmail.com# look for sources etc.  This list is exported as extras_dir_list.
2955341Sstever@gmail.combase_dir = main.srcdir.abspath
2965341Sstever@gmail.comif main['EXTRAS']:
2975341Sstever@gmail.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
2985341Sstever@gmail.comelse:
2995341Sstever@gmail.com    extras_dir_list = []
3005341Sstever@gmail.com
3015341Sstever@gmail.comExport('base_dir')
3025341Sstever@gmail.comExport('extras_dir_list')
3035341Sstever@gmail.com
3045341Sstever@gmail.com# the ext directory should be on the #includes path
3055341Sstever@gmail.commain.Append(CPPPATH=[Dir('ext')])
3065397Ssaidi@eecs.umich.edu
3075397Ssaidi@eecs.umich.edu# Add shared top-level headers
3085341Sstever@gmail.commain.Prepend(CPPPATH=Dir('include'))
3095341Sstever@gmail.com
3105341Sstever@gmail.comif GetOption('verbose'):
3115341Sstever@gmail.com    def MakeAction(action, string, *args, **kwargs):
3125341Sstever@gmail.com        return Action(action, *args, **kwargs)
3135341Sstever@gmail.comelse:
3145341Sstever@gmail.com    MakeAction = Action
3155341Sstever@gmail.com    main['CCCOMSTR']        = Transform("CC")
3165341Sstever@gmail.com    main['CXXCOMSTR']       = Transform("CXX")
3175341Sstever@gmail.com    main['ASCOMSTR']        = Transform("AS")
3185341Sstever@gmail.com    main['ARCOMSTR']        = Transform("AR", 0)
3195341Sstever@gmail.com    main['LINKCOMSTR']      = Transform("LINK", 0)
3205341Sstever@gmail.com    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
3215341Sstever@gmail.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
3225341Sstever@gmail.com    main['M4COMSTR']        = Transform("M4")
3235341Sstever@gmail.com    main['SHCCCOMSTR']      = Transform("SHCC")
3245341Sstever@gmail.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
3255341Sstever@gmail.comExport('MakeAction')
3265341Sstever@gmail.com
3275341Sstever@gmail.com# Initialize the Link-Time Optimization (LTO) flags
3285341Sstever@gmail.commain['LTO_CCFLAGS'] = []
3295341Sstever@gmail.commain['LTO_LDFLAGS'] = []
3305344Sstever@gmail.com
3315341Sstever@gmail.com# According to the readme, tcmalloc works best if the compiler doesn't
3325341Sstever@gmail.com# assume that we're using the builtin malloc and friends. These flags
3335341Sstever@gmail.com# are compiler-specific, so we need to set them after we detect which
3345341Sstever@gmail.com# compiler we're using.
3355341Sstever@gmail.commain['TCMALLOC_CCFLAGS'] = []
3362632Sstever@eecs.umich.edu
3375199Sstever@gmail.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
3383918Ssaidi@eecs.umich.eduCXX_V = readCommand([main['CXX'],'-V'], exception=False)
3393918Ssaidi@eecs.umich.edu
3403940Ssaidi@eecs.umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3414781Snate@binkert.orgmain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
3424781Snate@binkert.orgif main['GCC'] + main['CLANG'] > 1:
3433918Ssaidi@eecs.umich.edu    print('Error: How can we have two at the same time?')
3444781Snate@binkert.org    Exit(1)
3454781Snate@binkert.org
3463918Ssaidi@eecs.umich.edu# Set up default C++ compiler flags
3474781Snate@binkert.orgif main['GCC'] or main['CLANG']:
3484781Snate@binkert.org    # As gcc and clang share many flags, do the common parts here
3493940Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-pipe'])
3503942Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
3513940Ssaidi@eecs.umich.edu    # Enable -Wall and -Wextra and then disable the few warnings that
3523918Ssaidi@eecs.umich.edu    # we consistently violate
3533918Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
354955SN/A                         '-Wno-sign-compare', '-Wno-unused-parameter'])
3551858SN/A    # We always compile using C++11
3563918Ssaidi@eecs.umich.edu    main.Append(CXXFLAGS=['-std=c++11'])
3573918Ssaidi@eecs.umich.edu    if sys.platform.startswith('freebsd'):
3583918Ssaidi@eecs.umich.edu        main.Append(CCFLAGS=['-I/usr/local/include'])
3593918Ssaidi@eecs.umich.edu        main.Append(CXXFLAGS=['-I/usr/local/include'])
3603940Ssaidi@eecs.umich.edu
3613940Ssaidi@eecs.umich.edu    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
3623918Ssaidi@eecs.umich.edu    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
3633918Ssaidi@eecs.umich.edu    if GetOption('gold_linker'):
3643918Ssaidi@eecs.umich.edu        main.Append(LINKFLAGS='-fuse-ld=gold')
3653918Ssaidi@eecs.umich.edu    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
3663918Ssaidi@eecs.umich.edu    shared_partial_flags = ['-r', '-nostdlib']
3673918Ssaidi@eecs.umich.edu    main.Append(PSHLINKFLAGS=shared_partial_flags)
3683918Ssaidi@eecs.umich.edu    main.Append(PLINKFLAGS=shared_partial_flags)
3693918Ssaidi@eecs.umich.edu
3703918Ssaidi@eecs.umich.edu    # Treat warnings as errors but white list some warnings that we
3713940Ssaidi@eecs.umich.edu    # want to allow (e.g., deprecation warnings).
3723918Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-Werror',
3733918Ssaidi@eecs.umich.edu                         '-Wno-error=deprecated-declarations',
3745397Ssaidi@eecs.umich.edu                         '-Wno-error=deprecated',
3755397Ssaidi@eecs.umich.edu                        ])
3765397Ssaidi@eecs.umich.eduelse:
3775397Ssaidi@eecs.umich.edu    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
3785397Ssaidi@eecs.umich.edu    print("Don't know what compiler options to use for your compiler.")
3795397Ssaidi@eecs.umich.edu    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
3801851SN/A    print(termcap.Yellow + '       version:' + termcap.Normal, end = ' ')
3811851SN/A    if not CXX_version:
3821858SN/A        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
3835200Sstever@gmail.com              termcap.Normal)
384955SN/A    else:
3853053Sstever@eecs.umich.edu        print(CXX_version.replace('\n', '<nl>'))
3863053Sstever@eecs.umich.edu    print("       If you're trying to use a compiler other than GCC")
3873053Sstever@eecs.umich.edu    print("       or clang, there appears to be something wrong with your")
3883053Sstever@eecs.umich.edu    print("       environment.")
3893053Sstever@eecs.umich.edu    print("       ")
3903053Sstever@eecs.umich.edu    print("       If you are trying to use a compiler other than those listed")
3913053Sstever@eecs.umich.edu    print("       above you will need to ease fix SConstruct and ")
3923053Sstever@eecs.umich.edu    print("       src/SConscript to support that compiler.")
3933053Sstever@eecs.umich.edu    Exit(1)
3944742Sstever@eecs.umich.edu
3954742Sstever@eecs.umich.eduif main['GCC']:
3963053Sstever@eecs.umich.edu    # Check for a supported version of gcc. >= 4.8 is chosen for its
3973053Sstever@eecs.umich.edu    # level of c++11 support. See
3983053Sstever@eecs.umich.edu    # http://gcc.gnu.org/projects/cxx0x.html for details.
3993053Sstever@eecs.umich.edu    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
4003053Sstever@eecs.umich.edu    if compareVersions(gcc_version, "4.8") < 0:
4013053Sstever@eecs.umich.edu        print('Error: gcc version 4.8 or newer required.')
4023053Sstever@eecs.umich.edu        print('       Installed version: ', gcc_version)
4033053Sstever@eecs.umich.edu        Exit(1)
4043053Sstever@eecs.umich.edu
4052667Sstever@eecs.umich.edu    main['GCC_VERSION'] = gcc_version
4064554Sbinkertn@umich.edu
4074554Sbinkertn@umich.edu    if compareVersions(gcc_version, '4.9') >= 0:
4082667Sstever@eecs.umich.edu        # Incremental linking with LTO is currently broken in gcc versions
4094554Sbinkertn@umich.edu        # 4.9 and above. A version where everything works completely hasn't
4104554Sbinkertn@umich.edu        # yet been identified.
4114554Sbinkertn@umich.edu        #
4124554Sbinkertn@umich.edu        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
4134554Sbinkertn@umich.edu        main['BROKEN_INCREMENTAL_LTO'] = True
4144554Sbinkertn@umich.edu    if compareVersions(gcc_version, '6.0') >= 0:
4154554Sbinkertn@umich.edu        # gcc versions 6.0 and greater accept an -flinker-output flag which
4164781Snate@binkert.org        # selects what type of output the linker should generate. This is
4174554Sbinkertn@umich.edu        # necessary for incremental lto to work, but is also broken in
4184554Sbinkertn@umich.edu        # current versions of gcc. It may not be necessary in future
4192667Sstever@eecs.umich.edu        # versions. We add it here since it might be, and as a reminder that
4204554Sbinkertn@umich.edu        # it exists. It's excluded if lto is being forced.
4214554Sbinkertn@umich.edu        #
4224554Sbinkertn@umich.edu        # https://gcc.gnu.org/gcc-6/changes.html
4234554Sbinkertn@umich.edu        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
4242667Sstever@eecs.umich.edu        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
4254554Sbinkertn@umich.edu        if not GetOption('force_lto'):
4262667Sstever@eecs.umich.edu            main.Append(PSHLINKFLAGS='-flinker-output=rel')
4274554Sbinkertn@umich.edu            main.Append(PLINKFLAGS='-flinker-output=rel')
4284554Sbinkertn@umich.edu
4292667Sstever@eecs.umich.edu    # Make sure we warn if the user has requested to compile with the
4302638Sstever@eecs.umich.edu    # Undefined Benahvior Sanitizer and this version of gcc does not
4312638Sstever@eecs.umich.edu    # support it.
4322638Sstever@eecs.umich.edu    if GetOption('with_ubsan') and \
4333716Sstever@eecs.umich.edu            compareVersions(gcc_version, '4.9') < 0:
4343716Sstever@eecs.umich.edu        print(termcap.Yellow + termcap.Bold +
4351858SN/A            'Warning: UBSan is only supported using gcc 4.9 and later.' +
4365227Ssaidi@eecs.umich.edu            termcap.Normal)
4375227Ssaidi@eecs.umich.edu
4385227Ssaidi@eecs.umich.edu    disable_lto = GetOption('no_lto')
4395227Ssaidi@eecs.umich.edu    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
4405227Ssaidi@eecs.umich.edu            not GetOption('force_lto'):
4415227Ssaidi@eecs.umich.edu        print(termcap.Yellow + termcap.Bold +
4425227Ssaidi@eecs.umich.edu            'Warning: Your compiler doesn\'t support incremental linking' +
4435227Ssaidi@eecs.umich.edu            ' and lto at the same time, so lto is being disabled. To force' +
4445227Ssaidi@eecs.umich.edu            ' lto on anyway, use the --force-lto option. That will disable' +
4455227Ssaidi@eecs.umich.edu            ' partial linking.' +
4465227Ssaidi@eecs.umich.edu            termcap.Normal)
4475227Ssaidi@eecs.umich.edu        disable_lto = True
4485227Ssaidi@eecs.umich.edu
4495227Ssaidi@eecs.umich.edu    # Add the appropriate Link-Time Optimization (LTO) flags
4505227Ssaidi@eecs.umich.edu    # unless LTO is explicitly turned off. Note that these flags
4515204Sstever@gmail.com    # are only used by the fast target.
4525204Sstever@gmail.com    if not disable_lto:
4535204Sstever@gmail.com        # Pass the LTO flag when compiling to produce GIMPLE
4545204Sstever@gmail.com        # output, we merely create the flags here and only append
4555204Sstever@gmail.com        # them later
4565204Sstever@gmail.com        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4575204Sstever@gmail.com
4585204Sstever@gmail.com        # Use the same amount of jobs for LTO as we are running
4595204Sstever@gmail.com        # scons with
4605204Sstever@gmail.com        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4615204Sstever@gmail.com
4625204Sstever@gmail.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
4635204Sstever@gmail.com                                  '-fno-builtin-realloc', '-fno-builtin-free'])
4645204Sstever@gmail.com
4655204Sstever@gmail.com    # The address sanitizer is available for gcc >= 4.8
4665204Sstever@gmail.com    if GetOption('with_asan'):
4675204Sstever@gmail.com        if GetOption('with_ubsan') and \
4685204Sstever@gmail.com                compareVersions(main['GCC_VERSION'], '4.9') >= 0:
4695204Sstever@gmail.com            main.Append(CCFLAGS=['-fsanitize=address,undefined',
4703118Sstever@eecs.umich.edu                                 '-fno-omit-frame-pointer'],
4713118Sstever@eecs.umich.edu                        LINKFLAGS='-fsanitize=address,undefined')
4723118Sstever@eecs.umich.edu        else:
4733118Sstever@eecs.umich.edu            main.Append(CCFLAGS=['-fsanitize=address',
4743118Sstever@eecs.umich.edu                                 '-fno-omit-frame-pointer'],
4753118Sstever@eecs.umich.edu                        LINKFLAGS='-fsanitize=address')
4763118Sstever@eecs.umich.edu    # Only gcc >= 4.9 supports UBSan, so check both the version
4773118Sstever@eecs.umich.edu    # and the command-line option before adding the compiler and
4783118Sstever@eecs.umich.edu    # linker flags.
4793118Sstever@eecs.umich.edu    elif GetOption('with_ubsan') and \
4803118Sstever@eecs.umich.edu            compareVersions(main['GCC_VERSION'], '4.9') >= 0:
4813716Sstever@eecs.umich.edu        main.Append(CCFLAGS='-fsanitize=undefined')
4823118Sstever@eecs.umich.edu        main.Append(LINKFLAGS='-fsanitize=undefined')
4833118Sstever@eecs.umich.edu
4843118Sstever@eecs.umich.eduelif main['CLANG']:
4853118Sstever@eecs.umich.edu    # Check for a supported version of clang, >= 3.1 is needed to
4863118Sstever@eecs.umich.edu    # support similar features as gcc 4.8. See
4873118Sstever@eecs.umich.edu    # http://clang.llvm.org/cxx_status.html for details
4883118Sstever@eecs.umich.edu    clang_version_re = re.compile(".* version (\d+\.\d+)")
4893118Sstever@eecs.umich.edu    clang_version_match = clang_version_re.search(CXX_version)
4903118Sstever@eecs.umich.edu    if (clang_version_match):
4913716Sstever@eecs.umich.edu        clang_version = clang_version_match.groups()[0]
4923118Sstever@eecs.umich.edu        if compareVersions(clang_version, "3.1") < 0:
4933118Sstever@eecs.umich.edu            print('Error: clang version 3.1 or newer required.')
4943118Sstever@eecs.umich.edu            print('       Installed version:', clang_version)
4953118Sstever@eecs.umich.edu            Exit(1)
4963118Sstever@eecs.umich.edu    else:
4973118Sstever@eecs.umich.edu        print('Error: Unable to determine clang version.')
4983118Sstever@eecs.umich.edu        Exit(1)
4993118Sstever@eecs.umich.edu
5003118Sstever@eecs.umich.edu    # clang has a few additional warnings that we disable, extraneous
5013118Sstever@eecs.umich.edu    # parantheses are allowed due to Ruby's printing of the AST,
5023483Ssaidi@eecs.umich.edu    # finally self assignments are allowed as the generated CPU code
5033494Ssaidi@eecs.umich.edu    # is relying on this
5043494Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-Wno-parentheses',
5053483Ssaidi@eecs.umich.edu                         '-Wno-self-assign',
5063483Ssaidi@eecs.umich.edu                         # Some versions of libstdc++ (4.8?) seem to
5073483Ssaidi@eecs.umich.edu                         # use struct hash and class hash
5083053Sstever@eecs.umich.edu                         # interchangeably.
5093053Sstever@eecs.umich.edu                         '-Wno-mismatched-tags',
5103918Ssaidi@eecs.umich.edu                         ])
5113053Sstever@eecs.umich.edu
5123053Sstever@eecs.umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
5133053Sstever@eecs.umich.edu
5143053Sstever@eecs.umich.edu    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
5153053Sstever@eecs.umich.edu    # opposed to libstdc++, as the later is dated.
5161858SN/A    if sys.platform == "darwin":
5171858SN/A        main.Append(CXXFLAGS=['-stdlib=libc++'])
5181858SN/A        main.Append(LIBS=['c++'])
5191858SN/A
5201858SN/A    # On FreeBSD we need libthr.
5211858SN/A    if sys.platform.startswith('freebsd'):
5221859SN/A        main.Append(LIBS=['thr'])
5231858SN/A
5241858SN/A    # We require clang >= 3.1, so there is no need to check any
5251858SN/A    # versions here.
5261859SN/A    if GetOption('with_ubsan'):
5271859SN/A        if GetOption('with_asan'):
5281862SN/A            main.Append(CCFLAGS=['-fsanitize=address,undefined',
5293053Sstever@eecs.umich.edu                                 '-fno-omit-frame-pointer'],
5303053Sstever@eecs.umich.edu                       LINKFLAGS='-fsanitize=address,undefined')
5313053Sstever@eecs.umich.edu        else:
5323053Sstever@eecs.umich.edu            main.Append(CCFLAGS='-fsanitize=undefined',
5331859SN/A                        LINKFLAGS='-fsanitize=undefined')
5341859SN/A
5351859SN/A    elif GetOption('with_asan'):
5361859SN/A        main.Append(CCFLAGS=['-fsanitize=address',
5371859SN/A                             '-fno-omit-frame-pointer'],
5381859SN/A                   LINKFLAGS='-fsanitize=address')
5391859SN/A
5401859SN/Aelse:
5411862SN/A    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
5421859SN/A    print("Don't know what compiler options to use for your compiler.")
5431859SN/A    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
5441859SN/A    print(termcap.Yellow + '       version:' + termcap.Normal, end=' ')
5451858SN/A    if not CXX_version:
5461858SN/A        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
5472139SN/A              termcap.Normal)
5484202Sbinkertn@umich.edu    else:
5494202Sbinkertn@umich.edu        print(CXX_version.replace('\n', '<nl>'))
5502139SN/A    print("       If you're trying to use a compiler other than GCC")
5512155SN/A    print("       or clang, there appears to be something wrong with your")
5524202Sbinkertn@umich.edu    print("       environment.")
5534202Sbinkertn@umich.edu    print("       ")
5544202Sbinkertn@umich.edu    print("       If you are trying to use a compiler other than those listed")
5552155SN/A    print("       above you will need to ease fix SConstruct and ")
5561869SN/A    print("       src/SConscript to support that compiler.")
5571869SN/A    Exit(1)
5581869SN/A
5591869SN/A# Set up common yacc/bison flags (needed for Ruby)
5604202Sbinkertn@umich.edumain['YACCFLAGS'] = '-d'
5614202Sbinkertn@umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
5624202Sbinkertn@umich.edu
5634202Sbinkertn@umich.edu# Do this after we save setting back, or else we'll tack on an
5644202Sbinkertn@umich.edu# extra 'qdo' every time we run scons.
5654202Sbinkertn@umich.eduif main['BATCH']:
5664202Sbinkertn@umich.edu    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
5674202Sbinkertn@umich.edu    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
5685341Sstever@gmail.com    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
5695341Sstever@gmail.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
5705341Sstever@gmail.com    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
5715342Sstever@gmail.com
5725342Sstever@gmail.comif sys.platform == 'cygwin':
5734202Sbinkertn@umich.edu    # cygwin has some header file issues...
5744202Sbinkertn@umich.edu    main.Append(CCFLAGS=["-Wno-uninitialized"])
5754202Sbinkertn@umich.edu
5764202Sbinkertn@umich.edu# Check for the protobuf compiler
5774202Sbinkertn@umich.eduprotoc_version = readCommand([main['PROTOC'], '--version'],
5781869SN/A                             exception='').split()
5794202Sbinkertn@umich.edu
5801869SN/A# First two words should be "libprotoc x.y.z"
5812508SN/Aif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
5822508SN/A    print(termcap.Yellow + termcap.Bold +
5832508SN/A        'Warning: Protocol buffer compiler (protoc) not found.\n' +
5842508SN/A        '         Please install protobuf-compiler for tracing support.' +
5854202Sbinkertn@umich.edu        termcap.Normal)
5861869SN/A    main['PROTOC'] = False
5875385Sstever@gmail.comelse:
5885385Sstever@gmail.com    # Based on the availability of the compress stream wrappers,
5895385Sstever@gmail.com    # require 2.1.0
5905385Sstever@gmail.com    min_protoc_version = '2.1.0'
5911869SN/A    if compareVersions(protoc_version[1], min_protoc_version) < 0:
5921869SN/A        print(termcap.Yellow + termcap.Bold +
5931869SN/A            'Warning: protoc version', min_protoc_version,
5941869SN/A            'or newer required.\n' +
5951869SN/A            '         Installed version:', protoc_version[1],
5961965SN/A            termcap.Normal)
5971965SN/A        main['PROTOC'] = False
5981965SN/A    else:
5991869SN/A        # Attempt to determine the appropriate include path and
6001869SN/A        # library path using pkg-config, that means we also need to
6012733Sktlim@umich.edu        # check for pkg-config. Note that it is possible to use
6023356Sbinkertn@umich.edu        # protobuf without the involvement of pkg-config. Later on we
6033356Sbinkertn@umich.edu        # check go a library config check and at that point the test
6044773Snate@binkert.org        # will fail if libprotobuf cannot be found.
6051869SN/A        if readCommand(['pkg-config', '--version'], exception=''):
6061858SN/A            try:
6071869SN/A                # Attempt to establish what linking flags to add for protobuf
6081869SN/A                # using pkg-config
6091869SN/A                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
6101858SN/A            except:
6112761Sstever@eecs.umich.edu                print(termcap.Yellow + termcap.Bold +
6121869SN/A                    'Warning: pkg-config could not get protobuf flags.' +
6135385Sstever@gmail.com                    termcap.Normal)
6145385Sstever@gmail.com
6153584Ssaidi@eecs.umich.edu
6161869SN/A# Check for 'timeout' from GNU coreutils. If present, regressions will
6171869SN/A# be run with a time limit. We require version 8.13 since we rely on
6181869SN/A# support for the '--foreground' option.
6191869SN/Aif sys.platform.startswith('freebsd'):
6201869SN/A    timeout_lines = readCommand(['gtimeout', '--version'],
6211869SN/A                                exception='').splitlines()
6221858SN/Aelse:
623955SN/A    timeout_lines = readCommand(['timeout', '--version'],
624955SN/A                                exception='').splitlines()
6251869SN/A# Get the first line and tokenize it
6261869SN/Atimeout_version = timeout_lines[0].split() if timeout_lines else []
6271869SN/Amain['TIMEOUT'] =  timeout_version and \
6281869SN/A    compareVersions(timeout_version[-1], '8.13') >= 0
6291869SN/A
6301869SN/A# Add a custom Check function to test for structure members.
6311869SN/Adef CheckMember(context, include, decl, member, include_quotes="<>"):
6321869SN/A    context.Message("Checking for member %s in %s..." %
6331869SN/A                    (member, decl))
6341869SN/A    text = """
6351869SN/A#include %(header)s
6361869SN/Aint main(){
6371869SN/A  %(decl)s test;
6381869SN/A  (void)test.%(member)s;
6391869SN/A  return 0;
6401869SN/A};
6411869SN/A""" % { "header" : include_quotes[0] + include + include_quotes[1],
6421869SN/A        "decl" : decl,
6431869SN/A        "member" : member,
6441869SN/A        }
6451869SN/A
6461869SN/A    ret = context.TryCompile(text, extension=".cc")
6471869SN/A    context.Result(ret)
6481869SN/A    return ret
6491869SN/A
6501869SN/A# Platform-specific configuration.  Note again that we assume that all
6511869SN/A# builds under a given build root run on the same host platform.
6521869SN/Aconf = Configure(main,
6531869SN/A                 conf_dir = joinpath(build_root, '.scons_config'),
6543716Sstever@eecs.umich.edu                 log_file = joinpath(build_root, 'scons_config.log'),
6553356Sbinkertn@umich.edu                 custom_tests = {
6563356Sbinkertn@umich.edu        'CheckMember' : CheckMember,
6573356Sbinkertn@umich.edu        })
6583356Sbinkertn@umich.edu
6593356Sbinkertn@umich.edu# Check if we should compile a 64 bit binary on Mac OS X/Darwin
6603356Sbinkertn@umich.edutry:
6614781Snate@binkert.org    import platform
6621869SN/A    uname = platform.uname()
6631869SN/A    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
6641869SN/A        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
6651869SN/A            main.Append(CCFLAGS=['-arch', 'x86_64'])
6661869SN/A            main.Append(CFLAGS=['-arch', 'x86_64'])
6671869SN/A            main.Append(LINKFLAGS=['-arch', 'x86_64'])
6681869SN/A            main.Append(ASFLAGS=['-arch', 'x86_64'])
6692655Sstever@eecs.umich.eduexcept:
6702655Sstever@eecs.umich.edu    pass
6712655Sstever@eecs.umich.edu
6722655Sstever@eecs.umich.edu# Recent versions of scons substitute a "Null" object for Configure()
6732655Sstever@eecs.umich.edu# when configuration isn't necessary, e.g., if the "--help" option is
6742655Sstever@eecs.umich.edu# present.  Unfortuantely this Null object always returns false,
6752655Sstever@eecs.umich.edu# breaking all our configuration checks.  We replace it with our own
6762655Sstever@eecs.umich.edu# more optimistic null object that returns True instead.
6772655Sstever@eecs.umich.eduif not conf:
6782655Sstever@eecs.umich.edu    def NullCheck(*args, **kwargs):
6792655Sstever@eecs.umich.edu        return True
6802655Sstever@eecs.umich.edu
6812655Sstever@eecs.umich.edu    class NullConf:
6822655Sstever@eecs.umich.edu        def __init__(self, env):
6832655Sstever@eecs.umich.edu            self.env = env
6842655Sstever@eecs.umich.edu        def Finish(self):
6852655Sstever@eecs.umich.edu            return self.env
6862655Sstever@eecs.umich.edu        def __getattr__(self, mname):
6872655Sstever@eecs.umich.edu            return NullCheck
6882655Sstever@eecs.umich.edu
6892655Sstever@eecs.umich.edu    conf = NullConf(main)
6902655Sstever@eecs.umich.edu
6912655Sstever@eecs.umich.edu# Cache build files in the supplied directory.
6922655Sstever@eecs.umich.eduif main['M5_BUILD_CACHE']:
6932655Sstever@eecs.umich.edu    print('Using build cache located at', main['M5_BUILD_CACHE'])
6942655Sstever@eecs.umich.edu    CacheDir(main['M5_BUILD_CACHE'])
6952638Sstever@eecs.umich.edu
6962638Sstever@eecs.umich.edumain['USE_PYTHON'] = not GetOption('without_python')
6973716Sstever@eecs.umich.eduif main['USE_PYTHON']:
6982638Sstever@eecs.umich.edu    # Find Python include and library directories for embedding the
6992638Sstever@eecs.umich.edu    # interpreter. We rely on python-config to resolve the appropriate
7001869SN/A    # includes and linker flags. ParseConfig does not seem to understand
7011869SN/A    # the more exotic linker flags such as -Xlinker and -export-dynamic so
7023546Sgblack@eecs.umich.edu    # we add them explicitly below. If you want to link in an alternate
7033546Sgblack@eecs.umich.edu    # version of python, see above for instructions on how to invoke
7043546Sgblack@eecs.umich.edu    # scons with the appropriate PATH set.
7053546Sgblack@eecs.umich.edu    #
7064202Sbinkertn@umich.edu    # First we check if python2-config exists, else we use python-config
7073546Sgblack@eecs.umich.edu    python_config = readCommand(['which', 'python2-config'],
7083546Sgblack@eecs.umich.edu                                exception='').strip()
7093546Sgblack@eecs.umich.edu    if not os.path.exists(python_config):
7103546Sgblack@eecs.umich.edu        python_config = readCommand(['which', 'python-config'],
7113546Sgblack@eecs.umich.edu                                    exception='').strip()
7124781Snate@binkert.org    py_includes = readCommand([python_config, '--includes'],
7134781Snate@binkert.org                              exception='').split()
7144781Snate@binkert.org    py_includes = filter(lambda s: match(r'.*\/include\/.*',s), py_includes)
7154781Snate@binkert.org    # Strip the -I from the include folders before adding them to the
7164781Snate@binkert.org    # CPPPATH
7174781Snate@binkert.org    py_includes = map(lambda s: s[2:] if s.startswith('-I') else s, py_includes)
7184781Snate@binkert.org    main.Append(CPPPATH=py_includes)
7194781Snate@binkert.org
7204781Snate@binkert.org    # Read the linker flags and split them into libraries and other link
7214781Snate@binkert.org    # flags. The libraries are added later through the call the CheckLib.
7224781Snate@binkert.org    py_ld_flags = readCommand([python_config, '--ldflags'],
7234781Snate@binkert.org        exception='').split()
7243546Sgblack@eecs.umich.edu    py_libs = []
7253546Sgblack@eecs.umich.edu    for lib in py_ld_flags:
7263546Sgblack@eecs.umich.edu         if not lib.startswith('-l'):
7274781Snate@binkert.org             main.Append(LINKFLAGS=[lib])
7283546Sgblack@eecs.umich.edu         else:
7293546Sgblack@eecs.umich.edu             lib = lib[2:]
7303546Sgblack@eecs.umich.edu             if lib not in py_libs:
7313546Sgblack@eecs.umich.edu                 py_libs.append(lib)
7323546Sgblack@eecs.umich.edu
7333546Sgblack@eecs.umich.edu    # verify that this stuff works
7343546Sgblack@eecs.umich.edu    if not conf.CheckHeader('Python.h', '<>'):
7353546Sgblack@eecs.umich.edu        print("Error: Check failed for Python.h header in", py_includes)
7363546Sgblack@eecs.umich.edu        print("Two possible reasons:")
7373546Sgblack@eecs.umich.edu        print("1. Python headers are not installed (You can install the "
7384202Sbinkertn@umich.edu              "package python-dev on Ubuntu and RedHat)")
7393546Sgblack@eecs.umich.edu        print("2. SCons is using a wrong C compiler. This can happen if "
7403546Sgblack@eecs.umich.edu              "CC has the wrong value.")
7413546Sgblack@eecs.umich.edu        print("CC = %s" % main['CC'])
742955SN/A        Exit(1)
743955SN/A
744955SN/A    for lib in py_libs:
745955SN/A        if not conf.CheckLib(lib):
7461858SN/A            print("Error: can't find library %s required by python" % lib)
7471858SN/A            Exit(1)
7481858SN/A
7492632Sstever@eecs.umich.edu# On Solaris you need to use libsocket for socket ops
7502632Sstever@eecs.umich.eduif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7515343Sstever@gmail.com   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7525343Sstever@gmail.com       print("Can't find library with socket calls (e.g. accept())")
7535343Sstever@gmail.com       Exit(1)
7544773Snate@binkert.org
7554773Snate@binkert.org# Check for zlib.  If the check passes, libz will be automatically
7562632Sstever@eecs.umich.edu# added to the LIBS environment variable.
7572632Sstever@eecs.umich.eduif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
7582632Sstever@eecs.umich.edu    print('Error: did not find needed zlib compression library '
7592023SN/A          'and/or zlib.h header file.')
7602632Sstever@eecs.umich.edu    print('       Please install zlib and try again.')
7612632Sstever@eecs.umich.edu    Exit(1)
7622632Sstever@eecs.umich.edu
7632632Sstever@eecs.umich.edu# If we have the protobuf compiler, also make sure we have the
7642632Sstever@eecs.umich.edu# development libraries. If the check passes, libprotobuf will be
7653716Sstever@eecs.umich.edu# automatically added to the LIBS environment variable. After
7665342Sstever@gmail.com# this, we can use the HAVE_PROTOBUF flag to determine if we have
7672632Sstever@eecs.umich.edu# got both protoc and libprotobuf available.
7682632Sstever@eecs.umich.edumain['HAVE_PROTOBUF'] = main['PROTOC'] and \
7692632Sstever@eecs.umich.edu    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
7702632Sstever@eecs.umich.edu                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
7712023SN/A
7722632Sstever@eecs.umich.edu# Valgrind gets much less confused if you tell it when you're using
7732632Sstever@eecs.umich.edu# alternative stacks.
7745342Sstever@gmail.commain['HAVE_VALGRIND'] = conf.CheckCHeader('valgrind/valgrind.h')
7751889SN/A
7762632Sstever@eecs.umich.edu# If we have the compiler but not the library, print another warning.
7772632Sstever@eecs.umich.eduif main['PROTOC'] and not main['HAVE_PROTOBUF']:
7782632Sstever@eecs.umich.edu    print(termcap.Yellow + termcap.Bold +
7792632Sstever@eecs.umich.edu        'Warning: did not find protocol buffer library and/or headers.\n' +
7803716Sstever@eecs.umich.edu    '       Please install libprotobuf-dev for tracing support.' +
7813716Sstever@eecs.umich.edu    termcap.Normal)
7825342Sstever@gmail.com
7832632Sstever@eecs.umich.edu# Check for librt.
7842632Sstever@eecs.umich.eduhave_posix_clock = \
7852632Sstever@eecs.umich.edu    conf.CheckLibWithHeader(None, 'time.h', 'C',
7862632Sstever@eecs.umich.edu                            'clock_nanosleep(0,0,NULL,NULL);') or \
7872632Sstever@eecs.umich.edu    conf.CheckLibWithHeader('rt', 'time.h', 'C',
7882632Sstever@eecs.umich.edu                            'clock_nanosleep(0,0,NULL,NULL);')
7892632Sstever@eecs.umich.edu
7901888SN/Ahave_posix_timers = \
7911888SN/A    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
7921869SN/A                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
7931869SN/A
7941858SN/Aif not GetOption('without_tcmalloc'):
7955341Sstever@gmail.com    if conf.CheckLib('tcmalloc'):
7962598SN/A        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
7972598SN/A    elif conf.CheckLib('tcmalloc_minimal'):
7982598SN/A        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
7992598SN/A    else:
8001858SN/A        print(termcap.Yellow + termcap.Bold +
8011858SN/A              "You can get a 12% performance improvement by "
8021858SN/A              "installing tcmalloc (libgoogle-perftools-dev package "
8031858SN/A              "on Ubuntu or RedHat)." + termcap.Normal)
8041858SN/A
8051858SN/A
8061858SN/A# Detect back trace implementations. The last implementation in the
8071858SN/A# list will be used by default.
8081858SN/Abacktrace_impls = [ "none" ]
8091871SN/A
8101858SN/Abacktrace_checker = 'char temp;' + \
8111858SN/A    ' backtrace_symbols_fd((void*)&temp, 0, 0);'
8121858SN/Aif conf.CheckLibWithHeader(None, 'execinfo.h', 'C', backtrace_checker):
8131858SN/A    backtrace_impls.append("glibc")
8141858SN/Aelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
8151858SN/A                             backtrace_checker):
8161858SN/A    # NetBSD and FreeBSD need libexecinfo.
8171858SN/A    backtrace_impls.append("glibc")
8181858SN/A    main.Append(LIBS=['execinfo'])
8191858SN/A
8201858SN/Aif backtrace_impls[-1] == "none":
8211859SN/A    default_backtrace_impl = "none"
8221859SN/A    print(termcap.Yellow + termcap.Bold +
8231869SN/A        "No suitable back trace implementation found." +
8241888SN/A        termcap.Normal)
8252632Sstever@eecs.umich.edu
8261869SN/Aif not have_posix_clock:
8271965SN/A    print("Can't find library for POSIX clocks.")
8281965SN/A
8291965SN/A# Check for <fenv.h> (C99 FP environment control)
8302761Sstever@eecs.umich.eduhave_fenv = conf.CheckHeader('fenv.h', '<>')
8311869SN/Aif not have_fenv:
8321869SN/A    print("Warning: Header file <fenv.h> not found.")
8332632Sstever@eecs.umich.edu    print("         This host has no IEEE FP rounding mode control.")
8342667Sstever@eecs.umich.edu
8351869SN/A# Check for <png.h> (libpng library needed if wanting to dump
8361869SN/A# frame buffer image in png format)
8372929Sktlim@umich.eduhave_png = conf.CheckHeader('png.h', '<>')
8382929Sktlim@umich.eduif not have_png:
8393716Sstever@eecs.umich.edu    print("Warning: Header file <png.h> not found.")
8402929Sktlim@umich.edu    print("         This host has no libpng library.")
841955SN/A    print("         Disabling support for PNG framebuffers.")
8422598SN/A
8432598SN/A# Check if we should enable KVM-based hardware virtualization. The API
8443546Sgblack@eecs.umich.edu# we rely on exists since version 2.6.36 of the kernel, but somehow
845955SN/A# the KVM_API_VERSION does not reflect the change. We test for one of
846955SN/A# the types as a fall back.
847955SN/Ahave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
8481530SN/Aif not have_kvm:
849955SN/A    print("Info: Compatible header file <linux/kvm.h> not found, "
850955SN/A          "disabling KVM support.")
851955SN/A
852# Check if the TUN/TAP driver is available.
853have_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
854if not have_tuntap:
855    print("Info: Compatible header file <linux/if_tun.h> not found.")
856
857# x86 needs support for xsave. We test for the structure here since we
858# won't be able to run new tests by the time we know which ISA we're
859# targeting.
860have_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
861                                    '#include <linux/kvm.h>') != 0
862
863# Check if the requested target ISA is compatible with the host
864def is_isa_kvm_compatible(isa):
865    try:
866        import platform
867        host_isa = platform.machine()
868    except:
869        print("Warning: Failed to determine host ISA.")
870        return False
871
872    if not have_posix_timers:
873        print("Warning: Can not enable KVM, host seems to lack support "
874              "for POSIX timers")
875        return False
876
877    if isa == "arm":
878        return host_isa in ( "armv7l", "aarch64" )
879    elif isa == "x86":
880        if host_isa != "x86_64":
881            return False
882
883        if not have_kvm_xsave:
884            print("KVM on x86 requires xsave support in kernel headers.")
885            return False
886
887        return True
888    else:
889        return False
890
891
892# Check if the exclude_host attribute is available. We want this to
893# get accurate instruction counts in KVM.
894main['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
895    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
896
897
898######################################################################
899#
900# Finish the configuration
901#
902main = conf.Finish()
903
904######################################################################
905#
906# Collect all non-global variables
907#
908
909# Define the universe of supported ISAs
910all_isa_list = [ ]
911all_gpu_isa_list = [ ]
912Export('all_isa_list')
913Export('all_gpu_isa_list')
914
915class CpuModel(object):
916    '''The CpuModel class encapsulates everything the ISA parser needs to
917    know about a particular CPU model.'''
918
919    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
920    dict = {}
921
922    # Constructor.  Automatically adds models to CpuModel.dict.
923    def __init__(self, name, default=False):
924        self.name = name           # name of model
925
926        # This cpu is enabled by default
927        self.default = default
928
929        # Add self to dict
930        if name in CpuModel.dict:
931            raise AttributeError, "CpuModel '%s' already registered" % name
932        CpuModel.dict[name] = self
933
934Export('CpuModel')
935
936# Sticky variables get saved in the variables file so they persist from
937# one invocation to the next (unless overridden, in which case the new
938# value becomes sticky).
939sticky_vars = Variables(args=ARGUMENTS)
940Export('sticky_vars')
941
942# Sticky variables that should be exported
943export_vars = []
944Export('export_vars')
945
946# For Ruby
947all_protocols = []
948Export('all_protocols')
949protocol_dirs = []
950Export('protocol_dirs')
951slicc_includes = []
952Export('slicc_includes')
953
954# Walk the tree and execute all SConsopts scripts that wil add to the
955# above variables
956if GetOption('verbose'):
957    print("Reading SConsopts")
958for bdir in [ base_dir ] + extras_dir_list:
959    if not isdir(bdir):
960        print("Error: directory '%s' does not exist" % bdir)
961        Exit(1)
962    for root, dirs, files in os.walk(bdir):
963        if 'SConsopts' in files:
964            if GetOption('verbose'):
965                print("Reading", joinpath(root, 'SConsopts'))
966            SConscript(joinpath(root, 'SConsopts'))
967
968all_isa_list.sort()
969all_gpu_isa_list.sort()
970
971sticky_vars.AddVariables(
972    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
973    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
974    ListVariable('CPU_MODELS', 'CPU models',
975                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
976                 sorted(CpuModel.dict.keys())),
977    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
978                 False),
979    BoolVariable('SS_COMPATIBLE_FP',
980                 'Make floating-point results compatible with SimpleScalar',
981                 False),
982    BoolVariable('USE_SSE2',
983                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
984                 False),
985    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
986    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
987    BoolVariable('USE_PNG',  'Enable support for PNG images', have_png),
988    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability',
989                 False),
990    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models',
991                 have_kvm),
992    BoolVariable('USE_TUNTAP',
993                 'Enable using a tap device to bridge to the host network',
994                 have_tuntap),
995    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
996    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
997                  all_protocols),
998    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
999                 backtrace_impls[-1], backtrace_impls)
1000    )
1001
1002# These variables get exported to #defines in config/*.hh (see src/SConscript).
1003export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
1004                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
1005                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_VALGRIND',
1006                'HAVE_PERF_ATTR_EXCLUDE_HOST', 'USE_PNG']
1007
1008###################################################
1009#
1010# Define a SCons builder for configuration flag headers.
1011#
1012###################################################
1013
1014# This function generates a config header file that #defines the
1015# variable symbol to the current variable setting (0 or 1).  The source
1016# operands are the name of the variable and a Value node containing the
1017# value of the variable.
1018def build_config_file(target, source, env):
1019    (variable, value) = [s.get_contents() for s in source]
1020    f = file(str(target[0]), 'w')
1021    print('#define', variable, value, file=f)
1022    f.close()
1023    return None
1024
1025# Combine the two functions into a scons Action object.
1026config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1027
1028# The emitter munges the source & target node lists to reflect what
1029# we're really doing.
1030def config_emitter(target, source, env):
1031    # extract variable name from Builder arg
1032    variable = str(target[0])
1033    # True target is config header file
1034    target = joinpath('config', variable.lower() + '.hh')
1035    val = env[variable]
1036    if isinstance(val, bool):
1037        # Force value to 0/1
1038        val = int(val)
1039    elif isinstance(val, str):
1040        val = '"' + val + '"'
1041
1042    # Sources are variable name & value (packaged in SCons Value nodes)
1043    return ([target], [Value(variable), Value(val)])
1044
1045config_builder = Builder(emitter = config_emitter, action = config_action)
1046
1047main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1048
1049###################################################
1050#
1051# Builders for static and shared partially linked object files.
1052#
1053###################################################
1054
1055partial_static_builder = Builder(action=SCons.Defaults.LinkAction,
1056                                 src_suffix='$OBJSUFFIX',
1057                                 src_builder=['StaticObject', 'Object'],
1058                                 LINKFLAGS='$PLINKFLAGS',
1059                                 LIBS='')
1060
1061def partial_shared_emitter(target, source, env):
1062    for tgt in target:
1063        tgt.attributes.shared = 1
1064    return (target, source)
1065partial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
1066                                 emitter=partial_shared_emitter,
1067                                 src_suffix='$SHOBJSUFFIX',
1068                                 src_builder='SharedObject',
1069                                 SHLINKFLAGS='$PSHLINKFLAGS',
1070                                 LIBS='')
1071
1072main.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
1073                         'PartialStatic' : partial_static_builder })
1074
1075def add_local_rpath(env, *targets):
1076    '''Set up an RPATH for a library which lives in the build directory.
1077
1078    The construction environment variable BIN_RPATH_PREFIX should be set to
1079    the relative path of the build directory starting from the location of the
1080    binary.'''
1081    for target in targets:
1082        target = env.Entry(target)
1083        if not target.isdir():
1084            target = target.dir
1085        relpath = os.path.relpath(target.abspath, env['BUILDDIR'])
1086        components = [
1087            '\\$$ORIGIN',
1088            '${BIN_RPATH_PREFIX}',
1089            relpath
1090        ]
1091        env.Append(RPATH=[env.Literal(os.path.join(*components))])
1092
1093if sys.platform != "darwin":
1094    main.Append(LINKFLAGS=Split('-z origin'))
1095
1096main.AddMethod(add_local_rpath, 'AddLocalRPATH')
1097
1098# builds in ext are shared across all configs in the build root.
1099ext_dir = abspath(joinpath(str(main.root), 'ext'))
1100ext_build_dirs = []
1101for root, dirs, files in os.walk(ext_dir):
1102    if 'SConscript' in files:
1103        build_dir = os.path.relpath(root, ext_dir)
1104        ext_build_dirs.append(build_dir)
1105        main.SConscript(joinpath(root, 'SConscript'),
1106                        variant_dir=joinpath(build_root, build_dir))
1107
1108gdb_xml_dir = joinpath(ext_dir, 'gdb-xml')
1109Export('gdb_xml_dir')
1110
1111main.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
1112
1113###################################################
1114#
1115# This builder and wrapper method are used to set up a directory with
1116# switching headers. Those are headers which are in a generic location and
1117# that include more specific headers from a directory chosen at build time
1118# based on the current build settings.
1119#
1120###################################################
1121
1122def build_switching_header(target, source, env):
1123    path = str(target[0])
1124    subdir = str(source[0])
1125    dp, fp = os.path.split(path)
1126    dp = os.path.relpath(os.path.realpath(dp),
1127                         os.path.realpath(env['BUILDDIR']))
1128    with open(path, 'w') as hdr:
1129        print('#include "%s/%s/%s"' % (dp, subdir, fp), file=hdr)
1130
1131switching_header_action = MakeAction(build_switching_header,
1132                                     Transform('GENERATE'))
1133
1134switching_header_builder = Builder(action=switching_header_action,
1135                                   source_factory=Value,
1136                                   single_source=True)
1137
1138main.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
1139
1140def switching_headers(self, headers, source):
1141    for header in headers:
1142        self.SwitchingHeader(header, source)
1143
1144main.AddMethod(switching_headers, 'SwitchingHeaders')
1145
1146###################################################
1147#
1148# Define build environments for selected configurations.
1149#
1150###################################################
1151
1152for variant_path in variant_paths:
1153    if not GetOption('silent'):
1154        print("Building in", variant_path)
1155
1156    # Make a copy of the build-root environment to use for this config.
1157    env = main.Clone()
1158    env['BUILDDIR'] = variant_path
1159
1160    # variant_dir is the tail component of build path, and is used to
1161    # determine the build parameters (e.g., 'ALPHA_SE')
1162    (build_root, variant_dir) = splitpath(variant_path)
1163
1164    # Set env variables according to the build directory config.
1165    sticky_vars.files = []
1166    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1167    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1168    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1169    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1170    if isfile(current_vars_file):
1171        sticky_vars.files.append(current_vars_file)
1172        if not GetOption('silent'):
1173            print("Using saved variables file %s" % current_vars_file)
1174    elif variant_dir in ext_build_dirs:
1175        # Things in ext are built without a variant directory.
1176        continue
1177    else:
1178        # Build dir-specific variables file doesn't exist.
1179
1180        # Make sure the directory is there so we can create it later
1181        opt_dir = dirname(current_vars_file)
1182        if not isdir(opt_dir):
1183            mkdir(opt_dir)
1184
1185        # Get default build variables from source tree.  Variables are
1186        # normally determined by name of $VARIANT_DIR, but can be
1187        # overridden by '--default=' arg on command line.
1188        default = GetOption('default')
1189        opts_dir = joinpath(main.root.abspath, 'build_opts')
1190        if default:
1191            default_vars_files = [joinpath(build_root, 'variables', default),
1192                                  joinpath(opts_dir, default)]
1193        else:
1194            default_vars_files = [joinpath(opts_dir, variant_dir)]
1195        existing_files = filter(isfile, default_vars_files)
1196        if existing_files:
1197            default_vars_file = existing_files[0]
1198            sticky_vars.files.append(default_vars_file)
1199            print("Variables file %s not found,\n  using defaults in %s"
1200                  % (current_vars_file, default_vars_file))
1201        else:
1202            print("Error: cannot find variables file %s or "
1203                  "default file(s) %s"
1204                  % (current_vars_file, ' or '.join(default_vars_files)))
1205            Exit(1)
1206
1207    # Apply current variable settings to env
1208    sticky_vars.Update(env)
1209
1210    help_texts["local_vars"] += \
1211        "Build variables for %s:\n" % variant_dir \
1212                 + sticky_vars.GenerateHelpText(env)
1213
1214    # Process variable settings.
1215
1216    if not have_fenv and env['USE_FENV']:
1217        print("Warning: <fenv.h> not available; "
1218              "forcing USE_FENV to False in", variant_dir + ".")
1219        env['USE_FENV'] = False
1220
1221    if not env['USE_FENV']:
1222        print("Warning: No IEEE FP rounding mode control in",
1223              variant_dir + ".")
1224        print("         FP results may deviate slightly from other platforms.")
1225
1226    if not have_png and env['USE_PNG']:
1227        print("Warning: <png.h> not available; "
1228              "forcing USE_PNG to False in", variant_dir + ".")
1229        env['USE_PNG'] = False
1230
1231    if env['USE_PNG']:
1232        env.Append(LIBS=['png'])
1233
1234    if env['EFENCE']:
1235        env.Append(LIBS=['efence'])
1236
1237    if env['USE_KVM']:
1238        if not have_kvm:
1239            print("Warning: Can not enable KVM, host seems to "
1240                  "lack KVM support")
1241            env['USE_KVM'] = False
1242        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1243            print("Info: KVM support disabled due to unsupported host and "
1244                  "target ISA combination")
1245            env['USE_KVM'] = False
1246
1247    if env['USE_TUNTAP']:
1248        if not have_tuntap:
1249            print("Warning: Can't connect EtherTap with a tap device.")
1250            env['USE_TUNTAP'] = False
1251
1252    if env['BUILD_GPU']:
1253        env.Append(CPPDEFINES=['BUILD_GPU'])
1254
1255    # Warn about missing optional functionality
1256    if env['USE_KVM']:
1257        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1258            print("Warning: perf_event headers lack support for the "
1259                  "exclude_host attribute. KVM instruction counts will "
1260                  "be inaccurate.")
1261
1262    # Save sticky variable settings back to current variables file
1263    sticky_vars.Save(current_vars_file, env)
1264
1265    if env['USE_SSE2']:
1266        env.Append(CCFLAGS=['-msse2'])
1267
1268    # The src/SConscript file sets up the build rules in 'env' according
1269    # to the configured variables.  It returns a list of environments,
1270    # one for each variant build (debug, opt, etc.)
1271    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1272
1273# base help text
1274Help('''
1275Usage: scons [scons options] [build variables] [target(s)]
1276
1277Extra scons options:
1278%(options)s
1279
1280Global build variables:
1281%(global_vars)s
1282
1283%(local_vars)s
1284''' % help_texts)
1285