SimObject.py revision 8597
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
328331Ssteve.reinhardt@amd.comfrom types import FunctionType, MethodType, ModuleType
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
1007673Snate@binkert.orgdef public_value(key, value):
1017673Snate@binkert.org    return key.startswith('_') or \
1028331Ssteve.reinhardt@amd.com               isinstance(value, (FunctionType, MethodType, ModuleType,
1038331Ssteve.reinhardt@amd.com                                  classmethod, type))
1047673Snate@binkert.org
1052740SN/A# The metaclass for SimObject.  This class controls how new classes
1062740SN/A# that derive from SimObject are instantiated, and provides inherited
1072740SN/A# class behavior (just like a class controls how instances of that
1082740SN/A# class are instantiated, and provides inherited instance behavior).
1091692SN/Aclass MetaSimObject(type):
1101427SN/A    # Attributes that can be set only at initialization time
1117493Ssteve.reinhardt@amd.com    init_keywords = { 'abstract' : bool,
1127493Ssteve.reinhardt@amd.com                      'cxx_class' : str,
1137493Ssteve.reinhardt@amd.com                      'cxx_type' : str,
1147493Ssteve.reinhardt@amd.com                      'type' : str }
1151427SN/A    # Attributes that can be set any time
1167493Ssteve.reinhardt@amd.com    keywords = { 'check' : FunctionType }
117679SN/A
118679SN/A    # __new__ is called before __init__, and is where the statements
119679SN/A    # in the body of the class definition get loaded into the class's
1202740SN/A    # __dict__.  We intercept this to filter out parameter & port assignments
121679SN/A    # and only allow "private" attributes to be passed to the base
122679SN/A    # __new__ (starting with underscore).
1231310SN/A    def __new__(mcls, name, bases, dict):
1246654Snate@binkert.org        assert name not in allClasses, "SimObject %s already present" % name
1254762Snate@binkert.org
1262740SN/A        # Copy "private" attributes, functions, and classes to the
1272740SN/A        # official dict.  Everything else goes in _init_dict to be
1282740SN/A        # filtered in __init__.
1292740SN/A        cls_dict = {}
1302740SN/A        value_dict = {}
1312740SN/A        for key,val in dict.items():
1327673Snate@binkert.org            if public_value(key, val):
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']
1924859Snate@binkert.org
1938597Ssteve.reinhardt@amd.com        # Export methods are automatically inherited via C++, so we
1948597Ssteve.reinhardt@amd.com        # don't want the method declarations to get inherited on the
1958597Ssteve.reinhardt@amd.com        # python side (and thus end up getting repeated in the wrapped
1968597Ssteve.reinhardt@amd.com        # versions of derived classes).  The code below basicallly
1978597Ssteve.reinhardt@amd.com        # suppresses inheritance by substituting in the base (null)
1988597Ssteve.reinhardt@amd.com        # versions of these methods unless a different version is
1998597Ssteve.reinhardt@amd.com        # explicitly supplied.
2008597Ssteve.reinhardt@amd.com        for method_name in ('export_methods', 'export_method_cxx_predecls',
2018597Ssteve.reinhardt@amd.com                            'export_method_swig_predecls'):
2028597Ssteve.reinhardt@amd.com            if method_name not in cls.__dict__:
2038597Ssteve.reinhardt@amd.com                base_method = getattr(MetaSimObject, method_name)
2048597Ssteve.reinhardt@amd.com                m = MethodType(base_method, cls, MetaSimObject)
2058597Ssteve.reinhardt@amd.com                setattr(cls, method_name, m)
2068597Ssteve.reinhardt@amd.com
2072740SN/A        # Now process the _value_dict items.  They could be defining
2082740SN/A        # new (or overriding existing) parameters or ports, setting
2092740SN/A        # class keywords (e.g., 'abstract'), or setting parameter
2102740SN/A        # values or port bindings.  The first 3 can only be set when
2112740SN/A        # the class is defined, so we handle them here.  The others
2122740SN/A        # can be set later too, so just emulate that by calling
2132740SN/A        # setattr().
2142740SN/A        for key,val in cls._value_dict.items():
2151527SN/A            # param descriptions
2162740SN/A            if isinstance(val, ParamDesc):
2171585SN/A                cls._new_param(key, val)
2181427SN/A
2192738SN/A            # port objects
2202738SN/A            elif isinstance(val, Port):
2213105Sstever@eecs.umich.edu                cls._new_port(key, val)
2222738SN/A
2231427SN/A            # init-time-only keywords
2241427SN/A            elif cls.init_keywords.has_key(key):
2251427SN/A                cls._set_keyword(key, val, cls.init_keywords[key])
2261427SN/A
2271427SN/A            # default: use normal path (ends up in __setattr__)
2281427SN/A            else:
2291427SN/A                setattr(cls, key, val)
2301427SN/A
2311427SN/A    def _set_keyword(cls, keyword, val, kwtype):
2321427SN/A        if not isinstance(val, kwtype):
2331427SN/A            raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
2341427SN/A                  (keyword, type(val), kwtype)
2357493Ssteve.reinhardt@amd.com        if isinstance(val, FunctionType):
2361427SN/A            val = classmethod(val)
2371427SN/A        type.__setattr__(cls, keyword, val)
2381427SN/A
2393100SN/A    def _new_param(cls, name, pdesc):
2403100SN/A        # each param desc should be uniquely assigned to one variable
2413100SN/A        assert(not hasattr(pdesc, 'name'))
2423100SN/A        pdesc.name = name
2433100SN/A        cls._params[name] = pdesc
2443100SN/A        if hasattr(pdesc, 'default'):
2453105Sstever@eecs.umich.edu            cls._set_param(name, pdesc.default, pdesc)
2463105Sstever@eecs.umich.edu
2473105Sstever@eecs.umich.edu    def _set_param(cls, name, value, param):
2483105Sstever@eecs.umich.edu        assert(param.name == name)
2493105Sstever@eecs.umich.edu        try:
2508321Ssteve.reinhardt@amd.com            value = param.convert(value)
2513105Sstever@eecs.umich.edu        except Exception, e:
2523105Sstever@eecs.umich.edu            msg = "%s\nError setting param %s.%s to %s\n" % \
2533105Sstever@eecs.umich.edu                  (e, cls.__name__, name, value)
2543105Sstever@eecs.umich.edu            e.args = (msg, )
2553105Sstever@eecs.umich.edu            raise
2568321Ssteve.reinhardt@amd.com        cls._values[name] = value
2578321Ssteve.reinhardt@amd.com        # if param value is a SimObject, make it a child too, so that
2588321Ssteve.reinhardt@amd.com        # it gets cloned properly when the class is instantiated
2598321Ssteve.reinhardt@amd.com        if isSimObjectOrVector(value) and not value.has_parent():
2608321Ssteve.reinhardt@amd.com            cls._add_cls_child(name, value)
2618321Ssteve.reinhardt@amd.com
2628321Ssteve.reinhardt@amd.com    def _add_cls_child(cls, name, child):
2638321Ssteve.reinhardt@amd.com        # It's a little funky to have a class as a parent, but these
2648321Ssteve.reinhardt@amd.com        # objects should never be instantiated (only cloned, which
2658321Ssteve.reinhardt@amd.com        # clears the parent pointer), and this makes it clear that the
2668321Ssteve.reinhardt@amd.com        # object is not an orphan and can provide better error
2678321Ssteve.reinhardt@amd.com        # messages.
2688321Ssteve.reinhardt@amd.com        child.set_parent(cls, name)
2698321Ssteve.reinhardt@amd.com        cls._children[name] = child
2703105Sstever@eecs.umich.edu
2713105Sstever@eecs.umich.edu    def _new_port(cls, name, port):
2723105Sstever@eecs.umich.edu        # each port should be uniquely assigned to one variable
2733105Sstever@eecs.umich.edu        assert(not hasattr(port, 'name'))
2743105Sstever@eecs.umich.edu        port.name = name
2753105Sstever@eecs.umich.edu        cls._ports[name] = port
2763105Sstever@eecs.umich.edu        if hasattr(port, 'default'):
2773105Sstever@eecs.umich.edu            cls._cls_get_port_ref(name).connect(port.default)
2783105Sstever@eecs.umich.edu
2793105Sstever@eecs.umich.edu    # same as _get_port_ref, effectively, but for classes
2803105Sstever@eecs.umich.edu    def _cls_get_port_ref(cls, attr):
2813105Sstever@eecs.umich.edu        # Return reference that can be assigned to another port
2823105Sstever@eecs.umich.edu        # via __setattr__.  There is only ever one reference
2833105Sstever@eecs.umich.edu        # object per port, but we create them lazily here.
2843105Sstever@eecs.umich.edu        ref = cls._port_refs.get(attr)
2853105Sstever@eecs.umich.edu        if not ref:
2863105Sstever@eecs.umich.edu            ref = cls._ports[attr].makeRef(cls)
2873105Sstever@eecs.umich.edu            cls._port_refs[attr] = ref
2883105Sstever@eecs.umich.edu        return ref
2891585SN/A
2901310SN/A    # Set attribute (called on foo.attr = value when foo is an
2911310SN/A    # instance of class cls).
2921310SN/A    def __setattr__(cls, attr, value):
2931310SN/A        # normal processing for private attributes
2947673Snate@binkert.org        if public_value(attr, value):
2951310SN/A            type.__setattr__(cls, attr, value)
2961310SN/A            return
2971310SN/A
2981310SN/A        if cls.keywords.has_key(attr):
2991427SN/A            cls._set_keyword(attr, value, cls.keywords[attr])
3001310SN/A            return
3011310SN/A
3022738SN/A        if cls._ports.has_key(attr):
3033105Sstever@eecs.umich.edu            cls._cls_get_port_ref(attr).connect(value)
3042738SN/A            return
3052738SN/A
3062740SN/A        if isSimObjectOrSequence(value) and cls._instantiated:
3072740SN/A            raise RuntimeError, \
3082740SN/A                  "cannot set SimObject parameter '%s' after\n" \
3092740SN/A                  "    class %s has been instantiated or subclassed" \
3102740SN/A                  % (attr, cls.__name__)
3112740SN/A
3122740SN/A        # check for param
3133105Sstever@eecs.umich.edu        param = cls._params.get(attr)
3141310SN/A        if param:
3153105Sstever@eecs.umich.edu            cls._set_param(attr, value, param)
3163105Sstever@eecs.umich.edu            return
3173105Sstever@eecs.umich.edu
3183105Sstever@eecs.umich.edu        if isSimObjectOrSequence(value):
3193105Sstever@eecs.umich.edu            # If RHS is a SimObject, it's an implicit child assignment.
3208321Ssteve.reinhardt@amd.com            cls._add_cls_child(attr, coerceSimObjectOrVector(value))
3213105Sstever@eecs.umich.edu            return
3223105Sstever@eecs.umich.edu
3233105Sstever@eecs.umich.edu        # no valid assignment... raise exception
3243105Sstever@eecs.umich.edu        raise AttributeError, \
3253105Sstever@eecs.umich.edu              "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
3261310SN/A
3271585SN/A    def __getattr__(cls, attr):
3287675Snate@binkert.org        if attr == 'cxx_class_path':
3297675Snate@binkert.org            return cls.cxx_class.split('::')
3307675Snate@binkert.org
3317675Snate@binkert.org        if attr == 'cxx_class_name':
3327675Snate@binkert.org            return cls.cxx_class_path[-1]
3337675Snate@binkert.org
3347675Snate@binkert.org        if attr == 'cxx_namespaces':
3357675Snate@binkert.org            return cls.cxx_class_path[:-1]
3367675Snate@binkert.org
3371692SN/A        if cls._values.has_key(attr):
3381692SN/A            return cls._values[attr]
3391585SN/A
3407528Ssteve.reinhardt@amd.com        if cls._children.has_key(attr):
3417528Ssteve.reinhardt@amd.com            return cls._children[attr]
3427528Ssteve.reinhardt@amd.com
3431585SN/A        raise AttributeError, \
3441585SN/A              "object '%s' has no attribute '%s'" % (cls.__name__, attr)
3451585SN/A
3463100SN/A    def __str__(cls):
3473100SN/A        return cls.__name__
3483100SN/A
3498596Ssteve.reinhardt@amd.com    # See ParamValue.cxx_predecls for description.
3508596Ssteve.reinhardt@amd.com    def cxx_predecls(cls, code):
3518596Ssteve.reinhardt@amd.com        code('#include "params/$cls.hh"')
3528596Ssteve.reinhardt@amd.com
3538596Ssteve.reinhardt@amd.com    # See ParamValue.swig_predecls for description.
3548596Ssteve.reinhardt@amd.com    def swig_predecls(cls, code):
3558596Ssteve.reinhardt@amd.com        code('%import "python/m5/internal/param_$cls.i"')
3568596Ssteve.reinhardt@amd.com
3578597Ssteve.reinhardt@amd.com    # Hook for exporting additional C++ methods to Python via SWIG.
3588597Ssteve.reinhardt@amd.com    # Default is none, override using @classmethod in class definition.
3598597Ssteve.reinhardt@amd.com    def export_methods(cls, code):
3608597Ssteve.reinhardt@amd.com        pass
3618597Ssteve.reinhardt@amd.com
3628597Ssteve.reinhardt@amd.com    # Generate the code needed as a prerequisite for the C++ methods
3638597Ssteve.reinhardt@amd.com    # exported via export_methods() to be compiled in the _wrap.cc
3648597Ssteve.reinhardt@amd.com    # file.  Typically generates one or more #include statements.  If
3658597Ssteve.reinhardt@amd.com    # any methods are exported, typically at least the C++ header
3668597Ssteve.reinhardt@amd.com    # declaring the relevant SimObject class must be included.
3678597Ssteve.reinhardt@amd.com    def export_method_cxx_predecls(cls, code):
3688597Ssteve.reinhardt@amd.com        pass
3698597Ssteve.reinhardt@amd.com
3708597Ssteve.reinhardt@amd.com    # Generate the code needed as a prerequisite for the C++ methods
3718597Ssteve.reinhardt@amd.com    # exported via export_methods() to be processed by SWIG.
3728597Ssteve.reinhardt@amd.com    # Typically generates one or more %include or %import statements.
3738597Ssteve.reinhardt@amd.com    # If any methods are exported, typically at least the C++ header
3748597Ssteve.reinhardt@amd.com    # declaring the relevant SimObject class must be included.
3758597Ssteve.reinhardt@amd.com    def export_method_swig_predecls(cls, code):
3768597Ssteve.reinhardt@amd.com        pass
3778597Ssteve.reinhardt@amd.com
3788596Ssteve.reinhardt@amd.com    # Generate the declaration for this object for wrapping with SWIG.
3798596Ssteve.reinhardt@amd.com    # Generates code that goes into a SWIG .i file.  Called from
3808596Ssteve.reinhardt@amd.com    # src/SConscript.
3818596Ssteve.reinhardt@amd.com    def swig_decl(cls, code):
3828596Ssteve.reinhardt@amd.com        class_path = cls.cxx_class.split('::')
3838596Ssteve.reinhardt@amd.com        classname = class_path[-1]
3848596Ssteve.reinhardt@amd.com        namespaces = class_path[:-1]
3858596Ssteve.reinhardt@amd.com
3868596Ssteve.reinhardt@amd.com        # The 'local' attribute restricts us to the params declared in
3878596Ssteve.reinhardt@amd.com        # the object itself, not including inherited params (which
3888596Ssteve.reinhardt@amd.com        # will also be inherited from the base class's param struct
3898596Ssteve.reinhardt@amd.com        # here).
3908596Ssteve.reinhardt@amd.com        params = cls._params.local.values()
3918596Ssteve.reinhardt@amd.com
3928596Ssteve.reinhardt@amd.com        code('%module(package="m5.internal") param_$cls')
3938596Ssteve.reinhardt@amd.com        code()
3948596Ssteve.reinhardt@amd.com        code('%{')
3958596Ssteve.reinhardt@amd.com        code('#include "params/$cls.hh"')
3968596Ssteve.reinhardt@amd.com        for param in params:
3978596Ssteve.reinhardt@amd.com            param.cxx_predecls(code)
3988597Ssteve.reinhardt@amd.com        cls.export_method_cxx_predecls(code)
3998596Ssteve.reinhardt@amd.com        code('%}')
4008596Ssteve.reinhardt@amd.com        code()
4018596Ssteve.reinhardt@amd.com
4028596Ssteve.reinhardt@amd.com        for param in params:
4038596Ssteve.reinhardt@amd.com            param.swig_predecls(code)
4048597Ssteve.reinhardt@amd.com        cls.export_method_swig_predecls(code)
4058596Ssteve.reinhardt@amd.com
4068596Ssteve.reinhardt@amd.com        code()
4078596Ssteve.reinhardt@amd.com        if cls._base:
4088596Ssteve.reinhardt@amd.com            code('%import "python/m5/internal/param_${{cls._base}}.i"')
4098596Ssteve.reinhardt@amd.com        code()
4108596Ssteve.reinhardt@amd.com
4118596Ssteve.reinhardt@amd.com        for ns in namespaces:
4128596Ssteve.reinhardt@amd.com            code('namespace $ns {')
4138596Ssteve.reinhardt@amd.com
4148596Ssteve.reinhardt@amd.com        if namespaces:
4158596Ssteve.reinhardt@amd.com            code('// avoid name conflicts')
4168596Ssteve.reinhardt@amd.com            sep_string = '_COLONS_'
4178596Ssteve.reinhardt@amd.com            flat_name = sep_string.join(class_path)
4188596Ssteve.reinhardt@amd.com            code('%rename($flat_name) $classname;')
4198596Ssteve.reinhardt@amd.com
4208597Ssteve.reinhardt@amd.com        code()
4218597Ssteve.reinhardt@amd.com        code('// stop swig from creating/wrapping default ctor/dtor')
4228597Ssteve.reinhardt@amd.com        code('%nodefault $classname;')
4238597Ssteve.reinhardt@amd.com        code('class $classname')
4248597Ssteve.reinhardt@amd.com        if cls._base:
4258597Ssteve.reinhardt@amd.com            code('    : public ${{cls._base.cxx_class}}')
4268597Ssteve.reinhardt@amd.com        code('{')
4278597Ssteve.reinhardt@amd.com        code('  public:')
4288597Ssteve.reinhardt@amd.com        cls.export_methods(code)
4298597Ssteve.reinhardt@amd.com        code('};')
4308596Ssteve.reinhardt@amd.com
4318596Ssteve.reinhardt@amd.com        for ns in reversed(namespaces):
4328596Ssteve.reinhardt@amd.com            code('} // namespace $ns')
4338596Ssteve.reinhardt@amd.com
4348596Ssteve.reinhardt@amd.com        code()
4358596Ssteve.reinhardt@amd.com        code('%include "params/$cls.hh"')
4368596Ssteve.reinhardt@amd.com
4378596Ssteve.reinhardt@amd.com
4388596Ssteve.reinhardt@amd.com    # Generate the C++ declaration (.hh file) for this SimObject's
4398596Ssteve.reinhardt@amd.com    # param struct.  Called from src/SConscript.
4408596Ssteve.reinhardt@amd.com    def cxx_param_decl(cls, code):
4418596Ssteve.reinhardt@amd.com        # The 'local' attribute restricts us to the params declared in
4423100SN/A        # the object itself, not including inherited params (which
4433100SN/A        # will also be inherited from the base class's param struct
4443100SN/A        # here).
4454762Snate@binkert.org        params = cls._params.local.values()
4463100SN/A        try:
4473100SN/A            ptypes = [p.ptype for p in params]
4483100SN/A        except:
4493100SN/A            print cls, p, p.ptype_str
4503100SN/A            print params
4513100SN/A            raise
4523100SN/A
4537675Snate@binkert.org        class_path = cls._value_dict['cxx_class'].split('::')
4547675Snate@binkert.org
4557675Snate@binkert.org        code('''\
4567675Snate@binkert.org#ifndef __PARAMS__${cls}__
4577675Snate@binkert.org#define __PARAMS__${cls}__
4587675Snate@binkert.org
4597675Snate@binkert.org''')
4607675Snate@binkert.org
4617675Snate@binkert.org        # A forward class declaration is sufficient since we are just
4627675Snate@binkert.org        # declaring a pointer.
4637675Snate@binkert.org        for ns in class_path[:-1]:
4647675Snate@binkert.org            code('namespace $ns {')
4657675Snate@binkert.org        code('class $0;', class_path[-1])
4667675Snate@binkert.org        for ns in reversed(class_path[:-1]):
4677811Ssteve.reinhardt@amd.com            code('} // namespace $ns')
4687675Snate@binkert.org        code()
4697675Snate@binkert.org
4708597Ssteve.reinhardt@amd.com        # The base SimObject has a couple of params that get
4718597Ssteve.reinhardt@amd.com        # automatically set from Python without being declared through
4728597Ssteve.reinhardt@amd.com        # the normal Param mechanism; we slip them in here (needed
4738597Ssteve.reinhardt@amd.com        # predecls now, actual declarations below)
4748597Ssteve.reinhardt@amd.com        if cls == SimObject:
4758597Ssteve.reinhardt@amd.com            code('''
4768597Ssteve.reinhardt@amd.com#ifndef PY_VERSION
4778597Ssteve.reinhardt@amd.comstruct PyObject;
4788597Ssteve.reinhardt@amd.com#endif
4798597Ssteve.reinhardt@amd.com
4808597Ssteve.reinhardt@amd.com#include <string>
4818597Ssteve.reinhardt@amd.com
4828597Ssteve.reinhardt@amd.comstruct EventQueue;
4838597Ssteve.reinhardt@amd.com''')
4847673Snate@binkert.org        for param in params:
4857673Snate@binkert.org            param.cxx_predecls(code)
4867673Snate@binkert.org        code()
4874762Snate@binkert.org
4885610Snate@binkert.org        if cls._base:
4897673Snate@binkert.org            code('#include "params/${{cls._base.type}}.hh"')
4907673Snate@binkert.org            code()
4914762Snate@binkert.org
4924762Snate@binkert.org        for ptype in ptypes:
4934762Snate@binkert.org            if issubclass(ptype, Enum):
4947673Snate@binkert.org                code('#include "enums/${{ptype.__name__}}.hh"')
4957673Snate@binkert.org                code()
4964762Snate@binkert.org
4978596Ssteve.reinhardt@amd.com        # now generate the actual param struct
4988597Ssteve.reinhardt@amd.com        code("struct ${cls}Params")
4998597Ssteve.reinhardt@amd.com        if cls._base:
5008597Ssteve.reinhardt@amd.com            code("    : public ${{cls._base.type}}Params")
5018597Ssteve.reinhardt@amd.com        code("{")
5028597Ssteve.reinhardt@amd.com        if not hasattr(cls, 'abstract') or not cls.abstract:
5038597Ssteve.reinhardt@amd.com            if 'type' in cls.__dict__:
5048597Ssteve.reinhardt@amd.com                code("    ${{cls.cxx_type}} create();")
5058597Ssteve.reinhardt@amd.com
5068597Ssteve.reinhardt@amd.com        code.indent()
5078596Ssteve.reinhardt@amd.com        if cls == SimObject:
5088597Ssteve.reinhardt@amd.com            code('''
5098597Ssteve.reinhardt@amd.com    SimObjectParams()
5108597Ssteve.reinhardt@amd.com    {
5118597Ssteve.reinhardt@amd.com        extern EventQueue mainEventQueue;
5128597Ssteve.reinhardt@amd.com        eventq = &mainEventQueue;
5138597Ssteve.reinhardt@amd.com    }
5148597Ssteve.reinhardt@amd.com    virtual ~SimObjectParams() {}
5158596Ssteve.reinhardt@amd.com
5168597Ssteve.reinhardt@amd.com    std::string name;
5178597Ssteve.reinhardt@amd.com    PyObject *pyobj;
5188597Ssteve.reinhardt@amd.com    EventQueue *eventq;
5198597Ssteve.reinhardt@amd.com            ''')
5208597Ssteve.reinhardt@amd.com        for param in params:
5218597Ssteve.reinhardt@amd.com            param.cxx_decl(code)
5228597Ssteve.reinhardt@amd.com        code.dedent()
5238597Ssteve.reinhardt@amd.com        code('};')
5245488Snate@binkert.org
5257673Snate@binkert.org        code()
5267673Snate@binkert.org        code('#endif // __PARAMS__${cls}__')
5275488Snate@binkert.org        return code
5285488Snate@binkert.org
5295488Snate@binkert.org
5303100SN/A
5312740SN/A# The SimObject class is the root of the special hierarchy.  Most of
532679SN/A# the code in this class deals with the configuration hierarchy itself
533679SN/A# (parent/child node relationships).
5341692SN/Aclass SimObject(object):
5351692SN/A    # Specify metaclass.  Any class inheriting from SimObject will
536679SN/A    # get this metaclass.
5371692SN/A    __metaclass__ = MetaSimObject
5383100SN/A    type = 'SimObject'
5394762Snate@binkert.org    abstract = True
5403100SN/A
5418597Ssteve.reinhardt@amd.com    @classmethod
5428597Ssteve.reinhardt@amd.com    def export_method_cxx_predecls(cls, code):
5438597Ssteve.reinhardt@amd.com        code('''
5448597Ssteve.reinhardt@amd.com#include <Python.h>
5458597Ssteve.reinhardt@amd.com
5468597Ssteve.reinhardt@amd.com#include "sim/serialize.hh"
5478597Ssteve.reinhardt@amd.com#include "sim/sim_object.hh"
5488597Ssteve.reinhardt@amd.com''')
5498597Ssteve.reinhardt@amd.com
5508597Ssteve.reinhardt@amd.com    @classmethod
5518597Ssteve.reinhardt@amd.com    def export_method_swig_predecls(cls, code):
5528597Ssteve.reinhardt@amd.com        code('''
5538597Ssteve.reinhardt@amd.com%include <std_string.i>
5548597Ssteve.reinhardt@amd.com''')
5558597Ssteve.reinhardt@amd.com
5568597Ssteve.reinhardt@amd.com    @classmethod
5578597Ssteve.reinhardt@amd.com    def export_methods(cls, code):
5588597Ssteve.reinhardt@amd.com        code('''
5598597Ssteve.reinhardt@amd.com    enum State {
5608597Ssteve.reinhardt@amd.com      Running,
5618597Ssteve.reinhardt@amd.com      Draining,
5628597Ssteve.reinhardt@amd.com      Drained
5638597Ssteve.reinhardt@amd.com    };
5648597Ssteve.reinhardt@amd.com
5658597Ssteve.reinhardt@amd.com    void init();
5668597Ssteve.reinhardt@amd.com    void loadState(Checkpoint *cp);
5678597Ssteve.reinhardt@amd.com    void initState();
5688597Ssteve.reinhardt@amd.com    void regStats();
5698597Ssteve.reinhardt@amd.com    void regFormulas();
5708597Ssteve.reinhardt@amd.com    void resetStats();
5718597Ssteve.reinhardt@amd.com    void startup();
5728597Ssteve.reinhardt@amd.com
5738597Ssteve.reinhardt@amd.com    unsigned int drain(Event *drain_event);
5748597Ssteve.reinhardt@amd.com    void resume();
5758597Ssteve.reinhardt@amd.com    void switchOut();
5768597Ssteve.reinhardt@amd.com    void takeOverFrom(BaseCPU *cpu);
5778597Ssteve.reinhardt@amd.com''')
5788597Ssteve.reinhardt@amd.com
5792740SN/A    # Initialize new instance.  For objects with SimObject-valued
5802740SN/A    # children, we need to recursively clone the classes represented
5812740SN/A    # by those param values as well in a consistent "deep copy"-style
5822740SN/A    # fashion.  That is, we want to make sure that each instance is
5832740SN/A    # cloned only once, and that if there are multiple references to
5842740SN/A    # the same original object, we end up with the corresponding
5852740SN/A    # cloned references all pointing to the same cloned instance.
5862740SN/A    def __init__(self, **kwargs):
5872740SN/A        ancestor = kwargs.get('_ancestor')
5882740SN/A        memo_dict = kwargs.get('_memo')
5892740SN/A        if memo_dict is None:
5902740SN/A            # prepare to memoize any recursively instantiated objects
5912740SN/A            memo_dict = {}
5922740SN/A        elif ancestor:
5932740SN/A            # memoize me now to avoid problems with recursive calls
5942740SN/A            memo_dict[ancestor] = self
5952711SN/A
5962740SN/A        if not ancestor:
5972740SN/A            ancestor = self.__class__
5982740SN/A        ancestor._instantiated = True
5992711SN/A
6002740SN/A        # initialize required attributes
6012740SN/A        self._parent = None
6027528Ssteve.reinhardt@amd.com        self._name = None
6032740SN/A        self._ccObject = None  # pointer to C++ object
6044762Snate@binkert.org        self._ccParams = None
6052740SN/A        self._instantiated = False # really "cloned"
6062712SN/A
6078321Ssteve.reinhardt@amd.com        # Clone children specified at class level.  No need for a
6088321Ssteve.reinhardt@amd.com        # multidict here since we will be cloning everything.
6098321Ssteve.reinhardt@amd.com        # Do children before parameter values so that children that
6108321Ssteve.reinhardt@amd.com        # are also param values get cloned properly.
6118321Ssteve.reinhardt@amd.com        self._children = {}
6128321Ssteve.reinhardt@amd.com        for key,val in ancestor._children.iteritems():
6138321Ssteve.reinhardt@amd.com            self.add_child(key, val(_memo=memo_dict))
6148321Ssteve.reinhardt@amd.com
6152711SN/A        # Inherit parameter values from class using multidict so
6167528Ssteve.reinhardt@amd.com        # individual value settings can be overridden but we still
6177528Ssteve.reinhardt@amd.com        # inherit late changes to non-overridden class values.
6182740SN/A        self._values = multidict(ancestor._values)
6192740SN/A        # clone SimObject-valued parameters
6202740SN/A        for key,val in ancestor._values.iteritems():
6217528Ssteve.reinhardt@amd.com            val = tryAsSimObjectOrVector(val)
6227528Ssteve.reinhardt@amd.com            if val is not None:
6237528Ssteve.reinhardt@amd.com                self._values[key] = val(_memo=memo_dict)
6247528Ssteve.reinhardt@amd.com
6252740SN/A        # clone port references.  no need to use a multidict here
6262740SN/A        # since we will be creating new references for all ports.
6273105Sstever@eecs.umich.edu        self._port_refs = {}
6283105Sstever@eecs.umich.edu        for key,val in ancestor._port_refs.iteritems():
6293105Sstever@eecs.umich.edu            self._port_refs[key] = val.clone(self, memo_dict)
6301692SN/A        # apply attribute assignments from keyword args, if any
6311692SN/A        for key,val in kwargs.iteritems():
6321692SN/A            setattr(self, key, val)
633679SN/A
6342740SN/A    # "Clone" the current instance by creating another instance of
6352740SN/A    # this instance's class, but that inherits its parameter values
6362740SN/A    # and port mappings from the current instance.  If we're in a
6372740SN/A    # "deep copy" recursive clone, check the _memo dict to see if
6382740SN/A    # we've already cloned this instance.
6391692SN/A    def __call__(self, **kwargs):
6402740SN/A        memo_dict = kwargs.get('_memo')
6412740SN/A        if memo_dict is None:
6422740SN/A            # no memo_dict: must be top-level clone operation.
6432740SN/A            # this is only allowed at the root of a hierarchy
6442740SN/A            if self._parent:
6452740SN/A                raise RuntimeError, "attempt to clone object %s " \
6462740SN/A                      "not at the root of a tree (parent = %s)" \
6472740SN/A                      % (self, self._parent)
6482740SN/A            # create a new dict and use that.
6492740SN/A            memo_dict = {}
6502740SN/A            kwargs['_memo'] = memo_dict
6512740SN/A        elif memo_dict.has_key(self):
6522740SN/A            # clone already done & memoized
6532740SN/A            return memo_dict[self]
6542740SN/A        return self.__class__(_ancestor = self, **kwargs)
6551343SN/A
6563105Sstever@eecs.umich.edu    def _get_port_ref(self, attr):
6573105Sstever@eecs.umich.edu        # Return reference that can be assigned to another port
6583105Sstever@eecs.umich.edu        # via __setattr__.  There is only ever one reference
6593105Sstever@eecs.umich.edu        # object per port, but we create them lazily here.
6603105Sstever@eecs.umich.edu        ref = self._port_refs.get(attr)
6613105Sstever@eecs.umich.edu        if not ref:
6623105Sstever@eecs.umich.edu            ref = self._ports[attr].makeRef(self)
6633105Sstever@eecs.umich.edu            self._port_refs[attr] = ref
6643105Sstever@eecs.umich.edu        return ref
6653105Sstever@eecs.umich.edu
6661692SN/A    def __getattr__(self, attr):
6672738SN/A        if self._ports.has_key(attr):
6683105Sstever@eecs.umich.edu            return self._get_port_ref(attr)
6692738SN/A
6701692SN/A        if self._values.has_key(attr):
6711692SN/A            return self._values[attr]
6721427SN/A
6737528Ssteve.reinhardt@amd.com        if self._children.has_key(attr):
6747528Ssteve.reinhardt@amd.com            return self._children[attr]
6757528Ssteve.reinhardt@amd.com
6767500Ssteve.reinhardt@amd.com        # If the attribute exists on the C++ object, transparently
6777500Ssteve.reinhardt@amd.com        # forward the reference there.  This is typically used for
6787500Ssteve.reinhardt@amd.com        # SWIG-wrapped methods such as init(), regStats(),
6797527Ssteve.reinhardt@amd.com        # regFormulas(), resetStats(), startup(), drain(), and
6807527Ssteve.reinhardt@amd.com        # resume().
6817500Ssteve.reinhardt@amd.com        if self._ccObject and hasattr(self._ccObject, attr):
6827500Ssteve.reinhardt@amd.com            return getattr(self._ccObject, attr)
6837500Ssteve.reinhardt@amd.com
6841692SN/A        raise AttributeError, "object '%s' has no attribute '%s'" \
6851692SN/A              % (self.__class__.__name__, attr)
6861427SN/A
6871692SN/A    # Set attribute (called on foo.attr = value when foo is an
6881692SN/A    # instance of class cls).
6891692SN/A    def __setattr__(self, attr, value):
6901692SN/A        # normal processing for private attributes
6911692SN/A        if attr.startswith('_'):
6921692SN/A            object.__setattr__(self, attr, value)
6931692SN/A            return
6941427SN/A
6952738SN/A        if self._ports.has_key(attr):
6962738SN/A            # set up port connection
6973105Sstever@eecs.umich.edu            self._get_port_ref(attr).connect(value)
6982738SN/A            return
6992738SN/A
7002740SN/A        if isSimObjectOrSequence(value) and self._instantiated:
7012740SN/A            raise RuntimeError, \
7022740SN/A                  "cannot set SimObject parameter '%s' after\n" \
7032740SN/A                  "    instance been cloned %s" % (attr, `self`)
7042740SN/A
7053105Sstever@eecs.umich.edu        param = self._params.get(attr)
7061692SN/A        if param:
7071310SN/A            try:
7081692SN/A                value = param.convert(value)
7091587SN/A            except Exception, e:
7101692SN/A                msg = "%s\nError setting param %s.%s to %s\n" % \
7111692SN/A                      (e, self.__class__.__name__, attr, value)
7121605SN/A                e.args = (msg, )
7131605SN/A                raise
7147528Ssteve.reinhardt@amd.com            self._values[attr] = value
7158321Ssteve.reinhardt@amd.com            # implicitly parent unparented objects assigned as params
7168321Ssteve.reinhardt@amd.com            if isSimObjectOrVector(value) and not value.has_parent():
7178321Ssteve.reinhardt@amd.com                self.add_child(attr, value)
7183105Sstever@eecs.umich.edu            return
7191310SN/A
7207528Ssteve.reinhardt@amd.com        # if RHS is a SimObject, it's an implicit child assignment
7213105Sstever@eecs.umich.edu        if isSimObjectOrSequence(value):
7227528Ssteve.reinhardt@amd.com            self.add_child(attr, value)
7233105Sstever@eecs.umich.edu            return
7241693SN/A
7253105Sstever@eecs.umich.edu        # no valid assignment... raise exception
7263105Sstever@eecs.umich.edu        raise AttributeError, "Class %s has no parameter %s" \
7273105Sstever@eecs.umich.edu              % (self.__class__.__name__, attr)
7281310SN/A
7291310SN/A
7301692SN/A    # this hack allows tacking a '[0]' onto parameters that may or may
7311692SN/A    # not be vectors, and always getting the first element (e.g. cpus)
7321692SN/A    def __getitem__(self, key):
7331692SN/A        if key == 0:
7341692SN/A            return self
7351692SN/A        raise TypeError, "Non-zero index '%s' to SimObject" % key
7361310SN/A
7377528Ssteve.reinhardt@amd.com    # Also implemented by SimObjectVector
7387528Ssteve.reinhardt@amd.com    def clear_parent(self, old_parent):
7397528Ssteve.reinhardt@amd.com        assert self._parent is old_parent
7407528Ssteve.reinhardt@amd.com        self._parent = None
7417528Ssteve.reinhardt@amd.com
7427528Ssteve.reinhardt@amd.com    # Also implemented by SimObjectVector
7437528Ssteve.reinhardt@amd.com    def set_parent(self, parent, name):
7447528Ssteve.reinhardt@amd.com        self._parent = parent
7457528Ssteve.reinhardt@amd.com        self._name = name
7467528Ssteve.reinhardt@amd.com
7477528Ssteve.reinhardt@amd.com    # Also implemented by SimObjectVector
7487528Ssteve.reinhardt@amd.com    def get_name(self):
7497528Ssteve.reinhardt@amd.com        return self._name
7507528Ssteve.reinhardt@amd.com
7518321Ssteve.reinhardt@amd.com    # Also implemented by SimObjectVector
7528321Ssteve.reinhardt@amd.com    def has_parent(self):
7538321Ssteve.reinhardt@amd.com        return self._parent is not None
7547528Ssteve.reinhardt@amd.com
7557742Sgblack@eecs.umich.edu    # clear out child with given name. This code is not likely to be exercised.
7567742Sgblack@eecs.umich.edu    # See comment in add_child.
7571693SN/A    def clear_child(self, name):
7581693SN/A        child = self._children[name]
7597528Ssteve.reinhardt@amd.com        child.clear_parent(self)
7601693SN/A        del self._children[name]
7611693SN/A
7627528Ssteve.reinhardt@amd.com    # Add a new child to this object.
7637528Ssteve.reinhardt@amd.com    def add_child(self, name, child):
7647528Ssteve.reinhardt@amd.com        child = coerceSimObjectOrVector(child)
7658321Ssteve.reinhardt@amd.com        if child.has_parent():
7668321Ssteve.reinhardt@amd.com            print "warning: add_child('%s'): child '%s' already has parent" % \
7678321Ssteve.reinhardt@amd.com                  (name, child.get_name())
7687528Ssteve.reinhardt@amd.com        if self._children.has_key(name):
7697742Sgblack@eecs.umich.edu            # This code path had an undiscovered bug that would make it fail
7707742Sgblack@eecs.umich.edu            # at runtime. It had been here for a long time and was only
7717742Sgblack@eecs.umich.edu            # exposed by a buggy script. Changes here will probably not be
7727742Sgblack@eecs.umich.edu            # exercised without specialized testing.
7737738Sgblack@eecs.umich.edu            self.clear_child(name)
7747528Ssteve.reinhardt@amd.com        child.set_parent(self, name)
7757528Ssteve.reinhardt@amd.com        self._children[name] = child
7761310SN/A
7777528Ssteve.reinhardt@amd.com    # Take SimObject-valued parameters that haven't been explicitly
7787528Ssteve.reinhardt@amd.com    # assigned as children and make them children of the object that
7797528Ssteve.reinhardt@amd.com    # they were assigned to as a parameter value.  This guarantees
7807528Ssteve.reinhardt@amd.com    # that when we instantiate all the parameter objects we're still
7817528Ssteve.reinhardt@amd.com    # inside the configuration hierarchy.
7827528Ssteve.reinhardt@amd.com    def adoptOrphanParams(self):
7837528Ssteve.reinhardt@amd.com        for key,val in self._values.iteritems():
7847528Ssteve.reinhardt@amd.com            if not isSimObjectVector(val) and isSimObjectSequence(val):
7857528Ssteve.reinhardt@amd.com                # need to convert raw SimObject sequences to
7868321Ssteve.reinhardt@amd.com                # SimObjectVector class so we can call has_parent()
7877528Ssteve.reinhardt@amd.com                val = SimObjectVector(val)
7887528Ssteve.reinhardt@amd.com                self._values[key] = val
7898321Ssteve.reinhardt@amd.com            if isSimObjectOrVector(val) and not val.has_parent():
7908321Ssteve.reinhardt@amd.com                print "warning: %s adopting orphan SimObject param '%s'" \
7918321Ssteve.reinhardt@amd.com                      % (self, key)
7927528Ssteve.reinhardt@amd.com                self.add_child(key, val)
7933105Sstever@eecs.umich.edu
7941692SN/A    def path(self):
7952740SN/A        if not self._parent:
7968321Ssteve.reinhardt@amd.com            return '<orphan %s>' % self.__class__
7971692SN/A        ppath = self._parent.path()
7981692SN/A        if ppath == 'root':
7991692SN/A            return self._name
8001692SN/A        return ppath + "." + self._name
8011310SN/A
8021692SN/A    def __str__(self):
8031692SN/A        return self.path()
8041310SN/A
8051692SN/A    def ini_str(self):
8061692SN/A        return self.path()
8071310SN/A
8081692SN/A    def find_any(self, ptype):
8091692SN/A        if isinstance(self, ptype):
8101692SN/A            return self, True
8111310SN/A
8121692SN/A        found_obj = None
8131692SN/A        for child in self._children.itervalues():
8141692SN/A            if isinstance(child, ptype):
8151692SN/A                if found_obj != None and child != found_obj:
8161692SN/A                    raise AttributeError, \
8171692SN/A                          'parent.any matched more than one: %s %s' % \
8181814SN/A                          (found_obj.path, child.path)
8191692SN/A                found_obj = child
8201692SN/A        # search param space
8211692SN/A        for pname,pdesc in self._params.iteritems():
8221692SN/A            if issubclass(pdesc.ptype, ptype):
8231692SN/A                match_obj = self._values[pname]
8241692SN/A                if found_obj != None and found_obj != match_obj:
8251692SN/A                    raise AttributeError, \
8265952Ssaidi@eecs.umich.edu                          'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path)
8271692SN/A                found_obj = match_obj
8281692SN/A        return found_obj, found_obj != None
8291692SN/A
8308459SAli.Saidi@ARM.com    def find_all(self, ptype):
8318459SAli.Saidi@ARM.com        all = {}
8328459SAli.Saidi@ARM.com        # search children
8338459SAli.Saidi@ARM.com        for child in self._children.itervalues():
8348459SAli.Saidi@ARM.com            if isinstance(child, ptype) and not isproxy(child) and \
8358459SAli.Saidi@ARM.com               not isNullPointer(child):
8368459SAli.Saidi@ARM.com                all[child] = True
8378459SAli.Saidi@ARM.com        # search param space
8388459SAli.Saidi@ARM.com        for pname,pdesc in self._params.iteritems():
8398459SAli.Saidi@ARM.com            if issubclass(pdesc.ptype, ptype):
8408459SAli.Saidi@ARM.com                match_obj = self._values[pname]
8418459SAli.Saidi@ARM.com                if not isproxy(match_obj) and not isNullPointer(match_obj):
8428459SAli.Saidi@ARM.com                    all[match_obj] = True
8438459SAli.Saidi@ARM.com        return all.keys(), True
8448459SAli.Saidi@ARM.com
8451815SN/A    def unproxy(self, base):
8461815SN/A        return self
8471815SN/A
8487527Ssteve.reinhardt@amd.com    def unproxyParams(self):
8493105Sstever@eecs.umich.edu        for param in self._params.iterkeys():
8503105Sstever@eecs.umich.edu            value = self._values.get(param)
8516654Snate@binkert.org            if value != None and isproxy(value):
8523105Sstever@eecs.umich.edu                try:
8533105Sstever@eecs.umich.edu                    value = value.unproxy(self)
8543105Sstever@eecs.umich.edu                except:
8553105Sstever@eecs.umich.edu                    print "Error in unproxying param '%s' of %s" % \
8563105Sstever@eecs.umich.edu                          (param, self.path())
8573105Sstever@eecs.umich.edu                    raise
8583105Sstever@eecs.umich.edu                setattr(self, param, value)
8593105Sstever@eecs.umich.edu
8603107Sstever@eecs.umich.edu        # Unproxy ports in sorted order so that 'append' operations on
8613107Sstever@eecs.umich.edu        # vector ports are done in a deterministic fashion.
8623107Sstever@eecs.umich.edu        port_names = self._ports.keys()
8633107Sstever@eecs.umich.edu        port_names.sort()
8643107Sstever@eecs.umich.edu        for port_name in port_names:
8653105Sstever@eecs.umich.edu            port = self._port_refs.get(port_name)
8663105Sstever@eecs.umich.edu            if port != None:
8673105Sstever@eecs.umich.edu                port.unproxy(self)
8683105Sstever@eecs.umich.edu
8695037Smilesck@eecs.umich.edu    def print_ini(self, ini_file):
8705543Ssaidi@eecs.umich.edu        print >>ini_file, '[' + self.path() + ']'       # .ini section header
8711692SN/A
8722738SN/A        instanceDict[self.path()] = self
8732738SN/A
8744081Sbinkertn@umich.edu        if hasattr(self, 'type'):
8755037Smilesck@eecs.umich.edu            print >>ini_file, 'type=%s' % self.type
8761692SN/A
8771692SN/A        child_names = self._children.keys()
8781692SN/A        child_names.sort()
8794081Sbinkertn@umich.edu        if len(child_names):
8807528Ssteve.reinhardt@amd.com            print >>ini_file, 'children=%s' % \
8817528Ssteve.reinhardt@amd.com                  ' '.join(self._children[n].get_name() for n in child_names)
8821692SN/A
8831692SN/A        param_names = self._params.keys()
8841692SN/A        param_names.sort()
8851692SN/A        for param in param_names:
8863105Sstever@eecs.umich.edu            value = self._values.get(param)
8871692SN/A            if value != None:
8885037Smilesck@eecs.umich.edu                print >>ini_file, '%s=%s' % (param,
8895037Smilesck@eecs.umich.edu                                             self._values[param].ini_str())
8901692SN/A
8913103Sstever@eecs.umich.edu        port_names = self._ports.keys()
8923103Sstever@eecs.umich.edu        port_names.sort()
8933103Sstever@eecs.umich.edu        for port_name in port_names:
8943105Sstever@eecs.umich.edu            port = self._port_refs.get(port_name, None)
8953105Sstever@eecs.umich.edu            if port != None:
8965037Smilesck@eecs.umich.edu                print >>ini_file, '%s=%s' % (port_name, port.ini_str())
8973103Sstever@eecs.umich.edu
8985543Ssaidi@eecs.umich.edu        print >>ini_file        # blank line between objects
8991692SN/A
9004762Snate@binkert.org    def getCCParams(self):
9014762Snate@binkert.org        if self._ccParams:
9024762Snate@binkert.org            return self._ccParams
9034762Snate@binkert.org
9047677Snate@binkert.org        cc_params_struct = getattr(m5.internal.params, '%sParams' % self.type)
9054762Snate@binkert.org        cc_params = cc_params_struct()
9065488Snate@binkert.org        cc_params.pyobj = self
9074762Snate@binkert.org        cc_params.name = str(self)
9084762Snate@binkert.org
9094762Snate@binkert.org        param_names = self._params.keys()
9104762Snate@binkert.org        param_names.sort()
9114762Snate@binkert.org        for param in param_names:
9124762Snate@binkert.org            value = self._values.get(param)
9134762Snate@binkert.org            if value is None:
9146654Snate@binkert.org                fatal("%s.%s without default or user set value",
9156654Snate@binkert.org                      self.path(), param)
9164762Snate@binkert.org
9174762Snate@binkert.org            value = value.getValue()
9184762Snate@binkert.org            if isinstance(self._params[param], VectorParamDesc):
9194762Snate@binkert.org                assert isinstance(value, list)
9204762Snate@binkert.org                vec = getattr(cc_params, param)
9214762Snate@binkert.org                assert not len(vec)
9224762Snate@binkert.org                for v in value:
9234762Snate@binkert.org                    vec.append(v)
9244762Snate@binkert.org            else:
9254762Snate@binkert.org                setattr(cc_params, param, value)
9264762Snate@binkert.org
9274762Snate@binkert.org        port_names = self._ports.keys()
9284762Snate@binkert.org        port_names.sort()
9294762Snate@binkert.org        for port_name in port_names:
9304762Snate@binkert.org            port = self._port_refs.get(port_name, None)
9314762Snate@binkert.org            if port != None:
9324762Snate@binkert.org                setattr(cc_params, port_name, port)
9334762Snate@binkert.org        self._ccParams = cc_params
9344762Snate@binkert.org        return self._ccParams
9352738SN/A
9362740SN/A    # Get C++ object corresponding to this object, calling C++ if
9372740SN/A    # necessary to construct it.  Does *not* recursively create
9382740SN/A    # children.
9392740SN/A    def getCCObject(self):
9402740SN/A        if not self._ccObject:
9417526Ssteve.reinhardt@amd.com            # Make sure this object is in the configuration hierarchy
9427526Ssteve.reinhardt@amd.com            if not self._parent and not isRoot(self):
9437526Ssteve.reinhardt@amd.com                raise RuntimeError, "Attempt to instantiate orphan node"
9447526Ssteve.reinhardt@amd.com            # Cycles in the configuration hierarchy are not supported. This
9455244Sgblack@eecs.umich.edu            # will catch the resulting recursion and stop.
9465244Sgblack@eecs.umich.edu            self._ccObject = -1
9475244Sgblack@eecs.umich.edu            params = self.getCCParams()
9484762Snate@binkert.org            self._ccObject = params.create()
9492740SN/A        elif self._ccObject == -1:
9507526Ssteve.reinhardt@amd.com            raise RuntimeError, "%s: Cycle found in configuration hierarchy." \
9512740SN/A                  % self.path()
9522740SN/A        return self._ccObject
9532740SN/A
9547527Ssteve.reinhardt@amd.com    def descendants(self):
9557527Ssteve.reinhardt@amd.com        yield self
9567527Ssteve.reinhardt@amd.com        for child in self._children.itervalues():
9577527Ssteve.reinhardt@amd.com            for obj in child.descendants():
9587527Ssteve.reinhardt@amd.com                yield obj
9597527Ssteve.reinhardt@amd.com
9607527Ssteve.reinhardt@amd.com    # Call C++ to create C++ object corresponding to this object
9614762Snate@binkert.org    def createCCObject(self):
9624762Snate@binkert.org        self.getCCParams()
9634762Snate@binkert.org        self.getCCObject() # force creation
9644762Snate@binkert.org
9654762Snate@binkert.org    def getValue(self):
9664762Snate@binkert.org        return self.getCCObject()
9674762Snate@binkert.org
9682738SN/A    # Create C++ port connections corresponding to the connections in
9697527Ssteve.reinhardt@amd.com    # _port_refs
9702738SN/A    def connectPorts(self):
9713105Sstever@eecs.umich.edu        for portRef in self._port_refs.itervalues():
9723105Sstever@eecs.umich.edu            portRef.ccConnect()
9732797SN/A
9744553Sbinkertn@umich.edu    def getMemoryMode(self):
9754553Sbinkertn@umich.edu        if not isinstance(self, m5.objects.System):
9764553Sbinkertn@umich.edu            return None
9774553Sbinkertn@umich.edu
9784859Snate@binkert.org        return self._ccObject.getMemoryMode()
9794553Sbinkertn@umich.edu
9802797SN/A    def changeTiming(self, mode):
9813202Shsul@eecs.umich.edu        if isinstance(self, m5.objects.System):
9823202Shsul@eecs.umich.edu            # i don't know if there's a better way to do this - calling
9833202Shsul@eecs.umich.edu            # setMemoryMode directly from self._ccObject results in calling
9843202Shsul@eecs.umich.edu            # SimObject::setMemoryMode, not the System::setMemoryMode
9854859Snate@binkert.org            self._ccObject.setMemoryMode(mode)
9862797SN/A
9872797SN/A    def takeOverFrom(self, old_cpu):
9884859Snate@binkert.org        self._ccObject.takeOverFrom(old_cpu._ccObject)
9892797SN/A
9901692SN/A    # generate output file for 'dot' to display as a pretty graph.
9911692SN/A    # this code is currently broken.
9921342SN/A    def outputDot(self, dot):
9931342SN/A        label = "{%s|" % self.path
9941342SN/A        if isSimObject(self.realtype):
9951342SN/A            label +=  '%s|' % self.type
9961342SN/A
9971342SN/A        if self.children:
9981342SN/A            # instantiate children in same order they were added for
9991342SN/A            # backward compatibility (else we can end up with cpu1
10001342SN/A            # before cpu0).
10011342SN/A            for c in self.children:
10021342SN/A                dot.add_edge(pydot.Edge(self.path,c.path, style="bold"))
10031342SN/A
10041342SN/A        simobjs = []
10051342SN/A        for param in self.params:
10061342SN/A            try:
10071342SN/A                if param.value is None:
10081342SN/A                    raise AttributeError, 'Parameter with no value'
10091342SN/A
10101692SN/A                value = param.value
10111342SN/A                string = param.string(value)
10121587SN/A            except Exception, e:
10131605SN/A                msg = 'exception in %s:%s\n%s' % (self.name, param.name, e)
10141605SN/A                e.args = (msg, )
10151342SN/A                raise
10161605SN/A
10171692SN/A            if isSimObject(param.ptype) and string != "Null":
10181342SN/A                simobjs.append(string)
10191342SN/A            else:
10201342SN/A                label += '%s = %s\\n' % (param.name, string)
10211342SN/A
10221342SN/A        for so in simobjs:
10231342SN/A            label += "|<%s> %s" % (so, so)
10241587SN/A            dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so,
10251587SN/A                                    tailport="w"))
10261342SN/A        label += '}'
10271342SN/A        dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label))
10281342SN/A
10291342SN/A        # recursively dump out children
10301342SN/A        for c in self.children:
10311342SN/A            c.outputDot(dot)
10321342SN/A
10333101Sstever@eecs.umich.edu# Function to provide to C++ so it can look up instances based on paths
10343101Sstever@eecs.umich.edudef resolveSimObject(name):
10353101Sstever@eecs.umich.edu    obj = instanceDict[name]
10363101Sstever@eecs.umich.edu    return obj.getCCObject()
1037679SN/A
10386654Snate@binkert.orgdef isSimObject(value):
10396654Snate@binkert.org    return isinstance(value, SimObject)
10406654Snate@binkert.org
10416654Snate@binkert.orgdef isSimObjectClass(value):
10426654Snate@binkert.org    return issubclass(value, SimObject)
10436654Snate@binkert.org
10447528Ssteve.reinhardt@amd.comdef isSimObjectVector(value):
10457528Ssteve.reinhardt@amd.com    return isinstance(value, SimObjectVector)
10467528Ssteve.reinhardt@amd.com
10476654Snate@binkert.orgdef isSimObjectSequence(value):
10486654Snate@binkert.org    if not isinstance(value, (list, tuple)) or len(value) == 0:
10496654Snate@binkert.org        return False
10506654Snate@binkert.org
10516654Snate@binkert.org    for val in value:
10526654Snate@binkert.org        if not isNullPointer(val) and not isSimObject(val):
10536654Snate@binkert.org            return False
10546654Snate@binkert.org
10556654Snate@binkert.org    return True
10566654Snate@binkert.org
10576654Snate@binkert.orgdef isSimObjectOrSequence(value):
10586654Snate@binkert.org    return isSimObject(value) or isSimObjectSequence(value)
10596654Snate@binkert.org
10607526Ssteve.reinhardt@amd.comdef isRoot(obj):
10617526Ssteve.reinhardt@amd.com    from m5.objects import Root
10627526Ssteve.reinhardt@amd.com    return obj and obj is Root.getInstance()
10637526Ssteve.reinhardt@amd.com
10647528Ssteve.reinhardt@amd.comdef isSimObjectOrVector(value):
10657528Ssteve.reinhardt@amd.com    return isSimObject(value) or isSimObjectVector(value)
10667528Ssteve.reinhardt@amd.com
10677528Ssteve.reinhardt@amd.comdef tryAsSimObjectOrVector(value):
10687528Ssteve.reinhardt@amd.com    if isSimObjectOrVector(value):
10697528Ssteve.reinhardt@amd.com        return value
10707528Ssteve.reinhardt@amd.com    if isSimObjectSequence(value):
10717528Ssteve.reinhardt@amd.com        return SimObjectVector(value)
10727528Ssteve.reinhardt@amd.com    return None
10737528Ssteve.reinhardt@amd.com
10747528Ssteve.reinhardt@amd.comdef coerceSimObjectOrVector(value):
10757528Ssteve.reinhardt@amd.com    value = tryAsSimObjectOrVector(value)
10767528Ssteve.reinhardt@amd.com    if value is None:
10777528Ssteve.reinhardt@amd.com        raise TypeError, "SimObject or SimObjectVector expected"
10787528Ssteve.reinhardt@amd.com    return value
10797528Ssteve.reinhardt@amd.com
10806654Snate@binkert.orgbaseClasses = allClasses.copy()
10816654Snate@binkert.orgbaseInstances = instanceDict.copy()
10826654Snate@binkert.org
10836654Snate@binkert.orgdef clear():
10846654Snate@binkert.org    global allClasses, instanceDict
10856654Snate@binkert.org
10866654Snate@binkert.org    allClasses = baseClasses.copy()
10876654Snate@binkert.org    instanceDict = baseInstances.copy()
10886654Snate@binkert.org
10891528SN/A# __all__ defines the list of symbols that get exported when
10901528SN/A# 'from config import *' is invoked.  Try to keep this reasonably
10911528SN/A# short to avoid polluting other namespaces.
10924762Snate@binkert.org__all__ = [ 'SimObject' ]
1093