SConscript revision 11984
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
4955SN/A# All rights reserved.
5955SN/A#
6955SN/A# Redistribution and use in source and binary forms, with or without
7955SN/A# modification, are permitted provided that the following conditions are
8955SN/A# met: redistributions of source code must retain the above copyright
9955SN/A# notice, this list of conditions and the following disclaimer;
10955SN/A# redistributions in binary form must reproduce the above copyright
11955SN/A# notice, this list of conditions and the following disclaimer in the
12955SN/A# documentation and/or other materials provided with the distribution;
13955SN/A# neither the name of the copyright holders nor the names of its
14955SN/A# contributors may be used to endorse or promote products derived from
15955SN/A# this software without specific prior written permission.
16955SN/A#
17955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
282665Ssaidi@eecs.umich.edu#
294762Snate@binkert.org# Authors: Nathan Binkert
30955SN/A
315522Snate@binkert.orgimport array
326143Snate@binkert.orgimport bisect
334762Snate@binkert.orgimport imp
345522Snate@binkert.orgimport marshal
35955SN/Aimport os
365522Snate@binkert.orgimport re
37955SN/Aimport subprocess
385522Snate@binkert.orgimport sys
394202Sbinkertn@umich.eduimport zlib
405742Snate@binkert.org
41955SN/Afrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
424381Sbinkertn@umich.edu
434381Sbinkertn@umich.eduimport SCons
448334Snate@binkert.org
45955SN/A# This file defines how to build a particular configuration of gem5
46955SN/A# based on variable settings in the 'env' build environment.
474202Sbinkertn@umich.edu
48955SN/AImport('*')
494382Sbinkertn@umich.edu
504382Sbinkertn@umich.edu# Children need to see the environment
514382Sbinkertn@umich.eduExport('env')
526654Snate@binkert.org
535517Snate@binkert.orgbuild_env = [(opt, env[opt]) for opt in export_vars]
548614Sgblack@eecs.umich.edu
557674Snate@binkert.orgfrom m5.util import code_formatter, compareVersions
566143Snate@binkert.org
576143Snate@binkert.org########################################################################
586143Snate@binkert.org# Code for adding source files of various types
598233Snate@binkert.org#
608233Snate@binkert.org# When specifying a source file of some type, a set of guards can be
618233Snate@binkert.org# specified for that file.  When get() is used to find the files, if
628233Snate@binkert.org# get specifies a set of filters, only files that match those filters
638233Snate@binkert.org# will be accepted (unspecified filters on files are assumed to be
648334Snate@binkert.org# false).  Current filters are:
658334Snate@binkert.org#     main -- specifies the gem5 main() function
6610453SAndrew.Bardsley@arm.com#     skip_lib -- do not put this file into the gem5 library
6710453SAndrew.Bardsley@arm.com#     skip_no_python -- do not put this file into a no_python library
688233Snate@binkert.org#       as it embeds compiled Python
698233Snate@binkert.org#     <unittest> -- unit tests use filters based on the unit test name
708233Snate@binkert.org#
718233Snate@binkert.org# A parent can now be specified for a source file and default filter
728233Snate@binkert.org# values will be retrieved recursively from parents (children override
738233Snate@binkert.org# parents).
746143Snate@binkert.org#
758233Snate@binkert.orgdef guarded_source_iterator(sources, **guards):
768233Snate@binkert.org    '''Iterate over a set of sources, gated by a set of guards.'''
778233Snate@binkert.org    for src in sources:
786143Snate@binkert.org        for flag,value in guards.iteritems():
796143Snate@binkert.org            # if the flag is found and has a different value, skip
806143Snate@binkert.org            # this file
816143Snate@binkert.org            if src.all_guards.get(flag, False) != value:
828233Snate@binkert.org                break
838233Snate@binkert.org        else:
848233Snate@binkert.org            yield src
856143Snate@binkert.org
868233Snate@binkert.orgclass SourceMeta(type):
878233Snate@binkert.org    '''Meta class for source files that keeps track of all files of a
888233Snate@binkert.org    particular type and has a get function for finding all functions
898233Snate@binkert.org    of a certain type that match a set of guards'''
906143Snate@binkert.org    def __init__(cls, name, bases, dict):
916143Snate@binkert.org        super(SourceMeta, cls).__init__(name, bases, dict)
926143Snate@binkert.org        cls.all = []
934762Snate@binkert.org
946143Snate@binkert.org    def get(cls, **guards):
958233Snate@binkert.org        '''Find all files that match the specified guards.  If a source
968233Snate@binkert.org        file does not specify a flag, the default is False'''
978233Snate@binkert.org        for s in guarded_source_iterator(cls.all, **guards):
988233Snate@binkert.org            yield s
998233Snate@binkert.org
1006143Snate@binkert.orgclass SourceFile(object):
1018233Snate@binkert.org    '''Base object that encapsulates the notion of a source file.
1028233Snate@binkert.org    This includes, the source node, target node, various manipulations
1038233Snate@binkert.org    of those.  A source file also specifies a set of guards which
1048233Snate@binkert.org    describing which builds the source file applies to.  A parent can
1056143Snate@binkert.org    also be specified to get default guards from'''
1066143Snate@binkert.org    __metaclass__ = SourceMeta
1076143Snate@binkert.org    def __init__(self, source, parent=None, **guards):
1086143Snate@binkert.org        self.guards = guards
1096143Snate@binkert.org        self.parent = parent
1106143Snate@binkert.org
1116143Snate@binkert.org        tnode = source
1126143Snate@binkert.org        if not isinstance(source, SCons.Node.FS.File):
1136143Snate@binkert.org            tnode = File(source)
1147065Snate@binkert.org
1156143Snate@binkert.org        self.tnode = tnode
1168233Snate@binkert.org        self.snode = tnode.srcnode()
1178233Snate@binkert.org
1188233Snate@binkert.org        for base in type(self).__mro__:
1198233Snate@binkert.org            if issubclass(base, SourceFile):
1208233Snate@binkert.org                base.all.append(self)
1218233Snate@binkert.org
1228233Snate@binkert.org    @property
1238233Snate@binkert.org    def filename(self):
1248233Snate@binkert.org        return str(self.tnode)
1258233Snate@binkert.org
1268233Snate@binkert.org    @property
1278233Snate@binkert.org    def dirname(self):
1288233Snate@binkert.org        return dirname(self.filename)
1298233Snate@binkert.org
1308233Snate@binkert.org    @property
1318233Snate@binkert.org    def basename(self):
1328233Snate@binkert.org        return basename(self.filename)
1338233Snate@binkert.org
1348233Snate@binkert.org    @property
1358233Snate@binkert.org    def extname(self):
1368233Snate@binkert.org        index = self.basename.rfind('.')
1378233Snate@binkert.org        if index <= 0:
1388233Snate@binkert.org            # dot files aren't extensions
1398233Snate@binkert.org            return self.basename, None
1408233Snate@binkert.org
1418233Snate@binkert.org        return self.basename[:index], self.basename[index+1:]
1428233Snate@binkert.org
1438233Snate@binkert.org    @property
1448233Snate@binkert.org    def all_guards(self):
1458233Snate@binkert.org        '''find all guards for this object getting default values
1468233Snate@binkert.org        recursively from its parents'''
1476143Snate@binkert.org        guards = {}
1486143Snate@binkert.org        if self.parent:
1496143Snate@binkert.org            guards.update(self.parent.guards)
1506143Snate@binkert.org        guards.update(self.guards)
1516143Snate@binkert.org        return guards
1526143Snate@binkert.org
1539982Satgutier@umich.edu    def __lt__(self, other): return self.filename < other.filename
15410196SCurtis.Dunham@arm.com    def __le__(self, other): return self.filename <= other.filename
15510196SCurtis.Dunham@arm.com    def __gt__(self, other): return self.filename > other.filename
15610196SCurtis.Dunham@arm.com    def __ge__(self, other): return self.filename >= other.filename
15710196SCurtis.Dunham@arm.com    def __eq__(self, other): return self.filename == other.filename
15810196SCurtis.Dunham@arm.com    def __ne__(self, other): return self.filename != other.filename
15910196SCurtis.Dunham@arm.com
16010196SCurtis.Dunham@arm.com    @staticmethod
16110196SCurtis.Dunham@arm.com    def done():
1626143Snate@binkert.org        def disabled(cls, name, *ignored):
1636143Snate@binkert.org            raise RuntimeError("Additional SourceFile '%s'" % name,\
1648945Ssteve.reinhardt@amd.com                  "declared, but targets deps are already fixed.")
1658233Snate@binkert.org        SourceFile.__init__ = disabled
1668233Snate@binkert.org
1676143Snate@binkert.org
1688945Ssteve.reinhardt@amd.comclass Source(SourceFile):
1696143Snate@binkert.org    current_group = None
1706143Snate@binkert.org    source_groups = { None : [] }
1716143Snate@binkert.org
1726143Snate@binkert.org    @classmethod
1735522Snate@binkert.org    def set_group(cls, group):
1746143Snate@binkert.org        if not group in Source.source_groups:
1756143Snate@binkert.org            Source.source_groups[group] = []
1766143Snate@binkert.org        Source.current_group = group
1779982Satgutier@umich.edu
1788233Snate@binkert.org    '''Add a c/c++ source file to the build'''
1798233Snate@binkert.org    def __init__(self, source, Werror=True, swig=False, **guards):
1808233Snate@binkert.org        '''specify the source file, and any guards'''
1816143Snate@binkert.org        super(Source, self).__init__(source, **guards)
1826143Snate@binkert.org
1836143Snate@binkert.org        self.Werror = Werror
1846143Snate@binkert.org        self.swig = swig
1855522Snate@binkert.org
1865522Snate@binkert.org        Source.source_groups[Source.current_group].append(self)
1875522Snate@binkert.org
1885522Snate@binkert.orgclass PySource(SourceFile):
1895604Snate@binkert.org    '''Add a python source file to the named package'''
1905604Snate@binkert.org    invalid_sym_char = re.compile('[^A-z0-9_]')
1916143Snate@binkert.org    modules = {}
1926143Snate@binkert.org    tnodes = {}
1934762Snate@binkert.org    symnames = {}
1944762Snate@binkert.org
1956143Snate@binkert.org    def __init__(self, package, source, **guards):
1966727Ssteve.reinhardt@amd.com        '''specify the python package, the source file, and any guards'''
1976727Ssteve.reinhardt@amd.com        super(PySource, self).__init__(source, **guards)
1986727Ssteve.reinhardt@amd.com
1994762Snate@binkert.org        modname,ext = self.extname
2006143Snate@binkert.org        assert ext == 'py'
2016143Snate@binkert.org
2026143Snate@binkert.org        if package:
2036143Snate@binkert.org            path = package.split('.')
2046727Ssteve.reinhardt@amd.com        else:
2056143Snate@binkert.org            path = []
2067674Snate@binkert.org
2077674Snate@binkert.org        modpath = path[:]
2085604Snate@binkert.org        if modname != '__init__':
2096143Snate@binkert.org            modpath += [ modname ]
2106143Snate@binkert.org        modpath = '.'.join(modpath)
2116143Snate@binkert.org
2124762Snate@binkert.org        arcpath = path + [ self.basename ]
2136143Snate@binkert.org        abspath = self.snode.abspath
2144762Snate@binkert.org        if not exists(abspath):
2154762Snate@binkert.org            abspath = self.tnode.abspath
2164762Snate@binkert.org
2176143Snate@binkert.org        self.package = package
2186143Snate@binkert.org        self.modname = modname
2194762Snate@binkert.org        self.modpath = modpath
2208233Snate@binkert.org        self.arcname = joinpath(*arcpath)
2218233Snate@binkert.org        self.abspath = abspath
2228233Snate@binkert.org        self.compiled = File(self.filename + 'c')
2238233Snate@binkert.org        self.cpp = File(self.filename + '.cc')
2246143Snate@binkert.org        self.symname = PySource.invalid_sym_char.sub('_', modpath)
2256143Snate@binkert.org
2264762Snate@binkert.org        PySource.modules[modpath] = self
2276143Snate@binkert.org        PySource.tnodes[self.tnode] = self
2284762Snate@binkert.org        PySource.symnames[self.symname] = self
2296143Snate@binkert.org
2304762Snate@binkert.orgclass SimObject(PySource):
2316143Snate@binkert.org    '''Add a SimObject python file as a python source object and add
2328233Snate@binkert.org    it to a list of sim object modules'''
2338233Snate@binkert.org
23410453SAndrew.Bardsley@arm.com    fixed = False
2356143Snate@binkert.org    modnames = []
2366143Snate@binkert.org
2376143Snate@binkert.org    def __init__(self, source, **guards):
2386143Snate@binkert.org        '''Specify the source file and any guards (automatically in
2396143Snate@binkert.org        the m5.objects package)'''
2406143Snate@binkert.org        super(SimObject, self).__init__('m5.objects', source, **guards)
2416143Snate@binkert.org        if self.fixed:
2426143Snate@binkert.org            raise AttributeError, "Too late to call SimObject now."
24310453SAndrew.Bardsley@arm.com
24410453SAndrew.Bardsley@arm.com        bisect.insort_right(SimObject.modnames, self.modname)
245955SN/A
2469396Sandreas.hansson@arm.comclass SwigSource(SourceFile):
2479396Sandreas.hansson@arm.com    '''Add a swig file to build'''
2489396Sandreas.hansson@arm.com
2499396Sandreas.hansson@arm.com    def __init__(self, package, source, **guards):
2509396Sandreas.hansson@arm.com        '''Specify the python package, the source file, and any guards'''
2519396Sandreas.hansson@arm.com        super(SwigSource, self).__init__(source, skip_no_python=True, **guards)
2529396Sandreas.hansson@arm.com
2539396Sandreas.hansson@arm.com        modname,ext = self.extname
2549396Sandreas.hansson@arm.com        assert ext == 'i'
2559396Sandreas.hansson@arm.com
2569396Sandreas.hansson@arm.com        self.package = package
2579396Sandreas.hansson@arm.com        self.module = modname
2589396Sandreas.hansson@arm.com        cc_file = joinpath(self.dirname, modname + '_wrap.cc')
2599930Sandreas.hansson@arm.com        py_file = joinpath(self.dirname, modname + '.py')
2609930Sandreas.hansson@arm.com
2619396Sandreas.hansson@arm.com        self.cc_source = Source(cc_file, swig=True, parent=self, **guards)
2628235Snate@binkert.org        self.py_source = PySource(package, py_file, parent=self, **guards)
2638235Snate@binkert.org
2646143Snate@binkert.orgclass ProtoBuf(SourceFile):
2658235Snate@binkert.org    '''Add a Protocol Buffer to build'''
2669003SAli.Saidi@ARM.com
2678235Snate@binkert.org    def __init__(self, source, **guards):
2688235Snate@binkert.org        '''Specify the source file, and any guards'''
2698235Snate@binkert.org        super(ProtoBuf, self).__init__(source, **guards)
2708235Snate@binkert.org
2718235Snate@binkert.org        # Get the file name and the extension
2728235Snate@binkert.org        modname,ext = self.extname
2738235Snate@binkert.org        assert ext == 'proto'
2748235Snate@binkert.org
2758235Snate@binkert.org        # Currently, we stick to generating the C++ headers, so we
2768235Snate@binkert.org        # only need to track the source and header.
2778235Snate@binkert.org        self.cc_file = File(modname + '.pb.cc')
2788235Snate@binkert.org        self.hh_file = File(modname + '.pb.h')
2798235Snate@binkert.org
2808235Snate@binkert.orgclass UnitTest(object):
2819003SAli.Saidi@ARM.com    '''Create a UnitTest'''
2828235Snate@binkert.org
2835584Snate@binkert.org    all = []
2844382Sbinkertn@umich.edu    def __init__(self, target, *sources, **kwargs):
2854202Sbinkertn@umich.edu        '''Specify the target name and any sources.  Sources that are
2864382Sbinkertn@umich.edu        not SourceFiles are evalued with Source().  All files are
2874382Sbinkertn@umich.edu        guarded with a guard of the same name as the UnitTest
2884382Sbinkertn@umich.edu        target.'''
2899396Sandreas.hansson@arm.com
2905584Snate@binkert.org        srcs = []
2914382Sbinkertn@umich.edu        for src in sources:
2924382Sbinkertn@umich.edu            if not isinstance(src, SourceFile):
2934382Sbinkertn@umich.edu                src = Source(src, skip_lib=True)
2948232Snate@binkert.org            src.guards[target] = True
2955192Ssaidi@eecs.umich.edu            srcs.append(src)
2968232Snate@binkert.org
2978232Snate@binkert.org        self.sources = srcs
2988232Snate@binkert.org        self.target = target
2995192Ssaidi@eecs.umich.edu        self.main = kwargs.get('main', False)
3008232Snate@binkert.org        UnitTest.all.append(self)
3015192Ssaidi@eecs.umich.edu
3025799Snate@binkert.org# Children should have access
3038232Snate@binkert.orgExport('Source')
3045192Ssaidi@eecs.umich.eduExport('PySource')
3055192Ssaidi@eecs.umich.eduExport('SimObject')
3065192Ssaidi@eecs.umich.eduExport('SwigSource')
3078232Snate@binkert.orgExport('ProtoBuf')
3085192Ssaidi@eecs.umich.eduExport('UnitTest')
3098232Snate@binkert.org
3105192Ssaidi@eecs.umich.edu########################################################################
3115192Ssaidi@eecs.umich.edu#
3125192Ssaidi@eecs.umich.edu# Debug Flags
3135192Ssaidi@eecs.umich.edu#
3144382Sbinkertn@umich.edudebug_flags = {}
3154382Sbinkertn@umich.edudef DebugFlag(name, desc=None):
3164382Sbinkertn@umich.edu    if name in debug_flags:
3172667Sstever@eecs.umich.edu        raise AttributeError, "Flag %s already specified" % name
3182667Sstever@eecs.umich.edu    debug_flags[name] = (name, (), desc)
3192667Sstever@eecs.umich.edu
3202667Sstever@eecs.umich.edudef CompoundFlag(name, flags, desc=None):
3212667Sstever@eecs.umich.edu    if name in debug_flags:
3222667Sstever@eecs.umich.edu        raise AttributeError, "Flag %s already specified" % name
3235742Snate@binkert.org
3245742Snate@binkert.org    compound = tuple(flags)
3255742Snate@binkert.org    debug_flags[name] = (name, compound, desc)
3265793Snate@binkert.org
3278334Snate@binkert.orgExport('DebugFlag')
3285793Snate@binkert.orgExport('CompoundFlag')
3295793Snate@binkert.org
3305793Snate@binkert.org########################################################################
3314382Sbinkertn@umich.edu#
3324762Snate@binkert.org# Set some compiler variables
3335344Sstever@gmail.com#
3344382Sbinkertn@umich.edu
3355341Sstever@gmail.com# Include file paths are rooted in this directory.  SCons will
3365742Snate@binkert.org# automatically expand '.' to refer to both the source directory and
3375742Snate@binkert.org# the corresponding build directory to pick up generated include
3385742Snate@binkert.org# files.
3395742Snate@binkert.orgenv.Append(CPPPATH=Dir('.'))
3405742Snate@binkert.org
3414762Snate@binkert.orgfor extra_dir in extras_dir_list:
3425742Snate@binkert.org    env.Append(CPPPATH=Dir(extra_dir))
3435742Snate@binkert.org
3447722Sgblack@eecs.umich.edu# Workaround for bug in SCons version > 0.97d20071212
3455742Snate@binkert.org# Scons bug id: 2006 gem5 Bug id: 308
3465742Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
3475742Snate@binkert.org    Dir(root[len(base_dir) + 1:])
3489930Sandreas.hansson@arm.com
3499930Sandreas.hansson@arm.com########################################################################
3509930Sandreas.hansson@arm.com#
3519930Sandreas.hansson@arm.com# Walk the tree and execute all SConscripts in subdirectories
3529930Sandreas.hansson@arm.com#
3535742Snate@binkert.org
3548242Sbradley.danofsky@amd.comhere = Dir('.').srcnode().abspath
3558242Sbradley.danofsky@amd.comfor root, dirs, files in os.walk(base_dir, topdown=True):
3568242Sbradley.danofsky@amd.com    if root == here:
3578242Sbradley.danofsky@amd.com        # we don't want to recurse back into this SConscript
3585341Sstever@gmail.com        continue
3595742Snate@binkert.org
3607722Sgblack@eecs.umich.edu    if 'SConscript' in files:
3614773Snate@binkert.org        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
3626108Snate@binkert.org        Source.set_group(build_dir)
3631858SN/A        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3641085SN/A
3656658Snate@binkert.orgfor extra_dir in extras_dir_list:
3666658Snate@binkert.org    prefix_len = len(dirname(extra_dir)) + 1
3677673Snate@binkert.org
3686658Snate@binkert.org    # Also add the corresponding build directory to pick up generated
3696658Snate@binkert.org    # include files.
3706658Snate@binkert.org    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
3716658Snate@binkert.org
3726658Snate@binkert.org    for root, dirs, files in os.walk(extra_dir, topdown=True):
3736658Snate@binkert.org        # if build lives in the extras directory, don't walk down it
3746658Snate@binkert.org        if 'build' in dirs:
3757673Snate@binkert.org            dirs.remove('build')
3767673Snate@binkert.org
3777673Snate@binkert.org        if 'SConscript' in files:
3787673Snate@binkert.org            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
3797673Snate@binkert.org            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3807673Snate@binkert.org
3817673Snate@binkert.orgfor opt in export_vars:
38210467Sandreas.hansson@arm.com    env.ConfigFile(opt)
3836658Snate@binkert.org
3847673Snate@binkert.orgdef makeTheISA(source, target, env):
38510467Sandreas.hansson@arm.com    isas = [ src.get_contents() for src in source ]
38610467Sandreas.hansson@arm.com    target_isa = env['TARGET_ISA']
38710467Sandreas.hansson@arm.com    def define(isa):
38810467Sandreas.hansson@arm.com        return isa.upper() + '_ISA'
38910467Sandreas.hansson@arm.com
39010467Sandreas.hansson@arm.com    def namespace(isa):
39110467Sandreas.hansson@arm.com        return isa[0].upper() + isa[1:].lower() + 'ISA'
39210467Sandreas.hansson@arm.com
39310467Sandreas.hansson@arm.com
39410467Sandreas.hansson@arm.com    code = code_formatter()
39510467Sandreas.hansson@arm.com    code('''\
3967673Snate@binkert.org#ifndef __CONFIG_THE_ISA_HH__
3977673Snate@binkert.org#define __CONFIG_THE_ISA_HH__
3987673Snate@binkert.org
3997673Snate@binkert.org''')
4007673Snate@binkert.org
4019048SAli.Saidi@ARM.com    # create defines for the preprocessing and compile-time determination
4027673Snate@binkert.org    for i,isa in enumerate(isas):
4037673Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
4047673Snate@binkert.org    code()
4057673Snate@binkert.org
4066658Snate@binkert.org    # create an enum for any run-time determination of the ISA, we
4077756SAli.Saidi@ARM.com    # reuse the same name as the namespaces
4087816Ssteve.reinhardt@amd.com    code('enum class Arch {')
4096658Snate@binkert.org    for i,isa in enumerate(isas):
4104382Sbinkertn@umich.edu        if i + 1 == len(isas):
4114382Sbinkertn@umich.edu            code('  $0 = $1', namespace(isa), define(isa))
4124762Snate@binkert.org        else:
4134762Snate@binkert.org            code('  $0 = $1,', namespace(isa), define(isa))
4144762Snate@binkert.org    code('};')
4156654Snate@binkert.org
4166654Snate@binkert.org    code('''
4175517Snate@binkert.org
4185517Snate@binkert.org#define THE_ISA ${{define(target_isa)}}
4195517Snate@binkert.org#define TheISA ${{namespace(target_isa)}}
4205517Snate@binkert.org#define THE_ISA_STR "${{target_isa}}"
4215517Snate@binkert.org
4225517Snate@binkert.org#endif // __CONFIG_THE_ISA_HH__''')
4235517Snate@binkert.org
4245517Snate@binkert.org    code.write(str(target[0]))
4255517Snate@binkert.org
4265517Snate@binkert.orgenv.Command('config/the_isa.hh', map(Value, all_isa_list),
4275517Snate@binkert.org            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
4285517Snate@binkert.org
4295517Snate@binkert.orgdef makeTheGPUISA(source, target, env):
4305517Snate@binkert.org    isas = [ src.get_contents() for src in source ]
4315517Snate@binkert.org    target_gpu_isa = env['TARGET_GPU_ISA']
4325517Snate@binkert.org    def define(isa):
4335517Snate@binkert.org        return isa.upper() + '_ISA'
4346654Snate@binkert.org
4355517Snate@binkert.org    def namespace(isa):
4365517Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA'
4375517Snate@binkert.org
4385517Snate@binkert.org
4395517Snate@binkert.org    code = code_formatter()
4405517Snate@binkert.org    code('''\
4415517Snate@binkert.org#ifndef __CONFIG_THE_GPU_ISA_HH__
4425517Snate@binkert.org#define __CONFIG_THE_GPU_ISA_HH__
4436143Snate@binkert.org
4446654Snate@binkert.org''')
4455517Snate@binkert.org
4465517Snate@binkert.org    # create defines for the preprocessing and compile-time determination
4475517Snate@binkert.org    for i,isa in enumerate(isas):
4485517Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
4495517Snate@binkert.org    code()
4505517Snate@binkert.org
4515517Snate@binkert.org    # create an enum for any run-time determination of the ISA, we
4525517Snate@binkert.org    # reuse the same name as the namespaces
4535517Snate@binkert.org    code('enum class GPUArch {')
4545517Snate@binkert.org    for i,isa in enumerate(isas):
4555517Snate@binkert.org        if i + 1 == len(isas):
4565517Snate@binkert.org            code('  $0 = $1', namespace(isa), define(isa))
4575517Snate@binkert.org        else:
4585517Snate@binkert.org            code('  $0 = $1,', namespace(isa), define(isa))
4596654Snate@binkert.org    code('};')
4606654Snate@binkert.org
4615517Snate@binkert.org    code('''
4625517Snate@binkert.org
4636143Snate@binkert.org#define THE_GPU_ISA ${{define(target_gpu_isa)}}
4646143Snate@binkert.org#define TheGpuISA ${{namespace(target_gpu_isa)}}
4656143Snate@binkert.org#define THE_GPU_ISA_STR "${{target_gpu_isa}}"
4666727Ssteve.reinhardt@amd.com
4675517Snate@binkert.org#endif // __CONFIG_THE_GPU_ISA_HH__''')
4686727Ssteve.reinhardt@amd.com
4695517Snate@binkert.org    code.write(str(target[0]))
4705517Snate@binkert.org
4715517Snate@binkert.orgenv.Command('config/the_gpu_isa.hh', map(Value, all_gpu_isa_list),
4726654Snate@binkert.org            MakeAction(makeTheGPUISA, Transform("CFG ISA", 0)))
4736654Snate@binkert.org
4747673Snate@binkert.org########################################################################
4756654Snate@binkert.org#
4766654Snate@binkert.org# Prevent any SimObjects from being added after this point, they
4776654Snate@binkert.org# should all have been added in the SConscripts above
4786654Snate@binkert.org#
4795517Snate@binkert.orgSimObject.fixed = True
4805517Snate@binkert.org
4815517Snate@binkert.orgclass DictImporter(object):
4826143Snate@binkert.org    '''This importer takes a dictionary of arbitrary module names that
4835517Snate@binkert.org    map to arbitrary filenames.'''
4844762Snate@binkert.org    def __init__(self, modules):
4855517Snate@binkert.org        self.modules = modules
4865517Snate@binkert.org        self.installed = set()
4876143Snate@binkert.org
4886143Snate@binkert.org    def __del__(self):
4895517Snate@binkert.org        self.unload()
4905517Snate@binkert.org
4915517Snate@binkert.org    def unload(self):
4925517Snate@binkert.org        import sys
4935517Snate@binkert.org        for module in self.installed:
4945517Snate@binkert.org            del sys.modules[module]
4955517Snate@binkert.org        self.installed = set()
4965517Snate@binkert.org
4975517Snate@binkert.org    def find_module(self, fullname, path):
4989338SAndreas.Sandberg@arm.com        if fullname == 'm5.defines':
4999338SAndreas.Sandberg@arm.com            return self
5009338SAndreas.Sandberg@arm.com
5019338SAndreas.Sandberg@arm.com        if fullname == 'm5.objects':
5029338SAndreas.Sandberg@arm.com            return self
5039338SAndreas.Sandberg@arm.com
5048596Ssteve.reinhardt@amd.com        if fullname.startswith('_m5'):
5058596Ssteve.reinhardt@amd.com            return None
5068596Ssteve.reinhardt@amd.com
5078596Ssteve.reinhardt@amd.com        source = self.modules.get(fullname, None)
5088596Ssteve.reinhardt@amd.com        if source is not None and fullname.startswith('m5.objects'):
5098596Ssteve.reinhardt@amd.com            return self
5108596Ssteve.reinhardt@amd.com
5116143Snate@binkert.org        return None
5125517Snate@binkert.org
5136654Snate@binkert.org    def load_module(self, fullname):
5146654Snate@binkert.org        mod = imp.new_module(fullname)
5156654Snate@binkert.org        sys.modules[fullname] = mod
5166654Snate@binkert.org        self.installed.add(fullname)
5176654Snate@binkert.org
5186654Snate@binkert.org        mod.__loader__ = self
5195517Snate@binkert.org        if fullname == 'm5.objects':
5205517Snate@binkert.org            mod.__path__ = fullname.split('.')
5215517Snate@binkert.org            return mod
5228596Ssteve.reinhardt@amd.com
5238596Ssteve.reinhardt@amd.com        if fullname == 'm5.defines':
5244762Snate@binkert.org            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
5254762Snate@binkert.org            return mod
5264762Snate@binkert.org
5274762Snate@binkert.org        source = self.modules[fullname]
5284762Snate@binkert.org        if source.modname == '__init__':
5294762Snate@binkert.org            mod.__path__ = source.modpath
5307675Snate@binkert.org        mod.__file__ = source.abspath
53110584Sandreas.hansson@arm.com
5324762Snate@binkert.org        exec file(source.abspath, 'r') in mod.__dict__
5334762Snate@binkert.org
5344762Snate@binkert.org        return mod
5354762Snate@binkert.org
5364382Sbinkertn@umich.eduimport m5.SimObject
5374382Sbinkertn@umich.eduimport m5.params
5385517Snate@binkert.orgfrom m5.util import code_formatter
5396654Snate@binkert.org
5405517Snate@binkert.orgm5.SimObject.clear()
5418126Sgblack@eecs.umich.edum5.params.clear()
5426654Snate@binkert.org
5437673Snate@binkert.org# install the python importer so we can grab stuff from the source
5446654Snate@binkert.org# tree itself.  We can't have SimObjects added after this point or
5456654Snate@binkert.org# else we won't know about them for the rest of the stuff.
5466654Snate@binkert.orgimporter = DictImporter(PySource.modules)
5476654Snate@binkert.orgsys.meta_path[0:0] = [ importer ]
5486654Snate@binkert.org
5496654Snate@binkert.org# import all sim objects so we can populate the all_objects list
5506654Snate@binkert.org# make sure that we're working with a list, then let's sort it
5516669Snate@binkert.orgfor modname in SimObject.modnames:
5526669Snate@binkert.org    exec('from m5.objects import %s' % modname)
5536669Snate@binkert.org
5546669Snate@binkert.org# we need to unload all of the currently imported modules so that they
5556669Snate@binkert.org# will be re-imported the next time the sconscript is run
5566669Snate@binkert.orgimporter.unload()
5576654Snate@binkert.orgsys.meta_path.remove(importer)
5587673Snate@binkert.org
5595517Snate@binkert.orgsim_objects = m5.SimObject.allClasses
5608126Sgblack@eecs.umich.eduall_enums = m5.params.allEnums
5615798Snate@binkert.org
5627756SAli.Saidi@ARM.comif m5.SimObject.noCxxHeader:
5637816Ssteve.reinhardt@amd.com    print >> sys.stderr, \
5645798Snate@binkert.org        "warning: At least one SimObject lacks a header specification. " \
5655798Snate@binkert.org        "This can cause unexpected results in the generated SWIG " \
5665517Snate@binkert.org        "wrappers."
5675517Snate@binkert.org
5687673Snate@binkert.org# Find param types that need to be explicitly wrapped with swig.
5695517Snate@binkert.org# These will be recognized because the ParamDesc will have a
5705517Snate@binkert.org# swig_decl() method.  Most param types are based on types that don't
5717673Snate@binkert.org# need this, either because they're based on native types (like Int)
5727673Snate@binkert.org# or because they're SimObjects (which get swigged independently).
5735517Snate@binkert.org# For now the only things handled here are VectorParam types.
5745798Snate@binkert.orgparams_to_swig = {}
5755798Snate@binkert.orgfor name,obj in sorted(sim_objects.iteritems()):
5768333Snate@binkert.org    for param in obj._params.local.values():
5777816Ssteve.reinhardt@amd.com        # load the ptype attribute now because it depends on the
5785798Snate@binkert.org        # current version of SimObject.allClasses, but when scons
5795798Snate@binkert.org        # actually uses the value, all versions of
5804762Snate@binkert.org        # SimObject.allClasses will have been loaded
5814762Snate@binkert.org        param.ptype
5824762Snate@binkert.org
5834762Snate@binkert.org        if not hasattr(param, 'swig_decl'):
5844762Snate@binkert.org            continue
5858596Ssteve.reinhardt@amd.com        pname = param.ptype_str
5865517Snate@binkert.org        if pname not in params_to_swig:
5875517Snate@binkert.org            params_to_swig[pname] = param
5885517Snate@binkert.org
5895517Snate@binkert.org########################################################################
5905517Snate@binkert.org#
5917673Snate@binkert.org# calculate extra dependencies
5928596Ssteve.reinhardt@amd.com#
5937673Snate@binkert.orgmodule_depends = ["m5", "m5.SimObject", "m5.params"]
5945517Snate@binkert.orgdepends = [ PySource.modules[dep].snode for dep in module_depends ]
59510458Sandreas.hansson@arm.comdepends.sort(key = lambda x: x.name)
59610458Sandreas.hansson@arm.com
59710458Sandreas.hansson@arm.com########################################################################
59810458Sandreas.hansson@arm.com#
59910458Sandreas.hansson@arm.com# Commands for the basic automatically generated python files
60010458Sandreas.hansson@arm.com#
60110458Sandreas.hansson@arm.com
60210458Sandreas.hansson@arm.com# Generate Python file containing a dict specifying the current
60310458Sandreas.hansson@arm.com# buildEnv flags.
60410458Sandreas.hansson@arm.comdef makeDefinesPyFile(target, source, env):
60510458Sandreas.hansson@arm.com    build_env = source[0].get_contents()
60610458Sandreas.hansson@arm.com
6078596Ssteve.reinhardt@amd.com    code = code_formatter()
6085517Snate@binkert.org    code("""
6095517Snate@binkert.orgimport _m5.core
6105517Snate@binkert.orgimport m5.util
6118596Ssteve.reinhardt@amd.com
6125517Snate@binkert.orgbuildEnv = m5.util.SmartDict($build_env)
6137673Snate@binkert.org
6147673Snate@binkert.orgcompileDate = _m5.core.compileDate
6157673Snate@binkert.org_globals = globals()
6165517Snate@binkert.orgfor key,val in _m5.core.__dict__.iteritems():
6175517Snate@binkert.org    if key.startswith('flag_'):
6185517Snate@binkert.org        flag = key[5:]
6195517Snate@binkert.org        _globals[flag] = val
6205517Snate@binkert.orgdel _globals
6215517Snate@binkert.org""")
6225517Snate@binkert.org    code.write(target[0].abspath)
6237673Snate@binkert.org
6247673Snate@binkert.orgdefines_info = Value(build_env)
6257673Snate@binkert.org# Generate a file with all of the compile options in it
6265517Snate@binkert.orgenv.Command('python/m5/defines.py', defines_info,
6278596Ssteve.reinhardt@amd.com            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
6285517Snate@binkert.orgPySource('m5', 'python/m5/defines.py')
6295517Snate@binkert.org
6305517Snate@binkert.org# Generate python file containing info about the M5 source code
6315517Snate@binkert.orgdef makeInfoPyFile(target, source, env):
6325517Snate@binkert.org    code = code_formatter()
6337673Snate@binkert.org    for src in source:
6347673Snate@binkert.org        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
6357673Snate@binkert.org        code('$src = ${{repr(data)}}')
6365517Snate@binkert.org    code.write(str(target[0]))
6378596Ssteve.reinhardt@amd.com
6387675Snate@binkert.org# Generate a file that wraps the basic top level files
6397675Snate@binkert.orgenv.Command('python/m5/info.py',
6407675Snate@binkert.org            [ '#/COPYING', '#/LICENSE', '#/README', ],
6417675Snate@binkert.org            MakeAction(makeInfoPyFile, Transform("INFO")))
6427675Snate@binkert.orgPySource('m5', 'python/m5/info.py')
6437675Snate@binkert.org
6448596Ssteve.reinhardt@amd.com########################################################################
6457675Snate@binkert.org#
6467675Snate@binkert.org# Create all of the SimObject param headers and enum headers
6478596Ssteve.reinhardt@amd.com#
6488596Ssteve.reinhardt@amd.com
6498596Ssteve.reinhardt@amd.comdef createSimObjectParamStruct(target, source, env):
6508596Ssteve.reinhardt@amd.com    assert len(target) == 1 and len(source) == 1
6518596Ssteve.reinhardt@amd.com
6528596Ssteve.reinhardt@amd.com    name = str(source[0].get_contents())
6538596Ssteve.reinhardt@amd.com    obj = sim_objects[name]
6548596Ssteve.reinhardt@amd.com
65510454SCurtis.Dunham@arm.com    code = code_formatter()
65610454SCurtis.Dunham@arm.com    obj.cxx_param_decl(code)
65710454SCurtis.Dunham@arm.com    code.write(target[0].abspath)
65810454SCurtis.Dunham@arm.com
6598596Ssteve.reinhardt@amd.comdef createSimObjectCxxConfig(is_header):
6604762Snate@binkert.org    def body(target, source, env):
6616143Snate@binkert.org        assert len(target) == 1 and len(source) == 1
6626143Snate@binkert.org
6636143Snate@binkert.org        name = str(source[0].get_contents())
6644762Snate@binkert.org        obj = sim_objects[name]
6654762Snate@binkert.org
6664762Snate@binkert.org        code = code_formatter()
6677756SAli.Saidi@ARM.com        obj.cxx_config_param_file(code, is_header)
6688596Ssteve.reinhardt@amd.com        code.write(target[0].abspath)
6694762Snate@binkert.org    return body
67010454SCurtis.Dunham@arm.com
6714762Snate@binkert.orgdef createParamSwigWrapper(target, source, env):
67210458Sandreas.hansson@arm.com    assert len(target) == 1 and len(source) == 1
67310458Sandreas.hansson@arm.com
67410458Sandreas.hansson@arm.com    name = str(source[0].get_contents())
67510458Sandreas.hansson@arm.com    param = params_to_swig[name]
67610458Sandreas.hansson@arm.com
67710458Sandreas.hansson@arm.com    code = code_formatter()
67810458Sandreas.hansson@arm.com    param.swig_decl(code)
67910458Sandreas.hansson@arm.com    code.write(target[0].abspath)
68010458Sandreas.hansson@arm.com
68110458Sandreas.hansson@arm.comdef createEnumStrings(target, source, env):
68210458Sandreas.hansson@arm.com    assert len(target) == 1 and len(source) == 1
68310458Sandreas.hansson@arm.com
68410458Sandreas.hansson@arm.com    name = str(source[0].get_contents())
68510458Sandreas.hansson@arm.com    obj = all_enums[name]
68610458Sandreas.hansson@arm.com
68710458Sandreas.hansson@arm.com    code = code_formatter()
68810458Sandreas.hansson@arm.com    obj.cxx_def(code)
68910458Sandreas.hansson@arm.com    code.write(target[0].abspath)
69010458Sandreas.hansson@arm.com
69110458Sandreas.hansson@arm.comdef createEnumDecls(target, source, env):
69210458Sandreas.hansson@arm.com    assert len(target) == 1 and len(source) == 1
69310458Sandreas.hansson@arm.com
69410458Sandreas.hansson@arm.com    name = str(source[0].get_contents())
69510458Sandreas.hansson@arm.com    obj = all_enums[name]
69610458Sandreas.hansson@arm.com
69710458Sandreas.hansson@arm.com    code = code_formatter()
69810458Sandreas.hansson@arm.com    obj.cxx_decl(code)
69910458Sandreas.hansson@arm.com    code.write(target[0].abspath)
70010458Sandreas.hansson@arm.com
70110458Sandreas.hansson@arm.comdef createEnumSwigWrapper(target, source, env):
70210458Sandreas.hansson@arm.com    assert len(target) == 1 and len(source) == 1
70310458Sandreas.hansson@arm.com
70410458Sandreas.hansson@arm.com    name = str(source[0].get_contents())
70510458Sandreas.hansson@arm.com    obj = all_enums[name]
70610458Sandreas.hansson@arm.com
70710458Sandreas.hansson@arm.com    code = code_formatter()
70810458Sandreas.hansson@arm.com    obj.swig_decl(code)
70910458Sandreas.hansson@arm.com    code.write(target[0].abspath)
71010458Sandreas.hansson@arm.com
71110458Sandreas.hansson@arm.comdef createSimObjectSwigWrapper(target, source, env):
71210458Sandreas.hansson@arm.com    name = source[0].get_contents()
71310458Sandreas.hansson@arm.com    obj = sim_objects[name]
71410458Sandreas.hansson@arm.com
71510458Sandreas.hansson@arm.com    code = code_formatter()
71610458Sandreas.hansson@arm.com    obj.swig_decl(code)
71710458Sandreas.hansson@arm.com    code.write(target[0].abspath)
71810458Sandreas.hansson@arm.com
71910458Sandreas.hansson@arm.com# dummy target for generated code
72010458Sandreas.hansson@arm.com# we start out with all the Source files so they get copied to build/*/ also.
72110584Sandreas.hansson@arm.comSWIG = env.Dummy('swig', [s.tnode for s in Source.get()])
72210458Sandreas.hansson@arm.com
72310458Sandreas.hansson@arm.com# Generate all of the SimObject param C++ struct header files
72410458Sandreas.hansson@arm.comparams_hh_files = []
72510458Sandreas.hansson@arm.comfor name,simobj in sorted(sim_objects.iteritems()):
72610458Sandreas.hansson@arm.com    py_source = PySource.modules[simobj.__module__]
7278596Ssteve.reinhardt@amd.com    extra_deps = [ py_source.tnode ]
7285463Snate@binkert.org
72910584Sandreas.hansson@arm.com    hh_file = File('params/%s.hh' % name)
7308596Ssteve.reinhardt@amd.com    params_hh_files.append(hh_file)
7315463Snate@binkert.org    env.Command(hh_file, Value(name),
7327756SAli.Saidi@ARM.com                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
7338596Ssteve.reinhardt@amd.com    env.Depends(hh_file, depends + extra_deps)
7344762Snate@binkert.org    env.Depends(SWIG, hh_file)
73510454SCurtis.Dunham@arm.com
7367677Snate@binkert.org# C++ parameter description files
7374762Snate@binkert.orgif GetOption('with_cxx_config'):
7384762Snate@binkert.org    for name,simobj in sorted(sim_objects.iteritems()):
7396143Snate@binkert.org        py_source = PySource.modules[simobj.__module__]
7406143Snate@binkert.org        extra_deps = [ py_source.tnode ]
7416143Snate@binkert.org
7424762Snate@binkert.org        cxx_config_hh_file = File('cxx_config/%s.hh' % name)
7434762Snate@binkert.org        cxx_config_cc_file = File('cxx_config/%s.cc' % name)
7447756SAli.Saidi@ARM.com        env.Command(cxx_config_hh_file, Value(name),
7457816Ssteve.reinhardt@amd.com                    MakeAction(createSimObjectCxxConfig(True),
7464762Snate@binkert.org                    Transform("CXXCPRHH")))
74710454SCurtis.Dunham@arm.com        env.Command(cxx_config_cc_file, Value(name),
7484762Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(False),
7494762Snate@binkert.org                    Transform("CXXCPRCC")))
7504762Snate@binkert.org        env.Depends(cxx_config_hh_file, depends + extra_deps +
7517756SAli.Saidi@ARM.com                    [File('params/%s.hh' % name), File('sim/cxx_config.hh')])
7528596Ssteve.reinhardt@amd.com        env.Depends(cxx_config_cc_file, depends + extra_deps +
7534762Snate@binkert.org                    [cxx_config_hh_file])
75410454SCurtis.Dunham@arm.com        Source(cxx_config_cc_file)
7554762Snate@binkert.org
7567677Snate@binkert.org    cxx_config_init_cc_file = File('cxx_config/init.cc')
7577756SAli.Saidi@ARM.com
7588596Ssteve.reinhardt@amd.com    def createCxxConfigInitCC(target, source, env):
7597675Snate@binkert.org        assert len(target) == 1 and len(source) == 1
76010454SCurtis.Dunham@arm.com
7617677Snate@binkert.org        code = code_formatter()
7625517Snate@binkert.org
7638596Ssteve.reinhardt@amd.com        for name,simobj in sorted(sim_objects.iteritems()):
76410584Sandreas.hansson@arm.com            if not hasattr(simobj, 'abstract') or not simobj.abstract:
7659248SAndreas.Sandberg@arm.com                code('#include "cxx_config/${name}.hh"')
7669248SAndreas.Sandberg@arm.com        code()
7678596Ssteve.reinhardt@amd.com        code('void cxxConfigInit()')
7688596Ssteve.reinhardt@amd.com        code('{')
7698596Ssteve.reinhardt@amd.com        code.indent()
7709248SAndreas.Sandberg@arm.com        for name,simobj in sorted(sim_objects.iteritems()):
7718596Ssteve.reinhardt@amd.com            not_abstract = not hasattr(simobj, 'abstract') or \
7724762Snate@binkert.org                not simobj.abstract
7737674Snate@binkert.org            if not_abstract and 'type' in simobj.__dict__:
7747674Snate@binkert.org                code('cxx_config_directory["${name}"] = '
7757674Snate@binkert.org                     '${name}CxxConfigParams::makeDirectoryEntry();')
7767674Snate@binkert.org        code.dedent()
7777674Snate@binkert.org        code('}')
7787674Snate@binkert.org        code.write(target[0].abspath)
7797674Snate@binkert.org
7807674Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
7817674Snate@binkert.org    extra_deps = [ py_source.tnode ]
7827674Snate@binkert.org    env.Command(cxx_config_init_cc_file, Value(name),
7837674Snate@binkert.org        MakeAction(createCxxConfigInitCC, Transform("CXXCINIT")))
7847674Snate@binkert.org    cxx_param_hh_files = ["cxx_config/%s.hh" % simobj
7857674Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems())
7867674Snate@binkert.org        if not hasattr(simobj, 'abstract') or not simobj.abstract]
7877674Snate@binkert.org    Depends(cxx_config_init_cc_file, cxx_param_hh_files +
7884762Snate@binkert.org            [File('sim/cxx_config.hh')])
7896143Snate@binkert.org    Source(cxx_config_init_cc_file)
7906143Snate@binkert.org
7917756SAli.Saidi@ARM.com# Generate any needed param SWIG wrapper files
7927816Ssteve.reinhardt@amd.comparams_i_files = []
7938235Snate@binkert.orgfor name,param in sorted(params_to_swig.iteritems()):
7948596Ssteve.reinhardt@amd.com    i_file = File('python/_m5/%s.i' % (param.swig_module_name()))
7957756SAli.Saidi@ARM.com    params_i_files.append(i_file)
7967816Ssteve.reinhardt@amd.com    env.Command(i_file, Value(name),
79710454SCurtis.Dunham@arm.com                MakeAction(createParamSwigWrapper, Transform("SW PARAM")))
7988235Snate@binkert.org    env.Depends(i_file, depends)
7994382Sbinkertn@umich.edu    env.Depends(SWIG, i_file)
8009396Sandreas.hansson@arm.com    SwigSource('_m5', i_file)
8019396Sandreas.hansson@arm.com
8029396Sandreas.hansson@arm.com# Generate all enum header files
8039396Sandreas.hansson@arm.comfor name,enum in sorted(all_enums.iteritems()):
8049396Sandreas.hansson@arm.com    py_source = PySource.modules[enum.__module__]
8059396Sandreas.hansson@arm.com    extra_deps = [ py_source.tnode ]
8069396Sandreas.hansson@arm.com
8079396Sandreas.hansson@arm.com    cc_file = File('enums/%s.cc' % name)
8089396Sandreas.hansson@arm.com    env.Command(cc_file, Value(name),
8099396Sandreas.hansson@arm.com                MakeAction(createEnumStrings, Transform("ENUM STR")))
8109396Sandreas.hansson@arm.com    env.Depends(cc_file, depends + extra_deps)
8119396Sandreas.hansson@arm.com    env.Depends(SWIG, cc_file)
81210454SCurtis.Dunham@arm.com    Source(cc_file)
8139396Sandreas.hansson@arm.com
8149396Sandreas.hansson@arm.com    hh_file = File('enums/%s.hh' % name)
8159396Sandreas.hansson@arm.com    env.Command(hh_file, Value(name),
8169396Sandreas.hansson@arm.com                MakeAction(createEnumDecls, Transform("ENUMDECL")))
8179396Sandreas.hansson@arm.com    env.Depends(hh_file, depends + extra_deps)
8189396Sandreas.hansson@arm.com    env.Depends(SWIG, hh_file)
8198232Snate@binkert.org
8208232Snate@binkert.org    i_file = File('python/_m5/enum_%s.i' % name)
8218232Snate@binkert.org    env.Command(i_file, Value(name),
8228232Snate@binkert.org                MakeAction(createEnumSwigWrapper, Transform("ENUMSWIG")))
8238232Snate@binkert.org    env.Depends(i_file, depends + extra_deps)
8246229Snate@binkert.org    env.Depends(SWIG, i_file)
82510455SCurtis.Dunham@arm.com    SwigSource('_m5', i_file)
8266229Snate@binkert.org
82710455SCurtis.Dunham@arm.com# Generate SimObject SWIG wrapper files
82810455SCurtis.Dunham@arm.comfor name,simobj in sorted(sim_objects.iteritems()):
82910455SCurtis.Dunham@arm.com    py_source = PySource.modules[simobj.__module__]
8305517Snate@binkert.org    extra_deps = [ py_source.tnode ]
8315517Snate@binkert.org    i_file = File('python/_m5/param_%s.i' % name)
8327673Snate@binkert.org    env.Command(i_file, Value(name),
8335517Snate@binkert.org                MakeAction(createSimObjectSwigWrapper, Transform("SO SWIG")))
83410455SCurtis.Dunham@arm.com    env.Depends(i_file, depends + extra_deps)
8355517Snate@binkert.org    SwigSource('_m5', i_file)
8365517Snate@binkert.org
8378232Snate@binkert.org# Generate the main swig init file
83810455SCurtis.Dunham@arm.comdef makeEmbeddedSwigInit(package):
83910455SCurtis.Dunham@arm.com    def body(target, source, env):
84010455SCurtis.Dunham@arm.com        assert len(target) == 1 and len(source) == 1
8417673Snate@binkert.org
8427673Snate@binkert.org        code = code_formatter()
84310455SCurtis.Dunham@arm.com        module = source[0].get_contents()
84410455SCurtis.Dunham@arm.com        # Provide the full context so that the swig-generated call to
84510455SCurtis.Dunham@arm.com        # Py_InitModule ends up placing the embedded module in the
8465517Snate@binkert.org        # right package.
84710455SCurtis.Dunham@arm.com        context = str(package) + "._" + str(module)
84810455SCurtis.Dunham@arm.com        code('''\
84910455SCurtis.Dunham@arm.com        #include "sim/init.hh"
85010455SCurtis.Dunham@arm.com
85110455SCurtis.Dunham@arm.com        extern "C" {
85210455SCurtis.Dunham@arm.com            void init_${module}();
85310455SCurtis.Dunham@arm.com        }
85410455SCurtis.Dunham@arm.com
85510455SCurtis.Dunham@arm.com        EmbeddedSwig embed_swig_${module}(init_${module}, "${context}");
85610455SCurtis.Dunham@arm.com        ''')
85710455SCurtis.Dunham@arm.com        code.write(str(target[0]))
85810455SCurtis.Dunham@arm.com    return body
8595517Snate@binkert.org
86010455SCurtis.Dunham@arm.com# Build all swig modules
8618232Snate@binkert.orgfor swig in SwigSource.all:
8628232Snate@binkert.org    env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
8635517Snate@binkert.org                MakeAction('$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
8647673Snate@binkert.org                '-o ${TARGETS[0]} $SOURCES', Transform("SWIG")))
8655517Snate@binkert.org    cc_file = str(swig.tnode)
8668232Snate@binkert.org    init_file = '%s/%s_init.cc' % (dirname(cc_file), basename(cc_file))
8678232Snate@binkert.org    env.Command(init_file, Value(swig.module),
8685517Snate@binkert.org                MakeAction(makeEmbeddedSwigInit(swig.package),
8698232Snate@binkert.org                           Transform("EMBED SW")))
8708232Snate@binkert.org    env.Depends(SWIG, init_file)
8718232Snate@binkert.org    Source(init_file, **swig.guards)
8727673Snate@binkert.org
8735517Snate@binkert.org# Build all protocol buffers if we have got protoc and protobuf available
8745517Snate@binkert.orgif env['HAVE_PROTOBUF']:
8757673Snate@binkert.org    for proto in ProtoBuf.all:
8765517Snate@binkert.org        # Use both the source and header as the target, and the .proto
87710455SCurtis.Dunham@arm.com        # file as the source. When executing the protoc compiler, also
8785517Snate@binkert.org        # specify the proto_path to avoid having the generated files
8795517Snate@binkert.org        # include the path.
8808232Snate@binkert.org        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
8818232Snate@binkert.org                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
8825517Snate@binkert.org                               '--proto_path ${SOURCE.dir} $SOURCE',
8838232Snate@binkert.org                               Transform("PROTOC")))
8848232Snate@binkert.org
8855517Snate@binkert.org        env.Depends(SWIG, [proto.cc_file, proto.hh_file])
8868232Snate@binkert.org        # Add the C++ source file
8878232Snate@binkert.org        Source(proto.cc_file, **proto.guards)
8888232Snate@binkert.orgelif ProtoBuf.all:
8895517Snate@binkert.org    print 'Got protobuf to build, but lacks support!'
8908232Snate@binkert.org    Exit(1)
8918232Snate@binkert.org
8928232Snate@binkert.org#
8938232Snate@binkert.org# Handle debug flags
8948232Snate@binkert.org#
8958232Snate@binkert.orgdef makeDebugFlagCC(target, source, env):
8965517Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
8978232Snate@binkert.org
8988232Snate@binkert.org    code = code_formatter()
8995517Snate@binkert.org
9008232Snate@binkert.org    # delay definition of CompoundFlags until after all the definition
9017673Snate@binkert.org    # of all constituent SimpleFlags
9025517Snate@binkert.org    comp_code = code_formatter()
9037673Snate@binkert.org
9045517Snate@binkert.org    # file header
9058232Snate@binkert.org    code('''
9068232Snate@binkert.org/*
9078232Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated by SCons.
9085192Ssaidi@eecs.umich.edu */
90910454SCurtis.Dunham@arm.com
91010454SCurtis.Dunham@arm.com#include "base/debug.hh"
9118232Snate@binkert.org
91210455SCurtis.Dunham@arm.comnamespace Debug {
91310455SCurtis.Dunham@arm.com
91410455SCurtis.Dunham@arm.com''')
91510455SCurtis.Dunham@arm.com
91610455SCurtis.Dunham@arm.com    for name, flag in sorted(source[0].read().iteritems()):
91710455SCurtis.Dunham@arm.com        n, compound, desc = flag
9185192Ssaidi@eecs.umich.edu        assert n == name
9197674Snate@binkert.org
9205522Snate@binkert.org        if not compound:
9215522Snate@binkert.org            code('SimpleFlag $name("$name", "$desc");')
9227674Snate@binkert.org        else:
9237674Snate@binkert.org            comp_code('CompoundFlag $name("$name", "$desc",')
9247674Snate@binkert.org            comp_code.indent()
9257674Snate@binkert.org            last = len(compound) - 1
9267674Snate@binkert.org            for i,flag in enumerate(compound):
9277674Snate@binkert.org                if i != last:
9287674Snate@binkert.org                    comp_code('&$flag,')
9297674Snate@binkert.org                else:
9305522Snate@binkert.org                    comp_code('&$flag);')
9315522Snate@binkert.org            comp_code.dedent()
9325522Snate@binkert.org
9335517Snate@binkert.org    code.append(comp_code)
9345522Snate@binkert.org    code()
9355517Snate@binkert.org    code('} // namespace Debug')
9366143Snate@binkert.org
9376727Ssteve.reinhardt@amd.com    code.write(str(target[0]))
9385522Snate@binkert.org
9395522Snate@binkert.orgdef makeDebugFlagHH(target, source, env):
9405522Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
9417674Snate@binkert.org
9425517Snate@binkert.org    val = eval(source[0].get_contents())
9437673Snate@binkert.org    name, compound, desc = val
9447673Snate@binkert.org
9457674Snate@binkert.org    code = code_formatter()
9467673Snate@binkert.org
9477674Snate@binkert.org    # file header boilerplate
9487674Snate@binkert.org    code('''\
9498946Sandreas.hansson@arm.com/*
9507674Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated by SCons.
9517674Snate@binkert.org */
9527674Snate@binkert.org
9535522Snate@binkert.org#ifndef __DEBUG_${name}_HH__
9545522Snate@binkert.org#define __DEBUG_${name}_HH__
9557674Snate@binkert.org
9567674Snate@binkert.orgnamespace Debug {
9577674Snate@binkert.org''')
9587674Snate@binkert.org
9597673Snate@binkert.org    if compound:
9607674Snate@binkert.org        code('class CompoundFlag;')
9617674Snate@binkert.org    code('class SimpleFlag;')
9627674Snate@binkert.org
9637674Snate@binkert.org    if compound:
9647674Snate@binkert.org        code('extern CompoundFlag $name;')
9657674Snate@binkert.org        for flag in compound:
9667674Snate@binkert.org            code('extern SimpleFlag $flag;')
9677674Snate@binkert.org    else:
9687811Ssteve.reinhardt@amd.com        code('extern SimpleFlag $name;')
9697674Snate@binkert.org
9707673Snate@binkert.org    code('''
9715522Snate@binkert.org}
9726143Snate@binkert.org
97310453SAndrew.Bardsley@arm.com#endif // __DEBUG_${name}_HH__
9747816Ssteve.reinhardt@amd.com''')
97510454SCurtis.Dunham@arm.com
97610453SAndrew.Bardsley@arm.com    code.write(str(target[0]))
9774382Sbinkertn@umich.edu
9784382Sbinkertn@umich.edufor name,flag in sorted(debug_flags.iteritems()):
9794382Sbinkertn@umich.edu    n, compound, desc = flag
9804382Sbinkertn@umich.edu    assert n == name
9814382Sbinkertn@umich.edu
9824382Sbinkertn@umich.edu    hh_file = 'debug/%s.hh' % name
9834382Sbinkertn@umich.edu    env.Command(hh_file, Value(flag),
9844382Sbinkertn@umich.edu                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
98510196SCurtis.Dunham@arm.com    env.Depends(SWIG, hh_file)
9864382Sbinkertn@umich.edu
98710196SCurtis.Dunham@arm.comenv.Command('debug/flags.cc', Value(debug_flags),
98810196SCurtis.Dunham@arm.com            MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
98910196SCurtis.Dunham@arm.comenv.Depends(SWIG, 'debug/flags.cc')
99010196SCurtis.Dunham@arm.comSource('debug/flags.cc')
99110196SCurtis.Dunham@arm.com
99210196SCurtis.Dunham@arm.com# version tags
99310196SCurtis.Dunham@arm.comtags = \
994955SN/Aenv.Command('sim/tags.cc', None,
9952655Sstever@eecs.umich.edu            MakeAction('util/cpt_upgrader.py --get-cc-file > $TARGET',
9962655Sstever@eecs.umich.edu                       Transform("VER TAGS")))
9972655Sstever@eecs.umich.eduenv.AlwaysBuild(tags)
9982655Sstever@eecs.umich.edu
99910196SCurtis.Dunham@arm.com# Embed python files.  All .py files that have been indicated by a
10005601Snate@binkert.org# PySource() call in a SConscript need to be embedded into the M5
10015601Snate@binkert.org# library.  To do that, we compile the file to byte code, marshal the
100210196SCurtis.Dunham@arm.com# byte code, compress it, and then generate a c++ file that
100310196SCurtis.Dunham@arm.com# inserts the result into an array.
100410196SCurtis.Dunham@arm.comdef embedPyFile(target, source, env):
10055522Snate@binkert.org    def c_str(string):
10065863Snate@binkert.org        if string is None:
10075601Snate@binkert.org            return "0"
10085601Snate@binkert.org        return '"%s"' % string
10095601Snate@binkert.org
10105863Snate@binkert.org    '''Action function to compile a .py into a code object, marshal
10119556Sandreas.hansson@arm.com    it, compress it, and stick it into an asm file so the code appears
10129556Sandreas.hansson@arm.com    as just bytes with a label in the data section'''
10139556Sandreas.hansson@arm.com
10149556Sandreas.hansson@arm.com    src = file(str(source[0]), 'r').read()
10159556Sandreas.hansson@arm.com
10169556Sandreas.hansson@arm.com    pysource = PySource.tnodes[source[0]]
10179556Sandreas.hansson@arm.com    compiled = compile(src, pysource.abspath, 'exec')
10189556Sandreas.hansson@arm.com    marshalled = marshal.dumps(compiled)
10199556Sandreas.hansson@arm.com    compressed = zlib.compress(marshalled)
10205559Snate@binkert.org    data = compressed
10219556Sandreas.hansson@arm.com    sym = pysource.symname
10229618Ssteve.reinhardt@amd.com
10239618Ssteve.reinhardt@amd.com    code = code_formatter()
10249618Ssteve.reinhardt@amd.com    code('''\
102510238Sandreas.hansson@arm.com#include "sim/init.hh"
102610238Sandreas.hansson@arm.com
10279554Sandreas.hansson@arm.comnamespace {
10289556Sandreas.hansson@arm.com
10299556Sandreas.hansson@arm.comconst uint8_t data_${sym}[] = {
10309556Sandreas.hansson@arm.com''')
10319556Sandreas.hansson@arm.com    code.indent()
10329555Sandreas.hansson@arm.com    step = 16
10339555Sandreas.hansson@arm.com    for i in xrange(0, len(data), step):
10349556Sandreas.hansson@arm.com        x = array.array('B', data[i:i+step])
103510457Sandreas.hansson@arm.com        code(''.join('%d,' % d for d in x))
103610457Sandreas.hansson@arm.com    code.dedent()
103710457Sandreas.hansson@arm.com
103810457Sandreas.hansson@arm.com    code('''};
103910457Sandreas.hansson@arm.com
104010457Sandreas.hansson@arm.comEmbeddedPython embedded_${sym}(
104110457Sandreas.hansson@arm.com    ${{c_str(pysource.arcname)}},
104210457Sandreas.hansson@arm.com    ${{c_str(pysource.abspath)}},
104310457Sandreas.hansson@arm.com    ${{c_str(pysource.modpath)}},
10448737Skoansin.tan@gmail.com    data_${sym},
10459556Sandreas.hansson@arm.com    ${{len(data)}},
10469556Sandreas.hansson@arm.com    ${{len(marshalled)}});
10479556Sandreas.hansson@arm.com
10489554Sandreas.hansson@arm.com} // anonymous namespace
104910278SAndreas.Sandberg@ARM.com''')
105010278SAndreas.Sandberg@ARM.com    code.write(str(target[0]))
105110278SAndreas.Sandberg@ARM.com
105210278SAndreas.Sandberg@ARM.comfor source in PySource.all:
105310278SAndreas.Sandberg@ARM.com    env.Command(source.cpp, source.tnode,
105410278SAndreas.Sandberg@ARM.com                MakeAction(embedPyFile, Transform("EMBED PY")))
105510278SAndreas.Sandberg@ARM.com    env.Depends(SWIG, source.cpp)
105610278SAndreas.Sandberg@ARM.com    Source(source.cpp, skip_no_python=True)
105710457Sandreas.hansson@arm.com
105810457Sandreas.hansson@arm.com########################################################################
105910457Sandreas.hansson@arm.com#
106010457Sandreas.hansson@arm.com# Define binaries.  Each different build type (debug, opt, etc.) gets
106110457Sandreas.hansson@arm.com# a slightly different build environment.
106210457Sandreas.hansson@arm.com#
10638945Ssteve.reinhardt@amd.com
10648945Ssteve.reinhardt@amd.com# List of constructed environments to pass back to SConstruct
10658945Ssteve.reinhardt@amd.comdate_source = Source('base/date.cc', skip_lib=True)
10666143Snate@binkert.org
10676143Snate@binkert.org# Capture this directory for the closure makeEnv, otherwise when it is
10686143Snate@binkert.org# called, it won't know what directory it should use.
10696143Snate@binkert.orgvariant_dir = Dir('.').path
10706143Snate@binkert.orgdef variant(*path):
10716143Snate@binkert.org    return os.path.join(variant_dir, *path)
10726143Snate@binkert.orgdef variantd(*path):
10738945Ssteve.reinhardt@amd.com    return variant(*path)+'/'
10748945Ssteve.reinhardt@amd.com
10756143Snate@binkert.org# Function to create a new build environment as clone of current
10766143Snate@binkert.org# environment 'env' with modified object suffix and optional stripped
10776143Snate@binkert.org# binary.  Additional keyword arguments are appended to corresponding
10786143Snate@binkert.org# build environment vars.
10796143Snate@binkert.orgdef makeEnv(env, label, objsfx, strip = False, **kwargs):
10806143Snate@binkert.org    # SCons doesn't know to append a library suffix when there is a '.' in the
10816143Snate@binkert.org    # name.  Use '_' instead.
10826143Snate@binkert.org    libname = variant('gem5_' + label)
10836143Snate@binkert.org    exename = variant('gem5.' + label)
10846143Snate@binkert.org    secondary_exename = variant('m5.' + label)
10856143Snate@binkert.org
10866143Snate@binkert.org    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
10876143Snate@binkert.org    new_env.Label = label
108810453SAndrew.Bardsley@arm.com    new_env.Append(**kwargs)
108910453SAndrew.Bardsley@arm.com
109010453SAndrew.Bardsley@arm.com    swig_env = new_env.Clone()
109110453SAndrew.Bardsley@arm.com
109210453SAndrew.Bardsley@arm.com    # Both gcc and clang have issues with unused labels and values in
109310453SAndrew.Bardsley@arm.com    # the SWIG generated code
109410453SAndrew.Bardsley@arm.com    swig_env.Append(CCFLAGS=['-Wno-unused-label', '-Wno-unused-value'])
109510453SAndrew.Bardsley@arm.com
109610453SAndrew.Bardsley@arm.com    if env['GCC']:
10976143Snate@binkert.org        # Depending on the SWIG version, we also need to supress
10986143Snate@binkert.org        # warnings about uninitialized variables and missing field
10996143Snate@binkert.org        # initializers.
110010453SAndrew.Bardsley@arm.com        swig_env.Append(CCFLAGS=['-Wno-uninitialized',
11016143Snate@binkert.org                                 '-Wno-missing-field-initializers',
11026240Snate@binkert.org                                 '-Wno-unused-but-set-variable',
11035554Snate@binkert.org                                 '-Wno-maybe-uninitialized',
11045522Snate@binkert.org                                 '-Wno-type-limits'])
11055522Snate@binkert.org
11065797Snate@binkert.org
11075797Snate@binkert.org        # The address sanitizer is available for gcc >= 4.8
11085522Snate@binkert.org        if GetOption('with_asan'):
11095601Snate@binkert.org            if GetOption('with_ubsan') and \
11108233Snate@binkert.org                    compareVersions(env['GCC_VERSION'], '4.9') >= 0:
11118233Snate@binkert.org                new_env.Append(CCFLAGS=['-fsanitize=address,undefined',
11128235Snate@binkert.org                                        '-fno-omit-frame-pointer'])
11138235Snate@binkert.org                new_env.Append(LINKFLAGS='-fsanitize=address,undefined')
11148235Snate@binkert.org            else:
11158235Snate@binkert.org                new_env.Append(CCFLAGS=['-fsanitize=address',
11169003SAli.Saidi@ARM.com                                        '-fno-omit-frame-pointer'])
11179003SAli.Saidi@ARM.com                new_env.Append(LINKFLAGS='-fsanitize=address')
111810196SCurtis.Dunham@arm.com        # Only gcc >= 4.9 supports UBSan, so check both the version
111910196SCurtis.Dunham@arm.com        # and the command-line option before adding the compiler and
11208235Snate@binkert.org        # linker flags.
11216143Snate@binkert.org        elif GetOption('with_ubsan') and \
11222655Sstever@eecs.umich.edu                compareVersions(env['GCC_VERSION'], '4.9') >= 0:
11236143Snate@binkert.org            new_env.Append(CCFLAGS='-fsanitize=undefined')
11246143Snate@binkert.org            new_env.Append(LINKFLAGS='-fsanitize=undefined')
11258233Snate@binkert.org
11266143Snate@binkert.org
11276143Snate@binkert.org    if env['CLANG']:
11284007Ssaidi@eecs.umich.edu        swig_env.Append(CCFLAGS=['-Wno-sometimes-uninitialized',
11294596Sbinkertn@umich.edu                                 '-Wno-deprecated-register',
11304007Ssaidi@eecs.umich.edu                                 '-Wno-tautological-compare'])
11314596Sbinkertn@umich.edu
11327756SAli.Saidi@ARM.com        # We require clang >= 3.1, so there is no need to check any
11337816Ssteve.reinhardt@amd.com        # versions here.
11348334Snate@binkert.org        if GetOption('with_ubsan'):
11358334Snate@binkert.org            if GetOption('with_asan'):
11368334Snate@binkert.org                new_env.Append(CCFLAGS=['-fsanitize=address,undefined',
11378334Snate@binkert.org                                        '-fno-omit-frame-pointer'])
11385601Snate@binkert.org                new_env.Append(LINKFLAGS='-fsanitize=address,undefined')
113910196SCurtis.Dunham@arm.com            else:
11402655Sstever@eecs.umich.edu                new_env.Append(CCFLAGS='-fsanitize=undefined')
11419225Sandreas.hansson@arm.com                new_env.Append(LINKFLAGS='-fsanitize=undefined')
11429225Sandreas.hansson@arm.com
11439226Sandreas.hansson@arm.com        elif GetOption('with_asan'):
11449226Sandreas.hansson@arm.com            new_env.Append(CCFLAGS=['-fsanitize=address',
11459225Sandreas.hansson@arm.com                                    '-fno-omit-frame-pointer'])
11469226Sandreas.hansson@arm.com            new_env.Append(LINKFLAGS='-fsanitize=address')
11479226Sandreas.hansson@arm.com
11489226Sandreas.hansson@arm.com    werror_env = new_env.Clone()
11499226Sandreas.hansson@arm.com    # Treat warnings as errors but white list some warnings that we
11509226Sandreas.hansson@arm.com    # want to allow (e.g., deprecation warnings).
11519226Sandreas.hansson@arm.com    werror_env.Append(CCFLAGS=['-Werror',
11529225Sandreas.hansson@arm.com                               '-Wno-error=deprecated-declarations',
11539227Sandreas.hansson@arm.com                               '-Wno-error=deprecated',
11549227Sandreas.hansson@arm.com                               ])
11559227Sandreas.hansson@arm.com
11569227Sandreas.hansson@arm.com    def make_obj(source, static, extra_deps = None):
11578946Sandreas.hansson@arm.com        '''This function adds the specified source to the correct
11583918Ssaidi@eecs.umich.edu        build environment, and returns the corresponding SCons Object
11599225Sandreas.hansson@arm.com        nodes'''
11603918Ssaidi@eecs.umich.edu
11619225Sandreas.hansson@arm.com        if source.swig:
11629225Sandreas.hansson@arm.com            env = swig_env
11639227Sandreas.hansson@arm.com        elif source.Werror:
11649227Sandreas.hansson@arm.com            env = werror_env
11659227Sandreas.hansson@arm.com        else:
11669226Sandreas.hansson@arm.com            env = new_env
11679225Sandreas.hansson@arm.com
11689227Sandreas.hansson@arm.com        if static:
11699227Sandreas.hansson@arm.com            obj = env.StaticObject(source.tnode)
11709227Sandreas.hansson@arm.com        else:
11719227Sandreas.hansson@arm.com            obj = env.SharedObject(source.tnode)
11728946Sandreas.hansson@arm.com
11739225Sandreas.hansson@arm.com        if extra_deps:
11749226Sandreas.hansson@arm.com            env.Depends(obj, extra_deps)
11759226Sandreas.hansson@arm.com
11769226Sandreas.hansson@arm.com        return obj
11773515Ssaidi@eecs.umich.edu
11783918Ssaidi@eecs.umich.edu    lib_guards = {'main': False, 'skip_lib': False}
11794762Snate@binkert.org
11803515Ssaidi@eecs.umich.edu    # Without Python, leave out all SWIG and Python content from the
11818881Smarc.orr@gmail.com    # library builds.  The option doesn't affect gem5 built as a program
11828881Smarc.orr@gmail.com    if GetOption('without_python'):
11838881Smarc.orr@gmail.com        lib_guards['skip_no_python'] = False
11848881Smarc.orr@gmail.com
11858881Smarc.orr@gmail.com    static_objs = []
11869226Sandreas.hansson@arm.com    shared_objs = []
11879226Sandreas.hansson@arm.com    for s in guarded_source_iterator(Source.source_groups[None], **lib_guards):
11889226Sandreas.hansson@arm.com        static_objs.append(make_obj(s, True))
11898881Smarc.orr@gmail.com        shared_objs.append(make_obj(s, False))
11908881Smarc.orr@gmail.com
11918881Smarc.orr@gmail.com    partial_objs = []
11928881Smarc.orr@gmail.com    for group, all_srcs in Source.source_groups.iteritems():
11938881Smarc.orr@gmail.com        # If these are the ungrouped source files, skip them.
11948881Smarc.orr@gmail.com        if not group:
11958881Smarc.orr@gmail.com            continue
11968881Smarc.orr@gmail.com
11978881Smarc.orr@gmail.com        # Get a list of the source files compatible with the current guards.
11988881Smarc.orr@gmail.com        srcs = [ s for s in guarded_source_iterator(all_srcs, **lib_guards) ]
11998881Smarc.orr@gmail.com        # If there aren't any left, skip this group.
12008881Smarc.orr@gmail.com        if not srcs:
12018881Smarc.orr@gmail.com            continue
12028881Smarc.orr@gmail.com
12038881Smarc.orr@gmail.com        # Set up the static partially linked objects.
12048881Smarc.orr@gmail.com        source_objs = [ make_obj(s, True) for s in srcs ]
120510196SCurtis.Dunham@arm.com        file_name = new_env.subst("${OBJPREFIX}lib${OBJSUFFIX}.partial")
120610196SCurtis.Dunham@arm.com        target = File(joinpath(group, file_name))
120710196SCurtis.Dunham@arm.com        partial = env.PartialStatic(target=target, source=source_objs)
120810196SCurtis.Dunham@arm.com        static_objs.append(partial)
1209955SN/A
121010196SCurtis.Dunham@arm.com        # Set up the shared partially linked objects.
1211955SN/A        source_objs = [ make_obj(s, False) for s in srcs ]
121210196SCurtis.Dunham@arm.com        file_name = new_env.subst("${SHOBJPREFIX}lib${SHOBJSUFFIX}.partial")
121310196SCurtis.Dunham@arm.com        target = File(joinpath(group, file_name))
121410196SCurtis.Dunham@arm.com        partial = env.PartialShared(target=target, source=source_objs)
121510196SCurtis.Dunham@arm.com        shared_objs.append(partial)
121610196SCurtis.Dunham@arm.com
121710196SCurtis.Dunham@arm.com    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
121810196SCurtis.Dunham@arm.com    static_objs.append(static_date)
1219955SN/A
122010196SCurtis.Dunham@arm.com    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
122110196SCurtis.Dunham@arm.com    shared_objs.append(shared_date)
122210196SCurtis.Dunham@arm.com
122310196SCurtis.Dunham@arm.com    # First make a library of everything but main() so other programs can
122410196SCurtis.Dunham@arm.com    # link against m5.
122510196SCurtis.Dunham@arm.com    static_lib = new_env.StaticLibrary(libname, static_objs)
122610196SCurtis.Dunham@arm.com    shared_lib = new_env.SharedLibrary(libname, shared_objs)
12271869SN/A
122810196SCurtis.Dunham@arm.com    # Now link a stub with main() and the static library.
122910196SCurtis.Dunham@arm.com    main_objs = [ make_obj(s, True) for s in Source.get(main=True) ]
123010196SCurtis.Dunham@arm.com
123110196SCurtis.Dunham@arm.com    for test in UnitTest.all:
123210196SCurtis.Dunham@arm.com        flags = { test.target : True }
123310196SCurtis.Dunham@arm.com        test_sources = Source.get(**flags)
123410196SCurtis.Dunham@arm.com        test_objs = [ make_obj(s, static=True) for s in test_sources ]
12359226Sandreas.hansson@arm.com        if test.main:
123610196SCurtis.Dunham@arm.com            test_objs += main_objs
123710196SCurtis.Dunham@arm.com        path = variant('unittest/%s.%s' % (test.target, label))
123810196SCurtis.Dunham@arm.com        new_env.Program(path, test_objs + static_objs)
123910196SCurtis.Dunham@arm.com
124010196SCurtis.Dunham@arm.com    progname = exename
124110196SCurtis.Dunham@arm.com    if strip:
124210196SCurtis.Dunham@arm.com        progname += '.unstripped'
124310196SCurtis.Dunham@arm.com
124410196SCurtis.Dunham@arm.com    # When linking the gem5 binary, the command line can be too big for the
124510196SCurtis.Dunham@arm.com    # shell to handle. Use "subprocess" to spawn processes without passing
124610196SCurtis.Dunham@arm.com    # through the shell to avoid this problem. That means we also can't use
124710196SCurtis.Dunham@arm.com    # shell syntax in any of the commands this will run, but that isn't
124810196SCurtis.Dunham@arm.com    # currently an issue.
124910196SCurtis.Dunham@arm.com    def spawn_with_subprocess(sh, escape, cmd, args, env):
125010196SCurtis.Dunham@arm.com        return subprocess.call(args, env=env)
125110196SCurtis.Dunham@arm.com
125210196SCurtis.Dunham@arm.com    # Since we're not running through a shell, no escaping is necessary either.
125310196SCurtis.Dunham@arm.com    targets = new_env.Program(progname, main_objs + static_objs,
125410196SCurtis.Dunham@arm.com                              SPAWN=spawn_with_subprocess,
125510196SCurtis.Dunham@arm.com                              ESCAPE=lambda x: x)
125610196SCurtis.Dunham@arm.com
125710196SCurtis.Dunham@arm.com    if strip:
125810196SCurtis.Dunham@arm.com        if sys.platform == 'sunos5':
125910196SCurtis.Dunham@arm.com            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
126010196SCurtis.Dunham@arm.com        else:
126110196SCurtis.Dunham@arm.com            cmd = 'strip $SOURCE -o $TARGET'
126210196SCurtis.Dunham@arm.com        targets = new_env.Command(exename, progname,
126310196SCurtis.Dunham@arm.com                    MakeAction(cmd, Transform("STRIP")))
126410196SCurtis.Dunham@arm.com
126510196SCurtis.Dunham@arm.com    new_env.Command(secondary_exename, exename,
126610196SCurtis.Dunham@arm.com            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
126710196SCurtis.Dunham@arm.com
126810196SCurtis.Dunham@arm.com    new_env.M5Binary = targets[0]
126910196SCurtis.Dunham@arm.com    return new_env
127010196SCurtis.Dunham@arm.com
127110196SCurtis.Dunham@arm.com# Start out with the compiler flags common to all compilers,
127210196SCurtis.Dunham@arm.com# i.e. they all use -g for opt and -g -pg for prof
127310196SCurtis.Dunham@arm.comccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
127410196SCurtis.Dunham@arm.com           'perf' : ['-g']}
127510196SCurtis.Dunham@arm.com
127610196SCurtis.Dunham@arm.com# Start out with the linker flags common to all linkers, i.e. -pg for
127710196SCurtis.Dunham@arm.com# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
127810196SCurtis.Dunham@arm.com# no-as-needed and as-needed as the binutils linker is too clever and
1279# simply doesn't link to the library otherwise.
1280ldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
1281           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
1282
1283# For Link Time Optimization, the optimisation flags used to compile
1284# individual files are decoupled from those used at link time
1285# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
1286# to also update the linker flags based on the target.
1287if env['GCC']:
1288    if sys.platform == 'sunos5':
1289        ccflags['debug'] += ['-gstabs+']
1290    else:
1291        ccflags['debug'] += ['-ggdb3']
1292    ldflags['debug'] += ['-O0']
1293    # opt, fast, prof and perf all share the same cc flags, also add
1294    # the optimization to the ldflags as LTO defers the optimization
1295    # to link time
1296    for target in ['opt', 'fast', 'prof', 'perf']:
1297        ccflags[target] += ['-O3']
1298        ldflags[target] += ['-O3']
1299
1300    ccflags['fast'] += env['LTO_CCFLAGS']
1301    ldflags['fast'] += env['LTO_LDFLAGS']
1302elif env['CLANG']:
1303    ccflags['debug'] += ['-g', '-O0']
1304    # opt, fast, prof and perf all share the same cc flags
1305    for target in ['opt', 'fast', 'prof', 'perf']:
1306        ccflags[target] += ['-O3']
1307else:
1308    print 'Unknown compiler, please fix compiler options'
1309    Exit(1)
1310
1311
1312# To speed things up, we only instantiate the build environments we
1313# need.  We try to identify the needed environment for each target; if
1314# we can't, we fall back on instantiating all the environments just to
1315# be safe.
1316target_types = ['debug', 'opt', 'fast', 'prof', 'perf']
1317obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
1318              'gpo' : 'perf'}
1319
1320def identifyTarget(t):
1321    ext = t.split('.')[-1]
1322    if ext in target_types:
1323        return ext
1324    if obj2target.has_key(ext):
1325        return obj2target[ext]
1326    match = re.search(r'/tests/([^/]+)/', t)
1327    if match and match.group(1) in target_types:
1328        return match.group(1)
1329    return 'all'
1330
1331needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
1332if 'all' in needed_envs:
1333    needed_envs += target_types
1334
1335def makeEnvirons(target, source, env):
1336    # cause any later Source() calls to be fatal, as a diagnostic.
1337    Source.done()
1338
1339    envList = []
1340
1341    # Debug binary
1342    if 'debug' in needed_envs:
1343        envList.append(
1344            makeEnv(env, 'debug', '.do',
1345                    CCFLAGS = Split(ccflags['debug']),
1346                    CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
1347                    LINKFLAGS = Split(ldflags['debug'])))
1348
1349    # Optimized binary
1350    if 'opt' in needed_envs:
1351        envList.append(
1352            makeEnv(env, 'opt', '.o',
1353                    CCFLAGS = Split(ccflags['opt']),
1354                    CPPDEFINES = ['TRACING_ON=1'],
1355                    LINKFLAGS = Split(ldflags['opt'])))
1356
1357    # "Fast" binary
1358    if 'fast' in needed_envs:
1359        envList.append(
1360            makeEnv(env, 'fast', '.fo', strip = True,
1361                    CCFLAGS = Split(ccflags['fast']),
1362                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1363                    LINKFLAGS = Split(ldflags['fast'])))
1364
1365    # Profiled binary using gprof
1366    if 'prof' in needed_envs:
1367        envList.append(
1368            makeEnv(env, 'prof', '.po',
1369                    CCFLAGS = Split(ccflags['prof']),
1370                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1371                    LINKFLAGS = Split(ldflags['prof'])))
1372
1373    # Profiled binary using google-pprof
1374    if 'perf' in needed_envs:
1375        envList.append(
1376            makeEnv(env, 'perf', '.gpo',
1377                    CCFLAGS = Split(ccflags['perf']),
1378                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1379                    LINKFLAGS = Split(ldflags['perf'])))
1380
1381    # Set up the regression tests for each build.
1382    for e in envList:
1383        SConscript(os.path.join(env.root.abspath, 'tests', 'SConscript'),
1384                   variant_dir = variantd('tests', e.Label),
1385                   exports = { 'env' : e }, duplicate = False)
1386
1387# The MakeEnvirons Builder defers the full dependency collection until
1388# after processing the ISA definition (due to dynamically generated
1389# source files).  Add this dependency to all targets so they will wait
1390# until the environments are completely set up.  Otherwise, a second
1391# process (e.g. -j2 or higher) will try to compile the requested target,
1392# not know how, and fail.
1393env.Append(BUILDERS = {'MakeEnvirons' :
1394                        Builder(action=MakeAction(makeEnvirons,
1395                                                  Transform("ENVIRONS", 1)))})
1396
1397isa_target = env['PHONY_BASE'] + '-deps'
1398environs   = env['PHONY_BASE'] + '-environs'
1399env.Depends('#all-deps',     isa_target)
1400env.Depends('#all-environs', environs)
1401env.ScanISA(isa_target, File('arch/%s/generated/inc.d' % env['TARGET_ISA']))
1402envSetup = env.MakeEnvirons(environs, isa_target)
1403
1404# make sure no -deps targets occur before all ISAs are complete
1405env.Depends(isa_target, '#all-isas')
1406# likewise for -environs targets and all the -deps targets
1407env.Depends(environs, '#all-deps')
1408