simobject.py

来自「M5,一个功能强大的多处理器系统模拟器.很多针对处理器架构,性能的研究都使用它作」· Python 代码 · 共 911 行 · 第 1/3 页

PY
911
字号
# Copyright (c) 2004, 2005, 2006# The Regents of The University of Michigan# All Rights Reserved## This code is part of the M5 simulator.## Permission is granted to use, copy, create derivative works and# redistribute this software and such derivative works for any# purpose, so long as the copyright notice above, this grant of# permission, and the disclaimer below appear in all copies made; and# so long as the name of The University of Michigan is not used in any# advertising or publicity pertaining to the use or distribution of# this software without specific, written prior authorization.## THIS SOFTWARE IS PROVIDED AS IS, WITHOUT REPRESENTATION FROM THE# UNIVERSITY OF MICHIGAN AS TO ITS FITNESS FOR ANY PURPOSE, AND# WITHOUT WARRANTY BY THE UNIVERSITY OF MICHIGAN OF ANY KIND, EITHER# EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR# PURPOSE. THE REGENTS OF THE UNIVERSITY OF MICHIGAN SHALL NOT BE# LIABLE FOR ANY DAMAGES, INCLUDING DIRECT, SPECIAL, INDIRECT,# INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WITH RESPECT TO ANY CLAIM# ARISING OUT OF OR IN CONNECTION WITH THE USE OF THE SOFTWARE, EVEN# IF IT HAS BEEN OR IS HEREAFTER ADVISED OF THE POSSIBILITY OF SUCH# DAMAGES.## Authors: Steven K. Reinhardt#          Nathan L. Binkertimport sys, typesimport proxyimport m5from util import *from multidict import multidict# These utility functions have to come first because they're# referenced in params.py... otherwise they won't be defined when we# import params below, and the recursive import of this file from# params.py will not find these names.def isSimObject(value):    return isinstance(value, SimObject)def isSimObjectClass(value):    return issubclass(value, SimObject)def isSimObjectSequence(value):    if not isinstance(value, (list, tuple)) or len(value) == 0:        return False    for val in value:        if not isNullPointer(val) and not isSimObject(val):            return False    return Truedef isSimObjectOrSequence(value):    return isSimObject(value) or isSimObjectSequence(value)# Have to import params up top since Param is referenced on initial# load (when SimObject class references Param to create a class# variable, the 'name' param)...from params import *# There are a few things we need that aren't in params.__all__ since# normal users don't need themfrom params import ParamDesc, VectorParamDesc, isNullPointer, SimObjVectornoDot = Falsetry:    import pydotexcept:    noDot = True####################################################################### M5 Python Configuration Utility## The basic idea is to write simple Python programs that build Python# objects corresponding to M5 SimObjects for the desired simulation# configuration.  For now, the Python emits a .ini file that can be# parsed by M5.  In the future, some tighter integration between M5# and the Python interpreter may allow bypassing the .ini file.## Each SimObject class in M5 is represented by a Python class with the# same name.  The Python inheritance tree mirrors the M5 C++ tree# (e.g., SimpleCPU derives from BaseCPU in both cases, and all# SimObjects inherit from a single SimObject base class).  To specify# an instance of an M5 SimObject in a configuration, the user simply# instantiates the corresponding Python object.  The parameters for# that SimObject are given by assigning to attributes of the Python# object, either using keyword assignment in the constructor or in# separate assignment statements.  For example:## cache = BaseCache(size='64KB')# cache.hit_latency = 3# cache.assoc = 8## The magic lies in the mapping of the Python attributes for SimObject# classes to the actual SimObject parameter specifications.  This# allows parameter validity checking in the Python code.  Continuing# the example above, the statements "cache.blurfl=3" or# "cache.assoc='hello'" would both result in runtime errors in Python,# since the BaseCache object has no 'blurfl' parameter and the 'assoc'# parameter requires an integer, respectively.  This magic is done# primarily by overriding the special __setattr__ method that controls# assignment to object attributes.## Once a set of Python objects have been instantiated in a hierarchy,# calling 'instantiate(obj)' (where obj is the root of the hierarchy)# will generate a .ini file.####################################################################### list of all SimObject classesallClasses = {}# dict to look up SimObjects based on pathinstanceDict = {}# The metaclass for SimObject.  This class controls how new classes# that derive from SimObject are instantiated, and provides inherited# class behavior (just like a class controls how instances of that# class are instantiated, and provides inherited instance behavior).class MetaSimObject(type):    # Attributes that can be set only at initialization time    init_keywords = { 'abstract' : types.BooleanType,                      'cxx_namespace' : types.StringType,                      'cxx_class' : types.StringType,                      'cxx_type' : types.StringType,                      'cxx_predecls' : types.ListType,                      'swig_objdecls' : types.ListType,                      'swig_predecls' : types.ListType,                      'type' : types.StringType }    # Attributes that can be set any time    keywords = { 'check' : types.FunctionType }    # __new__ is called before __init__, and is where the statements    # in the body of the class definition get loaded into the class's    # __dict__.  We intercept this to filter out parameter & port assignments    # and only allow "private" attributes to be passed to the base    # __new__ (starting with underscore).    def __new__(mcls, name, bases, dict):        assert name not in allClasses        # Copy "private" attributes, functions, and classes to the        # official dict.  Everything else goes in _init_dict to be        # filtered in __init__.        cls_dict = {}        value_dict = {}        for key,val in dict.items():            if key.startswith('_') or isinstance(val, (types.FunctionType,                                                       types.TypeType)):                cls_dict[key] = val            else:                # must be a param/port setting                value_dict[key] = val        if 'abstract' not in value_dict:            value_dict['abstract'] = False        cls_dict['_value_dict'] = value_dict        cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict)        if 'type' in value_dict:            allClasses[name] = cls        return cls    # subclass initialization    def __init__(cls, name, bases, dict):        # calls type.__init__()... I think that's a no-op, but leave        # it here just in case it's not.        super(MetaSimObject, cls).__init__(name, bases, dict)        # initialize required attributes        # class-only attributes        cls._params = multidict() # param descriptions        cls._ports = multidict()  # port descriptions        # class or instance attributes        cls._values = multidict()   # param values        cls._port_refs = multidict() # port ref objects        cls._instantiated = False # really instantiated, cloned, or subclassed        # We don't support multiple inheritance.  If you want to, you        # must fix multidict to deal with it properly.        if len(bases) > 1:            raise TypeError, "SimObjects do not support multiple inheritance"        base = bases[0]        # Set up general inheritance via multidicts.  A subclass will        # inherit all its settings from the base class.  The only time        # the following is not true is when we define the SimObject        # class itself (in which case the multidicts have no parent).        if isinstance(base, MetaSimObject):            cls._params.parent = base._params            cls._ports.parent = base._ports            cls._values.parent = base._values            cls._port_refs.parent = base._port_refs            # mark base as having been subclassed            base._instantiated = True        # default keyword values        if 'type' in cls._value_dict:            _type = cls._value_dict['type']            if 'cxx_class' not in cls._value_dict:                cls._value_dict['cxx_class'] = _type            namespace = cls._value_dict.get('cxx_namespace', None)            _cxx_class = cls._value_dict['cxx_class']            if 'cxx_type' not in cls._value_dict:                t = _cxx_class + '*'                if namespace:                    t = '%s::%s' % (namespace, t)                cls._value_dict['cxx_type'] = t            if 'cxx_predecls' not in cls._value_dict:                # A forward class declaration is sufficient since we are                # just declaring a pointer.                decl = 'class %s;' % _cxx_class                if namespace:                    decl = 'namespace %s { %s }' % (namespace, decl)                cls._value_dict['cxx_predecls'] = [decl]            if 'swig_predecls' not in cls._value_dict:                # A forward class declaration is sufficient since we are                # just declaring a pointer.                cls._value_dict['swig_predecls'] = \                    cls._value_dict['cxx_predecls']        if 'swig_objdecls' not in cls._value_dict:            cls._value_dict['swig_objdecls'] = []        # Now process the _value_dict items.  They could be defining        # new (or overriding existing) parameters or ports, setting        # class keywords (e.g., 'abstract'), or setting parameter        # values or port bindings.  The first 3 can only be set when        # the class is defined, so we handle them here.  The others        # can be set later too, so just emulate that by calling        # setattr().        for key,val in cls._value_dict.items():            # param descriptions            if isinstance(val, ParamDesc):                cls._new_param(key, val)            # port objects            elif isinstance(val, Port):                cls._new_port(key, val)            # init-time-only keywords            elif cls.init_keywords.has_key(key):                cls._set_keyword(key, val, cls.init_keywords[key])            # default: use normal path (ends up in __setattr__)            else:                setattr(cls, key, val)    def _set_keyword(cls, keyword, val, kwtype):        if not isinstance(val, kwtype):            raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \                  (keyword, type(val), kwtype)        if isinstance(val, types.FunctionType):            val = classmethod(val)        type.__setattr__(cls, keyword, val)    def _new_param(cls, name, pdesc):        # each param desc should be uniquely assigned to one variable        assert(not hasattr(pdesc, 'name'))        pdesc.name = name        cls._params[name] = pdesc        if hasattr(pdesc, 'default'):            cls._set_param(name, pdesc.default, pdesc)    def _set_param(cls, name, value, param):        assert(param.name == name)        try:            cls._values[name] = param.convert(value)        except Exception, e:            msg = "%s\nError setting param %s.%s to %s\n" % \                  (e, cls.__name__, name, value)            e.args = (msg, )            raise    def _new_port(cls, name, port):        # each port should be uniquely assigned to one variable        assert(not hasattr(port, 'name'))        port.name = name        cls._ports[name] = port        if hasattr(port, 'default'):            cls._cls_get_port_ref(name).connect(port.default)    # same as _get_port_ref, effectively, but for classes    def _cls_get_port_ref(cls, attr):        # Return reference that can be assigned to another port        # via __setattr__.  There is only ever one reference        # object per port, but we create them lazily here.        ref = cls._port_refs.get(attr)        if not ref:            ref = cls._ports[attr].makeRef(cls)            cls._port_refs[attr] = ref        return ref    # Set attribute (called on foo.attr = value when foo is an    # instance of class cls).    def __setattr__(cls, attr, value):        # normal processing for private attributes

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?