SConstruct revision 10860:cba0f26038b4
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2013, 2015 ARM Limited
4955SN/A# All rights reserved.
5955SN/A#
6955SN/A# The license below extends only to copyright in the software and shall
7955SN/A# not be construed as granting a license to any other intellectual
8955SN/A# property including but not limited to intellectual property relating
9955SN/A# to a hardware implementation of the functionality of the software
10955SN/A# licensed hereunder.  You may use the software subject to the license
11955SN/A# terms below provided that you ensure that this notice is replicated
12955SN/A# unmodified and in its entirety in all distributions of the software,
13955SN/A# modified or unmodified, in source code or in binary form.
14955SN/A#
15955SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
16955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
17955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
18955SN/A# All rights reserved.
19955SN/A#
20955SN/A# Redistribution and use in source and binary forms, with or without
21955SN/A# modification, are permitted provided that the following conditions are
22955SN/A# met: redistributions of source code must retain the above copyright
23955SN/A# notice, this list of conditions and the following disclaimer;
24955SN/A# redistributions in binary form must reproduce the above copyright
25955SN/A# notice, this list of conditions and the following disclaimer in the
26955SN/A# documentation and/or other materials provided with the distribution;
27955SN/A# neither the name of the copyright holders nor the names of its
282665Ssaidi@eecs.umich.edu# contributors may be used to endorse or promote products derived from
294762Snate@binkert.org# this software without specific prior written permission.
30955SN/A#
315522Snate@binkert.org# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
326143Snate@binkert.org# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
334762Snate@binkert.org# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
345522Snate@binkert.org# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
365522Snate@binkert.org# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
3711974Sgabeblack@google.com# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
395522Snate@binkert.org# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
404202Sbinkertn@umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
415742Snate@binkert.org# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42955SN/A#
434381Sbinkertn@umich.edu# Authors: Steve Reinhardt
444381Sbinkertn@umich.edu#          Nathan Binkert
4512246Sgabeblack@google.com
4612246Sgabeblack@google.com###################################################
478334Snate@binkert.org#
48955SN/A# SCons top-level build description (SConstruct) file.
49955SN/A#
504202Sbinkertn@umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
51955SN/A# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
524382Sbinkertn@umich.edu# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
534382Sbinkertn@umich.edu# the optimized full-system version).
544382Sbinkertn@umich.edu#
556654Snate@binkert.org# You can build gem5 in a different directory as long as there is a
565517Snate@binkert.org# 'build/<CONFIG>' somewhere along the target path.  The build system
578614Sgblack@eecs.umich.edu# expects that all configs under the same build directory are being
587674Snate@binkert.org# built for the same host system.
596143Snate@binkert.org#
606143Snate@binkert.org# Examples:
616143Snate@binkert.org#
628233Snate@binkert.org#   The following two commands are equivalent.  The '-u' option tells
638233Snate@binkert.org#   scons to search up the directory tree for this SConstruct file.
648233Snate@binkert.org#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
658233Snate@binkert.org#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
668233Snate@binkert.org#
678334Snate@binkert.org#   The following two commands are equivalent and demonstrate building
688334Snate@binkert.org#   in a directory outside of the source tree.  The '-C' option tells
6910453SAndrew.Bardsley@arm.com#   scons to chdir to the specified directory to find this SConstruct
7010453SAndrew.Bardsley@arm.com#   file.
718233Snate@binkert.org#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
728233Snate@binkert.org#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
738233Snate@binkert.org#
748233Snate@binkert.org# You can use 'scons -H' to print scons options.  If you're in this
758233Snate@binkert.org# 'gem5' directory (or use -u or -C to tell scons where to find this
768233Snate@binkert.org# file), you can use 'scons -h' to print all the gem5-specific build
7711983Sgabeblack@google.com# options as well.
7811983Sgabeblack@google.com#
7911983Sgabeblack@google.com###################################################
8011983Sgabeblack@google.com
8111983Sgabeblack@google.com# Check for recent-enough Python and SCons versions.
8211983Sgabeblack@google.comtry:
8311983Sgabeblack@google.com    # Really old versions of scons only take two options for the
8411983Sgabeblack@google.com    # function, so check once without the revision and once with the
8511983Sgabeblack@google.com    # revision, the first instance will fail for stuff other than
8611983Sgabeblack@google.com    # 0.98, and the second will fail for 0.98.0
8711983Sgabeblack@google.com    EnsureSConsVersion(0, 98)
886143Snate@binkert.org    EnsureSConsVersion(0, 98, 1)
898233Snate@binkert.orgexcept SystemExit, e:
908233Snate@binkert.org    print """
918233Snate@binkert.orgFor more details, see:
926143Snate@binkert.org    http://gem5.org/Dependencies
936143Snate@binkert.org"""
946143Snate@binkert.org    raise
9511308Santhony.gutierrez@amd.com
968233Snate@binkert.org# We ensure the python version early because because python-config
978233Snate@binkert.org# requires python 2.5
988233Snate@binkert.orgtry:
9911983Sgabeblack@google.com    EnsurePythonVersion(2, 5)
10011983Sgabeblack@google.comexcept SystemExit, e:
1014762Snate@binkert.org    print """
1026143Snate@binkert.orgYou can use a non-default installation of the Python interpreter by
1038233Snate@binkert.orgrearranging your PATH so that scons finds the non-default 'python' and
1048233Snate@binkert.org'python-config' first.
1058233Snate@binkert.org
1068233Snate@binkert.orgFor more details, see:
1078233Snate@binkert.org    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1086143Snate@binkert.org"""
1098233Snate@binkert.org    raise
1108233Snate@binkert.org
1118233Snate@binkert.org# Global Python includes
1128233Snate@binkert.orgimport itertools
1136143Snate@binkert.orgimport os
1146143Snate@binkert.orgimport re
1156143Snate@binkert.orgimport subprocess
1166143Snate@binkert.orgimport sys
1176143Snate@binkert.org
1186143Snate@binkert.orgfrom os import mkdir, environ
1196143Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1206143Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1216143Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1227065Snate@binkert.org
1236143Snate@binkert.org# SCons includes
1248233Snate@binkert.orgimport SCons
1258233Snate@binkert.orgimport SCons.Node
1268233Snate@binkert.org
1278233Snate@binkert.orgextra_python_paths = [
1288233Snate@binkert.org    Dir('src/python').srcnode().abspath, # gem5 includes
1298233Snate@binkert.org    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1308233Snate@binkert.org    ]
1318233Snate@binkert.org
1328233Snate@binkert.orgsys.path[1:1] = extra_python_paths
1338233Snate@binkert.org
1348233Snate@binkert.orgfrom m5.util import compareVersions, readCommand
1358233Snate@binkert.orgfrom m5.util.terminal import get_termcap
1368233Snate@binkert.org
1378233Snate@binkert.orghelp_texts = {
1388233Snate@binkert.org    "options" : "",
1398233Snate@binkert.org    "global_vars" : "",
1408233Snate@binkert.org    "local_vars" : ""
1418233Snate@binkert.org}
1428233Snate@binkert.org
1438233Snate@binkert.orgExport("help_texts")
1448233Snate@binkert.org
1458233Snate@binkert.org
1468233Snate@binkert.org# There's a bug in scons in that (1) by default, the help texts from
1478233Snate@binkert.org# AddOption() are supposed to be displayed when you type 'scons -h'
1488233Snate@binkert.org# and (2) you can override the help displayed by 'scons -h' using the
1498233Snate@binkert.org# Help() function, but these two features are incompatible: once
1508233Snate@binkert.org# you've overridden the help text using Help(), there's no way to get
1518233Snate@binkert.org# at the help texts from AddOptions.  See:
1528233Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1538233Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1548233Snate@binkert.org# This hack lets us extract the help text from AddOptions and
1556143Snate@binkert.org# re-inject it via Help().  Ideally someday this bug will be fixed and
1566143Snate@binkert.org# we can just use AddOption directly.
1576143Snate@binkert.orgdef AddLocalOption(*args, **kwargs):
1586143Snate@binkert.org    col_width = 30
1596143Snate@binkert.org
1606143Snate@binkert.org    help = "  " + ", ".join(args)
1619982Satgutier@umich.edu    if "help" in kwargs:
16210196SCurtis.Dunham@arm.com        length = len(help)
16310196SCurtis.Dunham@arm.com        if length >= col_width:
16410196SCurtis.Dunham@arm.com            help += "\n" + " " * col_width
16510196SCurtis.Dunham@arm.com        else:
16610196SCurtis.Dunham@arm.com            help += " " * (col_width - length)
16710196SCurtis.Dunham@arm.com        help += kwargs["help"]
16810196SCurtis.Dunham@arm.com    help_texts["options"] += help + "\n"
16910196SCurtis.Dunham@arm.com
1706143Snate@binkert.org    AddOption(*args, **kwargs)
17111983Sgabeblack@google.com
17211983Sgabeblack@google.comAddLocalOption('--colors', dest='use_colors', action='store_true',
17311983Sgabeblack@google.com               help="Add color to abbreviated scons output")
17411983Sgabeblack@google.comAddLocalOption('--no-colors', dest='use_colors', action='store_false',
17511983Sgabeblack@google.com               help="Don't add color to abbreviated scons output")
17611983Sgabeblack@google.comAddLocalOption('--with-cxx-config', dest='with_cxx_config',
17711983Sgabeblack@google.com               action='store_true',
17811983Sgabeblack@google.com               help="Build with support for C++-based configuration")
17911983Sgabeblack@google.comAddLocalOption('--default', dest='default', type='string', action='store',
1806143Snate@binkert.org               help='Override which build_opts file to use for defaults')
18111988Sandreas.sandberg@arm.comAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1828233Snate@binkert.org               help='Disable style checking hooks')
1838233Snate@binkert.orgAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1846143Snate@binkert.org               help='Disable Link-Time Optimization for fast')
1858945Ssteve.reinhardt@amd.comAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1866143Snate@binkert.org               help='Update test reference outputs')
18711983Sgabeblack@google.comAddLocalOption('--verbose', dest='verbose', action='store_true',
18811983Sgabeblack@google.com               help='Print full tool command lines')
1896143Snate@binkert.orgAddLocalOption('--without-python', dest='without_python',
1906143Snate@binkert.org               action='store_true',
1915522Snate@binkert.org               help='Build without Python configuration support')
1926143Snate@binkert.orgAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1936143Snate@binkert.org               action='store_true',
1946143Snate@binkert.org               help='Disable linking against tcmalloc')
1959982Satgutier@umich.eduAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1968233Snate@binkert.org               help='Build with Undefined Behavior Sanitizer if available')
1978233Snate@binkert.org
1988233Snate@binkert.orgtermcap = get_termcap(GetOption('use_colors'))
1996143Snate@binkert.org
2006143Snate@binkert.org########################################################################
2016143Snate@binkert.org#
2026143Snate@binkert.org# Set up the main build environment.
2035522Snate@binkert.org#
2045522Snate@binkert.org########################################################################
2055522Snate@binkert.org
2065522Snate@binkert.org# export TERM so that clang reports errors in color
2075604Snate@binkert.orguse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
2085604Snate@binkert.org                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
2096143Snate@binkert.org                 'PYTHONPATH', 'RANLIB', 'SWIG', 'TERM' ])
2106143Snate@binkert.org
2114762Snate@binkert.orguse_prefixes = [
2124762Snate@binkert.org    "M5",           # M5 configuration (e.g., path to kernels)
2136143Snate@binkert.org    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
2146727Ssteve.reinhardt@amd.com    "CCACHE_",      # ccache (caching compiler wrapper) configuration
2156727Ssteve.reinhardt@amd.com    "CCC_",         # clang static analyzer configuration
2166727Ssteve.reinhardt@amd.com    ]
2174762Snate@binkert.org
2186143Snate@binkert.orguse_env = {}
2196143Snate@binkert.orgfor key,val in sorted(os.environ.iteritems()):
2206143Snate@binkert.org    if key in use_vars or \
2216143Snate@binkert.org            any([key.startswith(prefix) for prefix in use_prefixes]):
2226727Ssteve.reinhardt@amd.com        use_env[key] = val
2236143Snate@binkert.org
2247674Snate@binkert.org# Tell scons to avoid implicit command dependencies to avoid issues
2257674Snate@binkert.org# with the param wrappes being compiled twice (see
2265604Snate@binkert.org# http://scons.tigris.org/issues/show_bug.cgi?id=2811)
2276143Snate@binkert.orgmain = Environment(ENV=use_env, IMPLICIT_COMMAND_DEPENDENCIES=0)
2286143Snate@binkert.orgmain.Decider('MD5-timestamp')
2296143Snate@binkert.orgmain.root = Dir(".")         # The current directory (where this file lives).
2304762Snate@binkert.orgmain.srcdir = Dir("src")     # The source directory
2316143Snate@binkert.org
2324762Snate@binkert.orgmain_dict_keys = main.Dictionary().keys()
2334762Snate@binkert.org
2344762Snate@binkert.org# Check that we have a C/C++ compiler
2356143Snate@binkert.orgif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2366143Snate@binkert.org    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2374762Snate@binkert.org    Exit(1)
2388233Snate@binkert.org
2398233Snate@binkert.org# Check that swig is present
2408233Snate@binkert.orgif not 'SWIG' in main_dict_keys:
2418233Snate@binkert.org    print "swig is not installed (package swig on Ubuntu and RedHat)"
2426143Snate@binkert.org    Exit(1)
2436143Snate@binkert.org
2444762Snate@binkert.org# add useful python code PYTHONPATH so it can be used by subprocesses
2456143Snate@binkert.org# as well
2464762Snate@binkert.orgmain.AppendENVPath('PYTHONPATH', extra_python_paths)
2479396Sandreas.hansson@arm.com
2489396Sandreas.hansson@arm.com########################################################################
2499396Sandreas.hansson@arm.com#
2509396Sandreas.hansson@arm.com# Mercurial Stuff.
2519396Sandreas.hansson@arm.com#
2529396Sandreas.hansson@arm.com# If the gem5 directory is a mercurial repository, we should do some
2539396Sandreas.hansson@arm.com# extra things.
2549396Sandreas.hansson@arm.com#
2559396Sandreas.hansson@arm.com########################################################################
2569396Sandreas.hansson@arm.com
2579396Sandreas.hansson@arm.comhgdir = main.root.Dir(".hg")
2589396Sandreas.hansson@arm.com
2599396Sandreas.hansson@arm.commercurial_style_message = """
2609930Sandreas.hansson@arm.comYou're missing the gem5 style hook, which automatically checks your code
2619930Sandreas.hansson@arm.comagainst the gem5 style rules on hg commit and qrefresh commands.  This
2629396Sandreas.hansson@arm.comscript will now install the hook in your .hg/hgrc file.
2638235Snate@binkert.orgPress enter to continue, or ctrl-c to abort: """
2648235Snate@binkert.org
2656143Snate@binkert.orgmercurial_style_hook = """
2668235Snate@binkert.org# The following lines were automatically added by gem5/SConstruct
2679003SAli.Saidi@ARM.com# to provide the gem5 style-checking hooks
2688235Snate@binkert.org[extensions]
2698235Snate@binkert.orgstyle = %s/util/style.py
2708235Snate@binkert.org
2718235Snate@binkert.org[hooks]
2728235Snate@binkert.orgpretxncommit.style = python:style.check_style
2738235Snate@binkert.orgpre-qrefresh.style = python:style.check_style
2748235Snate@binkert.org# End of SConstruct additions
2758235Snate@binkert.org
2768235Snate@binkert.org""" % (main.root.abspath)
2778235Snate@binkert.org
2788235Snate@binkert.orgmercurial_lib_not_found = """
2798235Snate@binkert.orgMercurial libraries cannot be found, ignoring style hook.  If
2808235Snate@binkert.orgyou are a gem5 developer, please fix this and run the style
2818235Snate@binkert.orghook. It is important.
2829003SAli.Saidi@ARM.com"""
2838235Snate@binkert.org
2845584Snate@binkert.org# Check for style hook and prompt for installation if it's not there.
2854382Sbinkertn@umich.edu# Skip this if --ignore-style was specified, there's no .hg dir to
2864202Sbinkertn@umich.edu# install a hook in, or there's no interactive terminal to prompt.
2874382Sbinkertn@umich.eduif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2884382Sbinkertn@umich.edu    style_hook = True
2899396Sandreas.hansson@arm.com    try:
2905584Snate@binkert.org        from mercurial import ui
2914382Sbinkertn@umich.edu        ui = ui.ui()
2924382Sbinkertn@umich.edu        ui.readconfig(hgdir.File('hgrc').abspath)
2934382Sbinkertn@umich.edu        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2948232Snate@binkert.org                     ui.config('hooks', 'pre-qrefresh.style', None)
2955192Ssaidi@eecs.umich.edu    except ImportError:
2968232Snate@binkert.org        print mercurial_lib_not_found
2978232Snate@binkert.org
2988232Snate@binkert.org    if not style_hook:
2995192Ssaidi@eecs.umich.edu        print mercurial_style_message,
3008232Snate@binkert.org        # continue unless user does ctrl-c/ctrl-d etc.
3015192Ssaidi@eecs.umich.edu        try:
3025799Snate@binkert.org            raw_input()
3038232Snate@binkert.org        except:
3045192Ssaidi@eecs.umich.edu            print "Input exception, exiting scons.\n"
3055192Ssaidi@eecs.umich.edu            sys.exit(1)
3065192Ssaidi@eecs.umich.edu        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
3078232Snate@binkert.org        print "Adding style hook to", hgrc_path, "\n"
3085192Ssaidi@eecs.umich.edu        try:
3098232Snate@binkert.org            hgrc = open(hgrc_path, 'a')
3105192Ssaidi@eecs.umich.edu            hgrc.write(mercurial_style_hook)
3115192Ssaidi@eecs.umich.edu            hgrc.close()
3125192Ssaidi@eecs.umich.edu        except:
3135192Ssaidi@eecs.umich.edu            print "Error updating", hgrc_path
3144382Sbinkertn@umich.edu            sys.exit(1)
3154382Sbinkertn@umich.edu
3164382Sbinkertn@umich.edu
3172667Sstever@eecs.umich.edu###################################################
3182667Sstever@eecs.umich.edu#
3192667Sstever@eecs.umich.edu# Figure out which configurations to set up based on the path(s) of
3202667Sstever@eecs.umich.edu# the target(s).
3212667Sstever@eecs.umich.edu#
3222667Sstever@eecs.umich.edu###################################################
3235742Snate@binkert.org
3245742Snate@binkert.org# Find default configuration & binary.
3255742Snate@binkert.orgDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
3265793Snate@binkert.org
3278334Snate@binkert.org# helper function: find last occurrence of element in list
3285793Snate@binkert.orgdef rfind(l, elt, offs = -1):
3295793Snate@binkert.org    for i in range(len(l)+offs, 0, -1):
3305793Snate@binkert.org        if l[i] == elt:
3314382Sbinkertn@umich.edu            return i
3324762Snate@binkert.org    raise ValueError, "element not found"
3335344Sstever@gmail.com
3344382Sbinkertn@umich.edu# Take a list of paths (or SCons Nodes) and return a list with all
3355341Sstever@gmail.com# paths made absolute and ~-expanded.  Paths will be interpreted
3365742Snate@binkert.org# relative to the launch directory unless a different root is provided
3375742Snate@binkert.orgdef makePathListAbsolute(path_list, root=GetLaunchDir()):
3385742Snate@binkert.org    return [abspath(joinpath(root, expanduser(str(p))))
3395742Snate@binkert.org            for p in path_list]
3405742Snate@binkert.org
3414762Snate@binkert.org# Each target must have 'build' in the interior of the path; the
3425742Snate@binkert.org# directory below this will determine the build parameters.  For
3435742Snate@binkert.org# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
34411984Sgabeblack@google.com# recognize that ALPHA_SE specifies the configuration because it
3457722Sgblack@eecs.umich.edu# follow 'build' in the build path.
3465742Snate@binkert.org
3475742Snate@binkert.org# The funky assignment to "[:]" is needed to replace the list contents
3485742Snate@binkert.org# in place rather than reassign the symbol to a new list, which
3499930Sandreas.hansson@arm.com# doesn't work (obviously!).
3509930Sandreas.hansson@arm.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3519930Sandreas.hansson@arm.com
3529930Sandreas.hansson@arm.com# Generate a list of the unique build roots and configs that the
3539930Sandreas.hansson@arm.com# collected targets reference.
3545742Snate@binkert.orgvariant_paths = []
3558242Sbradley.danofsky@amd.combuild_root = None
3568242Sbradley.danofsky@amd.comfor t in BUILD_TARGETS:
3578242Sbradley.danofsky@amd.com    path_dirs = t.split('/')
3588242Sbradley.danofsky@amd.com    try:
3595341Sstever@gmail.com        build_top = rfind(path_dirs, 'build', -2)
3605742Snate@binkert.org    except:
3617722Sgblack@eecs.umich.edu        print "Error: no non-leaf 'build' dir found on target path", t
3624773Snate@binkert.org        Exit(1)
3636108Snate@binkert.org    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3641858SN/A    if not build_root:
3651085SN/A        build_root = this_build_root
3666658Snate@binkert.org    else:
3676658Snate@binkert.org        if this_build_root != build_root:
3687673Snate@binkert.org            print "Error: build targets not under same build root\n"\
3696658Snate@binkert.org                  "  %s\n  %s" % (build_root, this_build_root)
3706658Snate@binkert.org            Exit(1)
37111308Santhony.gutierrez@amd.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
3726658Snate@binkert.org    if variant_path not in variant_paths:
37311308Santhony.gutierrez@amd.com        variant_paths.append(variant_path)
3746658Snate@binkert.org
3756658Snate@binkert.org# Make sure build_root exists (might not if this is the first build there)
3767673Snate@binkert.orgif not isdir(build_root):
3777673Snate@binkert.org    mkdir(build_root)
3787673Snate@binkert.orgmain['BUILDROOT'] = build_root
3797673Snate@binkert.org
3807673Snate@binkert.orgExport('main')
3817673Snate@binkert.org
3827673Snate@binkert.orgmain.SConsignFile(joinpath(build_root, "sconsign"))
38310467Sandreas.hansson@arm.com
3846658Snate@binkert.org# Default duplicate option is to use hard links, but this messes up
3857673Snate@binkert.org# when you use emacs to edit a file in the target dir, as emacs moves
38610467Sandreas.hansson@arm.com# file to file~ then copies to file, breaking the link.  Symbolic
38710467Sandreas.hansson@arm.com# (soft) links work better.
38810467Sandreas.hansson@arm.commain.SetOption('duplicate', 'soft-copy')
38910467Sandreas.hansson@arm.com
39010467Sandreas.hansson@arm.com#
39110467Sandreas.hansson@arm.com# Set up global sticky variables... these are common to an entire build
39210467Sandreas.hansson@arm.com# tree (not specific to a particular build like ALPHA_SE)
39310467Sandreas.hansson@arm.com#
39410467Sandreas.hansson@arm.com
39510467Sandreas.hansson@arm.comglobal_vars_file = joinpath(build_root, 'variables.global')
39610467Sandreas.hansson@arm.com
3977673Snate@binkert.orgglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3987673Snate@binkert.org
3997673Snate@binkert.orgglobal_vars.AddVariables(
4007673Snate@binkert.org    ('CC', 'C compiler', environ.get('CC', main['CC'])),
4017673Snate@binkert.org    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
4029048SAli.Saidi@ARM.com    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
4037673Snate@binkert.org    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
4047673Snate@binkert.org    ('BATCH', 'Use batch pool for build and tests', False),
4057673Snate@binkert.org    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
4067673Snate@binkert.org    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
4076658Snate@binkert.org    ('EXTRAS', 'Add extra directories to the compilation', '')
4087756SAli.Saidi@ARM.com    )
4097816Ssteve.reinhardt@amd.com
4106658Snate@binkert.org# Update main environment with values from ARGUMENTS & global_vars_file
41111308Santhony.gutierrez@amd.comglobal_vars.Update(main)
41211308Santhony.gutierrez@amd.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
41311308Santhony.gutierrez@amd.com
41411308Santhony.gutierrez@amd.com# Save sticky variable settings back to current variables file
41511308Santhony.gutierrez@amd.comglobal_vars.Save(global_vars_file, main)
41611308Santhony.gutierrez@amd.com
41711308Santhony.gutierrez@amd.com# Parse EXTRAS variable to build list of all directories where we're
41811308Santhony.gutierrez@amd.com# look for sources etc.  This list is exported as extras_dir_list.
41911308Santhony.gutierrez@amd.combase_dir = main.srcdir.abspath
42011308Santhony.gutierrez@amd.comif main['EXTRAS']:
42111308Santhony.gutierrez@amd.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
42211308Santhony.gutierrez@amd.comelse:
42311308Santhony.gutierrez@amd.com    extras_dir_list = []
42411308Santhony.gutierrez@amd.com
42511308Santhony.gutierrez@amd.comExport('base_dir')
42611308Santhony.gutierrez@amd.comExport('extras_dir_list')
42711308Santhony.gutierrez@amd.com
42811308Santhony.gutierrez@amd.com# the ext directory should be on the #includes path
42911308Santhony.gutierrez@amd.commain.Append(CPPPATH=[Dir('ext')])
43011308Santhony.gutierrez@amd.com
43111308Santhony.gutierrez@amd.comdef strip_build_path(path, env):
43211308Santhony.gutierrez@amd.com    path = str(path)
43311308Santhony.gutierrez@amd.com    variant_base = env['BUILDROOT'] + os.path.sep
43411308Santhony.gutierrez@amd.com    if path.startswith(variant_base):
43511308Santhony.gutierrez@amd.com        path = path[len(variant_base):]
43611308Santhony.gutierrez@amd.com    elif path.startswith('build/'):
43711308Santhony.gutierrez@amd.com        path = path[6:]
43811308Santhony.gutierrez@amd.com    return path
43911308Santhony.gutierrez@amd.com
44011308Santhony.gutierrez@amd.com# Generate a string of the form:
44111308Santhony.gutierrez@amd.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
44211308Santhony.gutierrez@amd.com# to print while building.
44311308Santhony.gutierrez@amd.comclass Transform(object):
44411308Santhony.gutierrez@amd.com    # all specific color settings should be here and nowhere else
44511308Santhony.gutierrez@amd.com    tool_color = termcap.Normal
44611308Santhony.gutierrez@amd.com    pfx_color = termcap.Yellow
44711308Santhony.gutierrez@amd.com    srcs_color = termcap.Yellow + termcap.Bold
44811308Santhony.gutierrez@amd.com    arrow_color = termcap.Blue + termcap.Bold
44911308Santhony.gutierrez@amd.com    tgts_color = termcap.Yellow + termcap.Bold
45011308Santhony.gutierrez@amd.com
45111308Santhony.gutierrez@amd.com    def __init__(self, tool, max_sources=99):
45211308Santhony.gutierrez@amd.com        self.format = self.tool_color + (" [%8s] " % tool) \
45311308Santhony.gutierrez@amd.com                      + self.pfx_color + "%s" \
45411308Santhony.gutierrez@amd.com                      + self.srcs_color + "%s" \
45511308Santhony.gutierrez@amd.com                      + self.arrow_color + " -> " \
4564382Sbinkertn@umich.edu                      + self.tgts_color + "%s" \
4574382Sbinkertn@umich.edu                      + termcap.Normal
4584762Snate@binkert.org        self.max_sources = max_sources
4594762Snate@binkert.org
4604762Snate@binkert.org    def __call__(self, target, source, env, for_signature=None):
4616654Snate@binkert.org        # truncate source list according to max_sources param
4626654Snate@binkert.org        source = source[0:self.max_sources]
4635517Snate@binkert.org        def strip(f):
4645517Snate@binkert.org            return strip_build_path(str(f), env)
4655517Snate@binkert.org        if len(source) > 0:
4665517Snate@binkert.org            srcs = map(strip, source)
4675517Snate@binkert.org        else:
4685517Snate@binkert.org            srcs = ['']
4695517Snate@binkert.org        tgts = map(strip, target)
4705517Snate@binkert.org        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4715517Snate@binkert.org        # operation that has nothing to do with paths.
4725517Snate@binkert.org        com_pfx = os.path.commonprefix(srcs + tgts)
4735517Snate@binkert.org        com_pfx_len = len(com_pfx)
4745517Snate@binkert.org        if com_pfx:
4755517Snate@binkert.org            # do some cleanup and sanity checking on common prefix
4765517Snate@binkert.org            if com_pfx[-1] == ".":
4775517Snate@binkert.org                # prefix matches all but file extension: ok
4785517Snate@binkert.org                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4795517Snate@binkert.org                com_pfx = com_pfx[0:-1]
4806654Snate@binkert.org            elif com_pfx[-1] == "/":
4815517Snate@binkert.org                # common prefix is directory path: OK
4825517Snate@binkert.org                pass
4835517Snate@binkert.org            else:
4845517Snate@binkert.org                src0_len = len(srcs[0])
4855517Snate@binkert.org                tgt0_len = len(tgts[0])
48611802Sandreas.sandberg@arm.com                if src0_len == com_pfx_len:
4875517Snate@binkert.org                    # source is a substring of target, OK
4885517Snate@binkert.org                    pass
4896143Snate@binkert.org                elif tgt0_len == com_pfx_len:
4906654Snate@binkert.org                    # target is a substring of source, need to back up to
4915517Snate@binkert.org                    # avoid empty string on RHS of arrow
4925517Snate@binkert.org                    sep_idx = com_pfx.rfind(".")
4935517Snate@binkert.org                    if sep_idx != -1:
4945517Snate@binkert.org                        com_pfx = com_pfx[0:sep_idx]
4955517Snate@binkert.org                    else:
4965517Snate@binkert.org                        com_pfx = ''
4975517Snate@binkert.org                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4985517Snate@binkert.org                    # still splitting at file extension: ok
4995517Snate@binkert.org                    pass
5005517Snate@binkert.org                else:
5015517Snate@binkert.org                    # probably a fluke; ignore it
5025517Snate@binkert.org                    com_pfx = ''
5035517Snate@binkert.org        # recalculate length in case com_pfx was modified
5045517Snate@binkert.org        com_pfx_len = len(com_pfx)
5056654Snate@binkert.org        def fmt(files):
5066654Snate@binkert.org            f = map(lambda s: s[com_pfx_len:], files)
5075517Snate@binkert.org            return ', '.join(f)
5085517Snate@binkert.org        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
5096143Snate@binkert.org
5106143Snate@binkert.orgExport('Transform')
5116143Snate@binkert.org
5126727Ssteve.reinhardt@amd.com# enable the regression script to use the termcap
5135517Snate@binkert.orgmain['TERMCAP'] = termcap
5146727Ssteve.reinhardt@amd.com
5155517Snate@binkert.orgif GetOption('verbose'):
5165517Snate@binkert.org    def MakeAction(action, string, *args, **kwargs):
5175517Snate@binkert.org        return Action(action, *args, **kwargs)
5186654Snate@binkert.orgelse:
5196654Snate@binkert.org    MakeAction = Action
5207673Snate@binkert.org    main['CCCOMSTR']        = Transform("CC")
5216654Snate@binkert.org    main['CXXCOMSTR']       = Transform("CXX")
5226654Snate@binkert.org    main['ASCOMSTR']        = Transform("AS")
5236654Snate@binkert.org    main['SWIGCOMSTR']      = Transform("SWIG")
5246654Snate@binkert.org    main['ARCOMSTR']        = Transform("AR", 0)
5255517Snate@binkert.org    main['LINKCOMSTR']      = Transform("LINK", 0)
5265517Snate@binkert.org    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
5275517Snate@binkert.org    main['M4COMSTR']        = Transform("M4")
5286143Snate@binkert.org    main['SHCCCOMSTR']      = Transform("SHCC")
5295517Snate@binkert.org    main['SHCXXCOMSTR']     = Transform("SHCXX")
5304762Snate@binkert.orgExport('MakeAction')
5315517Snate@binkert.org
5325517Snate@binkert.org# Initialize the Link-Time Optimization (LTO) flags
5336143Snate@binkert.orgmain['LTO_CCFLAGS'] = []
5346143Snate@binkert.orgmain['LTO_LDFLAGS'] = []
5355517Snate@binkert.org
5365517Snate@binkert.org# According to the readme, tcmalloc works best if the compiler doesn't
5375517Snate@binkert.org# assume that we're using the builtin malloc and friends. These flags
5385517Snate@binkert.org# are compiler-specific, so we need to set them after we detect which
5395517Snate@binkert.org# compiler we're using.
5405517Snate@binkert.orgmain['TCMALLOC_CCFLAGS'] = []
5415517Snate@binkert.org
5425517Snate@binkert.orgCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5435517Snate@binkert.orgCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5446143Snate@binkert.org
5455517Snate@binkert.orgmain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5466654Snate@binkert.orgmain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5476654Snate@binkert.orgif main['GCC'] + main['CLANG'] > 1:
5486654Snate@binkert.org    print 'Error: How can we have two at the same time?'
5496654Snate@binkert.org    Exit(1)
5506654Snate@binkert.org
5516654Snate@binkert.org# Set up default C++ compiler flags
5524762Snate@binkert.orgif main['GCC'] or main['CLANG']:
5534762Snate@binkert.org    # As gcc and clang share many flags, do the common parts here
5544762Snate@binkert.org    main.Append(CCFLAGS=['-pipe'])
5554762Snate@binkert.org    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5564762Snate@binkert.org    # Enable -Wall and then disable the few warnings that we
5577675Snate@binkert.org    # consistently violate
55810584Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5594762Snate@binkert.org    # We always compile using C++11, but only gcc >= 4.7 and clang 3.1
5604762Snate@binkert.org    # actually use that name, so we stick with c++0x
5614762Snate@binkert.org    main.Append(CXXFLAGS=['-std=c++0x'])
5624762Snate@binkert.org    # Add selected sanity checks from -Wextra
5634382Sbinkertn@umich.edu    main.Append(CXXFLAGS=['-Wmissing-field-initializers',
5644382Sbinkertn@umich.edu                          '-Woverloaded-virtual'])
5655517Snate@binkert.orgelse:
5666654Snate@binkert.org    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5675517Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
5688126Sgblack@eecs.umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5696654Snate@binkert.org    print termcap.Yellow + '       version:' + termcap.Normal,
5707673Snate@binkert.org    if not CXX_version:
5716654Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
57211802Sandreas.sandberg@arm.com               termcap.Normal
5736654Snate@binkert.org    else:
5746654Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
5756654Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
5766654Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
57711802Sandreas.sandberg@arm.com    print "       environment."
5786669Snate@binkert.org    print "       "
57911802Sandreas.sandberg@arm.com    print "       If you are trying to use a compiler other than those listed"
5806669Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
5816669Snate@binkert.org    print "       src/SConscript to support that compiler."
5826669Snate@binkert.org    Exit(1)
5836669Snate@binkert.org
5846654Snate@binkert.orgif main['GCC']:
5857673Snate@binkert.org    # Check for a supported version of gcc. >= 4.6 is chosen for its
5865517Snate@binkert.org    # level of c++11 support. See
5878126Sgblack@eecs.umich.edu    # http://gcc.gnu.org/projects/cxx0x.html for details. 4.6 is also
5885798Snate@binkert.org    # the first version with proper LTO support.
5897756SAli.Saidi@ARM.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5907816Ssteve.reinhardt@amd.com    if compareVersions(gcc_version, "4.6") < 0:
5915798Snate@binkert.org        print 'Error: gcc version 4.6 or newer required.'
5925798Snate@binkert.org        print '       Installed version:', gcc_version
5935517Snate@binkert.org        Exit(1)
5945517Snate@binkert.org
5957673Snate@binkert.org    main['GCC_VERSION'] = gcc_version
5965517Snate@binkert.org
5975517Snate@binkert.org    # gcc from version 4.8 and above generates "rep; ret" instructions
5987673Snate@binkert.org    # to avoid performance penalties on certain AMD chips. Older
5997673Snate@binkert.org    # assemblers detect this as an error, "Error: expecting string
6005517Snate@binkert.org    # instruction after `rep'"
6015798Snate@binkert.org    if compareVersions(gcc_version, "4.8") > 0:
6025798Snate@binkert.org        as_version = readCommand([main['AS'], '-v', '/dev/null'],
6038333Snate@binkert.org                                 exception=False).split()
6047816Ssteve.reinhardt@amd.com
6055798Snate@binkert.org        if not as_version or compareVersions(as_version[-1], "2.23") < 0:
6065798Snate@binkert.org            print termcap.Yellow + termcap.Bold + \
6074762Snate@binkert.org                'Warning: This combination of gcc and binutils have' + \
6084762Snate@binkert.org                ' known incompatibilities.\n' + \
6094762Snate@binkert.org                '         If you encounter build problems, please update ' + \
6104762Snate@binkert.org                'binutils to 2.23.' + \
6114762Snate@binkert.org                termcap.Normal
6128596Ssteve.reinhardt@amd.com
6135517Snate@binkert.org    # Make sure we warn if the user has requested to compile with the
6145517Snate@binkert.org    # Undefined Benahvior Sanitizer and this version of gcc does not
61511997Sgabeblack@google.com    # support it.
6165517Snate@binkert.org    if GetOption('with_ubsan') and \
6175517Snate@binkert.org            compareVersions(gcc_version, '4.9') < 0:
6187673Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
6198596Ssteve.reinhardt@amd.com            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
6207673Snate@binkert.org            termcap.Normal
6215517Snate@binkert.org
62210458Sandreas.hansson@arm.com    # Add the appropriate Link-Time Optimization (LTO) flags
62310458Sandreas.hansson@arm.com    # unless LTO is explicitly turned off. Note that these flags
62410458Sandreas.hansson@arm.com    # are only used by the fast target.
62510458Sandreas.hansson@arm.com    if not GetOption('no_lto'):
62610458Sandreas.hansson@arm.com        # Pass the LTO flag when compiling to produce GIMPLE
62710458Sandreas.hansson@arm.com        # output, we merely create the flags here and only append
62810458Sandreas.hansson@arm.com        # them later
62910458Sandreas.hansson@arm.com        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
63010458Sandreas.hansson@arm.com
63110458Sandreas.hansson@arm.com        # Use the same amount of jobs for LTO as we are running
63210458Sandreas.hansson@arm.com        # scons with
63310458Sandreas.hansson@arm.com        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
6345517Snate@binkert.org
63511996Sgabeblack@google.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
6365517Snate@binkert.org                                  '-fno-builtin-realloc', '-fno-builtin-free'])
63711997Sgabeblack@google.com
63811996Sgabeblack@google.comelif main['CLANG']:
6395517Snate@binkert.org    # Check for a supported version of clang, >= 3.0 is needed to
6405517Snate@binkert.org    # support similar features as gcc 4.6. See
6417673Snate@binkert.org    # http://clang.llvm.org/cxx_status.html for details
6427673Snate@binkert.org    clang_version_re = re.compile(".* version (\d+\.\d+)")
64311996Sgabeblack@google.com    clang_version_match = clang_version_re.search(CXX_version)
64411988Sandreas.sandberg@arm.com    if (clang_version_match):
6457673Snate@binkert.org        clang_version = clang_version_match.groups()[0]
6465517Snate@binkert.org        if compareVersions(clang_version, "3.0") < 0:
6478596Ssteve.reinhardt@amd.com            print 'Error: clang version 3.0 or newer required.'
6485517Snate@binkert.org            print '       Installed version:', clang_version
6495517Snate@binkert.org            Exit(1)
65011997Sgabeblack@google.com    else:
6515517Snate@binkert.org        print 'Error: Unable to determine clang version.'
6525517Snate@binkert.org        Exit(1)
6537673Snate@binkert.org
6547673Snate@binkert.org    # clang has a few additional warnings that we disable,
6557673Snate@binkert.org    # tautological comparisons are allowed due to unsigned integers
6565517Snate@binkert.org    # being compared to constants that happen to be 0, and extraneous
65711988Sandreas.sandberg@arm.com    # parantheses are allowed due to Ruby's printing of the AST,
65811997Sgabeblack@google.com    # finally self assignments are allowed as the generated CPU code
6598596Ssteve.reinhardt@amd.com    # is relying on this
6608596Ssteve.reinhardt@amd.com    main.Append(CCFLAGS=['-Wno-tautological-compare',
6618596Ssteve.reinhardt@amd.com                         '-Wno-parentheses',
66211988Sandreas.sandberg@arm.com                         '-Wno-self-assign',
6638596Ssteve.reinhardt@amd.com                         # Some versions of libstdc++ (4.8?) seem to
6648596Ssteve.reinhardt@amd.com                         # use struct hash and class hash
6658596Ssteve.reinhardt@amd.com                         # interchangeably.
6664762Snate@binkert.org                         '-Wno-mismatched-tags',
6676143Snate@binkert.org                         ])
6686143Snate@binkert.org
6696143Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
6704762Snate@binkert.org
6714762Snate@binkert.org    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
6724762Snate@binkert.org    # opposed to libstdc++, as the later is dated.
6737756SAli.Saidi@ARM.com    if sys.platform == "darwin":
6748596Ssteve.reinhardt@amd.com        main.Append(CXXFLAGS=['-stdlib=libc++'])
6754762Snate@binkert.org        main.Append(LIBS=['c++'])
6764762Snate@binkert.org
67710458Sandreas.hansson@arm.comelse:
67810458Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
67910458Sandreas.hansson@arm.com    print "Don't know what compiler options to use for your compiler."
68010458Sandreas.hansson@arm.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
68110458Sandreas.hansson@arm.com    print termcap.Yellow + '       version:' + termcap.Normal,
68210458Sandreas.hansson@arm.com    if not CXX_version:
68310458Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
68410458Sandreas.hansson@arm.com               termcap.Normal
68510458Sandreas.hansson@arm.com    else:
68610458Sandreas.hansson@arm.com        print CXX_version.replace('\n', '<nl>')
68710458Sandreas.hansson@arm.com    print "       If you're trying to use a compiler other than GCC"
68810458Sandreas.hansson@arm.com    print "       or clang, there appears to be something wrong with your"
68910458Sandreas.hansson@arm.com    print "       environment."
69010458Sandreas.hansson@arm.com    print "       "
69110458Sandreas.hansson@arm.com    print "       If you are trying to use a compiler other than those listed"
69210458Sandreas.hansson@arm.com    print "       above you will need to ease fix SConstruct and "
69310458Sandreas.hansson@arm.com    print "       src/SConscript to support that compiler."
69410458Sandreas.hansson@arm.com    Exit(1)
69510458Sandreas.hansson@arm.com
69610458Sandreas.hansson@arm.com# Set up common yacc/bison flags (needed for Ruby)
69710458Sandreas.hansson@arm.commain['YACCFLAGS'] = '-d'
69810458Sandreas.hansson@arm.commain['YACCHXXFILESUFFIX'] = '.hh'
69910458Sandreas.hansson@arm.com
70010458Sandreas.hansson@arm.com# Do this after we save setting back, or else we'll tack on an
70110458Sandreas.hansson@arm.com# extra 'qdo' every time we run scons.
70210458Sandreas.hansson@arm.comif main['BATCH']:
70310458Sandreas.hansson@arm.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
70410458Sandreas.hansson@arm.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
70510458Sandreas.hansson@arm.com    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
70610458Sandreas.hansson@arm.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
70710458Sandreas.hansson@arm.com    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
70810458Sandreas.hansson@arm.com
70910458Sandreas.hansson@arm.comif sys.platform == 'cygwin':
71010458Sandreas.hansson@arm.com    # cygwin has some header file issues...
71110458Sandreas.hansson@arm.com    main.Append(CCFLAGS=["-Wno-uninitialized"])
71210458Sandreas.hansson@arm.com
71310458Sandreas.hansson@arm.com# Check for the protobuf compiler
71410458Sandreas.hansson@arm.comprotoc_version = readCommand([main['PROTOC'], '--version'],
71510458Sandreas.hansson@arm.com                             exception='').split()
71610458Sandreas.hansson@arm.com
71710458Sandreas.hansson@arm.com# First two words should be "libprotoc x.y.z"
71810458Sandreas.hansson@arm.comif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
71910458Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + \
72010458Sandreas.hansson@arm.com        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
72110458Sandreas.hansson@arm.com        '         Please install protobuf-compiler for tracing support.' + \
72210458Sandreas.hansson@arm.com        termcap.Normal
72310458Sandreas.hansson@arm.com    main['PROTOC'] = False
72410458Sandreas.hansson@arm.comelse:
72510458Sandreas.hansson@arm.com    # Based on the availability of the compress stream wrappers,
72610584Sandreas.hansson@arm.com    # require 2.1.0
72710458Sandreas.hansson@arm.com    min_protoc_version = '2.1.0'
72810458Sandreas.hansson@arm.com    if compareVersions(protoc_version[1], min_protoc_version) < 0:
72910458Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + \
73010458Sandreas.hansson@arm.com            'Warning: protoc version', min_protoc_version, \
73110458Sandreas.hansson@arm.com            'or newer required.\n' + \
7324762Snate@binkert.org            '         Installed version:', protoc_version[1], \
7336143Snate@binkert.org            termcap.Normal
7346143Snate@binkert.org        main['PROTOC'] = False
7356143Snate@binkert.org    else:
7364762Snate@binkert.org        # Attempt to determine the appropriate include path and
7374762Snate@binkert.org        # library path using pkg-config, that means we also need to
73811996Sgabeblack@google.com        # check for pkg-config. Note that it is possible to use
7397816Ssteve.reinhardt@amd.com        # protobuf without the involvement of pkg-config. Later on we
7404762Snate@binkert.org        # check go a library config check and at that point the test
7414762Snate@binkert.org        # will fail if libprotobuf cannot be found.
7424762Snate@binkert.org        if readCommand(['pkg-config', '--version'], exception=''):
7434762Snate@binkert.org            try:
7447756SAli.Saidi@ARM.com                # Attempt to establish what linking flags to add for protobuf
7458596Ssteve.reinhardt@amd.com                # using pkg-config
7464762Snate@binkert.org                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
7474762Snate@binkert.org            except:
74811988Sandreas.sandberg@arm.com                print termcap.Yellow + termcap.Bold + \
74911988Sandreas.sandberg@arm.com                    'Warning: pkg-config could not get protobuf flags.' + \
75011988Sandreas.sandberg@arm.com                    termcap.Normal
75111988Sandreas.sandberg@arm.com
75211988Sandreas.sandberg@arm.com# Check for SWIG
75311988Sandreas.sandberg@arm.comif not main.has_key('SWIG'):
75411988Sandreas.sandberg@arm.com    print 'Error: SWIG utility not found.'
75511988Sandreas.sandberg@arm.com    print '       Please install (see http://www.swig.org) and retry.'
75611988Sandreas.sandberg@arm.com    Exit(1)
75711988Sandreas.sandberg@arm.com
75811988Sandreas.sandberg@arm.com# Check for appropriate SWIG version
7594382Sbinkertn@umich.eduswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
7609396Sandreas.hansson@arm.com# First 3 words should be "SWIG Version x.y.z"
7619396Sandreas.hansson@arm.comif len(swig_version) < 3 or \
7629396Sandreas.hansson@arm.com        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
7639396Sandreas.hansson@arm.com    print 'Error determining SWIG version.'
7649396Sandreas.hansson@arm.com    Exit(1)
7659396Sandreas.hansson@arm.com
7669396Sandreas.hansson@arm.commin_swig_version = '2.0.4'
7679396Sandreas.hansson@arm.comif compareVersions(swig_version[2], min_swig_version) < 0:
7689396Sandreas.hansson@arm.com    print 'Error: SWIG version', min_swig_version, 'or newer required.'
7699396Sandreas.hansson@arm.com    print '       Installed version:', swig_version[2]
7709396Sandreas.hansson@arm.com    Exit(1)
7719396Sandreas.hansson@arm.com
7729396Sandreas.hansson@arm.com# Check for known incompatibilities. The standard library shipped with
7739396Sandreas.hansson@arm.com# gcc >= 4.9 does not play well with swig versions prior to 3.0
7749396Sandreas.hansson@arm.comif main['GCC'] and compareVersions(gcc_version, '4.9') >= 0 and \
7759396Sandreas.hansson@arm.com        compareVersions(swig_version[2], '3.0') < 0:
7769396Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + \
7779396Sandreas.hansson@arm.com        'Warning: This combination of gcc and swig have' + \
7788232Snate@binkert.org        ' known incompatibilities.\n' + \
7798232Snate@binkert.org        '         If you encounter build problems, please update ' + \
7808232Snate@binkert.org        'swig to 3.0 or later.' + \
7818232Snate@binkert.org        termcap.Normal
7828232Snate@binkert.org
7836229Snate@binkert.org# Set up SWIG flags & scanner
78410455SCurtis.Dunham@arm.comswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
7856229Snate@binkert.orgmain.Append(SWIGFLAGS=swig_flags)
78610455SCurtis.Dunham@arm.com
78710455SCurtis.Dunham@arm.com# Check for 'timeout' from GNU coreutils. If present, regressions will
78810455SCurtis.Dunham@arm.com# be run with a time limit. We require version 8.13 since we rely on
7895517Snate@binkert.org# support for the '--foreground' option.
7905517Snate@binkert.orgtimeout_lines = readCommand(['timeout', '--version'],
7917673Snate@binkert.org                            exception='').splitlines()
7925517Snate@binkert.org# Get the first line and tokenize it
79310455SCurtis.Dunham@arm.comtimeout_version = timeout_lines[0].split() if timeout_lines else []
7945517Snate@binkert.orgmain['TIMEOUT'] =  timeout_version and \
7955517Snate@binkert.org    compareVersions(timeout_version[-1], '8.13') >= 0
7968232Snate@binkert.org
79710455SCurtis.Dunham@arm.com# filter out all existing swig scanners, they mess up the dependency
79810455SCurtis.Dunham@arm.com# stuff for some reason
79910455SCurtis.Dunham@arm.comscanners = []
8007673Snate@binkert.orgfor scanner in main['SCANNERS']:
8017673Snate@binkert.org    skeys = scanner.skeys
80210455SCurtis.Dunham@arm.com    if skeys == '.i':
80310455SCurtis.Dunham@arm.com        continue
80410455SCurtis.Dunham@arm.com
8055517Snate@binkert.org    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
80610455SCurtis.Dunham@arm.com        continue
80710455SCurtis.Dunham@arm.com
80810455SCurtis.Dunham@arm.com    scanners.append(scanner)
80910455SCurtis.Dunham@arm.com
81010455SCurtis.Dunham@arm.com# add the new swig scanner that we like better
81110455SCurtis.Dunham@arm.comfrom SCons.Scanner import ClassicCPP as CPPScanner
81210455SCurtis.Dunham@arm.comswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
81310455SCurtis.Dunham@arm.comscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
81410685Sandreas.hansson@arm.com
81510455SCurtis.Dunham@arm.com# replace the scanners list that has what we want
81610685Sandreas.hansson@arm.commain['SCANNERS'] = scanners
81710455SCurtis.Dunham@arm.com
8185517Snate@binkert.org# Add a custom Check function to the Configure context so that we can
81910455SCurtis.Dunham@arm.com# figure out if the compiler adds leading underscores to global
8208232Snate@binkert.org# variables.  This is needed for the autogenerated asm files that we
8218232Snate@binkert.org# use for embedding the python code.
8225517Snate@binkert.orgdef CheckLeading(context):
8237673Snate@binkert.org    context.Message("Checking for leading underscore in global variables...")
8245517Snate@binkert.org    # 1) Define a global variable called x from asm so the C compiler
8258232Snate@binkert.org    #    won't change the symbol at all.
8268232Snate@binkert.org    # 2) Declare that variable.
8275517Snate@binkert.org    # 3) Use the variable
8288232Snate@binkert.org    #
8298232Snate@binkert.org    # If the compiler prepends an underscore, this will successfully
8308232Snate@binkert.org    # link because the external symbol 'x' will be called '_x' which
8317673Snate@binkert.org    # was defined by the asm statement.  If the compiler does not
8325517Snate@binkert.org    # prepend an underscore, this will not successfully link because
8335517Snate@binkert.org    # '_x' will have been defined by assembly, while the C portion of
8347673Snate@binkert.org    # the code will be trying to use 'x'
8355517Snate@binkert.org    ret = context.TryLink('''
83610455SCurtis.Dunham@arm.com        asm(".globl _x; _x: .byte 0");
8375517Snate@binkert.org        extern int x;
8385517Snate@binkert.org        int main() { return x; }
8398232Snate@binkert.org        ''', extension=".c")
8408232Snate@binkert.org    context.env.Append(LEADING_UNDERSCORE=ret)
8415517Snate@binkert.org    context.Result(ret)
8428232Snate@binkert.org    return ret
8438232Snate@binkert.org
8445517Snate@binkert.org# Add a custom Check function to test for structure members.
8458232Snate@binkert.orgdef CheckMember(context, include, decl, member, include_quotes="<>"):
8468232Snate@binkert.org    context.Message("Checking for member %s in %s..." %
8478232Snate@binkert.org                    (member, decl))
8485517Snate@binkert.org    text = """
8498232Snate@binkert.org#include %(header)s
8508232Snate@binkert.orgint main(){
8518232Snate@binkert.org  %(decl)s test;
8528232Snate@binkert.org  (void)test.%(member)s;
8538232Snate@binkert.org  return 0;
8548232Snate@binkert.org};
8555517Snate@binkert.org""" % { "header" : include_quotes[0] + include + include_quotes[1],
8568232Snate@binkert.org        "decl" : decl,
8578232Snate@binkert.org        "member" : member,
8585517Snate@binkert.org        }
8598232Snate@binkert.org
8607673Snate@binkert.org    ret = context.TryCompile(text, extension=".cc")
8615517Snate@binkert.org    context.Result(ret)
8627673Snate@binkert.org    return ret
8635517Snate@binkert.org
8648232Snate@binkert.org# Platform-specific configuration.  Note again that we assume that all
8658232Snate@binkert.org# builds under a given build root run on the same host platform.
8668232Snate@binkert.orgconf = Configure(main,
8675192Ssaidi@eecs.umich.edu                 conf_dir = joinpath(build_root, '.scons_config'),
86810454SCurtis.Dunham@arm.com                 log_file = joinpath(build_root, 'scons_config.log'),
86910454SCurtis.Dunham@arm.com                 custom_tests = {
8708232Snate@binkert.org        'CheckLeading' : CheckLeading,
87110455SCurtis.Dunham@arm.com        'CheckMember' : CheckMember,
87210455SCurtis.Dunham@arm.com        })
87310455SCurtis.Dunham@arm.com
87410455SCurtis.Dunham@arm.com# Check for leading underscores.  Don't really need to worry either
8755192Ssaidi@eecs.umich.edu# way so don't need to check the return code.
87611077SCurtis.Dunham@arm.comconf.CheckLeading()
87711330SCurtis.Dunham@arm.com
87811077SCurtis.Dunham@arm.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
87911077SCurtis.Dunham@arm.comtry:
88011077SCurtis.Dunham@arm.com    import platform
88111330SCurtis.Dunham@arm.com    uname = platform.uname()
88211077SCurtis.Dunham@arm.com    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
8837674Snate@binkert.org        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
8845522Snate@binkert.org            main.Append(CCFLAGS=['-arch', 'x86_64'])
8855522Snate@binkert.org            main.Append(CFLAGS=['-arch', 'x86_64'])
8867674Snate@binkert.org            main.Append(LINKFLAGS=['-arch', 'x86_64'])
8877674Snate@binkert.org            main.Append(ASFLAGS=['-arch', 'x86_64'])
8887674Snate@binkert.orgexcept:
8897674Snate@binkert.org    pass
8907674Snate@binkert.org
8917674Snate@binkert.org# Recent versions of scons substitute a "Null" object for Configure()
8927674Snate@binkert.org# when configuration isn't necessary, e.g., if the "--help" option is
8937674Snate@binkert.org# present.  Unfortuantely this Null object always returns false,
8945522Snate@binkert.org# breaking all our configuration checks.  We replace it with our own
8955522Snate@binkert.org# more optimistic null object that returns True instead.
8965522Snate@binkert.orgif not conf:
8975517Snate@binkert.org    def NullCheck(*args, **kwargs):
8985522Snate@binkert.org        return True
8995517Snate@binkert.org
9006143Snate@binkert.org    class NullConf:
9016727Ssteve.reinhardt@amd.com        def __init__(self, env):
9025522Snate@binkert.org            self.env = env
9035522Snate@binkert.org        def Finish(self):
9045522Snate@binkert.org            return self.env
9057674Snate@binkert.org        def __getattr__(self, mname):
9065517Snate@binkert.org            return NullCheck
9077673Snate@binkert.org
9087673Snate@binkert.org    conf = NullConf(main)
9097674Snate@binkert.org
9107673Snate@binkert.org# Cache build files in the supplied directory.
9117674Snate@binkert.orgif main['M5_BUILD_CACHE']:
9127674Snate@binkert.org    print 'Using build cache located at', main['M5_BUILD_CACHE']
9138946Sandreas.hansson@arm.com    CacheDir(main['M5_BUILD_CACHE'])
9147674Snate@binkert.org
9157674Snate@binkert.orgif not GetOption('without_python'):
9167674Snate@binkert.org    # Find Python include and library directories for embedding the
9175522Snate@binkert.org    # interpreter. We rely on python-config to resolve the appropriate
9185522Snate@binkert.org    # includes and linker flags. ParseConfig does not seem to understand
9197674Snate@binkert.org    # the more exotic linker flags such as -Xlinker and -export-dynamic so
9207674Snate@binkert.org    # we add them explicitly below. If you want to link in an alternate
92111308Santhony.gutierrez@amd.com    # version of python, see above for instructions on how to invoke
9227674Snate@binkert.org    # scons with the appropriate PATH set.
9237673Snate@binkert.org    #
9247674Snate@binkert.org    # First we check if python2-config exists, else we use python-config
9257674Snate@binkert.org    python_config = readCommand(['which', 'python2-config'],
9267674Snate@binkert.org                                exception='').strip()
9277674Snate@binkert.org    if not os.path.exists(python_config):
9287674Snate@binkert.org        python_config = readCommand(['which', 'python-config'],
9297674Snate@binkert.org                                    exception='').strip()
9307674Snate@binkert.org    py_includes = readCommand([python_config, '--includes'],
9317674Snate@binkert.org                              exception='').split()
9327811Ssteve.reinhardt@amd.com    # Strip the -I from the include folders before adding them to the
9337674Snate@binkert.org    # CPPPATH
9347673Snate@binkert.org    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
9355522Snate@binkert.org
9366143Snate@binkert.org    # Read the linker flags and split them into libraries and other link
93710453SAndrew.Bardsley@arm.com    # flags. The libraries are added later through the call the CheckLib.
9387816Ssteve.reinhardt@amd.com    py_ld_flags = readCommand([python_config, '--ldflags'],
93910453SAndrew.Bardsley@arm.com        exception='').split()
9404382Sbinkertn@umich.edu    py_libs = []
9414382Sbinkertn@umich.edu    for lib in py_ld_flags:
9424382Sbinkertn@umich.edu         if not lib.startswith('-l'):
9434382Sbinkertn@umich.edu             main.Append(LINKFLAGS=[lib])
9444382Sbinkertn@umich.edu         else:
9454382Sbinkertn@umich.edu             lib = lib[2:]
9464382Sbinkertn@umich.edu             if lib not in py_libs:
9474382Sbinkertn@umich.edu                 py_libs.append(lib)
94810196SCurtis.Dunham@arm.com
9494382Sbinkertn@umich.edu    # verify that this stuff works
9502655Sstever@eecs.umich.edu    if not conf.CheckHeader('Python.h', '<>'):
9512655Sstever@eecs.umich.edu        print "Error: can't find Python.h header in", py_includes
9522655Sstever@eecs.umich.edu        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
9532655Sstever@eecs.umich.edu        Exit(1)
95412063Sgabeblack@google.com
9555601Snate@binkert.org    for lib in py_libs:
9565601Snate@binkert.org        if not conf.CheckLib(lib):
95712222Sgabeblack@google.com            print "Error: can't find library %s required by python" % lib
95812222Sgabeblack@google.com            Exit(1)
95912222Sgabeblack@google.com
9605522Snate@binkert.org# On Solaris you need to use libsocket for socket ops
9615863Snate@binkert.orgif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
9625601Snate@binkert.org   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
9635601Snate@binkert.org       print "Can't find library with socket calls (e.g. accept())"
9645601Snate@binkert.org       Exit(1)
9655559Snate@binkert.org
96611718Sjoseph.gross@amd.com# Check for zlib.  If the check passes, libz will be automatically
96711718Sjoseph.gross@amd.com# added to the LIBS environment variable.
96811718Sjoseph.gross@amd.comif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
96911718Sjoseph.gross@amd.com    print 'Error: did not find needed zlib compression library '\
97011718Sjoseph.gross@amd.com          'and/or zlib.h header file.'
97111718Sjoseph.gross@amd.com    print '       Please install zlib and try again.'
97211718Sjoseph.gross@amd.com    Exit(1)
97311718Sjoseph.gross@amd.com
97411718Sjoseph.gross@amd.com# If we have the protobuf compiler, also make sure we have the
97511718Sjoseph.gross@amd.com# development libraries. If the check passes, libprotobuf will be
97611718Sjoseph.gross@amd.com# automatically added to the LIBS environment variable. After
97710457Sandreas.hansson@arm.com# this, we can use the HAVE_PROTOBUF flag to determine if we have
97810457Sandreas.hansson@arm.com# got both protoc and libprotobuf available.
97910457Sandreas.hansson@arm.commain['HAVE_PROTOBUF'] = main['PROTOC'] and \
98011718Sjoseph.gross@amd.com    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
98110457Sandreas.hansson@arm.com                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
98210457Sandreas.hansson@arm.com
98310457Sandreas.hansson@arm.com# If we have the compiler but not the library, print another warning.
98410457Sandreas.hansson@arm.comif main['PROTOC'] and not main['HAVE_PROTOBUF']:
98511342Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + \
9868737Skoansin.tan@gmail.com        'Warning: did not find protocol buffer library and/or headers.\n' + \
98711342Sandreas.hansson@arm.com    '       Please install libprotobuf-dev for tracing support.' + \
98811342Sandreas.hansson@arm.com    termcap.Normal
98910457Sandreas.hansson@arm.com
99011718Sjoseph.gross@amd.com# Check for librt.
99111718Sjoseph.gross@amd.comhave_posix_clock = \
99211718Sjoseph.gross@amd.com    conf.CheckLibWithHeader(None, 'time.h', 'C',
99311718Sjoseph.gross@amd.com                            'clock_nanosleep(0,0,NULL,NULL);') or \
99411718Sjoseph.gross@amd.com    conf.CheckLibWithHeader('rt', 'time.h', 'C',
99511718Sjoseph.gross@amd.com                            'clock_nanosleep(0,0,NULL,NULL);')
99611718Sjoseph.gross@amd.com
99710457Sandreas.hansson@arm.comhave_posix_timers = \
99811718Sjoseph.gross@amd.com    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
99911500Sandreas.hansson@arm.com                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
100011500Sandreas.hansson@arm.com
100111342Sandreas.hansson@arm.comif not GetOption('without_tcmalloc'):
100211342Sandreas.hansson@arm.com    if conf.CheckLib('tcmalloc'):
10038945Ssteve.reinhardt@amd.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
100410686SAndreas.Sandberg@ARM.com    elif conf.CheckLib('tcmalloc_minimal'):
100510686SAndreas.Sandberg@ARM.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
100610686SAndreas.Sandberg@ARM.com    else:
100710686SAndreas.Sandberg@ARM.com        print termcap.Yellow + termcap.Bold + \
100810686SAndreas.Sandberg@ARM.com              "You can get a 12% performance improvement by "\
100910686SAndreas.Sandberg@ARM.com              "installing tcmalloc (libgoogle-perftools-dev package "\
10108945Ssteve.reinhardt@amd.com              "on Ubuntu or RedHat)." + termcap.Normal
10116143Snate@binkert.org
10126143Snate@binkert.orgif not have_posix_clock:
10136143Snate@binkert.org    print "Can't find library for POSIX clocks."
10146143Snate@binkert.org
10156143Snate@binkert.org# Check for <fenv.h> (C99 FP environment control)
101611988Sandreas.sandberg@arm.comhave_fenv = conf.CheckHeader('fenv.h', '<>')
10178945Ssteve.reinhardt@amd.comif not have_fenv:
10186143Snate@binkert.org    print "Warning: Header file <fenv.h> not found."
10196143Snate@binkert.org    print "         This host has no IEEE FP rounding mode control."
10206143Snate@binkert.org
10216143Snate@binkert.org# Check if we should enable KVM-based hardware virtualization. The API
10226143Snate@binkert.org# we rely on exists since version 2.6.36 of the kernel, but somehow
10236143Snate@binkert.org# the KVM_API_VERSION does not reflect the change. We test for one of
10246143Snate@binkert.org# the types as a fall back.
10256143Snate@binkert.orghave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
10266143Snate@binkert.orgif not have_kvm:
10276143Snate@binkert.org    print "Info: Compatible header file <linux/kvm.h> not found, " \
10286143Snate@binkert.org        "disabling KVM support."
10296143Snate@binkert.org
10306143Snate@binkert.org# x86 needs support for xsave. We test for the structure here since we
103110453SAndrew.Bardsley@arm.com# won't be able to run new tests by the time we know which ISA we're
103210453SAndrew.Bardsley@arm.com# targeting.
103311988Sandreas.sandberg@arm.comhave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
103411988Sandreas.sandberg@arm.com                                    '#include <linux/kvm.h>') != 0
103510453SAndrew.Bardsley@arm.com
103610453SAndrew.Bardsley@arm.com# Check if the requested target ISA is compatible with the host
103710453SAndrew.Bardsley@arm.comdef is_isa_kvm_compatible(isa):
103811983Sgabeblack@google.com    try:
103911983Sgabeblack@google.com        import platform
104011983Sgabeblack@google.com        host_isa = platform.machine()
104111983Sgabeblack@google.com    except:
104211983Sgabeblack@google.com        print "Warning: Failed to determine host ISA."
104311983Sgabeblack@google.com        return False
104411983Sgabeblack@google.com
104511983Sgabeblack@google.com    if not have_posix_timers:
104611983Sgabeblack@google.com        print "Warning: Can not enable KVM, host seems to lack support " \
104711983Sgabeblack@google.com            "for POSIX timers"
104811983Sgabeblack@google.com        return False
104911983Sgabeblack@google.com
105011983Sgabeblack@google.com    if isa == "arm":
105111983Sgabeblack@google.com        return host_isa in ( "armv7l", "aarch64" )
105211983Sgabeblack@google.com    elif isa == "x86":
105311983Sgabeblack@google.com        if host_isa != "x86_64":
105411983Sgabeblack@google.com            return False
105511983Sgabeblack@google.com
105612063Sgabeblack@google.com        if not have_kvm_xsave:
105712063Sgabeblack@google.com            print "KVM on x86 requires xsave support in kernel headers."
105812063Sgabeblack@google.com            return False
105912063Sgabeblack@google.com
106012063Sgabeblack@google.com        return True
106112063Sgabeblack@google.com    else:
106212063Sgabeblack@google.com        return False
106312063Sgabeblack@google.com
106411983Sgabeblack@google.com
106511983Sgabeblack@google.com# Check if the exclude_host attribute is available. We want this to
106611983Sgabeblack@google.com# get accurate instruction counts in KVM.
106711983Sgabeblack@google.commain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
106811983Sgabeblack@google.com    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
106911983Sgabeblack@google.com
107011983Sgabeblack@google.com
107111983Sgabeblack@google.com######################################################################
107211983Sgabeblack@google.com#
107311983Sgabeblack@google.com# Finish the configuration
107411983Sgabeblack@google.com#
107511983Sgabeblack@google.commain = conf.Finish()
107611983Sgabeblack@google.com
10776143Snate@binkert.org######################################################################
10786143Snate@binkert.org#
10796143Snate@binkert.org# Collect all non-global variables
108010453SAndrew.Bardsley@arm.com#
10816143Snate@binkert.org
10826240Snate@binkert.org# Define the universe of supported ISAs
10835554Snate@binkert.orgall_isa_list = [ ]
10845522Snate@binkert.orgExport('all_isa_list')
10855522Snate@binkert.org
10865797Snate@binkert.orgclass CpuModel(object):
10875797Snate@binkert.org    '''The CpuModel class encapsulates everything the ISA parser needs to
10885522Snate@binkert.org    know about a particular CPU model.'''
10895601Snate@binkert.org
10908233Snate@binkert.org    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
10918233Snate@binkert.org    dict = {}
10928235Snate@binkert.org
10938235Snate@binkert.org    # Constructor.  Automatically adds models to CpuModel.dict.
10948235Snate@binkert.org    def __init__(self, name, default=False):
10958235Snate@binkert.org        self.name = name           # name of model
10969003SAli.Saidi@ARM.com
10979003SAli.Saidi@ARM.com        # This cpu is enabled by default
109812222Sgabeblack@google.com        self.default = default
109910196SCurtis.Dunham@arm.com
11008235Snate@binkert.org        # Add self to dict
11016143Snate@binkert.org        if name in CpuModel.dict:
11022655Sstever@eecs.umich.edu            raise AttributeError, "CpuModel '%s' already registered" % name
11036143Snate@binkert.org        CpuModel.dict[name] = self
11046143Snate@binkert.org
110511985Sgabeblack@google.comExport('CpuModel')
11066143Snate@binkert.org
11076143Snate@binkert.org# Sticky variables get saved in the variables file so they persist from
11084007Ssaidi@eecs.umich.edu# one invocation to the next (unless overridden, in which case the new
11094596Sbinkertn@umich.edu# value becomes sticky).
11104007Ssaidi@eecs.umich.edusticky_vars = Variables(args=ARGUMENTS)
11114596Sbinkertn@umich.eduExport('sticky_vars')
11127756SAli.Saidi@ARM.com
11137816Ssteve.reinhardt@amd.com# Sticky variables that should be exported
11148334Snate@binkert.orgexport_vars = []
11158334Snate@binkert.orgExport('export_vars')
11168334Snate@binkert.org
11178334Snate@binkert.org# For Ruby
11185601Snate@binkert.orgall_protocols = []
111911993Sgabeblack@google.comExport('all_protocols')
112011993Sgabeblack@google.comprotocol_dirs = []
112111993Sgabeblack@google.comExport('protocol_dirs')
112212223Sgabeblack@google.comslicc_includes = []
112311993Sgabeblack@google.comExport('slicc_includes')
11242655Sstever@eecs.umich.edu
11259225Sandreas.hansson@arm.com# Walk the tree and execute all SConsopts scripts that wil add to the
11269225Sandreas.hansson@arm.com# above variables
11279226Sandreas.hansson@arm.comif GetOption('verbose'):
11289226Sandreas.hansson@arm.com    print "Reading SConsopts"
11299225Sandreas.hansson@arm.comfor bdir in [ base_dir ] + extras_dir_list:
11309226Sandreas.hansson@arm.com    if not isdir(bdir):
11319226Sandreas.hansson@arm.com        print "Error: directory '%s' does not exist" % bdir
11329226Sandreas.hansson@arm.com        Exit(1)
11339226Sandreas.hansson@arm.com    for root, dirs, files in os.walk(bdir):
11349226Sandreas.hansson@arm.com        if 'SConsopts' in files:
11359226Sandreas.hansson@arm.com            if GetOption('verbose'):
11369225Sandreas.hansson@arm.com                print "Reading", joinpath(root, 'SConsopts')
11379227Sandreas.hansson@arm.com            SConscript(joinpath(root, 'SConsopts'))
11389227Sandreas.hansson@arm.com
11399227Sandreas.hansson@arm.comall_isa_list.sort()
11409227Sandreas.hansson@arm.com
11418946Sandreas.hansson@arm.comsticky_vars.AddVariables(
11423918Ssaidi@eecs.umich.edu    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
11439225Sandreas.hansson@arm.com    ListVariable('CPU_MODELS', 'CPU models',
11443918Ssaidi@eecs.umich.edu                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
11459225Sandreas.hansson@arm.com                 sorted(CpuModel.dict.keys())),
11469225Sandreas.hansson@arm.com    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
11479227Sandreas.hansson@arm.com                 False),
11489227Sandreas.hansson@arm.com    BoolVariable('SS_COMPATIBLE_FP',
11499227Sandreas.hansson@arm.com                 'Make floating-point results compatible with SimpleScalar',
11509226Sandreas.hansson@arm.com                 False),
11519225Sandreas.hansson@arm.com    BoolVariable('USE_SSE2',
11529227Sandreas.hansson@arm.com                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
11539227Sandreas.hansson@arm.com                 False),
11549227Sandreas.hansson@arm.com    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
11559227Sandreas.hansson@arm.com    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
11568946Sandreas.hansson@arm.com    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
11579225Sandreas.hansson@arm.com    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
11589226Sandreas.hansson@arm.com    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
11599226Sandreas.hansson@arm.com                  all_protocols),
11609226Sandreas.hansson@arm.com    )
11613515Ssaidi@eecs.umich.edu
11623918Ssaidi@eecs.umich.edu# These variables get exported to #defines in config/*.hh (see src/SConscript).
11634762Snate@binkert.orgexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'CP_ANNOTATE',
11643515Ssaidi@eecs.umich.edu                'USE_POSIX_CLOCK', 'USE_KVM', 'PROTOCOL', 'HAVE_PROTOBUF',
11658881Smarc.orr@gmail.com                'HAVE_PERF_ATTR_EXCLUDE_HOST']
11668881Smarc.orr@gmail.com
11678881Smarc.orr@gmail.com###################################################
11688881Smarc.orr@gmail.com#
11698881Smarc.orr@gmail.com# Define a SCons builder for configuration flag headers.
11709226Sandreas.hansson@arm.com#
11719226Sandreas.hansson@arm.com###################################################
11729226Sandreas.hansson@arm.com
11738881Smarc.orr@gmail.com# This function generates a config header file that #defines the
11748881Smarc.orr@gmail.com# variable symbol to the current variable setting (0 or 1).  The source
11758881Smarc.orr@gmail.com# operands are the name of the variable and a Value node containing the
11768881Smarc.orr@gmail.com# value of the variable.
11778881Smarc.orr@gmail.comdef build_config_file(target, source, env):
11788881Smarc.orr@gmail.com    (variable, value) = [s.get_contents() for s in source]
11798881Smarc.orr@gmail.com    f = file(str(target[0]), 'w')
11808881Smarc.orr@gmail.com    print >> f, '#define', variable, value
11818881Smarc.orr@gmail.com    f.close()
11828881Smarc.orr@gmail.com    return None
11838881Smarc.orr@gmail.com
11848881Smarc.orr@gmail.com# Combine the two functions into a scons Action object.
11858881Smarc.orr@gmail.comconfig_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
11868881Smarc.orr@gmail.com
11878881Smarc.orr@gmail.com# The emitter munges the source & target node lists to reflect what
11888881Smarc.orr@gmail.com# we're really doing.
118912222Sgabeblack@google.comdef config_emitter(target, source, env):
119012222Sgabeblack@google.com    # extract variable name from Builder arg
119112222Sgabeblack@google.com    variable = str(target[0])
119212222Sgabeblack@google.com    # True target is config header file
119312222Sgabeblack@google.com    target = joinpath('config', variable.lower() + '.hh')
119412222Sgabeblack@google.com    val = env[variable]
1195955SN/A    if isinstance(val, bool):
119612222Sgabeblack@google.com        # Force value to 0/1
119712222Sgabeblack@google.com        val = int(val)
119812222Sgabeblack@google.com    elif isinstance(val, str):
119912222Sgabeblack@google.com        val = '"' + val + '"'
120012222Sgabeblack@google.com
120112222Sgabeblack@google.com    # Sources are variable name & value (packaged in SCons Value nodes)
1202955SN/A    return ([target], [Value(variable), Value(val)])
120312222Sgabeblack@google.com
120412222Sgabeblack@google.comconfig_builder = Builder(emitter = config_emitter, action = config_action)
120512222Sgabeblack@google.com
120612222Sgabeblack@google.commain.Append(BUILDERS = { 'ConfigFile' : config_builder })
120712222Sgabeblack@google.com
120812222Sgabeblack@google.com# libelf build is shared across all configs in the build root.
120912222Sgabeblack@google.commain.SConscript('ext/libelf/SConscript',
121012222Sgabeblack@google.com                variant_dir = joinpath(build_root, 'libelf'))
121112222Sgabeblack@google.com
121212222Sgabeblack@google.com# gzstream build is shared across all configs in the build root.
12131869SN/Amain.SConscript('ext/gzstream/SConscript',
121412222Sgabeblack@google.com                variant_dir = joinpath(build_root, 'gzstream'))
121512222Sgabeblack@google.com
121612222Sgabeblack@google.com# libfdt build is shared across all configs in the build root.
121712222Sgabeblack@google.commain.SConscript('ext/libfdt/SConscript',
121812222Sgabeblack@google.com                variant_dir = joinpath(build_root, 'libfdt'))
121912222Sgabeblack@google.com
12209226Sandreas.hansson@arm.com# fputils build is shared across all configs in the build root.
122112222Sgabeblack@google.commain.SConscript('ext/fputils/SConscript',
122212222Sgabeblack@google.com                variant_dir = joinpath(build_root, 'fputils'))
122312222Sgabeblack@google.com
122412222Sgabeblack@google.com# DRAMSim2 build is shared across all configs in the build root.
122512222Sgabeblack@google.commain.SConscript('ext/dramsim2/SConscript',
122612222Sgabeblack@google.com                variant_dir = joinpath(build_root, 'dramsim2'))
1227
1228# DRAMPower build is shared across all configs in the build root.
1229main.SConscript('ext/drampower/SConscript',
1230                variant_dir = joinpath(build_root, 'drampower'))
1231
1232###################################################
1233#
1234# This function is used to set up a directory with switching headers
1235#
1236###################################################
1237
1238main['ALL_ISA_LIST'] = all_isa_list
1239all_isa_deps = {}
1240def make_switching_dir(dname, switch_headers, env):
1241    # Generate the header.  target[0] is the full path of the output
1242    # header to generate.  'source' is a dummy variable, since we get the
1243    # list of ISAs from env['ALL_ISA_LIST'].
1244    def gen_switch_hdr(target, source, env):
1245        fname = str(target[0])
1246        isa = env['TARGET_ISA'].lower()
1247        try:
1248            f = open(fname, 'w')
1249            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1250            f.close()
1251        except IOError:
1252            print "Failed to create %s" % fname
1253            raise
1254
1255    # Build SCons Action object. 'varlist' specifies env vars that this
1256    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1257    # should get re-executed.
1258    switch_hdr_action = MakeAction(gen_switch_hdr,
1259                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1260
1261    # Instantiate actions for each header
1262    for hdr in switch_headers:
1263        env.Command(hdr, [], switch_hdr_action)
1264
1265    isa_target = Dir('.').up().name.lower().replace('_', '-')
1266    env['PHONY_BASE'] = '#'+isa_target
1267    all_isa_deps[isa_target] = None
1268
1269Export('make_switching_dir')
1270
1271# all-isas -> all-deps -> all-environs -> all_targets
1272main.Alias('#all-isas', [])
1273main.Alias('#all-deps', '#all-isas')
1274
1275# Dummy target to ensure all environments are created before telling
1276# SCons what to actually make (the command line arguments).  We attach
1277# them to the dependence graph after the environments are complete.
1278ORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
1279def environsComplete(target, source, env):
1280    for t in ORIG_BUILD_TARGETS:
1281        main.Depends('#all-targets', t)
1282
1283# Each build/* switching_dir attaches its *-environs target to #all-environs.
1284main.Append(BUILDERS = {'CompleteEnvirons' :
1285                        Builder(action=MakeAction(environsComplete, None))})
1286main.CompleteEnvirons('#all-environs', [])
1287
1288def doNothing(**ignored): pass
1289main.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
1290
1291# The final target to which all the original targets ultimately get attached.
1292main.Dummy('#all-targets', '#all-environs')
1293BUILD_TARGETS[:] = ['#all-targets']
1294
1295###################################################
1296#
1297# Define build environments for selected configurations.
1298#
1299###################################################
1300
1301for variant_path in variant_paths:
1302    if not GetOption('silent'):
1303        print "Building in", variant_path
1304
1305    # Make a copy of the build-root environment to use for this config.
1306    env = main.Clone()
1307    env['BUILDDIR'] = variant_path
1308
1309    # variant_dir is the tail component of build path, and is used to
1310    # determine the build parameters (e.g., 'ALPHA_SE')
1311    (build_root, variant_dir) = splitpath(variant_path)
1312
1313    # Set env variables according to the build directory config.
1314    sticky_vars.files = []
1315    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1316    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1317    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1318    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1319    if isfile(current_vars_file):
1320        sticky_vars.files.append(current_vars_file)
1321        if not GetOption('silent'):
1322            print "Using saved variables file %s" % current_vars_file
1323    else:
1324        # Build dir-specific variables file doesn't exist.
1325
1326        # Make sure the directory is there so we can create it later
1327        opt_dir = dirname(current_vars_file)
1328        if not isdir(opt_dir):
1329            mkdir(opt_dir)
1330
1331        # Get default build variables from source tree.  Variables are
1332        # normally determined by name of $VARIANT_DIR, but can be
1333        # overridden by '--default=' arg on command line.
1334        default = GetOption('default')
1335        opts_dir = joinpath(main.root.abspath, 'build_opts')
1336        if default:
1337            default_vars_files = [joinpath(build_root, 'variables', default),
1338                                  joinpath(opts_dir, default)]
1339        else:
1340            default_vars_files = [joinpath(opts_dir, variant_dir)]
1341        existing_files = filter(isfile, default_vars_files)
1342        if existing_files:
1343            default_vars_file = existing_files[0]
1344            sticky_vars.files.append(default_vars_file)
1345            print "Variables file %s not found,\n  using defaults in %s" \
1346                  % (current_vars_file, default_vars_file)
1347        else:
1348            print "Error: cannot find variables file %s or " \
1349                  "default file(s) %s" \
1350                  % (current_vars_file, ' or '.join(default_vars_files))
1351            Exit(1)
1352
1353    # Apply current variable settings to env
1354    sticky_vars.Update(env)
1355
1356    help_texts["local_vars"] += \
1357        "Build variables for %s:\n" % variant_dir \
1358                 + sticky_vars.GenerateHelpText(env)
1359
1360    # Process variable settings.
1361
1362    if not have_fenv and env['USE_FENV']:
1363        print "Warning: <fenv.h> not available; " \
1364              "forcing USE_FENV to False in", variant_dir + "."
1365        env['USE_FENV'] = False
1366
1367    if not env['USE_FENV']:
1368        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1369        print "         FP results may deviate slightly from other platforms."
1370
1371    if env['EFENCE']:
1372        env.Append(LIBS=['efence'])
1373
1374    if env['USE_KVM']:
1375        if not have_kvm:
1376            print "Warning: Can not enable KVM, host seems to lack KVM support"
1377            env['USE_KVM'] = False
1378        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1379            print "Info: KVM support disabled due to unsupported host and " \
1380                "target ISA combination"
1381            env['USE_KVM'] = False
1382
1383    # Warn about missing optional functionality
1384    if env['USE_KVM']:
1385        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1386            print "Warning: perf_event headers lack support for the " \
1387                "exclude_host attribute. KVM instruction counts will " \
1388                "be inaccurate."
1389
1390    # Save sticky variable settings back to current variables file
1391    sticky_vars.Save(current_vars_file, env)
1392
1393    if env['USE_SSE2']:
1394        env.Append(CCFLAGS=['-msse2'])
1395
1396    # The src/SConscript file sets up the build rules in 'env' according
1397    # to the configured variables.  It returns a list of environments,
1398    # one for each variant build (debug, opt, etc.)
1399    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1400
1401def pairwise(iterable):
1402    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1403    a, b = itertools.tee(iterable)
1404    b.next()
1405    return itertools.izip(a, b)
1406
1407# Create false dependencies so SCons will parse ISAs, establish
1408# dependencies, and setup the build Environments serially. Either
1409# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1410# greater than 1. It appears to be standard race condition stuff; it
1411# doesn't always fail, but usually, and the behaviors are different.
1412# Every time I tried to remove this, builds would fail in some
1413# creative new way. So, don't do that. You'll want to, though, because
1414# tests/SConscript takes a long time to make its Environments.
1415for t1, t2 in pairwise(sorted(all_isa_deps.iterkeys())):
1416    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1417    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1418
1419# base help text
1420Help('''
1421Usage: scons [scons options] [build variables] [target(s)]
1422
1423Extra scons options:
1424%(options)s
1425
1426Global build variables:
1427%(global_vars)s
1428
1429%(local_vars)s
1430''' % help_texts)
1431