inst_block_stack.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. namespace Carbon::Check {
  9. auto InstBlockStack::Push(SemIR::InstBlockId id) -> void {
  10. CARBON_VLOG("{0} Push {1}\n", name_, id_stack_.size());
  11. CARBON_CHECK(id_stack_.size() < (1 << 20),
  12. "Excessive stack size: likely infinite loop");
  13. id_stack_.push_back(id);
  14. insts_stack_.PushArray();
  15. }
  16. auto InstBlockStack::Push(SemIR::InstBlockId id,
  17. llvm::ArrayRef<SemIR::InstId> inst_ids) -> void {
  18. Push(id);
  19. insts_stack_.AppendToTop(inst_ids);
  20. }
  21. auto InstBlockStack::PeekOrAdd(int depth) -> SemIR::InstBlockId {
  22. CARBON_CHECK(static_cast<int>(id_stack_.size()) > depth, "no such block");
  23. int index = id_stack_.size() - depth - 1;
  24. auto& slot = id_stack_[index];
  25. if (!slot.is_valid()) {
  26. slot = sem_ir_->inst_blocks().AddDefaultValue();
  27. }
  28. return slot;
  29. }
  30. auto InstBlockStack::Pop() -> SemIR::InstBlockId {
  31. CARBON_CHECK(!empty(), "no current block");
  32. auto id = id_stack_.pop_back_val();
  33. auto insts = insts_stack_.PeekArray();
  34. // Finalize the block.
  35. if (!insts.empty() && id != SemIR::InstBlockId::Unreachable) {
  36. if (id.is_valid()) {
  37. sem_ir_->inst_blocks().Set(id, insts);
  38. } else {
  39. id = sem_ir_->inst_blocks().Add(insts);
  40. }
  41. }
  42. insts_stack_.PopArray();
  43. CARBON_VLOG("{0} Pop {1}: {2}\n", name_, id_stack_.size(), id);
  44. return id.is_valid() ? id : SemIR::InstBlockId::Empty;
  45. }
  46. auto InstBlockStack::PopAndDiscard() -> void {
  47. CARBON_CHECK(!empty(), "no current block");
  48. id_stack_.pop_back();
  49. insts_stack_.PopArray();
  50. CARBON_VLOG("{0} PopAndDiscard {1}\n", name_, id_stack_.size());
  51. }
  52. auto InstBlockStack::PrintForStackDump(SemIR::Formatter& formatter, int indent,
  53. llvm::raw_ostream& output) const
  54. -> void {
  55. output.indent(indent);
  56. output << name_ << ":\n";
  57. for (const auto& [i, id] : llvm::enumerate(id_stack_)) {
  58. output.indent(indent + 2);
  59. output << i << ". " << id;
  60. formatter.PrintPartialTrailingCodeBlock(insts_stack_.PeekArrayAt(i),
  61. indent + 4, output);
  62. output << "\n";
  63. }
  64. }
  65. } // namespace Carbon::Check