SimObject.py (6654:4c84e771cca7) SimObject.py (7493:81328f5e764a)
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 math
31import sys
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 math
31import sys
32import types
32from types import FunctionType
33
34try:
35 import pydot
36except:
37 pydot = False
38
39import m5
40from m5.util import *
41
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)...
45from 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
48from m5.params import ParamDesc, VectorParamDesc, isNullPointer, SimObjVector
49
50from m5.proxy import *
51from m5.proxy import isproxy
52
53#####################################################################
54#
55# M5 Python Configuration Utility
56#
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.
62#
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:
72#
73# cache = BaseCache(size='64KB')
74# cache.hit_latency = 3
75# cache.assoc = 8
76#
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.
86#
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.
90#
91#####################################################################
92
93# list of all SimObject classes
94allClasses = {}
95
96# dict to look up SimObjects based on path
97instanceDict = {}
98
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).
103class MetaSimObject(type):
104 # Attributes that can be set only at initialization time
33
34try:
35 import pydot
36except:
37 pydot = False
38
39import m5
40from m5.util import *
41
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)...
45from 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
48from m5.params import ParamDesc, VectorParamDesc, isNullPointer, SimObjVector
49
50from m5.proxy import *
51from m5.proxy import isproxy
52
53#####################################################################
54#
55# M5 Python Configuration Utility
56#
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.
62#
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:
72#
73# cache = BaseCache(size='64KB')
74# cache.hit_latency = 3
75# cache.assoc = 8
76#
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.
86#
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.
90#
91#####################################################################
92
93# list of all SimObject classes
94allClasses = {}
95
96# dict to look up SimObjects based on path
97instanceDict = {}
98
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).
103class MetaSimObject(type):
104 # Attributes that can be set only at initialization time
105 init_keywords = { 'abstract' : types.BooleanType,
106 'cxx_class' : types.StringType,
107 'cxx_type' : types.StringType,
108 'cxx_predecls' : types.ListType,
109 'swig_objdecls' : types.ListType,
110 'swig_predecls' : types.ListType,
111 'type' : types.StringType }
105 init_keywords = { 'abstract' : bool,
106 'cxx_class' : str,
107 'cxx_type' : str,
108 'cxx_predecls' : list,
109 'swig_objdecls' : list,
110 'swig_predecls' : list,
111 'type' : str }
112 # Attributes that can be set any time
112 # Attributes that can be set any time
113 keywords = { 'check' : types.FunctionType }
113 keywords = { 'check' : FunctionType }
114
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
122
123 # Copy "private" attributes, functions, and classes to the
124 # official dict. Everything else goes in _init_dict to be
125 # filtered in __init__.
126 cls_dict = {}
127 value_dict = {}
128 for key,val in dict.items():
114
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
122
123 # Copy "private" attributes, functions, and classes to the
124 # official dict. Everything else goes in _init_dict to be
125 # filtered in __init__.
126 cls_dict = {}
127 value_dict = {}
128 for key,val in dict.items():
129 if key.startswith('_') or isinstance(val, (types.FunctionType,
130 types.TypeType)):
129 if key.startswith('_') or isinstance(val, (FunctionType,
130 classmethod,
131 type)):
131 cls_dict[key] = val
132 else:
133 # must be a param/port setting
134 value_dict[key] = val
135 if 'abstract' not in value_dict:
136 value_dict['abstract'] = False
137 cls_dict['_value_dict'] = value_dict
138 cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict)
139 if 'type' in value_dict:
140 allClasses[name] = cls
141 return cls
142
143 # subclass initialization
144 def __init__(cls, name, bases, dict):
145 # calls type.__init__()... I think that's a no-op, but leave
146 # it here just in case it's not.
147 super(MetaSimObject, cls).__init__(name, bases, dict)
148
149 # initialize required attributes
150
151 # class-only attributes
152 cls._params = multidict() # param descriptions
153 cls._ports = multidict() # port descriptions
154
155 # class or instance attributes
156 cls._values = multidict() # param values
157 cls._port_refs = multidict() # port ref objects
158 cls._instantiated = False # really instantiated, cloned, or subclassed
159
160 # We don't support multiple inheritance. If you want to, you
161 # must fix multidict to deal with it properly.
162 if len(bases) > 1:
163 raise TypeError, "SimObjects do not support multiple inheritance"
164
165 base = bases[0]
166
167 # Set up general inheritance via multidicts. A subclass will
168 # inherit all its settings from the base class. The only time
169 # the following is not true is when we define the SimObject
170 # class itself (in which case the multidicts have no parent).
171 if isinstance(base, MetaSimObject):
172 cls._base = base
173 cls._params.parent = base._params
174 cls._ports.parent = base._ports
175 cls._values.parent = base._values
176 cls._port_refs.parent = base._port_refs
177 # mark base as having been subclassed
178 base._instantiated = True
179 else:
180 cls._base = None
181
182 # default keyword values
183 if 'type' in cls._value_dict:
184 if 'cxx_class' not in cls._value_dict:
185 cls._value_dict['cxx_class'] = cls._value_dict['type']
186
187 cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class']
188
189 if 'cxx_predecls' not in cls._value_dict:
190 # A forward class declaration is sufficient since we are
191 # just declaring a pointer.
192 class_path = cls._value_dict['cxx_class'].split('::')
193 class_path.reverse()
194 decl = 'class %s;' % class_path[0]
195 for ns in class_path[1:]:
196 decl = 'namespace %s { %s }' % (ns, decl)
197 cls._value_dict['cxx_predecls'] = [decl]
198
199 if 'swig_predecls' not in cls._value_dict:
200 # A forward class declaration is sufficient since we are
201 # just declaring a pointer.
202 cls._value_dict['swig_predecls'] = \
203 cls._value_dict['cxx_predecls']
204
205 if 'swig_objdecls' not in cls._value_dict:
206 cls._value_dict['swig_objdecls'] = []
207
208 # Now process the _value_dict items. They could be defining
209 # new (or overriding existing) parameters or ports, setting
210 # class keywords (e.g., 'abstract'), or setting parameter
211 # values or port bindings. The first 3 can only be set when
212 # the class is defined, so we handle them here. The others
213 # can be set later too, so just emulate that by calling
214 # setattr().
215 for key,val in cls._value_dict.items():
216 # param descriptions
217 if isinstance(val, ParamDesc):
218 cls._new_param(key, val)
219
220 # port objects
221 elif isinstance(val, Port):
222 cls._new_port(key, val)
223
224 # init-time-only keywords
225 elif cls.init_keywords.has_key(key):
226 cls._set_keyword(key, val, cls.init_keywords[key])
227
228 # default: use normal path (ends up in __setattr__)
229 else:
230 setattr(cls, key, val)
231
232 def _set_keyword(cls, keyword, val, kwtype):
233 if not isinstance(val, kwtype):
234 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
235 (keyword, type(val), kwtype)
132 cls_dict[key] = val
133 else:
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
142 return cls
143
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)
149
150 # initialize required attributes
151
152 # class-only attributes
153 cls._params = multidict() # param descriptions
154 cls._ports = multidict() # port descriptions
155
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
160
161 # We don't support multiple inheritance. If you want to, you
162 # must fix multidict to deal with it properly.
163 if len(bases) > 1:
164 raise TypeError, "SimObjects do not support multiple inheritance"
165
166 base = bases[0]
167
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):
173 cls._base = base
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
180 else:
181 cls._base = None
182
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']
187
188 cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class']
189
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('::')
194 class_path.reverse()
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]
199
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']
205
206 if 'swig_objdecls' not in cls._value_dict:
207 cls._value_dict['swig_objdecls'] = []
208
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
215 # setattr().
216 for key,val in cls._value_dict.items():
217 # param descriptions
218 if isinstance(val, ParamDesc):
219 cls._new_param(key, val)
220
221 # port objects
222 elif isinstance(val, Port):
223 cls._new_port(key, val)
224
225 # init-time-only keywords
226 elif cls.init_keywords.has_key(key):
227 cls._set_keyword(key, val, cls.init_keywords[key])
228
229 # default: use normal path (ends up in __setattr__)
230 else:
231 setattr(cls, key, val)
232
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)
236 if isinstance(val, types.FunctionType):
237 if isinstance(val, FunctionType):
237 val = classmethod(val)
238 type.__setattr__(cls, keyword, val)
239
240 def _new_param(cls, name, pdesc):
241 # each param desc should be uniquely assigned to one variable
242 assert(not hasattr(pdesc, 'name'))
243 pdesc.name = name
244 cls._params[name] = pdesc
245 if hasattr(pdesc, 'default'):
246 cls._set_param(name, pdesc.default, pdesc)
247
248 def _set_param(cls, name, value, param):
249 assert(param.name == name)
250 try:
251 cls._values[name] = param.convert(value)
252 except Exception, e:
253 msg = "%s\nError setting param %s.%s to %s\n" % \
254 (e, cls.__name__, name, value)
255 e.args = (msg, )
256 raise
257
258 def _new_port(cls, name, port):
259 # each port should be uniquely assigned to one variable
260 assert(not hasattr(port, 'name'))
261 port.name = name
262 cls._ports[name] = port
263 if hasattr(port, 'default'):
264 cls._cls_get_port_ref(name).connect(port.default)
265
266 # same as _get_port_ref, effectively, but for classes
267 def _cls_get_port_ref(cls, attr):
268 # Return reference that can be assigned to another port
269 # via __setattr__. There is only ever one reference
270 # object per port, but we create them lazily here.
271 ref = cls._port_refs.get(attr)
272 if not ref:
273 ref = cls._ports[attr].makeRef(cls)
274 cls._port_refs[attr] = ref
275 return ref
276
277 # Set attribute (called on foo.attr = value when foo is an
278 # instance of class cls).
279 def __setattr__(cls, attr, value):
280 # normal processing for private attributes
281 if attr.startswith('_'):
282 type.__setattr__(cls, attr, value)
283 return
284
285 if cls.keywords.has_key(attr):
286 cls._set_keyword(attr, value, cls.keywords[attr])
287 return
288
289 if cls._ports.has_key(attr):
290 cls._cls_get_port_ref(attr).connect(value)
291 return
292
293 if isSimObjectOrSequence(value) and cls._instantiated:
294 raise RuntimeError, \
295 "cannot set SimObject parameter '%s' after\n" \
296 " class %s has been instantiated or subclassed" \
297 % (attr, cls.__name__)
298
299 # check for param
300 param = cls._params.get(attr)
301 if param:
302 cls._set_param(attr, value, param)
303 return
304
305 if isSimObjectOrSequence(value):
306 # If RHS is a SimObject, it's an implicit child assignment.
307 # Classes don't have children, so we just put this object
308 # in _values; later, each instance will do a 'setattr(self,
309 # attr, _values[attr])' in SimObject.__init__ which will
310 # add this object as a child.
311 cls._values[attr] = value
312 return
313
314 # no valid assignment... raise exception
315 raise AttributeError, \
316 "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
317
318 def __getattr__(cls, attr):
319 if cls._values.has_key(attr):
320 return cls._values[attr]
321
322 raise AttributeError, \
323 "object '%s' has no attribute '%s'" % (cls.__name__, attr)
324
325 def __str__(cls):
326 return cls.__name__
327
328 def cxx_decl(cls):
329 code = "#ifndef __PARAMS__%s\n" % cls
330 code += "#define __PARAMS__%s\n\n" % cls
331
332 # The 'dict' attribute restricts us to the params declared in
333 # the object itself, not including inherited params (which
334 # will also be inherited from the base class's param struct
335 # here).
336 params = cls._params.local.values()
337 try:
338 ptypes = [p.ptype for p in params]
339 except:
340 print cls, p, p.ptype_str
341 print params
342 raise
343
344 # get a list of lists of predeclaration lines
345 predecls = []
346 predecls.extend(cls.cxx_predecls)
347 for p in params:
348 predecls.extend(p.cxx_predecls())
349 # remove redundant lines
350 predecls2 = []
351 for pd in predecls:
352 if pd not in predecls2:
353 predecls2.append(pd)
354 predecls2.sort()
355 code += "\n".join(predecls2)
356 code += "\n\n";
357
358 if cls._base:
359 code += '#include "params/%s.hh"\n\n' % cls._base.type
360
361 for ptype in ptypes:
362 if issubclass(ptype, Enum):
363 code += '#include "enums/%s.hh"\n' % ptype.__name__
364 code += "\n\n"
365
366 code += cls.cxx_struct(cls._base, params)
367
368 # close #ifndef __PARAMS__* guard
369 code += "\n#endif\n"
370 return code
371
372 def cxx_struct(cls, base, params):
373 if cls == SimObject:
374 return '#include "sim/sim_object_params.hh"\n'
375
376 # now generate the actual param struct
377 code = "struct %sParams" % cls
378 if base:
379 code += " : public %sParams" % base.type
380 code += "\n{\n"
381 if not hasattr(cls, 'abstract') or not cls.abstract:
382 if 'type' in cls.__dict__:
383 code += " %s create();\n" % cls.cxx_type
384 decls = [p.cxx_decl() for p in params]
385 decls.sort()
386 code += "".join([" %s\n" % d for d in decls])
387 code += "};\n"
388
389 return code
390
391 def swig_decl(cls):
392 code = '%%module %s\n' % cls
393
394 code += '%{\n'
395 code += '#include "params/%s.hh"\n' % cls
396 code += '%}\n\n'
397
398 # The 'dict' attribute restricts us to the params declared in
399 # the object itself, not including inherited params (which
400 # will also be inherited from the base class's param struct
401 # here).
402 params = cls._params.local.values()
403 ptypes = [p.ptype for p in params]
404
405 # get a list of lists of predeclaration lines
406 predecls = []
407 predecls.extend([ p.swig_predecls() for p in params ])
408 # flatten
409 predecls = reduce(lambda x,y:x+y, predecls, [])
410 # remove redundant lines
411 predecls2 = []
412 for pd in predecls:
413 if pd not in predecls2:
414 predecls2.append(pd)
415 predecls2.sort()
416 code += "\n".join(predecls2)
417 code += "\n\n";
418
419 if cls._base:
420 code += '%%import "params/%s.i"\n\n' % cls._base.type
421
422 for ptype in ptypes:
423 if issubclass(ptype, Enum):
424 code += '%%import "enums/%s.hh"\n' % ptype.__name__
425 code += "\n\n"
426
427 code += '%%import "params/%s_type.hh"\n\n' % cls
428 code += '%%include "params/%s.hh"\n\n' % cls
429
430 return code
431
432# The SimObject class is the root of the special hierarchy. Most of
433# the code in this class deals with the configuration hierarchy itself
434# (parent/child node relationships).
435class SimObject(object):
436 # Specify metaclass. Any class inheriting from SimObject will
437 # get this metaclass.
438 __metaclass__ = MetaSimObject
439 type = 'SimObject'
440 abstract = True
441
442 swig_objdecls = [ '%include "python/swig/sim_object.i"' ]
443
444 # Initialize new instance. For objects with SimObject-valued
445 # children, we need to recursively clone the classes represented
446 # by those param values as well in a consistent "deep copy"-style
447 # fashion. That is, we want to make sure that each instance is
448 # cloned only once, and that if there are multiple references to
449 # the same original object, we end up with the corresponding
450 # cloned references all pointing to the same cloned instance.
451 def __init__(self, **kwargs):
452 ancestor = kwargs.get('_ancestor')
453 memo_dict = kwargs.get('_memo')
454 if memo_dict is None:
455 # prepare to memoize any recursively instantiated objects
456 memo_dict = {}
457 elif ancestor:
458 # memoize me now to avoid problems with recursive calls
459 memo_dict[ancestor] = self
460
461 if not ancestor:
462 ancestor = self.__class__
463 ancestor._instantiated = True
464
465 # initialize required attributes
466 self._parent = None
467 self._children = {}
468 self._ccObject = None # pointer to C++ object
469 self._ccParams = None
470 self._instantiated = False # really "cloned"
471
472 # Inherit parameter values from class using multidict so
473 # individual value settings can be overridden.
474 self._values = multidict(ancestor._values)
475 # clone SimObject-valued parameters
476 for key,val in ancestor._values.iteritems():
477 if isSimObject(val):
478 setattr(self, key, val(_memo=memo_dict))
479 elif isSimObjectSequence(val) and len(val):
480 setattr(self, key, [ v(_memo=memo_dict) for v in val ])
481 # clone port references. no need to use a multidict here
482 # since we will be creating new references for all ports.
483 self._port_refs = {}
484 for key,val in ancestor._port_refs.iteritems():
485 self._port_refs[key] = val.clone(self, memo_dict)
486 # apply attribute assignments from keyword args, if any
487 for key,val in kwargs.iteritems():
488 setattr(self, key, val)
489
490 # "Clone" the current instance by creating another instance of
491 # this instance's class, but that inherits its parameter values
492 # and port mappings from the current instance. If we're in a
493 # "deep copy" recursive clone, check the _memo dict to see if
494 # we've already cloned this instance.
495 def __call__(self, **kwargs):
496 memo_dict = kwargs.get('_memo')
497 if memo_dict is None:
498 # no memo_dict: must be top-level clone operation.
499 # this is only allowed at the root of a hierarchy
500 if self._parent:
501 raise RuntimeError, "attempt to clone object %s " \
502 "not at the root of a tree (parent = %s)" \
503 % (self, self._parent)
504 # create a new dict and use that.
505 memo_dict = {}
506 kwargs['_memo'] = memo_dict
507 elif memo_dict.has_key(self):
508 # clone already done & memoized
509 return memo_dict[self]
510 return self.__class__(_ancestor = self, **kwargs)
511
512 def _get_port_ref(self, attr):
513 # Return reference that can be assigned to another port
514 # via __setattr__. There is only ever one reference
515 # object per port, but we create them lazily here.
516 ref = self._port_refs.get(attr)
517 if not ref:
518 ref = self._ports[attr].makeRef(self)
519 self._port_refs[attr] = ref
520 return ref
521
522 def __getattr__(self, attr):
523 if self._ports.has_key(attr):
524 return self._get_port_ref(attr)
525
526 if self._values.has_key(attr):
527 return self._values[attr]
528
529 raise AttributeError, "object '%s' has no attribute '%s'" \
530 % (self.__class__.__name__, attr)
531
532 # Set attribute (called on foo.attr = value when foo is an
533 # instance of class cls).
534 def __setattr__(self, attr, value):
535 # normal processing for private attributes
536 if attr.startswith('_'):
537 object.__setattr__(self, attr, value)
538 return
539
540 if self._ports.has_key(attr):
541 # set up port connection
542 self._get_port_ref(attr).connect(value)
543 return
544
545 if isSimObjectOrSequence(value) and self._instantiated:
546 raise RuntimeError, \
547 "cannot set SimObject parameter '%s' after\n" \
548 " instance been cloned %s" % (attr, `self`)
549
550 # must be SimObject param
551 param = self._params.get(attr)
552 if param:
553 try:
554 value = param.convert(value)
555 except Exception, e:
556 msg = "%s\nError setting param %s.%s to %s\n" % \
557 (e, self.__class__.__name__, attr, value)
558 e.args = (msg, )
559 raise
560 self._set_child(attr, value)
561 return
562
563 if isSimObjectOrSequence(value):
564 self._set_child(attr, value)
565 return
566
567 # no valid assignment... raise exception
568 raise AttributeError, "Class %s has no parameter %s" \
569 % (self.__class__.__name__, attr)
570
571
572 # this hack allows tacking a '[0]' onto parameters that may or may
573 # not be vectors, and always getting the first element (e.g. cpus)
574 def __getitem__(self, key):
575 if key == 0:
576 return self
577 raise TypeError, "Non-zero index '%s' to SimObject" % key
578
579 # clear out children with given name, even if it's a vector
580 def clear_child(self, name):
581 if not self._children.has_key(name):
582 return
583 child = self._children[name]
584 if isinstance(child, SimObjVector):
585 for i in xrange(len(child)):
586 del self._children["s%d" % (name, i)]
587 del self._children[name]
588
589 def add_child(self, name, value):
590 self._children[name] = value
591
592 def _maybe_set_parent(self, parent, name):
593 if not self._parent:
594 self._parent = parent
595 self._name = name
596 parent.add_child(name, self)
597
598 def _set_child(self, attr, value):
599 # if RHS is a SimObject, it's an implicit child assignment
600 # clear out old child with this name, if any
601 self.clear_child(attr)
602
603 if isSimObject(value):
604 value._maybe_set_parent(self, attr)
605 elif isSimObjectSequence(value):
606 value = SimObjVector(value)
607 if len(value) == 1:
608 value[0]._maybe_set_parent(self, attr)
609 else:
610 width = int(math.ceil(math.log(len(value))/math.log(10)))
611 for i,v in enumerate(value):
612 v._maybe_set_parent(self, "%s%0*d" % (attr, width, i))
613
614 self._values[attr] = value
615
616 def path(self):
617 if not self._parent:
618 return 'root'
619 ppath = self._parent.path()
620 if ppath == 'root':
621 return self._name
622 return ppath + "." + self._name
623
624 def __str__(self):
625 return self.path()
626
627 def ini_str(self):
628 return self.path()
629
630 def find_any(self, ptype):
631 if isinstance(self, ptype):
632 return self, True
633
634 found_obj = None
635 for child in self._children.itervalues():
636 if isinstance(child, ptype):
637 if found_obj != None and child != found_obj:
638 raise AttributeError, \
639 'parent.any matched more than one: %s %s' % \
640 (found_obj.path, child.path)
641 found_obj = child
642 # search param space
643 for pname,pdesc in self._params.iteritems():
644 if issubclass(pdesc.ptype, ptype):
645 match_obj = self._values[pname]
646 if found_obj != None and found_obj != match_obj:
647 raise AttributeError, \
648 'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path)
649 found_obj = match_obj
650 return found_obj, found_obj != None
651
652 def unproxy(self, base):
653 return self
654
655 def unproxy_all(self):
656 for param in self._params.iterkeys():
657 value = self._values.get(param)
658 if value != None and isproxy(value):
659 try:
660 value = value.unproxy(self)
661 except:
662 print "Error in unproxying param '%s' of %s" % \
663 (param, self.path())
664 raise
665 setattr(self, param, value)
666
667 # Unproxy ports in sorted order so that 'append' operations on
668 # vector ports are done in a deterministic fashion.
669 port_names = self._ports.keys()
670 port_names.sort()
671 for port_name in port_names:
672 port = self._port_refs.get(port_name)
673 if port != None:
674 port.unproxy(self)
675
676 # Unproxy children in sorted order for determinism also.
677 child_names = self._children.keys()
678 child_names.sort()
679 for child in child_names:
680 self._children[child].unproxy_all()
681
682 def print_ini(self, ini_file):
683 print >>ini_file, '[' + self.path() + ']' # .ini section header
684
685 instanceDict[self.path()] = self
686
687 if hasattr(self, 'type'):
688 print >>ini_file, 'type=%s' % self.type
689
690 child_names = self._children.keys()
691 child_names.sort()
692 if len(child_names):
693 print >>ini_file, 'children=%s' % ' '.join(child_names)
694
695 param_names = self._params.keys()
696 param_names.sort()
697 for param in param_names:
698 value = self._values.get(param)
699 if value != None:
700 print >>ini_file, '%s=%s' % (param,
701 self._values[param].ini_str())
702
703 port_names = self._ports.keys()
704 port_names.sort()
705 for port_name in port_names:
706 port = self._port_refs.get(port_name, None)
707 if port != None:
708 print >>ini_file, '%s=%s' % (port_name, port.ini_str())
709
710 print >>ini_file # blank line between objects
711
712 for child in child_names:
713 self._children[child].print_ini(ini_file)
714
715 def getCCParams(self):
716 if self._ccParams:
717 return self._ccParams
718
719 cc_params_struct = getattr(m5.objects.params, '%sParams' % self.type)
720 cc_params = cc_params_struct()
721 cc_params.pyobj = self
722 cc_params.name = str(self)
723
724 param_names = self._params.keys()
725 param_names.sort()
726 for param in param_names:
727 value = self._values.get(param)
728 if value is None:
729 fatal("%s.%s without default or user set value",
730 self.path(), param)
731
732 value = value.getValue()
733 if isinstance(self._params[param], VectorParamDesc):
734 assert isinstance(value, list)
735 vec = getattr(cc_params, param)
736 assert not len(vec)
737 for v in value:
738 vec.append(v)
739 else:
740 setattr(cc_params, param, value)
741
742 port_names = self._ports.keys()
743 port_names.sort()
744 for port_name in port_names:
745 port = self._port_refs.get(port_name, None)
746 if port != None:
747 setattr(cc_params, port_name, port)
748 self._ccParams = cc_params
749 return self._ccParams
750
751 # Get C++ object corresponding to this object, calling C++ if
752 # necessary to construct it. Does *not* recursively create
753 # children.
754 def getCCObject(self):
755 if not self._ccObject:
756 # Cycles in the configuration heirarchy are not supported. This
757 # will catch the resulting recursion and stop.
758 self._ccObject = -1
759 params = self.getCCParams()
760 self._ccObject = params.create()
761 elif self._ccObject == -1:
762 raise RuntimeError, "%s: Cycle found in configuration heirarchy." \
763 % self.path()
764 return self._ccObject
765
766 # Call C++ to create C++ object corresponding to this object and
767 # (recursively) all its children
768 def createCCObject(self):
769 self.getCCParams()
770 self.getCCObject() # force creation
771 for child in self._children.itervalues():
772 child.createCCObject()
773
774 def getValue(self):
775 return self.getCCObject()
776
777 # Create C++ port connections corresponding to the connections in
778 # _port_refs (& recursively for all children)
779 def connectPorts(self):
780 for portRef in self._port_refs.itervalues():
781 portRef.ccConnect()
782 for child in self._children.itervalues():
783 child.connectPorts()
784
785 def startDrain(self, drain_event, recursive):
786 count = 0
787 if isinstance(self, SimObject):
788 count += self._ccObject.drain(drain_event)
789 if recursive:
790 for child in self._children.itervalues():
791 count += child.startDrain(drain_event, True)
792 return count
793
794 def resume(self):
795 if isinstance(self, SimObject):
796 self._ccObject.resume()
797 for child in self._children.itervalues():
798 child.resume()
799
800 def getMemoryMode(self):
801 if not isinstance(self, m5.objects.System):
802 return None
803
804 return self._ccObject.getMemoryMode()
805
806 def changeTiming(self, mode):
807 if isinstance(self, m5.objects.System):
808 # i don't know if there's a better way to do this - calling
809 # setMemoryMode directly from self._ccObject results in calling
810 # SimObject::setMemoryMode, not the System::setMemoryMode
811 self._ccObject.setMemoryMode(mode)
812 for child in self._children.itervalues():
813 child.changeTiming(mode)
814
815 def takeOverFrom(self, old_cpu):
816 self._ccObject.takeOverFrom(old_cpu._ccObject)
817
818 # generate output file for 'dot' to display as a pretty graph.
819 # this code is currently broken.
820 def outputDot(self, dot):
821 label = "{%s|" % self.path
822 if isSimObject(self.realtype):
823 label += '%s|' % self.type
824
825 if self.children:
826 # instantiate children in same order they were added for
827 # backward compatibility (else we can end up with cpu1
828 # before cpu0).
829 for c in self.children:
830 dot.add_edge(pydot.Edge(self.path,c.path, style="bold"))
831
832 simobjs = []
833 for param in self.params:
834 try:
835 if param.value is None:
836 raise AttributeError, 'Parameter with no value'
837
838 value = param.value
839 string = param.string(value)
840 except Exception, e:
841 msg = 'exception in %s:%s\n%s' % (self.name, param.name, e)
842 e.args = (msg, )
843 raise
844
845 if isSimObject(param.ptype) and string != "Null":
846 simobjs.append(string)
847 else:
848 label += '%s = %s\\n' % (param.name, string)
849
850 for so in simobjs:
851 label += "|<%s> %s" % (so, so)
852 dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so,
853 tailport="w"))
854 label += '}'
855 dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label))
856
857 # recursively dump out children
858 for c in self.children:
859 c.outputDot(dot)
860
861# Function to provide to C++ so it can look up instances based on paths
862def resolveSimObject(name):
863 obj = instanceDict[name]
864 return obj.getCCObject()
865
866def isSimObject(value):
867 return isinstance(value, SimObject)
868
869def isSimObjectClass(value):
870 return issubclass(value, SimObject)
871
872def isSimObjectSequence(value):
873 if not isinstance(value, (list, tuple)) or len(value) == 0:
874 return False
875
876 for val in value:
877 if not isNullPointer(val) and not isSimObject(val):
878 return False
879
880 return True
881
882def isSimObjectOrSequence(value):
883 return isSimObject(value) or isSimObjectSequence(value)
884
885baseClasses = allClasses.copy()
886baseInstances = instanceDict.copy()
887
888def clear():
889 global allClasses, instanceDict
890
891 allClasses = baseClasses.copy()
892 instanceDict = baseInstances.copy()
893
894# __all__ defines the list of symbols that get exported when
895# 'from config import *' is invoked. Try to keep this reasonably
896# short to avoid polluting other namespaces.
897__all__ = [ 'SimObject' ]
238 val = classmethod(val)
239 type.__setattr__(cls, keyword, val)
240
241 def _new_param(cls, name, pdesc):
242 # each param desc should be uniquely assigned to one variable
243 assert(not hasattr(pdesc, 'name'))
244 pdesc.name = name
245 cls._params[name] = pdesc
246 if hasattr(pdesc, 'default'):
247 cls._set_param(name, pdesc.default, pdesc)
248
249 def _set_param(cls, name, value, param):
250 assert(param.name == name)
251 try:
252 cls._values[name] = param.convert(value)
253 except Exception, e:
254 msg = "%s\nError setting param %s.%s to %s\n" % \
255 (e, cls.__name__, name, value)
256 e.args = (msg, )
257 raise
258
259 def _new_port(cls, name, port):
260 # each port should be uniquely assigned to one variable
261 assert(not hasattr(port, 'name'))
262 port.name = name
263 cls._ports[name] = port
264 if hasattr(port, 'default'):
265 cls._cls_get_port_ref(name).connect(port.default)
266
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)
273 if not ref:
274 ref = cls._ports[attr].makeRef(cls)
275 cls._port_refs[attr] = ref
276 return ref
277
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)
284 return
285
286 if cls.keywords.has_key(attr):
287 cls._set_keyword(attr, value, cls.keywords[attr])
288 return
289
290 if cls._ports.has_key(attr):
291 cls._cls_get_port_ref(attr).connect(value)
292 return
293
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__)
299
300 # check for param
301 param = cls._params.get(attr)
302 if param:
303 cls._set_param(attr, value, param)
304 return
305
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
313 return
314
315 # no valid assignment... raise exception
316 raise AttributeError, \
317 "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
318
319 def __getattr__(cls, attr):
320 if cls._values.has_key(attr):
321 return cls._values[attr]
322
323 raise AttributeError, \
324 "object '%s' has no attribute '%s'" % (cls.__name__, attr)
325
326 def __str__(cls):
327 return cls.__name__
328
329 def cxx_decl(cls):
330 code = "#ifndef __PARAMS__%s\n" % cls
331 code += "#define __PARAMS__%s\n\n" % cls
332
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
336 # here).
337 params = cls._params.local.values()
338 try:
339 ptypes = [p.ptype for p in params]
340 except:
341 print cls, p, p.ptype_str
342 print params
343 raise
344
345 # get a list of lists of predeclaration lines
346 predecls = []
347 predecls.extend(cls.cxx_predecls)
348 for p in params:
349 predecls.extend(p.cxx_predecls())
350 # remove redundant lines
351 predecls2 = []
352 for pd in predecls:
353 if pd not in predecls2:
354 predecls2.append(pd)
355 predecls2.sort()
356 code += "\n".join(predecls2)
357 code += "\n\n";
358
359 if cls._base:
360 code += '#include "params/%s.hh"\n\n' % cls._base.type
361
362 for ptype in ptypes:
363 if issubclass(ptype, Enum):
364 code += '#include "enums/%s.hh"\n' % ptype.__name__
365 code += "\n\n"
366
367 code += cls.cxx_struct(cls._base, params)
368
369 # close #ifndef __PARAMS__* guard
370 code += "\n#endif\n"
371 return code
372
373 def cxx_struct(cls, base, params):
374 if cls == SimObject:
375 return '#include "sim/sim_object_params.hh"\n'
376
377 # now generate the actual param struct
378 code = "struct %sParams" % cls
379 if base:
380 code += " : public %sParams" % base.type
381 code += "\n{\n"
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]
386 decls.sort()
387 code += "".join([" %s\n" % d for d in decls])
388 code += "};\n"
389
390 return code
391
392 def swig_decl(cls):
393 code = '%%module %s\n' % cls
394
395 code += '%{\n'
396 code += '#include "params/%s.hh"\n' % cls
397 code += '%}\n\n'
398
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
402 # here).
403 params = cls._params.local.values()
404 ptypes = [p.ptype for p in params]
405
406 # get a list of lists of predeclaration lines
407 predecls = []
408 predecls.extend([ p.swig_predecls() for p in params ])
409 # flatten
410 predecls = reduce(lambda x,y:x+y, predecls, [])
411 # remove redundant lines
412 predecls2 = []
413 for pd in predecls:
414 if pd not in predecls2:
415 predecls2.append(pd)
416 predecls2.sort()
417 code += "\n".join(predecls2)
418 code += "\n\n";
419
420 if cls._base:
421 code += '%%import "params/%s.i"\n\n' % cls._base.type
422
423 for ptype in ptypes:
424 if issubclass(ptype, Enum):
425 code += '%%import "enums/%s.hh"\n' % ptype.__name__
426 code += "\n\n"
427
428 code += '%%import "params/%s_type.hh"\n\n' % cls
429 code += '%%include "params/%s.hh"\n\n' % cls
430
431 return code
432
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).
436class SimObject(object):
437 # Specify metaclass. Any class inheriting from SimObject will
438 # get this metaclass.
439 __metaclass__ = MetaSimObject
440 type = 'SimObject'
441 abstract = True
442
443 swig_objdecls = [ '%include "python/swig/sim_object.i"' ]
444
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
457 memo_dict = {}
458 elif ancestor:
459 # memoize me now to avoid problems with recursive calls
460 memo_dict[ancestor] = self
461
462 if not ancestor:
463 ancestor = self.__class__
464 ancestor._instantiated = True
465
466 # initialize required attributes
467 self._parent = None
468 self._children = {}
469 self._ccObject = None # pointer to C++ object
470 self._ccParams = None
471 self._instantiated = False # really "cloned"
472
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():
478 if isSimObject(val):
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.
484 self._port_refs = {}
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)
490
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
501 if self._parent:
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.
506 memo_dict = {}
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)
512
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)
518 if not ref:
519 ref = self._ports[attr].makeRef(self)
520 self._port_refs[attr] = ref
521 return ref
522
523 def __getattr__(self, attr):
524 if self._ports.has_key(attr):
525 return self._get_port_ref(attr)
526
527 if self._values.has_key(attr):
528 return self._values[attr]
529
530 raise AttributeError, "object '%s' has no attribute '%s'" \
531 % (self.__class__.__name__, attr)
532
533 # Set attribute (called on foo.attr = value when foo is an
534 # instance of class cls).
535 def __setattr__(self, attr, value):
536 # normal processing for private attributes
537 if attr.startswith('_'):
538 object.__setattr__(self, attr, value)
539 return
540
541 if self._ports.has_key(attr):
542 # set up port connection
543 self._get_port_ref(attr).connect(value)
544 return
545
546 if isSimObjectOrSequence(value) and self._instantiated:
547 raise RuntimeError, \
548 "cannot set SimObject parameter '%s' after\n" \
549 " instance been cloned %s" % (attr, `self`)
550
551 # must be SimObject param
552 param = self._params.get(attr)
553 if param:
554 try:
555 value = param.convert(value)
556 except Exception, e:
557 msg = "%s\nError setting param %s.%s to %s\n" % \
558 (e, self.__class__.__name__, attr, value)
559 e.args = (msg, )
560 raise
561 self._set_child(attr, value)
562 return
563
564 if isSimObjectOrSequence(value):
565 self._set_child(attr, value)
566 return
567
568 # no valid assignment... raise exception
569 raise AttributeError, "Class %s has no parameter %s" \
570 % (self.__class__.__name__, attr)
571
572
573 # this hack allows tacking a '[0]' onto parameters that may or may
574 # not be vectors, and always getting the first element (e.g. cpus)
575 def __getitem__(self, key):
576 if key == 0:
577 return self
578 raise TypeError, "Non-zero index '%s' to SimObject" % key
579
580 # clear out children with given name, even if it's a vector
581 def clear_child(self, name):
582 if not self._children.has_key(name):
583 return
584 child = self._children[name]
585 if isinstance(child, SimObjVector):
586 for i in xrange(len(child)):
587 del self._children["s%d" % (name, i)]
588 del self._children[name]
589
590 def add_child(self, name, value):
591 self._children[name] = value
592
593 def _maybe_set_parent(self, parent, name):
594 if not self._parent:
595 self._parent = parent
596 self._name = name
597 parent.add_child(name, self)
598
599 def _set_child(self, attr, value):
600 # if RHS is a SimObject, it's an implicit child assignment
601 # clear out old child with this name, if any
602 self.clear_child(attr)
603
604 if isSimObject(value):
605 value._maybe_set_parent(self, attr)
606 elif isSimObjectSequence(value):
607 value = SimObjVector(value)
608 if len(value) == 1:
609 value[0]._maybe_set_parent(self, attr)
610 else:
611 width = int(math.ceil(math.log(len(value))/math.log(10)))
612 for i,v in enumerate(value):
613 v._maybe_set_parent(self, "%s%0*d" % (attr, width, i))
614
615 self._values[attr] = value
616
617 def path(self):
618 if not self._parent:
619 return 'root'
620 ppath = self._parent.path()
621 if ppath == 'root':
622 return self._name
623 return ppath + "." + self._name
624
625 def __str__(self):
626 return self.path()
627
628 def ini_str(self):
629 return self.path()
630
631 def find_any(self, ptype):
632 if isinstance(self, ptype):
633 return self, True
634
635 found_obj = None
636 for child in self._children.itervalues():
637 if isinstance(child, ptype):
638 if found_obj != None and child != found_obj:
639 raise AttributeError, \
640 'parent.any matched more than one: %s %s' % \
641 (found_obj.path, child.path)
642 found_obj = child
643 # search param space
644 for pname,pdesc in self._params.iteritems():
645 if issubclass(pdesc.ptype, ptype):
646 match_obj = self._values[pname]
647 if found_obj != None and found_obj != match_obj:
648 raise AttributeError, \
649 'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path)
650 found_obj = match_obj
651 return found_obj, found_obj != None
652
653 def unproxy(self, base):
654 return self
655
656 def unproxy_all(self):
657 for param in self._params.iterkeys():
658 value = self._values.get(param)
659 if value != None and isproxy(value):
660 try:
661 value = value.unproxy(self)
662 except:
663 print "Error in unproxying param '%s' of %s" % \
664 (param, self.path())
665 raise
666 setattr(self, param, value)
667
668 # Unproxy ports in sorted order so that 'append' operations on
669 # vector ports are done in a deterministic fashion.
670 port_names = self._ports.keys()
671 port_names.sort()
672 for port_name in port_names:
673 port = self._port_refs.get(port_name)
674 if port != None:
675 port.unproxy(self)
676
677 # Unproxy children in sorted order for determinism also.
678 child_names = self._children.keys()
679 child_names.sort()
680 for child in child_names:
681 self._children[child].unproxy_all()
682
683 def print_ini(self, ini_file):
684 print >>ini_file, '[' + self.path() + ']' # .ini section header
685
686 instanceDict[self.path()] = self
687
688 if hasattr(self, 'type'):
689 print >>ini_file, 'type=%s' % self.type
690
691 child_names = self._children.keys()
692 child_names.sort()
693 if len(child_names):
694 print >>ini_file, 'children=%s' % ' '.join(child_names)
695
696 param_names = self._params.keys()
697 param_names.sort()
698 for param in param_names:
699 value = self._values.get(param)
700 if value != None:
701 print >>ini_file, '%s=%s' % (param,
702 self._values[param].ini_str())
703
704 port_names = self._ports.keys()
705 port_names.sort()
706 for port_name in port_names:
707 port = self._port_refs.get(port_name, None)
708 if port != None:
709 print >>ini_file, '%s=%s' % (port_name, port.ini_str())
710
711 print >>ini_file # blank line between objects
712
713 for child in child_names:
714 self._children[child].print_ini(ini_file)
715
716 def getCCParams(self):
717 if self._ccParams:
718 return self._ccParams
719
720 cc_params_struct = getattr(m5.objects.params, '%sParams' % self.type)
721 cc_params = cc_params_struct()
722 cc_params.pyobj = self
723 cc_params.name = str(self)
724
725 param_names = self._params.keys()
726 param_names.sort()
727 for param in param_names:
728 value = self._values.get(param)
729 if value is None:
730 fatal("%s.%s without default or user set value",
731 self.path(), param)
732
733 value = value.getValue()
734 if isinstance(self._params[param], VectorParamDesc):
735 assert isinstance(value, list)
736 vec = getattr(cc_params, param)
737 assert not len(vec)
738 for v in value:
739 vec.append(v)
740 else:
741 setattr(cc_params, param, value)
742
743 port_names = self._ports.keys()
744 port_names.sort()
745 for port_name in port_names:
746 port = self._port_refs.get(port_name, None)
747 if port != None:
748 setattr(cc_params, port_name, port)
749 self._ccParams = cc_params
750 return self._ccParams
751
752 # Get C++ object corresponding to this object, calling C++ if
753 # necessary to construct it. Does *not* recursively create
754 # children.
755 def getCCObject(self):
756 if not self._ccObject:
757 # Cycles in the configuration heirarchy are not supported. This
758 # will catch the resulting recursion and stop.
759 self._ccObject = -1
760 params = self.getCCParams()
761 self._ccObject = params.create()
762 elif self._ccObject == -1:
763 raise RuntimeError, "%s: Cycle found in configuration heirarchy." \
764 % self.path()
765 return self._ccObject
766
767 # Call C++ to create C++ object corresponding to this object and
768 # (recursively) all its children
769 def createCCObject(self):
770 self.getCCParams()
771 self.getCCObject() # force creation
772 for child in self._children.itervalues():
773 child.createCCObject()
774
775 def getValue(self):
776 return self.getCCObject()
777
778 # Create C++ port connections corresponding to the connections in
779 # _port_refs (& recursively for all children)
780 def connectPorts(self):
781 for portRef in self._port_refs.itervalues():
782 portRef.ccConnect()
783 for child in self._children.itervalues():
784 child.connectPorts()
785
786 def startDrain(self, drain_event, recursive):
787 count = 0
788 if isinstance(self, SimObject):
789 count += self._ccObject.drain(drain_event)
790 if recursive:
791 for child in self._children.itervalues():
792 count += child.startDrain(drain_event, True)
793 return count
794
795 def resume(self):
796 if isinstance(self, SimObject):
797 self._ccObject.resume()
798 for child in self._children.itervalues():
799 child.resume()
800
801 def getMemoryMode(self):
802 if not isinstance(self, m5.objects.System):
803 return None
804
805 return self._ccObject.getMemoryMode()
806
807 def changeTiming(self, mode):
808 if isinstance(self, m5.objects.System):
809 # i don't know if there's a better way to do this - calling
810 # setMemoryMode directly from self._ccObject results in calling
811 # SimObject::setMemoryMode, not the System::setMemoryMode
812 self._ccObject.setMemoryMode(mode)
813 for child in self._children.itervalues():
814 child.changeTiming(mode)
815
816 def takeOverFrom(self, old_cpu):
817 self._ccObject.takeOverFrom(old_cpu._ccObject)
818
819 # generate output file for 'dot' to display as a pretty graph.
820 # this code is currently broken.
821 def outputDot(self, dot):
822 label = "{%s|" % self.path
823 if isSimObject(self.realtype):
824 label += '%s|' % self.type
825
826 if self.children:
827 # instantiate children in same order they were added for
828 # backward compatibility (else we can end up with cpu1
829 # before cpu0).
830 for c in self.children:
831 dot.add_edge(pydot.Edge(self.path,c.path, style="bold"))
832
833 simobjs = []
834 for param in self.params:
835 try:
836 if param.value is None:
837 raise AttributeError, 'Parameter with no value'
838
839 value = param.value
840 string = param.string(value)
841 except Exception, e:
842 msg = 'exception in %s:%s\n%s' % (self.name, param.name, e)
843 e.args = (msg, )
844 raise
845
846 if isSimObject(param.ptype) and string != "Null":
847 simobjs.append(string)
848 else:
849 label += '%s = %s\\n' % (param.name, string)
850
851 for so in simobjs:
852 label += "|<%s> %s" % (so, so)
853 dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so,
854 tailport="w"))
855 label += '}'
856 dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label))
857
858 # recursively dump out children
859 for c in self.children:
860 c.outputDot(dot)
861
862# Function to provide to C++ so it can look up instances based on paths
863def resolveSimObject(name):
864 obj = instanceDict[name]
865 return obj.getCCObject()
866
867def isSimObject(value):
868 return isinstance(value, SimObject)
869
870def isSimObjectClass(value):
871 return issubclass(value, SimObject)
872
873def isSimObjectSequence(value):
874 if not isinstance(value, (list, tuple)) or len(value) == 0:
875 return False
876
877 for val in value:
878 if not isNullPointer(val) and not isSimObject(val):
879 return False
880
881 return True
882
883def isSimObjectOrSequence(value):
884 return isSimObject(value) or isSimObjectSequence(value)
885
886baseClasses = allClasses.copy()
887baseInstances = instanceDict.copy()
888
889def clear():
890 global allClasses, instanceDict
891
892 allClasses = baseClasses.copy()
893 instanceDict = baseInstances.copy()
894
895# __all__ defines the list of symbols that get exported when
896# 'from config import *' is invoked. Try to keep this reasonably
897# short to avoid polluting other namespaces.
898__all__ = [ 'SimObject' ]