SConstruct revision 12246
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2013, 2015-2017 ARM Limited
4955SN/A# All rights reserved.
5955SN/A#
6955SN/A# The license below extends only to copyright in the software and shall
7955SN/A# not be construed as granting a license to any other intellectual
8955SN/A# property including but not limited to intellectual property relating
9955SN/A# to a hardware implementation of the functionality of the software
10955SN/A# licensed hereunder.  You may use the software subject to the license
11955SN/A# terms below provided that you ensure that this notice is replicated
12955SN/A# unmodified and in its entirety in all distributions of the software,
13955SN/A# modified or unmodified, in source code or in binary form.
14955SN/A#
15955SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
16955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
17955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
18955SN/A# All rights reserved.
19955SN/A#
20955SN/A# Redistribution and use in source and binary forms, with or without
21955SN/A# modification, are permitted provided that the following conditions are
22955SN/A# met: redistributions of source code must retain the above copyright
23955SN/A# notice, this list of conditions and the following disclaimer;
24955SN/A# redistributions in binary form must reproduce the above copyright
25955SN/A# notice, this list of conditions and the following disclaimer in the
26955SN/A# documentation and/or other materials provided with the distribution;
27955SN/A# neither the name of the copyright holders nor the names of its
282665Ssaidi@eecs.umich.edu# contributors may be used to endorse or promote products derived from
292665Ssaidi@eecs.umich.edu# this software without specific prior written permission.
30955SN/A#
31955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
352632Sstever@eecs.umich.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
362632Sstever@eecs.umich.edu# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
372632Sstever@eecs.umich.edu# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
382632Sstever@eecs.umich.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
402632Sstever@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
412632Sstever@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
422761Sstever@eecs.umich.edu#
432632Sstever@eecs.umich.edu# Authors: Steve Reinhardt
442632Sstever@eecs.umich.edu#          Nathan Binkert
452632Sstever@eecs.umich.edu
462761Sstever@eecs.umich.edu###################################################
472761Sstever@eecs.umich.edu#
482761Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
492632Sstever@eecs.umich.edu#
502632Sstever@eecs.umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
512761Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
522761Sstever@eecs.umich.edu# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
532761Sstever@eecs.umich.edu# the optimized full-system version).
542761Sstever@eecs.umich.edu#
552761Sstever@eecs.umich.edu# You can build gem5 in a different directory as long as there is a
562632Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
572632Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
582632Sstever@eecs.umich.edu# built for the same host system.
592632Sstever@eecs.umich.edu#
602632Sstever@eecs.umich.edu# Examples:
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
63955SN/A#   scons to search up the directory tree for this SConstruct file.
64955SN/A#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
65955SN/A#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
66955SN/A#
67955SN/A#   The following two commands are equivalent and demonstrate building
683918Ssaidi@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
694202Sbinkertn@umich.edu#   scons to chdir to the specified directory to find this SConstruct
704678Snate@binkert.org#   file.
71955SN/A#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
722656Sstever@eecs.umich.edu#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
732656Sstever@eecs.umich.edu#
742656Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
752656Sstever@eecs.umich.edu# 'gem5' directory (or use -u or -C to tell scons where to find this
762656Sstever@eecs.umich.edu# file), you can use 'scons -h' to print all the gem5-specific build
772656Sstever@eecs.umich.edu# options as well.
782656Sstever@eecs.umich.edu#
792653Sstever@eecs.umich.edu###################################################
802653Sstever@eecs.umich.edu
812653Sstever@eecs.umich.edu# Global Python includes
822653Sstever@eecs.umich.eduimport itertools
832653Sstever@eecs.umich.eduimport os
842653Sstever@eecs.umich.eduimport re
852653Sstever@eecs.umich.eduimport shutil
862653Sstever@eecs.umich.eduimport subprocess
872653Sstever@eecs.umich.eduimport sys
882653Sstever@eecs.umich.edu
892653Sstever@eecs.umich.edufrom os import mkdir, environ
901852SN/Afrom os.path import abspath, basename, dirname, expanduser, normpath
91955SN/Afrom os.path import exists,  isdir, isfile
92955SN/Afrom os.path import join as joinpath, split as splitpath
93955SN/A
943717Sstever@eecs.umich.edu# SCons includes
953716Sstever@eecs.umich.eduimport SCons
96955SN/Aimport SCons.Node
971533SN/A
983716Sstever@eecs.umich.edufrom m5.util import compareVersions, readCommand
991533SN/A
1004678Snate@binkert.orghelp_texts = {
1014678Snate@binkert.org    "options" : "",
1024678Snate@binkert.org    "global_vars" : "",
1034678Snate@binkert.org    "local_vars" : ""
1044678Snate@binkert.org}
1054678Snate@binkert.org
1064678Snate@binkert.orgExport("help_texts")
1074678Snate@binkert.org
1084678Snate@binkert.org
1094678Snate@binkert.org# There's a bug in scons in that (1) by default, the help texts from
1104678Snate@binkert.org# AddOption() are supposed to be displayed when you type 'scons -h'
1114678Snate@binkert.org# and (2) you can override the help displayed by 'scons -h' using the
1124678Snate@binkert.org# Help() function, but these two features are incompatible: once
1134678Snate@binkert.org# you've overridden the help text using Help(), there's no way to get
1144678Snate@binkert.org# at the help texts from AddOptions.  See:
1154678Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1164678Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1174678Snate@binkert.org# This hack lets us extract the help text from AddOptions and
1184678Snate@binkert.org# re-inject it via Help().  Ideally someday this bug will be fixed and
1194678Snate@binkert.org# we can just use AddOption directly.
1204678Snate@binkert.orgdef AddLocalOption(*args, **kwargs):
1214678Snate@binkert.org    col_width = 30
1224678Snate@binkert.org
1234678Snate@binkert.org    help = "  " + ", ".join(args)
1244678Snate@binkert.org    if "help" in kwargs:
1254678Snate@binkert.org        length = len(help)
1264678Snate@binkert.org        if length >= col_width:
1274678Snate@binkert.org            help += "\n" + " " * col_width
128955SN/A        else:
129955SN/A            help += " " * (col_width - length)
1302632Sstever@eecs.umich.edu        help += kwargs["help"]
1312632Sstever@eecs.umich.edu    help_texts["options"] += help + "\n"
132955SN/A
133955SN/A    AddOption(*args, **kwargs)
134955SN/A
135955SN/AAddLocalOption('--colors', dest='use_colors', action='store_true',
1362632Sstever@eecs.umich.edu               help="Add color to abbreviated scons output")
137955SN/AAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1382632Sstever@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1392632Sstever@eecs.umich.eduAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1402632Sstever@eecs.umich.edu               action='store_true',
1412632Sstever@eecs.umich.edu               help="Build with support for C++-based configuration")
1422632Sstever@eecs.umich.eduAddLocalOption('--default', dest='default', type='string', action='store',
1432632Sstever@eecs.umich.edu               help='Override which build_opts file to use for defaults')
1442632Sstever@eecs.umich.eduAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1453053Sstever@eecs.umich.edu               help='Disable style checking hooks')
1463053Sstever@eecs.umich.eduAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1473053Sstever@eecs.umich.edu               help='Disable Link-Time Optimization for fast')
1483053Sstever@eecs.umich.eduAddLocalOption('--force-lto', dest='force_lto', action='store_true',
1493053Sstever@eecs.umich.edu               help='Use Link-Time Optimization instead of partial linking' +
1503053Sstever@eecs.umich.edu                    ' when the compiler doesn\'t support using them together.')
1513053Sstever@eecs.umich.eduAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1523053Sstever@eecs.umich.edu               help='Update test reference outputs')
1533053Sstever@eecs.umich.eduAddLocalOption('--verbose', dest='verbose', action='store_true',
1543053Sstever@eecs.umich.edu               help='Print full tool command lines')
1553053Sstever@eecs.umich.eduAddLocalOption('--without-python', dest='without_python',
1563053Sstever@eecs.umich.edu               action='store_true',
1573053Sstever@eecs.umich.edu               help='Build without Python configuration support')
1583053Sstever@eecs.umich.eduAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1593053Sstever@eecs.umich.edu               action='store_true',
1603053Sstever@eecs.umich.edu               help='Disable linking against tcmalloc')
1612632Sstever@eecs.umich.eduAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1622632Sstever@eecs.umich.edu               help='Build with Undefined Behavior Sanitizer if available')
1632632Sstever@eecs.umich.eduAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1642632Sstever@eecs.umich.edu               help='Build with Address Sanitizer if available')
1652632Sstever@eecs.umich.edu
1662632Sstever@eecs.umich.eduif GetOption('no_lto') and GetOption('force_lto'):
1673718Sstever@eecs.umich.edu    print '--no-lto and --force-lto are mutually exclusive'
1683718Sstever@eecs.umich.edu    Exit(1)
1693718Sstever@eecs.umich.edu
1703718Sstever@eecs.umich.edu########################################################################
1713718Sstever@eecs.umich.edu#
1723718Sstever@eecs.umich.edu# Set up the main build environment.
1733718Sstever@eecs.umich.edu#
1743718Sstever@eecs.umich.edu########################################################################
1753718Sstever@eecs.umich.edu
1763718Sstever@eecs.umich.edumain = Environment()
1773718Sstever@eecs.umich.edu
1783718Sstever@eecs.umich.edufrom gem5_scons import Transform
1793718Sstever@eecs.umich.edufrom gem5_scons.util import get_termcap
1802634Sstever@eecs.umich.edutermcap = get_termcap()
1812634Sstever@eecs.umich.edu
1822632Sstever@eecs.umich.edumain_dict_keys = main.Dictionary().keys()
1832638Sstever@eecs.umich.edu
1842632Sstever@eecs.umich.edu# Check that we have a C/C++ compiler
1852632Sstever@eecs.umich.eduif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
1862632Sstever@eecs.umich.edu    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
1872632Sstever@eecs.umich.edu    Exit(1)
1882632Sstever@eecs.umich.edu
1892632Sstever@eecs.umich.edu###################################################
1901858SN/A#
1913716Sstever@eecs.umich.edu# Figure out which configurations to set up based on the path(s) of
1922638Sstever@eecs.umich.edu# the target(s).
1932638Sstever@eecs.umich.edu#
1942638Sstever@eecs.umich.edu###################################################
1952638Sstever@eecs.umich.edu
1962638Sstever@eecs.umich.edu# Find default configuration & binary.
1972638Sstever@eecs.umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
1982638Sstever@eecs.umich.edu
1993716Sstever@eecs.umich.edu# helper function: find last occurrence of element in list
2002634Sstever@eecs.umich.edudef rfind(l, elt, offs = -1):
2012634Sstever@eecs.umich.edu    for i in range(len(l)+offs, 0, -1):
202955SN/A        if l[i] == elt:
203955SN/A            return i
204955SN/A    raise ValueError, "element not found"
205955SN/A
206955SN/A# Take a list of paths (or SCons Nodes) and return a list with all
207955SN/A# paths made absolute and ~-expanded.  Paths will be interpreted
208955SN/A# relative to the launch directory unless a different root is provided
209955SN/Adef makePathListAbsolute(path_list, root=GetLaunchDir()):
2101858SN/A    return [abspath(joinpath(root, expanduser(str(p))))
2111858SN/A            for p in path_list]
2122632Sstever@eecs.umich.edu
213955SN/A# Each target must have 'build' in the interior of the path; the
2143643Ssaidi@eecs.umich.edu# directory below this will determine the build parameters.  For
2153643Ssaidi@eecs.umich.edu# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2163643Ssaidi@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
2173643Ssaidi@eecs.umich.edu# follow 'build' in the build path.
2183643Ssaidi@eecs.umich.edu
2193643Ssaidi@eecs.umich.edu# The funky assignment to "[:]" is needed to replace the list contents
2203643Ssaidi@eecs.umich.edu# in place rather than reassign the symbol to a new list, which
2213643Ssaidi@eecs.umich.edu# doesn't work (obviously!).
2224494Ssaidi@eecs.umich.eduBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
2234494Ssaidi@eecs.umich.edu
2243716Sstever@eecs.umich.edu# Generate a list of the unique build roots and configs that the
2251105SN/A# collected targets reference.
2262667Sstever@eecs.umich.eduvariant_paths = []
2272667Sstever@eecs.umich.edubuild_root = None
2282667Sstever@eecs.umich.edufor t in BUILD_TARGETS:
2292667Sstever@eecs.umich.edu    path_dirs = t.split('/')
2302667Sstever@eecs.umich.edu    try:
2312667Sstever@eecs.umich.edu        build_top = rfind(path_dirs, 'build', -2)
2321869SN/A    except:
2331869SN/A        print "Error: no non-leaf 'build' dir found on target path", t
2341869SN/A        Exit(1)
2351869SN/A    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2361869SN/A    if not build_root:
2371065SN/A        build_root = this_build_root
2382632Sstever@eecs.umich.edu    else:
2392632Sstever@eecs.umich.edu        if this_build_root != build_root:
2403918Ssaidi@eecs.umich.edu            print "Error: build targets not under same build root\n"\
2413918Ssaidi@eecs.umich.edu                  "  %s\n  %s" % (build_root, this_build_root)
2423940Ssaidi@eecs.umich.edu            Exit(1)
2433918Ssaidi@eecs.umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
2443918Ssaidi@eecs.umich.edu    if variant_path not in variant_paths:
2453918Ssaidi@eecs.umich.edu        variant_paths.append(variant_path)
2463918Ssaidi@eecs.umich.edu
2473918Ssaidi@eecs.umich.edu# Make sure build_root exists (might not if this is the first build there)
2483918Ssaidi@eecs.umich.eduif not isdir(build_root):
2493940Ssaidi@eecs.umich.edu    mkdir(build_root)
2503940Ssaidi@eecs.umich.edumain['BUILDROOT'] = build_root
2513940Ssaidi@eecs.umich.edu
2523942Ssaidi@eecs.umich.eduExport('main')
2533940Ssaidi@eecs.umich.edu
2543918Ssaidi@eecs.umich.edumain.SConsignFile(joinpath(build_root, "sconsign"))
2553918Ssaidi@eecs.umich.edu
256955SN/A# Default duplicate option is to use hard links, but this messes up
2571858SN/A# when you use emacs to edit a file in the target dir, as emacs moves
2583918Ssaidi@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
2593918Ssaidi@eecs.umich.edu# (soft) links work better.
2603918Ssaidi@eecs.umich.edumain.SetOption('duplicate', 'soft-copy')
2613918Ssaidi@eecs.umich.edu
2623940Ssaidi@eecs.umich.edu#
2633940Ssaidi@eecs.umich.edu# Set up global sticky variables... these are common to an entire build
2643918Ssaidi@eecs.umich.edu# tree (not specific to a particular build like ALPHA_SE)
2653918Ssaidi@eecs.umich.edu#
2663918Ssaidi@eecs.umich.edu
2673918Ssaidi@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
2683918Ssaidi@eecs.umich.edu
2693918Ssaidi@eecs.umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
2703918Ssaidi@eecs.umich.edu
2713918Ssaidi@eecs.umich.eduglobal_vars.AddVariables(
2723918Ssaidi@eecs.umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
2733940Ssaidi@eecs.umich.edu    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
2743918Ssaidi@eecs.umich.edu    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
2753918Ssaidi@eecs.umich.edu    ('BATCH', 'Use batch pool for build and tests', False),
2761851SN/A    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
2771851SN/A    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
2781858SN/A    ('EXTRAS', 'Add extra directories to the compilation', '')
2792632Sstever@eecs.umich.edu    )
280955SN/A
2813053Sstever@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
2823053Sstever@eecs.umich.eduglobal_vars.Update(main)
2833053Sstever@eecs.umich.eduhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
2843053Sstever@eecs.umich.edu
2853053Sstever@eecs.umich.edu# Save sticky variable settings back to current variables file
2863053Sstever@eecs.umich.eduglobal_vars.Save(global_vars_file, main)
2873053Sstever@eecs.umich.edu
2883053Sstever@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
2893053Sstever@eecs.umich.edu# look for sources etc.  This list is exported as extras_dir_list.
2904742Sstever@eecs.umich.edubase_dir = main.srcdir.abspath
2914742Sstever@eecs.umich.eduif main['EXTRAS']:
2923053Sstever@eecs.umich.edu    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
2933053Sstever@eecs.umich.eduelse:
2943053Sstever@eecs.umich.edu    extras_dir_list = []
2953053Sstever@eecs.umich.edu
2963053Sstever@eecs.umich.eduExport('base_dir')
2973053Sstever@eecs.umich.eduExport('extras_dir_list')
2983053Sstever@eecs.umich.edu
2993053Sstever@eecs.umich.edu# the ext directory should be on the #includes path
3003053Sstever@eecs.umich.edumain.Append(CPPPATH=[Dir('ext')])
3012667Sstever@eecs.umich.edu
3024554Sbinkertn@umich.edu# Add shared top-level headers
3034554Sbinkertn@umich.edumain.Prepend(CPPPATH=Dir('include'))
3042667Sstever@eecs.umich.edu
3054554Sbinkertn@umich.eduif GetOption('verbose'):
3064554Sbinkertn@umich.edu    def MakeAction(action, string, *args, **kwargs):
3074554Sbinkertn@umich.edu        return Action(action, *args, **kwargs)
3084554Sbinkertn@umich.eduelse:
3094554Sbinkertn@umich.edu    MakeAction = Action
3104554Sbinkertn@umich.edu    main['CCCOMSTR']        = Transform("CC")
3114554Sbinkertn@umich.edu    main['CXXCOMSTR']       = Transform("CXX")
3124554Sbinkertn@umich.edu    main['ASCOMSTR']        = Transform("AS")
3134554Sbinkertn@umich.edu    main['ARCOMSTR']        = Transform("AR", 0)
3144554Sbinkertn@umich.edu    main['LINKCOMSTR']      = Transform("LINK", 0)
3152667Sstever@eecs.umich.edu    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
3164554Sbinkertn@umich.edu    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
3174554Sbinkertn@umich.edu    main['M4COMSTR']        = Transform("M4")
3184554Sbinkertn@umich.edu    main['SHCCCOMSTR']      = Transform("SHCC")
3194554Sbinkertn@umich.edu    main['SHCXXCOMSTR']     = Transform("SHCXX")
3202667Sstever@eecs.umich.eduExport('MakeAction')
3214554Sbinkertn@umich.edu
3222667Sstever@eecs.umich.edu# Initialize the Link-Time Optimization (LTO) flags
3234554Sbinkertn@umich.edumain['LTO_CCFLAGS'] = []
3244554Sbinkertn@umich.edumain['LTO_LDFLAGS'] = []
3252667Sstever@eecs.umich.edu
3262638Sstever@eecs.umich.edu# According to the readme, tcmalloc works best if the compiler doesn't
3272638Sstever@eecs.umich.edu# assume that we're using the builtin malloc and friends. These flags
3282638Sstever@eecs.umich.edu# are compiler-specific, so we need to set them after we detect which
3293716Sstever@eecs.umich.edu# compiler we're using.
3303716Sstever@eecs.umich.edumain['TCMALLOC_CCFLAGS'] = []
3311858SN/A
3323118Sstever@eecs.umich.eduCXX_version = readCommand([main['CXX'],'--version'], exception=False)
3333118Sstever@eecs.umich.eduCXX_V = readCommand([main['CXX'],'-V'], exception=False)
3343118Sstever@eecs.umich.edu
3353118Sstever@eecs.umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3363118Sstever@eecs.umich.edumain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
3373118Sstever@eecs.umich.eduif main['GCC'] + main['CLANG'] > 1:
3383118Sstever@eecs.umich.edu    print 'Error: How can we have two at the same time?'
3393118Sstever@eecs.umich.edu    Exit(1)
3403118Sstever@eecs.umich.edu
3413118Sstever@eecs.umich.edu# Set up default C++ compiler flags
3423118Sstever@eecs.umich.eduif main['GCC'] or main['CLANG']:
3433716Sstever@eecs.umich.edu    # As gcc and clang share many flags, do the common parts here
3443118Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-pipe'])
3453118Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
3463118Sstever@eecs.umich.edu    # Enable -Wall and -Wextra and then disable the few warnings that
3473118Sstever@eecs.umich.edu    # we consistently violate
3483118Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
3493118Sstever@eecs.umich.edu                         '-Wno-sign-compare', '-Wno-unused-parameter'])
3503118Sstever@eecs.umich.edu    # We always compile using C++11
3513118Sstever@eecs.umich.edu    main.Append(CXXFLAGS=['-std=c++11'])
3523118Sstever@eecs.umich.edu    if sys.platform.startswith('freebsd'):
3533716Sstever@eecs.umich.edu        main.Append(CCFLAGS=['-I/usr/local/include'])
3543118Sstever@eecs.umich.edu        main.Append(CXXFLAGS=['-I/usr/local/include'])
3553118Sstever@eecs.umich.edu
3563118Sstever@eecs.umich.edu    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
3573118Sstever@eecs.umich.edu    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
3583118Sstever@eecs.umich.edu    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
3593118Sstever@eecs.umich.edu    shared_partial_flags = ['-r', '-nostdlib']
3603118Sstever@eecs.umich.edu    main.Append(PSHLINKFLAGS=shared_partial_flags)
3613118Sstever@eecs.umich.edu    main.Append(PLINKFLAGS=shared_partial_flags)
3623118Sstever@eecs.umich.eduelse:
3633118Sstever@eecs.umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
3643483Ssaidi@eecs.umich.edu    print "Don't know what compiler options to use for your compiler."
3653494Ssaidi@eecs.umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
3663494Ssaidi@eecs.umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
3673483Ssaidi@eecs.umich.edu    if not CXX_version:
3683483Ssaidi@eecs.umich.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
3693483Ssaidi@eecs.umich.edu               termcap.Normal
3703053Sstever@eecs.umich.edu    else:
3713053Sstever@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
3723918Ssaidi@eecs.umich.edu    print "       If you're trying to use a compiler other than GCC"
3733053Sstever@eecs.umich.edu    print "       or clang, there appears to be something wrong with your"
3743053Sstever@eecs.umich.edu    print "       environment."
3753053Sstever@eecs.umich.edu    print "       "
3763053Sstever@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
3773053Sstever@eecs.umich.edu    print "       above you will need to ease fix SConstruct and "
3781858SN/A    print "       src/SConscript to support that compiler."
3791858SN/A    Exit(1)
3801858SN/A
3811858SN/Aif main['GCC']:
3821858SN/A    # Check for a supported version of gcc. >= 4.8 is chosen for its
3831858SN/A    # level of c++11 support. See
3841859SN/A    # http://gcc.gnu.org/projects/cxx0x.html for details.
3851858SN/A    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
3861858SN/A    if compareVersions(gcc_version, "4.8") < 0:
3871858SN/A        print 'Error: gcc version 4.8 or newer required.'
3881859SN/A        print '       Installed version:', gcc_version
3891859SN/A        Exit(1)
3901862SN/A
3913053Sstever@eecs.umich.edu    main['GCC_VERSION'] = gcc_version
3923053Sstever@eecs.umich.edu
3933053Sstever@eecs.umich.edu    if compareVersions(gcc_version, '4.9') >= 0:
3943053Sstever@eecs.umich.edu        # Incremental linking with LTO is currently broken in gcc versions
3951859SN/A        # 4.9 and above. A version where everything works completely hasn't
3961859SN/A        # yet been identified.
3971859SN/A        #
3981859SN/A        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
3991859SN/A        main['BROKEN_INCREMENTAL_LTO'] = True
4001859SN/A    if compareVersions(gcc_version, '6.0') >= 0:
4011859SN/A        # gcc versions 6.0 and greater accept an -flinker-output flag which
4021859SN/A        # selects what type of output the linker should generate. This is
4031862SN/A        # necessary for incremental lto to work, but is also broken in
4041859SN/A        # current versions of gcc. It may not be necessary in future
4051859SN/A        # versions. We add it here since it might be, and as a reminder that
4061859SN/A        # it exists. It's excluded if lto is being forced.
4071858SN/A        #
4081858SN/A        # https://gcc.gnu.org/gcc-6/changes.html
4092139SN/A        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
4104202Sbinkertn@umich.edu        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
4114202Sbinkertn@umich.edu        if not GetOption('force_lto'):
4122139SN/A            main.Append(PSHLINKFLAGS='-flinker-output=rel')
4132155SN/A            main.Append(PLINKFLAGS='-flinker-output=rel')
4144202Sbinkertn@umich.edu
4154202Sbinkertn@umich.edu    # gcc from version 4.8 and above generates "rep; ret" instructions
4164202Sbinkertn@umich.edu    # to avoid performance penalties on certain AMD chips. Older
4172155SN/A    # assemblers detect this as an error, "Error: expecting string
4181869SN/A    # instruction after `rep'"
4191869SN/A    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
4201869SN/A                                  '-o', '/dev/null'],
4211869SN/A                                 exception=False).split()
4224202Sbinkertn@umich.edu
4234202Sbinkertn@umich.edu    # version strings may contain extra distro-specific
4244202Sbinkertn@umich.edu    # qualifiers, so play it safe and keep only what comes before
4254202Sbinkertn@umich.edu    # the first hyphen
4264202Sbinkertn@umich.edu    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
4274202Sbinkertn@umich.edu
4284202Sbinkertn@umich.edu    if not as_version or compareVersions(as_version, "2.23") < 0:
4294202Sbinkertn@umich.edu        print termcap.Yellow + termcap.Bold + \
4304202Sbinkertn@umich.edu            'Warning: This combination of gcc and binutils have' + \
4314202Sbinkertn@umich.edu            ' known incompatibilities.\n' + \
4324202Sbinkertn@umich.edu            '         If you encounter build problems, please update ' + \
4334202Sbinkertn@umich.edu            'binutils to 2.23.' + \
4344202Sbinkertn@umich.edu            termcap.Normal
4354202Sbinkertn@umich.edu
4364202Sbinkertn@umich.edu    # Make sure we warn if the user has requested to compile with the
4374202Sbinkertn@umich.edu    # Undefined Benahvior Sanitizer and this version of gcc does not
4384773Snate@binkert.org    # support it.
4394773Snate@binkert.org    if GetOption('with_ubsan') and \
4404773Snate@binkert.org            compareVersions(gcc_version, '4.9') < 0:
4414773Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
4424773Snate@binkert.org            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
4434773Snate@binkert.org            termcap.Normal
4444773Snate@binkert.org
4451869SN/A    disable_lto = GetOption('no_lto')
4464202Sbinkertn@umich.edu    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
4471869SN/A            not GetOption('force_lto'):
4482508SN/A        print termcap.Yellow + termcap.Bold + \
4492508SN/A            'Warning: Your compiler doesn\'t support incremental linking' + \
4502508SN/A            ' and lto at the same time, so lto is being disabled. To force' + \
4512508SN/A            ' lto on anyway, use the --force-lto option. That will disable' + \
4524202Sbinkertn@umich.edu            ' partial linking.' + \
4531869SN/A            termcap.Normal
4541869SN/A        disable_lto = True
4551869SN/A
4561869SN/A    # Add the appropriate Link-Time Optimization (LTO) flags
4571869SN/A    # unless LTO is explicitly turned off. Note that these flags
4581869SN/A    # are only used by the fast target.
4591965SN/A    if not disable_lto:
4601965SN/A        # Pass the LTO flag when compiling to produce GIMPLE
4611965SN/A        # output, we merely create the flags here and only append
4621869SN/A        # them later
4631869SN/A        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4642733Sktlim@umich.edu
4651869SN/A        # Use the same amount of jobs for LTO as we are running
4661884SN/A        # scons with
4671884SN/A        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4683356Sbinkertn@umich.edu
4693356Sbinkertn@umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
4703356Sbinkertn@umich.edu                                  '-fno-builtin-realloc', '-fno-builtin-free'])
4714773Snate@binkert.org
4724773Snate@binkert.org    # add option to check for undeclared overrides
4734773Snate@binkert.org    if compareVersions(gcc_version, "5.0") > 0:
4741869SN/A        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
4751858SN/A
4761869SN/Aelif main['CLANG']:
4771869SN/A    # Check for a supported version of clang, >= 3.1 is needed to
4781869SN/A    # support similar features as gcc 4.8. See
4791858SN/A    # http://clang.llvm.org/cxx_status.html for details
4802761Sstever@eecs.umich.edu    clang_version_re = re.compile(".* version (\d+\.\d+)")
4811869SN/A    clang_version_match = clang_version_re.search(CXX_version)
4822733Sktlim@umich.edu    if (clang_version_match):
4833584Ssaidi@eecs.umich.edu        clang_version = clang_version_match.groups()[0]
4841869SN/A        if compareVersions(clang_version, "3.1") < 0:
4851869SN/A            print 'Error: clang version 3.1 or newer required.'
4861869SN/A            print '       Installed version:', clang_version
4871869SN/A            Exit(1)
4881869SN/A    else:
4891869SN/A        print 'Error: Unable to determine clang version.'
4901858SN/A        Exit(1)
491955SN/A
492955SN/A    # clang has a few additional warnings that we disable, extraneous
4931869SN/A    # parantheses are allowed due to Ruby's printing of the AST,
4941869SN/A    # finally self assignments are allowed as the generated CPU code
4951869SN/A    # is relying on this
4961869SN/A    main.Append(CCFLAGS=['-Wno-parentheses',
4971869SN/A                         '-Wno-self-assign',
4981869SN/A                         # Some versions of libstdc++ (4.8?) seem to
4991869SN/A                         # use struct hash and class hash
5001869SN/A                         # interchangeably.
5011869SN/A                         '-Wno-mismatched-tags',
5021869SN/A                         ])
5031869SN/A
5041869SN/A    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
5051869SN/A
5061869SN/A    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
5071869SN/A    # opposed to libstdc++, as the later is dated.
5081869SN/A    if sys.platform == "darwin":
5091869SN/A        main.Append(CXXFLAGS=['-stdlib=libc++'])
5101869SN/A        main.Append(LIBS=['c++'])
5111869SN/A
5121869SN/A    # On FreeBSD we need libthr.
5131869SN/A    if sys.platform.startswith('freebsd'):
5141869SN/A        main.Append(LIBS=['thr'])
5151869SN/A
5161869SN/Aelse:
5171869SN/A    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5181869SN/A    print "Don't know what compiler options to use for your compiler."
5191869SN/A    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5201869SN/A    print termcap.Yellow + '       version:' + termcap.Normal,
5211869SN/A    if not CXX_version:
5223716Sstever@eecs.umich.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5233356Sbinkertn@umich.edu               termcap.Normal
5243356Sbinkertn@umich.edu    else:
5253356Sbinkertn@umich.edu        print CXX_version.replace('\n', '<nl>')
5263356Sbinkertn@umich.edu    print "       If you're trying to use a compiler other than GCC"
5273356Sbinkertn@umich.edu    print "       or clang, there appears to be something wrong with your"
5283356Sbinkertn@umich.edu    print "       environment."
5293356Sbinkertn@umich.edu    print "       "
5301869SN/A    print "       If you are trying to use a compiler other than those listed"
5311869SN/A    print "       above you will need to ease fix SConstruct and "
5321869SN/A    print "       src/SConscript to support that compiler."
5331869SN/A    Exit(1)
5341869SN/A
5351869SN/A# Set up common yacc/bison flags (needed for Ruby)
5361869SN/Amain['YACCFLAGS'] = '-d'
5372655Sstever@eecs.umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
5382655Sstever@eecs.umich.edu
5392655Sstever@eecs.umich.edu# Do this after we save setting back, or else we'll tack on an
5402655Sstever@eecs.umich.edu# extra 'qdo' every time we run scons.
5412655Sstever@eecs.umich.eduif main['BATCH']:
5422655Sstever@eecs.umich.edu    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
5432655Sstever@eecs.umich.edu    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
5442655Sstever@eecs.umich.edu    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
5452655Sstever@eecs.umich.edu    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
5462655Sstever@eecs.umich.edu    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
5472655Sstever@eecs.umich.edu
5482655Sstever@eecs.umich.eduif sys.platform == 'cygwin':
5492655Sstever@eecs.umich.edu    # cygwin has some header file issues...
5502655Sstever@eecs.umich.edu    main.Append(CCFLAGS=["-Wno-uninitialized"])
5512655Sstever@eecs.umich.edu
5522655Sstever@eecs.umich.edu# Check for the protobuf compiler
5532655Sstever@eecs.umich.eduprotoc_version = readCommand([main['PROTOC'], '--version'],
5542655Sstever@eecs.umich.edu                             exception='').split()
5552655Sstever@eecs.umich.edu
5562655Sstever@eecs.umich.edu# First two words should be "libprotoc x.y.z"
5572655Sstever@eecs.umich.eduif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
5582655Sstever@eecs.umich.edu    print termcap.Yellow + termcap.Bold + \
5592655Sstever@eecs.umich.edu        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
5602655Sstever@eecs.umich.edu        '         Please install protobuf-compiler for tracing support.' + \
5612655Sstever@eecs.umich.edu        termcap.Normal
5622655Sstever@eecs.umich.edu    main['PROTOC'] = False
5632634Sstever@eecs.umich.eduelse:
5642634Sstever@eecs.umich.edu    # Based on the availability of the compress stream wrappers,
5652634Sstever@eecs.umich.edu    # require 2.1.0
5662634Sstever@eecs.umich.edu    min_protoc_version = '2.1.0'
5672634Sstever@eecs.umich.edu    if compareVersions(protoc_version[1], min_protoc_version) < 0:
5682634Sstever@eecs.umich.edu        print termcap.Yellow + termcap.Bold + \
5692638Sstever@eecs.umich.edu            'Warning: protoc version', min_protoc_version, \
5702638Sstever@eecs.umich.edu            'or newer required.\n' + \
5713716Sstever@eecs.umich.edu            '         Installed version:', protoc_version[1], \
5722638Sstever@eecs.umich.edu            termcap.Normal
5732638Sstever@eecs.umich.edu        main['PROTOC'] = False
5741869SN/A    else:
5751869SN/A        # Attempt to determine the appropriate include path and
5763546Sgblack@eecs.umich.edu        # library path using pkg-config, that means we also need to
5773546Sgblack@eecs.umich.edu        # check for pkg-config. Note that it is possible to use
5783546Sgblack@eecs.umich.edu        # protobuf without the involvement of pkg-config. Later on we
5793546Sgblack@eecs.umich.edu        # check go a library config check and at that point the test
5804202Sbinkertn@umich.edu        # will fail if libprotobuf cannot be found.
5813546Sgblack@eecs.umich.edu        if readCommand(['pkg-config', '--version'], exception=''):
5823546Sgblack@eecs.umich.edu            try:
5833546Sgblack@eecs.umich.edu                # Attempt to establish what linking flags to add for protobuf
5843546Sgblack@eecs.umich.edu                # using pkg-config
5853546Sgblack@eecs.umich.edu                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
5863546Sgblack@eecs.umich.edu            except:
5873546Sgblack@eecs.umich.edu                print termcap.Yellow + termcap.Bold + \
5883546Sgblack@eecs.umich.edu                    'Warning: pkg-config could not get protobuf flags.' + \
5893546Sgblack@eecs.umich.edu                    termcap.Normal
5903546Sgblack@eecs.umich.edu
5914202Sbinkertn@umich.edu
5923546Sgblack@eecs.umich.edu# Check for 'timeout' from GNU coreutils. If present, regressions will
5933546Sgblack@eecs.umich.edu# be run with a time limit. We require version 8.13 since we rely on
5943546Sgblack@eecs.umich.edu# support for the '--foreground' option.
5953546Sgblack@eecs.umich.eduif sys.platform.startswith('freebsd'):
5963546Sgblack@eecs.umich.edu    timeout_lines = readCommand(['gtimeout', '--version'],
5973546Sgblack@eecs.umich.edu                                exception='').splitlines()
5983546Sgblack@eecs.umich.eduelse:
5993546Sgblack@eecs.umich.edu    timeout_lines = readCommand(['timeout', '--version'],
6003546Sgblack@eecs.umich.edu                                exception='').splitlines()
6013546Sgblack@eecs.umich.edu# Get the first line and tokenize it
6023546Sgblack@eecs.umich.edutimeout_version = timeout_lines[0].split() if timeout_lines else []
6033546Sgblack@eecs.umich.edumain['TIMEOUT'] =  timeout_version and \
6043546Sgblack@eecs.umich.edu    compareVersions(timeout_version[-1], '8.13') >= 0
6053546Sgblack@eecs.umich.edu
6063546Sgblack@eecs.umich.edu# Add a custom Check function to test for structure members.
6073546Sgblack@eecs.umich.edudef CheckMember(context, include, decl, member, include_quotes="<>"):
6083546Sgblack@eecs.umich.edu    context.Message("Checking for member %s in %s..." %
6093546Sgblack@eecs.umich.edu                    (member, decl))
6103546Sgblack@eecs.umich.edu    text = """
6113546Sgblack@eecs.umich.edu#include %(header)s
6124202Sbinkertn@umich.eduint main(){
6133546Sgblack@eecs.umich.edu  %(decl)s test;
6143546Sgblack@eecs.umich.edu  (void)test.%(member)s;
6153546Sgblack@eecs.umich.edu  return 0;
616955SN/A};
617955SN/A""" % { "header" : include_quotes[0] + include + include_quotes[1],
618955SN/A        "decl" : decl,
619955SN/A        "member" : member,
6201858SN/A        }
6211858SN/A
6221858SN/A    ret = context.TryCompile(text, extension=".cc")
6232632Sstever@eecs.umich.edu    context.Result(ret)
6242632Sstever@eecs.umich.edu    return ret
6254773Snate@binkert.org
6264773Snate@binkert.org# Platform-specific configuration.  Note again that we assume that all
6272632Sstever@eecs.umich.edu# builds under a given build root run on the same host platform.
6282632Sstever@eecs.umich.educonf = Configure(main,
6292632Sstever@eecs.umich.edu                 conf_dir = joinpath(build_root, '.scons_config'),
6302634Sstever@eecs.umich.edu                 log_file = joinpath(build_root, 'scons_config.log'),
6312638Sstever@eecs.umich.edu                 custom_tests = {
6322023SN/A        'CheckMember' : CheckMember,
6332632Sstever@eecs.umich.edu        })
6342632Sstever@eecs.umich.edu
6352632Sstever@eecs.umich.edu# Check if we should compile a 64 bit binary on Mac OS X/Darwin
6362632Sstever@eecs.umich.edutry:
6372632Sstever@eecs.umich.edu    import platform
6383716Sstever@eecs.umich.edu    uname = platform.uname()
6392632Sstever@eecs.umich.edu    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
6402632Sstever@eecs.umich.edu        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
6412632Sstever@eecs.umich.edu            main.Append(CCFLAGS=['-arch', 'x86_64'])
6422632Sstever@eecs.umich.edu            main.Append(CFLAGS=['-arch', 'x86_64'])
6432632Sstever@eecs.umich.edu            main.Append(LINKFLAGS=['-arch', 'x86_64'])
6442023SN/A            main.Append(ASFLAGS=['-arch', 'x86_64'])
6452632Sstever@eecs.umich.eduexcept:
6462632Sstever@eecs.umich.edu    pass
6471889SN/A
6481889SN/A# Recent versions of scons substitute a "Null" object for Configure()
6492632Sstever@eecs.umich.edu# when configuration isn't necessary, e.g., if the "--help" option is
6502632Sstever@eecs.umich.edu# present.  Unfortuantely this Null object always returns false,
6512632Sstever@eecs.umich.edu# breaking all our configuration checks.  We replace it with our own
6522632Sstever@eecs.umich.edu# more optimistic null object that returns True instead.
6533716Sstever@eecs.umich.eduif not conf:
6543716Sstever@eecs.umich.edu    def NullCheck(*args, **kwargs):
6552632Sstever@eecs.umich.edu        return True
6562632Sstever@eecs.umich.edu
6572632Sstever@eecs.umich.edu    class NullConf:
6582632Sstever@eecs.umich.edu        def __init__(self, env):
6592632Sstever@eecs.umich.edu            self.env = env
6602632Sstever@eecs.umich.edu        def Finish(self):
6612632Sstever@eecs.umich.edu            return self.env
6622632Sstever@eecs.umich.edu        def __getattr__(self, mname):
6631888SN/A            return NullCheck
6641888SN/A
6651869SN/A    conf = NullConf(main)
6661869SN/A
6671858SN/A# Cache build files in the supplied directory.
6682598SN/Aif main['M5_BUILD_CACHE']:
6692598SN/A    print 'Using build cache located at', main['M5_BUILD_CACHE']
6702598SN/A    CacheDir(main['M5_BUILD_CACHE'])
6712598SN/A
6722598SN/Amain['USE_PYTHON'] = not GetOption('without_python')
6731858SN/Aif main['USE_PYTHON']:
6741858SN/A    # Find Python include and library directories for embedding the
6751858SN/A    # interpreter. We rely on python-config to resolve the appropriate
6761858SN/A    # includes and linker flags. ParseConfig does not seem to understand
6771858SN/A    # the more exotic linker flags such as -Xlinker and -export-dynamic so
6781858SN/A    # we add them explicitly below. If you want to link in an alternate
6791858SN/A    # version of python, see above for instructions on how to invoke
6801858SN/A    # scons with the appropriate PATH set.
6811858SN/A    #
6821871SN/A    # First we check if python2-config exists, else we use python-config
6831858SN/A    python_config = readCommand(['which', 'python2-config'],
6841858SN/A                                exception='').strip()
6851858SN/A    if not os.path.exists(python_config):
6861858SN/A        python_config = readCommand(['which', 'python-config'],
6871858SN/A                                    exception='').strip()
6881858SN/A    py_includes = readCommand([python_config, '--includes'],
6891858SN/A                              exception='').split()
6901858SN/A    # Strip the -I from the include folders before adding them to the
6911858SN/A    # CPPPATH
6921858SN/A    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
6931858SN/A
6941859SN/A    # Read the linker flags and split them into libraries and other link
6951859SN/A    # flags. The libraries are added later through the call the CheckLib.
6961869SN/A    py_ld_flags = readCommand([python_config, '--ldflags'],
6971888SN/A        exception='').split()
6982632Sstever@eecs.umich.edu    py_libs = []
6991869SN/A    for lib in py_ld_flags:
7001884SN/A         if not lib.startswith('-l'):
7011884SN/A             main.Append(LINKFLAGS=[lib])
7021884SN/A         else:
7031884SN/A             lib = lib[2:]
7041884SN/A             if lib not in py_libs:
7051884SN/A                 py_libs.append(lib)
7061965SN/A
7071965SN/A    # verify that this stuff works
7081965SN/A    if not conf.CheckHeader('Python.h', '<>'):
7092761Sstever@eecs.umich.edu        print "Error: can't find Python.h header in", py_includes
7101869SN/A        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
7111869SN/A        Exit(1)
7122632Sstever@eecs.umich.edu
7132667Sstever@eecs.umich.edu    for lib in py_libs:
7141869SN/A        if not conf.CheckLib(lib):
7151869SN/A            print "Error: can't find library %s required by python" % lib
7162929Sktlim@umich.edu            Exit(1)
7172929Sktlim@umich.edu
7183716Sstever@eecs.umich.edu# On Solaris you need to use libsocket for socket ops
7192929Sktlim@umich.eduif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
720955SN/A   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7212598SN/A       print "Can't find library with socket calls (e.g. accept())"
7222598SN/A       Exit(1)
7233546Sgblack@eecs.umich.edu
724955SN/A# Check for zlib.  If the check passes, libz will be automatically
725955SN/A# added to the LIBS environment variable.
726955SN/Aif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
7271530SN/A    print 'Error: did not find needed zlib compression library '\
728955SN/A          'and/or zlib.h header file.'
729955SN/A    print '       Please install zlib and try again.'
730955SN/A    Exit(1)
731
732# If we have the protobuf compiler, also make sure we have the
733# development libraries. If the check passes, libprotobuf will be
734# automatically added to the LIBS environment variable. After
735# this, we can use the HAVE_PROTOBUF flag to determine if we have
736# got both protoc and libprotobuf available.
737main['HAVE_PROTOBUF'] = main['PROTOC'] and \
738    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
739                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
740
741# If we have the compiler but not the library, print another warning.
742if main['PROTOC'] and not main['HAVE_PROTOBUF']:
743    print termcap.Yellow + termcap.Bold + \
744        'Warning: did not find protocol buffer library and/or headers.\n' + \
745    '       Please install libprotobuf-dev for tracing support.' + \
746    termcap.Normal
747
748# Check for librt.
749have_posix_clock = \
750    conf.CheckLibWithHeader(None, 'time.h', 'C',
751                            'clock_nanosleep(0,0,NULL,NULL);') or \
752    conf.CheckLibWithHeader('rt', 'time.h', 'C',
753                            'clock_nanosleep(0,0,NULL,NULL);')
754
755have_posix_timers = \
756    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
757                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
758
759if not GetOption('without_tcmalloc'):
760    if conf.CheckLib('tcmalloc'):
761        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
762    elif conf.CheckLib('tcmalloc_minimal'):
763        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
764    else:
765        print termcap.Yellow + termcap.Bold + \
766              "You can get a 12% performance improvement by "\
767              "installing tcmalloc (libgoogle-perftools-dev package "\
768              "on Ubuntu or RedHat)." + termcap.Normal
769
770
771# Detect back trace implementations. The last implementation in the
772# list will be used by default.
773backtrace_impls = [ "none" ]
774
775if conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
776                           'backtrace_symbols_fd((void*)0, 0, 0);'):
777    backtrace_impls.append("glibc")
778elif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
779                           'backtrace_symbols_fd((void*)0, 0, 0);'):
780    # NetBSD and FreeBSD need libexecinfo.
781    backtrace_impls.append("glibc")
782    main.Append(LIBS=['execinfo'])
783
784if backtrace_impls[-1] == "none":
785    default_backtrace_impl = "none"
786    print termcap.Yellow + termcap.Bold + \
787        "No suitable back trace implementation found." + \
788        termcap.Normal
789
790if not have_posix_clock:
791    print "Can't find library for POSIX clocks."
792
793# Check for <fenv.h> (C99 FP environment control)
794have_fenv = conf.CheckHeader('fenv.h', '<>')
795if not have_fenv:
796    print "Warning: Header file <fenv.h> not found."
797    print "         This host has no IEEE FP rounding mode control."
798
799# Check for <png.h> (libpng library needed if wanting to dump
800# frame buffer image in png format)
801have_png = conf.CheckHeader('png.h', '<>')
802if not have_png:
803    print "Warning: Header file <png.h> not found."
804    print "         This host has no libpng library."
805    print "         Disabling support for PNG framebuffers."
806
807# Check if we should enable KVM-based hardware virtualization. The API
808# we rely on exists since version 2.6.36 of the kernel, but somehow
809# the KVM_API_VERSION does not reflect the change. We test for one of
810# the types as a fall back.
811have_kvm = conf.CheckHeader('linux/kvm.h', '<>')
812if not have_kvm:
813    print "Info: Compatible header file <linux/kvm.h> not found, " \
814        "disabling KVM support."
815
816# Check if the TUN/TAP driver is available.
817have_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
818if not have_tuntap:
819    print "Info: Compatible header file <linux/if_tun.h> not found."
820
821# x86 needs support for xsave. We test for the structure here since we
822# won't be able to run new tests by the time we know which ISA we're
823# targeting.
824have_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
825                                    '#include <linux/kvm.h>') != 0
826
827# Check if the requested target ISA is compatible with the host
828def is_isa_kvm_compatible(isa):
829    try:
830        import platform
831        host_isa = platform.machine()
832    except:
833        print "Warning: Failed to determine host ISA."
834        return False
835
836    if not have_posix_timers:
837        print "Warning: Can not enable KVM, host seems to lack support " \
838            "for POSIX timers"
839        return False
840
841    if isa == "arm":
842        return host_isa in ( "armv7l", "aarch64" )
843    elif isa == "x86":
844        if host_isa != "x86_64":
845            return False
846
847        if not have_kvm_xsave:
848            print "KVM on x86 requires xsave support in kernel headers."
849            return False
850
851        return True
852    else:
853        return False
854
855
856# Check if the exclude_host attribute is available. We want this to
857# get accurate instruction counts in KVM.
858main['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
859    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
860
861
862######################################################################
863#
864# Finish the configuration
865#
866main = conf.Finish()
867
868######################################################################
869#
870# Collect all non-global variables
871#
872
873# Define the universe of supported ISAs
874all_isa_list = [ ]
875all_gpu_isa_list = [ ]
876Export('all_isa_list')
877Export('all_gpu_isa_list')
878
879class CpuModel(object):
880    '''The CpuModel class encapsulates everything the ISA parser needs to
881    know about a particular CPU model.'''
882
883    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
884    dict = {}
885
886    # Constructor.  Automatically adds models to CpuModel.dict.
887    def __init__(self, name, default=False):
888        self.name = name           # name of model
889
890        # This cpu is enabled by default
891        self.default = default
892
893        # Add self to dict
894        if name in CpuModel.dict:
895            raise AttributeError, "CpuModel '%s' already registered" % name
896        CpuModel.dict[name] = self
897
898Export('CpuModel')
899
900# Sticky variables get saved in the variables file so they persist from
901# one invocation to the next (unless overridden, in which case the new
902# value becomes sticky).
903sticky_vars = Variables(args=ARGUMENTS)
904Export('sticky_vars')
905
906# Sticky variables that should be exported
907export_vars = []
908Export('export_vars')
909
910# For Ruby
911all_protocols = []
912Export('all_protocols')
913protocol_dirs = []
914Export('protocol_dirs')
915slicc_includes = []
916Export('slicc_includes')
917
918# Walk the tree and execute all SConsopts scripts that wil add to the
919# above variables
920if GetOption('verbose'):
921    print "Reading SConsopts"
922for bdir in [ base_dir ] + extras_dir_list:
923    if not isdir(bdir):
924        print "Error: directory '%s' does not exist" % bdir
925        Exit(1)
926    for root, dirs, files in os.walk(bdir):
927        if 'SConsopts' in files:
928            if GetOption('verbose'):
929                print "Reading", joinpath(root, 'SConsopts')
930            SConscript(joinpath(root, 'SConsopts'))
931
932all_isa_list.sort()
933all_gpu_isa_list.sort()
934
935sticky_vars.AddVariables(
936    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
937    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
938    ListVariable('CPU_MODELS', 'CPU models',
939                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
940                 sorted(CpuModel.dict.keys())),
941    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
942                 False),
943    BoolVariable('SS_COMPATIBLE_FP',
944                 'Make floating-point results compatible with SimpleScalar',
945                 False),
946    BoolVariable('USE_SSE2',
947                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
948                 False),
949    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
950    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
951    BoolVariable('USE_PNG',  'Enable support for PNG images', have_png),
952    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability',
953                 False),
954    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models',
955                 have_kvm),
956    BoolVariable('USE_TUNTAP',
957                 'Enable using a tap device to bridge to the host network',
958                 have_tuntap),
959    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
960    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
961                  all_protocols),
962    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
963                 backtrace_impls[-1], backtrace_impls)
964    )
965
966# These variables get exported to #defines in config/*.hh (see src/SConscript).
967export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
968                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
969                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST',
970                'USE_PNG']
971
972###################################################
973#
974# Define a SCons builder for configuration flag headers.
975#
976###################################################
977
978# This function generates a config header file that #defines the
979# variable symbol to the current variable setting (0 or 1).  The source
980# operands are the name of the variable and a Value node containing the
981# value of the variable.
982def build_config_file(target, source, env):
983    (variable, value) = [s.get_contents() for s in source]
984    f = file(str(target[0]), 'w')
985    print >> f, '#define', variable, value
986    f.close()
987    return None
988
989# Combine the two functions into a scons Action object.
990config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
991
992# The emitter munges the source & target node lists to reflect what
993# we're really doing.
994def config_emitter(target, source, env):
995    # extract variable name from Builder arg
996    variable = str(target[0])
997    # True target is config header file
998    target = joinpath('config', variable.lower() + '.hh')
999    val = env[variable]
1000    if isinstance(val, bool):
1001        # Force value to 0/1
1002        val = int(val)
1003    elif isinstance(val, str):
1004        val = '"' + val + '"'
1005
1006    # Sources are variable name & value (packaged in SCons Value nodes)
1007    return ([target], [Value(variable), Value(val)])
1008
1009config_builder = Builder(emitter = config_emitter, action = config_action)
1010
1011main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1012
1013###################################################
1014#
1015# Builders for static and shared partially linked object files.
1016#
1017###################################################
1018
1019partial_static_builder = Builder(action=SCons.Defaults.LinkAction,
1020                                 src_suffix='$OBJSUFFIX',
1021                                 src_builder=['StaticObject', 'Object'],
1022                                 LINKFLAGS='$PLINKFLAGS',
1023                                 LIBS='')
1024
1025def partial_shared_emitter(target, source, env):
1026    for tgt in target:
1027        tgt.attributes.shared = 1
1028    return (target, source)
1029partial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
1030                                 emitter=partial_shared_emitter,
1031                                 src_suffix='$SHOBJSUFFIX',
1032                                 src_builder='SharedObject',
1033                                 SHLINKFLAGS='$PSHLINKFLAGS',
1034                                 LIBS='')
1035
1036main.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
1037                         'PartialStatic' : partial_static_builder })
1038
1039# builds in ext are shared across all configs in the build root.
1040ext_dir = abspath(joinpath(str(main.root), 'ext'))
1041ext_build_dirs = []
1042for root, dirs, files in os.walk(ext_dir):
1043    if 'SConscript' in files:
1044        build_dir = os.path.relpath(root, ext_dir)
1045        ext_build_dirs.append(build_dir)
1046        main.SConscript(joinpath(root, 'SConscript'),
1047                        variant_dir=joinpath(build_root, build_dir))
1048
1049main.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
1050
1051###################################################
1052#
1053# This builder and wrapper method are used to set up a directory with
1054# switching headers. Those are headers which are in a generic location and
1055# that include more specific headers from a directory chosen at build time
1056# based on the current build settings.
1057#
1058###################################################
1059
1060def build_switching_header(target, source, env):
1061    path = str(target[0])
1062    subdir = str(source[0])
1063    dp, fp = os.path.split(path)
1064    dp = os.path.relpath(os.path.realpath(dp),
1065                         os.path.realpath(env['BUILDDIR']))
1066    with open(path, 'w') as hdr:
1067        print >>hdr, '#include "%s/%s/%s"' % (dp, subdir, fp)
1068
1069switching_header_action = MakeAction(build_switching_header,
1070                                     Transform('GENERATE'))
1071
1072switching_header_builder = Builder(action=switching_header_action,
1073                                   source_factory=Value,
1074                                   single_source=True)
1075
1076main.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
1077
1078def switching_headers(self, headers, source):
1079    for header in headers:
1080        self.SwitchingHeader(header, source)
1081
1082main.AddMethod(switching_headers, 'SwitchingHeaders')
1083
1084###################################################
1085#
1086# Define build environments for selected configurations.
1087#
1088###################################################
1089
1090for variant_path in variant_paths:
1091    if not GetOption('silent'):
1092        print "Building in", variant_path
1093
1094    # Make a copy of the build-root environment to use for this config.
1095    env = main.Clone()
1096    env['BUILDDIR'] = variant_path
1097
1098    # variant_dir is the tail component of build path, and is used to
1099    # determine the build parameters (e.g., 'ALPHA_SE')
1100    (build_root, variant_dir) = splitpath(variant_path)
1101
1102    # Set env variables according to the build directory config.
1103    sticky_vars.files = []
1104    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1105    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1106    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1107    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1108    if isfile(current_vars_file):
1109        sticky_vars.files.append(current_vars_file)
1110        if not GetOption('silent'):
1111            print "Using saved variables file %s" % current_vars_file
1112    elif variant_dir in ext_build_dirs:
1113        # Things in ext are built without a variant directory.
1114        continue
1115    else:
1116        # Build dir-specific variables file doesn't exist.
1117
1118        # Make sure the directory is there so we can create it later
1119        opt_dir = dirname(current_vars_file)
1120        if not isdir(opt_dir):
1121            mkdir(opt_dir)
1122
1123        # Get default build variables from source tree.  Variables are
1124        # normally determined by name of $VARIANT_DIR, but can be
1125        # overridden by '--default=' arg on command line.
1126        default = GetOption('default')
1127        opts_dir = joinpath(main.root.abspath, 'build_opts')
1128        if default:
1129            default_vars_files = [joinpath(build_root, 'variables', default),
1130                                  joinpath(opts_dir, default)]
1131        else:
1132            default_vars_files = [joinpath(opts_dir, variant_dir)]
1133        existing_files = filter(isfile, default_vars_files)
1134        if existing_files:
1135            default_vars_file = existing_files[0]
1136            sticky_vars.files.append(default_vars_file)
1137            print "Variables file %s not found,\n  using defaults in %s" \
1138                  % (current_vars_file, default_vars_file)
1139        else:
1140            print "Error: cannot find variables file %s or " \
1141                  "default file(s) %s" \
1142                  % (current_vars_file, ' or '.join(default_vars_files))
1143            Exit(1)
1144
1145    # Apply current variable settings to env
1146    sticky_vars.Update(env)
1147
1148    help_texts["local_vars"] += \
1149        "Build variables for %s:\n" % variant_dir \
1150                 + sticky_vars.GenerateHelpText(env)
1151
1152    # Process variable settings.
1153
1154    if not have_fenv and env['USE_FENV']:
1155        print "Warning: <fenv.h> not available; " \
1156              "forcing USE_FENV to False in", variant_dir + "."
1157        env['USE_FENV'] = False
1158
1159    if not env['USE_FENV']:
1160        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1161        print "         FP results may deviate slightly from other platforms."
1162
1163    if not have_png and env['USE_PNG']:
1164        print "Warning: <png.h> not available; " \
1165              "forcing USE_PNG to False in", variant_dir + "."
1166        env['USE_PNG'] = False
1167
1168    if env['USE_PNG']:
1169        env.Append(LIBS=['png'])
1170
1171    if env['EFENCE']:
1172        env.Append(LIBS=['efence'])
1173
1174    if env['USE_KVM']:
1175        if not have_kvm:
1176            print "Warning: Can not enable KVM, host seems to lack KVM support"
1177            env['USE_KVM'] = False
1178        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1179            print "Info: KVM support disabled due to unsupported host and " \
1180                "target ISA combination"
1181            env['USE_KVM'] = False
1182
1183    if env['USE_TUNTAP']:
1184        if not have_tuntap:
1185            print "Warning: Can't connect EtherTap with a tap device."
1186            env['USE_TUNTAP'] = False
1187
1188    if env['BUILD_GPU']:
1189        env.Append(CPPDEFINES=['BUILD_GPU'])
1190
1191    # Warn about missing optional functionality
1192    if env['USE_KVM']:
1193        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1194            print "Warning: perf_event headers lack support for the " \
1195                "exclude_host attribute. KVM instruction counts will " \
1196                "be inaccurate."
1197
1198    # Save sticky variable settings back to current variables file
1199    sticky_vars.Save(current_vars_file, env)
1200
1201    if env['USE_SSE2']:
1202        env.Append(CCFLAGS=['-msse2'])
1203
1204    # The src/SConscript file sets up the build rules in 'env' according
1205    # to the configured variables.  It returns a list of environments,
1206    # one for each variant build (debug, opt, etc.)
1207    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1208
1209# base help text
1210Help('''
1211Usage: scons [scons options] [build variables] [target(s)]
1212
1213Extra scons options:
1214%(options)s
1215
1216Global build variables:
1217%(global_vars)s
1218
1219%(local_vars)s
1220''' % help_texts)
1221