SConstruct revision 13715
1955SN/A# -*- mode:python -*-
2955SN/A
37816Ssteve.reinhardt@amd.com# Copyright (c) 2013, 2015-2017 ARM Limited
45871Snate@binkert.org# All rights reserved.
51762SN/A#
6955SN/A# The license below extends only to copyright in the software and shall
7955SN/A# not be construed as granting a license to any other intellectual
8955SN/A# property including but not limited to intellectual property relating
9955SN/A# to a hardware implementation of the functionality of the software
10955SN/A# licensed hereunder.  You may use the software subject to the license
11955SN/A# terms below provided that you ensure that this notice is replicated
12955SN/A# unmodified and in its entirety in all distributions of the software,
13955SN/A# modified or unmodified, in source code or in binary form.
14955SN/A#
15955SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
16955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
17955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
18955SN/A# All rights reserved.
19955SN/A#
20955SN/A# Redistribution and use in source and binary forms, with or without
21955SN/A# modification, are permitted provided that the following conditions are
22955SN/A# met: redistributions of source code must retain the above copyright
23955SN/A# notice, this list of conditions and the following disclaimer;
24955SN/A# redistributions in binary form must reproduce the above copyright
25955SN/A# notice, this list of conditions and the following disclaimer in the
26955SN/A# documentation and/or other materials provided with the distribution;
27955SN/A# neither the name of the copyright holders nor the names of its
28955SN/A# contributors may be used to endorse or promote products derived from
29955SN/A# this software without specific prior written permission.
302665Ssaidi@eecs.umich.edu#
312665Ssaidi@eecs.umich.edu# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
325863Snate@binkert.org# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
382632Sstever@eecs.umich.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
392632Sstever@eecs.umich.edu# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
402632Sstever@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
412632Sstever@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42955SN/A#
432632Sstever@eecs.umich.edu# Authors: Steve Reinhardt
442632Sstever@eecs.umich.edu#          Nathan Binkert
452761Sstever@eecs.umich.edu
462632Sstever@eecs.umich.edu###################################################
472632Sstever@eecs.umich.edu#
482632Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
492761Sstever@eecs.umich.edu#
502761Sstever@eecs.umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
512761Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
522632Sstever@eecs.umich.edu# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
532632Sstever@eecs.umich.edu# the optimized full-system version).
542761Sstever@eecs.umich.edu#
552761Sstever@eecs.umich.edu# You can build gem5 in a different directory as long as there is a
562761Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
572761Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
582761Sstever@eecs.umich.edu# built for the same host system.
592632Sstever@eecs.umich.edu#
602632Sstever@eecs.umich.edu# Examples:
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
632632Sstever@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
642632Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
652632Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
66955SN/A#
67955SN/A#   The following two commands are equivalent and demonstrate building
68955SN/A#   in a directory outside of the source tree.  The '-C' option tells
695863Snate@binkert.org#   scons to chdir to the specified directory to find this SConstruct
705863Snate@binkert.org#   file.
715863Snate@binkert.org#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
725863Snate@binkert.org#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
735863Snate@binkert.org#
745863Snate@binkert.org# You can use 'scons -H' to print scons options.  If you're in this
755863Snate@binkert.org# 'gem5' directory (or use -u or -C to tell scons where to find this
765863Snate@binkert.org# file), you can use 'scons -h' to print all the gem5-specific build
775863Snate@binkert.org# options as well.
785863Snate@binkert.org#
795863Snate@binkert.org###################################################
805863Snate@binkert.org
815863Snate@binkert.orgfrom __future__ import print_function
825863Snate@binkert.org
835863Snate@binkert.org# Global Python includes
845863Snate@binkert.orgimport itertools
855863Snate@binkert.orgimport os
865863Snate@binkert.orgimport re
875863Snate@binkert.orgimport shutil
885863Snate@binkert.orgimport subprocess
895863Snate@binkert.orgimport sys
905863Snate@binkert.org
915863Snate@binkert.orgfrom os import mkdir, environ
925863Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
935863Snate@binkert.orgfrom os.path import exists,  isdir, isfile
945863Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
955863Snate@binkert.orgfrom re import match
965863Snate@binkert.org
975863Snate@binkert.org# SCons includes
985863Snate@binkert.orgimport SCons
995863Snate@binkert.orgimport SCons.Node
1006654Snate@binkert.org
101955SN/Afrom m5.util import compareVersions, readCommand
1025396Ssaidi@eecs.umich.edu
1035863Snate@binkert.orghelp_texts = {
1045863Snate@binkert.org    "options" : "",
1054202Sbinkertn@umich.edu    "global_vars" : "",
1065863Snate@binkert.org    "local_vars" : ""
1075863Snate@binkert.org}
1085863Snate@binkert.org
1095863Snate@binkert.orgExport("help_texts")
110955SN/A
1116654Snate@binkert.org
1125273Sstever@gmail.com# There's a bug in scons in that (1) by default, the help texts from
1135871Snate@binkert.org# AddOption() are supposed to be displayed when you type 'scons -h'
1145273Sstever@gmail.com# and (2) you can override the help displayed by 'scons -h' using the
1156655Snate@binkert.org# Help() function, but these two features are incompatible: once
1166655Snate@binkert.org# you've overridden the help text using Help(), there's no way to get
1176655Snate@binkert.org# at the help texts from AddOptions.  See:
1186655Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1196655Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1206655Snate@binkert.org# This hack lets us extract the help text from AddOptions and
1215871Snate@binkert.org# re-inject it via Help().  Ideally someday this bug will be fixed and
1226654Snate@binkert.org# we can just use AddOption directly.
1235396Ssaidi@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1248120Sgblack@eecs.umich.edu    col_width = 30
1258120Sgblack@eecs.umich.edu
1268120Sgblack@eecs.umich.edu    help = "  " + ", ".join(args)
1278120Sgblack@eecs.umich.edu    if "help" in kwargs:
1288120Sgblack@eecs.umich.edu        length = len(help)
1298120Sgblack@eecs.umich.edu        if length >= col_width:
1308120Sgblack@eecs.umich.edu            help += "\n" + " " * col_width
1318120Sgblack@eecs.umich.edu        else:
1328120Sgblack@eecs.umich.edu            help += " " * (col_width - length)
1338120Sgblack@eecs.umich.edu        help += kwargs["help"]
1348120Sgblack@eecs.umich.edu    help_texts["options"] += help + "\n"
1358120Sgblack@eecs.umich.edu
1368120Sgblack@eecs.umich.edu    AddOption(*args, **kwargs)
1378120Sgblack@eecs.umich.edu
1388120Sgblack@eecs.umich.eduAddLocalOption('--colors', dest='use_colors', action='store_true',
1398120Sgblack@eecs.umich.edu               help="Add color to abbreviated scons output")
1408120Sgblack@eecs.umich.eduAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1418120Sgblack@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1428120Sgblack@eecs.umich.eduAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1438120Sgblack@eecs.umich.edu               action='store_true',
1448120Sgblack@eecs.umich.edu               help="Build with support for C++-based configuration")
1458120Sgblack@eecs.umich.eduAddLocalOption('--default', dest='default', type='string', action='store',
1468120Sgblack@eecs.umich.edu               help='Override which build_opts file to use for defaults')
1478120Sgblack@eecs.umich.eduAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1488120Sgblack@eecs.umich.edu               help='Disable style checking hooks')
1498120Sgblack@eecs.umich.eduAddLocalOption('--gold-linker', dest='gold_linker', action='store_true',
1508120Sgblack@eecs.umich.edu               help='Use the gold linker')
1518120Sgblack@eecs.umich.eduAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1528120Sgblack@eecs.umich.edu               help='Disable Link-Time Optimization for fast')
1538120Sgblack@eecs.umich.eduAddLocalOption('--force-lto', dest='force_lto', action='store_true',
1548120Sgblack@eecs.umich.edu               help='Use Link-Time Optimization instead of partial linking' +
1558120Sgblack@eecs.umich.edu                    ' when the compiler doesn\'t support using them together.')
1568120Sgblack@eecs.umich.eduAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1578120Sgblack@eecs.umich.edu               help='Update test reference outputs')
1588120Sgblack@eecs.umich.eduAddLocalOption('--verbose', dest='verbose', action='store_true',
1598120Sgblack@eecs.umich.edu               help='Print full tool command lines')
1607816Ssteve.reinhardt@amd.comAddLocalOption('--without-python', dest='without_python',
1617816Ssteve.reinhardt@amd.com               action='store_true',
1627816Ssteve.reinhardt@amd.com               help='Build without Python configuration support')
1637816Ssteve.reinhardt@amd.comAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1647816Ssteve.reinhardt@amd.com               action='store_true',
1657816Ssteve.reinhardt@amd.com               help='Disable linking against tcmalloc')
1667816Ssteve.reinhardt@amd.comAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1677816Ssteve.reinhardt@amd.com               help='Build with Undefined Behavior Sanitizer if available')
1687816Ssteve.reinhardt@amd.comAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1695871Snate@binkert.org               help='Build with Address Sanitizer if available')
1705871Snate@binkert.org
1716121Snate@binkert.orgif GetOption('no_lto') and GetOption('force_lto'):
1725871Snate@binkert.org    print('--no-lto and --force-lto are mutually exclusive')
1735871Snate@binkert.org    Exit(1)
1746003Snate@binkert.org
1756655Snate@binkert.org########################################################################
176955SN/A#
1775871Snate@binkert.org# Set up the main build environment.
1785871Snate@binkert.org#
1795871Snate@binkert.org########################################################################
1805871Snate@binkert.org
181955SN/Amain = Environment()
1826121Snate@binkert.org
1836121Snate@binkert.orgfrom gem5_scons import Transform
1846121Snate@binkert.orgfrom gem5_scons.util import get_termcap
1851533SN/Atermcap = get_termcap()
1866655Snate@binkert.org
1876655Snate@binkert.orgmain_dict_keys = main.Dictionary().keys()
1886655Snate@binkert.org
1896655Snate@binkert.org# Check that we have a C/C++ compiler
1905871Snate@binkert.orgif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
1915871Snate@binkert.org    print("No C++ compiler installed (package g++ on Ubuntu and RedHat)")
1925863Snate@binkert.org    Exit(1)
1935871Snate@binkert.org
1945871Snate@binkert.org###################################################
1955871Snate@binkert.org#
1965871Snate@binkert.org# Figure out which configurations to set up based on the path(s) of
1975871Snate@binkert.org# the target(s).
1985863Snate@binkert.org#
1996121Snate@binkert.org###################################################
2005863Snate@binkert.org
2015871Snate@binkert.org# Find default configuration & binary.
2028336Ssteve.reinhardt@amd.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
2038336Ssteve.reinhardt@amd.com
2048336Ssteve.reinhardt@amd.com# helper function: find last occurrence of element in list
2058336Ssteve.reinhardt@amd.comdef rfind(l, elt, offs = -1):
2064678Snate@binkert.org    for i in range(len(l)+offs, 0, -1):
2078336Ssteve.reinhardt@amd.com        if l[i] == elt:
2088336Ssteve.reinhardt@amd.com            return i
2098336Ssteve.reinhardt@amd.com    raise ValueError, "element not found"
2104678Snate@binkert.org
2114678Snate@binkert.org# Take a list of paths (or SCons Nodes) and return a list with all
2124678Snate@binkert.org# paths made absolute and ~-expanded.  Paths will be interpreted
2134678Snate@binkert.org# relative to the launch directory unless a different root is provided
2147827Snate@binkert.orgdef makePathListAbsolute(path_list, root=GetLaunchDir()):
2157827Snate@binkert.org    return [abspath(joinpath(root, expanduser(str(p))))
2168336Ssteve.reinhardt@amd.com            for p in path_list]
2174678Snate@binkert.org
2188336Ssteve.reinhardt@amd.comdef find_first_prog(prog_names):
2198336Ssteve.reinhardt@amd.com    """Find the absolute path to the first existing binary in prog_names"""
2208336Ssteve.reinhardt@amd.com
2218336Ssteve.reinhardt@amd.com    if not isinstance(prog_names, (list, tuple)):
2228336Ssteve.reinhardt@amd.com        prog_names = [ prog_names ]
2238336Ssteve.reinhardt@amd.com
2245871Snate@binkert.org    for p in prog_names:
2255871Snate@binkert.org        p = main.WhereIs(p)
2268336Ssteve.reinhardt@amd.com        if p is not None:
2278336Ssteve.reinhardt@amd.com            return p
2288336Ssteve.reinhardt@amd.com
2298336Ssteve.reinhardt@amd.com    return None
2308336Ssteve.reinhardt@amd.com
2315871Snate@binkert.org# Each target must have 'build' in the interior of the path; the
2328336Ssteve.reinhardt@amd.com# directory below this will determine the build parameters.  For
2338336Ssteve.reinhardt@amd.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2348336Ssteve.reinhardt@amd.com# recognize that ALPHA_SE specifies the configuration because it
2358336Ssteve.reinhardt@amd.com# follow 'build' in the build path.
2368336Ssteve.reinhardt@amd.com
2374678Snate@binkert.org# The funky assignment to "[:]" is needed to replace the list contents
2385871Snate@binkert.org# in place rather than reassign the symbol to a new list, which
2394678Snate@binkert.org# doesn't work (obviously!).
2408336Ssteve.reinhardt@amd.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
2418336Ssteve.reinhardt@amd.com
2428336Ssteve.reinhardt@amd.com# Generate a list of the unique build roots and configs that the
2438336Ssteve.reinhardt@amd.com# collected targets reference.
2448336Ssteve.reinhardt@amd.comvariant_paths = []
2458336Ssteve.reinhardt@amd.combuild_root = None
2468336Ssteve.reinhardt@amd.comfor t in BUILD_TARGETS:
2478336Ssteve.reinhardt@amd.com    path_dirs = t.split('/')
2488336Ssteve.reinhardt@amd.com    try:
2498336Ssteve.reinhardt@amd.com        build_top = rfind(path_dirs, 'build', -2)
2508336Ssteve.reinhardt@amd.com    except:
2518336Ssteve.reinhardt@amd.com        print("Error: no non-leaf 'build' dir found on target path", t)
2528336Ssteve.reinhardt@amd.com        Exit(1)
2538336Ssteve.reinhardt@amd.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2548336Ssteve.reinhardt@amd.com    if not build_root:
2558336Ssteve.reinhardt@amd.com        build_root = this_build_root
2568336Ssteve.reinhardt@amd.com    else:
2575871Snate@binkert.org        if this_build_root != build_root:
2586121Snate@binkert.org            print("Error: build targets not under same build root\n"
259955SN/A                  "  %s\n  %s" % (build_root, this_build_root))
260955SN/A            Exit(1)
2612632Sstever@eecs.umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
2622632Sstever@eecs.umich.edu    if variant_path not in variant_paths:
263955SN/A        variant_paths.append(variant_path)
264955SN/A
265955SN/A# Make sure build_root exists (might not if this is the first build there)
266955SN/Aif not isdir(build_root):
2675863Snate@binkert.org    mkdir(build_root)
268955SN/Amain['BUILDROOT'] = build_root
2692632Sstever@eecs.umich.edu
2702632Sstever@eecs.umich.eduExport('main')
2712632Sstever@eecs.umich.edu
2722632Sstever@eecs.umich.edumain.SConsignFile(joinpath(build_root, "sconsign"))
2732632Sstever@eecs.umich.edu
2742632Sstever@eecs.umich.edu# Default duplicate option is to use hard links, but this messes up
2752632Sstever@eecs.umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
2768268Ssteve.reinhardt@amd.com# file to file~ then copies to file, breaking the link.  Symbolic
2778268Ssteve.reinhardt@amd.com# (soft) links work better.
2788268Ssteve.reinhardt@amd.commain.SetOption('duplicate', 'soft-copy')
2798268Ssteve.reinhardt@amd.com
2808268Ssteve.reinhardt@amd.com#
2818268Ssteve.reinhardt@amd.com# Set up global sticky variables... these are common to an entire build
2828268Ssteve.reinhardt@amd.com# tree (not specific to a particular build like ALPHA_SE)
2832632Sstever@eecs.umich.edu#
2842632Sstever@eecs.umich.edu
2852632Sstever@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
2862632Sstever@eecs.umich.edu
2878268Ssteve.reinhardt@amd.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
2882632Sstever@eecs.umich.edu
2898268Ssteve.reinhardt@amd.comglobal_vars.AddVariables(
2908268Ssteve.reinhardt@amd.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
2918268Ssteve.reinhardt@amd.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
2928268Ssteve.reinhardt@amd.com    ('PYTHON_CONFIG', 'Python config binary to use',
2933718Sstever@eecs.umich.edu     [ 'python2.7-config', 'python-config' ]),
2942634Sstever@eecs.umich.edu    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
2952634Sstever@eecs.umich.edu    ('BATCH', 'Use batch pool for build and tests', False),
2965863Snate@binkert.org    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
2972638Sstever@eecs.umich.edu    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
2988268Ssteve.reinhardt@amd.com    ('EXTRAS', 'Add extra directories to the compilation', '')
2992632Sstever@eecs.umich.edu    )
3002632Sstever@eecs.umich.edu
3012632Sstever@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
3022632Sstever@eecs.umich.eduglobal_vars.Update(main)
3032632Sstever@eecs.umich.eduhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3041858SN/A
3053716Sstever@eecs.umich.edu# Save sticky variable settings back to current variables file
3062638Sstever@eecs.umich.eduglobal_vars.Save(global_vars_file, main)
3072638Sstever@eecs.umich.edu
3082638Sstever@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
3092638Sstever@eecs.umich.edu# look for sources etc.  This list is exported as extras_dir_list.
3102638Sstever@eecs.umich.edubase_dir = main.srcdir.abspath
3112638Sstever@eecs.umich.eduif main['EXTRAS']:
3122638Sstever@eecs.umich.edu    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
3135863Snate@binkert.orgelse:
3145863Snate@binkert.org    extras_dir_list = []
3155863Snate@binkert.org
316955SN/AExport('base_dir')
3175341Sstever@gmail.comExport('extras_dir_list')
3185341Sstever@gmail.com
3195863Snate@binkert.org# the ext directory should be on the #includes path
3207756SAli.Saidi@ARM.commain.Append(CPPPATH=[Dir('ext')])
3215341Sstever@gmail.com
3226121Snate@binkert.org# Add shared top-level headers
3234494Ssaidi@eecs.umich.edumain.Prepend(CPPPATH=Dir('include'))
3246121Snate@binkert.org
3251105SN/Aif GetOption('verbose'):
3262667Sstever@eecs.umich.edu    def MakeAction(action, string, *args, **kwargs):
3272667Sstever@eecs.umich.edu        return Action(action, *args, **kwargs)
3282667Sstever@eecs.umich.eduelse:
3292667Sstever@eecs.umich.edu    MakeAction = Action
3306121Snate@binkert.org    main['CCCOMSTR']        = Transform("CC")
3312667Sstever@eecs.umich.edu    main['CXXCOMSTR']       = Transform("CXX")
3325341Sstever@gmail.com    main['ASCOMSTR']        = Transform("AS")
3335863Snate@binkert.org    main['ARCOMSTR']        = Transform("AR", 0)
3345341Sstever@gmail.com    main['LINKCOMSTR']      = Transform("LINK", 0)
3355341Sstever@gmail.com    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
3365341Sstever@gmail.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
3378120Sgblack@eecs.umich.edu    main['M4COMSTR']        = Transform("M4")
3385341Sstever@gmail.com    main['SHCCCOMSTR']      = Transform("SHCC")
3398120Sgblack@eecs.umich.edu    main['SHCXXCOMSTR']     = Transform("SHCXX")
3405341Sstever@gmail.comExport('MakeAction')
3418120Sgblack@eecs.umich.edu
3426121Snate@binkert.org# Initialize the Link-Time Optimization (LTO) flags
3436121Snate@binkert.orgmain['LTO_CCFLAGS'] = []
3445397Ssaidi@eecs.umich.edumain['LTO_LDFLAGS'] = []
3455397Ssaidi@eecs.umich.edu
3467727SAli.Saidi@ARM.com# According to the readme, tcmalloc works best if the compiler doesn't
3478268Ssteve.reinhardt@amd.com# assume that we're using the builtin malloc and friends. These flags
3486168Snate@binkert.org# are compiler-specific, so we need to set them after we detect which
3495341Sstever@gmail.com# compiler we're using.
3508120Sgblack@eecs.umich.edumain['TCMALLOC_CCFLAGS'] = []
3518120Sgblack@eecs.umich.edu
3528120Sgblack@eecs.umich.eduCXX_version = readCommand([main['CXX'],'--version'], exception=False)
3536814Sgblack@eecs.umich.eduCXX_V = readCommand([main['CXX'],'-V'], exception=False)
3545863Snate@binkert.org
3558120Sgblack@eecs.umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3565341Sstever@gmail.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
3575863Snate@binkert.orgif main['GCC'] + main['CLANG'] > 1:
3588268Ssteve.reinhardt@amd.com    print('Error: How can we have two at the same time?')
3596121Snate@binkert.org    Exit(1)
3606121Snate@binkert.org
3618268Ssteve.reinhardt@amd.com# Set up default C++ compiler flags
3625742Snate@binkert.orgif main['GCC'] or main['CLANG']:
3635742Snate@binkert.org    # As gcc and clang share many flags, do the common parts here
3645341Sstever@gmail.com    main.Append(CCFLAGS=['-pipe'])
3655742Snate@binkert.org    main.Append(CCFLAGS=['-fno-strict-aliasing'])
3665742Snate@binkert.org    # Enable -Wall and -Wextra and then disable the few warnings that
3675341Sstever@gmail.com    # we consistently violate
3686017Snate@binkert.org    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
3696121Snate@binkert.org                         '-Wno-sign-compare', '-Wno-unused-parameter'])
3706017Snate@binkert.org    # We always compile using C++11
3717816Ssteve.reinhardt@amd.com    main.Append(CXXFLAGS=['-std=c++11'])
3727756SAli.Saidi@ARM.com    if sys.platform.startswith('freebsd'):
3737756SAli.Saidi@ARM.com        main.Append(CCFLAGS=['-I/usr/local/include'])
3747756SAli.Saidi@ARM.com        main.Append(CXXFLAGS=['-I/usr/local/include'])
3757756SAli.Saidi@ARM.com
3767756SAli.Saidi@ARM.com    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
3777756SAli.Saidi@ARM.com    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
3787756SAli.Saidi@ARM.com    if GetOption('gold_linker'):
3797756SAli.Saidi@ARM.com        main.Append(LINKFLAGS='-fuse-ld=gold')
3807816Ssteve.reinhardt@amd.com    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
3817816Ssteve.reinhardt@amd.com    shared_partial_flags = ['-r', '-nostdlib']
3827816Ssteve.reinhardt@amd.com    main.Append(PSHLINKFLAGS=shared_partial_flags)
3837816Ssteve.reinhardt@amd.com    main.Append(PLINKFLAGS=shared_partial_flags)
3847816Ssteve.reinhardt@amd.com
3857816Ssteve.reinhardt@amd.com    # Treat warnings as errors but white list some warnings that we
3867816Ssteve.reinhardt@amd.com    # want to allow (e.g., deprecation warnings).
3877816Ssteve.reinhardt@amd.com    main.Append(CCFLAGS=['-Werror',
3887816Ssteve.reinhardt@amd.com                         '-Wno-error=deprecated-declarations',
3897816Ssteve.reinhardt@amd.com                         '-Wno-error=deprecated',
3907756SAli.Saidi@ARM.com                        ])
3917816Ssteve.reinhardt@amd.comelse:
3927816Ssteve.reinhardt@amd.com    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
3937816Ssteve.reinhardt@amd.com    print("Don't know what compiler options to use for your compiler.")
3947816Ssteve.reinhardt@amd.com    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
3957816Ssteve.reinhardt@amd.com    print(termcap.Yellow + '       version:' + termcap.Normal, end = ' ')
3967816Ssteve.reinhardt@amd.com    if not CXX_version:
3977816Ssteve.reinhardt@amd.com        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
3987816Ssteve.reinhardt@amd.com              termcap.Normal)
3997816Ssteve.reinhardt@amd.com    else:
4007816Ssteve.reinhardt@amd.com        print(CXX_version.replace('\n', '<nl>'))
4017816Ssteve.reinhardt@amd.com    print("       If you're trying to use a compiler other than GCC")
4027816Ssteve.reinhardt@amd.com    print("       or clang, there appears to be something wrong with your")
4037816Ssteve.reinhardt@amd.com    print("       environment.")
4047816Ssteve.reinhardt@amd.com    print("       ")
4057816Ssteve.reinhardt@amd.com    print("       If you are trying to use a compiler other than those listed")
4067816Ssteve.reinhardt@amd.com    print("       above you will need to ease fix SConstruct and ")
4077816Ssteve.reinhardt@amd.com    print("       src/SConscript to support that compiler.")
4087816Ssteve.reinhardt@amd.com    Exit(1)
4097816Ssteve.reinhardt@amd.com
4107816Ssteve.reinhardt@amd.comif main['GCC']:
4117816Ssteve.reinhardt@amd.com    # Check for a supported version of gcc. >= 4.8 is chosen for its
4127816Ssteve.reinhardt@amd.com    # level of c++11 support. See
4137816Ssteve.reinhardt@amd.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
4147816Ssteve.reinhardt@amd.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
4157816Ssteve.reinhardt@amd.com    if compareVersions(gcc_version, "4.8") < 0:
4167816Ssteve.reinhardt@amd.com        print('Error: gcc version 4.8 or newer required.')
4177816Ssteve.reinhardt@amd.com        print('       Installed version: ', gcc_version)
4187816Ssteve.reinhardt@amd.com        Exit(1)
4197816Ssteve.reinhardt@amd.com
4207816Ssteve.reinhardt@amd.com    main['GCC_VERSION'] = gcc_version
4217816Ssteve.reinhardt@amd.com
4227816Ssteve.reinhardt@amd.com    if compareVersions(gcc_version, '4.9') >= 0:
4237816Ssteve.reinhardt@amd.com        # Incremental linking with LTO is currently broken in gcc versions
4247816Ssteve.reinhardt@amd.com        # 4.9 and above. A version where everything works completely hasn't
4257816Ssteve.reinhardt@amd.com        # yet been identified.
4267816Ssteve.reinhardt@amd.com        #
4277816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
4287816Ssteve.reinhardt@amd.com        main['BROKEN_INCREMENTAL_LTO'] = True
4297816Ssteve.reinhardt@amd.com    if compareVersions(gcc_version, '6.0') >= 0:
4307816Ssteve.reinhardt@amd.com        # gcc versions 6.0 and greater accept an -flinker-output flag which
4317816Ssteve.reinhardt@amd.com        # selects what type of output the linker should generate. This is
4327816Ssteve.reinhardt@amd.com        # necessary for incremental lto to work, but is also broken in
4337816Ssteve.reinhardt@amd.com        # current versions of gcc. It may not be necessary in future
4347816Ssteve.reinhardt@amd.com        # versions. We add it here since it might be, and as a reminder that
4357816Ssteve.reinhardt@amd.com        # it exists. It's excluded if lto is being forced.
4367816Ssteve.reinhardt@amd.com        #
4377816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/gcc-6/changes.html
4387816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
4397816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
4407816Ssteve.reinhardt@amd.com        if not GetOption('force_lto'):
4417816Ssteve.reinhardt@amd.com            main.Append(PSHLINKFLAGS='-flinker-output=rel')
4427816Ssteve.reinhardt@amd.com            main.Append(PLINKFLAGS='-flinker-output=rel')
4437816Ssteve.reinhardt@amd.com
4447816Ssteve.reinhardt@amd.com    # Make sure we warn if the user has requested to compile with the
4457816Ssteve.reinhardt@amd.com    # Undefined Benahvior Sanitizer and this version of gcc does not
4467816Ssteve.reinhardt@amd.com    # support it.
4477816Ssteve.reinhardt@amd.com    if GetOption('with_ubsan') and \
4487816Ssteve.reinhardt@amd.com            compareVersions(gcc_version, '4.9') < 0:
4497816Ssteve.reinhardt@amd.com        print(termcap.Yellow + termcap.Bold +
4507816Ssteve.reinhardt@amd.com            'Warning: UBSan is only supported using gcc 4.9 and later.' +
4517816Ssteve.reinhardt@amd.com            termcap.Normal)
4527756SAli.Saidi@ARM.com
4538120Sgblack@eecs.umich.edu    disable_lto = GetOption('no_lto')
4547756SAli.Saidi@ARM.com    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
4557756SAli.Saidi@ARM.com            not GetOption('force_lto'):
4567756SAli.Saidi@ARM.com        print(termcap.Yellow + termcap.Bold +
4577756SAli.Saidi@ARM.com            'Warning: Your compiler doesn\'t support incremental linking' +
4587816Ssteve.reinhardt@amd.com            ' and lto at the same time, so lto is being disabled. To force' +
4597816Ssteve.reinhardt@amd.com            ' lto on anyway, use the --force-lto option. That will disable' +
4607816Ssteve.reinhardt@amd.com            ' partial linking.' +
4617816Ssteve.reinhardt@amd.com            termcap.Normal)
4627816Ssteve.reinhardt@amd.com        disable_lto = True
4637816Ssteve.reinhardt@amd.com
4647816Ssteve.reinhardt@amd.com    # Add the appropriate Link-Time Optimization (LTO) flags
4657816Ssteve.reinhardt@amd.com    # unless LTO is explicitly turned off. Note that these flags
4667816Ssteve.reinhardt@amd.com    # are only used by the fast target.
4677816Ssteve.reinhardt@amd.com    if not disable_lto:
4687756SAli.Saidi@ARM.com        # Pass the LTO flag when compiling to produce GIMPLE
4697756SAli.Saidi@ARM.com        # output, we merely create the flags here and only append
4706654Snate@binkert.org        # them later
4716654Snate@binkert.org        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4725871Snate@binkert.org
4736121Snate@binkert.org        # Use the same amount of jobs for LTO as we are running
4746121Snate@binkert.org        # scons with
4756121Snate@binkert.org        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4768737Skoansin.tan@gmail.com
4778737Skoansin.tan@gmail.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
4783940Ssaidi@eecs.umich.edu                                  '-fno-builtin-realloc', '-fno-builtin-free'])
4793918Ssaidi@eecs.umich.edu
4803918Ssaidi@eecs.umich.edu    # The address sanitizer is available for gcc >= 4.8
4811858SN/A    if GetOption('with_asan'):
4826121Snate@binkert.org        if GetOption('with_ubsan') and \
4837739Sgblack@eecs.umich.edu                compareVersions(main['GCC_VERSION'], '4.9') >= 0:
4847739Sgblack@eecs.umich.edu            main.Append(CCFLAGS=['-fsanitize=address,undefined',
4856143Snate@binkert.org                                 '-fno-omit-frame-pointer'],
4867739Sgblack@eecs.umich.edu                        LINKFLAGS='-fsanitize=address,undefined')
4877618SAli.Saidi@arm.com        else:
4887618SAli.Saidi@arm.com            main.Append(CCFLAGS=['-fsanitize=address',
4897618SAli.Saidi@arm.com                                 '-fno-omit-frame-pointer'],
4907618SAli.Saidi@arm.com                        LINKFLAGS='-fsanitize=address')
4918614Sgblack@eecs.umich.edu    # Only gcc >= 4.9 supports UBSan, so check both the version
4927618SAli.Saidi@arm.com    # and the command-line option before adding the compiler and
4937618SAli.Saidi@arm.com    # linker flags.
4947618SAli.Saidi@arm.com    elif GetOption('with_ubsan') and \
4957739Sgblack@eecs.umich.edu            compareVersions(main['GCC_VERSION'], '4.9') >= 0:
4966121Snate@binkert.org        main.Append(CCFLAGS='-fsanitize=undefined')
4973940Ssaidi@eecs.umich.edu        main.Append(LINKFLAGS='-fsanitize=undefined')
4986121Snate@binkert.org
4997739Sgblack@eecs.umich.eduelif main['CLANG']:
5007739Sgblack@eecs.umich.edu    # Check for a supported version of clang, >= 3.1 is needed to
5017739Sgblack@eecs.umich.edu    # support similar features as gcc 4.8. See
5027739Sgblack@eecs.umich.edu    # http://clang.llvm.org/cxx_status.html for details
5037739Sgblack@eecs.umich.edu    clang_version_re = re.compile(".* version (\d+\.\d+)")
5047739Sgblack@eecs.umich.edu    clang_version_match = clang_version_re.search(CXX_version)
5058737Skoansin.tan@gmail.com    if (clang_version_match):
5068737Skoansin.tan@gmail.com        clang_version = clang_version_match.groups()[0]
5078737Skoansin.tan@gmail.com        if compareVersions(clang_version, "3.1") < 0:
5088737Skoansin.tan@gmail.com            print('Error: clang version 3.1 or newer required.')
5098737Skoansin.tan@gmail.com            print('       Installed version:', clang_version)
5108737Skoansin.tan@gmail.com            Exit(1)
5118737Skoansin.tan@gmail.com    else:
5128737Skoansin.tan@gmail.com        print('Error: Unable to determine clang version.')
5138737Skoansin.tan@gmail.com        Exit(1)
5148737Skoansin.tan@gmail.com
5158737Skoansin.tan@gmail.com    # clang has a few additional warnings that we disable, extraneous
5168737Skoansin.tan@gmail.com    # parantheses are allowed due to Ruby's printing of the AST,
5178737Skoansin.tan@gmail.com    # finally self assignments are allowed as the generated CPU code
5188737Skoansin.tan@gmail.com    # is relying on this
5198737Skoansin.tan@gmail.com    main.Append(CCFLAGS=['-Wno-parentheses',
5208737Skoansin.tan@gmail.com                         '-Wno-self-assign',
5218737Skoansin.tan@gmail.com                         # Some versions of libstdc++ (4.8?) seem to
5228737Skoansin.tan@gmail.com                         # use struct hash and class hash
5233918Ssaidi@eecs.umich.edu                         # interchangeably.
5243918Ssaidi@eecs.umich.edu                         '-Wno-mismatched-tags',
5253940Ssaidi@eecs.umich.edu                         ])
5263918Ssaidi@eecs.umich.edu
5273918Ssaidi@eecs.umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
5286157Snate@binkert.org
5296157Snate@binkert.org    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
5306157Snate@binkert.org    # opposed to libstdc++, as the later is dated.
5316157Snate@binkert.org    if sys.platform == "darwin":
5325397Ssaidi@eecs.umich.edu        main.Append(CXXFLAGS=['-stdlib=libc++'])
5335397Ssaidi@eecs.umich.edu        main.Append(LIBS=['c++'])
5346121Snate@binkert.org
5356121Snate@binkert.org    # On FreeBSD we need libthr.
5366121Snate@binkert.org    if sys.platform.startswith('freebsd'):
5376121Snate@binkert.org        main.Append(LIBS=['thr'])
5386121Snate@binkert.org
5396121Snate@binkert.org    # We require clang >= 3.1, so there is no need to check any
5405397Ssaidi@eecs.umich.edu    # versions here.
5411851SN/A    if GetOption('with_ubsan'):
5421851SN/A        if GetOption('with_asan'):
5437739Sgblack@eecs.umich.edu            main.Append(CCFLAGS=['-fsanitize=address,undefined',
544955SN/A                                 '-fno-omit-frame-pointer'],
5453053Sstever@eecs.umich.edu                       LINKFLAGS='-fsanitize=address,undefined')
5466121Snate@binkert.org        else:
5473053Sstever@eecs.umich.edu            main.Append(CCFLAGS='-fsanitize=undefined',
5483053Sstever@eecs.umich.edu                        LINKFLAGS='-fsanitize=undefined')
5493053Sstever@eecs.umich.edu
5503053Sstever@eecs.umich.edu    elif GetOption('with_asan'):
5513053Sstever@eecs.umich.edu        main.Append(CCFLAGS=['-fsanitize=address',
5526654Snate@binkert.org                             '-fno-omit-frame-pointer'],
5533053Sstever@eecs.umich.edu                   LINKFLAGS='-fsanitize=address')
5544742Sstever@eecs.umich.edu
5554742Sstever@eecs.umich.eduelse:
5563053Sstever@eecs.umich.edu    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
5573053Sstever@eecs.umich.edu    print("Don't know what compiler options to use for your compiler.")
5583053Sstever@eecs.umich.edu    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
5593053Sstever@eecs.umich.edu    print(termcap.Yellow + '       version:' + termcap.Normal, end=' ')
5606654Snate@binkert.org    if not CXX_version:
5613053Sstever@eecs.umich.edu        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
5623053Sstever@eecs.umich.edu              termcap.Normal)
5633053Sstever@eecs.umich.edu    else:
5643053Sstever@eecs.umich.edu        print(CXX_version.replace('\n', '<nl>'))
5652667Sstever@eecs.umich.edu    print("       If you're trying to use a compiler other than GCC")
5664554Sbinkertn@umich.edu    print("       or clang, there appears to be something wrong with your")
5676121Snate@binkert.org    print("       environment.")
5682667Sstever@eecs.umich.edu    print("       ")
5694554Sbinkertn@umich.edu    print("       If you are trying to use a compiler other than those listed")
5704554Sbinkertn@umich.edu    print("       above you will need to ease fix SConstruct and ")
5714554Sbinkertn@umich.edu    print("       src/SConscript to support that compiler.")
5726121Snate@binkert.org    Exit(1)
5734554Sbinkertn@umich.edu
5744554Sbinkertn@umich.edu# Set up common yacc/bison flags (needed for Ruby)
5754554Sbinkertn@umich.edumain['YACCFLAGS'] = '-d'
5764781Snate@binkert.orgmain['YACCHXXFILESUFFIX'] = '.hh'
5774554Sbinkertn@umich.edu
5784554Sbinkertn@umich.edu# Do this after we save setting back, or else we'll tack on an
5792667Sstever@eecs.umich.edu# extra 'qdo' every time we run scons.
5804554Sbinkertn@umich.eduif main['BATCH']:
5814554Sbinkertn@umich.edu    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
5824554Sbinkertn@umich.edu    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
5834554Sbinkertn@umich.edu    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
5842667Sstever@eecs.umich.edu    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
5854554Sbinkertn@umich.edu    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
5862667Sstever@eecs.umich.edu
5874554Sbinkertn@umich.eduif sys.platform == 'cygwin':
5886121Snate@binkert.org    # cygwin has some header file issues...
5892667Sstever@eecs.umich.edu    main.Append(CCFLAGS=["-Wno-uninitialized"])
5905522Snate@binkert.org
5915522Snate@binkert.org# Check for the protobuf compiler
5925522Snate@binkert.orgprotoc_version = readCommand([main['PROTOC'], '--version'],
5935522Snate@binkert.org                             exception='').split()
5945522Snate@binkert.org
5955522Snate@binkert.org# First two words should be "libprotoc x.y.z"
5965522Snate@binkert.orgif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
5975522Snate@binkert.org    print(termcap.Yellow + termcap.Bold +
5985522Snate@binkert.org        'Warning: Protocol buffer compiler (protoc) not found.\n' +
5995522Snate@binkert.org        '         Please install protobuf-compiler for tracing support.' +
6005522Snate@binkert.org        termcap.Normal)
6015522Snate@binkert.org    main['PROTOC'] = False
6025522Snate@binkert.orgelse:
6035522Snate@binkert.org    # Based on the availability of the compress stream wrappers,
6045522Snate@binkert.org    # require 2.1.0
6055522Snate@binkert.org    min_protoc_version = '2.1.0'
6065522Snate@binkert.org    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6075522Snate@binkert.org        print(termcap.Yellow + termcap.Bold +
6085522Snate@binkert.org            'Warning: protoc version', min_protoc_version,
6095522Snate@binkert.org            'or newer required.\n' +
6105522Snate@binkert.org            '         Installed version:', protoc_version[1],
6115522Snate@binkert.org            termcap.Normal)
6125522Snate@binkert.org        main['PROTOC'] = False
6135522Snate@binkert.org    else:
6145522Snate@binkert.org        # Attempt to determine the appropriate include path and
6155522Snate@binkert.org        # library path using pkg-config, that means we also need to
6162638Sstever@eecs.umich.edu        # check for pkg-config. Note that it is possible to use
6172638Sstever@eecs.umich.edu        # protobuf without the involvement of pkg-config. Later on we
6186121Snate@binkert.org        # check go a library config check and at that point the test
6193716Sstever@eecs.umich.edu        # will fail if libprotobuf cannot be found.
6205522Snate@binkert.org        if readCommand(['pkg-config', '--version'], exception=''):
6215522Snate@binkert.org            try:
6225522Snate@binkert.org                # Attempt to establish what linking flags to add for protobuf
6235522Snate@binkert.org                # using pkg-config
6245522Snate@binkert.org                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
6255522Snate@binkert.org            except:
6261858SN/A                print(termcap.Yellow + termcap.Bold +
6275227Ssaidi@eecs.umich.edu                    'Warning: pkg-config could not get protobuf flags.' +
6285227Ssaidi@eecs.umich.edu                    termcap.Normal)
6295227Ssaidi@eecs.umich.edu
6305227Ssaidi@eecs.umich.edu
6316654Snate@binkert.org# Check for 'timeout' from GNU coreutils. If present, regressions will
6326654Snate@binkert.org# be run with a time limit. We require version 8.13 since we rely on
6337769SAli.Saidi@ARM.com# support for the '--foreground' option.
6347769SAli.Saidi@ARM.comif sys.platform.startswith('freebsd'):
6357769SAli.Saidi@ARM.com    timeout_lines = readCommand(['gtimeout', '--version'],
6367769SAli.Saidi@ARM.com                                exception='').splitlines()
6375227Ssaidi@eecs.umich.eduelse:
6385227Ssaidi@eecs.umich.edu    timeout_lines = readCommand(['timeout', '--version'],
6395227Ssaidi@eecs.umich.edu                                exception='').splitlines()
6405204Sstever@gmail.com# Get the first line and tokenize it
6415204Sstever@gmail.comtimeout_version = timeout_lines[0].split() if timeout_lines else []
6425204Sstever@gmail.commain['TIMEOUT'] =  timeout_version and \
6435204Sstever@gmail.com    compareVersions(timeout_version[-1], '8.13') >= 0
6445204Sstever@gmail.com
6455204Sstever@gmail.com# Add a custom Check function to test for structure members.
6465204Sstever@gmail.comdef CheckMember(context, include, decl, member, include_quotes="<>"):
6475204Sstever@gmail.com    context.Message("Checking for member %s in %s..." %
6485204Sstever@gmail.com                    (member, decl))
6495204Sstever@gmail.com    text = """
6505204Sstever@gmail.com#include %(header)s
6515204Sstever@gmail.comint main(){
6525204Sstever@gmail.com  %(decl)s test;
6535204Sstever@gmail.com  (void)test.%(member)s;
6545204Sstever@gmail.com  return 0;
6555204Sstever@gmail.com};
6565204Sstever@gmail.com""" % { "header" : include_quotes[0] + include + include_quotes[1],
6576121Snate@binkert.org        "decl" : decl,
6585204Sstever@gmail.com        "member" : member,
6593118Sstever@eecs.umich.edu        }
6603118Sstever@eecs.umich.edu
6613118Sstever@eecs.umich.edu    ret = context.TryCompile(text, extension=".cc")
6623118Sstever@eecs.umich.edu    context.Result(ret)
6633118Sstever@eecs.umich.edu    return ret
6645863Snate@binkert.org
6653118Sstever@eecs.umich.edu# Platform-specific configuration.  Note again that we assume that all
6665863Snate@binkert.org# builds under a given build root run on the same host platform.
6673118Sstever@eecs.umich.educonf = Configure(main,
6687457Snate@binkert.org                 conf_dir = joinpath(build_root, '.scons_config'),
6697457Snate@binkert.org                 log_file = joinpath(build_root, 'scons_config.log'),
6705863Snate@binkert.org                 custom_tests = {
6715863Snate@binkert.org        'CheckMember' : CheckMember,
6725863Snate@binkert.org        })
6735863Snate@binkert.org
6745863Snate@binkert.org# Check if we should compile a 64 bit binary on Mac OS X/Darwin
6755863Snate@binkert.orgtry:
6765863Snate@binkert.org    import platform
6776003Snate@binkert.org    uname = platform.uname()
6785863Snate@binkert.org    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
6795863Snate@binkert.org        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
6805863Snate@binkert.org            main.Append(CCFLAGS=['-arch', 'x86_64'])
6816120Snate@binkert.org            main.Append(CFLAGS=['-arch', 'x86_64'])
6825863Snate@binkert.org            main.Append(LINKFLAGS=['-arch', 'x86_64'])
6835863Snate@binkert.org            main.Append(ASFLAGS=['-arch', 'x86_64'])
6845863Snate@binkert.orgexcept:
6858655Sandreas.hansson@arm.com    pass
6868655Sandreas.hansson@arm.com
6878655Sandreas.hansson@arm.com# Recent versions of scons substitute a "Null" object for Configure()
6888655Sandreas.hansson@arm.com# when configuration isn't necessary, e.g., if the "--help" option is
6898655Sandreas.hansson@arm.com# present.  Unfortuantely this Null object always returns false,
6908655Sandreas.hansson@arm.com# breaking all our configuration checks.  We replace it with our own
6918655Sandreas.hansson@arm.com# more optimistic null object that returns True instead.
6928655Sandreas.hansson@arm.comif not conf:
6936120Snate@binkert.org    def NullCheck(*args, **kwargs):
6945863Snate@binkert.org        return True
6956121Snate@binkert.org
6966121Snate@binkert.org    class NullConf:
6975863Snate@binkert.org        def __init__(self, env):
6987727SAli.Saidi@ARM.com            self.env = env
6997727SAli.Saidi@ARM.com        def Finish(self):
7007727SAli.Saidi@ARM.com            return self.env
7017727SAli.Saidi@ARM.com        def __getattr__(self, mname):
7027727SAli.Saidi@ARM.com            return NullCheck
7037727SAli.Saidi@ARM.com
7045863Snate@binkert.org    conf = NullConf(main)
7053118Sstever@eecs.umich.edu
7065863Snate@binkert.org# Cache build files in the supplied directory.
7073118Sstever@eecs.umich.eduif main['M5_BUILD_CACHE']:
7083118Sstever@eecs.umich.edu    print('Using build cache located at', main['M5_BUILD_CACHE'])
7095863Snate@binkert.org    CacheDir(main['M5_BUILD_CACHE'])
7105863Snate@binkert.org
7115863Snate@binkert.orgmain['USE_PYTHON'] = not GetOption('without_python')
7125863Snate@binkert.orgif main['USE_PYTHON']:
7133118Sstever@eecs.umich.edu    # Find Python include and library directories for embedding the
7143483Ssaidi@eecs.umich.edu    # interpreter. We rely on python-config to resolve the appropriate
7153494Ssaidi@eecs.umich.edu    # includes and linker flags. ParseConfig does not seem to understand
7163494Ssaidi@eecs.umich.edu    # the more exotic linker flags such as -Xlinker and -export-dynamic so
7173483Ssaidi@eecs.umich.edu    # we add them explicitly below. If you want to link in an alternate
7183483Ssaidi@eecs.umich.edu    # version of python, see above for instructions on how to invoke
7193483Ssaidi@eecs.umich.edu    # scons with the appropriate PATH set.
7203053Sstever@eecs.umich.edu
7213053Sstever@eecs.umich.edu    python_config = find_first_prog(main['PYTHON_CONFIG'])
7223918Ssaidi@eecs.umich.edu    if python_config is None:
7233053Sstever@eecs.umich.edu        print("Error: can't find a suitable python-config, tried %s" % \
7243053Sstever@eecs.umich.edu              main['PYTHON_CONFIG'])
7253053Sstever@eecs.umich.edu        Exit(1)
7263053Sstever@eecs.umich.edu
7273053Sstever@eecs.umich.edu    print("Info: Using Python config: %s" % (python_config, ))
7287840Snate@binkert.org    py_includes = readCommand([python_config, '--includes'],
7297865Sgblack@eecs.umich.edu                              exception='').split()
7307865Sgblack@eecs.umich.edu    py_includes = filter(lambda s: match(r'.*\/include\/.*',s), py_includes)
7317865Sgblack@eecs.umich.edu    # Strip the -I from the include folders before adding them to the
7327865Sgblack@eecs.umich.edu    # CPPPATH
7337865Sgblack@eecs.umich.edu    py_includes = map(lambda s: s[2:] if s.startswith('-I') else s, py_includes)
7347840Snate@binkert.org    main.Append(CPPPATH=py_includes)
7357840Snate@binkert.org
7367840Snate@binkert.org    # Read the linker flags and split them into libraries and other link
7377840Snate@binkert.org    # flags. The libraries are added later through the call the CheckLib.
7381858SN/A    py_ld_flags = readCommand([python_config, '--ldflags'],
7391858SN/A        exception='').split()
7401858SN/A    py_libs = []
7411858SN/A    for lib in py_ld_flags:
7421858SN/A         if not lib.startswith('-l'):
7431858SN/A             main.Append(LINKFLAGS=[lib])
7445863Snate@binkert.org         else:
7455863Snate@binkert.org             lib = lib[2:]
7465863Snate@binkert.org             if lib not in py_libs:
7475863Snate@binkert.org                 py_libs.append(lib)
7486121Snate@binkert.org
7491858SN/A    # verify that this stuff works
7505863Snate@binkert.org    if not conf.CheckHeader('Python.h', '<>'):
7515863Snate@binkert.org        print("Error: Check failed for Python.h header in", py_includes)
7525863Snate@binkert.org        print("Two possible reasons:")
7535863Snate@binkert.org        print("1. Python headers are not installed (You can install the "
7545863Snate@binkert.org              "package python-dev on Ubuntu and RedHat)")
7552139SN/A        print("2. SCons is using a wrong C compiler. This can happen if "
7564202Sbinkertn@umich.edu              "CC has the wrong value.")
7574202Sbinkertn@umich.edu        print("CC = %s" % main['CC'])
7582139SN/A        Exit(1)
7596994Snate@binkert.org
7606994Snate@binkert.org    for lib in py_libs:
7616994Snate@binkert.org        if not conf.CheckLib(lib):
7626994Snate@binkert.org            print("Error: can't find library %s required by python" % lib)
7636994Snate@binkert.org            Exit(1)
7646994Snate@binkert.org
7656994Snate@binkert.org# On Solaris you need to use libsocket for socket ops
7666994Snate@binkert.orgif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7676994Snate@binkert.org   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7686994Snate@binkert.org       print("Can't find library with socket calls (e.g. accept())")
7696994Snate@binkert.org       Exit(1)
7706994Snate@binkert.org
7716994Snate@binkert.org# Check for zlib.  If the check passes, libz will be automatically
7726994Snate@binkert.org# added to the LIBS environment variable.
7736994Snate@binkert.orgif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
7746994Snate@binkert.org    print('Error: did not find needed zlib compression library '
7756994Snate@binkert.org          'and/or zlib.h header file.')
7766994Snate@binkert.org    print('       Please install zlib and try again.')
7776994Snate@binkert.org    Exit(1)
7786994Snate@binkert.org
7796994Snate@binkert.org# If we have the protobuf compiler, also make sure we have the
7806994Snate@binkert.org# development libraries. If the check passes, libprotobuf will be
7816994Snate@binkert.org# automatically added to the LIBS environment variable. After
7826994Snate@binkert.org# this, we can use the HAVE_PROTOBUF flag to determine if we have
7836994Snate@binkert.org# got both protoc and libprotobuf available.
7846994Snate@binkert.orgmain['HAVE_PROTOBUF'] = main['PROTOC'] and \
7856994Snate@binkert.org    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
7866994Snate@binkert.org                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
7872155SN/A
7885863Snate@binkert.org# Valgrind gets much less confused if you tell it when you're using
7891869SN/A# alternative stacks.
7901869SN/Amain['HAVE_VALGRIND'] = conf.CheckCHeader('valgrind/valgrind.h')
7915863Snate@binkert.org
7925863Snate@binkert.org# If we have the compiler but not the library, print another warning.
7934202Sbinkertn@umich.eduif main['PROTOC'] and not main['HAVE_PROTOBUF']:
7946108Snate@binkert.org    print(termcap.Yellow + termcap.Bold +
7956108Snate@binkert.org        'Warning: did not find protocol buffer library and/or headers.\n' +
7966108Snate@binkert.org    '       Please install libprotobuf-dev for tracing support.' +
7976108Snate@binkert.org    termcap.Normal)
7984202Sbinkertn@umich.edu
7995863Snate@binkert.org# Check for librt.
8008474Sgblack@eecs.umich.eduhave_posix_clock = \
8018474Sgblack@eecs.umich.edu    conf.CheckLibWithHeader(None, 'time.h', 'C',
8025742Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);') or \
8038268Ssteve.reinhardt@amd.com    conf.CheckLibWithHeader('rt', 'time.h', 'C',
8048268Ssteve.reinhardt@amd.com                            'clock_nanosleep(0,0,NULL,NULL);')
8058268Ssteve.reinhardt@amd.com
8065742Snate@binkert.orghave_posix_timers = \
8075341Sstever@gmail.com    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
8088474Sgblack@eecs.umich.edu                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
8098474Sgblack@eecs.umich.edu
8105342Sstever@gmail.comif not GetOption('without_tcmalloc'):
8114202Sbinkertn@umich.edu    if conf.CheckLib('tcmalloc'):
8124202Sbinkertn@umich.edu        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
8134202Sbinkertn@umich.edu    elif conf.CheckLib('tcmalloc_minimal'):
8145863Snate@binkert.org        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
8155863Snate@binkert.org    else:
8165863Snate@binkert.org        print(termcap.Yellow + termcap.Bold +
8176994Snate@binkert.org              "You can get a 12% performance improvement by "
8186994Snate@binkert.org              "installing tcmalloc (libgoogle-perftools-dev package "
8196994Snate@binkert.org              "on Ubuntu or RedHat)." + termcap.Normal)
8205863Snate@binkert.org
8218152Ssteve.reinhardt@amd.com
8228152Ssteve.reinhardt@amd.com# Detect back trace implementations. The last implementation in the
8235863Snate@binkert.org# list will be used by default.
8245863Snate@binkert.orgbacktrace_impls = [ "none" ]
8255863Snate@binkert.org
8265863Snate@binkert.orgbacktrace_checker = 'char temp;' + \
8275863Snate@binkert.org    ' backtrace_symbols_fd((void*)&temp, 0, 0);'
8285863Snate@binkert.orgif conf.CheckLibWithHeader(None, 'execinfo.h', 'C', backtrace_checker):
8295863Snate@binkert.org    backtrace_impls.append("glibc")
8305863Snate@binkert.orgelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
8315863Snate@binkert.org                             backtrace_checker):
8325863Snate@binkert.org    # NetBSD and FreeBSD need libexecinfo.
8337840Snate@binkert.org    backtrace_impls.append("glibc")
8345863Snate@binkert.org    main.Append(LIBS=['execinfo'])
8355863Snate@binkert.org
8365952Ssaidi@eecs.umich.eduif backtrace_impls[-1] == "none":
8371869SN/A    default_backtrace_impl = "none"
8381858SN/A    print(termcap.Yellow + termcap.Bold +
8395863Snate@binkert.org        "No suitable back trace implementation found." +
8408297Snate@binkert.org        termcap.Normal)
8418152Ssteve.reinhardt@amd.com
8427840Snate@binkert.orgif not have_posix_clock:
8437840Snate@binkert.org    print("Can't find library for POSIX clocks.")
8441858SN/A
845955SN/A# Check for <fenv.h> (C99 FP environment control)
846955SN/Ahave_fenv = conf.CheckHeader('fenv.h', '<>')
8471869SN/Aif not have_fenv:
8481869SN/A    print("Warning: Header file <fenv.h> not found.")
8491869SN/A    print("         This host has no IEEE FP rounding mode control.")
8501869SN/A
8511869SN/A# Check for <png.h> (libpng library needed if wanting to dump
8525863Snate@binkert.org# frame buffer image in png format)
8535863Snate@binkert.orghave_png = conf.CheckHeader('png.h', '<>')
8545863Snate@binkert.orgif not have_png:
8551869SN/A    print("Warning: Header file <png.h> not found.")
8565863Snate@binkert.org    print("         This host has no libpng library.")
8571869SN/A    print("         Disabling support for PNG framebuffers.")
8585863Snate@binkert.org
8591869SN/A# Check if we should enable KVM-based hardware virtualization. The API
8601869SN/A# we rely on exists since version 2.6.36 of the kernel, but somehow
8611869SN/A# the KVM_API_VERSION does not reflect the change. We test for one of
8621869SN/A# the types as a fall back.
8638483Sgblack@eecs.umich.eduhave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
8641869SN/Aif not have_kvm:
8651869SN/A    print("Info: Compatible header file <linux/kvm.h> not found, "
8661869SN/A          "disabling KVM support.")
8671869SN/A
8685863Snate@binkert.org# Check if the TUN/TAP driver is available.
8695863Snate@binkert.orghave_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
8701869SN/Aif not have_tuntap:
8715863Snate@binkert.org    print("Info: Compatible header file <linux/if_tun.h> not found.")
8725863Snate@binkert.org
8733356Sbinkertn@umich.edu# x86 needs support for xsave. We test for the structure here since we
8743356Sbinkertn@umich.edu# won't be able to run new tests by the time we know which ISA we're
8753356Sbinkertn@umich.edu# targeting.
8763356Sbinkertn@umich.eduhave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
8773356Sbinkertn@umich.edu                                    '#include <linux/kvm.h>') != 0
8784781Snate@binkert.org
8795863Snate@binkert.org# Check if the requested target ISA is compatible with the host
8805863Snate@binkert.orgdef is_isa_kvm_compatible(isa):
8811869SN/A    try:
8821869SN/A        import platform
8831869SN/A        host_isa = platform.machine()
8846121Snate@binkert.org    except:
8851869SN/A        print("Warning: Failed to determine host ISA.")
8862638Sstever@eecs.umich.edu        return False
8876121Snate@binkert.org
8886121Snate@binkert.org    if not have_posix_timers:
8892638Sstever@eecs.umich.edu        print("Warning: Can not enable KVM, host seems to lack support "
8905749Scws3k@cs.virginia.edu              "for POSIX timers")
8916121Snate@binkert.org        return False
8926121Snate@binkert.org
8935749Scws3k@cs.virginia.edu    if isa == "arm":
8941869SN/A        return host_isa in ( "armv7l", "aarch64" )
8951869SN/A    elif isa == "x86":
8963546Sgblack@eecs.umich.edu        if host_isa != "x86_64":
8973546Sgblack@eecs.umich.edu            return False
8983546Sgblack@eecs.umich.edu
8993546Sgblack@eecs.umich.edu        if not have_kvm_xsave:
9006121Snate@binkert.org            print("KVM on x86 requires xsave support in kernel headers.")
9015863Snate@binkert.org            return False
9023546Sgblack@eecs.umich.edu
9033546Sgblack@eecs.umich.edu        return True
9043546Sgblack@eecs.umich.edu    else:
9053546Sgblack@eecs.umich.edu        return False
9064781Snate@binkert.org
9074781Snate@binkert.org
9086658Snate@binkert.org# Check if the exclude_host attribute is available. We want this to
9096658Snate@binkert.org# get accurate instruction counts in KVM.
9104781Snate@binkert.orgmain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
9113546Sgblack@eecs.umich.edu    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
9123546Sgblack@eecs.umich.edu
9133546Sgblack@eecs.umich.edu
9143546Sgblack@eecs.umich.edu######################################################################
9157756SAli.Saidi@ARM.com#
9167816Ssteve.reinhardt@amd.com# Finish the configuration
9173546Sgblack@eecs.umich.edu#
9183546Sgblack@eecs.umich.edumain = conf.Finish()
9193546Sgblack@eecs.umich.edu
9203546Sgblack@eecs.umich.edu######################################################################
9214202Sbinkertn@umich.edu#
9223546Sgblack@eecs.umich.edu# Collect all non-global variables
9233546Sgblack@eecs.umich.edu#
9243546Sgblack@eecs.umich.edu
925955SN/A# Define the universe of supported ISAs
926955SN/Aall_isa_list = [ ]
927955SN/Aall_gpu_isa_list = [ ]
928955SN/AExport('all_isa_list')
9295863Snate@binkert.orgExport('all_gpu_isa_list')
9305863Snate@binkert.org
9315343Sstever@gmail.comclass CpuModel(object):
9325343Sstever@gmail.com    '''The CpuModel class encapsulates everything the ISA parser needs to
9336121Snate@binkert.org    know about a particular CPU model.'''
9345863Snate@binkert.org
9354773Snate@binkert.org    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
9365863Snate@binkert.org    dict = {}
9372632Sstever@eecs.umich.edu
9385863Snate@binkert.org    # Constructor.  Automatically adds models to CpuModel.dict.
9392023SN/A    def __init__(self, name, default=False):
9405863Snate@binkert.org        self.name = name           # name of model
9415863Snate@binkert.org
9425863Snate@binkert.org        # This cpu is enabled by default
9435863Snate@binkert.org        self.default = default
9445863Snate@binkert.org
9455863Snate@binkert.org        # Add self to dict
9465863Snate@binkert.org        if name in CpuModel.dict:
9475863Snate@binkert.org            raise AttributeError, "CpuModel '%s' already registered" % name
9485863Snate@binkert.org        CpuModel.dict[name] = self
9492632Sstever@eecs.umich.edu
9505863Snate@binkert.orgExport('CpuModel')
9512023SN/A
9522632Sstever@eecs.umich.edu# Sticky variables get saved in the variables file so they persist from
9535863Snate@binkert.org# one invocation to the next (unless overridden, in which case the new
9545342Sstever@gmail.com# value becomes sticky).
9555863Snate@binkert.orgsticky_vars = Variables(args=ARGUMENTS)
9562632Sstever@eecs.umich.eduExport('sticky_vars')
9575863Snate@binkert.org
9585863Snate@binkert.org# Sticky variables that should be exported
9598267Ssteve.reinhardt@amd.comexport_vars = []
9608120Sgblack@eecs.umich.eduExport('export_vars')
9618267Ssteve.reinhardt@amd.com
9628267Ssteve.reinhardt@amd.com# For Ruby
9638267Ssteve.reinhardt@amd.comall_protocols = []
9648267Ssteve.reinhardt@amd.comExport('all_protocols')
9658267Ssteve.reinhardt@amd.comprotocol_dirs = []
9668267Ssteve.reinhardt@amd.comExport('protocol_dirs')
9678267Ssteve.reinhardt@amd.comslicc_includes = []
9688267Ssteve.reinhardt@amd.comExport('slicc_includes')
9698267Ssteve.reinhardt@amd.com
9705863Snate@binkert.org# Walk the tree and execute all SConsopts scripts that wil add to the
9715863Snate@binkert.org# above variables
9725863Snate@binkert.orgif GetOption('verbose'):
9732632Sstever@eecs.umich.edu    print("Reading SConsopts")
9748267Ssteve.reinhardt@amd.comfor bdir in [ base_dir ] + extras_dir_list:
9758267Ssteve.reinhardt@amd.com    if not isdir(bdir):
9768267Ssteve.reinhardt@amd.com        print("Error: directory '%s' does not exist" % bdir)
9772632Sstever@eecs.umich.edu        Exit(1)
9781888SN/A    for root, dirs, files in os.walk(bdir):
9795863Snate@binkert.org        if 'SConsopts' in files:
9805863Snate@binkert.org            if GetOption('verbose'):
9811858SN/A                print("Reading", joinpath(root, 'SConsopts'))
9828120Sgblack@eecs.umich.edu            SConscript(joinpath(root, 'SConsopts'))
9838120Sgblack@eecs.umich.edu
9847756SAli.Saidi@ARM.comall_isa_list.sort()
9852598SN/Aall_gpu_isa_list.sort()
9865863Snate@binkert.org
9871858SN/Asticky_vars.AddVariables(
9881858SN/A    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
9891858SN/A    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
9905863Snate@binkert.org    ListVariable('CPU_MODELS', 'CPU models',
9911858SN/A                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
9921858SN/A                 sorted(CpuModel.dict.keys())),
9931858SN/A    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
9945863Snate@binkert.org                 False),
9951871SN/A    BoolVariable('SS_COMPATIBLE_FP',
9961858SN/A                 'Make floating-point results compatible with SimpleScalar',
9971858SN/A                 False),
9981858SN/A    BoolVariable('USE_SSE2',
9991858SN/A                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
10005863Snate@binkert.org                 False),
10015863Snate@binkert.org    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
10021869SN/A    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
10031965SN/A    BoolVariable('USE_PNG',  'Enable support for PNG images', have_png),
10047739Sgblack@eecs.umich.edu    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability',
10051965SN/A                 False),
10062761Sstever@eecs.umich.edu    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models',
10075863Snate@binkert.org                 have_kvm),
10081869SN/A    BoolVariable('USE_TUNTAP',
10095863Snate@binkert.org                 'Enable using a tap device to bridge to the host network',
10102667Sstever@eecs.umich.edu                 have_tuntap),
10111869SN/A    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
10121869SN/A    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
10132929Sktlim@umich.edu                  all_protocols),
10142929Sktlim@umich.edu    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
10155863Snate@binkert.org                 backtrace_impls[-1], backtrace_impls)
10162929Sktlim@umich.edu    )
1017955SN/A
10188120Sgblack@eecs.umich.edu# These variables get exported to #defines in config/*.hh (see src/SConscript).
10198120Sgblack@eecs.umich.eduexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
10208120Sgblack@eecs.umich.edu                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
10218120Sgblack@eecs.umich.edu                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_VALGRIND',
10228120Sgblack@eecs.umich.edu                'HAVE_PERF_ATTR_EXCLUDE_HOST', 'USE_PNG']
10238120Sgblack@eecs.umich.edu
10248120Sgblack@eecs.umich.edu###################################################
10258120Sgblack@eecs.umich.edu#
10268120Sgblack@eecs.umich.edu# Define a SCons builder for configuration flag headers.
10278120Sgblack@eecs.umich.edu#
10288120Sgblack@eecs.umich.edu###################################################
10298120Sgblack@eecs.umich.edu
1030# This function generates a config header file that #defines the
1031# variable symbol to the current variable setting (0 or 1).  The source
1032# operands are the name of the variable and a Value node containing the
1033# value of the variable.
1034def build_config_file(target, source, env):
1035    (variable, value) = [s.get_contents() for s in source]
1036    f = file(str(target[0]), 'w')
1037    print('#define', variable, value, file=f)
1038    f.close()
1039    return None
1040
1041# Combine the two functions into a scons Action object.
1042config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1043
1044# The emitter munges the source & target node lists to reflect what
1045# we're really doing.
1046def config_emitter(target, source, env):
1047    # extract variable name from Builder arg
1048    variable = str(target[0])
1049    # True target is config header file
1050    target = joinpath('config', variable.lower() + '.hh')
1051    val = env[variable]
1052    if isinstance(val, bool):
1053        # Force value to 0/1
1054        val = int(val)
1055    elif isinstance(val, str):
1056        val = '"' + val + '"'
1057
1058    # Sources are variable name & value (packaged in SCons Value nodes)
1059    return ([target], [Value(variable), Value(val)])
1060
1061config_builder = Builder(emitter = config_emitter, action = config_action)
1062
1063main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1064
1065###################################################
1066#
1067# Builders for static and shared partially linked object files.
1068#
1069###################################################
1070
1071partial_static_builder = Builder(action=SCons.Defaults.LinkAction,
1072                                 src_suffix='$OBJSUFFIX',
1073                                 src_builder=['StaticObject', 'Object'],
1074                                 LINKFLAGS='$PLINKFLAGS',
1075                                 LIBS='')
1076
1077def partial_shared_emitter(target, source, env):
1078    for tgt in target:
1079        tgt.attributes.shared = 1
1080    return (target, source)
1081partial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
1082                                 emitter=partial_shared_emitter,
1083                                 src_suffix='$SHOBJSUFFIX',
1084                                 src_builder='SharedObject',
1085                                 SHLINKFLAGS='$PSHLINKFLAGS',
1086                                 LIBS='')
1087
1088main.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
1089                         'PartialStatic' : partial_static_builder })
1090
1091def add_local_rpath(env, *targets):
1092    '''Set up an RPATH for a library which lives in the build directory.
1093
1094    The construction environment variable BIN_RPATH_PREFIX should be set to
1095    the relative path of the build directory starting from the location of the
1096    binary.'''
1097    for target in targets:
1098        target = env.Entry(target)
1099        if not target.isdir():
1100            target = target.dir
1101        relpath = os.path.relpath(target.abspath, env['BUILDDIR'])
1102        components = [
1103            '\\$$ORIGIN',
1104            '${BIN_RPATH_PREFIX}',
1105            relpath
1106        ]
1107        env.Append(RPATH=[env.Literal(os.path.join(*components))])
1108
1109if sys.platform != "darwin":
1110    main.Append(LINKFLAGS=Split('-z origin'))
1111
1112main.AddMethod(add_local_rpath, 'AddLocalRPATH')
1113
1114# builds in ext are shared across all configs in the build root.
1115ext_dir = abspath(joinpath(str(main.root), 'ext'))
1116ext_build_dirs = []
1117for root, dirs, files in os.walk(ext_dir):
1118    if 'SConscript' in files:
1119        build_dir = os.path.relpath(root, ext_dir)
1120        ext_build_dirs.append(build_dir)
1121        main.SConscript(joinpath(root, 'SConscript'),
1122                        variant_dir=joinpath(build_root, build_dir))
1123
1124gdb_xml_dir = joinpath(ext_dir, 'gdb-xml')
1125Export('gdb_xml_dir')
1126
1127main.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
1128
1129###################################################
1130#
1131# This builder and wrapper method are used to set up a directory with
1132# switching headers. Those are headers which are in a generic location and
1133# that include more specific headers from a directory chosen at build time
1134# based on the current build settings.
1135#
1136###################################################
1137
1138def build_switching_header(target, source, env):
1139    path = str(target[0])
1140    subdir = str(source[0])
1141    dp, fp = os.path.split(path)
1142    dp = os.path.relpath(os.path.realpath(dp),
1143                         os.path.realpath(env['BUILDDIR']))
1144    with open(path, 'w') as hdr:
1145        print('#include "%s/%s/%s"' % (dp, subdir, fp), file=hdr)
1146
1147switching_header_action = MakeAction(build_switching_header,
1148                                     Transform('GENERATE'))
1149
1150switching_header_builder = Builder(action=switching_header_action,
1151                                   source_factory=Value,
1152                                   single_source=True)
1153
1154main.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
1155
1156def switching_headers(self, headers, source):
1157    for header in headers:
1158        self.SwitchingHeader(header, source)
1159
1160main.AddMethod(switching_headers, 'SwitchingHeaders')
1161
1162###################################################
1163#
1164# Define build environments for selected configurations.
1165#
1166###################################################
1167
1168for variant_path in variant_paths:
1169    if not GetOption('silent'):
1170        print("Building in", variant_path)
1171
1172    # Make a copy of the build-root environment to use for this config.
1173    env = main.Clone()
1174    env['BUILDDIR'] = variant_path
1175
1176    # variant_dir is the tail component of build path, and is used to
1177    # determine the build parameters (e.g., 'ALPHA_SE')
1178    (build_root, variant_dir) = splitpath(variant_path)
1179
1180    # Set env variables according to the build directory config.
1181    sticky_vars.files = []
1182    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1183    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1184    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1185    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1186    if isfile(current_vars_file):
1187        sticky_vars.files.append(current_vars_file)
1188        if not GetOption('silent'):
1189            print("Using saved variables file %s" % current_vars_file)
1190    elif variant_dir in ext_build_dirs:
1191        # Things in ext are built without a variant directory.
1192        continue
1193    else:
1194        # Build dir-specific variables file doesn't exist.
1195
1196        # Make sure the directory is there so we can create it later
1197        opt_dir = dirname(current_vars_file)
1198        if not isdir(opt_dir):
1199            mkdir(opt_dir)
1200
1201        # Get default build variables from source tree.  Variables are
1202        # normally determined by name of $VARIANT_DIR, but can be
1203        # overridden by '--default=' arg on command line.
1204        default = GetOption('default')
1205        opts_dir = joinpath(main.root.abspath, 'build_opts')
1206        if default:
1207            default_vars_files = [joinpath(build_root, 'variables', default),
1208                                  joinpath(opts_dir, default)]
1209        else:
1210            default_vars_files = [joinpath(opts_dir, variant_dir)]
1211        existing_files = filter(isfile, default_vars_files)
1212        if existing_files:
1213            default_vars_file = existing_files[0]
1214            sticky_vars.files.append(default_vars_file)
1215            print("Variables file %s not found,\n  using defaults in %s"
1216                  % (current_vars_file, default_vars_file))
1217        else:
1218            print("Error: cannot find variables file %s or "
1219                  "default file(s) %s"
1220                  % (current_vars_file, ' or '.join(default_vars_files)))
1221            Exit(1)
1222
1223    # Apply current variable settings to env
1224    sticky_vars.Update(env)
1225
1226    help_texts["local_vars"] += \
1227        "Build variables for %s:\n" % variant_dir \
1228                 + sticky_vars.GenerateHelpText(env)
1229
1230    # Process variable settings.
1231
1232    if not have_fenv and env['USE_FENV']:
1233        print("Warning: <fenv.h> not available; "
1234              "forcing USE_FENV to False in", variant_dir + ".")
1235        env['USE_FENV'] = False
1236
1237    if not env['USE_FENV']:
1238        print("Warning: No IEEE FP rounding mode control in",
1239              variant_dir + ".")
1240        print("         FP results may deviate slightly from other platforms.")
1241
1242    if not have_png and env['USE_PNG']:
1243        print("Warning: <png.h> not available; "
1244              "forcing USE_PNG to False in", variant_dir + ".")
1245        env['USE_PNG'] = False
1246
1247    if env['USE_PNG']:
1248        env.Append(LIBS=['png'])
1249
1250    if env['EFENCE']:
1251        env.Append(LIBS=['efence'])
1252
1253    if env['USE_KVM']:
1254        if not have_kvm:
1255            print("Warning: Can not enable KVM, host seems to "
1256                  "lack KVM support")
1257            env['USE_KVM'] = False
1258        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1259            print("Info: KVM support disabled due to unsupported host and "
1260                  "target ISA combination")
1261            env['USE_KVM'] = False
1262
1263    if env['USE_TUNTAP']:
1264        if not have_tuntap:
1265            print("Warning: Can't connect EtherTap with a tap device.")
1266            env['USE_TUNTAP'] = False
1267
1268    if env['BUILD_GPU']:
1269        env.Append(CPPDEFINES=['BUILD_GPU'])
1270
1271    # Warn about missing optional functionality
1272    if env['USE_KVM']:
1273        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1274            print("Warning: perf_event headers lack support for the "
1275                  "exclude_host attribute. KVM instruction counts will "
1276                  "be inaccurate.")
1277
1278    # Save sticky variable settings back to current variables file
1279    sticky_vars.Save(current_vars_file, env)
1280
1281    if env['USE_SSE2']:
1282        env.Append(CCFLAGS=['-msse2'])
1283
1284    # The src/SConscript file sets up the build rules in 'env' according
1285    # to the configured variables.  It returns a list of environments,
1286    # one for each variant build (debug, opt, etc.)
1287    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1288
1289# base help text
1290Help('''
1291Usage: scons [scons options] [build variables] [target(s)]
1292
1293Extra scons options:
1294%(options)s
1295
1296Global build variables:
1297%(global_vars)s
1298
1299%(local_vars)s
1300''' % help_texts)
1301