SConscript revision 7067
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
3711974Sgabeblack@google.comimport sys
38955SN/Aimport zlib
395522Snate@binkert.org
404202Sbinkertn@umich.edufrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
415742Snate@binkert.org
42955SN/Aimport SCons
434381Sbinkertn@umich.edu
444381Sbinkertn@umich.edu# This file defines how to build a particular configuration of M5
4512246Sgabeblack@google.com# based on variable settings in the 'env' build environment.
4612246Sgabeblack@google.com
478334Snate@binkert.orgImport('*')
48955SN/A
49955SN/A# Children need to see the environment
504202Sbinkertn@umich.eduExport('env')
51955SN/A
524382Sbinkertn@umich.edubuild_env = [(opt, env[opt]) for opt in export_vars]
534382Sbinkertn@umich.edu
544382Sbinkertn@umich.edu########################################################################
556654Snate@binkert.org# Code for adding source files of various types
565517Snate@binkert.org#
578614Sgblack@eecs.umich.educlass SourceMeta(type):
587674Snate@binkert.org    def __init__(cls, name, bases, dict):
596143Snate@binkert.org        super(SourceMeta, cls).__init__(name, bases, dict)
606143Snate@binkert.org        cls.all = []
616143Snate@binkert.org        
6212302Sgabeblack@google.com    def get(cls, **kwargs):
6312302Sgabeblack@google.com        for src in cls.all:
6412302Sgabeblack@google.com            for attr,value in kwargs.iteritems():
6512302Sgabeblack@google.com                if getattr(src, attr) != value:
6612302Sgabeblack@google.com                    break
6712302Sgabeblack@google.com            else:
6812302Sgabeblack@google.com                yield src
6912302Sgabeblack@google.com
7012302Sgabeblack@google.comclass SourceFile(object):
7112302Sgabeblack@google.com    __metaclass__ = SourceMeta
7212302Sgabeblack@google.com    def __init__(self, source):
7312302Sgabeblack@google.com        tnode = source
7412363Sgabeblack@google.com        if not isinstance(source, SCons.Node.FS.File):
7512302Sgabeblack@google.com            tnode = File(source)
7612302Sgabeblack@google.com
7712302Sgabeblack@google.com        self.tnode = tnode
7812363Sgabeblack@google.com        self.snode = tnode.srcnode()
7912302Sgabeblack@google.com        self.filename = str(tnode)
8012302Sgabeblack@google.com        self.dirname = dirname(self.filename)
8112302Sgabeblack@google.com        self.basename = basename(self.filename)
8212302Sgabeblack@google.com        index = self.basename.rfind('.')
8312302Sgabeblack@google.com        if index <= 0:
8412302Sgabeblack@google.com            # dot files aren't extensions
8512302Sgabeblack@google.com            self.extname = self.basename, None
8612363Sgabeblack@google.com        else:
8712302Sgabeblack@google.com            self.extname = self.basename[:index], self.basename[index+1:]
8812302Sgabeblack@google.com
8912302Sgabeblack@google.com        for base in type(self).__mro__:
9012302Sgabeblack@google.com            if issubclass(base, SourceFile):
9111983Sgabeblack@google.com                base.all.append(self)
926143Snate@binkert.org
938233Snate@binkert.org    def __lt__(self, other): return self.filename < other.filename
9412302Sgabeblack@google.com    def __le__(self, other): return self.filename <= other.filename
956143Snate@binkert.org    def __gt__(self, other): return self.filename > other.filename
966143Snate@binkert.org    def __ge__(self, other): return self.filename >= other.filename
9712302Sgabeblack@google.com    def __eq__(self, other): return self.filename == other.filename
984762Snate@binkert.org    def __ne__(self, other): return self.filename != other.filename
996143Snate@binkert.org        
1008233Snate@binkert.orgclass Source(SourceFile):
1018233Snate@binkert.org    '''Add a c/c++ source file to the build'''
10212302Sgabeblack@google.com    def __init__(self, source, Werror=True, swig=False, bin_only=False,
10312302Sgabeblack@google.com                 skip_lib=False):
1046143Snate@binkert.org        super(Source, self).__init__(source)
10512362Sgabeblack@google.com
10612362Sgabeblack@google.com        self.Werror = Werror
10712362Sgabeblack@google.com        self.swig = swig
10812362Sgabeblack@google.com        self.bin_only = bin_only
10912302Sgabeblack@google.com        self.skip_lib = bin_only or skip_lib
11012302Sgabeblack@google.com
11112302Sgabeblack@google.comclass PySource(SourceFile):
11212302Sgabeblack@google.com    '''Add a python source file to the named package'''
11312302Sgabeblack@google.com    invalid_sym_char = re.compile('[^A-z0-9_]')
11412363Sgabeblack@google.com    modules = {}
11512363Sgabeblack@google.com    tnodes = {}
11612363Sgabeblack@google.com    symnames = {}
11712363Sgabeblack@google.com    
11812302Sgabeblack@google.com    def __init__(self, package, source):
11912363Sgabeblack@google.com        super(PySource, self).__init__(source)
12012363Sgabeblack@google.com
12112363Sgabeblack@google.com        modname,ext = self.extname
12212363Sgabeblack@google.com        assert ext == 'py'
12312363Sgabeblack@google.com
1248233Snate@binkert.org        if package:
1256143Snate@binkert.org            path = package.split('.')
1266143Snate@binkert.org        else:
1276143Snate@binkert.org            path = []
1286143Snate@binkert.org
1296143Snate@binkert.org        modpath = path[:]
1306143Snate@binkert.org        if modname != '__init__':
1316143Snate@binkert.org            modpath += [ modname ]
1326143Snate@binkert.org        modpath = '.'.join(modpath)
1336143Snate@binkert.org
1347065Snate@binkert.org        arcpath = path + [ self.basename ]
1356143Snate@binkert.org        abspath = self.snode.abspath
13612362Sgabeblack@google.com        if not exists(abspath):
13712362Sgabeblack@google.com            abspath = self.tnode.abspath
13812362Sgabeblack@google.com
13912362Sgabeblack@google.com        self.package = package
14012362Sgabeblack@google.com        self.modname = modname
14112362Sgabeblack@google.com        self.modpath = modpath
14212362Sgabeblack@google.com        self.arcname = joinpath(*arcpath)
14312362Sgabeblack@google.com        self.abspath = abspath
14412362Sgabeblack@google.com        self.compiled = File(self.filename + 'c')
14512362Sgabeblack@google.com        self.assembly = File(self.filename + '.s')
14612362Sgabeblack@google.com        self.symname = "PyEMB_" + PySource.invalid_sym_char.sub('_', modpath)
14712362Sgabeblack@google.com
1488233Snate@binkert.org        PySource.modules[modpath] = self
1498233Snate@binkert.org        PySource.tnodes[self.tnode] = self
1508233Snate@binkert.org        PySource.symnames[self.symname] = self
1518233Snate@binkert.org
1528233Snate@binkert.orgclass SimObject(PySource):
1538233Snate@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
1578233Snate@binkert.org    modnames = []
1588233Snate@binkert.org
1598233Snate@binkert.org    def __init__(self, source):
1608233Snate@binkert.org        super(SimObject, self).__init__('m5.objects', source)
1618233Snate@binkert.org        if self.fixed:
1628233Snate@binkert.org            raise AttributeError, "Too late to call SimObject now."
1638233Snate@binkert.org
1648233Snate@binkert.org        bisect.insort_right(SimObject.modnames, self.modname)
1658233Snate@binkert.org
1668233Snate@binkert.orgclass SwigSource(SourceFile):
1678233Snate@binkert.org    '''Add a swig file to build'''
1688233Snate@binkert.org
1696143Snate@binkert.org    def __init__(self, package, source):
1706143Snate@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
1759982Satgutier@umich.edu        self.module = modname
1766143Snate@binkert.org        cc_file = joinpath(self.dirname, modname + '_wrap.cc')
17712302Sgabeblack@google.com        py_file = joinpath(self.dirname, modname + '.py')
17812302Sgabeblack@google.com
17912302Sgabeblack@google.com        self.cc_source = Source(cc_file, swig=True)
18012302Sgabeblack@google.com        self.py_source = PySource(package, py_file)
18112302Sgabeblack@google.com
18212302Sgabeblack@google.comunit_tests = []
18312302Sgabeblack@google.comdef UnitTest(target, sources):
18412302Sgabeblack@google.com    if not isinstance(sources, (list, tuple)):
18511983Sgabeblack@google.com        sources = [ sources ]
18611983Sgabeblack@google.com
18711983Sgabeblack@google.com    sources = [ Source(src, skip_lib=True) for src in sources ]
18812302Sgabeblack@google.com    unit_tests.append((target, sources))
18912302Sgabeblack@google.com
19012302Sgabeblack@google.com# Children should have access
19112302Sgabeblack@google.comExport('Source')
19212302Sgabeblack@google.comExport('PySource')
19312302Sgabeblack@google.comExport('SimObject')
19411983Sgabeblack@google.comExport('SwigSource')
1956143Snate@binkert.orgExport('UnitTest')
19612305Sgabeblack@google.com
19712302Sgabeblack@google.com########################################################################
19812302Sgabeblack@google.com#
19912302Sgabeblack@google.com# Trace Flags
2006143Snate@binkert.org#
2016143Snate@binkert.orgtrace_flags = {}
2026143Snate@binkert.orgdef TraceFlag(name, desc=None):
2035522Snate@binkert.org    if name in trace_flags:
2046143Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
2056143Snate@binkert.org    trace_flags[name] = (name, (), desc)
2066143Snate@binkert.org
2079982Satgutier@umich.edudef CompoundFlag(name, flags, desc=None):
20812302Sgabeblack@google.com    if name in trace_flags:
20912302Sgabeblack@google.com        raise AttributeError, "Flag %s already specified" % name
21012302Sgabeblack@google.com
2116143Snate@binkert.org    compound = tuple(flags)
2126143Snate@binkert.org    trace_flags[name] = (name, compound, desc)
2136143Snate@binkert.org
2146143Snate@binkert.orgExport('TraceFlag')
2155522Snate@binkert.orgExport('CompoundFlag')
2165522Snate@binkert.org
2175522Snate@binkert.org########################################################################
2185522Snate@binkert.org#
2195604Snate@binkert.org# Set some compiler variables
2205604Snate@binkert.org#
2216143Snate@binkert.org
2226143Snate@binkert.org# Include file paths are rooted in this directory.  SCons will
2234762Snate@binkert.org# automatically expand '.' to refer to both the source directory and
2244762Snate@binkert.org# the corresponding build directory to pick up generated include
2256143Snate@binkert.org# files.
2266727Ssteve.reinhardt@amd.comenv.Append(CPPPATH=Dir('.'))
2276727Ssteve.reinhardt@amd.com
2286727Ssteve.reinhardt@amd.comfor extra_dir in extras_dir_list:
2294762Snate@binkert.org    env.Append(CPPPATH=Dir(extra_dir))
2306143Snate@binkert.org
2316143Snate@binkert.org# Workaround for bug in SCons version > 0.97d20071212
2326143Snate@binkert.org# Scons bug id: 2006 M5 Bug id: 308 
2336143Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
2346727Ssteve.reinhardt@amd.com    Dir(root[len(base_dir) + 1:])
2356143Snate@binkert.org
2367674Snate@binkert.org########################################################################
2377674Snate@binkert.org#
2385604Snate@binkert.org# Walk the tree and execute all SConscripts in subdirectories
2396143Snate@binkert.org#
2406143Snate@binkert.org
2416143Snate@binkert.orghere = Dir('.').srcnode().abspath
2424762Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
2436143Snate@binkert.org    if root == here:
2444762Snate@binkert.org        # we don't want to recurse back into this SConscript
2454762Snate@binkert.org        continue
2464762Snate@binkert.org
2476143Snate@binkert.org    if 'SConscript' in files:
2486143Snate@binkert.org        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
2494762Snate@binkert.org        SConscript(joinpath(root, 'SConscript'), build_dir=build_dir)
25012302Sgabeblack@google.com
25112302Sgabeblack@google.comfor extra_dir in extras_dir_list:
2528233Snate@binkert.org    prefix_len = len(dirname(extra_dir)) + 1
25312302Sgabeblack@google.com    for root, dirs, files in os.walk(extra_dir, topdown=True):
2546143Snate@binkert.org        if 'SConscript' in files:
2556143Snate@binkert.org            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
2564762Snate@binkert.org            SConscript(joinpath(root, 'SConscript'), build_dir=build_dir)
2576143Snate@binkert.org
2584762Snate@binkert.orgfor opt in export_vars:
2599396Sandreas.hansson@arm.com    env.ConfigFile(opt)
2609396Sandreas.hansson@arm.com
2619396Sandreas.hansson@arm.comdef makeTheISA(source, target, env):
26212302Sgabeblack@google.com    f = file(str(target[0]), 'w')
26312302Sgabeblack@google.com
26412302Sgabeblack@google.com    isas = [ src.get_contents() for src in source ]
2659396Sandreas.hansson@arm.com    target = env['TARGET_ISA']
2669396Sandreas.hansson@arm.com    def define(isa):
2679396Sandreas.hansson@arm.com        return isa.upper() + '_ISA'
2689396Sandreas.hansson@arm.com    
2699396Sandreas.hansson@arm.com    def namespace(isa):
2709396Sandreas.hansson@arm.com        return isa[0].upper() + isa[1:].lower() + 'ISA' 
2719396Sandreas.hansson@arm.com
2729930Sandreas.hansson@arm.com
2739930Sandreas.hansson@arm.com    print >>f, '#ifndef __CONFIG_THE_ISA_HH__'
2749396Sandreas.hansson@arm.com    print >>f, '#define __CONFIG_THE_ISA_HH__'
2758235Snate@binkert.org    print >>f
2768235Snate@binkert.org    for i,isa in enumerate(isas):
2776143Snate@binkert.org        print >>f, '#define %s %d' % (define(isa), i + 1)
2788235Snate@binkert.org    print >>f
2799003SAli.Saidi@ARM.com    print >>f, '#define THE_ISA %s' % (define(target))
2808235Snate@binkert.org    print >>f, '#define TheISA %s' % (namespace(target))
2818235Snate@binkert.org    print >>f
28212302Sgabeblack@google.com    print >>f, '#endif // __CONFIG_THE_ISA_HH__'  
2838235Snate@binkert.org
28412302Sgabeblack@google.comenv.Command('config/the_isa.hh', map(Value, all_isa_list), makeTheISA)
2858235Snate@binkert.org
2868235Snate@binkert.org########################################################################
28712302Sgabeblack@google.com#
2888235Snate@binkert.org# Prevent any SimObjects from being added after this point, they
2898235Snate@binkert.org# should all have been added in the SConscripts above
2908235Snate@binkert.org#
2918235Snate@binkert.orgSimObject.fixed = True
2929003SAli.Saidi@ARM.com
29312313Sgabeblack@google.comclass DictImporter(object):
29412313Sgabeblack@google.com    '''This importer takes a dictionary of arbitrary module names that
29512313Sgabeblack@google.com    map to arbitrary filenames.'''
29612313Sgabeblack@google.com    def __init__(self, modules):
29712313Sgabeblack@google.com        self.modules = modules
29812313Sgabeblack@google.com        self.installed = set()
29912315Sgabeblack@google.com
30012315Sgabeblack@google.com    def __del__(self):
30112315Sgabeblack@google.com        self.unload()
3025584Snate@binkert.org
3034382Sbinkertn@umich.edu    def unload(self):
3044202Sbinkertn@umich.edu        import sys
3054382Sbinkertn@umich.edu        for module in self.installed:
3064382Sbinkertn@umich.edu            del sys.modules[module]
3079396Sandreas.hansson@arm.com        self.installed = set()
3085584Snate@binkert.org
30912313Sgabeblack@google.com    def find_module(self, fullname, path):
3104382Sbinkertn@umich.edu        if fullname == 'm5.defines':
3114382Sbinkertn@umich.edu            return self
3124382Sbinkertn@umich.edu
3138232Snate@binkert.org        if fullname == 'm5.objects':
3145192Ssaidi@eecs.umich.edu            return self
3158232Snate@binkert.org
3168232Snate@binkert.org        if fullname.startswith('m5.internal'):
3178232Snate@binkert.org            return None
3185192Ssaidi@eecs.umich.edu
3198232Snate@binkert.org        source = self.modules.get(fullname, None)
3205192Ssaidi@eecs.umich.edu        if source is not None and fullname.startswith('m5.objects'):
3215799Snate@binkert.org            return self
3228232Snate@binkert.org
3235192Ssaidi@eecs.umich.edu        return None
3245192Ssaidi@eecs.umich.edu
3255192Ssaidi@eecs.umich.edu    def load_module(self, fullname):
3268232Snate@binkert.org        mod = imp.new_module(fullname)
3275192Ssaidi@eecs.umich.edu        sys.modules[fullname] = mod
3288232Snate@binkert.org        self.installed.add(fullname)
3295192Ssaidi@eecs.umich.edu
3305192Ssaidi@eecs.umich.edu        mod.__loader__ = self
3315192Ssaidi@eecs.umich.edu        if fullname == 'm5.objects':
3325192Ssaidi@eecs.umich.edu            mod.__path__ = fullname.split('.')
3334382Sbinkertn@umich.edu            return mod
3344382Sbinkertn@umich.edu
3354382Sbinkertn@umich.edu        if fullname == 'm5.defines':
3362667Sstever@eecs.umich.edu            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
3372667Sstever@eecs.umich.edu            return mod
3382667Sstever@eecs.umich.edu
3392667Sstever@eecs.umich.edu        source = self.modules[fullname]
3402667Sstever@eecs.umich.edu        if source.modname == '__init__':
3412667Sstever@eecs.umich.edu            mod.__path__ = source.modpath
3425742Snate@binkert.org        mod.__file__ = source.abspath
3435742Snate@binkert.org
3445742Snate@binkert.org        exec file(source.abspath, 'r') in mod.__dict__
3455793Snate@binkert.org
3468334Snate@binkert.org        return mod
3475793Snate@binkert.org
3485793Snate@binkert.orgimport m5.SimObject
3495793Snate@binkert.orgimport m5.params
3504382Sbinkertn@umich.edu
3514762Snate@binkert.orgm5.SimObject.clear()
3525344Sstever@gmail.comm5.params.clear()
3534382Sbinkertn@umich.edu
3545341Sstever@gmail.com# install the python importer so we can grab stuff from the source
3555742Snate@binkert.org# tree itself.  We can't have SimObjects added after this point or
3565742Snate@binkert.org# else we won't know about them for the rest of the stuff.
3575742Snate@binkert.orgimporter = DictImporter(PySource.modules)
3585742Snate@binkert.orgsys.meta_path[0:0] = [ importer ]
3595742Snate@binkert.org
3604762Snate@binkert.org# import all sim objects so we can populate the all_objects list
3615742Snate@binkert.org# make sure that we're working with a list, then let's sort it
3625742Snate@binkert.orgfor modname in SimObject.modnames:
36311984Sgabeblack@google.com    exec('from m5.objects import %s' % modname)
3647722Sgblack@eecs.umich.edu
3655742Snate@binkert.org# we need to unload all of the currently imported modules so that they
3665742Snate@binkert.org# will be re-imported the next time the sconscript is run
3675742Snate@binkert.orgimporter.unload()
3689930Sandreas.hansson@arm.comsys.meta_path.remove(importer)
3699930Sandreas.hansson@arm.com
3709930Sandreas.hansson@arm.comsim_objects = m5.SimObject.allClasses
3719930Sandreas.hansson@arm.comall_enums = m5.params.allEnums
3729930Sandreas.hansson@arm.com
3735742Snate@binkert.orgall_params = {}
3748242Sbradley.danofsky@amd.comfor name,obj in sorted(sim_objects.iteritems()):
3758242Sbradley.danofsky@amd.com    for param in obj._params.local.values():
3768242Sbradley.danofsky@amd.com        # load the ptype attribute now because it depends on the
3778242Sbradley.danofsky@amd.com        # current version of SimObject.allClasses, but when scons
3785341Sstever@gmail.com        # actually uses the value, all versions of
3795742Snate@binkert.org        # SimObject.allClasses will have been loaded
3807722Sgblack@eecs.umich.edu        param.ptype
3814773Snate@binkert.org
3826108Snate@binkert.org        if not hasattr(param, 'swig_decl'):
3831858SN/A            continue
3841085SN/A        pname = param.ptype_str
3856658Snate@binkert.org        if pname not in all_params:
3866658Snate@binkert.org            all_params[pname] = param
3877673Snate@binkert.org
3886658Snate@binkert.org########################################################################
3896658Snate@binkert.org#
39011308Santhony.gutierrez@amd.com# calculate extra dependencies
3916658Snate@binkert.org#
39211308Santhony.gutierrez@amd.commodule_depends = ["m5", "m5.SimObject", "m5.params"]
3936658Snate@binkert.orgdepends = [ PySource.modules[dep].tnode for dep in module_depends ]
3946658Snate@binkert.org
3957673Snate@binkert.org########################################################################
3967673Snate@binkert.org#
3977673Snate@binkert.org# Commands for the basic automatically generated python files
3987673Snate@binkert.org#
3997673Snate@binkert.org
4007673Snate@binkert.org# Generate Python file containing a dict specifying the current
4017673Snate@binkert.org# buildEnv flags.
40210467Sandreas.hansson@arm.comdef makeDefinesPyFile(target, source, env):
4036658Snate@binkert.org    build_env, hg_info = [ x.get_contents() for x in source ]
4047673Snate@binkert.org
40510467Sandreas.hansson@arm.com    code = m5.util.code_formatter()
40610467Sandreas.hansson@arm.com    code("""
40710467Sandreas.hansson@arm.comimport m5.internal
40810467Sandreas.hansson@arm.comimport m5.util
40910467Sandreas.hansson@arm.com
41010467Sandreas.hansson@arm.combuildEnv = m5.util.SmartDict($build_env)
41110467Sandreas.hansson@arm.comhgRev = '$hg_info'
41210467Sandreas.hansson@arm.com
41310467Sandreas.hansson@arm.comcompileDate = m5.internal.core.compileDate
41410467Sandreas.hansson@arm.com_globals = globals()
41510467Sandreas.hansson@arm.comfor key,val in m5.internal.core.__dict__.iteritems():
4167673Snate@binkert.org    if key.startswith('flag_'):
4177673Snate@binkert.org        flag = key[5:]
4187673Snate@binkert.org        _globals[flag] = val
4197673Snate@binkert.orgdel _globals
4207673Snate@binkert.org""")
4219048SAli.Saidi@ARM.com    code.write(str(target[0]))
4227673Snate@binkert.org
4237673Snate@binkert.orgdefines_info = [ Value(build_env), Value(env['HG_INFO']) ]
4247673Snate@binkert.org# Generate a file with all of the compile options in it
4257673Snate@binkert.orgenv.Command('python/m5/defines.py', defines_info, makeDefinesPyFile)
4266658Snate@binkert.orgPySource('m5', 'python/m5/defines.py')
4277756SAli.Saidi@ARM.com
4287816Ssteve.reinhardt@amd.com# Generate python file containing info about the M5 source code
4296658Snate@binkert.orgdef makeInfoPyFile(target, source, env):
43011308Santhony.gutierrez@amd.com    f = file(str(target[0]), 'w')
43111308Santhony.gutierrez@amd.com    for src in source:
43211308Santhony.gutierrez@amd.com        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
43311308Santhony.gutierrez@amd.com        print >>f, "%s = %s" % (src, repr(data))
43411308Santhony.gutierrez@amd.com    f.close()
43511308Santhony.gutierrez@amd.com
43611308Santhony.gutierrez@amd.com# Generate a file that wraps the basic top level files
43711308Santhony.gutierrez@amd.comenv.Command('python/m5/info.py',
43811308Santhony.gutierrez@amd.com            [ '#/AUTHORS', '#/LICENSE', '#/README', '#/RELEASE_NOTES' ],
43911308Santhony.gutierrez@amd.com            makeInfoPyFile)
44011308Santhony.gutierrez@amd.comPySource('m5', 'python/m5/info.py')
44111308Santhony.gutierrez@amd.com
44211308Santhony.gutierrez@amd.com# Generate the __init__.py file for m5.objects
44311308Santhony.gutierrez@amd.comdef makeObjectsInitFile(target, source, env):
44411308Santhony.gutierrez@amd.com    f = file(str(target[0]), 'w')
44511308Santhony.gutierrez@amd.com    print >>f, 'from params import *'
44611308Santhony.gutierrez@amd.com    print >>f, 'from m5.SimObject import *'
44711308Santhony.gutierrez@amd.com    for module in source:
44811308Santhony.gutierrez@amd.com        print >>f, 'from %s import *' % module.get_contents()
44911308Santhony.gutierrez@amd.com    f.close()
45011308Santhony.gutierrez@amd.com
45111308Santhony.gutierrez@amd.com# Generate an __init__.py file for the objects package
45211308Santhony.gutierrez@amd.comenv.Command('python/m5/objects/__init__.py',
45311308Santhony.gutierrez@amd.com            map(Value, SimObject.modnames),
45411308Santhony.gutierrez@amd.com            makeObjectsInitFile)
45511308Santhony.gutierrez@amd.comPySource('m5.objects', 'python/m5/objects/__init__.py')
45611308Santhony.gutierrez@amd.com
45711308Santhony.gutierrez@amd.com########################################################################
45811308Santhony.gutierrez@amd.com#
45911308Santhony.gutierrez@amd.com# Create all of the SimObject param headers and enum headers
46011308Santhony.gutierrez@amd.com#
46111308Santhony.gutierrez@amd.com
46211308Santhony.gutierrez@amd.comdef createSimObjectParam(target, source, env):
46311308Santhony.gutierrez@amd.com    assert len(target) == 1 and len(source) == 1
46411308Santhony.gutierrez@amd.com
46511308Santhony.gutierrez@amd.com    hh_file = file(target[0].abspath, 'w')
46611308Santhony.gutierrez@amd.com    name = str(source[0].get_contents())
46711308Santhony.gutierrez@amd.com    obj = sim_objects[name]
46811308Santhony.gutierrez@amd.com
46911308Santhony.gutierrez@amd.com    print >>hh_file, obj.cxx_decl()
47011308Santhony.gutierrez@amd.com    hh_file.close()
47111308Santhony.gutierrez@amd.com
47211308Santhony.gutierrez@amd.comdef createSwigParam(target, source, env):
47311308Santhony.gutierrez@amd.com    assert len(target) == 1 and len(source) == 1
47411308Santhony.gutierrez@amd.com
4754382Sbinkertn@umich.edu    i_file = file(target[0].abspath, 'w')
4764382Sbinkertn@umich.edu    name = str(source[0].get_contents())
4774762Snate@binkert.org    param = all_params[name]
4784762Snate@binkert.org
4794762Snate@binkert.org    for line in param.swig_decl():
4806654Snate@binkert.org        print >>i_file, line
4816654Snate@binkert.org    i_file.close()
4825517Snate@binkert.org
4835517Snate@binkert.orgdef createEnumStrings(target, source, env):
4845517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
4855517Snate@binkert.org
4865517Snate@binkert.org    cc_file = file(target[0].abspath, 'w')
4875517Snate@binkert.org    name = str(source[0].get_contents())
4885517Snate@binkert.org    obj = all_enums[name]
4895517Snate@binkert.org
4905517Snate@binkert.org    print >>cc_file, obj.cxx_def()
4915517Snate@binkert.org    cc_file.close()
4925517Snate@binkert.org
4935517Snate@binkert.orgdef createEnumParam(target, source, env):
4945517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
4955517Snate@binkert.org
4965517Snate@binkert.org    hh_file = file(target[0].abspath, 'w')
4975517Snate@binkert.org    name = str(source[0].get_contents())
4985517Snate@binkert.org    obj = all_enums[name]
4996654Snate@binkert.org
5005517Snate@binkert.org    print >>hh_file, obj.cxx_decl()
5015517Snate@binkert.org    hh_file.close()
5025517Snate@binkert.org
5035517Snate@binkert.org# Generate all of the SimObject param struct header files
5045517Snate@binkert.orgparams_hh_files = []
50511802Sandreas.sandberg@arm.comfor name,simobj in sorted(sim_objects.iteritems()):
5065517Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
5075517Snate@binkert.org    extra_deps = [ py_source.tnode ]
5086143Snate@binkert.org
5096654Snate@binkert.org    hh_file = File('params/%s.hh' % name)
5105517Snate@binkert.org    params_hh_files.append(hh_file)
5115517Snate@binkert.org    env.Command(hh_file, Value(name), createSimObjectParam)
5125517Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
5135517Snate@binkert.org
5145517Snate@binkert.org# Generate any parameter header files needed
5155517Snate@binkert.orgparams_i_files = []
5165517Snate@binkert.orgfor name,param in all_params.iteritems():
5175517Snate@binkert.org    i_file = File('params/%s_%s.i' % (name, param.file_ext))
5185517Snate@binkert.org    params_i_files.append(i_file)
5195517Snate@binkert.org    env.Command(i_file, Value(name), createSwigParam)
5205517Snate@binkert.org    env.Depends(i_file, depends)
5215517Snate@binkert.org
5225517Snate@binkert.org# Generate all enum header files
5235517Snate@binkert.orgfor name,enum in sorted(all_enums.iteritems()):
5246654Snate@binkert.org    py_source = PySource.modules[enum.__module__]
5256654Snate@binkert.org    extra_deps = [ py_source.tnode ]
5265517Snate@binkert.org
5275517Snate@binkert.org    cc_file = File('enums/%s.cc' % name)
5286143Snate@binkert.org    env.Command(cc_file, Value(name), createEnumStrings)
5296143Snate@binkert.org    env.Depends(cc_file, depends + extra_deps)
5306143Snate@binkert.org    Source(cc_file)
5316727Ssteve.reinhardt@amd.com
5325517Snate@binkert.org    hh_file = File('enums/%s.hh' % name)
5336727Ssteve.reinhardt@amd.com    env.Command(hh_file, Value(name), createEnumParam)
5345517Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
5355517Snate@binkert.org
5365517Snate@binkert.org# Build the big monolithic swigged params module (wraps all SimObject
5376654Snate@binkert.org# param structs and enum structs)
5386654Snate@binkert.orgdef buildParams(target, source, env):
5397673Snate@binkert.org    names = [ s.get_contents() for s in source ]
5406654Snate@binkert.org    objs = [ sim_objects[name] for name in names ]
5416654Snate@binkert.org    out = file(target[0].abspath, 'w')
5426654Snate@binkert.org
5436654Snate@binkert.org    ordered_objs = []
5445517Snate@binkert.org    obj_seen = set()
5455517Snate@binkert.org    def order_obj(obj):
5465517Snate@binkert.org        name = str(obj)
5476143Snate@binkert.org        if name in obj_seen:
5485517Snate@binkert.org            return
5494762Snate@binkert.org
5505517Snate@binkert.org        obj_seen.add(name)
5515517Snate@binkert.org        if str(obj) != 'SimObject':
5526143Snate@binkert.org            order_obj(obj.__bases__[0])
5536143Snate@binkert.org
5545517Snate@binkert.org        ordered_objs.append(obj)
5555517Snate@binkert.org
5565517Snate@binkert.org    for obj in objs:
5575517Snate@binkert.org        order_obj(obj)
5585517Snate@binkert.org
5595517Snate@binkert.org    enums = set()
5605517Snate@binkert.org    predecls = []
5615517Snate@binkert.org    pd_seen = set()
5625517Snate@binkert.org
5636143Snate@binkert.org    def add_pds(*pds):
5645517Snate@binkert.org        for pd in pds:
5656654Snate@binkert.org            if pd not in pd_seen:
5666654Snate@binkert.org                predecls.append(pd)
5676654Snate@binkert.org                pd_seen.add(pd)
5686654Snate@binkert.org
5696654Snate@binkert.org    for obj in ordered_objs:
5706654Snate@binkert.org        params = obj._params.local.values()
5714762Snate@binkert.org        for param in params:
5724762Snate@binkert.org            ptype = param.ptype
5734762Snate@binkert.org            if issubclass(ptype, m5.params.Enum):
5744762Snate@binkert.org                if ptype not in enums:
5754762Snate@binkert.org                    enums.add(ptype)
5767675Snate@binkert.org            pds = param.swig_predecls()
57710584Sandreas.hansson@arm.com            if isinstance(pds, (list, tuple)):
5784762Snate@binkert.org                add_pds(*pds)
5794762Snate@binkert.org            else:
5804762Snate@binkert.org                add_pds(pds)
5814762Snate@binkert.org
5824382Sbinkertn@umich.edu    print >>out, '%module params'
5834382Sbinkertn@umich.edu
5845517Snate@binkert.org    print >>out, '%{'
5856654Snate@binkert.org    for obj in ordered_objs:
5865517Snate@binkert.org        print >>out, '#include "params/%s.hh"' % obj
5878126Sgblack@eecs.umich.edu    print >>out, '%}'
5886654Snate@binkert.org
5897673Snate@binkert.org    for pd in predecls:
5906654Snate@binkert.org        print >>out, pd
59111802Sandreas.sandberg@arm.com
5926654Snate@binkert.org    enums = list(enums)
5936654Snate@binkert.org    enums.sort()
5946654Snate@binkert.org    for enum in enums:
5956654Snate@binkert.org        print >>out, '%%include "enums/%s.hh"' % enum.__name__
59611802Sandreas.sandberg@arm.com    print >>out
5976669Snate@binkert.org
59811802Sandreas.sandberg@arm.com    for obj in ordered_objs:
5996669Snate@binkert.org        if obj.swig_objdecls:
6006669Snate@binkert.org            for decl in obj.swig_objdecls:
6016669Snate@binkert.org                print >>out, decl
6026669Snate@binkert.org            continue
6036654Snate@binkert.org
6047673Snate@binkert.org        class_path = obj.cxx_class.split('::')
6055517Snate@binkert.org        classname = class_path[-1]
6068126Sgblack@eecs.umich.edu        namespaces = class_path[:-1]
6075798Snate@binkert.org        namespaces.reverse()
6087756SAli.Saidi@ARM.com
6097816Ssteve.reinhardt@amd.com        code = ''
6105798Snate@binkert.org
6115798Snate@binkert.org        if namespaces:
6125517Snate@binkert.org            code += '// avoid name conflicts\n'
6135517Snate@binkert.org            sep_string = '_COLONS_'
6147673Snate@binkert.org            flat_name = sep_string.join(class_path)
6155517Snate@binkert.org            code += '%%rename(%s) %s;\n' % (flat_name, classname)
6165517Snate@binkert.org
6177673Snate@binkert.org        code += '// stop swig from creating/wrapping default ctor/dtor\n'
6187673Snate@binkert.org        code += '%%nodefault %s;\n' % classname
6195517Snate@binkert.org        code += 'class %s ' % classname
6205798Snate@binkert.org        if obj._base:
6215798Snate@binkert.org            code += ': public %s' % obj._base.cxx_class
6228333Snate@binkert.org        code += ' {};\n'
6237816Ssteve.reinhardt@amd.com
6245798Snate@binkert.org        for ns in namespaces:
6255798Snate@binkert.org            new_code = 'namespace %s {\n' % ns
6264762Snate@binkert.org            new_code += code
6274762Snate@binkert.org            new_code += '}\n'
6284762Snate@binkert.org            code = new_code
6294762Snate@binkert.org
6304762Snate@binkert.org        print >>out, code
6318596Ssteve.reinhardt@amd.com
6325517Snate@binkert.org    print >>out, '%%include "src/sim/sim_object_params.hh"' % obj
6335517Snate@binkert.org    for obj in ordered_objs:
63411997Sgabeblack@google.com        print >>out, '%%include "params/%s.hh"' % obj
6355517Snate@binkert.org
6365517Snate@binkert.orgparams_file = File('params/params.i')
6377673Snate@binkert.orgnames = sorted(sim_objects.keys())
6388596Ssteve.reinhardt@amd.comenv.Command(params_file, map(Value, names), buildParams)
6397673Snate@binkert.orgenv.Depends(params_file, params_hh_files + params_i_files + depends)
6405517Snate@binkert.orgSwigSource('m5.objects', params_file)
64110458Sandreas.hansson@arm.com
64210458Sandreas.hansson@arm.com# Build all swig modules
64310458Sandreas.hansson@arm.comfor swig in SwigSource.all:
64410458Sandreas.hansson@arm.com    env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
64510458Sandreas.hansson@arm.com                '$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
64610458Sandreas.hansson@arm.com                '-o ${TARGETS[0]} $SOURCES')
64710458Sandreas.hansson@arm.com    env.Depends(swig.py_source.tnode, swig.tnode)
64810458Sandreas.hansson@arm.com    env.Depends(swig.cc_source.tnode, swig.tnode)
64910458Sandreas.hansson@arm.com
65010458Sandreas.hansson@arm.com# Generate the main swig init file
65110458Sandreas.hansson@arm.comdef makeSwigInit(target, source, env):
65210458Sandreas.hansson@arm.com    f = file(str(target[0]), 'w')
6535517Snate@binkert.org    print >>f, 'extern "C" {'
65411996Sgabeblack@google.com    for module in source:
6555517Snate@binkert.org        print >>f, '    void init_%s();' % module.get_contents()
65611997Sgabeblack@google.com    print >>f, '}'
65711996Sgabeblack@google.com    print >>f, 'void initSwig() {'
6585517Snate@binkert.org    for module in source:
6595517Snate@binkert.org        print >>f, '    init_%s();' % module.get_contents()
6607673Snate@binkert.org    print >>f, '}'
6617673Snate@binkert.org    f.close()
66211996Sgabeblack@google.com
66311988Sandreas.sandberg@arm.comenv.Command('python/swig/init.cc',
6647673Snate@binkert.org            map(Value, sorted(s.module for s in SwigSource.all)),
6655517Snate@binkert.org            makeSwigInit)
6668596Ssteve.reinhardt@amd.comSource('python/swig/init.cc')
6675517Snate@binkert.org
6685517Snate@binkert.orgdef getFlags(source_flags):
66911997Sgabeblack@google.com    flagsMap = {}
6705517Snate@binkert.org    flagsList = []
6715517Snate@binkert.org    for s in source_flags:
6727673Snate@binkert.org        val = eval(s.get_contents())
6737673Snate@binkert.org        name, compound, desc = val
6747673Snate@binkert.org        flagsList.append(val)
6755517Snate@binkert.org        flagsMap[name] = bool(compound)
67611988Sandreas.sandberg@arm.com    
67711997Sgabeblack@google.com    for name, compound, desc in flagsList:
6788596Ssteve.reinhardt@amd.com        for flag in compound:
6798596Ssteve.reinhardt@amd.com            if flag not in flagsMap:
6808596Ssteve.reinhardt@amd.com                raise AttributeError, "Trace flag %s not found" % flag
68111988Sandreas.sandberg@arm.com            if flagsMap[flag]:
6828596Ssteve.reinhardt@amd.com                raise AttributeError, \
6838596Ssteve.reinhardt@amd.com                    "Compound flag can't point to another compound flag"
6848596Ssteve.reinhardt@amd.com
6854762Snate@binkert.org    flagsList.sort()
6866143Snate@binkert.org    return flagsList
6876143Snate@binkert.org
6886143Snate@binkert.org
6894762Snate@binkert.org# Generate traceflags.py
6904762Snate@binkert.orgdef traceFlagsPy(target, source, env):
6914762Snate@binkert.org    assert(len(target) == 1)
6927756SAli.Saidi@ARM.com
6938596Ssteve.reinhardt@amd.com    f = file(str(target[0]), 'w')
6944762Snate@binkert.org   
6954762Snate@binkert.org    allFlags = getFlags(source)
69610458Sandreas.hansson@arm.com
69710458Sandreas.hansson@arm.com    print >>f, 'basic = ['
69810458Sandreas.hansson@arm.com    for flag, compound, desc in allFlags:
69910458Sandreas.hansson@arm.com        if not compound:
70010458Sandreas.hansson@arm.com            print >>f, "    '%s'," % flag
70110458Sandreas.hansson@arm.com    print >>f, "    ]"
70210458Sandreas.hansson@arm.com    print >>f
70310458Sandreas.hansson@arm.com
70410458Sandreas.hansson@arm.com    print >>f, 'compound = ['
70510458Sandreas.hansson@arm.com    print >>f, "    'All',"
70610458Sandreas.hansson@arm.com    for flag, compound, desc in allFlags:
70710458Sandreas.hansson@arm.com        if compound:
70810458Sandreas.hansson@arm.com            print >>f, "    '%s'," % flag
70910458Sandreas.hansson@arm.com    print >>f, "    ]"
71010458Sandreas.hansson@arm.com    print >>f
71110458Sandreas.hansson@arm.com
71210458Sandreas.hansson@arm.com    print >>f, "all = frozenset(basic + compound)"
71310458Sandreas.hansson@arm.com    print >>f
71410458Sandreas.hansson@arm.com
71510458Sandreas.hansson@arm.com    print >>f, 'compoundMap = {'
71610458Sandreas.hansson@arm.com    all = tuple([flag for flag,compound,desc in allFlags if not compound])
71710458Sandreas.hansson@arm.com    print >>f, "    'All' : %s," % (all, )
71810458Sandreas.hansson@arm.com    for flag, compound, desc in allFlags:
71910458Sandreas.hansson@arm.com        if compound:
72010458Sandreas.hansson@arm.com            print >>f, "    '%s' : %s," % (flag, compound)
72110458Sandreas.hansson@arm.com    print >>f, "    }"
72210458Sandreas.hansson@arm.com    print >>f
72310458Sandreas.hansson@arm.com
72410458Sandreas.hansson@arm.com    print >>f, 'descriptions = {'
72510458Sandreas.hansson@arm.com    print >>f, "    'All' : 'All flags',"
72610458Sandreas.hansson@arm.com    for flag, compound, desc in allFlags:
72710458Sandreas.hansson@arm.com        print >>f, "    '%s' : '%s'," % (flag, desc)
72810458Sandreas.hansson@arm.com    print >>f, "    }"
72910458Sandreas.hansson@arm.com
73010458Sandreas.hansson@arm.com    f.close()
73110458Sandreas.hansson@arm.com
73210458Sandreas.hansson@arm.comdef traceFlagsCC(target, source, env):
73310458Sandreas.hansson@arm.com    assert(len(target) == 1)
73410458Sandreas.hansson@arm.com
73510458Sandreas.hansson@arm.com    f = file(str(target[0]), 'w')
73610458Sandreas.hansson@arm.com
73710458Sandreas.hansson@arm.com    allFlags = getFlags(source)
73810458Sandreas.hansson@arm.com
73910458Sandreas.hansson@arm.com    # file header
74010458Sandreas.hansson@arm.com    print >>f, '''
74110458Sandreas.hansson@arm.com/*
74210458Sandreas.hansson@arm.com * DO NOT EDIT THIS FILE! Automatically generated
74310458Sandreas.hansson@arm.com */
74410458Sandreas.hansson@arm.com
74510584Sandreas.hansson@arm.com#include "base/traceflags.hh"
74610458Sandreas.hansson@arm.com
74710458Sandreas.hansson@arm.comusing namespace Trace;
74810458Sandreas.hansson@arm.com
74910458Sandreas.hansson@arm.comconst char *Trace::flagStrings[] =
75010458Sandreas.hansson@arm.com{'''
7514762Snate@binkert.org
7526143Snate@binkert.org    # The string array is used by SimpleEnumParam to map the strings
7536143Snate@binkert.org    # provided by the user to enum values.
7546143Snate@binkert.org    for flag, compound, desc in allFlags:
7554762Snate@binkert.org        if not compound:
7564762Snate@binkert.org            print >>f, '    "%s",' % flag
75711996Sgabeblack@google.com
7587816Ssteve.reinhardt@amd.com    print >>f, '    "All",'
7594762Snate@binkert.org    for flag, compound, desc in allFlags:
7604762Snate@binkert.org        if compound:
7614762Snate@binkert.org            print >>f, '    "%s",' % flag
7624762Snate@binkert.org
7637756SAli.Saidi@ARM.com    print >>f, '};'
7648596Ssteve.reinhardt@amd.com    print >>f
7654762Snate@binkert.org    print >>f, 'const int Trace::numFlagStrings = %d;' % (len(allFlags) + 1)
7664762Snate@binkert.org    print >>f
76711988Sandreas.sandberg@arm.com
76811988Sandreas.sandberg@arm.com    #
76911988Sandreas.sandberg@arm.com    # Now define the individual compound flag arrays.  There is an array
77011988Sandreas.sandberg@arm.com    # for each compound flag listing the component base flags.
77111988Sandreas.sandberg@arm.com    #
77211988Sandreas.sandberg@arm.com    all = tuple([flag for flag,compound,desc in allFlags if not compound])
77311988Sandreas.sandberg@arm.com    print >>f, 'static const Flags AllMap[] = {'
77411988Sandreas.sandberg@arm.com    for flag, compound, desc in allFlags:
77511988Sandreas.sandberg@arm.com        if not compound:
77611988Sandreas.sandberg@arm.com            print >>f, "    %s," % flag
77711988Sandreas.sandberg@arm.com    print >>f, '};'
7784382Sbinkertn@umich.edu    print >>f
7799396Sandreas.hansson@arm.com
7809396Sandreas.hansson@arm.com    for flag, compound, desc in allFlags:
7819396Sandreas.hansson@arm.com        if not compound:
7829396Sandreas.hansson@arm.com            continue
7839396Sandreas.hansson@arm.com        print >>f, 'static const Flags %sMap[] = {' % flag
7849396Sandreas.hansson@arm.com        for flag in compound:
7859396Sandreas.hansson@arm.com            print >>f, "    %s," % flag
7869396Sandreas.hansson@arm.com        print >>f, "    (Flags)-1"
7879396Sandreas.hansson@arm.com        print >>f, '};'
7889396Sandreas.hansson@arm.com        print >>f
7899396Sandreas.hansson@arm.com
7909396Sandreas.hansson@arm.com    #
7919396Sandreas.hansson@arm.com    # Finally the compoundFlags[] array maps the compound flags
79212302Sgabeblack@google.com    # to their individual arrays/
7939396Sandreas.hansson@arm.com    #
7949396Sandreas.hansson@arm.com    print >>f, 'const Flags *Trace::compoundFlags[] ='
7959396Sandreas.hansson@arm.com    print >>f, '{'
7969396Sandreas.hansson@arm.com    print >>f, '    AllMap,'
7978232Snate@binkert.org    for flag, compound, desc in allFlags:
7988232Snate@binkert.org        if compound:
7998232Snate@binkert.org            print >>f, '    %sMap,' % flag
8008232Snate@binkert.org    # file trailer
8018232Snate@binkert.org    print >>f, '};'
8026229Snate@binkert.org
80310455SCurtis.Dunham@arm.com    f.close()
8046229Snate@binkert.org
80510455SCurtis.Dunham@arm.comdef traceFlagsHH(target, source, env):
80610455SCurtis.Dunham@arm.com    assert(len(target) == 1)
80710455SCurtis.Dunham@arm.com
8085517Snate@binkert.org    f = file(str(target[0]), 'w')
8095517Snate@binkert.org
8107673Snate@binkert.org    allFlags = getFlags(source)
8115517Snate@binkert.org
81210455SCurtis.Dunham@arm.com    # file header boilerplate
8135517Snate@binkert.org    print >>f, '''
8145517Snate@binkert.org/*
8158232Snate@binkert.org * DO NOT EDIT THIS FILE!
81610455SCurtis.Dunham@arm.com *
81710455SCurtis.Dunham@arm.com * Automatically generated from traceflags.py
81810455SCurtis.Dunham@arm.com */
8197673Snate@binkert.org
8207673Snate@binkert.org#ifndef __BASE_TRACE_FLAGS_HH__
82110455SCurtis.Dunham@arm.com#define __BASE_TRACE_FLAGS_HH__
82210455SCurtis.Dunham@arm.com
82310455SCurtis.Dunham@arm.comnamespace Trace {
8245517Snate@binkert.org
82510455SCurtis.Dunham@arm.comenum Flags {'''
82610455SCurtis.Dunham@arm.com
82710455SCurtis.Dunham@arm.com    # Generate the enum.  Base flags come first, then compound flags.
82810455SCurtis.Dunham@arm.com    idx = 0
82910455SCurtis.Dunham@arm.com    for flag, compound, desc in allFlags:
83010455SCurtis.Dunham@arm.com        if not compound:
83110455SCurtis.Dunham@arm.com            print >>f, '    %s = %d,' % (flag, idx)
83210455SCurtis.Dunham@arm.com            idx += 1
83310685Sandreas.hansson@arm.com
83410455SCurtis.Dunham@arm.com    numBaseFlags = idx
83510685Sandreas.hansson@arm.com    print >>f, '    NumFlags = %d,' % idx
83610455SCurtis.Dunham@arm.com
8375517Snate@binkert.org    # put a comment in here to separate base from compound flags
83810455SCurtis.Dunham@arm.com    print >>f, '''
8398232Snate@binkert.org// The remaining enum values are *not* valid indices for Trace::flags.
8408232Snate@binkert.org// They are "compound" flags, which correspond to sets of base
8415517Snate@binkert.org// flags, and are used by changeFlag.'''
8427673Snate@binkert.org
8435517Snate@binkert.org    print >>f, '    All = %d,' % idx
8448232Snate@binkert.org    idx += 1
8458232Snate@binkert.org    for flag, compound, desc in allFlags:
8465517Snate@binkert.org        if compound:
8478232Snate@binkert.org            print >>f, '    %s = %d,' % (flag, idx)
8488232Snate@binkert.org            idx += 1
8498232Snate@binkert.org
8507673Snate@binkert.org    numCompoundFlags = idx - numBaseFlags
8515517Snate@binkert.org    print >>f, '    NumCompoundFlags = %d' % numCompoundFlags
8525517Snate@binkert.org
8537673Snate@binkert.org    # trailer boilerplate
8545517Snate@binkert.org    print >>f, '''\
85510455SCurtis.Dunham@arm.com}; // enum Flags
8565517Snate@binkert.org
8575517Snate@binkert.org// Array of strings for SimpleEnumParam
8588232Snate@binkert.orgextern const char *flagStrings[];
8598232Snate@binkert.orgextern const int numFlagStrings;
8605517Snate@binkert.org
8618232Snate@binkert.org// Array of arraay pointers: for each compound flag, gives the list of
8628232Snate@binkert.org// base flags to set.  Inidividual flag arrays are terminated by -1.
8635517Snate@binkert.orgextern const Flags *compoundFlags[];
8648232Snate@binkert.org
8658232Snate@binkert.org/* namespace Trace */ }
8668232Snate@binkert.org
8675517Snate@binkert.org#endif // __BASE_TRACE_FLAGS_HH__
8688232Snate@binkert.org'''
8698232Snate@binkert.org
8708232Snate@binkert.org    f.close()
8718232Snate@binkert.org
8728232Snate@binkert.orgflags = map(Value, trace_flags.values())
8738232Snate@binkert.orgenv.Command('base/traceflags.py', flags, traceFlagsPy)
8745517Snate@binkert.orgPySource('m5', 'base/traceflags.py')
8758232Snate@binkert.org
8768232Snate@binkert.orgenv.Command('base/traceflags.hh', flags, traceFlagsHH)
8775517Snate@binkert.orgenv.Command('base/traceflags.cc', flags, traceFlagsCC)
8788232Snate@binkert.orgSource('base/traceflags.cc')
8797673Snate@binkert.org
8805517Snate@binkert.org# embed python files.  All .py files that have been indicated by a
8817673Snate@binkert.org# PySource() call in a SConscript need to be embedded into the M5
8825517Snate@binkert.org# library.  To do that, we compile the file to byte code, marshal the
8838232Snate@binkert.org# byte code, compress it, and then generate an assembly file that
8848232Snate@binkert.org# inserts the result into the data section with symbols indicating the
8858232Snate@binkert.org# beginning, and end (and with the size at the end)
8865192Ssaidi@eecs.umich.edudef objectifyPyFile(target, source, env):
88710454SCurtis.Dunham@arm.com    '''Action function to compile a .py into a code object, marshal
88810454SCurtis.Dunham@arm.com    it, compress it, and stick it into an asm file so the code appears
8898232Snate@binkert.org    as just bytes with a label in the data section'''
89010455SCurtis.Dunham@arm.com
89110455SCurtis.Dunham@arm.com    src = file(str(source[0]), 'r').read()
89210455SCurtis.Dunham@arm.com    dst = file(str(target[0]), 'w')
89310455SCurtis.Dunham@arm.com
8945192Ssaidi@eecs.umich.edu    pysource = PySource.tnodes[source[0]]
89511077SCurtis.Dunham@arm.com    compiled = compile(src, pysource.abspath, 'exec')
89611330SCurtis.Dunham@arm.com    marshalled = marshal.dumps(compiled)
89711077SCurtis.Dunham@arm.com    compressed = zlib.compress(marshalled)
89811077SCurtis.Dunham@arm.com    data = compressed
89911077SCurtis.Dunham@arm.com
90011330SCurtis.Dunham@arm.com    # Some C/C++ compilers prepend an underscore to global symbol
90111077SCurtis.Dunham@arm.com    # names, so if they're going to do that, we need to prepend that
9027674Snate@binkert.org    # leading underscore to globals in the assembly file.
9035522Snate@binkert.org    if env['LEADING_UNDERSCORE']:
9045522Snate@binkert.org        sym = '_' + pysource.symname
9057674Snate@binkert.org    else:
9067674Snate@binkert.org        sym = pysource.symname
9077674Snate@binkert.org
9087674Snate@binkert.org    step = 16
9097674Snate@binkert.org    print >>dst, ".data"
9107674Snate@binkert.org    print >>dst, ".globl %s_beg" % sym
9117674Snate@binkert.org    print >>dst, ".globl %s_end" % sym
9127674Snate@binkert.org    print >>dst, "%s_beg:" % sym
9135522Snate@binkert.org    for i in xrange(0, len(data), step):
9145522Snate@binkert.org        x = array.array('B', data[i:i+step])
9155522Snate@binkert.org        print >>dst, ".byte", ','.join([str(d) for d in x])
9165517Snate@binkert.org    print >>dst, "%s_end:" % sym
9175522Snate@binkert.org    print >>dst, ".long %d" % len(marshalled)
9185517Snate@binkert.org
9196143Snate@binkert.orgfor source in PySource.all:
9206727Ssteve.reinhardt@amd.com    env.Command(source.assembly, source.tnode, objectifyPyFile)
9215522Snate@binkert.org    Source(source.assembly)
9225522Snate@binkert.org
9235522Snate@binkert.org# Generate init_python.cc which creates a bunch of EmbeddedPyModule
9247674Snate@binkert.org# structs that describe the embedded python code.  One such struct
9255517Snate@binkert.org# contains information about the importer that python uses to get at
9267673Snate@binkert.org# the embedded files, and then there's a list of all of the rest that
9277673Snate@binkert.org# the importer uses to load the rest on demand.
9287674Snate@binkert.orgdef pythonInit(target, source, env):
9297673Snate@binkert.org    dst = file(str(target[0]), 'w')
9307674Snate@binkert.org
9317674Snate@binkert.org    def dump_mod(sym, endchar=','):
9328946Sandreas.hansson@arm.com        pysource = PySource.symnames[sym]
9337674Snate@binkert.org        print >>dst, '    { "%s",' % pysource.arcname
9347674Snate@binkert.org        print >>dst, '      "%s",' % pysource.modpath
9357674Snate@binkert.org        print >>dst, '       %s_beg, %s_end,' % (sym, sym)
9365522Snate@binkert.org        print >>dst, '       %s_end - %s_beg,' % (sym, sym)
9375522Snate@binkert.org        print >>dst, '       *(int *)%s_end }%s'  % (sym, endchar)
9387674Snate@binkert.org    
9397674Snate@binkert.org    print >>dst, '#include "sim/init.hh"'
94011308Santhony.gutierrez@amd.com
9417674Snate@binkert.org    for sym in source:
9427673Snate@binkert.org        sym = sym.get_contents()
9437674Snate@binkert.org        print >>dst, "extern const char %s_beg[], %s_end[];" % (sym, sym)
9447674Snate@binkert.org
9457674Snate@binkert.org    print >>dst, "const EmbeddedPyModule embeddedPyImporter = "
9467674Snate@binkert.org    dump_mod("PyEMB_importer", endchar=';');
9477674Snate@binkert.org    print >>dst
9487674Snate@binkert.org
9497674Snate@binkert.org    print >>dst, "const EmbeddedPyModule embeddedPyModules[] = {"
9507674Snate@binkert.org    for i,sym in enumerate(source):
9517811Ssteve.reinhardt@amd.com        sym = sym.get_contents()
9527674Snate@binkert.org        if sym == "PyEMB_importer":
9537673Snate@binkert.org            # Skip the importer since we've already exported it
9545522Snate@binkert.org            continue
9556143Snate@binkert.org        dump_mod(sym)
95610453SAndrew.Bardsley@arm.com    print >>dst, "    { 0, 0, 0, 0, 0, 0 }"
9577816Ssteve.reinhardt@amd.com    print >>dst, "};"
95812302Sgabeblack@google.com
9594382Sbinkertn@umich.edu
9604382Sbinkertn@umich.eduenv.Command('sim/init_python.cc',
9614382Sbinkertn@umich.edu            map(Value, (s.symname for s in PySource.all)),
9624382Sbinkertn@umich.edu            pythonInit)
9634382Sbinkertn@umich.eduSource('sim/init_python.cc')
9644382Sbinkertn@umich.edu
9654382Sbinkertn@umich.edu########################################################################
9664382Sbinkertn@umich.edu#
96712302Sgabeblack@google.com# Define binaries.  Each different build type (debug, opt, etc.) gets
9684382Sbinkertn@umich.edu# a slightly different build environment.
9692655Sstever@eecs.umich.edu#
9702655Sstever@eecs.umich.edu
9712655Sstever@eecs.umich.edu# List of constructed environments to pass back to SConstruct
9722655Sstever@eecs.umich.eduenvList = []
97312063Sgabeblack@google.com
9745601Snate@binkert.orgdate_source = Source('base/date.cc', skip_lib=True)
9755601Snate@binkert.org
97612222Sgabeblack@google.com# Function to create a new build environment as clone of current
97712222Sgabeblack@google.com# environment 'env' with modified object suffix and optional stripped
97812222Sgabeblack@google.com# binary.  Additional keyword arguments are appended to corresponding
9795522Snate@binkert.org# build environment vars.
9805863Snate@binkert.orgdef makeEnv(label, objsfx, strip = False, **kwargs):
9815601Snate@binkert.org    # SCons doesn't know to append a library suffix when there is a '.' in the
9825601Snate@binkert.org    # name.  Use '_' instead.
9835601Snate@binkert.org    libname = 'm5_' + label
98412302Sgabeblack@google.com    exename = 'm5.' + label
98510453SAndrew.Bardsley@arm.com
98611988Sandreas.sandberg@arm.com    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
98711988Sandreas.sandberg@arm.com    new_env.Label = label
98810453SAndrew.Bardsley@arm.com    new_env.Append(**kwargs)
98912302Sgabeblack@google.com
99010453SAndrew.Bardsley@arm.com    swig_env = new_env.Clone()
99111983Sgabeblack@google.com    swig_env.Append(CCFLAGS='-Werror')
99211983Sgabeblack@google.com    if env['GCC']:
99312302Sgabeblack@google.com        swig_env.Append(CCFLAGS='-Wno-uninitialized')
99412302Sgabeblack@google.com        swig_env.Append(CCFLAGS='-Wno-sign-compare')
99512362Sgabeblack@google.com        swig_env.Append(CCFLAGS='-Wno-parentheses')
99612362Sgabeblack@google.com
99711983Sgabeblack@google.com    werror_env = new_env.Clone()
99812302Sgabeblack@google.com    werror_env.Append(CCFLAGS='-Werror')
99912302Sgabeblack@google.com
100011983Sgabeblack@google.com    def make_obj(source, static, extra_deps = None):
100111983Sgabeblack@google.com        '''This function adds the specified source to the correct
100211983Sgabeblack@google.com        build environment, and returns the corresponding SCons Object
100312362Sgabeblack@google.com        nodes'''
100412362Sgabeblack@google.com
100512310Sgabeblack@google.com        if source.swig:
100612063Sgabeblack@google.com            env = swig_env
100712063Sgabeblack@google.com        elif source.Werror:
100812063Sgabeblack@google.com            env = werror_env
100912310Sgabeblack@google.com        else:
101012310Sgabeblack@google.com            env = new_env
101112063Sgabeblack@google.com
101212063Sgabeblack@google.com        if static:
101311983Sgabeblack@google.com            obj = env.StaticObject(source.tnode)
101411983Sgabeblack@google.com        else:
101511983Sgabeblack@google.com            obj = env.SharedObject(source.tnode)
101612310Sgabeblack@google.com
101712310Sgabeblack@google.com        if extra_deps:
101811983Sgabeblack@google.com            env.Depends(obj, extra_deps)
101911983Sgabeblack@google.com
102011983Sgabeblack@google.com        return obj
102111983Sgabeblack@google.com
102212310Sgabeblack@google.com    static_objs = [ make_obj(s, True) for s in Source.get(skip_lib=False)]
102312310Sgabeblack@google.com    shared_objs = [ make_obj(s, False) for s in Source.get(skip_lib=False)]
10246143Snate@binkert.org
102512362Sgabeblack@google.com    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
102612306Sgabeblack@google.com    static_objs.append(static_date)
102712310Sgabeblack@google.com    
102810453SAndrew.Bardsley@arm.com    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
102912362Sgabeblack@google.com    shared_objs.append(shared_date)
103012306Sgabeblack@google.com
103112310Sgabeblack@google.com    # First make a library of everything but main() so other programs can
10325554Snate@binkert.org    # link against m5.
10335522Snate@binkert.org    static_lib = new_env.StaticLibrary(libname, static_objs)
10345522Snate@binkert.org    shared_lib = new_env.SharedLibrary(libname, shared_objs)
10355797Snate@binkert.org
10365797Snate@binkert.org    for target, sources in unit_tests:
10375522Snate@binkert.org        objs = [ make_obj(s, static=True) for s in sources ]
10385601Snate@binkert.org        new_env.Program("unittest/%s.%s" % (target, label), objs + static_objs)
103912362Sgabeblack@google.com
10408233Snate@binkert.org    # Now link a stub with main() and the static library.
10418235Snate@binkert.org    bin_objs = [make_obj(s, True) for s in Source.get(bin_only=True) ]
104212302Sgabeblack@google.com    progname = exename
104312362Sgabeblack@google.com    if strip:
10449003SAli.Saidi@ARM.com        progname += '.unstripped'
10459003SAli.Saidi@ARM.com
104612222Sgabeblack@google.com    targets = new_env.Program(progname, bin_objs + static_objs)
104710196SCurtis.Dunham@arm.com
10488235Snate@binkert.org    if strip:
104912313Sgabeblack@google.com        if sys.platform == 'sunos5':
105012313Sgabeblack@google.com            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
105112313Sgabeblack@google.com        else:
105212313Sgabeblack@google.com            cmd = 'strip $SOURCE -o $TARGET'
105312313Sgabeblack@google.com        targets = new_env.Command(exename, progname, cmd)
105412362Sgabeblack@google.com            
105512315Sgabeblack@google.com    new_env.M5Binary = targets[0]
105612315Sgabeblack@google.com    envList.append(new_env)
105712313Sgabeblack@google.com
10586143Snate@binkert.org# Debug binary
10592655Sstever@eecs.umich.educcflags = {}
10606143Snate@binkert.orgif env['GCC']:
10616143Snate@binkert.org    if sys.platform == 'sunos5':
106211985Sgabeblack@google.com        ccflags['debug'] = '-gstabs+'
10636143Snate@binkert.org    else:
10646143Snate@binkert.org        ccflags['debug'] = '-ggdb3'
10654007Ssaidi@eecs.umich.edu    ccflags['opt'] = '-g -O3'
10664596Sbinkertn@umich.edu    ccflags['fast'] = '-O3'
10674007Ssaidi@eecs.umich.edu    ccflags['prof'] = '-O3 -g -pg'
10684596Sbinkertn@umich.eduelif env['SUNCC']:
10697756SAli.Saidi@ARM.com    ccflags['debug'] = '-g0'
10707816Ssteve.reinhardt@amd.com    ccflags['opt'] = '-g -O'
10718334Snate@binkert.org    ccflags['fast'] = '-fast'
10728334Snate@binkert.org    ccflags['prof'] = '-fast -g -pg'
10738334Snate@binkert.orgelif env['ICC']:
10748334Snate@binkert.org    ccflags['debug'] = '-g -O0'
10755601Snate@binkert.org    ccflags['opt'] = '-g -O'
107611993Sgabeblack@google.com    ccflags['fast'] = '-fast'
107711993Sgabeblack@google.com    ccflags['prof'] = '-fast -g -pg'
107811993Sgabeblack@google.comelse:
107912223Sgabeblack@google.com    print 'Unknown compiler, please fix compiler options'
108011993Sgabeblack@google.com    Exit(1)
10812655Sstever@eecs.umich.edu
10829225Sandreas.hansson@arm.commakeEnv('debug', '.do',
10839225Sandreas.hansson@arm.com        CCFLAGS = Split(ccflags['debug']),
10849226Sandreas.hansson@arm.com        CPPDEFINES = ['DEBUG', 'TRACING_ON=1'])
10859226Sandreas.hansson@arm.com
10869225Sandreas.hansson@arm.com# Optimized binary
10879226Sandreas.hansson@arm.commakeEnv('opt', '.o',
10889226Sandreas.hansson@arm.com        CCFLAGS = Split(ccflags['opt']),
10899226Sandreas.hansson@arm.com        CPPDEFINES = ['TRACING_ON=1'])
10909226Sandreas.hansson@arm.com
10919226Sandreas.hansson@arm.com# "Fast" binary
10929226Sandreas.hansson@arm.commakeEnv('fast', '.fo', strip = True,
10939225Sandreas.hansson@arm.com        CCFLAGS = Split(ccflags['fast']),
10949227Sandreas.hansson@arm.com        CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'])
10959227Sandreas.hansson@arm.com
10969227Sandreas.hansson@arm.com# Profiled binary
10979227Sandreas.hansson@arm.commakeEnv('prof', '.po',
10988946Sandreas.hansson@arm.com        CCFLAGS = Split(ccflags['prof']),
10993918Ssaidi@eecs.umich.edu        CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
11009225Sandreas.hansson@arm.com        LINKFLAGS = '-pg')
11013918Ssaidi@eecs.umich.edu
11029225Sandreas.hansson@arm.comReturn('envList')
11039225Sandreas.hansson@arm.com