SimObject.py revision 10267
18840Sandreas.hansson@arm.com# Copyright (c) 2012 ARM Limited
28840Sandreas.hansson@arm.com# All rights reserved.
38840Sandreas.hansson@arm.com#
48840Sandreas.hansson@arm.com# The license below extends only to copyright in the software and shall
58840Sandreas.hansson@arm.com# not be construed as granting a license to any other intellectual
68840Sandreas.hansson@arm.com# property including but not limited to intellectual property relating
78840Sandreas.hansson@arm.com# to a hardware implementation of the functionality of the software
88840Sandreas.hansson@arm.com# licensed hereunder.  You may use the software subject to the license
98840Sandreas.hansson@arm.com# terms below provided that you ensure that this notice is replicated
108840Sandreas.hansson@arm.com# unmodified and in its entirety in all distributions of the software,
118840Sandreas.hansson@arm.com# modified or unmodified, in source code or in binary form.
128840Sandreas.hansson@arm.com#
132740SN/A# Copyright (c) 2004-2006 The Regents of The University of Michigan
149983Sstever@gmail.com# Copyright (c) 2010-20013 Advanced Micro Devices, Inc.
159983Sstever@gmail.com# Copyright (c) 2013 Mark D. Hill and David A. Wood
161046SN/A# All rights reserved.
171046SN/A#
181046SN/A# Redistribution and use in source and binary forms, with or without
191046SN/A# modification, are permitted provided that the following conditions are
201046SN/A# met: redistributions of source code must retain the above copyright
211046SN/A# notice, this list of conditions and the following disclaimer;
221046SN/A# redistributions in binary form must reproduce the above copyright
231046SN/A# notice, this list of conditions and the following disclaimer in the
241046SN/A# documentation and/or other materials provided with the distribution;
251046SN/A# neither the name of the copyright holders nor the names of its
261046SN/A# contributors may be used to endorse or promote products derived from
271046SN/A# this software without specific prior written permission.
281046SN/A#
291046SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
301046SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
311046SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
321046SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
331046SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
341046SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
351046SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
361046SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
371046SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
381046SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
391046SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
402665SN/A#
412665SN/A# Authors: Steve Reinhardt
422665SN/A#          Nathan Binkert
438840Sandreas.hansson@arm.com#          Andreas Hansson
441046SN/A
455766Snate@binkert.orgimport sys
468331Ssteve.reinhardt@amd.comfrom types import FunctionType, MethodType, ModuleType
471438SN/A
484762Snate@binkert.orgimport m5
496654Snate@binkert.orgfrom m5.util import *
503102Sstever@eecs.umich.edu
513102Sstever@eecs.umich.edu# Have to import params up top since Param is referenced on initial
523102Sstever@eecs.umich.edu# load (when SimObject class references Param to create a class
533102Sstever@eecs.umich.edu# variable, the 'name' param)...
546654Snate@binkert.orgfrom m5.params import *
553102Sstever@eecs.umich.edu# There are a few things we need that aren't in params.__all__ since
563102Sstever@eecs.umich.edu# normal users don't need them
577528Ssteve.reinhardt@amd.comfrom m5.params import ParamDesc, VectorParamDesc, \
588839Sandreas.hansson@arm.com     isNullPointer, SimObjectVector, Port
593102Sstever@eecs.umich.edu
606654Snate@binkert.orgfrom m5.proxy import *
616654Snate@binkert.orgfrom m5.proxy import isproxy
62679SN/A
63679SN/A#####################################################################
64679SN/A#
65679SN/A# M5 Python Configuration Utility
66679SN/A#
67679SN/A# The basic idea is to write simple Python programs that build Python
681692SN/A# objects corresponding to M5 SimObjects for the desired simulation
69679SN/A# configuration.  For now, the Python emits a .ini file that can be
70679SN/A# parsed by M5.  In the future, some tighter integration between M5
71679SN/A# and the Python interpreter may allow bypassing the .ini file.
72679SN/A#
73679SN/A# Each SimObject class in M5 is represented by a Python class with the
74679SN/A# same name.  The Python inheritance tree mirrors the M5 C++ tree
75679SN/A# (e.g., SimpleCPU derives from BaseCPU in both cases, and all
76679SN/A# SimObjects inherit from a single SimObject base class).  To specify
77679SN/A# an instance of an M5 SimObject in a configuration, the user simply
78679SN/A# instantiates the corresponding Python object.  The parameters for
79679SN/A# that SimObject are given by assigning to attributes of the Python
80679SN/A# object, either using keyword assignment in the constructor or in
81679SN/A# separate assignment statements.  For example:
82679SN/A#
831692SN/A# cache = BaseCache(size='64KB')
84679SN/A# cache.hit_latency = 3
85679SN/A# cache.assoc = 8
86679SN/A#
87679SN/A# The magic lies in the mapping of the Python attributes for SimObject
88679SN/A# classes to the actual SimObject parameter specifications.  This
89679SN/A# allows parameter validity checking in the Python code.  Continuing
90679SN/A# the example above, the statements "cache.blurfl=3" or
91679SN/A# "cache.assoc='hello'" would both result in runtime errors in Python,
92679SN/A# since the BaseCache object has no 'blurfl' parameter and the 'assoc'
93679SN/A# parameter requires an integer, respectively.  This magic is done
94679SN/A# primarily by overriding the special __setattr__ method that controls
95679SN/A# assignment to object attributes.
96679SN/A#
97679SN/A# Once a set of Python objects have been instantiated in a hierarchy,
98679SN/A# calling 'instantiate(obj)' (where obj is the root of the hierarchy)
992740SN/A# will generate a .ini file.
100679SN/A#
101679SN/A#####################################################################
102679SN/A
1034762Snate@binkert.org# list of all SimObject classes
1044762Snate@binkert.orgallClasses = {}
1054762Snate@binkert.org
1062738SN/A# dict to look up SimObjects based on path
1072738SN/AinstanceDict = {}
1082738SN/A
1099338SAndreas.Sandberg@arm.com# Did any of the SimObjects lack a header file?
1109338SAndreas.Sandberg@arm.comnoCxxHeader = False
1119338SAndreas.Sandberg@arm.com
1127673Snate@binkert.orgdef public_value(key, value):
1137673Snate@binkert.org    return key.startswith('_') or \
1148331Ssteve.reinhardt@amd.com               isinstance(value, (FunctionType, MethodType, ModuleType,
1158331Ssteve.reinhardt@amd.com                                  classmethod, type))
1167673Snate@binkert.org
1172740SN/A# The metaclass for SimObject.  This class controls how new classes
1182740SN/A# that derive from SimObject are instantiated, and provides inherited
1192740SN/A# class behavior (just like a class controls how instances of that
1202740SN/A# class are instantiated, and provides inherited instance behavior).
1211692SN/Aclass MetaSimObject(type):
1221427SN/A    # Attributes that can be set only at initialization time
1237493Ssteve.reinhardt@amd.com    init_keywords = { 'abstract' : bool,
1247493Ssteve.reinhardt@amd.com                      'cxx_class' : str,
1257493Ssteve.reinhardt@amd.com                      'cxx_type' : str,
1269338SAndreas.Sandberg@arm.com                      'cxx_header' : str,
1279342SAndreas.Sandberg@arm.com                      'type' : str,
1289342SAndreas.Sandberg@arm.com                      'cxx_bases' : list }
1291427SN/A    # Attributes that can be set any time
1307493Ssteve.reinhardt@amd.com    keywords = { 'check' : FunctionType }
131679SN/A
132679SN/A    # __new__ is called before __init__, and is where the statements
133679SN/A    # in the body of the class definition get loaded into the class's
1342740SN/A    # __dict__.  We intercept this to filter out parameter & port assignments
135679SN/A    # and only allow "private" attributes to be passed to the base
136679SN/A    # __new__ (starting with underscore).
1371310SN/A    def __new__(mcls, name, bases, dict):
1386654Snate@binkert.org        assert name not in allClasses, "SimObject %s already present" % name
1394762Snate@binkert.org
1402740SN/A        # Copy "private" attributes, functions, and classes to the
1412740SN/A        # official dict.  Everything else goes in _init_dict to be
1422740SN/A        # filtered in __init__.
1432740SN/A        cls_dict = {}
1442740SN/A        value_dict = {}
1452740SN/A        for key,val in dict.items():
1467673Snate@binkert.org            if public_value(key, val):
1472740SN/A                cls_dict[key] = val
1482740SN/A            else:
1492740SN/A                # must be a param/port setting
1502740SN/A                value_dict[key] = val
1514762Snate@binkert.org        if 'abstract' not in value_dict:
1524762Snate@binkert.org            value_dict['abstract'] = False
1539342SAndreas.Sandberg@arm.com        if 'cxx_bases' not in value_dict:
1549342SAndreas.Sandberg@arm.com            value_dict['cxx_bases'] = []
1552740SN/A        cls_dict['_value_dict'] = value_dict
1564762Snate@binkert.org        cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict)
1574762Snate@binkert.org        if 'type' in value_dict:
1584762Snate@binkert.org            allClasses[name] = cls
1594762Snate@binkert.org        return cls
160679SN/A
1612711SN/A    # subclass initialization
162679SN/A    def __init__(cls, name, bases, dict):
1632711SN/A        # calls type.__init__()... I think that's a no-op, but leave
1642711SN/A        # it here just in case it's not.
1651692SN/A        super(MetaSimObject, cls).__init__(name, bases, dict)
1661310SN/A
1671427SN/A        # initialize required attributes
1682740SN/A
1692740SN/A        # class-only attributes
1702740SN/A        cls._params = multidict() # param descriptions
1712740SN/A        cls._ports = multidict()  # port descriptions
1722740SN/A
1732740SN/A        # class or instance attributes
1742740SN/A        cls._values = multidict()   # param values
17510267SGeoffrey.Blake@arm.com        cls._hr_values = multidict() # human readable param values
1767528Ssteve.reinhardt@amd.com        cls._children = multidict() # SimObject children
1773105Sstever@eecs.umich.edu        cls._port_refs = multidict() # port ref objects
1782740SN/A        cls._instantiated = False # really instantiated, cloned, or subclassed
1791310SN/A
1809100SBrad.Beckmann@amd.com        # We don't support multiple inheritance of sim objects.  If you want
1819100SBrad.Beckmann@amd.com        # to, you must fix multidict to deal with it properly. Non sim-objects
1829100SBrad.Beckmann@amd.com        # are ok, though
1839100SBrad.Beckmann@amd.com        bTotal = 0
1849100SBrad.Beckmann@amd.com        for c in bases:
1859100SBrad.Beckmann@amd.com            if isinstance(c, MetaSimObject):
1869100SBrad.Beckmann@amd.com                bTotal += 1
1879100SBrad.Beckmann@amd.com            if bTotal > 1:
1889100SBrad.Beckmann@amd.com                raise TypeError, "SimObjects do not support multiple inheritance"
1891692SN/A
1901692SN/A        base = bases[0]
1911692SN/A
1922740SN/A        # Set up general inheritance via multidicts.  A subclass will
1932740SN/A        # inherit all its settings from the base class.  The only time
1942740SN/A        # the following is not true is when we define the SimObject
1952740SN/A        # class itself (in which case the multidicts have no parent).
1961692SN/A        if isinstance(base, MetaSimObject):
1975610Snate@binkert.org            cls._base = base
1981692SN/A            cls._params.parent = base._params
1992740SN/A            cls._ports.parent = base._ports
2001692SN/A            cls._values.parent = base._values
20110267SGeoffrey.Blake@arm.com            cls._hr_values.parent = base._hr_values
2027528Ssteve.reinhardt@amd.com            cls._children.parent = base._children
2033105Sstever@eecs.umich.edu            cls._port_refs.parent = base._port_refs
2042740SN/A            # mark base as having been subclassed
2052712SN/A            base._instantiated = True
2065610Snate@binkert.org        else:
2075610Snate@binkert.org            cls._base = None
2081692SN/A
2094762Snate@binkert.org        # default keyword values
2104762Snate@binkert.org        if 'type' in cls._value_dict:
2114762Snate@binkert.org            if 'cxx_class' not in cls._value_dict:
2125610Snate@binkert.org                cls._value_dict['cxx_class'] = cls._value_dict['type']
2134762Snate@binkert.org
2145610Snate@binkert.org            cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class']
2154859Snate@binkert.org
2169338SAndreas.Sandberg@arm.com            if 'cxx_header' not in cls._value_dict:
2179338SAndreas.Sandberg@arm.com                global noCxxHeader
2189338SAndreas.Sandberg@arm.com                noCxxHeader = True
2199528Ssascha.bischoff@arm.com                warn("No header file specified for SimObject: %s", name)
2209338SAndreas.Sandberg@arm.com
2218597Ssteve.reinhardt@amd.com        # Export methods are automatically inherited via C++, so we
2228597Ssteve.reinhardt@amd.com        # don't want the method declarations to get inherited on the
2238597Ssteve.reinhardt@amd.com        # python side (and thus end up getting repeated in the wrapped
2248597Ssteve.reinhardt@amd.com        # versions of derived classes).  The code below basicallly
2258597Ssteve.reinhardt@amd.com        # suppresses inheritance by substituting in the base (null)
2268597Ssteve.reinhardt@amd.com        # versions of these methods unless a different version is
2278597Ssteve.reinhardt@amd.com        # explicitly supplied.
2288597Ssteve.reinhardt@amd.com        for method_name in ('export_methods', 'export_method_cxx_predecls',
2298597Ssteve.reinhardt@amd.com                            'export_method_swig_predecls'):
2308597Ssteve.reinhardt@amd.com            if method_name not in cls.__dict__:
2318597Ssteve.reinhardt@amd.com                base_method = getattr(MetaSimObject, method_name)
2328597Ssteve.reinhardt@amd.com                m = MethodType(base_method, cls, MetaSimObject)
2338597Ssteve.reinhardt@amd.com                setattr(cls, method_name, m)
2348597Ssteve.reinhardt@amd.com
2352740SN/A        # Now process the _value_dict items.  They could be defining
2362740SN/A        # new (or overriding existing) parameters or ports, setting
2372740SN/A        # class keywords (e.g., 'abstract'), or setting parameter
2382740SN/A        # values or port bindings.  The first 3 can only be set when
2392740SN/A        # the class is defined, so we handle them here.  The others
2402740SN/A        # can be set later too, so just emulate that by calling
2412740SN/A        # setattr().
2422740SN/A        for key,val in cls._value_dict.items():
2431527SN/A            # param descriptions
2442740SN/A            if isinstance(val, ParamDesc):
2451585SN/A                cls._new_param(key, val)
2461427SN/A
2472738SN/A            # port objects
2482738SN/A            elif isinstance(val, Port):
2493105Sstever@eecs.umich.edu                cls._new_port(key, val)
2502738SN/A
2511427SN/A            # init-time-only keywords
2521427SN/A            elif cls.init_keywords.has_key(key):
2531427SN/A                cls._set_keyword(key, val, cls.init_keywords[key])
2541427SN/A
2551427SN/A            # default: use normal path (ends up in __setattr__)
2561427SN/A            else:
2571427SN/A                setattr(cls, key, val)
2581427SN/A
2591427SN/A    def _set_keyword(cls, keyword, val, kwtype):
2601427SN/A        if not isinstance(val, kwtype):
2611427SN/A            raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
2621427SN/A                  (keyword, type(val), kwtype)
2637493Ssteve.reinhardt@amd.com        if isinstance(val, FunctionType):
2641427SN/A            val = classmethod(val)
2651427SN/A        type.__setattr__(cls, keyword, val)
2661427SN/A
2673100SN/A    def _new_param(cls, name, pdesc):
2683100SN/A        # each param desc should be uniquely assigned to one variable
2693100SN/A        assert(not hasattr(pdesc, 'name'))
2703100SN/A        pdesc.name = name
2713100SN/A        cls._params[name] = pdesc
2723100SN/A        if hasattr(pdesc, 'default'):
2733105Sstever@eecs.umich.edu            cls._set_param(name, pdesc.default, pdesc)
2743105Sstever@eecs.umich.edu
2753105Sstever@eecs.umich.edu    def _set_param(cls, name, value, param):
2763105Sstever@eecs.umich.edu        assert(param.name == name)
2773105Sstever@eecs.umich.edu        try:
27810267SGeoffrey.Blake@arm.com            hr_value = value
2798321Ssteve.reinhardt@amd.com            value = param.convert(value)
2803105Sstever@eecs.umich.edu        except Exception, e:
2813105Sstever@eecs.umich.edu            msg = "%s\nError setting param %s.%s to %s\n" % \
2823105Sstever@eecs.umich.edu                  (e, cls.__name__, name, value)
2833105Sstever@eecs.umich.edu            e.args = (msg, )
2843105Sstever@eecs.umich.edu            raise
2858321Ssteve.reinhardt@amd.com        cls._values[name] = value
2868321Ssteve.reinhardt@amd.com        # if param value is a SimObject, make it a child too, so that
2878321Ssteve.reinhardt@amd.com        # it gets cloned properly when the class is instantiated
2888321Ssteve.reinhardt@amd.com        if isSimObjectOrVector(value) and not value.has_parent():
2898321Ssteve.reinhardt@amd.com            cls._add_cls_child(name, value)
29010267SGeoffrey.Blake@arm.com        # update human-readable values of the param if it has a literal
29110267SGeoffrey.Blake@arm.com        # value and is not an object or proxy.
29210267SGeoffrey.Blake@arm.com        if not (isSimObjectOrVector(value) or\
29310267SGeoffrey.Blake@arm.com                isinstance(value, m5.proxy.BaseProxy)):
29410267SGeoffrey.Blake@arm.com            cls._hr_values[name] = hr_value
2958321Ssteve.reinhardt@amd.com
2968321Ssteve.reinhardt@amd.com    def _add_cls_child(cls, name, child):
2978321Ssteve.reinhardt@amd.com        # It's a little funky to have a class as a parent, but these
2988321Ssteve.reinhardt@amd.com        # objects should never be instantiated (only cloned, which
2998321Ssteve.reinhardt@amd.com        # clears the parent pointer), and this makes it clear that the
3008321Ssteve.reinhardt@amd.com        # object is not an orphan and can provide better error
3018321Ssteve.reinhardt@amd.com        # messages.
3028321Ssteve.reinhardt@amd.com        child.set_parent(cls, name)
3038321Ssteve.reinhardt@amd.com        cls._children[name] = child
3043105Sstever@eecs.umich.edu
3053105Sstever@eecs.umich.edu    def _new_port(cls, name, port):
3063105Sstever@eecs.umich.edu        # each port should be uniquely assigned to one variable
3073105Sstever@eecs.umich.edu        assert(not hasattr(port, 'name'))
3083105Sstever@eecs.umich.edu        port.name = name
3093105Sstever@eecs.umich.edu        cls._ports[name] = port
3103105Sstever@eecs.umich.edu
3113105Sstever@eecs.umich.edu    # same as _get_port_ref, effectively, but for classes
3123105Sstever@eecs.umich.edu    def _cls_get_port_ref(cls, attr):
3133105Sstever@eecs.umich.edu        # Return reference that can be assigned to another port
3143105Sstever@eecs.umich.edu        # via __setattr__.  There is only ever one reference
3153105Sstever@eecs.umich.edu        # object per port, but we create them lazily here.
3163105Sstever@eecs.umich.edu        ref = cls._port_refs.get(attr)
3173105Sstever@eecs.umich.edu        if not ref:
3183105Sstever@eecs.umich.edu            ref = cls._ports[attr].makeRef(cls)
3193105Sstever@eecs.umich.edu            cls._port_refs[attr] = ref
3203105Sstever@eecs.umich.edu        return ref
3211585SN/A
3221310SN/A    # Set attribute (called on foo.attr = value when foo is an
3231310SN/A    # instance of class cls).
3241310SN/A    def __setattr__(cls, attr, value):
3251310SN/A        # normal processing for private attributes
3267673Snate@binkert.org        if public_value(attr, value):
3271310SN/A            type.__setattr__(cls, attr, value)
3281310SN/A            return
3291310SN/A
3301310SN/A        if cls.keywords.has_key(attr):
3311427SN/A            cls._set_keyword(attr, value, cls.keywords[attr])
3321310SN/A            return
3331310SN/A
3342738SN/A        if cls._ports.has_key(attr):
3353105Sstever@eecs.umich.edu            cls._cls_get_port_ref(attr).connect(value)
3362738SN/A            return
3372738SN/A
3382740SN/A        if isSimObjectOrSequence(value) and cls._instantiated:
3392740SN/A            raise RuntimeError, \
3402740SN/A                  "cannot set SimObject parameter '%s' after\n" \
3412740SN/A                  "    class %s has been instantiated or subclassed" \
3422740SN/A                  % (attr, cls.__name__)
3432740SN/A
3442740SN/A        # check for param
3453105Sstever@eecs.umich.edu        param = cls._params.get(attr)
3461310SN/A        if param:
3473105Sstever@eecs.umich.edu            cls._set_param(attr, value, param)
3483105Sstever@eecs.umich.edu            return
3493105Sstever@eecs.umich.edu
3503105Sstever@eecs.umich.edu        if isSimObjectOrSequence(value):
3513105Sstever@eecs.umich.edu            # If RHS is a SimObject, it's an implicit child assignment.
3528321Ssteve.reinhardt@amd.com            cls._add_cls_child(attr, coerceSimObjectOrVector(value))
3533105Sstever@eecs.umich.edu            return
3543105Sstever@eecs.umich.edu
3553105Sstever@eecs.umich.edu        # no valid assignment... raise exception
3563105Sstever@eecs.umich.edu        raise AttributeError, \
3573105Sstever@eecs.umich.edu              "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
3581310SN/A
3591585SN/A    def __getattr__(cls, attr):
3607675Snate@binkert.org        if attr == 'cxx_class_path':
3617675Snate@binkert.org            return cls.cxx_class.split('::')
3627675Snate@binkert.org
3637675Snate@binkert.org        if attr == 'cxx_class_name':
3647675Snate@binkert.org            return cls.cxx_class_path[-1]
3657675Snate@binkert.org
3667675Snate@binkert.org        if attr == 'cxx_namespaces':
3677675Snate@binkert.org            return cls.cxx_class_path[:-1]
3687675Snate@binkert.org
3691692SN/A        if cls._values.has_key(attr):
3701692SN/A            return cls._values[attr]
3711585SN/A
3727528Ssteve.reinhardt@amd.com        if cls._children.has_key(attr):
3737528Ssteve.reinhardt@amd.com            return cls._children[attr]
3747528Ssteve.reinhardt@amd.com
3751585SN/A        raise AttributeError, \
3761585SN/A              "object '%s' has no attribute '%s'" % (cls.__name__, attr)
3771585SN/A
3783100SN/A    def __str__(cls):
3793100SN/A        return cls.__name__
3803100SN/A
3818596Ssteve.reinhardt@amd.com    # See ParamValue.cxx_predecls for description.
3828596Ssteve.reinhardt@amd.com    def cxx_predecls(cls, code):
3838596Ssteve.reinhardt@amd.com        code('#include "params/$cls.hh"')
3848596Ssteve.reinhardt@amd.com
3858596Ssteve.reinhardt@amd.com    # See ParamValue.swig_predecls for description.
3868596Ssteve.reinhardt@amd.com    def swig_predecls(cls, code):
3878596Ssteve.reinhardt@amd.com        code('%import "python/m5/internal/param_$cls.i"')
3888596Ssteve.reinhardt@amd.com
3898597Ssteve.reinhardt@amd.com    # Hook for exporting additional C++ methods to Python via SWIG.
3908597Ssteve.reinhardt@amd.com    # Default is none, override using @classmethod in class definition.
3918597Ssteve.reinhardt@amd.com    def export_methods(cls, code):
3928597Ssteve.reinhardt@amd.com        pass
3938597Ssteve.reinhardt@amd.com
3948597Ssteve.reinhardt@amd.com    # Generate the code needed as a prerequisite for the C++ methods
3958597Ssteve.reinhardt@amd.com    # exported via export_methods() to be compiled in the _wrap.cc
3968597Ssteve.reinhardt@amd.com    # file.  Typically generates one or more #include statements.  If
3978597Ssteve.reinhardt@amd.com    # any methods are exported, typically at least the C++ header
3988597Ssteve.reinhardt@amd.com    # declaring the relevant SimObject class must be included.
3998597Ssteve.reinhardt@amd.com    def export_method_cxx_predecls(cls, code):
4008597Ssteve.reinhardt@amd.com        pass
4018597Ssteve.reinhardt@amd.com
4028597Ssteve.reinhardt@amd.com    # Generate the code needed as a prerequisite for the C++ methods
4038597Ssteve.reinhardt@amd.com    # exported via export_methods() to be processed by SWIG.
4048597Ssteve.reinhardt@amd.com    # Typically generates one or more %include or %import statements.
4058597Ssteve.reinhardt@amd.com    # If any methods are exported, typically at least the C++ header
4068597Ssteve.reinhardt@amd.com    # declaring the relevant SimObject class must be included.
4078597Ssteve.reinhardt@amd.com    def export_method_swig_predecls(cls, code):
4088597Ssteve.reinhardt@amd.com        pass
4098597Ssteve.reinhardt@amd.com
4108596Ssteve.reinhardt@amd.com    # Generate the declaration for this object for wrapping with SWIG.
4118596Ssteve.reinhardt@amd.com    # Generates code that goes into a SWIG .i file.  Called from
4128596Ssteve.reinhardt@amd.com    # src/SConscript.
4138596Ssteve.reinhardt@amd.com    def swig_decl(cls, code):
4148596Ssteve.reinhardt@amd.com        class_path = cls.cxx_class.split('::')
4158596Ssteve.reinhardt@amd.com        classname = class_path[-1]
4168596Ssteve.reinhardt@amd.com        namespaces = class_path[:-1]
4178596Ssteve.reinhardt@amd.com
4188596Ssteve.reinhardt@amd.com        # The 'local' attribute restricts us to the params declared in
4198596Ssteve.reinhardt@amd.com        # the object itself, not including inherited params (which
4208596Ssteve.reinhardt@amd.com        # will also be inherited from the base class's param struct
4218596Ssteve.reinhardt@amd.com        # here).
4228596Ssteve.reinhardt@amd.com        params = cls._params.local.values()
4238840Sandreas.hansson@arm.com        ports = cls._ports.local
4248596Ssteve.reinhardt@amd.com
4258596Ssteve.reinhardt@amd.com        code('%module(package="m5.internal") param_$cls')
4268596Ssteve.reinhardt@amd.com        code()
4278596Ssteve.reinhardt@amd.com        code('%{')
4289342SAndreas.Sandberg@arm.com        code('#include "sim/sim_object.hh"')
4298596Ssteve.reinhardt@amd.com        code('#include "params/$cls.hh"')
4308596Ssteve.reinhardt@amd.com        for param in params:
4318596Ssteve.reinhardt@amd.com            param.cxx_predecls(code)
4329338SAndreas.Sandberg@arm.com        code('#include "${{cls.cxx_header}}"')
4338597Ssteve.reinhardt@amd.com        cls.export_method_cxx_predecls(code)
4348860Sandreas.hansson@arm.com        code('''\
4358860Sandreas.hansson@arm.com/**
4368860Sandreas.hansson@arm.com  * This is a workaround for bug in swig. Prior to gcc 4.6.1 the STL
4378860Sandreas.hansson@arm.com  * headers like vector, string, etc. used to automatically pull in
4388860Sandreas.hansson@arm.com  * the cstddef header but starting with gcc 4.6.1 they no longer do.
4398860Sandreas.hansson@arm.com  * This leads to swig generated a file that does not compile so we
4408860Sandreas.hansson@arm.com  * explicitly include cstddef. Additionally, including version 2.0.4,
4418860Sandreas.hansson@arm.com  * swig uses ptrdiff_t without the std:: namespace prefix which is
4428860Sandreas.hansson@arm.com  * required with gcc 4.6.1. We explicitly provide access to it.
4438860Sandreas.hansson@arm.com  */
4448860Sandreas.hansson@arm.com#include <cstddef>
4458860Sandreas.hansson@arm.comusing std::ptrdiff_t;
4468860Sandreas.hansson@arm.com''')
4478596Ssteve.reinhardt@amd.com        code('%}')
4488596Ssteve.reinhardt@amd.com        code()
4498596Ssteve.reinhardt@amd.com
4508596Ssteve.reinhardt@amd.com        for param in params:
4518596Ssteve.reinhardt@amd.com            param.swig_predecls(code)
4528597Ssteve.reinhardt@amd.com        cls.export_method_swig_predecls(code)
4538596Ssteve.reinhardt@amd.com
4548596Ssteve.reinhardt@amd.com        code()
4558596Ssteve.reinhardt@amd.com        if cls._base:
4568596Ssteve.reinhardt@amd.com            code('%import "python/m5/internal/param_${{cls._base}}.i"')
4578596Ssteve.reinhardt@amd.com        code()
4588596Ssteve.reinhardt@amd.com
4598596Ssteve.reinhardt@amd.com        for ns in namespaces:
4608596Ssteve.reinhardt@amd.com            code('namespace $ns {')
4618596Ssteve.reinhardt@amd.com
4628596Ssteve.reinhardt@amd.com        if namespaces:
4638596Ssteve.reinhardt@amd.com            code('// avoid name conflicts')
4648596Ssteve.reinhardt@amd.com            sep_string = '_COLONS_'
4658596Ssteve.reinhardt@amd.com            flat_name = sep_string.join(class_path)
4668596Ssteve.reinhardt@amd.com            code('%rename($flat_name) $classname;')
4678596Ssteve.reinhardt@amd.com
4688597Ssteve.reinhardt@amd.com        code()
4698597Ssteve.reinhardt@amd.com        code('// stop swig from creating/wrapping default ctor/dtor')
4708597Ssteve.reinhardt@amd.com        code('%nodefault $classname;')
4718597Ssteve.reinhardt@amd.com        code('class $classname')
4728597Ssteve.reinhardt@amd.com        if cls._base:
4739342SAndreas.Sandberg@arm.com            bases = [ cls._base.cxx_class ] + cls.cxx_bases
4749342SAndreas.Sandberg@arm.com        else:
4759342SAndreas.Sandberg@arm.com            bases = cls.cxx_bases
4769342SAndreas.Sandberg@arm.com        base_first = True
4779342SAndreas.Sandberg@arm.com        for base in bases:
4789342SAndreas.Sandberg@arm.com            if base_first:
4799342SAndreas.Sandberg@arm.com                code('    : public ${{base}}')
4809342SAndreas.Sandberg@arm.com                base_first = False
4819342SAndreas.Sandberg@arm.com            else:
4829342SAndreas.Sandberg@arm.com                code('    , public ${{base}}')
4839342SAndreas.Sandberg@arm.com
4848597Ssteve.reinhardt@amd.com        code('{')
4858597Ssteve.reinhardt@amd.com        code('  public:')
4868597Ssteve.reinhardt@amd.com        cls.export_methods(code)
4878597Ssteve.reinhardt@amd.com        code('};')
4888596Ssteve.reinhardt@amd.com
4898596Ssteve.reinhardt@amd.com        for ns in reversed(namespaces):
4908596Ssteve.reinhardt@amd.com            code('} // namespace $ns')
4918596Ssteve.reinhardt@amd.com
4928596Ssteve.reinhardt@amd.com        code()
4938596Ssteve.reinhardt@amd.com        code('%include "params/$cls.hh"')
4948596Ssteve.reinhardt@amd.com
4958596Ssteve.reinhardt@amd.com
4968596Ssteve.reinhardt@amd.com    # Generate the C++ declaration (.hh file) for this SimObject's
4978596Ssteve.reinhardt@amd.com    # param struct.  Called from src/SConscript.
4988596Ssteve.reinhardt@amd.com    def cxx_param_decl(cls, code):
4998596Ssteve.reinhardt@amd.com        # The 'local' attribute restricts us to the params declared in
5003100SN/A        # the object itself, not including inherited params (which
5013100SN/A        # will also be inherited from the base class's param struct
5023100SN/A        # here).
5034762Snate@binkert.org        params = cls._params.local.values()
5048840Sandreas.hansson@arm.com        ports = cls._ports.local
5053100SN/A        try:
5063100SN/A            ptypes = [p.ptype for p in params]
5073100SN/A        except:
5083100SN/A            print cls, p, p.ptype_str
5093100SN/A            print params
5103100SN/A            raise
5113100SN/A
5127675Snate@binkert.org        class_path = cls._value_dict['cxx_class'].split('::')
5137675Snate@binkert.org
5147675Snate@binkert.org        code('''\
5157675Snate@binkert.org#ifndef __PARAMS__${cls}__
5167675Snate@binkert.org#define __PARAMS__${cls}__
5177675Snate@binkert.org
5187675Snate@binkert.org''')
5197675Snate@binkert.org
5207675Snate@binkert.org        # A forward class declaration is sufficient since we are just
5217675Snate@binkert.org        # declaring a pointer.
5227675Snate@binkert.org        for ns in class_path[:-1]:
5237675Snate@binkert.org            code('namespace $ns {')
5247675Snate@binkert.org        code('class $0;', class_path[-1])
5257675Snate@binkert.org        for ns in reversed(class_path[:-1]):
5267811Ssteve.reinhardt@amd.com            code('} // namespace $ns')
5277675Snate@binkert.org        code()
5287675Snate@binkert.org
5298597Ssteve.reinhardt@amd.com        # The base SimObject has a couple of params that get
5308597Ssteve.reinhardt@amd.com        # automatically set from Python without being declared through
5318597Ssteve.reinhardt@amd.com        # the normal Param mechanism; we slip them in here (needed
5328597Ssteve.reinhardt@amd.com        # predecls now, actual declarations below)
5338597Ssteve.reinhardt@amd.com        if cls == SimObject:
5348597Ssteve.reinhardt@amd.com            code('''
5358597Ssteve.reinhardt@amd.com#ifndef PY_VERSION
5368597Ssteve.reinhardt@amd.comstruct PyObject;
5378597Ssteve.reinhardt@amd.com#endif
5388597Ssteve.reinhardt@amd.com
5398597Ssteve.reinhardt@amd.com#include <string>
5408597Ssteve.reinhardt@amd.com''')
5417673Snate@binkert.org        for param in params:
5427673Snate@binkert.org            param.cxx_predecls(code)
5438840Sandreas.hansson@arm.com        for port in ports.itervalues():
5448840Sandreas.hansson@arm.com            port.cxx_predecls(code)
5457673Snate@binkert.org        code()
5464762Snate@binkert.org
5475610Snate@binkert.org        if cls._base:
5487673Snate@binkert.org            code('#include "params/${{cls._base.type}}.hh"')
5497673Snate@binkert.org            code()
5504762Snate@binkert.org
5514762Snate@binkert.org        for ptype in ptypes:
5524762Snate@binkert.org            if issubclass(ptype, Enum):
5537673Snate@binkert.org                code('#include "enums/${{ptype.__name__}}.hh"')
5547673Snate@binkert.org                code()
5554762Snate@binkert.org
5568596Ssteve.reinhardt@amd.com        # now generate the actual param struct
5578597Ssteve.reinhardt@amd.com        code("struct ${cls}Params")
5588597Ssteve.reinhardt@amd.com        if cls._base:
5598597Ssteve.reinhardt@amd.com            code("    : public ${{cls._base.type}}Params")
5608597Ssteve.reinhardt@amd.com        code("{")
5618597Ssteve.reinhardt@amd.com        if not hasattr(cls, 'abstract') or not cls.abstract:
5628597Ssteve.reinhardt@amd.com            if 'type' in cls.__dict__:
5638597Ssteve.reinhardt@amd.com                code("    ${{cls.cxx_type}} create();")
5648597Ssteve.reinhardt@amd.com
5658597Ssteve.reinhardt@amd.com        code.indent()
5668596Ssteve.reinhardt@amd.com        if cls == SimObject:
5678597Ssteve.reinhardt@amd.com            code('''
5689983Sstever@gmail.com    SimObjectParams() {}
5698597Ssteve.reinhardt@amd.com    virtual ~SimObjectParams() {}
5708596Ssteve.reinhardt@amd.com
5718597Ssteve.reinhardt@amd.com    std::string name;
5728597Ssteve.reinhardt@amd.com    PyObject *pyobj;
5738597Ssteve.reinhardt@amd.com            ''')
5748597Ssteve.reinhardt@amd.com        for param in params:
5758597Ssteve.reinhardt@amd.com            param.cxx_decl(code)
5768840Sandreas.hansson@arm.com        for port in ports.itervalues():
5778840Sandreas.hansson@arm.com            port.cxx_decl(code)
5788840Sandreas.hansson@arm.com
5798597Ssteve.reinhardt@amd.com        code.dedent()
5808597Ssteve.reinhardt@amd.com        code('};')
5815488Snate@binkert.org
5827673Snate@binkert.org        code()
5837673Snate@binkert.org        code('#endif // __PARAMS__${cls}__')
5845488Snate@binkert.org        return code
5855488Snate@binkert.org
5865488Snate@binkert.org
5879983Sstever@gmail.com# This *temporary* definition is required to support calls from the
5889983Sstever@gmail.com# SimObject class definition to the MetaSimObject methods (in
5899983Sstever@gmail.com# particular _set_param, which gets called for parameters with default
5909983Sstever@gmail.com# values defined on the SimObject class itself).  It will get
5919983Sstever@gmail.com# overridden by the permanent definition (which requires that
5929983Sstever@gmail.com# SimObject be defined) lower in this file.
5939983Sstever@gmail.comdef isSimObjectOrVector(value):
5949983Sstever@gmail.com    return False
5953100SN/A
59610267SGeoffrey.Blake@arm.com# This class holds information about each simobject parameter
59710267SGeoffrey.Blake@arm.com# that should be displayed on the command line for use in the
59810267SGeoffrey.Blake@arm.com# configuration system.
59910267SGeoffrey.Blake@arm.comclass ParamInfo(object):
60010267SGeoffrey.Blake@arm.com  def __init__(self, type, desc, type_str, example, default_val, access_str):
60110267SGeoffrey.Blake@arm.com    self.type = type
60210267SGeoffrey.Blake@arm.com    self.desc = desc
60310267SGeoffrey.Blake@arm.com    self.type_str = type_str
60410267SGeoffrey.Blake@arm.com    self.example_str = example
60510267SGeoffrey.Blake@arm.com    self.default_val = default_val
60610267SGeoffrey.Blake@arm.com    # The string representation used to access this param through python.
60710267SGeoffrey.Blake@arm.com    # The method to access this parameter presented on the command line may
60810267SGeoffrey.Blake@arm.com    # be different, so this needs to be stored for later use.
60910267SGeoffrey.Blake@arm.com    self.access_str = access_str
61010267SGeoffrey.Blake@arm.com    self.created = True
61110267SGeoffrey.Blake@arm.com
61210267SGeoffrey.Blake@arm.com  # Make it so we can only set attributes at initialization time
61310267SGeoffrey.Blake@arm.com  # and effectively make this a const object.
61410267SGeoffrey.Blake@arm.com  def __setattr__(self, name, value):
61510267SGeoffrey.Blake@arm.com    if not "created" in self.__dict__:
61610267SGeoffrey.Blake@arm.com      self.__dict__[name] = value
61710267SGeoffrey.Blake@arm.com
6182740SN/A# The SimObject class is the root of the special hierarchy.  Most of
619679SN/A# the code in this class deals with the configuration hierarchy itself
620679SN/A# (parent/child node relationships).
6211692SN/Aclass SimObject(object):
6221692SN/A    # Specify metaclass.  Any class inheriting from SimObject will
623679SN/A    # get this metaclass.
6241692SN/A    __metaclass__ = MetaSimObject
6253100SN/A    type = 'SimObject'
6264762Snate@binkert.org    abstract = True
6279983Sstever@gmail.com
6289338SAndreas.Sandberg@arm.com    cxx_header = "sim/sim_object.hh"
6299345SAndreas.Sandberg@ARM.com    cxx_bases = [ "Drainable", "Serializable" ]
6309983Sstever@gmail.com    eventq_index = Param.UInt32(Parent.eventq_index, "Event Queue Index")
6319342SAndreas.Sandberg@arm.com
6328597Ssteve.reinhardt@amd.com    @classmethod
6338597Ssteve.reinhardt@amd.com    def export_method_swig_predecls(cls, code):
6348597Ssteve.reinhardt@amd.com        code('''
6358597Ssteve.reinhardt@amd.com%include <std_string.i>
6369342SAndreas.Sandberg@arm.com
6379342SAndreas.Sandberg@arm.com%import "python/swig/drain.i"
6389345SAndreas.Sandberg@ARM.com%import "python/swig/serialize.i"
6398597Ssteve.reinhardt@amd.com''')
6408597Ssteve.reinhardt@amd.com
6418597Ssteve.reinhardt@amd.com    @classmethod
6428597Ssteve.reinhardt@amd.com    def export_methods(cls, code):
6438597Ssteve.reinhardt@amd.com        code('''
6448597Ssteve.reinhardt@amd.com    void init();
6458597Ssteve.reinhardt@amd.com    void loadState(Checkpoint *cp);
6468597Ssteve.reinhardt@amd.com    void initState();
6478597Ssteve.reinhardt@amd.com    void regStats();
6488597Ssteve.reinhardt@amd.com    void resetStats();
64910023Smatt.horsnell@ARM.com    void regProbePoints();
65010023Smatt.horsnell@ARM.com    void regProbeListeners();
6518597Ssteve.reinhardt@amd.com    void startup();
6528597Ssteve.reinhardt@amd.com''')
6538597Ssteve.reinhardt@amd.com
65410267SGeoffrey.Blake@arm.com    # Returns a dict of all the option strings that can be
65510267SGeoffrey.Blake@arm.com    # generated as command line options for this simobject instance
65610267SGeoffrey.Blake@arm.com    # by tracing all reachable params in the top level instance and
65710267SGeoffrey.Blake@arm.com    # any children it contains.
65810267SGeoffrey.Blake@arm.com    def enumerateParams(self, flags_dict = {},
65910267SGeoffrey.Blake@arm.com                        cmd_line_str = "", access_str = ""):
66010267SGeoffrey.Blake@arm.com        if hasattr(self, "_paramEnumed"):
66110267SGeoffrey.Blake@arm.com            print "Cycle detected enumerating params"
66210267SGeoffrey.Blake@arm.com        else:
66310267SGeoffrey.Blake@arm.com            self._paramEnumed = True
66410267SGeoffrey.Blake@arm.com            # Scan the children first to pick up all the objects in this SimObj
66510267SGeoffrey.Blake@arm.com            for keys in self._children:
66610267SGeoffrey.Blake@arm.com                child = self._children[keys]
66710267SGeoffrey.Blake@arm.com                next_cmdline_str = cmd_line_str + keys
66810267SGeoffrey.Blake@arm.com                next_access_str = access_str + keys
66910267SGeoffrey.Blake@arm.com                if not isSimObjectVector(child):
67010267SGeoffrey.Blake@arm.com                    next_cmdline_str = next_cmdline_str + "."
67110267SGeoffrey.Blake@arm.com                    next_access_str = next_access_str + "."
67210267SGeoffrey.Blake@arm.com                flags_dict = child.enumerateParams(flags_dict,
67310267SGeoffrey.Blake@arm.com                                                   next_cmdline_str,
67410267SGeoffrey.Blake@arm.com                                                   next_access_str)
67510267SGeoffrey.Blake@arm.com
67610267SGeoffrey.Blake@arm.com            # Go through the simple params in the simobject in this level
67710267SGeoffrey.Blake@arm.com            # of the simobject hierarchy and save information about the
67810267SGeoffrey.Blake@arm.com            # parameter to be used for generating and processing command line
67910267SGeoffrey.Blake@arm.com            # options to the simulator to set these parameters.
68010267SGeoffrey.Blake@arm.com            for keys,values in self._params.items():
68110267SGeoffrey.Blake@arm.com                if values.isCmdLineSettable():
68210267SGeoffrey.Blake@arm.com                    type_str = ''
68310267SGeoffrey.Blake@arm.com                    ex_str = values.example_str()
68410267SGeoffrey.Blake@arm.com                    ptype = None
68510267SGeoffrey.Blake@arm.com                    if isinstance(values, VectorParamDesc):
68610267SGeoffrey.Blake@arm.com                        type_str = 'Vector_%s' % values.ptype_str
68710267SGeoffrey.Blake@arm.com                        ptype = values
68810267SGeoffrey.Blake@arm.com                    else:
68910267SGeoffrey.Blake@arm.com                        type_str = '%s' % values.ptype_str
69010267SGeoffrey.Blake@arm.com                        ptype = values.ptype
69110267SGeoffrey.Blake@arm.com
69210267SGeoffrey.Blake@arm.com                    if keys in self._hr_values\
69310267SGeoffrey.Blake@arm.com                       and keys in self._values\
69410267SGeoffrey.Blake@arm.com                       and not isinstance(self._values[keys], m5.proxy.BaseProxy):
69510267SGeoffrey.Blake@arm.com                        cmd_str = cmd_line_str + keys
69610267SGeoffrey.Blake@arm.com                        acc_str = access_str + keys
69710267SGeoffrey.Blake@arm.com                        flags_dict[cmd_str] = ParamInfo(ptype,
69810267SGeoffrey.Blake@arm.com                                    self._params[keys].desc, type_str, ex_str,
69910267SGeoffrey.Blake@arm.com                                    values.pretty_print(self._hr_values[keys]),
70010267SGeoffrey.Blake@arm.com                                    acc_str)
70110267SGeoffrey.Blake@arm.com                    elif not keys in self._hr_values\
70210267SGeoffrey.Blake@arm.com                         and not keys in self._values:
70310267SGeoffrey.Blake@arm.com                        # Empty param
70410267SGeoffrey.Blake@arm.com                        cmd_str = cmd_line_str + keys
70510267SGeoffrey.Blake@arm.com                        acc_str = access_str + keys
70610267SGeoffrey.Blake@arm.com                        flags_dict[cmd_str] = ParamInfo(ptype,
70710267SGeoffrey.Blake@arm.com                                    self._params[keys].desc,
70810267SGeoffrey.Blake@arm.com                                    type_str, ex_str, '', acc_str)
70910267SGeoffrey.Blake@arm.com
71010267SGeoffrey.Blake@arm.com        return flags_dict
71110267SGeoffrey.Blake@arm.com
7122740SN/A    # Initialize new instance.  For objects with SimObject-valued
7132740SN/A    # children, we need to recursively clone the classes represented
7142740SN/A    # by those param values as well in a consistent "deep copy"-style
7152740SN/A    # fashion.  That is, we want to make sure that each instance is
7162740SN/A    # cloned only once, and that if there are multiple references to
7172740SN/A    # the same original object, we end up with the corresponding
7182740SN/A    # cloned references all pointing to the same cloned instance.
7192740SN/A    def __init__(self, **kwargs):
7202740SN/A        ancestor = kwargs.get('_ancestor')
7212740SN/A        memo_dict = kwargs.get('_memo')
7222740SN/A        if memo_dict is None:
7232740SN/A            # prepare to memoize any recursively instantiated objects
7242740SN/A            memo_dict = {}
7252740SN/A        elif ancestor:
7262740SN/A            # memoize me now to avoid problems with recursive calls
7272740SN/A            memo_dict[ancestor] = self
7282711SN/A
7292740SN/A        if not ancestor:
7302740SN/A            ancestor = self.__class__
7312740SN/A        ancestor._instantiated = True
7322711SN/A
7332740SN/A        # initialize required attributes
7342740SN/A        self._parent = None
7357528Ssteve.reinhardt@amd.com        self._name = None
7362740SN/A        self._ccObject = None  # pointer to C++ object
7374762Snate@binkert.org        self._ccParams = None
7382740SN/A        self._instantiated = False # really "cloned"
7392712SN/A
7408321Ssteve.reinhardt@amd.com        # Clone children specified at class level.  No need for a
7418321Ssteve.reinhardt@amd.com        # multidict here since we will be cloning everything.
7428321Ssteve.reinhardt@amd.com        # Do children before parameter values so that children that
7438321Ssteve.reinhardt@amd.com        # are also param values get cloned properly.
7448321Ssteve.reinhardt@amd.com        self._children = {}
7458321Ssteve.reinhardt@amd.com        for key,val in ancestor._children.iteritems():
7468321Ssteve.reinhardt@amd.com            self.add_child(key, val(_memo=memo_dict))
7478321Ssteve.reinhardt@amd.com
7482711SN/A        # Inherit parameter values from class using multidict so
7497528Ssteve.reinhardt@amd.com        # individual value settings can be overridden but we still
7507528Ssteve.reinhardt@amd.com        # inherit late changes to non-overridden class values.
7512740SN/A        self._values = multidict(ancestor._values)
75210267SGeoffrey.Blake@arm.com        self._hr_values = multidict(ancestor._hr_values)
7532740SN/A        # clone SimObject-valued parameters
7542740SN/A        for key,val in ancestor._values.iteritems():
7557528Ssteve.reinhardt@amd.com            val = tryAsSimObjectOrVector(val)
7567528Ssteve.reinhardt@amd.com            if val is not None:
7577528Ssteve.reinhardt@amd.com                self._values[key] = val(_memo=memo_dict)
7587528Ssteve.reinhardt@amd.com
7592740SN/A        # clone port references.  no need to use a multidict here
7602740SN/A        # since we will be creating new references for all ports.
7613105Sstever@eecs.umich.edu        self._port_refs = {}
7623105Sstever@eecs.umich.edu        for key,val in ancestor._port_refs.iteritems():
7633105Sstever@eecs.umich.edu            self._port_refs[key] = val.clone(self, memo_dict)
7641692SN/A        # apply attribute assignments from keyword args, if any
7651692SN/A        for key,val in kwargs.iteritems():
7661692SN/A            setattr(self, key, val)
767679SN/A
7682740SN/A    # "Clone" the current instance by creating another instance of
7692740SN/A    # this instance's class, but that inherits its parameter values
7702740SN/A    # and port mappings from the current instance.  If we're in a
7712740SN/A    # "deep copy" recursive clone, check the _memo dict to see if
7722740SN/A    # we've already cloned this instance.
7731692SN/A    def __call__(self, **kwargs):
7742740SN/A        memo_dict = kwargs.get('_memo')
7752740SN/A        if memo_dict is None:
7762740SN/A            # no memo_dict: must be top-level clone operation.
7772740SN/A            # this is only allowed at the root of a hierarchy
7782740SN/A            if self._parent:
7792740SN/A                raise RuntimeError, "attempt to clone object %s " \
7802740SN/A                      "not at the root of a tree (parent = %s)" \
7812740SN/A                      % (self, self._parent)
7822740SN/A            # create a new dict and use that.
7832740SN/A            memo_dict = {}
7842740SN/A            kwargs['_memo'] = memo_dict
7852740SN/A        elif memo_dict.has_key(self):
7862740SN/A            # clone already done & memoized
7872740SN/A            return memo_dict[self]
7882740SN/A        return self.__class__(_ancestor = self, **kwargs)
7891343SN/A
7903105Sstever@eecs.umich.edu    def _get_port_ref(self, attr):
7913105Sstever@eecs.umich.edu        # Return reference that can be assigned to another port
7923105Sstever@eecs.umich.edu        # via __setattr__.  There is only ever one reference
7933105Sstever@eecs.umich.edu        # object per port, but we create them lazily here.
7943105Sstever@eecs.umich.edu        ref = self._port_refs.get(attr)
7959940SGeoffrey.Blake@arm.com        if ref == None:
7963105Sstever@eecs.umich.edu            ref = self._ports[attr].makeRef(self)
7973105Sstever@eecs.umich.edu            self._port_refs[attr] = ref
7983105Sstever@eecs.umich.edu        return ref
7993105Sstever@eecs.umich.edu
8001692SN/A    def __getattr__(self, attr):
8012738SN/A        if self._ports.has_key(attr):
8023105Sstever@eecs.umich.edu            return self._get_port_ref(attr)
8032738SN/A
8041692SN/A        if self._values.has_key(attr):
8051692SN/A            return self._values[attr]
8061427SN/A
8077528Ssteve.reinhardt@amd.com        if self._children.has_key(attr):
8087528Ssteve.reinhardt@amd.com            return self._children[attr]
8097528Ssteve.reinhardt@amd.com
8107500Ssteve.reinhardt@amd.com        # If the attribute exists on the C++ object, transparently
8117500Ssteve.reinhardt@amd.com        # forward the reference there.  This is typically used for
8127500Ssteve.reinhardt@amd.com        # SWIG-wrapped methods such as init(), regStats(),
8139195SAndreas.Sandberg@arm.com        # resetStats(), startup(), drain(), and
8147527Ssteve.reinhardt@amd.com        # resume().
8157500Ssteve.reinhardt@amd.com        if self._ccObject and hasattr(self._ccObject, attr):
8167500Ssteve.reinhardt@amd.com            return getattr(self._ccObject, attr)
8177500Ssteve.reinhardt@amd.com
81810002Ssteve.reinhardt@amd.com        err_string = "object '%s' has no attribute '%s'" \
8191692SN/A              % (self.__class__.__name__, attr)
8201427SN/A
82110002Ssteve.reinhardt@amd.com        if not self._ccObject:
82210002Ssteve.reinhardt@amd.com            err_string += "\n  (C++ object is not yet constructed," \
82310002Ssteve.reinhardt@amd.com                          " so wrapped C++ methods are unavailable.)"
82410002Ssteve.reinhardt@amd.com
82510002Ssteve.reinhardt@amd.com        raise AttributeError, err_string
82610002Ssteve.reinhardt@amd.com
8271692SN/A    # Set attribute (called on foo.attr = value when foo is an
8281692SN/A    # instance of class cls).
8291692SN/A    def __setattr__(self, attr, value):
8301692SN/A        # normal processing for private attributes
8311692SN/A        if attr.startswith('_'):
8321692SN/A            object.__setattr__(self, attr, value)
8331692SN/A            return
8341427SN/A
8352738SN/A        if self._ports.has_key(attr):
8362738SN/A            # set up port connection
8373105Sstever@eecs.umich.edu            self._get_port_ref(attr).connect(value)
8382738SN/A            return
8392738SN/A
8403105Sstever@eecs.umich.edu        param = self._params.get(attr)
8411692SN/A        if param:
8421310SN/A            try:
84310267SGeoffrey.Blake@arm.com                hr_value = value
8441692SN/A                value = param.convert(value)
8451587SN/A            except Exception, e:
8461692SN/A                msg = "%s\nError setting param %s.%s to %s\n" % \
8471692SN/A                      (e, self.__class__.__name__, attr, value)
8481605SN/A                e.args = (msg, )
8491605SN/A                raise
8507528Ssteve.reinhardt@amd.com            self._values[attr] = value
8518321Ssteve.reinhardt@amd.com            # implicitly parent unparented objects assigned as params
8528321Ssteve.reinhardt@amd.com            if isSimObjectOrVector(value) and not value.has_parent():
8538321Ssteve.reinhardt@amd.com                self.add_child(attr, value)
85410267SGeoffrey.Blake@arm.com            # set the human-readable value dict if this is a param
85510267SGeoffrey.Blake@arm.com            # with a literal value and is not being set as an object
85610267SGeoffrey.Blake@arm.com            # or proxy.
85710267SGeoffrey.Blake@arm.com            if not (isSimObjectOrVector(value) or\
85810267SGeoffrey.Blake@arm.com                    isinstance(value, m5.proxy.BaseProxy)):
85910267SGeoffrey.Blake@arm.com                self._hr_values[attr] = hr_value
86010267SGeoffrey.Blake@arm.com
8613105Sstever@eecs.umich.edu            return
8621310SN/A
8637528Ssteve.reinhardt@amd.com        # if RHS is a SimObject, it's an implicit child assignment
8643105Sstever@eecs.umich.edu        if isSimObjectOrSequence(value):
8657528Ssteve.reinhardt@amd.com            self.add_child(attr, value)
8663105Sstever@eecs.umich.edu            return
8671693SN/A
8683105Sstever@eecs.umich.edu        # no valid assignment... raise exception
8693105Sstever@eecs.umich.edu        raise AttributeError, "Class %s has no parameter %s" \
8703105Sstever@eecs.umich.edu              % (self.__class__.__name__, attr)
8711310SN/A
8721310SN/A
8731692SN/A    # this hack allows tacking a '[0]' onto parameters that may or may
8741692SN/A    # not be vectors, and always getting the first element (e.g. cpus)
8751692SN/A    def __getitem__(self, key):
8761692SN/A        if key == 0:
8771692SN/A            return self
87810267SGeoffrey.Blake@arm.com        raise IndexError, "Non-zero index '%s' to SimObject" % key
87910267SGeoffrey.Blake@arm.com
88010267SGeoffrey.Blake@arm.com    # this hack allows us to iterate over a SimObject that may
88110267SGeoffrey.Blake@arm.com    # not be a vector, so we can call a loop over it and get just one
88210267SGeoffrey.Blake@arm.com    # element.
88310267SGeoffrey.Blake@arm.com    def __len__(self):
88410267SGeoffrey.Blake@arm.com        return 1
8851310SN/A
8867528Ssteve.reinhardt@amd.com    # Also implemented by SimObjectVector
8877528Ssteve.reinhardt@amd.com    def clear_parent(self, old_parent):
8887528Ssteve.reinhardt@amd.com        assert self._parent is old_parent
8897528Ssteve.reinhardt@amd.com        self._parent = None
8907528Ssteve.reinhardt@amd.com
8917528Ssteve.reinhardt@amd.com    # Also implemented by SimObjectVector
8927528Ssteve.reinhardt@amd.com    def set_parent(self, parent, name):
8937528Ssteve.reinhardt@amd.com        self._parent = parent
8947528Ssteve.reinhardt@amd.com        self._name = name
8957528Ssteve.reinhardt@amd.com
8969953Sgeoffrey.blake@arm.com    # Return parent object of this SimObject, not implemented by SimObjectVector
8979953Sgeoffrey.blake@arm.com    # because the elements in a SimObjectVector may not share the same parent
8989953Sgeoffrey.blake@arm.com    def get_parent(self):
8999953Sgeoffrey.blake@arm.com        return self._parent
9009953Sgeoffrey.blake@arm.com
9017528Ssteve.reinhardt@amd.com    # Also implemented by SimObjectVector
9027528Ssteve.reinhardt@amd.com    def get_name(self):
9037528Ssteve.reinhardt@amd.com        return self._name
9047528Ssteve.reinhardt@amd.com
9058321Ssteve.reinhardt@amd.com    # Also implemented by SimObjectVector
9068321Ssteve.reinhardt@amd.com    def has_parent(self):
9078321Ssteve.reinhardt@amd.com        return self._parent is not None
9087528Ssteve.reinhardt@amd.com
9097742Sgblack@eecs.umich.edu    # clear out child with given name. This code is not likely to be exercised.
9107742Sgblack@eecs.umich.edu    # See comment in add_child.
9111693SN/A    def clear_child(self, name):
9121693SN/A        child = self._children[name]
9137528Ssteve.reinhardt@amd.com        child.clear_parent(self)
9141693SN/A        del self._children[name]
9151693SN/A
9167528Ssteve.reinhardt@amd.com    # Add a new child to this object.
9177528Ssteve.reinhardt@amd.com    def add_child(self, name, child):
9187528Ssteve.reinhardt@amd.com        child = coerceSimObjectOrVector(child)
9198321Ssteve.reinhardt@amd.com        if child.has_parent():
9209528Ssascha.bischoff@arm.com            warn("add_child('%s'): child '%s' already has parent", name,
9219528Ssascha.bischoff@arm.com                child.get_name())
9227528Ssteve.reinhardt@amd.com        if self._children.has_key(name):
9237742Sgblack@eecs.umich.edu            # This code path had an undiscovered bug that would make it fail
9247742Sgblack@eecs.umich.edu            # at runtime. It had been here for a long time and was only
9257742Sgblack@eecs.umich.edu            # exposed by a buggy script. Changes here will probably not be
9267742Sgblack@eecs.umich.edu            # exercised without specialized testing.
9277738Sgblack@eecs.umich.edu            self.clear_child(name)
9287528Ssteve.reinhardt@amd.com        child.set_parent(self, name)
9297528Ssteve.reinhardt@amd.com        self._children[name] = child
9301310SN/A
9317528Ssteve.reinhardt@amd.com    # Take SimObject-valued parameters that haven't been explicitly
9327528Ssteve.reinhardt@amd.com    # assigned as children and make them children of the object that
9337528Ssteve.reinhardt@amd.com    # they were assigned to as a parameter value.  This guarantees
9347528Ssteve.reinhardt@amd.com    # that when we instantiate all the parameter objects we're still
9357528Ssteve.reinhardt@amd.com    # inside the configuration hierarchy.
9367528Ssteve.reinhardt@amd.com    def adoptOrphanParams(self):
9377528Ssteve.reinhardt@amd.com        for key,val in self._values.iteritems():
9387528Ssteve.reinhardt@amd.com            if not isSimObjectVector(val) and isSimObjectSequence(val):
9397528Ssteve.reinhardt@amd.com                # need to convert raw SimObject sequences to
9408321Ssteve.reinhardt@amd.com                # SimObjectVector class so we can call has_parent()
9417528Ssteve.reinhardt@amd.com                val = SimObjectVector(val)
9427528Ssteve.reinhardt@amd.com                self._values[key] = val
9438321Ssteve.reinhardt@amd.com            if isSimObjectOrVector(val) and not val.has_parent():
9449528Ssascha.bischoff@arm.com                warn("%s adopting orphan SimObject param '%s'", self, key)
9457528Ssteve.reinhardt@amd.com                self.add_child(key, val)
9463105Sstever@eecs.umich.edu
9471692SN/A    def path(self):
9482740SN/A        if not self._parent:
9498321Ssteve.reinhardt@amd.com            return '<orphan %s>' % self.__class__
9501692SN/A        ppath = self._parent.path()
9511692SN/A        if ppath == 'root':
9521692SN/A            return self._name
9531692SN/A        return ppath + "." + self._name
9541310SN/A
9551692SN/A    def __str__(self):
9561692SN/A        return self.path()
9571310SN/A
9581692SN/A    def ini_str(self):
9591692SN/A        return self.path()
9601310SN/A
9611692SN/A    def find_any(self, ptype):
9621692SN/A        if isinstance(self, ptype):
9631692SN/A            return self, True
9641310SN/A
9651692SN/A        found_obj = None
9661692SN/A        for child in self._children.itervalues():
96710195SGeoffrey.Blake@arm.com            visited = False
96810195SGeoffrey.Blake@arm.com            if hasattr(child, '_visited'):
96910195SGeoffrey.Blake@arm.com              visited = getattr(child, '_visited')
97010195SGeoffrey.Blake@arm.com
97110195SGeoffrey.Blake@arm.com            if isinstance(child, ptype) and not visited:
9721692SN/A                if found_obj != None and child != found_obj:
9731692SN/A                    raise AttributeError, \
9741692SN/A                          'parent.any matched more than one: %s %s' % \
9751814SN/A                          (found_obj.path, child.path)
9761692SN/A                found_obj = child
9771692SN/A        # search param space
9781692SN/A        for pname,pdesc in self._params.iteritems():
9791692SN/A            if issubclass(pdesc.ptype, ptype):
9801692SN/A                match_obj = self._values[pname]
9811692SN/A                if found_obj != None and found_obj != match_obj:
9821692SN/A                    raise AttributeError, \
9835952Ssaidi@eecs.umich.edu                          'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path)
9841692SN/A                found_obj = match_obj
9851692SN/A        return found_obj, found_obj != None
9861692SN/A
9878459SAli.Saidi@ARM.com    def find_all(self, ptype):
9888459SAli.Saidi@ARM.com        all = {}
9898459SAli.Saidi@ARM.com        # search children
9908459SAli.Saidi@ARM.com        for child in self._children.itervalues():
9919410Sandreas.hansson@arm.com            # a child could be a list, so ensure we visit each item
9929410Sandreas.hansson@arm.com            if isinstance(child, list):
9939410Sandreas.hansson@arm.com                children = child
9949410Sandreas.hansson@arm.com            else:
9959410Sandreas.hansson@arm.com                children = [child]
9969410Sandreas.hansson@arm.com
9979410Sandreas.hansson@arm.com            for child in children:
9989410Sandreas.hansson@arm.com                if isinstance(child, ptype) and not isproxy(child) and \
9999410Sandreas.hansson@arm.com                        not isNullPointer(child):
10009410Sandreas.hansson@arm.com                    all[child] = True
10019410Sandreas.hansson@arm.com                if isSimObject(child):
10029410Sandreas.hansson@arm.com                    # also add results from the child itself
10039410Sandreas.hansson@arm.com                    child_all, done = child.find_all(ptype)
10049410Sandreas.hansson@arm.com                    all.update(dict(zip(child_all, [done] * len(child_all))))
10058459SAli.Saidi@ARM.com        # search param space
10068459SAli.Saidi@ARM.com        for pname,pdesc in self._params.iteritems():
10078459SAli.Saidi@ARM.com            if issubclass(pdesc.ptype, ptype):
10088459SAli.Saidi@ARM.com                match_obj = self._values[pname]
10098459SAli.Saidi@ARM.com                if not isproxy(match_obj) and not isNullPointer(match_obj):
10108459SAli.Saidi@ARM.com                    all[match_obj] = True
10118459SAli.Saidi@ARM.com        return all.keys(), True
10128459SAli.Saidi@ARM.com
10131815SN/A    def unproxy(self, base):
10141815SN/A        return self
10151815SN/A
10167527Ssteve.reinhardt@amd.com    def unproxyParams(self):
10173105Sstever@eecs.umich.edu        for param in self._params.iterkeys():
10183105Sstever@eecs.umich.edu            value = self._values.get(param)
10196654Snate@binkert.org            if value != None and isproxy(value):
10203105Sstever@eecs.umich.edu                try:
10213105Sstever@eecs.umich.edu                    value = value.unproxy(self)
10223105Sstever@eecs.umich.edu                except:
10233105Sstever@eecs.umich.edu                    print "Error in unproxying param '%s' of %s" % \
10243105Sstever@eecs.umich.edu                          (param, self.path())
10253105Sstever@eecs.umich.edu                    raise
10263105Sstever@eecs.umich.edu                setattr(self, param, value)
10273105Sstever@eecs.umich.edu
10283107Sstever@eecs.umich.edu        # Unproxy ports in sorted order so that 'append' operations on
10293107Sstever@eecs.umich.edu        # vector ports are done in a deterministic fashion.
10303107Sstever@eecs.umich.edu        port_names = self._ports.keys()
10313107Sstever@eecs.umich.edu        port_names.sort()
10323107Sstever@eecs.umich.edu        for port_name in port_names:
10333105Sstever@eecs.umich.edu            port = self._port_refs.get(port_name)
10343105Sstever@eecs.umich.edu            if port != None:
10353105Sstever@eecs.umich.edu                port.unproxy(self)
10363105Sstever@eecs.umich.edu
10375037Smilesck@eecs.umich.edu    def print_ini(self, ini_file):
10385543Ssaidi@eecs.umich.edu        print >>ini_file, '[' + self.path() + ']'       # .ini section header
10391692SN/A
10402738SN/A        instanceDict[self.path()] = self
10412738SN/A
10424081Sbinkertn@umich.edu        if hasattr(self, 'type'):
10435037Smilesck@eecs.umich.edu            print >>ini_file, 'type=%s' % self.type
10441692SN/A
10458664SAli.Saidi@ARM.com        if len(self._children.keys()):
10467528Ssteve.reinhardt@amd.com            print >>ini_file, 'children=%s' % \
10478664SAli.Saidi@ARM.com                  ' '.join(self._children[n].get_name() \
10488664SAli.Saidi@ARM.com                  for n in sorted(self._children.keys()))
10491692SN/A
10508664SAli.Saidi@ARM.com        for param in sorted(self._params.keys()):
10513105Sstever@eecs.umich.edu            value = self._values.get(param)
10521692SN/A            if value != None:
10535037Smilesck@eecs.umich.edu                print >>ini_file, '%s=%s' % (param,
10545037Smilesck@eecs.umich.edu                                             self._values[param].ini_str())
10551692SN/A
10568664SAli.Saidi@ARM.com        for port_name in sorted(self._ports.keys()):
10573105Sstever@eecs.umich.edu            port = self._port_refs.get(port_name, None)
10583105Sstever@eecs.umich.edu            if port != None:
10595037Smilesck@eecs.umich.edu                print >>ini_file, '%s=%s' % (port_name, port.ini_str())
10603103Sstever@eecs.umich.edu
10615543Ssaidi@eecs.umich.edu        print >>ini_file        # blank line between objects
10621692SN/A
10638664SAli.Saidi@ARM.com    # generate a tree of dictionaries expressing all the parameters in the
10648664SAli.Saidi@ARM.com    # instantiated system for use by scripts that want to do power, thermal
10658664SAli.Saidi@ARM.com    # visualization, and other similar tasks
10668664SAli.Saidi@ARM.com    def get_config_as_dict(self):
10678664SAli.Saidi@ARM.com        d = attrdict()
10688664SAli.Saidi@ARM.com        if hasattr(self, 'type'):
10698664SAli.Saidi@ARM.com            d.type = self.type
10708664SAli.Saidi@ARM.com        if hasattr(self, 'cxx_class'):
10718664SAli.Saidi@ARM.com            d.cxx_class = self.cxx_class
10729017Sandreas.hansson@arm.com        # Add the name and path of this object to be able to link to
10739017Sandreas.hansson@arm.com        # the stats
10749017Sandreas.hansson@arm.com        d.name = self.get_name()
10759017Sandreas.hansson@arm.com        d.path = self.path()
10768664SAli.Saidi@ARM.com
10778664SAli.Saidi@ARM.com        for param in sorted(self._params.keys()):
10788664SAli.Saidi@ARM.com            value = self._values.get(param)
10798848Ssteve.reinhardt@amd.com            if value != None:
10808848Ssteve.reinhardt@amd.com                try:
10818848Ssteve.reinhardt@amd.com                    # Use native type for those supported by JSON and
10828848Ssteve.reinhardt@amd.com                    # strings for everything else. skipkeys=True seems
10838848Ssteve.reinhardt@amd.com                    # to not work as well as one would hope
10848848Ssteve.reinhardt@amd.com                    if type(self._values[param].value) in \
10858848Ssteve.reinhardt@amd.com                            [str, unicode, int, long, float, bool, None]:
10868848Ssteve.reinhardt@amd.com                        d[param] = self._values[param].value
10878848Ssteve.reinhardt@amd.com                    else:
10888848Ssteve.reinhardt@amd.com                        d[param] = str(self._values[param])
10898669Ssaidi@eecs.umich.edu
10908848Ssteve.reinhardt@amd.com                except AttributeError:
10918848Ssteve.reinhardt@amd.com                    pass
10928664SAli.Saidi@ARM.com
10938664SAli.Saidi@ARM.com        for n in sorted(self._children.keys()):
10949017Sandreas.hansson@arm.com            child = self._children[n]
10959017Sandreas.hansson@arm.com            # Use the name of the attribute (and not get_name()) as
10969017Sandreas.hansson@arm.com            # the key in the JSON dictionary to capture the hierarchy
10979017Sandreas.hansson@arm.com            # in the Python code that assembled this system
10989017Sandreas.hansson@arm.com            d[n] = child.get_config_as_dict()
10998664SAli.Saidi@ARM.com
11008664SAli.Saidi@ARM.com        for port_name in sorted(self._ports.keys()):
11018664SAli.Saidi@ARM.com            port = self._port_refs.get(port_name, None)
11028664SAli.Saidi@ARM.com            if port != None:
11039017Sandreas.hansson@arm.com                # Represent each port with a dictionary containing the
11049017Sandreas.hansson@arm.com                # prominent attributes
11059017Sandreas.hansson@arm.com                d[port_name] = port.get_config_as_dict()
11068664SAli.Saidi@ARM.com
11078664SAli.Saidi@ARM.com        return d
11088664SAli.Saidi@ARM.com
11094762Snate@binkert.org    def getCCParams(self):
11104762Snate@binkert.org        if self._ccParams:
11114762Snate@binkert.org            return self._ccParams
11124762Snate@binkert.org
11137677Snate@binkert.org        cc_params_struct = getattr(m5.internal.params, '%sParams' % self.type)
11144762Snate@binkert.org        cc_params = cc_params_struct()
11155488Snate@binkert.org        cc_params.pyobj = self
11164762Snate@binkert.org        cc_params.name = str(self)
11174762Snate@binkert.org
11184762Snate@binkert.org        param_names = self._params.keys()
11194762Snate@binkert.org        param_names.sort()
11204762Snate@binkert.org        for param in param_names:
11214762Snate@binkert.org            value = self._values.get(param)
11224762Snate@binkert.org            if value is None:
11236654Snate@binkert.org                fatal("%s.%s without default or user set value",
11246654Snate@binkert.org                      self.path(), param)
11254762Snate@binkert.org
11264762Snate@binkert.org            value = value.getValue()
11274762Snate@binkert.org            if isinstance(self._params[param], VectorParamDesc):
11284762Snate@binkert.org                assert isinstance(value, list)
11294762Snate@binkert.org                vec = getattr(cc_params, param)
11304762Snate@binkert.org                assert not len(vec)
11314762Snate@binkert.org                for v in value:
11324762Snate@binkert.org                    vec.append(v)
11334762Snate@binkert.org            else:
11344762Snate@binkert.org                setattr(cc_params, param, value)
11354762Snate@binkert.org
11364762Snate@binkert.org        port_names = self._ports.keys()
11374762Snate@binkert.org        port_names.sort()
11384762Snate@binkert.org        for port_name in port_names:
11394762Snate@binkert.org            port = self._port_refs.get(port_name, None)
11408912Sandreas.hansson@arm.com            if port != None:
11418912Sandreas.hansson@arm.com                port_count = len(port)
11428912Sandreas.hansson@arm.com            else:
11438912Sandreas.hansson@arm.com                port_count = 0
11448900Sandreas.hansson@arm.com            setattr(cc_params, 'port_' + port_name + '_connection_count',
11458912Sandreas.hansson@arm.com                    port_count)
11464762Snate@binkert.org        self._ccParams = cc_params
11474762Snate@binkert.org        return self._ccParams
11482738SN/A
11492740SN/A    # Get C++ object corresponding to this object, calling C++ if
11502740SN/A    # necessary to construct it.  Does *not* recursively create
11512740SN/A    # children.
11522740SN/A    def getCCObject(self):
11532740SN/A        if not self._ccObject:
11547526Ssteve.reinhardt@amd.com            # Make sure this object is in the configuration hierarchy
11557526Ssteve.reinhardt@amd.com            if not self._parent and not isRoot(self):
11567526Ssteve.reinhardt@amd.com                raise RuntimeError, "Attempt to instantiate orphan node"
11577526Ssteve.reinhardt@amd.com            # Cycles in the configuration hierarchy are not supported. This
11585244Sgblack@eecs.umich.edu            # will catch the resulting recursion and stop.
11595244Sgblack@eecs.umich.edu            self._ccObject = -1
116010267SGeoffrey.Blake@arm.com            if not self.abstract:
116110267SGeoffrey.Blake@arm.com                params = self.getCCParams()
116210267SGeoffrey.Blake@arm.com                self._ccObject = params.create()
11632740SN/A        elif self._ccObject == -1:
11647526Ssteve.reinhardt@amd.com            raise RuntimeError, "%s: Cycle found in configuration hierarchy." \
11652740SN/A                  % self.path()
11662740SN/A        return self._ccObject
11672740SN/A
11687527Ssteve.reinhardt@amd.com    def descendants(self):
11697527Ssteve.reinhardt@amd.com        yield self
11707527Ssteve.reinhardt@amd.com        for child in self._children.itervalues():
11717527Ssteve.reinhardt@amd.com            for obj in child.descendants():
11727527Ssteve.reinhardt@amd.com                yield obj
11737527Ssteve.reinhardt@amd.com
11747527Ssteve.reinhardt@amd.com    # Call C++ to create C++ object corresponding to this object
11754762Snate@binkert.org    def createCCObject(self):
11764762Snate@binkert.org        self.getCCParams()
11774762Snate@binkert.org        self.getCCObject() # force creation
11784762Snate@binkert.org
11794762Snate@binkert.org    def getValue(self):
11804762Snate@binkert.org        return self.getCCObject()
11814762Snate@binkert.org
11822738SN/A    # Create C++ port connections corresponding to the connections in
11837527Ssteve.reinhardt@amd.com    # _port_refs
11842738SN/A    def connectPorts(self):
11853105Sstever@eecs.umich.edu        for portRef in self._port_refs.itervalues():
11863105Sstever@eecs.umich.edu            portRef.ccConnect()
11872797SN/A
11883101Sstever@eecs.umich.edu# Function to provide to C++ so it can look up instances based on paths
11893101Sstever@eecs.umich.edudef resolveSimObject(name):
11903101Sstever@eecs.umich.edu    obj = instanceDict[name]
11913101Sstever@eecs.umich.edu    return obj.getCCObject()
1192679SN/A
11936654Snate@binkert.orgdef isSimObject(value):
11946654Snate@binkert.org    return isinstance(value, SimObject)
11956654Snate@binkert.org
11966654Snate@binkert.orgdef isSimObjectClass(value):
11976654Snate@binkert.org    return issubclass(value, SimObject)
11986654Snate@binkert.org
11997528Ssteve.reinhardt@amd.comdef isSimObjectVector(value):
12007528Ssteve.reinhardt@amd.com    return isinstance(value, SimObjectVector)
12017528Ssteve.reinhardt@amd.com
12026654Snate@binkert.orgdef isSimObjectSequence(value):
12036654Snate@binkert.org    if not isinstance(value, (list, tuple)) or len(value) == 0:
12046654Snate@binkert.org        return False
12056654Snate@binkert.org
12066654Snate@binkert.org    for val in value:
12076654Snate@binkert.org        if not isNullPointer(val) and not isSimObject(val):
12086654Snate@binkert.org            return False
12096654Snate@binkert.org
12106654Snate@binkert.org    return True
12116654Snate@binkert.org
12126654Snate@binkert.orgdef isSimObjectOrSequence(value):
12136654Snate@binkert.org    return isSimObject(value) or isSimObjectSequence(value)
12146654Snate@binkert.org
12157526Ssteve.reinhardt@amd.comdef isRoot(obj):
12167526Ssteve.reinhardt@amd.com    from m5.objects import Root
12177526Ssteve.reinhardt@amd.com    return obj and obj is Root.getInstance()
12187526Ssteve.reinhardt@amd.com
12197528Ssteve.reinhardt@amd.comdef isSimObjectOrVector(value):
12207528Ssteve.reinhardt@amd.com    return isSimObject(value) or isSimObjectVector(value)
12217528Ssteve.reinhardt@amd.com
12227528Ssteve.reinhardt@amd.comdef tryAsSimObjectOrVector(value):
12237528Ssteve.reinhardt@amd.com    if isSimObjectOrVector(value):
12247528Ssteve.reinhardt@amd.com        return value
12257528Ssteve.reinhardt@amd.com    if isSimObjectSequence(value):
12267528Ssteve.reinhardt@amd.com        return SimObjectVector(value)
12277528Ssteve.reinhardt@amd.com    return None
12287528Ssteve.reinhardt@amd.com
12297528Ssteve.reinhardt@amd.comdef coerceSimObjectOrVector(value):
12307528Ssteve.reinhardt@amd.com    value = tryAsSimObjectOrVector(value)
12317528Ssteve.reinhardt@amd.com    if value is None:
12327528Ssteve.reinhardt@amd.com        raise TypeError, "SimObject or SimObjectVector expected"
12337528Ssteve.reinhardt@amd.com    return value
12347528Ssteve.reinhardt@amd.com
12356654Snate@binkert.orgbaseClasses = allClasses.copy()
12366654Snate@binkert.orgbaseInstances = instanceDict.copy()
12376654Snate@binkert.org
12386654Snate@binkert.orgdef clear():
12399338SAndreas.Sandberg@arm.com    global allClasses, instanceDict, noCxxHeader
12406654Snate@binkert.org
12416654Snate@binkert.org    allClasses = baseClasses.copy()
12426654Snate@binkert.org    instanceDict = baseInstances.copy()
12439338SAndreas.Sandberg@arm.com    noCxxHeader = False
12446654Snate@binkert.org
12451528SN/A# __all__ defines the list of symbols that get exported when
12461528SN/A# 'from config import *' is invoked.  Try to keep this reasonably
12471528SN/A# short to avoid polluting other namespaces.
12484762Snate@binkert.org__all__ = [ 'SimObject' ]
1249