d1aec44b384eefad29e5a4946f18e9574a14cd14
1 # Copyright (c) 2004-2006 The Regents of The University of Michigan
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.
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.
27 # Authors: Steve Reinhardt
35 from multidict
import multidict
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.
41 def isSimObject(value
):
42 return isinstance(value
, SimObject
)
44 def isSimObjectClass(value
):
45 return issubclass(value
, SimObject
)
47 def isSimObjectSequence(value
):
48 if not isinstance(value
, (list, tuple)) or len(value
) == 0:
52 if not isNullPointer(val
) and not isSimObject(val
):
57 def isSimObjectOrSequence(value
):
58 return isSimObject(value
) or isSimObjectSequence(value
)
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)...
64 # There are a few things we need that aren't in params.__all__ since
65 # normal users don't need them
66 from params
import ParamDesc
, VectorParamDesc
, isNullPointer
, SimObjVector
74 #####################################################################
76 # M5 Python Configuration Utility
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.
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:
94 # cache = BaseCache(size='64KB')
95 # cache.hit_latency = 3
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.
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.
112 #####################################################################
114 # list of all SimObject classes
117 # dict to look up SimObjects based on path
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).
124 class 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
}
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
145 # Copy "private" attributes, functions, and classes to the
146 # official dict. Everything else goes in _init_dict to be
147 # filtered in __init__.
150 for key
,val
in dict.items():
151 if key
.startswith('_') or isinstance(val
, (types
.FunctionType
,
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
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)
171 # initialize required attributes
173 # class-only attributes
174 cls
._params
= multidict() # param descriptions
175 cls
._ports
= multidict() # port descriptions
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
182 # We don't support multiple inheritance. If you want to, you
183 # must fix multidict to deal with it properly.
185 raise TypeError, "SimObjects do not support multiple inheritance"
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
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
207 namespace
= cls
._value
_dict
.get('cxx_namespace', None)
209 _cxx_class
= cls
._value
_dict
['cxx_class']
210 if 'cxx_type' not in cls
._value
_dict
:
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
220 namespaces
= namespace
.split('::')
222 for namespace
in namespaces
:
223 decl
= 'namespace %s { %s }' % (namespace
, decl
)
224 cls
._value
_dict
['cxx_predecls'] = [decl
]
226 if 'swig_predecls' not in cls
._value
_dict
:
227 # A forward class declaration is sufficient since we are
228 # just declaring a pointer.
229 cls
._value
_dict
['swig_predecls'] = \
230 cls
._value
_dict
['cxx_predecls']
232 if 'swig_objdecls' not in cls
._value
_dict
:
233 cls
._value
_dict
['swig_objdecls'] = []
235 # Now process the _value_dict items. They could be defining
236 # new (or overriding existing) parameters or ports, setting
237 # class keywords (e.g., 'abstract'), or setting parameter
238 # values or port bindings. The first 3 can only be set when
239 # the class is defined, so we handle them here. The others
240 # can be set later too, so just emulate that by calling
242 for key
,val
in cls
._value
_dict
.items():
244 if isinstance(val
, ParamDesc
):
245 cls
._new
_param
(key
, val
)
248 elif isinstance(val
, Port
):
249 cls
._new
_port
(key
, val
)
251 # init-time-only keywords
252 elif cls
.init_keywords
.has_key(key
):
253 cls
._set
_keyword
(key
, val
, cls
.init_keywords
[key
])
255 # default: use normal path (ends up in __setattr__)
257 setattr(cls
, key
, val
)
259 def _set_keyword(cls
, keyword
, val
, kwtype
):
260 if not isinstance(val
, kwtype
):
261 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
262 (keyword
, type(val
), kwtype
)
263 if isinstance(val
, types
.FunctionType
):
264 val
= classmethod(val
)
265 type.__setattr
__(cls
, keyword
, val
)
267 def _new_param(cls
, name
, pdesc
):
268 # each param desc should be uniquely assigned to one variable
269 assert(not hasattr(pdesc
, 'name'))
271 cls
._params
[name
] = pdesc
272 if hasattr(pdesc
, 'default'):
273 cls
._set
_param
(name
, pdesc
.default
, pdesc
)
275 def _set_param(cls
, name
, value
, param
):
276 assert(param
.name
== name
)
278 cls
._values
[name
] = param
.convert(value
)
280 msg
= "%s\nError setting param %s.%s to %s\n" % \
281 (e
, cls
.__name
__, name
, value
)
285 def _new_port(cls
, name
, port
):
286 # each port should be uniquely assigned to one variable
287 assert(not hasattr(port
, 'name'))
289 cls
._ports
[name
] = port
290 if hasattr(port
, 'default'):
291 cls
._cls
_get
_port
_ref
(name
).connect(port
.default
)
293 # same as _get_port_ref, effectively, but for classes
294 def _cls_get_port_ref(cls
, attr
):
295 # Return reference that can be assigned to another port
296 # via __setattr__. There is only ever one reference
297 # object per port, but we create them lazily here.
298 ref
= cls
._port
_refs
.get(attr
)
300 ref
= cls
._ports
[attr
].makeRef(cls
)
301 cls
._port
_refs
[attr
] = ref
304 # Set attribute (called on foo.attr = value when foo is an
305 # instance of class cls).
306 def __setattr__(cls
, attr
, value
):
307 # normal processing for private attributes
308 if attr
.startswith('_'):
309 type.__setattr
__(cls
, attr
, value
)
312 if cls
.keywords
.has_key(attr
):
313 cls
._set
_keyword
(attr
, value
, cls
.keywords
[attr
])
316 if cls
._ports
.has_key(attr
):
317 cls
._cls
_get
_port
_ref
(attr
).connect(value
)
320 if isSimObjectOrSequence(value
) and cls
._instantiated
:
321 raise RuntimeError, \
322 "cannot set SimObject parameter '%s' after\n" \
323 " class %s has been instantiated or subclassed" \
324 % (attr
, cls
.__name
__)
327 param
= cls
._params
.get(attr
)
329 cls
._set
_param
(attr
, value
, param
)
332 if isSimObjectOrSequence(value
):
333 # If RHS is a SimObject, it's an implicit child assignment.
334 # Classes don't have children, so we just put this object
335 # in _values; later, each instance will do a 'setattr(self,
336 # attr, _values[attr])' in SimObject.__init__ which will
337 # add this object as a child.
338 cls
._values
[attr
] = value
341 # no valid assignment... raise exception
342 raise AttributeError, \
343 "Class %s has no parameter \'%s\'" % (cls
.__name
__, attr
)
345 def __getattr__(cls
, attr
):
346 if cls
._values
.has_key(attr
):
347 return cls
._values
[attr
]
349 raise AttributeError, \
350 "object '%s' has no attribute '%s'" % (cls
.__name
__, attr
)
356 if str(cls
) == 'SimObject':
359 return cls
.__bases
__[0].type
362 code
= "#ifndef __PARAMS__%s\n" % cls
363 code
+= "#define __PARAMS__%s\n\n" % cls
365 # The 'dict' attribute restricts us to the params declared in
366 # the object itself, not including inherited params (which
367 # will also be inherited from the base class's param struct
369 params
= cls
._params
.local
.values()
371 ptypes
= [p
.ptype
for p
in params
]
373 print cls
, p
, p
.ptype_str
377 # get a list of lists of predeclaration lines
379 predecls
.extend(cls
.cxx_predecls
)
381 predecls
.extend(p
.cxx_predecls())
382 # remove redundant lines
385 if pd
not in predecls2
:
388 code
+= "\n".join(predecls2
)
391 base
= cls
.get_base()
393 code
+= '#include "params/%s.hh"\n\n' % base
396 if issubclass(ptype
, Enum
):
397 code
+= '#include "enums/%s.hh"\n' % ptype
.__name
__
400 # now generate the actual param struct
401 code
+= "struct %sParams" % cls
403 code
+= " : public %sParams" % base
406 code
+= " virtual ~%sParams() {}\n" % cls
407 if not hasattr(cls
, 'abstract') or not cls
.abstract
:
408 if 'type' in cls
.__dict
__:
409 code
+= " %s create();\n" % cls
.cxx_type
410 decls
= [p
.cxx_decl() for p
in params
]
412 code
+= "".join([" %s\n" % d
for d
in decls
])
415 # close #ifndef __PARAMS__* guard
419 def cxx_type_decl(cls
):
420 base
= cls
.get_base()
424 code
+= '#include "%s_type.h"\n' % base
426 # now generate dummy code for inheritance
427 code
+= "struct %s" % cls
.cxx_class
429 code
+= " : public %s" % base
.cxx_class
435 base
= cls
.get_base()
437 code
= '%%module %s\n' % cls
440 code
+= '#include "params/%s.hh"\n' % cls
443 # The 'dict' attribute restricts us to the params declared in
444 # the object itself, not including inherited params (which
445 # will also be inherited from the base class's param struct
447 params
= cls
._params
.local
.values()
448 ptypes
= [p
.ptype
for p
in params
]
450 # get a list of lists of predeclaration lines
452 predecls
.extend([ p
.swig_predecls() for p
in params
])
454 predecls
= reduce(lambda x
,y
:x
+y
, predecls
, [])
455 # remove redundant lines
458 if pd
not in predecls2
:
461 code
+= "\n".join(predecls2
)
465 code
+= '%%import "params/%s.i"\n\n' % base
468 if issubclass(ptype
, Enum
):
469 code
+= '%%import "enums/%s.hh"\n' % ptype
.__name
__
472 code
+= '%%import "params/%s_type.hh"\n\n' % cls
473 code
+= '%%include "params/%s.hh"\n\n' % cls
477 # The SimObject class is the root of the special hierarchy. Most of
478 # the code in this class deals with the configuration hierarchy itself
479 # (parent/child node relationships).
480 class SimObject(object):
481 # Specify metaclass. Any class inheriting from SimObject will
482 # get this metaclass.
483 __metaclass__
= MetaSimObject
487 name
= Param
.String("Object name")
488 swig_objdecls
= [ '%include "python/swig/sim_object.i"' ]
490 # Initialize new instance. For objects with SimObject-valued
491 # children, we need to recursively clone the classes represented
492 # by those param values as well in a consistent "deep copy"-style
493 # fashion. That is, we want to make sure that each instance is
494 # cloned only once, and that if there are multiple references to
495 # the same original object, we end up with the corresponding
496 # cloned references all pointing to the same cloned instance.
497 def __init__(self
, **kwargs
):
498 ancestor
= kwargs
.get('_ancestor')
499 memo_dict
= kwargs
.get('_memo')
500 if memo_dict
is None:
501 # prepare to memoize any recursively instantiated objects
504 # memoize me now to avoid problems with recursive calls
505 memo_dict
[ancestor
] = self
508 ancestor
= self
.__class
__
509 ancestor
._instantiated
= True
511 # initialize required attributes
514 self
._ccObject
= None # pointer to C++ object
515 self
._ccParams
= None
516 self
._instantiated
= False # really "cloned"
518 # Inherit parameter values from class using multidict so
519 # individual value settings can be overridden.
520 self
._values
= multidict(ancestor
._values
)
521 # clone SimObject-valued parameters
522 for key
,val
in ancestor
._values
.iteritems():
524 setattr(self
, key
, val(_memo
=memo_dict
))
525 elif isSimObjectSequence(val
) and len(val
):
526 setattr(self
, key
, [ v(_memo
=memo_dict
) for v
in val
])
527 # clone port references. no need to use a multidict here
528 # since we will be creating new references for all ports.
530 for key
,val
in ancestor
._port
_refs
.iteritems():
531 self
._port
_refs
[key
] = val
.clone(self
, memo_dict
)
532 # apply attribute assignments from keyword args, if any
533 for key
,val
in kwargs
.iteritems():
534 setattr(self
, key
, val
)
536 # "Clone" the current instance by creating another instance of
537 # this instance's class, but that inherits its parameter values
538 # and port mappings from the current instance. If we're in a
539 # "deep copy" recursive clone, check the _memo dict to see if
540 # we've already cloned this instance.
541 def __call__(self
, **kwargs
):
542 memo_dict
= kwargs
.get('_memo')
543 if memo_dict
is None:
544 # no memo_dict: must be top-level clone operation.
545 # this is only allowed at the root of a hierarchy
547 raise RuntimeError, "attempt to clone object %s " \
548 "not at the root of a tree (parent = %s)" \
549 % (self
, self
._parent
)
550 # create a new dict and use that.
552 kwargs
['_memo'] = memo_dict
553 elif memo_dict
.has_key(self
):
554 # clone already done & memoized
555 return memo_dict
[self
]
556 return self
.__class
__(_ancestor
= self
, **kwargs
)
558 def _get_port_ref(self
, attr
):
559 # Return reference that can be assigned to another port
560 # via __setattr__. There is only ever one reference
561 # object per port, but we create them lazily here.
562 ref
= self
._port
_refs
.get(attr
)
564 ref
= self
._ports
[attr
].makeRef(self
)
565 self
._port
_refs
[attr
] = ref
568 def __getattr__(self
, attr
):
569 if self
._ports
.has_key(attr
):
570 return self
._get
_port
_ref
(attr
)
572 if self
._values
.has_key(attr
):
573 return self
._values
[attr
]
575 raise AttributeError, "object '%s' has no attribute '%s'" \
576 % (self
.__class
__.__name
__, attr
)
578 # Set attribute (called on foo.attr = value when foo is an
579 # instance of class cls).
580 def __setattr__(self
, attr
, value
):
581 # normal processing for private attributes
582 if attr
.startswith('_'):
583 object.__setattr
__(self
, attr
, value
)
586 if self
._ports
.has_key(attr
):
587 # set up port connection
588 self
._get
_port
_ref
(attr
).connect(value
)
591 if isSimObjectOrSequence(value
) and self
._instantiated
:
592 raise RuntimeError, \
593 "cannot set SimObject parameter '%s' after\n" \
594 " instance been cloned %s" % (attr
, `self`
)
596 # must be SimObject param
597 param
= self
._params
.get(attr
)
600 value
= param
.convert(value
)
602 msg
= "%s\nError setting param %s.%s to %s\n" % \
603 (e
, self
.__class
__.__name
__, attr
, value
)
606 self
._set
_child
(attr
, value
)
609 if isSimObjectOrSequence(value
):
610 self
._set
_child
(attr
, value
)
613 # no valid assignment... raise exception
614 raise AttributeError, "Class %s has no parameter %s" \
615 % (self
.__class
__.__name
__, attr
)
618 # this hack allows tacking a '[0]' onto parameters that may or may
619 # not be vectors, and always getting the first element (e.g. cpus)
620 def __getitem__(self
, key
):
623 raise TypeError, "Non-zero index '%s' to SimObject" % key
625 # clear out children with given name, even if it's a vector
626 def clear_child(self
, name
):
627 if not self
._children
.has_key(name
):
629 child
= self
._children
[name
]
630 if isinstance(child
, SimObjVector
):
631 for i
in xrange(len(child
)):
632 del self
._children
["s%d" % (name
, i
)]
633 del self
._children
[name
]
635 def add_child(self
, name
, value
):
636 self
._children
[name
] = value
638 def _maybe_set_parent(self
, parent
, name
):
640 self
._parent
= parent
642 parent
.add_child(name
, self
)
644 def _set_child(self
, attr
, value
):
645 # if RHS is a SimObject, it's an implicit child assignment
646 # clear out old child with this name, if any
647 self
.clear_child(attr
)
649 if isSimObject(value
):
650 value
._maybe
_set
_parent
(self
, attr
)
651 elif isSimObjectSequence(value
):
652 value
= SimObjVector(value
)
654 value
[0]._maybe
_set
_parent
(self
, attr
)
656 for i
,v
in enumerate(value
):
657 v
._maybe
_set
_parent
(self
, "%s%d" % (attr
, i
))
659 self
._values
[attr
] = value
664 ppath
= self
._parent
.path()
667 return ppath
+ "." + self
._name
675 def find_any(self
, ptype
):
676 if isinstance(self
, ptype
):
680 for child
in self
._children
.itervalues():
681 if isinstance(child
, ptype
):
682 if found_obj
!= None and child
!= found_obj
:
683 raise AttributeError, \
684 'parent.any matched more than one: %s %s' % \
685 (found_obj
.path
, child
.path
)
688 for pname
,pdesc
in self
._params
.iteritems():
689 if issubclass(pdesc
.ptype
, ptype
):
690 match_obj
= self
._values
[pname
]
691 if found_obj
!= None and found_obj
!= match_obj
:
692 raise AttributeError, \
693 'parent.any matched more than one: %s' % obj
.path
694 found_obj
= match_obj
695 return found_obj
, found_obj
!= None
697 def unproxy(self
, base
):
700 def unproxy_all(self
):
701 for param
in self
._params
.iterkeys():
702 value
= self
._values
.get(param
)
703 if value
!= None and proxy
.isproxy(value
):
705 value
= value
.unproxy(self
)
707 print "Error in unproxying param '%s' of %s" % \
710 setattr(self
, param
, value
)
712 # Unproxy ports in sorted order so that 'append' operations on
713 # vector ports are done in a deterministic fashion.
714 port_names
= self
._ports
.keys()
716 for port_name
in port_names
:
717 port
= self
._port
_refs
.get(port_name
)
721 # Unproxy children in sorted order for determinism also.
722 child_names
= self
._children
.keys()
724 for child
in child_names
:
725 self
._children
[child
].unproxy_all()
727 def print_ini(self
, ini_file
):
728 print >>ini_file
, '[' + self
.path() + ']' # .ini section header
730 instanceDict
[self
.path()] = self
732 if hasattr(self
, 'type'):
733 print >>ini_file
, 'type=%s' % self
.type
735 child_names
= self
._children
.keys()
738 print >>ini_file
, 'children=%s' % ' '.join(child_names
)
740 param_names
= self
._params
.keys()
742 for param
in param_names
:
743 value
= self
._values
.get(param
)
745 print >>ini_file
, '%s=%s' % (param
,
746 self
._values
[param
].ini_str())
748 port_names
= self
._ports
.keys()
750 for port_name
in port_names
:
751 port
= self
._port
_refs
.get(port_name
, None)
753 print >>ini_file
, '%s=%s' % (port_name
, port
.ini_str())
755 print >>ini_file
# blank line between objects
757 for child
in child_names
:
758 self
._children
[child
].print_ini(ini_file
)
760 def getCCParams(self
):
762 return self
._ccParams
764 cc_params_struct
= getattr(m5
.objects
.params
, '%sParams' % self
.type)
765 cc_params
= cc_params_struct()
766 cc_params
.object = self
767 cc_params
.name
= str(self
)
769 param_names
= self
._params
.keys()
771 for param
in param_names
:
772 value
= self
._values
.get(param
)
776 value
= value
.getValue()
777 if isinstance(self
._params
[param
], VectorParamDesc
):
778 assert isinstance(value
, list)
779 vec
= getattr(cc_params
, param
)
784 setattr(cc_params
, param
, value
)
786 port_names
= self
._ports
.keys()
788 for port_name
in port_names
:
789 port
= self
._port
_refs
.get(port_name
, None)
791 setattr(cc_params
, port_name
, port
)
792 self
._ccParams
= cc_params
793 return self
._ccParams
795 # Get C++ object corresponding to this object, calling C++ if
796 # necessary to construct it. Does *not* recursively create
798 def getCCObject(self
):
799 if not self
._ccObject
:
800 # Cycles in the configuration heirarchy are not supported. This
801 # will catch the resulting recursion and stop.
803 params
= self
.getCCParams()
804 self
._ccObject
= params
.create()
805 elif self
._ccObject
== -1:
806 raise RuntimeError, "%s: Cycle found in configuration heirarchy." \
808 return self
._ccObject
810 # Call C++ to create C++ object corresponding to this object and
811 # (recursively) all its children
812 def createCCObject(self
):
814 self
.getCCObject() # force creation
815 for child
in self
._children
.itervalues():
816 child
.createCCObject()
819 return self
.getCCObject()
821 # Create C++ port connections corresponding to the connections in
822 # _port_refs (& recursively for all children)
823 def connectPorts(self
):
824 for portRef
in self
._port
_refs
.itervalues():
826 for child
in self
._children
.itervalues():
829 def startDrain(self
, drain_event
, recursive
):
831 if isinstance(self
, SimObject
):
832 count
+= self
._ccObject
.drain(drain_event
)
834 for child
in self
._children
.itervalues():
835 count
+= child
.startDrain(drain_event
, True)
839 if isinstance(self
, SimObject
):
840 self
._ccObject
.resume()
841 for child
in self
._children
.itervalues():
844 def getMemoryMode(self
):
845 if not isinstance(self
, m5
.objects
.System
):
848 return self
._ccObject
.getMemoryMode()
850 def changeTiming(self
, mode
):
851 if isinstance(self
, m5
.objects
.System
):
852 # i don't know if there's a better way to do this - calling
853 # setMemoryMode directly from self._ccObject results in calling
854 # SimObject::setMemoryMode, not the System::setMemoryMode
855 self
._ccObject
.setMemoryMode(mode
)
856 for child
in self
._children
.itervalues():
857 child
.changeTiming(mode
)
859 def takeOverFrom(self
, old_cpu
):
860 self
._ccObject
.takeOverFrom(old_cpu
._ccObject
)
862 # generate output file for 'dot' to display as a pretty graph.
863 # this code is currently broken.
864 def outputDot(self
, dot
):
865 label
= "{%s|" % self
.path
866 if isSimObject(self
.realtype
):
867 label
+= '%s|' % self
.type
870 # instantiate children in same order they were added for
871 # backward compatibility (else we can end up with cpu1
873 for c
in self
.children
:
874 dot
.add_edge(pydot
.Edge(self
.path
,c
.path
, style
="bold"))
877 for param
in self
.params
:
879 if param
.value
is None:
880 raise AttributeError, 'Parameter with no value'
883 string
= param
.string(value
)
885 msg
= 'exception in %s:%s\n%s' % (self
.name
, param
.name
, e
)
889 if isSimObject(param
.ptype
) and string
!= "Null":
890 simobjs
.append(string
)
892 label
+= '%s = %s\\n' % (param
.name
, string
)
895 label
+= "|<%s> %s" % (so
, so
)
896 dot
.add_edge(pydot
.Edge("%s:%s" % (self
.path
, so
), so
,
899 dot
.add_node(pydot
.Node(self
.path
,shape
="Mrecord",label
=label
))
901 # recursively dump out children
902 for c
in self
.children
:
905 # Function to provide to C++ so it can look up instances based on paths
906 def resolveSimObject(name
):
907 obj
= instanceDict
[name
]
908 return obj
.getCCObject()
910 # __all__ defines the list of symbols that get exported when
911 # 'from config import *' is invoked. Try to keep this reasonably
912 # short to avoid polluting other namespaces.
913 __all__
= [ 'SimObject' ]