SConstruct revision 12790
1955SN/A# -*- mode:python -*-
2955SN/A
37816Ssteve.reinhardt@amd.com# Copyright (c) 2013, 2015-2017 ARM Limited
45871Snate@binkert.org# All rights reserved.
51762SN/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
29955SN/A# this software without specific prior written permission.
302665Ssaidi@eecs.umich.edu#
312665Ssaidi@eecs.umich.edu# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
325863Snate@binkert.org# "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
37955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
388878Ssteve.reinhardt@amd.com# 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
408878Ssteve.reinhardt@amd.com# (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.
42955SN/A#
438878Ssteve.reinhardt@amd.com# Authors: Steve Reinhardt
442632Sstever@eecs.umich.edu#          Nathan Binkert
452761Sstever@eecs.umich.edu
462632Sstever@eecs.umich.edu###################################################
472632Sstever@eecs.umich.edu#
482632Sstever@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
512761Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
528878Ssteve.reinhardt@amd.com# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
538878Ssteve.reinhardt@amd.com# 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
582761Sstever@eecs.umich.edu# built for the same host system.
598878Ssteve.reinhardt@amd.com#
608878Ssteve.reinhardt@amd.com# Examples:
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
638878Ssteve.reinhardt@amd.com#   scons to search up the directory tree for this SConstruct file.
648878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
652632Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
66955SN/A#
67955SN/A#   The following two commands are equivalent and demonstrate building
68955SN/A#   in a directory outside of the source tree.  The '-C' option tells
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###################################################
808878Ssteve.reinhardt@amd.com
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.org
968878Ssteve.reinhardt@amd.com# SCons includes
975863Snate@binkert.orgimport SCons
985863Snate@binkert.orgimport SCons.Node
995863Snate@binkert.org
1006654Snate@binkert.orgfrom m5.util import compareVersions, readCommand
101955SN/A
1025396Ssaidi@eecs.umich.eduhelp_texts = {
1035863Snate@binkert.org    "options" : "",
1045863Snate@binkert.org    "global_vars" : "",
1054202Sbinkertn@umich.edu    "local_vars" : ""
1065863Snate@binkert.org}
1075863Snate@binkert.org
1085863Snate@binkert.orgExport("help_texts")
1095863Snate@binkert.org
110955SN/A
1116654Snate@binkert.org# There's a bug in scons in that (1) by default, the help texts from
1125273Sstever@gmail.com# AddOption() are supposed to be displayed when you type 'scons -h'
1135871Snate@binkert.org# and (2) you can override the help displayed by 'scons -h' using the
1145273Sstever@gmail.com# Help() function, but these two features are incompatible: once
1156655Snate@binkert.org# you've overridden the help text using Help(), there's no way to get
1168878Ssteve.reinhardt@amd.com# at the help texts from AddOptions.  See:
1176655Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1186655Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1196655Snate@binkert.org# This hack lets us extract the help text from AddOptions and
1206655Snate@binkert.org# re-inject it via Help().  Ideally someday this bug will be fixed and
1215871Snate@binkert.org# we can just use AddOption directly.
1226654Snate@binkert.orgdef AddLocalOption(*args, **kwargs):
1235396Ssaidi@eecs.umich.edu    col_width = 30
1248120Sgblack@eecs.umich.edu
1258120Sgblack@eecs.umich.edu    help = "  " + ", ".join(args)
1268120Sgblack@eecs.umich.edu    if "help" in kwargs:
1278120Sgblack@eecs.umich.edu        length = len(help)
1288120Sgblack@eecs.umich.edu        if length >= col_width:
1298120Sgblack@eecs.umich.edu            help += "\n" + " " * col_width
1308120Sgblack@eecs.umich.edu        else:
1318120Sgblack@eecs.umich.edu            help += " " * (col_width - length)
1328120Sgblack@eecs.umich.edu        help += kwargs["help"]
1338120Sgblack@eecs.umich.edu    help_texts["options"] += help + "\n"
1348120Sgblack@eecs.umich.edu
1358120Sgblack@eecs.umich.edu    AddOption(*args, **kwargs)
1368120Sgblack@eecs.umich.edu
1378120Sgblack@eecs.umich.eduAddLocalOption('--colors', dest='use_colors', action='store_true',
1388120Sgblack@eecs.umich.edu               help="Add color to abbreviated scons output")
1398120Sgblack@eecs.umich.eduAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1408120Sgblack@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1418120Sgblack@eecs.umich.eduAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1428120Sgblack@eecs.umich.edu               action='store_true',
1438120Sgblack@eecs.umich.edu               help="Build with support for C++-based configuration")
1448120Sgblack@eecs.umich.eduAddLocalOption('--default', dest='default', type='string', action='store',
1458120Sgblack@eecs.umich.edu               help='Override which build_opts file to use for defaults')
1468120Sgblack@eecs.umich.eduAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1478120Sgblack@eecs.umich.edu               help='Disable style checking hooks')
1488120Sgblack@eecs.umich.eduAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1498120Sgblack@eecs.umich.edu               help='Disable Link-Time Optimization for fast')
1508120Sgblack@eecs.umich.eduAddLocalOption('--force-lto', dest='force_lto', action='store_true',
1518120Sgblack@eecs.umich.edu               help='Use Link-Time Optimization instead of partial linking' +
1528120Sgblack@eecs.umich.edu                    ' when the compiler doesn\'t support using them together.')
1538120Sgblack@eecs.umich.eduAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1548120Sgblack@eecs.umich.edu               help='Update test reference outputs')
1558120Sgblack@eecs.umich.eduAddLocalOption('--verbose', dest='verbose', action='store_true',
1568120Sgblack@eecs.umich.edu               help='Print full tool command lines')
1578120Sgblack@eecs.umich.eduAddLocalOption('--without-python', dest='without_python',
1588120Sgblack@eecs.umich.edu               action='store_true',
1598120Sgblack@eecs.umich.edu               help='Build without Python configuration support')
1607816Ssteve.reinhardt@amd.comAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1617816Ssteve.reinhardt@amd.com               action='store_true',
1627816Ssteve.reinhardt@amd.com               help='Disable linking against tcmalloc')
1637816Ssteve.reinhardt@amd.comAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1647816Ssteve.reinhardt@amd.com               help='Build with Undefined Behavior Sanitizer if available')
1657816Ssteve.reinhardt@amd.comAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1667816Ssteve.reinhardt@amd.com               help='Build with Address Sanitizer if available')
1677816Ssteve.reinhardt@amd.com
1687816Ssteve.reinhardt@amd.comif GetOption('no_lto') and GetOption('force_lto'):
1695871Snate@binkert.org    print('--no-lto and --force-lto are mutually exclusive')
1705871Snate@binkert.org    Exit(1)
1716121Snate@binkert.org
1725871Snate@binkert.org########################################################################
1735871Snate@binkert.org#
1746003Snate@binkert.org# Set up the main build environment.
1756655Snate@binkert.org#
176955SN/A########################################################################
1775871Snate@binkert.org
1785871Snate@binkert.orgmain = Environment()
1795871Snate@binkert.org
1805871Snate@binkert.orgfrom gem5_scons import Transform
181955SN/Afrom gem5_scons.util import get_termcap
1826121Snate@binkert.orgtermcap = get_termcap()
1836121Snate@binkert.org
1846121Snate@binkert.orgmain_dict_keys = main.Dictionary().keys()
1851533SN/A
1866655Snate@binkert.org# Check that we have a C/C++ compiler
1876655Snate@binkert.orgif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
1886655Snate@binkert.org    print("No C++ compiler installed (package g++ on Ubuntu and RedHat)")
1896655Snate@binkert.org    Exit(1)
1905871Snate@binkert.org
1915871Snate@binkert.org###################################################
1925863Snate@binkert.org#
1935871Snate@binkert.org# Figure out which configurations to set up based on the path(s) of
1948878Ssteve.reinhardt@amd.com# the target(s).
1955871Snate@binkert.org#
1965871Snate@binkert.org###################################################
1975871Snate@binkert.org
1985863Snate@binkert.org# Find default configuration & binary.
1996121Snate@binkert.orgDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
2005863Snate@binkert.org
2015871Snate@binkert.org# helper function: find last occurrence of element in list
2028336Ssteve.reinhardt@amd.comdef rfind(l, elt, offs = -1):
2038336Ssteve.reinhardt@amd.com    for i in range(len(l)+offs, 0, -1):
2048336Ssteve.reinhardt@amd.com        if l[i] == elt:
2058336Ssteve.reinhardt@amd.com            return i
2064678Snate@binkert.org    raise ValueError, "element not found"
2078336Ssteve.reinhardt@amd.com
2088336Ssteve.reinhardt@amd.com# Take a list of paths (or SCons Nodes) and return a list with all
2098336Ssteve.reinhardt@amd.com# paths made absolute and ~-expanded.  Paths will be interpreted
2104678Snate@binkert.org# relative to the launch directory unless a different root is provided
2114678Snate@binkert.orgdef makePathListAbsolute(path_list, root=GetLaunchDir()):
2124678Snate@binkert.org    return [abspath(joinpath(root, expanduser(str(p))))
2134678Snate@binkert.org            for p in path_list]
2147827Snate@binkert.org
2157827Snate@binkert.org# Each target must have 'build' in the interior of the path; the
2168336Ssteve.reinhardt@amd.com# directory below this will determine the build parameters.  For
2174678Snate@binkert.org# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2188336Ssteve.reinhardt@amd.com# recognize that ALPHA_SE specifies the configuration because it
2198336Ssteve.reinhardt@amd.com# follow 'build' in the build path.
2208336Ssteve.reinhardt@amd.com
2218336Ssteve.reinhardt@amd.com# The funky assignment to "[:]" is needed to replace the list contents
2228336Ssteve.reinhardt@amd.com# in place rather than reassign the symbol to a new list, which
2238336Ssteve.reinhardt@amd.com# doesn't work (obviously!).
2245871Snate@binkert.orgBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
2255871Snate@binkert.org
2268336Ssteve.reinhardt@amd.com# Generate a list of the unique build roots and configs that the
2278336Ssteve.reinhardt@amd.com# collected targets reference.
2288336Ssteve.reinhardt@amd.comvariant_paths = []
2298336Ssteve.reinhardt@amd.combuild_root = None
2308336Ssteve.reinhardt@amd.comfor t in BUILD_TARGETS:
2315871Snate@binkert.org    path_dirs = t.split('/')
2328336Ssteve.reinhardt@amd.com    try:
2338336Ssteve.reinhardt@amd.com        build_top = rfind(path_dirs, 'build', -2)
2348336Ssteve.reinhardt@amd.com    except:
2358336Ssteve.reinhardt@amd.com        print("Error: no non-leaf 'build' dir found on target path", t)
2368336Ssteve.reinhardt@amd.com        Exit(1)
2374678Snate@binkert.org    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2385871Snate@binkert.org    if not build_root:
2394678Snate@binkert.org        build_root = this_build_root
2408336Ssteve.reinhardt@amd.com    else:
2418336Ssteve.reinhardt@amd.com        if this_build_root != build_root:
2428336Ssteve.reinhardt@amd.com            print("Error: build targets not under same build root\n"
2438336Ssteve.reinhardt@amd.com                  "  %s\n  %s" % (build_root, this_build_root))
2448336Ssteve.reinhardt@amd.com            Exit(1)
2458336Ssteve.reinhardt@amd.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
2468336Ssteve.reinhardt@amd.com    if variant_path not in variant_paths:
2478336Ssteve.reinhardt@amd.com        variant_paths.append(variant_path)
2488336Ssteve.reinhardt@amd.com
2498336Ssteve.reinhardt@amd.com# Make sure build_root exists (might not if this is the first build there)
2508336Ssteve.reinhardt@amd.comif not isdir(build_root):
2518336Ssteve.reinhardt@amd.com    mkdir(build_root)
2528336Ssteve.reinhardt@amd.commain['BUILDROOT'] = build_root
2538336Ssteve.reinhardt@amd.com
2548336Ssteve.reinhardt@amd.comExport('main')
2558336Ssteve.reinhardt@amd.com
2568336Ssteve.reinhardt@amd.commain.SConsignFile(joinpath(build_root, "sconsign"))
2575871Snate@binkert.org
2586121Snate@binkert.org# Default duplicate option is to use hard links, but this messes up
259955SN/A# when you use emacs to edit a file in the target dir, as emacs moves
260955SN/A# file to file~ then copies to file, breaking the link.  Symbolic
2612632Sstever@eecs.umich.edu# (soft) links work better.
2622632Sstever@eecs.umich.edumain.SetOption('duplicate', 'soft-copy')
263955SN/A
264955SN/A#
265955SN/A# Set up global sticky variables... these are common to an entire build
266955SN/A# tree (not specific to a particular build like ALPHA_SE)
2678878Ssteve.reinhardt@amd.com#
268955SN/A
2692632Sstever@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
2702632Sstever@eecs.umich.edu
2712632Sstever@eecs.umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
2722632Sstever@eecs.umich.edu
2732632Sstever@eecs.umich.eduglobal_vars.AddVariables(
2742632Sstever@eecs.umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
2752632Sstever@eecs.umich.edu    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
2768268Ssteve.reinhardt@amd.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
2778268Ssteve.reinhardt@amd.com    ('BATCH', 'Use batch pool for build and tests', False),
2788268Ssteve.reinhardt@amd.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
2798268Ssteve.reinhardt@amd.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
2808268Ssteve.reinhardt@amd.com    ('EXTRAS', 'Add extra directories to the compilation', '')
2818268Ssteve.reinhardt@amd.com    )
2828268Ssteve.reinhardt@amd.com
2832632Sstever@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
2842632Sstever@eecs.umich.eduglobal_vars.Update(main)
2852632Sstever@eecs.umich.eduhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
2862632Sstever@eecs.umich.edu
2878268Ssteve.reinhardt@amd.com# Save sticky variable settings back to current variables file
2882632Sstever@eecs.umich.eduglobal_vars.Save(global_vars_file, main)
2898268Ssteve.reinhardt@amd.com
2908268Ssteve.reinhardt@amd.com# Parse EXTRAS variable to build list of all directories where we're
2918268Ssteve.reinhardt@amd.com# look for sources etc.  This list is exported as extras_dir_list.
2928268Ssteve.reinhardt@amd.combase_dir = main.srcdir.abspath
2933718Sstever@eecs.umich.eduif main['EXTRAS']:
2942634Sstever@eecs.umich.edu    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
2952634Sstever@eecs.umich.eduelse:
2965863Snate@binkert.org    extras_dir_list = []
2972638Sstever@eecs.umich.edu
2988268Ssteve.reinhardt@amd.comExport('base_dir')
2992632Sstever@eecs.umich.eduExport('extras_dir_list')
3002632Sstever@eecs.umich.edu
3012632Sstever@eecs.umich.edu# the ext directory should be on the #includes path
3022632Sstever@eecs.umich.edumain.Append(CPPPATH=[Dir('ext')])
3032632Sstever@eecs.umich.edu
3041858SN/A# Add shared top-level headers
3053716Sstever@eecs.umich.edumain.Prepend(CPPPATH=Dir('include'))
3062638Sstever@eecs.umich.edu
3072638Sstever@eecs.umich.eduif GetOption('verbose'):
3082638Sstever@eecs.umich.edu    def MakeAction(action, string, *args, **kwargs):
3092638Sstever@eecs.umich.edu        return Action(action, *args, **kwargs)
3102638Sstever@eecs.umich.eduelse:
3112638Sstever@eecs.umich.edu    MakeAction = Action
3122638Sstever@eecs.umich.edu    main['CCCOMSTR']        = Transform("CC")
3135863Snate@binkert.org    main['CXXCOMSTR']       = Transform("CXX")
3145863Snate@binkert.org    main['ASCOMSTR']        = Transform("AS")
3155863Snate@binkert.org    main['ARCOMSTR']        = Transform("AR", 0)
316955SN/A    main['LINKCOMSTR']      = Transform("LINK", 0)
3175341Sstever@gmail.com    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
3185341Sstever@gmail.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
3195863Snate@binkert.org    main['M4COMSTR']        = Transform("M4")
3207756SAli.Saidi@ARM.com    main['SHCCCOMSTR']      = Transform("SHCC")
3215341Sstever@gmail.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
3226121Snate@binkert.orgExport('MakeAction')
3234494Ssaidi@eecs.umich.edu
3246121Snate@binkert.org# Initialize the Link-Time Optimization (LTO) flags
3251105SN/Amain['LTO_CCFLAGS'] = []
3262667Sstever@eecs.umich.edumain['LTO_LDFLAGS'] = []
3272667Sstever@eecs.umich.edu
3282667Sstever@eecs.umich.edu# According to the readme, tcmalloc works best if the compiler doesn't
3292667Sstever@eecs.umich.edu# assume that we're using the builtin malloc and friends. These flags
3306121Snate@binkert.org# are compiler-specific, so we need to set them after we detect which
3312667Sstever@eecs.umich.edu# compiler we're using.
3325341Sstever@gmail.commain['TCMALLOC_CCFLAGS'] = []
3335863Snate@binkert.org
3345341Sstever@gmail.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
3355341Sstever@gmail.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
3365341Sstever@gmail.com
3378120Sgblack@eecs.umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3385341Sstever@gmail.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
3398120Sgblack@eecs.umich.eduif main['GCC'] + main['CLANG'] > 1:
3405341Sstever@gmail.com    print('Error: How can we have two at the same time?')
3418120Sgblack@eecs.umich.edu    Exit(1)
3426121Snate@binkert.org
3436121Snate@binkert.org# Set up default C++ compiler flags
3445397Ssaidi@eecs.umich.eduif main['GCC'] or main['CLANG']:
3455397Ssaidi@eecs.umich.edu    # As gcc and clang share many flags, do the common parts here
3467727SAli.Saidi@ARM.com    main.Append(CCFLAGS=['-pipe'])
3478268Ssteve.reinhardt@amd.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
3486168Snate@binkert.org    # Enable -Wall and -Wextra and then disable the few warnings that
3495341Sstever@gmail.com    # we consistently violate
3508120Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
3518120Sgblack@eecs.umich.edu                         '-Wno-sign-compare', '-Wno-unused-parameter'])
3528120Sgblack@eecs.umich.edu    # We always compile using C++11
3536814Sgblack@eecs.umich.edu    main.Append(CXXFLAGS=['-std=c++11'])
3545863Snate@binkert.org    if sys.platform.startswith('freebsd'):
3558120Sgblack@eecs.umich.edu        main.Append(CCFLAGS=['-I/usr/local/include'])
3565341Sstever@gmail.com        main.Append(CXXFLAGS=['-I/usr/local/include'])
3575863Snate@binkert.org
3588268Ssteve.reinhardt@amd.com    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
3596121Snate@binkert.org    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
3606121Snate@binkert.org    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
3618268Ssteve.reinhardt@amd.com    shared_partial_flags = ['-r', '-nostdlib']
3625742Snate@binkert.org    main.Append(PSHLINKFLAGS=shared_partial_flags)
3635742Snate@binkert.org    main.Append(PLINKFLAGS=shared_partial_flags)
3645341Sstever@gmail.com
3655742Snate@binkert.org    # Treat warnings as errors but white list some warnings that we
3665742Snate@binkert.org    # want to allow (e.g., deprecation warnings).
3675341Sstever@gmail.com    main.Append(CCFLAGS=['-Werror',
3686017Snate@binkert.org                         '-Wno-error=deprecated-declarations',
3696121Snate@binkert.org                         '-Wno-error=deprecated',
3706017Snate@binkert.org                        ])
3717816Ssteve.reinhardt@amd.comelse:
3727756SAli.Saidi@ARM.com    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
3737756SAli.Saidi@ARM.com    print("Don't know what compiler options to use for your compiler.")
3747756SAli.Saidi@ARM.com    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
3757756SAli.Saidi@ARM.com    print(termcap.Yellow + '       version:' + termcap.Normal, end = ' ')
3767756SAli.Saidi@ARM.com    if not CXX_version:
3777756SAli.Saidi@ARM.com        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
3787756SAli.Saidi@ARM.com              termcap.Normal)
3797756SAli.Saidi@ARM.com    else:
3807816Ssteve.reinhardt@amd.com        print(CXX_version.replace('\n', '<nl>'))
3817816Ssteve.reinhardt@amd.com    print("       If you're trying to use a compiler other than GCC")
3827816Ssteve.reinhardt@amd.com    print("       or clang, there appears to be something wrong with your")
3837816Ssteve.reinhardt@amd.com    print("       environment.")
3847816Ssteve.reinhardt@amd.com    print("       ")
3857816Ssteve.reinhardt@amd.com    print("       If you are trying to use a compiler other than those listed")
3867816Ssteve.reinhardt@amd.com    print("       above you will need to ease fix SConstruct and ")
3877816Ssteve.reinhardt@amd.com    print("       src/SConscript to support that compiler.")
3887816Ssteve.reinhardt@amd.com    Exit(1)
3897816Ssteve.reinhardt@amd.com
3907756SAli.Saidi@ARM.comif main['GCC']:
3917816Ssteve.reinhardt@amd.com    # Check for a supported version of gcc. >= 4.8 is chosen for its
3927816Ssteve.reinhardt@amd.com    # level of c++11 support. See
3937816Ssteve.reinhardt@amd.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
3947816Ssteve.reinhardt@amd.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
3957816Ssteve.reinhardt@amd.com    if compareVersions(gcc_version, "4.8") < 0:
3967816Ssteve.reinhardt@amd.com        print('Error: gcc version 4.8 or newer required.')
3977816Ssteve.reinhardt@amd.com        print('       Installed version: ', gcc_version)
3987816Ssteve.reinhardt@amd.com        Exit(1)
3997816Ssteve.reinhardt@amd.com
4007816Ssteve.reinhardt@amd.com    main['GCC_VERSION'] = gcc_version
4017816Ssteve.reinhardt@amd.com
4027816Ssteve.reinhardt@amd.com    if compareVersions(gcc_version, '4.9') >= 0:
4037816Ssteve.reinhardt@amd.com        # Incremental linking with LTO is currently broken in gcc versions
4047816Ssteve.reinhardt@amd.com        # 4.9 and above. A version where everything works completely hasn't
4057816Ssteve.reinhardt@amd.com        # yet been identified.
4067816Ssteve.reinhardt@amd.com        #
4077816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
4087816Ssteve.reinhardt@amd.com        main['BROKEN_INCREMENTAL_LTO'] = True
4097816Ssteve.reinhardt@amd.com    if compareVersions(gcc_version, '6.0') >= 0:
4107816Ssteve.reinhardt@amd.com        # gcc versions 6.0 and greater accept an -flinker-output flag which
4117816Ssteve.reinhardt@amd.com        # selects what type of output the linker should generate. This is
4127816Ssteve.reinhardt@amd.com        # necessary for incremental lto to work, but is also broken in
4137816Ssteve.reinhardt@amd.com        # current versions of gcc. It may not be necessary in future
4147816Ssteve.reinhardt@amd.com        # versions. We add it here since it might be, and as a reminder that
4157816Ssteve.reinhardt@amd.com        # it exists. It's excluded if lto is being forced.
4167816Ssteve.reinhardt@amd.com        #
4177816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/gcc-6/changes.html
4187816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
4197816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
4207816Ssteve.reinhardt@amd.com        if not GetOption('force_lto'):
4217816Ssteve.reinhardt@amd.com            main.Append(PSHLINKFLAGS='-flinker-output=rel')
4227816Ssteve.reinhardt@amd.com            main.Append(PLINKFLAGS='-flinker-output=rel')
4237816Ssteve.reinhardt@amd.com
4247816Ssteve.reinhardt@amd.com    # gcc from version 4.8 and above generates "rep; ret" instructions
4257816Ssteve.reinhardt@amd.com    # to avoid performance penalties on certain AMD chips. Older
4267816Ssteve.reinhardt@amd.com    # assemblers detect this as an error, "Error: expecting string
4277816Ssteve.reinhardt@amd.com    # instruction after `rep'"
4287816Ssteve.reinhardt@amd.com    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
4297816Ssteve.reinhardt@amd.com                                  '-o', '/dev/null'],
4307816Ssteve.reinhardt@amd.com                                 exception=False).split()
4317816Ssteve.reinhardt@amd.com
4327816Ssteve.reinhardt@amd.com    # version strings may contain extra distro-specific
4337816Ssteve.reinhardt@amd.com    # qualifiers, so play it safe and keep only what comes before
4347816Ssteve.reinhardt@amd.com    # the first hyphen
4357816Ssteve.reinhardt@amd.com    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
4367816Ssteve.reinhardt@amd.com
4377816Ssteve.reinhardt@amd.com    if not as_version or compareVersions(as_version, "2.23") < 0:
4387816Ssteve.reinhardt@amd.com        print(termcap.Yellow + termcap.Bold +
4397816Ssteve.reinhardt@amd.com            'Warning: This combination of gcc and binutils have' +
4407816Ssteve.reinhardt@amd.com            ' known incompatibilities.\n' +
4417816Ssteve.reinhardt@amd.com            '         If you encounter build problems, please update ' +
4427816Ssteve.reinhardt@amd.com            'binutils to 2.23.' +
4437816Ssteve.reinhardt@amd.com            termcap.Normal)
4447816Ssteve.reinhardt@amd.com
4457816Ssteve.reinhardt@amd.com    # Make sure we warn if the user has requested to compile with the
4467816Ssteve.reinhardt@amd.com    # Undefined Benahvior Sanitizer and this version of gcc does not
4477816Ssteve.reinhardt@amd.com    # support it.
4487816Ssteve.reinhardt@amd.com    if GetOption('with_ubsan') and \
4497816Ssteve.reinhardt@amd.com            compareVersions(gcc_version, '4.9') < 0:
4507816Ssteve.reinhardt@amd.com        print(termcap.Yellow + termcap.Bold +
4517816Ssteve.reinhardt@amd.com            'Warning: UBSan is only supported using gcc 4.9 and later.' +
4527756SAli.Saidi@ARM.com            termcap.Normal)
4538120Sgblack@eecs.umich.edu
4547756SAli.Saidi@ARM.com    disable_lto = GetOption('no_lto')
4557756SAli.Saidi@ARM.com    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
4567756SAli.Saidi@ARM.com            not GetOption('force_lto'):
4577756SAli.Saidi@ARM.com        print(termcap.Yellow + termcap.Bold +
4587816Ssteve.reinhardt@amd.com            'Warning: Your compiler doesn\'t support incremental linking' +
4597816Ssteve.reinhardt@amd.com            ' and lto at the same time, so lto is being disabled. To force' +
4607816Ssteve.reinhardt@amd.com            ' lto on anyway, use the --force-lto option. That will disable' +
4617816Ssteve.reinhardt@amd.com            ' partial linking.' +
4627816Ssteve.reinhardt@amd.com            termcap.Normal)
4637816Ssteve.reinhardt@amd.com        disable_lto = True
4647816Ssteve.reinhardt@amd.com
4657816Ssteve.reinhardt@amd.com    # Add the appropriate Link-Time Optimization (LTO) flags
4667816Ssteve.reinhardt@amd.com    # unless LTO is explicitly turned off. Note that these flags
4677816Ssteve.reinhardt@amd.com    # are only used by the fast target.
4687756SAli.Saidi@ARM.com    if not disable_lto:
4697756SAli.Saidi@ARM.com        # Pass the LTO flag when compiling to produce GIMPLE
4706654Snate@binkert.org        # output, we merely create the flags here and only append
4716654Snate@binkert.org        # them later
4725871Snate@binkert.org        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4736121Snate@binkert.org
4746121Snate@binkert.org        # Use the same amount of jobs for LTO as we are running
4756121Snate@binkert.org        # scons with
4768737Skoansin.tan@gmail.com        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4778737Skoansin.tan@gmail.com
4783940Ssaidi@eecs.umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
4793918Ssaidi@eecs.umich.edu                                  '-fno-builtin-realloc', '-fno-builtin-free'])
4803918Ssaidi@eecs.umich.edu
4811858SN/A    # The address sanitizer is available for gcc >= 4.8
4826121Snate@binkert.org    if GetOption('with_asan'):
4837739Sgblack@eecs.umich.edu        if GetOption('with_ubsan') and \
4847739Sgblack@eecs.umich.edu                compareVersions(main['GCC_VERSION'], '4.9') >= 0:
4856143Snate@binkert.org            main.Append(CCFLAGS=['-fsanitize=address,undefined',
4867739Sgblack@eecs.umich.edu                                 '-fno-omit-frame-pointer'],
4877618SAli.Saidi@arm.com                       LINKFLAGS='-fsanitize=address,undefined')
4887618SAli.Saidi@arm.com        else:
4897618SAli.Saidi@arm.com            main.Append(CCFLAGS=['-fsanitize=address',
4907618SAli.Saidi@arm.com                                 '-fno-omit-frame-pointer'],
4918614Sgblack@eecs.umich.edu                       LINKFLAGS='-fsanitize=address')
4927618SAli.Saidi@arm.com    # Only gcc >= 4.9 supports UBSan, so check both the version
4937618SAli.Saidi@arm.com    # and the command-line option before adding the compiler and
4947618SAli.Saidi@arm.com    # linker flags.
4957739Sgblack@eecs.umich.edu    elif GetOption('with_ubsan') and \
4966121Snate@binkert.org            compareVersions(main['GCC_VERSION'], '4.9') >= 0:
4973940Ssaidi@eecs.umich.edu        main.Append(CCFLAGS='-fsanitize=undefined')
4986121Snate@binkert.org        main.Append(LINKFLAGS='-fsanitize=undefined')
4997739Sgblack@eecs.umich.edu
5007739Sgblack@eecs.umich.eduelif main['CLANG']:
5017739Sgblack@eecs.umich.edu    # Check for a supported version of clang, >= 3.1 is needed to
5027739Sgblack@eecs.umich.edu    # support similar features as gcc 4.8. See
5037739Sgblack@eecs.umich.edu    # http://clang.llvm.org/cxx_status.html for details
5047739Sgblack@eecs.umich.edu    clang_version_re = re.compile(".* version (\d+\.\d+)")
5058737Skoansin.tan@gmail.com    clang_version_match = clang_version_re.search(CXX_version)
5068737Skoansin.tan@gmail.com    if (clang_version_match):
5078737Skoansin.tan@gmail.com        clang_version = clang_version_match.groups()[0]
5088737Skoansin.tan@gmail.com        if compareVersions(clang_version, "3.1") < 0:
5098737Skoansin.tan@gmail.com            print('Error: clang version 3.1 or newer required.')
5108737Skoansin.tan@gmail.com            print('       Installed version:', clang_version)
5118737Skoansin.tan@gmail.com            Exit(1)
5128737Skoansin.tan@gmail.com    else:
5138737Skoansin.tan@gmail.com        print('Error: Unable to determine clang version.')
5148737Skoansin.tan@gmail.com        Exit(1)
5158737Skoansin.tan@gmail.com
5168737Skoansin.tan@gmail.com    # clang has a few additional warnings that we disable, extraneous
5178737Skoansin.tan@gmail.com    # parantheses are allowed due to Ruby's printing of the AST,
5188737Skoansin.tan@gmail.com    # finally self assignments are allowed as the generated CPU code
5198737Skoansin.tan@gmail.com    # is relying on this
5208737Skoansin.tan@gmail.com    main.Append(CCFLAGS=['-Wno-parentheses',
5218737Skoansin.tan@gmail.com                         '-Wno-self-assign',
5228737Skoansin.tan@gmail.com                         # Some versions of libstdc++ (4.8?) seem to
5233918Ssaidi@eecs.umich.edu                         # use struct hash and class hash
5243918Ssaidi@eecs.umich.edu                         # interchangeably.
5253940Ssaidi@eecs.umich.edu                         '-Wno-mismatched-tags',
5263918Ssaidi@eecs.umich.edu                         ])
5273918Ssaidi@eecs.umich.edu
5286157Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
5296157Snate@binkert.org
5306157Snate@binkert.org    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
5316157Snate@binkert.org    # opposed to libstdc++, as the later is dated.
5325397Ssaidi@eecs.umich.edu    if sys.platform == "darwin":
5335397Ssaidi@eecs.umich.edu        main.Append(CXXFLAGS=['-stdlib=libc++'])
5346121Snate@binkert.org        main.Append(LIBS=['c++'])
5356121Snate@binkert.org
5366121Snate@binkert.org    # On FreeBSD we need libthr.
5376121Snate@binkert.org    if sys.platform.startswith('freebsd'):
5386121Snate@binkert.org        main.Append(LIBS=['thr'])
5396121Snate@binkert.org
5405397Ssaidi@eecs.umich.edu    # We require clang >= 3.1, so there is no need to check any
5411851SN/A    # versions here.
5421851SN/A    if GetOption('with_ubsan'):
5437739Sgblack@eecs.umich.edu        if GetOption('with_asan'):
544955SN/A            env.Append(CCFLAGS=['-fsanitize=address,undefined',
5453053Sstever@eecs.umich.edu                                '-fno-omit-frame-pointer'],
5466121Snate@binkert.org                       LINKFLAGS='-fsanitize=address,undefined')
5473053Sstever@eecs.umich.edu        else:
5483053Sstever@eecs.umich.edu            env.Append(CCFLAGS='-fsanitize=undefined',
5493053Sstever@eecs.umich.edu                       LINKFLAGS='-fsanitize=undefined')
5503053Sstever@eecs.umich.edu
5513053Sstever@eecs.umich.edu    elif GetOption('with_asan'):
5526654Snate@binkert.org        env.Append(CCFLAGS=['-fsanitize=address',
5533053Sstever@eecs.umich.edu                            '-fno-omit-frame-pointer'],
5544742Sstever@eecs.umich.edu                   LINKFLAGS='-fsanitize=address')
5554742Sstever@eecs.umich.edu
5563053Sstever@eecs.umich.eduelse:
5573053Sstever@eecs.umich.edu    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
5583053Sstever@eecs.umich.edu    print("Don't know what compiler options to use for your compiler.")
5593053Sstever@eecs.umich.edu    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
5606654Snate@binkert.org    print(termcap.Yellow + '       version:' + termcap.Normal, end=' ')
5613053Sstever@eecs.umich.edu    if not CXX_version:
5623053Sstever@eecs.umich.edu        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
5633053Sstever@eecs.umich.edu              termcap.Normal)
5643053Sstever@eecs.umich.edu    else:
5652667Sstever@eecs.umich.edu        print(CXX_version.replace('\n', '<nl>'))
5664554Sbinkertn@umich.edu    print("       If you're trying to use a compiler other than GCC")
5676121Snate@binkert.org    print("       or clang, there appears to be something wrong with your")
5682667Sstever@eecs.umich.edu    print("       environment.")
5694554Sbinkertn@umich.edu    print("       ")
5704554Sbinkertn@umich.edu    print("       If you are trying to use a compiler other than those listed")
5714554Sbinkertn@umich.edu    print("       above you will need to ease fix SConstruct and ")
5726121Snate@binkert.org    print("       src/SConscript to support that compiler.")
5734554Sbinkertn@umich.edu    Exit(1)
5744554Sbinkertn@umich.edu
5754554Sbinkertn@umich.edu# Set up common yacc/bison flags (needed for Ruby)
5764781Snate@binkert.orgmain['YACCFLAGS'] = '-d'
5774554Sbinkertn@umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
5784554Sbinkertn@umich.edu
5792667Sstever@eecs.umich.edu# Do this after we save setting back, or else we'll tack on an
5804554Sbinkertn@umich.edu# extra 'qdo' every time we run scons.
5814554Sbinkertn@umich.eduif main['BATCH']:
5824554Sbinkertn@umich.edu    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
5834554Sbinkertn@umich.edu    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
5842667Sstever@eecs.umich.edu    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
5854554Sbinkertn@umich.edu    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
5862667Sstever@eecs.umich.edu    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
5874554Sbinkertn@umich.edu
5886121Snate@binkert.orgif sys.platform == 'cygwin':
5892667Sstever@eecs.umich.edu    # cygwin has some header file issues...
5905522Snate@binkert.org    main.Append(CCFLAGS=["-Wno-uninitialized"])
5915522Snate@binkert.org
5925522Snate@binkert.org# Check for the protobuf compiler
5935522Snate@binkert.orgprotoc_version = readCommand([main['PROTOC'], '--version'],
5945522Snate@binkert.org                             exception='').split()
5955522Snate@binkert.org
5965522Snate@binkert.org# First two words should be "libprotoc x.y.z"
5975522Snate@binkert.orgif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
5985522Snate@binkert.org    print(termcap.Yellow + termcap.Bold +
5995522Snate@binkert.org        'Warning: Protocol buffer compiler (protoc) not found.\n' +
6005522Snate@binkert.org        '         Please install protobuf-compiler for tracing support.' +
6015522Snate@binkert.org        termcap.Normal)
6025522Snate@binkert.org    main['PROTOC'] = False
6035522Snate@binkert.orgelse:
6045522Snate@binkert.org    # Based on the availability of the compress stream wrappers,
6055522Snate@binkert.org    # require 2.1.0
6065522Snate@binkert.org    min_protoc_version = '2.1.0'
6075522Snate@binkert.org    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6085522Snate@binkert.org        print(termcap.Yellow + termcap.Bold +
6095522Snate@binkert.org            'Warning: protoc version', min_protoc_version,
6105522Snate@binkert.org            'or newer required.\n' +
6115522Snate@binkert.org            '         Installed version:', protoc_version[1],
6125522Snate@binkert.org            termcap.Normal)
6135522Snate@binkert.org        main['PROTOC'] = False
6145522Snate@binkert.org    else:
6155522Snate@binkert.org        # Attempt to determine the appropriate include path and
6162638Sstever@eecs.umich.edu        # library path using pkg-config, that means we also need to
6172638Sstever@eecs.umich.edu        # check for pkg-config. Note that it is possible to use
6186121Snate@binkert.org        # protobuf without the involvement of pkg-config. Later on we
6193716Sstever@eecs.umich.edu        # check go a library config check and at that point the test
6205522Snate@binkert.org        # will fail if libprotobuf cannot be found.
6215522Snate@binkert.org        if readCommand(['pkg-config', '--version'], exception=''):
6225522Snate@binkert.org            try:
6235522Snate@binkert.org                # Attempt to establish what linking flags to add for protobuf
6245522Snate@binkert.org                # using pkg-config
6255522Snate@binkert.org                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
6261858SN/A            except:
6275227Ssaidi@eecs.umich.edu                print(termcap.Yellow + termcap.Bold +
6285227Ssaidi@eecs.umich.edu                    'Warning: pkg-config could not get protobuf flags.' +
6295227Ssaidi@eecs.umich.edu                    termcap.Normal)
6305227Ssaidi@eecs.umich.edu
6316654Snate@binkert.org
6326654Snate@binkert.org# Check for 'timeout' from GNU coreutils. If present, regressions will
6337769SAli.Saidi@ARM.com# be run with a time limit. We require version 8.13 since we rely on
6347769SAli.Saidi@ARM.com# support for the '--foreground' option.
6357769SAli.Saidi@ARM.comif sys.platform.startswith('freebsd'):
6367769SAli.Saidi@ARM.com    timeout_lines = readCommand(['gtimeout', '--version'],
6375227Ssaidi@eecs.umich.edu                                exception='').splitlines()
6385227Ssaidi@eecs.umich.eduelse:
6395227Ssaidi@eecs.umich.edu    timeout_lines = readCommand(['timeout', '--version'],
6405204Sstever@gmail.com                                exception='').splitlines()
6415204Sstever@gmail.com# Get the first line and tokenize it
6425204Sstever@gmail.comtimeout_version = timeout_lines[0].split() if timeout_lines else []
6435204Sstever@gmail.commain['TIMEOUT'] =  timeout_version and \
6445204Sstever@gmail.com    compareVersions(timeout_version[-1], '8.13') >= 0
6455204Sstever@gmail.com
6465204Sstever@gmail.com# Add a custom Check function to test for structure members.
6475204Sstever@gmail.comdef CheckMember(context, include, decl, member, include_quotes="<>"):
6485204Sstever@gmail.com    context.Message("Checking for member %s in %s..." %
6495204Sstever@gmail.com                    (member, decl))
6505204Sstever@gmail.com    text = """
6515204Sstever@gmail.com#include %(header)s
6525204Sstever@gmail.comint main(){
6535204Sstever@gmail.com  %(decl)s test;
6545204Sstever@gmail.com  (void)test.%(member)s;
6555204Sstever@gmail.com  return 0;
6565204Sstever@gmail.com};
6576121Snate@binkert.org""" % { "header" : include_quotes[0] + include + include_quotes[1],
6585204Sstever@gmail.com        "decl" : decl,
6593118Sstever@eecs.umich.edu        "member" : member,
6603118Sstever@eecs.umich.edu        }
6613118Sstever@eecs.umich.edu
6623118Sstever@eecs.umich.edu    ret = context.TryCompile(text, extension=".cc")
6633118Sstever@eecs.umich.edu    context.Result(ret)
6645863Snate@binkert.org    return ret
6653118Sstever@eecs.umich.edu
6665863Snate@binkert.org# Platform-specific configuration.  Note again that we assume that all
6673118Sstever@eecs.umich.edu# builds under a given build root run on the same host platform.
6687457Snate@binkert.orgconf = Configure(main,
6697457Snate@binkert.org                 conf_dir = joinpath(build_root, '.scons_config'),
6705863Snate@binkert.org                 log_file = joinpath(build_root, 'scons_config.log'),
6715863Snate@binkert.org                 custom_tests = {
6725863Snate@binkert.org        'CheckMember' : CheckMember,
6735863Snate@binkert.org        })
6745863Snate@binkert.org
6755863Snate@binkert.org# Check if we should compile a 64 bit binary on Mac OS X/Darwin
6765863Snate@binkert.orgtry:
6776003Snate@binkert.org    import platform
6785863Snate@binkert.org    uname = platform.uname()
6795863Snate@binkert.org    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
6805863Snate@binkert.org        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
6816120Snate@binkert.org            main.Append(CCFLAGS=['-arch', 'x86_64'])
6825863Snate@binkert.org            main.Append(CFLAGS=['-arch', 'x86_64'])
6835863Snate@binkert.org            main.Append(LINKFLAGS=['-arch', 'x86_64'])
6845863Snate@binkert.org            main.Append(ASFLAGS=['-arch', 'x86_64'])
6858655Sandreas.hansson@arm.comexcept:
6868655Sandreas.hansson@arm.com    pass
6878655Sandreas.hansson@arm.com
6888655Sandreas.hansson@arm.com# Recent versions of scons substitute a "Null" object for Configure()
6898655Sandreas.hansson@arm.com# when configuration isn't necessary, e.g., if the "--help" option is
6908655Sandreas.hansson@arm.com# present.  Unfortuantely this Null object always returns false,
6918655Sandreas.hansson@arm.com# breaking all our configuration checks.  We replace it with our own
6928655Sandreas.hansson@arm.com# more optimistic null object that returns True instead.
6936120Snate@binkert.orgif not conf:
6945863Snate@binkert.org    def NullCheck(*args, **kwargs):
6956121Snate@binkert.org        return True
6966121Snate@binkert.org
6975863Snate@binkert.org    class NullConf:
6987727SAli.Saidi@ARM.com        def __init__(self, env):
6997727SAli.Saidi@ARM.com            self.env = env
7007727SAli.Saidi@ARM.com        def Finish(self):
7017727SAli.Saidi@ARM.com            return self.env
7027727SAli.Saidi@ARM.com        def __getattr__(self, mname):
7037727SAli.Saidi@ARM.com            return NullCheck
7045863Snate@binkert.org
7053118Sstever@eecs.umich.edu    conf = NullConf(main)
7065863Snate@binkert.org
7073118Sstever@eecs.umich.edu# Cache build files in the supplied directory.
7083118Sstever@eecs.umich.eduif main['M5_BUILD_CACHE']:
7095863Snate@binkert.org    print('Using build cache located at', main['M5_BUILD_CACHE'])
7105863Snate@binkert.org    CacheDir(main['M5_BUILD_CACHE'])
7115863Snate@binkert.org
7125863Snate@binkert.orgmain['USE_PYTHON'] = not GetOption('without_python')
7133118Sstever@eecs.umich.eduif main['USE_PYTHON']:
7143483Ssaidi@eecs.umich.edu    # Find Python include and library directories for embedding the
7153494Ssaidi@eecs.umich.edu    # interpreter. We rely on python-config to resolve the appropriate
7163494Ssaidi@eecs.umich.edu    # includes and linker flags. ParseConfig does not seem to understand
7173483Ssaidi@eecs.umich.edu    # the more exotic linker flags such as -Xlinker and -export-dynamic so
7183483Ssaidi@eecs.umich.edu    # we add them explicitly below. If you want to link in an alternate
7193483Ssaidi@eecs.umich.edu    # version of python, see above for instructions on how to invoke
7203053Sstever@eecs.umich.edu    # scons with the appropriate PATH set.
7213053Sstever@eecs.umich.edu    #
7223918Ssaidi@eecs.umich.edu    # First we check if python2-config exists, else we use python-config
7233053Sstever@eecs.umich.edu    python_config = readCommand(['which', 'python2-config'],
7243053Sstever@eecs.umich.edu                                exception='').strip()
7253053Sstever@eecs.umich.edu    if not os.path.exists(python_config):
7263053Sstever@eecs.umich.edu        python_config = readCommand(['which', 'python-config'],
7273053Sstever@eecs.umich.edu                                    exception='').strip()
7287840Snate@binkert.org    py_includes = readCommand([python_config, '--includes'],
7297865Sgblack@eecs.umich.edu                              exception='').split()
7307865Sgblack@eecs.umich.edu    # Strip the -I from the include folders before adding them to the
7317865Sgblack@eecs.umich.edu    # CPPPATH
7327865Sgblack@eecs.umich.edu    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
7337865Sgblack@eecs.umich.edu
7347840Snate@binkert.org    # Read the linker flags and split them into libraries and other link
7357840Snate@binkert.org    # flags. The libraries are added later through the call the CheckLib.
7367840Snate@binkert.org    py_ld_flags = readCommand([python_config, '--ldflags'],
7377840Snate@binkert.org        exception='').split()
7381858SN/A    py_libs = []
7391858SN/A    for lib in py_ld_flags:
7401858SN/A         if not lib.startswith('-l'):
7411858SN/A             main.Append(LINKFLAGS=[lib])
7421858SN/A         else:
7431858SN/A             lib = lib[2:]
7445863Snate@binkert.org             if lib not in py_libs:
7455863Snate@binkert.org                 py_libs.append(lib)
7465863Snate@binkert.org
7475863Snate@binkert.org    # verify that this stuff works
7486121Snate@binkert.org    if not conf.CheckHeader('Python.h', '<>'):
7491858SN/A        print("Error: Check failed for Python.h header in", py_includes)
7505863Snate@binkert.org        print("Two possible reasons:")
7515863Snate@binkert.org        print("1. Python headers are not installed (You can install the "
7525863Snate@binkert.org              "package python-dev on Ubuntu and RedHat)")
7535863Snate@binkert.org        print("2. SCons is using a wrong C compiler. This can happen if "
7545863Snate@binkert.org              "CC has the wrong value.")
7552139SN/A        print("CC = %s" % main['CC'])
7564202Sbinkertn@umich.edu        Exit(1)
7574202Sbinkertn@umich.edu
7582139SN/A    for lib in py_libs:
7596994Snate@binkert.org        if not conf.CheckLib(lib):
7606994Snate@binkert.org            print("Error: can't find library %s required by python" % lib)
7616994Snate@binkert.org            Exit(1)
7626994Snate@binkert.org
7636994Snate@binkert.org# On Solaris you need to use libsocket for socket ops
7646994Snate@binkert.orgif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7656994Snate@binkert.org   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7666994Snate@binkert.org       print("Can't find library with socket calls (e.g. accept())")
7676994Snate@binkert.org       Exit(1)
7686994Snate@binkert.org
7696994Snate@binkert.org# Check for zlib.  If the check passes, libz will be automatically
7706994Snate@binkert.org# added to the LIBS environment variable.
7716994Snate@binkert.orgif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
7726994Snate@binkert.org    print('Error: did not find needed zlib compression library '
7736994Snate@binkert.org          'and/or zlib.h header file.')
7746994Snate@binkert.org    print('       Please install zlib and try again.')
7756994Snate@binkert.org    Exit(1)
7766994Snate@binkert.org
7776994Snate@binkert.org# If we have the protobuf compiler, also make sure we have the
7786994Snate@binkert.org# development libraries. If the check passes, libprotobuf will be
7796994Snate@binkert.org# automatically added to the LIBS environment variable. After
7806994Snate@binkert.org# this, we can use the HAVE_PROTOBUF flag to determine if we have
7816994Snate@binkert.org# got both protoc and libprotobuf available.
7826994Snate@binkert.orgmain['HAVE_PROTOBUF'] = main['PROTOC'] and \
7836994Snate@binkert.org    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
7846994Snate@binkert.org                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
7856994Snate@binkert.org
7866994Snate@binkert.org# If we have the compiler but not the library, print another warning.
7872155SN/Aif main['PROTOC'] and not main['HAVE_PROTOBUF']:
7885863Snate@binkert.org    print(termcap.Yellow + termcap.Bold +
7891869SN/A        'Warning: did not find protocol buffer library and/or headers.\n' +
7901869SN/A    '       Please install libprotobuf-dev for tracing support.' +
7915863Snate@binkert.org    termcap.Normal)
7925863Snate@binkert.org
7934202Sbinkertn@umich.edu# Check for librt.
7946108Snate@binkert.orghave_posix_clock = \
7956108Snate@binkert.org    conf.CheckLibWithHeader(None, 'time.h', 'C',
7966108Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);') or \
7976108Snate@binkert.org    conf.CheckLibWithHeader('rt', 'time.h', 'C',
7984202Sbinkertn@umich.edu                            'clock_nanosleep(0,0,NULL,NULL);')
7995863Snate@binkert.org
8008474Sgblack@eecs.umich.eduhave_posix_timers = \
8018474Sgblack@eecs.umich.edu    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
8025742Snate@binkert.org                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
8038268Ssteve.reinhardt@amd.com
8048268Ssteve.reinhardt@amd.comif not GetOption('without_tcmalloc'):
8058268Ssteve.reinhardt@amd.com    if conf.CheckLib('tcmalloc'):
8065742Snate@binkert.org        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
8075341Sstever@gmail.com    elif conf.CheckLib('tcmalloc_minimal'):
8088474Sgblack@eecs.umich.edu        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
8098474Sgblack@eecs.umich.edu    else:
8105342Sstever@gmail.com        print(termcap.Yellow + termcap.Bold +
8114202Sbinkertn@umich.edu              "You can get a 12% performance improvement by "
8124202Sbinkertn@umich.edu              "installing tcmalloc (libgoogle-perftools-dev package "
8134202Sbinkertn@umich.edu              "on Ubuntu or RedHat)." + termcap.Normal)
8145863Snate@binkert.org
8155863Snate@binkert.org
8166994Snate@binkert.org# Detect back trace implementations. The last implementation in the
8176994Snate@binkert.org# list will be used by default.
8186994Snate@binkert.orgbacktrace_impls = [ "none" ]
8195863Snate@binkert.org
8208152Ssteve.reinhardt@amd.combacktrace_checker = 'char temp;' + \
8218878Ssteve.reinhardt@amd.com    ' backtrace_symbols_fd((void*)&temp, 0, 0);'
8225863Snate@binkert.orgif conf.CheckLibWithHeader(None, 'execinfo.h', 'C', backtrace_checker):
8235863Snate@binkert.org    backtrace_impls.append("glibc")
8245863Snate@binkert.orgelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
8255863Snate@binkert.org                             backtrace_checker):
8265863Snate@binkert.org    # NetBSD and FreeBSD need libexecinfo.
8275863Snate@binkert.org    backtrace_impls.append("glibc")
8285863Snate@binkert.org    main.Append(LIBS=['execinfo'])
8295863Snate@binkert.org
8305863Snate@binkert.orgif backtrace_impls[-1] == "none":
8315863Snate@binkert.org    default_backtrace_impl = "none"
8327840Snate@binkert.org    print(termcap.Yellow + termcap.Bold +
8335863Snate@binkert.org        "No suitable back trace implementation found." +
8345863Snate@binkert.org        termcap.Normal)
8355952Ssaidi@eecs.umich.edu
8361869SN/Aif not have_posix_clock:
8371858SN/A    print("Can't find library for POSIX clocks.")
8385863Snate@binkert.org
8398805Sgblack@eecs.umich.edu# Check for <fenv.h> (C99 FP environment control)
8408805Sgblack@eecs.umich.eduhave_fenv = conf.CheckHeader('fenv.h', '<>')
8418805Sgblack@eecs.umich.eduif not have_fenv:
8421858SN/A    print("Warning: Header file <fenv.h> not found.")
843955SN/A    print("         This host has no IEEE FP rounding mode control.")
844955SN/A
8451869SN/A# Check for <png.h> (libpng library needed if wanting to dump
8461869SN/A# frame buffer image in png format)
8471869SN/Ahave_png = conf.CheckHeader('png.h', '<>')
8481869SN/Aif not have_png:
8491869SN/A    print("Warning: Header file <png.h> not found.")
8505863Snate@binkert.org    print("         This host has no libpng library.")
8515863Snate@binkert.org    print("         Disabling support for PNG framebuffers.")
8525863Snate@binkert.org
8531869SN/A# Check if we should enable KVM-based hardware virtualization. The API
8545863Snate@binkert.org# we rely on exists since version 2.6.36 of the kernel, but somehow
8551869SN/A# the KVM_API_VERSION does not reflect the change. We test for one of
8565863Snate@binkert.org# the types as a fall back.
8571869SN/Ahave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
8581869SN/Aif not have_kvm:
8591869SN/A    print("Info: Compatible header file <linux/kvm.h> not found, "
8601869SN/A          "disabling KVM support.")
8618483Sgblack@eecs.umich.edu
8621869SN/A# Check if the TUN/TAP driver is available.
8631869SN/Ahave_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
8641869SN/Aif not have_tuntap:
8651869SN/A    print("Info: Compatible header file <linux/if_tun.h> not found.")
8665863Snate@binkert.org
8675863Snate@binkert.org# x86 needs support for xsave. We test for the structure here since we
8681869SN/A# won't be able to run new tests by the time we know which ISA we're
8695863Snate@binkert.org# targeting.
8705863Snate@binkert.orghave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
8713356Sbinkertn@umich.edu                                    '#include <linux/kvm.h>') != 0
8723356Sbinkertn@umich.edu
8733356Sbinkertn@umich.edu# Check if the requested target ISA is compatible with the host
8743356Sbinkertn@umich.edudef is_isa_kvm_compatible(isa):
8753356Sbinkertn@umich.edu    try:
8764781Snate@binkert.org        import platform
8775863Snate@binkert.org        host_isa = platform.machine()
8785863Snate@binkert.org    except:
8791869SN/A        print("Warning: Failed to determine host ISA.")
8801869SN/A        return False
8811869SN/A
8826121Snate@binkert.org    if not have_posix_timers:
8831869SN/A        print("Warning: Can not enable KVM, host seems to lack support "
8842638Sstever@eecs.umich.edu              "for POSIX timers")
8856121Snate@binkert.org        return False
8866121Snate@binkert.org
8872638Sstever@eecs.umich.edu    if isa == "arm":
8885749Scws3k@cs.virginia.edu        return host_isa in ( "armv7l", "aarch64" )
8896121Snate@binkert.org    elif isa == "x86":
8906121Snate@binkert.org        if host_isa != "x86_64":
8915749Scws3k@cs.virginia.edu            return False
8921869SN/A
8931869SN/A        if not have_kvm_xsave:
8943546Sgblack@eecs.umich.edu            print("KVM on x86 requires xsave support in kernel headers.")
8953546Sgblack@eecs.umich.edu            return False
8963546Sgblack@eecs.umich.edu
8973546Sgblack@eecs.umich.edu        return True
8986121Snate@binkert.org    else:
8995863Snate@binkert.org        return False
9003546Sgblack@eecs.umich.edu
9013546Sgblack@eecs.umich.edu
9023546Sgblack@eecs.umich.edu# Check if the exclude_host attribute is available. We want this to
9033546Sgblack@eecs.umich.edu# get accurate instruction counts in KVM.
9044781Snate@binkert.orgmain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
9054781Snate@binkert.org    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
9066658Snate@binkert.org
9076658Snate@binkert.org
9084781Snate@binkert.org######################################################################
9093546Sgblack@eecs.umich.edu#
9103546Sgblack@eecs.umich.edu# Finish the configuration
9113546Sgblack@eecs.umich.edu#
9123546Sgblack@eecs.umich.edumain = conf.Finish()
9137756SAli.Saidi@ARM.com
9147816Ssteve.reinhardt@amd.com######################################################################
9153546Sgblack@eecs.umich.edu#
9163546Sgblack@eecs.umich.edu# Collect all non-global variables
9173546Sgblack@eecs.umich.edu#
9183546Sgblack@eecs.umich.edu
9194202Sbinkertn@umich.edu# Define the universe of supported ISAs
9203546Sgblack@eecs.umich.eduall_isa_list = [ ]
9213546Sgblack@eecs.umich.eduall_gpu_isa_list = [ ]
9223546Sgblack@eecs.umich.eduExport('all_isa_list')
923955SN/AExport('all_gpu_isa_list')
924955SN/A
925955SN/Aclass CpuModel(object):
926955SN/A    '''The CpuModel class encapsulates everything the ISA parser needs to
9275863Snate@binkert.org    know about a particular CPU model.'''
9285863Snate@binkert.org
9295343Sstever@gmail.com    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
9305343Sstever@gmail.com    dict = {}
9316121Snate@binkert.org
9325863Snate@binkert.org    # Constructor.  Automatically adds models to CpuModel.dict.
9334773Snate@binkert.org    def __init__(self, name, default=False):
9345863Snate@binkert.org        self.name = name           # name of model
9352632Sstever@eecs.umich.edu
9365863Snate@binkert.org        # This cpu is enabled by default
9372023SN/A        self.default = default
9385863Snate@binkert.org
9395863Snate@binkert.org        # Add self to dict
9405863Snate@binkert.org        if name in CpuModel.dict:
9415863Snate@binkert.org            raise AttributeError, "CpuModel '%s' already registered" % name
9425863Snate@binkert.org        CpuModel.dict[name] = self
9435863Snate@binkert.org
9445863Snate@binkert.orgExport('CpuModel')
9455863Snate@binkert.org
9465863Snate@binkert.org# Sticky variables get saved in the variables file so they persist from
9472632Sstever@eecs.umich.edu# one invocation to the next (unless overridden, in which case the new
9485863Snate@binkert.org# value becomes sticky).
9492023SN/Asticky_vars = Variables(args=ARGUMENTS)
9502632Sstever@eecs.umich.eduExport('sticky_vars')
9515863Snate@binkert.org
9525342Sstever@gmail.com# Sticky variables that should be exported
9535863Snate@binkert.orgexport_vars = []
9542632Sstever@eecs.umich.eduExport('export_vars')
9555863Snate@binkert.org
9565863Snate@binkert.org# For Ruby
9578267Ssteve.reinhardt@amd.comall_protocols = []
9588120Sgblack@eecs.umich.eduExport('all_protocols')
9598267Ssteve.reinhardt@amd.comprotocol_dirs = []
9608267Ssteve.reinhardt@amd.comExport('protocol_dirs')
9618267Ssteve.reinhardt@amd.comslicc_includes = []
9628267Ssteve.reinhardt@amd.comExport('slicc_includes')
9638267Ssteve.reinhardt@amd.com
9648267Ssteve.reinhardt@amd.com# Walk the tree and execute all SConsopts scripts that wil add to the
9658267Ssteve.reinhardt@amd.com# above variables
9668267Ssteve.reinhardt@amd.comif GetOption('verbose'):
9678267Ssteve.reinhardt@amd.com    print("Reading SConsopts")
9685863Snate@binkert.orgfor bdir in [ base_dir ] + extras_dir_list:
9695863Snate@binkert.org    if not isdir(bdir):
9705863Snate@binkert.org        print("Error: directory '%s' does not exist" % bdir)
9712632Sstever@eecs.umich.edu        Exit(1)
9728267Ssteve.reinhardt@amd.com    for root, dirs, files in os.walk(bdir):
9738267Ssteve.reinhardt@amd.com        if 'SConsopts' in files:
9748267Ssteve.reinhardt@amd.com            if GetOption('verbose'):
9752632Sstever@eecs.umich.edu                print("Reading", joinpath(root, 'SConsopts'))
9761888SN/A            SConscript(joinpath(root, 'SConsopts'))
9775863Snate@binkert.org
9785863Snate@binkert.orgall_isa_list.sort()
9791858SN/Aall_gpu_isa_list.sort()
9808120Sgblack@eecs.umich.edu
9818120Sgblack@eecs.umich.edusticky_vars.AddVariables(
9827756SAli.Saidi@ARM.com    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
9832598SN/A    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
9845863Snate@binkert.org    ListVariable('CPU_MODELS', 'CPU models',
9851858SN/A                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
9861858SN/A                 sorted(CpuModel.dict.keys())),
9871858SN/A    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
9885863Snate@binkert.org                 False),
9891858SN/A    BoolVariable('SS_COMPATIBLE_FP',
9901858SN/A                 'Make floating-point results compatible with SimpleScalar',
9911858SN/A                 False),
9925863Snate@binkert.org    BoolVariable('USE_SSE2',
9931871SN/A                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
9941858SN/A                 False),
9951858SN/A    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
9961858SN/A    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
9971858SN/A    BoolVariable('USE_PNG',  'Enable support for PNG images', have_png),
9985863Snate@binkert.org    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability',
9995863Snate@binkert.org                 False),
10001869SN/A    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models',
10011965SN/A                 have_kvm),
10027739Sgblack@eecs.umich.edu    BoolVariable('USE_TUNTAP',
10031965SN/A                 'Enable using a tap device to bridge to the host network',
10042761Sstever@eecs.umich.edu                 have_tuntap),
10055863Snate@binkert.org    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
10061869SN/A    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
10075863Snate@binkert.org                  all_protocols),
10082667Sstever@eecs.umich.edu    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
10091869SN/A                 backtrace_impls[-1], backtrace_impls)
10101869SN/A    )
10112929Sktlim@umich.edu
10122929Sktlim@umich.edu# These variables get exported to #defines in config/*.hh (see src/SConscript).
10135863Snate@binkert.orgexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
10142929Sktlim@umich.edu                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
1015955SN/A                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST',
10168120Sgblack@eecs.umich.edu                'USE_PNG']
10178120Sgblack@eecs.umich.edu
10188120Sgblack@eecs.umich.edu###################################################
10198120Sgblack@eecs.umich.edu#
10208120Sgblack@eecs.umich.edu# Define a SCons builder for configuration flag headers.
10218120Sgblack@eecs.umich.edu#
10228120Sgblack@eecs.umich.edu###################################################
10238120Sgblack@eecs.umich.edu
10248120Sgblack@eecs.umich.edu# This function generates a config header file that #defines the
10258120Sgblack@eecs.umich.edu# variable symbol to the current variable setting (0 or 1).  The source
10268120Sgblack@eecs.umich.edu# operands are the name of the variable and a Value node containing the
10278120Sgblack@eecs.umich.edu# value of the variable.
1028def build_config_file(target, source, env):
1029    (variable, value) = [s.get_contents() for s in source]
1030    f = file(str(target[0]), 'w')
1031    print('#define', variable, value, file=f)
1032    f.close()
1033    return None
1034
1035# Combine the two functions into a scons Action object.
1036config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1037
1038# The emitter munges the source & target node lists to reflect what
1039# we're really doing.
1040def config_emitter(target, source, env):
1041    # extract variable name from Builder arg
1042    variable = str(target[0])
1043    # True target is config header file
1044    target = joinpath('config', variable.lower() + '.hh')
1045    val = env[variable]
1046    if isinstance(val, bool):
1047        # Force value to 0/1
1048        val = int(val)
1049    elif isinstance(val, str):
1050        val = '"' + val + '"'
1051
1052    # Sources are variable name & value (packaged in SCons Value nodes)
1053    return ([target], [Value(variable), Value(val)])
1054
1055config_builder = Builder(emitter = config_emitter, action = config_action)
1056
1057main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1058
1059###################################################
1060#
1061# Builders for static and shared partially linked object files.
1062#
1063###################################################
1064
1065partial_static_builder = Builder(action=SCons.Defaults.LinkAction,
1066                                 src_suffix='$OBJSUFFIX',
1067                                 src_builder=['StaticObject', 'Object'],
1068                                 LINKFLAGS='$PLINKFLAGS',
1069                                 LIBS='')
1070
1071def partial_shared_emitter(target, source, env):
1072    for tgt in target:
1073        tgt.attributes.shared = 1
1074    return (target, source)
1075partial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
1076                                 emitter=partial_shared_emitter,
1077                                 src_suffix='$SHOBJSUFFIX',
1078                                 src_builder='SharedObject',
1079                                 SHLINKFLAGS='$PSHLINKFLAGS',
1080                                 LIBS='')
1081
1082main.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
1083                         'PartialStatic' : partial_static_builder })
1084
1085# builds in ext are shared across all configs in the build root.
1086ext_dir = abspath(joinpath(str(main.root), 'ext'))
1087ext_build_dirs = []
1088for root, dirs, files in os.walk(ext_dir):
1089    if 'SConscript' in files:
1090        build_dir = os.path.relpath(root, ext_dir)
1091        ext_build_dirs.append(build_dir)
1092        main.SConscript(joinpath(root, 'SConscript'),
1093                        variant_dir=joinpath(build_root, build_dir))
1094
1095main.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
1096
1097###################################################
1098#
1099# This builder and wrapper method are used to set up a directory with
1100# switching headers. Those are headers which are in a generic location and
1101# that include more specific headers from a directory chosen at build time
1102# based on the current build settings.
1103#
1104###################################################
1105
1106def build_switching_header(target, source, env):
1107    path = str(target[0])
1108    subdir = str(source[0])
1109    dp, fp = os.path.split(path)
1110    dp = os.path.relpath(os.path.realpath(dp),
1111                         os.path.realpath(env['BUILDDIR']))
1112    with open(path, 'w') as hdr:
1113        print('#include "%s/%s/%s"' % (dp, subdir, fp), file=hdr)
1114
1115switching_header_action = MakeAction(build_switching_header,
1116                                     Transform('GENERATE'))
1117
1118switching_header_builder = Builder(action=switching_header_action,
1119                                   source_factory=Value,
1120                                   single_source=True)
1121
1122main.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
1123
1124def switching_headers(self, headers, source):
1125    for header in headers:
1126        self.SwitchingHeader(header, source)
1127
1128main.AddMethod(switching_headers, 'SwitchingHeaders')
1129
1130###################################################
1131#
1132# Define build environments for selected configurations.
1133#
1134###################################################
1135
1136for variant_path in variant_paths:
1137    if not GetOption('silent'):
1138        print("Building in", variant_path)
1139
1140    # Make a copy of the build-root environment to use for this config.
1141    env = main.Clone()
1142    env['BUILDDIR'] = variant_path
1143
1144    # variant_dir is the tail component of build path, and is used to
1145    # determine the build parameters (e.g., 'ALPHA_SE')
1146    (build_root, variant_dir) = splitpath(variant_path)
1147
1148    # Set env variables according to the build directory config.
1149    sticky_vars.files = []
1150    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1151    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1152    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1153    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1154    if isfile(current_vars_file):
1155        sticky_vars.files.append(current_vars_file)
1156        if not GetOption('silent'):
1157            print("Using saved variables file %s" % current_vars_file)
1158    elif variant_dir in ext_build_dirs:
1159        # Things in ext are built without a variant directory.
1160        continue
1161    else:
1162        # Build dir-specific variables file doesn't exist.
1163
1164        # Make sure the directory is there so we can create it later
1165        opt_dir = dirname(current_vars_file)
1166        if not isdir(opt_dir):
1167            mkdir(opt_dir)
1168
1169        # Get default build variables from source tree.  Variables are
1170        # normally determined by name of $VARIANT_DIR, but can be
1171        # overridden by '--default=' arg on command line.
1172        default = GetOption('default')
1173        opts_dir = joinpath(main.root.abspath, 'build_opts')
1174        if default:
1175            default_vars_files = [joinpath(build_root, 'variables', default),
1176                                  joinpath(opts_dir, default)]
1177        else:
1178            default_vars_files = [joinpath(opts_dir, variant_dir)]
1179        existing_files = filter(isfile, default_vars_files)
1180        if existing_files:
1181            default_vars_file = existing_files[0]
1182            sticky_vars.files.append(default_vars_file)
1183            print("Variables file %s not found,\n  using defaults in %s"
1184                  % (current_vars_file, default_vars_file))
1185        else:
1186            print("Error: cannot find variables file %s or "
1187                  "default file(s) %s"
1188                  % (current_vars_file, ' or '.join(default_vars_files)))
1189            Exit(1)
1190
1191    # Apply current variable settings to env
1192    sticky_vars.Update(env)
1193
1194    help_texts["local_vars"] += \
1195        "Build variables for %s:\n" % variant_dir \
1196                 + sticky_vars.GenerateHelpText(env)
1197
1198    # Process variable settings.
1199
1200    if not have_fenv and env['USE_FENV']:
1201        print("Warning: <fenv.h> not available; "
1202              "forcing USE_FENV to False in", variant_dir + ".")
1203        env['USE_FENV'] = False
1204
1205    if not env['USE_FENV']:
1206        print("Warning: No IEEE FP rounding mode control in",
1207              variant_dir + ".")
1208        print("         FP results may deviate slightly from other platforms.")
1209
1210    if not have_png and env['USE_PNG']:
1211        print("Warning: <png.h> not available; "
1212              "forcing USE_PNG to False in", variant_dir + ".")
1213        env['USE_PNG'] = False
1214
1215    if env['USE_PNG']:
1216        env.Append(LIBS=['png'])
1217
1218    if env['EFENCE']:
1219        env.Append(LIBS=['efence'])
1220
1221    if env['USE_KVM']:
1222        if not have_kvm:
1223            print("Warning: Can not enable KVM, host seems to "
1224                  "lack KVM support")
1225            env['USE_KVM'] = False
1226        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1227            print("Info: KVM support disabled due to unsupported host and "
1228                  "target ISA combination")
1229            env['USE_KVM'] = False
1230
1231    if env['USE_TUNTAP']:
1232        if not have_tuntap:
1233            print("Warning: Can't connect EtherTap with a tap device.")
1234            env['USE_TUNTAP'] = False
1235
1236    if env['BUILD_GPU']:
1237        env.Append(CPPDEFINES=['BUILD_GPU'])
1238
1239    # Warn about missing optional functionality
1240    if env['USE_KVM']:
1241        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1242            print("Warning: perf_event headers lack support for the "
1243                  "exclude_host attribute. KVM instruction counts will "
1244                  "be inaccurate.")
1245
1246    # Save sticky variable settings back to current variables file
1247    sticky_vars.Save(current_vars_file, env)
1248
1249    if env['USE_SSE2']:
1250        env.Append(CCFLAGS=['-msse2'])
1251
1252    # The src/SConscript file sets up the build rules in 'env' according
1253    # to the configured variables.  It returns a list of environments,
1254    # one for each variant build (debug, opt, etc.)
1255    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1256
1257# base help text
1258Help('''
1259Usage: scons [scons options] [build variables] [target(s)]
1260
1261Extra scons options:
1262%(options)s
1263
1264Global build variables:
1265%(global_vars)s
1266
1267%(local_vars)s
1268''' % help_texts)
1269