graph-visualizer.cc 43.5 KB
Newer Older
1 2 3 4 5 6
// Copyright 2013 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/compiler/graph-visualizer.h"

7
#include <memory>
8 9 10
#include <sstream>
#include <string>

11
#include "src/base/platform/wrappers.h"
12
#include "src/base/vector.h"
13 14
#include "src/codegen/optimized-compilation-info.h"
#include "src/codegen/source-position.h"
15
#include "src/compiler/all-nodes.h"
16
#include "src/compiler/backend/register-allocation.h"
17
#include "src/compiler/backend/register-allocator.h"
18
#include "src/compiler/compiler-source-position-table.h"
19
#include "src/compiler/graph.h"
20
#include "src/compiler/node-origin-table.h"
21
#include "src/compiler/node-properties.h"
22
#include "src/compiler/node.h"
23
#include "src/compiler/opcodes.h"
24
#include "src/compiler/operator-properties.h"
25
#include "src/compiler/operator.h"
26 27
#include "src/compiler/schedule.h"
#include "src/compiler/scheduler.h"
28
#include "src/interpreter/bytecodes.h"
29
#include "src/objects/script-inl.h"
30
#include "src/objects/shared-function-info.h"
31
#include "src/utils/ostreams.h"
32 33 34 35 36

namespace v8 {
namespace internal {
namespace compiler {

37 38 39 40 41 42 43 44
const char* get_cached_trace_turbo_filename(OptimizedCompilationInfo* info) {
  if (!info->trace_turbo_filename()) {
    info->set_trace_turbo_filename(
        GetVisualizerLogFileName(info, FLAG_trace_turbo_path, nullptr, "json"));
  }
  return info->trace_turbo_filename();
}

45 46
TurboJsonFile::TurboJsonFile(OptimizedCompilationInfo* info,
                             std::ios_base::openmode mode)
47 48 49
    : std::ofstream(get_cached_trace_turbo_filename(info), mode) {}

TurboJsonFile::~TurboJsonFile() { flush(); }
50

51 52 53 54 55 56
TurboCfgFile::TurboCfgFile(Isolate* isolate)
    : std::ofstream(Isolate::GetTurboCfgFileName(isolate).c_str(),
                    std::ios_base::app) {}

TurboCfgFile::~TurboCfgFile() { flush(); }

57 58 59 60 61 62
std::ostream& operator<<(std::ostream& out,
                         const SourcePositionAsJSON& asJSON) {
  asJSON.sp.PrintJson(out);
  return out;
}

63 64 65 66 67
std::ostream& operator<<(std::ostream& out, const NodeOriginAsJSON& asJSON) {
  asJSON.no.PrintJson(out);
  return out;
}

68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
class JSONEscaped {
 public:
  explicit JSONEscaped(const std::ostringstream& os) : str_(os.str()) {}

  friend std::ostream& operator<<(std::ostream& os, const JSONEscaped& e) {
    for (char c : e.str_) PipeCharacter(os, c);
    return os;
  }

 private:
  static std::ostream& PipeCharacter(std::ostream& os, char c) {
    if (c == '"') return os << "\\\"";
    if (c == '\\') return os << "\\\\";
    if (c == '\b') return os << "\\b";
    if (c == '\f') return os << "\\f";
    if (c == '\n') return os << "\\n";
    if (c == '\r') return os << "\\r";
    if (c == '\t') return os << "\\t";
    return os << c;
  }

  const std::string str_;
};

92 93 94 95 96 97 98 99 100 101 102 103 104
void JsonPrintFunctionSource(std::ostream& os, int source_id,
                             std::unique_ptr<char[]> function_name,
                             Handle<Script> script, Isolate* isolate,
                             Handle<SharedFunctionInfo> shared, bool with_key) {
  if (with_key) os << "\"" << source_id << "\" : ";

  os << "{ ";
  os << "\"sourceId\": " << source_id;
  os << ", \"functionName\": \"" << function_name.get() << "\" ";

  int start = 0;
  int end = 0;
  if (!script.is_null() && !script->IsUndefined(isolate) && !shared.is_null()) {
105
    Object source_name = script->name();
106
    os << ", \"sourceName\": \"";
107
    if (source_name.IsString()) {
108
      std::ostringstream escaped_name;
109
      escaped_name << String::cast(source_name).ToCString().get();
110
      os << JSONEscaped(escaped_name);
111 112 113
    }
    os << "\"";
    {
114
      DisallowGarbageCollection no_gc;
115 116 117 118
      start = shared->StartPosition();
      end = shared->EndPosition();
      os << ", \"sourceText\": \"";
      int len = shared->EndPosition() - start;
119
      SubStringRange source(String::cast(script->source()), no_gc, start, len);
120
      for (auto c : source) {
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
        os << AsEscapedUC16ForJSON(c);
      }
      os << "\"";
    }
  } else {
    os << ", \"sourceName\": \"\"";
    os << ", \"sourceText\": \"\"";
  }
  os << ", \"startPosition\": " << start;
  os << ", \"endPosition\": " << end;
  os << "}";
}

int SourceIdAssigner::GetIdFor(Handle<SharedFunctionInfo> shared) {
  for (unsigned i = 0; i < printed_.size(); i++) {
    if (printed_.at(i).is_identical_to(shared)) {
137
      source_ids_.push_back(i);
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
      return i;
    }
  }
  const int source_id = static_cast<int>(printed_.size());
  printed_.push_back(shared);
  source_ids_.push_back(source_id);
  return source_id;
}

namespace {

void JsonPrintInlinedFunctionInfo(
    std::ostream& os, int source_id, int inlining_id,
    const OptimizedCompilationInfo::InlinedFunctionHolder& h) {
  os << "\"" << inlining_id << "\" : ";
  os << "{ \"inliningId\" : " << inlining_id;
  os << ", \"sourceId\" : " << source_id;
  const SourcePosition position = h.position.position;
  if (position.IsKnown()) {
    os << ", \"inliningPosition\" : " << AsJSON(position);
  }
  os << "}";
}

}  // namespace

void JsonPrintAllSourceWithPositions(std::ostream& os,
                                     OptimizedCompilationInfo* info,
                                     Isolate* isolate) {
  os << "\"sources\" : {";
  Handle<Script> script =
169 170
      (info->shared_info().is_null() ||
       info->shared_info()->script() == Object())
171
          ? Handle<Script>()
172
          : handle(Script::cast(info->shared_info()->script()), isolate);
173 174 175
  JsonPrintFunctionSource(os, -1,
                          info->shared_info().is_null()
                              ? std::unique_ptr<char[]>(new char[1]{0})
176
                              : info->shared_info()->DebugNameCStr(),
177 178 179 180 181 182 183
                          script, isolate, info->shared_info(), true);
  const auto& inlined = info->inlined_functions();
  SourceIdAssigner id_assigner(info->inlined_functions().size());
  for (unsigned id = 0; id < inlined.size(); id++) {
    os << ", ";
    Handle<SharedFunctionInfo> shared = inlined[id].shared_info;
    const int source_id = id_assigner.GetIdFor(shared);
184
    JsonPrintFunctionSource(os, source_id, shared->DebugNameCStr(),
185 186
                            handle(Script::cast(shared->script()), isolate),
                            isolate, shared, true);
187 188 189 190 191 192 193 194 195 196 197 198 199
  }
  os << "}, ";
  os << "\"inlinings\" : {";
  bool need_comma = false;
  for (unsigned id = 0; id < inlined.size(); id++) {
    if (need_comma) os << ", ";
    const int source_id = id_assigner.GetIdAt(id);
    JsonPrintInlinedFunctionInfo(os, source_id, id, inlined[id]);
    need_comma = true;
  }
  os << "}";
}

200
std::unique_ptr<char[]> GetVisualizerLogFileName(OptimizedCompilationInfo* info,
201
                                                 const char* optional_base_dir,
202 203
                                                 const char* phase,
                                                 const char* suffix) {
204
  base::EmbeddedVector<char, 256> filename(0);
205
  std::unique_ptr<char[]> debug_name = info->GetDebugName();
206
  int optimization_id = info->IsOptimizing() ? info->optimization_id() : 0;
207
  if (strlen(debug_name.get()) > 0) {
208
    SNPrintF(filename, "turbo-%s-%i", debug_name.get(), optimization_id);
209
  } else if (info->has_shared_info()) {
210
    SNPrintF(filename, "turbo-%p-%i",
211
             reinterpret_cast<void*>(info->shared_info()->address()),
212
             optimization_id);
213
  } else {
214
    SNPrintF(filename, "turbo-none-%i", optimization_id);
215
  }
216
  base::EmbeddedVector<char, 256> source_file(0);
217
  bool source_available = false;
218
  if (FLAG_trace_file_names && info->has_shared_info() &&
219 220 221
      info->shared_info()->script().IsScript()) {
    Object source_name = Script::cast(info->shared_info()->script()).name();
    if (source_name.IsString()) {
222
      String str = String::cast(source_name);
223 224
      if (str.length() > 0) {
        SNPrintF(source_file, "%s", str.ToCString().get());
225 226
        std::replace(source_file.begin(),
                     source_file.begin() + source_file.length(), '/', '_');
227 228 229 230
        source_available = true;
      }
    }
  }
231
  std::replace(filename.begin(), filename.begin() + filename.length(), ' ',
232
               '_');
233 234
  std::replace(filename.begin(), filename.begin() + filename.length(), ':',
               '-');
235

236
  base::EmbeddedVector<char, 256> base_dir;
237 238 239 240 241 242 243
  if (optional_base_dir != nullptr) {
    SNPrintF(base_dir, "%s%c", optional_base_dir,
             base::OS::DirectorySeparator());
  } else {
    base_dir[0] = '\0';
  }

244
  base::EmbeddedVector<char, 256> full_filename;
245
  if (phase == nullptr && !source_available) {
246
    SNPrintF(full_filename, "%s%s.%s", base_dir.begin(), filename.begin(),
247
             suffix);
248
  } else if (phase != nullptr && !source_available) {
249
    SNPrintF(full_filename, "%s%s-%s.%s", base_dir.begin(), filename.begin(),
250
             phase, suffix);
251
  } else if (phase == nullptr && source_available) {
252 253
    SNPrintF(full_filename, "%s%s_%s.%s", base_dir.begin(), filename.begin(),
             source_file.begin(), suffix);
254
  } else {
255 256
    SNPrintF(full_filename, "%s%s_%s-%s.%s", base_dir.begin(), filename.begin(),
             source_file.begin(), phase, suffix);
257
  }
258 259

  char* buffer = new char[full_filename.length() + 1];
260
  memcpy(buffer, full_filename.begin(), full_filename.length());
261
  buffer[full_filename.length()] = '\0';
262
  return std::unique_ptr<char[]>(buffer);
263 264 265
}


266
static int SafeId(Node* node) { return node == nullptr ? -1 : node->id(); }
267
static const char* SafeMnemonic(Node* node) {
268
  return node == nullptr ? "null" : node->op()->mnemonic();
269
}
270 271

class JSONGraphNodeWriter {
272
 public:
danno's avatar
danno committed
273
  JSONGraphNodeWriter(std::ostream& os, Zone* zone, const Graph* graph,
274 275
                      const SourcePositionTable* positions,
                      const NodeOriginTable* origins)
276 277 278 279
      : os_(os),
        all_(zone, graph, false),
        live_(zone, graph, true),
        positions_(positions),
280
        origins_(origins),
281
        first_node_(true) {}
282 283
  JSONGraphNodeWriter(const JSONGraphNodeWriter&) = delete;
  JSONGraphNodeWriter& operator=(const JSONGraphNodeWriter&) = delete;
284

285
  void Print() {
286
    for (Node* const node : all_.reachable) PrintNode(node);
danno's avatar
danno committed
287
    os_ << "\n";
288
  }
289

290 291 292 293
  void PrintNode(Node* node) {
    if (first_node_) {
      first_node_ = false;
    } else {
danno's avatar
danno committed
294
      os_ << ",\n";
295
    }
296
    std::ostringstream label, title, properties;
297 298
    node->op()->PrintTo(label, Operator::PrintVerbosity::kSilent);
    node->op()->PrintTo(title, Operator::PrintVerbosity::kVerbose);
299
    node->op()->PrintPropsTo(properties);
300 301 302
    os_ << "{\"id\":" << SafeId(node) << ",\"label\":\"" << JSONEscaped(label)
        << "\""
        << ",\"title\":\"" << JSONEscaped(title) << "\""
303
        << ",\"live\": " << (live_.IsLive(node) ? "true" : "false")
304
        << ",\"properties\":\"" << JSONEscaped(properties) << "\"";
305
    IrOpcode::Value opcode = node->opcode();
306
    if (IrOpcode::IsPhiOpcode(opcode)) {
307 308 309 310 311 312 313 314 315 316 317 318
      os_ << ",\"rankInputs\":[0," << NodeProperties::FirstControlIndex(node)
          << "]";
      os_ << ",\"rankWithInput\":[" << NodeProperties::FirstControlIndex(node)
          << "]";
    } else if (opcode == IrOpcode::kIfTrue || opcode == IrOpcode::kIfFalse ||
               opcode == IrOpcode::kLoop) {
      os_ << ",\"rankInputs\":[" << NodeProperties::FirstControlIndex(node)
          << "]";
    }
    if (opcode == IrOpcode::kBranch) {
      os_ << ",\"rankInputs\":[0]";
    }
319 320 321 322 323
    if (positions_ != nullptr) {
      SourcePosition position = positions_->GetSourcePosition(node);
      if (position.IsKnown()) {
        os_ << ", \"sourcePosition\" : " << AsJSON(position);
      }
danno's avatar
danno committed
324
    }
325 326 327 328 329 330
    if (origins_) {
      NodeOrigin origin = origins_->GetNodeOrigin(node);
      if (origin.IsKnown()) {
        os_ << ", \"origin\" : " << AsJSON(origin);
      }
    }
331 332 333
    os_ << ",\"opcode\":\"" << IrOpcode::Mnemonic(node->opcode()) << "\"";
    os_ << ",\"control\":" << (NodeProperties::IsControl(node) ? "true"
                                                               : "false");
334 335 336 337 338 339
    os_ << ",\"opinfo\":\"" << node->op()->ValueInputCount() << " v "
        << node->op()->EffectInputCount() << " eff "
        << node->op()->ControlInputCount() << " ctrl in, "
        << node->op()->ValueOutputCount() << " v "
        << node->op()->EffectOutputCount() << " eff "
        << node->op()->ControlOutputCount() << " ctrl out\"";
340
    if (NodeProperties::IsTyped(node)) {
341
      Type type = NodeProperties::GetType(node);
342
      std::ostringstream type_out;
343
      type.PrintTo(type_out);
344
      os_ << ",\"type\":\"" << JSONEscaped(type_out) << "\"";
345
    }
346 347
    os_ << "}";
  }
348 349

 private:
350
  std::ostream& os_;
351
  AllNodes all_;
352
  AllNodes live_;
danno's avatar
danno committed
353
  const SourcePositionTable* positions_;
354
  const NodeOriginTable* origins_;
355 356 357 358
  bool first_node_;
};


359
class JSONGraphEdgeWriter {
360
 public:
361
  JSONGraphEdgeWriter(std::ostream& os, Zone* zone, const Graph* graph)
362
      : os_(os), all_(zone, graph, false), first_edge_(true) {}
363 364
  JSONGraphEdgeWriter(const JSONGraphEdgeWriter&) = delete;
  JSONGraphEdgeWriter& operator=(const JSONGraphEdgeWriter&) = delete;
365

366
  void Print() {
367
    for (Node* const node : all_.reachable) PrintEdges(node);
danno's avatar
danno committed
368
    os_ << "\n";
369 370 371 372 373
  }

  void PrintEdges(Node* node) {
    for (int i = 0; i < node->InputCount(); i++) {
      Node* input = node->InputAt(i);
374
      if (input == nullptr) continue;
375 376 377
      PrintEdge(node, i, input);
    }
  }
378

379 380 381 382
  void PrintEdge(Node* from, int index, Node* to) {
    if (first_edge_) {
      first_edge_ = false;
    } else {
danno's avatar
danno committed
383
      os_ << ",\n";
384
    }
385
    const char* edge_type = nullptr;
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
    if (index < NodeProperties::FirstValueIndex(from)) {
      edge_type = "unknown";
    } else if (index < NodeProperties::FirstContextIndex(from)) {
      edge_type = "value";
    } else if (index < NodeProperties::FirstFrameStateIndex(from)) {
      edge_type = "context";
    } else if (index < NodeProperties::FirstEffectIndex(from)) {
      edge_type = "frame-state";
    } else if (index < NodeProperties::FirstControlIndex(from)) {
      edge_type = "effect";
    } else {
      edge_type = "control";
    }
    os_ << "{\"source\":" << SafeId(to) << ",\"target\":" << SafeId(from)
        << ",\"index\":" << index << ",\"type\":\"" << edge_type << "\"}";
  }
402 403

 private:
404
  std::ostream& os_;
405
  AllNodes all_;
406 407 408
  bool first_edge_;
};

409
std::ostream& operator<<(std::ostream& os, const GraphAsJSON& ad) {
410
  AccountingAllocator allocator;
411
  Zone tmp_zone(&allocator, ZONE_NAME);
danno's avatar
danno committed
412
  os << "{\n\"nodes\":[";
413 414
  JSONGraphNodeWriter(os, &tmp_zone, &ad.graph, ad.positions, ad.origins)
      .Print();
danno's avatar
danno committed
415
  os << "],\n\"edges\":[";
416 417 418 419 420 421
  JSONGraphEdgeWriter(os, &tmp_zone, &ad.graph).Print();
  os << "]}";
  return os;
}


422 423
class GraphC1Visualizer {
 public:
424
  GraphC1Visualizer(std::ostream& os, Zone* zone);
425 426
  GraphC1Visualizer(const GraphC1Visualizer&) = delete;
  GraphC1Visualizer& operator=(const GraphC1Visualizer&) = delete;
427

428
  void PrintCompilation(const OptimizedCompilationInfo* info);
429 430 431
  void PrintSchedule(const char* phase, const Schedule* schedule,
                     const SourcePositionTable* positions,
                     const InstructionSequence* instructions);
432 433
  void PrintLiveRanges(const char* phase,
                       const TopTierRegisterAllocationData* data);
434 435 436 437 438 439 440
  Zone* zone() const { return zone_; }

 private:
  void PrintIndent();
  void PrintStringProperty(const char* name, const char* value);
  void PrintLongProperty(const char* name, int64_t value);
  void PrintIntProperty(const char* name, int value);
441
  void PrintBlockProperty(const char* name, int rpo_number);
442 443 444
  void PrintNodeId(Node* n);
  void PrintNode(Node* n);
  void PrintInputs(Node* n);
445 446
  template <typename InputIterator>
  void PrintInputs(InputIterator* i, int count, const char* prefix);
447 448
  void PrintType(Node* node);

449 450
  void PrintLiveRange(const LiveRange* range, const char* type, int vreg);
  void PrintLiveRangeChain(const TopLevelLiveRange* range, const char* type);
451

452
  class Tag final {
453 454 455 456 457 458 459 460 461 462 463 464 465
   public:
    Tag(GraphC1Visualizer* visualizer, const char* name) {
      name_ = name;
      visualizer_ = visualizer;
      visualizer->PrintIndent();
      visualizer_->os_ << "begin_" << name << "\n";
      visualizer->indent_++;
    }

    ~Tag() {
      visualizer_->indent_--;
      visualizer_->PrintIndent();
      visualizer_->os_ << "end_" << name_ << "\n";
466
      DCHECK_LE(0, visualizer_->indent_);
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
    }

   private:
    GraphC1Visualizer* visualizer_;
    const char* name_;
  };

  std::ostream& os_;
  int indent_;
  Zone* zone_;
};


void GraphC1Visualizer::PrintIndent() {
  for (int i = 0; i < indent_; i++) {
    os_ << "  ";
  }
}


GraphC1Visualizer::GraphC1Visualizer(std::ostream& os, Zone* zone)
    : os_(os), indent_(0), zone_(zone) {}


void GraphC1Visualizer::PrintStringProperty(const char* name,
                                            const char* value) {
  PrintIndent();
  os_ << name << " \"" << value << "\"\n";
}


void GraphC1Visualizer::PrintLongProperty(const char* name, int64_t value) {
  PrintIndent();
  os_ << name << " " << static_cast<int>(value / 1000) << "\n";
}


504
void GraphC1Visualizer::PrintBlockProperty(const char* name, int rpo_number) {
505
  PrintIndent();
506
  os_ << name << " \"B" << rpo_number << "\"\n";
507 508 509 510 511 512 513 514
}


void GraphC1Visualizer::PrintIntProperty(const char* name, int value) {
  PrintIndent();
  os_ << name << " " << value << "\n";
}

515
void GraphC1Visualizer::PrintCompilation(const OptimizedCompilationInfo* info) {
516
  Tag tag(this, "compilation");
517
  std::unique_ptr<char[]> name = info->GetDebugName();
518
  if (info->IsOptimizing()) {
519
    PrintStringProperty("name", name.get());
520
    PrintIndent();
521 522
    os_ << "method \"" << name.get() << ":" << info->optimization_id()
        << "\"\n";
523
  } else {
524
    PrintStringProperty("name", name.get());
525 526
    PrintStringProperty("method", "stub");
  }
527 528 529
  PrintLongProperty(
      "date",
      static_cast<int64_t>(V8::GetCurrentPlatform()->CurrentClockTimeMillis()));
530 531 532
}


533
void GraphC1Visualizer::PrintNodeId(Node* n) { os_ << "n" << SafeId(n); }
534 535 536 537 538 539 540 541 542


void GraphC1Visualizer::PrintNode(Node* n) {
  PrintNodeId(n);
  os_ << " " << *n->op() << " ";
  PrintInputs(n);
}


543 544
template <typename InputIterator>
void GraphC1Visualizer::PrintInputs(InputIterator* i, int count,
545 546 547 548 549 550 551 552 553 554 555 556 557 558
                                    const char* prefix) {
  if (count > 0) {
    os_ << prefix;
  }
  while (count > 0) {
    os_ << " ";
    PrintNodeId(**i);
    ++(*i);
    count--;
  }
}


void GraphC1Visualizer::PrintInputs(Node* node) {
danno's avatar
danno committed
559
  auto i = node->inputs().begin();
560
  PrintInputs(&i, node->op()->ValueInputCount(), " ");
561 562 563 564
  PrintInputs(&i, OperatorProperties::GetContextInputCount(node->op()),
              " Ctx:");
  PrintInputs(&i, OperatorProperties::GetFrameStateInputCount(node->op()),
              " FS:");
565 566
  PrintInputs(&i, node->op()->EffectInputCount(), " Eff:");
  PrintInputs(&i, node->op()->ControlInputCount(), " Ctrl:");
567 568 569 570
}


void GraphC1Visualizer::PrintType(Node* node) {
571
  if (NodeProperties::IsTyped(node)) {
572
    Type type = NodeProperties::GetType(node);
573
    os_ << " type:" << type;
574
  }
575 576 577 578 579 580 581 582 583 584 585 586 587
}


void GraphC1Visualizer::PrintSchedule(const char* phase,
                                      const Schedule* schedule,
                                      const SourcePositionTable* positions,
                                      const InstructionSequence* instructions) {
  Tag tag(this, "cfg");
  PrintStringProperty("name", phase);
  const BasicBlockVector* rpo = schedule->rpo_order();
  for (size_t i = 0; i < rpo->size(); i++) {
    BasicBlock* current = (*rpo)[i];
    Tag block_tag(this, "block");
588
    PrintBlockProperty("name", current->rpo_number());
589 590 591 592 593
    PrintIntProperty("from_bci", -1);
    PrintIntProperty("to_bci", -1);

    PrintIndent();
    os_ << "predecessors";
594
    for (BasicBlock* predecessor : current->predecessors()) {
595
      os_ << " \"B" << predecessor->rpo_number() << "\"";
596 597 598 599 600
    }
    os_ << "\n";

    PrintIndent();
    os_ << "successors";
601
    for (BasicBlock* successor : current->successors()) {
602
      os_ << " \"B" << successor->rpo_number() << "\"";
603 604 605 606 607 608 609 610 611
    }
    os_ << "\n";

    PrintIndent();
    os_ << "xhandlers\n";

    PrintIndent();
    os_ << "flags\n";

612
    if (current->dominator() != nullptr) {
613
      PrintBlockProperty("dominator", current->dominator()->rpo_number());
614 615 616 617
    }

    PrintIntProperty("loop_depth", current->loop_depth());

618
    const InstructionBlock* instruction_block =
619 620
        instructions->InstructionBlockAt(
            RpoNumber::FromInt(current->rpo_number()));
621 622 623
    if (instruction_block->code_start() >= 0) {
      int first_index = instruction_block->first_instruction_index();
      int last_index = instruction_block->last_instruction_index();
624 625
      PrintIntProperty(
          "first_lir_id",
626
          LifetimePosition::GapFromInstructionIndex(first_index).value());
627 628
      PrintIntProperty("last_lir_id",
                       LifetimePosition::InstructionFromInstructionIndex(
629
                           last_index).value());
630 631 632 633 634 635
    }

    {
      Tag states_tag(this, "states");
      Tag locals_tag(this, "locals");
      int total = 0;
636 637 638
      for (BasicBlock::const_iterator it = current->begin();
           it != current->end(); ++it) {
        if ((*it)->opcode() == IrOpcode::kPhi) total++;
639 640 641 642
      }
      PrintIntProperty("size", total);
      PrintStringProperty("method", "None");
      int index = 0;
643 644 645
      for (BasicBlock::const_iterator it = current->begin();
           it != current->end(); ++it) {
        if ((*it)->opcode() != IrOpcode::kPhi) continue;
646 647
        PrintIndent();
        os_ << index << " ";
648
        PrintNodeId(*it);
649
        os_ << " [";
650
        PrintInputs(*it);
651 652 653 654 655 656 657
        os_ << "]\n";
        index++;
      }
    }

    {
      Tag HIR_tag(this, "HIR");
658 659 660
      for (BasicBlock::const_iterator it = current->begin();
           it != current->end(); ++it) {
        Node* node = *it;
661 662 663 664 665 666 667 668 669
        if (node->opcode() == IrOpcode::kPhi) continue;
        int uses = node->UseCount();
        PrintIndent();
        os_ << "0 " << uses << " ";
        PrintNode(node);
        if (FLAG_trace_turbo_types) {
          os_ << " ";
          PrintType(node);
        }
670
        if (positions != nullptr) {
671
          SourcePosition position = positions->GetSourcePosition(node);
672
          if (position.IsKnown()) {
673
            os_ << " pos:";
674 675 676
            if (position.isInlined()) {
              os_ << "inlining(" << position.InliningId() << "),";
            }
677
            os_ << position.ScriptOffset();
678 679 680 681 682 683 684 685 686
          }
        }
        os_ << " <|@\n";
      }

      BasicBlock::Control control = current->control();
      if (control != BasicBlock::kNone) {
        PrintIndent();
        os_ << "0 0 ";
687
        if (current->control_input() != nullptr) {
688 689
          PrintNode(current->control_input());
        } else {
690
          os_ << -1 - current->rpo_number() << " Goto";
691 692
        }
        os_ << " ->";
693
        for (BasicBlock* successor : current->successors()) {
694
          os_ << " B" << successor->rpo_number();
695
        }
696
        if (FLAG_trace_turbo_types && current->control_input() != nullptr) {
697 698 699 700 701 702 703
          os_ << " ";
          PrintType(current->control_input());
        }
        os_ << " <|@\n";
      }
    }

704
    if (instructions != nullptr) {
705
      Tag LIR_tag(this, "LIR");
706 707
      for (int j = instruction_block->first_instruction_index();
           j <= instruction_block->last_instruction_index(); j++) {
708
        PrintIndent();
709
        os_ << j << " " << *instructions->InstructionAt(j) << " <|@\n";
710 711 712 713 714
      }
    }
  }
}

715 716
void GraphC1Visualizer::PrintLiveRanges(
    const char* phase, const TopTierRegisterAllocationData* data) {
717 718 719
  Tag tag(this, "intervals");
  PrintStringProperty("name", phase);

720
  for (const TopLevelLiveRange* range : data->fixed_double_live_ranges()) {
721
    PrintLiveRangeChain(range, "fixed");
722 723
  }

724
  for (const TopLevelLiveRange* range : data->fixed_live_ranges()) {
725
    PrintLiveRangeChain(range, "fixed");
726 727
  }

728
  for (const TopLevelLiveRange* range : data->live_ranges()) {
729 730 731 732
    PrintLiveRangeChain(range, "object");
  }
}

733
void GraphC1Visualizer::PrintLiveRangeChain(const TopLevelLiveRange* range,
734
                                            const char* type) {
735
  if (range == nullptr || range->IsEmpty()) return;
736
  int vreg = range->vreg();
737 738
  for (const LiveRange* child = range; child != nullptr;
       child = child->next()) {
739
    PrintLiveRange(child, type, vreg);
740 741 742
  }
}

743
void GraphC1Visualizer::PrintLiveRange(const LiveRange* range, const char* type,
744
                                       int vreg) {
745
  if (range != nullptr && !range->IsEmpty()) {
746
    PrintIndent();
747
    os_ << vreg << ":" << range->relative_id() << " " << type;
748
    if (range->HasRegisterAssigned()) {
749
      AllocatedOperand op = AllocatedOperand::cast(range->GetAssignedOperand());
750
      if (op.IsRegister()) {
751
        os_ << " \"" << Register::from_code(op.register_code()) << "\"";
752
      } else if (op.IsDoubleRegister()) {
753
        os_ << " \"" << DoubleRegister::from_code(op.register_code()) << "\"";
754
      } else if (op.IsFloatRegister()) {
755
        os_ << " \"" << FloatRegister::from_code(op.register_code()) << "\"";
756 757 758
      } else {
        DCHECK(op.IsSimd128Register());
        os_ << " \"" << Simd128Register::from_code(op.register_code()) << "\"";
759
      }
760
    } else if (range->spilled()) {
761
      const TopLevelLiveRange* top = range->TopLevel();
762
      int index = -1;
763
      if (top->HasSpillRange()) {
764
        index = kMaxInt;  // This hasn't been set yet.
765 766 767 768
      } else if (top->GetSpillOperand()->IsConstant()) {
        os_ << " \"const(nostack):"
            << ConstantOperand::cast(top->GetSpillOperand())->virtual_register()
            << "\"";
769
      } else {
770
        index = AllocatedOperand::cast(top->GetSpillOperand())->index();
771 772 773
        if (IsFloatingPoint(top->representation())) {
          os_ << " \"fp_stack:" << index << "\"";
        } else {
774 775
          os_ << " \"stack:" << index << "\"";
        }
776 777
      }
    }
778

779 780
    const TopLevelLiveRange* parent = range->TopLevel();
    os_ << " " << parent->vreg() << ":" << parent->relative_id();
781 782

    // TODO(herhut) Find something useful to print for the hint field
783 784 785 786 787
    if (range->get_bundle() != nullptr) {
      os_ << " B" << range->get_bundle()->id();
    } else {
      os_ << " unknown";
    }
788

789 790
    for (const UseInterval* interval = range->first_interval();
         interval != nullptr; interval = interval->next()) {
791 792
      os_ << " [" << interval->start().value() << ", "
          << interval->end().value() << "[";
793 794 795
    }

    UsePosition* current_pos = range->first_pos();
796
    while (current_pos != nullptr) {
797
      if (current_pos->RegisterIsBeneficial() || FLAG_trace_all_uses) {
798
        os_ << " " << current_pos->pos().value() << " M";
799 800 801 802 803 804 805 806 807 808
      }
      current_pos = current_pos->next();
    }

    os_ << " \"\"\n";
  }
}


std::ostream& operator<<(std::ostream& os, const AsC1VCompilation& ac) {
809
  AccountingAllocator allocator;
810
  Zone tmp_zone(&allocator, ZONE_NAME);
811 812 813 814 815 816
  GraphC1Visualizer(os, &tmp_zone).PrintCompilation(ac.info_);
  return os;
}


std::ostream& operator<<(std::ostream& os, const AsC1V& ac) {
817
  AccountingAllocator allocator;
818
  Zone tmp_zone(&allocator, ZONE_NAME);
819 820 821 822 823 824
  GraphC1Visualizer(os, &tmp_zone)
      .PrintSchedule(ac.phase_, ac.schedule_, ac.positions_, ac.instructions_);
  return os;
}


825 826
std::ostream& operator<<(std::ostream& os,
                         const AsC1VRegisterAllocationData& ac) {
827 828 829 830 831 832 833 834
  // TODO(rmcilroy): Add support for fast register allocator.
  if (ac.data_->type() == RegisterAllocationData::kTopTier) {
    AccountingAllocator allocator;
    Zone tmp_zone(&allocator, ZONE_NAME);
    GraphC1Visualizer(os, &tmp_zone)
        .PrintLiveRanges(ac.phase_,
                         TopTierRegisterAllocationData::cast(ac.data_));
  }
835 836
  return os;
}
837 838 839 840 841 842

const int kUnvisited = 0;
const int kOnStack = 1;
const int kVisited = 2;

std::ostream& operator<<(std::ostream& os, const AsRPO& ar) {
843
  AccountingAllocator allocator;
844
  Zone local_zone(&allocator, ZONE_NAME);
845 846 847 848 849 850 851 852 853 854 855 856 857 858

  // Do a post-order depth-first search on the RPO graph. For every node,
  // print:
  //
  //   - the node id
  //   - the operator mnemonic
  //   - in square brackets its parameter (if present)
  //   - in parentheses the list of argument ids and their mnemonics
  //   - the node type (if it is typed)

  // Post-order guarantees that all inputs of a node will be printed before
  // the node itself, if there are no cycles. Any cycles are broken
  // arbitrarily.

859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
  ZoneVector<byte> state(ar.graph.NodeCount(), kUnvisited, &local_zone);
  ZoneStack<Node*> stack(&local_zone);

  stack.push(ar.graph.end());
  state[ar.graph.end()->id()] = kOnStack;
  while (!stack.empty()) {
    Node* n = stack.top();
    bool pop = true;
    for (Node* const i : n->inputs()) {
      if (state[i->id()] == kUnvisited) {
        state[i->id()] = kOnStack;
        stack.push(i);
        pop = false;
        break;
      }
    }
    if (pop) {
      state[n->id()] = kVisited;
      stack.pop();
878
      os << "#" << n->id() << ":" << *n->op() << "(";
879
      // Print the inputs.
880 881 882 883 884
      int j = 0;
      for (Node* const i : n->inputs()) {
        if (j++ > 0) os << ", ";
        os << "#" << SafeId(i) << ":" << SafeMnemonic(i);
      }
885
      os << ")";
886
      // Print the node type, if any.
887
      if (NodeProperties::IsTyped(n)) {
888
        os << "  [Type: " << NodeProperties::GetType(n) << "]";
889 890
      }
      os << std::endl;
891 892 893 894
    }
  }
  return os;
}
895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916

namespace {

void PrintIndent(std::ostream& os, int indent) {
  os << "     ";
  for (int i = 0; i < indent; i++) {
    os << ". ";
  }
}

void PrintScheduledNode(std::ostream& os, int indent, Node* n) {
  PrintIndent(os, indent);
  os << "#" << n->id() << ":" << *n->op() << "(";
  // Print the inputs.
  int j = 0;
  for (Node* const i : n->inputs()) {
    if (j++ > 0) os << ", ";
    os << "#" << SafeId(i) << ":" << SafeMnemonic(i);
  }
  os << ")";
  // Print the node type, if any.
  if (NodeProperties::IsTyped(n)) {
917
    os << "  [Type: " << NodeProperties::GetType(n) << "]";
918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
  }
}

void PrintScheduledGraph(std::ostream& os, const Schedule* schedule) {
  const BasicBlockVector* rpo = schedule->rpo_order();
  for (size_t i = 0; i < rpo->size(); i++) {
    BasicBlock* current = (*rpo)[i];
    int indent = current->loop_depth();

    os << "  + Block B" << current->rpo_number() << " (pred:";
    for (BasicBlock* predecessor : current->predecessors()) {
      os << " B" << predecessor->rpo_number();
    }
    if (current->IsLoopHeader()) {
      os << ", loop until B" << current->loop_end()->rpo_number();
    } else if (current->loop_header()) {
      os << ", in loop B" << current->loop_header()->rpo_number();
    }
    os << ")" << std::endl;

938 939 940
    for (BasicBlock::const_iterator it = current->begin(); it != current->end();
         ++it) {
      Node* node = *it;
941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
      PrintScheduledNode(os, indent, node);
      os << std::endl;
    }

    if (current->SuccessorCount() > 0) {
      if (current->control_input() != nullptr) {
        PrintScheduledNode(os, indent, current->control_input());
      } else {
        PrintIndent(os, indent);
        os << "Goto";
      }
      os << " ->";

      bool isFirst = true;
      for (BasicBlock* successor : current->successors()) {
        if (isFirst) {
          isFirst = false;
        } else {
          os << ",";
        }
        os << " B" << successor->rpo_number();
      }
      os << std::endl;
    } else {
965
      DCHECK_NULL(current->control_input());
966 967 968 969 970 971
    }
  }
}

}  // namespace

972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002
std::ostream& operator<<(std::ostream& os,
                         const LiveRangeAsJSON& live_range_json) {
  const LiveRange& range = live_range_json.range_;
  os << "{\"id\":" << range.relative_id() << ",\"type\":";
  if (range.HasRegisterAssigned()) {
    const InstructionOperand op = range.GetAssignedOperand();
    os << "\"assigned\",\"op\":"
       << InstructionOperandAsJSON{&op, &(live_range_json.code_)};
  } else if (range.spilled() && !range.TopLevel()->HasNoSpillType()) {
    const TopLevelLiveRange* top = range.TopLevel();
    if (top->HasSpillOperand()) {
      os << "\"assigned\",\"op\":"
         << InstructionOperandAsJSON{top->GetSpillOperand(),
                                     &(live_range_json.code_)};
    } else {
      int index = top->GetSpillRange()->assigned_slot();
      os << "\"spilled\",\"op\":";
      if (IsFloatingPoint(top->representation())) {
        os << "\"fp_stack:" << index << "\"";
      } else {
        os << "\"stack:" << index << "\"";
      }
    }
  } else {
    os << "\"none\"";
  }

  os << ",\"intervals\":[";
  bool first = true;
  for (const UseInterval* interval = range.first_interval();
       interval != nullptr; interval = interval->next()) {
1003 1004 1005 1006 1007
    if (first) {
      first = false;
    } else {
      os << ",";
    }
1008 1009 1010 1011
    os << "[" << interval->start().value() << "," << interval->end().value()
       << "]";
  }

1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023
  os << "],\"uses\":[";
  first = true;
  for (UsePosition* current_pos = range.first_pos(); current_pos != nullptr;
       current_pos = current_pos->next()) {
    if (first) {
      first = false;
    } else {
      os << ",";
    }
    os << current_pos->pos().value();
  }

1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
  os << "]}";
  return os;
}

std::ostream& operator<<(
    std::ostream& os,
    const TopLevelLiveRangeAsJSON& top_level_live_range_json) {
  int vreg = top_level_live_range_json.range_.vreg();
  bool first = true;
  os << "\"" << (vreg > 0 ? vreg : -vreg) << "\":{ \"child_ranges\":[";
  for (const LiveRange* child = &(top_level_live_range_json.range_);
       child != nullptr; child = child->next()) {
    if (!top_level_live_range_json.range_.IsEmpty()) {
1037 1038 1039 1040 1041
      if (first) {
        first = false;
      } else {
        os << ",";
      }
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061
      os << LiveRangeAsJSON{*child, top_level_live_range_json.code_};
    }
  }
  os << "]";
  if (top_level_live_range_json.range_.IsFixed()) {
    os << ", \"is_deferred\": "
       << (top_level_live_range_json.range_.IsDeferredFixed() ? "true"
                                                              : "false");
  }
  os << "}";
  return os;
}

void PrintTopLevelLiveRanges(std::ostream& os,
                             const ZoneVector<TopLevelLiveRange*> ranges,
                             const InstructionSequence& code) {
  bool first = true;
  os << "{";
  for (const TopLevelLiveRange* range : ranges) {
    if (range != nullptr && !range->IsEmpty()) {
1062 1063 1064 1065 1066
      if (first) {
        first = false;
      } else {
        os << ",";
      }
1067 1068 1069 1070 1071 1072 1073 1074
      os << TopLevelLiveRangeAsJSON{*range, code};
    }
  }
  os << "}";
}

std::ostream& operator<<(std::ostream& os,
                         const RegisterAllocationDataAsJSON& ac) {
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090
  if (ac.data_.type() == RegisterAllocationData::kTopTier) {
    const TopTierRegisterAllocationData& ac_data =
        TopTierRegisterAllocationData::cast(ac.data_);
    os << "\"fixed_double_live_ranges\": ";
    PrintTopLevelLiveRanges(os, ac_data.fixed_double_live_ranges(), ac.code_);
    os << ",\"fixed_live_ranges\": ";
    PrintTopLevelLiveRanges(os, ac_data.fixed_live_ranges(), ac.code_);
    os << ",\"live_ranges\": ";
    PrintTopLevelLiveRanges(os, ac_data.live_ranges(), ac.code_);
  } else {
    // TODO(rmcilroy): Add support for fast register allocation data. For now
    // output the expected fields to keep Turbolizer happy.
    os << "\"fixed_double_live_ranges\": {}";
    os << ",\"fixed_live_ranges\": {}";
    os << ",\"live_ranges\": {}";
  }
1091 1092 1093
  return os;
}

1094 1095 1096 1097 1098
std::ostream& operator<<(std::ostream& os, const AsScheduledGraph& scheduled) {
  PrintScheduledGraph(os, scheduled.schedule);
  return os;
}

1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
std::ostream& operator<<(std::ostream& os, const InstructionOperandAsJSON& o) {
  const InstructionOperand* op = o.op_;
  const InstructionSequence* code = o.code_;
  os << "{";
  switch (op->kind()) {
    case InstructionOperand::UNALLOCATED: {
      const UnallocatedOperand* unalloc = UnallocatedOperand::cast(op);
      os << "\"type\": \"unallocated\", ";
      os << "\"text\": \"v" << unalloc->virtual_register() << "\"";
      if (unalloc->basic_policy() == UnallocatedOperand::FIXED_SLOT) {
        os << ",\"tooltip\": \"FIXED_SLOT: " << unalloc->fixed_slot_index()
           << "\"";
        break;
      }
      switch (unalloc->extended_policy()) {
        case UnallocatedOperand::NONE:
          break;
        case UnallocatedOperand::FIXED_REGISTER: {
          os << ",\"tooltip\": \"FIXED_REGISTER: "
1118
             << Register::from_code(unalloc->fixed_register_index()) << "\"";
1119 1120 1121 1122
          break;
        }
        case UnallocatedOperand::FIXED_FP_REGISTER: {
          os << ",\"tooltip\": \"FIXED_FP_REGISTER: "
1123
             << DoubleRegister::from_code(unalloc->fixed_register_index())
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134
             << "\"";
          break;
        }
        case UnallocatedOperand::MUST_HAVE_REGISTER: {
          os << ",\"tooltip\": \"MUST_HAVE_REGISTER\"";
          break;
        }
        case UnallocatedOperand::MUST_HAVE_SLOT: {
          os << ",\"tooltip\": \"MUST_HAVE_SLOT\"";
          break;
        }
1135 1136 1137
        case UnallocatedOperand::SAME_AS_INPUT: {
          os << ",\"tooltip\": \"SAME_AS_INPUT: " << unalloc->input_index()
             << "\"";
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167
          break;
        }
        case UnallocatedOperand::REGISTER_OR_SLOT: {
          os << ",\"tooltip\": \"REGISTER_OR_SLOT\"";
          break;
        }
        case UnallocatedOperand::REGISTER_OR_SLOT_OR_CONSTANT: {
          os << ",\"tooltip\": \"REGISTER_OR_SLOT_OR_CONSTANT\"";
          break;
        }
      }
      break;
    }
    case InstructionOperand::CONSTANT: {
      int vreg = ConstantOperand::cast(op)->virtual_register();
      os << "\"type\": \"constant\", ";
      os << "\"text\": \"v" << vreg << "\",";
      os << "\"tooltip\": \"";
      std::stringstream tooltip;
      tooltip << code->GetConstant(vreg);
      for (const auto& c : tooltip.str()) {
        os << AsEscapedUC16ForJSON(c);
      }
      os << "\"";
      break;
    }
    case InstructionOperand::IMMEDIATE: {
      os << "\"type\": \"immediate\", ";
      const ImmediateOperand* imm = ImmediateOperand::cast(op);
      switch (imm->type()) {
1168 1169
        case ImmediateOperand::INLINE_INT32: {
          os << "\"text\": \"#" << imm->inline_int32_value() << "\"";
1170 1171
          break;
        }
1172 1173 1174 1175 1176 1177
        case ImmediateOperand::INLINE_INT64: {
          os << "\"text\": \"#" << imm->inline_int64_value() << "\"";
          break;
        }
        case ImmediateOperand::INDEXED_RPO:
        case ImmediateOperand::INDEXED_IMM: {
1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193
          int index = imm->indexed_value();
          os << "\"text\": \"imm:" << index << "\",";
          os << "\"tooltip\": \"";
          std::stringstream tooltip;
          tooltip << code->GetImmediate(imm);
          for (const auto& c : tooltip.str()) {
            os << AsEscapedUC16ForJSON(c);
          }
          os << "\"";
          break;
        }
      }
      break;
    }
    case InstructionOperand::ALLOCATED: {
      const LocationOperand* allocated = LocationOperand::cast(op);
1194
      os << "\"type\": \"allocated\", ";
1195 1196 1197 1198 1199 1200
      os << "\"text\": \"";
      if (op->IsStackSlot()) {
        os << "stack:" << allocated->index();
      } else if (op->IsFPStackSlot()) {
        os << "fp_stack:" << allocated->index();
      } else if (op->IsRegister()) {
1201 1202 1203
        if (allocated->register_code() < Register::kNumRegisters) {
          os << Register::from_code(allocated->register_code());
        } else {
1204
          os << Register::GetSpecialRegisterName(allocated->register_code());
1205
        }
1206
      } else if (op->IsDoubleRegister()) {
1207
        os << DoubleRegister::from_code(allocated->register_code());
1208
      } else if (op->IsFloatRegister()) {
1209
        os << FloatRegister::from_code(allocated->register_code());
1210 1211
      } else {
        DCHECK(op->IsSimd128Register());
1212
        os << Simd128Register::from_code(allocated->register_code());
1213 1214 1215 1216 1217 1218
      }
      os << "\",";
      os << "\"tooltip\": \""
         << MachineReprToString(allocated->representation()) << "\"";
      break;
    }
1219
    case InstructionOperand::PENDING:
1220 1221 1222 1223 1224 1225 1226
    case InstructionOperand::INVALID:
      UNREACHABLE();
  }
  os << "}";
  return os;
}

1227 1228
std::ostream& operator<<(std::ostream& os, const InstructionAsJSON& i_json) {
  const Instruction* instr = i_json.instr_;
1229 1230

  os << "{";
1231
  os << "\"id\": " << i_json.index_ << ",";
1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
  os << "\"opcode\": \"" << ArchOpcodeField::decode(instr->opcode()) << "\",";
  os << "\"flags\": \"";
  FlagsMode fm = FlagsModeField::decode(instr->opcode());
  AddressingMode am = AddressingModeField::decode(instr->opcode());
  if (am != kMode_None) {
    os << " : " << AddressingModeField::decode(instr->opcode());
  }
  if (fm != kFlags_none) {
    os << " && " << fm << " if "
       << FlagsConditionField::decode(instr->opcode());
  }
  os << "\",";

  os << "\"gaps\": [";
  for (int i = Instruction::FIRST_GAP_POSITION;
       i <= Instruction::LAST_GAP_POSITION; i++) {
    if (i != Instruction::FIRST_GAP_POSITION) os << ",";
    os << "[";
    const ParallelMove* pm = instr->parallel_moves()[i];
    if (pm == nullptr) {
      os << "]";
      continue;
    }
    bool first = true;
    for (MoveOperands* move : *pm) {
      if (move->IsEliminated()) continue;
1258 1259 1260 1261 1262
      if (first) {
        first = false;
      } else {
        os << ",";
      }
1263 1264 1265
      os << "[" << InstructionOperandAsJSON{&move->destination(), i_json.code_}
         << "," << InstructionOperandAsJSON{&move->source(), i_json.code_}
         << "]";
1266 1267 1268 1269 1270 1271 1272 1273 1274 1275
    }
    os << "]";
  }
  os << "],";

  os << "\"outputs\": [";
  bool need_comma = false;
  for (size_t i = 0; i < instr->OutputCount(); i++) {
    if (need_comma) os << ",";
    need_comma = true;
1276
    os << InstructionOperandAsJSON{instr->OutputAt(i), i_json.code_};
1277 1278 1279 1280 1281 1282 1283 1284
  }
  os << "],";

  os << "\"inputs\": [";
  need_comma = false;
  for (size_t i = 0; i < instr->InputCount(); i++) {
    if (need_comma) os << ",";
    need_comma = true;
1285
    os << InstructionOperandAsJSON{instr->InputAt(i), i_json.code_};
1286 1287 1288 1289 1290 1291 1292 1293
  }
  os << "],";

  os << "\"temps\": [";
  need_comma = false;
  for (size_t i = 0; i < instr->TempCount(); i++) {
    if (need_comma) os << ",";
    need_comma = true;
1294
    os << InstructionOperandAsJSON{instr->TempAt(i), i_json.code_};
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306
  }
  os << "]";
  os << "}";

  return os;
}

std::ostream& operator<<(std::ostream& os, const InstructionBlockAsJSON& b) {
  const InstructionBlock* block = b.block_;
  const InstructionSequence* code = b.code_;
  os << "{";
  os << "\"id\": " << block->rpo_number() << ",";
1307 1308
  os << "\"deferred\": " << (block->IsDeferred() ? "true" : "false");
  os << ",";
1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
  os << "\"loop_header\": " << block->IsLoopHeader() << ",";
  if (block->IsLoopHeader()) {
    os << "\"loop_end\": " << block->loop_end() << ",";
  }
  os << "\"predecessors\": [";
  bool need_comma = false;
  for (RpoNumber pred : block->predecessors()) {
    if (need_comma) os << ",";
    need_comma = true;
    os << pred.ToInt();
  }
  os << "],";
  os << "\"successors\": [";
  need_comma = false;
  for (RpoNumber succ : block->successors()) {
    if (need_comma) os << ",";
    need_comma = true;
    os << succ.ToInt();
  }
  os << "],";
  os << "\"phis\": [";
  bool needs_comma = false;
1331
  InstructionOperandAsJSON json_op = {nullptr, code};
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348
  for (const PhiInstruction* phi : block->phis()) {
    if (needs_comma) os << ",";
    needs_comma = true;
    json_op.op_ = &phi->output();
    os << "{\"output\" : " << json_op << ",";
    os << "\"operands\": [";
    bool op_needs_comma = false;
    for (int input : phi->operands()) {
      if (op_needs_comma) os << ",";
      op_needs_comma = true;
      os << "\"v" << input << "\"";
    }
    os << "]}";
  }
  os << "],";

  os << "\"instructions\": [";
1349
  InstructionAsJSON json_instr = {-1, nullptr, code};
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367
  need_comma = false;
  for (int j = block->first_instruction_index();
       j <= block->last_instruction_index(); j++) {
    if (need_comma) os << ",";
    need_comma = true;
    json_instr.index_ = j;
    json_instr.instr_ = code->InstructionAt(j);
    os << json_instr;
  }
  os << "]";
  os << "}";

  return os;
}

std::ostream& operator<<(std::ostream& os, const InstructionSequenceAsJSON& s) {
  const InstructionSequence* code = s.sequence_;

1368
  os << "[";
1369 1370 1371 1372 1373

  bool need_comma = false;
  for (int i = 0; i < code->InstructionBlockCount(); i++) {
    if (need_comma) os << ",";
    need_comma = true;
1374 1375
    os << InstructionBlockAsJSON{
        code->InstructionBlockAt(RpoNumber::FromInt(i)), code};
1376 1377 1378 1379 1380 1381
  }
  os << "]";

  return os;
}

1382 1383 1384
}  // namespace compiler
}  // namespace internal
}  // namespace v8