SConstruct revision 11342
1955SN/A# -*- mode:python -*-
2955SN/A
37816Ssteve.reinhardt@amd.com# Copyright (c) 2013, 2015 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 itertools
1135871Snate@binkert.orgimport os
1145273Sstever@gmail.comimport re
1156655Snate@binkert.orgimport subprocess
1168878Ssteve.reinhardt@amd.comimport sys
1176655Snate@binkert.org
1186655Snate@binkert.orgfrom os import mkdir, environ
1196655Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1206655Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1215871Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1226654Snate@binkert.org
1238947Sandreas.hansson@arm.com# SCons includes
1245396Ssaidi@eecs.umich.eduimport SCons
1258120Sgblack@eecs.umich.eduimport SCons.Node
1268120Sgblack@eecs.umich.edu
1278120Sgblack@eecs.umich.eduextra_python_paths = [
1288120Sgblack@eecs.umich.edu    Dir('src/python').srcnode().abspath, # gem5 includes
1298120Sgblack@eecs.umich.edu    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1308120Sgblack@eecs.umich.edu    ]
1318120Sgblack@eecs.umich.edu
1328120Sgblack@eecs.umich.edusys.path[1:1] = extra_python_paths
1338879Ssteve.reinhardt@amd.com
1348879Ssteve.reinhardt@amd.comfrom m5.util import compareVersions, readCommand
1358879Ssteve.reinhardt@amd.comfrom m5.util.terminal import get_termcap
1368879Ssteve.reinhardt@amd.com
1378879Ssteve.reinhardt@amd.comhelp_texts = {
1388879Ssteve.reinhardt@amd.com    "options" : "",
1398879Ssteve.reinhardt@amd.com    "global_vars" : "",
1408879Ssteve.reinhardt@amd.com    "local_vars" : ""
1418879Ssteve.reinhardt@amd.com}
1428879Ssteve.reinhardt@amd.com
1438879Ssteve.reinhardt@amd.comExport("help_texts")
1448879Ssteve.reinhardt@amd.com
1458879Ssteve.reinhardt@amd.com
1468120Sgblack@eecs.umich.edu# There's a bug in scons in that (1) by default, the help texts from
1478120Sgblack@eecs.umich.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1488120Sgblack@eecs.umich.edu# and (2) you can override the help displayed by 'scons -h' using the
1498120Sgblack@eecs.umich.edu# Help() function, but these two features are incompatible: once
1508120Sgblack@eecs.umich.edu# you've overridden the help text using Help(), there's no way to get
1518120Sgblack@eecs.umich.edu# at the help texts from AddOptions.  See:
1528120Sgblack@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1538120Sgblack@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1548120Sgblack@eecs.umich.edu# This hack lets us extract the help text from AddOptions and
1558120Sgblack@eecs.umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1568120Sgblack@eecs.umich.edu# we can just use AddOption directly.
1578120Sgblack@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1588120Sgblack@eecs.umich.edu    col_width = 30
1598120Sgblack@eecs.umich.edu
1608879Ssteve.reinhardt@amd.com    help = "  " + ", ".join(args)
1618879Ssteve.reinhardt@amd.com    if "help" in kwargs:
1628879Ssteve.reinhardt@amd.com        length = len(help)
1638879Ssteve.reinhardt@amd.com        if length >= col_width:
1648879Ssteve.reinhardt@amd.com            help += "\n" + " " * col_width
1658879Ssteve.reinhardt@amd.com        else:
1668879Ssteve.reinhardt@amd.com            help += " " * (col_width - length)
1678879Ssteve.reinhardt@amd.com        help += kwargs["help"]
1688879Ssteve.reinhardt@amd.com    help_texts["options"] += help + "\n"
1698879Ssteve.reinhardt@amd.com
1708879Ssteve.reinhardt@amd.com    AddOption(*args, **kwargs)
1718879Ssteve.reinhardt@amd.com
1728120Sgblack@eecs.umich.eduAddLocalOption('--colors', dest='use_colors', action='store_true',
1738947Sandreas.hansson@arm.com               help="Add color to abbreviated scons output")
1747816Ssteve.reinhardt@amd.comAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1755871Snate@binkert.org               help="Don't add color to abbreviated scons output")
1765871Snate@binkert.orgAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1776121Snate@binkert.org               action='store_true',
1785871Snate@binkert.org               help="Build with support for C++-based configuration")
1795871Snate@binkert.orgAddLocalOption('--default', dest='default', type='string', action='store',
1806003Snate@binkert.org               help='Override which build_opts file to use for defaults')
1818980Ssteve.reinhardt@amd.comAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
182955SN/A               help='Disable style checking hooks')
1835871Snate@binkert.orgAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1845871Snate@binkert.org               help='Disable Link-Time Optimization for fast')
1855871Snate@binkert.orgAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1865871Snate@binkert.org               help='Update test reference outputs')
187955SN/AAddLocalOption('--verbose', dest='verbose', action='store_true',
1886121Snate@binkert.org               help='Print full tool command lines')
1898881Smarc.orr@gmail.comAddLocalOption('--without-python', dest='without_python',
1906121Snate@binkert.org               action='store_true',
1916121Snate@binkert.org               help='Build without Python configuration support')
1921533SN/AAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1936655Snate@binkert.org               action='store_true',
1946655Snate@binkert.org               help='Disable linking against tcmalloc')
1956655Snate@binkert.orgAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1966655Snate@binkert.org               help='Build with Undefined Behavior Sanitizer if available')
1975871Snate@binkert.orgAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1985871Snate@binkert.org               help='Build with Address Sanitizer if available')
1995863Snate@binkert.org
2005871Snate@binkert.orgtermcap = get_termcap(GetOption('use_colors'))
2018878Ssteve.reinhardt@amd.com
2025871Snate@binkert.org########################################################################
2035871Snate@binkert.org#
2045871Snate@binkert.org# Set up the main build environment.
2055863Snate@binkert.org#
2066121Snate@binkert.org########################################################################
2075863Snate@binkert.org
2085871Snate@binkert.org# export TERM so that clang reports errors in color
2098336Ssteve.reinhardt@amd.comuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
2108336Ssteve.reinhardt@amd.com                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
2118336Ssteve.reinhardt@amd.com                 'PYTHONPATH', 'RANLIB', 'SWIG', 'TERM' ])
2128336Ssteve.reinhardt@amd.com
2134678Snate@binkert.orguse_prefixes = [
2148336Ssteve.reinhardt@amd.com    "ASAN_",           # address sanitizer symbolizer path and settings
2158336Ssteve.reinhardt@amd.com    "CCACHE_",         # ccache (caching compiler wrapper) configuration
2168336Ssteve.reinhardt@amd.com    "CCC_",            # clang static analyzer configuration
2174678Snate@binkert.org    "DISTCC_",         # distcc (distributed compiler wrapper) configuration
2184678Snate@binkert.org    "INCLUDE_SERVER_", # distcc pump server settings
2194678Snate@binkert.org    "M5",              # M5 configuration (e.g., path to kernels)
2204678Snate@binkert.org    ]
2217827Snate@binkert.org
2227827Snate@binkert.orguse_env = {}
2238336Ssteve.reinhardt@amd.comfor key,val in sorted(os.environ.iteritems()):
2244678Snate@binkert.org    if key in use_vars or \
2258336Ssteve.reinhardt@amd.com            any([key.startswith(prefix) for prefix in use_prefixes]):
2268336Ssteve.reinhardt@amd.com        use_env[key] = val
2278336Ssteve.reinhardt@amd.com
2288336Ssteve.reinhardt@amd.com# Tell scons to avoid implicit command dependencies to avoid issues
2298336Ssteve.reinhardt@amd.com# with the param wrappes being compiled twice (see
2308336Ssteve.reinhardt@amd.com# http://scons.tigris.org/issues/show_bug.cgi?id=2811)
2315871Snate@binkert.orgmain = Environment(ENV=use_env, IMPLICIT_COMMAND_DEPENDENCIES=0)
2325871Snate@binkert.orgmain.Decider('MD5-timestamp')
2338336Ssteve.reinhardt@amd.commain.root = Dir(".")         # The current directory (where this file lives).
2348336Ssteve.reinhardt@amd.commain.srcdir = Dir("src")     # The source directory
2358336Ssteve.reinhardt@amd.com
2368336Ssteve.reinhardt@amd.commain_dict_keys = main.Dictionary().keys()
2378336Ssteve.reinhardt@amd.com
2385871Snate@binkert.org# Check that we have a C/C++ compiler
2398336Ssteve.reinhardt@amd.comif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2408336Ssteve.reinhardt@amd.com    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2418336Ssteve.reinhardt@amd.com    Exit(1)
2428336Ssteve.reinhardt@amd.com
2438336Ssteve.reinhardt@amd.com# Check that swig is present
2444678Snate@binkert.orgif not 'SWIG' in main_dict_keys:
2455871Snate@binkert.org    print "swig is not installed (package swig on Ubuntu and RedHat)"
2464678Snate@binkert.org    Exit(1)
2478336Ssteve.reinhardt@amd.com
2488336Ssteve.reinhardt@amd.com# add useful python code PYTHONPATH so it can be used by subprocesses
2498336Ssteve.reinhardt@amd.com# as well
2508336Ssteve.reinhardt@amd.commain.AppendENVPath('PYTHONPATH', extra_python_paths)
2518336Ssteve.reinhardt@amd.com
2528336Ssteve.reinhardt@amd.com########################################################################
2538336Ssteve.reinhardt@amd.com#
2548336Ssteve.reinhardt@amd.com# Mercurial Stuff.
2558336Ssteve.reinhardt@amd.com#
2568336Ssteve.reinhardt@amd.com# If the gem5 directory is a mercurial repository, we should do some
2578336Ssteve.reinhardt@amd.com# extra things.
2588336Ssteve.reinhardt@amd.com#
2598336Ssteve.reinhardt@amd.com########################################################################
2608336Ssteve.reinhardt@amd.com
2618336Ssteve.reinhardt@amd.comhgdir = main.root.Dir(".hg")
2628336Ssteve.reinhardt@amd.com
2638336Ssteve.reinhardt@amd.commercurial_style_message = """
2645871Snate@binkert.orgYou're missing the gem5 style hook, which automatically checks your code
2656121Snate@binkert.orgagainst the gem5 style rules on hg commit and qrefresh commands.  This
266955SN/Ascript will now install the hook in your .hg/hgrc file.
267955SN/APress enter to continue, or ctrl-c to abort: """
2682632Sstever@eecs.umich.edu
2692632Sstever@eecs.umich.edumercurial_style_hook = """
270955SN/A# The following lines were automatically added by gem5/SConstruct
271955SN/A# to provide the gem5 style-checking hooks
272955SN/A[extensions]
273955SN/Astyle = %s/util/style.py
2748878Ssteve.reinhardt@amd.com
275955SN/A[hooks]
2762632Sstever@eecs.umich.edupretxncommit.style = python:style.check_style
2772632Sstever@eecs.umich.edupre-qrefresh.style = python:style.check_style
2782632Sstever@eecs.umich.edu# End of SConstruct additions
2792632Sstever@eecs.umich.edu
2802632Sstever@eecs.umich.edu""" % (main.root.abspath)
2812632Sstever@eecs.umich.edu
2822632Sstever@eecs.umich.edumercurial_lib_not_found = """
2838268Ssteve.reinhardt@amd.comMercurial libraries cannot be found, ignoring style hook.  If
2848268Ssteve.reinhardt@amd.comyou are a gem5 developer, please fix this and run the style
2858268Ssteve.reinhardt@amd.comhook. It is important.
2868268Ssteve.reinhardt@amd.com"""
2878268Ssteve.reinhardt@amd.com
2888268Ssteve.reinhardt@amd.com# Check for style hook and prompt for installation if it's not there.
2898268Ssteve.reinhardt@amd.com# Skip this if --ignore-style was specified, there's no .hg dir to
2902632Sstever@eecs.umich.edu# install a hook in, or there's no interactive terminal to prompt.
2912632Sstever@eecs.umich.eduif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2922632Sstever@eecs.umich.edu    style_hook = True
2932632Sstever@eecs.umich.edu    try:
2948268Ssteve.reinhardt@amd.com        from mercurial import ui
2952632Sstever@eecs.umich.edu        ui = ui.ui()
2968268Ssteve.reinhardt@amd.com        ui.readconfig(hgdir.File('hgrc').abspath)
2978268Ssteve.reinhardt@amd.com        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2988268Ssteve.reinhardt@amd.com                     ui.config('hooks', 'pre-qrefresh.style', None)
2998268Ssteve.reinhardt@amd.com    except ImportError:
3003718Sstever@eecs.umich.edu        print mercurial_lib_not_found
3012634Sstever@eecs.umich.edu
3022634Sstever@eecs.umich.edu    if not style_hook:
3035863Snate@binkert.org        print mercurial_style_message,
3042638Sstever@eecs.umich.edu        # continue unless user does ctrl-c/ctrl-d etc.
3058268Ssteve.reinhardt@amd.com        try:
3062632Sstever@eecs.umich.edu            raw_input()
3072632Sstever@eecs.umich.edu        except:
3082632Sstever@eecs.umich.edu            print "Input exception, exiting scons.\n"
3092632Sstever@eecs.umich.edu            sys.exit(1)
3102632Sstever@eecs.umich.edu        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
3111858SN/A        print "Adding style hook to", hgrc_path, "\n"
3123716Sstever@eecs.umich.edu        try:
3132638Sstever@eecs.umich.edu            hgrc = open(hgrc_path, 'a')
3142638Sstever@eecs.umich.edu            hgrc.write(mercurial_style_hook)
3152638Sstever@eecs.umich.edu            hgrc.close()
3162638Sstever@eecs.umich.edu        except:
3172638Sstever@eecs.umich.edu            print "Error updating", hgrc_path
3182638Sstever@eecs.umich.edu            sys.exit(1)
3192638Sstever@eecs.umich.edu
3205863Snate@binkert.org
3215863Snate@binkert.org###################################################
3225863Snate@binkert.org#
323955SN/A# Figure out which configurations to set up based on the path(s) of
3245341Sstever@gmail.com# the target(s).
3255341Sstever@gmail.com#
3265863Snate@binkert.org###################################################
3277756SAli.Saidi@ARM.com
3285341Sstever@gmail.com# Find default configuration & binary.
3296121Snate@binkert.orgDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
3304494Ssaidi@eecs.umich.edu
3316121Snate@binkert.org# helper function: find last occurrence of element in list
3321105SN/Adef rfind(l, elt, offs = -1):
3332667Sstever@eecs.umich.edu    for i in range(len(l)+offs, 0, -1):
3342667Sstever@eecs.umich.edu        if l[i] == elt:
3352667Sstever@eecs.umich.edu            return i
3362667Sstever@eecs.umich.edu    raise ValueError, "element not found"
3376121Snate@binkert.org
3382667Sstever@eecs.umich.edu# Take a list of paths (or SCons Nodes) and return a list with all
3395341Sstever@gmail.com# paths made absolute and ~-expanded.  Paths will be interpreted
3405863Snate@binkert.org# relative to the launch directory unless a different root is provided
3415341Sstever@gmail.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
3425341Sstever@gmail.com    return [abspath(joinpath(root, expanduser(str(p))))
3435341Sstever@gmail.com            for p in path_list]
3448120Sgblack@eecs.umich.edu
3455341Sstever@gmail.com# Each target must have 'build' in the interior of the path; the
3468120Sgblack@eecs.umich.edu# directory below this will determine the build parameters.  For
3475341Sstever@gmail.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3488120Sgblack@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
3496121Snate@binkert.org# follow 'build' in the build path.
3506121Snate@binkert.org
3518980Ssteve.reinhardt@amd.com# The funky assignment to "[:]" is needed to replace the list contents
3525397Ssaidi@eecs.umich.edu# in place rather than reassign the symbol to a new list, which
3535397Ssaidi@eecs.umich.edu# doesn't work (obviously!).
3547727SAli.Saidi@ARM.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3558268Ssteve.reinhardt@amd.com
3566168Snate@binkert.org# Generate a list of the unique build roots and configs that the
3575341Sstever@gmail.com# collected targets reference.
3588120Sgblack@eecs.umich.eduvariant_paths = []
3598120Sgblack@eecs.umich.edubuild_root = None
3608120Sgblack@eecs.umich.edufor t in BUILD_TARGETS:
3616814Sgblack@eecs.umich.edu    path_dirs = t.split('/')
3625863Snate@binkert.org    try:
3638120Sgblack@eecs.umich.edu        build_top = rfind(path_dirs, 'build', -2)
3645341Sstever@gmail.com    except:
3655863Snate@binkert.org        print "Error: no non-leaf 'build' dir found on target path", t
3668268Ssteve.reinhardt@amd.com        Exit(1)
3676121Snate@binkert.org    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3686121Snate@binkert.org    if not build_root:
3698268Ssteve.reinhardt@amd.com        build_root = this_build_root
3705742Snate@binkert.org    else:
3715742Snate@binkert.org        if this_build_root != build_root:
3725341Sstever@gmail.com            print "Error: build targets not under same build root\n"\
3735742Snate@binkert.org                  "  %s\n  %s" % (build_root, this_build_root)
3745742Snate@binkert.org            Exit(1)
3755341Sstever@gmail.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
3766017Snate@binkert.org    if variant_path not in variant_paths:
3776121Snate@binkert.org        variant_paths.append(variant_path)
3786017Snate@binkert.org
3797816Ssteve.reinhardt@amd.com# Make sure build_root exists (might not if this is the first build there)
3807756SAli.Saidi@ARM.comif not isdir(build_root):
3817756SAli.Saidi@ARM.com    mkdir(build_root)
3827756SAli.Saidi@ARM.commain['BUILDROOT'] = build_root
3837756SAli.Saidi@ARM.com
3847756SAli.Saidi@ARM.comExport('main')
3857756SAli.Saidi@ARM.com
3867756SAli.Saidi@ARM.commain.SConsignFile(joinpath(build_root, "sconsign"))
3877756SAli.Saidi@ARM.com
3887816Ssteve.reinhardt@amd.com# Default duplicate option is to use hard links, but this messes up
3897816Ssteve.reinhardt@amd.com# when you use emacs to edit a file in the target dir, as emacs moves
3907816Ssteve.reinhardt@amd.com# file to file~ then copies to file, breaking the link.  Symbolic
3917816Ssteve.reinhardt@amd.com# (soft) links work better.
3927816Ssteve.reinhardt@amd.commain.SetOption('duplicate', 'soft-copy')
3937816Ssteve.reinhardt@amd.com
3947816Ssteve.reinhardt@amd.com#
3957816Ssteve.reinhardt@amd.com# Set up global sticky variables... these are common to an entire build
3967816Ssteve.reinhardt@amd.com# tree (not specific to a particular build like ALPHA_SE)
3977816Ssteve.reinhardt@amd.com#
3987756SAli.Saidi@ARM.com
3997816Ssteve.reinhardt@amd.comglobal_vars_file = joinpath(build_root, 'variables.global')
4007816Ssteve.reinhardt@amd.com
4017816Ssteve.reinhardt@amd.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
4027816Ssteve.reinhardt@amd.com
4037816Ssteve.reinhardt@amd.comglobal_vars.AddVariables(
4047816Ssteve.reinhardt@amd.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
4057816Ssteve.reinhardt@amd.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
4067816Ssteve.reinhardt@amd.com    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
4077816Ssteve.reinhardt@amd.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
4087816Ssteve.reinhardt@amd.com    ('BATCH', 'Use batch pool for build and tests', False),
4097816Ssteve.reinhardt@amd.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
4107816Ssteve.reinhardt@amd.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
4117816Ssteve.reinhardt@amd.com    ('EXTRAS', 'Add extra directories to the compilation', '')
4127816Ssteve.reinhardt@amd.com    )
4137816Ssteve.reinhardt@amd.com
4147816Ssteve.reinhardt@amd.com# Update main environment with values from ARGUMENTS & global_vars_file
4157816Ssteve.reinhardt@amd.comglobal_vars.Update(main)
4167816Ssteve.reinhardt@amd.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
4177816Ssteve.reinhardt@amd.com
4187816Ssteve.reinhardt@amd.com# Save sticky variable settings back to current variables file
4197816Ssteve.reinhardt@amd.comglobal_vars.Save(global_vars_file, main)
4207816Ssteve.reinhardt@amd.com
4217816Ssteve.reinhardt@amd.com# Parse EXTRAS variable to build list of all directories where we're
4227816Ssteve.reinhardt@amd.com# look for sources etc.  This list is exported as extras_dir_list.
4237816Ssteve.reinhardt@amd.combase_dir = main.srcdir.abspath
4247816Ssteve.reinhardt@amd.comif main['EXTRAS']:
4257816Ssteve.reinhardt@amd.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
4267816Ssteve.reinhardt@amd.comelse:
4277816Ssteve.reinhardt@amd.com    extras_dir_list = []
4287816Ssteve.reinhardt@amd.com
4297816Ssteve.reinhardt@amd.comExport('base_dir')
4307816Ssteve.reinhardt@amd.comExport('extras_dir_list')
4317816Ssteve.reinhardt@amd.com
4327816Ssteve.reinhardt@amd.com# the ext directory should be on the #includes path
4337816Ssteve.reinhardt@amd.commain.Append(CPPPATH=[Dir('ext')])
4347816Ssteve.reinhardt@amd.com
4357816Ssteve.reinhardt@amd.comdef strip_build_path(path, env):
4367816Ssteve.reinhardt@amd.com    path = str(path)
4377816Ssteve.reinhardt@amd.com    variant_base = env['BUILDROOT'] + os.path.sep
4387816Ssteve.reinhardt@amd.com    if path.startswith(variant_base):
4397816Ssteve.reinhardt@amd.com        path = path[len(variant_base):]
4407816Ssteve.reinhardt@amd.com    elif path.startswith('build/'):
4417816Ssteve.reinhardt@amd.com        path = path[6:]
4427816Ssteve.reinhardt@amd.com    return path
4437816Ssteve.reinhardt@amd.com
4447816Ssteve.reinhardt@amd.com# Generate a string of the form:
4457816Ssteve.reinhardt@amd.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
4467816Ssteve.reinhardt@amd.com# to print while building.
4477816Ssteve.reinhardt@amd.comclass Transform(object):
4487816Ssteve.reinhardt@amd.com    # all specific color settings should be here and nowhere else
4497816Ssteve.reinhardt@amd.com    tool_color = termcap.Normal
4507816Ssteve.reinhardt@amd.com    pfx_color = termcap.Yellow
4517816Ssteve.reinhardt@amd.com    srcs_color = termcap.Yellow + termcap.Bold
4527816Ssteve.reinhardt@amd.com    arrow_color = termcap.Blue + termcap.Bold
4537816Ssteve.reinhardt@amd.com    tgts_color = termcap.Yellow + termcap.Bold
4547816Ssteve.reinhardt@amd.com
4557816Ssteve.reinhardt@amd.com    def __init__(self, tool, max_sources=99):
4567816Ssteve.reinhardt@amd.com        self.format = self.tool_color + (" [%8s] " % tool) \
4577816Ssteve.reinhardt@amd.com                      + self.pfx_color + "%s" \
4587816Ssteve.reinhardt@amd.com                      + self.srcs_color + "%s" \
4597816Ssteve.reinhardt@amd.com                      + self.arrow_color + " -> " \
4608947Sandreas.hansson@arm.com                      + self.tgts_color + "%s" \
4618947Sandreas.hansson@arm.com                      + termcap.Normal
4627756SAli.Saidi@ARM.com        self.max_sources = max_sources
4638120Sgblack@eecs.umich.edu
4647756SAli.Saidi@ARM.com    def __call__(self, target, source, env, for_signature=None):
4657756SAli.Saidi@ARM.com        # truncate source list according to max_sources param
4667756SAli.Saidi@ARM.com        source = source[0:self.max_sources]
4677756SAli.Saidi@ARM.com        def strip(f):
4687816Ssteve.reinhardt@amd.com            return strip_build_path(str(f), env)
4697816Ssteve.reinhardt@amd.com        if len(source) > 0:
4707816Ssteve.reinhardt@amd.com            srcs = map(strip, source)
4717816Ssteve.reinhardt@amd.com        else:
4727816Ssteve.reinhardt@amd.com            srcs = ['']
4737816Ssteve.reinhardt@amd.com        tgts = map(strip, target)
4747816Ssteve.reinhardt@amd.com        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4757816Ssteve.reinhardt@amd.com        # operation that has nothing to do with paths.
4767816Ssteve.reinhardt@amd.com        com_pfx = os.path.commonprefix(srcs + tgts)
4777816Ssteve.reinhardt@amd.com        com_pfx_len = len(com_pfx)
4787756SAli.Saidi@ARM.com        if com_pfx:
4797756SAli.Saidi@ARM.com            # do some cleanup and sanity checking on common prefix
4806654Snate@binkert.org            if com_pfx[-1] == ".":
4816654Snate@binkert.org                # prefix matches all but file extension: ok
4825871Snate@binkert.org                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4836121Snate@binkert.org                com_pfx = com_pfx[0:-1]
4846121Snate@binkert.org            elif com_pfx[-1] == "/":
4856121Snate@binkert.org                # common prefix is directory path: OK
4868946Sandreas.hansson@arm.com                pass
4878737Skoansin.tan@gmail.com            else:
4883940Ssaidi@eecs.umich.edu                src0_len = len(srcs[0])
4893918Ssaidi@eecs.umich.edu                tgt0_len = len(tgts[0])
4903918Ssaidi@eecs.umich.edu                if src0_len == com_pfx_len:
4911858SN/A                    # source is a substring of target, OK
4926121Snate@binkert.org                    pass
4937739Sgblack@eecs.umich.edu                elif tgt0_len == com_pfx_len:
4947739Sgblack@eecs.umich.edu                    # target is a substring of source, need to back up to
4956143Snate@binkert.org                    # avoid empty string on RHS of arrow
4967618SAli.Saidi@arm.com                    sep_idx = com_pfx.rfind(".")
4977618SAli.Saidi@arm.com                    if sep_idx != -1:
4987618SAli.Saidi@arm.com                        com_pfx = com_pfx[0:sep_idx]
4997618SAli.Saidi@arm.com                    else:
5008614Sgblack@eecs.umich.edu                        com_pfx = ''
5017618SAli.Saidi@arm.com                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
5027618SAli.Saidi@arm.com                    # still splitting at file extension: ok
5037618SAli.Saidi@arm.com                    pass
5047739Sgblack@eecs.umich.edu                else:
5058946Sandreas.hansson@arm.com                    # probably a fluke; ignore it
5068946Sandreas.hansson@arm.com                    com_pfx = ''
5076121Snate@binkert.org        # recalculate length in case com_pfx was modified
5083940Ssaidi@eecs.umich.edu        com_pfx_len = len(com_pfx)
5096121Snate@binkert.org        def fmt(files):
5107739Sgblack@eecs.umich.edu            f = map(lambda s: s[com_pfx_len:], files)
5117739Sgblack@eecs.umich.edu            return ', '.join(f)
5127739Sgblack@eecs.umich.edu        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
5137739Sgblack@eecs.umich.edu
5147739Sgblack@eecs.umich.eduExport('Transform')
5157739Sgblack@eecs.umich.edu
5168737Skoansin.tan@gmail.com# enable the regression script to use the termcap
5178737Skoansin.tan@gmail.commain['TERMCAP'] = termcap
5188737Skoansin.tan@gmail.com
5198737Skoansin.tan@gmail.comif GetOption('verbose'):
5208737Skoansin.tan@gmail.com    def MakeAction(action, string, *args, **kwargs):
5218737Skoansin.tan@gmail.com        return Action(action, *args, **kwargs)
5228737Skoansin.tan@gmail.comelse:
5238737Skoansin.tan@gmail.com    MakeAction = Action
5248737Skoansin.tan@gmail.com    main['CCCOMSTR']        = Transform("CC")
5258737Skoansin.tan@gmail.com    main['CXXCOMSTR']       = Transform("CXX")
5268737Skoansin.tan@gmail.com    main['ASCOMSTR']        = Transform("AS")
5278737Skoansin.tan@gmail.com    main['SWIGCOMSTR']      = Transform("SWIG")
5288737Skoansin.tan@gmail.com    main['ARCOMSTR']        = Transform("AR", 0)
5298737Skoansin.tan@gmail.com    main['LINKCOMSTR']      = Transform("LINK", 0)
5308737Skoansin.tan@gmail.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
5318737Skoansin.tan@gmail.com    main['M4COMSTR']        = Transform("M4")
5328737Skoansin.tan@gmail.com    main['SHCCCOMSTR']      = Transform("SHCC")
5338737Skoansin.tan@gmail.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
5348946Sandreas.hansson@arm.comExport('MakeAction')
5358946Sandreas.hansson@arm.com
5368946Sandreas.hansson@arm.com# Initialize the Link-Time Optimization (LTO) flags
5378946Sandreas.hansson@arm.commain['LTO_CCFLAGS'] = []
5388946Sandreas.hansson@arm.commain['LTO_LDFLAGS'] = []
5398946Sandreas.hansson@arm.com
5403918Ssaidi@eecs.umich.edu# According to the readme, tcmalloc works best if the compiler doesn't
5413918Ssaidi@eecs.umich.edu# assume that we're using the builtin malloc and friends. These flags
5423940Ssaidi@eecs.umich.edu# are compiler-specific, so we need to set them after we detect which
5433918Ssaidi@eecs.umich.edu# compiler we're using.
5443918Ssaidi@eecs.umich.edumain['TCMALLOC_CCFLAGS'] = []
5456157Snate@binkert.org
5466157Snate@binkert.orgCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5476157Snate@binkert.orgCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5486157Snate@binkert.org
5495397Ssaidi@eecs.umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5505397Ssaidi@eecs.umich.edumain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5516121Snate@binkert.orgif main['GCC'] + main['CLANG'] > 1:
5526121Snate@binkert.org    print 'Error: How can we have two at the same time?'
5536121Snate@binkert.org    Exit(1)
5546121Snate@binkert.org
5556121Snate@binkert.org# Set up default C++ compiler flags
5566121Snate@binkert.orgif main['GCC'] or main['CLANG']:
5575397Ssaidi@eecs.umich.edu    # As gcc and clang share many flags, do the common parts here
5581851SN/A    main.Append(CCFLAGS=['-pipe'])
5591851SN/A    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5607739Sgblack@eecs.umich.edu    # Enable -Wall and -Wextra and then disable the few warnings that
561955SN/A    # we consistently violate
5623053Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
5636121Snate@binkert.org                         '-Wno-sign-compare', '-Wno-unused-parameter'])
5643053Sstever@eecs.umich.edu    # We always compile using C++11
5653053Sstever@eecs.umich.edu    main.Append(CXXFLAGS=['-std=c++11'])
5663053Sstever@eecs.umich.eduelse:
5673053Sstever@eecs.umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5683053Sstever@eecs.umich.edu    print "Don't know what compiler options to use for your compiler."
5696654Snate@binkert.org    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5703053Sstever@eecs.umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
5714742Sstever@eecs.umich.edu    if not CXX_version:
5724742Sstever@eecs.umich.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5733053Sstever@eecs.umich.edu               termcap.Normal
5743053Sstever@eecs.umich.edu    else:
5753053Sstever@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
5768960Ssteve.reinhardt@amd.com    print "       If you're trying to use a compiler other than GCC"
5776654Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
5783053Sstever@eecs.umich.edu    print "       environment."
5793053Sstever@eecs.umich.edu    print "       "
5803053Sstever@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
5813053Sstever@eecs.umich.edu    print "       above you will need to ease fix SConstruct and "
5822667Sstever@eecs.umich.edu    print "       src/SConscript to support that compiler."
5834554Sbinkertn@umich.edu    Exit(1)
5846121Snate@binkert.org
5852667Sstever@eecs.umich.eduif main['GCC']:
5864554Sbinkertn@umich.edu    # Check for a supported version of gcc. >= 4.7 is chosen for its
5874554Sbinkertn@umich.edu    # level of c++11 support. See
5884554Sbinkertn@umich.edu    # http://gcc.gnu.org/projects/cxx0x.html for details.
5896121Snate@binkert.org    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5904554Sbinkertn@umich.edu    if compareVersions(gcc_version, "4.7") < 0:
5914554Sbinkertn@umich.edu        print 'Error: gcc version 4.7 or newer required.'
5924554Sbinkertn@umich.edu        print '       Installed version:', gcc_version
5934781Snate@binkert.org        Exit(1)
5944554Sbinkertn@umich.edu
5954554Sbinkertn@umich.edu    main['GCC_VERSION'] = gcc_version
5962667Sstever@eecs.umich.edu
5974554Sbinkertn@umich.edu    # gcc from version 4.8 and above generates "rep; ret" instructions
5984554Sbinkertn@umich.edu    # to avoid performance penalties on certain AMD chips. Older
5994554Sbinkertn@umich.edu    # assemblers detect this as an error, "Error: expecting string
6004554Sbinkertn@umich.edu    # instruction after `rep'"
6012667Sstever@eecs.umich.edu    if compareVersions(gcc_version, "4.8") > 0:
6024554Sbinkertn@umich.edu        as_version_raw = readCommand([main['AS'], '-v', '/dev/null'],
6032667Sstever@eecs.umich.edu                                     exception=False).split()
6044554Sbinkertn@umich.edu
6056121Snate@binkert.org        # version strings may contain extra distro-specific
6062667Sstever@eecs.umich.edu        # qualifiers, so play it safe and keep only what comes before
6075522Snate@binkert.org        # the first hyphen
6085522Snate@binkert.org        as_version = as_version_raw[-1].split('-')[0] if as_version_raw \
6095522Snate@binkert.org            else None
6105522Snate@binkert.org
6115522Snate@binkert.org        if not as_version or compareVersions(as_version, "2.23") < 0:
6125522Snate@binkert.org            print termcap.Yellow + termcap.Bold + \
6135522Snate@binkert.org                'Warning: This combination of gcc and binutils have' + \
6145522Snate@binkert.org                ' known incompatibilities.\n' + \
6155522Snate@binkert.org                '         If you encounter build problems, please update ' + \
6165522Snate@binkert.org                'binutils to 2.23.' + \
6175522Snate@binkert.org                termcap.Normal
6185522Snate@binkert.org
6195522Snate@binkert.org    # Make sure we warn if the user has requested to compile with the
6205522Snate@binkert.org    # Undefined Benahvior Sanitizer and this version of gcc does not
6215522Snate@binkert.org    # support it.
6225522Snate@binkert.org    if GetOption('with_ubsan') and \
6235522Snate@binkert.org            compareVersions(gcc_version, '4.9') < 0:
6245522Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
6255522Snate@binkert.org            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
6265522Snate@binkert.org            termcap.Normal
6275522Snate@binkert.org
6285522Snate@binkert.org    # Add the appropriate Link-Time Optimization (LTO) flags
6295522Snate@binkert.org    # unless LTO is explicitly turned off. Note that these flags
6305522Snate@binkert.org    # are only used by the fast target.
6315522Snate@binkert.org    if not GetOption('no_lto'):
6325522Snate@binkert.org        # Pass the LTO flag when compiling to produce GIMPLE
6332638Sstever@eecs.umich.edu        # output, we merely create the flags here and only append
6342638Sstever@eecs.umich.edu        # them later
6356121Snate@binkert.org        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
6363716Sstever@eecs.umich.edu
6375522Snate@binkert.org        # Use the same amount of jobs for LTO as we are running
6385522Snate@binkert.org        # scons with
6395522Snate@binkert.org        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
6405522Snate@binkert.org
6415522Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
6425522Snate@binkert.org                                  '-fno-builtin-realloc', '-fno-builtin-free'])
6431858SN/A
6445227Ssaidi@eecs.umich.eduelif main['CLANG']:
6455227Ssaidi@eecs.umich.edu    # Check for a supported version of clang, >= 3.1 is needed to
6465227Ssaidi@eecs.umich.edu    # support similar features as gcc 4.7. See
6475227Ssaidi@eecs.umich.edu    # http://clang.llvm.org/cxx_status.html for details
6486654Snate@binkert.org    clang_version_re = re.compile(".* version (\d+\.\d+)")
6496654Snate@binkert.org    clang_version_match = clang_version_re.search(CXX_version)
6507769SAli.Saidi@ARM.com    if (clang_version_match):
6517769SAli.Saidi@ARM.com        clang_version = clang_version_match.groups()[0]
6527769SAli.Saidi@ARM.com        if compareVersions(clang_version, "3.1") < 0:
6537769SAli.Saidi@ARM.com            print 'Error: clang version 3.1 or newer required.'
6545227Ssaidi@eecs.umich.edu            print '       Installed version:', clang_version
6555227Ssaidi@eecs.umich.edu            Exit(1)
6565227Ssaidi@eecs.umich.edu    else:
6575204Sstever@gmail.com        print 'Error: Unable to determine clang version.'
6585204Sstever@gmail.com        Exit(1)
6595204Sstever@gmail.com
6605204Sstever@gmail.com    # clang has a few additional warnings that we disable, extraneous
6615204Sstever@gmail.com    # parantheses are allowed due to Ruby's printing of the AST,
6625204Sstever@gmail.com    # finally self assignments are allowed as the generated CPU code
6635204Sstever@gmail.com    # is relying on this
6645204Sstever@gmail.com    main.Append(CCFLAGS=['-Wno-parentheses',
6655204Sstever@gmail.com                         '-Wno-self-assign',
6665204Sstever@gmail.com                         # Some versions of libstdc++ (4.8?) seem to
6675204Sstever@gmail.com                         # use struct hash and class hash
6685204Sstever@gmail.com                         # interchangeably.
6695204Sstever@gmail.com                         '-Wno-mismatched-tags',
6705204Sstever@gmail.com                         ])
6715204Sstever@gmail.com
6725204Sstever@gmail.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
6735204Sstever@gmail.com
6746121Snate@binkert.org    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
6755204Sstever@gmail.com    # opposed to libstdc++, as the later is dated.
6763118Sstever@eecs.umich.edu    if sys.platform == "darwin":
6773118Sstever@eecs.umich.edu        main.Append(CXXFLAGS=['-stdlib=libc++'])
6783118Sstever@eecs.umich.edu        main.Append(LIBS=['c++'])
6793118Sstever@eecs.umich.edu
6803118Sstever@eecs.umich.eduelse:
6815863Snate@binkert.org    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6823118Sstever@eecs.umich.edu    print "Don't know what compiler options to use for your compiler."
6835863Snate@binkert.org    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6843118Sstever@eecs.umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
6857457Snate@binkert.org    if not CXX_version:
6867457Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6875863Snate@binkert.org               termcap.Normal
6885863Snate@binkert.org    else:
6895863Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
6905863Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
6915863Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
6925863Snate@binkert.org    print "       environment."
6935863Snate@binkert.org    print "       "
6946003Snate@binkert.org    print "       If you are trying to use a compiler other than those listed"
6955863Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
6965863Snate@binkert.org    print "       src/SConscript to support that compiler."
6975863Snate@binkert.org    Exit(1)
6986120Snate@binkert.org
6995863Snate@binkert.org# Set up common yacc/bison flags (needed for Ruby)
7005863Snate@binkert.orgmain['YACCFLAGS'] = '-d'
7015863Snate@binkert.orgmain['YACCHXXFILESUFFIX'] = '.hh'
7028655Sandreas.hansson@arm.com
7038655Sandreas.hansson@arm.com# Do this after we save setting back, or else we'll tack on an
7048655Sandreas.hansson@arm.com# extra 'qdo' every time we run scons.
7058655Sandreas.hansson@arm.comif main['BATCH']:
7068655Sandreas.hansson@arm.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
7078655Sandreas.hansson@arm.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
7088655Sandreas.hansson@arm.com    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
7098655Sandreas.hansson@arm.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
7106120Snate@binkert.org    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
7115863Snate@binkert.org
7126121Snate@binkert.orgif sys.platform == 'cygwin':
7136121Snate@binkert.org    # cygwin has some header file issues...
7145863Snate@binkert.org    main.Append(CCFLAGS=["-Wno-uninitialized"])
7157727SAli.Saidi@ARM.com
7167727SAli.Saidi@ARM.com# Check for the protobuf compiler
7177727SAli.Saidi@ARM.comprotoc_version = readCommand([main['PROTOC'], '--version'],
7187727SAli.Saidi@ARM.com                             exception='').split()
7197727SAli.Saidi@ARM.com
7207727SAli.Saidi@ARM.com# First two words should be "libprotoc x.y.z"
7215863Snate@binkert.orgif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
7223118Sstever@eecs.umich.edu    print termcap.Yellow + termcap.Bold + \
7235863Snate@binkert.org        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
7243118Sstever@eecs.umich.edu        '         Please install protobuf-compiler for tracing support.' + \
7253118Sstever@eecs.umich.edu        termcap.Normal
7265863Snate@binkert.org    main['PROTOC'] = False
7275863Snate@binkert.orgelse:
7285863Snate@binkert.org    # Based on the availability of the compress stream wrappers,
7295863Snate@binkert.org    # require 2.1.0
7303118Sstever@eecs.umich.edu    min_protoc_version = '2.1.0'
7313483Ssaidi@eecs.umich.edu    if compareVersions(protoc_version[1], min_protoc_version) < 0:
7323494Ssaidi@eecs.umich.edu        print termcap.Yellow + termcap.Bold + \
7333494Ssaidi@eecs.umich.edu            'Warning: protoc version', min_protoc_version, \
7343483Ssaidi@eecs.umich.edu            'or newer required.\n' + \
7353483Ssaidi@eecs.umich.edu            '         Installed version:', protoc_version[1], \
7363483Ssaidi@eecs.umich.edu            termcap.Normal
7373053Sstever@eecs.umich.edu        main['PROTOC'] = False
7383053Sstever@eecs.umich.edu    else:
7393918Ssaidi@eecs.umich.edu        # Attempt to determine the appropriate include path and
7403053Sstever@eecs.umich.edu        # library path using pkg-config, that means we also need to
7413053Sstever@eecs.umich.edu        # check for pkg-config. Note that it is possible to use
7423053Sstever@eecs.umich.edu        # protobuf without the involvement of pkg-config. Later on we
7433053Sstever@eecs.umich.edu        # check go a library config check and at that point the test
7443053Sstever@eecs.umich.edu        # will fail if libprotobuf cannot be found.
7457840Snate@binkert.org        if readCommand(['pkg-config', '--version'], exception=''):
7467865Sgblack@eecs.umich.edu            try:
7477865Sgblack@eecs.umich.edu                # Attempt to establish what linking flags to add for protobuf
7487865Sgblack@eecs.umich.edu                # using pkg-config
7497865Sgblack@eecs.umich.edu                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
7507865Sgblack@eecs.umich.edu            except:
7517840Snate@binkert.org                print termcap.Yellow + termcap.Bold + \
7527840Snate@binkert.org                    'Warning: pkg-config could not get protobuf flags.' + \
7537840Snate@binkert.org                    termcap.Normal
7547840Snate@binkert.org
7551858SN/A# Check for SWIG
7561858SN/Aif not main.has_key('SWIG'):
7571858SN/A    print 'Error: SWIG utility not found.'
7581858SN/A    print '       Please install (see http://www.swig.org) and retry.'
7591858SN/A    Exit(1)
7601858SN/A
7615863Snate@binkert.org# Check for appropriate SWIG version
7625863Snate@binkert.orgswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
7635863Snate@binkert.org# First 3 words should be "SWIG Version x.y.z"
7645863Snate@binkert.orgif len(swig_version) < 3 or \
7656121Snate@binkert.org        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
7661858SN/A    print 'Error determining SWIG version.'
7675863Snate@binkert.org    Exit(1)
7685863Snate@binkert.org
7695863Snate@binkert.orgmin_swig_version = '2.0.4'
7705863Snate@binkert.orgif compareVersions(swig_version[2], min_swig_version) < 0:
7715863Snate@binkert.org    print 'Error: SWIG version', min_swig_version, 'or newer required.'
7722139SN/A    print '       Installed version:', swig_version[2]
7734202Sbinkertn@umich.edu    Exit(1)
7744202Sbinkertn@umich.edu
7752139SN/A# Check for known incompatibilities. The standard library shipped with
7766994Snate@binkert.org# gcc >= 4.9 does not play well with swig versions prior to 3.0
7776994Snate@binkert.orgif main['GCC'] and compareVersions(gcc_version, '4.9') >= 0 and \
7786994Snate@binkert.org        compareVersions(swig_version[2], '3.0') < 0:
7796994Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
7806994Snate@binkert.org        'Warning: This combination of gcc and swig have' + \
7816994Snate@binkert.org        ' known incompatibilities.\n' + \
7826994Snate@binkert.org        '         If you encounter build problems, please update ' + \
7836994Snate@binkert.org        'swig to 3.0 or later.' + \
7846994Snate@binkert.org        termcap.Normal
7856994Snate@binkert.org
7866994Snate@binkert.org# Set up SWIG flags & scanner
7876994Snate@binkert.orgswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
7886994Snate@binkert.orgmain.Append(SWIGFLAGS=swig_flags)
7896994Snate@binkert.org
7906994Snate@binkert.org# Check for 'timeout' from GNU coreutils. If present, regressions will
7916994Snate@binkert.org# be run with a time limit. We require version 8.13 since we rely on
7926994Snate@binkert.org# support for the '--foreground' option.
7936994Snate@binkert.orgtimeout_lines = readCommand(['timeout', '--version'],
7946994Snate@binkert.org                            exception='').splitlines()
7956994Snate@binkert.org# Get the first line and tokenize it
7966994Snate@binkert.orgtimeout_version = timeout_lines[0].split() if timeout_lines else []
7976994Snate@binkert.orgmain['TIMEOUT'] =  timeout_version and \
7986994Snate@binkert.org    compareVersions(timeout_version[-1], '8.13') >= 0
7996994Snate@binkert.org
8006994Snate@binkert.org# filter out all existing swig scanners, they mess up the dependency
8016994Snate@binkert.org# stuff for some reason
8026994Snate@binkert.orgscanners = []
8036994Snate@binkert.orgfor scanner in main['SCANNERS']:
8042155SN/A    skeys = scanner.skeys
8055863Snate@binkert.org    if skeys == '.i':
8061869SN/A        continue
8071869SN/A
8085863Snate@binkert.org    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
8095863Snate@binkert.org        continue
8104202Sbinkertn@umich.edu
8116108Snate@binkert.org    scanners.append(scanner)
8126108Snate@binkert.org
8136108Snate@binkert.org# add the new swig scanner that we like better
8146108Snate@binkert.orgfrom SCons.Scanner import ClassicCPP as CPPScanner
8154202Sbinkertn@umich.eduswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
8165863Snate@binkert.orgscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
8178474Sgblack@eecs.umich.edu
8188474Sgblack@eecs.umich.edu# replace the scanners list that has what we want
8195742Snate@binkert.orgmain['SCANNERS'] = scanners
8208268Ssteve.reinhardt@amd.com
8218268Ssteve.reinhardt@amd.com# Add a custom Check function to test for structure members.
8228268Ssteve.reinhardt@amd.comdef CheckMember(context, include, decl, member, include_quotes="<>"):
8235742Snate@binkert.org    context.Message("Checking for member %s in %s..." %
8245341Sstever@gmail.com                    (member, decl))
8258474Sgblack@eecs.umich.edu    text = """
8268474Sgblack@eecs.umich.edu#include %(header)s
8275342Sstever@gmail.comint main(){
8284202Sbinkertn@umich.edu  %(decl)s test;
8294202Sbinkertn@umich.edu  (void)test.%(member)s;
8304202Sbinkertn@umich.edu  return 0;
8315863Snate@binkert.org};
8325863Snate@binkert.org""" % { "header" : include_quotes[0] + include + include_quotes[1],
8336994Snate@binkert.org        "decl" : decl,
8346994Snate@binkert.org        "member" : member,
8356994Snate@binkert.org        }
8365863Snate@binkert.org
8375863Snate@binkert.org    ret = context.TryCompile(text, extension=".cc")
8385863Snate@binkert.org    context.Result(ret)
8395863Snate@binkert.org    return ret
8405863Snate@binkert.org
8415863Snate@binkert.org# Platform-specific configuration.  Note again that we assume that all
8425863Snate@binkert.org# builds under a given build root run on the same host platform.
8435863Snate@binkert.orgconf = Configure(main,
8447840Snate@binkert.org                 conf_dir = joinpath(build_root, '.scons_config'),
8455863Snate@binkert.org                 log_file = joinpath(build_root, 'scons_config.log'),
8465952Ssaidi@eecs.umich.edu                 custom_tests = {
8471869SN/A        'CheckMember' : CheckMember,
8481858SN/A        })
8495863Snate@binkert.org
8509044SAli.Saidi@ARM.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
8518805Sgblack@eecs.umich.edutry:
8521858SN/A    import platform
853955SN/A    uname = platform.uname()
854955SN/A    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
8551869SN/A        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
8561869SN/A            main.Append(CCFLAGS=['-arch', 'x86_64'])
8571869SN/A            main.Append(CFLAGS=['-arch', 'x86_64'])
8581869SN/A            main.Append(LINKFLAGS=['-arch', 'x86_64'])
8591869SN/A            main.Append(ASFLAGS=['-arch', 'x86_64'])
8605863Snate@binkert.orgexcept:
8615863Snate@binkert.org    pass
8625863Snate@binkert.org
8631869SN/A# Recent versions of scons substitute a "Null" object for Configure()
8645863Snate@binkert.org# when configuration isn't necessary, e.g., if the "--help" option is
8651869SN/A# present.  Unfortuantely this Null object always returns false,
8665863Snate@binkert.org# breaking all our configuration checks.  We replace it with our own
8671869SN/A# more optimistic null object that returns True instead.
8681869SN/Aif not conf:
8691869SN/A    def NullCheck(*args, **kwargs):
8701869SN/A        return True
8718483Sgblack@eecs.umich.edu
8721869SN/A    class NullConf:
8731869SN/A        def __init__(self, env):
8741869SN/A            self.env = env
8751869SN/A        def Finish(self):
8765863Snate@binkert.org            return self.env
8775863Snate@binkert.org        def __getattr__(self, mname):
8781869SN/A            return NullCheck
8795863Snate@binkert.org
8805863Snate@binkert.org    conf = NullConf(main)
8813356Sbinkertn@umich.edu
8823356Sbinkertn@umich.edu# Cache build files in the supplied directory.
8833356Sbinkertn@umich.eduif main['M5_BUILD_CACHE']:
8843356Sbinkertn@umich.edu    print 'Using build cache located at', main['M5_BUILD_CACHE']
8853356Sbinkertn@umich.edu    CacheDir(main['M5_BUILD_CACHE'])
8864781Snate@binkert.org
8875863Snate@binkert.orgif not GetOption('without_python'):
8885863Snate@binkert.org    # Find Python include and library directories for embedding the
8891869SN/A    # interpreter. We rely on python-config to resolve the appropriate
8901869SN/A    # includes and linker flags. ParseConfig does not seem to understand
8911869SN/A    # the more exotic linker flags such as -Xlinker and -export-dynamic so
8926121Snate@binkert.org    # we add them explicitly below. If you want to link in an alternate
8931869SN/A    # version of python, see above for instructions on how to invoke
8942638Sstever@eecs.umich.edu    # scons with the appropriate PATH set.
8956121Snate@binkert.org    #
8966121Snate@binkert.org    # First we check if python2-config exists, else we use python-config
8972638Sstever@eecs.umich.edu    python_config = readCommand(['which', 'python2-config'],
8985749Scws3k@cs.virginia.edu                                exception='').strip()
8996121Snate@binkert.org    if not os.path.exists(python_config):
9006121Snate@binkert.org        python_config = readCommand(['which', 'python-config'],
9015749Scws3k@cs.virginia.edu                                    exception='').strip()
9021869SN/A    py_includes = readCommand([python_config, '--includes'],
9031869SN/A                              exception='').split()
9043546Sgblack@eecs.umich.edu    # Strip the -I from the include folders before adding them to the
9053546Sgblack@eecs.umich.edu    # CPPPATH
9063546Sgblack@eecs.umich.edu    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
9073546Sgblack@eecs.umich.edu
9086121Snate@binkert.org    # Read the linker flags and split them into libraries and other link
9095863Snate@binkert.org    # flags. The libraries are added later through the call the CheckLib.
9103546Sgblack@eecs.umich.edu    py_ld_flags = readCommand([python_config, '--ldflags'],
9113546Sgblack@eecs.umich.edu        exception='').split()
9123546Sgblack@eecs.umich.edu    py_libs = []
9133546Sgblack@eecs.umich.edu    for lib in py_ld_flags:
9144781Snate@binkert.org         if not lib.startswith('-l'):
9154781Snate@binkert.org             main.Append(LINKFLAGS=[lib])
9166658Snate@binkert.org         else:
9176658Snate@binkert.org             lib = lib[2:]
9184781Snate@binkert.org             if lib not in py_libs:
9193546Sgblack@eecs.umich.edu                 py_libs.append(lib)
9203546Sgblack@eecs.umich.edu
9213546Sgblack@eecs.umich.edu    # verify that this stuff works
9223546Sgblack@eecs.umich.edu    if not conf.CheckHeader('Python.h', '<>'):
9237756SAli.Saidi@ARM.com        print "Error: can't find Python.h header in", py_includes
9247816Ssteve.reinhardt@amd.com        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
9253546Sgblack@eecs.umich.edu        Exit(1)
9263546Sgblack@eecs.umich.edu
9273546Sgblack@eecs.umich.edu    for lib in py_libs:
9283546Sgblack@eecs.umich.edu        if not conf.CheckLib(lib):
9294202Sbinkertn@umich.edu            print "Error: can't find library %s required by python" % lib
9303546Sgblack@eecs.umich.edu            Exit(1)
9313546Sgblack@eecs.umich.edu
9323546Sgblack@eecs.umich.edu# On Solaris you need to use libsocket for socket ops
933955SN/Aif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
934955SN/A   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
935955SN/A       print "Can't find library with socket calls (e.g. accept())"
936955SN/A       Exit(1)
9375863Snate@binkert.org
9385863Snate@binkert.org# Check for zlib.  If the check passes, libz will be automatically
9395343Sstever@gmail.com# added to the LIBS environment variable.
9405343Sstever@gmail.comif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
9416121Snate@binkert.org    print 'Error: did not find needed zlib compression library '\
9425863Snate@binkert.org          'and/or zlib.h header file.'
9434773Snate@binkert.org    print '       Please install zlib and try again.'
9445863Snate@binkert.org    Exit(1)
9452632Sstever@eecs.umich.edu
9465863Snate@binkert.org# If we have the protobuf compiler, also make sure we have the
9472023SN/A# development libraries. If the check passes, libprotobuf will be
9485863Snate@binkert.org# automatically added to the LIBS environment variable. After
9495863Snate@binkert.org# this, we can use the HAVE_PROTOBUF flag to determine if we have
9505863Snate@binkert.org# got both protoc and libprotobuf available.
9515863Snate@binkert.orgmain['HAVE_PROTOBUF'] = main['PROTOC'] and \
9525863Snate@binkert.org    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
9535863Snate@binkert.org                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
9545863Snate@binkert.org
9555863Snate@binkert.org# If we have the compiler but not the library, print another warning.
9565863Snate@binkert.orgif main['PROTOC'] and not main['HAVE_PROTOBUF']:
9572632Sstever@eecs.umich.edu    print termcap.Yellow + termcap.Bold + \
9585863Snate@binkert.org        'Warning: did not find protocol buffer library and/or headers.\n' + \
9592023SN/A    '       Please install libprotobuf-dev for tracing support.' + \
9602632Sstever@eecs.umich.edu    termcap.Normal
9615863Snate@binkert.org
9625342Sstever@gmail.com# Check for librt.
9635863Snate@binkert.orghave_posix_clock = \
9642632Sstever@eecs.umich.edu    conf.CheckLibWithHeader(None, 'time.h', 'C',
9655863Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);') or \
9665863Snate@binkert.org    conf.CheckLibWithHeader('rt', 'time.h', 'C',
9678267Ssteve.reinhardt@amd.com                            'clock_nanosleep(0,0,NULL,NULL);')
9688120Sgblack@eecs.umich.edu
9698267Ssteve.reinhardt@amd.comhave_posix_timers = \
9708267Ssteve.reinhardt@amd.com    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
9718267Ssteve.reinhardt@amd.com                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
9728267Ssteve.reinhardt@amd.com
9738267Ssteve.reinhardt@amd.comif not GetOption('without_tcmalloc'):
9748267Ssteve.reinhardt@amd.com    if conf.CheckLib('tcmalloc'):
9758267Ssteve.reinhardt@amd.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
9768267Ssteve.reinhardt@amd.com    elif conf.CheckLib('tcmalloc_minimal'):
9778267Ssteve.reinhardt@amd.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
9785863Snate@binkert.org    else:
9795863Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
9805863Snate@binkert.org              "You can get a 12% performance improvement by "\
9812632Sstever@eecs.umich.edu              "installing tcmalloc (libgoogle-perftools-dev package "\
9828267Ssteve.reinhardt@amd.com              "on Ubuntu or RedHat)." + termcap.Normal
9838267Ssteve.reinhardt@amd.com
9848267Ssteve.reinhardt@amd.com
9852632Sstever@eecs.umich.edu# Detect back trace implementations. The last implementation in the
9861888SN/A# list will be used by default.
9875863Snate@binkert.orgbacktrace_impls = [ "none" ]
9885863Snate@binkert.org
9891858SN/Aif conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
9908120Sgblack@eecs.umich.edu                           'backtrace_symbols_fd((void*)0, 0, 0);'):
9918120Sgblack@eecs.umich.edu    backtrace_impls.append("glibc")
9927756SAli.Saidi@ARM.com
9932598SN/Aif backtrace_impls[-1] == "none":
9945863Snate@binkert.org    default_backtrace_impl = "none"
9951858SN/A    print termcap.Yellow + termcap.Bold + \
9961858SN/A        "No suitable back trace implementation found." + \
9971858SN/A        termcap.Normal
9985863Snate@binkert.org
9991858SN/Aif not have_posix_clock:
10001858SN/A    print "Can't find library for POSIX clocks."
10011858SN/A
10025863Snate@binkert.org# Check for <fenv.h> (C99 FP environment control)
10031871SN/Ahave_fenv = conf.CheckHeader('fenv.h', '<>')
10041858SN/Aif not have_fenv:
10051858SN/A    print "Warning: Header file <fenv.h> not found."
10061858SN/A    print "         This host has no IEEE FP rounding mode control."
10071858SN/A
10085863Snate@binkert.org# Check if we should enable KVM-based hardware virtualization. The API
10095863Snate@binkert.org# we rely on exists since version 2.6.36 of the kernel, but somehow
10101869SN/A# the KVM_API_VERSION does not reflect the change. We test for one of
10111965SN/A# the types as a fall back.
10127739Sgblack@eecs.umich.eduhave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
10131965SN/Aif not have_kvm:
10142761Sstever@eecs.umich.edu    print "Info: Compatible header file <linux/kvm.h> not found, " \
10155863Snate@binkert.org        "disabling KVM support."
10161869SN/A
10175863Snate@binkert.org# x86 needs support for xsave. We test for the structure here since we
10182667Sstever@eecs.umich.edu# won't be able to run new tests by the time we know which ISA we're
10191869SN/A# targeting.
10201869SN/Ahave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
10212929Sktlim@umich.edu                                    '#include <linux/kvm.h>') != 0
10222929Sktlim@umich.edu
10235863Snate@binkert.org# Check if the requested target ISA is compatible with the host
10242929Sktlim@umich.edudef is_isa_kvm_compatible(isa):
1025955SN/A    try:
10268120Sgblack@eecs.umich.edu        import platform
10278120Sgblack@eecs.umich.edu        host_isa = platform.machine()
10288120Sgblack@eecs.umich.edu    except:
10298120Sgblack@eecs.umich.edu        print "Warning: Failed to determine host ISA."
10308120Sgblack@eecs.umich.edu        return False
10318120Sgblack@eecs.umich.edu
10328120Sgblack@eecs.umich.edu    if not have_posix_timers:
10338120Sgblack@eecs.umich.edu        print "Warning: Can not enable KVM, host seems to lack support " \
10348120Sgblack@eecs.umich.edu            "for POSIX timers"
10358120Sgblack@eecs.umich.edu        return False
10368120Sgblack@eecs.umich.edu
10378120Sgblack@eecs.umich.edu    if isa == "arm":
1038        return host_isa in ( "armv7l", "aarch64" )
1039    elif isa == "x86":
1040        if host_isa != "x86_64":
1041            return False
1042
1043        if not have_kvm_xsave:
1044            print "KVM on x86 requires xsave support in kernel headers."
1045            return False
1046
1047        return True
1048    else:
1049        return False
1050
1051
1052# Check if the exclude_host attribute is available. We want this to
1053# get accurate instruction counts in KVM.
1054main['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
1055    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
1056
1057
1058######################################################################
1059#
1060# Finish the configuration
1061#
1062main = conf.Finish()
1063
1064######################################################################
1065#
1066# Collect all non-global variables
1067#
1068
1069# Define the universe of supported ISAs
1070all_isa_list = [ ]
1071all_gpu_isa_list = [ ]
1072Export('all_isa_list')
1073Export('all_gpu_isa_list')
1074
1075class CpuModel(object):
1076    '''The CpuModel class encapsulates everything the ISA parser needs to
1077    know about a particular CPU model.'''
1078
1079    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
1080    dict = {}
1081
1082    # Constructor.  Automatically adds models to CpuModel.dict.
1083    def __init__(self, name, default=False):
1084        self.name = name           # name of model
1085
1086        # This cpu is enabled by default
1087        self.default = default
1088
1089        # Add self to dict
1090        if name in CpuModel.dict:
1091            raise AttributeError, "CpuModel '%s' already registered" % name
1092        CpuModel.dict[name] = self
1093
1094Export('CpuModel')
1095
1096# Sticky variables get saved in the variables file so they persist from
1097# one invocation to the next (unless overridden, in which case the new
1098# value becomes sticky).
1099sticky_vars = Variables(args=ARGUMENTS)
1100Export('sticky_vars')
1101
1102# Sticky variables that should be exported
1103export_vars = []
1104Export('export_vars')
1105
1106# For Ruby
1107all_protocols = []
1108Export('all_protocols')
1109protocol_dirs = []
1110Export('protocol_dirs')
1111slicc_includes = []
1112Export('slicc_includes')
1113
1114# Walk the tree and execute all SConsopts scripts that wil add to the
1115# above variables
1116if GetOption('verbose'):
1117    print "Reading SConsopts"
1118for bdir in [ base_dir ] + extras_dir_list:
1119    if not isdir(bdir):
1120        print "Error: directory '%s' does not exist" % bdir
1121        Exit(1)
1122    for root, dirs, files in os.walk(bdir):
1123        if 'SConsopts' in files:
1124            if GetOption('verbose'):
1125                print "Reading", joinpath(root, 'SConsopts')
1126            SConscript(joinpath(root, 'SConsopts'))
1127
1128all_isa_list.sort()
1129all_gpu_isa_list.sort()
1130
1131sticky_vars.AddVariables(
1132    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
1133    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
1134    ListVariable('CPU_MODELS', 'CPU models',
1135                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
1136                 sorted(CpuModel.dict.keys())),
1137    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
1138                 False),
1139    BoolVariable('SS_COMPATIBLE_FP',
1140                 'Make floating-point results compatible with SimpleScalar',
1141                 False),
1142    BoolVariable('USE_SSE2',
1143                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
1144                 False),
1145    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
1146    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
1147    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
1148    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
1149    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
1150    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1151                  all_protocols),
1152    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
1153                 backtrace_impls[-1], backtrace_impls)
1154    )
1155
1156# These variables get exported to #defines in config/*.hh (see src/SConscript).
1157export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
1158                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'PROTOCOL',
1159                'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST']
1160
1161###################################################
1162#
1163# Define a SCons builder for configuration flag headers.
1164#
1165###################################################
1166
1167# This function generates a config header file that #defines the
1168# variable symbol to the current variable setting (0 or 1).  The source
1169# operands are the name of the variable and a Value node containing the
1170# value of the variable.
1171def build_config_file(target, source, env):
1172    (variable, value) = [s.get_contents() for s in source]
1173    f = file(str(target[0]), 'w')
1174    print >> f, '#define', variable, value
1175    f.close()
1176    return None
1177
1178# Combine the two functions into a scons Action object.
1179config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1180
1181# The emitter munges the source & target node lists to reflect what
1182# we're really doing.
1183def config_emitter(target, source, env):
1184    # extract variable name from Builder arg
1185    variable = str(target[0])
1186    # True target is config header file
1187    target = joinpath('config', variable.lower() + '.hh')
1188    val = env[variable]
1189    if isinstance(val, bool):
1190        # Force value to 0/1
1191        val = int(val)
1192    elif isinstance(val, str):
1193        val = '"' + val + '"'
1194
1195    # Sources are variable name & value (packaged in SCons Value nodes)
1196    return ([target], [Value(variable), Value(val)])
1197
1198config_builder = Builder(emitter = config_emitter, action = config_action)
1199
1200main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1201
1202# libelf build is shared across all configs in the build root.
1203main.SConscript('ext/libelf/SConscript',
1204                variant_dir = joinpath(build_root, 'libelf'))
1205
1206# iostream3 build is shared across all configs in the build root.
1207main.SConscript('ext/iostream3/SConscript',
1208                variant_dir = joinpath(build_root, 'iostream3'))
1209
1210# libfdt build is shared across all configs in the build root.
1211main.SConscript('ext/libfdt/SConscript',
1212                variant_dir = joinpath(build_root, 'libfdt'))
1213
1214# fputils build is shared across all configs in the build root.
1215main.SConscript('ext/fputils/SConscript',
1216                variant_dir = joinpath(build_root, 'fputils'))
1217
1218# DRAMSim2 build is shared across all configs in the build root.
1219main.SConscript('ext/dramsim2/SConscript',
1220                variant_dir = joinpath(build_root, 'dramsim2'))
1221
1222# DRAMPower build is shared across all configs in the build root.
1223main.SConscript('ext/drampower/SConscript',
1224                variant_dir = joinpath(build_root, 'drampower'))
1225
1226# nomali build is shared across all configs in the build root.
1227main.SConscript('ext/nomali/SConscript',
1228                variant_dir = joinpath(build_root, 'nomali'))
1229
1230###################################################
1231#
1232# This function is used to set up a directory with switching headers
1233#
1234###################################################
1235
1236main['ALL_ISA_LIST'] = all_isa_list
1237main['ALL_GPU_ISA_LIST'] = all_gpu_isa_list
1238all_isa_deps = {}
1239def make_switching_dir(dname, switch_headers, env):
1240    # Generate the header.  target[0] is the full path of the output
1241    # header to generate.  'source' is a dummy variable, since we get the
1242    # list of ISAs from env['ALL_ISA_LIST'].
1243    def gen_switch_hdr(target, source, env):
1244        fname = str(target[0])
1245        isa = env['TARGET_ISA'].lower()
1246        try:
1247            f = open(fname, 'w')
1248            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1249            f.close()
1250        except IOError:
1251            print "Failed to create %s" % fname
1252            raise
1253
1254    # Build SCons Action object. 'varlist' specifies env vars that this
1255    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1256    # should get re-executed.
1257    switch_hdr_action = MakeAction(gen_switch_hdr,
1258                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1259
1260    # Instantiate actions for each header
1261    for hdr in switch_headers:
1262        env.Command(hdr, [], switch_hdr_action)
1263
1264    isa_target = Dir('.').up().name.lower().replace('_', '-')
1265    env['PHONY_BASE'] = '#'+isa_target
1266    all_isa_deps[isa_target] = None
1267
1268Export('make_switching_dir')
1269
1270def make_gpu_switching_dir(dname, switch_headers, env):
1271    # Generate the header.  target[0] is the full path of the output
1272    # header to generate.  'source' is a dummy variable, since we get the
1273    # list of ISAs from env['ALL_ISA_LIST'].
1274    def gen_switch_hdr(target, source, env):
1275        fname = str(target[0])
1276
1277        isa = env['TARGET_GPU_ISA'].lower()
1278
1279        try:
1280            f = open(fname, 'w')
1281            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1282            f.close()
1283        except IOError:
1284            print "Failed to create %s" % fname
1285            raise
1286
1287    # Build SCons Action object. 'varlist' specifies env vars that this
1288    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1289    # should get re-executed.
1290    switch_hdr_action = MakeAction(gen_switch_hdr,
1291                          Transform("GENERATE"), varlist=['ALL_ISA_GPU_LIST'])
1292
1293    # Instantiate actions for each header
1294    for hdr in switch_headers:
1295        env.Command(hdr, [], switch_hdr_action)
1296
1297Export('make_gpu_switching_dir')
1298
1299# all-isas -> all-deps -> all-environs -> all_targets
1300main.Alias('#all-isas', [])
1301main.Alias('#all-deps', '#all-isas')
1302
1303# Dummy target to ensure all environments are created before telling
1304# SCons what to actually make (the command line arguments).  We attach
1305# them to the dependence graph after the environments are complete.
1306ORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
1307def environsComplete(target, source, env):
1308    for t in ORIG_BUILD_TARGETS:
1309        main.Depends('#all-targets', t)
1310
1311# Each build/* switching_dir attaches its *-environs target to #all-environs.
1312main.Append(BUILDERS = {'CompleteEnvirons' :
1313                        Builder(action=MakeAction(environsComplete, None))})
1314main.CompleteEnvirons('#all-environs', [])
1315
1316def doNothing(**ignored): pass
1317main.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
1318
1319# The final target to which all the original targets ultimately get attached.
1320main.Dummy('#all-targets', '#all-environs')
1321BUILD_TARGETS[:] = ['#all-targets']
1322
1323###################################################
1324#
1325# Define build environments for selected configurations.
1326#
1327###################################################
1328
1329for variant_path in variant_paths:
1330    if not GetOption('silent'):
1331        print "Building in", variant_path
1332
1333    # Make a copy of the build-root environment to use for this config.
1334    env = main.Clone()
1335    env['BUILDDIR'] = variant_path
1336
1337    # variant_dir is the tail component of build path, and is used to
1338    # determine the build parameters (e.g., 'ALPHA_SE')
1339    (build_root, variant_dir) = splitpath(variant_path)
1340
1341    # Set env variables according to the build directory config.
1342    sticky_vars.files = []
1343    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1344    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1345    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1346    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1347    if isfile(current_vars_file):
1348        sticky_vars.files.append(current_vars_file)
1349        if not GetOption('silent'):
1350            print "Using saved variables file %s" % current_vars_file
1351    else:
1352        # Build dir-specific variables file doesn't exist.
1353
1354        # Make sure the directory is there so we can create it later
1355        opt_dir = dirname(current_vars_file)
1356        if not isdir(opt_dir):
1357            mkdir(opt_dir)
1358
1359        # Get default build variables from source tree.  Variables are
1360        # normally determined by name of $VARIANT_DIR, but can be
1361        # overridden by '--default=' arg on command line.
1362        default = GetOption('default')
1363        opts_dir = joinpath(main.root.abspath, 'build_opts')
1364        if default:
1365            default_vars_files = [joinpath(build_root, 'variables', default),
1366                                  joinpath(opts_dir, default)]
1367        else:
1368            default_vars_files = [joinpath(opts_dir, variant_dir)]
1369        existing_files = filter(isfile, default_vars_files)
1370        if existing_files:
1371            default_vars_file = existing_files[0]
1372            sticky_vars.files.append(default_vars_file)
1373            print "Variables file %s not found,\n  using defaults in %s" \
1374                  % (current_vars_file, default_vars_file)
1375        else:
1376            print "Error: cannot find variables file %s or " \
1377                  "default file(s) %s" \
1378                  % (current_vars_file, ' or '.join(default_vars_files))
1379            Exit(1)
1380
1381    # Apply current variable settings to env
1382    sticky_vars.Update(env)
1383
1384    help_texts["local_vars"] += \
1385        "Build variables for %s:\n" % variant_dir \
1386                 + sticky_vars.GenerateHelpText(env)
1387
1388    # Process variable settings.
1389
1390    if not have_fenv and env['USE_FENV']:
1391        print "Warning: <fenv.h> not available; " \
1392              "forcing USE_FENV to False in", variant_dir + "."
1393        env['USE_FENV'] = False
1394
1395    if not env['USE_FENV']:
1396        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1397        print "         FP results may deviate slightly from other platforms."
1398
1399    if env['EFENCE']:
1400        env.Append(LIBS=['efence'])
1401
1402    if env['USE_KVM']:
1403        if not have_kvm:
1404            print "Warning: Can not enable KVM, host seems to lack KVM support"
1405            env['USE_KVM'] = False
1406        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1407            print "Info: KVM support disabled due to unsupported host and " \
1408                "target ISA combination"
1409            env['USE_KVM'] = False
1410
1411    # Warn about missing optional functionality
1412    if env['USE_KVM']:
1413        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1414            print "Warning: perf_event headers lack support for the " \
1415                "exclude_host attribute. KVM instruction counts will " \
1416                "be inaccurate."
1417
1418    # Save sticky variable settings back to current variables file
1419    sticky_vars.Save(current_vars_file, env)
1420
1421    if env['USE_SSE2']:
1422        env.Append(CCFLAGS=['-msse2'])
1423
1424    # The src/SConscript file sets up the build rules in 'env' according
1425    # to the configured variables.  It returns a list of environments,
1426    # one for each variant build (debug, opt, etc.)
1427    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1428
1429def pairwise(iterable):
1430    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1431    a, b = itertools.tee(iterable)
1432    b.next()
1433    return itertools.izip(a, b)
1434
1435# Create false dependencies so SCons will parse ISAs, establish
1436# dependencies, and setup the build Environments serially. Either
1437# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1438# greater than 1. It appears to be standard race condition stuff; it
1439# doesn't always fail, but usually, and the behaviors are different.
1440# Every time I tried to remove this, builds would fail in some
1441# creative new way. So, don't do that. You'll want to, though, because
1442# tests/SConscript takes a long time to make its Environments.
1443for t1, t2 in pairwise(sorted(all_isa_deps.iterkeys())):
1444    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1445    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1446
1447# base help text
1448Help('''
1449Usage: scons [scons options] [build variables] [target(s)]
1450
1451Extra scons options:
1452%(options)s
1453
1454Global build variables:
1455%(global_vars)s
1456
1457%(local_vars)s
1458''' % help_texts)
1459