SConstruct revision 12563:8d59ed22ae79
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.edufrom __future__ import print_function
822653Sstever@eecs.umich.edu
832653Sstever@eecs.umich.edu# Global Python includes
842653Sstever@eecs.umich.eduimport itertools
852653Sstever@eecs.umich.eduimport os
862653Sstever@eecs.umich.eduimport re
872653Sstever@eecs.umich.eduimport shutil
882653Sstever@eecs.umich.eduimport subprocess
894781Snate@binkert.orgimport sys
901852SN/A
91955SN/Afrom os import mkdir, environ
92955SN/Afrom os.path import abspath, basename, dirname, expanduser, normpath
93955SN/Afrom os.path import exists,  isdir, isfile
943717Sstever@eecs.umich.edufrom os.path import join as joinpath, split as splitpath
953716Sstever@eecs.umich.edu
96955SN/A# SCons includes
971533SN/Aimport SCons
983716Sstever@eecs.umich.eduimport SCons.Node
991533SN/A
1004678Snate@binkert.orgfrom m5.util import compareVersions, readCommand
1014678Snate@binkert.org
1024678Snate@binkert.orghelp_texts = {
1034678Snate@binkert.org    "options" : "",
1044678Snate@binkert.org    "global_vars" : "",
1054678Snate@binkert.org    "local_vars" : ""
1064678Snate@binkert.org}
1074678Snate@binkert.org
1084678Snate@binkert.orgExport("help_texts")
1094678Snate@binkert.org
1104678Snate@binkert.org
1114678Snate@binkert.org# There's a bug in scons in that (1) by default, the help texts from
1124678Snate@binkert.org# AddOption() are supposed to be displayed when you type 'scons -h'
1134678Snate@binkert.org# and (2) you can override the help displayed by 'scons -h' using the
1144678Snate@binkert.org# Help() function, but these two features are incompatible: once
1154678Snate@binkert.org# you've overridden the help text using Help(), there's no way to get
1164678Snate@binkert.org# at the help texts from AddOptions.  See:
1174678Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1184678Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1194678Snate@binkert.org# This hack lets us extract the help text from AddOptions and
1204678Snate@binkert.org# re-inject it via Help().  Ideally someday this bug will be fixed and
1214678Snate@binkert.org# we can just use AddOption directly.
1224678Snate@binkert.orgdef AddLocalOption(*args, **kwargs):
1234678Snate@binkert.org    col_width = 30
1244678Snate@binkert.org
1254678Snate@binkert.org    help = "  " + ", ".join(args)
1264678Snate@binkert.org    if "help" in kwargs:
1274678Snate@binkert.org        length = len(help)
128955SN/A        if length >= col_width:
129955SN/A            help += "\n" + " " * col_width
1302632Sstever@eecs.umich.edu        else:
1312632Sstever@eecs.umich.edu            help += " " * (col_width - length)
132955SN/A        help += kwargs["help"]
133955SN/A    help_texts["options"] += help + "\n"
134955SN/A
135955SN/A    AddOption(*args, **kwargs)
1362632Sstever@eecs.umich.edu
137955SN/AAddLocalOption('--colors', dest='use_colors', action='store_true',
1382632Sstever@eecs.umich.edu               help="Add color to abbreviated scons output")
1392632Sstever@eecs.umich.eduAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1402632Sstever@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1412632Sstever@eecs.umich.eduAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1422632Sstever@eecs.umich.edu               action='store_true',
1432632Sstever@eecs.umich.edu               help="Build with support for C++-based configuration")
1442632Sstever@eecs.umich.eduAddLocalOption('--default', dest='default', type='string', action='store',
1453053Sstever@eecs.umich.edu               help='Override which build_opts file to use for defaults')
1463053Sstever@eecs.umich.eduAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1473053Sstever@eecs.umich.edu               help='Disable style checking hooks')
1483053Sstever@eecs.umich.eduAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1493053Sstever@eecs.umich.edu               help='Disable Link-Time Optimization for fast')
1503053Sstever@eecs.umich.eduAddLocalOption('--force-lto', dest='force_lto', action='store_true',
1513053Sstever@eecs.umich.edu               help='Use Link-Time Optimization instead of partial linking' +
1523053Sstever@eecs.umich.edu                    ' when the compiler doesn\'t support using them together.')
1533053Sstever@eecs.umich.eduAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1543053Sstever@eecs.umich.edu               help='Update test reference outputs')
1553053Sstever@eecs.umich.eduAddLocalOption('--verbose', dest='verbose', action='store_true',
1563053Sstever@eecs.umich.edu               help='Print full tool command lines')
1573053Sstever@eecs.umich.eduAddLocalOption('--without-python', dest='without_python',
1583053Sstever@eecs.umich.edu               action='store_true',
1593053Sstever@eecs.umich.edu               help='Build without Python configuration support')
1603053Sstever@eecs.umich.eduAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1612632Sstever@eecs.umich.edu               action='store_true',
1622632Sstever@eecs.umich.edu               help='Disable linking against tcmalloc')
1632632Sstever@eecs.umich.eduAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1642632Sstever@eecs.umich.edu               help='Build with Undefined Behavior Sanitizer if available')
1652632Sstever@eecs.umich.eduAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1662632Sstever@eecs.umich.edu               help='Build with Address Sanitizer if available')
1673718Sstever@eecs.umich.edu
1683718Sstever@eecs.umich.eduif GetOption('no_lto') and GetOption('force_lto'):
1693718Sstever@eecs.umich.edu    print('--no-lto and --force-lto are mutually exclusive')
1703718Sstever@eecs.umich.edu    Exit(1)
1713718Sstever@eecs.umich.edu
1723718Sstever@eecs.umich.edu########################################################################
1733718Sstever@eecs.umich.edu#
1743718Sstever@eecs.umich.edu# Set up the main build environment.
1753718Sstever@eecs.umich.edu#
1763718Sstever@eecs.umich.edu########################################################################
1773718Sstever@eecs.umich.edu
1783718Sstever@eecs.umich.edumain = Environment()
1793718Sstever@eecs.umich.edu
1802634Sstever@eecs.umich.edufrom gem5_scons import Transform
1812634Sstever@eecs.umich.edufrom gem5_scons.util import get_termcap
1822632Sstever@eecs.umich.edutermcap = get_termcap()
1832638Sstever@eecs.umich.edu
1842632Sstever@eecs.umich.edumain_dict_keys = main.Dictionary().keys()
1852632Sstever@eecs.umich.edu
1862632Sstever@eecs.umich.edu# Check that we have a C/C++ compiler
1872632Sstever@eecs.umich.eduif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
1882632Sstever@eecs.umich.edu    print("No C++ compiler installed (package g++ on Ubuntu and RedHat)")
1892632Sstever@eecs.umich.edu    Exit(1)
1901858SN/A
1913716Sstever@eecs.umich.edu###################################################
1922638Sstever@eecs.umich.edu#
1932638Sstever@eecs.umich.edu# Figure out which configurations to set up based on the path(s) of
1942638Sstever@eecs.umich.edu# the target(s).
1952638Sstever@eecs.umich.edu#
1962638Sstever@eecs.umich.edu###################################################
1972638Sstever@eecs.umich.edu
1982638Sstever@eecs.umich.edu# Find default configuration & binary.
1993716Sstever@eecs.umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
2002634Sstever@eecs.umich.edu
2012634Sstever@eecs.umich.edu# helper function: find last occurrence of element in list
202955SN/Adef rfind(l, elt, offs = -1):
203955SN/A    for i in range(len(l)+offs, 0, -1):
204955SN/A        if l[i] == elt:
205955SN/A            return i
206955SN/A    raise ValueError, "element not found"
207955SN/A
208955SN/A# Take a list of paths (or SCons Nodes) and return a list with all
209955SN/A# paths made absolute and ~-expanded.  Paths will be interpreted
2101858SN/A# relative to the launch directory unless a different root is provided
2111858SN/Adef makePathListAbsolute(path_list, root=GetLaunchDir()):
2122632Sstever@eecs.umich.edu    return [abspath(joinpath(root, expanduser(str(p))))
213955SN/A            for p in path_list]
2144781Snate@binkert.org
2153643Ssaidi@eecs.umich.edu# Each target must have 'build' in the interior of the path; the
2163643Ssaidi@eecs.umich.edu# directory below this will determine the build parameters.  For
2173643Ssaidi@eecs.umich.edu# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2183643Ssaidi@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
2193643Ssaidi@eecs.umich.edu# follow 'build' in the build path.
2203643Ssaidi@eecs.umich.edu
2213643Ssaidi@eecs.umich.edu# The funky assignment to "[:]" is needed to replace the list contents
2224494Ssaidi@eecs.umich.edu# in place rather than reassign the symbol to a new list, which
2234494Ssaidi@eecs.umich.edu# doesn't work (obviously!).
2243716Sstever@eecs.umich.eduBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
2251105SN/A
2262667Sstever@eecs.umich.edu# Generate a list of the unique build roots and configs that the
2272667Sstever@eecs.umich.edu# collected targets reference.
2282667Sstever@eecs.umich.eduvariant_paths = []
2292667Sstever@eecs.umich.edubuild_root = None
2302667Sstever@eecs.umich.edufor t in BUILD_TARGETS:
2312667Sstever@eecs.umich.edu    path_dirs = t.split('/')
2321869SN/A    try:
2331869SN/A        build_top = rfind(path_dirs, 'build', -2)
2341869SN/A    except:
2351869SN/A        print("Error: no non-leaf 'build' dir found on target path", t)
2361869SN/A        Exit(1)
2371065SN/A    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2382632Sstever@eecs.umich.edu    if not build_root:
2392632Sstever@eecs.umich.edu        build_root = this_build_root
2403918Ssaidi@eecs.umich.edu    else:
2413918Ssaidi@eecs.umich.edu        if this_build_root != build_root:
2423940Ssaidi@eecs.umich.edu            print("Error: build targets not under same build root\n"
2434781Snate@binkert.org                  "  %s\n  %s" % (build_root, this_build_root))
2444781Snate@binkert.org            Exit(1)
2453918Ssaidi@eecs.umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
2464781Snate@binkert.org    if variant_path not in variant_paths:
2474781Snate@binkert.org        variant_paths.append(variant_path)
2483918Ssaidi@eecs.umich.edu
2494781Snate@binkert.org# Make sure build_root exists (might not if this is the first build there)
2504781Snate@binkert.orgif not isdir(build_root):
2513940Ssaidi@eecs.umich.edu    mkdir(build_root)
2523942Ssaidi@eecs.umich.edumain['BUILDROOT'] = build_root
2533940Ssaidi@eecs.umich.edu
2543918Ssaidi@eecs.umich.eduExport('main')
2553918Ssaidi@eecs.umich.edu
256955SN/Amain.SConsignFile(joinpath(build_root, "sconsign"))
2571858SN/A
2583918Ssaidi@eecs.umich.edu# Default duplicate option is to use hard links, but this messes up
2593918Ssaidi@eecs.umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
2603918Ssaidi@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
2613918Ssaidi@eecs.umich.edu# (soft) links work better.
2623940Ssaidi@eecs.umich.edumain.SetOption('duplicate', 'soft-copy')
2633940Ssaidi@eecs.umich.edu
2643918Ssaidi@eecs.umich.edu#
2653918Ssaidi@eecs.umich.edu# Set up global sticky variables... these are common to an entire build
2663918Ssaidi@eecs.umich.edu# tree (not specific to a particular build like ALPHA_SE)
2673918Ssaidi@eecs.umich.edu#
2683918Ssaidi@eecs.umich.edu
2693918Ssaidi@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
2703918Ssaidi@eecs.umich.edu
2713918Ssaidi@eecs.umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
2723918Ssaidi@eecs.umich.edu
2733940Ssaidi@eecs.umich.eduglobal_vars.AddVariables(
2743918Ssaidi@eecs.umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
2753918Ssaidi@eecs.umich.edu    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
2761851SN/A    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
2771851SN/A    ('BATCH', 'Use batch pool for build and tests', False),
2781858SN/A    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
2792632Sstever@eecs.umich.edu    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
280955SN/A    ('EXTRAS', 'Add extra directories to the compilation', '')
2813053Sstever@eecs.umich.edu    )
2823053Sstever@eecs.umich.edu
2833053Sstever@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
2843053Sstever@eecs.umich.eduglobal_vars.Update(main)
2853053Sstever@eecs.umich.eduhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
2863053Sstever@eecs.umich.edu
2873053Sstever@eecs.umich.edu# Save sticky variable settings back to current variables file
2883053Sstever@eecs.umich.eduglobal_vars.Save(global_vars_file, main)
2893053Sstever@eecs.umich.edu
2904742Sstever@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
2914742Sstever@eecs.umich.edu# look for sources etc.  This list is exported as extras_dir_list.
2923053Sstever@eecs.umich.edubase_dir = main.srcdir.abspath
2933053Sstever@eecs.umich.eduif main['EXTRAS']:
2943053Sstever@eecs.umich.edu    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
2953053Sstever@eecs.umich.eduelse:
2963053Sstever@eecs.umich.edu    extras_dir_list = []
2973053Sstever@eecs.umich.edu
2983053Sstever@eecs.umich.eduExport('base_dir')
2993053Sstever@eecs.umich.eduExport('extras_dir_list')
3003053Sstever@eecs.umich.edu
3012667Sstever@eecs.umich.edu# the ext directory should be on the #includes path
3024554Sbinkertn@umich.edumain.Append(CPPPATH=[Dir('ext')])
3034554Sbinkertn@umich.edu
3042667Sstever@eecs.umich.edu# Add shared top-level headers
3054554Sbinkertn@umich.edumain.Prepend(CPPPATH=Dir('include'))
3064554Sbinkertn@umich.edu
3074554Sbinkertn@umich.eduif GetOption('verbose'):
3084554Sbinkertn@umich.edu    def MakeAction(action, string, *args, **kwargs):
3094554Sbinkertn@umich.edu        return Action(action, *args, **kwargs)
3104554Sbinkertn@umich.eduelse:
3114554Sbinkertn@umich.edu    MakeAction = Action
3124781Snate@binkert.org    main['CCCOMSTR']        = Transform("CC")
3134554Sbinkertn@umich.edu    main['CXXCOMSTR']       = Transform("CXX")
3144554Sbinkertn@umich.edu    main['ASCOMSTR']        = Transform("AS")
3152667Sstever@eecs.umich.edu    main['ARCOMSTR']        = Transform("AR", 0)
3164554Sbinkertn@umich.edu    main['LINKCOMSTR']      = Transform("LINK", 0)
3174554Sbinkertn@umich.edu    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
3184554Sbinkertn@umich.edu    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
3194554Sbinkertn@umich.edu    main['M4COMSTR']        = Transform("M4")
3202667Sstever@eecs.umich.edu    main['SHCCCOMSTR']      = Transform("SHCC")
3214554Sbinkertn@umich.edu    main['SHCXXCOMSTR']     = Transform("SHCXX")
3222667Sstever@eecs.umich.eduExport('MakeAction')
3234554Sbinkertn@umich.edu
3244554Sbinkertn@umich.edu# Initialize the Link-Time Optimization (LTO) flags
3252667Sstever@eecs.umich.edumain['LTO_CCFLAGS'] = []
3262638Sstever@eecs.umich.edumain['LTO_LDFLAGS'] = []
3272638Sstever@eecs.umich.edu
3282638Sstever@eecs.umich.edu# According to the readme, tcmalloc works best if the compiler doesn't
3293716Sstever@eecs.umich.edu# assume that we're using the builtin malloc and friends. These flags
3303716Sstever@eecs.umich.edu# are compiler-specific, so we need to set them after we detect which
3311858SN/A# compiler we're using.
3323118Sstever@eecs.umich.edumain['TCMALLOC_CCFLAGS'] = []
3333118Sstever@eecs.umich.edu
3343118Sstever@eecs.umich.eduCXX_version = readCommand([main['CXX'],'--version'], exception=False)
3353118Sstever@eecs.umich.eduCXX_V = readCommand([main['CXX'],'-V'], exception=False)
3363118Sstever@eecs.umich.edu
3373118Sstever@eecs.umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3383118Sstever@eecs.umich.edumain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
3393118Sstever@eecs.umich.eduif main['GCC'] + main['CLANG'] > 1:
3403118Sstever@eecs.umich.edu    print('Error: How can we have two at the same time?')
3413118Sstever@eecs.umich.edu    Exit(1)
3423118Sstever@eecs.umich.edu
3433716Sstever@eecs.umich.edu# Set up default C++ compiler flags
3443118Sstever@eecs.umich.eduif main['GCC'] or main['CLANG']:
3453118Sstever@eecs.umich.edu    # As gcc and clang share many flags, do the common parts here
3463118Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-pipe'])
3473118Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
3483118Sstever@eecs.umich.edu    # Enable -Wall and -Wextra and then disable the few warnings that
3493118Sstever@eecs.umich.edu    # we consistently violate
3503118Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
3513118Sstever@eecs.umich.edu                         '-Wno-sign-compare', '-Wno-unused-parameter'])
3523118Sstever@eecs.umich.edu    # We always compile using C++11
3533716Sstever@eecs.umich.edu    main.Append(CXXFLAGS=['-std=c++11'])
3543118Sstever@eecs.umich.edu    if sys.platform.startswith('freebsd'):
3553118Sstever@eecs.umich.edu        main.Append(CCFLAGS=['-I/usr/local/include'])
3563118Sstever@eecs.umich.edu        main.Append(CXXFLAGS=['-I/usr/local/include'])
3573118Sstever@eecs.umich.edu
3583118Sstever@eecs.umich.edu    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
3593118Sstever@eecs.umich.edu    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
3603118Sstever@eecs.umich.edu    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
3613118Sstever@eecs.umich.edu    shared_partial_flags = ['-r', '-nostdlib']
3623118Sstever@eecs.umich.edu    main.Append(PSHLINKFLAGS=shared_partial_flags)
3633118Sstever@eecs.umich.edu    main.Append(PLINKFLAGS=shared_partial_flags)
3643483Ssaidi@eecs.umich.edu
3653494Ssaidi@eecs.umich.edu    # Treat warnings as errors but white list some warnings that we
3663494Ssaidi@eecs.umich.edu    # want to allow (e.g., deprecation warnings).
3673483Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-Werror',
3683483Ssaidi@eecs.umich.edu                         '-Wno-error=deprecated-declarations',
3693483Ssaidi@eecs.umich.edu                         '-Wno-error=deprecated',
3703053Sstever@eecs.umich.edu                        ])
3713053Sstever@eecs.umich.eduelse:
3723918Ssaidi@eecs.umich.edu    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
3733053Sstever@eecs.umich.edu    print("Don't know what compiler options to use for your compiler.")
3743053Sstever@eecs.umich.edu    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
3753053Sstever@eecs.umich.edu    print(termcap.Yellow + '       version:' + termcap.Normal, end = ' ')
3763053Sstever@eecs.umich.edu    if not CXX_version:
3773053Sstever@eecs.umich.edu        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
3781858SN/A              termcap.Normal)
3791858SN/A    else:
3801858SN/A        print(CXX_version.replace('\n', '<nl>'))
3811858SN/A    print("       If you're trying to use a compiler other than GCC")
3821858SN/A    print("       or clang, there appears to be something wrong with your")
3831858SN/A    print("       environment.")
3841859SN/A    print("       ")
3851858SN/A    print("       If you are trying to use a compiler other than those listed")
3861858SN/A    print("       above you will need to ease fix SConstruct and ")
3871858SN/A    print("       src/SConscript to support that compiler.")
3881859SN/A    Exit(1)
3891859SN/A
3901862SN/Aif main['GCC']:
3913053Sstever@eecs.umich.edu    # Check for a supported version of gcc. >= 4.8 is chosen for its
3923053Sstever@eecs.umich.edu    # level of c++11 support. See
3933053Sstever@eecs.umich.edu    # http://gcc.gnu.org/projects/cxx0x.html for details.
3943053Sstever@eecs.umich.edu    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
3951859SN/A    if compareVersions(gcc_version, "4.8") < 0:
3961859SN/A        print('Error: gcc version 4.8 or newer required.')
3971859SN/A        print('       Installed version: ', gcc_version)
3981859SN/A        Exit(1)
3991859SN/A
4001859SN/A    main['GCC_VERSION'] = gcc_version
4011859SN/A
4021859SN/A    if compareVersions(gcc_version, '4.9') >= 0:
4031862SN/A        # Incremental linking with LTO is currently broken in gcc versions
4041859SN/A        # 4.9 and above. A version where everything works completely hasn't
4051859SN/A        # yet been identified.
4061859SN/A        #
4071858SN/A        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
4081858SN/A        main['BROKEN_INCREMENTAL_LTO'] = True
4092139SN/A    if compareVersions(gcc_version, '6.0') >= 0:
4104202Sbinkertn@umich.edu        # gcc versions 6.0 and greater accept an -flinker-output flag which
4114202Sbinkertn@umich.edu        # selects what type of output the linker should generate. This is
4122139SN/A        # necessary for incremental lto to work, but is also broken in
4132155SN/A        # current versions of gcc. It may not be necessary in future
4144202Sbinkertn@umich.edu        # versions. We add it here since it might be, and as a reminder that
4154202Sbinkertn@umich.edu        # it exists. It's excluded if lto is being forced.
4164202Sbinkertn@umich.edu        #
4172155SN/A        # https://gcc.gnu.org/gcc-6/changes.html
4181869SN/A        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
4191869SN/A        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
4201869SN/A        if not GetOption('force_lto'):
4211869SN/A            main.Append(PSHLINKFLAGS='-flinker-output=rel')
4224202Sbinkertn@umich.edu            main.Append(PLINKFLAGS='-flinker-output=rel')
4234202Sbinkertn@umich.edu
4244202Sbinkertn@umich.edu    # gcc from version 4.8 and above generates "rep; ret" instructions
4254202Sbinkertn@umich.edu    # to avoid performance penalties on certain AMD chips. Older
4264202Sbinkertn@umich.edu    # assemblers detect this as an error, "Error: expecting string
4274202Sbinkertn@umich.edu    # instruction after `rep'"
4284202Sbinkertn@umich.edu    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
4294202Sbinkertn@umich.edu                                  '-o', '/dev/null'],
4304202Sbinkertn@umich.edu                                 exception=False).split()
4314202Sbinkertn@umich.edu
4324202Sbinkertn@umich.edu    # version strings may contain extra distro-specific
4334202Sbinkertn@umich.edu    # qualifiers, so play it safe and keep only what comes before
4344202Sbinkertn@umich.edu    # the first hyphen
4354202Sbinkertn@umich.edu    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
4364202Sbinkertn@umich.edu
4374202Sbinkertn@umich.edu    if not as_version or compareVersions(as_version, "2.23") < 0:
4384773Snate@binkert.org        print(termcap.Yellow + termcap.Bold +
4394775Snate@binkert.org            'Warning: This combination of gcc and binutils have' +
4404775Snate@binkert.org            ' known incompatibilities.\n' +
4414773Snate@binkert.org            '         If you encounter build problems, please update ' +
4424773Snate@binkert.org            'binutils to 2.23.' +
4434773Snate@binkert.org            termcap.Normal)
4444773Snate@binkert.org
4454773Snate@binkert.org    # Make sure we warn if the user has requested to compile with the
4464773Snate@binkert.org    # Undefined Benahvior Sanitizer and this version of gcc does not
4471869SN/A    # support it.
4484202Sbinkertn@umich.edu    if GetOption('with_ubsan') and \
4491869SN/A            compareVersions(gcc_version, '4.9') < 0:
4502508SN/A        print(termcap.Yellow + termcap.Bold +
4512508SN/A            'Warning: UBSan is only supported using gcc 4.9 and later.' +
4522508SN/A            termcap.Normal)
4532508SN/A
4544202Sbinkertn@umich.edu    disable_lto = GetOption('no_lto')
4551869SN/A    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
4561869SN/A            not GetOption('force_lto'):
4571869SN/A        print(termcap.Yellow + termcap.Bold +
4581869SN/A            'Warning: Your compiler doesn\'t support incremental linking' +
4591869SN/A            ' and lto at the same time, so lto is being disabled. To force' +
4601869SN/A            ' lto on anyway, use the --force-lto option. That will disable' +
4611965SN/A            ' partial linking.' +
4621965SN/A            termcap.Normal)
4631965SN/A        disable_lto = True
4641869SN/A
4651869SN/A    # Add the appropriate Link-Time Optimization (LTO) flags
4662733Sktlim@umich.edu    # unless LTO is explicitly turned off. Note that these flags
4671869SN/A    # are only used by the fast target.
4681884SN/A    if not disable_lto:
4691884SN/A        # Pass the LTO flag when compiling to produce GIMPLE
4703356Sbinkertn@umich.edu        # output, we merely create the flags here and only append
4713356Sbinkertn@umich.edu        # them later
4723356Sbinkertn@umich.edu        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4734773Snate@binkert.org
4744773Snate@binkert.org        # Use the same amount of jobs for LTO as we are running
4754773Snate@binkert.org        # scons with
4761869SN/A        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4771858SN/A
4781869SN/A    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
4791869SN/A                                  '-fno-builtin-realloc', '-fno-builtin-free'])
4801869SN/A
4811858SN/A    # add option to check for undeclared overrides
4822761Sstever@eecs.umich.edu    if compareVersions(gcc_version, "5.0") > 0:
4831869SN/A        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
4842733Sktlim@umich.edu
4853584Ssaidi@eecs.umich.edu    # The address sanitizer is available for gcc >= 4.8
4861869SN/A    if GetOption('with_asan'):
4871869SN/A        if GetOption('with_ubsan') and \
4881869SN/A                compareVersions(env['GCC_VERSION'], '4.9') >= 0:
4891869SN/A            env.Append(CCFLAGS=['-fsanitize=address,undefined',
4901869SN/A                                '-fno-omit-frame-pointer'],
4911869SN/A                       LINKFLAGS='-fsanitize=address,undefined')
4921858SN/A        else:
493955SN/A            env.Append(CCFLAGS=['-fsanitize=address',
494955SN/A                                '-fno-omit-frame-pointer'],
4951869SN/A                       LINKFLAGS='-fsanitize=address')
4961869SN/A    # Only gcc >= 4.9 supports UBSan, so check both the version
4971869SN/A    # and the command-line option before adding the compiler and
4981869SN/A    # linker flags.
4991869SN/A    elif GetOption('with_ubsan') and \
5001869SN/A            compareVersions(env['GCC_VERSION'], '4.9') >= 0:
5011869SN/A        env.Append(CCFLAGS='-fsanitize=undefined')
5021869SN/A        env.Append(LINKFLAGS='-fsanitize=undefined')
5031869SN/A
5041869SN/Aelif main['CLANG']:
5051869SN/A    # Check for a supported version of clang, >= 3.1 is needed to
5061869SN/A    # support similar features as gcc 4.8. See
5071869SN/A    # http://clang.llvm.org/cxx_status.html for details
5081869SN/A    clang_version_re = re.compile(".* version (\d+\.\d+)")
5091869SN/A    clang_version_match = clang_version_re.search(CXX_version)
5101869SN/A    if (clang_version_match):
5111869SN/A        clang_version = clang_version_match.groups()[0]
5121869SN/A        if compareVersions(clang_version, "3.1") < 0:
5131869SN/A            print('Error: clang version 3.1 or newer required.')
5141869SN/A            print('       Installed version:', clang_version)
5151869SN/A            Exit(1)
5161869SN/A    else:
5171869SN/A        print('Error: Unable to determine clang version.')
5181869SN/A        Exit(1)
5191869SN/A
5201869SN/A    # clang has a few additional warnings that we disable, extraneous
5211869SN/A    # parantheses are allowed due to Ruby's printing of the AST,
5221869SN/A    # finally self assignments are allowed as the generated CPU code
5231869SN/A    # is relying on this
5243716Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wno-parentheses',
5253356Sbinkertn@umich.edu                         '-Wno-self-assign',
5263356Sbinkertn@umich.edu                         # Some versions of libstdc++ (4.8?) seem to
5273356Sbinkertn@umich.edu                         # use struct hash and class hash
5283356Sbinkertn@umich.edu                         # interchangeably.
5293356Sbinkertn@umich.edu                         '-Wno-mismatched-tags',
5303356Sbinkertn@umich.edu                         ])
5314781Snate@binkert.org
5321869SN/A    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
5331869SN/A
5341869SN/A    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
5351869SN/A    # opposed to libstdc++, as the later is dated.
5361869SN/A    if sys.platform == "darwin":
5371869SN/A        main.Append(CXXFLAGS=['-stdlib=libc++'])
5381869SN/A        main.Append(LIBS=['c++'])
5392655Sstever@eecs.umich.edu
5402655Sstever@eecs.umich.edu    # On FreeBSD we need libthr.
5412655Sstever@eecs.umich.edu    if sys.platform.startswith('freebsd'):
5422655Sstever@eecs.umich.edu        main.Append(LIBS=['thr'])
5432655Sstever@eecs.umich.edu
5442655Sstever@eecs.umich.edu    # We require clang >= 3.1, so there is no need to check any
5452655Sstever@eecs.umich.edu    # versions here.
5462655Sstever@eecs.umich.edu    if GetOption('with_ubsan'):
5472655Sstever@eecs.umich.edu        if GetOption('with_asan'):
5482655Sstever@eecs.umich.edu            env.Append(CCFLAGS=['-fsanitize=address,undefined',
5492655Sstever@eecs.umich.edu                                '-fno-omit-frame-pointer'],
5502655Sstever@eecs.umich.edu                       LINKFLAGS='-fsanitize=address,undefined')
5512655Sstever@eecs.umich.edu        else:
5522655Sstever@eecs.umich.edu            env.Append(CCFLAGS='-fsanitize=undefined',
5532655Sstever@eecs.umich.edu                       LINKFLAGS='-fsanitize=undefined')
5542655Sstever@eecs.umich.edu
5552655Sstever@eecs.umich.edu    elif GetOption('with_asan'):
5562655Sstever@eecs.umich.edu        env.Append(CCFLAGS=['-fsanitize=address',
5572655Sstever@eecs.umich.edu                            '-fno-omit-frame-pointer'],
5582655Sstever@eecs.umich.edu                   LINKFLAGS='-fsanitize=address')
5592655Sstever@eecs.umich.edu
5602655Sstever@eecs.umich.eduelse:
5612655Sstever@eecs.umich.edu    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
5622655Sstever@eecs.umich.edu    print("Don't know what compiler options to use for your compiler.")
5632655Sstever@eecs.umich.edu    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
5642655Sstever@eecs.umich.edu    print(termcap.Yellow + '       version:' + termcap.Normal, end=' ')
5652634Sstever@eecs.umich.edu    if not CXX_version:
5662634Sstever@eecs.umich.edu        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
5672634Sstever@eecs.umich.edu              termcap.Normal)
5682634Sstever@eecs.umich.edu    else:
5692634Sstever@eecs.umich.edu        print(CXX_version.replace('\n', '<nl>'))
5702634Sstever@eecs.umich.edu    print("       If you're trying to use a compiler other than GCC")
5712638Sstever@eecs.umich.edu    print("       or clang, there appears to be something wrong with your")
5722638Sstever@eecs.umich.edu    print("       environment.")
5733716Sstever@eecs.umich.edu    print("       ")
5742638Sstever@eecs.umich.edu    print("       If you are trying to use a compiler other than those listed")
5752638Sstever@eecs.umich.edu    print("       above you will need to ease fix SConstruct and ")
5761869SN/A    print("       src/SConscript to support that compiler.")
5771869SN/A    Exit(1)
5783546Sgblack@eecs.umich.edu
5793546Sgblack@eecs.umich.edu# Set up common yacc/bison flags (needed for Ruby)
5803546Sgblack@eecs.umich.edumain['YACCFLAGS'] = '-d'
5813546Sgblack@eecs.umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
5824202Sbinkertn@umich.edu
5833546Sgblack@eecs.umich.edu# Do this after we save setting back, or else we'll tack on an
5843546Sgblack@eecs.umich.edu# extra 'qdo' every time we run scons.
5853546Sgblack@eecs.umich.eduif main['BATCH']:
5863546Sgblack@eecs.umich.edu    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
5873546Sgblack@eecs.umich.edu    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
5884781Snate@binkert.org    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
5894781Snate@binkert.org    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
5904781Snate@binkert.org    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
5914781Snate@binkert.org
5924781Snate@binkert.orgif sys.platform == 'cygwin':
5934781Snate@binkert.org    # cygwin has some header file issues...
5944781Snate@binkert.org    main.Append(CCFLAGS=["-Wno-uninitialized"])
5954781Snate@binkert.org
5964781Snate@binkert.org# Check for the protobuf compiler
5974781Snate@binkert.orgprotoc_version = readCommand([main['PROTOC'], '--version'],
5984781Snate@binkert.org                             exception='').split()
5994781Snate@binkert.org
6003546Sgblack@eecs.umich.edu# First two words should be "libprotoc x.y.z"
6013546Sgblack@eecs.umich.eduif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6023546Sgblack@eecs.umich.edu    print(termcap.Yellow + termcap.Bold +
6034781Snate@binkert.org        'Warning: Protocol buffer compiler (protoc) not found.\n' +
6043546Sgblack@eecs.umich.edu        '         Please install protobuf-compiler for tracing support.' +
6053546Sgblack@eecs.umich.edu        termcap.Normal)
6063546Sgblack@eecs.umich.edu    main['PROTOC'] = False
6073546Sgblack@eecs.umich.eduelse:
6083546Sgblack@eecs.umich.edu    # Based on the availability of the compress stream wrappers,
6093546Sgblack@eecs.umich.edu    # require 2.1.0
6103546Sgblack@eecs.umich.edu    min_protoc_version = '2.1.0'
6113546Sgblack@eecs.umich.edu    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6123546Sgblack@eecs.umich.edu        print(termcap.Yellow + termcap.Bold +
6133546Sgblack@eecs.umich.edu            'Warning: protoc version', min_protoc_version,
6144202Sbinkertn@umich.edu            'or newer required.\n' +
6153546Sgblack@eecs.umich.edu            '         Installed version:', protoc_version[1],
6163546Sgblack@eecs.umich.edu            termcap.Normal)
6173546Sgblack@eecs.umich.edu        main['PROTOC'] = False
618955SN/A    else:
619955SN/A        # Attempt to determine the appropriate include path and
620955SN/A        # library path using pkg-config, that means we also need to
621955SN/A        # check for pkg-config. Note that it is possible to use
6221858SN/A        # protobuf without the involvement of pkg-config. Later on we
6231858SN/A        # check go a library config check and at that point the test
6241858SN/A        # will fail if libprotobuf cannot be found.
6252632Sstever@eecs.umich.edu        if readCommand(['pkg-config', '--version'], exception=''):
6262632Sstever@eecs.umich.edu            try:
6274773Snate@binkert.org                # Attempt to establish what linking flags to add for protobuf
6284773Snate@binkert.org                # using pkg-config
6292632Sstever@eecs.umich.edu                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
6302632Sstever@eecs.umich.edu            except:
6312632Sstever@eecs.umich.edu                print(termcap.Yellow + termcap.Bold +
6322634Sstever@eecs.umich.edu                    'Warning: pkg-config could not get protobuf flags.' +
6332638Sstever@eecs.umich.edu                    termcap.Normal)
6342023SN/A
6352632Sstever@eecs.umich.edu
6362632Sstever@eecs.umich.edu# Check for 'timeout' from GNU coreutils. If present, regressions will
6372632Sstever@eecs.umich.edu# be run with a time limit. We require version 8.13 since we rely on
6382632Sstever@eecs.umich.edu# support for the '--foreground' option.
6392632Sstever@eecs.umich.eduif sys.platform.startswith('freebsd'):
6403716Sstever@eecs.umich.edu    timeout_lines = readCommand(['gtimeout', '--version'],
6412632Sstever@eecs.umich.edu                                exception='').splitlines()
6422632Sstever@eecs.umich.eduelse:
6432632Sstever@eecs.umich.edu    timeout_lines = readCommand(['timeout', '--version'],
6442632Sstever@eecs.umich.edu                                exception='').splitlines()
6452632Sstever@eecs.umich.edu# Get the first line and tokenize it
6462023SN/Atimeout_version = timeout_lines[0].split() if timeout_lines else []
6472632Sstever@eecs.umich.edumain['TIMEOUT'] =  timeout_version and \
6482632Sstever@eecs.umich.edu    compareVersions(timeout_version[-1], '8.13') >= 0
6491889SN/A
6501889SN/A# Add a custom Check function to test for structure members.
6512632Sstever@eecs.umich.edudef CheckMember(context, include, decl, member, include_quotes="<>"):
6522632Sstever@eecs.umich.edu    context.Message("Checking for member %s in %s..." %
6532632Sstever@eecs.umich.edu                    (member, decl))
6542632Sstever@eecs.umich.edu    text = """
6553716Sstever@eecs.umich.edu#include %(header)s
6563716Sstever@eecs.umich.eduint main(){
6572632Sstever@eecs.umich.edu  %(decl)s test;
6582632Sstever@eecs.umich.edu  (void)test.%(member)s;
6592632Sstever@eecs.umich.edu  return 0;
6602632Sstever@eecs.umich.edu};
6612632Sstever@eecs.umich.edu""" % { "header" : include_quotes[0] + include + include_quotes[1],
6622632Sstever@eecs.umich.edu        "decl" : decl,
6632632Sstever@eecs.umich.edu        "member" : member,
6642632Sstever@eecs.umich.edu        }
6651888SN/A
6661888SN/A    ret = context.TryCompile(text, extension=".cc")
6671869SN/A    context.Result(ret)
6681869SN/A    return ret
6691858SN/A
6702598SN/A# Platform-specific configuration.  Note again that we assume that all
6712598SN/A# builds under a given build root run on the same host platform.
6722598SN/Aconf = Configure(main,
6732598SN/A                 conf_dir = joinpath(build_root, '.scons_config'),
6742598SN/A                 log_file = joinpath(build_root, 'scons_config.log'),
6751858SN/A                 custom_tests = {
6761858SN/A        'CheckMember' : CheckMember,
6771858SN/A        })
6781858SN/A
6791858SN/A# Check if we should compile a 64 bit binary on Mac OS X/Darwin
6801858SN/Atry:
6811858SN/A    import platform
6821858SN/A    uname = platform.uname()
6831858SN/A    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
6841871SN/A        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
6851858SN/A            main.Append(CCFLAGS=['-arch', 'x86_64'])
6861858SN/A            main.Append(CFLAGS=['-arch', 'x86_64'])
6871858SN/A            main.Append(LINKFLAGS=['-arch', 'x86_64'])
6881858SN/A            main.Append(ASFLAGS=['-arch', 'x86_64'])
6891858SN/Aexcept:
6901858SN/A    pass
6911858SN/A
6921858SN/A# Recent versions of scons substitute a "Null" object for Configure()
6931858SN/A# when configuration isn't necessary, e.g., if the "--help" option is
6941858SN/A# present.  Unfortuantely this Null object always returns false,
6951858SN/A# breaking all our configuration checks.  We replace it with our own
6961859SN/A# more optimistic null object that returns True instead.
6971859SN/Aif not conf:
6981869SN/A    def NullCheck(*args, **kwargs):
6991888SN/A        return True
7002632Sstever@eecs.umich.edu
7011869SN/A    class NullConf:
7021884SN/A        def __init__(self, env):
7031884SN/A            self.env = env
7041884SN/A        def Finish(self):
7051884SN/A            return self.env
7061884SN/A        def __getattr__(self, mname):
7071884SN/A            return NullCheck
7081965SN/A
7091965SN/A    conf = NullConf(main)
7101965SN/A
7112761Sstever@eecs.umich.edu# Cache build files in the supplied directory.
7121869SN/Aif main['M5_BUILD_CACHE']:
7131869SN/A    print('Using build cache located at', main['M5_BUILD_CACHE'])
7142632Sstever@eecs.umich.edu    CacheDir(main['M5_BUILD_CACHE'])
7152667Sstever@eecs.umich.edu
7161869SN/Amain['USE_PYTHON'] = not GetOption('without_python')
7171869SN/Aif main['USE_PYTHON']:
7182929Sktlim@umich.edu    # Find Python include and library directories for embedding the
7192929Sktlim@umich.edu    # interpreter. We rely on python-config to resolve the appropriate
7203716Sstever@eecs.umich.edu    # includes and linker flags. ParseConfig does not seem to understand
7212929Sktlim@umich.edu    # the more exotic linker flags such as -Xlinker and -export-dynamic so
722955SN/A    # we add them explicitly below. If you want to link in an alternate
7232598SN/A    # version of python, see above for instructions on how to invoke
7242598SN/A    # scons with the appropriate PATH set.
7253546Sgblack@eecs.umich.edu    #
726955SN/A    # First we check if python2-config exists, else we use python-config
727955SN/A    python_config = readCommand(['which', 'python2-config'],
728955SN/A                                exception='').strip()
7291530SN/A    if not os.path.exists(python_config):
730955SN/A        python_config = readCommand(['which', 'python-config'],
731955SN/A                                    exception='').strip()
732955SN/A    py_includes = readCommand([python_config, '--includes'],
733                              exception='').split()
734    # Strip the -I from the include folders before adding them to the
735    # CPPPATH
736    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
737
738    # Read the linker flags and split them into libraries and other link
739    # flags. The libraries are added later through the call the CheckLib.
740    py_ld_flags = readCommand([python_config, '--ldflags'],
741        exception='').split()
742    py_libs = []
743    for lib in py_ld_flags:
744         if not lib.startswith('-l'):
745             main.Append(LINKFLAGS=[lib])
746         else:
747             lib = lib[2:]
748             if lib not in py_libs:
749                 py_libs.append(lib)
750
751    # verify that this stuff works
752    if not conf.CheckHeader('Python.h', '<>'):
753        print("Error: can't find Python.h header in", py_includes)
754        print("Install Python headers (package python-dev on " +
755              "Ubuntu and RedHat)")
756        Exit(1)
757
758    for lib in py_libs:
759        if not conf.CheckLib(lib):
760            print("Error: can't find library %s required by python" % lib)
761            Exit(1)
762
763# On Solaris you need to use libsocket for socket ops
764if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
765   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
766       print("Can't find library with socket calls (e.g. accept())")
767       Exit(1)
768
769# Check for zlib.  If the check passes, libz will be automatically
770# added to the LIBS environment variable.
771if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
772    print('Error: did not find needed zlib compression library '
773          'and/or zlib.h header file.')
774    print('       Please install zlib and try again.')
775    Exit(1)
776
777# If we have the protobuf compiler, also make sure we have the
778# development libraries. If the check passes, libprotobuf will be
779# automatically added to the LIBS environment variable. After
780# this, we can use the HAVE_PROTOBUF flag to determine if we have
781# got both protoc and libprotobuf available.
782main['HAVE_PROTOBUF'] = main['PROTOC'] and \
783    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
784                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
785
786# If we have the compiler but not the library, print another warning.
787if main['PROTOC'] and not main['HAVE_PROTOBUF']:
788    print(termcap.Yellow + termcap.Bold +
789        'Warning: did not find protocol buffer library and/or headers.\n' +
790    '       Please install libprotobuf-dev for tracing support.' +
791    termcap.Normal)
792
793# Check for librt.
794have_posix_clock = \
795    conf.CheckLibWithHeader(None, 'time.h', 'C',
796                            'clock_nanosleep(0,0,NULL,NULL);') or \
797    conf.CheckLibWithHeader('rt', 'time.h', 'C',
798                            'clock_nanosleep(0,0,NULL,NULL);')
799
800have_posix_timers = \
801    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
802                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
803
804if not GetOption('without_tcmalloc'):
805    if conf.CheckLib('tcmalloc'):
806        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
807    elif conf.CheckLib('tcmalloc_minimal'):
808        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
809    else:
810        print(termcap.Yellow + termcap.Bold +
811              "You can get a 12% performance improvement by "
812              "installing tcmalloc (libgoogle-perftools-dev package "
813              "on Ubuntu or RedHat)." + termcap.Normal)
814
815
816# Detect back trace implementations. The last implementation in the
817# list will be used by default.
818backtrace_impls = [ "none" ]
819
820backtrace_checker = 'char temp;' + \
821    ' backtrace_symbols_fd((void*)&temp, 0, 0);'
822if conf.CheckLibWithHeader(None, 'execinfo.h', 'C', backtrace_checker):
823    backtrace_impls.append("glibc")
824elif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
825                             backtrace_checker):
826    # NetBSD and FreeBSD need libexecinfo.
827    backtrace_impls.append("glibc")
828    main.Append(LIBS=['execinfo'])
829
830if backtrace_impls[-1] == "none":
831    default_backtrace_impl = "none"
832    print(termcap.Yellow + termcap.Bold +
833        "No suitable back trace implementation found." +
834        termcap.Normal)
835
836if not have_posix_clock:
837    print("Can't find library for POSIX clocks.")
838
839# Check for <fenv.h> (C99 FP environment control)
840have_fenv = conf.CheckHeader('fenv.h', '<>')
841if not have_fenv:
842    print("Warning: Header file <fenv.h> not found.")
843    print("         This host has no IEEE FP rounding mode control.")
844
845# Check for <png.h> (libpng library needed if wanting to dump
846# frame buffer image in png format)
847have_png = conf.CheckHeader('png.h', '<>')
848if not have_png:
849    print("Warning: Header file <png.h> not found.")
850    print("         This host has no libpng library.")
851    print("         Disabling support for PNG framebuffers.")
852
853# Check if we should enable KVM-based hardware virtualization. The API
854# we rely on exists since version 2.6.36 of the kernel, but somehow
855# the KVM_API_VERSION does not reflect the change. We test for one of
856# the types as a fall back.
857have_kvm = conf.CheckHeader('linux/kvm.h', '<>')
858if not have_kvm:
859    print("Info: Compatible header file <linux/kvm.h> not found, "
860          "disabling KVM support.")
861
862# Check if the TUN/TAP driver is available.
863have_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
864if not have_tuntap:
865    print("Info: Compatible header file <linux/if_tun.h> not found.")
866
867# x86 needs support for xsave. We test for the structure here since we
868# won't be able to run new tests by the time we know which ISA we're
869# targeting.
870have_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
871                                    '#include <linux/kvm.h>') != 0
872
873# Check if the requested target ISA is compatible with the host
874def is_isa_kvm_compatible(isa):
875    try:
876        import platform
877        host_isa = platform.machine()
878    except:
879        print("Warning: Failed to determine host ISA.")
880        return False
881
882    if not have_posix_timers:
883        print("Warning: Can not enable KVM, host seems to lack support "
884              "for POSIX timers")
885        return False
886
887    if isa == "arm":
888        return host_isa in ( "armv7l", "aarch64" )
889    elif isa == "x86":
890        if host_isa != "x86_64":
891            return False
892
893        if not have_kvm_xsave:
894            print("KVM on x86 requires xsave support in kernel headers.")
895            return False
896
897        return True
898    else:
899        return False
900
901
902# Check if the exclude_host attribute is available. We want this to
903# get accurate instruction counts in KVM.
904main['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
905    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
906
907
908######################################################################
909#
910# Finish the configuration
911#
912main = conf.Finish()
913
914######################################################################
915#
916# Collect all non-global variables
917#
918
919# Define the universe of supported ISAs
920all_isa_list = [ ]
921all_gpu_isa_list = [ ]
922Export('all_isa_list')
923Export('all_gpu_isa_list')
924
925class CpuModel(object):
926    '''The CpuModel class encapsulates everything the ISA parser needs to
927    know about a particular CPU model.'''
928
929    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
930    dict = {}
931
932    # Constructor.  Automatically adds models to CpuModel.dict.
933    def __init__(self, name, default=False):
934        self.name = name           # name of model
935
936        # This cpu is enabled by default
937        self.default = default
938
939        # Add self to dict
940        if name in CpuModel.dict:
941            raise AttributeError, "CpuModel '%s' already registered" % name
942        CpuModel.dict[name] = self
943
944Export('CpuModel')
945
946# Sticky variables get saved in the variables file so they persist from
947# one invocation to the next (unless overridden, in which case the new
948# value becomes sticky).
949sticky_vars = Variables(args=ARGUMENTS)
950Export('sticky_vars')
951
952# Sticky variables that should be exported
953export_vars = []
954Export('export_vars')
955
956# For Ruby
957all_protocols = []
958Export('all_protocols')
959protocol_dirs = []
960Export('protocol_dirs')
961slicc_includes = []
962Export('slicc_includes')
963
964# Walk the tree and execute all SConsopts scripts that wil add to the
965# above variables
966if GetOption('verbose'):
967    print("Reading SConsopts")
968for bdir in [ base_dir ] + extras_dir_list:
969    if not isdir(bdir):
970        print("Error: directory '%s' does not exist" % bdir)
971        Exit(1)
972    for root, dirs, files in os.walk(bdir):
973        if 'SConsopts' in files:
974            if GetOption('verbose'):
975                print("Reading", joinpath(root, 'SConsopts'))
976            SConscript(joinpath(root, 'SConsopts'))
977
978all_isa_list.sort()
979all_gpu_isa_list.sort()
980
981sticky_vars.AddVariables(
982    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
983    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
984    ListVariable('CPU_MODELS', 'CPU models',
985                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
986                 sorted(CpuModel.dict.keys())),
987    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
988                 False),
989    BoolVariable('SS_COMPATIBLE_FP',
990                 'Make floating-point results compatible with SimpleScalar',
991                 False),
992    BoolVariable('USE_SSE2',
993                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
994                 False),
995    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
996    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
997    BoolVariable('USE_PNG',  'Enable support for PNG images', have_png),
998    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability',
999                 False),
1000    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models',
1001                 have_kvm),
1002    BoolVariable('USE_TUNTAP',
1003                 'Enable using a tap device to bridge to the host network',
1004                 have_tuntap),
1005    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
1006    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1007                  all_protocols),
1008    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
1009                 backtrace_impls[-1], backtrace_impls)
1010    )
1011
1012# These variables get exported to #defines in config/*.hh (see src/SConscript).
1013export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
1014                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
1015                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST',
1016                'USE_PNG']
1017
1018###################################################
1019#
1020# Define a SCons builder for configuration flag headers.
1021#
1022###################################################
1023
1024# This function generates a config header file that #defines the
1025# variable symbol to the current variable setting (0 or 1).  The source
1026# operands are the name of the variable and a Value node containing the
1027# value of the variable.
1028def build_config_file(target, source, env):
1029    (variable, value) = [s.get_contents() for s in source]
1030    f = file(str(target[0]), 'w')
1031    print('#define', variable, value, file=f)
1032    f.close()
1033    return None
1034
1035# Combine the two functions into a scons Action object.
1036config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1037
1038# The emitter munges the source & target node lists to reflect what
1039# we're really doing.
1040def config_emitter(target, source, env):
1041    # extract variable name from Builder arg
1042    variable = str(target[0])
1043    # True target is config header file
1044    target = joinpath('config', variable.lower() + '.hh')
1045    val = env[variable]
1046    if isinstance(val, bool):
1047        # Force value to 0/1
1048        val = int(val)
1049    elif isinstance(val, str):
1050        val = '"' + val + '"'
1051
1052    # Sources are variable name & value (packaged in SCons Value nodes)
1053    return ([target], [Value(variable), Value(val)])
1054
1055config_builder = Builder(emitter = config_emitter, action = config_action)
1056
1057main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1058
1059###################################################
1060#
1061# Builders for static and shared partially linked object files.
1062#
1063###################################################
1064
1065partial_static_builder = Builder(action=SCons.Defaults.LinkAction,
1066                                 src_suffix='$OBJSUFFIX',
1067                                 src_builder=['StaticObject', 'Object'],
1068                                 LINKFLAGS='$PLINKFLAGS',
1069                                 LIBS='')
1070
1071def partial_shared_emitter(target, source, env):
1072    for tgt in target:
1073        tgt.attributes.shared = 1
1074    return (target, source)
1075partial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
1076                                 emitter=partial_shared_emitter,
1077                                 src_suffix='$SHOBJSUFFIX',
1078                                 src_builder='SharedObject',
1079                                 SHLINKFLAGS='$PSHLINKFLAGS',
1080                                 LIBS='')
1081
1082main.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
1083                         'PartialStatic' : partial_static_builder })
1084
1085# builds in ext are shared across all configs in the build root.
1086ext_dir = abspath(joinpath(str(main.root), 'ext'))
1087ext_build_dirs = []
1088for root, dirs, files in os.walk(ext_dir):
1089    if 'SConscript' in files:
1090        build_dir = os.path.relpath(root, ext_dir)
1091        ext_build_dirs.append(build_dir)
1092        main.SConscript(joinpath(root, 'SConscript'),
1093                        variant_dir=joinpath(build_root, build_dir))
1094
1095main.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
1096
1097###################################################
1098#
1099# This builder and wrapper method are used to set up a directory with
1100# switching headers. Those are headers which are in a generic location and
1101# that include more specific headers from a directory chosen at build time
1102# based on the current build settings.
1103#
1104###################################################
1105
1106def build_switching_header(target, source, env):
1107    path = str(target[0])
1108    subdir = str(source[0])
1109    dp, fp = os.path.split(path)
1110    dp = os.path.relpath(os.path.realpath(dp),
1111                         os.path.realpath(env['BUILDDIR']))
1112    with open(path, 'w') as hdr:
1113        print('#include "%s/%s/%s"' % (dp, subdir, fp), file=hdr)
1114
1115switching_header_action = MakeAction(build_switching_header,
1116                                     Transform('GENERATE'))
1117
1118switching_header_builder = Builder(action=switching_header_action,
1119                                   source_factory=Value,
1120                                   single_source=True)
1121
1122main.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
1123
1124def switching_headers(self, headers, source):
1125    for header in headers:
1126        self.SwitchingHeader(header, source)
1127
1128main.AddMethod(switching_headers, 'SwitchingHeaders')
1129
1130###################################################
1131#
1132# Define build environments for selected configurations.
1133#
1134###################################################
1135
1136for variant_path in variant_paths:
1137    if not GetOption('silent'):
1138        print("Building in", variant_path)
1139
1140    # Make a copy of the build-root environment to use for this config.
1141    env = main.Clone()
1142    env['BUILDDIR'] = variant_path
1143
1144    # variant_dir is the tail component of build path, and is used to
1145    # determine the build parameters (e.g., 'ALPHA_SE')
1146    (build_root, variant_dir) = splitpath(variant_path)
1147
1148    # Set env variables according to the build directory config.
1149    sticky_vars.files = []
1150    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1151    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1152    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1153    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1154    if isfile(current_vars_file):
1155        sticky_vars.files.append(current_vars_file)
1156        if not GetOption('silent'):
1157            print("Using saved variables file %s" % current_vars_file)
1158    elif variant_dir in ext_build_dirs:
1159        # Things in ext are built without a variant directory.
1160        continue
1161    else:
1162        # Build dir-specific variables file doesn't exist.
1163
1164        # Make sure the directory is there so we can create it later
1165        opt_dir = dirname(current_vars_file)
1166        if not isdir(opt_dir):
1167            mkdir(opt_dir)
1168
1169        # Get default build variables from source tree.  Variables are
1170        # normally determined by name of $VARIANT_DIR, but can be
1171        # overridden by '--default=' arg on command line.
1172        default = GetOption('default')
1173        opts_dir = joinpath(main.root.abspath, 'build_opts')
1174        if default:
1175            default_vars_files = [joinpath(build_root, 'variables', default),
1176                                  joinpath(opts_dir, default)]
1177        else:
1178            default_vars_files = [joinpath(opts_dir, variant_dir)]
1179        existing_files = filter(isfile, default_vars_files)
1180        if existing_files:
1181            default_vars_file = existing_files[0]
1182            sticky_vars.files.append(default_vars_file)
1183            print("Variables file %s not found,\n  using defaults in %s"
1184                  % (current_vars_file, default_vars_file))
1185        else:
1186            print("Error: cannot find variables file %s or "
1187                  "default file(s) %s"
1188                  % (current_vars_file, ' or '.join(default_vars_files)))
1189            Exit(1)
1190
1191    # Apply current variable settings to env
1192    sticky_vars.Update(env)
1193
1194    help_texts["local_vars"] += \
1195        "Build variables for %s:\n" % variant_dir \
1196                 + sticky_vars.GenerateHelpText(env)
1197
1198    # Process variable settings.
1199
1200    if not have_fenv and env['USE_FENV']:
1201        print("Warning: <fenv.h> not available; "
1202              "forcing USE_FENV to False in", variant_dir + ".")
1203        env['USE_FENV'] = False
1204
1205    if not env['USE_FENV']:
1206        print("Warning: No IEEE FP rounding mode control in",
1207              variant_dir + ".")
1208        print("         FP results may deviate slightly from other platforms.")
1209
1210    if not have_png and env['USE_PNG']:
1211        print("Warning: <png.h> not available; "
1212              "forcing USE_PNG to False in", variant_dir + ".")
1213        env['USE_PNG'] = False
1214
1215    if env['USE_PNG']:
1216        env.Append(LIBS=['png'])
1217
1218    if env['EFENCE']:
1219        env.Append(LIBS=['efence'])
1220
1221    if env['USE_KVM']:
1222        if not have_kvm:
1223            print("Warning: Can not enable KVM, host seems to "
1224                  "lack KVM support")
1225            env['USE_KVM'] = False
1226        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1227            print("Info: KVM support disabled due to unsupported host and "
1228                  "target ISA combination")
1229            env['USE_KVM'] = False
1230
1231    if env['USE_TUNTAP']:
1232        if not have_tuntap:
1233            print("Warning: Can't connect EtherTap with a tap device.")
1234            env['USE_TUNTAP'] = False
1235
1236    if env['BUILD_GPU']:
1237        env.Append(CPPDEFINES=['BUILD_GPU'])
1238
1239    # Warn about missing optional functionality
1240    if env['USE_KVM']:
1241        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1242            print("Warning: perf_event headers lack support for the "
1243                  "exclude_host attribute. KVM instruction counts will "
1244                  "be inaccurate.")
1245
1246    # Save sticky variable settings back to current variables file
1247    sticky_vars.Save(current_vars_file, env)
1248
1249    if env['USE_SSE2']:
1250        env.Append(CCFLAGS=['-msse2'])
1251
1252    # The src/SConscript file sets up the build rules in 'env' according
1253    # to the configured variables.  It returns a list of environments,
1254    # one for each variant build (debug, opt, etc.)
1255    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1256
1257# base help text
1258Help('''
1259Usage: scons [scons options] [build variables] [target(s)]
1260
1261Extra scons options:
1262%(options)s
1263
1264Global build variables:
1265%(global_vars)s
1266
1267%(local_vars)s
1268''' % help_texts)
1269