inst_block_stack.cpp 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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.has_value()) {
  26. slot = sem_ir_->inst_blocks().AddPlaceholder();
  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.has_value()) {
  37. sem_ir_->inst_blocks().ReplacePlaceholder(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.has_value() ? 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(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 << ".\t" << id << "\t{";
  60. llvm::ListSeparator sep;
  61. for (auto id : insts_stack_.PeekArrayAt(i)) {
  62. output << sep << id;
  63. }
  64. output << "}\n";
  65. }
  66. }
  67. } // namespace Carbon::Check