pypy / pypy / tool / jitlogparser / parser.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
import re, sys

from rpython.jit.metainterp.resoperation import opname
from rpython.jit.tool.oparser import OpParser
from rpython.tool.logparser import parse_log_file, extract_category
from copy import copy

def parse_code_data(arg):
    name = None
    lineno = 0
    filename = None
    bytecode_no = 0
    bytecode_name = None
    m = re.search('<code object ([<>\w]+)[\.,] file \'(.+?)\'[\.,] line (\d+)> #(\d+) (\w+)',
                  arg)
    if m is None:
        # a non-code loop, like StrLiteralSearch or something
        if arg:
            bytecode_name = arg
    else:
        name, filename, lineno, bytecode_no, bytecode_name = m.groups()
    return name, bytecode_name, filename, int(lineno), int(bytecode_no)

class Op(object):
    bridge = None
    offset = None
    asm = None
    failargs = ()

    def __init__(self, name, args, res, descr):
        self.name = name
        self.args = args
        self.res = res
        self.descr = descr
        self._is_guard = name.startswith('guard_')
        if self._is_guard:
            self.guard_no = int(self.descr[len('<Guard'):-1])

    def setfailargs(self, failargs):
        self.failargs = failargs

    def getarg(self, i):
        return self.args[i]

    def getargs(self):
        return self.args[:]

    def getres(self):
        return self.res

    def getdescr(self):
        return self.descr

    def is_guard(self):
        return self._is_guard

    def repr(self):
        args = self.getargs()
        if self.descr is not None:
            args.append('descr=%s' % self.descr)
        arglist = ', '.join(args)
        if self.res is not None:
            return '%s = %s(%s)' % (self.getres(), self.name, arglist)
        else:
            return '%s(%s)' % (self.name, arglist)

    def __repr__(self):
        return self.repr()

class SimpleParser(OpParser):

    # factory method
    Op = Op
    use_mock_model = True

    def postprocess(self, loop, backend_dump=None, backend_tp=None,
                    dump_start=0):
        if backend_dump is not None:
            raw_asm = self._asm_disassemble(backend_dump.decode('hex'),
                                            backend_tp, dump_start)
            asm = []
            start = 0
            for elem in raw_asm:
                if len(elem.split("\t")) < 3:
                    continue
                e = elem.split("\t")
                adr = e[0]
                v = " ".join(e[2:])
                if not start:
                    start = int(adr.strip(":"), 16)
                ofs = int(adr.strip(":"), 16) - start
                if ofs >= 0:
                    asm.append((ofs, v.strip("\n")))
            asm_index = 0
            for i, op in enumerate(loop.operations):
                end = 0
                j = i + 1
                while end == 0:
                    if j == len(loop.operations):
                        end = loop.last_offset
                        break
                    if loop.operations[j].offset is None:
                        j += 1
                    else:
                        end = loop.operations[j].offset
                if op.offset is not None:
                    while asm[asm_index][0] < op.offset:
                        asm_index += 1
                    end_index = asm_index
                    while asm[end_index][0] < end and end_index < len(asm) - 1:
                        end_index += 1
                    op.asm = '\n'.join([asm[i][1] for i in range(asm_index, end_index)])
        return loop

    def _asm_disassemble(self, d, origin_addr, tp):
        from rpython.jit.backend.tool.viewcode import machine_code_dump
        return list(machine_code_dump(d, tp, origin_addr))

    @classmethod
    def parse_from_input(cls, input, **kwds):
        parser = cls(input, None, {}, 'lltype', None,
                     nonstrict=True)
        loop = parser.parse()
        return parser.postprocess(loop, **kwds)

    def parse_args(self, opname, argspec):
        if not argspec.strip():
            return [], None
        if opname == 'debug_merge_point':
            return argspec.split(", ", 2), None
        else:
            args = argspec.split(', ')
            descr = None
            if args[-1].startswith('descr='):
                descr = args[-1][len('descr='):]
                args = args[:-1]
            if args == ['']:
                args = []
            return (args, descr)

    def box_for_var(self, res):
        return res

    def create_op(self, opnum, args, res, descr):
        return self.Op(intern(opname[opnum].lower()), args, res, descr)



class NonCodeError(Exception):
    pass

class TraceForOpcode(object):
    code = None
    is_bytecode = True
    inline_level = None
    has_dmp = False

    def __init__(self, operations, storage, loopname):
        for op in operations:
            if op.name == 'debug_merge_point':
                self.inline_level = int(op.args[0])
                parsed = parse_code_data(op.args[2][1:-1])
                (self.name, self.bytecode_name, self.filename,
                 self.startlineno, self.bytecode_no) = parsed
                break
        else:
            self.inline_level = 0
            parsed = parse_code_data(loopname)
            (self.name, self.bytecode_name, self.filename,
             self.startlineno, self.bytecode_no) = parsed
        self.operations = operations
        self.storage = storage
        self.code = storage.disassemble_code(self.filename, self.startlineno,
                                             self.name)

    def repr(self):
        if self.filename is None:
            return self.bytecode_name
        return "%s, file '%s', line %d" % (self.name, self.filename,
                                           self.startlineno)

    def getcode(self):
        return self.code

    def has_valid_code(self):
        return self.code is not None

    def getopcode(self):
        if self.code is None:
            return None
        return self.code.map[self.bytecode_no]

    def getlineno(self):
        code = self.getopcode()
        if code is None:
            return None
        return code.lineno
    lineno = property(getlineno)

    def getline_starts_here(self):
        return self.getopcode().line_starts_here
    line_starts_here = property(getline_starts_here)

    def __repr__(self):
        return "[%s]" % ", ".join([repr(op) for op in self.operations])

    def pretty_print(self, out):
        pass

class Function(object):
    filename = None
    name = None
    startlineno = 0
    _linerange = None
    _lineset = None
    is_bytecode = False
    inline_level = None
    bytecode_name = None

    # factory method
    TraceForOpcode = TraceForOpcode

    def __init__(self, chunks, path, storage, inputargs=''):
        self.path = path
        self.inputargs = inputargs
        self.chunks = chunks
        for chunk in self.chunks:
            if chunk.bytecode_name is not None:
                self.startlineno = chunk.startlineno
                self.filename = chunk.filename
                self.name = chunk.name
                self.inline_level = chunk.inline_level
                break
        self.storage = storage

    @classmethod
    def from_operations(cls, operations, storage, limit=None, inputargs='',
                        loopname=''):
        """ Slice given operation list into a chain of TraceForOpcode chunks.
        Also detect inlined functions and make them Function
        """
        stack = []

        def getpath(stack):
            return ",".join([str(len(v)) for v in stack])

        def append_to_res(bc):
            if bc.inline_level is not None:
                if bc.inline_level == len(stack) - 1:
                    pass
                elif bc.inline_level > len(stack) - 1:
                    stack.append([])
                else:
                    while bc.inline_level + 1 < len(stack):
                        last = stack.pop()
                        stack[-1].append(cls(last, getpath(stack), storage))
            stack[-1].append(bc)

        so_far = []
        stack = []
        nothing_yet = True
        for op in operations:
            if op.name == 'debug_merge_point':
                if so_far:
                    opc = cls.TraceForOpcode(so_far, storage, loopname)
                    if nothing_yet:
                        nothing_yet = False
                        for i in xrange(opc.inline_level + 1):
                            stack.append([])
                    append_to_res(opc)
                    if limit:
                        break
                    so_far = []
            so_far.append(op)
        if so_far:
            append_to_res(cls.TraceForOpcode(so_far, storage, loopname))
        # wrap stack back up
        if not stack:
            # no ops whatsoever
            return cls([], getpath(stack), storage, inputargs)
        while True:
            next = stack.pop()
            if not stack:
                return cls(next, getpath(stack), storage, inputargs)
            stack[-1].append(cls(next, getpath(stack), storage))


    def getlinerange(self):
        if self._linerange is None:
            self._compute_linerange()
        return self._linerange
    linerange = property(getlinerange)

    def getlineset(self):
        if self._lineset is None:
            self._compute_linerange()
        return self._lineset
    lineset = property(getlineset)

    def has_valid_code(self):
        for chunk in self.chunks:
            if chunk.has_valid_code():
                return True
        return False

    def _compute_linerange(self):
        self._lineset = set()
        minline = sys.maxint
        maxline = -1
        for chunk in self.chunks:
            if chunk.is_bytecode and chunk.has_valid_code():
                lineno = chunk.lineno
                minline = min(minline, lineno)
                maxline = max(maxline, lineno)
                if chunk.line_starts_here or len(chunk.operations) > 1:
                    self._lineset.add(lineno)
        if minline == sys.maxint:
            minline = 0
            maxline = 0
        self._linerange = minline, maxline

    def repr(self):
        if self.filename is None:
            return self.chunks[0].bytecode_name
        return "%s, file '%s', line %d" % (self.name, self.filename,
                                           self.startlineno)

    def __repr__(self):
        return "[%s]" % ", ".join([repr(chunk) for chunk in self.chunks])

    def pretty_print(self, out):
        print >>out, "Loop starting at %s in %s at %d" % (self.name,
                                        self.filename, self.startlineno)
        lineno = -1
        for chunk in self.chunks:
            if chunk.filename is not None and chunk.lineno != lineno:
                lineno = chunk.lineno
                source = chunk.getcode().source[chunk.lineno -
                                                chunk.startlineno]
                print >>out, "  ", source
            chunk.pretty_print(out)


def adjust_bridges(loop, bridges):
    """ Slice given loop according to given bridges to follow. Returns a plain
    list of operations.
    """
    ops = loop.operations
    res = []
    i = 0
    while i < len(ops):
        op = ops[i]
        if op.is_guard() and bridges.get('loop-' + str(op.guard_no), None):
            res.append(op)
            i = 0
            if hasattr(op.bridge, 'force_asm'):
                op.bridge.force_asm()
            ops = op.bridge.operations
        else:
            res.append(op)
            i += 1
    return res


def import_log(logname, ParserCls=SimpleParser):
    log = parse_log_file(logname)
    addrs = {}
    for entry in extract_category(log, 'jit-backend-addr'):
        m = re.search('bootstrap ([-\da-f]+)', entry)
        if not m:
            # a bridge
            m = re.search('has address ([-\da-f]+)', entry)
            addr = int(m.group(1), 16)
            entry = entry.lower()
            m = re.search('guard \d+', entry)
            name = m.group(0)
        else:
            name = entry[:entry.find('(') - 1].lower()
            addr = int(m.group(1), 16)
        addrs.setdefault(addr, []).append(name)
    dumps = {}
    for entry in extract_category(log, 'jit-backend-dump'):
        backend, _, dump, _ = entry.split("\n")
        _, addr, _, data = re.split(" +", dump)
        backend_name = backend.split(" ")[1]
        addr = int(addr[1:], 16)
        if addr in addrs and addrs[addr]:
            name = addrs[addr].pop(0) # they should come in order
            dumps[name] = (backend_name, addr, data)
    loops = []
    for entry in extract_category(log, 'jit-log-opt'):
        parser = ParserCls(entry, None, {}, 'lltype', None,
                           nonstrict=True)
        loop = parser.parse()
        comm = loop.comment
        comm = comm.lower()
        if comm.startswith('# bridge'):
            m = re.search('guard \d+', comm)
            name = m.group(0)
        elif "(" in comm:
            name = comm[2:comm.find('(')-1]
        else:
            name = " ".join(comm[2:].split(" ", 2)[:2])
        if name in dumps:
            bname, start_ofs, dump = dumps[name]
            loop.force_asm = (lambda dump=dump, start_ofs=start_ofs,
                              bname=bname, loop=loop:
                              parser.postprocess(loop, backend_tp=bname,
                                                 backend_dump=dump,
                                                 dump_start=start_ofs))
        loops += split_trace(loop)
    return log, loops

def split_trace(trace):
    labels = [0]
    if trace.comment and 'Guard' in trace.comment:
        descrs = ['bridge ' + re.search('Guard (\d+)', trace.comment).group(1)]
    else:
        descrs = ['entry ' + re.search('Loop (\d+)', trace.comment).group(1)]
    for i, op in enumerate(trace.operations):
        if op.name == 'label':
            labels.append(i)
            descrs.append(op.descr)
    labels.append(len(trace.operations) - 1)
    parts = []
    for i in range(len(labels) - 1):
        start, stop = labels[i], labels[i+1]
        part = copy(trace)
        part.operations = trace.operations[start : stop + 1]
        part.descr = descrs[i]
        part.comment = trace.comment
        parts.append(part)

    return parts

def parse_log_counts(input, loops):
    if not input:
        return
    lines = input[-1].splitlines()
    mapping = {}
    for loop in loops:
        mapping[loop.descr] = loop
    for line in lines:
        if line:
            num, count = line.split(':', 2)
            mapping[num].count = int(count)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.