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