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