SConstruct revision 9926:45a013c50eff
1955SN/A# -*- mode:python -*-
2955SN/A
37816Ssteve.reinhardt@amd.com# Copyright (c) 2013 ARM Limited
45871Snate@binkert.org# All rights reserved.
51762SN/A#
6955SN/A# The license below extends only to copyright in the software and shall
7955SN/A# not be construed as granting a license to any other intellectual
8955SN/A# property including but not limited to intellectual property relating
9955SN/A# to a hardware implementation of the functionality of the software
10955SN/A# licensed hereunder.  You may use the software subject to the license
11955SN/A# terms below provided that you ensure that this notice is replicated
12955SN/A# unmodified and in its entirety in all distributions of the software,
13955SN/A# modified or unmodified, in source code or in binary form.
14955SN/A#
15955SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
16955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
17955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
18955SN/A# All rights reserved.
19955SN/A#
20955SN/A# Redistribution and use in source and binary forms, with or without
21955SN/A# modification, are permitted provided that the following conditions are
22955SN/A# met: redistributions of source code must retain the above copyright
23955SN/A# notice, this list of conditions and the following disclaimer;
24955SN/A# redistributions in binary form must reproduce the above copyright
25955SN/A# notice, this list of conditions and the following disclaimer in the
26955SN/A# documentation and/or other materials provided with the distribution;
27955SN/A# neither the name of the copyright holders nor the names of its
28955SN/A# contributors may be used to endorse or promote products derived from
29955SN/A# this software without specific prior written permission.
302665Ssaidi@eecs.umich.edu#
312665Ssaidi@eecs.umich.edu# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
325863Snate@binkert.org# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
388878Ssteve.reinhardt@amd.com# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
392632Sstever@eecs.umich.edu# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
408878Ssteve.reinhardt@amd.com# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
412632Sstever@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42955SN/A#
438878Ssteve.reinhardt@amd.com# Authors: Steve Reinhardt
442632Sstever@eecs.umich.edu#          Nathan Binkert
452761Sstever@eecs.umich.edu
462632Sstever@eecs.umich.edu###################################################
472632Sstever@eecs.umich.edu#
482632Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
492761Sstever@eecs.umich.edu#
502761Sstever@eecs.umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
512761Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
528878Ssteve.reinhardt@amd.com# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
538878Ssteve.reinhardt@amd.com# the optimized full-system version).
542761Sstever@eecs.umich.edu#
552761Sstever@eecs.umich.edu# You can build gem5 in a different directory as long as there is a
562761Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
572761Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
582761Sstever@eecs.umich.edu# built for the same host system.
598878Ssteve.reinhardt@amd.com#
608878Ssteve.reinhardt@amd.com# Examples:
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
638878Ssteve.reinhardt@amd.com#   scons to search up the directory tree for this SConstruct file.
648878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
652632Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
66955SN/A#
67955SN/A#   The following two commands are equivalent and demonstrate building
68955SN/A#   in a directory outside of the source tree.  The '-C' option tells
695863Snate@binkert.org#   scons to chdir to the specified directory to find this SConstruct
705863Snate@binkert.org#   file.
715863Snate@binkert.org#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
725863Snate@binkert.org#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
735863Snate@binkert.org#
745863Snate@binkert.org# You can use 'scons -H' to print scons options.  If you're in this
755863Snate@binkert.org# 'gem5' directory (or use -u or -C to tell scons where to find this
765863Snate@binkert.org# file), you can use 'scons -h' to print all the gem5-specific build
775863Snate@binkert.org# options as well.
785863Snate@binkert.org#
795863Snate@binkert.org###################################################
808878Ssteve.reinhardt@amd.com
815863Snate@binkert.org# Check for recent-enough Python and SCons versions.
825863Snate@binkert.orgtry:
835863Snate@binkert.org    # Really old versions of scons only take two options for the
845863Snate@binkert.org    # function, so check once without the revision and once with the
855863Snate@binkert.org    # revision, the first instance will fail for stuff other than
865863Snate@binkert.org    # 0.98, and the second will fail for 0.98.0
875863Snate@binkert.org    EnsureSConsVersion(0, 98)
885863Snate@binkert.org    EnsureSConsVersion(0, 98, 1)
895863Snate@binkert.orgexcept SystemExit, e:
905863Snate@binkert.org    print """
915863Snate@binkert.orgFor more details, see:
925863Snate@binkert.org    http://gem5.org/Dependencies
935863Snate@binkert.org"""
945863Snate@binkert.org    raise
955863Snate@binkert.org
968878Ssteve.reinhardt@amd.com# We ensure the python version early because because python-config
975863Snate@binkert.org# requires python 2.5
985863Snate@binkert.orgtry:
995863Snate@binkert.org    EnsurePythonVersion(2, 5)
1006654Snate@binkert.orgexcept SystemExit, e:
101955SN/A    print """
1025396Ssaidi@eecs.umich.eduYou can use a non-default installation of the Python interpreter by
1035863Snate@binkert.orgrearranging your PATH so that scons finds the non-default 'python' and
1045863Snate@binkert.org'python-config' first.
1054202Sbinkertn@umich.edu
1065863Snate@binkert.orgFor more details, see:
1075863Snate@binkert.org    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1085863Snate@binkert.org"""
1095863Snate@binkert.org    raise
110955SN/A
1116654Snate@binkert.org# Global Python includes
1125273Sstever@gmail.comimport os
1135871Snate@binkert.orgimport re
1145273Sstever@gmail.comimport subprocess
1156655Snate@binkert.orgimport sys
1168878Ssteve.reinhardt@amd.com
1176655Snate@binkert.orgfrom os import mkdir, environ
1186655Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1196655Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1206655Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1215871Snate@binkert.org
1226654Snate@binkert.org# SCons includes
1238947Sandreas.hansson@arm.comimport SCons
1245396Ssaidi@eecs.umich.eduimport SCons.Node
1258120Sgblack@eecs.umich.edu
1268120Sgblack@eecs.umich.eduextra_python_paths = [
1278120Sgblack@eecs.umich.edu    Dir('src/python').srcnode().abspath, # gem5 includes
1288120Sgblack@eecs.umich.edu    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1298120Sgblack@eecs.umich.edu    ]
1308120Sgblack@eecs.umich.edu
1318120Sgblack@eecs.umich.edusys.path[1:1] = extra_python_paths
1328120Sgblack@eecs.umich.edu
1338879Ssteve.reinhardt@amd.comfrom m5.util import compareVersions, readCommand
1348879Ssteve.reinhardt@amd.comfrom m5.util.terminal import get_termcap
1358879Ssteve.reinhardt@amd.com
1368879Ssteve.reinhardt@amd.comhelp_texts = {
1378879Ssteve.reinhardt@amd.com    "options" : "",
1388879Ssteve.reinhardt@amd.com    "global_vars" : "",
1398879Ssteve.reinhardt@amd.com    "local_vars" : ""
1408879Ssteve.reinhardt@amd.com}
1418879Ssteve.reinhardt@amd.com
1428879Ssteve.reinhardt@amd.comExport("help_texts")
1438879Ssteve.reinhardt@amd.com
1448879Ssteve.reinhardt@amd.com
1458879Ssteve.reinhardt@amd.com# There's a bug in scons in that (1) by default, the help texts from
1468120Sgblack@eecs.umich.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1478120Sgblack@eecs.umich.edu# and (2) you can override the help displayed by 'scons -h' using the
1488120Sgblack@eecs.umich.edu# Help() function, but these two features are incompatible: once
1498120Sgblack@eecs.umich.edu# you've overridden the help text using Help(), there's no way to get
1508120Sgblack@eecs.umich.edu# at the help texts from AddOptions.  See:
1518120Sgblack@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1528120Sgblack@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1538120Sgblack@eecs.umich.edu# This hack lets us extract the help text from AddOptions and
1548120Sgblack@eecs.umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1558120Sgblack@eecs.umich.edu# we can just use AddOption directly.
1568120Sgblack@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1578120Sgblack@eecs.umich.edu    col_width = 30
1588120Sgblack@eecs.umich.edu
1598120Sgblack@eecs.umich.edu    help = "  " + ", ".join(args)
1608879Ssteve.reinhardt@amd.com    if "help" in kwargs:
1618879Ssteve.reinhardt@amd.com        length = len(help)
1628879Ssteve.reinhardt@amd.com        if length >= col_width:
1638879Ssteve.reinhardt@amd.com            help += "\n" + " " * col_width
1648879Ssteve.reinhardt@amd.com        else:
1658879Ssteve.reinhardt@amd.com            help += " " * (col_width - length)
1668879Ssteve.reinhardt@amd.com        help += kwargs["help"]
1678879Ssteve.reinhardt@amd.com    help_texts["options"] += help + "\n"
1688879Ssteve.reinhardt@amd.com
1698879Ssteve.reinhardt@amd.com    AddOption(*args, **kwargs)
1708879Ssteve.reinhardt@amd.com
1718879Ssteve.reinhardt@amd.comAddLocalOption('--colors', dest='use_colors', action='store_true',
1728120Sgblack@eecs.umich.edu               help="Add color to abbreviated scons output")
1738947Sandreas.hansson@arm.comAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1747816Ssteve.reinhardt@amd.com               help="Don't add color to abbreviated scons output")
1755871Snate@binkert.orgAddLocalOption('--default', dest='default', type='string', action='store',
1765871Snate@binkert.org               help='Override which build_opts file to use for defaults')
1776121Snate@binkert.orgAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1785871Snate@binkert.org               help='Disable style checking hooks')
1795871Snate@binkert.orgAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1806003Snate@binkert.org               help='Disable Link-Time Optimization for fast')
1818980Ssteve.reinhardt@amd.comAddLocalOption('--update-ref', dest='update_ref', action='store_true',
182955SN/A               help='Update test reference outputs')
1835871Snate@binkert.orgAddLocalOption('--verbose', dest='verbose', action='store_true',
1845871Snate@binkert.org               help='Print full tool command lines')
1855871Snate@binkert.org
1865871Snate@binkert.orgtermcap = get_termcap(GetOption('use_colors'))
187955SN/A
1886121Snate@binkert.org########################################################################
1898881Smarc.orr@gmail.com#
1906121Snate@binkert.org# Set up the main build environment.
1916121Snate@binkert.org#
1921533SN/A########################################################################
1936655Snate@binkert.org
1946655Snate@binkert.org# export TERM so that clang reports errors in color
1956655Snate@binkert.orguse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
1966655Snate@binkert.org                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PYTHONPATH',
1975871Snate@binkert.org                 'RANLIB', 'SWIG', 'TERM' ])
1985871Snate@binkert.org
1995863Snate@binkert.orguse_prefixes = [
2005871Snate@binkert.org    "M5",           # M5 configuration (e.g., path to kernels)
2018878Ssteve.reinhardt@amd.com    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
2025871Snate@binkert.org    "CCACHE_",      # ccache (caching compiler wrapper) configuration
2035871Snate@binkert.org    "CCC_",         # clang static analyzer configuration
2045871Snate@binkert.org    ]
2055863Snate@binkert.org
2066121Snate@binkert.orguse_env = {}
2075863Snate@binkert.orgfor key,val in os.environ.iteritems():
2085871Snate@binkert.org    if key in use_vars or \
2098336Ssteve.reinhardt@amd.com            any([key.startswith(prefix) for prefix in use_prefixes]):
2108336Ssteve.reinhardt@amd.com        use_env[key] = val
2118336Ssteve.reinhardt@amd.com
2128336Ssteve.reinhardt@amd.commain = Environment(ENV=use_env)
2134678Snate@binkert.orgmain.Decider('MD5-timestamp')
2148336Ssteve.reinhardt@amd.commain.root = Dir(".")         # The current directory (where this file lives).
2158336Ssteve.reinhardt@amd.commain.srcdir = Dir("src")     # The source directory
2168336Ssteve.reinhardt@amd.com
2174678Snate@binkert.orgmain_dict_keys = main.Dictionary().keys()
2184678Snate@binkert.org
2194678Snate@binkert.org# Check that we have a C/C++ compiler
2204678Snate@binkert.orgif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2217827Snate@binkert.org    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2227827Snate@binkert.org    Exit(1)
2238336Ssteve.reinhardt@amd.com
2244678Snate@binkert.org# Check that swig is present
2258336Ssteve.reinhardt@amd.comif not 'SWIG' in main_dict_keys:
2268336Ssteve.reinhardt@amd.com    print "swig is not installed (package swig on Ubuntu and RedHat)"
2278336Ssteve.reinhardt@amd.com    Exit(1)
2288336Ssteve.reinhardt@amd.com
2298336Ssteve.reinhardt@amd.com# add useful python code PYTHONPATH so it can be used by subprocesses
2308336Ssteve.reinhardt@amd.com# as well
2315871Snate@binkert.orgmain.AppendENVPath('PYTHONPATH', extra_python_paths)
2325871Snate@binkert.org
2338336Ssteve.reinhardt@amd.com########################################################################
2348336Ssteve.reinhardt@amd.com#
2358336Ssteve.reinhardt@amd.com# Mercurial Stuff.
2368336Ssteve.reinhardt@amd.com#
2378336Ssteve.reinhardt@amd.com# If the gem5 directory is a mercurial repository, we should do some
2385871Snate@binkert.org# extra things.
2398336Ssteve.reinhardt@amd.com#
2408336Ssteve.reinhardt@amd.com########################################################################
2418336Ssteve.reinhardt@amd.com
2428336Ssteve.reinhardt@amd.comhgdir = main.root.Dir(".hg")
2438336Ssteve.reinhardt@amd.com
2444678Snate@binkert.orgmercurial_style_message = """
2455871Snate@binkert.orgYou're missing the gem5 style hook, which automatically checks your code
2464678Snate@binkert.orgagainst the gem5 style rules on hg commit and qrefresh commands.  This
2478336Ssteve.reinhardt@amd.comscript will now install the hook in your .hg/hgrc file.
2488336Ssteve.reinhardt@amd.comPress enter to continue, or ctrl-c to abort: """
2498336Ssteve.reinhardt@amd.com
2508336Ssteve.reinhardt@amd.commercurial_style_hook = """
2518336Ssteve.reinhardt@amd.com# The following lines were automatically added by gem5/SConstruct
2528336Ssteve.reinhardt@amd.com# to provide the gem5 style-checking hooks
2538336Ssteve.reinhardt@amd.com[extensions]
2548336Ssteve.reinhardt@amd.comstyle = %s/util/style.py
2558336Ssteve.reinhardt@amd.com
2568336Ssteve.reinhardt@amd.com[hooks]
2578336Ssteve.reinhardt@amd.compretxncommit.style = python:style.check_style
2588336Ssteve.reinhardt@amd.compre-qrefresh.style = python:style.check_style
2598336Ssteve.reinhardt@amd.com# End of SConstruct additions
2608336Ssteve.reinhardt@amd.com
2618336Ssteve.reinhardt@amd.com""" % (main.root.abspath)
2628336Ssteve.reinhardt@amd.com
2638336Ssteve.reinhardt@amd.commercurial_lib_not_found = """
2645871Snate@binkert.orgMercurial libraries cannot be found, ignoring style hook.  If
2656121Snate@binkert.orgyou are a gem5 developer, please fix this and run the style
266955SN/Ahook. It is important.
267955SN/A"""
2682632Sstever@eecs.umich.edu
2692632Sstever@eecs.umich.edu# Check for style hook and prompt for installation if it's not there.
270955SN/A# Skip this if --ignore-style was specified, there's no .hg dir to
271955SN/A# install a hook in, or there's no interactive terminal to prompt.
272955SN/Aif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
273955SN/A    style_hook = True
2748878Ssteve.reinhardt@amd.com    try:
275955SN/A        from mercurial import ui
2762632Sstever@eecs.umich.edu        ui = ui.ui()
2772632Sstever@eecs.umich.edu        ui.readconfig(hgdir.File('hgrc').abspath)
2782632Sstever@eecs.umich.edu        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2792632Sstever@eecs.umich.edu                     ui.config('hooks', 'pre-qrefresh.style', None)
2802632Sstever@eecs.umich.edu    except ImportError:
2812632Sstever@eecs.umich.edu        print mercurial_lib_not_found
2822632Sstever@eecs.umich.edu
2838268Ssteve.reinhardt@amd.com    if not style_hook:
2848268Ssteve.reinhardt@amd.com        print mercurial_style_message,
2858268Ssteve.reinhardt@amd.com        # continue unless user does ctrl-c/ctrl-d etc.
2868268Ssteve.reinhardt@amd.com        try:
2878268Ssteve.reinhardt@amd.com            raw_input()
2888268Ssteve.reinhardt@amd.com        except:
2898268Ssteve.reinhardt@amd.com            print "Input exception, exiting scons.\n"
2902632Sstever@eecs.umich.edu            sys.exit(1)
2912632Sstever@eecs.umich.edu        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
2922632Sstever@eecs.umich.edu        print "Adding style hook to", hgrc_path, "\n"
2932632Sstever@eecs.umich.edu        try:
2948268Ssteve.reinhardt@amd.com            hgrc = open(hgrc_path, 'a')
2952632Sstever@eecs.umich.edu            hgrc.write(mercurial_style_hook)
2968268Ssteve.reinhardt@amd.com            hgrc.close()
2978268Ssteve.reinhardt@amd.com        except:
2988268Ssteve.reinhardt@amd.com            print "Error updating", hgrc_path
2998268Ssteve.reinhardt@amd.com            sys.exit(1)
3003718Sstever@eecs.umich.edu
3012634Sstever@eecs.umich.edu
3022634Sstever@eecs.umich.edu###################################################
3035863Snate@binkert.org#
3042638Sstever@eecs.umich.edu# Figure out which configurations to set up based on the path(s) of
3058268Ssteve.reinhardt@amd.com# the target(s).
3062632Sstever@eecs.umich.edu#
3072632Sstever@eecs.umich.edu###################################################
3082632Sstever@eecs.umich.edu
3092632Sstever@eecs.umich.edu# Find default configuration & binary.
3102632Sstever@eecs.umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
3111858SN/A
3123716Sstever@eecs.umich.edu# helper function: find last occurrence of element in list
3132638Sstever@eecs.umich.edudef rfind(l, elt, offs = -1):
3142638Sstever@eecs.umich.edu    for i in range(len(l)+offs, 0, -1):
3152638Sstever@eecs.umich.edu        if l[i] == elt:
3162638Sstever@eecs.umich.edu            return i
3172638Sstever@eecs.umich.edu    raise ValueError, "element not found"
3182638Sstever@eecs.umich.edu
3192638Sstever@eecs.umich.edu# Take a list of paths (or SCons Nodes) and return a list with all
3205863Snate@binkert.org# paths made absolute and ~-expanded.  Paths will be interpreted
3215863Snate@binkert.org# relative to the launch directory unless a different root is provided
3225863Snate@binkert.orgdef makePathListAbsolute(path_list, root=GetLaunchDir()):
323955SN/A    return [abspath(joinpath(root, expanduser(str(p))))
3245341Sstever@gmail.com            for p in path_list]
3255341Sstever@gmail.com
3265863Snate@binkert.org# Each target must have 'build' in the interior of the path; the
3277756SAli.Saidi@ARM.com# directory below this will determine the build parameters.  For
3285341Sstever@gmail.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3296121Snate@binkert.org# recognize that ALPHA_SE specifies the configuration because it
3304494Ssaidi@eecs.umich.edu# follow 'build' in the build path.
3316121Snate@binkert.org
3321105SN/A# The funky assignment to "[:]" is needed to replace the list contents
3332667Sstever@eecs.umich.edu# in place rather than reassign the symbol to a new list, which
3342667Sstever@eecs.umich.edu# doesn't work (obviously!).
3352667Sstever@eecs.umich.eduBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3362667Sstever@eecs.umich.edu
3376121Snate@binkert.org# Generate a list of the unique build roots and configs that the
3382667Sstever@eecs.umich.edu# collected targets reference.
3395341Sstever@gmail.comvariant_paths = []
3405863Snate@binkert.orgbuild_root = None
3415341Sstever@gmail.comfor t in BUILD_TARGETS:
3425341Sstever@gmail.com    path_dirs = t.split('/')
3435341Sstever@gmail.com    try:
3448120Sgblack@eecs.umich.edu        build_top = rfind(path_dirs, 'build', -2)
3455341Sstever@gmail.com    except:
3468120Sgblack@eecs.umich.edu        print "Error: no non-leaf 'build' dir found on target path", t
3475341Sstever@gmail.com        Exit(1)
3488120Sgblack@eecs.umich.edu    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3496121Snate@binkert.org    if not build_root:
3506121Snate@binkert.org        build_root = this_build_root
3518980Ssteve.reinhardt@amd.com    else:
3525397Ssaidi@eecs.umich.edu        if this_build_root != build_root:
3535397Ssaidi@eecs.umich.edu            print "Error: build targets not under same build root\n"\
3547727SAli.Saidi@ARM.com                  "  %s\n  %s" % (build_root, this_build_root)
3558268Ssteve.reinhardt@amd.com            Exit(1)
3566168Snate@binkert.org    variant_path = joinpath('/',*path_dirs[:build_top+2])
3575341Sstever@gmail.com    if variant_path not in variant_paths:
3588120Sgblack@eecs.umich.edu        variant_paths.append(variant_path)
3598120Sgblack@eecs.umich.edu
3608120Sgblack@eecs.umich.edu# Make sure build_root exists (might not if this is the first build there)
3616814Sgblack@eecs.umich.eduif not isdir(build_root):
3625863Snate@binkert.org    mkdir(build_root)
3638120Sgblack@eecs.umich.edumain['BUILDROOT'] = build_root
3645341Sstever@gmail.com
3655863Snate@binkert.orgExport('main')
3668268Ssteve.reinhardt@amd.com
3676121Snate@binkert.orgmain.SConsignFile(joinpath(build_root, "sconsign"))
3686121Snate@binkert.org
3698268Ssteve.reinhardt@amd.com# Default duplicate option is to use hard links, but this messes up
3705742Snate@binkert.org# when you use emacs to edit a file in the target dir, as emacs moves
3715742Snate@binkert.org# file to file~ then copies to file, breaking the link.  Symbolic
3725341Sstever@gmail.com# (soft) links work better.
3735742Snate@binkert.orgmain.SetOption('duplicate', 'soft-copy')
3745742Snate@binkert.org
3755341Sstever@gmail.com#
3766017Snate@binkert.org# Set up global sticky variables... these are common to an entire build
3776121Snate@binkert.org# tree (not specific to a particular build like ALPHA_SE)
3786017Snate@binkert.org#
3797816Ssteve.reinhardt@amd.com
3807756SAli.Saidi@ARM.comglobal_vars_file = joinpath(build_root, 'variables.global')
3817756SAli.Saidi@ARM.com
3827756SAli.Saidi@ARM.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3837756SAli.Saidi@ARM.com
3847756SAli.Saidi@ARM.comglobal_vars.AddVariables(
3857756SAli.Saidi@ARM.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3867756SAli.Saidi@ARM.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3877756SAli.Saidi@ARM.com    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
3887816Ssteve.reinhardt@amd.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
3897816Ssteve.reinhardt@amd.com    ('BATCH', 'Use batch pool for build and tests', False),
3907816Ssteve.reinhardt@amd.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3917816Ssteve.reinhardt@amd.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
3927816Ssteve.reinhardt@amd.com    ('EXTRAS', 'Add extra directories to the compilation', '')
3937816Ssteve.reinhardt@amd.com    )
3947816Ssteve.reinhardt@amd.com
3957816Ssteve.reinhardt@amd.com# Update main environment with values from ARGUMENTS & global_vars_file
3967816Ssteve.reinhardt@amd.comglobal_vars.Update(main)
3977816Ssteve.reinhardt@amd.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3987756SAli.Saidi@ARM.com
3997816Ssteve.reinhardt@amd.com# Save sticky variable settings back to current variables file
4007816Ssteve.reinhardt@amd.comglobal_vars.Save(global_vars_file, main)
4017816Ssteve.reinhardt@amd.com
4027816Ssteve.reinhardt@amd.com# Parse EXTRAS variable to build list of all directories where we're
4037816Ssteve.reinhardt@amd.com# look for sources etc.  This list is exported as extras_dir_list.
4047816Ssteve.reinhardt@amd.combase_dir = main.srcdir.abspath
4057816Ssteve.reinhardt@amd.comif main['EXTRAS']:
4067816Ssteve.reinhardt@amd.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
4077816Ssteve.reinhardt@amd.comelse:
4087816Ssteve.reinhardt@amd.com    extras_dir_list = []
4097816Ssteve.reinhardt@amd.com
4107816Ssteve.reinhardt@amd.comExport('base_dir')
4117816Ssteve.reinhardt@amd.comExport('extras_dir_list')
4127816Ssteve.reinhardt@amd.com
4137816Ssteve.reinhardt@amd.com# the ext directory should be on the #includes path
4147816Ssteve.reinhardt@amd.commain.Append(CPPPATH=[Dir('ext')])
4157816Ssteve.reinhardt@amd.com
4167816Ssteve.reinhardt@amd.comdef strip_build_path(path, env):
4177816Ssteve.reinhardt@amd.com    path = str(path)
4187816Ssteve.reinhardt@amd.com    variant_base = env['BUILDROOT'] + os.path.sep
4197816Ssteve.reinhardt@amd.com    if path.startswith(variant_base):
4207816Ssteve.reinhardt@amd.com        path = path[len(variant_base):]
4217816Ssteve.reinhardt@amd.com    elif path.startswith('build/'):
4227816Ssteve.reinhardt@amd.com        path = path[6:]
4237816Ssteve.reinhardt@amd.com    return path
4247816Ssteve.reinhardt@amd.com
4257816Ssteve.reinhardt@amd.com# Generate a string of the form:
4267816Ssteve.reinhardt@amd.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
4277816Ssteve.reinhardt@amd.com# to print while building.
4287816Ssteve.reinhardt@amd.comclass Transform(object):
4297816Ssteve.reinhardt@amd.com    # all specific color settings should be here and nowhere else
4307816Ssteve.reinhardt@amd.com    tool_color = termcap.Normal
4317816Ssteve.reinhardt@amd.com    pfx_color = termcap.Yellow
4327816Ssteve.reinhardt@amd.com    srcs_color = termcap.Yellow + termcap.Bold
4337816Ssteve.reinhardt@amd.com    arrow_color = termcap.Blue + termcap.Bold
4347816Ssteve.reinhardt@amd.com    tgts_color = termcap.Yellow + termcap.Bold
4357816Ssteve.reinhardt@amd.com
4367816Ssteve.reinhardt@amd.com    def __init__(self, tool, max_sources=99):
4377816Ssteve.reinhardt@amd.com        self.format = self.tool_color + (" [%8s] " % tool) \
4387816Ssteve.reinhardt@amd.com                      + self.pfx_color + "%s" \
4397816Ssteve.reinhardt@amd.com                      + self.srcs_color + "%s" \
4407816Ssteve.reinhardt@amd.com                      + self.arrow_color + " -> " \
4417816Ssteve.reinhardt@amd.com                      + self.tgts_color + "%s" \
4427816Ssteve.reinhardt@amd.com                      + termcap.Normal
4437816Ssteve.reinhardt@amd.com        self.max_sources = max_sources
4447816Ssteve.reinhardt@amd.com
4457816Ssteve.reinhardt@amd.com    def __call__(self, target, source, env, for_signature=None):
4467816Ssteve.reinhardt@amd.com        # truncate source list according to max_sources param
4477816Ssteve.reinhardt@amd.com        source = source[0:self.max_sources]
4487816Ssteve.reinhardt@amd.com        def strip(f):
4497816Ssteve.reinhardt@amd.com            return strip_build_path(str(f), env)
4507816Ssteve.reinhardt@amd.com        if len(source) > 0:
4517816Ssteve.reinhardt@amd.com            srcs = map(strip, source)
4527816Ssteve.reinhardt@amd.com        else:
4537816Ssteve.reinhardt@amd.com            srcs = ['']
4547816Ssteve.reinhardt@amd.com        tgts = map(strip, target)
4557816Ssteve.reinhardt@amd.com        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4567816Ssteve.reinhardt@amd.com        # operation that has nothing to do with paths.
4577816Ssteve.reinhardt@amd.com        com_pfx = os.path.commonprefix(srcs + tgts)
4587816Ssteve.reinhardt@amd.com        com_pfx_len = len(com_pfx)
4597816Ssteve.reinhardt@amd.com        if com_pfx:
4608947Sandreas.hansson@arm.com            # do some cleanup and sanity checking on common prefix
4618947Sandreas.hansson@arm.com            if com_pfx[-1] == ".":
4627756SAli.Saidi@ARM.com                # prefix matches all but file extension: ok
4638120Sgblack@eecs.umich.edu                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4647756SAli.Saidi@ARM.com                com_pfx = com_pfx[0:-1]
4657756SAli.Saidi@ARM.com            elif com_pfx[-1] == "/":
4667756SAli.Saidi@ARM.com                # common prefix is directory path: OK
4677756SAli.Saidi@ARM.com                pass
4687816Ssteve.reinhardt@amd.com            else:
4697816Ssteve.reinhardt@amd.com                src0_len = len(srcs[0])
4707816Ssteve.reinhardt@amd.com                tgt0_len = len(tgts[0])
4717816Ssteve.reinhardt@amd.com                if src0_len == com_pfx_len:
4727816Ssteve.reinhardt@amd.com                    # source is a substring of target, OK
4737816Ssteve.reinhardt@amd.com                    pass
4747816Ssteve.reinhardt@amd.com                elif tgt0_len == com_pfx_len:
4757816Ssteve.reinhardt@amd.com                    # target is a substring of source, need to back up to
4767816Ssteve.reinhardt@amd.com                    # avoid empty string on RHS of arrow
4777816Ssteve.reinhardt@amd.com                    sep_idx = com_pfx.rfind(".")
4787756SAli.Saidi@ARM.com                    if sep_idx != -1:
4797756SAli.Saidi@ARM.com                        com_pfx = com_pfx[0:sep_idx]
4806654Snate@binkert.org                    else:
4816654Snate@binkert.org                        com_pfx = ''
4825871Snate@binkert.org                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4836121Snate@binkert.org                    # still splitting at file extension: ok
4846121Snate@binkert.org                    pass
4856121Snate@binkert.org                else:
4868946Sandreas.hansson@arm.com                    # probably a fluke; ignore it
4878737Skoansin.tan@gmail.com                    com_pfx = ''
4883940Ssaidi@eecs.umich.edu        # recalculate length in case com_pfx was modified
4893918Ssaidi@eecs.umich.edu        com_pfx_len = len(com_pfx)
4903918Ssaidi@eecs.umich.edu        def fmt(files):
4911858SN/A            f = map(lambda s: s[com_pfx_len:], files)
4926121Snate@binkert.org            return ', '.join(f)
4937739Sgblack@eecs.umich.edu        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
4947739Sgblack@eecs.umich.edu
4956143Snate@binkert.orgExport('Transform')
4967618SAli.Saidi@arm.com
4977618SAli.Saidi@arm.com# enable the regression script to use the termcap
4987618SAli.Saidi@arm.commain['TERMCAP'] = termcap
4997618SAli.Saidi@arm.com
5008614Sgblack@eecs.umich.eduif GetOption('verbose'):
5017618SAli.Saidi@arm.com    def MakeAction(action, string, *args, **kwargs):
5027618SAli.Saidi@arm.com        return Action(action, *args, **kwargs)
5037618SAli.Saidi@arm.comelse:
5047739Sgblack@eecs.umich.edu    MakeAction = Action
5058946Sandreas.hansson@arm.com    main['CCCOMSTR']        = Transform("CC")
5068946Sandreas.hansson@arm.com    main['CXXCOMSTR']       = Transform("CXX")
5076121Snate@binkert.org    main['ASCOMSTR']        = Transform("AS")
5083940Ssaidi@eecs.umich.edu    main['SWIGCOMSTR']      = Transform("SWIG")
5096121Snate@binkert.org    main['ARCOMSTR']        = Transform("AR", 0)
5107739Sgblack@eecs.umich.edu    main['LINKCOMSTR']      = Transform("LINK", 0)
5117739Sgblack@eecs.umich.edu    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
5127739Sgblack@eecs.umich.edu    main['M4COMSTR']        = Transform("M4")
5137739Sgblack@eecs.umich.edu    main['SHCCCOMSTR']      = Transform("SHCC")
5147739Sgblack@eecs.umich.edu    main['SHCXXCOMSTR']     = Transform("SHCXX")
5157739Sgblack@eecs.umich.eduExport('MakeAction')
5168737Skoansin.tan@gmail.com
5178737Skoansin.tan@gmail.com# Initialize the Link-Time Optimization (LTO) flags
5188737Skoansin.tan@gmail.commain['LTO_CCFLAGS'] = []
5198737Skoansin.tan@gmail.commain['LTO_LDFLAGS'] = []
5208737Skoansin.tan@gmail.com
5218737Skoansin.tan@gmail.com# According to the readme, tcmalloc works best if the compiler doesn't
5228737Skoansin.tan@gmail.com# assume that we're using the builtin malloc and friends. These flags
5238737Skoansin.tan@gmail.com# are compiler-specific, so we need to set them after we detect which
5248737Skoansin.tan@gmail.com# compiler we're using.
5258737Skoansin.tan@gmail.commain['TCMALLOC_CCFLAGS'] = []
5268737Skoansin.tan@gmail.com
5278737Skoansin.tan@gmail.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5288737Skoansin.tan@gmail.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5298737Skoansin.tan@gmail.com
5308737Skoansin.tan@gmail.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5318737Skoansin.tan@gmail.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5328737Skoansin.tan@gmail.comif main['GCC'] + main['CLANG'] > 1:
5338737Skoansin.tan@gmail.com    print 'Error: How can we have two at the same time?'
5348946Sandreas.hansson@arm.com    Exit(1)
5358946Sandreas.hansson@arm.com
5368946Sandreas.hansson@arm.com# Set up default C++ compiler flags
5378946Sandreas.hansson@arm.comif main['GCC'] or main['CLANG']:
5388946Sandreas.hansson@arm.com    # As gcc and clang share many flags, do the common parts here
5398946Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-pipe'])
5403918Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5419068SAli.Saidi@ARM.com    # Enable -Wall and then disable the few warnings that we
5429068SAli.Saidi@ARM.com    # consistently violate
5439068SAli.Saidi@ARM.com    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5449068SAli.Saidi@ARM.com    # We always compile using C++11, but only gcc >= 4.7 and clang 3.1
5459068SAli.Saidi@ARM.com    # actually use that name, so we stick with c++0x
5469068SAli.Saidi@ARM.com    main.Append(CXXFLAGS=['-std=c++0x'])
5479068SAli.Saidi@ARM.com    # Add selected sanity checks from -Wextra
5489068SAli.Saidi@ARM.com    main.Append(CXXFLAGS=['-Wmissing-field-initializers',
5499068SAli.Saidi@ARM.com                          '-Woverloaded-virtual'])
5509068SAli.Saidi@ARM.comelse:
5519068SAli.Saidi@ARM.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5529068SAli.Saidi@ARM.com    print "Don't know what compiler options to use for your compiler."
5539068SAli.Saidi@ARM.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5549068SAli.Saidi@ARM.com    print termcap.Yellow + '       version:' + termcap.Normal,
5559068SAli.Saidi@ARM.com    if not CXX_version:
5569068SAli.Saidi@ARM.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5573918Ssaidi@eecs.umich.edu               termcap.Normal
5583918Ssaidi@eecs.umich.edu    else:
5596157Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
5606157Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
5616157Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
5626157Snate@binkert.org    print "       environment."
5635397Ssaidi@eecs.umich.edu    print "       "
5645397Ssaidi@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
5656121Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
5666121Snate@binkert.org    print "       src/SConscript to support that compiler."
5676121Snate@binkert.org    Exit(1)
5686121Snate@binkert.org
5696121Snate@binkert.orgif main['GCC']:
5706121Snate@binkert.org    # Check for a supported version of gcc, >= 4.4 is needed for c++0x
5715397Ssaidi@eecs.umich.edu    # support. See http://gcc.gnu.org/projects/cxx0x.html for details
5721851SN/A    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5731851SN/A    if compareVersions(gcc_version, "4.4") < 0:
5747739Sgblack@eecs.umich.edu        print 'Error: gcc version 4.4 or newer required.'
575955SN/A        print '       Installed version:', gcc_version
5763053Sstever@eecs.umich.edu        Exit(1)
5776121Snate@binkert.org
5783053Sstever@eecs.umich.edu    main['GCC_VERSION'] = gcc_version
5793053Sstever@eecs.umich.edu
5803053Sstever@eecs.umich.edu    # Check for versions with bugs
5813053Sstever@eecs.umich.edu    if not compareVersions(gcc_version, '4.4.1') or \
5823053Sstever@eecs.umich.edu       not compareVersions(gcc_version, '4.4.2'):
5836654Snate@binkert.org        print 'Info: Tree vectorizer in GCC 4.4.1 & 4.4.2 is buggy, disabling.'
5843053Sstever@eecs.umich.edu        main.Append(CCFLAGS=['-fno-tree-vectorize'])
5854742Sstever@eecs.umich.edu
5864742Sstever@eecs.umich.edu    # LTO support is only really working properly from 4.6 and beyond
5873053Sstever@eecs.umich.edu    if compareVersions(gcc_version, '4.6') >= 0:
5883053Sstever@eecs.umich.edu        # Add the appropriate Link-Time Optimization (LTO) flags
5893053Sstever@eecs.umich.edu        # unless LTO is explicitly turned off. Note that these flags
5908960Ssteve.reinhardt@amd.com        # are only used by the fast target.
5916654Snate@binkert.org        if not GetOption('no_lto'):
5923053Sstever@eecs.umich.edu            # Pass the LTO flag when compiling to produce GIMPLE
5933053Sstever@eecs.umich.edu            # output, we merely create the flags here and only append
5943053Sstever@eecs.umich.edu            # them later/
5953053Sstever@eecs.umich.edu            main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
5962667Sstever@eecs.umich.edu
5974554Sbinkertn@umich.edu            # Use the same amount of jobs for LTO as we are running
5986121Snate@binkert.org            # scons with, we hardcode the use of the linker plugin
5992667Sstever@eecs.umich.edu            # which requires either gold or GNU ld >= 2.21
6004554Sbinkertn@umich.edu            main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs'),
6014554Sbinkertn@umich.edu                                   '-fuse-linker-plugin']
6024554Sbinkertn@umich.edu
6036121Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
6044554Sbinkertn@umich.edu                                  '-fno-builtin-realloc', '-fno-builtin-free'])
6054554Sbinkertn@umich.edu
6064554Sbinkertn@umich.eduelif main['CLANG']:
6074781Snate@binkert.org    # Check for a supported version of clang, >= 2.9 is needed to
6084554Sbinkertn@umich.edu    # support similar features as gcc 4.4. See
6094554Sbinkertn@umich.edu    # http://clang.llvm.org/cxx_status.html for details
6102667Sstever@eecs.umich.edu    clang_version_re = re.compile(".* version (\d+\.\d+)")
6114554Sbinkertn@umich.edu    clang_version_match = clang_version_re.match(CXX_version)
6124554Sbinkertn@umich.edu    if (clang_version_match):
6134554Sbinkertn@umich.edu        clang_version = clang_version_match.groups()[0]
6144554Sbinkertn@umich.edu        if compareVersions(clang_version, "2.9") < 0:
6152667Sstever@eecs.umich.edu            print 'Error: clang version 2.9 or newer required.'
6164554Sbinkertn@umich.edu            print '       Installed version:', clang_version
6172667Sstever@eecs.umich.edu            Exit(1)
6184554Sbinkertn@umich.edu    else:
6196121Snate@binkert.org        print 'Error: Unable to determine clang version.'
6202667Sstever@eecs.umich.edu        Exit(1)
6215522Snate@binkert.org
6225522Snate@binkert.org    # clang has a few additional warnings that we disable,
6235522Snate@binkert.org    # tautological comparisons are allowed due to unsigned integers
6245522Snate@binkert.org    # being compared to constants that happen to be 0, and extraneous
6255522Snate@binkert.org    # parantheses are allowed due to Ruby's printing of the AST,
6265522Snate@binkert.org    # finally self assignments are allowed as the generated CPU code
6275522Snate@binkert.org    # is relying on this
6285522Snate@binkert.org    main.Append(CCFLAGS=['-Wno-tautological-compare',
6295522Snate@binkert.org                         '-Wno-parentheses',
6305522Snate@binkert.org                         '-Wno-self-assign'])
6315522Snate@binkert.org
6325522Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
6335522Snate@binkert.org
6345522Snate@binkert.org    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
6355522Snate@binkert.org    # opposed to libstdc++, as the later is dated.
6365522Snate@binkert.org    if sys.platform == "darwin":
6375522Snate@binkert.org        main.Append(CXXFLAGS=['-stdlib=libc++'])
6385522Snate@binkert.org        main.Append(LIBS=['c++'])
6395522Snate@binkert.org
6405522Snate@binkert.orgelse:
6415522Snate@binkert.org    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6425522Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
6435522Snate@binkert.org    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6445522Snate@binkert.org    print termcap.Yellow + '       version:' + termcap.Normal,
6455522Snate@binkert.org    if not CXX_version:
6465522Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6472638Sstever@eecs.umich.edu               termcap.Normal
6482638Sstever@eecs.umich.edu    else:
6496121Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
6503716Sstever@eecs.umich.edu    print "       If you're trying to use a compiler other than GCC"
6515522Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
6525522Snate@binkert.org    print "       environment."
6535522Snate@binkert.org    print "       "
6545522Snate@binkert.org    print "       If you are trying to use a compiler other than those listed"
6555522Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
6565522Snate@binkert.org    print "       src/SConscript to support that compiler."
6571858SN/A    Exit(1)
6585227Ssaidi@eecs.umich.edu
6595227Ssaidi@eecs.umich.edu# Set up common yacc/bison flags (needed for Ruby)
6605227Ssaidi@eecs.umich.edumain['YACCFLAGS'] = '-d'
6615227Ssaidi@eecs.umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
6626654Snate@binkert.org
6636654Snate@binkert.org# Do this after we save setting back, or else we'll tack on an
6647769SAli.Saidi@ARM.com# extra 'qdo' every time we run scons.
6657769SAli.Saidi@ARM.comif main['BATCH']:
6667769SAli.Saidi@ARM.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
6677769SAli.Saidi@ARM.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
6685227Ssaidi@eecs.umich.edu    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
6695227Ssaidi@eecs.umich.edu    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
6705227Ssaidi@eecs.umich.edu    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
6715204Sstever@gmail.com
6725204Sstever@gmail.comif sys.platform == 'cygwin':
6735204Sstever@gmail.com    # cygwin has some header file issues...
6745204Sstever@gmail.com    main.Append(CCFLAGS=["-Wno-uninitialized"])
6755204Sstever@gmail.com
6765204Sstever@gmail.com# Check for the protobuf compiler
6775204Sstever@gmail.comprotoc_version = readCommand([main['PROTOC'], '--version'],
6785204Sstever@gmail.com                             exception='').split()
6795204Sstever@gmail.com
6805204Sstever@gmail.com# First two words should be "libprotoc x.y.z"
6815204Sstever@gmail.comif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6825204Sstever@gmail.com    print termcap.Yellow + termcap.Bold + \
6835204Sstever@gmail.com        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
6845204Sstever@gmail.com        '         Please install protobuf-compiler for tracing support.' + \
6855204Sstever@gmail.com        termcap.Normal
6865204Sstever@gmail.com    main['PROTOC'] = False
6875204Sstever@gmail.comelse:
6886121Snate@binkert.org    # Based on the availability of the compress stream wrappers,
6895204Sstever@gmail.com    # require 2.1.0
6903118Sstever@eecs.umich.edu    min_protoc_version = '2.1.0'
6913118Sstever@eecs.umich.edu    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6923118Sstever@eecs.umich.edu        print termcap.Yellow + termcap.Bold + \
6933118Sstever@eecs.umich.edu            'Warning: protoc version', min_protoc_version, \
6943118Sstever@eecs.umich.edu            'or newer required.\n' + \
6955863Snate@binkert.org            '         Installed version:', protoc_version[1], \
6963118Sstever@eecs.umich.edu            termcap.Normal
6975863Snate@binkert.org        main['PROTOC'] = False
6983118Sstever@eecs.umich.edu    else:
6997457Snate@binkert.org        # Attempt to determine the appropriate include path and
7007457Snate@binkert.org        # library path using pkg-config, that means we also need to
7015863Snate@binkert.org        # check for pkg-config. Note that it is possible to use
7025863Snate@binkert.org        # protobuf without the involvement of pkg-config. Later on we
7035863Snate@binkert.org        # check go a library config check and at that point the test
7045863Snate@binkert.org        # will fail if libprotobuf cannot be found.
7055863Snate@binkert.org        if readCommand(['pkg-config', '--version'], exception=''):
7065863Snate@binkert.org            try:
7075863Snate@binkert.org                # Attempt to establish what linking flags to add for protobuf
7086003Snate@binkert.org                # using pkg-config
7095863Snate@binkert.org                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
7105863Snate@binkert.org            except:
7115863Snate@binkert.org                print termcap.Yellow + termcap.Bold + \
7126120Snate@binkert.org                    'Warning: pkg-config could not get protobuf flags.' + \
7135863Snate@binkert.org                    termcap.Normal
7145863Snate@binkert.org
7155863Snate@binkert.org# Check for SWIG
7168655Sandreas.hansson@arm.comif not main.has_key('SWIG'):
7178655Sandreas.hansson@arm.com    print 'Error: SWIG utility not found.'
7188655Sandreas.hansson@arm.com    print '       Please install (see http://www.swig.org) and retry.'
7198655Sandreas.hansson@arm.com    Exit(1)
7208655Sandreas.hansson@arm.com
7218655Sandreas.hansson@arm.com# Check for appropriate SWIG version
7228655Sandreas.hansson@arm.comswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
7238655Sandreas.hansson@arm.com# First 3 words should be "SWIG Version x.y.z"
7246120Snate@binkert.orgif len(swig_version) < 3 or \
7255863Snate@binkert.org        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
7266121Snate@binkert.org    print 'Error determining SWIG version.'
7276121Snate@binkert.org    Exit(1)
7285863Snate@binkert.org
7297727SAli.Saidi@ARM.commin_swig_version = '1.3.34'
7307727SAli.Saidi@ARM.comif compareVersions(swig_version[2], min_swig_version) < 0:
7317727SAli.Saidi@ARM.com    print 'Error: SWIG version', min_swig_version, 'or newer required.'
7327727SAli.Saidi@ARM.com    print '       Installed version:', swig_version[2]
7337727SAli.Saidi@ARM.com    Exit(1)
7347727SAli.Saidi@ARM.com
7355863Snate@binkert.org# Older versions of swig do not play well with more recent versions of
7363118Sstever@eecs.umich.edu# gcc due to assumptions on implicit includes (cstddef) and use of
7375863Snate@binkert.org# namespaces
7383118Sstever@eecs.umich.eduif main['GCC'] and compareVersions(gcc_version, '4.6') > 0 and \
7393118Sstever@eecs.umich.edu        compareVersions(swig_version[2], '2') < 0:
7405863Snate@binkert.org    print '\n' + termcap.Yellow + termcap.Bold + \
7415863Snate@binkert.org        'Warning: SWIG 1.x cause issues with gcc 4.6 and later.\n' + \
7425863Snate@binkert.org        termcap.Normal + \
7435863Snate@binkert.org        'Use SWIG 2.x to avoid assumptions on implicit includes\n' + \
7443118Sstever@eecs.umich.edu        'and use of namespaces\n'
7453483Ssaidi@eecs.umich.edu
7463494Ssaidi@eecs.umich.edu# Set up SWIG flags & scanner
7473494Ssaidi@eecs.umich.eduswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
7483483Ssaidi@eecs.umich.edumain.Append(SWIGFLAGS=swig_flags)
7493483Ssaidi@eecs.umich.edu
7503483Ssaidi@eecs.umich.edu# filter out all existing swig scanners, they mess up the dependency
7513053Sstever@eecs.umich.edu# stuff for some reason
7523053Sstever@eecs.umich.eduscanners = []
7533918Ssaidi@eecs.umich.edufor scanner in main['SCANNERS']:
7543053Sstever@eecs.umich.edu    skeys = scanner.skeys
7553053Sstever@eecs.umich.edu    if skeys == '.i':
7563053Sstever@eecs.umich.edu        continue
7573053Sstever@eecs.umich.edu
7583053Sstever@eecs.umich.edu    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
7597840Snate@binkert.org        continue
7607865Sgblack@eecs.umich.edu
7617865Sgblack@eecs.umich.edu    scanners.append(scanner)
7627865Sgblack@eecs.umich.edu
7637865Sgblack@eecs.umich.edu# add the new swig scanner that we like better
7647865Sgblack@eecs.umich.edufrom SCons.Scanner import ClassicCPP as CPPScanner
7657840Snate@binkert.orgswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
7669045SAli.Saidi@ARM.comscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
7679045SAli.Saidi@ARM.com
7689045SAli.Saidi@ARM.com# replace the scanners list that has what we want
7699045SAli.Saidi@ARM.commain['SCANNERS'] = scanners
7709045SAli.Saidi@ARM.com
7719045SAli.Saidi@ARM.com# Add a custom Check function to the Configure context so that we can
7729045SAli.Saidi@ARM.com# figure out if the compiler adds leading underscores to global
7739045SAli.Saidi@ARM.com# variables.  This is needed for the autogenerated asm files that we
7747840Snate@binkert.org# use for embedding the python code.
7757840Snate@binkert.orgdef CheckLeading(context):
7767840Snate@binkert.org    context.Message("Checking for leading underscore in global variables...")
7771858SN/A    # 1) Define a global variable called x from asm so the C compiler
7781858SN/A    #    won't change the symbol at all.
7791858SN/A    # 2) Declare that variable.
7801858SN/A    # 3) Use the variable
7811858SN/A    #
7821858SN/A    # If the compiler prepends an underscore, this will successfully
7835863Snate@binkert.org    # link because the external symbol 'x' will be called '_x' which
7845863Snate@binkert.org    # was defined by the asm statement.  If the compiler does not
7855863Snate@binkert.org    # prepend an underscore, this will not successfully link because
7865863Snate@binkert.org    # '_x' will have been defined by assembly, while the C portion of
7876121Snate@binkert.org    # the code will be trying to use 'x'
7881858SN/A    ret = context.TryLink('''
7895863Snate@binkert.org        asm(".globl _x; _x: .byte 0");
7905863Snate@binkert.org        extern int x;
7915863Snate@binkert.org        int main() { return x; }
7925863Snate@binkert.org        ''', extension=".c")
7935863Snate@binkert.org    context.env.Append(LEADING_UNDERSCORE=ret)
7942139SN/A    context.Result(ret)
7954202Sbinkertn@umich.edu    return ret
7964202Sbinkertn@umich.edu
7972139SN/A# Platform-specific configuration.  Note again that we assume that all
7986994Snate@binkert.org# builds under a given build root run on the same host platform.
7996994Snate@binkert.orgconf = Configure(main,
8006994Snate@binkert.org                 conf_dir = joinpath(build_root, '.scons_config'),
8016994Snate@binkert.org                 log_file = joinpath(build_root, 'scons_config.log'),
8026994Snate@binkert.org                 custom_tests = { 'CheckLeading' : CheckLeading })
8036994Snate@binkert.org
8046994Snate@binkert.org# Check for leading underscores.  Don't really need to worry either
8056994Snate@binkert.org# way so don't need to check the return code.
8066994Snate@binkert.orgconf.CheckLeading()
8076994Snate@binkert.org
8086994Snate@binkert.org# Check if we should compile a 64 bit binary on Mac OS X/Darwin
8096994Snate@binkert.orgtry:
8106994Snate@binkert.org    import platform
8116994Snate@binkert.org    uname = platform.uname()
8126994Snate@binkert.org    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
8136994Snate@binkert.org        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
8146994Snate@binkert.org            main.Append(CCFLAGS=['-arch', 'x86_64'])
8156994Snate@binkert.org            main.Append(CFLAGS=['-arch', 'x86_64'])
8166994Snate@binkert.org            main.Append(LINKFLAGS=['-arch', 'x86_64'])
8176994Snate@binkert.org            main.Append(ASFLAGS=['-arch', 'x86_64'])
8186994Snate@binkert.orgexcept:
8196994Snate@binkert.org    pass
8206994Snate@binkert.org
8216994Snate@binkert.org# Recent versions of scons substitute a "Null" object for Configure()
8226994Snate@binkert.org# when configuration isn't necessary, e.g., if the "--help" option is
8236994Snate@binkert.org# present.  Unfortuantely this Null object always returns false,
8246994Snate@binkert.org# breaking all our configuration checks.  We replace it with our own
8256994Snate@binkert.org# more optimistic null object that returns True instead.
8262155SN/Aif not conf:
8275863Snate@binkert.org    def NullCheck(*args, **kwargs):
8281869SN/A        return True
8291869SN/A
8305863Snate@binkert.org    class NullConf:
8315863Snate@binkert.org        def __init__(self, env):
8324202Sbinkertn@umich.edu            self.env = env
8336108Snate@binkert.org        def Finish(self):
8346108Snate@binkert.org            return self.env
8356108Snate@binkert.org        def __getattr__(self, mname):
8366108Snate@binkert.org            return NullCheck
8374202Sbinkertn@umich.edu
8385863Snate@binkert.org    conf = NullConf(main)
8398474Sgblack@eecs.umich.edu
8408474Sgblack@eecs.umich.edu# Cache build files in the supplied directory.
8415742Snate@binkert.orgif main['M5_BUILD_CACHE']:
8428268Ssteve.reinhardt@amd.com    print 'Using build cache located at', main['M5_BUILD_CACHE']
8438268Ssteve.reinhardt@amd.com    CacheDir(main['M5_BUILD_CACHE'])
8448268Ssteve.reinhardt@amd.com
8455742Snate@binkert.org# Find Python include and library directories for embedding the
8465341Sstever@gmail.com# interpreter. We rely on python-config to resolve the appropriate
8478474Sgblack@eecs.umich.edu# includes and linker flags. ParseConfig does not seem to understand
8488474Sgblack@eecs.umich.edu# the more exotic linker flags such as -Xlinker and -export-dynamic so
8495342Sstever@gmail.com# we add them explicitly below. If you want to link in an alternate
8504202Sbinkertn@umich.edu# version of python, see above for instructions on how to invoke
8514202Sbinkertn@umich.edu# scons with the appropriate PATH set.
8524202Sbinkertn@umich.edupy_includes = readCommand(['python-config', '--includes'],
8535863Snate@binkert.org                          exception='').split()
8545863Snate@binkert.org# Strip the -I from the include folders before adding them to the
8556994Snate@binkert.org# CPPPATH
8566994Snate@binkert.orgmain.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
8576994Snate@binkert.org
8585863Snate@binkert.org# Read the linker flags and split them into libraries and other link
8595863Snate@binkert.org# flags. The libraries are added later through the call the CheckLib.
8605863Snate@binkert.orgpy_ld_flags = readCommand(['python-config', '--ldflags'], exception='').split()
8615863Snate@binkert.orgpy_libs = []
8625863Snate@binkert.orgfor lib in py_ld_flags:
8635863Snate@binkert.org     if not lib.startswith('-l'):
8645863Snate@binkert.org         main.Append(LINKFLAGS=[lib])
8655863Snate@binkert.org     else:
8667840Snate@binkert.org         lib = lib[2:]
8675863Snate@binkert.org         if lib not in py_libs:
8685952Ssaidi@eecs.umich.edu             py_libs.append(lib)
8691869SN/A
8701858SN/A# verify that this stuff works
8715863Snate@binkert.orgif not conf.CheckHeader('Python.h', '<>'):
8729044SAli.Saidi@ARM.com    print "Error: can't find Python.h header in", py_includes
8738805Sgblack@eecs.umich.edu    print "Install Python headers (package python-dev on Ubuntu and RedHat)"
8741858SN/A    Exit(1)
875955SN/A
876955SN/Afor lib in py_libs:
8771869SN/A    if not conf.CheckLib(lib):
8781869SN/A        print "Error: can't find library %s required by python" % lib
8791869SN/A        Exit(1)
8801869SN/A
8811869SN/A# On Solaris you need to use libsocket for socket ops
8825863Snate@binkert.orgif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
8835863Snate@binkert.org   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
8845863Snate@binkert.org       print "Can't find library with socket calls (e.g. accept())"
8851869SN/A       Exit(1)
8865863Snate@binkert.org
8871869SN/A# Check for zlib.  If the check passes, libz will be automatically
8885863Snate@binkert.org# added to the LIBS environment variable.
8891869SN/Aif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
8901869SN/A    print 'Error: did not find needed zlib compression library '\
8911869SN/A          'and/or zlib.h header file.'
8921869SN/A    print '       Please install zlib and try again.'
8938483Sgblack@eecs.umich.edu    Exit(1)
8941869SN/A
8951869SN/A# If we have the protobuf compiler, also make sure we have the
8961869SN/A# development libraries. If the check passes, libprotobuf will be
8971869SN/A# automatically added to the LIBS environment variable. After
8985863Snate@binkert.org# this, we can use the HAVE_PROTOBUF flag to determine if we have
8995863Snate@binkert.org# got both protoc and libprotobuf available.
9001869SN/Amain['HAVE_PROTOBUF'] = main['PROTOC'] and \
9015863Snate@binkert.org    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
9025863Snate@binkert.org                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
9033356Sbinkertn@umich.edu
9043356Sbinkertn@umich.edu# If we have the compiler but not the library, print another warning.
9053356Sbinkertn@umich.eduif main['PROTOC'] and not main['HAVE_PROTOBUF']:
9063356Sbinkertn@umich.edu    print termcap.Yellow + termcap.Bold + \
9073356Sbinkertn@umich.edu        'Warning: did not find protocol buffer library and/or headers.\n' + \
9084781Snate@binkert.org    '       Please install libprotobuf-dev for tracing support.' + \
9095863Snate@binkert.org    termcap.Normal
9105863Snate@binkert.org
9111869SN/A# Check for librt.
9121869SN/Ahave_posix_clock = \
9131869SN/A    conf.CheckLibWithHeader(None, 'time.h', 'C',
9146121Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);') or \
9151869SN/A    conf.CheckLibWithHeader('rt', 'time.h', 'C',
9162638Sstever@eecs.umich.edu                            'clock_nanosleep(0,0,NULL,NULL);')
9176121Snate@binkert.org
9186121Snate@binkert.orghave_posix_timers = \
9192638Sstever@eecs.umich.edu    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
9205749Scws3k@cs.virginia.edu                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
9216121Snate@binkert.org
9226121Snate@binkert.orgif conf.CheckLib('tcmalloc'):
9235749Scws3k@cs.virginia.edu    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
9241869SN/Aelif conf.CheckLib('tcmalloc_minimal'):
9251869SN/A    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
9263546Sgblack@eecs.umich.eduelse:
9273546Sgblack@eecs.umich.edu    print termcap.Yellow + termcap.Bold + \
9283546Sgblack@eecs.umich.edu          "You can get a 12% performance improvement by installing tcmalloc "\
9293546Sgblack@eecs.umich.edu          "(libgoogle-perftools-dev package on Ubuntu or RedHat)." + \
9306121Snate@binkert.org          termcap.Normal
9315863Snate@binkert.org
9323546Sgblack@eecs.umich.eduif not have_posix_clock:
9333546Sgblack@eecs.umich.edu    print "Can't find library for POSIX clocks."
9343546Sgblack@eecs.umich.edu
9353546Sgblack@eecs.umich.edu# Check for <fenv.h> (C99 FP environment control)
9364781Snate@binkert.orghave_fenv = conf.CheckHeader('fenv.h', '<>')
9374781Snate@binkert.orgif not have_fenv:
9386658Snate@binkert.org    print "Warning: Header file <fenv.h> not found."
9396658Snate@binkert.org    print "         This host has no IEEE FP rounding mode control."
9404781Snate@binkert.org
9413546Sgblack@eecs.umich.edu# Check if we should enable KVM-based hardware virtualization. The API
9423546Sgblack@eecs.umich.edu# we rely on exists since version 2.6.36 of the kernel, but somehow
9433546Sgblack@eecs.umich.edu# the KVM_API_VERSION does not reflect the change. We test for one of
9443546Sgblack@eecs.umich.edu# the types as a fall back.
9457756SAli.Saidi@ARM.comhave_kvm = conf.CheckHeader('linux/kvm.h', '<>') and \
9467816Ssteve.reinhardt@amd.com    conf.CheckTypeSize('struct kvm_xsave', '#include <linux/kvm.h>') != 0
9473546Sgblack@eecs.umich.eduif not have_kvm:
9483546Sgblack@eecs.umich.edu    print "Info: Compatible header file <linux/kvm.h> not found, " \
9493546Sgblack@eecs.umich.edu        "disabling KVM support."
9503546Sgblack@eecs.umich.edu
9514202Sbinkertn@umich.edu# Check if the requested target ISA is compatible with the host
9523546Sgblack@eecs.umich.edudef is_isa_kvm_compatible(isa):
9533546Sgblack@eecs.umich.edu    isa_comp_table = {
9543546Sgblack@eecs.umich.edu        "arm" : ( "armv7l" ),
955955SN/A        "x86" : ( "x86_64" ),
956955SN/A        }
957955SN/A    try:
958955SN/A        import platform
9595863Snate@binkert.org        host_isa = platform.machine()
9605863Snate@binkert.org    except:
9615343Sstever@gmail.com        print "Warning: Failed to determine host ISA."
9625343Sstever@gmail.com        return False
9636121Snate@binkert.org
9645863Snate@binkert.org    return host_isa in isa_comp_table.get(isa, [])
9654773Snate@binkert.org
9665863Snate@binkert.org
9672632Sstever@eecs.umich.edu######################################################################
9685863Snate@binkert.org#
9692023SN/A# Finish the configuration
9705863Snate@binkert.org#
9715863Snate@binkert.orgmain = conf.Finish()
9725863Snate@binkert.org
9735863Snate@binkert.org######################################################################
9745863Snate@binkert.org#
9755863Snate@binkert.org# Collect all non-global variables
9765863Snate@binkert.org#
9775863Snate@binkert.org
9785863Snate@binkert.org# Define the universe of supported ISAs
9792632Sstever@eecs.umich.eduall_isa_list = [ ]
9805863Snate@binkert.orgExport('all_isa_list')
9812023SN/A
9822632Sstever@eecs.umich.educlass CpuModel(object):
9835863Snate@binkert.org    '''The CpuModel class encapsulates everything the ISA parser needs to
9845342Sstever@gmail.com    know about a particular CPU model.'''
9855863Snate@binkert.org
9862632Sstever@eecs.umich.edu    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
9875863Snate@binkert.org    dict = {}
9885863Snate@binkert.org    list = []
9898267Ssteve.reinhardt@amd.com    defaults = []
9908120Sgblack@eecs.umich.edu
9918267Ssteve.reinhardt@amd.com    # Constructor.  Automatically adds models to CpuModel.dict.
9928267Ssteve.reinhardt@amd.com    def __init__(self, name, filename, includes, strings, default=False):
9938267Ssteve.reinhardt@amd.com        self.name = name           # name of model
9948267Ssteve.reinhardt@amd.com        self.filename = filename   # filename for output exec code
9958267Ssteve.reinhardt@amd.com        self.includes = includes   # include files needed in exec file
9968267Ssteve.reinhardt@amd.com        # The 'strings' dict holds all the per-CPU symbols we can
9978267Ssteve.reinhardt@amd.com        # substitute into templates etc.
9988267Ssteve.reinhardt@amd.com        self.strings = strings
9998267Ssteve.reinhardt@amd.com
10005863Snate@binkert.org        # This cpu is enabled by default
10015863Snate@binkert.org        self.default = default
10025863Snate@binkert.org
10032632Sstever@eecs.umich.edu        # Add self to dict
10048267Ssteve.reinhardt@amd.com        if name in CpuModel.dict:
10058267Ssteve.reinhardt@amd.com            raise AttributeError, "CpuModel '%s' already registered" % name
10068267Ssteve.reinhardt@amd.com        CpuModel.dict[name] = self
10072632Sstever@eecs.umich.edu        CpuModel.list.append(name)
10081888SN/A
10095863Snate@binkert.orgExport('CpuModel')
10105863Snate@binkert.org
10111858SN/A# Sticky variables get saved in the variables file so they persist from
10128120Sgblack@eecs.umich.edu# one invocation to the next (unless overridden, in which case the new
10138120Sgblack@eecs.umich.edu# value becomes sticky).
10147756SAli.Saidi@ARM.comsticky_vars = Variables(args=ARGUMENTS)
10152598SN/AExport('sticky_vars')
10165863Snate@binkert.org
10171858SN/A# Sticky variables that should be exported
10181858SN/Aexport_vars = []
10191858SN/AExport('export_vars')
10205863Snate@binkert.org
10211858SN/A# For Ruby
10221858SN/Aall_protocols = []
10231858SN/AExport('all_protocols')
10245863Snate@binkert.orgprotocol_dirs = []
10251871SN/AExport('protocol_dirs')
10261858SN/Aslicc_includes = []
10271858SN/AExport('slicc_includes')
10281858SN/A
10291858SN/A# Walk the tree and execute all SConsopts scripts that wil add to the
10305863Snate@binkert.org# above variables
10315863Snate@binkert.orgif not GetOption('verbose'):
10321869SN/A    print "Reading SConsopts"
10331965SN/Afor bdir in [ base_dir ] + extras_dir_list:
10347739Sgblack@eecs.umich.edu    if not isdir(bdir):
10351965SN/A        print "Error: directory '%s' does not exist" % bdir
10369045SAli.Saidi@ARM.com        Exit(1)
10379045SAli.Saidi@ARM.com    for root, dirs, files in os.walk(bdir):
10389045SAli.Saidi@ARM.com        if 'SConsopts' in files:
10392761Sstever@eecs.umich.edu            if GetOption('verbose'):
10405863Snate@binkert.org                print "Reading", joinpath(root, 'SConsopts')
10411869SN/A            SConscript(joinpath(root, 'SConsopts'))
10425863Snate@binkert.org
10432667Sstever@eecs.umich.eduall_isa_list.sort()
10441869SN/A
10451869SN/Asticky_vars.AddVariables(
10462929Sktlim@umich.edu    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
10472929Sktlim@umich.edu    ListVariable('CPU_MODELS', 'CPU models',
10485863Snate@binkert.org                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
10492929Sktlim@umich.edu                 sorted(CpuModel.list)),
1050955SN/A    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
10518120Sgblack@eecs.umich.edu                 False),
10528120Sgblack@eecs.umich.edu    BoolVariable('SS_COMPATIBLE_FP',
10538120Sgblack@eecs.umich.edu                 'Make floating-point results compatible with SimpleScalar',
10548120Sgblack@eecs.umich.edu                 False),
10558120Sgblack@eecs.umich.edu    BoolVariable('USE_SSE2',
10568120Sgblack@eecs.umich.edu                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
10578120Sgblack@eecs.umich.edu                 False),
10588120Sgblack@eecs.umich.edu    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
10598120Sgblack@eecs.umich.edu    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
10608120Sgblack@eecs.umich.edu    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
10618120Sgblack@eecs.umich.edu    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
10628120Sgblack@eecs.umich.edu    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1063                  all_protocols),
1064    )
1065
1066# These variables get exported to #defines in config/*.hh (see src/SConscript).
1067export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'CP_ANNOTATE',
1068                'USE_POSIX_CLOCK', 'PROTOCOL', 'HAVE_PROTOBUF']
1069
1070###################################################
1071#
1072# Define a SCons builder for configuration flag headers.
1073#
1074###################################################
1075
1076# This function generates a config header file that #defines the
1077# variable symbol to the current variable setting (0 or 1).  The source
1078# operands are the name of the variable and a Value node containing the
1079# value of the variable.
1080def build_config_file(target, source, env):
1081    (variable, value) = [s.get_contents() for s in source]
1082    f = file(str(target[0]), 'w')
1083    print >> f, '#define', variable, value
1084    f.close()
1085    return None
1086
1087# Combine the two functions into a scons Action object.
1088config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1089
1090# The emitter munges the source & target node lists to reflect what
1091# we're really doing.
1092def config_emitter(target, source, env):
1093    # extract variable name from Builder arg
1094    variable = str(target[0])
1095    # True target is config header file
1096    target = joinpath('config', variable.lower() + '.hh')
1097    val = env[variable]
1098    if isinstance(val, bool):
1099        # Force value to 0/1
1100        val = int(val)
1101    elif isinstance(val, str):
1102        val = '"' + val + '"'
1103
1104    # Sources are variable name & value (packaged in SCons Value nodes)
1105    return ([target], [Value(variable), Value(val)])
1106
1107config_builder = Builder(emitter = config_emitter, action = config_action)
1108
1109main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1110
1111# libelf build is shared across all configs in the build root.
1112main.SConscript('ext/libelf/SConscript',
1113                variant_dir = joinpath(build_root, 'libelf'))
1114
1115# gzstream build is shared across all configs in the build root.
1116main.SConscript('ext/gzstream/SConscript',
1117                variant_dir = joinpath(build_root, 'gzstream'))
1118
1119# libfdt build is shared across all configs in the build root.
1120main.SConscript('ext/libfdt/SConscript',
1121                variant_dir = joinpath(build_root, 'libfdt'))
1122
1123# fputils build is shared across all configs in the build root.
1124main.SConscript('ext/fputils/SConscript',
1125                variant_dir = joinpath(build_root, 'fputils'))
1126
1127###################################################
1128#
1129# This function is used to set up a directory with switching headers
1130#
1131###################################################
1132
1133main['ALL_ISA_LIST'] = all_isa_list
1134def make_switching_dir(dname, switch_headers, env):
1135    # Generate the header.  target[0] is the full path of the output
1136    # header to generate.  'source' is a dummy variable, since we get the
1137    # list of ISAs from env['ALL_ISA_LIST'].
1138    def gen_switch_hdr(target, source, env):
1139        fname = str(target[0])
1140        f = open(fname, 'w')
1141        isa = env['TARGET_ISA'].lower()
1142        print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1143        f.close()
1144
1145    # Build SCons Action object. 'varlist' specifies env vars that this
1146    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1147    # should get re-executed.
1148    switch_hdr_action = MakeAction(gen_switch_hdr,
1149                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1150
1151    # Instantiate actions for each header
1152    for hdr in switch_headers:
1153        env.Command(hdr, [], switch_hdr_action)
1154Export('make_switching_dir')
1155
1156###################################################
1157#
1158# Define build environments for selected configurations.
1159#
1160###################################################
1161
1162for variant_path in variant_paths:
1163    print "Building in", variant_path
1164
1165    # Make a copy of the build-root environment to use for this config.
1166    env = main.Clone()
1167    env['BUILDDIR'] = variant_path
1168
1169    # variant_dir is the tail component of build path, and is used to
1170    # determine the build parameters (e.g., 'ALPHA_SE')
1171    (build_root, variant_dir) = splitpath(variant_path)
1172
1173    # Set env variables according to the build directory config.
1174    sticky_vars.files = []
1175    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1176    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1177    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1178    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1179    if isfile(current_vars_file):
1180        sticky_vars.files.append(current_vars_file)
1181        print "Using saved variables file %s" % current_vars_file
1182    else:
1183        # Build dir-specific variables file doesn't exist.
1184
1185        # Make sure the directory is there so we can create it later
1186        opt_dir = dirname(current_vars_file)
1187        if not isdir(opt_dir):
1188            mkdir(opt_dir)
1189
1190        # Get default build variables from source tree.  Variables are
1191        # normally determined by name of $VARIANT_DIR, but can be
1192        # overridden by '--default=' arg on command line.
1193        default = GetOption('default')
1194        opts_dir = joinpath(main.root.abspath, 'build_opts')
1195        if default:
1196            default_vars_files = [joinpath(build_root, 'variables', default),
1197                                  joinpath(opts_dir, default)]
1198        else:
1199            default_vars_files = [joinpath(opts_dir, variant_dir)]
1200        existing_files = filter(isfile, default_vars_files)
1201        if existing_files:
1202            default_vars_file = existing_files[0]
1203            sticky_vars.files.append(default_vars_file)
1204            print "Variables file %s not found,\n  using defaults in %s" \
1205                  % (current_vars_file, default_vars_file)
1206        else:
1207            print "Error: cannot find variables file %s or " \
1208                  "default file(s) %s" \
1209                  % (current_vars_file, ' or '.join(default_vars_files))
1210            Exit(1)
1211
1212    # Apply current variable settings to env
1213    sticky_vars.Update(env)
1214
1215    help_texts["local_vars"] += \
1216        "Build variables for %s:\n" % variant_dir \
1217                 + sticky_vars.GenerateHelpText(env)
1218
1219    # Process variable settings.
1220
1221    if not have_fenv and env['USE_FENV']:
1222        print "Warning: <fenv.h> not available; " \
1223              "forcing USE_FENV to False in", variant_dir + "."
1224        env['USE_FENV'] = False
1225
1226    if not env['USE_FENV']:
1227        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1228        print "         FP results may deviate slightly from other platforms."
1229
1230    if env['EFENCE']:
1231        env.Append(LIBS=['efence'])
1232
1233    if env['USE_KVM']:
1234        if not have_kvm:
1235            print "Warning: Can not enable KVM, host seems to lack KVM support"
1236            env['USE_KVM'] = False
1237        elif not have_posix_timers:
1238            print "Warning: Can not enable KVM, host seems to lack support " \
1239                "for POSIX timers"
1240            env['USE_KVM'] = False
1241        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1242            print "Info: KVM support disabled due to unsupported host and " \
1243                "target ISA combination"
1244            env['USE_KVM'] = False
1245
1246    # Save sticky variable settings back to current variables file
1247    sticky_vars.Save(current_vars_file, env)
1248
1249    if env['USE_SSE2']:
1250        env.Append(CCFLAGS=['-msse2'])
1251
1252    # The src/SConscript file sets up the build rules in 'env' according
1253    # to the configured variables.  It returns a list of environments,
1254    # one for each variant build (debug, opt, etc.)
1255    envList = SConscript('src/SConscript', variant_dir = variant_path,
1256                         exports = 'env')
1257
1258    # Set up the regression tests for each build.
1259    for e in envList:
1260        SConscript('tests/SConscript',
1261                   variant_dir = joinpath(variant_path, 'tests', e.Label),
1262                   exports = { 'env' : e }, duplicate = False)
1263
1264# base help text
1265Help('''
1266Usage: scons [scons options] [build variables] [target(s)]
1267
1268Extra scons options:
1269%(options)s
1270
1271Global build variables:
1272%(global_vars)s
1273
1274%(local_vars)s
1275''' % help_texts)
1276