SConstruct revision 13577
1955SN/A# -*- mode:python -*-
2955SN/A
35871Snate@binkert.org# Copyright (c) 2013, 2015-2017 ARM Limited
41762SN/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
28955SN/A# contributors may be used to endorse or promote products derived from
292665Ssaidi@eecs.umich.edu# this software without specific prior written permission.
302665Ssaidi@eecs.umich.edu#
315863Snate@binkert.org# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
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
392632Sstever@eecs.umich.edu# 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
41955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
422632Sstever@eecs.umich.edu#
432632Sstever@eecs.umich.edu# Authors: Steve Reinhardt
442761Sstever@eecs.umich.edu#          Nathan Binkert
452632Sstever@eecs.umich.edu
462632Sstever@eecs.umich.edu###################################################
472632Sstever@eecs.umich.edu#
482761Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
492761Sstever@eecs.umich.edu#
502761Sstever@eecs.umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
512632Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
522632Sstever@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
562761Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
572761Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
582632Sstever@eecs.umich.edu# built for the same host system.
592632Sstever@eecs.umich.edu#
602632Sstever@eecs.umich.edu# Examples:
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
632632Sstever@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
642632Sstever@eecs.umich.edu#   % 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
685863Snate@binkert.org#   in a directory outside of the source tree.  The '-C' option tells
695863Snate@binkert.org#   scons to chdir to the specified directory to find this SConstruct
705863Snate@binkert.org#   file.
715863Snate@binkert.org#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
725863Snate@binkert.org#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
735863Snate@binkert.org#
745863Snate@binkert.org# You can use 'scons -H' to print scons options.  If you're in this
755863Snate@binkert.org# 'gem5' directory (or use -u or -C to tell scons where to find this
765863Snate@binkert.org# file), you can use 'scons -h' to print all the gem5-specific build
775863Snate@binkert.org# options as well.
785863Snate@binkert.org#
795863Snate@binkert.org###################################################
805863Snate@binkert.org
815863Snate@binkert.orgfrom __future__ import print_function
825863Snate@binkert.org
835863Snate@binkert.org# Global Python includes
845863Snate@binkert.orgimport itertools
855863Snate@binkert.orgimport os
865863Snate@binkert.orgimport re
875863Snate@binkert.orgimport shutil
885863Snate@binkert.orgimport subprocess
895863Snate@binkert.orgimport sys
905863Snate@binkert.org
915863Snate@binkert.orgfrom os import mkdir, environ
925863Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
935863Snate@binkert.orgfrom os.path import exists,  isdir, isfile
945863Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
955863Snate@binkert.orgfrom re import match
965863Snate@binkert.org
975863Snate@binkert.org# SCons includes
985863Snate@binkert.orgimport SCons
99955SN/Aimport SCons.Node
1005396Ssaidi@eecs.umich.edu
1015863Snate@binkert.orgfrom m5.util import compareVersions, readCommand
1025863Snate@binkert.org
1034202Sbinkertn@umich.eduhelp_texts = {
1045863Snate@binkert.org    "options" : "",
1055863Snate@binkert.org    "global_vars" : "",
1065863Snate@binkert.org    "local_vars" : ""
1075863Snate@binkert.org}
108955SN/A
1095273Sstever@gmail.comExport("help_texts")
1105871Snate@binkert.org
1115273Sstever@gmail.com
1125871Snate@binkert.org# There's a bug in scons in that (1) by default, the help texts from
1135863Snate@binkert.org# AddOption() are supposed to be displayed when you type 'scons -h'
1145863Snate@binkert.org# and (2) you can override the help displayed by 'scons -h' using the
1155863Snate@binkert.org# Help() function, but these two features are incompatible: once
1165871Snate@binkert.org# you've overridden the help text using Help(), there's no way to get
1175872Snate@binkert.org# at the help texts from AddOptions.  See:
1185872Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1195872Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1205871Snate@binkert.org# This hack lets us extract the help text from AddOptions and
1215871Snate@binkert.org# re-inject it via Help().  Ideally someday this bug will be fixed and
1225871Snate@binkert.org# we can just use AddOption directly.
1235871Snate@binkert.orgdef AddLocalOption(*args, **kwargs):
1245871Snate@binkert.org    col_width = 30
1255871Snate@binkert.org
1265871Snate@binkert.org    help = "  " + ", ".join(args)
1275871Snate@binkert.org    if "help" in kwargs:
1285871Snate@binkert.org        length = len(help)
1295871Snate@binkert.org        if length >= col_width:
1305871Snate@binkert.org            help += "\n" + " " * col_width
1315871Snate@binkert.org        else:
1325871Snate@binkert.org            help += " " * (col_width - length)
1335871Snate@binkert.org        help += kwargs["help"]
1345863Snate@binkert.org    help_texts["options"] += help + "\n"
1355227Ssaidi@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',
1445588Ssaidi@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',
1505396Ssaidi@eecs.umich.edu               help='Use the gold linker')
1515396Ssaidi@eecs.umich.eduAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1525396Ssaidi@eecs.umich.edu               help='Disable Link-Time Optimization for fast')
1535396Ssaidi@eecs.umich.eduAddLocalOption('--force-lto', dest='force_lto', action='store_true',
1545396Ssaidi@eecs.umich.edu               help='Use Link-Time Optimization instead of partial linking' +
1555396Ssaidi@eecs.umich.edu                    ' when the compiler doesn\'t support using them together.')
1565396Ssaidi@eecs.umich.eduAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1575396Ssaidi@eecs.umich.edu               help='Update test reference outputs')
1585396Ssaidi@eecs.umich.eduAddLocalOption('--verbose', dest='verbose', action='store_true',
1595871Snate@binkert.org               help='Print full tool command lines')
1605871Snate@binkert.orgAddLocalOption('--without-python', dest='without_python',
1616121Snate@binkert.org               action='store_true',
1625871Snate@binkert.org               help='Build without Python configuration support')
1635871Snate@binkert.orgAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1646003Snate@binkert.org               action='store_true',
1656003Snate@binkert.org               help='Disable linking against tcmalloc')
166955SN/AAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1675871Snate@binkert.org               help='Build with Undefined Behavior Sanitizer if available')
1685871Snate@binkert.orgAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1695871Snate@binkert.org               help='Build with Address Sanitizer if available')
1705871Snate@binkert.org
171955SN/Aif GetOption('no_lto') and GetOption('force_lto'):
1726121Snate@binkert.org    print('--no-lto and --force-lto are mutually exclusive')
1736121Snate@binkert.org    Exit(1)
1746121Snate@binkert.org
1751533SN/A########################################################################
1765871Snate@binkert.org#
1775871Snate@binkert.org# Set up the main build environment.
1785863Snate@binkert.org#
1795871Snate@binkert.org########################################################################
1805871Snate@binkert.org
1815871Snate@binkert.orgmain = Environment()
1825871Snate@binkert.org
1835871Snate@binkert.orgfrom gem5_scons import Transform
1845863Snate@binkert.orgfrom gem5_scons.util import get_termcap
1856121Snate@binkert.orgtermcap = get_termcap()
1865863Snate@binkert.org
1875871Snate@binkert.orgmain_dict_keys = main.Dictionary().keys()
1884678Snate@binkert.org
1894678Snate@binkert.org# Check that we have a C/C++ compiler
1904678Snate@binkert.orgif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
1914678Snate@binkert.org    print("No C++ compiler installed (package g++ on Ubuntu and RedHat)")
1924678Snate@binkert.org    Exit(1)
1934678Snate@binkert.org
1944678Snate@binkert.org###################################################
1954678Snate@binkert.org#
1964678Snate@binkert.org# Figure out which configurations to set up based on the path(s) of
1974678Snate@binkert.org# the target(s).
1984678Snate@binkert.org#
1994678Snate@binkert.org###################################################
2006121Snate@binkert.org
2014678Snate@binkert.org# Find default configuration & binary.
2025871Snate@binkert.orgDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
2035871Snate@binkert.org
2045871Snate@binkert.org# helper function: find last occurrence of element in list
2055871Snate@binkert.orgdef rfind(l, elt, offs = -1):
2065871Snate@binkert.org    for i in range(len(l)+offs, 0, -1):
2075871Snate@binkert.org        if l[i] == elt:
2085871Snate@binkert.org            return i
2095871Snate@binkert.org    raise ValueError, "element not found"
2105871Snate@binkert.org
2115871Snate@binkert.org# Take a list of paths (or SCons Nodes) and return a list with all
2125871Snate@binkert.org# paths made absolute and ~-expanded.  Paths will be interpreted
2135871Snate@binkert.org# relative to the launch directory unless a different root is provided
2145871Snate@binkert.orgdef makePathListAbsolute(path_list, root=GetLaunchDir()):
2155990Ssaidi@eecs.umich.edu    return [abspath(joinpath(root, expanduser(str(p))))
2165871Snate@binkert.org            for p in path_list]
2175871Snate@binkert.org
2185871Snate@binkert.org# Each target must have 'build' in the interior of the path; the
2194678Snate@binkert.org# directory below this will determine the build parameters.  For
2206121Snate@binkert.org# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2215871Snate@binkert.org# recognize that ALPHA_SE specifies the configuration because it
2225871Snate@binkert.org# follow 'build' in the build path.
2235871Snate@binkert.org
2245871Snate@binkert.org# The funky assignment to "[:]" is needed to replace the list contents
2255871Snate@binkert.org# in place rather than reassign the symbol to a new list, which
2265871Snate@binkert.org# doesn't work (obviously!).
2275871Snate@binkert.orgBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
2285871Snate@binkert.org
2295871Snate@binkert.org# Generate a list of the unique build roots and configs that the
2304678Snate@binkert.org# collected targets reference.
2315871Snate@binkert.orgvariant_paths = []
2324678Snate@binkert.orgbuild_root = None
2335871Snate@binkert.orgfor t in BUILD_TARGETS:
2345871Snate@binkert.org    path_dirs = t.split('/')
2355871Snate@binkert.org    try:
2365871Snate@binkert.org        build_top = rfind(path_dirs, 'build', -2)
2375871Snate@binkert.org    except:
2385871Snate@binkert.org        print("Error: no non-leaf 'build' dir found on target path", t)
2395871Snate@binkert.org        Exit(1)
2405871Snate@binkert.org    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2415871Snate@binkert.org    if not build_root:
2426121Snate@binkert.org        build_root = this_build_root
2436121Snate@binkert.org    else:
2445863Snate@binkert.org        if this_build_root != build_root:
245955SN/A            print("Error: build targets not under same build root\n"
246955SN/A                  "  %s\n  %s" % (build_root, this_build_root))
2472632Sstever@eecs.umich.edu            Exit(1)
2482632Sstever@eecs.umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
249955SN/A    if variant_path not in variant_paths:
250955SN/A        variant_paths.append(variant_path)
251955SN/A
252955SN/A# Make sure build_root exists (might not if this is the first build there)
2535863Snate@binkert.orgif not isdir(build_root):
254955SN/A    mkdir(build_root)
2552632Sstever@eecs.umich.edumain['BUILDROOT'] = build_root
2562632Sstever@eecs.umich.edu
2572632Sstever@eecs.umich.eduExport('main')
2582632Sstever@eecs.umich.edu
2592632Sstever@eecs.umich.edumain.SConsignFile(joinpath(build_root, "sconsign"))
2602632Sstever@eecs.umich.edu
2612632Sstever@eecs.umich.edu# Default duplicate option is to use hard links, but this messes up
2622632Sstever@eecs.umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
2632632Sstever@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
2642632Sstever@eecs.umich.edu# (soft) links work better.
2652632Sstever@eecs.umich.edumain.SetOption('duplicate', 'soft-copy')
2662632Sstever@eecs.umich.edu
2672632Sstever@eecs.umich.edu#
2683718Sstever@eecs.umich.edu# Set up global sticky variables... these are common to an entire build
2693718Sstever@eecs.umich.edu# tree (not specific to a particular build like ALPHA_SE)
2703718Sstever@eecs.umich.edu#
2713718Sstever@eecs.umich.edu
2723718Sstever@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
2735863Snate@binkert.org
2745863Snate@binkert.orgglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
2753718Sstever@eecs.umich.edu
2763718Sstever@eecs.umich.eduglobal_vars.AddVariables(
2776121Snate@binkert.org    ('CC', 'C compiler', environ.get('CC', main['CC'])),
2785863Snate@binkert.org    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
2793718Sstever@eecs.umich.edu    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
2803718Sstever@eecs.umich.edu    ('BATCH', 'Use batch pool for build and tests', False),
2812634Sstever@eecs.umich.edu    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
2822634Sstever@eecs.umich.edu    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
2835863Snate@binkert.org    ('EXTRAS', 'Add extra directories to the compilation', '')
2842638Sstever@eecs.umich.edu    )
2852632Sstever@eecs.umich.edu
2862632Sstever@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
2872632Sstever@eecs.umich.eduglobal_vars.Update(main)
2882632Sstever@eecs.umich.eduhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
2892632Sstever@eecs.umich.edu
2902632Sstever@eecs.umich.edu# Save sticky variable settings back to current variables file
2911858SN/Aglobal_vars.Save(global_vars_file, main)
2923716Sstever@eecs.umich.edu
2932638Sstever@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
2942638Sstever@eecs.umich.edu# look for sources etc.  This list is exported as extras_dir_list.
2952638Sstever@eecs.umich.edubase_dir = main.srcdir.abspath
2962638Sstever@eecs.umich.eduif main['EXTRAS']:
2972638Sstever@eecs.umich.edu    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
2982638Sstever@eecs.umich.eduelse:
2992638Sstever@eecs.umich.edu    extras_dir_list = []
3005863Snate@binkert.org
3015863Snate@binkert.orgExport('base_dir')
3025863Snate@binkert.orgExport('extras_dir_list')
303955SN/A
3045341Sstever@gmail.com# the ext directory should be on the #includes path
3055341Sstever@gmail.commain.Append(CPPPATH=[Dir('ext')])
3065863Snate@binkert.org
3075341Sstever@gmail.com# Add shared top-level headers
3086121Snate@binkert.orgmain.Prepend(CPPPATH=Dir('include'))
3094494Ssaidi@eecs.umich.edu
3106121Snate@binkert.orgif GetOption('verbose'):
3111105SN/A    def MakeAction(action, string, *args, **kwargs):
3122667Sstever@eecs.umich.edu        return Action(action, *args, **kwargs)
3132667Sstever@eecs.umich.eduelse:
3142667Sstever@eecs.umich.edu    MakeAction = Action
3152667Sstever@eecs.umich.edu    main['CCCOMSTR']        = Transform("CC")
3166121Snate@binkert.org    main['CXXCOMSTR']       = Transform("CXX")
3172667Sstever@eecs.umich.edu    main['ASCOMSTR']        = Transform("AS")
3185341Sstever@gmail.com    main['ARCOMSTR']        = Transform("AR", 0)
3195863Snate@binkert.org    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")
3235863Snate@binkert.org    main['SHCCCOMSTR']      = Transform("SHCC")
3245341Sstever@gmail.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
3255341Sstever@gmail.comExport('MakeAction')
3265341Sstever@gmail.com
3275863Snate@binkert.org# Initialize the Link-Time Optimization (LTO) flags
3285341Sstever@gmail.commain['LTO_CCFLAGS'] = []
3295341Sstever@gmail.commain['LTO_LDFLAGS'] = []
3305341Sstever@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'] = []
3365341Sstever@gmail.com
3375341Sstever@gmail.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
3385863Snate@binkert.orgCXX_V = readCommand([main['CXX'],'-V'], exception=False)
3395341Sstever@gmail.com
3405863Snate@binkert.orgmain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3415341Sstever@gmail.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
3425863Snate@binkert.orgif main['GCC'] + main['CLANG'] > 1:
3436121Snate@binkert.org    print('Error: How can we have two at the same time?')
3446121Snate@binkert.org    Exit(1)
3455397Ssaidi@eecs.umich.edu
3465397Ssaidi@eecs.umich.edu# Set up default C++ compiler flags
3475341Sstever@gmail.comif main['GCC'] or main['CLANG']:
3485341Sstever@gmail.com    # As gcc and clang share many flags, do the common parts here
3495341Sstever@gmail.com    main.Append(CCFLAGS=['-pipe'])
3505341Sstever@gmail.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
3515341Sstever@gmail.com    # Enable -Wall and -Wextra and then disable the few warnings that
3525341Sstever@gmail.com    # we consistently violate
3535341Sstever@gmail.com    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
3545341Sstever@gmail.com                         '-Wno-sign-compare', '-Wno-unused-parameter'])
3555863Snate@binkert.org    # We always compile using C++11
3565341Sstever@gmail.com    main.Append(CXXFLAGS=['-std=c++11'])
3575341Sstever@gmail.com    if sys.platform.startswith('freebsd'):
3586121Snate@binkert.org        main.Append(CCFLAGS=['-I/usr/local/include'])
3595341Sstever@gmail.com        main.Append(CXXFLAGS=['-I/usr/local/include'])
3606121Snate@binkert.org
3616121Snate@binkert.org    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
3625341Sstever@gmail.com    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
3635863Snate@binkert.org    if GetOption('gold_linker'):
3646121Snate@binkert.org        main.Append(LINKFLAGS='-fuse-ld=gold')
3655341Sstever@gmail.com    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
3665863Snate@binkert.org    shared_partial_flags = ['-r', '-nostdlib']
3675341Sstever@gmail.com    main.Append(PSHLINKFLAGS=shared_partial_flags)
3686121Snate@binkert.org    main.Append(PLINKFLAGS=shared_partial_flags)
3696121Snate@binkert.org
3706121Snate@binkert.org    # Treat warnings as errors but white list some warnings that we
3715742Snate@binkert.org    # want to allow (e.g., deprecation warnings).
3725742Snate@binkert.org    main.Append(CCFLAGS=['-Werror',
3735341Sstever@gmail.com                         '-Wno-error=deprecated-declarations',
3745742Snate@binkert.org                         '-Wno-error=deprecated',
3755742Snate@binkert.org                        ])
3765341Sstever@gmail.comelse:
3776017Snate@binkert.org    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
3786121Snate@binkert.org    print("Don't know what compiler options to use for your compiler.")
3796017Snate@binkert.org    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
3802632Sstever@eecs.umich.edu    print(termcap.Yellow + '       version:' + termcap.Normal, end = ' ')
3816121Snate@binkert.org    if not CXX_version:
3825871Snate@binkert.org        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
3836121Snate@binkert.org              termcap.Normal)
3846121Snate@binkert.org    else:
3855871Snate@binkert.org        print(CXX_version.replace('\n', '<nl>'))
3866121Snate@binkert.org    print("       If you're trying to use a compiler other than GCC")
3876121Snate@binkert.org    print("       or clang, there appears to be something wrong with your")
3886121Snate@binkert.org    print("       environment.")
3896121Snate@binkert.org    print("       ")
3903940Ssaidi@eecs.umich.edu    print("       If you are trying to use a compiler other than those listed")
3913918Ssaidi@eecs.umich.edu    print("       above you will need to ease fix SConstruct and ")
3923918Ssaidi@eecs.umich.edu    print("       src/SConscript to support that compiler.")
3931858SN/A    Exit(1)
3946121Snate@binkert.org
3956121Snate@binkert.orgif main['GCC']:
3966121Snate@binkert.org    # Check for a supported version of gcc. >= 4.8 is chosen for its
3976143Snate@binkert.org    # level of c++11 support. See
3986121Snate@binkert.org    # http://gcc.gnu.org/projects/cxx0x.html for details.
3996121Snate@binkert.org    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
4003940Ssaidi@eecs.umich.edu    if compareVersions(gcc_version, "4.8") < 0:
4016121Snate@binkert.org        print('Error: gcc version 4.8 or newer required.')
4026121Snate@binkert.org        print('       Installed version: ', gcc_version)
4036121Snate@binkert.org        Exit(1)
4046121Snate@binkert.org
4056121Snate@binkert.org    main['GCC_VERSION'] = gcc_version
4066121Snate@binkert.org
4076121Snate@binkert.org    if compareVersions(gcc_version, '4.9') >= 0:
4083918Ssaidi@eecs.umich.edu        # Incremental linking with LTO is currently broken in gcc versions
4093918Ssaidi@eecs.umich.edu        # 4.9 and above. A version where everything works completely hasn't
4103940Ssaidi@eecs.umich.edu        # yet been identified.
4113918Ssaidi@eecs.umich.edu        #
4123918Ssaidi@eecs.umich.edu        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
4136157Snate@binkert.org        main['BROKEN_INCREMENTAL_LTO'] = True
4146157Snate@binkert.org    if compareVersions(gcc_version, '6.0') >= 0:
4156157Snate@binkert.org        # gcc versions 6.0 and greater accept an -flinker-output flag which
4166157Snate@binkert.org        # selects what type of output the linker should generate. This is
4175397Ssaidi@eecs.umich.edu        # necessary for incremental lto to work, but is also broken in
4185397Ssaidi@eecs.umich.edu        # current versions of gcc. It may not be necessary in future
4196121Snate@binkert.org        # versions. We add it here since it might be, and as a reminder that
4206121Snate@binkert.org        # it exists. It's excluded if lto is being forced.
4216121Snate@binkert.org        #
4226121Snate@binkert.org        # https://gcc.gnu.org/gcc-6/changes.html
4236121Snate@binkert.org        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
4246121Snate@binkert.org        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
4255397Ssaidi@eecs.umich.edu        if not GetOption('force_lto'):
4261851SN/A            main.Append(PSHLINKFLAGS='-flinker-output=rel')
4271851SN/A            main.Append(PLINKFLAGS='-flinker-output=rel')
4286121Snate@binkert.org
429955SN/A    # Make sure we warn if the user has requested to compile with the
4303053Sstever@eecs.umich.edu    # Undefined Benahvior Sanitizer and this version of gcc does not
4316121Snate@binkert.org    # support it.
4323053Sstever@eecs.umich.edu    if GetOption('with_ubsan') and \
4333053Sstever@eecs.umich.edu            compareVersions(gcc_version, '4.9') < 0:
4343053Sstever@eecs.umich.edu        print(termcap.Yellow + termcap.Bold +
4353053Sstever@eecs.umich.edu            'Warning: UBSan is only supported using gcc 4.9 and later.' +
4363053Sstever@eecs.umich.edu            termcap.Normal)
4375871Snate@binkert.org
4383053Sstever@eecs.umich.edu    disable_lto = GetOption('no_lto')
4394742Sstever@eecs.umich.edu    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
4404742Sstever@eecs.umich.edu            not GetOption('force_lto'):
4413053Sstever@eecs.umich.edu        print(termcap.Yellow + termcap.Bold +
4423053Sstever@eecs.umich.edu            'Warning: Your compiler doesn\'t support incremental linking' +
4433053Sstever@eecs.umich.edu            ' and lto at the same time, so lto is being disabled. To force' +
4443053Sstever@eecs.umich.edu            ' lto on anyway, use the --force-lto option. That will disable' +
4453053Sstever@eecs.umich.edu            ' partial linking.' +
4463053Sstever@eecs.umich.edu            termcap.Normal)
4473053Sstever@eecs.umich.edu        disable_lto = True
4483053Sstever@eecs.umich.edu
4493053Sstever@eecs.umich.edu    # Add the appropriate Link-Time Optimization (LTO) flags
4502667Sstever@eecs.umich.edu    # unless LTO is explicitly turned off. Note that these flags
4514554Sbinkertn@umich.edu    # are only used by the fast target.
4526121Snate@binkert.org    if not disable_lto:
4532667Sstever@eecs.umich.edu        # Pass the LTO flag when compiling to produce GIMPLE
4544554Sbinkertn@umich.edu        # output, we merely create the flags here and only append
4554554Sbinkertn@umich.edu        # them later
4564554Sbinkertn@umich.edu        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4576121Snate@binkert.org
4584554Sbinkertn@umich.edu        # Use the same amount of jobs for LTO as we are running
4594554Sbinkertn@umich.edu        # scons with
4604554Sbinkertn@umich.edu        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4614781Snate@binkert.org
4624554Sbinkertn@umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
4634554Sbinkertn@umich.edu                                  '-fno-builtin-realloc', '-fno-builtin-free'])
4642667Sstever@eecs.umich.edu
4654554Sbinkertn@umich.edu    # The address sanitizer is available for gcc >= 4.8
4664554Sbinkertn@umich.edu    if GetOption('with_asan'):
4674554Sbinkertn@umich.edu        if GetOption('with_ubsan') and \
4684554Sbinkertn@umich.edu                compareVersions(main['GCC_VERSION'], '4.9') >= 0:
4692667Sstever@eecs.umich.edu            main.Append(CCFLAGS=['-fsanitize=address,undefined',
4704554Sbinkertn@umich.edu                                 '-fno-omit-frame-pointer'],
4712667Sstever@eecs.umich.edu                        LINKFLAGS='-fsanitize=address,undefined')
4724554Sbinkertn@umich.edu        else:
4736121Snate@binkert.org            main.Append(CCFLAGS=['-fsanitize=address',
4742667Sstever@eecs.umich.edu                                 '-fno-omit-frame-pointer'],
4755522Snate@binkert.org                        LINKFLAGS='-fsanitize=address')
4765522Snate@binkert.org    # Only gcc >= 4.9 supports UBSan, so check both the version
4775522Snate@binkert.org    # and the command-line option before adding the compiler and
4785522Snate@binkert.org    # linker flags.
4795522Snate@binkert.org    elif GetOption('with_ubsan') and \
4805522Snate@binkert.org            compareVersions(main['GCC_VERSION'], '4.9') >= 0:
4815522Snate@binkert.org        main.Append(CCFLAGS='-fsanitize=undefined')
4825522Snate@binkert.org        main.Append(LINKFLAGS='-fsanitize=undefined')
4835522Snate@binkert.org
4845522Snate@binkert.orgelif main['CLANG']:
4855522Snate@binkert.org    # Check for a supported version of clang, >= 3.1 is needed to
4865522Snate@binkert.org    # support similar features as gcc 4.8. See
4875522Snate@binkert.org    # http://clang.llvm.org/cxx_status.html for details
4885522Snate@binkert.org    clang_version_re = re.compile(".* version (\d+\.\d+)")
4895522Snate@binkert.org    clang_version_match = clang_version_re.search(CXX_version)
4905522Snate@binkert.org    if (clang_version_match):
4915522Snate@binkert.org        clang_version = clang_version_match.groups()[0]
4925522Snate@binkert.org        if compareVersions(clang_version, "3.1") < 0:
4935522Snate@binkert.org            print('Error: clang version 3.1 or newer required.')
4945522Snate@binkert.org            print('       Installed version:', clang_version)
4955522Snate@binkert.org            Exit(1)
4965522Snate@binkert.org    else:
4975522Snate@binkert.org        print('Error: Unable to determine clang version.')
4985522Snate@binkert.org        Exit(1)
4995522Snate@binkert.org
5005522Snate@binkert.org    # clang has a few additional warnings that we disable, extraneous
5012638Sstever@eecs.umich.edu    # parantheses are allowed due to Ruby's printing of the AST,
5022638Sstever@eecs.umich.edu    # finally self assignments are allowed as the generated CPU code
5036121Snate@binkert.org    # is relying on this
5043716Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wno-parentheses',
5055522Snate@binkert.org                         '-Wno-self-assign',
5065522Snate@binkert.org                         # Some versions of libstdc++ (4.8?) seem to
5075522Snate@binkert.org                         # use struct hash and class hash
5085522Snate@binkert.org                         # interchangeably.
5095522Snate@binkert.org                         '-Wno-mismatched-tags',
5105522Snate@binkert.org                         ])
5111858SN/A
5125227Ssaidi@eecs.umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
5135227Ssaidi@eecs.umich.edu
5145227Ssaidi@eecs.umich.edu    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
5155227Ssaidi@eecs.umich.edu    # opposed to libstdc++, as the later is dated.
5165227Ssaidi@eecs.umich.edu    if sys.platform == "darwin":
5175863Snate@binkert.org        main.Append(CXXFLAGS=['-stdlib=libc++'])
5186121Snate@binkert.org        main.Append(LIBS=['c++'])
5196121Snate@binkert.org
5206121Snate@binkert.org    # On FreeBSD we need libthr.
5216121Snate@binkert.org    if sys.platform.startswith('freebsd'):
5225227Ssaidi@eecs.umich.edu        main.Append(LIBS=['thr'])
5235227Ssaidi@eecs.umich.edu
5245227Ssaidi@eecs.umich.edu    # We require clang >= 3.1, so there is no need to check any
5255204Sstever@gmail.com    # versions here.
5265204Sstever@gmail.com    if GetOption('with_ubsan'):
5275204Sstever@gmail.com        if GetOption('with_asan'):
5285204Sstever@gmail.com            main.Append(CCFLAGS=['-fsanitize=address,undefined',
5295204Sstever@gmail.com                                 '-fno-omit-frame-pointer'],
5305204Sstever@gmail.com                       LINKFLAGS='-fsanitize=address,undefined')
5315204Sstever@gmail.com        else:
5325204Sstever@gmail.com            main.Append(CCFLAGS='-fsanitize=undefined',
5335204Sstever@gmail.com                        LINKFLAGS='-fsanitize=undefined')
5345204Sstever@gmail.com
5355204Sstever@gmail.com    elif GetOption('with_asan'):
5365204Sstever@gmail.com        main.Append(CCFLAGS=['-fsanitize=address',
5375204Sstever@gmail.com                             '-fno-omit-frame-pointer'],
5385204Sstever@gmail.com                   LINKFLAGS='-fsanitize=address')
5395204Sstever@gmail.com
5405204Sstever@gmail.comelse:
5415204Sstever@gmail.com    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
5426121Snate@binkert.org    print("Don't know what compiler options to use for your compiler.")
5435204Sstever@gmail.com    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
5443118Sstever@eecs.umich.edu    print(termcap.Yellow + '       version:' + termcap.Normal, end=' ')
5453118Sstever@eecs.umich.edu    if not CXX_version:
5463118Sstever@eecs.umich.edu        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
5473118Sstever@eecs.umich.edu              termcap.Normal)
5483118Sstever@eecs.umich.edu    else:
5495863Snate@binkert.org        print(CXX_version.replace('\n', '<nl>'))
5503118Sstever@eecs.umich.edu    print("       If you're trying to use a compiler other than GCC")
5515863Snate@binkert.org    print("       or clang, there appears to be something wrong with your")
5523118Sstever@eecs.umich.edu    print("       environment.")
5535863Snate@binkert.org    print("       ")
5545863Snate@binkert.org    print("       If you are trying to use a compiler other than those listed")
5555863Snate@binkert.org    print("       above you will need to ease fix SConstruct and ")
5565863Snate@binkert.org    print("       src/SConscript to support that compiler.")
5575863Snate@binkert.org    Exit(1)
5585863Snate@binkert.org
5595863Snate@binkert.org# Set up common yacc/bison flags (needed for Ruby)
5605863Snate@binkert.orgmain['YACCFLAGS'] = '-d'
5616003Snate@binkert.orgmain['YACCHXXFILESUFFIX'] = '.hh'
5625863Snate@binkert.org
5635863Snate@binkert.org# Do this after we save setting back, or else we'll tack on an
5645863Snate@binkert.org# extra 'qdo' every time we run scons.
5656120Snate@binkert.orgif main['BATCH']:
5665863Snate@binkert.org    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
5675863Snate@binkert.org    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
5685863Snate@binkert.org    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
5696120Snate@binkert.org    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
5706120Snate@binkert.org    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
5715863Snate@binkert.org
5725863Snate@binkert.orgif sys.platform == 'cygwin':
5736120Snate@binkert.org    # cygwin has some header file issues...
5745863Snate@binkert.org    main.Append(CCFLAGS=["-Wno-uninitialized"])
5756121Snate@binkert.org
5766121Snate@binkert.org# Check for the protobuf compiler
5775863Snate@binkert.orgprotoc_version = readCommand([main['PROTOC'], '--version'],
5785863Snate@binkert.org                             exception='').split()
5793118Sstever@eecs.umich.edu
5805863Snate@binkert.org# First two words should be "libprotoc x.y.z"
5813118Sstever@eecs.umich.eduif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
5823118Sstever@eecs.umich.edu    print(termcap.Yellow + termcap.Bold +
5835863Snate@binkert.org        'Warning: Protocol buffer compiler (protoc) not found.\n' +
5845863Snate@binkert.org        '         Please install protobuf-compiler for tracing support.' +
5855863Snate@binkert.org        termcap.Normal)
5865863Snate@binkert.org    main['PROTOC'] = False
5873118Sstever@eecs.umich.eduelse:
5883483Ssaidi@eecs.umich.edu    # Based on the availability of the compress stream wrappers,
5893494Ssaidi@eecs.umich.edu    # require 2.1.0
5903494Ssaidi@eecs.umich.edu    min_protoc_version = '2.1.0'
5913483Ssaidi@eecs.umich.edu    if compareVersions(protoc_version[1], min_protoc_version) < 0:
5923483Ssaidi@eecs.umich.edu        print(termcap.Yellow + termcap.Bold +
5933483Ssaidi@eecs.umich.edu            'Warning: protoc version', min_protoc_version,
5943053Sstever@eecs.umich.edu            'or newer required.\n' +
5953053Sstever@eecs.umich.edu            '         Installed version:', protoc_version[1],
5963918Ssaidi@eecs.umich.edu            termcap.Normal)
5973053Sstever@eecs.umich.edu        main['PROTOC'] = False
5983053Sstever@eecs.umich.edu    else:
5993053Sstever@eecs.umich.edu        # Attempt to determine the appropriate include path and
6003053Sstever@eecs.umich.edu        # library path using pkg-config, that means we also need to
6013053Sstever@eecs.umich.edu        # check for pkg-config. Note that it is possible to use
6021858SN/A        # protobuf without the involvement of pkg-config. Later on we
6031858SN/A        # check go a library config check and at that point the test
6041858SN/A        # will fail if libprotobuf cannot be found.
6051858SN/A        if readCommand(['pkg-config', '--version'], exception=''):
6061858SN/A            try:
6071858SN/A                # Attempt to establish what linking flags to add for protobuf
6085863Snate@binkert.org                # using pkg-config
6095863Snate@binkert.org                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
6101859SN/A            except:
6115863Snate@binkert.org                print(termcap.Yellow + termcap.Bold +
6121858SN/A                    'Warning: pkg-config could not get protobuf flags.' +
6135863Snate@binkert.org                    termcap.Normal)
6141858SN/A
6151859SN/A
6161859SN/A# Check for 'timeout' from GNU coreutils. If present, regressions will
6175863Snate@binkert.org# be run with a time limit. We require version 8.13 since we rely on
6183053Sstever@eecs.umich.edu# support for the '--foreground' option.
6193053Sstever@eecs.umich.eduif sys.platform.startswith('freebsd'):
6203053Sstever@eecs.umich.edu    timeout_lines = readCommand(['gtimeout', '--version'],
6213053Sstever@eecs.umich.edu                                exception='').splitlines()
6221859SN/Aelse:
6231859SN/A    timeout_lines = readCommand(['timeout', '--version'],
6241859SN/A                                exception='').splitlines()
6251859SN/A# Get the first line and tokenize it
6261859SN/Atimeout_version = timeout_lines[0].split() if timeout_lines else []
6271859SN/Amain['TIMEOUT'] =  timeout_version and \
6281859SN/A    compareVersions(timeout_version[-1], '8.13') >= 0
6291859SN/A
6301862SN/A# Add a custom Check function to test for structure members.
6311859SN/Adef CheckMember(context, include, decl, member, include_quotes="<>"):
6321859SN/A    context.Message("Checking for member %s in %s..." %
6331859SN/A                    (member, decl))
6345863Snate@binkert.org    text = """
6355863Snate@binkert.org#include %(header)s
6365863Snate@binkert.orgint main(){
6375863Snate@binkert.org  %(decl)s test;
6386121Snate@binkert.org  (void)test.%(member)s;
6391858SN/A  return 0;
6405863Snate@binkert.org};
6415863Snate@binkert.org""" % { "header" : include_quotes[0] + include + include_quotes[1],
6425863Snate@binkert.org        "decl" : decl,
6435863Snate@binkert.org        "member" : member,
6445863Snate@binkert.org        }
6452139SN/A
6464202Sbinkertn@umich.edu    ret = context.TryCompile(text, extension=".cc")
6474202Sbinkertn@umich.edu    context.Result(ret)
6482139SN/A    return ret
6492155SN/A
6504202Sbinkertn@umich.edu# Platform-specific configuration.  Note again that we assume that all
6514202Sbinkertn@umich.edu# builds under a given build root run on the same host platform.
6524202Sbinkertn@umich.educonf = Configure(main,
6532155SN/A                 conf_dir = joinpath(build_root, '.scons_config'),
6545863Snate@binkert.org                 log_file = joinpath(build_root, 'scons_config.log'),
6551869SN/A                 custom_tests = {
6561869SN/A        'CheckMember' : CheckMember,
6575863Snate@binkert.org        })
6585863Snate@binkert.org
6594202Sbinkertn@umich.edu# Check if we should compile a 64 bit binary on Mac OS X/Darwin
6606108Snate@binkert.orgtry:
6616108Snate@binkert.org    import platform
6626108Snate@binkert.org    uname = platform.uname()
6636108Snate@binkert.org    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
6645863Snate@binkert.org        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
6655863Snate@binkert.org            main.Append(CCFLAGS=['-arch', 'x86_64'])
6665863Snate@binkert.org            main.Append(CFLAGS=['-arch', 'x86_64'])
6674202Sbinkertn@umich.edu            main.Append(LINKFLAGS=['-arch', 'x86_64'])
6684202Sbinkertn@umich.edu            main.Append(ASFLAGS=['-arch', 'x86_64'])
6695863Snate@binkert.orgexcept:
6705742Snate@binkert.org    pass
6715742Snate@binkert.org
6725341Sstever@gmail.com# Recent versions of scons substitute a "Null" object for Configure()
6735342Sstever@gmail.com# when configuration isn't necessary, e.g., if the "--help" option is
6745342Sstever@gmail.com# present.  Unfortuantely this Null object always returns false,
6754202Sbinkertn@umich.edu# breaking all our configuration checks.  We replace it with our own
6764202Sbinkertn@umich.edu# more optimistic null object that returns True instead.
6774202Sbinkertn@umich.eduif not conf:
6784202Sbinkertn@umich.edu    def NullCheck(*args, **kwargs):
6794202Sbinkertn@umich.edu        return True
6805863Snate@binkert.org
6815863Snate@binkert.org    class NullConf:
6825863Snate@binkert.org        def __init__(self, env):
6835863Snate@binkert.org            self.env = env
6845863Snate@binkert.org        def Finish(self):
6855863Snate@binkert.org            return self.env
6865863Snate@binkert.org        def __getattr__(self, mname):
6875863Snate@binkert.org            return NullCheck
6885863Snate@binkert.org
6895863Snate@binkert.org    conf = NullConf(main)
6905863Snate@binkert.org
6915863Snate@binkert.org# Cache build files in the supplied directory.
6925863Snate@binkert.orgif main['M5_BUILD_CACHE']:
6935863Snate@binkert.org    print('Using build cache located at', main['M5_BUILD_CACHE'])
6945863Snate@binkert.org    CacheDir(main['M5_BUILD_CACHE'])
6955863Snate@binkert.org
6965863Snate@binkert.orgmain['USE_PYTHON'] = not GetOption('without_python')
6975863Snate@binkert.orgif main['USE_PYTHON']:
6985863Snate@binkert.org    # Find Python include and library directories for embedding the
6995863Snate@binkert.org    # interpreter. We rely on python-config to resolve the appropriate
7005952Ssaidi@eecs.umich.edu    # includes and linker flags. ParseConfig does not seem to understand
7011869SN/A    # the more exotic linker flags such as -Xlinker and -export-dynamic so
7021858SN/A    # we add them explicitly below. If you want to link in an alternate
7035863Snate@binkert.org    # version of python, see above for instructions on how to invoke
7045863Snate@binkert.org    # scons with the appropriate PATH set.
7051869SN/A    #
7061858SN/A    # First we check if python2-config exists, else we use python-config
7075863Snate@binkert.org    python_config = readCommand(['which', 'python2-config'],
7086108Snate@binkert.org                                exception='').strip()
7096108Snate@binkert.org    if not os.path.exists(python_config):
7106108Snate@binkert.org        python_config = readCommand(['which', 'python-config'],
7111858SN/A                                    exception='').strip()
712955SN/A    py_includes = readCommand([python_config, '--includes'],
713955SN/A                              exception='').split()
7141869SN/A    py_includes = filter(lambda s: match(r'.*\/include\/.*',s), py_includes)
7151869SN/A    # Strip the -I from the include folders before adding them to the
7161869SN/A    # CPPPATH
7171869SN/A    py_includes = map(lambda s: s[2:] if s.startswith('-I') else s, py_includes)
7181869SN/A    main.Append(CPPPATH=py_includes)
7195863Snate@binkert.org
7205863Snate@binkert.org    # Read the linker flags and split them into libraries and other link
7215863Snate@binkert.org    # flags. The libraries are added later through the call the CheckLib.
7221869SN/A    py_ld_flags = readCommand([python_config, '--ldflags'],
7235863Snate@binkert.org        exception='').split()
7241869SN/A    py_libs = []
7255863Snate@binkert.org    for lib in py_ld_flags:
7261869SN/A         if not lib.startswith('-l'):
7271869SN/A             main.Append(LINKFLAGS=[lib])
7281869SN/A         else:
7291869SN/A             lib = lib[2:]
7301869SN/A             if lib not in py_libs:
7315863Snate@binkert.org                 py_libs.append(lib)
7325863Snate@binkert.org
7331869SN/A    # verify that this stuff works
7341869SN/A    if not conf.CheckHeader('Python.h', '<>'):
7351869SN/A        print("Error: Check failed for Python.h header in", py_includes)
7361869SN/A        print("Two possible reasons:")
7371869SN/A        print("1. Python headers are not installed (You can install the "
7381869SN/A              "package python-dev on Ubuntu and RedHat)")
7391869SN/A        print("2. SCons is using a wrong C compiler. This can happen if "
7405863Snate@binkert.org              "CC has the wrong value.")
7415863Snate@binkert.org        print("CC = %s" % main['CC'])
7421869SN/A        Exit(1)
7435863Snate@binkert.org
7445863Snate@binkert.org    for lib in py_libs:
7453356Sbinkertn@umich.edu        if not conf.CheckLib(lib):
7463356Sbinkertn@umich.edu            print("Error: can't find library %s required by python" % lib)
7473356Sbinkertn@umich.edu            Exit(1)
7483356Sbinkertn@umich.edu
7493356Sbinkertn@umich.edu# On Solaris you need to use libsocket for socket ops
7504781Snate@binkert.orgif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7515863Snate@binkert.org   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7525863Snate@binkert.org       print("Can't find library with socket calls (e.g. accept())")
7531869SN/A       Exit(1)
7541869SN/A
7551869SN/A# Check for zlib.  If the check passes, libz will be automatically
7566121Snate@binkert.org# added to the LIBS environment variable.
7571869SN/Aif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
7582638Sstever@eecs.umich.edu    print('Error: did not find needed zlib compression library '
7596121Snate@binkert.org          'and/or zlib.h header file.')
7606121Snate@binkert.org    print('       Please install zlib and try again.')
7612638Sstever@eecs.umich.edu    Exit(1)
7625749Scws3k@cs.virginia.edu
7636121Snate@binkert.org# If we have the protobuf compiler, also make sure we have the
7646121Snate@binkert.org# development libraries. If the check passes, libprotobuf will be
7655749Scws3k@cs.virginia.edu# automatically added to the LIBS environment variable. After
7661869SN/A# this, we can use the HAVE_PROTOBUF flag to determine if we have
7671869SN/A# got both protoc and libprotobuf available.
7683546Sgblack@eecs.umich.edumain['HAVE_PROTOBUF'] = main['PROTOC'] and \
7693546Sgblack@eecs.umich.edu    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
7703546Sgblack@eecs.umich.edu                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
7713546Sgblack@eecs.umich.edu
7726121Snate@binkert.org# Valgrind gets much less confused if you tell it when you're using
7735863Snate@binkert.org# alternative stacks.
7743546Sgblack@eecs.umich.edumain['HAVE_VALGRIND'] = conf.CheckCHeader('valgrind/valgrind.h')
7753546Sgblack@eecs.umich.edu
7763546Sgblack@eecs.umich.edu# If we have the compiler but not the library, print another warning.
7773546Sgblack@eecs.umich.eduif main['PROTOC'] and not main['HAVE_PROTOBUF']:
7784781Snate@binkert.org    print(termcap.Yellow + termcap.Bold +
7795863Snate@binkert.org        'Warning: did not find protocol buffer library and/or headers.\n' +
7804781Snate@binkert.org    '       Please install libprotobuf-dev for tracing support.' +
7814781Snate@binkert.org    termcap.Normal)
7824781Snate@binkert.org
7834781Snate@binkert.org# Check for librt.
7844781Snate@binkert.orghave_posix_clock = \
7855863Snate@binkert.org    conf.CheckLibWithHeader(None, 'time.h', 'C',
7864781Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);') or \
7874781Snate@binkert.org    conf.CheckLibWithHeader('rt', 'time.h', 'C',
7884781Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);')
7894781Snate@binkert.org
7903546Sgblack@eecs.umich.eduhave_posix_timers = \
7913546Sgblack@eecs.umich.edu    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
7923546Sgblack@eecs.umich.edu                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
7934781Snate@binkert.org
7943546Sgblack@eecs.umich.eduif not GetOption('without_tcmalloc'):
7953546Sgblack@eecs.umich.edu    if conf.CheckLib('tcmalloc'):
7963546Sgblack@eecs.umich.edu        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
7973546Sgblack@eecs.umich.edu    elif conf.CheckLib('tcmalloc_minimal'):
7983546Sgblack@eecs.umich.edu        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
7993546Sgblack@eecs.umich.edu    else:
8003546Sgblack@eecs.umich.edu        print(termcap.Yellow + termcap.Bold +
8013546Sgblack@eecs.umich.edu              "You can get a 12% performance improvement by "
8023546Sgblack@eecs.umich.edu              "installing tcmalloc (libgoogle-perftools-dev package "
8033546Sgblack@eecs.umich.edu              "on Ubuntu or RedHat)." + termcap.Normal)
8044202Sbinkertn@umich.edu
8053546Sgblack@eecs.umich.edu
8063546Sgblack@eecs.umich.edu# Detect back trace implementations. The last implementation in the
8073546Sgblack@eecs.umich.edu# list will be used by default.
808955SN/Abacktrace_impls = [ "none" ]
809955SN/A
810955SN/Abacktrace_checker = 'char temp;' + \
811955SN/A    ' backtrace_symbols_fd((void*)&temp, 0, 0);'
8125863Snate@binkert.orgif conf.CheckLibWithHeader(None, 'execinfo.h', 'C', backtrace_checker):
8135863Snate@binkert.org    backtrace_impls.append("glibc")
8145343Sstever@gmail.comelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
8155343Sstever@gmail.com                             backtrace_checker):
8166121Snate@binkert.org    # NetBSD and FreeBSD need libexecinfo.
8175863Snate@binkert.org    backtrace_impls.append("glibc")
8184773Snate@binkert.org    main.Append(LIBS=['execinfo'])
8195863Snate@binkert.org
8202632Sstever@eecs.umich.eduif backtrace_impls[-1] == "none":
8215863Snate@binkert.org    default_backtrace_impl = "none"
8222023SN/A    print(termcap.Yellow + termcap.Bold +
8235863Snate@binkert.org        "No suitable back trace implementation found." +
8245863Snate@binkert.org        termcap.Normal)
8255863Snate@binkert.org
8265863Snate@binkert.orgif not have_posix_clock:
8275863Snate@binkert.org    print("Can't find library for POSIX clocks.")
8285863Snate@binkert.org
8295863Snate@binkert.org# Check for <fenv.h> (C99 FP environment control)
8305863Snate@binkert.orghave_fenv = conf.CheckHeader('fenv.h', '<>')
8315863Snate@binkert.orgif not have_fenv:
8322632Sstever@eecs.umich.edu    print("Warning: Header file <fenv.h> not found.")
8335863Snate@binkert.org    print("         This host has no IEEE FP rounding mode control.")
8342023SN/A
8352632Sstever@eecs.umich.edu# Check for <png.h> (libpng library needed if wanting to dump
8365863Snate@binkert.org# frame buffer image in png format)
8375342Sstever@gmail.comhave_png = conf.CheckHeader('png.h', '<>')
8385863Snate@binkert.orgif not have_png:
8392632Sstever@eecs.umich.edu    print("Warning: Header file <png.h> not found.")
8405863Snate@binkert.org    print("         This host has no libpng library.")
8415863Snate@binkert.org    print("         Disabling support for PNG framebuffers.")
8422632Sstever@eecs.umich.edu
8435863Snate@binkert.org# Check if we should enable KVM-based hardware virtualization. The API
8445863Snate@binkert.org# we rely on exists since version 2.6.36 of the kernel, but somehow
8455863Snate@binkert.org# the KVM_API_VERSION does not reflect the change. We test for one of
8465863Snate@binkert.org# the types as a fall back.
8475863Snate@binkert.orghave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
8485863Snate@binkert.orgif not have_kvm:
8492632Sstever@eecs.umich.edu    print("Info: Compatible header file <linux/kvm.h> not found, "
8505863Snate@binkert.org          "disabling KVM support.")
8515863Snate@binkert.org
8522632Sstever@eecs.umich.edu# Check if the TUN/TAP driver is available.
8531888SN/Ahave_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
8545863Snate@binkert.orgif not have_tuntap:
8555863Snate@binkert.org    print("Info: Compatible header file <linux/if_tun.h> not found.")
8565863Snate@binkert.org
8571858SN/A# x86 needs support for xsave. We test for the structure here since we
8585863Snate@binkert.org# won't be able to run new tests by the time we know which ISA we're
8595863Snate@binkert.org# targeting.
8605863Snate@binkert.orghave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
8615863Snate@binkert.org                                    '#include <linux/kvm.h>') != 0
8622598SN/A
8635863Snate@binkert.org# Check if the requested target ISA is compatible with the host
8641858SN/Adef is_isa_kvm_compatible(isa):
8651858SN/A    try:
8661858SN/A        import platform
8675863Snate@binkert.org        host_isa = platform.machine()
8681858SN/A    except:
8691858SN/A        print("Warning: Failed to determine host ISA.")
8701858SN/A        return False
8715863Snate@binkert.org
8721871SN/A    if not have_posix_timers:
8731858SN/A        print("Warning: Can not enable KVM, host seems to lack support "
8741858SN/A              "for POSIX timers")
8751858SN/A        return False
8761858SN/A
8771858SN/A    if isa == "arm":
8781858SN/A        return host_isa in ( "armv7l", "aarch64" )
8791858SN/A    elif isa == "x86":
8805863Snate@binkert.org        if host_isa != "x86_64":
8811858SN/A            return False
8821858SN/A
8835863Snate@binkert.org        if not have_kvm_xsave:
8841859SN/A            print("KVM on x86 requires xsave support in kernel headers.")
8851859SN/A            return False
8861869SN/A
8875863Snate@binkert.org        return True
8885863Snate@binkert.org    else:
8891869SN/A        return False
8901965SN/A
8911965SN/A
8921965SN/A# Check if the exclude_host attribute is available. We want this to
8932761Sstever@eecs.umich.edu# get accurate instruction counts in KVM.
8945863Snate@binkert.orgmain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
8951869SN/A    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
8965863Snate@binkert.org
8972667Sstever@eecs.umich.edu
8981869SN/A######################################################################
8991869SN/A#
9002929Sktlim@umich.edu# Finish the configuration
9012929Sktlim@umich.edu#
9025863Snate@binkert.orgmain = conf.Finish()
9032929Sktlim@umich.edu
904955SN/A######################################################################
9052598SN/A#
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
1075# builds in ext are shared across all configs in the build root.
1076ext_dir = abspath(joinpath(str(main.root), 'ext'))
1077ext_build_dirs = []
1078for root, dirs, files in os.walk(ext_dir):
1079    if 'SConscript' in files:
1080        build_dir = os.path.relpath(root, ext_dir)
1081        ext_build_dirs.append(build_dir)
1082        main.SConscript(joinpath(root, 'SConscript'),
1083                        variant_dir=joinpath(build_root, build_dir))
1084
1085gdb_xml_dir = joinpath(ext_dir, 'gdb-xml')
1086Export('gdb_xml_dir')
1087
1088main.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
1089
1090###################################################
1091#
1092# This builder and wrapper method are used to set up a directory with
1093# switching headers. Those are headers which are in a generic location and
1094# that include more specific headers from a directory chosen at build time
1095# based on the current build settings.
1096#
1097###################################################
1098
1099def build_switching_header(target, source, env):
1100    path = str(target[0])
1101    subdir = str(source[0])
1102    dp, fp = os.path.split(path)
1103    dp = os.path.relpath(os.path.realpath(dp),
1104                         os.path.realpath(env['BUILDDIR']))
1105    with open(path, 'w') as hdr:
1106        print('#include "%s/%s/%s"' % (dp, subdir, fp), file=hdr)
1107
1108switching_header_action = MakeAction(build_switching_header,
1109                                     Transform('GENERATE'))
1110
1111switching_header_builder = Builder(action=switching_header_action,
1112                                   source_factory=Value,
1113                                   single_source=True)
1114
1115main.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
1116
1117def switching_headers(self, headers, source):
1118    for header in headers:
1119        self.SwitchingHeader(header, source)
1120
1121main.AddMethod(switching_headers, 'SwitchingHeaders')
1122
1123###################################################
1124#
1125# Define build environments for selected configurations.
1126#
1127###################################################
1128
1129for variant_path in variant_paths:
1130    if not GetOption('silent'):
1131        print("Building in", variant_path)
1132
1133    # Make a copy of the build-root environment to use for this config.
1134    env = main.Clone()
1135    env['BUILDDIR'] = variant_path
1136
1137    # variant_dir is the tail component of build path, and is used to
1138    # determine the build parameters (e.g., 'ALPHA_SE')
1139    (build_root, variant_dir) = splitpath(variant_path)
1140
1141    # Set env variables according to the build directory config.
1142    sticky_vars.files = []
1143    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1144    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1145    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1146    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1147    if isfile(current_vars_file):
1148        sticky_vars.files.append(current_vars_file)
1149        if not GetOption('silent'):
1150            print("Using saved variables file %s" % current_vars_file)
1151    elif variant_dir in ext_build_dirs:
1152        # Things in ext are built without a variant directory.
1153        continue
1154    else:
1155        # Build dir-specific variables file doesn't exist.
1156
1157        # Make sure the directory is there so we can create it later
1158        opt_dir = dirname(current_vars_file)
1159        if not isdir(opt_dir):
1160            mkdir(opt_dir)
1161
1162        # Get default build variables from source tree.  Variables are
1163        # normally determined by name of $VARIANT_DIR, but can be
1164        # overridden by '--default=' arg on command line.
1165        default = GetOption('default')
1166        opts_dir = joinpath(main.root.abspath, 'build_opts')
1167        if default:
1168            default_vars_files = [joinpath(build_root, 'variables', default),
1169                                  joinpath(opts_dir, default)]
1170        else:
1171            default_vars_files = [joinpath(opts_dir, variant_dir)]
1172        existing_files = filter(isfile, default_vars_files)
1173        if existing_files:
1174            default_vars_file = existing_files[0]
1175            sticky_vars.files.append(default_vars_file)
1176            print("Variables file %s not found,\n  using defaults in %s"
1177                  % (current_vars_file, default_vars_file))
1178        else:
1179            print("Error: cannot find variables file %s or "
1180                  "default file(s) %s"
1181                  % (current_vars_file, ' or '.join(default_vars_files)))
1182            Exit(1)
1183
1184    # Apply current variable settings to env
1185    sticky_vars.Update(env)
1186
1187    help_texts["local_vars"] += \
1188        "Build variables for %s:\n" % variant_dir \
1189                 + sticky_vars.GenerateHelpText(env)
1190
1191    # Process variable settings.
1192
1193    if not have_fenv and env['USE_FENV']:
1194        print("Warning: <fenv.h> not available; "
1195              "forcing USE_FENV to False in", variant_dir + ".")
1196        env['USE_FENV'] = False
1197
1198    if not env['USE_FENV']:
1199        print("Warning: No IEEE FP rounding mode control in",
1200              variant_dir + ".")
1201        print("         FP results may deviate slightly from other platforms.")
1202
1203    if not have_png and env['USE_PNG']:
1204        print("Warning: <png.h> not available; "
1205              "forcing USE_PNG to False in", variant_dir + ".")
1206        env['USE_PNG'] = False
1207
1208    if env['USE_PNG']:
1209        env.Append(LIBS=['png'])
1210
1211    if env['EFENCE']:
1212        env.Append(LIBS=['efence'])
1213
1214    if env['USE_KVM']:
1215        if not have_kvm:
1216            print("Warning: Can not enable KVM, host seems to "
1217                  "lack KVM support")
1218            env['USE_KVM'] = False
1219        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1220            print("Info: KVM support disabled due to unsupported host and "
1221                  "target ISA combination")
1222            env['USE_KVM'] = False
1223
1224    if env['USE_TUNTAP']:
1225        if not have_tuntap:
1226            print("Warning: Can't connect EtherTap with a tap device.")
1227            env['USE_TUNTAP'] = False
1228
1229    if env['BUILD_GPU']:
1230        env.Append(CPPDEFINES=['BUILD_GPU'])
1231
1232    # Warn about missing optional functionality
1233    if env['USE_KVM']:
1234        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1235            print("Warning: perf_event headers lack support for the "
1236                  "exclude_host attribute. KVM instruction counts will "
1237                  "be inaccurate.")
1238
1239    # Save sticky variable settings back to current variables file
1240    sticky_vars.Save(current_vars_file, env)
1241
1242    if env['USE_SSE2']:
1243        env.Append(CCFLAGS=['-msse2'])
1244
1245    # The src/SConscript file sets up the build rules in 'env' according
1246    # to the configured variables.  It returns a list of environments,
1247    # one for each variant build (debug, opt, etc.)
1248    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1249
1250# base help text
1251Help('''
1252Usage: scons [scons options] [build variables] [target(s)]
1253
1254Extra scons options:
1255%(options)s
1256
1257Global build variables:
1258%(global_vars)s
1259
1260%(local_vars)s
1261''' % help_texts)
1262