SConstruct revision 10878
1955SN/A# -*- mode:python -*-
2955SN/A
35871Snate@binkert.org# Copyright (c) 2013, 2015 ARM Limited
41762SN/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
28955SN/A# contributors may be used to endorse or promote products derived from
292665Ssaidi@eecs.umich.edu# this software without specific prior written permission.
302665Ssaidi@eecs.umich.edu#
315863Snate@binkert.org# 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
35955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36955SN/A# 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
392632Sstever@eecs.umich.edu# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
402632Sstever@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
41955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
422632Sstever@eecs.umich.edu#
432632Sstever@eecs.umich.edu# Authors: Steve Reinhardt
442761Sstever@eecs.umich.edu#          Nathan Binkert
452632Sstever@eecs.umich.edu
462632Sstever@eecs.umich.edu###################################################
472632Sstever@eecs.umich.edu#
482761Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
492761Sstever@eecs.umich.edu#
502761Sstever@eecs.umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
512632Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
522632Sstever@eecs.umich.edu# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
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
562761Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
572761Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
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
632632Sstever@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
642632Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
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
685863Snate@binkert.org#   in a directory outside of the source tree.  The '-C' option tells
695863Snate@binkert.org#   scons to chdir to the specified directory to find this SConstruct
705863Snate@binkert.org#   file.
715863Snate@binkert.org#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
725863Snate@binkert.org#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
735863Snate@binkert.org#
745863Snate@binkert.org# You can use 'scons -H' to print scons options.  If you're in this
755863Snate@binkert.org# 'gem5' directory (or use -u or -C to tell scons where to find this
765863Snate@binkert.org# file), you can use 'scons -h' to print all the gem5-specific build
775863Snate@binkert.org# options as well.
785863Snate@binkert.org#
795863Snate@binkert.org###################################################
805863Snate@binkert.org
815863Snate@binkert.org# Check for recent-enough Python and SCons versions.
825863Snate@binkert.orgtry:
835863Snate@binkert.org    # Really old versions of scons only take two options for the
845863Snate@binkert.org    # function, so check once without the revision and once with the
855863Snate@binkert.org    # revision, the first instance will fail for stuff other than
865863Snate@binkert.org    # 0.98, and the second will fail for 0.98.0
875863Snate@binkert.org    EnsureSConsVersion(0, 98)
885863Snate@binkert.org    EnsureSConsVersion(0, 98, 1)
895863Snate@binkert.orgexcept SystemExit, e:
905863Snate@binkert.org    print """
915863Snate@binkert.orgFor more details, see:
925863Snate@binkert.org    http://gem5.org/Dependencies
935863Snate@binkert.org"""
945863Snate@binkert.org    raise
955863Snate@binkert.org
965863Snate@binkert.org# We ensure the python version early because because python-config
975863Snate@binkert.org# requires python 2.5
985863Snate@binkert.orgtry:
996654Snate@binkert.org    EnsurePythonVersion(2, 5)
100955SN/Aexcept SystemExit, e:
1015396Ssaidi@eecs.umich.edu    print """
1025863Snate@binkert.orgYou can use a non-default installation of the Python interpreter by
1035863Snate@binkert.orgrearranging your PATH so that scons finds the non-default 'python' and
1044202Sbinkertn@umich.edu'python-config' first.
1055863Snate@binkert.org
1065863Snate@binkert.orgFor more details, see:
1075863Snate@binkert.org    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1085863Snate@binkert.org"""
109955SN/A    raise
1106654Snate@binkert.org
1115273Sstever@gmail.com# Global Python includes
1125871Snate@binkert.orgimport itertools
1135273Sstever@gmail.comimport os
1146654Snate@binkert.orgimport re
1156654Snate@binkert.orgimport subprocess
1165871Snate@binkert.orgimport sys
1176654Snate@binkert.org
1185396Ssaidi@eecs.umich.edufrom os import mkdir, environ
1195871Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1205871Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1216121Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1225871Snate@binkert.org
1235871Snate@binkert.org# SCons includes
1246003Snate@binkert.orgimport SCons
1256003Snate@binkert.orgimport SCons.Node
126955SN/A
1275871Snate@binkert.orgextra_python_paths = [
1285871Snate@binkert.org    Dir('src/python').srcnode().abspath, # gem5 includes
1295871Snate@binkert.org    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1305871Snate@binkert.org    ]
131955SN/A
1326121Snate@binkert.orgsys.path[1:1] = extra_python_paths
1336121Snate@binkert.org
1346121Snate@binkert.orgfrom m5.util import compareVersions, readCommand
1351533SN/Afrom m5.util.terminal import get_termcap
1365871Snate@binkert.org
1375871Snate@binkert.orghelp_texts = {
1385863Snate@binkert.org    "options" : "",
1395871Snate@binkert.org    "global_vars" : "",
1405871Snate@binkert.org    "local_vars" : ""
1415871Snate@binkert.org}
1425871Snate@binkert.org
1435871Snate@binkert.orgExport("help_texts")
1445863Snate@binkert.org
1456121Snate@binkert.org
1465863Snate@binkert.org# There's a bug in scons in that (1) by default, the help texts from
1475871Snate@binkert.org# AddOption() are supposed to be displayed when you type 'scons -h'
1484678Snate@binkert.org# and (2) you can override the help displayed by 'scons -h' using the
1494678Snate@binkert.org# Help() function, but these two features are incompatible: once
1504678Snate@binkert.org# you've overridden the help text using Help(), there's no way to get
1514678Snate@binkert.org# at the help texts from AddOptions.  See:
1524678Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1534678Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1544678Snate@binkert.org# This hack lets us extract the help text from AddOptions and
1554678Snate@binkert.org# re-inject it via Help().  Ideally someday this bug will be fixed and
1564678Snate@binkert.org# we can just use AddOption directly.
1574678Snate@binkert.orgdef AddLocalOption(*args, **kwargs):
1584678Snate@binkert.org    col_width = 30
1594678Snate@binkert.org
1606121Snate@binkert.org    help = "  " + ", ".join(args)
1614678Snate@binkert.org    if "help" in kwargs:
1625871Snate@binkert.org        length = len(help)
1635871Snate@binkert.org        if length >= col_width:
1645871Snate@binkert.org            help += "\n" + " " * col_width
1655871Snate@binkert.org        else:
1665871Snate@binkert.org            help += " " * (col_width - length)
1675871Snate@binkert.org        help += kwargs["help"]
1685871Snate@binkert.org    help_texts["options"] += help + "\n"
1695871Snate@binkert.org
1705871Snate@binkert.org    AddOption(*args, **kwargs)
1715871Snate@binkert.org
1725871Snate@binkert.orgAddLocalOption('--colors', dest='use_colors', action='store_true',
1735871Snate@binkert.org               help="Add color to abbreviated scons output")
1745871Snate@binkert.orgAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1755990Ssaidi@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1765871Snate@binkert.orgAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1775871Snate@binkert.org               action='store_true',
1785871Snate@binkert.org               help="Build with support for C++-based configuration")
1794678Snate@binkert.orgAddLocalOption('--default', dest='default', type='string', action='store',
1806654Snate@binkert.org               help='Override which build_opts file to use for defaults')
1815871Snate@binkert.orgAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1825871Snate@binkert.org               help='Disable style checking hooks')
1835871Snate@binkert.orgAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1845871Snate@binkert.org               help='Disable Link-Time Optimization for fast')
1855871Snate@binkert.orgAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1865871Snate@binkert.org               help='Update test reference outputs')
1875871Snate@binkert.orgAddLocalOption('--verbose', dest='verbose', action='store_true',
1885871Snate@binkert.org               help='Print full tool command lines')
1895871Snate@binkert.orgAddLocalOption('--without-python', dest='without_python',
1904678Snate@binkert.org               action='store_true',
1915871Snate@binkert.org               help='Build without Python configuration support')
1924678Snate@binkert.orgAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1935871Snate@binkert.org               action='store_true',
1945871Snate@binkert.org               help='Disable linking against tcmalloc')
1955871Snate@binkert.orgAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1965871Snate@binkert.org               help='Build with Undefined Behavior Sanitizer if available')
1975871Snate@binkert.org
1985871Snate@binkert.orgtermcap = get_termcap(GetOption('use_colors'))
1995871Snate@binkert.org
2005871Snate@binkert.org########################################################################
2015871Snate@binkert.org#
2026121Snate@binkert.org# Set up the main build environment.
2036121Snate@binkert.org#
2045863Snate@binkert.org########################################################################
205955SN/A
206955SN/A# export TERM so that clang reports errors in color
2072632Sstever@eecs.umich.eduuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
2082632Sstever@eecs.umich.edu                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
209955SN/A                 'PYTHONPATH', 'RANLIB', 'SWIG', 'TERM' ])
210955SN/A
211955SN/Ause_prefixes = [
212955SN/A    "M5",           # M5 configuration (e.g., path to kernels)
2135863Snate@binkert.org    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
214955SN/A    "CCACHE_",      # ccache (caching compiler wrapper) configuration
2152632Sstever@eecs.umich.edu    "CCC_",         # clang static analyzer configuration
2162632Sstever@eecs.umich.edu    ]
2172632Sstever@eecs.umich.edu
2182632Sstever@eecs.umich.eduuse_env = {}
2192632Sstever@eecs.umich.edufor key,val in sorted(os.environ.iteritems()):
2202632Sstever@eecs.umich.edu    if key in use_vars or \
2212632Sstever@eecs.umich.edu            any([key.startswith(prefix) for prefix in use_prefixes]):
2222632Sstever@eecs.umich.edu        use_env[key] = val
2232632Sstever@eecs.umich.edu
2242632Sstever@eecs.umich.edu# Tell scons to avoid implicit command dependencies to avoid issues
2252632Sstever@eecs.umich.edu# with the param wrappes being compiled twice (see
2262632Sstever@eecs.umich.edu# http://scons.tigris.org/issues/show_bug.cgi?id=2811)
2272632Sstever@eecs.umich.edumain = Environment(ENV=use_env, IMPLICIT_COMMAND_DEPENDENCIES=0)
2283718Sstever@eecs.umich.edumain.Decider('MD5-timestamp')
2293718Sstever@eecs.umich.edumain.root = Dir(".")         # The current directory (where this file lives).
2303718Sstever@eecs.umich.edumain.srcdir = Dir("src")     # The source directory
2313718Sstever@eecs.umich.edu
2323718Sstever@eecs.umich.edumain_dict_keys = main.Dictionary().keys()
2335863Snate@binkert.org
2345863Snate@binkert.org# Check that we have a C/C++ compiler
2353718Sstever@eecs.umich.eduif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2363718Sstever@eecs.umich.edu    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2376121Snate@binkert.org    Exit(1)
2385863Snate@binkert.org
2393718Sstever@eecs.umich.edu# Check that swig is present
2403718Sstever@eecs.umich.eduif not 'SWIG' in main_dict_keys:
2412634Sstever@eecs.umich.edu    print "swig is not installed (package swig on Ubuntu and RedHat)"
2422634Sstever@eecs.umich.edu    Exit(1)
2435863Snate@binkert.org
2442638Sstever@eecs.umich.edu# add useful python code PYTHONPATH so it can be used by subprocesses
2452632Sstever@eecs.umich.edu# as well
2462632Sstever@eecs.umich.edumain.AppendENVPath('PYTHONPATH', extra_python_paths)
2472632Sstever@eecs.umich.edu
2482632Sstever@eecs.umich.edu########################################################################
2492632Sstever@eecs.umich.edu#
2502632Sstever@eecs.umich.edu# Mercurial Stuff.
2511858SN/A#
2523716Sstever@eecs.umich.edu# If the gem5 directory is a mercurial repository, we should do some
2532638Sstever@eecs.umich.edu# extra things.
2542638Sstever@eecs.umich.edu#
2552638Sstever@eecs.umich.edu########################################################################
2562638Sstever@eecs.umich.edu
2572638Sstever@eecs.umich.eduhgdir = main.root.Dir(".hg")
2582638Sstever@eecs.umich.edu
2592638Sstever@eecs.umich.edumercurial_style_message = """
2605863Snate@binkert.orgYou're missing the gem5 style hook, which automatically checks your code
2615863Snate@binkert.orgagainst the gem5 style rules on hg commit and qrefresh commands.  This
2625863Snate@binkert.orgscript will now install the hook in your .hg/hgrc file.
263955SN/APress enter to continue, or ctrl-c to abort: """
2645341Sstever@gmail.com
2655341Sstever@gmail.commercurial_style_hook = """
2665863Snate@binkert.org# The following lines were automatically added by gem5/SConstruct
2675341Sstever@gmail.com# to provide the gem5 style-checking hooks
2686121Snate@binkert.org[extensions]
2694494Ssaidi@eecs.umich.edustyle = %s/util/style.py
2706121Snate@binkert.org
2711105SN/A[hooks]
2722667Sstever@eecs.umich.edupretxncommit.style = python:style.check_style
2732667Sstever@eecs.umich.edupre-qrefresh.style = python:style.check_style
2742667Sstever@eecs.umich.edu# End of SConstruct additions
2752667Sstever@eecs.umich.edu
2766121Snate@binkert.org""" % (main.root.abspath)
2772667Sstever@eecs.umich.edu
2785341Sstever@gmail.commercurial_lib_not_found = """
2795863Snate@binkert.orgMercurial libraries cannot be found, ignoring style hook.  If
2805341Sstever@gmail.comyou are a gem5 developer, please fix this and run the style
2815341Sstever@gmail.comhook. It is important.
2825341Sstever@gmail.com"""
2835863Snate@binkert.org
2845341Sstever@gmail.com# Check for style hook and prompt for installation if it's not there.
2855341Sstever@gmail.com# Skip this if --ignore-style was specified, there's no .hg dir to
2865341Sstever@gmail.com# install a hook in, or there's no interactive terminal to prompt.
2875863Snate@binkert.orgif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2885341Sstever@gmail.com    style_hook = True
2895341Sstever@gmail.com    try:
2905341Sstever@gmail.com        from mercurial import ui
2915341Sstever@gmail.com        ui = ui.ui()
2925341Sstever@gmail.com        ui.readconfig(hgdir.File('hgrc').abspath)
2935341Sstever@gmail.com        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2945341Sstever@gmail.com                     ui.config('hooks', 'pre-qrefresh.style', None)
2955341Sstever@gmail.com    except ImportError:
2965341Sstever@gmail.com        print mercurial_lib_not_found
2975341Sstever@gmail.com
2985863Snate@binkert.org    if not style_hook:
2995341Sstever@gmail.com        print mercurial_style_message,
3005863Snate@binkert.org        # continue unless user does ctrl-c/ctrl-d etc.
3015341Sstever@gmail.com        try:
3025863Snate@binkert.org            raw_input()
3036121Snate@binkert.org        except:
3046121Snate@binkert.org            print "Input exception, exiting scons.\n"
3055397Ssaidi@eecs.umich.edu            sys.exit(1)
3065397Ssaidi@eecs.umich.edu        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
3075341Sstever@gmail.com        print "Adding style hook to", hgrc_path, "\n"
3086168Snate@binkert.org        try:
3096168Snate@binkert.org            hgrc = open(hgrc_path, 'a')
3106168Snate@binkert.org            hgrc.write(mercurial_style_hook)
3115341Sstever@gmail.com            hgrc.close()
3125341Sstever@gmail.com        except:
3135341Sstever@gmail.com            print "Error updating", hgrc_path
3145341Sstever@gmail.com            sys.exit(1)
3155341Sstever@gmail.com
3165863Snate@binkert.org
3175341Sstever@gmail.com###################################################
3185341Sstever@gmail.com#
3196121Snate@binkert.org# Figure out which configurations to set up based on the path(s) of
3205341Sstever@gmail.com# the target(s).
3216121Snate@binkert.org#
3226121Snate@binkert.org###################################################
3235341Sstever@gmail.com
3245863Snate@binkert.org# Find default configuration & binary.
3256121Snate@binkert.orgDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
3265341Sstever@gmail.com
3275863Snate@binkert.org# helper function: find last occurrence of element in list
3285341Sstever@gmail.comdef rfind(l, elt, offs = -1):
3296121Snate@binkert.org    for i in range(len(l)+offs, 0, -1):
3306121Snate@binkert.org        if l[i] == elt:
3316121Snate@binkert.org            return i
3325742Snate@binkert.org    raise ValueError, "element not found"
3335742Snate@binkert.org
3345341Sstever@gmail.com# Take a list of paths (or SCons Nodes) and return a list with all
3355742Snate@binkert.org# paths made absolute and ~-expanded.  Paths will be interpreted
3365742Snate@binkert.org# relative to the launch directory unless a different root is provided
3375341Sstever@gmail.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
3386017Snate@binkert.org    return [abspath(joinpath(root, expanduser(str(p))))
3396121Snate@binkert.org            for p in path_list]
3406017Snate@binkert.org
3412632Sstever@eecs.umich.edu# Each target must have 'build' in the interior of the path; the
3426121Snate@binkert.org# directory below this will determine the build parameters.  For
3435871Snate@binkert.org# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3446654Snate@binkert.org# recognize that ALPHA_SE specifies the configuration because it
3456654Snate@binkert.org# follow 'build' in the build path.
3465871Snate@binkert.org
3476121Snate@binkert.org# The funky assignment to "[:]" is needed to replace the list contents
3486121Snate@binkert.org# in place rather than reassign the symbol to a new list, which
3496121Snate@binkert.org# doesn't work (obviously!).
3506121Snate@binkert.orgBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3513940Ssaidi@eecs.umich.edu
3523918Ssaidi@eecs.umich.edu# Generate a list of the unique build roots and configs that the
3533918Ssaidi@eecs.umich.edu# collected targets reference.
3541858SN/Avariant_paths = []
3556121Snate@binkert.orgbuild_root = None
3566121Snate@binkert.orgfor t in BUILD_TARGETS:
3576121Snate@binkert.org    path_dirs = t.split('/')
3586143Snate@binkert.org    try:
3596121Snate@binkert.org        build_top = rfind(path_dirs, 'build', -2)
3606121Snate@binkert.org    except:
3613940Ssaidi@eecs.umich.edu        print "Error: no non-leaf 'build' dir found on target path", t
3626121Snate@binkert.org        Exit(1)
3636121Snate@binkert.org    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3646121Snate@binkert.org    if not build_root:
3656121Snate@binkert.org        build_root = this_build_root
3666121Snate@binkert.org    else:
3676121Snate@binkert.org        if this_build_root != build_root:
3686121Snate@binkert.org            print "Error: build targets not under same build root\n"\
3693918Ssaidi@eecs.umich.edu                  "  %s\n  %s" % (build_root, this_build_root)
3703918Ssaidi@eecs.umich.edu            Exit(1)
3713940Ssaidi@eecs.umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
3723918Ssaidi@eecs.umich.edu    if variant_path not in variant_paths:
3733918Ssaidi@eecs.umich.edu        variant_paths.append(variant_path)
3746157Snate@binkert.org
3756157Snate@binkert.org# Make sure build_root exists (might not if this is the first build there)
3766157Snate@binkert.orgif not isdir(build_root):
3776157Snate@binkert.org    mkdir(build_root)
3785397Ssaidi@eecs.umich.edumain['BUILDROOT'] = build_root
3795397Ssaidi@eecs.umich.edu
3806121Snate@binkert.orgExport('main')
3816121Snate@binkert.org
3826121Snate@binkert.orgmain.SConsignFile(joinpath(build_root, "sconsign"))
3836121Snate@binkert.org
3846121Snate@binkert.org# Default duplicate option is to use hard links, but this messes up
3856121Snate@binkert.org# when you use emacs to edit a file in the target dir, as emacs moves
3865397Ssaidi@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
3871851SN/A# (soft) links work better.
3881851SN/Amain.SetOption('duplicate', 'soft-copy')
3896121Snate@binkert.org
390955SN/A#
3913053Sstever@eecs.umich.edu# Set up global sticky variables... these are common to an entire build
3926121Snate@binkert.org# tree (not specific to a particular build like ALPHA_SE)
3933053Sstever@eecs.umich.edu#
3943053Sstever@eecs.umich.edu
3953053Sstever@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
3963053Sstever@eecs.umich.edu
3973053Sstever@eecs.umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3986654Snate@binkert.org
3993053Sstever@eecs.umich.eduglobal_vars.AddVariables(
4004742Sstever@eecs.umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
4014742Sstever@eecs.umich.edu    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
4023053Sstever@eecs.umich.edu    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
4033053Sstever@eecs.umich.edu    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
4043053Sstever@eecs.umich.edu    ('BATCH', 'Use batch pool for build and tests', False),
4053053Sstever@eecs.umich.edu    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
4066654Snate@binkert.org    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
4073053Sstever@eecs.umich.edu    ('EXTRAS', 'Add extra directories to the compilation', '')
4083053Sstever@eecs.umich.edu    )
4093053Sstever@eecs.umich.edu
4103053Sstever@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
4112667Sstever@eecs.umich.eduglobal_vars.Update(main)
4124554Sbinkertn@umich.eduhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
4136121Snate@binkert.org
4142667Sstever@eecs.umich.edu# Save sticky variable settings back to current variables file
4154554Sbinkertn@umich.eduglobal_vars.Save(global_vars_file, main)
4164554Sbinkertn@umich.edu
4174554Sbinkertn@umich.edu# Parse EXTRAS variable to build list of all directories where we're
4186121Snate@binkert.org# look for sources etc.  This list is exported as extras_dir_list.
4194554Sbinkertn@umich.edubase_dir = main.srcdir.abspath
4204554Sbinkertn@umich.eduif main['EXTRAS']:
4214554Sbinkertn@umich.edu    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
4224781Snate@binkert.orgelse:
4234554Sbinkertn@umich.edu    extras_dir_list = []
4244554Sbinkertn@umich.edu
4252667Sstever@eecs.umich.eduExport('base_dir')
4264554Sbinkertn@umich.eduExport('extras_dir_list')
4274554Sbinkertn@umich.edu
4284554Sbinkertn@umich.edu# the ext directory should be on the #includes path
4294554Sbinkertn@umich.edumain.Append(CPPPATH=[Dir('ext')])
4302667Sstever@eecs.umich.edu
4314554Sbinkertn@umich.edudef strip_build_path(path, env):
4322667Sstever@eecs.umich.edu    path = str(path)
4334554Sbinkertn@umich.edu    variant_base = env['BUILDROOT'] + os.path.sep
4346121Snate@binkert.org    if path.startswith(variant_base):
4352667Sstever@eecs.umich.edu        path = path[len(variant_base):]
4365522Snate@binkert.org    elif path.startswith('build/'):
4375522Snate@binkert.org        path = path[6:]
4385522Snate@binkert.org    return path
4395522Snate@binkert.org
4405522Snate@binkert.org# Generate a string of the form:
4415522Snate@binkert.org#   common/path/prefix/src1, src2 -> tgt1, tgt2
4425522Snate@binkert.org# to print while building.
4435522Snate@binkert.orgclass Transform(object):
4445522Snate@binkert.org    # all specific color settings should be here and nowhere else
4455522Snate@binkert.org    tool_color = termcap.Normal
4465522Snate@binkert.org    pfx_color = termcap.Yellow
4475522Snate@binkert.org    srcs_color = termcap.Yellow + termcap.Bold
4485522Snate@binkert.org    arrow_color = termcap.Blue + termcap.Bold
4495522Snate@binkert.org    tgts_color = termcap.Yellow + termcap.Bold
4505522Snate@binkert.org
4515522Snate@binkert.org    def __init__(self, tool, max_sources=99):
4525522Snate@binkert.org        self.format = self.tool_color + (" [%8s] " % tool) \
4535522Snate@binkert.org                      + self.pfx_color + "%s" \
4545522Snate@binkert.org                      + self.srcs_color + "%s" \
4555522Snate@binkert.org                      + self.arrow_color + " -> " \
4565522Snate@binkert.org                      + self.tgts_color + "%s" \
4575522Snate@binkert.org                      + termcap.Normal
4585522Snate@binkert.org        self.max_sources = max_sources
4595522Snate@binkert.org
4605522Snate@binkert.org    def __call__(self, target, source, env, for_signature=None):
4615522Snate@binkert.org        # truncate source list according to max_sources param
4622638Sstever@eecs.umich.edu        source = source[0:self.max_sources]
4632638Sstever@eecs.umich.edu        def strip(f):
4646121Snate@binkert.org            return strip_build_path(str(f), env)
4653716Sstever@eecs.umich.edu        if len(source) > 0:
4665522Snate@binkert.org            srcs = map(strip, source)
4675522Snate@binkert.org        else:
4685522Snate@binkert.org            srcs = ['']
4695522Snate@binkert.org        tgts = map(strip, target)
4705522Snate@binkert.org        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4715522Snate@binkert.org        # operation that has nothing to do with paths.
4721858SN/A        com_pfx = os.path.commonprefix(srcs + tgts)
4735227Ssaidi@eecs.umich.edu        com_pfx_len = len(com_pfx)
4745227Ssaidi@eecs.umich.edu        if com_pfx:
4755227Ssaidi@eecs.umich.edu            # do some cleanup and sanity checking on common prefix
4765227Ssaidi@eecs.umich.edu            if com_pfx[-1] == ".":
4776654Snate@binkert.org                # prefix matches all but file extension: ok
4786654Snate@binkert.org                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4796121Snate@binkert.org                com_pfx = com_pfx[0:-1]
4806121Snate@binkert.org            elif com_pfx[-1] == "/":
4816121Snate@binkert.org                # common prefix is directory path: OK
4826121Snate@binkert.org                pass
4835227Ssaidi@eecs.umich.edu            else:
4845227Ssaidi@eecs.umich.edu                src0_len = len(srcs[0])
4855227Ssaidi@eecs.umich.edu                tgt0_len = len(tgts[0])
4865204Sstever@gmail.com                if src0_len == com_pfx_len:
4875204Sstever@gmail.com                    # source is a substring of target, OK
4885204Sstever@gmail.com                    pass
4895204Sstever@gmail.com                elif tgt0_len == com_pfx_len:
4905204Sstever@gmail.com                    # target is a substring of source, need to back up to
4915204Sstever@gmail.com                    # avoid empty string on RHS of arrow
4925204Sstever@gmail.com                    sep_idx = com_pfx.rfind(".")
4935204Sstever@gmail.com                    if sep_idx != -1:
4945204Sstever@gmail.com                        com_pfx = com_pfx[0:sep_idx]
4955204Sstever@gmail.com                    else:
4965204Sstever@gmail.com                        com_pfx = ''
4975204Sstever@gmail.com                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4985204Sstever@gmail.com                    # still splitting at file extension: ok
4995204Sstever@gmail.com                    pass
5005204Sstever@gmail.com                else:
5015204Sstever@gmail.com                    # probably a fluke; ignore it
5025204Sstever@gmail.com                    com_pfx = ''
5036121Snate@binkert.org        # recalculate length in case com_pfx was modified
5045204Sstever@gmail.com        com_pfx_len = len(com_pfx)
5053118Sstever@eecs.umich.edu        def fmt(files):
5063118Sstever@eecs.umich.edu            f = map(lambda s: s[com_pfx_len:], files)
5073118Sstever@eecs.umich.edu            return ', '.join(f)
5083118Sstever@eecs.umich.edu        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
5093118Sstever@eecs.umich.edu
5105863Snate@binkert.orgExport('Transform')
5113118Sstever@eecs.umich.edu
5125863Snate@binkert.org# enable the regression script to use the termcap
5133118Sstever@eecs.umich.edumain['TERMCAP'] = termcap
5145863Snate@binkert.org
5155863Snate@binkert.orgif GetOption('verbose'):
5165863Snate@binkert.org    def MakeAction(action, string, *args, **kwargs):
5175863Snate@binkert.org        return Action(action, *args, **kwargs)
5185863Snate@binkert.orgelse:
5195863Snate@binkert.org    MakeAction = Action
5205863Snate@binkert.org    main['CCCOMSTR']        = Transform("CC")
5215863Snate@binkert.org    main['CXXCOMSTR']       = Transform("CXX")
5226003Snate@binkert.org    main['ASCOMSTR']        = Transform("AS")
5235863Snate@binkert.org    main['SWIGCOMSTR']      = Transform("SWIG")
5245863Snate@binkert.org    main['ARCOMSTR']        = Transform("AR", 0)
5255863Snate@binkert.org    main['LINKCOMSTR']      = Transform("LINK", 0)
5266120Snate@binkert.org    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
5275863Snate@binkert.org    main['M4COMSTR']        = Transform("M4")
5285863Snate@binkert.org    main['SHCCCOMSTR']      = Transform("SHCC")
5295863Snate@binkert.org    main['SHCXXCOMSTR']     = Transform("SHCXX")
5306120Snate@binkert.orgExport('MakeAction')
5316120Snate@binkert.org
5325863Snate@binkert.org# Initialize the Link-Time Optimization (LTO) flags
5335863Snate@binkert.orgmain['LTO_CCFLAGS'] = []
5346120Snate@binkert.orgmain['LTO_LDFLAGS'] = []
5355863Snate@binkert.org
5366121Snate@binkert.org# According to the readme, tcmalloc works best if the compiler doesn't
5376121Snate@binkert.org# assume that we're using the builtin malloc and friends. These flags
5385863Snate@binkert.org# are compiler-specific, so we need to set them after we detect which
5395863Snate@binkert.org# compiler we're using.
5403118Sstever@eecs.umich.edumain['TCMALLOC_CCFLAGS'] = []
5415863Snate@binkert.org
5423118Sstever@eecs.umich.eduCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5433118Sstever@eecs.umich.eduCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5445863Snate@binkert.org
5455863Snate@binkert.orgmain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5465863Snate@binkert.orgmain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5475863Snate@binkert.orgif main['GCC'] + main['CLANG'] > 1:
5483118Sstever@eecs.umich.edu    print 'Error: How can we have two at the same time?'
5493483Ssaidi@eecs.umich.edu    Exit(1)
5503494Ssaidi@eecs.umich.edu
5513494Ssaidi@eecs.umich.edu# Set up default C++ compiler flags
5523483Ssaidi@eecs.umich.eduif main['GCC'] or main['CLANG']:
5533483Ssaidi@eecs.umich.edu    # As gcc and clang share many flags, do the common parts here
5543483Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-pipe'])
5553053Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5563053Sstever@eecs.umich.edu    # Enable -Wall and then disable the few warnings that we
5573918Ssaidi@eecs.umich.edu    # consistently violate
5583053Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5593053Sstever@eecs.umich.edu    # We always compile using C++11
5603053Sstever@eecs.umich.edu    main.Append(CXXFLAGS=['-std=c++11'])
5613053Sstever@eecs.umich.edu    # Add selected sanity checks from -Wextra
5623053Sstever@eecs.umich.edu    main.Append(CXXFLAGS=['-Wmissing-field-initializers',
5631858SN/A                          '-Woverloaded-virtual'])
5641858SN/Aelse:
5651858SN/A    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5661858SN/A    print "Don't know what compiler options to use for your compiler."
5671858SN/A    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5681858SN/A    print termcap.Yellow + '       version:' + termcap.Normal,
5695863Snate@binkert.org    if not CXX_version:
5705863Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5711859SN/A               termcap.Normal
5725863Snate@binkert.org    else:
5731858SN/A        print CXX_version.replace('\n', '<nl>')
5745863Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
5751858SN/A    print "       or clang, there appears to be something wrong with your"
5761859SN/A    print "       environment."
5771859SN/A    print "       "
5786654Snate@binkert.org    print "       If you are trying to use a compiler other than those listed"
5793053Sstever@eecs.umich.edu    print "       above you will need to ease fix SConstruct and "
5806654Snate@binkert.org    print "       src/SConscript to support that compiler."
5813053Sstever@eecs.umich.edu    Exit(1)
5823053Sstever@eecs.umich.edu
5831859SN/Aif main['GCC']:
5841859SN/A    # Check for a supported version of gcc. >= 4.7 is chosen for its
5851859SN/A    # level of c++11 support. See
5861859SN/A    # http://gcc.gnu.org/projects/cxx0x.html for details.
5871859SN/A    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5881859SN/A    if compareVersions(gcc_version, "4.7") < 0:
5891859SN/A        print 'Error: gcc version 4.7 or newer required.'
5901859SN/A        print '       Installed version:', gcc_version
5911862SN/A        Exit(1)
5921859SN/A
5931859SN/A    main['GCC_VERSION'] = gcc_version
5941859SN/A
5955863Snate@binkert.org    # gcc from version 4.8 and above generates "rep; ret" instructions
5965863Snate@binkert.org    # to avoid performance penalties on certain AMD chips. Older
5975863Snate@binkert.org    # assemblers detect this as an error, "Error: expecting string
5985863Snate@binkert.org    # instruction after `rep'"
5996121Snate@binkert.org    if compareVersions(gcc_version, "4.8") > 0:
6001858SN/A        as_version_raw = readCommand([main['AS'], '-v', '/dev/null'],
6015863Snate@binkert.org                                     exception=False).split()
6025863Snate@binkert.org
6035863Snate@binkert.org        # version strings may contain extra distro-specific
6045863Snate@binkert.org        # qualifiers, so play it safe and keep only what comes before
6055863Snate@binkert.org        # the first hyphen
6062139SN/A        as_version = as_version_raw[-1].split('-')[0] if as_version_raw \
6074202Sbinkertn@umich.edu            else None
6084202Sbinkertn@umich.edu
6092139SN/A        if not as_version or compareVersions(as_version, "2.23") < 0:
6102155SN/A            print termcap.Yellow + termcap.Bold + \
6114202Sbinkertn@umich.edu                'Warning: This combination of gcc and binutils have' + \
6124202Sbinkertn@umich.edu                ' known incompatibilities.\n' + \
6134202Sbinkertn@umich.edu                '         If you encounter build problems, please update ' + \
6142155SN/A                'binutils to 2.23.' + \
6155863Snate@binkert.org                termcap.Normal
6161869SN/A
6171869SN/A    # Make sure we warn if the user has requested to compile with the
6185863Snate@binkert.org    # Undefined Benahvior Sanitizer and this version of gcc does not
6195863Snate@binkert.org    # support it.
6204202Sbinkertn@umich.edu    if GetOption('with_ubsan') and \
6216108Snate@binkert.org            compareVersions(gcc_version, '4.9') < 0:
6226108Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
6236108Snate@binkert.org            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
6246108Snate@binkert.org            termcap.Normal
6255863Snate@binkert.org
6265863Snate@binkert.org    # Add the appropriate Link-Time Optimization (LTO) flags
6275863Snate@binkert.org    # unless LTO is explicitly turned off. Note that these flags
6284202Sbinkertn@umich.edu    # are only used by the fast target.
6294202Sbinkertn@umich.edu    if not GetOption('no_lto'):
6305863Snate@binkert.org        # Pass the LTO flag when compiling to produce GIMPLE
6315742Snate@binkert.org        # output, we merely create the flags here and only append
6325742Snate@binkert.org        # them later
6335341Sstever@gmail.com        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
6345342Sstever@gmail.com
6355342Sstever@gmail.com        # Use the same amount of jobs for LTO as we are running
6364202Sbinkertn@umich.edu        # scons with
6374202Sbinkertn@umich.edu        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
6384202Sbinkertn@umich.edu
6394202Sbinkertn@umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
6404202Sbinkertn@umich.edu                                  '-fno-builtin-realloc', '-fno-builtin-free'])
6415863Snate@binkert.org
6425863Snate@binkert.orgelif main['CLANG']:
6435863Snate@binkert.org    # Check for a supported version of clang, >= 3.1 is needed to
6445863Snate@binkert.org    # support similar features as gcc 4.7. See
6455863Snate@binkert.org    # http://clang.llvm.org/cxx_status.html for details
6465863Snate@binkert.org    clang_version_re = re.compile(".* version (\d+\.\d+)")
6475863Snate@binkert.org    clang_version_match = clang_version_re.search(CXX_version)
6485863Snate@binkert.org    if (clang_version_match):
6495863Snate@binkert.org        clang_version = clang_version_match.groups()[0]
6505863Snate@binkert.org        if compareVersions(clang_version, "3.1") < 0:
6515863Snate@binkert.org            print 'Error: clang version 3.1 or newer required.'
6525863Snate@binkert.org            print '       Installed version:', clang_version
6535863Snate@binkert.org            Exit(1)
6545863Snate@binkert.org    else:
6555863Snate@binkert.org        print 'Error: Unable to determine clang version.'
6565863Snate@binkert.org        Exit(1)
6575863Snate@binkert.org
6585863Snate@binkert.org    # clang has a few additional warnings that we disable,
6595863Snate@binkert.org    # tautological comparisons are allowed due to unsigned integers
6605863Snate@binkert.org    # being compared to constants that happen to be 0, and extraneous
6615952Ssaidi@eecs.umich.edu    # parantheses are allowed due to Ruby's printing of the AST,
6621869SN/A    # finally self assignments are allowed as the generated CPU code
6631858SN/A    # is relying on this
6645863Snate@binkert.org    main.Append(CCFLAGS=['-Wno-tautological-compare',
6655863Snate@binkert.org                         '-Wno-parentheses',
6661869SN/A                         '-Wno-self-assign',
6671858SN/A                         # Some versions of libstdc++ (4.8?) seem to
6685863Snate@binkert.org                         # use struct hash and class hash
6696108Snate@binkert.org                         # interchangeably.
6706108Snate@binkert.org                         '-Wno-mismatched-tags',
6716108Snate@binkert.org                         ])
6721858SN/A
673955SN/A    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
674955SN/A
6751869SN/A    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
6761869SN/A    # opposed to libstdc++, as the later is dated.
6771869SN/A    if sys.platform == "darwin":
6781869SN/A        main.Append(CXXFLAGS=['-stdlib=libc++'])
6791869SN/A        main.Append(LIBS=['c++'])
6805863Snate@binkert.org
6815863Snate@binkert.orgelse:
6825863Snate@binkert.org    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6831869SN/A    print "Don't know what compiler options to use for your compiler."
6845863Snate@binkert.org    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6851869SN/A    print termcap.Yellow + '       version:' + termcap.Normal,
6865863Snate@binkert.org    if not CXX_version:
6871869SN/A        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6881869SN/A               termcap.Normal
6891869SN/A    else:
6901869SN/A        print CXX_version.replace('\n', '<nl>')
6911869SN/A    print "       If you're trying to use a compiler other than GCC"
6925863Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
6935863Snate@binkert.org    print "       environment."
6941869SN/A    print "       "
6951869SN/A    print "       If you are trying to use a compiler other than those listed"
6961869SN/A    print "       above you will need to ease fix SConstruct and "
6971869SN/A    print "       src/SConscript to support that compiler."
6981869SN/A    Exit(1)
6991869SN/A
7001869SN/A# Set up common yacc/bison flags (needed for Ruby)
7015863Snate@binkert.orgmain['YACCFLAGS'] = '-d'
7025863Snate@binkert.orgmain['YACCHXXFILESUFFIX'] = '.hh'
7031869SN/A
7045863Snate@binkert.org# Do this after we save setting back, or else we'll tack on an
7055863Snate@binkert.org# extra 'qdo' every time we run scons.
7063356Sbinkertn@umich.eduif main['BATCH']:
7073356Sbinkertn@umich.edu    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
7083356Sbinkertn@umich.edu    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
7093356Sbinkertn@umich.edu    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
7103356Sbinkertn@umich.edu    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
7114781Snate@binkert.org    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
7125863Snate@binkert.org
7135863Snate@binkert.orgif sys.platform == 'cygwin':
7141869SN/A    # cygwin has some header file issues...
7151869SN/A    main.Append(CCFLAGS=["-Wno-uninitialized"])
7161869SN/A
7176121Snate@binkert.org# Check for the protobuf compiler
7181869SN/Aprotoc_version = readCommand([main['PROTOC'], '--version'],
7192638Sstever@eecs.umich.edu                             exception='').split()
7206121Snate@binkert.org
7216121Snate@binkert.org# First two words should be "libprotoc x.y.z"
7222638Sstever@eecs.umich.eduif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
7235749Scws3k@cs.virginia.edu    print termcap.Yellow + termcap.Bold + \
7246121Snate@binkert.org        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
7256121Snate@binkert.org        '         Please install protobuf-compiler for tracing support.' + \
7265749Scws3k@cs.virginia.edu        termcap.Normal
7271869SN/A    main['PROTOC'] = False
7281869SN/Aelse:
7293546Sgblack@eecs.umich.edu    # Based on the availability of the compress stream wrappers,
7303546Sgblack@eecs.umich.edu    # require 2.1.0
7313546Sgblack@eecs.umich.edu    min_protoc_version = '2.1.0'
7323546Sgblack@eecs.umich.edu    if compareVersions(protoc_version[1], min_protoc_version) < 0:
7336121Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
7345863Snate@binkert.org            'Warning: protoc version', min_protoc_version, \
7353546Sgblack@eecs.umich.edu            'or newer required.\n' + \
7363546Sgblack@eecs.umich.edu            '         Installed version:', protoc_version[1], \
7373546Sgblack@eecs.umich.edu            termcap.Normal
7383546Sgblack@eecs.umich.edu        main['PROTOC'] = False
7394781Snate@binkert.org    else:
7405863Snate@binkert.org        # Attempt to determine the appropriate include path and
7414781Snate@binkert.org        # library path using pkg-config, that means we also need to
7424781Snate@binkert.org        # check for pkg-config. Note that it is possible to use
7434781Snate@binkert.org        # protobuf without the involvement of pkg-config. Later on we
7444781Snate@binkert.org        # check go a library config check and at that point the test
7454781Snate@binkert.org        # will fail if libprotobuf cannot be found.
7465863Snate@binkert.org        if readCommand(['pkg-config', '--version'], exception=''):
7474781Snate@binkert.org            try:
7484781Snate@binkert.org                # Attempt to establish what linking flags to add for protobuf
7494781Snate@binkert.org                # using pkg-config
7504781Snate@binkert.org                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
7513546Sgblack@eecs.umich.edu            except:
7523546Sgblack@eecs.umich.edu                print termcap.Yellow + termcap.Bold + \
7533546Sgblack@eecs.umich.edu                    'Warning: pkg-config could not get protobuf flags.' + \
7544781Snate@binkert.org                    termcap.Normal
7553546Sgblack@eecs.umich.edu
7563546Sgblack@eecs.umich.edu# Check for SWIG
7573546Sgblack@eecs.umich.eduif not main.has_key('SWIG'):
7583546Sgblack@eecs.umich.edu    print 'Error: SWIG utility not found.'
7593546Sgblack@eecs.umich.edu    print '       Please install (see http://www.swig.org) and retry.'
7603546Sgblack@eecs.umich.edu    Exit(1)
7613546Sgblack@eecs.umich.edu
7623546Sgblack@eecs.umich.edu# Check for appropriate SWIG version
7633546Sgblack@eecs.umich.eduswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
7643546Sgblack@eecs.umich.edu# First 3 words should be "SWIG Version x.y.z"
7654202Sbinkertn@umich.eduif len(swig_version) < 3 or \
7663546Sgblack@eecs.umich.edu        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
7673546Sgblack@eecs.umich.edu    print 'Error determining SWIG version.'
7683546Sgblack@eecs.umich.edu    Exit(1)
769955SN/A
770955SN/Amin_swig_version = '2.0.4'
771955SN/Aif compareVersions(swig_version[2], min_swig_version) < 0:
772955SN/A    print 'Error: SWIG version', min_swig_version, 'or newer required.'
7735863Snate@binkert.org    print '       Installed version:', swig_version[2]
7745863Snate@binkert.org    Exit(1)
7755343Sstever@gmail.com
7765343Sstever@gmail.com# Check for known incompatibilities. The standard library shipped with
7776121Snate@binkert.org# gcc >= 4.9 does not play well with swig versions prior to 3.0
7785863Snate@binkert.orgif main['GCC'] and compareVersions(gcc_version, '4.9') >= 0 and \
7794773Snate@binkert.org        compareVersions(swig_version[2], '3.0') < 0:
7805863Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
7812632Sstever@eecs.umich.edu        'Warning: This combination of gcc and swig have' + \
7825863Snate@binkert.org        ' known incompatibilities.\n' + \
7832023SN/A        '         If you encounter build problems, please update ' + \
7845863Snate@binkert.org        'swig to 3.0 or later.' + \
7855863Snate@binkert.org        termcap.Normal
7865863Snate@binkert.org
7875863Snate@binkert.org# Set up SWIG flags & scanner
7885863Snate@binkert.orgswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
7895863Snate@binkert.orgmain.Append(SWIGFLAGS=swig_flags)
7905863Snate@binkert.org
7915863Snate@binkert.org# Check for 'timeout' from GNU coreutils. If present, regressions will
7925863Snate@binkert.org# be run with a time limit. We require version 8.13 since we rely on
7932632Sstever@eecs.umich.edu# support for the '--foreground' option.
7945863Snate@binkert.orgtimeout_lines = readCommand(['timeout', '--version'],
7952023SN/A                            exception='').splitlines()
7962632Sstever@eecs.umich.edu# Get the first line and tokenize it
7975863Snate@binkert.orgtimeout_version = timeout_lines[0].split() if timeout_lines else []
7985342Sstever@gmail.commain['TIMEOUT'] =  timeout_version and \
7995863Snate@binkert.org    compareVersions(timeout_version[-1], '8.13') >= 0
8002632Sstever@eecs.umich.edu
8015863Snate@binkert.org# filter out all existing swig scanners, they mess up the dependency
8025863Snate@binkert.org# stuff for some reason
8032632Sstever@eecs.umich.eduscanners = []
8045863Snate@binkert.orgfor scanner in main['SCANNERS']:
8055863Snate@binkert.org    skeys = scanner.skeys
8065863Snate@binkert.org    if skeys == '.i':
8075863Snate@binkert.org        continue
8085863Snate@binkert.org
8095863Snate@binkert.org    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
8102632Sstever@eecs.umich.edu        continue
8115863Snate@binkert.org
8125863Snate@binkert.org    scanners.append(scanner)
8132632Sstever@eecs.umich.edu
8141888SN/A# add the new swig scanner that we like better
8155863Snate@binkert.orgfrom SCons.Scanner import ClassicCPP as CPPScanner
8165863Snate@binkert.orgswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
8175863Snate@binkert.orgscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
8181858SN/A
8195863Snate@binkert.org# replace the scanners list that has what we want
8205863Snate@binkert.orgmain['SCANNERS'] = scanners
8215863Snate@binkert.org
8225863Snate@binkert.org# Add a custom Check function to the Configure context so that we can
8232598SN/A# figure out if the compiler adds leading underscores to global
8245863Snate@binkert.org# variables.  This is needed for the autogenerated asm files that we
8251858SN/A# use for embedding the python code.
8261858SN/Adef CheckLeading(context):
8271858SN/A    context.Message("Checking for leading underscore in global variables...")
8285863Snate@binkert.org    # 1) Define a global variable called x from asm so the C compiler
8291858SN/A    #    won't change the symbol at all.
8301858SN/A    # 2) Declare that variable.
8311858SN/A    # 3) Use the variable
8325863Snate@binkert.org    #
8331871SN/A    # If the compiler prepends an underscore, this will successfully
8341858SN/A    # link because the external symbol 'x' will be called '_x' which
8351858SN/A    # was defined by the asm statement.  If the compiler does not
8361858SN/A    # prepend an underscore, this will not successfully link because
8371858SN/A    # '_x' will have been defined by assembly, while the C portion of
8381858SN/A    # the code will be trying to use 'x'
8391858SN/A    ret = context.TryLink('''
8401858SN/A        asm(".globl _x; _x: .byte 0");
8415863Snate@binkert.org        extern int x;
8421858SN/A        int main() { return x; }
8431858SN/A        ''', extension=".c")
8445863Snate@binkert.org    context.env.Append(LEADING_UNDERSCORE=ret)
8451859SN/A    context.Result(ret)
8461859SN/A    return ret
8471869SN/A
8485863Snate@binkert.org# Add a custom Check function to test for structure members.
8495863Snate@binkert.orgdef CheckMember(context, include, decl, member, include_quotes="<>"):
8501869SN/A    context.Message("Checking for member %s in %s..." %
8511965SN/A                    (member, decl))
8521965SN/A    text = """
8531965SN/A#include %(header)s
8542761Sstever@eecs.umich.eduint main(){
8555863Snate@binkert.org  %(decl)s test;
8561869SN/A  (void)test.%(member)s;
8575863Snate@binkert.org  return 0;
8582667Sstever@eecs.umich.edu};
8591869SN/A""" % { "header" : include_quotes[0] + include + include_quotes[1],
8601869SN/A        "decl" : decl,
8612929Sktlim@umich.edu        "member" : member,
8622929Sktlim@umich.edu        }
8635863Snate@binkert.org
8642929Sktlim@umich.edu    ret = context.TryCompile(text, extension=".cc")
865955SN/A    context.Result(ret)
8662598SN/A    return ret
867
868# Platform-specific configuration.  Note again that we assume that all
869# builds under a given build root run on the same host platform.
870conf = Configure(main,
871                 conf_dir = joinpath(build_root, '.scons_config'),
872                 log_file = joinpath(build_root, 'scons_config.log'),
873                 custom_tests = {
874        'CheckLeading' : CheckLeading,
875        'CheckMember' : CheckMember,
876        })
877
878# Check for leading underscores.  Don't really need to worry either
879# way so don't need to check the return code.
880conf.CheckLeading()
881
882# Check if we should compile a 64 bit binary on Mac OS X/Darwin
883try:
884    import platform
885    uname = platform.uname()
886    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
887        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
888            main.Append(CCFLAGS=['-arch', 'x86_64'])
889            main.Append(CFLAGS=['-arch', 'x86_64'])
890            main.Append(LINKFLAGS=['-arch', 'x86_64'])
891            main.Append(ASFLAGS=['-arch', 'x86_64'])
892except:
893    pass
894
895# Recent versions of scons substitute a "Null" object for Configure()
896# when configuration isn't necessary, e.g., if the "--help" option is
897# present.  Unfortuantely this Null object always returns false,
898# breaking all our configuration checks.  We replace it with our own
899# more optimistic null object that returns True instead.
900if not conf:
901    def NullCheck(*args, **kwargs):
902        return True
903
904    class NullConf:
905        def __init__(self, env):
906            self.env = env
907        def Finish(self):
908            return self.env
909        def __getattr__(self, mname):
910            return NullCheck
911
912    conf = NullConf(main)
913
914# Cache build files in the supplied directory.
915if main['M5_BUILD_CACHE']:
916    print 'Using build cache located at', main['M5_BUILD_CACHE']
917    CacheDir(main['M5_BUILD_CACHE'])
918
919if not GetOption('without_python'):
920    # Find Python include and library directories for embedding the
921    # interpreter. We rely on python-config to resolve the appropriate
922    # includes and linker flags. ParseConfig does not seem to understand
923    # the more exotic linker flags such as -Xlinker and -export-dynamic so
924    # we add them explicitly below. If you want to link in an alternate
925    # version of python, see above for instructions on how to invoke
926    # scons with the appropriate PATH set.
927    #
928    # First we check if python2-config exists, else we use python-config
929    python_config = readCommand(['which', 'python2-config'],
930                                exception='').strip()
931    if not os.path.exists(python_config):
932        python_config = readCommand(['which', 'python-config'],
933                                    exception='').strip()
934    py_includes = readCommand([python_config, '--includes'],
935                              exception='').split()
936    # Strip the -I from the include folders before adding them to the
937    # CPPPATH
938    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
939
940    # Read the linker flags and split them into libraries and other link
941    # flags. The libraries are added later through the call the CheckLib.
942    py_ld_flags = readCommand([python_config, '--ldflags'],
943        exception='').split()
944    py_libs = []
945    for lib in py_ld_flags:
946         if not lib.startswith('-l'):
947             main.Append(LINKFLAGS=[lib])
948         else:
949             lib = lib[2:]
950             if lib not in py_libs:
951                 py_libs.append(lib)
952
953    # verify that this stuff works
954    if not conf.CheckHeader('Python.h', '<>'):
955        print "Error: can't find Python.h header in", py_includes
956        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
957        Exit(1)
958
959    for lib in py_libs:
960        if not conf.CheckLib(lib):
961            print "Error: can't find library %s required by python" % lib
962            Exit(1)
963
964# On Solaris you need to use libsocket for socket ops
965if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
966   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
967       print "Can't find library with socket calls (e.g. accept())"
968       Exit(1)
969
970# Check for zlib.  If the check passes, libz will be automatically
971# added to the LIBS environment variable.
972if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
973    print 'Error: did not find needed zlib compression library '\
974          'and/or zlib.h header file.'
975    print '       Please install zlib and try again.'
976    Exit(1)
977
978# If we have the protobuf compiler, also make sure we have the
979# development libraries. If the check passes, libprotobuf will be
980# automatically added to the LIBS environment variable. After
981# this, we can use the HAVE_PROTOBUF flag to determine if we have
982# got both protoc and libprotobuf available.
983main['HAVE_PROTOBUF'] = main['PROTOC'] and \
984    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
985                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
986
987# If we have the compiler but not the library, print another warning.
988if main['PROTOC'] and not main['HAVE_PROTOBUF']:
989    print termcap.Yellow + termcap.Bold + \
990        'Warning: did not find protocol buffer library and/or headers.\n' + \
991    '       Please install libprotobuf-dev for tracing support.' + \
992    termcap.Normal
993
994# Check for librt.
995have_posix_clock = \
996    conf.CheckLibWithHeader(None, 'time.h', 'C',
997                            'clock_nanosleep(0,0,NULL,NULL);') or \
998    conf.CheckLibWithHeader('rt', 'time.h', 'C',
999                            'clock_nanosleep(0,0,NULL,NULL);')
1000
1001have_posix_timers = \
1002    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
1003                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
1004
1005if not GetOption('without_tcmalloc'):
1006    if conf.CheckLib('tcmalloc'):
1007        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
1008    elif conf.CheckLib('tcmalloc_minimal'):
1009        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
1010    else:
1011        print termcap.Yellow + termcap.Bold + \
1012              "You can get a 12% performance improvement by "\
1013              "installing tcmalloc (libgoogle-perftools-dev package "\
1014              "on Ubuntu or RedHat)." + termcap.Normal
1015
1016if not have_posix_clock:
1017    print "Can't find library for POSIX clocks."
1018
1019# Check for <fenv.h> (C99 FP environment control)
1020have_fenv = conf.CheckHeader('fenv.h', '<>')
1021if not have_fenv:
1022    print "Warning: Header file <fenv.h> not found."
1023    print "         This host has no IEEE FP rounding mode control."
1024
1025# Check if we should enable KVM-based hardware virtualization. The API
1026# we rely on exists since version 2.6.36 of the kernel, but somehow
1027# the KVM_API_VERSION does not reflect the change. We test for one of
1028# the types as a fall back.
1029have_kvm = conf.CheckHeader('linux/kvm.h', '<>')
1030if not have_kvm:
1031    print "Info: Compatible header file <linux/kvm.h> not found, " \
1032        "disabling KVM support."
1033
1034# x86 needs support for xsave. We test for the structure here since we
1035# won't be able to run new tests by the time we know which ISA we're
1036# targeting.
1037have_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
1038                                    '#include <linux/kvm.h>') != 0
1039
1040# Check if the requested target ISA is compatible with the host
1041def is_isa_kvm_compatible(isa):
1042    try:
1043        import platform
1044        host_isa = platform.machine()
1045    except:
1046        print "Warning: Failed to determine host ISA."
1047        return False
1048
1049    if not have_posix_timers:
1050        print "Warning: Can not enable KVM, host seems to lack support " \
1051            "for POSIX timers"
1052        return False
1053
1054    if isa == "arm":
1055        return host_isa in ( "armv7l", "aarch64" )
1056    elif isa == "x86":
1057        if host_isa != "x86_64":
1058            return False
1059
1060        if not have_kvm_xsave:
1061            print "KVM on x86 requires xsave support in kernel headers."
1062            return False
1063
1064        return True
1065    else:
1066        return False
1067
1068
1069# Check if the exclude_host attribute is available. We want this to
1070# get accurate instruction counts in KVM.
1071main['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
1072    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
1073
1074
1075######################################################################
1076#
1077# Finish the configuration
1078#
1079main = conf.Finish()
1080
1081######################################################################
1082#
1083# Collect all non-global variables
1084#
1085
1086# Define the universe of supported ISAs
1087all_isa_list = [ ]
1088Export('all_isa_list')
1089
1090class CpuModel(object):
1091    '''The CpuModel class encapsulates everything the ISA parser needs to
1092    know about a particular CPU model.'''
1093
1094    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
1095    dict = {}
1096
1097    # Constructor.  Automatically adds models to CpuModel.dict.
1098    def __init__(self, name, default=False):
1099        self.name = name           # name of model
1100
1101        # This cpu is enabled by default
1102        self.default = default
1103
1104        # Add self to dict
1105        if name in CpuModel.dict:
1106            raise AttributeError, "CpuModel '%s' already registered" % name
1107        CpuModel.dict[name] = self
1108
1109Export('CpuModel')
1110
1111# Sticky variables get saved in the variables file so they persist from
1112# one invocation to the next (unless overridden, in which case the new
1113# value becomes sticky).
1114sticky_vars = Variables(args=ARGUMENTS)
1115Export('sticky_vars')
1116
1117# Sticky variables that should be exported
1118export_vars = []
1119Export('export_vars')
1120
1121# For Ruby
1122all_protocols = []
1123Export('all_protocols')
1124protocol_dirs = []
1125Export('protocol_dirs')
1126slicc_includes = []
1127Export('slicc_includes')
1128
1129# Walk the tree and execute all SConsopts scripts that wil add to the
1130# above variables
1131if GetOption('verbose'):
1132    print "Reading SConsopts"
1133for bdir in [ base_dir ] + extras_dir_list:
1134    if not isdir(bdir):
1135        print "Error: directory '%s' does not exist" % bdir
1136        Exit(1)
1137    for root, dirs, files in os.walk(bdir):
1138        if 'SConsopts' in files:
1139            if GetOption('verbose'):
1140                print "Reading", joinpath(root, 'SConsopts')
1141            SConscript(joinpath(root, 'SConsopts'))
1142
1143all_isa_list.sort()
1144
1145sticky_vars.AddVariables(
1146    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
1147    ListVariable('CPU_MODELS', 'CPU models',
1148                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
1149                 sorted(CpuModel.dict.keys())),
1150    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
1151                 False),
1152    BoolVariable('SS_COMPATIBLE_FP',
1153                 'Make floating-point results compatible with SimpleScalar',
1154                 False),
1155    BoolVariable('USE_SSE2',
1156                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
1157                 False),
1158    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
1159    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
1160    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
1161    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
1162    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1163                  all_protocols),
1164    )
1165
1166# These variables get exported to #defines in config/*.hh (see src/SConscript).
1167export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'CP_ANNOTATE',
1168                'USE_POSIX_CLOCK', 'USE_KVM', 'PROTOCOL', 'HAVE_PROTOBUF',
1169                'HAVE_PERF_ATTR_EXCLUDE_HOST']
1170
1171###################################################
1172#
1173# Define a SCons builder for configuration flag headers.
1174#
1175###################################################
1176
1177# This function generates a config header file that #defines the
1178# variable symbol to the current variable setting (0 or 1).  The source
1179# operands are the name of the variable and a Value node containing the
1180# value of the variable.
1181def build_config_file(target, source, env):
1182    (variable, value) = [s.get_contents() for s in source]
1183    f = file(str(target[0]), 'w')
1184    print >> f, '#define', variable, value
1185    f.close()
1186    return None
1187
1188# Combine the two functions into a scons Action object.
1189config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1190
1191# The emitter munges the source & target node lists to reflect what
1192# we're really doing.
1193def config_emitter(target, source, env):
1194    # extract variable name from Builder arg
1195    variable = str(target[0])
1196    # True target is config header file
1197    target = joinpath('config', variable.lower() + '.hh')
1198    val = env[variable]
1199    if isinstance(val, bool):
1200        # Force value to 0/1
1201        val = int(val)
1202    elif isinstance(val, str):
1203        val = '"' + val + '"'
1204
1205    # Sources are variable name & value (packaged in SCons Value nodes)
1206    return ([target], [Value(variable), Value(val)])
1207
1208config_builder = Builder(emitter = config_emitter, action = config_action)
1209
1210main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1211
1212# libelf build is shared across all configs in the build root.
1213main.SConscript('ext/libelf/SConscript',
1214                variant_dir = joinpath(build_root, 'libelf'))
1215
1216# gzstream build is shared across all configs in the build root.
1217main.SConscript('ext/gzstream/SConscript',
1218                variant_dir = joinpath(build_root, 'gzstream'))
1219
1220# libfdt build is shared across all configs in the build root.
1221main.SConscript('ext/libfdt/SConscript',
1222                variant_dir = joinpath(build_root, 'libfdt'))
1223
1224# fputils build is shared across all configs in the build root.
1225main.SConscript('ext/fputils/SConscript',
1226                variant_dir = joinpath(build_root, 'fputils'))
1227
1228# DRAMSim2 build is shared across all configs in the build root.
1229main.SConscript('ext/dramsim2/SConscript',
1230                variant_dir = joinpath(build_root, 'dramsim2'))
1231
1232# DRAMPower build is shared across all configs in the build root.
1233main.SConscript('ext/drampower/SConscript',
1234                variant_dir = joinpath(build_root, 'drampower'))
1235
1236###################################################
1237#
1238# This function is used to set up a directory with switching headers
1239#
1240###################################################
1241
1242main['ALL_ISA_LIST'] = all_isa_list
1243all_isa_deps = {}
1244def make_switching_dir(dname, switch_headers, env):
1245    # Generate the header.  target[0] is the full path of the output
1246    # header to generate.  'source' is a dummy variable, since we get the
1247    # list of ISAs from env['ALL_ISA_LIST'].
1248    def gen_switch_hdr(target, source, env):
1249        fname = str(target[0])
1250        isa = env['TARGET_ISA'].lower()
1251        try:
1252            f = open(fname, 'w')
1253            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1254            f.close()
1255        except IOError:
1256            print "Failed to create %s" % fname
1257            raise
1258
1259    # Build SCons Action object. 'varlist' specifies env vars that this
1260    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1261    # should get re-executed.
1262    switch_hdr_action = MakeAction(gen_switch_hdr,
1263                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1264
1265    # Instantiate actions for each header
1266    for hdr in switch_headers:
1267        env.Command(hdr, [], switch_hdr_action)
1268
1269    isa_target = Dir('.').up().name.lower().replace('_', '-')
1270    env['PHONY_BASE'] = '#'+isa_target
1271    all_isa_deps[isa_target] = None
1272
1273Export('make_switching_dir')
1274
1275# all-isas -> all-deps -> all-environs -> all_targets
1276main.Alias('#all-isas', [])
1277main.Alias('#all-deps', '#all-isas')
1278
1279# Dummy target to ensure all environments are created before telling
1280# SCons what to actually make (the command line arguments).  We attach
1281# them to the dependence graph after the environments are complete.
1282ORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
1283def environsComplete(target, source, env):
1284    for t in ORIG_BUILD_TARGETS:
1285        main.Depends('#all-targets', t)
1286
1287# Each build/* switching_dir attaches its *-environs target to #all-environs.
1288main.Append(BUILDERS = {'CompleteEnvirons' :
1289                        Builder(action=MakeAction(environsComplete, None))})
1290main.CompleteEnvirons('#all-environs', [])
1291
1292def doNothing(**ignored): pass
1293main.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
1294
1295# The final target to which all the original targets ultimately get attached.
1296main.Dummy('#all-targets', '#all-environs')
1297BUILD_TARGETS[:] = ['#all-targets']
1298
1299###################################################
1300#
1301# Define build environments for selected configurations.
1302#
1303###################################################
1304
1305for variant_path in variant_paths:
1306    if not GetOption('silent'):
1307        print "Building in", variant_path
1308
1309    # Make a copy of the build-root environment to use for this config.
1310    env = main.Clone()
1311    env['BUILDDIR'] = variant_path
1312
1313    # variant_dir is the tail component of build path, and is used to
1314    # determine the build parameters (e.g., 'ALPHA_SE')
1315    (build_root, variant_dir) = splitpath(variant_path)
1316
1317    # Set env variables according to the build directory config.
1318    sticky_vars.files = []
1319    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1320    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1321    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1322    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1323    if isfile(current_vars_file):
1324        sticky_vars.files.append(current_vars_file)
1325        if not GetOption('silent'):
1326            print "Using saved variables file %s" % current_vars_file
1327    else:
1328        # Build dir-specific variables file doesn't exist.
1329
1330        # Make sure the directory is there so we can create it later
1331        opt_dir = dirname(current_vars_file)
1332        if not isdir(opt_dir):
1333            mkdir(opt_dir)
1334
1335        # Get default build variables from source tree.  Variables are
1336        # normally determined by name of $VARIANT_DIR, but can be
1337        # overridden by '--default=' arg on command line.
1338        default = GetOption('default')
1339        opts_dir = joinpath(main.root.abspath, 'build_opts')
1340        if default:
1341            default_vars_files = [joinpath(build_root, 'variables', default),
1342                                  joinpath(opts_dir, default)]
1343        else:
1344            default_vars_files = [joinpath(opts_dir, variant_dir)]
1345        existing_files = filter(isfile, default_vars_files)
1346        if existing_files:
1347            default_vars_file = existing_files[0]
1348            sticky_vars.files.append(default_vars_file)
1349            print "Variables file %s not found,\n  using defaults in %s" \
1350                  % (current_vars_file, default_vars_file)
1351        else:
1352            print "Error: cannot find variables file %s or " \
1353                  "default file(s) %s" \
1354                  % (current_vars_file, ' or '.join(default_vars_files))
1355            Exit(1)
1356
1357    # Apply current variable settings to env
1358    sticky_vars.Update(env)
1359
1360    help_texts["local_vars"] += \
1361        "Build variables for %s:\n" % variant_dir \
1362                 + sticky_vars.GenerateHelpText(env)
1363
1364    # Process variable settings.
1365
1366    if not have_fenv and env['USE_FENV']:
1367        print "Warning: <fenv.h> not available; " \
1368              "forcing USE_FENV to False in", variant_dir + "."
1369        env['USE_FENV'] = False
1370
1371    if not env['USE_FENV']:
1372        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1373        print "         FP results may deviate slightly from other platforms."
1374
1375    if env['EFENCE']:
1376        env.Append(LIBS=['efence'])
1377
1378    if env['USE_KVM']:
1379        if not have_kvm:
1380            print "Warning: Can not enable KVM, host seems to lack KVM support"
1381            env['USE_KVM'] = False
1382        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1383            print "Info: KVM support disabled due to unsupported host and " \
1384                "target ISA combination"
1385            env['USE_KVM'] = False
1386
1387    # Warn about missing optional functionality
1388    if env['USE_KVM']:
1389        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1390            print "Warning: perf_event headers lack support for the " \
1391                "exclude_host attribute. KVM instruction counts will " \
1392                "be inaccurate."
1393
1394    # Save sticky variable settings back to current variables file
1395    sticky_vars.Save(current_vars_file, env)
1396
1397    if env['USE_SSE2']:
1398        env.Append(CCFLAGS=['-msse2'])
1399
1400    # The src/SConscript file sets up the build rules in 'env' according
1401    # to the configured variables.  It returns a list of environments,
1402    # one for each variant build (debug, opt, etc.)
1403    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1404
1405def pairwise(iterable):
1406    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1407    a, b = itertools.tee(iterable)
1408    b.next()
1409    return itertools.izip(a, b)
1410
1411# Create false dependencies so SCons will parse ISAs, establish
1412# dependencies, and setup the build Environments serially. Either
1413# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1414# greater than 1. It appears to be standard race condition stuff; it
1415# doesn't always fail, but usually, and the behaviors are different.
1416# Every time I tried to remove this, builds would fail in some
1417# creative new way. So, don't do that. You'll want to, though, because
1418# tests/SConscript takes a long time to make its Environments.
1419for t1, t2 in pairwise(sorted(all_isa_deps.iterkeys())):
1420    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1421    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1422
1423# base help text
1424Help('''
1425Usage: scons [scons options] [build variables] [target(s)]
1426
1427Extra scons options:
1428%(options)s
1429
1430Global build variables:
1431%(global_vars)s
1432
1433%(local_vars)s
1434''' % help_texts)
1435