SimObject.py revision 5543
12623SN/A# Copyright (c) 2004-2006 The Regents of The University of Michigan
22623SN/A# All rights reserved.
32623SN/A#
42623SN/A# Redistribution and use in source and binary forms, with or without
52623SN/A# modification, are permitted provided that the following conditions are
62623SN/A# met: redistributions of source code must retain the above copyright
72623SN/A# notice, this list of conditions and the following disclaimer;
82623SN/A# redistributions in binary form must reproduce the above copyright
92623SN/A# notice, this list of conditions and the following disclaimer in the
102623SN/A# documentation and/or other materials provided with the distribution;
112623SN/A# neither the name of the copyright holders nor the names of its
122623SN/A# contributors may be used to endorse or promote products derived from
132623SN/A# this software without specific prior written permission.
142623SN/A#
152623SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
162623SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
172623SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
182623SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
192623SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
202623SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
212623SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
222623SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
232623SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
242623SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
252623SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
262623SN/A#
272665Ssaidi@eecs.umich.edu# Authors: Steve Reinhardt
282665Ssaidi@eecs.umich.edu#          Nathan Binkert
292623SN/A
302623SN/Aimport sys, types
313170Sstever@eecs.umich.edu
323806Ssaidi@eecs.umich.eduimport proxy
332623SN/Aimport m5
344040Ssaidi@eecs.umich.edufrom util import *
352623SN/A
362623SN/A# These utility functions have to come first because they're
373348Sbinkertn@umich.edu# referenced in params.py... otherwise they won't be defined when we
383348Sbinkertn@umich.edu# import params below, and the recursive import of this file from
394762Snate@binkert.org# params.py will not find these names.
402901Ssaidi@eecs.umich.edudef isSimObject(value):
412623SN/A    return isinstance(value, SimObject)
422623SN/A
432623SN/Adef isSimObjectClass(value):
442623SN/A    return issubclass(value, SimObject)
452623SN/A
462623SN/Adef isSimObjectSequence(value):
472623SN/A    if not isinstance(value, (list, tuple)) or len(value) == 0:
482623SN/A        return False
492623SN/A
502623SN/A    for val in value:
512623SN/A        if not isNullPointer(val) and not isSimObject(val):
522623SN/A            return False
532623SN/A
542623SN/A    return True
552623SN/A
562623SN/Adef isSimObjectOrSequence(value):
572623SN/A    return isSimObject(value) or isSimObjectSequence(value)
582623SN/A
592623SN/A# Have to import params up top since Param is referenced on initial
604873Sstever@eecs.umich.edu# load (when SimObject class references Param to create a class
612623SN/A# variable, the 'name' param)...
622623SN/Afrom params import *
632856Srdreslin@umich.edu# There are a few things we need that aren't in params.__all__ since
642856Srdreslin@umich.edu# normal users don't need them
652856Srdreslin@umich.edufrom params import ParamDesc, VectorParamDesc, isNullPointer, SimObjVector
662856Srdreslin@umich.edu
672856Srdreslin@umich.edunoDot = False
682856Srdreslin@umich.edutry:
692856Srdreslin@umich.edu    import pydot
704968Sacolyte@umich.eduexcept:
714968Sacolyte@umich.edu    noDot = True
724968Sacolyte@umich.edu
734968Sacolyte@umich.edu#####################################################################
742856Srdreslin@umich.edu#
752856Srdreslin@umich.edu# M5 Python Configuration Utility
762856Srdreslin@umich.edu#
772623SN/A# The basic idea is to write simple Python programs that build Python
782623SN/A# objects corresponding to M5 SimObjects for the desired simulation
792623SN/A# configuration.  For now, the Python emits a .ini file that can be
802623SN/A# parsed by M5.  In the future, some tighter integration between M5
812623SN/A# and the Python interpreter may allow bypassing the .ini file.
822623SN/A#
832680Sktlim@umich.edu# Each SimObject class in M5 is represented by a Python class with the
842680Sktlim@umich.edu# same name.  The Python inheritance tree mirrors the M5 C++ tree
852623SN/A# (e.g., SimpleCPU derives from BaseCPU in both cases, and all
862623SN/A# SimObjects inherit from a single SimObject base class).  To specify
872680Sktlim@umich.edu# an instance of an M5 SimObject in a configuration, the user simply
882623SN/A# instantiates the corresponding Python object.  The parameters for
892623SN/A# that SimObject are given by assigning to attributes of the Python
904968Sacolyte@umich.edu# object, either using keyword assignment in the constructor or in
914968Sacolyte@umich.edu# separate assignment statements.  For example:
924968Sacolyte@umich.edu#
934968Sacolyte@umich.edu# cache = BaseCache(size='64KB')
944968Sacolyte@umich.edu# cache.hit_latency = 3
954968Sacolyte@umich.edu# cache.assoc = 8
962623SN/A#
972623SN/A# The magic lies in the mapping of the Python attributes for SimObject
982623SN/A# classes to the actual SimObject parameter specifications.  This
993349Sbinkertn@umich.edu# allows parameter validity checking in the Python code.  Continuing
1002623SN/A# the example above, the statements "cache.blurfl=3" or
1013184Srdreslin@umich.edu# "cache.assoc='hello'" would both result in runtime errors in Python,
1022623SN/A# since the BaseCache object has no 'blurfl' parameter and the 'assoc'
1032623SN/A# parameter requires an integer, respectively.  This magic is done
1042623SN/A# primarily by overriding the special __setattr__ method that controls
1052623SN/A# assignment to object attributes.
1063349Sbinkertn@umich.edu#
1072623SN/A# Once a set of Python objects have been instantiated in a hierarchy,
1083310Srdreslin@umich.edu# calling 'instantiate(obj)' (where obj is the root of the hierarchy)
1093649Srdreslin@umich.edu# will generate a .ini file.
1102623SN/A#
1112623SN/A#####################################################################
1122623SN/A
1133349Sbinkertn@umich.edu# list of all SimObject classes
1142623SN/AallClasses = {}
1153184Srdreslin@umich.edu
1163184Srdreslin@umich.edu# dict to look up SimObjects based on path
1172623SN/AinstanceDict = {}
1182623SN/A
1192623SN/A# The metaclass for SimObject.  This class controls how new classes
1202623SN/A# that derive from SimObject are instantiated, and provides inherited
1212623SN/A# class behavior (just like a class controls how instances of that
1223647Srdreslin@umich.edu# class are instantiated, and provides inherited instance behavior).
1233647Srdreslin@umich.educlass MetaSimObject(type):
1243647Srdreslin@umich.edu    # Attributes that can be set only at initialization time
1253647Srdreslin@umich.edu    init_keywords = { 'abstract' : types.BooleanType,
1263647Srdreslin@umich.edu                      'cxx_namespace' : types.StringType,
1272626SN/A                      'cxx_class' : types.StringType,
1283647Srdreslin@umich.edu                      'cxx_type' : types.StringType,
1292626SN/A                      'cxx_predecls' : types.ListType,
1302623SN/A                      'swig_objdecls' : types.ListType,
1312623SN/A                      'swig_predecls' : types.ListType,
1322623SN/A                      'type' : types.StringType }
1332657Ssaidi@eecs.umich.edu    # Attributes that can be set any time
1342623SN/A    keywords = { 'check' : types.FunctionType }
1352623SN/A
1362623SN/A    # __new__ is called before __init__, and is where the statements
1372623SN/A    # in the body of the class definition get loaded into the class's
1382623SN/A    # __dict__.  We intercept this to filter out parameter & port assignments
1394192Sktlim@umich.edu    # and only allow "private" attributes to be passed to the base
1404192Sktlim@umich.edu    # __new__ (starting with underscore).
1414192Sktlim@umich.edu    def __new__(mcls, name, bases, dict):
1424192Sktlim@umich.edu        assert name not in allClasses
1434192Sktlim@umich.edu
1444192Sktlim@umich.edu        # Copy "private" attributes, functions, and classes to the
1454192Sktlim@umich.edu        # official dict.  Everything else goes in _init_dict to be
1464192Sktlim@umich.edu        # filtered in __init__.
1474192Sktlim@umich.edu        cls_dict = {}
1484192Sktlim@umich.edu        value_dict = {}
1494192Sktlim@umich.edu        for key,val in dict.items():
1502623SN/A            if key.startswith('_') or isinstance(val, (types.FunctionType,
1512623SN/A                                                       types.TypeType)):
1522623SN/A                cls_dict[key] = val
1532623SN/A            else:
1544968Sacolyte@umich.edu                # must be a param/port setting
1554968Sacolyte@umich.edu                value_dict[key] = val
1562623SN/A        if 'abstract' not in value_dict:
1572623SN/A            value_dict['abstract'] = False
1582623SN/A        cls_dict['_value_dict'] = value_dict
1593647Srdreslin@umich.edu        cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict)
1603647Srdreslin@umich.edu        if 'type' in value_dict:
1613647Srdreslin@umich.edu            allClasses[name] = cls
1625169Ssaidi@eecs.umich.edu        return cls
1635169Ssaidi@eecs.umich.edu
1645169Ssaidi@eecs.umich.edu    # subclass initialization
1652623SN/A    def __init__(cls, name, bases, dict):
1662623SN/A        # calls type.__init__()... I think that's a no-op, but leave
1672623SN/A        # it here just in case it's not.
1682623SN/A        super(MetaSimObject, cls).__init__(name, bases, dict)
1692623SN/A
1702623SN/A        # initialize required attributes
1712623SN/A
1722623SN/A        # class-only attributes
1732623SN/A        cls._params = multidict() # param descriptions
1742623SN/A        cls._ports = multidict()  # port descriptions
1752915Sktlim@umich.edu
1762915Sktlim@umich.edu        # class or instance attributes
1773177Shsul@eecs.umich.edu        cls._values = multidict()   # param values
1783177Shsul@eecs.umich.edu        cls._port_refs = multidict() # port ref objects
1793145Shsul@eecs.umich.edu        cls._instantiated = False # really instantiated, cloned, or subclassed
1802623SN/A
1812623SN/A        # We don't support multiple inheritance.  If you want to, you
1822623SN/A        # must fix multidict to deal with it properly.
1832623SN/A        if len(bases) > 1:
1842623SN/A            raise TypeError, "SimObjects do not support multiple inheritance"
1852623SN/A
1862623SN/A        base = bases[0]
1872915Sktlim@umich.edu
1882915Sktlim@umich.edu        # Set up general inheritance via multidicts.  A subclass will
1893177Shsul@eecs.umich.edu        # inherit all its settings from the base class.  The only time
1903145Shsul@eecs.umich.edu        # the following is not true is when we define the SimObject
1912915Sktlim@umich.edu        # class itself (in which case the multidicts have no parent).
1922915Sktlim@umich.edu        if isinstance(base, MetaSimObject):
1932915Sktlim@umich.edu            cls._params.parent = base._params
1942915Sktlim@umich.edu            cls._ports.parent = base._ports
1952915Sktlim@umich.edu            cls._values.parent = base._values
1962915Sktlim@umich.edu            cls._port_refs.parent = base._port_refs
1975220Ssaidi@eecs.umich.edu            # mark base as having been subclassed
1985220Ssaidi@eecs.umich.edu            base._instantiated = True
1995220Ssaidi@eecs.umich.edu
2004940Snate@binkert.org        # default keyword values
2015220Ssaidi@eecs.umich.edu        if 'type' in cls._value_dict:
2023324Shsul@eecs.umich.edu            _type = cls._value_dict['type']
2035220Ssaidi@eecs.umich.edu            if 'cxx_class' not in cls._value_dict:
2045220Ssaidi@eecs.umich.edu                cls._value_dict['cxx_class'] = _type
2055220Ssaidi@eecs.umich.edu
2065220Ssaidi@eecs.umich.edu            namespace = cls._value_dict.get('cxx_namespace', None)
2073324Shsul@eecs.umich.edu
2082915Sktlim@umich.edu            _cxx_class = cls._value_dict['cxx_class']
2092623SN/A            if 'cxx_type' not in cls._value_dict:
2102623SN/A                t = _cxx_class + '*'
2112623SN/A                if namespace:
2122798Sktlim@umich.edu                    t = '%s::%s' % (namespace, t)
2132623SN/A                cls._value_dict['cxx_type'] = t
2142798Sktlim@umich.edu            if 'cxx_predecls' not in cls._value_dict:
2152798Sktlim@umich.edu                # A forward class declaration is sufficient since we are
2162623SN/A                # just declaring a pointer.
2172798Sktlim@umich.edu                decl = 'class %s;' % _cxx_class
2182623SN/A                if namespace:
2192623SN/A                    namespaces = namespace.split('::')
2202623SN/A                    namespaces.reverse()
2212623SN/A                    for namespace in namespaces:
2222623SN/A                        decl = 'namespace %s { %s }' % (namespace, decl)
2232623SN/A                cls._value_dict['cxx_predecls'] = [decl]
2244192Sktlim@umich.edu
2252623SN/A            if 'swig_predecls' not in cls._value_dict:
2262623SN/A                # A forward class declaration is sufficient since we are
2272623SN/A                # just declaring a pointer.
2282680Sktlim@umich.edu                cls._value_dict['swig_predecls'] = \
2292623SN/A                    cls._value_dict['cxx_predecls']
2302680Sktlim@umich.edu
2312680Sktlim@umich.edu        if 'swig_objdecls' not in cls._value_dict:
2322680Sktlim@umich.edu            cls._value_dict['swig_objdecls'] = []
2332623SN/A
2343495Sktlim@umich.edu        # Now process the _value_dict items.  They could be defining
2352623SN/A        # new (or overriding existing) parameters or ports, setting
2362623SN/A        # class keywords (e.g., 'abstract'), or setting parameter
2372623SN/A        # values or port bindings.  The first 3 can only be set when
2383512Sktlim@umich.edu        # the class is defined, so we handle them here.  The others
2393512Sktlim@umich.edu        # can be set later too, so just emulate that by calling
2403512Sktlim@umich.edu        # setattr().
2415169Ssaidi@eecs.umich.edu        for key,val in cls._value_dict.items():
2425169Ssaidi@eecs.umich.edu            # param descriptions
2432623SN/A            if isinstance(val, ParamDesc):
2442623SN/A                cls._new_param(key, val)
2452623SN/A
2462623SN/A            # port objects
2472623SN/A            elif isinstance(val, Port):
2482623SN/A                cls._new_port(key, val)
2494940Snate@binkert.org
2504940Snate@binkert.org            # init-time-only keywords
2512623SN/A            elif cls.init_keywords.has_key(key):
2522683Sktlim@umich.edu                cls._set_keyword(key, val, cls.init_keywords[key])
2532623SN/A
2542623SN/A            # default: use normal path (ends up in __setattr__)
2552623SN/A            else:
2562623SN/A                setattr(cls, key, val)
2572623SN/A
2585101Ssaidi@eecs.umich.edu    def _set_keyword(cls, keyword, val, kwtype):
2593686Sktlim@umich.edu        if not isinstance(val, kwtype):
2603430Sgblack@eecs.umich.edu            raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
2615100Ssaidi@eecs.umich.edu                  (keyword, type(val), kwtype)
2622623SN/A        if isinstance(val, types.FunctionType):
2632623SN/A            val = classmethod(val)
2642623SN/A        type.__setattr__(cls, keyword, val)
2652623SN/A
2662623SN/A    def _new_param(cls, name, pdesc):
2672623SN/A        # each param desc should be uniquely assigned to one variable
2682623SN/A        assert(not hasattr(pdesc, 'name'))
2694940Snate@binkert.org        pdesc.name = name
2704940Snate@binkert.org        cls._params[name] = pdesc
2712623SN/A        if hasattr(pdesc, 'default'):
2722683Sktlim@umich.edu            cls._set_param(name, pdesc.default, pdesc)
2732623SN/A
2742623SN/A    def _set_param(cls, name, value, param):
2752626SN/A        assert(param.name == name)
2762626SN/A        try:
2772626SN/A            cls._values[name] = param.convert(value)
2782626SN/A        except Exception, e:
2792626SN/A            msg = "%s\nError setting param %s.%s to %s\n" % \
2802623SN/A                  (e, cls.__name__, name, value)
2812623SN/A            e.args = (msg, )
2822623SN/A            raise
2832623SN/A
2842623SN/A    def _new_port(cls, name, port):
2852623SN/A        # each port should be uniquely assigned to one variable
2862623SN/A        assert(not hasattr(port, 'name'))
2872623SN/A        port.name = name
2882623SN/A        cls._ports[name] = port
2892623SN/A        if hasattr(port, 'default'):
2903169Sstever@eecs.umich.edu            cls._cls_get_port_ref(name).connect(port.default)
2914870Sstever@eecs.umich.edu
2922623SN/A    # same as _get_port_ref, effectively, but for classes
2932623SN/A    def _cls_get_port_ref(cls, attr):
2942623SN/A        # Return reference that can be assigned to another port
2952623SN/A        # via __setattr__.  There is only ever one reference
2962623SN/A        # object per port, but we create them lazily here.
2974999Sgblack@eecs.umich.edu        ref = cls._port_refs.get(attr)
2984999Sgblack@eecs.umich.edu        if not ref:
2994999Sgblack@eecs.umich.edu            ref = cls._ports[attr].makeRef(cls)
3004999Sgblack@eecs.umich.edu            cls._port_refs[attr] = ref
3012623SN/A        return ref
3024999Sgblack@eecs.umich.edu
3032623SN/A    # Set attribute (called on foo.attr = value when foo is an
3044999Sgblack@eecs.umich.edu    # instance of class cls).
3054999Sgblack@eecs.umich.edu    def __setattr__(cls, attr, value):
3064999Sgblack@eecs.umich.edu        # normal processing for private attributes
3074999Sgblack@eecs.umich.edu        if attr.startswith('_'):
3084999Sgblack@eecs.umich.edu            type.__setattr__(cls, attr, value)
3094999Sgblack@eecs.umich.edu            return
3104999Sgblack@eecs.umich.edu
3114999Sgblack@eecs.umich.edu        if cls.keywords.has_key(attr):
3124999Sgblack@eecs.umich.edu            cls._set_keyword(attr, value, cls.keywords[attr])
3134999Sgblack@eecs.umich.edu            return
3144999Sgblack@eecs.umich.edu
3154999Sgblack@eecs.umich.edu        if cls._ports.has_key(attr):
3164999Sgblack@eecs.umich.edu            cls._cls_get_port_ref(attr).connect(value)
3174999Sgblack@eecs.umich.edu            return
3184999Sgblack@eecs.umich.edu
3194999Sgblack@eecs.umich.edu        if isSimObjectOrSequence(value) and cls._instantiated:
3204999Sgblack@eecs.umich.edu            raise RuntimeError, \
3214999Sgblack@eecs.umich.edu                  "cannot set SimObject parameter '%s' after\n" \
3224999Sgblack@eecs.umich.edu                  "    class %s has been instantiated or subclassed" \
3234999Sgblack@eecs.umich.edu                  % (attr, cls.__name__)
3244999Sgblack@eecs.umich.edu
3254999Sgblack@eecs.umich.edu        # check for param
3264999Sgblack@eecs.umich.edu        param = cls._params.get(attr)
3274999Sgblack@eecs.umich.edu        if param:
3284999Sgblack@eecs.umich.edu            cls._set_param(attr, value, param)
3294999Sgblack@eecs.umich.edu            return
3304999Sgblack@eecs.umich.edu
3314999Sgblack@eecs.umich.edu        if isSimObjectOrSequence(value):
3324999Sgblack@eecs.umich.edu            # If RHS is a SimObject, it's an implicit child assignment.
3334999Sgblack@eecs.umich.edu            # Classes don't have children, so we just put this object
3344999Sgblack@eecs.umich.edu            # in _values; later, each instance will do a 'setattr(self,
3355012Sgblack@eecs.umich.edu            # attr, _values[attr])' in SimObject.__init__ which will
3364999Sgblack@eecs.umich.edu            # add this object as a child.
3374999Sgblack@eecs.umich.edu            cls._values[attr] = value
3384999Sgblack@eecs.umich.edu            return
3394999Sgblack@eecs.umich.edu
3404999Sgblack@eecs.umich.edu        # no valid assignment... raise exception
3414968Sacolyte@umich.edu        raise AttributeError, \
3424986Ssaidi@eecs.umich.edu              "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
3434999Sgblack@eecs.umich.edu
3444999Sgblack@eecs.umich.edu    def __getattr__(cls, attr):
3454999Sgblack@eecs.umich.edu        if cls._values.has_key(attr):
3464762Snate@binkert.org            return cls._values[attr]
3474999Sgblack@eecs.umich.edu
3484999Sgblack@eecs.umich.edu        raise AttributeError, \
3494999Sgblack@eecs.umich.edu              "object '%s' has no attribute '%s'" % (cls.__name__, attr)
3504999Sgblack@eecs.umich.edu
3514999Sgblack@eecs.umich.edu    def __str__(cls):
3524999Sgblack@eecs.umich.edu        return cls.__name__
3534999Sgblack@eecs.umich.edu
3544999Sgblack@eecs.umich.edu    def get_base(cls):
3554968Sacolyte@umich.edu        if str(cls) == 'SimObject':
3563170Sstever@eecs.umich.edu            return None
3574999Sgblack@eecs.umich.edu
3584999Sgblack@eecs.umich.edu        return  cls.__bases__[0].type
3594999Sgblack@eecs.umich.edu
3604999Sgblack@eecs.umich.edu    def cxx_decl(cls):
3614999Sgblack@eecs.umich.edu        code = "#ifndef __PARAMS__%s\n" % cls
3624999Sgblack@eecs.umich.edu        code += "#define __PARAMS__%s\n\n" % cls
3634999Sgblack@eecs.umich.edu
3644999Sgblack@eecs.umich.edu        # The 'dict' attribute restricts us to the params declared in
3654999Sgblack@eecs.umich.edu        # the object itself, not including inherited params (which
3664999Sgblack@eecs.umich.edu        # will also be inherited from the base class's param struct
3672623SN/A        # here).
3682623SN/A        params = cls._params.local.values()
3692623SN/A        try:
3705177Sgblack@eecs.umich.edu            ptypes = [p.ptype for p in params]
3715177Sgblack@eecs.umich.edu        except:
3725177Sgblack@eecs.umich.edu            print cls, p, p.ptype_str
3735177Sgblack@eecs.umich.edu            print params
3745177Sgblack@eecs.umich.edu            raise
3755177Sgblack@eecs.umich.edu
3765177Sgblack@eecs.umich.edu        # get a list of lists of predeclaration lines
3775177Sgblack@eecs.umich.edu        predecls = []
3785177Sgblack@eecs.umich.edu        predecls.extend(cls.cxx_predecls)
3795177Sgblack@eecs.umich.edu        for p in params:
3805177Sgblack@eecs.umich.edu            predecls.extend(p.cxx_predecls())
3815177Sgblack@eecs.umich.edu        # remove redundant lines
3825177Sgblack@eecs.umich.edu        predecls2 = []
3835177Sgblack@eecs.umich.edu        for pd in predecls:
3845177Sgblack@eecs.umich.edu            if pd not in predecls2:
3855177Sgblack@eecs.umich.edu                predecls2.append(pd)
3865177Sgblack@eecs.umich.edu        predecls2.sort()
3875177Sgblack@eecs.umich.edu        code += "\n".join(predecls2)
3885177Sgblack@eecs.umich.edu        code += "\n\n";
3895177Sgblack@eecs.umich.edu
3905177Sgblack@eecs.umich.edu        base = cls.get_base()
3915177Sgblack@eecs.umich.edu        if base:
3925177Sgblack@eecs.umich.edu            code += '#include "params/%s.hh"\n\n' % base
3935177Sgblack@eecs.umich.edu
3945177Sgblack@eecs.umich.edu        for ptype in ptypes:
3955177Sgblack@eecs.umich.edu            if issubclass(ptype, Enum):
3965177Sgblack@eecs.umich.edu                code += '#include "enums/%s.hh"\n' % ptype.__name__
3975177Sgblack@eecs.umich.edu                code += "\n\n"
3985177Sgblack@eecs.umich.edu
3995177Sgblack@eecs.umich.edu        code += cls.cxx_struct(base, params)
4005177Sgblack@eecs.umich.edu
4015177Sgblack@eecs.umich.edu        # close #ifndef __PARAMS__* guard
4025177Sgblack@eecs.umich.edu        code += "\n#endif\n"
4035177Sgblack@eecs.umich.edu        return code
4045177Sgblack@eecs.umich.edu
4055177Sgblack@eecs.umich.edu    def cxx_struct(cls, base, params):
4065177Sgblack@eecs.umich.edu        if cls == SimObject:
4075177Sgblack@eecs.umich.edu            return '#include "sim/sim_object_params.hh"\n'
4085177Sgblack@eecs.umich.edu
4095177Sgblack@eecs.umich.edu        # now generate the actual param struct
4105177Sgblack@eecs.umich.edu        code = "struct %sParams" % cls
4115177Sgblack@eecs.umich.edu        if base:
4125177Sgblack@eecs.umich.edu            code += " : public %sParams" % base
4135177Sgblack@eecs.umich.edu        code += "\n{\n"
4145177Sgblack@eecs.umich.edu        if not hasattr(cls, 'abstract') or not cls.abstract:
4155177Sgblack@eecs.umich.edu            if 'type' in cls.__dict__:
4165177Sgblack@eecs.umich.edu                code += "    %s create();\n" % cls.cxx_type
4175177Sgblack@eecs.umich.edu        decls = [p.cxx_decl() for p in params]
4185177Sgblack@eecs.umich.edu        decls.sort()
4195177Sgblack@eecs.umich.edu        code += "".join(["    %s\n" % d for d in decls])
4205177Sgblack@eecs.umich.edu        code += "};\n"
4215177Sgblack@eecs.umich.edu
4225177Sgblack@eecs.umich.edu        return code
4235177Sgblack@eecs.umich.edu
4245177Sgblack@eecs.umich.edu    def cxx_type_decl(cls):
4252623SN/A        base = cls.get_base()
4262623SN/A        code = ''
4272623SN/A
4282623SN/A        if base:
4294115Ssaidi@eecs.umich.edu            code += '#include "%s_type.h"\n' % base
4304115Ssaidi@eecs.umich.edu
4314115Ssaidi@eecs.umich.edu        # now generate dummy code for inheritance
4324115Ssaidi@eecs.umich.edu        code += "struct %s" % cls.cxx_class
4334040Ssaidi@eecs.umich.edu        if base:
4344040Ssaidi@eecs.umich.edu            code += " : public %s" % base.cxx_class
4354040Ssaidi@eecs.umich.edu        code += "\n{};\n"
4364040Ssaidi@eecs.umich.edu
4372623SN/A        return code
4382623SN/A
4392623SN/A    def swig_decl(cls):
4402623SN/A        base = cls.get_base()
4412623SN/A
4422623SN/A        code = '%%module %s\n' % cls
4432623SN/A
4442623SN/A        code += '%{\n'
4452623SN/A        code += '#include "params/%s.hh"\n' % cls
4462623SN/A        code += '%}\n\n'
4472623SN/A
4482623SN/A        # The 'dict' attribute restricts us to the params declared in
4492623SN/A        # the object itself, not including inherited params (which
4502623SN/A        # will also be inherited from the base class's param struct
4512623SN/A        # here).
4522623SN/A        params = cls._params.local.values()
4532623SN/A        ptypes = [p.ptype for p in params]
4542623SN/A
4552623SN/A        # get a list of lists of predeclaration lines
4562623SN/A        predecls = []
4572623SN/A        predecls.extend([ p.swig_predecls() for p in params ])
4582623SN/A        # flatten
4592623SN/A        predecls = reduce(lambda x,y:x+y, predecls, [])
4602623SN/A        # remove redundant lines
4612623SN/A        predecls2 = []
4622623SN/A        for pd in predecls:
4632623SN/A            if pd not in predecls2:
4642623SN/A                predecls2.append(pd)
4652623SN/A        predecls2.sort()
4662623SN/A        code += "\n".join(predecls2)
4672623SN/A        code += "\n\n";
4682623SN/A
4692623SN/A        if base:
4702623SN/A            code += '%%import "params/%s.i"\n\n' % base
4712623SN/A
4722623SN/A        for ptype in ptypes:
4732623SN/A            if issubclass(ptype, Enum):
4742623SN/A                code += '%%import "enums/%s.hh"\n' % ptype.__name__
4752623SN/A                code += "\n\n"
4762623SN/A
4772623SN/A        code += '%%import "params/%s_type.hh"\n\n' % cls
4782623SN/A        code += '%%include "params/%s.hh"\n\n' % cls
4792623SN/A
4803169Sstever@eecs.umich.edu        return code
4814870Sstever@eecs.umich.edu
4822623SN/A# The SimObject class is the root of the special hierarchy.  Most of
4832623SN/A# the code in this class deals with the configuration hierarchy itself
4842623SN/A# (parent/child node relationships).
4852623SN/Aclass SimObject(object):
4862623SN/A    # Specify metaclass.  Any class inheriting from SimObject will
4874999Sgblack@eecs.umich.edu    # get this metaclass.
4884999Sgblack@eecs.umich.edu    __metaclass__ = MetaSimObject
4894999Sgblack@eecs.umich.edu    type = 'SimObject'
4904999Sgblack@eecs.umich.edu    abstract = True
4912623SN/A
4924999Sgblack@eecs.umich.edu    swig_objdecls = [ '%include "python/swig/sim_object.i"' ]
4932623SN/A
4944999Sgblack@eecs.umich.edu    # Initialize new instance.  For objects with SimObject-valued
4954999Sgblack@eecs.umich.edu    # children, we need to recursively clone the classes represented
4964999Sgblack@eecs.umich.edu    # by those param values as well in a consistent "deep copy"-style
4974999Sgblack@eecs.umich.edu    # fashion.  That is, we want to make sure that each instance is
4984999Sgblack@eecs.umich.edu    # cloned only once, and that if there are multiple references to
4994999Sgblack@eecs.umich.edu    # the same original object, we end up with the corresponding
5004999Sgblack@eecs.umich.edu    # cloned references all pointing to the same cloned instance.
5014999Sgblack@eecs.umich.edu    def __init__(self, **kwargs):
5024999Sgblack@eecs.umich.edu        ancestor = kwargs.get('_ancestor')
5034999Sgblack@eecs.umich.edu        memo_dict = kwargs.get('_memo')
5044999Sgblack@eecs.umich.edu        if memo_dict is None:
5054999Sgblack@eecs.umich.edu            # prepare to memoize any recursively instantiated objects
5064999Sgblack@eecs.umich.edu            memo_dict = {}
5074999Sgblack@eecs.umich.edu        elif ancestor:
5084999Sgblack@eecs.umich.edu            # memoize me now to avoid problems with recursive calls
5094999Sgblack@eecs.umich.edu            memo_dict[ancestor] = self
5104999Sgblack@eecs.umich.edu
5114999Sgblack@eecs.umich.edu        if not ancestor:
5124999Sgblack@eecs.umich.edu            ancestor = self.__class__
5134999Sgblack@eecs.umich.edu        ancestor._instantiated = True
5144999Sgblack@eecs.umich.edu
5154999Sgblack@eecs.umich.edu        # initialize required attributes
5164999Sgblack@eecs.umich.edu        self._parent = None
5174999Sgblack@eecs.umich.edu        self._children = {}
5184999Sgblack@eecs.umich.edu        self._ccObject = None  # pointer to C++ object
5194999Sgblack@eecs.umich.edu        self._ccParams = None
5204999Sgblack@eecs.umich.edu        self._instantiated = False # really "cloned"
5214999Sgblack@eecs.umich.edu
5224999Sgblack@eecs.umich.edu        # Inherit parameter values from class using multidict so
5234999Sgblack@eecs.umich.edu        # individual value settings can be overridden.
5244999Sgblack@eecs.umich.edu        self._values = multidict(ancestor._values)
5254999Sgblack@eecs.umich.edu        # clone SimObject-valued parameters
5264999Sgblack@eecs.umich.edu        for key,val in ancestor._values.iteritems():
5274999Sgblack@eecs.umich.edu            if isSimObject(val):
5284999Sgblack@eecs.umich.edu                setattr(self, key, val(_memo=memo_dict))
5294999Sgblack@eecs.umich.edu            elif isSimObjectSequence(val) and len(val):
5304999Sgblack@eecs.umich.edu                setattr(self, key, [ v(_memo=memo_dict) for v in val ])
5314999Sgblack@eecs.umich.edu        # clone port references.  no need to use a multidict here
5324999Sgblack@eecs.umich.edu        # since we will be creating new references for all ports.
5334999Sgblack@eecs.umich.edu        self._port_refs = {}
5344999Sgblack@eecs.umich.edu        for key,val in ancestor._port_refs.iteritems():
5354999Sgblack@eecs.umich.edu            self._port_refs[key] = val.clone(self, memo_dict)
5364999Sgblack@eecs.umich.edu        # apply attribute assignments from keyword args, if any
5374999Sgblack@eecs.umich.edu        for key,val in kwargs.iteritems():
5384999Sgblack@eecs.umich.edu            setattr(self, key, val)
5394999Sgblack@eecs.umich.edu
5404999Sgblack@eecs.umich.edu    # "Clone" the current instance by creating another instance of
5414999Sgblack@eecs.umich.edu    # this instance's class, but that inherits its parameter values
5424999Sgblack@eecs.umich.edu    # and port mappings from the current instance.  If we're in a
5434999Sgblack@eecs.umich.edu    # "deep copy" recursive clone, check the _memo dict to see if
5444999Sgblack@eecs.umich.edu    # we've already cloned this instance.
5454999Sgblack@eecs.umich.edu    def __call__(self, **kwargs):
5464999Sgblack@eecs.umich.edu        memo_dict = kwargs.get('_memo')
5474999Sgblack@eecs.umich.edu        if memo_dict is None:
5484999Sgblack@eecs.umich.edu            # no memo_dict: must be top-level clone operation.
5494999Sgblack@eecs.umich.edu            # this is only allowed at the root of a hierarchy
5504999Sgblack@eecs.umich.edu            if self._parent:
5514999Sgblack@eecs.umich.edu                raise RuntimeError, "attempt to clone object %s " \
5524999Sgblack@eecs.umich.edu                      "not at the root of a tree (parent = %s)" \
5534878Sstever@eecs.umich.edu                      % (self, self._parent)
5544040Ssaidi@eecs.umich.edu            # create a new dict and use that.
5554040Ssaidi@eecs.umich.edu            memo_dict = {}
5564999Sgblack@eecs.umich.edu            kwargs['_memo'] = memo_dict
5574999Sgblack@eecs.umich.edu        elif memo_dict.has_key(self):
5584999Sgblack@eecs.umich.edu            # clone already done & memoized
5592631SN/A            return memo_dict[self]
5604999Sgblack@eecs.umich.edu        return self.__class__(_ancestor = self, **kwargs)
5614999Sgblack@eecs.umich.edu
5624999Sgblack@eecs.umich.edu    def _get_port_ref(self, attr):
5634999Sgblack@eecs.umich.edu        # Return reference that can be assigned to another port
5644999Sgblack@eecs.umich.edu        # via __setattr__.  There is only ever one reference
5654999Sgblack@eecs.umich.edu        # object per port, but we create them lazily here.
5664999Sgblack@eecs.umich.edu        ref = self._port_refs.get(attr)
5674999Sgblack@eecs.umich.edu        if not ref:
5683170Sstever@eecs.umich.edu            ref = self._ports[attr].makeRef(self)
5693170Sstever@eecs.umich.edu            self._port_refs[attr] = ref
5704999Sgblack@eecs.umich.edu        return ref
5714999Sgblack@eecs.umich.edu
5724999Sgblack@eecs.umich.edu    def __getattr__(self, attr):
5734999Sgblack@eecs.umich.edu        if self._ports.has_key(attr):
5744999Sgblack@eecs.umich.edu            return self._get_port_ref(attr)
5754999Sgblack@eecs.umich.edu
5764999Sgblack@eecs.umich.edu        if self._values.has_key(attr):
5774999Sgblack@eecs.umich.edu            return self._values[attr]
5784999Sgblack@eecs.umich.edu
5794999Sgblack@eecs.umich.edu        raise AttributeError, "object '%s' has no attribute '%s'" \
5802623SN/A              % (self.__class__.__name__, attr)
5812623SN/A
5822623SN/A    # Set attribute (called on foo.attr = value when foo is an
5835177Sgblack@eecs.umich.edu    # instance of class cls).
5845177Sgblack@eecs.umich.edu    def __setattr__(self, attr, value):
5855177Sgblack@eecs.umich.edu        # normal processing for private attributes
5865177Sgblack@eecs.umich.edu        if attr.startswith('_'):
5875177Sgblack@eecs.umich.edu            object.__setattr__(self, attr, value)
5885177Sgblack@eecs.umich.edu            return
5895177Sgblack@eecs.umich.edu
5905177Sgblack@eecs.umich.edu        if self._ports.has_key(attr):
5915177Sgblack@eecs.umich.edu            # set up port connection
5925177Sgblack@eecs.umich.edu            self._get_port_ref(attr).connect(value)
5935177Sgblack@eecs.umich.edu            return
5945177Sgblack@eecs.umich.edu
5955177Sgblack@eecs.umich.edu        if isSimObjectOrSequence(value) and self._instantiated:
5965177Sgblack@eecs.umich.edu            raise RuntimeError, \
5975177Sgblack@eecs.umich.edu                  "cannot set SimObject parameter '%s' after\n" \
5985177Sgblack@eecs.umich.edu                  "    instance been cloned %s" % (attr, `self`)
5995177Sgblack@eecs.umich.edu
6005177Sgblack@eecs.umich.edu        # must be SimObject param
6015177Sgblack@eecs.umich.edu        param = self._params.get(attr)
6025177Sgblack@eecs.umich.edu        if param:
6035177Sgblack@eecs.umich.edu            try:
6045177Sgblack@eecs.umich.edu                value = param.convert(value)
6055177Sgblack@eecs.umich.edu            except Exception, e:
6065177Sgblack@eecs.umich.edu                msg = "%s\nError setting param %s.%s to %s\n" % \
6075177Sgblack@eecs.umich.edu                      (e, self.__class__.__name__, attr, value)
6085177Sgblack@eecs.umich.edu                e.args = (msg, )
6095177Sgblack@eecs.umich.edu                raise
6105177Sgblack@eecs.umich.edu            self._set_child(attr, value)
6115177Sgblack@eecs.umich.edu            return
6125177Sgblack@eecs.umich.edu
6135177Sgblack@eecs.umich.edu        if isSimObjectOrSequence(value):
6145177Sgblack@eecs.umich.edu            self._set_child(attr, value)
6155177Sgblack@eecs.umich.edu            return
6165177Sgblack@eecs.umich.edu
6175177Sgblack@eecs.umich.edu        # no valid assignment... raise exception
6185177Sgblack@eecs.umich.edu        raise AttributeError, "Class %s has no parameter %s" \
6195177Sgblack@eecs.umich.edu              % (self.__class__.__name__, attr)
6205177Sgblack@eecs.umich.edu
6215177Sgblack@eecs.umich.edu
6225177Sgblack@eecs.umich.edu    # this hack allows tacking a '[0]' onto parameters that may or may
6235177Sgblack@eecs.umich.edu    # not be vectors, and always getting the first element (e.g. cpus)
6245177Sgblack@eecs.umich.edu    def __getitem__(self, key):
6255177Sgblack@eecs.umich.edu        if key == 0:
6265177Sgblack@eecs.umich.edu            return self
6275177Sgblack@eecs.umich.edu        raise TypeError, "Non-zero index '%s' to SimObject" % key
6285177Sgblack@eecs.umich.edu
6295177Sgblack@eecs.umich.edu    # clear out children with given name, even if it's a vector
6305177Sgblack@eecs.umich.edu    def clear_child(self, name):
6315177Sgblack@eecs.umich.edu        if not self._children.has_key(name):
6325177Sgblack@eecs.umich.edu            return
6335177Sgblack@eecs.umich.edu        child = self._children[name]
6345177Sgblack@eecs.umich.edu        if isinstance(child, SimObjVector):
6355177Sgblack@eecs.umich.edu            for i in xrange(len(child)):
6365177Sgblack@eecs.umich.edu                del self._children["s%d" % (name, i)]
6375177Sgblack@eecs.umich.edu        del self._children[name]
6385177Sgblack@eecs.umich.edu
6395177Sgblack@eecs.umich.edu    def add_child(self, name, value):
6405177Sgblack@eecs.umich.edu        self._children[name] = value
6412623SN/A
6422623SN/A    def _maybe_set_parent(self, parent, name):
6434224Sgblack@eecs.umich.edu        if not self._parent:
6444224Sgblack@eecs.umich.edu            self._parent = parent
6454224Sgblack@eecs.umich.edu            self._name = name
6464224Sgblack@eecs.umich.edu            parent.add_child(name, self)
6474224Sgblack@eecs.umich.edu
6484224Sgblack@eecs.umich.edu    def _set_child(self, attr, value):
6494224Sgblack@eecs.umich.edu        # if RHS is a SimObject, it's an implicit child assignment
6504224Sgblack@eecs.umich.edu        # clear out old child with this name, if any
6514224Sgblack@eecs.umich.edu        self.clear_child(attr)
6524224Sgblack@eecs.umich.edu
6534224Sgblack@eecs.umich.edu        if isSimObject(value):
6542623SN/A            value._maybe_set_parent(self, attr)
6552623SN/A        elif isSimObjectSequence(value):
6562623SN/A            value = SimObjVector(value)
6572623SN/A            if len(value) == 1:
6582623SN/A                value[0]._maybe_set_parent(self, attr)
6592623SN/A            else:
6602623SN/A                for i,v in enumerate(value):
6612623SN/A                    v._maybe_set_parent(self, "%s%d" % (attr, i))
6622623SN/A
6632623SN/A        self._values[attr] = value
6642623SN/A
6652623SN/A    def path(self):
6662623SN/A        if not self._parent:
6672623SN/A            return 'root'
6682623SN/A        ppath = self._parent.path()
6692623SN/A        if ppath == 'root':
6702623SN/A            return self._name
6712623SN/A        return ppath + "." + self._name
6722623SN/A
6732623SN/A    def __str__(self):
6742623SN/A        return self.path()
6752623SN/A
6762623SN/A    def ini_str(self):
6772623SN/A        return self.path()
6782623SN/A
6792623SN/A    def find_any(self, ptype):
6802623SN/A        if isinstance(self, ptype):
6812623SN/A            return self, True
6822623SN/A
6832623SN/A        found_obj = None
6842623SN/A        for child in self._children.itervalues():
6852623SN/A            if isinstance(child, ptype):
6862623SN/A                if found_obj != None and child != found_obj:
6872623SN/A                    raise AttributeError, \
6882623SN/A                          'parent.any matched more than one: %s %s' % \
6892623SN/A                          (found_obj.path, child.path)
6902623SN/A                found_obj = child
6912623SN/A        # search param space
6922623SN/A        for pname,pdesc in self._params.iteritems():
6932623SN/A            if issubclass(pdesc.ptype, ptype):
6942623SN/A                match_obj = self._values[pname]
6952623SN/A                if found_obj != None and found_obj != match_obj:
6962623SN/A                    raise AttributeError, \
6972623SN/A                          'parent.any matched more than one: %s' % obj.path
6982623SN/A                found_obj = match_obj
6992623SN/A        return found_obj, found_obj != None
7002623SN/A
7012623SN/A    def unproxy(self, base):
7024940Snate@binkert.org        return self
7034940Snate@binkert.org
7045100Ssaidi@eecs.umich.edu    def unproxy_all(self):
7052623SN/A        for param in self._params.iterkeys():
7062623SN/A            value = self._values.get(param)
7072623SN/A            if value != None and proxy.isproxy(value):
7082623SN/A                try:
7093387Sgblack@eecs.umich.edu                    value = value.unproxy(self)
7103387Sgblack@eecs.umich.edu                except:
7112626SN/A                    print "Error in unproxying param '%s' of %s" % \
7124870Sstever@eecs.umich.edu                          (param, self.path())
7132623SN/A                    raise
7142623SN/A                setattr(self, param, value)
7154182Sgblack@eecs.umich.edu
7164182Sgblack@eecs.umich.edu        # Unproxy ports in sorted order so that 'append' operations on
7174182Sgblack@eecs.umich.edu        # vector ports are done in a deterministic fashion.
7182662Sstever@eecs.umich.edu        port_names = self._ports.keys()
7194182Sgblack@eecs.umich.edu        port_names.sort()
7204593Sgblack@eecs.umich.edu        for port_name in port_names:
7214593Sgblack@eecs.umich.edu            port = self._port_refs.get(port_name)
7224182Sgblack@eecs.umich.edu            if port != None:
7234870Sstever@eecs.umich.edu                port.unproxy(self)
7244870Sstever@eecs.umich.edu
7254870Sstever@eecs.umich.edu        # Unproxy children in sorted order for determinism also.
7262623SN/A        child_names = self._children.keys()
7274968Sacolyte@umich.edu        child_names.sort()
7284968Sacolyte@umich.edu        for child in child_names:
7294968Sacolyte@umich.edu            self._children[child].unproxy_all()
7304968Sacolyte@umich.edu
7314968Sacolyte@umich.edu    def print_ini(self, ini_file):
7324986Ssaidi@eecs.umich.edu        print >>ini_file, '[' + self.path() + ']'       # .ini section header
7334968Sacolyte@umich.edu
7344182Sgblack@eecs.umich.edu        instanceDict[self.path()] = self
7354182Sgblack@eecs.umich.edu
7364593Sgblack@eecs.umich.edu        if hasattr(self, 'type'):
7374182Sgblack@eecs.umich.edu            print >>ini_file, 'type=%s' % self.type
7382623SN/A
7393814Ssaidi@eecs.umich.edu        child_names = self._children.keys()
7405001Sgblack@eecs.umich.edu        child_names.sort()
7414182Sgblack@eecs.umich.edu        if len(child_names):
7424998Sgblack@eecs.umich.edu            print >>ini_file, 'children=%s' % ' '.join(child_names)
7434998Sgblack@eecs.umich.edu
7444998Sgblack@eecs.umich.edu        param_names = self._params.keys()
7454998Sgblack@eecs.umich.edu        param_names.sort()
7465001Sgblack@eecs.umich.edu        for param in param_names:
7475001Sgblack@eecs.umich.edu            value = self._values.get(param)
7485001Sgblack@eecs.umich.edu            if value != None:
7495001Sgblack@eecs.umich.edu                print >>ini_file, '%s=%s' % (param,
7505001Sgblack@eecs.umich.edu                                             self._values[param].ini_str())
7514998Sgblack@eecs.umich.edu
7524182Sgblack@eecs.umich.edu        port_names = self._ports.keys()
7534182Sgblack@eecs.umich.edu        port_names.sort()
7542623SN/A        for port_name in port_names:
7553814Ssaidi@eecs.umich.edu            port = self._port_refs.get(port_name, None)
7564539Sgblack@eecs.umich.edu            if port != None:
7574539Sgblack@eecs.umich.edu                print >>ini_file, '%s=%s' % (port_name, port.ini_str())
7583814Ssaidi@eecs.umich.edu
7593814Ssaidi@eecs.umich.edu        print >>ini_file        # blank line between objects
7602623SN/A
7614182Sgblack@eecs.umich.edu        for child in child_names:
7625100Ssaidi@eecs.umich.edu            self._children[child].print_ini(ini_file)
7632623SN/A
7645100Ssaidi@eecs.umich.edu    def getCCParams(self):
7655100Ssaidi@eecs.umich.edu        if self._ccParams:
7665100Ssaidi@eecs.umich.edu            return self._ccParams
7675100Ssaidi@eecs.umich.edu
7682803Ssaidi@eecs.umich.edu        cc_params_struct = getattr(m5.objects.params, '%sParams' % self.type)
7695100Ssaidi@eecs.umich.edu        cc_params = cc_params_struct()
7702623SN/A        cc_params.pyobj = self
7712623SN/A        cc_params.name = str(self)
7722623SN/A
7734377Sgblack@eecs.umich.edu        param_names = self._params.keys()
7744182Sgblack@eecs.umich.edu        param_names.sort()
7752623SN/A        for param in param_names:
7762623SN/A            value = self._values.get(param)
7772626SN/A            if value is None:
7782626SN/A                continue
7792623SN/A
7802623SN/A            value = value.getValue()
7812623SN/A            if isinstance(self._params[param], VectorParamDesc):
7822623SN/A                assert isinstance(value, list)
7832623SN/A                vec = getattr(cc_params, param)
7842623SN/A                assert not len(vec)
7852623SN/A                for v in value:
7864762Snate@binkert.org                    vec.append(v)
7874762Snate@binkert.org            else:
7882623SN/A                setattr(cc_params, param, value)
7892623SN/A
7904762Snate@binkert.org        port_names = self._ports.keys()
7912623SN/A        port_names.sort()
7922623SN/A        for port_name in port_names:
7932623SN/A            port = self._port_refs.get(port_name, None)
7942623SN/A            if port != None:
7952623SN/A                setattr(cc_params, port_name, port)
7963119Sktlim@umich.edu        self._ccParams = cc_params
7972623SN/A        return self._ccParams
7983661Srdreslin@umich.edu
7992623SN/A    # Get C++ object corresponding to this object, calling C++ if
8002623SN/A    # necessary to construct it.  Does *not* recursively create
8012623SN/A    # children.
8022623SN/A    def getCCObject(self):
8032623SN/A        if not self._ccObject:
8042901Ssaidi@eecs.umich.edu            # Cycles in the configuration heirarchy are not supported. This
8053170Sstever@eecs.umich.edu            # will catch the resulting recursion and stop.
8064776Sgblack@eecs.umich.edu            self._ccObject = -1
8072623SN/A            params = self.getCCParams()
8082623SN/A            self._ccObject = params.create()
8092623SN/A        elif self._ccObject == -1:
8104997Sgblack@eecs.umich.edu            raise RuntimeError, "%s: Cycle found in configuration heirarchy." \
8112623SN/A                  % self.path()
8123617Sbinkertn@umich.edu        return self._ccObject
8133617Sbinkertn@umich.edu
8143617Sbinkertn@umich.edu    # Call C++ to create C++ object corresponding to this object and
8152623SN/A    # (recursively) all its children
8164762Snate@binkert.org    def createCCObject(self):
8174762Snate@binkert.org        self.getCCParams()
8184762Snate@binkert.org        self.getCCObject() # force creation
8192623SN/A        for child in self._children.itervalues():
8202623SN/A            child.createCCObject()
8212623SN/A
8222623SN/A    def getValue(self):
8232623SN/A        return self.getCCObject()
824
825    # Create C++ port connections corresponding to the connections in
826    # _port_refs (& recursively for all children)
827    def connectPorts(self):
828        for portRef in self._port_refs.itervalues():
829            portRef.ccConnect()
830        for child in self._children.itervalues():
831            child.connectPorts()
832
833    def startDrain(self, drain_event, recursive):
834        count = 0
835        if isinstance(self, SimObject):
836            count += self._ccObject.drain(drain_event)
837        if recursive:
838            for child in self._children.itervalues():
839                count += child.startDrain(drain_event, True)
840        return count
841
842    def resume(self):
843        if isinstance(self, SimObject):
844            self._ccObject.resume()
845        for child in self._children.itervalues():
846            child.resume()
847
848    def getMemoryMode(self):
849        if not isinstance(self, m5.objects.System):
850            return None
851
852        return self._ccObject.getMemoryMode()
853
854    def changeTiming(self, mode):
855        if isinstance(self, m5.objects.System):
856            # i don't know if there's a better way to do this - calling
857            # setMemoryMode directly from self._ccObject results in calling
858            # SimObject::setMemoryMode, not the System::setMemoryMode
859            self._ccObject.setMemoryMode(mode)
860        for child in self._children.itervalues():
861            child.changeTiming(mode)
862
863    def takeOverFrom(self, old_cpu):
864        self._ccObject.takeOverFrom(old_cpu._ccObject)
865
866    # generate output file for 'dot' to display as a pretty graph.
867    # this code is currently broken.
868    def outputDot(self, dot):
869        label = "{%s|" % self.path
870        if isSimObject(self.realtype):
871            label +=  '%s|' % self.type
872
873        if self.children:
874            # instantiate children in same order they were added for
875            # backward compatibility (else we can end up with cpu1
876            # before cpu0).
877            for c in self.children:
878                dot.add_edge(pydot.Edge(self.path,c.path, style="bold"))
879
880        simobjs = []
881        for param in self.params:
882            try:
883                if param.value is None:
884                    raise AttributeError, 'Parameter with no value'
885
886                value = param.value
887                string = param.string(value)
888            except Exception, e:
889                msg = 'exception in %s:%s\n%s' % (self.name, param.name, e)
890                e.args = (msg, )
891                raise
892
893            if isSimObject(param.ptype) and string != "Null":
894                simobjs.append(string)
895            else:
896                label += '%s = %s\\n' % (param.name, string)
897
898        for so in simobjs:
899            label += "|<%s> %s" % (so, so)
900            dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so,
901                                    tailport="w"))
902        label += '}'
903        dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label))
904
905        # recursively dump out children
906        for c in self.children:
907            c.outputDot(dot)
908
909# Function to provide to C++ so it can look up instances based on paths
910def resolveSimObject(name):
911    obj = instanceDict[name]
912    return obj.getCCObject()
913
914# __all__ defines the list of symbols that get exported when
915# 'from config import *' is invoked.  Try to keep this reasonably
916# short to avoid polluting other namespaces.
917__all__ = [ 'SimObject' ]
918