SimObject.py revision 5766
12740SN/A# Copyright (c) 2004-2006 The Regents of The University of Michigan 21046SN/A# All rights reserved. 31046SN/A# 41046SN/A# Redistribution and use in source and binary forms, with or without 51046SN/A# modification, are permitted provided that the following conditions are 61046SN/A# met: redistributions of source code must retain the above copyright 71046SN/A# notice, this list of conditions and the following disclaimer; 81046SN/A# redistributions in binary form must reproduce the above copyright 91046SN/A# notice, this list of conditions and the following disclaimer in the 101046SN/A# documentation and/or other materials provided with the distribution; 111046SN/A# neither the name of the copyright holders nor the names of its 121046SN/A# contributors may be used to endorse or promote products derived from 131046SN/A# this software without specific prior written permission. 141046SN/A# 151046SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 161046SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 171046SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 181046SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 191046SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 201046SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 211046SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 221046SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 231046SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 241046SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 251046SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 262665SN/A# 272665SN/A# Authors: Steve Reinhardt 282665SN/A# Nathan Binkert 291046SN/A 305766Snate@binkert.orgimport math 315766Snate@binkert.orgimport sys 325766Snate@binkert.orgimport types 331438SN/A 344762Snate@binkert.orgimport proxy 354762Snate@binkert.orgimport m5 363102Sstever@eecs.umich.edufrom util import * 371438SN/A 383102Sstever@eecs.umich.edu# These utility functions have to come first because they're 393102Sstever@eecs.umich.edu# referenced in params.py... otherwise they won't be defined when we 403102Sstever@eecs.umich.edu# import params below, and the recursive import of this file from 413102Sstever@eecs.umich.edu# params.py will not find these names. 423102Sstever@eecs.umich.edudef isSimObject(value): 433102Sstever@eecs.umich.edu return isinstance(value, SimObject) 443102Sstever@eecs.umich.edu 453102Sstever@eecs.umich.edudef isSimObjectClass(value): 463102Sstever@eecs.umich.edu return issubclass(value, SimObject) 473102Sstever@eecs.umich.edu 483102Sstever@eecs.umich.edudef isSimObjectSequence(value): 493102Sstever@eecs.umich.edu if not isinstance(value, (list, tuple)) or len(value) == 0: 503102Sstever@eecs.umich.edu return False 513102Sstever@eecs.umich.edu 523102Sstever@eecs.umich.edu for val in value: 533102Sstever@eecs.umich.edu if not isNullPointer(val) and not isSimObject(val): 543102Sstever@eecs.umich.edu return False 553102Sstever@eecs.umich.edu 563102Sstever@eecs.umich.edu return True 573102Sstever@eecs.umich.edu 583102Sstever@eecs.umich.edudef isSimObjectOrSequence(value): 593102Sstever@eecs.umich.edu return isSimObject(value) or isSimObjectSequence(value) 603102Sstever@eecs.umich.edu 613102Sstever@eecs.umich.edu# Have to import params up top since Param is referenced on initial 623102Sstever@eecs.umich.edu# load (when SimObject class references Param to create a class 633102Sstever@eecs.umich.edu# variable, the 'name' param)... 643102Sstever@eecs.umich.edufrom params import * 653102Sstever@eecs.umich.edu# There are a few things we need that aren't in params.__all__ since 663102Sstever@eecs.umich.edu# normal users don't need them 674762Snate@binkert.orgfrom params import ParamDesc, VectorParamDesc, isNullPointer, SimObjVector 683102Sstever@eecs.umich.edu 691342SN/AnoDot = False 701342SN/Atry: 711378SN/A import pydot 721342SN/Aexcept: 731378SN/A noDot = True 74679SN/A 75679SN/A##################################################################### 76679SN/A# 77679SN/A# M5 Python Configuration Utility 78679SN/A# 79679SN/A# The basic idea is to write simple Python programs that build Python 801692SN/A# objects corresponding to M5 SimObjects for the desired simulation 81679SN/A# configuration. For now, the Python emits a .ini file that can be 82679SN/A# parsed by M5. In the future, some tighter integration between M5 83679SN/A# and the Python interpreter may allow bypassing the .ini file. 84679SN/A# 85679SN/A# Each SimObject class in M5 is represented by a Python class with the 86679SN/A# same name. The Python inheritance tree mirrors the M5 C++ tree 87679SN/A# (e.g., SimpleCPU derives from BaseCPU in both cases, and all 88679SN/A# SimObjects inherit from a single SimObject base class). To specify 89679SN/A# an instance of an M5 SimObject in a configuration, the user simply 90679SN/A# instantiates the corresponding Python object. The parameters for 91679SN/A# that SimObject are given by assigning to attributes of the Python 92679SN/A# object, either using keyword assignment in the constructor or in 93679SN/A# separate assignment statements. For example: 94679SN/A# 951692SN/A# cache = BaseCache(size='64KB') 96679SN/A# cache.hit_latency = 3 97679SN/A# cache.assoc = 8 98679SN/A# 99679SN/A# The magic lies in the mapping of the Python attributes for SimObject 100679SN/A# classes to the actual SimObject parameter specifications. This 101679SN/A# allows parameter validity checking in the Python code. Continuing 102679SN/A# the example above, the statements "cache.blurfl=3" or 103679SN/A# "cache.assoc='hello'" would both result in runtime errors in Python, 104679SN/A# since the BaseCache object has no 'blurfl' parameter and the 'assoc' 105679SN/A# parameter requires an integer, respectively. This magic is done 106679SN/A# primarily by overriding the special __setattr__ method that controls 107679SN/A# assignment to object attributes. 108679SN/A# 109679SN/A# Once a set of Python objects have been instantiated in a hierarchy, 110679SN/A# calling 'instantiate(obj)' (where obj is the root of the hierarchy) 1112740SN/A# will generate a .ini file. 112679SN/A# 113679SN/A##################################################################### 114679SN/A 1154762Snate@binkert.org# list of all SimObject classes 1164762Snate@binkert.orgallClasses = {} 1174762Snate@binkert.org 1182738SN/A# dict to look up SimObjects based on path 1192738SN/AinstanceDict = {} 1202738SN/A 1212740SN/A# The metaclass for SimObject. This class controls how new classes 1222740SN/A# that derive from SimObject are instantiated, and provides inherited 1232740SN/A# class behavior (just like a class controls how instances of that 1242740SN/A# class are instantiated, and provides inherited instance behavior). 1251692SN/Aclass MetaSimObject(type): 1261427SN/A # Attributes that can be set only at initialization time 1271692SN/A init_keywords = { 'abstract' : types.BooleanType, 1284762Snate@binkert.org 'cxx_class' : types.StringType, 1294762Snate@binkert.org 'cxx_type' : types.StringType, 1304762Snate@binkert.org 'cxx_predecls' : types.ListType, 1314859Snate@binkert.org 'swig_objdecls' : types.ListType, 1324762Snate@binkert.org 'swig_predecls' : types.ListType, 1331692SN/A 'type' : types.StringType } 1341427SN/A # Attributes that can be set any time 1354762Snate@binkert.org keywords = { 'check' : types.FunctionType } 136679SN/A 137679SN/A # __new__ is called before __init__, and is where the statements 138679SN/A # in the body of the class definition get loaded into the class's 1392740SN/A # __dict__. We intercept this to filter out parameter & port assignments 140679SN/A # and only allow "private" attributes to be passed to the base 141679SN/A # __new__ (starting with underscore). 1421310SN/A def __new__(mcls, name, bases, dict): 1434762Snate@binkert.org assert name not in allClasses 1444762Snate@binkert.org 1452740SN/A # Copy "private" attributes, functions, and classes to the 1462740SN/A # official dict. Everything else goes in _init_dict to be 1472740SN/A # filtered in __init__. 1482740SN/A cls_dict = {} 1492740SN/A value_dict = {} 1502740SN/A for key,val in dict.items(): 1512740SN/A if key.startswith('_') or isinstance(val, (types.FunctionType, 1522740SN/A types.TypeType)): 1532740SN/A cls_dict[key] = val 1542740SN/A else: 1552740SN/A # must be a param/port setting 1562740SN/A value_dict[key] = val 1574762Snate@binkert.org if 'abstract' not in value_dict: 1584762Snate@binkert.org value_dict['abstract'] = False 1592740SN/A cls_dict['_value_dict'] = value_dict 1604762Snate@binkert.org cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict) 1614762Snate@binkert.org if 'type' in value_dict: 1624762Snate@binkert.org allClasses[name] = cls 1634762Snate@binkert.org return cls 164679SN/A 1652711SN/A # subclass initialization 166679SN/A def __init__(cls, name, bases, dict): 1672711SN/A # calls type.__init__()... I think that's a no-op, but leave 1682711SN/A # it here just in case it's not. 1691692SN/A super(MetaSimObject, cls).__init__(name, bases, dict) 1701310SN/A 1711427SN/A # initialize required attributes 1722740SN/A 1732740SN/A # class-only attributes 1742740SN/A cls._params = multidict() # param descriptions 1752740SN/A cls._ports = multidict() # port descriptions 1762740SN/A 1772740SN/A # class or instance attributes 1782740SN/A cls._values = multidict() # param values 1793105Sstever@eecs.umich.edu cls._port_refs = multidict() # port ref objects 1802740SN/A cls._instantiated = False # really instantiated, cloned, or subclassed 1811310SN/A 1821692SN/A # We don't support multiple inheritance. If you want to, you 1831585SN/A # must fix multidict to deal with it properly. 1841692SN/A if len(bases) > 1: 1851692SN/A raise TypeError, "SimObjects do not support multiple inheritance" 1861692SN/A 1871692SN/A base = bases[0] 1881692SN/A 1892740SN/A # Set up general inheritance via multidicts. A subclass will 1902740SN/A # inherit all its settings from the base class. The only time 1912740SN/A # the following is not true is when we define the SimObject 1922740SN/A # class itself (in which case the multidicts have no parent). 1931692SN/A if isinstance(base, MetaSimObject): 1945610Snate@binkert.org cls._base = base 1951692SN/A cls._params.parent = base._params 1962740SN/A cls._ports.parent = base._ports 1971692SN/A cls._values.parent = base._values 1983105Sstever@eecs.umich.edu cls._port_refs.parent = base._port_refs 1992740SN/A # mark base as having been subclassed 2002712SN/A base._instantiated = True 2015610Snate@binkert.org else: 2025610Snate@binkert.org cls._base = None 2031692SN/A 2044762Snate@binkert.org # default keyword values 2054762Snate@binkert.org if 'type' in cls._value_dict: 2064762Snate@binkert.org if 'cxx_class' not in cls._value_dict: 2075610Snate@binkert.org cls._value_dict['cxx_class'] = cls._value_dict['type'] 2084762Snate@binkert.org 2095610Snate@binkert.org cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class'] 2105610Snate@binkert.org 2114762Snate@binkert.org if 'cxx_predecls' not in cls._value_dict: 2124762Snate@binkert.org # A forward class declaration is sufficient since we are 2134762Snate@binkert.org # just declaring a pointer. 2145610Snate@binkert.org class_path = cls._value_dict['cxx_class'].split('::') 2155610Snate@binkert.org class_path.reverse() 2165610Snate@binkert.org decl = 'class %s;' % class_path[0] 2175610Snate@binkert.org for ns in class_path[1:]: 2185610Snate@binkert.org decl = 'namespace %s { %s }' % (ns, decl) 2194762Snate@binkert.org cls._value_dict['cxx_predecls'] = [decl] 2204762Snate@binkert.org 2214762Snate@binkert.org if 'swig_predecls' not in cls._value_dict: 2224762Snate@binkert.org # A forward class declaration is sufficient since we are 2234762Snate@binkert.org # just declaring a pointer. 2244762Snate@binkert.org cls._value_dict['swig_predecls'] = \ 2254762Snate@binkert.org cls._value_dict['cxx_predecls'] 2264762Snate@binkert.org 2274859Snate@binkert.org if 'swig_objdecls' not in cls._value_dict: 2284859Snate@binkert.org cls._value_dict['swig_objdecls'] = [] 2294859Snate@binkert.org 2302740SN/A # Now process the _value_dict items. They could be defining 2312740SN/A # new (or overriding existing) parameters or ports, setting 2322740SN/A # class keywords (e.g., 'abstract'), or setting parameter 2332740SN/A # values or port bindings. The first 3 can only be set when 2342740SN/A # the class is defined, so we handle them here. The others 2352740SN/A # can be set later too, so just emulate that by calling 2362740SN/A # setattr(). 2372740SN/A for key,val in cls._value_dict.items(): 2381527SN/A # param descriptions 2392740SN/A if isinstance(val, ParamDesc): 2401585SN/A cls._new_param(key, val) 2411427SN/A 2422738SN/A # port objects 2432738SN/A elif isinstance(val, Port): 2443105Sstever@eecs.umich.edu cls._new_port(key, val) 2452738SN/A 2461427SN/A # init-time-only keywords 2471427SN/A elif cls.init_keywords.has_key(key): 2481427SN/A cls._set_keyword(key, val, cls.init_keywords[key]) 2491427SN/A 2501427SN/A # default: use normal path (ends up in __setattr__) 2511427SN/A else: 2521427SN/A setattr(cls, key, val) 2531427SN/A 2541427SN/A def _set_keyword(cls, keyword, val, kwtype): 2551427SN/A if not isinstance(val, kwtype): 2561427SN/A raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \ 2571427SN/A (keyword, type(val), kwtype) 2581427SN/A if isinstance(val, types.FunctionType): 2591427SN/A val = classmethod(val) 2601427SN/A type.__setattr__(cls, keyword, val) 2611427SN/A 2623100SN/A def _new_param(cls, name, pdesc): 2633100SN/A # each param desc should be uniquely assigned to one variable 2643100SN/A assert(not hasattr(pdesc, 'name')) 2653100SN/A pdesc.name = name 2663100SN/A cls._params[name] = pdesc 2673100SN/A if hasattr(pdesc, 'default'): 2683105Sstever@eecs.umich.edu cls._set_param(name, pdesc.default, pdesc) 2693105Sstever@eecs.umich.edu 2703105Sstever@eecs.umich.edu def _set_param(cls, name, value, param): 2713105Sstever@eecs.umich.edu assert(param.name == name) 2723105Sstever@eecs.umich.edu try: 2733105Sstever@eecs.umich.edu cls._values[name] = param.convert(value) 2743105Sstever@eecs.umich.edu except Exception, e: 2753105Sstever@eecs.umich.edu msg = "%s\nError setting param %s.%s to %s\n" % \ 2763105Sstever@eecs.umich.edu (e, cls.__name__, name, value) 2773105Sstever@eecs.umich.edu e.args = (msg, ) 2783105Sstever@eecs.umich.edu raise 2793105Sstever@eecs.umich.edu 2803105Sstever@eecs.umich.edu def _new_port(cls, name, port): 2813105Sstever@eecs.umich.edu # each port should be uniquely assigned to one variable 2823105Sstever@eecs.umich.edu assert(not hasattr(port, 'name')) 2833105Sstever@eecs.umich.edu port.name = name 2843105Sstever@eecs.umich.edu cls._ports[name] = port 2853105Sstever@eecs.umich.edu if hasattr(port, 'default'): 2863105Sstever@eecs.umich.edu cls._cls_get_port_ref(name).connect(port.default) 2873105Sstever@eecs.umich.edu 2883105Sstever@eecs.umich.edu # same as _get_port_ref, effectively, but for classes 2893105Sstever@eecs.umich.edu def _cls_get_port_ref(cls, attr): 2903105Sstever@eecs.umich.edu # Return reference that can be assigned to another port 2913105Sstever@eecs.umich.edu # via __setattr__. There is only ever one reference 2923105Sstever@eecs.umich.edu # object per port, but we create them lazily here. 2933105Sstever@eecs.umich.edu ref = cls._port_refs.get(attr) 2943105Sstever@eecs.umich.edu if not ref: 2953105Sstever@eecs.umich.edu ref = cls._ports[attr].makeRef(cls) 2963105Sstever@eecs.umich.edu cls._port_refs[attr] = ref 2973105Sstever@eecs.umich.edu return ref 2981585SN/A 2991310SN/A # Set attribute (called on foo.attr = value when foo is an 3001310SN/A # instance of class cls). 3011310SN/A def __setattr__(cls, attr, value): 3021310SN/A # normal processing for private attributes 3031310SN/A if attr.startswith('_'): 3041310SN/A type.__setattr__(cls, attr, value) 3051310SN/A return 3061310SN/A 3071310SN/A if cls.keywords.has_key(attr): 3081427SN/A cls._set_keyword(attr, value, cls.keywords[attr]) 3091310SN/A return 3101310SN/A 3112738SN/A if cls._ports.has_key(attr): 3123105Sstever@eecs.umich.edu cls._cls_get_port_ref(attr).connect(value) 3132738SN/A return 3142738SN/A 3152740SN/A if isSimObjectOrSequence(value) and cls._instantiated: 3162740SN/A raise RuntimeError, \ 3172740SN/A "cannot set SimObject parameter '%s' after\n" \ 3182740SN/A " class %s has been instantiated or subclassed" \ 3192740SN/A % (attr, cls.__name__) 3202740SN/A 3212740SN/A # check for param 3223105Sstever@eecs.umich.edu param = cls._params.get(attr) 3231310SN/A if param: 3243105Sstever@eecs.umich.edu cls._set_param(attr, value, param) 3253105Sstever@eecs.umich.edu return 3263105Sstever@eecs.umich.edu 3273105Sstever@eecs.umich.edu if isSimObjectOrSequence(value): 3283105Sstever@eecs.umich.edu # If RHS is a SimObject, it's an implicit child assignment. 3293105Sstever@eecs.umich.edu # Classes don't have children, so we just put this object 3303105Sstever@eecs.umich.edu # in _values; later, each instance will do a 'setattr(self, 3313105Sstever@eecs.umich.edu # attr, _values[attr])' in SimObject.__init__ which will 3323105Sstever@eecs.umich.edu # add this object as a child. 3332740SN/A cls._values[attr] = value 3343105Sstever@eecs.umich.edu return 3353105Sstever@eecs.umich.edu 3363105Sstever@eecs.umich.edu # no valid assignment... raise exception 3373105Sstever@eecs.umich.edu raise AttributeError, \ 3383105Sstever@eecs.umich.edu "Class %s has no parameter \'%s\'" % (cls.__name__, attr) 3391310SN/A 3401585SN/A def __getattr__(cls, attr): 3411692SN/A if cls._values.has_key(attr): 3421692SN/A return cls._values[attr] 3431585SN/A 3441585SN/A raise AttributeError, \ 3451585SN/A "object '%s' has no attribute '%s'" % (cls.__name__, attr) 3461585SN/A 3473100SN/A def __str__(cls): 3483100SN/A return cls.__name__ 3493100SN/A 3503100SN/A def cxx_decl(cls): 3514762Snate@binkert.org code = "#ifndef __PARAMS__%s\n" % cls 3524762Snate@binkert.org code += "#define __PARAMS__%s\n\n" % cls 3534762Snate@binkert.org 3543100SN/A # The 'dict' attribute restricts us to the params declared in 3553100SN/A # the object itself, not including inherited params (which 3563100SN/A # will also be inherited from the base class's param struct 3573100SN/A # here). 3584762Snate@binkert.org params = cls._params.local.values() 3593100SN/A try: 3603100SN/A ptypes = [p.ptype for p in params] 3613100SN/A except: 3623100SN/A print cls, p, p.ptype_str 3633100SN/A print params 3643100SN/A raise 3653100SN/A 3663100SN/A # get a list of lists of predeclaration lines 3674762Snate@binkert.org predecls = [] 3684762Snate@binkert.org predecls.extend(cls.cxx_predecls) 3694762Snate@binkert.org for p in params: 3704762Snate@binkert.org predecls.extend(p.cxx_predecls()) 3714762Snate@binkert.org # remove redundant lines 3724762Snate@binkert.org predecls2 = [] 3734762Snate@binkert.org for pd in predecls: 3744762Snate@binkert.org if pd not in predecls2: 3754762Snate@binkert.org predecls2.append(pd) 3764762Snate@binkert.org predecls2.sort() 3774762Snate@binkert.org code += "\n".join(predecls2) 3784762Snate@binkert.org code += "\n\n"; 3794762Snate@binkert.org 3805610Snate@binkert.org if cls._base: 3815610Snate@binkert.org code += '#include "params/%s.hh"\n\n' % cls._base.type 3824762Snate@binkert.org 3834762Snate@binkert.org for ptype in ptypes: 3844762Snate@binkert.org if issubclass(ptype, Enum): 3854762Snate@binkert.org code += '#include "enums/%s.hh"\n' % ptype.__name__ 3864762Snate@binkert.org code += "\n\n" 3874762Snate@binkert.org 3885610Snate@binkert.org code += cls.cxx_struct(cls._base, params) 3895488Snate@binkert.org 3905488Snate@binkert.org # close #ifndef __PARAMS__* guard 3915488Snate@binkert.org code += "\n#endif\n" 3925488Snate@binkert.org return code 3935488Snate@binkert.org 3945488Snate@binkert.org def cxx_struct(cls, base, params): 3955488Snate@binkert.org if cls == SimObject: 3965488Snate@binkert.org return '#include "sim/sim_object_params.hh"\n' 3975488Snate@binkert.org 3984762Snate@binkert.org # now generate the actual param struct 3995488Snate@binkert.org code = "struct %sParams" % cls 4004762Snate@binkert.org if base: 4015610Snate@binkert.org code += " : public %sParams" % base.type 4024762Snate@binkert.org code += "\n{\n" 4034762Snate@binkert.org if not hasattr(cls, 'abstract') or not cls.abstract: 4044762Snate@binkert.org if 'type' in cls.__dict__: 4054762Snate@binkert.org code += " %s create();\n" % cls.cxx_type 4064762Snate@binkert.org decls = [p.cxx_decl() for p in params] 4074762Snate@binkert.org decls.sort() 4084762Snate@binkert.org code += "".join([" %s\n" % d for d in decls]) 4094762Snate@binkert.org code += "};\n" 4104762Snate@binkert.org 4114762Snate@binkert.org return code 4124762Snate@binkert.org 4134762Snate@binkert.org def swig_decl(cls): 4144762Snate@binkert.org code = '%%module %s\n' % cls 4154762Snate@binkert.org 4164762Snate@binkert.org code += '%{\n' 4174762Snate@binkert.org code += '#include "params/%s.hh"\n' % cls 4184762Snate@binkert.org code += '%}\n\n' 4194762Snate@binkert.org 4204762Snate@binkert.org # The 'dict' attribute restricts us to the params declared in 4214762Snate@binkert.org # the object itself, not including inherited params (which 4224762Snate@binkert.org # will also be inherited from the base class's param struct 4234762Snate@binkert.org # here). 4244762Snate@binkert.org params = cls._params.local.values() 4254762Snate@binkert.org ptypes = [p.ptype for p in params] 4264762Snate@binkert.org 4274762Snate@binkert.org # get a list of lists of predeclaration lines 4284762Snate@binkert.org predecls = [] 4294762Snate@binkert.org predecls.extend([ p.swig_predecls() for p in params ]) 4303100SN/A # flatten 4313100SN/A predecls = reduce(lambda x,y:x+y, predecls, []) 4323100SN/A # remove redundant lines 4333100SN/A predecls2 = [] 4343100SN/A for pd in predecls: 4353100SN/A if pd not in predecls2: 4363100SN/A predecls2.append(pd) 4373100SN/A predecls2.sort() 4383100SN/A code += "\n".join(predecls2) 4393100SN/A code += "\n\n"; 4403100SN/A 4415610Snate@binkert.org if cls._base: 4425610Snate@binkert.org code += '%%import "params/%s.i"\n\n' % cls._base.type 4433100SN/A 4444762Snate@binkert.org for ptype in ptypes: 4454762Snate@binkert.org if issubclass(ptype, Enum): 4464762Snate@binkert.org code += '%%import "enums/%s.hh"\n' % ptype.__name__ 4474762Snate@binkert.org code += "\n\n" 4483100SN/A 4494762Snate@binkert.org code += '%%import "params/%s_type.hh"\n\n' % cls 4503100SN/A code += '%%include "params/%s.hh"\n\n' % cls 4513100SN/A 4523100SN/A return code 4533100SN/A 4542740SN/A# The SimObject class is the root of the special hierarchy. Most of 455679SN/A# the code in this class deals with the configuration hierarchy itself 456679SN/A# (parent/child node relationships). 4571692SN/Aclass SimObject(object): 4581692SN/A # Specify metaclass. Any class inheriting from SimObject will 459679SN/A # get this metaclass. 4601692SN/A __metaclass__ = MetaSimObject 4613100SN/A type = 'SimObject' 4624762Snate@binkert.org abstract = True 4633100SN/A 4644859Snate@binkert.org swig_objdecls = [ '%include "python/swig/sim_object.i"' ] 465679SN/A 4662740SN/A # Initialize new instance. For objects with SimObject-valued 4672740SN/A # children, we need to recursively clone the classes represented 4682740SN/A # by those param values as well in a consistent "deep copy"-style 4692740SN/A # fashion. That is, we want to make sure that each instance is 4702740SN/A # cloned only once, and that if there are multiple references to 4712740SN/A # the same original object, we end up with the corresponding 4722740SN/A # cloned references all pointing to the same cloned instance. 4732740SN/A def __init__(self, **kwargs): 4742740SN/A ancestor = kwargs.get('_ancestor') 4752740SN/A memo_dict = kwargs.get('_memo') 4762740SN/A if memo_dict is None: 4772740SN/A # prepare to memoize any recursively instantiated objects 4782740SN/A memo_dict = {} 4792740SN/A elif ancestor: 4802740SN/A # memoize me now to avoid problems with recursive calls 4812740SN/A memo_dict[ancestor] = self 4822711SN/A 4832740SN/A if not ancestor: 4842740SN/A ancestor = self.__class__ 4852740SN/A ancestor._instantiated = True 4862711SN/A 4872740SN/A # initialize required attributes 4882740SN/A self._parent = None 4892740SN/A self._children = {} 4902740SN/A self._ccObject = None # pointer to C++ object 4914762Snate@binkert.org self._ccParams = None 4922740SN/A self._instantiated = False # really "cloned" 4932712SN/A 4942711SN/A # Inherit parameter values from class using multidict so 4952711SN/A # individual value settings can be overridden. 4962740SN/A self._values = multidict(ancestor._values) 4972740SN/A # clone SimObject-valued parameters 4982740SN/A for key,val in ancestor._values.iteritems(): 4992740SN/A if isSimObject(val): 5002740SN/A setattr(self, key, val(_memo=memo_dict)) 5012740SN/A elif isSimObjectSequence(val) and len(val): 5022740SN/A setattr(self, key, [ v(_memo=memo_dict) for v in val ]) 5032740SN/A # clone port references. no need to use a multidict here 5042740SN/A # since we will be creating new references for all ports. 5053105Sstever@eecs.umich.edu self._port_refs = {} 5063105Sstever@eecs.umich.edu for key,val in ancestor._port_refs.iteritems(): 5073105Sstever@eecs.umich.edu self._port_refs[key] = val.clone(self, memo_dict) 5081692SN/A # apply attribute assignments from keyword args, if any 5091692SN/A for key,val in kwargs.iteritems(): 5101692SN/A setattr(self, key, val) 511679SN/A 5122740SN/A # "Clone" the current instance by creating another instance of 5132740SN/A # this instance's class, but that inherits its parameter values 5142740SN/A # and port mappings from the current instance. If we're in a 5152740SN/A # "deep copy" recursive clone, check the _memo dict to see if 5162740SN/A # we've already cloned this instance. 5171692SN/A def __call__(self, **kwargs): 5182740SN/A memo_dict = kwargs.get('_memo') 5192740SN/A if memo_dict is None: 5202740SN/A # no memo_dict: must be top-level clone operation. 5212740SN/A # this is only allowed at the root of a hierarchy 5222740SN/A if self._parent: 5232740SN/A raise RuntimeError, "attempt to clone object %s " \ 5242740SN/A "not at the root of a tree (parent = %s)" \ 5252740SN/A % (self, self._parent) 5262740SN/A # create a new dict and use that. 5272740SN/A memo_dict = {} 5282740SN/A kwargs['_memo'] = memo_dict 5292740SN/A elif memo_dict.has_key(self): 5302740SN/A # clone already done & memoized 5312740SN/A return memo_dict[self] 5322740SN/A return self.__class__(_ancestor = self, **kwargs) 5331343SN/A 5343105Sstever@eecs.umich.edu def _get_port_ref(self, attr): 5353105Sstever@eecs.umich.edu # Return reference that can be assigned to another port 5363105Sstever@eecs.umich.edu # via __setattr__. There is only ever one reference 5373105Sstever@eecs.umich.edu # object per port, but we create them lazily here. 5383105Sstever@eecs.umich.edu ref = self._port_refs.get(attr) 5393105Sstever@eecs.umich.edu if not ref: 5403105Sstever@eecs.umich.edu ref = self._ports[attr].makeRef(self) 5413105Sstever@eecs.umich.edu self._port_refs[attr] = ref 5423105Sstever@eecs.umich.edu return ref 5433105Sstever@eecs.umich.edu 5441692SN/A def __getattr__(self, attr): 5452738SN/A if self._ports.has_key(attr): 5463105Sstever@eecs.umich.edu return self._get_port_ref(attr) 5472738SN/A 5481692SN/A if self._values.has_key(attr): 5491692SN/A return self._values[attr] 5501427SN/A 5511692SN/A raise AttributeError, "object '%s' has no attribute '%s'" \ 5521692SN/A % (self.__class__.__name__, attr) 5531427SN/A 5541692SN/A # Set attribute (called on foo.attr = value when foo is an 5551692SN/A # instance of class cls). 5561692SN/A def __setattr__(self, attr, value): 5571692SN/A # normal processing for private attributes 5581692SN/A if attr.startswith('_'): 5591692SN/A object.__setattr__(self, attr, value) 5601692SN/A return 5611427SN/A 5622738SN/A if self._ports.has_key(attr): 5632738SN/A # set up port connection 5643105Sstever@eecs.umich.edu self._get_port_ref(attr).connect(value) 5652738SN/A return 5662738SN/A 5672740SN/A if isSimObjectOrSequence(value) and self._instantiated: 5682740SN/A raise RuntimeError, \ 5692740SN/A "cannot set SimObject parameter '%s' after\n" \ 5702740SN/A " instance been cloned %s" % (attr, `self`) 5712740SN/A 5721692SN/A # must be SimObject param 5733105Sstever@eecs.umich.edu param = self._params.get(attr) 5741692SN/A if param: 5751310SN/A try: 5761692SN/A value = param.convert(value) 5771587SN/A except Exception, e: 5781692SN/A msg = "%s\nError setting param %s.%s to %s\n" % \ 5791692SN/A (e, self.__class__.__name__, attr, value) 5801605SN/A e.args = (msg, ) 5811605SN/A raise 5823105Sstever@eecs.umich.edu self._set_child(attr, value) 5833105Sstever@eecs.umich.edu return 5841310SN/A 5853105Sstever@eecs.umich.edu if isSimObjectOrSequence(value): 5863105Sstever@eecs.umich.edu self._set_child(attr, value) 5873105Sstever@eecs.umich.edu return 5881693SN/A 5893105Sstever@eecs.umich.edu # no valid assignment... raise exception 5903105Sstever@eecs.umich.edu raise AttributeError, "Class %s has no parameter %s" \ 5913105Sstever@eecs.umich.edu % (self.__class__.__name__, attr) 5921310SN/A 5931310SN/A 5941692SN/A # this hack allows tacking a '[0]' onto parameters that may or may 5951692SN/A # not be vectors, and always getting the first element (e.g. cpus) 5961692SN/A def __getitem__(self, key): 5971692SN/A if key == 0: 5981692SN/A return self 5991692SN/A raise TypeError, "Non-zero index '%s' to SimObject" % key 6001310SN/A 6011693SN/A # clear out children with given name, even if it's a vector 6021693SN/A def clear_child(self, name): 6031693SN/A if not self._children.has_key(name): 6041693SN/A return 6051693SN/A child = self._children[name] 6061693SN/A if isinstance(child, SimObjVector): 6071693SN/A for i in xrange(len(child)): 6081693SN/A del self._children["s%d" % (name, i)] 6091693SN/A del self._children[name] 6101693SN/A 6111692SN/A def add_child(self, name, value): 6121692SN/A self._children[name] = value 6131310SN/A 6143105Sstever@eecs.umich.edu def _maybe_set_parent(self, parent, name): 6152740SN/A if not self._parent: 6161692SN/A self._parent = parent 6171692SN/A self._name = name 6181692SN/A parent.add_child(name, self) 6191310SN/A 6203105Sstever@eecs.umich.edu def _set_child(self, attr, value): 6213105Sstever@eecs.umich.edu # if RHS is a SimObject, it's an implicit child assignment 6223105Sstever@eecs.umich.edu # clear out old child with this name, if any 6233105Sstever@eecs.umich.edu self.clear_child(attr) 6243105Sstever@eecs.umich.edu 6253105Sstever@eecs.umich.edu if isSimObject(value): 6263105Sstever@eecs.umich.edu value._maybe_set_parent(self, attr) 6273105Sstever@eecs.umich.edu elif isSimObjectSequence(value): 6283105Sstever@eecs.umich.edu value = SimObjVector(value) 6294762Snate@binkert.org if len(value) == 1: 6304762Snate@binkert.org value[0]._maybe_set_parent(self, attr) 6314762Snate@binkert.org else: 6325766Snate@binkert.org width = int(math.ceil(math.log(len(value))/math.log(10))) 6334762Snate@binkert.org for i,v in enumerate(value): 6345766Snate@binkert.org v._maybe_set_parent(self, "%s%0*d" % (attr, width, i)) 6353105Sstever@eecs.umich.edu 6363105Sstever@eecs.umich.edu self._values[attr] = value 6373105Sstever@eecs.umich.edu 6381692SN/A def path(self): 6392740SN/A if not self._parent: 6401692SN/A return 'root' 6411692SN/A ppath = self._parent.path() 6421692SN/A if ppath == 'root': 6431692SN/A return self._name 6441692SN/A return ppath + "." + self._name 6451310SN/A 6461692SN/A def __str__(self): 6471692SN/A return self.path() 6481310SN/A 6491692SN/A def ini_str(self): 6501692SN/A return self.path() 6511310SN/A 6521692SN/A def find_any(self, ptype): 6531692SN/A if isinstance(self, ptype): 6541692SN/A return self, True 6551310SN/A 6561692SN/A found_obj = None 6571692SN/A for child in self._children.itervalues(): 6581692SN/A if isinstance(child, ptype): 6591692SN/A if found_obj != None and child != found_obj: 6601692SN/A raise AttributeError, \ 6611692SN/A 'parent.any matched more than one: %s %s' % \ 6621814SN/A (found_obj.path, child.path) 6631692SN/A found_obj = child 6641692SN/A # search param space 6651692SN/A for pname,pdesc in self._params.iteritems(): 6661692SN/A if issubclass(pdesc.ptype, ptype): 6671692SN/A match_obj = self._values[pname] 6681692SN/A if found_obj != None and found_obj != match_obj: 6691692SN/A raise AttributeError, \ 6701692SN/A 'parent.any matched more than one: %s' % obj.path 6711692SN/A found_obj = match_obj 6721692SN/A return found_obj, found_obj != None 6731692SN/A 6741815SN/A def unproxy(self, base): 6751815SN/A return self 6761815SN/A 6773105Sstever@eecs.umich.edu def unproxy_all(self): 6783105Sstever@eecs.umich.edu for param in self._params.iterkeys(): 6793105Sstever@eecs.umich.edu value = self._values.get(param) 6803105Sstever@eecs.umich.edu if value != None and proxy.isproxy(value): 6813105Sstever@eecs.umich.edu try: 6823105Sstever@eecs.umich.edu value = value.unproxy(self) 6833105Sstever@eecs.umich.edu except: 6843105Sstever@eecs.umich.edu print "Error in unproxying param '%s' of %s" % \ 6853105Sstever@eecs.umich.edu (param, self.path()) 6863105Sstever@eecs.umich.edu raise 6873105Sstever@eecs.umich.edu setattr(self, param, value) 6883105Sstever@eecs.umich.edu 6893107Sstever@eecs.umich.edu # Unproxy ports in sorted order so that 'append' operations on 6903107Sstever@eecs.umich.edu # vector ports are done in a deterministic fashion. 6913107Sstever@eecs.umich.edu port_names = self._ports.keys() 6923107Sstever@eecs.umich.edu port_names.sort() 6933107Sstever@eecs.umich.edu for port_name in port_names: 6943105Sstever@eecs.umich.edu port = self._port_refs.get(port_name) 6953105Sstever@eecs.umich.edu if port != None: 6963105Sstever@eecs.umich.edu port.unproxy(self) 6973105Sstever@eecs.umich.edu 6983107Sstever@eecs.umich.edu # Unproxy children in sorted order for determinism also. 6993107Sstever@eecs.umich.edu child_names = self._children.keys() 7003107Sstever@eecs.umich.edu child_names.sort() 7013107Sstever@eecs.umich.edu for child in child_names: 7023107Sstever@eecs.umich.edu self._children[child].unproxy_all() 7033105Sstever@eecs.umich.edu 7045037Smilesck@eecs.umich.edu def print_ini(self, ini_file): 7055543Ssaidi@eecs.umich.edu print >>ini_file, '[' + self.path() + ']' # .ini section header 7061692SN/A 7072738SN/A instanceDict[self.path()] = self 7082738SN/A 7094081Sbinkertn@umich.edu if hasattr(self, 'type'): 7105037Smilesck@eecs.umich.edu print >>ini_file, 'type=%s' % self.type 7111692SN/A 7121692SN/A child_names = self._children.keys() 7131692SN/A child_names.sort() 7144081Sbinkertn@umich.edu if len(child_names): 7155037Smilesck@eecs.umich.edu print >>ini_file, 'children=%s' % ' '.join(child_names) 7161692SN/A 7171692SN/A param_names = self._params.keys() 7181692SN/A param_names.sort() 7191692SN/A for param in param_names: 7203105Sstever@eecs.umich.edu value = self._values.get(param) 7211692SN/A if value != None: 7225037Smilesck@eecs.umich.edu print >>ini_file, '%s=%s' % (param, 7235037Smilesck@eecs.umich.edu self._values[param].ini_str()) 7241692SN/A 7253103Sstever@eecs.umich.edu port_names = self._ports.keys() 7263103Sstever@eecs.umich.edu port_names.sort() 7273103Sstever@eecs.umich.edu for port_name in port_names: 7283105Sstever@eecs.umich.edu port = self._port_refs.get(port_name, None) 7293105Sstever@eecs.umich.edu if port != None: 7305037Smilesck@eecs.umich.edu print >>ini_file, '%s=%s' % (port_name, port.ini_str()) 7313103Sstever@eecs.umich.edu 7325543Ssaidi@eecs.umich.edu print >>ini_file # blank line between objects 7331692SN/A 7341692SN/A for child in child_names: 7355037Smilesck@eecs.umich.edu self._children[child].print_ini(ini_file) 7361692SN/A 7374762Snate@binkert.org def getCCParams(self): 7384762Snate@binkert.org if self._ccParams: 7394762Snate@binkert.org return self._ccParams 7404762Snate@binkert.org 7415033Smilesck@eecs.umich.edu cc_params_struct = getattr(m5.objects.params, '%sParams' % self.type) 7424762Snate@binkert.org cc_params = cc_params_struct() 7435488Snate@binkert.org cc_params.pyobj = self 7444762Snate@binkert.org cc_params.name = str(self) 7454762Snate@binkert.org 7464762Snate@binkert.org param_names = self._params.keys() 7474762Snate@binkert.org param_names.sort() 7484762Snate@binkert.org for param in param_names: 7494762Snate@binkert.org value = self._values.get(param) 7504762Snate@binkert.org if value is None: 7514762Snate@binkert.org continue 7524762Snate@binkert.org 7534762Snate@binkert.org value = value.getValue() 7544762Snate@binkert.org if isinstance(self._params[param], VectorParamDesc): 7554762Snate@binkert.org assert isinstance(value, list) 7564762Snate@binkert.org vec = getattr(cc_params, param) 7574762Snate@binkert.org assert not len(vec) 7584762Snate@binkert.org for v in value: 7594762Snate@binkert.org vec.append(v) 7604762Snate@binkert.org else: 7614762Snate@binkert.org setattr(cc_params, param, value) 7624762Snate@binkert.org 7634762Snate@binkert.org port_names = self._ports.keys() 7644762Snate@binkert.org port_names.sort() 7654762Snate@binkert.org for port_name in port_names: 7664762Snate@binkert.org port = self._port_refs.get(port_name, None) 7674762Snate@binkert.org if port != None: 7684762Snate@binkert.org setattr(cc_params, port_name, port) 7694762Snate@binkert.org self._ccParams = cc_params 7704762Snate@binkert.org return self._ccParams 7712738SN/A 7722740SN/A # Get C++ object corresponding to this object, calling C++ if 7732740SN/A # necessary to construct it. Does *not* recursively create 7742740SN/A # children. 7752740SN/A def getCCObject(self): 7762740SN/A if not self._ccObject: 7775244Sgblack@eecs.umich.edu # Cycles in the configuration heirarchy are not supported. This 7785244Sgblack@eecs.umich.edu # will catch the resulting recursion and stop. 7795244Sgblack@eecs.umich.edu self._ccObject = -1 7805244Sgblack@eecs.umich.edu params = self.getCCParams() 7814762Snate@binkert.org self._ccObject = params.create() 7822740SN/A elif self._ccObject == -1: 7835244Sgblack@eecs.umich.edu raise RuntimeError, "%s: Cycle found in configuration heirarchy." \ 7842740SN/A % self.path() 7852740SN/A return self._ccObject 7862740SN/A 7874762Snate@binkert.org # Call C++ to create C++ object corresponding to this object and 7884762Snate@binkert.org # (recursively) all its children 7894762Snate@binkert.org def createCCObject(self): 7904762Snate@binkert.org self.getCCParams() 7914762Snate@binkert.org self.getCCObject() # force creation 7924762Snate@binkert.org for child in self._children.itervalues(): 7934762Snate@binkert.org child.createCCObject() 7944762Snate@binkert.org 7954762Snate@binkert.org def getValue(self): 7964762Snate@binkert.org return self.getCCObject() 7974762Snate@binkert.org 7982738SN/A # Create C++ port connections corresponding to the connections in 7993105Sstever@eecs.umich.edu # _port_refs (& recursively for all children) 8002738SN/A def connectPorts(self): 8013105Sstever@eecs.umich.edu for portRef in self._port_refs.itervalues(): 8023105Sstever@eecs.umich.edu portRef.ccConnect() 8032738SN/A for child in self._children.itervalues(): 8042738SN/A child.connectPorts() 8052738SN/A 8062839SN/A def startDrain(self, drain_event, recursive): 8072797SN/A count = 0 8084081Sbinkertn@umich.edu if isinstance(self, SimObject): 8092901SN/A count += self._ccObject.drain(drain_event) 8102797SN/A if recursive: 8112797SN/A for child in self._children.itervalues(): 8122839SN/A count += child.startDrain(drain_event, True) 8132797SN/A return count 8142797SN/A 8152797SN/A def resume(self): 8164081Sbinkertn@umich.edu if isinstance(self, SimObject): 8172797SN/A self._ccObject.resume() 8182797SN/A for child in self._children.itervalues(): 8192797SN/A child.resume() 8202797SN/A 8214553Sbinkertn@umich.edu def getMemoryMode(self): 8224553Sbinkertn@umich.edu if not isinstance(self, m5.objects.System): 8234553Sbinkertn@umich.edu return None 8244553Sbinkertn@umich.edu 8254859Snate@binkert.org return self._ccObject.getMemoryMode() 8264553Sbinkertn@umich.edu 8272797SN/A def changeTiming(self, mode): 8283202Shsul@eecs.umich.edu if isinstance(self, m5.objects.System): 8293202Shsul@eecs.umich.edu # i don't know if there's a better way to do this - calling 8303202Shsul@eecs.umich.edu # setMemoryMode directly from self._ccObject results in calling 8313202Shsul@eecs.umich.edu # SimObject::setMemoryMode, not the System::setMemoryMode 8324859Snate@binkert.org self._ccObject.setMemoryMode(mode) 8332797SN/A for child in self._children.itervalues(): 8342797SN/A child.changeTiming(mode) 8352797SN/A 8362797SN/A def takeOverFrom(self, old_cpu): 8374859Snate@binkert.org self._ccObject.takeOverFrom(old_cpu._ccObject) 8382797SN/A 8391692SN/A # generate output file for 'dot' to display as a pretty graph. 8401692SN/A # this code is currently broken. 8411342SN/A def outputDot(self, dot): 8421342SN/A label = "{%s|" % self.path 8431342SN/A if isSimObject(self.realtype): 8441342SN/A label += '%s|' % self.type 8451342SN/A 8461342SN/A if self.children: 8471342SN/A # instantiate children in same order they were added for 8481342SN/A # backward compatibility (else we can end up with cpu1 8491342SN/A # before cpu0). 8501342SN/A for c in self.children: 8511342SN/A dot.add_edge(pydot.Edge(self.path,c.path, style="bold")) 8521342SN/A 8531342SN/A simobjs = [] 8541342SN/A for param in self.params: 8551342SN/A try: 8561342SN/A if param.value is None: 8571342SN/A raise AttributeError, 'Parameter with no value' 8581342SN/A 8591692SN/A value = param.value 8601342SN/A string = param.string(value) 8611587SN/A except Exception, e: 8621605SN/A msg = 'exception in %s:%s\n%s' % (self.name, param.name, e) 8631605SN/A e.args = (msg, ) 8641342SN/A raise 8651605SN/A 8661692SN/A if isSimObject(param.ptype) and string != "Null": 8671342SN/A simobjs.append(string) 8681342SN/A else: 8691342SN/A label += '%s = %s\\n' % (param.name, string) 8701342SN/A 8711342SN/A for so in simobjs: 8721342SN/A label += "|<%s> %s" % (so, so) 8731587SN/A dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so, 8741587SN/A tailport="w")) 8751342SN/A label += '}' 8761342SN/A dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label)) 8771342SN/A 8781342SN/A # recursively dump out children 8791342SN/A for c in self.children: 8801342SN/A c.outputDot(dot) 8811342SN/A 8823101Sstever@eecs.umich.edu# Function to provide to C++ so it can look up instances based on paths 8833101Sstever@eecs.umich.edudef resolveSimObject(name): 8843101Sstever@eecs.umich.edu obj = instanceDict[name] 8853101Sstever@eecs.umich.edu return obj.getCCObject() 886679SN/A 8871528SN/A# __all__ defines the list of symbols that get exported when 8881528SN/A# 'from config import *' is invoked. Try to keep this reasonably 8891528SN/A# short to avoid polluting other namespaces. 8904762Snate@binkert.org__all__ = [ 'SimObject' ] 891