SimObject.py revision 7534
12740SN/A# Copyright (c) 2004-2006 The Regents of The University of Michigan
27534Ssteve.reinhardt@amd.com# Copyright (c) 2010 Advanced Micro Devices, Inc.
31046SN/A# All rights reserved.
41046SN/A#
51046SN/A# Redistribution and use in source and binary forms, with or without
61046SN/A# modification, are permitted provided that the following conditions are
71046SN/A# met: redistributions of source code must retain the above copyright
81046SN/A# notice, this list of conditions and the following disclaimer;
91046SN/A# redistributions in binary form must reproduce the above copyright
101046SN/A# notice, this list of conditions and the following disclaimer in the
111046SN/A# documentation and/or other materials provided with the distribution;
121046SN/A# neither the name of the copyright holders nor the names of its
131046SN/A# contributors may be used to endorse or promote products derived from
141046SN/A# this software without specific prior written permission.
151046SN/A#
161046SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
171046SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
181046SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
191046SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
201046SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
211046SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
221046SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
231046SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
241046SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
251046SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
261046SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
272665SN/A#
282665SN/A# Authors: Steve Reinhardt
292665SN/A#          Nathan Binkert
301046SN/A
315766Snate@binkert.orgimport sys
327493Ssteve.reinhardt@amd.comfrom types import FunctionType
331438SN/A
346654Snate@binkert.orgtry:
356654Snate@binkert.org    import pydot
366654Snate@binkert.orgexcept:
376654Snate@binkert.org    pydot = False
386654Snate@binkert.org
394762Snate@binkert.orgimport m5
406654Snate@binkert.orgfrom m5.util import *
413102Sstever@eecs.umich.edu
423102Sstever@eecs.umich.edu# Have to import params up top since Param is referenced on initial
433102Sstever@eecs.umich.edu# load (when SimObject class references Param to create a class
443102Sstever@eecs.umich.edu# variable, the 'name' param)...
456654Snate@binkert.orgfrom m5.params import *
463102Sstever@eecs.umich.edu# There are a few things we need that aren't in params.__all__ since
473102Sstever@eecs.umich.edu# normal users don't need them
487528Ssteve.reinhardt@amd.comfrom m5.params import ParamDesc, VectorParamDesc, \
497528Ssteve.reinhardt@amd.com     isNullPointer, SimObjectVector
503102Sstever@eecs.umich.edu
516654Snate@binkert.orgfrom m5.proxy import *
526654Snate@binkert.orgfrom m5.proxy import isproxy
53679SN/A
54679SN/A#####################################################################
55679SN/A#
56679SN/A# M5 Python Configuration Utility
57679SN/A#
58679SN/A# The basic idea is to write simple Python programs that build Python
591692SN/A# objects corresponding to M5 SimObjects for the desired simulation
60679SN/A# configuration.  For now, the Python emits a .ini file that can be
61679SN/A# parsed by M5.  In the future, some tighter integration between M5
62679SN/A# and the Python interpreter may allow bypassing the .ini file.
63679SN/A#
64679SN/A# Each SimObject class in M5 is represented by a Python class with the
65679SN/A# same name.  The Python inheritance tree mirrors the M5 C++ tree
66679SN/A# (e.g., SimpleCPU derives from BaseCPU in both cases, and all
67679SN/A# SimObjects inherit from a single SimObject base class).  To specify
68679SN/A# an instance of an M5 SimObject in a configuration, the user simply
69679SN/A# instantiates the corresponding Python object.  The parameters for
70679SN/A# that SimObject are given by assigning to attributes of the Python
71679SN/A# object, either using keyword assignment in the constructor or in
72679SN/A# separate assignment statements.  For example:
73679SN/A#
741692SN/A# cache = BaseCache(size='64KB')
75679SN/A# cache.hit_latency = 3
76679SN/A# cache.assoc = 8
77679SN/A#
78679SN/A# The magic lies in the mapping of the Python attributes for SimObject
79679SN/A# classes to the actual SimObject parameter specifications.  This
80679SN/A# allows parameter validity checking in the Python code.  Continuing
81679SN/A# the example above, the statements "cache.blurfl=3" or
82679SN/A# "cache.assoc='hello'" would both result in runtime errors in Python,
83679SN/A# since the BaseCache object has no 'blurfl' parameter and the 'assoc'
84679SN/A# parameter requires an integer, respectively.  This magic is done
85679SN/A# primarily by overriding the special __setattr__ method that controls
86679SN/A# assignment to object attributes.
87679SN/A#
88679SN/A# Once a set of Python objects have been instantiated in a hierarchy,
89679SN/A# calling 'instantiate(obj)' (where obj is the root of the hierarchy)
902740SN/A# will generate a .ini file.
91679SN/A#
92679SN/A#####################################################################
93679SN/A
944762Snate@binkert.org# list of all SimObject classes
954762Snate@binkert.orgallClasses = {}
964762Snate@binkert.org
972738SN/A# dict to look up SimObjects based on path
982738SN/AinstanceDict = {}
992738SN/A
1002740SN/A# The metaclass for SimObject.  This class controls how new classes
1012740SN/A# that derive from SimObject are instantiated, and provides inherited
1022740SN/A# class behavior (just like a class controls how instances of that
1032740SN/A# class are instantiated, and provides inherited instance behavior).
1041692SN/Aclass MetaSimObject(type):
1051427SN/A    # Attributes that can be set only at initialization time
1067493Ssteve.reinhardt@amd.com    init_keywords = { 'abstract' : bool,
1077493Ssteve.reinhardt@amd.com                      'cxx_class' : str,
1087493Ssteve.reinhardt@amd.com                      'cxx_type' : str,
1097493Ssteve.reinhardt@amd.com                      'cxx_predecls' : list,
1107493Ssteve.reinhardt@amd.com                      'swig_objdecls' : list,
1117493Ssteve.reinhardt@amd.com                      'swig_predecls' : list,
1127493Ssteve.reinhardt@amd.com                      'type' : str }
1131427SN/A    # Attributes that can be set any time
1147493Ssteve.reinhardt@amd.com    keywords = { 'check' : FunctionType }
115679SN/A
116679SN/A    # __new__ is called before __init__, and is where the statements
117679SN/A    # in the body of the class definition get loaded into the class's
1182740SN/A    # __dict__.  We intercept this to filter out parameter & port assignments
119679SN/A    # and only allow "private" attributes to be passed to the base
120679SN/A    # __new__ (starting with underscore).
1211310SN/A    def __new__(mcls, name, bases, dict):
1226654Snate@binkert.org        assert name not in allClasses, "SimObject %s already present" % name
1234762Snate@binkert.org
1242740SN/A        # Copy "private" attributes, functions, and classes to the
1252740SN/A        # official dict.  Everything else goes in _init_dict to be
1262740SN/A        # filtered in __init__.
1272740SN/A        cls_dict = {}
1282740SN/A        value_dict = {}
1292740SN/A        for key,val in dict.items():
1307493Ssteve.reinhardt@amd.com            if key.startswith('_') or isinstance(val, (FunctionType,
1317493Ssteve.reinhardt@amd.com                                                       classmethod,
1327493Ssteve.reinhardt@amd.com                                                       type)):
1332740SN/A                cls_dict[key] = val
1342740SN/A            else:
1352740SN/A                # must be a param/port setting
1362740SN/A                value_dict[key] = val
1374762Snate@binkert.org        if 'abstract' not in value_dict:
1384762Snate@binkert.org            value_dict['abstract'] = False
1392740SN/A        cls_dict['_value_dict'] = value_dict
1404762Snate@binkert.org        cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict)
1414762Snate@binkert.org        if 'type' in value_dict:
1424762Snate@binkert.org            allClasses[name] = cls
1434762Snate@binkert.org        return cls
144679SN/A
1452711SN/A    # subclass initialization
146679SN/A    def __init__(cls, name, bases, dict):
1472711SN/A        # calls type.__init__()... I think that's a no-op, but leave
1482711SN/A        # it here just in case it's not.
1491692SN/A        super(MetaSimObject, cls).__init__(name, bases, dict)
1501310SN/A
1511427SN/A        # initialize required attributes
1522740SN/A
1532740SN/A        # class-only attributes
1542740SN/A        cls._params = multidict() # param descriptions
1552740SN/A        cls._ports = multidict()  # port descriptions
1562740SN/A
1572740SN/A        # class or instance attributes
1582740SN/A        cls._values = multidict()   # param values
1597528Ssteve.reinhardt@amd.com        cls._children = multidict() # SimObject children
1603105Sstever@eecs.umich.edu        cls._port_refs = multidict() # port ref objects
1612740SN/A        cls._instantiated = False # really instantiated, cloned, or subclassed
1621310SN/A
1631692SN/A        # We don't support multiple inheritance.  If you want to, you
1641585SN/A        # must fix multidict to deal with it properly.
1651692SN/A        if len(bases) > 1:
1661692SN/A            raise TypeError, "SimObjects do not support multiple inheritance"
1671692SN/A
1681692SN/A        base = bases[0]
1691692SN/A
1702740SN/A        # Set up general inheritance via multidicts.  A subclass will
1712740SN/A        # inherit all its settings from the base class.  The only time
1722740SN/A        # the following is not true is when we define the SimObject
1732740SN/A        # class itself (in which case the multidicts have no parent).
1741692SN/A        if isinstance(base, MetaSimObject):
1755610Snate@binkert.org            cls._base = base
1761692SN/A            cls._params.parent = base._params
1772740SN/A            cls._ports.parent = base._ports
1781692SN/A            cls._values.parent = base._values
1797528Ssteve.reinhardt@amd.com            cls._children.parent = base._children
1803105Sstever@eecs.umich.edu            cls._port_refs.parent = base._port_refs
1812740SN/A            # mark base as having been subclassed
1822712SN/A            base._instantiated = True
1835610Snate@binkert.org        else:
1845610Snate@binkert.org            cls._base = None
1851692SN/A
1864762Snate@binkert.org        # default keyword values
1874762Snate@binkert.org        if 'type' in cls._value_dict:
1884762Snate@binkert.org            if 'cxx_class' not in cls._value_dict:
1895610Snate@binkert.org                cls._value_dict['cxx_class'] = cls._value_dict['type']
1904762Snate@binkert.org
1915610Snate@binkert.org            cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class']
1925610Snate@binkert.org
1934762Snate@binkert.org            if 'cxx_predecls' not in cls._value_dict:
1944762Snate@binkert.org                # A forward class declaration is sufficient since we are
1954762Snate@binkert.org                # just declaring a pointer.
1965610Snate@binkert.org                class_path = cls._value_dict['cxx_class'].split('::')
1975610Snate@binkert.org                class_path.reverse()
1985610Snate@binkert.org                decl = 'class %s;' % class_path[0]
1995610Snate@binkert.org                for ns in class_path[1:]:
2005610Snate@binkert.org                    decl = 'namespace %s { %s }' % (ns, decl)
2014762Snate@binkert.org                cls._value_dict['cxx_predecls'] = [decl]
2024762Snate@binkert.org
2034762Snate@binkert.org            if 'swig_predecls' not in cls._value_dict:
2044762Snate@binkert.org                # A forward class declaration is sufficient since we are
2054762Snate@binkert.org                # just declaring a pointer.
2064762Snate@binkert.org                cls._value_dict['swig_predecls'] = \
2074762Snate@binkert.org                    cls._value_dict['cxx_predecls']
2084762Snate@binkert.org
2094859Snate@binkert.org        if 'swig_objdecls' not in cls._value_dict:
2104859Snate@binkert.org            cls._value_dict['swig_objdecls'] = []
2114859Snate@binkert.org
2122740SN/A        # Now process the _value_dict items.  They could be defining
2132740SN/A        # new (or overriding existing) parameters or ports, setting
2142740SN/A        # class keywords (e.g., 'abstract'), or setting parameter
2152740SN/A        # values or port bindings.  The first 3 can only be set when
2162740SN/A        # the class is defined, so we handle them here.  The others
2172740SN/A        # can be set later too, so just emulate that by calling
2182740SN/A        # setattr().
2192740SN/A        for key,val in cls._value_dict.items():
2201527SN/A            # param descriptions
2212740SN/A            if isinstance(val, ParamDesc):
2221585SN/A                cls._new_param(key, val)
2231427SN/A
2242738SN/A            # port objects
2252738SN/A            elif isinstance(val, Port):
2263105Sstever@eecs.umich.edu                cls._new_port(key, val)
2272738SN/A
2281427SN/A            # init-time-only keywords
2291427SN/A            elif cls.init_keywords.has_key(key):
2301427SN/A                cls._set_keyword(key, val, cls.init_keywords[key])
2311427SN/A
2321427SN/A            # default: use normal path (ends up in __setattr__)
2331427SN/A            else:
2341427SN/A                setattr(cls, key, val)
2351427SN/A
2361427SN/A    def _set_keyword(cls, keyword, val, kwtype):
2371427SN/A        if not isinstance(val, kwtype):
2381427SN/A            raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
2391427SN/A                  (keyword, type(val), kwtype)
2407493Ssteve.reinhardt@amd.com        if isinstance(val, FunctionType):
2411427SN/A            val = classmethod(val)
2421427SN/A        type.__setattr__(cls, keyword, val)
2431427SN/A
2443100SN/A    def _new_param(cls, name, pdesc):
2453100SN/A        # each param desc should be uniquely assigned to one variable
2463100SN/A        assert(not hasattr(pdesc, 'name'))
2473100SN/A        pdesc.name = name
2483100SN/A        cls._params[name] = pdesc
2493100SN/A        if hasattr(pdesc, 'default'):
2503105Sstever@eecs.umich.edu            cls._set_param(name, pdesc.default, pdesc)
2513105Sstever@eecs.umich.edu
2523105Sstever@eecs.umich.edu    def _set_param(cls, name, value, param):
2533105Sstever@eecs.umich.edu        assert(param.name == name)
2543105Sstever@eecs.umich.edu        try:
2553105Sstever@eecs.umich.edu            cls._values[name] = param.convert(value)
2563105Sstever@eecs.umich.edu        except Exception, e:
2573105Sstever@eecs.umich.edu            msg = "%s\nError setting param %s.%s to %s\n" % \
2583105Sstever@eecs.umich.edu                  (e, cls.__name__, name, value)
2593105Sstever@eecs.umich.edu            e.args = (msg, )
2603105Sstever@eecs.umich.edu            raise
2613105Sstever@eecs.umich.edu
2623105Sstever@eecs.umich.edu    def _new_port(cls, name, port):
2633105Sstever@eecs.umich.edu        # each port should be uniquely assigned to one variable
2643105Sstever@eecs.umich.edu        assert(not hasattr(port, 'name'))
2653105Sstever@eecs.umich.edu        port.name = name
2663105Sstever@eecs.umich.edu        cls._ports[name] = port
2673105Sstever@eecs.umich.edu        if hasattr(port, 'default'):
2683105Sstever@eecs.umich.edu            cls._cls_get_port_ref(name).connect(port.default)
2693105Sstever@eecs.umich.edu
2703105Sstever@eecs.umich.edu    # same as _get_port_ref, effectively, but for classes
2713105Sstever@eecs.umich.edu    def _cls_get_port_ref(cls, attr):
2723105Sstever@eecs.umich.edu        # Return reference that can be assigned to another port
2733105Sstever@eecs.umich.edu        # via __setattr__.  There is only ever one reference
2743105Sstever@eecs.umich.edu        # object per port, but we create them lazily here.
2753105Sstever@eecs.umich.edu        ref = cls._port_refs.get(attr)
2763105Sstever@eecs.umich.edu        if not ref:
2773105Sstever@eecs.umich.edu            ref = cls._ports[attr].makeRef(cls)
2783105Sstever@eecs.umich.edu            cls._port_refs[attr] = ref
2793105Sstever@eecs.umich.edu        return ref
2801585SN/A
2811310SN/A    # Set attribute (called on foo.attr = value when foo is an
2821310SN/A    # instance of class cls).
2831310SN/A    def __setattr__(cls, attr, value):
2841310SN/A        # normal processing for private attributes
2851310SN/A        if attr.startswith('_'):
2861310SN/A            type.__setattr__(cls, attr, value)
2871310SN/A            return
2881310SN/A
2891310SN/A        if cls.keywords.has_key(attr):
2901427SN/A            cls._set_keyword(attr, value, cls.keywords[attr])
2911310SN/A            return
2921310SN/A
2932738SN/A        if cls._ports.has_key(attr):
2943105Sstever@eecs.umich.edu            cls._cls_get_port_ref(attr).connect(value)
2952738SN/A            return
2962738SN/A
2972740SN/A        if isSimObjectOrSequence(value) and cls._instantiated:
2982740SN/A            raise RuntimeError, \
2992740SN/A                  "cannot set SimObject parameter '%s' after\n" \
3002740SN/A                  "    class %s has been instantiated or subclassed" \
3012740SN/A                  % (attr, cls.__name__)
3022740SN/A
3032740SN/A        # check for param
3043105Sstever@eecs.umich.edu        param = cls._params.get(attr)
3051310SN/A        if param:
3063105Sstever@eecs.umich.edu            cls._set_param(attr, value, param)
3073105Sstever@eecs.umich.edu            return
3083105Sstever@eecs.umich.edu
3093105Sstever@eecs.umich.edu        if isSimObjectOrSequence(value):
3103105Sstever@eecs.umich.edu            # If RHS is a SimObject, it's an implicit child assignment.
3117528Ssteve.reinhardt@amd.com            cls._children[attr] = coerceSimObjectOrVector(value)
3123105Sstever@eecs.umich.edu            return
3133105Sstever@eecs.umich.edu
3143105Sstever@eecs.umich.edu        # no valid assignment... raise exception
3153105Sstever@eecs.umich.edu        raise AttributeError, \
3163105Sstever@eecs.umich.edu              "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
3171310SN/A
3181585SN/A    def __getattr__(cls, attr):
3191692SN/A        if cls._values.has_key(attr):
3201692SN/A            return cls._values[attr]
3211585SN/A
3227528Ssteve.reinhardt@amd.com        if cls._children.has_key(attr):
3237528Ssteve.reinhardt@amd.com            return cls._children[attr]
3247528Ssteve.reinhardt@amd.com
3251585SN/A        raise AttributeError, \
3261585SN/A              "object '%s' has no attribute '%s'" % (cls.__name__, attr)
3271585SN/A
3283100SN/A    def __str__(cls):
3293100SN/A        return cls.__name__
3303100SN/A
3313100SN/A    def cxx_decl(cls):
3324762Snate@binkert.org        code = "#ifndef __PARAMS__%s\n" % cls
3334762Snate@binkert.org        code += "#define __PARAMS__%s\n\n" % cls
3344762Snate@binkert.org
3353100SN/A        # The 'dict' attribute restricts us to the params declared in
3363100SN/A        # the object itself, not including inherited params (which
3373100SN/A        # will also be inherited from the base class's param struct
3383100SN/A        # here).
3394762Snate@binkert.org        params = cls._params.local.values()
3403100SN/A        try:
3413100SN/A            ptypes = [p.ptype for p in params]
3423100SN/A        except:
3433100SN/A            print cls, p, p.ptype_str
3443100SN/A            print params
3453100SN/A            raise
3463100SN/A
3473100SN/A        # get a list of lists of predeclaration lines
3484762Snate@binkert.org        predecls = []
3494762Snate@binkert.org        predecls.extend(cls.cxx_predecls)
3504762Snate@binkert.org        for p in params:
3514762Snate@binkert.org            predecls.extend(p.cxx_predecls())
3524762Snate@binkert.org        # remove redundant lines
3534762Snate@binkert.org        predecls2 = []
3544762Snate@binkert.org        for pd in predecls:
3554762Snate@binkert.org            if pd not in predecls2:
3564762Snate@binkert.org                predecls2.append(pd)
3574762Snate@binkert.org        predecls2.sort()
3584762Snate@binkert.org        code += "\n".join(predecls2)
3594762Snate@binkert.org        code += "\n\n";
3604762Snate@binkert.org
3615610Snate@binkert.org        if cls._base:
3625610Snate@binkert.org            code += '#include "params/%s.hh"\n\n' % cls._base.type
3634762Snate@binkert.org
3644762Snate@binkert.org        for ptype in ptypes:
3654762Snate@binkert.org            if issubclass(ptype, Enum):
3664762Snate@binkert.org                code += '#include "enums/%s.hh"\n' % ptype.__name__
3674762Snate@binkert.org                code += "\n\n"
3684762Snate@binkert.org
3695610Snate@binkert.org        code += cls.cxx_struct(cls._base, params)
3705488Snate@binkert.org
3715488Snate@binkert.org        # close #ifndef __PARAMS__* guard
3725488Snate@binkert.org        code += "\n#endif\n"
3735488Snate@binkert.org        return code
3745488Snate@binkert.org
3755488Snate@binkert.org    def cxx_struct(cls, base, params):
3765488Snate@binkert.org        if cls == SimObject:
3775488Snate@binkert.org            return '#include "sim/sim_object_params.hh"\n'
3785488Snate@binkert.org
3794762Snate@binkert.org        # now generate the actual param struct
3805488Snate@binkert.org        code = "struct %sParams" % cls
3814762Snate@binkert.org        if base:
3825610Snate@binkert.org            code += " : public %sParams" % base.type
3834762Snate@binkert.org        code += "\n{\n"
3844762Snate@binkert.org        if not hasattr(cls, 'abstract') or not cls.abstract:
3854762Snate@binkert.org            if 'type' in cls.__dict__:
3864762Snate@binkert.org                code += "    %s create();\n" % cls.cxx_type
3874762Snate@binkert.org        decls = [p.cxx_decl() for p in params]
3884762Snate@binkert.org        decls.sort()
3894762Snate@binkert.org        code += "".join(["    %s\n" % d for d in decls])
3904762Snate@binkert.org        code += "};\n"
3914762Snate@binkert.org
3924762Snate@binkert.org        return code
3934762Snate@binkert.org
3944762Snate@binkert.org    def swig_decl(cls):
3954762Snate@binkert.org        code = '%%module %s\n' % cls
3964762Snate@binkert.org
3974762Snate@binkert.org        code += '%{\n'
3984762Snate@binkert.org        code += '#include "params/%s.hh"\n' % cls
3994762Snate@binkert.org        code += '%}\n\n'
4004762Snate@binkert.org
4014762Snate@binkert.org        # The 'dict' attribute restricts us to the params declared in
4024762Snate@binkert.org        # the object itself, not including inherited params (which
4034762Snate@binkert.org        # will also be inherited from the base class's param struct
4044762Snate@binkert.org        # here).
4054762Snate@binkert.org        params = cls._params.local.values()
4064762Snate@binkert.org        ptypes = [p.ptype for p in params]
4074762Snate@binkert.org
4084762Snate@binkert.org        # get a list of lists of predeclaration lines
4094762Snate@binkert.org        predecls = []
4104762Snate@binkert.org        predecls.extend([ p.swig_predecls() for p in params ])
4113100SN/A        # flatten
4123100SN/A        predecls = reduce(lambda x,y:x+y, predecls, [])
4133100SN/A        # remove redundant lines
4143100SN/A        predecls2 = []
4153100SN/A        for pd in predecls:
4163100SN/A            if pd not in predecls2:
4173100SN/A                predecls2.append(pd)
4183100SN/A        predecls2.sort()
4193100SN/A        code += "\n".join(predecls2)
4203100SN/A        code += "\n\n";
4213100SN/A
4225610Snate@binkert.org        if cls._base:
4235610Snate@binkert.org            code += '%%import "params/%s.i"\n\n' % cls._base.type
4243100SN/A
4254762Snate@binkert.org        for ptype in ptypes:
4264762Snate@binkert.org            if issubclass(ptype, Enum):
4274762Snate@binkert.org                code += '%%import "enums/%s.hh"\n' % ptype.__name__
4284762Snate@binkert.org                code += "\n\n"
4293100SN/A
4304762Snate@binkert.org        code += '%%import "params/%s_type.hh"\n\n' % cls
4313100SN/A        code += '%%include "params/%s.hh"\n\n' % cls
4323100SN/A
4333100SN/A        return code
4343100SN/A
4352740SN/A# The SimObject class is the root of the special hierarchy.  Most of
436679SN/A# the code in this class deals with the configuration hierarchy itself
437679SN/A# (parent/child node relationships).
4381692SN/Aclass SimObject(object):
4391692SN/A    # Specify metaclass.  Any class inheriting from SimObject will
440679SN/A    # get this metaclass.
4411692SN/A    __metaclass__ = MetaSimObject
4423100SN/A    type = 'SimObject'
4434762Snate@binkert.org    abstract = True
4443100SN/A
4454859Snate@binkert.org    swig_objdecls = [ '%include "python/swig/sim_object.i"' ]
446679SN/A
4472740SN/A    # Initialize new instance.  For objects with SimObject-valued
4482740SN/A    # children, we need to recursively clone the classes represented
4492740SN/A    # by those param values as well in a consistent "deep copy"-style
4502740SN/A    # fashion.  That is, we want to make sure that each instance is
4512740SN/A    # cloned only once, and that if there are multiple references to
4522740SN/A    # the same original object, we end up with the corresponding
4532740SN/A    # cloned references all pointing to the same cloned instance.
4542740SN/A    def __init__(self, **kwargs):
4552740SN/A        ancestor = kwargs.get('_ancestor')
4562740SN/A        memo_dict = kwargs.get('_memo')
4572740SN/A        if memo_dict is None:
4582740SN/A            # prepare to memoize any recursively instantiated objects
4592740SN/A            memo_dict = {}
4602740SN/A        elif ancestor:
4612740SN/A            # memoize me now to avoid problems with recursive calls
4622740SN/A            memo_dict[ancestor] = self
4632711SN/A
4642740SN/A        if not ancestor:
4652740SN/A            ancestor = self.__class__
4662740SN/A        ancestor._instantiated = True
4672711SN/A
4682740SN/A        # initialize required attributes
4692740SN/A        self._parent = None
4707528Ssteve.reinhardt@amd.com        self._name = None
4712740SN/A        self._ccObject = None  # pointer to C++ object
4724762Snate@binkert.org        self._ccParams = None
4732740SN/A        self._instantiated = False # really "cloned"
4742712SN/A
4752711SN/A        # Inherit parameter values from class using multidict so
4767528Ssteve.reinhardt@amd.com        # individual value settings can be overridden but we still
4777528Ssteve.reinhardt@amd.com        # inherit late changes to non-overridden class values.
4782740SN/A        self._values = multidict(ancestor._values)
4792740SN/A        # clone SimObject-valued parameters
4802740SN/A        for key,val in ancestor._values.iteritems():
4817528Ssteve.reinhardt@amd.com            val = tryAsSimObjectOrVector(val)
4827528Ssteve.reinhardt@amd.com            if val is not None:
4837528Ssteve.reinhardt@amd.com                self._values[key] = val(_memo=memo_dict)
4847528Ssteve.reinhardt@amd.com
4857528Ssteve.reinhardt@amd.com        # Clone children specified at class level.  No need for a
4867528Ssteve.reinhardt@amd.com        # multidict here since we will be cloning everything.
4877528Ssteve.reinhardt@amd.com        self._children = {}
4887528Ssteve.reinhardt@amd.com        for key,val in ancestor._children.iteritems():
4897528Ssteve.reinhardt@amd.com            self.add_child(key, val(_memo=memo_dict))
4907528Ssteve.reinhardt@amd.com
4912740SN/A        # clone port references.  no need to use a multidict here
4922740SN/A        # since we will be creating new references for all ports.
4933105Sstever@eecs.umich.edu        self._port_refs = {}
4943105Sstever@eecs.umich.edu        for key,val in ancestor._port_refs.iteritems():
4953105Sstever@eecs.umich.edu            self._port_refs[key] = val.clone(self, memo_dict)
4961692SN/A        # apply attribute assignments from keyword args, if any
4971692SN/A        for key,val in kwargs.iteritems():
4981692SN/A            setattr(self, key, val)
499679SN/A
5002740SN/A    # "Clone" the current instance by creating another instance of
5012740SN/A    # this instance's class, but that inherits its parameter values
5022740SN/A    # and port mappings from the current instance.  If we're in a
5032740SN/A    # "deep copy" recursive clone, check the _memo dict to see if
5042740SN/A    # we've already cloned this instance.
5051692SN/A    def __call__(self, **kwargs):
5062740SN/A        memo_dict = kwargs.get('_memo')
5072740SN/A        if memo_dict is None:
5082740SN/A            # no memo_dict: must be top-level clone operation.
5092740SN/A            # this is only allowed at the root of a hierarchy
5102740SN/A            if self._parent:
5112740SN/A                raise RuntimeError, "attempt to clone object %s " \
5122740SN/A                      "not at the root of a tree (parent = %s)" \
5132740SN/A                      % (self, self._parent)
5142740SN/A            # create a new dict and use that.
5152740SN/A            memo_dict = {}
5162740SN/A            kwargs['_memo'] = memo_dict
5172740SN/A        elif memo_dict.has_key(self):
5182740SN/A            # clone already done & memoized
5192740SN/A            return memo_dict[self]
5202740SN/A        return self.__class__(_ancestor = self, **kwargs)
5211343SN/A
5223105Sstever@eecs.umich.edu    def _get_port_ref(self, attr):
5233105Sstever@eecs.umich.edu        # Return reference that can be assigned to another port
5243105Sstever@eecs.umich.edu        # via __setattr__.  There is only ever one reference
5253105Sstever@eecs.umich.edu        # object per port, but we create them lazily here.
5263105Sstever@eecs.umich.edu        ref = self._port_refs.get(attr)
5273105Sstever@eecs.umich.edu        if not ref:
5283105Sstever@eecs.umich.edu            ref = self._ports[attr].makeRef(self)
5293105Sstever@eecs.umich.edu            self._port_refs[attr] = ref
5303105Sstever@eecs.umich.edu        return ref
5313105Sstever@eecs.umich.edu
5321692SN/A    def __getattr__(self, attr):
5332738SN/A        if self._ports.has_key(attr):
5343105Sstever@eecs.umich.edu            return self._get_port_ref(attr)
5352738SN/A
5361692SN/A        if self._values.has_key(attr):
5371692SN/A            return self._values[attr]
5381427SN/A
5397528Ssteve.reinhardt@amd.com        if self._children.has_key(attr):
5407528Ssteve.reinhardt@amd.com            return self._children[attr]
5417528Ssteve.reinhardt@amd.com
5427500Ssteve.reinhardt@amd.com        # If the attribute exists on the C++ object, transparently
5437500Ssteve.reinhardt@amd.com        # forward the reference there.  This is typically used for
5447500Ssteve.reinhardt@amd.com        # SWIG-wrapped methods such as init(), regStats(),
5457527Ssteve.reinhardt@amd.com        # regFormulas(), resetStats(), startup(), drain(), and
5467527Ssteve.reinhardt@amd.com        # resume().
5477500Ssteve.reinhardt@amd.com        if self._ccObject and hasattr(self._ccObject, attr):
5487500Ssteve.reinhardt@amd.com            return getattr(self._ccObject, attr)
5497500Ssteve.reinhardt@amd.com
5501692SN/A        raise AttributeError, "object '%s' has no attribute '%s'" \
5511692SN/A              % (self.__class__.__name__, attr)
5521427SN/A
5531692SN/A    # Set attribute (called on foo.attr = value when foo is an
5541692SN/A    # instance of class cls).
5551692SN/A    def __setattr__(self, attr, value):
5561692SN/A        # normal processing for private attributes
5571692SN/A        if attr.startswith('_'):
5581692SN/A            object.__setattr__(self, attr, value)
5591692SN/A            return
5601427SN/A
5612738SN/A        if self._ports.has_key(attr):
5622738SN/A            # set up port connection
5633105Sstever@eecs.umich.edu            self._get_port_ref(attr).connect(value)
5642738SN/A            return
5652738SN/A
5662740SN/A        if isSimObjectOrSequence(value) and self._instantiated:
5672740SN/A            raise RuntimeError, \
5682740SN/A                  "cannot set SimObject parameter '%s' after\n" \
5692740SN/A                  "    instance been cloned %s" % (attr, `self`)
5702740SN/A
5713105Sstever@eecs.umich.edu        param = self._params.get(attr)
5721692SN/A        if param:
5731310SN/A            try:
5741692SN/A                value = param.convert(value)
5751587SN/A            except Exception, e:
5761692SN/A                msg = "%s\nError setting param %s.%s to %s\n" % \
5771692SN/A                      (e, self.__class__.__name__, attr, value)
5781605SN/A                e.args = (msg, )
5791605SN/A                raise
5807528Ssteve.reinhardt@amd.com            self._values[attr] = value
5813105Sstever@eecs.umich.edu            return
5821310SN/A
5837528Ssteve.reinhardt@amd.com        # if RHS is a SimObject, it's an implicit child assignment
5843105Sstever@eecs.umich.edu        if isSimObjectOrSequence(value):
5857528Ssteve.reinhardt@amd.com            self.add_child(attr, value)
5863105Sstever@eecs.umich.edu            return
5871693SN/A
5883105Sstever@eecs.umich.edu        # no valid assignment... raise exception
5893105Sstever@eecs.umich.edu        raise AttributeError, "Class %s has no parameter %s" \
5903105Sstever@eecs.umich.edu              % (self.__class__.__name__, attr)
5911310SN/A
5921310SN/A
5931692SN/A    # this hack allows tacking a '[0]' onto parameters that may or may
5941692SN/A    # not be vectors, and always getting the first element (e.g. cpus)
5951692SN/A    def __getitem__(self, key):
5961692SN/A        if key == 0:
5971692SN/A            return self
5981692SN/A        raise TypeError, "Non-zero index '%s' to SimObject" % key
5991310SN/A
6007528Ssteve.reinhardt@amd.com    # Also implemented by SimObjectVector
6017528Ssteve.reinhardt@amd.com    def clear_parent(self, old_parent):
6027528Ssteve.reinhardt@amd.com        assert self._parent is old_parent
6037528Ssteve.reinhardt@amd.com        self._parent = None
6047528Ssteve.reinhardt@amd.com
6057528Ssteve.reinhardt@amd.com    # Also implemented by SimObjectVector
6067528Ssteve.reinhardt@amd.com    def set_parent(self, parent, name):
6077528Ssteve.reinhardt@amd.com        self._parent = parent
6087528Ssteve.reinhardt@amd.com        self._name = name
6097528Ssteve.reinhardt@amd.com
6107528Ssteve.reinhardt@amd.com    # Also implemented by SimObjectVector
6117528Ssteve.reinhardt@amd.com    def get_name(self):
6127528Ssteve.reinhardt@amd.com        return self._name
6137528Ssteve.reinhardt@amd.com
6147528Ssteve.reinhardt@amd.com    # use this rather than directly accessing _parent for symmetry
6157528Ssteve.reinhardt@amd.com    # with SimObjectVector
6167528Ssteve.reinhardt@amd.com    def get_parent(self):
6177528Ssteve.reinhardt@amd.com        return self._parent
6187528Ssteve.reinhardt@amd.com
6197528Ssteve.reinhardt@amd.com    # clear out child with given name
6201693SN/A    def clear_child(self, name):
6211693SN/A        child = self._children[name]
6227528Ssteve.reinhardt@amd.com        child.clear_parent(self)
6231693SN/A        del self._children[name]
6241693SN/A
6257528Ssteve.reinhardt@amd.com    # Add a new child to this object.
6267528Ssteve.reinhardt@amd.com    def add_child(self, name, child):
6277528Ssteve.reinhardt@amd.com        child = coerceSimObjectOrVector(child)
6287528Ssteve.reinhardt@amd.com        if child.get_parent():
6297528Ssteve.reinhardt@amd.com            raise RuntimeError, \
6307528Ssteve.reinhardt@amd.com                  "add_child('%s'): child '%s' already has parent '%s'" % \
6317528Ssteve.reinhardt@amd.com                  (name, child._name, child._parent)
6327528Ssteve.reinhardt@amd.com        if self._children.has_key(name):
6337528Ssteve.reinhardt@amd.com            clear_child(name)
6347528Ssteve.reinhardt@amd.com        child.set_parent(self, name)
6357528Ssteve.reinhardt@amd.com        self._children[name] = child
6361310SN/A
6377528Ssteve.reinhardt@amd.com    # Take SimObject-valued parameters that haven't been explicitly
6387528Ssteve.reinhardt@amd.com    # assigned as children and make them children of the object that
6397528Ssteve.reinhardt@amd.com    # they were assigned to as a parameter value.  This guarantees
6407528Ssteve.reinhardt@amd.com    # that when we instantiate all the parameter objects we're still
6417528Ssteve.reinhardt@amd.com    # inside the configuration hierarchy.
6427528Ssteve.reinhardt@amd.com    def adoptOrphanParams(self):
6437528Ssteve.reinhardt@amd.com        for key,val in self._values.iteritems():
6447528Ssteve.reinhardt@amd.com            if not isSimObjectVector(val) and isSimObjectSequence(val):
6457528Ssteve.reinhardt@amd.com                # need to convert raw SimObject sequences to
6467528Ssteve.reinhardt@amd.com                # SimObjectVector class so we can call get_parent()
6477528Ssteve.reinhardt@amd.com                val = SimObjectVector(val)
6487528Ssteve.reinhardt@amd.com                self._values[key] = val
6497528Ssteve.reinhardt@amd.com            if isSimObjectOrVector(val) and not val.get_parent():
6507528Ssteve.reinhardt@amd.com                self.add_child(key, val)
6513105Sstever@eecs.umich.edu
6521692SN/A    def path(self):
6532740SN/A        if not self._parent:
6547525Ssteve.reinhardt@amd.com            return '(orphan)'
6551692SN/A        ppath = self._parent.path()
6561692SN/A        if ppath == 'root':
6571692SN/A            return self._name
6581692SN/A        return ppath + "." + self._name
6591310SN/A
6601692SN/A    def __str__(self):
6611692SN/A        return self.path()
6621310SN/A
6631692SN/A    def ini_str(self):
6641692SN/A        return self.path()
6651310SN/A
6661692SN/A    def find_any(self, ptype):
6671692SN/A        if isinstance(self, ptype):
6681692SN/A            return self, True
6691310SN/A
6701692SN/A        found_obj = None
6711692SN/A        for child in self._children.itervalues():
6721692SN/A            if isinstance(child, ptype):
6731692SN/A                if found_obj != None and child != found_obj:
6741692SN/A                    raise AttributeError, \
6751692SN/A                          'parent.any matched more than one: %s %s' % \
6761814SN/A                          (found_obj.path, child.path)
6771692SN/A                found_obj = child
6781692SN/A        # search param space
6791692SN/A        for pname,pdesc in self._params.iteritems():
6801692SN/A            if issubclass(pdesc.ptype, ptype):
6811692SN/A                match_obj = self._values[pname]
6821692SN/A                if found_obj != None and found_obj != match_obj:
6831692SN/A                    raise AttributeError, \
6845952Ssaidi@eecs.umich.edu                          'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path)
6851692SN/A                found_obj = match_obj
6861692SN/A        return found_obj, found_obj != None
6871692SN/A
6881815SN/A    def unproxy(self, base):
6891815SN/A        return self
6901815SN/A
6917527Ssteve.reinhardt@amd.com    def unproxyParams(self):
6923105Sstever@eecs.umich.edu        for param in self._params.iterkeys():
6933105Sstever@eecs.umich.edu            value = self._values.get(param)
6946654Snate@binkert.org            if value != None and isproxy(value):
6953105Sstever@eecs.umich.edu                try:
6963105Sstever@eecs.umich.edu                    value = value.unproxy(self)
6973105Sstever@eecs.umich.edu                except:
6983105Sstever@eecs.umich.edu                    print "Error in unproxying param '%s' of %s" % \
6993105Sstever@eecs.umich.edu                          (param, self.path())
7003105Sstever@eecs.umich.edu                    raise
7013105Sstever@eecs.umich.edu                setattr(self, param, value)
7023105Sstever@eecs.umich.edu
7033107Sstever@eecs.umich.edu        # Unproxy ports in sorted order so that 'append' operations on
7043107Sstever@eecs.umich.edu        # vector ports are done in a deterministic fashion.
7053107Sstever@eecs.umich.edu        port_names = self._ports.keys()
7063107Sstever@eecs.umich.edu        port_names.sort()
7073107Sstever@eecs.umich.edu        for port_name in port_names:
7083105Sstever@eecs.umich.edu            port = self._port_refs.get(port_name)
7093105Sstever@eecs.umich.edu            if port != None:
7103105Sstever@eecs.umich.edu                port.unproxy(self)
7113105Sstever@eecs.umich.edu
7125037Smilesck@eecs.umich.edu    def print_ini(self, ini_file):
7135543Ssaidi@eecs.umich.edu        print >>ini_file, '[' + self.path() + ']'       # .ini section header
7141692SN/A
7152738SN/A        instanceDict[self.path()] = self
7162738SN/A
7174081Sbinkertn@umich.edu        if hasattr(self, 'type'):
7185037Smilesck@eecs.umich.edu            print >>ini_file, 'type=%s' % self.type
7191692SN/A
7201692SN/A        child_names = self._children.keys()
7211692SN/A        child_names.sort()
7224081Sbinkertn@umich.edu        if len(child_names):
7237528Ssteve.reinhardt@amd.com            print >>ini_file, 'children=%s' % \
7247528Ssteve.reinhardt@amd.com                  ' '.join(self._children[n].get_name() for n in child_names)
7251692SN/A
7261692SN/A        param_names = self._params.keys()
7271692SN/A        param_names.sort()
7281692SN/A        for param in param_names:
7293105Sstever@eecs.umich.edu            value = self._values.get(param)
7301692SN/A            if value != None:
7315037Smilesck@eecs.umich.edu                print >>ini_file, '%s=%s' % (param,
7325037Smilesck@eecs.umich.edu                                             self._values[param].ini_str())
7331692SN/A
7343103Sstever@eecs.umich.edu        port_names = self._ports.keys()
7353103Sstever@eecs.umich.edu        port_names.sort()
7363103Sstever@eecs.umich.edu        for port_name in port_names:
7373105Sstever@eecs.umich.edu            port = self._port_refs.get(port_name, None)
7383105Sstever@eecs.umich.edu            if port != None:
7395037Smilesck@eecs.umich.edu                print >>ini_file, '%s=%s' % (port_name, port.ini_str())
7403103Sstever@eecs.umich.edu
7415543Ssaidi@eecs.umich.edu        print >>ini_file        # blank line between objects
7421692SN/A
7434762Snate@binkert.org    def getCCParams(self):
7444762Snate@binkert.org        if self._ccParams:
7454762Snate@binkert.org            return self._ccParams
7464762Snate@binkert.org
7475033Smilesck@eecs.umich.edu        cc_params_struct = getattr(m5.objects.params, '%sParams' % self.type)
7484762Snate@binkert.org        cc_params = cc_params_struct()
7495488Snate@binkert.org        cc_params.pyobj = self
7504762Snate@binkert.org        cc_params.name = str(self)
7514762Snate@binkert.org
7524762Snate@binkert.org        param_names = self._params.keys()
7534762Snate@binkert.org        param_names.sort()
7544762Snate@binkert.org        for param in param_names:
7554762Snate@binkert.org            value = self._values.get(param)
7564762Snate@binkert.org            if value is None:
7576654Snate@binkert.org                fatal("%s.%s without default or user set value",
7586654Snate@binkert.org                      self.path(), param)
7594762Snate@binkert.org
7604762Snate@binkert.org            value = value.getValue()
7614762Snate@binkert.org            if isinstance(self._params[param], VectorParamDesc):
7624762Snate@binkert.org                assert isinstance(value, list)
7634762Snate@binkert.org                vec = getattr(cc_params, param)
7644762Snate@binkert.org                assert not len(vec)
7654762Snate@binkert.org                for v in value:
7664762Snate@binkert.org                    vec.append(v)
7674762Snate@binkert.org            else:
7684762Snate@binkert.org                setattr(cc_params, param, value)
7694762Snate@binkert.org
7704762Snate@binkert.org        port_names = self._ports.keys()
7714762Snate@binkert.org        port_names.sort()
7724762Snate@binkert.org        for port_name in port_names:
7734762Snate@binkert.org            port = self._port_refs.get(port_name, None)
7744762Snate@binkert.org            if port != None:
7754762Snate@binkert.org                setattr(cc_params, port_name, port)
7764762Snate@binkert.org        self._ccParams = cc_params
7774762Snate@binkert.org        return self._ccParams
7782738SN/A
7792740SN/A    # Get C++ object corresponding to this object, calling C++ if
7802740SN/A    # necessary to construct it.  Does *not* recursively create
7812740SN/A    # children.
7822740SN/A    def getCCObject(self):
7832740SN/A        if not self._ccObject:
7847526Ssteve.reinhardt@amd.com            # Make sure this object is in the configuration hierarchy
7857526Ssteve.reinhardt@amd.com            if not self._parent and not isRoot(self):
7867526Ssteve.reinhardt@amd.com                raise RuntimeError, "Attempt to instantiate orphan node"
7877526Ssteve.reinhardt@amd.com            # Cycles in the configuration hierarchy are not supported. This
7885244Sgblack@eecs.umich.edu            # will catch the resulting recursion and stop.
7895244Sgblack@eecs.umich.edu            self._ccObject = -1
7905244Sgblack@eecs.umich.edu            params = self.getCCParams()
7914762Snate@binkert.org            self._ccObject = params.create()
7922740SN/A        elif self._ccObject == -1:
7937526Ssteve.reinhardt@amd.com            raise RuntimeError, "%s: Cycle found in configuration hierarchy." \
7942740SN/A                  % self.path()
7952740SN/A        return self._ccObject
7962740SN/A
7977527Ssteve.reinhardt@amd.com    def descendants(self):
7987527Ssteve.reinhardt@amd.com        yield self
7997527Ssteve.reinhardt@amd.com        for child in self._children.itervalues():
8007527Ssteve.reinhardt@amd.com            for obj in child.descendants():
8017527Ssteve.reinhardt@amd.com                yield obj
8027527Ssteve.reinhardt@amd.com
8037527Ssteve.reinhardt@amd.com    # Call C++ to create C++ object corresponding to this object
8044762Snate@binkert.org    def createCCObject(self):
8054762Snate@binkert.org        self.getCCParams()
8064762Snate@binkert.org        self.getCCObject() # force creation
8074762Snate@binkert.org
8084762Snate@binkert.org    def getValue(self):
8094762Snate@binkert.org        return self.getCCObject()
8104762Snate@binkert.org
8112738SN/A    # Create C++ port connections corresponding to the connections in
8127527Ssteve.reinhardt@amd.com    # _port_refs
8132738SN/A    def connectPorts(self):
8143105Sstever@eecs.umich.edu        for portRef in self._port_refs.itervalues():
8153105Sstever@eecs.umich.edu            portRef.ccConnect()
8162797SN/A
8174553Sbinkertn@umich.edu    def getMemoryMode(self):
8184553Sbinkertn@umich.edu        if not isinstance(self, m5.objects.System):
8194553Sbinkertn@umich.edu            return None
8204553Sbinkertn@umich.edu
8214859Snate@binkert.org        return self._ccObject.getMemoryMode()
8224553Sbinkertn@umich.edu
8232797SN/A    def changeTiming(self, mode):
8243202Shsul@eecs.umich.edu        if isinstance(self, m5.objects.System):
8253202Shsul@eecs.umich.edu            # i don't know if there's a better way to do this - calling
8263202Shsul@eecs.umich.edu            # setMemoryMode directly from self._ccObject results in calling
8273202Shsul@eecs.umich.edu            # SimObject::setMemoryMode, not the System::setMemoryMode
8284859Snate@binkert.org            self._ccObject.setMemoryMode(mode)
8292797SN/A
8302797SN/A    def takeOverFrom(self, old_cpu):
8314859Snate@binkert.org        self._ccObject.takeOverFrom(old_cpu._ccObject)
8322797SN/A
8331692SN/A    # generate output file for 'dot' to display as a pretty graph.
8341692SN/A    # this code is currently broken.
8351342SN/A    def outputDot(self, dot):
8361342SN/A        label = "{%s|" % self.path
8371342SN/A        if isSimObject(self.realtype):
8381342SN/A            label +=  '%s|' % self.type
8391342SN/A
8401342SN/A        if self.children:
8411342SN/A            # instantiate children in same order they were added for
8421342SN/A            # backward compatibility (else we can end up with cpu1
8431342SN/A            # before cpu0).
8441342SN/A            for c in self.children:
8451342SN/A                dot.add_edge(pydot.Edge(self.path,c.path, style="bold"))
8461342SN/A
8471342SN/A        simobjs = []
8481342SN/A        for param in self.params:
8491342SN/A            try:
8501342SN/A                if param.value is None:
8511342SN/A                    raise AttributeError, 'Parameter with no value'
8521342SN/A
8531692SN/A                value = param.value
8541342SN/A                string = param.string(value)
8551587SN/A            except Exception, e:
8561605SN/A                msg = 'exception in %s:%s\n%s' % (self.name, param.name, e)
8571605SN/A                e.args = (msg, )
8581342SN/A                raise
8591605SN/A
8601692SN/A            if isSimObject(param.ptype) and string != "Null":
8611342SN/A                simobjs.append(string)
8621342SN/A            else:
8631342SN/A                label += '%s = %s\\n' % (param.name, string)
8641342SN/A
8651342SN/A        for so in simobjs:
8661342SN/A            label += "|<%s> %s" % (so, so)
8671587SN/A            dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so,
8681587SN/A                                    tailport="w"))
8691342SN/A        label += '}'
8701342SN/A        dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label))
8711342SN/A
8721342SN/A        # recursively dump out children
8731342SN/A        for c in self.children:
8741342SN/A            c.outputDot(dot)
8751342SN/A
8763101Sstever@eecs.umich.edu# Function to provide to C++ so it can look up instances based on paths
8773101Sstever@eecs.umich.edudef resolveSimObject(name):
8783101Sstever@eecs.umich.edu    obj = instanceDict[name]
8793101Sstever@eecs.umich.edu    return obj.getCCObject()
880679SN/A
8816654Snate@binkert.orgdef isSimObject(value):
8826654Snate@binkert.org    return isinstance(value, SimObject)
8836654Snate@binkert.org
8846654Snate@binkert.orgdef isSimObjectClass(value):
8856654Snate@binkert.org    return issubclass(value, SimObject)
8866654Snate@binkert.org
8877528Ssteve.reinhardt@amd.comdef isSimObjectVector(value):
8887528Ssteve.reinhardt@amd.com    return isinstance(value, SimObjectVector)
8897528Ssteve.reinhardt@amd.com
8906654Snate@binkert.orgdef isSimObjectSequence(value):
8916654Snate@binkert.org    if not isinstance(value, (list, tuple)) or len(value) == 0:
8926654Snate@binkert.org        return False
8936654Snate@binkert.org
8946654Snate@binkert.org    for val in value:
8956654Snate@binkert.org        if not isNullPointer(val) and not isSimObject(val):
8966654Snate@binkert.org            return False
8976654Snate@binkert.org
8986654Snate@binkert.org    return True
8996654Snate@binkert.org
9006654Snate@binkert.orgdef isSimObjectOrSequence(value):
9016654Snate@binkert.org    return isSimObject(value) or isSimObjectSequence(value)
9026654Snate@binkert.org
9037526Ssteve.reinhardt@amd.comdef isRoot(obj):
9047526Ssteve.reinhardt@amd.com    from m5.objects import Root
9057526Ssteve.reinhardt@amd.com    return obj and obj is Root.getInstance()
9067526Ssteve.reinhardt@amd.com
9077528Ssteve.reinhardt@amd.comdef isSimObjectOrVector(value):
9087528Ssteve.reinhardt@amd.com    return isSimObject(value) or isSimObjectVector(value)
9097528Ssteve.reinhardt@amd.com
9107528Ssteve.reinhardt@amd.comdef tryAsSimObjectOrVector(value):
9117528Ssteve.reinhardt@amd.com    if isSimObjectOrVector(value):
9127528Ssteve.reinhardt@amd.com        return value
9137528Ssteve.reinhardt@amd.com    if isSimObjectSequence(value):
9147528Ssteve.reinhardt@amd.com        return SimObjectVector(value)
9157528Ssteve.reinhardt@amd.com    return None
9167528Ssteve.reinhardt@amd.com
9177528Ssteve.reinhardt@amd.comdef coerceSimObjectOrVector(value):
9187528Ssteve.reinhardt@amd.com    value = tryAsSimObjectOrVector(value)
9197528Ssteve.reinhardt@amd.com    if value is None:
9207528Ssteve.reinhardt@amd.com        raise TypeError, "SimObject or SimObjectVector expected"
9217528Ssteve.reinhardt@amd.com    return value
9227528Ssteve.reinhardt@amd.com
9236654Snate@binkert.orgbaseClasses = allClasses.copy()
9246654Snate@binkert.orgbaseInstances = instanceDict.copy()
9256654Snate@binkert.org
9266654Snate@binkert.orgdef clear():
9276654Snate@binkert.org    global allClasses, instanceDict
9286654Snate@binkert.org
9296654Snate@binkert.org    allClasses = baseClasses.copy()
9306654Snate@binkert.org    instanceDict = baseInstances.copy()
9316654Snate@binkert.org
9321528SN/A# __all__ defines the list of symbols that get exported when
9331528SN/A# 'from config import *' is invoked.  Try to keep this reasonably
9341528SN/A# short to avoid polluting other namespaces.
9354762Snate@binkert.org__all__ = [ 'SimObject' ]
936