SConstruct revision 13713
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.com# Each target must have 'build' in the interior of the path; the
2198336Ssteve.reinhardt@amd.com# directory below this will determine the build parameters.  For
2208336Ssteve.reinhardt@amd.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2218336Ssteve.reinhardt@amd.com# recognize that ALPHA_SE specifies the configuration because it
2228336Ssteve.reinhardt@amd.com# follow 'build' in the build path.
2238336Ssteve.reinhardt@amd.com
2245871Snate@binkert.org# The funky assignment to "[:]" is needed to replace the list contents
2255871Snate@binkert.org# in place rather than reassign the symbol to a new list, which
2268336Ssteve.reinhardt@amd.com# doesn't work (obviously!).
2278336Ssteve.reinhardt@amd.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
2288336Ssteve.reinhardt@amd.com
2298336Ssteve.reinhardt@amd.com# Generate a list of the unique build roots and configs that the
2308336Ssteve.reinhardt@amd.com# collected targets reference.
2315871Snate@binkert.orgvariant_paths = []
2328336Ssteve.reinhardt@amd.combuild_root = None
2338336Ssteve.reinhardt@amd.comfor t in BUILD_TARGETS:
2348336Ssteve.reinhardt@amd.com    path_dirs = t.split('/')
2358336Ssteve.reinhardt@amd.com    try:
2368336Ssteve.reinhardt@amd.com        build_top = rfind(path_dirs, 'build', -2)
2374678Snate@binkert.org    except:
2385871Snate@binkert.org        print("Error: no non-leaf 'build' dir found on target path", t)
2394678Snate@binkert.org        Exit(1)
2408336Ssteve.reinhardt@amd.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2418336Ssteve.reinhardt@amd.com    if not build_root:
2428336Ssteve.reinhardt@amd.com        build_root = this_build_root
2438336Ssteve.reinhardt@amd.com    else:
2448336Ssteve.reinhardt@amd.com        if this_build_root != build_root:
2458336Ssteve.reinhardt@amd.com            print("Error: build targets not under same build root\n"
2468336Ssteve.reinhardt@amd.com                  "  %s\n  %s" % (build_root, this_build_root))
2478336Ssteve.reinhardt@amd.com            Exit(1)
2488336Ssteve.reinhardt@amd.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
2498336Ssteve.reinhardt@amd.com    if variant_path not in variant_paths:
2508336Ssteve.reinhardt@amd.com        variant_paths.append(variant_path)
2518336Ssteve.reinhardt@amd.com
2528336Ssteve.reinhardt@amd.com# Make sure build_root exists (might not if this is the first build there)
2538336Ssteve.reinhardt@amd.comif not isdir(build_root):
2548336Ssteve.reinhardt@amd.com    mkdir(build_root)
2558336Ssteve.reinhardt@amd.commain['BUILDROOT'] = build_root
2568336Ssteve.reinhardt@amd.com
2575871Snate@binkert.orgExport('main')
2586121Snate@binkert.org
259955SN/Amain.SConsignFile(joinpath(build_root, "sconsign"))
260955SN/A
2612632Sstever@eecs.umich.edu# Default duplicate option is to use hard links, but this messes up
2622632Sstever@eecs.umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
263955SN/A# file to file~ then copies to file, breaking the link.  Symbolic
264955SN/A# (soft) links work better.
265955SN/Amain.SetOption('duplicate', 'soft-copy')
266955SN/A
2675863Snate@binkert.org#
268955SN/A# Set up global sticky variables... these are common to an entire build
2692632Sstever@eecs.umich.edu# tree (not specific to a particular build like ALPHA_SE)
2702632Sstever@eecs.umich.edu#
2712632Sstever@eecs.umich.edu
2722632Sstever@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
2732632Sstever@eecs.umich.edu
2742632Sstever@eecs.umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
2752632Sstever@eecs.umich.edu
2768268Ssteve.reinhardt@amd.comglobal_vars.AddVariables(
2778268Ssteve.reinhardt@amd.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
2788268Ssteve.reinhardt@amd.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
2798268Ssteve.reinhardt@amd.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
2808268Ssteve.reinhardt@amd.com    ('BATCH', 'Use batch pool for build and tests', False),
2818268Ssteve.reinhardt@amd.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
2828268Ssteve.reinhardt@amd.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
2832632Sstever@eecs.umich.edu    ('EXTRAS', 'Add extra directories to the compilation', '')
2842632Sstever@eecs.umich.edu    )
2852632Sstever@eecs.umich.edu
2862632Sstever@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
2878268Ssteve.reinhardt@amd.comglobal_vars.Update(main)
2882632Sstever@eecs.umich.eduhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
2898268Ssteve.reinhardt@amd.com
2908268Ssteve.reinhardt@amd.com# Save sticky variable settings back to current variables file
2918268Ssteve.reinhardt@amd.comglobal_vars.Save(global_vars_file, main)
2928268Ssteve.reinhardt@amd.com
2933718Sstever@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
2942634Sstever@eecs.umich.edu# look for sources etc.  This list is exported as extras_dir_list.
2952634Sstever@eecs.umich.edubase_dir = main.srcdir.abspath
2965863Snate@binkert.orgif main['EXTRAS']:
2972638Sstever@eecs.umich.edu    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
2988268Ssteve.reinhardt@amd.comelse:
2992632Sstever@eecs.umich.edu    extras_dir_list = []
3002632Sstever@eecs.umich.edu
3012632Sstever@eecs.umich.eduExport('base_dir')
3022632Sstever@eecs.umich.eduExport('extras_dir_list')
3032632Sstever@eecs.umich.edu
3041858SN/A# the ext directory should be on the #includes path
3053716Sstever@eecs.umich.edumain.Append(CPPPATH=[Dir('ext')])
3062638Sstever@eecs.umich.edu
3072638Sstever@eecs.umich.edu# Add shared top-level headers
3082638Sstever@eecs.umich.edumain.Prepend(CPPPATH=Dir('include'))
3092638Sstever@eecs.umich.edu
3102638Sstever@eecs.umich.eduif GetOption('verbose'):
3112638Sstever@eecs.umich.edu    def MakeAction(action, string, *args, **kwargs):
3122638Sstever@eecs.umich.edu        return Action(action, *args, **kwargs)
3135863Snate@binkert.orgelse:
3145863Snate@binkert.org    MakeAction = Action
3155863Snate@binkert.org    main['CCCOMSTR']        = Transform("CC")
316955SN/A    main['CXXCOMSTR']       = Transform("CXX")
3175341Sstever@gmail.com    main['ASCOMSTR']        = Transform("AS")
3185341Sstever@gmail.com    main['ARCOMSTR']        = Transform("AR", 0)
3195863Snate@binkert.org    main['LINKCOMSTR']      = Transform("LINK", 0)
3207756SAli.Saidi@ARM.com    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
3215341Sstever@gmail.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
3226121Snate@binkert.org    main['M4COMSTR']        = Transform("M4")
3234494Ssaidi@eecs.umich.edu    main['SHCCCOMSTR']      = Transform("SHCC")
3246121Snate@binkert.org    main['SHCXXCOMSTR']     = Transform("SHCXX")
3251105SN/AExport('MakeAction')
3262667Sstever@eecs.umich.edu
3272667Sstever@eecs.umich.edu# Initialize the Link-Time Optimization (LTO) flags
3282667Sstever@eecs.umich.edumain['LTO_CCFLAGS'] = []
3292667Sstever@eecs.umich.edumain['LTO_LDFLAGS'] = []
3306121Snate@binkert.org
3312667Sstever@eecs.umich.edu# According to the readme, tcmalloc works best if the compiler doesn't
3325341Sstever@gmail.com# assume that we're using the builtin malloc and friends. These flags
3335863Snate@binkert.org# are compiler-specific, so we need to set them after we detect which
3345341Sstever@gmail.com# compiler we're using.
3355341Sstever@gmail.commain['TCMALLOC_CCFLAGS'] = []
3365341Sstever@gmail.com
3378120Sgblack@eecs.umich.eduCXX_version = readCommand([main['CXX'],'--version'], exception=False)
3385341Sstever@gmail.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
3398120Sgblack@eecs.umich.edu
3405341Sstever@gmail.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3418120Sgblack@eecs.umich.edumain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
3426121Snate@binkert.orgif main['GCC'] + main['CLANG'] > 1:
3436121Snate@binkert.org    print('Error: How can we have two at the same time?')
3445397Ssaidi@eecs.umich.edu    Exit(1)
3455397Ssaidi@eecs.umich.edu
3467727SAli.Saidi@ARM.com# Set up default C++ compiler flags
3478268Ssteve.reinhardt@amd.comif main['GCC'] or main['CLANG']:
3486168Snate@binkert.org    # As gcc and clang share many flags, do the common parts here
3495341Sstever@gmail.com    main.Append(CCFLAGS=['-pipe'])
3508120Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
3518120Sgblack@eecs.umich.edu    # Enable -Wall and -Wextra and then disable the few warnings that
3528120Sgblack@eecs.umich.edu    # we consistently violate
3536814Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
3545863Snate@binkert.org                         '-Wno-sign-compare', '-Wno-unused-parameter'])
3558120Sgblack@eecs.umich.edu    # We always compile using C++11
3565341Sstever@gmail.com    main.Append(CXXFLAGS=['-std=c++11'])
3575863Snate@binkert.org    if sys.platform.startswith('freebsd'):
3588268Ssteve.reinhardt@amd.com        main.Append(CCFLAGS=['-I/usr/local/include'])
3596121Snate@binkert.org        main.Append(CXXFLAGS=['-I/usr/local/include'])
3606121Snate@binkert.org
3618268Ssteve.reinhardt@amd.com    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
3625742Snate@binkert.org    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
3635742Snate@binkert.org    if GetOption('gold_linker'):
3645341Sstever@gmail.com        main.Append(LINKFLAGS='-fuse-ld=gold')
3655742Snate@binkert.org    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
3665742Snate@binkert.org    shared_partial_flags = ['-r', '-nostdlib']
3675341Sstever@gmail.com    main.Append(PSHLINKFLAGS=shared_partial_flags)
3686017Snate@binkert.org    main.Append(PLINKFLAGS=shared_partial_flags)
3696121Snate@binkert.org
3706017Snate@binkert.org    # Treat warnings as errors but white list some warnings that we
3717816Ssteve.reinhardt@amd.com    # want to allow (e.g., deprecation warnings).
3727756SAli.Saidi@ARM.com    main.Append(CCFLAGS=['-Werror',
3737756SAli.Saidi@ARM.com                         '-Wno-error=deprecated-declarations',
3747756SAli.Saidi@ARM.com                         '-Wno-error=deprecated',
3757756SAli.Saidi@ARM.com                        ])
3767756SAli.Saidi@ARM.comelse:
3777756SAli.Saidi@ARM.com    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
3787756SAli.Saidi@ARM.com    print("Don't know what compiler options to use for your compiler.")
3797756SAli.Saidi@ARM.com    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
3807816Ssteve.reinhardt@amd.com    print(termcap.Yellow + '       version:' + termcap.Normal, end = ' ')
3817816Ssteve.reinhardt@amd.com    if not CXX_version:
3827816Ssteve.reinhardt@amd.com        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
3837816Ssteve.reinhardt@amd.com              termcap.Normal)
3847816Ssteve.reinhardt@amd.com    else:
3857816Ssteve.reinhardt@amd.com        print(CXX_version.replace('\n', '<nl>'))
3867816Ssteve.reinhardt@amd.com    print("       If you're trying to use a compiler other than GCC")
3877816Ssteve.reinhardt@amd.com    print("       or clang, there appears to be something wrong with your")
3887816Ssteve.reinhardt@amd.com    print("       environment.")
3897816Ssteve.reinhardt@amd.com    print("       ")
3907756SAli.Saidi@ARM.com    print("       If you are trying to use a compiler other than those listed")
3917816Ssteve.reinhardt@amd.com    print("       above you will need to ease fix SConstruct and ")
3927816Ssteve.reinhardt@amd.com    print("       src/SConscript to support that compiler.")
3937816Ssteve.reinhardt@amd.com    Exit(1)
3947816Ssteve.reinhardt@amd.com
3957816Ssteve.reinhardt@amd.comif main['GCC']:
3967816Ssteve.reinhardt@amd.com    # Check for a supported version of gcc. >= 4.8 is chosen for its
3977816Ssteve.reinhardt@amd.com    # level of c++11 support. See
3987816Ssteve.reinhardt@amd.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
3997816Ssteve.reinhardt@amd.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
4007816Ssteve.reinhardt@amd.com    if compareVersions(gcc_version, "4.8") < 0:
4017816Ssteve.reinhardt@amd.com        print('Error: gcc version 4.8 or newer required.')
4027816Ssteve.reinhardt@amd.com        print('       Installed version: ', gcc_version)
4037816Ssteve.reinhardt@amd.com        Exit(1)
4047816Ssteve.reinhardt@amd.com
4057816Ssteve.reinhardt@amd.com    main['GCC_VERSION'] = gcc_version
4067816Ssteve.reinhardt@amd.com
4077816Ssteve.reinhardt@amd.com    if compareVersions(gcc_version, '4.9') >= 0:
4087816Ssteve.reinhardt@amd.com        # Incremental linking with LTO is currently broken in gcc versions
4097816Ssteve.reinhardt@amd.com        # 4.9 and above. A version where everything works completely hasn't
4107816Ssteve.reinhardt@amd.com        # yet been identified.
4117816Ssteve.reinhardt@amd.com        #
4127816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
4137816Ssteve.reinhardt@amd.com        main['BROKEN_INCREMENTAL_LTO'] = True
4147816Ssteve.reinhardt@amd.com    if compareVersions(gcc_version, '6.0') >= 0:
4157816Ssteve.reinhardt@amd.com        # gcc versions 6.0 and greater accept an -flinker-output flag which
4167816Ssteve.reinhardt@amd.com        # selects what type of output the linker should generate. This is
4177816Ssteve.reinhardt@amd.com        # necessary for incremental lto to work, but is also broken in
4187816Ssteve.reinhardt@amd.com        # current versions of gcc. It may not be necessary in future
4197816Ssteve.reinhardt@amd.com        # versions. We add it here since it might be, and as a reminder that
4207816Ssteve.reinhardt@amd.com        # it exists. It's excluded if lto is being forced.
4217816Ssteve.reinhardt@amd.com        #
4227816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/gcc-6/changes.html
4237816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
4247816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
4257816Ssteve.reinhardt@amd.com        if not GetOption('force_lto'):
4267816Ssteve.reinhardt@amd.com            main.Append(PSHLINKFLAGS='-flinker-output=rel')
4277816Ssteve.reinhardt@amd.com            main.Append(PLINKFLAGS='-flinker-output=rel')
4287816Ssteve.reinhardt@amd.com
4297816Ssteve.reinhardt@amd.com    # Make sure we warn if the user has requested to compile with the
4307816Ssteve.reinhardt@amd.com    # Undefined Benahvior Sanitizer and this version of gcc does not
4317816Ssteve.reinhardt@amd.com    # support it.
4327816Ssteve.reinhardt@amd.com    if GetOption('with_ubsan') and \
4337816Ssteve.reinhardt@amd.com            compareVersions(gcc_version, '4.9') < 0:
4347816Ssteve.reinhardt@amd.com        print(termcap.Yellow + termcap.Bold +
4357816Ssteve.reinhardt@amd.com            'Warning: UBSan is only supported using gcc 4.9 and later.' +
4367816Ssteve.reinhardt@amd.com            termcap.Normal)
4377816Ssteve.reinhardt@amd.com
4387816Ssteve.reinhardt@amd.com    disable_lto = GetOption('no_lto')
4397816Ssteve.reinhardt@amd.com    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
4407816Ssteve.reinhardt@amd.com            not GetOption('force_lto'):
4417816Ssteve.reinhardt@amd.com        print(termcap.Yellow + termcap.Bold +
4427816Ssteve.reinhardt@amd.com            'Warning: Your compiler doesn\'t support incremental linking' +
4437816Ssteve.reinhardt@amd.com            ' and lto at the same time, so lto is being disabled. To force' +
4447816Ssteve.reinhardt@amd.com            ' lto on anyway, use the --force-lto option. That will disable' +
4457816Ssteve.reinhardt@amd.com            ' partial linking.' +
4467816Ssteve.reinhardt@amd.com            termcap.Normal)
4477816Ssteve.reinhardt@amd.com        disable_lto = True
4487816Ssteve.reinhardt@amd.com
4497816Ssteve.reinhardt@amd.com    # Add the appropriate Link-Time Optimization (LTO) flags
4507816Ssteve.reinhardt@amd.com    # unless LTO is explicitly turned off. Note that these flags
4517816Ssteve.reinhardt@amd.com    # are only used by the fast target.
4527756SAli.Saidi@ARM.com    if not disable_lto:
4538120Sgblack@eecs.umich.edu        # Pass the LTO flag when compiling to produce GIMPLE
4547756SAli.Saidi@ARM.com        # output, we merely create the flags here and only append
4557756SAli.Saidi@ARM.com        # them later
4567756SAli.Saidi@ARM.com        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4577756SAli.Saidi@ARM.com
4587816Ssteve.reinhardt@amd.com        # Use the same amount of jobs for LTO as we are running
4597816Ssteve.reinhardt@amd.com        # scons with
4607816Ssteve.reinhardt@amd.com        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4617816Ssteve.reinhardt@amd.com
4627816Ssteve.reinhardt@amd.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
4637816Ssteve.reinhardt@amd.com                                  '-fno-builtin-realloc', '-fno-builtin-free'])
4647816Ssteve.reinhardt@amd.com
4657816Ssteve.reinhardt@amd.com    # The address sanitizer is available for gcc >= 4.8
4667816Ssteve.reinhardt@amd.com    if GetOption('with_asan'):
4677816Ssteve.reinhardt@amd.com        if GetOption('with_ubsan') and \
4687756SAli.Saidi@ARM.com                compareVersions(main['GCC_VERSION'], '4.9') >= 0:
4697756SAli.Saidi@ARM.com            main.Append(CCFLAGS=['-fsanitize=address,undefined',
4706654Snate@binkert.org                                 '-fno-omit-frame-pointer'],
4716654Snate@binkert.org                        LINKFLAGS='-fsanitize=address,undefined')
4725871Snate@binkert.org        else:
4736121Snate@binkert.org            main.Append(CCFLAGS=['-fsanitize=address',
4746121Snate@binkert.org                                 '-fno-omit-frame-pointer'],
4756121Snate@binkert.org                        LINKFLAGS='-fsanitize=address')
4766121Snate@binkert.org    # Only gcc >= 4.9 supports UBSan, so check both the version
4773940Ssaidi@eecs.umich.edu    # and the command-line option before adding the compiler and
4783918Ssaidi@eecs.umich.edu    # linker flags.
4793918Ssaidi@eecs.umich.edu    elif GetOption('with_ubsan') and \
4801858SN/A            compareVersions(main['GCC_VERSION'], '4.9') >= 0:
4816121Snate@binkert.org        main.Append(CCFLAGS='-fsanitize=undefined')
4827739Sgblack@eecs.umich.edu        main.Append(LINKFLAGS='-fsanitize=undefined')
4837739Sgblack@eecs.umich.edu
4846143Snate@binkert.orgelif main['CLANG']:
4857739Sgblack@eecs.umich.edu    # Check for a supported version of clang, >= 3.1 is needed to
4867618SAli.Saidi@arm.com    # support similar features as gcc 4.8. See
4877618SAli.Saidi@arm.com    # http://clang.llvm.org/cxx_status.html for details
4887618SAli.Saidi@arm.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
4897618SAli.Saidi@arm.com    clang_version_match = clang_version_re.search(CXX_version)
4907618SAli.Saidi@arm.com    if (clang_version_match):
4917618SAli.Saidi@arm.com        clang_version = clang_version_match.groups()[0]
4927618SAli.Saidi@arm.com        if compareVersions(clang_version, "3.1") < 0:
4937739Sgblack@eecs.umich.edu            print('Error: clang version 3.1 or newer required.')
4946121Snate@binkert.org            print('       Installed version:', clang_version)
4953940Ssaidi@eecs.umich.edu            Exit(1)
4966121Snate@binkert.org    else:
4977739Sgblack@eecs.umich.edu        print('Error: Unable to determine clang version.')
4987739Sgblack@eecs.umich.edu        Exit(1)
4997739Sgblack@eecs.umich.edu
5007739Sgblack@eecs.umich.edu    # clang has a few additional warnings that we disable, extraneous
5017739Sgblack@eecs.umich.edu    # parantheses are allowed due to Ruby's printing of the AST,
5027739Sgblack@eecs.umich.edu    # finally self assignments are allowed as the generated CPU code
5033918Ssaidi@eecs.umich.edu    # is relying on this
5043918Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-Wno-parentheses',
5053940Ssaidi@eecs.umich.edu                         '-Wno-self-assign',
5063918Ssaidi@eecs.umich.edu                         # Some versions of libstdc++ (4.8?) seem to
5073918Ssaidi@eecs.umich.edu                         # use struct hash and class hash
5086157Snate@binkert.org                         # interchangeably.
5096157Snate@binkert.org                         '-Wno-mismatched-tags',
5106157Snate@binkert.org                         ])
5116157Snate@binkert.org
5125397Ssaidi@eecs.umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
5135397Ssaidi@eecs.umich.edu
5146121Snate@binkert.org    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
5156121Snate@binkert.org    # opposed to libstdc++, as the later is dated.
5166121Snate@binkert.org    if sys.platform == "darwin":
5176121Snate@binkert.org        main.Append(CXXFLAGS=['-stdlib=libc++'])
5186121Snate@binkert.org        main.Append(LIBS=['c++'])
5196121Snate@binkert.org
5205397Ssaidi@eecs.umich.edu    # On FreeBSD we need libthr.
5211851SN/A    if sys.platform.startswith('freebsd'):
5221851SN/A        main.Append(LIBS=['thr'])
5237739Sgblack@eecs.umich.edu
524955SN/A    # We require clang >= 3.1, so there is no need to check any
5253053Sstever@eecs.umich.edu    # versions here.
5266121Snate@binkert.org    if GetOption('with_ubsan'):
5273053Sstever@eecs.umich.edu        if GetOption('with_asan'):
5283053Sstever@eecs.umich.edu            main.Append(CCFLAGS=['-fsanitize=address,undefined',
5293053Sstever@eecs.umich.edu                                 '-fno-omit-frame-pointer'],
5303053Sstever@eecs.umich.edu                       LINKFLAGS='-fsanitize=address,undefined')
5313053Sstever@eecs.umich.edu        else:
5326654Snate@binkert.org            main.Append(CCFLAGS='-fsanitize=undefined',
5333053Sstever@eecs.umich.edu                        LINKFLAGS='-fsanitize=undefined')
5344742Sstever@eecs.umich.edu
5354742Sstever@eecs.umich.edu    elif GetOption('with_asan'):
5363053Sstever@eecs.umich.edu        main.Append(CCFLAGS=['-fsanitize=address',
5373053Sstever@eecs.umich.edu                             '-fno-omit-frame-pointer'],
5383053Sstever@eecs.umich.edu                   LINKFLAGS='-fsanitize=address')
5393053Sstever@eecs.umich.edu
5406654Snate@binkert.orgelse:
5413053Sstever@eecs.umich.edu    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
5423053Sstever@eecs.umich.edu    print("Don't know what compiler options to use for your compiler.")
5433053Sstever@eecs.umich.edu    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
5443053Sstever@eecs.umich.edu    print(termcap.Yellow + '       version:' + termcap.Normal, end=' ')
5452667Sstever@eecs.umich.edu    if not CXX_version:
5464554Sbinkertn@umich.edu        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
5476121Snate@binkert.org              termcap.Normal)
5482667Sstever@eecs.umich.edu    else:
5494554Sbinkertn@umich.edu        print(CXX_version.replace('\n', '<nl>'))
5504554Sbinkertn@umich.edu    print("       If you're trying to use a compiler other than GCC")
5514554Sbinkertn@umich.edu    print("       or clang, there appears to be something wrong with your")
5526121Snate@binkert.org    print("       environment.")
5534554Sbinkertn@umich.edu    print("       ")
5544554Sbinkertn@umich.edu    print("       If you are trying to use a compiler other than those listed")
5554554Sbinkertn@umich.edu    print("       above you will need to ease fix SConstruct and ")
5564781Snate@binkert.org    print("       src/SConscript to support that compiler.")
5574554Sbinkertn@umich.edu    Exit(1)
5584554Sbinkertn@umich.edu
5592667Sstever@eecs.umich.edu# Set up common yacc/bison flags (needed for Ruby)
5604554Sbinkertn@umich.edumain['YACCFLAGS'] = '-d'
5614554Sbinkertn@umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
5624554Sbinkertn@umich.edu
5634554Sbinkertn@umich.edu# Do this after we save setting back, or else we'll tack on an
5642667Sstever@eecs.umich.edu# extra 'qdo' every time we run scons.
5654554Sbinkertn@umich.eduif main['BATCH']:
5662667Sstever@eecs.umich.edu    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
5674554Sbinkertn@umich.edu    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
5686121Snate@binkert.org    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
5692667Sstever@eecs.umich.edu    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
5705522Snate@binkert.org    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
5715522Snate@binkert.org
5725522Snate@binkert.orgif sys.platform == 'cygwin':
5735522Snate@binkert.org    # cygwin has some header file issues...
5745522Snate@binkert.org    main.Append(CCFLAGS=["-Wno-uninitialized"])
5755522Snate@binkert.org
5765522Snate@binkert.org# Check for the protobuf compiler
5775522Snate@binkert.orgprotoc_version = readCommand([main['PROTOC'], '--version'],
5785522Snate@binkert.org                             exception='').split()
5795522Snate@binkert.org
5805522Snate@binkert.org# First two words should be "libprotoc x.y.z"
5815522Snate@binkert.orgif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
5825522Snate@binkert.org    print(termcap.Yellow + termcap.Bold +
5835522Snate@binkert.org        'Warning: Protocol buffer compiler (protoc) not found.\n' +
5845522Snate@binkert.org        '         Please install protobuf-compiler for tracing support.' +
5855522Snate@binkert.org        termcap.Normal)
5865522Snate@binkert.org    main['PROTOC'] = False
5875522Snate@binkert.orgelse:
5885522Snate@binkert.org    # Based on the availability of the compress stream wrappers,
5895522Snate@binkert.org    # require 2.1.0
5905522Snate@binkert.org    min_protoc_version = '2.1.0'
5915522Snate@binkert.org    if compareVersions(protoc_version[1], min_protoc_version) < 0:
5925522Snate@binkert.org        print(termcap.Yellow + termcap.Bold +
5935522Snate@binkert.org            'Warning: protoc version', min_protoc_version,
5945522Snate@binkert.org            'or newer required.\n' +
5955522Snate@binkert.org            '         Installed version:', protoc_version[1],
5962638Sstever@eecs.umich.edu            termcap.Normal)
5972638Sstever@eecs.umich.edu        main['PROTOC'] = False
5986121Snate@binkert.org    else:
5993716Sstever@eecs.umich.edu        # Attempt to determine the appropriate include path and
6005522Snate@binkert.org        # library path using pkg-config, that means we also need to
6015522Snate@binkert.org        # check for pkg-config. Note that it is possible to use
6025522Snate@binkert.org        # protobuf without the involvement of pkg-config. Later on we
6035522Snate@binkert.org        # check go a library config check and at that point the test
6045522Snate@binkert.org        # will fail if libprotobuf cannot be found.
6055522Snate@binkert.org        if readCommand(['pkg-config', '--version'], exception=''):
6061858SN/A            try:
6075227Ssaidi@eecs.umich.edu                # Attempt to establish what linking flags to add for protobuf
6085227Ssaidi@eecs.umich.edu                # using pkg-config
6095227Ssaidi@eecs.umich.edu                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
6105227Ssaidi@eecs.umich.edu            except:
6116654Snate@binkert.org                print(termcap.Yellow + termcap.Bold +
6126654Snate@binkert.org                    'Warning: pkg-config could not get protobuf flags.' +
6137769SAli.Saidi@ARM.com                    termcap.Normal)
6147769SAli.Saidi@ARM.com
6157769SAli.Saidi@ARM.com
6167769SAli.Saidi@ARM.com# Check for 'timeout' from GNU coreutils. If present, regressions will
6175227Ssaidi@eecs.umich.edu# be run with a time limit. We require version 8.13 since we rely on
6185227Ssaidi@eecs.umich.edu# support for the '--foreground' option.
6195227Ssaidi@eecs.umich.eduif sys.platform.startswith('freebsd'):
6205204Sstever@gmail.com    timeout_lines = readCommand(['gtimeout', '--version'],
6215204Sstever@gmail.com                                exception='').splitlines()
6225204Sstever@gmail.comelse:
6235204Sstever@gmail.com    timeout_lines = readCommand(['timeout', '--version'],
6245204Sstever@gmail.com                                exception='').splitlines()
6255204Sstever@gmail.com# Get the first line and tokenize it
6265204Sstever@gmail.comtimeout_version = timeout_lines[0].split() if timeout_lines else []
6275204Sstever@gmail.commain['TIMEOUT'] =  timeout_version and \
6285204Sstever@gmail.com    compareVersions(timeout_version[-1], '8.13') >= 0
6295204Sstever@gmail.com
6305204Sstever@gmail.com# Add a custom Check function to test for structure members.
6315204Sstever@gmail.comdef CheckMember(context, include, decl, member, include_quotes="<>"):
6325204Sstever@gmail.com    context.Message("Checking for member %s in %s..." %
6335204Sstever@gmail.com                    (member, decl))
6345204Sstever@gmail.com    text = """
6355204Sstever@gmail.com#include %(header)s
6365204Sstever@gmail.comint main(){
6376121Snate@binkert.org  %(decl)s test;
6385204Sstever@gmail.com  (void)test.%(member)s;
6393118Sstever@eecs.umich.edu  return 0;
6403118Sstever@eecs.umich.edu};
6413118Sstever@eecs.umich.edu""" % { "header" : include_quotes[0] + include + include_quotes[1],
6423118Sstever@eecs.umich.edu        "decl" : decl,
6433118Sstever@eecs.umich.edu        "member" : member,
6445863Snate@binkert.org        }
6453118Sstever@eecs.umich.edu
6465863Snate@binkert.org    ret = context.TryCompile(text, extension=".cc")
6473118Sstever@eecs.umich.edu    context.Result(ret)
6487457Snate@binkert.org    return ret
6497457Snate@binkert.org
6505863Snate@binkert.org# Platform-specific configuration.  Note again that we assume that all
6515863Snate@binkert.org# builds under a given build root run on the same host platform.
6525863Snate@binkert.orgconf = Configure(main,
6535863Snate@binkert.org                 conf_dir = joinpath(build_root, '.scons_config'),
6545863Snate@binkert.org                 log_file = joinpath(build_root, 'scons_config.log'),
6555863Snate@binkert.org                 custom_tests = {
6565863Snate@binkert.org        'CheckMember' : CheckMember,
6576003Snate@binkert.org        })
6585863Snate@binkert.org
6595863Snate@binkert.org# Check if we should compile a 64 bit binary on Mac OS X/Darwin
6605863Snate@binkert.orgtry:
6616120Snate@binkert.org    import platform
6625863Snate@binkert.org    uname = platform.uname()
6635863Snate@binkert.org    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
6645863Snate@binkert.org        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
6656120Snate@binkert.org            main.Append(CCFLAGS=['-arch', 'x86_64'])
6666120Snate@binkert.org            main.Append(CFLAGS=['-arch', 'x86_64'])
6675863Snate@binkert.org            main.Append(LINKFLAGS=['-arch', 'x86_64'])
6685863Snate@binkert.org            main.Append(ASFLAGS=['-arch', 'x86_64'])
6696120Snate@binkert.orgexcept:
6705863Snate@binkert.org    pass
6716121Snate@binkert.org
6726121Snate@binkert.org# Recent versions of scons substitute a "Null" object for Configure()
6735863Snate@binkert.org# when configuration isn't necessary, e.g., if the "--help" option is
6747727SAli.Saidi@ARM.com# present.  Unfortuantely this Null object always returns false,
6757727SAli.Saidi@ARM.com# breaking all our configuration checks.  We replace it with our own
6767727SAli.Saidi@ARM.com# more optimistic null object that returns True instead.
6777727SAli.Saidi@ARM.comif not conf:
6787727SAli.Saidi@ARM.com    def NullCheck(*args, **kwargs):
6797727SAli.Saidi@ARM.com        return True
6805863Snate@binkert.org
6813118Sstever@eecs.umich.edu    class NullConf:
6825863Snate@binkert.org        def __init__(self, env):
6833118Sstever@eecs.umich.edu            self.env = env
6843118Sstever@eecs.umich.edu        def Finish(self):
6855863Snate@binkert.org            return self.env
6865863Snate@binkert.org        def __getattr__(self, mname):
6875863Snate@binkert.org            return NullCheck
6885863Snate@binkert.org
6893118Sstever@eecs.umich.edu    conf = NullConf(main)
6903483Ssaidi@eecs.umich.edu
6913494Ssaidi@eecs.umich.edu# Cache build files in the supplied directory.
6923494Ssaidi@eecs.umich.eduif main['M5_BUILD_CACHE']:
6933483Ssaidi@eecs.umich.edu    print('Using build cache located at', main['M5_BUILD_CACHE'])
6943483Ssaidi@eecs.umich.edu    CacheDir(main['M5_BUILD_CACHE'])
6953483Ssaidi@eecs.umich.edu
6963053Sstever@eecs.umich.edumain['USE_PYTHON'] = not GetOption('without_python')
6973053Sstever@eecs.umich.eduif main['USE_PYTHON']:
6983918Ssaidi@eecs.umich.edu    # Find Python include and library directories for embedding the
6993053Sstever@eecs.umich.edu    # interpreter. We rely on python-config to resolve the appropriate
7003053Sstever@eecs.umich.edu    # includes and linker flags. ParseConfig does not seem to understand
7013053Sstever@eecs.umich.edu    # the more exotic linker flags such as -Xlinker and -export-dynamic so
7023053Sstever@eecs.umich.edu    # we add them explicitly below. If you want to link in an alternate
7033053Sstever@eecs.umich.edu    # version of python, see above for instructions on how to invoke
7047840Snate@binkert.org    # scons with the appropriate PATH set.
7057865Sgblack@eecs.umich.edu    #
7067865Sgblack@eecs.umich.edu    # First we check if python2-config exists, else we use python-config
7077865Sgblack@eecs.umich.edu    python_config = readCommand(['which', 'python2-config'],
7087865Sgblack@eecs.umich.edu                                exception='').strip()
7097865Sgblack@eecs.umich.edu    if not os.path.exists(python_config):
7107840Snate@binkert.org        python_config = readCommand(['which', 'python-config'],
7117840Snate@binkert.org                                    exception='').strip()
7127840Snate@binkert.org    py_includes = readCommand([python_config, '--includes'],
7137840Snate@binkert.org                              exception='').split()
7141858SN/A    py_includes = filter(lambda s: match(r'.*\/include\/.*',s), py_includes)
7151858SN/A    # Strip the -I from the include folders before adding them to the
7161858SN/A    # CPPPATH
7171858SN/A    py_includes = map(lambda s: s[2:] if s.startswith('-I') else s, py_includes)
7181858SN/A    main.Append(CPPPATH=py_includes)
7191858SN/A
7205863Snate@binkert.org    # Read the linker flags and split them into libraries and other link
7215863Snate@binkert.org    # flags. The libraries are added later through the call the CheckLib.
7225863Snate@binkert.org    py_ld_flags = readCommand([python_config, '--ldflags'],
7235863Snate@binkert.org        exception='').split()
7246121Snate@binkert.org    py_libs = []
7251858SN/A    for lib in py_ld_flags:
7265863Snate@binkert.org         if not lib.startswith('-l'):
7275863Snate@binkert.org             main.Append(LINKFLAGS=[lib])
7285863Snate@binkert.org         else:
7295863Snate@binkert.org             lib = lib[2:]
7305863Snate@binkert.org             if lib not in py_libs:
7312139SN/A                 py_libs.append(lib)
7324202Sbinkertn@umich.edu
7334202Sbinkertn@umich.edu    # verify that this stuff works
7342139SN/A    if not conf.CheckHeader('Python.h', '<>'):
7356994Snate@binkert.org        print("Error: Check failed for Python.h header in", py_includes)
7366994Snate@binkert.org        print("Two possible reasons:")
7376994Snate@binkert.org        print("1. Python headers are not installed (You can install the "
7386994Snate@binkert.org              "package python-dev on Ubuntu and RedHat)")
7396994Snate@binkert.org        print("2. SCons is using a wrong C compiler. This can happen if "
7406994Snate@binkert.org              "CC has the wrong value.")
7416994Snate@binkert.org        print("CC = %s" % main['CC'])
7426994Snate@binkert.org        Exit(1)
7436994Snate@binkert.org
7446994Snate@binkert.org    for lib in py_libs:
7456994Snate@binkert.org        if not conf.CheckLib(lib):
7466994Snate@binkert.org            print("Error: can't find library %s required by python" % lib)
7476994Snate@binkert.org            Exit(1)
7486994Snate@binkert.org
7496994Snate@binkert.org# On Solaris you need to use libsocket for socket ops
7506994Snate@binkert.orgif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7516994Snate@binkert.org   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7526994Snate@binkert.org       print("Can't find library with socket calls (e.g. accept())")
7536994Snate@binkert.org       Exit(1)
7546994Snate@binkert.org
7556994Snate@binkert.org# Check for zlib.  If the check passes, libz will be automatically
7566994Snate@binkert.org# added to the LIBS environment variable.
7576994Snate@binkert.orgif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
7586994Snate@binkert.org    print('Error: did not find needed zlib compression library '
7596994Snate@binkert.org          'and/or zlib.h header file.')
7606994Snate@binkert.org    print('       Please install zlib and try again.')
7616994Snate@binkert.org    Exit(1)
7626994Snate@binkert.org
7632155SN/A# If we have the protobuf compiler, also make sure we have the
7645863Snate@binkert.org# development libraries. If the check passes, libprotobuf will be
7651869SN/A# automatically added to the LIBS environment variable. After
7661869SN/A# this, we can use the HAVE_PROTOBUF flag to determine if we have
7675863Snate@binkert.org# got both protoc and libprotobuf available.
7685863Snate@binkert.orgmain['HAVE_PROTOBUF'] = main['PROTOC'] and \
7694202Sbinkertn@umich.edu    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
7706108Snate@binkert.org                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
7716108Snate@binkert.org
7726108Snate@binkert.org# Valgrind gets much less confused if you tell it when you're using
7736108Snate@binkert.org# alternative stacks.
7744202Sbinkertn@umich.edumain['HAVE_VALGRIND'] = conf.CheckCHeader('valgrind/valgrind.h')
7755863Snate@binkert.org
7768474Sgblack@eecs.umich.edu# If we have the compiler but not the library, print another warning.
7778474Sgblack@eecs.umich.eduif main['PROTOC'] and not main['HAVE_PROTOBUF']:
7785742Snate@binkert.org    print(termcap.Yellow + termcap.Bold +
7798268Ssteve.reinhardt@amd.com        'Warning: did not find protocol buffer library and/or headers.\n' +
7808268Ssteve.reinhardt@amd.com    '       Please install libprotobuf-dev for tracing support.' +
7818268Ssteve.reinhardt@amd.com    termcap.Normal)
7825742Snate@binkert.org
7835341Sstever@gmail.com# Check for librt.
7848474Sgblack@eecs.umich.eduhave_posix_clock = \
7858474Sgblack@eecs.umich.edu    conf.CheckLibWithHeader(None, 'time.h', 'C',
7865342Sstever@gmail.com                            'clock_nanosleep(0,0,NULL,NULL);') or \
7874202Sbinkertn@umich.edu    conf.CheckLibWithHeader('rt', 'time.h', 'C',
7884202Sbinkertn@umich.edu                            'clock_nanosleep(0,0,NULL,NULL);')
7894202Sbinkertn@umich.edu
7905863Snate@binkert.orghave_posix_timers = \
7915863Snate@binkert.org    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
7925863Snate@binkert.org                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
7936994Snate@binkert.org
7946994Snate@binkert.orgif not GetOption('without_tcmalloc'):
7956994Snate@binkert.org    if conf.CheckLib('tcmalloc'):
7965863Snate@binkert.org        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
7978152Ssteve.reinhardt@amd.com    elif conf.CheckLib('tcmalloc_minimal'):
7988152Ssteve.reinhardt@amd.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
7995863Snate@binkert.org    else:
8005863Snate@binkert.org        print(termcap.Yellow + termcap.Bold +
8015863Snate@binkert.org              "You can get a 12% performance improvement by "
8025863Snate@binkert.org              "installing tcmalloc (libgoogle-perftools-dev package "
8035863Snate@binkert.org              "on Ubuntu or RedHat)." + termcap.Normal)
8045863Snate@binkert.org
8055863Snate@binkert.org
8065863Snate@binkert.org# Detect back trace implementations. The last implementation in the
8075863Snate@binkert.org# list will be used by default.
8085863Snate@binkert.orgbacktrace_impls = [ "none" ]
8097840Snate@binkert.org
8105863Snate@binkert.orgbacktrace_checker = 'char temp;' + \
8115863Snate@binkert.org    ' backtrace_symbols_fd((void*)&temp, 0, 0);'
8125952Ssaidi@eecs.umich.eduif conf.CheckLibWithHeader(None, 'execinfo.h', 'C', backtrace_checker):
8137450Sstever@gmail.com    backtrace_impls.append("glibc")
8141869SN/Aelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
8151858SN/A                             backtrace_checker):
8165863Snate@binkert.org    # NetBSD and FreeBSD need libexecinfo.
8178297Snate@binkert.org    backtrace_impls.append("glibc")
8188152Ssteve.reinhardt@amd.com    main.Append(LIBS=['execinfo'])
8197840Snate@binkert.org
8207840Snate@binkert.orgif backtrace_impls[-1] == "none":
8211858SN/A    default_backtrace_impl = "none"
822955SN/A    print(termcap.Yellow + termcap.Bold +
823955SN/A        "No suitable back trace implementation found." +
8241869SN/A        termcap.Normal)
8251869SN/A
8261869SN/Aif not have_posix_clock:
8271869SN/A    print("Can't find library for POSIX clocks.")
8281869SN/A
8295863Snate@binkert.org# Check for <fenv.h> (C99 FP environment control)
8305863Snate@binkert.orghave_fenv = conf.CheckHeader('fenv.h', '<>')
8315863Snate@binkert.orgif not have_fenv:
8321869SN/A    print("Warning: Header file <fenv.h> not found.")
8335863Snate@binkert.org    print("         This host has no IEEE FP rounding mode control.")
8341869SN/A
8355863Snate@binkert.org# Check for <png.h> (libpng library needed if wanting to dump
8361869SN/A# frame buffer image in png format)
8371869SN/Ahave_png = conf.CheckHeader('png.h', '<>')
8381869SN/Aif not have_png:
8391869SN/A    print("Warning: Header file <png.h> not found.")
8401869SN/A    print("         This host has no libpng library.")
8415863Snate@binkert.org    print("         Disabling support for PNG framebuffers.")
8425863Snate@binkert.org
8431869SN/A# Check if we should enable KVM-based hardware virtualization. The API
8441869SN/A# we rely on exists since version 2.6.36 of the kernel, but somehow
8451869SN/A# the KVM_API_VERSION does not reflect the change. We test for one of
8461869SN/A# the types as a fall back.
8471869SN/Ahave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
8481869SN/Aif not have_kvm:
8491869SN/A    print("Info: Compatible header file <linux/kvm.h> not found, "
8505863Snate@binkert.org          "disabling KVM support.")
8515863Snate@binkert.org
8521869SN/A# Check if the TUN/TAP driver is available.
8535863Snate@binkert.orghave_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
8545863Snate@binkert.orgif not have_tuntap:
8553356Sbinkertn@umich.edu    print("Info: Compatible header file <linux/if_tun.h> not found.")
8563356Sbinkertn@umich.edu
8573356Sbinkertn@umich.edu# x86 needs support for xsave. We test for the structure here since we
8583356Sbinkertn@umich.edu# won't be able to run new tests by the time we know which ISA we're
8593356Sbinkertn@umich.edu# targeting.
8604781Snate@binkert.orghave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
8615863Snate@binkert.org                                    '#include <linux/kvm.h>') != 0
8625863Snate@binkert.org
8631869SN/A# Check if the requested target ISA is compatible with the host
8641869SN/Adef is_isa_kvm_compatible(isa):
8651869SN/A    try:
8666121Snate@binkert.org        import platform
8671869SN/A        host_isa = platform.machine()
8682638Sstever@eecs.umich.edu    except:
8696121Snate@binkert.org        print("Warning: Failed to determine host ISA.")
8706121Snate@binkert.org        return False
8712638Sstever@eecs.umich.edu
8725749Scws3k@cs.virginia.edu    if not have_posix_timers:
8736121Snate@binkert.org        print("Warning: Can not enable KVM, host seems to lack support "
8746121Snate@binkert.org              "for POSIX timers")
8755749Scws3k@cs.virginia.edu        return False
8761869SN/A
8771869SN/A    if isa == "arm":
8783546Sgblack@eecs.umich.edu        return host_isa in ( "armv7l", "aarch64" )
8793546Sgblack@eecs.umich.edu    elif isa == "x86":
8803546Sgblack@eecs.umich.edu        if host_isa != "x86_64":
8813546Sgblack@eecs.umich.edu            return False
8826121Snate@binkert.org
8835863Snate@binkert.org        if not have_kvm_xsave:
8843546Sgblack@eecs.umich.edu            print("KVM on x86 requires xsave support in kernel headers.")
8853546Sgblack@eecs.umich.edu            return False
8863546Sgblack@eecs.umich.edu
8873546Sgblack@eecs.umich.edu        return True
8884781Snate@binkert.org    else:
8894781Snate@binkert.org        return False
8906658Snate@binkert.org
8916658Snate@binkert.org
8924781Snate@binkert.org# Check if the exclude_host attribute is available. We want this to
8933546Sgblack@eecs.umich.edu# get accurate instruction counts in KVM.
8943546Sgblack@eecs.umich.edumain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
8953546Sgblack@eecs.umich.edu    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
8963546Sgblack@eecs.umich.edu
8977756SAli.Saidi@ARM.com
8987816Ssteve.reinhardt@amd.com######################################################################
8993546Sgblack@eecs.umich.edu#
9003546Sgblack@eecs.umich.edu# Finish the configuration
9013546Sgblack@eecs.umich.edu#
9023546Sgblack@eecs.umich.edumain = conf.Finish()
9034202Sbinkertn@umich.edu
9043546Sgblack@eecs.umich.edu######################################################################
9053546Sgblack@eecs.umich.edu#
9063546Sgblack@eecs.umich.edu# Collect all non-global variables
907955SN/A#
908955SN/A
909955SN/A# Define the universe of supported ISAs
910955SN/Aall_isa_list = [ ]
9115863Snate@binkert.orgall_gpu_isa_list = [ ]
9125863Snate@binkert.orgExport('all_isa_list')
9135343Sstever@gmail.comExport('all_gpu_isa_list')
9145343Sstever@gmail.com
9156121Snate@binkert.orgclass CpuModel(object):
9165863Snate@binkert.org    '''The CpuModel class encapsulates everything the ISA parser needs to
9174773Snate@binkert.org    know about a particular CPU model.'''
9185863Snate@binkert.org
9192632Sstever@eecs.umich.edu    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
9205863Snate@binkert.org    dict = {}
9212023SN/A
9225863Snate@binkert.org    # Constructor.  Automatically adds models to CpuModel.dict.
9235863Snate@binkert.org    def __init__(self, name, default=False):
9245863Snate@binkert.org        self.name = name           # name of model
9255863Snate@binkert.org
9265863Snate@binkert.org        # This cpu is enabled by default
9275863Snate@binkert.org        self.default = default
9285863Snate@binkert.org
9295863Snate@binkert.org        # Add self to dict
9305863Snate@binkert.org        if name in CpuModel.dict:
9312632Sstever@eecs.umich.edu            raise AttributeError, "CpuModel '%s' already registered" % name
9325863Snate@binkert.org        CpuModel.dict[name] = self
9332023SN/A
9342632Sstever@eecs.umich.eduExport('CpuModel')
9355863Snate@binkert.org
9365342Sstever@gmail.com# Sticky variables get saved in the variables file so they persist from
9375863Snate@binkert.org# one invocation to the next (unless overridden, in which case the new
9382632Sstever@eecs.umich.edu# value becomes sticky).
9395863Snate@binkert.orgsticky_vars = Variables(args=ARGUMENTS)
9405863Snate@binkert.orgExport('sticky_vars')
9418267Ssteve.reinhardt@amd.com
9428120Sgblack@eecs.umich.edu# Sticky variables that should be exported
9438267Ssteve.reinhardt@amd.comexport_vars = []
9448267Ssteve.reinhardt@amd.comExport('export_vars')
9458267Ssteve.reinhardt@amd.com
9468267Ssteve.reinhardt@amd.com# For Ruby
9478267Ssteve.reinhardt@amd.comall_protocols = []
9488267Ssteve.reinhardt@amd.comExport('all_protocols')
9498267Ssteve.reinhardt@amd.comprotocol_dirs = []
9508267Ssteve.reinhardt@amd.comExport('protocol_dirs')
9518267Ssteve.reinhardt@amd.comslicc_includes = []
9525863Snate@binkert.orgExport('slicc_includes')
9535863Snate@binkert.org
9545863Snate@binkert.org# Walk the tree and execute all SConsopts scripts that wil add to the
9552632Sstever@eecs.umich.edu# above variables
9568267Ssteve.reinhardt@amd.comif GetOption('verbose'):
9578267Ssteve.reinhardt@amd.com    print("Reading SConsopts")
9588267Ssteve.reinhardt@amd.comfor bdir in [ base_dir ] + extras_dir_list:
9592632Sstever@eecs.umich.edu    if not isdir(bdir):
9601888SN/A        print("Error: directory '%s' does not exist" % bdir)
9615863Snate@binkert.org        Exit(1)
9625863Snate@binkert.org    for root, dirs, files in os.walk(bdir):
9631858SN/A        if 'SConsopts' in files:
9648120Sgblack@eecs.umich.edu            if GetOption('verbose'):
9658120Sgblack@eecs.umich.edu                print("Reading", joinpath(root, 'SConsopts'))
9667756SAli.Saidi@ARM.com            SConscript(joinpath(root, 'SConsopts'))
9672598SN/A
9685863Snate@binkert.orgall_isa_list.sort()
9691858SN/Aall_gpu_isa_list.sort()
9701858SN/A
9711858SN/Asticky_vars.AddVariables(
9725863Snate@binkert.org    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
9731858SN/A    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
9741858SN/A    ListVariable('CPU_MODELS', 'CPU models',
9751858SN/A                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
9765863Snate@binkert.org                 sorted(CpuModel.dict.keys())),
9771871SN/A    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
9781858SN/A                 False),
9791858SN/A    BoolVariable('SS_COMPATIBLE_FP',
9801858SN/A                 'Make floating-point results compatible with SimpleScalar',
9811858SN/A                 False),
9825863Snate@binkert.org    BoolVariable('USE_SSE2',
9835863Snate@binkert.org                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
9841869SN/A                 False),
9851965SN/A    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
9867739Sgblack@eecs.umich.edu    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
9871965SN/A    BoolVariable('USE_PNG',  'Enable support for PNG images', have_png),
9882761Sstever@eecs.umich.edu    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability',
9895863Snate@binkert.org                 False),
9901869SN/A    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models',
9915863Snate@binkert.org                 have_kvm),
9922667Sstever@eecs.umich.edu    BoolVariable('USE_TUNTAP',
9931869SN/A                 'Enable using a tap device to bridge to the host network',
9941869SN/A                 have_tuntap),
9952929Sktlim@umich.edu    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
9962929Sktlim@umich.edu    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
9975863Snate@binkert.org                  all_protocols),
9982929Sktlim@umich.edu    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
999955SN/A                 backtrace_impls[-1], backtrace_impls)
10008120Sgblack@eecs.umich.edu    )
10018120Sgblack@eecs.umich.edu
10028120Sgblack@eecs.umich.edu# These variables get exported to #defines in config/*.hh (see src/SConscript).
10038120Sgblack@eecs.umich.eduexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
10048120Sgblack@eecs.umich.edu                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
10058120Sgblack@eecs.umich.edu                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_VALGRIND',
10068120Sgblack@eecs.umich.edu                'HAVE_PERF_ATTR_EXCLUDE_HOST', 'USE_PNG']
10078120Sgblack@eecs.umich.edu
10088120Sgblack@eecs.umich.edu###################################################
10098120Sgblack@eecs.umich.edu#
10108120Sgblack@eecs.umich.edu# Define a SCons builder for configuration flag headers.
10118120Sgblack@eecs.umich.edu#
1012###################################################
1013
1014# This function generates a config header file that #defines the
1015# variable symbol to the current variable setting (0 or 1).  The source
1016# operands are the name of the variable and a Value node containing the
1017# value of the variable.
1018def build_config_file(target, source, env):
1019    (variable, value) = [s.get_contents() for s in source]
1020    f = file(str(target[0]), 'w')
1021    print('#define', variable, value, file=f)
1022    f.close()
1023    return None
1024
1025# Combine the two functions into a scons Action object.
1026config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1027
1028# The emitter munges the source & target node lists to reflect what
1029# we're really doing.
1030def config_emitter(target, source, env):
1031    # extract variable name from Builder arg
1032    variable = str(target[0])
1033    # True target is config header file
1034    target = joinpath('config', variable.lower() + '.hh')
1035    val = env[variable]
1036    if isinstance(val, bool):
1037        # Force value to 0/1
1038        val = int(val)
1039    elif isinstance(val, str):
1040        val = '"' + val + '"'
1041
1042    # Sources are variable name & value (packaged in SCons Value nodes)
1043    return ([target], [Value(variable), Value(val)])
1044
1045config_builder = Builder(emitter = config_emitter, action = config_action)
1046
1047main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1048
1049###################################################
1050#
1051# Builders for static and shared partially linked object files.
1052#
1053###################################################
1054
1055partial_static_builder = Builder(action=SCons.Defaults.LinkAction,
1056                                 src_suffix='$OBJSUFFIX',
1057                                 src_builder=['StaticObject', 'Object'],
1058                                 LINKFLAGS='$PLINKFLAGS',
1059                                 LIBS='')
1060
1061def partial_shared_emitter(target, source, env):
1062    for tgt in target:
1063        tgt.attributes.shared = 1
1064    return (target, source)
1065partial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
1066                                 emitter=partial_shared_emitter,
1067                                 src_suffix='$SHOBJSUFFIX',
1068                                 src_builder='SharedObject',
1069                                 SHLINKFLAGS='$PSHLINKFLAGS',
1070                                 LIBS='')
1071
1072main.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
1073                         'PartialStatic' : partial_static_builder })
1074
1075def add_local_rpath(env, *targets):
1076    '''Set up an RPATH for a library which lives in the build directory.
1077
1078    The construction environment variable BIN_RPATH_PREFIX should be set to
1079    the relative path of the build directory starting from the location of the
1080    binary.'''
1081    for target in targets:
1082        target = env.Entry(target)
1083        if not target.isdir():
1084            target = target.dir
1085        relpath = os.path.relpath(target.abspath, env['BUILDDIR'])
1086        components = [
1087            '\\$$ORIGIN',
1088            '${BIN_RPATH_PREFIX}',
1089            relpath
1090        ]
1091        env.Append(RPATH=[env.Literal(os.path.join(*components))])
1092
1093if sys.platform != "darwin":
1094    main.Append(LINKFLAGS=Split('-z origin'))
1095
1096main.AddMethod(add_local_rpath, 'AddLocalRPATH')
1097
1098# builds in ext are shared across all configs in the build root.
1099ext_dir = abspath(joinpath(str(main.root), 'ext'))
1100ext_build_dirs = []
1101for root, dirs, files in os.walk(ext_dir):
1102    if 'SConscript' in files:
1103        build_dir = os.path.relpath(root, ext_dir)
1104        ext_build_dirs.append(build_dir)
1105        main.SConscript(joinpath(root, 'SConscript'),
1106                        variant_dir=joinpath(build_root, build_dir))
1107
1108gdb_xml_dir = joinpath(ext_dir, 'gdb-xml')
1109Export('gdb_xml_dir')
1110
1111main.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
1112
1113###################################################
1114#
1115# This builder and wrapper method are used to set up a directory with
1116# switching headers. Those are headers which are in a generic location and
1117# that include more specific headers from a directory chosen at build time
1118# based on the current build settings.
1119#
1120###################################################
1121
1122def build_switching_header(target, source, env):
1123    path = str(target[0])
1124    subdir = str(source[0])
1125    dp, fp = os.path.split(path)
1126    dp = os.path.relpath(os.path.realpath(dp),
1127                         os.path.realpath(env['BUILDDIR']))
1128    with open(path, 'w') as hdr:
1129        print('#include "%s/%s/%s"' % (dp, subdir, fp), file=hdr)
1130
1131switching_header_action = MakeAction(build_switching_header,
1132                                     Transform('GENERATE'))
1133
1134switching_header_builder = Builder(action=switching_header_action,
1135                                   source_factory=Value,
1136                                   single_source=True)
1137
1138main.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
1139
1140def switching_headers(self, headers, source):
1141    for header in headers:
1142        self.SwitchingHeader(header, source)
1143
1144main.AddMethod(switching_headers, 'SwitchingHeaders')
1145
1146###################################################
1147#
1148# Define build environments for selected configurations.
1149#
1150###################################################
1151
1152for variant_path in variant_paths:
1153    if not GetOption('silent'):
1154        print("Building in", variant_path)
1155
1156    # Make a copy of the build-root environment to use for this config.
1157    env = main.Clone()
1158    env['BUILDDIR'] = variant_path
1159
1160    # variant_dir is the tail component of build path, and is used to
1161    # determine the build parameters (e.g., 'ALPHA_SE')
1162    (build_root, variant_dir) = splitpath(variant_path)
1163
1164    # Set env variables according to the build directory config.
1165    sticky_vars.files = []
1166    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1167    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1168    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1169    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1170    if isfile(current_vars_file):
1171        sticky_vars.files.append(current_vars_file)
1172        if not GetOption('silent'):
1173            print("Using saved variables file %s" % current_vars_file)
1174    elif variant_dir in ext_build_dirs:
1175        # Things in ext are built without a variant directory.
1176        continue
1177    else:
1178        # Build dir-specific variables file doesn't exist.
1179
1180        # Make sure the directory is there so we can create it later
1181        opt_dir = dirname(current_vars_file)
1182        if not isdir(opt_dir):
1183            mkdir(opt_dir)
1184
1185        # Get default build variables from source tree.  Variables are
1186        # normally determined by name of $VARIANT_DIR, but can be
1187        # overridden by '--default=' arg on command line.
1188        default = GetOption('default')
1189        opts_dir = joinpath(main.root.abspath, 'build_opts')
1190        if default:
1191            default_vars_files = [joinpath(build_root, 'variables', default),
1192                                  joinpath(opts_dir, default)]
1193        else:
1194            default_vars_files = [joinpath(opts_dir, variant_dir)]
1195        existing_files = filter(isfile, default_vars_files)
1196        if existing_files:
1197            default_vars_file = existing_files[0]
1198            sticky_vars.files.append(default_vars_file)
1199            print("Variables file %s not found,\n  using defaults in %s"
1200                  % (current_vars_file, default_vars_file))
1201        else:
1202            print("Error: cannot find variables file %s or "
1203                  "default file(s) %s"
1204                  % (current_vars_file, ' or '.join(default_vars_files)))
1205            Exit(1)
1206
1207    # Apply current variable settings to env
1208    sticky_vars.Update(env)
1209
1210    help_texts["local_vars"] += \
1211        "Build variables for %s:\n" % variant_dir \
1212                 + sticky_vars.GenerateHelpText(env)
1213
1214    # Process variable settings.
1215
1216    if not have_fenv and env['USE_FENV']:
1217        print("Warning: <fenv.h> not available; "
1218              "forcing USE_FENV to False in", variant_dir + ".")
1219        env['USE_FENV'] = False
1220
1221    if not env['USE_FENV']:
1222        print("Warning: No IEEE FP rounding mode control in",
1223              variant_dir + ".")
1224        print("         FP results may deviate slightly from other platforms.")
1225
1226    if not have_png and env['USE_PNG']:
1227        print("Warning: <png.h> not available; "
1228              "forcing USE_PNG to False in", variant_dir + ".")
1229        env['USE_PNG'] = False
1230
1231    if env['USE_PNG']:
1232        env.Append(LIBS=['png'])
1233
1234    if env['EFENCE']:
1235        env.Append(LIBS=['efence'])
1236
1237    if env['USE_KVM']:
1238        if not have_kvm:
1239            print("Warning: Can not enable KVM, host seems to "
1240                  "lack KVM support")
1241            env['USE_KVM'] = False
1242        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1243            print("Info: KVM support disabled due to unsupported host and "
1244                  "target ISA combination")
1245            env['USE_KVM'] = False
1246
1247    if env['USE_TUNTAP']:
1248        if not have_tuntap:
1249            print("Warning: Can't connect EtherTap with a tap device.")
1250            env['USE_TUNTAP'] = False
1251
1252    if env['BUILD_GPU']:
1253        env.Append(CPPDEFINES=['BUILD_GPU'])
1254
1255    # Warn about missing optional functionality
1256    if env['USE_KVM']:
1257        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1258            print("Warning: perf_event headers lack support for the "
1259                  "exclude_host attribute. KVM instruction counts will "
1260                  "be inaccurate.")
1261
1262    # Save sticky variable settings back to current variables file
1263    sticky_vars.Save(current_vars_file, env)
1264
1265    if env['USE_SSE2']:
1266        env.Append(CCFLAGS=['-msse2'])
1267
1268    # The src/SConscript file sets up the build rules in 'env' according
1269    # to the configured variables.  It returns a list of environments,
1270    # one for each variant build (debug, opt, etc.)
1271    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1272
1273# base help text
1274Help('''
1275Usage: scons [scons options] [build variables] [target(s)]
1276
1277Extra scons options:
1278%(options)s
1279
1280Global build variables:
1281%(global_vars)s
1282
1283%(local_vars)s
1284''' % help_texts)
1285