SConscript revision 12797
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'
1519982Satgutier@umich.edu        if isinstance(tags, basestring):
15210196SCurtis.Dunham@arm.com            tags = set([tags])
15310196SCurtis.Dunham@arm.com        if not isinstance(tags, set):
15410196SCurtis.Dunham@arm.com            tags = set(tags)
15510196SCurtis.Dunham@arm.com        self.tags = tags
15610196SCurtis.Dunham@arm.com
15710196SCurtis.Dunham@arm.com        if add_tags:
15810196SCurtis.Dunham@arm.com            if isinstance(add_tags, basestring):
15910196SCurtis.Dunham@arm.com                add_tags = set([add_tags])
1606143Snate@binkert.org            if not isinstance(add_tags, set):
1616143Snate@binkert.org                add_tags = set(add_tags)
1628945Ssteve.reinhardt@amd.com            self.tags |= add_tags
1638233Snate@binkert.org
1648233Snate@binkert.org        tnode = source
1656143Snate@binkert.org        if not isinstance(source, SCons.Node.FS.File):
1668945Ssteve.reinhardt@amd.com            tnode = File(source)
1676143Snate@binkert.org
1686143Snate@binkert.org        self.tnode = tnode
1696143Snate@binkert.org        self.snode = tnode.srcnode()
1706143Snate@binkert.org
1715522Snate@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
1759982Satgutier@umich.edu    def static(self, env):
1768233Snate@binkert.org        key = (self.tnode, env['OBJSUFFIX'])
1778233Snate@binkert.org        if not key in self.static_objs:
1788233Snate@binkert.org            self.static_objs[key] = env.StaticObject(self.tnode)
1796143Snate@binkert.org        return self.static_objs[key]
1806143Snate@binkert.org
1816143Snate@binkert.org    def shared(self, env):
1826143Snate@binkert.org        key = (self.tnode, env['OBJSUFFIX'])
1835522Snate@binkert.org        if not key in self.shared_objs:
1845522Snate@binkert.org            self.shared_objs[key] = env.SharedObject(self.tnode)
1855522Snate@binkert.org        return self.shared_objs[key]
1865522Snate@binkert.org
1875604Snate@binkert.org    @property
1885604Snate@binkert.org    def filename(self):
1896143Snate@binkert.org        return str(self.tnode)
1906143Snate@binkert.org
1914762Snate@binkert.org    @property
1924762Snate@binkert.org    def dirname(self):
1936143Snate@binkert.org        return dirname(self.filename)
1946727Ssteve.reinhardt@amd.com
1956727Ssteve.reinhardt@amd.com    @property
1966727Ssteve.reinhardt@amd.com    def basename(self):
1974762Snate@binkert.org        return basename(self.filename)
1986143Snate@binkert.org
1996143Snate@binkert.org    @property
2006143Snate@binkert.org    def extname(self):
2016143Snate@binkert.org        index = self.basename.rfind('.')
2026727Ssteve.reinhardt@amd.com        if index <= 0:
2036143Snate@binkert.org            # dot files aren't extensions
2047674Snate@binkert.org            return self.basename, None
2057674Snate@binkert.org
2065604Snate@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
2096143Snate@binkert.org    def __le__(self, other): return self.filename <= other.filename
2104762Snate@binkert.org    def __gt__(self, other): return self.filename > other.filename
2116143Snate@binkert.org    def __ge__(self, other): return self.filename >= other.filename
2124762Snate@binkert.org    def __eq__(self, other): return self.filename == other.filename
2134762Snate@binkert.org    def __ne__(self, other): return self.filename != other.filename
2144762Snate@binkert.org
2156143Snate@binkert.orgclass Source(SourceFile):
2166143Snate@binkert.org    ungrouped_tag = 'No link group'
2174762Snate@binkert.org    source_groups = set()
2188233Snate@binkert.org
2198233Snate@binkert.org    _current_group_tag = ungrouped_tag
2208233Snate@binkert.org
2218233Snate@binkert.org    @staticmethod
2226143Snate@binkert.org    def link_group_tag(group):
2236143Snate@binkert.org        return 'link group: %s' % group
2244762Snate@binkert.org
2256143Snate@binkert.org    @classmethod
2264762Snate@binkert.org    def set_group(cls, group):
2276143Snate@binkert.org        new_tag = Source.link_group_tag(group)
2284762Snate@binkert.org        Source._current_group_tag = new_tag
2296143Snate@binkert.org        Source.source_groups.add(group)
2308233Snate@binkert.org
2318233Snate@binkert.org    def _add_link_group_tag(self):
2328233Snate@binkert.org        self.tags.add(Source._current_group_tag)
2336143Snate@binkert.org
2346143Snate@binkert.org    '''Add a c/c++ source file to the build'''
2356143Snate@binkert.org    def __init__(self, source, tags=None, add_tags=None):
2366143Snate@binkert.org        '''specify the source file, and any tags'''
2376143Snate@binkert.org        super(Source, self).__init__(source, tags, add_tags)
2386143Snate@binkert.org        self._add_link_group_tag()
2396143Snate@binkert.org
2406143Snate@binkert.orgclass PySource(SourceFile):
2418233Snate@binkert.org    '''Add a python source file to the named package'''
2428233Snate@binkert.org    invalid_sym_char = re.compile('[^A-z0-9_]')
243955SN/A    modules = {}
2449396Sandreas.hansson@arm.com    tnodes = {}
2459396Sandreas.hansson@arm.com    symnames = {}
2469396Sandreas.hansson@arm.com
2479396Sandreas.hansson@arm.com    def __init__(self, package, source, tags=None, add_tags=None):
2489396Sandreas.hansson@arm.com        '''specify the python package, the source file, and any tags'''
2499396Sandreas.hansson@arm.com        super(PySource, self).__init__(source, tags, add_tags)
2509396Sandreas.hansson@arm.com
2519396Sandreas.hansson@arm.com        modname,ext = self.extname
2529396Sandreas.hansson@arm.com        assert ext == 'py'
2539396Sandreas.hansson@arm.com
2549396Sandreas.hansson@arm.com        if package:
2559396Sandreas.hansson@arm.com            path = package.split('.')
2569396Sandreas.hansson@arm.com        else:
2579930Sandreas.hansson@arm.com            path = []
2589930Sandreas.hansson@arm.com
2599396Sandreas.hansson@arm.com        modpath = path[:]
2608235Snate@binkert.org        if modname != '__init__':
2618235Snate@binkert.org            modpath += [ modname ]
2626143Snate@binkert.org        modpath = '.'.join(modpath)
2638235Snate@binkert.org
2649003SAli.Saidi@ARM.com        arcpath = path + [ self.basename ]
2658235Snate@binkert.org        abspath = self.snode.abspath
2668235Snate@binkert.org        if not exists(abspath):
2678235Snate@binkert.org            abspath = self.tnode.abspath
2688235Snate@binkert.org
2698235Snate@binkert.org        self.package = package
2708235Snate@binkert.org        self.modname = modname
2718235Snate@binkert.org        self.modpath = modpath
2728235Snate@binkert.org        self.arcname = joinpath(*arcpath)
2738235Snate@binkert.org        self.abspath = abspath
2748235Snate@binkert.org        self.compiled = File(self.filename + 'c')
2758235Snate@binkert.org        self.cpp = File(self.filename + '.cc')
2768235Snate@binkert.org        self.symname = PySource.invalid_sym_char.sub('_', modpath)
2778235Snate@binkert.org
2788235Snate@binkert.org        PySource.modules[modpath] = self
2799003SAli.Saidi@ARM.com        PySource.tnodes[self.tnode] = self
2808235Snate@binkert.org        PySource.symnames[self.symname] = self
2815584Snate@binkert.org
2824382Sbinkertn@umich.educlass SimObject(PySource):
2834202Sbinkertn@umich.edu    '''Add a SimObject python file as a python source object and add
2844382Sbinkertn@umich.edu    it to a list of sim object modules'''
2854382Sbinkertn@umich.edu
2864382Sbinkertn@umich.edu    fixed = False
2879396Sandreas.hansson@arm.com    modnames = []
2885584Snate@binkert.org
2894382Sbinkertn@umich.edu    def __init__(self, source, tags=None, add_tags=None):
2904382Sbinkertn@umich.edu        '''Specify the source file and any tags (automatically in
2914382Sbinkertn@umich.edu        the m5.objects package)'''
2928232Snate@binkert.org        super(SimObject, self).__init__('m5.objects', source, tags, add_tags)
2935192Ssaidi@eecs.umich.edu        if self.fixed:
2948232Snate@binkert.org            raise AttributeError, "Too late to call SimObject now."
2958232Snate@binkert.org
2968232Snate@binkert.org        bisect.insort_right(SimObject.modnames, self.modname)
2975192Ssaidi@eecs.umich.edu
2988232Snate@binkert.orgclass ProtoBuf(SourceFile):
2995192Ssaidi@eecs.umich.edu    '''Add a Protocol Buffer to build'''
3005799Snate@binkert.org
3018232Snate@binkert.org    def __init__(self, source, tags=None, add_tags=None):
3025192Ssaidi@eecs.umich.edu        '''Specify the source file, and any tags'''
3035192Ssaidi@eecs.umich.edu        super(ProtoBuf, self).__init__(source, tags, add_tags)
3045192Ssaidi@eecs.umich.edu
3058232Snate@binkert.org        # Get the file name and the extension
3065192Ssaidi@eecs.umich.edu        modname,ext = self.extname
3078232Snate@binkert.org        assert ext == 'proto'
3085192Ssaidi@eecs.umich.edu
3095192Ssaidi@eecs.umich.edu        # Currently, we stick to generating the C++ headers, so we
3105192Ssaidi@eecs.umich.edu        # only need to track the source and header.
3115192Ssaidi@eecs.umich.edu        self.cc_file = File(modname + '.pb.cc')
3124382Sbinkertn@umich.edu        self.hh_file = File(modname + '.pb.h')
3134382Sbinkertn@umich.edu
3144382Sbinkertn@umich.edu
3152667Sstever@eecs.umich.eduexectuable_classes = []
3162667Sstever@eecs.umich.educlass ExecutableMeta(type):
3172667Sstever@eecs.umich.edu    '''Meta class for Executables.'''
3182667Sstever@eecs.umich.edu    all = []
3192667Sstever@eecs.umich.edu
3202667Sstever@eecs.umich.edu    def __init__(cls, name, bases, d):
3215742Snate@binkert.org        if not d.pop('abstract', False):
3225742Snate@binkert.org            ExecutableMeta.all.append(cls)
3235742Snate@binkert.org        super(ExecutableMeta, cls).__init__(name, bases, d)
3245793Snate@binkert.org
3258334Snate@binkert.org        cls.all = []
3265793Snate@binkert.org
3275793Snate@binkert.orgclass Executable(object):
3285793Snate@binkert.org    '''Base class for creating an executable from sources.'''
3294382Sbinkertn@umich.edu    __metaclass__ = ExecutableMeta
3304762Snate@binkert.org
3315344Sstever@gmail.com    abstract = True
3324382Sbinkertn@umich.edu
3335341Sstever@gmail.com    def __init__(self, target, *srcs_and_filts):
3345742Snate@binkert.org        '''Specify the target name and any sources. Sources that are
3355742Snate@binkert.org        not SourceFiles are evalued with Source().'''
3365742Snate@binkert.org        super(Executable, self).__init__()
3375742Snate@binkert.org        self.all.append(self)
3385742Snate@binkert.org        self.target = target
3394762Snate@binkert.org
3405742Snate@binkert.org        isFilter = lambda arg: isinstance(arg, SourceFilter)
3415742Snate@binkert.org        self.filters = filter(isFilter, srcs_and_filts)
3427722Sgblack@eecs.umich.edu        sources = filter(lambda a: not isFilter(a), srcs_and_filts)
3435742Snate@binkert.org
3445742Snate@binkert.org        srcs = SourceList()
3455742Snate@binkert.org        for src in sources:
3469930Sandreas.hansson@arm.com            if not isinstance(src, SourceFile):
3479930Sandreas.hansson@arm.com                src = Source(src, tags=[])
3489930Sandreas.hansson@arm.com            srcs.append(src)
3499930Sandreas.hansson@arm.com
3509930Sandreas.hansson@arm.com        self.sources = srcs
3515742Snate@binkert.org        self.dir = Dir('.')
3528242Sbradley.danofsky@amd.com
3538242Sbradley.danofsky@amd.com    def path(self, env):
3548242Sbradley.danofsky@amd.com        return self.dir.File(self.target + '.' + env['EXE_SUFFIX'])
3558242Sbradley.danofsky@amd.com
3565341Sstever@gmail.com    def srcs_to_objs(self, env, sources):
3575742Snate@binkert.org        return list([ s.static(env) for s in sources ])
3587722Sgblack@eecs.umich.edu
3594773Snate@binkert.org    @classmethod
3606108Snate@binkert.org    def declare_all(cls, env):
3611858SN/A        return list([ instance.declare(env) for instance in cls.all ])
3621085SN/A
3636658Snate@binkert.org    def declare(self, env, objs=None):
3646658Snate@binkert.org        if objs is None:
3657673Snate@binkert.org            objs = self.srcs_to_objs(env, self.sources)
3666658Snate@binkert.org
3676658Snate@binkert.org        if env['STRIP_EXES']:
3686658Snate@binkert.org            stripped = self.path(env)
3696658Snate@binkert.org            unstripped = env.File(str(stripped) + '.unstripped')
3706658Snate@binkert.org            if sys.platform == 'sunos5':
3716658Snate@binkert.org                cmd = 'cp $SOURCE $TARGET; strip $TARGET'
3726658Snate@binkert.org            else:
3737673Snate@binkert.org                cmd = 'strip $SOURCE -o $TARGET'
3747673Snate@binkert.org            env.Program(unstripped, objs)
3757673Snate@binkert.org            return env.Command(stripped, unstripped,
3767673Snate@binkert.org                               MakeAction(cmd, Transform("STRIP")))
3777673Snate@binkert.org        else:
3787673Snate@binkert.org            return env.Program(self.path(env), objs)
3797673Snate@binkert.org
3806658Snate@binkert.orgclass UnitTest(Executable):
3817673Snate@binkert.org    '''Create a UnitTest'''
3827673Snate@binkert.org    def __init__(self, target, *srcs_and_filts, **kwargs):
3837673Snate@binkert.org        super(UnitTest, self).__init__(target, *srcs_and_filts)
3847673Snate@binkert.org
3857673Snate@binkert.org        self.main = kwargs.get('main', False)
3867673Snate@binkert.org
3879048SAli.Saidi@ARM.com    def declare(self, env):
3887673Snate@binkert.org        sources = list(self.sources)
3897673Snate@binkert.org        for f in self.filters:
3907673Snate@binkert.org            sources = Source.all.apply_filter(f)
3917673Snate@binkert.org        objs = self.srcs_to_objs(env, sources) + env['STATIC_OBJS']
3926658Snate@binkert.org        if self.main:
3937756SAli.Saidi@ARM.com            objs += env['MAIN_OBJS']
3947816Ssteve.reinhardt@amd.com        return super(UnitTest, self).declare(env, objs)
3956658Snate@binkert.org
3964382Sbinkertn@umich.educlass GTest(Executable):
3974382Sbinkertn@umich.edu    '''Create a unit test based on the google test framework.'''
3984762Snate@binkert.org    all = []
3994762Snate@binkert.org    def __init__(self, *srcs_and_filts, **kwargs):
4004762Snate@binkert.org        super(GTest, self).__init__(*srcs_and_filts)
4016654Snate@binkert.org
4026654Snate@binkert.org        self.skip_lib = kwargs.pop('skip_lib', False)
4035517Snate@binkert.org
4045517Snate@binkert.org    @classmethod
4055517Snate@binkert.org    def declare_all(cls, env):
4065517Snate@binkert.org        env = env.Clone()
4075517Snate@binkert.org        env.Append(LIBS=env['GTEST_LIBS'])
4085517Snate@binkert.org        env.Append(CPPFLAGS=env['GTEST_CPPFLAGS'])
4095517Snate@binkert.org        env['GTEST_LIB_SOURCES'] = Source.all.with_tag('gtest lib')
4105517Snate@binkert.org        env['GTEST_OUT_DIR'] = \
4115517Snate@binkert.org            Dir(env['BUILDDIR']).Dir('unittests.' + env['EXE_SUFFIX'])
4125517Snate@binkert.org        return super(GTest, cls).declare_all(env)
4135517Snate@binkert.org
4145517Snate@binkert.org    def declare(self, env):
4155517Snate@binkert.org        sources = list(self.sources)
4165517Snate@binkert.org        if not self.skip_lib:
4175517Snate@binkert.org            sources += env['GTEST_LIB_SOURCES']
4185517Snate@binkert.org        for f in self.filters:
4195517Snate@binkert.org            sources += Source.all.apply_filter(f)
4206654Snate@binkert.org        objs = self.srcs_to_objs(env, sources)
4215517Snate@binkert.org
4225517Snate@binkert.org        binary = super(GTest, self).declare(env, objs)
4235517Snate@binkert.org
4245517Snate@binkert.org        out_dir = env['GTEST_OUT_DIR']
4255517Snate@binkert.org        xml_file = out_dir.Dir(str(self.dir)).File(self.target + '.xml')
4265517Snate@binkert.org        AlwaysBuild(env.Command(xml_file, binary,
4275517Snate@binkert.org            "${SOURCES[0]} --gtest_output=xml:${TARGETS[0]}"))
4285517Snate@binkert.org
4296143Snate@binkert.org        return binary
4306654Snate@binkert.org
4315517Snate@binkert.orgclass Gem5(Executable):
4325517Snate@binkert.org    '''Create a gem5 executable.'''
4335517Snate@binkert.org
4345517Snate@binkert.org    def __init__(self, target):
4355517Snate@binkert.org        super(Gem5, self).__init__(target)
4365517Snate@binkert.org
4375517Snate@binkert.org    def declare(self, env):
4385517Snate@binkert.org        objs = env['MAIN_OBJS'] + env['STATIC_OBJS']
4395517Snate@binkert.org        return super(Gem5, self).declare(env, objs)
4405517Snate@binkert.org
4415517Snate@binkert.org
4425517Snate@binkert.org# Children should have access
4435517Snate@binkert.orgExport('Source')
4445517Snate@binkert.orgExport('PySource')
4456654Snate@binkert.orgExport('SimObject')
4466654Snate@binkert.orgExport('ProtoBuf')
4475517Snate@binkert.orgExport('Executable')
4485517Snate@binkert.orgExport('UnitTest')
4496143Snate@binkert.orgExport('GTest')
4506143Snate@binkert.org
4516143Snate@binkert.org########################################################################
4526727Ssteve.reinhardt@amd.com#
4535517Snate@binkert.org# Debug Flags
4546727Ssteve.reinhardt@amd.com#
4555517Snate@binkert.orgdebug_flags = {}
4565517Snate@binkert.orgdef DebugFlag(name, desc=None):
4575517Snate@binkert.org    if name in debug_flags:
4586654Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
4596654Snate@binkert.org    debug_flags[name] = (name, (), desc)
4607673Snate@binkert.org
4616654Snate@binkert.orgdef CompoundFlag(name, flags, desc=None):
4626654Snate@binkert.org    if name in debug_flags:
4636654Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
4646654Snate@binkert.org
4655517Snate@binkert.org    compound = tuple(flags)
4665517Snate@binkert.org    debug_flags[name] = (name, compound, desc)
4675517Snate@binkert.org
4686143Snate@binkert.orgExport('DebugFlag')
4695517Snate@binkert.orgExport('CompoundFlag')
4704762Snate@binkert.org
4715517Snate@binkert.org########################################################################
4725517Snate@binkert.org#
4736143Snate@binkert.org# Set some compiler variables
4746143Snate@binkert.org#
4755517Snate@binkert.org
4765517Snate@binkert.org# Include file paths are rooted in this directory.  SCons will
4775517Snate@binkert.org# automatically expand '.' to refer to both the source directory and
4785517Snate@binkert.org# the corresponding build directory to pick up generated include
4795517Snate@binkert.org# files.
4805517Snate@binkert.orgenv.Append(CPPPATH=Dir('.'))
4815517Snate@binkert.org
4825517Snate@binkert.orgfor extra_dir in extras_dir_list:
4835517Snate@binkert.org    env.Append(CPPPATH=Dir(extra_dir))
4849338SAndreas.Sandberg@arm.com
4859338SAndreas.Sandberg@arm.com# Workaround for bug in SCons version > 0.97d20071212
4869338SAndreas.Sandberg@arm.com# Scons bug id: 2006 gem5 Bug id: 308
4879338SAndreas.Sandberg@arm.comfor root, dirs, files in os.walk(base_dir, topdown=True):
4889338SAndreas.Sandberg@arm.com    Dir(root[len(base_dir) + 1:])
4899338SAndreas.Sandberg@arm.com
4908596Ssteve.reinhardt@amd.com########################################################################
4918596Ssteve.reinhardt@amd.com#
4928596Ssteve.reinhardt@amd.com# Walk the tree and execute all SConscripts in subdirectories
4938596Ssteve.reinhardt@amd.com#
4948596Ssteve.reinhardt@amd.com
4958596Ssteve.reinhardt@amd.comhere = Dir('.').srcnode().abspath
4968596Ssteve.reinhardt@amd.comfor root, dirs, files in os.walk(base_dir, topdown=True):
4976143Snate@binkert.org    if root == here:
4985517Snate@binkert.org        # we don't want to recurse back into this SConscript
4996654Snate@binkert.org        continue
5006654Snate@binkert.org
5016654Snate@binkert.org    if 'SConscript' in files:
5026654Snate@binkert.org        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
5036654Snate@binkert.org        Source.set_group(build_dir)
5046654Snate@binkert.org        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
5055517Snate@binkert.org
5065517Snate@binkert.orgfor extra_dir in extras_dir_list:
5075517Snate@binkert.org    prefix_len = len(dirname(extra_dir)) + 1
5088596Ssteve.reinhardt@amd.com
5098596Ssteve.reinhardt@amd.com    # Also add the corresponding build directory to pick up generated
5104762Snate@binkert.org    # include files.
5114762Snate@binkert.org    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
5124762Snate@binkert.org
5134762Snate@binkert.org    for root, dirs, files in os.walk(extra_dir, topdown=True):
5144762Snate@binkert.org        # if build lives in the extras directory, don't walk down it
5154762Snate@binkert.org        if 'build' in dirs:
5167675Snate@binkert.org            dirs.remove('build')
5174762Snate@binkert.org
5184762Snate@binkert.org        if 'SConscript' in files:
5194762Snate@binkert.org            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
5204762Snate@binkert.org            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
5214382Sbinkertn@umich.edu
5224382Sbinkertn@umich.edufor opt in export_vars:
5235517Snate@binkert.org    env.ConfigFile(opt)
5246654Snate@binkert.org
5255517Snate@binkert.orgdef makeTheISA(source, target, env):
5268126Sgblack@eecs.umich.edu    isas = [ src.get_contents() for src in source ]
5276654Snate@binkert.org    target_isa = env['TARGET_ISA']
5287673Snate@binkert.org    def define(isa):
5296654Snate@binkert.org        return isa.upper() + '_ISA'
5306654Snate@binkert.org
5316654Snate@binkert.org    def namespace(isa):
5326654Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA'
5336654Snate@binkert.org
5346654Snate@binkert.org
5356654Snate@binkert.org    code = code_formatter()
5366669Snate@binkert.org    code('''\
5376669Snate@binkert.org#ifndef __CONFIG_THE_ISA_HH__
5386669Snate@binkert.org#define __CONFIG_THE_ISA_HH__
5396669Snate@binkert.org
5406669Snate@binkert.org''')
5416669Snate@binkert.org
5426654Snate@binkert.org    # create defines for the preprocessing and compile-time determination
5437673Snate@binkert.org    for i,isa in enumerate(isas):
5445517Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
5458126Sgblack@eecs.umich.edu    code()
5465798Snate@binkert.org
5477756SAli.Saidi@ARM.com    # create an enum for any run-time determination of the ISA, we
5487816Ssteve.reinhardt@amd.com    # reuse the same name as the namespaces
5495798Snate@binkert.org    code('enum class Arch {')
5505798Snate@binkert.org    for i,isa in enumerate(isas):
5515517Snate@binkert.org        if i + 1 == len(isas):
5525517Snate@binkert.org            code('  $0 = $1', namespace(isa), define(isa))
5537673Snate@binkert.org        else:
5545517Snate@binkert.org            code('  $0 = $1,', namespace(isa), define(isa))
5555517Snate@binkert.org    code('};')
5567673Snate@binkert.org
5577673Snate@binkert.org    code('''
5585517Snate@binkert.org
5595798Snate@binkert.org#define THE_ISA ${{define(target_isa)}}
5605798Snate@binkert.org#define TheISA ${{namespace(target_isa)}}
5618333Snate@binkert.org#define THE_ISA_STR "${{target_isa}}"
5627816Ssteve.reinhardt@amd.com
5635798Snate@binkert.org#endif // __CONFIG_THE_ISA_HH__''')
5645798Snate@binkert.org
5654762Snate@binkert.org    code.write(str(target[0]))
5664762Snate@binkert.org
5674762Snate@binkert.orgenv.Command('config/the_isa.hh', map(Value, all_isa_list),
5684762Snate@binkert.org            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
5694762Snate@binkert.org
5708596Ssteve.reinhardt@amd.comdef makeTheGPUISA(source, target, env):
5715517Snate@binkert.org    isas = [ src.get_contents() for src in source ]
5725517Snate@binkert.org    target_gpu_isa = env['TARGET_GPU_ISA']
5735517Snate@binkert.org    def define(isa):
5745517Snate@binkert.org        return isa.upper() + '_ISA'
5755517Snate@binkert.org
5767673Snate@binkert.org    def namespace(isa):
5778596Ssteve.reinhardt@amd.com        return isa[0].upper() + isa[1:].lower() + 'ISA'
5787673Snate@binkert.org
5795517Snate@binkert.org
5808596Ssteve.reinhardt@amd.com    code = code_formatter()
5815517Snate@binkert.org    code('''\
5825517Snate@binkert.org#ifndef __CONFIG_THE_GPU_ISA_HH__
5835517Snate@binkert.org#define __CONFIG_THE_GPU_ISA_HH__
5848596Ssteve.reinhardt@amd.com
5855517Snate@binkert.org''')
5867673Snate@binkert.org
5877673Snate@binkert.org    # create defines for the preprocessing and compile-time determination
5887673Snate@binkert.org    for i,isa in enumerate(isas):
5895517Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
5905517Snate@binkert.org    code()
5915517Snate@binkert.org
5925517Snate@binkert.org    # create an enum for any run-time determination of the ISA, we
5935517Snate@binkert.org    # reuse the same name as the namespaces
5945517Snate@binkert.org    code('enum class GPUArch {')
5955517Snate@binkert.org    for i,isa in enumerate(isas):
5967673Snate@binkert.org        if i + 1 == len(isas):
5977673Snate@binkert.org            code('  $0 = $1', namespace(isa), define(isa))
5987673Snate@binkert.org        else:
5995517Snate@binkert.org            code('  $0 = $1,', namespace(isa), define(isa))
6008596Ssteve.reinhardt@amd.com    code('};')
6015517Snate@binkert.org
6025517Snate@binkert.org    code('''
6035517Snate@binkert.org
6045517Snate@binkert.org#define THE_GPU_ISA ${{define(target_gpu_isa)}}
6055517Snate@binkert.org#define TheGpuISA ${{namespace(target_gpu_isa)}}
6067673Snate@binkert.org#define THE_GPU_ISA_STR "${{target_gpu_isa}}"
6077673Snate@binkert.org
6087673Snate@binkert.org#endif // __CONFIG_THE_GPU_ISA_HH__''')
6095517Snate@binkert.org
6108596Ssteve.reinhardt@amd.com    code.write(str(target[0]))
6117675Snate@binkert.org
6127675Snate@binkert.orgenv.Command('config/the_gpu_isa.hh', map(Value, all_gpu_isa_list),
6137675Snate@binkert.org            MakeAction(makeTheGPUISA, Transform("CFG ISA", 0)))
6147675Snate@binkert.org
6157675Snate@binkert.org########################################################################
6167675Snate@binkert.org#
6178596Ssteve.reinhardt@amd.com# Prevent any SimObjects from being added after this point, they
6187675Snate@binkert.org# should all have been added in the SConscripts above
6197675Snate@binkert.org#
6208596Ssteve.reinhardt@amd.comSimObject.fixed = True
6218596Ssteve.reinhardt@amd.com
6228596Ssteve.reinhardt@amd.comclass DictImporter(object):
6238596Ssteve.reinhardt@amd.com    '''This importer takes a dictionary of arbitrary module names that
6248596Ssteve.reinhardt@amd.com    map to arbitrary filenames.'''
6258596Ssteve.reinhardt@amd.com    def __init__(self, modules):
6268596Ssteve.reinhardt@amd.com        self.modules = modules
6278596Ssteve.reinhardt@amd.com        self.installed = set()
6288596Ssteve.reinhardt@amd.com
6294762Snate@binkert.org    def __del__(self):
6306143Snate@binkert.org        self.unload()
6316143Snate@binkert.org
6326143Snate@binkert.org    def unload(self):
6334762Snate@binkert.org        import sys
6344762Snate@binkert.org        for module in self.installed:
6354762Snate@binkert.org            del sys.modules[module]
6367756SAli.Saidi@ARM.com        self.installed = set()
6378596Ssteve.reinhardt@amd.com
6384762Snate@binkert.org    def find_module(self, fullname, path):
6394762Snate@binkert.org        if fullname == 'm5.defines':
6408596Ssteve.reinhardt@amd.com            return self
6415463Snate@binkert.org
6428596Ssteve.reinhardt@amd.com        if fullname == 'm5.objects':
6438596Ssteve.reinhardt@amd.com            return self
6445463Snate@binkert.org
6457756SAli.Saidi@ARM.com        if fullname.startswith('_m5'):
6468596Ssteve.reinhardt@amd.com            return None
6474762Snate@binkert.org
6487677Snate@binkert.org        source = self.modules.get(fullname, None)
6494762Snate@binkert.org        if source is not None and fullname.startswith('m5.objects'):
6504762Snate@binkert.org            return self
6516143Snate@binkert.org
6526143Snate@binkert.org        return None
6536143Snate@binkert.org
6544762Snate@binkert.org    def load_module(self, fullname):
6554762Snate@binkert.org        mod = imp.new_module(fullname)
6567756SAli.Saidi@ARM.com        sys.modules[fullname] = mod
6577816Ssteve.reinhardt@amd.com        self.installed.add(fullname)
6584762Snate@binkert.org
6594762Snate@binkert.org        mod.__loader__ = self
6604762Snate@binkert.org        if fullname == 'm5.objects':
6614762Snate@binkert.org            mod.__path__ = fullname.split('.')
6627756SAli.Saidi@ARM.com            return mod
6638596Ssteve.reinhardt@amd.com
6644762Snate@binkert.org        if fullname == 'm5.defines':
6654762Snate@binkert.org            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
6667677Snate@binkert.org            return mod
6677756SAli.Saidi@ARM.com
6688596Ssteve.reinhardt@amd.com        source = self.modules[fullname]
6697675Snate@binkert.org        if source.modname == '__init__':
6707677Snate@binkert.org            mod.__path__ = source.modpath
6715517Snate@binkert.org        mod.__file__ = source.abspath
6728596Ssteve.reinhardt@amd.com
6739248SAndreas.Sandberg@arm.com        exec file(source.abspath, 'r') in mod.__dict__
6749248SAndreas.Sandberg@arm.com
6759248SAndreas.Sandberg@arm.com        return mod
6769248SAndreas.Sandberg@arm.com
6778596Ssteve.reinhardt@amd.comimport m5.SimObject
6788596Ssteve.reinhardt@amd.comimport m5.params
6798596Ssteve.reinhardt@amd.comfrom m5.util import code_formatter
6809248SAndreas.Sandberg@arm.com
6818596Ssteve.reinhardt@amd.comm5.SimObject.clear()
6824762Snate@binkert.orgm5.params.clear()
6837674Snate@binkert.org
6847674Snate@binkert.org# install the python importer so we can grab stuff from the source
6857674Snate@binkert.org# tree itself.  We can't have SimObjects added after this point or
6867674Snate@binkert.org# else we won't know about them for the rest of the stuff.
6877674Snate@binkert.orgimporter = DictImporter(PySource.modules)
6887674Snate@binkert.orgsys.meta_path[0:0] = [ importer ]
6897674Snate@binkert.org
6907674Snate@binkert.org# import all sim objects so we can populate the all_objects list
6917674Snate@binkert.org# make sure that we're working with a list, then let's sort it
6927674Snate@binkert.orgfor modname in SimObject.modnames:
6937674Snate@binkert.org    exec('from m5.objects import %s' % modname)
6947674Snate@binkert.org
6957674Snate@binkert.org# we need to unload all of the currently imported modules so that they
6967674Snate@binkert.org# will be re-imported the next time the sconscript is run
6977674Snate@binkert.orgimporter.unload()
6984762Snate@binkert.orgsys.meta_path.remove(importer)
6996143Snate@binkert.org
7006143Snate@binkert.orgsim_objects = m5.SimObject.allClasses
7017756SAli.Saidi@ARM.comall_enums = m5.params.allEnums
7027816Ssteve.reinhardt@amd.com
7038235Snate@binkert.orgfor name,obj in sorted(sim_objects.iteritems()):
7048596Ssteve.reinhardt@amd.com    for param in obj._params.local.values():
7057756SAli.Saidi@ARM.com        # load the ptype attribute now because it depends on the
7067816Ssteve.reinhardt@amd.com        # current version of SimObject.allClasses, but when scons
7078235Snate@binkert.org        # actually uses the value, all versions of
7084382Sbinkertn@umich.edu        # SimObject.allClasses will have been loaded
7099396Sandreas.hansson@arm.com        param.ptype
7109396Sandreas.hansson@arm.com
7119396Sandreas.hansson@arm.com########################################################################
7129396Sandreas.hansson@arm.com#
7139396Sandreas.hansson@arm.com# calculate extra dependencies
7149396Sandreas.hansson@arm.com#
7159396Sandreas.hansson@arm.commodule_depends = ["m5", "m5.SimObject", "m5.params"]
7169396Sandreas.hansson@arm.comdepends = [ PySource.modules[dep].snode for dep in module_depends ]
7179396Sandreas.hansson@arm.comdepends.sort(key = lambda x: x.name)
7189396Sandreas.hansson@arm.com
7199396Sandreas.hansson@arm.com########################################################################
7209396Sandreas.hansson@arm.com#
7219396Sandreas.hansson@arm.com# Commands for the basic automatically generated python files
7229396Sandreas.hansson@arm.com#
7239396Sandreas.hansson@arm.com
7249396Sandreas.hansson@arm.com# Generate Python file containing a dict specifying the current
7259396Sandreas.hansson@arm.com# buildEnv flags.
7269396Sandreas.hansson@arm.comdef makeDefinesPyFile(target, source, env):
7278232Snate@binkert.org    build_env = source[0].get_contents()
7288232Snate@binkert.org
7298232Snate@binkert.org    code = code_formatter()
7308232Snate@binkert.org    code("""
7318232Snate@binkert.orgimport _m5.core
7326229Snate@binkert.orgimport m5.util
7338232Snate@binkert.org
7348232Snate@binkert.orgbuildEnv = m5.util.SmartDict($build_env)
7358232Snate@binkert.org
7366229Snate@binkert.orgcompileDate = _m5.core.compileDate
7377673Snate@binkert.org_globals = globals()
7385517Snate@binkert.orgfor key,val in _m5.core.__dict__.iteritems():
7395517Snate@binkert.org    if key.startswith('flag_'):
7407673Snate@binkert.org        flag = key[5:]
7415517Snate@binkert.org        _globals[flag] = val
7425517Snate@binkert.orgdel _globals
7435517Snate@binkert.org""")
7445517Snate@binkert.org    code.write(target[0].abspath)
7458232Snate@binkert.org
7467673Snate@binkert.orgdefines_info = Value(build_env)
7477673Snate@binkert.org# Generate a file with all of the compile options in it
7488232Snate@binkert.orgenv.Command('python/m5/defines.py', defines_info,
7498232Snate@binkert.org            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
7508232Snate@binkert.orgPySource('m5', 'python/m5/defines.py')
7518232Snate@binkert.org
7527673Snate@binkert.org# Generate python file containing info about the M5 source code
7535517Snate@binkert.orgdef makeInfoPyFile(target, source, env):
7548232Snate@binkert.org    code = code_formatter()
7558232Snate@binkert.org    for src in source:
7568232Snate@binkert.org        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
7578232Snate@binkert.org        code('$src = ${{repr(data)}}')
7587673Snate@binkert.org    code.write(str(target[0]))
7598232Snate@binkert.org
7608232Snate@binkert.org# Generate a file that wraps the basic top level files
7618232Snate@binkert.orgenv.Command('python/m5/info.py',
7628232Snate@binkert.org            [ '#/COPYING', '#/LICENSE', '#/README', ],
7638232Snate@binkert.org            MakeAction(makeInfoPyFile, Transform("INFO")))
7648232Snate@binkert.orgPySource('m5', 'python/m5/info.py')
7657673Snate@binkert.org
7665517Snate@binkert.org########################################################################
7678232Snate@binkert.org#
7688232Snate@binkert.org# Create all of the SimObject param headers and enum headers
7695517Snate@binkert.org#
7707673Snate@binkert.org
7715517Snate@binkert.orgdef createSimObjectParamStruct(target, source, env):
7728232Snate@binkert.org    assert len(target) == 1 and len(source) == 1
7738232Snate@binkert.org
7745517Snate@binkert.org    name = source[0].get_text_contents()
7758232Snate@binkert.org    obj = sim_objects[name]
7768232Snate@binkert.org
7778232Snate@binkert.org    code = code_formatter()
7787673Snate@binkert.org    obj.cxx_param_decl(code)
7795517Snate@binkert.org    code.write(target[0].abspath)
7805517Snate@binkert.org
7817673Snate@binkert.orgdef createSimObjectCxxConfig(is_header):
7825517Snate@binkert.org    def body(target, source, env):
7835517Snate@binkert.org        assert len(target) == 1 and len(source) == 1
7845517Snate@binkert.org
7858232Snate@binkert.org        name = str(source[0].get_contents())
7865517Snate@binkert.org        obj = sim_objects[name]
7875517Snate@binkert.org
7888232Snate@binkert.org        code = code_formatter()
7898232Snate@binkert.org        obj.cxx_config_param_file(code, is_header)
7905517Snate@binkert.org        code.write(target[0].abspath)
7918232Snate@binkert.org    return body
7928232Snate@binkert.org
7935517Snate@binkert.orgdef createEnumStrings(target, source, env):
7948232Snate@binkert.org    assert len(target) == 1 and len(source) == 2
7958232Snate@binkert.org
7968232Snate@binkert.org    name = source[0].get_text_contents()
7975517Snate@binkert.org    use_python = source[1].read()
7988232Snate@binkert.org    obj = all_enums[name]
7998232Snate@binkert.org
8008232Snate@binkert.org    code = code_formatter()
8018232Snate@binkert.org    obj.cxx_def(code)
8028232Snate@binkert.org    if use_python:
8038232Snate@binkert.org        obj.pybind_def(code)
8045517Snate@binkert.org    code.write(target[0].abspath)
8058232Snate@binkert.org
8068232Snate@binkert.orgdef createEnumDecls(target, source, env):
8075517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
8088232Snate@binkert.org
8097673Snate@binkert.org    name = source[0].get_text_contents()
8105517Snate@binkert.org    obj = all_enums[name]
8117673Snate@binkert.org
8125517Snate@binkert.org    code = code_formatter()
8138232Snate@binkert.org    obj.cxx_decl(code)
8148232Snate@binkert.org    code.write(target[0].abspath)
8158232Snate@binkert.org
8165192Ssaidi@eecs.umich.edudef createSimObjectPyBindWrapper(target, source, env):
8178232Snate@binkert.org    name = source[0].get_text_contents()
8188232Snate@binkert.org    obj = sim_objects[name]
8198232Snate@binkert.org
8208232Snate@binkert.org    code = code_formatter()
8218232Snate@binkert.org    obj.pybind_decl(code)
8225192Ssaidi@eecs.umich.edu    code.write(target[0].abspath)
8237674Snate@binkert.org
8245522Snate@binkert.org# Generate all of the SimObject param C++ struct header files
8255522Snate@binkert.orgparams_hh_files = []
8267674Snate@binkert.orgfor name,simobj in sorted(sim_objects.iteritems()):
8277674Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
8287674Snate@binkert.org    extra_deps = [ py_source.tnode ]
8297674Snate@binkert.org
8307674Snate@binkert.org    hh_file = File('params/%s.hh' % name)
8317674Snate@binkert.org    params_hh_files.append(hh_file)
8327674Snate@binkert.org    env.Command(hh_file, Value(name),
8337674Snate@binkert.org                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
8345522Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
8355522Snate@binkert.org
8365522Snate@binkert.org# C++ parameter description files
8375517Snate@binkert.orgif GetOption('with_cxx_config'):
8385522Snate@binkert.org    for name,simobj in sorted(sim_objects.iteritems()):
8395517Snate@binkert.org        py_source = PySource.modules[simobj.__module__]
8406143Snate@binkert.org        extra_deps = [ py_source.tnode ]
8416727Ssteve.reinhardt@amd.com
8425522Snate@binkert.org        cxx_config_hh_file = File('cxx_config/%s.hh' % name)
8435522Snate@binkert.org        cxx_config_cc_file = File('cxx_config/%s.cc' % name)
8445522Snate@binkert.org        env.Command(cxx_config_hh_file, Value(name),
8457674Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(True),
8465517Snate@binkert.org                    Transform("CXXCPRHH")))
8477673Snate@binkert.org        env.Command(cxx_config_cc_file, Value(name),
8487673Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(False),
8497674Snate@binkert.org                    Transform("CXXCPRCC")))
8507673Snate@binkert.org        env.Depends(cxx_config_hh_file, depends + extra_deps +
8517674Snate@binkert.org                    [File('params/%s.hh' % name), File('sim/cxx_config.hh')])
8527674Snate@binkert.org        env.Depends(cxx_config_cc_file, depends + extra_deps +
8538946Sandreas.hansson@arm.com                    [cxx_config_hh_file])
8547674Snate@binkert.org        Source(cxx_config_cc_file)
8557674Snate@binkert.org
8567674Snate@binkert.org    cxx_config_init_cc_file = File('cxx_config/init.cc')
8575522Snate@binkert.org
8585522Snate@binkert.org    def createCxxConfigInitCC(target, source, env):
8597674Snate@binkert.org        assert len(target) == 1 and len(source) == 1
8607674Snate@binkert.org
8617674Snate@binkert.org        code = code_formatter()
8627674Snate@binkert.org
8637673Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems()):
8647674Snate@binkert.org            if not hasattr(simobj, 'abstract') or not simobj.abstract:
8657674Snate@binkert.org                code('#include "cxx_config/${name}.hh"')
8667674Snate@binkert.org        code()
8677674Snate@binkert.org        code('void cxxConfigInit()')
8687674Snate@binkert.org        code('{')
8697674Snate@binkert.org        code.indent()
8707674Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems()):
8717674Snate@binkert.org            not_abstract = not hasattr(simobj, 'abstract') or \
8727811Ssteve.reinhardt@amd.com                not simobj.abstract
8737674Snate@binkert.org            if not_abstract and 'type' in simobj.__dict__:
8747673Snate@binkert.org                code('cxx_config_directory["${name}"] = '
8755522Snate@binkert.org                     '${name}CxxConfigParams::makeDirectoryEntry();')
8766143Snate@binkert.org        code.dedent()
8777756SAli.Saidi@ARM.com        code('}')
8787816Ssteve.reinhardt@amd.com        code.write(target[0].abspath)
8797674Snate@binkert.org
8804382Sbinkertn@umich.edu    py_source = PySource.modules[simobj.__module__]
8814382Sbinkertn@umich.edu    extra_deps = [ py_source.tnode ]
8824382Sbinkertn@umich.edu    env.Command(cxx_config_init_cc_file, Value(name),
8834382Sbinkertn@umich.edu        MakeAction(createCxxConfigInitCC, Transform("CXXCINIT")))
8844382Sbinkertn@umich.edu    cxx_param_hh_files = ["cxx_config/%s.hh" % simobj
8854382Sbinkertn@umich.edu        for name,simobj in sorted(sim_objects.iteritems())
8864382Sbinkertn@umich.edu        if not hasattr(simobj, 'abstract') or not simobj.abstract]
8874382Sbinkertn@umich.edu    Depends(cxx_config_init_cc_file, cxx_param_hh_files +
88810196SCurtis.Dunham@arm.com            [File('sim/cxx_config.hh')])
8894382Sbinkertn@umich.edu    Source(cxx_config_init_cc_file)
89010196SCurtis.Dunham@arm.com
89110196SCurtis.Dunham@arm.com# Generate all enum header files
89210196SCurtis.Dunham@arm.comfor name,enum in sorted(all_enums.iteritems()):
89310196SCurtis.Dunham@arm.com    py_source = PySource.modules[enum.__module__]
89410196SCurtis.Dunham@arm.com    extra_deps = [ py_source.tnode ]
89510196SCurtis.Dunham@arm.com
89610196SCurtis.Dunham@arm.com    cc_file = File('enums/%s.cc' % name)
897955SN/A    env.Command(cc_file, [Value(name), Value(env['USE_PYTHON'])],
8982655Sstever@eecs.umich.edu                MakeAction(createEnumStrings, Transform("ENUM STR")))
8992655Sstever@eecs.umich.edu    env.Depends(cc_file, depends + extra_deps)
9002655Sstever@eecs.umich.edu    Source(cc_file)
9012655Sstever@eecs.umich.edu
90210196SCurtis.Dunham@arm.com    hh_file = File('enums/%s.hh' % name)
9035601Snate@binkert.org    env.Command(hh_file, Value(name),
9045601Snate@binkert.org                MakeAction(createEnumDecls, Transform("ENUMDECL")))
90510196SCurtis.Dunham@arm.com    env.Depends(hh_file, depends + extra_deps)
90610196SCurtis.Dunham@arm.com
90710196SCurtis.Dunham@arm.com# Generate SimObject Python bindings wrapper files
9085522Snate@binkert.orgif env['USE_PYTHON']:
9095863Snate@binkert.org    for name,simobj in sorted(sim_objects.iteritems()):
9105601Snate@binkert.org        py_source = PySource.modules[simobj.__module__]
9115601Snate@binkert.org        extra_deps = [ py_source.tnode ]
9125601Snate@binkert.org        cc_file = File('python/_m5/param_%s.cc' % name)
9135863Snate@binkert.org        env.Command(cc_file, Value(name),
9149556Sandreas.hansson@arm.com                    MakeAction(createSimObjectPyBindWrapper,
9159556Sandreas.hansson@arm.com                               Transform("SO PyBind")))
9169556Sandreas.hansson@arm.com        env.Depends(cc_file, depends + extra_deps)
9179556Sandreas.hansson@arm.com        Source(cc_file)
9189556Sandreas.hansson@arm.com
9199556Sandreas.hansson@arm.com# Build all protocol buffers if we have got protoc and protobuf available
9209556Sandreas.hansson@arm.comif env['HAVE_PROTOBUF']:
9219556Sandreas.hansson@arm.com    for proto in ProtoBuf.all:
9229556Sandreas.hansson@arm.com        # Use both the source and header as the target, and the .proto
9235559Snate@binkert.org        # file as the source. When executing the protoc compiler, also
9249556Sandreas.hansson@arm.com        # specify the proto_path to avoid having the generated files
9259618Ssteve.reinhardt@amd.com        # include the path.
9269618Ssteve.reinhardt@amd.com        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
9279618Ssteve.reinhardt@amd.com                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
92810238Sandreas.hansson@arm.com                               '--proto_path ${SOURCE.dir} $SOURCE',
92910238Sandreas.hansson@arm.com                               Transform("PROTOC")))
9309554Sandreas.hansson@arm.com
9319556Sandreas.hansson@arm.com        # Add the C++ source file
9329556Sandreas.hansson@arm.com        Source(proto.cc_file, tags=proto.tags)
9339556Sandreas.hansson@arm.comelif ProtoBuf.all:
9349556Sandreas.hansson@arm.com    print('Got protobuf to build, but lacks support!')
9359555Sandreas.hansson@arm.com    Exit(1)
9369555Sandreas.hansson@arm.com
9379556Sandreas.hansson@arm.com#
9388737Skoansin.tan@gmail.com# Handle debug flags
9399556Sandreas.hansson@arm.com#
9409556Sandreas.hansson@arm.comdef makeDebugFlagCC(target, source, env):
9419556Sandreas.hansson@arm.com    assert(len(target) == 1 and len(source) == 1)
9429554Sandreas.hansson@arm.com
9438945Ssteve.reinhardt@amd.com    code = code_formatter()
9448945Ssteve.reinhardt@amd.com
9458945Ssteve.reinhardt@amd.com    # delay definition of CompoundFlags until after all the definition
9466143Snate@binkert.org    # of all constituent SimpleFlags
9476143Snate@binkert.org    comp_code = code_formatter()
9486143Snate@binkert.org
9496143Snate@binkert.org    # file header
9506143Snate@binkert.org    code('''
9516143Snate@binkert.org/*
9526143Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated by SCons.
9538945Ssteve.reinhardt@amd.com */
9548945Ssteve.reinhardt@amd.com
9556143Snate@binkert.org#include "base/debug.hh"
9566143Snate@binkert.org
9576143Snate@binkert.orgnamespace Debug {
9586143Snate@binkert.org
9596143Snate@binkert.org''')
9606143Snate@binkert.org
9616143Snate@binkert.org    for name, flag in sorted(source[0].read().iteritems()):
9626143Snate@binkert.org        n, compound, desc = flag
9636143Snate@binkert.org        assert n == name
9646143Snate@binkert.org
9656143Snate@binkert.org        if not compound:
9666143Snate@binkert.org            code('SimpleFlag $name("$name", "$desc");')
9676143Snate@binkert.org        else:
9688594Snate@binkert.org            comp_code('CompoundFlag $name("$name", "$desc",')
9698594Snate@binkert.org            comp_code.indent()
9708594Snate@binkert.org            last = len(compound) - 1
9718594Snate@binkert.org            for i,flag in enumerate(compound):
9726143Snate@binkert.org                if i != last:
9736143Snate@binkert.org                    comp_code('&$flag,')
9746143Snate@binkert.org                else:
9756143Snate@binkert.org                    comp_code('&$flag);')
9766143Snate@binkert.org            comp_code.dedent()
9776240Snate@binkert.org
9785554Snate@binkert.org    code.append(comp_code)
9795522Snate@binkert.org    code()
9805522Snate@binkert.org    code('} // namespace Debug')
9815797Snate@binkert.org
9825797Snate@binkert.org    code.write(str(target[0]))
9835522Snate@binkert.org
9845601Snate@binkert.orgdef makeDebugFlagHH(target, source, env):
9858233Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
9868233Snate@binkert.org
9878235Snate@binkert.org    val = eval(source[0].get_contents())
9888235Snate@binkert.org    name, compound, desc = val
9898235Snate@binkert.org
9908235Snate@binkert.org    code = code_formatter()
9919003SAli.Saidi@ARM.com
9929003SAli.Saidi@ARM.com    # file header boilerplate
99310196SCurtis.Dunham@arm.com    code('''\
99410196SCurtis.Dunham@arm.com/*
9958235Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated by SCons.
9966143Snate@binkert.org */
9972655Sstever@eecs.umich.edu
9986143Snate@binkert.org#ifndef __DEBUG_${name}_HH__
9996143Snate@binkert.org#define __DEBUG_${name}_HH__
10008233Snate@binkert.org
10016143Snate@binkert.orgnamespace Debug {
10026143Snate@binkert.org''')
10034007Ssaidi@eecs.umich.edu
10044596Sbinkertn@umich.edu    if compound:
10054007Ssaidi@eecs.umich.edu        code('class CompoundFlag;')
10064596Sbinkertn@umich.edu    code('class SimpleFlag;')
10077756SAli.Saidi@ARM.com
10087816Ssteve.reinhardt@amd.com    if compound:
10098334Snate@binkert.org        code('extern CompoundFlag $name;')
10108334Snate@binkert.org        for flag in compound:
10118334Snate@binkert.org            code('extern SimpleFlag $flag;')
10128334Snate@binkert.org    else:
10135601Snate@binkert.org        code('extern SimpleFlag $name;')
101410196SCurtis.Dunham@arm.com
10152655Sstever@eecs.umich.edu    code('''
10169225Sandreas.hansson@arm.com}
10179225Sandreas.hansson@arm.com
10189226Sandreas.hansson@arm.com#endif // __DEBUG_${name}_HH__
10199226Sandreas.hansson@arm.com''')
10209225Sandreas.hansson@arm.com
10219226Sandreas.hansson@arm.com    code.write(str(target[0]))
10229226Sandreas.hansson@arm.com
10239226Sandreas.hansson@arm.comfor name,flag in sorted(debug_flags.iteritems()):
10249226Sandreas.hansson@arm.com    n, compound, desc = flag
10259226Sandreas.hansson@arm.com    assert n == name
10269226Sandreas.hansson@arm.com
10279225Sandreas.hansson@arm.com    hh_file = 'debug/%s.hh' % name
10289227Sandreas.hansson@arm.com    env.Command(hh_file, Value(flag),
10299227Sandreas.hansson@arm.com                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
10309227Sandreas.hansson@arm.com
10319227Sandreas.hansson@arm.comenv.Command('debug/flags.cc', Value(debug_flags),
10328946Sandreas.hansson@arm.com            MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
10333918Ssaidi@eecs.umich.eduSource('debug/flags.cc')
10349225Sandreas.hansson@arm.com
10353918Ssaidi@eecs.umich.edu# version tags
10369225Sandreas.hansson@arm.comtags = \
10379225Sandreas.hansson@arm.comenv.Command('sim/tags.cc', None,
10389227Sandreas.hansson@arm.com            MakeAction('util/cpt_upgrader.py --get-cc-file > $TARGET',
10399227Sandreas.hansson@arm.com                       Transform("VER TAGS")))
10409227Sandreas.hansson@arm.comenv.AlwaysBuild(tags)
10419226Sandreas.hansson@arm.com
10429225Sandreas.hansson@arm.com# Embed python files.  All .py files that have been indicated by a
10439227Sandreas.hansson@arm.com# PySource() call in a SConscript need to be embedded into the M5
10449227Sandreas.hansson@arm.com# library.  To do that, we compile the file to byte code, marshal the
10459227Sandreas.hansson@arm.com# byte code, compress it, and then generate a c++ file that
10469227Sandreas.hansson@arm.com# inserts the result into an array.
10478946Sandreas.hansson@arm.comdef embedPyFile(target, source, env):
10489225Sandreas.hansson@arm.com    def c_str(string):
10499226Sandreas.hansson@arm.com        if string is None:
10509226Sandreas.hansson@arm.com            return "0"
10519226Sandreas.hansson@arm.com        return '"%s"' % string
10523515Ssaidi@eecs.umich.edu
10533918Ssaidi@eecs.umich.edu    '''Action function to compile a .py into a code object, marshal
10544762Snate@binkert.org    it, compress it, and stick it into an asm file so the code appears
10553515Ssaidi@eecs.umich.edu    as just bytes with a label in the data section'''
10568881Smarc.orr@gmail.com
10578881Smarc.orr@gmail.com    src = file(str(source[0]), 'r').read()
10588881Smarc.orr@gmail.com
10598881Smarc.orr@gmail.com    pysource = PySource.tnodes[source[0]]
10608881Smarc.orr@gmail.com    compiled = compile(src, pysource.abspath, 'exec')
10619226Sandreas.hansson@arm.com    marshalled = marshal.dumps(compiled)
10629226Sandreas.hansson@arm.com    compressed = zlib.compress(marshalled)
10639226Sandreas.hansson@arm.com    data = compressed
10648881Smarc.orr@gmail.com    sym = pysource.symname
10658881Smarc.orr@gmail.com
10668881Smarc.orr@gmail.com    code = code_formatter()
10678881Smarc.orr@gmail.com    code('''\
10688881Smarc.orr@gmail.com#include "sim/init.hh"
10698881Smarc.orr@gmail.com
10708881Smarc.orr@gmail.comnamespace {
10718881Smarc.orr@gmail.com
10728881Smarc.orr@gmail.comconst uint8_t data_${sym}[] = {
10738881Smarc.orr@gmail.com''')
10748881Smarc.orr@gmail.com    code.indent()
10758881Smarc.orr@gmail.com    step = 16
10768881Smarc.orr@gmail.com    for i in xrange(0, len(data), step):
10778881Smarc.orr@gmail.com        x = array.array('B', data[i:i+step])
10788881Smarc.orr@gmail.com        code(''.join('%d,' % d for d in x))
10798881Smarc.orr@gmail.com    code.dedent()
108010196SCurtis.Dunham@arm.com
108110196SCurtis.Dunham@arm.com    code('''};
108210196SCurtis.Dunham@arm.com
108310196SCurtis.Dunham@arm.comEmbeddedPython embedded_${sym}(
1084955SN/A    ${{c_str(pysource.arcname)}},
108510196SCurtis.Dunham@arm.com    ${{c_str(pysource.abspath)}},
1086955SN/A    ${{c_str(pysource.modpath)}},
108710196SCurtis.Dunham@arm.com    data_${sym},
108810196SCurtis.Dunham@arm.com    ${{len(data)}},
108910196SCurtis.Dunham@arm.com    ${{len(marshalled)}});
109010196SCurtis.Dunham@arm.com
109110196SCurtis.Dunham@arm.com} // anonymous namespace
109210196SCurtis.Dunham@arm.com''')
109310196SCurtis.Dunham@arm.com    code.write(str(target[0]))
1094955SN/A
109510196SCurtis.Dunham@arm.comfor source in PySource.all:
109610196SCurtis.Dunham@arm.com    env.Command(source.cpp, source.tnode,
109710196SCurtis.Dunham@arm.com                MakeAction(embedPyFile, Transform("EMBED PY")))
109810196SCurtis.Dunham@arm.com    Source(source.cpp, tags=source.tags, add_tags='python')
109910196SCurtis.Dunham@arm.com
110010196SCurtis.Dunham@arm.com########################################################################
110110196SCurtis.Dunham@arm.com#
11021869SN/A# Define binaries.  Each different build type (debug, opt, etc.) gets
110310196SCurtis.Dunham@arm.com# a slightly different build environment.
110410196SCurtis.Dunham@arm.com#
110510196SCurtis.Dunham@arm.com
110610196SCurtis.Dunham@arm.com# List of constructed environments to pass back to SConstruct
110710196SCurtis.Dunham@arm.comdate_source = Source('base/date.cc', tags=[])
110810196SCurtis.Dunham@arm.com
110910196SCurtis.Dunham@arm.comgem5_binary = Gem5('gem5')
11109226Sandreas.hansson@arm.com
111110196SCurtis.Dunham@arm.com# Function to create a new build environment as clone of current
111210196SCurtis.Dunham@arm.com# environment 'env' with modified object suffix and optional stripped
111310196SCurtis.Dunham@arm.com# binary.  Additional keyword arguments are appended to corresponding
111410196SCurtis.Dunham@arm.com# build environment vars.
111510196SCurtis.Dunham@arm.comdef makeEnv(env, label, objsfx, strip=False, disable_partial=False, **kwargs):
111610196SCurtis.Dunham@arm.com    # SCons doesn't know to append a library suffix when there is a '.' in the
111710196SCurtis.Dunham@arm.com    # name.  Use '_' instead.
111810196SCurtis.Dunham@arm.com    libname = 'gem5_' + label
111910196SCurtis.Dunham@arm.com    secondary_exename = 'm5.' + label
112010196SCurtis.Dunham@arm.com
112110196SCurtis.Dunham@arm.com    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
112210196SCurtis.Dunham@arm.com    new_env.Label = label
112310196SCurtis.Dunham@arm.com    new_env.Append(**kwargs)
112410196SCurtis.Dunham@arm.com
112510196SCurtis.Dunham@arm.com    lib_sources = Source.all.with_tag('gem5 lib')
112610196SCurtis.Dunham@arm.com
112710196SCurtis.Dunham@arm.com    # Without Python, leave out all Python content from the library
112810196SCurtis.Dunham@arm.com    # builds.  The option doesn't affect gem5 built as a program
112910196SCurtis.Dunham@arm.com    if GetOption('without_python'):
113010196SCurtis.Dunham@arm.com        lib_sources = lib_sources.without_tag('python')
113110196SCurtis.Dunham@arm.com
113210196SCurtis.Dunham@arm.com    static_objs = []
113310196SCurtis.Dunham@arm.com    shared_objs = []
113410196SCurtis.Dunham@arm.com
113510196SCurtis.Dunham@arm.com    for s in lib_sources.with_tag(Source.ungrouped_tag):
113610196SCurtis.Dunham@arm.com        static_objs.append(s.static(new_env))
113710196SCurtis.Dunham@arm.com        shared_objs.append(s.shared(new_env))
113810196SCurtis.Dunham@arm.com
113910196SCurtis.Dunham@arm.com    for group in Source.source_groups:
114010196SCurtis.Dunham@arm.com        srcs = lib_sources.with_tag(Source.link_group_tag(group))
114110196SCurtis.Dunham@arm.com        if not srcs:
114210196SCurtis.Dunham@arm.com            continue
114310196SCurtis.Dunham@arm.com
114410196SCurtis.Dunham@arm.com        group_static = [ s.static(new_env) for s in srcs ]
114510196SCurtis.Dunham@arm.com        group_shared = [ s.shared(new_env) for s in srcs ]
114610196SCurtis.Dunham@arm.com
114710196SCurtis.Dunham@arm.com        # If partial linking is disabled, add these sources to the build
114810196SCurtis.Dunham@arm.com        # directly, and short circuit this loop.
114910196SCurtis.Dunham@arm.com        if disable_partial:
115010196SCurtis.Dunham@arm.com            static_objs.extend(group_static)
115110196SCurtis.Dunham@arm.com            shared_objs.extend(group_shared)
115210196SCurtis.Dunham@arm.com            continue
115310196SCurtis.Dunham@arm.com
1154        # Set up the static partially linked objects.
1155        file_name = new_env.subst("${OBJPREFIX}lib${OBJSUFFIX}.partial")
1156        target = File(joinpath(group, file_name))
1157        partial = env.PartialStatic(target=target, source=group_static)
1158        static_objs.extend(partial)
1159
1160        # Set up the shared partially linked objects.
1161        file_name = new_env.subst("${SHOBJPREFIX}lib${SHOBJSUFFIX}.partial")
1162        target = File(joinpath(group, file_name))
1163        partial = env.PartialShared(target=target, source=group_shared)
1164        shared_objs.extend(partial)
1165
1166    static_date = date_source.static(new_env)
1167    new_env.Depends(static_date, static_objs)
1168    static_objs.extend(static_date)
1169
1170    shared_date = date_source.shared(new_env)
1171    new_env.Depends(shared_date, shared_objs)
1172    shared_objs.extend(shared_date)
1173
1174    main_objs = [ s.static(new_env) for s in Source.all.with_tag('main') ]
1175
1176    # First make a library of everything but main() so other programs can
1177    # link against m5.
1178    static_lib = new_env.StaticLibrary(libname, static_objs)
1179    shared_lib = new_env.SharedLibrary(libname, shared_objs)
1180
1181    # Keep track of the object files generated so far so Executables can
1182    # include them.
1183    new_env['STATIC_OBJS'] = static_objs
1184    new_env['SHARED_OBJS'] = shared_objs
1185    new_env['MAIN_OBJS'] = main_objs
1186
1187    new_env['STATIC_LIB'] = static_lib
1188    new_env['SHARED_LIB'] = shared_lib
1189
1190    # Record some settings for building Executables.
1191    new_env['EXE_SUFFIX'] = label
1192    new_env['STRIP_EXES'] = strip
1193
1194    for cls in ExecutableMeta.all:
1195        cls.declare_all(new_env)
1196
1197    new_env.M5Binary = File(gem5_binary.path(new_env))
1198
1199    new_env.Command(secondary_exename, new_env.M5Binary,
1200            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
1201
1202    # Set up regression tests.
1203    SConscript(os.path.join(env.root.abspath, 'tests', 'SConscript'),
1204               variant_dir=Dir('tests').Dir(new_env.Label),
1205               exports={ 'env' : new_env }, duplicate=False)
1206
1207# Start out with the compiler flags common to all compilers,
1208# i.e. they all use -g for opt and -g -pg for prof
1209ccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
1210           'perf' : ['-g']}
1211
1212# Start out with the linker flags common to all linkers, i.e. -pg for
1213# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
1214# no-as-needed and as-needed as the binutils linker is too clever and
1215# simply doesn't link to the library otherwise.
1216ldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
1217           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
1218
1219# For Link Time Optimization, the optimisation flags used to compile
1220# individual files are decoupled from those used at link time
1221# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
1222# to also update the linker flags based on the target.
1223if env['GCC']:
1224    if sys.platform == 'sunos5':
1225        ccflags['debug'] += ['-gstabs+']
1226    else:
1227        ccflags['debug'] += ['-ggdb3']
1228    ldflags['debug'] += ['-O0']
1229    # opt, fast, prof and perf all share the same cc flags, also add
1230    # the optimization to the ldflags as LTO defers the optimization
1231    # to link time
1232    for target in ['opt', 'fast', 'prof', 'perf']:
1233        ccflags[target] += ['-O3']
1234        ldflags[target] += ['-O3']
1235
1236    ccflags['fast'] += env['LTO_CCFLAGS']
1237    ldflags['fast'] += env['LTO_LDFLAGS']
1238elif env['CLANG']:
1239    ccflags['debug'] += ['-g', '-O0']
1240    # opt, fast, prof and perf all share the same cc flags
1241    for target in ['opt', 'fast', 'prof', 'perf']:
1242        ccflags[target] += ['-O3']
1243else:
1244    print('Unknown compiler, please fix compiler options')
1245    Exit(1)
1246
1247
1248# To speed things up, we only instantiate the build environments we
1249# need.  We try to identify the needed environment for each target; if
1250# we can't, we fall back on instantiating all the environments just to
1251# be safe.
1252target_types = ['debug', 'opt', 'fast', 'prof', 'perf']
1253obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
1254              'gpo' : 'perf'}
1255
1256def identifyTarget(t):
1257    ext = t.split('.')[-1]
1258    if ext in target_types:
1259        return ext
1260    if obj2target.has_key(ext):
1261        return obj2target[ext]
1262    match = re.search(r'/tests/([^/]+)/', t)
1263    if match and match.group(1) in target_types:
1264        return match.group(1)
1265    return 'all'
1266
1267needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
1268if 'all' in needed_envs:
1269    needed_envs += target_types
1270
1271# Debug binary
1272if 'debug' in needed_envs:
1273    makeEnv(env, 'debug', '.do',
1274            CCFLAGS = Split(ccflags['debug']),
1275            CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
1276            LINKFLAGS = Split(ldflags['debug']))
1277
1278# Optimized binary
1279if 'opt' in needed_envs:
1280    makeEnv(env, 'opt', '.o',
1281            CCFLAGS = Split(ccflags['opt']),
1282            CPPDEFINES = ['TRACING_ON=1'],
1283            LINKFLAGS = Split(ldflags['opt']))
1284
1285# "Fast" binary
1286if 'fast' in needed_envs:
1287    disable_partial = \
1288            env.get('BROKEN_INCREMENTAL_LTO', False) and \
1289            GetOption('force_lto')
1290    makeEnv(env, 'fast', '.fo', strip = True,
1291            CCFLAGS = Split(ccflags['fast']),
1292            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1293            LINKFLAGS = Split(ldflags['fast']),
1294            disable_partial=disable_partial)
1295
1296# Profiled binary using gprof
1297if 'prof' in needed_envs:
1298    makeEnv(env, 'prof', '.po',
1299            CCFLAGS = Split(ccflags['prof']),
1300            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1301            LINKFLAGS = Split(ldflags['prof']))
1302
1303# Profiled binary using google-pprof
1304if 'perf' in needed_envs:
1305    makeEnv(env, 'perf', '.gpo',
1306            CCFLAGS = Split(ccflags['perf']),
1307            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1308            LINKFLAGS = Split(ldflags['perf']))
1309