SConscript revision 6397
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 sys
385522Snate@binkert.orgimport zlib
394202Sbinkertn@umich.edu
405742Snate@binkert.orgfrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
41955SN/A
424381Sbinkertn@umich.eduimport SCons
434381Sbinkertn@umich.edu
448334Snate@binkert.org# This file defines how to build a particular configuration of M5
45955SN/A# based on variable settings in the 'env' build environment.
46955SN/A
474202Sbinkertn@umich.eduImport('*')
48955SN/A
494382Sbinkertn@umich.edu# Children need to see the environment
504382Sbinkertn@umich.eduExport('env')
514382Sbinkertn@umich.edu
526654Snate@binkert.orgbuild_env = dict([(opt, env[opt]) for opt in export_vars])
535517Snate@binkert.org
547674Snate@binkert.org########################################################################
557674Snate@binkert.org# Code for adding source files of various types
566143Snate@binkert.org#
576143Snate@binkert.orgclass SourceMeta(type):
586143Snate@binkert.org    def __init__(cls, name, bases, dict):
598233Snate@binkert.org        super(SourceMeta, cls).__init__(name, bases, dict)
608233Snate@binkert.org        cls.all = []
618233Snate@binkert.org        
628233Snate@binkert.org    def get(cls, **kwargs):
638233Snate@binkert.org        for src in cls.all:
648334Snate@binkert.org            for attr,value in kwargs.iteritems():
658334Snate@binkert.org                if getattr(src, attr) != value:
668233Snate@binkert.org                    break
678233Snate@binkert.org            else:
688233Snate@binkert.org                yield src
698233Snate@binkert.org
708233Snate@binkert.orgclass SourceFile(object):
718233Snate@binkert.org    __metaclass__ = SourceMeta
726143Snate@binkert.org    def __init__(self, source):
738233Snate@binkert.org        tnode = source
748233Snate@binkert.org        if not isinstance(source, SCons.Node.FS.File):
758233Snate@binkert.org            tnode = File(source)
766143Snate@binkert.org
776143Snate@binkert.org        self.tnode = tnode
786143Snate@binkert.org        self.snode = tnode.srcnode()
796143Snate@binkert.org        self.filename = str(tnode)
808233Snate@binkert.org        self.dirname = dirname(self.filename)
818233Snate@binkert.org        self.basename = basename(self.filename)
828233Snate@binkert.org        index = self.basename.rfind('.')
836143Snate@binkert.org        if index <= 0:
848233Snate@binkert.org            # dot files aren't extensions
858233Snate@binkert.org            self.extname = self.basename, None
868233Snate@binkert.org        else:
878233Snate@binkert.org            self.extname = self.basename[:index], self.basename[index+1:]
886143Snate@binkert.org
896143Snate@binkert.org        for base in type(self).__mro__:
906143Snate@binkert.org            if issubclass(base, SourceFile):
914762Snate@binkert.org                bisect.insort_right(base.all, self)       
926143Snate@binkert.org
938233Snate@binkert.org    def __lt__(self, other): return self.filename < other.filename
948233Snate@binkert.org    def __le__(self, other): return self.filename <= other.filename
958233Snate@binkert.org    def __gt__(self, other): return self.filename > other.filename
968233Snate@binkert.org    def __ge__(self, other): return self.filename >= other.filename
978233Snate@binkert.org    def __eq__(self, other): return self.filename == other.filename
986143Snate@binkert.org    def __ne__(self, other): return self.filename != other.filename
998233Snate@binkert.org        
1008233Snate@binkert.orgclass Source(SourceFile):
1018233Snate@binkert.org    '''Add a c/c++ source file to the build'''
1028233Snate@binkert.org    def __init__(self, source, Werror=True, swig=False, bin_only=False,
1036143Snate@binkert.org                 skip_lib=False):
1046143Snate@binkert.org        super(Source, self).__init__(source)
1056143Snate@binkert.org
1066143Snate@binkert.org        self.Werror = Werror
1076143Snate@binkert.org        self.swig = swig
1086143Snate@binkert.org        self.bin_only = bin_only
1096143Snate@binkert.org        self.skip_lib = bin_only or skip_lib
1106143Snate@binkert.org
1116143Snate@binkert.orgclass PySource(SourceFile):
1127065Snate@binkert.org    '''Add a python source file to the named package'''
1136143Snate@binkert.org    invalid_sym_char = re.compile('[^A-z0-9_]')
1148233Snate@binkert.org    modules = {}
1158233Snate@binkert.org    tnodes = {}
1168233Snate@binkert.org    symnames = {}
1178233Snate@binkert.org    
1188233Snate@binkert.org    def __init__(self, package, source):
1198233Snate@binkert.org        super(PySource, self).__init__(source)
1208233Snate@binkert.org
1218233Snate@binkert.org        modname,ext = self.extname
1228233Snate@binkert.org        assert ext == 'py'
1238233Snate@binkert.org
1248233Snate@binkert.org        if package:
1258233Snate@binkert.org            path = package.split('.')
1268233Snate@binkert.org        else:
1278233Snate@binkert.org            path = []
1288233Snate@binkert.org
1298233Snate@binkert.org        modpath = path[:]
1308233Snate@binkert.org        if modname != '__init__':
1318233Snate@binkert.org            modpath += [ modname ]
1328233Snate@binkert.org        modpath = '.'.join(modpath)
1338233Snate@binkert.org
1348233Snate@binkert.org        arcpath = path + [ self.basename ]
1358233Snate@binkert.org        debugname = self.snode.abspath
1368233Snate@binkert.org        if not exists(debugname):
1378233Snate@binkert.org            debugname = self.tnode.abspath
1388233Snate@binkert.org
1398233Snate@binkert.org        self.package = package
1408233Snate@binkert.org        self.modname = modname
1418233Snate@binkert.org        self.modpath = modpath
1428233Snate@binkert.org        self.arcname = joinpath(*arcpath)
1438233Snate@binkert.org        self.debugname = debugname
1448233Snate@binkert.org        self.compiled = File(self.filename + 'c')
1456143Snate@binkert.org        self.assembly = File(self.filename + '.s')
1466143Snate@binkert.org        self.symname = "PyEMB_" + PySource.invalid_sym_char.sub('_', modpath)
1476143Snate@binkert.org
1486143Snate@binkert.org        PySource.modules[modpath] = self
1496143Snate@binkert.org        PySource.tnodes[self.tnode] = self
1506143Snate@binkert.org        PySource.symnames[self.symname] = self
1516143Snate@binkert.org
1526143Snate@binkert.orgclass SimObject(PySource):
1536143Snate@binkert.org    '''Add a SimObject python file as a python source object and add
1548233Snate@binkert.org    it to a list of sim object modules'''
1558233Snate@binkert.org
1568233Snate@binkert.org    fixed = False
1576143Snate@binkert.org    modnames = []
1586143Snate@binkert.org
1596143Snate@binkert.org    def __init__(self, source):
1606143Snate@binkert.org        super(SimObject, self).__init__('m5.objects', source)
1616143Snate@binkert.org        if self.fixed:
1626143Snate@binkert.org            raise AttributeError, "Too late to call SimObject now."
1635522Snate@binkert.org
1646143Snate@binkert.org        bisect.insort_right(SimObject.modnames, self.modname)
1656143Snate@binkert.org
1666143Snate@binkert.orgclass SwigSource(SourceFile):
1676143Snate@binkert.org    '''Add a swig file to build'''
1688233Snate@binkert.org
1698233Snate@binkert.org    def __init__(self, package, source):
1708233Snate@binkert.org        super(SwigSource, self).__init__(source)
1716143Snate@binkert.org
1726143Snate@binkert.org        modname,ext = self.extname
1736143Snate@binkert.org        assert ext == 'i'
1746143Snate@binkert.org
1755522Snate@binkert.org        self.module = modname
1765522Snate@binkert.org        cc_file = joinpath(self.dirname, modname + '_wrap.cc')
1775522Snate@binkert.org        py_file = joinpath(self.dirname, modname + '.py')
1785522Snate@binkert.org
1795604Snate@binkert.org        self.cc_source = Source(cc_file, swig=True)
1805604Snate@binkert.org        self.py_source = PySource(package, py_file)
1816143Snate@binkert.org
1826143Snate@binkert.orgunit_tests = []
1834762Snate@binkert.orgdef UnitTest(target, sources):
1844762Snate@binkert.org    if not isinstance(sources, (list, tuple)):
1856143Snate@binkert.org        sources = [ sources ]
1866727Ssteve.reinhardt@amd.com
1876727Ssteve.reinhardt@amd.com    sources = [ Source(src, skip_lib=True) for src in sources ]
1886727Ssteve.reinhardt@amd.com    unit_tests.append((target, sources))
1894762Snate@binkert.org
1906143Snate@binkert.org# Children should have access
1916143Snate@binkert.orgExport('Source')
1926143Snate@binkert.orgExport('PySource')
1936143Snate@binkert.orgExport('SimObject')
1946727Ssteve.reinhardt@amd.comExport('SwigSource')
1956143Snate@binkert.orgExport('UnitTest')
1967674Snate@binkert.org
1977674Snate@binkert.org########################################################################
1985604Snate@binkert.org#
1996143Snate@binkert.org# Trace Flags
2006143Snate@binkert.org#
2016143Snate@binkert.orgtrace_flags = {}
2024762Snate@binkert.orgdef TraceFlag(name, desc=None):
2036143Snate@binkert.org    if name in trace_flags:
2044762Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
2054762Snate@binkert.org    trace_flags[name] = (name, (), desc)
2064762Snate@binkert.org
2076143Snate@binkert.orgdef CompoundFlag(name, flags, desc=None):
2086143Snate@binkert.org    if name in trace_flags:
2094762Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
2108233Snate@binkert.org
2118233Snate@binkert.org    compound = tuple(flags)
2128233Snate@binkert.org    trace_flags[name] = (name, compound, desc)
2138233Snate@binkert.org
2146143Snate@binkert.orgExport('TraceFlag')
2156143Snate@binkert.orgExport('CompoundFlag')
2164762Snate@binkert.org
2176143Snate@binkert.org########################################################################
2184762Snate@binkert.org#
2196143Snate@binkert.org# Set some compiler variables
2204762Snate@binkert.org#
2216143Snate@binkert.org
2228233Snate@binkert.org# Include file paths are rooted in this directory.  SCons will
2238233Snate@binkert.org# automatically expand '.' to refer to both the source directory and
2248233Snate@binkert.org# the corresponding build directory to pick up generated include
2256143Snate@binkert.org# files.
2266143Snate@binkert.orgenv.Append(CPPPATH=Dir('.'))
2276143Snate@binkert.org
2286143Snate@binkert.orgfor extra_dir in extras_dir_list:
2296143Snate@binkert.org    env.Append(CPPPATH=Dir(extra_dir))
2306143Snate@binkert.org
2316143Snate@binkert.org# Add a flag defining what THE_ISA should be for all compilation
2326143Snate@binkert.orgenv.Append(CPPDEFINES=[('THE_ISA','%s_ISA' % env['TARGET_ISA'].upper())])
2338233Snate@binkert.org
2348233Snate@binkert.org# Workaround for bug in SCons version > 0.97d20071212
235955SN/A# Scons bug id: 2006 M5 Bug id: 308 
2368235Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
2378235Snate@binkert.org    Dir(root[len(base_dir) + 1:])
2386143Snate@binkert.org
2398235Snate@binkert.org########################################################################
2408235Snate@binkert.org#
2418235Snate@binkert.org# Walk the tree and execute all SConscripts in subdirectories
2428235Snate@binkert.org#
2438235Snate@binkert.org
2448235Snate@binkert.orghere = Dir('.').srcnode().abspath
2458235Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
2468235Snate@binkert.org    if root == here:
2478235Snate@binkert.org        # we don't want to recurse back into this SConscript
2488235Snate@binkert.org        continue
2498235Snate@binkert.org
2508235Snate@binkert.org    if 'SConscript' in files:
2518235Snate@binkert.org        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
2528235Snate@binkert.org        SConscript(joinpath(root, 'SConscript'), build_dir=build_dir)
2538235Snate@binkert.org
2548235Snate@binkert.orgfor extra_dir in extras_dir_list:
2558235Snate@binkert.org    prefix_len = len(dirname(extra_dir)) + 1
2565584Snate@binkert.org    for root, dirs, files in os.walk(extra_dir, topdown=True):
2574382Sbinkertn@umich.edu        if 'SConscript' in files:
2584202Sbinkertn@umich.edu            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
2594382Sbinkertn@umich.edu            SConscript(joinpath(root, 'SConscript'), build_dir=build_dir)
2604382Sbinkertn@umich.edu
2614382Sbinkertn@umich.edufor opt in export_vars:
2625584Snate@binkert.org    env.ConfigFile(opt)
2634382Sbinkertn@umich.edu
2644382Sbinkertn@umich.edu########################################################################
2654382Sbinkertn@umich.edu#
2668232Snate@binkert.org# Prevent any SimObjects from being added after this point, they
2675192Ssaidi@eecs.umich.edu# should all have been added in the SConscripts above
2688232Snate@binkert.org#
2698232Snate@binkert.orgclass DictImporter(object):
2708232Snate@binkert.org    '''This importer takes a dictionary of arbitrary module names that
2715192Ssaidi@eecs.umich.edu    map to arbitrary filenames.'''
2728232Snate@binkert.org    def __init__(self, modules):
2735192Ssaidi@eecs.umich.edu        self.modules = modules
2745799Snate@binkert.org        self.installed = set()
2758232Snate@binkert.org
2765192Ssaidi@eecs.umich.edu    def __del__(self):
2775192Ssaidi@eecs.umich.edu        self.unload()
2785192Ssaidi@eecs.umich.edu
2798232Snate@binkert.org    def unload(self):
2805192Ssaidi@eecs.umich.edu        import sys
2818232Snate@binkert.org        for module in self.installed:
2825192Ssaidi@eecs.umich.edu            del sys.modules[module]
2835192Ssaidi@eecs.umich.edu        self.installed = set()
2845192Ssaidi@eecs.umich.edu
2855192Ssaidi@eecs.umich.edu    def find_module(self, fullname, path):
2864382Sbinkertn@umich.edu        if fullname == 'defines':
2874382Sbinkertn@umich.edu            return self
2884382Sbinkertn@umich.edu
2892667Sstever@eecs.umich.edu        if fullname == 'm5.objects':
2902667Sstever@eecs.umich.edu            return self
2912667Sstever@eecs.umich.edu
2922667Sstever@eecs.umich.edu        if fullname.startswith('m5.internal'):
2932667Sstever@eecs.umich.edu            return None
2942667Sstever@eecs.umich.edu
2955742Snate@binkert.org        source = self.modules.get(fullname, None)
2965742Snate@binkert.org        if source is not None and exists(source.snode.abspath):
2975742Snate@binkert.org            return self
2985793Snate@binkert.org
2998334Snate@binkert.org        return None
3005793Snate@binkert.org
3015793Snate@binkert.org    def load_module(self, fullname):
3025793Snate@binkert.org        mod = imp.new_module(fullname)
3034382Sbinkertn@umich.edu        sys.modules[fullname] = mod
3044762Snate@binkert.org        self.installed.add(fullname)
3055344Sstever@gmail.com
3064382Sbinkertn@umich.edu        mod.__loader__ = self
3075341Sstever@gmail.com        if fullname == 'm5.objects':
3085742Snate@binkert.org            mod.__path__ = fullname.split('.')
3095742Snate@binkert.org            return mod
3105742Snate@binkert.org
3115742Snate@binkert.org        if fullname == 'defines':
3125742Snate@binkert.org            mod.__dict__['buildEnv'] = build_env
3134762Snate@binkert.org            return mod
3145742Snate@binkert.org
3155742Snate@binkert.org        source = self.modules[fullname]
3167722Sgblack@eecs.umich.edu        if source.modname == '__init__':
3175742Snate@binkert.org            mod.__path__ = source.modpath
3185742Snate@binkert.org        mod.__file__ = source.snode.abspath
3195742Snate@binkert.org
3205742Snate@binkert.org        exec file(source.snode.abspath, 'r') in mod.__dict__
3218242Sbradley.danofsky@amd.com
3228242Sbradley.danofsky@amd.com        return mod
3238242Sbradley.danofsky@amd.com
3248242Sbradley.danofsky@amd.com# install the python importer so we can grab stuff from the source
3255341Sstever@gmail.com# tree itself.  We can't have SimObjects added after this point or
3265742Snate@binkert.org# else we won't know about them for the rest of the stuff.
3277722Sgblack@eecs.umich.eduSimObject.fixed = True
3284773Snate@binkert.orgimporter = DictImporter(PySource.modules)
3296108Snate@binkert.orgsys.meta_path[0:0] = [ importer ]
3301858SN/A
3311085SN/Aimport m5
3326658Snate@binkert.org
3336658Snate@binkert.org# import all sim objects so we can populate the all_objects list
3347673Snate@binkert.org# make sure that we're working with a list, then let's sort it
3356658Snate@binkert.orgfor modname in SimObject.modnames:
3366658Snate@binkert.org    exec('from m5.objects import %s' % modname)
3376658Snate@binkert.org
3386658Snate@binkert.org# we need to unload all of the currently imported modules so that they
3396658Snate@binkert.org# will be re-imported the next time the sconscript is run
3406658Snate@binkert.orgimporter.unload()
3416658Snate@binkert.orgsys.meta_path.remove(importer)
3427673Snate@binkert.org
3437673Snate@binkert.orgsim_objects = m5.SimObject.allClasses
3447673Snate@binkert.orgall_enums = m5.params.allEnums
3457673Snate@binkert.org
3467673Snate@binkert.orgall_params = {}
3477673Snate@binkert.orgfor name,obj in sorted(sim_objects.iteritems()):
3487673Snate@binkert.org    for param in obj._params.local.values():
3496658Snate@binkert.org        if not hasattr(param, 'swig_decl'):
3507673Snate@binkert.org            continue
3517673Snate@binkert.org        pname = param.ptype_str
3527673Snate@binkert.org        if pname not in all_params:
3537673Snate@binkert.org            all_params[pname] = param
3547673Snate@binkert.org
3557673Snate@binkert.org########################################################################
3567673Snate@binkert.org#
3577673Snate@binkert.org# calculate extra dependencies
3587673Snate@binkert.org#
3597673Snate@binkert.orgmodule_depends = ["m5", "m5.SimObject", "m5.params"]
3606658Snate@binkert.orgdepends = [ PySource.modules[dep].tnode for dep in module_depends ]
3617756SAli.Saidi@ARM.com
3627816Ssteve.reinhardt@amd.com########################################################################
3636658Snate@binkert.org#
3644382Sbinkertn@umich.edu# Commands for the basic automatically generated python files
3654382Sbinkertn@umich.edu#
3664762Snate@binkert.org
3674762Snate@binkert.org# Generate Python file containing a dict specifying the current
3684762Snate@binkert.org# build_env flags.
3696654Snate@binkert.orgdef makeDefinesPyFile(target, source, env):
3706654Snate@binkert.org    f = file(str(target[0]), 'w')
3715517Snate@binkert.org    build_env, hg_info = [ x.get_contents() for x in source ]
3725517Snate@binkert.org    print >>f, "buildEnv = %s" % build_env
3735517Snate@binkert.org    print >>f, "hgRev = '%s'" % hg_info
3745517Snate@binkert.org    f.close()
3755517Snate@binkert.org
3765517Snate@binkert.orgdefines_info = [ Value(build_env), Value(env['HG_INFO']) ]
3775517Snate@binkert.org# Generate a file with all of the compile options in it
3785517Snate@binkert.orgenv.Command('python/m5/defines.py', defines_info, makeDefinesPyFile)
3795517Snate@binkert.orgPySource('m5', 'python/m5/defines.py')
3805517Snate@binkert.org
3815517Snate@binkert.org# Generate python file containing info about the M5 source code
3825517Snate@binkert.orgdef makeInfoPyFile(target, source, env):
3835517Snate@binkert.org    f = file(str(target[0]), 'w')
3845517Snate@binkert.org    for src in source:
3855517Snate@binkert.org        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
3865517Snate@binkert.org        print >>f, "%s = %s" % (src, repr(data))
3875517Snate@binkert.org    f.close()
3886654Snate@binkert.org
3895517Snate@binkert.org# Generate a file that wraps the basic top level files
3905517Snate@binkert.orgenv.Command('python/m5/info.py',
3915517Snate@binkert.org            [ '#/AUTHORS', '#/LICENSE', '#/README', '#/RELEASE_NOTES' ],
3925517Snate@binkert.org            makeInfoPyFile)
3935517Snate@binkert.orgPySource('m5', 'python/m5/info.py')
3945517Snate@binkert.org
3955517Snate@binkert.org# Generate the __init__.py file for m5.objects
3965517Snate@binkert.orgdef makeObjectsInitFile(target, source, env):
3976143Snate@binkert.org    f = file(str(target[0]), 'w')
3986654Snate@binkert.org    print >>f, 'from params import *'
3995517Snate@binkert.org    print >>f, 'from m5.SimObject import *'
4005517Snate@binkert.org    for module in source:
4015517Snate@binkert.org        print >>f, 'from %s import *' % module.get_contents()
4025517Snate@binkert.org    f.close()
4035517Snate@binkert.org
4045517Snate@binkert.org# Generate an __init__.py file for the objects package
4055517Snate@binkert.orgenv.Command('python/m5/objects/__init__.py',
4065517Snate@binkert.org            map(Value, SimObject.modnames),
4075517Snate@binkert.org            makeObjectsInitFile)
4085517Snate@binkert.orgPySource('m5.objects', 'python/m5/objects/__init__.py')
4095517Snate@binkert.org
4105517Snate@binkert.org########################################################################
4115517Snate@binkert.org#
4125517Snate@binkert.org# Create all of the SimObject param headers and enum headers
4136654Snate@binkert.org#
4146654Snate@binkert.org
4155517Snate@binkert.orgdef createSimObjectParam(target, source, env):
4165517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
4176143Snate@binkert.org
4186143Snate@binkert.org    hh_file = file(target[0].abspath, 'w')
4196143Snate@binkert.org    name = str(source[0].get_contents())
4206727Ssteve.reinhardt@amd.com    obj = sim_objects[name]
4215517Snate@binkert.org
4226727Ssteve.reinhardt@amd.com    print >>hh_file, obj.cxx_decl()
4235517Snate@binkert.org    hh_file.close()
4245517Snate@binkert.org
4255517Snate@binkert.orgdef createSwigParam(target, source, env):
4266654Snate@binkert.org    assert len(target) == 1 and len(source) == 1
4276654Snate@binkert.org
4287673Snate@binkert.org    i_file = file(target[0].abspath, 'w')
4296654Snate@binkert.org    name = str(source[0].get_contents())
4306654Snate@binkert.org    param = all_params[name]
4316654Snate@binkert.org
4326654Snate@binkert.org    for line in param.swig_decl():
4335517Snate@binkert.org        print >>i_file, line
4345517Snate@binkert.org    i_file.close()
4355517Snate@binkert.org
4366143Snate@binkert.orgdef createEnumStrings(target, source, env):
4375517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
4384762Snate@binkert.org
4395517Snate@binkert.org    cc_file = file(target[0].abspath, 'w')
4405517Snate@binkert.org    name = str(source[0].get_contents())
4416143Snate@binkert.org    obj = all_enums[name]
4426143Snate@binkert.org
4435517Snate@binkert.org    print >>cc_file, obj.cxx_def()
4445517Snate@binkert.org    cc_file.close()
4455517Snate@binkert.org
4465517Snate@binkert.orgdef createEnumParam(target, source, env):
4475517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
4485517Snate@binkert.org
4495517Snate@binkert.org    hh_file = file(target[0].abspath, 'w')
4505517Snate@binkert.org    name = str(source[0].get_contents())
4515517Snate@binkert.org    obj = all_enums[name]
4525517Snate@binkert.org
4536143Snate@binkert.org    print >>hh_file, obj.cxx_decl()
4545517Snate@binkert.org    hh_file.close()
4556654Snate@binkert.org
4566654Snate@binkert.org# Generate all of the SimObject param struct header files
4576654Snate@binkert.orgparams_hh_files = []
4586654Snate@binkert.orgfor name,simobj in sorted(sim_objects.iteritems()):
4596654Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
4606654Snate@binkert.org    extra_deps = [ py_source.tnode ]
4615517Snate@binkert.org
4625517Snate@binkert.org    hh_file = File('params/%s.hh' % name)
4635517Snate@binkert.org    params_hh_files.append(hh_file)
4645517Snate@binkert.org    env.Command(hh_file, Value(name), createSimObjectParam)
4655517Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
4664762Snate@binkert.org
4674762Snate@binkert.org# Generate any parameter header files needed
4684762Snate@binkert.orgparams_i_files = []
4694762Snate@binkert.orgfor name,param in all_params.iteritems():
4704762Snate@binkert.org    if isinstance(param, m5.params.VectorParamDesc):
4714762Snate@binkert.org        ext = 'vptype'
4727675Snate@binkert.org    else:
4734762Snate@binkert.org        ext = 'ptype'
4744762Snate@binkert.org
4754762Snate@binkert.org    i_file = File('params/%s_%s.i' % (name, ext))
4764762Snate@binkert.org    params_i_files.append(i_file)
4774382Sbinkertn@umich.edu    env.Command(i_file, Value(name), createSwigParam)
4784382Sbinkertn@umich.edu    env.Depends(i_file, depends)
4795517Snate@binkert.org
4806654Snate@binkert.org# Generate all enum header files
4815517Snate@binkert.orgfor name,enum in sorted(all_enums.iteritems()):
4828126Sgblack@eecs.umich.edu    py_source = PySource.modules[enum.__module__]
4836654Snate@binkert.org    extra_deps = [ py_source.tnode ]
4847673Snate@binkert.org
4856654Snate@binkert.org    cc_file = File('enums/%s.cc' % name)
4866654Snate@binkert.org    env.Command(cc_file, Value(name), createEnumStrings)
4876654Snate@binkert.org    env.Depends(cc_file, depends + extra_deps)
4886654Snate@binkert.org    Source(cc_file)
4896654Snate@binkert.org
4906654Snate@binkert.org    hh_file = File('enums/%s.hh' % name)
4916654Snate@binkert.org    env.Command(hh_file, Value(name), createEnumParam)
4926669Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
4936669Snate@binkert.org
4946669Snate@binkert.org# Build the big monolithic swigged params module (wraps all SimObject
4956669Snate@binkert.org# param structs and enum structs)
4966669Snate@binkert.orgdef buildParams(target, source, env):
4976669Snate@binkert.org    names = [ s.get_contents() for s in source ]
4986654Snate@binkert.org    objs = [ sim_objects[name] for name in names ]
4997673Snate@binkert.org    out = file(target[0].abspath, 'w')
5005517Snate@binkert.org
5018126Sgblack@eecs.umich.edu    ordered_objs = []
5025798Snate@binkert.org    obj_seen = set()
5037756SAli.Saidi@ARM.com    def order_obj(obj):
5047816Ssteve.reinhardt@amd.com        name = str(obj)
5055798Snate@binkert.org        if name in obj_seen:
5065798Snate@binkert.org            return
5075517Snate@binkert.org
5085517Snate@binkert.org        obj_seen.add(name)
5097673Snate@binkert.org        if str(obj) != 'SimObject':
5105517Snate@binkert.org            order_obj(obj.__bases__[0])
5115517Snate@binkert.org
5127673Snate@binkert.org        ordered_objs.append(obj)
5137673Snate@binkert.org
5145517Snate@binkert.org    for obj in objs:
5155798Snate@binkert.org        order_obj(obj)
5165798Snate@binkert.org
5178333Snate@binkert.org    enums = set()
5187816Ssteve.reinhardt@amd.com    predecls = []
5195798Snate@binkert.org    pd_seen = set()
5205798Snate@binkert.org
5214762Snate@binkert.org    def add_pds(*pds):
5224762Snate@binkert.org        for pd in pds:
5234762Snate@binkert.org            if pd not in pd_seen:
5244762Snate@binkert.org                predecls.append(pd)
5254762Snate@binkert.org                pd_seen.add(pd)
5265517Snate@binkert.org
5275517Snate@binkert.org    for obj in ordered_objs:
5285517Snate@binkert.org        params = obj._params.local.values()
5295517Snate@binkert.org        for param in params:
5305517Snate@binkert.org            ptype = param.ptype
5315517Snate@binkert.org            if issubclass(ptype, m5.params.Enum):
5327673Snate@binkert.org                if ptype not in enums:
5337673Snate@binkert.org                    enums.add(ptype)
5347673Snate@binkert.org            pds = param.swig_predecls()
5355517Snate@binkert.org            if isinstance(pds, (list, tuple)):
5365517Snate@binkert.org                add_pds(*pds)
5375517Snate@binkert.org            else:
5385517Snate@binkert.org                add_pds(pds)
5395517Snate@binkert.org
5405517Snate@binkert.org    print >>out, '%module params'
5415517Snate@binkert.org
5427673Snate@binkert.org    print >>out, '%{'
5437677Snate@binkert.org    for obj in ordered_objs:
5447673Snate@binkert.org        print >>out, '#include "params/%s.hh"' % obj
5457673Snate@binkert.org    print >>out, '%}'
5465517Snate@binkert.org
5475517Snate@binkert.org    for pd in predecls:
5485517Snate@binkert.org        print >>out, pd
5495517Snate@binkert.org
5505517Snate@binkert.org    enums = list(enums)
5515517Snate@binkert.org    enums.sort()
5525517Snate@binkert.org    for enum in enums:
5537673Snate@binkert.org        print >>out, '%%include "enums/%s.hh"' % enum.__name__
5547673Snate@binkert.org    print >>out
5557673Snate@binkert.org
5565517Snate@binkert.org    for obj in ordered_objs:
5575517Snate@binkert.org        if obj.swig_objdecls:
5585517Snate@binkert.org            for decl in obj.swig_objdecls:
5595517Snate@binkert.org                print >>out, decl
5605517Snate@binkert.org            continue
5615517Snate@binkert.org
5625517Snate@binkert.org        class_path = obj.cxx_class.split('::')
5637673Snate@binkert.org        classname = class_path[-1]
5647673Snate@binkert.org        namespaces = class_path[:-1]
5657673Snate@binkert.org        namespaces.reverse()
5665517Snate@binkert.org
5677675Snate@binkert.org        code = ''
5687675Snate@binkert.org
5697675Snate@binkert.org        if namespaces:
5707675Snate@binkert.org            code += '// avoid name conflicts\n'
5717675Snate@binkert.org            sep_string = '_COLONS_'
5727675Snate@binkert.org            flat_name = sep_string.join(class_path)
5737675Snate@binkert.org            code += '%%rename(%s) %s;\n' % (flat_name, classname)
5747675Snate@binkert.org
5757677Snate@binkert.org        code += '// stop swig from creating/wrapping default ctor/dtor\n'
5767675Snate@binkert.org        code += '%%nodefault %s;\n' % classname
5777675Snate@binkert.org        code += 'class %s ' % classname
5787675Snate@binkert.org        if obj._base:
5797675Snate@binkert.org            code += ': public %s' % obj._base.cxx_class
5807675Snate@binkert.org        code += ' {};\n'
5817675Snate@binkert.org
5827675Snate@binkert.org        for ns in namespaces:
5837675Snate@binkert.org            new_code = 'namespace %s {\n' % ns
5847675Snate@binkert.org            new_code += code
5854762Snate@binkert.org            new_code += '}\n'
5864762Snate@binkert.org            code = new_code
5876143Snate@binkert.org
5886143Snate@binkert.org        print >>out, code
5896143Snate@binkert.org
5904762Snate@binkert.org    print >>out, '%%include "src/sim/sim_object_params.hh"' % obj
5914762Snate@binkert.org    for obj in ordered_objs:
5924762Snate@binkert.org        print >>out, '%%include "params/%s.hh"' % obj
5937756SAli.Saidi@ARM.com
5947816Ssteve.reinhardt@amd.comparams_file = File('params/params.i')
5954762Snate@binkert.orgnames = sorted(sim_objects.keys())
5964762Snate@binkert.orgenv.Command(params_file, map(Value, names), buildParams)
5974762Snate@binkert.orgenv.Depends(params_file, params_hh_files + params_i_files + depends)
5985463Snate@binkert.orgSwigSource('m5.objects', params_file)
5995517Snate@binkert.org
6007677Snate@binkert.org# Build all swig modules
6015463Snate@binkert.orgfor swig in SwigSource.all:
6027756SAli.Saidi@ARM.com    env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
6037816Ssteve.reinhardt@amd.com                '$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
6044762Snate@binkert.org                '-o ${TARGETS[0]} $SOURCES')
6057677Snate@binkert.org    env.Depends(swig.py_source.tnode, swig.tnode)
6064762Snate@binkert.org    env.Depends(swig.cc_source.tnode, swig.tnode)
6074762Snate@binkert.org
6086143Snate@binkert.org# Generate the main swig init file
6096143Snate@binkert.orgdef makeSwigInit(target, source, env):
6106143Snate@binkert.org    f = file(str(target[0]), 'w')
6114762Snate@binkert.org    print >>f, 'extern "C" {'
6124762Snate@binkert.org    for module in source:
6137756SAli.Saidi@ARM.com        print >>f, '    void init_%s();' % module.get_contents()
6147816Ssteve.reinhardt@amd.com    print >>f, '}'
6154762Snate@binkert.org    print >>f, 'void initSwig() {'
6164762Snate@binkert.org    for module in source:
6174762Snate@binkert.org        print >>f, '    init_%s();' % module.get_contents()
6184762Snate@binkert.org    print >>f, '}'
6197756SAli.Saidi@ARM.com    f.close()
6207816Ssteve.reinhardt@amd.com
6214762Snate@binkert.orgenv.Command('python/swig/init.cc',
6224762Snate@binkert.org            map(Value, sorted(s.module for s in SwigSource.all)),
6237677Snate@binkert.org            makeSwigInit)
6247756SAli.Saidi@ARM.comSource('python/swig/init.cc')
6257816Ssteve.reinhardt@amd.com
6267675Snate@binkert.orgdef getFlags(source_flags):
6277677Snate@binkert.org    flagsMap = {}
6285517Snate@binkert.org    flagsList = []
6297675Snate@binkert.org    for s in source_flags:
6307675Snate@binkert.org        val = eval(s.get_contents())
6317675Snate@binkert.org        name, compound, desc = val
6327675Snate@binkert.org        flagsList.append(val)
6337675Snate@binkert.org        flagsMap[name] = bool(compound)
6347675Snate@binkert.org    
6357675Snate@binkert.org    for name, compound, desc in flagsList:
6365517Snate@binkert.org        for flag in compound:
6377673Snate@binkert.org            if flag not in flagsMap:
6385517Snate@binkert.org                raise AttributeError, "Trace flag %s not found" % flag
6397677Snate@binkert.org            if flagsMap[flag]:
6407675Snate@binkert.org                raise AttributeError, \
6417673Snate@binkert.org                    "Compound flag can't point to another compound flag"
6427675Snate@binkert.org
6437675Snate@binkert.org    flagsList.sort()
6447675Snate@binkert.org    return flagsList
6457673Snate@binkert.org
6467675Snate@binkert.org
6475517Snate@binkert.org# Generate traceflags.py
6487675Snate@binkert.orgdef traceFlagsPy(target, source, env):
6497675Snate@binkert.org    assert(len(target) == 1)
6507673Snate@binkert.org
6517675Snate@binkert.org    f = file(str(target[0]), 'w')
6527675Snate@binkert.org   
6537677Snate@binkert.org    allFlags = getFlags(source)
6547675Snate@binkert.org
6557675Snate@binkert.org    print >>f, 'basic = ['
6567675Snate@binkert.org    for flag, compound, desc in allFlags:
6575517Snate@binkert.org        if not compound:
6587675Snate@binkert.org            print >>f, "    '%s'," % flag
6595517Snate@binkert.org    print >>f, "    ]"
6607673Snate@binkert.org    print >>f
6615517Snate@binkert.org
6627675Snate@binkert.org    print >>f, 'compound = ['
6637677Snate@binkert.org    print >>f, "    'All',"
6647756SAli.Saidi@ARM.com    for flag, compound, desc in allFlags:
6657816Ssteve.reinhardt@amd.com        if compound:
6667675Snate@binkert.org            print >>f, "    '%s'," % flag
6677677Snate@binkert.org    print >>f, "    ]"
6684762Snate@binkert.org    print >>f
6697674Snate@binkert.org
6707674Snate@binkert.org    print >>f, "all = frozenset(basic + compound)"
6717674Snate@binkert.org    print >>f
6727674Snate@binkert.org
6737674Snate@binkert.org    print >>f, 'compoundMap = {'
6747674Snate@binkert.org    all = tuple([flag for flag,compound,desc in allFlags if not compound])
6757674Snate@binkert.org    print >>f, "    'All' : %s," % (all, )
6767674Snate@binkert.org    for flag, compound, desc in allFlags:
6777674Snate@binkert.org        if compound:
6787674Snate@binkert.org            print >>f, "    '%s' : %s," % (flag, compound)
6797674Snate@binkert.org    print >>f, "    }"
6807674Snate@binkert.org    print >>f
6817674Snate@binkert.org
6827674Snate@binkert.org    print >>f, 'descriptions = {'
6837674Snate@binkert.org    print >>f, "    'All' : 'All flags',"
6844762Snate@binkert.org    for flag, compound, desc in allFlags:
6856143Snate@binkert.org        print >>f, "    '%s' : '%s'," % (flag, desc)
6866143Snate@binkert.org    print >>f, "    }"
6877756SAli.Saidi@ARM.com
6887816Ssteve.reinhardt@amd.com    f.close()
6898235Snate@binkert.org
6908235Snate@binkert.orgdef traceFlagsCC(target, source, env):
6917756SAli.Saidi@ARM.com    assert(len(target) == 1)
6927816Ssteve.reinhardt@amd.com
6938235Snate@binkert.org    f = file(str(target[0]), 'w')
6944382Sbinkertn@umich.edu
6958232Snate@binkert.org    allFlags = getFlags(source)
6968232Snate@binkert.org
6978232Snate@binkert.org    # file header
6988232Snate@binkert.org    print >>f, '''
6998232Snate@binkert.org/*
7006229Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated
7018232Snate@binkert.org */
7028232Snate@binkert.org
7038232Snate@binkert.org#include "base/traceflags.hh"
7046229Snate@binkert.org
7057673Snate@binkert.orgusing namespace Trace;
7065517Snate@binkert.org
7075517Snate@binkert.orgconst char *Trace::flagStrings[] =
7087673Snate@binkert.org{'''
7095517Snate@binkert.org
7105517Snate@binkert.org    # The string array is used by SimpleEnumParam to map the strings
7115517Snate@binkert.org    # provided by the user to enum values.
7125517Snate@binkert.org    for flag, compound, desc in allFlags:
7138232Snate@binkert.org        if not compound:
7147673Snate@binkert.org            print >>f, '    "%s",' % flag
7157673Snate@binkert.org
7168232Snate@binkert.org    print >>f, '    "All",'
7178232Snate@binkert.org    for flag, compound, desc in allFlags:
7188232Snate@binkert.org        if compound:
7198232Snate@binkert.org            print >>f, '    "%s",' % flag
7207673Snate@binkert.org
7215517Snate@binkert.org    print >>f, '};'
7228232Snate@binkert.org    print >>f
7238232Snate@binkert.org    print >>f, 'const int Trace::numFlagStrings = %d;' % (len(allFlags) + 1)
7248232Snate@binkert.org    print >>f
7258232Snate@binkert.org
7267673Snate@binkert.org    #
7278232Snate@binkert.org    # Now define the individual compound flag arrays.  There is an array
7288232Snate@binkert.org    # for each compound flag listing the component base flags.
7298232Snate@binkert.org    #
7308232Snate@binkert.org    all = tuple([flag for flag,compound,desc in allFlags if not compound])
7318232Snate@binkert.org    print >>f, 'static const Flags AllMap[] = {'
7328232Snate@binkert.org    for flag, compound, desc in allFlags:
7337673Snate@binkert.org        if not compound:
7345517Snate@binkert.org            print >>f, "    %s," % flag
7358232Snate@binkert.org    print >>f, '};'
7368232Snate@binkert.org    print >>f
7375517Snate@binkert.org
7387673Snate@binkert.org    for flag, compound, desc in allFlags:
7395517Snate@binkert.org        if not compound:
7408232Snate@binkert.org            continue
7418232Snate@binkert.org        print >>f, 'static const Flags %sMap[] = {' % flag
7425517Snate@binkert.org        for flag in compound:
7438232Snate@binkert.org            print >>f, "    %s," % flag
7448232Snate@binkert.org        print >>f, "    (Flags)-1"
7458232Snate@binkert.org        print >>f, '};'
7467673Snate@binkert.org        print >>f
7475517Snate@binkert.org
7485517Snate@binkert.org    #
7497673Snate@binkert.org    # Finally the compoundFlags[] array maps the compound flags
7505517Snate@binkert.org    # to their individual arrays/
7515517Snate@binkert.org    #
7525517Snate@binkert.org    print >>f, 'const Flags *Trace::compoundFlags[] ='
7538232Snate@binkert.org    print >>f, '{'
7545517Snate@binkert.org    print >>f, '    AllMap,'
7555517Snate@binkert.org    for flag, compound, desc in allFlags:
7568232Snate@binkert.org        if compound:
7578232Snate@binkert.org            print >>f, '    %sMap,' % flag
7585517Snate@binkert.org    # file trailer
7598232Snate@binkert.org    print >>f, '};'
7608232Snate@binkert.org
7615517Snate@binkert.org    f.close()
7628232Snate@binkert.org
7638232Snate@binkert.orgdef traceFlagsHH(target, source, env):
7648232Snate@binkert.org    assert(len(target) == 1)
7655517Snate@binkert.org
7668232Snate@binkert.org    f = file(str(target[0]), 'w')
7678232Snate@binkert.org
7688232Snate@binkert.org    allFlags = getFlags(source)
7698232Snate@binkert.org
7708232Snate@binkert.org    # file header boilerplate
7718232Snate@binkert.org    print >>f, '''
7725517Snate@binkert.org/*
7738232Snate@binkert.org * DO NOT EDIT THIS FILE!
7748232Snate@binkert.org *
7755517Snate@binkert.org * Automatically generated from traceflags.py
7768232Snate@binkert.org */
7777673Snate@binkert.org
7785517Snate@binkert.org#ifndef __BASE_TRACE_FLAGS_HH__
7797673Snate@binkert.org#define __BASE_TRACE_FLAGS_HH__
7805517Snate@binkert.org
7818232Snate@binkert.orgnamespace Trace {
7828232Snate@binkert.org
7838232Snate@binkert.orgenum Flags {'''
7845192Ssaidi@eecs.umich.edu
7858232Snate@binkert.org    # Generate the enum.  Base flags come first, then compound flags.
7868232Snate@binkert.org    idx = 0
7878232Snate@binkert.org    for flag, compound, desc in allFlags:
7888232Snate@binkert.org        if not compound:
7898232Snate@binkert.org            print >>f, '    %s = %d,' % (flag, idx)
7905192Ssaidi@eecs.umich.edu            idx += 1
7917674Snate@binkert.org
7925522Snate@binkert.org    numBaseFlags = idx
7935522Snate@binkert.org    print >>f, '    NumFlags = %d,' % idx
7947674Snate@binkert.org
7957674Snate@binkert.org    # put a comment in here to separate base from compound flags
7967674Snate@binkert.org    print >>f, '''
7977674Snate@binkert.org// The remaining enum values are *not* valid indices for Trace::flags.
7987674Snate@binkert.org// They are "compound" flags, which correspond to sets of base
7997674Snate@binkert.org// flags, and are used by changeFlag.'''
8007674Snate@binkert.org
8017674Snate@binkert.org    print >>f, '    All = %d,' % idx
8025522Snate@binkert.org    idx += 1
8035522Snate@binkert.org    for flag, compound, desc in allFlags:
8045522Snate@binkert.org        if compound:
8055517Snate@binkert.org            print >>f, '    %s = %d,' % (flag, idx)
8065522Snate@binkert.org            idx += 1
8075517Snate@binkert.org
8086143Snate@binkert.org    numCompoundFlags = idx - numBaseFlags
8096727Ssteve.reinhardt@amd.com    print >>f, '    NumCompoundFlags = %d' % numCompoundFlags
8105522Snate@binkert.org
8115522Snate@binkert.org    # trailer boilerplate
8125522Snate@binkert.org    print >>f, '''\
8137674Snate@binkert.org}; // enum Flags
8145517Snate@binkert.org
8157673Snate@binkert.org// Array of strings for SimpleEnumParam
8167673Snate@binkert.orgextern const char *flagStrings[];
8177674Snate@binkert.orgextern const int numFlagStrings;
8187673Snate@binkert.org
8197674Snate@binkert.org// Array of arraay pointers: for each compound flag, gives the list of
8207674Snate@binkert.org// base flags to set.  Inidividual flag arrays are terminated by -1.
8217674Snate@binkert.orgextern const Flags *compoundFlags[];
8227674Snate@binkert.org
8237674Snate@binkert.org/* namespace Trace */ }
8247674Snate@binkert.org
8255522Snate@binkert.org#endif // __BASE_TRACE_FLAGS_HH__
8265522Snate@binkert.org'''
8277674Snate@binkert.org
8287674Snate@binkert.org    f.close()
8297674Snate@binkert.org
8307674Snate@binkert.orgflags = map(Value, trace_flags.values())
8317673Snate@binkert.orgenv.Command('base/traceflags.py', flags, traceFlagsPy)
8327674Snate@binkert.orgPySource('m5', 'base/traceflags.py')
8337674Snate@binkert.org
8347674Snate@binkert.orgenv.Command('base/traceflags.hh', flags, traceFlagsHH)
8357674Snate@binkert.orgenv.Command('base/traceflags.cc', flags, traceFlagsCC)
8367674Snate@binkert.orgSource('base/traceflags.cc')
8377674Snate@binkert.org
8387674Snate@binkert.org# embed python files.  All .py files that have been indicated by a
8397674Snate@binkert.org# PySource() call in a SConscript need to be embedded into the M5
8407811Ssteve.reinhardt@amd.com# library.  To do that, we compile the file to byte code, marshal the
8417674Snate@binkert.org# byte code, compress it, and then generate an assembly file that
8427673Snate@binkert.org# inserts the result into the data section with symbols indicating the
8435522Snate@binkert.org# beginning, and end (and with the size at the end)
8446143Snate@binkert.orgdef objectifyPyFile(target, source, env):
8457756SAli.Saidi@ARM.com    '''Action function to compile a .py into a code object, marshal
8467816Ssteve.reinhardt@amd.com    it, compress it, and stick it into an asm file so the code appears
8477674Snate@binkert.org    as just bytes with a label in the data section'''
8484382Sbinkertn@umich.edu
8494382Sbinkertn@umich.edu    src = file(str(source[0]), 'r').read()
8504382Sbinkertn@umich.edu    dst = file(str(target[0]), 'w')
8514382Sbinkertn@umich.edu
8524382Sbinkertn@umich.edu    pysource = PySource.tnodes[source[0]]
8534382Sbinkertn@umich.edu    compiled = compile(src, pysource.debugname, 'exec')
8544382Sbinkertn@umich.edu    marshalled = marshal.dumps(compiled)
8554382Sbinkertn@umich.edu    compressed = zlib.compress(marshalled)
8564382Sbinkertn@umich.edu    data = compressed
8574382Sbinkertn@umich.edu
8586143Snate@binkert.org    # Some C/C++ compilers prepend an underscore to global symbol
859955SN/A    # names, so if they're going to do that, we need to prepend that
8602655Sstever@eecs.umich.edu    # leading underscore to globals in the assembly file.
8612655Sstever@eecs.umich.edu    if env['LEADING_UNDERSCORE']:
8622655Sstever@eecs.umich.edu        sym = '_' + pysource.symname
8632655Sstever@eecs.umich.edu    else:
8642655Sstever@eecs.umich.edu        sym = pysource.symname
8655601Snate@binkert.org
8665601Snate@binkert.org    step = 16
8678334Snate@binkert.org    print >>dst, ".data"
8688334Snate@binkert.org    print >>dst, ".globl %s_beg" % sym
8698334Snate@binkert.org    print >>dst, ".globl %s_end" % sym
8705522Snate@binkert.org    print >>dst, "%s_beg:" % sym
8715863Snate@binkert.org    for i in xrange(0, len(data), step):
8725601Snate@binkert.org        x = array.array('B', data[i:i+step])
8735601Snate@binkert.org        print >>dst, ".byte", ','.join([str(d) for d in x])
8745601Snate@binkert.org    print >>dst, "%s_end:" % sym
8755863Snate@binkert.org    print >>dst, ".long %d" % len(marshalled)
8766143Snate@binkert.org
8775559Snate@binkert.orgfor source in PySource.all:
8785559Snate@binkert.org    env.Command(source.assembly, source.tnode, objectifyPyFile)
8795559Snate@binkert.org    Source(source.assembly)
8805559Snate@binkert.org
8815601Snate@binkert.org# Generate init_python.cc which creates a bunch of EmbeddedPyModule
8826143Snate@binkert.org# structs that describe the embedded python code.  One such struct
8836143Snate@binkert.org# contains information about the importer that python uses to get at
8846143Snate@binkert.org# the embedded files, and then there's a list of all of the rest that
8856143Snate@binkert.org# the importer uses to load the rest on demand.
8866143Snate@binkert.orgdef pythonInit(target, source, env):
8876143Snate@binkert.org    dst = file(str(target[0]), 'w')
8886143Snate@binkert.org
8896143Snate@binkert.org    def dump_mod(sym, endchar=','):
8906143Snate@binkert.org        pysource = PySource.symnames[sym]
8916143Snate@binkert.org        print >>dst, '    { "%s",' % pysource.arcname
8926143Snate@binkert.org        print >>dst, '      "%s",' % pysource.modpath
8936143Snate@binkert.org        print >>dst, '       %s_beg, %s_end,' % (sym, sym)
8946143Snate@binkert.org        print >>dst, '       %s_end - %s_beg,' % (sym, sym)
8956143Snate@binkert.org        print >>dst, '       *(int *)%s_end }%s'  % (sym, endchar)
8966143Snate@binkert.org    
8976143Snate@binkert.org    print >>dst, '#include "sim/init.hh"'
8986143Snate@binkert.org
8996143Snate@binkert.org    for sym in source:
9006143Snate@binkert.org        sym = sym.get_contents()
9016143Snate@binkert.org        print >>dst, "extern const char %s_beg[], %s_end[];" % (sym, sym)
9026143Snate@binkert.org
9036143Snate@binkert.org    print >>dst, "const EmbeddedPyModule embeddedPyImporter = "
9046143Snate@binkert.org    dump_mod("PyEMB_importer", endchar=';');
9056143Snate@binkert.org    print >>dst
9066143Snate@binkert.org
9078233Snate@binkert.org    print >>dst, "const EmbeddedPyModule embeddedPyModules[] = {"
9088233Snate@binkert.org    for i,sym in enumerate(source):
9098233Snate@binkert.org        sym = sym.get_contents()
9106143Snate@binkert.org        if sym == "PyEMB_importer":
9116143Snate@binkert.org            # Skip the importer since we've already exported it
9126143Snate@binkert.org            continue
9136143Snate@binkert.org        dump_mod(sym)
9146143Snate@binkert.org    print >>dst, "    { 0, 0, 0, 0, 0, 0 }"
9156240Snate@binkert.org    print >>dst, "};"
9165554Snate@binkert.org
9175522Snate@binkert.org
9185522Snate@binkert.orgenv.Command('sim/init_python.cc',
9195797Snate@binkert.org            map(Value, (s.symname for s in PySource.all)),
9205797Snate@binkert.org            pythonInit)
9215522Snate@binkert.orgSource('sim/init_python.cc')
9225601Snate@binkert.org
9238233Snate@binkert.org########################################################################
9248233Snate@binkert.org#
9258235Snate@binkert.org# Define binaries.  Each different build type (debug, opt, etc.) gets
9268235Snate@binkert.org# a slightly different build environment.
9278235Snate@binkert.org#
9288235Snate@binkert.org
9298235Snate@binkert.org# List of constructed environments to pass back to SConstruct
9308235Snate@binkert.orgenvList = []
9318235Snate@binkert.org
9326143Snate@binkert.orgdate_source = Source('base/date.cc', skip_lib=True)
9332655Sstever@eecs.umich.edu
9346143Snate@binkert.org# Function to create a new build environment as clone of current
9356143Snate@binkert.org# environment 'env' with modified object suffix and optional stripped
9368233Snate@binkert.org# binary.  Additional keyword arguments are appended to corresponding
9376143Snate@binkert.org# build environment vars.
9386143Snate@binkert.orgdef makeEnv(label, objsfx, strip = False, **kwargs):
9394007Ssaidi@eecs.umich.edu    # SCons doesn't know to append a library suffix when there is a '.' in the
9404596Sbinkertn@umich.edu    # name.  Use '_' instead.
9414007Ssaidi@eecs.umich.edu    libname = 'm5_' + label
9424596Sbinkertn@umich.edu    exename = 'm5.' + label
9437756SAli.Saidi@ARM.com
9447816Ssteve.reinhardt@amd.com    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
9458334Snate@binkert.org    new_env.Label = label
9468334Snate@binkert.org    new_env.Append(**kwargs)
9478334Snate@binkert.org
9488334Snate@binkert.org    swig_env = new_env.Clone()
9495601Snate@binkert.org    swig_env.Append(CCFLAGS='-Werror')
9505601Snate@binkert.org    if env['GCC']:
9512655Sstever@eecs.umich.edu        swig_env.Append(CCFLAGS='-Wno-uninitialized')
952955SN/A        swig_env.Append(CCFLAGS='-Wno-sign-compare')
9533918Ssaidi@eecs.umich.edu        swig_env.Append(CCFLAGS='-Wno-parentheses')
9543918Ssaidi@eecs.umich.edu
9553918Ssaidi@eecs.umich.edu    werror_env = new_env.Clone()
9563918Ssaidi@eecs.umich.edu    werror_env.Append(CCFLAGS='-Werror')
9573918Ssaidi@eecs.umich.edu
9583918Ssaidi@eecs.umich.edu    def make_obj(source, static, extra_deps = None):
9593918Ssaidi@eecs.umich.edu        '''This function adds the specified source to the correct
9603918Ssaidi@eecs.umich.edu        build environment, and returns the corresponding SCons Object
9613918Ssaidi@eecs.umich.edu        nodes'''
9623918Ssaidi@eecs.umich.edu
9633918Ssaidi@eecs.umich.edu        if source.swig:
9643918Ssaidi@eecs.umich.edu            env = swig_env
9653918Ssaidi@eecs.umich.edu        elif source.Werror:
9663918Ssaidi@eecs.umich.edu            env = werror_env
9673940Ssaidi@eecs.umich.edu        else:
9683940Ssaidi@eecs.umich.edu            env = new_env
9693940Ssaidi@eecs.umich.edu
9703942Ssaidi@eecs.umich.edu        if static:
9713940Ssaidi@eecs.umich.edu            obj = env.StaticObject(source.tnode)
9723515Ssaidi@eecs.umich.edu        else:
9733918Ssaidi@eecs.umich.edu            obj = env.SharedObject(source.tnode)
9744762Snate@binkert.org
9753515Ssaidi@eecs.umich.edu        if extra_deps:
9762655Sstever@eecs.umich.edu            env.Depends(obj, extra_deps)
9773918Ssaidi@eecs.umich.edu
9783619Sbinkertn@umich.edu        return obj
979955SN/A
980955SN/A    static_objs = [ make_obj(s, True) for s in Source.get(skip_lib=False)]
9812655Sstever@eecs.umich.edu    shared_objs = [ make_obj(s, False) for s in Source.get(skip_lib=False)]
9823918Ssaidi@eecs.umich.edu
9833619Sbinkertn@umich.edu    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
984955SN/A    static_objs.append(static_date)
985955SN/A    
9862655Sstever@eecs.umich.edu    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
9873918Ssaidi@eecs.umich.edu    shared_objs.append(shared_date)
9883619Sbinkertn@umich.edu
989955SN/A    # First make a library of everything but main() so other programs can
990955SN/A    # link against m5.
9912655Sstever@eecs.umich.edu    static_lib = new_env.StaticLibrary(libname, static_objs)
9923918Ssaidi@eecs.umich.edu    shared_lib = new_env.SharedLibrary(libname, shared_objs)
9933683Sstever@eecs.umich.edu
9942655Sstever@eecs.umich.edu    for target, sources in unit_tests:
9951869SN/A        objs = [ make_obj(s, static=True) for s in sources ]
9961869SN/A        new_env.Program("unittest/%s.%s" % (target, label), objs + static_objs)
997
998    # Now link a stub with main() and the static library.
999    bin_objs = [make_obj(s, True) for s in Source.get(bin_only=True) ]
1000    progname = exename
1001    if strip:
1002        progname += '.unstripped'
1003
1004    targets = new_env.Program(progname, bin_objs + static_objs)
1005
1006    if strip:
1007        if sys.platform == 'sunos5':
1008            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
1009        else:
1010            cmd = 'strip $SOURCE -o $TARGET'
1011        targets = new_env.Command(exename, progname, cmd)
1012            
1013    new_env.M5Binary = targets[0]
1014    envList.append(new_env)
1015
1016# Debug binary
1017ccflags = {}
1018if env['GCC']:
1019    if sys.platform == 'sunos5':
1020        ccflags['debug'] = '-gstabs+'
1021    else:
1022        ccflags['debug'] = '-ggdb3'
1023    ccflags['opt'] = '-g -O3'
1024    ccflags['fast'] = '-O3'
1025    ccflags['prof'] = '-O3 -g -pg'
1026elif env['SUNCC']:
1027    ccflags['debug'] = '-g0'
1028    ccflags['opt'] = '-g -O'
1029    ccflags['fast'] = '-fast'
1030    ccflags['prof'] = '-fast -g -pg'
1031elif env['ICC']:
1032    ccflags['debug'] = '-g -O0'
1033    ccflags['opt'] = '-g -O'
1034    ccflags['fast'] = '-fast'
1035    ccflags['prof'] = '-fast -g -pg'
1036else:
1037    print 'Unknown compiler, please fix compiler options'
1038    Exit(1)
1039
1040makeEnv('debug', '.do',
1041        CCFLAGS = Split(ccflags['debug']),
1042        CPPDEFINES = ['DEBUG', 'TRACING_ON=1'])
1043
1044# Optimized binary
1045makeEnv('opt', '.o',
1046        CCFLAGS = Split(ccflags['opt']),
1047        CPPDEFINES = ['TRACING_ON=1'])
1048
1049# "Fast" binary
1050makeEnv('fast', '.fo', strip = True,
1051        CCFLAGS = Split(ccflags['fast']),
1052        CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'])
1053
1054# Profiled binary
1055makeEnv('prof', '.po',
1056        CCFLAGS = Split(ccflags['prof']),
1057        CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1058        LINKFLAGS = '-pg')
1059
1060Return('envList')
1061