SimObject.py revision 5821:2831ae658bfc
15217Ssaidi@eecs.umich.edu# Copyright (c) 2004-2006 The Regents of The University of Michigan 29428SAndreas.Sandberg@ARM.com# All rights reserved. 39920Syasuko.eckert@amd.com# 49428SAndreas.Sandberg@ARM.com# Redistribution and use in source and binary forms, with or without 59428SAndreas.Sandberg@ARM.com# modification, are permitted provided that the following conditions are 69428SAndreas.Sandberg@ARM.com# met: redistributions of source code must retain the above copyright 79428SAndreas.Sandberg@ARM.com# notice, this list of conditions and the following disclaimer; 89428SAndreas.Sandberg@ARM.com# redistributions in binary form must reproduce the above copyright 99428SAndreas.Sandberg@ARM.com# notice, this list of conditions and the following disclaimer in the 109428SAndreas.Sandberg@ARM.com# documentation and/or other materials provided with the distribution; 119428SAndreas.Sandberg@ARM.com# neither the name of the copyright holders nor the names of its 129428SAndreas.Sandberg@ARM.com# contributors may be used to endorse or promote products derived from 139428SAndreas.Sandberg@ARM.com# this software without specific prior written permission. 149428SAndreas.Sandberg@ARM.com# 155217Ssaidi@eecs.umich.edu# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 165217Ssaidi@eecs.umich.edu# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 175217Ssaidi@eecs.umich.edu# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 185217Ssaidi@eecs.umich.edu# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 195217Ssaidi@eecs.umich.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 205217Ssaidi@eecs.umich.edu# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 215217Ssaidi@eecs.umich.edu# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 225217Ssaidi@eecs.umich.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 235217Ssaidi@eecs.umich.edu# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 245217Ssaidi@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 255217Ssaidi@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 265217Ssaidi@eecs.umich.edu# 275217Ssaidi@eecs.umich.edu# Authors: Steve Reinhardt 285217Ssaidi@eecs.umich.edu# Nathan Binkert 295217Ssaidi@eecs.umich.edu 305217Ssaidi@eecs.umich.eduimport math 315217Ssaidi@eecs.umich.eduimport sys 325217Ssaidi@eecs.umich.eduimport types 335217Ssaidi@eecs.umich.edu 345217Ssaidi@eecs.umich.eduimport proxy 355217Ssaidi@eecs.umich.eduimport m5 365217Ssaidi@eecs.umich.edufrom util import * 375217Ssaidi@eecs.umich.edu 385217Ssaidi@eecs.umich.edu# These utility functions have to come first because they're 395217Ssaidi@eecs.umich.edu# referenced in params.py... otherwise they won't be defined when we 405217Ssaidi@eecs.umich.edu# import params below, and the recursive import of this file from 415217Ssaidi@eecs.umich.edu# params.py will not find these names. 425217Ssaidi@eecs.umich.edudef isSimObject(value): 435217Ssaidi@eecs.umich.edu return isinstance(value, SimObject) 4411627Smichael.lebeane@amd.com 455217Ssaidi@eecs.umich.edudef isSimObjectClass(value): 465217Ssaidi@eecs.umich.edu return issubclass(value, SimObject) 476658Snate@binkert.org 489441SAndreas.Sandberg@ARM.comdef isSimObjectSequence(value): 499441SAndreas.Sandberg@ARM.com if not isinstance(value, (list, tuple)) or len(value) == 0: 505217Ssaidi@eecs.umich.edu return False 518232Snate@binkert.org 5211627Smichael.lebeane@amd.com for val in value: 5311627Smichael.lebeane@amd.com if not isNullPointer(val) and not isSimObject(val): 549441SAndreas.Sandberg@ARM.com return False 555217Ssaidi@eecs.umich.edu 565217Ssaidi@eecs.umich.edu return True 575217Ssaidi@eecs.umich.edu 585217Ssaidi@eecs.umich.edudef isSimObjectOrSequence(value): 595217Ssaidi@eecs.umich.edu return isSimObject(value) or isSimObjectSequence(value) 605217Ssaidi@eecs.umich.edu 615217Ssaidi@eecs.umich.edu# Have to import params up top since Param is referenced on initial 625217Ssaidi@eecs.umich.edu# load (when SimObject class references Param to create a class 635217Ssaidi@eecs.umich.edu# variable, the 'name' param)... 645217Ssaidi@eecs.umich.edufrom params import * 655217Ssaidi@eecs.umich.edu# There are a few things we need that aren't in params.__all__ since 665217Ssaidi@eecs.umich.edu# normal users don't need them 675217Ssaidi@eecs.umich.edufrom params import ParamDesc, VectorParamDesc, isNullPointer, SimObjVector 685217Ssaidi@eecs.umich.edu 695217Ssaidi@eecs.umich.edunoDot = False 705217Ssaidi@eecs.umich.edutry: 715217Ssaidi@eecs.umich.edu import pydot 725217Ssaidi@eecs.umich.eduexcept: 735217Ssaidi@eecs.umich.edu noDot = True 745217Ssaidi@eecs.umich.edu 755217Ssaidi@eecs.umich.edu##################################################################### 765217Ssaidi@eecs.umich.edu# 775217Ssaidi@eecs.umich.edu# M5 Python Configuration Utility 785217Ssaidi@eecs.umich.edu# 795217Ssaidi@eecs.umich.edu# The basic idea is to write simple Python programs that build Python 805217Ssaidi@eecs.umich.edu# objects corresponding to M5 SimObjects for the desired simulation 815217Ssaidi@eecs.umich.edu# configuration. For now, the Python emits a .ini file that can be 825217Ssaidi@eecs.umich.edu# parsed by M5. In the future, some tighter integration between M5 835217Ssaidi@eecs.umich.edu# and the Python interpreter may allow bypassing the .ini file. 845217Ssaidi@eecs.umich.edu# 855217Ssaidi@eecs.umich.edu# Each SimObject class in M5 is represented by a Python class with the 869920Syasuko.eckert@amd.com# same name. The Python inheritance tree mirrors the M5 C++ tree 879920Syasuko.eckert@amd.com# (e.g., SimpleCPU derives from BaseCPU in both cases, and all 889920Syasuko.eckert@amd.com# SimObjects inherit from a single SimObject base class). To specify 899920Syasuko.eckert@amd.com# an instance of an M5 SimObject in a configuration, the user simply 909920Syasuko.eckert@amd.com# instantiates the corresponding Python object. The parameters for 919920Syasuko.eckert@amd.com# that SimObject are given by assigning to attributes of the Python 929920Syasuko.eckert@amd.com# object, either using keyword assignment in the constructor or in 939920Syasuko.eckert@amd.com# separate assignment statements. For example: 947720Sgblack@eecs.umich.edu# 957720Sgblack@eecs.umich.edu# cache = BaseCache(size='64KB') 965712Shsul@eecs.umich.edu# cache.hit_latency = 3 975712Shsul@eecs.umich.edu# cache.assoc = 8 985217Ssaidi@eecs.umich.edu# 995217Ssaidi@eecs.umich.edu# The magic lies in the mapping of the Python attributes for SimObject 1005714Shsul@eecs.umich.edu# classes to the actual SimObject parameter specifications. This 10111005Sandreas.sandberg@arm.com# allows parameter validity checking in the Python code. Continuing 10211005Sandreas.sandberg@arm.com# the example above, the statements "cache.blurfl=3" or 10311005Sandreas.sandberg@arm.com# "cache.assoc='hello'" would both result in runtime errors in Python, 1045714Shsul@eecs.umich.edu# since the BaseCache object has no 'blurfl' parameter and the 'assoc' 1055714Shsul@eecs.umich.edu# parameter requires an integer, respectively. This magic is done 1065714Shsul@eecs.umich.edu# primarily by overriding the special __setattr__ method that controls 1075217Ssaidi@eecs.umich.edu# assignment to object attributes. 1089428SAndreas.Sandberg@ARM.com# 1099428SAndreas.Sandberg@ARM.com# Once a set of Python objects have been instantiated in a hierarchy, 11011627Smichael.lebeane@amd.com# calling 'instantiate(obj)' (where obj is the root of the hierarchy) 11111627Smichael.lebeane@amd.com# will generate a .ini file. 11211627Smichael.lebeane@amd.com# 11311627Smichael.lebeane@amd.com##################################################################### 11411627Smichael.lebeane@amd.com 11511627Smichael.lebeane@amd.com# list of all SimObject classes 11611627Smichael.lebeane@amd.comallClasses = {} 11711627Smichael.lebeane@amd.com 11811627Smichael.lebeane@amd.com# dict to look up SimObjects based on path 11911627Smichael.lebeane@amd.cominstanceDict = {} 12011627Smichael.lebeane@amd.com 12111627Smichael.lebeane@amd.com# The metaclass for SimObject. This class controls how new classes 12211627Smichael.lebeane@amd.com# that derive from SimObject are instantiated, and provides inherited 12311627Smichael.lebeane@amd.com# class behavior (just like a class controls how instances of that 12411627Smichael.lebeane@amd.com# class are instantiated, and provides inherited instance behavior). 12511627Smichael.lebeane@amd.comclass MetaSimObject(type): 12611627Smichael.lebeane@amd.com # Attributes that can be set only at initialization time 12711627Smichael.lebeane@amd.com init_keywords = { 'abstract' : types.BooleanType, 12811627Smichael.lebeane@amd.com 'cxx_class' : types.StringType, 12911627Smichael.lebeane@amd.com 'cxx_type' : types.StringType, 13011627Smichael.lebeane@amd.com 'cxx_predecls' : types.ListType, 13111627Smichael.lebeane@amd.com 'swig_objdecls' : types.ListType, 13211627Smichael.lebeane@amd.com 'swig_predecls' : types.ListType, 13311627Smichael.lebeane@amd.com 'type' : types.StringType } 13411627Smichael.lebeane@amd.com # Attributes that can be set any time 13511627Smichael.lebeane@amd.com keywords = { 'check' : types.FunctionType } 13611627Smichael.lebeane@amd.com 13711627Smichael.lebeane@amd.com # __new__ is called before __init__, and is where the statements 13811627Smichael.lebeane@amd.com # in the body of the class definition get loaded into the class's 13911627Smichael.lebeane@amd.com # __dict__. We intercept this to filter out parameter & port assignments 14011627Smichael.lebeane@amd.com # and only allow "private" attributes to be passed to the base 14111627Smichael.lebeane@amd.com # __new__ (starting with underscore). 14211627Smichael.lebeane@amd.com def __new__(mcls, name, bases, dict): 14310905Sandreas.sandberg@arm.com assert name not in allClasses 1449428SAndreas.Sandberg@ARM.com 1459428SAndreas.Sandberg@ARM.com # Copy "private" attributes, functions, and classes to the 1469428SAndreas.Sandberg@ARM.com # official dict. Everything else goes in _init_dict to be 1479428SAndreas.Sandberg@ARM.com # filtered in __init__. 1489428SAndreas.Sandberg@ARM.com cls_dict = {} 1499428SAndreas.Sandberg@ARM.com value_dict = {} 1509428SAndreas.Sandberg@ARM.com for key,val in dict.items(): 1519428SAndreas.Sandberg@ARM.com if key.startswith('_') or isinstance(val, (types.FunctionType, 15210905Sandreas.sandberg@arm.com types.TypeType)): 1539428SAndreas.Sandberg@ARM.com cls_dict[key] = val 1549428SAndreas.Sandberg@ARM.com else: 1559428SAndreas.Sandberg@ARM.com # must be a param/port setting 1569428SAndreas.Sandberg@ARM.com value_dict[key] = val 1579428SAndreas.Sandberg@ARM.com if 'abstract' not in value_dict: 1589428SAndreas.Sandberg@ARM.com value_dict['abstract'] = False 1599920Syasuko.eckert@amd.com cls_dict['_value_dict'] = value_dict 1609920Syasuko.eckert@amd.com cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict) 1619920Syasuko.eckert@amd.com if 'type' in value_dict: 1629920Syasuko.eckert@amd.com allClasses[name] = cls 1639920Syasuko.eckert@amd.com return cls 1649920Syasuko.eckert@amd.com 1659920Syasuko.eckert@amd.com # subclass initialization 16610905Sandreas.sandberg@arm.com def __init__(cls, name, bases, dict): 1679428SAndreas.Sandberg@ARM.com # calls type.__init__()... I think that's a no-op, but leave 1689428SAndreas.Sandberg@ARM.com # it here just in case it's not. 1699428SAndreas.Sandberg@ARM.com super(MetaSimObject, cls).__init__(name, bases, dict) 1709428SAndreas.Sandberg@ARM.com 1719428SAndreas.Sandberg@ARM.com # initialize required attributes 17210905Sandreas.sandberg@arm.com 1739428SAndreas.Sandberg@ARM.com # class-only attributes 1749428SAndreas.Sandberg@ARM.com cls._params = multidict() # param descriptions 1759428SAndreas.Sandberg@ARM.com cls._ports = multidict() # port descriptions 1769428SAndreas.Sandberg@ARM.com 1779428SAndreas.Sandberg@ARM.com # class or instance attributes 1789428SAndreas.Sandberg@ARM.com cls._values = multidict() # param values 17910905Sandreas.sandberg@arm.com cls._port_refs = multidict() # port ref objects 1809428SAndreas.Sandberg@ARM.com cls._instantiated = False # really instantiated, cloned, or subclassed 1819428SAndreas.Sandberg@ARM.com 1829428SAndreas.Sandberg@ARM.com # We don't support multiple inheritance. If you want to, you 1839428SAndreas.Sandberg@ARM.com # must fix multidict to deal with it properly. 1849428SAndreas.Sandberg@ARM.com if len(bases) > 1: 1859428SAndreas.Sandberg@ARM.com raise TypeError, "SimObjects do not support multiple inheritance" 1869428SAndreas.Sandberg@ARM.com 1879428SAndreas.Sandberg@ARM.com base = bases[0] 1889920Syasuko.eckert@amd.com 1899920Syasuko.eckert@amd.com # Set up general inheritance via multidicts. A subclass will 1909920Syasuko.eckert@amd.com # inherit all its settings from the base class. The only time 1919920Syasuko.eckert@amd.com # the following is not true is when we define the SimObject 1929920Syasuko.eckert@amd.com # class itself (in which case the multidicts have no parent). 1939920Syasuko.eckert@amd.com if isinstance(base, MetaSimObject): 1949920Syasuko.eckert@amd.com cls._base = base 1959428SAndreas.Sandberg@ARM.com cls._params.parent = base._params 19610905Sandreas.sandberg@arm.com cls._ports.parent = base._ports 1979428SAndreas.Sandberg@ARM.com cls._values.parent = base._values 1989428SAndreas.Sandberg@ARM.com cls._port_refs.parent = base._port_refs 1999428SAndreas.Sandberg@ARM.com # mark base as having been subclassed 2009428SAndreas.Sandberg@ARM.com base._instantiated = True 2019441SAndreas.Sandberg@ARM.com else: 2029441SAndreas.Sandberg@ARM.com cls._base = None 2039441SAndreas.Sandberg@ARM.com 2049441SAndreas.Sandberg@ARM.com # default keyword values 2059441SAndreas.Sandberg@ARM.com if 'type' in cls._value_dict: 2069441SAndreas.Sandberg@ARM.com if 'cxx_class' not in cls._value_dict: 2079441SAndreas.Sandberg@ARM.com cls._value_dict['cxx_class'] = cls._value_dict['type'] 2089441SAndreas.Sandberg@ARM.com 2099441SAndreas.Sandberg@ARM.com cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class'] 2109441SAndreas.Sandberg@ARM.com 2119441SAndreas.Sandberg@ARM.com if 'cxx_predecls' not in cls._value_dict: 2129441SAndreas.Sandberg@ARM.com # A forward class declaration is sufficient since we are 2139441SAndreas.Sandberg@ARM.com # just declaring a pointer. 2149441SAndreas.Sandberg@ARM.com class_path = cls._value_dict['cxx_class'].split('::') 2159441SAndreas.Sandberg@ARM.com class_path.reverse() 2169441SAndreas.Sandberg@ARM.com decl = 'class %s;' % class_path[0] 2179441SAndreas.Sandberg@ARM.com for ns in class_path[1:]: 2189441SAndreas.Sandberg@ARM.com decl = 'namespace %s { %s }' % (ns, decl) 2199441SAndreas.Sandberg@ARM.com cls._value_dict['cxx_predecls'] = [decl] 2209441SAndreas.Sandberg@ARM.com 2219441SAndreas.Sandberg@ARM.com if 'swig_predecls' not in cls._value_dict: 2229441SAndreas.Sandberg@ARM.com # A forward class declaration is sufficient since we are 2239441SAndreas.Sandberg@ARM.com # just declaring a pointer. 2249441SAndreas.Sandberg@ARM.com cls._value_dict['swig_predecls'] = \ 2259441SAndreas.Sandberg@ARM.com cls._value_dict['cxx_predecls'] 2269441SAndreas.Sandberg@ARM.com 2279441SAndreas.Sandberg@ARM.com if 'swig_objdecls' not in cls._value_dict: 2289441SAndreas.Sandberg@ARM.com cls._value_dict['swig_objdecls'] = [] 2299441SAndreas.Sandberg@ARM.com 2309441SAndreas.Sandberg@ARM.com # Now process the _value_dict items. They could be defining 2319441SAndreas.Sandberg@ARM.com # new (or overriding existing) parameters or ports, setting 2329441SAndreas.Sandberg@ARM.com # class keywords (e.g., 'abstract'), or setting parameter 2339441SAndreas.Sandberg@ARM.com # values or port bindings. The first 3 can only be set when 2349441SAndreas.Sandberg@ARM.com # the class is defined, so we handle them here. The others 235 # can be set later too, so just emulate that by calling 236 # setattr(). 237 for key,val in cls._value_dict.items(): 238 # param descriptions 239 if isinstance(val, ParamDesc): 240 cls._new_param(key, val) 241 242 # port objects 243 elif isinstance(val, Port): 244 cls._new_port(key, val) 245 246 # init-time-only keywords 247 elif cls.init_keywords.has_key(key): 248 cls._set_keyword(key, val, cls.init_keywords[key]) 249 250 # default: use normal path (ends up in __setattr__) 251 else: 252 setattr(cls, key, val) 253 254 def _set_keyword(cls, keyword, val, kwtype): 255 if not isinstance(val, kwtype): 256 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \ 257 (keyword, type(val), kwtype) 258 if isinstance(val, types.FunctionType): 259 val = classmethod(val) 260 type.__setattr__(cls, keyword, val) 261 262 def _new_param(cls, name, pdesc): 263 # each param desc should be uniquely assigned to one variable 264 assert(not hasattr(pdesc, 'name')) 265 pdesc.name = name 266 cls._params[name] = pdesc 267 if hasattr(pdesc, 'default'): 268 cls._set_param(name, pdesc.default, pdesc) 269 270 def _set_param(cls, name, value, param): 271 assert(param.name == name) 272 try: 273 cls._values[name] = param.convert(value) 274 except Exception, e: 275 msg = "%s\nError setting param %s.%s to %s\n" % \ 276 (e, cls.__name__, name, value) 277 e.args = (msg, ) 278 raise 279 280 def _new_port(cls, name, port): 281 # each port should be uniquely assigned to one variable 282 assert(not hasattr(port, 'name')) 283 port.name = name 284 cls._ports[name] = port 285 if hasattr(port, 'default'): 286 cls._cls_get_port_ref(name).connect(port.default) 287 288 # same as _get_port_ref, effectively, but for classes 289 def _cls_get_port_ref(cls, attr): 290 # Return reference that can be assigned to another port 291 # via __setattr__. There is only ever one reference 292 # object per port, but we create them lazily here. 293 ref = cls._port_refs.get(attr) 294 if not ref: 295 ref = cls._ports[attr].makeRef(cls) 296 cls._port_refs[attr] = ref 297 return ref 298 299 # Set attribute (called on foo.attr = value when foo is an 300 # instance of class cls). 301 def __setattr__(cls, attr, value): 302 # normal processing for private attributes 303 if attr.startswith('_'): 304 type.__setattr__(cls, attr, value) 305 return 306 307 if cls.keywords.has_key(attr): 308 cls._set_keyword(attr, value, cls.keywords[attr]) 309 return 310 311 if cls._ports.has_key(attr): 312 cls._cls_get_port_ref(attr).connect(value) 313 return 314 315 if isSimObjectOrSequence(value) and cls._instantiated: 316 raise RuntimeError, \ 317 "cannot set SimObject parameter '%s' after\n" \ 318 " class %s has been instantiated or subclassed" \ 319 % (attr, cls.__name__) 320 321 # check for param 322 param = cls._params.get(attr) 323 if param: 324 cls._set_param(attr, value, param) 325 return 326 327 if isSimObjectOrSequence(value): 328 # If RHS is a SimObject, it's an implicit child assignment. 329 # Classes don't have children, so we just put this object 330 # in _values; later, each instance will do a 'setattr(self, 331 # attr, _values[attr])' in SimObject.__init__ which will 332 # add this object as a child. 333 cls._values[attr] = value 334 return 335 336 # no valid assignment... raise exception 337 raise AttributeError, \ 338 "Class %s has no parameter \'%s\'" % (cls.__name__, attr) 339 340 def __getattr__(cls, attr): 341 if cls._values.has_key(attr): 342 return cls._values[attr] 343 344 raise AttributeError, \ 345 "object '%s' has no attribute '%s'" % (cls.__name__, attr) 346 347 def __str__(cls): 348 return cls.__name__ 349 350 def cxx_decl(cls): 351 code = "#ifndef __PARAMS__%s\n" % cls 352 code += "#define __PARAMS__%s\n\n" % cls 353 354 # The 'dict' attribute restricts us to the params declared in 355 # the object itself, not including inherited params (which 356 # will also be inherited from the base class's param struct 357 # here). 358 params = cls._params.local.values() 359 try: 360 ptypes = [p.ptype for p in params] 361 except: 362 print cls, p, p.ptype_str 363 print params 364 raise 365 366 # get a list of lists of predeclaration lines 367 predecls = [] 368 predecls.extend(cls.cxx_predecls) 369 for p in params: 370 predecls.extend(p.cxx_predecls()) 371 # remove redundant lines 372 predecls2 = [] 373 for pd in predecls: 374 if pd not in predecls2: 375 predecls2.append(pd) 376 predecls2.sort() 377 code += "\n".join(predecls2) 378 code += "\n\n"; 379 380 if cls._base: 381 code += '#include "params/%s.hh"\n\n' % cls._base.type 382 383 for ptype in ptypes: 384 if issubclass(ptype, Enum): 385 code += '#include "enums/%s.hh"\n' % ptype.__name__ 386 code += "\n\n" 387 388 code += cls.cxx_struct(cls._base, params) 389 390 # close #ifndef __PARAMS__* guard 391 code += "\n#endif\n" 392 return code 393 394 def cxx_struct(cls, base, params): 395 if cls == SimObject: 396 return '#include "sim/sim_object_params.hh"\n' 397 398 # now generate the actual param struct 399 code = "struct %sParams" % cls 400 if base: 401 code += " : public %sParams" % base.type 402 code += "\n{\n" 403 if not hasattr(cls, 'abstract') or not cls.abstract: 404 if 'type' in cls.__dict__: 405 code += " %s create();\n" % cls.cxx_type 406 decls = [p.cxx_decl() for p in params] 407 decls.sort() 408 code += "".join([" %s\n" % d for d in decls]) 409 code += "};\n" 410 411 return code 412 413 def swig_decl(cls): 414 code = '%%module %s\n' % cls 415 416 code += '%{\n' 417 code += '#include "params/%s.hh"\n' % cls 418 code += '%}\n\n' 419 420 # The 'dict' attribute restricts us to the params declared in 421 # the object itself, not including inherited params (which 422 # will also be inherited from the base class's param struct 423 # here). 424 params = cls._params.local.values() 425 ptypes = [p.ptype for p in params] 426 427 # get a list of lists of predeclaration lines 428 predecls = [] 429 predecls.extend([ p.swig_predecls() for p in params ]) 430 # flatten 431 predecls = reduce(lambda x,y:x+y, predecls, []) 432 # remove redundant lines 433 predecls2 = [] 434 for pd in predecls: 435 if pd not in predecls2: 436 predecls2.append(pd) 437 predecls2.sort() 438 code += "\n".join(predecls2) 439 code += "\n\n"; 440 441 if cls._base: 442 code += '%%import "params/%s.i"\n\n' % cls._base.type 443 444 for ptype in ptypes: 445 if issubclass(ptype, Enum): 446 code += '%%import "enums/%s.hh"\n' % ptype.__name__ 447 code += "\n\n" 448 449 code += '%%import "params/%s_type.hh"\n\n' % cls 450 code += '%%include "params/%s.hh"\n\n' % cls 451 452 return code 453 454# The SimObject class is the root of the special hierarchy. Most of 455# the code in this class deals with the configuration hierarchy itself 456# (parent/child node relationships). 457class SimObject(object): 458 # Specify metaclass. Any class inheriting from SimObject will 459 # get this metaclass. 460 __metaclass__ = MetaSimObject 461 type = 'SimObject' 462 abstract = True 463 464 swig_objdecls = [ '%include "python/swig/sim_object.i"' ] 465 466 # Initialize new instance. For objects with SimObject-valued 467 # children, we need to recursively clone the classes represented 468 # by those param values as well in a consistent "deep copy"-style 469 # fashion. That is, we want to make sure that each instance is 470 # cloned only once, and that if there are multiple references to 471 # the same original object, we end up with the corresponding 472 # cloned references all pointing to the same cloned instance. 473 def __init__(self, **kwargs): 474 ancestor = kwargs.get('_ancestor') 475 memo_dict = kwargs.get('_memo') 476 if memo_dict is None: 477 # prepare to memoize any recursively instantiated objects 478 memo_dict = {} 479 elif ancestor: 480 # memoize me now to avoid problems with recursive calls 481 memo_dict[ancestor] = self 482 483 if not ancestor: 484 ancestor = self.__class__ 485 ancestor._instantiated = True 486 487 # initialize required attributes 488 self._parent = None 489 self._children = {} 490 self._ccObject = None # pointer to C++ object 491 self._ccParams = None 492 self._instantiated = False # really "cloned" 493 494 # Inherit parameter values from class using multidict so 495 # individual value settings can be overridden. 496 self._values = multidict(ancestor._values) 497 # clone SimObject-valued parameters 498 for key,val in ancestor._values.iteritems(): 499 if isSimObject(val): 500 setattr(self, key, val(_memo=memo_dict)) 501 elif isSimObjectSequence(val) and len(val): 502 setattr(self, key, [ v(_memo=memo_dict) for v in val ]) 503 # clone port references. no need to use a multidict here 504 # since we will be creating new references for all ports. 505 self._port_refs = {} 506 for key,val in ancestor._port_refs.iteritems(): 507 self._port_refs[key] = val.clone(self, memo_dict) 508 # apply attribute assignments from keyword args, if any 509 for key,val in kwargs.iteritems(): 510 setattr(self, key, val) 511 512 # "Clone" the current instance by creating another instance of 513 # this instance's class, but that inherits its parameter values 514 # and port mappings from the current instance. If we're in a 515 # "deep copy" recursive clone, check the _memo dict to see if 516 # we've already cloned this instance. 517 def __call__(self, **kwargs): 518 memo_dict = kwargs.get('_memo') 519 if memo_dict is None: 520 # no memo_dict: must be top-level clone operation. 521 # this is only allowed at the root of a hierarchy 522 if self._parent: 523 raise RuntimeError, "attempt to clone object %s " \ 524 "not at the root of a tree (parent = %s)" \ 525 % (self, self._parent) 526 # create a new dict and use that. 527 memo_dict = {} 528 kwargs['_memo'] = memo_dict 529 elif memo_dict.has_key(self): 530 # clone already done & memoized 531 return memo_dict[self] 532 return self.__class__(_ancestor = self, **kwargs) 533 534 def _get_port_ref(self, attr): 535 # Return reference that can be assigned to another port 536 # via __setattr__. There is only ever one reference 537 # object per port, but we create them lazily here. 538 ref = self._port_refs.get(attr) 539 if not ref: 540 ref = self._ports[attr].makeRef(self) 541 self._port_refs[attr] = ref 542 return ref 543 544 def __getattr__(self, attr): 545 if self._ports.has_key(attr): 546 return self._get_port_ref(attr) 547 548 if self._values.has_key(attr): 549 return self._values[attr] 550 551 raise AttributeError, "object '%s' has no attribute '%s'" \ 552 % (self.__class__.__name__, attr) 553 554 # Set attribute (called on foo.attr = value when foo is an 555 # instance of class cls). 556 def __setattr__(self, attr, value): 557 # normal processing for private attributes 558 if attr.startswith('_'): 559 object.__setattr__(self, attr, value) 560 return 561 562 if self._ports.has_key(attr): 563 # set up port connection 564 self._get_port_ref(attr).connect(value) 565 return 566 567 if isSimObjectOrSequence(value) and self._instantiated: 568 raise RuntimeError, \ 569 "cannot set SimObject parameter '%s' after\n" \ 570 " instance been cloned %s" % (attr, `self`) 571 572 # must be SimObject param 573 param = self._params.get(attr) 574 if param: 575 try: 576 value = param.convert(value) 577 except Exception, e: 578 msg = "%s\nError setting param %s.%s to %s\n" % \ 579 (e, self.__class__.__name__, attr, value) 580 e.args = (msg, ) 581 raise 582 self._set_child(attr, value) 583 return 584 585 if isSimObjectOrSequence(value): 586 self._set_child(attr, value) 587 return 588 589 # no valid assignment... raise exception 590 raise AttributeError, "Class %s has no parameter %s" \ 591 % (self.__class__.__name__, attr) 592 593 594 # this hack allows tacking a '[0]' onto parameters that may or may 595 # not be vectors, and always getting the first element (e.g. cpus) 596 def __getitem__(self, key): 597 if key == 0: 598 return self 599 raise TypeError, "Non-zero index '%s' to SimObject" % key 600 601 # clear out children with given name, even if it's a vector 602 def clear_child(self, name): 603 if not self._children.has_key(name): 604 return 605 child = self._children[name] 606 if isinstance(child, SimObjVector): 607 for i in xrange(len(child)): 608 del self._children["s%d" % (name, i)] 609 del self._children[name] 610 611 def add_child(self, name, value): 612 self._children[name] = value 613 614 def _maybe_set_parent(self, parent, name): 615 if not self._parent: 616 self._parent = parent 617 self._name = name 618 parent.add_child(name, self) 619 620 def _set_child(self, attr, value): 621 # if RHS is a SimObject, it's an implicit child assignment 622 # clear out old child with this name, if any 623 self.clear_child(attr) 624 625 if isSimObject(value): 626 value._maybe_set_parent(self, attr) 627 elif isSimObjectSequence(value): 628 value = SimObjVector(value) 629 if len(value) == 1: 630 value[0]._maybe_set_parent(self, attr) 631 else: 632 width = int(math.ceil(math.log(len(value))/math.log(10))) 633 for i,v in enumerate(value): 634 v._maybe_set_parent(self, "%s%0*d" % (attr, width, i)) 635 636 self._values[attr] = value 637 638 def path(self): 639 if not self._parent: 640 return 'root' 641 ppath = self._parent.path() 642 if ppath == 'root': 643 return self._name 644 return ppath + "." + self._name 645 646 def __str__(self): 647 return self.path() 648 649 def ini_str(self): 650 return self.path() 651 652 def find_any(self, ptype): 653 if isinstance(self, ptype): 654 return self, True 655 656 found_obj = None 657 for child in self._children.itervalues(): 658 if isinstance(child, ptype): 659 if found_obj != None and child != found_obj: 660 raise AttributeError, \ 661 'parent.any matched more than one: %s %s' % \ 662 (found_obj.path, child.path) 663 found_obj = child 664 # search param space 665 for pname,pdesc in self._params.iteritems(): 666 if issubclass(pdesc.ptype, ptype): 667 match_obj = self._values[pname] 668 if found_obj != None and found_obj != match_obj: 669 raise AttributeError, \ 670 'parent.any matched more than one: %s' % obj.path 671 found_obj = match_obj 672 return found_obj, found_obj != None 673 674 def unproxy(self, base): 675 return self 676 677 def unproxy_all(self): 678 for param in self._params.iterkeys(): 679 value = self._values.get(param) 680 if value != None and proxy.isproxy(value): 681 try: 682 value = value.unproxy(self) 683 except: 684 print "Error in unproxying param '%s' of %s" % \ 685 (param, self.path()) 686 raise 687 setattr(self, param, value) 688 689 # Unproxy ports in sorted order so that 'append' operations on 690 # vector ports are done in a deterministic fashion. 691 port_names = self._ports.keys() 692 port_names.sort() 693 for port_name in port_names: 694 port = self._port_refs.get(port_name) 695 if port != None: 696 port.unproxy(self) 697 698 # Unproxy children in sorted order for determinism also. 699 child_names = self._children.keys() 700 child_names.sort() 701 for child in child_names: 702 self._children[child].unproxy_all() 703 704 def print_ini(self, ini_file): 705 print >>ini_file, '[' + self.path() + ']' # .ini section header 706 707 instanceDict[self.path()] = self 708 709 if hasattr(self, 'type'): 710 print >>ini_file, 'type=%s' % self.type 711 712 child_names = self._children.keys() 713 child_names.sort() 714 if len(child_names): 715 print >>ini_file, 'children=%s' % ' '.join(child_names) 716 717 param_names = self._params.keys() 718 param_names.sort() 719 for param in param_names: 720 value = self._values.get(param) 721 if value != None: 722 print >>ini_file, '%s=%s' % (param, 723 self._values[param].ini_str()) 724 725 port_names = self._ports.keys() 726 port_names.sort() 727 for port_name in port_names: 728 port = self._port_refs.get(port_name, None) 729 if port != None: 730 print >>ini_file, '%s=%s' % (port_name, port.ini_str()) 731 732 print >>ini_file # blank line between objects 733 734 for child in child_names: 735 self._children[child].print_ini(ini_file) 736 737 def getCCParams(self): 738 if self._ccParams: 739 return self._ccParams 740 741 cc_params_struct = getattr(m5.objects.params, '%sParams' % self.type) 742 cc_params = cc_params_struct() 743 cc_params.pyobj = self 744 cc_params.name = str(self) 745 746 param_names = self._params.keys() 747 param_names.sort() 748 for param in param_names: 749 value = self._values.get(param) 750 if value is None: 751 m5.fatal("%s.%s without default or user set value" \ 752 % (self.path(), param)) 753 754 value = value.getValue() 755 if isinstance(self._params[param], VectorParamDesc): 756 assert isinstance(value, list) 757 vec = getattr(cc_params, param) 758 assert not len(vec) 759 for v in value: 760 vec.append(v) 761 else: 762 setattr(cc_params, param, value) 763 764 port_names = self._ports.keys() 765 port_names.sort() 766 for port_name in port_names: 767 port = self._port_refs.get(port_name, None) 768 if port != None: 769 setattr(cc_params, port_name, port) 770 self._ccParams = cc_params 771 return self._ccParams 772 773 # Get C++ object corresponding to this object, calling C++ if 774 # necessary to construct it. Does *not* recursively create 775 # children. 776 def getCCObject(self): 777 if not self._ccObject: 778 # Cycles in the configuration heirarchy are not supported. This 779 # will catch the resulting recursion and stop. 780 self._ccObject = -1 781 params = self.getCCParams() 782 self._ccObject = params.create() 783 elif self._ccObject == -1: 784 raise RuntimeError, "%s: Cycle found in configuration heirarchy." \ 785 % self.path() 786 return self._ccObject 787 788 # Call C++ to create C++ object corresponding to this object and 789 # (recursively) all its children 790 def createCCObject(self): 791 self.getCCParams() 792 self.getCCObject() # force creation 793 for child in self._children.itervalues(): 794 child.createCCObject() 795 796 def getValue(self): 797 return self.getCCObject() 798 799 # Create C++ port connections corresponding to the connections in 800 # _port_refs (& recursively for all children) 801 def connectPorts(self): 802 for portRef in self._port_refs.itervalues(): 803 portRef.ccConnect() 804 for child in self._children.itervalues(): 805 child.connectPorts() 806 807 def startDrain(self, drain_event, recursive): 808 count = 0 809 if isinstance(self, SimObject): 810 count += self._ccObject.drain(drain_event) 811 if recursive: 812 for child in self._children.itervalues(): 813 count += child.startDrain(drain_event, True) 814 return count 815 816 def resume(self): 817 if isinstance(self, SimObject): 818 self._ccObject.resume() 819 for child in self._children.itervalues(): 820 child.resume() 821 822 def getMemoryMode(self): 823 if not isinstance(self, m5.objects.System): 824 return None 825 826 return self._ccObject.getMemoryMode() 827 828 def changeTiming(self, mode): 829 if isinstance(self, m5.objects.System): 830 # i don't know if there's a better way to do this - calling 831 # setMemoryMode directly from self._ccObject results in calling 832 # SimObject::setMemoryMode, not the System::setMemoryMode 833 self._ccObject.setMemoryMode(mode) 834 for child in self._children.itervalues(): 835 child.changeTiming(mode) 836 837 def takeOverFrom(self, old_cpu): 838 self._ccObject.takeOverFrom(old_cpu._ccObject) 839 840 # generate output file for 'dot' to display as a pretty graph. 841 # this code is currently broken. 842 def outputDot(self, dot): 843 label = "{%s|" % self.path 844 if isSimObject(self.realtype): 845 label += '%s|' % self.type 846 847 if self.children: 848 # instantiate children in same order they were added for 849 # backward compatibility (else we can end up with cpu1 850 # before cpu0). 851 for c in self.children: 852 dot.add_edge(pydot.Edge(self.path,c.path, style="bold")) 853 854 simobjs = [] 855 for param in self.params: 856 try: 857 if param.value is None: 858 raise AttributeError, 'Parameter with no value' 859 860 value = param.value 861 string = param.string(value) 862 except Exception, e: 863 msg = 'exception in %s:%s\n%s' % (self.name, param.name, e) 864 e.args = (msg, ) 865 raise 866 867 if isSimObject(param.ptype) and string != "Null": 868 simobjs.append(string) 869 else: 870 label += '%s = %s\\n' % (param.name, string) 871 872 for so in simobjs: 873 label += "|<%s> %s" % (so, so) 874 dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so, 875 tailport="w")) 876 label += '}' 877 dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label)) 878 879 # recursively dump out children 880 for c in self.children: 881 c.outputDot(dot) 882 883# Function to provide to C++ so it can look up instances based on paths 884def resolveSimObject(name): 885 obj = instanceDict[name] 886 return obj.getCCObject() 887 888# __all__ defines the list of symbols that get exported when 889# 'from config import *' is invoked. Try to keep this reasonably 890# short to avoid polluting other namespaces. 891__all__ = [ 'SimObject' ] 892