o3-pipeview.py revision 9252:f350fac86d0f
16906SBrad.Beckmann@amd.com#! /usr/bin/env python
26906SBrad.Beckmann@amd.com
36906SBrad.Beckmann@amd.com# Copyright (c) 2011 ARM Limited
46906SBrad.Beckmann@amd.com# All rights reserved
56906SBrad.Beckmann@amd.com#
66906SBrad.Beckmann@amd.com# The license below extends only to copyright in the software and shall
76906SBrad.Beckmann@amd.com# not be construed as granting a license to any other intellectual
86906SBrad.Beckmann@amd.com# property including but not limited to intellectual property relating
96906SBrad.Beckmann@amd.com# to a hardware implementation of the functionality of the software
106906SBrad.Beckmann@amd.com# licensed hereunder.  You may use the software subject to the license
116906SBrad.Beckmann@amd.com# terms below provided that you ensure that this notice is replicated
126906SBrad.Beckmann@amd.com# unmodified and in its entirety in all distributions of the software,
136906SBrad.Beckmann@amd.com# modified or unmodified, in source code or in binary form.
146906SBrad.Beckmann@amd.com#
156906SBrad.Beckmann@amd.com# Redistribution and use in source and binary forms, with or without
166906SBrad.Beckmann@amd.com# modification, are permitted provided that the following conditions are
176906SBrad.Beckmann@amd.com# met: redistributions of source code must retain the above copyright
186906SBrad.Beckmann@amd.com# notice, this list of conditions and the following disclaimer;
196906SBrad.Beckmann@amd.com# redistributions in binary form must reproduce the above copyright
206906SBrad.Beckmann@amd.com# notice, this list of conditions and the following disclaimer in the
216906SBrad.Beckmann@amd.com# documentation and/or other materials provided with the distribution;
226906SBrad.Beckmann@amd.com# neither the name of the copyright holders nor the names of its
236906SBrad.Beckmann@amd.com# contributors may be used to endorse or promote products derived from
246906SBrad.Beckmann@amd.com# this software without specific prior written permission.
256906SBrad.Beckmann@amd.com#
266906SBrad.Beckmann@amd.com# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
276906SBrad.Beckmann@amd.com# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
286906SBrad.Beckmann@amd.com# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
296906SBrad.Beckmann@amd.com# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
308183Snilay@cs.wisc.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
316906SBrad.Beckmann@amd.com# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
326906SBrad.Beckmann@amd.com# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
336906SBrad.Beckmann@amd.com# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
349100SBrad.Beckmann@amd.com# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
356906SBrad.Beckmann@amd.com# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
366906SBrad.Beckmann@amd.com# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
376906SBrad.Beckmann@amd.com#
386906SBrad.Beckmann@amd.com# Authors: Giacomo Gabrielli
396906SBrad.Beckmann@amd.com
406906SBrad.Beckmann@amd.com# Pipeline activity viewer for the O3 CPU model.
416906SBrad.Beckmann@amd.com
427538SBrad.Beckmann@amd.comimport optparse
437538SBrad.Beckmann@amd.comimport os
447538SBrad.Beckmann@amd.comimport sys
458929Snilay@cs.wisc.eduimport copy
466906SBrad.Beckmann@amd.com
476906SBrad.Beckmann@amd.com# Temporary storage for instructions. The queue is filled in out-of-order
486906SBrad.Beckmann@amd.com# until it reaches 'max_threshold' number of instructions. It is then
496906SBrad.Beckmann@amd.com# sorted out and instructions are printed out until their number drops to
506906SBrad.Beckmann@amd.com# 'min_threshold'.
516906SBrad.Beckmann@amd.com# It is assumed that the instructions are not out of order for more then
526906SBrad.Beckmann@amd.com# 'min_threshold' places - otherwise they will appear out of order.
536906SBrad.Beckmann@amd.cominsts = {
546906SBrad.Beckmann@amd.com    'queue': [] ,         # Instructions to print.
556906SBrad.Beckmann@amd.com    'max_threshold':2000, # Instructions are sorted out and printed when
566906SBrad.Beckmann@amd.com                          # their number reaches this threshold.
576906SBrad.Beckmann@amd.com    'min_threshold':1000, # Printing stops when this number is reached.
586906SBrad.Beckmann@amd.com    'sn_start':0,         # The first instruction seq. number to be printed.
596906SBrad.Beckmann@amd.com    'sn_stop':0,          # The last instruction seq. number to be printed.
606906SBrad.Beckmann@amd.com    'tick_start':0,       # The first tick to be printed
616906SBrad.Beckmann@amd.com    'tick_stop':0,        # The last tick to be printed
626906SBrad.Beckmann@amd.com    'tick_drift':2000,    # Used to calculate the start and the end of main
636906SBrad.Beckmann@amd.com                          # loop. We assume here that the instructions are not
646906SBrad.Beckmann@amd.com                          # out of order for more then 2000 CPU ticks,
658180SBrad.Beckmann@amd.com                          # otherwise the print may not start/stop
668257SBrad.Beckmann@amd.com                          # at the time specified by tick_start/stop.
678257SBrad.Beckmann@amd.com    'only_committed':0    # Set if only committed instructions are printed.
686906SBrad.Beckmann@amd.com}
696906SBrad.Beckmann@amd.com
706906SBrad.Beckmann@amd.comdef process_trace(trace, outfile, cycle_time, width, color, timestamps,
716906SBrad.Beckmann@amd.com                  committed_only, start_tick, stop_tick, start_sn, stop_sn):
726906SBrad.Beckmann@amd.com    global insts
736906SBrad.Beckmann@amd.com
746906SBrad.Beckmann@amd.com    insts['sn_start'] = start_sn
756906SBrad.Beckmann@amd.com    insts['sn_stop'] = stop_sn
768180SBrad.Beckmann@amd.com    insts['tick_start'] = start_tick
778180SBrad.Beckmann@amd.com    insts['tick_stop'] = stop_tick
786906SBrad.Beckmann@amd.com    insts['tick_drift'] = insts['tick_drift'] * cycle_time
796906SBrad.Beckmann@amd.com    insts['only_committed'] = committed_only
806906SBrad.Beckmann@amd.com    line = None
816906SBrad.Beckmann@amd.com    fields = None
828322Ssteve.reinhardt@amd.com
838322Ssteve.reinhardt@amd.com    # Read the first line
848436SBrad.Beckmann@amd.com    line = trace.readline()
858717Snilay@cs.wisc.edu    if not line: return
868717Snilay@cs.wisc.edu    fields = line.split(':')
878436SBrad.Beckmann@amd.com
888322Ssteve.reinhardt@amd.com    # Skip lines up to the starting tick
897015SBrad.Beckmann@amd.com    if start_tick != 0:
907015SBrad.Beckmann@amd.com        while True:
916906SBrad.Beckmann@amd.com            if fields[0] != 'O3PipeView': continue
928436SBrad.Beckmann@amd.com            if (int(fields[2]) > 0 and
936906SBrad.Beckmann@amd.com                int(fields[2]) >= start_tick-insts['tick_drift']): break
948322Ssteve.reinhardt@amd.com            line = trace.readline()
958322Ssteve.reinhardt@amd.com            if not line: return
966906SBrad.Beckmann@amd.com            fields = line.split(':')
978845Sandreas.hansson@arm.com
986906SBrad.Beckmann@amd.com    # Skip lines up to the starting sequence number
999468Smalek.musleh@gmail.com    if start_sn != 0:
1006906SBrad.Beckmann@amd.com        while True:
1016906SBrad.Beckmann@amd.com            if fields[0] != 'O3PipeView': continue
1026906SBrad.Beckmann@amd.com            if (fields[1] == 'fetch' and
1036906SBrad.Beckmann@amd.com                int(fields[5]) >= (start_sn-insts['max_threshold'])):
1046906SBrad.Beckmann@amd.com                break
1056906SBrad.Beckmann@amd.com            line = trace.readline()
1068257SBrad.Beckmann@amd.com            if not line: return
1078257SBrad.Beckmann@amd.com            fields = line.split(':')
1089232Sandreas.hansson@arm.com
1099232Sandreas.hansson@arm.com    # Skip lines up to next instruction fetch
1106906SBrad.Beckmann@amd.com    while fields[0] != 'O3PipeView' or fields[1] != 'fetch':
1116906SBrad.Beckmann@amd.com        line = trace.readline()
1129793Sakash.bagdia@arm.com        if not line: return
1139793Sakash.bagdia@arm.com        fields = line.split(':')
1149793Sakash.bagdia@arm.com
1159793Sakash.bagdia@arm.com    # Print header
1169793Sakash.bagdia@arm.com    outfile.write('// f = fetch, d = decode, n = rename, p = dispatch, '
1179793Sakash.bagdia@arm.com                  'i = issue, c = complete, r = retire\n\n')
1189793Sakash.bagdia@arm.com    outfile.write(' ' + 'timeline'.center(width) +
1196906SBrad.Beckmann@amd.com                  '   ' + 'tick'.center(15) +
1206906SBrad.Beckmann@amd.com                  '  ' + 'pc.upc'.center(12) +
1216906SBrad.Beckmann@amd.com                  '  ' + 'disasm'.ljust(25) +
1226906SBrad.Beckmann@amd.com                  '  ' + 'seq_num'.center(15))
1236906SBrad.Beckmann@amd.com    if timestamps:
1249793Sakash.bagdia@arm.com        outfile.write('timestamps'.center(25))
1259793Sakash.bagdia@arm.com    outfile.write('\n')
1269793Sakash.bagdia@arm.com
1279793Sakash.bagdia@arm.com    # Region of interest
1286906SBrad.Beckmann@amd.com    curr_inst = {}
1296906SBrad.Beckmann@amd.com    while True:
1306906SBrad.Beckmann@amd.com        if fields[0] == 'O3PipeView':
1316906SBrad.Beckmann@amd.com            curr_inst[fields[1]] = int(fields[2])
1326906SBrad.Beckmann@amd.com            if fields[1] == 'fetch':
1338257SBrad.Beckmann@amd.com                if ((stop_tick > 0 and int(fields[2]) > stop_tick+insts['tick_drift']) or
1346906SBrad.Beckmann@amd.com                    (stop_sn > 0 and int(fields[5]) > (stop_sn+insts['max_threshold']))):
1357541SBrad.Beckmann@amd.com                    print_insts(outfile, cycle_time, width, color, timestamps, 0)
1367541SBrad.Beckmann@amd.com                    return
1377541SBrad.Beckmann@amd.com                (curr_inst['pc'], curr_inst['upc']) = fields[3:5]
1387541SBrad.Beckmann@amd.com                curr_inst['sn'] = int(fields[5])
1397541SBrad.Beckmann@amd.com                curr_inst['disasm'] = ' '.join(fields[6][:-1].split())
1407541SBrad.Beckmann@amd.com            elif fields[1] == 'retire':
1418436SBrad.Beckmann@amd.com                queue_inst(outfile, curr_inst, cycle_time, width, color, timestamps)
1428436SBrad.Beckmann@amd.com        line = trace.readline()
1436906SBrad.Beckmann@amd.com        if not line: return
1449468Smalek.musleh@gmail.com        fields = line.split(':')
1456906SBrad.Beckmann@amd.com
1466906SBrad.Beckmann@amd.com
1478257SBrad.Beckmann@amd.com#Sorts out instructions according to sequence number
1488257SBrad.Beckmann@amd.comdef compare_by_sn(a, b):
1498929Snilay@cs.wisc.edu    return cmp(a['sn'], b['sn'])
1506906SBrad.Beckmann@amd.com
1516906SBrad.Beckmann@amd.com# Puts new instruction into the print queue.
1526906SBrad.Beckmann@amd.com# Sorts out and prints instructions when their number reaches threshold value
1536906SBrad.Beckmann@amd.comdef queue_inst(outfile, inst, cycle_time, width, color, timestamps):
1548477Snilay@cs.wisc.edu    global insts
1556906SBrad.Beckmann@amd.com    l_copy = copy.deepcopy(inst)
1566906SBrad.Beckmann@amd.com    insts['queue'].append(l_copy)
1578257SBrad.Beckmann@amd.com    if len(insts['queue']) > insts['max_threshold']:
1588477Snilay@cs.wisc.edu        print_insts(outfile, cycle_time, width, color, timestamps, insts['min_threshold'])
1598477Snilay@cs.wisc.edu
1606906SBrad.Beckmann@amd.com# Sorts out and prints instructions in print queue
1619468Smalek.musleh@gmail.comdef print_insts(outfile, cycle_time, width, color, timestamps, lower_threshold):
1629468Smalek.musleh@gmail.com    global insts
1636906SBrad.Beckmann@amd.com    insts['queue'].sort(compare_by_sn)
1648257SBrad.Beckmann@amd.com    while len(insts['queue']) > lower_threshold:
1658257SBrad.Beckmann@amd.com        print_item=insts['queue'].pop(0)
1666906SBrad.Beckmann@amd.com        # As the instructions are processed out of order the main loop starts
1676906SBrad.Beckmann@amd.com        # earlier then specified by start_sn/tick and finishes later then what
1689100SBrad.Beckmann@amd.com        # is defined in stop_sn/tick.
1699100SBrad.Beckmann@amd.com        # Therefore, here we have to filter out instructions that reside out of
1709100SBrad.Beckmann@amd.com        # the specified boundaries.
171        if (insts['sn_start'] > 0 and print_item['sn'] < insts['sn_start']):
172            continue; # earlier then the starting sequence number
173        if (insts['sn_stop'] > 0 and print_item['sn'] > insts['sn_stop']):
174            continue; # later then the ending sequence number
175        if (insts['tick_start'] > 0 and print_item['fetch'] < insts['tick_start']):
176            continue; # earlier then the starting tick number
177        if (insts['tick_stop'] > 0 and print_item['fetch'] > insts['tick_stop']):
178            continue; # later then the ending tick number
179
180        if (insts['only_committed'] != 0 and print_item['retire'] == 0):
181            continue; # retire is set to zero if it hasn't been completed
182        print_inst(outfile,  print_item, cycle_time, width, color, timestamps)
183
184# Prints a single instruction
185def print_inst(outfile, inst, cycle_time, width, color, timestamps):
186    if color:
187        from m5.util.terminal import termcap
188    else:
189        from m5.util.terminal import no_termcap as termcap
190    # Pipeline stages
191    stages = [{'name': 'fetch',
192               'color': termcap.Blue + termcap.Reverse,
193               'shorthand': 'f'},
194              {'name': 'decode',
195               'color': termcap.Yellow + termcap.Reverse,
196               'shorthand': 'd'},
197              {'name': 'rename',
198               'color': termcap.Magenta + termcap.Reverse,
199               'shorthand': 'n'},
200              {'name': 'dispatch',
201               'color': termcap.Green + termcap.Reverse,
202               'shorthand': 'p'},
203              {'name': 'issue',
204               'color': termcap.Red + termcap.Reverse,
205               'shorthand': 'i'},
206              {'name': 'complete',
207               'color': termcap.Cyan + termcap.Reverse,
208               'shorthand': 'c'},
209              {'name': 'retire',
210               'color': termcap.Blue + termcap.Reverse,
211               'shorthand': 'r'}]
212
213    # Print
214
215    time_width = width * cycle_time
216    base_tick = (inst['fetch'] / time_width) * time_width
217
218    # Find out the time of the last event - it may not
219    # be 'retire' if the instruction is not comlpeted.
220    last_event_time = max(inst['fetch'], inst['decode'],inst['rename'],
221        inst['dispatch'],inst['issue'], inst['complete'], inst['retire'])
222
223    # Timeline shorter then time_width is printed in compact form where
224    # the print continues at the start of the same line.
225    if ((last_event_time - inst['fetch']) < time_width):
226        num_lines = 1 # compact form
227    else:
228        num_lines = ((last_event_time - base_tick) / time_width) + 1
229
230    curr_color = termcap.Normal
231
232    # This will visually distinguish completed and abandoned intructions.
233    if inst['retire'] == 0: dot = '=' # abandoned instruction
234    else:                   dot = '.' # completed instruction
235
236    for i in range(num_lines):
237        start_tick = base_tick + i * time_width
238        end_tick = start_tick + time_width
239        if num_lines == 1:  # compact form
240            end_tick += (inst['fetch'] - base_tick)
241        events = []
242        for stage_idx in range(len(stages)):
243            tick = inst[stages[stage_idx]['name']]
244            if tick != 0:
245                if tick >= start_tick and tick < end_tick:
246                    events.append((tick % time_width,
247                                   stages[stage_idx]['name'],
248                                   stage_idx, tick))
249        events.sort()
250        outfile.write('[')
251        pos = 0
252        if num_lines == 1 and events[0][2] != 0:  # event is not fetch
253            curr_color = stages[events[0][2] - 1]['color']
254        for event in events:
255            if (stages[event[2]]['name'] == 'dispatch' and
256                inst['dispatch'] == inst['issue']):
257                continue
258            outfile.write(curr_color + dot * ((event[0] / cycle_time) - pos))
259            outfile.write(stages[event[2]]['color'] +
260                          stages[event[2]]['shorthand'])
261
262            if event[3] != last_event_time:  # event is not the last one
263                curr_color = stages[event[2]]['color']
264            else:
265                curr_color = termcap.Normal
266
267            pos = (event[0] / cycle_time) + 1
268        outfile.write(curr_color + dot * (width - pos) + termcap.Normal +
269                      ']-(' + str(base_tick + i * time_width).rjust(15) + ') ')
270        if i == 0:
271            outfile.write('%s.%s  %s [%s]' % (
272                    inst['pc'].rjust(10),
273                    inst['upc'],
274                    inst['disasm'].ljust(25),
275                    str(inst['sn']).rjust(15)))
276            if timestamps:
277                outfile.write('  f=%s, r=%s' % (inst['fetch'], inst['retire']))
278            outfile.write('\n')
279        else:
280            outfile.write('...'.center(12) + '\n')
281
282
283def validate_range(my_range):
284    my_range = [int(i) for i in my_range.split(':')]
285    if (len(my_range) != 2 or
286        my_range[0] < 0 or
287        my_range[1] > 0 and my_range[0] >= my_range[1]):
288        return None
289    return my_range
290
291
292def main():
293    # Parse options
294    usage = ('%prog [OPTION]... TRACE_FILE')
295    parser = optparse.OptionParser(usage=usage)
296    parser.add_option(
297        '-o',
298        dest='outfile',
299        default=os.path.join(os.getcwd(), 'o3-pipeview.out'),
300        help="output file (default: '%default')")
301    parser.add_option(
302        '-t',
303        dest='tick_range',
304        default='0:-1',
305        help="tick range (default: '%default'; -1 == inf.)")
306    parser.add_option(
307        '-i',
308        dest='inst_range',
309        default='0:-1',
310        help="instruction range (default: '%default'; -1 == inf.)")
311    parser.add_option(
312        '-w',
313        dest='width',
314        type='int', default=80,
315        help="timeline width (default: '%default')")
316    parser.add_option(
317        '--color',
318        action='store_true', default=False,
319        help="enable colored output (default: '%default')")
320    parser.add_option(
321        '-c', '--cycle-time',
322        type='int', default=1000,
323        help="CPU cycle time in ticks (default: '%default')")
324    parser.add_option(
325        '--timestamps',
326        action='store_true', default=False,
327        help="print fetch and retire timestamps (default: '%default')")
328    parser.add_option(
329        '--only_committed',
330        action='store_true', default=False,
331        help="display only committed (completed) instructions (default: '%default')")
332    (options, args) = parser.parse_args()
333    if len(args) != 1:
334        parser.error('incorrect number of arguments')
335        sys.exit(1)
336    tick_range = validate_range(options.tick_range)
337    if not tick_range:
338        parser.error('invalid range')
339        sys.exit(1)
340    inst_range = validate_range(options.inst_range)
341    if not inst_range:
342        parser.error('invalid range')
343        sys.exit(1)
344    # Process trace
345    print 'Processing trace... ',
346    with open(args[0], 'r') as trace:
347        with open(options.outfile, 'w') as out:
348            process_trace(trace, out, options.cycle_time, options.width,
349                          options.color, options.timestamps,
350                          options.only_committed, *(tick_range + inst_range))
351    print 'done!'
352
353
354if __name__ == '__main__':
355    sys.path.append(os.path.join(
356            os.path.dirname(os.path.abspath(__file__)),
357            '..', 'src', 'python'))
358    main()
359