SConstruct revision 9590
17199Sgblack@eecs.umich.edu# -*- mode:python -*-
27199Sgblack@eecs.umich.edu
37199Sgblack@eecs.umich.edu# Copyright (c) 2011 Advanced Micro Devices, Inc.
47199Sgblack@eecs.umich.edu# Copyright (c) 2009 The Hewlett-Packard Development Company
57199Sgblack@eecs.umich.edu# Copyright (c) 2004-2005 The Regents of The University of Michigan
67199Sgblack@eecs.umich.edu# All rights reserved.
77199Sgblack@eecs.umich.edu#
87199Sgblack@eecs.umich.edu# Redistribution and use in source and binary forms, with or without
97199Sgblack@eecs.umich.edu# modification, are permitted provided that the following conditions are
107199Sgblack@eecs.umich.edu# met: redistributions of source code must retain the above copyright
117199Sgblack@eecs.umich.edu# notice, this list of conditions and the following disclaimer;
127199Sgblack@eecs.umich.edu# redistributions in binary form must reproduce the above copyright
137199Sgblack@eecs.umich.edu# notice, this list of conditions and the following disclaimer in the
147199Sgblack@eecs.umich.edu# documentation and/or other materials provided with the distribution;
157199Sgblack@eecs.umich.edu# neither the name of the copyright holders nor the names of its
167199Sgblack@eecs.umich.edu# contributors may be used to endorse or promote products derived from
177199Sgblack@eecs.umich.edu# this software without specific prior written permission.
187199Sgblack@eecs.umich.edu#
197199Sgblack@eecs.umich.edu# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
207199Sgblack@eecs.umich.edu# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
217199Sgblack@eecs.umich.edu# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
227199Sgblack@eecs.umich.edu# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
237199Sgblack@eecs.umich.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
247199Sgblack@eecs.umich.edu# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
257199Sgblack@eecs.umich.edu# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
267199Sgblack@eecs.umich.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
277199Sgblack@eecs.umich.edu# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
287199Sgblack@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
297199Sgblack@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
307199Sgblack@eecs.umich.edu#
317199Sgblack@eecs.umich.edu# Authors: Steve Reinhardt
327199Sgblack@eecs.umich.edu#          Nathan Binkert
337199Sgblack@eecs.umich.edu
347199Sgblack@eecs.umich.edu###################################################
357199Sgblack@eecs.umich.edu#
367199Sgblack@eecs.umich.edu# SCons top-level build description (SConstruct) file.
377199Sgblack@eecs.umich.edu#
387199Sgblack@eecs.umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
397199Sgblack@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
407199Sgblack@eecs.umich.edu# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
417199Sgblack@eecs.umich.edu# the optimized full-system version).
427199Sgblack@eecs.umich.edu#
437199Sgblack@eecs.umich.edu# You can build gem5 in a different directory as long as there is a
447199Sgblack@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
457199Sgblack@eecs.umich.edu# expects that all configs under the same build directory are being
467199Sgblack@eecs.umich.edu# built for the same host system.
477199Sgblack@eecs.umich.edu#
487199Sgblack@eecs.umich.edu# Examples:
497199Sgblack@eecs.umich.edu#
507199Sgblack@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
517199Sgblack@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
527199Sgblack@eecs.umich.edu#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
537199Sgblack@eecs.umich.edu#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
547199Sgblack@eecs.umich.edu#
557199Sgblack@eecs.umich.edu#   The following two commands are equivalent and demonstrate building
567199Sgblack@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
577199Sgblack@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
587202Sgblack@eecs.umich.edu#   file.
597202Sgblack@eecs.umich.edu#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
607202Sgblack@eecs.umich.edu#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
617202Sgblack@eecs.umich.edu#
627202Sgblack@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
637202Sgblack@eecs.umich.edu# 'gem5' directory (or use -u or -C to tell scons where to find this
647202Sgblack@eecs.umich.edu# file), you can use 'scons -h' to print all the gem5-specific build
657202Sgblack@eecs.umich.edu# options as well.
667599Sminkyu.jeong@arm.com#
677783SGiacomo.Gabrielli@arm.com###################################################
687202Sgblack@eecs.umich.edu
697202Sgblack@eecs.umich.edu# Check for recent-enough Python and SCons versions.
707202Sgblack@eecs.umich.edutry:
717202Sgblack@eecs.umich.edu    # Really old versions of scons only take two options for the
727202Sgblack@eecs.umich.edu    # function, so check once without the revision and once with the
737202Sgblack@eecs.umich.edu    # revision, the first instance will fail for stuff other than
747202Sgblack@eecs.umich.edu    # 0.98, and the second will fail for 0.98.0
757599Sminkyu.jeong@arm.com    EnsureSConsVersion(0, 98)
767783SGiacomo.Gabrielli@arm.com    EnsureSConsVersion(0, 98, 1)
777202Sgblack@eecs.umich.eduexcept SystemExit, e:
787202Sgblack@eecs.umich.edu    print """
797202Sgblack@eecs.umich.eduFor more details, see:
807202Sgblack@eecs.umich.edu    http://gem5.org/Dependencies
817202Sgblack@eecs.umich.edu"""
827400SAli.Saidi@ARM.com    raise
837202Sgblack@eecs.umich.edu
847400SAli.Saidi@ARM.com# We ensure the python version early because we have stuff that
857202Sgblack@eecs.umich.edu# requires python 2.4
867797Sgblack@eecs.umich.edutry:
877797Sgblack@eecs.umich.edu    EnsurePythonVersion(2, 4)
887858SMatt.Horsnell@arm.comexcept SystemExit, e:
897858SMatt.Horsnell@arm.com    print """
907202Sgblack@eecs.umich.eduYou can use a non-default installation of the Python interpreter by
917202Sgblack@eecs.umich.edueither (1) rearranging your PATH so that scons finds the non-default
927202Sgblack@eecs.umich.edu'python' first or (2) explicitly invoking an alternative interpreter
937202Sgblack@eecs.umich.eduon the scons script.
947599Sminkyu.jeong@arm.com
957599Sminkyu.jeong@arm.comFor more details, see:
967202Sgblack@eecs.umich.edu    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
977202Sgblack@eecs.umich.edu"""
987202Sgblack@eecs.umich.edu    raise
997202Sgblack@eecs.umich.edu
1007202Sgblack@eecs.umich.edu# Global Python includes
1017202Sgblack@eecs.umich.eduimport os
1027202Sgblack@eecs.umich.eduimport re
1037599Sminkyu.jeong@arm.comimport subprocess
1047599Sminkyu.jeong@arm.comimport sys
1057202Sgblack@eecs.umich.edu
1067202Sgblack@eecs.umich.edufrom os import mkdir, environ
1077202Sgblack@eecs.umich.edufrom os.path import abspath, basename, dirname, expanduser, normpath
1087202Sgblack@eecs.umich.edufrom os.path import exists,  isdir, isfile
1097202Sgblack@eecs.umich.edufrom os.path import join as joinpath, split as splitpath
1107400SAli.Saidi@ARM.com
1117202Sgblack@eecs.umich.edu# SCons includes
1127400SAli.Saidi@ARM.comimport SCons
1137202Sgblack@eecs.umich.eduimport SCons.Node
1147797Sgblack@eecs.umich.edu
1157797Sgblack@eecs.umich.eduextra_python_paths = [
1167858SMatt.Horsnell@arm.com    Dir('src/python').srcnode().abspath, # gem5 includes
1177858SMatt.Horsnell@arm.com    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1187202Sgblack@eecs.umich.edu    ]
1197202Sgblack@eecs.umich.edu
1207202Sgblack@eecs.umich.edusys.path[1:1] = extra_python_paths
1217202Sgblack@eecs.umich.edu
1227599Sminkyu.jeong@arm.comfrom m5.util import compareVersions, readCommand
1237599Sminkyu.jeong@arm.comfrom m5.util.terminal import get_termcap
1247202Sgblack@eecs.umich.edu
1257202Sgblack@eecs.umich.eduhelp_texts = {
1267202Sgblack@eecs.umich.edu    "options" : "",
1277202Sgblack@eecs.umich.edu    "global_vars" : "",
1287202Sgblack@eecs.umich.edu    "local_vars" : ""
1297202Sgblack@eecs.umich.edu}
1307202Sgblack@eecs.umich.edu
1317599Sminkyu.jeong@arm.comExport("help_texts")
1327599Sminkyu.jeong@arm.com
1337202Sgblack@eecs.umich.edu
1347202Sgblack@eecs.umich.edu# There's a bug in scons in that (1) by default, the help texts from
1357202Sgblack@eecs.umich.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1367209Sgblack@eecs.umich.edu# and (2) you can override the help displayed by 'scons -h' using the
1377209Sgblack@eecs.umich.edu# Help() function, but these two features are incompatible: once
1387209Sgblack@eecs.umich.edu# you've overridden the help text using Help(), there's no way to get
1397209Sgblack@eecs.umich.edu# at the help texts from AddOptions.  See:
1407209Sgblack@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1417261Sgblack@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1427209Sgblack@eecs.umich.edu# This hack lets us extract the help text from AddOptions and
1437209Sgblack@eecs.umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1447261Sgblack@eecs.umich.edu# we can just use AddOption directly.
1457261Sgblack@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1467209Sgblack@eecs.umich.edu    col_width = 30
1477209Sgblack@eecs.umich.edu
1487209Sgblack@eecs.umich.edu    help = "  " + ", ".join(args)
1497209Sgblack@eecs.umich.edu    if "help" in kwargs:
1507209Sgblack@eecs.umich.edu        length = len(help)
1517209Sgblack@eecs.umich.edu        if length >= col_width:
1527209Sgblack@eecs.umich.edu            help += "\n" + " " * col_width
1537209Sgblack@eecs.umich.edu        else:
1547209Sgblack@eecs.umich.edu            help += " " * (col_width - length)
1557261Sgblack@eecs.umich.edu        help += kwargs["help"]
1567209Sgblack@eecs.umich.edu    help_texts["options"] += help + "\n"
1577209Sgblack@eecs.umich.edu
1587261Sgblack@eecs.umich.edu    AddOption(*args, **kwargs)
1597261Sgblack@eecs.umich.edu
1607209Sgblack@eecs.umich.eduAddLocalOption('--colors', dest='use_colors', action='store_true',
1617209Sgblack@eecs.umich.edu               help="Add color to abbreviated scons output")
1627209Sgblack@eecs.umich.eduAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1637209Sgblack@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1647209Sgblack@eecs.umich.eduAddLocalOption('--default', dest='default', type='string', action='store',
1657209Sgblack@eecs.umich.edu               help='Override which build_opts file to use for defaults')
1667261Sgblack@eecs.umich.eduAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1677209Sgblack@eecs.umich.edu               help='Disable style checking hooks')
1687209Sgblack@eecs.umich.eduAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1697261Sgblack@eecs.umich.edu               help='Disable Link-Time Optimization for fast')
1707261Sgblack@eecs.umich.eduAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1717209Sgblack@eecs.umich.edu               help='Update test reference outputs')
1727226Sgblack@eecs.umich.eduAddLocalOption('--verbose', dest='verbose', action='store_true',
1737249Sgblack@eecs.umich.edu               help='Print full tool command lines')
1747249Sgblack@eecs.umich.edu
1757249Sgblack@eecs.umich.edutermcap = get_termcap(GetOption('use_colors'))
1767249Sgblack@eecs.umich.edu
1777249Sgblack@eecs.umich.edu########################################################################
1787249Sgblack@eecs.umich.edu#
1797249Sgblack@eecs.umich.edu# Set up the main build environment.
1807249Sgblack@eecs.umich.edu#
1817249Sgblack@eecs.umich.edu########################################################################
1827249Sgblack@eecs.umich.eduuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
1837249Sgblack@eecs.umich.edu                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PYTHONPATH',
1847249Sgblack@eecs.umich.edu                 'RANLIB', 'SWIG' ])
1857249Sgblack@eecs.umich.edu
1867261Sgblack@eecs.umich.eduuse_prefixes = [
1877249Sgblack@eecs.umich.edu    "M5",           # M5 configuration (e.g., path to kernels)
1887249Sgblack@eecs.umich.edu    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
1897261Sgblack@eecs.umich.edu    "CCACHE_",      # ccache (caching compiler wrapper) configuration
1907261Sgblack@eecs.umich.edu    "CCC_",         # clang static analyzer configuration
1917249Sgblack@eecs.umich.edu    ]
1927249Sgblack@eecs.umich.edu
1937251Sgblack@eecs.umich.eduuse_env = {}
1947251Sgblack@eecs.umich.edufor key,val in os.environ.iteritems():
1957251Sgblack@eecs.umich.edu    if key in use_vars or \
1967261Sgblack@eecs.umich.edu            any([key.startswith(prefix) for prefix in use_prefixes]):
1977251Sgblack@eecs.umich.edu        use_env[key] = val
1987251Sgblack@eecs.umich.edu
1997261Sgblack@eecs.umich.edumain = Environment(ENV=use_env)
2007261Sgblack@eecs.umich.edumain.Decider('MD5-timestamp')
2017251Sgblack@eecs.umich.edumain.root = Dir(".")         # The current directory (where this file lives).
2027251Sgblack@eecs.umich.edumain.srcdir = Dir("src")     # The source directory
2037226Sgblack@eecs.umich.edu
2047226Sgblack@eecs.umich.edumain_dict_keys = main.Dictionary().keys()
2057226Sgblack@eecs.umich.edu
2067232Sgblack@eecs.umich.edu# Check that we have a C/C++ compiler
2077226Sgblack@eecs.umich.eduif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2087226Sgblack@eecs.umich.edu    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2097226Sgblack@eecs.umich.edu    Exit(1)
2107226Sgblack@eecs.umich.edu
2117226Sgblack@eecs.umich.edu# Check that swig is present
2127232Sgblack@eecs.umich.eduif not 'SWIG' in main_dict_keys:
2137226Sgblack@eecs.umich.edu    print "swig is not installed (package swig on Ubuntu and RedHat)"
2147422Sgblack@eecs.umich.edu    Exit(1)
2157232Sgblack@eecs.umich.edu
2167232Sgblack@eecs.umich.edu# add useful python code PYTHONPATH so it can be used by subprocesses
2177226Sgblack@eecs.umich.edu# as well
2187226Sgblack@eecs.umich.edumain.AppendENVPath('PYTHONPATH', extra_python_paths)
2197226Sgblack@eecs.umich.edu
2207226Sgblack@eecs.umich.edu########################################################################
2217226Sgblack@eecs.umich.edu#
2227232Sgblack@eecs.umich.edu# Mercurial Stuff.
2237226Sgblack@eecs.umich.edu#
2247226Sgblack@eecs.umich.edu# If the gem5 directory is a mercurial repository, we should do some
2257226Sgblack@eecs.umich.edu# extra things.
2267226Sgblack@eecs.umich.edu#
2277226Sgblack@eecs.umich.edu########################################################################
2287232Sgblack@eecs.umich.edu
2297226Sgblack@eecs.umich.eduhgdir = main.root.Dir(".hg")
2307422Sgblack@eecs.umich.edu
2317232Sgblack@eecs.umich.edumercurial_style_message = """
2327232Sgblack@eecs.umich.eduYou're missing the gem5 style hook, which automatically checks your code
2337226Sgblack@eecs.umich.eduagainst the gem5 style rules on hg commit and qrefresh commands.  This
2347226Sgblack@eecs.umich.eduscript will now install the hook in your .hg/hgrc file.
2357226Sgblack@eecs.umich.eduPress enter to continue, or ctrl-c to abort: """
2367226Sgblack@eecs.umich.edu
2377226Sgblack@eecs.umich.edumercurial_style_hook = """
2387226Sgblack@eecs.umich.edu# The following lines were automatically added by gem5/SConstruct
2397226Sgblack@eecs.umich.edu# to provide the gem5 style-checking hooks
2407226Sgblack@eecs.umich.edu[extensions]
2417232Sgblack@eecs.umich.edustyle = %s/util/style.py
2427226Sgblack@eecs.umich.edu
2437226Sgblack@eecs.umich.edu[hooks]
2447232Sgblack@eecs.umich.edupretxncommit.style = python:style.check_style
2457226Sgblack@eecs.umich.edupre-qrefresh.style = python:style.check_style
2467226Sgblack@eecs.umich.edu# End of SConstruct additions
2477226Sgblack@eecs.umich.edu
2487226Sgblack@eecs.umich.edu""" % (main.root.abspath)
2497232Sgblack@eecs.umich.edu
2507226Sgblack@eecs.umich.edumercurial_lib_not_found = """
2517422Sgblack@eecs.umich.eduMercurial libraries cannot be found, ignoring style hook.  If
2527232Sgblack@eecs.umich.eduyou are a gem5 developer, please fix this and run the style
2537232Sgblack@eecs.umich.eduhook. It is important.
2547226Sgblack@eecs.umich.edu"""
2557226Sgblack@eecs.umich.edu
2567226Sgblack@eecs.umich.edu# Check for style hook and prompt for installation if it's not there.
2577226Sgblack@eecs.umich.edu# Skip this if --ignore-style was specified, there's no .hg dir to
2587226Sgblack@eecs.umich.edu# install a hook in, or there's no interactive terminal to prompt.
2597226Sgblack@eecs.umich.eduif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2607226Sgblack@eecs.umich.edu    style_hook = True
2617226Sgblack@eecs.umich.edu    try:
2627232Sgblack@eecs.umich.edu        from mercurial import ui
2637226Sgblack@eecs.umich.edu        ui = ui.ui()
2647226Sgblack@eecs.umich.edu        ui.readconfig(hgdir.File('hgrc').abspath)
2657232Sgblack@eecs.umich.edu        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2667226Sgblack@eecs.umich.edu                     ui.config('hooks', 'pre-qrefresh.style', None)
2677226Sgblack@eecs.umich.edu    except ImportError:
2687226Sgblack@eecs.umich.edu        print mercurial_lib_not_found
2697226Sgblack@eecs.umich.edu
2707232Sgblack@eecs.umich.edu    if not style_hook:
2717226Sgblack@eecs.umich.edu        print mercurial_style_message,
2727422Sgblack@eecs.umich.edu        # continue unless user does ctrl-c/ctrl-d etc.
2737232Sgblack@eecs.umich.edu        try:
2747232Sgblack@eecs.umich.edu            raw_input()
2757226Sgblack@eecs.umich.edu        except:
2767234Sgblack@eecs.umich.edu            print "Input exception, exiting scons.\n"
2777234Sgblack@eecs.umich.edu            sys.exit(1)
2787234Sgblack@eecs.umich.edu        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
2797234Sgblack@eecs.umich.edu        print "Adding style hook to", hgrc_path, "\n"
2807234Sgblack@eecs.umich.edu        try:
2817234Sgblack@eecs.umich.edu            hgrc = open(hgrc_path, 'a')
2827234Sgblack@eecs.umich.edu            hgrc.write(mercurial_style_hook)
2837234Sgblack@eecs.umich.edu            hgrc.close()
2847234Sgblack@eecs.umich.edu        except:
2857234Sgblack@eecs.umich.edu            print "Error updating", hgrc_path
2867234Sgblack@eecs.umich.edu            sys.exit(1)
2877234Sgblack@eecs.umich.edu
2887234Sgblack@eecs.umich.edu
2897234Sgblack@eecs.umich.edu###################################################
2907234Sgblack@eecs.umich.edu#
2917234Sgblack@eecs.umich.edu# Figure out which configurations to set up based on the path(s) of
2927234Sgblack@eecs.umich.edu# the target(s).
2937234Sgblack@eecs.umich.edu#
2947234Sgblack@eecs.umich.edu###################################################
2957234Sgblack@eecs.umich.edu
2967234Sgblack@eecs.umich.edu# Find default configuration & binary.
2977234Sgblack@eecs.umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
2987234Sgblack@eecs.umich.edu
2997234Sgblack@eecs.umich.edu# helper function: find last occurrence of element in list
3007234Sgblack@eecs.umich.edudef rfind(l, elt, offs = -1):
3017234Sgblack@eecs.umich.edu    for i in range(len(l)+offs, 0, -1):
3027234Sgblack@eecs.umich.edu        if l[i] == elt:
3037234Sgblack@eecs.umich.edu            return i
3047234Sgblack@eecs.umich.edu    raise ValueError, "element not found"
3057234Sgblack@eecs.umich.edu
3067234Sgblack@eecs.umich.edu# Take a list of paths (or SCons Nodes) and return a list with all
3077234Sgblack@eecs.umich.edu# paths made absolute and ~-expanded.  Paths will be interpreted
3087234Sgblack@eecs.umich.edu# relative to the launch directory unless a different root is provided
3097234Sgblack@eecs.umich.edudef makePathListAbsolute(path_list, root=GetLaunchDir()):
3107234Sgblack@eecs.umich.edu    return [abspath(joinpath(root, expanduser(str(p))))
3117234Sgblack@eecs.umich.edu            for p in path_list]
3127234Sgblack@eecs.umich.edu
3137234Sgblack@eecs.umich.edu# Each target must have 'build' in the interior of the path; the
3147234Sgblack@eecs.umich.edu# directory below this will determine the build parameters.  For
3157234Sgblack@eecs.umich.edu# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3167234Sgblack@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
3177234Sgblack@eecs.umich.edu# follow 'build' in the build path.
3187234Sgblack@eecs.umich.edu
3197234Sgblack@eecs.umich.edu# The funky assignment to "[:]" is needed to replace the list contents
3207234Sgblack@eecs.umich.edu# in place rather than reassign the symbol to a new list, which
3217234Sgblack@eecs.umich.edu# doesn't work (obviously!).
3227234Sgblack@eecs.umich.eduBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3237234Sgblack@eecs.umich.edu
3247234Sgblack@eecs.umich.edu# Generate a list of the unique build roots and configs that the
3257234Sgblack@eecs.umich.edu# collected targets reference.
3267234Sgblack@eecs.umich.eduvariant_paths = []
3277234Sgblack@eecs.umich.edubuild_root = None
3287234Sgblack@eecs.umich.edufor t in BUILD_TARGETS:
3297234Sgblack@eecs.umich.edu    path_dirs = t.split('/')
3307234Sgblack@eecs.umich.edu    try:
3317234Sgblack@eecs.umich.edu        build_top = rfind(path_dirs, 'build', -2)
3327234Sgblack@eecs.umich.edu    except:
3337234Sgblack@eecs.umich.edu        print "Error: no non-leaf 'build' dir found on target path", t
3347234Sgblack@eecs.umich.edu        Exit(1)
3357234Sgblack@eecs.umich.edu    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3367234Sgblack@eecs.umich.edu    if not build_root:
3377234Sgblack@eecs.umich.edu        build_root = this_build_root
3387234Sgblack@eecs.umich.edu    else:
3397234Sgblack@eecs.umich.edu        if this_build_root != build_root:
3407234Sgblack@eecs.umich.edu            print "Error: build targets not under same build root\n"\
3417234Sgblack@eecs.umich.edu                  "  %s\n  %s" % (build_root, this_build_root)
3427234Sgblack@eecs.umich.edu            Exit(1)
3437234Sgblack@eecs.umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
3447234Sgblack@eecs.umich.edu    if variant_path not in variant_paths:
3457234Sgblack@eecs.umich.edu        variant_paths.append(variant_path)
3467234Sgblack@eecs.umich.edu
3477234Sgblack@eecs.umich.edu# Make sure build_root exists (might not if this is the first build there)
3487234Sgblack@eecs.umich.eduif not isdir(build_root):
3497234Sgblack@eecs.umich.edu    mkdir(build_root)
3507234Sgblack@eecs.umich.edumain['BUILDROOT'] = build_root
3517234Sgblack@eecs.umich.edu
3527234Sgblack@eecs.umich.eduExport('main')
3537234Sgblack@eecs.umich.edu
3547234Sgblack@eecs.umich.edumain.SConsignFile(joinpath(build_root, "sconsign"))
3557234Sgblack@eecs.umich.edu
3567234Sgblack@eecs.umich.edu# Default duplicate option is to use hard links, but this messes up
3577234Sgblack@eecs.umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
3587234Sgblack@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
3597234Sgblack@eecs.umich.edu# (soft) links work better.
3607234Sgblack@eecs.umich.edumain.SetOption('duplicate', 'soft-copy')
3617234Sgblack@eecs.umich.edu
3627234Sgblack@eecs.umich.edu#
3637234Sgblack@eecs.umich.edu# Set up global sticky variables... these are common to an entire build
3647234Sgblack@eecs.umich.edu# tree (not specific to a particular build like ALPHA_SE)
3657234Sgblack@eecs.umich.edu#
3667234Sgblack@eecs.umich.edu
3677234Sgblack@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
3687234Sgblack@eecs.umich.edu
3697234Sgblack@eecs.umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3707234Sgblack@eecs.umich.edu
3717234Sgblack@eecs.umich.eduglobal_vars.AddVariables(
3727234Sgblack@eecs.umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3737234Sgblack@eecs.umich.edu    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3747234Sgblack@eecs.umich.edu    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
3757234Sgblack@eecs.umich.edu    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
3767234Sgblack@eecs.umich.edu    ('BATCH', 'Use batch pool for build and tests', False),
3777234Sgblack@eecs.umich.edu    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3787234Sgblack@eecs.umich.edu    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
3797234Sgblack@eecs.umich.edu    ('EXTRAS', 'Add extra directories to the compilation', '')
3807234Sgblack@eecs.umich.edu    )
3817234Sgblack@eecs.umich.edu
3827234Sgblack@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
3837234Sgblack@eecs.umich.eduglobal_vars.Update(main)
3847234Sgblack@eecs.umich.eduhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3857234Sgblack@eecs.umich.edu
3867234Sgblack@eecs.umich.edu# Save sticky variable settings back to current variables file
3877234Sgblack@eecs.umich.eduglobal_vars.Save(global_vars_file, main)
3887234Sgblack@eecs.umich.edu
3897234Sgblack@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
3907234Sgblack@eecs.umich.edu# look for sources etc.  This list is exported as extras_dir_list.
3917234Sgblack@eecs.umich.edubase_dir = main.srcdir.abspath
3927234Sgblack@eecs.umich.eduif main['EXTRAS']:
3937234Sgblack@eecs.umich.edu    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
3947234Sgblack@eecs.umich.eduelse:
3957234Sgblack@eecs.umich.edu    extras_dir_list = []
3967234Sgblack@eecs.umich.edu
3977234Sgblack@eecs.umich.eduExport('base_dir')
3987234Sgblack@eecs.umich.eduExport('extras_dir_list')
3997234Sgblack@eecs.umich.edu
4007234Sgblack@eecs.umich.edu# the ext directory should be on the #includes path
4017234Sgblack@eecs.umich.edumain.Append(CPPPATH=[Dir('ext')])
4027234Sgblack@eecs.umich.edu
4037234Sgblack@eecs.umich.edudef strip_build_path(path, env):
4047234Sgblack@eecs.umich.edu    path = str(path)
4057234Sgblack@eecs.umich.edu    variant_base = env['BUILDROOT'] + os.path.sep
4067234Sgblack@eecs.umich.edu    if path.startswith(variant_base):
4077234Sgblack@eecs.umich.edu        path = path[len(variant_base):]
4087234Sgblack@eecs.umich.edu    elif path.startswith('build/'):
4097234Sgblack@eecs.umich.edu        path = path[6:]
4107234Sgblack@eecs.umich.edu    return path
4117234Sgblack@eecs.umich.edu
4127234Sgblack@eecs.umich.edu# Generate a string of the form:
4137234Sgblack@eecs.umich.edu#   common/path/prefix/src1, src2 -> tgt1, tgt2
4147234Sgblack@eecs.umich.edu# to print while building.
4157234Sgblack@eecs.umich.educlass Transform(object):
4167234Sgblack@eecs.umich.edu    # all specific color settings should be here and nowhere else
4177234Sgblack@eecs.umich.edu    tool_color = termcap.Normal
4187239Sgblack@eecs.umich.edu    pfx_color = termcap.Yellow
4197239Sgblack@eecs.umich.edu    srcs_color = termcap.Yellow + termcap.Bold
4207239Sgblack@eecs.umich.edu    arrow_color = termcap.Blue + termcap.Bold
4217239Sgblack@eecs.umich.edu    tgts_color = termcap.Yellow + termcap.Bold
4227239Sgblack@eecs.umich.edu
4237239Sgblack@eecs.umich.edu    def __init__(self, tool, max_sources=99):
4247239Sgblack@eecs.umich.edu        self.format = self.tool_color + (" [%8s] " % tool) \
4257239Sgblack@eecs.umich.edu                      + self.pfx_color + "%s" \
4267239Sgblack@eecs.umich.edu                      + self.srcs_color + "%s" \
4277239Sgblack@eecs.umich.edu                      + self.arrow_color + " -> " \
4287239Sgblack@eecs.umich.edu                      + self.tgts_color + "%s" \
4297239Sgblack@eecs.umich.edu                      + termcap.Normal
4307239Sgblack@eecs.umich.edu        self.max_sources = max_sources
4317239Sgblack@eecs.umich.edu
4327422Sgblack@eecs.umich.edu    def __call__(self, target, source, env, for_signature=None):
4337239Sgblack@eecs.umich.edu        # truncate source list according to max_sources param
4347239Sgblack@eecs.umich.edu        source = source[0:self.max_sources]
4357239Sgblack@eecs.umich.edu        def strip(f):
4367242Sgblack@eecs.umich.edu            return strip_build_path(str(f), env)
4377242Sgblack@eecs.umich.edu        if len(source) > 0:
4387242Sgblack@eecs.umich.edu            srcs = map(strip, source)
4397242Sgblack@eecs.umich.edu        else:
4407242Sgblack@eecs.umich.edu            srcs = ['']
4417242Sgblack@eecs.umich.edu        tgts = map(strip, target)
4427242Sgblack@eecs.umich.edu        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4437242Sgblack@eecs.umich.edu        # operation that has nothing to do with paths.
4447242Sgblack@eecs.umich.edu        com_pfx = os.path.commonprefix(srcs + tgts)
4457242Sgblack@eecs.umich.edu        com_pfx_len = len(com_pfx)
4467242Sgblack@eecs.umich.edu        if com_pfx:
4477242Sgblack@eecs.umich.edu            # do some cleanup and sanity checking on common prefix
4487242Sgblack@eecs.umich.edu            if com_pfx[-1] == ".":
4497242Sgblack@eecs.umich.edu                # prefix matches all but file extension: ok
4507242Sgblack@eecs.umich.edu                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4517242Sgblack@eecs.umich.edu                com_pfx = com_pfx[0:-1]
4527242Sgblack@eecs.umich.edu            elif com_pfx[-1] == "/":
4537242Sgblack@eecs.umich.edu                # common prefix is directory path: OK
4547242Sgblack@eecs.umich.edu                pass
4557242Sgblack@eecs.umich.edu            else:
4567242Sgblack@eecs.umich.edu                src0_len = len(srcs[0])
4577242Sgblack@eecs.umich.edu                tgt0_len = len(tgts[0])
4587242Sgblack@eecs.umich.edu                if src0_len == com_pfx_len:
4597242Sgblack@eecs.umich.edu                    # source is a substring of target, OK
4607242Sgblack@eecs.umich.edu                    pass
4617242Sgblack@eecs.umich.edu                elif tgt0_len == com_pfx_len:
4627242Sgblack@eecs.umich.edu                    # target is a substring of source, need to back up to
4637242Sgblack@eecs.umich.edu                    # avoid empty string on RHS of arrow
4647242Sgblack@eecs.umich.edu                    sep_idx = com_pfx.rfind(".")
4657242Sgblack@eecs.umich.edu                    if sep_idx != -1:
4667242Sgblack@eecs.umich.edu                        com_pfx = com_pfx[0:sep_idx]
4677242Sgblack@eecs.umich.edu                    else:
4687242Sgblack@eecs.umich.edu                        com_pfx = ''
4697242Sgblack@eecs.umich.edu                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4707242Sgblack@eecs.umich.edu                    # still splitting at file extension: ok
4717242Sgblack@eecs.umich.edu                    pass
4727247Sgblack@eecs.umich.edu                else:
4737797Sgblack@eecs.umich.edu                    # probably a fluke; ignore it
4747848SAli.Saidi@ARM.com                    com_pfx = ''
4757410Sgblack@eecs.umich.edu        # recalculate length in case com_pfx was modified
4767410Sgblack@eecs.umich.edu        com_pfx_len = len(com_pfx)
4777410Sgblack@eecs.umich.edu        def fmt(files):
4787410Sgblack@eecs.umich.edu            f = map(lambda s: s[com_pfx_len:], files)
4797408Sgblack@eecs.umich.edu            return ', '.join(f)
4807408Sgblack@eecs.umich.edu        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
4817247Sgblack@eecs.umich.edu
4827247Sgblack@eecs.umich.eduExport('Transform')
4837408Sgblack@eecs.umich.edu
4847408Sgblack@eecs.umich.edu# enable the regression script to use the termcap
4857418Sgblack@eecs.umich.edumain['TERMCAP'] = termcap
4867418Sgblack@eecs.umich.edu
4877418Sgblack@eecs.umich.eduif GetOption('verbose'):
4887418Sgblack@eecs.umich.edu    def MakeAction(action, string, *args, **kwargs):
4897418Sgblack@eecs.umich.edu        return Action(action, *args, **kwargs)
4907418Sgblack@eecs.umich.eduelse:
4917418Sgblack@eecs.umich.edu    MakeAction = Action
4927418Sgblack@eecs.umich.edu    main['CCCOMSTR']        = Transform("CC")
4937418Sgblack@eecs.umich.edu    main['CXXCOMSTR']       = Transform("CXX")
4947418Sgblack@eecs.umich.edu    main['ASCOMSTR']        = Transform("AS")
4957418Sgblack@eecs.umich.edu    main['SWIGCOMSTR']      = Transform("SWIG")
4967418Sgblack@eecs.umich.edu    main['ARCOMSTR']        = Transform("AR", 0)
4977418Sgblack@eecs.umich.edu    main['LINKCOMSTR']      = Transform("LINK", 0)
4987418Sgblack@eecs.umich.edu    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
4997418Sgblack@eecs.umich.edu    main['M4COMSTR']        = Transform("M4")
5007418Sgblack@eecs.umich.edu    main['SHCCCOMSTR']      = Transform("SHCC")
5017648SAli.Saidi@ARM.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
5027418Sgblack@eecs.umich.eduExport('MakeAction')
5037418Sgblack@eecs.umich.edu
5047418Sgblack@eecs.umich.edu# Initialize the Link-Time Optimization (LTO) flags
5057418Sgblack@eecs.umich.edumain['LTO_CCFLAGS'] = []
5067418Sgblack@eecs.umich.edumain['LTO_LDFLAGS'] = []
5077418Sgblack@eecs.umich.edu
5087418Sgblack@eecs.umich.edu# According to the readme, tcmalloc works best if the compiler doesn't
5097418Sgblack@eecs.umich.edu# assume that we're using the builtin malloc and friends. These flags
5107418Sgblack@eecs.umich.edu# are compiler-specific, so we need to set them after we detect which
5117418Sgblack@eecs.umich.edu# compiler we're using.
5127418Sgblack@eecs.umich.edumain['TCMALLOC_CCFLAGS'] = []
5137418Sgblack@eecs.umich.edu
5147418Sgblack@eecs.umich.eduCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5157418Sgblack@eecs.umich.eduCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5167418Sgblack@eecs.umich.edu
5177418Sgblack@eecs.umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5187418Sgblack@eecs.umich.edumain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5197418Sgblack@eecs.umich.eduif main['GCC'] + main['CLANG'] > 1:
5207418Sgblack@eecs.umich.edu    print 'Error: How can we have two at the same time?'
5217418Sgblack@eecs.umich.edu    Exit(1)
5227418Sgblack@eecs.umich.edu
5237418Sgblack@eecs.umich.edu# Set up default C++ compiler flags
5247418Sgblack@eecs.umich.eduif main['GCC'] or main['CLANG']:
5257418Sgblack@eecs.umich.edu    # As gcc and clang share many flags, do the common parts here
5267418Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-pipe'])
5277418Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5287648SAli.Saidi@ARM.com    # Enable -Wall and then disable the few warnings that we
5297418Sgblack@eecs.umich.edu    # consistently violate
5307418Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5317418Sgblack@eecs.umich.edu    # We always compile using C++11, but only gcc >= 4.7 and clang 3.1
5327418Sgblack@eecs.umich.edu    # actually use that name, so we stick with c++0x
5337408Sgblack@eecs.umich.edu    main.Append(CXXFLAGS=['-std=c++0x'])
5347408Sgblack@eecs.umich.edu    # Add selected sanity checks from -Wextra
5357648SAli.Saidi@ARM.com    main.Append(CXXFLAGS=['-Wmissing-field-initializers',
5367648SAli.Saidi@ARM.com                          '-Woverloaded-virtual'])
5377408Sgblack@eecs.umich.eduelse:
5387408Sgblack@eecs.umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5397408Sgblack@eecs.umich.edu    print "Don't know what compiler options to use for your compiler."
5407409Sgblack@eecs.umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5417409Sgblack@eecs.umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
5427409Sgblack@eecs.umich.edu    if not CXX_version:
5437409Sgblack@eecs.umich.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5447409Sgblack@eecs.umich.edu               termcap.Normal
5457409Sgblack@eecs.umich.edu    else:
5467409Sgblack@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
5477409Sgblack@eecs.umich.edu    print "       If you're trying to use a compiler other than GCC"
5487409Sgblack@eecs.umich.edu    print "       or clang, there appears to be something wrong with your"
5497409Sgblack@eecs.umich.edu    print "       environment."
5507409Sgblack@eecs.umich.edu    print "       "
5517409Sgblack@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
5527409Sgblack@eecs.umich.edu    print "       above you will need to ease fix SConstruct and "
5537254Sgblack@eecs.umich.edu    print "       src/SConscript to support that compiler."
5547254Sgblack@eecs.umich.edu    Exit(1)
5557254Sgblack@eecs.umich.edu
5567254Sgblack@eecs.umich.eduif main['GCC']:
5577254Sgblack@eecs.umich.edu    # Check for a supported version of gcc, >= 4.4 is needed for c++0x
5587254Sgblack@eecs.umich.edu    # support. See http://gcc.gnu.org/projects/cxx0x.html for details
5597254Sgblack@eecs.umich.edu    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5607254Sgblack@eecs.umich.edu    if compareVersions(gcc_version, "4.4") < 0:
5617254Sgblack@eecs.umich.edu        print 'Error: gcc version 4.4 or newer required.'
5627254Sgblack@eecs.umich.edu        print '       Installed version:', gcc_version
5637254Sgblack@eecs.umich.edu        Exit(1)
5647254Sgblack@eecs.umich.edu
5657254Sgblack@eecs.umich.edu    main['GCC_VERSION'] = gcc_version
5667254Sgblack@eecs.umich.edu
5677254Sgblack@eecs.umich.edu    # Check for versions with bugs
5687254Sgblack@eecs.umich.edu    if not compareVersions(gcc_version, '4.4.1') or \
5697254Sgblack@eecs.umich.edu       not compareVersions(gcc_version, '4.4.2'):
5707254Sgblack@eecs.umich.edu        print 'Info: Tree vectorizer in GCC 4.4.1 & 4.4.2 is buggy, disabling.'
5717254Sgblack@eecs.umich.edu        main.Append(CCFLAGS=['-fno-tree-vectorize'])
5727254Sgblack@eecs.umich.edu
5737254Sgblack@eecs.umich.edu    # LTO support is only really working properly from 4.6 and beyond
5747257Sgblack@eecs.umich.edu    if compareVersions(gcc_version, '4.6') >= 0:
5757257Sgblack@eecs.umich.edu        # Add the appropriate Link-Time Optimization (LTO) flags
5767257Sgblack@eecs.umich.edu        # unless LTO is explicitly turned off. Note that these flags
5777257Sgblack@eecs.umich.edu        # are only used by the fast target.
5787257Sgblack@eecs.umich.edu        if not GetOption('no_lto'):
5797257Sgblack@eecs.umich.edu            # Pass the LTO flag when compiling to produce GIMPLE
5807257Sgblack@eecs.umich.edu            # output, we merely create the flags here and only append
5817257Sgblack@eecs.umich.edu            # them later/
5827257Sgblack@eecs.umich.edu            main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
5837257Sgblack@eecs.umich.edu
5847257Sgblack@eecs.umich.edu            # Use the same amount of jobs for LTO as we are running
5857257Sgblack@eecs.umich.edu            # scons with, we hardcode the use of the linker plugin
5867257Sgblack@eecs.umich.edu            # which requires either gold or GNU ld >= 2.21
5877257Sgblack@eecs.umich.edu            main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs'),
5887257Sgblack@eecs.umich.edu                                   '-fuse-linker-plugin']
5897257Sgblack@eecs.umich.edu
5907257Sgblack@eecs.umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
5917257Sgblack@eecs.umich.edu                                  '-fno-builtin-realloc', '-fno-builtin-free'])
5927257Sgblack@eecs.umich.edu
5937257Sgblack@eecs.umich.eduelif main['CLANG']:
5947257Sgblack@eecs.umich.edu    # Check for a supported version of clang, >= 2.9 is needed to
5957262Sgblack@eecs.umich.edu    # support similar features as gcc 4.4. See
5967347SAli.Saidi@ARM.com    # http://clang.llvm.org/cxx_status.html for details
5977347SAli.Saidi@ARM.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
5987347SAli.Saidi@ARM.com    clang_version_match = clang_version_re.match(CXX_version)
5997347SAli.Saidi@ARM.com    if (clang_version_match):
6007347SAli.Saidi@ARM.com        clang_version = clang_version_match.groups()[0]
6017347SAli.Saidi@ARM.com        if compareVersions(clang_version, "2.9") < 0:
6027347SAli.Saidi@ARM.com            print 'Error: clang version 2.9 or newer required.'
6037347SAli.Saidi@ARM.com            print '       Installed version:', clang_version
6047347SAli.Saidi@ARM.com            Exit(1)
6057347SAli.Saidi@ARM.com    else:
6067347SAli.Saidi@ARM.com        print 'Error: Unable to determine clang version.'
6077262Sgblack@eecs.umich.edu        Exit(1)
6087347SAli.Saidi@ARM.com
6097262Sgblack@eecs.umich.edu    # clang has a few additional warnings that we disable,
6107262Sgblack@eecs.umich.edu    # tautological comparisons are allowed due to unsigned integers
6117262Sgblack@eecs.umich.edu    # being compared to constants that happen to be 0, and extraneous
6127262Sgblack@eecs.umich.edu    # parantheses are allowed due to Ruby's printing of the AST,
6137262Sgblack@eecs.umich.edu    # finally self assignments are allowed as the generated CPU code
6147347SAli.Saidi@ARM.com    # is relying on this
6157347SAli.Saidi@ARM.com    main.Append(CCFLAGS=['-Wno-tautological-compare',
6167347SAli.Saidi@ARM.com                         '-Wno-parentheses',
6177347SAli.Saidi@ARM.com                         '-Wno-self-assign'])
6187347SAli.Saidi@ARM.com
6197347SAli.Saidi@ARM.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
6207347SAli.Saidi@ARM.com
6217347SAli.Saidi@ARM.com    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
6227347SAli.Saidi@ARM.com    # opposed to libstdc++ to make the transition from TR1 to
6237347SAli.Saidi@ARM.com    # C++11. See http://libcxx.llvm.org. However, clang has chosen a
6247347SAli.Saidi@ARM.com    # strict implementation of the C++11 standard, and does not allow
6257262Sgblack@eecs.umich.edu    # incomplete types in template arguments (besides unique_ptr and
6267347SAli.Saidi@ARM.com    # shared_ptr), and the libc++ STL containers create problems in
6277599Sminkyu.jeong@arm.com    # combination with the current gem5 code. For now, we stick with
6287599Sminkyu.jeong@arm.com    # libstdc++ and use the TR1 namespace.
6297262Sgblack@eecs.umich.edu    # if sys.platform == "darwin":
6307262Sgblack@eecs.umich.edu    #     main.Append(CXXFLAGS=['-stdlib=libc++'])
6317262Sgblack@eecs.umich.edu
6327283Sgblack@eecs.umich.eduelse:
6337420Sgblack@eecs.umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6347420Sgblack@eecs.umich.edu    print "Don't know what compiler options to use for your compiler."
6357420Sgblack@eecs.umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6367420Sgblack@eecs.umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
6377420Sgblack@eecs.umich.edu    if not CXX_version:
6387420Sgblack@eecs.umich.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6397420Sgblack@eecs.umich.edu               termcap.Normal
6407420Sgblack@eecs.umich.edu    else:
6417420Sgblack@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
6427599Sminkyu.jeong@arm.com    print "       If you're trying to use a compiler other than GCC"
6437599Sminkyu.jeong@arm.com    print "       or clang, there appears to be something wrong with your"
6447420Sgblack@eecs.umich.edu    print "       environment."
6457420Sgblack@eecs.umich.edu    print "       "
6467420Sgblack@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
6477420Sgblack@eecs.umich.edu    print "       above you will need to ease fix SConstruct and "
6487283Sgblack@eecs.umich.edu    print "       src/SConscript to support that compiler."
6497797Sgblack@eecs.umich.edu    Exit(1)
6507797Sgblack@eecs.umich.edu
6517283Sgblack@eecs.umich.edu# Set up common yacc/bison flags (needed for Ruby)
6527283Sgblack@eecs.umich.edumain['YACCFLAGS'] = '-d'
6537283Sgblack@eecs.umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
6547283Sgblack@eecs.umich.edu
6557283Sgblack@eecs.umich.edu# Do this after we save setting back, or else we'll tack on an
6567283Sgblack@eecs.umich.edu# extra 'qdo' every time we run scons.
6577283Sgblack@eecs.umich.eduif main['BATCH']:
6587283Sgblack@eecs.umich.edu    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
6597283Sgblack@eecs.umich.edu    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
6607797Sgblack@eecs.umich.edu    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
6617797Sgblack@eecs.umich.edu    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
6627283Sgblack@eecs.umich.edu    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
6637283Sgblack@eecs.umich.edu
6647283Sgblack@eecs.umich.eduif sys.platform == 'cygwin':
6657283Sgblack@eecs.umich.edu    # cygwin has some header file issues...
6667283Sgblack@eecs.umich.edu    main.Append(CCFLAGS=["-Wno-uninitialized"])
6677283Sgblack@eecs.umich.edu
6687283Sgblack@eecs.umich.edu# Check for the protobuf compiler
6697307Sgblack@eecs.umich.eduprotoc_version = readCommand([main['PROTOC'], '--version'],
6707307Sgblack@eecs.umich.edu                             exception='').split()
6717307Sgblack@eecs.umich.edu
6727307Sgblack@eecs.umich.edu# First two words should be "libprotoc x.y.z"
6737307Sgblack@eecs.umich.eduif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6747307Sgblack@eecs.umich.edu    print termcap.Yellow + termcap.Bold + \
6757307Sgblack@eecs.umich.edu        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
6767307Sgblack@eecs.umich.edu        '         Please install protobuf-compiler for tracing support.' + \
6777648SAli.Saidi@ARM.com        termcap.Normal
6787648SAli.Saidi@ARM.com    main['PROTOC'] = False
6797307Sgblack@eecs.umich.eduelse:
6807307Sgblack@eecs.umich.edu    # Based on the availability of the compress stream wrappers,
6817307Sgblack@eecs.umich.edu    # require 2.1.0
6827315Sgblack@eecs.umich.edu    min_protoc_version = '2.1.0'
6837603SGene.Wu@arm.com    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6847705Sgblack@eecs.umich.edu        print termcap.Yellow + termcap.Bold + \
6857705Sgblack@eecs.umich.edu            'Warning: protoc version', min_protoc_version, \
6867603SGene.Wu@arm.com            'or newer required.\n' + \
6877603SGene.Wu@arm.com            '         Installed version:', protoc_version[1], \
6887603SGene.Wu@arm.com            termcap.Normal
6897603SGene.Wu@arm.com        main['PROTOC'] = False
6907603SGene.Wu@arm.com    else:
6917609SGene.Wu@arm.com        # Attempt to determine the appropriate include path and
6927603SGene.Wu@arm.com        # library path using pkg-config, that means we also need to
6937603SGene.Wu@arm.com        # check for pkg-config. Note that it is possible to use
6947609SGene.Wu@arm.com        # protobuf without the involvement of pkg-config. Later on we
6957609SGene.Wu@arm.com        # check go a library config check and at that point the test
6967603SGene.Wu@arm.com        # will fail if libprotobuf cannot be found.
6977605SGene.Wu@arm.com        if readCommand(['pkg-config', '--version'], exception=''):
6987605SGene.Wu@arm.com            try:
6997605SGene.Wu@arm.com                # Attempt to establish what linking flags to add for protobuf
7007605SGene.Wu@arm.com                # using pkg-config
7017605SGene.Wu@arm.com                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
7027605SGene.Wu@arm.com            except:
7037605SGene.Wu@arm.com                print termcap.Yellow + termcap.Bold + \
7047605SGene.Wu@arm.com                    'Warning: pkg-config could not get protobuf flags.' + \
7057605SGene.Wu@arm.com                    termcap.Normal
7067605SGene.Wu@arm.com
7077605SGene.Wu@arm.com# Check for SWIG
7087605SGene.Wu@arm.comif not main.has_key('SWIG'):
7097605SGene.Wu@arm.com    print 'Error: SWIG utility not found.'
7107605SGene.Wu@arm.com    print '       Please install (see http://www.swig.org) and retry.'
7117605SGene.Wu@arm.com    Exit(1)
7127605SGene.Wu@arm.com
7137605SGene.Wu@arm.com# Check for appropriate SWIG version
7147605SGene.Wu@arm.comswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
7157605SGene.Wu@arm.com# First 3 words should be "SWIG Version x.y.z"
7167605SGene.Wu@arm.comif len(swig_version) < 3 or \
7177605SGene.Wu@arm.com        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
7187605SGene.Wu@arm.com    print 'Error determining SWIG version.'
7197605SGene.Wu@arm.com    Exit(1)
7207605SGene.Wu@arm.com
7217605SGene.Wu@arm.commin_swig_version = '1.3.34'
7227605SGene.Wu@arm.comif compareVersions(swig_version[2], min_swig_version) < 0:
7237605SGene.Wu@arm.com    print 'Error: SWIG version', min_swig_version, 'or newer required.'
7247613SGene.Wu@arm.com    print '       Installed version:', swig_version[2]
7257613SGene.Wu@arm.com    Exit(1)
7267613SGene.Wu@arm.com
7277613SGene.Wu@arm.comif swig_version[2] == "2.0.9":
7287613SGene.Wu@arm.com    print '\n' + termcap.Yellow + termcap.Bold + \
7297613SGene.Wu@arm.com        'Warning: SWIG version 2.0.9 sometimes generates broken code.\n' + \
7307613SGene.Wu@arm.com        termcap.Normal + \
7317613SGene.Wu@arm.com        'This problem only affects some platforms and some Python\n' + \
7327613SGene.Wu@arm.com        'versions. See the following SWIG bug report for details:\n' + \
7337315Sgblack@eecs.umich.edu        'http://sourceforge.net/p/swig/bugs/1297/\n'
7347315Sgblack@eecs.umich.edu
7357315Sgblack@eecs.umich.edu
7367315Sgblack@eecs.umich.edu# Set up SWIG flags & scanner
7377315Sgblack@eecs.umich.eduswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
7387315Sgblack@eecs.umich.edumain.Append(SWIGFLAGS=swig_flags)
7397315Sgblack@eecs.umich.edu
7407315Sgblack@eecs.umich.edu# filter out all existing swig scanners, they mess up the dependency
7417400SAli.Saidi@ARM.com# stuff for some reason
7427315Sgblack@eecs.umich.eduscanners = []
7437315Sgblack@eecs.umich.edufor scanner in main['SCANNERS']:
7447315Sgblack@eecs.umich.edu    skeys = scanner.skeys
7457315Sgblack@eecs.umich.edu    if skeys == '.i':
7467315Sgblack@eecs.umich.edu        continue
7477315Sgblack@eecs.umich.edu
7487400SAli.Saidi@ARM.com    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
7497315Sgblack@eecs.umich.edu        continue
7507315Sgblack@eecs.umich.edu
7517315Sgblack@eecs.umich.edu    scanners.append(scanner)
7527315Sgblack@eecs.umich.edu
7537315Sgblack@eecs.umich.edu# add the new swig scanner that we like better
7547315Sgblack@eecs.umich.edufrom SCons.Scanner import ClassicCPP as CPPScanner
7557315Sgblack@eecs.umich.eduswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
7567315Sgblack@eecs.umich.eduscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
7577315Sgblack@eecs.umich.edu
7587315Sgblack@eecs.umich.edu# replace the scanners list that has what we want
7597315Sgblack@eecs.umich.edumain['SCANNERS'] = scanners
7607599Sminkyu.jeong@arm.com
7617599Sminkyu.jeong@arm.com# Add a custom Check function to the Configure context so that we can
7627315Sgblack@eecs.umich.edu# figure out if the compiler adds leading underscores to global
7637315Sgblack@eecs.umich.edu# variables.  This is needed for the autogenerated asm files that we
7647315Sgblack@eecs.umich.edu# use for embedding the python code.
7657202Sgblack@eecs.umich.edudef CheckLeading(context):
766    context.Message("Checking for leading underscore in global variables...")
767    # 1) Define a global variable called x from asm so the C compiler
768    #    won't change the symbol at all.
769    # 2) Declare that variable.
770    # 3) Use the variable
771    #
772    # If the compiler prepends an underscore, this will successfully
773    # link because the external symbol 'x' will be called '_x' which
774    # was defined by the asm statement.  If the compiler does not
775    # prepend an underscore, this will not successfully link because
776    # '_x' will have been defined by assembly, while the C portion of
777    # the code will be trying to use 'x'
778    ret = context.TryLink('''
779        asm(".globl _x; _x: .byte 0");
780        extern int x;
781        int main() { return x; }
782        ''', extension=".c")
783    context.env.Append(LEADING_UNDERSCORE=ret)
784    context.Result(ret)
785    return ret
786
787# Platform-specific configuration.  Note again that we assume that all
788# builds under a given build root run on the same host platform.
789conf = Configure(main,
790                 conf_dir = joinpath(build_root, '.scons_config'),
791                 log_file = joinpath(build_root, 'scons_config.log'),
792                 custom_tests = { 'CheckLeading' : CheckLeading })
793
794# Check for leading underscores.  Don't really need to worry either
795# way so don't need to check the return code.
796conf.CheckLeading()
797
798# Check if we should compile a 64 bit binary on Mac OS X/Darwin
799try:
800    import platform
801    uname = platform.uname()
802    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
803        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
804            main.Append(CCFLAGS=['-arch', 'x86_64'])
805            main.Append(CFLAGS=['-arch', 'x86_64'])
806            main.Append(LINKFLAGS=['-arch', 'x86_64'])
807            main.Append(ASFLAGS=['-arch', 'x86_64'])
808except:
809    pass
810
811# Recent versions of scons substitute a "Null" object for Configure()
812# when configuration isn't necessary, e.g., if the "--help" option is
813# present.  Unfortuantely this Null object always returns false,
814# breaking all our configuration checks.  We replace it with our own
815# more optimistic null object that returns True instead.
816if not conf:
817    def NullCheck(*args, **kwargs):
818        return True
819
820    class NullConf:
821        def __init__(self, env):
822            self.env = env
823        def Finish(self):
824            return self.env
825        def __getattr__(self, mname):
826            return NullCheck
827
828    conf = NullConf(main)
829
830# Find Python include and library directories for embedding the
831# interpreter.  For consistency, we will use the same Python
832# installation used to run scons (and thus this script).  If you want
833# to link in an alternate version, see above for instructions on how
834# to invoke scons with a different copy of the Python interpreter.
835from distutils import sysconfig
836
837py_getvar = sysconfig.get_config_var
838
839py_debug = getattr(sys, 'pydebug', False)
840py_version = 'python' + py_getvar('VERSION') + (py_debug and "_d" or "")
841
842py_general_include = sysconfig.get_python_inc()
843py_platform_include = sysconfig.get_python_inc(plat_specific=True)
844py_includes = [ py_general_include ]
845if py_platform_include != py_general_include:
846    py_includes.append(py_platform_include)
847
848py_lib_path = [ py_getvar('LIBDIR') ]
849# add the prefix/lib/pythonX.Y/config dir, but only if there is no
850# shared library in prefix/lib/.
851if not py_getvar('Py_ENABLE_SHARED'):
852    py_lib_path.append(py_getvar('LIBPL'))
853    # Python requires the flags in LINKFORSHARED to be added the
854    # linker flags when linking with a statically with Python. Failing
855    # to do so can lead to errors from the Python's dynamic module
856    # loader at start up.
857    main.Append(LINKFLAGS=[py_getvar('LINKFORSHARED').split()])
858
859py_libs = []
860for lib in py_getvar('LIBS').split() + py_getvar('SYSLIBS').split():
861    if not lib.startswith('-l'):
862        # Python requires some special flags to link (e.g. -framework
863        # common on OS X systems), assume appending preserves order
864        main.Append(LINKFLAGS=[lib])
865    else:
866        lib = lib[2:]
867        if lib not in py_libs:
868            py_libs.append(lib)
869py_libs.append(py_version)
870
871main.Append(CPPPATH=py_includes)
872main.Append(LIBPATH=py_lib_path)
873
874# Cache build files in the supplied directory.
875if main['M5_BUILD_CACHE']:
876    print 'Using build cache located at', main['M5_BUILD_CACHE']
877    CacheDir(main['M5_BUILD_CACHE'])
878
879
880# verify that this stuff works
881if not conf.CheckHeader('Python.h', '<>'):
882    print "Error: can't find Python.h header in", py_includes
883    print "Install Python headers (package python-dev on Ubuntu and RedHat)"
884    Exit(1)
885
886for lib in py_libs:
887    if not conf.CheckLib(lib):
888        print "Error: can't find library %s required by python" % lib
889        Exit(1)
890
891# On Solaris you need to use libsocket for socket ops
892if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
893   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
894       print "Can't find library with socket calls (e.g. accept())"
895       Exit(1)
896
897# Check for zlib.  If the check passes, libz will be automatically
898# added to the LIBS environment variable.
899if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
900    print 'Error: did not find needed zlib compression library '\
901          'and/or zlib.h header file.'
902    print '       Please install zlib and try again.'
903    Exit(1)
904
905# If we have the protobuf compiler, also make sure we have the
906# development libraries. If the check passes, libprotobuf will be
907# automatically added to the LIBS environment variable. After
908# this, we can use the HAVE_PROTOBUF flag to determine if we have
909# got both protoc and libprotobuf available.
910main['HAVE_PROTOBUF'] = main['PROTOC'] and \
911    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
912                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
913
914# If we have the compiler but not the library, print another warning.
915if main['PROTOC'] and not main['HAVE_PROTOBUF']:
916    print termcap.Yellow + termcap.Bold + \
917        'Warning: did not find protocol buffer library and/or headers.\n' + \
918    '       Please install libprotobuf-dev for tracing support.' + \
919    termcap.Normal
920
921# Check for librt.
922have_posix_clock = \
923    conf.CheckLibWithHeader(None, 'time.h', 'C',
924                            'clock_nanosleep(0,0,NULL,NULL);') or \
925    conf.CheckLibWithHeader('rt', 'time.h', 'C',
926                            'clock_nanosleep(0,0,NULL,NULL);')
927
928if conf.CheckLib('tcmalloc_minimal'):
929    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
930else:
931    print termcap.Yellow + termcap.Bold + \
932          "You can get a 12% performance improvement by installing tcmalloc "\
933          "(libgoogle-perftools-dev package on Ubuntu or RedHat)." + \
934          termcap.Normal
935
936if not have_posix_clock:
937    print "Can't find library for POSIX clocks."
938
939# Check for <fenv.h> (C99 FP environment control)
940have_fenv = conf.CheckHeader('fenv.h', '<>')
941if not have_fenv:
942    print "Warning: Header file <fenv.h> not found."
943    print "         This host has no IEEE FP rounding mode control."
944
945######################################################################
946#
947# Finish the configuration
948#
949main = conf.Finish()
950
951######################################################################
952#
953# Collect all non-global variables
954#
955
956# Define the universe of supported ISAs
957all_isa_list = [ ]
958Export('all_isa_list')
959
960class CpuModel(object):
961    '''The CpuModel class encapsulates everything the ISA parser needs to
962    know about a particular CPU model.'''
963
964    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
965    dict = {}
966    list = []
967    defaults = []
968
969    # Constructor.  Automatically adds models to CpuModel.dict.
970    def __init__(self, name, filename, includes, strings, default=False):
971        self.name = name           # name of model
972        self.filename = filename   # filename for output exec code
973        self.includes = includes   # include files needed in exec file
974        # The 'strings' dict holds all the per-CPU symbols we can
975        # substitute into templates etc.
976        self.strings = strings
977
978        # This cpu is enabled by default
979        self.default = default
980
981        # Add self to dict
982        if name in CpuModel.dict:
983            raise AttributeError, "CpuModel '%s' already registered" % name
984        CpuModel.dict[name] = self
985        CpuModel.list.append(name)
986
987Export('CpuModel')
988
989# Sticky variables get saved in the variables file so they persist from
990# one invocation to the next (unless overridden, in which case the new
991# value becomes sticky).
992sticky_vars = Variables(args=ARGUMENTS)
993Export('sticky_vars')
994
995# Sticky variables that should be exported
996export_vars = []
997Export('export_vars')
998
999# For Ruby
1000all_protocols = []
1001Export('all_protocols')
1002protocol_dirs = []
1003Export('protocol_dirs')
1004slicc_includes = []
1005Export('slicc_includes')
1006
1007# Walk the tree and execute all SConsopts scripts that wil add to the
1008# above variables
1009if not GetOption('verbose'):
1010    print "Reading SConsopts"
1011for bdir in [ base_dir ] + extras_dir_list:
1012    if not isdir(bdir):
1013        print "Error: directory '%s' does not exist" % bdir
1014        Exit(1)
1015    for root, dirs, files in os.walk(bdir):
1016        if 'SConsopts' in files:
1017            if GetOption('verbose'):
1018                print "Reading", joinpath(root, 'SConsopts')
1019            SConscript(joinpath(root, 'SConsopts'))
1020
1021all_isa_list.sort()
1022
1023sticky_vars.AddVariables(
1024    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
1025    ListVariable('CPU_MODELS', 'CPU models',
1026                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
1027                 sorted(CpuModel.list)),
1028    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
1029                 False),
1030    BoolVariable('SS_COMPATIBLE_FP',
1031                 'Make floating-point results compatible with SimpleScalar',
1032                 False),
1033    BoolVariable('USE_SSE2',
1034                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
1035                 False),
1036    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
1037    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
1038    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
1039    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1040                  all_protocols),
1041    )
1042
1043# These variables get exported to #defines in config/*.hh (see src/SConscript).
1044export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'CP_ANNOTATE',
1045                'USE_POSIX_CLOCK', 'PROTOCOL', 'HAVE_PROTOBUF']
1046
1047###################################################
1048#
1049# Define a SCons builder for configuration flag headers.
1050#
1051###################################################
1052
1053# This function generates a config header file that #defines the
1054# variable symbol to the current variable setting (0 or 1).  The source
1055# operands are the name of the variable and a Value node containing the
1056# value of the variable.
1057def build_config_file(target, source, env):
1058    (variable, value) = [s.get_contents() for s in source]
1059    f = file(str(target[0]), 'w')
1060    print >> f, '#define', variable, value
1061    f.close()
1062    return None
1063
1064# Combine the two functions into a scons Action object.
1065config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1066
1067# The emitter munges the source & target node lists to reflect what
1068# we're really doing.
1069def config_emitter(target, source, env):
1070    # extract variable name from Builder arg
1071    variable = str(target[0])
1072    # True target is config header file
1073    target = joinpath('config', variable.lower() + '.hh')
1074    val = env[variable]
1075    if isinstance(val, bool):
1076        # Force value to 0/1
1077        val = int(val)
1078    elif isinstance(val, str):
1079        val = '"' + val + '"'
1080
1081    # Sources are variable name & value (packaged in SCons Value nodes)
1082    return ([target], [Value(variable), Value(val)])
1083
1084config_builder = Builder(emitter = config_emitter, action = config_action)
1085
1086main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1087
1088# libelf build is shared across all configs in the build root.
1089main.SConscript('ext/libelf/SConscript',
1090                variant_dir = joinpath(build_root, 'libelf'))
1091
1092# gzstream build is shared across all configs in the build root.
1093main.SConscript('ext/gzstream/SConscript',
1094                variant_dir = joinpath(build_root, 'gzstream'))
1095
1096# libfdt build is shared across all configs in the build root.
1097main.SConscript('ext/libfdt/SConscript',
1098                variant_dir = joinpath(build_root, 'libfdt'))
1099
1100###################################################
1101#
1102# This function is used to set up a directory with switching headers
1103#
1104###################################################
1105
1106main['ALL_ISA_LIST'] = all_isa_list
1107def make_switching_dir(dname, switch_headers, env):
1108    # Generate the header.  target[0] is the full path of the output
1109    # header to generate.  'source' is a dummy variable, since we get the
1110    # list of ISAs from env['ALL_ISA_LIST'].
1111    def gen_switch_hdr(target, source, env):
1112        fname = str(target[0])
1113        f = open(fname, 'w')
1114        isa = env['TARGET_ISA'].lower()
1115        print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1116        f.close()
1117
1118    # Build SCons Action object. 'varlist' specifies env vars that this
1119    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1120    # should get re-executed.
1121    switch_hdr_action = MakeAction(gen_switch_hdr,
1122                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1123
1124    # Instantiate actions for each header
1125    for hdr in switch_headers:
1126        env.Command(hdr, [], switch_hdr_action)
1127Export('make_switching_dir')
1128
1129###################################################
1130#
1131# Define build environments for selected configurations.
1132#
1133###################################################
1134
1135for variant_path in variant_paths:
1136    print "Building in", variant_path
1137
1138    # Make a copy of the build-root environment to use for this config.
1139    env = main.Clone()
1140    env['BUILDDIR'] = variant_path
1141
1142    # variant_dir is the tail component of build path, and is used to
1143    # determine the build parameters (e.g., 'ALPHA_SE')
1144    (build_root, variant_dir) = splitpath(variant_path)
1145
1146    # Set env variables according to the build directory config.
1147    sticky_vars.files = []
1148    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1149    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1150    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1151    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1152    if isfile(current_vars_file):
1153        sticky_vars.files.append(current_vars_file)
1154        print "Using saved variables file %s" % current_vars_file
1155    else:
1156        # Build dir-specific variables file doesn't exist.
1157
1158        # Make sure the directory is there so we can create it later
1159        opt_dir = dirname(current_vars_file)
1160        if not isdir(opt_dir):
1161            mkdir(opt_dir)
1162
1163        # Get default build variables from source tree.  Variables are
1164        # normally determined by name of $VARIANT_DIR, but can be
1165        # overridden by '--default=' arg on command line.
1166        default = GetOption('default')
1167        opts_dir = joinpath(main.root.abspath, 'build_opts')
1168        if default:
1169            default_vars_files = [joinpath(build_root, 'variables', default),
1170                                  joinpath(opts_dir, default)]
1171        else:
1172            default_vars_files = [joinpath(opts_dir, variant_dir)]
1173        existing_files = filter(isfile, default_vars_files)
1174        if existing_files:
1175            default_vars_file = existing_files[0]
1176            sticky_vars.files.append(default_vars_file)
1177            print "Variables file %s not found,\n  using defaults in %s" \
1178                  % (current_vars_file, default_vars_file)
1179        else:
1180            print "Error: cannot find variables file %s or " \
1181                  "default file(s) %s" \
1182                  % (current_vars_file, ' or '.join(default_vars_files))
1183            Exit(1)
1184
1185    # Apply current variable settings to env
1186    sticky_vars.Update(env)
1187
1188    help_texts["local_vars"] += \
1189        "Build variables for %s:\n" % variant_dir \
1190                 + sticky_vars.GenerateHelpText(env)
1191
1192    # Process variable settings.
1193
1194    if not have_fenv and env['USE_FENV']:
1195        print "Warning: <fenv.h> not available; " \
1196              "forcing USE_FENV to False in", variant_dir + "."
1197        env['USE_FENV'] = False
1198
1199    if not env['USE_FENV']:
1200        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1201        print "         FP results may deviate slightly from other platforms."
1202
1203    if env['EFENCE']:
1204        env.Append(LIBS=['efence'])
1205
1206    # Save sticky variable settings back to current variables file
1207    sticky_vars.Save(current_vars_file, env)
1208
1209    if env['USE_SSE2']:
1210        env.Append(CCFLAGS=['-msse2'])
1211
1212    # The src/SConscript file sets up the build rules in 'env' according
1213    # to the configured variables.  It returns a list of environments,
1214    # one for each variant build (debug, opt, etc.)
1215    envList = SConscript('src/SConscript', variant_dir = variant_path,
1216                         exports = 'env')
1217
1218    # Set up the regression tests for each build.
1219    for e in envList:
1220        SConscript('tests/SConscript',
1221                   variant_dir = joinpath(variant_path, 'tests', e.Label),
1222                   exports = { 'env' : e }, duplicate = False)
1223
1224# base help text
1225Help('''
1226Usage: scons [scons options] [build variables] [target(s)]
1227
1228Extra scons options:
1229%(options)s
1230
1231Global build variables:
1232%(global_vars)s
1233
1234%(local_vars)s
1235''' % help_texts)
1236