SimObject.py (12563:8d59ed22ae79) SimObject.py (12742:a48daf1c7e56)
1# Copyright (c) 2017 ARM Limited
2# All rights reserved.
3#
4# The license below extends only to copyright in the software and shall
5# not be construed as granting a license to any other intellectual
6# property including but not limited to intellectual property relating
7# to a hardware implementation of the functionality of the software
8# licensed hereunder. You may use the software subject to the license
9# terms below provided that you ensure that this notice is replicated
10# unmodified and in its entirety in all distributions of the software,
11# modified or unmodified, in source code or in binary form.
12#
13# Copyright (c) 2004-2006 The Regents of The University of Michigan
14# Copyright (c) 2010-20013 Advanced Micro Devices, Inc.
15# Copyright (c) 2013 Mark D. Hill and David A. Wood
16# All rights reserved.
17#
18# Redistribution and use in source and binary forms, with or without
19# modification, are permitted provided that the following conditions are
20# met: redistributions of source code must retain the above copyright
21# notice, this list of conditions and the following disclaimer;
22# redistributions in binary form must reproduce the above copyright
23# notice, this list of conditions and the following disclaimer in the
24# documentation and/or other materials provided with the distribution;
25# neither the name of the copyright holders nor the names of its
26# contributors may be used to endorse or promote products derived from
27# this software without specific prior written permission.
28#
29# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40#
41# Authors: Steve Reinhardt
42# Nathan Binkert
43# Andreas Hansson
44# Andreas Sandberg
45
46from __future__ import print_function
47
48import sys
49from types import FunctionType, MethodType, ModuleType
50from functools import wraps
51import inspect
52
53import m5
54from m5.util import *
55from m5.util.pybind import *
56# Use the pyfdt and not the helper class, because the fdthelper
57# relies on the SimObject definition
58from m5.ext.pyfdt import pyfdt
59
60# Have to import params up top since Param is referenced on initial
61# load (when SimObject class references Param to create a class
62# variable, the 'name' param)...
63from m5.params import *
64# There are a few things we need that aren't in params.__all__ since
65# normal users don't need them
66from m5.params import ParamDesc, VectorParamDesc, \
67 isNullPointer, SimObjectVector, Port
68
69from m5.proxy import *
70from m5.proxy import isproxy
71
72#####################################################################
73#
74# M5 Python Configuration Utility
75#
76# The basic idea is to write simple Python programs that build Python
77# objects corresponding to M5 SimObjects for the desired simulation
78# configuration. For now, the Python emits a .ini file that can be
79# parsed by M5. In the future, some tighter integration between M5
80# and the Python interpreter may allow bypassing the .ini file.
81#
82# Each SimObject class in M5 is represented by a Python class with the
83# same name. The Python inheritance tree mirrors the M5 C++ tree
84# (e.g., SimpleCPU derives from BaseCPU in both cases, and all
85# SimObjects inherit from a single SimObject base class). To specify
86# an instance of an M5 SimObject in a configuration, the user simply
87# instantiates the corresponding Python object. The parameters for
88# that SimObject are given by assigning to attributes of the Python
89# object, either using keyword assignment in the constructor or in
90# separate assignment statements. For example:
91#
92# cache = BaseCache(size='64KB')
93# cache.hit_latency = 3
94# cache.assoc = 8
95#
96# The magic lies in the mapping of the Python attributes for SimObject
97# classes to the actual SimObject parameter specifications. This
98# allows parameter validity checking in the Python code. Continuing
99# the example above, the statements "cache.blurfl=3" or
100# "cache.assoc='hello'" would both result in runtime errors in Python,
101# since the BaseCache object has no 'blurfl' parameter and the 'assoc'
102# parameter requires an integer, respectively. This magic is done
103# primarily by overriding the special __setattr__ method that controls
104# assignment to object attributes.
105#
106# Once a set of Python objects have been instantiated in a hierarchy,
107# calling 'instantiate(obj)' (where obj is the root of the hierarchy)
108# will generate a .ini file.
109#
110#####################################################################
111
112# list of all SimObject classes
113allClasses = {}
114
115# dict to look up SimObjects based on path
116instanceDict = {}
117
118# Did any of the SimObjects lack a header file?
119noCxxHeader = False
120
121def public_value(key, value):
122 return key.startswith('_') or \
123 isinstance(value, (FunctionType, MethodType, ModuleType,
124 classmethod, type))
125
126def createCxxConfigDirectoryEntryFile(code, name, simobj, is_header):
127 entry_class = 'CxxConfigDirectoryEntry_%s' % name
128 param_class = '%sCxxConfigParams' % name
129
130 code('#include "params/%s.hh"' % name)
131
132 if not is_header:
133 for param in simobj._params.values():
134 if isSimObjectClass(param.ptype):
135 code('#include "%s"' % param.ptype._value_dict['cxx_header'])
136 code('#include "params/%s.hh"' % param.ptype.__name__)
137 else:
138 param.ptype.cxx_ini_predecls(code)
139
140 if is_header:
141 member_prefix = ''
142 end_of_decl = ';'
143 code('#include "sim/cxx_config.hh"')
144 code()
145 code('class ${param_class} : public CxxConfigParams,'
146 ' public ${name}Params')
147 code('{')
148 code(' private:')
149 code.indent()
150 code('class DirectoryEntry : public CxxConfigDirectoryEntry')
151 code('{')
152 code(' public:')
153 code.indent()
154 code('DirectoryEntry();');
155 code()
156 code('CxxConfigParams *makeParamsObject() const')
157 code('{ return new ${param_class}; }')
158 code.dedent()
159 code('};')
160 code()
161 code.dedent()
162 code(' public:')
163 code.indent()
164 else:
165 member_prefix = '%s::' % param_class
166 end_of_decl = ''
167 code('#include "%s"' % simobj._value_dict['cxx_header'])
168 code('#include "base/str.hh"')
169 code('#include "cxx_config/${name}.hh"')
170
171 if simobj._ports.values() != []:
172 code('#include "mem/mem_object.hh"')
173 code('#include "mem/port.hh"')
174
175 code()
176 code('${member_prefix}DirectoryEntry::DirectoryEntry()');
177 code('{')
178
179 def cxx_bool(b):
180 return 'true' if b else 'false'
181
182 code.indent()
183 for param in simobj._params.values():
184 is_vector = isinstance(param, m5.params.VectorParamDesc)
185 is_simobj = issubclass(param.ptype, m5.SimObject.SimObject)
186
187 code('parameters["%s"] = new ParamDesc("%s", %s, %s);' %
188 (param.name, param.name, cxx_bool(is_vector),
189 cxx_bool(is_simobj)));
190
191 for port in simobj._ports.values():
192 is_vector = isinstance(port, m5.params.VectorPort)
193 is_master = port.role == 'MASTER'
194
195 code('ports["%s"] = new PortDesc("%s", %s, %s);' %
196 (port.name, port.name, cxx_bool(is_vector),
197 cxx_bool(is_master)))
198
199 code.dedent()
200 code('}')
201 code()
202
203 code('bool ${member_prefix}setSimObject(const std::string &name,')
204 code(' SimObject *simObject)${end_of_decl}')
205
206 if not is_header:
207 code('{')
208 code.indent()
209 code('bool ret = true;')
210 code()
211 code('if (false) {')
212 for param in simobj._params.values():
213 is_vector = isinstance(param, m5.params.VectorParamDesc)
214 is_simobj = issubclass(param.ptype, m5.SimObject.SimObject)
215
216 if is_simobj and not is_vector:
217 code('} else if (name == "${{param.name}}") {')
218 code.indent()
219 code('this->${{param.name}} = '
220 'dynamic_cast<${{param.ptype.cxx_type}}>(simObject);')
221 code('if (simObject && !this->${{param.name}})')
222 code(' ret = false;')
223 code.dedent()
224 code('} else {')
225 code(' ret = false;')
226 code('}')
227 code()
228 code('return ret;')
229 code.dedent()
230 code('}')
231
232 code()
233 code('bool ${member_prefix}setSimObjectVector('
234 'const std::string &name,')
235 code(' const std::vector<SimObject *> &simObjects)${end_of_decl}')
236
237 if not is_header:
238 code('{')
239 code.indent()
240 code('bool ret = true;')
241 code()
242 code('if (false) {')
243 for param in simobj._params.values():
244 is_vector = isinstance(param, m5.params.VectorParamDesc)
245 is_simobj = issubclass(param.ptype, m5.SimObject.SimObject)
246
247 if is_simobj and is_vector:
248 code('} else if (name == "${{param.name}}") {')
249 code.indent()
250 code('this->${{param.name}}.clear();')
251 code('for (auto i = simObjects.begin(); '
252 'ret && i != simObjects.end(); i ++)')
253 code('{')
254 code.indent()
255 code('${{param.ptype.cxx_type}} object = '
256 'dynamic_cast<${{param.ptype.cxx_type}}>(*i);')
257 code('if (*i && !object)')
258 code(' ret = false;')
259 code('else')
260 code(' this->${{param.name}}.push_back(object);')
261 code.dedent()
262 code('}')
263 code.dedent()
264 code('} else {')
265 code(' ret = false;')
266 code('}')
267 code()
268 code('return ret;')
269 code.dedent()
270 code('}')
271
272 code()
273 code('void ${member_prefix}setName(const std::string &name_)'
274 '${end_of_decl}')
275
276 if not is_header:
277 code('{')
278 code.indent()
279 code('this->name = name_;')
280 code.dedent()
281 code('}')
282
283 if is_header:
284 code('const std::string &${member_prefix}getName()')
285 code('{ return this->name; }')
286
287 code()
288 code('bool ${member_prefix}setParam(const std::string &name,')
289 code(' const std::string &value, const Flags flags)${end_of_decl}')
290
291 if not is_header:
292 code('{')
293 code.indent()
294 code('bool ret = true;')
295 code()
296 code('if (false) {')
297 for param in simobj._params.values():
298 is_vector = isinstance(param, m5.params.VectorParamDesc)
299 is_simobj = issubclass(param.ptype, m5.SimObject.SimObject)
300
301 if not is_simobj and not is_vector:
302 code('} else if (name == "${{param.name}}") {')
303 code.indent()
304 param.ptype.cxx_ini_parse(code,
305 'value', 'this->%s' % param.name, 'ret =')
306 code.dedent()
307 code('} else {')
308 code(' ret = false;')
309 code('}')
310 code()
311 code('return ret;')
312 code.dedent()
313 code('}')
314
315 code()
316 code('bool ${member_prefix}setParamVector('
317 'const std::string &name,')
318 code(' const std::vector<std::string> &values,')
319 code(' const Flags flags)${end_of_decl}')
320
321 if not is_header:
322 code('{')
323 code.indent()
324 code('bool ret = true;')
325 code()
326 code('if (false) {')
327 for param in simobj._params.values():
328 is_vector = isinstance(param, m5.params.VectorParamDesc)
329 is_simobj = issubclass(param.ptype, m5.SimObject.SimObject)
330
331 if not is_simobj and is_vector:
332 code('} else if (name == "${{param.name}}") {')
333 code.indent()
334 code('${{param.name}}.clear();')
335 code('for (auto i = values.begin(); '
336 'ret && i != values.end(); i ++)')
337 code('{')
338 code.indent()
339 code('${{param.ptype.cxx_type}} elem;')
340 param.ptype.cxx_ini_parse(code,
341 '*i', 'elem', 'ret =')
342 code('if (ret)')
343 code(' this->${{param.name}}.push_back(elem);')
344 code.dedent()
345 code('}')
346 code.dedent()
347 code('} else {')
348 code(' ret = false;')
349 code('}')
350 code()
351 code('return ret;')
352 code.dedent()
353 code('}')
354
355 code()
356 code('bool ${member_prefix}setPortConnectionCount('
357 'const std::string &name,')
358 code(' unsigned int count)${end_of_decl}')
359
360 if not is_header:
361 code('{')
362 code.indent()
363 code('bool ret = true;')
364 code()
365 code('if (false)')
366 code(' ;')
367 for port in simobj._ports.values():
368 code('else if (name == "${{port.name}}")')
369 code(' this->port_${{port.name}}_connection_count = count;')
370 code('else')
371 code(' ret = false;')
372 code()
373 code('return ret;')
374 code.dedent()
375 code('}')
376
377 code()
378 code('SimObject *${member_prefix}simObjectCreate()${end_of_decl}')
379
380 if not is_header:
381 code('{')
382 if hasattr(simobj, 'abstract') and simobj.abstract:
383 code(' return NULL;')
384 else:
385 code(' return this->create();')
386 code('}')
387
388 if is_header:
389 code()
390 code('static CxxConfigDirectoryEntry'
391 ' *${member_prefix}makeDirectoryEntry()')
392 code('{ return new DirectoryEntry; }')
393
394 if is_header:
395 code.dedent()
396 code('};')
397
398# The metaclass for SimObject. This class controls how new classes
399# that derive from SimObject are instantiated, and provides inherited
400# class behavior (just like a class controls how instances of that
401# class are instantiated, and provides inherited instance behavior).
402class MetaSimObject(type):
403 # Attributes that can be set only at initialization time
404 init_keywords = {
405 'abstract' : bool,
406 'cxx_class' : str,
407 'cxx_type' : str,
408 'cxx_header' : str,
409 'type' : str,
1# Copyright (c) 2017 ARM Limited
2# All rights reserved.
3#
4# The license below extends only to copyright in the software and shall
5# not be construed as granting a license to any other intellectual
6# property including but not limited to intellectual property relating
7# to a hardware implementation of the functionality of the software
8# licensed hereunder. You may use the software subject to the license
9# terms below provided that you ensure that this notice is replicated
10# unmodified and in its entirety in all distributions of the software,
11# modified or unmodified, in source code or in binary form.
12#
13# Copyright (c) 2004-2006 The Regents of The University of Michigan
14# Copyright (c) 2010-20013 Advanced Micro Devices, Inc.
15# Copyright (c) 2013 Mark D. Hill and David A. Wood
16# All rights reserved.
17#
18# Redistribution and use in source and binary forms, with or without
19# modification, are permitted provided that the following conditions are
20# met: redistributions of source code must retain the above copyright
21# notice, this list of conditions and the following disclaimer;
22# redistributions in binary form must reproduce the above copyright
23# notice, this list of conditions and the following disclaimer in the
24# documentation and/or other materials provided with the distribution;
25# neither the name of the copyright holders nor the names of its
26# contributors may be used to endorse or promote products derived from
27# this software without specific prior written permission.
28#
29# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40#
41# Authors: Steve Reinhardt
42# Nathan Binkert
43# Andreas Hansson
44# Andreas Sandberg
45
46from __future__ import print_function
47
48import sys
49from types import FunctionType, MethodType, ModuleType
50from functools import wraps
51import inspect
52
53import m5
54from m5.util import *
55from m5.util.pybind import *
56# Use the pyfdt and not the helper class, because the fdthelper
57# relies on the SimObject definition
58from m5.ext.pyfdt import pyfdt
59
60# Have to import params up top since Param is referenced on initial
61# load (when SimObject class references Param to create a class
62# variable, the 'name' param)...
63from m5.params import *
64# There are a few things we need that aren't in params.__all__ since
65# normal users don't need them
66from m5.params import ParamDesc, VectorParamDesc, \
67 isNullPointer, SimObjectVector, Port
68
69from m5.proxy import *
70from m5.proxy import isproxy
71
72#####################################################################
73#
74# M5 Python Configuration Utility
75#
76# The basic idea is to write simple Python programs that build Python
77# objects corresponding to M5 SimObjects for the desired simulation
78# configuration. For now, the Python emits a .ini file that can be
79# parsed by M5. In the future, some tighter integration between M5
80# and the Python interpreter may allow bypassing the .ini file.
81#
82# Each SimObject class in M5 is represented by a Python class with the
83# same name. The Python inheritance tree mirrors the M5 C++ tree
84# (e.g., SimpleCPU derives from BaseCPU in both cases, and all
85# SimObjects inherit from a single SimObject base class). To specify
86# an instance of an M5 SimObject in a configuration, the user simply
87# instantiates the corresponding Python object. The parameters for
88# that SimObject are given by assigning to attributes of the Python
89# object, either using keyword assignment in the constructor or in
90# separate assignment statements. For example:
91#
92# cache = BaseCache(size='64KB')
93# cache.hit_latency = 3
94# cache.assoc = 8
95#
96# The magic lies in the mapping of the Python attributes for SimObject
97# classes to the actual SimObject parameter specifications. This
98# allows parameter validity checking in the Python code. Continuing
99# the example above, the statements "cache.blurfl=3" or
100# "cache.assoc='hello'" would both result in runtime errors in Python,
101# since the BaseCache object has no 'blurfl' parameter and the 'assoc'
102# parameter requires an integer, respectively. This magic is done
103# primarily by overriding the special __setattr__ method that controls
104# assignment to object attributes.
105#
106# Once a set of Python objects have been instantiated in a hierarchy,
107# calling 'instantiate(obj)' (where obj is the root of the hierarchy)
108# will generate a .ini file.
109#
110#####################################################################
111
112# list of all SimObject classes
113allClasses = {}
114
115# dict to look up SimObjects based on path
116instanceDict = {}
117
118# Did any of the SimObjects lack a header file?
119noCxxHeader = False
120
121def public_value(key, value):
122 return key.startswith('_') or \
123 isinstance(value, (FunctionType, MethodType, ModuleType,
124 classmethod, type))
125
126def createCxxConfigDirectoryEntryFile(code, name, simobj, is_header):
127 entry_class = 'CxxConfigDirectoryEntry_%s' % name
128 param_class = '%sCxxConfigParams' % name
129
130 code('#include "params/%s.hh"' % name)
131
132 if not is_header:
133 for param in simobj._params.values():
134 if isSimObjectClass(param.ptype):
135 code('#include "%s"' % param.ptype._value_dict['cxx_header'])
136 code('#include "params/%s.hh"' % param.ptype.__name__)
137 else:
138 param.ptype.cxx_ini_predecls(code)
139
140 if is_header:
141 member_prefix = ''
142 end_of_decl = ';'
143 code('#include "sim/cxx_config.hh"')
144 code()
145 code('class ${param_class} : public CxxConfigParams,'
146 ' public ${name}Params')
147 code('{')
148 code(' private:')
149 code.indent()
150 code('class DirectoryEntry : public CxxConfigDirectoryEntry')
151 code('{')
152 code(' public:')
153 code.indent()
154 code('DirectoryEntry();');
155 code()
156 code('CxxConfigParams *makeParamsObject() const')
157 code('{ return new ${param_class}; }')
158 code.dedent()
159 code('};')
160 code()
161 code.dedent()
162 code(' public:')
163 code.indent()
164 else:
165 member_prefix = '%s::' % param_class
166 end_of_decl = ''
167 code('#include "%s"' % simobj._value_dict['cxx_header'])
168 code('#include "base/str.hh"')
169 code('#include "cxx_config/${name}.hh"')
170
171 if simobj._ports.values() != []:
172 code('#include "mem/mem_object.hh"')
173 code('#include "mem/port.hh"')
174
175 code()
176 code('${member_prefix}DirectoryEntry::DirectoryEntry()');
177 code('{')
178
179 def cxx_bool(b):
180 return 'true' if b else 'false'
181
182 code.indent()
183 for param in simobj._params.values():
184 is_vector = isinstance(param, m5.params.VectorParamDesc)
185 is_simobj = issubclass(param.ptype, m5.SimObject.SimObject)
186
187 code('parameters["%s"] = new ParamDesc("%s", %s, %s);' %
188 (param.name, param.name, cxx_bool(is_vector),
189 cxx_bool(is_simobj)));
190
191 for port in simobj._ports.values():
192 is_vector = isinstance(port, m5.params.VectorPort)
193 is_master = port.role == 'MASTER'
194
195 code('ports["%s"] = new PortDesc("%s", %s, %s);' %
196 (port.name, port.name, cxx_bool(is_vector),
197 cxx_bool(is_master)))
198
199 code.dedent()
200 code('}')
201 code()
202
203 code('bool ${member_prefix}setSimObject(const std::string &name,')
204 code(' SimObject *simObject)${end_of_decl}')
205
206 if not is_header:
207 code('{')
208 code.indent()
209 code('bool ret = true;')
210 code()
211 code('if (false) {')
212 for param in simobj._params.values():
213 is_vector = isinstance(param, m5.params.VectorParamDesc)
214 is_simobj = issubclass(param.ptype, m5.SimObject.SimObject)
215
216 if is_simobj and not is_vector:
217 code('} else if (name == "${{param.name}}") {')
218 code.indent()
219 code('this->${{param.name}} = '
220 'dynamic_cast<${{param.ptype.cxx_type}}>(simObject);')
221 code('if (simObject && !this->${{param.name}})')
222 code(' ret = false;')
223 code.dedent()
224 code('} else {')
225 code(' ret = false;')
226 code('}')
227 code()
228 code('return ret;')
229 code.dedent()
230 code('}')
231
232 code()
233 code('bool ${member_prefix}setSimObjectVector('
234 'const std::string &name,')
235 code(' const std::vector<SimObject *> &simObjects)${end_of_decl}')
236
237 if not is_header:
238 code('{')
239 code.indent()
240 code('bool ret = true;')
241 code()
242 code('if (false) {')
243 for param in simobj._params.values():
244 is_vector = isinstance(param, m5.params.VectorParamDesc)
245 is_simobj = issubclass(param.ptype, m5.SimObject.SimObject)
246
247 if is_simobj and is_vector:
248 code('} else if (name == "${{param.name}}") {')
249 code.indent()
250 code('this->${{param.name}}.clear();')
251 code('for (auto i = simObjects.begin(); '
252 'ret && i != simObjects.end(); i ++)')
253 code('{')
254 code.indent()
255 code('${{param.ptype.cxx_type}} object = '
256 'dynamic_cast<${{param.ptype.cxx_type}}>(*i);')
257 code('if (*i && !object)')
258 code(' ret = false;')
259 code('else')
260 code(' this->${{param.name}}.push_back(object);')
261 code.dedent()
262 code('}')
263 code.dedent()
264 code('} else {')
265 code(' ret = false;')
266 code('}')
267 code()
268 code('return ret;')
269 code.dedent()
270 code('}')
271
272 code()
273 code('void ${member_prefix}setName(const std::string &name_)'
274 '${end_of_decl}')
275
276 if not is_header:
277 code('{')
278 code.indent()
279 code('this->name = name_;')
280 code.dedent()
281 code('}')
282
283 if is_header:
284 code('const std::string &${member_prefix}getName()')
285 code('{ return this->name; }')
286
287 code()
288 code('bool ${member_prefix}setParam(const std::string &name,')
289 code(' const std::string &value, const Flags flags)${end_of_decl}')
290
291 if not is_header:
292 code('{')
293 code.indent()
294 code('bool ret = true;')
295 code()
296 code('if (false) {')
297 for param in simobj._params.values():
298 is_vector = isinstance(param, m5.params.VectorParamDesc)
299 is_simobj = issubclass(param.ptype, m5.SimObject.SimObject)
300
301 if not is_simobj and not is_vector:
302 code('} else if (name == "${{param.name}}") {')
303 code.indent()
304 param.ptype.cxx_ini_parse(code,
305 'value', 'this->%s' % param.name, 'ret =')
306 code.dedent()
307 code('} else {')
308 code(' ret = false;')
309 code('}')
310 code()
311 code('return ret;')
312 code.dedent()
313 code('}')
314
315 code()
316 code('bool ${member_prefix}setParamVector('
317 'const std::string &name,')
318 code(' const std::vector<std::string> &values,')
319 code(' const Flags flags)${end_of_decl}')
320
321 if not is_header:
322 code('{')
323 code.indent()
324 code('bool ret = true;')
325 code()
326 code('if (false) {')
327 for param in simobj._params.values():
328 is_vector = isinstance(param, m5.params.VectorParamDesc)
329 is_simobj = issubclass(param.ptype, m5.SimObject.SimObject)
330
331 if not is_simobj and is_vector:
332 code('} else if (name == "${{param.name}}") {')
333 code.indent()
334 code('${{param.name}}.clear();')
335 code('for (auto i = values.begin(); '
336 'ret && i != values.end(); i ++)')
337 code('{')
338 code.indent()
339 code('${{param.ptype.cxx_type}} elem;')
340 param.ptype.cxx_ini_parse(code,
341 '*i', 'elem', 'ret =')
342 code('if (ret)')
343 code(' this->${{param.name}}.push_back(elem);')
344 code.dedent()
345 code('}')
346 code.dedent()
347 code('} else {')
348 code(' ret = false;')
349 code('}')
350 code()
351 code('return ret;')
352 code.dedent()
353 code('}')
354
355 code()
356 code('bool ${member_prefix}setPortConnectionCount('
357 'const std::string &name,')
358 code(' unsigned int count)${end_of_decl}')
359
360 if not is_header:
361 code('{')
362 code.indent()
363 code('bool ret = true;')
364 code()
365 code('if (false)')
366 code(' ;')
367 for port in simobj._ports.values():
368 code('else if (name == "${{port.name}}")')
369 code(' this->port_${{port.name}}_connection_count = count;')
370 code('else')
371 code(' ret = false;')
372 code()
373 code('return ret;')
374 code.dedent()
375 code('}')
376
377 code()
378 code('SimObject *${member_prefix}simObjectCreate()${end_of_decl}')
379
380 if not is_header:
381 code('{')
382 if hasattr(simobj, 'abstract') and simobj.abstract:
383 code(' return NULL;')
384 else:
385 code(' return this->create();')
386 code('}')
387
388 if is_header:
389 code()
390 code('static CxxConfigDirectoryEntry'
391 ' *${member_prefix}makeDirectoryEntry()')
392 code('{ return new DirectoryEntry; }')
393
394 if is_header:
395 code.dedent()
396 code('};')
397
398# The metaclass for SimObject. This class controls how new classes
399# that derive from SimObject are instantiated, and provides inherited
400# class behavior (just like a class controls how instances of that
401# class are instantiated, and provides inherited instance behavior).
402class MetaSimObject(type):
403 # Attributes that can be set only at initialization time
404 init_keywords = {
405 'abstract' : bool,
406 'cxx_class' : str,
407 'cxx_type' : str,
408 'cxx_header' : str,
409 'type' : str,
410 'cxx_bases' : list,
410 'cxx_extra_bases' : list,
411 'cxx_exports' : list,
412 'cxx_param_exports' : list,
413 }
414 # Attributes that can be set any time
415 keywords = { 'check' : FunctionType }
416
417 # __new__ is called before __init__, and is where the statements
418 # in the body of the class definition get loaded into the class's
419 # __dict__. We intercept this to filter out parameter & port assignments
420 # and only allow "private" attributes to be passed to the base
421 # __new__ (starting with underscore).
422 def __new__(mcls, name, bases, dict):
423 assert name not in allClasses, "SimObject %s already present" % name
424
425 # Copy "private" attributes, functions, and classes to the
426 # official dict. Everything else goes in _init_dict to be
427 # filtered in __init__.
428 cls_dict = {}
429 value_dict = {}
430 cxx_exports = []
431 for key,val in dict.items():
432 try:
433 cxx_exports.append(getattr(val, "__pybind"))
434 except AttributeError:
435 pass
436
437 if public_value(key, val):
438 cls_dict[key] = val
439 else:
440 # must be a param/port setting
441 value_dict[key] = val
442 if 'abstract' not in value_dict:
443 value_dict['abstract'] = False
411 'cxx_exports' : list,
412 'cxx_param_exports' : list,
413 }
414 # Attributes that can be set any time
415 keywords = { 'check' : FunctionType }
416
417 # __new__ is called before __init__, and is where the statements
418 # in the body of the class definition get loaded into the class's
419 # __dict__. We intercept this to filter out parameter & port assignments
420 # and only allow "private" attributes to be passed to the base
421 # __new__ (starting with underscore).
422 def __new__(mcls, name, bases, dict):
423 assert name not in allClasses, "SimObject %s already present" % name
424
425 # Copy "private" attributes, functions, and classes to the
426 # official dict. Everything else goes in _init_dict to be
427 # filtered in __init__.
428 cls_dict = {}
429 value_dict = {}
430 cxx_exports = []
431 for key,val in dict.items():
432 try:
433 cxx_exports.append(getattr(val, "__pybind"))
434 except AttributeError:
435 pass
436
437 if public_value(key, val):
438 cls_dict[key] = val
439 else:
440 # must be a param/port setting
441 value_dict[key] = val
442 if 'abstract' not in value_dict:
443 value_dict['abstract'] = False
444 if 'cxx_bases' not in value_dict:
445 value_dict['cxx_bases'] = []
444 if 'cxx_extra_bases' not in value_dict:
445 value_dict['cxx_extra_bases'] = []
446 if 'cxx_exports' not in value_dict:
447 value_dict['cxx_exports'] = cxx_exports
448 else:
449 value_dict['cxx_exports'] += cxx_exports
450 if 'cxx_param_exports' not in value_dict:
451 value_dict['cxx_param_exports'] = []
452 cls_dict['_value_dict'] = value_dict
453 cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict)
454 if 'type' in value_dict:
455 allClasses[name] = cls
456 return cls
457
458 # subclass initialization
459 def __init__(cls, name, bases, dict):
460 # calls type.__init__()... I think that's a no-op, but leave
461 # it here just in case it's not.
462 super(MetaSimObject, cls).__init__(name, bases, dict)
463
464 # initialize required attributes
465
466 # class-only attributes
467 cls._params = multidict() # param descriptions
468 cls._ports = multidict() # port descriptions
469
470 # class or instance attributes
471 cls._values = multidict() # param values
472 cls._hr_values = multidict() # human readable param values
473 cls._children = multidict() # SimObject children
474 cls._port_refs = multidict() # port ref objects
475 cls._instantiated = False # really instantiated, cloned, or subclassed
476
477 # We don't support multiple inheritance of sim objects. If you want
478 # to, you must fix multidict to deal with it properly. Non sim-objects
479 # are ok, though
480 bTotal = 0
481 for c in bases:
482 if isinstance(c, MetaSimObject):
483 bTotal += 1
484 if bTotal > 1:
485 raise TypeError, \
486 "SimObjects do not support multiple inheritance"
487
488 base = bases[0]
489
490 # Set up general inheritance via multidicts. A subclass will
491 # inherit all its settings from the base class. The only time
492 # the following is not true is when we define the SimObject
493 # class itself (in which case the multidicts have no parent).
494 if isinstance(base, MetaSimObject):
495 cls._base = base
496 cls._params.parent = base._params
497 cls._ports.parent = base._ports
498 cls._values.parent = base._values
499 cls._hr_values.parent = base._hr_values
500 cls._children.parent = base._children
501 cls._port_refs.parent = base._port_refs
502 # mark base as having been subclassed
503 base._instantiated = True
504 else:
505 cls._base = None
506
507 # default keyword values
508 if 'type' in cls._value_dict:
509 if 'cxx_class' not in cls._value_dict:
510 cls._value_dict['cxx_class'] = cls._value_dict['type']
511
512 cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class']
513
514 if 'cxx_header' not in cls._value_dict:
515 global noCxxHeader
516 noCxxHeader = True
517 warn("No header file specified for SimObject: %s", name)
518
519 # Now process the _value_dict items. They could be defining
520 # new (or overriding existing) parameters or ports, setting
521 # class keywords (e.g., 'abstract'), or setting parameter
522 # values or port bindings. The first 3 can only be set when
523 # the class is defined, so we handle them here. The others
524 # can be set later too, so just emulate that by calling
525 # setattr().
526 for key,val in cls._value_dict.items():
527 # param descriptions
528 if isinstance(val, ParamDesc):
529 cls._new_param(key, val)
530
531 # port objects
532 elif isinstance(val, Port):
533 cls._new_port(key, val)
534
535 # init-time-only keywords
536 elif cls.init_keywords.has_key(key):
537 cls._set_keyword(key, val, cls.init_keywords[key])
538
539 # default: use normal path (ends up in __setattr__)
540 else:
541 setattr(cls, key, val)
542
543 def _set_keyword(cls, keyword, val, kwtype):
544 if not isinstance(val, kwtype):
545 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
546 (keyword, type(val), kwtype)
547 if isinstance(val, FunctionType):
548 val = classmethod(val)
549 type.__setattr__(cls, keyword, val)
550
551 def _new_param(cls, name, pdesc):
552 # each param desc should be uniquely assigned to one variable
553 assert(not hasattr(pdesc, 'name'))
554 pdesc.name = name
555 cls._params[name] = pdesc
556 if hasattr(pdesc, 'default'):
557 cls._set_param(name, pdesc.default, pdesc)
558
559 def _set_param(cls, name, value, param):
560 assert(param.name == name)
561 try:
562 hr_value = value
563 value = param.convert(value)
564 except Exception, e:
565 msg = "%s\nError setting param %s.%s to %s\n" % \
566 (e, cls.__name__, name, value)
567 e.args = (msg, )
568 raise
569 cls._values[name] = value
570 # if param value is a SimObject, make it a child too, so that
571 # it gets cloned properly when the class is instantiated
572 if isSimObjectOrVector(value) and not value.has_parent():
573 cls._add_cls_child(name, value)
574 # update human-readable values of the param if it has a literal
575 # value and is not an object or proxy.
576 if not (isSimObjectOrVector(value) or\
577 isinstance(value, m5.proxy.BaseProxy)):
578 cls._hr_values[name] = hr_value
579
580 def _add_cls_child(cls, name, child):
581 # It's a little funky to have a class as a parent, but these
582 # objects should never be instantiated (only cloned, which
583 # clears the parent pointer), and this makes it clear that the
584 # object is not an orphan and can provide better error
585 # messages.
586 child.set_parent(cls, name)
587 if not isNullPointer(child):
588 cls._children[name] = child
589
590 def _new_port(cls, name, port):
591 # each port should be uniquely assigned to one variable
592 assert(not hasattr(port, 'name'))
593 port.name = name
594 cls._ports[name] = port
595
596 # same as _get_port_ref, effectively, but for classes
597 def _cls_get_port_ref(cls, attr):
598 # Return reference that can be assigned to another port
599 # via __setattr__. There is only ever one reference
600 # object per port, but we create them lazily here.
601 ref = cls._port_refs.get(attr)
602 if not ref:
603 ref = cls._ports[attr].makeRef(cls)
604 cls._port_refs[attr] = ref
605 return ref
606
607 # Set attribute (called on foo.attr = value when foo is an
608 # instance of class cls).
609 def __setattr__(cls, attr, value):
610 # normal processing for private attributes
611 if public_value(attr, value):
612 type.__setattr__(cls, attr, value)
613 return
614
615 if cls.keywords.has_key(attr):
616 cls._set_keyword(attr, value, cls.keywords[attr])
617 return
618
619 if cls._ports.has_key(attr):
620 cls._cls_get_port_ref(attr).connect(value)
621 return
622
623 if isSimObjectOrSequence(value) and cls._instantiated:
624 raise RuntimeError, \
625 "cannot set SimObject parameter '%s' after\n" \
626 " class %s has been instantiated or subclassed" \
627 % (attr, cls.__name__)
628
629 # check for param
630 param = cls._params.get(attr)
631 if param:
632 cls._set_param(attr, value, param)
633 return
634
635 if isSimObjectOrSequence(value):
636 # If RHS is a SimObject, it's an implicit child assignment.
637 cls._add_cls_child(attr, coerceSimObjectOrVector(value))
638 return
639
640 # no valid assignment... raise exception
641 raise AttributeError, \
642 "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
643
644 def __getattr__(cls, attr):
645 if attr == 'cxx_class_path':
646 return cls.cxx_class.split('::')
647
648 if attr == 'cxx_class_name':
649 return cls.cxx_class_path[-1]
650
651 if attr == 'cxx_namespaces':
652 return cls.cxx_class_path[:-1]
653
654 if cls._values.has_key(attr):
655 return cls._values[attr]
656
657 if cls._children.has_key(attr):
658 return cls._children[attr]
659
660 raise AttributeError, \
661 "object '%s' has no attribute '%s'" % (cls.__name__, attr)
662
663 def __str__(cls):
664 return cls.__name__
665
666 # See ParamValue.cxx_predecls for description.
667 def cxx_predecls(cls, code):
668 code('#include "params/$cls.hh"')
669
670 def pybind_predecls(cls, code):
671 code('#include "${{cls.cxx_header}}"')
672
673 def pybind_decl(cls, code):
674 class_path = cls.cxx_class.split('::')
675 namespaces, classname = class_path[:-1], class_path[-1]
676 py_class_name = '_COLONS_'.join(class_path) if namespaces else \
677 classname;
678
679 # The 'local' attribute restricts us to the params declared in
680 # the object itself, not including inherited params (which
681 # will also be inherited from the base class's param struct
682 # here). Sort the params based on their key
683 params = map(lambda (k, v): v, sorted(cls._params.local.items()))
684 ports = cls._ports.local
685
686 code('''#include "pybind11/pybind11.h"
687#include "pybind11/stl.h"
688
689#include "params/$cls.hh"
690#include "python/pybind11/core.hh"
691#include "sim/init.hh"
692#include "sim/sim_object.hh"
693
694#include "${{cls.cxx_header}}"
695
696''')
697
698 for param in params:
699 param.pybind_predecls(code)
700
701 code('''namespace py = pybind11;
702
703static void
704module_init(py::module &m_internal)
705{
706 py::module m = m_internal.def_submodule("param_${cls}");
707''')
708 code.indent()
709 if cls._base:
710 code('py::class_<${cls}Params, ${{cls._base.type}}Params, ' \
711 'std::unique_ptr<${{cls}}Params, py::nodelete>>(' \
712 'm, "${cls}Params")')
713 else:
714 code('py::class_<${cls}Params, ' \
715 'std::unique_ptr<${cls}Params, py::nodelete>>(' \
716 'm, "${cls}Params")')
717
718 code.indent()
719 if not hasattr(cls, 'abstract') or not cls.abstract:
720 code('.def(py::init<>())')
721 code('.def("create", &${cls}Params::create)')
722
723 param_exports = cls.cxx_param_exports + [
724 PyBindProperty(k)
725 for k, v in sorted(cls._params.local.items())
726 ] + [
727 PyBindProperty("port_%s_connection_count" % port.name)
728 for port in ports.itervalues()
729 ]
730 for exp in param_exports:
731 exp.export(code, "%sParams" % cls)
732
733 code(';')
734 code()
735 code.dedent()
736
446 if 'cxx_exports' not in value_dict:
447 value_dict['cxx_exports'] = cxx_exports
448 else:
449 value_dict['cxx_exports'] += cxx_exports
450 if 'cxx_param_exports' not in value_dict:
451 value_dict['cxx_param_exports'] = []
452 cls_dict['_value_dict'] = value_dict
453 cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict)
454 if 'type' in value_dict:
455 allClasses[name] = cls
456 return cls
457
458 # subclass initialization
459 def __init__(cls, name, bases, dict):
460 # calls type.__init__()... I think that's a no-op, but leave
461 # it here just in case it's not.
462 super(MetaSimObject, cls).__init__(name, bases, dict)
463
464 # initialize required attributes
465
466 # class-only attributes
467 cls._params = multidict() # param descriptions
468 cls._ports = multidict() # port descriptions
469
470 # class or instance attributes
471 cls._values = multidict() # param values
472 cls._hr_values = multidict() # human readable param values
473 cls._children = multidict() # SimObject children
474 cls._port_refs = multidict() # port ref objects
475 cls._instantiated = False # really instantiated, cloned, or subclassed
476
477 # We don't support multiple inheritance of sim objects. If you want
478 # to, you must fix multidict to deal with it properly. Non sim-objects
479 # are ok, though
480 bTotal = 0
481 for c in bases:
482 if isinstance(c, MetaSimObject):
483 bTotal += 1
484 if bTotal > 1:
485 raise TypeError, \
486 "SimObjects do not support multiple inheritance"
487
488 base = bases[0]
489
490 # Set up general inheritance via multidicts. A subclass will
491 # inherit all its settings from the base class. The only time
492 # the following is not true is when we define the SimObject
493 # class itself (in which case the multidicts have no parent).
494 if isinstance(base, MetaSimObject):
495 cls._base = base
496 cls._params.parent = base._params
497 cls._ports.parent = base._ports
498 cls._values.parent = base._values
499 cls._hr_values.parent = base._hr_values
500 cls._children.parent = base._children
501 cls._port_refs.parent = base._port_refs
502 # mark base as having been subclassed
503 base._instantiated = True
504 else:
505 cls._base = None
506
507 # default keyword values
508 if 'type' in cls._value_dict:
509 if 'cxx_class' not in cls._value_dict:
510 cls._value_dict['cxx_class'] = cls._value_dict['type']
511
512 cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class']
513
514 if 'cxx_header' not in cls._value_dict:
515 global noCxxHeader
516 noCxxHeader = True
517 warn("No header file specified for SimObject: %s", name)
518
519 # Now process the _value_dict items. They could be defining
520 # new (or overriding existing) parameters or ports, setting
521 # class keywords (e.g., 'abstract'), or setting parameter
522 # values or port bindings. The first 3 can only be set when
523 # the class is defined, so we handle them here. The others
524 # can be set later too, so just emulate that by calling
525 # setattr().
526 for key,val in cls._value_dict.items():
527 # param descriptions
528 if isinstance(val, ParamDesc):
529 cls._new_param(key, val)
530
531 # port objects
532 elif isinstance(val, Port):
533 cls._new_port(key, val)
534
535 # init-time-only keywords
536 elif cls.init_keywords.has_key(key):
537 cls._set_keyword(key, val, cls.init_keywords[key])
538
539 # default: use normal path (ends up in __setattr__)
540 else:
541 setattr(cls, key, val)
542
543 def _set_keyword(cls, keyword, val, kwtype):
544 if not isinstance(val, kwtype):
545 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
546 (keyword, type(val), kwtype)
547 if isinstance(val, FunctionType):
548 val = classmethod(val)
549 type.__setattr__(cls, keyword, val)
550
551 def _new_param(cls, name, pdesc):
552 # each param desc should be uniquely assigned to one variable
553 assert(not hasattr(pdesc, 'name'))
554 pdesc.name = name
555 cls._params[name] = pdesc
556 if hasattr(pdesc, 'default'):
557 cls._set_param(name, pdesc.default, pdesc)
558
559 def _set_param(cls, name, value, param):
560 assert(param.name == name)
561 try:
562 hr_value = value
563 value = param.convert(value)
564 except Exception, e:
565 msg = "%s\nError setting param %s.%s to %s\n" % \
566 (e, cls.__name__, name, value)
567 e.args = (msg, )
568 raise
569 cls._values[name] = value
570 # if param value is a SimObject, make it a child too, so that
571 # it gets cloned properly when the class is instantiated
572 if isSimObjectOrVector(value) and not value.has_parent():
573 cls._add_cls_child(name, value)
574 # update human-readable values of the param if it has a literal
575 # value and is not an object or proxy.
576 if not (isSimObjectOrVector(value) or\
577 isinstance(value, m5.proxy.BaseProxy)):
578 cls._hr_values[name] = hr_value
579
580 def _add_cls_child(cls, name, child):
581 # It's a little funky to have a class as a parent, but these
582 # objects should never be instantiated (only cloned, which
583 # clears the parent pointer), and this makes it clear that the
584 # object is not an orphan and can provide better error
585 # messages.
586 child.set_parent(cls, name)
587 if not isNullPointer(child):
588 cls._children[name] = child
589
590 def _new_port(cls, name, port):
591 # each port should be uniquely assigned to one variable
592 assert(not hasattr(port, 'name'))
593 port.name = name
594 cls._ports[name] = port
595
596 # same as _get_port_ref, effectively, but for classes
597 def _cls_get_port_ref(cls, attr):
598 # Return reference that can be assigned to another port
599 # via __setattr__. There is only ever one reference
600 # object per port, but we create them lazily here.
601 ref = cls._port_refs.get(attr)
602 if not ref:
603 ref = cls._ports[attr].makeRef(cls)
604 cls._port_refs[attr] = ref
605 return ref
606
607 # Set attribute (called on foo.attr = value when foo is an
608 # instance of class cls).
609 def __setattr__(cls, attr, value):
610 # normal processing for private attributes
611 if public_value(attr, value):
612 type.__setattr__(cls, attr, value)
613 return
614
615 if cls.keywords.has_key(attr):
616 cls._set_keyword(attr, value, cls.keywords[attr])
617 return
618
619 if cls._ports.has_key(attr):
620 cls._cls_get_port_ref(attr).connect(value)
621 return
622
623 if isSimObjectOrSequence(value) and cls._instantiated:
624 raise RuntimeError, \
625 "cannot set SimObject parameter '%s' after\n" \
626 " class %s has been instantiated or subclassed" \
627 % (attr, cls.__name__)
628
629 # check for param
630 param = cls._params.get(attr)
631 if param:
632 cls._set_param(attr, value, param)
633 return
634
635 if isSimObjectOrSequence(value):
636 # If RHS is a SimObject, it's an implicit child assignment.
637 cls._add_cls_child(attr, coerceSimObjectOrVector(value))
638 return
639
640 # no valid assignment... raise exception
641 raise AttributeError, \
642 "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
643
644 def __getattr__(cls, attr):
645 if attr == 'cxx_class_path':
646 return cls.cxx_class.split('::')
647
648 if attr == 'cxx_class_name':
649 return cls.cxx_class_path[-1]
650
651 if attr == 'cxx_namespaces':
652 return cls.cxx_class_path[:-1]
653
654 if cls._values.has_key(attr):
655 return cls._values[attr]
656
657 if cls._children.has_key(attr):
658 return cls._children[attr]
659
660 raise AttributeError, \
661 "object '%s' has no attribute '%s'" % (cls.__name__, attr)
662
663 def __str__(cls):
664 return cls.__name__
665
666 # See ParamValue.cxx_predecls for description.
667 def cxx_predecls(cls, code):
668 code('#include "params/$cls.hh"')
669
670 def pybind_predecls(cls, code):
671 code('#include "${{cls.cxx_header}}"')
672
673 def pybind_decl(cls, code):
674 class_path = cls.cxx_class.split('::')
675 namespaces, classname = class_path[:-1], class_path[-1]
676 py_class_name = '_COLONS_'.join(class_path) if namespaces else \
677 classname;
678
679 # The 'local' attribute restricts us to the params declared in
680 # the object itself, not including inherited params (which
681 # will also be inherited from the base class's param struct
682 # here). Sort the params based on their key
683 params = map(lambda (k, v): v, sorted(cls._params.local.items()))
684 ports = cls._ports.local
685
686 code('''#include "pybind11/pybind11.h"
687#include "pybind11/stl.h"
688
689#include "params/$cls.hh"
690#include "python/pybind11/core.hh"
691#include "sim/init.hh"
692#include "sim/sim_object.hh"
693
694#include "${{cls.cxx_header}}"
695
696''')
697
698 for param in params:
699 param.pybind_predecls(code)
700
701 code('''namespace py = pybind11;
702
703static void
704module_init(py::module &m_internal)
705{
706 py::module m = m_internal.def_submodule("param_${cls}");
707''')
708 code.indent()
709 if cls._base:
710 code('py::class_<${cls}Params, ${{cls._base.type}}Params, ' \
711 'std::unique_ptr<${{cls}}Params, py::nodelete>>(' \
712 'm, "${cls}Params")')
713 else:
714 code('py::class_<${cls}Params, ' \
715 'std::unique_ptr<${cls}Params, py::nodelete>>(' \
716 'm, "${cls}Params")')
717
718 code.indent()
719 if not hasattr(cls, 'abstract') or not cls.abstract:
720 code('.def(py::init<>())')
721 code('.def("create", &${cls}Params::create)')
722
723 param_exports = cls.cxx_param_exports + [
724 PyBindProperty(k)
725 for k, v in sorted(cls._params.local.items())
726 ] + [
727 PyBindProperty("port_%s_connection_count" % port.name)
728 for port in ports.itervalues()
729 ]
730 for exp in param_exports:
731 exp.export(code, "%sParams" % cls)
732
733 code(';')
734 code()
735 code.dedent()
736
737 bases = [ cls._base.cxx_class ] + cls.cxx_bases if cls._base else \
738 cls.cxx_bases
737 bases = [ cls._base.cxx_class ] + cls.cxx_extra_bases if \
738 cls._base else cls.cxx_extra_bases
739 if bases:
740 base_str = ", ".join(bases)
741 code('py::class_<${{cls.cxx_class}}, ${base_str}, ' \
742 'std::unique_ptr<${{cls.cxx_class}}, py::nodelete>>(' \
743 'm, "${py_class_name}")')
744 else:
745 code('py::class_<${{cls.cxx_class}}, ' \
746 'std::unique_ptr<${{cls.cxx_class}}, py::nodelete>>(' \
747 'm, "${py_class_name}")')
748 code.indent()
749 for exp in cls.cxx_exports:
750 exp.export(code, cls.cxx_class)
751 code(';')
752 code.dedent()
753 code()
754 code.dedent()
755 code('}')
756 code()
757 code('static EmbeddedPyBind embed_obj("${0}", module_init, "${1}");',
758 cls, cls._base.type if cls._base else "")
759
760
761 # Generate the C++ declaration (.hh file) for this SimObject's
762 # param struct. Called from src/SConscript.
763 def cxx_param_decl(cls, code):
764 # The 'local' attribute restricts us to the params declared in
765 # the object itself, not including inherited params (which
766 # will also be inherited from the base class's param struct
767 # here). Sort the params based on their key
768 params = map(lambda (k, v): v, sorted(cls._params.local.items()))
769 ports = cls._ports.local
770 try:
771 ptypes = [p.ptype for p in params]
772 except:
773 print(cls, p, p.ptype_str)
774 print(params)
775 raise
776
777 class_path = cls._value_dict['cxx_class'].split('::')
778
779 code('''\
780#ifndef __PARAMS__${cls}__
781#define __PARAMS__${cls}__
782
783''')
784
785
786 # The base SimObject has a couple of params that get
787 # automatically set from Python without being declared through
788 # the normal Param mechanism; we slip them in here (needed
789 # predecls now, actual declarations below)
790 if cls == SimObject:
791 code('''#include <string>''')
792
793 # A forward class declaration is sufficient since we are just
794 # declaring a pointer.
795 for ns in class_path[:-1]:
796 code('namespace $ns {')
797 code('class $0;', class_path[-1])
798 for ns in reversed(class_path[:-1]):
799 code('} // namespace $ns')
800 code()
801
802 for param in params:
803 param.cxx_predecls(code)
804 for port in ports.itervalues():
805 port.cxx_predecls(code)
806 code()
807
808 if cls._base:
809 code('#include "params/${{cls._base.type}}.hh"')
810 code()
811
812 for ptype in ptypes:
813 if issubclass(ptype, Enum):
814 code('#include "enums/${{ptype.__name__}}.hh"')
815 code()
816
817 # now generate the actual param struct
818 code("struct ${cls}Params")
819 if cls._base:
820 code(" : public ${{cls._base.type}}Params")
821 code("{")
822 if not hasattr(cls, 'abstract') or not cls.abstract:
823 if 'type' in cls.__dict__:
824 code(" ${{cls.cxx_type}} create();")
825
826 code.indent()
827 if cls == SimObject:
828 code('''
829 SimObjectParams() {}
830 virtual ~SimObjectParams() {}
831
832 std::string name;
833 ''')
834
835 for param in params:
836 param.cxx_decl(code)
837 for port in ports.itervalues():
838 port.cxx_decl(code)
839
840 code.dedent()
841 code('};')
842
843 code()
844 code('#endif // __PARAMS__${cls}__')
845 return code
846
847 # Generate the C++ declaration/definition files for this SimObject's
848 # param struct to allow C++ initialisation
849 def cxx_config_param_file(cls, code, is_header):
850 createCxxConfigDirectoryEntryFile(code, cls.__name__, cls, is_header)
851 return code
852
853# This *temporary* definition is required to support calls from the
854# SimObject class definition to the MetaSimObject methods (in
855# particular _set_param, which gets called for parameters with default
856# values defined on the SimObject class itself). It will get
857# overridden by the permanent definition (which requires that
858# SimObject be defined) lower in this file.
859def isSimObjectOrVector(value):
860 return False
861
862def cxxMethod(*args, **kwargs):
863 """Decorator to export C++ functions to Python"""
864
865 def decorate(func):
866 name = func.func_name
867 override = kwargs.get("override", False)
868 cxx_name = kwargs.get("cxx_name", name)
869
870 args, varargs, keywords, defaults = inspect.getargspec(func)
871 if varargs or keywords:
872 raise ValueError("Wrapped methods must not contain variable " \
873 "arguments")
874
875 # Create tuples of (argument, default)
876 if defaults:
877 args = args[:-len(defaults)] + zip(args[-len(defaults):], defaults)
878 # Don't include self in the argument list to PyBind
879 args = args[1:]
880
881
882 @wraps(func)
883 def cxx_call(self, *args, **kwargs):
884 ccobj = self.getCCObject()
885 return getattr(ccobj, name)(*args, **kwargs)
886
887 @wraps(func)
888 def py_call(self, *args, **kwargs):
889 return self.func(*args, **kwargs)
890
891 f = py_call if override else cxx_call
892 f.__pybind = PyBindMethod(name, cxx_name=cxx_name, args=args)
893
894 return f
895
896 if len(args) == 0:
897 return decorate
898 elif len(args) == 1 and len(kwargs) == 0:
899 return decorate(*args)
900 else:
901 raise TypeError("One argument and no kwargs, or only kwargs expected")
902
903# This class holds information about each simobject parameter
904# that should be displayed on the command line for use in the
905# configuration system.
906class ParamInfo(object):
907 def __init__(self, type, desc, type_str, example, default_val, access_str):
908 self.type = type
909 self.desc = desc
910 self.type_str = type_str
911 self.example_str = example
912 self.default_val = default_val
913 # The string representation used to access this param through python.
914 # The method to access this parameter presented on the command line may
915 # be different, so this needs to be stored for later use.
916 self.access_str = access_str
917 self.created = True
918
919 # Make it so we can only set attributes at initialization time
920 # and effectively make this a const object.
921 def __setattr__(self, name, value):
922 if not "created" in self.__dict__:
923 self.__dict__[name] = value
924
925# The SimObject class is the root of the special hierarchy. Most of
926# the code in this class deals with the configuration hierarchy itself
927# (parent/child node relationships).
928class SimObject(object):
929 # Specify metaclass. Any class inheriting from SimObject will
930 # get this metaclass.
931 __metaclass__ = MetaSimObject
932 type = 'SimObject'
933 abstract = True
934
935 cxx_header = "sim/sim_object.hh"
739 if bases:
740 base_str = ", ".join(bases)
741 code('py::class_<${{cls.cxx_class}}, ${base_str}, ' \
742 'std::unique_ptr<${{cls.cxx_class}}, py::nodelete>>(' \
743 'm, "${py_class_name}")')
744 else:
745 code('py::class_<${{cls.cxx_class}}, ' \
746 'std::unique_ptr<${{cls.cxx_class}}, py::nodelete>>(' \
747 'm, "${py_class_name}")')
748 code.indent()
749 for exp in cls.cxx_exports:
750 exp.export(code, cls.cxx_class)
751 code(';')
752 code.dedent()
753 code()
754 code.dedent()
755 code('}')
756 code()
757 code('static EmbeddedPyBind embed_obj("${0}", module_init, "${1}");',
758 cls, cls._base.type if cls._base else "")
759
760
761 # Generate the C++ declaration (.hh file) for this SimObject's
762 # param struct. Called from src/SConscript.
763 def cxx_param_decl(cls, code):
764 # The 'local' attribute restricts us to the params declared in
765 # the object itself, not including inherited params (which
766 # will also be inherited from the base class's param struct
767 # here). Sort the params based on their key
768 params = map(lambda (k, v): v, sorted(cls._params.local.items()))
769 ports = cls._ports.local
770 try:
771 ptypes = [p.ptype for p in params]
772 except:
773 print(cls, p, p.ptype_str)
774 print(params)
775 raise
776
777 class_path = cls._value_dict['cxx_class'].split('::')
778
779 code('''\
780#ifndef __PARAMS__${cls}__
781#define __PARAMS__${cls}__
782
783''')
784
785
786 # The base SimObject has a couple of params that get
787 # automatically set from Python without being declared through
788 # the normal Param mechanism; we slip them in here (needed
789 # predecls now, actual declarations below)
790 if cls == SimObject:
791 code('''#include <string>''')
792
793 # A forward class declaration is sufficient since we are just
794 # declaring a pointer.
795 for ns in class_path[:-1]:
796 code('namespace $ns {')
797 code('class $0;', class_path[-1])
798 for ns in reversed(class_path[:-1]):
799 code('} // namespace $ns')
800 code()
801
802 for param in params:
803 param.cxx_predecls(code)
804 for port in ports.itervalues():
805 port.cxx_predecls(code)
806 code()
807
808 if cls._base:
809 code('#include "params/${{cls._base.type}}.hh"')
810 code()
811
812 for ptype in ptypes:
813 if issubclass(ptype, Enum):
814 code('#include "enums/${{ptype.__name__}}.hh"')
815 code()
816
817 # now generate the actual param struct
818 code("struct ${cls}Params")
819 if cls._base:
820 code(" : public ${{cls._base.type}}Params")
821 code("{")
822 if not hasattr(cls, 'abstract') or not cls.abstract:
823 if 'type' in cls.__dict__:
824 code(" ${{cls.cxx_type}} create();")
825
826 code.indent()
827 if cls == SimObject:
828 code('''
829 SimObjectParams() {}
830 virtual ~SimObjectParams() {}
831
832 std::string name;
833 ''')
834
835 for param in params:
836 param.cxx_decl(code)
837 for port in ports.itervalues():
838 port.cxx_decl(code)
839
840 code.dedent()
841 code('};')
842
843 code()
844 code('#endif // __PARAMS__${cls}__')
845 return code
846
847 # Generate the C++ declaration/definition files for this SimObject's
848 # param struct to allow C++ initialisation
849 def cxx_config_param_file(cls, code, is_header):
850 createCxxConfigDirectoryEntryFile(code, cls.__name__, cls, is_header)
851 return code
852
853# This *temporary* definition is required to support calls from the
854# SimObject class definition to the MetaSimObject methods (in
855# particular _set_param, which gets called for parameters with default
856# values defined on the SimObject class itself). It will get
857# overridden by the permanent definition (which requires that
858# SimObject be defined) lower in this file.
859def isSimObjectOrVector(value):
860 return False
861
862def cxxMethod(*args, **kwargs):
863 """Decorator to export C++ functions to Python"""
864
865 def decorate(func):
866 name = func.func_name
867 override = kwargs.get("override", False)
868 cxx_name = kwargs.get("cxx_name", name)
869
870 args, varargs, keywords, defaults = inspect.getargspec(func)
871 if varargs or keywords:
872 raise ValueError("Wrapped methods must not contain variable " \
873 "arguments")
874
875 # Create tuples of (argument, default)
876 if defaults:
877 args = args[:-len(defaults)] + zip(args[-len(defaults):], defaults)
878 # Don't include self in the argument list to PyBind
879 args = args[1:]
880
881
882 @wraps(func)
883 def cxx_call(self, *args, **kwargs):
884 ccobj = self.getCCObject()
885 return getattr(ccobj, name)(*args, **kwargs)
886
887 @wraps(func)
888 def py_call(self, *args, **kwargs):
889 return self.func(*args, **kwargs)
890
891 f = py_call if override else cxx_call
892 f.__pybind = PyBindMethod(name, cxx_name=cxx_name, args=args)
893
894 return f
895
896 if len(args) == 0:
897 return decorate
898 elif len(args) == 1 and len(kwargs) == 0:
899 return decorate(*args)
900 else:
901 raise TypeError("One argument and no kwargs, or only kwargs expected")
902
903# This class holds information about each simobject parameter
904# that should be displayed on the command line for use in the
905# configuration system.
906class ParamInfo(object):
907 def __init__(self, type, desc, type_str, example, default_val, access_str):
908 self.type = type
909 self.desc = desc
910 self.type_str = type_str
911 self.example_str = example
912 self.default_val = default_val
913 # The string representation used to access this param through python.
914 # The method to access this parameter presented on the command line may
915 # be different, so this needs to be stored for later use.
916 self.access_str = access_str
917 self.created = True
918
919 # Make it so we can only set attributes at initialization time
920 # and effectively make this a const object.
921 def __setattr__(self, name, value):
922 if not "created" in self.__dict__:
923 self.__dict__[name] = value
924
925# The SimObject class is the root of the special hierarchy. Most of
926# the code in this class deals with the configuration hierarchy itself
927# (parent/child node relationships).
928class SimObject(object):
929 # Specify metaclass. Any class inheriting from SimObject will
930 # get this metaclass.
931 __metaclass__ = MetaSimObject
932 type = 'SimObject'
933 abstract = True
934
935 cxx_header = "sim/sim_object.hh"
936 cxx_bases = [ "Drainable", "Serializable" ]
936 cxx_extra_bases = [ "Drainable", "Serializable" ]
937 eventq_index = Param.UInt32(Parent.eventq_index, "Event Queue Index")
938
939 cxx_exports = [
940 PyBindMethod("init"),
941 PyBindMethod("initState"),
942 PyBindMethod("memInvalidate"),
943 PyBindMethod("memWriteback"),
944 PyBindMethod("regStats"),
945 PyBindMethod("resetStats"),
946 PyBindMethod("regProbePoints"),
947 PyBindMethod("regProbeListeners"),
948 PyBindMethod("startup"),
949 ]
950
951 cxx_param_exports = [
952 PyBindProperty("name"),
953 ]
954
955 @cxxMethod
956 def loadState(self, cp):
957 """Load SimObject state from a checkpoint"""
958 pass
959
960 # Returns a dict of all the option strings that can be
961 # generated as command line options for this simobject instance
962 # by tracing all reachable params in the top level instance and
963 # any children it contains.
964 def enumerateParams(self, flags_dict = {},
965 cmd_line_str = "", access_str = ""):
966 if hasattr(self, "_paramEnumed"):
967 print("Cycle detected enumerating params")
968 else:
969 self._paramEnumed = True
970 # Scan the children first to pick up all the objects in this SimObj
971 for keys in self._children:
972 child = self._children[keys]
973 next_cmdline_str = cmd_line_str + keys
974 next_access_str = access_str + keys
975 if not isSimObjectVector(child):
976 next_cmdline_str = next_cmdline_str + "."
977 next_access_str = next_access_str + "."
978 flags_dict = child.enumerateParams(flags_dict,
979 next_cmdline_str,
980 next_access_str)
981
982 # Go through the simple params in the simobject in this level
983 # of the simobject hierarchy and save information about the
984 # parameter to be used for generating and processing command line
985 # options to the simulator to set these parameters.
986 for keys,values in self._params.items():
987 if values.isCmdLineSettable():
988 type_str = ''
989 ex_str = values.example_str()
990 ptype = None
991 if isinstance(values, VectorParamDesc):
992 type_str = 'Vector_%s' % values.ptype_str
993 ptype = values
994 else:
995 type_str = '%s' % values.ptype_str
996 ptype = values.ptype
997
998 if keys in self._hr_values\
999 and keys in self._values\
1000 and not isinstance(self._values[keys],
1001 m5.proxy.BaseProxy):
1002 cmd_str = cmd_line_str + keys
1003 acc_str = access_str + keys
1004 flags_dict[cmd_str] = ParamInfo(ptype,
1005 self._params[keys].desc, type_str, ex_str,
1006 values.pretty_print(self._hr_values[keys]),
1007 acc_str)
1008 elif not keys in self._hr_values\
1009 and not keys in self._values:
1010 # Empty param
1011 cmd_str = cmd_line_str + keys
1012 acc_str = access_str + keys
1013 flags_dict[cmd_str] = ParamInfo(ptype,
1014 self._params[keys].desc,
1015 type_str, ex_str, '', acc_str)
1016
1017 return flags_dict
1018
1019 # Initialize new instance. For objects with SimObject-valued
1020 # children, we need to recursively clone the classes represented
1021 # by those param values as well in a consistent "deep copy"-style
1022 # fashion. That is, we want to make sure that each instance is
1023 # cloned only once, and that if there are multiple references to
1024 # the same original object, we end up with the corresponding
1025 # cloned references all pointing to the same cloned instance.
1026 def __init__(self, **kwargs):
1027 ancestor = kwargs.get('_ancestor')
1028 memo_dict = kwargs.get('_memo')
1029 if memo_dict is None:
1030 # prepare to memoize any recursively instantiated objects
1031 memo_dict = {}
1032 elif ancestor:
1033 # memoize me now to avoid problems with recursive calls
1034 memo_dict[ancestor] = self
1035
1036 if not ancestor:
1037 ancestor = self.__class__
1038 ancestor._instantiated = True
1039
1040 # initialize required attributes
1041 self._parent = None
1042 self._name = None
1043 self._ccObject = None # pointer to C++ object
1044 self._ccParams = None
1045 self._instantiated = False # really "cloned"
1046
1047 # Clone children specified at class level. No need for a
1048 # multidict here since we will be cloning everything.
1049 # Do children before parameter values so that children that
1050 # are also param values get cloned properly.
1051 self._children = {}
1052 for key,val in ancestor._children.iteritems():
1053 self.add_child(key, val(_memo=memo_dict))
1054
1055 # Inherit parameter values from class using multidict so
1056 # individual value settings can be overridden but we still
1057 # inherit late changes to non-overridden class values.
1058 self._values = multidict(ancestor._values)
1059 self._hr_values = multidict(ancestor._hr_values)
1060 # clone SimObject-valued parameters
1061 for key,val in ancestor._values.iteritems():
1062 val = tryAsSimObjectOrVector(val)
1063 if val is not None:
1064 self._values[key] = val(_memo=memo_dict)
1065
1066 # clone port references. no need to use a multidict here
1067 # since we will be creating new references for all ports.
1068 self._port_refs = {}
1069 for key,val in ancestor._port_refs.iteritems():
1070 self._port_refs[key] = val.clone(self, memo_dict)
1071 # apply attribute assignments from keyword args, if any
1072 for key,val in kwargs.iteritems():
1073 setattr(self, key, val)
1074
1075 # "Clone" the current instance by creating another instance of
1076 # this instance's class, but that inherits its parameter values
1077 # and port mappings from the current instance. If we're in a
1078 # "deep copy" recursive clone, check the _memo dict to see if
1079 # we've already cloned this instance.
1080 def __call__(self, **kwargs):
1081 memo_dict = kwargs.get('_memo')
1082 if memo_dict is None:
1083 # no memo_dict: must be top-level clone operation.
1084 # this is only allowed at the root of a hierarchy
1085 if self._parent:
1086 raise RuntimeError, "attempt to clone object %s " \
1087 "not at the root of a tree (parent = %s)" \
1088 % (self, self._parent)
1089 # create a new dict and use that.
1090 memo_dict = {}
1091 kwargs['_memo'] = memo_dict
1092 elif memo_dict.has_key(self):
1093 # clone already done & memoized
1094 return memo_dict[self]
1095 return self.__class__(_ancestor = self, **kwargs)
1096
1097 def _get_port_ref(self, attr):
1098 # Return reference that can be assigned to another port
1099 # via __setattr__. There is only ever one reference
1100 # object per port, but we create them lazily here.
1101 ref = self._port_refs.get(attr)
1102 if ref == None:
1103 ref = self._ports[attr].makeRef(self)
1104 self._port_refs[attr] = ref
1105 return ref
1106
1107 def __getattr__(self, attr):
1108 if self._ports.has_key(attr):
1109 return self._get_port_ref(attr)
1110
1111 if self._values.has_key(attr):
1112 return self._values[attr]
1113
1114 if self._children.has_key(attr):
1115 return self._children[attr]
1116
1117 # If the attribute exists on the C++ object, transparently
1118 # forward the reference there. This is typically used for
1119 # methods exported to Python (e.g., init(), and startup())
1120 if self._ccObject and hasattr(self._ccObject, attr):
1121 return getattr(self._ccObject, attr)
1122
1123 err_string = "object '%s' has no attribute '%s'" \
1124 % (self.__class__.__name__, attr)
1125
1126 if not self._ccObject:
1127 err_string += "\n (C++ object is not yet constructed," \
1128 " so wrapped C++ methods are unavailable.)"
1129
1130 raise AttributeError, err_string
1131
1132 # Set attribute (called on foo.attr = value when foo is an
1133 # instance of class cls).
1134 def __setattr__(self, attr, value):
1135 # normal processing for private attributes
1136 if attr.startswith('_'):
1137 object.__setattr__(self, attr, value)
1138 return
1139
1140 if self._ports.has_key(attr):
1141 # set up port connection
1142 self._get_port_ref(attr).connect(value)
1143 return
1144
1145 param = self._params.get(attr)
1146 if param:
1147 try:
1148 hr_value = value
1149 value = param.convert(value)
1150 except Exception, e:
1151 msg = "%s\nError setting param %s.%s to %s\n" % \
1152 (e, self.__class__.__name__, attr, value)
1153 e.args = (msg, )
1154 raise
1155 self._values[attr] = value
1156 # implicitly parent unparented objects assigned as params
1157 if isSimObjectOrVector(value) and not value.has_parent():
1158 self.add_child(attr, value)
1159 # set the human-readable value dict if this is a param
1160 # with a literal value and is not being set as an object
1161 # or proxy.
1162 if not (isSimObjectOrVector(value) or\
1163 isinstance(value, m5.proxy.BaseProxy)):
1164 self._hr_values[attr] = hr_value
1165
1166 return
1167
1168 # if RHS is a SimObject, it's an implicit child assignment
1169 if isSimObjectOrSequence(value):
1170 self.add_child(attr, value)
1171 return
1172
1173 # no valid assignment... raise exception
1174 raise AttributeError, "Class %s has no parameter %s" \
1175 % (self.__class__.__name__, attr)
1176
1177
1178 # this hack allows tacking a '[0]' onto parameters that may or may
1179 # not be vectors, and always getting the first element (e.g. cpus)
1180 def __getitem__(self, key):
1181 if key == 0:
1182 return self
1183 raise IndexError, "Non-zero index '%s' to SimObject" % key
1184
1185 # this hack allows us to iterate over a SimObject that may
1186 # not be a vector, so we can call a loop over it and get just one
1187 # element.
1188 def __len__(self):
1189 return 1
1190
1191 # Also implemented by SimObjectVector
1192 def clear_parent(self, old_parent):
1193 assert self._parent is old_parent
1194 self._parent = None
1195
1196 # Also implemented by SimObjectVector
1197 def set_parent(self, parent, name):
1198 self._parent = parent
1199 self._name = name
1200
1201 # Return parent object of this SimObject, not implemented by
1202 # SimObjectVector because the elements in a SimObjectVector may not share
1203 # the same parent
1204 def get_parent(self):
1205 return self._parent
1206
1207 # Also implemented by SimObjectVector
1208 def get_name(self):
1209 return self._name
1210
1211 # Also implemented by SimObjectVector
1212 def has_parent(self):
1213 return self._parent is not None
1214
1215 # clear out child with given name. This code is not likely to be exercised.
1216 # See comment in add_child.
1217 def clear_child(self, name):
1218 child = self._children[name]
1219 child.clear_parent(self)
1220 del self._children[name]
1221
1222 # Add a new child to this object.
1223 def add_child(self, name, child):
1224 child = coerceSimObjectOrVector(child)
1225 if child.has_parent():
1226 warn("add_child('%s'): child '%s' already has parent", name,
1227 child.get_name())
1228 if self._children.has_key(name):
1229 # This code path had an undiscovered bug that would make it fail
1230 # at runtime. It had been here for a long time and was only
1231 # exposed by a buggy script. Changes here will probably not be
1232 # exercised without specialized testing.
1233 self.clear_child(name)
1234 child.set_parent(self, name)
1235 if not isNullPointer(child):
1236 self._children[name] = child
1237
1238 # Take SimObject-valued parameters that haven't been explicitly
1239 # assigned as children and make them children of the object that
1240 # they were assigned to as a parameter value. This guarantees
1241 # that when we instantiate all the parameter objects we're still
1242 # inside the configuration hierarchy.
1243 def adoptOrphanParams(self):
1244 for key,val in self._values.iteritems():
1245 if not isSimObjectVector(val) and isSimObjectSequence(val):
1246 # need to convert raw SimObject sequences to
1247 # SimObjectVector class so we can call has_parent()
1248 val = SimObjectVector(val)
1249 self._values[key] = val
1250 if isSimObjectOrVector(val) and not val.has_parent():
1251 warn("%s adopting orphan SimObject param '%s'", self, key)
1252 self.add_child(key, val)
1253
1254 def path(self):
1255 if not self._parent:
1256 return '<orphan %s>' % self.__class__
1257 elif isinstance(self._parent, MetaSimObject):
1258 return str(self.__class__)
1259
1260 ppath = self._parent.path()
1261 if ppath == 'root':
1262 return self._name
1263 return ppath + "." + self._name
1264
1265 def __str__(self):
1266 return self.path()
1267
1268 def config_value(self):
1269 return self.path()
1270
1271 def ini_str(self):
1272 return self.path()
1273
1274 def find_any(self, ptype):
1275 if isinstance(self, ptype):
1276 return self, True
1277
1278 found_obj = None
1279 for child in self._children.itervalues():
1280 visited = False
1281 if hasattr(child, '_visited'):
1282 visited = getattr(child, '_visited')
1283
1284 if isinstance(child, ptype) and not visited:
1285 if found_obj != None and child != found_obj:
1286 raise AttributeError, \
1287 'parent.any matched more than one: %s %s' % \
1288 (found_obj.path, child.path)
1289 found_obj = child
1290 # search param space
1291 for pname,pdesc in self._params.iteritems():
1292 if issubclass(pdesc.ptype, ptype):
1293 match_obj = self._values[pname]
1294 if found_obj != None and found_obj != match_obj:
1295 raise AttributeError, \
1296 'parent.any matched more than one: %s and %s' % \
1297 (found_obj.path, match_obj.path)
1298 found_obj = match_obj
1299 return found_obj, found_obj != None
1300
1301 def find_all(self, ptype):
1302 all = {}
1303 # search children
1304 for child in self._children.itervalues():
1305 # a child could be a list, so ensure we visit each item
1306 if isinstance(child, list):
1307 children = child
1308 else:
1309 children = [child]
1310
1311 for child in children:
1312 if isinstance(child, ptype) and not isproxy(child) and \
1313 not isNullPointer(child):
1314 all[child] = True
1315 if isSimObject(child):
1316 # also add results from the child itself
1317 child_all, done = child.find_all(ptype)
1318 all.update(dict(zip(child_all, [done] * len(child_all))))
1319 # search param space
1320 for pname,pdesc in self._params.iteritems():
1321 if issubclass(pdesc.ptype, ptype):
1322 match_obj = self._values[pname]
1323 if not isproxy(match_obj) and not isNullPointer(match_obj):
1324 all[match_obj] = True
1325 # Also make sure to sort the keys based on the objects' path to
1326 # ensure that the order is the same on all hosts
1327 return sorted(all.keys(), key = lambda o: o.path()), True
1328
1329 def unproxy(self, base):
1330 return self
1331
1332 def unproxyParams(self):
1333 for param in self._params.iterkeys():
1334 value = self._values.get(param)
1335 if value != None and isproxy(value):
1336 try:
1337 value = value.unproxy(self)
1338 except:
1339 print("Error in unproxying param '%s' of %s" %
1340 (param, self.path()))
1341 raise
1342 setattr(self, param, value)
1343
1344 # Unproxy ports in sorted order so that 'append' operations on
1345 # vector ports are done in a deterministic fashion.
1346 port_names = self._ports.keys()
1347 port_names.sort()
1348 for port_name in port_names:
1349 port = self._port_refs.get(port_name)
1350 if port != None:
1351 port.unproxy(self)
1352
1353 def print_ini(self, ini_file):
1354 print('[' + self.path() + ']', file=ini_file) # .ini section header
1355
1356 instanceDict[self.path()] = self
1357
1358 if hasattr(self, 'type'):
1359 print('type=%s' % self.type, file=ini_file)
1360
1361 if len(self._children.keys()):
1362 print('children=%s' %
1363 ' '.join(self._children[n].get_name()
1364 for n in sorted(self._children.keys())),
1365 file=ini_file)
1366
1367 for param in sorted(self._params.keys()):
1368 value = self._values.get(param)
1369 if value != None:
1370 print('%s=%s' % (param, self._values[param].ini_str()),
1371 file=ini_file)
1372
1373 for port_name in sorted(self._ports.keys()):
1374 port = self._port_refs.get(port_name, None)
1375 if port != None:
1376 print('%s=%s' % (port_name, port.ini_str()), file=ini_file)
1377
1378 print(file=ini_file) # blank line between objects
1379
1380 # generate a tree of dictionaries expressing all the parameters in the
1381 # instantiated system for use by scripts that want to do power, thermal
1382 # visualization, and other similar tasks
1383 def get_config_as_dict(self):
1384 d = attrdict()
1385 if hasattr(self, 'type'):
1386 d.type = self.type
1387 if hasattr(self, 'cxx_class'):
1388 d.cxx_class = self.cxx_class
1389 # Add the name and path of this object to be able to link to
1390 # the stats
1391 d.name = self.get_name()
1392 d.path = self.path()
1393
1394 for param in sorted(self._params.keys()):
1395 value = self._values.get(param)
1396 if value != None:
1397 d[param] = value.config_value()
1398
1399 for n in sorted(self._children.keys()):
1400 child = self._children[n]
1401 # Use the name of the attribute (and not get_name()) as
1402 # the key in the JSON dictionary to capture the hierarchy
1403 # in the Python code that assembled this system
1404 d[n] = child.get_config_as_dict()
1405
1406 for port_name in sorted(self._ports.keys()):
1407 port = self._port_refs.get(port_name, None)
1408 if port != None:
1409 # Represent each port with a dictionary containing the
1410 # prominent attributes
1411 d[port_name] = port.get_config_as_dict()
1412
1413 return d
1414
1415 def getCCParams(self):
1416 if self._ccParams:
1417 return self._ccParams
1418
1419 cc_params_struct = getattr(m5.internal.params, '%sParams' % self.type)
1420 cc_params = cc_params_struct()
1421 cc_params.name = str(self)
1422
1423 param_names = self._params.keys()
1424 param_names.sort()
1425 for param in param_names:
1426 value = self._values.get(param)
1427 if value is None:
1428 fatal("%s.%s without default or user set value",
1429 self.path(), param)
1430
1431 value = value.getValue()
1432 if isinstance(self._params[param], VectorParamDesc):
1433 assert isinstance(value, list)
1434 vec = getattr(cc_params, param)
1435 assert not len(vec)
1436 # Some types are exposed as opaque types. They support
1437 # the append operation unlike the automatically
1438 # wrapped types.
1439 if isinstance(vec, list):
1440 setattr(cc_params, param, list(value))
1441 else:
1442 for v in value:
1443 getattr(cc_params, param).append(v)
1444 else:
1445 setattr(cc_params, param, value)
1446
1447 port_names = self._ports.keys()
1448 port_names.sort()
1449 for port_name in port_names:
1450 port = self._port_refs.get(port_name, None)
1451 if port != None:
1452 port_count = len(port)
1453 else:
1454 port_count = 0
1455 setattr(cc_params, 'port_' + port_name + '_connection_count',
1456 port_count)
1457 self._ccParams = cc_params
1458 return self._ccParams
1459
1460 # Get C++ object corresponding to this object, calling C++ if
1461 # necessary to construct it. Does *not* recursively create
1462 # children.
1463 def getCCObject(self):
1464 if not self._ccObject:
1465 # Make sure this object is in the configuration hierarchy
1466 if not self._parent and not isRoot(self):
1467 raise RuntimeError, "Attempt to instantiate orphan node"
1468 # Cycles in the configuration hierarchy are not supported. This
1469 # will catch the resulting recursion and stop.
1470 self._ccObject = -1
1471 if not self.abstract:
1472 params = self.getCCParams()
1473 self._ccObject = params.create()
1474 elif self._ccObject == -1:
1475 raise RuntimeError, "%s: Cycle found in configuration hierarchy." \
1476 % self.path()
1477 return self._ccObject
1478
1479 def descendants(self):
1480 yield self
1481 # The order of the dict is implementation dependent, so sort
1482 # it based on the key (name) to ensure the order is the same
1483 # on all hosts
1484 for (name, child) in sorted(self._children.iteritems()):
1485 for obj in child.descendants():
1486 yield obj
1487
1488 # Call C++ to create C++ object corresponding to this object
1489 def createCCObject(self):
1490 self.getCCParams()
1491 self.getCCObject() # force creation
1492
1493 def getValue(self):
1494 return self.getCCObject()
1495
1496 # Create C++ port connections corresponding to the connections in
1497 # _port_refs
1498 def connectPorts(self):
1499 # Sort the ports based on their attribute name to ensure the
1500 # order is the same on all hosts
1501 for (attr, portRef) in sorted(self._port_refs.iteritems()):
1502 portRef.ccConnect()
1503
1504 # Default function for generating the device structure.
1505 # Can be overloaded by the inheriting class
1506 def generateDeviceTree(self, state):
1507 return # return without yielding anything
1508 yield # make this function a (null) generator
1509
1510 def recurseDeviceTree(self, state):
1511 for child in [getattr(self, c) for c in self._children]:
1512 for item in child: # For looping over SimObjectVectors
1513 if isinstance(item, SimObject):
1514 for dt in item.generateDeviceTree(state):
1515 yield dt
1516
1517# Function to provide to C++ so it can look up instances based on paths
1518def resolveSimObject(name):
1519 obj = instanceDict[name]
1520 return obj.getCCObject()
1521
1522def isSimObject(value):
1523 return isinstance(value, SimObject)
1524
1525def isSimObjectClass(value):
1526 return issubclass(value, SimObject)
1527
1528def isSimObjectVector(value):
1529 return isinstance(value, SimObjectVector)
1530
1531def isSimObjectSequence(value):
1532 if not isinstance(value, (list, tuple)) or len(value) == 0:
1533 return False
1534
1535 for val in value:
1536 if not isNullPointer(val) and not isSimObject(val):
1537 return False
1538
1539 return True
1540
1541def isSimObjectOrSequence(value):
1542 return isSimObject(value) or isSimObjectSequence(value)
1543
1544def isRoot(obj):
1545 from m5.objects import Root
1546 return obj and obj is Root.getInstance()
1547
1548def isSimObjectOrVector(value):
1549 return isSimObject(value) or isSimObjectVector(value)
1550
1551def tryAsSimObjectOrVector(value):
1552 if isSimObjectOrVector(value):
1553 return value
1554 if isSimObjectSequence(value):
1555 return SimObjectVector(value)
1556 return None
1557
1558def coerceSimObjectOrVector(value):
1559 value = tryAsSimObjectOrVector(value)
1560 if value is None:
1561 raise TypeError, "SimObject or SimObjectVector expected"
1562 return value
1563
1564baseClasses = allClasses.copy()
1565baseInstances = instanceDict.copy()
1566
1567def clear():
1568 global allClasses, instanceDict, noCxxHeader
1569
1570 allClasses = baseClasses.copy()
1571 instanceDict = baseInstances.copy()
1572 noCxxHeader = False
1573
1574# __all__ defines the list of symbols that get exported when
1575# 'from config import *' is invoked. Try to keep this reasonably
1576# short to avoid polluting other namespaces.
1577__all__ = [
1578 'SimObject',
1579 'cxxMethod',
1580 'PyBindMethod',
1581 'PyBindProperty',
1582]
937 eventq_index = Param.UInt32(Parent.eventq_index, "Event Queue Index")
938
939 cxx_exports = [
940 PyBindMethod("init"),
941 PyBindMethod("initState"),
942 PyBindMethod("memInvalidate"),
943 PyBindMethod("memWriteback"),
944 PyBindMethod("regStats"),
945 PyBindMethod("resetStats"),
946 PyBindMethod("regProbePoints"),
947 PyBindMethod("regProbeListeners"),
948 PyBindMethod("startup"),
949 ]
950
951 cxx_param_exports = [
952 PyBindProperty("name"),
953 ]
954
955 @cxxMethod
956 def loadState(self, cp):
957 """Load SimObject state from a checkpoint"""
958 pass
959
960 # Returns a dict of all the option strings that can be
961 # generated as command line options for this simobject instance
962 # by tracing all reachable params in the top level instance and
963 # any children it contains.
964 def enumerateParams(self, flags_dict = {},
965 cmd_line_str = "", access_str = ""):
966 if hasattr(self, "_paramEnumed"):
967 print("Cycle detected enumerating params")
968 else:
969 self._paramEnumed = True
970 # Scan the children first to pick up all the objects in this SimObj
971 for keys in self._children:
972 child = self._children[keys]
973 next_cmdline_str = cmd_line_str + keys
974 next_access_str = access_str + keys
975 if not isSimObjectVector(child):
976 next_cmdline_str = next_cmdline_str + "."
977 next_access_str = next_access_str + "."
978 flags_dict = child.enumerateParams(flags_dict,
979 next_cmdline_str,
980 next_access_str)
981
982 # Go through the simple params in the simobject in this level
983 # of the simobject hierarchy and save information about the
984 # parameter to be used for generating and processing command line
985 # options to the simulator to set these parameters.
986 for keys,values in self._params.items():
987 if values.isCmdLineSettable():
988 type_str = ''
989 ex_str = values.example_str()
990 ptype = None
991 if isinstance(values, VectorParamDesc):
992 type_str = 'Vector_%s' % values.ptype_str
993 ptype = values
994 else:
995 type_str = '%s' % values.ptype_str
996 ptype = values.ptype
997
998 if keys in self._hr_values\
999 and keys in self._values\
1000 and not isinstance(self._values[keys],
1001 m5.proxy.BaseProxy):
1002 cmd_str = cmd_line_str + keys
1003 acc_str = access_str + keys
1004 flags_dict[cmd_str] = ParamInfo(ptype,
1005 self._params[keys].desc, type_str, ex_str,
1006 values.pretty_print(self._hr_values[keys]),
1007 acc_str)
1008 elif not keys in self._hr_values\
1009 and not keys in self._values:
1010 # Empty param
1011 cmd_str = cmd_line_str + keys
1012 acc_str = access_str + keys
1013 flags_dict[cmd_str] = ParamInfo(ptype,
1014 self._params[keys].desc,
1015 type_str, ex_str, '', acc_str)
1016
1017 return flags_dict
1018
1019 # Initialize new instance. For objects with SimObject-valued
1020 # children, we need to recursively clone the classes represented
1021 # by those param values as well in a consistent "deep copy"-style
1022 # fashion. That is, we want to make sure that each instance is
1023 # cloned only once, and that if there are multiple references to
1024 # the same original object, we end up with the corresponding
1025 # cloned references all pointing to the same cloned instance.
1026 def __init__(self, **kwargs):
1027 ancestor = kwargs.get('_ancestor')
1028 memo_dict = kwargs.get('_memo')
1029 if memo_dict is None:
1030 # prepare to memoize any recursively instantiated objects
1031 memo_dict = {}
1032 elif ancestor:
1033 # memoize me now to avoid problems with recursive calls
1034 memo_dict[ancestor] = self
1035
1036 if not ancestor:
1037 ancestor = self.__class__
1038 ancestor._instantiated = True
1039
1040 # initialize required attributes
1041 self._parent = None
1042 self._name = None
1043 self._ccObject = None # pointer to C++ object
1044 self._ccParams = None
1045 self._instantiated = False # really "cloned"
1046
1047 # Clone children specified at class level. No need for a
1048 # multidict here since we will be cloning everything.
1049 # Do children before parameter values so that children that
1050 # are also param values get cloned properly.
1051 self._children = {}
1052 for key,val in ancestor._children.iteritems():
1053 self.add_child(key, val(_memo=memo_dict))
1054
1055 # Inherit parameter values from class using multidict so
1056 # individual value settings can be overridden but we still
1057 # inherit late changes to non-overridden class values.
1058 self._values = multidict(ancestor._values)
1059 self._hr_values = multidict(ancestor._hr_values)
1060 # clone SimObject-valued parameters
1061 for key,val in ancestor._values.iteritems():
1062 val = tryAsSimObjectOrVector(val)
1063 if val is not None:
1064 self._values[key] = val(_memo=memo_dict)
1065
1066 # clone port references. no need to use a multidict here
1067 # since we will be creating new references for all ports.
1068 self._port_refs = {}
1069 for key,val in ancestor._port_refs.iteritems():
1070 self._port_refs[key] = val.clone(self, memo_dict)
1071 # apply attribute assignments from keyword args, if any
1072 for key,val in kwargs.iteritems():
1073 setattr(self, key, val)
1074
1075 # "Clone" the current instance by creating another instance of
1076 # this instance's class, but that inherits its parameter values
1077 # and port mappings from the current instance. If we're in a
1078 # "deep copy" recursive clone, check the _memo dict to see if
1079 # we've already cloned this instance.
1080 def __call__(self, **kwargs):
1081 memo_dict = kwargs.get('_memo')
1082 if memo_dict is None:
1083 # no memo_dict: must be top-level clone operation.
1084 # this is only allowed at the root of a hierarchy
1085 if self._parent:
1086 raise RuntimeError, "attempt to clone object %s " \
1087 "not at the root of a tree (parent = %s)" \
1088 % (self, self._parent)
1089 # create a new dict and use that.
1090 memo_dict = {}
1091 kwargs['_memo'] = memo_dict
1092 elif memo_dict.has_key(self):
1093 # clone already done & memoized
1094 return memo_dict[self]
1095 return self.__class__(_ancestor = self, **kwargs)
1096
1097 def _get_port_ref(self, attr):
1098 # Return reference that can be assigned to another port
1099 # via __setattr__. There is only ever one reference
1100 # object per port, but we create them lazily here.
1101 ref = self._port_refs.get(attr)
1102 if ref == None:
1103 ref = self._ports[attr].makeRef(self)
1104 self._port_refs[attr] = ref
1105 return ref
1106
1107 def __getattr__(self, attr):
1108 if self._ports.has_key(attr):
1109 return self._get_port_ref(attr)
1110
1111 if self._values.has_key(attr):
1112 return self._values[attr]
1113
1114 if self._children.has_key(attr):
1115 return self._children[attr]
1116
1117 # If the attribute exists on the C++ object, transparently
1118 # forward the reference there. This is typically used for
1119 # methods exported to Python (e.g., init(), and startup())
1120 if self._ccObject and hasattr(self._ccObject, attr):
1121 return getattr(self._ccObject, attr)
1122
1123 err_string = "object '%s' has no attribute '%s'" \
1124 % (self.__class__.__name__, attr)
1125
1126 if not self._ccObject:
1127 err_string += "\n (C++ object is not yet constructed," \
1128 " so wrapped C++ methods are unavailable.)"
1129
1130 raise AttributeError, err_string
1131
1132 # Set attribute (called on foo.attr = value when foo is an
1133 # instance of class cls).
1134 def __setattr__(self, attr, value):
1135 # normal processing for private attributes
1136 if attr.startswith('_'):
1137 object.__setattr__(self, attr, value)
1138 return
1139
1140 if self._ports.has_key(attr):
1141 # set up port connection
1142 self._get_port_ref(attr).connect(value)
1143 return
1144
1145 param = self._params.get(attr)
1146 if param:
1147 try:
1148 hr_value = value
1149 value = param.convert(value)
1150 except Exception, e:
1151 msg = "%s\nError setting param %s.%s to %s\n" % \
1152 (e, self.__class__.__name__, attr, value)
1153 e.args = (msg, )
1154 raise
1155 self._values[attr] = value
1156 # implicitly parent unparented objects assigned as params
1157 if isSimObjectOrVector(value) and not value.has_parent():
1158 self.add_child(attr, value)
1159 # set the human-readable value dict if this is a param
1160 # with a literal value and is not being set as an object
1161 # or proxy.
1162 if not (isSimObjectOrVector(value) or\
1163 isinstance(value, m5.proxy.BaseProxy)):
1164 self._hr_values[attr] = hr_value
1165
1166 return
1167
1168 # if RHS is a SimObject, it's an implicit child assignment
1169 if isSimObjectOrSequence(value):
1170 self.add_child(attr, value)
1171 return
1172
1173 # no valid assignment... raise exception
1174 raise AttributeError, "Class %s has no parameter %s" \
1175 % (self.__class__.__name__, attr)
1176
1177
1178 # this hack allows tacking a '[0]' onto parameters that may or may
1179 # not be vectors, and always getting the first element (e.g. cpus)
1180 def __getitem__(self, key):
1181 if key == 0:
1182 return self
1183 raise IndexError, "Non-zero index '%s' to SimObject" % key
1184
1185 # this hack allows us to iterate over a SimObject that may
1186 # not be a vector, so we can call a loop over it and get just one
1187 # element.
1188 def __len__(self):
1189 return 1
1190
1191 # Also implemented by SimObjectVector
1192 def clear_parent(self, old_parent):
1193 assert self._parent is old_parent
1194 self._parent = None
1195
1196 # Also implemented by SimObjectVector
1197 def set_parent(self, parent, name):
1198 self._parent = parent
1199 self._name = name
1200
1201 # Return parent object of this SimObject, not implemented by
1202 # SimObjectVector because the elements in a SimObjectVector may not share
1203 # the same parent
1204 def get_parent(self):
1205 return self._parent
1206
1207 # Also implemented by SimObjectVector
1208 def get_name(self):
1209 return self._name
1210
1211 # Also implemented by SimObjectVector
1212 def has_parent(self):
1213 return self._parent is not None
1214
1215 # clear out child with given name. This code is not likely to be exercised.
1216 # See comment in add_child.
1217 def clear_child(self, name):
1218 child = self._children[name]
1219 child.clear_parent(self)
1220 del self._children[name]
1221
1222 # Add a new child to this object.
1223 def add_child(self, name, child):
1224 child = coerceSimObjectOrVector(child)
1225 if child.has_parent():
1226 warn("add_child('%s'): child '%s' already has parent", name,
1227 child.get_name())
1228 if self._children.has_key(name):
1229 # This code path had an undiscovered bug that would make it fail
1230 # at runtime. It had been here for a long time and was only
1231 # exposed by a buggy script. Changes here will probably not be
1232 # exercised without specialized testing.
1233 self.clear_child(name)
1234 child.set_parent(self, name)
1235 if not isNullPointer(child):
1236 self._children[name] = child
1237
1238 # Take SimObject-valued parameters that haven't been explicitly
1239 # assigned as children and make them children of the object that
1240 # they were assigned to as a parameter value. This guarantees
1241 # that when we instantiate all the parameter objects we're still
1242 # inside the configuration hierarchy.
1243 def adoptOrphanParams(self):
1244 for key,val in self._values.iteritems():
1245 if not isSimObjectVector(val) and isSimObjectSequence(val):
1246 # need to convert raw SimObject sequences to
1247 # SimObjectVector class so we can call has_parent()
1248 val = SimObjectVector(val)
1249 self._values[key] = val
1250 if isSimObjectOrVector(val) and not val.has_parent():
1251 warn("%s adopting orphan SimObject param '%s'", self, key)
1252 self.add_child(key, val)
1253
1254 def path(self):
1255 if not self._parent:
1256 return '<orphan %s>' % self.__class__
1257 elif isinstance(self._parent, MetaSimObject):
1258 return str(self.__class__)
1259
1260 ppath = self._parent.path()
1261 if ppath == 'root':
1262 return self._name
1263 return ppath + "." + self._name
1264
1265 def __str__(self):
1266 return self.path()
1267
1268 def config_value(self):
1269 return self.path()
1270
1271 def ini_str(self):
1272 return self.path()
1273
1274 def find_any(self, ptype):
1275 if isinstance(self, ptype):
1276 return self, True
1277
1278 found_obj = None
1279 for child in self._children.itervalues():
1280 visited = False
1281 if hasattr(child, '_visited'):
1282 visited = getattr(child, '_visited')
1283
1284 if isinstance(child, ptype) and not visited:
1285 if found_obj != None and child != found_obj:
1286 raise AttributeError, \
1287 'parent.any matched more than one: %s %s' % \
1288 (found_obj.path, child.path)
1289 found_obj = child
1290 # search param space
1291 for pname,pdesc in self._params.iteritems():
1292 if issubclass(pdesc.ptype, ptype):
1293 match_obj = self._values[pname]
1294 if found_obj != None and found_obj != match_obj:
1295 raise AttributeError, \
1296 'parent.any matched more than one: %s and %s' % \
1297 (found_obj.path, match_obj.path)
1298 found_obj = match_obj
1299 return found_obj, found_obj != None
1300
1301 def find_all(self, ptype):
1302 all = {}
1303 # search children
1304 for child in self._children.itervalues():
1305 # a child could be a list, so ensure we visit each item
1306 if isinstance(child, list):
1307 children = child
1308 else:
1309 children = [child]
1310
1311 for child in children:
1312 if isinstance(child, ptype) and not isproxy(child) and \
1313 not isNullPointer(child):
1314 all[child] = True
1315 if isSimObject(child):
1316 # also add results from the child itself
1317 child_all, done = child.find_all(ptype)
1318 all.update(dict(zip(child_all, [done] * len(child_all))))
1319 # search param space
1320 for pname,pdesc in self._params.iteritems():
1321 if issubclass(pdesc.ptype, ptype):
1322 match_obj = self._values[pname]
1323 if not isproxy(match_obj) and not isNullPointer(match_obj):
1324 all[match_obj] = True
1325 # Also make sure to sort the keys based on the objects' path to
1326 # ensure that the order is the same on all hosts
1327 return sorted(all.keys(), key = lambda o: o.path()), True
1328
1329 def unproxy(self, base):
1330 return self
1331
1332 def unproxyParams(self):
1333 for param in self._params.iterkeys():
1334 value = self._values.get(param)
1335 if value != None and isproxy(value):
1336 try:
1337 value = value.unproxy(self)
1338 except:
1339 print("Error in unproxying param '%s' of %s" %
1340 (param, self.path()))
1341 raise
1342 setattr(self, param, value)
1343
1344 # Unproxy ports in sorted order so that 'append' operations on
1345 # vector ports are done in a deterministic fashion.
1346 port_names = self._ports.keys()
1347 port_names.sort()
1348 for port_name in port_names:
1349 port = self._port_refs.get(port_name)
1350 if port != None:
1351 port.unproxy(self)
1352
1353 def print_ini(self, ini_file):
1354 print('[' + self.path() + ']', file=ini_file) # .ini section header
1355
1356 instanceDict[self.path()] = self
1357
1358 if hasattr(self, 'type'):
1359 print('type=%s' % self.type, file=ini_file)
1360
1361 if len(self._children.keys()):
1362 print('children=%s' %
1363 ' '.join(self._children[n].get_name()
1364 for n in sorted(self._children.keys())),
1365 file=ini_file)
1366
1367 for param in sorted(self._params.keys()):
1368 value = self._values.get(param)
1369 if value != None:
1370 print('%s=%s' % (param, self._values[param].ini_str()),
1371 file=ini_file)
1372
1373 for port_name in sorted(self._ports.keys()):
1374 port = self._port_refs.get(port_name, None)
1375 if port != None:
1376 print('%s=%s' % (port_name, port.ini_str()), file=ini_file)
1377
1378 print(file=ini_file) # blank line between objects
1379
1380 # generate a tree of dictionaries expressing all the parameters in the
1381 # instantiated system for use by scripts that want to do power, thermal
1382 # visualization, and other similar tasks
1383 def get_config_as_dict(self):
1384 d = attrdict()
1385 if hasattr(self, 'type'):
1386 d.type = self.type
1387 if hasattr(self, 'cxx_class'):
1388 d.cxx_class = self.cxx_class
1389 # Add the name and path of this object to be able to link to
1390 # the stats
1391 d.name = self.get_name()
1392 d.path = self.path()
1393
1394 for param in sorted(self._params.keys()):
1395 value = self._values.get(param)
1396 if value != None:
1397 d[param] = value.config_value()
1398
1399 for n in sorted(self._children.keys()):
1400 child = self._children[n]
1401 # Use the name of the attribute (and not get_name()) as
1402 # the key in the JSON dictionary to capture the hierarchy
1403 # in the Python code that assembled this system
1404 d[n] = child.get_config_as_dict()
1405
1406 for port_name in sorted(self._ports.keys()):
1407 port = self._port_refs.get(port_name, None)
1408 if port != None:
1409 # Represent each port with a dictionary containing the
1410 # prominent attributes
1411 d[port_name] = port.get_config_as_dict()
1412
1413 return d
1414
1415 def getCCParams(self):
1416 if self._ccParams:
1417 return self._ccParams
1418
1419 cc_params_struct = getattr(m5.internal.params, '%sParams' % self.type)
1420 cc_params = cc_params_struct()
1421 cc_params.name = str(self)
1422
1423 param_names = self._params.keys()
1424 param_names.sort()
1425 for param in param_names:
1426 value = self._values.get(param)
1427 if value is None:
1428 fatal("%s.%s without default or user set value",
1429 self.path(), param)
1430
1431 value = value.getValue()
1432 if isinstance(self._params[param], VectorParamDesc):
1433 assert isinstance(value, list)
1434 vec = getattr(cc_params, param)
1435 assert not len(vec)
1436 # Some types are exposed as opaque types. They support
1437 # the append operation unlike the automatically
1438 # wrapped types.
1439 if isinstance(vec, list):
1440 setattr(cc_params, param, list(value))
1441 else:
1442 for v in value:
1443 getattr(cc_params, param).append(v)
1444 else:
1445 setattr(cc_params, param, value)
1446
1447 port_names = self._ports.keys()
1448 port_names.sort()
1449 for port_name in port_names:
1450 port = self._port_refs.get(port_name, None)
1451 if port != None:
1452 port_count = len(port)
1453 else:
1454 port_count = 0
1455 setattr(cc_params, 'port_' + port_name + '_connection_count',
1456 port_count)
1457 self._ccParams = cc_params
1458 return self._ccParams
1459
1460 # Get C++ object corresponding to this object, calling C++ if
1461 # necessary to construct it. Does *not* recursively create
1462 # children.
1463 def getCCObject(self):
1464 if not self._ccObject:
1465 # Make sure this object is in the configuration hierarchy
1466 if not self._parent and not isRoot(self):
1467 raise RuntimeError, "Attempt to instantiate orphan node"
1468 # Cycles in the configuration hierarchy are not supported. This
1469 # will catch the resulting recursion and stop.
1470 self._ccObject = -1
1471 if not self.abstract:
1472 params = self.getCCParams()
1473 self._ccObject = params.create()
1474 elif self._ccObject == -1:
1475 raise RuntimeError, "%s: Cycle found in configuration hierarchy." \
1476 % self.path()
1477 return self._ccObject
1478
1479 def descendants(self):
1480 yield self
1481 # The order of the dict is implementation dependent, so sort
1482 # it based on the key (name) to ensure the order is the same
1483 # on all hosts
1484 for (name, child) in sorted(self._children.iteritems()):
1485 for obj in child.descendants():
1486 yield obj
1487
1488 # Call C++ to create C++ object corresponding to this object
1489 def createCCObject(self):
1490 self.getCCParams()
1491 self.getCCObject() # force creation
1492
1493 def getValue(self):
1494 return self.getCCObject()
1495
1496 # Create C++ port connections corresponding to the connections in
1497 # _port_refs
1498 def connectPorts(self):
1499 # Sort the ports based on their attribute name to ensure the
1500 # order is the same on all hosts
1501 for (attr, portRef) in sorted(self._port_refs.iteritems()):
1502 portRef.ccConnect()
1503
1504 # Default function for generating the device structure.
1505 # Can be overloaded by the inheriting class
1506 def generateDeviceTree(self, state):
1507 return # return without yielding anything
1508 yield # make this function a (null) generator
1509
1510 def recurseDeviceTree(self, state):
1511 for child in [getattr(self, c) for c in self._children]:
1512 for item in child: # For looping over SimObjectVectors
1513 if isinstance(item, SimObject):
1514 for dt in item.generateDeviceTree(state):
1515 yield dt
1516
1517# Function to provide to C++ so it can look up instances based on paths
1518def resolveSimObject(name):
1519 obj = instanceDict[name]
1520 return obj.getCCObject()
1521
1522def isSimObject(value):
1523 return isinstance(value, SimObject)
1524
1525def isSimObjectClass(value):
1526 return issubclass(value, SimObject)
1527
1528def isSimObjectVector(value):
1529 return isinstance(value, SimObjectVector)
1530
1531def isSimObjectSequence(value):
1532 if not isinstance(value, (list, tuple)) or len(value) == 0:
1533 return False
1534
1535 for val in value:
1536 if not isNullPointer(val) and not isSimObject(val):
1537 return False
1538
1539 return True
1540
1541def isSimObjectOrSequence(value):
1542 return isSimObject(value) or isSimObjectSequence(value)
1543
1544def isRoot(obj):
1545 from m5.objects import Root
1546 return obj and obj is Root.getInstance()
1547
1548def isSimObjectOrVector(value):
1549 return isSimObject(value) or isSimObjectVector(value)
1550
1551def tryAsSimObjectOrVector(value):
1552 if isSimObjectOrVector(value):
1553 return value
1554 if isSimObjectSequence(value):
1555 return SimObjectVector(value)
1556 return None
1557
1558def coerceSimObjectOrVector(value):
1559 value = tryAsSimObjectOrVector(value)
1560 if value is None:
1561 raise TypeError, "SimObject or SimObjectVector expected"
1562 return value
1563
1564baseClasses = allClasses.copy()
1565baseInstances = instanceDict.copy()
1566
1567def clear():
1568 global allClasses, instanceDict, noCxxHeader
1569
1570 allClasses = baseClasses.copy()
1571 instanceDict = baseInstances.copy()
1572 noCxxHeader = False
1573
1574# __all__ defines the list of symbols that get exported when
1575# 'from config import *' is invoked. Try to keep this reasonably
1576# short to avoid polluting other namespaces.
1577__all__ = [
1578 'SimObject',
1579 'cxxMethod',
1580 'PyBindMethod',
1581 'PyBindProperty',
1582]