SimObject.py revision 3107
12740SN/A# Copyright (c) 2004-2006 The Regents of The University of Michigan
21046SN/A# All rights reserved.
31046SN/A#
41046SN/A# Redistribution and use in source and binary forms, with or without
51046SN/A# modification, are permitted provided that the following conditions are
61046SN/A# met: redistributions of source code must retain the above copyright
71046SN/A# notice, this list of conditions and the following disclaimer;
81046SN/A# redistributions in binary form must reproduce the above copyright
91046SN/A# notice, this list of conditions and the following disclaimer in the
101046SN/A# documentation and/or other materials provided with the distribution;
111046SN/A# neither the name of the copyright holders nor the names of its
121046SN/A# contributors may be used to endorse or promote products derived from
131046SN/A# this software without specific prior written permission.
141046SN/A#
151046SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
161046SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
171046SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
181046SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
191046SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
201046SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
211046SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
221046SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
231046SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
241046SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
251046SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
262665SN/A#
272665SN/A# Authors: Steve Reinhardt
282665SN/A#          Nathan Binkert
291046SN/A
303101Sstever@eecs.umich.eduimport sys, types
311438SN/A
323102Sstever@eecs.umich.edufrom util import *
331585SN/Afrom multidict import multidict
341438SN/A
353102Sstever@eecs.umich.edu# These utility functions have to come first because they're
363102Sstever@eecs.umich.edu# referenced in params.py... otherwise they won't be defined when we
373102Sstever@eecs.umich.edu# import params below, and the recursive import of this file from
383102Sstever@eecs.umich.edu# params.py will not find these names.
393102Sstever@eecs.umich.edudef isSimObject(value):
403102Sstever@eecs.umich.edu    return isinstance(value, SimObject)
413102Sstever@eecs.umich.edu
423102Sstever@eecs.umich.edudef isSimObjectClass(value):
433102Sstever@eecs.umich.edu    return issubclass(value, SimObject)
443102Sstever@eecs.umich.edu
453102Sstever@eecs.umich.edudef isSimObjectSequence(value):
463102Sstever@eecs.umich.edu    if not isinstance(value, (list, tuple)) or len(value) == 0:
473102Sstever@eecs.umich.edu        return False
483102Sstever@eecs.umich.edu
493102Sstever@eecs.umich.edu    for val in value:
503102Sstever@eecs.umich.edu        if not isNullPointer(val) and not isSimObject(val):
513102Sstever@eecs.umich.edu            return False
523102Sstever@eecs.umich.edu
533102Sstever@eecs.umich.edu    return True
543102Sstever@eecs.umich.edu
553102Sstever@eecs.umich.edudef isSimObjectOrSequence(value):
563102Sstever@eecs.umich.edu    return isSimObject(value) or isSimObjectSequence(value)
573102Sstever@eecs.umich.edu
583102Sstever@eecs.umich.edu# Have to import params up top since Param is referenced on initial
593102Sstever@eecs.umich.edu# load (when SimObject class references Param to create a class
603102Sstever@eecs.umich.edu# variable, the 'name' param)...
613102Sstever@eecs.umich.edufrom params import *
623102Sstever@eecs.umich.edu# There are a few things we need that aren't in params.__all__ since
633102Sstever@eecs.umich.edu# normal users don't need them
643102Sstever@eecs.umich.edufrom params import ParamDesc, isNullPointer, SimObjVector
653102Sstever@eecs.umich.edu
661342SN/AnoDot = False
671342SN/Atry:
681378SN/A    import pydot
691342SN/Aexcept:
701378SN/A    noDot = True
71679SN/A
72679SN/A#####################################################################
73679SN/A#
74679SN/A# M5 Python Configuration Utility
75679SN/A#
76679SN/A# The basic idea is to write simple Python programs that build Python
771692SN/A# objects corresponding to M5 SimObjects for the desired simulation
78679SN/A# configuration.  For now, the Python emits a .ini file that can be
79679SN/A# parsed by M5.  In the future, some tighter integration between M5
80679SN/A# and the Python interpreter may allow bypassing the .ini file.
81679SN/A#
82679SN/A# Each SimObject class in M5 is represented by a Python class with the
83679SN/A# same name.  The Python inheritance tree mirrors the M5 C++ tree
84679SN/A# (e.g., SimpleCPU derives from BaseCPU in both cases, and all
85679SN/A# SimObjects inherit from a single SimObject base class).  To specify
86679SN/A# an instance of an M5 SimObject in a configuration, the user simply
87679SN/A# instantiates the corresponding Python object.  The parameters for
88679SN/A# that SimObject are given by assigning to attributes of the Python
89679SN/A# object, either using keyword assignment in the constructor or in
90679SN/A# separate assignment statements.  For example:
91679SN/A#
921692SN/A# cache = BaseCache(size='64KB')
93679SN/A# cache.hit_latency = 3
94679SN/A# cache.assoc = 8
95679SN/A#
96679SN/A# The magic lies in the mapping of the Python attributes for SimObject
97679SN/A# classes to the actual SimObject parameter specifications.  This
98679SN/A# allows parameter validity checking in the Python code.  Continuing
99679SN/A# the example above, the statements "cache.blurfl=3" or
100679SN/A# "cache.assoc='hello'" would both result in runtime errors in Python,
101679SN/A# since the BaseCache object has no 'blurfl' parameter and the 'assoc'
102679SN/A# parameter requires an integer, respectively.  This magic is done
103679SN/A# primarily by overriding the special __setattr__ method that controls
104679SN/A# assignment to object attributes.
105679SN/A#
106679SN/A# Once a set of Python objects have been instantiated in a hierarchy,
107679SN/A# calling 'instantiate(obj)' (where obj is the root of the hierarchy)
1082740SN/A# will generate a .ini file.
109679SN/A#
110679SN/A#####################################################################
111679SN/A
1122738SN/A# dict to look up SimObjects based on path
1132738SN/AinstanceDict = {}
1142738SN/A
1152740SN/A# The metaclass for SimObject.  This class controls how new classes
1162740SN/A# that derive from SimObject are instantiated, and provides inherited
1172740SN/A# class behavior (just like a class controls how instances of that
1182740SN/A# class are instantiated, and provides inherited instance behavior).
1191692SN/Aclass MetaSimObject(type):
1201427SN/A    # Attributes that can be set only at initialization time
1211692SN/A    init_keywords = { 'abstract' : types.BooleanType,
1221692SN/A                      'type' : types.StringType }
1231427SN/A    # Attributes that can be set any time
1243100SN/A    keywords = { 'check' : types.FunctionType,
1253100SN/A                 'cxx_type' : types.StringType,
1263100SN/A                 'cxx_predecls' : types.ListType,
1273100SN/A                 'swig_predecls' : types.ListType }
128679SN/A
129679SN/A    # __new__ is called before __init__, and is where the statements
130679SN/A    # in the body of the class definition get loaded into the class's
1312740SN/A    # __dict__.  We intercept this to filter out parameter & port assignments
132679SN/A    # and only allow "private" attributes to be passed to the base
133679SN/A    # __new__ (starting with underscore).
1341310SN/A    def __new__(mcls, name, bases, dict):
1352740SN/A        # Copy "private" attributes, functions, and classes to the
1362740SN/A        # official dict.  Everything else goes in _init_dict to be
1372740SN/A        # filtered in __init__.
1382740SN/A        cls_dict = {}
1392740SN/A        value_dict = {}
1402740SN/A        for key,val in dict.items():
1412740SN/A            if key.startswith('_') or isinstance(val, (types.FunctionType,
1422740SN/A                                                       types.TypeType)):
1432740SN/A                cls_dict[key] = val
1442740SN/A            else:
1452740SN/A                # must be a param/port setting
1462740SN/A                value_dict[key] = val
1472740SN/A        cls_dict['_value_dict'] = value_dict
1481692SN/A        return super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict)
149679SN/A
1502711SN/A    # subclass initialization
151679SN/A    def __init__(cls, name, bases, dict):
1522711SN/A        # calls type.__init__()... I think that's a no-op, but leave
1532711SN/A        # it here just in case it's not.
1541692SN/A        super(MetaSimObject, cls).__init__(name, bases, dict)
1551310SN/A
1561427SN/A        # initialize required attributes
1572740SN/A
1582740SN/A        # class-only attributes
1592740SN/A        cls._params = multidict() # param descriptions
1602740SN/A        cls._ports = multidict()  # port descriptions
1612740SN/A
1622740SN/A        # class or instance attributes
1632740SN/A        cls._values = multidict()   # param values
1643105Sstever@eecs.umich.edu        cls._port_refs = multidict() # port ref objects
1652740SN/A        cls._instantiated = False # really instantiated, cloned, or subclassed
1661310SN/A
1671692SN/A        # We don't support multiple inheritance.  If you want to, you
1681585SN/A        # must fix multidict to deal with it properly.
1691692SN/A        if len(bases) > 1:
1701692SN/A            raise TypeError, "SimObjects do not support multiple inheritance"
1711692SN/A
1721692SN/A        base = bases[0]
1731692SN/A
1742740SN/A        # Set up general inheritance via multidicts.  A subclass will
1752740SN/A        # inherit all its settings from the base class.  The only time
1762740SN/A        # the following is not true is when we define the SimObject
1772740SN/A        # class itself (in which case the multidicts have no parent).
1781692SN/A        if isinstance(base, MetaSimObject):
1791692SN/A            cls._params.parent = base._params
1802740SN/A            cls._ports.parent = base._ports
1811692SN/A            cls._values.parent = base._values
1823105Sstever@eecs.umich.edu            cls._port_refs.parent = base._port_refs
1832740SN/A            # mark base as having been subclassed
1842712SN/A            base._instantiated = True
1851692SN/A
1862740SN/A        # Now process the _value_dict items.  They could be defining
1872740SN/A        # new (or overriding existing) parameters or ports, setting
1882740SN/A        # class keywords (e.g., 'abstract'), or setting parameter
1892740SN/A        # values or port bindings.  The first 3 can only be set when
1902740SN/A        # the class is defined, so we handle them here.  The others
1912740SN/A        # can be set later too, so just emulate that by calling
1922740SN/A        # setattr().
1932740SN/A        for key,val in cls._value_dict.items():
1941527SN/A            # param descriptions
1952740SN/A            if isinstance(val, ParamDesc):
1961585SN/A                cls._new_param(key, val)
1971427SN/A
1982738SN/A            # port objects
1992738SN/A            elif isinstance(val, Port):
2003105Sstever@eecs.umich.edu                cls._new_port(key, val)
2012738SN/A
2021427SN/A            # init-time-only keywords
2031427SN/A            elif cls.init_keywords.has_key(key):
2041427SN/A                cls._set_keyword(key, val, cls.init_keywords[key])
2051427SN/A
2061427SN/A            # default: use normal path (ends up in __setattr__)
2071427SN/A            else:
2081427SN/A                setattr(cls, key, val)
2091427SN/A
2103100SN/A        cls.cxx_type = cls.type + '*'
2113100SN/A        # A forward class declaration is sufficient since we are just
2123100SN/A        # declaring a pointer.
2133100SN/A        cls.cxx_predecls = ['class %s;' % cls.type]
2143100SN/A        cls.swig_predecls = cls.cxx_predecls
2153100SN/A
2161427SN/A    def _set_keyword(cls, keyword, val, kwtype):
2171427SN/A        if not isinstance(val, kwtype):
2181427SN/A            raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
2191427SN/A                  (keyword, type(val), kwtype)
2201427SN/A        if isinstance(val, types.FunctionType):
2211427SN/A            val = classmethod(val)
2221427SN/A        type.__setattr__(cls, keyword, val)
2231427SN/A
2243100SN/A    def _new_param(cls, name, pdesc):
2253100SN/A        # each param desc should be uniquely assigned to one variable
2263100SN/A        assert(not hasattr(pdesc, 'name'))
2273100SN/A        pdesc.name = name
2283100SN/A        cls._params[name] = pdesc
2293100SN/A        if hasattr(pdesc, 'default'):
2303105Sstever@eecs.umich.edu            cls._set_param(name, pdesc.default, pdesc)
2313105Sstever@eecs.umich.edu
2323105Sstever@eecs.umich.edu    def _set_param(cls, name, value, param):
2333105Sstever@eecs.umich.edu        assert(param.name == name)
2343105Sstever@eecs.umich.edu        try:
2353105Sstever@eecs.umich.edu            cls._values[name] = param.convert(value)
2363105Sstever@eecs.umich.edu        except Exception, e:
2373105Sstever@eecs.umich.edu            msg = "%s\nError setting param %s.%s to %s\n" % \
2383105Sstever@eecs.umich.edu                  (e, cls.__name__, name, value)
2393105Sstever@eecs.umich.edu            e.args = (msg, )
2403105Sstever@eecs.umich.edu            raise
2413105Sstever@eecs.umich.edu
2423105Sstever@eecs.umich.edu    def _new_port(cls, name, port):
2433105Sstever@eecs.umich.edu        # each port should be uniquely assigned to one variable
2443105Sstever@eecs.umich.edu        assert(not hasattr(port, 'name'))
2453105Sstever@eecs.umich.edu        port.name = name
2463105Sstever@eecs.umich.edu        cls._ports[name] = port
2473105Sstever@eecs.umich.edu        if hasattr(port, 'default'):
2483105Sstever@eecs.umich.edu            cls._cls_get_port_ref(name).connect(port.default)
2493105Sstever@eecs.umich.edu
2503105Sstever@eecs.umich.edu    # same as _get_port_ref, effectively, but for classes
2513105Sstever@eecs.umich.edu    def _cls_get_port_ref(cls, attr):
2523105Sstever@eecs.umich.edu        # Return reference that can be assigned to another port
2533105Sstever@eecs.umich.edu        # via __setattr__.  There is only ever one reference
2543105Sstever@eecs.umich.edu        # object per port, but we create them lazily here.
2553105Sstever@eecs.umich.edu        ref = cls._port_refs.get(attr)
2563105Sstever@eecs.umich.edu        if not ref:
2573105Sstever@eecs.umich.edu            ref = cls._ports[attr].makeRef(cls)
2583105Sstever@eecs.umich.edu            cls._port_refs[attr] = ref
2593105Sstever@eecs.umich.edu        return ref
2601585SN/A
2611310SN/A    # Set attribute (called on foo.attr = value when foo is an
2621310SN/A    # instance of class cls).
2631310SN/A    def __setattr__(cls, attr, value):
2641310SN/A        # normal processing for private attributes
2651310SN/A        if attr.startswith('_'):
2661310SN/A            type.__setattr__(cls, attr, value)
2671310SN/A            return
2681310SN/A
2691310SN/A        if cls.keywords.has_key(attr):
2701427SN/A            cls._set_keyword(attr, value, cls.keywords[attr])
2711310SN/A            return
2721310SN/A
2732738SN/A        if cls._ports.has_key(attr):
2743105Sstever@eecs.umich.edu            cls._cls_get_port_ref(attr).connect(value)
2752738SN/A            return
2762738SN/A
2772740SN/A        if isSimObjectOrSequence(value) and cls._instantiated:
2782740SN/A            raise RuntimeError, \
2792740SN/A                  "cannot set SimObject parameter '%s' after\n" \
2802740SN/A                  "    class %s has been instantiated or subclassed" \
2812740SN/A                  % (attr, cls.__name__)
2822740SN/A
2832740SN/A        # check for param
2843105Sstever@eecs.umich.edu        param = cls._params.get(attr)
2851310SN/A        if param:
2863105Sstever@eecs.umich.edu            cls._set_param(attr, value, param)
2873105Sstever@eecs.umich.edu            return
2883105Sstever@eecs.umich.edu
2893105Sstever@eecs.umich.edu        if isSimObjectOrSequence(value):
2903105Sstever@eecs.umich.edu            # If RHS is a SimObject, it's an implicit child assignment.
2913105Sstever@eecs.umich.edu            # Classes don't have children, so we just put this object
2923105Sstever@eecs.umich.edu            # in _values; later, each instance will do a 'setattr(self,
2933105Sstever@eecs.umich.edu            # attr, _values[attr])' in SimObject.__init__ which will
2943105Sstever@eecs.umich.edu            # add this object as a child.
2952740SN/A            cls._values[attr] = value
2963105Sstever@eecs.umich.edu            return
2973105Sstever@eecs.umich.edu
2983105Sstever@eecs.umich.edu        # no valid assignment... raise exception
2993105Sstever@eecs.umich.edu        raise AttributeError, \
3003105Sstever@eecs.umich.edu              "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
3011310SN/A
3021585SN/A    def __getattr__(cls, attr):
3031692SN/A        if cls._values.has_key(attr):
3041692SN/A            return cls._values[attr]
3051585SN/A
3061585SN/A        raise AttributeError, \
3071585SN/A              "object '%s' has no attribute '%s'" % (cls.__name__, attr)
3081585SN/A
3093100SN/A    def __str__(cls):
3103100SN/A        return cls.__name__
3113100SN/A
3123100SN/A    def cxx_decl(cls):
3133100SN/A        code = "#ifndef __PARAMS__%s\n#define __PARAMS__%s\n\n" % (cls, cls)
3143100SN/A
3153100SN/A        if str(cls) != 'SimObject':
3163100SN/A            base = cls.__bases__[0].type
3173100SN/A        else:
3183100SN/A            base = None
3193100SN/A
3203100SN/A        # The 'dict' attribute restricts us to the params declared in
3213100SN/A        # the object itself, not including inherited params (which
3223100SN/A        # will also be inherited from the base class's param struct
3233100SN/A        # here).
3243100SN/A        params = cls._params.dict.values()
3253100SN/A        try:
3263100SN/A            ptypes = [p.ptype for p in params]
3273100SN/A        except:
3283100SN/A            print cls, p, p.ptype_str
3293100SN/A            print params
3303100SN/A            raise
3313100SN/A
3323100SN/A        # get a list of lists of predeclaration lines
3333100SN/A        predecls = [p.cxx_predecls() for p in params]
3343100SN/A        # flatten
3353100SN/A        predecls = reduce(lambda x,y:x+y, predecls, [])
3363100SN/A        # remove redundant lines
3373100SN/A        predecls2 = []
3383100SN/A        for pd in predecls:
3393100SN/A            if pd not in predecls2:
3403100SN/A                predecls2.append(pd)
3413100SN/A        predecls2.sort()
3423100SN/A        code += "\n".join(predecls2)
3433100SN/A        code += "\n\n";
3443100SN/A
3453100SN/A        if base:
3463100SN/A            code += '#include "params/%s.hh"\n\n' % base
3473100SN/A
3483100SN/A        # Generate declarations for locally defined enumerations.
3493100SN/A        enum_ptypes = [t for t in ptypes if issubclass(t, Enum)]
3503100SN/A        if enum_ptypes:
3513100SN/A            code += "\n".join([t.cxx_decl() for t in enum_ptypes])
3523100SN/A            code += "\n\n"
3533100SN/A
3543100SN/A        # now generate the actual param struct
3553100SN/A        code += "struct %sParams" % cls
3563100SN/A        if base:
3573100SN/A            code += " : public %sParams" % base
3583100SN/A        code += " {\n"
3593100SN/A        decls = [p.cxx_decl() for p in params]
3603100SN/A        decls.sort()
3613100SN/A        code += "".join(["    %s\n" % d for d in decls])
3623100SN/A        code += "};\n"
3633100SN/A
3643100SN/A        # close #ifndef __PARAMS__* guard
3653100SN/A        code += "\n#endif\n"
3663100SN/A        return code
3673100SN/A
3683100SN/A    def swig_decl(cls):
3693100SN/A
3703100SN/A        code = '%%module %sParams\n' % cls
3713100SN/A
3723100SN/A        if str(cls) != 'SimObject':
3733100SN/A            base = cls.__bases__[0].type
3743100SN/A        else:
3753100SN/A            base = None
3763100SN/A
3773100SN/A        # The 'dict' attribute restricts us to the params declared in
3783100SN/A        # the object itself, not including inherited params (which
3793100SN/A        # will also be inherited from the base class's param struct
3803100SN/A        # here).
3813100SN/A        params = cls._params.dict.values()
3823100SN/A        ptypes = [p.ptype for p in params]
3833100SN/A
3843100SN/A        # get a list of lists of predeclaration lines
3853100SN/A        predecls = [p.swig_predecls() for p in params]
3863100SN/A        # flatten
3873100SN/A        predecls = reduce(lambda x,y:x+y, predecls, [])
3883100SN/A        # remove redundant lines
3893100SN/A        predecls2 = []
3903100SN/A        for pd in predecls:
3913100SN/A            if pd not in predecls2:
3923100SN/A                predecls2.append(pd)
3933100SN/A        predecls2.sort()
3943100SN/A        code += "\n".join(predecls2)
3953100SN/A        code += "\n\n";
3963100SN/A
3973100SN/A        if base:
3983100SN/A            code += '%%import "python/m5/swig/%sParams.i"\n\n' % base
3993100SN/A
4003100SN/A        code += '%{\n'
4013100SN/A        code += '#include "params/%s.hh"\n' % cls
4023100SN/A        code += '%}\n\n'
4033100SN/A        code += '%%include "params/%s.hh"\n\n' % cls
4043100SN/A
4053100SN/A        return code
4063100SN/A
4072740SN/A# The SimObject class is the root of the special hierarchy.  Most of
408679SN/A# the code in this class deals with the configuration hierarchy itself
409679SN/A# (parent/child node relationships).
4101692SN/Aclass SimObject(object):
4111692SN/A    # Specify metaclass.  Any class inheriting from SimObject will
412679SN/A    # get this metaclass.
4131692SN/A    __metaclass__ = MetaSimObject
4143100SN/A    type = 'SimObject'
4153100SN/A
4163100SN/A    name = Param.String("Object name")
417679SN/A
4182740SN/A    # Initialize new instance.  For objects with SimObject-valued
4192740SN/A    # children, we need to recursively clone the classes represented
4202740SN/A    # by those param values as well in a consistent "deep copy"-style
4212740SN/A    # fashion.  That is, we want to make sure that each instance is
4222740SN/A    # cloned only once, and that if there are multiple references to
4232740SN/A    # the same original object, we end up with the corresponding
4242740SN/A    # cloned references all pointing to the same cloned instance.
4252740SN/A    def __init__(self, **kwargs):
4262740SN/A        ancestor = kwargs.get('_ancestor')
4272740SN/A        memo_dict = kwargs.get('_memo')
4282740SN/A        if memo_dict is None:
4292740SN/A            # prepare to memoize any recursively instantiated objects
4302740SN/A            memo_dict = {}
4312740SN/A        elif ancestor:
4322740SN/A            # memoize me now to avoid problems with recursive calls
4332740SN/A            memo_dict[ancestor] = self
4342711SN/A
4352740SN/A        if not ancestor:
4362740SN/A            ancestor = self.__class__
4372740SN/A        ancestor._instantiated = True
4382711SN/A
4392740SN/A        # initialize required attributes
4402740SN/A        self._parent = None
4412740SN/A        self._children = {}
4422740SN/A        self._ccObject = None  # pointer to C++ object
4432740SN/A        self._instantiated = False # really "cloned"
4442712SN/A
4452711SN/A        # Inherit parameter values from class using multidict so
4462711SN/A        # individual value settings can be overridden.
4472740SN/A        self._values = multidict(ancestor._values)
4482740SN/A        # clone SimObject-valued parameters
4492740SN/A        for key,val in ancestor._values.iteritems():
4502740SN/A            if isSimObject(val):
4512740SN/A                setattr(self, key, val(_memo=memo_dict))
4522740SN/A            elif isSimObjectSequence(val) and len(val):
4532740SN/A                setattr(self, key, [ v(_memo=memo_dict) for v in val ])
4542740SN/A        # clone port references.  no need to use a multidict here
4552740SN/A        # since we will be creating new references for all ports.
4563105Sstever@eecs.umich.edu        self._port_refs = {}
4573105Sstever@eecs.umich.edu        for key,val in ancestor._port_refs.iteritems():
4583105Sstever@eecs.umich.edu            self._port_refs[key] = val.clone(self, memo_dict)
4591692SN/A        # apply attribute assignments from keyword args, if any
4601692SN/A        for key,val in kwargs.iteritems():
4611692SN/A            setattr(self, key, val)
462679SN/A
4632740SN/A    # "Clone" the current instance by creating another instance of
4642740SN/A    # this instance's class, but that inherits its parameter values
4652740SN/A    # and port mappings from the current instance.  If we're in a
4662740SN/A    # "deep copy" recursive clone, check the _memo dict to see if
4672740SN/A    # we've already cloned this instance.
4681692SN/A    def __call__(self, **kwargs):
4692740SN/A        memo_dict = kwargs.get('_memo')
4702740SN/A        if memo_dict is None:
4712740SN/A            # no memo_dict: must be top-level clone operation.
4722740SN/A            # this is only allowed at the root of a hierarchy
4732740SN/A            if self._parent:
4742740SN/A                raise RuntimeError, "attempt to clone object %s " \
4752740SN/A                      "not at the root of a tree (parent = %s)" \
4762740SN/A                      % (self, self._parent)
4772740SN/A            # create a new dict and use that.
4782740SN/A            memo_dict = {}
4792740SN/A            kwargs['_memo'] = memo_dict
4802740SN/A        elif memo_dict.has_key(self):
4812740SN/A            # clone already done & memoized
4822740SN/A            return memo_dict[self]
4832740SN/A        return self.__class__(_ancestor = self, **kwargs)
4841343SN/A
4853105Sstever@eecs.umich.edu    def _get_port_ref(self, attr):
4863105Sstever@eecs.umich.edu        # Return reference that can be assigned to another port
4873105Sstever@eecs.umich.edu        # via __setattr__.  There is only ever one reference
4883105Sstever@eecs.umich.edu        # object per port, but we create them lazily here.
4893105Sstever@eecs.umich.edu        ref = self._port_refs.get(attr)
4903105Sstever@eecs.umich.edu        if not ref:
4913105Sstever@eecs.umich.edu            ref = self._ports[attr].makeRef(self)
4923105Sstever@eecs.umich.edu            self._port_refs[attr] = ref
4933105Sstever@eecs.umich.edu        return ref
4943105Sstever@eecs.umich.edu
4951692SN/A    def __getattr__(self, attr):
4962738SN/A        if self._ports.has_key(attr):
4973105Sstever@eecs.umich.edu            return self._get_port_ref(attr)
4982738SN/A
4991692SN/A        if self._values.has_key(attr):
5001692SN/A            return self._values[attr]
5011427SN/A
5021692SN/A        raise AttributeError, "object '%s' has no attribute '%s'" \
5031692SN/A              % (self.__class__.__name__, attr)
5041427SN/A
5051692SN/A    # Set attribute (called on foo.attr = value when foo is an
5061692SN/A    # instance of class cls).
5071692SN/A    def __setattr__(self, attr, value):
5081692SN/A        # normal processing for private attributes
5091692SN/A        if attr.startswith('_'):
5101692SN/A            object.__setattr__(self, attr, value)
5111692SN/A            return
5121427SN/A
5132738SN/A        if self._ports.has_key(attr):
5142738SN/A            # set up port connection
5153105Sstever@eecs.umich.edu            self._get_port_ref(attr).connect(value)
5162738SN/A            return
5172738SN/A
5182740SN/A        if isSimObjectOrSequence(value) and self._instantiated:
5192740SN/A            raise RuntimeError, \
5202740SN/A                  "cannot set SimObject parameter '%s' after\n" \
5212740SN/A                  "    instance been cloned %s" % (attr, `self`)
5222740SN/A
5231692SN/A        # must be SimObject param
5243105Sstever@eecs.umich.edu        param = self._params.get(attr)
5251692SN/A        if param:
5261310SN/A            try:
5271692SN/A                value = param.convert(value)
5281587SN/A            except Exception, e:
5291692SN/A                msg = "%s\nError setting param %s.%s to %s\n" % \
5301692SN/A                      (e, self.__class__.__name__, attr, value)
5311605SN/A                e.args = (msg, )
5321605SN/A                raise
5333105Sstever@eecs.umich.edu            self._set_child(attr, value)
5343105Sstever@eecs.umich.edu            return
5351310SN/A
5363105Sstever@eecs.umich.edu        if isSimObjectOrSequence(value):
5373105Sstever@eecs.umich.edu            self._set_child(attr, value)
5383105Sstever@eecs.umich.edu            return
5391693SN/A
5403105Sstever@eecs.umich.edu        # no valid assignment... raise exception
5413105Sstever@eecs.umich.edu        raise AttributeError, "Class %s has no parameter %s" \
5423105Sstever@eecs.umich.edu              % (self.__class__.__name__, attr)
5431310SN/A
5441310SN/A
5451692SN/A    # this hack allows tacking a '[0]' onto parameters that may or may
5461692SN/A    # not be vectors, and always getting the first element (e.g. cpus)
5471692SN/A    def __getitem__(self, key):
5481692SN/A        if key == 0:
5491692SN/A            return self
5501692SN/A        raise TypeError, "Non-zero index '%s' to SimObject" % key
5511310SN/A
5521693SN/A    # clear out children with given name, even if it's a vector
5531693SN/A    def clear_child(self, name):
5541693SN/A        if not self._children.has_key(name):
5551693SN/A            return
5561693SN/A        child = self._children[name]
5571693SN/A        if isinstance(child, SimObjVector):
5581693SN/A            for i in xrange(len(child)):
5591693SN/A                del self._children["s%d" % (name, i)]
5601693SN/A        del self._children[name]
5611693SN/A
5621692SN/A    def add_child(self, name, value):
5631692SN/A        self._children[name] = value
5641310SN/A
5653105Sstever@eecs.umich.edu    def _maybe_set_parent(self, parent, name):
5662740SN/A        if not self._parent:
5671692SN/A            self._parent = parent
5681692SN/A            self._name = name
5691692SN/A            parent.add_child(name, self)
5701310SN/A
5713105Sstever@eecs.umich.edu    def _set_child(self, attr, value):
5723105Sstever@eecs.umich.edu        # if RHS is a SimObject, it's an implicit child assignment
5733105Sstever@eecs.umich.edu        # clear out old child with this name, if any
5743105Sstever@eecs.umich.edu        self.clear_child(attr)
5753105Sstever@eecs.umich.edu
5763105Sstever@eecs.umich.edu        if isSimObject(value):
5773105Sstever@eecs.umich.edu            value._maybe_set_parent(self, attr)
5783105Sstever@eecs.umich.edu        elif isSimObjectSequence(value):
5793105Sstever@eecs.umich.edu            value = SimObjVector(value)
5803105Sstever@eecs.umich.edu            [v._maybe_set_parent(self, "%s%d" % (attr, i))
5813105Sstever@eecs.umich.edu             for i,v in enumerate(value)]
5823105Sstever@eecs.umich.edu
5833105Sstever@eecs.umich.edu        self._values[attr] = value
5843105Sstever@eecs.umich.edu
5851692SN/A    def path(self):
5862740SN/A        if not self._parent:
5871692SN/A            return 'root'
5881692SN/A        ppath = self._parent.path()
5891692SN/A        if ppath == 'root':
5901692SN/A            return self._name
5911692SN/A        return ppath + "." + self._name
5921310SN/A
5931692SN/A    def __str__(self):
5941692SN/A        return self.path()
5951310SN/A
5961692SN/A    def ini_str(self):
5971692SN/A        return self.path()
5981310SN/A
5991692SN/A    def find_any(self, ptype):
6001692SN/A        if isinstance(self, ptype):
6011692SN/A            return self, True
6021310SN/A
6031692SN/A        found_obj = None
6041692SN/A        for child in self._children.itervalues():
6051692SN/A            if isinstance(child, ptype):
6061692SN/A                if found_obj != None and child != found_obj:
6071692SN/A                    raise AttributeError, \
6081692SN/A                          'parent.any matched more than one: %s %s' % \
6091814SN/A                          (found_obj.path, child.path)
6101692SN/A                found_obj = child
6111692SN/A        # search param space
6121692SN/A        for pname,pdesc in self._params.iteritems():
6131692SN/A            if issubclass(pdesc.ptype, ptype):
6141692SN/A                match_obj = self._values[pname]
6151692SN/A                if found_obj != None and found_obj != match_obj:
6161692SN/A                    raise AttributeError, \
6171692SN/A                          'parent.any matched more than one: %s' % obj.path
6181692SN/A                found_obj = match_obj
6191692SN/A        return found_obj, found_obj != None
6201692SN/A
6211815SN/A    def unproxy(self, base):
6221815SN/A        return self
6231815SN/A
6243105Sstever@eecs.umich.edu    def unproxy_all(self):
6253105Sstever@eecs.umich.edu        for param in self._params.iterkeys():
6263105Sstever@eecs.umich.edu            value = self._values.get(param)
6273105Sstever@eecs.umich.edu            if value != None and proxy.isproxy(value):
6283105Sstever@eecs.umich.edu                try:
6293105Sstever@eecs.umich.edu                    value = value.unproxy(self)
6303105Sstever@eecs.umich.edu                except:
6313105Sstever@eecs.umich.edu                    print "Error in unproxying param '%s' of %s" % \
6323105Sstever@eecs.umich.edu                          (param, self.path())
6333105Sstever@eecs.umich.edu                    raise
6343105Sstever@eecs.umich.edu                setattr(self, param, value)
6353105Sstever@eecs.umich.edu
6363107Sstever@eecs.umich.edu        # Unproxy ports in sorted order so that 'append' operations on
6373107Sstever@eecs.umich.edu        # vector ports are done in a deterministic fashion.
6383107Sstever@eecs.umich.edu        port_names = self._ports.keys()
6393107Sstever@eecs.umich.edu        port_names.sort()
6403107Sstever@eecs.umich.edu        for port_name in port_names:
6413105Sstever@eecs.umich.edu            port = self._port_refs.get(port_name)
6423105Sstever@eecs.umich.edu            if port != None:
6433105Sstever@eecs.umich.edu                port.unproxy(self)
6443105Sstever@eecs.umich.edu
6453107Sstever@eecs.umich.edu        # Unproxy children in sorted order for determinism also.
6463107Sstever@eecs.umich.edu        child_names = self._children.keys()
6473107Sstever@eecs.umich.edu        child_names.sort()
6483107Sstever@eecs.umich.edu        for child in child_names:
6493107Sstever@eecs.umich.edu            self._children[child].unproxy_all()
6503105Sstever@eecs.umich.edu
6511692SN/A    def print_ini(self):
6521692SN/A        print '[' + self.path() + ']'	# .ini section header
6531692SN/A
6542738SN/A        instanceDict[self.path()] = self
6552738SN/A
6561692SN/A        if hasattr(self, 'type') and not isinstance(self, ParamContext):
6571799SN/A            print 'type=%s' % self.type
6581692SN/A
6591692SN/A        child_names = self._children.keys()
6601692SN/A        child_names.sort()
6611692SN/A        np_child_names = [c for c in child_names \
6621692SN/A                          if not isinstance(self._children[c], ParamContext)]
6631692SN/A        if len(np_child_names):
6641799SN/A            print 'children=%s' % ' '.join(np_child_names)
6651692SN/A
6661692SN/A        param_names = self._params.keys()
6671692SN/A        param_names.sort()
6681692SN/A        for param in param_names:
6693105Sstever@eecs.umich.edu            value = self._values.get(param)
6701692SN/A            if value != None:
6711799SN/A                print '%s=%s' % (param, self._values[param].ini_str())
6721692SN/A
6733103Sstever@eecs.umich.edu        port_names = self._ports.keys()
6743103Sstever@eecs.umich.edu        port_names.sort()
6753103Sstever@eecs.umich.edu        for port_name in port_names:
6763105Sstever@eecs.umich.edu            port = self._port_refs.get(port_name, None)
6773105Sstever@eecs.umich.edu            if port != None:
6783105Sstever@eecs.umich.edu                print '%s=%s' % (port_name, port.ini_str())
6793103Sstever@eecs.umich.edu
6801692SN/A        print	# blank line between objects
6811692SN/A
6821692SN/A        for child in child_names:
6831692SN/A            self._children[child].print_ini()
6841692SN/A
6852738SN/A    # Call C++ to create C++ object corresponding to this object and
6862738SN/A    # (recursively) all its children
6872738SN/A    def createCCObject(self):
6882740SN/A        self.getCCObject() # force creation
6892738SN/A        for child in self._children.itervalues():
6902738SN/A            child.createCCObject()
6912738SN/A
6922740SN/A    # Get C++ object corresponding to this object, calling C++ if
6932740SN/A    # necessary to construct it.  Does *not* recursively create
6942740SN/A    # children.
6952740SN/A    def getCCObject(self):
6962740SN/A        if not self._ccObject:
6972740SN/A            self._ccObject = -1 # flag to catch cycles in recursion
6982763SN/A            self._ccObject = cc_main.createSimObject(self.path())
6992740SN/A        elif self._ccObject == -1:
7002740SN/A            raise RuntimeError, "%s: recursive call to getCCObject()" \
7012740SN/A                  % self.path()
7022740SN/A        return self._ccObject
7032740SN/A
7042738SN/A    # Create C++ port connections corresponding to the connections in
7053105Sstever@eecs.umich.edu    # _port_refs (& recursively for all children)
7062738SN/A    def connectPorts(self):
7073105Sstever@eecs.umich.edu        for portRef in self._port_refs.itervalues():
7083105Sstever@eecs.umich.edu            portRef.ccConnect()
7092738SN/A        for child in self._children.itervalues():
7102738SN/A            child.connectPorts()
7112738SN/A
7122839SN/A    def startDrain(self, drain_event, recursive):
7132797SN/A        count = 0
7142797SN/A        # ParamContexts don't serialize
7152797SN/A        if isinstance(self, SimObject) and not isinstance(self, ParamContext):
7162901SN/A            count += self._ccObject.drain(drain_event)
7172797SN/A        if recursive:
7182797SN/A            for child in self._children.itervalues():
7192839SN/A                count += child.startDrain(drain_event, True)
7202797SN/A        return count
7212797SN/A
7222797SN/A    def resume(self):
7232797SN/A        if isinstance(self, SimObject) and not isinstance(self, ParamContext):
7242797SN/A            self._ccObject.resume()
7252797SN/A        for child in self._children.itervalues():
7262797SN/A            child.resume()
7272797SN/A
7282797SN/A    def changeTiming(self, mode):
7292901SN/A        if isinstance(self, System):
7302797SN/A            self._ccObject.setMemoryMode(mode)
7312797SN/A        for child in self._children.itervalues():
7322797SN/A            child.changeTiming(mode)
7332797SN/A
7342797SN/A    def takeOverFrom(self, old_cpu):
7352797SN/A        cpu_ptr = cc_main.convertToBaseCPUPtr(old_cpu._ccObject)
7362797SN/A        self._ccObject.takeOverFrom(cpu_ptr)
7372797SN/A
7381692SN/A    # generate output file for 'dot' to display as a pretty graph.
7391692SN/A    # this code is currently broken.
7401342SN/A    def outputDot(self, dot):
7411342SN/A        label = "{%s|" % self.path
7421342SN/A        if isSimObject(self.realtype):
7431342SN/A            label +=  '%s|' % self.type
7441342SN/A
7451342SN/A        if self.children:
7461342SN/A            # instantiate children in same order they were added for
7471342SN/A            # backward compatibility (else we can end up with cpu1
7481342SN/A            # before cpu0).
7491342SN/A            for c in self.children:
7501342SN/A                dot.add_edge(pydot.Edge(self.path,c.path, style="bold"))
7511342SN/A
7521342SN/A        simobjs = []
7531342SN/A        for param in self.params:
7541342SN/A            try:
7551342SN/A                if param.value is None:
7561342SN/A                    raise AttributeError, 'Parameter with no value'
7571342SN/A
7581692SN/A                value = param.value
7591342SN/A                string = param.string(value)
7601587SN/A            except Exception, e:
7611605SN/A                msg = 'exception in %s:%s\n%s' % (self.name, param.name, e)
7621605SN/A                e.args = (msg, )
7631342SN/A                raise
7641605SN/A
7651692SN/A            if isSimObject(param.ptype) and string != "Null":
7661342SN/A                simobjs.append(string)
7671342SN/A            else:
7681342SN/A                label += '%s = %s\\n' % (param.name, string)
7691342SN/A
7701342SN/A        for so in simobjs:
7711342SN/A            label += "|<%s> %s" % (so, so)
7721587SN/A            dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so,
7731587SN/A                                    tailport="w"))
7741342SN/A        label += '}'
7751342SN/A        dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label))
7761342SN/A
7771342SN/A        # recursively dump out children
7781342SN/A        for c in self.children:
7791342SN/A            c.outputDot(dot)
7801342SN/A
7811692SN/Aclass ParamContext(SimObject):
7821692SN/A    pass
7831692SN/A
7843101Sstever@eecs.umich.edu# Function to provide to C++ so it can look up instances based on paths
7853101Sstever@eecs.umich.edudef resolveSimObject(name):
7863101Sstever@eecs.umich.edu    obj = instanceDict[name]
7873101Sstever@eecs.umich.edu    return obj.getCCObject()
788679SN/A
7891528SN/A# __all__ defines the list of symbols that get exported when
7901528SN/A# 'from config import *' is invoked.  Try to keep this reasonably
7911528SN/A# short to avoid polluting other namespaces.
7923101Sstever@eecs.umich.edu__all__ = ['SimObject', 'ParamContext']
7931692SN/A
7943102Sstever@eecs.umich.edu
7953102Sstever@eecs.umich.edu# see comment on imports at end of __init__.py.
7963102Sstever@eecs.umich.eduimport proxy
7973102Sstever@eecs.umich.eduimport cc_main
7983103Sstever@eecs.umich.eduimport m5
799