1// Copyright 2022 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.
4
5#ifndef V8_MAGLEV_MAGLEV_GRAPH_LABELLER_H_
6#define V8_MAGLEV_MAGLEV_GRAPH_LABELLER_H_
7
8#include <map>
9
10#include "src/maglev/maglev-graph.h"
11#include "src/maglev/maglev-ir.h"
12
13namespace v8 {
14namespace internal {
15namespace maglev {
16
17class MaglevGraphLabeller {
18 public:
19  void RegisterNode(const Node* node) {
20    if (node_ids_.emplace(node, next_node_id_).second) {
21      next_node_id_++;
22    }
23  }
24  void RegisterBasicBlock(const BasicBlock* block) {
25    block_ids_[block] = next_block_id_++;
26    if (node_ids_.emplace(block->control_node(), next_node_id_).second) {
27      next_node_id_++;
28    }
29  }
30
31  int BlockId(const BasicBlock* block) { return block_ids_[block]; }
32  int NodeId(const NodeBase* node) { return node_ids_[node]; }
33
34  int max_node_id() const { return next_node_id_ - 1; }
35
36  int max_node_id_width() const { return std::ceil(std::log10(max_node_id())); }
37
38  void PrintNodeLabel(std::ostream& os, const Node* node) {
39    auto node_id_it = node_ids_.find(node);
40
41    if (node_id_it == node_ids_.end()) {
42      os << "<invalid node " << node << ">";
43      return;
44    }
45
46    os << "n" << node_id_it->second;
47  }
48
49  void PrintInput(std::ostream& os, const Input& input) {
50    PrintNodeLabel(os, input.node());
51    os << ":" << input.operand();
52  }
53
54 private:
55  std::map<const BasicBlock*, int> block_ids_;
56  std::map<const NodeBase*, int> node_ids_;
57  int next_block_id_ = 1;
58  int next_node_id_ = 1;
59};
60
61}  // namespace maglev
62}  // namespace internal
63}  // namespace v8
64
65#endif  // V8_MAGLEV_MAGLEV_GRAPH_LABELLER_H_
66