SimObject.py (3103:330ec058b026) | SimObject.py (3105:993f1abefd67) |
---|---|
1# Copyright (c) 2004-2006 The Regents of The University of Michigan 2# All rights reserved. 3# 4# Redistribution and use in source and binary forms, with or without 5# modification, are permitted provided that the following conditions are 6# met: redistributions of source code must retain the above copyright 7# notice, this list of conditions and the following disclaimer; 8# redistributions in binary form must reproduce the above copyright --- 147 unchanged lines hidden (view full) --- 156 # initialize required attributes 157 158 # class-only attributes 159 cls._params = multidict() # param descriptions 160 cls._ports = multidict() # port descriptions 161 162 # class or instance attributes 163 cls._values = multidict() # param values | 1# Copyright (c) 2004-2006 The Regents of The University of Michigan 2# All rights reserved. 3# 4# Redistribution and use in source and binary forms, with or without 5# modification, are permitted provided that the following conditions are 6# met: redistributions of source code must retain the above copyright 7# notice, this list of conditions and the following disclaimer; 8# redistributions in binary form must reproduce the above copyright --- 147 unchanged lines hidden (view full) --- 156 # initialize required attributes 157 158 # class-only attributes 159 cls._params = multidict() # param descriptions 160 cls._ports = multidict() # port descriptions 161 162 # class or instance attributes 163 cls._values = multidict() # param values |
164 cls._port_map = multidict() # port bindings | 164 cls._port_refs = multidict() # port ref objects |
165 cls._instantiated = False # really instantiated, cloned, or subclassed 166 167 # We don't support multiple inheritance. If you want to, you 168 # must fix multidict to deal with it properly. 169 if len(bases) > 1: 170 raise TypeError, "SimObjects do not support multiple inheritance" 171 172 base = bases[0] 173 174 # Set up general inheritance via multidicts. A subclass will 175 # inherit all its settings from the base class. The only time 176 # the following is not true is when we define the SimObject 177 # class itself (in which case the multidicts have no parent). 178 if isinstance(base, MetaSimObject): 179 cls._params.parent = base._params 180 cls._ports.parent = base._ports 181 cls._values.parent = base._values | 165 cls._instantiated = False # really instantiated, cloned, or subclassed 166 167 # We don't support multiple inheritance. If you want to, you 168 # must fix multidict to deal with it properly. 169 if len(bases) > 1: 170 raise TypeError, "SimObjects do not support multiple inheritance" 171 172 base = bases[0] 173 174 # Set up general inheritance via multidicts. A subclass will 175 # inherit all its settings from the base class. The only time 176 # the following is not true is when we define the SimObject 177 # class itself (in which case the multidicts have no parent). 178 if isinstance(base, MetaSimObject): 179 cls._params.parent = base._params 180 cls._ports.parent = base._ports 181 cls._values.parent = base._values |
182 cls._port_map.parent = base._port_map | 182 cls._port_refs.parent = base._port_refs |
183 # mark base as having been subclassed 184 base._instantiated = True 185 186 # Now process the _value_dict items. They could be defining 187 # new (or overriding existing) parameters or ports, setting 188 # class keywords (e.g., 'abstract'), or setting parameter 189 # values or port bindings. The first 3 can only be set when 190 # the class is defined, so we handle them here. The others 191 # can be set later too, so just emulate that by calling 192 # setattr(). 193 for key,val in cls._value_dict.items(): 194 # param descriptions 195 if isinstance(val, ParamDesc): 196 cls._new_param(key, val) 197 198 # port objects 199 elif isinstance(val, Port): | 183 # mark base as having been subclassed 184 base._instantiated = True 185 186 # Now process the _value_dict items. They could be defining 187 # new (or overriding existing) parameters or ports, setting 188 # class keywords (e.g., 'abstract'), or setting parameter 189 # values or port bindings. The first 3 can only be set when 190 # the class is defined, so we handle them here. The others 191 # can be set later too, so just emulate that by calling 192 # setattr(). 193 for key,val in cls._value_dict.items(): 194 # param descriptions 195 if isinstance(val, ParamDesc): 196 cls._new_param(key, val) 197 198 # port objects 199 elif isinstance(val, Port): |
200 cls._ports[key] = val | 200 cls._new_port(key, val) |
201 202 # init-time-only keywords 203 elif cls.init_keywords.has_key(key): 204 cls._set_keyword(key, val, cls.init_keywords[key]) 205 206 # default: use normal path (ends up in __setattr__) 207 else: 208 setattr(cls, key, val) --- 13 unchanged lines hidden (view full) --- 222 type.__setattr__(cls, keyword, val) 223 224 def _new_param(cls, name, pdesc): 225 # each param desc should be uniquely assigned to one variable 226 assert(not hasattr(pdesc, 'name')) 227 pdesc.name = name 228 cls._params[name] = pdesc 229 if hasattr(pdesc, 'default'): | 201 202 # init-time-only keywords 203 elif cls.init_keywords.has_key(key): 204 cls._set_keyword(key, val, cls.init_keywords[key]) 205 206 # default: use normal path (ends up in __setattr__) 207 else: 208 setattr(cls, key, val) --- 13 unchanged lines hidden (view full) --- 222 type.__setattr__(cls, keyword, val) 223 224 def _new_param(cls, name, pdesc): 225 # each param desc should be uniquely assigned to one variable 226 assert(not hasattr(pdesc, 'name')) 227 pdesc.name = name 228 cls._params[name] = pdesc 229 if hasattr(pdesc, 'default'): |
230 setattr(cls, name, pdesc.default) | 230 cls._set_param(name, pdesc.default, pdesc) |
231 | 231 |
232 def _set_param(cls, name, value, param): 233 assert(param.name == name) 234 try: 235 cls._values[name] = param.convert(value) 236 except Exception, e: 237 msg = "%s\nError setting param %s.%s to %s\n" % \ 238 (e, cls.__name__, name, value) 239 e.args = (msg, ) 240 raise 241 242 def _new_port(cls, name, port): 243 # each port should be uniquely assigned to one variable 244 assert(not hasattr(port, 'name')) 245 port.name = name 246 cls._ports[name] = port 247 if hasattr(port, 'default'): 248 cls._cls_get_port_ref(name).connect(port.default) 249 250 # same as _get_port_ref, effectively, but for classes 251 def _cls_get_port_ref(cls, attr): 252 # Return reference that can be assigned to another port 253 # via __setattr__. There is only ever one reference 254 # object per port, but we create them lazily here. 255 ref = cls._port_refs.get(attr) 256 if not ref: 257 ref = cls._ports[attr].makeRef(cls) 258 cls._port_refs[attr] = ref 259 return ref 260 |
|
232 # Set attribute (called on foo.attr = value when foo is an 233 # instance of class cls). 234 def __setattr__(cls, attr, value): 235 # normal processing for private attributes 236 if attr.startswith('_'): 237 type.__setattr__(cls, attr, value) 238 return 239 240 if cls.keywords.has_key(attr): 241 cls._set_keyword(attr, value, cls.keywords[attr]) 242 return 243 244 if cls._ports.has_key(attr): | 261 # Set attribute (called on foo.attr = value when foo is an 262 # instance of class cls). 263 def __setattr__(cls, attr, value): 264 # normal processing for private attributes 265 if attr.startswith('_'): 266 type.__setattr__(cls, attr, value) 267 return 268 269 if cls.keywords.has_key(attr): 270 cls._set_keyword(attr, value, cls.keywords[attr]) 271 return 272 273 if cls._ports.has_key(attr): |
245 self._ports[attr].connect(self, attr, value) | 274 cls._cls_get_port_ref(attr).connect(value) |
246 return 247 248 if isSimObjectOrSequence(value) and cls._instantiated: 249 raise RuntimeError, \ 250 "cannot set SimObject parameter '%s' after\n" \ 251 " class %s has been instantiated or subclassed" \ 252 % (attr, cls.__name__) 253 254 # check for param | 275 return 276 277 if isSimObjectOrSequence(value) and cls._instantiated: 278 raise RuntimeError, \ 279 "cannot set SimObject parameter '%s' after\n" \ 280 " class %s has been instantiated or subclassed" \ 281 % (attr, cls.__name__) 282 283 # check for param |
255 param = cls._params.get(attr, None) | 284 param = cls._params.get(attr) |
256 if param: | 285 if param: |
257 try: 258 cls._values[attr] = param.convert(value) 259 except Exception, e: 260 msg = "%s\nError setting param %s.%s to %s\n" % \ 261 (e, cls.__name__, attr, value) 262 e.args = (msg, ) 263 raise 264 elif isSimObjectOrSequence(value): 265 # if RHS is a SimObject, it's an implicit child assignment | 286 cls._set_param(attr, value, param) 287 return 288 289 if isSimObjectOrSequence(value): 290 # If RHS is a SimObject, it's an implicit child assignment. 291 # Classes don't have children, so we just put this object 292 # in _values; later, each instance will do a 'setattr(self, 293 # attr, _values[attr])' in SimObject.__init__ which will 294 # add this object as a child. |
266 cls._values[attr] = value | 295 cls._values[attr] = value |
267 else: 268 raise AttributeError, \ 269 "Class %s has no parameter \'%s\'" % (cls.__name__, attr) | 296 return |
270 | 297 |
298 # no valid assignment... raise exception 299 raise AttributeError, \ 300 "Class %s has no parameter \'%s\'" % (cls.__name__, attr) 301 |
|
271 def __getattr__(cls, attr): 272 if cls._values.has_key(attr): 273 return cls._values[attr] 274 275 raise AttributeError, \ 276 "object '%s' has no attribute '%s'" % (cls.__name__, attr) 277 278 def __str__(cls): --- 138 unchanged lines hidden (view full) --- 417 # clone SimObject-valued parameters 418 for key,val in ancestor._values.iteritems(): 419 if isSimObject(val): 420 setattr(self, key, val(_memo=memo_dict)) 421 elif isSimObjectSequence(val) and len(val): 422 setattr(self, key, [ v(_memo=memo_dict) for v in val ]) 423 # clone port references. no need to use a multidict here 424 # since we will be creating new references for all ports. | 302 def __getattr__(cls, attr): 303 if cls._values.has_key(attr): 304 return cls._values[attr] 305 306 raise AttributeError, \ 307 "object '%s' has no attribute '%s'" % (cls.__name__, attr) 308 309 def __str__(cls): --- 138 unchanged lines hidden (view full) --- 448 # clone SimObject-valued parameters 449 for key,val in ancestor._values.iteritems(): 450 if isSimObject(val): 451 setattr(self, key, val(_memo=memo_dict)) 452 elif isSimObjectSequence(val) and len(val): 453 setattr(self, key, [ v(_memo=memo_dict) for v in val ]) 454 # clone port references. no need to use a multidict here 455 # since we will be creating new references for all ports. |
425 self._port_map = {} 426 for key,val in ancestor._port_map.iteritems(): 427 self._port_map[key] = applyOrMap(val, 'clone', memo_dict) | 456 self._port_refs = {} 457 for key,val in ancestor._port_refs.iteritems(): 458 self._port_refs[key] = val.clone(self, memo_dict) |
428 # apply attribute assignments from keyword args, if any 429 for key,val in kwargs.iteritems(): 430 setattr(self, key, val) 431 432 # "Clone" the current instance by creating another instance of 433 # this instance's class, but that inherits its parameter values 434 # and port mappings from the current instance. If we're in a 435 # "deep copy" recursive clone, check the _memo dict to see if --- 10 unchanged lines hidden (view full) --- 446 # create a new dict and use that. 447 memo_dict = {} 448 kwargs['_memo'] = memo_dict 449 elif memo_dict.has_key(self): 450 # clone already done & memoized 451 return memo_dict[self] 452 return self.__class__(_ancestor = self, **kwargs) 453 | 459 # apply attribute assignments from keyword args, if any 460 for key,val in kwargs.iteritems(): 461 setattr(self, key, val) 462 463 # "Clone" the current instance by creating another instance of 464 # this instance's class, but that inherits its parameter values 465 # and port mappings from the current instance. If we're in a 466 # "deep copy" recursive clone, check the _memo dict to see if --- 10 unchanged lines hidden (view full) --- 477 # create a new dict and use that. 478 memo_dict = {} 479 kwargs['_memo'] = memo_dict 480 elif memo_dict.has_key(self): 481 # clone already done & memoized 482 return memo_dict[self] 483 return self.__class__(_ancestor = self, **kwargs) 484 |
485 def _get_port_ref(self, attr): 486 # Return reference that can be assigned to another port 487 # via __setattr__. There is only ever one reference 488 # object per port, but we create them lazily here. 489 ref = self._port_refs.get(attr) 490 if not ref: 491 ref = self._ports[attr].makeRef(self) 492 self._port_refs[attr] = ref 493 return ref 494 |
|
454 def __getattr__(self, attr): 455 if self._ports.has_key(attr): | 495 def __getattr__(self, attr): 496 if self._ports.has_key(attr): |
456 # return reference that can be assigned to another port 457 # via __setattr__ 458 return self._ports[attr].makeRef(self, attr) | 497 return self._get_port_ref(attr) |
459 460 if self._values.has_key(attr): 461 return self._values[attr] 462 463 raise AttributeError, "object '%s' has no attribute '%s'" \ 464 % (self.__class__.__name__, attr) 465 466 # Set attribute (called on foo.attr = value when foo is an 467 # instance of class cls). 468 def __setattr__(self, attr, value): 469 # normal processing for private attributes 470 if attr.startswith('_'): 471 object.__setattr__(self, attr, value) 472 return 473 474 if self._ports.has_key(attr): 475 # set up port connection | 498 499 if self._values.has_key(attr): 500 return self._values[attr] 501 502 raise AttributeError, "object '%s' has no attribute '%s'" \ 503 % (self.__class__.__name__, attr) 504 505 # Set attribute (called on foo.attr = value when foo is an 506 # instance of class cls). 507 def __setattr__(self, attr, value): 508 # normal processing for private attributes 509 if attr.startswith('_'): 510 object.__setattr__(self, attr, value) 511 return 512 513 if self._ports.has_key(attr): 514 # set up port connection |
476 self._ports[attr].connect(self, attr, value) | 515 self._get_port_ref(attr).connect(value) |
477 return 478 479 if isSimObjectOrSequence(value) and self._instantiated: 480 raise RuntimeError, \ 481 "cannot set SimObject parameter '%s' after\n" \ 482 " instance been cloned %s" % (attr, `self`) 483 484 # must be SimObject param | 516 return 517 518 if isSimObjectOrSequence(value) and self._instantiated: 519 raise RuntimeError, \ 520 "cannot set SimObject parameter '%s' after\n" \ 521 " instance been cloned %s" % (attr, `self`) 522 523 # must be SimObject param |
485 param = self._params.get(attr, None) | 524 param = self._params.get(attr) |
486 if param: 487 try: 488 value = param.convert(value) 489 except Exception, e: 490 msg = "%s\nError setting param %s.%s to %s\n" % \ 491 (e, self.__class__.__name__, attr, value) 492 e.args = (msg, ) 493 raise | 525 if param: 526 try: 527 value = param.convert(value) 528 except Exception, e: 529 msg = "%s\nError setting param %s.%s to %s\n" % \ 530 (e, self.__class__.__name__, attr, value) 531 e.args = (msg, ) 532 raise |
494 elif isSimObjectOrSequence(value): 495 pass 496 else: 497 raise AttributeError, "Class %s has no parameter %s" \ 498 % (self.__class__.__name__, attr) | 533 self._set_child(attr, value) 534 return |
499 | 535 |
500 # clear out old child with this name, if any 501 self.clear_child(attr) | 536 if isSimObjectOrSequence(value): 537 self._set_child(attr, value) 538 return |
502 | 539 |
503 if isSimObject(value): 504 value.set_path(self, attr) 505 elif isSimObjectSequence(value): 506 value = SimObjVector(value) 507 [v.set_path(self, "%s%d" % (attr, i)) for i,v in enumerate(value)] | 540 # no valid assignment... raise exception 541 raise AttributeError, "Class %s has no parameter %s" \ 542 % (self.__class__.__name__, attr) |
508 | 543 |
509 self._values[attr] = value | |
510 511 # this hack allows tacking a '[0]' onto parameters that may or may 512 # not be vectors, and always getting the first element (e.g. cpus) 513 def __getitem__(self, key): 514 if key == 0: 515 return self 516 raise TypeError, "Non-zero index '%s' to SimObject" % key 517 --- 5 unchanged lines hidden (view full) --- 523 if isinstance(child, SimObjVector): 524 for i in xrange(len(child)): 525 del self._children["s%d" % (name, i)] 526 del self._children[name] 527 528 def add_child(self, name, value): 529 self._children[name] = value 530 | 544 545 # this hack allows tacking a '[0]' onto parameters that may or may 546 # not be vectors, and always getting the first element (e.g. cpus) 547 def __getitem__(self, key): 548 if key == 0: 549 return self 550 raise TypeError, "Non-zero index '%s' to SimObject" % key 551 --- 5 unchanged lines hidden (view full) --- 557 if isinstance(child, SimObjVector): 558 for i in xrange(len(child)): 559 del self._children["s%d" % (name, i)] 560 del self._children[name] 561 562 def add_child(self, name, value): 563 self._children[name] = value 564 |
531 def set_path(self, parent, name): | 565 def _maybe_set_parent(self, parent, name): |
532 if not self._parent: 533 self._parent = parent 534 self._name = name 535 parent.add_child(name, self) 536 | 566 if not self._parent: 567 self._parent = parent 568 self._name = name 569 parent.add_child(name, self) 570 |
571 def _set_child(self, attr, value): 572 # if RHS is a SimObject, it's an implicit child assignment 573 # clear out old child with this name, if any 574 self.clear_child(attr) 575 576 if isSimObject(value): 577 value._maybe_set_parent(self, attr) 578 elif isSimObjectSequence(value): 579 value = SimObjVector(value) 580 [v._maybe_set_parent(self, "%s%d" % (attr, i)) 581 for i,v in enumerate(value)] 582 583 self._values[attr] = value 584 |
|
537 def path(self): 538 if not self._parent: 539 return 'root' 540 ppath = self._parent.path() 541 if ppath == 'root': 542 return self._name 543 return ppath + "." + self._name 544 --- 23 unchanged lines hidden (view full) --- 568 raise AttributeError, \ 569 'parent.any matched more than one: %s' % obj.path 570 found_obj = match_obj 571 return found_obj, found_obj != None 572 573 def unproxy(self, base): 574 return self 575 | 585 def path(self): 586 if not self._parent: 587 return 'root' 588 ppath = self._parent.path() 589 if ppath == 'root': 590 return self._name 591 return ppath + "." + self._name 592 --- 23 unchanged lines hidden (view full) --- 616 raise AttributeError, \ 617 'parent.any matched more than one: %s' % obj.path 618 found_obj = match_obj 619 return found_obj, found_obj != None 620 621 def unproxy(self, base): 622 return self 623 |
624 def unproxy_all(self): 625 for param in self._params.iterkeys(): 626 value = self._values.get(param) 627 if value != None and proxy.isproxy(value): 628 try: 629 value = value.unproxy(self) 630 except: 631 print "Error in unproxying param '%s' of %s" % \ 632 (param, self.path()) 633 raise 634 setattr(self, param, value) 635 636 for port_name in self._ports.iterkeys(): 637 port = self._port_refs.get(port_name) 638 if port != None: 639 port.unproxy(self) 640 641 for child in self._children.itervalues(): 642 child.unproxy_all() 643 |
|
576 def print_ini(self): 577 print '[' + self.path() + ']' # .ini section header 578 579 instanceDict[self.path()] = self 580 581 if hasattr(self, 'type') and not isinstance(self, ParamContext): 582 print 'type=%s' % self.type 583 584 child_names = self._children.keys() 585 child_names.sort() 586 np_child_names = [c for c in child_names \ 587 if not isinstance(self._children[c], ParamContext)] 588 if len(np_child_names): 589 print 'children=%s' % ' '.join(np_child_names) 590 591 param_names = self._params.keys() 592 param_names.sort() 593 for param in param_names: | 644 def print_ini(self): 645 print '[' + self.path() + ']' # .ini section header 646 647 instanceDict[self.path()] = self 648 649 if hasattr(self, 'type') and not isinstance(self, ParamContext): 650 print 'type=%s' % self.type 651 652 child_names = self._children.keys() 653 child_names.sort() 654 np_child_names = [c for c in child_names \ 655 if not isinstance(self._children[c], ParamContext)] 656 if len(np_child_names): 657 print 'children=%s' % ' '.join(np_child_names) 658 659 param_names = self._params.keys() 660 param_names.sort() 661 for param in param_names: |
594 value = self._values.get(param, None) | 662 value = self._values.get(param) |
595 if value != None: | 663 if value != None: |
596 if proxy.isproxy(value): 597 try: 598 value = value.unproxy(self) 599 except: 600 print >> sys.stderr, \ 601 "Error in unproxying param '%s' of %s" % \ 602 (param, self.path()) 603 raise 604 setattr(self, param, value) | |
605 print '%s=%s' % (param, self._values[param].ini_str()) 606 607 port_names = self._ports.keys() 608 port_names.sort() 609 for port_name in port_names: | 664 print '%s=%s' % (param, self._values[param].ini_str()) 665 666 port_names = self._ports.keys() 667 port_names.sort() 668 for port_name in port_names: |
610 port = self._port_map.get(port_name, None) 611 if port == None: 612 default = getattr(self._ports[port_name], 'default', None) 613 if default == None: 614 # port is unbound... that's OK, go to next port 615 continue 616 else: 617 print port_name, default 618 port = m5.makeList(port) # make list even if it's a scalar port 619 print '%s=%s' % (port_name, ' '.join([str(p) for p in port])) | 669 port = self._port_refs.get(port_name, None) 670 if port != None: 671 print '%s=%s' % (port_name, port.ini_str()) |
620 621 print # blank line between objects 622 623 for child in child_names: 624 self._children[child].print_ini() 625 626 # Call C++ to create C++ object corresponding to this object and 627 # (recursively) all its children --- 10 unchanged lines hidden (view full) --- 638 self._ccObject = -1 # flag to catch cycles in recursion 639 self._ccObject = cc_main.createSimObject(self.path()) 640 elif self._ccObject == -1: 641 raise RuntimeError, "%s: recursive call to getCCObject()" \ 642 % self.path() 643 return self._ccObject 644 645 # Create C++ port connections corresponding to the connections in | 672 673 print # blank line between objects 674 675 for child in child_names: 676 self._children[child].print_ini() 677 678 # Call C++ to create C++ object corresponding to this object and 679 # (recursively) all its children --- 10 unchanged lines hidden (view full) --- 690 self._ccObject = -1 # flag to catch cycles in recursion 691 self._ccObject = cc_main.createSimObject(self.path()) 692 elif self._ccObject == -1: 693 raise RuntimeError, "%s: recursive call to getCCObject()" \ 694 % self.path() 695 return self._ccObject 696 697 # Create C++ port connections corresponding to the connections in |
646 # _port_map (& recursively for all children) | 698 # _port_refs (& recursively for all children) |
647 def connectPorts(self): | 699 def connectPorts(self): |
648 for portRef in self._port_map.itervalues(): 649 applyOrMap(portRef, 'ccConnect') | 700 for portRef in self._port_refs.itervalues(): 701 portRef.ccConnect() |
650 for child in self._children.itervalues(): 651 child.connectPorts() 652 653 def startDrain(self, drain_event, recursive): 654 count = 0 655 # ParamContexts don't serialize 656 if isinstance(self, SimObject) and not isinstance(self, ParamContext): 657 count += self._ccObject.drain(drain_event) --- 82 unchanged lines hidden --- | 702 for child in self._children.itervalues(): 703 child.connectPorts() 704 705 def startDrain(self, drain_event, recursive): 706 count = 0 707 # ParamContexts don't serialize 708 if isinstance(self, SimObject) and not isinstance(self, ParamContext): 709 count += self._ccObject.drain(drain_event) --- 82 unchanged lines hidden --- |