SConscript revision 9419:54d5c0e5852a
1955SN/A# -*- mode:python -*-
2955SN/A
35871Snate@binkert.org# Copyright (c) 2004-2005 The Regents of The University of Michigan
41762SN/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.
28955SN/A#
292665Ssaidi@eecs.umich.edu# Authors: Nathan Binkert
302665Ssaidi@eecs.umich.edu
315863Snate@binkert.orgimport array
32955SN/Aimport bisect
33955SN/Aimport imp
34955SN/Aimport marshal
35955SN/Aimport os
36955SN/Aimport re
372632Sstever@eecs.umich.eduimport sys
382632Sstever@eecs.umich.eduimport zlib
392632Sstever@eecs.umich.edu
402632Sstever@eecs.umich.edufrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
41955SN/A
422632Sstever@eecs.umich.eduimport SCons
432632Sstever@eecs.umich.edu
442761Sstever@eecs.umich.edu# This file defines how to build a particular configuration of gem5
452632Sstever@eecs.umich.edu# based on variable settings in the 'env' build environment.
462632Sstever@eecs.umich.edu
472632Sstever@eecs.umich.eduImport('*')
482761Sstever@eecs.umich.edu
492761Sstever@eecs.umich.edu# Children need to see the environment
502761Sstever@eecs.umich.eduExport('env')
512632Sstever@eecs.umich.edu
522632Sstever@eecs.umich.edubuild_env = [(opt, env[opt]) for opt in export_vars]
532761Sstever@eecs.umich.edu
542761Sstever@eecs.umich.edufrom m5.util import code_formatter, compareVersions
552761Sstever@eecs.umich.edu
562761Sstever@eecs.umich.edu########################################################################
572761Sstever@eecs.umich.edu# Code for adding source files of various types
582632Sstever@eecs.umich.edu#
592632Sstever@eecs.umich.edu# When specifying a source file of some type, a set of guards can be
602632Sstever@eecs.umich.edu# specified for that file.  When get() is used to find the files, if
612632Sstever@eecs.umich.edu# get specifies a set of filters, only files that match those filters
622632Sstever@eecs.umich.edu# will be accepted (unspecified filters on files are assumed to be
632632Sstever@eecs.umich.edu# false).  Current filters are:
642632Sstever@eecs.umich.edu#     main -- specifies the gem5 main() function
65955SN/A#     skip_lib -- do not put this file into the gem5 library
66955SN/A#     <unittest> -- unit tests use filters based on the unit test name
67955SN/A#
685863Snate@binkert.org# A parent can now be specified for a source file and default filter
695863Snate@binkert.org# values will be retrieved recursively from parents (children override
705863Snate@binkert.org# parents).
715863Snate@binkert.org#
725863Snate@binkert.orgclass SourceMeta(type):
735863Snate@binkert.org    '''Meta class for source files that keeps track of all files of a
745863Snate@binkert.org    particular type and has a get function for finding all functions
755863Snate@binkert.org    of a certain type that match a set of guards'''
765863Snate@binkert.org    def __init__(cls, name, bases, dict):
775863Snate@binkert.org        super(SourceMeta, cls).__init__(name, bases, dict)
785863Snate@binkert.org        cls.all = []
795863Snate@binkert.org        
805863Snate@binkert.org    def get(cls, **guards):
815863Snate@binkert.org        '''Find all files that match the specified guards.  If a source
825863Snate@binkert.org        file does not specify a flag, the default is False'''
835863Snate@binkert.org        for src in cls.all:
845863Snate@binkert.org            for flag,value in guards.iteritems():
855863Snate@binkert.org                # if the flag is found and has a different value, skip
865863Snate@binkert.org                # this file
875863Snate@binkert.org                if src.all_guards.get(flag, False) != value:
885863Snate@binkert.org                    break
895863Snate@binkert.org            else:
905863Snate@binkert.org                yield src
915863Snate@binkert.org
925863Snate@binkert.orgclass SourceFile(object):
935863Snate@binkert.org    '''Base object that encapsulates the notion of a source file.
945863Snate@binkert.org    This includes, the source node, target node, various manipulations
955863Snate@binkert.org    of those.  A source file also specifies a set of guards which
965863Snate@binkert.org    describing which builds the source file applies to.  A parent can
975863Snate@binkert.org    also be specified to get default guards from'''
985863Snate@binkert.org    __metaclass__ = SourceMeta
99955SN/A    def __init__(self, source, parent=None, **guards):
1005396Ssaidi@eecs.umich.edu        self.guards = guards
1015863Snate@binkert.org        self.parent = parent
1025863Snate@binkert.org
1034202Sbinkertn@umich.edu        tnode = source
1045863Snate@binkert.org        if not isinstance(source, SCons.Node.FS.File):
1055863Snate@binkert.org            tnode = File(source)
1065863Snate@binkert.org
1075863Snate@binkert.org        self.tnode = tnode
108955SN/A        self.snode = tnode.srcnode()
1095273Sstever@gmail.com
1105871Snate@binkert.org        for base in type(self).__mro__:
1115273Sstever@gmail.com            if issubclass(base, SourceFile):
1125871Snate@binkert.org                base.all.append(self)
1135863Snate@binkert.org
1145863Snate@binkert.org    @property
1155863Snate@binkert.org    def filename(self):
1165871Snate@binkert.org        return str(self.tnode)
1175872Snate@binkert.org
1185872Snate@binkert.org    @property
1195872Snate@binkert.org    def dirname(self):
1205871Snate@binkert.org        return dirname(self.filename)
1215871Snate@binkert.org
1225871Snate@binkert.org    @property
1235871Snate@binkert.org    def basename(self):
1245871Snate@binkert.org        return basename(self.filename)
1255871Snate@binkert.org
1265871Snate@binkert.org    @property
1275871Snate@binkert.org    def extname(self):
1285871Snate@binkert.org        index = self.basename.rfind('.')
1295871Snate@binkert.org        if index <= 0:
1305871Snate@binkert.org            # dot files aren't extensions
1315871Snate@binkert.org            return self.basename, None
1325871Snate@binkert.org
1335871Snate@binkert.org        return self.basename[:index], self.basename[index+1:]
1345863Snate@binkert.org
1355227Ssaidi@eecs.umich.edu    @property
1365396Ssaidi@eecs.umich.edu    def all_guards(self):
1375396Ssaidi@eecs.umich.edu        '''find all guards for this object getting default values
1385396Ssaidi@eecs.umich.edu        recursively from its parents'''
1395396Ssaidi@eecs.umich.edu        guards = {}
1405396Ssaidi@eecs.umich.edu        if self.parent:
1415396Ssaidi@eecs.umich.edu            guards.update(self.parent.guards)
1425396Ssaidi@eecs.umich.edu        guards.update(self.guards)
1435396Ssaidi@eecs.umich.edu        return guards
1445588Ssaidi@eecs.umich.edu
1455396Ssaidi@eecs.umich.edu    def __lt__(self, other): return self.filename < other.filename
1465396Ssaidi@eecs.umich.edu    def __le__(self, other): return self.filename <= other.filename
1475396Ssaidi@eecs.umich.edu    def __gt__(self, other): return self.filename > other.filename
1485396Ssaidi@eecs.umich.edu    def __ge__(self, other): return self.filename >= other.filename
1495396Ssaidi@eecs.umich.edu    def __eq__(self, other): return self.filename == other.filename
1505396Ssaidi@eecs.umich.edu    def __ne__(self, other): return self.filename != other.filename
1515396Ssaidi@eecs.umich.edu        
1525396Ssaidi@eecs.umich.educlass Source(SourceFile):
1535396Ssaidi@eecs.umich.edu    '''Add a c/c++ source file to the build'''
1545396Ssaidi@eecs.umich.edu    def __init__(self, source, Werror=True, swig=False, **guards):
1555396Ssaidi@eecs.umich.edu        '''specify the source file, and any guards'''
1565396Ssaidi@eecs.umich.edu        super(Source, self).__init__(source, **guards)
1575396Ssaidi@eecs.umich.edu
1585396Ssaidi@eecs.umich.edu        self.Werror = Werror
1595871Snate@binkert.org        self.swig = swig
1605871Snate@binkert.org
1615871Snate@binkert.orgclass PySource(SourceFile):
1625871Snate@binkert.org    '''Add a python source file to the named package'''
1635871Snate@binkert.org    invalid_sym_char = re.compile('[^A-z0-9_]')
1645871Snate@binkert.org    modules = {}
165955SN/A    tnodes = {}
1665871Snate@binkert.org    symnames = {}
1675871Snate@binkert.org    
1685871Snate@binkert.org    def __init__(self, package, source, **guards):
1695871Snate@binkert.org        '''specify the python package, the source file, and any guards'''
170955SN/A        super(PySource, self).__init__(source, **guards)
1715871Snate@binkert.org
1725871Snate@binkert.org        modname,ext = self.extname
1735871Snate@binkert.org        assert ext == 'py'
1741533SN/A
1755871Snate@binkert.org        if package:
1765871Snate@binkert.org            path = package.split('.')
1775863Snate@binkert.org        else:
1785871Snate@binkert.org            path = []
1795871Snate@binkert.org
1805871Snate@binkert.org        modpath = path[:]
1815871Snate@binkert.org        if modname != '__init__':
1825871Snate@binkert.org            modpath += [ modname ]
1835863Snate@binkert.org        modpath = '.'.join(modpath)
1845871Snate@binkert.org
1855863Snate@binkert.org        arcpath = path + [ self.basename ]
1865871Snate@binkert.org        abspath = self.snode.abspath
1874678Snate@binkert.org        if not exists(abspath):
1884678Snate@binkert.org            abspath = self.tnode.abspath
1894678Snate@binkert.org
1904678Snate@binkert.org        self.package = package
1914678Snate@binkert.org        self.modname = modname
1924678Snate@binkert.org        self.modpath = modpath
1934678Snate@binkert.org        self.arcname = joinpath(*arcpath)
1944678Snate@binkert.org        self.abspath = abspath
1954678Snate@binkert.org        self.compiled = File(self.filename + 'c')
1964678Snate@binkert.org        self.cpp = File(self.filename + '.cc')
1974678Snate@binkert.org        self.symname = PySource.invalid_sym_char.sub('_', modpath)
1984678Snate@binkert.org
1995871Snate@binkert.org        PySource.modules[modpath] = self
2004678Snate@binkert.org        PySource.tnodes[self.tnode] = self
2015871Snate@binkert.org        PySource.symnames[self.symname] = self
2025871Snate@binkert.org
2035871Snate@binkert.orgclass SimObject(PySource):
2045871Snate@binkert.org    '''Add a SimObject python file as a python source object and add
2055871Snate@binkert.org    it to a list of sim object modules'''
2065871Snate@binkert.org
2075871Snate@binkert.org    fixed = False
2085871Snate@binkert.org    modnames = []
2095871Snate@binkert.org
2105871Snate@binkert.org    def __init__(self, source, **guards):
2115871Snate@binkert.org        '''Specify the source file and any guards (automatically in
2125871Snate@binkert.org        the m5.objects package)'''
2135871Snate@binkert.org        super(SimObject, self).__init__('m5.objects', source, **guards)
2145871Snate@binkert.org        if self.fixed:
2155871Snate@binkert.org            raise AttributeError, "Too late to call SimObject now."
2165871Snate@binkert.org
2174678Snate@binkert.org        bisect.insort_right(SimObject.modnames, self.modname)
2185871Snate@binkert.org
2195871Snate@binkert.orgclass SwigSource(SourceFile):
2205871Snate@binkert.org    '''Add a swig file to build'''
2215871Snate@binkert.org
2225871Snate@binkert.org    def __init__(self, package, source, **guards):
2235871Snate@binkert.org        '''Specify the python package, the source file, and any guards'''
2245871Snate@binkert.org        super(SwigSource, self).__init__(source, **guards)
2255871Snate@binkert.org
2265871Snate@binkert.org        modname,ext = self.extname
2275871Snate@binkert.org        assert ext == 'i'
2285871Snate@binkert.org
2295871Snate@binkert.org        self.module = modname
2305871Snate@binkert.org        cc_file = joinpath(self.dirname, modname + '_wrap.cc')
2314678Snate@binkert.org        py_file = joinpath(self.dirname, modname + '.py')
2325871Snate@binkert.org
2334678Snate@binkert.org        self.cc_source = Source(cc_file, swig=True, parent=self)
2345871Snate@binkert.org        self.py_source = PySource(package, py_file, parent=self)
2355871Snate@binkert.org
2365871Snate@binkert.orgclass ProtoBuf(SourceFile):
2375871Snate@binkert.org    '''Add a Protocol Buffer to build'''
2385871Snate@binkert.org
2395871Snate@binkert.org    def __init__(self, source, **guards):
2405871Snate@binkert.org        '''Specify the source file, and any guards'''
2415871Snate@binkert.org        super(ProtoBuf, self).__init__(source, **guards)
2425871Snate@binkert.org
2435863Snate@binkert.org        # Get the file name and the extension
244955SN/A        modname,ext = self.extname
245955SN/A        assert ext == 'proto'
2462632Sstever@eecs.umich.edu
2472632Sstever@eecs.umich.edu        # Currently, we stick to generating the C++ headers, so we
248955SN/A        # only need to track the source and header.
249955SN/A        self.cc_file = File(joinpath(self.dirname, modname + '.pb.cc'))
250955SN/A        self.hh_file = File(joinpath(self.dirname, modname + '.pb.h'))
251955SN/A
2525863Snate@binkert.orgclass UnitTest(object):
253955SN/A    '''Create a UnitTest'''
2542632Sstever@eecs.umich.edu
2552632Sstever@eecs.umich.edu    all = []
2562632Sstever@eecs.umich.edu    def __init__(self, target, *sources, **kwargs):
2572632Sstever@eecs.umich.edu        '''Specify the target name and any sources.  Sources that are
2582632Sstever@eecs.umich.edu        not SourceFiles are evalued with Source().  All files are
2592632Sstever@eecs.umich.edu        guarded with a guard of the same name as the UnitTest
2602632Sstever@eecs.umich.edu        target.'''
2612632Sstever@eecs.umich.edu
2622632Sstever@eecs.umich.edu        srcs = []
2632632Sstever@eecs.umich.edu        for src in sources:
2642632Sstever@eecs.umich.edu            if not isinstance(src, SourceFile):
2652632Sstever@eecs.umich.edu                src = Source(src, skip_lib=True)
2662632Sstever@eecs.umich.edu            src.guards[target] = True
2673718Sstever@eecs.umich.edu            srcs.append(src)
2683718Sstever@eecs.umich.edu
2693718Sstever@eecs.umich.edu        self.sources = srcs
2703718Sstever@eecs.umich.edu        self.target = target
2713718Sstever@eecs.umich.edu        self.main = kwargs.get('main', False)
2725863Snate@binkert.org        UnitTest.all.append(self)
2735863Snate@binkert.org
2743718Sstever@eecs.umich.edu# Children should have access
2753718Sstever@eecs.umich.eduExport('Source')
2765863Snate@binkert.orgExport('PySource')
2775863Snate@binkert.orgExport('SimObject')
2783718Sstever@eecs.umich.eduExport('SwigSource')
2793718Sstever@eecs.umich.eduExport('ProtoBuf')
2802634Sstever@eecs.umich.eduExport('UnitTest')
2812634Sstever@eecs.umich.edu
2825863Snate@binkert.org########################################################################
2832638Sstever@eecs.umich.edu#
2842632Sstever@eecs.umich.edu# Debug Flags
2852632Sstever@eecs.umich.edu#
2862632Sstever@eecs.umich.edudebug_flags = {}
2872632Sstever@eecs.umich.edudef DebugFlag(name, desc=None):
2882632Sstever@eecs.umich.edu    if name in debug_flags:
2892632Sstever@eecs.umich.edu        raise AttributeError, "Flag %s already specified" % name
2901858SN/A    debug_flags[name] = (name, (), desc)
2913716Sstever@eecs.umich.edu
2922638Sstever@eecs.umich.edudef CompoundFlag(name, flags, desc=None):
2932638Sstever@eecs.umich.edu    if name in debug_flags:
2942638Sstever@eecs.umich.edu        raise AttributeError, "Flag %s already specified" % name
2952638Sstever@eecs.umich.edu
2962638Sstever@eecs.umich.edu    compound = tuple(flags)
2972638Sstever@eecs.umich.edu    debug_flags[name] = (name, compound, desc)
2982638Sstever@eecs.umich.edu
2995863Snate@binkert.orgExport('DebugFlag')
3005863Snate@binkert.orgExport('CompoundFlag')
3015863Snate@binkert.org
302955SN/A########################################################################
3035341Sstever@gmail.com#
3045341Sstever@gmail.com# Set some compiler variables
3055863Snate@binkert.org#
3065341Sstever@gmail.com
3074494Ssaidi@eecs.umich.edu# Include file paths are rooted in this directory.  SCons will
3084494Ssaidi@eecs.umich.edu# automatically expand '.' to refer to both the source directory and
3095863Snate@binkert.org# the corresponding build directory to pick up generated include
3101105SN/A# files.
3112667Sstever@eecs.umich.eduenv.Append(CPPPATH=Dir('.'))
3122667Sstever@eecs.umich.edu
3132667Sstever@eecs.umich.edufor extra_dir in extras_dir_list:
3142667Sstever@eecs.umich.edu    env.Append(CPPPATH=Dir(extra_dir))
3152667Sstever@eecs.umich.edu
3162667Sstever@eecs.umich.edu# Workaround for bug in SCons version > 0.97d20071212
3175341Sstever@gmail.com# Scons bug id: 2006 gem5 Bug id: 308
3185863Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
3195341Sstever@gmail.com    Dir(root[len(base_dir) + 1:])
3205341Sstever@gmail.com
3215341Sstever@gmail.com########################################################################
3225863Snate@binkert.org#
3235341Sstever@gmail.com# Walk the tree and execute all SConscripts in subdirectories
3245341Sstever@gmail.com#
3255341Sstever@gmail.com
3265863Snate@binkert.orghere = Dir('.').srcnode().abspath
3275341Sstever@gmail.comfor root, dirs, files in os.walk(base_dir, topdown=True):
3285341Sstever@gmail.com    if root == here:
3295341Sstever@gmail.com        # we don't want to recurse back into this SConscript
3305341Sstever@gmail.com        continue
3315341Sstever@gmail.com
3325341Sstever@gmail.com    if 'SConscript' in files:
3335341Sstever@gmail.com        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
3345341Sstever@gmail.com        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3355341Sstever@gmail.com
3365341Sstever@gmail.comfor extra_dir in extras_dir_list:
3375863Snate@binkert.org    prefix_len = len(dirname(extra_dir)) + 1
3385341Sstever@gmail.com    for root, dirs, files in os.walk(extra_dir, topdown=True):
3395863Snate@binkert.org        # if build lives in the extras directory, don't walk down it
3405341Sstever@gmail.com        if 'build' in dirs:
3415863Snate@binkert.org            dirs.remove('build')
3425863Snate@binkert.org
3435863Snate@binkert.org        if 'SConscript' in files:
3445397Ssaidi@eecs.umich.edu            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
3455397Ssaidi@eecs.umich.edu            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3465341Sstever@gmail.com
3475341Sstever@gmail.comfor opt in export_vars:
3485341Sstever@gmail.com    env.ConfigFile(opt)
3495341Sstever@gmail.com
3505341Sstever@gmail.comdef makeTheISA(source, target, env):
3515341Sstever@gmail.com    isas = [ src.get_contents() for src in source ]
3525341Sstever@gmail.com    target_isa = env['TARGET_ISA']
3535341Sstever@gmail.com    def define(isa):
3545863Snate@binkert.org        return isa.upper() + '_ISA'
3555341Sstever@gmail.com    
3565341Sstever@gmail.com    def namespace(isa):
3575863Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA' 
3585341Sstever@gmail.com
3595863Snate@binkert.org
3605863Snate@binkert.org    code = code_formatter()
3615341Sstever@gmail.com    code('''\
3625863Snate@binkert.org#ifndef __CONFIG_THE_ISA_HH__
3635863Snate@binkert.org#define __CONFIG_THE_ISA_HH__
3645341Sstever@gmail.com
3655863Snate@binkert.org''')
3665341Sstever@gmail.com
3675871Snate@binkert.org    for i,isa in enumerate(isas):
3685341Sstever@gmail.com        code('#define $0 $1', define(isa), i + 1)
3695742Snate@binkert.org
3705742Snate@binkert.org    code('''
3715742Snate@binkert.org
3725341Sstever@gmail.com#define THE_ISA ${{define(target_isa)}}
3735742Snate@binkert.org#define TheISA ${{namespace(target_isa)}}
3745742Snate@binkert.org#define THE_ISA_STR "${{target_isa}}"
3755341Sstever@gmail.com
3762632Sstever@eecs.umich.edu#endif // __CONFIG_THE_ISA_HH__''')
3775199Sstever@gmail.com
3785871Snate@binkert.org    code.write(str(target[0]))
3795871Snate@binkert.org
3805871Snate@binkert.orgenv.Command('config/the_isa.hh', map(Value, all_isa_list),
3815871Snate@binkert.org            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
3825871Snate@binkert.org
3835871Snate@binkert.org########################################################################
3845871Snate@binkert.org#
3853942Ssaidi@eecs.umich.edu# Prevent any SimObjects from being added after this point, they
3863940Ssaidi@eecs.umich.edu# should all have been added in the SConscripts above
3873918Ssaidi@eecs.umich.edu#
3883918Ssaidi@eecs.umich.eduSimObject.fixed = True
3891858SN/A
3903918Ssaidi@eecs.umich.educlass DictImporter(object):
3913918Ssaidi@eecs.umich.edu    '''This importer takes a dictionary of arbitrary module names that
3923918Ssaidi@eecs.umich.edu    map to arbitrary filenames.'''
3933918Ssaidi@eecs.umich.edu    def __init__(self, modules):
3945571Snate@binkert.org        self.modules = modules
3953940Ssaidi@eecs.umich.edu        self.installed = set()
3963940Ssaidi@eecs.umich.edu
3973918Ssaidi@eecs.umich.edu    def __del__(self):
3983918Ssaidi@eecs.umich.edu        self.unload()
3993918Ssaidi@eecs.umich.edu
4003918Ssaidi@eecs.umich.edu    def unload(self):
4013918Ssaidi@eecs.umich.edu        import sys
4023918Ssaidi@eecs.umich.edu        for module in self.installed:
4035871Snate@binkert.org            del sys.modules[module]
4043918Ssaidi@eecs.umich.edu        self.installed = set()
4053918Ssaidi@eecs.umich.edu
4063940Ssaidi@eecs.umich.edu    def find_module(self, fullname, path):
4073918Ssaidi@eecs.umich.edu        if fullname == 'm5.defines':
4083918Ssaidi@eecs.umich.edu            return self
4095397Ssaidi@eecs.umich.edu
4105397Ssaidi@eecs.umich.edu        if fullname == 'm5.objects':
4115397Ssaidi@eecs.umich.edu            return self
4125708Ssaidi@eecs.umich.edu
4135708Ssaidi@eecs.umich.edu        if fullname.startswith('m5.internal'):
4145708Ssaidi@eecs.umich.edu            return None
4155708Ssaidi@eecs.umich.edu
4165708Ssaidi@eecs.umich.edu        source = self.modules.get(fullname, None)
4175397Ssaidi@eecs.umich.edu        if source is not None and fullname.startswith('m5.objects'):
4181851SN/A            return self
4191851SN/A
4201858SN/A        return None
4215200Sstever@gmail.com
422955SN/A    def load_module(self, fullname):
4233053Sstever@eecs.umich.edu        mod = imp.new_module(fullname)
4243053Sstever@eecs.umich.edu        sys.modules[fullname] = mod
4253053Sstever@eecs.umich.edu        self.installed.add(fullname)
4263053Sstever@eecs.umich.edu
4273053Sstever@eecs.umich.edu        mod.__loader__ = self
4283053Sstever@eecs.umich.edu        if fullname == 'm5.objects':
4293053Sstever@eecs.umich.edu            mod.__path__ = fullname.split('.')
4305871Snate@binkert.org            return mod
4313053Sstever@eecs.umich.edu
4324742Sstever@eecs.umich.edu        if fullname == 'm5.defines':
4334742Sstever@eecs.umich.edu            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
4343053Sstever@eecs.umich.edu            return mod
4353053Sstever@eecs.umich.edu
4363053Sstever@eecs.umich.edu        source = self.modules[fullname]
4373053Sstever@eecs.umich.edu        if source.modname == '__init__':
4383053Sstever@eecs.umich.edu            mod.__path__ = source.modpath
4393053Sstever@eecs.umich.edu        mod.__file__ = source.abspath
4403053Sstever@eecs.umich.edu
4413053Sstever@eecs.umich.edu        exec file(source.abspath, 'r') in mod.__dict__
4423053Sstever@eecs.umich.edu
4432667Sstever@eecs.umich.edu        return mod
4444554Sbinkertn@umich.edu
4454554Sbinkertn@umich.eduimport m5.SimObject
4462667Sstever@eecs.umich.eduimport m5.params
4474554Sbinkertn@umich.edufrom m5.util import code_formatter
4484554Sbinkertn@umich.edu
4494554Sbinkertn@umich.edum5.SimObject.clear()
4504554Sbinkertn@umich.edum5.params.clear()
4514554Sbinkertn@umich.edu
4524554Sbinkertn@umich.edu# install the python importer so we can grab stuff from the source
4534554Sbinkertn@umich.edu# tree itself.  We can't have SimObjects added after this point or
4544781Snate@binkert.org# else we won't know about them for the rest of the stuff.
4554554Sbinkertn@umich.eduimporter = DictImporter(PySource.modules)
4564554Sbinkertn@umich.edusys.meta_path[0:0] = [ importer ]
4572667Sstever@eecs.umich.edu
4584554Sbinkertn@umich.edu# import all sim objects so we can populate the all_objects list
4594554Sbinkertn@umich.edu# make sure that we're working with a list, then let's sort it
4604554Sbinkertn@umich.edufor modname in SimObject.modnames:
4614554Sbinkertn@umich.edu    exec('from m5.objects import %s' % modname)
4622667Sstever@eecs.umich.edu
4634554Sbinkertn@umich.edu# we need to unload all of the currently imported modules so that they
4642667Sstever@eecs.umich.edu# will be re-imported the next time the sconscript is run
4654554Sbinkertn@umich.eduimporter.unload()
4664554Sbinkertn@umich.edusys.meta_path.remove(importer)
4672667Sstever@eecs.umich.edu
4685522Snate@binkert.orgsim_objects = m5.SimObject.allClasses
4695522Snate@binkert.orgall_enums = m5.params.allEnums
4705522Snate@binkert.org
4715522Snate@binkert.orgif m5.SimObject.noCxxHeader:
4725522Snate@binkert.org    print >> sys.stderr, \
4735522Snate@binkert.org        "warning: At least one SimObject lacks a header specification. " \
4745522Snate@binkert.org        "This can cause unexpected results in the generated SWIG " \
4755522Snate@binkert.org        "wrappers."
4765522Snate@binkert.org
4775522Snate@binkert.org# Find param types that need to be explicitly wrapped with swig.
4785522Snate@binkert.org# These will be recognized because the ParamDesc will have a
4795522Snate@binkert.org# swig_decl() method.  Most param types are based on types that don't
4805522Snate@binkert.org# need this, either because they're based on native types (like Int)
4815522Snate@binkert.org# or because they're SimObjects (which get swigged independently).
4825522Snate@binkert.org# For now the only things handled here are VectorParam types.
4835522Snate@binkert.orgparams_to_swig = {}
4845522Snate@binkert.orgfor name,obj in sorted(sim_objects.iteritems()):
4855522Snate@binkert.org    for param in obj._params.local.values():
4865522Snate@binkert.org        # load the ptype attribute now because it depends on the
4875522Snate@binkert.org        # current version of SimObject.allClasses, but when scons
4885522Snate@binkert.org        # actually uses the value, all versions of
4895522Snate@binkert.org        # SimObject.allClasses will have been loaded
4905522Snate@binkert.org        param.ptype
4915522Snate@binkert.org
4925522Snate@binkert.org        if not hasattr(param, 'swig_decl'):
4935522Snate@binkert.org            continue
4942638Sstever@eecs.umich.edu        pname = param.ptype_str
4952638Sstever@eecs.umich.edu        if pname not in params_to_swig:
4962638Sstever@eecs.umich.edu            params_to_swig[pname] = param
4973716Sstever@eecs.umich.edu
4985522Snate@binkert.org########################################################################
4995522Snate@binkert.org#
5005522Snate@binkert.org# calculate extra dependencies
5015522Snate@binkert.org#
5025522Snate@binkert.orgmodule_depends = ["m5", "m5.SimObject", "m5.params"]
5035522Snate@binkert.orgdepends = [ PySource.modules[dep].snode for dep in module_depends ]
5041858SN/A
5055227Ssaidi@eecs.umich.edu########################################################################
5065227Ssaidi@eecs.umich.edu#
5075227Ssaidi@eecs.umich.edu# Commands for the basic automatically generated python files
5085227Ssaidi@eecs.umich.edu#
5095227Ssaidi@eecs.umich.edu
5105863Snate@binkert.org# Generate Python file containing a dict specifying the current
5115227Ssaidi@eecs.umich.edu# buildEnv flags.
5125227Ssaidi@eecs.umich.edudef makeDefinesPyFile(target, source, env):
5135227Ssaidi@eecs.umich.edu    build_env = source[0].get_contents()
5145227Ssaidi@eecs.umich.edu
5155227Ssaidi@eecs.umich.edu    code = code_formatter()
5165227Ssaidi@eecs.umich.edu    code("""
5175227Ssaidi@eecs.umich.eduimport m5.internal
5185204Sstever@gmail.comimport m5.util
5195204Sstever@gmail.com
5205204Sstever@gmail.combuildEnv = m5.util.SmartDict($build_env)
5215204Sstever@gmail.com
5225204Sstever@gmail.comcompileDate = m5.internal.core.compileDate
5235204Sstever@gmail.com_globals = globals()
5245204Sstever@gmail.comfor key,val in m5.internal.core.__dict__.iteritems():
5255204Sstever@gmail.com    if key.startswith('flag_'):
5265204Sstever@gmail.com        flag = key[5:]
5275204Sstever@gmail.com        _globals[flag] = val
5285204Sstever@gmail.comdel _globals
5295204Sstever@gmail.com""")
5305204Sstever@gmail.com    code.write(target[0].abspath)
5315204Sstever@gmail.com
5325204Sstever@gmail.comdefines_info = Value(build_env)
5335204Sstever@gmail.com# Generate a file with all of the compile options in it
5345204Sstever@gmail.comenv.Command('python/m5/defines.py', defines_info,
5355204Sstever@gmail.com            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
5365204Sstever@gmail.comPySource('m5', 'python/m5/defines.py')
5373118Sstever@eecs.umich.edu
5383118Sstever@eecs.umich.edu# Generate python file containing info about the M5 source code
5393118Sstever@eecs.umich.edudef makeInfoPyFile(target, source, env):
5403118Sstever@eecs.umich.edu    code = code_formatter()
5413118Sstever@eecs.umich.edu    for src in source:
5425863Snate@binkert.org        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
5433118Sstever@eecs.umich.edu        code('$src = ${{repr(data)}}')
5445863Snate@binkert.org    code.write(str(target[0]))
5453118Sstever@eecs.umich.edu
5465863Snate@binkert.org# Generate a file that wraps the basic top level files
5475863Snate@binkert.orgenv.Command('python/m5/info.py',
5485863Snate@binkert.org            [ '#/COPYING', '#/LICENSE', '#/README', ],
5495863Snate@binkert.org            MakeAction(makeInfoPyFile, Transform("INFO")))
5505863Snate@binkert.orgPySource('m5', 'python/m5/info.py')
5515863Snate@binkert.org
5525863Snate@binkert.org########################################################################
5535863Snate@binkert.org#
5545863Snate@binkert.org# Create all of the SimObject param headers and enum headers
5555863Snate@binkert.org#
5565863Snate@binkert.org
5575863Snate@binkert.orgdef createSimObjectParamStruct(target, source, env):
5585863Snate@binkert.org    assert len(target) == 1 and len(source) == 1
5595863Snate@binkert.org
5605863Snate@binkert.org    name = str(source[0].get_contents())
5615863Snate@binkert.org    obj = sim_objects[name]
5625863Snate@binkert.org
5635863Snate@binkert.org    code = code_formatter()
5645863Snate@binkert.org    obj.cxx_param_decl(code)
5655863Snate@binkert.org    code.write(target[0].abspath)
5665863Snate@binkert.org
5675863Snate@binkert.orgdef createParamSwigWrapper(target, source, env):
5685863Snate@binkert.org    assert len(target) == 1 and len(source) == 1
5695863Snate@binkert.org
5705863Snate@binkert.org    name = str(source[0].get_contents())
5713118Sstever@eecs.umich.edu    param = params_to_swig[name]
5725863Snate@binkert.org
5733118Sstever@eecs.umich.edu    code = code_formatter()
5743118Sstever@eecs.umich.edu    param.swig_decl(code)
5755863Snate@binkert.org    code.write(target[0].abspath)
5765863Snate@binkert.org
5775863Snate@binkert.orgdef createEnumStrings(target, source, env):
5785863Snate@binkert.org    assert len(target) == 1 and len(source) == 1
5795863Snate@binkert.org
5805863Snate@binkert.org    name = str(source[0].get_contents())
5813118Sstever@eecs.umich.edu    obj = all_enums[name]
5823483Ssaidi@eecs.umich.edu
5833494Ssaidi@eecs.umich.edu    code = code_formatter()
5843494Ssaidi@eecs.umich.edu    obj.cxx_def(code)
5853483Ssaidi@eecs.umich.edu    code.write(target[0].abspath)
5863483Ssaidi@eecs.umich.edu
5873483Ssaidi@eecs.umich.edudef createEnumDecls(target, source, env):
5883053Sstever@eecs.umich.edu    assert len(target) == 1 and len(source) == 1
5893053Sstever@eecs.umich.edu
5903918Ssaidi@eecs.umich.edu    name = str(source[0].get_contents())
5913053Sstever@eecs.umich.edu    obj = all_enums[name]
5923053Sstever@eecs.umich.edu
5933053Sstever@eecs.umich.edu    code = code_formatter()
5943053Sstever@eecs.umich.edu    obj.cxx_decl(code)
5953053Sstever@eecs.umich.edu    code.write(target[0].abspath)
5961858SN/A
5971858SN/Adef createEnumSwigWrapper(target, source, env):
5981858SN/A    assert len(target) == 1 and len(source) == 1
5991858SN/A
6001858SN/A    name = str(source[0].get_contents())
6011858SN/A    obj = all_enums[name]
6025863Snate@binkert.org
6035863Snate@binkert.org    code = code_formatter()
6041859SN/A    obj.swig_decl(code)
6055863Snate@binkert.org    code.write(target[0].abspath)
6061858SN/A
6075863Snate@binkert.orgdef createSimObjectSwigWrapper(target, source, env):
6081858SN/A    name = source[0].get_contents()
6091859SN/A    obj = sim_objects[name]
6101859SN/A
6115863Snate@binkert.org    code = code_formatter()
6123053Sstever@eecs.umich.edu    obj.swig_decl(code)
6133053Sstever@eecs.umich.edu    code.write(target[0].abspath)
6143053Sstever@eecs.umich.edu
6153053Sstever@eecs.umich.edu# Generate all of the SimObject param C++ struct header files
6161859SN/Aparams_hh_files = []
6171859SN/Afor name,simobj in sorted(sim_objects.iteritems()):
6181859SN/A    py_source = PySource.modules[simobj.__module__]
6191859SN/A    extra_deps = [ py_source.tnode ]
6201859SN/A
6211859SN/A    hh_file = File('params/%s.hh' % name)
6221859SN/A    params_hh_files.append(hh_file)
6231859SN/A    env.Command(hh_file, Value(name),
6241862SN/A                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
6251859SN/A    env.Depends(hh_file, depends + extra_deps)
6261859SN/A
6271859SN/A# Generate any needed param SWIG wrapper files
6285863Snate@binkert.orgparams_i_files = []
6295863Snate@binkert.orgfor name,param in params_to_swig.iteritems():
6305863Snate@binkert.org    i_file = File('python/m5/internal/%s.i' % (param.swig_module_name()))
6315863Snate@binkert.org    params_i_files.append(i_file)
6321858SN/A    env.Command(i_file, Value(name),
6331858SN/A                MakeAction(createParamSwigWrapper, Transform("SW PARAM")))
6345863Snate@binkert.org    env.Depends(i_file, depends)
6355863Snate@binkert.org    SwigSource('m5.internal', i_file)
6365863Snate@binkert.org
6375863Snate@binkert.org# Generate all enum header files
6385863Snate@binkert.orgfor name,enum in sorted(all_enums.iteritems()):
6395871Snate@binkert.org    py_source = PySource.modules[enum.__module__]
6405871Snate@binkert.org    extra_deps = [ py_source.tnode ]
6412139SN/A
6424202Sbinkertn@umich.edu    cc_file = File('enums/%s.cc' % name)
6434202Sbinkertn@umich.edu    env.Command(cc_file, Value(name),
6442139SN/A                MakeAction(createEnumStrings, Transform("ENUM STR")))
6452155SN/A    env.Depends(cc_file, depends + extra_deps)
6464202Sbinkertn@umich.edu    Source(cc_file)
6474202Sbinkertn@umich.edu
6484202Sbinkertn@umich.edu    hh_file = File('enums/%s.hh' % name)
6492155SN/A    env.Command(hh_file, Value(name),
6505863Snate@binkert.org                MakeAction(createEnumDecls, Transform("ENUMDECL")))
6511869SN/A    env.Depends(hh_file, depends + extra_deps)
6521869SN/A
6535863Snate@binkert.org    i_file = File('python/m5/internal/enum_%s.i' % name)
6545863Snate@binkert.org    env.Command(i_file, Value(name),
6554202Sbinkertn@umich.edu                MakeAction(createEnumSwigWrapper, Transform("ENUMSWIG")))
6565863Snate@binkert.org    env.Depends(i_file, depends + extra_deps)
6575863Snate@binkert.org    SwigSource('m5.internal', i_file)
6585863Snate@binkert.org
6594202Sbinkertn@umich.edu# Generate SimObject SWIG wrapper files
6604202Sbinkertn@umich.edufor name,simobj in sim_objects.iteritems():
6615863Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
6625742Snate@binkert.org    extra_deps = [ py_source.tnode ]
6635742Snate@binkert.org
6645341Sstever@gmail.com    i_file = File('python/m5/internal/param_%s.i' % name)
6655342Sstever@gmail.com    env.Command(i_file, Value(name),
6665342Sstever@gmail.com                MakeAction(createSimObjectSwigWrapper, Transform("SO SWIG")))
6674202Sbinkertn@umich.edu    env.Depends(i_file, depends + extra_deps)
6684202Sbinkertn@umich.edu    SwigSource('m5.internal', i_file)
6694202Sbinkertn@umich.edu
6704202Sbinkertn@umich.edu# Generate the main swig init file
6714202Sbinkertn@umich.edudef makeEmbeddedSwigInit(target, source, env):
6725863Snate@binkert.org    code = code_formatter()
6735863Snate@binkert.org    module = source[0].get_contents()
6745863Snate@binkert.org    code('''\
6755863Snate@binkert.org#include "sim/init.hh"
6765863Snate@binkert.org
6775863Snate@binkert.orgextern "C" {
6785863Snate@binkert.org    void init_${module}();
6795863Snate@binkert.org}
6805863Snate@binkert.org
6815863Snate@binkert.orgEmbeddedSwig embed_swig_${module}(init_${module});
6825863Snate@binkert.org''')
6835863Snate@binkert.org    code.write(str(target[0]))
6845863Snate@binkert.org    
6855863Snate@binkert.org# Build all swig modules
6865863Snate@binkert.orgfor swig in SwigSource.all:
6875863Snate@binkert.org    env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
6885863Snate@binkert.org                MakeAction('$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
6895863Snate@binkert.org                '-o ${TARGETS[0]} $SOURCES', Transform("SWIG")))
6905863Snate@binkert.org    cc_file = str(swig.tnode)
6915863Snate@binkert.org    init_file = '%s/%s_init.cc' % (dirname(cc_file), basename(cc_file))
6921869SN/A    env.Command(init_file, Value(swig.module),
6931858SN/A                MakeAction(makeEmbeddedSwigInit, Transform("EMBED SW")))
6945863Snate@binkert.org    Source(init_file, **swig.guards)
6955863Snate@binkert.org
6961869SN/A# Build all protocol buffers if we have got protoc and protobuf available
6971858SN/Aif env['HAVE_PROTOBUF']:
6985863Snate@binkert.org    for proto in ProtoBuf.all:
6995863Snate@binkert.org        # Use both the source and header as the target, and the .proto
7005863Snate@binkert.org        # file as the source. When executing the protoc compiler, also
7015863Snate@binkert.org        # specify the proto_path to avoid having the generated files
7025863Snate@binkert.org        # include the path.
7031858SN/A        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
704955SN/A                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
705955SN/A                               '--proto_path ${SOURCE.dir} $SOURCE',
7061869SN/A                               Transform("PROTOC")))
7071869SN/A
7081869SN/A        # Add the C++ source file
7091869SN/A        Source(proto.cc_file, **proto.guards)
7101869SN/Aelif ProtoBuf.all:
7115863Snate@binkert.org    print 'Got protobuf to build, but lacks support!'
7125863Snate@binkert.org    Exit(1)
7135863Snate@binkert.org
7141869SN/A#
7155863Snate@binkert.org# Handle debug flags
7161869SN/A#
7175863Snate@binkert.orgdef makeDebugFlagCC(target, source, env):
7181869SN/A    assert(len(target) == 1 and len(source) == 1)
7191869SN/A
7201869SN/A    val = eval(source[0].get_contents())
7211869SN/A    name, compound, desc = val
7221869SN/A    compound = list(sorted(compound))
7235863Snate@binkert.org
7245863Snate@binkert.org    code = code_formatter()
7251869SN/A
7261869SN/A    # file header
7271869SN/A    code('''
7281869SN/A/*
7291869SN/A * DO NOT EDIT THIS FILE! Automatically generated
7301869SN/A */
7311869SN/A
7325863Snate@binkert.org#include "base/debug.hh"
7335863Snate@binkert.org''')
7341869SN/A
7355863Snate@binkert.org    for flag in compound:
7365863Snate@binkert.org        code('#include "debug/$flag.hh"')
7373356Sbinkertn@umich.edu    code()
7383356Sbinkertn@umich.edu    code('namespace Debug {')
7393356Sbinkertn@umich.edu    code()
7403356Sbinkertn@umich.edu
7413356Sbinkertn@umich.edu    if not compound:
7424781Snate@binkert.org        code('SimpleFlag $name("$name", "$desc");')
7435863Snate@binkert.org    else:
7445863Snate@binkert.org        code('CompoundFlag $name("$name", "$desc",')
7451869SN/A        code.indent()
7461869SN/A        last = len(compound) - 1
7471869SN/A        for i,flag in enumerate(compound):
7481869SN/A            if i != last:
7491869SN/A                code('$flag,')
7502638Sstever@eecs.umich.edu            else:
7512638Sstever@eecs.umich.edu                code('$flag);')
7525871Snate@binkert.org        code.dedent()
7532638Sstever@eecs.umich.edu
7545749Scws3k@cs.virginia.edu    code()
7555749Scws3k@cs.virginia.edu    code('} // namespace Debug')
7565871Snate@binkert.org
7575749Scws3k@cs.virginia.edu    code.write(str(target[0]))
7581869SN/A
7591869SN/Adef makeDebugFlagHH(target, source, env):
7603546Sgblack@eecs.umich.edu    assert(len(target) == 1 and len(source) == 1)
7613546Sgblack@eecs.umich.edu
7623546Sgblack@eecs.umich.edu    val = eval(source[0].get_contents())
7633546Sgblack@eecs.umich.edu    name, compound, desc = val
7644202Sbinkertn@umich.edu
7655863Snate@binkert.org    code = code_formatter()
7663546Sgblack@eecs.umich.edu
7673546Sgblack@eecs.umich.edu    # file header boilerplate
7683546Sgblack@eecs.umich.edu    code('''\
7693546Sgblack@eecs.umich.edu/*
7704781Snate@binkert.org * DO NOT EDIT THIS FILE!
7715863Snate@binkert.org *
7724781Snate@binkert.org * Automatically generated by SCons
7734781Snate@binkert.org */
7744781Snate@binkert.org
7754781Snate@binkert.org#ifndef __DEBUG_${name}_HH__
7764781Snate@binkert.org#define __DEBUG_${name}_HH__
7775863Snate@binkert.org
7784781Snate@binkert.orgnamespace Debug {
7794781Snate@binkert.org''')
7804781Snate@binkert.org
7814781Snate@binkert.org    if compound:
7823546Sgblack@eecs.umich.edu        code('class CompoundFlag;')
7833546Sgblack@eecs.umich.edu    code('class SimpleFlag;')
7843546Sgblack@eecs.umich.edu
7854781Snate@binkert.org    if compound:
7863546Sgblack@eecs.umich.edu        code('extern CompoundFlag $name;')
7873546Sgblack@eecs.umich.edu        for flag in compound:
7883546Sgblack@eecs.umich.edu            code('extern SimpleFlag $flag;')
7893546Sgblack@eecs.umich.edu    else:
7903546Sgblack@eecs.umich.edu        code('extern SimpleFlag $name;')
7913546Sgblack@eecs.umich.edu
7923546Sgblack@eecs.umich.edu    code('''
7933546Sgblack@eecs.umich.edu}
7943546Sgblack@eecs.umich.edu
7953546Sgblack@eecs.umich.edu#endif // __DEBUG_${name}_HH__
7964202Sbinkertn@umich.edu''')
7973546Sgblack@eecs.umich.edu
7983546Sgblack@eecs.umich.edu    code.write(str(target[0]))
7993546Sgblack@eecs.umich.edu
800955SN/Afor name,flag in sorted(debug_flags.iteritems()):
801955SN/A    n, compound, desc = flag
802955SN/A    assert n == name
803955SN/A
8041858SN/A    env.Command('debug/%s.hh' % name, Value(flag),
8051858SN/A                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
8061858SN/A    env.Command('debug/%s.cc' % name, Value(flag),
8075863Snate@binkert.org                MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
8085863Snate@binkert.org    Source('debug/%s.cc' % name)
8095343Sstever@gmail.com
8105343Sstever@gmail.com# Embed python files.  All .py files that have been indicated by a
8115863Snate@binkert.org# PySource() call in a SConscript need to be embedded into the M5
8125863Snate@binkert.org# library.  To do that, we compile the file to byte code, marshal the
8134773Snate@binkert.org# byte code, compress it, and then generate a c++ file that
8145863Snate@binkert.org# inserts the result into an array.
8152632Sstever@eecs.umich.edudef embedPyFile(target, source, env):
8165863Snate@binkert.org    def c_str(string):
8172023SN/A        if string is None:
8185863Snate@binkert.org            return "0"
8195863Snate@binkert.org        return '"%s"' % string
8205863Snate@binkert.org
8215863Snate@binkert.org    '''Action function to compile a .py into a code object, marshal
8225863Snate@binkert.org    it, compress it, and stick it into an asm file so the code appears
8235863Snate@binkert.org    as just bytes with a label in the data section'''
8245863Snate@binkert.org
8255863Snate@binkert.org    src = file(str(source[0]), 'r').read()
8265863Snate@binkert.org
8272632Sstever@eecs.umich.edu    pysource = PySource.tnodes[source[0]]
8285863Snate@binkert.org    compiled = compile(src, pysource.abspath, 'exec')
8292023SN/A    marshalled = marshal.dumps(compiled)
8302632Sstever@eecs.umich.edu    compressed = zlib.compress(marshalled)
8315863Snate@binkert.org    data = compressed
8325342Sstever@gmail.com    sym = pysource.symname
8335863Snate@binkert.org
8342632Sstever@eecs.umich.edu    code = code_formatter()
8355863Snate@binkert.org    code('''\
8365863Snate@binkert.org#include "sim/init.hh"
8372632Sstever@eecs.umich.edu
8385863Snate@binkert.orgnamespace {
8395863Snate@binkert.org
8405863Snate@binkert.orgconst uint8_t data_${sym}[] = {
8415863Snate@binkert.org''')
8425863Snate@binkert.org    code.indent()
8435863Snate@binkert.org    step = 16
8442632Sstever@eecs.umich.edu    for i in xrange(0, len(data), step):
8455863Snate@binkert.org        x = array.array('B', data[i:i+step])
8465863Snate@binkert.org        code(''.join('%d,' % d for d in x))
8472632Sstever@eecs.umich.edu    code.dedent()
8481888SN/A    
8495863Snate@binkert.org    code('''};
8505863Snate@binkert.org
8515863Snate@binkert.orgEmbeddedPython embedded_${sym}(
8521858SN/A    ${{c_str(pysource.arcname)}},
8535863Snate@binkert.org    ${{c_str(pysource.abspath)}},
8545863Snate@binkert.org    ${{c_str(pysource.modpath)}},
8555863Snate@binkert.org    data_${sym},
8565863Snate@binkert.org    ${{len(data)}},
8572598SN/A    ${{len(marshalled)}});
8585863Snate@binkert.org
8591858SN/A} // anonymous namespace
8601858SN/A''')
8611858SN/A    code.write(str(target[0]))
8625863Snate@binkert.org
8631858SN/Afor source in PySource.all:
8641858SN/A    env.Command(source.cpp, source.tnode, 
8651858SN/A                MakeAction(embedPyFile, Transform("EMBED PY")))
8665863Snate@binkert.org    Source(source.cpp)
8671871SN/A
8681858SN/A########################################################################
8691858SN/A#
8701858SN/A# Define binaries.  Each different build type (debug, opt, etc.) gets
8711858SN/A# a slightly different build environment.
8721858SN/A#
8731858SN/A
8741858SN/A# List of constructed environments to pass back to SConstruct
8755863Snate@binkert.orgenvList = []
8761858SN/A
8771858SN/Adate_source = Source('base/date.cc', skip_lib=True)
8785863Snate@binkert.org
8791859SN/A# Function to create a new build environment as clone of current
8801859SN/A# environment 'env' with modified object suffix and optional stripped
8811869SN/A# binary.  Additional keyword arguments are appended to corresponding
8825863Snate@binkert.org# build environment vars.
8835863Snate@binkert.orgdef makeEnv(label, objsfx, strip = False, **kwargs):
8841869SN/A    # SCons doesn't know to append a library suffix when there is a '.' in the
8851965SN/A    # name.  Use '_' instead.
8861965SN/A    libname = 'gem5_' + label
8871965SN/A    exename = 'gem5.' + label
8882761Sstever@eecs.umich.edu    secondary_exename = 'm5.' + label
8895863Snate@binkert.org
8901869SN/A    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
8915863Snate@binkert.org    new_env.Label = label
8922667Sstever@eecs.umich.edu    new_env.Append(**kwargs)
8931869SN/A
8941869SN/A    swig_env = new_env.Clone()
8952929Sktlim@umich.edu    swig_env.Append(CCFLAGS='-Werror')
8962929Sktlim@umich.edu    if env['GCC']:
8975863Snate@binkert.org        swig_env.Append(CCFLAGS=['-Wno-uninitialized', '-Wno-sign-compare',
8982929Sktlim@umich.edu                                 '-Wno-parentheses', '-Wno-unused-label',
899955SN/A                                 '-Wno-unused-value'])
9002598SN/A        if compareVersions(env['GCC_VERSION'], '4.6') >= 0:
901            swig_env.Append(CCFLAGS='-Wno-unused-but-set-variable')
902    if env['CLANG']:
903        swig_env.Append(CCFLAGS=['-Wno-unused-label', '-Wno-unused-value'])
904
905    werror_env = new_env.Clone()
906    werror_env.Append(CCFLAGS='-Werror')
907
908    def make_obj(source, static, extra_deps = None):
909        '''This function adds the specified source to the correct
910        build environment, and returns the corresponding SCons Object
911        nodes'''
912
913        if source.swig:
914            env = swig_env
915        elif source.Werror:
916            env = werror_env
917        else:
918            env = new_env
919
920        if static:
921            obj = env.StaticObject(source.tnode)
922        else:
923            obj = env.SharedObject(source.tnode)
924
925        if extra_deps:
926            env.Depends(obj, extra_deps)
927
928        return obj
929
930    static_objs = \
931        [ make_obj(s, True) for s in Source.get(main=False, skip_lib=False) ]
932    shared_objs = \
933        [ make_obj(s, False) for s in Source.get(main=False, skip_lib=False) ]
934
935    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
936    static_objs.append(static_date)
937    
938    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
939    shared_objs.append(shared_date)
940
941    # First make a library of everything but main() so other programs can
942    # link against m5.
943    static_lib = new_env.StaticLibrary(libname, static_objs)
944    shared_lib = new_env.SharedLibrary(libname, shared_objs)
945
946    # Now link a stub with main() and the static library.
947    main_objs = [ make_obj(s, True) for s in Source.get(main=True) ]
948
949    for test in UnitTest.all:
950        flags = { test.target : True }
951        test_sources = Source.get(**flags)
952        test_objs = [ make_obj(s, static=True) for s in test_sources ]
953        if test.main:
954            test_objs += main_objs
955        testname = "unittest/%s.%s" % (test.target, label)
956        new_env.Program(testname, test_objs + static_objs)
957
958    progname = exename
959    if strip:
960        progname += '.unstripped'
961
962    targets = new_env.Program(progname, main_objs + static_objs)
963
964    if strip:
965        if sys.platform == 'sunos5':
966            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
967        else:
968            cmd = 'strip $SOURCE -o $TARGET'
969        targets = new_env.Command(exename, progname,
970                    MakeAction(cmd, Transform("STRIP")))
971
972    new_env.Command(secondary_exename, exename,
973            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
974
975    new_env.M5Binary = targets[0]
976    envList.append(new_env)
977
978# Start out with the compiler flags common to all compilers,
979# i.e. they all use -g for opt and -g -pg for prof
980ccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
981           'perf' : ['-g']}
982
983# Start out with the linker flags common to all linkers, i.e. -pg for
984# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
985# no-as-needed and as-needed as the binutils linker is too clever and
986# simply doesn't link to the library otherwise.
987ldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
988           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
989
990# For Link Time Optimization, the optimisation flags used to compile
991# individual files are decoupled from those used at link time
992# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
993# to also update the linker flags based on the target.
994if env['GCC']:
995    if sys.platform == 'sunos5':
996        ccflags['debug'] += ['-gstabs+']
997    else:
998        ccflags['debug'] += ['-ggdb3']
999    ldflags['debug'] += ['-O0']
1000    # opt, fast, prof and perf all share the same cc flags, also add
1001    # the optimization to the ldflags as LTO defers the optimization
1002    # to link time
1003    for target in ['opt', 'fast', 'prof', 'perf']:
1004        ccflags[target] += ['-O3']
1005        ldflags[target] += ['-O3']
1006
1007    ccflags['fast'] += env['LTO_CCFLAGS']
1008    ldflags['fast'] += env['LTO_LDFLAGS']
1009elif env['CLANG']:
1010    ccflags['debug'] += ['-g', '-O0']
1011    # opt, fast, prof and perf all share the same cc flags
1012    for target in ['opt', 'fast', 'prof', 'perf']:
1013        ccflags[target] += ['-O3']
1014else:
1015    print 'Unknown compiler, please fix compiler options'
1016    Exit(1)
1017
1018
1019# To speed things up, we only instantiate the build environments we
1020# need.  We try to identify the needed environment for each target; if
1021# we can't, we fall back on instantiating all the environments just to
1022# be safe.
1023target_types = ['debug', 'opt', 'fast', 'prof', 'perf']
1024obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
1025              'gpo' : 'perf'}
1026
1027def identifyTarget(t):
1028    ext = t.split('.')[-1]
1029    if ext in target_types:
1030        return ext
1031    if obj2target.has_key(ext):
1032        return obj2target[ext]
1033    match = re.search(r'/tests/([^/]+)/', t)
1034    if match and match.group(1) in target_types:
1035        return match.group(1)
1036    return 'all'
1037
1038needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
1039if 'all' in needed_envs:
1040    needed_envs += target_types
1041
1042# Debug binary
1043if 'debug' in needed_envs:
1044    makeEnv('debug', '.do',
1045            CCFLAGS = Split(ccflags['debug']),
1046            CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
1047            LINKFLAGS = Split(ldflags['debug']))
1048
1049# Optimized binary
1050if 'opt' in needed_envs:
1051    makeEnv('opt', '.o',
1052            CCFLAGS = Split(ccflags['opt']),
1053            CPPDEFINES = ['TRACING_ON=1'],
1054            LINKFLAGS = Split(ldflags['opt']))
1055
1056# "Fast" binary
1057if 'fast' in needed_envs:
1058    makeEnv('fast', '.fo', strip = True,
1059            CCFLAGS = Split(ccflags['fast']),
1060            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1061            LINKFLAGS = Split(ldflags['fast']))
1062
1063# Profiled binary using gprof
1064if 'prof' in needed_envs:
1065    makeEnv('prof', '.po',
1066            CCFLAGS = Split(ccflags['prof']),
1067            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1068            LINKFLAGS = Split(ldflags['prof']))
1069
1070# Profiled binary using google-pprof
1071if 'perf' in needed_envs:
1072    makeEnv('perf', '.gpo',
1073            CCFLAGS = Split(ccflags['perf']),
1074            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1075            LINKFLAGS = Split(ldflags['perf']))
1076
1077Return('envList')
1078