SimObject.py (8459:b8c3c20d0385) SimObject.py (8596:e6e22fa77883)
1# Copyright (c) 2004-2006 The Regents of The University of Michigan
2# Copyright (c) 2010 Advanced Micro Devices, Inc.
3# All rights reserved.
4#
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.
15#
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.
27#
28# Authors: Steve Reinhardt
29# Nathan Binkert
30
31import sys
32from types import FunctionType, MethodType, ModuleType
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, \
49 isNullPointer, SimObjectVector
50
51from m5.proxy import *
52from m5.proxy import isproxy
53
54#####################################################################
55#
56# M5 Python Configuration Utility
57#
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.
63#
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:
73#
74# cache = BaseCache(size='64KB')
75# cache.hit_latency = 3
76# cache.assoc = 8
77#
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.
87#
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.
91#
92#####################################################################
93
94# list of all SimObject classes
95allClasses = {}
96
97# dict to look up SimObjects based on path
98instanceDict = {}
99
1# Copyright (c) 2004-2006 The Regents of The University of Michigan
2# Copyright (c) 2010 Advanced Micro Devices, Inc.
3# All rights reserved.
4#
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.
15#
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.
27#
28# Authors: Steve Reinhardt
29# Nathan Binkert
30
31import sys
32from types import FunctionType, MethodType, ModuleType
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, \
49 isNullPointer, SimObjectVector
50
51from m5.proxy import *
52from m5.proxy import isproxy
53
54#####################################################################
55#
56# M5 Python Configuration Utility
57#
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.
63#
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:
73#
74# cache = BaseCache(size='64KB')
75# cache.hit_latency = 3
76# cache.assoc = 8
77#
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.
87#
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.
91#
92#####################################################################
93
94# list of all SimObject classes
95allClasses = {}
96
97# dict to look up SimObjects based on path
98instanceDict = {}
99
100def default_cxx_predecls(cls, code):
101 code('#include "params/$cls.hh"')
102
103def default_swig_predecls(cls, code):
104 code('%import "python/m5/internal/param_$cls.i"')
105
106def default_swig_objdecls(cls, code):
107 class_path = cls.cxx_class.split('::')
108 classname = class_path[-1]
109 namespaces = class_path[:-1]
110
111 for ns in namespaces:
112 code('namespace $ns {')
113
114 if namespaces:
115 code('// avoid name conflicts')
116 sep_string = '_COLONS_'
117 flat_name = sep_string.join(class_path)
118 code('%rename($flat_name) $classname;')
119
120 code()
121 code('// stop swig from creating/wrapping default ctor/dtor')
122 code('%nodefault $classname;')
123 code('class $classname')
124 if cls._base:
125 code(' : public ${{cls._base.cxx_class}}')
126 code('{};')
127
128 for ns in reversed(namespaces):
129 code('} // namespace $ns')
130
131def public_value(key, value):
132 return key.startswith('_') or \
133 isinstance(value, (FunctionType, MethodType, ModuleType,
134 classmethod, type))
135
136# The metaclass for SimObject. This class controls how new classes
137# that derive from SimObject are instantiated, and provides inherited
138# class behavior (just like a class controls how instances of that
139# class are instantiated, and provides inherited instance behavior).
140class MetaSimObject(type):
141 # Attributes that can be set only at initialization time
142 init_keywords = { 'abstract' : bool,
143 'cxx_class' : str,
144 'cxx_type' : str,
100def public_value(key, value):
101 return key.startswith('_') or \
102 isinstance(value, (FunctionType, MethodType, ModuleType,
103 classmethod, type))
104
105# The metaclass for SimObject. This class controls how new classes
106# that derive from SimObject are instantiated, and provides inherited
107# class behavior (just like a class controls how instances of that
108# class are instantiated, and provides inherited instance behavior).
109class MetaSimObject(type):
110 # Attributes that can be set only at initialization time
111 init_keywords = { 'abstract' : bool,
112 'cxx_class' : str,
113 'cxx_type' : str,
145 'cxx_predecls' : MethodType,
146 'swig_objdecls' : MethodType,
147 'swig_predecls' : MethodType,
148 'type' : str }
149 # Attributes that can be set any time
150 keywords = { 'check' : FunctionType }
151
152 # __new__ is called before __init__, and is where the statements
153 # in the body of the class definition get loaded into the class's
154 # __dict__. We intercept this to filter out parameter & port assignments
155 # and only allow "private" attributes to be passed to the base
156 # __new__ (starting with underscore).
157 def __new__(mcls, name, bases, dict):
158 assert name not in allClasses, "SimObject %s already present" % name
159
160 # Copy "private" attributes, functions, and classes to the
161 # official dict. Everything else goes in _init_dict to be
162 # filtered in __init__.
163 cls_dict = {}
164 value_dict = {}
165 for key,val in dict.items():
166 if public_value(key, val):
167 cls_dict[key] = val
168 else:
169 # must be a param/port setting
170 value_dict[key] = val
171 if 'abstract' not in value_dict:
172 value_dict['abstract'] = False
173 cls_dict['_value_dict'] = value_dict
174 cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict)
175 if 'type' in value_dict:
176 allClasses[name] = cls
177 return cls
178
179 # subclass initialization
180 def __init__(cls, name, bases, dict):
181 # calls type.__init__()... I think that's a no-op, but leave
182 # it here just in case it's not.
183 super(MetaSimObject, cls).__init__(name, bases, dict)
184
185 # initialize required attributes
186
187 # class-only attributes
188 cls._params = multidict() # param descriptions
189 cls._ports = multidict() # port descriptions
190
191 # class or instance attributes
192 cls._values = multidict() # param values
193 cls._children = multidict() # SimObject children
194 cls._port_refs = multidict() # port ref objects
195 cls._instantiated = False # really instantiated, cloned, or subclassed
196
197 # We don't support multiple inheritance. If you want to, you
198 # must fix multidict to deal with it properly.
199 if len(bases) > 1:
200 raise TypeError, "SimObjects do not support multiple inheritance"
201
202 base = bases[0]
203
204 # Set up general inheritance via multidicts. A subclass will
205 # inherit all its settings from the base class. The only time
206 # the following is not true is when we define the SimObject
207 # class itself (in which case the multidicts have no parent).
208 if isinstance(base, MetaSimObject):
209 cls._base = base
210 cls._params.parent = base._params
211 cls._ports.parent = base._ports
212 cls._values.parent = base._values
213 cls._children.parent = base._children
214 cls._port_refs.parent = base._port_refs
215 # mark base as having been subclassed
216 base._instantiated = True
217 else:
218 cls._base = None
219
220 # default keyword values
221 if 'type' in cls._value_dict:
222 if 'cxx_class' not in cls._value_dict:
223 cls._value_dict['cxx_class'] = cls._value_dict['type']
224
225 cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class']
114 'type' : str }
115 # Attributes that can be set any time
116 keywords = { 'check' : FunctionType }
117
118 # __new__ is called before __init__, and is where the statements
119 # in the body of the class definition get loaded into the class's
120 # __dict__. We intercept this to filter out parameter & port assignments
121 # and only allow "private" attributes to be passed to the base
122 # __new__ (starting with underscore).
123 def __new__(mcls, name, bases, dict):
124 assert name not in allClasses, "SimObject %s already present" % name
125
126 # Copy "private" attributes, functions, and classes to the
127 # official dict. Everything else goes in _init_dict to be
128 # filtered in __init__.
129 cls_dict = {}
130 value_dict = {}
131 for key,val in dict.items():
132 if public_value(key, val):
133 cls_dict[key] = val
134 else:
135 # must be a param/port setting
136 value_dict[key] = val
137 if 'abstract' not in value_dict:
138 value_dict['abstract'] = False
139 cls_dict['_value_dict'] = value_dict
140 cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict)
141 if 'type' in value_dict:
142 allClasses[name] = cls
143 return cls
144
145 # subclass initialization
146 def __init__(cls, name, bases, dict):
147 # calls type.__init__()... I think that's a no-op, but leave
148 # it here just in case it's not.
149 super(MetaSimObject, cls).__init__(name, bases, dict)
150
151 # initialize required attributes
152
153 # class-only attributes
154 cls._params = multidict() # param descriptions
155 cls._ports = multidict() # port descriptions
156
157 # class or instance attributes
158 cls._values = multidict() # param values
159 cls._children = multidict() # SimObject children
160 cls._port_refs = multidict() # port ref objects
161 cls._instantiated = False # really instantiated, cloned, or subclassed
162
163 # We don't support multiple inheritance. If you want to, you
164 # must fix multidict to deal with it properly.
165 if len(bases) > 1:
166 raise TypeError, "SimObjects do not support multiple inheritance"
167
168 base = bases[0]
169
170 # Set up general inheritance via multidicts. A subclass will
171 # inherit all its settings from the base class. The only time
172 # the following is not true is when we define the SimObject
173 # class itself (in which case the multidicts have no parent).
174 if isinstance(base, MetaSimObject):
175 cls._base = base
176 cls._params.parent = base._params
177 cls._ports.parent = base._ports
178 cls._values.parent = base._values
179 cls._children.parent = base._children
180 cls._port_refs.parent = base._port_refs
181 # mark base as having been subclassed
182 base._instantiated = True
183 else:
184 cls._base = None
185
186 # default keyword values
187 if 'type' in cls._value_dict:
188 if 'cxx_class' not in cls._value_dict:
189 cls._value_dict['cxx_class'] = cls._value_dict['type']
190
191 cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class']
226
227 if 'cxx_predecls' not in cls.__dict__:
228 m = MethodType(default_cxx_predecls, cls, MetaSimObject)
229 setattr(cls, 'cxx_predecls', m)
230
192
231 if 'swig_predecls' not in cls.__dict__:
232 m = MethodType(default_swig_predecls, cls, MetaSimObject)
233 setattr(cls, 'swig_predecls', m)
234
235 if 'swig_objdecls' not in cls.__dict__:
236 m = MethodType(default_swig_objdecls, cls, MetaSimObject)
237 setattr(cls, 'swig_objdecls', m)
238
239 # Now process the _value_dict items. They could be defining
240 # new (or overriding existing) parameters or ports, setting
241 # class keywords (e.g., 'abstract'), or setting parameter
242 # values or port bindings. The first 3 can only be set when
243 # the class is defined, so we handle them here. The others
244 # can be set later too, so just emulate that by calling
245 # setattr().
246 for key,val in cls._value_dict.items():
247 # param descriptions
248 if isinstance(val, ParamDesc):
249 cls._new_param(key, val)
250
251 # port objects
252 elif isinstance(val, Port):
253 cls._new_port(key, val)
254
255 # init-time-only keywords
256 elif cls.init_keywords.has_key(key):
257 cls._set_keyword(key, val, cls.init_keywords[key])
258
259 # default: use normal path (ends up in __setattr__)
260 else:
261 setattr(cls, key, val)
262
263 def _set_keyword(cls, keyword, val, kwtype):
264 if not isinstance(val, kwtype):
265 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
266 (keyword, type(val), kwtype)
267 if isinstance(val, FunctionType):
268 val = classmethod(val)
269 type.__setattr__(cls, keyword, val)
270
271 def _new_param(cls, name, pdesc):
272 # each param desc should be uniquely assigned to one variable
273 assert(not hasattr(pdesc, 'name'))
274 pdesc.name = name
275 cls._params[name] = pdesc
276 if hasattr(pdesc, 'default'):
277 cls._set_param(name, pdesc.default, pdesc)
278
279 def _set_param(cls, name, value, param):
280 assert(param.name == name)
281 try:
282 value = param.convert(value)
283 except Exception, e:
284 msg = "%s\nError setting param %s.%s to %s\n" % \
285 (e, cls.__name__, name, value)
286 e.args = (msg, )
287 raise
288 cls._values[name] = value
289 # if param value is a SimObject, make it a child too, so that
290 # it gets cloned properly when the class is instantiated
291 if isSimObjectOrVector(value) and not value.has_parent():
292 cls._add_cls_child(name, value)
293
294 def _add_cls_child(cls, name, child):
295 # It's a little funky to have a class as a parent, but these
296 # objects should never be instantiated (only cloned, which
297 # clears the parent pointer), and this makes it clear that the
298 # object is not an orphan and can provide better error
299 # messages.
300 child.set_parent(cls, name)
301 cls._children[name] = child
302
303 def _new_port(cls, name, port):
304 # each port should be uniquely assigned to one variable
305 assert(not hasattr(port, 'name'))
306 port.name = name
307 cls._ports[name] = port
308 if hasattr(port, 'default'):
309 cls._cls_get_port_ref(name).connect(port.default)
310
311 # same as _get_port_ref, effectively, but for classes
312 def _cls_get_port_ref(cls, attr):
313 # Return reference that can be assigned to another port
314 # via __setattr__. There is only ever one reference
315 # object per port, but we create them lazily here.
316 ref = cls._port_refs.get(attr)
317 if not ref:
318 ref = cls._ports[attr].makeRef(cls)
319 cls._port_refs[attr] = ref
320 return ref
321
322 # Set attribute (called on foo.attr = value when foo is an
323 # instance of class cls).
324 def __setattr__(cls, attr, value):
325 # normal processing for private attributes
326 if public_value(attr, value):
327 type.__setattr__(cls, attr, value)
328 return
329
330 if cls.keywords.has_key(attr):
331 cls._set_keyword(attr, value, cls.keywords[attr])
332 return
333
334 if cls._ports.has_key(attr):
335 cls._cls_get_port_ref(attr).connect(value)
336 return
337
338 if isSimObjectOrSequence(value) and cls._instantiated:
339 raise RuntimeError, \
340 "cannot set SimObject parameter '%s' after\n" \
341 " class %s has been instantiated or subclassed" \
342 % (attr, cls.__name__)
343
344 # check for param
345 param = cls._params.get(attr)
346 if param:
347 cls._set_param(attr, value, param)
348 return
349
350 if isSimObjectOrSequence(value):
351 # If RHS is a SimObject, it's an implicit child assignment.
352 cls._add_cls_child(attr, coerceSimObjectOrVector(value))
353 return
354
355 # no valid assignment... raise exception
356 raise AttributeError, \
357 "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
358
359 def __getattr__(cls, attr):
360 if attr == 'cxx_class_path':
361 return cls.cxx_class.split('::')
362
363 if attr == 'cxx_class_name':
364 return cls.cxx_class_path[-1]
365
366 if attr == 'cxx_namespaces':
367 return cls.cxx_class_path[:-1]
368
369 if cls._values.has_key(attr):
370 return cls._values[attr]
371
372 if cls._children.has_key(attr):
373 return cls._children[attr]
374
375 raise AttributeError, \
376 "object '%s' has no attribute '%s'" % (cls.__name__, attr)
377
378 def __str__(cls):
379 return cls.__name__
380
193 # Now process the _value_dict items. They could be defining
194 # new (or overriding existing) parameters or ports, setting
195 # class keywords (e.g., 'abstract'), or setting parameter
196 # values or port bindings. The first 3 can only be set when
197 # the class is defined, so we handle them here. The others
198 # can be set later too, so just emulate that by calling
199 # setattr().
200 for key,val in cls._value_dict.items():
201 # param descriptions
202 if isinstance(val, ParamDesc):
203 cls._new_param(key, val)
204
205 # port objects
206 elif isinstance(val, Port):
207 cls._new_port(key, val)
208
209 # init-time-only keywords
210 elif cls.init_keywords.has_key(key):
211 cls._set_keyword(key, val, cls.init_keywords[key])
212
213 # default: use normal path (ends up in __setattr__)
214 else:
215 setattr(cls, key, val)
216
217 def _set_keyword(cls, keyword, val, kwtype):
218 if not isinstance(val, kwtype):
219 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
220 (keyword, type(val), kwtype)
221 if isinstance(val, FunctionType):
222 val = classmethod(val)
223 type.__setattr__(cls, keyword, val)
224
225 def _new_param(cls, name, pdesc):
226 # each param desc should be uniquely assigned to one variable
227 assert(not hasattr(pdesc, 'name'))
228 pdesc.name = name
229 cls._params[name] = pdesc
230 if hasattr(pdesc, 'default'):
231 cls._set_param(name, pdesc.default, pdesc)
232
233 def _set_param(cls, name, value, param):
234 assert(param.name == name)
235 try:
236 value = param.convert(value)
237 except Exception, e:
238 msg = "%s\nError setting param %s.%s to %s\n" % \
239 (e, cls.__name__, name, value)
240 e.args = (msg, )
241 raise
242 cls._values[name] = value
243 # if param value is a SimObject, make it a child too, so that
244 # it gets cloned properly when the class is instantiated
245 if isSimObjectOrVector(value) and not value.has_parent():
246 cls._add_cls_child(name, value)
247
248 def _add_cls_child(cls, name, child):
249 # It's a little funky to have a class as a parent, but these
250 # objects should never be instantiated (only cloned, which
251 # clears the parent pointer), and this makes it clear that the
252 # object is not an orphan and can provide better error
253 # messages.
254 child.set_parent(cls, name)
255 cls._children[name] = child
256
257 def _new_port(cls, name, port):
258 # each port should be uniquely assigned to one variable
259 assert(not hasattr(port, 'name'))
260 port.name = name
261 cls._ports[name] = port
262 if hasattr(port, 'default'):
263 cls._cls_get_port_ref(name).connect(port.default)
264
265 # same as _get_port_ref, effectively, but for classes
266 def _cls_get_port_ref(cls, attr):
267 # Return reference that can be assigned to another port
268 # via __setattr__. There is only ever one reference
269 # object per port, but we create them lazily here.
270 ref = cls._port_refs.get(attr)
271 if not ref:
272 ref = cls._ports[attr].makeRef(cls)
273 cls._port_refs[attr] = ref
274 return ref
275
276 # Set attribute (called on foo.attr = value when foo is an
277 # instance of class cls).
278 def __setattr__(cls, attr, value):
279 # normal processing for private attributes
280 if public_value(attr, value):
281 type.__setattr__(cls, attr, value)
282 return
283
284 if cls.keywords.has_key(attr):
285 cls._set_keyword(attr, value, cls.keywords[attr])
286 return
287
288 if cls._ports.has_key(attr):
289 cls._cls_get_port_ref(attr).connect(value)
290 return
291
292 if isSimObjectOrSequence(value) and cls._instantiated:
293 raise RuntimeError, \
294 "cannot set SimObject parameter '%s' after\n" \
295 " class %s has been instantiated or subclassed" \
296 % (attr, cls.__name__)
297
298 # check for param
299 param = cls._params.get(attr)
300 if param:
301 cls._set_param(attr, value, param)
302 return
303
304 if isSimObjectOrSequence(value):
305 # If RHS is a SimObject, it's an implicit child assignment.
306 cls._add_cls_child(attr, coerceSimObjectOrVector(value))
307 return
308
309 # no valid assignment... raise exception
310 raise AttributeError, \
311 "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
312
313 def __getattr__(cls, attr):
314 if attr == 'cxx_class_path':
315 return cls.cxx_class.split('::')
316
317 if attr == 'cxx_class_name':
318 return cls.cxx_class_path[-1]
319
320 if attr == 'cxx_namespaces':
321 return cls.cxx_class_path[:-1]
322
323 if cls._values.has_key(attr):
324 return cls._values[attr]
325
326 if cls._children.has_key(attr):
327 return cls._children[attr]
328
329 raise AttributeError, \
330 "object '%s' has no attribute '%s'" % (cls.__name__, attr)
331
332 def __str__(cls):
333 return cls.__name__
334
381 def cxx_decl(cls, code):
382 # The 'dict' attribute restricts us to the params declared in
335 # See ParamValue.cxx_predecls for description.
336 def cxx_predecls(cls, code):
337 code('#include "params/$cls.hh"')
338
339 # See ParamValue.swig_predecls for description.
340 def swig_predecls(cls, code):
341 code('%import "python/m5/internal/param_$cls.i"')
342
343 # Generate the declaration for this object for wrapping with SWIG.
344 # Generates code that goes into a SWIG .i file. Called from
345 # src/SConscript.
346 def swig_decl(cls, code):
347 class_path = cls.cxx_class.split('::')
348 classname = class_path[-1]
349 namespaces = class_path[:-1]
350
351 # The 'local' attribute restricts us to the params declared in
383 # the object itself, not including inherited params (which
384 # will also be inherited from the base class's param struct
385 # here).
386 params = cls._params.local.values()
352 # the object itself, not including inherited params (which
353 # will also be inherited from the base class's param struct
354 # here).
355 params = cls._params.local.values()
356
357 code('%module(package="m5.internal") param_$cls')
358 code()
359 code('%{')
360 code('#include "params/$cls.hh"')
361 for param in params:
362 param.cxx_predecls(code)
363 code('%}')
364 code()
365
366 for param in params:
367 param.swig_predecls(code)
368
369 code()
370 if cls._base:
371 code('%import "python/m5/internal/param_${{cls._base}}.i"')
372 code()
373
374 for ns in namespaces:
375 code('namespace $ns {')
376
377 if namespaces:
378 code('// avoid name conflicts')
379 sep_string = '_COLONS_'
380 flat_name = sep_string.join(class_path)
381 code('%rename($flat_name) $classname;')
382
383 if cls == SimObject:
384 code('%include "python/swig/sim_object.i"')
385 else:
386 code()
387 code('// stop swig from creating/wrapping default ctor/dtor')
388 code('%nodefault $classname;')
389 code('class $classname')
390 if cls._base:
391 code(' : public ${{cls._base.cxx_class}}')
392 code('{};')
393
394 for ns in reversed(namespaces):
395 code('} // namespace $ns')
396
397 code()
398 code('%include "params/$cls.hh"')
399
400
401 # Generate the C++ declaration (.hh file) for this SimObject's
402 # param struct. Called from src/SConscript.
403 def cxx_param_decl(cls, code):
404 # The 'local' attribute restricts us to the params declared in
405 # the object itself, not including inherited params (which
406 # will also be inherited from the base class's param struct
407 # here).
408 params = cls._params.local.values()
387 try:
388 ptypes = [p.ptype for p in params]
389 except:
390 print cls, p, p.ptype_str
391 print params
392 raise
393
394 class_path = cls._value_dict['cxx_class'].split('::')
395
396 code('''\
397#ifndef __PARAMS__${cls}__
398#define __PARAMS__${cls}__
399
400''')
401
402 # A forward class declaration is sufficient since we are just
403 # declaring a pointer.
404 for ns in class_path[:-1]:
405 code('namespace $ns {')
406 code('class $0;', class_path[-1])
407 for ns in reversed(class_path[:-1]):
408 code('} // namespace $ns')
409 code()
410
411 for param in params:
412 param.cxx_predecls(code)
413 code()
414
415 if cls._base:
416 code('#include "params/${{cls._base.type}}.hh"')
417 code()
418
419 for ptype in ptypes:
420 if issubclass(ptype, Enum):
421 code('#include "enums/${{ptype.__name__}}.hh"')
422 code()
423
409 try:
410 ptypes = [p.ptype for p in params]
411 except:
412 print cls, p, p.ptype_str
413 print params
414 raise
415
416 class_path = cls._value_dict['cxx_class'].split('::')
417
418 code('''\
419#ifndef __PARAMS__${cls}__
420#define __PARAMS__${cls}__
421
422''')
423
424 # A forward class declaration is sufficient since we are just
425 # declaring a pointer.
426 for ns in class_path[:-1]:
427 code('namespace $ns {')
428 code('class $0;', class_path[-1])
429 for ns in reversed(class_path[:-1]):
430 code('} // namespace $ns')
431 code()
432
433 for param in params:
434 param.cxx_predecls(code)
435 code()
436
437 if cls._base:
438 code('#include "params/${{cls._base.type}}.hh"')
439 code()
440
441 for ptype in ptypes:
442 if issubclass(ptype, Enum):
443 code('#include "enums/${{ptype.__name__}}.hh"')
444 code()
445
424 cls.cxx_struct(code, cls._base, params)
425
426 code()
427 code('#endif // __PARAMS__${cls}__')
428 return code
429
430 def cxx_struct(cls, code, base, params):
446 # now generate the actual param struct
431 if cls == SimObject:
432 code('#include "sim/sim_object_params.hh"')
447 if cls == SimObject:
448 code('#include "sim/sim_object_params.hh"')
433 return
449 else:
450 code("struct ${cls}Params")
451 if cls._base:
452 code(" : public ${{cls._base.type}}Params")
453 code("{")
454 if not hasattr(cls, 'abstract') or not cls.abstract:
455 if 'type' in cls.__dict__:
456 code(" ${{cls.cxx_type}} create();")
434
457
435 # now generate the actual param struct
436 code("struct ${cls}Params")
437 if base:
438 code(" : public ${{base.type}}Params")
439 code("{")
440 if not hasattr(cls, 'abstract') or not cls.abstract:
441 if 'type' in cls.__dict__:
442 code(" ${{cls.cxx_type}} create();")
458 code.indent()
459 for param in params:
460 param.cxx_decl(code)
461 code.dedent()
462 code('};')
443
463
444 code.indent()
445 for param in params:
446 param.cxx_decl(code)
447 code.dedent()
448 code('};')
449
450 def swig_decl(cls, code):
451 code('''\
452%module $cls
453
454%{
455#include "params/$cls.hh"
456%}
457
458''')
459
460 # The 'dict' attribute restricts us to the params declared in
461 # the object itself, not including inherited params (which
462 # will also be inherited from the base class's param struct
463 # here).
464 params = cls._params.local.values()
465 ptypes = [p.ptype for p in params]
466
467 # get all predeclarations
468 for param in params:
469 param.swig_predecls(code)
470 code()
464 code()
465 code('#endif // __PARAMS__${cls}__')
466 return code
471
467
472 if cls._base:
473 code('%import "python/m5/internal/param_${{cls._base.type}}.i"')
474 code()
475
468
476 for ptype in ptypes:
477 if issubclass(ptype, Enum):
478 code('%import "enums/${{ptype.__name__}}.hh"')
479 code()
480
469
481 code('%import "params/${cls}_type.hh"')
482 code('%include "params/${cls}.hh"')
483
484# The SimObject class is the root of the special hierarchy. Most of
485# the code in this class deals with the configuration hierarchy itself
486# (parent/child node relationships).
487class SimObject(object):
488 # Specify metaclass. Any class inheriting from SimObject will
489 # get this metaclass.
490 __metaclass__ = MetaSimObject
491 type = 'SimObject'
492 abstract = True
493
470# The SimObject class is the root of the special hierarchy. Most of
471# the code in this class deals with the configuration hierarchy itself
472# (parent/child node relationships).
473class SimObject(object):
474 # Specify metaclass. Any class inheriting from SimObject will
475 # get this metaclass.
476 __metaclass__ = MetaSimObject
477 type = 'SimObject'
478 abstract = True
479
494 @classmethod
495 def swig_objdecls(cls, code):
496 code('%include "python/swig/sim_object.i"')
497
498 # Initialize new instance. For objects with SimObject-valued
499 # children, we need to recursively clone the classes represented
500 # by those param values as well in a consistent "deep copy"-style
501 # fashion. That is, we want to make sure that each instance is
502 # cloned only once, and that if there are multiple references to
503 # the same original object, we end up with the corresponding
504 # cloned references all pointing to the same cloned instance.
505 def __init__(self, **kwargs):
506 ancestor = kwargs.get('_ancestor')
507 memo_dict = kwargs.get('_memo')
508 if memo_dict is None:
509 # prepare to memoize any recursively instantiated objects
510 memo_dict = {}
511 elif ancestor:
512 # memoize me now to avoid problems with recursive calls
513 memo_dict[ancestor] = self
514
515 if not ancestor:
516 ancestor = self.__class__
517 ancestor._instantiated = True
518
519 # initialize required attributes
520 self._parent = None
521 self._name = None
522 self._ccObject = None # pointer to C++ object
523 self._ccParams = None
524 self._instantiated = False # really "cloned"
525
526 # Clone children specified at class level. No need for a
527 # multidict here since we will be cloning everything.
528 # Do children before parameter values so that children that
529 # are also param values get cloned properly.
530 self._children = {}
531 for key,val in ancestor._children.iteritems():
532 self.add_child(key, val(_memo=memo_dict))
533
534 # Inherit parameter values from class using multidict so
535 # individual value settings can be overridden but we still
536 # inherit late changes to non-overridden class values.
537 self._values = multidict(ancestor._values)
538 # clone SimObject-valued parameters
539 for key,val in ancestor._values.iteritems():
540 val = tryAsSimObjectOrVector(val)
541 if val is not None:
542 self._values[key] = val(_memo=memo_dict)
543
544 # clone port references. no need to use a multidict here
545 # since we will be creating new references for all ports.
546 self._port_refs = {}
547 for key,val in ancestor._port_refs.iteritems():
548 self._port_refs[key] = val.clone(self, memo_dict)
549 # apply attribute assignments from keyword args, if any
550 for key,val in kwargs.iteritems():
551 setattr(self, key, val)
552
553 # "Clone" the current instance by creating another instance of
554 # this instance's class, but that inherits its parameter values
555 # and port mappings from the current instance. If we're in a
556 # "deep copy" recursive clone, check the _memo dict to see if
557 # we've already cloned this instance.
558 def __call__(self, **kwargs):
559 memo_dict = kwargs.get('_memo')
560 if memo_dict is None:
561 # no memo_dict: must be top-level clone operation.
562 # this is only allowed at the root of a hierarchy
563 if self._parent:
564 raise RuntimeError, "attempt to clone object %s " \
565 "not at the root of a tree (parent = %s)" \
566 % (self, self._parent)
567 # create a new dict and use that.
568 memo_dict = {}
569 kwargs['_memo'] = memo_dict
570 elif memo_dict.has_key(self):
571 # clone already done & memoized
572 return memo_dict[self]
573 return self.__class__(_ancestor = self, **kwargs)
574
575 def _get_port_ref(self, attr):
576 # Return reference that can be assigned to another port
577 # via __setattr__. There is only ever one reference
578 # object per port, but we create them lazily here.
579 ref = self._port_refs.get(attr)
580 if not ref:
581 ref = self._ports[attr].makeRef(self)
582 self._port_refs[attr] = ref
583 return ref
584
585 def __getattr__(self, attr):
586 if self._ports.has_key(attr):
587 return self._get_port_ref(attr)
588
589 if self._values.has_key(attr):
590 return self._values[attr]
591
592 if self._children.has_key(attr):
593 return self._children[attr]
594
595 # If the attribute exists on the C++ object, transparently
596 # forward the reference there. This is typically used for
597 # SWIG-wrapped methods such as init(), regStats(),
598 # regFormulas(), resetStats(), startup(), drain(), and
599 # resume().
600 if self._ccObject and hasattr(self._ccObject, attr):
601 return getattr(self._ccObject, attr)
602
603 raise AttributeError, "object '%s' has no attribute '%s'" \
604 % (self.__class__.__name__, attr)
605
606 # Set attribute (called on foo.attr = value when foo is an
607 # instance of class cls).
608 def __setattr__(self, attr, value):
609 # normal processing for private attributes
610 if attr.startswith('_'):
611 object.__setattr__(self, attr, value)
612 return
613
614 if self._ports.has_key(attr):
615 # set up port connection
616 self._get_port_ref(attr).connect(value)
617 return
618
619 if isSimObjectOrSequence(value) and self._instantiated:
620 raise RuntimeError, \
621 "cannot set SimObject parameter '%s' after\n" \
622 " instance been cloned %s" % (attr, `self`)
623
624 param = self._params.get(attr)
625 if param:
626 try:
627 value = param.convert(value)
628 except Exception, e:
629 msg = "%s\nError setting param %s.%s to %s\n" % \
630 (e, self.__class__.__name__, attr, value)
631 e.args = (msg, )
632 raise
633 self._values[attr] = value
634 # implicitly parent unparented objects assigned as params
635 if isSimObjectOrVector(value) and not value.has_parent():
636 self.add_child(attr, value)
637 return
638
639 # if RHS is a SimObject, it's an implicit child assignment
640 if isSimObjectOrSequence(value):
641 self.add_child(attr, value)
642 return
643
644 # no valid assignment... raise exception
645 raise AttributeError, "Class %s has no parameter %s" \
646 % (self.__class__.__name__, attr)
647
648
649 # this hack allows tacking a '[0]' onto parameters that may or may
650 # not be vectors, and always getting the first element (e.g. cpus)
651 def __getitem__(self, key):
652 if key == 0:
653 return self
654 raise TypeError, "Non-zero index '%s' to SimObject" % key
655
656 # Also implemented by SimObjectVector
657 def clear_parent(self, old_parent):
658 assert self._parent is old_parent
659 self._parent = None
660
661 # Also implemented by SimObjectVector
662 def set_parent(self, parent, name):
663 self._parent = parent
664 self._name = name
665
666 # Also implemented by SimObjectVector
667 def get_name(self):
668 return self._name
669
670 # Also implemented by SimObjectVector
671 def has_parent(self):
672 return self._parent is not None
673
674 # clear out child with given name. This code is not likely to be exercised.
675 # See comment in add_child.
676 def clear_child(self, name):
677 child = self._children[name]
678 child.clear_parent(self)
679 del self._children[name]
680
681 # Add a new child to this object.
682 def add_child(self, name, child):
683 child = coerceSimObjectOrVector(child)
684 if child.has_parent():
685 print "warning: add_child('%s'): child '%s' already has parent" % \
686 (name, child.get_name())
687 if self._children.has_key(name):
688 # This code path had an undiscovered bug that would make it fail
689 # at runtime. It had been here for a long time and was only
690 # exposed by a buggy script. Changes here will probably not be
691 # exercised without specialized testing.
692 self.clear_child(name)
693 child.set_parent(self, name)
694 self._children[name] = child
695
696 # Take SimObject-valued parameters that haven't been explicitly
697 # assigned as children and make them children of the object that
698 # they were assigned to as a parameter value. This guarantees
699 # that when we instantiate all the parameter objects we're still
700 # inside the configuration hierarchy.
701 def adoptOrphanParams(self):
702 for key,val in self._values.iteritems():
703 if not isSimObjectVector(val) and isSimObjectSequence(val):
704 # need to convert raw SimObject sequences to
705 # SimObjectVector class so we can call has_parent()
706 val = SimObjectVector(val)
707 self._values[key] = val
708 if isSimObjectOrVector(val) and not val.has_parent():
709 print "warning: %s adopting orphan SimObject param '%s'" \
710 % (self, key)
711 self.add_child(key, val)
712
713 def path(self):
714 if not self._parent:
715 return '<orphan %s>' % self.__class__
716 ppath = self._parent.path()
717 if ppath == 'root':
718 return self._name
719 return ppath + "." + self._name
720
721 def __str__(self):
722 return self.path()
723
724 def ini_str(self):
725 return self.path()
726
727 def find_any(self, ptype):
728 if isinstance(self, ptype):
729 return self, True
730
731 found_obj = None
732 for child in self._children.itervalues():
733 if isinstance(child, ptype):
734 if found_obj != None and child != found_obj:
735 raise AttributeError, \
736 'parent.any matched more than one: %s %s' % \
737 (found_obj.path, child.path)
738 found_obj = child
739 # search param space
740 for pname,pdesc in self._params.iteritems():
741 if issubclass(pdesc.ptype, ptype):
742 match_obj = self._values[pname]
743 if found_obj != None and found_obj != match_obj:
744 raise AttributeError, \
745 'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path)
746 found_obj = match_obj
747 return found_obj, found_obj != None
748
749 def find_all(self, ptype):
750 all = {}
751 # search children
752 for child in self._children.itervalues():
753 if isinstance(child, ptype) and not isproxy(child) and \
754 not isNullPointer(child):
755 all[child] = True
756 # search param space
757 for pname,pdesc in self._params.iteritems():
758 if issubclass(pdesc.ptype, ptype):
759 match_obj = self._values[pname]
760 if not isproxy(match_obj) and not isNullPointer(match_obj):
761 all[match_obj] = True
762 return all.keys(), True
763
764 def unproxy(self, base):
765 return self
766
767 def unproxyParams(self):
768 for param in self._params.iterkeys():
769 value = self._values.get(param)
770 if value != None and isproxy(value):
771 try:
772 value = value.unproxy(self)
773 except:
774 print "Error in unproxying param '%s' of %s" % \
775 (param, self.path())
776 raise
777 setattr(self, param, value)
778
779 # Unproxy ports in sorted order so that 'append' operations on
780 # vector ports are done in a deterministic fashion.
781 port_names = self._ports.keys()
782 port_names.sort()
783 for port_name in port_names:
784 port = self._port_refs.get(port_name)
785 if port != None:
786 port.unproxy(self)
787
788 def print_ini(self, ini_file):
789 print >>ini_file, '[' + self.path() + ']' # .ini section header
790
791 instanceDict[self.path()] = self
792
793 if hasattr(self, 'type'):
794 print >>ini_file, 'type=%s' % self.type
795
796 child_names = self._children.keys()
797 child_names.sort()
798 if len(child_names):
799 print >>ini_file, 'children=%s' % \
800 ' '.join(self._children[n].get_name() for n in child_names)
801
802 param_names = self._params.keys()
803 param_names.sort()
804 for param in param_names:
805 value = self._values.get(param)
806 if value != None:
807 print >>ini_file, '%s=%s' % (param,
808 self._values[param].ini_str())
809
810 port_names = self._ports.keys()
811 port_names.sort()
812 for port_name in port_names:
813 port = self._port_refs.get(port_name, None)
814 if port != None:
815 print >>ini_file, '%s=%s' % (port_name, port.ini_str())
816
817 print >>ini_file # blank line between objects
818
819 def getCCParams(self):
820 if self._ccParams:
821 return self._ccParams
822
823 cc_params_struct = getattr(m5.internal.params, '%sParams' % self.type)
824 cc_params = cc_params_struct()
825 cc_params.pyobj = self
826 cc_params.name = str(self)
827
828 param_names = self._params.keys()
829 param_names.sort()
830 for param in param_names:
831 value = self._values.get(param)
832 if value is None:
833 fatal("%s.%s without default or user set value",
834 self.path(), param)
835
836 value = value.getValue()
837 if isinstance(self._params[param], VectorParamDesc):
838 assert isinstance(value, list)
839 vec = getattr(cc_params, param)
840 assert not len(vec)
841 for v in value:
842 vec.append(v)
843 else:
844 setattr(cc_params, param, value)
845
846 port_names = self._ports.keys()
847 port_names.sort()
848 for port_name in port_names:
849 port = self._port_refs.get(port_name, None)
850 if port != None:
851 setattr(cc_params, port_name, port)
852 self._ccParams = cc_params
853 return self._ccParams
854
855 # Get C++ object corresponding to this object, calling C++ if
856 # necessary to construct it. Does *not* recursively create
857 # children.
858 def getCCObject(self):
859 if not self._ccObject:
860 # Make sure this object is in the configuration hierarchy
861 if not self._parent and not isRoot(self):
862 raise RuntimeError, "Attempt to instantiate orphan node"
863 # Cycles in the configuration hierarchy are not supported. This
864 # will catch the resulting recursion and stop.
865 self._ccObject = -1
866 params = self.getCCParams()
867 self._ccObject = params.create()
868 elif self._ccObject == -1:
869 raise RuntimeError, "%s: Cycle found in configuration hierarchy." \
870 % self.path()
871 return self._ccObject
872
873 def descendants(self):
874 yield self
875 for child in self._children.itervalues():
876 for obj in child.descendants():
877 yield obj
878
879 # Call C++ to create C++ object corresponding to this object
880 def createCCObject(self):
881 self.getCCParams()
882 self.getCCObject() # force creation
883
884 def getValue(self):
885 return self.getCCObject()
886
887 # Create C++ port connections corresponding to the connections in
888 # _port_refs
889 def connectPorts(self):
890 for portRef in self._port_refs.itervalues():
891 portRef.ccConnect()
892
893 def getMemoryMode(self):
894 if not isinstance(self, m5.objects.System):
895 return None
896
897 return self._ccObject.getMemoryMode()
898
899 def changeTiming(self, mode):
900 if isinstance(self, m5.objects.System):
901 # i don't know if there's a better way to do this - calling
902 # setMemoryMode directly from self._ccObject results in calling
903 # SimObject::setMemoryMode, not the System::setMemoryMode
904 self._ccObject.setMemoryMode(mode)
905
906 def takeOverFrom(self, old_cpu):
907 self._ccObject.takeOverFrom(old_cpu._ccObject)
908
909 # generate output file for 'dot' to display as a pretty graph.
910 # this code is currently broken.
911 def outputDot(self, dot):
912 label = "{%s|" % self.path
913 if isSimObject(self.realtype):
914 label += '%s|' % self.type
915
916 if self.children:
917 # instantiate children in same order they were added for
918 # backward compatibility (else we can end up with cpu1
919 # before cpu0).
920 for c in self.children:
921 dot.add_edge(pydot.Edge(self.path,c.path, style="bold"))
922
923 simobjs = []
924 for param in self.params:
925 try:
926 if param.value is None:
927 raise AttributeError, 'Parameter with no value'
928
929 value = param.value
930 string = param.string(value)
931 except Exception, e:
932 msg = 'exception in %s:%s\n%s' % (self.name, param.name, e)
933 e.args = (msg, )
934 raise
935
936 if isSimObject(param.ptype) and string != "Null":
937 simobjs.append(string)
938 else:
939 label += '%s = %s\\n' % (param.name, string)
940
941 for so in simobjs:
942 label += "|<%s> %s" % (so, so)
943 dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so,
944 tailport="w"))
945 label += '}'
946 dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label))
947
948 # recursively dump out children
949 for c in self.children:
950 c.outputDot(dot)
951
952# Function to provide to C++ so it can look up instances based on paths
953def resolveSimObject(name):
954 obj = instanceDict[name]
955 return obj.getCCObject()
956
957def isSimObject(value):
958 return isinstance(value, SimObject)
959
960def isSimObjectClass(value):
961 return issubclass(value, SimObject)
962
963def isSimObjectVector(value):
964 return isinstance(value, SimObjectVector)
965
966def isSimObjectSequence(value):
967 if not isinstance(value, (list, tuple)) or len(value) == 0:
968 return False
969
970 for val in value:
971 if not isNullPointer(val) and not isSimObject(val):
972 return False
973
974 return True
975
976def isSimObjectOrSequence(value):
977 return isSimObject(value) or isSimObjectSequence(value)
978
979def isRoot(obj):
980 from m5.objects import Root
981 return obj and obj is Root.getInstance()
982
983def isSimObjectOrVector(value):
984 return isSimObject(value) or isSimObjectVector(value)
985
986def tryAsSimObjectOrVector(value):
987 if isSimObjectOrVector(value):
988 return value
989 if isSimObjectSequence(value):
990 return SimObjectVector(value)
991 return None
992
993def coerceSimObjectOrVector(value):
994 value = tryAsSimObjectOrVector(value)
995 if value is None:
996 raise TypeError, "SimObject or SimObjectVector expected"
997 return value
998
999baseClasses = allClasses.copy()
1000baseInstances = instanceDict.copy()
1001
1002def clear():
1003 global allClasses, instanceDict
1004
1005 allClasses = baseClasses.copy()
1006 instanceDict = baseInstances.copy()
1007
1008# __all__ defines the list of symbols that get exported when
1009# 'from config import *' is invoked. Try to keep this reasonably
1010# short to avoid polluting other namespaces.
1011__all__ = [ 'SimObject' ]
480 # Initialize new instance. For objects with SimObject-valued
481 # children, we need to recursively clone the classes represented
482 # by those param values as well in a consistent "deep copy"-style
483 # fashion. That is, we want to make sure that each instance is
484 # cloned only once, and that if there are multiple references to
485 # the same original object, we end up with the corresponding
486 # cloned references all pointing to the same cloned instance.
487 def __init__(self, **kwargs):
488 ancestor = kwargs.get('_ancestor')
489 memo_dict = kwargs.get('_memo')
490 if memo_dict is None:
491 # prepare to memoize any recursively instantiated objects
492 memo_dict = {}
493 elif ancestor:
494 # memoize me now to avoid problems with recursive calls
495 memo_dict[ancestor] = self
496
497 if not ancestor:
498 ancestor = self.__class__
499 ancestor._instantiated = True
500
501 # initialize required attributes
502 self._parent = None
503 self._name = None
504 self._ccObject = None # pointer to C++ object
505 self._ccParams = None
506 self._instantiated = False # really "cloned"
507
508 # Clone children specified at class level. No need for a
509 # multidict here since we will be cloning everything.
510 # Do children before parameter values so that children that
511 # are also param values get cloned properly.
512 self._children = {}
513 for key,val in ancestor._children.iteritems():
514 self.add_child(key, val(_memo=memo_dict))
515
516 # Inherit parameter values from class using multidict so
517 # individual value settings can be overridden but we still
518 # inherit late changes to non-overridden class values.
519 self._values = multidict(ancestor._values)
520 # clone SimObject-valued parameters
521 for key,val in ancestor._values.iteritems():
522 val = tryAsSimObjectOrVector(val)
523 if val is not None:
524 self._values[key] = val(_memo=memo_dict)
525
526 # clone port references. no need to use a multidict here
527 # since we will be creating new references for all ports.
528 self._port_refs = {}
529 for key,val in ancestor._port_refs.iteritems():
530 self._port_refs[key] = val.clone(self, memo_dict)
531 # apply attribute assignments from keyword args, if any
532 for key,val in kwargs.iteritems():
533 setattr(self, key, val)
534
535 # "Clone" the current instance by creating another instance of
536 # this instance's class, but that inherits its parameter values
537 # and port mappings from the current instance. If we're in a
538 # "deep copy" recursive clone, check the _memo dict to see if
539 # we've already cloned this instance.
540 def __call__(self, **kwargs):
541 memo_dict = kwargs.get('_memo')
542 if memo_dict is None:
543 # no memo_dict: must be top-level clone operation.
544 # this is only allowed at the root of a hierarchy
545 if self._parent:
546 raise RuntimeError, "attempt to clone object %s " \
547 "not at the root of a tree (parent = %s)" \
548 % (self, self._parent)
549 # create a new dict and use that.
550 memo_dict = {}
551 kwargs['_memo'] = memo_dict
552 elif memo_dict.has_key(self):
553 # clone already done & memoized
554 return memo_dict[self]
555 return self.__class__(_ancestor = self, **kwargs)
556
557 def _get_port_ref(self, attr):
558 # Return reference that can be assigned to another port
559 # via __setattr__. There is only ever one reference
560 # object per port, but we create them lazily here.
561 ref = self._port_refs.get(attr)
562 if not ref:
563 ref = self._ports[attr].makeRef(self)
564 self._port_refs[attr] = ref
565 return ref
566
567 def __getattr__(self, attr):
568 if self._ports.has_key(attr):
569 return self._get_port_ref(attr)
570
571 if self._values.has_key(attr):
572 return self._values[attr]
573
574 if self._children.has_key(attr):
575 return self._children[attr]
576
577 # If the attribute exists on the C++ object, transparently
578 # forward the reference there. This is typically used for
579 # SWIG-wrapped methods such as init(), regStats(),
580 # regFormulas(), resetStats(), startup(), drain(), and
581 # resume().
582 if self._ccObject and hasattr(self._ccObject, attr):
583 return getattr(self._ccObject, attr)
584
585 raise AttributeError, "object '%s' has no attribute '%s'" \
586 % (self.__class__.__name__, attr)
587
588 # Set attribute (called on foo.attr = value when foo is an
589 # instance of class cls).
590 def __setattr__(self, attr, value):
591 # normal processing for private attributes
592 if attr.startswith('_'):
593 object.__setattr__(self, attr, value)
594 return
595
596 if self._ports.has_key(attr):
597 # set up port connection
598 self._get_port_ref(attr).connect(value)
599 return
600
601 if isSimObjectOrSequence(value) and self._instantiated:
602 raise RuntimeError, \
603 "cannot set SimObject parameter '%s' after\n" \
604 " instance been cloned %s" % (attr, `self`)
605
606 param = self._params.get(attr)
607 if param:
608 try:
609 value = param.convert(value)
610 except Exception, e:
611 msg = "%s\nError setting param %s.%s to %s\n" % \
612 (e, self.__class__.__name__, attr, value)
613 e.args = (msg, )
614 raise
615 self._values[attr] = value
616 # implicitly parent unparented objects assigned as params
617 if isSimObjectOrVector(value) and not value.has_parent():
618 self.add_child(attr, value)
619 return
620
621 # if RHS is a SimObject, it's an implicit child assignment
622 if isSimObjectOrSequence(value):
623 self.add_child(attr, value)
624 return
625
626 # no valid assignment... raise exception
627 raise AttributeError, "Class %s has no parameter %s" \
628 % (self.__class__.__name__, attr)
629
630
631 # this hack allows tacking a '[0]' onto parameters that may or may
632 # not be vectors, and always getting the first element (e.g. cpus)
633 def __getitem__(self, key):
634 if key == 0:
635 return self
636 raise TypeError, "Non-zero index '%s' to SimObject" % key
637
638 # Also implemented by SimObjectVector
639 def clear_parent(self, old_parent):
640 assert self._parent is old_parent
641 self._parent = None
642
643 # Also implemented by SimObjectVector
644 def set_parent(self, parent, name):
645 self._parent = parent
646 self._name = name
647
648 # Also implemented by SimObjectVector
649 def get_name(self):
650 return self._name
651
652 # Also implemented by SimObjectVector
653 def has_parent(self):
654 return self._parent is not None
655
656 # clear out child with given name. This code is not likely to be exercised.
657 # See comment in add_child.
658 def clear_child(self, name):
659 child = self._children[name]
660 child.clear_parent(self)
661 del self._children[name]
662
663 # Add a new child to this object.
664 def add_child(self, name, child):
665 child = coerceSimObjectOrVector(child)
666 if child.has_parent():
667 print "warning: add_child('%s'): child '%s' already has parent" % \
668 (name, child.get_name())
669 if self._children.has_key(name):
670 # This code path had an undiscovered bug that would make it fail
671 # at runtime. It had been here for a long time and was only
672 # exposed by a buggy script. Changes here will probably not be
673 # exercised without specialized testing.
674 self.clear_child(name)
675 child.set_parent(self, name)
676 self._children[name] = child
677
678 # Take SimObject-valued parameters that haven't been explicitly
679 # assigned as children and make them children of the object that
680 # they were assigned to as a parameter value. This guarantees
681 # that when we instantiate all the parameter objects we're still
682 # inside the configuration hierarchy.
683 def adoptOrphanParams(self):
684 for key,val in self._values.iteritems():
685 if not isSimObjectVector(val) and isSimObjectSequence(val):
686 # need to convert raw SimObject sequences to
687 # SimObjectVector class so we can call has_parent()
688 val = SimObjectVector(val)
689 self._values[key] = val
690 if isSimObjectOrVector(val) and not val.has_parent():
691 print "warning: %s adopting orphan SimObject param '%s'" \
692 % (self, key)
693 self.add_child(key, val)
694
695 def path(self):
696 if not self._parent:
697 return '<orphan %s>' % self.__class__
698 ppath = self._parent.path()
699 if ppath == 'root':
700 return self._name
701 return ppath + "." + self._name
702
703 def __str__(self):
704 return self.path()
705
706 def ini_str(self):
707 return self.path()
708
709 def find_any(self, ptype):
710 if isinstance(self, ptype):
711 return self, True
712
713 found_obj = None
714 for child in self._children.itervalues():
715 if isinstance(child, ptype):
716 if found_obj != None and child != found_obj:
717 raise AttributeError, \
718 'parent.any matched more than one: %s %s' % \
719 (found_obj.path, child.path)
720 found_obj = child
721 # search param space
722 for pname,pdesc in self._params.iteritems():
723 if issubclass(pdesc.ptype, ptype):
724 match_obj = self._values[pname]
725 if found_obj != None and found_obj != match_obj:
726 raise AttributeError, \
727 'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path)
728 found_obj = match_obj
729 return found_obj, found_obj != None
730
731 def find_all(self, ptype):
732 all = {}
733 # search children
734 for child in self._children.itervalues():
735 if isinstance(child, ptype) and not isproxy(child) and \
736 not isNullPointer(child):
737 all[child] = True
738 # search param space
739 for pname,pdesc in self._params.iteritems():
740 if issubclass(pdesc.ptype, ptype):
741 match_obj = self._values[pname]
742 if not isproxy(match_obj) and not isNullPointer(match_obj):
743 all[match_obj] = True
744 return all.keys(), True
745
746 def unproxy(self, base):
747 return self
748
749 def unproxyParams(self):
750 for param in self._params.iterkeys():
751 value = self._values.get(param)
752 if value != None and isproxy(value):
753 try:
754 value = value.unproxy(self)
755 except:
756 print "Error in unproxying param '%s' of %s" % \
757 (param, self.path())
758 raise
759 setattr(self, param, value)
760
761 # Unproxy ports in sorted order so that 'append' operations on
762 # vector ports are done in a deterministic fashion.
763 port_names = self._ports.keys()
764 port_names.sort()
765 for port_name in port_names:
766 port = self._port_refs.get(port_name)
767 if port != None:
768 port.unproxy(self)
769
770 def print_ini(self, ini_file):
771 print >>ini_file, '[' + self.path() + ']' # .ini section header
772
773 instanceDict[self.path()] = self
774
775 if hasattr(self, 'type'):
776 print >>ini_file, 'type=%s' % self.type
777
778 child_names = self._children.keys()
779 child_names.sort()
780 if len(child_names):
781 print >>ini_file, 'children=%s' % \
782 ' '.join(self._children[n].get_name() for n in child_names)
783
784 param_names = self._params.keys()
785 param_names.sort()
786 for param in param_names:
787 value = self._values.get(param)
788 if value != None:
789 print >>ini_file, '%s=%s' % (param,
790 self._values[param].ini_str())
791
792 port_names = self._ports.keys()
793 port_names.sort()
794 for port_name in port_names:
795 port = self._port_refs.get(port_name, None)
796 if port != None:
797 print >>ini_file, '%s=%s' % (port_name, port.ini_str())
798
799 print >>ini_file # blank line between objects
800
801 def getCCParams(self):
802 if self._ccParams:
803 return self._ccParams
804
805 cc_params_struct = getattr(m5.internal.params, '%sParams' % self.type)
806 cc_params = cc_params_struct()
807 cc_params.pyobj = self
808 cc_params.name = str(self)
809
810 param_names = self._params.keys()
811 param_names.sort()
812 for param in param_names:
813 value = self._values.get(param)
814 if value is None:
815 fatal("%s.%s without default or user set value",
816 self.path(), param)
817
818 value = value.getValue()
819 if isinstance(self._params[param], VectorParamDesc):
820 assert isinstance(value, list)
821 vec = getattr(cc_params, param)
822 assert not len(vec)
823 for v in value:
824 vec.append(v)
825 else:
826 setattr(cc_params, param, value)
827
828 port_names = self._ports.keys()
829 port_names.sort()
830 for port_name in port_names:
831 port = self._port_refs.get(port_name, None)
832 if port != None:
833 setattr(cc_params, port_name, port)
834 self._ccParams = cc_params
835 return self._ccParams
836
837 # Get C++ object corresponding to this object, calling C++ if
838 # necessary to construct it. Does *not* recursively create
839 # children.
840 def getCCObject(self):
841 if not self._ccObject:
842 # Make sure this object is in the configuration hierarchy
843 if not self._parent and not isRoot(self):
844 raise RuntimeError, "Attempt to instantiate orphan node"
845 # Cycles in the configuration hierarchy are not supported. This
846 # will catch the resulting recursion and stop.
847 self._ccObject = -1
848 params = self.getCCParams()
849 self._ccObject = params.create()
850 elif self._ccObject == -1:
851 raise RuntimeError, "%s: Cycle found in configuration hierarchy." \
852 % self.path()
853 return self._ccObject
854
855 def descendants(self):
856 yield self
857 for child in self._children.itervalues():
858 for obj in child.descendants():
859 yield obj
860
861 # Call C++ to create C++ object corresponding to this object
862 def createCCObject(self):
863 self.getCCParams()
864 self.getCCObject() # force creation
865
866 def getValue(self):
867 return self.getCCObject()
868
869 # Create C++ port connections corresponding to the connections in
870 # _port_refs
871 def connectPorts(self):
872 for portRef in self._port_refs.itervalues():
873 portRef.ccConnect()
874
875 def getMemoryMode(self):
876 if not isinstance(self, m5.objects.System):
877 return None
878
879 return self._ccObject.getMemoryMode()
880
881 def changeTiming(self, mode):
882 if isinstance(self, m5.objects.System):
883 # i don't know if there's a better way to do this - calling
884 # setMemoryMode directly from self._ccObject results in calling
885 # SimObject::setMemoryMode, not the System::setMemoryMode
886 self._ccObject.setMemoryMode(mode)
887
888 def takeOverFrom(self, old_cpu):
889 self._ccObject.takeOverFrom(old_cpu._ccObject)
890
891 # generate output file for 'dot' to display as a pretty graph.
892 # this code is currently broken.
893 def outputDot(self, dot):
894 label = "{%s|" % self.path
895 if isSimObject(self.realtype):
896 label += '%s|' % self.type
897
898 if self.children:
899 # instantiate children in same order they were added for
900 # backward compatibility (else we can end up with cpu1
901 # before cpu0).
902 for c in self.children:
903 dot.add_edge(pydot.Edge(self.path,c.path, style="bold"))
904
905 simobjs = []
906 for param in self.params:
907 try:
908 if param.value is None:
909 raise AttributeError, 'Parameter with no value'
910
911 value = param.value
912 string = param.string(value)
913 except Exception, e:
914 msg = 'exception in %s:%s\n%s' % (self.name, param.name, e)
915 e.args = (msg, )
916 raise
917
918 if isSimObject(param.ptype) and string != "Null":
919 simobjs.append(string)
920 else:
921 label += '%s = %s\\n' % (param.name, string)
922
923 for so in simobjs:
924 label += "|<%s> %s" % (so, so)
925 dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so,
926 tailport="w"))
927 label += '}'
928 dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label))
929
930 # recursively dump out children
931 for c in self.children:
932 c.outputDot(dot)
933
934# Function to provide to C++ so it can look up instances based on paths
935def resolveSimObject(name):
936 obj = instanceDict[name]
937 return obj.getCCObject()
938
939def isSimObject(value):
940 return isinstance(value, SimObject)
941
942def isSimObjectClass(value):
943 return issubclass(value, SimObject)
944
945def isSimObjectVector(value):
946 return isinstance(value, SimObjectVector)
947
948def isSimObjectSequence(value):
949 if not isinstance(value, (list, tuple)) or len(value) == 0:
950 return False
951
952 for val in value:
953 if not isNullPointer(val) and not isSimObject(val):
954 return False
955
956 return True
957
958def isSimObjectOrSequence(value):
959 return isSimObject(value) or isSimObjectSequence(value)
960
961def isRoot(obj):
962 from m5.objects import Root
963 return obj and obj is Root.getInstance()
964
965def isSimObjectOrVector(value):
966 return isSimObject(value) or isSimObjectVector(value)
967
968def tryAsSimObjectOrVector(value):
969 if isSimObjectOrVector(value):
970 return value
971 if isSimObjectSequence(value):
972 return SimObjectVector(value)
973 return None
974
975def coerceSimObjectOrVector(value):
976 value = tryAsSimObjectOrVector(value)
977 if value is None:
978 raise TypeError, "SimObject or SimObjectVector expected"
979 return value
980
981baseClasses = allClasses.copy()
982baseInstances = instanceDict.copy()
983
984def clear():
985 global allClasses, instanceDict
986
987 allClasses = baseClasses.copy()
988 instanceDict = baseInstances.copy()
989
990# __all__ defines the list of symbols that get exported when
991# 'from config import *' is invoked. Try to keep this reasonably
992# short to avoid polluting other namespaces.
993__all__ = [ 'SimObject' ]