SConscript revision 12366
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
4955SN/A# All rights reserved.
5955SN/A#
6955SN/A# Redistribution and use in source and binary forms, with or without
7955SN/A# modification, are permitted provided that the following conditions are
8955SN/A# met: redistributions of source code must retain the above copyright
9955SN/A# notice, this list of conditions and the following disclaimer;
10955SN/A# redistributions in binary form must reproduce the above copyright
11955SN/A# notice, this list of conditions and the following disclaimer in the
12955SN/A# documentation and/or other materials provided with the distribution;
13955SN/A# neither the name of the copyright holders nor the names of its
14955SN/A# contributors may be used to endorse or promote products derived from
15955SN/A# this software without specific prior written permission.
16955SN/A#
17955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
282665Ssaidi@eecs.umich.edu#
294762Snate@binkert.org# Authors: Nathan Binkert
30955SN/A
315522Snate@binkert.orgimport array
326143Snate@binkert.orgimport bisect
334762Snate@binkert.orgimport imp
345522Snate@binkert.orgimport marshal
35955SN/Aimport os
365522Snate@binkert.orgimport re
37955SN/Aimport subprocess
385522Snate@binkert.orgimport sys
394202Sbinkertn@umich.eduimport zlib
405742Snate@binkert.org
41955SN/Afrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
424381Sbinkertn@umich.edu
434381Sbinkertn@umich.eduimport SCons
44955SN/A
45955SN/Afrom gem5_scons import Transform
46955SN/A
474202Sbinkertn@umich.edu# This file defines how to build a particular configuration of gem5
48955SN/A# based on variable settings in the 'env' build environment.
494382Sbinkertn@umich.edu
504382Sbinkertn@umich.eduImport('*')
514382Sbinkertn@umich.edu
526654Snate@binkert.org# Children need to see the environment
535517Snate@binkert.orgExport('env')
546143Snate@binkert.org
556143Snate@binkert.orgbuild_env = [(opt, env[opt]) for opt in export_vars]
566143Snate@binkert.org
576143Snate@binkert.orgfrom m5.util import code_formatter, compareVersions
586143Snate@binkert.org
596143Snate@binkert.org########################################################################
606143Snate@binkert.org# Code for adding source files of various types
616143Snate@binkert.org#
626143Snate@binkert.org# When specifying a source file of some type, a set of tags can be
636143Snate@binkert.org# specified for that file.
646143Snate@binkert.org
656143Snate@binkert.orgclass SourceList(list):
666143Snate@binkert.org    def with_tags_that(self, predicate):
676143Snate@binkert.org        '''Return a list of sources with tags that satisfy a predicate.'''
686143Snate@binkert.org        def match(source):
694762Snate@binkert.org            return predicate(source.tags)
706143Snate@binkert.org        return SourceList(filter(match, self))
716143Snate@binkert.org
726143Snate@binkert.org    def with_any_tags(self, *tags):
736143Snate@binkert.org        '''Return a list of sources with any of the supplied tags.'''
746143Snate@binkert.org        return self.with_tags_that(lambda stags: len(set(tags) & stags) > 0)
756143Snate@binkert.org
766143Snate@binkert.org    def with_all_tags(self, *tags):
776143Snate@binkert.org        '''Return a list of sources with all of the supplied tags.'''
786143Snate@binkert.org        return self.with_tags_that(lambda stags: set(tags) <= stags)
796143Snate@binkert.org
806143Snate@binkert.org    def with_tag(self, tag):
816143Snate@binkert.org        '''Return a list of sources with the supplied tag.'''
826143Snate@binkert.org        return self.with_tags_that(lambda stags: tag in stags)
836143Snate@binkert.org
846143Snate@binkert.org    def without_tags(self, *tags):
856143Snate@binkert.org        '''Return a list of sources without any of the supplied tags.'''
866143Snate@binkert.org        return self.with_tags_that(lambda stags: len(set(tags) & stags) == 0)
876143Snate@binkert.org
886143Snate@binkert.org    def without_tag(self, tag):
896143Snate@binkert.org        '''Return a list of sources with the supplied tag.'''
906143Snate@binkert.org        return self.with_tags_that(lambda stags: tag not in stags)
917065Snate@binkert.org
926143Snate@binkert.orgclass SourceMeta(type):
936143Snate@binkert.org    '''Meta class for source files that keeps track of all files of a
946143Snate@binkert.org    particular type.'''
956143Snate@binkert.org    def __init__(cls, name, bases, dict):
966143Snate@binkert.org        super(SourceMeta, cls).__init__(name, bases, dict)
976143Snate@binkert.org        cls.all = SourceList()
986143Snate@binkert.org
996143Snate@binkert.orgclass SourceFile(object):
1006143Snate@binkert.org    '''Base object that encapsulates the notion of a source file.
1016143Snate@binkert.org    This includes, the source node, target node, various manipulations
1026143Snate@binkert.org    of those.  A source file also specifies a set of tags which
1036143Snate@binkert.org    describing arbitrary properties of the source file.'''
1046143Snate@binkert.org    __metaclass__ = SourceMeta
1056143Snate@binkert.org
1066143Snate@binkert.org    static_objs = {}
1076143Snate@binkert.org    shared_objs = {}
1086143Snate@binkert.org
1096143Snate@binkert.org    def __init__(self, source, tags=None, add_tags=None):
1106143Snate@binkert.org        if tags is None:
1116143Snate@binkert.org            tags='gem5 lib'
1126143Snate@binkert.org        if isinstance(tags, basestring):
1135522Snate@binkert.org            tags = set([tags])
1146143Snate@binkert.org        if not isinstance(tags, set):
1156143Snate@binkert.org            tags = set(tags)
1166143Snate@binkert.org        self.tags = tags
1176143Snate@binkert.org
1186143Snate@binkert.org        if add_tags:
1196143Snate@binkert.org            if isinstance(add_tags, basestring):
1206143Snate@binkert.org                add_tags = set([add_tags])
1216143Snate@binkert.org            if not isinstance(add_tags, set):
1226143Snate@binkert.org                add_tags = set(add_tags)
1236143Snate@binkert.org            self.tags |= add_tags
1245522Snate@binkert.org
1255522Snate@binkert.org        tnode = source
1265522Snate@binkert.org        if not isinstance(source, SCons.Node.FS.File):
1275522Snate@binkert.org            tnode = File(source)
1285604Snate@binkert.org
1295604Snate@binkert.org        self.tnode = tnode
1306143Snate@binkert.org        self.snode = tnode.srcnode()
1316143Snate@binkert.org
1324762Snate@binkert.org        for base in type(self).__mro__:
1334762Snate@binkert.org            if issubclass(base, SourceFile):
1346143Snate@binkert.org                base.all.append(self)
1356727Ssteve.reinhardt@amd.com
1366727Ssteve.reinhardt@amd.com    def static(self, env):
1376727Ssteve.reinhardt@amd.com        key = (self.tnode, env['OBJSUFFIX'])
1384762Snate@binkert.org        if not key in self.static_objs:
1396143Snate@binkert.org            self.static_objs[key] = env.StaticObject(self.tnode)
1406143Snate@binkert.org        return self.static_objs[key]
1416143Snate@binkert.org
1426143Snate@binkert.org    def shared(self, env):
1436727Ssteve.reinhardt@amd.com        key = (self.tnode, env['OBJSUFFIX'])
1446143Snate@binkert.org        if not key in self.shared_objs:
1456143Snate@binkert.org            self.shared_objs[key] = env.SharedObject(self.tnode)
1466143Snate@binkert.org        return self.shared_objs[key]
1475604Snate@binkert.org
1486143Snate@binkert.org    @property
1496143Snate@binkert.org    def filename(self):
1506143Snate@binkert.org        return str(self.tnode)
1514762Snate@binkert.org
1526143Snate@binkert.org    @property
1534762Snate@binkert.org    def dirname(self):
1544762Snate@binkert.org        return dirname(self.filename)
1554762Snate@binkert.org
1566143Snate@binkert.org    @property
1576143Snate@binkert.org    def basename(self):
1584762Snate@binkert.org        return basename(self.filename)
1596143Snate@binkert.org
1606143Snate@binkert.org    @property
1616143Snate@binkert.org    def extname(self):
1626143Snate@binkert.org        index = self.basename.rfind('.')
1634762Snate@binkert.org        if index <= 0:
1646143Snate@binkert.org            # dot files aren't extensions
1654762Snate@binkert.org            return self.basename, None
1666143Snate@binkert.org
1674762Snate@binkert.org        return self.basename[:index], self.basename[index+1:]
1686143Snate@binkert.org
1696143Snate@binkert.org    def __lt__(self, other): return self.filename < other.filename
1706143Snate@binkert.org    def __le__(self, other): return self.filename <= other.filename
1716143Snate@binkert.org    def __gt__(self, other): return self.filename > other.filename
1726143Snate@binkert.org    def __ge__(self, other): return self.filename >= other.filename
1736143Snate@binkert.org    def __eq__(self, other): return self.filename == other.filename
1746143Snate@binkert.org    def __ne__(self, other): return self.filename != other.filename
1756143Snate@binkert.org
1766143Snate@binkert.orgclass Source(SourceFile):
1776143Snate@binkert.org    ungrouped_tag = 'No link group'
1786143Snate@binkert.org    source_groups = set()
1796143Snate@binkert.org
1806143Snate@binkert.org    _current_group_tag = ungrouped_tag
181955SN/A
1825584Snate@binkert.org    @staticmethod
1835584Snate@binkert.org    def link_group_tag(group):
1845584Snate@binkert.org        return 'link group: %s' % group
1855584Snate@binkert.org
1866143Snate@binkert.org    @classmethod
1876143Snate@binkert.org    def set_group(cls, group):
1886143Snate@binkert.org        new_tag = Source.link_group_tag(group)
1895584Snate@binkert.org        Source._current_group_tag = new_tag
1904382Sbinkertn@umich.edu        Source.source_groups.add(group)
1914202Sbinkertn@umich.edu
1924382Sbinkertn@umich.edu    def _add_link_group_tag(self):
1934382Sbinkertn@umich.edu        self.tags.add(Source._current_group_tag)
1944382Sbinkertn@umich.edu
1955584Snate@binkert.org    '''Add a c/c++ source file to the build'''
1964382Sbinkertn@umich.edu    def __init__(self, source, tags=None, add_tags=None):
1974382Sbinkertn@umich.edu        '''specify the source file, and any tags'''
1984382Sbinkertn@umich.edu        super(Source, self).__init__(source, tags, add_tags)
1995192Ssaidi@eecs.umich.edu        self._add_link_group_tag()
2005192Ssaidi@eecs.umich.edu
2015799Snate@binkert.orgclass PySource(SourceFile):
2025799Snate@binkert.org    '''Add a python source file to the named package'''
2035799Snate@binkert.org    invalid_sym_char = re.compile('[^A-z0-9_]')
2045192Ssaidi@eecs.umich.edu    modules = {}
2055799Snate@binkert.org    tnodes = {}
2065192Ssaidi@eecs.umich.edu    symnames = {}
2075799Snate@binkert.org
2085799Snate@binkert.org    def __init__(self, package, source, tags=None, add_tags=None):
2095192Ssaidi@eecs.umich.edu        '''specify the python package, the source file, and any tags'''
2105192Ssaidi@eecs.umich.edu        super(PySource, self).__init__(source, tags, add_tags)
2115192Ssaidi@eecs.umich.edu
2125799Snate@binkert.org        modname,ext = self.extname
2135192Ssaidi@eecs.umich.edu        assert ext == 'py'
2145192Ssaidi@eecs.umich.edu
2155192Ssaidi@eecs.umich.edu        if package:
2165192Ssaidi@eecs.umich.edu            path = package.split('.')
2175192Ssaidi@eecs.umich.edu        else:
2185192Ssaidi@eecs.umich.edu            path = []
2194382Sbinkertn@umich.edu
2204382Sbinkertn@umich.edu        modpath = path[:]
2214382Sbinkertn@umich.edu        if modname != '__init__':
2222667Sstever@eecs.umich.edu            modpath += [ modname ]
2232667Sstever@eecs.umich.edu        modpath = '.'.join(modpath)
2242667Sstever@eecs.umich.edu
2252667Sstever@eecs.umich.edu        arcpath = path + [ self.basename ]
2262667Sstever@eecs.umich.edu        abspath = self.snode.abspath
2272667Sstever@eecs.umich.edu        if not exists(abspath):
2285742Snate@binkert.org            abspath = self.tnode.abspath
2295742Snate@binkert.org
2305742Snate@binkert.org        self.package = package
2315793Snate@binkert.org        self.modname = modname
2325793Snate@binkert.org        self.modpath = modpath
2335793Snate@binkert.org        self.arcname = joinpath(*arcpath)
2345793Snate@binkert.org        self.abspath = abspath
2355793Snate@binkert.org        self.compiled = File(self.filename + 'c')
2364382Sbinkertn@umich.edu        self.cpp = File(self.filename + '.cc')
2374762Snate@binkert.org        self.symname = PySource.invalid_sym_char.sub('_', modpath)
2385344Sstever@gmail.com
2394382Sbinkertn@umich.edu        PySource.modules[modpath] = self
2405341Sstever@gmail.com        PySource.tnodes[self.tnode] = self
2415742Snate@binkert.org        PySource.symnames[self.symname] = self
2425742Snate@binkert.org
2435742Snate@binkert.orgclass SimObject(PySource):
2445742Snate@binkert.org    '''Add a SimObject python file as a python source object and add
2455742Snate@binkert.org    it to a list of sim object modules'''
2464762Snate@binkert.org
2475742Snate@binkert.org    fixed = False
2485742Snate@binkert.org    modnames = []
2495742Snate@binkert.org
2505742Snate@binkert.org    def __init__(self, source, tags=None, add_tags=None):
2515742Snate@binkert.org        '''Specify the source file and any tags (automatically in
2525742Snate@binkert.org        the m5.objects package)'''
2535742Snate@binkert.org        super(SimObject, self).__init__('m5.objects', source, tags, add_tags)
2545341Sstever@gmail.com        if self.fixed:
2555742Snate@binkert.org            raise AttributeError, "Too late to call SimObject now."
2565341Sstever@gmail.com
2574773Snate@binkert.org        bisect.insort_right(SimObject.modnames, self.modname)
2586108Snate@binkert.org
2591858SN/Aclass ProtoBuf(SourceFile):
2601085SN/A    '''Add a Protocol Buffer to build'''
2616658Snate@binkert.org
2626658Snate@binkert.org    def __init__(self, source, tags=None, add_tags=None):
2636658Snate@binkert.org        '''Specify the source file, and any tags'''
2646658Snate@binkert.org        super(ProtoBuf, self).__init__(source, tags, add_tags)
2656658Snate@binkert.org
2666658Snate@binkert.org        # Get the file name and the extension
2676658Snate@binkert.org        modname,ext = self.extname
2686658Snate@binkert.org        assert ext == 'proto'
2696658Snate@binkert.org
2706658Snate@binkert.org        # Currently, we stick to generating the C++ headers, so we
2716658Snate@binkert.org        # only need to track the source and header.
2726658Snate@binkert.org        self.cc_file = File(modname + '.pb.cc')
2736658Snate@binkert.org        self.hh_file = File(modname + '.pb.h')
2746658Snate@binkert.org
2756658Snate@binkert.orgclass UnitTest(object):
2766658Snate@binkert.org    '''Create a UnitTest'''
2776658Snate@binkert.org
2786658Snate@binkert.org    all = []
2796658Snate@binkert.org    def __init__(self, target, *sources, **kwargs):
2806658Snate@binkert.org        '''Specify the target name and any sources.  Sources that are
2816658Snate@binkert.org        not SourceFiles are evalued with Source().  All files are
2826658Snate@binkert.org        tagged with the name of the UnitTest target.'''
2836658Snate@binkert.org
2846658Snate@binkert.org        srcs = SourceList()
2856658Snate@binkert.org        for src in sources:
2864382Sbinkertn@umich.edu            if not isinstance(src, SourceFile):
2874382Sbinkertn@umich.edu                src = Source(src, tags=str(target))
2884762Snate@binkert.org            srcs.append(src)
2894762Snate@binkert.org
2904762Snate@binkert.org        self.sources = srcs
2916654Snate@binkert.org        self.target = target
2926654Snate@binkert.org        self.main = kwargs.get('main', False)
2935517Snate@binkert.org        self.all.append(self)
2945517Snate@binkert.org
2955517Snate@binkert.orgclass GTest(UnitTest):
2965517Snate@binkert.org    '''Create a unit test based on the google test framework.'''
2975517Snate@binkert.org
2985517Snate@binkert.org    all = []
2995517Snate@binkert.org    def __init__(self, *args, **kwargs):
3005517Snate@binkert.org        super(GTest, self).__init__(*args, **kwargs)
3015517Snate@binkert.org        self.dir = Dir('.')
3025517Snate@binkert.org
3035517Snate@binkert.org# Children should have access
3045517Snate@binkert.orgExport('Source')
3055517Snate@binkert.orgExport('PySource')
3065517Snate@binkert.orgExport('SimObject')
3075517Snate@binkert.orgExport('ProtoBuf')
3085517Snate@binkert.orgExport('UnitTest')
3095517Snate@binkert.orgExport('GTest')
3106654Snate@binkert.org
3115517Snate@binkert.org########################################################################
3125517Snate@binkert.org#
3135517Snate@binkert.org# Debug Flags
3145517Snate@binkert.org#
3155517Snate@binkert.orgdebug_flags = {}
3165517Snate@binkert.orgdef DebugFlag(name, desc=None):
3175517Snate@binkert.org    if name in debug_flags:
3185517Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
3196143Snate@binkert.org    debug_flags[name] = (name, (), desc)
3206654Snate@binkert.org
3215517Snate@binkert.orgdef CompoundFlag(name, flags, desc=None):
3225517Snate@binkert.org    if name in debug_flags:
3235517Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
3245517Snate@binkert.org
3255517Snate@binkert.org    compound = tuple(flags)
3265517Snate@binkert.org    debug_flags[name] = (name, compound, desc)
3275517Snate@binkert.org
3285517Snate@binkert.orgExport('DebugFlag')
3295517Snate@binkert.orgExport('CompoundFlag')
3305517Snate@binkert.org
3315517Snate@binkert.org########################################################################
3325517Snate@binkert.org#
3335517Snate@binkert.org# Set some compiler variables
3345517Snate@binkert.org#
3356654Snate@binkert.org
3366654Snate@binkert.org# Include file paths are rooted in this directory.  SCons will
3375517Snate@binkert.org# automatically expand '.' to refer to both the source directory and
3385517Snate@binkert.org# the corresponding build directory to pick up generated include
3396143Snate@binkert.org# files.
3406143Snate@binkert.orgenv.Append(CPPPATH=Dir('.'))
3416143Snate@binkert.org
3426727Ssteve.reinhardt@amd.comfor extra_dir in extras_dir_list:
3435517Snate@binkert.org    env.Append(CPPPATH=Dir(extra_dir))
3446727Ssteve.reinhardt@amd.com
3455517Snate@binkert.org# Workaround for bug in SCons version > 0.97d20071212
3465517Snate@binkert.org# Scons bug id: 2006 gem5 Bug id: 308
3475517Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
3486654Snate@binkert.org    Dir(root[len(base_dir) + 1:])
3496654Snate@binkert.org
3506654Snate@binkert.org########################################################################
3516654Snate@binkert.org#
3526654Snate@binkert.org# Walk the tree and execute all SConscripts in subdirectories
3536654Snate@binkert.org#
3545517Snate@binkert.org
3555517Snate@binkert.orghere = Dir('.').srcnode().abspath
3565517Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
3576143Snate@binkert.org    if root == here:
3585517Snate@binkert.org        # we don't want to recurse back into this SConscript
3594762Snate@binkert.org        continue
3605517Snate@binkert.org
3615517Snate@binkert.org    if 'SConscript' in files:
3626143Snate@binkert.org        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
3636143Snate@binkert.org        Source.set_group(build_dir)
3645517Snate@binkert.org        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3655517Snate@binkert.org
3665517Snate@binkert.orgfor extra_dir in extras_dir_list:
3675517Snate@binkert.org    prefix_len = len(dirname(extra_dir)) + 1
3685517Snate@binkert.org
3695517Snate@binkert.org    # Also add the corresponding build directory to pick up generated
3705517Snate@binkert.org    # include files.
3715517Snate@binkert.org    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
3725517Snate@binkert.org
3735517Snate@binkert.org    for root, dirs, files in os.walk(extra_dir, topdown=True):
3746143Snate@binkert.org        # if build lives in the extras directory, don't walk down it
3755517Snate@binkert.org        if 'build' in dirs:
3766654Snate@binkert.org            dirs.remove('build')
3776654Snate@binkert.org
3786654Snate@binkert.org        if 'SConscript' in files:
3796654Snate@binkert.org            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
3806654Snate@binkert.org            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3816654Snate@binkert.org
3825517Snate@binkert.orgfor opt in export_vars:
3835517Snate@binkert.org    env.ConfigFile(opt)
3845517Snate@binkert.org
3855517Snate@binkert.orgdef makeTheISA(source, target, env):
3865517Snate@binkert.org    isas = [ src.get_contents() for src in source ]
3874762Snate@binkert.org    target_isa = env['TARGET_ISA']
3884762Snate@binkert.org    def define(isa):
3894762Snate@binkert.org        return isa.upper() + '_ISA'
3904762Snate@binkert.org
3914762Snate@binkert.org    def namespace(isa):
3924762Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA'
3936143Snate@binkert.org
3944762Snate@binkert.org
3954762Snate@binkert.org    code = code_formatter()
3964762Snate@binkert.org    code('''\
3974762Snate@binkert.org#ifndef __CONFIG_THE_ISA_HH__
3984382Sbinkertn@umich.edu#define __CONFIG_THE_ISA_HH__
3994382Sbinkertn@umich.edu
4005517Snate@binkert.org''')
4016654Snate@binkert.org
4025517Snate@binkert.org    # create defines for the preprocessing and compile-time determination
4035798Snate@binkert.org    for i,isa in enumerate(isas):
4046654Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
4056654Snate@binkert.org    code()
4066654Snate@binkert.org
4076654Snate@binkert.org    # create an enum for any run-time determination of the ISA, we
4086654Snate@binkert.org    # reuse the same name as the namespaces
4096654Snate@binkert.org    code('enum class Arch {')
4106654Snate@binkert.org    for i,isa in enumerate(isas):
4116654Snate@binkert.org        if i + 1 == len(isas):
4126654Snate@binkert.org            code('  $0 = $1', namespace(isa), define(isa))
4136654Snate@binkert.org        else:
4146669Snate@binkert.org            code('  $0 = $1,', namespace(isa), define(isa))
4156669Snate@binkert.org    code('};')
4166669Snate@binkert.org
4176669Snate@binkert.org    code('''
4186669Snate@binkert.org
4196669Snate@binkert.org#define THE_ISA ${{define(target_isa)}}
4206654Snate@binkert.org#define TheISA ${{namespace(target_isa)}}
4216654Snate@binkert.org#define THE_ISA_STR "${{target_isa}}"
4225517Snate@binkert.org
4235863Snate@binkert.org#endif // __CONFIG_THE_ISA_HH__''')
4245798Snate@binkert.org
4255798Snate@binkert.org    code.write(str(target[0]))
4265798Snate@binkert.org
4275798Snate@binkert.orgenv.Command('config/the_isa.hh', map(Value, all_isa_list),
4285517Snate@binkert.org            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
4295517Snate@binkert.org
4305517Snate@binkert.orgdef makeTheGPUISA(source, target, env):
4315517Snate@binkert.org    isas = [ src.get_contents() for src in source ]
4325517Snate@binkert.org    target_gpu_isa = env['TARGET_GPU_ISA']
4335517Snate@binkert.org    def define(isa):
4345517Snate@binkert.org        return isa.upper() + '_ISA'
4355517Snate@binkert.org
4365798Snate@binkert.org    def namespace(isa):
4375798Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA'
4385798Snate@binkert.org
4395798Snate@binkert.org
4405798Snate@binkert.org    code = code_formatter()
4415798Snate@binkert.org    code('''\
4425517Snate@binkert.org#ifndef __CONFIG_THE_GPU_ISA_HH__
4435517Snate@binkert.org#define __CONFIG_THE_GPU_ISA_HH__
4445517Snate@binkert.org
4455517Snate@binkert.org''')
4465517Snate@binkert.org
4475517Snate@binkert.org    # create defines for the preprocessing and compile-time determination
4485517Snate@binkert.org    for i,isa in enumerate(isas):
4495517Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
4505517Snate@binkert.org    code()
4514762Snate@binkert.org
4524382Sbinkertn@umich.edu    # create an enum for any run-time determination of the ISA, we
4536143Snate@binkert.org    # reuse the same name as the namespaces
4545517Snate@binkert.org    code('enum class GPUArch {')
4554382Sbinkertn@umich.edu    for i,isa in enumerate(isas):
4564382Sbinkertn@umich.edu        if i + 1 == len(isas):
4574762Snate@binkert.org            code('  $0 = $1', namespace(isa), define(isa))
4584762Snate@binkert.org        else:
4594762Snate@binkert.org            code('  $0 = $1,', namespace(isa), define(isa))
4604762Snate@binkert.org    code('};')
4614762Snate@binkert.org
4625517Snate@binkert.org    code('''
4635517Snate@binkert.org
4645517Snate@binkert.org#define THE_GPU_ISA ${{define(target_gpu_isa)}}
4655517Snate@binkert.org#define TheGpuISA ${{namespace(target_gpu_isa)}}
4665517Snate@binkert.org#define THE_GPU_ISA_STR "${{target_gpu_isa}}"
4675517Snate@binkert.org
4685517Snate@binkert.org#endif // __CONFIG_THE_GPU_ISA_HH__''')
4695517Snate@binkert.org
4706143Snate@binkert.org    code.write(str(target[0]))
4715517Snate@binkert.org
4725517Snate@binkert.orgenv.Command('config/the_gpu_isa.hh', map(Value, all_gpu_isa_list),
4735517Snate@binkert.org            MakeAction(makeTheGPUISA, Transform("CFG ISA", 0)))
4745517Snate@binkert.org
4755517Snate@binkert.org########################################################################
4765517Snate@binkert.org#
4775517Snate@binkert.org# Prevent any SimObjects from being added after this point, they
4785517Snate@binkert.org# should all have been added in the SConscripts above
4795517Snate@binkert.org#
4805517Snate@binkert.orgSimObject.fixed = True
4816143Snate@binkert.org
4825517Snate@binkert.orgclass DictImporter(object):
4835517Snate@binkert.org    '''This importer takes a dictionary of arbitrary module names that
4845517Snate@binkert.org    map to arbitrary filenames.'''
4855517Snate@binkert.org    def __init__(self, modules):
4865517Snate@binkert.org        self.modules = modules
4875517Snate@binkert.org        self.installed = set()
4885517Snate@binkert.org
4895517Snate@binkert.org    def __del__(self):
4905517Snate@binkert.org        self.unload()
4915517Snate@binkert.org
4925517Snate@binkert.org    def unload(self):
4935517Snate@binkert.org        import sys
4945517Snate@binkert.org        for module in self.installed:
4955517Snate@binkert.org            del sys.modules[module]
4965517Snate@binkert.org        self.installed = set()
4975517Snate@binkert.org
4985517Snate@binkert.org    def find_module(self, fullname, path):
4995517Snate@binkert.org        if fullname == 'm5.defines':
5005517Snate@binkert.org            return self
5016143Snate@binkert.org
5025517Snate@binkert.org        if fullname == 'm5.objects':
5034762Snate@binkert.org            return self
5044762Snate@binkert.org
5056143Snate@binkert.org        if fullname.startswith('_m5'):
5066143Snate@binkert.org            return None
5076143Snate@binkert.org
5084762Snate@binkert.org        source = self.modules.get(fullname, None)
5094762Snate@binkert.org        if source is not None and fullname.startswith('m5.objects'):
5104762Snate@binkert.org            return self
5115517Snate@binkert.org
5124762Snate@binkert.org        return None
5134762Snate@binkert.org
5144762Snate@binkert.org    def load_module(self, fullname):
5155463Snate@binkert.org        mod = imp.new_module(fullname)
5165517Snate@binkert.org        sys.modules[fullname] = mod
5176656Snate@binkert.org        self.installed.add(fullname)
5185463Snate@binkert.org
5195517Snate@binkert.org        mod.__loader__ = self
5204762Snate@binkert.org        if fullname == 'm5.objects':
5214762Snate@binkert.org            mod.__path__ = fullname.split('.')
5224762Snate@binkert.org            return mod
5236143Snate@binkert.org
5246143Snate@binkert.org        if fullname == 'm5.defines':
5256143Snate@binkert.org            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
5264762Snate@binkert.org            return mod
5274762Snate@binkert.org
5285517Snate@binkert.org        source = self.modules[fullname]
5294762Snate@binkert.org        if source.modname == '__init__':
5304762Snate@binkert.org            mod.__path__ = source.modpath
5314762Snate@binkert.org        mod.__file__ = source.abspath
5324762Snate@binkert.org
5335517Snate@binkert.org        exec file(source.abspath, 'r') in mod.__dict__
5344762Snate@binkert.org
5354762Snate@binkert.org        return mod
5364762Snate@binkert.org
5374762Snate@binkert.orgimport m5.SimObject
5385517Snate@binkert.orgimport m5.params
5395517Snate@binkert.orgfrom m5.util import code_formatter
5405517Snate@binkert.org
5415517Snate@binkert.orgm5.SimObject.clear()
5425517Snate@binkert.orgm5.params.clear()
5435517Snate@binkert.org
5445517Snate@binkert.org# install the python importer so we can grab stuff from the source
5455517Snate@binkert.org# tree itself.  We can't have SimObjects added after this point or
5465517Snate@binkert.org# else we won't know about them for the rest of the stuff.
5475517Snate@binkert.orgimporter = DictImporter(PySource.modules)
5485517Snate@binkert.orgsys.meta_path[0:0] = [ importer ]
5495517Snate@binkert.org
5505517Snate@binkert.org# import all sim objects so we can populate the all_objects list
5515517Snate@binkert.org# make sure that we're working with a list, then let's sort it
5525517Snate@binkert.orgfor modname in SimObject.modnames:
5535517Snate@binkert.org    exec('from m5.objects import %s' % modname)
5545517Snate@binkert.org
5555517Snate@binkert.org# we need to unload all of the currently imported modules so that they
5565517Snate@binkert.org# will be re-imported the next time the sconscript is run
5575517Snate@binkert.orgimporter.unload()
5585517Snate@binkert.orgsys.meta_path.remove(importer)
5595517Snate@binkert.org
5605517Snate@binkert.orgsim_objects = m5.SimObject.allClasses
5615517Snate@binkert.orgall_enums = m5.params.allEnums
5625517Snate@binkert.org
5635517Snate@binkert.orgfor name,obj in sorted(sim_objects.iteritems()):
5645517Snate@binkert.org    for param in obj._params.local.values():
5655517Snate@binkert.org        # load the ptype attribute now because it depends on the
5665517Snate@binkert.org        # current version of SimObject.allClasses, but when scons
5675517Snate@binkert.org        # actually uses the value, all versions of
5685517Snate@binkert.org        # SimObject.allClasses will have been loaded
5695517Snate@binkert.org        param.ptype
5705517Snate@binkert.org
5715517Snate@binkert.org########################################################################
5725517Snate@binkert.org#
5735517Snate@binkert.org# calculate extra dependencies
5745517Snate@binkert.org#
5755517Snate@binkert.orgmodule_depends = ["m5", "m5.SimObject", "m5.params"]
5765517Snate@binkert.orgdepends = [ PySource.modules[dep].snode for dep in module_depends ]
5775517Snate@binkert.orgdepends.sort(key = lambda x: x.name)
5785517Snate@binkert.org
5795517Snate@binkert.org########################################################################
5805517Snate@binkert.org#
5815517Snate@binkert.org# Commands for the basic automatically generated python files
5825517Snate@binkert.org#
5835517Snate@binkert.org
5845517Snate@binkert.org# Generate Python file containing a dict specifying the current
5855517Snate@binkert.org# buildEnv flags.
5865517Snate@binkert.orgdef makeDefinesPyFile(target, source, env):
5875517Snate@binkert.org    build_env = source[0].get_contents()
5885517Snate@binkert.org
5895517Snate@binkert.org    code = code_formatter()
5905517Snate@binkert.org    code("""
5915517Snate@binkert.orgimport _m5.core
5925517Snate@binkert.orgimport m5.util
5935517Snate@binkert.org
5945517Snate@binkert.orgbuildEnv = m5.util.SmartDict($build_env)
5955517Snate@binkert.org
5965517Snate@binkert.orgcompileDate = _m5.core.compileDate
5975517Snate@binkert.org_globals = globals()
5985517Snate@binkert.orgfor key,val in _m5.core.__dict__.iteritems():
5995517Snate@binkert.org    if key.startswith('flag_'):
6005517Snate@binkert.org        flag = key[5:]
6015517Snate@binkert.org        _globals[flag] = val
6025517Snate@binkert.orgdel _globals
6035517Snate@binkert.org""")
6045610Snate@binkert.org    code.write(target[0].abspath)
6055623Snate@binkert.org
6065623Snate@binkert.orgdefines_info = Value(build_env)
6075623Snate@binkert.org# Generate a file with all of the compile options in it
6085610Snate@binkert.orgenv.Command('python/m5/defines.py', defines_info,
6095517Snate@binkert.org            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
6105623Snate@binkert.orgPySource('m5', 'python/m5/defines.py')
6115623Snate@binkert.org
6125623Snate@binkert.org# Generate python file containing info about the M5 source code
6135623Snate@binkert.orgdef makeInfoPyFile(target, source, env):
6145623Snate@binkert.org    code = code_formatter()
6155623Snate@binkert.org    for src in source:
6165623Snate@binkert.org        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
6175517Snate@binkert.org        code('$src = ${{repr(data)}}')
6185610Snate@binkert.org    code.write(str(target[0]))
6195610Snate@binkert.org
6205610Snate@binkert.org# Generate a file that wraps the basic top level files
6215610Snate@binkert.orgenv.Command('python/m5/info.py',
6225517Snate@binkert.org            [ '#/COPYING', '#/LICENSE', '#/README', ],
6235517Snate@binkert.org            MakeAction(makeInfoPyFile, Transform("INFO")))
6245610Snate@binkert.orgPySource('m5', 'python/m5/info.py')
6255610Snate@binkert.org
6265517Snate@binkert.org########################################################################
6275517Snate@binkert.org#
6285517Snate@binkert.org# Create all of the SimObject param headers and enum headers
6295517Snate@binkert.org#
6305517Snate@binkert.org
6315517Snate@binkert.orgdef createSimObjectParamStruct(target, source, env):
6325517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6335517Snate@binkert.org
6345517Snate@binkert.org    name = source[0].get_text_contents()
6355517Snate@binkert.org    obj = sim_objects[name]
6364762Snate@binkert.org
6376143Snate@binkert.org    code = code_formatter()
6386143Snate@binkert.org    obj.cxx_param_decl(code)
6395463Snate@binkert.org    code.write(target[0].abspath)
6404762Snate@binkert.org
6414762Snate@binkert.orgdef createSimObjectCxxConfig(is_header):
6424762Snate@binkert.org    def body(target, source, env):
6436143Snate@binkert.org        assert len(target) == 1 and len(source) == 1
6446143Snate@binkert.org
6454382Sbinkertn@umich.edu        name = str(source[0].get_contents())
6464382Sbinkertn@umich.edu        obj = sim_objects[name]
6476143Snate@binkert.org
6486143Snate@binkert.org        code = code_formatter()
6494382Sbinkertn@umich.edu        obj.cxx_config_param_file(code, is_header)
6504762Snate@binkert.org        code.write(target[0].abspath)
6515517Snate@binkert.org    return body
6525517Snate@binkert.org
6535517Snate@binkert.orgdef createEnumStrings(target, source, env):
6545517Snate@binkert.org    assert len(target) == 1 and len(source) == 2
6555517Snate@binkert.org
6565517Snate@binkert.org    name = source[0].get_text_contents()
6575522Snate@binkert.org    use_python = source[1].read()
6585517Snate@binkert.org    obj = all_enums[name]
6595517Snate@binkert.org
6605517Snate@binkert.org    code = code_formatter()
6615517Snate@binkert.org    obj.cxx_def(code)
6625517Snate@binkert.org    if use_python:
6636143Snate@binkert.org        obj.pybind_def(code)
6646143Snate@binkert.org    code.write(target[0].abspath)
6656143Snate@binkert.org
6665522Snate@binkert.orgdef createEnumDecls(target, source, env):
6674382Sbinkertn@umich.edu    assert len(target) == 1 and len(source) == 1
6686229Snate@binkert.org
6696229Snate@binkert.org    name = source[0].get_text_contents()
6706229Snate@binkert.org    obj = all_enums[name]
6716229Snate@binkert.org
6726229Snate@binkert.org    code = code_formatter()
6736229Snate@binkert.org    obj.cxx_decl(code)
6746229Snate@binkert.org    code.write(target[0].abspath)
6756229Snate@binkert.org
6766229Snate@binkert.orgdef createSimObjectPyBindWrapper(target, source, env):
6776229Snate@binkert.org    name = source[0].get_text_contents()
6786229Snate@binkert.org    obj = sim_objects[name]
6796229Snate@binkert.org
6806229Snate@binkert.org    code = code_formatter()
6816229Snate@binkert.org    obj.pybind_decl(code)
6826229Snate@binkert.org    code.write(target[0].abspath)
6836229Snate@binkert.org
6846229Snate@binkert.org# Generate all of the SimObject param C++ struct header files
6856229Snate@binkert.orgparams_hh_files = []
6866229Snate@binkert.orgfor name,simobj in sorted(sim_objects.iteritems()):
6876229Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
6886229Snate@binkert.org    extra_deps = [ py_source.tnode ]
6895192Ssaidi@eecs.umich.edu
6905517Snate@binkert.org    hh_file = File('params/%s.hh' % name)
6915517Snate@binkert.org    params_hh_files.append(hh_file)
6925517Snate@binkert.org    env.Command(hh_file, Value(name),
6935517Snate@binkert.org                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
6946229Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
6956229Snate@binkert.org
6965799Snate@binkert.org# C++ parameter description files
6975799Snate@binkert.orgif GetOption('with_cxx_config'):
6985517Snate@binkert.org    for name,simobj in sorted(sim_objects.iteritems()):
6995517Snate@binkert.org        py_source = PySource.modules[simobj.__module__]
7005517Snate@binkert.org        extra_deps = [ py_source.tnode ]
7015517Snate@binkert.org
7025517Snate@binkert.org        cxx_config_hh_file = File('cxx_config/%s.hh' % name)
7035517Snate@binkert.org        cxx_config_cc_file = File('cxx_config/%s.cc' % name)
7045799Snate@binkert.org        env.Command(cxx_config_hh_file, Value(name),
7055517Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(True),
7065517Snate@binkert.org                    Transform("CXXCPRHH")))
7075517Snate@binkert.org        env.Command(cxx_config_cc_file, Value(name),
7085517Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(False),
7095517Snate@binkert.org                    Transform("CXXCPRCC")))
7105517Snate@binkert.org        env.Depends(cxx_config_hh_file, depends + extra_deps +
7115517Snate@binkert.org                    [File('params/%s.hh' % name), File('sim/cxx_config.hh')])
7125799Snate@binkert.org        env.Depends(cxx_config_cc_file, depends + extra_deps +
7135517Snate@binkert.org                    [cxx_config_hh_file])
7145517Snate@binkert.org        Source(cxx_config_cc_file)
7155799Snate@binkert.org
7165517Snate@binkert.org    cxx_config_init_cc_file = File('cxx_config/init.cc')
7175517Snate@binkert.org
7185517Snate@binkert.org    def createCxxConfigInitCC(target, source, env):
7195517Snate@binkert.org        assert len(target) == 1 and len(source) == 1
7205517Snate@binkert.org
7215517Snate@binkert.org        code = code_formatter()
7225517Snate@binkert.org
7235517Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems()):
7245799Snate@binkert.org            if not hasattr(simobj, 'abstract') or not simobj.abstract:
7255517Snate@binkert.org                code('#include "cxx_config/${name}.hh"')
7265517Snate@binkert.org        code()
7275517Snate@binkert.org        code('void cxxConfigInit()')
7285517Snate@binkert.org        code('{')
7295517Snate@binkert.org        code.indent()
7305517Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems()):
7315517Snate@binkert.org            not_abstract = not hasattr(simobj, 'abstract') or \
7325517Snate@binkert.org                not simobj.abstract
7335517Snate@binkert.org            if not_abstract and 'type' in simobj.__dict__:
7345517Snate@binkert.org                code('cxx_config_directory["${name}"] = '
7355517Snate@binkert.org                     '${name}CxxConfigParams::makeDirectoryEntry();')
7365517Snate@binkert.org        code.dedent()
7376229Snate@binkert.org        code('}')
7385517Snate@binkert.org        code.write(target[0].abspath)
7395517Snate@binkert.org
7405517Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
7415517Snate@binkert.org    extra_deps = [ py_source.tnode ]
7425517Snate@binkert.org    env.Command(cxx_config_init_cc_file, Value(name),
7435517Snate@binkert.org        MakeAction(createCxxConfigInitCC, Transform("CXXCINIT")))
7445517Snate@binkert.org    cxx_param_hh_files = ["cxx_config/%s.hh" % simobj
7455517Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems())
7465517Snate@binkert.org        if not hasattr(simobj, 'abstract') or not simobj.abstract]
7475517Snate@binkert.org    Depends(cxx_config_init_cc_file, cxx_param_hh_files +
7485517Snate@binkert.org            [File('sim/cxx_config.hh')])
7495517Snate@binkert.org    Source(cxx_config_init_cc_file)
7505517Snate@binkert.org
7515517Snate@binkert.org# Generate all enum header files
7525517Snate@binkert.orgfor name,enum in sorted(all_enums.iteritems()):
7535517Snate@binkert.org    py_source = PySource.modules[enum.__module__]
7545517Snate@binkert.org    extra_deps = [ py_source.tnode ]
7555517Snate@binkert.org
7565517Snate@binkert.org    cc_file = File('enums/%s.cc' % name)
7575517Snate@binkert.org    env.Command(cc_file, [Value(name), Value(env['USE_PYTHON'])],
7585517Snate@binkert.org                MakeAction(createEnumStrings, Transform("ENUM STR")))
7595517Snate@binkert.org    env.Depends(cc_file, depends + extra_deps)
7605517Snate@binkert.org    Source(cc_file)
7615517Snate@binkert.org
7625517Snate@binkert.org    hh_file = File('enums/%s.hh' % name)
7635517Snate@binkert.org    env.Command(hh_file, Value(name),
7645517Snate@binkert.org                MakeAction(createEnumDecls, Transform("ENUMDECL")))
7655517Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
7665517Snate@binkert.org
7675517Snate@binkert.org# Generate SimObject Python bindings wrapper files
7685517Snate@binkert.orgif env['USE_PYTHON']:
7695517Snate@binkert.org    for name,simobj in sorted(sim_objects.iteritems()):
7705517Snate@binkert.org        py_source = PySource.modules[simobj.__module__]
7715517Snate@binkert.org        extra_deps = [ py_source.tnode ]
7725517Snate@binkert.org        cc_file = File('python/_m5/param_%s.cc' % name)
7735517Snate@binkert.org        env.Command(cc_file, Value(name),
7745517Snate@binkert.org                    MakeAction(createSimObjectPyBindWrapper,
7755517Snate@binkert.org                               Transform("SO PyBind")))
7765517Snate@binkert.org        env.Depends(cc_file, depends + extra_deps)
7775517Snate@binkert.org        Source(cc_file)
7785517Snate@binkert.org
7795517Snate@binkert.org# Build all protocol buffers if we have got protoc and protobuf available
7805517Snate@binkert.orgif env['HAVE_PROTOBUF']:
7815517Snate@binkert.org    for proto in ProtoBuf.all:
7825517Snate@binkert.org        # Use both the source and header as the target, and the .proto
7835517Snate@binkert.org        # file as the source. When executing the protoc compiler, also
7845517Snate@binkert.org        # specify the proto_path to avoid having the generated files
7855517Snate@binkert.org        # include the path.
7865517Snate@binkert.org        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
7875517Snate@binkert.org                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
7885517Snate@binkert.org                               '--proto_path ${SOURCE.dir} $SOURCE',
7895517Snate@binkert.org                               Transform("PROTOC")))
7905517Snate@binkert.org
7915517Snate@binkert.org        # Add the C++ source file
7925517Snate@binkert.org        Source(proto.cc_file, tags=proto.tags)
7935517Snate@binkert.orgelif ProtoBuf.all:
7945517Snate@binkert.org    print 'Got protobuf to build, but lacks support!'
7955517Snate@binkert.org    Exit(1)
7965517Snate@binkert.org
7975517Snate@binkert.org#
7985517Snate@binkert.org# Handle debug flags
7995517Snate@binkert.org#
8005517Snate@binkert.orgdef makeDebugFlagCC(target, source, env):
8015517Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
8025517Snate@binkert.org
8035517Snate@binkert.org    code = code_formatter()
8045517Snate@binkert.org
8055517Snate@binkert.org    # delay definition of CompoundFlags until after all the definition
8065517Snate@binkert.org    # of all constituent SimpleFlags
8075517Snate@binkert.org    comp_code = code_formatter()
8085517Snate@binkert.org
8095517Snate@binkert.org    # file header
8106229Snate@binkert.org    code('''
8115517Snate@binkert.org/*
8125517Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated by SCons.
8135517Snate@binkert.org */
8145517Snate@binkert.org
8155517Snate@binkert.org#include "base/debug.hh"
8165517Snate@binkert.org
8175517Snate@binkert.orgnamespace Debug {
8185517Snate@binkert.org
8195517Snate@binkert.org''')
8205517Snate@binkert.org
8215517Snate@binkert.org    for name, flag in sorted(source[0].read().iteritems()):
8225517Snate@binkert.org        n, compound, desc = flag
8235517Snate@binkert.org        assert n == name
8245517Snate@binkert.org
8255517Snate@binkert.org        if not compound:
8265517Snate@binkert.org            code('SimpleFlag $name("$name", "$desc");')
8275517Snate@binkert.org        else:
8285517Snate@binkert.org            comp_code('CompoundFlag $name("$name", "$desc",')
8295517Snate@binkert.org            comp_code.indent()
8305517Snate@binkert.org            last = len(compound) - 1
8315517Snate@binkert.org            for i,flag in enumerate(compound):
8325517Snate@binkert.org                if i != last:
8335517Snate@binkert.org                    comp_code('&$flag,')
8345517Snate@binkert.org                else:
8355517Snate@binkert.org                    comp_code('&$flag);')
8365517Snate@binkert.org            comp_code.dedent()
8375517Snate@binkert.org
8385517Snate@binkert.org    code.append(comp_code)
8395517Snate@binkert.org    code()
8405517Snate@binkert.org    code('} // namespace Debug')
8415517Snate@binkert.org
8425517Snate@binkert.org    code.write(str(target[0]))
8435517Snate@binkert.org
8445517Snate@binkert.orgdef makeDebugFlagHH(target, source, env):
8455517Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
8465517Snate@binkert.org
8475517Snate@binkert.org    val = eval(source[0].get_contents())
8485517Snate@binkert.org    name, compound, desc = val
8495517Snate@binkert.org
8505517Snate@binkert.org    code = code_formatter()
8515517Snate@binkert.org
8525517Snate@binkert.org    # file header boilerplate
8535517Snate@binkert.org    code('''\
8545517Snate@binkert.org/*
8555517Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated by SCons.
8565517Snate@binkert.org */
8575517Snate@binkert.org
8585517Snate@binkert.org#ifndef __DEBUG_${name}_HH__
8595517Snate@binkert.org#define __DEBUG_${name}_HH__
8605517Snate@binkert.org
8615517Snate@binkert.orgnamespace Debug {
8625517Snate@binkert.org''')
8635517Snate@binkert.org
8645517Snate@binkert.org    if compound:
8655517Snate@binkert.org        code('class CompoundFlag;')
8665517Snate@binkert.org    code('class SimpleFlag;')
8675517Snate@binkert.org
8685517Snate@binkert.org    if compound:
8695517Snate@binkert.org        code('extern CompoundFlag $name;')
8705517Snate@binkert.org        for flag in compound:
8715517Snate@binkert.org            code('extern SimpleFlag $flag;')
8726143Snate@binkert.org    else:
8735517Snate@binkert.org        code('extern SimpleFlag $name;')
8745192Ssaidi@eecs.umich.edu
8755192Ssaidi@eecs.umich.edu    code('''
8765517Snate@binkert.org}
8775517Snate@binkert.org
8785192Ssaidi@eecs.umich.edu#endif // __DEBUG_${name}_HH__
8795192Ssaidi@eecs.umich.edu''')
8805522Snate@binkert.org
8815522Snate@binkert.org    code.write(str(target[0]))
8825522Snate@binkert.org
8835522Snate@binkert.orgfor name,flag in sorted(debug_flags.iteritems()):
8845522Snate@binkert.org    n, compound, desc = flag
8855522Snate@binkert.org    assert n == name
8865522Snate@binkert.org
8875522Snate@binkert.org    hh_file = 'debug/%s.hh' % name
8885522Snate@binkert.org    env.Command(hh_file, Value(flag),
8895522Snate@binkert.org                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
8905517Snate@binkert.org
8915522Snate@binkert.orgenv.Command('debug/flags.cc', Value(debug_flags),
8925522Snate@binkert.org            MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
8935517Snate@binkert.orgSource('debug/flags.cc')
8946143Snate@binkert.org
8956727Ssteve.reinhardt@amd.com# version tags
8965522Snate@binkert.orgtags = \
8975522Snate@binkert.orgenv.Command('sim/tags.cc', None,
8985522Snate@binkert.org            MakeAction('util/cpt_upgrader.py --get-cc-file > $TARGET',
8995517Snate@binkert.org                       Transform("VER TAGS")))
9005522Snate@binkert.orgenv.AlwaysBuild(tags)
9015522Snate@binkert.org
9025522Snate@binkert.org# Embed python files.  All .py files that have been indicated by a
9035522Snate@binkert.org# PySource() call in a SConscript need to be embedded into the M5
9045522Snate@binkert.org# library.  To do that, we compile the file to byte code, marshal the
9055522Snate@binkert.org# byte code, compress it, and then generate a c++ file that
9065522Snate@binkert.org# inserts the result into an array.
9075522Snate@binkert.orgdef embedPyFile(target, source, env):
9085522Snate@binkert.org    def c_str(string):
9095522Snate@binkert.org        if string is None:
9105522Snate@binkert.org            return "0"
9115522Snate@binkert.org        return '"%s"' % string
9125522Snate@binkert.org
9135522Snate@binkert.org    '''Action function to compile a .py into a code object, marshal
9145522Snate@binkert.org    it, compress it, and stick it into an asm file so the code appears
9155522Snate@binkert.org    as just bytes with a label in the data section'''
9165522Snate@binkert.org
9175522Snate@binkert.org    src = file(str(source[0]), 'r').read()
9185522Snate@binkert.org
9196143Snate@binkert.org    pysource = PySource.tnodes[source[0]]
9205522Snate@binkert.org    compiled = compile(src, pysource.abspath, 'exec')
9215522Snate@binkert.org    marshalled = marshal.dumps(compiled)
9224382Sbinkertn@umich.edu    compressed = zlib.compress(marshalled)
9235522Snate@binkert.org    data = compressed
9245522Snate@binkert.org    sym = pysource.symname
9255522Snate@binkert.org
9265522Snate@binkert.org    code = code_formatter()
9275522Snate@binkert.org    code('''\
9285522Snate@binkert.org#include "sim/init.hh"
9295522Snate@binkert.org
9304382Sbinkertn@umich.edunamespace {
9315522Snate@binkert.org
9326143Snate@binkert.orgconst uint8_t data_${sym}[] = {
9335522Snate@binkert.org''')
9345522Snate@binkert.org    code.indent()
9355522Snate@binkert.org    step = 16
9365522Snate@binkert.org    for i in xrange(0, len(data), step):
9375522Snate@binkert.org        x = array.array('B', data[i:i+step])
9385522Snate@binkert.org        code(''.join('%d,' % d for d in x))
9395522Snate@binkert.org    code.dedent()
9405522Snate@binkert.org
9415522Snate@binkert.org    code('''};
9425522Snate@binkert.org
9435522Snate@binkert.orgEmbeddedPython embedded_${sym}(
9445522Snate@binkert.org    ${{c_str(pysource.arcname)}},
9455522Snate@binkert.org    ${{c_str(pysource.abspath)}},
9465522Snate@binkert.org    ${{c_str(pysource.modpath)}},
9475522Snate@binkert.org    data_${sym},
9485522Snate@binkert.org    ${{len(data)}},
9495522Snate@binkert.org    ${{len(marshalled)}});
9505522Snate@binkert.org
9515522Snate@binkert.org} // anonymous namespace
9525522Snate@binkert.org''')
9535522Snate@binkert.org    code.write(str(target[0]))
9545522Snate@binkert.org
9555522Snate@binkert.orgfor source in PySource.all:
9565522Snate@binkert.org    env.Command(source.cpp, source.tnode,
9575522Snate@binkert.org                MakeAction(embedPyFile, Transform("EMBED PY")))
9585522Snate@binkert.org    Source(source.cpp, tags=source.tags, add_tags='python')
9596143Snate@binkert.org
9606143Snate@binkert.org########################################################################
9616143Snate@binkert.org#
9626143Snate@binkert.org# Define binaries.  Each different build type (debug, opt, etc.) gets
9635522Snate@binkert.org# a slightly different build environment.
9644382Sbinkertn@umich.edu#
9654382Sbinkertn@umich.edu
9664382Sbinkertn@umich.edu# List of constructed environments to pass back to SConstruct
9674382Sbinkertn@umich.edudate_source = Source('base/date.cc', tags=[])
9684382Sbinkertn@umich.edu
9694382Sbinkertn@umich.edu# Function to create a new build environment as clone of current
9704382Sbinkertn@umich.edu# environment 'env' with modified object suffix and optional stripped
9714382Sbinkertn@umich.edu# binary.  Additional keyword arguments are appended to corresponding
9724382Sbinkertn@umich.edu# build environment vars.
9734382Sbinkertn@umich.edudef makeEnv(env, label, objsfx, strip=False, disable_partial=False, **kwargs):
9746143Snate@binkert.org    # SCons doesn't know to append a library suffix when there is a '.' in the
975955SN/A    # name.  Use '_' instead.
9762655Sstever@eecs.umich.edu    libname = 'gem5_' + label
9772655Sstever@eecs.umich.edu    exename = 'gem5.' + label
9782655Sstever@eecs.umich.edu    secondary_exename = 'm5.' + label
9792655Sstever@eecs.umich.edu
9802655Sstever@eecs.umich.edu    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
9815601Snate@binkert.org    new_env.Label = label
9825601Snate@binkert.org    new_env.Append(**kwargs)
9835601Snate@binkert.org
9845601Snate@binkert.org    lib_sources = Source.all.with_tag('gem5 lib')
9855522Snate@binkert.org
9865863Snate@binkert.org    # Without Python, leave out all Python content from the library
9875601Snate@binkert.org    # builds.  The option doesn't affect gem5 built as a program
9885601Snate@binkert.org    if GetOption('without_python'):
9895601Snate@binkert.org        lib_sources = lib_sources.without_tag('python')
9905863Snate@binkert.org
9916143Snate@binkert.org    static_objs = []
9925559Snate@binkert.org    shared_objs = []
9935559Snate@binkert.org
9945559Snate@binkert.org    for s in lib_sources.with_tag(Source.ungrouped_tag):
9955559Snate@binkert.org        static_objs.append(s.static(new_env))
9965601Snate@binkert.org        shared_objs.append(s.shared(new_env))
9976143Snate@binkert.org
9986143Snate@binkert.org    for group in Source.source_groups:
9996143Snate@binkert.org        srcs = lib_sources.with_tag(Source.link_group_tag(group))
10006143Snate@binkert.org        if not srcs:
10016143Snate@binkert.org            continue
10026143Snate@binkert.org
10036143Snate@binkert.org        group_static = [ s.static(new_env) for s in srcs ]
10046143Snate@binkert.org        group_shared = [ s.shared(new_env) for s in srcs ]
10056143Snate@binkert.org
10066143Snate@binkert.org        # If partial linking is disabled, add these sources to the build
10076143Snate@binkert.org        # directly, and short circuit this loop.
10086143Snate@binkert.org        if disable_partial:
10096143Snate@binkert.org            static_objs.extend(group_static)
10106143Snate@binkert.org            shared_objs.extend(group_shared)
10116143Snate@binkert.org            continue
10126143Snate@binkert.org
10136143Snate@binkert.org        # Set up the static partially linked objects.
10146143Snate@binkert.org        file_name = new_env.subst("${OBJPREFIX}lib${OBJSUFFIX}.partial")
10156143Snate@binkert.org        target = File(joinpath(group, file_name))
10166143Snate@binkert.org        partial = env.PartialStatic(target=target, source=group_static)
10176143Snate@binkert.org        static_objs.extend(partial)
10186143Snate@binkert.org
10196143Snate@binkert.org        # Set up the shared partially linked objects.
10206143Snate@binkert.org        file_name = new_env.subst("${SHOBJPREFIX}lib${SHOBJSUFFIX}.partial")
10216143Snate@binkert.org        target = File(joinpath(group, file_name))
10226143Snate@binkert.org        partial = env.PartialShared(target=target, source=group_shared)
10236143Snate@binkert.org        shared_objs.extend(partial)
10246143Snate@binkert.org
10256143Snate@binkert.org    static_date = date_source.static(new_env)
10266143Snate@binkert.org    new_env.Depends(static_date, static_objs)
10276143Snate@binkert.org    static_objs.extend(static_date)
10286143Snate@binkert.org
10296240Snate@binkert.org    shared_date = date_source.shared(new_env)
10305554Snate@binkert.org    new_env.Depends(shared_date, shared_objs)
10315522Snate@binkert.org    shared_objs.extend(shared_date)
10325522Snate@binkert.org
10335797Snate@binkert.org    # First make a library of everything but main() so other programs can
10345797Snate@binkert.org    # link against m5.
10355522Snate@binkert.org    static_lib = new_env.StaticLibrary(libname, static_objs)
10365584Snate@binkert.org    shared_lib = new_env.SharedLibrary(libname, shared_objs)
10376143Snate@binkert.org
10385862Snate@binkert.org    # Now link a stub with main() and the static library.
10395584Snate@binkert.org    main_objs = [ s.static(new_env) for s in Source.all.with_tag('main') ]
10405601Snate@binkert.org
10416143Snate@binkert.org    for test in UnitTest.all:
10426143Snate@binkert.org        test_sources = Source.all.with_tag(str(test.target))
10432655Sstever@eecs.umich.edu        test_objs = [ s.static(new_env) for s in test_sources ]
10446143Snate@binkert.org        if test.main:
10456143Snate@binkert.org            test_objs += main_objs
10466143Snate@binkert.org        path = 'unittest/%s.%s' % (test.target, label)
10476143Snate@binkert.org        new_env.Program(path, test_objs + static_objs)
10486143Snate@binkert.org
10494007Ssaidi@eecs.umich.edu    gtest_env = new_env.Clone()
10504596Sbinkertn@umich.edu    gtest_env.Append(LIBS=gtest_env['GTEST_LIBS'])
10514007Ssaidi@eecs.umich.edu    gtest_env.Append(CPPFLAGS=gtest_env['GTEST_CPPFLAGS'])
10524596Sbinkertn@umich.edu    for test in GTest.all:
10536143Snate@binkert.org        test_sources = Source.all.with_tag(str(test.target))
10545522Snate@binkert.org        test_objs = [ s.static(gtest_env) for s in test_sources ]
10555601Snate@binkert.org        gtest_env.Program(test.dir.File('%s.%s' % (test.target, label)),
10565601Snate@binkert.org                          test_objs)
10572655Sstever@eecs.umich.edu
1058955SN/A    progname = exename
10593918Ssaidi@eecs.umich.edu    if strip:
10603918Ssaidi@eecs.umich.edu        progname += '.unstripped'
10613918Ssaidi@eecs.umich.edu
10623918Ssaidi@eecs.umich.edu    targets = new_env.Program(progname, main_objs + static_objs)
10633918Ssaidi@eecs.umich.edu
10643918Ssaidi@eecs.umich.edu    if strip:
10653918Ssaidi@eecs.umich.edu        if sys.platform == 'sunos5':
10663918Ssaidi@eecs.umich.edu            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
10673918Ssaidi@eecs.umich.edu        else:
10683918Ssaidi@eecs.umich.edu            cmd = 'strip $SOURCE -o $TARGET'
10693918Ssaidi@eecs.umich.edu        targets = new_env.Command(exename, progname,
10703918Ssaidi@eecs.umich.edu                    MakeAction(cmd, Transform("STRIP")))
10713918Ssaidi@eecs.umich.edu
10723918Ssaidi@eecs.umich.edu    new_env.Command(secondary_exename, exename,
10733940Ssaidi@eecs.umich.edu            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
10743940Ssaidi@eecs.umich.edu
10753940Ssaidi@eecs.umich.edu    new_env.M5Binary = targets[0]
10763942Ssaidi@eecs.umich.edu
10773940Ssaidi@eecs.umich.edu    # Set up regression tests.
10783515Ssaidi@eecs.umich.edu    SConscript(os.path.join(env.root.abspath, 'tests', 'SConscript'),
10793918Ssaidi@eecs.umich.edu               variant_dir=Dir('tests').Dir(new_env.Label),
10804762Snate@binkert.org               exports={ 'env' : new_env }, duplicate=False)
10813515Ssaidi@eecs.umich.edu
10822655Sstever@eecs.umich.edu# Start out with the compiler flags common to all compilers,
10833918Ssaidi@eecs.umich.edu# i.e. they all use -g for opt and -g -pg for prof
10843619Sbinkertn@umich.educcflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
1085955SN/A           'perf' : ['-g']}
1086955SN/A
10872655Sstever@eecs.umich.edu# Start out with the linker flags common to all linkers, i.e. -pg for
10883918Ssaidi@eecs.umich.edu# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
10893619Sbinkertn@umich.edu# no-as-needed and as-needed as the binutils linker is too clever and
1090955SN/A# simply doesn't link to the library otherwise.
1091955SN/Aldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
10922655Sstever@eecs.umich.edu           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
10933918Ssaidi@eecs.umich.edu
10943619Sbinkertn@umich.edu# For Link Time Optimization, the optimisation flags used to compile
1095955SN/A# individual files are decoupled from those used at link time
1096955SN/A# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
10972655Sstever@eecs.umich.edu# to also update the linker flags based on the target.
10983918Ssaidi@eecs.umich.eduif env['GCC']:
10993683Sstever@eecs.umich.edu    if sys.platform == 'sunos5':
11002655Sstever@eecs.umich.edu        ccflags['debug'] += ['-gstabs+']
11011869SN/A    else:
11021869SN/A        ccflags['debug'] += ['-ggdb3']
1103    ldflags['debug'] += ['-O0']
1104    # opt, fast, prof and perf all share the same cc flags, also add
1105    # the optimization to the ldflags as LTO defers the optimization
1106    # to link time
1107    for target in ['opt', 'fast', 'prof', 'perf']:
1108        ccflags[target] += ['-O3']
1109        ldflags[target] += ['-O3']
1110
1111    ccflags['fast'] += env['LTO_CCFLAGS']
1112    ldflags['fast'] += env['LTO_LDFLAGS']
1113elif env['CLANG']:
1114    ccflags['debug'] += ['-g', '-O0']
1115    # opt, fast, prof and perf all share the same cc flags
1116    for target in ['opt', 'fast', 'prof', 'perf']:
1117        ccflags[target] += ['-O3']
1118else:
1119    print 'Unknown compiler, please fix compiler options'
1120    Exit(1)
1121
1122
1123# To speed things up, we only instantiate the build environments we
1124# need.  We try to identify the needed environment for each target; if
1125# we can't, we fall back on instantiating all the environments just to
1126# be safe.
1127target_types = ['debug', 'opt', 'fast', 'prof', 'perf']
1128obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
1129              'gpo' : 'perf'}
1130
1131def identifyTarget(t):
1132    ext = t.split('.')[-1]
1133    if ext in target_types:
1134        return ext
1135    if obj2target.has_key(ext):
1136        return obj2target[ext]
1137    match = re.search(r'/tests/([^/]+)/', t)
1138    if match and match.group(1) in target_types:
1139        return match.group(1)
1140    return 'all'
1141
1142needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
1143if 'all' in needed_envs:
1144    needed_envs += target_types
1145
1146# Debug binary
1147if 'debug' in needed_envs:
1148    makeEnv(env, 'debug', '.do',
1149            CCFLAGS = Split(ccflags['debug']),
1150            CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
1151            LINKFLAGS = Split(ldflags['debug']))
1152
1153# Optimized binary
1154if 'opt' in needed_envs:
1155    makeEnv(env, 'opt', '.o',
1156            CCFLAGS = Split(ccflags['opt']),
1157            CPPDEFINES = ['TRACING_ON=1'],
1158            LINKFLAGS = Split(ldflags['opt']))
1159
1160# "Fast" binary
1161if 'fast' in needed_envs:
1162    disable_partial = \
1163            env.get('BROKEN_INCREMENTAL_LTO', False) and \
1164            GetOption('force_lto')
1165    makeEnv(env, 'fast', '.fo', strip = True,
1166            CCFLAGS = Split(ccflags['fast']),
1167            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1168            LINKFLAGS = Split(ldflags['fast']),
1169            disable_partial=disable_partial)
1170
1171# Profiled binary using gprof
1172if 'prof' in needed_envs:
1173    makeEnv(env, 'prof', '.po',
1174            CCFLAGS = Split(ccflags['prof']),
1175            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1176            LINKFLAGS = Split(ldflags['prof']))
1177
1178# Profiled binary using google-pprof
1179if 'perf' in needed_envs:
1180    makeEnv(env, 'perf', '.gpo',
1181            CCFLAGS = Split(ccflags['perf']),
1182            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1183            LINKFLAGS = Split(ldflags['perf']))
1184