node_block_stack.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #include "toolchain/check/node_block_stack.h"
  5. #include "common/vlog.h"
  6. #include "llvm/ADT/STLExtras.h"
  7. #include "llvm/ADT/StringExtras.h"
  8. #include "toolchain/sem_ir/node.h"
  9. namespace Carbon::Check {
  10. auto NodeBlockStack::Push(SemIR::NodeBlockId id) -> void {
  11. CARBON_VLOG() << name_ << " Push " << size_ << "\n";
  12. CARBON_CHECK(size_ < (1 << 20))
  13. << "Excessive stack size: likely infinite loop";
  14. if (size_ == static_cast<int>(stack_.size())) {
  15. stack_.emplace_back();
  16. }
  17. stack_[size_].Reset(id);
  18. ++size_;
  19. }
  20. auto NodeBlockStack::PeekForAdd(int depth) -> SemIR::NodeBlockId {
  21. CARBON_CHECK(size() > depth) << "no such block";
  22. int index = size() - depth - 1;
  23. auto& slot = stack_[index];
  24. if (!slot.id.is_valid()) {
  25. slot.id = semantics_ir_->AddNodeBlockId();
  26. CARBON_VLOG() << name_ << " Add " << index << ": " << slot.id << "\n";
  27. }
  28. return slot.id;
  29. }
  30. auto NodeBlockStack::Pop() -> SemIR::NodeBlockId {
  31. CARBON_CHECK(!empty()) << "no current block";
  32. --size_;
  33. auto& back = stack_[size_];
  34. // Finalize the block.
  35. if (!back.content.empty() && back.id != SemIR::NodeBlockId::Unreachable) {
  36. if (back.id.is_valid()) {
  37. semantics_ir_->SetNodeBlock(back.id, back.content);
  38. } else {
  39. back.id = semantics_ir_->AddNodeBlock(back.content);
  40. }
  41. }
  42. CARBON_VLOG() << name_ << " Pop " << size_ << ": " << back.id << "\n";
  43. if (!back.id.is_valid()) {
  44. return SemIR::NodeBlockId::Empty;
  45. }
  46. return back.id;
  47. }
  48. auto NodeBlockStack::PrintForStackDump(llvm::raw_ostream& output) const
  49. -> void {
  50. output << name_ << ":\n";
  51. for (const auto& [i, entry] : llvm::enumerate(stack_)) {
  52. output << "\t" << i << ".\t" << entry.id << "\t{";
  53. llvm::ListSeparator sep;
  54. for (auto id : entry.content) {
  55. output << sep << id;
  56. }
  57. output << "}\n";
  58. }
  59. }
  60. } // namespace Carbon::Check