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