SConscript revision 12563
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.orgfrom __future__ import print_function
326143Snate@binkert.org
334762Snate@binkert.orgimport array
345522Snate@binkert.orgimport bisect
35955SN/Aimport functools
365522Snate@binkert.orgimport imp
37955SN/Aimport marshal
385522Snate@binkert.orgimport os
394202Sbinkertn@umich.eduimport re
405742Snate@binkert.orgimport subprocess
41955SN/Aimport sys
424381Sbinkertn@umich.eduimport zlib
434381Sbinkertn@umich.edu
448334Snate@binkert.orgfrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
45955SN/A
46955SN/Aimport SCons
474202Sbinkertn@umich.edu
48955SN/Afrom gem5_scons import Transform
494382Sbinkertn@umich.edu
504382Sbinkertn@umich.edu# This file defines how to build a particular configuration of gem5
514382Sbinkertn@umich.edu# based on variable settings in the 'env' build environment.
526654Snate@binkert.org
535517Snate@binkert.orgImport('*')
548614Sgblack@eecs.umich.edu
557674Snate@binkert.org# Children need to see the environment
566143Snate@binkert.orgExport('env')
576143Snate@binkert.org
586143Snate@binkert.orgbuild_env = [(opt, env[opt]) for opt in export_vars]
598233Snate@binkert.org
608233Snate@binkert.orgfrom m5.util import code_formatter, compareVersions
618233Snate@binkert.org
628233Snate@binkert.org########################################################################
638233Snate@binkert.org# Code for adding source files of various types
648334Snate@binkert.org#
658334Snate@binkert.org# When specifying a source file of some type, a set of tags can be
668233Snate@binkert.org# specified for that file.
678233Snate@binkert.org
688233Snate@binkert.orgclass SourceFilter(object):
698233Snate@binkert.org    def __init__(self, predicate):
708233Snate@binkert.org        self.predicate = predicate
718233Snate@binkert.org
726143Snate@binkert.org    def __or__(self, other):
738233Snate@binkert.org        return SourceFilter(lambda tags: self.predicate(tags) or
748233Snate@binkert.org                                         other.predicate(tags))
758233Snate@binkert.org
766143Snate@binkert.org    def __and__(self, other):
776143Snate@binkert.org        return SourceFilter(lambda tags: self.predicate(tags) and
786143Snate@binkert.org                                         other.predicate(tags))
796143Snate@binkert.org
808233Snate@binkert.orgdef with_tags_that(predicate):
818233Snate@binkert.org    '''Return a list of sources with tags that satisfy a predicate.'''
828233Snate@binkert.org    return SourceFilter(predicate)
836143Snate@binkert.org
848233Snate@binkert.orgdef with_any_tags(*tags):
858233Snate@binkert.org    '''Return a list of sources with any of the supplied tags.'''
868233Snate@binkert.org    return SourceFilter(lambda stags: len(set(tags) & stags) > 0)
878233Snate@binkert.org
886143Snate@binkert.orgdef with_all_tags(*tags):
896143Snate@binkert.org    '''Return a list of sources with all of the supplied tags.'''
906143Snate@binkert.org    return SourceFilter(lambda stags: set(tags) <= stags)
914762Snate@binkert.org
926143Snate@binkert.orgdef with_tag(tag):
938233Snate@binkert.org    '''Return a list of sources with the supplied tag.'''
948233Snate@binkert.org    return SourceFilter(lambda stags: tag in stags)
958233Snate@binkert.org
968233Snate@binkert.orgdef without_tags(*tags):
978233Snate@binkert.org    '''Return a list of sources without any of the supplied tags.'''
986143Snate@binkert.org    return SourceFilter(lambda stags: len(set(tags) & stags) == 0)
998233Snate@binkert.org
1008233Snate@binkert.orgdef without_tag(tag):
1018233Snate@binkert.org    '''Return a list of sources with the supplied tag.'''
1028233Snate@binkert.org    return SourceFilter(lambda stags: tag not in stags)
1036143Snate@binkert.org
1046143Snate@binkert.orgsource_filter_factories = {
1056143Snate@binkert.org    'with_tags_that': with_tags_that,
1066143Snate@binkert.org    'with_any_tags': with_any_tags,
1076143Snate@binkert.org    'with_all_tags': with_all_tags,
1086143Snate@binkert.org    'with_tag': with_tag,
1096143Snate@binkert.org    'without_tags': without_tags,
1106143Snate@binkert.org    'without_tag': without_tag,
1116143Snate@binkert.org}
1127065Snate@binkert.org
1136143Snate@binkert.orgExport(source_filter_factories)
1148233Snate@binkert.org
1158233Snate@binkert.orgclass SourceList(list):
1168233Snate@binkert.org    def apply_filter(self, f):
1178233Snate@binkert.org        def match(source):
1188233Snate@binkert.org            return f.predicate(source.tags)
1198233Snate@binkert.org        return SourceList(filter(match, self))
1208233Snate@binkert.org
1218233Snate@binkert.org    def __getattr__(self, name):
1228233Snate@binkert.org        func = source_filter_factories.get(name, None)
1238233Snate@binkert.org        if not func:
1248233Snate@binkert.org            raise AttributeError
1258233Snate@binkert.org
1268233Snate@binkert.org        @functools.wraps(func)
1278233Snate@binkert.org        def wrapper(*args, **kwargs):
1288233Snate@binkert.org            return self.apply_filter(func(*args, **kwargs))
1298233Snate@binkert.org        return wrapper
1308233Snate@binkert.org
1318233Snate@binkert.orgclass SourceMeta(type):
1328233Snate@binkert.org    '''Meta class for source files that keeps track of all files of a
1338233Snate@binkert.org    particular type.'''
1348233Snate@binkert.org    def __init__(cls, name, bases, dict):
1358233Snate@binkert.org        super(SourceMeta, cls).__init__(name, bases, dict)
1368233Snate@binkert.org        cls.all = SourceList()
1378233Snate@binkert.org
1388233Snate@binkert.orgclass SourceFile(object):
1398233Snate@binkert.org    '''Base object that encapsulates the notion of a source file.
1408233Snate@binkert.org    This includes, the source node, target node, various manipulations
1418233Snate@binkert.org    of those.  A source file also specifies a set of tags which
1428233Snate@binkert.org    describing arbitrary properties of the source file.'''
1438233Snate@binkert.org    __metaclass__ = SourceMeta
1448233Snate@binkert.org
1456143Snate@binkert.org    static_objs = {}
1466143Snate@binkert.org    shared_objs = {}
1476143Snate@binkert.org
1486143Snate@binkert.org    def __init__(self, source, tags=None, add_tags=None):
1496143Snate@binkert.org        if tags is None:
1506143Snate@binkert.org            tags='gem5 lib'
1516143Snate@binkert.org        if isinstance(tags, basestring):
1526143Snate@binkert.org            tags = set([tags])
1536143Snate@binkert.org        if not isinstance(tags, set):
1548233Snate@binkert.org            tags = set(tags)
1558233Snate@binkert.org        self.tags = tags
1568233Snate@binkert.org
1576143Snate@binkert.org        if add_tags:
1586143Snate@binkert.org            if isinstance(add_tags, basestring):
1596143Snate@binkert.org                add_tags = set([add_tags])
1606143Snate@binkert.org            if not isinstance(add_tags, set):
1616143Snate@binkert.org                add_tags = set(add_tags)
1626143Snate@binkert.org            self.tags |= add_tags
1635522Snate@binkert.org
1646143Snate@binkert.org        tnode = source
1656143Snate@binkert.org        if not isinstance(source, SCons.Node.FS.File):
1666143Snate@binkert.org            tnode = File(source)
1676143Snate@binkert.org
1688233Snate@binkert.org        self.tnode = tnode
1698233Snate@binkert.org        self.snode = tnode.srcnode()
1708233Snate@binkert.org
1716143Snate@binkert.org        for base in type(self).__mro__:
1726143Snate@binkert.org            if issubclass(base, SourceFile):
1736143Snate@binkert.org                base.all.append(self)
1746143Snate@binkert.org
1755522Snate@binkert.org    def static(self, env):
1765522Snate@binkert.org        key = (self.tnode, env['OBJSUFFIX'])
1775522Snate@binkert.org        if not key in self.static_objs:
1785522Snate@binkert.org            self.static_objs[key] = env.StaticObject(self.tnode)
1795604Snate@binkert.org        return self.static_objs[key]
1805604Snate@binkert.org
1816143Snate@binkert.org    def shared(self, env):
1826143Snate@binkert.org        key = (self.tnode, env['OBJSUFFIX'])
1834762Snate@binkert.org        if not key in self.shared_objs:
1844762Snate@binkert.org            self.shared_objs[key] = env.SharedObject(self.tnode)
1856143Snate@binkert.org        return self.shared_objs[key]
1866727Ssteve.reinhardt@amd.com
1876727Ssteve.reinhardt@amd.com    @property
1886727Ssteve.reinhardt@amd.com    def filename(self):
1894762Snate@binkert.org        return str(self.tnode)
1906143Snate@binkert.org
1916143Snate@binkert.org    @property
1926143Snate@binkert.org    def dirname(self):
1936143Snate@binkert.org        return dirname(self.filename)
1946727Ssteve.reinhardt@amd.com
1956143Snate@binkert.org    @property
1967674Snate@binkert.org    def basename(self):
1977674Snate@binkert.org        return basename(self.filename)
1985604Snate@binkert.org
1996143Snate@binkert.org    @property
2006143Snate@binkert.org    def extname(self):
2016143Snate@binkert.org        index = self.basename.rfind('.')
2024762Snate@binkert.org        if index <= 0:
2036143Snate@binkert.org            # dot files aren't extensions
2044762Snate@binkert.org            return self.basename, None
2054762Snate@binkert.org
2064762Snate@binkert.org        return self.basename[:index], self.basename[index+1:]
2076143Snate@binkert.org
2086143Snate@binkert.org    def __lt__(self, other): return self.filename < other.filename
2094762Snate@binkert.org    def __le__(self, other): return self.filename <= other.filename
2108233Snate@binkert.org    def __gt__(self, other): return self.filename > other.filename
2118233Snate@binkert.org    def __ge__(self, other): return self.filename >= other.filename
2128233Snate@binkert.org    def __eq__(self, other): return self.filename == other.filename
2138233Snate@binkert.org    def __ne__(self, other): return self.filename != other.filename
2146143Snate@binkert.org
2156143Snate@binkert.orgclass Source(SourceFile):
2164762Snate@binkert.org    ungrouped_tag = 'No link group'
2176143Snate@binkert.org    source_groups = set()
2184762Snate@binkert.org
2196143Snate@binkert.org    _current_group_tag = ungrouped_tag
2204762Snate@binkert.org
2216143Snate@binkert.org    @staticmethod
2228233Snate@binkert.org    def link_group_tag(group):
2238233Snate@binkert.org        return 'link group: %s' % group
2248233Snate@binkert.org
2256143Snate@binkert.org    @classmethod
2266143Snate@binkert.org    def set_group(cls, group):
2276143Snate@binkert.org        new_tag = Source.link_group_tag(group)
2286143Snate@binkert.org        Source._current_group_tag = new_tag
2296143Snate@binkert.org        Source.source_groups.add(group)
2306143Snate@binkert.org
2316143Snate@binkert.org    def _add_link_group_tag(self):
2326143Snate@binkert.org        self.tags.add(Source._current_group_tag)
2338233Snate@binkert.org
2348233Snate@binkert.org    '''Add a c/c++ source file to the build'''
235955SN/A    def __init__(self, source, tags=None, add_tags=None):
2368235Snate@binkert.org        '''specify the source file, and any tags'''
2378235Snate@binkert.org        super(Source, self).__init__(source, tags, add_tags)
2386143Snate@binkert.org        self._add_link_group_tag()
2398235Snate@binkert.org
2408235Snate@binkert.orgclass PySource(SourceFile):
2418235Snate@binkert.org    '''Add a python source file to the named package'''
2428235Snate@binkert.org    invalid_sym_char = re.compile('[^A-z0-9_]')
2438235Snate@binkert.org    modules = {}
2448235Snate@binkert.org    tnodes = {}
2458235Snate@binkert.org    symnames = {}
2468235Snate@binkert.org
2478235Snate@binkert.org    def __init__(self, package, source, tags=None, add_tags=None):
2488235Snate@binkert.org        '''specify the python package, the source file, and any tags'''
2498235Snate@binkert.org        super(PySource, self).__init__(source, tags, add_tags)
2508235Snate@binkert.org
2518235Snate@binkert.org        modname,ext = self.extname
2528235Snate@binkert.org        assert ext == 'py'
2538235Snate@binkert.org
2548235Snate@binkert.org        if package:
2558235Snate@binkert.org            path = package.split('.')
2565584Snate@binkert.org        else:
2574382Sbinkertn@umich.edu            path = []
2584202Sbinkertn@umich.edu
2594382Sbinkertn@umich.edu        modpath = path[:]
2604382Sbinkertn@umich.edu        if modname != '__init__':
2614382Sbinkertn@umich.edu            modpath += [ modname ]
2625584Snate@binkert.org        modpath = '.'.join(modpath)
2634382Sbinkertn@umich.edu
2644382Sbinkertn@umich.edu        arcpath = path + [ self.basename ]
2654382Sbinkertn@umich.edu        abspath = self.snode.abspath
2668232Snate@binkert.org        if not exists(abspath):
2675192Ssaidi@eecs.umich.edu            abspath = self.tnode.abspath
2688232Snate@binkert.org
2698232Snate@binkert.org        self.package = package
2708232Snate@binkert.org        self.modname = modname
2715192Ssaidi@eecs.umich.edu        self.modpath = modpath
2728232Snate@binkert.org        self.arcname = joinpath(*arcpath)
2735192Ssaidi@eecs.umich.edu        self.abspath = abspath
2745799Snate@binkert.org        self.compiled = File(self.filename + 'c')
2758232Snate@binkert.org        self.cpp = File(self.filename + '.cc')
2765192Ssaidi@eecs.umich.edu        self.symname = PySource.invalid_sym_char.sub('_', modpath)
2775192Ssaidi@eecs.umich.edu
2785192Ssaidi@eecs.umich.edu        PySource.modules[modpath] = self
2798232Snate@binkert.org        PySource.tnodes[self.tnode] = self
2805192Ssaidi@eecs.umich.edu        PySource.symnames[self.symname] = self
2818232Snate@binkert.org
2825192Ssaidi@eecs.umich.educlass SimObject(PySource):
2835192Ssaidi@eecs.umich.edu    '''Add a SimObject python file as a python source object and add
2845192Ssaidi@eecs.umich.edu    it to a list of sim object modules'''
2855192Ssaidi@eecs.umich.edu
2864382Sbinkertn@umich.edu    fixed = False
2874382Sbinkertn@umich.edu    modnames = []
2884382Sbinkertn@umich.edu
2892667Sstever@eecs.umich.edu    def __init__(self, source, tags=None, add_tags=None):
2902667Sstever@eecs.umich.edu        '''Specify the source file and any tags (automatically in
2912667Sstever@eecs.umich.edu        the m5.objects package)'''
2922667Sstever@eecs.umich.edu        super(SimObject, self).__init__('m5.objects', source, tags, add_tags)
2932667Sstever@eecs.umich.edu        if self.fixed:
2942667Sstever@eecs.umich.edu            raise AttributeError, "Too late to call SimObject now."
2955742Snate@binkert.org
2965742Snate@binkert.org        bisect.insort_right(SimObject.modnames, self.modname)
2975742Snate@binkert.org
2985793Snate@binkert.orgclass ProtoBuf(SourceFile):
2998334Snate@binkert.org    '''Add a Protocol Buffer to build'''
3005793Snate@binkert.org
3015793Snate@binkert.org    def __init__(self, source, tags=None, add_tags=None):
3025793Snate@binkert.org        '''Specify the source file, and any tags'''
3034382Sbinkertn@umich.edu        super(ProtoBuf, self).__init__(source, tags, add_tags)
3044762Snate@binkert.org
3055344Sstever@gmail.com        # Get the file name and the extension
3064382Sbinkertn@umich.edu        modname,ext = self.extname
3075341Sstever@gmail.com        assert ext == 'proto'
3085742Snate@binkert.org
3095742Snate@binkert.org        # Currently, we stick to generating the C++ headers, so we
3105742Snate@binkert.org        # only need to track the source and header.
3115742Snate@binkert.org        self.cc_file = File(modname + '.pb.cc')
3125742Snate@binkert.org        self.hh_file = File(modname + '.pb.h')
3134762Snate@binkert.org
3145742Snate@binkert.orgclass UnitTest(object):
3155742Snate@binkert.org    '''Create a UnitTest'''
3167722Sgblack@eecs.umich.edu
3175742Snate@binkert.org    all = []
3185742Snate@binkert.org    def __init__(self, target, *sources, **kwargs):
3195742Snate@binkert.org        '''Specify the target name and any sources.  Sources that are
3205742Snate@binkert.org        not SourceFiles are evalued with Source().  All files are
3218242Sbradley.danofsky@amd.com        tagged with the name of the UnitTest target.'''
3228242Sbradley.danofsky@amd.com
3238242Sbradley.danofsky@amd.com        srcs = SourceList()
3248242Sbradley.danofsky@amd.com        for src in sources:
3255341Sstever@gmail.com            if not isinstance(src, SourceFile):
3265742Snate@binkert.org                src = Source(src, tags=str(target))
3277722Sgblack@eecs.umich.edu            srcs.append(src)
3284773Snate@binkert.org
3296108Snate@binkert.org        self.sources = srcs
3301858SN/A        self.target = target
3311085SN/A        self.main = kwargs.get('main', False)
3326658Snate@binkert.org        self.all.append(self)
3336658Snate@binkert.org
3347673Snate@binkert.orgclass GTest(UnitTest):
3356658Snate@binkert.org    '''Create a unit test based on the google test framework.'''
3366658Snate@binkert.org    all = []
3376658Snate@binkert.org    def __init__(self, *args, **kwargs):
3386658Snate@binkert.org        isFilter = lambda arg: isinstance(arg, SourceFilter)
3396658Snate@binkert.org        self.filters = filter(isFilter, args)
3406658Snate@binkert.org        args = filter(lambda a: not isFilter(a), args)
3416658Snate@binkert.org        super(GTest, self).__init__(*args, **kwargs)
3427673Snate@binkert.org        self.dir = Dir('.')
3437673Snate@binkert.org        self.skip_lib = kwargs.pop('skip_lib', False)
3447673Snate@binkert.org
3457673Snate@binkert.org# Children should have access
3467673Snate@binkert.orgExport('Source')
3477673Snate@binkert.orgExport('PySource')
3487673Snate@binkert.orgExport('SimObject')
3496658Snate@binkert.orgExport('ProtoBuf')
3507673Snate@binkert.orgExport('UnitTest')
3517673Snate@binkert.orgExport('GTest')
3527673Snate@binkert.org
3537673Snate@binkert.org########################################################################
3547673Snate@binkert.org#
3557673Snate@binkert.org# Debug Flags
3567673Snate@binkert.org#
3577673Snate@binkert.orgdebug_flags = {}
3587673Snate@binkert.orgdef DebugFlag(name, desc=None):
3597673Snate@binkert.org    if name in debug_flags:
3606658Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
3617756SAli.Saidi@ARM.com    debug_flags[name] = (name, (), desc)
3627816Ssteve.reinhardt@amd.com
3636658Snate@binkert.orgdef CompoundFlag(name, flags, desc=None):
3644382Sbinkertn@umich.edu    if name in debug_flags:
3654382Sbinkertn@umich.edu        raise AttributeError, "Flag %s already specified" % name
3664762Snate@binkert.org
3674762Snate@binkert.org    compound = tuple(flags)
3684762Snate@binkert.org    debug_flags[name] = (name, compound, desc)
3696654Snate@binkert.org
3706654Snate@binkert.orgExport('DebugFlag')
3715517Snate@binkert.orgExport('CompoundFlag')
3725517Snate@binkert.org
3735517Snate@binkert.org########################################################################
3745517Snate@binkert.org#
3755517Snate@binkert.org# Set some compiler variables
3765517Snate@binkert.org#
3775517Snate@binkert.org
3785517Snate@binkert.org# Include file paths are rooted in this directory.  SCons will
3795517Snate@binkert.org# automatically expand '.' to refer to both the source directory and
3805517Snate@binkert.org# the corresponding build directory to pick up generated include
3815517Snate@binkert.org# files.
3825517Snate@binkert.orgenv.Append(CPPPATH=Dir('.'))
3835517Snate@binkert.org
3845517Snate@binkert.orgfor extra_dir in extras_dir_list:
3855517Snate@binkert.org    env.Append(CPPPATH=Dir(extra_dir))
3865517Snate@binkert.org
3875517Snate@binkert.org# Workaround for bug in SCons version > 0.97d20071212
3886654Snate@binkert.org# Scons bug id: 2006 gem5 Bug id: 308
3895517Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
3905517Snate@binkert.org    Dir(root[len(base_dir) + 1:])
3915517Snate@binkert.org
3925517Snate@binkert.org########################################################################
3935517Snate@binkert.org#
3945517Snate@binkert.org# Walk the tree and execute all SConscripts in subdirectories
3955517Snate@binkert.org#
3965517Snate@binkert.org
3976143Snate@binkert.orghere = Dir('.').srcnode().abspath
3986654Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
3995517Snate@binkert.org    if root == here:
4005517Snate@binkert.org        # we don't want to recurse back into this SConscript
4015517Snate@binkert.org        continue
4025517Snate@binkert.org
4035517Snate@binkert.org    if 'SConscript' in files:
4045517Snate@binkert.org        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
4055517Snate@binkert.org        Source.set_group(build_dir)
4065517Snate@binkert.org        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
4075517Snate@binkert.org
4085517Snate@binkert.orgfor extra_dir in extras_dir_list:
4095517Snate@binkert.org    prefix_len = len(dirname(extra_dir)) + 1
4105517Snate@binkert.org
4115517Snate@binkert.org    # Also add the corresponding build directory to pick up generated
4125517Snate@binkert.org    # include files.
4136654Snate@binkert.org    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
4146654Snate@binkert.org
4155517Snate@binkert.org    for root, dirs, files in os.walk(extra_dir, topdown=True):
4165517Snate@binkert.org        # if build lives in the extras directory, don't walk down it
4176143Snate@binkert.org        if 'build' in dirs:
4186143Snate@binkert.org            dirs.remove('build')
4196143Snate@binkert.org
4206727Ssteve.reinhardt@amd.com        if 'SConscript' in files:
4215517Snate@binkert.org            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
4226727Ssteve.reinhardt@amd.com            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
4235517Snate@binkert.org
4245517Snate@binkert.orgfor opt in export_vars:
4255517Snate@binkert.org    env.ConfigFile(opt)
4266654Snate@binkert.org
4276654Snate@binkert.orgdef makeTheISA(source, target, env):
4287673Snate@binkert.org    isas = [ src.get_contents() for src in source ]
4296654Snate@binkert.org    target_isa = env['TARGET_ISA']
4306654Snate@binkert.org    def define(isa):
4316654Snate@binkert.org        return isa.upper() + '_ISA'
4326654Snate@binkert.org
4335517Snate@binkert.org    def namespace(isa):
4345517Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA'
4355517Snate@binkert.org
4366143Snate@binkert.org
4375517Snate@binkert.org    code = code_formatter()
4384762Snate@binkert.org    code('''\
4395517Snate@binkert.org#ifndef __CONFIG_THE_ISA_HH__
4405517Snate@binkert.org#define __CONFIG_THE_ISA_HH__
4416143Snate@binkert.org
4426143Snate@binkert.org''')
4435517Snate@binkert.org
4445517Snate@binkert.org    # create defines for the preprocessing and compile-time determination
4455517Snate@binkert.org    for i,isa in enumerate(isas):
4465517Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
4475517Snate@binkert.org    code()
4485517Snate@binkert.org
4495517Snate@binkert.org    # create an enum for any run-time determination of the ISA, we
4505517Snate@binkert.org    # reuse the same name as the namespaces
4515517Snate@binkert.org    code('enum class Arch {')
4528596Ssteve.reinhardt@amd.com    for i,isa in enumerate(isas):
4538596Ssteve.reinhardt@amd.com        if i + 1 == len(isas):
4548596Ssteve.reinhardt@amd.com            code('  $0 = $1', namespace(isa), define(isa))
4558596Ssteve.reinhardt@amd.com        else:
4568596Ssteve.reinhardt@amd.com            code('  $0 = $1,', namespace(isa), define(isa))
4578596Ssteve.reinhardt@amd.com    code('};')
4588596Ssteve.reinhardt@amd.com
4596143Snate@binkert.org    code('''
4605517Snate@binkert.org
4616654Snate@binkert.org#define THE_ISA ${{define(target_isa)}}
4626654Snate@binkert.org#define TheISA ${{namespace(target_isa)}}
4636654Snate@binkert.org#define THE_ISA_STR "${{target_isa}}"
4646654Snate@binkert.org
4656654Snate@binkert.org#endif // __CONFIG_THE_ISA_HH__''')
4666654Snate@binkert.org
4675517Snate@binkert.org    code.write(str(target[0]))
4685517Snate@binkert.org
4695517Snate@binkert.orgenv.Command('config/the_isa.hh', map(Value, all_isa_list),
4708596Ssteve.reinhardt@amd.com            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
4718596Ssteve.reinhardt@amd.com
4724762Snate@binkert.orgdef makeTheGPUISA(source, target, env):
4734762Snate@binkert.org    isas = [ src.get_contents() for src in source ]
4744762Snate@binkert.org    target_gpu_isa = env['TARGET_GPU_ISA']
4754762Snate@binkert.org    def define(isa):
4764762Snate@binkert.org        return isa.upper() + '_ISA'
4774762Snate@binkert.org
4787675Snate@binkert.org    def namespace(isa):
4794762Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA'
4804762Snate@binkert.org
4814762Snate@binkert.org
4824762Snate@binkert.org    code = code_formatter()
4834382Sbinkertn@umich.edu    code('''\
4844382Sbinkertn@umich.edu#ifndef __CONFIG_THE_GPU_ISA_HH__
4855517Snate@binkert.org#define __CONFIG_THE_GPU_ISA_HH__
4866654Snate@binkert.org
4875517Snate@binkert.org''')
4888126Sgblack@eecs.umich.edu
4896654Snate@binkert.org    # create defines for the preprocessing and compile-time determination
4907673Snate@binkert.org    for i,isa in enumerate(isas):
4916654Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
4926654Snate@binkert.org    code()
4936654Snate@binkert.org
4946654Snate@binkert.org    # create an enum for any run-time determination of the ISA, we
4956654Snate@binkert.org    # reuse the same name as the namespaces
4966654Snate@binkert.org    code('enum class GPUArch {')
4976654Snate@binkert.org    for i,isa in enumerate(isas):
4986669Snate@binkert.org        if i + 1 == len(isas):
4996669Snate@binkert.org            code('  $0 = $1', namespace(isa), define(isa))
5006669Snate@binkert.org        else:
5016669Snate@binkert.org            code('  $0 = $1,', namespace(isa), define(isa))
5026669Snate@binkert.org    code('};')
5036669Snate@binkert.org
5046654Snate@binkert.org    code('''
5057673Snate@binkert.org
5065517Snate@binkert.org#define THE_GPU_ISA ${{define(target_gpu_isa)}}
5078126Sgblack@eecs.umich.edu#define TheGpuISA ${{namespace(target_gpu_isa)}}
5085798Snate@binkert.org#define THE_GPU_ISA_STR "${{target_gpu_isa}}"
5097756SAli.Saidi@ARM.com
5107816Ssteve.reinhardt@amd.com#endif // __CONFIG_THE_GPU_ISA_HH__''')
5115798Snate@binkert.org
5125798Snate@binkert.org    code.write(str(target[0]))
5135517Snate@binkert.org
5145517Snate@binkert.orgenv.Command('config/the_gpu_isa.hh', map(Value, all_gpu_isa_list),
5157673Snate@binkert.org            MakeAction(makeTheGPUISA, Transform("CFG ISA", 0)))
5165517Snate@binkert.org
5175517Snate@binkert.org########################################################################
5187673Snate@binkert.org#
5197673Snate@binkert.org# Prevent any SimObjects from being added after this point, they
5205517Snate@binkert.org# should all have been added in the SConscripts above
5215798Snate@binkert.org#
5225798Snate@binkert.orgSimObject.fixed = True
5238333Snate@binkert.org
5247816Ssteve.reinhardt@amd.comclass DictImporter(object):
5255798Snate@binkert.org    '''This importer takes a dictionary of arbitrary module names that
5265798Snate@binkert.org    map to arbitrary filenames.'''
5274762Snate@binkert.org    def __init__(self, modules):
5284762Snate@binkert.org        self.modules = modules
5294762Snate@binkert.org        self.installed = set()
5304762Snate@binkert.org
5314762Snate@binkert.org    def __del__(self):
5328596Ssteve.reinhardt@amd.com        self.unload()
5335517Snate@binkert.org
5345517Snate@binkert.org    def unload(self):
5355517Snate@binkert.org        import sys
5365517Snate@binkert.org        for module in self.installed:
5375517Snate@binkert.org            del sys.modules[module]
5387673Snate@binkert.org        self.installed = set()
5398596Ssteve.reinhardt@amd.com
5407673Snate@binkert.org    def find_module(self, fullname, path):
5415517Snate@binkert.org        if fullname == 'm5.defines':
5428596Ssteve.reinhardt@amd.com            return self
5435517Snate@binkert.org
5445517Snate@binkert.org        if fullname == 'm5.objects':
5455517Snate@binkert.org            return self
5468596Ssteve.reinhardt@amd.com
5475517Snate@binkert.org        if fullname.startswith('_m5'):
5487673Snate@binkert.org            return None
5497673Snate@binkert.org
5507673Snate@binkert.org        source = self.modules.get(fullname, None)
5515517Snate@binkert.org        if source is not None and fullname.startswith('m5.objects'):
5525517Snate@binkert.org            return self
5535517Snate@binkert.org
5545517Snate@binkert.org        return None
5555517Snate@binkert.org
5565517Snate@binkert.org    def load_module(self, fullname):
5575517Snate@binkert.org        mod = imp.new_module(fullname)
5587673Snate@binkert.org        sys.modules[fullname] = mod
5597673Snate@binkert.org        self.installed.add(fullname)
5607673Snate@binkert.org
5615517Snate@binkert.org        mod.__loader__ = self
5628596Ssteve.reinhardt@amd.com        if fullname == 'm5.objects':
5635517Snate@binkert.org            mod.__path__ = fullname.split('.')
5645517Snate@binkert.org            return mod
5655517Snate@binkert.org
5665517Snate@binkert.org        if fullname == 'm5.defines':
5675517Snate@binkert.org            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
5687673Snate@binkert.org            return mod
5697673Snate@binkert.org
5707673Snate@binkert.org        source = self.modules[fullname]
5715517Snate@binkert.org        if source.modname == '__init__':
5728596Ssteve.reinhardt@amd.com            mod.__path__ = source.modpath
5737675Snate@binkert.org        mod.__file__ = source.abspath
5747675Snate@binkert.org
5757675Snate@binkert.org        exec file(source.abspath, 'r') in mod.__dict__
5767675Snate@binkert.org
5777675Snate@binkert.org        return mod
5787675Snate@binkert.org
5798596Ssteve.reinhardt@amd.comimport m5.SimObject
5807675Snate@binkert.orgimport m5.params
5817675Snate@binkert.orgfrom m5.util import code_formatter
5828596Ssteve.reinhardt@amd.com
5838596Ssteve.reinhardt@amd.comm5.SimObject.clear()
5848596Ssteve.reinhardt@amd.comm5.params.clear()
5858596Ssteve.reinhardt@amd.com
5868596Ssteve.reinhardt@amd.com# install the python importer so we can grab stuff from the source
5878596Ssteve.reinhardt@amd.com# tree itself.  We can't have SimObjects added after this point or
5888596Ssteve.reinhardt@amd.com# else we won't know about them for the rest of the stuff.
5898596Ssteve.reinhardt@amd.comimporter = DictImporter(PySource.modules)
5908596Ssteve.reinhardt@amd.comsys.meta_path[0:0] = [ importer ]
5914762Snate@binkert.org
5926143Snate@binkert.org# import all sim objects so we can populate the all_objects list
5936143Snate@binkert.org# make sure that we're working with a list, then let's sort it
5946143Snate@binkert.orgfor modname in SimObject.modnames:
5954762Snate@binkert.org    exec('from m5.objects import %s' % modname)
5964762Snate@binkert.org
5974762Snate@binkert.org# we need to unload all of the currently imported modules so that they
5987756SAli.Saidi@ARM.com# will be re-imported the next time the sconscript is run
5998596Ssteve.reinhardt@amd.comimporter.unload()
6004762Snate@binkert.orgsys.meta_path.remove(importer)
6014762Snate@binkert.org
6028596Ssteve.reinhardt@amd.comsim_objects = m5.SimObject.allClasses
6035463Snate@binkert.orgall_enums = m5.params.allEnums
6048596Ssteve.reinhardt@amd.com
6058596Ssteve.reinhardt@amd.comfor name,obj in sorted(sim_objects.iteritems()):
6065463Snate@binkert.org    for param in obj._params.local.values():
6077756SAli.Saidi@ARM.com        # load the ptype attribute now because it depends on the
6088596Ssteve.reinhardt@amd.com        # current version of SimObject.allClasses, but when scons
6094762Snate@binkert.org        # actually uses the value, all versions of
6107677Snate@binkert.org        # SimObject.allClasses will have been loaded
6114762Snate@binkert.org        param.ptype
6124762Snate@binkert.org
6136143Snate@binkert.org########################################################################
6146143Snate@binkert.org#
6156143Snate@binkert.org# calculate extra dependencies
6164762Snate@binkert.org#
6174762Snate@binkert.orgmodule_depends = ["m5", "m5.SimObject", "m5.params"]
6187756SAli.Saidi@ARM.comdepends = [ PySource.modules[dep].snode for dep in module_depends ]
6197816Ssteve.reinhardt@amd.comdepends.sort(key = lambda x: x.name)
6204762Snate@binkert.org
6214762Snate@binkert.org########################################################################
6224762Snate@binkert.org#
6234762Snate@binkert.org# Commands for the basic automatically generated python files
6247756SAli.Saidi@ARM.com#
6258596Ssteve.reinhardt@amd.com
6264762Snate@binkert.org# Generate Python file containing a dict specifying the current
6274762Snate@binkert.org# buildEnv flags.
6287677Snate@binkert.orgdef makeDefinesPyFile(target, source, env):
6297756SAli.Saidi@ARM.com    build_env = source[0].get_contents()
6308596Ssteve.reinhardt@amd.com
6317675Snate@binkert.org    code = code_formatter()
6327677Snate@binkert.org    code("""
6335517Snate@binkert.orgimport _m5.core
6348596Ssteve.reinhardt@amd.comimport m5.util
6357675Snate@binkert.org
6368596Ssteve.reinhardt@amd.combuildEnv = m5.util.SmartDict($build_env)
6378596Ssteve.reinhardt@amd.com
6388596Ssteve.reinhardt@amd.comcompileDate = _m5.core.compileDate
6398596Ssteve.reinhardt@amd.com_globals = globals()
6408596Ssteve.reinhardt@amd.comfor key,val in _m5.core.__dict__.iteritems():
6414762Snate@binkert.org    if key.startswith('flag_'):
6427674Snate@binkert.org        flag = key[5:]
6437674Snate@binkert.org        _globals[flag] = val
6447674Snate@binkert.orgdel _globals
6457674Snate@binkert.org""")
6467674Snate@binkert.org    code.write(target[0].abspath)
6477674Snate@binkert.org
6487674Snate@binkert.orgdefines_info = Value(build_env)
6497674Snate@binkert.org# Generate a file with all of the compile options in it
6507674Snate@binkert.orgenv.Command('python/m5/defines.py', defines_info,
6517674Snate@binkert.org            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
6527674Snate@binkert.orgPySource('m5', 'python/m5/defines.py')
6537674Snate@binkert.org
6547674Snate@binkert.org# Generate python file containing info about the M5 source code
6557674Snate@binkert.orgdef makeInfoPyFile(target, source, env):
6567674Snate@binkert.org    code = code_formatter()
6574762Snate@binkert.org    for src in source:
6586143Snate@binkert.org        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
6596143Snate@binkert.org        code('$src = ${{repr(data)}}')
6607756SAli.Saidi@ARM.com    code.write(str(target[0]))
6617816Ssteve.reinhardt@amd.com
6628235Snate@binkert.org# Generate a file that wraps the basic top level files
6638596Ssteve.reinhardt@amd.comenv.Command('python/m5/info.py',
6647756SAli.Saidi@ARM.com            [ '#/COPYING', '#/LICENSE', '#/README', ],
6657816Ssteve.reinhardt@amd.com            MakeAction(makeInfoPyFile, Transform("INFO")))
6668235Snate@binkert.orgPySource('m5', 'python/m5/info.py')
6674382Sbinkertn@umich.edu
6688232Snate@binkert.org########################################################################
6698232Snate@binkert.org#
6708232Snate@binkert.org# Create all of the SimObject param headers and enum headers
6718232Snate@binkert.org#
6728232Snate@binkert.org
6736229Snate@binkert.orgdef createSimObjectParamStruct(target, source, env):
6748232Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6758232Snate@binkert.org
6768232Snate@binkert.org    name = source[0].get_text_contents()
6776229Snate@binkert.org    obj = sim_objects[name]
6787673Snate@binkert.org
6795517Snate@binkert.org    code = code_formatter()
6805517Snate@binkert.org    obj.cxx_param_decl(code)
6817673Snate@binkert.org    code.write(target[0].abspath)
6825517Snate@binkert.org
6835517Snate@binkert.orgdef createSimObjectCxxConfig(is_header):
6845517Snate@binkert.org    def body(target, source, env):
6855517Snate@binkert.org        assert len(target) == 1 and len(source) == 1
6868232Snate@binkert.org
6877673Snate@binkert.org        name = str(source[0].get_contents())
6887673Snate@binkert.org        obj = sim_objects[name]
6898232Snate@binkert.org
6908232Snate@binkert.org        code = code_formatter()
6918232Snate@binkert.org        obj.cxx_config_param_file(code, is_header)
6928232Snate@binkert.org        code.write(target[0].abspath)
6937673Snate@binkert.org    return body
6945517Snate@binkert.org
6958232Snate@binkert.orgdef createEnumStrings(target, source, env):
6968232Snate@binkert.org    assert len(target) == 1 and len(source) == 2
6978232Snate@binkert.org
6988232Snate@binkert.org    name = source[0].get_text_contents()
6997673Snate@binkert.org    use_python = source[1].read()
7008232Snate@binkert.org    obj = all_enums[name]
7018232Snate@binkert.org
7028232Snate@binkert.org    code = code_formatter()
7038232Snate@binkert.org    obj.cxx_def(code)
7048232Snate@binkert.org    if use_python:
7058232Snate@binkert.org        obj.pybind_def(code)
7067673Snate@binkert.org    code.write(target[0].abspath)
7075517Snate@binkert.org
7088232Snate@binkert.orgdef createEnumDecls(target, source, env):
7098232Snate@binkert.org    assert len(target) == 1 and len(source) == 1
7105517Snate@binkert.org
7117673Snate@binkert.org    name = source[0].get_text_contents()
7125517Snate@binkert.org    obj = all_enums[name]
7138232Snate@binkert.org
7148232Snate@binkert.org    code = code_formatter()
7155517Snate@binkert.org    obj.cxx_decl(code)
7168232Snate@binkert.org    code.write(target[0].abspath)
7178232Snate@binkert.org
7188232Snate@binkert.orgdef createSimObjectPyBindWrapper(target, source, env):
7197673Snate@binkert.org    name = source[0].get_text_contents()
7205517Snate@binkert.org    obj = sim_objects[name]
7215517Snate@binkert.org
7227673Snate@binkert.org    code = code_formatter()
7235517Snate@binkert.org    obj.pybind_decl(code)
7245517Snate@binkert.org    code.write(target[0].abspath)
7255517Snate@binkert.org
7268232Snate@binkert.org# Generate all of the SimObject param C++ struct header files
7275517Snate@binkert.orgparams_hh_files = []
7285517Snate@binkert.orgfor name,simobj in sorted(sim_objects.iteritems()):
7298232Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
7308232Snate@binkert.org    extra_deps = [ py_source.tnode ]
7315517Snate@binkert.org
7328232Snate@binkert.org    hh_file = File('params/%s.hh' % name)
7338232Snate@binkert.org    params_hh_files.append(hh_file)
7345517Snate@binkert.org    env.Command(hh_file, Value(name),
7358232Snate@binkert.org                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
7368232Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
7378232Snate@binkert.org
7385517Snate@binkert.org# C++ parameter description files
7398232Snate@binkert.orgif GetOption('with_cxx_config'):
7408232Snate@binkert.org    for name,simobj in sorted(sim_objects.iteritems()):
7418232Snate@binkert.org        py_source = PySource.modules[simobj.__module__]
7428232Snate@binkert.org        extra_deps = [ py_source.tnode ]
7438232Snate@binkert.org
7448232Snate@binkert.org        cxx_config_hh_file = File('cxx_config/%s.hh' % name)
7455517Snate@binkert.org        cxx_config_cc_file = File('cxx_config/%s.cc' % name)
7468232Snate@binkert.org        env.Command(cxx_config_hh_file, Value(name),
7478232Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(True),
7485517Snate@binkert.org                    Transform("CXXCPRHH")))
7498232Snate@binkert.org        env.Command(cxx_config_cc_file, Value(name),
7507673Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(False),
7515517Snate@binkert.org                    Transform("CXXCPRCC")))
7527673Snate@binkert.org        env.Depends(cxx_config_hh_file, depends + extra_deps +
7535517Snate@binkert.org                    [File('params/%s.hh' % name), File('sim/cxx_config.hh')])
7548232Snate@binkert.org        env.Depends(cxx_config_cc_file, depends + extra_deps +
7558232Snate@binkert.org                    [cxx_config_hh_file])
7568232Snate@binkert.org        Source(cxx_config_cc_file)
7575192Ssaidi@eecs.umich.edu
7588232Snate@binkert.org    cxx_config_init_cc_file = File('cxx_config/init.cc')
7598232Snate@binkert.org
7608232Snate@binkert.org    def createCxxConfigInitCC(target, source, env):
7618232Snate@binkert.org        assert len(target) == 1 and len(source) == 1
7628232Snate@binkert.org
7635192Ssaidi@eecs.umich.edu        code = code_formatter()
7647674Snate@binkert.org
7655522Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems()):
7665522Snate@binkert.org            if not hasattr(simobj, 'abstract') or not simobj.abstract:
7677674Snate@binkert.org                code('#include "cxx_config/${name}.hh"')
7687674Snate@binkert.org        code()
7697674Snate@binkert.org        code('void cxxConfigInit()')
7707674Snate@binkert.org        code('{')
7717674Snate@binkert.org        code.indent()
7727674Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems()):
7737674Snate@binkert.org            not_abstract = not hasattr(simobj, 'abstract') or \
7747674Snate@binkert.org                not simobj.abstract
7755522Snate@binkert.org            if not_abstract and 'type' in simobj.__dict__:
7765522Snate@binkert.org                code('cxx_config_directory["${name}"] = '
7775522Snate@binkert.org                     '${name}CxxConfigParams::makeDirectoryEntry();')
7785517Snate@binkert.org        code.dedent()
7795522Snate@binkert.org        code('}')
7805517Snate@binkert.org        code.write(target[0].abspath)
7816143Snate@binkert.org
7826727Ssteve.reinhardt@amd.com    py_source = PySource.modules[simobj.__module__]
7835522Snate@binkert.org    extra_deps = [ py_source.tnode ]
7845522Snate@binkert.org    env.Command(cxx_config_init_cc_file, Value(name),
7855522Snate@binkert.org        MakeAction(createCxxConfigInitCC, Transform("CXXCINIT")))
7867674Snate@binkert.org    cxx_param_hh_files = ["cxx_config/%s.hh" % simobj
7875517Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems())
7887673Snate@binkert.org        if not hasattr(simobj, 'abstract') or not simobj.abstract]
7897673Snate@binkert.org    Depends(cxx_config_init_cc_file, cxx_param_hh_files +
7907674Snate@binkert.org            [File('sim/cxx_config.hh')])
7917673Snate@binkert.org    Source(cxx_config_init_cc_file)
7927674Snate@binkert.org
7937674Snate@binkert.org# Generate all enum header files
7947674Snate@binkert.orgfor name,enum in sorted(all_enums.iteritems()):
7957674Snate@binkert.org    py_source = PySource.modules[enum.__module__]
7967674Snate@binkert.org    extra_deps = [ py_source.tnode ]
7977674Snate@binkert.org
7985522Snate@binkert.org    cc_file = File('enums/%s.cc' % name)
7995522Snate@binkert.org    env.Command(cc_file, [Value(name), Value(env['USE_PYTHON'])],
8007674Snate@binkert.org                MakeAction(createEnumStrings, Transform("ENUM STR")))
8017674Snate@binkert.org    env.Depends(cc_file, depends + extra_deps)
8027674Snate@binkert.org    Source(cc_file)
8037674Snate@binkert.org
8047673Snate@binkert.org    hh_file = File('enums/%s.hh' % name)
8057674Snate@binkert.org    env.Command(hh_file, Value(name),
8067674Snate@binkert.org                MakeAction(createEnumDecls, Transform("ENUMDECL")))
8077674Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
8087674Snate@binkert.org
8097674Snate@binkert.org# Generate SimObject Python bindings wrapper files
8107674Snate@binkert.orgif env['USE_PYTHON']:
8117674Snate@binkert.org    for name,simobj in sorted(sim_objects.iteritems()):
8127674Snate@binkert.org        py_source = PySource.modules[simobj.__module__]
8137811Ssteve.reinhardt@amd.com        extra_deps = [ py_source.tnode ]
8147674Snate@binkert.org        cc_file = File('python/_m5/param_%s.cc' % name)
8157673Snate@binkert.org        env.Command(cc_file, Value(name),
8165522Snate@binkert.org                    MakeAction(createSimObjectPyBindWrapper,
8176143Snate@binkert.org                               Transform("SO PyBind")))
8187756SAli.Saidi@ARM.com        env.Depends(cc_file, depends + extra_deps)
8197816Ssteve.reinhardt@amd.com        Source(cc_file)
8207674Snate@binkert.org
8214382Sbinkertn@umich.edu# Build all protocol buffers if we have got protoc and protobuf available
8224382Sbinkertn@umich.eduif env['HAVE_PROTOBUF']:
8234382Sbinkertn@umich.edu    for proto in ProtoBuf.all:
8244382Sbinkertn@umich.edu        # Use both the source and header as the target, and the .proto
8254382Sbinkertn@umich.edu        # file as the source. When executing the protoc compiler, also
8264382Sbinkertn@umich.edu        # specify the proto_path to avoid having the generated files
8274382Sbinkertn@umich.edu        # include the path.
8284382Sbinkertn@umich.edu        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
8294382Sbinkertn@umich.edu                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
8304382Sbinkertn@umich.edu                               '--proto_path ${SOURCE.dir} $SOURCE',
8316143Snate@binkert.org                               Transform("PROTOC")))
832955SN/A
8332655Sstever@eecs.umich.edu        # Add the C++ source file
8342655Sstever@eecs.umich.edu        Source(proto.cc_file, tags=proto.tags)
8352655Sstever@eecs.umich.eduelif ProtoBuf.all:
8362655Sstever@eecs.umich.edu    print('Got protobuf to build, but lacks support!')
8372655Sstever@eecs.umich.edu    Exit(1)
8385601Snate@binkert.org
8395601Snate@binkert.org#
8408334Snate@binkert.org# Handle debug flags
8418334Snate@binkert.org#
8428334Snate@binkert.orgdef makeDebugFlagCC(target, source, env):
8435522Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
8445863Snate@binkert.org
8455601Snate@binkert.org    code = code_formatter()
8465601Snate@binkert.org
8475601Snate@binkert.org    # delay definition of CompoundFlags until after all the definition
8485863Snate@binkert.org    # of all constituent SimpleFlags
8496143Snate@binkert.org    comp_code = code_formatter()
8505559Snate@binkert.org
8515559Snate@binkert.org    # file header
8525559Snate@binkert.org    code('''
8535559Snate@binkert.org/*
8548614Sgblack@eecs.umich.edu * DO NOT EDIT THIS FILE! Automatically generated by SCons.
8558614Sgblack@eecs.umich.edu */
8568614Sgblack@eecs.umich.edu
8575601Snate@binkert.org#include "base/debug.hh"
8586143Snate@binkert.org
8596143Snate@binkert.orgnamespace Debug {
8606143Snate@binkert.org
8616143Snate@binkert.org''')
8626143Snate@binkert.org
8636143Snate@binkert.org    for name, flag in sorted(source[0].read().iteritems()):
8646143Snate@binkert.org        n, compound, desc = flag
8656143Snate@binkert.org        assert n == name
8666143Snate@binkert.org
8676143Snate@binkert.org        if not compound:
8686143Snate@binkert.org            code('SimpleFlag $name("$name", "$desc");')
8696143Snate@binkert.org        else:
8706143Snate@binkert.org            comp_code('CompoundFlag $name("$name", "$desc",')
8716143Snate@binkert.org            comp_code.indent()
8726143Snate@binkert.org            last = len(compound) - 1
8736143Snate@binkert.org            for i,flag in enumerate(compound):
8746143Snate@binkert.org                if i != last:
8756143Snate@binkert.org                    comp_code('&$flag,')
8766143Snate@binkert.org                else:
8776143Snate@binkert.org                    comp_code('&$flag);')
8786143Snate@binkert.org            comp_code.dedent()
8796143Snate@binkert.org
8806143Snate@binkert.org    code.append(comp_code)
8816143Snate@binkert.org    code()
8826143Snate@binkert.org    code('} // namespace Debug')
8838594Snate@binkert.org
8848594Snate@binkert.org    code.write(str(target[0]))
8858594Snate@binkert.org
8868594Snate@binkert.orgdef makeDebugFlagHH(target, source, env):
8876143Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
8886143Snate@binkert.org
8896143Snate@binkert.org    val = eval(source[0].get_contents())
8906143Snate@binkert.org    name, compound, desc = val
8916143Snate@binkert.org
8926240Snate@binkert.org    code = code_formatter()
8935554Snate@binkert.org
8945522Snate@binkert.org    # file header boilerplate
8955522Snate@binkert.org    code('''\
8965797Snate@binkert.org/*
8975797Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated by SCons.
8985522Snate@binkert.org */
8995601Snate@binkert.org
9008233Snate@binkert.org#ifndef __DEBUG_${name}_HH__
9018233Snate@binkert.org#define __DEBUG_${name}_HH__
9028235Snate@binkert.org
9038235Snate@binkert.orgnamespace Debug {
9048235Snate@binkert.org''')
9058235Snate@binkert.org
9068235Snate@binkert.org    if compound:
9078235Snate@binkert.org        code('class CompoundFlag;')
9088235Snate@binkert.org    code('class SimpleFlag;')
9096143Snate@binkert.org
9102655Sstever@eecs.umich.edu    if compound:
9116143Snate@binkert.org        code('extern CompoundFlag $name;')
9126143Snate@binkert.org        for flag in compound:
9138233Snate@binkert.org            code('extern SimpleFlag $flag;')
9146143Snate@binkert.org    else:
9156143Snate@binkert.org        code('extern SimpleFlag $name;')
9164007Ssaidi@eecs.umich.edu
9174596Sbinkertn@umich.edu    code('''
9184007Ssaidi@eecs.umich.edu}
9194596Sbinkertn@umich.edu
9207756SAli.Saidi@ARM.com#endif // __DEBUG_${name}_HH__
9217816Ssteve.reinhardt@amd.com''')
9228334Snate@binkert.org
9238334Snate@binkert.org    code.write(str(target[0]))
9248334Snate@binkert.org
9258334Snate@binkert.orgfor name,flag in sorted(debug_flags.iteritems()):
9265601Snate@binkert.org    n, compound, desc = flag
9275601Snate@binkert.org    assert n == name
9282655Sstever@eecs.umich.edu
929955SN/A    hh_file = 'debug/%s.hh' % name
9303918Ssaidi@eecs.umich.edu    env.Command(hh_file, Value(flag),
9313918Ssaidi@eecs.umich.edu                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
9323918Ssaidi@eecs.umich.edu
9333918Ssaidi@eecs.umich.eduenv.Command('debug/flags.cc', Value(debug_flags),
9343918Ssaidi@eecs.umich.edu            MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
9353918Ssaidi@eecs.umich.eduSource('debug/flags.cc')
9363918Ssaidi@eecs.umich.edu
9373918Ssaidi@eecs.umich.edu# version tags
9383918Ssaidi@eecs.umich.edutags = \
9393918Ssaidi@eecs.umich.eduenv.Command('sim/tags.cc', None,
9403918Ssaidi@eecs.umich.edu            MakeAction('util/cpt_upgrader.py --get-cc-file > $TARGET',
9413918Ssaidi@eecs.umich.edu                       Transform("VER TAGS")))
9423918Ssaidi@eecs.umich.eduenv.AlwaysBuild(tags)
9433918Ssaidi@eecs.umich.edu
9443940Ssaidi@eecs.umich.edu# Embed python files.  All .py files that have been indicated by a
9453940Ssaidi@eecs.umich.edu# PySource() call in a SConscript need to be embedded into the M5
9463940Ssaidi@eecs.umich.edu# library.  To do that, we compile the file to byte code, marshal the
9473942Ssaidi@eecs.umich.edu# byte code, compress it, and then generate a c++ file that
9483940Ssaidi@eecs.umich.edu# inserts the result into an array.
9493515Ssaidi@eecs.umich.edudef embedPyFile(target, source, env):
9503918Ssaidi@eecs.umich.edu    def c_str(string):
9514762Snate@binkert.org        if string is None:
9523515Ssaidi@eecs.umich.edu            return "0"
9532655Sstever@eecs.umich.edu        return '"%s"' % string
9543918Ssaidi@eecs.umich.edu
9553619Sbinkertn@umich.edu    '''Action function to compile a .py into a code object, marshal
956955SN/A    it, compress it, and stick it into an asm file so the code appears
957955SN/A    as just bytes with a label in the data section'''
9582655Sstever@eecs.umich.edu
9593918Ssaidi@eecs.umich.edu    src = file(str(source[0]), 'r').read()
9603619Sbinkertn@umich.edu
961955SN/A    pysource = PySource.tnodes[source[0]]
962955SN/A    compiled = compile(src, pysource.abspath, 'exec')
9632655Sstever@eecs.umich.edu    marshalled = marshal.dumps(compiled)
9643918Ssaidi@eecs.umich.edu    compressed = zlib.compress(marshalled)
9653619Sbinkertn@umich.edu    data = compressed
966955SN/A    sym = pysource.symname
967955SN/A
9682655Sstever@eecs.umich.edu    code = code_formatter()
9693918Ssaidi@eecs.umich.edu    code('''\
9703683Sstever@eecs.umich.edu#include "sim/init.hh"
9712655Sstever@eecs.umich.edu
9721869SN/Anamespace {
9731869SN/A
974const uint8_t data_${sym}[] = {
975''')
976    code.indent()
977    step = 16
978    for i in xrange(0, len(data), step):
979        x = array.array('B', data[i:i+step])
980        code(''.join('%d,' % d for d in x))
981    code.dedent()
982
983    code('''};
984
985EmbeddedPython embedded_${sym}(
986    ${{c_str(pysource.arcname)}},
987    ${{c_str(pysource.abspath)}},
988    ${{c_str(pysource.modpath)}},
989    data_${sym},
990    ${{len(data)}},
991    ${{len(marshalled)}});
992
993} // anonymous namespace
994''')
995    code.write(str(target[0]))
996
997for source in PySource.all:
998    env.Command(source.cpp, source.tnode,
999                MakeAction(embedPyFile, Transform("EMBED PY")))
1000    Source(source.cpp, tags=source.tags, add_tags='python')
1001
1002########################################################################
1003#
1004# Define binaries.  Each different build type (debug, opt, etc.) gets
1005# a slightly different build environment.
1006#
1007
1008# List of constructed environments to pass back to SConstruct
1009date_source = Source('base/date.cc', tags=[])
1010
1011# Function to create a new build environment as clone of current
1012# environment 'env' with modified object suffix and optional stripped
1013# binary.  Additional keyword arguments are appended to corresponding
1014# build environment vars.
1015def makeEnv(env, label, objsfx, strip=False, disable_partial=False, **kwargs):
1016    # SCons doesn't know to append a library suffix when there is a '.' in the
1017    # name.  Use '_' instead.
1018    libname = 'gem5_' + label
1019    exename = 'gem5.' + label
1020    secondary_exename = 'm5.' + label
1021
1022    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
1023    new_env.Label = label
1024    new_env.Append(**kwargs)
1025
1026    lib_sources = Source.all.with_tag('gem5 lib')
1027
1028    # Without Python, leave out all Python content from the library
1029    # builds.  The option doesn't affect gem5 built as a program
1030    if GetOption('without_python'):
1031        lib_sources = lib_sources.without_tag('python')
1032
1033    static_objs = []
1034    shared_objs = []
1035
1036    for s in lib_sources.with_tag(Source.ungrouped_tag):
1037        static_objs.append(s.static(new_env))
1038        shared_objs.append(s.shared(new_env))
1039
1040    for group in Source.source_groups:
1041        srcs = lib_sources.with_tag(Source.link_group_tag(group))
1042        if not srcs:
1043            continue
1044
1045        group_static = [ s.static(new_env) for s in srcs ]
1046        group_shared = [ s.shared(new_env) for s in srcs ]
1047
1048        # If partial linking is disabled, add these sources to the build
1049        # directly, and short circuit this loop.
1050        if disable_partial:
1051            static_objs.extend(group_static)
1052            shared_objs.extend(group_shared)
1053            continue
1054
1055        # Set up the static partially linked objects.
1056        file_name = new_env.subst("${OBJPREFIX}lib${OBJSUFFIX}.partial")
1057        target = File(joinpath(group, file_name))
1058        partial = env.PartialStatic(target=target, source=group_static)
1059        static_objs.extend(partial)
1060
1061        # Set up the shared partially linked objects.
1062        file_name = new_env.subst("${SHOBJPREFIX}lib${SHOBJSUFFIX}.partial")
1063        target = File(joinpath(group, file_name))
1064        partial = env.PartialShared(target=target, source=group_shared)
1065        shared_objs.extend(partial)
1066
1067    static_date = date_source.static(new_env)
1068    new_env.Depends(static_date, static_objs)
1069    static_objs.extend(static_date)
1070
1071    shared_date = date_source.shared(new_env)
1072    new_env.Depends(shared_date, shared_objs)
1073    shared_objs.extend(shared_date)
1074
1075    # First make a library of everything but main() so other programs can
1076    # link against m5.
1077    static_lib = new_env.StaticLibrary(libname, static_objs)
1078    shared_lib = new_env.SharedLibrary(libname, shared_objs)
1079
1080    # Now link a stub with main() and the static library.
1081    main_objs = [ s.static(new_env) for s in Source.all.with_tag('main') ]
1082
1083    for test in UnitTest.all:
1084        test_sources = Source.all.with_tag(str(test.target))
1085        test_objs = [ s.static(new_env) for s in test_sources ]
1086        if test.main:
1087            test_objs += main_objs
1088        path = 'unittest/%s.%s' % (test.target, label)
1089        new_env.Program(path, test_objs + static_objs)
1090
1091    gtest_env = new_env.Clone()
1092    gtest_env.Append(LIBS=gtest_env['GTEST_LIBS'])
1093    gtest_env.Append(CPPFLAGS=gtest_env['GTEST_CPPFLAGS'])
1094    gtestlib_sources = Source.all.with_tag('gtest lib')
1095    gtest_out_dir = Dir(new_env['BUILDDIR']).Dir('unittests.%s' % label)
1096    for test in GTest.all:
1097        test_sources = list(test.sources)
1098        if not test.skip_lib:
1099            test_sources += gtestlib_sources
1100        for f in test.filters:
1101            test_sources += Source.all.apply_filter(f)
1102        test_objs = [ s.static(gtest_env) for s in test_sources ]
1103        test_binary = gtest_env.Program(
1104            test.dir.File('%s.%s' % (test.target, label)), test_objs)
1105
1106        AlwaysBuild(gtest_env.Command(
1107            gtest_out_dir.File("%s/%s.xml" % (test.dir, test.target)),
1108            test_binary, "${SOURCES[0]} --gtest_output=xml:${TARGETS[0]}"))
1109
1110    progname = exename
1111    if strip:
1112        progname += '.unstripped'
1113
1114    targets = new_env.Program(progname, main_objs + static_objs)
1115
1116    if strip:
1117        if sys.platform == 'sunos5':
1118            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
1119        else:
1120            cmd = 'strip $SOURCE -o $TARGET'
1121        targets = new_env.Command(exename, progname,
1122                    MakeAction(cmd, Transform("STRIP")))
1123
1124    new_env.Command(secondary_exename, exename,
1125            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
1126
1127    new_env.M5Binary = targets[0]
1128
1129    # Set up regression tests.
1130    SConscript(os.path.join(env.root.abspath, 'tests', 'SConscript'),
1131               variant_dir=Dir('tests').Dir(new_env.Label),
1132               exports={ 'env' : new_env }, duplicate=False)
1133
1134# Start out with the compiler flags common to all compilers,
1135# i.e. they all use -g for opt and -g -pg for prof
1136ccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
1137           'perf' : ['-g']}
1138
1139# Start out with the linker flags common to all linkers, i.e. -pg for
1140# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
1141# no-as-needed and as-needed as the binutils linker is too clever and
1142# simply doesn't link to the library otherwise.
1143ldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
1144           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
1145
1146# For Link Time Optimization, the optimisation flags used to compile
1147# individual files are decoupled from those used at link time
1148# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
1149# to also update the linker flags based on the target.
1150if env['GCC']:
1151    if sys.platform == 'sunos5':
1152        ccflags['debug'] += ['-gstabs+']
1153    else:
1154        ccflags['debug'] += ['-ggdb3']
1155    ldflags['debug'] += ['-O0']
1156    # opt, fast, prof and perf all share the same cc flags, also add
1157    # the optimization to the ldflags as LTO defers the optimization
1158    # to link time
1159    for target in ['opt', 'fast', 'prof', 'perf']:
1160        ccflags[target] += ['-O3']
1161        ldflags[target] += ['-O3']
1162
1163    ccflags['fast'] += env['LTO_CCFLAGS']
1164    ldflags['fast'] += env['LTO_LDFLAGS']
1165elif env['CLANG']:
1166    ccflags['debug'] += ['-g', '-O0']
1167    # opt, fast, prof and perf all share the same cc flags
1168    for target in ['opt', 'fast', 'prof', 'perf']:
1169        ccflags[target] += ['-O3']
1170else:
1171    print('Unknown compiler, please fix compiler options')
1172    Exit(1)
1173
1174
1175# To speed things up, we only instantiate the build environments we
1176# need.  We try to identify the needed environment for each target; if
1177# we can't, we fall back on instantiating all the environments just to
1178# be safe.
1179target_types = ['debug', 'opt', 'fast', 'prof', 'perf']
1180obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
1181              'gpo' : 'perf'}
1182
1183def identifyTarget(t):
1184    ext = t.split('.')[-1]
1185    if ext in target_types:
1186        return ext
1187    if obj2target.has_key(ext):
1188        return obj2target[ext]
1189    match = re.search(r'/tests/([^/]+)/', t)
1190    if match and match.group(1) in target_types:
1191        return match.group(1)
1192    return 'all'
1193
1194needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
1195if 'all' in needed_envs:
1196    needed_envs += target_types
1197
1198# Debug binary
1199if 'debug' in needed_envs:
1200    makeEnv(env, 'debug', '.do',
1201            CCFLAGS = Split(ccflags['debug']),
1202            CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
1203            LINKFLAGS = Split(ldflags['debug']))
1204
1205# Optimized binary
1206if 'opt' in needed_envs:
1207    makeEnv(env, 'opt', '.o',
1208            CCFLAGS = Split(ccflags['opt']),
1209            CPPDEFINES = ['TRACING_ON=1'],
1210            LINKFLAGS = Split(ldflags['opt']))
1211
1212# "Fast" binary
1213if 'fast' in needed_envs:
1214    disable_partial = \
1215            env.get('BROKEN_INCREMENTAL_LTO', False) and \
1216            GetOption('force_lto')
1217    makeEnv(env, 'fast', '.fo', strip = True,
1218            CCFLAGS = Split(ccflags['fast']),
1219            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1220            LINKFLAGS = Split(ldflags['fast']),
1221            disable_partial=disable_partial)
1222
1223# Profiled binary using gprof
1224if 'prof' in needed_envs:
1225    makeEnv(env, 'prof', '.po',
1226            CCFLAGS = Split(ccflags['prof']),
1227            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1228            LINKFLAGS = Split(ldflags['prof']))
1229
1230# Profiled binary using google-pprof
1231if 'perf' in needed_envs:
1232    makeEnv(env, 'perf', '.gpo',
1233            CCFLAGS = Split(ccflags['perf']),
1234            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1235            LINKFLAGS = Split(ldflags['perf']))
1236