inst_block_stack.cpp 2.1 KB

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