inst_block_stack.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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() << name_ << " Push " << size_ << "\n";
  11. CARBON_CHECK(size_ < (1 << 20))
  12. << "Excessive stack size: likely infinite loop";
  13. if (size_ == static_cast<int>(stack_.size())) {
  14. stack_.emplace_back();
  15. }
  16. stack_[size_].Reset(id);
  17. ++size_;
  18. }
  19. auto InstBlockStack::PushGlobalInit() -> void {
  20. Push(init_block_id_);
  21. stack_[size_ - 1].content = std::move(init_block_);
  22. }
  23. auto InstBlockStack::PeekOrAdd(int depth) -> SemIR::InstBlockId {
  24. CARBON_CHECK(size_ > depth) << "no such block";
  25. int index = size_ - depth - 1;
  26. auto& slot = stack_[index];
  27. if (!slot.id.is_valid()) {
  28. slot.id = sem_ir_->inst_blocks().AddDefaultValue();
  29. }
  30. return slot.id;
  31. }
  32. auto InstBlockStack::Pop() -> SemIR::InstBlockId {
  33. CARBON_CHECK(!empty()) << "no current block";
  34. --size_;
  35. auto& back = stack_[size_];
  36. // Finalize the block.
  37. if (!back.content.empty() && back.id != SemIR::InstBlockId::Unreachable) {
  38. if (back.id.is_valid()) {
  39. sem_ir_->inst_blocks().Set(back.id, back.content);
  40. } else {
  41. back.id = sem_ir_->inst_blocks().Add(back.content);
  42. }
  43. }
  44. CARBON_VLOG() << name_ << " Pop " << size_ << ": " << back.id << "\n";
  45. if (!back.id.is_valid()) {
  46. return SemIR::InstBlockId::Empty;
  47. }
  48. return back.id;
  49. }
  50. auto InstBlockStack::PopGlobalInit() -> void {
  51. init_block_ = std::move(stack_[size_ - 1].content);
  52. init_block_id_ = stack_[size_ - 1].id;
  53. PopAndDiscard();
  54. }
  55. auto InstBlockStack::PopAndDiscard() -> void {
  56. CARBON_CHECK(!empty()) << "no current block";
  57. --size_;
  58. CARBON_VLOG() << name_ << " PopAndDiscard " << size_ << "\n";
  59. }
  60. auto InstBlockStack::PrintForStackDump(llvm::raw_ostream& output) const
  61. -> void {
  62. output << name_ << ":\n";
  63. for (const auto& [i, entry] : llvm::enumerate(stack_)) {
  64. output << "\t" << i << ".\t" << entry.id << "\t{";
  65. llvm::ListSeparator sep;
  66. for (auto id : entry.content) {
  67. output << sep << id;
  68. }
  69. output << "}\n";
  70. }
  71. }
  72. } // namespace Carbon::Check