SConstruct revision 11811
1955SN/A# -*- mode:python -*-
2955SN/A
312230Sgiacomo.travaglini@arm.com# Copyright (c) 2013, 2015, 2016 ARM Limited
49812Sandreas.hansson@arm.com# All rights reserved.
59812Sandreas.hansson@arm.com#
69812Sandreas.hansson@arm.com# The license below extends only to copyright in the software and shall
79812Sandreas.hansson@arm.com# not be construed as granting a license to any other intellectual
89812Sandreas.hansson@arm.com# property including but not limited to intellectual property relating
99812Sandreas.hansson@arm.com# to a hardware implementation of the functionality of the software
109812Sandreas.hansson@arm.com# licensed hereunder.  You may use the software subject to the license
119812Sandreas.hansson@arm.com# terms below provided that you ensure that this notice is replicated
129812Sandreas.hansson@arm.com# unmodified and in its entirety in all distributions of the software,
139812Sandreas.hansson@arm.com# modified or unmodified, in source code or in binary form.
149812Sandreas.hansson@arm.com#
157816Ssteve.reinhardt@amd.com# Copyright (c) 2011 Advanced Micro Devices, Inc.
165871Snate@binkert.org# Copyright (c) 2009 The Hewlett-Packard Development Company
171762SN/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.
30955SN/A#
31955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
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,
38955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40955SN/A# (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.
422665Ssaidi@eecs.umich.edu#
432665Ssaidi@eecs.umich.edu# Authors: Steve Reinhardt
445863Snate@binkert.org#          Nathan Binkert
45955SN/A
46955SN/A###################################################
47955SN/A#
48955SN/A# SCons top-level build description (SConstruct) file.
49955SN/A#
508878Ssteve.reinhardt@amd.com# 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>'
528878Ssteve.reinhardt@amd.com# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
532632Sstever@eecs.umich.edu# the optimized full-system version).
54955SN/A#
558878Ssteve.reinhardt@amd.com# You can build gem5 in a different directory as long as there is a
562632Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
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:
612761Sstever@eecs.umich.edu#
622761Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
632761Sstever@eecs.umich.edu#   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
658878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
662761Sstever@eecs.umich.edu#
672761Sstever@eecs.umich.edu#   The following two commands are equivalent and demonstrate building
682761Sstever@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
692761Sstever@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
702761Sstever@eecs.umich.edu#   file.
718878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
728878Ssteve.reinhardt@amd.com#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
732632Sstever@eecs.umich.edu#
742632Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
758878Ssteve.reinhardt@amd.com# 'gem5' directory (or use -u or -C to tell scons where to find this
768878Ssteve.reinhardt@amd.com# file), you can use 'scons -h' to print all the gem5-specific build
772632Sstever@eecs.umich.edu# options as well.
78955SN/A#
79955SN/A###################################################
80955SN/A
816654Snate@binkert.org# Check for recent-enough Python and SCons versions.
8210196SCurtis.Dunham@arm.comtry:
83955SN/A    # Really old versions of scons only take two options for the
845396Ssaidi@eecs.umich.edu    # function, so check once without the revision and once with the
8511401Sandreas.sandberg@arm.com    # 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)
884202Sbinkertn@umich.edu    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
93955SN/A"""
946654Snate@binkert.org    raise
955273Sstever@gmail.com
965871Snate@binkert.org# We ensure the python version early because because python-config
975273Sstever@gmail.com# requires python 2.5
986654Snate@binkert.orgtry:
995396Ssaidi@eecs.umich.edu    EnsurePythonVersion(2, 5)
1008120Sgblack@eecs.umich.eduexcept SystemExit, e:
1018120Sgblack@eecs.umich.edu    print """
1028120Sgblack@eecs.umich.eduYou can use a non-default installation of the Python interpreter by
1038120Sgblack@eecs.umich.edurearranging your PATH so that scons finds the non-default 'python' and
1048120Sgblack@eecs.umich.edu'python-config' first.
1058120Sgblack@eecs.umich.edu
1068120Sgblack@eecs.umich.eduFor more details, see:
1078120Sgblack@eecs.umich.edu    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1088879Ssteve.reinhardt@amd.com"""
1098879Ssteve.reinhardt@amd.com    raise
1108879Ssteve.reinhardt@amd.com
1118879Ssteve.reinhardt@amd.com# Global Python includes
1128879Ssteve.reinhardt@amd.comimport itertools
1138879Ssteve.reinhardt@amd.comimport os
1148879Ssteve.reinhardt@amd.comimport re
1158879Ssteve.reinhardt@amd.comimport shutil
1168879Ssteve.reinhardt@amd.comimport subprocess
1178879Ssteve.reinhardt@amd.comimport sys
1188879Ssteve.reinhardt@amd.com
1198879Ssteve.reinhardt@amd.comfrom os import mkdir, environ
1208879Ssteve.reinhardt@amd.comfrom os.path import abspath, basename, dirname, expanduser, normpath
1218120Sgblack@eecs.umich.edufrom os.path import exists,  isdir, isfile
1228120Sgblack@eecs.umich.edufrom os.path import join as joinpath, split as splitpath
1238120Sgblack@eecs.umich.edu
1248120Sgblack@eecs.umich.edu# SCons includes
1258120Sgblack@eecs.umich.eduimport SCons
1268120Sgblack@eecs.umich.eduimport SCons.Node
1278120Sgblack@eecs.umich.edu
1288120Sgblack@eecs.umich.eduextra_python_paths = [
1298120Sgblack@eecs.umich.edu    Dir('src/python').srcnode().abspath, # gem5 includes
1308120Sgblack@eecs.umich.edu    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1318120Sgblack@eecs.umich.edu    ]
1328120Sgblack@eecs.umich.edu
1338120Sgblack@eecs.umich.edusys.path[1:1] = extra_python_paths
1348120Sgblack@eecs.umich.edu
1358879Ssteve.reinhardt@amd.comfrom m5.util import compareVersions, readCommand
1368879Ssteve.reinhardt@amd.comfrom m5.util.terminal import get_termcap
1378879Ssteve.reinhardt@amd.com
1388879Ssteve.reinhardt@amd.comhelp_texts = {
13910458Sandreas.hansson@arm.com    "options" : "",
14010458Sandreas.hansson@arm.com    "global_vars" : "",
14110458Sandreas.hansson@arm.com    "local_vars" : ""
1428879Ssteve.reinhardt@amd.com}
1438879Ssteve.reinhardt@amd.com
1448879Ssteve.reinhardt@amd.comExport("help_texts")
1458879Ssteve.reinhardt@amd.com
1469227Sandreas.hansson@arm.com
1479227Sandreas.hansson@arm.com# There's a bug in scons in that (1) by default, the help texts from
14812063Sgabeblack@google.com# AddOption() are supposed to be displayed when you type 'scons -h'
14912063Sgabeblack@google.com# and (2) you can override the help displayed by 'scons -h' using the
15012063Sgabeblack@google.com# Help() function, but these two features are incompatible: once
1518879Ssteve.reinhardt@amd.com# you've overridden the help text using Help(), there's no way to get
1528879Ssteve.reinhardt@amd.com# at the help texts from AddOptions.  See:
1538879Ssteve.reinhardt@amd.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1548879Ssteve.reinhardt@amd.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
15510453SAndrew.Bardsley@arm.com# This hack lets us extract the help text from AddOptions and
15610453SAndrew.Bardsley@arm.com# re-inject it via Help().  Ideally someday this bug will be fixed and
15710453SAndrew.Bardsley@arm.com# we can just use AddOption directly.
15810456SCurtis.Dunham@arm.comdef AddLocalOption(*args, **kwargs):
15910456SCurtis.Dunham@arm.com    col_width = 30
16010456SCurtis.Dunham@arm.com
16110457Sandreas.hansson@arm.com    help = "  " + ", ".join(args)
16210457Sandreas.hansson@arm.com    if "help" in kwargs:
16311342Sandreas.hansson@arm.com        length = len(help)
16411342Sandreas.hansson@arm.com        if length >= col_width:
1658120Sgblack@eecs.umich.edu            help += "\n" + " " * col_width
16612063Sgabeblack@google.com        else:
16712063Sgabeblack@google.com            help += " " * (col_width - length)
16812063Sgabeblack@google.com        help += kwargs["help"]
16912063Sgabeblack@google.com    help_texts["options"] += help + "\n"
1705871Snate@binkert.org
1715871Snate@binkert.org    AddOption(*args, **kwargs)
1726121Snate@binkert.org
1735871Snate@binkert.orgAddLocalOption('--colors', dest='use_colors', action='store_true',
1745871Snate@binkert.org               help="Add color to abbreviated scons output")
1759926Sstan.czerniawski@arm.comAddLocalOption('--no-colors', dest='use_colors', action='store_false',
17612243Sgabeblack@google.com               help="Don't add color to abbreviated scons output")
1771533SN/AAddLocalOption('--with-cxx-config', dest='with_cxx_config',
17812246Sgabeblack@google.com               action='store_true',
17912246Sgabeblack@google.com               help="Build with support for C++-based configuration")
18012246Sgabeblack@google.comAddLocalOption('--default', dest='default', type='string', action='store',
18112246Sgabeblack@google.com               help='Override which build_opts file to use for defaults')
1829239Sandreas.hansson@arm.comAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1839239Sandreas.hansson@arm.com               help='Disable style checking hooks')
1849239Sandreas.hansson@arm.comAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1859239Sandreas.hansson@arm.com               help='Disable Link-Time Optimization for fast')
1869239Sandreas.hansson@arm.comAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1879239Sandreas.hansson@arm.com               help='Update test reference outputs')
1889239Sandreas.hansson@arm.comAddLocalOption('--verbose', dest='verbose', action='store_true',
189955SN/A               help='Print full tool command lines')
190955SN/AAddLocalOption('--without-python', dest='without_python',
1912632Sstever@eecs.umich.edu               action='store_true',
1922632Sstever@eecs.umich.edu               help='Build without Python configuration support')
193955SN/AAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
194955SN/A               action='store_true',
195955SN/A               help='Disable linking against tcmalloc')
196955SN/AAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1978878Ssteve.reinhardt@amd.com               help='Build with Undefined Behavior Sanitizer if available')
198955SN/AAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1992632Sstever@eecs.umich.edu               help='Build with Address Sanitizer if available')
2002632Sstever@eecs.umich.edu
2012632Sstever@eecs.umich.edutermcap = get_termcap(GetOption('use_colors'))
2022632Sstever@eecs.umich.edu
2032632Sstever@eecs.umich.edu########################################################################
2042632Sstever@eecs.umich.edu#
2052632Sstever@eecs.umich.edu# Set up the main build environment.
2068268Ssteve.reinhardt@amd.com#
2078268Ssteve.reinhardt@amd.com########################################################################
2088268Ssteve.reinhardt@amd.com
2098268Ssteve.reinhardt@amd.com# export TERM so that clang reports errors in color
2108268Ssteve.reinhardt@amd.comuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
2118268Ssteve.reinhardt@amd.com                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
2128268Ssteve.reinhardt@amd.com                 'PYTHONPATH', 'RANLIB', 'SWIG', 'TERM' ])
2132632Sstever@eecs.umich.edu
2142632Sstever@eecs.umich.eduuse_prefixes = [
2152632Sstever@eecs.umich.edu    "ASAN_",           # address sanitizer symbolizer path and settings
2162632Sstever@eecs.umich.edu    "CCACHE_",         # ccache (caching compiler wrapper) configuration
2178268Ssteve.reinhardt@amd.com    "CCC_",            # clang static analyzer configuration
2182632Sstever@eecs.umich.edu    "DISTCC_",         # distcc (distributed compiler wrapper) configuration
2198268Ssteve.reinhardt@amd.com    "INCLUDE_SERVER_", # distcc pump server settings
2208268Ssteve.reinhardt@amd.com    "M5",              # M5 configuration (e.g., path to kernels)
2218268Ssteve.reinhardt@amd.com    ]
2228268Ssteve.reinhardt@amd.com
2233718Sstever@eecs.umich.eduuse_env = {}
2242634Sstever@eecs.umich.edufor key,val in sorted(os.environ.iteritems()):
2252634Sstever@eecs.umich.edu    if key in use_vars or \
2265863Snate@binkert.org            any([key.startswith(prefix) for prefix in use_prefixes]):
2272638Sstever@eecs.umich.edu        use_env[key] = val
2288268Ssteve.reinhardt@amd.com
2292632Sstever@eecs.umich.edu# Tell scons to avoid implicit command dependencies to avoid issues
2302632Sstever@eecs.umich.edu# with the param wrappes being compiled twice (see
2312632Sstever@eecs.umich.edu# http://scons.tigris.org/issues/show_bug.cgi?id=2811)
2322632Sstever@eecs.umich.edumain = Environment(ENV=use_env, IMPLICIT_COMMAND_DEPENDENCIES=0)
2332632Sstever@eecs.umich.edumain.Decider('MD5-timestamp')
2341858SN/Amain.root = Dir(".")         # The current directory (where this file lives).
2353716Sstever@eecs.umich.edumain.srcdir = Dir("src")     # The source directory
2362638Sstever@eecs.umich.edu
2372638Sstever@eecs.umich.edumain_dict_keys = main.Dictionary().keys()
2382638Sstever@eecs.umich.edu
2392638Sstever@eecs.umich.edu# Check that we have a C/C++ compiler
2402638Sstever@eecs.umich.eduif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2412638Sstever@eecs.umich.edu    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2422638Sstever@eecs.umich.edu    Exit(1)
2435863Snate@binkert.org
2445863Snate@binkert.org# Check that swig is present
2455863Snate@binkert.orgif not 'SWIG' in main_dict_keys:
246955SN/A    print "swig is not installed (package swig on Ubuntu and RedHat)"
2475341Sstever@gmail.com    Exit(1)
2485341Sstever@gmail.com
2495863Snate@binkert.org# add useful python code PYTHONPATH so it can be used by subprocesses
2507756SAli.Saidi@ARM.com# as well
2515341Sstever@gmail.commain.AppendENVPath('PYTHONPATH', extra_python_paths)
2526121Snate@binkert.org
2534494Ssaidi@eecs.umich.edu########################################################################
2546121Snate@binkert.org#
2551105SN/A# Mercurial Stuff.
2562667Sstever@eecs.umich.edu#
2572667Sstever@eecs.umich.edu# If the gem5 directory is a mercurial repository, we should do some
2582667Sstever@eecs.umich.edu# extra things.
2592667Sstever@eecs.umich.edu#
2606121Snate@binkert.org########################################################################
2612667Sstever@eecs.umich.edu
2625341Sstever@gmail.comhgdir = main.root.Dir(".hg")
2635863Snate@binkert.org
2645341Sstever@gmail.com
2655341Sstever@gmail.comstyle_message = """
2665341Sstever@gmail.comYou're missing the gem5 style hook, which automatically checks your code
2678120Sgblack@eecs.umich.eduagainst the gem5 style rules on %s.
2685341Sstever@gmail.comThis script will now install the hook in your %s.
2698120Sgblack@eecs.umich.eduPress enter to continue, or ctrl-c to abort: """
2705341Sstever@gmail.com
2718120Sgblack@eecs.umich.edumercurial_style_message = style_message % ("hg commit and qrefresh commands",
2726121Snate@binkert.org                                           ".hg/hgrc file")
2736121Snate@binkert.orggit_style_message = style_message % ("'git commit'",
2749396Sandreas.hansson@arm.com                                     ".git/hooks/ directory")
2755397Ssaidi@eecs.umich.edu
2765397Ssaidi@eecs.umich.edumercurial_style_upgrade_message = """
2777727SAli.Saidi@ARM.comYour Mercurial style hooks are not up-to-date. This script will now
2788268Ssteve.reinhardt@amd.comtry to automatically update them. A backup of your hgrc will be saved
2796168Snate@binkert.orgin .hg/hgrc.old.
2805341Sstever@gmail.comPress enter to continue, or ctrl-c to abort: """
2818120Sgblack@eecs.umich.edu
2828120Sgblack@eecs.umich.edumercurial_style_hook = """
2838120Sgblack@eecs.umich.edu# The following lines were automatically added by gem5/SConstruct
2846814Sgblack@eecs.umich.edu# to provide the gem5 style-checking hooks
2855863Snate@binkert.org[extensions]
2868120Sgblack@eecs.umich.eduhgstyle = %s/util/hgstyle.py
2875341Sstever@gmail.com
2885863Snate@binkert.org[hooks]
2898268Ssteve.reinhardt@amd.compretxncommit.style = python:hgstyle.check_style
2906121Snate@binkert.orgpre-qrefresh.style = python:hgstyle.check_style
2916121Snate@binkert.org# End of SConstruct additions
2928268Ssteve.reinhardt@amd.com
2935742Snate@binkert.org""" % (main.root.abspath)
2945742Snate@binkert.org
2955341Sstever@gmail.commercurial_lib_not_found = """
2965742Snate@binkert.orgMercurial libraries cannot be found, ignoring style hook.  If
2975742Snate@binkert.orgyou are a gem5 developer, please fix this and run the style
2985341Sstever@gmail.comhook. It is important.
2996017Snate@binkert.org"""
3006121Snate@binkert.org
3016017Snate@binkert.org# Check for style hook and prompt for installation if it's not there.
30212158Sandreas.sandberg@arm.com# Skip this if --ignore-style was specified, there's no interactive
30312158Sandreas.sandberg@arm.com# terminal to prompt, or no recognized revision control system can be
30412158Sandreas.sandberg@arm.com# found.
3058120Sgblack@eecs.umich.eduignore_style = GetOption('ignore_style') or not sys.stdin.isatty()
3067756SAli.Saidi@ARM.com
3077756SAli.Saidi@ARM.com# Try wire up Mercurial to the style hooks
3087756SAli.Saidi@ARM.comif not ignore_style and hgdir.exists():
3097756SAli.Saidi@ARM.com    style_hook = True
3107816Ssteve.reinhardt@amd.com    style_hooks = tuple()
3117816Ssteve.reinhardt@amd.com    hgrc = hgdir.File('hgrc')
3127816Ssteve.reinhardt@amd.com    hgrc_old = hgdir.File('hgrc.old')
3137816Ssteve.reinhardt@amd.com    try:
3147816Ssteve.reinhardt@amd.com        from mercurial import ui
31511979Sgabeblack@google.com        ui = ui.ui()
3167816Ssteve.reinhardt@amd.com        ui.readconfig(hgrc.abspath)
3177816Ssteve.reinhardt@amd.com        style_hooks = (ui.config('hooks', 'pretxncommit.style', None),
3187816Ssteve.reinhardt@amd.com                       ui.config('hooks', 'pre-qrefresh.style', None))
3197816Ssteve.reinhardt@amd.com        style_hook = all(style_hooks)
3207756SAli.Saidi@ARM.com        style_extension = ui.config('extensions', 'style', None)
3217756SAli.Saidi@ARM.com    except ImportError:
3229227Sandreas.hansson@arm.com        print mercurial_lib_not_found
3239227Sandreas.hansson@arm.com
3249227Sandreas.hansson@arm.com    if "python:style.check_style" in style_hooks:
3259227Sandreas.hansson@arm.com        # Try to upgrade the style hooks
3269590Sandreas@sandberg.pp.se        print mercurial_style_upgrade_message
3279590Sandreas@sandberg.pp.se        # continue unless user does ctrl-c/ctrl-d etc.
3289590Sandreas@sandberg.pp.se        try:
3299590Sandreas@sandberg.pp.se            raw_input()
3309590Sandreas@sandberg.pp.se        except:
3319590Sandreas@sandberg.pp.se            print "Input exception, exiting scons.\n"
3326654Snate@binkert.org            sys.exit(1)
3336654Snate@binkert.org        shutil.copyfile(hgrc.abspath, hgrc_old.abspath)
3345871Snate@binkert.org        re_style_hook = re.compile(r"^([^=#]+)\.style\s*=\s*([^#\s]+).*")
3356121Snate@binkert.org        re_style_extension = re.compile("style\s*=\s*([^#\s]+).*")
3368946Sandreas.hansson@arm.com        old, new = open(hgrc_old.abspath, 'r'), open(hgrc.abspath, 'w')
3379419Sandreas.hansson@arm.com        for l in old:
3383940Ssaidi@eecs.umich.edu            m_hook = re_style_hook.match(l)
3393918Ssaidi@eecs.umich.edu            m_ext = re_style_extension.match(l)
3403918Ssaidi@eecs.umich.edu            if m_hook:
3411858SN/A                hook, check = m_hook.groups()
3429556Sandreas.hansson@arm.com                if check != "python:style.check_style":
3439556Sandreas.hansson@arm.com                    print "Warning: %s.style is using a non-default " \
3449556Sandreas.hansson@arm.com                        "checker: %s" % (hook, check)
3459556Sandreas.hansson@arm.com                if hook not in ("pretxncommit", "pre-qrefresh"):
34611294Sandreas.hansson@arm.com                    print "Warning: Updating unknown style hook: %s" % hook
34711294Sandreas.hansson@arm.com
34811294Sandreas.hansson@arm.com                l = "%s.style = python:hgstyle.check_style\n" % hook
34911294Sandreas.hansson@arm.com            elif m_ext and m_ext.group(1) == style_extension:
35010878Sandreas.hansson@arm.com                l = "hgstyle = %s/util/hgstyle.py\n" % main.root.abspath
35110878Sandreas.hansson@arm.com
35211811Sbaz21@cam.ac.uk            new.write(l)
35311811Sbaz21@cam.ac.uk    elif not style_hook:
35411811Sbaz21@cam.ac.uk        print mercurial_style_message,
35511982Sgabeblack@google.com        # continue unless user does ctrl-c/ctrl-d etc.
35611982Sgabeblack@google.com        try:
35711982Sgabeblack@google.com            raw_input()
35811982Sgabeblack@google.com        except:
35911992Sgabeblack@google.com            print "Input exception, exiting scons.\n"
36011982Sgabeblack@google.com            sys.exit(1)
36111982Sgabeblack@google.com        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
3629556Sandreas.hansson@arm.com        print "Adding style hook to", hgrc_path, "\n"
3639556Sandreas.hansson@arm.com        try:
3649556Sandreas.hansson@arm.com            with open(hgrc_path, 'a') as f:
3659556Sandreas.hansson@arm.com                f.write(mercurial_style_hook)
3669556Sandreas.hansson@arm.com        except:
3679556Sandreas.hansson@arm.com            print "Error updating", hgrc_path
3689556Sandreas.hansson@arm.com            sys.exit(1)
3699556Sandreas.hansson@arm.com
3709556Sandreas.hansson@arm.comdef install_git_style_hooks():
3719556Sandreas.hansson@arm.com    try:
3729556Sandreas.hansson@arm.com        gitdir = Dir(readCommand(
3739556Sandreas.hansson@arm.com            ["git", "rev-parse", "--git-dir"]).strip("\n"))
3749556Sandreas.hansson@arm.com    except Exception, e:
3759556Sandreas.hansson@arm.com        print "Warning: Failed to find git repo directory: %s" % e
3769556Sandreas.hansson@arm.com        return
3779556Sandreas.hansson@arm.com
3789556Sandreas.hansson@arm.com    git_hooks = gitdir.Dir("hooks")
3799556Sandreas.hansson@arm.com    git_pre_commit_hook = git_hooks.File("pre-commit")
3809556Sandreas.hansson@arm.com    git_style_script = File("util/git-pre-commit.py")
3816121Snate@binkert.org
38211500Sandreas.hansson@arm.com    if git_pre_commit_hook.exists():
38310238Sandreas.hansson@arm.com        return
38410878Sandreas.hansson@arm.com
3859420Sandreas.hansson@arm.com    print git_style_message,
38611500Sandreas.hansson@arm.com    try:
38711500Sandreas.hansson@arm.com        raw_input()
3889420Sandreas.hansson@arm.com    except:
3899420Sandreas.hansson@arm.com        print "Input exception, exiting scons.\n"
3909420Sandreas.hansson@arm.com        sys.exit(1)
3919420Sandreas.hansson@arm.com
3929420Sandreas.hansson@arm.com    if not git_hooks.exists():
39312063Sgabeblack@google.com        mkdir(git_hooks.get_abspath())
39412063Sgabeblack@google.com
39512063Sgabeblack@google.com    # Use a relative symlink if the hooks live in the source directory
39612063Sgabeblack@google.com    if git_pre_commit_hook.is_under(main.root):
39712063Sgabeblack@google.com        script_path = os.path.relpath(
39812063Sgabeblack@google.com            git_style_script.get_abspath(),
39912063Sgabeblack@google.com            git_pre_commit_hook.Dir(".").get_abspath())
40012063Sgabeblack@google.com    else:
40112063Sgabeblack@google.com        script_path = git_style_script.get_abspath()
40212063Sgabeblack@google.com
40312063Sgabeblack@google.com    try:
40412063Sgabeblack@google.com        os.symlink(script_path, git_pre_commit_hook.get_abspath())
40512063Sgabeblack@google.com    except:
40612063Sgabeblack@google.com        print "Error updating git pre-commit hook"
40712063Sgabeblack@google.com        raise
40812063Sgabeblack@google.com
40912063Sgabeblack@google.com# Try to wire up git to the style hooks
41012063Sgabeblack@google.comif not ignore_style and main.root.Entry(".git").exists():
41112063Sgabeblack@google.com    install_git_style_hooks()
41212063Sgabeblack@google.com
41312063Sgabeblack@google.com###################################################
41412063Sgabeblack@google.com#
41510264Sandreas.hansson@arm.com# Figure out which configurations to set up based on the path(s) of
41610264Sandreas.hansson@arm.com# the target(s).
41710264Sandreas.hansson@arm.com#
41810264Sandreas.hansson@arm.com###################################################
41911925Sgabeblack@google.com
42011925Sgabeblack@google.com# Find default configuration & binary.
42111500Sandreas.hansson@arm.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
42210264Sandreas.hansson@arm.com
42311500Sandreas.hansson@arm.com# helper function: find last occurrence of element in list
42411500Sandreas.hansson@arm.comdef rfind(l, elt, offs = -1):
42511500Sandreas.hansson@arm.com    for i in range(len(l)+offs, 0, -1):
42611500Sandreas.hansson@arm.com        if l[i] == elt:
42710866Sandreas.hansson@arm.com            return i
42811500Sandreas.hansson@arm.com    raise ValueError, "element not found"
42911500Sandreas.hansson@arm.com
43011500Sandreas.hansson@arm.com# Take a list of paths (or SCons Nodes) and return a list with all
43111500Sandreas.hansson@arm.com# paths made absolute and ~-expanded.  Paths will be interpreted
43211500Sandreas.hansson@arm.com# relative to the launch directory unless a different root is provided
43311500Sandreas.hansson@arm.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
43411500Sandreas.hansson@arm.com    return [abspath(joinpath(root, expanduser(str(p))))
43510264Sandreas.hansson@arm.com            for p in path_list]
43610457Sandreas.hansson@arm.com
43710457Sandreas.hansson@arm.com# Each target must have 'build' in the interior of the path; the
43810457Sandreas.hansson@arm.com# directory below this will determine the build parameters.  For
43910457Sandreas.hansson@arm.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
44010457Sandreas.hansson@arm.com# recognize that ALPHA_SE specifies the configuration because it
44110457Sandreas.hansson@arm.com# follow 'build' in the build path.
44210457Sandreas.hansson@arm.com
44310457Sandreas.hansson@arm.com# The funky assignment to "[:]" is needed to replace the list contents
44410457Sandreas.hansson@arm.com# in place rather than reassign the symbol to a new list, which
44512063Sgabeblack@google.com# doesn't work (obviously!).
44612063Sgabeblack@google.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
44712063Sgabeblack@google.com
44812063Sgabeblack@google.com# Generate a list of the unique build roots and configs that the
44912063Sgabeblack@google.com# collected targets reference.
45012063Sgabeblack@google.comvariant_paths = []
45112063Sgabeblack@google.combuild_root = None
45212063Sgabeblack@google.comfor t in BUILD_TARGETS:
45312063Sgabeblack@google.com    path_dirs = t.split('/')
45412063Sgabeblack@google.com    try:
45512063Sgabeblack@google.com        build_top = rfind(path_dirs, 'build', -2)
45610238Sandreas.hansson@arm.com    except:
45710238Sandreas.hansson@arm.com        print "Error: no non-leaf 'build' dir found on target path", t
45810238Sandreas.hansson@arm.com        Exit(1)
45912063Sgabeblack@google.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
46010238Sandreas.hansson@arm.com    if not build_root:
46110238Sandreas.hansson@arm.com        build_root = this_build_root
46210416Sandreas.hansson@arm.com    else:
46310238Sandreas.hansson@arm.com        if this_build_root != build_root:
4649227Sandreas.hansson@arm.com            print "Error: build targets not under same build root\n"\
46510238Sandreas.hansson@arm.com                  "  %s\n  %s" % (build_root, this_build_root)
46610416Sandreas.hansson@arm.com            Exit(1)
46710416Sandreas.hansson@arm.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
4689227Sandreas.hansson@arm.com    if variant_path not in variant_paths:
4699590Sandreas@sandberg.pp.se        variant_paths.append(variant_path)
4709590Sandreas@sandberg.pp.se
4719590Sandreas@sandberg.pp.se# Make sure build_root exists (might not if this is the first build there)
47211497SMatteo.Andreozzi@arm.comif not isdir(build_root):
47311497SMatteo.Andreozzi@arm.com    mkdir(build_root)
47411497SMatteo.Andreozzi@arm.commain['BUILDROOT'] = build_root
47511497SMatteo.Andreozzi@arm.com
47612304Sgabeblack@google.comExport('main')
47712304Sgabeblack@google.com
47812304Sgabeblack@google.commain.SConsignFile(joinpath(build_root, "sconsign"))
47912304Sgabeblack@google.com
48012304Sgabeblack@google.com# Default duplicate option is to use hard links, but this messes up
48112304Sgabeblack@google.com# when you use emacs to edit a file in the target dir, as emacs moves
48212304Sgabeblack@google.com# file to file~ then copies to file, breaking the link.  Symbolic
48312304Sgabeblack@google.com# (soft) links work better.
48412304Sgabeblack@google.commain.SetOption('duplicate', 'soft-copy')
48512304Sgabeblack@google.com
48612304Sgabeblack@google.com#
48712304Sgabeblack@google.com# Set up global sticky variables... these are common to an entire build
48812304Sgabeblack@google.com# tree (not specific to a particular build like ALPHA_SE)
48912304Sgabeblack@google.com#
49012304Sgabeblack@google.com
49112304Sgabeblack@google.comglobal_vars_file = joinpath(build_root, 'variables.global')
49212304Sgabeblack@google.com
49312304Sgabeblack@google.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
49412304Sgabeblack@google.com
4958737Skoansin.tan@gmail.comglobal_vars.AddVariables(
49610878Sandreas.hansson@arm.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
49711500Sandreas.hansson@arm.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
4989420Sandreas.hansson@arm.com    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
4998737Skoansin.tan@gmail.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
50010106SMitch.Hayenga@arm.com    ('BATCH', 'Use batch pool for build and tests', False),
5018737Skoansin.tan@gmail.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
5028737Skoansin.tan@gmail.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
50310878Sandreas.hansson@arm.com    ('EXTRAS', 'Add extra directories to the compilation', '')
50410878Sandreas.hansson@arm.com    )
5058737Skoansin.tan@gmail.com
5068737Skoansin.tan@gmail.com# Update main environment with values from ARGUMENTS & global_vars_file
5078737Skoansin.tan@gmail.comglobal_vars.Update(main)
5088737Skoansin.tan@gmail.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
5098737Skoansin.tan@gmail.com
5108737Skoansin.tan@gmail.com# Save sticky variable settings back to current variables file
51111294Sandreas.hansson@arm.comglobal_vars.Save(global_vars_file, main)
5129556Sandreas.hansson@arm.com
5139556Sandreas.hansson@arm.com# Parse EXTRAS variable to build list of all directories where we're
5149556Sandreas.hansson@arm.com# look for sources etc.  This list is exported as extras_dir_list.
51511294Sandreas.hansson@arm.combase_dir = main.srcdir.abspath
51610278SAndreas.Sandberg@ARM.comif main['EXTRAS']:
51710278SAndreas.Sandberg@ARM.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
51810278SAndreas.Sandberg@ARM.comelse:
51910278SAndreas.Sandberg@ARM.com    extras_dir_list = []
52010278SAndreas.Sandberg@ARM.com
52110278SAndreas.Sandberg@ARM.comExport('base_dir')
5229556Sandreas.hansson@arm.comExport('extras_dir_list')
5239590Sandreas@sandberg.pp.se
5249590Sandreas@sandberg.pp.se# the ext directory should be on the #includes path
5259420Sandreas.hansson@arm.commain.Append(CPPPATH=[Dir('ext')])
5269846Sandreas.hansson@arm.com
5279846Sandreas.hansson@arm.comdef strip_build_path(path, env):
5289846Sandreas.hansson@arm.com    path = str(path)
5299846Sandreas.hansson@arm.com    variant_base = env['BUILDROOT'] + os.path.sep
5308946Sandreas.hansson@arm.com    if path.startswith(variant_base):
53111811Sbaz21@cam.ac.uk        path = path[len(variant_base):]
53211811Sbaz21@cam.ac.uk    elif path.startswith('build/'):
53311811Sbaz21@cam.ac.uk        path = path[6:]
53411811Sbaz21@cam.ac.uk    return path
53512304Sgabeblack@google.com
53612304Sgabeblack@google.com# Generate a string of the form:
53712304Sgabeblack@google.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
53812304Sgabeblack@google.com# to print while building.
53912304Sgabeblack@google.comclass Transform(object):
54012304Sgabeblack@google.com    # all specific color settings should be here and nowhere else
54112304Sgabeblack@google.com    tool_color = termcap.Normal
54212304Sgabeblack@google.com    pfx_color = termcap.Yellow
54312304Sgabeblack@google.com    srcs_color = termcap.Yellow + termcap.Bold
54412304Sgabeblack@google.com    arrow_color = termcap.Blue + termcap.Bold
54512304Sgabeblack@google.com    tgts_color = termcap.Yellow + termcap.Bold
54612304Sgabeblack@google.com
54712304Sgabeblack@google.com    def __init__(self, tool, max_sources=99):
54812304Sgabeblack@google.com        self.format = self.tool_color + (" [%8s] " % tool) \
54912304Sgabeblack@google.com                      + self.pfx_color + "%s" \
55012304Sgabeblack@google.com                      + self.srcs_color + "%s" \
5513918Ssaidi@eecs.umich.edu                      + self.arrow_color + " -> " \
5529068SAli.Saidi@ARM.com                      + self.tgts_color + "%s" \
5539068SAli.Saidi@ARM.com                      + termcap.Normal
5549068SAli.Saidi@ARM.com        self.max_sources = max_sources
5559068SAli.Saidi@ARM.com
5569068SAli.Saidi@ARM.com    def __call__(self, target, source, env, for_signature=None):
5579068SAli.Saidi@ARM.com        # truncate source list according to max_sources param
5589068SAli.Saidi@ARM.com        source = source[0:self.max_sources]
5599068SAli.Saidi@ARM.com        def strip(f):
5609068SAli.Saidi@ARM.com            return strip_build_path(str(f), env)
5619419Sandreas.hansson@arm.com        if len(source) > 0:
5629068SAli.Saidi@ARM.com            srcs = map(strip, source)
5639068SAli.Saidi@ARM.com        else:
5649068SAli.Saidi@ARM.com            srcs = ['']
5659068SAli.Saidi@ARM.com        tgts = map(strip, target)
5669068SAli.Saidi@ARM.com        # surprisingly, os.path.commonprefix is a dumb char-by-char string
5679068SAli.Saidi@ARM.com        # operation that has nothing to do with paths.
5683918Ssaidi@eecs.umich.edu        com_pfx = os.path.commonprefix(srcs + tgts)
5693918Ssaidi@eecs.umich.edu        com_pfx_len = len(com_pfx)
5706157Snate@binkert.org        if com_pfx:
5716157Snate@binkert.org            # do some cleanup and sanity checking on common prefix
5726157Snate@binkert.org            if com_pfx[-1] == ".":
5736157Snate@binkert.org                # prefix matches all but file extension: ok
5745397Ssaidi@eecs.umich.edu                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
5755397Ssaidi@eecs.umich.edu                com_pfx = com_pfx[0:-1]
5766121Snate@binkert.org            elif com_pfx[-1] == "/":
5776121Snate@binkert.org                # common prefix is directory path: OK
5786121Snate@binkert.org                pass
5796121Snate@binkert.org            else:
5806121Snate@binkert.org                src0_len = len(srcs[0])
5816121Snate@binkert.org                tgt0_len = len(tgts[0])
5825397Ssaidi@eecs.umich.edu                if src0_len == com_pfx_len:
5831851SN/A                    # source is a substring of target, OK
5841851SN/A                    pass
5857739Sgblack@eecs.umich.edu                elif tgt0_len == com_pfx_len:
586955SN/A                    # target is a substring of source, need to back up to
5879396Sandreas.hansson@arm.com                    # avoid empty string on RHS of arrow
5889396Sandreas.hansson@arm.com                    sep_idx = com_pfx.rfind(".")
5899396Sandreas.hansson@arm.com                    if sep_idx != -1:
5909396Sandreas.hansson@arm.com                        com_pfx = com_pfx[0:sep_idx]
5919396Sandreas.hansson@arm.com                    else:
5929396Sandreas.hansson@arm.com                        com_pfx = ''
5939396Sandreas.hansson@arm.com                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
5949396Sandreas.hansson@arm.com                    # still splitting at file extension: ok
5959396Sandreas.hansson@arm.com                    pass
5969396Sandreas.hansson@arm.com                else:
5979396Sandreas.hansson@arm.com                    # probably a fluke; ignore it
5989396Sandreas.hansson@arm.com                    com_pfx = ''
5999396Sandreas.hansson@arm.com        # recalculate length in case com_pfx was modified
6009396Sandreas.hansson@arm.com        com_pfx_len = len(com_pfx)
6019396Sandreas.hansson@arm.com        def fmt(files):
6029396Sandreas.hansson@arm.com            f = map(lambda s: s[com_pfx_len:], files)
6039477Sandreas.hansson@arm.com            return ', '.join(f)
6049477Sandreas.hansson@arm.com        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
6059477Sandreas.hansson@arm.com
6069477Sandreas.hansson@arm.comExport('Transform')
6079477Sandreas.hansson@arm.com
6089477Sandreas.hansson@arm.com# enable the regression script to use the termcap
6099477Sandreas.hansson@arm.commain['TERMCAP'] = termcap
6109477Sandreas.hansson@arm.com
6119477Sandreas.hansson@arm.comif GetOption('verbose'):
6129477Sandreas.hansson@arm.com    def MakeAction(action, string, *args, **kwargs):
6139477Sandreas.hansson@arm.com        return Action(action, *args, **kwargs)
6149477Sandreas.hansson@arm.comelse:
6159477Sandreas.hansson@arm.com    MakeAction = Action
6169477Sandreas.hansson@arm.com    main['CCCOMSTR']        = Transform("CC")
6179477Sandreas.hansson@arm.com    main['CXXCOMSTR']       = Transform("CXX")
6189477Sandreas.hansson@arm.com    main['ASCOMSTR']        = Transform("AS")
6199477Sandreas.hansson@arm.com    main['SWIGCOMSTR']      = Transform("SWIG")
6209477Sandreas.hansson@arm.com    main['ARCOMSTR']        = Transform("AR", 0)
6219477Sandreas.hansson@arm.com    main['LINKCOMSTR']      = Transform("LINK", 0)
6229477Sandreas.hansson@arm.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
6239477Sandreas.hansson@arm.com    main['M4COMSTR']        = Transform("M4")
6249477Sandreas.hansson@arm.com    main['SHCCCOMSTR']      = Transform("SHCC")
6259396Sandreas.hansson@arm.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
6262667Sstever@eecs.umich.eduExport('MakeAction')
62710710Sandreas.hansson@arm.com
62810710Sandreas.hansson@arm.com# Initialize the Link-Time Optimization (LTO) flags
62910710Sandreas.hansson@arm.commain['LTO_CCFLAGS'] = []
63011811Sbaz21@cam.ac.ukmain['LTO_LDFLAGS'] = []
63111811Sbaz21@cam.ac.uk
63211811Sbaz21@cam.ac.uk# According to the readme, tcmalloc works best if the compiler doesn't
63311811Sbaz21@cam.ac.uk# assume that we're using the builtin malloc and friends. These flags
63411811Sbaz21@cam.ac.uk# are compiler-specific, so we need to set them after we detect which
63511811Sbaz21@cam.ac.uk# compiler we're using.
63610710Sandreas.hansson@arm.commain['TCMALLOC_CCFLAGS'] = []
63710710Sandreas.hansson@arm.com
63810710Sandreas.hansson@arm.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
63910710Sandreas.hansson@arm.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
64010384SCurtis.Dunham@arm.com
6419986Sandreas@sandberg.pp.semain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
6429986Sandreas@sandberg.pp.semain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
6439986Sandreas@sandberg.pp.seif main['GCC'] + main['CLANG'] > 1:
6449986Sandreas@sandberg.pp.se    print 'Error: How can we have two at the same time?'
6459986Sandreas@sandberg.pp.se    Exit(1)
6469986Sandreas@sandberg.pp.se
6479986Sandreas@sandberg.pp.se# Set up default C++ compiler flags
6489986Sandreas@sandberg.pp.seif main['GCC'] or main['CLANG']:
6499986Sandreas@sandberg.pp.se    # As gcc and clang share many flags, do the common parts here
6509986Sandreas@sandberg.pp.se    main.Append(CCFLAGS=['-pipe'])
6519986Sandreas@sandberg.pp.se    main.Append(CCFLAGS=['-fno-strict-aliasing'])
6529986Sandreas@sandberg.pp.se    # Enable -Wall and -Wextra and then disable the few warnings that
6539986Sandreas@sandberg.pp.se    # we consistently violate
6549986Sandreas@sandberg.pp.se    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
6559986Sandreas@sandberg.pp.se                         '-Wno-sign-compare', '-Wno-unused-parameter'])
6569986Sandreas@sandberg.pp.se    # We always compile using C++11
6579986Sandreas@sandberg.pp.se    main.Append(CXXFLAGS=['-std=c++11'])
6589986Sandreas@sandberg.pp.se    if sys.platform.startswith('freebsd'):
6599986Sandreas@sandberg.pp.se        main.Append(CCFLAGS=['-I/usr/local/include'])
6609986Sandreas@sandberg.pp.se        main.Append(CXXFLAGS=['-I/usr/local/include'])
6612638Sstever@eecs.umich.eduelse:
6622638Sstever@eecs.umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6636121Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
6643716Sstever@eecs.umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6655522Snate@binkert.org    print termcap.Yellow + '       version:' + termcap.Normal,
6669986Sandreas@sandberg.pp.se    if not CXX_version:
6679986Sandreas@sandberg.pp.se        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6689986Sandreas@sandberg.pp.se               termcap.Normal
6695522Snate@binkert.org    else:
6705227Ssaidi@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
6715227Ssaidi@eecs.umich.edu    print "       If you're trying to use a compiler other than GCC"
6725227Ssaidi@eecs.umich.edu    print "       or clang, there appears to be something wrong with your"
6735227Ssaidi@eecs.umich.edu    print "       environment."
6746654Snate@binkert.org    print "       "
6756654Snate@binkert.org    print "       If you are trying to use a compiler other than those listed"
6767769SAli.Saidi@ARM.com    print "       above you will need to ease fix SConstruct and "
6777769SAli.Saidi@ARM.com    print "       src/SConscript to support that compiler."
6787769SAli.Saidi@ARM.com    Exit(1)
6797769SAli.Saidi@ARM.com
6805227Ssaidi@eecs.umich.eduif main['GCC']:
6815227Ssaidi@eecs.umich.edu    # Check for a supported version of gcc. >= 4.8 is chosen for its
6825227Ssaidi@eecs.umich.edu    # level of c++11 support. See
6835204Sstever@gmail.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
6845204Sstever@gmail.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
6855204Sstever@gmail.com    if compareVersions(gcc_version, "4.8") < 0:
6865204Sstever@gmail.com        print 'Error: gcc version 4.8 or newer required.'
6875204Sstever@gmail.com        print '       Installed version:', gcc_version
6885204Sstever@gmail.com        Exit(1)
6895204Sstever@gmail.com
6905204Sstever@gmail.com    main['GCC_VERSION'] = gcc_version
6915204Sstever@gmail.com
6925204Sstever@gmail.com    # gcc from version 4.8 and above generates "rep; ret" instructions
6935204Sstever@gmail.com    # to avoid performance penalties on certain AMD chips. Older
6945204Sstever@gmail.com    # assemblers detect this as an error, "Error: expecting string
6955204Sstever@gmail.com    # instruction after `rep'"
6965204Sstever@gmail.com    as_version_raw = readCommand([main['AS'], '-v', '/dev/null'],
6975204Sstever@gmail.com                                 exception=False).split()
6985204Sstever@gmail.com
6995204Sstever@gmail.com    # version strings may contain extra distro-specific
7006121Snate@binkert.org    # qualifiers, so play it safe and keep only what comes before
7015204Sstever@gmail.com    # the first hyphen
7027727SAli.Saidi@ARM.com    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
7037727SAli.Saidi@ARM.com
7047727SAli.Saidi@ARM.com    if not as_version or compareVersions(as_version, "2.23") < 0:
7057727SAli.Saidi@ARM.com        print termcap.Yellow + termcap.Bold + \
7067727SAli.Saidi@ARM.com            'Warning: This combination of gcc and binutils have' + \
70711988Sandreas.sandberg@arm.com            ' known incompatibilities.\n' + \
70811988Sandreas.sandberg@arm.com            '         If you encounter build problems, please update ' + \
70910453SAndrew.Bardsley@arm.com            'binutils to 2.23.' + \
71010453SAndrew.Bardsley@arm.com            termcap.Normal
71110453SAndrew.Bardsley@arm.com
71210453SAndrew.Bardsley@arm.com    # Make sure we warn if the user has requested to compile with the
71310453SAndrew.Bardsley@arm.com    # Undefined Benahvior Sanitizer and this version of gcc does not
71410453SAndrew.Bardsley@arm.com    # support it.
71510453SAndrew.Bardsley@arm.com    if GetOption('with_ubsan') and \
71610453SAndrew.Bardsley@arm.com            compareVersions(gcc_version, '4.9') < 0:
71710453SAndrew.Bardsley@arm.com        print termcap.Yellow + termcap.Bold + \
71810453SAndrew.Bardsley@arm.com            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
71910160Sandreas.hansson@arm.com            termcap.Normal
72010453SAndrew.Bardsley@arm.com
72110453SAndrew.Bardsley@arm.com    # Add the appropriate Link-Time Optimization (LTO) flags
72210453SAndrew.Bardsley@arm.com    # unless LTO is explicitly turned off. Note that these flags
72310453SAndrew.Bardsley@arm.com    # are only used by the fast target.
72410453SAndrew.Bardsley@arm.com    if not GetOption('no_lto'):
72510453SAndrew.Bardsley@arm.com        # Pass the LTO flag when compiling to produce GIMPLE
72610453SAndrew.Bardsley@arm.com        # output, we merely create the flags here and only append
72710453SAndrew.Bardsley@arm.com        # them later
7289812Sandreas.hansson@arm.com        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
72910453SAndrew.Bardsley@arm.com
73010453SAndrew.Bardsley@arm.com        # Use the same amount of jobs for LTO as we are running
73110453SAndrew.Bardsley@arm.com        # scons with
73210453SAndrew.Bardsley@arm.com        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
73310453SAndrew.Bardsley@arm.com
73410453SAndrew.Bardsley@arm.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
73510453SAndrew.Bardsley@arm.com                                  '-fno-builtin-realloc', '-fno-builtin-free'])
73610453SAndrew.Bardsley@arm.com
73710453SAndrew.Bardsley@arm.com    # add option to check for undeclared overrides
73810453SAndrew.Bardsley@arm.com    if compareVersions(gcc_version, "5.0") > 0:
73910453SAndrew.Bardsley@arm.com        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
74010453SAndrew.Bardsley@arm.com
7417727SAli.Saidi@ARM.comelif main['CLANG']:
74210453SAndrew.Bardsley@arm.com    # Check for a supported version of clang, >= 3.1 is needed to
74310453SAndrew.Bardsley@arm.com    # support similar features as gcc 4.8. See
74410453SAndrew.Bardsley@arm.com    # http://clang.llvm.org/cxx_status.html for details
74510453SAndrew.Bardsley@arm.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
74610453SAndrew.Bardsley@arm.com    clang_version_match = clang_version_re.search(CXX_version)
7473118Sstever@eecs.umich.edu    if (clang_version_match):
74810453SAndrew.Bardsley@arm.com        clang_version = clang_version_match.groups()[0]
74910453SAndrew.Bardsley@arm.com        if compareVersions(clang_version, "3.1") < 0:
75010453SAndrew.Bardsley@arm.com            print 'Error: clang version 3.1 or newer required.'
75110453SAndrew.Bardsley@arm.com            print '       Installed version:', clang_version
7523118Sstever@eecs.umich.edu            Exit(1)
7533483Ssaidi@eecs.umich.edu    else:
7543494Ssaidi@eecs.umich.edu        print 'Error: Unable to determine clang version.'
7553494Ssaidi@eecs.umich.edu        Exit(1)
7563483Ssaidi@eecs.umich.edu
7573483Ssaidi@eecs.umich.edu    # clang has a few additional warnings that we disable, extraneous
7583483Ssaidi@eecs.umich.edu    # parantheses are allowed due to Ruby's printing of the AST,
7593053Sstever@eecs.umich.edu    # finally self assignments are allowed as the generated CPU code
7603053Sstever@eecs.umich.edu    # is relying on this
7613918Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-Wno-parentheses',
7623053Sstever@eecs.umich.edu                         '-Wno-self-assign',
7633053Sstever@eecs.umich.edu                         # Some versions of libstdc++ (4.8?) seem to
7643053Sstever@eecs.umich.edu                         # use struct hash and class hash
7653053Sstever@eecs.umich.edu                         # interchangeably.
7663053Sstever@eecs.umich.edu                         '-Wno-mismatched-tags',
7679396Sandreas.hansson@arm.com                         ])
7689396Sandreas.hansson@arm.com
7699396Sandreas.hansson@arm.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
7709396Sandreas.hansson@arm.com
7719396Sandreas.hansson@arm.com    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
7729396Sandreas.hansson@arm.com    # opposed to libstdc++, as the later is dated.
7739396Sandreas.hansson@arm.com    if sys.platform == "darwin":
7749396Sandreas.hansson@arm.com        main.Append(CXXFLAGS=['-stdlib=libc++'])
7759396Sandreas.hansson@arm.com        main.Append(LIBS=['c++'])
7769477Sandreas.hansson@arm.com
7779396Sandreas.hansson@arm.com    # On FreeBSD we need libthr.
7789477Sandreas.hansson@arm.com    if sys.platform.startswith('freebsd'):
7799477Sandreas.hansson@arm.com        main.Append(LIBS=['thr'])
7809477Sandreas.hansson@arm.com
7819477Sandreas.hansson@arm.comelse:
7829396Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
7837840Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
7847865Sgblack@eecs.umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
7857865Sgblack@eecs.umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
7867865Sgblack@eecs.umich.edu    if not CXX_version:
7877865Sgblack@eecs.umich.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
7887865Sgblack@eecs.umich.edu               termcap.Normal
7897840Snate@binkert.org    else:
7909900Sandreas@sandberg.pp.se        print CXX_version.replace('\n', '<nl>')
7919900Sandreas@sandberg.pp.se    print "       If you're trying to use a compiler other than GCC"
7929900Sandreas@sandberg.pp.se    print "       or clang, there appears to be something wrong with your"
7939900Sandreas@sandberg.pp.se    print "       environment."
79410456SCurtis.Dunham@arm.com    print "       "
79510456SCurtis.Dunham@arm.com    print "       If you are trying to use a compiler other than those listed"
79610456SCurtis.Dunham@arm.com    print "       above you will need to ease fix SConstruct and "
79710456SCurtis.Dunham@arm.com    print "       src/SConscript to support that compiler."
79810456SCurtis.Dunham@arm.com    Exit(1)
79910456SCurtis.Dunham@arm.com
80010456SCurtis.Dunham@arm.com# Set up common yacc/bison flags (needed for Ruby)
80110456SCurtis.Dunham@arm.commain['YACCFLAGS'] = '-d'
80210456SCurtis.Dunham@arm.commain['YACCHXXFILESUFFIX'] = '.hh'
80310456SCurtis.Dunham@arm.com
8049045SAli.Saidi@ARM.com# Do this after we save setting back, or else we'll tack on an
80511235Sandreas.sandberg@arm.com# extra 'qdo' every time we run scons.
80611235Sandreas.sandberg@arm.comif main['BATCH']:
80711235Sandreas.sandberg@arm.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
80811235Sandreas.sandberg@arm.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
80911235Sandreas.sandberg@arm.com    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
81011235Sandreas.sandberg@arm.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
81111235Sandreas.sandberg@arm.com    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
81211235Sandreas.sandberg@arm.com
81311811Sbaz21@cam.ac.ukif sys.platform == 'cygwin':
81411811Sbaz21@cam.ac.uk    # cygwin has some header file issues...
81511811Sbaz21@cam.ac.uk    main.Append(CCFLAGS=["-Wno-uninitialized"])
81611811Sbaz21@cam.ac.uk
81711811Sbaz21@cam.ac.uk# Check for the protobuf compiler
81811235Sandreas.sandberg@arm.comprotoc_version = readCommand([main['PROTOC'], '--version'],
81911235Sandreas.sandberg@arm.com                             exception='').split()
82011235Sandreas.sandberg@arm.com
82111235Sandreas.sandberg@arm.com# First two words should be "libprotoc x.y.z"
82211235Sandreas.sandberg@arm.comif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
82311235Sandreas.sandberg@arm.com    print termcap.Yellow + termcap.Bold + \
82411235Sandreas.sandberg@arm.com        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
8257840Snate@binkert.org        '         Please install protobuf-compiler for tracing support.' + \
8267840Snate@binkert.org        termcap.Normal
8277840Snate@binkert.org    main['PROTOC'] = False
8281858SN/Aelse:
8291858SN/A    # Based on the availability of the compress stream wrappers,
8301858SN/A    # require 2.1.0
8311858SN/A    min_protoc_version = '2.1.0'
8321858SN/A    if compareVersions(protoc_version[1], min_protoc_version) < 0:
8331858SN/A        print termcap.Yellow + termcap.Bold + \
83412230Sgiacomo.travaglini@arm.com            'Warning: protoc version', min_protoc_version, \
83512230Sgiacomo.travaglini@arm.com            'or newer required.\n' + \
83612230Sgiacomo.travaglini@arm.com            '         Installed version:', protoc_version[1], \
83712230Sgiacomo.travaglini@arm.com            termcap.Normal
83812230Sgiacomo.travaglini@arm.com        main['PROTOC'] = False
83912230Sgiacomo.travaglini@arm.com    else:
84012230Sgiacomo.travaglini@arm.com        # Attempt to determine the appropriate include path and
84112230Sgiacomo.travaglini@arm.com        # library path using pkg-config, that means we also need to
8429903Sandreas.hansson@arm.com        # check for pkg-config. Note that it is possible to use
8439903Sandreas.hansson@arm.com        # protobuf without the involvement of pkg-config. Later on we
8449903Sandreas.hansson@arm.com        # check go a library config check and at that point the test
8459903Sandreas.hansson@arm.com        # will fail if libprotobuf cannot be found.
84610841Sandreas.sandberg@arm.com        if readCommand(['pkg-config', '--version'], exception=''):
8479651SAndreas.Sandberg@ARM.com            try:
8489903Sandreas.hansson@arm.com                # Attempt to establish what linking flags to add for protobuf
8499651SAndreas.Sandberg@ARM.com                # using pkg-config
8509651SAndreas.Sandberg@ARM.com                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
85112056Sgabeblack@google.com            except:
85212056Sgabeblack@google.com                print termcap.Yellow + termcap.Bold + \
85312056Sgabeblack@google.com                    'Warning: pkg-config could not get protobuf flags.' + \
85412056Sgabeblack@google.com                    termcap.Normal
85512056Sgabeblack@google.com
85610841Sandreas.sandberg@arm.com# Check for SWIG
85710841Sandreas.sandberg@arm.comif not main.has_key('SWIG'):
85810841Sandreas.sandberg@arm.com    print 'Error: SWIG utility not found.'
85910841Sandreas.sandberg@arm.com    print '       Please install (see http://www.swig.org) and retry.'
86010841Sandreas.sandberg@arm.com    Exit(1)
86110841Sandreas.sandberg@arm.com
8629651SAndreas.Sandberg@ARM.com# Check for appropriate SWIG version
8639651SAndreas.Sandberg@ARM.comswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
8649651SAndreas.Sandberg@ARM.com# First 3 words should be "SWIG Version x.y.z"
8659651SAndreas.Sandberg@ARM.comif len(swig_version) < 3 or \
8669651SAndreas.Sandberg@ARM.com        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
8679651SAndreas.Sandberg@ARM.com    print 'Error determining SWIG version.'
8689651SAndreas.Sandberg@ARM.com    Exit(1)
8699651SAndreas.Sandberg@ARM.com
8709651SAndreas.Sandberg@ARM.commin_swig_version = '2.0.4'
87110841Sandreas.sandberg@arm.comif compareVersions(swig_version[2], min_swig_version) < 0:
87210841Sandreas.sandberg@arm.com    print 'Error: SWIG version', min_swig_version, 'or newer required.'
87310841Sandreas.sandberg@arm.com    print '       Installed version:', swig_version[2]
87410841Sandreas.sandberg@arm.com    Exit(1)
87510841Sandreas.sandberg@arm.com
87610841Sandreas.sandberg@arm.com# Check for known incompatibilities. The standard library shipped with
87710860Sandreas.sandberg@arm.com# gcc >= 4.9 does not play well with swig versions prior to 3.0
87810841Sandreas.sandberg@arm.comif main['GCC'] and compareVersions(gcc_version, '4.9') >= 0 and \
87910841Sandreas.sandberg@arm.com        compareVersions(swig_version[2], '3.0') < 0:
88010841Sandreas.sandberg@arm.com    print termcap.Yellow + termcap.Bold + \
88110841Sandreas.sandberg@arm.com        'Warning: This combination of gcc and swig have' + \
88210841Sandreas.sandberg@arm.com        ' known incompatibilities.\n' + \
88310841Sandreas.sandberg@arm.com        '         If you encounter build problems, please update ' + \
88410841Sandreas.sandberg@arm.com        'swig to 3.0 or later.' + \
88510841Sandreas.sandberg@arm.com        termcap.Normal
88610841Sandreas.sandberg@arm.com
88710841Sandreas.sandberg@arm.com# Set up SWIG flags & scanner
88810841Sandreas.sandberg@arm.comswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
8899651SAndreas.Sandberg@ARM.commain.Append(SWIGFLAGS=swig_flags)
8909651SAndreas.Sandberg@ARM.com
8919986Sandreas@sandberg.pp.se# Check for 'timeout' from GNU coreutils. If present, regressions will
8929986Sandreas@sandberg.pp.se# be run with a time limit. We require version 8.13 since we rely on
8939986Sandreas@sandberg.pp.se# support for the '--foreground' option.
8949986Sandreas@sandberg.pp.seif sys.platform.startswith('freebsd'):
8959986Sandreas@sandberg.pp.se    timeout_lines = readCommand(['gtimeout', '--version'],
8969986Sandreas@sandberg.pp.se                                exception='').splitlines()
8975863Snate@binkert.orgelse:
8985863Snate@binkert.org    timeout_lines = readCommand(['timeout', '--version'],
8995863Snate@binkert.org                                exception='').splitlines()
9005863Snate@binkert.org# Get the first line and tokenize it
9016121Snate@binkert.orgtimeout_version = timeout_lines[0].split() if timeout_lines else []
9021858SN/Amain['TIMEOUT'] =  timeout_version and \
9035863Snate@binkert.org    compareVersions(timeout_version[-1], '8.13') >= 0
9045863Snate@binkert.org
9055863Snate@binkert.org# filter out all existing swig scanners, they mess up the dependency
9065863Snate@binkert.org# stuff for some reason
9075863Snate@binkert.orgscanners = []
9082139SN/Afor scanner in main['SCANNERS']:
9094202Sbinkertn@umich.edu    skeys = scanner.skeys
91011308Santhony.gutierrez@amd.com    if skeys == '.i':
9114202Sbinkertn@umich.edu        continue
91211308Santhony.gutierrez@amd.com
9132139SN/A    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
9146994Snate@binkert.org        continue
9156994Snate@binkert.org
9166994Snate@binkert.org    scanners.append(scanner)
9176994Snate@binkert.org
9186994Snate@binkert.org# add the new swig scanner that we like better
9196994Snate@binkert.orgfrom SCons.Scanner import ClassicCPP as CPPScanner
9206994Snate@binkert.orgswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
9216994Snate@binkert.orgscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
92210319SAndreas.Sandberg@ARM.com
9236994Snate@binkert.org# replace the scanners list that has what we want
9246994Snate@binkert.orgmain['SCANNERS'] = scanners
9256994Snate@binkert.org
9266994Snate@binkert.org# Add a custom Check function to test for structure members.
9276994Snate@binkert.orgdef CheckMember(context, include, decl, member, include_quotes="<>"):
9286994Snate@binkert.org    context.Message("Checking for member %s in %s..." %
9296994Snate@binkert.org                    (member, decl))
9306994Snate@binkert.org    text = """
9316994Snate@binkert.org#include %(header)s
9326994Snate@binkert.orgint main(){
9336994Snate@binkert.org  %(decl)s test;
9342155SN/A  (void)test.%(member)s;
9355863Snate@binkert.org  return 0;
9361869SN/A};
9371869SN/A""" % { "header" : include_quotes[0] + include + include_quotes[1],
9385863Snate@binkert.org        "decl" : decl,
9395863Snate@binkert.org        "member" : member,
9404202Sbinkertn@umich.edu        }
9416108Snate@binkert.org
9426108Snate@binkert.org    ret = context.TryCompile(text, extension=".cc")
9436108Snate@binkert.org    context.Result(ret)
9446108Snate@binkert.org    return ret
9459219Spower.jg@gmail.com
9469219Spower.jg@gmail.com# Platform-specific configuration.  Note again that we assume that all
9479219Spower.jg@gmail.com# builds under a given build root run on the same host platform.
9489219Spower.jg@gmail.comconf = Configure(main,
9499219Spower.jg@gmail.com                 conf_dir = joinpath(build_root, '.scons_config'),
9509219Spower.jg@gmail.com                 log_file = joinpath(build_root, 'scons_config.log'),
9519219Spower.jg@gmail.com                 custom_tests = {
9529219Spower.jg@gmail.com        'CheckMember' : CheckMember,
9534202Sbinkertn@umich.edu        })
9545863Snate@binkert.org
95510135SCurtis.Dunham@arm.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
9568474Sgblack@eecs.umich.edutry:
9575742Snate@binkert.org    import platform
9588268Ssteve.reinhardt@amd.com    uname = platform.uname()
9598268Ssteve.reinhardt@amd.com    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
9608268Ssteve.reinhardt@amd.com        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
9615742Snate@binkert.org            main.Append(CCFLAGS=['-arch', 'x86_64'])
9625341Sstever@gmail.com            main.Append(CFLAGS=['-arch', 'x86_64'])
9638474Sgblack@eecs.umich.edu            main.Append(LINKFLAGS=['-arch', 'x86_64'])
9648474Sgblack@eecs.umich.edu            main.Append(ASFLAGS=['-arch', 'x86_64'])
9655342Sstever@gmail.comexcept:
9664202Sbinkertn@umich.edu    pass
9674202Sbinkertn@umich.edu
96811308Santhony.gutierrez@amd.com# Recent versions of scons substitute a "Null" object for Configure()
9694202Sbinkertn@umich.edu# when configuration isn't necessary, e.g., if the "--help" option is
9705863Snate@binkert.org# present.  Unfortuantely this Null object always returns false,
9715863Snate@binkert.org# breaking all our configuration checks.  We replace it with our own
97211308Santhony.gutierrez@amd.com# more optimistic null object that returns True instead.
9736994Snate@binkert.orgif not conf:
9746994Snate@binkert.org    def NullCheck(*args, **kwargs):
97510319SAndreas.Sandberg@ARM.com        return True
9765863Snate@binkert.org
9775863Snate@binkert.org    class NullConf:
9785863Snate@binkert.org        def __init__(self, env):
9795863Snate@binkert.org            self.env = env
9805863Snate@binkert.org        def Finish(self):
9815863Snate@binkert.org            return self.env
9825863Snate@binkert.org        def __getattr__(self, mname):
9835863Snate@binkert.org            return NullCheck
9847840Snate@binkert.org
9855863Snate@binkert.org    conf = NullConf(main)
98612230Sgiacomo.travaglini@arm.com
98712230Sgiacomo.travaglini@arm.com# Cache build files in the supplied directory.
98812230Sgiacomo.travaglini@arm.comif main['M5_BUILD_CACHE']:
98912230Sgiacomo.travaglini@arm.com    print 'Using build cache located at', main['M5_BUILD_CACHE']
99012230Sgiacomo.travaglini@arm.com    CacheDir(main['M5_BUILD_CACHE'])
99112056Sgabeblack@google.com
99212056Sgabeblack@google.comif not GetOption('without_python'):
99312056Sgabeblack@google.com    # Find Python include and library directories for embedding the
99411308Santhony.gutierrez@amd.com    # interpreter. We rely on python-config to resolve the appropriate
9959219Spower.jg@gmail.com    # includes and linker flags. ParseConfig does not seem to understand
9969219Spower.jg@gmail.com    # the more exotic linker flags such as -Xlinker and -export-dynamic so
99711235Sandreas.sandberg@arm.com    # we add them explicitly below. If you want to link in an alternate
99811235Sandreas.sandberg@arm.com    # version of python, see above for instructions on how to invoke
9991869SN/A    # scons with the appropriate PATH set.
10001858SN/A    #
10015863Snate@binkert.org    # First we check if python2-config exists, else we use python-config
100211308Santhony.gutierrez@amd.com    python_config = readCommand(['which', 'python2-config'],
100312061Sjason@lowepower.com                                exception='').strip()
100412230Sgiacomo.travaglini@arm.com    if not os.path.exists(python_config):
100512230Sgiacomo.travaglini@arm.com        python_config = readCommand(['which', 'python-config'],
10061858SN/A                                    exception='').strip()
1007955SN/A    py_includes = readCommand([python_config, '--includes'],
1008955SN/A                              exception='').split()
10091869SN/A    # Strip the -I from the include folders before adding them to the
10101869SN/A    # CPPPATH
10111869SN/A    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
10121869SN/A
10131869SN/A    # Read the linker flags and split them into libraries and other link
10145863Snate@binkert.org    # flags. The libraries are added later through the call the CheckLib.
10155863Snate@binkert.org    py_ld_flags = readCommand([python_config, '--ldflags'],
10165863Snate@binkert.org        exception='').split()
10171869SN/A    py_libs = []
10185863Snate@binkert.org    for lib in py_ld_flags:
10191869SN/A         if not lib.startswith('-l'):
10205863Snate@binkert.org             main.Append(LINKFLAGS=[lib])
10211869SN/A         else:
10221869SN/A             lib = lib[2:]
10231869SN/A             if lib not in py_libs:
10241869SN/A                 py_libs.append(lib)
10258483Sgblack@eecs.umich.edu
10261869SN/A    # verify that this stuff works
10271869SN/A    if not conf.CheckHeader('Python.h', '<>'):
10281869SN/A        print "Error: can't find Python.h header in", py_includes
10291869SN/A        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
10305863Snate@binkert.org        Exit(1)
10315863Snate@binkert.org
10321869SN/A    for lib in py_libs:
10335863Snate@binkert.org        if not conf.CheckLib(lib):
10345863Snate@binkert.org            print "Error: can't find library %s required by python" % lib
10353356Sbinkertn@umich.edu            Exit(1)
10363356Sbinkertn@umich.edu
10373356Sbinkertn@umich.edu# On Solaris you need to use libsocket for socket ops
10383356Sbinkertn@umich.eduif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
10393356Sbinkertn@umich.edu   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
10404781Snate@binkert.org       print "Can't find library with socket calls (e.g. accept())"
10415863Snate@binkert.org       Exit(1)
10425863Snate@binkert.org
10431869SN/A# Check for zlib.  If the check passes, libz will be automatically
10441869SN/A# added to the LIBS environment variable.
10451869SN/Aif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
10466121Snate@binkert.org    print 'Error: did not find needed zlib compression library '\
10471869SN/A          'and/or zlib.h header file.'
104811982Sgabeblack@google.com    print '       Please install zlib and try again.'
104911982Sgabeblack@google.com    Exit(1)
105011982Sgabeblack@google.com
105111982Sgabeblack@google.com# If we have the protobuf compiler, also make sure we have the
105211982Sgabeblack@google.com# development libraries. If the check passes, libprotobuf will be
105311982Sgabeblack@google.com# automatically added to the LIBS environment variable. After
105411982Sgabeblack@google.com# this, we can use the HAVE_PROTOBUF flag to determine if we have
105511982Sgabeblack@google.com# got both protoc and libprotobuf available.
105611982Sgabeblack@google.commain['HAVE_PROTOBUF'] = main['PROTOC'] and \
105711982Sgabeblack@google.com    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
105811982Sgabeblack@google.com                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
105911982Sgabeblack@google.com
106011982Sgabeblack@google.com# If we have the compiler but not the library, print another warning.
106111982Sgabeblack@google.comif main['PROTOC'] and not main['HAVE_PROTOBUF']:
106211982Sgabeblack@google.com    print termcap.Yellow + termcap.Bold + \
106311982Sgabeblack@google.com        'Warning: did not find protocol buffer library and/or headers.\n' + \
106411982Sgabeblack@google.com    '       Please install libprotobuf-dev for tracing support.' + \
106511982Sgabeblack@google.com    termcap.Normal
106611982Sgabeblack@google.com
106711982Sgabeblack@google.com# Check for librt.
106811982Sgabeblack@google.comhave_posix_clock = \
106911982Sgabeblack@google.com    conf.CheckLibWithHeader(None, 'time.h', 'C',
107011982Sgabeblack@google.com                            'clock_nanosleep(0,0,NULL,NULL);') or \
107111982Sgabeblack@google.com    conf.CheckLibWithHeader('rt', 'time.h', 'C',
107211982Sgabeblack@google.com                            'clock_nanosleep(0,0,NULL,NULL);')
107311982Sgabeblack@google.com
107411978Sgabeblack@google.comhave_posix_timers = \
107511978Sgabeblack@google.com    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
107612034Sgabeblack@google.com                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
107711978Sgabeblack@google.com
107811978Sgabeblack@google.comif not GetOption('without_tcmalloc'):
107911978Sgabeblack@google.com    if conf.CheckLib('tcmalloc'):
108012034Sgabeblack@google.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
108111978Sgabeblack@google.com    elif conf.CheckLib('tcmalloc_minimal'):
108211978Sgabeblack@google.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
108310915Sandreas.sandberg@arm.com    else:
108411986Sandreas.sandberg@arm.com        print termcap.Yellow + termcap.Bold + \
108511986Sandreas.sandberg@arm.com              "You can get a 12% performance improvement by "\
10861869SN/A              "installing tcmalloc (libgoogle-perftools-dev package "\
10871869SN/A              "on Ubuntu or RedHat)." + termcap.Normal
108812015Sgabeblack@google.com
108912015Sgabeblack@google.com
109012015Sgabeblack@google.com# Detect back trace implementations. The last implementation in the
109112015Sgabeblack@google.com# list will be used by default.
10923546Sgblack@eecs.umich.edubacktrace_impls = [ "none" ]
10933546Sgblack@eecs.umich.edu
10943546Sgblack@eecs.umich.eduif conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
109512015Sgabeblack@google.com                           'backtrace_symbols_fd((void*)0, 0, 0);'):
109612015Sgabeblack@google.com    backtrace_impls.append("glibc")
109712015Sgabeblack@google.comelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
109812015Sgabeblack@google.com                           'backtrace_symbols_fd((void*)0, 0, 0);'):
109912015Sgabeblack@google.com    # NetBSD and FreeBSD need libexecinfo.
110012015Sgabeblack@google.com    backtrace_impls.append("glibc")
110112015Sgabeblack@google.com    main.Append(LIBS=['execinfo'])
110212015Sgabeblack@google.com
11033546Sgblack@eecs.umich.eduif backtrace_impls[-1] == "none":
110412015Sgabeblack@google.com    default_backtrace_impl = "none"
110512015Sgabeblack@google.com    print termcap.Yellow + termcap.Bold + \
110610196SCurtis.Dunham@arm.com        "No suitable back trace implementation found." + \
110712015Sgabeblack@google.com        termcap.Normal
110812015Sgabeblack@google.com
110912015Sgabeblack@google.comif not have_posix_clock:
111012015Sgabeblack@google.com    print "Can't find library for POSIX clocks."
111112015Sgabeblack@google.com
111212015Sgabeblack@google.com# Check for <fenv.h> (C99 FP environment control)
111312015Sgabeblack@google.comhave_fenv = conf.CheckHeader('fenv.h', '<>')
111412015Sgabeblack@google.comif not have_fenv:
111512015Sgabeblack@google.com    print "Warning: Header file <fenv.h> not found."
111612015Sgabeblack@google.com    print "         This host has no IEEE FP rounding mode control."
111712015Sgabeblack@google.com
11183546Sgblack@eecs.umich.edu# Check if we should enable KVM-based hardware virtualization. The API
11193546Sgblack@eecs.umich.edu# we rely on exists since version 2.6.36 of the kernel, but somehow
11203546Sgblack@eecs.umich.edu# the KVM_API_VERSION does not reflect the change. We test for one of
1121955SN/A# the types as a fall back.
1122955SN/Ahave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
1123955SN/Aif not have_kvm:
1124955SN/A    print "Info: Compatible header file <linux/kvm.h> not found, " \
11255863Snate@binkert.org        "disabling KVM support."
112610135SCurtis.Dunham@arm.com
112710135SCurtis.Dunham@arm.com# x86 needs support for xsave. We test for the structure here since we
11285343Sstever@gmail.com# won't be able to run new tests by the time we know which ISA we're
11295343Sstever@gmail.com# targeting.
11306121Snate@binkert.orghave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
11315863Snate@binkert.org                                    '#include <linux/kvm.h>') != 0
11324773Snate@binkert.org
11335863Snate@binkert.org# Check if the requested target ISA is compatible with the host
11342632Sstever@eecs.umich.edudef is_isa_kvm_compatible(isa):
11355863Snate@binkert.org    try:
11362023SN/A        import platform
11375863Snate@binkert.org        host_isa = platform.machine()
11385863Snate@binkert.org    except:
11395863Snate@binkert.org        print "Warning: Failed to determine host ISA."
11405863Snate@binkert.org        return False
11415863Snate@binkert.org
11425863Snate@binkert.org    if not have_posix_timers:
11435863Snate@binkert.org        print "Warning: Can not enable KVM, host seems to lack support " \
11445863Snate@binkert.org            "for POSIX timers"
114510135SCurtis.Dunham@arm.com        return False
114610135SCurtis.Dunham@arm.com
114712034Sgabeblack@google.com    if isa == "arm":
114812034Sgabeblack@google.com        return host_isa in ( "armv7l", "aarch64" )
114912034Sgabeblack@google.com    elif isa == "x86":
11502632Sstever@eecs.umich.edu        if host_isa != "x86_64":
11515863Snate@binkert.org            return False
11522023SN/A
11532632Sstever@eecs.umich.edu        if not have_kvm_xsave:
11545863Snate@binkert.org            print "KVM on x86 requires xsave support in kernel headers."
11555342Sstever@gmail.com            return False
11565863Snate@binkert.org
11572632Sstever@eecs.umich.edu        return True
11585863Snate@binkert.org    else:
11595863Snate@binkert.org        return False
11608267Ssteve.reinhardt@amd.com
11618120Sgblack@eecs.umich.edu
11628267Ssteve.reinhardt@amd.com# Check if the exclude_host attribute is available. We want this to
11638267Ssteve.reinhardt@amd.com# get accurate instruction counts in KVM.
11648267Ssteve.reinhardt@amd.commain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
11658267Ssteve.reinhardt@amd.com    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
11668267Ssteve.reinhardt@amd.com
11678267Ssteve.reinhardt@amd.com
11688267Ssteve.reinhardt@amd.com######################################################################
11698267Ssteve.reinhardt@amd.com#
11708267Ssteve.reinhardt@amd.com# Finish the configuration
11715863Snate@binkert.org#
11725863Snate@binkert.orgmain = conf.Finish()
11735863Snate@binkert.org
11742632Sstever@eecs.umich.edu######################################################################
11758267Ssteve.reinhardt@amd.com#
11768267Ssteve.reinhardt@amd.com# Collect all non-global variables
11778267Ssteve.reinhardt@amd.com#
11782632Sstever@eecs.umich.edu
11791888SN/A# Define the universe of supported ISAs
11805863Snate@binkert.orgall_isa_list = [ ]
11815863Snate@binkert.orgall_gpu_isa_list = [ ]
11821858SN/AExport('all_isa_list')
11838120Sgblack@eecs.umich.eduExport('all_gpu_isa_list')
11848120Sgblack@eecs.umich.edu
11857756SAli.Saidi@ARM.comclass CpuModel(object):
11862598SN/A    '''The CpuModel class encapsulates everything the ISA parser needs to
11875863Snate@binkert.org    know about a particular CPU model.'''
11881858SN/A
11891858SN/A    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
11901858SN/A    dict = {}
11915863Snate@binkert.org
11921858SN/A    # Constructor.  Automatically adds models to CpuModel.dict.
11931858SN/A    def __init__(self, name, default=False):
11941858SN/A        self.name = name           # name of model
11955863Snate@binkert.org
11961871SN/A        # This cpu is enabled by default
11971858SN/A        self.default = default
119812230Sgiacomo.travaglini@arm.com
119912230Sgiacomo.travaglini@arm.com        # Add self to dict
120012230Sgiacomo.travaglini@arm.com        if name in CpuModel.dict:
120112230Sgiacomo.travaglini@arm.com            raise AttributeError, "CpuModel '%s' already registered" % name
120212230Sgiacomo.travaglini@arm.com        CpuModel.dict[name] = self
120312230Sgiacomo.travaglini@arm.com
120412230Sgiacomo.travaglini@arm.comExport('CpuModel')
120512230Sgiacomo.travaglini@arm.com
12061858SN/A# Sticky variables get saved in the variables file so they persist from
12071858SN/A# one invocation to the next (unless overridden, in which case the new
12081858SN/A# value becomes sticky).
12099651SAndreas.Sandberg@ARM.comsticky_vars = Variables(args=ARGUMENTS)
12109651SAndreas.Sandberg@ARM.comExport('sticky_vars')
12119651SAndreas.Sandberg@ARM.com
12129651SAndreas.Sandberg@ARM.com# Sticky variables that should be exported
12139651SAndreas.Sandberg@ARM.comexport_vars = []
12149651SAndreas.Sandberg@ARM.comExport('export_vars')
12159651SAndreas.Sandberg@ARM.com
12169651SAndreas.Sandberg@ARM.com# For Ruby
12179651SAndreas.Sandberg@ARM.comall_protocols = []
121812056Sgabeblack@google.comExport('all_protocols')
121912056Sgabeblack@google.comprotocol_dirs = []
122012056Sgabeblack@google.comExport('protocol_dirs')
122112056Sgabeblack@google.comslicc_includes = []
122212056Sgabeblack@google.comExport('slicc_includes')
122311798Santhony.gutierrez@amd.com
122411798Santhony.gutierrez@amd.com# Walk the tree and execute all SConsopts scripts that wil add to the
122511798Santhony.gutierrez@amd.com# above variables
12269986Sandreas@sandberg.pp.seif GetOption('verbose'):
12279986Sandreas@sandberg.pp.se    print "Reading SConsopts"
12289986Sandreas@sandberg.pp.sefor bdir in [ base_dir ] + extras_dir_list:
12299986Sandreas@sandberg.pp.se    if not isdir(bdir):
12309986Sandreas@sandberg.pp.se        print "Error: directory '%s' does not exist" % bdir
12319986Sandreas@sandberg.pp.se        Exit(1)
12329986Sandreas@sandberg.pp.se    for root, dirs, files in os.walk(bdir):
12335863Snate@binkert.org        if 'SConsopts' in files:
12345863Snate@binkert.org            if GetOption('verbose'):
12351869SN/A                print "Reading", joinpath(root, 'SConsopts')
12361965SN/A            SConscript(joinpath(root, 'SConsopts'))
12377739Sgblack@eecs.umich.edu
12381965SN/Aall_isa_list.sort()
12392761Sstever@eecs.umich.eduall_gpu_isa_list.sort()
12405863Snate@binkert.org
12411869SN/Asticky_vars.AddVariables(
124210196SCurtis.Dunham@arm.com    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
12431869SN/A    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
12448120Sgblack@eecs.umich.edu    ListVariable('CPU_MODELS', 'CPU models',
12458120Sgblack@eecs.umich.edu                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
12468120Sgblack@eecs.umich.edu                 sorted(CpuModel.dict.keys())),
12478120Sgblack@eecs.umich.edu    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
12488120Sgblack@eecs.umich.edu                 False),
12498120Sgblack@eecs.umich.edu    BoolVariable('SS_COMPATIBLE_FP',
12508120Sgblack@eecs.umich.edu                 'Make floating-point results compatible with SimpleScalar',
12518120Sgblack@eecs.umich.edu                 False),
12528120Sgblack@eecs.umich.edu    BoolVariable('USE_SSE2',
12538120Sgblack@eecs.umich.edu                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
12548120Sgblack@eecs.umich.edu                 False),
12558120Sgblack@eecs.umich.edu    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
1256    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
1257    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
1258    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
1259    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
1260    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1261                  all_protocols),
1262    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
1263                 backtrace_impls[-1], backtrace_impls)
1264    )
1265
1266# These variables get exported to #defines in config/*.hh (see src/SConscript).
1267export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
1268                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'PROTOCOL',
1269                'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST']
1270
1271###################################################
1272#
1273# Define a SCons builder for configuration flag headers.
1274#
1275###################################################
1276
1277# This function generates a config header file that #defines the
1278# variable symbol to the current variable setting (0 or 1).  The source
1279# operands are the name of the variable and a Value node containing the
1280# value of the variable.
1281def build_config_file(target, source, env):
1282    (variable, value) = [s.get_contents() for s in source]
1283    f = file(str(target[0]), 'w')
1284    print >> f, '#define', variable, value
1285    f.close()
1286    return None
1287
1288# Combine the two functions into a scons Action object.
1289config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1290
1291# The emitter munges the source & target node lists to reflect what
1292# we're really doing.
1293def config_emitter(target, source, env):
1294    # extract variable name from Builder arg
1295    variable = str(target[0])
1296    # True target is config header file
1297    target = joinpath('config', variable.lower() + '.hh')
1298    val = env[variable]
1299    if isinstance(val, bool):
1300        # Force value to 0/1
1301        val = int(val)
1302    elif isinstance(val, str):
1303        val = '"' + val + '"'
1304
1305    # Sources are variable name & value (packaged in SCons Value nodes)
1306    return ([target], [Value(variable), Value(val)])
1307
1308config_builder = Builder(emitter = config_emitter, action = config_action)
1309
1310main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1311
1312# libelf build is shared across all configs in the build root.
1313main.SConscript('ext/libelf/SConscript',
1314                variant_dir = joinpath(build_root, 'libelf'))
1315
1316# iostream3 build is shared across all configs in the build root.
1317main.SConscript('ext/iostream3/SConscript',
1318                variant_dir = joinpath(build_root, 'iostream3'))
1319
1320# libfdt build is shared across all configs in the build root.
1321main.SConscript('ext/libfdt/SConscript',
1322                variant_dir = joinpath(build_root, 'libfdt'))
1323
1324# fputils build is shared across all configs in the build root.
1325main.SConscript('ext/fputils/SConscript',
1326                variant_dir = joinpath(build_root, 'fputils'))
1327
1328# DRAMSim2 build is shared across all configs in the build root.
1329main.SConscript('ext/dramsim2/SConscript',
1330                variant_dir = joinpath(build_root, 'dramsim2'))
1331
1332# DRAMPower build is shared across all configs in the build root.
1333main.SConscript('ext/drampower/SConscript',
1334                variant_dir = joinpath(build_root, 'drampower'))
1335
1336# nomali build is shared across all configs in the build root.
1337main.SConscript('ext/nomali/SConscript',
1338                variant_dir = joinpath(build_root, 'nomali'))
1339
1340###################################################
1341#
1342# This function is used to set up a directory with switching headers
1343#
1344###################################################
1345
1346main['ALL_ISA_LIST'] = all_isa_list
1347main['ALL_GPU_ISA_LIST'] = all_gpu_isa_list
1348all_isa_deps = {}
1349def make_switching_dir(dname, switch_headers, env):
1350    # Generate the header.  target[0] is the full path of the output
1351    # header to generate.  'source' is a dummy variable, since we get the
1352    # list of ISAs from env['ALL_ISA_LIST'].
1353    def gen_switch_hdr(target, source, env):
1354        fname = str(target[0])
1355        isa = env['TARGET_ISA'].lower()
1356        try:
1357            f = open(fname, 'w')
1358            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1359            f.close()
1360        except IOError:
1361            print "Failed to create %s" % fname
1362            raise
1363
1364    # Build SCons Action object. 'varlist' specifies env vars that this
1365    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1366    # should get re-executed.
1367    switch_hdr_action = MakeAction(gen_switch_hdr,
1368                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1369
1370    # Instantiate actions for each header
1371    for hdr in switch_headers:
1372        env.Command(hdr, [], switch_hdr_action)
1373
1374    isa_target = Dir('.').up().name.lower().replace('_', '-')
1375    env['PHONY_BASE'] = '#'+isa_target
1376    all_isa_deps[isa_target] = None
1377
1378Export('make_switching_dir')
1379
1380def make_gpu_switching_dir(dname, switch_headers, env):
1381    # Generate the header.  target[0] is the full path of the output
1382    # header to generate.  'source' is a dummy variable, since we get the
1383    # list of ISAs from env['ALL_ISA_LIST'].
1384    def gen_switch_hdr(target, source, env):
1385        fname = str(target[0])
1386
1387        isa = env['TARGET_GPU_ISA'].lower()
1388
1389        try:
1390            f = open(fname, 'w')
1391            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1392            f.close()
1393        except IOError:
1394            print "Failed to create %s" % fname
1395            raise
1396
1397    # Build SCons Action object. 'varlist' specifies env vars that this
1398    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1399    # should get re-executed.
1400    switch_hdr_action = MakeAction(gen_switch_hdr,
1401                          Transform("GENERATE"), varlist=['ALL_ISA_GPU_LIST'])
1402
1403    # Instantiate actions for each header
1404    for hdr in switch_headers:
1405        env.Command(hdr, [], switch_hdr_action)
1406
1407Export('make_gpu_switching_dir')
1408
1409# all-isas -> all-deps -> all-environs -> all_targets
1410main.Alias('#all-isas', [])
1411main.Alias('#all-deps', '#all-isas')
1412
1413# Dummy target to ensure all environments are created before telling
1414# SCons what to actually make (the command line arguments).  We attach
1415# them to the dependence graph after the environments are complete.
1416ORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
1417def environsComplete(target, source, env):
1418    for t in ORIG_BUILD_TARGETS:
1419        main.Depends('#all-targets', t)
1420
1421# Each build/* switching_dir attaches its *-environs target to #all-environs.
1422main.Append(BUILDERS = {'CompleteEnvirons' :
1423                        Builder(action=MakeAction(environsComplete, None))})
1424main.CompleteEnvirons('#all-environs', [])
1425
1426def doNothing(**ignored): pass
1427main.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
1428
1429# The final target to which all the original targets ultimately get attached.
1430main.Dummy('#all-targets', '#all-environs')
1431BUILD_TARGETS[:] = ['#all-targets']
1432
1433###################################################
1434#
1435# Define build environments for selected configurations.
1436#
1437###################################################
1438
1439for variant_path in variant_paths:
1440    if not GetOption('silent'):
1441        print "Building in", variant_path
1442
1443    # Make a copy of the build-root environment to use for this config.
1444    env = main.Clone()
1445    env['BUILDDIR'] = variant_path
1446
1447    # variant_dir is the tail component of build path, and is used to
1448    # determine the build parameters (e.g., 'ALPHA_SE')
1449    (build_root, variant_dir) = splitpath(variant_path)
1450
1451    # Set env variables according to the build directory config.
1452    sticky_vars.files = []
1453    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1454    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1455    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1456    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1457    if isfile(current_vars_file):
1458        sticky_vars.files.append(current_vars_file)
1459        if not GetOption('silent'):
1460            print "Using saved variables file %s" % current_vars_file
1461    else:
1462        # Build dir-specific variables file doesn't exist.
1463
1464        # Make sure the directory is there so we can create it later
1465        opt_dir = dirname(current_vars_file)
1466        if not isdir(opt_dir):
1467            mkdir(opt_dir)
1468
1469        # Get default build variables from source tree.  Variables are
1470        # normally determined by name of $VARIANT_DIR, but can be
1471        # overridden by '--default=' arg on command line.
1472        default = GetOption('default')
1473        opts_dir = joinpath(main.root.abspath, 'build_opts')
1474        if default:
1475            default_vars_files = [joinpath(build_root, 'variables', default),
1476                                  joinpath(opts_dir, default)]
1477        else:
1478            default_vars_files = [joinpath(opts_dir, variant_dir)]
1479        existing_files = filter(isfile, default_vars_files)
1480        if existing_files:
1481            default_vars_file = existing_files[0]
1482            sticky_vars.files.append(default_vars_file)
1483            print "Variables file %s not found,\n  using defaults in %s" \
1484                  % (current_vars_file, default_vars_file)
1485        else:
1486            print "Error: cannot find variables file %s or " \
1487                  "default file(s) %s" \
1488                  % (current_vars_file, ' or '.join(default_vars_files))
1489            Exit(1)
1490
1491    # Apply current variable settings to env
1492    sticky_vars.Update(env)
1493
1494    help_texts["local_vars"] += \
1495        "Build variables for %s:\n" % variant_dir \
1496                 + sticky_vars.GenerateHelpText(env)
1497
1498    # Process variable settings.
1499
1500    if not have_fenv and env['USE_FENV']:
1501        print "Warning: <fenv.h> not available; " \
1502              "forcing USE_FENV to False in", variant_dir + "."
1503        env['USE_FENV'] = False
1504
1505    if not env['USE_FENV']:
1506        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1507        print "         FP results may deviate slightly from other platforms."
1508
1509    if env['EFENCE']:
1510        env.Append(LIBS=['efence'])
1511
1512    if env['USE_KVM']:
1513        if not have_kvm:
1514            print "Warning: Can not enable KVM, host seems to lack KVM support"
1515            env['USE_KVM'] = False
1516        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1517            print "Info: KVM support disabled due to unsupported host and " \
1518                "target ISA combination"
1519            env['USE_KVM'] = False
1520
1521    if env['BUILD_GPU']:
1522        env.Append(CPPDEFINES=['BUILD_GPU'])
1523
1524    # Warn about missing optional functionality
1525    if env['USE_KVM']:
1526        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1527            print "Warning: perf_event headers lack support for the " \
1528                "exclude_host attribute. KVM instruction counts will " \
1529                "be inaccurate."
1530
1531    # Save sticky variable settings back to current variables file
1532    sticky_vars.Save(current_vars_file, env)
1533
1534    if env['USE_SSE2']:
1535        env.Append(CCFLAGS=['-msse2'])
1536
1537    # The src/SConscript file sets up the build rules in 'env' according
1538    # to the configured variables.  It returns a list of environments,
1539    # one for each variant build (debug, opt, etc.)
1540    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1541
1542def pairwise(iterable):
1543    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1544    a, b = itertools.tee(iterable)
1545    b.next()
1546    return itertools.izip(a, b)
1547
1548# Create false dependencies so SCons will parse ISAs, establish
1549# dependencies, and setup the build Environments serially. Either
1550# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1551# greater than 1. It appears to be standard race condition stuff; it
1552# doesn't always fail, but usually, and the behaviors are different.
1553# Every time I tried to remove this, builds would fail in some
1554# creative new way. So, don't do that. You'll want to, though, because
1555# tests/SConscript takes a long time to make its Environments.
1556for t1, t2 in pairwise(sorted(all_isa_deps.iterkeys())):
1557    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1558    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1559
1560# base help text
1561Help('''
1562Usage: scons [scons options] [build variables] [target(s)]
1563
1564Extra scons options:
1565%(options)s
1566
1567Global build variables:
1568%(global_vars)s
1569
1570%(local_vars)s
1571''' % help_texts)
1572