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