Debian Codegraph @

go/ir/html.go

raw
1 // Copyright 2015 The Go Authors. All rights reserved.
2 // Copyright 2019 Dominik Honnef. All rights reserved.
3
4 package ir
5
6 import (
7 "bytes"
8 "fmt"
9 "go/types"
10 "html"
11 "io"
12 "log"
13 "os"
14 "os/exec"
15 "path/filepath"
16 "reflect"
17 "sort"
18 "strings"
19 )
20
21 func live(f *Function) []bool {
22 max := 0
23 var ops []*Value
24
25 for _, b := range f.Blocks {
26 for _, instr := range b.Instrs {
27 if int(instr.ID()) > max {
28 max = int(instr.ID())
29 }
30 }
31 }
32
33 out := make([]bool, max+1)
34 var q []Node
35 for _, b := range f.Blocks {
36 for _, instr := range b.Instrs {
37 switch instr.(type) {
38 case *BlankStore, *Call, *ConstantSwitch, *Defer, *Go, *If, *Jump, *MapUpdate, *Next, *Panic, *Recv, *Return, *RunDefers, *Send, *Store, *Unreachable:
39 out[instr.ID()] = true
40 q = append(q, instr)
41 }
42 }
43 }
44
45 for len(q) > 0 {
46 v := q[len(q)-1]
47 q = q[:len(q)-1]
48 for _, op := range v.Operands(ops) {
49 if *op == nil {
50 continue
51 }
52 if !out[(*op).ID()] {
53 out[(*op).ID()] = true
54 q = append(q, *op)
55 }
56 }
57 }
58
59 return out
60 }
61
62 type funcPrinter interface {
63 startBlock(b *BasicBlock, reachable bool)
64 endBlock(b *BasicBlock)
65 value(v Node, live bool)
66 startDepCycle()
67 endDepCycle()
68 named(n string, vals []Value)
69 }
70
71 func namedValues(f *Function) map[types.Object][]Value {
72 names := map[types.Object][]Value{}
73 for _, b := range f.Blocks {
74 for _, instr := range b.Instrs {
75 if instr, ok := instr.(*DebugRef); ok {
76 if obj := instr.object; obj != nil {
77 names[obj] = append(names[obj], instr.X)
78 }
79 }
80 }
81 }
82 // XXX deduplicate values
83 return names
84 }
85
86 func fprintFunc(p funcPrinter, f *Function) {
87 // XXX does our IR form preserve unreachable blocks?
88 // reachable, live := findlive(f)
89
90 l := live(f)
91 for _, b := range f.Blocks {
92 // XXX
93 // p.startBlock(b, reachable[b.Index])
94 p.startBlock(b, true)
95
96 end := max(len(b.Instrs)-1, 0)
97 for _, v := range b.Instrs[:end] {
98 if _, ok := v.(*DebugRef); !ok {
99 p.value(v, l[v.ID()])
100 }
101 }
102 p.endBlock(b)
103 }
104
105 names := namedValues(f)
106 keys := make([]types.Object, 0, len(names))
107 for key := range names {
108 keys = append(keys, key)
109 }
110 sort.Slice(keys, func(i, j int) bool {
111 return keys[i].Pos() < keys[j].Pos()
112 })
113 for _, key := range keys {
114 p.named(key.Name(), names[key])
115 }
116 }
117
118 func opName(v Node) string {
119 switch v := v.(type) {
120 case *Call:
121 if v.Common().IsInvoke() {
122 return "Invoke"
123 }
124 return "Call"
125 case *Alloc:
126 if v.Heap {
127 return "HeapAlloc"
128 }
129 return "StackAlloc"
130 case *Select:
131 if v.Blocking {
132 return "SelectBlocking"
133 }
134 return "SelectNonBlocking"
135 default:
136 return reflect.ValueOf(v).Type().Elem().Name()
137 }
138 }
139
140 type HTMLWriter struct {
141 w io.WriteCloser
142 path string
143 dot *dotWriter
144 }
145
146 func NewHTMLWriter(path string, funcname, cfgMask string) *HTMLWriter {
147 out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
148 if err != nil {
149 log.Fatalf("%v", err)
150 }
151 pwd, err := os.Getwd()
152 if err != nil {
153 log.Fatalf("%v", err)
154 }
155 html := HTMLWriter{w: out, path: filepath.Join(pwd, path)}
156 html.dot = newDotWriter()
157 html.start(funcname)
158 return &html
159 }
160
161 func (w *HTMLWriter) start(name string) {
162 if w == nil {
163 return
164 }
165 w.WriteString("<html>")
166 w.WriteString(`<head>
167 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
168 <style>
169
170 body {
171 font-size: 14px;
172 font-family: Arial, sans-serif;
173 }
174
175 h1 {
176 font-size: 18px;
177 display: inline-block;
178 margin: 0 1em .5em 0;
179 }
180
181 #helplink {
182 display: inline-block;
183 }
184
185 #help {
186 display: none;
187 }
188
189 .stats {
190 font-size: 60%;
191 }
192
193 table {
194 border: 1px solid black;
195 table-layout: fixed;
196 width: 300px;
197 }
198
199 th, td {
200 border: 1px solid black;
201 overflow: hidden;
202 width: 400px;
203 vertical-align: top;
204 padding: 5px;
205 }
206
207 td > h2 {
208 cursor: pointer;
209 font-size: 120%;
210 }
211
212 td.collapsed {
213 font-size: 12px;
214 width: 12px;
215 border: 0px;
216 padding: 0;
217 cursor: pointer;
218 background: #fafafa;
219 }
220
221 td.collapsed div {
222 -moz-transform: rotate(-90.0deg); /* FF3.5+ */
223 -o-transform: rotate(-90.0deg); /* Opera 10.5 */
224 -webkit-transform: rotate(-90.0deg); /* Saf3.1+, Chrome */
225 filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083); /* IE6,IE7 */
226 -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)"; /* IE8 */
227 margin-top: 10.3em;
228 margin-left: -10em;
229 margin-right: -10em;
230 text-align: right;
231 }
232
233 code, pre, .lines, .ast {
234 font-family: Menlo, monospace;
235 font-size: 12px;
236 }
237
238 pre {
239 -moz-tab-size: 4;
240 -o-tab-size: 4;
241 tab-size: 4;
242 }
243
244 .allow-x-scroll {
245 overflow-x: scroll;
246 }
247
248 .lines {
249 float: left;
250 overflow: hidden;
251 text-align: right;
252 }
253
254 .lines div {
255 padding-right: 10px;
256 color: gray;
257 }
258
259 div.line-number {
260 font-size: 12px;
261 }
262
263 .ast {
264 white-space: nowrap;
265 }
266
267 td.ssa-prog {
268 width: 600px;
269 word-wrap: break-word;
270 }
271
272 li {
273 list-style-type: none;
274 }
275
276 li.ssa-long-value {
277 text-indent: -2em; /* indent wrapped lines */
278 }
279
280 li.ssa-value-list {
281 display: inline;
282 }
283
284 li.ssa-start-block {
285 padding: 0;
286 margin: 0;
287 }
288
289 li.ssa-end-block {
290 padding: 0;
291 margin: 0;
292 }
293
294 ul.ssa-print-func {
295 padding-left: 0;
296 }
297
298 li.ssa-start-block button {
299 padding: 0 1em;
300 margin: 0;
301 border: none;
302 display: inline;
303 font-size: 14px;
304 float: right;
305 }
306
307 button:hover {
308 background-color: #eee;
309 cursor: pointer;
310 }
311
312 dl.ssa-gen {
313 padding-left: 0;
314 }
315
316 dt.ssa-prog-src {
317 padding: 0;
318 margin: 0;
319 float: left;
320 width: 4em;
321 }
322
323 dd.ssa-prog {
324 padding: 0;
325 margin-right: 0;
326 margin-left: 4em;
327 }
328
329 .dead-value {
330 color: gray;
331 }
332
333 .dead-block {
334 opacity: 0.5;
335 }
336
337 .depcycle {
338 font-style: italic;
339 }
340
341 .line-number {
342 font-size: 11px;
343 }
344
345 .no-line-number {
346 font-size: 11px;
347 color: gray;
348 }
349
350 .zoom {
351 position: absolute;
352 float: left;
353 white-space: nowrap;
354 background-color: #eee;
355 }
356
357 .zoom a:link, .zoom a:visited {
358 text-decoration: none;
359 color: blue;
360 font-size: 16px;
361 padding: 4px 2px;
362 }
363
364 svg {
365 cursor: default;
366 outline: 1px solid #eee;
367 }
368
369 .highlight-aquamarine { background-color: aquamarine; }
370 .highlight-coral { background-color: coral; }
371 .highlight-lightpink { background-color: lightpink; }
372 .highlight-lightsteelblue { background-color: lightsteelblue; }
373 .highlight-palegreen { background-color: palegreen; }
374 .highlight-skyblue { background-color: skyblue; }
375 .highlight-lightgray { background-color: lightgray; }
376 .highlight-yellow { background-color: yellow; }
377 .highlight-lime { background-color: lime; }
378 .highlight-khaki { background-color: khaki; }
379 .highlight-aqua { background-color: aqua; }
380 .highlight-salmon { background-color: salmon; }
381
382 .outline-blue { outline: blue solid 2px; }
383 .outline-red { outline: red solid 2px; }
384 .outline-blueviolet { outline: blueviolet solid 2px; }
385 .outline-darkolivegreen { outline: darkolivegreen solid 2px; }
386 .outline-fuchsia { outline: fuchsia solid 2px; }
387 .outline-sienna { outline: sienna solid 2px; }
388 .outline-gold { outline: gold solid 2px; }
389 .outline-orangered { outline: orangered solid 2px; }
390 .outline-teal { outline: teal solid 2px; }
391 .outline-maroon { outline: maroon solid 2px; }
392 .outline-black { outline: black solid 2px; }
393
394 ellipse.outline-blue { stroke-width: 2px; stroke: blue; }
395 ellipse.outline-red { stroke-width: 2px; stroke: red; }
396 ellipse.outline-blueviolet { stroke-width: 2px; stroke: blueviolet; }
397 ellipse.outline-darkolivegreen { stroke-width: 2px; stroke: darkolivegreen; }
398 ellipse.outline-fuchsia { stroke-width: 2px; stroke: fuchsia; }
399 ellipse.outline-sienna { stroke-width: 2px; stroke: sienna; }
400 ellipse.outline-gold { stroke-width: 2px; stroke: gold; }
401 ellipse.outline-orangered { stroke-width: 2px; stroke: orangered; }
402 ellipse.outline-teal { stroke-width: 2px; stroke: teal; }
403 ellipse.outline-maroon { stroke-width: 2px; stroke: maroon; }
404 ellipse.outline-black { stroke-width: 2px; stroke: black; }
405
406 </style>
407
408 <script type="text/javascript">
409 // ordered list of all available highlight colors
410 var highlights = [
411 "highlight-aquamarine",
412 "highlight-coral",
413 "highlight-lightpink",
414 "highlight-lightsteelblue",
415 "highlight-palegreen",
416 "highlight-skyblue",
417 "highlight-lightgray",
418 "highlight-yellow",
419 "highlight-lime",
420 "highlight-khaki",
421 "highlight-aqua",
422 "highlight-salmon"
423 ];
424
425 // state: which value is highlighted this color?
426 var highlighted = {};
427 for (var i = 0; i < highlights.length; i++) {
428 highlighted[highlights[i]] = "";
429 }
430
431 // ordered list of all available outline colors
432 var outlines = [
433 "outline-blue",
434 "outline-red",
435 "outline-blueviolet",
436 "outline-darkolivegreen",
437 "outline-fuchsia",
438 "outline-sienna",
439 "outline-gold",
440 "outline-orangered",
441 "outline-teal",
442 "outline-maroon",
443 "outline-black"
444 ];
445
446 // state: which value is outlined this color?
447 var outlined = {};
448 for (var i = 0; i < outlines.length; i++) {
449 outlined[outlines[i]] = "";
450 }
451
452 window.onload = function() {
453 var ssaElemClicked = function(elem, event, selections, selected) {
454 event.stopPropagation();
455
456 // TODO: pushState with updated state and read it on page load,
457 // so that state can survive across reloads
458
459 // find all values with the same name
460 var c = elem.classList.item(0);
461 var x = document.getElementsByClassName(c);
462
463 // if selected, remove selections from all of them
464 // otherwise, attempt to add
465
466 var remove = "";
467 for (var i = 0; i < selections.length; i++) {
468 var color = selections[i];
469 if (selected[color] == c) {
470 remove = color;
471 break;
472 }
473 }
474
475 if (remove != "") {
476 for (var i = 0; i < x.length; i++) {
477 x[i].classList.remove(remove);
478 }
479 selected[remove] = "";
480 return;
481 }
482
483 // we're adding a selection
484 // find first available color
485 var avail = "";
486 for (var i = 0; i < selections.length; i++) {
487 var color = selections[i];
488 if (selected[color] == "") {
489 avail = color;
490 break;
491 }
492 }
493 if (avail == "") {
494 alert("out of selection colors; go add more");
495 return;
496 }
497
498 // set that as the selection
499 for (var i = 0; i < x.length; i++) {
500 x[i].classList.add(avail);
501 }
502 selected[avail] = c;
503 };
504
505 var ssaValueClicked = function(event) {
506 ssaElemClicked(this, event, highlights, highlighted);
507 };
508
509 var ssaBlockClicked = function(event) {
510 ssaElemClicked(this, event, outlines, outlined);
511 };
512
513 var ssavalues = document.getElementsByClassName("ssa-value");
514 for (var i = 0; i < ssavalues.length; i++) {
515 ssavalues[i].addEventListener('click', ssaValueClicked);
516 }
517
518 var ssalongvalues = document.getElementsByClassName("ssa-long-value");
519 for (var i = 0; i < ssalongvalues.length; i++) {
520 // don't attach listeners to li nodes, just the spans they contain
521 if (ssalongvalues[i].nodeName == "SPAN") {
522 ssalongvalues[i].addEventListener('click', ssaValueClicked);
523 }
524 }
525
526 var ssablocks = document.getElementsByClassName("ssa-block");
527 for (var i = 0; i < ssablocks.length; i++) {
528 ssablocks[i].addEventListener('click', ssaBlockClicked);
529 }
530
531 var lines = document.getElementsByClassName("line-number");
532 for (var i = 0; i < lines.length; i++) {
533 lines[i].addEventListener('click', ssaValueClicked);
534 }
535
536 // Contains phase names which are expanded by default. Other columns are collapsed.
537 var expandedDefault = [
538 "start",
539 "deadcode",
540 "opt",
541 "lower",
542 "late deadcode",
543 "regalloc",
544 "genssa",
545 ];
546
547 function toggler(phase) {
548 return function() {
549 toggle_cell(phase+'-col');
550 toggle_cell(phase+'-exp');
551 };
552 }
553
554 function toggle_cell(id) {
555 var e = document.getElementById(id);
556 if (e.style.display == 'table-cell') {
557 e.style.display = 'none';
558 } else {
559 e.style.display = 'table-cell';
560 }
561 }
562
563 // Go through all columns and collapse needed phases.
564 var td = document.getElementsByTagName("td");
565 for (var i = 0; i < td.length; i++) {
566 var id = td[i].id;
567 var phase = id.substr(0, id.length-4);
568 var show = expandedDefault.indexOf(phase) !== -1
569 if (id.endsWith("-exp")) {
570 var h2 = td[i].getElementsByTagName("h2");
571 if (h2 && h2[0]) {
572 h2[0].addEventListener('click', toggler(phase));
573 }
574 } else {
575 td[i].addEventListener('click', toggler(phase));
576 }
577 if (id.endsWith("-col") && show || id.endsWith("-exp") && !show) {
578 td[i].style.display = 'none';
579 continue;
580 }
581 td[i].style.display = 'table-cell';
582 }
583
584 // find all svg block nodes, add their block classes
585 var nodes = document.querySelectorAll('*[id^="graph_node_"]');
586 for (var i = 0; i < nodes.length; i++) {
587 var node = nodes[i];
588 var name = node.id.toString();
589 var block = name.substring(name.lastIndexOf("_")+1);
590 node.classList.remove("node");
591 node.classList.add(block);
592 node.addEventListener('click', ssaBlockClicked);
593 var ellipse = node.getElementsByTagName('ellipse')[0];
594 ellipse.classList.add(block);
595 ellipse.addEventListener('click', ssaBlockClicked);
596 }
597
598 // make big graphs smaller
599 var targetScale = 0.5;
600 var nodes = document.querySelectorAll('*[id^="svg_graph_"]');
601 // TODO: Implement smarter auto-zoom using the viewBox attribute
602 // and in case of big graphs set the width and height of the svg graph to
603 // maximum allowed.
604 for (var i = 0; i < nodes.length; i++) {
605 var node = nodes[i];
606 var name = node.id.toString();
607 var phase = name.substring(name.lastIndexOf("_")+1);
608 var gNode = document.getElementById("g_graph_"+phase);
609 var scale = gNode.transform.baseVal.getItem(0).matrix.a;
610 if (scale > targetScale) {
611 node.width.baseVal.value *= targetScale / scale;
612 node.height.baseVal.value *= targetScale / scale;
613 }
614 }
615 };
616
617 function toggle_visibility(id) {
618 var e = document.getElementById(id);
619 if (e.style.display == 'block') {
620 e.style.display = 'none';
621 } else {
622 e.style.display = 'block';
623 }
624 }
625
626 function hideBlock(el) {
627 var es = el.parentNode.parentNode.getElementsByClassName("ssa-value-list");
628 if (es.length===0)
629 return;
630 var e = es[0];
631 if (e.style.display === 'block' || e.style.display === '') {
632 e.style.display = 'none';
633 el.innerHTML = '+';
634 } else {
635 e.style.display = 'block';
636 el.innerHTML = '-';
637 }
638 }
639
640 // TODO: scale the graph with the viewBox attribute.
641 function graphReduce(id) {
642 var node = document.getElementById(id);
643 if (node) {
644 node.width.baseVal.value *= 0.9;
645 node.height.baseVal.value *= 0.9;
646 }
647 return false;
648 }
649
650 function graphEnlarge(id) {
651 var node = document.getElementById(id);
652 if (node) {
653 node.width.baseVal.value *= 1.1;
654 node.height.baseVal.value *= 1.1;
655 }
656 return false;
657 }
658
659 function makeDraggable(event) {
660 var svg = event.target;
661 if (window.PointerEvent) {
662 svg.addEventListener('pointerdown', startDrag);
663 svg.addEventListener('pointermove', drag);
664 svg.addEventListener('pointerup', endDrag);
665 svg.addEventListener('pointerleave', endDrag);
666 } else {
667 svg.addEventListener('mousedown', startDrag);
668 svg.addEventListener('mousemove', drag);
669 svg.addEventListener('mouseup', endDrag);
670 svg.addEventListener('mouseleave', endDrag);
671 }
672
673 var point = svg.createSVGPoint();
674 var isPointerDown = false;
675 var pointerOrigin;
676 var viewBox = svg.viewBox.baseVal;
677
678 function getPointFromEvent (event) {
679 point.x = event.clientX;
680 point.y = event.clientY;
681
682 // We get the current transformation matrix of the SVG and we inverse it
683 var invertedSVGMatrix = svg.getScreenCTM().inverse();
684 return point.matrixTransform(invertedSVGMatrix);
685 }
686
687 function startDrag(event) {
688 isPointerDown = true;
689 pointerOrigin = getPointFromEvent(event);
690 }
691
692 function drag(event) {
693 if (!isPointerDown) {
694 return;
695 }
696 event.preventDefault();
697
698 var pointerPosition = getPointFromEvent(event);
699 viewBox.x -= (pointerPosition.x - pointerOrigin.x);
700 viewBox.y -= (pointerPosition.y - pointerOrigin.y);
701 }
702
703 function endDrag(event) {
704 isPointerDown = false;
705 }
706 }</script>
707
708 </head>`)
709 w.WriteString("<body>")
710 w.WriteString("<h1>")
711 w.WriteString(html.EscapeString(name))
712 w.WriteString("</h1>")
713 w.WriteString(`
714 <a href="#" onclick="toggle_visibility('help');return false;" id="helplink">help</a>
715 <div id="help">
716
717 <p>
718 Click on a value or block to toggle highlighting of that value/block
719 and its uses. (Values and blocks are highlighted by ID, and IDs of
720 dead items may be reused, so not all highlights necessarily correspond
721 to the clicked item.)
722 </p>
723
724 <p>
725 Faded out values and blocks are dead code that has not been eliminated.
726 </p>
727
728 <p>
729 Values printed in italics have a dependency cycle.
730 </p>
731
732 <p>
733 <b>CFG</b>: Dashed edge is for unlikely branches. Blue color is for backward edges.
734 Edge with a dot means that this edge follows the order in which blocks were laid out.
735 </p>
736
737 </div>
738 `)
739 w.WriteString("<table>")
740 w.WriteString("<tr>")
741 }
742
743 func (w *HTMLWriter) Close() {
744 if w == nil {
745 return
746 }
747 io.WriteString(w.w, "</tr>")
748 io.WriteString(w.w, "</table>")
749 io.WriteString(w.w, "</body>")
750 io.WriteString(w.w, "</html>")
751 w.w.Close()
752 fmt.Printf("dumped IR to %v\n", w.path)
753 }
754
755 // WriteFunc writes f in a column headed by title.
756 // phase is used for collapsing columns and should be unique across the table.
757 func (w *HTMLWriter) WriteFunc(phase, title string, f *Function) {
758 if w == nil {
759 return
760 }
761 w.WriteColumn(phase, title, "", funcHTML(f, phase, w.dot))
762 }
763
764 // WriteColumn writes raw HTML in a column headed by title.
765 // It is intended for pre- and post-compilation log output.
766 func (w *HTMLWriter) WriteColumn(phase, title, class, html string) {
767 if w == nil {
768 return
769 }
770 id := strings.Replace(phase, " ", "-", -1)
771 // collapsed column
772 w.Printf("<td id=\"%v-col\" class=\"collapsed\"><div>%v</div></td>", id, phase)
773
774 if class == "" {
775 w.Printf("<td id=\"%v-exp\">", id)
776 } else {
777 w.Printf("<td id=\"%v-exp\" class=\"%v\">", id, class)
778 }
779 w.WriteString("<h2>" + title + "</h2>")
780 w.WriteString(html)
781 w.WriteString("</td>")
782 }
783
784 func (w *HTMLWriter) Printf(msg string, v ...any) {
785 if _, err := fmt.Fprintf(w.w, msg, v...); err != nil {
786 log.Fatalf("%v", err)
787 }
788 }
789
790 func (w *HTMLWriter) WriteString(s string) {
791 if _, err := io.WriteString(w.w, s); err != nil {
792 log.Fatalf("%v", err)
793 }
794 }
795
796 func valueHTML(v Node) string {
797 if v == nil {
798 return "&lt;nil&gt;"
799 }
800 // TODO: Using the value ID as the class ignores the fact
801 // that value IDs get recycled and that some values
802 // are transmuted into other values.
803 class := fmt.Sprintf("t%d", v.ID())
804 var label string
805 switch v := v.(type) {
806 case *Function:
807 label = v.RelString(nil)
808 case *Builtin:
809 label = v.Name()
810 default:
811 label = class
812 }
813 return fmt.Sprintf("<span class=\"%s ssa-value\">%s</span>", class, label)
814 }
815
816 func valueLongHTML(v Node) string {
817 // TODO: Any intra-value formatting?
818 // I'm wary of adding too much visual noise,
819 // but a little bit might be valuable.
820 // We already have visual noise in the form of punctuation
821 // maybe we could replace some of that with formatting.
822 var s strings.Builder
823 s.WriteString(fmt.Sprintf("<span class=\"t%d ssa-long-value\">", v.ID()))
824
825 linenumber := "<span class=\"no-line-number\">(?)</span>"
826 if v.Pos().IsValid() {
827 line := v.Parent().Prog.Fset.Position(v.Pos()).Line
828 linenumber = fmt.Sprintf("<span class=\"l%v line-number\">(%d)</span>", line, line)
829 }
830
831 s.WriteString(fmt.Sprintf("%s %s = %s", valueHTML(v), linenumber, opName(v)))
832
833 if v, ok := v.(Value); ok {
834 s.WriteString(" &lt;" + html.EscapeString(v.Type().String()) + "&gt;")
835 }
836
837 switch v := v.(type) {
838 case *Parameter:
839 s.WriteString(fmt.Sprintf(" {%s}", html.EscapeString(v.name)))
840 case *BinOp:
841 s.WriteString(fmt.Sprintf(" {%s}", html.EscapeString(v.Op.String())))
842 case *UnOp:
843 s.WriteString(fmt.Sprintf(" {%s}", html.EscapeString(v.Op.String())))
844 case *Extract:
845 name := v.Tuple.Type().(*types.Tuple).At(v.Index).Name()
846 s.WriteString(fmt.Sprintf(" [%d] (%s)", v.Index, name))
847 case *Field:
848 st := v.X.Type().Underlying().(*types.Struct)
849 // Be robust against a bad index.
850 name := "?"
851 if 0 <= v.Field && v.Field < st.NumFields() {
852 name = st.Field(v.Field).Name()
853 }
854 s.WriteString(fmt.Sprintf(" [%d] (%s)", v.Field, name))
855 case *FieldAddr:
856 st := deref(v.X.Type()).Underlying().(*types.Struct)
857 // Be robust against a bad index.
858 name := "?"
859 if 0 <= v.Field && v.Field < st.NumFields() {
860 name = st.Field(v.Field).Name()
861 }
862
863 s.WriteString(fmt.Sprintf(" [%d] (%s)", v.Field, name))
864 case *Recv:
865 s.WriteString(fmt.Sprintf(" {%t}", v.CommaOk))
866 case *Call:
867 if v.Common().IsInvoke() {
868 s.WriteString(fmt.Sprintf(" {%s}", html.EscapeString(v.Common().Method.FullName())))
869 }
870 case *Const:
871 if v.Value == nil {
872 s.WriteString(" {&lt;nil&gt;}")
873 } else {
874 s.WriteString(fmt.Sprintf(" {%s}", html.EscapeString(v.Value.String())))
875 }
876 case *Sigma:
877 s.WriteString(fmt.Sprintf(" [#%s]", v.From))
878 }
879 for _, a := range v.Operands(nil) {
880 s.WriteString(fmt.Sprintf(" %s", valueHTML(*a)))
881 }
882 if v, ok := v.(Instruction); ok {
883 s.WriteString(fmt.Sprintf(" (%s)", v.Comment()))
884 }
885
886 // OPT(dh): we're calling namedValues many times on the same function.
887 allNames := namedValues(v.Parent())
888 var names []string
889 for name, values := range allNames {
890 for _, value := range values {
891 if v == value {
892 names = append(names, name.Name())
893 break
894 }
895 }
896 }
897 if len(names) != 0 {
898 s.WriteString(" (" + strings.Join(names, ", ") + ")")
899 }
900
901 s.WriteString("</span>")
902 return s.String()
903 }
904
905 func blockHTML(b *BasicBlock) string {
906 // TODO: Using the value ID as the class ignores the fact
907 // that value IDs get recycled and that some values
908 // are transmuted into other values.
909 s := html.EscapeString(b.String())
910 return fmt.Sprintf("<span class=\"%s ssa-block\">%s</span>", s, s)
911 }
912
913 func blockLongHTML(b *BasicBlock) string {
914 var kind string
915 var term Instruction
916 if len(b.Instrs) > 0 {
917 term = b.Control()
918 kind = opName(term)
919 }
920 // TODO: improve this for HTML?
921 var s strings.Builder
922 s.WriteString(fmt.Sprintf("<span class=\"b%d ssa-block\">%s</span>", b.Index, kind))
923
924 if term != nil {
925 ops := term.Operands(nil)
926 if len(ops) > 0 {
927 var ss []string
928 for _, op := range ops {
929 ss = append(ss, valueHTML(*op))
930 }
931 s.WriteString(" " + strings.Join(ss, ", "))
932 }
933 }
934 if len(b.Succs) > 0 {
935 s.WriteString(" &#8594;") // right arrow
936 for _, c := range b.Succs {
937 s.WriteString(" " + blockHTML(c))
938 }
939 }
940 return s.String()
941 }
942
943 func funcHTML(f *Function, phase string, dot *dotWriter) string {
944 buf := new(bytes.Buffer)
945 if dot != nil {
946 dot.writeFuncSVG(buf, phase, f)
947 }
948 fmt.Fprint(buf, "<code>")
949 p := htmlFuncPrinter{w: buf}
950 fprintFunc(p, f)
951
952 // fprintFunc(&buf, f) // TODO: HTML, not text, <br /> for line breaks, etc.
953 fmt.Fprint(buf, "</code>")
954 return buf.String()
955 }
956
957 type htmlFuncPrinter struct {
958 w io.Writer
959 }
960
961 func (p htmlFuncPrinter) startBlock(b *BasicBlock, reachable bool) {
962 var dead string
963 if !reachable {
964 dead = "dead-block"
965 }
966 fmt.Fprintf(p.w, "<ul class=\"%s ssa-print-func %s\">", b, dead)
967 fmt.Fprintf(p.w, "<li class=\"ssa-start-block\">%s:", blockHTML(b))
968 if len(b.Preds) > 0 {
969 io.WriteString(p.w, " &#8592;") // left arrow
970 for _, pred := range b.Preds {
971 fmt.Fprintf(p.w, " %s", blockHTML(pred))
972 }
973 }
974 if len(b.Instrs) > 0 {
975 io.WriteString(p.w, `<button onclick="hideBlock(this)">-</button>`)
976 }
977 io.WriteString(p.w, "</li>")
978 if len(b.Instrs) > 0 { // start list of values
979 io.WriteString(p.w, "<li class=\"ssa-value-list\">")
980 io.WriteString(p.w, "<ul>")
981 }
982 }
983
984 func (p htmlFuncPrinter) endBlock(b *BasicBlock) {
985 if len(b.Instrs) > 0 { // end list of values
986 io.WriteString(p.w, "</ul>")
987 io.WriteString(p.w, "</li>")
988 }
989 io.WriteString(p.w, "<li class=\"ssa-end-block\">")
990 fmt.Fprint(p.w, blockLongHTML(b))
991 io.WriteString(p.w, "</li>")
992 io.WriteString(p.w, "</ul>")
993 }
994
995 func (p htmlFuncPrinter) value(v Node, live bool) {
996 var dead string
997 if !live {
998 dead = "dead-value"
999 }
1000 fmt.Fprintf(p.w, "<li class=\"ssa-long-value %s\">", dead)
1001 fmt.Fprint(p.w, valueLongHTML(v))
1002 io.WriteString(p.w, "</li>")
1003 }
1004
1005 func (p htmlFuncPrinter) startDepCycle() {
1006 fmt.Fprintln(p.w, "<span class=\"depcycle\">")
1007 }
1008
1009 func (p htmlFuncPrinter) endDepCycle() {
1010 fmt.Fprintln(p.w, "</span>")
1011 }
1012
1013 func (p htmlFuncPrinter) named(n string, vals []Value) {
1014 fmt.Fprintf(p.w, "<li>name %s: ", n)
1015 for _, val := range vals {
1016 fmt.Fprintf(p.w, "%s ", valueHTML(val))
1017 }
1018 fmt.Fprintf(p.w, "</li>")
1019 }
1020
1021 type dotWriter struct {
1022 path string
1023 broken bool
1024 }
1025
1026 // newDotWriter returns non-nil value when mask is valid.
1027 // dotWriter will generate SVGs only for the phases specified in the mask.
1028 // mask can contain following patterns and combinations of them:
1029 // * - all of them;
1030 // x-y - x through y, inclusive;
1031 // x,y - x and y, but not the passes between.
1032 func newDotWriter() *dotWriter {
1033 path, err := exec.LookPath("dot")
1034 if err != nil {
1035 fmt.Println(err)
1036 return nil
1037 }
1038 return &dotWriter{path: path}
1039 }
1040
1041 func (d *dotWriter) writeFuncSVG(w io.Writer, phase string, f *Function) {
1042 if d.broken {
1043 return
1044 }
1045 cmd := exec.Command(d.path, "-Tsvg")
1046 pipe, err := cmd.StdinPipe()
1047 if err != nil {
1048 d.broken = true
1049 fmt.Println(err)
1050 return
1051 }
1052 buf := new(bytes.Buffer)
1053 cmd.Stdout = buf
1054 bufErr := new(bytes.Buffer)
1055 cmd.Stderr = bufErr
1056 err = cmd.Start()
1057 if err != nil {
1058 d.broken = true
1059 fmt.Println(err)
1060 return
1061 }
1062 fmt.Fprint(pipe, `digraph "" { margin=0; size="4,40"; ranksep=.2; `)
1063 id := strings.Replace(phase, " ", "-", -1)
1064 fmt.Fprintf(pipe, `id="g_graph_%s";`, id)
1065 fmt.Fprintf(pipe, `node [style=filled,fillcolor=white,fontsize=16,fontname="Menlo,Times,serif",margin="0.01,0.03"];`)
1066 fmt.Fprintf(pipe, `edge [fontsize=16,fontname="Menlo,Times,serif"];`)
1067 for _, b := range f.Blocks {
1068 layout := ""
1069 fmt.Fprintf(pipe, `%v [label="%v%s\n%v",id="graph_node_%v_%v"];`, b, b, layout, b.Control().String(), id, b)
1070 }
1071 indexOf := make([]int, len(f.Blocks))
1072 for i, b := range f.Blocks {
1073 indexOf[b.Index] = i
1074 }
1075
1076 // XXX
1077 /*
1078 ponums := make([]int32, len(f.Blocks))
1079 _ = postorderWithNumbering(f, ponums)
1080 isBackEdge := func(from, to int) bool {
1081 return ponums[from] <= ponums[to]
1082 }
1083 */
1084 isBackEdge := func(from, to int) bool { return false }
1085
1086 for _, b := range f.Blocks {
1087 for i, s := range b.Succs {
1088 style := "solid"
1089 color := "black"
1090 arrow := "vee"
1091 if isBackEdge(b.Index, s.Index) {
1092 color = "blue"
1093 }
1094 fmt.Fprintf(pipe, `%v -> %v [label=" %d ",style="%s",color="%s",arrowhead="%s"];`, b, s, i, style, color, arrow)
1095 }
1096 }
1097 fmt.Fprint(pipe, "}")
1098 pipe.Close()
1099 err = cmd.Wait()
1100 if err != nil {
1101 d.broken = true
1102 fmt.Printf("dot: %v\n%v\n", err, bufErr.String())
1103 return
1104 }
1105
1106 svgID := "svg_graph_" + id
1107 fmt.Fprintf(w, `<div class="zoom"><button onclick="return graphReduce('%s');">-</button> <button onclick="return graphEnlarge('%s');">+</button></div>`, svgID, svgID)
1108 // For now, an awful hack: edit the html as it passes through
1109 // our fingers, finding '<svg ' and injecting needed attributes after it.
1110 err = d.copyUntil(w, buf, `<svg `)
1111 if err != nil {
1112 fmt.Printf("injecting attributes: %v\n", err)
1113 return
1114 }
1115 fmt.Fprintf(w, ` id="%s" onload="makeDraggable(evt)" width="100%%" `, svgID)
1116 io.Copy(w, buf)
1117 }
1118
1119 func (d *dotWriter) copyUntil(w io.Writer, buf *bytes.Buffer, sep string) error {
1120 i := bytes.Index(buf.Bytes(), []byte(sep))
1121 if i == -1 {
1122 return fmt.Errorf("couldn't find dot sep %q", sep)
1123 }
1124 _, err := io.CopyN(w, buf, int64(i+len(sep)))
1125 return err
1126 }