d26a9905180c00ea53d6dd512f419c77f7a686f9
1 # Copyright (c) 2004-2006 The Regents of The University of Michigan
2 # Copyright (c) 2010 Advanced Micro Devices, Inc.
5 # Redistribution and use in source and binary forms, with or without
6 # modification, are permitted provided that the following conditions are
7 # met: redistributions of source code must retain the above copyright
8 # notice, this list of conditions and the following disclaimer;
9 # redistributions in binary form must reproduce the above copyright
10 # notice, this list of conditions and the following disclaimer in the
11 # documentation and/or other materials provided with the distribution;
12 # neither the name of the copyright holders nor the names of its
13 # contributors may be used to endorse or promote products derived from
14 # this software without specific prior written permission.
16 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 # Authors: Steve Reinhardt
32 from types
import FunctionType
, MethodType
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
, \
49 isNullPointer
, SimObjectVector
51 from m5
.proxy
import *
52 from m5
.proxy
import isproxy
54 #####################################################################
56 # M5 Python Configuration Utility
58 # The basic idea is to write simple Python programs that build Python
59 # objects corresponding to M5 SimObjects for the desired simulation
60 # configuration. For now, the Python emits a .ini file that can be
61 # parsed by M5. In the future, some tighter integration between M5
62 # and the Python interpreter may allow bypassing the .ini file.
64 # Each SimObject class in M5 is represented by a Python class with the
65 # same name. The Python inheritance tree mirrors the M5 C++ tree
66 # (e.g., SimpleCPU derives from BaseCPU in both cases, and all
67 # SimObjects inherit from a single SimObject base class). To specify
68 # an instance of an M5 SimObject in a configuration, the user simply
69 # instantiates the corresponding Python object. The parameters for
70 # that SimObject are given by assigning to attributes of the Python
71 # object, either using keyword assignment in the constructor or in
72 # separate assignment statements. For example:
74 # cache = BaseCache(size='64KB')
75 # cache.hit_latency = 3
78 # The magic lies in the mapping of the Python attributes for SimObject
79 # classes to the actual SimObject parameter specifications. This
80 # allows parameter validity checking in the Python code. Continuing
81 # the example above, the statements "cache.blurfl=3" or
82 # "cache.assoc='hello'" would both result in runtime errors in Python,
83 # since the BaseCache object has no 'blurfl' parameter and the 'assoc'
84 # parameter requires an integer, respectively. This magic is done
85 # primarily by overriding the special __setattr__ method that controls
86 # assignment to object attributes.
88 # Once a set of Python objects have been instantiated in a hierarchy,
89 # calling 'instantiate(obj)' (where obj is the root of the hierarchy)
90 # will generate a .ini file.
92 #####################################################################
94 # list of all SimObject classes
97 # dict to look up SimObjects based on path
100 def default_cxx_predecls(cls
, code
):
101 '''A forward class declaration is sufficient since we are
102 just declaring a pointer.'''
104 class_path
= cls
._value
_dict
['cxx_class'].split('::')
105 for ns
in class_path
[:-1]:
106 code('namespace $ns {')
107 code('class $0;', class_path
[-1])
108 for ns
in reversed(class_path
[:-1]):
109 code('/* namespace $ns */ }')
111 def default_swig_objdecls(cls
, code
):
112 class_path
= cls
.cxx_class
.split('::')
113 classname
= class_path
[-1]
114 namespaces
= class_path
[:-1]
116 for ns
in namespaces
:
117 code('namespace $ns {')
120 code('// avoid name conflicts')
121 sep_string
= '_COLONS_'
122 flat_name
= sep_string
.join(class_path
)
123 code('%rename($flat_name) $classname;')
126 code('// stop swig from creating/wrapping default ctor/dtor')
127 code('%nodefault $classname;')
128 code('class $classname')
130 code(' : public ${{cls._base.cxx_class}}')
133 for ns
in reversed(namespaces
):
134 code('/* namespace $ns */ }')
136 def public_value(key
, value
):
137 return key
.startswith('_') or \
138 isinstance(value
, (FunctionType
, MethodType
, classmethod, type))
140 # The metaclass for SimObject. This class controls how new classes
141 # that derive from SimObject are instantiated, and provides inherited
142 # class behavior (just like a class controls how instances of that
143 # class are instantiated, and provides inherited instance behavior).
144 class MetaSimObject(type):
145 # Attributes that can be set only at initialization time
146 init_keywords
= { 'abstract' : bool,
149 'cxx_predecls' : MethodType
,
150 'swig_objdecls' : MethodType
,
151 'swig_predecls' : MethodType
,
153 # Attributes that can be set any time
154 keywords
= { 'check' : FunctionType
}
156 # __new__ is called before __init__, and is where the statements
157 # in the body of the class definition get loaded into the class's
158 # __dict__. We intercept this to filter out parameter & port assignments
159 # and only allow "private" attributes to be passed to the base
160 # __new__ (starting with underscore).
161 def __new__(mcls
, name
, bases
, dict):
162 assert name
not in allClasses
, "SimObject %s already present" % name
164 # Copy "private" attributes, functions, and classes to the
165 # official dict. Everything else goes in _init_dict to be
166 # filtered in __init__.
169 for key
,val
in dict.items():
170 if public_value(key
, val
):
173 # must be a param/port setting
174 value_dict
[key
] = val
175 if 'abstract' not in value_dict
:
176 value_dict
['abstract'] = False
177 cls_dict
['_value_dict'] = value_dict
178 cls
= super(MetaSimObject
, mcls
).__new
__(mcls
, name
, bases
, cls_dict
)
179 if 'type' in value_dict
:
180 allClasses
[name
] = cls
183 # subclass initialization
184 def __init__(cls
, name
, bases
, dict):
185 # calls type.__init__()... I think that's a no-op, but leave
186 # it here just in case it's not.
187 super(MetaSimObject
, cls
).__init
__(name
, bases
, dict)
189 # initialize required attributes
191 # class-only attributes
192 cls
._params
= multidict() # param descriptions
193 cls
._ports
= multidict() # port descriptions
195 # class or instance attributes
196 cls
._values
= multidict() # param values
197 cls
._children
= multidict() # SimObject children
198 cls
._port
_refs
= multidict() # port ref objects
199 cls
._instantiated
= False # really instantiated, cloned, or subclassed
201 # We don't support multiple inheritance. If you want to, you
202 # must fix multidict to deal with it properly.
204 raise TypeError, "SimObjects do not support multiple inheritance"
208 # Set up general inheritance via multidicts. A subclass will
209 # inherit all its settings from the base class. The only time
210 # the following is not true is when we define the SimObject
211 # class itself (in which case the multidicts have no parent).
212 if isinstance(base
, MetaSimObject
):
214 cls
._params
.parent
= base
._params
215 cls
._ports
.parent
= base
._ports
216 cls
._values
.parent
= base
._values
217 cls
._children
.parent
= base
._children
218 cls
._port
_refs
.parent
= base
._port
_refs
219 # mark base as having been subclassed
220 base
._instantiated
= True
224 # default keyword values
225 if 'type' in cls
._value
_dict
:
226 if 'cxx_class' not in cls
._value
_dict
:
227 cls
._value
_dict
['cxx_class'] = cls
._value
_dict
['type']
229 cls
._value
_dict
['cxx_type'] = '%s *' % cls
._value
_dict
['cxx_class']
231 if 'cxx_predecls' not in cls
.__dict
__:
232 m
= MethodType(default_cxx_predecls
, cls
, MetaSimObject
)
233 setattr(cls
, 'cxx_predecls', m
)
235 if 'swig_predecls' not in cls
.__dict
__:
236 setattr(cls
, 'swig_predecls', getattr(cls
, 'cxx_predecls'))
238 if 'swig_objdecls' not in cls
.__dict
__:
239 m
= MethodType(default_swig_objdecls
, cls
, MetaSimObject
)
240 setattr(cls
, 'swig_objdecls', m
)
242 # Now process the _value_dict items. They could be defining
243 # new (or overriding existing) parameters or ports, setting
244 # class keywords (e.g., 'abstract'), or setting parameter
245 # values or port bindings. The first 3 can only be set when
246 # the class is defined, so we handle them here. The others
247 # can be set later too, so just emulate that by calling
249 for key
,val
in cls
._value
_dict
.items():
251 if isinstance(val
, ParamDesc
):
252 cls
._new
_param
(key
, val
)
255 elif isinstance(val
, Port
):
256 cls
._new
_port
(key
, val
)
258 # init-time-only keywords
259 elif cls
.init_keywords
.has_key(key
):
260 cls
._set
_keyword
(key
, val
, cls
.init_keywords
[key
])
262 # default: use normal path (ends up in __setattr__)
264 setattr(cls
, key
, val
)
266 def _set_keyword(cls
, keyword
, val
, kwtype
):
267 if not isinstance(val
, kwtype
):
268 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
269 (keyword
, type(val
), kwtype
)
270 if isinstance(val
, FunctionType
):
271 val
= classmethod(val
)
272 type.__setattr
__(cls
, keyword
, val
)
274 def _new_param(cls
, name
, pdesc
):
275 # each param desc should be uniquely assigned to one variable
276 assert(not hasattr(pdesc
, 'name'))
278 cls
._params
[name
] = pdesc
279 if hasattr(pdesc
, 'default'):
280 cls
._set
_param
(name
, pdesc
.default
, pdesc
)
282 def _set_param(cls
, name
, value
, param
):
283 assert(param
.name
== name
)
285 cls
._values
[name
] = param
.convert(value
)
287 msg
= "%s\nError setting param %s.%s to %s\n" % \
288 (e
, cls
.__name
__, name
, value
)
292 def _new_port(cls
, name
, port
):
293 # each port should be uniquely assigned to one variable
294 assert(not hasattr(port
, 'name'))
296 cls
._ports
[name
] = port
297 if hasattr(port
, 'default'):
298 cls
._cls
_get
_port
_ref
(name
).connect(port
.default
)
300 # same as _get_port_ref, effectively, but for classes
301 def _cls_get_port_ref(cls
, attr
):
302 # Return reference that can be assigned to another port
303 # via __setattr__. There is only ever one reference
304 # object per port, but we create them lazily here.
305 ref
= cls
._port
_refs
.get(attr
)
307 ref
= cls
._ports
[attr
].makeRef(cls
)
308 cls
._port
_refs
[attr
] = ref
311 # Set attribute (called on foo.attr = value when foo is an
312 # instance of class cls).
313 def __setattr__(cls
, attr
, value
):
314 # normal processing for private attributes
315 if public_value(attr
, value
):
316 type.__setattr
__(cls
, attr
, value
)
319 if cls
.keywords
.has_key(attr
):
320 cls
._set
_keyword
(attr
, value
, cls
.keywords
[attr
])
323 if cls
._ports
.has_key(attr
):
324 cls
._cls
_get
_port
_ref
(attr
).connect(value
)
327 if isSimObjectOrSequence(value
) and cls
._instantiated
:
328 raise RuntimeError, \
329 "cannot set SimObject parameter '%s' after\n" \
330 " class %s has been instantiated or subclassed" \
331 % (attr
, cls
.__name
__)
334 param
= cls
._params
.get(attr
)
336 cls
._set
_param
(attr
, value
, param
)
339 if isSimObjectOrSequence(value
):
340 # If RHS is a SimObject, it's an implicit child assignment.
341 cls
._children
[attr
] = coerceSimObjectOrVector(value
)
344 # no valid assignment... raise exception
345 raise AttributeError, \
346 "Class %s has no parameter \'%s\'" % (cls
.__name
__, attr
)
348 def __getattr__(cls
, attr
):
349 if cls
._values
.has_key(attr
):
350 return cls
._values
[attr
]
352 if cls
._children
.has_key(attr
):
353 return cls
._children
[attr
]
355 raise AttributeError, \
356 "object '%s' has no attribute '%s'" % (cls
.__name
__, attr
)
361 def cxx_decl(cls
, code
):
363 #ifndef __PARAMS__${cls}__
364 #define __PARAMS__${cls}__
368 # The 'dict' attribute restricts us to the params declared in
369 # the object itself, not including inherited params (which
370 # will also be inherited from the base class's param struct
372 params
= cls
._params
.local
.values()
374 ptypes
= [p
.ptype
for p
in params
]
376 print cls
, p
, p
.ptype_str
380 # get all predeclarations
381 cls
.cxx_predecls(code
)
383 param
.cxx_predecls(code
)
387 code('#include "params/${{cls._base.type}}.hh"')
391 if issubclass(ptype
, Enum
):
392 code('#include "enums/${{ptype.__name__}}.hh"')
395 cls
.cxx_struct(code
, cls
._base
, params
)
397 # close #ifndef __PARAMS__* guard
399 code('#endif // __PARAMS__${cls}__')
402 def cxx_struct(cls
, code
, base
, params
):
404 code('#include "sim/sim_object_params.hh"')
407 # now generate the actual param struct
408 code("struct ${cls}Params")
410 code(" : public ${{base.type}}Params")
412 if not hasattr(cls
, 'abstract') or not cls
.abstract
:
413 if 'type' in cls
.__dict
__:
414 code(" ${{cls.cxx_type}} create();")
422 def swig_decl(cls
, code
):
427 #include "params/$cls.hh"
432 # The 'dict' attribute restricts us to the params declared in
433 # the object itself, not including inherited params (which
434 # will also be inherited from the base class's param struct
436 params
= cls
._params
.local
.values()
437 ptypes
= [p
.ptype
for p
in params
]
439 # get all predeclarations
441 param
.swig_predecls(code
)
445 code('%import "params/${{cls._base.type}}.i"')
449 if issubclass(ptype
, Enum
):
450 code('%import "enums/${{ptype.__name__}}.hh"')
453 code('%import "params/${cls}_type.hh"')
454 code('%include "params/${cls}.hh"')
456 # The SimObject class is the root of the special hierarchy. Most of
457 # the code in this class deals with the configuration hierarchy itself
458 # (parent/child node relationships).
459 class SimObject(object):
460 # Specify metaclass. Any class inheriting from SimObject will
461 # get this metaclass.
462 __metaclass__
= MetaSimObject
467 def swig_objdecls(cls
, code
):
468 code('%include "python/swig/sim_object.i"')
470 # Initialize new instance. For objects with SimObject-valued
471 # children, we need to recursively clone the classes represented
472 # by those param values as well in a consistent "deep copy"-style
473 # fashion. That is, we want to make sure that each instance is
474 # cloned only once, and that if there are multiple references to
475 # the same original object, we end up with the corresponding
476 # cloned references all pointing to the same cloned instance.
477 def __init__(self
, **kwargs
):
478 ancestor
= kwargs
.get('_ancestor')
479 memo_dict
= kwargs
.get('_memo')
480 if memo_dict
is None:
481 # prepare to memoize any recursively instantiated objects
484 # memoize me now to avoid problems with recursive calls
485 memo_dict
[ancestor
] = self
488 ancestor
= self
.__class
__
489 ancestor
._instantiated
= True
491 # initialize required attributes
494 self
._ccObject
= None # pointer to C++ object
495 self
._ccParams
= None
496 self
._instantiated
= False # really "cloned"
498 # Inherit parameter values from class using multidict so
499 # individual value settings can be overridden but we still
500 # inherit late changes to non-overridden class values.
501 self
._values
= multidict(ancestor
._values
)
502 # clone SimObject-valued parameters
503 for key
,val
in ancestor
._values
.iteritems():
504 val
= tryAsSimObjectOrVector(val
)
506 self
._values
[key
] = val(_memo
=memo_dict
)
508 # Clone children specified at class level. No need for a
509 # multidict here since we will be cloning everything.
511 for key
,val
in ancestor
._children
.iteritems():
512 self
.add_child(key
, val(_memo
=memo_dict
))
514 # clone port references. no need to use a multidict here
515 # since we will be creating new references for all ports.
517 for key
,val
in ancestor
._port
_refs
.iteritems():
518 self
._port
_refs
[key
] = val
.clone(self
, memo_dict
)
519 # apply attribute assignments from keyword args, if any
520 for key
,val
in kwargs
.iteritems():
521 setattr(self
, key
, val
)
523 # "Clone" the current instance by creating another instance of
524 # this instance's class, but that inherits its parameter values
525 # and port mappings from the current instance. If we're in a
526 # "deep copy" recursive clone, check the _memo dict to see if
527 # we've already cloned this instance.
528 def __call__(self
, **kwargs
):
529 memo_dict
= kwargs
.get('_memo')
530 if memo_dict
is None:
531 # no memo_dict: must be top-level clone operation.
532 # this is only allowed at the root of a hierarchy
534 raise RuntimeError, "attempt to clone object %s " \
535 "not at the root of a tree (parent = %s)" \
536 % (self
, self
._parent
)
537 # create a new dict and use that.
539 kwargs
['_memo'] = memo_dict
540 elif memo_dict
.has_key(self
):
541 # clone already done & memoized
542 return memo_dict
[self
]
543 return self
.__class
__(_ancestor
= self
, **kwargs
)
545 def _get_port_ref(self
, attr
):
546 # Return reference that can be assigned to another port
547 # via __setattr__. There is only ever one reference
548 # object per port, but we create them lazily here.
549 ref
= self
._port
_refs
.get(attr
)
551 ref
= self
._ports
[attr
].makeRef(self
)
552 self
._port
_refs
[attr
] = ref
555 def __getattr__(self
, attr
):
556 if self
._ports
.has_key(attr
):
557 return self
._get
_port
_ref
(attr
)
559 if self
._values
.has_key(attr
):
560 return self
._values
[attr
]
562 if self
._children
.has_key(attr
):
563 return self
._children
[attr
]
565 # If the attribute exists on the C++ object, transparently
566 # forward the reference there. This is typically used for
567 # SWIG-wrapped methods such as init(), regStats(),
568 # regFormulas(), resetStats(), startup(), drain(), and
570 if self
._ccObject
and hasattr(self
._ccObject
, attr
):
571 return getattr(self
._ccObject
, attr
)
573 raise AttributeError, "object '%s' has no attribute '%s'" \
574 % (self
.__class
__.__name
__, attr
)
576 # Set attribute (called on foo.attr = value when foo is an
577 # instance of class cls).
578 def __setattr__(self
, attr
, value
):
579 # normal processing for private attributes
580 if attr
.startswith('_'):
581 object.__setattr
__(self
, attr
, value
)
584 if self
._ports
.has_key(attr
):
585 # set up port connection
586 self
._get
_port
_ref
(attr
).connect(value
)
589 if isSimObjectOrSequence(value
) and self
._instantiated
:
590 raise RuntimeError, \
591 "cannot set SimObject parameter '%s' after\n" \
592 " instance been cloned %s" % (attr
, `self`
)
594 param
= self
._params
.get(attr
)
597 value
= param
.convert(value
)
599 msg
= "%s\nError setting param %s.%s to %s\n" % \
600 (e
, self
.__class
__.__name
__, attr
, value
)
603 self
._values
[attr
] = value
606 # if RHS is a SimObject, it's an implicit child assignment
607 if isSimObjectOrSequence(value
):
608 self
.add_child(attr
, value
)
611 # no valid assignment... raise exception
612 raise AttributeError, "Class %s has no parameter %s" \
613 % (self
.__class
__.__name
__, attr
)
616 # this hack allows tacking a '[0]' onto parameters that may or may
617 # not be vectors, and always getting the first element (e.g. cpus)
618 def __getitem__(self
, key
):
621 raise TypeError, "Non-zero index '%s' to SimObject" % key
623 # Also implemented by SimObjectVector
624 def clear_parent(self
, old_parent
):
625 assert self
._parent
is old_parent
628 # Also implemented by SimObjectVector
629 def set_parent(self
, parent
, name
):
630 self
._parent
= parent
633 # Also implemented by SimObjectVector
637 # use this rather than directly accessing _parent for symmetry
638 # with SimObjectVector
639 def get_parent(self
):
642 # clear out child with given name
643 def clear_child(self
, name
):
644 child
= self
._children
[name
]
645 child
.clear_parent(self
)
646 del self
._children
[name
]
648 # Add a new child to this object.
649 def add_child(self
, name
, child
):
650 child
= coerceSimObjectOrVector(child
)
651 if child
.get_parent():
652 raise RuntimeError, \
653 "add_child('%s'): child '%s' already has parent '%s'" % \
654 (name
, child
._name
, child
._parent
)
655 if self
._children
.has_key(name
):
657 child
.set_parent(self
, name
)
658 self
._children
[name
] = child
660 # Take SimObject-valued parameters that haven't been explicitly
661 # assigned as children and make them children of the object that
662 # they were assigned to as a parameter value. This guarantees
663 # that when we instantiate all the parameter objects we're still
664 # inside the configuration hierarchy.
665 def adoptOrphanParams(self
):
666 for key
,val
in self
._values
.iteritems():
667 if not isSimObjectVector(val
) and isSimObjectSequence(val
):
668 # need to convert raw SimObject sequences to
669 # SimObjectVector class so we can call get_parent()
670 val
= SimObjectVector(val
)
671 self
._values
[key
] = val
672 if isSimObjectOrVector(val
) and not val
.get_parent():
673 self
.add_child(key
, val
)
678 ppath
= self
._parent
.path()
681 return ppath
+ "." + self
._name
689 def find_any(self
, ptype
):
690 if isinstance(self
, ptype
):
694 for child
in self
._children
.itervalues():
695 if isinstance(child
, ptype
):
696 if found_obj
!= None and child
!= found_obj
:
697 raise AttributeError, \
698 'parent.any matched more than one: %s %s' % \
699 (found_obj
.path
, child
.path
)
702 for pname
,pdesc
in self
._params
.iteritems():
703 if issubclass(pdesc
.ptype
, ptype
):
704 match_obj
= self
._values
[pname
]
705 if found_obj
!= None and found_obj
!= match_obj
:
706 raise AttributeError, \
707 'parent.any matched more than one: %s and %s' % (found_obj
.path
, match_obj
.path
)
708 found_obj
= match_obj
709 return found_obj
, found_obj
!= None
711 def unproxy(self
, base
):
714 def unproxyParams(self
):
715 for param
in self
._params
.iterkeys():
716 value
= self
._values
.get(param
)
717 if value
!= None and isproxy(value
):
719 value
= value
.unproxy(self
)
721 print "Error in unproxying param '%s' of %s" % \
724 setattr(self
, param
, value
)
726 # Unproxy ports in sorted order so that 'append' operations on
727 # vector ports are done in a deterministic fashion.
728 port_names
= self
._ports
.keys()
730 for port_name
in port_names
:
731 port
= self
._port
_refs
.get(port_name
)
735 def print_ini(self
, ini_file
):
736 print >>ini_file
, '[' + self
.path() + ']' # .ini section header
738 instanceDict
[self
.path()] = self
740 if hasattr(self
, 'type'):
741 print >>ini_file
, 'type=%s' % self
.type
743 child_names
= self
._children
.keys()
746 print >>ini_file
, 'children=%s' % \
747 ' '.join(self
._children
[n
].get_name() for n
in child_names
)
749 param_names
= self
._params
.keys()
751 for param
in param_names
:
752 value
= self
._values
.get(param
)
754 print >>ini_file
, '%s=%s' % (param
,
755 self
._values
[param
].ini_str())
757 port_names
= self
._ports
.keys()
759 for port_name
in port_names
:
760 port
= self
._port
_refs
.get(port_name
, None)
762 print >>ini_file
, '%s=%s' % (port_name
, port
.ini_str())
764 print >>ini_file
# blank line between objects
766 def getCCParams(self
):
768 return self
._ccParams
770 cc_params_struct
= getattr(m5
.objects
.params
, '%sParams' % self
.type)
771 cc_params
= cc_params_struct()
772 cc_params
.pyobj
= self
773 cc_params
.name
= str(self
)
775 param_names
= self
._params
.keys()
777 for param
in param_names
:
778 value
= self
._values
.get(param
)
780 fatal("%s.%s without default or user set value",
783 value
= value
.getValue()
784 if isinstance(self
._params
[param
], VectorParamDesc
):
785 assert isinstance(value
, list)
786 vec
= getattr(cc_params
, param
)
791 setattr(cc_params
, param
, value
)
793 port_names
= self
._ports
.keys()
795 for port_name
in port_names
:
796 port
= self
._port
_refs
.get(port_name
, None)
798 setattr(cc_params
, port_name
, port
)
799 self
._ccParams
= cc_params
800 return self
._ccParams
802 # Get C++ object corresponding to this object, calling C++ if
803 # necessary to construct it. Does *not* recursively create
805 def getCCObject(self
):
806 if not self
._ccObject
:
807 # Make sure this object is in the configuration hierarchy
808 if not self
._parent
and not isRoot(self
):
809 raise RuntimeError, "Attempt to instantiate orphan node"
810 # Cycles in the configuration hierarchy are not supported. This
811 # will catch the resulting recursion and stop.
813 params
= self
.getCCParams()
814 self
._ccObject
= params
.create()
815 elif self
._ccObject
== -1:
816 raise RuntimeError, "%s: Cycle found in configuration hierarchy." \
818 return self
._ccObject
820 def descendants(self
):
822 for child
in self
._children
.itervalues():
823 for obj
in child
.descendants():
826 # Call C++ to create C++ object corresponding to this object
827 def createCCObject(self
):
829 self
.getCCObject() # force creation
832 return self
.getCCObject()
834 # Create C++ port connections corresponding to the connections in
836 def connectPorts(self
):
837 for portRef
in self
._port
_refs
.itervalues():
840 def getMemoryMode(self
):
841 if not isinstance(self
, m5
.objects
.System
):
844 return self
._ccObject
.getMemoryMode()
846 def changeTiming(self
, mode
):
847 if isinstance(self
, m5
.objects
.System
):
848 # i don't know if there's a better way to do this - calling
849 # setMemoryMode directly from self._ccObject results in calling
850 # SimObject::setMemoryMode, not the System::setMemoryMode
851 self
._ccObject
.setMemoryMode(mode
)
853 def takeOverFrom(self
, old_cpu
):
854 self
._ccObject
.takeOverFrom(old_cpu
._ccObject
)
856 # generate output file for 'dot' to display as a pretty graph.
857 # this code is currently broken.
858 def outputDot(self
, dot
):
859 label
= "{%s|" % self
.path
860 if isSimObject(self
.realtype
):
861 label
+= '%s|' % self
.type
864 # instantiate children in same order they were added for
865 # backward compatibility (else we can end up with cpu1
867 for c
in self
.children
:
868 dot
.add_edge(pydot
.Edge(self
.path
,c
.path
, style
="bold"))
871 for param
in self
.params
:
873 if param
.value
is None:
874 raise AttributeError, 'Parameter with no value'
877 string
= param
.string(value
)
879 msg
= 'exception in %s:%s\n%s' % (self
.name
, param
.name
, e
)
883 if isSimObject(param
.ptype
) and string
!= "Null":
884 simobjs
.append(string
)
886 label
+= '%s = %s\\n' % (param
.name
, string
)
889 label
+= "|<%s> %s" % (so
, so
)
890 dot
.add_edge(pydot
.Edge("%s:%s" % (self
.path
, so
), so
,
893 dot
.add_node(pydot
.Node(self
.path
,shape
="Mrecord",label
=label
))
895 # recursively dump out children
896 for c
in self
.children
:
899 # Function to provide to C++ so it can look up instances based on paths
900 def resolveSimObject(name
):
901 obj
= instanceDict
[name
]
902 return obj
.getCCObject()
904 def isSimObject(value
):
905 return isinstance(value
, SimObject
)
907 def isSimObjectClass(value
):
908 return issubclass(value
, SimObject
)
910 def isSimObjectVector(value
):
911 return isinstance(value
, SimObjectVector
)
913 def isSimObjectSequence(value
):
914 if not isinstance(value
, (list, tuple)) or len(value
) == 0:
918 if not isNullPointer(val
) and not isSimObject(val
):
923 def isSimObjectOrSequence(value
):
924 return isSimObject(value
) or isSimObjectSequence(value
)
927 from m5
.objects
import Root
928 return obj
and obj
is Root
.getInstance()
930 def isSimObjectOrVector(value
):
931 return isSimObject(value
) or isSimObjectVector(value
)
933 def tryAsSimObjectOrVector(value
):
934 if isSimObjectOrVector(value
):
936 if isSimObjectSequence(value
):
937 return SimObjectVector(value
)
940 def coerceSimObjectOrVector(value
):
941 value
= tryAsSimObjectOrVector(value
)
943 raise TypeError, "SimObject or SimObjectVector expected"
946 baseClasses
= allClasses
.copy()
947 baseInstances
= instanceDict
.copy()
950 global allClasses
, instanceDict
952 allClasses
= baseClasses
.copy()
953 instanceDict
= baseInstances
.copy()
955 # __all__ defines the list of symbols that get exported when
956 # 'from config import *' is invoked. Try to keep this reasonably
957 # short to avoid polluting other namespaces.
958 __all__
= [ 'SimObject' ]