SimObject.py revision 1046
18840Sandreas.hansson@arm.com# Copyright (c) 2004 The Regents of The University of Michigan 28840Sandreas.hansson@arm.com# All rights reserved. 38840Sandreas.hansson@arm.com# 48840Sandreas.hansson@arm.com# Redistribution and use in source and binary forms, with or without 58840Sandreas.hansson@arm.com# modification, are permitted provided that the following conditions are 68840Sandreas.hansson@arm.com# met: redistributions of source code must retain the above copyright 78840Sandreas.hansson@arm.com# notice, this list of conditions and the following disclaimer; 88840Sandreas.hansson@arm.com# redistributions in binary form must reproduce the above copyright 98840Sandreas.hansson@arm.com# notice, this list of conditions and the following disclaimer in the 108840Sandreas.hansson@arm.com# documentation and/or other materials provided with the distribution; 118840Sandreas.hansson@arm.com# neither the name of the copyright holders nor the names of its 128840Sandreas.hansson@arm.com# contributors may be used to endorse or promote products derived from 132740SN/A# this software without specific prior written permission. 147534Ssteve.reinhardt@amd.com# 151046SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 161046SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 171046SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 181046SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 191046SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 201046SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 211046SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 221046SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 231046SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 241046SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 251046SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 261046SN/A 271046SN/Afrom __future__ import generators 281046SN/A 291046SN/Aimport os 301046SN/Aimport re 311046SN/Aimport sys 321046SN/A 331046SN/A##################################################################### 341046SN/A# 351046SN/A# M5 Python Configuration Utility 361046SN/A# 371046SN/A# The basic idea is to write simple Python programs that build Python 381046SN/A# objects corresponding to M5 SimObjects for the deisred simulation 392665SN/A# configuration. For now, the Python emits a .ini file that can be 402665SN/A# parsed by M5. In the future, some tighter integration between M5 412665SN/A# and the Python interpreter may allow bypassing the .ini file. 428840Sandreas.hansson@arm.com# 431046SN/A# Each SimObject class in M5 is represented by a Python class with the 445766Snate@binkert.org# same name. The Python inheritance tree mirrors the M5 C++ tree 458331Ssteve.reinhardt@amd.com# (e.g., SimpleCPU derives from BaseCPU in both cases, and all 461438SN/A# SimObjects inherit from a single SimObject base class). To specify 476654Snate@binkert.org# an instance of an M5 SimObject in a configuration, the user simply 486654Snate@binkert.org# instantiates the corresponding Python object. The parameters for 496654Snate@binkert.org# that SimObject are given by assigning to attributes of the Python 506654Snate@binkert.org# object, either using keyword assignment in the constructor or in 516654Snate@binkert.org# separate assignment statements. For example: 524762Snate@binkert.org# 536654Snate@binkert.org# cache = BaseCache('my_cache', root, size=64*K) 543102Sstever@eecs.umich.edu# cache.hit_latency = 3 553102Sstever@eecs.umich.edu# cache.assoc = 8 563102Sstever@eecs.umich.edu# 573102Sstever@eecs.umich.edu# (The first two constructor arguments specify the name of the created 586654Snate@binkert.org# cache and its parent node in the hierarchy.) 593102Sstever@eecs.umich.edu# 603102Sstever@eecs.umich.edu# The magic lies in the mapping of the Python attributes for SimObject 617528Ssteve.reinhardt@amd.com# classes to the actual SimObject parameter specifications. This 628839Sandreas.hansson@arm.com# allows parameter validity checking in the Python code. Continuing 633102Sstever@eecs.umich.edu# the example above, the statements "cache.blurfl=3" or 646654Snate@binkert.org# "cache.assoc='hello'" would both result in runtime errors in Python, 656654Snate@binkert.org# since the BaseCache object has no 'blurfl' parameter and the 'assoc' 66679SN/A# parameter requires an integer, respectively. This magic is done 67679SN/A# primarily by overriding the special __setattr__ method that controls 68679SN/A# assignment to object attributes. 69679SN/A# 70679SN/A# The Python module provides another class, ConfigNode, which is a 71679SN/A# superclass of SimObject. ConfigNode implements the parent/child 721692SN/A# relationship for building the configuration hierarchy tree. 73679SN/A# Concrete instances of ConfigNode can be used to group objects in the 74679SN/A# hierarchy, but do not correspond to SimObjects themselves (like a 75679SN/A# .ini section with "children=" but no "type=". 76679SN/A# 77679SN/A# Once a set of Python objects have been instantiated in a hierarchy, 78679SN/A# calling 'instantiate(obj)' (where obj is the root of the hierarchy) 79679SN/A# will generate a .ini file. See simple-4cpu.py for an example 80679SN/A# (corresponding to m5-test/simple-4cpu.ini). 81679SN/A# 82679SN/A##################################################################### 83679SN/A 84679SN/A##################################################################### 85679SN/A# 86679SN/A# ConfigNode/SimObject classes 871692SN/A# 88679SN/A# The Python class hierarchy rooted by ConfigNode (which is the base 89679SN/A# class of SimObject, which in turn is the base class of all other M5 90679SN/A# SimObject classes) has special attribute behavior. In general, an 91679SN/A# object in this hierarchy has three categories of attribute-like 92679SN/A# things: 93679SN/A# 94679SN/A# 1. Regular Python methods and variables. These must start with an 95679SN/A# underscore to be treated normally. 96679SN/A# 97679SN/A# 2. SimObject parameters. These values are stored as normal Python 98679SN/A# attributes, but all assignments to these attributes are checked 99679SN/A# against the pre-defined set of parameters stored in the class's 100679SN/A# _param_dict dictionary. Assignments to attributes that do not 101679SN/A# correspond to predefined parameters, or that are not of the correct 102679SN/A# type, incur runtime errors. 1032740SN/A# 104679SN/A# 3. Hierarchy children. The child nodes of a ConfigNode are stored 105679SN/A# in the node's _children dictionary, but can be accessed using the 106679SN/A# Python attribute dot-notation (just as they are printed out by the 1074762Snate@binkert.org# simulator). Children cannot be created using attribute assigment; 1084762Snate@binkert.org# they must be added by specifying the parent node in the child's 1094762Snate@binkert.org# constructor or using the '+=' operator. 1102738SN/A 1112738SN/A# The SimObject parameters are the most complex, for a few reasons. 1122738SN/A# First, both parameter descriptions and parameter values are 1137673Snate@binkert.org# inherited. Thus parameter description lookup must go up the 1147673Snate@binkert.org# inheritance chain like normal attribute lookup, but this behavior 1158331Ssteve.reinhardt@amd.com# must be explicitly coded since the lookup occurs in each class's 1168331Ssteve.reinhardt@amd.com# _param_dict attribute. Second, because parameter values can be set 1177673Snate@binkert.org# on SimObject classes (to implement default values), the parameter 1182740SN/A# checking behavior must be enforced on class attribute assignments as 1192740SN/A# well as instance attribute assignments. Finally, because we allow 1202740SN/A# class specialization via inheritance (e.g., see the L1Cache class in 1212740SN/A# the simple-4cpu.py example), we must do parameter checking even on 1221692SN/A# class instantiation. To provide all these features, we use a 1231427SN/A# metaclass to define most of the SimObject parameter behavior for 1247493Ssteve.reinhardt@amd.com# this class hierarchy. 1257493Ssteve.reinhardt@amd.com# 1267493Ssteve.reinhardt@amd.com##################################################################### 1277493Ssteve.reinhardt@amd.com 1281427SN/A# The metaclass for ConfigNode (and thus for everything that derives 1297493Ssteve.reinhardt@amd.com# from ConfigNode, including SimObject). This class controls how new 130679SN/A# classes that derive from ConfigNode are instantiated, and provides 131679SN/A# inherited class behavior (just like a class controls how instances 132679SN/A# of that class are instantiated, and provides inherited instance 1332740SN/A# behavior). 134679SN/Aclass MetaConfigNode(type): 135679SN/A 1361310SN/A # __new__ is called before __init__, and is where the statements 1376654Snate@binkert.org # in the body of the class definition get loaded into the class's 1384762Snate@binkert.org # __dict__. We intercept this to filter out parameter assignments 1392740SN/A # and only allow "private" attributes to be passed to the base 1402740SN/A # __new__ (starting with underscore). 1412740SN/A def __new__(cls, name, bases, dict): 1422740SN/A priv_keys = [k for k in dict.iterkeys() if k.startswith('_')] 1432740SN/A priv_dict = {} 1442740SN/A for k in priv_keys: priv_dict[k] = dict[k]; del dict[k] 1457673Snate@binkert.org # entries left in dict will get passed to __init__, where we'll 1462740SN/A # deal with them as params. 1472740SN/A return super(MetaConfigNode, cls).__new__(cls, name, bases, priv_dict) 1482740SN/A 1492740SN/A # initialization: start out with an empty param dict (makes life 1504762Snate@binkert.org # simpler if we can assume _param_dict is always valid). Also 1514762Snate@binkert.org # build inheritance list to simplify searching for inherited 1522740SN/A # params. Finally set parameters specified in class definition 1534762Snate@binkert.org # (if any). 1544762Snate@binkert.org def __init__(cls, name, bases, dict): 1554762Snate@binkert.org super(MetaConfigNode, cls).__init__(cls, name, bases, {}) 1564762Snate@binkert.org # initialize _param_dict to empty 157679SN/A cls._param_dict = {} 1582711SN/A # __mro__ is the ordered list of classes Python uses for 159679SN/A # method resolution. We want to pick out the ones that have a 1602711SN/A # _param_dict attribute for doing parameter lookups. 1612711SN/A cls._param_bases = \ 1621692SN/A [c for c in cls.__mro__ if hasattr(c, '_param_dict')] 1631310SN/A # initialize attributes with values from class definition 1641427SN/A for (pname, value) in dict.items(): 1652740SN/A try: 1662740SN/A setattr(cls, pname, value) 1672740SN/A except Exception, exc: 1682740SN/A print "Error setting '%s' to '%s' on class '%s'\n" \ 1692740SN/A % (pname, value, cls.__name__), exc 1702740SN/A 1712740SN/A # set the class's parameter dictionary (called when loading 1727528Ssteve.reinhardt@amd.com # class descriptions) 1733105Sstever@eecs.umich.edu def set_param_dict(cls, param_dict): 1742740SN/A # should only be called once (current one should be empty one 1751310SN/A # from __init__) 1761692SN/A assert not cls._param_dict 1771585SN/A cls._param_dict = param_dict 1781692SN/A # initialize attributes with default values 1791692SN/A for (pname, param) in param_dict.items(): 1801692SN/A try: 1811692SN/A setattr(cls, pname, param.default) 1821692SN/A except Exception, exc: 1832740SN/A print "Error setting '%s' default on class '%s'\n" \ 1842740SN/A % (pname, cls.__name__), exc 1852740SN/A 1862740SN/A # Set the class's parameter dictionary given a code string of 1871692SN/A # parameter initializers (as from an object description file). 1885610Snate@binkert.org # Note that the caller must pass in the namespace in which to 1891692SN/A # execute the code (usually the caller's globals()), since if we 1902740SN/A # call globals() from inside this function all we get is this 1911692SN/A # module's internal scope. 1927528Ssteve.reinhardt@amd.com def init_params(cls, init_code, ctx): 1933105Sstever@eecs.umich.edu dict = {} 1942740SN/A try: 1952712SN/A exec fixPythonIndentation(init_code) in ctx, dict 1965610Snate@binkert.org except Exception, exc: 1975610Snate@binkert.org print "Error in %s.init_params:" % cls.__name__, exc 1981692SN/A raise 1994762Snate@binkert.org cls.set_param_dict(dict) 2004762Snate@binkert.org 2014762Snate@binkert.org # Lookup a parameter description by name in the given class. Use 2025610Snate@binkert.org # the _param_bases list defined in __init__ to go up the 2034762Snate@binkert.org # inheritance hierarchy if necessary. 2045610Snate@binkert.org def lookup_param(cls, param_name): 2054859Snate@binkert.org for c in cls._param_bases: 2068597Ssteve.reinhardt@amd.com param = c._param_dict.get(param_name) 2078597Ssteve.reinhardt@amd.com if param: return param 2088597Ssteve.reinhardt@amd.com return None 2098597Ssteve.reinhardt@amd.com 2108597Ssteve.reinhardt@amd.com # Set attribute (called on foo.attr_name = value when foo is an 2118597Ssteve.reinhardt@amd.com # instance of class cls). 2128597Ssteve.reinhardt@amd.com def __setattr__(cls, attr_name, value): 2138597Ssteve.reinhardt@amd.com # normal processing for private attributes 2148597Ssteve.reinhardt@amd.com if attr_name.startswith('_'): 2158597Ssteve.reinhardt@amd.com type.__setattr__(cls, attr_name, value) 2168597Ssteve.reinhardt@amd.com return 2178597Ssteve.reinhardt@amd.com # no '_': must be SimObject param 2188597Ssteve.reinhardt@amd.com param = cls.lookup_param(attr_name) 2198597Ssteve.reinhardt@amd.com if not param: 2202740SN/A raise AttributeError, \ 2212740SN/A "Class %s has no parameter %s" % (cls.__name__, attr_name) 2222740SN/A # It's ok: set attribute by delegating to 'object' class. 2232740SN/A # Note the use of param.make_value() to verify/canonicalize 2242740SN/A # the assigned value 2252740SN/A type.__setattr__(cls, attr_name, param.make_value(value)) 2262740SN/A 2272740SN/A # generator that iterates across all parameters for this class and 2281527SN/A # all classes it inherits from 2292740SN/A def all_param_names(cls): 2301585SN/A for c in cls._param_bases: 2311427SN/A for p in c._param_dict.iterkeys(): 2322738SN/A yield p 2332738SN/A 2343105Sstever@eecs.umich.edu# The ConfigNode class is the root of the special hierarchy. Most of 2352738SN/A# the code in this class deals with the configuration hierarchy itself 2361427SN/A# (parent/child node relationships). 2371427SN/Aclass ConfigNode(object): 2381427SN/A # Specify metaclass. Any class inheriting from ConfigNode will 2391427SN/A # get this metaclass. 2401427SN/A __metaclass__ = MetaConfigNode 2411427SN/A 2421427SN/A # Constructor. Since bare ConfigNodes don't have parameters, just 2431427SN/A # worry about the name and the parent/child stuff. 2441427SN/A def __init__(self, _name, _parent=None): 2451427SN/A # Type-check _name 2461427SN/A if type(_name) != str: 2471427SN/A if isinstance(_name, ConfigNode): 2487493Ssteve.reinhardt@amd.com # special case message for common error of trying to 2491427SN/A # coerce a SimObject to the wrong type 2501427SN/A raise TypeError, \ 2511427SN/A "Attempt to coerce %s to %s" \ 2523100SN/A % (_name.__class__.__name__, self.__class__.__name__) 2533100SN/A else: 2543100SN/A raise TypeError, \ 2553100SN/A "%s name must be string (was %s, %s)" \ 2563100SN/A % (self.__class__.__name__, _name, type(_name)) 2573100SN/A # if specified, parent must be a subclass of ConfigNode 2583105Sstever@eecs.umich.edu if _parent != None and not isinstance(_parent, ConfigNode): 2593105Sstever@eecs.umich.edu raise TypeError, \ 2603105Sstever@eecs.umich.edu "%s parent must be ConfigNode subclass (was %s, %s)" \ 2613105Sstever@eecs.umich.edu % (self.__class__.__name__, _name, type(_name)) 2623105Sstever@eecs.umich.edu self._name = _name 2638321Ssteve.reinhardt@amd.com self._parent = _parent 2643105Sstever@eecs.umich.edu if (_parent): 2653105Sstever@eecs.umich.edu _parent._add_child(self) 2663105Sstever@eecs.umich.edu self._children = {} 2673105Sstever@eecs.umich.edu # keep a list of children in addition to the dictionary keys 2683105Sstever@eecs.umich.edu # so we can remember the order they were added and print them 2698321Ssteve.reinhardt@amd.com # out in that order. 2708321Ssteve.reinhardt@amd.com self._child_list = [] 2718321Ssteve.reinhardt@amd.com 2728321Ssteve.reinhardt@amd.com # When printing (e.g. to .ini file), just give the name. 2738321Ssteve.reinhardt@amd.com def __str__(self): 2748321Ssteve.reinhardt@amd.com return self._name 2758321Ssteve.reinhardt@amd.com 2768321Ssteve.reinhardt@amd.com # Catch attribute accesses that could be requesting children, and 2778321Ssteve.reinhardt@amd.com # satisfy them. Note that __getattr__ is called only if the 2788321Ssteve.reinhardt@amd.com # regular attribute lookup fails, so private and parameter lookups 2798321Ssteve.reinhardt@amd.com # will already be satisfied before we ever get here. 2808321Ssteve.reinhardt@amd.com def __getattr__(self, name): 2818321Ssteve.reinhardt@amd.com try: 2828321Ssteve.reinhardt@amd.com return self._children[name] 2833105Sstever@eecs.umich.edu except KeyError: 2843105Sstever@eecs.umich.edu raise AttributeError, \ 2853105Sstever@eecs.umich.edu "Node '%s' has no attribute or child '%s'" \ 2863105Sstever@eecs.umich.edu % (self._name, name) 2873105Sstever@eecs.umich.edu 2883105Sstever@eecs.umich.edu # Set attribute. All attribute assignments go through here. Must 2893105Sstever@eecs.umich.edu # be private attribute (starts with '_') or valid parameter entry. 2903105Sstever@eecs.umich.edu # Basically identical to MetaConfigClass.__setattr__(), except 2913105Sstever@eecs.umich.edu # this sets attributes on specific instances rather than on classes. 2923105Sstever@eecs.umich.edu def __setattr__(self, attr_name, value): 2933105Sstever@eecs.umich.edu if attr_name.startswith('_'): 2943105Sstever@eecs.umich.edu object.__setattr__(self, attr_name, value) 2953105Sstever@eecs.umich.edu return 2963105Sstever@eecs.umich.edu # not private; look up as param 2973105Sstever@eecs.umich.edu param = self.__class__.lookup_param(attr_name) 2983105Sstever@eecs.umich.edu if not param: 2993105Sstever@eecs.umich.edu raise AttributeError, \ 3001585SN/A "Class %s has no parameter %s" \ 3011310SN/A % (self.__class__.__name__, attr_name) 3021310SN/A # It's ok: set attribute by delegating to 'object' class. 3031310SN/A # Note the use of param.make_value() to verify/canonicalize 3041310SN/A # the assigned value. 3057673Snate@binkert.org v = param.make_value(value) 3061310SN/A object.__setattr__(self, attr_name, v) 3071310SN/A 3081310SN/A # A little convenient magic: if the parameter is a ConfigNode 3091310SN/A # (or vector of ConfigNodes, or anything else with a 3101427SN/A # '_set_parent_if_none' function attribute) that does not have 3111310SN/A # a parent (and so is not part of the configuration 3121310SN/A # hierarchy), then make this node its parent. 3132738SN/A if hasattr(v, '_set_parent_if_none'): 3143105Sstever@eecs.umich.edu v._set_parent_if_none(self) 3152738SN/A 3162738SN/A def _path(self): 3172740SN/A # Return absolute path from root. 3182740SN/A if not self._parent and self._name != 'Universe': 3192740SN/A print >> sys.stderr, "Warning:", self._name, "has no parent" 3202740SN/A parent_path = self._parent and self._parent._path() 3212740SN/A if parent_path and parent_path != 'Universe': 3222740SN/A return parent_path + '.' + self._name 3232740SN/A else: 3243105Sstever@eecs.umich.edu return self._name 3251310SN/A 3263105Sstever@eecs.umich.edu # Add a child to this node. 3273105Sstever@eecs.umich.edu def _add_child(self, new_child): 3283105Sstever@eecs.umich.edu # set child's parent before calling this function 3293105Sstever@eecs.umich.edu assert new_child._parent == self 3303105Sstever@eecs.umich.edu if not isinstance(new_child, ConfigNode): 3318321Ssteve.reinhardt@amd.com raise TypeError, \ 3323105Sstever@eecs.umich.edu "ConfigNode child must also be of class ConfigNode" 3333105Sstever@eecs.umich.edu if new_child._name in self._children: 3343105Sstever@eecs.umich.edu raise AttributeError, \ 3353105Sstever@eecs.umich.edu "Node '%s' already has a child '%s'" \ 3363105Sstever@eecs.umich.edu % (self._name, new_child._name) 3371310SN/A self._children[new_child._name] = new_child 3381585SN/A self._child_list += [new_child] 3397675Snate@binkert.org 3407675Snate@binkert.org # operator overload for '+='. You can say "node += child" to add 3417675Snate@binkert.org # a child that was created with parent=None. An early attempt 3427675Snate@binkert.org # at playing with syntax; turns out not to be that useful. 3437675Snate@binkert.org def __iadd__(self, new_child): 3447675Snate@binkert.org if new_child._parent != None: 3457675Snate@binkert.org raise AttributeError, \ 3467675Snate@binkert.org "Node '%s' already has a parent" % new_child._name 3477675Snate@binkert.org new_child._parent = self 3481692SN/A self._add_child(new_child) 3491692SN/A return self 3501585SN/A 3517528Ssteve.reinhardt@amd.com # Set this instance's parent to 'parent' if it doesn't already 3527528Ssteve.reinhardt@amd.com # have one. See ConfigNode.__setattr__(). 3537528Ssteve.reinhardt@amd.com def _set_parent_if_none(self, parent): 3541585SN/A if self._parent == None: 3551585SN/A parent += self 3561585SN/A 3573100SN/A # Print instance info to .ini file. 3583100SN/A def _instantiate(self): 3593100SN/A print '[' + self._path() + ']' # .ini section header 3608596Ssteve.reinhardt@amd.com if self._child_list: 3618596Ssteve.reinhardt@amd.com # instantiate children in same order they were added for 3628596Ssteve.reinhardt@amd.com # backward compatibility (else we can end up with cpu1 3638596Ssteve.reinhardt@amd.com # before cpu0). 3648596Ssteve.reinhardt@amd.com print 'children =', ' '.join([c._name for c in self._child_list]) 3658596Ssteve.reinhardt@amd.com self._instantiateParams() 3668596Ssteve.reinhardt@amd.com print 3678596Ssteve.reinhardt@amd.com # recursively dump out children 3688597Ssteve.reinhardt@amd.com for c in self._child_list: 3698597Ssteve.reinhardt@amd.com c._instantiate() 3708597Ssteve.reinhardt@amd.com 3718597Ssteve.reinhardt@amd.com # ConfigNodes have no parameters. Overridden by SimObject. 3728597Ssteve.reinhardt@amd.com def _instantiateParams(self): 3738597Ssteve.reinhardt@amd.com pass 3748597Ssteve.reinhardt@amd.com 3758597Ssteve.reinhardt@amd.com# SimObject is a minimal extension of ConfigNode, implementing a 3768597Ssteve.reinhardt@amd.com# hierarchy node that corresponds to an M5 SimObject. It prints out a 3778597Ssteve.reinhardt@amd.com# "type=" line to indicate its SimObject class, prints out the 3788597Ssteve.reinhardt@amd.com# assigned parameters corresponding to its class, and allows 3798597Ssteve.reinhardt@amd.com# parameters to be set by keyword in the constructor. Note that most 3808597Ssteve.reinhardt@amd.com# of the heavy lifting for the SimObject param handling is done in the 3818597Ssteve.reinhardt@amd.com# MetaConfigNode metaclass. 3828597Ssteve.reinhardt@amd.com 3838597Ssteve.reinhardt@amd.comclass SimObject(ConfigNode): 3848597Ssteve.reinhardt@amd.com # initialization: like ConfigNode, but handle keyword-based 3858597Ssteve.reinhardt@amd.com # parameter initializers. 3868597Ssteve.reinhardt@amd.com def __init__(self, _name, _parent=None, **params): 3878597Ssteve.reinhardt@amd.com ConfigNode.__init__(self, _name, _parent) 3888597Ssteve.reinhardt@amd.com for param, value in params.items(): 3898596Ssteve.reinhardt@amd.com setattr(self, param, value) 3908596Ssteve.reinhardt@amd.com 3918596Ssteve.reinhardt@amd.com # print type and parameter values to .ini file 3928596Ssteve.reinhardt@amd.com def _instantiateParams(self): 3938596Ssteve.reinhardt@amd.com print "type =", self.__class__._name 3948596Ssteve.reinhardt@amd.com for pname in self.__class__.all_param_names(): 3958596Ssteve.reinhardt@amd.com value = getattr(self, pname) 3968596Ssteve.reinhardt@amd.com if value != None: 3978596Ssteve.reinhardt@amd.com print pname, '=', value 3988596Ssteve.reinhardt@amd.com 3998596Ssteve.reinhardt@amd.com def _sim_code(cls): 4008596Ssteve.reinhardt@amd.com name = cls.__name__ 4018596Ssteve.reinhardt@amd.com param_names = cls._param_dict.keys() 4028840Sandreas.hansson@arm.com param_names.sort() 4038596Ssteve.reinhardt@amd.com code = "BEGIN_DECLARE_SIM_OBJECT_PARAMS(%s)\n" % name 4048596Ssteve.reinhardt@amd.com decls = [" " + cls._param_dict[pname].sim_decl(pname) \ 4058596Ssteve.reinhardt@amd.com for pname in param_names] 4068596Ssteve.reinhardt@amd.com code += "\n".join(decls) + "\n" 4078596Ssteve.reinhardt@amd.com code += "END_DECLARE_SIM_OBJECT_PARAMS(%s)\n\n" % name 4088596Ssteve.reinhardt@amd.com code += "BEGIN_INIT_SIM_OBJECT_PARAMS(%s)\n" % name 4098596Ssteve.reinhardt@amd.com inits = [" " + cls._param_dict[pname].sim_init(pname) \ 4108597Ssteve.reinhardt@amd.com for pname in param_names] 4118860Sandreas.hansson@arm.com code += ",\n".join(inits) + "\n" 4128860Sandreas.hansson@arm.com code += "END_INIT_SIM_OBJECT_PARAMS(%s)\n\n" % name 4138860Sandreas.hansson@arm.com return code 4148860Sandreas.hansson@arm.com _sim_code = classmethod(_sim_code) 4158860Sandreas.hansson@arm.com 4168860Sandreas.hansson@arm.com##################################################################### 4178860Sandreas.hansson@arm.com# 4188860Sandreas.hansson@arm.com# Parameter description classes 4198860Sandreas.hansson@arm.com# 4208860Sandreas.hansson@arm.com# The _param_dict dictionary in each class maps parameter names to 4218860Sandreas.hansson@arm.com# either a Param or a VectorParam object. These objects contain the 4228860Sandreas.hansson@arm.com# parameter description string, the parameter type, and the default 4238860Sandreas.hansson@arm.com# value (loaded from the PARAM section of the .odesc files). The 4248596Ssteve.reinhardt@amd.com# make_value() method on these objects is used to force whatever value 4258596Ssteve.reinhardt@amd.com# is assigned to the parameter to the appropriate type. 4268596Ssteve.reinhardt@amd.com# 4278596Ssteve.reinhardt@amd.com# Note that the default values are loaded into the class's attribute 4288596Ssteve.reinhardt@amd.com# space when the parameter dictionary is initialized (in 4298597Ssteve.reinhardt@amd.com# MetaConfigNode.set_param_dict()); after that point they aren't 4308596Ssteve.reinhardt@amd.com# used. 4318596Ssteve.reinhardt@amd.com# 4328596Ssteve.reinhardt@amd.com##################################################################### 4338596Ssteve.reinhardt@amd.com 4348596Ssteve.reinhardt@amd.comdef isNullPointer(value): 4358596Ssteve.reinhardt@amd.com return isinstance(value, NullSimObject) 4368596Ssteve.reinhardt@amd.com 4378596Ssteve.reinhardt@amd.com# Regular parameter. 4388596Ssteve.reinhardt@amd.comclass Param(object): 4398596Ssteve.reinhardt@amd.com # Constructor. E.g., Param(Int, "number of widgets", 5) 4408596Ssteve.reinhardt@amd.com def __init__(self, ptype, desc, default=None): 4418596Ssteve.reinhardt@amd.com self.ptype = ptype 4428596Ssteve.reinhardt@amd.com self.ptype_name = self.ptype.__name__ 4438596Ssteve.reinhardt@amd.com self.desc = desc 4448596Ssteve.reinhardt@amd.com self.default = default 4458597Ssteve.reinhardt@amd.com 4468597Ssteve.reinhardt@amd.com # Convert assigned value to appropriate type. Force parameter 4478597Ssteve.reinhardt@amd.com # value (rhs of '=') to ptype (or None, which means not set). 4488597Ssteve.reinhardt@amd.com def make_value(self, value): 4498597Ssteve.reinhardt@amd.com # nothing to do if None or already correct type. Also allow NULL 4508597Ssteve.reinhardt@amd.com # pointer to be assigned where a SimObject is expected. 4518597Ssteve.reinhardt@amd.com if value == None or isinstance(value, self.ptype) or \ 4528597Ssteve.reinhardt@amd.com isNullPointer(value) and issubclass(self.ptype, ConfigNode): 4538597Ssteve.reinhardt@amd.com return value 4548597Ssteve.reinhardt@amd.com # this type conversion will raise an exception if it's illegal 4558596Ssteve.reinhardt@amd.com return self.ptype(value) 4568596Ssteve.reinhardt@amd.com 4578596Ssteve.reinhardt@amd.com def sim_decl(self, name): 4588596Ssteve.reinhardt@amd.com return 'Param<%s> %s;' % (self.ptype_name, name) 4598596Ssteve.reinhardt@amd.com 4608596Ssteve.reinhardt@amd.com def sim_init(self, name): 4618596Ssteve.reinhardt@amd.com if self.default == None: 4628596Ssteve.reinhardt@amd.com return 'INIT_PARAM(%s, "%s")' % (name, self.desc) 4638596Ssteve.reinhardt@amd.com else: 4648596Ssteve.reinhardt@amd.com return 'INIT_PARAM_DFLT(%s, "%s", %s)' % \ 4658596Ssteve.reinhardt@amd.com (name, self.desc, str(self.default)) 4668596Ssteve.reinhardt@amd.com 4673100SN/A# The _VectorParamValue class is a wrapper for vector-valued 4683100SN/A# parameters. The leading underscore indicates that users shouldn't 4693100SN/A# see this class; it's magically generated by VectorParam. The 4704762Snate@binkert.org# parameter values are stored in the 'value' field as a Python list of 4718840Sandreas.hansson@arm.com# whatever type the parameter is supposed to be. The only purpose of 4723100SN/A# storing these instead of a raw Python list is that we can override 4733100SN/A# the __str__() method to not print out '[' and ']' in the .ini file. 4743100SN/Aclass _VectorParamValue(object): 4753100SN/A def __init__(self, value): 4763100SN/A assert isinstance(value, list) or value == None 4773100SN/A self.value = value 4783100SN/A 4797675Snate@binkert.org def __str__(self): 4807675Snate@binkert.org return ' '.join(map(str, self.value)) 4817675Snate@binkert.org 4827675Snate@binkert.org # Set member instance's parents to 'parent' if they don't already 4837675Snate@binkert.org # have one. Extends "magic" parenting of ConfigNodes to vectors 4847675Snate@binkert.org # of ConfigNodes as well. See ConfigNode.__setattr__(). 4857675Snate@binkert.org def _set_parent_if_none(self, parent): 4867675Snate@binkert.org if self.value and hasattr(self.value[0], '_set_parent_if_none'): 4877675Snate@binkert.org for v in self.value: 4887675Snate@binkert.org v._set_parent_if_none(parent) 4897675Snate@binkert.org 4907675Snate@binkert.org# Vector-valued parameter description. Just like Param, except that 4917675Snate@binkert.org# the value is a vector (list) of the specified type instead of a 4927675Snate@binkert.org# single value. 4937811Ssteve.reinhardt@amd.comclass VectorParam(Param): 4947675Snate@binkert.org 4957675Snate@binkert.org # Inherit Param constructor. However, the resulting parameter 4968597Ssteve.reinhardt@amd.com # will be a list of ptype rather than a single element of ptype. 4978597Ssteve.reinhardt@amd.com def __init__(self, ptype, desc, default=None): 4988597Ssteve.reinhardt@amd.com Param.__init__(self, ptype, desc, default) 4998597Ssteve.reinhardt@amd.com 5008597Ssteve.reinhardt@amd.com # Convert assigned value to appropriate type. If the RHS is not a 5018597Ssteve.reinhardt@amd.com # list or tuple, it generates a single-element list. 5028597Ssteve.reinhardt@amd.com def make_value(self, value): 5038597Ssteve.reinhardt@amd.com if value == None: return value 5048597Ssteve.reinhardt@amd.com if isinstance(value, list) or isinstance(value, tuple): 5058597Ssteve.reinhardt@amd.com # list: coerce each element into new list 5068597Ssteve.reinhardt@amd.com val_list = [Param.make_value(self, v) for v in iter(value)] 5078597Ssteve.reinhardt@amd.com else: 5088737Skoansin.tan@gmail.com # singleton: coerce & wrap in a list 5098597Ssteve.reinhardt@amd.com val_list = [Param.make_value(self, value)] 5107673Snate@binkert.org # wrap list in _VectorParamValue (see above) 5117673Snate@binkert.org return _VectorParamValue(val_list) 5128840Sandreas.hansson@arm.com 5138840Sandreas.hansson@arm.com def sim_decl(self, name): 5147673Snate@binkert.org return 'VectorParam<%s> %s;' % (self.ptype_name, name) 5154762Snate@binkert.org 5165610Snate@binkert.org # sim_init inherited from Param 5177673Snate@binkert.org 5187673Snate@binkert.org##################################################################### 5194762Snate@binkert.org# 5204762Snate@binkert.org# Parameter Types 5214762Snate@binkert.org# 5227673Snate@binkert.org# Though native Python types could be used to specify parameter types 5237673Snate@binkert.org# (the 'ptype' field of the Param and VectorParam classes), it's more 5244762Snate@binkert.org# flexible to define our own set of types. This gives us more control 5258596Ssteve.reinhardt@amd.com# over how Python expressions are converted to values (via the 5268597Ssteve.reinhardt@amd.com# __init__() constructor) and how these values are printed out (via 5278597Ssteve.reinhardt@amd.com# the __str__() conversion method). Eventually we'll need these types 5288597Ssteve.reinhardt@amd.com# to correspond to distinct C++ types as well. 5298597Ssteve.reinhardt@amd.com# 5308597Ssteve.reinhardt@amd.com##################################################################### 5318597Ssteve.reinhardt@amd.com 5328597Ssteve.reinhardt@amd.com# Integer parameter type. 5338597Ssteve.reinhardt@amd.comclass Int(object): 5348597Ssteve.reinhardt@amd.com # Constructor. Value must be Python int or long (long integer). 5358596Ssteve.reinhardt@amd.com def __init__(self, value): 5368597Ssteve.reinhardt@amd.com t = type(value) 5378597Ssteve.reinhardt@amd.com if t == int or t == long: 5388597Ssteve.reinhardt@amd.com self.value = value 5398597Ssteve.reinhardt@amd.com else: 5408597Ssteve.reinhardt@amd.com raise TypeError, "Int param got value %s %s" % (repr(value), t) 5418597Ssteve.reinhardt@amd.com 5428597Ssteve.reinhardt@amd.com # Use Python string conversion. Note that this puts an 'L' on the 5438596Ssteve.reinhardt@amd.com # end of long integers; we can strip that off here if it gives us 5448597Ssteve.reinhardt@amd.com # trouble. 5458597Ssteve.reinhardt@amd.com def __str__(self): 5468597Ssteve.reinhardt@amd.com return str(self.value) 5478597Ssteve.reinhardt@amd.com 5488597Ssteve.reinhardt@amd.com# Counter, Addr, and Tick are just aliases for Int for now. 5498597Ssteve.reinhardt@amd.comclass Counter(Int): 5508840Sandreas.hansson@arm.com pass 5518840Sandreas.hansson@arm.com 5528840Sandreas.hansson@arm.comclass Addr(Int): 5538597Ssteve.reinhardt@amd.com pass 5548597Ssteve.reinhardt@amd.com 5555488Snate@binkert.orgclass Tick(Int): 5567673Snate@binkert.org pass 5577673Snate@binkert.org 5585488Snate@binkert.org# Boolean parameter type. 5595488Snate@binkert.orgclass Bool(object): 5605488Snate@binkert.org 5613100SN/A # Constructor. Typically the value will be one of the Python bool 5622740SN/A # constants True or False (or the aliases true and false below). 563679SN/A # Also need to take integer 0 or 1 values since bool was not a 564679SN/A # distinct type in Python 2.2. Parse a bunch of boolean-sounding 5651692SN/A # strings too just for kicks. 5661692SN/A def __init__(self, value): 567679SN/A t = type(value) 5681692SN/A if t == bool: 5693100SN/A self.value = value 5704762Snate@binkert.org elif t == int or t == long: 5713100SN/A if value == 1: 5728597Ssteve.reinhardt@amd.com self.value = True 5738597Ssteve.reinhardt@amd.com elif value == 0: 5748597Ssteve.reinhardt@amd.com self.value = False 5758597Ssteve.reinhardt@amd.com elif t == str: 5768597Ssteve.reinhardt@amd.com v = value.lower() 5778597Ssteve.reinhardt@amd.com if v == "true" or v == "t" or v == "yes" or v == "y": 5788597Ssteve.reinhardt@amd.com self.value = True 5798597Ssteve.reinhardt@amd.com elif v == "false" or v == "f" or v == "no" or v == "n": 5808597Ssteve.reinhardt@amd.com self.value = False 5818597Ssteve.reinhardt@amd.com # if we didn't set it yet, it must not be something we understand 5828597Ssteve.reinhardt@amd.com if not hasattr(self, 'value'): 5838597Ssteve.reinhardt@amd.com raise TypeError, "Bool param got value %s %s" % (repr(value), t) 5848597Ssteve.reinhardt@amd.com 5858597Ssteve.reinhardt@amd.com # Generate printable string version. 5868597Ssteve.reinhardt@amd.com def __str__(self): 5878597Ssteve.reinhardt@amd.com if self.value: return "true" 5888597Ssteve.reinhardt@amd.com else: return "false" 5898597Ssteve.reinhardt@amd.com 5908597Ssteve.reinhardt@amd.com# String-valued parameter. 5918597Ssteve.reinhardt@amd.comclass String(object): 5928597Ssteve.reinhardt@amd.com # Constructor. Value must be Python string. 5938597Ssteve.reinhardt@amd.com def __init__(self, value): 5948597Ssteve.reinhardt@amd.com t = type(value) 5958597Ssteve.reinhardt@amd.com if t == str: 5968597Ssteve.reinhardt@amd.com self.value = value 5978597Ssteve.reinhardt@amd.com else: 5988597Ssteve.reinhardt@amd.com raise TypeError, "String param got value %s %s" % (repr(value), t) 5998597Ssteve.reinhardt@amd.com 6008597Ssteve.reinhardt@amd.com # Generate printable string version. Not too tricky. 6018597Ssteve.reinhardt@amd.com def __str__(self): 6028597Ssteve.reinhardt@amd.com return self.value 6038597Ssteve.reinhardt@amd.com 6048597Ssteve.reinhardt@amd.com# Special class for NULL pointers. Note the special check in 6058597Ssteve.reinhardt@amd.com# make_param_value() above that lets these be assigned where a 6068597Ssteve.reinhardt@amd.com# SimObject is required. 6078597Ssteve.reinhardt@amd.comclass NullSimObject(object): 6088597Ssteve.reinhardt@amd.com # Constructor. No parameters, nothing to do. 6098597Ssteve.reinhardt@amd.com def __init__(self): 6102740SN/A pass 6112740SN/A 6122740SN/A def __str__(self): 6132740SN/A return "NULL" 6142740SN/A 6152740SN/A# The only instance you'll ever need... 6162740SN/ANULL = NullSimObject() 6172740SN/A 6182740SN/A# Enumerated types are a little more complex. The user specifies the 6192740SN/A# type as Enum(foo) where foo is either a list or dictionary of 6202740SN/A# alternatives (typically strings, but not necessarily so). (In the 6212740SN/A# long run, the integer value of the parameter will be the list index 6222740SN/A# or the corresponding dictionary value. For now, since we only check 6232740SN/A# that the alternative is valid and then spit it into a .ini file, 6242740SN/A# there's not much point in using the dictionary.) 6252740SN/A 6262711SN/A# What Enum() must do is generate a new type encapsulating the 6272740SN/A# provided list/dictionary so that specific values of the parameter 6282740SN/A# can be instances of that type. We define two hidden internal 6292740SN/A# classes (_ListEnum and _DictEnum) to serve as base classes, then 6302711SN/A# derive the new type from the appropriate base class on the fly. 6312740SN/A 6322740SN/A 6337528Ssteve.reinhardt@amd.com# Base class for list-based Enum types. 6342740SN/Aclass _ListEnum(object): 6354762Snate@binkert.org # Constructor. Value must be a member of the type's map list. 6362740SN/A def __init__(self, value): 6372712SN/A if value in self.map: 6388321Ssteve.reinhardt@amd.com self.value = value 6398321Ssteve.reinhardt@amd.com self.index = self.map.index(value) 6408321Ssteve.reinhardt@amd.com else: 6418321Ssteve.reinhardt@amd.com raise TypeError, "Enum param got bad value '%s' (not in %s)" \ 6428321Ssteve.reinhardt@amd.com % (value, self.map) 6438321Ssteve.reinhardt@amd.com 6448321Ssteve.reinhardt@amd.com # Generate printable string version of value. 6458321Ssteve.reinhardt@amd.com def __str__(self): 6462711SN/A return str(self.value) 6477528Ssteve.reinhardt@amd.com 6487528Ssteve.reinhardt@amd.comclass _DictEnum(object): 6492740SN/A # Constructor. Value must be a key in the type's map dictionary. 6502740SN/A def __init__(self, value): 6512740SN/A if value in self.map: 6527528Ssteve.reinhardt@amd.com self.value = value 6537528Ssteve.reinhardt@amd.com self.index = self.map[value] 6547528Ssteve.reinhardt@amd.com else: 6557528Ssteve.reinhardt@amd.com raise TypeError, "Enum param got bad value '%s' (not in %s)" \ 6562740SN/A % (value, self.map.keys()) 6572740SN/A 6583105Sstever@eecs.umich.edu # Generate printable string version of value. 6593105Sstever@eecs.umich.edu def __str__(self): 6603105Sstever@eecs.umich.edu return str(self.value) 6611692SN/A 6621692SN/A# Enum metaclass... calling Enum(foo) generates a new type (class) 6631692SN/A# that derives from _ListEnum or _DictEnum as appropriate. 664679SN/Aclass Enum(type): 6652740SN/A # counter to generate unique names for generated classes 6662740SN/A counter = 1 6672740SN/A 6682740SN/A def __new__(cls, map): 6692740SN/A if isinstance(map, dict): 6701692SN/A base = _DictEnum 6712740SN/A keys = map.keys() 6722740SN/A elif isinstance(map, list): 6732740SN/A base = _ListEnum 6742740SN/A keys = map 6752740SN/A else: 6762740SN/A raise TypeError, "Enum map must be list or dict (got %s)" % map 6772740SN/A classname = "Enum%04d" % Enum.counter 6782740SN/A Enum.counter += 1 6792740SN/A # New class derives from selected base, and gets a 'map' 6802740SN/A # attribute containing the specified list or dict. 6812740SN/A return type.__new__(cls, classname, (base,), { 'map': map }) 6822740SN/A 6832740SN/A 6842740SN/A# 6852740SN/A# "Constants"... handy aliases for various values. 6861343SN/A# 6873105Sstever@eecs.umich.edu 6883105Sstever@eecs.umich.edu# For compatibility with C++ bool constants. 6893105Sstever@eecs.umich.edufalse = False 6903105Sstever@eecs.umich.edutrue = True 6913105Sstever@eecs.umich.edu 6923105Sstever@eecs.umich.edu# Some memory range specifications use this as a default upper bound. 6933105Sstever@eecs.umich.eduMAX_ADDR = 2**64 - 1 6943105Sstever@eecs.umich.edu 6953105Sstever@eecs.umich.edu# For power-of-two sizing, e.g. 64*K gives an integer value 65536. 6963105Sstever@eecs.umich.eduK = 1024 6971692SN/AM = K*K 6982738SN/AG = K*M 6993105Sstever@eecs.umich.edu 7002738SN/A##################################################################### 7011692SN/A 7021692SN/A# Munge an arbitrary Python code string to get it to execute (mostly 7031427SN/A# dealing with indentation). Stolen from isa_parser.py... see 7047528Ssteve.reinhardt@amd.com# comments there for a more detailed description. 7057528Ssteve.reinhardt@amd.comdef fixPythonIndentation(s): 7067528Ssteve.reinhardt@amd.com # get rid of blank lines first 7077500Ssteve.reinhardt@amd.com s = re.sub(r'(?m)^\s*\n', '', s); 7087500Ssteve.reinhardt@amd.com if (s != '' and re.match(r'[ \t]', s[0])): 7097500Ssteve.reinhardt@amd.com s = 'if 1:\n' + s 7107527Ssteve.reinhardt@amd.com return s 7117527Ssteve.reinhardt@amd.com 7127500Ssteve.reinhardt@amd.com# Hook to generate C++ parameter code. 7137500Ssteve.reinhardt@amd.comdef gen_sim_code(file): 7147500Ssteve.reinhardt@amd.com for objname in sim_object_list: 7151692SN/A print >> file, eval("%s._sim_code()" % objname) 7161692SN/A 7171427SN/A# The final hook to generate .ini files. Called from configuration 7181692SN/A# script once config is built. 7191692SN/Adef instantiate(*objs): 7201692SN/A for obj in objs: 7211692SN/A obj._instantiate() 7221692SN/A 7231692SN/A 7241692SN/A