Skip to content

Commit da8c9d6

Browse files
authored
Avoid reallocation in RelationalValueStore (#6399)
Since `ValueStore` now separates its id and value types as two template parameters, we can use a `ValueStore` of `optional<ValueType>` as the storage instead of a `SmallVector`.
1 parent 7a400d2 commit da8c9d6

File tree

1 file changed

+6
-13
lines changed

1 file changed

+6
-13
lines changed

toolchain/base/relational_value_store.h

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88
#include <optional>
99

1010
#include "common/check.h"
11-
#include "llvm/ADT/SmallVector.h"
1211
#include "toolchain/base/value_store.h"
1312
#include "toolchain/base/value_store_types.h"
1413

@@ -40,16 +39,14 @@ class RelationalValueStore {
4039
using ConstRefType = ValueStoreTypes<ValueT>::ConstRefType;
4140

4241
explicit RelationalValueStore(const RelatedStoreT* related_store)
43-
: related_store_(related_store) {}
42+
: values_(related_store->GetIdTag()), related_store_(related_store) {}
4443

4544
// Given the related ID and a value, stores the value and returns a mapped ID
4645
// to reference it in the store.
4746
auto Add(RelatedIdType related_id, ValueType value) -> IdT {
4847
auto related_index = related_store_->GetRawIndex(related_id);
49-
if (static_cast<size_t>(related_index) >= values_.size()) {
50-
values_.resize(related_index + 1);
51-
}
52-
auto& opt = values_[related_index];
48+
values_.Resize(related_index + 1, std::nullopt);
49+
auto& opt = values_.Get(related_id);
5350
CARBON_CHECK(!opt.has_value(),
5451
"Add with `related_id` that was already added to the store");
5552
opt.emplace(std::move(value));
@@ -63,7 +60,7 @@ class RelationalValueStore {
6360
if (static_cast<size_t>(related_index) >= values_.size()) {
6461
return IdT::None;
6562
}
66-
auto& opt = values_[related_index];
63+
auto& opt = values_.Get(related_id);
6764
if (!opt.has_value()) {
6865
return IdT::None;
6966
}
@@ -72,15 +69,11 @@ class RelationalValueStore {
7269

7370
// Returns a value for an ID.
7471
auto Get(IdT id) const -> ConstRefType {
75-
CARBON_DCHECK(id.index >= 0, "{0}", id);
76-
auto index = related_store_->GetIdTag().Remove(id.index);
77-
return *values_[index];
72+
return *values_.Get(RelatedIdType(id.index));
7873
}
7974

8075
private:
81-
// Set inline size to 0 because these will typically be too large for the
82-
// stack, while this does make File smaller.
83-
llvm::SmallVector<std::optional<ValueType>, 0> values_;
76+
ValueStore<RelatedIdType, std::optional<ValueType>> values_;
8477
const RelatedStoreT* related_store_;
8578
};
8679

0 commit comments

Comments
 (0)