isa_parser.py revision 6691:cd68b6ecd68d
1# Copyright (c) 2003-2005 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
29import os
30import sys
31import re
32import string
33import traceback
34# get type names
35from types import *
36
37from m5.util.grammar import Grammar
38
39class ISAParser(Grammar):
40    def __init__(self, *args, **kwargs):
41        super(ISAParser, self).__init__(*args, **kwargs)
42        self.templateMap = {}
43
44    #####################################################################
45    #
46    #                                Lexer
47    #
48    # The PLY lexer module takes two things as input:
49    # - A list of token names (the string list 'tokens')
50    # - A regular expression describing a match for each token.  The
51    #   regexp for token FOO can be provided in two ways:
52    #   - as a string variable named t_FOO
53    #   - as the doc string for a function named t_FOO.  In this case,
54    #     the function is also executed, allowing an action to be
55    #     associated with each token match.
56    #
57    #####################################################################
58
59    # Reserved words.  These are listed separately as they are matched
60    # using the same regexp as generic IDs, but distinguished in the
61    # t_ID() function.  The PLY documentation suggests this approach.
62    reserved = (
63        'BITFIELD', 'DECODE', 'DECODER', 'DEFAULT', 'DEF', 'EXEC', 'FORMAT',
64        'HEADER', 'LET', 'NAMESPACE', 'OPERAND_TYPES', 'OPERANDS',
65        'OUTPUT', 'SIGNED', 'TEMPLATE'
66        )
67
68    # List of tokens.  The lex module requires this.
69    tokens = reserved + (
70        # identifier
71        'ID',
72
73        # integer literal
74        'INTLIT',
75
76        # string literal
77        'STRLIT',
78
79        # code literal
80        'CODELIT',
81
82        # ( ) [ ] { } < > , ; . : :: *
83        'LPAREN', 'RPAREN',
84        'LBRACKET', 'RBRACKET',
85        'LBRACE', 'RBRACE',
86        'LESS', 'GREATER', 'EQUALS',
87        'COMMA', 'SEMI', 'DOT', 'COLON', 'DBLCOLON',
88        'ASTERISK',
89
90        # C preprocessor directives
91        'CPPDIRECTIVE'
92
93    # The following are matched but never returned. commented out to
94    # suppress PLY warning
95        # newfile directive
96    #    'NEWFILE',
97
98        # endfile directive
99    #    'ENDFILE'
100    )
101
102    # Regular expressions for token matching
103    t_LPAREN           = r'\('
104    t_RPAREN           = r'\)'
105    t_LBRACKET         = r'\['
106    t_RBRACKET         = r'\]'
107    t_LBRACE           = r'\{'
108    t_RBRACE           = r'\}'
109    t_LESS             = r'\<'
110    t_GREATER          = r'\>'
111    t_EQUALS           = r'='
112    t_COMMA            = r','
113    t_SEMI             = r';'
114    t_DOT              = r'\.'
115    t_COLON            = r':'
116    t_DBLCOLON         = r'::'
117    t_ASTERISK         = r'\*'
118
119    # Identifiers and reserved words
120    reserved_map = { }
121    for r in reserved:
122        reserved_map[r.lower()] = r
123
124    def t_ID(self, t):
125        r'[A-Za-z_]\w*'
126        t.type = self.reserved_map.get(t.value, 'ID')
127        return t
128
129    # Integer literal
130    def t_INTLIT(self, t):
131        r'(0x[\da-fA-F]+)|\d+'
132        try:
133            t.value = int(t.value,0)
134        except ValueError:
135            error(t.lexer.lineno, 'Integer value "%s" too large' % t.value)
136            t.value = 0
137        return t
138
139    # String literal.  Note that these use only single quotes, and
140    # can span multiple lines.
141    def t_STRLIT(self, t):
142        r"(?m)'([^'])+'"
143        # strip off quotes
144        t.value = t.value[1:-1]
145        t.lexer.lineno += t.value.count('\n')
146        return t
147
148
149    # "Code literal"... like a string literal, but delimiters are
150    # '{{' and '}}' so they get formatted nicely under emacs c-mode
151    def t_CODELIT(self, t):
152        r"(?m)\{\{([^\}]|}(?!\}))+\}\}"
153        # strip off {{ & }}
154        t.value = t.value[2:-2]
155        t.lexer.lineno += t.value.count('\n')
156        return t
157
158    def t_CPPDIRECTIVE(self, t):
159        r'^\#[^\#].*\n'
160        t.lexer.lineno += t.value.count('\n')
161        return t
162
163    def t_NEWFILE(self, t):
164        r'^\#\#newfile\s+"[\w/.-]*"'
165        fileNameStack.push((t.value[11:-1], t.lexer.lineno))
166        t.lexer.lineno = 0
167
168    def t_ENDFILE(self, t):
169        r'^\#\#endfile'
170        (old_filename, t.lexer.lineno) = fileNameStack.pop()
171
172    #
173    # The functions t_NEWLINE, t_ignore, and t_error are
174    # special for the lex module.
175    #
176
177    # Newlines
178    def t_NEWLINE(self, t):
179        r'\n+'
180        t.lexer.lineno += t.value.count('\n')
181
182    # Comments
183    def t_comment(self, t):
184        r'//.*'
185
186    # Completely ignored characters
187    t_ignore = ' \t\x0c'
188
189    # Error handler
190    def t_error(self, t):
191        error(t.lexer.lineno, "illegal character '%s'" % t.value[0])
192        t.skip(1)
193
194    #####################################################################
195    #
196    #                                Parser
197    #
198    # Every function whose name starts with 'p_' defines a grammar
199    # rule.  The rule is encoded in the function's doc string, while
200    # the function body provides the action taken when the rule is
201    # matched.  The argument to each function is a list of the values
202    # of the rule's symbols: t[0] for the LHS, and t[1..n] for the
203    # symbols on the RHS.  For tokens, the value is copied from the
204    # t.value attribute provided by the lexer.  For non-terminals, the
205    # value is assigned by the producing rule; i.e., the job of the
206    # grammar rule function is to set the value for the non-terminal
207    # on the LHS (by assigning to t[0]).
208    #####################################################################
209
210    # The LHS of the first grammar rule is used as the start symbol
211    # (in this case, 'specification').  Note that this rule enforces
212    # that there will be exactly one namespace declaration, with 0 or
213    # more global defs/decls before and after it.  The defs & decls
214    # before the namespace decl will be outside the namespace; those
215    # after will be inside.  The decoder function is always inside the
216    # namespace.
217    def p_specification(self, t):
218        'specification : opt_defs_and_outputs name_decl opt_defs_and_outputs decode_block'
219        global_code = t[1]
220        isa_name = t[2]
221        namespace = isa_name + "Inst"
222        # wrap the decode block as a function definition
223        t[4].wrap_decode_block('''
224StaticInstPtr
225%(isa_name)s::decodeInst(%(isa_name)s::ExtMachInst machInst)
226{
227    using namespace %(namespace)s;
228''' % vars(), '}')
229        # both the latter output blocks and the decode block are in
230        # the namespace
231        namespace_code = t[3] + t[4]
232        # pass it all back to the caller of yacc.parse()
233        t[0] = (isa_name, namespace, global_code, namespace_code)
234
235    # ISA name declaration looks like "namespace <foo>;"
236    def p_name_decl(self, t):
237        'name_decl : NAMESPACE ID SEMI'
238        t[0] = t[2]
239
240    # 'opt_defs_and_outputs' is a possibly empty sequence of
241    # def and/or output statements.
242    def p_opt_defs_and_outputs_0(self, t):
243        'opt_defs_and_outputs : empty'
244        t[0] = GenCode()
245
246    def p_opt_defs_and_outputs_1(self, t):
247        'opt_defs_and_outputs : defs_and_outputs'
248        t[0] = t[1]
249
250    def p_defs_and_outputs_0(self, t):
251        'defs_and_outputs : def_or_output'
252        t[0] = t[1]
253
254    def p_defs_and_outputs_1(self, t):
255        'defs_and_outputs : defs_and_outputs def_or_output'
256        t[0] = t[1] + t[2]
257
258    # The list of possible definition/output statements.
259    def p_def_or_output(self, t):
260        '''def_or_output : def_format
261                         | def_bitfield
262                         | def_bitfield_struct
263                         | def_template
264                         | def_operand_types
265                         | def_operands
266                         | output_header
267                         | output_decoder
268                         | output_exec
269                         | global_let'''
270        t[0] = t[1]
271
272    # Output blocks 'output <foo> {{...}}' (C++ code blocks) are copied
273    # directly to the appropriate output section.
274
275    # Massage output block by substituting in template definitions and
276    # bit operators.  We handle '%'s embedded in the string that don't
277    # indicate template substitutions (or CPU-specific symbols, which
278    # get handled in GenCode) by doubling them first so that the
279    # format operation will reduce them back to single '%'s.
280    def process_output(self, s):
281        s = protect_non_subst_percents(s)
282        # protects cpu-specific symbols too
283        s = protect_cpu_symbols(s)
284        return substBitOps(s % self.templateMap)
285
286    def p_output_header(self, t):
287        'output_header : OUTPUT HEADER CODELIT SEMI'
288        t[0] = GenCode(header_output = self.process_output(t[3]))
289
290    def p_output_decoder(self, t):
291        'output_decoder : OUTPUT DECODER CODELIT SEMI'
292        t[0] = GenCode(decoder_output = self.process_output(t[3]))
293
294    def p_output_exec(self, t):
295        'output_exec : OUTPUT EXEC CODELIT SEMI'
296        t[0] = GenCode(exec_output = self.process_output(t[3]))
297
298    # global let blocks 'let {{...}}' (Python code blocks) are
299    # executed directly when seen.  Note that these execute in a
300    # special variable context 'exportContext' to prevent the code
301    # from polluting this script's namespace.
302    def p_global_let(self, t):
303        'global_let : LET CODELIT SEMI'
304        updateExportContext()
305        exportContext["header_output"] = ''
306        exportContext["decoder_output"] = ''
307        exportContext["exec_output"] = ''
308        exportContext["decode_block"] = ''
309        try:
310            exec fixPythonIndentation(t[2]) in exportContext
311        except Exception, exc:
312            error(t.lexer.lineno,
313                  'error: %s in global let block "%s".' % (exc, t[2]))
314        t[0] = GenCode(header_output = exportContext["header_output"],
315                       decoder_output = exportContext["decoder_output"],
316                       exec_output = exportContext["exec_output"],
317                       decode_block = exportContext["decode_block"])
318
319    # Define the mapping from operand type extensions to C++ types and
320    # bit widths (stored in operandTypeMap).
321    def p_def_operand_types(self, t):
322        'def_operand_types : DEF OPERAND_TYPES CODELIT SEMI'
323        try:
324            userDict = eval('{' + t[3] + '}')
325        except Exception, exc:
326            error(t.lexer.lineno,
327                  'error: %s in def operand_types block "%s".' % (exc, t[3]))
328        buildOperandTypeMap(userDict, t.lexer.lineno)
329        t[0] = GenCode() # contributes nothing to the output C++ file
330
331    # Define the mapping from operand names to operand classes and
332    # other traits.  Stored in operandNameMap.
333    def p_def_operands(self, t):
334        'def_operands : DEF OPERANDS CODELIT SEMI'
335        if not globals().has_key('operandTypeMap'):
336            error(t.lexer.lineno,
337                  'error: operand types must be defined before operands')
338        try:
339            userDict = eval('{' + t[3] + '}', exportContext)
340        except Exception, exc:
341            error(t.lexer.lineno,
342                  'error: %s in def operands block "%s".' % (exc, t[3]))
343        buildOperandNameMap(userDict, t.lexer.lineno)
344        t[0] = GenCode() # contributes nothing to the output C++ file
345
346    # A bitfield definition looks like:
347    # 'def [signed] bitfield <ID> [<first>:<last>]'
348    # This generates a preprocessor macro in the output file.
349    def p_def_bitfield_0(self, t):
350        'def_bitfield : DEF opt_signed BITFIELD ID LESS INTLIT COLON INTLIT GREATER SEMI'
351        expr = 'bits(machInst, %2d, %2d)' % (t[6], t[8])
352        if (t[2] == 'signed'):
353            expr = 'sext<%d>(%s)' % (t[6] - t[8] + 1, expr)
354        hash_define = '#undef %s\n#define %s\t%s\n' % (t[4], t[4], expr)
355        t[0] = GenCode(header_output = hash_define)
356
357    # alternate form for single bit: 'def [signed] bitfield <ID> [<bit>]'
358    def p_def_bitfield_1(self, t):
359        'def_bitfield : DEF opt_signed BITFIELD ID LESS INTLIT GREATER SEMI'
360        expr = 'bits(machInst, %2d, %2d)' % (t[6], t[6])
361        if (t[2] == 'signed'):
362            expr = 'sext<%d>(%s)' % (1, expr)
363        hash_define = '#undef %s\n#define %s\t%s\n' % (t[4], t[4], expr)
364        t[0] = GenCode(header_output = hash_define)
365
366    # alternate form for structure member: 'def bitfield <ID> <ID>'
367    def p_def_bitfield_struct(self, t):
368        'def_bitfield_struct : DEF opt_signed BITFIELD ID id_with_dot SEMI'
369        if (t[2] != ''):
370            error(t.lexer.lineno,
371                  'error: structure bitfields are always unsigned.')
372        expr = 'machInst.%s' % t[5]
373        hash_define = '#undef %s\n#define %s\t%s\n' % (t[4], t[4], expr)
374        t[0] = GenCode(header_output = hash_define)
375
376    def p_id_with_dot_0(self, t):
377        'id_with_dot : ID'
378        t[0] = t[1]
379
380    def p_id_with_dot_1(self, t):
381        'id_with_dot : ID DOT id_with_dot'
382        t[0] = t[1] + t[2] + t[3]
383
384    def p_opt_signed_0(self, t):
385        'opt_signed : SIGNED'
386        t[0] = t[1]
387
388    def p_opt_signed_1(self, t):
389        'opt_signed : empty'
390        t[0] = ''
391
392    def p_def_template(self, t):
393        'def_template : DEF TEMPLATE ID CODELIT SEMI'
394        self.templateMap[t[3]] = Template(t[4])
395        t[0] = GenCode()
396
397    # An instruction format definition looks like
398    # "def format <fmt>(<params>) {{...}};"
399    def p_def_format(self, t):
400        'def_format : DEF FORMAT ID LPAREN param_list RPAREN CODELIT SEMI'
401        (id, params, code) = (t[3], t[5], t[7])
402        defFormat(id, params, code, t.lexer.lineno)
403        t[0] = GenCode()
404
405    # The formal parameter list for an instruction format is a
406    # possibly empty list of comma-separated parameters.  Positional
407    # (standard, non-keyword) parameters must come first, followed by
408    # keyword parameters, followed by a '*foo' parameter that gets
409    # excess positional arguments (as in Python).  Each of these three
410    # parameter categories is optional.
411    #
412    # Note that we do not support the '**foo' parameter for collecting
413    # otherwise undefined keyword args.  Otherwise the parameter list
414    # is (I believe) identical to what is supported in Python.
415    #
416    # The param list generates a tuple, where the first element is a
417    # list of the positional params and the second element is a dict
418    # containing the keyword params.
419    def p_param_list_0(self, t):
420        'param_list : positional_param_list COMMA nonpositional_param_list'
421        t[0] = t[1] + t[3]
422
423    def p_param_list_1(self, t):
424        '''param_list : positional_param_list
425                      | nonpositional_param_list'''
426        t[0] = t[1]
427
428    def p_positional_param_list_0(self, t):
429        'positional_param_list : empty'
430        t[0] = []
431
432    def p_positional_param_list_1(self, t):
433        'positional_param_list : ID'
434        t[0] = [t[1]]
435
436    def p_positional_param_list_2(self, t):
437        'positional_param_list : positional_param_list COMMA ID'
438        t[0] = t[1] + [t[3]]
439
440    def p_nonpositional_param_list_0(self, t):
441        'nonpositional_param_list : keyword_param_list COMMA excess_args_param'
442        t[0] = t[1] + t[3]
443
444    def p_nonpositional_param_list_1(self, t):
445        '''nonpositional_param_list : keyword_param_list
446                                    | excess_args_param'''
447        t[0] = t[1]
448
449    def p_keyword_param_list_0(self, t):
450        'keyword_param_list : keyword_param'
451        t[0] = [t[1]]
452
453    def p_keyword_param_list_1(self, t):
454        'keyword_param_list : keyword_param_list COMMA keyword_param'
455        t[0] = t[1] + [t[3]]
456
457    def p_keyword_param(self, t):
458        'keyword_param : ID EQUALS expr'
459        t[0] = t[1] + ' = ' + t[3].__repr__()
460
461    def p_excess_args_param(self, t):
462        'excess_args_param : ASTERISK ID'
463        # Just concatenate them: '*ID'.  Wrap in list to be consistent
464        # with positional_param_list and keyword_param_list.
465        t[0] = [t[1] + t[2]]
466
467    # End of format definition-related rules.
468    ##############
469
470    #
471    # A decode block looks like:
472    #       decode <field1> [, <field2>]* [default <inst>] { ... }
473    #
474    def p_decode_block(self, t):
475        'decode_block : DECODE ID opt_default LBRACE decode_stmt_list RBRACE'
476        default_defaults = defaultStack.pop()
477        codeObj = t[5]
478        # use the "default defaults" only if there was no explicit
479        # default statement in decode_stmt_list
480        if not codeObj.has_decode_default:
481            codeObj += default_defaults
482        codeObj.wrap_decode_block('switch (%s) {\n' % t[2], '}\n')
483        t[0] = codeObj
484
485    # The opt_default statement serves only to push the "default
486    # defaults" onto defaultStack.  This value will be used by nested
487    # decode blocks, and used and popped off when the current
488    # decode_block is processed (in p_decode_block() above).
489    def p_opt_default_0(self, t):
490        'opt_default : empty'
491        # no default specified: reuse the one currently at the top of
492        # the stack
493        defaultStack.push(defaultStack.top())
494        # no meaningful value returned
495        t[0] = None
496
497    def p_opt_default_1(self, t):
498        'opt_default : DEFAULT inst'
499        # push the new default
500        codeObj = t[2]
501        codeObj.wrap_decode_block('\ndefault:\n', 'break;\n')
502        defaultStack.push(codeObj)
503        # no meaningful value returned
504        t[0] = None
505
506    def p_decode_stmt_list_0(self, t):
507        'decode_stmt_list : decode_stmt'
508        t[0] = t[1]
509
510    def p_decode_stmt_list_1(self, t):
511        'decode_stmt_list : decode_stmt decode_stmt_list'
512        if (t[1].has_decode_default and t[2].has_decode_default):
513            error(t.lexer.lineno, 'Two default cases in decode block')
514        t[0] = t[1] + t[2]
515
516    #
517    # Decode statement rules
518    #
519    # There are four types of statements allowed in a decode block:
520    # 1. Format blocks 'format <foo> { ... }'
521    # 2. Nested decode blocks
522    # 3. Instruction definitions.
523    # 4. C preprocessor directives.
524
525
526    # Preprocessor directives found in a decode statement list are
527    # passed through to the output, replicated to all of the output
528    # code streams.  This works well for ifdefs, so we can ifdef out
529    # both the declarations and the decode cases generated by an
530    # instruction definition.  Handling them as part of the grammar
531    # makes it easy to keep them in the right place with respect to
532    # the code generated by the other statements.
533    def p_decode_stmt_cpp(self, t):
534        'decode_stmt : CPPDIRECTIVE'
535        t[0] = GenCode(t[1], t[1], t[1], t[1])
536
537    # A format block 'format <foo> { ... }' sets the default
538    # instruction format used to handle instruction definitions inside
539    # the block.  This format can be overridden by using an explicit
540    # format on the instruction definition or with a nested format
541    # block.
542    def p_decode_stmt_format(self, t):
543        'decode_stmt : FORMAT push_format_id LBRACE decode_stmt_list RBRACE'
544        # The format will be pushed on the stack when 'push_format_id'
545        # is processed (see below).  Once the parser has recognized
546        # the full production (though the right brace), we're done
547        # with the format, so now we can pop it.
548        formatStack.pop()
549        t[0] = t[4]
550
551    # This rule exists so we can set the current format (& push the
552    # stack) when we recognize the format name part of the format
553    # block.
554    def p_push_format_id(self, t):
555        'push_format_id : ID'
556        try:
557            formatStack.push(formatMap[t[1]])
558            t[0] = ('', '// format %s' % t[1])
559        except KeyError:
560            error(t.lexer.lineno,
561                  'instruction format "%s" not defined.' % t[1])
562
563    # Nested decode block: if the value of the current field matches
564    # the specified constant, do a nested decode on some other field.
565    def p_decode_stmt_decode(self, t):
566        'decode_stmt : case_label COLON decode_block'
567        label = t[1]
568        codeObj = t[3]
569        # just wrap the decoding code from the block as a case in the
570        # outer switch statement.
571        codeObj.wrap_decode_block('\n%s:\n' % label)
572        codeObj.has_decode_default = (label == 'default')
573        t[0] = codeObj
574
575    # Instruction definition (finally!).
576    def p_decode_stmt_inst(self, t):
577        'decode_stmt : case_label COLON inst SEMI'
578        label = t[1]
579        codeObj = t[3]
580        codeObj.wrap_decode_block('\n%s:' % label, 'break;\n')
581        codeObj.has_decode_default = (label == 'default')
582        t[0] = codeObj
583
584    # The case label is either a list of one or more constants or
585    # 'default'
586    def p_case_label_0(self, t):
587        'case_label : intlit_list'
588        t[0] = ': '.join(map(lambda a: 'case %#x' % a, t[1]))
589
590    def p_case_label_1(self, t):
591        'case_label : DEFAULT'
592        t[0] = 'default'
593
594    #
595    # The constant list for a decode case label must be non-empty, but
596    # may have one or more comma-separated integer literals in it.
597    #
598    def p_intlit_list_0(self, t):
599        'intlit_list : INTLIT'
600        t[0] = [t[1]]
601
602    def p_intlit_list_1(self, t):
603        'intlit_list : intlit_list COMMA INTLIT'
604        t[0] = t[1]
605        t[0].append(t[3])
606
607    # Define an instruction using the current instruction format
608    # (specified by an enclosing format block).
609    # "<mnemonic>(<args>)"
610    def p_inst_0(self, t):
611        'inst : ID LPAREN arg_list RPAREN'
612        # Pass the ID and arg list to the current format class to deal with.
613        currentFormat = formatStack.top()
614        codeObj = currentFormat.defineInst(t[1], t[3], t.lexer.lineno)
615        args = ','.join(map(str, t[3]))
616        args = re.sub('(?m)^', '//', args)
617        args = re.sub('^//', '', args)
618        comment = '\n// %s::%s(%s)\n' % (currentFormat.id, t[1], args)
619        codeObj.prepend_all(comment)
620        t[0] = codeObj
621
622    # Define an instruction using an explicitly specified format:
623    # "<fmt>::<mnemonic>(<args>)"
624    def p_inst_1(self, t):
625        'inst : ID DBLCOLON ID LPAREN arg_list RPAREN'
626        try:
627            format = formatMap[t[1]]
628        except KeyError:
629            error(t.lexer.lineno,
630                  'instruction format "%s" not defined.' % t[1])
631        codeObj = format.defineInst(t[3], t[5], t.lexer.lineno)
632        comment = '\n// %s::%s(%s)\n' % (t[1], t[3], t[5])
633        codeObj.prepend_all(comment)
634        t[0] = codeObj
635
636    # The arg list generates a tuple, where the first element is a
637    # list of the positional args and the second element is a dict
638    # containing the keyword args.
639    def p_arg_list_0(self, t):
640        'arg_list : positional_arg_list COMMA keyword_arg_list'
641        t[0] = ( t[1], t[3] )
642
643    def p_arg_list_1(self, t):
644        'arg_list : positional_arg_list'
645        t[0] = ( t[1], {} )
646
647    def p_arg_list_2(self, t):
648        'arg_list : keyword_arg_list'
649        t[0] = ( [], t[1] )
650
651    def p_positional_arg_list_0(self, t):
652        'positional_arg_list : empty'
653        t[0] = []
654
655    def p_positional_arg_list_1(self, t):
656        'positional_arg_list : expr'
657        t[0] = [t[1]]
658
659    def p_positional_arg_list_2(self, t):
660        'positional_arg_list : positional_arg_list COMMA expr'
661        t[0] = t[1] + [t[3]]
662
663    def p_keyword_arg_list_0(self, t):
664        'keyword_arg_list : keyword_arg'
665        t[0] = t[1]
666
667    def p_keyword_arg_list_1(self, t):
668        'keyword_arg_list : keyword_arg_list COMMA keyword_arg'
669        t[0] = t[1]
670        t[0].update(t[3])
671
672    def p_keyword_arg(self, t):
673        'keyword_arg : ID EQUALS expr'
674        t[0] = { t[1] : t[3] }
675
676    #
677    # Basic expressions.  These constitute the argument values of
678    # "function calls" (i.e. instruction definitions in the decode
679    # block) and default values for formal parameters of format
680    # functions.
681    #
682    # Right now, these are either strings, integers, or (recursively)
683    # lists of exprs (using Python square-bracket list syntax).  Note
684    # that bare identifiers are trated as string constants here (since
685    # there isn't really a variable namespace to refer to).
686    #
687    def p_expr_0(self, t):
688        '''expr : ID
689                | INTLIT
690                | STRLIT
691                | CODELIT'''
692        t[0] = t[1]
693
694    def p_expr_1(self, t):
695        '''expr : LBRACKET list_expr RBRACKET'''
696        t[0] = t[2]
697
698    def p_list_expr_0(self, t):
699        'list_expr : expr'
700        t[0] = [t[1]]
701
702    def p_list_expr_1(self, t):
703        'list_expr : list_expr COMMA expr'
704        t[0] = t[1] + [t[3]]
705
706    def p_list_expr_2(self, t):
707        'list_expr : empty'
708        t[0] = []
709
710    #
711    # Empty production... use in other rules for readability.
712    #
713    def p_empty(self, t):
714        'empty :'
715        pass
716
717    # Parse error handler.  Note that the argument here is the
718    # offending *token*, not a grammar symbol (hence the need to use
719    # t.value)
720    def p_error(self, t):
721        if t:
722            error(t.lexer.lineno, "syntax error at '%s'" % t.value)
723        else:
724            error(0, "unknown syntax error", True)
725
726    # END OF GRAMMAR RULES
727
728# Now build the parser.
729parser = ISAParser()
730
731#####################################################################
732#
733#                           Support Classes
734#
735#####################################################################
736
737# Expand template with CPU-specific references into a dictionary with
738# an entry for each CPU model name.  The entry key is the model name
739# and the corresponding value is the template with the CPU-specific
740# refs substituted for that model.
741def expand_cpu_symbols_to_dict(template):
742    # Protect '%'s that don't go with CPU-specific terms
743    t = re.sub(r'%(?!\(CPU_)', '%%', template)
744    result = {}
745    for cpu in cpu_models:
746        result[cpu.name] = t % cpu.strings
747    return result
748
749# *If* the template has CPU-specific references, return a single
750# string containing a copy of the template for each CPU model with the
751# corresponding values substituted in.  If the template has no
752# CPU-specific references, it is returned unmodified.
753def expand_cpu_symbols_to_string(template):
754    if template.find('%(CPU_') != -1:
755        return reduce(lambda x,y: x+y,
756                      expand_cpu_symbols_to_dict(template).values())
757    else:
758        return template
759
760# Protect CPU-specific references by doubling the corresponding '%'s
761# (in preparation for substituting a different set of references into
762# the template).
763def protect_cpu_symbols(template):
764    return re.sub(r'%(?=\(CPU_)', '%%', template)
765
766# Protect any non-dict-substitution '%'s in a format string
767# (i.e. those not followed by '(')
768def protect_non_subst_percents(s):
769    return re.sub(r'%(?!\()', '%%', s)
770
771###############
772# GenCode class
773#
774# The GenCode class encapsulates generated code destined for various
775# output files.  The header_output and decoder_output attributes are
776# strings containing code destined for decoder.hh and decoder.cc
777# respectively.  The decode_block attribute contains code to be
778# incorporated in the decode function itself (that will also end up in
779# decoder.cc).  The exec_output attribute is a dictionary with a key
780# for each CPU model name; the value associated with a particular key
781# is the string of code for that CPU model's exec.cc file.  The
782# has_decode_default attribute is used in the decode block to allow
783# explicit default clauses to override default default clauses.
784
785class GenCode:
786    # Constructor.  At this point we substitute out all CPU-specific
787    # symbols.  For the exec output, these go into the per-model
788    # dictionary.  For all other output types they get collapsed into
789    # a single string.
790    def __init__(self,
791                 header_output = '', decoder_output = '', exec_output = '',
792                 decode_block = '', has_decode_default = False):
793        self.header_output = expand_cpu_symbols_to_string(header_output)
794        self.decoder_output = expand_cpu_symbols_to_string(decoder_output)
795        if isinstance(exec_output, dict):
796            self.exec_output = exec_output
797        elif isinstance(exec_output, str):
798            # If the exec_output arg is a single string, we replicate
799            # it for each of the CPU models, substituting and
800            # %(CPU_foo)s params appropriately.
801            self.exec_output = expand_cpu_symbols_to_dict(exec_output)
802        self.decode_block = expand_cpu_symbols_to_string(decode_block)
803        self.has_decode_default = has_decode_default
804
805    # Override '+' operator: generate a new GenCode object that
806    # concatenates all the individual strings in the operands.
807    def __add__(self, other):
808        exec_output = {}
809        for cpu in cpu_models:
810            n = cpu.name
811            exec_output[n] = self.exec_output[n] + other.exec_output[n]
812        return GenCode(self.header_output + other.header_output,
813                       self.decoder_output + other.decoder_output,
814                       exec_output,
815                       self.decode_block + other.decode_block,
816                       self.has_decode_default or other.has_decode_default)
817
818    # Prepend a string (typically a comment) to all the strings.
819    def prepend_all(self, pre):
820        self.header_output = pre + self.header_output
821        self.decoder_output  = pre + self.decoder_output
822        self.decode_block = pre + self.decode_block
823        for cpu in cpu_models:
824            self.exec_output[cpu.name] = pre + self.exec_output[cpu.name]
825
826    # Wrap the decode block in a pair of strings (e.g., 'case foo:'
827    # and 'break;').  Used to build the big nested switch statement.
828    def wrap_decode_block(self, pre, post = ''):
829        self.decode_block = pre + indent(self.decode_block) + post
830
831################
832# Format object.
833#
834# A format object encapsulates an instruction format.  It must provide
835# a defineInst() method that generates the code for an instruction
836# definition.
837
838exportContextSymbols = ('InstObjParams', 'makeList', 're', 'string')
839
840exportContext = {}
841
842def updateExportContext():
843    exportContext.update(exportDict(*exportContextSymbols))
844    exportContext.update(parser.templateMap)
845
846def exportDict(*symNames):
847    return dict([(s, eval(s)) for s in symNames])
848
849
850class Format:
851    def __init__(self, id, params, code):
852        # constructor: just save away arguments
853        self.id = id
854        self.params = params
855        label = 'def format ' + id
856        self.user_code = compile(fixPythonIndentation(code), label, 'exec')
857        param_list = string.join(params, ", ")
858        f = '''def defInst(_code, _context, %s):
859                my_locals = vars().copy()
860                exec _code in _context, my_locals
861                return my_locals\n''' % param_list
862        c = compile(f, label + ' wrapper', 'exec')
863        exec c
864        self.func = defInst
865
866    def defineInst(self, name, args, lineno):
867        context = {}
868        updateExportContext()
869        context.update(exportContext)
870        if len(name):
871            Name = name[0].upper()
872            if len(name) > 1:
873                Name += name[1:]
874        context.update({ 'name': name, 'Name': Name })
875        try:
876            vars = self.func(self.user_code, context, *args[0], **args[1])
877        except Exception, exc:
878            error(lineno, 'error defining "%s": %s.' % (name, exc))
879        for k in vars.keys():
880            if k not in ('header_output', 'decoder_output',
881                         'exec_output', 'decode_block'):
882                del vars[k]
883        return GenCode(**vars)
884
885# Special null format to catch an implicit-format instruction
886# definition outside of any format block.
887class NoFormat:
888    def __init__(self):
889        self.defaultInst = ''
890
891    def defineInst(self, name, args, lineno):
892        error(lineno,
893              'instruction definition "%s" with no active format!' % name)
894
895# This dictionary maps format name strings to Format objects.
896formatMap = {}
897
898# Define a new format
899def defFormat(id, params, code, lineno):
900    # make sure we haven't already defined this one
901    if formatMap.get(id, None) != None:
902        error(lineno, 'format %s redefined.' % id)
903    # create new object and store in global map
904    formatMap[id] = Format(id, params, code)
905
906
907##############
908# Stack: a simple stack object.  Used for both formats (formatStack)
909# and default cases (defaultStack).  Simply wraps a list to give more
910# stack-like syntax and enable initialization with an argument list
911# (as opposed to an argument that's a list).
912
913class Stack(list):
914    def __init__(self, *items):
915        list.__init__(self, items)
916
917    def push(self, item):
918        self.append(item);
919
920    def top(self):
921        return self[-1]
922
923# The global format stack.
924formatStack = Stack(NoFormat())
925
926# The global default case stack.
927defaultStack = Stack( None )
928
929# Global stack that tracks current file and line number.
930# Each element is a tuple (filename, lineno) that records the
931# *current* filename and the line number in the *previous* file where
932# it was included.
933fileNameStack = Stack()
934
935###################
936# Utility functions
937
938#
939# Indent every line in string 's' by two spaces
940# (except preprocessor directives).
941# Used to make nested code blocks look pretty.
942#
943def indent(s):
944    return re.sub(r'(?m)^(?!#)', '  ', s)
945
946#
947# Munge a somewhat arbitrarily formatted piece of Python code
948# (e.g. from a format 'let' block) into something whose indentation
949# will get by the Python parser.
950#
951# The two keys here are that Python will give a syntax error if
952# there's any whitespace at the beginning of the first line, and that
953# all lines at the same lexical nesting level must have identical
954# indentation.  Unfortunately the way code literals work, an entire
955# let block tends to have some initial indentation.  Rather than
956# trying to figure out what that is and strip it off, we prepend 'if
957# 1:' to make the let code the nested block inside the if (and have
958# the parser automatically deal with the indentation for us).
959#
960# We don't want to do this if (1) the code block is empty or (2) the
961# first line of the block doesn't have any whitespace at the front.
962
963def fixPythonIndentation(s):
964    # get rid of blank lines first
965    s = re.sub(r'(?m)^\s*\n', '', s);
966    if (s != '' and re.match(r'[ \t]', s[0])):
967        s = 'if 1:\n' + s
968    return s
969
970# Error handler.  Just call exit.  Output formatted to work under
971# Emacs compile-mode.  Optional 'print_traceback' arg, if set to True,
972# prints a Python stack backtrace too (can be handy when trying to
973# debug the parser itself).
974def error(lineno, string, print_traceback = False):
975    spaces = ""
976    for (filename, line) in fileNameStack[0:-1]:
977        print spaces + "In file included from " + filename + ":"
978        spaces += "  "
979    # Print a Python stack backtrace if requested.
980    if (print_traceback):
981        traceback.print_exc()
982    if lineno != 0:
983        line_str = "%d:" % lineno
984    else:
985        line_str = ""
986    sys.exit(spaces + "%s:%s %s" % (fileNameStack[-1][0], line_str, string))
987
988
989#####################################################################
990#
991#                      Bitfield Operator Support
992#
993#####################################################################
994
995bitOp1ArgRE = re.compile(r'<\s*(\w+)\s*:\s*>')
996
997bitOpWordRE = re.compile(r'(?<![\w\.])([\w\.]+)<\s*(\w+)\s*:\s*(\w+)\s*>')
998bitOpExprRE = re.compile(r'\)<\s*(\w+)\s*:\s*(\w+)\s*>')
999
1000def substBitOps(code):
1001    # first convert single-bit selectors to two-index form
1002    # i.e., <n> --> <n:n>
1003    code = bitOp1ArgRE.sub(r'<\1:\1>', code)
1004    # simple case: selector applied to ID (name)
1005    # i.e., foo<a:b> --> bits(foo, a, b)
1006    code = bitOpWordRE.sub(r'bits(\1, \2, \3)', code)
1007    # if selector is applied to expression (ending in ')'),
1008    # we need to search backward for matching '('
1009    match = bitOpExprRE.search(code)
1010    while match:
1011        exprEnd = match.start()
1012        here = exprEnd - 1
1013        nestLevel = 1
1014        while nestLevel > 0:
1015            if code[here] == '(':
1016                nestLevel -= 1
1017            elif code[here] == ')':
1018                nestLevel += 1
1019            here -= 1
1020            if here < 0:
1021                sys.exit("Didn't find '('!")
1022        exprStart = here+1
1023        newExpr = r'bits(%s, %s, %s)' % (code[exprStart:exprEnd+1],
1024                                         match.group(1), match.group(2))
1025        code = code[:exprStart] + newExpr + code[match.end():]
1026        match = bitOpExprRE.search(code)
1027    return code
1028
1029
1030####################
1031# Template objects.
1032#
1033# Template objects are format strings that allow substitution from
1034# the attribute spaces of other objects (e.g. InstObjParams instances).
1035
1036labelRE = re.compile(r'(?<!%)%\(([^\)]+)\)[sd]')
1037
1038class Template:
1039    def __init__(self, t):
1040        self.template = t
1041
1042    def subst(self, d):
1043        myDict = None
1044
1045        # Protect non-Python-dict substitutions (e.g. if there's a printf
1046        # in the templated C++ code)
1047        template = protect_non_subst_percents(self.template)
1048        # CPU-model-specific substitutions are handled later (in GenCode).
1049        template = protect_cpu_symbols(template)
1050
1051        # Build a dict ('myDict') to use for the template substitution.
1052        # Start with the template namespace.  Make a copy since we're
1053        # going to modify it.
1054        myDict = parser.templateMap.copy()
1055
1056        if isinstance(d, InstObjParams):
1057            # If we're dealing with an InstObjParams object, we need
1058            # to be a little more sophisticated.  The instruction-wide
1059            # parameters are already formed, but the parameters which
1060            # are only function wide still need to be generated.
1061            compositeCode = ''
1062
1063            myDict.update(d.__dict__)
1064            # The "operands" and "snippets" attributes of the InstObjParams
1065            # objects are for internal use and not substitution.
1066            del myDict['operands']
1067            del myDict['snippets']
1068
1069            snippetLabels = [l for l in labelRE.findall(template)
1070                             if d.snippets.has_key(l)]
1071
1072            snippets = dict([(s, mungeSnippet(d.snippets[s]))
1073                             for s in snippetLabels])
1074
1075            myDict.update(snippets)
1076
1077            compositeCode = ' '.join(map(str, snippets.values()))
1078
1079            # Add in template itself in case it references any
1080            # operands explicitly (like Mem)
1081            compositeCode += ' ' + template
1082
1083            operands = SubOperandList(compositeCode, d.operands)
1084
1085            myDict['op_decl'] = operands.concatAttrStrings('op_decl')
1086
1087            is_src = lambda op: op.is_src
1088            is_dest = lambda op: op.is_dest
1089
1090            myDict['op_src_decl'] = \
1091                      operands.concatSomeAttrStrings(is_src, 'op_src_decl')
1092            myDict['op_dest_decl'] = \
1093                      operands.concatSomeAttrStrings(is_dest, 'op_dest_decl')
1094
1095            myDict['op_rd'] = operands.concatAttrStrings('op_rd')
1096            myDict['op_wb'] = operands.concatAttrStrings('op_wb')
1097
1098            if d.operands.memOperand:
1099                myDict['mem_acc_size'] = d.operands.memOperand.mem_acc_size
1100                myDict['mem_acc_type'] = d.operands.memOperand.mem_acc_type
1101
1102        elif isinstance(d, dict):
1103            # if the argument is a dictionary, we just use it.
1104            myDict.update(d)
1105        elif hasattr(d, '__dict__'):
1106            # if the argument is an object, we use its attribute map.
1107            myDict.update(d.__dict__)
1108        else:
1109            raise TypeError, "Template.subst() arg must be or have dictionary"
1110        return template % myDict
1111
1112    # Convert to string.  This handles the case when a template with a
1113    # CPU-specific term gets interpolated into another template or into
1114    # an output block.
1115    def __str__(self):
1116        return expand_cpu_symbols_to_string(self.template)
1117
1118#####################################################################
1119#
1120#                             Code Parser
1121#
1122# The remaining code is the support for automatically extracting
1123# instruction characteristics from pseudocode.
1124#
1125#####################################################################
1126
1127# Force the argument to be a list.  Useful for flags, where a caller
1128# can specify a singleton flag or a list of flags.  Also usful for
1129# converting tuples to lists so they can be modified.
1130def makeList(arg):
1131    if isinstance(arg, list):
1132        return arg
1133    elif isinstance(arg, tuple):
1134        return list(arg)
1135    elif not arg:
1136        return []
1137    else:
1138        return [ arg ]
1139
1140# Generate operandTypeMap from the user's 'def operand_types'
1141# statement.
1142def buildOperandTypeMap(userDict, lineno):
1143    global operandTypeMap
1144    operandTypeMap = {}
1145    for (ext, (desc, size)) in userDict.iteritems():
1146        if desc == 'signed int':
1147            ctype = 'int%d_t' % size
1148            is_signed = 1
1149        elif desc == 'unsigned int':
1150            ctype = 'uint%d_t' % size
1151            is_signed = 0
1152        elif desc == 'float':
1153            is_signed = 1       # shouldn't really matter
1154            if size == 32:
1155                ctype = 'float'
1156            elif size == 64:
1157                ctype = 'double'
1158        elif desc == 'twin64 int':
1159            is_signed = 0
1160            ctype = 'Twin64_t'
1161        elif desc == 'twin32 int':
1162            is_signed = 0
1163            ctype = 'Twin32_t'
1164        if ctype == '':
1165            error(lineno, 'Unrecognized type description "%s" in userDict')
1166        operandTypeMap[ext] = (size, ctype, is_signed)
1167
1168#
1169#
1170#
1171# Base class for operand descriptors.  An instance of this class (or
1172# actually a class derived from this one) represents a specific
1173# operand for a code block (e.g, "Rc.sq" as a dest). Intermediate
1174# derived classes encapsulates the traits of a particular operand type
1175# (e.g., "32-bit integer register").
1176#
1177class Operand(object):
1178    def buildReadCode(self, func = None):
1179        code = self.read_code % {"name": self.base_name,
1180                                 "func": func,
1181                                 "op_idx": self.src_reg_idx,
1182                                 "reg_idx": self.reg_spec,
1183                                 "size": self.size,
1184                                 "ctype": self.ctype}
1185        if self.size != self.dflt_size:
1186            return '%s = bits(%s, %d, 0);\n' % \
1187                   (self.base_name, code, self.size-1)
1188        else:
1189            return '%s = %s;\n' % \
1190                   (self.base_name, code)
1191
1192    def buildWriteCode(self, func = None):
1193        if (self.size != self.dflt_size and self.is_signed):
1194            final_val = 'sext<%d>(%s)' % (self.size, self.base_name)
1195        else:
1196            final_val = self.base_name
1197        code = self.write_code % {"name": self.base_name,
1198                                  "func": func,
1199                                  "op_idx": self.dest_reg_idx,
1200                                  "reg_idx": self.reg_spec,
1201                                  "size": self.size,
1202                                  "ctype": self.ctype,
1203                                  "final_val": final_val}
1204        return '''
1205        {
1206            %s final_val = %s;
1207            %s;
1208            if (traceData) { traceData->setData(final_val); }
1209        }''' % (self.dflt_ctype, final_val, code)
1210
1211    def __init__(self, full_name, ext, is_src, is_dest):
1212        self.full_name = full_name
1213        self.ext = ext
1214        self.is_src = is_src
1215        self.is_dest = is_dest
1216        # The 'effective extension' (eff_ext) is either the actual
1217        # extension, if one was explicitly provided, or the default.
1218        if ext:
1219            self.eff_ext = ext
1220        else:
1221            self.eff_ext = self.dflt_ext
1222
1223        (self.size, self.ctype, self.is_signed) = operandTypeMap[self.eff_ext]
1224
1225        # note that mem_acc_size is undefined for non-mem operands...
1226        # template must be careful not to use it if it doesn't apply.
1227        if self.isMem():
1228            self.mem_acc_size = self.makeAccSize()
1229            if self.ctype in ['Twin32_t', 'Twin64_t']:
1230                self.mem_acc_type = 'Twin'
1231            else:
1232                self.mem_acc_type = 'uint'
1233
1234    # Finalize additional fields (primarily code fields).  This step
1235    # is done separately since some of these fields may depend on the
1236    # register index enumeration that hasn't been performed yet at the
1237    # time of __init__().
1238    def finalize(self):
1239        self.flags = self.getFlags()
1240        self.constructor = self.makeConstructor()
1241        self.op_decl = self.makeDecl()
1242
1243        if self.is_src:
1244            self.op_rd = self.makeRead()
1245            self.op_src_decl = self.makeDecl()
1246        else:
1247            self.op_rd = ''
1248            self.op_src_decl = ''
1249
1250        if self.is_dest:
1251            self.op_wb = self.makeWrite()
1252            self.op_dest_decl = self.makeDecl()
1253        else:
1254            self.op_wb = ''
1255            self.op_dest_decl = ''
1256
1257    def isMem(self):
1258        return 0
1259
1260    def isReg(self):
1261        return 0
1262
1263    def isFloatReg(self):
1264        return 0
1265
1266    def isIntReg(self):
1267        return 0
1268
1269    def isControlReg(self):
1270        return 0
1271
1272    def getFlags(self):
1273        # note the empty slice '[:]' gives us a copy of self.flags[0]
1274        # instead of a reference to it
1275        my_flags = self.flags[0][:]
1276        if self.is_src:
1277            my_flags += self.flags[1]
1278        if self.is_dest:
1279            my_flags += self.flags[2]
1280        return my_flags
1281
1282    def makeDecl(self):
1283        # Note that initializations in the declarations are solely
1284        # to avoid 'uninitialized variable' errors from the compiler.
1285        return self.ctype + ' ' + self.base_name + ' = 0;\n';
1286
1287class IntRegOperand(Operand):
1288    def isReg(self):
1289        return 1
1290
1291    def isIntReg(self):
1292        return 1
1293
1294    def makeConstructor(self):
1295        c = ''
1296        if self.is_src:
1297            c += '\n\t_srcRegIdx[%d] = %s;' % \
1298                 (self.src_reg_idx, self.reg_spec)
1299        if self.is_dest:
1300            c += '\n\t_destRegIdx[%d] = %s;' % \
1301                 (self.dest_reg_idx, self.reg_spec)
1302        return c
1303
1304    def makeRead(self):
1305        if (self.ctype == 'float' or self.ctype == 'double'):
1306            error(0, 'Attempt to read integer register as FP')
1307        if self.read_code != None:
1308            return self.buildReadCode('readIntRegOperand')
1309        if (self.size == self.dflt_size):
1310            return '%s = xc->readIntRegOperand(this, %d);\n' % \
1311                   (self.base_name, self.src_reg_idx)
1312        elif (self.size > self.dflt_size):
1313            int_reg_val = 'xc->readIntRegOperand(this, %d)' % \
1314                          (self.src_reg_idx)
1315            if (self.is_signed):
1316                int_reg_val = 'sext<%d>(%s)' % (self.dflt_size, int_reg_val)
1317            return '%s = %s;\n' % (self.base_name, int_reg_val)
1318        else:
1319            return '%s = bits(xc->readIntRegOperand(this, %d), %d, 0);\n' % \
1320                   (self.base_name, self.src_reg_idx, self.size-1)
1321
1322    def makeWrite(self):
1323        if (self.ctype == 'float' or self.ctype == 'double'):
1324            error(0, 'Attempt to write integer register as FP')
1325        if self.write_code != None:
1326            return self.buildWriteCode('setIntRegOperand')
1327        if (self.size != self.dflt_size and self.is_signed):
1328            final_val = 'sext<%d>(%s)' % (self.size, self.base_name)
1329        else:
1330            final_val = self.base_name
1331        wb = '''
1332        {
1333            %s final_val = %s;
1334            xc->setIntRegOperand(this, %d, final_val);\n
1335            if (traceData) { traceData->setData(final_val); }
1336        }''' % (self.dflt_ctype, final_val, self.dest_reg_idx)
1337        return wb
1338
1339class FloatRegOperand(Operand):
1340    def isReg(self):
1341        return 1
1342
1343    def isFloatReg(self):
1344        return 1
1345
1346    def makeConstructor(self):
1347        c = ''
1348        if self.is_src:
1349            c += '\n\t_srcRegIdx[%d] = %s + FP_Base_DepTag;' % \
1350                 (self.src_reg_idx, self.reg_spec)
1351        if self.is_dest:
1352            c += '\n\t_destRegIdx[%d] = %s + FP_Base_DepTag;' % \
1353                 (self.dest_reg_idx, self.reg_spec)
1354        return c
1355
1356    def makeRead(self):
1357        bit_select = 0
1358        if (self.ctype == 'float' or self.ctype == 'double'):
1359            func = 'readFloatRegOperand'
1360        else:
1361            func = 'readFloatRegOperandBits'
1362            if (self.size != self.dflt_size):
1363                bit_select = 1
1364        base = 'xc->%s(this, %d)' % (func, self.src_reg_idx)
1365        if self.read_code != None:
1366            return self.buildReadCode(func)
1367        if bit_select:
1368            return '%s = bits(%s, %d, 0);\n' % \
1369                   (self.base_name, base, self.size-1)
1370        else:
1371            return '%s = %s;\n' % (self.base_name, base)
1372
1373    def makeWrite(self):
1374        final_val = self.base_name
1375        final_ctype = self.ctype
1376        if (self.ctype == 'float' or self.ctype == 'double'):
1377            func = 'setFloatRegOperand'
1378        elif (self.ctype == 'uint32_t' or self.ctype == 'uint64_t'):
1379            func = 'setFloatRegOperandBits'
1380        else:
1381            func = 'setFloatRegOperandBits'
1382            final_ctype = 'uint%d_t' % self.dflt_size
1383            if (self.size != self.dflt_size and self.is_signed):
1384                final_val = 'sext<%d>(%s)' % (self.size, self.base_name)
1385        if self.write_code != None:
1386            return self.buildWriteCode(func)
1387        wb = '''
1388        {
1389            %s final_val = %s;
1390            xc->%s(this, %d, final_val);\n
1391            if (traceData) { traceData->setData(final_val); }
1392        }''' % (final_ctype, final_val, func, self.dest_reg_idx)
1393        return wb
1394
1395class ControlRegOperand(Operand):
1396    def isReg(self):
1397        return 1
1398
1399    def isControlReg(self):
1400        return 1
1401
1402    def makeConstructor(self):
1403        c = ''
1404        if self.is_src:
1405            c += '\n\t_srcRegIdx[%d] = %s + Ctrl_Base_DepTag;' % \
1406                 (self.src_reg_idx, self.reg_spec)
1407        if self.is_dest:
1408            c += '\n\t_destRegIdx[%d] = %s + Ctrl_Base_DepTag;' % \
1409                 (self.dest_reg_idx, self.reg_spec)
1410        return c
1411
1412    def makeRead(self):
1413        bit_select = 0
1414        if (self.ctype == 'float' or self.ctype == 'double'):
1415            error(0, 'Attempt to read control register as FP')
1416        if self.read_code != None:
1417            return self.buildReadCode('readMiscRegOperand')
1418        base = 'xc->readMiscRegOperand(this, %s)' % self.src_reg_idx
1419        if self.size == self.dflt_size:
1420            return '%s = %s;\n' % (self.base_name, base)
1421        else:
1422            return '%s = bits(%s, %d, 0);\n' % \
1423                   (self.base_name, base, self.size-1)
1424
1425    def makeWrite(self):
1426        if (self.ctype == 'float' or self.ctype == 'double'):
1427            error(0, 'Attempt to write control register as FP')
1428        if self.write_code != None:
1429            return self.buildWriteCode('setMiscRegOperand')
1430        wb = 'xc->setMiscRegOperand(this, %s, %s);\n' % \
1431             (self.dest_reg_idx, self.base_name)
1432        wb += 'if (traceData) { traceData->setData(%s); }' % \
1433              self.base_name
1434        return wb
1435
1436class MemOperand(Operand):
1437    def isMem(self):
1438        return 1
1439
1440    def makeConstructor(self):
1441        return ''
1442
1443    def makeDecl(self):
1444        # Note that initializations in the declarations are solely
1445        # to avoid 'uninitialized variable' errors from the compiler.
1446        # Declare memory data variable.
1447        if self.ctype in ['Twin32_t','Twin64_t']:
1448            return "%s %s; %s.a = 0; %s.b = 0;\n" % (self.ctype, self.base_name,
1449                    self.base_name, self.base_name)
1450        c = '%s %s = 0;\n' % (self.ctype, self.base_name)
1451        return c
1452
1453    def makeRead(self):
1454        if self.read_code != None:
1455            return self.buildReadCode()
1456        return ''
1457
1458    def makeWrite(self):
1459        if self.write_code != None:
1460            return self.buildWriteCode()
1461        return ''
1462
1463    # Return the memory access size *in bits*, suitable for
1464    # forming a type via "uint%d_t".  Divide by 8 if you want bytes.
1465    def makeAccSize(self):
1466        return self.size
1467
1468class PCOperand(Operand):
1469    def makeConstructor(self):
1470        return ''
1471
1472    def makeRead(self):
1473        return '%s = xc->readPC();\n' % self.base_name
1474
1475    def makeWrite(self):
1476        return 'xc->setPC(%s);\n' % self.base_name
1477
1478class UPCOperand(Operand):
1479    def makeConstructor(self):
1480        return ''
1481
1482    def makeRead(self):
1483        if self.read_code != None:
1484            return self.buildReadCode('readMicroPC')
1485        return '%s = xc->readMicroPC();\n' % self.base_name
1486
1487    def makeWrite(self):
1488        if self.write_code != None:
1489            return self.buildWriteCode('setMicroPC')
1490        return 'xc->setMicroPC(%s);\n' % self.base_name
1491
1492class NUPCOperand(Operand):
1493    def makeConstructor(self):
1494        return ''
1495
1496    def makeRead(self):
1497        if self.read_code != None:
1498            return self.buildReadCode('readNextMicroPC')
1499        return '%s = xc->readNextMicroPC();\n' % self.base_name
1500
1501    def makeWrite(self):
1502        if self.write_code != None:
1503            return self.buildWriteCode('setNextMicroPC')
1504        return 'xc->setNextMicroPC(%s);\n' % self.base_name
1505
1506class NPCOperand(Operand):
1507    def makeConstructor(self):
1508        return ''
1509
1510    def makeRead(self):
1511        if self.read_code != None:
1512            return self.buildReadCode('readNextPC')
1513        return '%s = xc->readNextPC();\n' % self.base_name
1514
1515    def makeWrite(self):
1516        if self.write_code != None:
1517            return self.buildWriteCode('setNextPC')
1518        return 'xc->setNextPC(%s);\n' % self.base_name
1519
1520class NNPCOperand(Operand):
1521    def makeConstructor(self):
1522        return ''
1523
1524    def makeRead(self):
1525        if self.read_code != None:
1526            return self.buildReadCode('readNextNPC')
1527        return '%s = xc->readNextNPC();\n' % self.base_name
1528
1529    def makeWrite(self):
1530        if self.write_code != None:
1531            return self.buildWriteCode('setNextNPC')
1532        return 'xc->setNextNPC(%s);\n' % self.base_name
1533
1534def buildOperandNameMap(userDict, lineno):
1535    global operandNameMap
1536    operandNameMap = {}
1537    for (op_name, val) in userDict.iteritems():
1538        (base_cls_name, dflt_ext, reg_spec, flags, sort_pri) = val[:5]
1539        if len(val) > 5:
1540            read_code = val[5]
1541        else:
1542            read_code = None
1543        if len(val) > 6:
1544            write_code = val[6]
1545        else:
1546            write_code = None
1547        if len(val) > 7:
1548            error(lineno,
1549                  'error: too many attributes for operand "%s"' %
1550                  base_cls_name)
1551
1552        (dflt_size, dflt_ctype, dflt_is_signed) = operandTypeMap[dflt_ext]
1553        # Canonical flag structure is a triple of lists, where each list
1554        # indicates the set of flags implied by this operand always, when
1555        # used as a source, and when used as a dest, respectively.
1556        # For simplicity this can be initialized using a variety of fairly
1557        # obvious shortcuts; we convert these to canonical form here.
1558        if not flags:
1559            # no flags specified (e.g., 'None')
1560            flags = ( [], [], [] )
1561        elif isinstance(flags, str):
1562            # a single flag: assumed to be unconditional
1563            flags = ( [ flags ], [], [] )
1564        elif isinstance(flags, list):
1565            # a list of flags: also assumed to be unconditional
1566            flags = ( flags, [], [] )
1567        elif isinstance(flags, tuple):
1568            # it's a tuple: it should be a triple,
1569            # but each item could be a single string or a list
1570            (uncond_flags, src_flags, dest_flags) = flags
1571            flags = (makeList(uncond_flags),
1572                     makeList(src_flags), makeList(dest_flags))
1573        # Accumulate attributes of new operand class in tmp_dict
1574        tmp_dict = {}
1575        for attr in ('dflt_ext', 'reg_spec', 'flags', 'sort_pri',
1576                     'dflt_size', 'dflt_ctype', 'dflt_is_signed',
1577                     'read_code', 'write_code'):
1578            tmp_dict[attr] = eval(attr)
1579        tmp_dict['base_name'] = op_name
1580        # New class name will be e.g. "IntReg_Ra"
1581        cls_name = base_cls_name + '_' + op_name
1582        # Evaluate string arg to get class object.  Note that the
1583        # actual base class for "IntReg" is "IntRegOperand", i.e. we
1584        # have to append "Operand".
1585        try:
1586            base_cls = eval(base_cls_name + 'Operand')
1587        except NameError:
1588            error(lineno,
1589                  'error: unknown operand base class "%s"' % base_cls_name)
1590        # The following statement creates a new class called
1591        # <cls_name> as a subclass of <base_cls> with the attributes
1592        # in tmp_dict, just as if we evaluated a class declaration.
1593        operandNameMap[op_name] = type(cls_name, (base_cls,), tmp_dict)
1594
1595    # Define operand variables.
1596    operands = userDict.keys()
1597
1598    operandsREString = (r'''
1599    (?<![\w\.])      # neg. lookbehind assertion: prevent partial matches
1600    ((%s)(?:\.(\w+))?)   # match: operand with optional '.' then suffix
1601    (?![\w\.])       # neg. lookahead assertion: prevent partial matches
1602    '''
1603                        % string.join(operands, '|'))
1604
1605    global operandsRE
1606    operandsRE = re.compile(operandsREString, re.MULTILINE|re.VERBOSE)
1607
1608    # Same as operandsREString, but extension is mandatory, and only two
1609    # groups are returned (base and ext, not full name as above).
1610    # Used for subtituting '_' for '.' to make C++ identifiers.
1611    operandsWithExtREString = (r'(?<![\w\.])(%s)\.(\w+)(?![\w\.])'
1612                               % string.join(operands, '|'))
1613
1614    global operandsWithExtRE
1615    operandsWithExtRE = re.compile(operandsWithExtREString, re.MULTILINE)
1616
1617maxInstSrcRegs = 0
1618maxInstDestRegs = 0
1619
1620class OperandList:
1621
1622    # Find all the operands in the given code block.  Returns an operand
1623    # descriptor list (instance of class OperandList).
1624    def __init__(self, code):
1625        self.items = []
1626        self.bases = {}
1627        # delete comments so we don't match on reg specifiers inside
1628        code = commentRE.sub('', code)
1629        # search for operands
1630        next_pos = 0
1631        while 1:
1632            match = operandsRE.search(code, next_pos)
1633            if not match:
1634                # no more matches: we're done
1635                break
1636            op = match.groups()
1637            # regexp groups are operand full name, base, and extension
1638            (op_full, op_base, op_ext) = op
1639            # if the token following the operand is an assignment, this is
1640            # a destination (LHS), else it's a source (RHS)
1641            is_dest = (assignRE.match(code, match.end()) != None)
1642            is_src = not is_dest
1643            # see if we've already seen this one
1644            op_desc = self.find_base(op_base)
1645            if op_desc:
1646                if op_desc.ext != op_ext:
1647                    error(0, 'Inconsistent extensions for operand %s' % \
1648                          op_base)
1649                op_desc.is_src = op_desc.is_src or is_src
1650                op_desc.is_dest = op_desc.is_dest or is_dest
1651            else:
1652                # new operand: create new descriptor
1653                op_desc = operandNameMap[op_base](op_full, op_ext,
1654                                                  is_src, is_dest)
1655                self.append(op_desc)
1656            # start next search after end of current match
1657            next_pos = match.end()
1658        self.sort()
1659        # enumerate source & dest register operands... used in building
1660        # constructor later
1661        self.numSrcRegs = 0
1662        self.numDestRegs = 0
1663        self.numFPDestRegs = 0
1664        self.numIntDestRegs = 0
1665        self.memOperand = None
1666        for op_desc in self.items:
1667            if op_desc.isReg():
1668                if op_desc.is_src:
1669                    op_desc.src_reg_idx = self.numSrcRegs
1670                    self.numSrcRegs += 1
1671                if op_desc.is_dest:
1672                    op_desc.dest_reg_idx = self.numDestRegs
1673                    self.numDestRegs += 1
1674                    if op_desc.isFloatReg():
1675                        self.numFPDestRegs += 1
1676                    elif op_desc.isIntReg():
1677                        self.numIntDestRegs += 1
1678            elif op_desc.isMem():
1679                if self.memOperand:
1680                    error(0, "Code block has more than one memory operand.")
1681                self.memOperand = op_desc
1682        global maxInstSrcRegs
1683        global maxInstDestRegs
1684        if maxInstSrcRegs < self.numSrcRegs:
1685            maxInstSrcRegs = self.numSrcRegs
1686        if maxInstDestRegs < self.numDestRegs:
1687            maxInstDestRegs = self.numDestRegs
1688        # now make a final pass to finalize op_desc fields that may depend
1689        # on the register enumeration
1690        for op_desc in self.items:
1691            op_desc.finalize()
1692
1693    def __len__(self):
1694        return len(self.items)
1695
1696    def __getitem__(self, index):
1697        return self.items[index]
1698
1699    def append(self, op_desc):
1700        self.items.append(op_desc)
1701        self.bases[op_desc.base_name] = op_desc
1702
1703    def find_base(self, base_name):
1704        # like self.bases[base_name], but returns None if not found
1705        # (rather than raising exception)
1706        return self.bases.get(base_name)
1707
1708    # internal helper function for concat[Some]Attr{Strings|Lists}
1709    def __internalConcatAttrs(self, attr_name, filter, result):
1710        for op_desc in self.items:
1711            if filter(op_desc):
1712                result += getattr(op_desc, attr_name)
1713        return result
1714
1715    # return a single string that is the concatenation of the (string)
1716    # values of the specified attribute for all operands
1717    def concatAttrStrings(self, attr_name):
1718        return self.__internalConcatAttrs(attr_name, lambda x: 1, '')
1719
1720    # like concatAttrStrings, but only include the values for the operands
1721    # for which the provided filter function returns true
1722    def concatSomeAttrStrings(self, filter, attr_name):
1723        return self.__internalConcatAttrs(attr_name, filter, '')
1724
1725    # return a single list that is the concatenation of the (list)
1726    # values of the specified attribute for all operands
1727    def concatAttrLists(self, attr_name):
1728        return self.__internalConcatAttrs(attr_name, lambda x: 1, [])
1729
1730    # like concatAttrLists, but only include the values for the operands
1731    # for which the provided filter function returns true
1732    def concatSomeAttrLists(self, filter, attr_name):
1733        return self.__internalConcatAttrs(attr_name, filter, [])
1734
1735    def sort(self):
1736        self.items.sort(lambda a, b: a.sort_pri - b.sort_pri)
1737
1738class SubOperandList(OperandList):
1739
1740    # Find all the operands in the given code block.  Returns an operand
1741    # descriptor list (instance of class OperandList).
1742    def __init__(self, code, master_list):
1743        self.items = []
1744        self.bases = {}
1745        # delete comments so we don't match on reg specifiers inside
1746        code = commentRE.sub('', code)
1747        # search for operands
1748        next_pos = 0
1749        while 1:
1750            match = operandsRE.search(code, next_pos)
1751            if not match:
1752                # no more matches: we're done
1753                break
1754            op = match.groups()
1755            # regexp groups are operand full name, base, and extension
1756            (op_full, op_base, op_ext) = op
1757            # find this op in the master list
1758            op_desc = master_list.find_base(op_base)
1759            if not op_desc:
1760                error(0, 'Found operand %s which is not in the master list!' \
1761                        ' This is an internal error' % \
1762                          op_base)
1763            else:
1764                # See if we've already found this operand
1765                op_desc = self.find_base(op_base)
1766                if not op_desc:
1767                    # if not, add a reference to it to this sub list
1768                    self.append(master_list.bases[op_base])
1769
1770            # start next search after end of current match
1771            next_pos = match.end()
1772        self.sort()
1773        self.memOperand = None
1774        for op_desc in self.items:
1775            if op_desc.isMem():
1776                if self.memOperand:
1777                    error(0, "Code block has more than one memory operand.")
1778                self.memOperand = op_desc
1779
1780# Regular expression object to match C++ comments
1781# (used in findOperands())
1782commentRE = re.compile(r'//.*\n')
1783
1784# Regular expression object to match assignment statements
1785# (used in findOperands())
1786assignRE = re.compile(r'\s*=(?!=)', re.MULTILINE)
1787
1788# Munge operand names in code string to make legal C++ variable names.
1789# This means getting rid of the type extension if any.
1790# (Will match base_name attribute of Operand object.)
1791def substMungedOpNames(code):
1792    return operandsWithExtRE.sub(r'\1', code)
1793
1794# Fix up code snippets for final substitution in templates.
1795def mungeSnippet(s):
1796    if isinstance(s, str):
1797        return substMungedOpNames(substBitOps(s))
1798    else:
1799        return s
1800
1801def makeFlagConstructor(flag_list):
1802    if len(flag_list) == 0:
1803        return ''
1804    # filter out repeated flags
1805    flag_list.sort()
1806    i = 1
1807    while i < len(flag_list):
1808        if flag_list[i] == flag_list[i-1]:
1809            del flag_list[i]
1810        else:
1811            i += 1
1812    pre = '\n\tflags['
1813    post = '] = true;'
1814    code = pre + string.join(flag_list, post + pre) + post
1815    return code
1816
1817# Assume all instruction flags are of the form 'IsFoo'
1818instFlagRE = re.compile(r'Is.*')
1819
1820# OpClass constants end in 'Op' except No_OpClass
1821opClassRE = re.compile(r'.*Op|No_OpClass')
1822
1823class InstObjParams:
1824    def __init__(self, mnem, class_name, base_class = '',
1825                 snippets = {}, opt_args = []):
1826        self.mnemonic = mnem
1827        self.class_name = class_name
1828        self.base_class = base_class
1829        if not isinstance(snippets, dict):
1830            snippets = {'code' : snippets}
1831        compositeCode = ' '.join(map(str, snippets.values()))
1832        self.snippets = snippets
1833
1834        self.operands = OperandList(compositeCode)
1835        self.constructor = self.operands.concatAttrStrings('constructor')
1836        self.constructor += \
1837                 '\n\t_numSrcRegs = %d;' % self.operands.numSrcRegs
1838        self.constructor += \
1839                 '\n\t_numDestRegs = %d;' % self.operands.numDestRegs
1840        self.constructor += \
1841                 '\n\t_numFPDestRegs = %d;' % self.operands.numFPDestRegs
1842        self.constructor += \
1843                 '\n\t_numIntDestRegs = %d;' % self.operands.numIntDestRegs
1844        self.flags = self.operands.concatAttrLists('flags')
1845
1846        # Make a basic guess on the operand class (function unit type).
1847        # These are good enough for most cases, and can be overridden
1848        # later otherwise.
1849        if 'IsStore' in self.flags:
1850            self.op_class = 'MemWriteOp'
1851        elif 'IsLoad' in self.flags or 'IsPrefetch' in self.flags:
1852            self.op_class = 'MemReadOp'
1853        elif 'IsFloating' in self.flags:
1854            self.op_class = 'FloatAddOp'
1855        else:
1856            self.op_class = 'IntAluOp'
1857
1858        # Optional arguments are assumed to be either StaticInst flags
1859        # or an OpClass value.  To avoid having to import a complete
1860        # list of these values to match against, we do it ad-hoc
1861        # with regexps.
1862        for oa in opt_args:
1863            if instFlagRE.match(oa):
1864                self.flags.append(oa)
1865            elif opClassRE.match(oa):
1866                self.op_class = oa
1867            else:
1868                error(0, 'InstObjParams: optional arg "%s" not recognized '
1869                      'as StaticInst::Flag or OpClass.' % oa)
1870
1871        # add flag initialization to contructor here to include
1872        # any flags added via opt_args
1873        self.constructor += makeFlagConstructor(self.flags)
1874
1875        # if 'IsFloating' is set, add call to the FP enable check
1876        # function (which should be provided by isa_desc via a declare)
1877        if 'IsFloating' in self.flags:
1878            self.fp_enable_check = 'fault = checkFpEnableFault(xc);'
1879        else:
1880            self.fp_enable_check = ''
1881
1882#######################
1883#
1884# Output file template
1885#
1886
1887file_template = '''
1888/*
1889 * DO NOT EDIT THIS FILE!!!
1890 *
1891 * It was automatically generated from the ISA description in %(filename)s
1892 */
1893
1894%(includes)s
1895
1896%(global_output)s
1897
1898namespace %(namespace)s {
1899
1900%(namespace_output)s
1901
1902} // namespace %(namespace)s
1903
1904%(decode_function)s
1905'''
1906
1907max_inst_regs_template = '''
1908/*
1909 * DO NOT EDIT THIS FILE!!!
1910 *
1911 * It was automatically generated from the ISA description in %(filename)s
1912 */
1913
1914namespace %(namespace)s {
1915
1916    const int MaxInstSrcRegs = %(MaxInstSrcRegs)d;
1917    const int MaxInstDestRegs = %(MaxInstDestRegs)d;
1918
1919} // namespace %(namespace)s
1920
1921'''
1922
1923
1924# Update the output file only if the new contents are different from
1925# the current contents.  Minimizes the files that need to be rebuilt
1926# after minor changes.
1927def update_if_needed(file, contents):
1928    update = False
1929    if os.access(file, os.R_OK):
1930        f = open(file, 'r')
1931        old_contents = f.read()
1932        f.close()
1933        if contents != old_contents:
1934            print 'Updating', file
1935            os.remove(file) # in case it's write-protected
1936            update = True
1937        else:
1938            print 'File', file, 'is unchanged'
1939    else:
1940        print 'Generating', file
1941        update = True
1942    if update:
1943        f = open(file, 'w')
1944        f.write(contents)
1945        f.close()
1946
1947# This regular expression matches '##include' directives
1948includeRE = re.compile(r'^\s*##include\s+"(?P<filename>[\w/.-]*)".*$',
1949                       re.MULTILINE)
1950
1951# Function to replace a matched '##include' directive with the
1952# contents of the specified file (with nested ##includes replaced
1953# recursively).  'matchobj' is an re match object (from a match of
1954# includeRE) and 'dirname' is the directory relative to which the file
1955# path should be resolved.
1956def replace_include(matchobj, dirname):
1957    fname = matchobj.group('filename')
1958    full_fname = os.path.normpath(os.path.join(dirname, fname))
1959    contents = '##newfile "%s"\n%s\n##endfile\n' % \
1960               (full_fname, read_and_flatten(full_fname))
1961    return contents
1962
1963# Read a file and recursively flatten nested '##include' files.
1964def read_and_flatten(filename):
1965    current_dir = os.path.dirname(filename)
1966    try:
1967        contents = open(filename).read()
1968    except IOError:
1969        error(0, 'Error including file "%s"' % filename)
1970    fileNameStack.push((filename, 0))
1971    # Find any includes and include them
1972    contents = includeRE.sub(lambda m: replace_include(m, current_dir),
1973                             contents)
1974    fileNameStack.pop()
1975    return contents
1976
1977#
1978# Read in and parse the ISA description.
1979#
1980def parse_isa_desc(isa_desc_file, output_dir):
1981    # Read file and (recursively) all included files into a string.
1982    # PLY requires that the input be in a single string so we have to
1983    # do this up front.
1984    isa_desc = read_and_flatten(isa_desc_file)
1985
1986    # Initialize filename stack with outer file.
1987    fileNameStack.push((isa_desc_file, 0))
1988
1989    # Parse it.
1990    (isa_name, namespace, global_code, namespace_code) = parser.parse(isa_desc)
1991
1992    # grab the last three path components of isa_desc_file to put in
1993    # the output
1994    filename = '/'.join(isa_desc_file.split('/')[-3:])
1995
1996    # generate decoder.hh
1997    includes = '#include "base/bitfield.hh" // for bitfield support'
1998    global_output = global_code.header_output
1999    namespace_output = namespace_code.header_output
2000    decode_function = ''
2001    update_if_needed(output_dir + '/decoder.hh', file_template % vars())
2002
2003    # generate decoder.cc
2004    includes = '#include "decoder.hh"'
2005    global_output = global_code.decoder_output
2006    namespace_output = namespace_code.decoder_output
2007    # namespace_output += namespace_code.decode_block
2008    decode_function = namespace_code.decode_block
2009    update_if_needed(output_dir + '/decoder.cc', file_template % vars())
2010
2011    # generate per-cpu exec files
2012    for cpu in cpu_models:
2013        includes = '#include "decoder.hh"\n'
2014        includes += cpu.includes
2015        global_output = global_code.exec_output[cpu.name]
2016        namespace_output = namespace_code.exec_output[cpu.name]
2017        decode_function = ''
2018        update_if_needed(output_dir + '/' + cpu.filename,
2019                          file_template % vars())
2020
2021    # The variable names here are hacky, but this will creat local variables
2022    # which will be referenced in vars() which have the value of the globals.
2023    global maxInstSrcRegs
2024    MaxInstSrcRegs = maxInstSrcRegs
2025    global maxInstDestRegs
2026    MaxInstDestRegs = maxInstDestRegs
2027    # max_inst_regs.hh
2028    update_if_needed(output_dir + '/max_inst_regs.hh', \
2029            max_inst_regs_template % vars())
2030
2031# global list of CpuModel objects (see cpu_models.py)
2032cpu_models = []
2033
2034# Called as script: get args from command line.
2035# Args are: <path to cpu_models.py> <isa desc file> <output dir> <cpu models>
2036if __name__ == '__main__':
2037    execfile(sys.argv[1])  # read in CpuModel definitions
2038    cpu_models = [CpuModel.dict[cpu] for cpu in sys.argv[4:]]
2039    parse_isa_desc(sys.argv[2], sys.argv[3])
2040