block_value_store.h 5.5 KB

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