SimObject.py revision 12023
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
46import sys
47from types import FunctionType, MethodType, ModuleType
48from functools import wraps
49import inspect
50
51import m5
52from m5.util import *
53from 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)...
58from 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
61from m5.params import ParamDesc, VectorParamDesc, \
62     isNullPointer, SimObjectVector, Port
63
64from m5.proxy import *
65from 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
108allClasses = {}
109
110# dict to look up SimObjects based on path
111instanceDict = {}
112
113# Did any of the SimObjects lack a header file?
114noCxxHeader = False
115
116def public_value(key, value):
117    return key.startswith('_') or \
118               isinstance(value, (FunctionType, MethodType, ModuleType,
119                                  classmethod, type))
120
121def 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).
397class 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 "sim/init.hh"
685#include "sim/sim_object.hh"
686
687#include "${{cls.cxx_header}}"
688
689''')
690
691        for param in params:
692            param.pybind_predecls(code)
693
694        code('''namespace py = pybind11;
695
696static void
697module_init(py::module &m_internal)
698{
699    py::module m = m_internal.def_submodule("param_${cls}");
700''')
701        code.indent()
702        if cls._base:
703            code('py::class_<${cls}Params, ${{cls._base.type}}Params>(m, ' \
704                 '"${cls}Params")')
705        else:
706            code('py::class_<${cls}Params>(m, "${cls}Params")')
707
708        code.indent()
709        if not hasattr(cls, 'abstract') or not cls.abstract:
710            code('.def(py::init<>())')
711            code('.def("create", &${cls}Params::create)')
712
713        param_exports = cls.cxx_param_exports + [
714            PyBindProperty(k)
715            for k, v in sorted(cls._params.local.items())
716        ] + [
717            PyBindProperty("port_%s_connection_count" % port.name)
718            for port in ports.itervalues()
719        ]
720        for exp in param_exports:
721            exp.export(code, "%sParams" % cls)
722
723        code(';')
724        code()
725        code.dedent()
726
727        bases = [ cls._base.cxx_class ] + cls.cxx_bases if cls._base else \
728                cls.cxx_bases
729        if bases:
730            base_str = ", ".join(bases)
731            code('py::class_<${{cls.cxx_class}}, ${base_str}>(m, ' \
732                 '"${py_class_name}")')
733        else:
734            code('py::class_<${{cls.cxx_class}}>(m, "${py_class_name}")')
735        code.indent()
736        for exp in cls.cxx_exports:
737            exp.export(code, cls.cxx_class)
738        code(';')
739        code.dedent()
740        code()
741        code.dedent()
742        code('}')
743        code()
744        code('static EmbeddedPyBind embed_obj("${0}", module_init, "${1}");',
745             cls, cls._base.type if cls._base else "")
746
747
748    # Generate the C++ declaration (.hh file) for this SimObject's
749    # param struct.  Called from src/SConscript.
750    def cxx_param_decl(cls, code):
751        # The 'local' attribute restricts us to the params declared in
752        # the object itself, not including inherited params (which
753        # will also be inherited from the base class's param struct
754        # here). Sort the params based on their key
755        params = map(lambda (k, v): v, sorted(cls._params.local.items()))
756        ports = cls._ports.local
757        try:
758            ptypes = [p.ptype for p in params]
759        except:
760            print cls, p, p.ptype_str
761            print params
762            raise
763
764        class_path = cls._value_dict['cxx_class'].split('::')
765
766        code('''\
767#ifndef __PARAMS__${cls}__
768#define __PARAMS__${cls}__
769
770''')
771
772
773        # The base SimObject has a couple of params that get
774        # automatically set from Python without being declared through
775        # the normal Param mechanism; we slip them in here (needed
776        # predecls now, actual declarations below)
777        if cls == SimObject:
778            code('''#include <string>''')
779
780        # A forward class declaration is sufficient since we are just
781        # declaring a pointer.
782        for ns in class_path[:-1]:
783            code('namespace $ns {')
784        code('class $0;', class_path[-1])
785        for ns in reversed(class_path[:-1]):
786            code('} // namespace $ns')
787        code()
788
789        for param in params:
790            param.cxx_predecls(code)
791        for port in ports.itervalues():
792            port.cxx_predecls(code)
793        code()
794
795        if cls._base:
796            code('#include "params/${{cls._base.type}}.hh"')
797            code()
798
799        for ptype in ptypes:
800            if issubclass(ptype, Enum):
801                code('#include "enums/${{ptype.__name__}}.hh"')
802                code()
803
804        # now generate the actual param struct
805        code("struct ${cls}Params")
806        if cls._base:
807            code("    : public ${{cls._base.type}}Params")
808        code("{")
809        if not hasattr(cls, 'abstract') or not cls.abstract:
810            if 'type' in cls.__dict__:
811                code("    ${{cls.cxx_type}} create();")
812
813        code.indent()
814        if cls == SimObject:
815            code('''
816    SimObjectParams() {}
817    virtual ~SimObjectParams() {}
818
819    std::string name;
820            ''')
821
822        for param in params:
823            param.cxx_decl(code)
824        for port in ports.itervalues():
825            port.cxx_decl(code)
826
827        code.dedent()
828        code('};')
829
830        code()
831        code('#endif // __PARAMS__${cls}__')
832        return code
833
834    # Generate the C++ declaration/definition files for this SimObject's
835    # param struct to allow C++ initialisation
836    def cxx_config_param_file(cls, code, is_header):
837        createCxxConfigDirectoryEntryFile(code, cls.__name__, cls, is_header)
838        return code
839
840# This *temporary* definition is required to support calls from the
841# SimObject class definition to the MetaSimObject methods (in
842# particular _set_param, which gets called for parameters with default
843# values defined on the SimObject class itself).  It will get
844# overridden by the permanent definition (which requires that
845# SimObject be defined) lower in this file.
846def isSimObjectOrVector(value):
847    return False
848
849def cxxMethod(*args, **kwargs):
850    """Decorator to export C++ functions to Python"""
851
852    def decorate(func):
853        name = func.func_name
854        override = kwargs.get("override", False)
855        cxx_name = kwargs.get("cxx_name", name)
856
857        args, varargs, keywords, defaults = inspect.getargspec(func)
858        if varargs or keywords:
859            raise ValueError("Wrapped methods must not contain variable " \
860                             "arguments")
861
862        # Create tuples of (argument, default)
863        if defaults:
864            args = args[:-len(defaults)] + zip(args[-len(defaults):], defaults)
865        # Don't include self in the argument list to PyBind
866        args = args[1:]
867
868
869        @wraps(func)
870        def cxx_call(self, *args, **kwargs):
871            ccobj = self.getCCObject()
872            return getattr(ccobj, name)(*args, **kwargs)
873
874        @wraps(func)
875        def py_call(self, *args, **kwargs):
876            return self.func(*args, **kwargs)
877
878        f = py_call if override else cxx_call
879        f.__pybind = PyBindMethod(name, cxx_name=cxx_name, args=args)
880
881        return f
882
883    if len(args) == 0:
884        return decorate
885    elif len(args) == 1 and len(kwargs) == 0:
886        return decorate(*args)
887    else:
888        raise TypeError("One argument and no kwargs, or only kwargs expected")
889
890# This class holds information about each simobject parameter
891# that should be displayed on the command line for use in the
892# configuration system.
893class ParamInfo(object):
894  def __init__(self, type, desc, type_str, example, default_val, access_str):
895    self.type = type
896    self.desc = desc
897    self.type_str = type_str
898    self.example_str = example
899    self.default_val = default_val
900    # The string representation used to access this param through python.
901    # The method to access this parameter presented on the command line may
902    # be different, so this needs to be stored for later use.
903    self.access_str = access_str
904    self.created = True
905
906  # Make it so we can only set attributes at initialization time
907  # and effectively make this a const object.
908  def __setattr__(self, name, value):
909    if not "created" in self.__dict__:
910      self.__dict__[name] = value
911
912# The SimObject class is the root of the special hierarchy.  Most of
913# the code in this class deals with the configuration hierarchy itself
914# (parent/child node relationships).
915class SimObject(object):
916    # Specify metaclass.  Any class inheriting from SimObject will
917    # get this metaclass.
918    __metaclass__ = MetaSimObject
919    type = 'SimObject'
920    abstract = True
921
922    cxx_header = "sim/sim_object.hh"
923    cxx_bases = [ "Drainable", "Serializable" ]
924    eventq_index = Param.UInt32(Parent.eventq_index, "Event Queue Index")
925
926    cxx_exports = [
927        PyBindMethod("init"),
928        PyBindMethod("initState"),
929        PyBindMethod("memInvalidate"),
930        PyBindMethod("memWriteback"),
931        PyBindMethod("regStats"),
932        PyBindMethod("resetStats"),
933        PyBindMethod("regProbePoints"),
934        PyBindMethod("regProbeListeners"),
935        PyBindMethod("startup"),
936    ]
937
938    cxx_param_exports = [
939        PyBindProperty("name"),
940    ]
941
942    @cxxMethod
943    def loadState(self, cp):
944        """Load SimObject state from a checkpoint"""
945        pass
946
947    # Returns a dict of all the option strings that can be
948    # generated as command line options for this simobject instance
949    # by tracing all reachable params in the top level instance and
950    # any children it contains.
951    def enumerateParams(self, flags_dict = {},
952                        cmd_line_str = "", access_str = ""):
953        if hasattr(self, "_paramEnumed"):
954            print "Cycle detected enumerating params"
955        else:
956            self._paramEnumed = True
957            # Scan the children first to pick up all the objects in this SimObj
958            for keys in self._children:
959                child = self._children[keys]
960                next_cmdline_str = cmd_line_str + keys
961                next_access_str = access_str + keys
962                if not isSimObjectVector(child):
963                    next_cmdline_str = next_cmdline_str + "."
964                    next_access_str = next_access_str + "."
965                flags_dict = child.enumerateParams(flags_dict,
966                                                   next_cmdline_str,
967                                                   next_access_str)
968
969            # Go through the simple params in the simobject in this level
970            # of the simobject hierarchy and save information about the
971            # parameter to be used for generating and processing command line
972            # options to the simulator to set these parameters.
973            for keys,values in self._params.items():
974                if values.isCmdLineSettable():
975                    type_str = ''
976                    ex_str = values.example_str()
977                    ptype = None
978                    if isinstance(values, VectorParamDesc):
979                        type_str = 'Vector_%s' % values.ptype_str
980                        ptype = values
981                    else:
982                        type_str = '%s' % values.ptype_str
983                        ptype = values.ptype
984
985                    if keys in self._hr_values\
986                       and keys in self._values\
987                       and not isinstance(self._values[keys],
988                                          m5.proxy.BaseProxy):
989                        cmd_str = cmd_line_str + keys
990                        acc_str = access_str + keys
991                        flags_dict[cmd_str] = ParamInfo(ptype,
992                                    self._params[keys].desc, type_str, ex_str,
993                                    values.pretty_print(self._hr_values[keys]),
994                                    acc_str)
995                    elif not keys in self._hr_values\
996                         and not keys in self._values:
997                        # Empty param
998                        cmd_str = cmd_line_str + keys
999                        acc_str = access_str + keys
1000                        flags_dict[cmd_str] = ParamInfo(ptype,
1001                                    self._params[keys].desc,
1002                                    type_str, ex_str, '', acc_str)
1003
1004        return flags_dict
1005
1006    # Initialize new instance.  For objects with SimObject-valued
1007    # children, we need to recursively clone the classes represented
1008    # by those param values as well in a consistent "deep copy"-style
1009    # fashion.  That is, we want to make sure that each instance is
1010    # cloned only once, and that if there are multiple references to
1011    # the same original object, we end up with the corresponding
1012    # cloned references all pointing to the same cloned instance.
1013    def __init__(self, **kwargs):
1014        ancestor = kwargs.get('_ancestor')
1015        memo_dict = kwargs.get('_memo')
1016        if memo_dict is None:
1017            # prepare to memoize any recursively instantiated objects
1018            memo_dict = {}
1019        elif ancestor:
1020            # memoize me now to avoid problems with recursive calls
1021            memo_dict[ancestor] = self
1022
1023        if not ancestor:
1024            ancestor = self.__class__
1025        ancestor._instantiated = True
1026
1027        # initialize required attributes
1028        self._parent = None
1029        self._name = None
1030        self._ccObject = None  # pointer to C++ object
1031        self._ccParams = None
1032        self._instantiated = False # really "cloned"
1033
1034        # Clone children specified at class level.  No need for a
1035        # multidict here since we will be cloning everything.
1036        # Do children before parameter values so that children that
1037        # are also param values get cloned properly.
1038        self._children = {}
1039        for key,val in ancestor._children.iteritems():
1040            self.add_child(key, val(_memo=memo_dict))
1041
1042        # Inherit parameter values from class using multidict so
1043        # individual value settings can be overridden but we still
1044        # inherit late changes to non-overridden class values.
1045        self._values = multidict(ancestor._values)
1046        self._hr_values = multidict(ancestor._hr_values)
1047        # clone SimObject-valued parameters
1048        for key,val in ancestor._values.iteritems():
1049            val = tryAsSimObjectOrVector(val)
1050            if val is not None:
1051                self._values[key] = val(_memo=memo_dict)
1052
1053        # clone port references.  no need to use a multidict here
1054        # since we will be creating new references for all ports.
1055        self._port_refs = {}
1056        for key,val in ancestor._port_refs.iteritems():
1057            self._port_refs[key] = val.clone(self, memo_dict)
1058        # apply attribute assignments from keyword args, if any
1059        for key,val in kwargs.iteritems():
1060            setattr(self, key, val)
1061
1062    # "Clone" the current instance by creating another instance of
1063    # this instance's class, but that inherits its parameter values
1064    # and port mappings from the current instance.  If we're in a
1065    # "deep copy" recursive clone, check the _memo dict to see if
1066    # we've already cloned this instance.
1067    def __call__(self, **kwargs):
1068        memo_dict = kwargs.get('_memo')
1069        if memo_dict is None:
1070            # no memo_dict: must be top-level clone operation.
1071            # this is only allowed at the root of a hierarchy
1072            if self._parent:
1073                raise RuntimeError, "attempt to clone object %s " \
1074                      "not at the root of a tree (parent = %s)" \
1075                      % (self, self._parent)
1076            # create a new dict and use that.
1077            memo_dict = {}
1078            kwargs['_memo'] = memo_dict
1079        elif memo_dict.has_key(self):
1080            # clone already done & memoized
1081            return memo_dict[self]
1082        return self.__class__(_ancestor = self, **kwargs)
1083
1084    def _get_port_ref(self, attr):
1085        # Return reference that can be assigned to another port
1086        # via __setattr__.  There is only ever one reference
1087        # object per port, but we create them lazily here.
1088        ref = self._port_refs.get(attr)
1089        if ref == None:
1090            ref = self._ports[attr].makeRef(self)
1091            self._port_refs[attr] = ref
1092        return ref
1093
1094    def __getattr__(self, attr):
1095        if self._ports.has_key(attr):
1096            return self._get_port_ref(attr)
1097
1098        if self._values.has_key(attr):
1099            return self._values[attr]
1100
1101        if self._children.has_key(attr):
1102            return self._children[attr]
1103
1104        # If the attribute exists on the C++ object, transparently
1105        # forward the reference there.  This is typically used for
1106        # methods exported to Python (e.g., init(), and startup())
1107        if self._ccObject and hasattr(self._ccObject, attr):
1108            return getattr(self._ccObject, attr)
1109
1110        err_string = "object '%s' has no attribute '%s'" \
1111              % (self.__class__.__name__, attr)
1112
1113        if not self._ccObject:
1114            err_string += "\n  (C++ object is not yet constructed," \
1115                          " so wrapped C++ methods are unavailable.)"
1116
1117        raise AttributeError, err_string
1118
1119    # Set attribute (called on foo.attr = value when foo is an
1120    # instance of class cls).
1121    def __setattr__(self, attr, value):
1122        # normal processing for private attributes
1123        if attr.startswith('_'):
1124            object.__setattr__(self, attr, value)
1125            return
1126
1127        if self._ports.has_key(attr):
1128            # set up port connection
1129            self._get_port_ref(attr).connect(value)
1130            return
1131
1132        param = self._params.get(attr)
1133        if param:
1134            try:
1135                hr_value = value
1136                value = param.convert(value)
1137            except Exception, e:
1138                msg = "%s\nError setting param %s.%s to %s\n" % \
1139                      (e, self.__class__.__name__, attr, value)
1140                e.args = (msg, )
1141                raise
1142            self._values[attr] = value
1143            # implicitly parent unparented objects assigned as params
1144            if isSimObjectOrVector(value) and not value.has_parent():
1145                self.add_child(attr, value)
1146            # set the human-readable value dict if this is a param
1147            # with a literal value and is not being set as an object
1148            # or proxy.
1149            if not (isSimObjectOrVector(value) or\
1150                    isinstance(value, m5.proxy.BaseProxy)):
1151                self._hr_values[attr] = hr_value
1152
1153            return
1154
1155        # if RHS is a SimObject, it's an implicit child assignment
1156        if isSimObjectOrSequence(value):
1157            self.add_child(attr, value)
1158            return
1159
1160        # no valid assignment... raise exception
1161        raise AttributeError, "Class %s has no parameter %s" \
1162              % (self.__class__.__name__, attr)
1163
1164
1165    # this hack allows tacking a '[0]' onto parameters that may or may
1166    # not be vectors, and always getting the first element (e.g. cpus)
1167    def __getitem__(self, key):
1168        if key == 0:
1169            return self
1170        raise IndexError, "Non-zero index '%s' to SimObject" % key
1171
1172    # this hack allows us to iterate over a SimObject that may
1173    # not be a vector, so we can call a loop over it and get just one
1174    # element.
1175    def __len__(self):
1176        return 1
1177
1178    # Also implemented by SimObjectVector
1179    def clear_parent(self, old_parent):
1180        assert self._parent is old_parent
1181        self._parent = None
1182
1183    # Also implemented by SimObjectVector
1184    def set_parent(self, parent, name):
1185        self._parent = parent
1186        self._name = name
1187
1188    # Return parent object of this SimObject, not implemented by
1189    # SimObjectVector because the elements in a SimObjectVector may not share
1190    # the same parent
1191    def get_parent(self):
1192        return self._parent
1193
1194    # Also implemented by SimObjectVector
1195    def get_name(self):
1196        return self._name
1197
1198    # Also implemented by SimObjectVector
1199    def has_parent(self):
1200        return self._parent is not None
1201
1202    # clear out child with given name. This code is not likely to be exercised.
1203    # See comment in add_child.
1204    def clear_child(self, name):
1205        child = self._children[name]
1206        child.clear_parent(self)
1207        del self._children[name]
1208
1209    # Add a new child to this object.
1210    def add_child(self, name, child):
1211        child = coerceSimObjectOrVector(child)
1212        if child.has_parent():
1213            warn("add_child('%s'): child '%s' already has parent", name,
1214                child.get_name())
1215        if self._children.has_key(name):
1216            # This code path had an undiscovered bug that would make it fail
1217            # at runtime. It had been here for a long time and was only
1218            # exposed by a buggy script. Changes here will probably not be
1219            # exercised without specialized testing.
1220            self.clear_child(name)
1221        child.set_parent(self, name)
1222        self._children[name] = child
1223
1224    # Take SimObject-valued parameters that haven't been explicitly
1225    # assigned as children and make them children of the object that
1226    # they were assigned to as a parameter value.  This guarantees
1227    # that when we instantiate all the parameter objects we're still
1228    # inside the configuration hierarchy.
1229    def adoptOrphanParams(self):
1230        for key,val in self._values.iteritems():
1231            if not isSimObjectVector(val) and isSimObjectSequence(val):
1232                # need to convert raw SimObject sequences to
1233                # SimObjectVector class so we can call has_parent()
1234                val = SimObjectVector(val)
1235                self._values[key] = val
1236            if isSimObjectOrVector(val) and not val.has_parent():
1237                warn("%s adopting orphan SimObject param '%s'", self, key)
1238                self.add_child(key, val)
1239
1240    def path(self):
1241        if not self._parent:
1242            return '<orphan %s>' % self.__class__
1243        elif isinstance(self._parent, MetaSimObject):
1244            return str(self.__class__)
1245
1246        ppath = self._parent.path()
1247        if ppath == 'root':
1248            return self._name
1249        return ppath + "." + self._name
1250
1251    def __str__(self):
1252        return self.path()
1253
1254    def config_value(self):
1255        return self.path()
1256
1257    def ini_str(self):
1258        return self.path()
1259
1260    def find_any(self, ptype):
1261        if isinstance(self, ptype):
1262            return self, True
1263
1264        found_obj = None
1265        for child in self._children.itervalues():
1266            visited = False
1267            if hasattr(child, '_visited'):
1268              visited = getattr(child, '_visited')
1269
1270            if isinstance(child, ptype) and not visited:
1271                if found_obj != None and child != found_obj:
1272                    raise AttributeError, \
1273                          'parent.any matched more than one: %s %s' % \
1274                          (found_obj.path, child.path)
1275                found_obj = child
1276        # search param space
1277        for pname,pdesc in self._params.iteritems():
1278            if issubclass(pdesc.ptype, ptype):
1279                match_obj = self._values[pname]
1280                if found_obj != None and found_obj != match_obj:
1281                    raise AttributeError, \
1282                          'parent.any matched more than one: %s and %s' % \
1283                          (found_obj.path, match_obj.path)
1284                found_obj = match_obj
1285        return found_obj, found_obj != None
1286
1287    def find_all(self, ptype):
1288        all = {}
1289        # search children
1290        for child in self._children.itervalues():
1291            # a child could be a list, so ensure we visit each item
1292            if isinstance(child, list):
1293                children = child
1294            else:
1295                children = [child]
1296
1297            for child in children:
1298                if isinstance(child, ptype) and not isproxy(child) and \
1299                        not isNullPointer(child):
1300                    all[child] = True
1301                if isSimObject(child):
1302                    # also add results from the child itself
1303                    child_all, done = child.find_all(ptype)
1304                    all.update(dict(zip(child_all, [done] * len(child_all))))
1305        # search param space
1306        for pname,pdesc in self._params.iteritems():
1307            if issubclass(pdesc.ptype, ptype):
1308                match_obj = self._values[pname]
1309                if not isproxy(match_obj) and not isNullPointer(match_obj):
1310                    all[match_obj] = True
1311        # Also make sure to sort the keys based on the objects' path to
1312        # ensure that the order is the same on all hosts
1313        return sorted(all.keys(), key = lambda o: o.path()), True
1314
1315    def unproxy(self, base):
1316        return self
1317
1318    def unproxyParams(self):
1319        for param in self._params.iterkeys():
1320            value = self._values.get(param)
1321            if value != None and isproxy(value):
1322                try:
1323                    value = value.unproxy(self)
1324                except:
1325                    print "Error in unproxying param '%s' of %s" % \
1326                          (param, self.path())
1327                    raise
1328                setattr(self, param, value)
1329
1330        # Unproxy ports in sorted order so that 'append' operations on
1331        # vector ports are done in a deterministic fashion.
1332        port_names = self._ports.keys()
1333        port_names.sort()
1334        for port_name in port_names:
1335            port = self._port_refs.get(port_name)
1336            if port != None:
1337                port.unproxy(self)
1338
1339    def print_ini(self, ini_file):
1340        print >>ini_file, '[' + self.path() + ']'       # .ini section header
1341
1342        instanceDict[self.path()] = self
1343
1344        if hasattr(self, 'type'):
1345            print >>ini_file, 'type=%s' % self.type
1346
1347        if len(self._children.keys()):
1348            print >>ini_file, 'children=%s' % \
1349                  ' '.join(self._children[n].get_name() \
1350                  for n in sorted(self._children.keys()))
1351
1352        for param in sorted(self._params.keys()):
1353            value = self._values.get(param)
1354            if value != None:
1355                print >>ini_file, '%s=%s' % (param,
1356                                             self._values[param].ini_str())
1357
1358        for port_name in sorted(self._ports.keys()):
1359            port = self._port_refs.get(port_name, None)
1360            if port != None:
1361                print >>ini_file, '%s=%s' % (port_name, port.ini_str())
1362
1363        print >>ini_file        # blank line between objects
1364
1365    # generate a tree of dictionaries expressing all the parameters in the
1366    # instantiated system for use by scripts that want to do power, thermal
1367    # visualization, and other similar tasks
1368    def get_config_as_dict(self):
1369        d = attrdict()
1370        if hasattr(self, 'type'):
1371            d.type = self.type
1372        if hasattr(self, 'cxx_class'):
1373            d.cxx_class = self.cxx_class
1374        # Add the name and path of this object to be able to link to
1375        # the stats
1376        d.name = self.get_name()
1377        d.path = self.path()
1378
1379        for param in sorted(self._params.keys()):
1380            value = self._values.get(param)
1381            if value != None:
1382                d[param] = value.config_value()
1383
1384        for n in sorted(self._children.keys()):
1385            child = self._children[n]
1386            # Use the name of the attribute (and not get_name()) as
1387            # the key in the JSON dictionary to capture the hierarchy
1388            # in the Python code that assembled this system
1389            d[n] = child.get_config_as_dict()
1390
1391        for port_name in sorted(self._ports.keys()):
1392            port = self._port_refs.get(port_name, None)
1393            if port != None:
1394                # Represent each port with a dictionary containing the
1395                # prominent attributes
1396                d[port_name] = port.get_config_as_dict()
1397
1398        return d
1399
1400    def getCCParams(self):
1401        if self._ccParams:
1402            return self._ccParams
1403
1404        cc_params_struct = getattr(m5.internal.params, '%sParams' % self.type)
1405        cc_params = cc_params_struct()
1406        cc_params.name = str(self)
1407
1408        param_names = self._params.keys()
1409        param_names.sort()
1410        for param in param_names:
1411            value = self._values.get(param)
1412            if value is None:
1413                fatal("%s.%s without default or user set value",
1414                      self.path(), param)
1415
1416            value = value.getValue()
1417            if isinstance(self._params[param], VectorParamDesc):
1418                assert isinstance(value, list)
1419                vec = getattr(cc_params, param)
1420                assert not len(vec)
1421                setattr(cc_params, param, list(value))
1422            else:
1423                setattr(cc_params, param, value)
1424
1425        port_names = self._ports.keys()
1426        port_names.sort()
1427        for port_name in port_names:
1428            port = self._port_refs.get(port_name, None)
1429            if port != None:
1430                port_count = len(port)
1431            else:
1432                port_count = 0
1433            setattr(cc_params, 'port_' + port_name + '_connection_count',
1434                    port_count)
1435        self._ccParams = cc_params
1436        return self._ccParams
1437
1438    # Get C++ object corresponding to this object, calling C++ if
1439    # necessary to construct it.  Does *not* recursively create
1440    # children.
1441    def getCCObject(self):
1442        if not self._ccObject:
1443            # Make sure this object is in the configuration hierarchy
1444            if not self._parent and not isRoot(self):
1445                raise RuntimeError, "Attempt to instantiate orphan node"
1446            # Cycles in the configuration hierarchy are not supported. This
1447            # will catch the resulting recursion and stop.
1448            self._ccObject = -1
1449            if not self.abstract:
1450                params = self.getCCParams()
1451                self._ccObject = params.create()
1452        elif self._ccObject == -1:
1453            raise RuntimeError, "%s: Cycle found in configuration hierarchy." \
1454                  % self.path()
1455        return self._ccObject
1456
1457    def descendants(self):
1458        yield self
1459        # The order of the dict is implementation dependent, so sort
1460        # it based on the key (name) to ensure the order is the same
1461        # on all hosts
1462        for (name, child) in sorted(self._children.iteritems()):
1463            for obj in child.descendants():
1464                yield obj
1465
1466    # Call C++ to create C++ object corresponding to this object
1467    def createCCObject(self):
1468        self.getCCParams()
1469        self.getCCObject() # force creation
1470
1471    def getValue(self):
1472        return self.getCCObject()
1473
1474    # Create C++ port connections corresponding to the connections in
1475    # _port_refs
1476    def connectPorts(self):
1477        # Sort the ports based on their attribute name to ensure the
1478        # order is the same on all hosts
1479        for (attr, portRef) in sorted(self._port_refs.iteritems()):
1480            portRef.ccConnect()
1481
1482# Function to provide to C++ so it can look up instances based on paths
1483def resolveSimObject(name):
1484    obj = instanceDict[name]
1485    return obj.getCCObject()
1486
1487def isSimObject(value):
1488    return isinstance(value, SimObject)
1489
1490def isSimObjectClass(value):
1491    return issubclass(value, SimObject)
1492
1493def isSimObjectVector(value):
1494    return isinstance(value, SimObjectVector)
1495
1496def isSimObjectSequence(value):
1497    if not isinstance(value, (list, tuple)) or len(value) == 0:
1498        return False
1499
1500    for val in value:
1501        if not isNullPointer(val) and not isSimObject(val):
1502            return False
1503
1504    return True
1505
1506def isSimObjectOrSequence(value):
1507    return isSimObject(value) or isSimObjectSequence(value)
1508
1509def isRoot(obj):
1510    from m5.objects import Root
1511    return obj and obj is Root.getInstance()
1512
1513def isSimObjectOrVector(value):
1514    return isSimObject(value) or isSimObjectVector(value)
1515
1516def tryAsSimObjectOrVector(value):
1517    if isSimObjectOrVector(value):
1518        return value
1519    if isSimObjectSequence(value):
1520        return SimObjectVector(value)
1521    return None
1522
1523def coerceSimObjectOrVector(value):
1524    value = tryAsSimObjectOrVector(value)
1525    if value is None:
1526        raise TypeError, "SimObject or SimObjectVector expected"
1527    return value
1528
1529baseClasses = allClasses.copy()
1530baseInstances = instanceDict.copy()
1531
1532def clear():
1533    global allClasses, instanceDict, noCxxHeader
1534
1535    allClasses = baseClasses.copy()
1536    instanceDict = baseInstances.copy()
1537    noCxxHeader = False
1538
1539# __all__ defines the list of symbols that get exported when
1540# 'from config import *' is invoked.  Try to keep this reasonably
1541# short to avoid polluting other namespaces.
1542__all__ = [
1543    'SimObject',
1544    'cxxMethod',
1545    'PyBindMethod',
1546    'PyBindProperty',
1547]
1548