SConstruct revision 9812
1955SN/A# -*- mode:python -*-
2955SN/A
37816Ssteve.reinhardt@amd.com# Copyright (c) 2013 ARM Limited
45871Snate@binkert.org# All rights reserved.
51762SN/A#
6955SN/A# The license below extends only to copyright in the software and shall
7955SN/A# not be construed as granting a license to any other intellectual
8955SN/A# property including but not limited to intellectual property relating
9955SN/A# to a hardware implementation of the functionality of the software
10955SN/A# licensed hereunder.  You may use the software subject to the license
11955SN/A# terms below provided that you ensure that this notice is replicated
12955SN/A# unmodified and in its entirety in all distributions of the software,
13955SN/A# modified or unmodified, in source code or in binary form.
14955SN/A#
15955SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
16955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
17955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
18955SN/A# All rights reserved.
19955SN/A#
20955SN/A# Redistribution and use in source and binary forms, with or without
21955SN/A# modification, are permitted provided that the following conditions are
22955SN/A# met: redistributions of source code must retain the above copyright
23955SN/A# notice, this list of conditions and the following disclaimer;
24955SN/A# redistributions in binary form must reproduce the above copyright
25955SN/A# notice, this list of conditions and the following disclaimer in the
26955SN/A# documentation and/or other materials provided with the distribution;
27955SN/A# neither the name of the copyright holders nor the names of its
28955SN/A# contributors may be used to endorse or promote products derived from
29955SN/A# this software without specific prior written permission.
302665Ssaidi@eecs.umich.edu#
312665Ssaidi@eecs.umich.edu# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
325863Snate@binkert.org# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
388878Ssteve.reinhardt@amd.com# 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
408878Ssteve.reinhardt@amd.com# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
412632Sstever@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42955SN/A#
438878Ssteve.reinhardt@amd.com# Authors: Steve Reinhardt
442632Sstever@eecs.umich.edu#          Nathan Binkert
452761Sstever@eecs.umich.edu
462632Sstever@eecs.umich.edu###################################################
472632Sstever@eecs.umich.edu#
482632Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
492761Sstever@eecs.umich.edu#
502761Sstever@eecs.umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
512761Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
528878Ssteve.reinhardt@amd.com# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
538878Ssteve.reinhardt@amd.com# the optimized full-system version).
542761Sstever@eecs.umich.edu#
552761Sstever@eecs.umich.edu# You can build gem5 in a different directory as long as there is a
562761Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
572761Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
582761Sstever@eecs.umich.edu# built for the same host system.
598878Ssteve.reinhardt@amd.com#
608878Ssteve.reinhardt@amd.com# Examples:
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
638878Ssteve.reinhardt@amd.com#   scons to search up the directory tree for this SConstruct file.
648878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
652632Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
66955SN/A#
67955SN/A#   The following two commands are equivalent and demonstrate building
68955SN/A#   in a directory outside of the source tree.  The '-C' option tells
695863Snate@binkert.org#   scons to chdir to the specified directory to find this SConstruct
705863Snate@binkert.org#   file.
715863Snate@binkert.org#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
725863Snate@binkert.org#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
735863Snate@binkert.org#
745863Snate@binkert.org# You can use 'scons -H' to print scons options.  If you're in this
755863Snate@binkert.org# 'gem5' directory (or use -u or -C to tell scons where to find this
765863Snate@binkert.org# file), you can use 'scons -h' to print all the gem5-specific build
775863Snate@binkert.org# options as well.
785863Snate@binkert.org#
795863Snate@binkert.org###################################################
808878Ssteve.reinhardt@amd.com
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
968878Ssteve.reinhardt@amd.com# We ensure the python version early because because python-config
975863Snate@binkert.org# requires python 2.5
985863Snate@binkert.orgtry:
995863Snate@binkert.org    EnsurePythonVersion(2, 5)
1006654Snate@binkert.orgexcept SystemExit, e:
101955SN/A    print """
1025396Ssaidi@eecs.umich.eduYou 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
1045863Snate@binkert.org'python-config' first.
1054202Sbinkertn@umich.edu
1065863Snate@binkert.orgFor more details, see:
1075863Snate@binkert.org    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1085863Snate@binkert.org"""
1095863Snate@binkert.org    raise
110955SN/A
1116654Snate@binkert.org# Global Python includes
1125273Sstever@gmail.comimport os
1135871Snate@binkert.orgimport re
1145273Sstever@gmail.comimport subprocess
1156655Snate@binkert.orgimport sys
1168878Ssteve.reinhardt@amd.com
1176655Snate@binkert.orgfrom os import mkdir, environ
1186655Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1199219Spower.jg@gmail.comfrom os.path import exists,  isdir, isfile
1206655Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1215871Snate@binkert.org
1226654Snate@binkert.org# SCons includes
1238947Sandreas.hansson@arm.comimport SCons
1245396Ssaidi@eecs.umich.eduimport SCons.Node
1258120Sgblack@eecs.umich.edu
1268120Sgblack@eecs.umich.eduextra_python_paths = [
1278120Sgblack@eecs.umich.edu    Dir('src/python').srcnode().abspath, # gem5 includes
1288120Sgblack@eecs.umich.edu    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1298120Sgblack@eecs.umich.edu    ]
1308120Sgblack@eecs.umich.edu
1318120Sgblack@eecs.umich.edusys.path[1:1] = extra_python_paths
1328120Sgblack@eecs.umich.edu
1338879Ssteve.reinhardt@amd.comfrom m5.util import compareVersions, readCommand
1348879Ssteve.reinhardt@amd.comfrom m5.util.terminal import get_termcap
1358879Ssteve.reinhardt@amd.com
1368879Ssteve.reinhardt@amd.comhelp_texts = {
1378879Ssteve.reinhardt@amd.com    "options" : "",
1388879Ssteve.reinhardt@amd.com    "global_vars" : "",
1398879Ssteve.reinhardt@amd.com    "local_vars" : ""
1408879Ssteve.reinhardt@amd.com}
1418879Ssteve.reinhardt@amd.com
1428879Ssteve.reinhardt@amd.comExport("help_texts")
1438879Ssteve.reinhardt@amd.com
1448879Ssteve.reinhardt@amd.com
1458879Ssteve.reinhardt@amd.com# There's a bug in scons in that (1) by default, the help texts from
1468120Sgblack@eecs.umich.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1478120Sgblack@eecs.umich.edu# and (2) you can override the help displayed by 'scons -h' using the
1488120Sgblack@eecs.umich.edu# Help() function, but these two features are incompatible: once
1498120Sgblack@eecs.umich.edu# you've overridden the help text using Help(), there's no way to get
1508120Sgblack@eecs.umich.edu# at the help texts from AddOptions.  See:
1518120Sgblack@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1528120Sgblack@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1538120Sgblack@eecs.umich.edu# This hack lets us extract the help text from AddOptions and
1548120Sgblack@eecs.umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1558120Sgblack@eecs.umich.edu# we can just use AddOption directly.
1568120Sgblack@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1578120Sgblack@eecs.umich.edu    col_width = 30
1588120Sgblack@eecs.umich.edu
1598120Sgblack@eecs.umich.edu    help = "  " + ", ".join(args)
1608879Ssteve.reinhardt@amd.com    if "help" in kwargs:
1618879Ssteve.reinhardt@amd.com        length = len(help)
1628879Ssteve.reinhardt@amd.com        if length >= col_width:
1638879Ssteve.reinhardt@amd.com            help += "\n" + " " * col_width
1648879Ssteve.reinhardt@amd.com        else:
1658879Ssteve.reinhardt@amd.com            help += " " * (col_width - length)
1668879Ssteve.reinhardt@amd.com        help += kwargs["help"]
1678879Ssteve.reinhardt@amd.com    help_texts["options"] += help + "\n"
1689227Sandreas.hansson@arm.com
1699227Sandreas.hansson@arm.com    AddOption(*args, **kwargs)
1708879Ssteve.reinhardt@amd.com
1718879Ssteve.reinhardt@amd.comAddLocalOption('--colors', dest='use_colors', action='store_true',
1728879Ssteve.reinhardt@amd.com               help="Add color to abbreviated scons output")
1738879Ssteve.reinhardt@amd.comAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1748120Sgblack@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1758947Sandreas.hansson@arm.comAddLocalOption('--default', dest='default', type='string', action='store',
1767816Ssteve.reinhardt@amd.com               help='Override which build_opts file to use for defaults')
1775871Snate@binkert.orgAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1785871Snate@binkert.org               help='Disable style checking hooks')
1796121Snate@binkert.orgAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1805871Snate@binkert.org               help='Disable Link-Time Optimization for fast')
1815871Snate@binkert.orgAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1829119Sandreas.hansson@arm.com               help='Update test reference outputs')
1839396Sandreas.hansson@arm.comAddLocalOption('--verbose', dest='verbose', action='store_true',
1849396Sandreas.hansson@arm.com               help='Print full tool command lines')
185955SN/A
1865871Snate@binkert.orgtermcap = get_termcap(GetOption('use_colors'))
1875871Snate@binkert.org
1885871Snate@binkert.org########################################################################
1895871Snate@binkert.org#
190955SN/A# Set up the main build environment.
1916121Snate@binkert.org#
1928881Smarc.orr@gmail.com########################################################################
1936121Snate@binkert.orguse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
1946121Snate@binkert.org                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PYTHONPATH',
1951533SN/A                 'RANLIB', 'SWIG' ])
1969239Sandreas.hansson@arm.com
1979239Sandreas.hansson@arm.comuse_prefixes = [
1989239Sandreas.hansson@arm.com    "M5",           # M5 configuration (e.g., path to kernels)
1999239Sandreas.hansson@arm.com    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
2009239Sandreas.hansson@arm.com    "CCACHE_",      # ccache (caching compiler wrapper) configuration
2019239Sandreas.hansson@arm.com    "CCC_",         # clang static analyzer configuration
2029239Sandreas.hansson@arm.com    ]
2039239Sandreas.hansson@arm.com
2049239Sandreas.hansson@arm.comuse_env = {}
2059239Sandreas.hansson@arm.comfor key,val in os.environ.iteritems():
2069239Sandreas.hansson@arm.com    if key in use_vars or \
2079239Sandreas.hansson@arm.com            any([key.startswith(prefix) for prefix in use_prefixes]):
2086655Snate@binkert.org        use_env[key] = val
2096655Snate@binkert.org
2106655Snate@binkert.orgmain = Environment(ENV=use_env)
2116655Snate@binkert.orgmain.Decider('MD5-timestamp')
2125871Snate@binkert.orgmain.root = Dir(".")         # The current directory (where this file lives).
2135871Snate@binkert.orgmain.srcdir = Dir("src")     # The source directory
2145863Snate@binkert.org
2155871Snate@binkert.orgmain_dict_keys = main.Dictionary().keys()
2168878Ssteve.reinhardt@amd.com
2175871Snate@binkert.org# Check that we have a C/C++ compiler
2185871Snate@binkert.orgif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2195871Snate@binkert.org    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2205863Snate@binkert.org    Exit(1)
2216121Snate@binkert.org
2225863Snate@binkert.org# Check that swig is present
2235871Snate@binkert.orgif not 'SWIG' in main_dict_keys:
2248336Ssteve.reinhardt@amd.com    print "swig is not installed (package swig on Ubuntu and RedHat)"
2258336Ssteve.reinhardt@amd.com    Exit(1)
2268336Ssteve.reinhardt@amd.com
2278336Ssteve.reinhardt@amd.com# add useful python code PYTHONPATH so it can be used by subprocesses
2284678Snate@binkert.org# as well
2298336Ssteve.reinhardt@amd.commain.AppendENVPath('PYTHONPATH', extra_python_paths)
2308336Ssteve.reinhardt@amd.com
2318336Ssteve.reinhardt@amd.com########################################################################
2324678Snate@binkert.org#
2334678Snate@binkert.org# Mercurial Stuff.
2344678Snate@binkert.org#
2354678Snate@binkert.org# If the gem5 directory is a mercurial repository, we should do some
2367827Snate@binkert.org# extra things.
2377827Snate@binkert.org#
2388336Ssteve.reinhardt@amd.com########################################################################
2394678Snate@binkert.org
2408336Ssteve.reinhardt@amd.comhgdir = main.root.Dir(".hg")
2418336Ssteve.reinhardt@amd.com
2428336Ssteve.reinhardt@amd.commercurial_style_message = """
2438336Ssteve.reinhardt@amd.comYou're missing the gem5 style hook, which automatically checks your code
2448336Ssteve.reinhardt@amd.comagainst the gem5 style rules on hg commit and qrefresh commands.  This
2458336Ssteve.reinhardt@amd.comscript will now install the hook in your .hg/hgrc file.
2465871Snate@binkert.orgPress enter to continue, or ctrl-c to abort: """
2475871Snate@binkert.org
2488336Ssteve.reinhardt@amd.commercurial_style_hook = """
2498336Ssteve.reinhardt@amd.com# The following lines were automatically added by gem5/SConstruct
2508336Ssteve.reinhardt@amd.com# to provide the gem5 style-checking hooks
2518336Ssteve.reinhardt@amd.com[extensions]
2528336Ssteve.reinhardt@amd.comstyle = %s/util/style.py
2535871Snate@binkert.org
2548336Ssteve.reinhardt@amd.com[hooks]
2558336Ssteve.reinhardt@amd.compretxncommit.style = python:style.check_style
2568336Ssteve.reinhardt@amd.compre-qrefresh.style = python:style.check_style
2578336Ssteve.reinhardt@amd.com# End of SConstruct additions
2588336Ssteve.reinhardt@amd.com
2594678Snate@binkert.org""" % (main.root.abspath)
2605871Snate@binkert.org
2614678Snate@binkert.orgmercurial_lib_not_found = """
2628336Ssteve.reinhardt@amd.comMercurial libraries cannot be found, ignoring style hook.  If
2638336Ssteve.reinhardt@amd.comyou are a gem5 developer, please fix this and run the style
2648336Ssteve.reinhardt@amd.comhook. It is important.
2658336Ssteve.reinhardt@amd.com"""
2668336Ssteve.reinhardt@amd.com
2678336Ssteve.reinhardt@amd.com# Check for style hook and prompt for installation if it's not there.
2688336Ssteve.reinhardt@amd.com# Skip this if --ignore-style was specified, there's no .hg dir to
2698336Ssteve.reinhardt@amd.com# install a hook in, or there's no interactive terminal to prompt.
2708336Ssteve.reinhardt@amd.comif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2718336Ssteve.reinhardt@amd.com    style_hook = True
2728336Ssteve.reinhardt@amd.com    try:
2738336Ssteve.reinhardt@amd.com        from mercurial import ui
2748336Ssteve.reinhardt@amd.com        ui = ui.ui()
2758336Ssteve.reinhardt@amd.com        ui.readconfig(hgdir.File('hgrc').abspath)
2768336Ssteve.reinhardt@amd.com        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2778336Ssteve.reinhardt@amd.com                     ui.config('hooks', 'pre-qrefresh.style', None)
2788336Ssteve.reinhardt@amd.com    except ImportError:
2795871Snate@binkert.org        print mercurial_lib_not_found
2806121Snate@binkert.org
281955SN/A    if not style_hook:
282955SN/A        print mercurial_style_message,
2832632Sstever@eecs.umich.edu        # continue unless user does ctrl-c/ctrl-d etc.
2842632Sstever@eecs.umich.edu        try:
285955SN/A            raw_input()
286955SN/A        except:
287955SN/A            print "Input exception, exiting scons.\n"
288955SN/A            sys.exit(1)
2898878Ssteve.reinhardt@amd.com        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
290955SN/A        print "Adding style hook to", hgrc_path, "\n"
2912632Sstever@eecs.umich.edu        try:
2922632Sstever@eecs.umich.edu            hgrc = open(hgrc_path, 'a')
2932632Sstever@eecs.umich.edu            hgrc.write(mercurial_style_hook)
2942632Sstever@eecs.umich.edu            hgrc.close()
2952632Sstever@eecs.umich.edu        except:
2962632Sstever@eecs.umich.edu            print "Error updating", hgrc_path
2972632Sstever@eecs.umich.edu            sys.exit(1)
2988268Ssteve.reinhardt@amd.com
2998268Ssteve.reinhardt@amd.com
3008268Ssteve.reinhardt@amd.com###################################################
3018268Ssteve.reinhardt@amd.com#
3028268Ssteve.reinhardt@amd.com# Figure out which configurations to set up based on the path(s) of
3038268Ssteve.reinhardt@amd.com# the target(s).
3048268Ssteve.reinhardt@amd.com#
3052632Sstever@eecs.umich.edu###################################################
3062632Sstever@eecs.umich.edu
3072632Sstever@eecs.umich.edu# Find default configuration & binary.
3082632Sstever@eecs.umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
3098268Ssteve.reinhardt@amd.com
3102632Sstever@eecs.umich.edu# helper function: find last occurrence of element in list
3118268Ssteve.reinhardt@amd.comdef rfind(l, elt, offs = -1):
3128268Ssteve.reinhardt@amd.com    for i in range(len(l)+offs, 0, -1):
3138268Ssteve.reinhardt@amd.com        if l[i] == elt:
3148268Ssteve.reinhardt@amd.com            return i
3153718Sstever@eecs.umich.edu    raise ValueError, "element not found"
3162634Sstever@eecs.umich.edu
3172634Sstever@eecs.umich.edu# Take a list of paths (or SCons Nodes) and return a list with all
3185863Snate@binkert.org# paths made absolute and ~-expanded.  Paths will be interpreted
3192638Sstever@eecs.umich.edu# relative to the launch directory unless a different root is provided
3208268Ssteve.reinhardt@amd.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
3212632Sstever@eecs.umich.edu    return [abspath(joinpath(root, expanduser(str(p))))
3222632Sstever@eecs.umich.edu            for p in path_list]
3232632Sstever@eecs.umich.edu
3242632Sstever@eecs.umich.edu# Each target must have 'build' in the interior of the path; the
3252632Sstever@eecs.umich.edu# directory below this will determine the build parameters.  For
3261858SN/A# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3273716Sstever@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
3282638Sstever@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
3322638Sstever@eecs.umich.edu# doesn't work (obviously!).
3332638Sstever@eecs.umich.eduBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3342638Sstever@eecs.umich.edu
3355863Snate@binkert.org# Generate a list of the unique build roots and configs that the
3365863Snate@binkert.org# collected targets reference.
3375863Snate@binkert.orgvariant_paths = []
338955SN/Abuild_root = None
3395341Sstever@gmail.comfor t in BUILD_TARGETS:
3405341Sstever@gmail.com    path_dirs = t.split('/')
3415863Snate@binkert.org    try:
3427756SAli.Saidi@ARM.com        build_top = rfind(path_dirs, 'build', -2)
3435341Sstever@gmail.com    except:
3446121Snate@binkert.org        print "Error: no non-leaf 'build' dir found on target path", t
3454494Ssaidi@eecs.umich.edu        Exit(1)
3466121Snate@binkert.org    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3471105SN/A    if not build_root:
3482667Sstever@eecs.umich.edu        build_root = this_build_root
3492667Sstever@eecs.umich.edu    else:
3502667Sstever@eecs.umich.edu        if this_build_root != build_root:
3512667Sstever@eecs.umich.edu            print "Error: build targets not under same build root\n"\
3526121Snate@binkert.org                  "  %s\n  %s" % (build_root, this_build_root)
3532667Sstever@eecs.umich.edu            Exit(1)
3545341Sstever@gmail.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
3555863Snate@binkert.org    if variant_path not in variant_paths:
3565341Sstever@gmail.com        variant_paths.append(variant_path)
3575341Sstever@gmail.com
3585341Sstever@gmail.com# Make sure build_root exists (might not if this is the first build there)
3598120Sgblack@eecs.umich.eduif not isdir(build_root):
3605341Sstever@gmail.com    mkdir(build_root)
3618120Sgblack@eecs.umich.edumain['BUILDROOT'] = build_root
3625341Sstever@gmail.com
3638120Sgblack@eecs.umich.eduExport('main')
3646121Snate@binkert.org
3656121Snate@binkert.orgmain.SConsignFile(joinpath(build_root, "sconsign"))
3668980Ssteve.reinhardt@amd.com
3679396Sandreas.hansson@arm.com# Default duplicate option is to use hard links, but this messes up
3685397Ssaidi@eecs.umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
3695397Ssaidi@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
3707727SAli.Saidi@ARM.com# (soft) links work better.
3718268Ssteve.reinhardt@amd.commain.SetOption('duplicate', 'soft-copy')
3726168Snate@binkert.org
3735341Sstever@gmail.com#
3748120Sgblack@eecs.umich.edu# Set up global sticky variables... these are common to an entire build
3758120Sgblack@eecs.umich.edu# tree (not specific to a particular build like ALPHA_SE)
3768120Sgblack@eecs.umich.edu#
3776814Sgblack@eecs.umich.edu
3785863Snate@binkert.orgglobal_vars_file = joinpath(build_root, 'variables.global')
3798120Sgblack@eecs.umich.edu
3805341Sstever@gmail.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3815863Snate@binkert.org
3828268Ssteve.reinhardt@amd.comglobal_vars.AddVariables(
3836121Snate@binkert.org    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3846121Snate@binkert.org    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3858268Ssteve.reinhardt@amd.com    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
3865742Snate@binkert.org    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
3875742Snate@binkert.org    ('BATCH', 'Use batch pool for build and tests', False),
3885341Sstever@gmail.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3895742Snate@binkert.org    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
3905742Snate@binkert.org    ('EXTRAS', 'Add extra directories to the compilation', '')
3915341Sstever@gmail.com    )
3926017Snate@binkert.org
3936121Snate@binkert.org# Update main environment with values from ARGUMENTS & global_vars_file
3946017Snate@binkert.orgglobal_vars.Update(main)
3957816Ssteve.reinhardt@amd.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3967756SAli.Saidi@ARM.com
3977756SAli.Saidi@ARM.com# Save sticky variable settings back to current variables file
3987756SAli.Saidi@ARM.comglobal_vars.Save(global_vars_file, main)
3997756SAli.Saidi@ARM.com
4007756SAli.Saidi@ARM.com# Parse EXTRAS variable to build list of all directories where we're
4017756SAli.Saidi@ARM.com# look for sources etc.  This list is exported as extras_dir_list.
4027756SAli.Saidi@ARM.combase_dir = main.srcdir.abspath
4037756SAli.Saidi@ARM.comif main['EXTRAS']:
4047816Ssteve.reinhardt@amd.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
4057816Ssteve.reinhardt@amd.comelse:
4067816Ssteve.reinhardt@amd.com    extras_dir_list = []
4077816Ssteve.reinhardt@amd.com
4087816Ssteve.reinhardt@amd.comExport('base_dir')
4097816Ssteve.reinhardt@amd.comExport('extras_dir_list')
4107816Ssteve.reinhardt@amd.com
4117816Ssteve.reinhardt@amd.com# the ext directory should be on the #includes path
4127816Ssteve.reinhardt@amd.commain.Append(CPPPATH=[Dir('ext')])
4137816Ssteve.reinhardt@amd.com
4147756SAli.Saidi@ARM.comdef strip_build_path(path, env):
4157816Ssteve.reinhardt@amd.com    path = str(path)
4167816Ssteve.reinhardt@amd.com    variant_base = env['BUILDROOT'] + os.path.sep
4177816Ssteve.reinhardt@amd.com    if path.startswith(variant_base):
4187816Ssteve.reinhardt@amd.com        path = path[len(variant_base):]
4197816Ssteve.reinhardt@amd.com    elif path.startswith('build/'):
4207816Ssteve.reinhardt@amd.com        path = path[6:]
4217816Ssteve.reinhardt@amd.com    return path
4227816Ssteve.reinhardt@amd.com
4237816Ssteve.reinhardt@amd.com# Generate a string of the form:
4247816Ssteve.reinhardt@amd.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
4257816Ssteve.reinhardt@amd.com# to print while building.
4267816Ssteve.reinhardt@amd.comclass Transform(object):
4277816Ssteve.reinhardt@amd.com    # all specific color settings should be here and nowhere else
4287816Ssteve.reinhardt@amd.com    tool_color = termcap.Normal
4297816Ssteve.reinhardt@amd.com    pfx_color = termcap.Yellow
4307816Ssteve.reinhardt@amd.com    srcs_color = termcap.Yellow + termcap.Bold
4317816Ssteve.reinhardt@amd.com    arrow_color = termcap.Blue + termcap.Bold
4327816Ssteve.reinhardt@amd.com    tgts_color = termcap.Yellow + termcap.Bold
4337816Ssteve.reinhardt@amd.com
4347816Ssteve.reinhardt@amd.com    def __init__(self, tool, max_sources=99):
4357816Ssteve.reinhardt@amd.com        self.format = self.tool_color + (" [%8s] " % tool) \
4367816Ssteve.reinhardt@amd.com                      + self.pfx_color + "%s" \
4377816Ssteve.reinhardt@amd.com                      + self.srcs_color + "%s" \
4387816Ssteve.reinhardt@amd.com                      + self.arrow_color + " -> " \
4397816Ssteve.reinhardt@amd.com                      + self.tgts_color + "%s" \
4407816Ssteve.reinhardt@amd.com                      + termcap.Normal
4417816Ssteve.reinhardt@amd.com        self.max_sources = max_sources
4427816Ssteve.reinhardt@amd.com
4437816Ssteve.reinhardt@amd.com    def __call__(self, target, source, env, for_signature=None):
4447816Ssteve.reinhardt@amd.com        # truncate source list according to max_sources param
4457816Ssteve.reinhardt@amd.com        source = source[0:self.max_sources]
4467816Ssteve.reinhardt@amd.com        def strip(f):
4477816Ssteve.reinhardt@amd.com            return strip_build_path(str(f), env)
4487816Ssteve.reinhardt@amd.com        if len(source) > 0:
4497816Ssteve.reinhardt@amd.com            srcs = map(strip, source)
4507816Ssteve.reinhardt@amd.com        else:
4517816Ssteve.reinhardt@amd.com            srcs = ['']
4527816Ssteve.reinhardt@amd.com        tgts = map(strip, target)
4537816Ssteve.reinhardt@amd.com        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4547816Ssteve.reinhardt@amd.com        # operation that has nothing to do with paths.
4557816Ssteve.reinhardt@amd.com        com_pfx = os.path.commonprefix(srcs + tgts)
4567816Ssteve.reinhardt@amd.com        com_pfx_len = len(com_pfx)
4577816Ssteve.reinhardt@amd.com        if com_pfx:
4587816Ssteve.reinhardt@amd.com            # do some cleanup and sanity checking on common prefix
4597816Ssteve.reinhardt@amd.com            if com_pfx[-1] == ".":
4607816Ssteve.reinhardt@amd.com                # prefix matches all but file extension: ok
4617816Ssteve.reinhardt@amd.com                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4627816Ssteve.reinhardt@amd.com                com_pfx = com_pfx[0:-1]
4637816Ssteve.reinhardt@amd.com            elif com_pfx[-1] == "/":
4647816Ssteve.reinhardt@amd.com                # common prefix is directory path: OK
4657816Ssteve.reinhardt@amd.com                pass
4667816Ssteve.reinhardt@amd.com            else:
4677816Ssteve.reinhardt@amd.com                src0_len = len(srcs[0])
4687816Ssteve.reinhardt@amd.com                tgt0_len = len(tgts[0])
4697816Ssteve.reinhardt@amd.com                if src0_len == com_pfx_len:
4707816Ssteve.reinhardt@amd.com                    # source is a substring of target, OK
4717816Ssteve.reinhardt@amd.com                    pass
4727816Ssteve.reinhardt@amd.com                elif tgt0_len == com_pfx_len:
4737816Ssteve.reinhardt@amd.com                    # target is a substring of source, need to back up to
4747816Ssteve.reinhardt@amd.com                    # avoid empty string on RHS of arrow
4757816Ssteve.reinhardt@amd.com                    sep_idx = com_pfx.rfind(".")
4768947Sandreas.hansson@arm.com                    if sep_idx != -1:
4778947Sandreas.hansson@arm.com                        com_pfx = com_pfx[0:sep_idx]
4787756SAli.Saidi@ARM.com                    else:
4798120Sgblack@eecs.umich.edu                        com_pfx = ''
4807756SAli.Saidi@ARM.com                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4817756SAli.Saidi@ARM.com                    # still splitting at file extension: ok
4827756SAli.Saidi@ARM.com                    pass
4837756SAli.Saidi@ARM.com                else:
4847816Ssteve.reinhardt@amd.com                    # probably a fluke; ignore it
4857816Ssteve.reinhardt@amd.com                    com_pfx = ''
4867816Ssteve.reinhardt@amd.com        # recalculate length in case com_pfx was modified
4877816Ssteve.reinhardt@amd.com        com_pfx_len = len(com_pfx)
4887816Ssteve.reinhardt@amd.com        def fmt(files):
4897816Ssteve.reinhardt@amd.com            f = map(lambda s: s[com_pfx_len:], files)
4907816Ssteve.reinhardt@amd.com            return ', '.join(f)
4917816Ssteve.reinhardt@amd.com        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
4927816Ssteve.reinhardt@amd.com
4937816Ssteve.reinhardt@amd.comExport('Transform')
4947756SAli.Saidi@ARM.com
4957756SAli.Saidi@ARM.com# enable the regression script to use the termcap
4969227Sandreas.hansson@arm.commain['TERMCAP'] = termcap
4979227Sandreas.hansson@arm.com
4989227Sandreas.hansson@arm.comif GetOption('verbose'):
4999227Sandreas.hansson@arm.com    def MakeAction(action, string, *args, **kwargs):
5006654Snate@binkert.org        return Action(action, *args, **kwargs)
5016654Snate@binkert.orgelse:
5025871Snate@binkert.org    MakeAction = Action
5036121Snate@binkert.org    main['CCCOMSTR']        = Transform("CC")
5046121Snate@binkert.org    main['CXXCOMSTR']       = Transform("CXX")
5056121Snate@binkert.org    main['ASCOMSTR']        = Transform("AS")
5068946Sandreas.hansson@arm.com    main['SWIGCOMSTR']      = Transform("SWIG")
5078737Skoansin.tan@gmail.com    main['ARCOMSTR']        = Transform("AR", 0)
5083940Ssaidi@eecs.umich.edu    main['LINKCOMSTR']      = Transform("LINK", 0)
5093918Ssaidi@eecs.umich.edu    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
5103918Ssaidi@eecs.umich.edu    main['M4COMSTR']        = Transform("M4")
5111858SN/A    main['SHCCCOMSTR']      = Transform("SHCC")
5126121Snate@binkert.org    main['SHCXXCOMSTR']     = Transform("SHCXX")
5137739Sgblack@eecs.umich.eduExport('MakeAction')
5147739Sgblack@eecs.umich.edu
5156143Snate@binkert.org# Initialize the Link-Time Optimization (LTO) flags
5167618SAli.Saidi@arm.commain['LTO_CCFLAGS'] = []
5177618SAli.Saidi@arm.commain['LTO_LDFLAGS'] = []
5187618SAli.Saidi@arm.com
5197618SAli.Saidi@arm.com# According to the readme, tcmalloc works best if the compiler doesn't
5208614Sgblack@eecs.umich.edu# assume that we're using the builtin malloc and friends. These flags
5217618SAli.Saidi@arm.com# are compiler-specific, so we need to set them after we detect which
5227618SAli.Saidi@arm.com# compiler we're using.
5237618SAli.Saidi@arm.commain['TCMALLOC_CCFLAGS'] = []
5247739Sgblack@eecs.umich.edu
5259224Sandreas.hansson@arm.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5269224Sandreas.hansson@arm.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5279224Sandreas.hansson@arm.com
5288946Sandreas.hansson@arm.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5299227Sandreas.hansson@arm.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5309227Sandreas.hansson@arm.comif main['GCC'] + main['CLANG'] > 1:
5319227Sandreas.hansson@arm.com    print 'Error: How can we have two at the same time?'
5329227Sandreas.hansson@arm.com    Exit(1)
5339227Sandreas.hansson@arm.com
5349227Sandreas.hansson@arm.com# Set up default C++ compiler flags
5359227Sandreas.hansson@arm.comif main['GCC'] or main['CLANG']:
5369227Sandreas.hansson@arm.com    # As gcc and clang share many flags, do the common parts here
5379227Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-pipe'])
5389227Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5399227Sandreas.hansson@arm.com    # Enable -Wall and then disable the few warnings that we
5409227Sandreas.hansson@arm.com    # consistently violate
5419227Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5429227Sandreas.hansson@arm.com    # We always compile using C++11, but only gcc >= 4.7 and clang 3.1
5439227Sandreas.hansson@arm.com    # actually use that name, so we stick with c++0x
5449227Sandreas.hansson@arm.com    main.Append(CXXFLAGS=['-std=c++0x'])
5459227Sandreas.hansson@arm.com    # Add selected sanity checks from -Wextra
5469227Sandreas.hansson@arm.com    main.Append(CXXFLAGS=['-Wmissing-field-initializers',
5476121Snate@binkert.org                          '-Woverloaded-virtual'])
5483940Ssaidi@eecs.umich.eduelse:
5496121Snate@binkert.org    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5507739Sgblack@eecs.umich.edu    print "Don't know what compiler options to use for your compiler."
5517739Sgblack@eecs.umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5527739Sgblack@eecs.umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
5537739Sgblack@eecs.umich.edu    if not CXX_version:
5547739Sgblack@eecs.umich.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5557739Sgblack@eecs.umich.edu               termcap.Normal
5568737Skoansin.tan@gmail.com    else:
5578737Skoansin.tan@gmail.com        print CXX_version.replace('\n', '<nl>')
5588737Skoansin.tan@gmail.com    print "       If you're trying to use a compiler other than GCC"
5598737Skoansin.tan@gmail.com    print "       or clang, there appears to be something wrong with your"
5608737Skoansin.tan@gmail.com    print "       environment."
5618737Skoansin.tan@gmail.com    print "       "
5628737Skoansin.tan@gmail.com    print "       If you are trying to use a compiler other than those listed"
5638737Skoansin.tan@gmail.com    print "       above you will need to ease fix SConstruct and "
5648737Skoansin.tan@gmail.com    print "       src/SConscript to support that compiler."
5658737Skoansin.tan@gmail.com    Exit(1)
5668737Skoansin.tan@gmail.com
5678737Skoansin.tan@gmail.comif main['GCC']:
5688737Skoansin.tan@gmail.com    # Check for a supported version of gcc, >= 4.4 is needed for c++0x
5698737Skoansin.tan@gmail.com    # support. See http://gcc.gnu.org/projects/cxx0x.html for details
5708737Skoansin.tan@gmail.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5718737Skoansin.tan@gmail.com    if compareVersions(gcc_version, "4.4") < 0:
5728737Skoansin.tan@gmail.com        print 'Error: gcc version 4.4 or newer required.'
5738737Skoansin.tan@gmail.com        print '       Installed version:', gcc_version
5748946Sandreas.hansson@arm.com        Exit(1)
5758946Sandreas.hansson@arm.com
5768946Sandreas.hansson@arm.com    main['GCC_VERSION'] = gcc_version
5778946Sandreas.hansson@arm.com
5789224Sandreas.hansson@arm.com    # Check for versions with bugs
5799224Sandreas.hansson@arm.com    if not compareVersions(gcc_version, '4.4.1') or \
5808946Sandreas.hansson@arm.com       not compareVersions(gcc_version, '4.4.2'):
5818946Sandreas.hansson@arm.com        print 'Info: Tree vectorizer in GCC 4.4.1 & 4.4.2 is buggy, disabling.'
5823918Ssaidi@eecs.umich.edu        main.Append(CCFLAGS=['-fno-tree-vectorize'])
5839068SAli.Saidi@ARM.com
5849068SAli.Saidi@ARM.com    # LTO support is only really working properly from 4.6 and beyond
5859068SAli.Saidi@ARM.com    if compareVersions(gcc_version, '4.6') >= 0:
5869068SAli.Saidi@ARM.com        # Add the appropriate Link-Time Optimization (LTO) flags
5879068SAli.Saidi@ARM.com        # unless LTO is explicitly turned off. Note that these flags
5889068SAli.Saidi@ARM.com        # are only used by the fast target.
5899068SAli.Saidi@ARM.com        if not GetOption('no_lto'):
5909068SAli.Saidi@ARM.com            # Pass the LTO flag when compiling to produce GIMPLE
5919068SAli.Saidi@ARM.com            # output, we merely create the flags here and only append
5929068SAli.Saidi@ARM.com            # them later/
5939068SAli.Saidi@ARM.com            main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
5949068SAli.Saidi@ARM.com
5959068SAli.Saidi@ARM.com            # Use the same amount of jobs for LTO as we are running
5969068SAli.Saidi@ARM.com            # scons with, we hardcode the use of the linker plugin
5979068SAli.Saidi@ARM.com            # which requires either gold or GNU ld >= 2.21
5989068SAli.Saidi@ARM.com            main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs'),
5993918Ssaidi@eecs.umich.edu                                   '-fuse-linker-plugin']
6003918Ssaidi@eecs.umich.edu
6016157Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
6026157Snate@binkert.org                                  '-fno-builtin-realloc', '-fno-builtin-free'])
6036157Snate@binkert.org
6046157Snate@binkert.orgelif main['CLANG']:
6055397Ssaidi@eecs.umich.edu    # Check for a supported version of clang, >= 2.9 is needed to
6065397Ssaidi@eecs.umich.edu    # support similar features as gcc 4.4. See
6076121Snate@binkert.org    # http://clang.llvm.org/cxx_status.html for details
6086121Snate@binkert.org    clang_version_re = re.compile(".* version (\d+\.\d+)")
6096121Snate@binkert.org    clang_version_match = clang_version_re.match(CXX_version)
6106121Snate@binkert.org    if (clang_version_match):
6116121Snate@binkert.org        clang_version = clang_version_match.groups()[0]
6126121Snate@binkert.org        if compareVersions(clang_version, "2.9") < 0:
6135397Ssaidi@eecs.umich.edu            print 'Error: clang version 2.9 or newer required.'
6141851SN/A            print '       Installed version:', clang_version
6151851SN/A            Exit(1)
6167739Sgblack@eecs.umich.edu    else:
617955SN/A        print 'Error: Unable to determine clang version.'
6189396Sandreas.hansson@arm.com        Exit(1)
6199396Sandreas.hansson@arm.com
6209396Sandreas.hansson@arm.com    # clang has a few additional warnings that we disable,
6219396Sandreas.hansson@arm.com    # tautological comparisons are allowed due to unsigned integers
6229396Sandreas.hansson@arm.com    # being compared to constants that happen to be 0, and extraneous
6239396Sandreas.hansson@arm.com    # parantheses are allowed due to Ruby's printing of the AST,
6249396Sandreas.hansson@arm.com    # finally self assignments are allowed as the generated CPU code
6259396Sandreas.hansson@arm.com    # is relying on this
6269396Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-Wno-tautological-compare',
6279396Sandreas.hansson@arm.com                         '-Wno-parentheses',
6289396Sandreas.hansson@arm.com                         '-Wno-self-assign'])
6299396Sandreas.hansson@arm.com
6309396Sandreas.hansson@arm.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
6319396Sandreas.hansson@arm.com
6329396Sandreas.hansson@arm.com    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
6339396Sandreas.hansson@arm.com    # opposed to libstdc++ to make the transition from TR1 to
6349396Sandreas.hansson@arm.com    # C++11. See http://libcxx.llvm.org. However, clang has chosen a
6359396Sandreas.hansson@arm.com    # strict implementation of the C++11 standard, and does not allow
6369396Sandreas.hansson@arm.com    # incomplete types in template arguments (besides unique_ptr and
6379396Sandreas.hansson@arm.com    # shared_ptr), and the libc++ STL containers create problems in
6389396Sandreas.hansson@arm.com    # combination with the current gem5 code. For now, we stick with
6399396Sandreas.hansson@arm.com    # libstdc++ and use the TR1 namespace.
6409396Sandreas.hansson@arm.com    # if sys.platform == "darwin":
6419396Sandreas.hansson@arm.com    #     main.Append(CXXFLAGS=['-stdlib=libc++'])
6429396Sandreas.hansson@arm.com
6439396Sandreas.hansson@arm.comelse:
6449396Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6459396Sandreas.hansson@arm.com    print "Don't know what compiler options to use for your compiler."
6463053Sstever@eecs.umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6476121Snate@binkert.org    print termcap.Yellow + '       version:' + termcap.Normal,
6483053Sstever@eecs.umich.edu    if not CXX_version:
6493053Sstever@eecs.umich.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6503053Sstever@eecs.umich.edu               termcap.Normal
6513053Sstever@eecs.umich.edu    else:
6523053Sstever@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
6539072Sandreas.hansson@arm.com    print "       If you're trying to use a compiler other than GCC"
6543053Sstever@eecs.umich.edu    print "       or clang, there appears to be something wrong with your"
6554742Sstever@eecs.umich.edu    print "       environment."
6564742Sstever@eecs.umich.edu    print "       "
6573053Sstever@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
6583053Sstever@eecs.umich.edu    print "       above you will need to ease fix SConstruct and "
6593053Sstever@eecs.umich.edu    print "       src/SConscript to support that compiler."
6608960Ssteve.reinhardt@amd.com    Exit(1)
6616654Snate@binkert.org
6623053Sstever@eecs.umich.edu# Set up common yacc/bison flags (needed for Ruby)
6633053Sstever@eecs.umich.edumain['YACCFLAGS'] = '-d'
6643053Sstever@eecs.umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
6653053Sstever@eecs.umich.edu
6662667Sstever@eecs.umich.edu# Do this after we save setting back, or else we'll tack on an
6674554Sbinkertn@umich.edu# extra 'qdo' every time we run scons.
6686121Snate@binkert.orgif main['BATCH']:
6692667Sstever@eecs.umich.edu    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
6704554Sbinkertn@umich.edu    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
6714554Sbinkertn@umich.edu    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
6724554Sbinkertn@umich.edu    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
6736121Snate@binkert.org    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
6744554Sbinkertn@umich.edu
6754554Sbinkertn@umich.eduif sys.platform == 'cygwin':
6764554Sbinkertn@umich.edu    # cygwin has some header file issues...
6774781Snate@binkert.org    main.Append(CCFLAGS=["-Wno-uninitialized"])
6784554Sbinkertn@umich.edu
6794554Sbinkertn@umich.edu# Check for the protobuf compiler
6802667Sstever@eecs.umich.eduprotoc_version = readCommand([main['PROTOC'], '--version'],
6814554Sbinkertn@umich.edu                             exception='').split()
6824554Sbinkertn@umich.edu
6834554Sbinkertn@umich.edu# First two words should be "libprotoc x.y.z"
6844554Sbinkertn@umich.eduif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6852667Sstever@eecs.umich.edu    print termcap.Yellow + termcap.Bold + \
6864554Sbinkertn@umich.edu        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
6872667Sstever@eecs.umich.edu        '         Please install protobuf-compiler for tracing support.' + \
6884554Sbinkertn@umich.edu        termcap.Normal
6896121Snate@binkert.org    main['PROTOC'] = False
6902667Sstever@eecs.umich.eduelse:
6915522Snate@binkert.org    # Based on the availability of the compress stream wrappers,
6925522Snate@binkert.org    # require 2.1.0
6935522Snate@binkert.org    min_protoc_version = '2.1.0'
6945522Snate@binkert.org    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6955522Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
6965522Snate@binkert.org            'Warning: protoc version', min_protoc_version, \
6975522Snate@binkert.org            'or newer required.\n' + \
6985522Snate@binkert.org            '         Installed version:', protoc_version[1], \
6995522Snate@binkert.org            termcap.Normal
7005522Snate@binkert.org        main['PROTOC'] = False
7015522Snate@binkert.org    else:
7025522Snate@binkert.org        # Attempt to determine the appropriate include path and
7035522Snate@binkert.org        # library path using pkg-config, that means we also need to
7045522Snate@binkert.org        # check for pkg-config. Note that it is possible to use
7055522Snate@binkert.org        # protobuf without the involvement of pkg-config. Later on we
7065522Snate@binkert.org        # check go a library config check and at that point the test
7075522Snate@binkert.org        # will fail if libprotobuf cannot be found.
7085522Snate@binkert.org        if readCommand(['pkg-config', '--version'], exception=''):
7095522Snate@binkert.org            try:
7105522Snate@binkert.org                # Attempt to establish what linking flags to add for protobuf
7115522Snate@binkert.org                # using pkg-config
7125522Snate@binkert.org                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
7135522Snate@binkert.org            except:
7145522Snate@binkert.org                print termcap.Yellow + termcap.Bold + \
7155522Snate@binkert.org                    'Warning: pkg-config could not get protobuf flags.' + \
7165522Snate@binkert.org                    termcap.Normal
7179255SAndreas.Sandberg@arm.com
7189255SAndreas.Sandberg@arm.com# Check for SWIG
7199255SAndreas.Sandberg@arm.comif not main.has_key('SWIG'):
7209255SAndreas.Sandberg@arm.com    print 'Error: SWIG utility not found.'
7219255SAndreas.Sandberg@arm.com    print '       Please install (see http://www.swig.org) and retry.'
7229255SAndreas.Sandberg@arm.com    Exit(1)
7239255SAndreas.Sandberg@arm.com
7249255SAndreas.Sandberg@arm.com# Check for appropriate SWIG version
7259255SAndreas.Sandberg@arm.comswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
7269255SAndreas.Sandberg@arm.com# First 3 words should be "SWIG Version x.y.z"
7279255SAndreas.Sandberg@arm.comif len(swig_version) < 3 or \
7289255SAndreas.Sandberg@arm.com        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
7292638Sstever@eecs.umich.edu    print 'Error determining SWIG version.'
7302638Sstever@eecs.umich.edu    Exit(1)
7316121Snate@binkert.org
7323716Sstever@eecs.umich.edumin_swig_version = '1.3.34'
7335522Snate@binkert.orgif compareVersions(swig_version[2], min_swig_version) < 0:
7349255SAndreas.Sandberg@arm.com    print 'Error: SWIG version', min_swig_version, 'or newer required.'
7359255SAndreas.Sandberg@arm.com    print '       Installed version:', swig_version[2]
7369255SAndreas.Sandberg@arm.com    Exit(1)
7375522Snate@binkert.org
7385522Snate@binkert.orgif swig_version[2] in ["2.0.9", "2.0.10"]:
7395522Snate@binkert.org    print '\n' + termcap.Yellow + termcap.Bold + \
7405522Snate@binkert.org        'Warning: SWIG version 2.0.9/10 sometimes generates broken code.\n' + \
7411858SN/A        termcap.Normal + \
7429255SAndreas.Sandberg@arm.com        'This problem only affects some platforms and some Python\n' + \
7439255SAndreas.Sandberg@arm.com        'versions. See the following SWIG bug report for details:\n' + \
7449255SAndreas.Sandberg@arm.com        'http://sourceforge.net/p/swig/bugs/1297/\n'
7455227Ssaidi@eecs.umich.edu
7465227Ssaidi@eecs.umich.edu
7475227Ssaidi@eecs.umich.edu# Set up SWIG flags & scanner
7485227Ssaidi@eecs.umich.eduswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
7496654Snate@binkert.orgmain.Append(SWIGFLAGS=swig_flags)
7506654Snate@binkert.org
7517769SAli.Saidi@ARM.com# filter out all existing swig scanners, they mess up the dependency
7527769SAli.Saidi@ARM.com# stuff for some reason
7537769SAli.Saidi@ARM.comscanners = []
7547769SAli.Saidi@ARM.comfor scanner in main['SCANNERS']:
7555227Ssaidi@eecs.umich.edu    skeys = scanner.skeys
7565227Ssaidi@eecs.umich.edu    if skeys == '.i':
7575227Ssaidi@eecs.umich.edu        continue
7585204Sstever@gmail.com
7595204Sstever@gmail.com    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
7605204Sstever@gmail.com        continue
7615204Sstever@gmail.com
7625204Sstever@gmail.com    scanners.append(scanner)
7635204Sstever@gmail.com
7645204Sstever@gmail.com# add the new swig scanner that we like better
7655204Sstever@gmail.comfrom SCons.Scanner import ClassicCPP as CPPScanner
7665204Sstever@gmail.comswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
7675204Sstever@gmail.comscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
7685204Sstever@gmail.com
7695204Sstever@gmail.com# replace the scanners list that has what we want
7705204Sstever@gmail.commain['SCANNERS'] = scanners
7715204Sstever@gmail.com
7725204Sstever@gmail.com# Add a custom Check function to the Configure context so that we can
7735204Sstever@gmail.com# figure out if the compiler adds leading underscores to global
7745204Sstever@gmail.com# variables.  This is needed for the autogenerated asm files that we
7756121Snate@binkert.org# use for embedding the python code.
7765204Sstever@gmail.comdef CheckLeading(context):
7773118Sstever@eecs.umich.edu    context.Message("Checking for leading underscore in global variables...")
7783118Sstever@eecs.umich.edu    # 1) Define a global variable called x from asm so the C compiler
7793118Sstever@eecs.umich.edu    #    won't change the symbol at all.
7803118Sstever@eecs.umich.edu    # 2) Declare that variable.
7813118Sstever@eecs.umich.edu    # 3) Use the variable
7825863Snate@binkert.org    #
7833118Sstever@eecs.umich.edu    # If the compiler prepends an underscore, this will successfully
7845863Snate@binkert.org    # link because the external symbol 'x' will be called '_x' which
7853118Sstever@eecs.umich.edu    # was defined by the asm statement.  If the compiler does not
7867457Snate@binkert.org    # prepend an underscore, this will not successfully link because
7877457Snate@binkert.org    # '_x' will have been defined by assembly, while the C portion of
7885863Snate@binkert.org    # the code will be trying to use 'x'
7895863Snate@binkert.org    ret = context.TryLink('''
7905863Snate@binkert.org        asm(".globl _x; _x: .byte 0");
7915863Snate@binkert.org        extern int x;
7925863Snate@binkert.org        int main() { return x; }
7935863Snate@binkert.org        ''', extension=".c")
7945863Snate@binkert.org    context.env.Append(LEADING_UNDERSCORE=ret)
7956003Snate@binkert.org    context.Result(ret)
7965863Snate@binkert.org    return ret
7975863Snate@binkert.org
7985863Snate@binkert.org# Platform-specific configuration.  Note again that we assume that all
7996120Snate@binkert.org# builds under a given build root run on the same host platform.
8005863Snate@binkert.orgconf = Configure(main,
8015863Snate@binkert.org                 conf_dir = joinpath(build_root, '.scons_config'),
8025863Snate@binkert.org                 log_file = joinpath(build_root, 'scons_config.log'),
8038655Sandreas.hansson@arm.com                 custom_tests = { 'CheckLeading' : CheckLeading })
8048655Sandreas.hansson@arm.com
8058655Sandreas.hansson@arm.com# Check for leading underscores.  Don't really need to worry either
8068655Sandreas.hansson@arm.com# way so don't need to check the return code.
8078655Sandreas.hansson@arm.comconf.CheckLeading()
8088655Sandreas.hansson@arm.com
8098655Sandreas.hansson@arm.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
8108655Sandreas.hansson@arm.comtry:
8116120Snate@binkert.org    import platform
8125863Snate@binkert.org    uname = platform.uname()
8136121Snate@binkert.org    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
8146121Snate@binkert.org        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
8155863Snate@binkert.org            main.Append(CCFLAGS=['-arch', 'x86_64'])
8167727SAli.Saidi@ARM.com            main.Append(CFLAGS=['-arch', 'x86_64'])
8177727SAli.Saidi@ARM.com            main.Append(LINKFLAGS=['-arch', 'x86_64'])
8187727SAli.Saidi@ARM.com            main.Append(ASFLAGS=['-arch', 'x86_64'])
8197727SAli.Saidi@ARM.comexcept:
8207727SAli.Saidi@ARM.com    pass
8217727SAli.Saidi@ARM.com
8225863Snate@binkert.org# Recent versions of scons substitute a "Null" object for Configure()
8233118Sstever@eecs.umich.edu# when configuration isn't necessary, e.g., if the "--help" option is
8245863Snate@binkert.org# present.  Unfortuantely this Null object always returns false,
8259239Sandreas.hansson@arm.com# breaking all our configuration checks.  We replace it with our own
8263118Sstever@eecs.umich.edu# more optimistic null object that returns True instead.
8273118Sstever@eecs.umich.eduif not conf:
8285863Snate@binkert.org    def NullCheck(*args, **kwargs):
8295863Snate@binkert.org        return True
8305863Snate@binkert.org
8315863Snate@binkert.org    class NullConf:
8323118Sstever@eecs.umich.edu        def __init__(self, env):
8333483Ssaidi@eecs.umich.edu            self.env = env
8343494Ssaidi@eecs.umich.edu        def Finish(self):
8353494Ssaidi@eecs.umich.edu            return self.env
8363483Ssaidi@eecs.umich.edu        def __getattr__(self, mname):
8373483Ssaidi@eecs.umich.edu            return NullCheck
8383483Ssaidi@eecs.umich.edu
8393053Sstever@eecs.umich.edu    conf = NullConf(main)
8403053Sstever@eecs.umich.edu
8413918Ssaidi@eecs.umich.edu# Cache build files in the supplied directory.
8423053Sstever@eecs.umich.eduif main['M5_BUILD_CACHE']:
8433053Sstever@eecs.umich.edu    print 'Using build cache located at', main['M5_BUILD_CACHE']
8443053Sstever@eecs.umich.edu    CacheDir(main['M5_BUILD_CACHE'])
8453053Sstever@eecs.umich.edu
8463053Sstever@eecs.umich.edu# Find Python include and library directories for embedding the
8479396Sandreas.hansson@arm.com# interpreter. We rely on python-config to resolve the appropriate
8489396Sandreas.hansson@arm.com# includes and linker flags. ParseConfig does not seem to understand
8499396Sandreas.hansson@arm.com# the more exotic linker flags such as -Xlinker and -export-dynamic so
8509396Sandreas.hansson@arm.com# we add them explicitly below. If you want to link in an alternate
8519396Sandreas.hansson@arm.com# version of python, see above for instructions on how to invoke
8529396Sandreas.hansson@arm.com# scons with the appropriate PATH set.
8539396Sandreas.hansson@arm.compy_includes = readCommand(['python-config', '--includes'],
8549396Sandreas.hansson@arm.com                          exception='').split()
8559396Sandreas.hansson@arm.com# Strip the -I from the include folders before adding them to the
8569396Sandreas.hansson@arm.com# CPPPATH
8579396Sandreas.hansson@arm.commain.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
8589396Sandreas.hansson@arm.com
8599396Sandreas.hansson@arm.com# Read the linker flags and split them into libraries and other link
8609396Sandreas.hansson@arm.com# flags. The libraries are added later through the call the CheckLib.
8619396Sandreas.hansson@arm.compy_ld_flags = readCommand(['python-config', '--ldflags'], exception='').split()
8627840Snate@binkert.orgpy_libs = []
8637865Sgblack@eecs.umich.edufor lib in py_ld_flags:
8647865Sgblack@eecs.umich.edu     if not lib.startswith('-l'):
8657865Sgblack@eecs.umich.edu         main.Append(LINKFLAGS=[lib])
8667865Sgblack@eecs.umich.edu     else:
8677865Sgblack@eecs.umich.edu         lib = lib[2:]
8687840Snate@binkert.org         if lib not in py_libs:
8699045SAli.Saidi@ARM.com             py_libs.append(lib)
8709045SAli.Saidi@ARM.com
8719045SAli.Saidi@ARM.com# verify that this stuff works
8729045SAli.Saidi@ARM.comif not conf.CheckHeader('Python.h', '<>'):
8739045SAli.Saidi@ARM.com    print "Error: can't find Python.h header in", py_includes
8749045SAli.Saidi@ARM.com    print "Install Python headers (package python-dev on Ubuntu and RedHat)"
8759071Sandreas.hansson@arm.com    Exit(1)
8769071Sandreas.hansson@arm.com
8779045SAli.Saidi@ARM.comfor lib in py_libs:
8787840Snate@binkert.org    if not conf.CheckLib(lib):
8797840Snate@binkert.org        print "Error: can't find library %s required by python" % lib
8807840Snate@binkert.org        Exit(1)
8811858SN/A
8821858SN/A# On Solaris you need to use libsocket for socket ops
8831858SN/Aif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
8841858SN/A   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
8851858SN/A       print "Can't find library with socket calls (e.g. accept())"
8861858SN/A       Exit(1)
8875863Snate@binkert.org
8885863Snate@binkert.org# Check for zlib.  If the check passes, libz will be automatically
8895863Snate@binkert.org# added to the LIBS environment variable.
8905863Snate@binkert.orgif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
8916121Snate@binkert.org    print 'Error: did not find needed zlib compression library '\
8921858SN/A          'and/or zlib.h header file.'
8935863Snate@binkert.org    print '       Please install zlib and try again.'
8945863Snate@binkert.org    Exit(1)
8955863Snate@binkert.org
8965863Snate@binkert.org# If we have the protobuf compiler, also make sure we have the
8975863Snate@binkert.org# development libraries. If the check passes, libprotobuf will be
8982139SN/A# automatically added to the LIBS environment variable. After
8994202Sbinkertn@umich.edu# this, we can use the HAVE_PROTOBUF flag to determine if we have
9004202Sbinkertn@umich.edu# got both protoc and libprotobuf available.
9012139SN/Amain['HAVE_PROTOBUF'] = main['PROTOC'] and \
9026994Snate@binkert.org    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
9036994Snate@binkert.org                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
9046994Snate@binkert.org
9056994Snate@binkert.org# If we have the compiler but not the library, print another warning.
9066994Snate@binkert.orgif main['PROTOC'] and not main['HAVE_PROTOBUF']:
9076994Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
9086994Snate@binkert.org        'Warning: did not find protocol buffer library and/or headers.\n' + \
9096994Snate@binkert.org    '       Please install libprotobuf-dev for tracing support.' + \
9106994Snate@binkert.org    termcap.Normal
9116994Snate@binkert.org
9126994Snate@binkert.org# Check for librt.
9136994Snate@binkert.orghave_posix_clock = \
9146994Snate@binkert.org    conf.CheckLibWithHeader(None, 'time.h', 'C',
9156994Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);') or \
9166994Snate@binkert.org    conf.CheckLibWithHeader('rt', 'time.h', 'C',
9176994Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);')
9186994Snate@binkert.org
9196994Snate@binkert.orgif conf.CheckLib('tcmalloc'):
9206994Snate@binkert.org    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
9216994Snate@binkert.orgelif conf.CheckLib('tcmalloc_minimal'):
9226994Snate@binkert.org    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
9236994Snate@binkert.orgelse:
9246994Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
9256994Snate@binkert.org          "You can get a 12% performance improvement by installing tcmalloc "\
9266994Snate@binkert.org          "(libgoogle-perftools-dev package on Ubuntu or RedHat)." + \
9276994Snate@binkert.org          termcap.Normal
9286994Snate@binkert.org
9296994Snate@binkert.orgif not have_posix_clock:
9302155SN/A    print "Can't find library for POSIX clocks."
9315863Snate@binkert.org
9321869SN/A# Check for <fenv.h> (C99 FP environment control)
9331869SN/Ahave_fenv = conf.CheckHeader('fenv.h', '<>')
9345863Snate@binkert.orgif not have_fenv:
9355863Snate@binkert.org    print "Warning: Header file <fenv.h> not found."
9364202Sbinkertn@umich.edu    print "         This host has no IEEE FP rounding mode control."
9376108Snate@binkert.org
9386108Snate@binkert.org# Check if we should enable KVM-based hardware virtualization
9396108Snate@binkert.orghave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
9406108Snate@binkert.orgif not have_kvm:
9419219Spower.jg@gmail.com    print "Info: Header file <linux/kvm.h> not found, " \
9429219Spower.jg@gmail.com        "disabling KVM support."
9439219Spower.jg@gmail.com
9449219Spower.jg@gmail.com# Check if the requested target ISA is compatible with the host
9459219Spower.jg@gmail.comdef is_isa_kvm_compatible(isa):
9469219Spower.jg@gmail.com    isa_comp_table = {
9479219Spower.jg@gmail.com        "arm" : ( "armv7l" ),
9489219Spower.jg@gmail.com        }
9494202Sbinkertn@umich.edu    try:
9505863Snate@binkert.org        import platform
9518474Sgblack@eecs.umich.edu        host_isa = platform.machine()
9528474Sgblack@eecs.umich.edu    except:
9535742Snate@binkert.org        print "Warning: Failed to determine host ISA."
9548268Ssteve.reinhardt@amd.com        return False
9558268Ssteve.reinhardt@amd.com
9568268Ssteve.reinhardt@amd.com    return host_isa in isa_comp_table.get(isa, [])
9575742Snate@binkert.org
9585341Sstever@gmail.com
9598474Sgblack@eecs.umich.edu######################################################################
9608474Sgblack@eecs.umich.edu#
9615342Sstever@gmail.com# Finish the configuration
9624202Sbinkertn@umich.edu#
9634202Sbinkertn@umich.edumain = conf.Finish()
9644202Sbinkertn@umich.edu
9655863Snate@binkert.org######################################################################
9665863Snate@binkert.org#
9676994Snate@binkert.org# Collect all non-global variables
9686994Snate@binkert.org#
9696994Snate@binkert.org
9705863Snate@binkert.org# Define the universe of supported ISAs
9715863Snate@binkert.orgall_isa_list = [ ]
9725863Snate@binkert.orgExport('all_isa_list')
9735863Snate@binkert.org
9745863Snate@binkert.orgclass CpuModel(object):
9755863Snate@binkert.org    '''The CpuModel class encapsulates everything the ISA parser needs to
9765863Snate@binkert.org    know about a particular CPU model.'''
9775863Snate@binkert.org
9787840Snate@binkert.org    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
9795863Snate@binkert.org    dict = {}
9805952Ssaidi@eecs.umich.edu    list = []
9819219Spower.jg@gmail.com    defaults = []
9829219Spower.jg@gmail.com
9831869SN/A    # Constructor.  Automatically adds models to CpuModel.dict.
9841858SN/A    def __init__(self, name, filename, includes, strings, default=False):
9855863Snate@binkert.org        self.name = name           # name of model
9869044SAli.Saidi@ARM.com        self.filename = filename   # filename for output exec code
9879219Spower.jg@gmail.com        self.includes = includes   # include files needed in exec file
9889396Sandreas.hansson@arm.com        # The 'strings' dict holds all the per-CPU symbols we can
9891858SN/A        # substitute into templates etc.
990955SN/A        self.strings = strings
991955SN/A
9921869SN/A        # This cpu is enabled by default
9931869SN/A        self.default = default
9941869SN/A
9951869SN/A        # Add self to dict
9961869SN/A        if name in CpuModel.dict:
9975863Snate@binkert.org            raise AttributeError, "CpuModel '%s' already registered" % name
9985863Snate@binkert.org        CpuModel.dict[name] = self
9995863Snate@binkert.org        CpuModel.list.append(name)
10001869SN/A
10015863Snate@binkert.orgExport('CpuModel')
10021869SN/A
10035863Snate@binkert.org# Sticky variables get saved in the variables file so they persist from
10041869SN/A# one invocation to the next (unless overridden, in which case the new
10051869SN/A# value becomes sticky).
10061869SN/Asticky_vars = Variables(args=ARGUMENTS)
10071869SN/AExport('sticky_vars')
10088483Sgblack@eecs.umich.edu
10091869SN/A# Sticky variables that should be exported
10101869SN/Aexport_vars = []
10111869SN/AExport('export_vars')
10121869SN/A
10135863Snate@binkert.org# For Ruby
10145863Snate@binkert.orgall_protocols = []
10151869SN/AExport('all_protocols')
10165863Snate@binkert.orgprotocol_dirs = []
10175863Snate@binkert.orgExport('protocol_dirs')
10183356Sbinkertn@umich.eduslicc_includes = []
10193356Sbinkertn@umich.eduExport('slicc_includes')
10203356Sbinkertn@umich.edu
10213356Sbinkertn@umich.edu# Walk the tree and execute all SConsopts scripts that wil add to the
10223356Sbinkertn@umich.edu# above variables
10234781Snate@binkert.orgif not GetOption('verbose'):
10245863Snate@binkert.org    print "Reading SConsopts"
10255863Snate@binkert.orgfor bdir in [ base_dir ] + extras_dir_list:
10261869SN/A    if not isdir(bdir):
10271869SN/A        print "Error: directory '%s' does not exist" % bdir
10281869SN/A        Exit(1)
10296121Snate@binkert.org    for root, dirs, files in os.walk(bdir):
10301869SN/A        if 'SConsopts' in files:
10312638Sstever@eecs.umich.edu            if GetOption('verbose'):
10326121Snate@binkert.org                print "Reading", joinpath(root, 'SConsopts')
10336121Snate@binkert.org            SConscript(joinpath(root, 'SConsopts'))
10342638Sstever@eecs.umich.edu
10355749Scws3k@cs.virginia.eduall_isa_list.sort()
10366121Snate@binkert.org
10376121Snate@binkert.orgsticky_vars.AddVariables(
10385749Scws3k@cs.virginia.edu    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
10391869SN/A    ListVariable('CPU_MODELS', 'CPU models',
10401869SN/A                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
10413546Sgblack@eecs.umich.edu                 sorted(CpuModel.list)),
10423546Sgblack@eecs.umich.edu    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
10433546Sgblack@eecs.umich.edu                 False),
10443546Sgblack@eecs.umich.edu    BoolVariable('SS_COMPATIBLE_FP',
10456121Snate@binkert.org                 'Make floating-point results compatible with SimpleScalar',
10465863Snate@binkert.org                 False),
10473546Sgblack@eecs.umich.edu    BoolVariable('USE_SSE2',
10483546Sgblack@eecs.umich.edu                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
10493546Sgblack@eecs.umich.edu                 False),
10503546Sgblack@eecs.umich.edu    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
10514781Snate@binkert.org    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
10524781Snate@binkert.org    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
10536658Snate@binkert.org    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
10546658Snate@binkert.org    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
10554781Snate@binkert.org                  all_protocols),
10563546Sgblack@eecs.umich.edu    )
10573546Sgblack@eecs.umich.edu
10583546Sgblack@eecs.umich.edu# These variables get exported to #defines in config/*.hh (see src/SConscript).
10593546Sgblack@eecs.umich.eduexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'CP_ANNOTATE',
10607756SAli.Saidi@ARM.com                'USE_POSIX_CLOCK', 'PROTOCOL', 'HAVE_PROTOBUF']
10617816Ssteve.reinhardt@amd.com
10623546Sgblack@eecs.umich.edu###################################################
10633546Sgblack@eecs.umich.edu#
10643546Sgblack@eecs.umich.edu# Define a SCons builder for configuration flag headers.
10653546Sgblack@eecs.umich.edu#
10664202Sbinkertn@umich.edu###################################################
10673546Sgblack@eecs.umich.edu
10683546Sgblack@eecs.umich.edu# This function generates a config header file that #defines the
10693546Sgblack@eecs.umich.edu# variable symbol to the current variable setting (0 or 1).  The source
1070955SN/A# operands are the name of the variable and a Value node containing the
1071955SN/A# value of the variable.
1072955SN/Adef build_config_file(target, source, env):
1073955SN/A    (variable, value) = [s.get_contents() for s in source]
10745863Snate@binkert.org    f = file(str(target[0]), 'w')
10755863Snate@binkert.org    print >> f, '#define', variable, value
10765343Sstever@gmail.com    f.close()
10775343Sstever@gmail.com    return None
10786121Snate@binkert.org
10795863Snate@binkert.org# Combine the two functions into a scons Action object.
10804773Snate@binkert.orgconfig_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
10815863Snate@binkert.org
10822632Sstever@eecs.umich.edu# The emitter munges the source & target node lists to reflect what
10835863Snate@binkert.org# we're really doing.
10842023SN/Adef config_emitter(target, source, env):
10855863Snate@binkert.org    # extract variable name from Builder arg
10865863Snate@binkert.org    variable = str(target[0])
10875863Snate@binkert.org    # True target is config header file
10885863Snate@binkert.org    target = joinpath('config', variable.lower() + '.hh')
10895863Snate@binkert.org    val = env[variable]
10905863Snate@binkert.org    if isinstance(val, bool):
10915863Snate@binkert.org        # Force value to 0/1
10925863Snate@binkert.org        val = int(val)
10935863Snate@binkert.org    elif isinstance(val, str):
10942632Sstever@eecs.umich.edu        val = '"' + val + '"'
10955863Snate@binkert.org
10962023SN/A    # Sources are variable name & value (packaged in SCons Value nodes)
10972632Sstever@eecs.umich.edu    return ([target], [Value(variable), Value(val)])
10985863Snate@binkert.org
10995342Sstever@gmail.comconfig_builder = Builder(emitter = config_emitter, action = config_action)
11005863Snate@binkert.org
11012632Sstever@eecs.umich.edumain.Append(BUILDERS = { 'ConfigFile' : config_builder })
11025863Snate@binkert.org
11035863Snate@binkert.org# libelf build is shared across all configs in the build root.
11048267Ssteve.reinhardt@amd.commain.SConscript('ext/libelf/SConscript',
11058120Sgblack@eecs.umich.edu                variant_dir = joinpath(build_root, 'libelf'))
11068267Ssteve.reinhardt@amd.com
11078267Ssteve.reinhardt@amd.com# gzstream build is shared across all configs in the build root.
11088267Ssteve.reinhardt@amd.commain.SConscript('ext/gzstream/SConscript',
11098267Ssteve.reinhardt@amd.com                variant_dir = joinpath(build_root, 'gzstream'))
11108267Ssteve.reinhardt@amd.com
11118267Ssteve.reinhardt@amd.com# libfdt build is shared across all configs in the build root.
11128267Ssteve.reinhardt@amd.commain.SConscript('ext/libfdt/SConscript',
11138267Ssteve.reinhardt@amd.com                variant_dir = joinpath(build_root, 'libfdt'))
11148267Ssteve.reinhardt@amd.com
11155863Snate@binkert.org###################################################
11165863Snate@binkert.org#
11175863Snate@binkert.org# This function is used to set up a directory with switching headers
11182632Sstever@eecs.umich.edu#
11198267Ssteve.reinhardt@amd.com###################################################
11208267Ssteve.reinhardt@amd.com
11218267Ssteve.reinhardt@amd.commain['ALL_ISA_LIST'] = all_isa_list
11222632Sstever@eecs.umich.edudef make_switching_dir(dname, switch_headers, env):
11231888SN/A    # Generate the header.  target[0] is the full path of the output
11245863Snate@binkert.org    # header to generate.  'source' is a dummy variable, since we get the
11255863Snate@binkert.org    # list of ISAs from env['ALL_ISA_LIST'].
11261858SN/A    def gen_switch_hdr(target, source, env):
11278120Sgblack@eecs.umich.edu        fname = str(target[0])
11288120Sgblack@eecs.umich.edu        f = open(fname, 'w')
11297756SAli.Saidi@ARM.com        isa = env['TARGET_ISA'].lower()
11302598SN/A        print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
11315863Snate@binkert.org        f.close()
11321858SN/A
11331858SN/A    # Build SCons Action object. 'varlist' specifies env vars that this
11341858SN/A    # action depends on; when env['ALL_ISA_LIST'] changes these actions
11355863Snate@binkert.org    # should get re-executed.
11361858SN/A    switch_hdr_action = MakeAction(gen_switch_hdr,
11371858SN/A                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
11381858SN/A
11395863Snate@binkert.org    # Instantiate actions for each header
11401871SN/A    for hdr in switch_headers:
11411858SN/A        env.Command(hdr, [], switch_hdr_action)
11421858SN/AExport('make_switching_dir')
11431858SN/A
11441858SN/A###################################################
11455863Snate@binkert.org#
11465863Snate@binkert.org# Define build environments for selected configurations.
11471869SN/A#
11481965SN/A###################################################
11497739Sgblack@eecs.umich.edu
11501965SN/Afor variant_path in variant_paths:
11519045SAli.Saidi@ARM.com    print "Building in", variant_path
11529045SAli.Saidi@ARM.com
11539045SAli.Saidi@ARM.com    # Make a copy of the build-root environment to use for this config.
11542761Sstever@eecs.umich.edu    env = main.Clone()
11555863Snate@binkert.org    env['BUILDDIR'] = variant_path
11561869SN/A
11575863Snate@binkert.org    # variant_dir is the tail component of build path, and is used to
11582667Sstever@eecs.umich.edu    # determine the build parameters (e.g., 'ALPHA_SE')
11591869SN/A    (build_root, variant_dir) = splitpath(variant_path)
11601869SN/A
11612929Sktlim@umich.edu    # Set env variables according to the build directory config.
11622929Sktlim@umich.edu    sticky_vars.files = []
11635863Snate@binkert.org    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
11642929Sktlim@umich.edu    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1165955SN/A    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
11668120Sgblack@eecs.umich.edu    current_vars_file = joinpath(build_root, 'variables', variant_dir)
11678120Sgblack@eecs.umich.edu    if isfile(current_vars_file):
11688120Sgblack@eecs.umich.edu        sticky_vars.files.append(current_vars_file)
11698120Sgblack@eecs.umich.edu        print "Using saved variables file %s" % current_vars_file
11708120Sgblack@eecs.umich.edu    else:
11718120Sgblack@eecs.umich.edu        # Build dir-specific variables file doesn't exist.
11728120Sgblack@eecs.umich.edu
11738120Sgblack@eecs.umich.edu        # Make sure the directory is there so we can create it later
11748120Sgblack@eecs.umich.edu        opt_dir = dirname(current_vars_file)
11758120Sgblack@eecs.umich.edu        if not isdir(opt_dir):
11768120Sgblack@eecs.umich.edu            mkdir(opt_dir)
11778120Sgblack@eecs.umich.edu
1178        # Get default build variables from source tree.  Variables are
1179        # normally determined by name of $VARIANT_DIR, but can be
1180        # overridden by '--default=' arg on command line.
1181        default = GetOption('default')
1182        opts_dir = joinpath(main.root.abspath, 'build_opts')
1183        if default:
1184            default_vars_files = [joinpath(build_root, 'variables', default),
1185                                  joinpath(opts_dir, default)]
1186        else:
1187            default_vars_files = [joinpath(opts_dir, variant_dir)]
1188        existing_files = filter(isfile, default_vars_files)
1189        if existing_files:
1190            default_vars_file = existing_files[0]
1191            sticky_vars.files.append(default_vars_file)
1192            print "Variables file %s not found,\n  using defaults in %s" \
1193                  % (current_vars_file, default_vars_file)
1194        else:
1195            print "Error: cannot find variables file %s or " \
1196                  "default file(s) %s" \
1197                  % (current_vars_file, ' or '.join(default_vars_files))
1198            Exit(1)
1199
1200    # Apply current variable settings to env
1201    sticky_vars.Update(env)
1202
1203    help_texts["local_vars"] += \
1204        "Build variables for %s:\n" % variant_dir \
1205                 + sticky_vars.GenerateHelpText(env)
1206
1207    # Process variable settings.
1208
1209    if not have_fenv and env['USE_FENV']:
1210        print "Warning: <fenv.h> not available; " \
1211              "forcing USE_FENV to False in", variant_dir + "."
1212        env['USE_FENV'] = False
1213
1214    if not env['USE_FENV']:
1215        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1216        print "         FP results may deviate slightly from other platforms."
1217
1218    if env['EFENCE']:
1219        env.Append(LIBS=['efence'])
1220
1221    if env['USE_KVM']:
1222        if not have_kvm:
1223            print "Warning: Can not enable KVM, host seems to lack KVM support"
1224            env['USE_KVM'] = False
1225        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1226            print "Info: KVM support disabled due to unsupported host and " \
1227                "target ISA combination"
1228            env['USE_KVM'] = False
1229
1230    # Save sticky variable settings back to current variables file
1231    sticky_vars.Save(current_vars_file, env)
1232
1233    if env['USE_SSE2']:
1234        env.Append(CCFLAGS=['-msse2'])
1235
1236    # The src/SConscript file sets up the build rules in 'env' according
1237    # to the configured variables.  It returns a list of environments,
1238    # one for each variant build (debug, opt, etc.)
1239    envList = SConscript('src/SConscript', variant_dir = variant_path,
1240                         exports = 'env')
1241
1242    # Set up the regression tests for each build.
1243    for e in envList:
1244        SConscript('tests/SConscript',
1245                   variant_dir = joinpath(variant_path, 'tests', e.Label),
1246                   exports = { 'env' : e }, duplicate = False)
1247
1248# base help text
1249Help('''
1250Usage: scons [scons options] [build variables] [target(s)]
1251
1252Extra scons options:
1253%(options)s
1254
1255Global build variables:
1256%(global_vars)s
1257
1258%(local_vars)s
1259''' % help_texts)
1260