node_block_stack.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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::PeekOrAdd(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. }
  27. return slot.id;
  28. }
  29. auto NodeBlockStack::Pop() -> SemIR::NodeBlockId {
  30. CARBON_CHECK(!empty()) << "no current block";
  31. --size_;
  32. auto& back = stack_[size_];
  33. // Finalize the block.
  34. if (!back.content.empty() && back.id != SemIR::NodeBlockId::Unreachable) {
  35. if (back.id.is_valid()) {
  36. semantics_ir_->SetNodeBlock(back.id, back.content);
  37. } else {
  38. back.id = semantics_ir_->AddNodeBlock(back.content);
  39. }
  40. }
  41. CARBON_VLOG() << name_ << " Pop " << size_ << ": " << back.id << "\n";
  42. if (!back.id.is_valid()) {
  43. return SemIR::NodeBlockId::Empty;
  44. }
  45. return back.id;
  46. }
  47. auto NodeBlockStack::PrintForStackDump(llvm::raw_ostream& output) const
  48. -> void {
  49. output << name_ << ":\n";
  50. for (const auto& [i, entry] : llvm::enumerate(stack_)) {
  51. output << "\t" << i << ".\t" << entry.id << "\t{";
  52. llvm::ListSeparator sep;
  53. for (auto id : entry.content) {
  54. output << sep << id;
  55. }
  56. output << "}\n";
  57. }
  58. }
  59. } // namespace Carbon::Check