block_value_store.h 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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. #ifndef CARBON_TOOLCHAIN_BASE_BLOCK_VALUE_STORE_H_
  5. #define CARBON_TOOLCHAIN_BASE_BLOCK_VALUE_STORE_H_
  6. #include <type_traits>
  7. #include "common/check.h"
  8. #include "common/set.h"
  9. #include "llvm/Support/Allocator.h"
  10. #include "toolchain/base/mem_usage.h"
  11. #include "toolchain/base/value_store.h"
  12. #include "toolchain/base/yaml.h"
  13. namespace Carbon::SemIR {
  14. // Provides a block-based ValueStore, which uses slab allocation of added
  15. // blocks. This allows references to values to outlast vector resizes that might
  16. // otherwise invalidate references.
  17. //
  18. // BlockValueStore is used as-is, but there are also children that expose the
  19. // protected members for type-specific functionality.
  20. template <typename IdT, typename ElementT>
  21. class BlockValueStore : public Yaml::Printable<BlockValueStore<IdT, ElementT>> {
  22. public:
  23. using IdType = IdT;
  24. using ElementType = ElementT;
  25. using RefType = llvm::MutableArrayRef<ElementT>;
  26. using ConstRefType = llvm::ArrayRef<ElementT>;
  27. explicit BlockValueStore(llvm::BumpPtrAllocator& allocator)
  28. : allocator_(&allocator) {
  29. auto empty = RefType();
  30. auto empty_val = canonical_blocks_.Insert(
  31. empty, [&] { return values_.Add(empty); }, KeyContext(this));
  32. CARBON_CHECK(empty_val.key() == IdT::Empty);
  33. }
  34. // Adds a block with the given content, returning an ID to reference it.
  35. auto Add(ConstRefType content) -> IdT {
  36. if (content.empty()) {
  37. return IdT::Empty;
  38. }
  39. return values_.Add(AllocateCopy(content));
  40. }
  41. // Returns the requested block.
  42. auto Get(IdT id) const -> ConstRefType { return values_.Get(id); }
  43. // Returns a mutable view of the requested block. This operation should be
  44. // avoided where possible; we generally want blocks to be immutable once
  45. // created.
  46. auto GetMutable(IdT id) -> RefType { return values_.Get(id); }
  47. // Returns a new block formed by applying `transform(elem_id)` to each element
  48. // in the specified block.
  49. template <typename TransformFnT>
  50. auto Transform(IdT id, TransformFnT transform) -> IdT {
  51. llvm::SmallVector<ElementType> block(llvm::map_range(Get(id), transform));
  52. return Add(block);
  53. }
  54. // Adds a block or finds an existing canonical block with the given content,
  55. // and returns an ID to reference it.
  56. auto AddCanonical(ConstRefType content) -> IdT {
  57. if (content.empty()) {
  58. return IdT::Empty;
  59. }
  60. auto result = canonical_blocks_.Insert(
  61. content, [&] { return Add(content); }, KeyContext(this));
  62. return result.key();
  63. }
  64. // Promotes an existing block ID to a canonical block ID, or returns an
  65. // existing canonical block ID if the block was already added. The specified
  66. // block must not be modified after this point.
  67. auto MakeCanonical(IdT id) -> IdT {
  68. // Get the content first so that we don't have unnecessary translation of
  69. // the `id` into the content during insertion.
  70. auto result = canonical_blocks_.Insert(
  71. Get(id), [id] { return id; }, KeyContext(this));
  72. return result.key();
  73. }
  74. auto OutputYaml() const -> Yaml::OutputMapping {
  75. return Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  76. for (auto [block_id, block] : values_.enumerate()) {
  77. map.Add(PrintToString(block_id),
  78. Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  79. for (auto [i, elem_id] : llvm::enumerate(block)) {
  80. map.Add(llvm::itostr(i), Yaml::OutputScalar(elem_id));
  81. }
  82. }));
  83. }
  84. });
  85. }
  86. // Collects memory usage of members.
  87. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  88. -> void {
  89. mem_usage.Collect(MemUsage::ConcatLabel(label, "values_"), values_);
  90. mem_usage.Collect(MemUsage::ConcatLabel(label, "canonical_blocks_"),
  91. canonical_blocks_, KeyContext(this));
  92. }
  93. auto size() const -> int { return values_.size(); }
  94. protected:
  95. // Allocates a copy of the given data using our slab allocator.
  96. auto AllocateCopy(ConstRefType data) -> RefType {
  97. auto result = AllocateUninitialized(data.size());
  98. std::uninitialized_copy(data.begin(), data.end(), result.begin());
  99. return result;
  100. }
  101. // Allocates an uninitialized array using our slab allocator.
  102. auto AllocateUninitialized(size_t size) -> RefType {
  103. // We're not going to run a destructor, so ensure that's OK.
  104. static_assert(std::is_trivially_destructible_v<ElementType>);
  105. auto storage = static_cast<ElementType*>(
  106. allocator_->Allocate(size * sizeof(ElementType), alignof(ElementType)));
  107. return RefType(storage, size);
  108. }
  109. // Allow children to have more complex value handling.
  110. auto values() -> ValueStore<IdT, RefType>& { return values_; }
  111. private:
  112. class KeyContext;
  113. llvm::BumpPtrAllocator* allocator_;
  114. ValueStore<IdT, RefType> values_;
  115. Set<IdT, /*SmallSize=*/0, KeyContext> canonical_blocks_;
  116. };
  117. template <typename IdT, typename ElementT>
  118. class BlockValueStore<IdT, ElementT>::KeyContext
  119. : public TranslatingKeyContext<KeyContext> {
  120. public:
  121. explicit KeyContext(const BlockValueStore* store) : store_(store) {}
  122. auto TranslateKey(IdT id) const -> ConstRefType { return store_->Get(id); }
  123. private:
  124. const BlockValueStore* store_;
  125. };
  126. } // namespace Carbon::SemIR
  127. #endif // CARBON_TOOLCHAIN_BASE_BLOCK_VALUE_STORE_H_