Skip to content

Commit 4aa4ee9

Browse files
authored
[Support] Add SpecificBumpPtrAllocator::identifyObject (#100475)
This already exists in BumpPtrAllocatorImpl, but I would like to use it from SpecificBumpPtrAllocator. I also noticed there was no test for identifyObject so I added one.
1 parent 9720690 commit 4aa4ee9

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed

llvm/include/llvm/Support/Allocator.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,13 @@ template <typename T> class SpecificBumpPtrAllocator {
435435

436436
/// Allocate space for an array of objects without constructing them.
437437
T *Allocate(size_t num = 1) { return Allocator.Allocate<T>(num); }
438+
439+
/// \return An index uniquely and reproducibly identifying
440+
/// an input pointer \p Ptr in the given allocator.
441+
/// Returns an empty optional if the pointer is not found in the allocator.
442+
std::optional<int64_t> identifyObject(const void *Ptr) {
443+
return Allocator.identifyObject(Ptr);
444+
}
438445
};
439446

440447
} // end namespace llvm

llvm/unittests/Support/AllocatorTest.cpp

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,27 @@ TEST(AllocatorTest, TestSlowerSlabGrowthDelay) {
208208
EXPECT_EQ(SlabSize * GrowthDelay + SlabSize * 2, Alloc.getTotalMemory());
209209
}
210210

211+
TEST(AllocatorTest, TestIdentifyObject) {
212+
BumpPtrAllocator Alloc;
213+
214+
uint64_t *a = (uint64_t *)Alloc.Allocate(sizeof(uint64_t), alignof(uint64_t));
215+
std::optional<int64_t> maybe_a_belongs = Alloc.identifyObject(a);
216+
EXPECT_TRUE(maybe_a_belongs.has_value());
217+
EXPECT_TRUE(*maybe_a_belongs >= 0);
218+
219+
uint64_t *b = nullptr;
220+
std::optional<int64_t> maybe_b_belongs = Alloc.identifyObject(b);
221+
EXPECT_FALSE(maybe_b_belongs);
222+
223+
// The default slab size is 4096 (or 512 uint64_t values). Custom slabs are
224+
// allocated when the requested size is larger than the slab size.
225+
uint64_t *c =
226+
(uint64_t *)Alloc.Allocate(sizeof(uint64_t) * 1024, alignof(uint64_t));
227+
std::optional<int64_t> maybe_c_belongs = Alloc.identifyObject(c);
228+
EXPECT_TRUE(maybe_c_belongs.has_value());
229+
EXPECT_TRUE(*maybe_c_belongs < 0);
230+
}
231+
211232
// Mock slab allocator that returns slabs aligned on 4096 bytes. There is no
212233
// easy portable way to do this, so this is kind of a hack.
213234
class MockSlabAllocator {

0 commit comments

Comments
 (0)