Debian Codegraph @

js/src/devtools/iongraph/iongraph

raw
1 #!/usr/bin/env python3
2 # vim: set ts=4 sw=4 tw=99 et:
3
4 # iongraph -- Translate IonMonkey JSON to GraphViz.
5 # Originally by Sean Stangl. See LICENSE.
6
7 import argparse
8 import html
9 import json
10 import glob
11 import os
12 import re
13 import shutil
14 import subprocess
15 import sys
16 import tempfile
17
18 def quote(s):
19 return '"%s"' % str(s)
20
21 # Simple classes for the used subset of GraphViz' Dot format.
22 # There are more complicated constructors out there, but they all
23 # pull in annoying dependencies (and are annoying dependencies themselves).
24 class GraphWidget:
25 def __init__(self):
26 self.name = ''
27 self.props = {}
28
29 def addprops(self, propdict):
30 for p in propdict:
31 self.props[p] = propdict[p]
32
33
34 class Node(GraphWidget):
35 def __init__(self, name):
36 GraphWidget.__init__(self)
37 self.name = str(name)
38
39 class Edge(GraphWidget):
40 def __init__(self, nfrom, nto):
41 GraphWidget.__init__(self)
42 self.nfrom = str(nfrom)
43 self.nto = str(nto)
44
45 class Graph(GraphWidget):
46 def __init__(self, name, func, type):
47 GraphWidget.__init__(self)
48 self.name = name
49 self.func = func
50 self.type = str(type)
51 self.props = {}
52 self.nodes = []
53 self.edges = []
54
55 def addnode(self, n):
56 self.nodes.append(n)
57
58 def addedge(self, e):
59 self.edges.append(e)
60
61 def writeprops(self, f, o):
62 if len(o.props) == 0:
63 return
64
65 print('[', end=' ', file=f)
66 for p in o.props:
67 print(str(p) + '=' + str(o.props[p]), end=' ', file=f)
68 print(']', end=' ', file=f)
69
70 def write(self, f):
71 print(self.type, '{', file=f)
72
73 # Use the pass name as the graph title (at the top).
74 legend = '<font color="blue">movable</font>, <u>guard</u>, <font color="red">in worklist</font>, <font color="gray50">recovered on bailout</font>'
75 print('labelloc = t;', file=f)
76 print('labelfontsize = 30;', file=f)
77 print('label = <<b>%s - %s</b><br/>%s<br/>&nbsp;>;' % (self.func['name'], self.name, legend), file=f)
78
79 # Output graph properties.
80 for p in self.props:
81 print(' ' + str(p) + '=' + str(self.props[p]), file=f)
82 print('', file=f)
83
84 # Output node list.
85 for n in self.nodes:
86 print(' ' + n.name, end=' ', file=f)
87 self.writeprops(f, n)
88 print(';', file=f)
89 print('', file=f)
90
91 # Output edge list.
92 for e in self.edges:
93 print(' ' + e.nfrom, '->', e.nto, end=' ', file=f)
94 self.writeprops(f, e)
95 print(';', file=f)
96
97 print('}', file=f)
98
99
100 # block obj -> node string with quotations
101 def getBlockNodeName(b):
102 return blockNumToNodeName(b['number'])
103
104 # int -> node string with quotations
105 def blockNumToNodeName(i):
106 return quote('Block' + str(i))
107
108 # resumePoint obj -> HTML-formatted string
109 def getResumePointRow(rp, mode):
110 if mode != None and mode != rp['mode']:
111 return ''
112
113 # Left column: caller.
114 rpCaller = '<td align="left"></td>'
115 if 'caller' in rp:
116 rpCaller = '<td align="left">&#40;&#40;%s&#41;&#41;</td>' % str(rp['caller'])
117
118 # Middle column: ordered contents of the MResumePoint.
119 insts = ''.join('%s ' % t for t in rp['operands'])
120 rpContents = '<td align="left"><font color="grey50">resumepoint %s</font></td>' % insts
121
122 # Right column: unused.
123 rpRight = '<td></td>'
124
125 return '<tr>%s%s%s</tr>' % (rpCaller, rpContents, rpRight)
126
127 # memInputs obj -> HTML-formatted string
128 def getMemInputsRow(list):
129 if len(list) == 0:
130 return ''
131
132 # Left column: caller.
133 memLeft = '<td align="left"></td>'
134
135 # Middle column: ordered contents of the MResumePoint.
136 insts = ''.join('%s ' % str(t) for t in list)
137 memContents = '<td align="left"><font color="grey50">memory %s</font></td>' % insts
138
139 # Right column: unused.
140 memRight = '<td></td>'
141
142 return '<tr>%s%s%s</tr>' % (memLeft, memContents, memRight)
143
144 # Outputs a single row for an instruction, excluding MResumePoints.
145 # instruction -> HTML-formatted string
146 def getInstructionRow(inst):
147 # Left column: instruction ID.
148 instId = str(inst['id'])
149 instLabel = '<td align="right" port="i%s">%s</td>' % (instId, instId)
150
151 # Middle column: instruction name.
152 instName = inst['opcode'].replace('->', '→').replace('<-', '←')
153 instName = html.escape(instName)
154 if 'attributes' in inst:
155 if 'RecoveredOnBailout' in inst['attributes']:
156 instName = '<font color="gray50">%s</font>' % instName
157 elif 'Movable' in inst['attributes']:
158 instName = '<font color="blue">%s</font>' % instName
159 if 'Guard' in inst['attributes']:
160 instName = '<u>%s</u>' % instName
161 if 'InWorklist' in inst['attributes']:
162 instName = '<font color="red">%s</font>' % instName
163 instName = '<td align="left">%s</td>' % instName
164
165 # Right column: instruction MIRType.
166 instType = ''
167 if 'type' in inst and inst['type'] != "None":
168 instType = '<td align="right">%s</td>' % html.escape(inst['type'])
169
170 return '<tr>%s%s%s</tr>' % (instLabel, instName, instType)
171
172 # block obj -> HTML-formatted string
173 def getBlockLabel(b):
174 s = '<<table border="0" cellborder="0" cellpadding="1">'
175
176 if 'blockUseCount' in b:
177 blockUseCount = " (Count: %s)" % str(b['blockUseCount'])
178 else:
179 blockUseCount = ""
180
181 blockAttr = ""
182 if 'attributes' in b:
183 if 'backedge' in b['attributes']:
184 blockAttr = ' <font color="lightpink">(backedge)</font>'
185 if 'loopheader' in b['attributes']:
186 blockAttr = ' <font color="lightgreen">(loop header)</font>'
187 if 'splitedge' in b['attributes']:
188 blockAttr = " (split edge)"
189
190 blockTitle = '<font color="white">Block %s%s%s</font>' % (str(b['number']), blockUseCount, blockAttr)
191 blockTitle = '<td align="center" bgcolor="black" colspan="3">%s</td>' % blockTitle
192 s += '<tr>%s</tr>' % blockTitle
193
194 if 'resumePoint' in b:
195 s += getResumePointRow(b['resumePoint'], None)
196
197 for inst in b['instructions']:
198 if 'resumePoint' in inst:
199 s += getResumePointRow(inst['resumePoint'], 'At')
200
201 s += getInstructionRow(inst)
202
203 if 'memInputs' in inst:
204 s += getMemInputsRow(inst['memInputs'])
205
206 if 'resumePoint' in inst:
207 s += getResumePointRow(inst['resumePoint'], 'After')
208
209 s += '</table>>'
210 return s
211
212 # str -> ir obj -> ir obj -> Graph
213 # 'ir' is the IR to be used.
214 # 'mir' is always the MIR.
215 # This is because the LIR graph does not contain successor information.
216 def buildGraphForIR(name, func, ir, mir):
217 if len(ir['blocks']) == 0:
218 return None
219
220 g = Graph(name, func, 'digraph')
221 g.addprops({'rankdir':'TB', 'splines':'true'})
222
223 for i in range(0, len(ir['blocks'])):
224 bactive = ir['blocks'][i] # Used for block contents.
225 b = mir['blocks'][i] # Used for drawing blocks and edges.
226
227 node = Node(getBlockNodeName(bactive))
228 node.addprops({'shape':'box', 'label':getBlockLabel(bactive)})
229
230 if 'backedge' in b['attributes']:
231 node.addprops({'color':'crimson'})
232 if 'loopheader' in b['attributes']:
233 node.addprops({'color':'limegreen'})
234 if 'splitedge' in b['attributes']:
235 node.addprops({'style':'dashed'})
236
237 g.addnode(node)
238
239 for succ in b['successors']: # which are integers
240 edge = Edge(getBlockNodeName(bactive), blockNumToNodeName(succ))
241
242 if len(b['successors']) == 2:
243 if succ == b['successors'][0]:
244 edge.addprops({'label':'1'})
245 else:
246 edge.addprops({'label':'0'})
247
248 g.addedge(edge)
249
250 return g
251
252 # pass obj -> output file -> (Graph OR None, Graph OR None)
253 # The return value is (MIR, LIR); either one may be absent.
254 def buildGraphsForPass(p, func):
255 name = p['name']
256 mir = p['mir']
257 lir = p['lir']
258 return (buildGraphForIR(name, func, mir, mir), buildGraphForIR(name, func, lir, mir))
259
260 # function obj -> (Graph OR None, Graph OR None) list
261 # First entry in each tuple corresponds to MIR; second, to LIR.
262 def buildGraphs(func):
263 graphstup = []
264 for p in func['passes']:
265 gtup = buildGraphsForPass(p, func)
266 graphstup.append(gtup)
267 return graphstup
268
269 # function obj -> (Graph OR None, Graph OR None) list
270 # Only builds the final pass.
271 def buildOnlyFinalPass(func):
272 if len(func['passes']) == 0:
273 return [None, None]
274 p = func['passes'][-1]
275 return [buildGraphsForPass(p, func)]
276
277 # Write out a graph, constructing a nice filename.
278 # function id -> pass id -> IR string -> Graph -> void
279 def outputPass(dir, fnum, pnum, irname, g):
280 funcid = str(fnum).zfill(2)
281 passid = str(pnum).zfill(2)
282
283 filename = os.path.join(dir, 'func%s-pass%s-%s-%s.gv' % (funcid, passid, g.name, str(irname)))
284 with open(filename, 'w') as fd:
285 g.write(fd)
286
287 # Add in closing } and ] braces to close a JSON file in case of error.
288 def parenthesize(s):
289 stack = []
290 inString = False
291
292 for c in s:
293 if c == '"': # Doesn't handle escaped strings.
294 inString = not inString
295
296 if not inString:
297 if c == '{' or c == '[':
298 stack.append(c)
299 elif c == '}' or c == ']':
300 stack.pop()
301
302 while stack:
303 c = stack.pop()
304 if c == '{': s += '}'
305 elif c == '[': s += ']'
306
307 return s
308
309
310 def genfiles(format, indir, outdir):
311 gvs = glob.glob(os.path.join(indir, '*.gv'))
312 gvs.sort()
313 for gv in gvs:
314 with open(os.path.join(outdir, '%s.%s' % (os.path.basename(gv), format)), 'w') as outfile:
315 sys.stderr.write(' writing %s\n' % (outfile.name))
316 subprocess.run(['dot', gv, '-T%s' % (format)], stdout=outfile, check=True)
317
318
319 def gengvs(indir, outdir):
320 gvs = glob.glob(os.path.join(indir, '*.gv'))
321 gvs.sort()
322 for gv in gvs:
323 sys.stderr.write(' writing %s\n' % (os.path.basename(gv)))
324 shutil.copy(gv, outdir)
325
326
327 def genmergedpdfs(indir, outdir):
328 gvs = glob.glob(os.path.join(indir, '*.gv'))
329 gvs.sort()
330 for gv in gvs:
331 with open(os.path.join(indir, '%s.pdf' % (os.path.basename(gv))), 'w') as outfile:
332 sys.stderr.write(' writing pdf %s\n' % (outfile.name))
333 subprocess.run(['dot', gv, '-Tpdf'], stdout=outfile, check=True)
334
335 sys.stderr.write('combining pdfs...\n')
336 which = (shutil.which('pdftk') and 'pdftk') or (shutil.which('qpdf') and 'qpdf')
337 prefixes = [os.path.basename(x) for x in glob.glob(os.path.join(indir, 'func*.pdf'))]
338 prefixes = [re.match(r'func[^-]*', x).group(0) for x in prefixes]
339 prefixes = list(set(prefixes))
340 prefixes.sort()
341 for prefix in prefixes:
342 pages = glob.glob(os.path.join(indir, '%s-*.pdf' % (prefix)))
343 pages.sort()
344 outfile = os.path.join(outdir, '%s.pdf' % (prefix))
345 sys.stderr.write(' writing pdf %s\n' % (outfile))
346 if which == 'pdftk':
347 subprocess.run(['pdftk', *pages, 'cat', 'output', outfile], check=True)
348 elif which == 'qpdf':
349 subprocess.run(['qpdf', '--empty', '--pages', *pages, '--', outfile], check=True)
350 else:
351 raise Exception("unknown pdf program")
352
353
354 def parsenums(numstr):
355 if numstr is None:
356 return None
357 return [int(x) for x in numstr.split(',')]
358
359
360 def parsenames(namestr):
361 return namestr and namestr.split(',')
362
363
364 def validate(args):
365 if not shutil.which('dot'):
366 sys.stderr.write("ERROR: graphviz (dot) is not installed\n")
367 exit(1)
368 if args.format == 'pdf':
369 if not (shutil.which('pdftk') or shutil.which('qpdf')):
370 sys.stderr.write("ERROR: either pdftk or qpdf must be installed in order to combine the generated PDFs.\n")
371 sys.stderr.write("If you don't care and just want individual PDFs, use `--format pdfs`.\n")
372 exit(1)
373 if not os.path.isdir(args.outdir):
374 sys.stderr.write("ERROR: could not find a directory at %s\n" % (args.outdir))
375 exit(1)
376
377
378 def gen(args):
379 validate(args)
380
381 with open(args.input, 'r') as fd:
382 s = fd.read()
383
384 sys.stderr.write("loading %s...\n" % (args.input))
385 ion = json.loads(parenthesize(s))
386
387 sys.stderr.write("generating graphviz...\n")
388
389 funcnums = parsenums(args.funcnum)
390 funcnames = parsenames(args.funcname)
391 passnums = parsenums(args.passnum)
392 with tempfile.TemporaryDirectory() as tmpdir:
393 for i in range(0, len(ion['functions'])):
394 func = ion['functions'][i]
395
396 if funcnums and i not in funcnums:
397 continue
398 if funcnames and func['name'] not in funcnames:
399 continue
400
401 gtl = buildOnlyFinalPass(func) if args.final else buildGraphs(func)
402
403 if len(gtl) == 0:
404 sys.stderr.write(" function %d (%s): abort during SSA construction.\n" % (i, func['name']))
405 else:
406 sys.stderr.write(" function %d (%s): success; %d passes.\n" % (i, func['name'], len(gtl)))
407
408 for j in range(0, len(gtl)):
409 gt = gtl[j]
410 if gt == None:
411 continue
412
413 mir = gt[0]
414 lir = gt[1]
415
416 if passnums and j in passnums:
417 if lir != None and args.out_lir:
418 lir.write(args.out_lir)
419 if mir != None and args.out_mir:
420 mir.write(args.out_mir)
421 if args.out_lir and args.out_mir:
422 break
423 elif passnums:
424 continue
425
426 # If only the final pass is requested, output both MIR and LIR.
427 if args.final:
428 if lir != None:
429 outputPass(tmpdir, i, j, 'lir', lir)
430 if mir != None:
431 outputPass(tmpdir, i, j, 'mir', mir)
432 continue
433
434 # Normally, only output one of (MIR, LIR), preferring LIR.
435 if lir != None:
436 outputPass(tmpdir, i, j, 'lir', lir)
437 elif mir != None:
438 outputPass(tmpdir, i, j, 'mir', mir)
439
440 if args.format == 'pdf':
441 sys.stderr.write("generating pdfs...\n")
442 genmergedpdfs(tmpdir, args.outdir)
443 elif args.format == 'gv':
444 sys.stderr.write("copying gvs...\n")
445 gengvs(tmpdir, args.outdir)
446 else:
447 format = 'pdf' if args.format == 'pdfs' else args.format
448 sys.stderr.write("generating %ss...\n" % (format))
449 genfiles(format, tmpdir, args.outdir)
450
451
452 def js_and_gen(args):
453 validate(args)
454
455 jsargs = args.remaining[1:]
456 jsenv = os.environ.copy()
457 flags = (jsenv['IONFLAGS'] if 'IONFLAGS' in jsenv else 'logs').split(',')
458 if 'logs' not in flags:
459 flags.append('logs')
460 jsenv['IONFLAGS'] = ','.join(flags)
461 subprocess.run([args.jspath or 'js', *jsargs], env=jsenv, check=True)
462
463 args.input = '/tmp/ion.json'
464 gen(args)
465
466
467 def jittest_and_gen(args):
468 validate(args)
469
470 testargs = args.remaining[1:]
471 testenv = os.environ.copy()
472 flags = (testenv['IONFLAGS'] if 'IONFLAGS' in testenv else 'logs').split(',')
473 if 'logs' not in flags:
474 flags.append('logs')
475 testenv['IONFLAGS'] = ','.join(flags)
476 jittest_path = os.path.join("js", "src", "jit-test", "jit_test.py")
477 cmd = " ".join([sys.executable, jittest_path, shutil.which("js"), "--one", *testargs])
478 print("Command:", cmd)
479 subprocess.run(cmd, env=testenv, shell=True, check=True)
480
481 args.input = '/tmp/ion.json'
482 gen(args)
483
484
485 def add_main_arguments(parser):
486 parser.add_argument('-o', '--outdir', help='The directory in which to store the output file(s).',
487 default='.')
488 parser.add_argument('-f', '--funcnum', help='Only operate on the specified function(s), by index. Multiple functions can be separated by commas, e.g. `1,5,234`.')
489 parser.add_argument('-n', '--funcname', help='Only operate on the specified function(s), by name. Multiple functions can be separated by commas, e.g. `foo,bar,baz`.')
490 parser.add_argument('-p', '--passnum', help='Only operate on the specified pass(es), by index. Multiple passes can be separated by commas, e.g. `1,5,234`.')
491 parser.add_argument('--format', help='The output file format (pdf by default). `pdf` will merge all the graphs for each function into a single PDF; all other formats will produce a single file per graph.',
492 choices=['gv', 'pdf', 'pdfs', 'png', 'svg'], default='pdf')
493 parser.add_argument('--final', help='Only generate the final optimized MIR/LIR graphs.',
494 action='store_true')
495 parser.add_argument('--out-mir', help='Select the file where the MIR output would be written to.',
496 type=argparse.FileType('w'))
497 parser.add_argument('--out-lir', help='Select the file where the LIR output would be written to.',
498 type=argparse.FileType('w'))
499
500
501 def main():
502 parser = argparse.ArgumentParser(description='Visualize Ion graphs using GraphViz.')
503 subparsers = parser.add_subparsers()
504 js = subparsers.add_parser('js', formatter_class=argparse.RawDescriptionHelpFormatter,
505 help='Subcommand: Run js and iongraph together in one call.',
506 description='Run js and iongraph together in one call. Arguments before the -- separator are for iongraph, while arguments after the -- will be passed to js.\n\nexample:\n iongraph js --funcnum 1 -- -m mymodule.mjs')
507 jittest = subparsers.add_parser('jit-test', formatter_class=argparse.RawDescriptionHelpFormatter,
508 help='Subcommand: Run jit-test and iongraph together in one call.',
509 description='Run jit-test and iongraph together in one call. Arguments before the -- separator are for iongraph, while arguments after the -- will be passed to jit-test.\n\nexample:\n iongraph jit-test --funcnum 1 -- category/test.js')
510
511 add_main_arguments(parser)
512 parser.add_argument('input', help='The JSON log file generated by IonMonkey. (Default: /tmp/ion.json)',
513 nargs='?', default='/tmp/ion.json')
514 parser.set_defaults(func=gen)
515
516 js.add_argument('--jspath', help='The path to the js executable.')
517 add_main_arguments(js)
518 js.add_argument('remaining', nargs=argparse.REMAINDER)
519 js.set_defaults(func=js_and_gen)
520
521 add_main_arguments(jittest)
522 jittest.add_argument('remaining', nargs=argparse.REMAINDER)
523 jittest.set_defaults(func=jittest_and_gen)
524
525 args = parser.parse_args()
526 args.func(args)
527
528
529 if __name__ == '__main__':
530 main()