SConstruct revision 9900
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2013 ARM Limited
4955SN/A# All rights reserved.
5955SN/A#
6955SN/A# The license below extends only to copyright in the software and shall
7955SN/A# not be construed as granting a license to any other intellectual
8955SN/A# property including but not limited to intellectual property relating
9955SN/A# to a hardware implementation of the functionality of the software
10955SN/A# licensed hereunder.  You may use the software subject to the license
11955SN/A# terms below provided that you ensure that this notice is replicated
12955SN/A# unmodified and in its entirety in all distributions of the software,
13955SN/A# modified or unmodified, in source code or in binary form.
14955SN/A#
15955SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
16955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
17955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
18955SN/A# All rights reserved.
19955SN/A#
20955SN/A# Redistribution and use in source and binary forms, with or without
21955SN/A# modification, are permitted provided that the following conditions are
22955SN/A# met: redistributions of source code must retain the above copyright
23955SN/A# notice, this list of conditions and the following disclaimer;
24955SN/A# redistributions in binary form must reproduce the above copyright
25955SN/A# notice, this list of conditions and the following disclaimer in the
26955SN/A# documentation and/or other materials provided with the distribution;
27955SN/A# neither the name of the copyright holders nor the names of its
282665Ssaidi@eecs.umich.edu# contributors may be used to endorse or promote products derived from
292665Ssaidi@eecs.umich.edu# this software without specific prior written permission.
30955SN/A#
31955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
352632Sstever@eecs.umich.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
362632Sstever@eecs.umich.edu# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
372632Sstever@eecs.umich.edu# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
382632Sstever@eecs.umich.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
402632Sstever@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
412632Sstever@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
422761Sstever@eecs.umich.edu#
432632Sstever@eecs.umich.edu# Authors: Steve Reinhardt
442632Sstever@eecs.umich.edu#          Nathan Binkert
452632Sstever@eecs.umich.edu
462761Sstever@eecs.umich.edu###################################################
472761Sstever@eecs.umich.edu#
482761Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
492632Sstever@eecs.umich.edu#
502632Sstever@eecs.umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
512761Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
522761Sstever@eecs.umich.edu# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
532761Sstever@eecs.umich.edu# the optimized full-system version).
542761Sstever@eecs.umich.edu#
552761Sstever@eecs.umich.edu# You can build gem5 in a different directory as long as there is a
562632Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
572632Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
582632Sstever@eecs.umich.edu# built for the same host system.
592632Sstever@eecs.umich.edu#
602632Sstever@eecs.umich.edu# Examples:
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
63955SN/A#   scons to search up the directory tree for this SConstruct file.
64955SN/A#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
65955SN/A#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
66955SN/A#
67955SN/A#   The following two commands are equivalent and demonstrate building
684202Sbinkertn@umich.edu#   in a directory outside of the source tree.  The '-C' option tells
694678Snate@binkert.org#   scons to chdir to the specified directory to find this SConstruct
70955SN/A#   file.
712656Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
722656Sstever@eecs.umich.edu#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
732656Sstever@eecs.umich.edu#
742656Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
752656Sstever@eecs.umich.edu# 'gem5' directory (or use -u or -C to tell scons where to find this
762656Sstever@eecs.umich.edu# file), you can use 'scons -h' to print all the gem5-specific build
772656Sstever@eecs.umich.edu# options as well.
782653Sstever@eecs.umich.edu#
795227Ssaidi@eecs.umich.edu###################################################
805227Ssaidi@eecs.umich.edu
815227Ssaidi@eecs.umich.edu# Check for recent-enough Python and SCons versions.
825227Ssaidi@eecs.umich.edutry:
832653Sstever@eecs.umich.edu    # Really old versions of scons only take two options for the
842653Sstever@eecs.umich.edu    # function, so check once without the revision and once with the
852653Sstever@eecs.umich.edu    # revision, the first instance will fail for stuff other than
862653Sstever@eecs.umich.edu    # 0.98, and the second will fail for 0.98.0
872653Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98)
882653Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98, 1)
892653Sstever@eecs.umich.eduexcept SystemExit, e:
902653Sstever@eecs.umich.edu    print """
912653Sstever@eecs.umich.eduFor more details, see:
924781Snate@binkert.org    http://gem5.org/Dependencies
931852SN/A"""
94955SN/A    raise
95955SN/A
96955SN/A# We ensure the python version early because because python-config
973717Sstever@eecs.umich.edu# requires python 2.5
983716Sstever@eecs.umich.edutry:
99955SN/A    EnsurePythonVersion(2, 5)
1001533SN/Aexcept SystemExit, e:
1013716Sstever@eecs.umich.edu    print """
1021533SN/AYou can use a non-default installation of the Python interpreter by
1034678Snate@binkert.orgrearranging your PATH so that scons finds the non-default 'python' and
1044678Snate@binkert.org'python-config' first.
1054678Snate@binkert.org
1064678Snate@binkert.orgFor more details, see:
1074678Snate@binkert.org    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1084678Snate@binkert.org"""
1094678Snate@binkert.org    raise
1104678Snate@binkert.org
1114678Snate@binkert.org# Global Python includes
1124678Snate@binkert.orgimport os
1134678Snate@binkert.orgimport re
1144678Snate@binkert.orgimport subprocess
1154678Snate@binkert.orgimport sys
1164678Snate@binkert.org
1174678Snate@binkert.orgfrom os import mkdir, environ
1184678Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1194678Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1204678Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1214678Snate@binkert.org
1224678Snate@binkert.org# SCons includes
1234678Snate@binkert.orgimport SCons
1244973Ssaidi@eecs.umich.eduimport SCons.Node
1254678Snate@binkert.org
1264678Snate@binkert.orgextra_python_paths = [
1274678Snate@binkert.org    Dir('src/python').srcnode().abspath, # gem5 includes
1284678Snate@binkert.org    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1294678Snate@binkert.org    ]
1304678Snate@binkert.org
131955SN/Asys.path[1:1] = extra_python_paths
132955SN/A
1332632Sstever@eecs.umich.edufrom m5.util import compareVersions, readCommand
1342632Sstever@eecs.umich.edufrom m5.util.terminal import get_termcap
135955SN/A
136955SN/Ahelp_texts = {
137955SN/A    "options" : "",
138955SN/A    "global_vars" : "",
1392632Sstever@eecs.umich.edu    "local_vars" : ""
140955SN/A}
1412632Sstever@eecs.umich.edu
1422632Sstever@eecs.umich.eduExport("help_texts")
1432632Sstever@eecs.umich.edu
1442632Sstever@eecs.umich.edu
1452632Sstever@eecs.umich.edu# There's a bug in scons in that (1) by default, the help texts from
1462632Sstever@eecs.umich.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1472632Sstever@eecs.umich.edu# and (2) you can override the help displayed by 'scons -h' using the
1483053Sstever@eecs.umich.edu# Help() function, but these two features are incompatible: once
1493053Sstever@eecs.umich.edu# you've overridden the help text using Help(), there's no way to get
1503053Sstever@eecs.umich.edu# at the help texts from AddOptions.  See:
1513053Sstever@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1523053Sstever@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1533053Sstever@eecs.umich.edu# This hack lets us extract the help text from AddOptions and
1543053Sstever@eecs.umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1553053Sstever@eecs.umich.edu# we can just use AddOption directly.
1563053Sstever@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1573053Sstever@eecs.umich.edu    col_width = 30
1583053Sstever@eecs.umich.edu
1593053Sstever@eecs.umich.edu    help = "  " + ", ".join(args)
1603053Sstever@eecs.umich.edu    if "help" in kwargs:
1613053Sstever@eecs.umich.edu        length = len(help)
1623053Sstever@eecs.umich.edu        if length >= col_width:
1633053Sstever@eecs.umich.edu            help += "\n" + " " * col_width
1642632Sstever@eecs.umich.edu        else:
1652632Sstever@eecs.umich.edu            help += " " * (col_width - length)
1662632Sstever@eecs.umich.edu        help += kwargs["help"]
1672632Sstever@eecs.umich.edu    help_texts["options"] += help + "\n"
1682632Sstever@eecs.umich.edu
1692632Sstever@eecs.umich.edu    AddOption(*args, **kwargs)
1703718Sstever@eecs.umich.edu
1713718Sstever@eecs.umich.eduAddLocalOption('--colors', dest='use_colors', action='store_true',
1723718Sstever@eecs.umich.edu               help="Add color to abbreviated scons output")
1733718Sstever@eecs.umich.eduAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1743718Sstever@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1753718Sstever@eecs.umich.eduAddLocalOption('--default', dest='default', type='string', action='store',
1763718Sstever@eecs.umich.edu               help='Override which build_opts file to use for defaults')
1773718Sstever@eecs.umich.eduAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1783718Sstever@eecs.umich.edu               help='Disable style checking hooks')
1793718Sstever@eecs.umich.eduAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1803718Sstever@eecs.umich.edu               help='Disable Link-Time Optimization for fast')
1813718Sstever@eecs.umich.eduAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1823718Sstever@eecs.umich.edu               help='Update test reference outputs')
1832634Sstever@eecs.umich.eduAddLocalOption('--verbose', dest='verbose', action='store_true',
1842634Sstever@eecs.umich.edu               help='Print full tool command lines')
1852632Sstever@eecs.umich.edu
1862638Sstever@eecs.umich.edutermcap = get_termcap(GetOption('use_colors'))
1872632Sstever@eecs.umich.edu
1882632Sstever@eecs.umich.edu########################################################################
1892632Sstever@eecs.umich.edu#
1902632Sstever@eecs.umich.edu# Set up the main build environment.
1912632Sstever@eecs.umich.edu#
1922632Sstever@eecs.umich.edu########################################################################
1931858SN/Ause_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
1943716Sstever@eecs.umich.edu                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PYTHONPATH',
1952638Sstever@eecs.umich.edu                 'RANLIB', 'SWIG' ])
1962638Sstever@eecs.umich.edu
1972638Sstever@eecs.umich.eduuse_prefixes = [
1982638Sstever@eecs.umich.edu    "M5",           # M5 configuration (e.g., path to kernels)
1992638Sstever@eecs.umich.edu    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
2002638Sstever@eecs.umich.edu    "CCACHE_",      # ccache (caching compiler wrapper) configuration
2012638Sstever@eecs.umich.edu    "CCC_",         # clang static analyzer configuration
2023716Sstever@eecs.umich.edu    ]
2032634Sstever@eecs.umich.edu
2042634Sstever@eecs.umich.eduuse_env = {}
205955SN/Afor key,val in os.environ.iteritems():
206955SN/A    if key in use_vars or \
207955SN/A            any([key.startswith(prefix) for prefix in use_prefixes]):
208955SN/A        use_env[key] = val
209955SN/A
210955SN/Amain = Environment(ENV=use_env)
211955SN/Amain.Decider('MD5-timestamp')
212955SN/Amain.root = Dir(".")         # The current directory (where this file lives).
2131858SN/Amain.srcdir = Dir("src")     # The source directory
2141858SN/A
2152632Sstever@eecs.umich.edumain_dict_keys = main.Dictionary().keys()
216955SN/A
2174781Snate@binkert.org# Check that we have a C/C++ compiler
2183643Ssaidi@eecs.umich.eduif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2193643Ssaidi@eecs.umich.edu    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2203643Ssaidi@eecs.umich.edu    Exit(1)
2213643Ssaidi@eecs.umich.edu
2223643Ssaidi@eecs.umich.edu# Check that swig is present
2233643Ssaidi@eecs.umich.eduif not 'SWIG' in main_dict_keys:
2243643Ssaidi@eecs.umich.edu    print "swig is not installed (package swig on Ubuntu and RedHat)"
2254494Ssaidi@eecs.umich.edu    Exit(1)
2264494Ssaidi@eecs.umich.edu
2273716Sstever@eecs.umich.edu# add useful python code PYTHONPATH so it can be used by subprocesses
2281105SN/A# as well
2292667Sstever@eecs.umich.edumain.AppendENVPath('PYTHONPATH', extra_python_paths)
2302667Sstever@eecs.umich.edu
2312667Sstever@eecs.umich.edu########################################################################
2322667Sstever@eecs.umich.edu#
2332667Sstever@eecs.umich.edu# Mercurial Stuff.
2342667Sstever@eecs.umich.edu#
2351869SN/A# If the gem5 directory is a mercurial repository, we should do some
2361869SN/A# extra things.
2371869SN/A#
2381869SN/A########################################################################
2391869SN/A
2401065SN/Ahgdir = main.root.Dir(".hg")
2412632Sstever@eecs.umich.edu
2425199Sstever@gmail.commercurial_style_message = """
2433918Ssaidi@eecs.umich.eduYou're missing the gem5 style hook, which automatically checks your code
2443918Ssaidi@eecs.umich.eduagainst the gem5 style rules on hg commit and qrefresh commands.  This
2453940Ssaidi@eecs.umich.eduscript will now install the hook in your .hg/hgrc file.
2464781Snate@binkert.orgPress enter to continue, or ctrl-c to abort: """
2474781Snate@binkert.org
2483918Ssaidi@eecs.umich.edumercurial_style_hook = """
2494781Snate@binkert.org# The following lines were automatically added by gem5/SConstruct
2504781Snate@binkert.org# to provide the gem5 style-checking hooks
2513918Ssaidi@eecs.umich.edu[extensions]
2524781Snate@binkert.orgstyle = %s/util/style.py
2534781Snate@binkert.org
2543940Ssaidi@eecs.umich.edu[hooks]
2553942Ssaidi@eecs.umich.edupretxncommit.style = python:style.check_style
2563940Ssaidi@eecs.umich.edupre-qrefresh.style = python:style.check_style
2573918Ssaidi@eecs.umich.edu# End of SConstruct additions
2583918Ssaidi@eecs.umich.edu
259955SN/A""" % (main.root.abspath)
2601858SN/A
2613918Ssaidi@eecs.umich.edumercurial_lib_not_found = """
2623918Ssaidi@eecs.umich.eduMercurial libraries cannot be found, ignoring style hook.  If
2633918Ssaidi@eecs.umich.eduyou are a gem5 developer, please fix this and run the style
2643918Ssaidi@eecs.umich.eduhook. It is important.
2653940Ssaidi@eecs.umich.edu"""
2663940Ssaidi@eecs.umich.edu
2673918Ssaidi@eecs.umich.edu# Check for style hook and prompt for installation if it's not there.
2683918Ssaidi@eecs.umich.edu# Skip this if --ignore-style was specified, there's no .hg dir to
2693918Ssaidi@eecs.umich.edu# install a hook in, or there's no interactive terminal to prompt.
2703918Ssaidi@eecs.umich.eduif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2713918Ssaidi@eecs.umich.edu    style_hook = True
2723918Ssaidi@eecs.umich.edu    try:
2733918Ssaidi@eecs.umich.edu        from mercurial import ui
2743918Ssaidi@eecs.umich.edu        ui = ui.ui()
2753918Ssaidi@eecs.umich.edu        ui.readconfig(hgdir.File('hgrc').abspath)
2763940Ssaidi@eecs.umich.edu        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2773918Ssaidi@eecs.umich.edu                     ui.config('hooks', 'pre-qrefresh.style', None)
2783918Ssaidi@eecs.umich.edu    except ImportError:
2791851SN/A        print mercurial_lib_not_found
2801851SN/A
2811858SN/A    if not style_hook:
2825200Sstever@gmail.com        print mercurial_style_message,
283955SN/A        # continue unless user does ctrl-c/ctrl-d etc.
2843053Sstever@eecs.umich.edu        try:
2853053Sstever@eecs.umich.edu            raw_input()
2863053Sstever@eecs.umich.edu        except:
2873053Sstever@eecs.umich.edu            print "Input exception, exiting scons.\n"
2883053Sstever@eecs.umich.edu            sys.exit(1)
2893053Sstever@eecs.umich.edu        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
2903053Sstever@eecs.umich.edu        print "Adding style hook to", hgrc_path, "\n"
2913053Sstever@eecs.umich.edu        try:
2923053Sstever@eecs.umich.edu            hgrc = open(hgrc_path, 'a')
2934742Sstever@eecs.umich.edu            hgrc.write(mercurial_style_hook)
2944742Sstever@eecs.umich.edu            hgrc.close()
2953053Sstever@eecs.umich.edu        except:
2963053Sstever@eecs.umich.edu            print "Error updating", hgrc_path
2973053Sstever@eecs.umich.edu            sys.exit(1)
2983053Sstever@eecs.umich.edu
2993053Sstever@eecs.umich.edu
3003053Sstever@eecs.umich.edu###################################################
3013053Sstever@eecs.umich.edu#
3023053Sstever@eecs.umich.edu# Figure out which configurations to set up based on the path(s) of
3033053Sstever@eecs.umich.edu# the target(s).
3042667Sstever@eecs.umich.edu#
3054554Sbinkertn@umich.edu###################################################
3064554Sbinkertn@umich.edu
3072667Sstever@eecs.umich.edu# Find default configuration & binary.
3084554Sbinkertn@umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
3094554Sbinkertn@umich.edu
3104554Sbinkertn@umich.edu# helper function: find last occurrence of element in list
3114554Sbinkertn@umich.edudef rfind(l, elt, offs = -1):
3124554Sbinkertn@umich.edu    for i in range(len(l)+offs, 0, -1):
3134554Sbinkertn@umich.edu        if l[i] == elt:
3144554Sbinkertn@umich.edu            return i
3154781Snate@binkert.org    raise ValueError, "element not found"
3164554Sbinkertn@umich.edu
3174554Sbinkertn@umich.edu# Take a list of paths (or SCons Nodes) and return a list with all
3182667Sstever@eecs.umich.edu# paths made absolute and ~-expanded.  Paths will be interpreted
3194554Sbinkertn@umich.edu# relative to the launch directory unless a different root is provided
3204554Sbinkertn@umich.edudef makePathListAbsolute(path_list, root=GetLaunchDir()):
3214554Sbinkertn@umich.edu    return [abspath(joinpath(root, expanduser(str(p))))
3224554Sbinkertn@umich.edu            for p in path_list]
3232667Sstever@eecs.umich.edu
3244554Sbinkertn@umich.edu# Each target must have 'build' in the interior of the path; the
3252667Sstever@eecs.umich.edu# directory below this will determine the build parameters.  For
3264554Sbinkertn@umich.edu# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3274554Sbinkertn@umich.edu# recognize that ALPHA_SE specifies the configuration because it
3282667Sstever@eecs.umich.edu# follow 'build' in the build path.
3292638Sstever@eecs.umich.edu
3302638Sstever@eecs.umich.edu# The funky assignment to "[:]" is needed to replace the list contents
3312638Sstever@eecs.umich.edu# in place rather than reassign the symbol to a new list, which
3323716Sstever@eecs.umich.edu# doesn't work (obviously!).
3333716Sstever@eecs.umich.eduBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3341858SN/A
3355227Ssaidi@eecs.umich.edu# Generate a list of the unique build roots and configs that the
3365227Ssaidi@eecs.umich.edu# collected targets reference.
3375227Ssaidi@eecs.umich.eduvariant_paths = []
3385227Ssaidi@eecs.umich.edubuild_root = None
3395227Ssaidi@eecs.umich.edufor t in BUILD_TARGETS:
3405227Ssaidi@eecs.umich.edu    path_dirs = t.split('/')
3415227Ssaidi@eecs.umich.edu    try:
3425227Ssaidi@eecs.umich.edu        build_top = rfind(path_dirs, 'build', -2)
3435227Ssaidi@eecs.umich.edu    except:
3445227Ssaidi@eecs.umich.edu        print "Error: no non-leaf 'build' dir found on target path", t
3455227Ssaidi@eecs.umich.edu        Exit(1)
3465227Ssaidi@eecs.umich.edu    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3475227Ssaidi@eecs.umich.edu    if not build_root:
3485227Ssaidi@eecs.umich.edu        build_root = this_build_root
3495227Ssaidi@eecs.umich.edu    else:
3505204Sstever@gmail.com        if this_build_root != build_root:
3515204Sstever@gmail.com            print "Error: build targets not under same build root\n"\
3525204Sstever@gmail.com                  "  %s\n  %s" % (build_root, this_build_root)
3535204Sstever@gmail.com            Exit(1)
3545204Sstever@gmail.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
3555204Sstever@gmail.com    if variant_path not in variant_paths:
3565204Sstever@gmail.com        variant_paths.append(variant_path)
3575204Sstever@gmail.com
3585204Sstever@gmail.com# Make sure build_root exists (might not if this is the first build there)
3595204Sstever@gmail.comif not isdir(build_root):
3605204Sstever@gmail.com    mkdir(build_root)
3615204Sstever@gmail.commain['BUILDROOT'] = build_root
3625204Sstever@gmail.com
3635204Sstever@gmail.comExport('main')
3645204Sstever@gmail.com
3655204Sstever@gmail.commain.SConsignFile(joinpath(build_root, "sconsign"))
3665204Sstever@gmail.com
3675204Sstever@gmail.com# Default duplicate option is to use hard links, but this messes up
3685204Sstever@gmail.com# when you use emacs to edit a file in the target dir, as emacs moves
3693118Sstever@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
3703118Sstever@eecs.umich.edu# (soft) links work better.
3713118Sstever@eecs.umich.edumain.SetOption('duplicate', 'soft-copy')
3723118Sstever@eecs.umich.edu
3733118Sstever@eecs.umich.edu#
3743118Sstever@eecs.umich.edu# Set up global sticky variables... these are common to an entire build
3753118Sstever@eecs.umich.edu# tree (not specific to a particular build like ALPHA_SE)
3763118Sstever@eecs.umich.edu#
3773118Sstever@eecs.umich.edu
3783118Sstever@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
3793118Sstever@eecs.umich.edu
3803716Sstever@eecs.umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3813118Sstever@eecs.umich.edu
3823118Sstever@eecs.umich.eduglobal_vars.AddVariables(
3833118Sstever@eecs.umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3843118Sstever@eecs.umich.edu    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3853118Sstever@eecs.umich.edu    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
3863118Sstever@eecs.umich.edu    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
3873118Sstever@eecs.umich.edu    ('BATCH', 'Use batch pool for build and tests', False),
3883118Sstever@eecs.umich.edu    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3893118Sstever@eecs.umich.edu    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
3903716Sstever@eecs.umich.edu    ('EXTRAS', 'Add extra directories to the compilation', '')
3913118Sstever@eecs.umich.edu    )
3923118Sstever@eecs.umich.edu
3933118Sstever@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
3943118Sstever@eecs.umich.eduglobal_vars.Update(main)
3953118Sstever@eecs.umich.eduhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3963118Sstever@eecs.umich.edu
3973118Sstever@eecs.umich.edu# Save sticky variable settings back to current variables file
3983118Sstever@eecs.umich.eduglobal_vars.Save(global_vars_file, main)
3993118Sstever@eecs.umich.edu
4003118Sstever@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
4013483Ssaidi@eecs.umich.edu# look for sources etc.  This list is exported as extras_dir_list.
4023494Ssaidi@eecs.umich.edubase_dir = main.srcdir.abspath
4033494Ssaidi@eecs.umich.eduif main['EXTRAS']:
4043483Ssaidi@eecs.umich.edu    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
4053483Ssaidi@eecs.umich.eduelse:
4063483Ssaidi@eecs.umich.edu    extras_dir_list = []
4073053Sstever@eecs.umich.edu
4083053Sstever@eecs.umich.eduExport('base_dir')
4093918Ssaidi@eecs.umich.eduExport('extras_dir_list')
4103053Sstever@eecs.umich.edu
4113053Sstever@eecs.umich.edu# the ext directory should be on the #includes path
4123053Sstever@eecs.umich.edumain.Append(CPPPATH=[Dir('ext')])
4133053Sstever@eecs.umich.edu
4143053Sstever@eecs.umich.edudef strip_build_path(path, env):
4151858SN/A    path = str(path)
4161858SN/A    variant_base = env['BUILDROOT'] + os.path.sep
4171858SN/A    if path.startswith(variant_base):
4181858SN/A        path = path[len(variant_base):]
4191858SN/A    elif path.startswith('build/'):
4201858SN/A        path = path[6:]
4211859SN/A    return path
4221858SN/A
4231858SN/A# Generate a string of the form:
4241858SN/A#   common/path/prefix/src1, src2 -> tgt1, tgt2
4251859SN/A# to print while building.
4261859SN/Aclass Transform(object):
4271862SN/A    # all specific color settings should be here and nowhere else
4283053Sstever@eecs.umich.edu    tool_color = termcap.Normal
4293053Sstever@eecs.umich.edu    pfx_color = termcap.Yellow
4303053Sstever@eecs.umich.edu    srcs_color = termcap.Yellow + termcap.Bold
4313053Sstever@eecs.umich.edu    arrow_color = termcap.Blue + termcap.Bold
4321859SN/A    tgts_color = termcap.Yellow + termcap.Bold
4331859SN/A
4341859SN/A    def __init__(self, tool, max_sources=99):
4351859SN/A        self.format = self.tool_color + (" [%8s] " % tool) \
4361859SN/A                      + self.pfx_color + "%s" \
4371859SN/A                      + self.srcs_color + "%s" \
4381859SN/A                      + self.arrow_color + " -> " \
4391859SN/A                      + self.tgts_color + "%s" \
4401862SN/A                      + termcap.Normal
4411859SN/A        self.max_sources = max_sources
4421859SN/A
4431859SN/A    def __call__(self, target, source, env, for_signature=None):
4441858SN/A        # truncate source list according to max_sources param
4451858SN/A        source = source[0:self.max_sources]
4462139SN/A        def strip(f):
4474202Sbinkertn@umich.edu            return strip_build_path(str(f), env)
4484202Sbinkertn@umich.edu        if len(source) > 0:
4492139SN/A            srcs = map(strip, source)
4502155SN/A        else:
4514202Sbinkertn@umich.edu            srcs = ['']
4524202Sbinkertn@umich.edu        tgts = map(strip, target)
4534202Sbinkertn@umich.edu        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4542155SN/A        # operation that has nothing to do with paths.
4551869SN/A        com_pfx = os.path.commonprefix(srcs + tgts)
4561869SN/A        com_pfx_len = len(com_pfx)
4571869SN/A        if com_pfx:
4581869SN/A            # do some cleanup and sanity checking on common prefix
4594202Sbinkertn@umich.edu            if com_pfx[-1] == ".":
4604202Sbinkertn@umich.edu                # prefix matches all but file extension: ok
4614202Sbinkertn@umich.edu                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4624202Sbinkertn@umich.edu                com_pfx = com_pfx[0:-1]
4634202Sbinkertn@umich.edu            elif com_pfx[-1] == "/":
4644202Sbinkertn@umich.edu                # common prefix is directory path: OK
4654202Sbinkertn@umich.edu                pass
4664202Sbinkertn@umich.edu            else:
4674202Sbinkertn@umich.edu                src0_len = len(srcs[0])
4684202Sbinkertn@umich.edu                tgt0_len = len(tgts[0])
4694202Sbinkertn@umich.edu                if src0_len == com_pfx_len:
4704202Sbinkertn@umich.edu                    # source is a substring of target, OK
4714202Sbinkertn@umich.edu                    pass
4724202Sbinkertn@umich.edu                elif tgt0_len == com_pfx_len:
4734202Sbinkertn@umich.edu                    # target is a substring of source, need to back up to
4744202Sbinkertn@umich.edu                    # avoid empty string on RHS of arrow
4754773Snate@binkert.org                    sep_idx = com_pfx.rfind(".")
4764775Snate@binkert.org                    if sep_idx != -1:
4774775Snate@binkert.org                        com_pfx = com_pfx[0:sep_idx]
4784773Snate@binkert.org                    else:
4794773Snate@binkert.org                        com_pfx = ''
4804773Snate@binkert.org                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4814773Snate@binkert.org                    # still splitting at file extension: ok
4824773Snate@binkert.org                    pass
4834773Snate@binkert.org                else:
4841869SN/A                    # probably a fluke; ignore it
4854202Sbinkertn@umich.edu                    com_pfx = ''
4861869SN/A        # recalculate length in case com_pfx was modified
4872508SN/A        com_pfx_len = len(com_pfx)
4882508SN/A        def fmt(files):
4892508SN/A            f = map(lambda s: s[com_pfx_len:], files)
4902508SN/A            return ', '.join(f)
4914202Sbinkertn@umich.edu        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
4921869SN/A
4931869SN/AExport('Transform')
4941869SN/A
4951869SN/A# enable the regression script to use the termcap
4961869SN/Amain['TERMCAP'] = termcap
4971869SN/A
4981965SN/Aif GetOption('verbose'):
4991965SN/A    def MakeAction(action, string, *args, **kwargs):
5001965SN/A        return Action(action, *args, **kwargs)
5011869SN/Aelse:
5021869SN/A    MakeAction = Action
5032733Sktlim@umich.edu    main['CCCOMSTR']        = Transform("CC")
5041869SN/A    main['CXXCOMSTR']       = Transform("CXX")
5051884SN/A    main['ASCOMSTR']        = Transform("AS")
5061884SN/A    main['SWIGCOMSTR']      = Transform("SWIG")
5073356Sbinkertn@umich.edu    main['ARCOMSTR']        = Transform("AR", 0)
5083356Sbinkertn@umich.edu    main['LINKCOMSTR']      = Transform("LINK", 0)
5093356Sbinkertn@umich.edu    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
5104773Snate@binkert.org    main['M4COMSTR']        = Transform("M4")
5114773Snate@binkert.org    main['SHCCCOMSTR']      = Transform("SHCC")
5124773Snate@binkert.org    main['SHCXXCOMSTR']     = Transform("SHCXX")
5131869SN/AExport('MakeAction')
5141858SN/A
5151869SN/A# Initialize the Link-Time Optimization (LTO) flags
5161869SN/Amain['LTO_CCFLAGS'] = []
5171869SN/Amain['LTO_LDFLAGS'] = []
5181858SN/A
5192761Sstever@eecs.umich.edu# According to the readme, tcmalloc works best if the compiler doesn't
5201869SN/A# assume that we're using the builtin malloc and friends. These flags
5212733Sktlim@umich.edu# are compiler-specific, so we need to set them after we detect which
5223584Ssaidi@eecs.umich.edu# compiler we're using.
5231869SN/Amain['TCMALLOC_CCFLAGS'] = []
5241869SN/A
5251869SN/ACXX_version = readCommand([main['CXX'],'--version'], exception=False)
5261869SN/ACXX_V = readCommand([main['CXX'],'-V'], exception=False)
5271869SN/A
5281869SN/Amain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5291858SN/Amain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
530955SN/Aif main['GCC'] + main['CLANG'] > 1:
531955SN/A    print 'Error: How can we have two at the same time?'
5321869SN/A    Exit(1)
5331869SN/A
5341869SN/A# Set up default C++ compiler flags
5351869SN/Aif main['GCC'] or main['CLANG']:
5361869SN/A    # As gcc and clang share many flags, do the common parts here
5371869SN/A    main.Append(CCFLAGS=['-pipe'])
5381869SN/A    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5391869SN/A    # Enable -Wall and then disable the few warnings that we
5401869SN/A    # consistently violate
5411869SN/A    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5421869SN/A    # We always compile using C++11, but only gcc >= 4.7 and clang 3.1
5431869SN/A    # actually use that name, so we stick with c++0x
5441869SN/A    main.Append(CXXFLAGS=['-std=c++0x'])
5451869SN/A    # Add selected sanity checks from -Wextra
5461869SN/A    main.Append(CXXFLAGS=['-Wmissing-field-initializers',
5471869SN/A                          '-Woverloaded-virtual'])
5481869SN/Aelse:
5491869SN/A    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5501869SN/A    print "Don't know what compiler options to use for your compiler."
5511869SN/A    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5521869SN/A    print termcap.Yellow + '       version:' + termcap.Normal,
5531869SN/A    if not CXX_version:
5541869SN/A        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5551869SN/A               termcap.Normal
5561869SN/A    else:
5571869SN/A        print CXX_version.replace('\n', '<nl>')
5581869SN/A    print "       If you're trying to use a compiler other than GCC"
5591869SN/A    print "       or clang, there appears to be something wrong with your"
5601869SN/A    print "       environment."
5613716Sstever@eecs.umich.edu    print "       "
5623356Sbinkertn@umich.edu    print "       If you are trying to use a compiler other than those listed"
5633356Sbinkertn@umich.edu    print "       above you will need to ease fix SConstruct and "
5643356Sbinkertn@umich.edu    print "       src/SConscript to support that compiler."
5653356Sbinkertn@umich.edu    Exit(1)
5663356Sbinkertn@umich.edu
5673356Sbinkertn@umich.eduif main['GCC']:
5684781Snate@binkert.org    # Check for a supported version of gcc, >= 4.4 is needed for c++0x
5691869SN/A    # support. See http://gcc.gnu.org/projects/cxx0x.html for details
5701869SN/A    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5711869SN/A    if compareVersions(gcc_version, "4.4") < 0:
5721869SN/A        print 'Error: gcc version 4.4 or newer required.'
5731869SN/A        print '       Installed version:', gcc_version
5741869SN/A        Exit(1)
5751869SN/A
5762655Sstever@eecs.umich.edu    main['GCC_VERSION'] = gcc_version
5772655Sstever@eecs.umich.edu
5782655Sstever@eecs.umich.edu    # Check for versions with bugs
5792655Sstever@eecs.umich.edu    if not compareVersions(gcc_version, '4.4.1') or \
5802655Sstever@eecs.umich.edu       not compareVersions(gcc_version, '4.4.2'):
5812655Sstever@eecs.umich.edu        print 'Info: Tree vectorizer in GCC 4.4.1 & 4.4.2 is buggy, disabling.'
5822655Sstever@eecs.umich.edu        main.Append(CCFLAGS=['-fno-tree-vectorize'])
5832655Sstever@eecs.umich.edu
5842655Sstever@eecs.umich.edu    # LTO support is only really working properly from 4.6 and beyond
5852655Sstever@eecs.umich.edu    if compareVersions(gcc_version, '4.6') >= 0:
5862655Sstever@eecs.umich.edu        # Add the appropriate Link-Time Optimization (LTO) flags
5872655Sstever@eecs.umich.edu        # unless LTO is explicitly turned off. Note that these flags
5882655Sstever@eecs.umich.edu        # are only used by the fast target.
5892655Sstever@eecs.umich.edu        if not GetOption('no_lto'):
5902655Sstever@eecs.umich.edu            # Pass the LTO flag when compiling to produce GIMPLE
5912655Sstever@eecs.umich.edu            # output, we merely create the flags here and only append
5922655Sstever@eecs.umich.edu            # them later/
5932655Sstever@eecs.umich.edu            main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
5942655Sstever@eecs.umich.edu
5952655Sstever@eecs.umich.edu            # Use the same amount of jobs for LTO as we are running
5962655Sstever@eecs.umich.edu            # scons with, we hardcode the use of the linker plugin
5972655Sstever@eecs.umich.edu            # which requires either gold or GNU ld >= 2.21
5982655Sstever@eecs.umich.edu            main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs'),
5992655Sstever@eecs.umich.edu                                   '-fuse-linker-plugin']
6002655Sstever@eecs.umich.edu
6012655Sstever@eecs.umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
6022634Sstever@eecs.umich.edu                                  '-fno-builtin-realloc', '-fno-builtin-free'])
6032634Sstever@eecs.umich.edu
6042634Sstever@eecs.umich.eduelif main['CLANG']:
6052634Sstever@eecs.umich.edu    # Check for a supported version of clang, >= 2.9 is needed to
6062634Sstever@eecs.umich.edu    # support similar features as gcc 4.4. See
6072634Sstever@eecs.umich.edu    # http://clang.llvm.org/cxx_status.html for details
6082638Sstever@eecs.umich.edu    clang_version_re = re.compile(".* version (\d+\.\d+)")
6092638Sstever@eecs.umich.edu    clang_version_match = clang_version_re.match(CXX_version)
6103716Sstever@eecs.umich.edu    if (clang_version_match):
6112638Sstever@eecs.umich.edu        clang_version = clang_version_match.groups()[0]
6122638Sstever@eecs.umich.edu        if compareVersions(clang_version, "2.9") < 0:
6131869SN/A            print 'Error: clang version 2.9 or newer required.'
6141869SN/A            print '       Installed version:', clang_version
6153546Sgblack@eecs.umich.edu            Exit(1)
6163546Sgblack@eecs.umich.edu    else:
6173546Sgblack@eecs.umich.edu        print 'Error: Unable to determine clang version.'
6183546Sgblack@eecs.umich.edu        Exit(1)
6194202Sbinkertn@umich.edu
6203546Sgblack@eecs.umich.edu    # clang has a few additional warnings that we disable,
6213546Sgblack@eecs.umich.edu    # tautological comparisons are allowed due to unsigned integers
6223546Sgblack@eecs.umich.edu    # being compared to constants that happen to be 0, and extraneous
6233546Sgblack@eecs.umich.edu    # parantheses are allowed due to Ruby's printing of the AST,
6243546Sgblack@eecs.umich.edu    # finally self assignments are allowed as the generated CPU code
6254781Snate@binkert.org    # is relying on this
6264781Snate@binkert.org    main.Append(CCFLAGS=['-Wno-tautological-compare',
6274781Snate@binkert.org                         '-Wno-parentheses',
6284781Snate@binkert.org                         '-Wno-self-assign'])
6294781Snate@binkert.org
6304781Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
6314781Snate@binkert.org
6324781Snate@binkert.org    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
6334781Snate@binkert.org    # opposed to libstdc++, as the later is dated.
6344781Snate@binkert.org    if sys.platform == "darwin":
6354781Snate@binkert.org        main.Append(CXXFLAGS=['-stdlib=libc++'])
6364781Snate@binkert.org        main.Append(LIBS=['c++'])
6373546Sgblack@eecs.umich.edu
6383546Sgblack@eecs.umich.eduelse:
6393546Sgblack@eecs.umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6404781Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
6413546Sgblack@eecs.umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6423546Sgblack@eecs.umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
6433546Sgblack@eecs.umich.edu    if not CXX_version:
6443546Sgblack@eecs.umich.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6453546Sgblack@eecs.umich.edu               termcap.Normal
6463546Sgblack@eecs.umich.edu    else:
6473546Sgblack@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
6483546Sgblack@eecs.umich.edu    print "       If you're trying to use a compiler other than GCC"
6493546Sgblack@eecs.umich.edu    print "       or clang, there appears to be something wrong with your"
6503546Sgblack@eecs.umich.edu    print "       environment."
6514202Sbinkertn@umich.edu    print "       "
6523546Sgblack@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
6533546Sgblack@eecs.umich.edu    print "       above you will need to ease fix SConstruct and "
6543546Sgblack@eecs.umich.edu    print "       src/SConscript to support that compiler."
655955SN/A    Exit(1)
656955SN/A
657955SN/A# Set up common yacc/bison flags (needed for Ruby)
658955SN/Amain['YACCFLAGS'] = '-d'
6591858SN/Amain['YACCHXXFILESUFFIX'] = '.hh'
6601858SN/A
6611858SN/A# Do this after we save setting back, or else we'll tack on an
6622632Sstever@eecs.umich.edu# extra 'qdo' every time we run scons.
6632632Sstever@eecs.umich.eduif main['BATCH']:
6644773Snate@binkert.org    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
6654773Snate@binkert.org    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
6662632Sstever@eecs.umich.edu    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
6672632Sstever@eecs.umich.edu    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
6682632Sstever@eecs.umich.edu    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
6692634Sstever@eecs.umich.edu
6702638Sstever@eecs.umich.eduif sys.platform == 'cygwin':
6712023SN/A    # cygwin has some header file issues...
6722632Sstever@eecs.umich.edu    main.Append(CCFLAGS=["-Wno-uninitialized"])
6732632Sstever@eecs.umich.edu
6742632Sstever@eecs.umich.edu# Check for the protobuf compiler
6752632Sstever@eecs.umich.eduprotoc_version = readCommand([main['PROTOC'], '--version'],
6762632Sstever@eecs.umich.edu                             exception='').split()
6773716Sstever@eecs.umich.edu
6782632Sstever@eecs.umich.edu# First two words should be "libprotoc x.y.z"
6792632Sstever@eecs.umich.eduif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6802632Sstever@eecs.umich.edu    print termcap.Yellow + termcap.Bold + \
6812632Sstever@eecs.umich.edu        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
6822632Sstever@eecs.umich.edu        '         Please install protobuf-compiler for tracing support.' + \
6832023SN/A        termcap.Normal
6842632Sstever@eecs.umich.edu    main['PROTOC'] = False
6852632Sstever@eecs.umich.eduelse:
6861889SN/A    # Based on the availability of the compress stream wrappers,
6871889SN/A    # require 2.1.0
6882632Sstever@eecs.umich.edu    min_protoc_version = '2.1.0'
6892632Sstever@eecs.umich.edu    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6902632Sstever@eecs.umich.edu        print termcap.Yellow + termcap.Bold + \
6912632Sstever@eecs.umich.edu            'Warning: protoc version', min_protoc_version, \
6923716Sstever@eecs.umich.edu            'or newer required.\n' + \
6933716Sstever@eecs.umich.edu            '         Installed version:', protoc_version[1], \
6942632Sstever@eecs.umich.edu            termcap.Normal
6952632Sstever@eecs.umich.edu        main['PROTOC'] = False
6962632Sstever@eecs.umich.edu    else:
6972632Sstever@eecs.umich.edu        # Attempt to determine the appropriate include path and
6982632Sstever@eecs.umich.edu        # library path using pkg-config, that means we also need to
6992632Sstever@eecs.umich.edu        # check for pkg-config. Note that it is possible to use
7002632Sstever@eecs.umich.edu        # protobuf without the involvement of pkg-config. Later on we
7012632Sstever@eecs.umich.edu        # check go a library config check and at that point the test
7021888SN/A        # will fail if libprotobuf cannot be found.
7031888SN/A        if readCommand(['pkg-config', '--version'], exception=''):
7041869SN/A            try:
7051869SN/A                # Attempt to establish what linking flags to add for protobuf
7061858SN/A                # using pkg-config
7072598SN/A                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
7082598SN/A            except:
7092598SN/A                print termcap.Yellow + termcap.Bold + \
7102598SN/A                    'Warning: pkg-config could not get protobuf flags.' + \
7112598SN/A                    termcap.Normal
7121858SN/A
7131858SN/A# Check for SWIG
7141858SN/Aif not main.has_key('SWIG'):
7151858SN/A    print 'Error: SWIG utility not found.'
7161858SN/A    print '       Please install (see http://www.swig.org) and retry.'
7171858SN/A    Exit(1)
7181858SN/A
7191858SN/A# Check for appropriate SWIG version
7201858SN/Aswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
7211871SN/A# First 3 words should be "SWIG Version x.y.z"
7221858SN/Aif len(swig_version) < 3 or \
7231858SN/A        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
7241858SN/A    print 'Error determining SWIG version.'
7251858SN/A    Exit(1)
7261858SN/A
7271858SN/Amin_swig_version = '1.3.34'
7281858SN/Aif compareVersions(swig_version[2], min_swig_version) < 0:
7291858SN/A    print 'Error: SWIG version', min_swig_version, 'or newer required.'
7301858SN/A    print '       Installed version:', swig_version[2]
7311858SN/A    Exit(1)
7321858SN/A
7331859SN/A# Older versions of swig do not play well with more recent versions of
7341859SN/A# gcc due to assumptions on implicit includes (cstddef) and use of
7351869SN/A# namespaces
7361888SN/Aif main['GCC'] and compareVersions(gcc_version, '4.6') > 0 and \
7372632Sstever@eecs.umich.edu        compareVersions(swig_version[2], '2') < 0:
7381869SN/A    print '\n' + termcap.Yellow + termcap.Bold + \
7391884SN/A        'Warning: SWIG 1.x cause issues with gcc 4.6 and later.\n' + \
7401884SN/A        termcap.Normal + \
7411884SN/A        'Use SWIG 2.x to avoid assumptions on implicit includes\n' + \
7421884SN/A        'and use of namespaces\n'
7431884SN/A
7441884SN/A# Set up SWIG flags & scanner
7451965SN/Aswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
7461965SN/Amain.Append(SWIGFLAGS=swig_flags)
7471965SN/A
7482761Sstever@eecs.umich.edu# filter out all existing swig scanners, they mess up the dependency
7491869SN/A# stuff for some reason
7501869SN/Ascanners = []
7512632Sstever@eecs.umich.edufor scanner in main['SCANNERS']:
7522667Sstever@eecs.umich.edu    skeys = scanner.skeys
7531869SN/A    if skeys == '.i':
7541869SN/A        continue
7552929Sktlim@umich.edu
7562929Sktlim@umich.edu    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
7573716Sstever@eecs.umich.edu        continue
7582929Sktlim@umich.edu
759955SN/A    scanners.append(scanner)
7602598SN/A
7612598SN/A# add the new swig scanner that we like better
7623546Sgblack@eecs.umich.edufrom SCons.Scanner import ClassicCPP as CPPScanner
763955SN/Aswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
764955SN/Ascanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
765955SN/A
7661530SN/A# replace the scanners list that has what we want
767955SN/Amain['SCANNERS'] = scanners
768955SN/A
769955SN/A# Add a custom Check function to the Configure context so that we can
770# figure out if the compiler adds leading underscores to global
771# variables.  This is needed for the autogenerated asm files that we
772# use for embedding the python code.
773def CheckLeading(context):
774    context.Message("Checking for leading underscore in global variables...")
775    # 1) Define a global variable called x from asm so the C compiler
776    #    won't change the symbol at all.
777    # 2) Declare that variable.
778    # 3) Use the variable
779    #
780    # If the compiler prepends an underscore, this will successfully
781    # link because the external symbol 'x' will be called '_x' which
782    # was defined by the asm statement.  If the compiler does not
783    # prepend an underscore, this will not successfully link because
784    # '_x' will have been defined by assembly, while the C portion of
785    # the code will be trying to use 'x'
786    ret = context.TryLink('''
787        asm(".globl _x; _x: .byte 0");
788        extern int x;
789        int main() { return x; }
790        ''', extension=".c")
791    context.env.Append(LEADING_UNDERSCORE=ret)
792    context.Result(ret)
793    return ret
794
795# Platform-specific configuration.  Note again that we assume that all
796# builds under a given build root run on the same host platform.
797conf = Configure(main,
798                 conf_dir = joinpath(build_root, '.scons_config'),
799                 log_file = joinpath(build_root, 'scons_config.log'),
800                 custom_tests = { 'CheckLeading' : CheckLeading })
801
802# Check for leading underscores.  Don't really need to worry either
803# way so don't need to check the return code.
804conf.CheckLeading()
805
806# Check if we should compile a 64 bit binary on Mac OS X/Darwin
807try:
808    import platform
809    uname = platform.uname()
810    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
811        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
812            main.Append(CCFLAGS=['-arch', 'x86_64'])
813            main.Append(CFLAGS=['-arch', 'x86_64'])
814            main.Append(LINKFLAGS=['-arch', 'x86_64'])
815            main.Append(ASFLAGS=['-arch', 'x86_64'])
816except:
817    pass
818
819# Recent versions of scons substitute a "Null" object for Configure()
820# when configuration isn't necessary, e.g., if the "--help" option is
821# present.  Unfortuantely this Null object always returns false,
822# breaking all our configuration checks.  We replace it with our own
823# more optimistic null object that returns True instead.
824if not conf:
825    def NullCheck(*args, **kwargs):
826        return True
827
828    class NullConf:
829        def __init__(self, env):
830            self.env = env
831        def Finish(self):
832            return self.env
833        def __getattr__(self, mname):
834            return NullCheck
835
836    conf = NullConf(main)
837
838# Cache build files in the supplied directory.
839if main['M5_BUILD_CACHE']:
840    print 'Using build cache located at', main['M5_BUILD_CACHE']
841    CacheDir(main['M5_BUILD_CACHE'])
842
843# Find Python include and library directories for embedding the
844# interpreter. We rely on python-config to resolve the appropriate
845# includes and linker flags. ParseConfig does not seem to understand
846# the more exotic linker flags such as -Xlinker and -export-dynamic so
847# we add them explicitly below. If you want to link in an alternate
848# version of python, see above for instructions on how to invoke
849# scons with the appropriate PATH set.
850py_includes = readCommand(['python-config', '--includes'],
851                          exception='').split()
852# Strip the -I from the include folders before adding them to the
853# CPPPATH
854main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
855
856# Read the linker flags and split them into libraries and other link
857# flags. The libraries are added later through the call the CheckLib.
858py_ld_flags = readCommand(['python-config', '--ldflags'], exception='').split()
859py_libs = []
860for lib in py_ld_flags:
861     if not lib.startswith('-l'):
862         main.Append(LINKFLAGS=[lib])
863     else:
864         lib = lib[2:]
865         if lib not in py_libs:
866             py_libs.append(lib)
867
868# verify that this stuff works
869if not conf.CheckHeader('Python.h', '<>'):
870    print "Error: can't find Python.h header in", py_includes
871    print "Install Python headers (package python-dev on Ubuntu and RedHat)"
872    Exit(1)
873
874for lib in py_libs:
875    if not conf.CheckLib(lib):
876        print "Error: can't find library %s required by python" % lib
877        Exit(1)
878
879# On Solaris you need to use libsocket for socket ops
880if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
881   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
882       print "Can't find library with socket calls (e.g. accept())"
883       Exit(1)
884
885# Check for zlib.  If the check passes, libz will be automatically
886# added to the LIBS environment variable.
887if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
888    print 'Error: did not find needed zlib compression library '\
889          'and/or zlib.h header file.'
890    print '       Please install zlib and try again.'
891    Exit(1)
892
893# If we have the protobuf compiler, also make sure we have the
894# development libraries. If the check passes, libprotobuf will be
895# automatically added to the LIBS environment variable. After
896# this, we can use the HAVE_PROTOBUF flag to determine if we have
897# got both protoc and libprotobuf available.
898main['HAVE_PROTOBUF'] = main['PROTOC'] and \
899    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
900                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
901
902# If we have the compiler but not the library, print another warning.
903if main['PROTOC'] and not main['HAVE_PROTOBUF']:
904    print termcap.Yellow + termcap.Bold + \
905        'Warning: did not find protocol buffer library and/or headers.\n' + \
906    '       Please install libprotobuf-dev for tracing support.' + \
907    termcap.Normal
908
909# Check for librt.
910have_posix_clock = \
911    conf.CheckLibWithHeader(None, 'time.h', 'C',
912                            'clock_nanosleep(0,0,NULL,NULL);') or \
913    conf.CheckLibWithHeader('rt', 'time.h', 'C',
914                            'clock_nanosleep(0,0,NULL,NULL);')
915
916have_posix_timers = \
917    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
918                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
919
920if conf.CheckLib('tcmalloc'):
921    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
922elif conf.CheckLib('tcmalloc_minimal'):
923    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
924else:
925    print termcap.Yellow + termcap.Bold + \
926          "You can get a 12% performance improvement by installing tcmalloc "\
927          "(libgoogle-perftools-dev package on Ubuntu or RedHat)." + \
928          termcap.Normal
929
930if not have_posix_clock:
931    print "Can't find library for POSIX clocks."
932
933# Check for <fenv.h> (C99 FP environment control)
934have_fenv = conf.CheckHeader('fenv.h', '<>')
935if not have_fenv:
936    print "Warning: Header file <fenv.h> not found."
937    print "         This host has no IEEE FP rounding mode control."
938
939# Check if we should enable KVM-based hardware virtualization
940have_kvm = conf.CheckHeader('linux/kvm.h', '<>')
941if not have_kvm:
942    print "Info: Header file <linux/kvm.h> not found, " \
943        "disabling KVM support."
944
945# Check if the requested target ISA is compatible with the host
946def is_isa_kvm_compatible(isa):
947    isa_comp_table = {
948        "arm" : ( "armv7l" ),
949        "x86" : ( "x86_64" ),
950        }
951    try:
952        import platform
953        host_isa = platform.machine()
954    except:
955        print "Warning: Failed to determine host ISA."
956        return False
957
958    return host_isa in isa_comp_table.get(isa, [])
959
960
961######################################################################
962#
963# Finish the configuration
964#
965main = conf.Finish()
966
967######################################################################
968#
969# Collect all non-global variables
970#
971
972# Define the universe of supported ISAs
973all_isa_list = [ ]
974Export('all_isa_list')
975
976class CpuModel(object):
977    '''The CpuModel class encapsulates everything the ISA parser needs to
978    know about a particular CPU model.'''
979
980    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
981    dict = {}
982    list = []
983    defaults = []
984
985    # Constructor.  Automatically adds models to CpuModel.dict.
986    def __init__(self, name, filename, includes, strings, default=False):
987        self.name = name           # name of model
988        self.filename = filename   # filename for output exec code
989        self.includes = includes   # include files needed in exec file
990        # The 'strings' dict holds all the per-CPU symbols we can
991        # substitute into templates etc.
992        self.strings = strings
993
994        # This cpu is enabled by default
995        self.default = default
996
997        # Add self to dict
998        if name in CpuModel.dict:
999            raise AttributeError, "CpuModel '%s' already registered" % name
1000        CpuModel.dict[name] = self
1001        CpuModel.list.append(name)
1002
1003Export('CpuModel')
1004
1005# Sticky variables get saved in the variables file so they persist from
1006# one invocation to the next (unless overridden, in which case the new
1007# value becomes sticky).
1008sticky_vars = Variables(args=ARGUMENTS)
1009Export('sticky_vars')
1010
1011# Sticky variables that should be exported
1012export_vars = []
1013Export('export_vars')
1014
1015# For Ruby
1016all_protocols = []
1017Export('all_protocols')
1018protocol_dirs = []
1019Export('protocol_dirs')
1020slicc_includes = []
1021Export('slicc_includes')
1022
1023# Walk the tree and execute all SConsopts scripts that wil add to the
1024# above variables
1025if not GetOption('verbose'):
1026    print "Reading SConsopts"
1027for bdir in [ base_dir ] + extras_dir_list:
1028    if not isdir(bdir):
1029        print "Error: directory '%s' does not exist" % bdir
1030        Exit(1)
1031    for root, dirs, files in os.walk(bdir):
1032        if 'SConsopts' in files:
1033            if GetOption('verbose'):
1034                print "Reading", joinpath(root, 'SConsopts')
1035            SConscript(joinpath(root, 'SConsopts'))
1036
1037all_isa_list.sort()
1038
1039sticky_vars.AddVariables(
1040    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
1041    ListVariable('CPU_MODELS', 'CPU models',
1042                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
1043                 sorted(CpuModel.list)),
1044    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
1045                 False),
1046    BoolVariable('SS_COMPATIBLE_FP',
1047                 'Make floating-point results compatible with SimpleScalar',
1048                 False),
1049    BoolVariable('USE_SSE2',
1050                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
1051                 False),
1052    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
1053    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
1054    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
1055    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
1056    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1057                  all_protocols),
1058    )
1059
1060# These variables get exported to #defines in config/*.hh (see src/SConscript).
1061export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'CP_ANNOTATE',
1062                'USE_POSIX_CLOCK', 'PROTOCOL', 'HAVE_PROTOBUF']
1063
1064###################################################
1065#
1066# Define a SCons builder for configuration flag headers.
1067#
1068###################################################
1069
1070# This function generates a config header file that #defines the
1071# variable symbol to the current variable setting (0 or 1).  The source
1072# operands are the name of the variable and a Value node containing the
1073# value of the variable.
1074def build_config_file(target, source, env):
1075    (variable, value) = [s.get_contents() for s in source]
1076    f = file(str(target[0]), 'w')
1077    print >> f, '#define', variable, value
1078    f.close()
1079    return None
1080
1081# Combine the two functions into a scons Action object.
1082config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1083
1084# The emitter munges the source & target node lists to reflect what
1085# we're really doing.
1086def config_emitter(target, source, env):
1087    # extract variable name from Builder arg
1088    variable = str(target[0])
1089    # True target is config header file
1090    target = joinpath('config', variable.lower() + '.hh')
1091    val = env[variable]
1092    if isinstance(val, bool):
1093        # Force value to 0/1
1094        val = int(val)
1095    elif isinstance(val, str):
1096        val = '"' + val + '"'
1097
1098    # Sources are variable name & value (packaged in SCons Value nodes)
1099    return ([target], [Value(variable), Value(val)])
1100
1101config_builder = Builder(emitter = config_emitter, action = config_action)
1102
1103main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1104
1105# libelf build is shared across all configs in the build root.
1106main.SConscript('ext/libelf/SConscript',
1107                variant_dir = joinpath(build_root, 'libelf'))
1108
1109# gzstream build is shared across all configs in the build root.
1110main.SConscript('ext/gzstream/SConscript',
1111                variant_dir = joinpath(build_root, 'gzstream'))
1112
1113# libfdt build is shared across all configs in the build root.
1114main.SConscript('ext/libfdt/SConscript',
1115                variant_dir = joinpath(build_root, 'libfdt'))
1116
1117# fputils build is shared across all configs in the build root.
1118main.SConscript('ext/fputils/SConscript',
1119                variant_dir = joinpath(build_root, 'fputils'))
1120
1121###################################################
1122#
1123# This function is used to set up a directory with switching headers
1124#
1125###################################################
1126
1127main['ALL_ISA_LIST'] = all_isa_list
1128def make_switching_dir(dname, switch_headers, env):
1129    # Generate the header.  target[0] is the full path of the output
1130    # header to generate.  'source' is a dummy variable, since we get the
1131    # list of ISAs from env['ALL_ISA_LIST'].
1132    def gen_switch_hdr(target, source, env):
1133        fname = str(target[0])
1134        f = open(fname, 'w')
1135        isa = env['TARGET_ISA'].lower()
1136        print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1137        f.close()
1138
1139    # Build SCons Action object. 'varlist' specifies env vars that this
1140    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1141    # should get re-executed.
1142    switch_hdr_action = MakeAction(gen_switch_hdr,
1143                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1144
1145    # Instantiate actions for each header
1146    for hdr in switch_headers:
1147        env.Command(hdr, [], switch_hdr_action)
1148Export('make_switching_dir')
1149
1150###################################################
1151#
1152# Define build environments for selected configurations.
1153#
1154###################################################
1155
1156for variant_path in variant_paths:
1157    print "Building in", variant_path
1158
1159    # Make a copy of the build-root environment to use for this config.
1160    env = main.Clone()
1161    env['BUILDDIR'] = variant_path
1162
1163    # variant_dir is the tail component of build path, and is used to
1164    # determine the build parameters (e.g., 'ALPHA_SE')
1165    (build_root, variant_dir) = splitpath(variant_path)
1166
1167    # Set env variables according to the build directory config.
1168    sticky_vars.files = []
1169    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1170    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1171    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1172    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1173    if isfile(current_vars_file):
1174        sticky_vars.files.append(current_vars_file)
1175        print "Using saved variables file %s" % current_vars_file
1176    else:
1177        # Build dir-specific variables file doesn't exist.
1178
1179        # Make sure the directory is there so we can create it later
1180        opt_dir = dirname(current_vars_file)
1181        if not isdir(opt_dir):
1182            mkdir(opt_dir)
1183
1184        # Get default build variables from source tree.  Variables are
1185        # normally determined by name of $VARIANT_DIR, but can be
1186        # overridden by '--default=' arg on command line.
1187        default = GetOption('default')
1188        opts_dir = joinpath(main.root.abspath, 'build_opts')
1189        if default:
1190            default_vars_files = [joinpath(build_root, 'variables', default),
1191                                  joinpath(opts_dir, default)]
1192        else:
1193            default_vars_files = [joinpath(opts_dir, variant_dir)]
1194        existing_files = filter(isfile, default_vars_files)
1195        if existing_files:
1196            default_vars_file = existing_files[0]
1197            sticky_vars.files.append(default_vars_file)
1198            print "Variables file %s not found,\n  using defaults in %s" \
1199                  % (current_vars_file, default_vars_file)
1200        else:
1201            print "Error: cannot find variables file %s or " \
1202                  "default file(s) %s" \
1203                  % (current_vars_file, ' or '.join(default_vars_files))
1204            Exit(1)
1205
1206    # Apply current variable settings to env
1207    sticky_vars.Update(env)
1208
1209    help_texts["local_vars"] += \
1210        "Build variables for %s:\n" % variant_dir \
1211                 + sticky_vars.GenerateHelpText(env)
1212
1213    # Process variable settings.
1214
1215    if not have_fenv and env['USE_FENV']:
1216        print "Warning: <fenv.h> not available; " \
1217              "forcing USE_FENV to False in", variant_dir + "."
1218        env['USE_FENV'] = False
1219
1220    if not env['USE_FENV']:
1221        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1222        print "         FP results may deviate slightly from other platforms."
1223
1224    if env['EFENCE']:
1225        env.Append(LIBS=['efence'])
1226
1227    if env['USE_KVM']:
1228        if not have_kvm:
1229            print "Warning: Can not enable KVM, host seems to lack KVM support"
1230            env['USE_KVM'] = False
1231        elif not have_posix_timers:
1232            print "Warning: Can not enable KVM, host seems to lack support " \
1233                "for POSIX timers"
1234            env['USE_KVM'] = False
1235        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1236            print "Info: KVM support disabled due to unsupported host and " \
1237                "target ISA combination"
1238            env['USE_KVM'] = False
1239
1240    # Save sticky variable settings back to current variables file
1241    sticky_vars.Save(current_vars_file, env)
1242
1243    if env['USE_SSE2']:
1244        env.Append(CCFLAGS=['-msse2'])
1245
1246    # The src/SConscript file sets up the build rules in 'env' according
1247    # to the configured variables.  It returns a list of environments,
1248    # one for each variant build (debug, opt, etc.)
1249    envList = SConscript('src/SConscript', variant_dir = variant_path,
1250                         exports = 'env')
1251
1252    # Set up the regression tests for each build.
1253    for e in envList:
1254        SConscript('tests/SConscript',
1255                   variant_dir = joinpath(variant_path, 'tests', e.Label),
1256                   exports = { 'env' : e }, duplicate = False)
1257
1258# base help text
1259Help('''
1260Usage: scons [scons options] [build variables] [target(s)]
1261
1262Extra scons options:
1263%(options)s
1264
1265Global build variables:
1266%(global_vars)s
1267
1268%(local_vars)s
1269''' % help_texts)
1270