inst_block_stack.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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/inst_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/inst.h"
  9. namespace Carbon::Check {
  10. auto InstBlockStack::Push(SemIR::InstBlockId 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 InstBlockStack::PeekOrAdd(int depth) -> SemIR::InstBlockId {
  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 = sem_ir_->inst_blocks().AddDefaultValue();
  26. }
  27. return slot.id;
  28. }
  29. auto InstBlockStack::Pop() -> SemIR::InstBlockId {
  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::InstBlockId::Unreachable) {
  35. if (back.id.is_valid()) {
  36. sem_ir_->inst_blocks().Set(back.id, back.content);
  37. } else {
  38. back.id = sem_ir_->inst_blocks().Add(back.content);
  39. }
  40. }
  41. CARBON_VLOG() << name_ << " Pop " << size_ << ": " << back.id << "\n";
  42. if (!back.id.is_valid()) {
  43. return SemIR::InstBlockId::Empty;
  44. }
  45. return back.id;
  46. }
  47. auto InstBlockStack::PopAndDiscard() -> void {
  48. CARBON_CHECK(!empty()) << "no current block";
  49. --size_;
  50. CARBON_VLOG() << name_ << " PopAndDiscard " << size_ << "\n";
  51. }
  52. auto InstBlockStack::PrintForStackDump(llvm::raw_ostream& output) const
  53. -> void {
  54. output << name_ << ":\n";
  55. for (const auto& [i, entry] : llvm::enumerate(stack_)) {
  56. output << "\t" << i << ".\t" << entry.id << "\t{";
  57. llvm::ListSeparator sep;
  58. for (auto id : entry.content) {
  59. output << sep << id;
  60. }
  61. output << "}\n";
  62. }
  63. }
  64. } // namespace Carbon::Check