SConstruct revision 14209
1955SN/A# -*- mode:python -*-
2955SN/A
37816Ssteve.reinhardt@amd.com# Copyright (c) 2013, 2015-2019 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.orgimport SCons.Node.FS
101955SN/A
1025396Ssaidi@eecs.umich.edufrom m5.util import compareVersions, readCommand
1035863Snate@binkert.org
1045863Snate@binkert.orghelp_texts = {
1054202Sbinkertn@umich.edu    "options" : "",
1065863Snate@binkert.org    "global_vars" : "",
1075863Snate@binkert.org    "local_vars" : ""
1085863Snate@binkert.org}
1095863Snate@binkert.org
110955SN/AExport("help_texts")
1116654Snate@binkert.org
1125273Sstever@gmail.com
1135871Snate@binkert.org# There's a bug in scons in that (1) by default, the help texts from
1145273Sstever@gmail.com# AddOption() are supposed to be displayed when you type 'scons -h'
1156655Snate@binkert.org# and (2) you can override the help displayed by 'scons -h' using the
1166655Snate@binkert.org# Help() function, but these two features are incompatible: once
1176655Snate@binkert.org# you've overridden the help text using Help(), there's no way to get
1186655Snate@binkert.org# at the help texts from AddOptions.  See:
1196655Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1206655Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1215871Snate@binkert.org# This hack lets us extract the help text from AddOptions and
1226654Snate@binkert.org# re-inject it via Help().  Ideally someday this bug will be fixed and
1235396Ssaidi@eecs.umich.edu# we can just use AddOption directly.
1248120Sgblack@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1258120Sgblack@eecs.umich.edu    col_width = 30
1268120Sgblack@eecs.umich.edu
1278120Sgblack@eecs.umich.edu    help = "  " + ", ".join(args)
1288120Sgblack@eecs.umich.edu    if "help" in kwargs:
1298120Sgblack@eecs.umich.edu        length = len(help)
1308120Sgblack@eecs.umich.edu        if length >= col_width:
1318120Sgblack@eecs.umich.edu            help += "\n" + " " * col_width
1328120Sgblack@eecs.umich.edu        else:
1338120Sgblack@eecs.umich.edu            help += " " * (col_width - length)
1348120Sgblack@eecs.umich.edu        help += kwargs["help"]
1358120Sgblack@eecs.umich.edu    help_texts["options"] += help + "\n"
1368120Sgblack@eecs.umich.edu
1378120Sgblack@eecs.umich.edu    AddOption(*args, **kwargs)
1388120Sgblack@eecs.umich.edu
1398120Sgblack@eecs.umich.eduAddLocalOption('--colors', dest='use_colors', action='store_true',
1408120Sgblack@eecs.umich.edu               help="Add color to abbreviated scons output")
1418120Sgblack@eecs.umich.eduAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1428120Sgblack@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1438120Sgblack@eecs.umich.eduAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1448120Sgblack@eecs.umich.edu               action='store_true',
1458120Sgblack@eecs.umich.edu               help="Build with support for C++-based configuration")
1468120Sgblack@eecs.umich.eduAddLocalOption('--default', dest='default', type='string', action='store',
1478120Sgblack@eecs.umich.edu               help='Override which build_opts file to use for defaults')
1488120Sgblack@eecs.umich.eduAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1498120Sgblack@eecs.umich.edu               help='Disable style checking hooks')
1508120Sgblack@eecs.umich.eduAddLocalOption('--gold-linker', dest='gold_linker', action='store_true',
1518120Sgblack@eecs.umich.edu               help='Use the gold linker')
1528120Sgblack@eecs.umich.eduAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1538120Sgblack@eecs.umich.edu               help='Disable Link-Time Optimization for fast')
1548120Sgblack@eecs.umich.eduAddLocalOption('--force-lto', dest='force_lto', action='store_true',
1558120Sgblack@eecs.umich.edu               help='Use Link-Time Optimization instead of partial linking' +
1568120Sgblack@eecs.umich.edu                    ' when the compiler doesn\'t support using them together.')
1578120Sgblack@eecs.umich.eduAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1588120Sgblack@eecs.umich.edu               help='Update test reference outputs')
1598120Sgblack@eecs.umich.eduAddLocalOption('--verbose', dest='verbose', action='store_true',
1607816Ssteve.reinhardt@amd.com               help='Print full tool command lines')
1617816Ssteve.reinhardt@amd.comAddLocalOption('--without-python', dest='without_python',
1627816Ssteve.reinhardt@amd.com               action='store_true',
1637816Ssteve.reinhardt@amd.com               help='Build without Python configuration support')
1647816Ssteve.reinhardt@amd.comAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1657816Ssteve.reinhardt@amd.com               action='store_true',
1667816Ssteve.reinhardt@amd.com               help='Disable linking against tcmalloc')
1677816Ssteve.reinhardt@amd.comAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1687816Ssteve.reinhardt@amd.com               help='Build with Undefined Behavior Sanitizer if available')
1695871Snate@binkert.orgAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1705871Snate@binkert.org               help='Build with Address Sanitizer if available')
1716121Snate@binkert.org
1725871Snate@binkert.orgif GetOption('no_lto') and GetOption('force_lto'):
1735871Snate@binkert.org    print('--no-lto and --force-lto are mutually exclusive')
1746003Snate@binkert.org    Exit(1)
1756655Snate@binkert.org
176955SN/A########################################################################
1775871Snate@binkert.org#
1785871Snate@binkert.org# Set up the main build environment.
1795871Snate@binkert.org#
1805871Snate@binkert.org########################################################################
181955SN/A
1826121Snate@binkert.orgmain = Environment()
1836121Snate@binkert.org
1846121Snate@binkert.orgfrom gem5_scons import Transform
1851533SN/Afrom gem5_scons.util import get_termcap
1866655Snate@binkert.orgtermcap = get_termcap()
1876655Snate@binkert.org
1886655Snate@binkert.orgmain_dict_keys = main.Dictionary().keys()
1896655Snate@binkert.org
1905871Snate@binkert.org# Check that we have a C/C++ compiler
1915871Snate@binkert.orgif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
1925863Snate@binkert.org    print("No C++ compiler installed (package g++ on Ubuntu and RedHat)")
1935871Snate@binkert.org    Exit(1)
1945871Snate@binkert.org
1955871Snate@binkert.org###################################################
1965871Snate@binkert.org#
1975871Snate@binkert.org# Figure out which configurations to set up based on the path(s) of
1985863Snate@binkert.org# the target(s).
1996121Snate@binkert.org#
2005863Snate@binkert.org###################################################
2015871Snate@binkert.org
2024678Snate@binkert.org# Find default configuration & binary.
2034678Snate@binkert.orgDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
2044678Snate@binkert.org
2054678Snate@binkert.org# helper function: find last occurrence of element in list
2064678Snate@binkert.orgdef rfind(l, elt, offs = -1):
2074678Snate@binkert.org    for i in range(len(l)+offs, 0, -1):
2084678Snate@binkert.org        if l[i] == elt:
2094678Snate@binkert.org            return i
2104678Snate@binkert.org    raise ValueError, "element not found"
2114678Snate@binkert.org
2124678Snate@binkert.org# Take a list of paths (or SCons Nodes) and return a list with all
2137827Snate@binkert.org# paths made absolute and ~-expanded.  Paths will be interpreted
2147827Snate@binkert.org# relative to the launch directory unless a different root is provided
2156121Snate@binkert.orgdef makePathListAbsolute(path_list, root=GetLaunchDir()):
2164678Snate@binkert.org    return [abspath(joinpath(root, expanduser(str(p))))
2175871Snate@binkert.org            for p in path_list]
2185871Snate@binkert.org
2195871Snate@binkert.orgdef find_first_prog(prog_names):
2205871Snate@binkert.org    """Find the absolute path to the first existing binary in prog_names"""
2215871Snate@binkert.org
2225871Snate@binkert.org    if not isinstance(prog_names, (list, tuple)):
2235871Snate@binkert.org        prog_names = [ prog_names ]
2245871Snate@binkert.org
2255871Snate@binkert.org    for p in prog_names:
2265871Snate@binkert.org        p = main.WhereIs(p)
2275871Snate@binkert.org        if p is not None:
2285871Snate@binkert.org            return p
2295871Snate@binkert.org
2305990Ssaidi@eecs.umich.edu    return None
2315871Snate@binkert.org
2325871Snate@binkert.org# Each target must have 'build' in the interior of the path; the
2335871Snate@binkert.org# directory below this will determine the build parameters.  For
2344678Snate@binkert.org# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2356654Snate@binkert.org# recognize that ALPHA_SE specifies the configuration because it
2365871Snate@binkert.org# follow 'build' in the build path.
2375871Snate@binkert.org
2385871Snate@binkert.org# The funky assignment to "[:]" is needed to replace the list contents
2395871Snate@binkert.org# in place rather than reassign the symbol to a new list, which
2405871Snate@binkert.org# doesn't work (obviously!).
2415871Snate@binkert.orgBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
2428120Sgblack@eecs.umich.edu
2435871Snate@binkert.org# Generate a list of the unique build roots and configs that the
2445871Snate@binkert.org# collected targets reference.
2454678Snate@binkert.orgvariant_paths = []
2465871Snate@binkert.orgbuild_root = None
2474678Snate@binkert.orgfor t in BUILD_TARGETS:
2485871Snate@binkert.org    path_dirs = t.split('/')
2495871Snate@binkert.org    try:
2505871Snate@binkert.org        build_top = rfind(path_dirs, 'build', -2)
2515871Snate@binkert.org    except:
2525871Snate@binkert.org        print("Error: no non-leaf 'build' dir found on target path", t)
2535871Snate@binkert.org        Exit(1)
2545871Snate@binkert.org    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2555871Snate@binkert.org    if not build_root:
2565871Snate@binkert.org        build_root = this_build_root
2576121Snate@binkert.org    else:
2586121Snate@binkert.org        if this_build_root != build_root:
2595863Snate@binkert.org            print("Error: build targets not under same build root\n"
260955SN/A                  "  %s\n  %s" % (build_root, this_build_root))
261955SN/A            Exit(1)
2622632Sstever@eecs.umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
2632632Sstever@eecs.umich.edu    if variant_path not in variant_paths:
264955SN/A        variant_paths.append(variant_path)
265955SN/A
266955SN/A# Make sure build_root exists (might not if this is the first build there)
267955SN/Aif not isdir(build_root):
2685863Snate@binkert.org    mkdir(build_root)
269955SN/Amain['BUILDROOT'] = build_root
2702632Sstever@eecs.umich.edu
2712632Sstever@eecs.umich.eduExport('main')
2722632Sstever@eecs.umich.edu
2732632Sstever@eecs.umich.edumain.SConsignFile(joinpath(build_root, "sconsign"))
2742632Sstever@eecs.umich.edu
2752632Sstever@eecs.umich.edu# Default duplicate option is to use hard links, but this messes up
2762632Sstever@eecs.umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
2772632Sstever@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
2782632Sstever@eecs.umich.edu# (soft) links work better.
2792632Sstever@eecs.umich.edumain.SetOption('duplicate', 'soft-copy')
2802632Sstever@eecs.umich.edu
2812632Sstever@eecs.umich.edu#
2822632Sstever@eecs.umich.edu# Set up global sticky variables... these are common to an entire build
2833718Sstever@eecs.umich.edu# tree (not specific to a particular build like ALPHA_SE)
2843718Sstever@eecs.umich.edu#
2853718Sstever@eecs.umich.edu
2863718Sstever@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
2873718Sstever@eecs.umich.edu
2885863Snate@binkert.orgglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
2895863Snate@binkert.org
2903718Sstever@eecs.umich.eduglobal_vars.AddVariables(
2913718Sstever@eecs.umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
2926121Snate@binkert.org    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
2935863Snate@binkert.org    ('CCFLAGS_EXTRA', 'Extra C and C++ compiler flags', ''),
2943718Sstever@eecs.umich.edu    ('LDFLAGS_EXTRA', 'Extra linker flags', ''),
2953718Sstever@eecs.umich.edu    ('PYTHON_CONFIG', 'Python config binary to use',
2962634Sstever@eecs.umich.edu     [ 'python2.7-config', 'python-config' ]),
2972634Sstever@eecs.umich.edu    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
2985863Snate@binkert.org    ('BATCH', 'Use batch pool for build and tests', False),
2992638Sstever@eecs.umich.edu    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3002632Sstever@eecs.umich.edu    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
3012632Sstever@eecs.umich.edu    ('EXTRAS', 'Add extra directories to the compilation', '')
3022632Sstever@eecs.umich.edu    )
3032632Sstever@eecs.umich.edu
3042632Sstever@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
3052632Sstever@eecs.umich.eduglobal_vars.Update(main)
3061858SN/Ahelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3073716Sstever@eecs.umich.edu
3082638Sstever@eecs.umich.edu# Save sticky variable settings back to current variables file
3092638Sstever@eecs.umich.eduglobal_vars.Save(global_vars_file, main)
3102638Sstever@eecs.umich.edu
3112638Sstever@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
3122638Sstever@eecs.umich.edu# look for sources etc.  This list is exported as extras_dir_list.
3132638Sstever@eecs.umich.edubase_dir = main.srcdir.abspath
3142638Sstever@eecs.umich.eduif main['EXTRAS']:
3155863Snate@binkert.org    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
3165863Snate@binkert.orgelse:
3175863Snate@binkert.org    extras_dir_list = []
318955SN/A
3195341Sstever@gmail.comExport('base_dir')
3205341Sstever@gmail.comExport('extras_dir_list')
3215863Snate@binkert.org
3227756SAli.Saidi@ARM.com# the ext directory should be on the #includes path
3235341Sstever@gmail.commain.Append(CPPPATH=[Dir('ext')])
3246121Snate@binkert.org
3254494Ssaidi@eecs.umich.edu# Add shared top-level headers
3266121Snate@binkert.orgmain.Prepend(CPPPATH=Dir('include'))
3271105SN/A
3282667Sstever@eecs.umich.eduif GetOption('verbose'):
3292667Sstever@eecs.umich.edu    def MakeAction(action, string, *args, **kwargs):
3302667Sstever@eecs.umich.edu        return Action(action, *args, **kwargs)
3312667Sstever@eecs.umich.eduelse:
3326121Snate@binkert.org    MakeAction = Action
3332667Sstever@eecs.umich.edu    main['CCCOMSTR']        = Transform("CC")
3345341Sstever@gmail.com    main['CXXCOMSTR']       = Transform("CXX")
3355863Snate@binkert.org    main['ASCOMSTR']        = Transform("AS")
3365341Sstever@gmail.com    main['ARCOMSTR']        = Transform("AR", 0)
3375341Sstever@gmail.com    main['LINKCOMSTR']      = Transform("LINK", 0)
3385341Sstever@gmail.com    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
3395863Snate@binkert.org    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
3405341Sstever@gmail.com    main['M4COMSTR']        = Transform("M4")
3415341Sstever@gmail.com    main['SHCCCOMSTR']      = Transform("SHCC")
3425341Sstever@gmail.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
3435863Snate@binkert.orgExport('MakeAction')
3445341Sstever@gmail.com
3455341Sstever@gmail.com# Initialize the Link-Time Optimization (LTO) flags
3465341Sstever@gmail.commain['LTO_CCFLAGS'] = []
3475341Sstever@gmail.commain['LTO_LDFLAGS'] = []
3485341Sstever@gmail.com
3495341Sstever@gmail.com# According to the readme, tcmalloc works best if the compiler doesn't
3505341Sstever@gmail.com# assume that we're using the builtin malloc and friends. These flags
3515341Sstever@gmail.com# are compiler-specific, so we need to set them after we detect which
3525341Sstever@gmail.com# compiler we're using.
3535341Sstever@gmail.commain['TCMALLOC_CCFLAGS'] = []
3548120Sgblack@eecs.umich.edu
3555341Sstever@gmail.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
3568120Sgblack@eecs.umich.eduCXX_V = readCommand([main['CXX'],'-V'], exception=False)
3575341Sstever@gmail.com
3588120Sgblack@eecs.umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3596121Snate@binkert.orgmain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
3606121Snate@binkert.orgif main['GCC'] + main['CLANG'] > 1:
3615397Ssaidi@eecs.umich.edu    print('Error: How can we have two at the same time?')
3625397Ssaidi@eecs.umich.edu    Exit(1)
3637727SAli.Saidi@ARM.com
3645341Sstever@gmail.com# Set up default C++ compiler flags
3656168Snate@binkert.orgif main['GCC'] or main['CLANG']:
3666168Snate@binkert.org    # As gcc and clang share many flags, do the common parts here
3675341Sstever@gmail.com    main.Append(CCFLAGS=['-pipe'])
3688120Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
3698120Sgblack@eecs.umich.edu    # Enable -Wall and -Wextra and then disable the few warnings that
3708120Sgblack@eecs.umich.edu    # we consistently violate
3716814Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
3725863Snate@binkert.org                         '-Wno-sign-compare', '-Wno-unused-parameter'])
3738120Sgblack@eecs.umich.edu    # We always compile using C++11
3745341Sstever@gmail.com    main.Append(CXXFLAGS=['-std=c++11'])
3755863Snate@binkert.org    if sys.platform.startswith('freebsd'):
3765341Sstever@gmail.com        main.Append(CCFLAGS=['-I/usr/local/include'])
3776121Snate@binkert.org        main.Append(CXXFLAGS=['-I/usr/local/include'])
3786121Snate@binkert.org
3796121Snate@binkert.org    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
3805742Snate@binkert.org    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
3815742Snate@binkert.org    if GetOption('gold_linker'):
3825341Sstever@gmail.com        main.Append(LINKFLAGS='-fuse-ld=gold')
3835742Snate@binkert.org    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
3845742Snate@binkert.org    shared_partial_flags = ['-r', '-nostdlib']
3855341Sstever@gmail.com    main.Append(PSHLINKFLAGS=shared_partial_flags)
3866017Snate@binkert.org    main.Append(PLINKFLAGS=shared_partial_flags)
3876121Snate@binkert.org
3886017Snate@binkert.org    # Treat warnings as errors but white list some warnings that we
3897816Ssteve.reinhardt@amd.com    # want to allow (e.g., deprecation warnings).
3907756SAli.Saidi@ARM.com    main.Append(CCFLAGS=['-Werror',
3917756SAli.Saidi@ARM.com                         '-Wno-error=deprecated-declarations',
3927756SAli.Saidi@ARM.com                         '-Wno-error=deprecated',
3937756SAli.Saidi@ARM.com                        ])
3947756SAli.Saidi@ARM.comelse:
3957756SAli.Saidi@ARM.com    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
3967756SAli.Saidi@ARM.com    print("Don't know what compiler options to use for your compiler.")
3977756SAli.Saidi@ARM.com    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
3987816Ssteve.reinhardt@amd.com    print(termcap.Yellow + '       version:' + termcap.Normal, end = ' ')
3997816Ssteve.reinhardt@amd.com    if not CXX_version:
4007816Ssteve.reinhardt@amd.com        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
4017816Ssteve.reinhardt@amd.com              termcap.Normal)
4027816Ssteve.reinhardt@amd.com    else:
4037816Ssteve.reinhardt@amd.com        print(CXX_version.replace('\n', '<nl>'))
4047816Ssteve.reinhardt@amd.com    print("       If you're trying to use a compiler other than GCC")
4057816Ssteve.reinhardt@amd.com    print("       or clang, there appears to be something wrong with your")
4067816Ssteve.reinhardt@amd.com    print("       environment.")
4077816Ssteve.reinhardt@amd.com    print("       ")
4087756SAli.Saidi@ARM.com    print("       If you are trying to use a compiler other than those listed")
4097816Ssteve.reinhardt@amd.com    print("       above you will need to ease fix SConstruct and ")
4107816Ssteve.reinhardt@amd.com    print("       src/SConscript to support that compiler.")
4117816Ssteve.reinhardt@amd.com    Exit(1)
4127816Ssteve.reinhardt@amd.com
4137816Ssteve.reinhardt@amd.comif main['GCC']:
4147816Ssteve.reinhardt@amd.com    # Check for a supported version of gcc. >= 4.8 is chosen for its
4157816Ssteve.reinhardt@amd.com    # level of c++11 support. See
4167816Ssteve.reinhardt@amd.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
4177816Ssteve.reinhardt@amd.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
4187816Ssteve.reinhardt@amd.com    if compareVersions(gcc_version, "4.8") < 0:
4197816Ssteve.reinhardt@amd.com        print('Error: gcc version 4.8 or newer required.')
4207816Ssteve.reinhardt@amd.com        print('       Installed version: ', gcc_version)
4217816Ssteve.reinhardt@amd.com        Exit(1)
4227816Ssteve.reinhardt@amd.com
4237816Ssteve.reinhardt@amd.com    main['GCC_VERSION'] = gcc_version
4247816Ssteve.reinhardt@amd.com
4257816Ssteve.reinhardt@amd.com    if compareVersions(gcc_version, '4.9') >= 0:
4267816Ssteve.reinhardt@amd.com        # Incremental linking with LTO is currently broken in gcc versions
4277816Ssteve.reinhardt@amd.com        # 4.9 and above. A version where everything works completely hasn't
4287816Ssteve.reinhardt@amd.com        # yet been identified.
4297816Ssteve.reinhardt@amd.com        #
4307816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
4317816Ssteve.reinhardt@amd.com        main['BROKEN_INCREMENTAL_LTO'] = True
4327816Ssteve.reinhardt@amd.com    if compareVersions(gcc_version, '6.0') >= 0:
4337816Ssteve.reinhardt@amd.com        # gcc versions 6.0 and greater accept an -flinker-output flag which
4347816Ssteve.reinhardt@amd.com        # selects what type of output the linker should generate. This is
4357816Ssteve.reinhardt@amd.com        # necessary for incremental lto to work, but is also broken in
4367816Ssteve.reinhardt@amd.com        # current versions of gcc. It may not be necessary in future
4377816Ssteve.reinhardt@amd.com        # versions. We add it here since it might be, and as a reminder that
4387816Ssteve.reinhardt@amd.com        # it exists. It's excluded if lto is being forced.
4397816Ssteve.reinhardt@amd.com        #
4407816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/gcc-6/changes.html
4417816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
4427816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
4437816Ssteve.reinhardt@amd.com        if not GetOption('force_lto'):
4447816Ssteve.reinhardt@amd.com            main.Append(PSHLINKFLAGS='-flinker-output=rel')
4457816Ssteve.reinhardt@amd.com            main.Append(PLINKFLAGS='-flinker-output=rel')
4467816Ssteve.reinhardt@amd.com
4477816Ssteve.reinhardt@amd.com    # Make sure we warn if the user has requested to compile with the
4487816Ssteve.reinhardt@amd.com    # Undefined Benahvior Sanitizer and this version of gcc does not
4497816Ssteve.reinhardt@amd.com    # support it.
4507816Ssteve.reinhardt@amd.com    if GetOption('with_ubsan') and \
4517816Ssteve.reinhardt@amd.com            compareVersions(gcc_version, '4.9') < 0:
4527816Ssteve.reinhardt@amd.com        print(termcap.Yellow + termcap.Bold +
4537816Ssteve.reinhardt@amd.com            'Warning: UBSan is only supported using gcc 4.9 and later.' +
4547816Ssteve.reinhardt@amd.com            termcap.Normal)
4557816Ssteve.reinhardt@amd.com
4567816Ssteve.reinhardt@amd.com    disable_lto = GetOption('no_lto')
4577816Ssteve.reinhardt@amd.com    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
4587816Ssteve.reinhardt@amd.com            not GetOption('force_lto'):
4597816Ssteve.reinhardt@amd.com        print(termcap.Yellow + termcap.Bold +
4607816Ssteve.reinhardt@amd.com            'Warning: Your compiler doesn\'t support incremental linking' +
4617816Ssteve.reinhardt@amd.com            ' and lto at the same time, so lto is being disabled. To force' +
4627816Ssteve.reinhardt@amd.com            ' lto on anyway, use the --force-lto option. That will disable' +
4637816Ssteve.reinhardt@amd.com            ' partial linking.' +
4647816Ssteve.reinhardt@amd.com            termcap.Normal)
4657816Ssteve.reinhardt@amd.com        disable_lto = True
4667816Ssteve.reinhardt@amd.com
4677816Ssteve.reinhardt@amd.com    # Add the appropriate Link-Time Optimization (LTO) flags
4687816Ssteve.reinhardt@amd.com    # unless LTO is explicitly turned off. Note that these flags
4697816Ssteve.reinhardt@amd.com    # are only used by the fast target.
4707756SAli.Saidi@ARM.com    if not disable_lto:
4718120Sgblack@eecs.umich.edu        # Pass the LTO flag when compiling to produce GIMPLE
4727756SAli.Saidi@ARM.com        # output, we merely create the flags here and only append
4737756SAli.Saidi@ARM.com        # them later
4747756SAli.Saidi@ARM.com        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4757756SAli.Saidi@ARM.com
4767816Ssteve.reinhardt@amd.com        # Use the same amount of jobs for LTO as we are running
4777816Ssteve.reinhardt@amd.com        # scons with
4787816Ssteve.reinhardt@amd.com        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4797816Ssteve.reinhardt@amd.com
4807816Ssteve.reinhardt@amd.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
4817816Ssteve.reinhardt@amd.com                                  '-fno-builtin-realloc', '-fno-builtin-free'])
4827816Ssteve.reinhardt@amd.com
4837816Ssteve.reinhardt@amd.com    # The address sanitizer is available for gcc >= 4.8
4847816Ssteve.reinhardt@amd.com    if GetOption('with_asan'):
4857816Ssteve.reinhardt@amd.com        if GetOption('with_ubsan') and \
4867756SAli.Saidi@ARM.com                compareVersions(main['GCC_VERSION'], '4.9') >= 0:
4877756SAli.Saidi@ARM.com            main.Append(CCFLAGS=['-fsanitize=address,undefined',
4886654Snate@binkert.org                                 '-fno-omit-frame-pointer'],
4896654Snate@binkert.org                        LINKFLAGS='-fsanitize=address,undefined')
4905871Snate@binkert.org        else:
4916121Snate@binkert.org            main.Append(CCFLAGS=['-fsanitize=address',
4926121Snate@binkert.org                                 '-fno-omit-frame-pointer'],
4936121Snate@binkert.org                        LINKFLAGS='-fsanitize=address')
4946121Snate@binkert.org    # Only gcc >= 4.9 supports UBSan, so check both the version
4953940Ssaidi@eecs.umich.edu    # and the command-line option before adding the compiler and
4963918Ssaidi@eecs.umich.edu    # linker flags.
4973918Ssaidi@eecs.umich.edu    elif GetOption('with_ubsan') and \
4981858SN/A            compareVersions(main['GCC_VERSION'], '4.9') >= 0:
4996121Snate@binkert.org        main.Append(CCFLAGS='-fsanitize=undefined')
5007739Sgblack@eecs.umich.edu        main.Append(LINKFLAGS='-fsanitize=undefined')
5017739Sgblack@eecs.umich.edu
5026143Snate@binkert.orgelif main['CLANG']:
5037739Sgblack@eecs.umich.edu    # Check for a supported version of clang, >= 3.1 is needed to
5047618SAli.Saidi@arm.com    # support similar features as gcc 4.8. See
5057618SAli.Saidi@arm.com    # http://clang.llvm.org/cxx_status.html for details
5067618SAli.Saidi@arm.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
5077618SAli.Saidi@arm.com    clang_version_match = clang_version_re.search(CXX_version)
5087618SAli.Saidi@arm.com    if (clang_version_match):
5097618SAli.Saidi@arm.com        clang_version = clang_version_match.groups()[0]
5107618SAli.Saidi@arm.com        if compareVersions(clang_version, "3.1") < 0:
5117739Sgblack@eecs.umich.edu            print('Error: clang version 3.1 or newer required.')
5126121Snate@binkert.org            print('       Installed version:', clang_version)
5133940Ssaidi@eecs.umich.edu            Exit(1)
5146121Snate@binkert.org    else:
5157739Sgblack@eecs.umich.edu        print('Error: Unable to determine clang version.')
5167739Sgblack@eecs.umich.edu        Exit(1)
5177739Sgblack@eecs.umich.edu
5187739Sgblack@eecs.umich.edu    # clang has a few additional warnings that we disable, extraneous
5197739Sgblack@eecs.umich.edu    # parantheses are allowed due to Ruby's printing of the AST,
5207739Sgblack@eecs.umich.edu    # finally self assignments are allowed as the generated CPU code
5213918Ssaidi@eecs.umich.edu    # is relying on this
5223918Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-Wno-parentheses',
5233940Ssaidi@eecs.umich.edu                         '-Wno-self-assign',
5243918Ssaidi@eecs.umich.edu                         # Some versions of libstdc++ (4.8?) seem to
5253918Ssaidi@eecs.umich.edu                         # use struct hash and class hash
5266157Snate@binkert.org                         # interchangeably.
5276157Snate@binkert.org                         '-Wno-mismatched-tags',
5286157Snate@binkert.org                         ])
5296157Snate@binkert.org
5305397Ssaidi@eecs.umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
5315397Ssaidi@eecs.umich.edu
5326121Snate@binkert.org    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
5336121Snate@binkert.org    # opposed to libstdc++, as the later is dated.
5346121Snate@binkert.org    if sys.platform == "darwin":
5356121Snate@binkert.org        main.Append(CXXFLAGS=['-stdlib=libc++'])
5366121Snate@binkert.org        main.Append(LIBS=['c++'])
5376121Snate@binkert.org
5385397Ssaidi@eecs.umich.edu    # On FreeBSD we need libthr.
5391851SN/A    if sys.platform.startswith('freebsd'):
5401851SN/A        main.Append(LIBS=['thr'])
5417739Sgblack@eecs.umich.edu
542955SN/A    # We require clang >= 3.1, so there is no need to check any
5433053Sstever@eecs.umich.edu    # versions here.
5446121Snate@binkert.org    if GetOption('with_ubsan'):
5453053Sstever@eecs.umich.edu        if GetOption('with_asan'):
5463053Sstever@eecs.umich.edu            main.Append(CCFLAGS=['-fsanitize=address,undefined',
5473053Sstever@eecs.umich.edu                                 '-fno-omit-frame-pointer'],
5483053Sstever@eecs.umich.edu                       LINKFLAGS='-fsanitize=address,undefined')
5493053Sstever@eecs.umich.edu        else:
5506654Snate@binkert.org            main.Append(CCFLAGS='-fsanitize=undefined',
5513053Sstever@eecs.umich.edu                        LINKFLAGS='-fsanitize=undefined')
5524742Sstever@eecs.umich.edu
5534742Sstever@eecs.umich.edu    elif GetOption('with_asan'):
5543053Sstever@eecs.umich.edu        main.Append(CCFLAGS=['-fsanitize=address',
5553053Sstever@eecs.umich.edu                             '-fno-omit-frame-pointer'],
5563053Sstever@eecs.umich.edu                   LINKFLAGS='-fsanitize=address')
5573053Sstever@eecs.umich.edu
5586654Snate@binkert.orgelse:
5593053Sstever@eecs.umich.edu    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
5603053Sstever@eecs.umich.edu    print("Don't know what compiler options to use for your compiler.")
5613053Sstever@eecs.umich.edu    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
5623053Sstever@eecs.umich.edu    print(termcap.Yellow + '       version:' + termcap.Normal, end=' ')
5632667Sstever@eecs.umich.edu    if not CXX_version:
5644554Sbinkertn@umich.edu        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
5656121Snate@binkert.org              termcap.Normal)
5662667Sstever@eecs.umich.edu    else:
5674554Sbinkertn@umich.edu        print(CXX_version.replace('\n', '<nl>'))
5684554Sbinkertn@umich.edu    print("       If you're trying to use a compiler other than GCC")
5694554Sbinkertn@umich.edu    print("       or clang, there appears to be something wrong with your")
5706121Snate@binkert.org    print("       environment.")
5714554Sbinkertn@umich.edu    print("       ")
5724554Sbinkertn@umich.edu    print("       If you are trying to use a compiler other than those listed")
5734554Sbinkertn@umich.edu    print("       above you will need to ease fix SConstruct and ")
5744781Snate@binkert.org    print("       src/SConscript to support that compiler.")
5754554Sbinkertn@umich.edu    Exit(1)
5764554Sbinkertn@umich.edu
5772667Sstever@eecs.umich.edu# Set up common yacc/bison flags (needed for Ruby)
5784554Sbinkertn@umich.edumain['YACCFLAGS'] = '-d'
5794554Sbinkertn@umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
5804554Sbinkertn@umich.edu
5814554Sbinkertn@umich.edu# Do this after we save setting back, or else we'll tack on an
5822667Sstever@eecs.umich.edu# extra 'qdo' every time we run scons.
5834554Sbinkertn@umich.eduif main['BATCH']:
5842667Sstever@eecs.umich.edu    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
5854554Sbinkertn@umich.edu    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
5866121Snate@binkert.org    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
5872667Sstever@eecs.umich.edu    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
5885522Snate@binkert.org    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
5895522Snate@binkert.org
5905522Snate@binkert.orgif sys.platform == 'cygwin':
5915522Snate@binkert.org    # cygwin has some header file issues...
5925522Snate@binkert.org    main.Append(CCFLAGS=["-Wno-uninitialized"])
5935522Snate@binkert.org
5945522Snate@binkert.org
5955522Snate@binkert.orghave_pkg_config = readCommand(['pkg-config', '--version'], exception='')
5965522Snate@binkert.org
5975522Snate@binkert.org# Check for the protobuf compiler
5985522Snate@binkert.orgprotoc_version = readCommand([main['PROTOC'], '--version'],
5995522Snate@binkert.org                             exception='').split()
6005522Snate@binkert.org
6015522Snate@binkert.org# First two words should be "libprotoc x.y.z"
6025522Snate@binkert.orgif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6035522Snate@binkert.org    print(termcap.Yellow + termcap.Bold +
6045522Snate@binkert.org        'Warning: Protocol buffer compiler (protoc) not found.\n' +
6055522Snate@binkert.org        '         Please install protobuf-compiler for tracing support.' +
6065522Snate@binkert.org        termcap.Normal)
6075522Snate@binkert.org    main['PROTOC'] = False
6085522Snate@binkert.orgelse:
6095522Snate@binkert.org    # Based on the availability of the compress stream wrappers,
6105522Snate@binkert.org    # require 2.1.0
6115522Snate@binkert.org    min_protoc_version = '2.1.0'
6125522Snate@binkert.org    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6135522Snate@binkert.org        print(termcap.Yellow + termcap.Bold +
6142638Sstever@eecs.umich.edu            'Warning: protoc version', min_protoc_version,
6152638Sstever@eecs.umich.edu            'or newer required.\n' +
6166121Snate@binkert.org            '         Installed version:', protoc_version[1],
6173716Sstever@eecs.umich.edu            termcap.Normal)
6185522Snate@binkert.org        main['PROTOC'] = False
6195522Snate@binkert.org    else:
6205522Snate@binkert.org        # Attempt to determine the appropriate include path and
6215522Snate@binkert.org        # library path using pkg-config, that means we also need to
6225522Snate@binkert.org        # check for pkg-config. Note that it is possible to use
6235522Snate@binkert.org        # protobuf without the involvement of pkg-config. Later on we
6241858SN/A        # check go a library config check and at that point the test
6255227Ssaidi@eecs.umich.edu        # will fail if libprotobuf cannot be found.
6265227Ssaidi@eecs.umich.edu        if have_pkg_config:
6275227Ssaidi@eecs.umich.edu            try:
6285227Ssaidi@eecs.umich.edu                # Attempt to establish what linking flags to add for protobuf
6296654Snate@binkert.org                # using pkg-config
6306654Snate@binkert.org                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
6317769SAli.Saidi@ARM.com            except:
6327769SAli.Saidi@ARM.com                print(termcap.Yellow + termcap.Bold +
6337769SAli.Saidi@ARM.com                    'Warning: pkg-config could not get protobuf flags.' +
6347769SAli.Saidi@ARM.com                    termcap.Normal)
6355227Ssaidi@eecs.umich.edu
6365227Ssaidi@eecs.umich.edu
6375227Ssaidi@eecs.umich.edu# Check for 'timeout' from GNU coreutils. If present, regressions will
6385204Sstever@gmail.com# be run with a time limit. We require version 8.13 since we rely on
6395204Sstever@gmail.com# support for the '--foreground' option.
6405204Sstever@gmail.comif sys.platform.startswith('freebsd'):
6415204Sstever@gmail.com    timeout_lines = readCommand(['gtimeout', '--version'],
6425204Sstever@gmail.com                                exception='').splitlines()
6435204Sstever@gmail.comelse:
6445204Sstever@gmail.com    timeout_lines = readCommand(['timeout', '--version'],
6455204Sstever@gmail.com                                exception='').splitlines()
6465204Sstever@gmail.com# Get the first line and tokenize it
6475204Sstever@gmail.comtimeout_version = timeout_lines[0].split() if timeout_lines else []
6485204Sstever@gmail.commain['TIMEOUT'] =  timeout_version and \
6495204Sstever@gmail.com    compareVersions(timeout_version[-1], '8.13') >= 0
6505204Sstever@gmail.com
6515204Sstever@gmail.com# Add a custom Check function to test for structure members.
6525204Sstever@gmail.comdef CheckMember(context, include, decl, member, include_quotes="<>"):
6535204Sstever@gmail.com    context.Message("Checking for member %s in %s..." %
6545204Sstever@gmail.com                    (member, decl))
6556121Snate@binkert.org    text = """
6565204Sstever@gmail.com#include %(header)s
6573118Sstever@eecs.umich.eduint main(){
6583118Sstever@eecs.umich.edu  %(decl)s test;
6593118Sstever@eecs.umich.edu  (void)test.%(member)s;
6603118Sstever@eecs.umich.edu  return 0;
6613118Sstever@eecs.umich.edu};
6625863Snate@binkert.org""" % { "header" : include_quotes[0] + include + include_quotes[1],
6633118Sstever@eecs.umich.edu        "decl" : decl,
6645863Snate@binkert.org        "member" : member,
6653118Sstever@eecs.umich.edu        }
6667457Snate@binkert.org
6677457Snate@binkert.org    ret = context.TryCompile(text, extension=".cc")
6685863Snate@binkert.org    context.Result(ret)
6695863Snate@binkert.org    return ret
6705863Snate@binkert.org
6715863Snate@binkert.org# Platform-specific configuration.  Note again that we assume that all
6725863Snate@binkert.org# builds under a given build root run on the same host platform.
6735863Snate@binkert.orgconf = Configure(main,
6745863Snate@binkert.org                 conf_dir = joinpath(build_root, '.scons_config'),
6756003Snate@binkert.org                 log_file = joinpath(build_root, 'scons_config.log'),
6765863Snate@binkert.org                 custom_tests = {
6775863Snate@binkert.org        'CheckMember' : CheckMember,
6785863Snate@binkert.org        })
6796120Snate@binkert.org
6805863Snate@binkert.org# Check if we should compile a 64 bit binary on Mac OS X/Darwin
6815863Snate@binkert.orgtry:
6825863Snate@binkert.org    import platform
6836120Snate@binkert.org    uname = platform.uname()
6846120Snate@binkert.org    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
6855863Snate@binkert.org        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
6865863Snate@binkert.org            main.Append(CCFLAGS=['-arch', 'x86_64'])
6876120Snate@binkert.org            main.Append(CFLAGS=['-arch', 'x86_64'])
6885863Snate@binkert.org            main.Append(LINKFLAGS=['-arch', 'x86_64'])
6896121Snate@binkert.org            main.Append(ASFLAGS=['-arch', 'x86_64'])
6906121Snate@binkert.orgexcept:
6915863Snate@binkert.org    pass
6927727SAli.Saidi@ARM.com
6937727SAli.Saidi@ARM.com# Recent versions of scons substitute a "Null" object for Configure()
6947727SAli.Saidi@ARM.com# when configuration isn't necessary, e.g., if the "--help" option is
6957727SAli.Saidi@ARM.com# present.  Unfortuantely this Null object always returns false,
6967727SAli.Saidi@ARM.com# breaking all our configuration checks.  We replace it with our own
6977727SAli.Saidi@ARM.com# more optimistic null object that returns True instead.
6985863Snate@binkert.orgif not conf:
6993118Sstever@eecs.umich.edu    def NullCheck(*args, **kwargs):
7005863Snate@binkert.org        return True
7013118Sstever@eecs.umich.edu
7023118Sstever@eecs.umich.edu    class NullConf:
7035863Snate@binkert.org        def __init__(self, env):
7045863Snate@binkert.org            self.env = env
7055863Snate@binkert.org        def Finish(self):
7065863Snate@binkert.org            return self.env
7073118Sstever@eecs.umich.edu        def __getattr__(self, mname):
7083483Ssaidi@eecs.umich.edu            return NullCheck
7093494Ssaidi@eecs.umich.edu
7103494Ssaidi@eecs.umich.edu    conf = NullConf(main)
7113483Ssaidi@eecs.umich.edu
7123483Ssaidi@eecs.umich.edu# Cache build files in the supplied directory.
7133483Ssaidi@eecs.umich.eduif main['M5_BUILD_CACHE']:
7143053Sstever@eecs.umich.edu    print('Using build cache located at', main['M5_BUILD_CACHE'])
7153053Sstever@eecs.umich.edu    CacheDir(main['M5_BUILD_CACHE'])
7163918Ssaidi@eecs.umich.edu
7173053Sstever@eecs.umich.edumain['USE_PYTHON'] = not GetOption('without_python')
7183053Sstever@eecs.umich.eduif main['USE_PYTHON']:
7193053Sstever@eecs.umich.edu    # Find Python include and library directories for embedding the
7203053Sstever@eecs.umich.edu    # interpreter. We rely on python-config to resolve the appropriate
7213053Sstever@eecs.umich.edu    # includes and linker flags. ParseConfig does not seem to understand
7227840Snate@binkert.org    # the more exotic linker flags such as -Xlinker and -export-dynamic so
7237865Sgblack@eecs.umich.edu    # we add them explicitly below. If you want to link in an alternate
7247865Sgblack@eecs.umich.edu    # version of python, see above for instructions on how to invoke
7257865Sgblack@eecs.umich.edu    # scons with the appropriate PATH set.
7267865Sgblack@eecs.umich.edu
7277865Sgblack@eecs.umich.edu    python_config = find_first_prog(main['PYTHON_CONFIG'])
7287840Snate@binkert.org    if python_config is None:
7297840Snate@binkert.org        print("Error: can't find a suitable python-config, tried %s" % \
7307840Snate@binkert.org              main['PYTHON_CONFIG'])
7317840Snate@binkert.org        Exit(1)
7321858SN/A
7331858SN/A    print("Info: Using Python config: %s" % (python_config, ))
7341858SN/A    py_includes = readCommand([python_config, '--includes'],
7351858SN/A                              exception='').split()
7361858SN/A    py_includes = filter(lambda s: match(r'.*\/include\/.*',s), py_includes)
7371858SN/A    # Strip the -I from the include folders before adding them to the
7385863Snate@binkert.org    # CPPPATH
7395863Snate@binkert.org    py_includes = map(lambda s: s[2:] if s.startswith('-I') else s, py_includes)
7401859SN/A    main.Append(CPPPATH=py_includes)
7415863Snate@binkert.org
7421858SN/A    # Read the linker flags and split them into libraries and other link
7435863Snate@binkert.org    # flags. The libraries are added later through the call the CheckLib.
7441858SN/A    py_ld_flags = readCommand([python_config, '--ldflags'],
7451859SN/A        exception='').split()
7461859SN/A    py_libs = []
7476654Snate@binkert.org    for lib in py_ld_flags:
7483053Sstever@eecs.umich.edu         if not lib.startswith('-l'):
7496654Snate@binkert.org             main.Append(LINKFLAGS=[lib])
7503053Sstever@eecs.umich.edu         else:
7513053Sstever@eecs.umich.edu             lib = lib[2:]
7521859SN/A             if lib not in py_libs:
7531859SN/A                 py_libs.append(lib)
7541859SN/A
7551859SN/A    # verify that this stuff works
7561859SN/A    if not conf.CheckHeader('Python.h', '<>'):
7571859SN/A        print("Error: Check failed for Python.h header in", py_includes)
7581859SN/A        print("Two possible reasons:")
7591859SN/A        print("1. Python headers are not installed (You can install the "
7601862SN/A              "package python-dev on Ubuntu and RedHat)")
7611859SN/A        print("2. SCons is using a wrong C compiler. This can happen if "
7621859SN/A              "CC has the wrong value.")
7631859SN/A        print("CC = %s" % main['CC'])
7645863Snate@binkert.org        Exit(1)
7655863Snate@binkert.org
7665863Snate@binkert.org    for lib in py_libs:
7675863Snate@binkert.org        if not conf.CheckLib(lib):
7686121Snate@binkert.org            print("Error: can't find library %s required by python" % lib)
7691858SN/A            Exit(1)
7705863Snate@binkert.org
7715863Snate@binkert.org# On Solaris you need to use libsocket for socket ops
7725863Snate@binkert.orgif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7735863Snate@binkert.org   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7745863Snate@binkert.org       print("Can't find library with socket calls (e.g. accept())")
7752139SN/A       Exit(1)
7764202Sbinkertn@umich.edu
7774202Sbinkertn@umich.edu# Check for zlib.  If the check passes, libz will be automatically
7782139SN/A# added to the LIBS environment variable.
7796994Snate@binkert.orgif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
7806994Snate@binkert.org    print('Error: did not find needed zlib compression library '
7816994Snate@binkert.org          'and/or zlib.h header file.')
7826994Snate@binkert.org    print('       Please install zlib and try again.')
7836994Snate@binkert.org    Exit(1)
7846994Snate@binkert.org
7856994Snate@binkert.org# If we have the protobuf compiler, also make sure we have the
7866994Snate@binkert.org# development libraries. If the check passes, libprotobuf will be
7876994Snate@binkert.org# automatically added to the LIBS environment variable. After
7886994Snate@binkert.org# this, we can use the HAVE_PROTOBUF flag to determine if we have
7896994Snate@binkert.org# got both protoc and libprotobuf available.
7906994Snate@binkert.orgmain['HAVE_PROTOBUF'] = main['PROTOC'] and \
7916994Snate@binkert.org    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
7926994Snate@binkert.org                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
7936994Snate@binkert.org
7946994Snate@binkert.org# Valgrind gets much less confused if you tell it when you're using
7956994Snate@binkert.org# alternative stacks.
7966994Snate@binkert.orgmain['HAVE_VALGRIND'] = conf.CheckCHeader('valgrind/valgrind.h')
7976994Snate@binkert.org
7986994Snate@binkert.org# If we have the compiler but not the library, print another warning.
7996994Snate@binkert.orgif main['PROTOC'] and not main['HAVE_PROTOBUF']:
8006994Snate@binkert.org    print(termcap.Yellow + termcap.Bold +
8016994Snate@binkert.org        'Warning: did not find protocol buffer library and/or headers.\n' +
8026994Snate@binkert.org    '       Please install libprotobuf-dev for tracing support.' +
8036994Snate@binkert.org    termcap.Normal)
8046994Snate@binkert.org
8056994Snate@binkert.org# Check for librt.
8066994Snate@binkert.orghave_posix_clock = \
8072155SN/A    conf.CheckLibWithHeader(None, 'time.h', 'C',
8085863Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);') or \
8091869SN/A    conf.CheckLibWithHeader('rt', 'time.h', 'C',
8101869SN/A                            'clock_nanosleep(0,0,NULL,NULL);')
8115863Snate@binkert.org
8125863Snate@binkert.orghave_posix_timers = \
8134202Sbinkertn@umich.edu    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
8146108Snate@binkert.org                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
8156108Snate@binkert.org
8166108Snate@binkert.orgif not GetOption('without_tcmalloc'):
8176108Snate@binkert.org    if conf.CheckLib('tcmalloc'):
8184202Sbinkertn@umich.edu        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
8195863Snate@binkert.org    elif conf.CheckLib('tcmalloc_minimal'):
8205742Snate@binkert.org        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
8215742Snate@binkert.org    else:
8225341Sstever@gmail.com        print(termcap.Yellow + termcap.Bold +
8235342Sstever@gmail.com              "You can get a 12% performance improvement by "
8245342Sstever@gmail.com              "installing tcmalloc (libgoogle-perftools-dev package "
8254202Sbinkertn@umich.edu              "on Ubuntu or RedHat)." + termcap.Normal)
8264202Sbinkertn@umich.edu
8274202Sbinkertn@umich.edu
8285863Snate@binkert.org# Detect back trace implementations. The last implementation in the
8295863Snate@binkert.org# list will be used by default.
8305863Snate@binkert.orgbacktrace_impls = [ "none" ]
8316994Snate@binkert.org
8326994Snate@binkert.orgbacktrace_checker = 'char temp;' + \
8336994Snate@binkert.org    ' backtrace_symbols_fd((void*)&temp, 0, 0);'
8345863Snate@binkert.orgif conf.CheckLibWithHeader(None, 'execinfo.h', 'C', backtrace_checker):
8355863Snate@binkert.org    backtrace_impls.append("glibc")
8365863Snate@binkert.orgelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
8375863Snate@binkert.org                             backtrace_checker):
8385863Snate@binkert.org    # NetBSD and FreeBSD need libexecinfo.
8395863Snate@binkert.org    backtrace_impls.append("glibc")
8405863Snate@binkert.org    main.Append(LIBS=['execinfo'])
8415863Snate@binkert.org
8425863Snate@binkert.orgif backtrace_impls[-1] == "none":
8435863Snate@binkert.org    default_backtrace_impl = "none"
8445863Snate@binkert.org    print(termcap.Yellow + termcap.Bold +
8455863Snate@binkert.org        "No suitable back trace implementation found." +
8465863Snate@binkert.org        termcap.Normal)
8475863Snate@binkert.org
8487840Snate@binkert.orgif not have_posix_clock:
8495863Snate@binkert.org    print("Can't find library for POSIX clocks.")
8505863Snate@binkert.org
8515952Ssaidi@eecs.umich.edu# Check for <fenv.h> (C99 FP environment control)
8527450Sstever@gmail.comhave_fenv = conf.CheckHeader('fenv.h', '<>')
8531869SN/Aif not have_fenv:
8541858SN/A    print("Warning: Header file <fenv.h> not found.")
8555863Snate@binkert.org    print("         This host has no IEEE FP rounding mode control.")
8566108Snate@binkert.org
8576108Snate@binkert.org# Check for <png.h> (libpng library needed if wanting to dump
8587840Snate@binkert.org# frame buffer image in png format)
8597840Snate@binkert.orghave_png = conf.CheckHeader('png.h', '<>')
8601858SN/Aif not have_png:
861955SN/A    print("Warning: Header file <png.h> not found.")
862955SN/A    print("         This host has no libpng library.")
8631869SN/A    print("         Disabling support for PNG framebuffers.")
8641869SN/A
8651869SN/A# Check if we should enable KVM-based hardware virtualization. The API
8661869SN/A# we rely on exists since version 2.6.36 of the kernel, but somehow
8671869SN/A# the KVM_API_VERSION does not reflect the change. We test for one of
8685863Snate@binkert.org# the types as a fall back.
8695863Snate@binkert.orghave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
8705863Snate@binkert.orgif not have_kvm:
8711869SN/A    print("Info: Compatible header file <linux/kvm.h> not found, "
8725863Snate@binkert.org          "disabling KVM support.")
8731869SN/A
8745863Snate@binkert.org# Check if the TUN/TAP driver is available.
8751869SN/Ahave_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
8761869SN/Aif not have_tuntap:
8771869SN/A    print("Info: Compatible header file <linux/if_tun.h> not found.")
8781869SN/A
8791869SN/A# x86 needs support for xsave. We test for the structure here since we
8805863Snate@binkert.org# won't be able to run new tests by the time we know which ISA we're
8815863Snate@binkert.org# targeting.
8821869SN/Ahave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
8831869SN/A                                    '#include <linux/kvm.h>') != 0
8841869SN/A
8851869SN/A# Check if the requested target ISA is compatible with the host
8861869SN/Adef is_isa_kvm_compatible(isa):
8871869SN/A    try:
8881869SN/A        import platform
8895863Snate@binkert.org        host_isa = platform.machine()
8905863Snate@binkert.org    except:
8911869SN/A        print("Warning: Failed to determine host ISA.")
8925863Snate@binkert.org        return False
8935863Snate@binkert.org
8943356Sbinkertn@umich.edu    if not have_posix_timers:
8953356Sbinkertn@umich.edu        print("Warning: Can not enable KVM, host seems to lack support "
8963356Sbinkertn@umich.edu              "for POSIX timers")
8973356Sbinkertn@umich.edu        return False
8983356Sbinkertn@umich.edu
8994781Snate@binkert.org    if isa == "arm":
9005863Snate@binkert.org        return host_isa in ( "armv7l", "aarch64" )
9015863Snate@binkert.org    elif isa == "x86":
9021869SN/A        if host_isa != "x86_64":
9031869SN/A            return False
9041869SN/A
9056121Snate@binkert.org        if not have_kvm_xsave:
9061869SN/A            print("KVM on x86 requires xsave support in kernel headers.")
9072638Sstever@eecs.umich.edu            return False
9086121Snate@binkert.org
9096121Snate@binkert.org        return True
9102638Sstever@eecs.umich.edu    else:
9115749Scws3k@cs.virginia.edu        return False
9126121Snate@binkert.org
9136121Snate@binkert.org
9145749Scws3k@cs.virginia.edu# Check if the exclude_host attribute is available. We want this to
9151869SN/A# get accurate instruction counts in KVM.
9161869SN/Amain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
9173546Sgblack@eecs.umich.edu    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
9183546Sgblack@eecs.umich.edu
9193546Sgblack@eecs.umich.edudef check_hdf5():
9203546Sgblack@eecs.umich.edu    return \
9216121Snate@binkert.org        conf.CheckLibWithHeader('hdf5', 'hdf5.h', 'C',
9225863Snate@binkert.org                                'H5Fcreate("", 0, 0, 0);') and \
9233546Sgblack@eecs.umich.edu        conf.CheckLibWithHeader('hdf5_cpp', 'H5Cpp.h', 'C++',
9243546Sgblack@eecs.umich.edu                                'H5::H5File("", 0);')
9253546Sgblack@eecs.umich.edu
9263546Sgblack@eecs.umich.edudef check_hdf5_pkg(name):
9274781Snate@binkert.org    print("Checking for %s using pkg-config..." % name, end="")
9284781Snate@binkert.org    if not have_pkg_config:
9296658Snate@binkert.org        print(" pkg-config not found")
9306658Snate@binkert.org        return False
9314781Snate@binkert.org
9323546Sgblack@eecs.umich.edu    try:
9333546Sgblack@eecs.umich.edu        main.ParseConfig('pkg-config --cflags-only-I --libs-only-L %s' % name)
9343546Sgblack@eecs.umich.edu        print(" yes")
9353546Sgblack@eecs.umich.edu        return True
9367756SAli.Saidi@ARM.com    except:
9377816Ssteve.reinhardt@amd.com        print(" no")
9383546Sgblack@eecs.umich.edu        return False
9393546Sgblack@eecs.umich.edu
9403546Sgblack@eecs.umich.edu# Check if there is a pkg-config configuration for hdf5. If we find
9413546Sgblack@eecs.umich.edu# it, setup the environment to enable linking and header inclusion. We
9424202Sbinkertn@umich.edu# don't actually try to include any headers or link with hdf5 at this
9433546Sgblack@eecs.umich.edu# stage.
9443546Sgblack@eecs.umich.eduif not check_hdf5_pkg('hdf5-serial'):
9453546Sgblack@eecs.umich.edu    check_hdf5_pkg('hdf5')
946955SN/A
947955SN/A# Check if the HDF5 libraries can be found. This check respects the
948955SN/A# include path and library path provided by pkg-config. We perform
949955SN/A# this check even if there isn't a pkg-config configuration for hdf5
9505863Snate@binkert.org# since some installations don't use pkg-config.
9515863Snate@binkert.orghave_hdf5 = check_hdf5()
9525343Sstever@gmail.comif not have_hdf5:
9535343Sstever@gmail.com    print("Warning: Couldn't find any HDF5 C++ libraries. Disabling")
9546121Snate@binkert.org    print("         HDF5 support.")
9555863Snate@binkert.org
9564773Snate@binkert.org######################################################################
9575863Snate@binkert.org#
9582632Sstever@eecs.umich.edu# Finish the configuration
9595863Snate@binkert.org#
9602023SN/Amain = conf.Finish()
9615863Snate@binkert.org
9625863Snate@binkert.org######################################################################
9635863Snate@binkert.org#
9645863Snate@binkert.org# Collect all non-global variables
9655863Snate@binkert.org#
9665863Snate@binkert.org
9675863Snate@binkert.org# Define the universe of supported ISAs
9685863Snate@binkert.orgall_isa_list = [ ]
9695863Snate@binkert.orgall_gpu_isa_list = [ ]
9702632Sstever@eecs.umich.eduExport('all_isa_list')
9715863Snate@binkert.orgExport('all_gpu_isa_list')
9722023SN/A
9732632Sstever@eecs.umich.educlass CpuModel(object):
9745863Snate@binkert.org    '''The CpuModel class encapsulates everything the ISA parser needs to
9755342Sstever@gmail.com    know about a particular CPU model.'''
9765863Snate@binkert.org
9772632Sstever@eecs.umich.edu    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
9785863Snate@binkert.org    dict = {}
9795863Snate@binkert.org
9802632Sstever@eecs.umich.edu    # Constructor.  Automatically adds models to CpuModel.dict.
9818120Sgblack@eecs.umich.edu    def __init__(self, name, default=False):
9828120Sgblack@eecs.umich.edu        self.name = name           # name of model
9838120Sgblack@eecs.umich.edu
9848120Sgblack@eecs.umich.edu        # This cpu is enabled by default
9855863Snate@binkert.org        self.default = default
9865863Snate@binkert.org
9875863Snate@binkert.org        # Add self to dict
9885863Snate@binkert.org        if name in CpuModel.dict:
9892632Sstever@eecs.umich.edu            raise AttributeError, "CpuModel '%s' already registered" % name
9905863Snate@binkert.org        CpuModel.dict[name] = self
9915863Snate@binkert.org
9922632Sstever@eecs.umich.eduExport('CpuModel')
9931888SN/A
9945863Snate@binkert.org# Sticky variables get saved in the variables file so they persist from
9955863Snate@binkert.org# one invocation to the next (unless overridden, in which case the new
9961858SN/A# value becomes sticky).
9978120Sgblack@eecs.umich.edusticky_vars = Variables(args=ARGUMENTS)
9988120Sgblack@eecs.umich.eduExport('sticky_vars')
9997756SAli.Saidi@ARM.com
10002598SN/A# Sticky variables that should be exported
10015863Snate@binkert.orgexport_vars = []
10021858SN/AExport('export_vars')
10031858SN/A
10041858SN/A# For Ruby
10055863Snate@binkert.orgall_protocols = []
10061858SN/AExport('all_protocols')
10071858SN/Aprotocol_dirs = []
10081858SN/AExport('protocol_dirs')
10095863Snate@binkert.orgslicc_includes = []
10101871SN/AExport('slicc_includes')
10111858SN/A
10121858SN/A# Walk the tree and execute all SConsopts scripts that wil add to the
10131858SN/A# above variables
10141858SN/Aif GetOption('verbose'):
10151858SN/A    print("Reading SConsopts")
10161858SN/Afor bdir in [ base_dir ] + extras_dir_list:
10171858SN/A    if not isdir(bdir):
10185863Snate@binkert.org        print("Error: directory '%s' does not exist" % bdir)
10191858SN/A        Exit(1)
10201858SN/A    for root, dirs, files in os.walk(bdir):
10215863Snate@binkert.org        if 'SConsopts' in files:
10221859SN/A            if GetOption('verbose'):
10231859SN/A                print("Reading", joinpath(root, 'SConsopts'))
10241869SN/A            SConscript(joinpath(root, 'SConsopts'))
10255863Snate@binkert.org
10265863Snate@binkert.orgall_isa_list.sort()
10271869SN/Aall_gpu_isa_list.sort()
10281965SN/A
10297739Sgblack@eecs.umich.edusticky_vars.AddVariables(
10301965SN/A    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
10312761Sstever@eecs.umich.edu    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
10325863Snate@binkert.org    ListVariable('CPU_MODELS', 'CPU models',
10331869SN/A                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
10345863Snate@binkert.org                 sorted(CpuModel.dict.keys())),
10352667Sstever@eecs.umich.edu    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
10361869SN/A                 False),
10371869SN/A    BoolVariable('SS_COMPATIBLE_FP',
10382929Sktlim@umich.edu                 'Make floating-point results compatible with SimpleScalar',
10392929Sktlim@umich.edu                 False),
10405863Snate@binkert.org    BoolVariable('USE_SSE2',
10412929Sktlim@umich.edu                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
1042955SN/A                 False),
10438120Sgblack@eecs.umich.edu    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
10448120Sgblack@eecs.umich.edu    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
10458120Sgblack@eecs.umich.edu    BoolVariable('USE_PNG',  'Enable support for PNG images', have_png),
10468120Sgblack@eecs.umich.edu    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability',
10478120Sgblack@eecs.umich.edu                 False),
10488120Sgblack@eecs.umich.edu    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models',
10498120Sgblack@eecs.umich.edu                 have_kvm),
10508120Sgblack@eecs.umich.edu    BoolVariable('USE_TUNTAP',
10518120Sgblack@eecs.umich.edu                 'Enable using a tap device to bridge to the host network',
10528120Sgblack@eecs.umich.edu                 have_tuntap),
10538120Sgblack@eecs.umich.edu    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
10548120Sgblack@eecs.umich.edu    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1055                  all_protocols),
1056    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
1057                 backtrace_impls[-1], backtrace_impls),
1058    ('NUMBER_BITS_PER_SET', 'Max elements in set (default 64)',
1059                 64),
1060    BoolVariable('USE_HDF5', 'Enable the HDF5 support', have_hdf5),
1061    )
1062
1063# These variables get exported to #defines in config/*.hh (see src/SConscript).
1064export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
1065                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
1066                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_VALGRIND',
1067                'HAVE_PERF_ATTR_EXCLUDE_HOST', 'USE_PNG',
1068                'NUMBER_BITS_PER_SET', 'USE_HDF5']
1069
1070###################################################
1071#
1072# Define a SCons builder for configuration flag headers.
1073#
1074###################################################
1075
1076# This function generates a config header file that #defines the
1077# variable symbol to the current variable setting (0 or 1).  The source
1078# operands are the name of the variable and a Value node containing the
1079# value of the variable.
1080def build_config_file(target, source, env):
1081    (variable, value) = [s.get_contents() for s in source]
1082    f = file(str(target[0]), 'w')
1083    print('#define', variable, value, file=f)
1084    f.close()
1085    return None
1086
1087# Combine the two functions into a scons Action object.
1088config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1089
1090# The emitter munges the source & target node lists to reflect what
1091# we're really doing.
1092def config_emitter(target, source, env):
1093    # extract variable name from Builder arg
1094    variable = str(target[0])
1095    # True target is config header file
1096    target = joinpath('config', variable.lower() + '.hh')
1097    val = env[variable]
1098    if isinstance(val, bool):
1099        # Force value to 0/1
1100        val = int(val)
1101    elif isinstance(val, str):
1102        val = '"' + val + '"'
1103
1104    # Sources are variable name & value (packaged in SCons Value nodes)
1105    return ([target], [Value(variable), Value(val)])
1106
1107config_builder = Builder(emitter = config_emitter, action = config_action)
1108
1109main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1110
1111###################################################
1112#
1113# Builders for static and shared partially linked object files.
1114#
1115###################################################
1116
1117partial_static_builder = Builder(action=SCons.Defaults.LinkAction,
1118                                 src_suffix='$OBJSUFFIX',
1119                                 src_builder=['StaticObject', 'Object'],
1120                                 LINKFLAGS='$PLINKFLAGS',
1121                                 LIBS='')
1122
1123def partial_shared_emitter(target, source, env):
1124    for tgt in target:
1125        tgt.attributes.shared = 1
1126    return (target, source)
1127partial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
1128                                 emitter=partial_shared_emitter,
1129                                 src_suffix='$SHOBJSUFFIX',
1130                                 src_builder='SharedObject',
1131                                 SHLINKFLAGS='$PSHLINKFLAGS',
1132                                 LIBS='')
1133
1134main.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
1135                         'PartialStatic' : partial_static_builder })
1136
1137def add_local_rpath(env, *targets):
1138    '''Set up an RPATH for a library which lives in the build directory.
1139
1140    The construction environment variable BIN_RPATH_PREFIX should be set to
1141    the relative path of the build directory starting from the location of the
1142    binary.'''
1143    for target in targets:
1144        target = env.Entry(target)
1145        if not isinstance(target, SCons.Node.FS.Dir):
1146            target = target.dir
1147        relpath = os.path.relpath(target.abspath, env['BUILDDIR'])
1148        components = [
1149            '\\$$ORIGIN',
1150            '${BIN_RPATH_PREFIX}',
1151            relpath
1152        ]
1153        env.Append(RPATH=[env.Literal(os.path.join(*components))])
1154
1155if sys.platform != "darwin":
1156    main.Append(LINKFLAGS=Split('-z origin'))
1157
1158main.AddMethod(add_local_rpath, 'AddLocalRPATH')
1159
1160# builds in ext are shared across all configs in the build root.
1161ext_dir = abspath(joinpath(str(main.root), 'ext'))
1162ext_build_dirs = []
1163for root, dirs, files in os.walk(ext_dir):
1164    if 'SConscript' in files:
1165        build_dir = os.path.relpath(root, ext_dir)
1166        ext_build_dirs.append(build_dir)
1167        main.SConscript(joinpath(root, 'SConscript'),
1168                        variant_dir=joinpath(build_root, build_dir))
1169
1170gdb_xml_dir = joinpath(ext_dir, 'gdb-xml')
1171Export('gdb_xml_dir')
1172
1173main.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
1174
1175###################################################
1176#
1177# This builder and wrapper method are used to set up a directory with
1178# switching headers. Those are headers which are in a generic location and
1179# that include more specific headers from a directory chosen at build time
1180# based on the current build settings.
1181#
1182###################################################
1183
1184def build_switching_header(target, source, env):
1185    path = str(target[0])
1186    subdir = str(source[0])
1187    dp, fp = os.path.split(path)
1188    dp = os.path.relpath(os.path.realpath(dp),
1189                         os.path.realpath(env['BUILDDIR']))
1190    with open(path, 'w') as hdr:
1191        print('#include "%s/%s/%s"' % (dp, subdir, fp), file=hdr)
1192
1193switching_header_action = MakeAction(build_switching_header,
1194                                     Transform('GENERATE'))
1195
1196switching_header_builder = Builder(action=switching_header_action,
1197                                   source_factory=Value,
1198                                   single_source=True)
1199
1200main.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
1201
1202def switching_headers(self, headers, source):
1203    for header in headers:
1204        self.SwitchingHeader(header, source)
1205
1206main.AddMethod(switching_headers, 'SwitchingHeaders')
1207
1208###################################################
1209#
1210# Define build environments for selected configurations.
1211#
1212###################################################
1213
1214for variant_path in variant_paths:
1215    if not GetOption('silent'):
1216        print("Building in", variant_path)
1217
1218    # Make a copy of the build-root environment to use for this config.
1219    env = main.Clone()
1220    env['BUILDDIR'] = variant_path
1221
1222    # variant_dir is the tail component of build path, and is used to
1223    # determine the build parameters (e.g., 'ALPHA_SE')
1224    (build_root, variant_dir) = splitpath(variant_path)
1225
1226    # Set env variables according to the build directory config.
1227    sticky_vars.files = []
1228    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1229    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1230    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1231    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1232    if isfile(current_vars_file):
1233        sticky_vars.files.append(current_vars_file)
1234        if not GetOption('silent'):
1235            print("Using saved variables file %s" % current_vars_file)
1236    elif variant_dir in ext_build_dirs:
1237        # Things in ext are built without a variant directory.
1238        continue
1239    else:
1240        # Build dir-specific variables file doesn't exist.
1241
1242        # Make sure the directory is there so we can create it later
1243        opt_dir = dirname(current_vars_file)
1244        if not isdir(opt_dir):
1245            mkdir(opt_dir)
1246
1247        # Get default build variables from source tree.  Variables are
1248        # normally determined by name of $VARIANT_DIR, but can be
1249        # overridden by '--default=' arg on command line.
1250        default = GetOption('default')
1251        opts_dir = joinpath(main.root.abspath, 'build_opts')
1252        if default:
1253            default_vars_files = [joinpath(build_root, 'variables', default),
1254                                  joinpath(opts_dir, default)]
1255        else:
1256            default_vars_files = [joinpath(opts_dir, variant_dir)]
1257        existing_files = filter(isfile, default_vars_files)
1258        if existing_files:
1259            default_vars_file = existing_files[0]
1260            sticky_vars.files.append(default_vars_file)
1261            print("Variables file %s not found,\n  using defaults in %s"
1262                  % (current_vars_file, default_vars_file))
1263        else:
1264            print("Error: cannot find variables file %s or "
1265                  "default file(s) %s"
1266                  % (current_vars_file, ' or '.join(default_vars_files)))
1267            Exit(1)
1268
1269    # Apply current variable settings to env
1270    sticky_vars.Update(env)
1271
1272    help_texts["local_vars"] += \
1273        "Build variables for %s:\n" % variant_dir \
1274                 + sticky_vars.GenerateHelpText(env)
1275
1276    # Process variable settings.
1277
1278    if not have_fenv and env['USE_FENV']:
1279        print("Warning: <fenv.h> not available; "
1280              "forcing USE_FENV to False in", variant_dir + ".")
1281        env['USE_FENV'] = False
1282
1283    if not env['USE_FENV']:
1284        print("Warning: No IEEE FP rounding mode control in",
1285              variant_dir + ".")
1286        print("         FP results may deviate slightly from other platforms.")
1287
1288    if not have_png and env['USE_PNG']:
1289        print("Warning: <png.h> not available; "
1290              "forcing USE_PNG to False in", variant_dir + ".")
1291        env['USE_PNG'] = False
1292
1293    if env['USE_PNG']:
1294        env.Append(LIBS=['png'])
1295
1296    if env['EFENCE']:
1297        env.Append(LIBS=['efence'])
1298
1299    if env['USE_KVM']:
1300        if not have_kvm:
1301            print("Warning: Can not enable KVM, host seems to "
1302                  "lack KVM support")
1303            env['USE_KVM'] = False
1304        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1305            print("Info: KVM support disabled due to unsupported host and "
1306                  "target ISA combination")
1307            env['USE_KVM'] = False
1308
1309    if env['USE_TUNTAP']:
1310        if not have_tuntap:
1311            print("Warning: Can't connect EtherTap with a tap device.")
1312            env['USE_TUNTAP'] = False
1313
1314    if env['BUILD_GPU']:
1315        env.Append(CPPDEFINES=['BUILD_GPU'])
1316
1317    # Warn about missing optional functionality
1318    if env['USE_KVM']:
1319        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1320            print("Warning: perf_event headers lack support for the "
1321                  "exclude_host attribute. KVM instruction counts will "
1322                  "be inaccurate.")
1323
1324    # Save sticky variable settings back to current variables file
1325    sticky_vars.Save(current_vars_file, env)
1326
1327    if env['USE_SSE2']:
1328        env.Append(CCFLAGS=['-msse2'])
1329
1330    env.Append(CCFLAGS='$CCFLAGS_EXTRA')
1331    env.Append(LINKFLAGS='$LDFLAGS_EXTRA')
1332
1333    # The src/SConscript file sets up the build rules in 'env' according
1334    # to the configured variables.  It returns a list of environments,
1335    # one for each variant build (debug, opt, etc.)
1336    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1337
1338# base help text
1339Help('''
1340Usage: scons [scons options] [build variables] [target(s)]
1341
1342Extra scons options:
1343%(options)s
1344
1345Global build variables:
1346%(global_vars)s
1347
1348%(local_vars)s
1349''' % help_texts)
1350