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