| 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#
|
1# Copyright (c) 2004-2006 The Regents of The University of Michigan 2# Copyright (c) 2010 Advanced Micro Devices, Inc. 3# All rights reserved. 4# 5# Redistribution and use in source and binary forms, with or without 6# modification, are permitted provided that the following conditions are 7# met: redistributions of source code must retain the above copyright 8# notice, this list of conditions and the following disclaimer; 9# redistributions in binary form must reproduce the above copyright 10# notice, this list of conditions and the following disclaimer in the 11# documentation and/or other materials provided with the distribution; 12# neither the name of the copyright holders nor the names of its 13# contributors may be used to endorse or promote products derived from 14# this software without specific prior written permission. 15# 16# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 18# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 19# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 20# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 21# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 22# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 23# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 26# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27# 28# Authors: Steve Reinhardt 29# Nathan Binkert
| 13# Copyright (c) 2004-2006 The Regents of The University of Michigan 14# Copyright (c) 2010 Advanced Micro Devices, Inc. 15# All rights reserved. 16# 17# Redistribution and use in source and binary forms, with or without 18# modification, are permitted provided that the following conditions are 19# met: redistributions of source code must retain the above copyright 20# notice, this list of conditions and the following disclaimer; 21# redistributions in binary form must reproduce the above copyright 22# notice, this list of conditions and the following disclaimer in the 23# documentation and/or other materials provided with the distribution; 24# neither the name of the copyright holders nor the names of its 25# contributors may be used to endorse or promote products derived from 26# this software without specific prior written permission. 27# 28# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 29# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 30# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 31# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 32# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 33# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 34# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 35# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 36# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 37# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 38# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 39# 40# Authors: Steve Reinhardt 41# Nathan Binkert
|
| 42# Andreas Hansson
|
30 31import sys 32from types import FunctionType, MethodType, ModuleType 33 34try: 35 import pydot 36except: 37 pydot = False 38 39import m5 40from m5.util import * 41 42# Have to import params up top since Param is referenced on initial 43# load (when SimObject class references Param to create a class 44# variable, the 'name' param)... 45from m5.params import * 46# There are a few things we need that aren't in params.__all__ since 47# normal users don't need them 48from m5.params import ParamDesc, VectorParamDesc, \ 49 isNullPointer, SimObjectVector, Port 50 51from m5.proxy import * 52from m5.proxy import isproxy 53 54##################################################################### 55# 56# M5 Python Configuration Utility 57# 58# The basic idea is to write simple Python programs that build Python 59# objects corresponding to M5 SimObjects for the desired simulation 60# configuration. For now, the Python emits a .ini file that can be 61# parsed by M5. In the future, some tighter integration between M5 62# and the Python interpreter may allow bypassing the .ini file. 63# 64# Each SimObject class in M5 is represented by a Python class with the 65# same name. The Python inheritance tree mirrors the M5 C++ tree 66# (e.g., SimpleCPU derives from BaseCPU in both cases, and all 67# SimObjects inherit from a single SimObject base class). To specify 68# an instance of an M5 SimObject in a configuration, the user simply 69# instantiates the corresponding Python object. The parameters for 70# that SimObject are given by assigning to attributes of the Python 71# object, either using keyword assignment in the constructor or in 72# separate assignment statements. For example: 73# 74# cache = BaseCache(size='64KB') 75# cache.hit_latency = 3 76# cache.assoc = 8 77# 78# The magic lies in the mapping of the Python attributes for SimObject 79# classes to the actual SimObject parameter specifications. This 80# allows parameter validity checking in the Python code. Continuing 81# the example above, the statements "cache.blurfl=3" or 82# "cache.assoc='hello'" would both result in runtime errors in Python, 83# since the BaseCache object has no 'blurfl' parameter and the 'assoc' 84# parameter requires an integer, respectively. This magic is done 85# primarily by overriding the special __setattr__ method that controls 86# assignment to object attributes. 87# 88# Once a set of Python objects have been instantiated in a hierarchy, 89# calling 'instantiate(obj)' (where obj is the root of the hierarchy) 90# will generate a .ini file. 91# 92##################################################################### 93 94# list of all SimObject classes 95allClasses = {} 96 97# dict to look up SimObjects based on path 98instanceDict = {} 99 100def public_value(key, value): 101 return key.startswith('_') or \ 102 isinstance(value, (FunctionType, MethodType, ModuleType, 103 classmethod, type)) 104 105# The metaclass for SimObject. This class controls how new classes 106# that derive from SimObject are instantiated, and provides inherited 107# class behavior (just like a class controls how instances of that 108# class are instantiated, and provides inherited instance behavior). 109class MetaSimObject(type): 110 # Attributes that can be set only at initialization time 111 init_keywords = { 'abstract' : bool, 112 'cxx_class' : str, 113 'cxx_type' : str, 114 'type' : str } 115 # Attributes that can be set any time 116 keywords = { 'check' : FunctionType } 117 118 # __new__ is called before __init__, and is where the statements 119 # in the body of the class definition get loaded into the class's 120 # __dict__. We intercept this to filter out parameter & port assignments 121 # and only allow "private" attributes to be passed to the base 122 # __new__ (starting with underscore). 123 def __new__(mcls, name, bases, dict): 124 assert name not in allClasses, "SimObject %s already present" % name 125 126 # Copy "private" attributes, functions, and classes to the 127 # official dict. Everything else goes in _init_dict to be 128 # filtered in __init__. 129 cls_dict = {} 130 value_dict = {} 131 for key,val in dict.items(): 132 if public_value(key, val): 133 cls_dict[key] = val 134 else: 135 # must be a param/port setting 136 value_dict[key] = val 137 if 'abstract' not in value_dict: 138 value_dict['abstract'] = False 139 cls_dict['_value_dict'] = value_dict 140 cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict) 141 if 'type' in value_dict: 142 allClasses[name] = cls 143 return cls 144 145 # subclass initialization 146 def __init__(cls, name, bases, dict): 147 # calls type.__init__()... I think that's a no-op, but leave 148 # it here just in case it's not. 149 super(MetaSimObject, cls).__init__(name, bases, dict) 150 151 # initialize required attributes 152 153 # class-only attributes 154 cls._params = multidict() # param descriptions 155 cls._ports = multidict() # port descriptions 156 157 # class or instance attributes 158 cls._values = multidict() # param values 159 cls._children = multidict() # SimObject children 160 cls._port_refs = multidict() # port ref objects 161 cls._instantiated = False # really instantiated, cloned, or subclassed 162 163 # We don't support multiple inheritance. If you want to, you 164 # must fix multidict to deal with it properly. 165 if len(bases) > 1: 166 raise TypeError, "SimObjects do not support multiple inheritance" 167 168 base = bases[0] 169 170 # Set up general inheritance via multidicts. A subclass will 171 # inherit all its settings from the base class. The only time 172 # the following is not true is when we define the SimObject 173 # class itself (in which case the multidicts have no parent). 174 if isinstance(base, MetaSimObject): 175 cls._base = base 176 cls._params.parent = base._params 177 cls._ports.parent = base._ports 178 cls._values.parent = base._values 179 cls._children.parent = base._children 180 cls._port_refs.parent = base._port_refs 181 # mark base as having been subclassed 182 base._instantiated = True 183 else: 184 cls._base = None 185 186 # default keyword values 187 if 'type' in cls._value_dict: 188 if 'cxx_class' not in cls._value_dict: 189 cls._value_dict['cxx_class'] = cls._value_dict['type'] 190 191 cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class'] 192 193 # Export methods are automatically inherited via C++, so we 194 # don't want the method declarations to get inherited on the 195 # python side (and thus end up getting repeated in the wrapped 196 # versions of derived classes). The code below basicallly 197 # suppresses inheritance by substituting in the base (null) 198 # versions of these methods unless a different version is 199 # explicitly supplied. 200 for method_name in ('export_methods', 'export_method_cxx_predecls', 201 'export_method_swig_predecls'): 202 if method_name not in cls.__dict__: 203 base_method = getattr(MetaSimObject, method_name) 204 m = MethodType(base_method, cls, MetaSimObject) 205 setattr(cls, method_name, m) 206 207 # Now process the _value_dict items. They could be defining 208 # new (or overriding existing) parameters or ports, setting 209 # class keywords (e.g., 'abstract'), or setting parameter 210 # values or port bindings. The first 3 can only be set when 211 # the class is defined, so we handle them here. The others 212 # can be set later too, so just emulate that by calling 213 # setattr(). 214 for key,val in cls._value_dict.items(): 215 # param descriptions 216 if isinstance(val, ParamDesc): 217 cls._new_param(key, val) 218 219 # port objects 220 elif isinstance(val, Port): 221 cls._new_port(key, val) 222 223 # init-time-only keywords 224 elif cls.init_keywords.has_key(key): 225 cls._set_keyword(key, val, cls.init_keywords[key]) 226 227 # default: use normal path (ends up in __setattr__) 228 else: 229 setattr(cls, key, val) 230 231 def _set_keyword(cls, keyword, val, kwtype): 232 if not isinstance(val, kwtype): 233 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \ 234 (keyword, type(val), kwtype) 235 if isinstance(val, FunctionType): 236 val = classmethod(val) 237 type.__setattr__(cls, keyword, val) 238 239 def _new_param(cls, name, pdesc): 240 # each param desc should be uniquely assigned to one variable 241 assert(not hasattr(pdesc, 'name')) 242 pdesc.name = name 243 cls._params[name] = pdesc 244 if hasattr(pdesc, 'default'): 245 cls._set_param(name, pdesc.default, pdesc) 246 247 def _set_param(cls, name, value, param): 248 assert(param.name == name) 249 try: 250 value = param.convert(value) 251 except Exception, e: 252 msg = "%s\nError setting param %s.%s to %s\n" % \ 253 (e, cls.__name__, name, value) 254 e.args = (msg, ) 255 raise 256 cls._values[name] = value 257 # if param value is a SimObject, make it a child too, so that 258 # it gets cloned properly when the class is instantiated 259 if isSimObjectOrVector(value) and not value.has_parent(): 260 cls._add_cls_child(name, value) 261 262 def _add_cls_child(cls, name, child): 263 # It's a little funky to have a class as a parent, but these 264 # objects should never be instantiated (only cloned, which 265 # clears the parent pointer), and this makes it clear that the 266 # object is not an orphan and can provide better error 267 # messages. 268 child.set_parent(cls, name) 269 cls._children[name] = child 270 271 def _new_port(cls, name, port): 272 # each port should be uniquely assigned to one variable 273 assert(not hasattr(port, 'name')) 274 port.name = name 275 cls._ports[name] = port 276 277 # same as _get_port_ref, effectively, but for classes 278 def _cls_get_port_ref(cls, attr): 279 # Return reference that can be assigned to another port 280 # via __setattr__. There is only ever one reference 281 # object per port, but we create them lazily here. 282 ref = cls._port_refs.get(attr) 283 if not ref: 284 ref = cls._ports[attr].makeRef(cls) 285 cls._port_refs[attr] = ref 286 return ref 287 288 # Set attribute (called on foo.attr = value when foo is an 289 # instance of class cls). 290 def __setattr__(cls, attr, value): 291 # normal processing for private attributes 292 if public_value(attr, value): 293 type.__setattr__(cls, attr, value) 294 return 295 296 if cls.keywords.has_key(attr): 297 cls._set_keyword(attr, value, cls.keywords[attr]) 298 return 299 300 if cls._ports.has_key(attr): 301 cls._cls_get_port_ref(attr).connect(value) 302 return 303 304 if isSimObjectOrSequence(value) and cls._instantiated: 305 raise RuntimeError, \ 306 "cannot set SimObject parameter '%s' after\n" \ 307 " class %s has been instantiated or subclassed" \ 308 % (attr, cls.__name__) 309 310 # check for param 311 param = cls._params.get(attr) 312 if param: 313 cls._set_param(attr, value, param) 314 return 315 316 if isSimObjectOrSequence(value): 317 # If RHS is a SimObject, it's an implicit child assignment. 318 cls._add_cls_child(attr, coerceSimObjectOrVector(value)) 319 return 320 321 # no valid assignment... raise exception 322 raise AttributeError, \ 323 "Class %s has no parameter \'%s\'" % (cls.__name__, attr) 324 325 def __getattr__(cls, attr): 326 if attr == 'cxx_class_path': 327 return cls.cxx_class.split('::') 328 329 if attr == 'cxx_class_name': 330 return cls.cxx_class_path[-1] 331 332 if attr == 'cxx_namespaces': 333 return cls.cxx_class_path[:-1] 334 335 if cls._values.has_key(attr): 336 return cls._values[attr] 337 338 if cls._children.has_key(attr): 339 return cls._children[attr] 340 341 raise AttributeError, \ 342 "object '%s' has no attribute '%s'" % (cls.__name__, attr) 343 344 def __str__(cls): 345 return cls.__name__ 346 347 # See ParamValue.cxx_predecls for description. 348 def cxx_predecls(cls, code): 349 code('#include "params/$cls.hh"') 350 351 # See ParamValue.swig_predecls for description. 352 def swig_predecls(cls, code): 353 code('%import "python/m5/internal/param_$cls.i"') 354 355 # Hook for exporting additional C++ methods to Python via SWIG. 356 # Default is none, override using @classmethod in class definition. 357 def export_methods(cls, code): 358 pass 359 360 # Generate the code needed as a prerequisite for the C++ methods 361 # exported via export_methods() to be compiled in the _wrap.cc 362 # file. Typically generates one or more #include statements. If 363 # any methods are exported, typically at least the C++ header 364 # declaring the relevant SimObject class must be included. 365 def export_method_cxx_predecls(cls, code): 366 pass 367 368 # Generate the code needed as a prerequisite for the C++ methods 369 # exported via export_methods() to be processed by SWIG. 370 # Typically generates one or more %include or %import statements. 371 # If any methods are exported, typically at least the C++ header 372 # declaring the relevant SimObject class must be included. 373 def export_method_swig_predecls(cls, code): 374 pass 375 376 # Generate the declaration for this object for wrapping with SWIG. 377 # Generates code that goes into a SWIG .i file. Called from 378 # src/SConscript. 379 def swig_decl(cls, code): 380 class_path = cls.cxx_class.split('::') 381 classname = class_path[-1] 382 namespaces = class_path[:-1] 383 384 # The 'local' attribute restricts us to the params declared in 385 # the object itself, not including inherited params (which 386 # will also be inherited from the base class's param struct 387 # here). 388 params = cls._params.local.values()
| 43 44import sys 45from types import FunctionType, MethodType, ModuleType 46 47try: 48 import pydot 49except: 50 pydot = False 51 52import m5 53from m5.util import * 54 55# Have to import params up top since Param is referenced on initial 56# load (when SimObject class references Param to create a class 57# variable, the 'name' param)... 58from m5.params import * 59# There are a few things we need that aren't in params.__all__ since 60# normal users don't need them 61from m5.params import ParamDesc, VectorParamDesc, \ 62 isNullPointer, SimObjectVector, Port 63 64from m5.proxy import * 65from m5.proxy import isproxy 66 67##################################################################### 68# 69# M5 Python Configuration Utility 70# 71# The basic idea is to write simple Python programs that build Python 72# objects corresponding to M5 SimObjects for the desired simulation 73# configuration. For now, the Python emits a .ini file that can be 74# parsed by M5. In the future, some tighter integration between M5 75# and the Python interpreter may allow bypassing the .ini file. 76# 77# Each SimObject class in M5 is represented by a Python class with the 78# same name. The Python inheritance tree mirrors the M5 C++ tree 79# (e.g., SimpleCPU derives from BaseCPU in both cases, and all 80# SimObjects inherit from a single SimObject base class). To specify 81# an instance of an M5 SimObject in a configuration, the user simply 82# instantiates the corresponding Python object. The parameters for 83# that SimObject are given by assigning to attributes of the Python 84# object, either using keyword assignment in the constructor or in 85# separate assignment statements. For example: 86# 87# cache = BaseCache(size='64KB') 88# cache.hit_latency = 3 89# cache.assoc = 8 90# 91# The magic lies in the mapping of the Python attributes for SimObject 92# classes to the actual SimObject parameter specifications. This 93# allows parameter validity checking in the Python code. Continuing 94# the example above, the statements "cache.blurfl=3" or 95# "cache.assoc='hello'" would both result in runtime errors in Python, 96# since the BaseCache object has no 'blurfl' parameter and the 'assoc' 97# parameter requires an integer, respectively. This magic is done 98# primarily by overriding the special __setattr__ method that controls 99# assignment to object attributes. 100# 101# Once a set of Python objects have been instantiated in a hierarchy, 102# calling 'instantiate(obj)' (where obj is the root of the hierarchy) 103# will generate a .ini file. 104# 105##################################################################### 106 107# list of all SimObject classes 108allClasses = {} 109 110# dict to look up SimObjects based on path 111instanceDict = {} 112 113def public_value(key, value): 114 return key.startswith('_') or \ 115 isinstance(value, (FunctionType, MethodType, ModuleType, 116 classmethod, type)) 117 118# The metaclass for SimObject. This class controls how new classes 119# that derive from SimObject are instantiated, and provides inherited 120# class behavior (just like a class controls how instances of that 121# class are instantiated, and provides inherited instance behavior). 122class MetaSimObject(type): 123 # Attributes that can be set only at initialization time 124 init_keywords = { 'abstract' : bool, 125 'cxx_class' : str, 126 'cxx_type' : str, 127 'type' : str } 128 # Attributes that can be set any time 129 keywords = { 'check' : FunctionType } 130 131 # __new__ is called before __init__, and is where the statements 132 # in the body of the class definition get loaded into the class's 133 # __dict__. We intercept this to filter out parameter & port assignments 134 # and only allow "private" attributes to be passed to the base 135 # __new__ (starting with underscore). 136 def __new__(mcls, name, bases, dict): 137 assert name not in allClasses, "SimObject %s already present" % name 138 139 # Copy "private" attributes, functions, and classes to the 140 # official dict. Everything else goes in _init_dict to be 141 # filtered in __init__. 142 cls_dict = {} 143 value_dict = {} 144 for key,val in dict.items(): 145 if public_value(key, val): 146 cls_dict[key] = val 147 else: 148 # must be a param/port setting 149 value_dict[key] = val 150 if 'abstract' not in value_dict: 151 value_dict['abstract'] = False 152 cls_dict['_value_dict'] = value_dict 153 cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict) 154 if 'type' in value_dict: 155 allClasses[name] = cls 156 return cls 157 158 # subclass initialization 159 def __init__(cls, name, bases, dict): 160 # calls type.__init__()... I think that's a no-op, but leave 161 # it here just in case it's not. 162 super(MetaSimObject, cls).__init__(name, bases, dict) 163 164 # initialize required attributes 165 166 # class-only attributes 167 cls._params = multidict() # param descriptions 168 cls._ports = multidict() # port descriptions 169 170 # class or instance attributes 171 cls._values = multidict() # param values 172 cls._children = multidict() # SimObject children 173 cls._port_refs = multidict() # port ref objects 174 cls._instantiated = False # really instantiated, cloned, or subclassed 175 176 # We don't support multiple inheritance. If you want to, you 177 # must fix multidict to deal with it properly. 178 if len(bases) > 1: 179 raise TypeError, "SimObjects do not support multiple inheritance" 180 181 base = bases[0] 182 183 # Set up general inheritance via multidicts. A subclass will 184 # inherit all its settings from the base class. The only time 185 # the following is not true is when we define the SimObject 186 # class itself (in which case the multidicts have no parent). 187 if isinstance(base, MetaSimObject): 188 cls._base = base 189 cls._params.parent = base._params 190 cls._ports.parent = base._ports 191 cls._values.parent = base._values 192 cls._children.parent = base._children 193 cls._port_refs.parent = base._port_refs 194 # mark base as having been subclassed 195 base._instantiated = True 196 else: 197 cls._base = None 198 199 # default keyword values 200 if 'type' in cls._value_dict: 201 if 'cxx_class' not in cls._value_dict: 202 cls._value_dict['cxx_class'] = cls._value_dict['type'] 203 204 cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class'] 205 206 # Export methods are automatically inherited via C++, so we 207 # don't want the method declarations to get inherited on the 208 # python side (and thus end up getting repeated in the wrapped 209 # versions of derived classes). The code below basicallly 210 # suppresses inheritance by substituting in the base (null) 211 # versions of these methods unless a different version is 212 # explicitly supplied. 213 for method_name in ('export_methods', 'export_method_cxx_predecls', 214 'export_method_swig_predecls'): 215 if method_name not in cls.__dict__: 216 base_method = getattr(MetaSimObject, method_name) 217 m = MethodType(base_method, cls, MetaSimObject) 218 setattr(cls, method_name, m) 219 220 # Now process the _value_dict items. They could be defining 221 # new (or overriding existing) parameters or ports, setting 222 # class keywords (e.g., 'abstract'), or setting parameter 223 # values or port bindings. The first 3 can only be set when 224 # the class is defined, so we handle them here. The others 225 # can be set later too, so just emulate that by calling 226 # setattr(). 227 for key,val in cls._value_dict.items(): 228 # param descriptions 229 if isinstance(val, ParamDesc): 230 cls._new_param(key, val) 231 232 # port objects 233 elif isinstance(val, Port): 234 cls._new_port(key, val) 235 236 # init-time-only keywords 237 elif cls.init_keywords.has_key(key): 238 cls._set_keyword(key, val, cls.init_keywords[key]) 239 240 # default: use normal path (ends up in __setattr__) 241 else: 242 setattr(cls, key, val) 243 244 def _set_keyword(cls, keyword, val, kwtype): 245 if not isinstance(val, kwtype): 246 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \ 247 (keyword, type(val), kwtype) 248 if isinstance(val, FunctionType): 249 val = classmethod(val) 250 type.__setattr__(cls, keyword, val) 251 252 def _new_param(cls, name, pdesc): 253 # each param desc should be uniquely assigned to one variable 254 assert(not hasattr(pdesc, 'name')) 255 pdesc.name = name 256 cls._params[name] = pdesc 257 if hasattr(pdesc, 'default'): 258 cls._set_param(name, pdesc.default, pdesc) 259 260 def _set_param(cls, name, value, param): 261 assert(param.name == name) 262 try: 263 value = param.convert(value) 264 except Exception, e: 265 msg = "%s\nError setting param %s.%s to %s\n" % \ 266 (e, cls.__name__, name, value) 267 e.args = (msg, ) 268 raise 269 cls._values[name] = value 270 # if param value is a SimObject, make it a child too, so that 271 # it gets cloned properly when the class is instantiated 272 if isSimObjectOrVector(value) and not value.has_parent(): 273 cls._add_cls_child(name, value) 274 275 def _add_cls_child(cls, name, child): 276 # It's a little funky to have a class as a parent, but these 277 # objects should never be instantiated (only cloned, which 278 # clears the parent pointer), and this makes it clear that the 279 # object is not an orphan and can provide better error 280 # messages. 281 child.set_parent(cls, name) 282 cls._children[name] = child 283 284 def _new_port(cls, name, port): 285 # each port should be uniquely assigned to one variable 286 assert(not hasattr(port, 'name')) 287 port.name = name 288 cls._ports[name] = port 289 290 # same as _get_port_ref, effectively, but for classes 291 def _cls_get_port_ref(cls, attr): 292 # Return reference that can be assigned to another port 293 # via __setattr__. There is only ever one reference 294 # object per port, but we create them lazily here. 295 ref = cls._port_refs.get(attr) 296 if not ref: 297 ref = cls._ports[attr].makeRef(cls) 298 cls._port_refs[attr] = ref 299 return ref 300 301 # Set attribute (called on foo.attr = value when foo is an 302 # instance of class cls). 303 def __setattr__(cls, attr, value): 304 # normal processing for private attributes 305 if public_value(attr, value): 306 type.__setattr__(cls, attr, value) 307 return 308 309 if cls.keywords.has_key(attr): 310 cls._set_keyword(attr, value, cls.keywords[attr]) 311 return 312 313 if cls._ports.has_key(attr): 314 cls._cls_get_port_ref(attr).connect(value) 315 return 316 317 if isSimObjectOrSequence(value) and cls._instantiated: 318 raise RuntimeError, \ 319 "cannot set SimObject parameter '%s' after\n" \ 320 " class %s has been instantiated or subclassed" \ 321 % (attr, cls.__name__) 322 323 # check for param 324 param = cls._params.get(attr) 325 if param: 326 cls._set_param(attr, value, param) 327 return 328 329 if isSimObjectOrSequence(value): 330 # If RHS is a SimObject, it's an implicit child assignment. 331 cls._add_cls_child(attr, coerceSimObjectOrVector(value)) 332 return 333 334 # no valid assignment... raise exception 335 raise AttributeError, \ 336 "Class %s has no parameter \'%s\'" % (cls.__name__, attr) 337 338 def __getattr__(cls, attr): 339 if attr == 'cxx_class_path': 340 return cls.cxx_class.split('::') 341 342 if attr == 'cxx_class_name': 343 return cls.cxx_class_path[-1] 344 345 if attr == 'cxx_namespaces': 346 return cls.cxx_class_path[:-1] 347 348 if cls._values.has_key(attr): 349 return cls._values[attr] 350 351 if cls._children.has_key(attr): 352 return cls._children[attr] 353 354 raise AttributeError, \ 355 "object '%s' has no attribute '%s'" % (cls.__name__, attr) 356 357 def __str__(cls): 358 return cls.__name__ 359 360 # See ParamValue.cxx_predecls for description. 361 def cxx_predecls(cls, code): 362 code('#include "params/$cls.hh"') 363 364 # See ParamValue.swig_predecls for description. 365 def swig_predecls(cls, code): 366 code('%import "python/m5/internal/param_$cls.i"') 367 368 # Hook for exporting additional C++ methods to Python via SWIG. 369 # Default is none, override using @classmethod in class definition. 370 def export_methods(cls, code): 371 pass 372 373 # Generate the code needed as a prerequisite for the C++ methods 374 # exported via export_methods() to be compiled in the _wrap.cc 375 # file. Typically generates one or more #include statements. If 376 # any methods are exported, typically at least the C++ header 377 # declaring the relevant SimObject class must be included. 378 def export_method_cxx_predecls(cls, code): 379 pass 380 381 # Generate the code needed as a prerequisite for the C++ methods 382 # exported via export_methods() to be processed by SWIG. 383 # Typically generates one or more %include or %import statements. 384 # If any methods are exported, typically at least the C++ header 385 # declaring the relevant SimObject class must be included. 386 def export_method_swig_predecls(cls, code): 387 pass 388 389 # Generate the declaration for this object for wrapping with SWIG. 390 # Generates code that goes into a SWIG .i file. Called from 391 # src/SConscript. 392 def swig_decl(cls, code): 393 class_path = cls.cxx_class.split('::') 394 classname = class_path[-1] 395 namespaces = class_path[:-1] 396 397 # The 'local' attribute restricts us to the params declared in 398 # the object itself, not including inherited params (which 399 # will also be inherited from the base class's param struct 400 # here). 401 params = cls._params.local.values()
|
| 402 ports = cls._ports.local
|
389 390 code('%module(package="m5.internal") param_$cls') 391 code() 392 code('%{') 393 code('#include "params/$cls.hh"') 394 for param in params: 395 param.cxx_predecls(code) 396 cls.export_method_cxx_predecls(code) 397 code('%}') 398 code() 399 400 for param in params: 401 param.swig_predecls(code) 402 cls.export_method_swig_predecls(code) 403 404 code() 405 if cls._base: 406 code('%import "python/m5/internal/param_${{cls._base}}.i"') 407 code() 408 409 for ns in namespaces: 410 code('namespace $ns {') 411 412 if namespaces: 413 code('// avoid name conflicts') 414 sep_string = '_COLONS_' 415 flat_name = sep_string.join(class_path) 416 code('%rename($flat_name) $classname;') 417 418 code() 419 code('// stop swig from creating/wrapping default ctor/dtor') 420 code('%nodefault $classname;') 421 code('class $classname') 422 if cls._base: 423 code(' : public ${{cls._base.cxx_class}}') 424 code('{') 425 code(' public:') 426 cls.export_methods(code) 427 code('};') 428 429 for ns in reversed(namespaces): 430 code('} // namespace $ns') 431 432 code() 433 code('%include "params/$cls.hh"') 434 435 436 # Generate the C++ declaration (.hh file) for this SimObject's 437 # param struct. Called from src/SConscript. 438 def cxx_param_decl(cls, code): 439 # The 'local' attribute restricts us to the params declared in 440 # the object itself, not including inherited params (which 441 # will also be inherited from the base class's param struct 442 # here). 443 params = cls._params.local.values()
| 403 404 code('%module(package="m5.internal") param_$cls') 405 code() 406 code('%{') 407 code('#include "params/$cls.hh"') 408 for param in params: 409 param.cxx_predecls(code) 410 cls.export_method_cxx_predecls(code) 411 code('%}') 412 code() 413 414 for param in params: 415 param.swig_predecls(code) 416 cls.export_method_swig_predecls(code) 417 418 code() 419 if cls._base: 420 code('%import "python/m5/internal/param_${{cls._base}}.i"') 421 code() 422 423 for ns in namespaces: 424 code('namespace $ns {') 425 426 if namespaces: 427 code('// avoid name conflicts') 428 sep_string = '_COLONS_' 429 flat_name = sep_string.join(class_path) 430 code('%rename($flat_name) $classname;') 431 432 code() 433 code('// stop swig from creating/wrapping default ctor/dtor') 434 code('%nodefault $classname;') 435 code('class $classname') 436 if cls._base: 437 code(' : public ${{cls._base.cxx_class}}') 438 code('{') 439 code(' public:') 440 cls.export_methods(code) 441 code('};') 442 443 for ns in reversed(namespaces): 444 code('} // namespace $ns') 445 446 code() 447 code('%include "params/$cls.hh"') 448 449 450 # Generate the C++ declaration (.hh file) for this SimObject's 451 # param struct. Called from src/SConscript. 452 def cxx_param_decl(cls, code): 453 # The 'local' attribute restricts us to the params declared in 454 # the object itself, not including inherited params (which 455 # will also be inherited from the base class's param struct 456 # here). 457 params = cls._params.local.values()
|
| 458 ports = cls._ports.local
|
444 try: 445 ptypes = [p.ptype for p in params] 446 except: 447 print cls, p, p.ptype_str 448 print params 449 raise 450 451 class_path = cls._value_dict['cxx_class'].split('::') 452 453 code('''\ 454#ifndef __PARAMS__${cls}__ 455#define __PARAMS__${cls}__ 456 457''') 458 459 # A forward class declaration is sufficient since we are just 460 # declaring a pointer. 461 for ns in class_path[:-1]: 462 code('namespace $ns {') 463 code('class $0;', class_path[-1]) 464 for ns in reversed(class_path[:-1]): 465 code('} // namespace $ns') 466 code() 467 468 # The base SimObject has a couple of params that get 469 # automatically set from Python without being declared through 470 # the normal Param mechanism; we slip them in here (needed 471 # predecls now, actual declarations below) 472 if cls == SimObject: 473 code(''' 474#ifndef PY_VERSION 475struct PyObject; 476#endif 477 478#include <string> 479 480class EventQueue; 481''') 482 for param in params: 483 param.cxx_predecls(code)
| 459 try: 460 ptypes = [p.ptype for p in params] 461 except: 462 print cls, p, p.ptype_str 463 print params 464 raise 465 466 class_path = cls._value_dict['cxx_class'].split('::') 467 468 code('''\ 469#ifndef __PARAMS__${cls}__ 470#define __PARAMS__${cls}__ 471 472''') 473 474 # A forward class declaration is sufficient since we are just 475 # declaring a pointer. 476 for ns in class_path[:-1]: 477 code('namespace $ns {') 478 code('class $0;', class_path[-1]) 479 for ns in reversed(class_path[:-1]): 480 code('} // namespace $ns') 481 code() 482 483 # The base SimObject has a couple of params that get 484 # automatically set from Python without being declared through 485 # the normal Param mechanism; we slip them in here (needed 486 # predecls now, actual declarations below) 487 if cls == SimObject: 488 code(''' 489#ifndef PY_VERSION 490struct PyObject; 491#endif 492 493#include <string> 494 495class EventQueue; 496''') 497 for param in params: 498 param.cxx_predecls(code)
|
| 499 for port in ports.itervalues(): 500 port.cxx_predecls(code)
|
484 code() 485 486 if cls._base: 487 code('#include "params/${{cls._base.type}}.hh"') 488 code() 489 490 for ptype in ptypes: 491 if issubclass(ptype, Enum): 492 code('#include "enums/${{ptype.__name__}}.hh"') 493 code() 494 495 # now generate the actual param struct 496 code("struct ${cls}Params") 497 if cls._base: 498 code(" : public ${{cls._base.type}}Params") 499 code("{") 500 if not hasattr(cls, 'abstract') or not cls.abstract: 501 if 'type' in cls.__dict__: 502 code(" ${{cls.cxx_type}} create();") 503 504 code.indent() 505 if cls == SimObject: 506 code(''' 507 SimObjectParams() 508 { 509 extern EventQueue mainEventQueue; 510 eventq = &mainEventQueue; 511 } 512 virtual ~SimObjectParams() {} 513 514 std::string name; 515 PyObject *pyobj; 516 EventQueue *eventq; 517 ''') 518 for param in params: 519 param.cxx_decl(code)
| 501 code() 502 503 if cls._base: 504 code('#include "params/${{cls._base.type}}.hh"') 505 code() 506 507 for ptype in ptypes: 508 if issubclass(ptype, Enum): 509 code('#include "enums/${{ptype.__name__}}.hh"') 510 code() 511 512 # now generate the actual param struct 513 code("struct ${cls}Params") 514 if cls._base: 515 code(" : public ${{cls._base.type}}Params") 516 code("{") 517 if not hasattr(cls, 'abstract') or not cls.abstract: 518 if 'type' in cls.__dict__: 519 code(" ${{cls.cxx_type}} create();") 520 521 code.indent() 522 if cls == SimObject: 523 code(''' 524 SimObjectParams() 525 { 526 extern EventQueue mainEventQueue; 527 eventq = &mainEventQueue; 528 } 529 virtual ~SimObjectParams() {} 530 531 std::string name; 532 PyObject *pyobj; 533 EventQueue *eventq; 534 ''') 535 for param in params: 536 param.cxx_decl(code)
|
| 537 for port in ports.itervalues(): 538 port.cxx_decl(code) 539
|
520 code.dedent() 521 code('};') 522 523 code() 524 code('#endif // __PARAMS__${cls}__') 525 return code 526 527 528 529# The SimObject class is the root of the special hierarchy. Most of 530# the code in this class deals with the configuration hierarchy itself 531# (parent/child node relationships). 532class SimObject(object): 533 # Specify metaclass. Any class inheriting from SimObject will 534 # get this metaclass. 535 __metaclass__ = MetaSimObject 536 type = 'SimObject' 537 abstract = True 538 539 @classmethod 540 def export_method_cxx_predecls(cls, code): 541 code(''' 542#include <Python.h> 543 544#include "sim/serialize.hh" 545#include "sim/sim_object.hh" 546''') 547 548 @classmethod 549 def export_method_swig_predecls(cls, code): 550 code(''' 551%include <std_string.i> 552''') 553 554 @classmethod 555 def export_methods(cls, code): 556 code(''' 557 enum State { 558 Running, 559 Draining, 560 Drained 561 }; 562 563 void init(); 564 void loadState(Checkpoint *cp); 565 void initState(); 566 void regStats(); 567 void regFormulas(); 568 void resetStats(); 569 void startup(); 570 571 unsigned int drain(Event *drain_event); 572 void resume(); 573 void switchOut(); 574 void takeOverFrom(BaseCPU *cpu); 575''') 576 577 # Initialize new instance. For objects with SimObject-valued 578 # children, we need to recursively clone the classes represented 579 # by those param values as well in a consistent "deep copy"-style 580 # fashion. That is, we want to make sure that each instance is 581 # cloned only once, and that if there are multiple references to 582 # the same original object, we end up with the corresponding 583 # cloned references all pointing to the same cloned instance. 584 def __init__(self, **kwargs): 585 ancestor = kwargs.get('_ancestor') 586 memo_dict = kwargs.get('_memo') 587 if memo_dict is None: 588 # prepare to memoize any recursively instantiated objects 589 memo_dict = {} 590 elif ancestor: 591 # memoize me now to avoid problems with recursive calls 592 memo_dict[ancestor] = self 593 594 if not ancestor: 595 ancestor = self.__class__ 596 ancestor._instantiated = True 597 598 # initialize required attributes 599 self._parent = None 600 self._name = None 601 self._ccObject = None # pointer to C++ object 602 self._ccParams = None 603 self._instantiated = False # really "cloned" 604 605 # Clone children specified at class level. No need for a 606 # multidict here since we will be cloning everything. 607 # Do children before parameter values so that children that 608 # are also param values get cloned properly. 609 self._children = {} 610 for key,val in ancestor._children.iteritems(): 611 self.add_child(key, val(_memo=memo_dict)) 612 613 # Inherit parameter values from class using multidict so 614 # individual value settings can be overridden but we still 615 # inherit late changes to non-overridden class values. 616 self._values = multidict(ancestor._values) 617 # clone SimObject-valued parameters 618 for key,val in ancestor._values.iteritems(): 619 val = tryAsSimObjectOrVector(val) 620 if val is not None: 621 self._values[key] = val(_memo=memo_dict) 622 623 # clone port references. no need to use a multidict here 624 # since we will be creating new references for all ports. 625 self._port_refs = {} 626 for key,val in ancestor._port_refs.iteritems(): 627 self._port_refs[key] = val.clone(self, memo_dict) 628 # apply attribute assignments from keyword args, if any 629 for key,val in kwargs.iteritems(): 630 setattr(self, key, val) 631 632 # "Clone" the current instance by creating another instance of 633 # this instance's class, but that inherits its parameter values 634 # and port mappings from the current instance. If we're in a 635 # "deep copy" recursive clone, check the _memo dict to see if 636 # we've already cloned this instance. 637 def __call__(self, **kwargs): 638 memo_dict = kwargs.get('_memo') 639 if memo_dict is None: 640 # no memo_dict: must be top-level clone operation. 641 # this is only allowed at the root of a hierarchy 642 if self._parent: 643 raise RuntimeError, "attempt to clone object %s " \ 644 "not at the root of a tree (parent = %s)" \ 645 % (self, self._parent) 646 # create a new dict and use that. 647 memo_dict = {} 648 kwargs['_memo'] = memo_dict 649 elif memo_dict.has_key(self): 650 # clone already done & memoized 651 return memo_dict[self] 652 return self.__class__(_ancestor = self, **kwargs) 653 654 def _get_port_ref(self, attr): 655 # Return reference that can be assigned to another port 656 # via __setattr__. There is only ever one reference 657 # object per port, but we create them lazily here. 658 ref = self._port_refs.get(attr) 659 if not ref: 660 ref = self._ports[attr].makeRef(self) 661 self._port_refs[attr] = ref 662 return ref 663 664 def __getattr__(self, attr): 665 if self._ports.has_key(attr): 666 return self._get_port_ref(attr) 667 668 if self._values.has_key(attr): 669 return self._values[attr] 670 671 if self._children.has_key(attr): 672 return self._children[attr] 673 674 # If the attribute exists on the C++ object, transparently 675 # forward the reference there. This is typically used for 676 # SWIG-wrapped methods such as init(), regStats(), 677 # regFormulas(), resetStats(), startup(), drain(), and 678 # resume(). 679 if self._ccObject and hasattr(self._ccObject, attr): 680 return getattr(self._ccObject, attr) 681 682 raise AttributeError, "object '%s' has no attribute '%s'" \ 683 % (self.__class__.__name__, attr) 684 685 # Set attribute (called on foo.attr = value when foo is an 686 # instance of class cls). 687 def __setattr__(self, attr, value): 688 # normal processing for private attributes 689 if attr.startswith('_'): 690 object.__setattr__(self, attr, value) 691 return 692 693 if self._ports.has_key(attr): 694 # set up port connection 695 self._get_port_ref(attr).connect(value) 696 return 697 698 if isSimObjectOrSequence(value) and self._instantiated: 699 raise RuntimeError, \ 700 "cannot set SimObject parameter '%s' after\n" \ 701 " instance been cloned %s" % (attr, `self`) 702 703 param = self._params.get(attr) 704 if param: 705 try: 706 value = param.convert(value) 707 except Exception, e: 708 msg = "%s\nError setting param %s.%s to %s\n" % \ 709 (e, self.__class__.__name__, attr, value) 710 e.args = (msg, ) 711 raise 712 self._values[attr] = value 713 # implicitly parent unparented objects assigned as params 714 if isSimObjectOrVector(value) and not value.has_parent(): 715 self.add_child(attr, value) 716 return 717 718 # if RHS is a SimObject, it's an implicit child assignment 719 if isSimObjectOrSequence(value): 720 self.add_child(attr, value) 721 return 722 723 # no valid assignment... raise exception 724 raise AttributeError, "Class %s has no parameter %s" \ 725 % (self.__class__.__name__, attr) 726 727 728 # this hack allows tacking a '[0]' onto parameters that may or may 729 # not be vectors, and always getting the first element (e.g. cpus) 730 def __getitem__(self, key): 731 if key == 0: 732 return self 733 raise TypeError, "Non-zero index '%s' to SimObject" % key 734 735 # Also implemented by SimObjectVector 736 def clear_parent(self, old_parent): 737 assert self._parent is old_parent 738 self._parent = None 739 740 # Also implemented by SimObjectVector 741 def set_parent(self, parent, name): 742 self._parent = parent 743 self._name = name 744 745 # Also implemented by SimObjectVector 746 def get_name(self): 747 return self._name 748 749 # Also implemented by SimObjectVector 750 def has_parent(self): 751 return self._parent is not None 752 753 # clear out child with given name. This code is not likely to be exercised. 754 # See comment in add_child. 755 def clear_child(self, name): 756 child = self._children[name] 757 child.clear_parent(self) 758 del self._children[name] 759 760 # Add a new child to this object. 761 def add_child(self, name, child): 762 child = coerceSimObjectOrVector(child) 763 if child.has_parent(): 764 print "warning: add_child('%s'): child '%s' already has parent" % \ 765 (name, child.get_name()) 766 if self._children.has_key(name): 767 # This code path had an undiscovered bug that would make it fail 768 # at runtime. It had been here for a long time and was only 769 # exposed by a buggy script. Changes here will probably not be 770 # exercised without specialized testing. 771 self.clear_child(name) 772 child.set_parent(self, name) 773 self._children[name] = child 774 775 # Take SimObject-valued parameters that haven't been explicitly 776 # assigned as children and make them children of the object that 777 # they were assigned to as a parameter value. This guarantees 778 # that when we instantiate all the parameter objects we're still 779 # inside the configuration hierarchy. 780 def adoptOrphanParams(self): 781 for key,val in self._values.iteritems(): 782 if not isSimObjectVector(val) and isSimObjectSequence(val): 783 # need to convert raw SimObject sequences to 784 # SimObjectVector class so we can call has_parent() 785 val = SimObjectVector(val) 786 self._values[key] = val 787 if isSimObjectOrVector(val) and not val.has_parent(): 788 print "warning: %s adopting orphan SimObject param '%s'" \ 789 % (self, key) 790 self.add_child(key, val) 791 792 def path(self): 793 if not self._parent: 794 return '<orphan %s>' % self.__class__ 795 ppath = self._parent.path() 796 if ppath == 'root': 797 return self._name 798 return ppath + "." + self._name 799 800 def __str__(self): 801 return self.path() 802 803 def ini_str(self): 804 return self.path() 805 806 def find_any(self, ptype): 807 if isinstance(self, ptype): 808 return self, True 809 810 found_obj = None 811 for child in self._children.itervalues(): 812 if isinstance(child, ptype): 813 if found_obj != None and child != found_obj: 814 raise AttributeError, \ 815 'parent.any matched more than one: %s %s' % \ 816 (found_obj.path, child.path) 817 found_obj = child 818 # search param space 819 for pname,pdesc in self._params.iteritems(): 820 if issubclass(pdesc.ptype, ptype): 821 match_obj = self._values[pname] 822 if found_obj != None and found_obj != match_obj: 823 raise AttributeError, \ 824 'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path) 825 found_obj = match_obj 826 return found_obj, found_obj != None 827 828 def find_all(self, ptype): 829 all = {} 830 # search children 831 for child in self._children.itervalues(): 832 if isinstance(child, ptype) and not isproxy(child) and \ 833 not isNullPointer(child): 834 all[child] = True 835 # search param space 836 for pname,pdesc in self._params.iteritems(): 837 if issubclass(pdesc.ptype, ptype): 838 match_obj = self._values[pname] 839 if not isproxy(match_obj) and not isNullPointer(match_obj): 840 all[match_obj] = True 841 return all.keys(), True 842 843 def unproxy(self, base): 844 return self 845 846 def unproxyParams(self): 847 for param in self._params.iterkeys(): 848 value = self._values.get(param) 849 if value != None and isproxy(value): 850 try: 851 value = value.unproxy(self) 852 except: 853 print "Error in unproxying param '%s' of %s" % \ 854 (param, self.path()) 855 raise 856 setattr(self, param, value) 857 858 # Unproxy ports in sorted order so that 'append' operations on 859 # vector ports are done in a deterministic fashion. 860 port_names = self._ports.keys() 861 port_names.sort() 862 for port_name in port_names: 863 port = self._port_refs.get(port_name) 864 if port != None: 865 port.unproxy(self) 866 867 def print_ini(self, ini_file): 868 print >>ini_file, '[' + self.path() + ']' # .ini section header 869 870 instanceDict[self.path()] = self 871 872 if hasattr(self, 'type'): 873 print >>ini_file, 'type=%s' % self.type 874 875 if len(self._children.keys()): 876 print >>ini_file, 'children=%s' % \ 877 ' '.join(self._children[n].get_name() \ 878 for n in sorted(self._children.keys())) 879 880 for param in sorted(self._params.keys()): 881 value = self._values.get(param) 882 if value != None: 883 print >>ini_file, '%s=%s' % (param, 884 self._values[param].ini_str()) 885 886 for port_name in sorted(self._ports.keys()): 887 port = self._port_refs.get(port_name, None) 888 if port != None: 889 print >>ini_file, '%s=%s' % (port_name, port.ini_str()) 890 891 print >>ini_file # blank line between objects 892 893 # generate a tree of dictionaries expressing all the parameters in the 894 # instantiated system for use by scripts that want to do power, thermal 895 # visualization, and other similar tasks 896 def get_config_as_dict(self): 897 d = attrdict() 898 if hasattr(self, 'type'): 899 d.type = self.type 900 if hasattr(self, 'cxx_class'): 901 d.cxx_class = self.cxx_class 902 903 for param in sorted(self._params.keys()): 904 value = self._values.get(param) 905 try: 906 # Use native type for those supported by JSON and 907 # strings for everything else. skipkeys=True seems 908 # to not work as well as one would hope 909 if type(self._values[param].value) in \ 910 [str, unicode, int, long, float, bool, None]: 911 d[param] = self._values[param].value 912 else: 913 d[param] = str(self._values[param]) 914 915 except AttributeError: 916 pass 917 918 for n in sorted(self._children.keys()): 919 d[self._children[n].get_name()] = self._children[n].get_config_as_dict() 920 921 for port_name in sorted(self._ports.keys()): 922 port = self._port_refs.get(port_name, None) 923 if port != None: 924 # Might want to actually make this reference the object 925 # in the future, although execing the string problem would 926 # get some of the way there 927 d[port_name] = port.ini_str() 928 929 return d 930 931 def getCCParams(self): 932 if self._ccParams: 933 return self._ccParams 934 935 cc_params_struct = getattr(m5.internal.params, '%sParams' % self.type) 936 cc_params = cc_params_struct() 937 cc_params.pyobj = self 938 cc_params.name = str(self) 939 940 param_names = self._params.keys() 941 param_names.sort() 942 for param in param_names: 943 value = self._values.get(param) 944 if value is None: 945 fatal("%s.%s without default or user set value", 946 self.path(), param) 947 948 value = value.getValue() 949 if isinstance(self._params[param], VectorParamDesc): 950 assert isinstance(value, list) 951 vec = getattr(cc_params, param) 952 assert not len(vec) 953 for v in value: 954 vec.append(v) 955 else: 956 setattr(cc_params, param, value) 957 958 port_names = self._ports.keys() 959 port_names.sort() 960 for port_name in port_names: 961 port = self._port_refs.get(port_name, None) 962 if port != None:
| 540 code.dedent() 541 code('};') 542 543 code() 544 code('#endif // __PARAMS__${cls}__') 545 return code 546 547 548 549# The SimObject class is the root of the special hierarchy. Most of 550# the code in this class deals with the configuration hierarchy itself 551# (parent/child node relationships). 552class SimObject(object): 553 # Specify metaclass. Any class inheriting from SimObject will 554 # get this metaclass. 555 __metaclass__ = MetaSimObject 556 type = 'SimObject' 557 abstract = True 558 559 @classmethod 560 def export_method_cxx_predecls(cls, code): 561 code(''' 562#include <Python.h> 563 564#include "sim/serialize.hh" 565#include "sim/sim_object.hh" 566''') 567 568 @classmethod 569 def export_method_swig_predecls(cls, code): 570 code(''' 571%include <std_string.i> 572''') 573 574 @classmethod 575 def export_methods(cls, code): 576 code(''' 577 enum State { 578 Running, 579 Draining, 580 Drained 581 }; 582 583 void init(); 584 void loadState(Checkpoint *cp); 585 void initState(); 586 void regStats(); 587 void regFormulas(); 588 void resetStats(); 589 void startup(); 590 591 unsigned int drain(Event *drain_event); 592 void resume(); 593 void switchOut(); 594 void takeOverFrom(BaseCPU *cpu); 595''') 596 597 # Initialize new instance. For objects with SimObject-valued 598 # children, we need to recursively clone the classes represented 599 # by those param values as well in a consistent "deep copy"-style 600 # fashion. That is, we want to make sure that each instance is 601 # cloned only once, and that if there are multiple references to 602 # the same original object, we end up with the corresponding 603 # cloned references all pointing to the same cloned instance. 604 def __init__(self, **kwargs): 605 ancestor = kwargs.get('_ancestor') 606 memo_dict = kwargs.get('_memo') 607 if memo_dict is None: 608 # prepare to memoize any recursively instantiated objects 609 memo_dict = {} 610 elif ancestor: 611 # memoize me now to avoid problems with recursive calls 612 memo_dict[ancestor] = self 613 614 if not ancestor: 615 ancestor = self.__class__ 616 ancestor._instantiated = True 617 618 # initialize required attributes 619 self._parent = None 620 self._name = None 621 self._ccObject = None # pointer to C++ object 622 self._ccParams = None 623 self._instantiated = False # really "cloned" 624 625 # Clone children specified at class level. No need for a 626 # multidict here since we will be cloning everything. 627 # Do children before parameter values so that children that 628 # are also param values get cloned properly. 629 self._children = {} 630 for key,val in ancestor._children.iteritems(): 631 self.add_child(key, val(_memo=memo_dict)) 632 633 # Inherit parameter values from class using multidict so 634 # individual value settings can be overridden but we still 635 # inherit late changes to non-overridden class values. 636 self._values = multidict(ancestor._values) 637 # clone SimObject-valued parameters 638 for key,val in ancestor._values.iteritems(): 639 val = tryAsSimObjectOrVector(val) 640 if val is not None: 641 self._values[key] = val(_memo=memo_dict) 642 643 # clone port references. no need to use a multidict here 644 # since we will be creating new references for all ports. 645 self._port_refs = {} 646 for key,val in ancestor._port_refs.iteritems(): 647 self._port_refs[key] = val.clone(self, memo_dict) 648 # apply attribute assignments from keyword args, if any 649 for key,val in kwargs.iteritems(): 650 setattr(self, key, val) 651 652 # "Clone" the current instance by creating another instance of 653 # this instance's class, but that inherits its parameter values 654 # and port mappings from the current instance. If we're in a 655 # "deep copy" recursive clone, check the _memo dict to see if 656 # we've already cloned this instance. 657 def __call__(self, **kwargs): 658 memo_dict = kwargs.get('_memo') 659 if memo_dict is None: 660 # no memo_dict: must be top-level clone operation. 661 # this is only allowed at the root of a hierarchy 662 if self._parent: 663 raise RuntimeError, "attempt to clone object %s " \ 664 "not at the root of a tree (parent = %s)" \ 665 % (self, self._parent) 666 # create a new dict and use that. 667 memo_dict = {} 668 kwargs['_memo'] = memo_dict 669 elif memo_dict.has_key(self): 670 # clone already done & memoized 671 return memo_dict[self] 672 return self.__class__(_ancestor = self, **kwargs) 673 674 def _get_port_ref(self, attr): 675 # Return reference that can be assigned to another port 676 # via __setattr__. There is only ever one reference 677 # object per port, but we create them lazily here. 678 ref = self._port_refs.get(attr) 679 if not ref: 680 ref = self._ports[attr].makeRef(self) 681 self._port_refs[attr] = ref 682 return ref 683 684 def __getattr__(self, attr): 685 if self._ports.has_key(attr): 686 return self._get_port_ref(attr) 687 688 if self._values.has_key(attr): 689 return self._values[attr] 690 691 if self._children.has_key(attr): 692 return self._children[attr] 693 694 # If the attribute exists on the C++ object, transparently 695 # forward the reference there. This is typically used for 696 # SWIG-wrapped methods such as init(), regStats(), 697 # regFormulas(), resetStats(), startup(), drain(), and 698 # resume(). 699 if self._ccObject and hasattr(self._ccObject, attr): 700 return getattr(self._ccObject, attr) 701 702 raise AttributeError, "object '%s' has no attribute '%s'" \ 703 % (self.__class__.__name__, attr) 704 705 # Set attribute (called on foo.attr = value when foo is an 706 # instance of class cls). 707 def __setattr__(self, attr, value): 708 # normal processing for private attributes 709 if attr.startswith('_'): 710 object.__setattr__(self, attr, value) 711 return 712 713 if self._ports.has_key(attr): 714 # set up port connection 715 self._get_port_ref(attr).connect(value) 716 return 717 718 if isSimObjectOrSequence(value) and self._instantiated: 719 raise RuntimeError, \ 720 "cannot set SimObject parameter '%s' after\n" \ 721 " instance been cloned %s" % (attr, `self`) 722 723 param = self._params.get(attr) 724 if param: 725 try: 726 value = param.convert(value) 727 except Exception, e: 728 msg = "%s\nError setting param %s.%s to %s\n" % \ 729 (e, self.__class__.__name__, attr, value) 730 e.args = (msg, ) 731 raise 732 self._values[attr] = value 733 # implicitly parent unparented objects assigned as params 734 if isSimObjectOrVector(value) and not value.has_parent(): 735 self.add_child(attr, value) 736 return 737 738 # if RHS is a SimObject, it's an implicit child assignment 739 if isSimObjectOrSequence(value): 740 self.add_child(attr, value) 741 return 742 743 # no valid assignment... raise exception 744 raise AttributeError, "Class %s has no parameter %s" \ 745 % (self.__class__.__name__, attr) 746 747 748 # this hack allows tacking a '[0]' onto parameters that may or may 749 # not be vectors, and always getting the first element (e.g. cpus) 750 def __getitem__(self, key): 751 if key == 0: 752 return self 753 raise TypeError, "Non-zero index '%s' to SimObject" % key 754 755 # Also implemented by SimObjectVector 756 def clear_parent(self, old_parent): 757 assert self._parent is old_parent 758 self._parent = None 759 760 # Also implemented by SimObjectVector 761 def set_parent(self, parent, name): 762 self._parent = parent 763 self._name = name 764 765 # Also implemented by SimObjectVector 766 def get_name(self): 767 return self._name 768 769 # Also implemented by SimObjectVector 770 def has_parent(self): 771 return self._parent is not None 772 773 # clear out child with given name. This code is not likely to be exercised. 774 # See comment in add_child. 775 def clear_child(self, name): 776 child = self._children[name] 777 child.clear_parent(self) 778 del self._children[name] 779 780 # Add a new child to this object. 781 def add_child(self, name, child): 782 child = coerceSimObjectOrVector(child) 783 if child.has_parent(): 784 print "warning: add_child('%s'): child '%s' already has parent" % \ 785 (name, child.get_name()) 786 if self._children.has_key(name): 787 # This code path had an undiscovered bug that would make it fail 788 # at runtime. It had been here for a long time and was only 789 # exposed by a buggy script. Changes here will probably not be 790 # exercised without specialized testing. 791 self.clear_child(name) 792 child.set_parent(self, name) 793 self._children[name] = child 794 795 # Take SimObject-valued parameters that haven't been explicitly 796 # assigned as children and make them children of the object that 797 # they were assigned to as a parameter value. This guarantees 798 # that when we instantiate all the parameter objects we're still 799 # inside the configuration hierarchy. 800 def adoptOrphanParams(self): 801 for key,val in self._values.iteritems(): 802 if not isSimObjectVector(val) and isSimObjectSequence(val): 803 # need to convert raw SimObject sequences to 804 # SimObjectVector class so we can call has_parent() 805 val = SimObjectVector(val) 806 self._values[key] = val 807 if isSimObjectOrVector(val) and not val.has_parent(): 808 print "warning: %s adopting orphan SimObject param '%s'" \ 809 % (self, key) 810 self.add_child(key, val) 811 812 def path(self): 813 if not self._parent: 814 return '<orphan %s>' % self.__class__ 815 ppath = self._parent.path() 816 if ppath == 'root': 817 return self._name 818 return ppath + "." + self._name 819 820 def __str__(self): 821 return self.path() 822 823 def ini_str(self): 824 return self.path() 825 826 def find_any(self, ptype): 827 if isinstance(self, ptype): 828 return self, True 829 830 found_obj = None 831 for child in self._children.itervalues(): 832 if isinstance(child, ptype): 833 if found_obj != None and child != found_obj: 834 raise AttributeError, \ 835 'parent.any matched more than one: %s %s' % \ 836 (found_obj.path, child.path) 837 found_obj = child 838 # search param space 839 for pname,pdesc in self._params.iteritems(): 840 if issubclass(pdesc.ptype, ptype): 841 match_obj = self._values[pname] 842 if found_obj != None and found_obj != match_obj: 843 raise AttributeError, \ 844 'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path) 845 found_obj = match_obj 846 return found_obj, found_obj != None 847 848 def find_all(self, ptype): 849 all = {} 850 # search children 851 for child in self._children.itervalues(): 852 if isinstance(child, ptype) and not isproxy(child) and \ 853 not isNullPointer(child): 854 all[child] = True 855 # search param space 856 for pname,pdesc in self._params.iteritems(): 857 if issubclass(pdesc.ptype, ptype): 858 match_obj = self._values[pname] 859 if not isproxy(match_obj) and not isNullPointer(match_obj): 860 all[match_obj] = True 861 return all.keys(), True 862 863 def unproxy(self, base): 864 return self 865 866 def unproxyParams(self): 867 for param in self._params.iterkeys(): 868 value = self._values.get(param) 869 if value != None and isproxy(value): 870 try: 871 value = value.unproxy(self) 872 except: 873 print "Error in unproxying param '%s' of %s" % \ 874 (param, self.path()) 875 raise 876 setattr(self, param, value) 877 878 # Unproxy ports in sorted order so that 'append' operations on 879 # vector ports are done in a deterministic fashion. 880 port_names = self._ports.keys() 881 port_names.sort() 882 for port_name in port_names: 883 port = self._port_refs.get(port_name) 884 if port != None: 885 port.unproxy(self) 886 887 def print_ini(self, ini_file): 888 print >>ini_file, '[' + self.path() + ']' # .ini section header 889 890 instanceDict[self.path()] = self 891 892 if hasattr(self, 'type'): 893 print >>ini_file, 'type=%s' % self.type 894 895 if len(self._children.keys()): 896 print >>ini_file, 'children=%s' % \ 897 ' '.join(self._children[n].get_name() \ 898 for n in sorted(self._children.keys())) 899 900 for param in sorted(self._params.keys()): 901 value = self._values.get(param) 902 if value != None: 903 print >>ini_file, '%s=%s' % (param, 904 self._values[param].ini_str()) 905 906 for port_name in sorted(self._ports.keys()): 907 port = self._port_refs.get(port_name, None) 908 if port != None: 909 print >>ini_file, '%s=%s' % (port_name, port.ini_str()) 910 911 print >>ini_file # blank line between objects 912 913 # generate a tree of dictionaries expressing all the parameters in the 914 # instantiated system for use by scripts that want to do power, thermal 915 # visualization, and other similar tasks 916 def get_config_as_dict(self): 917 d = attrdict() 918 if hasattr(self, 'type'): 919 d.type = self.type 920 if hasattr(self, 'cxx_class'): 921 d.cxx_class = self.cxx_class 922 923 for param in sorted(self._params.keys()): 924 value = self._values.get(param) 925 try: 926 # Use native type for those supported by JSON and 927 # strings for everything else. skipkeys=True seems 928 # to not work as well as one would hope 929 if type(self._values[param].value) in \ 930 [str, unicode, int, long, float, bool, None]: 931 d[param] = self._values[param].value 932 else: 933 d[param] = str(self._values[param]) 934 935 except AttributeError: 936 pass 937 938 for n in sorted(self._children.keys()): 939 d[self._children[n].get_name()] = self._children[n].get_config_as_dict() 940 941 for port_name in sorted(self._ports.keys()): 942 port = self._port_refs.get(port_name, None) 943 if port != None: 944 # Might want to actually make this reference the object 945 # in the future, although execing the string problem would 946 # get some of the way there 947 d[port_name] = port.ini_str() 948 949 return d 950 951 def getCCParams(self): 952 if self._ccParams: 953 return self._ccParams 954 955 cc_params_struct = getattr(m5.internal.params, '%sParams' % self.type) 956 cc_params = cc_params_struct() 957 cc_params.pyobj = self 958 cc_params.name = str(self) 959 960 param_names = self._params.keys() 961 param_names.sort() 962 for param in param_names: 963 value = self._values.get(param) 964 if value is None: 965 fatal("%s.%s without default or user set value", 966 self.path(), param) 967 968 value = value.getValue() 969 if isinstance(self._params[param], VectorParamDesc): 970 assert isinstance(value, list) 971 vec = getattr(cc_params, param) 972 assert not len(vec) 973 for v in value: 974 vec.append(v) 975 else: 976 setattr(cc_params, param, value) 977 978 port_names = self._ports.keys() 979 port_names.sort() 980 for port_name in port_names: 981 port = self._port_refs.get(port_name, None) 982 if port != None:
|
963 setattr(cc_params, port_name, port)
| 983 setattr(cc_params, 'port_' + port_name + '_connection_count', 984 len(port))
|
964 self._ccParams = cc_params 965 return self._ccParams 966 967 # Get C++ object corresponding to this object, calling C++ if 968 # necessary to construct it. Does *not* recursively create 969 # children. 970 def getCCObject(self): 971 if not self._ccObject: 972 # Make sure this object is in the configuration hierarchy 973 if not self._parent and not isRoot(self): 974 raise RuntimeError, "Attempt to instantiate orphan node" 975 # Cycles in the configuration hierarchy are not supported. This 976 # will catch the resulting recursion and stop. 977 self._ccObject = -1 978 params = self.getCCParams() 979 self._ccObject = params.create() 980 elif self._ccObject == -1: 981 raise RuntimeError, "%s: Cycle found in configuration hierarchy." \ 982 % self.path() 983 return self._ccObject 984 985 def descendants(self): 986 yield self 987 for child in self._children.itervalues(): 988 for obj in child.descendants(): 989 yield obj 990 991 # Call C++ to create C++ object corresponding to this object 992 def createCCObject(self): 993 self.getCCParams() 994 self.getCCObject() # force creation 995 996 def getValue(self): 997 return self.getCCObject() 998 999 # Create C++ port connections corresponding to the connections in 1000 # _port_refs 1001 def connectPorts(self): 1002 for portRef in self._port_refs.itervalues(): 1003 portRef.ccConnect() 1004 1005 def getMemoryMode(self): 1006 if not isinstance(self, m5.objects.System): 1007 return None 1008 1009 return self._ccObject.getMemoryMode() 1010 1011 def changeTiming(self, mode): 1012 if isinstance(self, m5.objects.System): 1013 # i don't know if there's a better way to do this - calling 1014 # setMemoryMode directly from self._ccObject results in calling 1015 # SimObject::setMemoryMode, not the System::setMemoryMode 1016 self._ccObject.setMemoryMode(mode) 1017 1018 def takeOverFrom(self, old_cpu): 1019 self._ccObject.takeOverFrom(old_cpu._ccObject) 1020 1021 # generate output file for 'dot' to display as a pretty graph. 1022 # this code is currently broken. 1023 def outputDot(self, dot): 1024 label = "{%s|" % self.path 1025 if isSimObject(self.realtype): 1026 label += '%s|' % self.type 1027 1028 if self.children: 1029 # instantiate children in same order they were added for 1030 # backward compatibility (else we can end up with cpu1 1031 # before cpu0). 1032 for c in self.children: 1033 dot.add_edge(pydot.Edge(self.path,c.path, style="bold")) 1034 1035 simobjs = [] 1036 for param in self.params: 1037 try: 1038 if param.value is None: 1039 raise AttributeError, 'Parameter with no value' 1040 1041 value = param.value 1042 string = param.string(value) 1043 except Exception, e: 1044 msg = 'exception in %s:%s\n%s' % (self.name, param.name, e) 1045 e.args = (msg, ) 1046 raise 1047 1048 if isSimObject(param.ptype) and string != "Null": 1049 simobjs.append(string) 1050 else: 1051 label += '%s = %s\\n' % (param.name, string) 1052 1053 for so in simobjs: 1054 label += "|<%s> %s" % (so, so) 1055 dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so, 1056 tailport="w")) 1057 label += '}' 1058 dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label)) 1059 1060 # recursively dump out children 1061 for c in self.children: 1062 c.outputDot(dot) 1063 1064# Function to provide to C++ so it can look up instances based on paths 1065def resolveSimObject(name): 1066 obj = instanceDict[name] 1067 return obj.getCCObject() 1068 1069def isSimObject(value): 1070 return isinstance(value, SimObject) 1071 1072def isSimObjectClass(value): 1073 return issubclass(value, SimObject) 1074 1075def isSimObjectVector(value): 1076 return isinstance(value, SimObjectVector) 1077 1078def isSimObjectSequence(value): 1079 if not isinstance(value, (list, tuple)) or len(value) == 0: 1080 return False 1081 1082 for val in value: 1083 if not isNullPointer(val) and not isSimObject(val): 1084 return False 1085 1086 return True 1087 1088def isSimObjectOrSequence(value): 1089 return isSimObject(value) or isSimObjectSequence(value) 1090 1091def isRoot(obj): 1092 from m5.objects import Root 1093 return obj and obj is Root.getInstance() 1094 1095def isSimObjectOrVector(value): 1096 return isSimObject(value) or isSimObjectVector(value) 1097 1098def tryAsSimObjectOrVector(value): 1099 if isSimObjectOrVector(value): 1100 return value 1101 if isSimObjectSequence(value): 1102 return SimObjectVector(value) 1103 return None 1104 1105def coerceSimObjectOrVector(value): 1106 value = tryAsSimObjectOrVector(value) 1107 if value is None: 1108 raise TypeError, "SimObject or SimObjectVector expected" 1109 return value 1110 1111baseClasses = allClasses.copy() 1112baseInstances = instanceDict.copy() 1113 1114def clear(): 1115 global allClasses, instanceDict 1116 1117 allClasses = baseClasses.copy() 1118 instanceDict = baseInstances.copy() 1119 1120# __all__ defines the list of symbols that get exported when 1121# 'from config import *' is invoked. Try to keep this reasonably 1122# short to avoid polluting other namespaces. 1123__all__ = [ 'SimObject' ]
| 985 self._ccParams = cc_params 986 return self._ccParams 987 988 # Get C++ object corresponding to this object, calling C++ if 989 # necessary to construct it. Does *not* recursively create 990 # children. 991 def getCCObject(self): 992 if not self._ccObject: 993 # Make sure this object is in the configuration hierarchy 994 if not self._parent and not isRoot(self): 995 raise RuntimeError, "Attempt to instantiate orphan node" 996 # Cycles in the configuration hierarchy are not supported. This 997 # will catch the resulting recursion and stop. 998 self._ccObject = -1 999 params = self.getCCParams() 1000 self._ccObject = params.create() 1001 elif self._ccObject == -1: 1002 raise RuntimeError, "%s: Cycle found in configuration hierarchy." \ 1003 % self.path() 1004 return self._ccObject 1005 1006 def descendants(self): 1007 yield self 1008 for child in self._children.itervalues(): 1009 for obj in child.descendants(): 1010 yield obj 1011 1012 # Call C++ to create C++ object corresponding to this object 1013 def createCCObject(self): 1014 self.getCCParams() 1015 self.getCCObject() # force creation 1016 1017 def getValue(self): 1018 return self.getCCObject() 1019 1020 # Create C++ port connections corresponding to the connections in 1021 # _port_refs 1022 def connectPorts(self): 1023 for portRef in self._port_refs.itervalues(): 1024 portRef.ccConnect() 1025 1026 def getMemoryMode(self): 1027 if not isinstance(self, m5.objects.System): 1028 return None 1029 1030 return self._ccObject.getMemoryMode() 1031 1032 def changeTiming(self, mode): 1033 if isinstance(self, m5.objects.System): 1034 # i don't know if there's a better way to do this - calling 1035 # setMemoryMode directly from self._ccObject results in calling 1036 # SimObject::setMemoryMode, not the System::setMemoryMode 1037 self._ccObject.setMemoryMode(mode) 1038 1039 def takeOverFrom(self, old_cpu): 1040 self._ccObject.takeOverFrom(old_cpu._ccObject) 1041 1042 # generate output file for 'dot' to display as a pretty graph. 1043 # this code is currently broken. 1044 def outputDot(self, dot): 1045 label = "{%s|" % self.path 1046 if isSimObject(self.realtype): 1047 label += '%s|' % self.type 1048 1049 if self.children: 1050 # instantiate children in same order they were added for 1051 # backward compatibility (else we can end up with cpu1 1052 # before cpu0). 1053 for c in self.children: 1054 dot.add_edge(pydot.Edge(self.path,c.path, style="bold")) 1055 1056 simobjs = [] 1057 for param in self.params: 1058 try: 1059 if param.value is None: 1060 raise AttributeError, 'Parameter with no value' 1061 1062 value = param.value 1063 string = param.string(value) 1064 except Exception, e: 1065 msg = 'exception in %s:%s\n%s' % (self.name, param.name, e) 1066 e.args = (msg, ) 1067 raise 1068 1069 if isSimObject(param.ptype) and string != "Null": 1070 simobjs.append(string) 1071 else: 1072 label += '%s = %s\\n' % (param.name, string) 1073 1074 for so in simobjs: 1075 label += "|<%s> %s" % (so, so) 1076 dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so, 1077 tailport="w")) 1078 label += '}' 1079 dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label)) 1080 1081 # recursively dump out children 1082 for c in self.children: 1083 c.outputDot(dot) 1084 1085# Function to provide to C++ so it can look up instances based on paths 1086def resolveSimObject(name): 1087 obj = instanceDict[name] 1088 return obj.getCCObject() 1089 1090def isSimObject(value): 1091 return isinstance(value, SimObject) 1092 1093def isSimObjectClass(value): 1094 return issubclass(value, SimObject) 1095 1096def isSimObjectVector(value): 1097 return isinstance(value, SimObjectVector) 1098 1099def isSimObjectSequence(value): 1100 if not isinstance(value, (list, tuple)) or len(value) == 0: 1101 return False 1102 1103 for val in value: 1104 if not isNullPointer(val) and not isSimObject(val): 1105 return False 1106 1107 return True 1108 1109def isSimObjectOrSequence(value): 1110 return isSimObject(value) or isSimObjectSequence(value) 1111 1112def isRoot(obj): 1113 from m5.objects import Root 1114 return obj and obj is Root.getInstance() 1115 1116def isSimObjectOrVector(value): 1117 return isSimObject(value) or isSimObjectVector(value) 1118 1119def tryAsSimObjectOrVector(value): 1120 if isSimObjectOrVector(value): 1121 return value 1122 if isSimObjectSequence(value): 1123 return SimObjectVector(value) 1124 return None 1125 1126def coerceSimObjectOrVector(value): 1127 value = tryAsSimObjectOrVector(value) 1128 if value is None: 1129 raise TypeError, "SimObject or SimObjectVector expected" 1130 return value 1131 1132baseClasses = allClasses.copy() 1133baseInstances = instanceDict.copy() 1134 1135def clear(): 1136 global allClasses, instanceDict 1137 1138 allClasses = baseClasses.copy() 1139 instanceDict = baseInstances.copy() 1140 1141# __all__ defines the list of symbols that get exported when 1142# 'from config import *' is invoked. Try to keep this reasonably 1143# short to avoid polluting other namespaces. 1144__all__ = [ 'SimObject' ]
|