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