69f79ed615a63847897cd6d3665d0b532544e5ec
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
32 from types
import FunctionType
42 # Have to import params up top since Param is referenced on initial
43 # load (when SimObject class references Param to create a class
44 # variable, the 'name' param)...
45 from m5
.params
import *
46 # There are a few things we need that aren't in params.__all__ since
47 # normal users don't need them
48 from m5
.params
import ParamDesc
, VectorParamDesc
, isNullPointer
, SimObjVector
50 from m5
.proxy
import *
51 from m5
.proxy
import isproxy
53 #####################################################################
55 # M5 Python Configuration Utility
57 # The basic idea is to write simple Python programs that build Python
58 # objects corresponding to M5 SimObjects for the desired simulation
59 # configuration. For now, the Python emits a .ini file that can be
60 # parsed by M5. In the future, some tighter integration between M5
61 # and the Python interpreter may allow bypassing the .ini file.
63 # Each SimObject class in M5 is represented by a Python class with the
64 # same name. The Python inheritance tree mirrors the M5 C++ tree
65 # (e.g., SimpleCPU derives from BaseCPU in both cases, and all
66 # SimObjects inherit from a single SimObject base class). To specify
67 # an instance of an M5 SimObject in a configuration, the user simply
68 # instantiates the corresponding Python object. The parameters for
69 # that SimObject are given by assigning to attributes of the Python
70 # object, either using keyword assignment in the constructor or in
71 # separate assignment statements. For example:
73 # cache = BaseCache(size='64KB')
74 # cache.hit_latency = 3
77 # The magic lies in the mapping of the Python attributes for SimObject
78 # classes to the actual SimObject parameter specifications. This
79 # allows parameter validity checking in the Python code. Continuing
80 # the example above, the statements "cache.blurfl=3" or
81 # "cache.assoc='hello'" would both result in runtime errors in Python,
82 # since the BaseCache object has no 'blurfl' parameter and the 'assoc'
83 # parameter requires an integer, respectively. This magic is done
84 # primarily by overriding the special __setattr__ method that controls
85 # assignment to object attributes.
87 # Once a set of Python objects have been instantiated in a hierarchy,
88 # calling 'instantiate(obj)' (where obj is the root of the hierarchy)
89 # will generate a .ini file.
91 #####################################################################
93 # list of all SimObject classes
96 # dict to look up SimObjects based on path
99 # The metaclass for SimObject. This class controls how new classes
100 # that derive from SimObject are instantiated, and provides inherited
101 # class behavior (just like a class controls how instances of that
102 # class are instantiated, and provides inherited instance behavior).
103 class MetaSimObject(type):
104 # Attributes that can be set only at initialization time
105 init_keywords
= { 'abstract' : bool,
108 'cxx_predecls' : list,
109 'swig_objdecls' : list,
110 'swig_predecls' : list,
112 # Attributes that can be set any time
113 keywords
= { 'check' : FunctionType
}
115 # __new__ is called before __init__, and is where the statements
116 # in the body of the class definition get loaded into the class's
117 # __dict__. We intercept this to filter out parameter & port assignments
118 # and only allow "private" attributes to be passed to the base
119 # __new__ (starting with underscore).
120 def __new__(mcls
, name
, bases
, dict):
121 assert name
not in allClasses
, "SimObject %s already present" % name
123 # Copy "private" attributes, functions, and classes to the
124 # official dict. Everything else goes in _init_dict to be
125 # filtered in __init__.
128 for key
,val
in dict.items():
129 if key
.startswith('_') or isinstance(val
, (FunctionType
,
134 # must be a param/port setting
135 value_dict
[key
] = val
136 if 'abstract' not in value_dict
:
137 value_dict
['abstract'] = False
138 cls_dict
['_value_dict'] = value_dict
139 cls
= super(MetaSimObject
, mcls
).__new
__(mcls
, name
, bases
, cls_dict
)
140 if 'type' in value_dict
:
141 allClasses
[name
] = cls
144 # subclass initialization
145 def __init__(cls
, name
, bases
, dict):
146 # calls type.__init__()... I think that's a no-op, but leave
147 # it here just in case it's not.
148 super(MetaSimObject
, cls
).__init
__(name
, bases
, dict)
150 # initialize required attributes
152 # class-only attributes
153 cls
._params
= multidict() # param descriptions
154 cls
._ports
= multidict() # port descriptions
156 # class or instance attributes
157 cls
._values
= multidict() # param values
158 cls
._port
_refs
= multidict() # port ref objects
159 cls
._instantiated
= False # really instantiated, cloned, or subclassed
161 # We don't support multiple inheritance. If you want to, you
162 # must fix multidict to deal with it properly.
164 raise TypeError, "SimObjects do not support multiple inheritance"
168 # Set up general inheritance via multidicts. A subclass will
169 # inherit all its settings from the base class. The only time
170 # the following is not true is when we define the SimObject
171 # class itself (in which case the multidicts have no parent).
172 if isinstance(base
, MetaSimObject
):
174 cls
._params
.parent
= base
._params
175 cls
._ports
.parent
= base
._ports
176 cls
._values
.parent
= base
._values
177 cls
._port
_refs
.parent
= base
._port
_refs
178 # mark base as having been subclassed
179 base
._instantiated
= True
183 # default keyword values
184 if 'type' in cls
._value
_dict
:
185 if 'cxx_class' not in cls
._value
_dict
:
186 cls
._value
_dict
['cxx_class'] = cls
._value
_dict
['type']
188 cls
._value
_dict
['cxx_type'] = '%s *' % cls
._value
_dict
['cxx_class']
190 if 'cxx_predecls' not in cls
._value
_dict
:
191 # A forward class declaration is sufficient since we are
192 # just declaring a pointer.
193 class_path
= cls
._value
_dict
['cxx_class'].split('::')
195 decl
= 'class %s;' % class_path
[0]
196 for ns
in class_path
[1:]:
197 decl
= 'namespace %s { %s }' % (ns
, decl
)
198 cls
._value
_dict
['cxx_predecls'] = [decl
]
200 if 'swig_predecls' not in cls
._value
_dict
:
201 # A forward class declaration is sufficient since we are
202 # just declaring a pointer.
203 cls
._value
_dict
['swig_predecls'] = \
204 cls
._value
_dict
['cxx_predecls']
206 if 'swig_objdecls' not in cls
._value
_dict
:
207 cls
._value
_dict
['swig_objdecls'] = []
209 # Now process the _value_dict items. They could be defining
210 # new (or overriding existing) parameters or ports, setting
211 # class keywords (e.g., 'abstract'), or setting parameter
212 # values or port bindings. The first 3 can only be set when
213 # the class is defined, so we handle them here. The others
214 # can be set later too, so just emulate that by calling
216 for key
,val
in cls
._value
_dict
.items():
218 if isinstance(val
, ParamDesc
):
219 cls
._new
_param
(key
, val
)
222 elif isinstance(val
, Port
):
223 cls
._new
_port
(key
, val
)
225 # init-time-only keywords
226 elif cls
.init_keywords
.has_key(key
):
227 cls
._set
_keyword
(key
, val
, cls
.init_keywords
[key
])
229 # default: use normal path (ends up in __setattr__)
231 setattr(cls
, key
, val
)
233 def _set_keyword(cls
, keyword
, val
, kwtype
):
234 if not isinstance(val
, kwtype
):
235 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
236 (keyword
, type(val
), kwtype
)
237 if isinstance(val
, FunctionType
):
238 val
= classmethod(val
)
239 type.__setattr
__(cls
, keyword
, val
)
241 def _new_param(cls
, name
, pdesc
):
242 # each param desc should be uniquely assigned to one variable
243 assert(not hasattr(pdesc
, 'name'))
245 cls
._params
[name
] = pdesc
246 if hasattr(pdesc
, 'default'):
247 cls
._set
_param
(name
, pdesc
.default
, pdesc
)
249 def _set_param(cls
, name
, value
, param
):
250 assert(param
.name
== name
)
252 cls
._values
[name
] = param
.convert(value
)
254 msg
= "%s\nError setting param %s.%s to %s\n" % \
255 (e
, cls
.__name
__, name
, value
)
259 def _new_port(cls
, name
, port
):
260 # each port should be uniquely assigned to one variable
261 assert(not hasattr(port
, 'name'))
263 cls
._ports
[name
] = port
264 if hasattr(port
, 'default'):
265 cls
._cls
_get
_port
_ref
(name
).connect(port
.default
)
267 # same as _get_port_ref, effectively, but for classes
268 def _cls_get_port_ref(cls
, attr
):
269 # Return reference that can be assigned to another port
270 # via __setattr__. There is only ever one reference
271 # object per port, but we create them lazily here.
272 ref
= cls
._port
_refs
.get(attr
)
274 ref
= cls
._ports
[attr
].makeRef(cls
)
275 cls
._port
_refs
[attr
] = ref
278 # Set attribute (called on foo.attr = value when foo is an
279 # instance of class cls).
280 def __setattr__(cls
, attr
, value
):
281 # normal processing for private attributes
282 if attr
.startswith('_'):
283 type.__setattr
__(cls
, attr
, value
)
286 if cls
.keywords
.has_key(attr
):
287 cls
._set
_keyword
(attr
, value
, cls
.keywords
[attr
])
290 if cls
._ports
.has_key(attr
):
291 cls
._cls
_get
_port
_ref
(attr
).connect(value
)
294 if isSimObjectOrSequence(value
) and cls
._instantiated
:
295 raise RuntimeError, \
296 "cannot set SimObject parameter '%s' after\n" \
297 " class %s has been instantiated or subclassed" \
298 % (attr
, cls
.__name
__)
301 param
= cls
._params
.get(attr
)
303 cls
._set
_param
(attr
, value
, param
)
306 if isSimObjectOrSequence(value
):
307 # If RHS is a SimObject, it's an implicit child assignment.
308 # Classes don't have children, so we just put this object
309 # in _values; later, each instance will do a 'setattr(self,
310 # attr, _values[attr])' in SimObject.__init__ which will
311 # add this object as a child.
312 cls
._values
[attr
] = value
315 # no valid assignment... raise exception
316 raise AttributeError, \
317 "Class %s has no parameter \'%s\'" % (cls
.__name
__, attr
)
319 def __getattr__(cls
, attr
):
320 if cls
._values
.has_key(attr
):
321 return cls
._values
[attr
]
323 raise AttributeError, \
324 "object '%s' has no attribute '%s'" % (cls
.__name
__, attr
)
330 code
= "#ifndef __PARAMS__%s\n" % cls
331 code
+= "#define __PARAMS__%s\n\n" % cls
333 # The 'dict' attribute restricts us to the params declared in
334 # the object itself, not including inherited params (which
335 # will also be inherited from the base class's param struct
337 params
= cls
._params
.local
.values()
339 ptypes
= [p
.ptype
for p
in params
]
341 print cls
, p
, p
.ptype_str
345 # get a list of lists of predeclaration lines
347 predecls
.extend(cls
.cxx_predecls
)
349 predecls
.extend(p
.cxx_predecls())
350 # remove redundant lines
353 if pd
not in predecls2
:
356 code
+= "\n".join(predecls2
)
360 code
+= '#include "params/%s.hh"\n\n' % cls
._base
.type
363 if issubclass(ptype
, Enum
):
364 code
+= '#include "enums/%s.hh"\n' % ptype
.__name
__
367 code
+= cls
.cxx_struct(cls
._base
, params
)
369 # close #ifndef __PARAMS__* guard
373 def cxx_struct(cls
, base
, params
):
375 return '#include "sim/sim_object_params.hh"\n'
377 # now generate the actual param struct
378 code
= "struct %sParams" % cls
380 code
+= " : public %sParams" % base
.type
382 if not hasattr(cls
, 'abstract') or not cls
.abstract
:
383 if 'type' in cls
.__dict
__:
384 code
+= " %s create();\n" % cls
.cxx_type
385 decls
= [p
.cxx_decl() for p
in params
]
387 code
+= "".join([" %s\n" % d
for d
in decls
])
393 code
= '%%module %s\n' % cls
396 code
+= '#include "params/%s.hh"\n' % cls
399 # The 'dict' attribute restricts us to the params declared in
400 # the object itself, not including inherited params (which
401 # will also be inherited from the base class's param struct
403 params
= cls
._params
.local
.values()
404 ptypes
= [p
.ptype
for p
in params
]
406 # get a list of lists of predeclaration lines
408 predecls
.extend([ p
.swig_predecls() for p
in params
])
410 predecls
= reduce(lambda x
,y
:x
+y
, predecls
, [])
411 # remove redundant lines
414 if pd
not in predecls2
:
417 code
+= "\n".join(predecls2
)
421 code
+= '%%import "params/%s.i"\n\n' % cls
._base
.type
424 if issubclass(ptype
, Enum
):
425 code
+= '%%import "enums/%s.hh"\n' % ptype
.__name
__
428 code
+= '%%import "params/%s_type.hh"\n\n' % cls
429 code
+= '%%include "params/%s.hh"\n\n' % cls
433 # The SimObject class is the root of the special hierarchy. Most of
434 # the code in this class deals with the configuration hierarchy itself
435 # (parent/child node relationships).
436 class SimObject(object):
437 # Specify metaclass. Any class inheriting from SimObject will
438 # get this metaclass.
439 __metaclass__
= MetaSimObject
443 swig_objdecls
= [ '%include "python/swig/sim_object.i"' ]
445 # Initialize new instance. For objects with SimObject-valued
446 # children, we need to recursively clone the classes represented
447 # by those param values as well in a consistent "deep copy"-style
448 # fashion. That is, we want to make sure that each instance is
449 # cloned only once, and that if there are multiple references to
450 # the same original object, we end up with the corresponding
451 # cloned references all pointing to the same cloned instance.
452 def __init__(self
, **kwargs
):
453 ancestor
= kwargs
.get('_ancestor')
454 memo_dict
= kwargs
.get('_memo')
455 if memo_dict
is None:
456 # prepare to memoize any recursively instantiated objects
459 # memoize me now to avoid problems with recursive calls
460 memo_dict
[ancestor
] = self
463 ancestor
= self
.__class
__
464 ancestor
._instantiated
= True
466 # initialize required attributes
469 self
._ccObject
= None # pointer to C++ object
470 self
._ccParams
= None
471 self
._instantiated
= False # really "cloned"
473 # Inherit parameter values from class using multidict so
474 # individual value settings can be overridden.
475 self
._values
= multidict(ancestor
._values
)
476 # clone SimObject-valued parameters
477 for key
,val
in ancestor
._values
.iteritems():
479 setattr(self
, key
, val(_memo
=memo_dict
))
480 elif isSimObjectSequence(val
) and len(val
):
481 setattr(self
, key
, [ v(_memo
=memo_dict
) for v
in val
])
482 # clone port references. no need to use a multidict here
483 # since we will be creating new references for all ports.
485 for key
,val
in ancestor
._port
_refs
.iteritems():
486 self
._port
_refs
[key
] = val
.clone(self
, memo_dict
)
487 # apply attribute assignments from keyword args, if any
488 for key
,val
in kwargs
.iteritems():
489 setattr(self
, key
, val
)
491 # "Clone" the current instance by creating another instance of
492 # this instance's class, but that inherits its parameter values
493 # and port mappings from the current instance. If we're in a
494 # "deep copy" recursive clone, check the _memo dict to see if
495 # we've already cloned this instance.
496 def __call__(self
, **kwargs
):
497 memo_dict
= kwargs
.get('_memo')
498 if memo_dict
is None:
499 # no memo_dict: must be top-level clone operation.
500 # this is only allowed at the root of a hierarchy
502 raise RuntimeError, "attempt to clone object %s " \
503 "not at the root of a tree (parent = %s)" \
504 % (self
, self
._parent
)
505 # create a new dict and use that.
507 kwargs
['_memo'] = memo_dict
508 elif memo_dict
.has_key(self
):
509 # clone already done & memoized
510 return memo_dict
[self
]
511 return self
.__class
__(_ancestor
= self
, **kwargs
)
513 def _get_port_ref(self
, attr
):
514 # Return reference that can be assigned to another port
515 # via __setattr__. There is only ever one reference
516 # object per port, but we create them lazily here.
517 ref
= self
._port
_refs
.get(attr
)
519 ref
= self
._ports
[attr
].makeRef(self
)
520 self
._port
_refs
[attr
] = ref
523 def __getattr__(self
, attr
):
524 if self
._ports
.has_key(attr
):
525 return self
._get
_port
_ref
(attr
)
527 if self
._values
.has_key(attr
):
528 return self
._values
[attr
]
530 # If the attribute exists on the C++ object, transparently
531 # forward the reference there. This is typically used for
532 # SWIG-wrapped methods such as init(), regStats(),
533 # regFormulas(), resetStats(), and startup().
534 if self
._ccObject
and hasattr(self
._ccObject
, attr
):
535 return getattr(self
._ccObject
, attr
)
537 raise AttributeError, "object '%s' has no attribute '%s'" \
538 % (self
.__class
__.__name
__, attr
)
540 # Set attribute (called on foo.attr = value when foo is an
541 # instance of class cls).
542 def __setattr__(self
, attr
, value
):
543 # normal processing for private attributes
544 if attr
.startswith('_'):
545 object.__setattr
__(self
, attr
, value
)
548 if self
._ports
.has_key(attr
):
549 # set up port connection
550 self
._get
_port
_ref
(attr
).connect(value
)
553 if isSimObjectOrSequence(value
) and self
._instantiated
:
554 raise RuntimeError, \
555 "cannot set SimObject parameter '%s' after\n" \
556 " instance been cloned %s" % (attr
, `self`
)
558 # must be SimObject param
559 param
= self
._params
.get(attr
)
562 value
= param
.convert(value
)
564 msg
= "%s\nError setting param %s.%s to %s\n" % \
565 (e
, self
.__class
__.__name
__, attr
, value
)
568 self
._set
_child
(attr
, value
)
571 if isSimObjectOrSequence(value
):
572 self
._set
_child
(attr
, value
)
575 # no valid assignment... raise exception
576 raise AttributeError, "Class %s has no parameter %s" \
577 % (self
.__class
__.__name
__, attr
)
580 # this hack allows tacking a '[0]' onto parameters that may or may
581 # not be vectors, and always getting the first element (e.g. cpus)
582 def __getitem__(self
, key
):
585 raise TypeError, "Non-zero index '%s' to SimObject" % key
587 # clear out children with given name, even if it's a vector
588 def clear_child(self
, name
):
589 if not self
._children
.has_key(name
):
591 child
= self
._children
[name
]
592 if isinstance(child
, SimObjVector
):
593 for i
in xrange(len(child
)):
594 del self
._children
["s%d" % (name
, i
)]
595 del self
._children
[name
]
597 def add_child(self
, name
, value
):
598 self
._children
[name
] = value
600 def _maybe_set_parent(self
, parent
, name
):
602 self
._parent
= parent
604 parent
.add_child(name
, self
)
606 def _set_child(self
, attr
, value
):
607 # if RHS is a SimObject, it's an implicit child assignment
608 # clear out old child with this name, if any
609 self
.clear_child(attr
)
611 if isSimObject(value
):
612 value
._maybe
_set
_parent
(self
, attr
)
613 elif isSimObjectSequence(value
):
614 value
= SimObjVector(value
)
616 value
[0]._maybe
_set
_parent
(self
, attr
)
618 width
= int(math
.ceil(math
.log(len(value
))/math
.log(10)))
619 for i
,v
in enumerate(value
):
620 v
._maybe
_set
_parent
(self
, "%s%0*d" % (attr
, width
, i
))
622 self
._values
[attr
] = value
627 ppath
= self
._parent
.path()
630 return ppath
+ "." + self
._name
638 def find_any(self
, ptype
):
639 if isinstance(self
, ptype
):
643 for child
in self
._children
.itervalues():
644 if isinstance(child
, ptype
):
645 if found_obj
!= None and child
!= found_obj
:
646 raise AttributeError, \
647 'parent.any matched more than one: %s %s' % \
648 (found_obj
.path
, child
.path
)
651 for pname
,pdesc
in self
._params
.iteritems():
652 if issubclass(pdesc
.ptype
, ptype
):
653 match_obj
= self
._values
[pname
]
654 if found_obj
!= None and found_obj
!= match_obj
:
655 raise AttributeError, \
656 'parent.any matched more than one: %s and %s' % (found_obj
.path
, match_obj
.path
)
657 found_obj
= match_obj
658 return found_obj
, found_obj
!= None
660 def unproxy(self
, base
):
663 def unproxy_all(self
):
664 for param
in self
._params
.iterkeys():
665 value
= self
._values
.get(param
)
666 if value
!= None and isproxy(value
):
668 value
= value
.unproxy(self
)
670 print "Error in unproxying param '%s' of %s" % \
673 setattr(self
, param
, value
)
675 # Unproxy ports in sorted order so that 'append' operations on
676 # vector ports are done in a deterministic fashion.
677 port_names
= self
._ports
.keys()
679 for port_name
in port_names
:
680 port
= self
._port
_refs
.get(port_name
)
684 # Unproxy children in sorted order for determinism also.
685 child_names
= self
._children
.keys()
687 for child
in child_names
:
688 self
._children
[child
].unproxy_all()
690 def print_ini(self
, ini_file
):
691 print >>ini_file
, '[' + self
.path() + ']' # .ini section header
693 instanceDict
[self
.path()] = self
695 if hasattr(self
, 'type'):
696 print >>ini_file
, 'type=%s' % self
.type
698 child_names
= self
._children
.keys()
701 print >>ini_file
, 'children=%s' % ' '.join(child_names
)
703 param_names
= self
._params
.keys()
705 for param
in param_names
:
706 value
= self
._values
.get(param
)
708 print >>ini_file
, '%s=%s' % (param
,
709 self
._values
[param
].ini_str())
711 port_names
= self
._ports
.keys()
713 for port_name
in port_names
:
714 port
= self
._port
_refs
.get(port_name
, None)
716 print >>ini_file
, '%s=%s' % (port_name
, port
.ini_str())
718 print >>ini_file
# blank line between objects
720 for child
in child_names
:
721 self
._children
[child
].print_ini(ini_file
)
723 def getCCParams(self
):
725 return self
._ccParams
727 cc_params_struct
= getattr(m5
.objects
.params
, '%sParams' % self
.type)
728 cc_params
= cc_params_struct()
729 cc_params
.pyobj
= self
730 cc_params
.name
= str(self
)
732 param_names
= self
._params
.keys()
734 for param
in param_names
:
735 value
= self
._values
.get(param
)
737 fatal("%s.%s without default or user set value",
740 value
= value
.getValue()
741 if isinstance(self
._params
[param
], VectorParamDesc
):
742 assert isinstance(value
, list)
743 vec
= getattr(cc_params
, param
)
748 setattr(cc_params
, param
, value
)
750 port_names
= self
._ports
.keys()
752 for port_name
in port_names
:
753 port
= self
._port
_refs
.get(port_name
, None)
755 setattr(cc_params
, port_name
, port
)
756 self
._ccParams
= cc_params
757 return self
._ccParams
759 # Get C++ object corresponding to this object, calling C++ if
760 # necessary to construct it. Does *not* recursively create
762 def getCCObject(self
):
763 if not self
._ccObject
:
764 # Make sure this object is in the configuration hierarchy
765 if not self
._parent
and not isRoot(self
):
766 raise RuntimeError, "Attempt to instantiate orphan node"
767 # Cycles in the configuration hierarchy are not supported. This
768 # will catch the resulting recursion and stop.
770 params
= self
.getCCParams()
771 self
._ccObject
= params
.create()
772 elif self
._ccObject
== -1:
773 raise RuntimeError, "%s: Cycle found in configuration hierarchy." \
775 return self
._ccObject
777 # Call C++ to create C++ object corresponding to this object and
778 # (recursively) all its children
779 def createCCObject(self
):
781 self
.getCCObject() # force creation
782 for child
in self
._children
.itervalues():
783 child
.createCCObject()
786 return self
.getCCObject()
788 # Create C++ port connections corresponding to the connections in
789 # _port_refs (& recursively for all children)
790 def connectPorts(self
):
791 for portRef
in self
._port
_refs
.itervalues():
793 for child
in self
._children
.itervalues():
796 def startDrain(self
, drain_event
, recursive
):
798 if isinstance(self
, SimObject
):
799 count
+= self
._ccObject
.drain(drain_event
)
801 for child
in self
._children
.itervalues():
802 count
+= child
.startDrain(drain_event
, True)
806 if isinstance(self
, SimObject
):
807 self
._ccObject
.resume()
808 for child
in self
._children
.itervalues():
811 def getMemoryMode(self
):
812 if not isinstance(self
, m5
.objects
.System
):
815 return self
._ccObject
.getMemoryMode()
817 def changeTiming(self
, mode
):
818 if isinstance(self
, m5
.objects
.System
):
819 # i don't know if there's a better way to do this - calling
820 # setMemoryMode directly from self._ccObject results in calling
821 # SimObject::setMemoryMode, not the System::setMemoryMode
822 self
._ccObject
.setMemoryMode(mode
)
823 for child
in self
._children
.itervalues():
824 child
.changeTiming(mode
)
826 def takeOverFrom(self
, old_cpu
):
827 self
._ccObject
.takeOverFrom(old_cpu
._ccObject
)
829 # generate output file for 'dot' to display as a pretty graph.
830 # this code is currently broken.
831 def outputDot(self
, dot
):
832 label
= "{%s|" % self
.path
833 if isSimObject(self
.realtype
):
834 label
+= '%s|' % self
.type
837 # instantiate children in same order they were added for
838 # backward compatibility (else we can end up with cpu1
840 for c
in self
.children
:
841 dot
.add_edge(pydot
.Edge(self
.path
,c
.path
, style
="bold"))
844 for param
in self
.params
:
846 if param
.value
is None:
847 raise AttributeError, 'Parameter with no value'
850 string
= param
.string(value
)
852 msg
= 'exception in %s:%s\n%s' % (self
.name
, param
.name
, e
)
856 if isSimObject(param
.ptype
) and string
!= "Null":
857 simobjs
.append(string
)
859 label
+= '%s = %s\\n' % (param
.name
, string
)
862 label
+= "|<%s> %s" % (so
, so
)
863 dot
.add_edge(pydot
.Edge("%s:%s" % (self
.path
, so
), so
,
866 dot
.add_node(pydot
.Node(self
.path
,shape
="Mrecord",label
=label
))
868 # recursively dump out children
869 for c
in self
.children
:
872 # Function to provide to C++ so it can look up instances based on paths
873 def resolveSimObject(name
):
874 obj
= instanceDict
[name
]
875 return obj
.getCCObject()
877 def isSimObject(value
):
878 return isinstance(value
, SimObject
)
880 def isSimObjectClass(value
):
881 return issubclass(value
, SimObject
)
883 def isSimObjectSequence(value
):
884 if not isinstance(value
, (list, tuple)) or len(value
) == 0:
888 if not isNullPointer(val
) and not isSimObject(val
):
893 def isSimObjectOrSequence(value
):
894 return isSimObject(value
) or isSimObjectSequence(value
)
897 from m5
.objects
import Root
898 return obj
and obj
is Root
.getInstance()
900 baseClasses
= allClasses
.copy()
901 baseInstances
= instanceDict
.copy()
904 global allClasses
, instanceDict
906 allClasses
= baseClasses
.copy()
907 instanceDict
= baseInstances
.copy()
909 # __all__ defines the list of symbols that get exported when
910 # 'from config import *' is invoked. Try to keep this reasonably
911 # short to avoid polluting other namespaces.
912 __all__
= [ 'SimObject' ]