SConstruct revision 10181:6270235e0585
16498Snate@binkert.org# -*- mode:python -*-
26498Snate@binkert.org
36498Snate@binkert.org# Copyright (c) 2013 ARM Limited
46498Snate@binkert.org# All rights reserved.
56498Snate@binkert.org#
66498Snate@binkert.org# The license below extends only to copyright in the software and shall
76498Snate@binkert.org# not be construed as granting a license to any other intellectual
86498Snate@binkert.org# property including but not limited to intellectual property relating
96498Snate@binkert.org# to a hardware implementation of the functionality of the software
106498Snate@binkert.org# licensed hereunder.  You may use the software subject to the license
116498Snate@binkert.org# terms below provided that you ensure that this notice is replicated
126498Snate@binkert.org# unmodified and in its entirety in all distributions of the software,
136498Snate@binkert.org# modified or unmodified, in source code or in binary form.
146498Snate@binkert.org#
156498Snate@binkert.org# Copyright (c) 2011 Advanced Micro Devices, Inc.
166498Snate@binkert.org# Copyright (c) 2009 The Hewlett-Packard Development Company
176498Snate@binkert.org# Copyright (c) 2004-2005 The Regents of The University of Michigan
186498Snate@binkert.org# All rights reserved.
196498Snate@binkert.org#
206498Snate@binkert.org# Redistribution and use in source and binary forms, with or without
216498Snate@binkert.org# modification, are permitted provided that the following conditions are
226498Snate@binkert.org# met: redistributions of source code must retain the above copyright
236498Snate@binkert.org# notice, this list of conditions and the following disclaimer;
246498Snate@binkert.org# redistributions in binary form must reproduce the above copyright
256498Snate@binkert.org# notice, this list of conditions and the following disclaimer in the
266498Snate@binkert.org# documentation and/or other materials provided with the distribution;
276498Snate@binkert.org# neither the name of the copyright holders nor the names of its
286498Snate@binkert.org# contributors may be used to endorse or promote products derived from
296498Snate@binkert.org# this software without specific prior written permission.
306498Snate@binkert.org#
316498Snate@binkert.org# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
326498Snate@binkert.org# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
336498Snate@binkert.org# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
346498Snate@binkert.org# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
356498Snate@binkert.org# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
366498Snate@binkert.org# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
376498Snate@binkert.org# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
386498Snate@binkert.org# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
396498Snate@binkert.org# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
406498Snate@binkert.org# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
416498Snate@binkert.org# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
426498Snate@binkert.org#
436498Snate@binkert.org# Authors: Steve Reinhardt
446498Snate@binkert.org#          Nathan Binkert
456498Snate@binkert.org
466498Snate@binkert.org###################################################
476498Snate@binkert.org#
486498Snate@binkert.org# SCons top-level build description (SConstruct) file.
496498Snate@binkert.org#
506498Snate@binkert.org# While in this directory ('gem5'), just type 'scons' to build the default
516498Snate@binkert.org# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
526498Snate@binkert.org# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
536498Snate@binkert.org# the optimized full-system version).
546498Snate@binkert.org#
556498Snate@binkert.org# You can build gem5 in a different directory as long as there is a
566498Snate@binkert.org# 'build/<CONFIG>' somewhere along the target path.  The build system
576498Snate@binkert.org# expects that all configs under the same build directory are being
586498Snate@binkert.org# built for the same host system.
596498Snate@binkert.org#
606498Snate@binkert.org# Examples:
616498Snate@binkert.org#
626498Snate@binkert.org#   The following two commands are equivalent.  The '-u' option tells
636498Snate@binkert.org#   scons to search up the directory tree for this SConstruct file.
646498Snate@binkert.org#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
656498Snate@binkert.org#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
666498Snate@binkert.org#
676498Snate@binkert.org#   The following two commands are equivalent and demonstrate building
686498Snate@binkert.org#   in a directory outside of the source tree.  The '-C' option tells
696498Snate@binkert.org#   scons to chdir to the specified directory to find this SConstruct
706498Snate@binkert.org#   file.
716498Snate@binkert.org#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
726498Snate@binkert.org#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
736498Snate@binkert.org#
746498Snate@binkert.org# You can use 'scons -H' to print scons options.  If you're in this
756498Snate@binkert.org# 'gem5' directory (or use -u or -C to tell scons where to find this
766498Snate@binkert.org# file), you can use 'scons -h' to print all the gem5-specific build
776498Snate@binkert.org# options as well.
786498Snate@binkert.org#
796498Snate@binkert.org###################################################
806498Snate@binkert.org
816498Snate@binkert.org# Check for recent-enough Python and SCons versions.
826498Snate@binkert.orgtry:
836498Snate@binkert.org    # Really old versions of scons only take two options for the
846498Snate@binkert.org    # function, so check once without the revision and once with the
856498Snate@binkert.org    # revision, the first instance will fail for stuff other than
866498Snate@binkert.org    # 0.98, and the second will fail for 0.98.0
876498Snate@binkert.org    EnsureSConsVersion(0, 98)
886498Snate@binkert.org    EnsureSConsVersion(0, 98, 1)
896498Snate@binkert.orgexcept SystemExit, e:
906498Snate@binkert.org    print """
916498Snate@binkert.orgFor more details, see:
926498Snate@binkert.org    http://gem5.org/Dependencies
936498Snate@binkert.org"""
946498Snate@binkert.org    raise
956498Snate@binkert.org
966498Snate@binkert.org# We ensure the python version early because because python-config
976498Snate@binkert.org# requires python 2.5
986498Snate@binkert.orgtry:
996498Snate@binkert.org    EnsurePythonVersion(2, 5)
1006498Snate@binkert.orgexcept SystemExit, e:
1016498Snate@binkert.org    print """
1026498Snate@binkert.orgYou can use a non-default installation of the Python interpreter by
1036498Snate@binkert.orgrearranging your PATH so that scons finds the non-default 'python' and
1046498Snate@binkert.org'python-config' first.
1056498Snate@binkert.org
1066498Snate@binkert.orgFor more details, see:
1076498Snate@binkert.org    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1086498Snate@binkert.org"""
1096498Snate@binkert.org    raise
1106498Snate@binkert.org
1116498Snate@binkert.org# Global Python includes
1126498Snate@binkert.orgimport os
1136498Snate@binkert.orgimport re
1146498Snate@binkert.orgimport subprocess
1156498Snate@binkert.orgimport sys
1166498Snate@binkert.org
1176498Snate@binkert.orgfrom os import mkdir, environ
1186498Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1196498Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1206498Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1216498Snate@binkert.org
1226498Snate@binkert.org# SCons includes
1236498Snate@binkert.orgimport SCons
1246498Snate@binkert.orgimport SCons.Node
1256498Snate@binkert.org
1266498Snate@binkert.orgextra_python_paths = [
1276498Snate@binkert.org    Dir('src/python').srcnode().abspath, # gem5 includes
1286498Snate@binkert.org    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1296498Snate@binkert.org    ]
1306498Snate@binkert.org
1316498Snate@binkert.orgsys.path[1:1] = extra_python_paths
1326498Snate@binkert.org
1336498Snate@binkert.orgfrom m5.util import compareVersions, readCommand
1346498Snate@binkert.orgfrom m5.util.terminal import get_termcap
1356498Snate@binkert.org
1366498Snate@binkert.orghelp_texts = {
1376498Snate@binkert.org    "options" : "",
1386498Snate@binkert.org    "global_vars" : "",
1396498Snate@binkert.org    "local_vars" : ""
1406498Snate@binkert.org}
1416498Snate@binkert.org
1426498Snate@binkert.orgExport("help_texts")
1436498Snate@binkert.org
1446498Snate@binkert.org
1456498Snate@binkert.org# There's a bug in scons in that (1) by default, the help texts from
1466498Snate@binkert.org# AddOption() are supposed to be displayed when you type 'scons -h'
1476498Snate@binkert.org# and (2) you can override the help displayed by 'scons -h' using the
1486498Snate@binkert.org# Help() function, but these two features are incompatible: once
1496498Snate@binkert.org# you've overridden the help text using Help(), there's no way to get
1506498Snate@binkert.org# at the help texts from AddOptions.  See:
1516498Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1526498Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1536498Snate@binkert.org# This hack lets us extract the help text from AddOptions and
1546498Snate@binkert.org# re-inject it via Help().  Ideally someday this bug will be fixed and
1556498Snate@binkert.org# we can just use AddOption directly.
1566498Snate@binkert.orgdef AddLocalOption(*args, **kwargs):
1576498Snate@binkert.org    col_width = 30
1586498Snate@binkert.org
1596498Snate@binkert.org    help = "  " + ", ".join(args)
1606498Snate@binkert.org    if "help" in kwargs:
1616498Snate@binkert.org        length = len(help)
1626498Snate@binkert.org        if length >= col_width:
1636498Snate@binkert.org            help += "\n" + " " * col_width
1646498Snate@binkert.org        else:
1656498Snate@binkert.org            help += " " * (col_width - length)
1666498Snate@binkert.org        help += kwargs["help"]
1676498Snate@binkert.org    help_texts["options"] += help + "\n"
1686498Snate@binkert.org
1696498Snate@binkert.org    AddOption(*args, **kwargs)
1706498Snate@binkert.org
1716498Snate@binkert.orgAddLocalOption('--colors', dest='use_colors', action='store_true',
1726498Snate@binkert.org               help="Add color to abbreviated scons output")
1736498Snate@binkert.orgAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1746498Snate@binkert.org               help="Don't add color to abbreviated scons output")
1756498Snate@binkert.orgAddLocalOption('--default', dest='default', type='string', action='store',
1766498Snate@binkert.org               help='Override which build_opts file to use for defaults')
1776498Snate@binkert.orgAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1786498Snate@binkert.org               help='Disable style checking hooks')
1796498Snate@binkert.orgAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1806498Snate@binkert.org               help='Disable Link-Time Optimization for fast')
1816498Snate@binkert.orgAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1826498Snate@binkert.org               help='Update test reference outputs')
1836498Snate@binkert.orgAddLocalOption('--verbose', dest='verbose', action='store_true',
1846498Snate@binkert.org               help='Print full tool command lines')
1856498Snate@binkert.org
1866498Snate@binkert.orgtermcap = get_termcap(GetOption('use_colors'))
1876498Snate@binkert.org
1886498Snate@binkert.org########################################################################
1896498Snate@binkert.org#
1906498Snate@binkert.org# Set up the main build environment.
1916498Snate@binkert.org#
1926498Snate@binkert.org########################################################################
1936498Snate@binkert.org
1946498Snate@binkert.org# export TERM so that clang reports errors in color
1956498Snate@binkert.orguse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
1966498Snate@binkert.org                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
1976498Snate@binkert.org                 'PYTHONPATH', 'RANLIB', 'SWIG', 'TERM' ])
1986498Snate@binkert.org
1996498Snate@binkert.orguse_prefixes = [
2006498Snate@binkert.org    "M5",           # M5 configuration (e.g., path to kernels)
2016498Snate@binkert.org    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
2026498Snate@binkert.org    "CCACHE_",      # ccache (caching compiler wrapper) configuration
2036498Snate@binkert.org    "CCC_",         # clang static analyzer configuration
2046498Snate@binkert.org    ]
2056498Snate@binkert.org
2066498Snate@binkert.orguse_env = {}
2076498Snate@binkert.orgfor key,val in os.environ.iteritems():
2086498Snate@binkert.org    if key in use_vars or \
2096498Snate@binkert.org            any([key.startswith(prefix) for prefix in use_prefixes]):
2106498Snate@binkert.org        use_env[key] = val
2116498Snate@binkert.org
2126498Snate@binkert.orgmain = Environment(ENV=use_env)
2136498Snate@binkert.orgmain.Decider('MD5-timestamp')
2146498Snate@binkert.orgmain.root = Dir(".")         # The current directory (where this file lives).
2156498Snate@binkert.orgmain.srcdir = Dir("src")     # The source directory
2166498Snate@binkert.org
2176498Snate@binkert.orgmain_dict_keys = main.Dictionary().keys()
2186498Snate@binkert.org
2196498Snate@binkert.org# Check that we have a C/C++ compiler
2206498Snate@binkert.orgif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2216498Snate@binkert.org    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2226498Snate@binkert.org    Exit(1)
2236498Snate@binkert.org
2246498Snate@binkert.org# Check that swig is present
2256498Snate@binkert.orgif not 'SWIG' in main_dict_keys:
2266498Snate@binkert.org    print "swig is not installed (package swig on Ubuntu and RedHat)"
2276498Snate@binkert.org    Exit(1)
2286498Snate@binkert.org
2296498Snate@binkert.org# add useful python code PYTHONPATH so it can be used by subprocesses
2306498Snate@binkert.org# as well
2316498Snate@binkert.orgmain.AppendENVPath('PYTHONPATH', extra_python_paths)
2326498Snate@binkert.org
2336498Snate@binkert.org########################################################################
2346498Snate@binkert.org#
2356498Snate@binkert.org# Mercurial Stuff.
2366498Snate@binkert.org#
2376498Snate@binkert.org# If the gem5 directory is a mercurial repository, we should do some
2386498Snate@binkert.org# extra things.
2396498Snate@binkert.org#
2406498Snate@binkert.org########################################################################
2416498Snate@binkert.org
2426498Snate@binkert.orghgdir = main.root.Dir(".hg")
2436498Snate@binkert.org
2446498Snate@binkert.orgmercurial_style_message = """
2456498Snate@binkert.orgYou're missing the gem5 style hook, which automatically checks your code
2466498Snate@binkert.orgagainst the gem5 style rules on hg commit and qrefresh commands.  This
2476498Snate@binkert.orgscript will now install the hook in your .hg/hgrc file.
2486498Snate@binkert.orgPress enter to continue, or ctrl-c to abort: """
2496498Snate@binkert.org
2506498Snate@binkert.orgmercurial_style_hook = """
2516498Snate@binkert.org# The following lines were automatically added by gem5/SConstruct
2526498Snate@binkert.org# to provide the gem5 style-checking hooks
2536498Snate@binkert.org[extensions]
2546498Snate@binkert.orgstyle = %s/util/style.py
2556498Snate@binkert.org
2566498Snate@binkert.org[hooks]
2576498Snate@binkert.orgpretxncommit.style = python:style.check_style
2586498Snate@binkert.orgpre-qrefresh.style = python:style.check_style
2596498Snate@binkert.org# End of SConstruct additions
2606498Snate@binkert.org
2616498Snate@binkert.org""" % (main.root.abspath)
2626498Snate@binkert.org
2636498Snate@binkert.orgmercurial_lib_not_found = """
2646498Snate@binkert.orgMercurial libraries cannot be found, ignoring style hook.  If
2656498Snate@binkert.orgyou are a gem5 developer, please fix this and run the style
2666498Snate@binkert.orghook. It is important.
2676498Snate@binkert.org"""
2686498Snate@binkert.org
2696498Snate@binkert.org# Check for style hook and prompt for installation if it's not there.
2706498Snate@binkert.org# Skip this if --ignore-style was specified, there's no .hg dir to
2716498Snate@binkert.org# install a hook in, or there's no interactive terminal to prompt.
2726498Snate@binkert.orgif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2736498Snate@binkert.org    style_hook = True
2746498Snate@binkert.org    try:
2756498Snate@binkert.org        from mercurial import ui
2766498Snate@binkert.org        ui = ui.ui()
2776498Snate@binkert.org        ui.readconfig(hgdir.File('hgrc').abspath)
2786498Snate@binkert.org        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2796498Snate@binkert.org                     ui.config('hooks', 'pre-qrefresh.style', None)
2806498Snate@binkert.org    except ImportError:
2816498Snate@binkert.org        print mercurial_lib_not_found
2826498Snate@binkert.org
2836498Snate@binkert.org    if not style_hook:
2846498Snate@binkert.org        print mercurial_style_message,
2856498Snate@binkert.org        # continue unless user does ctrl-c/ctrl-d etc.
2866498Snate@binkert.org        try:
2876498Snate@binkert.org            raw_input()
2886498Snate@binkert.org        except:
2896498Snate@binkert.org            print "Input exception, exiting scons.\n"
2906498Snate@binkert.org            sys.exit(1)
2916498Snate@binkert.org        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
2926498Snate@binkert.org        print "Adding style hook to", hgrc_path, "\n"
2936498Snate@binkert.org        try:
2946498Snate@binkert.org            hgrc = open(hgrc_path, 'a')
2956498Snate@binkert.org            hgrc.write(mercurial_style_hook)
2966498Snate@binkert.org            hgrc.close()
2976498Snate@binkert.org        except:
2986498Snate@binkert.org            print "Error updating", hgrc_path
2996498Snate@binkert.org            sys.exit(1)
3006498Snate@binkert.org
3016498Snate@binkert.org
3026498Snate@binkert.org###################################################
3036498Snate@binkert.org#
3046498Snate@binkert.org# Figure out which configurations to set up based on the path(s) of
3056498Snate@binkert.org# the target(s).
3066498Snate@binkert.org#
3076498Snate@binkert.org###################################################
3086498Snate@binkert.org
3096498Snate@binkert.org# Find default configuration & binary.
3106498Snate@binkert.orgDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
3116498Snate@binkert.org
3126498Snate@binkert.org# helper function: find last occurrence of element in list
3136498Snate@binkert.orgdef rfind(l, elt, offs = -1):
3146498Snate@binkert.org    for i in range(len(l)+offs, 0, -1):
3156498Snate@binkert.org        if l[i] == elt:
3166498Snate@binkert.org            return i
3176498Snate@binkert.org    raise ValueError, "element not found"
3186498Snate@binkert.org
3196498Snate@binkert.org# Take a list of paths (or SCons Nodes) and return a list with all
3206498Snate@binkert.org# paths made absolute and ~-expanded.  Paths will be interpreted
3216498Snate@binkert.org# relative to the launch directory unless a different root is provided
3226498Snate@binkert.orgdef makePathListAbsolute(path_list, root=GetLaunchDir()):
3236498Snate@binkert.org    return [abspath(joinpath(root, expanduser(str(p))))
3246498Snate@binkert.org            for p in path_list]
3256498Snate@binkert.org
3266498Snate@binkert.org# Each target must have 'build' in the interior of the path; the
3276498Snate@binkert.org# directory below this will determine the build parameters.  For
3286498Snate@binkert.org# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3296498Snate@binkert.org# recognize that ALPHA_SE specifies the configuration because it
3306498Snate@binkert.org# follow 'build' in the build path.
3316498Snate@binkert.org
3326498Snate@binkert.org# The funky assignment to "[:]" is needed to replace the list contents
3334479Sbinkertn@umich.edu# in place rather than reassign the symbol to a new list, which
3344479Sbinkertn@umich.edu# doesn't work (obviously!).
3354479Sbinkertn@umich.eduBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3364479Sbinkertn@umich.edu
3374479Sbinkertn@umich.edu# Generate a list of the unique build roots and configs that the
3384479Sbinkertn@umich.edu# collected targets reference.
3394479Sbinkertn@umich.eduvariant_paths = []
3404479Sbinkertn@umich.edubuild_root = None
3414479Sbinkertn@umich.edufor t in BUILD_TARGETS:
3424479Sbinkertn@umich.edu    path_dirs = t.split('/')
3434479Sbinkertn@umich.edu    try:
3444479Sbinkertn@umich.edu        build_top = rfind(path_dirs, 'build', -2)
3454479Sbinkertn@umich.edu    except:
3464479Sbinkertn@umich.edu        print "Error: no non-leaf 'build' dir found on target path", t
3474479Sbinkertn@umich.edu        Exit(1)
3484479Sbinkertn@umich.edu    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3494479Sbinkertn@umich.edu    if not build_root:
3504479Sbinkertn@umich.edu        build_root = this_build_root
3514479Sbinkertn@umich.edu    else:
3524479Sbinkertn@umich.edu        if this_build_root != build_root:
3534479Sbinkertn@umich.edu            print "Error: build targets not under same build root\n"\
3544479Sbinkertn@umich.edu                  "  %s\n  %s" % (build_root, this_build_root)
3554479Sbinkertn@umich.edu            Exit(1)
3564479Sbinkertn@umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
3574479Sbinkertn@umich.edu    if variant_path not in variant_paths:
3584479Sbinkertn@umich.edu        variant_paths.append(variant_path)
3594479Sbinkertn@umich.edu
3604479Sbinkertn@umich.edu# Make sure build_root exists (might not if this is the first build there)
3614479Sbinkertn@umich.eduif not isdir(build_root):
3624479Sbinkertn@umich.edu    mkdir(build_root)
3634479Sbinkertn@umich.edumain['BUILDROOT'] = build_root
3644479Sbinkertn@umich.edu
3654479Sbinkertn@umich.eduExport('main')
3664479Sbinkertn@umich.edu
3674479Sbinkertn@umich.edumain.SConsignFile(joinpath(build_root, "sconsign"))
3684479Sbinkertn@umich.edu
3694479Sbinkertn@umich.edu# Default duplicate option is to use hard links, but this messes up
3704479Sbinkertn@umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
3714479Sbinkertn@umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
3724479Sbinkertn@umich.edu# (soft) links work better.
3734479Sbinkertn@umich.edumain.SetOption('duplicate', 'soft-copy')
3744479Sbinkertn@umich.edu
3754479Sbinkertn@umich.edu#
3764479Sbinkertn@umich.edu# Set up global sticky variables... these are common to an entire build
3774479Sbinkertn@umich.edu# tree (not specific to a particular build like ALPHA_SE)
3784479Sbinkertn@umich.edu#
3794479Sbinkertn@umich.edu
3804479Sbinkertn@umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
3814479Sbinkertn@umich.edu
3824479Sbinkertn@umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3834479Sbinkertn@umich.edu
3844479Sbinkertn@umich.eduglobal_vars.AddVariables(
3854479Sbinkertn@umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3864479Sbinkertn@umich.edu    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3874479Sbinkertn@umich.edu    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
3884479Sbinkertn@umich.edu    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
3894479Sbinkertn@umich.edu    ('BATCH', 'Use batch pool for build and tests', False),
3904479Sbinkertn@umich.edu    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3914479Sbinkertn@umich.edu    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
3924479Sbinkertn@umich.edu    ('EXTRAS', 'Add extra directories to the compilation', '')
3934479Sbinkertn@umich.edu    )
3944479Sbinkertn@umich.edu
3954479Sbinkertn@umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
3964479Sbinkertn@umich.eduglobal_vars.Update(main)
3974479Sbinkertn@umich.eduhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3984479Sbinkertn@umich.edu
3994479Sbinkertn@umich.edu# Save sticky variable settings back to current variables file
4004479Sbinkertn@umich.eduglobal_vars.Save(global_vars_file, main)
4014479Sbinkertn@umich.edu
4024479Sbinkertn@umich.edu# Parse EXTRAS variable to build list of all directories where we're
4034479Sbinkertn@umich.edu# look for sources etc.  This list is exported as extras_dir_list.
4044479Sbinkertn@umich.edubase_dir = main.srcdir.abspath
4054479Sbinkertn@umich.eduif main['EXTRAS']:
4064479Sbinkertn@umich.edu    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
4074479Sbinkertn@umich.eduelse:
4084479Sbinkertn@umich.edu    extras_dir_list = []
4094479Sbinkertn@umich.edu
4104479Sbinkertn@umich.eduExport('base_dir')
4114479Sbinkertn@umich.eduExport('extras_dir_list')
4124479Sbinkertn@umich.edu
4134479Sbinkertn@umich.edu# the ext directory should be on the #includes path
4144479Sbinkertn@umich.edumain.Append(CPPPATH=[Dir('ext')])
4154479Sbinkertn@umich.edu
4164479Sbinkertn@umich.edudef strip_build_path(path, env):
4174479Sbinkertn@umich.edu    path = str(path)
4184479Sbinkertn@umich.edu    variant_base = env['BUILDROOT'] + os.path.sep
4194479Sbinkertn@umich.edu    if path.startswith(variant_base):
4204479Sbinkertn@umich.edu        path = path[len(variant_base):]
4214479Sbinkertn@umich.edu    elif path.startswith('build/'):
4224479Sbinkertn@umich.edu        path = path[6:]
4234479Sbinkertn@umich.edu    return path
4244479Sbinkertn@umich.edu
4254479Sbinkertn@umich.edu# Generate a string of the form:
4264479Sbinkertn@umich.edu#   common/path/prefix/src1, src2 -> tgt1, tgt2
4274479Sbinkertn@umich.edu# to print while building.
4284479Sbinkertn@umich.educlass Transform(object):
4294479Sbinkertn@umich.edu    # all specific color settings should be here and nowhere else
4304479Sbinkertn@umich.edu    tool_color = termcap.Normal
4314479Sbinkertn@umich.edu    pfx_color = termcap.Yellow
4324479Sbinkertn@umich.edu    srcs_color = termcap.Yellow + termcap.Bold
4334479Sbinkertn@umich.edu    arrow_color = termcap.Blue + termcap.Bold
4344479Sbinkertn@umich.edu    tgts_color = termcap.Yellow + termcap.Bold
4354479Sbinkertn@umich.edu
4364479Sbinkertn@umich.edu    def __init__(self, tool, max_sources=99):
4374479Sbinkertn@umich.edu        self.format = self.tool_color + (" [%8s] " % tool) \
4384479Sbinkertn@umich.edu                      + self.pfx_color + "%s" \
4394479Sbinkertn@umich.edu                      + self.srcs_color + "%s" \
4404479Sbinkertn@umich.edu                      + self.arrow_color + " -> " \
4414479Sbinkertn@umich.edu                      + self.tgts_color + "%s" \
4424479Sbinkertn@umich.edu                      + termcap.Normal
4434479Sbinkertn@umich.edu        self.max_sources = max_sources
4444479Sbinkertn@umich.edu
4454479Sbinkertn@umich.edu    def __call__(self, target, source, env, for_signature=None):
4464479Sbinkertn@umich.edu        # truncate source list according to max_sources param
4474479Sbinkertn@umich.edu        source = source[0:self.max_sources]
4484479Sbinkertn@umich.edu        def strip(f):
4494479Sbinkertn@umich.edu            return strip_build_path(str(f), env)
4504479Sbinkertn@umich.edu        if len(source) > 0:
4514479Sbinkertn@umich.edu            srcs = map(strip, source)
4524479Sbinkertn@umich.edu        else:
4534479Sbinkertn@umich.edu            srcs = ['']
4544479Sbinkertn@umich.edu        tgts = map(strip, target)
4554479Sbinkertn@umich.edu        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4564479Sbinkertn@umich.edu        # operation that has nothing to do with paths.
4574479Sbinkertn@umich.edu        com_pfx = os.path.commonprefix(srcs + tgts)
4584479Sbinkertn@umich.edu        com_pfx_len = len(com_pfx)
4594479Sbinkertn@umich.edu        if com_pfx:
4604479Sbinkertn@umich.edu            # do some cleanup and sanity checking on common prefix
4614479Sbinkertn@umich.edu            if com_pfx[-1] == ".":
4624479Sbinkertn@umich.edu                # prefix matches all but file extension: ok
4634479Sbinkertn@umich.edu                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4644479Sbinkertn@umich.edu                com_pfx = com_pfx[0:-1]
4654479Sbinkertn@umich.edu            elif com_pfx[-1] == "/":
4664479Sbinkertn@umich.edu                # common prefix is directory path: OK
4674479Sbinkertn@umich.edu                pass
4684479Sbinkertn@umich.edu            else:
4694479Sbinkertn@umich.edu                src0_len = len(srcs[0])
4704479Sbinkertn@umich.edu                tgt0_len = len(tgts[0])
4714479Sbinkertn@umich.edu                if src0_len == com_pfx_len:
4724479Sbinkertn@umich.edu                    # source is a substring of target, OK
4734479Sbinkertn@umich.edu                    pass
4744479Sbinkertn@umich.edu                elif tgt0_len == com_pfx_len:
4754479Sbinkertn@umich.edu                    # target is a substring of source, need to back up to
4764479Sbinkertn@umich.edu                    # avoid empty string on RHS of arrow
4774479Sbinkertn@umich.edu                    sep_idx = com_pfx.rfind(".")
4784479Sbinkertn@umich.edu                    if sep_idx != -1:
4794479Sbinkertn@umich.edu                        com_pfx = com_pfx[0:sep_idx]
4804479Sbinkertn@umich.edu                    else:
4814479Sbinkertn@umich.edu                        com_pfx = ''
4824479Sbinkertn@umich.edu                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4834479Sbinkertn@umich.edu                    # still splitting at file extension: ok
4844479Sbinkertn@umich.edu                    pass
4854479Sbinkertn@umich.edu                else:
4864479Sbinkertn@umich.edu                    # probably a fluke; ignore it
4874479Sbinkertn@umich.edu                    com_pfx = ''
4884479Sbinkertn@umich.edu        # recalculate length in case com_pfx was modified
4894479Sbinkertn@umich.edu        com_pfx_len = len(com_pfx)
4904479Sbinkertn@umich.edu        def fmt(files):
4914479Sbinkertn@umich.edu            f = map(lambda s: s[com_pfx_len:], files)
4924479Sbinkertn@umich.edu            return ', '.join(f)
4934479Sbinkertn@umich.edu        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
4944479Sbinkertn@umich.edu
4954479Sbinkertn@umich.eduExport('Transform')
4964479Sbinkertn@umich.edu
4974479Sbinkertn@umich.edu# enable the regression script to use the termcap
4984479Sbinkertn@umich.edumain['TERMCAP'] = termcap
4994479Sbinkertn@umich.edu
5004479Sbinkertn@umich.eduif GetOption('verbose'):
5014479Sbinkertn@umich.edu    def MakeAction(action, string, *args, **kwargs):
5024479Sbinkertn@umich.edu        return Action(action, *args, **kwargs)
5034479Sbinkertn@umich.eduelse:
5044479Sbinkertn@umich.edu    MakeAction = Action
5054479Sbinkertn@umich.edu    main['CCCOMSTR']        = Transform("CC")
5064479Sbinkertn@umich.edu    main['CXXCOMSTR']       = Transform("CXX")
5074479Sbinkertn@umich.edu    main['ASCOMSTR']        = Transform("AS")
5084479Sbinkertn@umich.edu    main['SWIGCOMSTR']      = Transform("SWIG")
5094479Sbinkertn@umich.edu    main['ARCOMSTR']        = Transform("AR", 0)
5104479Sbinkertn@umich.edu    main['LINKCOMSTR']      = Transform("LINK", 0)
5114479Sbinkertn@umich.edu    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
5124479Sbinkertn@umich.edu    main['M4COMSTR']        = Transform("M4")
5134479Sbinkertn@umich.edu    main['SHCCCOMSTR']      = Transform("SHCC")
5144479Sbinkertn@umich.edu    main['SHCXXCOMSTR']     = Transform("SHCXX")
5154479Sbinkertn@umich.eduExport('MakeAction')
5164479Sbinkertn@umich.edu
5174479Sbinkertn@umich.edu# Initialize the Link-Time Optimization (LTO) flags
5184479Sbinkertn@umich.edumain['LTO_CCFLAGS'] = []
5194479Sbinkertn@umich.edumain['LTO_LDFLAGS'] = []
5204479Sbinkertn@umich.edu
5214479Sbinkertn@umich.edu# According to the readme, tcmalloc works best if the compiler doesn't
5224479Sbinkertn@umich.edu# assume that we're using the builtin malloc and friends. These flags
5234479Sbinkertn@umich.edu# are compiler-specific, so we need to set them after we detect which
5244479Sbinkertn@umich.edu# compiler we're using.
5254479Sbinkertn@umich.edumain['TCMALLOC_CCFLAGS'] = []
5264479Sbinkertn@umich.edu
5274479Sbinkertn@umich.eduCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5284479Sbinkertn@umich.eduCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5294479Sbinkertn@umich.edu
5304479Sbinkertn@umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5314479Sbinkertn@umich.edumain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5324479Sbinkertn@umich.eduif main['GCC'] + main['CLANG'] > 1:
5334479Sbinkertn@umich.edu    print 'Error: How can we have two at the same time?'
5344479Sbinkertn@umich.edu    Exit(1)
5354479Sbinkertn@umich.edu
5364479Sbinkertn@umich.edu# Set up default C++ compiler flags
5374479Sbinkertn@umich.eduif main['GCC'] or main['CLANG']:
5384479Sbinkertn@umich.edu    # As gcc and clang share many flags, do the common parts here
5394479Sbinkertn@umich.edu    main.Append(CCFLAGS=['-pipe'])
5404479Sbinkertn@umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5414479Sbinkertn@umich.edu    # Enable -Wall and then disable the few warnings that we
5424479Sbinkertn@umich.edu    # consistently violate
5434479Sbinkertn@umich.edu    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5444479Sbinkertn@umich.edu    # We always compile using C++11, but only gcc >= 4.7 and clang 3.1
5454479Sbinkertn@umich.edu    # actually use that name, so we stick with c++0x
5464479Sbinkertn@umich.edu    main.Append(CXXFLAGS=['-std=c++0x'])
5474479Sbinkertn@umich.edu    # Add selected sanity checks from -Wextra
5484479Sbinkertn@umich.edu    main.Append(CXXFLAGS=['-Wmissing-field-initializers',
5494479Sbinkertn@umich.edu                          '-Woverloaded-virtual'])
5504479Sbinkertn@umich.eduelse:
5514479Sbinkertn@umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5524479Sbinkertn@umich.edu    print "Don't know what compiler options to use for your compiler."
5534479Sbinkertn@umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5544479Sbinkertn@umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
5554479Sbinkertn@umich.edu    if not CXX_version:
5564479Sbinkertn@umich.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5574479Sbinkertn@umich.edu               termcap.Normal
5584479Sbinkertn@umich.edu    else:
5594479Sbinkertn@umich.edu        print CXX_version.replace('\n', '<nl>')
5604479Sbinkertn@umich.edu    print "       If you're trying to use a compiler other than GCC"
5614479Sbinkertn@umich.edu    print "       or clang, there appears to be something wrong with your"
5624479Sbinkertn@umich.edu    print "       environment."
5634479Sbinkertn@umich.edu    print "       "
5644479Sbinkertn@umich.edu    print "       If you are trying to use a compiler other than those listed"
5654479Sbinkertn@umich.edu    print "       above you will need to ease fix SConstruct and "
5664479Sbinkertn@umich.edu    print "       src/SConscript to support that compiler."
5674479Sbinkertn@umich.edu    Exit(1)
5684479Sbinkertn@umich.edu
5694479Sbinkertn@umich.eduif main['GCC']:
5704479Sbinkertn@umich.edu    # Check for a supported version of gcc, >= 4.4 is needed for c++0x
5714479Sbinkertn@umich.edu    # support. See http://gcc.gnu.org/projects/cxx0x.html for details
5724479Sbinkertn@umich.edu    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5734479Sbinkertn@umich.edu    if compareVersions(gcc_version, "4.4") < 0:
5744479Sbinkertn@umich.edu        print 'Error: gcc version 4.4 or newer required.'
5754479Sbinkertn@umich.edu        print '       Installed version:', gcc_version
5764479Sbinkertn@umich.edu        Exit(1)
5774479Sbinkertn@umich.edu
5784479Sbinkertn@umich.edu    main['GCC_VERSION'] = gcc_version
5794479Sbinkertn@umich.edu
5804479Sbinkertn@umich.edu    # Check for versions with bugs
5814479Sbinkertn@umich.edu    if not compareVersions(gcc_version, '4.4.1') or \
5824479Sbinkertn@umich.edu       not compareVersions(gcc_version, '4.4.2'):
5834479Sbinkertn@umich.edu        print 'Info: Tree vectorizer in GCC 4.4.1 & 4.4.2 is buggy, disabling.'
5844479Sbinkertn@umich.edu        main.Append(CCFLAGS=['-fno-tree-vectorize'])
5854479Sbinkertn@umich.edu
5864479Sbinkertn@umich.edu    # LTO support is only really working properly from 4.6 and beyond
5874479Sbinkertn@umich.edu    if compareVersions(gcc_version, '4.6') >= 0:
5884479Sbinkertn@umich.edu        # Add the appropriate Link-Time Optimization (LTO) flags
5894479Sbinkertn@umich.edu        # unless LTO is explicitly turned off. Note that these flags
5904479Sbinkertn@umich.edu        # are only used by the fast target.
5914479Sbinkertn@umich.edu        if not GetOption('no_lto'):
5924479Sbinkertn@umich.edu            # Pass the LTO flag when compiling to produce GIMPLE
5934479Sbinkertn@umich.edu            # output, we merely create the flags here and only append
5944479Sbinkertn@umich.edu            # them later/
5954479Sbinkertn@umich.edu            main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
5964479Sbinkertn@umich.edu
5974479Sbinkertn@umich.edu            # Use the same amount of jobs for LTO as we are running
5984479Sbinkertn@umich.edu            # scons with, we hardcode the use of the linker plugin
5994479Sbinkertn@umich.edu            # which requires either gold or GNU ld >= 2.21
6004479Sbinkertn@umich.edu            main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs'),
6014479Sbinkertn@umich.edu                                   '-fuse-linker-plugin']
6024479Sbinkertn@umich.edu
6034479Sbinkertn@umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
6044479Sbinkertn@umich.edu                                  '-fno-builtin-realloc', '-fno-builtin-free'])
6054479Sbinkertn@umich.edu
6064479Sbinkertn@umich.eduelif main['CLANG']:
6074479Sbinkertn@umich.edu    # Check for a supported version of clang, >= 2.9 is needed to
6084479Sbinkertn@umich.edu    # support similar features as gcc 4.4. See
6094479Sbinkertn@umich.edu    # http://clang.llvm.org/cxx_status.html for details
6104479Sbinkertn@umich.edu    clang_version_re = re.compile(".* version (\d+\.\d+)")
6114479Sbinkertn@umich.edu    clang_version_match = clang_version_re.search(CXX_version)
6124479Sbinkertn@umich.edu    if (clang_version_match):
6134479Sbinkertn@umich.edu        clang_version = clang_version_match.groups()[0]
6144479Sbinkertn@umich.edu        if compareVersions(clang_version, "2.9") < 0:
6154479Sbinkertn@umich.edu            print 'Error: clang version 2.9 or newer required.'
6164479Sbinkertn@umich.edu            print '       Installed version:', clang_version
6174479Sbinkertn@umich.edu            Exit(1)
6184479Sbinkertn@umich.edu    else:
6194479Sbinkertn@umich.edu        print 'Error: Unable to determine clang version.'
6204479Sbinkertn@umich.edu        Exit(1)
6214479Sbinkertn@umich.edu
6224479Sbinkertn@umich.edu    # clang has a few additional warnings that we disable,
6234479Sbinkertn@umich.edu    # tautological comparisons are allowed due to unsigned integers
6244479Sbinkertn@umich.edu    # being compared to constants that happen to be 0, and extraneous
6254479Sbinkertn@umich.edu    # parantheses are allowed due to Ruby's printing of the AST,
6264479Sbinkertn@umich.edu    # finally self assignments are allowed as the generated CPU code
6274479Sbinkertn@umich.edu    # is relying on this
6284479Sbinkertn@umich.edu    main.Append(CCFLAGS=['-Wno-tautological-compare',
6294479Sbinkertn@umich.edu                         '-Wno-parentheses',
6304479Sbinkertn@umich.edu                         '-Wno-self-assign'])
6314479Sbinkertn@umich.edu
6324479Sbinkertn@umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
6334479Sbinkertn@umich.edu
6344479Sbinkertn@umich.edu    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
6354479Sbinkertn@umich.edu    # opposed to libstdc++, as the later is dated.
6364479Sbinkertn@umich.edu    if sys.platform == "darwin":
6374479Sbinkertn@umich.edu        main.Append(CXXFLAGS=['-stdlib=libc++'])
6384479Sbinkertn@umich.edu        main.Append(LIBS=['c++'])
6394479Sbinkertn@umich.edu
6404479Sbinkertn@umich.eduelse:
6414479Sbinkertn@umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6424479Sbinkertn@umich.edu    print "Don't know what compiler options to use for your compiler."
6434479Sbinkertn@umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6444479Sbinkertn@umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
6454479Sbinkertn@umich.edu    if not CXX_version:
6464479Sbinkertn@umich.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6474479Sbinkertn@umich.edu               termcap.Normal
6484479Sbinkertn@umich.edu    else:
6494479Sbinkertn@umich.edu        print CXX_version.replace('\n', '<nl>')
6504479Sbinkertn@umich.edu    print "       If you're trying to use a compiler other than GCC"
6514479Sbinkertn@umich.edu    print "       or clang, there appears to be something wrong with your"
6524479Sbinkertn@umich.edu    print "       environment."
6534479Sbinkertn@umich.edu    print "       "
6544479Sbinkertn@umich.edu    print "       If you are trying to use a compiler other than those listed"
6554479Sbinkertn@umich.edu    print "       above you will need to ease fix SConstruct and "
6564479Sbinkertn@umich.edu    print "       src/SConscript to support that compiler."
6574479Sbinkertn@umich.edu    Exit(1)
6584479Sbinkertn@umich.edu
6594479Sbinkertn@umich.edu# Set up common yacc/bison flags (needed for Ruby)
6604479Sbinkertn@umich.edumain['YACCFLAGS'] = '-d'
6614479Sbinkertn@umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
6624479Sbinkertn@umich.edu
6634479Sbinkertn@umich.edu# Do this after we save setting back, or else we'll tack on an
6644479Sbinkertn@umich.edu# extra 'qdo' every time we run scons.
6654479Sbinkertn@umich.eduif main['BATCH']:
6664479Sbinkertn@umich.edu    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
6674479Sbinkertn@umich.edu    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
6684479Sbinkertn@umich.edu    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
6694479Sbinkertn@umich.edu    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
6704479Sbinkertn@umich.edu    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
6714479Sbinkertn@umich.edu
6724479Sbinkertn@umich.eduif sys.platform == 'cygwin':
6734479Sbinkertn@umich.edu    # cygwin has some header file issues...
6744479Sbinkertn@umich.edu    main.Append(CCFLAGS=["-Wno-uninitialized"])
6754479Sbinkertn@umich.edu
6764479Sbinkertn@umich.edu# Check for the protobuf compiler
6774479Sbinkertn@umich.eduprotoc_version = readCommand([main['PROTOC'], '--version'],
6784479Sbinkertn@umich.edu                             exception='').split()
6794479Sbinkertn@umich.edu
6804479Sbinkertn@umich.edu# First two words should be "libprotoc x.y.z"
6814479Sbinkertn@umich.eduif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6824479Sbinkertn@umich.edu    print termcap.Yellow + termcap.Bold + \
6834479Sbinkertn@umich.edu        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
6844479Sbinkertn@umich.edu        '         Please install protobuf-compiler for tracing support.' + \
6854479Sbinkertn@umich.edu        termcap.Normal
6864479Sbinkertn@umich.edu    main['PROTOC'] = False
6874479Sbinkertn@umich.eduelse:
6884479Sbinkertn@umich.edu    # Based on the availability of the compress stream wrappers,
6894479Sbinkertn@umich.edu    # require 2.1.0
6904479Sbinkertn@umich.edu    min_protoc_version = '2.1.0'
6914479Sbinkertn@umich.edu    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6924479Sbinkertn@umich.edu        print termcap.Yellow + termcap.Bold + \
6934479Sbinkertn@umich.edu            'Warning: protoc version', min_protoc_version, \
6944479Sbinkertn@umich.edu            'or newer required.\n' + \
6954479Sbinkertn@umich.edu            '         Installed version:', protoc_version[1], \
6964479Sbinkertn@umich.edu            termcap.Normal
6974479Sbinkertn@umich.edu        main['PROTOC'] = False
6984479Sbinkertn@umich.edu    else:
6994479Sbinkertn@umich.edu        # Attempt to determine the appropriate include path and
7004479Sbinkertn@umich.edu        # library path using pkg-config, that means we also need to
7014479Sbinkertn@umich.edu        # check for pkg-config. Note that it is possible to use
7024479Sbinkertn@umich.edu        # protobuf without the involvement of pkg-config. Later on we
7034479Sbinkertn@umich.edu        # check go a library config check and at that point the test
7044479Sbinkertn@umich.edu        # will fail if libprotobuf cannot be found.
7054479Sbinkertn@umich.edu        if readCommand(['pkg-config', '--version'], exception=''):
7064479Sbinkertn@umich.edu            try:
7074479Sbinkertn@umich.edu                # Attempt to establish what linking flags to add for protobuf
7084479Sbinkertn@umich.edu                # using pkg-config
7094479Sbinkertn@umich.edu                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
7104479Sbinkertn@umich.edu            except:
7114479Sbinkertn@umich.edu                print termcap.Yellow + termcap.Bold + \
7124479Sbinkertn@umich.edu                    'Warning: pkg-config could not get protobuf flags.' + \
7134479Sbinkertn@umich.edu                    termcap.Normal
7144479Sbinkertn@umich.edu
7154479Sbinkertn@umich.edu# Check for SWIG
7164479Sbinkertn@umich.eduif not main.has_key('SWIG'):
7174479Sbinkertn@umich.edu    print 'Error: SWIG utility not found.'
7184479Sbinkertn@umich.edu    print '       Please install (see http://www.swig.org) and retry.'
7194479Sbinkertn@umich.edu    Exit(1)
7204479Sbinkertn@umich.edu
7214479Sbinkertn@umich.edu# Check for appropriate SWIG version
7224479Sbinkertn@umich.eduswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
7234479Sbinkertn@umich.edu# First 3 words should be "SWIG Version x.y.z"
7244479Sbinkertn@umich.eduif len(swig_version) < 3 or \
7254479Sbinkertn@umich.edu        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
7264479Sbinkertn@umich.edu    print 'Error determining SWIG version.'
7274479Sbinkertn@umich.edu    Exit(1)
7284479Sbinkertn@umich.edu
7294479Sbinkertn@umich.edumin_swig_version = '2.0.4'
7304479Sbinkertn@umich.eduif compareVersions(swig_version[2], min_swig_version) < 0:
7314479Sbinkertn@umich.edu    print 'Error: SWIG version', min_swig_version, 'or newer required.'
7324479Sbinkertn@umich.edu    print '       Installed version:', swig_version[2]
7334479Sbinkertn@umich.edu    Exit(1)
7344479Sbinkertn@umich.edu
7354479Sbinkertn@umich.edu# Set up SWIG flags & scanner
7364479Sbinkertn@umich.eduswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
7374479Sbinkertn@umich.edumain.Append(SWIGFLAGS=swig_flags)
7384479Sbinkertn@umich.edu
7394479Sbinkertn@umich.edu# filter out all existing swig scanners, they mess up the dependency
7404479Sbinkertn@umich.edu# stuff for some reason
7414479Sbinkertn@umich.eduscanners = []
7424479Sbinkertn@umich.edufor scanner in main['SCANNERS']:
7434479Sbinkertn@umich.edu    skeys = scanner.skeys
7444479Sbinkertn@umich.edu    if skeys == '.i':
7454479Sbinkertn@umich.edu        continue
7464479Sbinkertn@umich.edu
7474479Sbinkertn@umich.edu    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
7484479Sbinkertn@umich.edu        continue
7494479Sbinkertn@umich.edu
7504479Sbinkertn@umich.edu    scanners.append(scanner)
7514479Sbinkertn@umich.edu
7524479Sbinkertn@umich.edu# add the new swig scanner that we like better
7534479Sbinkertn@umich.edufrom SCons.Scanner import ClassicCPP as CPPScanner
7544479Sbinkertn@umich.eduswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
7554479Sbinkertn@umich.eduscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
7564479Sbinkertn@umich.edu
7574479Sbinkertn@umich.edu# replace the scanners list that has what we want
7584479Sbinkertn@umich.edumain['SCANNERS'] = scanners
7594479Sbinkertn@umich.edu
7604479Sbinkertn@umich.edu# Add a custom Check function to the Configure context so that we can
7614479Sbinkertn@umich.edu# figure out if the compiler adds leading underscores to global
7624479Sbinkertn@umich.edu# variables.  This is needed for the autogenerated asm files that we
7634479Sbinkertn@umich.edu# use for embedding the python code.
7644479Sbinkertn@umich.edudef CheckLeading(context):
7654479Sbinkertn@umich.edu    context.Message("Checking for leading underscore in global variables...")
7664479Sbinkertn@umich.edu    # 1) Define a global variable called x from asm so the C compiler
7674479Sbinkertn@umich.edu    #    won't change the symbol at all.
7684479Sbinkertn@umich.edu    # 2) Declare that variable.
7694479Sbinkertn@umich.edu    # 3) Use the variable
7704479Sbinkertn@umich.edu    #
7714479Sbinkertn@umich.edu    # If the compiler prepends an underscore, this will successfully
7724479Sbinkertn@umich.edu    # link because the external symbol 'x' will be called '_x' which
7734479Sbinkertn@umich.edu    # was defined by the asm statement.  If the compiler does not
7744479Sbinkertn@umich.edu    # prepend an underscore, this will not successfully link because
7754479Sbinkertn@umich.edu    # '_x' will have been defined by assembly, while the C portion of
7764479Sbinkertn@umich.edu    # the code will be trying to use 'x'
7774479Sbinkertn@umich.edu    ret = context.TryLink('''
7784479Sbinkertn@umich.edu        asm(".globl _x; _x: .byte 0");
7794479Sbinkertn@umich.edu        extern int x;
7804479Sbinkertn@umich.edu        int main() { return x; }
7814479Sbinkertn@umich.edu        ''', extension=".c")
7824479Sbinkertn@umich.edu    context.env.Append(LEADING_UNDERSCORE=ret)
7834479Sbinkertn@umich.edu    context.Result(ret)
7844479Sbinkertn@umich.edu    return ret
7854479Sbinkertn@umich.edu
7864479Sbinkertn@umich.edu# Add a custom Check function to test for structure members.
7874479Sbinkertn@umich.edudef CheckMember(context, include, decl, member, include_quotes="<>"):
7884479Sbinkertn@umich.edu    context.Message("Checking for member %s in %s..." %
7894479Sbinkertn@umich.edu                    (member, decl))
7904479Sbinkertn@umich.edu    text = """
7914479Sbinkertn@umich.edu#include %(header)s
7924479Sbinkertn@umich.eduint main(){
7934479Sbinkertn@umich.edu  %(decl)s test;
7944479Sbinkertn@umich.edu  (void)test.%(member)s;
7954479Sbinkertn@umich.edu  return 0;
7964479Sbinkertn@umich.edu};
7974479Sbinkertn@umich.edu""" % { "header" : include_quotes[0] + include + include_quotes[1],
7984479Sbinkertn@umich.edu        "decl" : decl,
7994479Sbinkertn@umich.edu        "member" : member,
8004479Sbinkertn@umich.edu        }
8014479Sbinkertn@umich.edu
8024479Sbinkertn@umich.edu    ret = context.TryCompile(text, extension=".cc")
8034479Sbinkertn@umich.edu    context.Result(ret)
8044479Sbinkertn@umich.edu    return ret
8054479Sbinkertn@umich.edu
8064479Sbinkertn@umich.edu# Platform-specific configuration.  Note again that we assume that all
8074479Sbinkertn@umich.edu# builds under a given build root run on the same host platform.
8084479Sbinkertn@umich.educonf = Configure(main,
8094479Sbinkertn@umich.edu                 conf_dir = joinpath(build_root, '.scons_config'),
8104479Sbinkertn@umich.edu                 log_file = joinpath(build_root, 'scons_config.log'),
8114479Sbinkertn@umich.edu                 custom_tests = {
8124479Sbinkertn@umich.edu        'CheckLeading' : CheckLeading,
8134479Sbinkertn@umich.edu        'CheckMember' : CheckMember,
8144479Sbinkertn@umich.edu        })
8154479Sbinkertn@umich.edu
8164479Sbinkertn@umich.edu# Check for leading underscores.  Don't really need to worry either
8174479Sbinkertn@umich.edu# way so don't need to check the return code.
8184479Sbinkertn@umich.educonf.CheckLeading()
8194479Sbinkertn@umich.edu
8204479Sbinkertn@umich.edu# Check if we should compile a 64 bit binary on Mac OS X/Darwin
8214479Sbinkertn@umich.edutry:
8224479Sbinkertn@umich.edu    import platform
8234479Sbinkertn@umich.edu    uname = platform.uname()
8244479Sbinkertn@umich.edu    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
8254479Sbinkertn@umich.edu        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
8264479Sbinkertn@umich.edu            main.Append(CCFLAGS=['-arch', 'x86_64'])
8274479Sbinkertn@umich.edu            main.Append(CFLAGS=['-arch', 'x86_64'])
8284479Sbinkertn@umich.edu            main.Append(LINKFLAGS=['-arch', 'x86_64'])
8294479Sbinkertn@umich.edu            main.Append(ASFLAGS=['-arch', 'x86_64'])
8304479Sbinkertn@umich.eduexcept:
8314479Sbinkertn@umich.edu    pass
8324479Sbinkertn@umich.edu
8334479Sbinkertn@umich.edu# Recent versions of scons substitute a "Null" object for Configure()
8344479Sbinkertn@umich.edu# when configuration isn't necessary, e.g., if the "--help" option is
8354479Sbinkertn@umich.edu# present.  Unfortuantely this Null object always returns false,
8364479Sbinkertn@umich.edu# breaking all our configuration checks.  We replace it with our own
8374479Sbinkertn@umich.edu# more optimistic null object that returns True instead.
8384479Sbinkertn@umich.eduif not conf:
8394479Sbinkertn@umich.edu    def NullCheck(*args, **kwargs):
8404479Sbinkertn@umich.edu        return True
8414479Sbinkertn@umich.edu
8424479Sbinkertn@umich.edu    class NullConf:
8434479Sbinkertn@umich.edu        def __init__(self, env):
8444479Sbinkertn@umich.edu            self.env = env
8454479Sbinkertn@umich.edu        def Finish(self):
8464479Sbinkertn@umich.edu            return self.env
8474479Sbinkertn@umich.edu        def __getattr__(self, mname):
8484479Sbinkertn@umich.edu            return NullCheck
8494479Sbinkertn@umich.edu
8504479Sbinkertn@umich.edu    conf = NullConf(main)
8514479Sbinkertn@umich.edu
8524479Sbinkertn@umich.edu# Cache build files in the supplied directory.
8534479Sbinkertn@umich.eduif main['M5_BUILD_CACHE']:
8544479Sbinkertn@umich.edu    print 'Using build cache located at', main['M5_BUILD_CACHE']
8554479Sbinkertn@umich.edu    CacheDir(main['M5_BUILD_CACHE'])
8564479Sbinkertn@umich.edu
8574479Sbinkertn@umich.edu# Find Python include and library directories for embedding the
8584479Sbinkertn@umich.edu# interpreter. We rely on python-config to resolve the appropriate
8594479Sbinkertn@umich.edu# includes and linker flags. ParseConfig does not seem to understand
8604479Sbinkertn@umich.edu# the more exotic linker flags such as -Xlinker and -export-dynamic so
8614479Sbinkertn@umich.edu# we add them explicitly below. If you want to link in an alternate
8624479Sbinkertn@umich.edu# version of python, see above for instructions on how to invoke
8634479Sbinkertn@umich.edu# scons with the appropriate PATH set.
8644479Sbinkertn@umich.edu#
8654479Sbinkertn@umich.edu# First we check if python2-config exists, else we use python-config
8664479Sbinkertn@umich.edupython_config = readCommand(['which', 'python2-config'], exception='').strip()
8674479Sbinkertn@umich.eduif not os.path.exists(python_config):
8684479Sbinkertn@umich.edu    python_config = readCommand(['which', 'python-config'],
8694479Sbinkertn@umich.edu                                exception='').strip()
8704479Sbinkertn@umich.edupy_includes = readCommand([python_config, '--includes'],
8714479Sbinkertn@umich.edu                          exception='').split()
8724479Sbinkertn@umich.edu# Strip the -I from the include folders before adding them to the
8734479Sbinkertn@umich.edu# CPPPATH
8744479Sbinkertn@umich.edumain.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
8754479Sbinkertn@umich.edu
8764479Sbinkertn@umich.edu# Read the linker flags and split them into libraries and other link
8774479Sbinkertn@umich.edu# flags. The libraries are added later through the call the CheckLib.
8784479Sbinkertn@umich.edupy_ld_flags = readCommand([python_config, '--ldflags'], exception='').split()
8794479Sbinkertn@umich.edupy_libs = []
8804479Sbinkertn@umich.edufor lib in py_ld_flags:
8814479Sbinkertn@umich.edu     if not lib.startswith('-l'):
8824479Sbinkertn@umich.edu         main.Append(LINKFLAGS=[lib])
8834479Sbinkertn@umich.edu     else:
8844479Sbinkertn@umich.edu         lib = lib[2:]
8854479Sbinkertn@umich.edu         if lib not in py_libs:
8864479Sbinkertn@umich.edu             py_libs.append(lib)
8874479Sbinkertn@umich.edu
8884479Sbinkertn@umich.edu# verify that this stuff works
8894479Sbinkertn@umich.eduif not conf.CheckHeader('Python.h', '<>'):
8904479Sbinkertn@umich.edu    print "Error: can't find Python.h header in", py_includes
8914479Sbinkertn@umich.edu    print "Install Python headers (package python-dev on Ubuntu and RedHat)"
8924479Sbinkertn@umich.edu    Exit(1)
8934479Sbinkertn@umich.edu
8944479Sbinkertn@umich.edufor lib in py_libs:
8954479Sbinkertn@umich.edu    if not conf.CheckLib(lib):
8964479Sbinkertn@umich.edu        print "Error: can't find library %s required by python" % lib
8974479Sbinkertn@umich.edu        Exit(1)
8984479Sbinkertn@umich.edu
8994479Sbinkertn@umich.edu# On Solaris you need to use libsocket for socket ops
9004479Sbinkertn@umich.eduif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
9014479Sbinkertn@umich.edu   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
9024479Sbinkertn@umich.edu       print "Can't find library with socket calls (e.g. accept())"
9034479Sbinkertn@umich.edu       Exit(1)
9044479Sbinkertn@umich.edu
9054479Sbinkertn@umich.edu# Check for zlib.  If the check passes, libz will be automatically
9064479Sbinkertn@umich.edu# added to the LIBS environment variable.
9074479Sbinkertn@umich.eduif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
9084479Sbinkertn@umich.edu    print 'Error: did not find needed zlib compression library '\
9094479Sbinkertn@umich.edu          'and/or zlib.h header file.'
9104479Sbinkertn@umich.edu    print '       Please install zlib and try again.'
9114479Sbinkertn@umich.edu    Exit(1)
9122632Sstever@eecs.umich.edu
9132632Sstever@eecs.umich.edu# If we have the protobuf compiler, also make sure we have the
9142632Sstever@eecs.umich.edu# development libraries. If the check passes, libprotobuf will be
9152632Sstever@eecs.umich.edu# automatically added to the LIBS environment variable. After
9162632Sstever@eecs.umich.edu# this, we can use the HAVE_PROTOBUF flag to determine if we have
9172632Sstever@eecs.umich.edu# got both protoc and libprotobuf available.
9182632Sstever@eecs.umich.edumain['HAVE_PROTOBUF'] = main['PROTOC'] and \
9192632Sstever@eecs.umich.edu    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
9202632Sstever@eecs.umich.edu                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
9212632Sstever@eecs.umich.edu
9222632Sstever@eecs.umich.edu# If we have the compiler but not the library, print another warning.
9232632Sstever@eecs.umich.eduif main['PROTOC'] and not main['HAVE_PROTOBUF']:
9242632Sstever@eecs.umich.edu    print termcap.Yellow + termcap.Bold + \
9252632Sstever@eecs.umich.edu        'Warning: did not find protocol buffer library and/or headers.\n' + \
9262632Sstever@eecs.umich.edu    '       Please install libprotobuf-dev for tracing support.' + \
9272632Sstever@eecs.umich.edu    termcap.Normal
9282632Sstever@eecs.umich.edu
9292632Sstever@eecs.umich.edu# Check for librt.
9302632Sstever@eecs.umich.eduhave_posix_clock = \
9312632Sstever@eecs.umich.edu    conf.CheckLibWithHeader(None, 'time.h', 'C',
9322632Sstever@eecs.umich.edu                            'clock_nanosleep(0,0,NULL,NULL);') or \
9332632Sstever@eecs.umich.edu    conf.CheckLibWithHeader('rt', 'time.h', 'C',
9342632Sstever@eecs.umich.edu                            'clock_nanosleep(0,0,NULL,NULL);')
9352632Sstever@eecs.umich.edu
9362632Sstever@eecs.umich.eduhave_posix_timers = \
9372632Sstever@eecs.umich.edu    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
9382632Sstever@eecs.umich.edu                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
9392632Sstever@eecs.umich.edu
9402632Sstever@eecs.umich.eduif conf.CheckLib('tcmalloc'):
9412632Sstever@eecs.umich.edu    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
9422632Sstever@eecs.umich.eduelif conf.CheckLib('tcmalloc_minimal'):
9432632Sstever@eecs.umich.edu    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
9442632Sstever@eecs.umich.eduelse:
9452632Sstever@eecs.umich.edu    print termcap.Yellow + termcap.Bold + \
9462632Sstever@eecs.umich.edu          "You can get a 12% performance improvement by installing tcmalloc "\
9472632Sstever@eecs.umich.edu          "(libgoogle-perftools-dev package on Ubuntu or RedHat)." + \
9482632Sstever@eecs.umich.edu          termcap.Normal
9492632Sstever@eecs.umich.edu
9502632Sstever@eecs.umich.eduif not have_posix_clock:
9512632Sstever@eecs.umich.edu    print "Can't find library for POSIX clocks."
9522632Sstever@eecs.umich.edu
9532632Sstever@eecs.umich.edu# Check for <fenv.h> (C99 FP environment control)
9542632Sstever@eecs.umich.eduhave_fenv = conf.CheckHeader('fenv.h', '<>')
9552632Sstever@eecs.umich.eduif not have_fenv:
9562632Sstever@eecs.umich.edu    print "Warning: Header file <fenv.h> not found."
9572632Sstever@eecs.umich.edu    print "         This host has no IEEE FP rounding mode control."
9582632Sstever@eecs.umich.edu
9592632Sstever@eecs.umich.edu# Check if we should enable KVM-based hardware virtualization. The API
9602632Sstever@eecs.umich.edu# we rely on exists since version 2.6.36 of the kernel, but somehow
9612632Sstever@eecs.umich.edu# the KVM_API_VERSION does not reflect the change. We test for one of
9622632Sstever@eecs.umich.edu# the types as a fall back.
9632632Sstever@eecs.umich.eduhave_kvm = conf.CheckHeader('linux/kvm.h', '<>') and \
9642632Sstever@eecs.umich.edu    conf.CheckTypeSize('struct kvm_xsave', '#include <linux/kvm.h>') != 0
9652632Sstever@eecs.umich.eduif not have_kvm:
9662632Sstever@eecs.umich.edu    print "Info: Compatible header file <linux/kvm.h> not found, " \
9672632Sstever@eecs.umich.edu        "disabling KVM support."
9682632Sstever@eecs.umich.edu
9692632Sstever@eecs.umich.edu# Check if the requested target ISA is compatible with the host
9702632Sstever@eecs.umich.edudef is_isa_kvm_compatible(isa):
9712632Sstever@eecs.umich.edu    isa_comp_table = {
9722632Sstever@eecs.umich.edu        "arm" : ( "armv7l" ),
9732632Sstever@eecs.umich.edu        "x86" : ( "x86_64" ),
9742632Sstever@eecs.umich.edu        }
9752632Sstever@eecs.umich.edu    try:
9762632Sstever@eecs.umich.edu        import platform
9772632Sstever@eecs.umich.edu        host_isa = platform.machine()
9782632Sstever@eecs.umich.edu    except:
9792632Sstever@eecs.umich.edu        print "Warning: Failed to determine host ISA."
9802632Sstever@eecs.umich.edu        return False
9812632Sstever@eecs.umich.edu
9822632Sstever@eecs.umich.edu    return host_isa in isa_comp_table.get(isa, [])
9832632Sstever@eecs.umich.edu
9842632Sstever@eecs.umich.edu
9852632Sstever@eecs.umich.edu# Check if the exclude_host attribute is available. We want this to
9862632Sstever@eecs.umich.edu# get accurate instruction counts in KVM.
9872632Sstever@eecs.umich.edumain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
9882632Sstever@eecs.umich.edu    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
9892632Sstever@eecs.umich.edu
9902632Sstever@eecs.umich.edu
9912632Sstever@eecs.umich.edu######################################################################
9922632Sstever@eecs.umich.edu#
9932632Sstever@eecs.umich.edu# Finish the configuration
9942632Sstever@eecs.umich.edu#
9952632Sstever@eecs.umich.edumain = conf.Finish()
9962632Sstever@eecs.umich.edu
9972632Sstever@eecs.umich.edu######################################################################
9982632Sstever@eecs.umich.edu#
9992632Sstever@eecs.umich.edu# Collect all non-global variables
10002632Sstever@eecs.umich.edu#
10012632Sstever@eecs.umich.edu
10022632Sstever@eecs.umich.edu# Define the universe of supported ISAs
10032632Sstever@eecs.umich.eduall_isa_list = [ ]
10042632Sstever@eecs.umich.eduExport('all_isa_list')
10052632Sstever@eecs.umich.edu
10062632Sstever@eecs.umich.educlass CpuModel(object):
10072632Sstever@eecs.umich.edu    '''The CpuModel class encapsulates everything the ISA parser needs to
10082632Sstever@eecs.umich.edu    know about a particular CPU model.'''
10092632Sstever@eecs.umich.edu
10102632Sstever@eecs.umich.edu    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
10112632Sstever@eecs.umich.edu    dict = {}
10122632Sstever@eecs.umich.edu    list = []
10132632Sstever@eecs.umich.edu    defaults = []
10142632Sstever@eecs.umich.edu
10152632Sstever@eecs.umich.edu    # Constructor.  Automatically adds models to CpuModel.dict.
10162632Sstever@eecs.umich.edu    def __init__(self, name, filename, includes, strings, default=False):
10172632Sstever@eecs.umich.edu        self.name = name           # name of model
10182632Sstever@eecs.umich.edu        self.filename = filename   # filename for output exec code
10192632Sstever@eecs.umich.edu        self.includes = includes   # include files needed in exec file
10202632Sstever@eecs.umich.edu        # The 'strings' dict holds all the per-CPU symbols we can
10212632Sstever@eecs.umich.edu        # substitute into templates etc.
10222632Sstever@eecs.umich.edu        self.strings = strings
10232632Sstever@eecs.umich.edu
10242632Sstever@eecs.umich.edu        # This cpu is enabled by default
10252632Sstever@eecs.umich.edu        self.default = default
10262632Sstever@eecs.umich.edu
10272632Sstever@eecs.umich.edu        # Add self to dict
10282632Sstever@eecs.umich.edu        if name in CpuModel.dict:
10292632Sstever@eecs.umich.edu            raise AttributeError, "CpuModel '%s' already registered" % name
10302632Sstever@eecs.umich.edu        CpuModel.dict[name] = self
10312632Sstever@eecs.umich.edu        CpuModel.list.append(name)
10322632Sstever@eecs.umich.edu
10332632Sstever@eecs.umich.eduExport('CpuModel')
10342632Sstever@eecs.umich.edu
10352632Sstever@eecs.umich.edu# Sticky variables get saved in the variables file so they persist from
10362632Sstever@eecs.umich.edu# one invocation to the next (unless overridden, in which case the new
10372632Sstever@eecs.umich.edu# value becomes sticky).
10382632Sstever@eecs.umich.edusticky_vars = Variables(args=ARGUMENTS)
10392632Sstever@eecs.umich.eduExport('sticky_vars')
10402632Sstever@eecs.umich.edu
10412632Sstever@eecs.umich.edu# Sticky variables that should be exported
10422632Sstever@eecs.umich.eduexport_vars = []
10432632Sstever@eecs.umich.eduExport('export_vars')
10442632Sstever@eecs.umich.edu
10452632Sstever@eecs.umich.edu# For Ruby
10462632Sstever@eecs.umich.eduall_protocols = []
10472632Sstever@eecs.umich.eduExport('all_protocols')
10482632Sstever@eecs.umich.eduprotocol_dirs = []
10492632Sstever@eecs.umich.eduExport('protocol_dirs')
10502632Sstever@eecs.umich.eduslicc_includes = []
10512632Sstever@eecs.umich.eduExport('slicc_includes')
10522632Sstever@eecs.umich.edu
10532632Sstever@eecs.umich.edu# Walk the tree and execute all SConsopts scripts that wil add to the
10542632Sstever@eecs.umich.edu# above variables
10552632Sstever@eecs.umich.eduif GetOption('verbose'):
10562632Sstever@eecs.umich.edu    print "Reading SConsopts"
10572632Sstever@eecs.umich.edufor bdir in [ base_dir ] + extras_dir_list:
10582632Sstever@eecs.umich.edu    if not isdir(bdir):
10592632Sstever@eecs.umich.edu        print "Error: directory '%s' does not exist" % bdir
10602632Sstever@eecs.umich.edu        Exit(1)
10612632Sstever@eecs.umich.edu    for root, dirs, files in os.walk(bdir):
10622632Sstever@eecs.umich.edu        if 'SConsopts' in files:
10632632Sstever@eecs.umich.edu            if GetOption('verbose'):
10642632Sstever@eecs.umich.edu                print "Reading", joinpath(root, 'SConsopts')
10652632Sstever@eecs.umich.edu            SConscript(joinpath(root, 'SConsopts'))
10662632Sstever@eecs.umich.edu
10672632Sstever@eecs.umich.eduall_isa_list.sort()
10682632Sstever@eecs.umich.edu
10692632Sstever@eecs.umich.edusticky_vars.AddVariables(
1070    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
1071    ListVariable('CPU_MODELS', 'CPU models',
1072                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
1073                 sorted(CpuModel.list)),
1074    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
1075                 False),
1076    BoolVariable('SS_COMPATIBLE_FP',
1077                 'Make floating-point results compatible with SimpleScalar',
1078                 False),
1079    BoolVariable('USE_SSE2',
1080                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
1081                 False),
1082    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
1083    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
1084    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
1085    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
1086    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1087                  all_protocols),
1088    )
1089
1090# These variables get exported to #defines in config/*.hh (see src/SConscript).
1091export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'CP_ANNOTATE',
1092                'USE_POSIX_CLOCK', 'PROTOCOL', 'HAVE_PROTOBUF',
1093                'HAVE_PERF_ATTR_EXCLUDE_HOST']
1094
1095###################################################
1096#
1097# Define a SCons builder for configuration flag headers.
1098#
1099###################################################
1100
1101# This function generates a config header file that #defines the
1102# variable symbol to the current variable setting (0 or 1).  The source
1103# operands are the name of the variable and a Value node containing the
1104# value of the variable.
1105def build_config_file(target, source, env):
1106    (variable, value) = [s.get_contents() for s in source]
1107    f = file(str(target[0]), 'w')
1108    print >> f, '#define', variable, value
1109    f.close()
1110    return None
1111
1112# Combine the two functions into a scons Action object.
1113config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1114
1115# The emitter munges the source & target node lists to reflect what
1116# we're really doing.
1117def config_emitter(target, source, env):
1118    # extract variable name from Builder arg
1119    variable = str(target[0])
1120    # True target is config header file
1121    target = joinpath('config', variable.lower() + '.hh')
1122    val = env[variable]
1123    if isinstance(val, bool):
1124        # Force value to 0/1
1125        val = int(val)
1126    elif isinstance(val, str):
1127        val = '"' + val + '"'
1128
1129    # Sources are variable name & value (packaged in SCons Value nodes)
1130    return ([target], [Value(variable), Value(val)])
1131
1132config_builder = Builder(emitter = config_emitter, action = config_action)
1133
1134main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1135
1136# libelf build is shared across all configs in the build root.
1137main.SConscript('ext/libelf/SConscript',
1138                variant_dir = joinpath(build_root, 'libelf'))
1139
1140# gzstream build is shared across all configs in the build root.
1141main.SConscript('ext/gzstream/SConscript',
1142                variant_dir = joinpath(build_root, 'gzstream'))
1143
1144# libfdt build is shared across all configs in the build root.
1145main.SConscript('ext/libfdt/SConscript',
1146                variant_dir = joinpath(build_root, 'libfdt'))
1147
1148# fputils build is shared across all configs in the build root.
1149main.SConscript('ext/fputils/SConscript',
1150                variant_dir = joinpath(build_root, 'fputils'))
1151
1152# DRAMSim2 build is shared across all configs in the build root.
1153main.SConscript('ext/dramsim2/SConscript',
1154                variant_dir = joinpath(build_root, 'dramsim2'))
1155
1156###################################################
1157#
1158# This function is used to set up a directory with switching headers
1159#
1160###################################################
1161
1162main['ALL_ISA_LIST'] = all_isa_list
1163def make_switching_dir(dname, switch_headers, env):
1164    # Generate the header.  target[0] is the full path of the output
1165    # header to generate.  'source' is a dummy variable, since we get the
1166    # list of ISAs from env['ALL_ISA_LIST'].
1167    def gen_switch_hdr(target, source, env):
1168        fname = str(target[0])
1169        f = open(fname, 'w')
1170        isa = env['TARGET_ISA'].lower()
1171        print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1172        f.close()
1173
1174    # Build SCons Action object. 'varlist' specifies env vars that this
1175    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1176    # should get re-executed.
1177    switch_hdr_action = MakeAction(gen_switch_hdr,
1178                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1179
1180    # Instantiate actions for each header
1181    for hdr in switch_headers:
1182        env.Command(hdr, [], switch_hdr_action)
1183Export('make_switching_dir')
1184
1185###################################################
1186#
1187# Define build environments for selected configurations.
1188#
1189###################################################
1190
1191for variant_path in variant_paths:
1192    if not GetOption('silent'):
1193        print "Building in", variant_path
1194
1195    # Make a copy of the build-root environment to use for this config.
1196    env = main.Clone()
1197    env['BUILDDIR'] = variant_path
1198
1199    # variant_dir is the tail component of build path, and is used to
1200    # determine the build parameters (e.g., 'ALPHA_SE')
1201    (build_root, variant_dir) = splitpath(variant_path)
1202
1203    # Set env variables according to the build directory config.
1204    sticky_vars.files = []
1205    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1206    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1207    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1208    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1209    if isfile(current_vars_file):
1210        sticky_vars.files.append(current_vars_file)
1211        if not GetOption('silent'):
1212            print "Using saved variables file %s" % current_vars_file
1213    else:
1214        # Build dir-specific variables file doesn't exist.
1215
1216        # Make sure the directory is there so we can create it later
1217        opt_dir = dirname(current_vars_file)
1218        if not isdir(opt_dir):
1219            mkdir(opt_dir)
1220
1221        # Get default build variables from source tree.  Variables are
1222        # normally determined by name of $VARIANT_DIR, but can be
1223        # overridden by '--default=' arg on command line.
1224        default = GetOption('default')
1225        opts_dir = joinpath(main.root.abspath, 'build_opts')
1226        if default:
1227            default_vars_files = [joinpath(build_root, 'variables', default),
1228                                  joinpath(opts_dir, default)]
1229        else:
1230            default_vars_files = [joinpath(opts_dir, variant_dir)]
1231        existing_files = filter(isfile, default_vars_files)
1232        if existing_files:
1233            default_vars_file = existing_files[0]
1234            sticky_vars.files.append(default_vars_file)
1235            print "Variables file %s not found,\n  using defaults in %s" \
1236                  % (current_vars_file, default_vars_file)
1237        else:
1238            print "Error: cannot find variables file %s or " \
1239                  "default file(s) %s" \
1240                  % (current_vars_file, ' or '.join(default_vars_files))
1241            Exit(1)
1242
1243    # Apply current variable settings to env
1244    sticky_vars.Update(env)
1245
1246    help_texts["local_vars"] += \
1247        "Build variables for %s:\n" % variant_dir \
1248                 + sticky_vars.GenerateHelpText(env)
1249
1250    # Process variable settings.
1251
1252    if not have_fenv and env['USE_FENV']:
1253        print "Warning: <fenv.h> not available; " \
1254              "forcing USE_FENV to False in", variant_dir + "."
1255        env['USE_FENV'] = False
1256
1257    if not env['USE_FENV']:
1258        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1259        print "         FP results may deviate slightly from other platforms."
1260
1261    if env['EFENCE']:
1262        env.Append(LIBS=['efence'])
1263
1264    if env['USE_KVM']:
1265        if not have_kvm:
1266            print "Warning: Can not enable KVM, host seems to lack KVM support"
1267            env['USE_KVM'] = False
1268        elif not have_posix_timers:
1269            print "Warning: Can not enable KVM, host seems to lack support " \
1270                "for POSIX timers"
1271            env['USE_KVM'] = False
1272        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1273            print "Info: KVM support disabled due to unsupported host and " \
1274                "target ISA combination"
1275            env['USE_KVM'] = False
1276
1277    # Warn about missing optional functionality
1278    if env['USE_KVM']:
1279        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1280            print "Warning: perf_event headers lack support for the " \
1281                "exclude_host attribute. KVM instruction counts will " \
1282                "be inaccurate."
1283
1284    # Save sticky variable settings back to current variables file
1285    sticky_vars.Save(current_vars_file, env)
1286
1287    if env['USE_SSE2']:
1288        env.Append(CCFLAGS=['-msse2'])
1289
1290    # The src/SConscript file sets up the build rules in 'env' according
1291    # to the configured variables.  It returns a list of environments,
1292    # one for each variant build (debug, opt, etc.)
1293    envList = SConscript('src/SConscript', variant_dir = variant_path,
1294                         exports = 'env')
1295
1296    # Set up the regression tests for each build.
1297    for e in envList:
1298        SConscript('tests/SConscript',
1299                   variant_dir = joinpath(variant_path, 'tests', e.Label),
1300                   exports = { 'env' : e }, duplicate = False)
1301
1302# base help text
1303Help('''
1304Usage: scons [scons options] [build variables] [target(s)]
1305
1306Extra scons options:
1307%(options)s
1308
1309Global build variables:
1310%(global_vars)s
1311
1312%(local_vars)s
1313''' % help_texts)
1314