SConstruct revision 12304
1955SN/A# -*- mode:python -*-
2955SN/A
311408Sandreas.sandberg@arm.com# Copyright (c) 2013, 2015-2017 ARM Limited
49812Sandreas.hansson@arm.com# All rights reserved.
59812Sandreas.hansson@arm.com#
69812Sandreas.hansson@arm.com# The license below extends only to copyright in the software and shall
79812Sandreas.hansson@arm.com# not be construed as granting a license to any other intellectual
89812Sandreas.hansson@arm.com# property including but not limited to intellectual property relating
99812Sandreas.hansson@arm.com# to a hardware implementation of the functionality of the software
109812Sandreas.hansson@arm.com# licensed hereunder.  You may use the software subject to the license
119812Sandreas.hansson@arm.com# terms below provided that you ensure that this notice is replicated
129812Sandreas.hansson@arm.com# unmodified and in its entirety in all distributions of the software,
139812Sandreas.hansson@arm.com# modified or unmodified, in source code or in binary form.
149812Sandreas.hansson@arm.com#
157816Ssteve.reinhardt@amd.com# Copyright (c) 2011 Advanced Micro Devices, Inc.
165871Snate@binkert.org# Copyright (c) 2009 The Hewlett-Packard Development Company
171762SN/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.
30955SN/A#
31955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
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,
38955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40955SN/A# (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.
422665Ssaidi@eecs.umich.edu#
432665Ssaidi@eecs.umich.edu# Authors: Steve Reinhardt
445863Snate@binkert.org#          Nathan Binkert
45955SN/A
46955SN/A###################################################
47955SN/A#
48955SN/A# SCons top-level build description (SConstruct) file.
49955SN/A#
508878Ssteve.reinhardt@amd.com# 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>'
528878Ssteve.reinhardt@amd.com# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
532632Sstever@eecs.umich.edu# the optimized full-system version).
54955SN/A#
558878Ssteve.reinhardt@amd.com# You can build gem5 in a different directory as long as there is a
562632Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
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:
612761Sstever@eecs.umich.edu#
622761Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
632761Sstever@eecs.umich.edu#   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
658878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
662761Sstever@eecs.umich.edu#
672761Sstever@eecs.umich.edu#   The following two commands are equivalent and demonstrate building
682761Sstever@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
692761Sstever@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
702761Sstever@eecs.umich.edu#   file.
718878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
728878Ssteve.reinhardt@amd.com#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
732632Sstever@eecs.umich.edu#
742632Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
758878Ssteve.reinhardt@amd.com# 'gem5' directory (or use -u or -C to tell scons where to find this
768878Ssteve.reinhardt@amd.com# file), you can use 'scons -h' to print all the gem5-specific build
772632Sstever@eecs.umich.edu# options as well.
78955SN/A#
79955SN/A###################################################
80955SN/A
815863Snate@binkert.org# Global Python includes
825863Snate@binkert.orgimport itertools
835863Snate@binkert.orgimport os
845863Snate@binkert.orgimport re
855863Snate@binkert.orgimport shutil
865863Snate@binkert.orgimport subprocess
875863Snate@binkert.orgimport sys
885863Snate@binkert.org
895863Snate@binkert.orgfrom os import mkdir, environ
905863Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
915863Snate@binkert.orgfrom os.path import exists,  isdir, isfile
928878Ssteve.reinhardt@amd.comfrom os.path import join as joinpath, split as splitpath
935863Snate@binkert.org
945863Snate@binkert.org# SCons includes
955863Snate@binkert.orgimport SCons
969812Sandreas.hansson@arm.comimport SCons.Node
979812Sandreas.hansson@arm.com
985863Snate@binkert.orgfrom m5.util import compareVersions, readCommand
999812Sandreas.hansson@arm.com
1005863Snate@binkert.orghelp_texts = {
1015863Snate@binkert.org    "options" : "",
1025863Snate@binkert.org    "global_vars" : "",
1039812Sandreas.hansson@arm.com    "local_vars" : ""
1049812Sandreas.hansson@arm.com}
1055863Snate@binkert.org
1065863Snate@binkert.orgExport("help_texts")
1078878Ssteve.reinhardt@amd.com
1085863Snate@binkert.org
1095863Snate@binkert.org# There's a bug in scons in that (1) by default, the help texts from
1105863Snate@binkert.org# AddOption() are supposed to be displayed when you type 'scons -h'
1116654Snate@binkert.org# and (2) you can override the help displayed by 'scons -h' using the
11210196SCurtis.Dunham@arm.com# Help() function, but these two features are incompatible: once
113955SN/A# you've overridden the help text using Help(), there's no way to get
1145396Ssaidi@eecs.umich.edu# at the help texts from AddOptions.  See:
11511401Sandreas.sandberg@arm.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1165863Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1175863Snate@binkert.org# This hack lets us extract the help text from AddOptions and
1184202Sbinkertn@umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1195863Snate@binkert.org# we can just use AddOption directly.
1205863Snate@binkert.orgdef AddLocalOption(*args, **kwargs):
1215863Snate@binkert.org    col_width = 30
1225863Snate@binkert.org
123955SN/A    help = "  " + ", ".join(args)
1246654Snate@binkert.org    if "help" in kwargs:
1255273Sstever@gmail.com        length = len(help)
1265871Snate@binkert.org        if length >= col_width:
1275273Sstever@gmail.com            help += "\n" + " " * col_width
1286655Snate@binkert.org        else:
1298878Ssteve.reinhardt@amd.com            help += " " * (col_width - length)
1306655Snate@binkert.org        help += kwargs["help"]
1316655Snate@binkert.org    help_texts["options"] += help + "\n"
1329219Spower.jg@gmail.com
1336655Snate@binkert.org    AddOption(*args, **kwargs)
1345871Snate@binkert.org
1356654Snate@binkert.orgAddLocalOption('--colors', dest='use_colors', action='store_true',
1368947Sandreas.hansson@arm.com               help="Add color to abbreviated scons output")
1375396Ssaidi@eecs.umich.eduAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1388120Sgblack@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1398120Sgblack@eecs.umich.eduAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1408120Sgblack@eecs.umich.edu               action='store_true',
1418120Sgblack@eecs.umich.edu               help="Build with support for C++-based configuration")
1428120Sgblack@eecs.umich.eduAddLocalOption('--default', dest='default', type='string', action='store',
1438120Sgblack@eecs.umich.edu               help='Override which build_opts file to use for defaults')
1448120Sgblack@eecs.umich.eduAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1458120Sgblack@eecs.umich.edu               help='Disable style checking hooks')
1468879Ssteve.reinhardt@amd.comAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1478879Ssteve.reinhardt@amd.com               help='Disable Link-Time Optimization for fast')
1488879Ssteve.reinhardt@amd.comAddLocalOption('--force-lto', dest='force_lto', action='store_true',
1498879Ssteve.reinhardt@amd.com               help='Use Link-Time Optimization instead of partial linking' +
1508879Ssteve.reinhardt@amd.com                    ' when the compiler doesn\'t support using them together.')
1518879Ssteve.reinhardt@amd.comAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1528879Ssteve.reinhardt@amd.com               help='Update test reference outputs')
1538879Ssteve.reinhardt@amd.comAddLocalOption('--verbose', dest='verbose', action='store_true',
1548879Ssteve.reinhardt@amd.com               help='Print full tool command lines')
1558879Ssteve.reinhardt@amd.comAddLocalOption('--without-python', dest='without_python',
1568879Ssteve.reinhardt@amd.com               action='store_true',
1578879Ssteve.reinhardt@amd.com               help='Build without Python configuration support')
1588879Ssteve.reinhardt@amd.comAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1598120Sgblack@eecs.umich.edu               action='store_true',
1608120Sgblack@eecs.umich.edu               help='Disable linking against tcmalloc')
1618120Sgblack@eecs.umich.eduAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1628120Sgblack@eecs.umich.edu               help='Build with Undefined Behavior Sanitizer if available')
1638120Sgblack@eecs.umich.eduAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1648120Sgblack@eecs.umich.edu               help='Build with Address Sanitizer if available')
1658120Sgblack@eecs.umich.edu
1668120Sgblack@eecs.umich.eduif GetOption('no_lto') and GetOption('force_lto'):
1678120Sgblack@eecs.umich.edu    print '--no-lto and --force-lto are mutually exclusive'
1688120Sgblack@eecs.umich.edu    Exit(1)
1698120Sgblack@eecs.umich.edu
1708120Sgblack@eecs.umich.edu########################################################################
1718120Sgblack@eecs.umich.edu#
1728120Sgblack@eecs.umich.edu# Set up the main build environment.
1738879Ssteve.reinhardt@amd.com#
1748879Ssteve.reinhardt@amd.com########################################################################
1758879Ssteve.reinhardt@amd.com
1768879Ssteve.reinhardt@amd.commain = Environment()
17710458Sandreas.hansson@arm.com
17810458Sandreas.hansson@arm.comfrom gem5_scons import Transform
17910458Sandreas.hansson@arm.comfrom gem5_scons.util import get_termcap
1808879Ssteve.reinhardt@amd.comtermcap = get_termcap()
1818879Ssteve.reinhardt@amd.com
1828879Ssteve.reinhardt@amd.commain_dict_keys = main.Dictionary().keys()
1838879Ssteve.reinhardt@amd.com
1849227Sandreas.hansson@arm.com# Check that we have a C/C++ compiler
1859227Sandreas.hansson@arm.comif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
1868879Ssteve.reinhardt@amd.com    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
1878879Ssteve.reinhardt@amd.com    Exit(1)
1888879Ssteve.reinhardt@amd.com
1898879Ssteve.reinhardt@amd.com###################################################
19010453SAndrew.Bardsley@arm.com#
19110453SAndrew.Bardsley@arm.com# Figure out which configurations to set up based on the path(s) of
19210453SAndrew.Bardsley@arm.com# the target(s).
19310456SCurtis.Dunham@arm.com#
19410456SCurtis.Dunham@arm.com###################################################
19510456SCurtis.Dunham@arm.com
19610457Sandreas.hansson@arm.com# Find default configuration & binary.
19710457Sandreas.hansson@arm.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
19811342Sandreas.hansson@arm.com
19911342Sandreas.hansson@arm.com# helper function: find last occurrence of element in list
2008120Sgblack@eecs.umich.edudef rfind(l, elt, offs = -1):
2018947Sandreas.hansson@arm.com    for i in range(len(l)+offs, 0, -1):
2027816Ssteve.reinhardt@amd.com        if l[i] == elt:
2035871Snate@binkert.org            return i
2045871Snate@binkert.org    raise ValueError, "element not found"
2056121Snate@binkert.org
2065871Snate@binkert.org# Take a list of paths (or SCons Nodes) and return a list with all
2075871Snate@binkert.org# paths made absolute and ~-expanded.  Paths will be interpreted
2089926Sstan.czerniawski@arm.com# relative to the launch directory unless a different root is provided
2099926Sstan.czerniawski@arm.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
2109119Sandreas.hansson@arm.com    return [abspath(joinpath(root, expanduser(str(p))))
21110068Sandreas.hansson@arm.com            for p in path_list]
21210068Sandreas.hansson@arm.com
213955SN/A# Each target must have 'build' in the interior of the path; the
2149416SAndreas.Sandberg@ARM.com# directory below this will determine the build parameters.  For
21511342Sandreas.hansson@arm.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
21611212Sjoseph.gross@amd.com# recognize that ALPHA_SE specifies the configuration because it
21711212Sjoseph.gross@amd.com# follow 'build' in the build path.
21811212Sjoseph.gross@amd.com
21911212Sjoseph.gross@amd.com# The funky assignment to "[:]" is needed to replace the list contents
22011212Sjoseph.gross@amd.com# in place rather than reassign the symbol to a new list, which
2219416SAndreas.Sandberg@ARM.com# doesn't work (obviously!).
2229416SAndreas.Sandberg@ARM.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
2235871Snate@binkert.org
22410584Sandreas.hansson@arm.com# Generate a list of the unique build roots and configs that the
2259416SAndreas.Sandberg@ARM.com# collected targets reference.
2269416SAndreas.Sandberg@ARM.comvariant_paths = []
2275871Snate@binkert.orgbuild_root = None
228955SN/Afor t in BUILD_TARGETS:
22910671Sandreas.hansson@arm.com    path_dirs = t.split('/')
23010671Sandreas.hansson@arm.com    try:
23110671Sandreas.hansson@arm.com        build_top = rfind(path_dirs, 'build', -2)
23210671Sandreas.hansson@arm.com    except:
2338881Smarc.orr@gmail.com        print "Error: no non-leaf 'build' dir found on target path", t
2346121Snate@binkert.org        Exit(1)
2356121Snate@binkert.org    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2361533SN/A    if not build_root:
2379239Sandreas.hansson@arm.com        build_root = this_build_root
2389239Sandreas.hansson@arm.com    else:
2399239Sandreas.hansson@arm.com        if this_build_root != build_root:
2409239Sandreas.hansson@arm.com            print "Error: build targets not under same build root\n"\
2419239Sandreas.hansson@arm.com                  "  %s\n  %s" % (build_root, this_build_root)
2429239Sandreas.hansson@arm.com            Exit(1)
2439239Sandreas.hansson@arm.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
2449239Sandreas.hansson@arm.com    if variant_path not in variant_paths:
2459239Sandreas.hansson@arm.com        variant_paths.append(variant_path)
2469239Sandreas.hansson@arm.com
2479239Sandreas.hansson@arm.com# Make sure build_root exists (might not if this is the first build there)
2489239Sandreas.hansson@arm.comif not isdir(build_root):
2496655Snate@binkert.org    mkdir(build_root)
2506655Snate@binkert.orgmain['BUILDROOT'] = build_root
2516655Snate@binkert.org
2526655Snate@binkert.orgExport('main')
2535871Snate@binkert.org
2545871Snate@binkert.orgmain.SConsignFile(joinpath(build_root, "sconsign"))
2555863Snate@binkert.org
2565871Snate@binkert.org# Default duplicate option is to use hard links, but this messes up
2578878Ssteve.reinhardt@amd.com# when you use emacs to edit a file in the target dir, as emacs moves
2585871Snate@binkert.org# file to file~ then copies to file, breaking the link.  Symbolic
2595871Snate@binkert.org# (soft) links work better.
2605871Snate@binkert.orgmain.SetOption('duplicate', 'soft-copy')
2615863Snate@binkert.org
2626121Snate@binkert.org#
2635863Snate@binkert.org# Set up global sticky variables... these are common to an entire build
26411408Sandreas.sandberg@arm.com# tree (not specific to a particular build like ALPHA_SE)
26511408Sandreas.sandberg@arm.com#
2668336Ssteve.reinhardt@amd.com
26711469SCurtis.Dunham@arm.comglobal_vars_file = joinpath(build_root, 'variables.global')
26811469SCurtis.Dunham@arm.com
2698336Ssteve.reinhardt@amd.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
2704678Snate@binkert.org
27111469SCurtis.Dunham@arm.comglobal_vars.AddVariables(
27211469SCurtis.Dunham@arm.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
27311469SCurtis.Dunham@arm.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
27411469SCurtis.Dunham@arm.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
27511408Sandreas.sandberg@arm.com    ('BATCH', 'Use batch pool for build and tests', False),
27611401Sandreas.sandberg@arm.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
27711401Sandreas.sandberg@arm.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
27811401Sandreas.sandberg@arm.com    ('EXTRAS', 'Add extra directories to the compilation', '')
27911401Sandreas.sandberg@arm.com    )
28011401Sandreas.sandberg@arm.com
28111401Sandreas.sandberg@arm.com# Update main environment with values from ARGUMENTS & global_vars_file
2828336Ssteve.reinhardt@amd.comglobal_vars.Update(main)
2838336Ssteve.reinhardt@amd.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
2848336Ssteve.reinhardt@amd.com
2854678Snate@binkert.org# Save sticky variable settings back to current variables file
28611401Sandreas.sandberg@arm.comglobal_vars.Save(global_vars_file, main)
2874678Snate@binkert.org
2884678Snate@binkert.org# Parse EXTRAS variable to build list of all directories where we're
28911401Sandreas.sandberg@arm.com# look for sources etc.  This list is exported as extras_dir_list.
29011401Sandreas.sandberg@arm.combase_dir = main.srcdir.abspath
2918336Ssteve.reinhardt@amd.comif main['EXTRAS']:
2924678Snate@binkert.org    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
2938336Ssteve.reinhardt@amd.comelse:
2948336Ssteve.reinhardt@amd.com    extras_dir_list = []
2958336Ssteve.reinhardt@amd.com
2968336Ssteve.reinhardt@amd.comExport('base_dir')
2978336Ssteve.reinhardt@amd.comExport('extras_dir_list')
2988336Ssteve.reinhardt@amd.com
2995871Snate@binkert.org# the ext directory should be on the #includes path
3005871Snate@binkert.orgmain.Append(CPPPATH=[Dir('ext')])
3018336Ssteve.reinhardt@amd.com
30211408Sandreas.sandberg@arm.com# Add shared top-level headers
30311408Sandreas.sandberg@arm.commain.Prepend(CPPPATH=Dir('include'))
30411408Sandreas.sandberg@arm.com
30511408Sandreas.sandberg@arm.comif GetOption('verbose'):
30611408Sandreas.sandberg@arm.com    def MakeAction(action, string, *args, **kwargs):
30711408Sandreas.sandberg@arm.com        return Action(action, *args, **kwargs)
30811408Sandreas.sandberg@arm.comelse:
3098336Ssteve.reinhardt@amd.com    MakeAction = Action
31011401Sandreas.sandberg@arm.com    main['CCCOMSTR']        = Transform("CC")
31111401Sandreas.sandberg@arm.com    main['CXXCOMSTR']       = Transform("CXX")
31211401Sandreas.sandberg@arm.com    main['ASCOMSTR']        = Transform("AS")
3135871Snate@binkert.org    main['ARCOMSTR']        = Transform("AR", 0)
3148336Ssteve.reinhardt@amd.com    main['LINKCOMSTR']      = Transform("LINK", 0)
3158336Ssteve.reinhardt@amd.com    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
31611401Sandreas.sandberg@arm.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
31711401Sandreas.sandberg@arm.com    main['M4COMSTR']        = Transform("M4")
31811401Sandreas.sandberg@arm.com    main['SHCCCOMSTR']      = Transform("SHCC")
31911401Sandreas.sandberg@arm.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
32011401Sandreas.sandberg@arm.comExport('MakeAction')
3214678Snate@binkert.org
3225871Snate@binkert.org# Initialize the Link-Time Optimization (LTO) flags
3234678Snate@binkert.orgmain['LTO_CCFLAGS'] = []
32411401Sandreas.sandberg@arm.commain['LTO_LDFLAGS'] = []
32511401Sandreas.sandberg@arm.com
32611401Sandreas.sandberg@arm.com# According to the readme, tcmalloc works best if the compiler doesn't
32711401Sandreas.sandberg@arm.com# assume that we're using the builtin malloc and friends. These flags
32811401Sandreas.sandberg@arm.com# are compiler-specific, so we need to set them after we detect which
32911401Sandreas.sandberg@arm.com# compiler we're using.
33011401Sandreas.sandberg@arm.commain['TCMALLOC_CCFLAGS'] = []
33111401Sandreas.sandberg@arm.com
33211401Sandreas.sandberg@arm.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
33311401Sandreas.sandberg@arm.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
33411401Sandreas.sandberg@arm.com
33511401Sandreas.sandberg@arm.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
33611450Sandreas.sandberg@arm.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
33711450Sandreas.sandberg@arm.comif main['GCC'] + main['CLANG'] > 1:
33811450Sandreas.sandberg@arm.com    print 'Error: How can we have two at the same time?'
33911450Sandreas.sandberg@arm.com    Exit(1)
34011450Sandreas.sandberg@arm.com
34111450Sandreas.sandberg@arm.com# Set up default C++ compiler flags
34211450Sandreas.sandberg@arm.comif main['GCC'] or main['CLANG']:
34311450Sandreas.sandberg@arm.com    # As gcc and clang share many flags, do the common parts here
34411450Sandreas.sandberg@arm.com    main.Append(CCFLAGS=['-pipe'])
34511450Sandreas.sandberg@arm.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
34611450Sandreas.sandberg@arm.com    # Enable -Wall and -Wextra and then disable the few warnings that
34711401Sandreas.sandberg@arm.com    # we consistently violate
34811450Sandreas.sandberg@arm.com    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
34911450Sandreas.sandberg@arm.com                         '-Wno-sign-compare', '-Wno-unused-parameter'])
35011450Sandreas.sandberg@arm.com    # We always compile using C++11
35111401Sandreas.sandberg@arm.com    main.Append(CXXFLAGS=['-std=c++11'])
35211450Sandreas.sandberg@arm.com    if sys.platform.startswith('freebsd'):
35311401Sandreas.sandberg@arm.com        main.Append(CCFLAGS=['-I/usr/local/include'])
3548336Ssteve.reinhardt@amd.com        main.Append(CXXFLAGS=['-I/usr/local/include'])
3558336Ssteve.reinhardt@amd.com
3568336Ssteve.reinhardt@amd.com    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
3578336Ssteve.reinhardt@amd.com    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
3588336Ssteve.reinhardt@amd.com    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
3598336Ssteve.reinhardt@amd.com    shared_partial_flags = ['-r', '-nostdlib']
3608336Ssteve.reinhardt@amd.com    main.Append(PSHLINKFLAGS=shared_partial_flags)
3618336Ssteve.reinhardt@amd.com    main.Append(PLINKFLAGS=shared_partial_flags)
3628336Ssteve.reinhardt@amd.comelse:
3638336Ssteve.reinhardt@amd.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
36411401Sandreas.sandberg@arm.com    print "Don't know what compiler options to use for your compiler."
36511401Sandreas.sandberg@arm.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
3668336Ssteve.reinhardt@amd.com    print termcap.Yellow + '       version:' + termcap.Normal,
3678336Ssteve.reinhardt@amd.com    if not CXX_version:
3688336Ssteve.reinhardt@amd.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
3695871Snate@binkert.org               termcap.Normal
37011476Sandreas.sandberg@arm.com    else:
37111476Sandreas.sandberg@arm.com        print CXX_version.replace('\n', '<nl>')
37211476Sandreas.sandberg@arm.com    print "       If you're trying to use a compiler other than GCC"
37311476Sandreas.sandberg@arm.com    print "       or clang, there appears to be something wrong with your"
37411476Sandreas.sandberg@arm.com    print "       environment."
37511476Sandreas.sandberg@arm.com    print "       "
37611476Sandreas.sandberg@arm.com    print "       If you are trying to use a compiler other than those listed"
37711476Sandreas.sandberg@arm.com    print "       above you will need to ease fix SConstruct and "
37811476Sandreas.sandberg@arm.com    print "       src/SConscript to support that compiler."
37911476Sandreas.sandberg@arm.com    Exit(1)
38011408Sandreas.sandberg@arm.com
38111408Sandreas.sandberg@arm.comif main['GCC']:
38211476Sandreas.sandberg@arm.com    # Check for a supported version of gcc. >= 4.8 is chosen for its
38311476Sandreas.sandberg@arm.com    # level of c++11 support. See
38411476Sandreas.sandberg@arm.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
38511408Sandreas.sandberg@arm.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
38611408Sandreas.sandberg@arm.com    if compareVersions(gcc_version, "4.8") < 0:
38711408Sandreas.sandberg@arm.com        print 'Error: gcc version 4.8 or newer required.'
38811408Sandreas.sandberg@arm.com        print '       Installed version:', gcc_version
38911408Sandreas.sandberg@arm.com        Exit(1)
39011408Sandreas.sandberg@arm.com
39111408Sandreas.sandberg@arm.com    main['GCC_VERSION'] = gcc_version
39211476Sandreas.sandberg@arm.com
39311476Sandreas.sandberg@arm.com    if compareVersions(gcc_version, '4.9') >= 0:
39411476Sandreas.sandberg@arm.com        # Incremental linking with LTO is currently broken in gcc versions
39511476Sandreas.sandberg@arm.com        # 4.9 and above. A version where everything works completely hasn't
39611476Sandreas.sandberg@arm.com        # yet been identified.
39711476Sandreas.sandberg@arm.com        #
39811408Sandreas.sandberg@arm.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
39911408Sandreas.sandberg@arm.com        main['BROKEN_INCREMENTAL_LTO'] = True
40011476Sandreas.sandberg@arm.com    if compareVersions(gcc_version, '6.0') >= 0:
40111476Sandreas.sandberg@arm.com        # gcc versions 6.0 and greater accept an -flinker-output flag which
40211476Sandreas.sandberg@arm.com        # selects what type of output the linker should generate. This is
40311476Sandreas.sandberg@arm.com        # necessary for incremental lto to work, but is also broken in
40411476Sandreas.sandberg@arm.com        # current versions of gcc. It may not be necessary in future
40511408Sandreas.sandberg@arm.com        # versions. We add it here since it might be, and as a reminder that
40611408Sandreas.sandberg@arm.com        # it exists. It's excluded if lto is being forced.
40711408Sandreas.sandberg@arm.com        #
40811476Sandreas.sandberg@arm.com        # https://gcc.gnu.org/gcc-6/changes.html
40911476Sandreas.sandberg@arm.com        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
41011476Sandreas.sandberg@arm.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
41111476Sandreas.sandberg@arm.com        if not GetOption('force_lto'):
4126121Snate@binkert.org            main.Append(PSHLINKFLAGS='-flinker-output=rel')
413955SN/A            main.Append(PLINKFLAGS='-flinker-output=rel')
414955SN/A
4152632Sstever@eecs.umich.edu    # gcc from version 4.8 and above generates "rep; ret" instructions
4162632Sstever@eecs.umich.edu    # to avoid performance penalties on certain AMD chips. Older
417955SN/A    # assemblers detect this as an error, "Error: expecting string
418955SN/A    # instruction after `rep'"
419955SN/A    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
420955SN/A                                  '-o', '/dev/null'],
4218878Ssteve.reinhardt@amd.com                                 exception=False).split()
422955SN/A
4232632Sstever@eecs.umich.edu    # version strings may contain extra distro-specific
4242632Sstever@eecs.umich.edu    # qualifiers, so play it safe and keep only what comes before
4252632Sstever@eecs.umich.edu    # the first hyphen
4262632Sstever@eecs.umich.edu    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
4272632Sstever@eecs.umich.edu
4282632Sstever@eecs.umich.edu    if not as_version or compareVersions(as_version, "2.23") < 0:
4292632Sstever@eecs.umich.edu        print termcap.Yellow + termcap.Bold + \
4308268Ssteve.reinhardt@amd.com            'Warning: This combination of gcc and binutils have' + \
4318268Ssteve.reinhardt@amd.com            ' known incompatibilities.\n' + \
4328268Ssteve.reinhardt@amd.com            '         If you encounter build problems, please update ' + \
4338268Ssteve.reinhardt@amd.com            'binutils to 2.23.' + \
4348268Ssteve.reinhardt@amd.com            termcap.Normal
4358268Ssteve.reinhardt@amd.com
4368268Ssteve.reinhardt@amd.com    # Make sure we warn if the user has requested to compile with the
4372632Sstever@eecs.umich.edu    # Undefined Benahvior Sanitizer and this version of gcc does not
4382632Sstever@eecs.umich.edu    # support it.
4392632Sstever@eecs.umich.edu    if GetOption('with_ubsan') and \
4402632Sstever@eecs.umich.edu            compareVersions(gcc_version, '4.9') < 0:
4418268Ssteve.reinhardt@amd.com        print termcap.Yellow + termcap.Bold + \
4422632Sstever@eecs.umich.edu            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
4438268Ssteve.reinhardt@amd.com            termcap.Normal
4448268Ssteve.reinhardt@amd.com
4458268Ssteve.reinhardt@amd.com    disable_lto = GetOption('no_lto')
4468268Ssteve.reinhardt@amd.com    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
4473718Sstever@eecs.umich.edu            not GetOption('force_lto'):
4482634Sstever@eecs.umich.edu        print termcap.Yellow + termcap.Bold + \
4492634Sstever@eecs.umich.edu            'Warning: Your compiler doesn\'t support incremental linking' + \
4505863Snate@binkert.org            ' and lto at the same time, so lto is being disabled. To force' + \
4512638Sstever@eecs.umich.edu            ' lto on anyway, use the --force-lto option. That will disable' + \
4528268Ssteve.reinhardt@amd.com            ' partial linking.' + \
4532632Sstever@eecs.umich.edu            termcap.Normal
4542632Sstever@eecs.umich.edu        disable_lto = True
4552632Sstever@eecs.umich.edu
4562632Sstever@eecs.umich.edu    # Add the appropriate Link-Time Optimization (LTO) flags
4572632Sstever@eecs.umich.edu    # unless LTO is explicitly turned off. Note that these flags
4581858SN/A    # are only used by the fast target.
4593716Sstever@eecs.umich.edu    if not disable_lto:
4602638Sstever@eecs.umich.edu        # Pass the LTO flag when compiling to produce GIMPLE
4612638Sstever@eecs.umich.edu        # output, we merely create the flags here and only append
4622638Sstever@eecs.umich.edu        # them later
4632638Sstever@eecs.umich.edu        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4642638Sstever@eecs.umich.edu
4652638Sstever@eecs.umich.edu        # Use the same amount of jobs for LTO as we are running
4662638Sstever@eecs.umich.edu        # scons with
4675863Snate@binkert.org        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4685863Snate@binkert.org
4695863Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
470955SN/A                                  '-fno-builtin-realloc', '-fno-builtin-free'])
4715341Sstever@gmail.com
4725341Sstever@gmail.com    # add option to check for undeclared overrides
4735863Snate@binkert.org    if compareVersions(gcc_version, "5.0") > 0:
4747756SAli.Saidi@ARM.com        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
4755341Sstever@gmail.com
4766121Snate@binkert.org    # The address sanitizer is available for gcc >= 4.8
4774494Ssaidi@eecs.umich.edu    if GetOption('with_asan'):
4786121Snate@binkert.org        if GetOption('with_ubsan') and \
4791105SN/A                compareVersions(env['GCC_VERSION'], '4.9') >= 0:
4802667Sstever@eecs.umich.edu            env.Append(CCFLAGS=['-fsanitize=address,undefined',
4812667Sstever@eecs.umich.edu                                '-fno-omit-frame-pointer'],
4822667Sstever@eecs.umich.edu                       LINKFLAGS='-fsanitize=address,undefined')
4832667Sstever@eecs.umich.edu        else:
4846121Snate@binkert.org            env.Append(CCFLAGS=['-fsanitize=address',
4852667Sstever@eecs.umich.edu                                '-fno-omit-frame-pointer'],
4865341Sstever@gmail.com                       LINKFLAGS='-fsanitize=address')
4875863Snate@binkert.org    # Only gcc >= 4.9 supports UBSan, so check both the version
4885341Sstever@gmail.com    # and the command-line option before adding the compiler and
4895341Sstever@gmail.com    # linker flags.
4905341Sstever@gmail.com    elif GetOption('with_ubsan') and \
4918120Sgblack@eecs.umich.edu            compareVersions(env['GCC_VERSION'], '4.9') >= 0:
4925341Sstever@gmail.com        env.Append(CCFLAGS='-fsanitize=undefined')
4938120Sgblack@eecs.umich.edu        env.Append(LINKFLAGS='-fsanitize=undefined')
4945341Sstever@gmail.com
4958120Sgblack@eecs.umich.eduelif main['CLANG']:
4966121Snate@binkert.org    # Check for a supported version of clang, >= 3.1 is needed to
4976121Snate@binkert.org    # support similar features as gcc 4.8. See
4988980Ssteve.reinhardt@amd.com    # http://clang.llvm.org/cxx_status.html for details
4999396Sandreas.hansson@arm.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
5005397Ssaidi@eecs.umich.edu    clang_version_match = clang_version_re.search(CXX_version)
5015397Ssaidi@eecs.umich.edu    if (clang_version_match):
5027727SAli.Saidi@ARM.com        clang_version = clang_version_match.groups()[0]
5038268Ssteve.reinhardt@amd.com        if compareVersions(clang_version, "3.1") < 0:
5046168Snate@binkert.org            print 'Error: clang version 3.1 or newer required.'
5055341Sstever@gmail.com            print '       Installed version:', clang_version
5068120Sgblack@eecs.umich.edu            Exit(1)
5078120Sgblack@eecs.umich.edu    else:
5088120Sgblack@eecs.umich.edu        print 'Error: Unable to determine clang version.'
5096814Sgblack@eecs.umich.edu        Exit(1)
5105863Snate@binkert.org
5118120Sgblack@eecs.umich.edu    # clang has a few additional warnings that we disable, extraneous
5125341Sstever@gmail.com    # parantheses are allowed due to Ruby's printing of the AST,
5135863Snate@binkert.org    # finally self assignments are allowed as the generated CPU code
5148268Ssteve.reinhardt@amd.com    # is relying on this
5156121Snate@binkert.org    main.Append(CCFLAGS=['-Wno-parentheses',
5166121Snate@binkert.org                         '-Wno-self-assign',
5178268Ssteve.reinhardt@amd.com                         # Some versions of libstdc++ (4.8?) seem to
5185742Snate@binkert.org                         # use struct hash and class hash
5195742Snate@binkert.org                         # interchangeably.
5205341Sstever@gmail.com                         '-Wno-mismatched-tags',
5215742Snate@binkert.org                         ])
5225742Snate@binkert.org
5235341Sstever@gmail.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
5246017Snate@binkert.org
5256121Snate@binkert.org    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
5266017Snate@binkert.org    # opposed to libstdc++, as the later is dated.
5277816Ssteve.reinhardt@amd.com    if sys.platform == "darwin":
5287756SAli.Saidi@ARM.com        main.Append(CXXFLAGS=['-stdlib=libc++'])
5297756SAli.Saidi@ARM.com        main.Append(LIBS=['c++'])
5307756SAli.Saidi@ARM.com
5317756SAli.Saidi@ARM.com    # On FreeBSD we need libthr.
5327756SAli.Saidi@ARM.com    if sys.platform.startswith('freebsd'):
5337756SAli.Saidi@ARM.com        main.Append(LIBS=['thr'])
5347756SAli.Saidi@ARM.com
5357756SAli.Saidi@ARM.com    # We require clang >= 3.1, so there is no need to check any
5367816Ssteve.reinhardt@amd.com    # versions here.
5377816Ssteve.reinhardt@amd.com    if GetOption('with_ubsan'):
5387816Ssteve.reinhardt@amd.com        if GetOption('with_asan'):
5397816Ssteve.reinhardt@amd.com            env.Append(CCFLAGS=['-fsanitize=address,undefined',
5407816Ssteve.reinhardt@amd.com                                '-fno-omit-frame-pointer'],
5417816Ssteve.reinhardt@amd.com                       LINKFLAGS='-fsanitize=address,undefined')
5427816Ssteve.reinhardt@amd.com        else:
5437816Ssteve.reinhardt@amd.com            env.Append(CCFLAGS='-fsanitize=undefined',
5447816Ssteve.reinhardt@amd.com                       LINKFLAGS='-fsanitize=undefined')
5457816Ssteve.reinhardt@amd.com
5467756SAli.Saidi@ARM.com    elif GetOption('with_asan'):
5477816Ssteve.reinhardt@amd.com        env.Append(CCFLAGS=['-fsanitize=address',
5487816Ssteve.reinhardt@amd.com                            '-fno-omit-frame-pointer'],
5497816Ssteve.reinhardt@amd.com                   LINKFLAGS='-fsanitize=address')
5507816Ssteve.reinhardt@amd.com
5517816Ssteve.reinhardt@amd.comelse:
5527816Ssteve.reinhardt@amd.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5537816Ssteve.reinhardt@amd.com    print "Don't know what compiler options to use for your compiler."
5547816Ssteve.reinhardt@amd.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5557816Ssteve.reinhardt@amd.com    print termcap.Yellow + '       version:' + termcap.Normal,
5567816Ssteve.reinhardt@amd.com    if not CXX_version:
5577816Ssteve.reinhardt@amd.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5587816Ssteve.reinhardt@amd.com               termcap.Normal
5597816Ssteve.reinhardt@amd.com    else:
5607816Ssteve.reinhardt@amd.com        print CXX_version.replace('\n', '<nl>')
5617816Ssteve.reinhardt@amd.com    print "       If you're trying to use a compiler other than GCC"
5627816Ssteve.reinhardt@amd.com    print "       or clang, there appears to be something wrong with your"
5637816Ssteve.reinhardt@amd.com    print "       environment."
5647816Ssteve.reinhardt@amd.com    print "       "
5657816Ssteve.reinhardt@amd.com    print "       If you are trying to use a compiler other than those listed"
5667816Ssteve.reinhardt@amd.com    print "       above you will need to ease fix SConstruct and "
5677816Ssteve.reinhardt@amd.com    print "       src/SConscript to support that compiler."
5687816Ssteve.reinhardt@amd.com    Exit(1)
5697816Ssteve.reinhardt@amd.com
5707816Ssteve.reinhardt@amd.com# Set up common yacc/bison flags (needed for Ruby)
5717816Ssteve.reinhardt@amd.commain['YACCFLAGS'] = '-d'
5727816Ssteve.reinhardt@amd.commain['YACCHXXFILESUFFIX'] = '.hh'
5737816Ssteve.reinhardt@amd.com
5747816Ssteve.reinhardt@amd.com# Do this after we save setting back, or else we'll tack on an
5757816Ssteve.reinhardt@amd.com# extra 'qdo' every time we run scons.
5767816Ssteve.reinhardt@amd.comif main['BATCH']:
5777816Ssteve.reinhardt@amd.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
5787816Ssteve.reinhardt@amd.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
5797816Ssteve.reinhardt@amd.com    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
5807816Ssteve.reinhardt@amd.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
5817816Ssteve.reinhardt@amd.com    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
5827816Ssteve.reinhardt@amd.com
5837816Ssteve.reinhardt@amd.comif sys.platform == 'cygwin':
5847816Ssteve.reinhardt@amd.com    # cygwin has some header file issues...
5857816Ssteve.reinhardt@amd.com    main.Append(CCFLAGS=["-Wno-uninitialized"])
5867816Ssteve.reinhardt@amd.com
5877816Ssteve.reinhardt@amd.com# Check for the protobuf compiler
5887816Ssteve.reinhardt@amd.comprotoc_version = readCommand([main['PROTOC'], '--version'],
5897816Ssteve.reinhardt@amd.com                             exception='').split()
5907816Ssteve.reinhardt@amd.com
5917816Ssteve.reinhardt@amd.com# First two words should be "libprotoc x.y.z"
5927816Ssteve.reinhardt@amd.comif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
5937816Ssteve.reinhardt@amd.com    print termcap.Yellow + termcap.Bold + \
5947816Ssteve.reinhardt@amd.com        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
5957816Ssteve.reinhardt@amd.com        '         Please install protobuf-compiler for tracing support.' + \
5967816Ssteve.reinhardt@amd.com        termcap.Normal
5977816Ssteve.reinhardt@amd.com    main['PROTOC'] = False
5987816Ssteve.reinhardt@amd.comelse:
5997816Ssteve.reinhardt@amd.com    # Based on the availability of the compress stream wrappers,
6007816Ssteve.reinhardt@amd.com    # require 2.1.0
6017816Ssteve.reinhardt@amd.com    min_protoc_version = '2.1.0'
6027816Ssteve.reinhardt@amd.com    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6037816Ssteve.reinhardt@amd.com        print termcap.Yellow + termcap.Bold + \
6047816Ssteve.reinhardt@amd.com            'Warning: protoc version', min_protoc_version, \
6057816Ssteve.reinhardt@amd.com            'or newer required.\n' + \
6067816Ssteve.reinhardt@amd.com            '         Installed version:', protoc_version[1], \
6077816Ssteve.reinhardt@amd.com            termcap.Normal
6088947Sandreas.hansson@arm.com        main['PROTOC'] = False
6098947Sandreas.hansson@arm.com    else:
6107756SAli.Saidi@ARM.com        # Attempt to determine the appropriate include path and
6118120Sgblack@eecs.umich.edu        # library path using pkg-config, that means we also need to
6127756SAli.Saidi@ARM.com        # check for pkg-config. Note that it is possible to use
6137756SAli.Saidi@ARM.com        # protobuf without the involvement of pkg-config. Later on we
6147756SAli.Saidi@ARM.com        # check go a library config check and at that point the test
6157756SAli.Saidi@ARM.com        # will fail if libprotobuf cannot be found.
6167816Ssteve.reinhardt@amd.com        if readCommand(['pkg-config', '--version'], exception=''):
6177816Ssteve.reinhardt@amd.com            try:
6187816Ssteve.reinhardt@amd.com                # Attempt to establish what linking flags to add for protobuf
6197816Ssteve.reinhardt@amd.com                # using pkg-config
6207816Ssteve.reinhardt@amd.com                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
6217816Ssteve.reinhardt@amd.com            except:
6227816Ssteve.reinhardt@amd.com                print termcap.Yellow + termcap.Bold + \
6237816Ssteve.reinhardt@amd.com                    'Warning: pkg-config could not get protobuf flags.' + \
6247816Ssteve.reinhardt@amd.com                    termcap.Normal
6257816Ssteve.reinhardt@amd.com
6267756SAli.Saidi@ARM.com
6277756SAli.Saidi@ARM.com# Check for 'timeout' from GNU coreutils. If present, regressions will
6289227Sandreas.hansson@arm.com# be run with a time limit. We require version 8.13 since we rely on
6299227Sandreas.hansson@arm.com# support for the '--foreground' option.
6309227Sandreas.hansson@arm.comif sys.platform.startswith('freebsd'):
6319227Sandreas.hansson@arm.com    timeout_lines = readCommand(['gtimeout', '--version'],
6329590Sandreas@sandberg.pp.se                                exception='').splitlines()
6339590Sandreas@sandberg.pp.seelse:
6349590Sandreas@sandberg.pp.se    timeout_lines = readCommand(['timeout', '--version'],
6359590Sandreas@sandberg.pp.se                                exception='').splitlines()
6369590Sandreas@sandberg.pp.se# Get the first line and tokenize it
6379590Sandreas@sandberg.pp.setimeout_version = timeout_lines[0].split() if timeout_lines else []
6386654Snate@binkert.orgmain['TIMEOUT'] =  timeout_version and \
6396654Snate@binkert.org    compareVersions(timeout_version[-1], '8.13') >= 0
6405871Snate@binkert.org
6416121Snate@binkert.org# Add a custom Check function to test for structure members.
6428946Sandreas.hansson@arm.comdef CheckMember(context, include, decl, member, include_quotes="<>"):
6439419Sandreas.hansson@arm.com    context.Message("Checking for member %s in %s..." %
6443940Ssaidi@eecs.umich.edu                    (member, decl))
6453918Ssaidi@eecs.umich.edu    text = """
6463918Ssaidi@eecs.umich.edu#include %(header)s
6471858SN/Aint main(){
6489556Sandreas.hansson@arm.com  %(decl)s test;
6499556Sandreas.hansson@arm.com  (void)test.%(member)s;
6509556Sandreas.hansson@arm.com  return 0;
6519556Sandreas.hansson@arm.com};
65211294Sandreas.hansson@arm.com""" % { "header" : include_quotes[0] + include + include_quotes[1],
65311294Sandreas.hansson@arm.com        "decl" : decl,
65411294Sandreas.hansson@arm.com        "member" : member,
65511294Sandreas.hansson@arm.com        }
65610878Sandreas.hansson@arm.com
65710878Sandreas.hansson@arm.com    ret = context.TryCompile(text, extension=".cc")
65811811Sbaz21@cam.ac.uk    context.Result(ret)
65911811Sbaz21@cam.ac.uk    return ret
66011811Sbaz21@cam.ac.uk
6619556Sandreas.hansson@arm.com# Platform-specific configuration.  Note again that we assume that all
6629556Sandreas.hansson@arm.com# builds under a given build root run on the same host platform.
6639556Sandreas.hansson@arm.comconf = Configure(main,
6649556Sandreas.hansson@arm.com                 conf_dir = joinpath(build_root, '.scons_config'),
6659556Sandreas.hansson@arm.com                 log_file = joinpath(build_root, 'scons_config.log'),
6669556Sandreas.hansson@arm.com                 custom_tests = {
6679556Sandreas.hansson@arm.com        'CheckMember' : CheckMember,
6689556Sandreas.hansson@arm.com        })
6699556Sandreas.hansson@arm.com
6709556Sandreas.hansson@arm.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
6719556Sandreas.hansson@arm.comtry:
6729556Sandreas.hansson@arm.com    import platform
6739556Sandreas.hansson@arm.com    uname = platform.uname()
6749556Sandreas.hansson@arm.com    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
6759556Sandreas.hansson@arm.com        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
6769556Sandreas.hansson@arm.com            main.Append(CCFLAGS=['-arch', 'x86_64'])
6779556Sandreas.hansson@arm.com            main.Append(CFLAGS=['-arch', 'x86_64'])
6789556Sandreas.hansson@arm.com            main.Append(LINKFLAGS=['-arch', 'x86_64'])
6799556Sandreas.hansson@arm.com            main.Append(ASFLAGS=['-arch', 'x86_64'])
6806121Snate@binkert.orgexcept:
68111500Sandreas.hansson@arm.com    pass
68210238Sandreas.hansson@arm.com
68310878Sandreas.hansson@arm.com# Recent versions of scons substitute a "Null" object for Configure()
6849420Sandreas.hansson@arm.com# when configuration isn't necessary, e.g., if the "--help" option is
68511500Sandreas.hansson@arm.com# present.  Unfortuantely this Null object always returns false,
68611500Sandreas.hansson@arm.com# breaking all our configuration checks.  We replace it with our own
6879420Sandreas.hansson@arm.com# more optimistic null object that returns True instead.
6889420Sandreas.hansson@arm.comif not conf:
6899420Sandreas.hansson@arm.com    def NullCheck(*args, **kwargs):
6909420Sandreas.hansson@arm.com        return True
6919420Sandreas.hansson@arm.com
69210264Sandreas.hansson@arm.com    class NullConf:
69310264Sandreas.hansson@arm.com        def __init__(self, env):
69410264Sandreas.hansson@arm.com            self.env = env
69510264Sandreas.hansson@arm.com        def Finish(self):
69611500Sandreas.hansson@arm.com            return self.env
69711500Sandreas.hansson@arm.com        def __getattr__(self, mname):
69810264Sandreas.hansson@arm.com            return NullCheck
69911500Sandreas.hansson@arm.com
70011500Sandreas.hansson@arm.com    conf = NullConf(main)
70111500Sandreas.hansson@arm.com
70211500Sandreas.hansson@arm.com# Cache build files in the supplied directory.
70310866Sandreas.hansson@arm.comif main['M5_BUILD_CACHE']:
70411500Sandreas.hansson@arm.com    print 'Using build cache located at', main['M5_BUILD_CACHE']
70511500Sandreas.hansson@arm.com    CacheDir(main['M5_BUILD_CACHE'])
70611500Sandreas.hansson@arm.com
70711500Sandreas.hansson@arm.commain['USE_PYTHON'] = not GetOption('without_python')
70811500Sandreas.hansson@arm.comif main['USE_PYTHON']:
70911500Sandreas.hansson@arm.com    # Find Python include and library directories for embedding the
71011500Sandreas.hansson@arm.com    # interpreter. We rely on python-config to resolve the appropriate
71110264Sandreas.hansson@arm.com    # includes and linker flags. ParseConfig does not seem to understand
71210457Sandreas.hansson@arm.com    # the more exotic linker flags such as -Xlinker and -export-dynamic so
71310457Sandreas.hansson@arm.com    # we add them explicitly below. If you want to link in an alternate
71410457Sandreas.hansson@arm.com    # version of python, see above for instructions on how to invoke
71510457Sandreas.hansson@arm.com    # scons with the appropriate PATH set.
71610457Sandreas.hansson@arm.com    #
71710457Sandreas.hansson@arm.com    # First we check if python2-config exists, else we use python-config
71810457Sandreas.hansson@arm.com    python_config = readCommand(['which', 'python2-config'],
71910457Sandreas.hansson@arm.com                                exception='').strip()
72010457Sandreas.hansson@arm.com    if not os.path.exists(python_config):
72110238Sandreas.hansson@arm.com        python_config = readCommand(['which', 'python-config'],
72210238Sandreas.hansson@arm.com                                    exception='').strip()
72310238Sandreas.hansson@arm.com    py_includes = readCommand([python_config, '--includes'],
72410238Sandreas.hansson@arm.com                              exception='').split()
72510238Sandreas.hansson@arm.com    # Strip the -I from the include folders before adding them to the
72610238Sandreas.hansson@arm.com    # CPPPATH
72710416Sandreas.hansson@arm.com    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
72810238Sandreas.hansson@arm.com
7299227Sandreas.hansson@arm.com    # Read the linker flags and split them into libraries and other link
73010238Sandreas.hansson@arm.com    # flags. The libraries are added later through the call the CheckLib.
73110416Sandreas.hansson@arm.com    py_ld_flags = readCommand([python_config, '--ldflags'],
73210416Sandreas.hansson@arm.com        exception='').split()
7339227Sandreas.hansson@arm.com    py_libs = []
7349590Sandreas@sandberg.pp.se    for lib in py_ld_flags:
7359590Sandreas@sandberg.pp.se         if not lib.startswith('-l'):
7369590Sandreas@sandberg.pp.se             main.Append(LINKFLAGS=[lib])
73711497SMatteo.Andreozzi@arm.com         else:
73811497SMatteo.Andreozzi@arm.com             lib = lib[2:]
73911497SMatteo.Andreozzi@arm.com             if lib not in py_libs:
74011497SMatteo.Andreozzi@arm.com                 py_libs.append(lib)
7418737Skoansin.tan@gmail.com
74210878Sandreas.hansson@arm.com    # verify that this stuff works
74311500Sandreas.hansson@arm.com    if not conf.CheckHeader('Python.h', '<>'):
7449420Sandreas.hansson@arm.com        print "Error: can't find Python.h header in", py_includes
7458737Skoansin.tan@gmail.com        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
74610106SMitch.Hayenga@arm.com        Exit(1)
7478737Skoansin.tan@gmail.com
7488737Skoansin.tan@gmail.com    for lib in py_libs:
74910878Sandreas.hansson@arm.com        if not conf.CheckLib(lib):
75010878Sandreas.hansson@arm.com            print "Error: can't find library %s required by python" % lib
7518737Skoansin.tan@gmail.com            Exit(1)
7528737Skoansin.tan@gmail.com
7538737Skoansin.tan@gmail.com# On Solaris you need to use libsocket for socket ops
7548737Skoansin.tan@gmail.comif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7558737Skoansin.tan@gmail.com   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7568737Skoansin.tan@gmail.com       print "Can't find library with socket calls (e.g. accept())"
75711294Sandreas.hansson@arm.com       Exit(1)
7589556Sandreas.hansson@arm.com
7599556Sandreas.hansson@arm.com# Check for zlib.  If the check passes, libz will be automatically
7609556Sandreas.hansson@arm.com# added to the LIBS environment variable.
76111294Sandreas.hansson@arm.comif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
76210278SAndreas.Sandberg@ARM.com    print 'Error: did not find needed zlib compression library '\
76310278SAndreas.Sandberg@ARM.com          'and/or zlib.h header file.'
76410278SAndreas.Sandberg@ARM.com    print '       Please install zlib and try again.'
76510278SAndreas.Sandberg@ARM.com    Exit(1)
76610278SAndreas.Sandberg@ARM.com
76710278SAndreas.Sandberg@ARM.com# If we have the protobuf compiler, also make sure we have the
7689556Sandreas.hansson@arm.com# development libraries. If the check passes, libprotobuf will be
7699590Sandreas@sandberg.pp.se# automatically added to the LIBS environment variable. After
7709590Sandreas@sandberg.pp.se# this, we can use the HAVE_PROTOBUF flag to determine if we have
7719420Sandreas.hansson@arm.com# got both protoc and libprotobuf available.
7729846Sandreas.hansson@arm.commain['HAVE_PROTOBUF'] = main['PROTOC'] and \
7739846Sandreas.hansson@arm.com    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
7749846Sandreas.hansson@arm.com                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
7759846Sandreas.hansson@arm.com
7768946Sandreas.hansson@arm.com# If we have the compiler but not the library, print another warning.
77711811Sbaz21@cam.ac.ukif main['PROTOC'] and not main['HAVE_PROTOBUF']:
77811811Sbaz21@cam.ac.uk    print termcap.Yellow + termcap.Bold + \
77911811Sbaz21@cam.ac.uk        'Warning: did not find protocol buffer library and/or headers.\n' + \
78011811Sbaz21@cam.ac.uk    '       Please install libprotobuf-dev for tracing support.' + \
7813918Ssaidi@eecs.umich.edu    termcap.Normal
7829068SAli.Saidi@ARM.com
7839068SAli.Saidi@ARM.com# Check for librt.
7849068SAli.Saidi@ARM.comhave_posix_clock = \
7859068SAli.Saidi@ARM.com    conf.CheckLibWithHeader(None, 'time.h', 'C',
7869068SAli.Saidi@ARM.com                            'clock_nanosleep(0,0,NULL,NULL);') or \
7879068SAli.Saidi@ARM.com    conf.CheckLibWithHeader('rt', 'time.h', 'C',
7889068SAli.Saidi@ARM.com                            'clock_nanosleep(0,0,NULL,NULL);')
7899068SAli.Saidi@ARM.com
7909068SAli.Saidi@ARM.comhave_posix_timers = \
7919419Sandreas.hansson@arm.com    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
7929068SAli.Saidi@ARM.com                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
7939068SAli.Saidi@ARM.com
7949068SAli.Saidi@ARM.comif not GetOption('without_tcmalloc'):
7959068SAli.Saidi@ARM.com    if conf.CheckLib('tcmalloc'):
7969068SAli.Saidi@ARM.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
7979068SAli.Saidi@ARM.com    elif conf.CheckLib('tcmalloc_minimal'):
7983918Ssaidi@eecs.umich.edu        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
7993918Ssaidi@eecs.umich.edu    else:
8006157Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
8016157Snate@binkert.org              "You can get a 12% performance improvement by "\
8026157Snate@binkert.org              "installing tcmalloc (libgoogle-perftools-dev package "\
8036157Snate@binkert.org              "on Ubuntu or RedHat)." + termcap.Normal
8045397Ssaidi@eecs.umich.edu
8055397Ssaidi@eecs.umich.edu
8066121Snate@binkert.org# Detect back trace implementations. The last implementation in the
8076121Snate@binkert.org# list will be used by default.
8086121Snate@binkert.orgbacktrace_impls = [ "none" ]
8096121Snate@binkert.org
8106121Snate@binkert.orgif conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
8116121Snate@binkert.org                           'backtrace_symbols_fd((void*)0, 0, 0);'):
8125397Ssaidi@eecs.umich.edu    backtrace_impls.append("glibc")
8131851SN/Aelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
8141851SN/A                           'backtrace_symbols_fd((void*)0, 0, 0);'):
8157739Sgblack@eecs.umich.edu    # NetBSD and FreeBSD need libexecinfo.
816955SN/A    backtrace_impls.append("glibc")
8179396Sandreas.hansson@arm.com    main.Append(LIBS=['execinfo'])
8189396Sandreas.hansson@arm.com
8199396Sandreas.hansson@arm.comif backtrace_impls[-1] == "none":
8209396Sandreas.hansson@arm.com    default_backtrace_impl = "none"
8219396Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + \
8229396Sandreas.hansson@arm.com        "No suitable back trace implementation found." + \
8239396Sandreas.hansson@arm.com        termcap.Normal
8249396Sandreas.hansson@arm.com
8259396Sandreas.hansson@arm.comif not have_posix_clock:
8269396Sandreas.hansson@arm.com    print "Can't find library for POSIX clocks."
8279396Sandreas.hansson@arm.com
8289396Sandreas.hansson@arm.com# Check for <fenv.h> (C99 FP environment control)
8299396Sandreas.hansson@arm.comhave_fenv = conf.CheckHeader('fenv.h', '<>')
8309396Sandreas.hansson@arm.comif not have_fenv:
8319396Sandreas.hansson@arm.com    print "Warning: Header file <fenv.h> not found."
8329396Sandreas.hansson@arm.com    print "         This host has no IEEE FP rounding mode control."
8339477Sandreas.hansson@arm.com
8349477Sandreas.hansson@arm.com# Check for <png.h> (libpng library needed if wanting to dump
8359477Sandreas.hansson@arm.com# frame buffer image in png format)
8369477Sandreas.hansson@arm.comhave_png = conf.CheckHeader('png.h', '<>')
8379477Sandreas.hansson@arm.comif not have_png:
8389477Sandreas.hansson@arm.com    print "Warning: Header file <png.h> not found."
8399477Sandreas.hansson@arm.com    print "         This host has no libpng library."
8409477Sandreas.hansson@arm.com    print "         Disabling support for PNG framebuffers."
8419477Sandreas.hansson@arm.com
8429477Sandreas.hansson@arm.com# Check if we should enable KVM-based hardware virtualization. The API
8439477Sandreas.hansson@arm.com# we rely on exists since version 2.6.36 of the kernel, but somehow
8449477Sandreas.hansson@arm.com# the KVM_API_VERSION does not reflect the change. We test for one of
8459477Sandreas.hansson@arm.com# the types as a fall back.
8469477Sandreas.hansson@arm.comhave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
8479477Sandreas.hansson@arm.comif not have_kvm:
8489477Sandreas.hansson@arm.com    print "Info: Compatible header file <linux/kvm.h> not found, " \
8499477Sandreas.hansson@arm.com        "disabling KVM support."
8509477Sandreas.hansson@arm.com
8519477Sandreas.hansson@arm.com# Check if the TUN/TAP driver is available.
8529477Sandreas.hansson@arm.comhave_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
8539477Sandreas.hansson@arm.comif not have_tuntap:
8549477Sandreas.hansson@arm.com    print "Info: Compatible header file <linux/if_tun.h> not found."
8559396Sandreas.hansson@arm.com
8563053Sstever@eecs.umich.edu# x86 needs support for xsave. We test for the structure here since we
8576121Snate@binkert.org# won't be able to run new tests by the time we know which ISA we're
8583053Sstever@eecs.umich.edu# targeting.
8593053Sstever@eecs.umich.eduhave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
8603053Sstever@eecs.umich.edu                                    '#include <linux/kvm.h>') != 0
8613053Sstever@eecs.umich.edu
8623053Sstever@eecs.umich.edu# Check if the requested target ISA is compatible with the host
8639072Sandreas.hansson@arm.comdef is_isa_kvm_compatible(isa):
8643053Sstever@eecs.umich.edu    try:
8654742Sstever@eecs.umich.edu        import platform
8664742Sstever@eecs.umich.edu        host_isa = platform.machine()
8673053Sstever@eecs.umich.edu    except:
8683053Sstever@eecs.umich.edu        print "Warning: Failed to determine host ISA."
8693053Sstever@eecs.umich.edu        return False
87010181SCurtis.Dunham@arm.com
8716654Snate@binkert.org    if not have_posix_timers:
8723053Sstever@eecs.umich.edu        print "Warning: Can not enable KVM, host seems to lack support " \
8733053Sstever@eecs.umich.edu            "for POSIX timers"
8743053Sstever@eecs.umich.edu        return False
8753053Sstever@eecs.umich.edu
87610425Sandreas.hansson@arm.com    if isa == "arm":
87710425Sandreas.hansson@arm.com        return host_isa in ( "armv7l", "aarch64" )
87810425Sandreas.hansson@arm.com    elif isa == "x86":
87910425Sandreas.hansson@arm.com        if host_isa != "x86_64":
88010425Sandreas.hansson@arm.com            return False
88110425Sandreas.hansson@arm.com
88210425Sandreas.hansson@arm.com        if not have_kvm_xsave:
88310425Sandreas.hansson@arm.com            print "KVM on x86 requires xsave support in kernel headers."
88410425Sandreas.hansson@arm.com            return False
88510425Sandreas.hansson@arm.com
88610425Sandreas.hansson@arm.com        return True
8872667Sstever@eecs.umich.edu    else:
8884554Sbinkertn@umich.edu        return False
8896121Snate@binkert.org
8902667Sstever@eecs.umich.edu
89110710Sandreas.hansson@arm.com# Check if the exclude_host attribute is available. We want this to
89210710Sandreas.hansson@arm.com# get accurate instruction counts in KVM.
89310710Sandreas.hansson@arm.commain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
89411811Sbaz21@cam.ac.uk    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
89511811Sbaz21@cam.ac.uk
89611811Sbaz21@cam.ac.uk
89711811Sbaz21@cam.ac.uk######################################################################
89811811Sbaz21@cam.ac.uk#
89911811Sbaz21@cam.ac.uk# Finish the configuration
90010710Sandreas.hansson@arm.com#
90110710Sandreas.hansson@arm.commain = conf.Finish()
90210710Sandreas.hansson@arm.com
90310710Sandreas.hansson@arm.com######################################################################
90410384SCurtis.Dunham@arm.com#
9054554Sbinkertn@umich.edu# Collect all non-global variables
9064554Sbinkertn@umich.edu#
9074554Sbinkertn@umich.edu
9086121Snate@binkert.org# Define the universe of supported ISAs
9094554Sbinkertn@umich.eduall_isa_list = [ ]
9104554Sbinkertn@umich.eduall_gpu_isa_list = [ ]
9114554Sbinkertn@umich.eduExport('all_isa_list')
9124781Snate@binkert.orgExport('all_gpu_isa_list')
9134554Sbinkertn@umich.edu
9144554Sbinkertn@umich.educlass CpuModel(object):
9152667Sstever@eecs.umich.edu    '''The CpuModel class encapsulates everything the ISA parser needs to
9164554Sbinkertn@umich.edu    know about a particular CPU model.'''
9174554Sbinkertn@umich.edu
9184554Sbinkertn@umich.edu    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
9194554Sbinkertn@umich.edu    dict = {}
9202667Sstever@eecs.umich.edu
9214554Sbinkertn@umich.edu    # Constructor.  Automatically adds models to CpuModel.dict.
9222667Sstever@eecs.umich.edu    def __init__(self, name, default=False):
9234554Sbinkertn@umich.edu        self.name = name           # name of model
9246121Snate@binkert.org
9252667Sstever@eecs.umich.edu        # This cpu is enabled by default
9269986Sandreas@sandberg.pp.se        self.default = default
9279986Sandreas@sandberg.pp.se
9289986Sandreas@sandberg.pp.se        # Add self to dict
9299986Sandreas@sandberg.pp.se        if name in CpuModel.dict:
9309986Sandreas@sandberg.pp.se            raise AttributeError, "CpuModel '%s' already registered" % name
9319986Sandreas@sandberg.pp.se        CpuModel.dict[name] = self
9329986Sandreas@sandberg.pp.se
9339986Sandreas@sandberg.pp.seExport('CpuModel')
9349986Sandreas@sandberg.pp.se
9359986Sandreas@sandberg.pp.se# Sticky variables get saved in the variables file so they persist from
9369986Sandreas@sandberg.pp.se# one invocation to the next (unless overridden, in which case the new
9379986Sandreas@sandberg.pp.se# value becomes sticky).
9389986Sandreas@sandberg.pp.sesticky_vars = Variables(args=ARGUMENTS)
9399986Sandreas@sandberg.pp.seExport('sticky_vars')
9409986Sandreas@sandberg.pp.se
9419986Sandreas@sandberg.pp.se# Sticky variables that should be exported
9429986Sandreas@sandberg.pp.seexport_vars = []
9439986Sandreas@sandberg.pp.seExport('export_vars')
9449986Sandreas@sandberg.pp.se
9459986Sandreas@sandberg.pp.se# For Ruby
9462638Sstever@eecs.umich.eduall_protocols = []
9472638Sstever@eecs.umich.eduExport('all_protocols')
9486121Snate@binkert.orgprotocol_dirs = []
9493716Sstever@eecs.umich.eduExport('protocol_dirs')
9505522Snate@binkert.orgslicc_includes = []
9519986Sandreas@sandberg.pp.seExport('slicc_includes')
9529986Sandreas@sandberg.pp.se
9539986Sandreas@sandberg.pp.se# Walk the tree and execute all SConsopts scripts that wil add to the
9545522Snate@binkert.org# above variables
9555227Ssaidi@eecs.umich.eduif GetOption('verbose'):
9565227Ssaidi@eecs.umich.edu    print "Reading SConsopts"
9575227Ssaidi@eecs.umich.edufor bdir in [ base_dir ] + extras_dir_list:
9585227Ssaidi@eecs.umich.edu    if not isdir(bdir):
9596654Snate@binkert.org        print "Error: directory '%s' does not exist" % bdir
9606654Snate@binkert.org        Exit(1)
9617769SAli.Saidi@ARM.com    for root, dirs, files in os.walk(bdir):
9627769SAli.Saidi@ARM.com        if 'SConsopts' in files:
9637769SAli.Saidi@ARM.com            if GetOption('verbose'):
9647769SAli.Saidi@ARM.com                print "Reading", joinpath(root, 'SConsopts')
9655227Ssaidi@eecs.umich.edu            SConscript(joinpath(root, 'SConsopts'))
9665227Ssaidi@eecs.umich.edu
9675227Ssaidi@eecs.umich.eduall_isa_list.sort()
9685204Sstever@gmail.comall_gpu_isa_list.sort()
9695204Sstever@gmail.com
9705204Sstever@gmail.comsticky_vars.AddVariables(
9715204Sstever@gmail.com    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
9725204Sstever@gmail.com    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
9735204Sstever@gmail.com    ListVariable('CPU_MODELS', 'CPU models',
9745204Sstever@gmail.com                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
9755204Sstever@gmail.com                 sorted(CpuModel.dict.keys())),
9765204Sstever@gmail.com    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
9775204Sstever@gmail.com                 False),
9785204Sstever@gmail.com    BoolVariable('SS_COMPATIBLE_FP',
9795204Sstever@gmail.com                 'Make floating-point results compatible with SimpleScalar',
9805204Sstever@gmail.com                 False),
9815204Sstever@gmail.com    BoolVariable('USE_SSE2',
9825204Sstever@gmail.com                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
9835204Sstever@gmail.com                 False),
9845204Sstever@gmail.com    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
9856121Snate@binkert.org    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
9865204Sstever@gmail.com    BoolVariable('USE_PNG',  'Enable support for PNG images', have_png),
9877727SAli.Saidi@ARM.com    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability',
9887727SAli.Saidi@ARM.com                 False),
9897727SAli.Saidi@ARM.com    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models',
9907727SAli.Saidi@ARM.com                 have_kvm),
9917727SAli.Saidi@ARM.com    BoolVariable('USE_TUNTAP',
99210453SAndrew.Bardsley@arm.com                 'Enable using a tap device to bridge to the host network',
99310453SAndrew.Bardsley@arm.com                 have_tuntap),
99410453SAndrew.Bardsley@arm.com    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
99510453SAndrew.Bardsley@arm.com    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
99610453SAndrew.Bardsley@arm.com                  all_protocols),
99710453SAndrew.Bardsley@arm.com    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
99810453SAndrew.Bardsley@arm.com                 backtrace_impls[-1], backtrace_impls)
99910453SAndrew.Bardsley@arm.com    )
100010453SAndrew.Bardsley@arm.com
100110453SAndrew.Bardsley@arm.com# These variables get exported to #defines in config/*.hh (see src/SConscript).
100210453SAndrew.Bardsley@arm.comexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
100310160Sandreas.hansson@arm.com                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
100410453SAndrew.Bardsley@arm.com                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST',
100510453SAndrew.Bardsley@arm.com                'USE_PNG']
100610453SAndrew.Bardsley@arm.com
100710453SAndrew.Bardsley@arm.com###################################################
100810453SAndrew.Bardsley@arm.com#
100910453SAndrew.Bardsley@arm.com# Define a SCons builder for configuration flag headers.
101010453SAndrew.Bardsley@arm.com#
101110453SAndrew.Bardsley@arm.com###################################################
10129812Sandreas.hansson@arm.com
101310453SAndrew.Bardsley@arm.com# This function generates a config header file that #defines the
101410453SAndrew.Bardsley@arm.com# variable symbol to the current variable setting (0 or 1).  The source
101510453SAndrew.Bardsley@arm.com# operands are the name of the variable and a Value node containing the
101610453SAndrew.Bardsley@arm.com# value of the variable.
101710453SAndrew.Bardsley@arm.comdef build_config_file(target, source, env):
101810453SAndrew.Bardsley@arm.com    (variable, value) = [s.get_contents() for s in source]
101910453SAndrew.Bardsley@arm.com    f = file(str(target[0]), 'w')
102010453SAndrew.Bardsley@arm.com    print >> f, '#define', variable, value
102110453SAndrew.Bardsley@arm.com    f.close()
102210453SAndrew.Bardsley@arm.com    return None
102310453SAndrew.Bardsley@arm.com
102410453SAndrew.Bardsley@arm.com# Combine the two functions into a scons Action object.
10257727SAli.Saidi@ARM.comconfig_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
102610453SAndrew.Bardsley@arm.com
102710453SAndrew.Bardsley@arm.com# The emitter munges the source & target node lists to reflect what
102810453SAndrew.Bardsley@arm.com# we're really doing.
102910453SAndrew.Bardsley@arm.comdef config_emitter(target, source, env):
103010453SAndrew.Bardsley@arm.com    # extract variable name from Builder arg
10313118Sstever@eecs.umich.edu    variable = str(target[0])
103210453SAndrew.Bardsley@arm.com    # True target is config header file
103310453SAndrew.Bardsley@arm.com    target = joinpath('config', variable.lower() + '.hh')
103410453SAndrew.Bardsley@arm.com    val = env[variable]
103510453SAndrew.Bardsley@arm.com    if isinstance(val, bool):
10363118Sstever@eecs.umich.edu        # Force value to 0/1
10373483Ssaidi@eecs.umich.edu        val = int(val)
10383494Ssaidi@eecs.umich.edu    elif isinstance(val, str):
10393494Ssaidi@eecs.umich.edu        val = '"' + val + '"'
10403483Ssaidi@eecs.umich.edu
10413483Ssaidi@eecs.umich.edu    # Sources are variable name & value (packaged in SCons Value nodes)
10423483Ssaidi@eecs.umich.edu    return ([target], [Value(variable), Value(val)])
10433053Sstever@eecs.umich.edu
10443053Sstever@eecs.umich.educonfig_builder = Builder(emitter = config_emitter, action = config_action)
10453918Ssaidi@eecs.umich.edu
10463053Sstever@eecs.umich.edumain.Append(BUILDERS = { 'ConfigFile' : config_builder })
10473053Sstever@eecs.umich.edu
10483053Sstever@eecs.umich.edu###################################################
10493053Sstever@eecs.umich.edu#
10503053Sstever@eecs.umich.edu# Builders for static and shared partially linked object files.
10519396Sandreas.hansson@arm.com#
10529396Sandreas.hansson@arm.com###################################################
10539396Sandreas.hansson@arm.com
10549396Sandreas.hansson@arm.compartial_static_builder = Builder(action=SCons.Defaults.LinkAction,
10559396Sandreas.hansson@arm.com                                 src_suffix='$OBJSUFFIX',
10569396Sandreas.hansson@arm.com                                 src_builder=['StaticObject', 'Object'],
10579396Sandreas.hansson@arm.com                                 LINKFLAGS='$PLINKFLAGS',
10589396Sandreas.hansson@arm.com                                 LIBS='')
10599396Sandreas.hansson@arm.com
10609477Sandreas.hansson@arm.comdef partial_shared_emitter(target, source, env):
10619396Sandreas.hansson@arm.com    for tgt in target:
10629477Sandreas.hansson@arm.com        tgt.attributes.shared = 1
10639477Sandreas.hansson@arm.com    return (target, source)
10649477Sandreas.hansson@arm.compartial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
10659477Sandreas.hansson@arm.com                                 emitter=partial_shared_emitter,
10669396Sandreas.hansson@arm.com                                 src_suffix='$SHOBJSUFFIX',
10677840Snate@binkert.org                                 src_builder='SharedObject',
10687865Sgblack@eecs.umich.edu                                 SHLINKFLAGS='$PSHLINKFLAGS',
10697865Sgblack@eecs.umich.edu                                 LIBS='')
10707865Sgblack@eecs.umich.edu
10717865Sgblack@eecs.umich.edumain.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
10727865Sgblack@eecs.umich.edu                         'PartialStatic' : partial_static_builder })
10737840Snate@binkert.org
10749900Sandreas@sandberg.pp.se# builds in ext are shared across all configs in the build root.
10759900Sandreas@sandberg.pp.seext_dir = abspath(joinpath(str(main.root), 'ext'))
10769900Sandreas@sandberg.pp.seext_build_dirs = []
10779900Sandreas@sandberg.pp.sefor root, dirs, files in os.walk(ext_dir):
107810456SCurtis.Dunham@arm.com    if 'SConscript' in files:
107910456SCurtis.Dunham@arm.com        build_dir = os.path.relpath(root, ext_dir)
108010456SCurtis.Dunham@arm.com        ext_build_dirs.append(build_dir)
108110456SCurtis.Dunham@arm.com        main.SConscript(joinpath(root, 'SConscript'),
108210456SCurtis.Dunham@arm.com                        variant_dir=joinpath(build_root, build_dir))
108310456SCurtis.Dunham@arm.com
108410456SCurtis.Dunham@arm.commain.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
108510456SCurtis.Dunham@arm.com
108610456SCurtis.Dunham@arm.com###################################################
108710456SCurtis.Dunham@arm.com#
10889045SAli.Saidi@ARM.com# This builder and wrapper method are used to set up a directory with
108911235Sandreas.sandberg@arm.com# switching headers. Those are headers which are in a generic location and
109011235Sandreas.sandberg@arm.com# that include more specific headers from a directory chosen at build time
109111235Sandreas.sandberg@arm.com# based on the current build settings.
109211235Sandreas.sandberg@arm.com#
109311235Sandreas.sandberg@arm.com###################################################
109411235Sandreas.sandberg@arm.com
109511235Sandreas.sandberg@arm.comdef build_switching_header(target, source, env):
109611235Sandreas.sandberg@arm.com    path = str(target[0])
109711811Sbaz21@cam.ac.uk    subdir = str(source[0])
109811811Sbaz21@cam.ac.uk    dp, fp = os.path.split(path)
109911811Sbaz21@cam.ac.uk    dp = os.path.relpath(os.path.realpath(dp),
110011811Sbaz21@cam.ac.uk                         os.path.realpath(env['BUILDDIR']))
110111811Sbaz21@cam.ac.uk    with open(path, 'w') as hdr:
110211235Sandreas.sandberg@arm.com        print >>hdr, '#include "%s/%s/%s"' % (dp, subdir, fp)
110311235Sandreas.sandberg@arm.com
110411235Sandreas.sandberg@arm.comswitching_header_action = MakeAction(build_switching_header,
110511235Sandreas.sandberg@arm.com                                     Transform('GENERATE'))
110611235Sandreas.sandberg@arm.com
110711235Sandreas.sandberg@arm.comswitching_header_builder = Builder(action=switching_header_action,
110811235Sandreas.sandberg@arm.com                                   source_factory=Value,
11097840Snate@binkert.org                                   single_source=True)
11107840Snate@binkert.org
11117840Snate@binkert.orgmain.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
11121858SN/A
11131858SN/Adef switching_headers(self, headers, source):
11141858SN/A    for header in headers:
11151858SN/A        self.SwitchingHeader(header, source)
11161858SN/A
11171858SN/Amain.AddMethod(switching_headers, 'SwitchingHeaders')
11189903Sandreas.hansson@arm.com
11199903Sandreas.hansson@arm.com###################################################
11209903Sandreas.hansson@arm.com#
11219903Sandreas.hansson@arm.com# Define build environments for selected configurations.
112210841Sandreas.sandberg@arm.com#
11239651SAndreas.Sandberg@ARM.com###################################################
11249903Sandreas.hansson@arm.com
11259651SAndreas.Sandberg@ARM.comfor variant_path in variant_paths:
11269651SAndreas.Sandberg@ARM.com    if not GetOption('silent'):
112710841Sandreas.sandberg@arm.com        print "Building in", variant_path
112810841Sandreas.sandberg@arm.com
112910841Sandreas.sandberg@arm.com    # Make a copy of the build-root environment to use for this config.
113010841Sandreas.sandberg@arm.com    env = main.Clone()
113110841Sandreas.sandberg@arm.com    env['BUILDDIR'] = variant_path
113210841Sandreas.sandberg@arm.com
11339651SAndreas.Sandberg@ARM.com    # variant_dir is the tail component of build path, and is used to
11349651SAndreas.Sandberg@ARM.com    # determine the build parameters (e.g., 'ALPHA_SE')
11359651SAndreas.Sandberg@ARM.com    (build_root, variant_dir) = splitpath(variant_path)
11369651SAndreas.Sandberg@ARM.com
11379651SAndreas.Sandberg@ARM.com    # Set env variables according to the build directory config.
11389651SAndreas.Sandberg@ARM.com    sticky_vars.files = []
11399651SAndreas.Sandberg@ARM.com    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
11409651SAndreas.Sandberg@ARM.com    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
11419651SAndreas.Sandberg@ARM.com    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
114210841Sandreas.sandberg@arm.com    current_vars_file = joinpath(build_root, 'variables', variant_dir)
114310841Sandreas.sandberg@arm.com    if isfile(current_vars_file):
114410841Sandreas.sandberg@arm.com        sticky_vars.files.append(current_vars_file)
114510841Sandreas.sandberg@arm.com        if not GetOption('silent'):
114610841Sandreas.sandberg@arm.com            print "Using saved variables file %s" % current_vars_file
114710841Sandreas.sandberg@arm.com    elif variant_dir in ext_build_dirs:
114810860Sandreas.sandberg@arm.com        # Things in ext are built without a variant directory.
114910841Sandreas.sandberg@arm.com        continue
115010841Sandreas.sandberg@arm.com    else:
115110841Sandreas.sandberg@arm.com        # Build dir-specific variables file doesn't exist.
115210841Sandreas.sandberg@arm.com
115310841Sandreas.sandberg@arm.com        # Make sure the directory is there so we can create it later
115410841Sandreas.sandberg@arm.com        opt_dir = dirname(current_vars_file)
115510841Sandreas.sandberg@arm.com        if not isdir(opt_dir):
115610841Sandreas.sandberg@arm.com            mkdir(opt_dir)
115710841Sandreas.sandberg@arm.com
115810841Sandreas.sandberg@arm.com        # Get default build variables from source tree.  Variables are
115910841Sandreas.sandberg@arm.com        # normally determined by name of $VARIANT_DIR, but can be
11609651SAndreas.Sandberg@ARM.com        # overridden by '--default=' arg on command line.
11619651SAndreas.Sandberg@ARM.com        default = GetOption('default')
11629986Sandreas@sandberg.pp.se        opts_dir = joinpath(main.root.abspath, 'build_opts')
11639986Sandreas@sandberg.pp.se        if default:
11649986Sandreas@sandberg.pp.se            default_vars_files = [joinpath(build_root, 'variables', default),
11659986Sandreas@sandberg.pp.se                                  joinpath(opts_dir, default)]
11669986Sandreas@sandberg.pp.se        else:
11679986Sandreas@sandberg.pp.se            default_vars_files = [joinpath(opts_dir, variant_dir)]
11685863Snate@binkert.org        existing_files = filter(isfile, default_vars_files)
11695863Snate@binkert.org        if existing_files:
11705863Snate@binkert.org            default_vars_file = existing_files[0]
11715863Snate@binkert.org            sticky_vars.files.append(default_vars_file)
11726121Snate@binkert.org            print "Variables file %s not found,\n  using defaults in %s" \
11731858SN/A                  % (current_vars_file, default_vars_file)
11745863Snate@binkert.org        else:
11755863Snate@binkert.org            print "Error: cannot find variables file %s or " \
11765863Snate@binkert.org                  "default file(s) %s" \
11775863Snate@binkert.org                  % (current_vars_file, ' or '.join(default_vars_files))
11785863Snate@binkert.org            Exit(1)
11792139SN/A
11804202Sbinkertn@umich.edu    # Apply current variable settings to env
118111308Santhony.gutierrez@amd.com    sticky_vars.Update(env)
11824202Sbinkertn@umich.edu
118311308Santhony.gutierrez@amd.com    help_texts["local_vars"] += \
11842139SN/A        "Build variables for %s:\n" % variant_dir \
11856994Snate@binkert.org                 + sticky_vars.GenerateHelpText(env)
11866994Snate@binkert.org
11876994Snate@binkert.org    # Process variable settings.
11886994Snate@binkert.org
11896994Snate@binkert.org    if not have_fenv and env['USE_FENV']:
11906994Snate@binkert.org        print "Warning: <fenv.h> not available; " \
11916994Snate@binkert.org              "forcing USE_FENV to False in", variant_dir + "."
11926994Snate@binkert.org        env['USE_FENV'] = False
119310319SAndreas.Sandberg@ARM.com
11946994Snate@binkert.org    if not env['USE_FENV']:
11956994Snate@binkert.org        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
11966994Snate@binkert.org        print "         FP results may deviate slightly from other platforms."
11976994Snate@binkert.org
11986994Snate@binkert.org    if not have_png and env['USE_PNG']:
11996994Snate@binkert.org        print "Warning: <png.h> not available; " \
12006994Snate@binkert.org              "forcing USE_PNG to False in", variant_dir + "."
12016994Snate@binkert.org        env['USE_PNG'] = False
12026994Snate@binkert.org
12036994Snate@binkert.org    if env['USE_PNG']:
12046994Snate@binkert.org        env.Append(LIBS=['png'])
12052155SN/A
12065863Snate@binkert.org    if env['EFENCE']:
12071869SN/A        env.Append(LIBS=['efence'])
12081869SN/A
12095863Snate@binkert.org    if env['USE_KVM']:
12105863Snate@binkert.org        if not have_kvm:
12114202Sbinkertn@umich.edu            print "Warning: Can not enable KVM, host seems to lack KVM support"
12126108Snate@binkert.org            env['USE_KVM'] = False
12136108Snate@binkert.org        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
12146108Snate@binkert.org            print "Info: KVM support disabled due to unsupported host and " \
12156108Snate@binkert.org                "target ISA combination"
12169219Spower.jg@gmail.com            env['USE_KVM'] = False
12179219Spower.jg@gmail.com
12189219Spower.jg@gmail.com    if env['USE_TUNTAP']:
12199219Spower.jg@gmail.com        if not have_tuntap:
12209219Spower.jg@gmail.com            print "Warning: Can't connect EtherTap with a tap device."
12219219Spower.jg@gmail.com            env['USE_TUNTAP'] = False
12229219Spower.jg@gmail.com
12239219Spower.jg@gmail.com    if env['BUILD_GPU']:
12244202Sbinkertn@umich.edu        env.Append(CPPDEFINES=['BUILD_GPU'])
12255863Snate@binkert.org
122610135SCurtis.Dunham@arm.com    # Warn about missing optional functionality
12278474Sgblack@eecs.umich.edu    if env['USE_KVM']:
12285742Snate@binkert.org        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
12298268Ssteve.reinhardt@amd.com            print "Warning: perf_event headers lack support for the " \
12308268Ssteve.reinhardt@amd.com                "exclude_host attribute. KVM instruction counts will " \
12318268Ssteve.reinhardt@amd.com                "be inaccurate."
12325742Snate@binkert.org
12335341Sstever@gmail.com    # Save sticky variable settings back to current variables file
12348474Sgblack@eecs.umich.edu    sticky_vars.Save(current_vars_file, env)
12358474Sgblack@eecs.umich.edu
12365342Sstever@gmail.com    if env['USE_SSE2']:
12374202Sbinkertn@umich.edu        env.Append(CCFLAGS=['-msse2'])
12384202Sbinkertn@umich.edu
123911308Santhony.gutierrez@amd.com    # The src/SConscript file sets up the build rules in 'env' according
12404202Sbinkertn@umich.edu    # to the configured variables.  It returns a list of environments,
12415863Snate@binkert.org    # one for each variant build (debug, opt, etc.)
12425863Snate@binkert.org    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
124311308Santhony.gutierrez@amd.com
12446994Snate@binkert.org# base help text
12456994Snate@binkert.orgHelp('''
124610319SAndreas.Sandberg@ARM.comUsage: scons [scons options] [build variables] [target(s)]
12475863Snate@binkert.org
12485863Snate@binkert.orgExtra scons options:
12495863Snate@binkert.org%(options)s
12505863Snate@binkert.org
12515863Snate@binkert.orgGlobal build variables:
12525863Snate@binkert.org%(global_vars)s
12535863Snate@binkert.org
12545863Snate@binkert.org%(local_vars)s
12557840Snate@binkert.org''' % help_texts)
12565863Snate@binkert.org