1 // Copyright 2013 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "src/compiler/graph-visualizer.h"
10 #include "src/code-stubs.h"
11 #include "src/compiler/all-nodes.h"
12 #include "src/compiler/graph.h"
13 #include "src/compiler/node.h"
14 #include "src/compiler/node-properties.h"
15 #include "src/compiler/opcodes.h"
16 #include "src/compiler/operator.h"
17 #include "src/compiler/operator-properties.h"
18 #include "src/compiler/register-allocator.h"
19 #include "src/compiler/schedule.h"
20 #include "src/compiler/scheduler.h"
21 #include "src/ostreams.h"
28 FILE* OpenVisualizerLogFile(CompilationInfo* info, const char* phase,
29 const char* suffix, const char* mode) {
30 EmbeddedVector<char, 256> filename;
31 SmartArrayPointer<char> function_name;
32 if (!info->shared_info().is_null()) {
33 function_name = info->shared_info()->DebugName()->ToCString();
34 if (strlen(function_name.get()) > 0) {
35 SNPrintF(filename, "turbo-%s", function_name.get());
37 SNPrintF(filename, "turbo-%p", static_cast<void*>(info));
40 SNPrintF(filename, "turbo-none-%s", phase);
42 std::replace(filename.start(), filename.start() + filename.length(), ' ',
45 EmbeddedVector<char, 256> full_filename;
47 SNPrintF(full_filename, "%s.%s", filename.start(), suffix);
49 SNPrintF(full_filename, "%s-%s.%s", filename.start(), phase, suffix);
51 return base::OS::FOpen(full_filename.start(), mode);
55 static int SafeId(Node* node) { return node == NULL ? -1 : node->id(); }
56 static const char* SafeMnemonic(Node* node) {
57 return node == NULL ? "null" : node->op()->mnemonic();
60 #define DEAD_COLOR "#999999"
64 explicit Escaped(const std::ostringstream& os,
65 const char* escaped_chars = "<>|{}")
66 : str_(os.str()), escaped_chars_(escaped_chars) {}
68 friend std::ostream& operator<<(std::ostream& os, const Escaped& e) {
69 for (std::string::const_iterator i = e.str_.begin(); i != e.str_.end();
71 if (e.needs_escape(*i)) os << "\\";
78 bool needs_escape(char ch) const {
79 for (size_t i = 0; i < strlen(escaped_chars_); ++i) {
80 if (ch == escaped_chars_[i]) return true;
85 const std::string str_;
86 const char* const escaped_chars_;
89 class JSONGraphNodeWriter {
91 JSONGraphNodeWriter(std::ostream& os, Zone* zone, const Graph* graph,
92 const SourcePositionTable* positions)
93 : os_(os), all_(zone, graph), positions_(positions), first_node_(true) {}
96 for (Node* const node : all_.live) PrintNode(node);
100 void PrintNode(Node* node) {
106 std::ostringstream label;
107 label << *node->op();
108 os_ << "{\"id\":" << SafeId(node) << ",\"label\":\"" << Escaped(label, "\"")
110 IrOpcode::Value opcode = node->opcode();
111 if (IrOpcode::IsPhiOpcode(opcode)) {
112 os_ << ",\"rankInputs\":[0," << NodeProperties::FirstControlIndex(node)
114 os_ << ",\"rankWithInput\":[" << NodeProperties::FirstControlIndex(node)
116 } else if (opcode == IrOpcode::kIfTrue || opcode == IrOpcode::kIfFalse ||
117 opcode == IrOpcode::kLoop) {
118 os_ << ",\"rankInputs\":[" << NodeProperties::FirstControlIndex(node)
121 if (opcode == IrOpcode::kBranch) {
122 os_ << ",\"rankInputs\":[0]";
124 SourcePosition position = positions_->GetSourcePosition(node);
125 if (!position.IsUnknown()) {
126 DCHECK(!position.IsInvalid());
127 os_ << ",\"pos\":" << position.raw();
129 os_ << ",\"opcode\":\"" << IrOpcode::Mnemonic(node->opcode()) << "\"";
130 os_ << ",\"control\":" << (NodeProperties::IsControl(node) ? "true"
138 const SourcePositionTable* positions_;
141 DISALLOW_COPY_AND_ASSIGN(JSONGraphNodeWriter);
145 class JSONGraphEdgeWriter {
147 JSONGraphEdgeWriter(std::ostream& os, Zone* zone, const Graph* graph)
148 : os_(os), all_(zone, graph), first_edge_(true) {}
151 for (Node* const node : all_.live) PrintEdges(node);
155 void PrintEdges(Node* node) {
156 for (int i = 0; i < node->InputCount(); i++) {
157 Node* input = node->InputAt(i);
158 if (input == NULL) continue;
159 PrintEdge(node, i, input);
163 void PrintEdge(Node* from, int index, Node* to) {
169 const char* edge_type = NULL;
170 if (index < NodeProperties::FirstValueIndex(from)) {
171 edge_type = "unknown";
172 } else if (index < NodeProperties::FirstContextIndex(from)) {
174 } else if (index < NodeProperties::FirstFrameStateIndex(from)) {
175 edge_type = "context";
176 } else if (index < NodeProperties::FirstEffectIndex(from)) {
177 edge_type = "frame-state";
178 } else if (index < NodeProperties::FirstControlIndex(from)) {
179 edge_type = "effect";
181 edge_type = "control";
183 os_ << "{\"source\":" << SafeId(to) << ",\"target\":" << SafeId(from)
184 << ",\"index\":" << index << ",\"type\":\"" << edge_type << "\"}";
192 DISALLOW_COPY_AND_ASSIGN(JSONGraphEdgeWriter);
196 std::ostream& operator<<(std::ostream& os, const AsJSON& ad) {
198 os << "{\n\"nodes\":[";
199 JSONGraphNodeWriter(os, &tmp_zone, &ad.graph, ad.positions).Print();
200 os << "],\n\"edges\":[";
201 JSONGraphEdgeWriter(os, &tmp_zone, &ad.graph).Print();
207 class GraphVisualizer {
209 GraphVisualizer(std::ostream& os, Zone* zone, const Graph* graph)
210 : all_(zone, graph), os_(os) {}
214 void PrintNode(Node* node, bool gray);
217 void PrintEdge(Edge edge);
222 DISALLOW_COPY_AND_ASSIGN(GraphVisualizer);
226 static Node* GetControlCluster(Node* node) {
227 if (OperatorProperties::IsBasicBlockBegin(node->op())) {
229 } else if (node->op()->ControlInputCount() == 1) {
230 Node* control = NodeProperties::GetControlInput(node, 0);
231 return control != NULL &&
232 OperatorProperties::IsBasicBlockBegin(control->op())
241 void GraphVisualizer::PrintNode(Node* node, bool gray) {
242 Node* control_cluster = GetControlCluster(node);
243 if (control_cluster != NULL) {
244 os_ << " subgraph cluster_BasicBlock" << control_cluster->id() << " {\n";
246 os_ << " ID" << SafeId(node) << " [\n";
248 os_ << " shape=\"record\"\n";
249 switch (node->opcode()) {
251 case IrOpcode::kDead:
252 case IrOpcode::kStart:
253 os_ << " style=\"diagonals\"\n";
255 case IrOpcode::kMerge:
256 case IrOpcode::kIfTrue:
257 case IrOpcode::kIfFalse:
258 case IrOpcode::kLoop:
259 os_ << " style=\"rounded\"\n";
266 os_ << " style=\"filled\"\n"
267 << " fillcolor=\"" DEAD_COLOR "\"\n";
270 std::ostringstream label;
271 label << *node->op();
272 os_ << " label=\"{{#" << SafeId(node) << ":" << Escaped(label);
274 auto i = node->input_edges().begin();
275 for (int j = node->op()->ValueInputCount(); j > 0; ++i, j--) {
276 os_ << "|<I" << (*i).index() << ">#" << SafeId((*i).to());
278 for (int j = OperatorProperties::GetContextInputCount(node->op()); j > 0;
280 os_ << "|<I" << (*i).index() << ">X #" << SafeId((*i).to());
282 for (int j = OperatorProperties::GetFrameStateInputCount(node->op()); j > 0;
284 os_ << "|<I" << (*i).index() << ">F #" << SafeId((*i).to());
286 for (int j = node->op()->EffectInputCount(); j > 0; ++i, j--) {
287 os_ << "|<I" << (*i).index() << ">E #" << SafeId((*i).to());
290 if (OperatorProperties::IsBasicBlockBegin(node->op()) ||
291 GetControlCluster(node) == NULL) {
292 for (int j = node->op()->ControlInputCount(); j > 0; ++i, j--) {
293 os_ << "|<I" << (*i).index() << ">C #" << SafeId((*i).to());
298 if (FLAG_trace_turbo_types && NodeProperties::IsTyped(node)) {
299 Bounds bounds = NodeProperties::GetBounds(node);
300 std::ostringstream upper;
301 bounds.upper->PrintTo(upper);
302 std::ostringstream lower;
303 bounds.lower->PrintTo(lower);
304 os_ << "|" << Escaped(upper) << "|" << Escaped(lower);
309 if (control_cluster != NULL) os_ << " }\n";
313 static bool IsLikelyBackEdge(Node* from, int index, Node* to) {
314 if (NodeProperties::IsPhi(from)) {
315 Node* control = NodeProperties::GetControlInput(from, 0);
316 return control != NULL && control->opcode() != IrOpcode::kMerge &&
317 control != to && index != 0;
318 } else if (from->opcode() == IrOpcode::kLoop) {
326 void GraphVisualizer::PrintEdge(Edge edge) {
327 Node* from = edge.from();
328 int index = edge.index();
329 Node* to = edge.to();
331 if (!all_.IsLive(to)) return; // skip inputs that point to dead or NULL.
333 bool unconstrained = IsLikelyBackEdge(from, index, to);
334 os_ << " ID" << SafeId(from);
336 if (OperatorProperties::IsBasicBlockBegin(from->op()) ||
337 GetControlCluster(from) == NULL ||
338 (from->op()->ControlInputCount() > 0 &&
339 NodeProperties::GetControlInput(from) != to)) {
340 os_ << ":I" << index << ":n -> ID" << SafeId(to) << ":s"
341 << "[" << (unconstrained ? "constraint=false, " : "")
342 << (NodeProperties::IsControlEdge(edge) ? "style=bold, " : "")
343 << (NodeProperties::IsEffectEdge(edge) ? "style=dotted, " : "")
344 << (NodeProperties::IsContextEdge(edge) ? "style=dashed, " : "") << "]";
346 os_ << " -> ID" << SafeId(to) << ":s [color=transparent, "
347 << (unconstrained ? "constraint=false, " : "")
348 << (NodeProperties::IsControlEdge(edge) ? "style=dashed, " : "") << "]";
354 void GraphVisualizer::Print() {
355 os_ << "digraph D {\n"
356 << " node [fontsize=8,height=0.25]\n"
357 << " rankdir=\"BT\"\n"
358 << " ranksep=\"1.2 equally\"\n"
359 << " overlap=\"false\"\n"
360 << " splines=\"true\"\n"
361 << " concentrate=\"true\"\n"
364 // Make sure all nodes have been output before writing out the edges.
365 for (Node* const node : all_.live) PrintNode(node, false);
366 for (Node* const node : all_.gray) PrintNode(node, true);
368 // With all the nodes written, add the edges.
369 for (Node* const node : all_.live) {
370 for (Edge edge : node->use_edges()) {
378 std::ostream& operator<<(std::ostream& os, const AsDOT& ad) {
380 GraphVisualizer(os, &tmp_zone, &ad.graph).Print();
385 class GraphC1Visualizer {
387 GraphC1Visualizer(std::ostream& os, Zone* zone); // NOLINT
389 void PrintCompilation(const CompilationInfo* info);
390 void PrintSchedule(const char* phase, const Schedule* schedule,
391 const SourcePositionTable* positions,
392 const InstructionSequence* instructions);
393 void PrintAllocator(const char* phase, const RegisterAllocator* allocator);
394 Zone* zone() const { return zone_; }
398 void PrintStringProperty(const char* name, const char* value);
399 void PrintLongProperty(const char* name, int64_t value);
400 void PrintIntProperty(const char* name, int value);
401 void PrintBlockProperty(const char* name, BasicBlock::Id block_id);
402 void PrintNodeId(Node* n);
403 void PrintNode(Node* n);
404 void PrintInputs(Node* n);
405 template <typename InputIterator>
406 void PrintInputs(InputIterator* i, int count, const char* prefix);
407 void PrintType(Node* node);
409 void PrintLiveRange(LiveRange* range, const char* type);
410 class Tag FINAL BASE_EMBEDDED {
412 Tag(GraphC1Visualizer* visualizer, const char* name) {
414 visualizer_ = visualizer;
415 visualizer->PrintIndent();
416 visualizer_->os_ << "begin_" << name << "\n";
417 visualizer->indent_++;
421 visualizer_->indent_--;
422 visualizer_->PrintIndent();
423 visualizer_->os_ << "end_" << name_ << "\n";
424 DCHECK(visualizer_->indent_ >= 0);
428 GraphC1Visualizer* visualizer_;
436 DISALLOW_COPY_AND_ASSIGN(GraphC1Visualizer);
440 void GraphC1Visualizer::PrintIndent() {
441 for (int i = 0; i < indent_; i++) {
447 GraphC1Visualizer::GraphC1Visualizer(std::ostream& os, Zone* zone)
448 : os_(os), indent_(0), zone_(zone) {}
451 void GraphC1Visualizer::PrintStringProperty(const char* name,
454 os_ << name << " \"" << value << "\"\n";
458 void GraphC1Visualizer::PrintLongProperty(const char* name, int64_t value) {
460 os_ << name << " " << static_cast<int>(value / 1000) << "\n";
464 void GraphC1Visualizer::PrintBlockProperty(const char* name,
465 BasicBlock::Id block_id) {
467 os_ << name << " \"B" << block_id << "\"\n";
471 void GraphC1Visualizer::PrintIntProperty(const char* name, int value) {
473 os_ << name << " " << value << "\n";
477 void GraphC1Visualizer::PrintCompilation(const CompilationInfo* info) {
478 Tag tag(this, "compilation");
479 if (info->IsOptimizing()) {
480 Handle<String> name = info->function()->debug_name();
481 PrintStringProperty("name", name->ToCString().get());
483 os_ << "method \"" << name->ToCString().get() << ":"
484 << info->optimization_id() << "\"\n";
486 CodeStub::Major major_key = info->code_stub()->MajorKey();
487 PrintStringProperty("name", CodeStub::MajorName(major_key, false));
488 PrintStringProperty("method", "stub");
490 PrintLongProperty("date",
491 static_cast<int64_t>(base::OS::TimeCurrentMillis()));
495 void GraphC1Visualizer::PrintNodeId(Node* n) { os_ << "n" << SafeId(n); }
498 void GraphC1Visualizer::PrintNode(Node* n) {
500 os_ << " " << *n->op() << " ";
505 template <typename InputIterator>
506 void GraphC1Visualizer::PrintInputs(InputIterator* i, int count,
507 const char* prefix) {
520 void GraphC1Visualizer::PrintInputs(Node* node) {
521 auto i = node->inputs().begin();
522 PrintInputs(&i, node->op()->ValueInputCount(), " ");
523 PrintInputs(&i, OperatorProperties::GetContextInputCount(node->op()),
525 PrintInputs(&i, OperatorProperties::GetFrameStateInputCount(node->op()),
527 PrintInputs(&i, node->op()->EffectInputCount(), " Eff:");
528 PrintInputs(&i, node->op()->ControlInputCount(), " Ctrl:");
532 void GraphC1Visualizer::PrintType(Node* node) {
533 if (NodeProperties::IsTyped(node)) {
534 Bounds bounds = NodeProperties::GetBounds(node);
536 bounds.upper->PrintTo(os_);
538 bounds.lower->PrintTo(os_);
543 void GraphC1Visualizer::PrintSchedule(const char* phase,
544 const Schedule* schedule,
545 const SourcePositionTable* positions,
546 const InstructionSequence* instructions) {
547 Tag tag(this, "cfg");
548 PrintStringProperty("name", phase);
549 const BasicBlockVector* rpo = schedule->rpo_order();
550 for (size_t i = 0; i < rpo->size(); i++) {
551 BasicBlock* current = (*rpo)[i];
552 Tag block_tag(this, "block");
553 PrintBlockProperty("name", current->id());
554 PrintIntProperty("from_bci", -1);
555 PrintIntProperty("to_bci", -1);
558 os_ << "predecessors";
559 for (BasicBlock* predecessor : current->predecessors()) {
560 os_ << " \"B" << predecessor->id() << "\"";
566 for (BasicBlock* successor : current->successors()) {
567 os_ << " \"B" << successor->id() << "\"";
572 os_ << "xhandlers\n";
577 if (current->dominator() != NULL) {
578 PrintBlockProperty("dominator", current->dominator()->id());
581 PrintIntProperty("loop_depth", current->loop_depth());
583 const InstructionBlock* instruction_block =
584 instructions->InstructionBlockAt(current->GetRpoNumber());
585 if (instruction_block->code_start() >= 0) {
586 int first_index = instruction_block->first_instruction_index();
587 int last_index = instruction_block->last_instruction_index();
588 PrintIntProperty("first_lir_id", LifetimePosition::FromInstructionIndex(
589 first_index).Value());
590 PrintIntProperty("last_lir_id", LifetimePosition::FromInstructionIndex(
591 last_index).Value());
595 Tag states_tag(this, "states");
596 Tag locals_tag(this, "locals");
598 for (BasicBlock::const_iterator i = current->begin(); i != current->end();
600 if ((*i)->opcode() == IrOpcode::kPhi) total++;
602 PrintIntProperty("size", total);
603 PrintStringProperty("method", "None");
605 for (BasicBlock::const_iterator i = current->begin(); i != current->end();
607 if ((*i)->opcode() != IrOpcode::kPhi) continue;
619 Tag HIR_tag(this, "HIR");
620 for (BasicBlock::const_iterator i = current->begin(); i != current->end();
623 if (node->opcode() == IrOpcode::kPhi) continue;
624 int uses = node->UseCount();
626 os_ << "0 " << uses << " ";
628 if (FLAG_trace_turbo_types) {
632 if (positions != NULL) {
633 SourcePosition position = positions->GetSourcePosition(node);
634 if (!position.IsUnknown()) {
635 DCHECK(!position.IsInvalid());
636 os_ << " pos:" << position.raw();
642 BasicBlock::Control control = current->control();
643 if (control != BasicBlock::kNone) {
646 if (current->control_input() != NULL) {
647 PrintNode(current->control_input());
649 os_ << -1 - current->id().ToInt() << " Goto";
652 for (BasicBlock* successor : current->successors()) {
653 os_ << " B" << successor->id();
655 if (FLAG_trace_turbo_types && current->control_input() != NULL) {
657 PrintType(current->control_input());
663 if (instructions != NULL) {
664 Tag LIR_tag(this, "LIR");
665 for (int j = instruction_block->first_instruction_index();
666 j <= instruction_block->last_instruction_index(); j++) {
668 PrintableInstruction printable = {RegisterConfiguration::ArchDefault(),
669 instructions->InstructionAt(j)};
670 os_ << j << " " << printable << " <|@\n";
677 void GraphC1Visualizer::PrintAllocator(const char* phase,
678 const RegisterAllocator* allocator) {
679 Tag tag(this, "intervals");
680 PrintStringProperty("name", phase);
682 for (auto range : allocator->fixed_double_live_ranges()) {
683 PrintLiveRange(range, "fixed");
686 for (auto range : allocator->fixed_live_ranges()) {
687 PrintLiveRange(range, "fixed");
690 for (auto range : allocator->live_ranges()) {
691 PrintLiveRange(range, "object");
696 void GraphC1Visualizer::PrintLiveRange(LiveRange* range, const char* type) {
697 if (range != NULL && !range->IsEmpty()) {
699 os_ << range->id() << " " << type;
700 if (range->HasRegisterAssigned()) {
701 InstructionOperand op = range->GetAssignedOperand();
702 int assigned_reg = op.index();
703 if (op.IsDoubleRegister()) {
704 os_ << " \"" << DoubleRegister::AllocationIndexToString(assigned_reg)
707 DCHECK(op.IsRegister());
708 os_ << " \"" << Register::AllocationIndexToString(assigned_reg) << "\"";
710 } else if (range->IsSpilled()) {
712 if (range->TopLevel()->HasSpillRange()) {
713 index = kMaxInt; // This hasn't been set yet.
715 index = range->TopLevel()->GetSpillOperand()->index();
717 if (range->TopLevel()->Kind() == DOUBLE_REGISTERS) {
718 os_ << " \"double_stack:" << index << "\"";
719 } else if (range->TopLevel()->Kind() == GENERAL_REGISTERS) {
720 os_ << " \"stack:" << index << "\"";
722 os_ << " \"const(nostack):" << index << "\"";
725 int parent_index = -1;
726 if (range->IsChild()) {
727 parent_index = range->parent()->id();
729 parent_index = range->id();
731 InstructionOperand* op = range->FirstHint();
733 if (op != NULL && op->IsUnallocated()) {
734 hint_index = UnallocatedOperand::cast(op)->virtual_register();
736 os_ << " " << parent_index << " " << hint_index;
737 UseInterval* cur_interval = range->first_interval();
738 while (cur_interval != NULL && range->Covers(cur_interval->start())) {
739 os_ << " [" << cur_interval->start().Value() << ", "
740 << cur_interval->end().Value() << "[";
741 cur_interval = cur_interval->next();
744 UsePosition* current_pos = range->first_pos();
745 while (current_pos != NULL) {
746 if (current_pos->RegisterIsBeneficial() || FLAG_trace_all_uses) {
747 os_ << " " << current_pos->pos().Value() << " M";
749 current_pos = current_pos->next();
757 std::ostream& operator<<(std::ostream& os, const AsC1VCompilation& ac) {
759 GraphC1Visualizer(os, &tmp_zone).PrintCompilation(ac.info_);
764 std::ostream& operator<<(std::ostream& os, const AsC1V& ac) {
766 GraphC1Visualizer(os, &tmp_zone)
767 .PrintSchedule(ac.phase_, ac.schedule_, ac.positions_, ac.instructions_);
772 std::ostream& operator<<(std::ostream& os, const AsC1VAllocator& ac) {
774 GraphC1Visualizer(os, &tmp_zone).PrintAllocator(ac.phase_, ac.allocator_);
778 const int kUnvisited = 0;
779 const int kOnStack = 1;
780 const int kVisited = 2;
782 std::ostream& operator<<(std::ostream& os, const AsRPO& ar) {
784 ZoneVector<byte> state(ar.graph.NodeCount(), kUnvisited, &local_zone);
785 ZoneStack<Node*> stack(&local_zone);
787 stack.push(ar.graph.end());
788 state[ar.graph.end()->id()] = kOnStack;
789 while (!stack.empty()) {
790 Node* n = stack.top();
792 for (Node* const i : n->inputs()) {
793 if (state[i->id()] == kUnvisited) {
794 state[i->id()] = kOnStack;
801 state[n->id()] = kVisited;
803 os << "#" << n->id() << ":" << *n->op() << "(";
805 for (Node* const i : n->inputs()) {
806 if (j++ > 0) os << ", ";
807 os << "#" << SafeId(i) << ":" << SafeMnemonic(i);
809 os << ")" << std::endl;
816 } // namespace v8::internal::compiler