31 32import proxy 33import m5 34from util import * 35 36# These utility functions have to come first because they're 37# referenced in params.py... otherwise they won't be defined when we 38# import params below, and the recursive import of this file from 39# params.py will not find these names. 40def isSimObject(value): 41 return isinstance(value, SimObject) 42 43def isSimObjectClass(value): 44 return issubclass(value, SimObject) 45 46def isSimObjectSequence(value): 47 if not isinstance(value, (list, tuple)) or len(value) == 0: 48 return False 49 50 for val in value: 51 if not isNullPointer(val) and not isSimObject(val): 52 return False 53 54 return True 55 56def isSimObjectOrSequence(value): 57 return isSimObject(value) or isSimObjectSequence(value) 58 59# Have to import params up top since Param is referenced on initial 60# load (when SimObject class references Param to create a class 61# variable, the 'name' param)... 62from params import * 63# There are a few things we need that aren't in params.__all__ since 64# normal users don't need them 65from params import ParamDesc, VectorParamDesc, isNullPointer, SimObjVector 66 67noDot = False 68try: 69 import pydot 70except: 71 noDot = True 72 73##################################################################### 74# 75# M5 Python Configuration Utility 76# 77# The basic idea is to write simple Python programs that build Python 78# objects corresponding to M5 SimObjects for the desired simulation 79# configuration. For now, the Python emits a .ini file that can be 80# parsed by M5. In the future, some tighter integration between M5 81# and the Python interpreter may allow bypassing the .ini file. 82# 83# Each SimObject class in M5 is represented by a Python class with the 84# same name. The Python inheritance tree mirrors the M5 C++ tree 85# (e.g., SimpleCPU derives from BaseCPU in both cases, and all 86# SimObjects inherit from a single SimObject base class). To specify 87# an instance of an M5 SimObject in a configuration, the user simply 88# instantiates the corresponding Python object. The parameters for 89# that SimObject are given by assigning to attributes of the Python 90# object, either using keyword assignment in the constructor or in 91# separate assignment statements. For example: 92# 93# cache = BaseCache(size='64KB') 94# cache.hit_latency = 3 95# cache.assoc = 8 96# 97# The magic lies in the mapping of the Python attributes for SimObject 98# classes to the actual SimObject parameter specifications. This 99# allows parameter validity checking in the Python code. Continuing 100# the example above, the statements "cache.blurfl=3" or 101# "cache.assoc='hello'" would both result in runtime errors in Python, 102# since the BaseCache object has no 'blurfl' parameter and the 'assoc' 103# parameter requires an integer, respectively. This magic is done 104# primarily by overriding the special __setattr__ method that controls 105# assignment to object attributes. 106# 107# Once a set of Python objects have been instantiated in a hierarchy, 108# calling 'instantiate(obj)' (where obj is the root of the hierarchy) 109# will generate a .ini file. 110# 111##################################################################### 112 113# list of all SimObject classes 114allClasses = {} 115 116# dict to look up SimObjects based on path 117instanceDict = {} 118 119# The metaclass for SimObject. This class controls how new classes 120# that derive from SimObject are instantiated, and provides inherited 121# class behavior (just like a class controls how instances of that 122# class are instantiated, and provides inherited instance behavior). 123class MetaSimObject(type): 124 # Attributes that can be set only at initialization time 125 init_keywords = { 'abstract' : types.BooleanType, 126 'cxx_class' : types.StringType, 127 'cxx_type' : types.StringType, 128 'cxx_predecls' : types.ListType, 129 'swig_objdecls' : types.ListType, 130 'swig_predecls' : types.ListType, 131 'type' : types.StringType } 132 # Attributes that can be set any time 133 keywords = { 'check' : types.FunctionType } 134 135 # __new__ is called before __init__, and is where the statements 136 # in the body of the class definition get loaded into the class's 137 # __dict__. We intercept this to filter out parameter & port assignments 138 # and only allow "private" attributes to be passed to the base 139 # __new__ (starting with underscore). 140 def __new__(mcls, name, bases, dict): 141 assert name not in allClasses 142 143 # Copy "private" attributes, functions, and classes to the 144 # official dict. Everything else goes in _init_dict to be 145 # filtered in __init__. 146 cls_dict = {} 147 value_dict = {} 148 for key,val in dict.items(): 149 if key.startswith('_') or isinstance(val, (types.FunctionType, 150 types.TypeType)): 151 cls_dict[key] = val 152 else: 153 # must be a param/port setting 154 value_dict[key] = val 155 if 'abstract' not in value_dict: 156 value_dict['abstract'] = False 157 cls_dict['_value_dict'] = value_dict 158 cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict) 159 if 'type' in value_dict: 160 allClasses[name] = cls 161 return cls 162 163 # subclass initialization 164 def __init__(cls, name, bases, dict): 165 # calls type.__init__()... I think that's a no-op, but leave 166 # it here just in case it's not. 167 super(MetaSimObject, cls).__init__(name, bases, dict) 168 169 # initialize required attributes 170 171 # class-only attributes 172 cls._params = multidict() # param descriptions 173 cls._ports = multidict() # port descriptions 174 175 # class or instance attributes 176 cls._values = multidict() # param values 177 cls._port_refs = multidict() # port ref objects 178 cls._instantiated = False # really instantiated, cloned, or subclassed 179 180 # We don't support multiple inheritance. If you want to, you 181 # must fix multidict to deal with it properly. 182 if len(bases) > 1: 183 raise TypeError, "SimObjects do not support multiple inheritance" 184 185 base = bases[0] 186 187 # Set up general inheritance via multidicts. A subclass will 188 # inherit all its settings from the base class. The only time 189 # the following is not true is when we define the SimObject 190 # class itself (in which case the multidicts have no parent). 191 if isinstance(base, MetaSimObject): 192 cls._base = base 193 cls._params.parent = base._params 194 cls._ports.parent = base._ports 195 cls._values.parent = base._values 196 cls._port_refs.parent = base._port_refs 197 # mark base as having been subclassed 198 base._instantiated = True 199 else: 200 cls._base = None 201 202 # default keyword values 203 if 'type' in cls._value_dict: 204 if 'cxx_class' not in cls._value_dict: 205 cls._value_dict['cxx_class'] = cls._value_dict['type'] 206 207 cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class'] 208 209 if 'cxx_predecls' not in cls._value_dict: 210 # A forward class declaration is sufficient since we are 211 # just declaring a pointer. 212 class_path = cls._value_dict['cxx_class'].split('::') 213 class_path.reverse() 214 decl = 'class %s;' % class_path[0] 215 for ns in class_path[1:]: 216 decl = 'namespace %s { %s }' % (ns, decl) 217 cls._value_dict['cxx_predecls'] = [decl] 218 219 if 'swig_predecls' not in cls._value_dict: 220 # A forward class declaration is sufficient since we are 221 # just declaring a pointer. 222 cls._value_dict['swig_predecls'] = \ 223 cls._value_dict['cxx_predecls'] 224 225 if 'swig_objdecls' not in cls._value_dict: 226 cls._value_dict['swig_objdecls'] = [] 227 228 # Now process the _value_dict items. They could be defining 229 # new (or overriding existing) parameters or ports, setting 230 # class keywords (e.g., 'abstract'), or setting parameter 231 # values or port bindings. The first 3 can only be set when 232 # the class is defined, so we handle them here. The others 233 # can be set later too, so just emulate that by calling 234 # setattr(). 235 for key,val in cls._value_dict.items(): 236 # param descriptions 237 if isinstance(val, ParamDesc): 238 cls._new_param(key, val) 239 240 # port objects 241 elif isinstance(val, Port): 242 cls._new_port(key, val) 243 244 # init-time-only keywords 245 elif cls.init_keywords.has_key(key): 246 cls._set_keyword(key, val, cls.init_keywords[key]) 247 248 # default: use normal path (ends up in __setattr__) 249 else: 250 setattr(cls, key, val) 251 252 def _set_keyword(cls, keyword, val, kwtype): 253 if not isinstance(val, kwtype): 254 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \ 255 (keyword, type(val), kwtype) 256 if isinstance(val, types.FunctionType): 257 val = classmethod(val) 258 type.__setattr__(cls, keyword, val) 259 260 def _new_param(cls, name, pdesc): 261 # each param desc should be uniquely assigned to one variable 262 assert(not hasattr(pdesc, 'name')) 263 pdesc.name = name 264 cls._params[name] = pdesc 265 if hasattr(pdesc, 'default'): 266 cls._set_param(name, pdesc.default, pdesc) 267 268 def _set_param(cls, name, value, param): 269 assert(param.name == name) 270 try: 271 cls._values[name] = param.convert(value) 272 except Exception, e: 273 msg = "%s\nError setting param %s.%s to %s\n" % \ 274 (e, cls.__name__, name, value) 275 e.args = (msg, ) 276 raise 277 278 def _new_port(cls, name, port): 279 # each port should be uniquely assigned to one variable 280 assert(not hasattr(port, 'name')) 281 port.name = name 282 cls._ports[name] = port 283 if hasattr(port, 'default'): 284 cls._cls_get_port_ref(name).connect(port.default) 285 286 # same as _get_port_ref, effectively, but for classes 287 def _cls_get_port_ref(cls, attr): 288 # Return reference that can be assigned to another port 289 # via __setattr__. There is only ever one reference 290 # object per port, but we create them lazily here. 291 ref = cls._port_refs.get(attr) 292 if not ref: 293 ref = cls._ports[attr].makeRef(cls) 294 cls._port_refs[attr] = ref 295 return ref 296 297 # Set attribute (called on foo.attr = value when foo is an 298 # instance of class cls). 299 def __setattr__(cls, attr, value): 300 # normal processing for private attributes 301 if attr.startswith('_'): 302 type.__setattr__(cls, attr, value) 303 return 304 305 if cls.keywords.has_key(attr): 306 cls._set_keyword(attr, value, cls.keywords[attr]) 307 return 308 309 if cls._ports.has_key(attr): 310 cls._cls_get_port_ref(attr).connect(value) 311 return 312 313 if isSimObjectOrSequence(value) and cls._instantiated: 314 raise RuntimeError, \ 315 "cannot set SimObject parameter '%s' after\n" \ 316 " class %s has been instantiated or subclassed" \ 317 % (attr, cls.__name__) 318 319 # check for param 320 param = cls._params.get(attr) 321 if param: 322 cls._set_param(attr, value, param) 323 return 324 325 if isSimObjectOrSequence(value): 326 # If RHS is a SimObject, it's an implicit child assignment. 327 # Classes don't have children, so we just put this object 328 # in _values; later, each instance will do a 'setattr(self, 329 # attr, _values[attr])' in SimObject.__init__ which will 330 # add this object as a child. 331 cls._values[attr] = value 332 return 333 334 # no valid assignment... raise exception 335 raise AttributeError, \ 336 "Class %s has no parameter \'%s\'" % (cls.__name__, attr) 337 338 def __getattr__(cls, attr): 339 if cls._values.has_key(attr): 340 return cls._values[attr] 341 342 raise AttributeError, \ 343 "object '%s' has no attribute '%s'" % (cls.__name__, attr) 344 345 def __str__(cls): 346 return cls.__name__ 347 348 def cxx_decl(cls): 349 code = "#ifndef __PARAMS__%s\n" % cls 350 code += "#define __PARAMS__%s\n\n" % cls 351 352 # The 'dict' attribute restricts us to the params declared in 353 # the object itself, not including inherited params (which 354 # will also be inherited from the base class's param struct 355 # here). 356 params = cls._params.local.values() 357 try: 358 ptypes = [p.ptype for p in params] 359 except: 360 print cls, p, p.ptype_str 361 print params 362 raise 363 364 # get a list of lists of predeclaration lines 365 predecls = [] 366 predecls.extend(cls.cxx_predecls) 367 for p in params: 368 predecls.extend(p.cxx_predecls()) 369 # remove redundant lines 370 predecls2 = [] 371 for pd in predecls: 372 if pd not in predecls2: 373 predecls2.append(pd) 374 predecls2.sort() 375 code += "\n".join(predecls2) 376 code += "\n\n"; 377 378 if cls._base: 379 code += '#include "params/%s.hh"\n\n' % cls._base.type 380 381 for ptype in ptypes: 382 if issubclass(ptype, Enum): 383 code += '#include "enums/%s.hh"\n' % ptype.__name__ 384 code += "\n\n" 385 386 code += cls.cxx_struct(cls._base, params) 387 388 # close #ifndef __PARAMS__* guard 389 code += "\n#endif\n" 390 return code 391 392 def cxx_struct(cls, base, params): 393 if cls == SimObject: 394 return '#include "sim/sim_object_params.hh"\n' 395 396 # now generate the actual param struct 397 code = "struct %sParams" % cls 398 if base: 399 code += " : public %sParams" % base.type 400 code += "\n{\n" 401 if not hasattr(cls, 'abstract') or not cls.abstract: 402 if 'type' in cls.__dict__: 403 code += " %s create();\n" % cls.cxx_type 404 decls = [p.cxx_decl() for p in params] 405 decls.sort() 406 code += "".join([" %s\n" % d for d in decls]) 407 code += "};\n" 408 409 return code 410 411 def swig_decl(cls): 412 code = '%%module %s\n' % cls 413 414 code += '%{\n' 415 code += '#include "params/%s.hh"\n' % cls 416 code += '%}\n\n' 417 418 # The 'dict' attribute restricts us to the params declared in 419 # the object itself, not including inherited params (which 420 # will also be inherited from the base class's param struct 421 # here). 422 params = cls._params.local.values() 423 ptypes = [p.ptype for p in params] 424 425 # get a list of lists of predeclaration lines 426 predecls = [] 427 predecls.extend([ p.swig_predecls() for p in params ]) 428 # flatten 429 predecls = reduce(lambda x,y:x+y, predecls, []) 430 # remove redundant lines 431 predecls2 = [] 432 for pd in predecls: 433 if pd not in predecls2: 434 predecls2.append(pd) 435 predecls2.sort() 436 code += "\n".join(predecls2) 437 code += "\n\n"; 438 439 if cls._base: 440 code += '%%import "params/%s.i"\n\n' % cls._base.type 441 442 for ptype in ptypes: 443 if issubclass(ptype, Enum): 444 code += '%%import "enums/%s.hh"\n' % ptype.__name__ 445 code += "\n\n" 446 447 code += '%%import "params/%s_type.hh"\n\n' % cls 448 code += '%%include "params/%s.hh"\n\n' % cls 449 450 return code 451 452# The SimObject class is the root of the special hierarchy. Most of 453# the code in this class deals with the configuration hierarchy itself 454# (parent/child node relationships). 455class SimObject(object): 456 # Specify metaclass. Any class inheriting from SimObject will 457 # get this metaclass. 458 __metaclass__ = MetaSimObject 459 type = 'SimObject' 460 abstract = True 461 462 swig_objdecls = [ '%include "python/swig/sim_object.i"' ] 463 464 # Initialize new instance. For objects with SimObject-valued 465 # children, we need to recursively clone the classes represented 466 # by those param values as well in a consistent "deep copy"-style 467 # fashion. That is, we want to make sure that each instance is 468 # cloned only once, and that if there are multiple references to 469 # the same original object, we end up with the corresponding 470 # cloned references all pointing to the same cloned instance. 471 def __init__(self, **kwargs): 472 ancestor = kwargs.get('_ancestor') 473 memo_dict = kwargs.get('_memo') 474 if memo_dict is None: 475 # prepare to memoize any recursively instantiated objects 476 memo_dict = {} 477 elif ancestor: 478 # memoize me now to avoid problems with recursive calls 479 memo_dict[ancestor] = self 480 481 if not ancestor: 482 ancestor = self.__class__ 483 ancestor._instantiated = True 484 485 # initialize required attributes 486 self._parent = None 487 self._children = {} 488 self._ccObject = None # pointer to C++ object 489 self._ccParams = None 490 self._instantiated = False # really "cloned" 491 492 # Inherit parameter values from class using multidict so 493 # individual value settings can be overridden. 494 self._values = multidict(ancestor._values) 495 # clone SimObject-valued parameters 496 for key,val in ancestor._values.iteritems(): 497 if isSimObject(val): 498 setattr(self, key, val(_memo=memo_dict)) 499 elif isSimObjectSequence(val) and len(val): 500 setattr(self, key, [ v(_memo=memo_dict) for v in val ]) 501 # clone port references. no need to use a multidict here 502 # since we will be creating new references for all ports. 503 self._port_refs = {} 504 for key,val in ancestor._port_refs.iteritems(): 505 self._port_refs[key] = val.clone(self, memo_dict) 506 # apply attribute assignments from keyword args, if any 507 for key,val in kwargs.iteritems(): 508 setattr(self, key, val) 509 510 # "Clone" the current instance by creating another instance of 511 # this instance's class, but that inherits its parameter values 512 # and port mappings from the current instance. If we're in a 513 # "deep copy" recursive clone, check the _memo dict to see if 514 # we've already cloned this instance. 515 def __call__(self, **kwargs): 516 memo_dict = kwargs.get('_memo') 517 if memo_dict is None: 518 # no memo_dict: must be top-level clone operation. 519 # this is only allowed at the root of a hierarchy 520 if self._parent: 521 raise RuntimeError, "attempt to clone object %s " \ 522 "not at the root of a tree (parent = %s)" \ 523 % (self, self._parent) 524 # create a new dict and use that. 525 memo_dict = {} 526 kwargs['_memo'] = memo_dict 527 elif memo_dict.has_key(self): 528 # clone already done & memoized 529 return memo_dict[self] 530 return self.__class__(_ancestor = self, **kwargs) 531 532 def _get_port_ref(self, attr): 533 # Return reference that can be assigned to another port 534 # via __setattr__. There is only ever one reference 535 # object per port, but we create them lazily here. 536 ref = self._port_refs.get(attr) 537 if not ref: 538 ref = self._ports[attr].makeRef(self) 539 self._port_refs[attr] = ref 540 return ref 541 542 def __getattr__(self, attr): 543 if self._ports.has_key(attr): 544 return self._get_port_ref(attr) 545 546 if self._values.has_key(attr): 547 return self._values[attr] 548 549 raise AttributeError, "object '%s' has no attribute '%s'" \ 550 % (self.__class__.__name__, attr) 551 552 # Set attribute (called on foo.attr = value when foo is an 553 # instance of class cls). 554 def __setattr__(self, attr, value): 555 # normal processing for private attributes 556 if attr.startswith('_'): 557 object.__setattr__(self, attr, value) 558 return 559 560 if self._ports.has_key(attr): 561 # set up port connection 562 self._get_port_ref(attr).connect(value) 563 return 564 565 if isSimObjectOrSequence(value) and self._instantiated: 566 raise RuntimeError, \ 567 "cannot set SimObject parameter '%s' after\n" \ 568 " instance been cloned %s" % (attr, `self`) 569 570 # must be SimObject param 571 param = self._params.get(attr) 572 if param: 573 try: 574 value = param.convert(value) 575 except Exception, e: 576 msg = "%s\nError setting param %s.%s to %s\n" % \ 577 (e, self.__class__.__name__, attr, value) 578 e.args = (msg, ) 579 raise 580 self._set_child(attr, value) 581 return 582 583 if isSimObjectOrSequence(value): 584 self._set_child(attr, value) 585 return 586 587 # no valid assignment... raise exception 588 raise AttributeError, "Class %s has no parameter %s" \ 589 % (self.__class__.__name__, attr) 590 591 592 # this hack allows tacking a '[0]' onto parameters that may or may 593 # not be vectors, and always getting the first element (e.g. cpus) 594 def __getitem__(self, key): 595 if key == 0: 596 return self 597 raise TypeError, "Non-zero index '%s' to SimObject" % key 598 599 # clear out children with given name, even if it's a vector 600 def clear_child(self, name): 601 if not self._children.has_key(name): 602 return 603 child = self._children[name] 604 if isinstance(child, SimObjVector): 605 for i in xrange(len(child)): 606 del self._children["s%d" % (name, i)] 607 del self._children[name] 608 609 def add_child(self, name, value): 610 self._children[name] = value 611 612 def _maybe_set_parent(self, parent, name): 613 if not self._parent: 614 self._parent = parent 615 self._name = name 616 parent.add_child(name, self) 617 618 def _set_child(self, attr, value): 619 # if RHS is a SimObject, it's an implicit child assignment 620 # clear out old child with this name, if any 621 self.clear_child(attr) 622 623 if isSimObject(value): 624 value._maybe_set_parent(self, attr) 625 elif isSimObjectSequence(value): 626 value = SimObjVector(value) 627 if len(value) == 1: 628 value[0]._maybe_set_parent(self, attr) 629 else:
| 33 34import proxy 35import m5 36from util import * 37 38# These utility functions have to come first because they're 39# referenced in params.py... otherwise they won't be defined when we 40# import params below, and the recursive import of this file from 41# params.py will not find these names. 42def isSimObject(value): 43 return isinstance(value, SimObject) 44 45def isSimObjectClass(value): 46 return issubclass(value, SimObject) 47 48def isSimObjectSequence(value): 49 if not isinstance(value, (list, tuple)) or len(value) == 0: 50 return False 51 52 for val in value: 53 if not isNullPointer(val) and not isSimObject(val): 54 return False 55 56 return True 57 58def isSimObjectOrSequence(value): 59 return isSimObject(value) or isSimObjectSequence(value) 60 61# Have to import params up top since Param is referenced on initial 62# load (when SimObject class references Param to create a class 63# variable, the 'name' param)... 64from params import * 65# There are a few things we need that aren't in params.__all__ since 66# normal users don't need them 67from params import ParamDesc, VectorParamDesc, isNullPointer, SimObjVector 68 69noDot = False 70try: 71 import pydot 72except: 73 noDot = True 74 75##################################################################### 76# 77# M5 Python Configuration Utility 78# 79# The basic idea is to write simple Python programs that build Python 80# objects corresponding to M5 SimObjects for the desired simulation 81# configuration. For now, the Python emits a .ini file that can be 82# parsed by M5. In the future, some tighter integration between M5 83# and the Python interpreter may allow bypassing the .ini file. 84# 85# Each SimObject class in M5 is represented by a Python class with the 86# same name. The Python inheritance tree mirrors the M5 C++ tree 87# (e.g., SimpleCPU derives from BaseCPU in both cases, and all 88# SimObjects inherit from a single SimObject base class). To specify 89# an instance of an M5 SimObject in a configuration, the user simply 90# instantiates the corresponding Python object. The parameters for 91# that SimObject are given by assigning to attributes of the Python 92# object, either using keyword assignment in the constructor or in 93# separate assignment statements. For example: 94# 95# cache = BaseCache(size='64KB') 96# cache.hit_latency = 3 97# cache.assoc = 8 98# 99# The magic lies in the mapping of the Python attributes for SimObject 100# classes to the actual SimObject parameter specifications. This 101# allows parameter validity checking in the Python code. Continuing 102# the example above, the statements "cache.blurfl=3" or 103# "cache.assoc='hello'" would both result in runtime errors in Python, 104# since the BaseCache object has no 'blurfl' parameter and the 'assoc' 105# parameter requires an integer, respectively. This magic is done 106# primarily by overriding the special __setattr__ method that controls 107# assignment to object attributes. 108# 109# Once a set of Python objects have been instantiated in a hierarchy, 110# calling 'instantiate(obj)' (where obj is the root of the hierarchy) 111# will generate a .ini file. 112# 113##################################################################### 114 115# list of all SimObject classes 116allClasses = {} 117 118# dict to look up SimObjects based on path 119instanceDict = {} 120 121# The metaclass for SimObject. This class controls how new classes 122# that derive from SimObject are instantiated, and provides inherited 123# class behavior (just like a class controls how instances of that 124# class are instantiated, and provides inherited instance behavior). 125class MetaSimObject(type): 126 # Attributes that can be set only at initialization time 127 init_keywords = { 'abstract' : types.BooleanType, 128 'cxx_class' : types.StringType, 129 'cxx_type' : types.StringType, 130 'cxx_predecls' : types.ListType, 131 'swig_objdecls' : types.ListType, 132 'swig_predecls' : types.ListType, 133 'type' : types.StringType } 134 # Attributes that can be set any time 135 keywords = { 'check' : types.FunctionType } 136 137 # __new__ is called before __init__, and is where the statements 138 # in the body of the class definition get loaded into the class's 139 # __dict__. We intercept this to filter out parameter & port assignments 140 # and only allow "private" attributes to be passed to the base 141 # __new__ (starting with underscore). 142 def __new__(mcls, name, bases, dict): 143 assert name not in allClasses 144 145 # Copy "private" attributes, functions, and classes to the 146 # official dict. Everything else goes in _init_dict to be 147 # filtered in __init__. 148 cls_dict = {} 149 value_dict = {} 150 for key,val in dict.items(): 151 if key.startswith('_') or isinstance(val, (types.FunctionType, 152 types.TypeType)): 153 cls_dict[key] = val 154 else: 155 # must be a param/port setting 156 value_dict[key] = val 157 if 'abstract' not in value_dict: 158 value_dict['abstract'] = False 159 cls_dict['_value_dict'] = value_dict 160 cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict) 161 if 'type' in value_dict: 162 allClasses[name] = cls 163 return cls 164 165 # subclass initialization 166 def __init__(cls, name, bases, dict): 167 # calls type.__init__()... I think that's a no-op, but leave 168 # it here just in case it's not. 169 super(MetaSimObject, cls).__init__(name, bases, dict) 170 171 # initialize required attributes 172 173 # class-only attributes 174 cls._params = multidict() # param descriptions 175 cls._ports = multidict() # port descriptions 176 177 # class or instance attributes 178 cls._values = multidict() # param values 179 cls._port_refs = multidict() # port ref objects 180 cls._instantiated = False # really instantiated, cloned, or subclassed 181 182 # We don't support multiple inheritance. If you want to, you 183 # must fix multidict to deal with it properly. 184 if len(bases) > 1: 185 raise TypeError, "SimObjects do not support multiple inheritance" 186 187 base = bases[0] 188 189 # Set up general inheritance via multidicts. A subclass will 190 # inherit all its settings from the base class. The only time 191 # the following is not true is when we define the SimObject 192 # class itself (in which case the multidicts have no parent). 193 if isinstance(base, MetaSimObject): 194 cls._base = base 195 cls._params.parent = base._params 196 cls._ports.parent = base._ports 197 cls._values.parent = base._values 198 cls._port_refs.parent = base._port_refs 199 # mark base as having been subclassed 200 base._instantiated = True 201 else: 202 cls._base = None 203 204 # default keyword values 205 if 'type' in cls._value_dict: 206 if 'cxx_class' not in cls._value_dict: 207 cls._value_dict['cxx_class'] = cls._value_dict['type'] 208 209 cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class'] 210 211 if 'cxx_predecls' not in cls._value_dict: 212 # A forward class declaration is sufficient since we are 213 # just declaring a pointer. 214 class_path = cls._value_dict['cxx_class'].split('::') 215 class_path.reverse() 216 decl = 'class %s;' % class_path[0] 217 for ns in class_path[1:]: 218 decl = 'namespace %s { %s }' % (ns, decl) 219 cls._value_dict['cxx_predecls'] = [decl] 220 221 if 'swig_predecls' not in cls._value_dict: 222 # A forward class declaration is sufficient since we are 223 # just declaring a pointer. 224 cls._value_dict['swig_predecls'] = \ 225 cls._value_dict['cxx_predecls'] 226 227 if 'swig_objdecls' not in cls._value_dict: 228 cls._value_dict['swig_objdecls'] = [] 229 230 # Now process the _value_dict items. They could be defining 231 # new (or overriding existing) parameters or ports, setting 232 # class keywords (e.g., 'abstract'), or setting parameter 233 # values or port bindings. The first 3 can only be set when 234 # 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 633 self._values[attr] = value 634 635 def path(self): 636 if not self._parent: 637 return 'root' 638 ppath = self._parent.path() 639 if ppath == 'root': 640 return self._name 641 return ppath + "." + self._name 642 643 def __str__(self): 644 return self.path() 645 646 def ini_str(self): 647 return self.path() 648 649 def find_any(self, ptype): 650 if isinstance(self, ptype): 651 return self, True 652 653 found_obj = None 654 for child in self._children.itervalues(): 655 if isinstance(child, ptype): 656 if found_obj != None and child != found_obj: 657 raise AttributeError, \ 658 'parent.any matched more than one: %s %s' % \ 659 (found_obj.path, child.path) 660 found_obj = child 661 # search param space 662 for pname,pdesc in self._params.iteritems(): 663 if issubclass(pdesc.ptype, ptype): 664 match_obj = self._values[pname] 665 if found_obj != None and found_obj != match_obj: 666 raise AttributeError, \ 667 'parent.any matched more than one: %s' % obj.path 668 found_obj = match_obj 669 return found_obj, found_obj != None 670 671 def unproxy(self, base): 672 return self 673 674 def unproxy_all(self): 675 for param in self._params.iterkeys(): 676 value = self._values.get(param) 677 if value != None and proxy.isproxy(value): 678 try: 679 value = value.unproxy(self) 680 except: 681 print "Error in unproxying param '%s' of %s" % \ 682 (param, self.path()) 683 raise 684 setattr(self, param, value) 685 686 # Unproxy ports in sorted order so that 'append' operations on 687 # vector ports are done in a deterministic fashion. 688 port_names = self._ports.keys() 689 port_names.sort() 690 for port_name in port_names: 691 port = self._port_refs.get(port_name) 692 if port != None: 693 port.unproxy(self) 694 695 # Unproxy children in sorted order for determinism also. 696 child_names = self._children.keys() 697 child_names.sort() 698 for child in child_names: 699 self._children[child].unproxy_all() 700 701 def print_ini(self, ini_file): 702 print >>ini_file, '[' + self.path() + ']' # .ini section header 703 704 instanceDict[self.path()] = self 705 706 if hasattr(self, 'type'): 707 print >>ini_file, 'type=%s' % self.type 708 709 child_names = self._children.keys() 710 child_names.sort() 711 if len(child_names): 712 print >>ini_file, 'children=%s' % ' '.join(child_names) 713 714 param_names = self._params.keys() 715 param_names.sort() 716 for param in param_names: 717 value = self._values.get(param) 718 if value != None: 719 print >>ini_file, '%s=%s' % (param, 720 self._values[param].ini_str()) 721 722 port_names = self._ports.keys() 723 port_names.sort() 724 for port_name in port_names: 725 port = self._port_refs.get(port_name, None) 726 if port != None: 727 print >>ini_file, '%s=%s' % (port_name, port.ini_str()) 728 729 print >>ini_file # blank line between objects 730 731 for child in child_names: 732 self._children[child].print_ini(ini_file) 733 734 def getCCParams(self): 735 if self._ccParams: 736 return self._ccParams 737 738 cc_params_struct = getattr(m5.objects.params, '%sParams' % self.type) 739 cc_params = cc_params_struct() 740 cc_params.pyobj = self 741 cc_params.name = str(self) 742 743 param_names = self._params.keys() 744 param_names.sort() 745 for param in param_names: 746 value = self._values.get(param) 747 if value is None: 748 continue 749 750 value = value.getValue() 751 if isinstance(self._params[param], VectorParamDesc): 752 assert isinstance(value, list) 753 vec = getattr(cc_params, param) 754 assert not len(vec) 755 for v in value: 756 vec.append(v) 757 else: 758 setattr(cc_params, param, value) 759 760 port_names = self._ports.keys() 761 port_names.sort() 762 for port_name in port_names: 763 port = self._port_refs.get(port_name, None) 764 if port != None: 765 setattr(cc_params, port_name, port) 766 self._ccParams = cc_params 767 return self._ccParams 768 769 # Get C++ object corresponding to this object, calling C++ if 770 # necessary to construct it. Does *not* recursively create 771 # children. 772 def getCCObject(self): 773 if not self._ccObject: 774 # Cycles in the configuration heirarchy are not supported. This 775 # will catch the resulting recursion and stop. 776 self._ccObject = -1 777 params = self.getCCParams() 778 self._ccObject = params.create() 779 elif self._ccObject == -1: 780 raise RuntimeError, "%s: Cycle found in configuration heirarchy." \ 781 % self.path() 782 return self._ccObject 783 784 # Call C++ to create C++ object corresponding to this object and 785 # (recursively) all its children 786 def createCCObject(self): 787 self.getCCParams() 788 self.getCCObject() # force creation 789 for child in self._children.itervalues(): 790 child.createCCObject() 791 792 def getValue(self): 793 return self.getCCObject() 794 795 # Create C++ port connections corresponding to the connections in 796 # _port_refs (& recursively for all children) 797 def connectPorts(self): 798 for portRef in self._port_refs.itervalues(): 799 portRef.ccConnect() 800 for child in self._children.itervalues(): 801 child.connectPorts() 802 803 def startDrain(self, drain_event, recursive): 804 count = 0 805 if isinstance(self, SimObject): 806 count += self._ccObject.drain(drain_event) 807 if recursive: 808 for child in self._children.itervalues(): 809 count += child.startDrain(drain_event, True) 810 return count 811 812 def resume(self): 813 if isinstance(self, SimObject): 814 self._ccObject.resume() 815 for child in self._children.itervalues(): 816 child.resume() 817 818 def getMemoryMode(self): 819 if not isinstance(self, m5.objects.System): 820 return None 821 822 return self._ccObject.getMemoryMode() 823 824 def changeTiming(self, mode): 825 if isinstance(self, m5.objects.System): 826 # i don't know if there's a better way to do this - calling 827 # setMemoryMode directly from self._ccObject results in calling 828 # SimObject::setMemoryMode, not the System::setMemoryMode 829 self._ccObject.setMemoryMode(mode) 830 for child in self._children.itervalues(): 831 child.changeTiming(mode) 832 833 def takeOverFrom(self, old_cpu): 834 self._ccObject.takeOverFrom(old_cpu._ccObject) 835 836 # generate output file for 'dot' to display as a pretty graph. 837 # this code is currently broken. 838 def outputDot(self, dot): 839 label = "{%s|" % self.path 840 if isSimObject(self.realtype): 841 label += '%s|' % self.type 842 843 if self.children: 844 # instantiate children in same order they were added for 845 # backward compatibility (else we can end up with cpu1 846 # before cpu0). 847 for c in self.children: 848 dot.add_edge(pydot.Edge(self.path,c.path, style="bold")) 849 850 simobjs = [] 851 for param in self.params: 852 try: 853 if param.value is None: 854 raise AttributeError, 'Parameter with no value' 855 856 value = param.value 857 string = param.string(value) 858 except Exception, e: 859 msg = 'exception in %s:%s\n%s' % (self.name, param.name, e) 860 e.args = (msg, ) 861 raise 862 863 if isSimObject(param.ptype) and string != "Null": 864 simobjs.append(string) 865 else: 866 label += '%s = %s\\n' % (param.name, string) 867 868 for so in simobjs: 869 label += "|<%s> %s" % (so, so) 870 dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so, 871 tailport="w")) 872 label += '}' 873 dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label)) 874 875 # recursively dump out children 876 for c in self.children: 877 c.outputDot(dot) 878 879# Function to provide to C++ so it can look up instances based on paths 880def resolveSimObject(name): 881 obj = instanceDict[name] 882 return obj.getCCObject() 883 884# __all__ defines the list of symbols that get exported when 885# 'from config import *' is invoked. Try to keep this reasonably 886# short to avoid polluting other namespaces. 887__all__ = [ 'SimObject' ]
| 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 continue 752 753 value = value.getValue() 754 if isinstance(self._params[param], VectorParamDesc): 755 assert isinstance(value, list) 756 vec = getattr(cc_params, param) 757 assert not len(vec) 758 for v in value: 759 vec.append(v) 760 else: 761 setattr(cc_params, param, value) 762 763 port_names = self._ports.keys() 764 port_names.sort() 765 for port_name in port_names: 766 port = self._port_refs.get(port_name, None) 767 if port != None: 768 setattr(cc_params, port_name, port) 769 self._ccParams = cc_params 770 return self._ccParams 771 772 # Get C++ object corresponding to this object, calling C++ if 773 # necessary to construct it. Does *not* recursively create 774 # children. 775 def getCCObject(self): 776 if not self._ccObject: 777 # Cycles in the configuration heirarchy are not supported. This 778 # will catch the resulting recursion and stop. 779 self._ccObject = -1 780 params = self.getCCParams() 781 self._ccObject = params.create() 782 elif self._ccObject == -1: 783 raise RuntimeError, "%s: Cycle found in configuration heirarchy." \ 784 % self.path() 785 return self._ccObject 786 787 # Call C++ to create C++ object corresponding to this object and 788 # (recursively) all its children 789 def createCCObject(self): 790 self.getCCParams() 791 self.getCCObject() # force creation 792 for child in self._children.itervalues(): 793 child.createCCObject() 794 795 def getValue(self): 796 return self.getCCObject() 797 798 # Create C++ port connections corresponding to the connections in 799 # _port_refs (& recursively for all children) 800 def connectPorts(self): 801 for portRef in self._port_refs.itervalues(): 802 portRef.ccConnect() 803 for child in self._children.itervalues(): 804 child.connectPorts() 805 806 def startDrain(self, drain_event, recursive): 807 count = 0 808 if isinstance(self, SimObject): 809 count += self._ccObject.drain(drain_event) 810 if recursive: 811 for child in self._children.itervalues(): 812 count += child.startDrain(drain_event, True) 813 return count 814 815 def resume(self): 816 if isinstance(self, SimObject): 817 self._ccObject.resume() 818 for child in self._children.itervalues(): 819 child.resume() 820 821 def getMemoryMode(self): 822 if not isinstance(self, m5.objects.System): 823 return None 824 825 return self._ccObject.getMemoryMode() 826 827 def changeTiming(self, mode): 828 if isinstance(self, m5.objects.System): 829 # i don't know if there's a better way to do this - calling 830 # setMemoryMode directly from self._ccObject results in calling 831 # SimObject::setMemoryMode, not the System::setMemoryMode 832 self._ccObject.setMemoryMode(mode) 833 for child in self._children.itervalues(): 834 child.changeTiming(mode) 835 836 def takeOverFrom(self, old_cpu): 837 self._ccObject.takeOverFrom(old_cpu._ccObject) 838 839 # generate output file for 'dot' to display as a pretty graph. 840 # this code is currently broken. 841 def outputDot(self, dot): 842 label = "{%s|" % self.path 843 if isSimObject(self.realtype): 844 label += '%s|' % self.type 845 846 if self.children: 847 # instantiate children in same order they were added for 848 # backward compatibility (else we can end up with cpu1 849 # before cpu0). 850 for c in self.children: 851 dot.add_edge(pydot.Edge(self.path,c.path, style="bold")) 852 853 simobjs = [] 854 for param in self.params: 855 try: 856 if param.value is None: 857 raise AttributeError, 'Parameter with no value' 858 859 value = param.value 860 string = param.string(value) 861 except Exception, e: 862 msg = 'exception in %s:%s\n%s' % (self.name, param.name, e) 863 e.args = (msg, ) 864 raise 865 866 if isSimObject(param.ptype) and string != "Null": 867 simobjs.append(string) 868 else: 869 label += '%s = %s\\n' % (param.name, string) 870 871 for so in simobjs: 872 label += "|<%s> %s" % (so, so) 873 dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so, 874 tailport="w")) 875 label += '}' 876 dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label)) 877 878 # recursively dump out children 879 for c in self.children: 880 c.outputDot(dot) 881 882# Function to provide to C++ so it can look up instances based on paths 883def resolveSimObject(name): 884 obj = instanceDict[name] 885 return obj.getCCObject() 886 887# __all__ defines the list of symbols that get exported when 888# 'from config import *' is invoked. Try to keep this reasonably 889# short to avoid polluting other namespaces. 890__all__ = [ 'SimObject' ]
|