SConscript revision 11999:252c50d5b736
14120Sgblack@eecs.umich.edu# -*- mode:python -*-
24120Sgblack@eecs.umich.edu
34120Sgblack@eecs.umich.edu# Copyright (c) 2004-2005 The Regents of The University of Michigan
44120Sgblack@eecs.umich.edu# All rights reserved.
54120Sgblack@eecs.umich.edu#
64120Sgblack@eecs.umich.edu# Redistribution and use in source and binary forms, with or without
74120Sgblack@eecs.umich.edu# modification, are permitted provided that the following conditions are
84120Sgblack@eecs.umich.edu# met: redistributions of source code must retain the above copyright
94120Sgblack@eecs.umich.edu# notice, this list of conditions and the following disclaimer;
104120Sgblack@eecs.umich.edu# redistributions in binary form must reproduce the above copyright
114120Sgblack@eecs.umich.edu# notice, this list of conditions and the following disclaimer in the
124120Sgblack@eecs.umich.edu# documentation and/or other materials provided with the distribution;
134120Sgblack@eecs.umich.edu# neither the name of the copyright holders nor the names of its
144120Sgblack@eecs.umich.edu# contributors may be used to endorse or promote products derived from
154120Sgblack@eecs.umich.edu# this software without specific prior written permission.
164120Sgblack@eecs.umich.edu#
174120Sgblack@eecs.umich.edu# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
184120Sgblack@eecs.umich.edu# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
194120Sgblack@eecs.umich.edu# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
204120Sgblack@eecs.umich.edu# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
214120Sgblack@eecs.umich.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
224120Sgblack@eecs.umich.edu# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
234120Sgblack@eecs.umich.edu# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
244120Sgblack@eecs.umich.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
254120Sgblack@eecs.umich.edu# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
264120Sgblack@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
274120Sgblack@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
284120Sgblack@eecs.umich.edu#
294120Sgblack@eecs.umich.edu# Authors: Nathan Binkert
304120Sgblack@eecs.umich.edu
315334Sgblack@eecs.umich.eduimport array
324120Sgblack@eecs.umich.eduimport bisect
334120Sgblack@eecs.umich.eduimport imp
344120Sgblack@eecs.umich.eduimport marshal
354120Sgblack@eecs.umich.eduimport os
364120Sgblack@eecs.umich.eduimport re
374120Sgblack@eecs.umich.eduimport subprocess
384120Sgblack@eecs.umich.eduimport sys
394120Sgblack@eecs.umich.eduimport zlib
404120Sgblack@eecs.umich.edu
414120Sgblack@eecs.umich.edufrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
424120Sgblack@eecs.umich.edu
434120Sgblack@eecs.umich.eduimport SCons
444120Sgblack@eecs.umich.edu
454120Sgblack@eecs.umich.edu# This file defines how to build a particular configuration of gem5
464120Sgblack@eecs.umich.edu# based on variable settings in the 'env' build environment.
474120Sgblack@eecs.umich.edu
484120Sgblack@eecs.umich.eduImport('*')
494120Sgblack@eecs.umich.edu
504120Sgblack@eecs.umich.edu# Children need to see the environment
514120Sgblack@eecs.umich.eduExport('env')
524120Sgblack@eecs.umich.edu
534120Sgblack@eecs.umich.edubuild_env = [(opt, env[opt]) for opt in export_vars]
544120Sgblack@eecs.umich.edu
554120Sgblack@eecs.umich.edufrom m5.util import code_formatter, compareVersions
564120Sgblack@eecs.umich.edu
574120Sgblack@eecs.umich.edu########################################################################
584120Sgblack@eecs.umich.edu# Code for adding source files of various types
594120Sgblack@eecs.umich.edu#
604120Sgblack@eecs.umich.edu# When specifying a source file of some type, a set of guards can be
614120Sgblack@eecs.umich.edu# specified for that file.  When get() is used to find the files, if
624120Sgblack@eecs.umich.edu# get specifies a set of filters, only files that match those filters
634120Sgblack@eecs.umich.edu# will be accepted (unspecified filters on files are assumed to be
644120Sgblack@eecs.umich.edu# false).  Current filters are:
654120Sgblack@eecs.umich.edu#     main -- specifies the gem5 main() function
664120Sgblack@eecs.umich.edu#     skip_lib -- do not put this file into the gem5 library
674120Sgblack@eecs.umich.edu#     skip_no_python -- do not put this file into a no_python library
684120Sgblack@eecs.umich.edu#       as it embeds compiled Python
694120Sgblack@eecs.umich.edu#     <unittest> -- unit tests use filters based on the unit test name
704120Sgblack@eecs.umich.edu#
714120Sgblack@eecs.umich.edu# A parent can now be specified for a source file and default filter
724120Sgblack@eecs.umich.edu# values will be retrieved recursively from parents (children override
734120Sgblack@eecs.umich.edu# parents).
744120Sgblack@eecs.umich.edu#
754120Sgblack@eecs.umich.edudef guarded_source_iterator(sources, **guards):
764120Sgblack@eecs.umich.edu    '''Iterate over a set of sources, gated by a set of guards.'''
774120Sgblack@eecs.umich.edu    for src in sources:
784120Sgblack@eecs.umich.edu        for flag,value in guards.iteritems():
794120Sgblack@eecs.umich.edu            # if the flag is found and has a different value, skip
804120Sgblack@eecs.umich.edu            # this file
814120Sgblack@eecs.umich.edu            if src.all_guards.get(flag, False) != value:
824120Sgblack@eecs.umich.edu                break
834120Sgblack@eecs.umich.edu        else:
844120Sgblack@eecs.umich.edu            yield src
854120Sgblack@eecs.umich.edu
864202Sbinkertn@umich.educlass SourceMeta(type):
875069Sgblack@eecs.umich.edu    '''Meta class for source files that keeps track of all files of a
884202Sbinkertn@umich.edu    particular type and has a get function for finding all functions
895659Sgblack@eecs.umich.edu    of a certain type that match a set of guards'''
904601Sgblack@eecs.umich.edu    def __init__(cls, name, bases, dict):
914202Sbinkertn@umich.edu        super(SourceMeta, cls).__init__(name, bases, dict)
925124Sgblack@eecs.umich.edu        cls.all = []
935083Sgblack@eecs.umich.edu
944679Sgblack@eecs.umich.edu    def get(cls, **guards):
955083Sgblack@eecs.umich.edu        '''Find all files that match the specified guards.  If a source
964679Sgblack@eecs.umich.edu        file does not specify a flag, the default is False'''
974679Sgblack@eecs.umich.edu        for s in guarded_source_iterator(cls.all, **guards):
984202Sbinkertn@umich.edu            yield s
994202Sbinkertn@umich.edu
1005124Sgblack@eecs.umich.educlass SourceFile(object):
1014249Sgblack@eecs.umich.edu    '''Base object that encapsulates the notion of a source file.
1024240Sgblack@eecs.umich.edu    This includes, the source node, target node, various manipulations
1034202Sbinkertn@umich.edu    of those.  A source file also specifies a set of guards which
1044202Sbinkertn@umich.edu    describing which builds the source file applies to.  A parent can
1054997Sgblack@eecs.umich.edu    also be specified to get default guards from'''
1065135Sgblack@eecs.umich.edu    __metaclass__ = SourceMeta
1074997Sgblack@eecs.umich.edu    def __init__(self, source, parent=None, **guards):
1084997Sgblack@eecs.umich.edu        self.guards = guards
1095192Ssaidi@eecs.umich.edu        self.parent = parent
1105192Ssaidi@eecs.umich.edu
1114120Sgblack@eecs.umich.edu        tnode = source
1124202Sbinkertn@umich.edu        if not isinstance(source, SCons.Node.FS.File):
1135649Sgblack@eecs.umich.edu            tnode = File(source)
1145649Sgblack@eecs.umich.edu
1155647Sgblack@eecs.umich.edu        self.tnode = tnode
1165132Sgblack@eecs.umich.edu        self.snode = tnode.srcnode()
1175132Sgblack@eecs.umich.edu
1184202Sbinkertn@umich.edu        for base in type(self).__mro__:
1195647Sgblack@eecs.umich.edu            if issubclass(base, SourceFile):
1205299Sgblack@eecs.umich.edu                base.all.append(self)
1215245Sgblack@eecs.umich.edu
1225132Sgblack@eecs.umich.edu    @property
1235086Sgblack@eecs.umich.edu    def filename(self):
1245086Sgblack@eecs.umich.edu        return str(self.tnode)
1254202Sbinkertn@umich.edu
1264202Sbinkertn@umich.edu    @property
1274120Sgblack@eecs.umich.edu    def dirname(self):
1284202Sbinkertn@umich.edu        return dirname(self.filename)
1294202Sbinkertn@umich.edu
1304202Sbinkertn@umich.edu    @property
1314120Sgblack@eecs.umich.edu    def basename(self):
1325069Sgblack@eecs.umich.edu        return basename(self.filename)
1335081Sgblack@eecs.umich.edu
1345081Sgblack@eecs.umich.edu    @property
1355081Sgblack@eecs.umich.edu    def extname(self):
1365081Sgblack@eecs.umich.edu        index = self.basename.rfind('.')
1375081Sgblack@eecs.umich.edu        if index <= 0:
1385081Sgblack@eecs.umich.edu            # dot files aren't extensions
1395081Sgblack@eecs.umich.edu            return self.basename, None
1405081Sgblack@eecs.umich.edu
1415081Sgblack@eecs.umich.edu        return self.basename[:index], self.basename[index+1:]
1425081Sgblack@eecs.umich.edu
1435081Sgblack@eecs.umich.edu    @property
1445081Sgblack@eecs.umich.edu    def all_guards(self):
1455081Sgblack@eecs.umich.edu        '''find all guards for this object getting default values
1465081Sgblack@eecs.umich.edu        recursively from its parents'''
1475081Sgblack@eecs.umich.edu        guards = {}
1485081Sgblack@eecs.umich.edu        if self.parent:
1495081Sgblack@eecs.umich.edu            guards.update(self.parent.guards)
1505081Sgblack@eecs.umich.edu        guards.update(self.guards)
1515081Sgblack@eecs.umich.edu        return guards
1525081Sgblack@eecs.umich.edu
1535081Sgblack@eecs.umich.edu    def __lt__(self, other): return self.filename < other.filename
1545081Sgblack@eecs.umich.edu    def __le__(self, other): return self.filename <= other.filename
1555081Sgblack@eecs.umich.edu    def __gt__(self, other): return self.filename > other.filename
1565081Sgblack@eecs.umich.edu    def __ge__(self, other): return self.filename >= other.filename
1575081Sgblack@eecs.umich.edu    def __eq__(self, other): return self.filename == other.filename
1585081Sgblack@eecs.umich.edu    def __ne__(self, other): return self.filename != other.filename
1595081Sgblack@eecs.umich.edu
1605081Sgblack@eecs.umich.edu    @staticmethod
1615081Sgblack@eecs.umich.edu    def done():
1625081Sgblack@eecs.umich.edu        def disabled(cls, name, *ignored):
1635081Sgblack@eecs.umich.edu            raise RuntimeError("Additional SourceFile '%s'" % name,\
1645081Sgblack@eecs.umich.edu                  "declared, but targets deps are already fixed.")
1655081Sgblack@eecs.umich.edu        SourceFile.__init__ = disabled
1665081Sgblack@eecs.umich.edu
1675081Sgblack@eecs.umich.edu
1685081Sgblack@eecs.umich.educlass Source(SourceFile):
1695081Sgblack@eecs.umich.edu    current_group = None
1705081Sgblack@eecs.umich.edu    source_groups = { None : [] }
1715081Sgblack@eecs.umich.edu
1725081Sgblack@eecs.umich.edu    @classmethod
1735081Sgblack@eecs.umich.edu    def set_group(cls, group):
1745081Sgblack@eecs.umich.edu        if not group in Source.source_groups:
1755081Sgblack@eecs.umich.edu            Source.source_groups[group] = []
1765081Sgblack@eecs.umich.edu        Source.current_group = group
1775081Sgblack@eecs.umich.edu
1785081Sgblack@eecs.umich.edu    '''Add a c/c++ source file to the build'''
1795081Sgblack@eecs.umich.edu    def __init__(self, source, Werror=True, **guards):
1805081Sgblack@eecs.umich.edu        '''specify the source file, and any guards'''
1815081Sgblack@eecs.umich.edu        super(Source, self).__init__(source, **guards)
1825081Sgblack@eecs.umich.edu
1835081Sgblack@eecs.umich.edu        self.Werror = Werror
1845081Sgblack@eecs.umich.edu
1855081Sgblack@eecs.umich.edu        Source.source_groups[Source.current_group].append(self)
1865081Sgblack@eecs.umich.edu
1875081Sgblack@eecs.umich.educlass PySource(SourceFile):
1885680Sgblack@eecs.umich.edu    '''Add a python source file to the named package'''
1895081Sgblack@eecs.umich.edu    invalid_sym_char = re.compile('[^A-z0-9_]')
1905173Sgblack@eecs.umich.edu    modules = {}
1915359Sgblack@eecs.umich.edu    tnodes = {}
1925081Sgblack@eecs.umich.edu    symnames = {}
1935149Sgblack@eecs.umich.edu
1945298Sgblack@eecs.umich.edu    def __init__(self, package, source, **guards):
1955081Sgblack@eecs.umich.edu        '''specify the python package, the source file, and any guards'''
1965081Sgblack@eecs.umich.edu        super(PySource, self).__init__(source, **guards)
1975081Sgblack@eecs.umich.edu
1985081Sgblack@eecs.umich.edu        modname,ext = self.extname
1995081Sgblack@eecs.umich.edu        assert ext == 'py'
2005081Sgblack@eecs.umich.edu
2015081Sgblack@eecs.umich.edu        if package:
2025081Sgblack@eecs.umich.edu            path = package.split('.')
2035081Sgblack@eecs.umich.edu        else:
2045081Sgblack@eecs.umich.edu            path = []
2055081Sgblack@eecs.umich.edu
2065081Sgblack@eecs.umich.edu        modpath = path[:]
2075081Sgblack@eecs.umich.edu        if modname != '__init__':
2085081Sgblack@eecs.umich.edu            modpath += [ modname ]
2095081Sgblack@eecs.umich.edu        modpath = '.'.join(modpath)
2105081Sgblack@eecs.umich.edu
2115081Sgblack@eecs.umich.edu        arcpath = path + [ self.basename ]
2125081Sgblack@eecs.umich.edu        abspath = self.snode.abspath
2135081Sgblack@eecs.umich.edu        if not exists(abspath):
2145081Sgblack@eecs.umich.edu            abspath = self.tnode.abspath
2155081Sgblack@eecs.umich.edu
2165081Sgblack@eecs.umich.edu        self.package = package
2175081Sgblack@eecs.umich.edu        self.modname = modname
2185081Sgblack@eecs.umich.edu        self.modpath = modpath
2195081Sgblack@eecs.umich.edu        self.arcname = joinpath(*arcpath)
2205081Sgblack@eecs.umich.edu        self.abspath = abspath
2215081Sgblack@eecs.umich.edu        self.compiled = File(self.filename + 'c')
2225081Sgblack@eecs.umich.edu        self.cpp = File(self.filename + '.cc')
2235081Sgblack@eecs.umich.edu        self.symname = PySource.invalid_sym_char.sub('_', modpath)
2245081Sgblack@eecs.umich.edu
2255081Sgblack@eecs.umich.edu        PySource.modules[modpath] = self
2265081Sgblack@eecs.umich.edu        PySource.tnodes[self.tnode] = self
2275081Sgblack@eecs.umich.edu        PySource.symnames[self.symname] = self
2285081Sgblack@eecs.umich.edu
2295081Sgblack@eecs.umich.educlass SimObject(PySource):
2305081Sgblack@eecs.umich.edu    '''Add a SimObject python file as a python source object and add
2315081Sgblack@eecs.umich.edu    it to a list of sim object modules'''
2325081Sgblack@eecs.umich.edu
2335081Sgblack@eecs.umich.edu    fixed = False
2345081Sgblack@eecs.umich.edu    modnames = []
2355081Sgblack@eecs.umich.edu
2365081Sgblack@eecs.umich.edu    def __init__(self, source, **guards):
2375081Sgblack@eecs.umich.edu        '''Specify the source file and any guards (automatically in
2385081Sgblack@eecs.umich.edu        the m5.objects package)'''
2395081Sgblack@eecs.umich.edu        super(SimObject, self).__init__('m5.objects', source, **guards)
2405081Sgblack@eecs.umich.edu        if self.fixed:
2415081Sgblack@eecs.umich.edu            raise AttributeError, "Too late to call SimObject now."
2425081Sgblack@eecs.umich.edu
2435081Sgblack@eecs.umich.edu        bisect.insort_right(SimObject.modnames, self.modname)
2445081Sgblack@eecs.umich.edu
2455081Sgblack@eecs.umich.educlass ProtoBuf(SourceFile):
2465081Sgblack@eecs.umich.edu    '''Add a Protocol Buffer to build'''
2475081Sgblack@eecs.umich.edu
2485081Sgblack@eecs.umich.edu    def __init__(self, source, **guards):
2495081Sgblack@eecs.umich.edu        '''Specify the source file, and any guards'''
2505081Sgblack@eecs.umich.edu        super(ProtoBuf, self).__init__(source, **guards)
2515081Sgblack@eecs.umich.edu
2525081Sgblack@eecs.umich.edu        # Get the file name and the extension
2535081Sgblack@eecs.umich.edu        modname,ext = self.extname
2545081Sgblack@eecs.umich.edu        assert ext == 'proto'
2555081Sgblack@eecs.umich.edu
2565081Sgblack@eecs.umich.edu        # Currently, we stick to generating the C++ headers, so we
2575081Sgblack@eecs.umich.edu        # only need to track the source and header.
2585081Sgblack@eecs.umich.edu        self.cc_file = File(modname + '.pb.cc')
2595081Sgblack@eecs.umich.edu        self.hh_file = File(modname + '.pb.h')
2605081Sgblack@eecs.umich.edu
2615081Sgblack@eecs.umich.educlass UnitTest(object):
2625081Sgblack@eecs.umich.edu    '''Create a UnitTest'''
2635081Sgblack@eecs.umich.edu
2645081Sgblack@eecs.umich.edu    all = []
2655081Sgblack@eecs.umich.edu    def __init__(self, target, *sources, **kwargs):
2665081Sgblack@eecs.umich.edu        '''Specify the target name and any sources.  Sources that are
2675081Sgblack@eecs.umich.edu        not SourceFiles are evalued with Source().  All files are
2685081Sgblack@eecs.umich.edu        guarded with a guard of the same name as the UnitTest
2695081Sgblack@eecs.umich.edu        target.'''
2705081Sgblack@eecs.umich.edu
2715081Sgblack@eecs.umich.edu        srcs = []
2725081Sgblack@eecs.umich.edu        for src in sources:
2735081Sgblack@eecs.umich.edu            if not isinstance(src, SourceFile):
2745081Sgblack@eecs.umich.edu                src = Source(src, skip_lib=True)
2755081Sgblack@eecs.umich.edu            src.guards[target] = True
2765081Sgblack@eecs.umich.edu            srcs.append(src)
2775081Sgblack@eecs.umich.edu
2785081Sgblack@eecs.umich.edu        self.sources = srcs
2795081Sgblack@eecs.umich.edu        self.target = target
2805081Sgblack@eecs.umich.edu        self.main = kwargs.get('main', False)
2815081Sgblack@eecs.umich.edu        UnitTest.all.append(self)
2825081Sgblack@eecs.umich.edu
2835081Sgblack@eecs.umich.edu# Children should have access
2845081Sgblack@eecs.umich.eduExport('Source')
2855081Sgblack@eecs.umich.eduExport('PySource')
2865081Sgblack@eecs.umich.eduExport('SimObject')
2875081Sgblack@eecs.umich.eduExport('ProtoBuf')
2885081Sgblack@eecs.umich.eduExport('UnitTest')
2895081Sgblack@eecs.umich.edu
2905081Sgblack@eecs.umich.edu########################################################################
2915081Sgblack@eecs.umich.edu#
2925081Sgblack@eecs.umich.edu# Debug Flags
2935081Sgblack@eecs.umich.edu#
2945081Sgblack@eecs.umich.edudebug_flags = {}
2955081Sgblack@eecs.umich.edudef DebugFlag(name, desc=None):
2965081Sgblack@eecs.umich.edu    if name in debug_flags:
2975081Sgblack@eecs.umich.edu        raise AttributeError, "Flag %s already specified" % name
2985081Sgblack@eecs.umich.edu    debug_flags[name] = (name, (), desc)
2995081Sgblack@eecs.umich.edu
3005081Sgblack@eecs.umich.edudef CompoundFlag(name, flags, desc=None):
3015081Sgblack@eecs.umich.edu    if name in debug_flags:
3025081Sgblack@eecs.umich.edu        raise AttributeError, "Flag %s already specified" % name
3035081Sgblack@eecs.umich.edu
3045081Sgblack@eecs.umich.edu    compound = tuple(flags)
3055081Sgblack@eecs.umich.edu    debug_flags[name] = (name, compound, desc)
3065081Sgblack@eecs.umich.edu
3075081Sgblack@eecs.umich.eduExport('DebugFlag')
3085081Sgblack@eecs.umich.eduExport('CompoundFlag')
3095081Sgblack@eecs.umich.edu
3105081Sgblack@eecs.umich.edu########################################################################
3115081Sgblack@eecs.umich.edu#
3125081Sgblack@eecs.umich.edu# Set some compiler variables
3135081Sgblack@eecs.umich.edu#
3145081Sgblack@eecs.umich.edu
3155081Sgblack@eecs.umich.edu# Include file paths are rooted in this directory.  SCons will
3165081Sgblack@eecs.umich.edu# automatically expand '.' to refer to both the source directory and
3175081Sgblack@eecs.umich.edu# the corresponding build directory to pick up generated include
3185081Sgblack@eecs.umich.edu# files.
3195081Sgblack@eecs.umich.eduenv.Append(CPPPATH=Dir('.'))
3205081Sgblack@eecs.umich.edu
3215081Sgblack@eecs.umich.edufor extra_dir in extras_dir_list:
3225081Sgblack@eecs.umich.edu    env.Append(CPPPATH=Dir(extra_dir))
3235081Sgblack@eecs.umich.edu
3245081Sgblack@eecs.umich.edu# Workaround for bug in SCons version > 0.97d20071212
3255081Sgblack@eecs.umich.edu# Scons bug id: 2006 gem5 Bug id: 308
3265081Sgblack@eecs.umich.edufor root, dirs, files in os.walk(base_dir, topdown=True):
3275081Sgblack@eecs.umich.edu    Dir(root[len(base_dir) + 1:])
3285081Sgblack@eecs.umich.edu
3295081Sgblack@eecs.umich.edu########################################################################
3305081Sgblack@eecs.umich.edu#
3315081Sgblack@eecs.umich.edu# Walk the tree and execute all SConscripts in subdirectories
3325081Sgblack@eecs.umich.edu#
3335081Sgblack@eecs.umich.edu
3345081Sgblack@eecs.umich.eduhere = Dir('.').srcnode().abspath
3355081Sgblack@eecs.umich.edufor root, dirs, files in os.walk(base_dir, topdown=True):
3365081Sgblack@eecs.umich.edu    if root == here:
3375081Sgblack@eecs.umich.edu        # we don't want to recurse back into this SConscript
3385081Sgblack@eecs.umich.edu        continue
3395081Sgblack@eecs.umich.edu
3405081Sgblack@eecs.umich.edu    if 'SConscript' in files:
3415081Sgblack@eecs.umich.edu        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
3425081Sgblack@eecs.umich.edu        Source.set_group(build_dir)
3435081Sgblack@eecs.umich.edu        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3445081Sgblack@eecs.umich.edu
3455081Sgblack@eecs.umich.edufor extra_dir in extras_dir_list:
3465081Sgblack@eecs.umich.edu    prefix_len = len(dirname(extra_dir)) + 1
3475081Sgblack@eecs.umich.edu
3485081Sgblack@eecs.umich.edu    # Also add the corresponding build directory to pick up generated
3495081Sgblack@eecs.umich.edu    # include files.
3505069Sgblack@eecs.umich.edu    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
3514202Sbinkertn@umich.edu
3524202Sbinkertn@umich.edu    for root, dirs, files in os.walk(extra_dir, topdown=True):
3534202Sbinkertn@umich.edu        # if build lives in the extras directory, don't walk down it
3545069Sgblack@eecs.umich.edu        if 'build' in dirs:
3555069Sgblack@eecs.umich.edu            dirs.remove('build')
3565069Sgblack@eecs.umich.edu
3575069Sgblack@eecs.umich.edu        if 'SConscript' in files:
3584202Sbinkertn@umich.edu            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
3594202Sbinkertn@umich.edu            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3605406Ssaidi@eecs.umich.edu
3615406Ssaidi@eecs.umich.edufor opt in export_vars:
3625406Ssaidi@eecs.umich.edu    env.ConfigFile(opt)
3635406Ssaidi@eecs.umich.edu
3645406Ssaidi@eecs.umich.edudef makeTheISA(source, target, env):
3655406Ssaidi@eecs.umich.edu    isas = [ src.get_contents() for src in source ]
3665406Ssaidi@eecs.umich.edu    target_isa = env['TARGET_ISA']
3675406Ssaidi@eecs.umich.edu    def define(isa):
3685406Ssaidi@eecs.umich.edu        return isa.upper() + '_ISA'
3695406Ssaidi@eecs.umich.edu
3705406Ssaidi@eecs.umich.edu    def namespace(isa):
3715406Ssaidi@eecs.umich.edu        return isa[0].upper() + isa[1:].lower() + 'ISA'
3725406Ssaidi@eecs.umich.edu
3735406Ssaidi@eecs.umich.edu
374    code = code_formatter()
375    code('''\
376#ifndef __CONFIG_THE_ISA_HH__
377#define __CONFIG_THE_ISA_HH__
378
379''')
380
381    # create defines for the preprocessing and compile-time determination
382    for i,isa in enumerate(isas):
383        code('#define $0 $1', define(isa), i + 1)
384    code()
385
386    # create an enum for any run-time determination of the ISA, we
387    # reuse the same name as the namespaces
388    code('enum class Arch {')
389    for i,isa in enumerate(isas):
390        if i + 1 == len(isas):
391            code('  $0 = $1', namespace(isa), define(isa))
392        else:
393            code('  $0 = $1,', namespace(isa), define(isa))
394    code('};')
395
396    code('''
397
398#define THE_ISA ${{define(target_isa)}}
399#define TheISA ${{namespace(target_isa)}}
400#define THE_ISA_STR "${{target_isa}}"
401
402#endif // __CONFIG_THE_ISA_HH__''')
403
404    code.write(str(target[0]))
405
406env.Command('config/the_isa.hh', map(Value, all_isa_list),
407            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
408
409def makeTheGPUISA(source, target, env):
410    isas = [ src.get_contents() for src in source ]
411    target_gpu_isa = env['TARGET_GPU_ISA']
412    def define(isa):
413        return isa.upper() + '_ISA'
414
415    def namespace(isa):
416        return isa[0].upper() + isa[1:].lower() + 'ISA'
417
418
419    code = code_formatter()
420    code('''\
421#ifndef __CONFIG_THE_GPU_ISA_HH__
422#define __CONFIG_THE_GPU_ISA_HH__
423
424''')
425
426    # create defines for the preprocessing and compile-time determination
427    for i,isa in enumerate(isas):
428        code('#define $0 $1', define(isa), i + 1)
429    code()
430
431    # create an enum for any run-time determination of the ISA, we
432    # reuse the same name as the namespaces
433    code('enum class GPUArch {')
434    for i,isa in enumerate(isas):
435        if i + 1 == len(isas):
436            code('  $0 = $1', namespace(isa), define(isa))
437        else:
438            code('  $0 = $1,', namespace(isa), define(isa))
439    code('};')
440
441    code('''
442
443#define THE_GPU_ISA ${{define(target_gpu_isa)}}
444#define TheGpuISA ${{namespace(target_gpu_isa)}}
445#define THE_GPU_ISA_STR "${{target_gpu_isa}}"
446
447#endif // __CONFIG_THE_GPU_ISA_HH__''')
448
449    code.write(str(target[0]))
450
451env.Command('config/the_gpu_isa.hh', map(Value, all_gpu_isa_list),
452            MakeAction(makeTheGPUISA, Transform("CFG ISA", 0)))
453
454########################################################################
455#
456# Prevent any SimObjects from being added after this point, they
457# should all have been added in the SConscripts above
458#
459SimObject.fixed = True
460
461class DictImporter(object):
462    '''This importer takes a dictionary of arbitrary module names that
463    map to arbitrary filenames.'''
464    def __init__(self, modules):
465        self.modules = modules
466        self.installed = set()
467
468    def __del__(self):
469        self.unload()
470
471    def unload(self):
472        import sys
473        for module in self.installed:
474            del sys.modules[module]
475        self.installed = set()
476
477    def find_module(self, fullname, path):
478        if fullname == 'm5.defines':
479            return self
480
481        if fullname == 'm5.objects':
482            return self
483
484        if fullname.startswith('_m5'):
485            return None
486
487        source = self.modules.get(fullname, None)
488        if source is not None and fullname.startswith('m5.objects'):
489            return self
490
491        return None
492
493    def load_module(self, fullname):
494        mod = imp.new_module(fullname)
495        sys.modules[fullname] = mod
496        self.installed.add(fullname)
497
498        mod.__loader__ = self
499        if fullname == 'm5.objects':
500            mod.__path__ = fullname.split('.')
501            return mod
502
503        if fullname == 'm5.defines':
504            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
505            return mod
506
507        source = self.modules[fullname]
508        if source.modname == '__init__':
509            mod.__path__ = source.modpath
510        mod.__file__ = source.abspath
511
512        exec file(source.abspath, 'r') in mod.__dict__
513
514        return mod
515
516import m5.SimObject
517import m5.params
518from m5.util import code_formatter
519
520m5.SimObject.clear()
521m5.params.clear()
522
523# install the python importer so we can grab stuff from the source
524# tree itself.  We can't have SimObjects added after this point or
525# else we won't know about them for the rest of the stuff.
526importer = DictImporter(PySource.modules)
527sys.meta_path[0:0] = [ importer ]
528
529# import all sim objects so we can populate the all_objects list
530# make sure that we're working with a list, then let's sort it
531for modname in SimObject.modnames:
532    exec('from m5.objects import %s' % modname)
533
534# we need to unload all of the currently imported modules so that they
535# will be re-imported the next time the sconscript is run
536importer.unload()
537sys.meta_path.remove(importer)
538
539sim_objects = m5.SimObject.allClasses
540all_enums = m5.params.allEnums
541
542for name,obj in sorted(sim_objects.iteritems()):
543    for param in obj._params.local.values():
544        # load the ptype attribute now because it depends on the
545        # current version of SimObject.allClasses, but when scons
546        # actually uses the value, all versions of
547        # SimObject.allClasses will have been loaded
548        param.ptype
549
550########################################################################
551#
552# calculate extra dependencies
553#
554module_depends = ["m5", "m5.SimObject", "m5.params"]
555depends = [ PySource.modules[dep].snode for dep in module_depends ]
556depends.sort(key = lambda x: x.name)
557
558########################################################################
559#
560# Commands for the basic automatically generated python files
561#
562
563# Generate Python file containing a dict specifying the current
564# buildEnv flags.
565def makeDefinesPyFile(target, source, env):
566    build_env = source[0].get_contents()
567
568    code = code_formatter()
569    code("""
570import _m5.core
571import m5.util
572
573buildEnv = m5.util.SmartDict($build_env)
574
575compileDate = _m5.core.compileDate
576_globals = globals()
577for key,val in _m5.core.__dict__.iteritems():
578    if key.startswith('flag_'):
579        flag = key[5:]
580        _globals[flag] = val
581del _globals
582""")
583    code.write(target[0].abspath)
584
585defines_info = Value(build_env)
586# Generate a file with all of the compile options in it
587env.Command('python/m5/defines.py', defines_info,
588            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
589PySource('m5', 'python/m5/defines.py')
590
591# Generate python file containing info about the M5 source code
592def makeInfoPyFile(target, source, env):
593    code = code_formatter()
594    for src in source:
595        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
596        code('$src = ${{repr(data)}}')
597    code.write(str(target[0]))
598
599# Generate a file that wraps the basic top level files
600env.Command('python/m5/info.py',
601            [ '#/COPYING', '#/LICENSE', '#/README', ],
602            MakeAction(makeInfoPyFile, Transform("INFO")))
603PySource('m5', 'python/m5/info.py')
604
605########################################################################
606#
607# Create all of the SimObject param headers and enum headers
608#
609
610def createSimObjectParamStruct(target, source, env):
611    assert len(target) == 1 and len(source) == 1
612
613    name = source[0].get_text_contents()
614    obj = sim_objects[name]
615
616    code = code_formatter()
617    obj.cxx_param_decl(code)
618    code.write(target[0].abspath)
619
620def createSimObjectCxxConfig(is_header):
621    def body(target, source, env):
622        assert len(target) == 1 and len(source) == 1
623
624        name = str(source[0].get_contents())
625        obj = sim_objects[name]
626
627        code = code_formatter()
628        obj.cxx_config_param_file(code, is_header)
629        code.write(target[0].abspath)
630    return body
631
632def createEnumStrings(target, source, env):
633    assert len(target) == 1 and len(source) == 2
634
635    name = source[0].get_text_contents()
636    use_python = source[1].read()
637    obj = all_enums[name]
638
639    code = code_formatter()
640    obj.cxx_def(code)
641    if use_python:
642        obj.pybind_def(code)
643    code.write(target[0].abspath)
644
645def createEnumDecls(target, source, env):
646    assert len(target) == 1 and len(source) == 1
647
648    name = source[0].get_text_contents()
649    obj = all_enums[name]
650
651    code = code_formatter()
652    obj.cxx_decl(code)
653    code.write(target[0].abspath)
654
655def createSimObjectPyBindWrapper(target, source, env):
656    name = source[0].get_text_contents()
657    obj = sim_objects[name]
658
659    code = code_formatter()
660    obj.pybind_decl(code)
661    code.write(target[0].abspath)
662
663# Generate all of the SimObject param C++ struct header files
664params_hh_files = []
665for name,simobj in sorted(sim_objects.iteritems()):
666    py_source = PySource.modules[simobj.__module__]
667    extra_deps = [ py_source.tnode ]
668
669    hh_file = File('params/%s.hh' % name)
670    params_hh_files.append(hh_file)
671    env.Command(hh_file, Value(name),
672                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
673    env.Depends(hh_file, depends + extra_deps)
674
675# C++ parameter description files
676if GetOption('with_cxx_config'):
677    for name,simobj in sorted(sim_objects.iteritems()):
678        py_source = PySource.modules[simobj.__module__]
679        extra_deps = [ py_source.tnode ]
680
681        cxx_config_hh_file = File('cxx_config/%s.hh' % name)
682        cxx_config_cc_file = File('cxx_config/%s.cc' % name)
683        env.Command(cxx_config_hh_file, Value(name),
684                    MakeAction(createSimObjectCxxConfig(True),
685                    Transform("CXXCPRHH")))
686        env.Command(cxx_config_cc_file, Value(name),
687                    MakeAction(createSimObjectCxxConfig(False),
688                    Transform("CXXCPRCC")))
689        env.Depends(cxx_config_hh_file, depends + extra_deps +
690                    [File('params/%s.hh' % name), File('sim/cxx_config.hh')])
691        env.Depends(cxx_config_cc_file, depends + extra_deps +
692                    [cxx_config_hh_file])
693        Source(cxx_config_cc_file)
694
695    cxx_config_init_cc_file = File('cxx_config/init.cc')
696
697    def createCxxConfigInitCC(target, source, env):
698        assert len(target) == 1 and len(source) == 1
699
700        code = code_formatter()
701
702        for name,simobj in sorted(sim_objects.iteritems()):
703            if not hasattr(simobj, 'abstract') or not simobj.abstract:
704                code('#include "cxx_config/${name}.hh"')
705        code()
706        code('void cxxConfigInit()')
707        code('{')
708        code.indent()
709        for name,simobj in sorted(sim_objects.iteritems()):
710            not_abstract = not hasattr(simobj, 'abstract') or \
711                not simobj.abstract
712            if not_abstract and 'type' in simobj.__dict__:
713                code('cxx_config_directory["${name}"] = '
714                     '${name}CxxConfigParams::makeDirectoryEntry();')
715        code.dedent()
716        code('}')
717        code.write(target[0].abspath)
718
719    py_source = PySource.modules[simobj.__module__]
720    extra_deps = [ py_source.tnode ]
721    env.Command(cxx_config_init_cc_file, Value(name),
722        MakeAction(createCxxConfigInitCC, Transform("CXXCINIT")))
723    cxx_param_hh_files = ["cxx_config/%s.hh" % simobj
724        for name,simobj in sorted(sim_objects.iteritems())
725        if not hasattr(simobj, 'abstract') or not simobj.abstract]
726    Depends(cxx_config_init_cc_file, cxx_param_hh_files +
727            [File('sim/cxx_config.hh')])
728    Source(cxx_config_init_cc_file)
729
730# Generate all enum header files
731for name,enum in sorted(all_enums.iteritems()):
732    py_source = PySource.modules[enum.__module__]
733    extra_deps = [ py_source.tnode ]
734
735    cc_file = File('enums/%s.cc' % name)
736    env.Command(cc_file, [Value(name), Value(env['USE_PYTHON'])],
737                MakeAction(createEnumStrings, Transform("ENUM STR")))
738    env.Depends(cc_file, depends + extra_deps)
739    Source(cc_file)
740
741    hh_file = File('enums/%s.hh' % name)
742    env.Command(hh_file, Value(name),
743                MakeAction(createEnumDecls, Transform("ENUMDECL")))
744    env.Depends(hh_file, depends + extra_deps)
745
746# Generate SimObject Python bindings wrapper files
747if env['USE_PYTHON']:
748    for name,simobj in sorted(sim_objects.iteritems()):
749        py_source = PySource.modules[simobj.__module__]
750        extra_deps = [ py_source.tnode ]
751        cc_file = File('python/_m5/param_%s.cc' % name)
752        env.Command(cc_file, Value(name),
753                    MakeAction(createSimObjectPyBindWrapper,
754                               Transform("SO PyBind")))
755        env.Depends(cc_file, depends + extra_deps)
756        Source(cc_file)
757
758# Build all protocol buffers if we have got protoc and protobuf available
759if env['HAVE_PROTOBUF']:
760    for proto in ProtoBuf.all:
761        # Use both the source and header as the target, and the .proto
762        # file as the source. When executing the protoc compiler, also
763        # specify the proto_path to avoid having the generated files
764        # include the path.
765        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
766                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
767                               '--proto_path ${SOURCE.dir} $SOURCE',
768                               Transform("PROTOC")))
769
770        # Add the C++ source file
771        Source(proto.cc_file, **proto.guards)
772elif ProtoBuf.all:
773    print 'Got protobuf to build, but lacks support!'
774    Exit(1)
775
776#
777# Handle debug flags
778#
779def makeDebugFlagCC(target, source, env):
780    assert(len(target) == 1 and len(source) == 1)
781
782    code = code_formatter()
783
784    # delay definition of CompoundFlags until after all the definition
785    # of all constituent SimpleFlags
786    comp_code = code_formatter()
787
788    # file header
789    code('''
790/*
791 * DO NOT EDIT THIS FILE! Automatically generated by SCons.
792 */
793
794#include "base/debug.hh"
795
796namespace Debug {
797
798''')
799
800    for name, flag in sorted(source[0].read().iteritems()):
801        n, compound, desc = flag
802        assert n == name
803
804        if not compound:
805            code('SimpleFlag $name("$name", "$desc");')
806        else:
807            comp_code('CompoundFlag $name("$name", "$desc",')
808            comp_code.indent()
809            last = len(compound) - 1
810            for i,flag in enumerate(compound):
811                if i != last:
812                    comp_code('&$flag,')
813                else:
814                    comp_code('&$flag);')
815            comp_code.dedent()
816
817    code.append(comp_code)
818    code()
819    code('} // namespace Debug')
820
821    code.write(str(target[0]))
822
823def makeDebugFlagHH(target, source, env):
824    assert(len(target) == 1 and len(source) == 1)
825
826    val = eval(source[0].get_contents())
827    name, compound, desc = val
828
829    code = code_formatter()
830
831    # file header boilerplate
832    code('''\
833/*
834 * DO NOT EDIT THIS FILE! Automatically generated by SCons.
835 */
836
837#ifndef __DEBUG_${name}_HH__
838#define __DEBUG_${name}_HH__
839
840namespace Debug {
841''')
842
843    if compound:
844        code('class CompoundFlag;')
845    code('class SimpleFlag;')
846
847    if compound:
848        code('extern CompoundFlag $name;')
849        for flag in compound:
850            code('extern SimpleFlag $flag;')
851    else:
852        code('extern SimpleFlag $name;')
853
854    code('''
855}
856
857#endif // __DEBUG_${name}_HH__
858''')
859
860    code.write(str(target[0]))
861
862for name,flag in sorted(debug_flags.iteritems()):
863    n, compound, desc = flag
864    assert n == name
865
866    hh_file = 'debug/%s.hh' % name
867    env.Command(hh_file, Value(flag),
868                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
869
870env.Command('debug/flags.cc', Value(debug_flags),
871            MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
872Source('debug/flags.cc')
873
874# version tags
875tags = \
876env.Command('sim/tags.cc', None,
877            MakeAction('util/cpt_upgrader.py --get-cc-file > $TARGET',
878                       Transform("VER TAGS")))
879env.AlwaysBuild(tags)
880
881# Embed python files.  All .py files that have been indicated by a
882# PySource() call in a SConscript need to be embedded into the M5
883# library.  To do that, we compile the file to byte code, marshal the
884# byte code, compress it, and then generate a c++ file that
885# inserts the result into an array.
886def embedPyFile(target, source, env):
887    def c_str(string):
888        if string is None:
889            return "0"
890        return '"%s"' % string
891
892    '''Action function to compile a .py into a code object, marshal
893    it, compress it, and stick it into an asm file so the code appears
894    as just bytes with a label in the data section'''
895
896    src = file(str(source[0]), 'r').read()
897
898    pysource = PySource.tnodes[source[0]]
899    compiled = compile(src, pysource.abspath, 'exec')
900    marshalled = marshal.dumps(compiled)
901    compressed = zlib.compress(marshalled)
902    data = compressed
903    sym = pysource.symname
904
905    code = code_formatter()
906    code('''\
907#include "sim/init.hh"
908
909namespace {
910
911const uint8_t data_${sym}[] = {
912''')
913    code.indent()
914    step = 16
915    for i in xrange(0, len(data), step):
916        x = array.array('B', data[i:i+step])
917        code(''.join('%d,' % d for d in x))
918    code.dedent()
919
920    code('''};
921
922EmbeddedPython embedded_${sym}(
923    ${{c_str(pysource.arcname)}},
924    ${{c_str(pysource.abspath)}},
925    ${{c_str(pysource.modpath)}},
926    data_${sym},
927    ${{len(data)}},
928    ${{len(marshalled)}});
929
930} // anonymous namespace
931''')
932    code.write(str(target[0]))
933
934for source in PySource.all:
935    env.Command(source.cpp, source.tnode,
936                MakeAction(embedPyFile, Transform("EMBED PY")))
937    Source(source.cpp, skip_no_python=True)
938
939########################################################################
940#
941# Define binaries.  Each different build type (debug, opt, etc.) gets
942# a slightly different build environment.
943#
944
945# List of constructed environments to pass back to SConstruct
946date_source = Source('base/date.cc', skip_lib=True)
947
948# Capture this directory for the closure makeEnv, otherwise when it is
949# called, it won't know what directory it should use.
950variant_dir = Dir('.').path
951def variant(*path):
952    return os.path.join(variant_dir, *path)
953def variantd(*path):
954    return variant(*path)+'/'
955
956# Function to create a new build environment as clone of current
957# environment 'env' with modified object suffix and optional stripped
958# binary.  Additional keyword arguments are appended to corresponding
959# build environment vars.
960def makeEnv(env, label, objsfx, strip = False, **kwargs):
961    # SCons doesn't know to append a library suffix when there is a '.' in the
962    # name.  Use '_' instead.
963    libname = variant('gem5_' + label)
964    exename = variant('gem5.' + label)
965    secondary_exename = variant('m5.' + label)
966
967    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
968    new_env.Label = label
969    new_env.Append(**kwargs)
970
971    if env['GCC']:
972        # The address sanitizer is available for gcc >= 4.8
973        if GetOption('with_asan'):
974            if GetOption('with_ubsan') and \
975                    compareVersions(env['GCC_VERSION'], '4.9') >= 0:
976                new_env.Append(CCFLAGS=['-fsanitize=address,undefined',
977                                        '-fno-omit-frame-pointer'])
978                new_env.Append(LINKFLAGS='-fsanitize=address,undefined')
979            else:
980                new_env.Append(CCFLAGS=['-fsanitize=address',
981                                        '-fno-omit-frame-pointer'])
982                new_env.Append(LINKFLAGS='-fsanitize=address')
983        # Only gcc >= 4.9 supports UBSan, so check both the version
984        # and the command-line option before adding the compiler and
985        # linker flags.
986        elif GetOption('with_ubsan') and \
987                compareVersions(env['GCC_VERSION'], '4.9') >= 0:
988            new_env.Append(CCFLAGS='-fsanitize=undefined')
989            new_env.Append(LINKFLAGS='-fsanitize=undefined')
990
991
992    if env['CLANG']:
993        # We require clang >= 3.1, so there is no need to check any
994        # versions here.
995        if GetOption('with_ubsan'):
996            if GetOption('with_asan'):
997                new_env.Append(CCFLAGS=['-fsanitize=address,undefined',
998                                        '-fno-omit-frame-pointer'])
999                new_env.Append(LINKFLAGS='-fsanitize=address,undefined')
1000            else:
1001                new_env.Append(CCFLAGS='-fsanitize=undefined')
1002                new_env.Append(LINKFLAGS='-fsanitize=undefined')
1003
1004        elif GetOption('with_asan'):
1005            new_env.Append(CCFLAGS=['-fsanitize=address',
1006                                    '-fno-omit-frame-pointer'])
1007            new_env.Append(LINKFLAGS='-fsanitize=address')
1008
1009    werror_env = new_env.Clone()
1010    # Treat warnings as errors but white list some warnings that we
1011    # want to allow (e.g., deprecation warnings).
1012    werror_env.Append(CCFLAGS=['-Werror',
1013                               '-Wno-error=deprecated-declarations',
1014                               '-Wno-error=deprecated',
1015                               ])
1016
1017    def make_obj(source, static, extra_deps = None):
1018        '''This function adds the specified source to the correct
1019        build environment, and returns the corresponding SCons Object
1020        nodes'''
1021
1022        if source.Werror:
1023            env = werror_env
1024        else:
1025            env = new_env
1026
1027        if static:
1028            obj = env.StaticObject(source.tnode)
1029        else:
1030            obj = env.SharedObject(source.tnode)
1031
1032        if extra_deps:
1033            env.Depends(obj, extra_deps)
1034
1035        return obj
1036
1037    lib_guards = {'main': False, 'skip_lib': False}
1038
1039    # Without Python, leave out all Python content from the library
1040    # builds.  The option doesn't affect gem5 built as a program
1041    if GetOption('without_python'):
1042        lib_guards['skip_no_python'] = False
1043
1044    static_objs = []
1045    shared_objs = []
1046    for s in guarded_source_iterator(Source.source_groups[None], **lib_guards):
1047        static_objs.append(make_obj(s, True))
1048        shared_objs.append(make_obj(s, False))
1049
1050    partial_objs = []
1051    for group, all_srcs in Source.source_groups.iteritems():
1052        # If these are the ungrouped source files, skip them.
1053        if not group:
1054            continue
1055
1056        # Get a list of the source files compatible with the current guards.
1057        srcs = [ s for s in guarded_source_iterator(all_srcs, **lib_guards) ]
1058        # If there aren't any left, skip this group.
1059        if not srcs:
1060            continue
1061
1062        # Set up the static partially linked objects.
1063        source_objs = [ make_obj(s, True) for s in srcs ]
1064        file_name = new_env.subst("${OBJPREFIX}lib${OBJSUFFIX}.partial")
1065        target = File(joinpath(group, file_name))
1066        partial = env.PartialStatic(target=target, source=source_objs)
1067        static_objs.append(partial)
1068
1069        # Set up the shared partially linked objects.
1070        source_objs = [ make_obj(s, False) for s in srcs ]
1071        file_name = new_env.subst("${SHOBJPREFIX}lib${SHOBJSUFFIX}.partial")
1072        target = File(joinpath(group, file_name))
1073        partial = env.PartialShared(target=target, source=source_objs)
1074        shared_objs.append(partial)
1075
1076    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
1077    static_objs.append(static_date)
1078
1079    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
1080    shared_objs.append(shared_date)
1081
1082    # First make a library of everything but main() so other programs can
1083    # link against m5.
1084    static_lib = new_env.StaticLibrary(libname, static_objs)
1085    shared_lib = new_env.SharedLibrary(libname, shared_objs)
1086
1087    # Now link a stub with main() and the static library.
1088    main_objs = [ make_obj(s, True) for s in Source.get(main=True) ]
1089
1090    for test in UnitTest.all:
1091        flags = { test.target : True }
1092        test_sources = Source.get(**flags)
1093        test_objs = [ make_obj(s, static=True) for s in test_sources ]
1094        if test.main:
1095            test_objs += main_objs
1096        path = variant('unittest/%s.%s' % (test.target, label))
1097        new_env.Program(path, test_objs + static_objs)
1098
1099    progname = exename
1100    if strip:
1101        progname += '.unstripped'
1102
1103    targets = new_env.Program(progname, main_objs + static_objs)
1104
1105    if strip:
1106        if sys.platform == 'sunos5':
1107            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
1108        else:
1109            cmd = 'strip $SOURCE -o $TARGET'
1110        targets = new_env.Command(exename, progname,
1111                    MakeAction(cmd, Transform("STRIP")))
1112
1113    new_env.Command(secondary_exename, exename,
1114            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
1115
1116    new_env.M5Binary = targets[0]
1117
1118    # Set up regression tests.
1119    SConscript(os.path.join(env.root.abspath, 'tests', 'SConscript'),
1120               variant_dir=variantd('tests', new_env.Label),
1121               exports={ 'env' : new_env }, duplicate=False)
1122
1123# Start out with the compiler flags common to all compilers,
1124# i.e. they all use -g for opt and -g -pg for prof
1125ccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
1126           'perf' : ['-g']}
1127
1128# Start out with the linker flags common to all linkers, i.e. -pg for
1129# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
1130# no-as-needed and as-needed as the binutils linker is too clever and
1131# simply doesn't link to the library otherwise.
1132ldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
1133           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
1134
1135# For Link Time Optimization, the optimisation flags used to compile
1136# individual files are decoupled from those used at link time
1137# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
1138# to also update the linker flags based on the target.
1139if env['GCC']:
1140    if sys.platform == 'sunos5':
1141        ccflags['debug'] += ['-gstabs+']
1142    else:
1143        ccflags['debug'] += ['-ggdb3']
1144    ldflags['debug'] += ['-O0']
1145    # opt, fast, prof and perf all share the same cc flags, also add
1146    # the optimization to the ldflags as LTO defers the optimization
1147    # to link time
1148    for target in ['opt', 'fast', 'prof', 'perf']:
1149        ccflags[target] += ['-O3']
1150        ldflags[target] += ['-O3']
1151
1152    ccflags['fast'] += env['LTO_CCFLAGS']
1153    ldflags['fast'] += env['LTO_LDFLAGS']
1154elif env['CLANG']:
1155    ccflags['debug'] += ['-g', '-O0']
1156    # opt, fast, prof and perf all share the same cc flags
1157    for target in ['opt', 'fast', 'prof', 'perf']:
1158        ccflags[target] += ['-O3']
1159else:
1160    print 'Unknown compiler, please fix compiler options'
1161    Exit(1)
1162
1163
1164# To speed things up, we only instantiate the build environments we
1165# need.  We try to identify the needed environment for each target; if
1166# we can't, we fall back on instantiating all the environments just to
1167# be safe.
1168target_types = ['debug', 'opt', 'fast', 'prof', 'perf']
1169obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
1170              'gpo' : 'perf'}
1171
1172def identifyTarget(t):
1173    ext = t.split('.')[-1]
1174    if ext in target_types:
1175        return ext
1176    if obj2target.has_key(ext):
1177        return obj2target[ext]
1178    match = re.search(r'/tests/([^/]+)/', t)
1179    if match and match.group(1) in target_types:
1180        return match.group(1)
1181    return 'all'
1182
1183needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
1184if 'all' in needed_envs:
1185    needed_envs += target_types
1186
1187def makeEnvirons(target, source, env):
1188    # cause any later Source() calls to be fatal, as a diagnostic.
1189    Source.done()
1190
1191    # Debug binary
1192    if 'debug' in needed_envs:
1193        makeEnv(env, 'debug', '.do',
1194                CCFLAGS = Split(ccflags['debug']),
1195                CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
1196                LINKFLAGS = Split(ldflags['debug']))
1197
1198    # Optimized binary
1199    if 'opt' in needed_envs:
1200        makeEnv(env, 'opt', '.o',
1201                CCFLAGS = Split(ccflags['opt']),
1202                CPPDEFINES = ['TRACING_ON=1'],
1203                LINKFLAGS = Split(ldflags['opt']))
1204
1205    # "Fast" binary
1206    if 'fast' in needed_envs:
1207        makeEnv(env, 'fast', '.fo', strip = True,
1208                CCFLAGS = Split(ccflags['fast']),
1209                CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1210                LINKFLAGS = Split(ldflags['fast']))
1211
1212    # Profiled binary using gprof
1213    if 'prof' in needed_envs:
1214        makeEnv(env, 'prof', '.po',
1215                CCFLAGS = Split(ccflags['prof']),
1216                CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1217                LINKFLAGS = Split(ldflags['prof']))
1218
1219    # Profiled binary using google-pprof
1220    if 'perf' in needed_envs:
1221        makeEnv(env, 'perf', '.gpo',
1222                CCFLAGS = Split(ccflags['perf']),
1223                CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1224                LINKFLAGS = Split(ldflags['perf']))
1225
1226# The MakeEnvirons Builder defers the full dependency collection until
1227# after processing the ISA definition (due to dynamically generated
1228# source files).  Add this dependency to all targets so they will wait
1229# until the environments are completely set up.  Otherwise, a second
1230# process (e.g. -j2 or higher) will try to compile the requested target,
1231# not know how, and fail.
1232env.Append(BUILDERS = {'MakeEnvirons' :
1233                        Builder(action=MakeAction(makeEnvirons,
1234                                                  Transform("ENVIRONS", 1)))})
1235
1236isa_target = '#${VARIANT_NAME}-deps'
1237environs = '#${VARIANT_NAME}-environs'
1238env.Depends('#all-deps', isa_target)
1239env.Depends('#all-environs', environs)
1240env.ScanISA(isa_target, File('arch/%s/generated/inc.d' % env['TARGET_ISA']))
1241envSetup = env.MakeEnvirons(environs, isa_target)
1242
1243# make sure no -deps targets occur before all ISAs are complete
1244env.Depends(isa_target, '#all-isas')
1245# likewise for -environs targets and all the -deps targets
1246env.Depends(environs, '#all-deps')
1247