This repository has been archived by the owner on Oct 28, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jalloc.hpp
1932 lines (1688 loc) · 65.7 KB
/
jalloc.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// jalloc.hpp - Just an Allocator™
// A high-performance, thread-safe memory allocator for C/C++
//
// Features:
// - Thread-safe & high-performance memory allocation
// - Multi-tiered allocation strategy for different sizes
// - SIMD-optimized memory operations
// - Automatic memory coalescing and return-to-OS policies
//
// Version: 1.0.0
// Author: alpluspluss
// Updated: 10/28/2024
// Created: 10/22/2024
// License: MIT
//
// This project is no longer maintained. Please feel free to fork and modify it.
// FYI: This allocator works best with small to medium-sized allocations (>= 4KB).
//
#pragma once
#include <array>
#include <atomic>
#include <cstddef>
#include <cstdint>
#include <mutex>
#include <new>
#if defined(__x86_64__)
#include <immintrin.h>
#include <emmintrin.h>
#include <xmmintrin.h>
#include <smmintrin.h>
#include <tmmintrin.h>
#ifdef __AVX2__
#include <avx2intrin.h>
#endif
#ifdef __AVX512F__
#include <avx512fintrin.h>
#endif
#ifdef _MSC_VER
#include <intrin.h>
#endif
// CPU Feature Detection functions
//--------------------------------------------------------------------------
// Detects availability of AVX2 and AVX-512 instructions at runtime
// Returns: true if the feature is available, false otherwise
//--------------------------------------------------------------------------
#ifdef __GNUC__
#include <cpuid.h>
ALWAYS_INLINE static bool cpu_has_avx2()
{
unsigned int eax, ebx, ecx, edx;
__get_cpuid(7, &eax, &ebx, &ecx, &edx);
return (ebx & bit_AVX2) != 0;
}
ALWAYS_INLINE static bool cpu_has_avx512f()
{
unsigned int eax, ebx, ecx, edx;
__get_cpuid(7, &eax, &ebx, &ecx, &edx);
return (ebx & bit_AVX512F) != 0;
}
#elif defined(_MSC_VER)
ALWAYS_INLINE static bool cpu_has_avx2()
{
int cpuInfo[4];
__cpuid(cpuInfo, 7);
return (cpuInfo[1] & (1 << 5)) != 0;
}
ALWAYS_INLINE static bool cpu_has_avx512f()
{
int cpuInfo[4];
__cpuid(cpuInfo, 7);
return (cpuInfo[1] & (1 << 16)) != 0;
}
#endif
//--------------------------------------------------------------------------
// SIMD Operation Definitions
// Provides unified interface for different SIMD instruction sets
//--------------------------------------------------------------------------
#ifdef __AVX512F__
// AVX-512: 64-byte vector operations
#define VECTOR_WIDTH 64
#define STREAM_STORE_VECTOR(addr, val) _mm512_stream_si512((__m512i*)(addr), val)
#define LOAD_VECTOR(addr) _mm512_loadu_si512((const __m512i*)(addr))
#define STORE_VECTOR(addr, val) _mm512_storeu_si512((__m512i*)(addr), val)
#define SET_ZERO_VECTOR() _mm512_setzero_si512()
#elif defined(__AVX2__)
// AVX2: 32-byte vector operations
#define VECTOR_WIDTH 32
#define STREAM_STORE_VECTOR(addr, val) _mm256_stream_si256((__m256i*)(addr), val)
#define LOAD_VECTOR(addr) _mm256_loadu_si256((const __m256i*)(addr))
#define STORE_VECTOR(addr, val) _mm256_storeu_si256((__m256i*)(addr), val)
#define SET_ZERO_VECTOR() _mm256_setzero_si256()
#else
// SSE: 16-byte vector operations (fallback)
#define VECTOR_WIDTH 16
#define STREAM_STORE_VECTOR(addr, val) _mm_stream_si128((__m128i*)(addr), val)
#define LOAD_VECTOR(addr) _mm_loadu_si128((const __m128i*)(addr))
#define STORE_VECTOR(addr, val) _mm_storeu_si128((__m128i*)(addr), val)
#define SET_ZERO_VECTOR() _mm_setzero_si128()
#endif
// Common operations available across all x86_64 platforms
#define STREAM_STORE_64(addr, val) _mm_stream_si64((__int64*)(addr), val)
#define CPU_PAUSE() _mm_pause()
#define MEMORY_FENCE() _mm_sfence()
#define CUSTOM_PREFETCH(addr) _mm_prefetch(reinterpret_cast<const char*>(addr), _MM_HINT_T0)
#define PREFETCH_WRITE(addr) _mm_prefetch(reinterpret_cast<const char*>(addr), _MM_HINT_T0)
#define PREFETCH_READ(addr) _mm_prefetch(reinterpret_cast<const char*>(addr), _MM_HINT_NTA)
#elif defined(__arm__) || defined(__aarch64__)
// ARM/AArch64 SIMD support using NEON
#include <arm_neon.h>
#ifdef __clang__
#include <arm_acle.h>
#endif
// ARM NEON: 16-byte vector operations
#define VECTOR_WIDTH 16
#if defined(__aarch64__)
// 64-bit ARM specific optimizations
#define STREAM_STORE_VECTOR(addr, val) vst1q_u8((uint8_t*)(addr), val)
#define LOAD_VECTOR(addr) vld1q_u8((const uint8_t*)(addr))
#define STORE_VECTOR(addr, val) vst1q_u8((uint8_t*)(addr), val)
#define SET_ZERO_VECTOR() vdupq_n_u8(0)
#define STREAM_STORE_64(addr, val) vst1_u64((uint64_t*)(addr), vcreate_u64(val))
#define MEMORY_FENCE() __dmb(SY)
// ARM-specific prefetch hints
#define CUSTOM_PREFETCH(addr) __asm__ volatile("prfm pldl1keep, [%0]" : : "r" (addr))
#define PREFETCH_WRITE(addr) __asm__ volatile("prfm pstl1keep, [%0]" : : "r" (addr))
#define PREFETCH_READ(addr) __asm__ volatile("prfm pldl1strm, [%0]" : : "r" (addr))
#else
// 32-bit ARM fallbacks
#define STREAM_STORE_VECTOR(addr, val) vst1q_u8((uint8_t*)(addr), val)
#define LOAD_VECTOR(addr) vld1q_u8((const uint8_t*)(addr))
#define STORE_VECTOR(addr, val) vst1q_u8((uint8_t*)(addr), val)
#define SET_ZERO_VECTOR() vdupq_n_u8(0)
#define STREAM_STORE_64(addr, val) *((int64_t*)(addr)) = val
#define MEMORY_FENCE() __dmb(SY)
#define CUSTOM_PREFETCH(addr) __pld(reinterpret_cast<const char*>(addr))
#define PREFETCH_WRITE(addr) __pld(reinterpret_cast<const char*>(addr))
#define PREFETCH_READ(addr) __pld(reinterpret_cast<const char*>(addr))
#endif
#define CPU_PAUSE() __yield()
#else
// Generic fallback for unsupported architectures
// Provides basic functionality without SIMD optimizations
#define VECTOR_WIDTH 8
#define STREAM_STORE_VECTOR(addr, val) *((int64_t*)(addr)) = val
#define LOAD_VECTOR(addr) *((const int64_t*)(addr))
#define STORE_VECTOR(addr, val) *((int64_t*)(addr)) = val
#define SET_ZERO_VECTOR() 0
#define STREAM_STORE_64(addr, val) *((int64_t*)(addr)) = val
#define CPU_PAUSE() ((void)0)
#define MEMORY_FENCE() std::atomic_thread_fence(std::memory_order_seq_cst)
#define CUSTOM_PREFETCH(addr) ((void)0)
#define PREFETCH_WRITE(addr) ((void)0)
#define PREFETCH_READ(addr) ((void)0)
#endif
// Compiler-specific optimizations and attributes
#if defined(__GNUC__) || defined(__clang__)
// GCC/Clang specific optimizations
#define LIKELY(x) __builtin_expect(!!(x), 1)
#define UNLIKELY(x) __builtin_expect(!!(x), 0)
#define ALWAYS_INLINE [[gnu::always_inline]] inline
#define ALIGN_TO(x) __attribute__((aligned(x)))
#if defined(__clang__)
// Clang-specific optimizations
#define HAVE_BUILTIN_ASSUME(x) __builtin_assume(x)
#define HAVE_BUILTIN_ASSUME_ALIGNED(x, a) __builtin_assume_aligned(x, a)
#define NO_SANITIZE_ADDRESS __attribute__((no_sanitize("address")))
#define VECTORIZE_LOOP _Pragma("clang loop vectorize(enable) interleave(enable)")
#define UNROLL_LOOP _Pragma("clang loop unroll(full)")
#else
// GCC-specific fallbacks
#define HAVE_BUILTIN_ASSUME(x) ((void)0)
#define HAVE_BUILTIN_ASSUME_ALIGNED(x, a) (x)
#define NO_SANITIZE_ADDRESS
#define VECTORIZE_LOOP _Pragma("GCC ivdep")
#define UNROLL_LOOP _Pragma("GCC unroll 8")
#endif
#else
// Generic fallbacks for other compilers
#define LIKELY(x) (x)
#define UNLIKELY(x) (x)
#define ALWAYS_INLINE inline
#define ALIGN_TO(x)
#define HAVE_BUILTIN_ASSUME(x) ((void)0)
#define HAVE_BUILTIN_ASSUME_ALIGNED(x, a) (x)
#define NO_SANITIZE_ADDRESS
#define VECTORIZE_LOOP
#define CUSTOM_PREFETCH(addr) ((void)0)
#endif
// Platform-specific memory management operations
#ifdef _WIN32
#include <malloc.h>
#include <windows.h>
// Windows virtual memory management
#define MAP_MEMORY(size) \
VirtualAlloc(nullptr, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)
#define UNMAP_MEMORY(ptr, size) VirtualFree(ptr, 0, MEM_RELEASE)
#ifndef MAP_FAILED
#define MAP_FAILED nullptr
#endif
#define ALIGNED_ALLOC(alignment, size) _aligned_malloc(size, alignment)
#define ALIGNED_FREE(ptr) _aligned_free(ptr)
#elif defined(__APPLE__)
#include <mach/mach.h>
#include <sys/mman.h>
#define MAP_MEMORY(size) \
mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)
#define UNMAP_MEMORY(ptr, size) munmap(ptr, size)
#define ALIGNED_ALLOC(alignment, size) aligned_alloc(alignment, size)
#define ALIGNED_FREE(ptr) free(ptr)
#else
// POSIX-compliant systems (Linux, BSD, etc.)
#include <sched.h>
#include <unistd.h>
#include <sys/mman.h>
#include <thread>
#define MAP_MEMORY(size) \
mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)
#define UNMAP_MEMORY(ptr, size) munmap(ptr, size)
#define ALIGNED_ALLOC(alignment, size) aligned_alloc(alignment, size)
#define ALIGNED_FREE(ptr) free(ptr)
#endif
// Allocator constants
// Hardware constants
static constexpr size_t CACHE_LINE_SIZE = 64; //Changable to 32 | 64
static constexpr size_t PG_SIZE = 4096;
// Block header
static constexpr size_t TINY_LARGE_THRESHOLD = 64;
static constexpr size_t SMALL_LARGE_THRESHOLD = 256;
static constexpr size_t ALIGNMENT = CACHE_LINE_SIZE;
static constexpr size_t LARGE_THRESHOLD = 1024 * 1024;
static constexpr size_t MAX_CACHED_BLOCKS = 32;
static constexpr size_t MAX_CACHE_SIZE = 64 * 1024 * 1024;
static constexpr size_t MIN_CACHE_BLOCK = 4 * 1024;
static constexpr size_t MAX_CACHE_BLOCK = 16 * 1024 * 1024;
static constexpr auto MAX_SIZE_RATIO = 1.25;
static constexpr size_t CACHE_SIZE = 32;
static constexpr size_t SIZE_CLASSES = 32;
static constexpr size_t TINY_CLASSES = 8;
static constexpr size_t MAX_POOLS = 8;
// Safety flags
static constexpr uint64_t SIZE_MASK = 0x0000FFFFFFFFFFFF;
static constexpr uint64_t CLASS_MASK = 0x00FF000000000000;
static constexpr uint64_t MMAP_FLAG = 1ULL << 62;
static constexpr uint64_t COALESCED_FLAG = 1ULL << 61;
static constexpr uint64_t HEADER_MAGIC = 0xDEADBEEF12345678;
static constexpr uint64_t MAGIC_MASK = 0xF000000000000000;
static constexpr uint64_t MAGIC_VALUE = 0xA000000000000000;
static constexpr uint64_t THREAD_OWNER_MASK = 0xFFFF000000000000;
struct size_class
{
uint16_t size;
uint16_t slot_size;
uint16_t blocks;
uint16_t slack;
};
static constexpr size_t get_alignment_for_size(const size_t size) noexcept
{
return size <= CACHE_LINE_SIZE
? CACHE_LINE_SIZE
: size >= PG_SIZE
? PG_SIZE
: 1ULL << (64 - __builtin_clzll(size - 1));
}
constexpr std::array<size_class, 32> size_classes = []
{
std::array<size_class, 32> classes{};
for (size_t i = 0; i < 32; ++i)
{
const size_t size = 1ULL << (i + 3);
const size_t alignment = get_alignment_for_size(size); // Use new function
const size_t slot = (size + alignment - 1) & ~(alignment - 1);
classes[i] = {
static_cast<uint16_t>(size),
static_cast<uint16_t>(slot),
static_cast<uint16_t>(PG_SIZE / slot),
static_cast<uint16_t>(slot - size)
};
}
return classes;
}();
struct thread_cache_t
{
struct cached_block
{
void* ptr;
uint8_t size_class;
};
struct size_class_cache
{
cached_block blocks[CACHE_SIZE];
size_t count;
};
alignas(CACHE_LINE_SIZE) size_class_cache caches[SIZE_CLASSES]{};
ALWAYS_INLINE
void *get(const uint8_t size_class) noexcept
{
auto &[blocks, count] = caches[size_class];
if (LIKELY(count > 0))
{
PREFETCH_READ(&blocks[count - 2]);
return blocks[--count].ptr;
}
return nullptr;
}
ALWAYS_INLINE
bool put(void *ptr, const uint8_t size_class) noexcept
{
auto &cache = caches[size_class];
if (LIKELY(cache.count < CACHE_SIZE))
{
cache.blocks[cache.count].ptr = ptr;
cache.blocks[cache.count].size_class = size_class;
++cache.count;
return true;
}
return false;
}
ALWAYS_INLINE
void clear() noexcept
{
for (auto&[blocks, count] : caches)
count = 0;
}
};
ALWAYS_INLINE
static void prefetch_for_read(const void* addr) noexcept
{
CUSTOM_PREFETCH(addr);
}
template<size_t stride = 64>
ALWAYS_INLINE
static void prefetch_range(const void* addr, const size_t size) noexcept
{
auto ptr = static_cast<const char*>(addr);
for (const char* end = ptr + size; ptr < end; ptr += stride)
CUSTOM_PREFETCH(ptr);
}
template<typename T>
ALWAYS_INLINE
static void stream_store(void* dst, const T& value) noexcept
{
STREAM_STORE_64(dst, static_cast<int64_t>(value));
}
#if defined(__x86_64__)
static ALWAYS_INLINE size_t count_trailing_zeros(uint64_t x)
{
#ifdef _MSC_VER
return _tzcnt_u64(x);
#else
return __builtin_ctzll(x);
#endif
}
static ALWAYS_INLINE void memory_fence()
{
_mm_mfence();
}
static ALWAYS_INLINE void prefetch(const void* addr)
{
_mm_prefetch(static_cast<const char*>(addr), _MM_HINT_T0);
}
#elif defined(__arm__) || defined(__aarch64__)
ALWAYS_INLINE
static size_t count_trailing_zeros(const uint64_t x)
{
return __builtin_ctzll(x);
}
ALWAYS_INLINE
static void memory_fence()
{
std::atomic_thread_fence(std::memory_order_seq_cst);
}
ALWAYS_INLINE
static void prefetch(const void* addr)
{
prefetch_for_read(addr);
}
#else
static ALWAYS_INLINE size_t count_trailing_zeros(uint64_t x)
{
return __builtin_ctzll(x);
}
static ALWAYS_INLINE void memory_fence()
{
std::atomic_thread_fence(std::memory_order_seq_cst);
}
static ALWAYS_INLINE void prefetch(const void*) {}
#endif
ALWAYS_INLINE
static bool is_base_aligned(const void *ptr) noexcept
{
return (reinterpret_cast<uintptr_t>(ptr) & (ALIGNMENT - 1)) == 0;
}
class Jallocator
{
struct bitmap
{
static constexpr size_t bits_per_word = 64;
static constexpr size_t words_per_bitmap = PG_SIZE / (CACHE_LINE_SIZE * 8);
alignas(CACHE_LINE_SIZE) std::atomic<uint64_t> words[words_per_bitmap];
bitmap() noexcept
{
for (auto& word : words)
word = ~0ULL;
}
ALWAYS_INLINE
size_t find_free_block(const size_t size) noexcept
{
const size_t alignment = get_alignment_for_size(size);
const size_t align_mask = (alignment / bits_per_word) - 1;
#if defined(__AVX512F__)
for (size_t i = 0; i < words_per_bitmap; i += 8)
{
if ((i & align_mask) != 0)
continue;
__m512i v = _mm512_loadu_si512((__m512i*)(words + i));
__mmask8 mask = _mm512_movepi64_mask(v);
if (mask)
{
const int lane = __builtin_ctz(mask);
const uint64_t word = words[i + lane].load(std::memory_order_relaxed);
const size_t bit = count_trailing_zeros(word);
const size_t block_offset = (i + lane) * 64 + bit;
if (block_offset * CACHE_LINE_SIZE % alignment == 0)
return block_offset;
}
}
#elif defined(__AVX2__)
for (size_t i = 0; i < words_per_bitmap; i += 4)
{
__m256i v = _mm256_loadu_si256((__m256i*)(words + i));
__m256i zero = _mm256_setzero_si256();
__m256i cmp = _mm256_cmpeq_epi64(v, zero);
uint32_t mask = ~_mm256_movemask_epi8(cmp);
if (mask != 0)
return i * 64 + __builtin_ctzll(mask);
}
#elif defined(__aarch64__)
for (size_t i = 0; i < words_per_bitmap; i += 2)
{
uint64x2_t v = vld1q_u64(reinterpret_cast<const uint64_t *>(words + i));
uint64x2_t zero = vdupq_n_u64(0);
if (vgetq_lane_u64(vceqq_u64(v, zero), 0) != -1ULL)
return i * 64 + __builtin_ctzll(words[i].load(std::memory_order_relaxed));
if (vgetq_lane_u64(vceqq_u64(v, zero), 1) != -1ULL)
return (i + 1) * 64 + __builtin_ctzll(words[i+1].load(std::memory_order_relaxed));
}
#endif
VECTORIZE_LOOP
for (size_t i = 0; i < words_per_bitmap; ++i)
{
if ((i & align_mask) != 0)
continue;
if (i + 1 < words_per_bitmap)
prefetch(&words[i + 1]);
uint64_t expected = words[i].load(std::memory_order_relaxed);
while (expected != 0)
{
const size_t bit = count_trailing_zeros(expected);
const size_t block_offset = i * bits_per_word + bit;
if (const uint64_t desired = expected & ~(1ULL << bit);
words[i].compare_exchange_weak(
expected, desired,
std::memory_order_acquire,
std::memory_order_relaxed))
{
memory_fence();
return block_offset;
}
}
}
return ~static_cast<size_t>(0);
}
ALWAYS_INLINE
void mark_free(const size_t index) noexcept
{
const size_t word_idx = index / bits_per_word;
const size_t bit_idx = index % bits_per_word;
prefetch(&words[word_idx]);
words[word_idx].fetch_or(1ULL << bit_idx, std::memory_order_release);
}
ALWAYS_INLINE
bool is_completely_free() const noexcept
{
for (size_t i = 0; i < words_per_bitmap; ++i)
{
if (i + 1 < words_per_bitmap)
prefetch(&words[i + 1]);
if (words[i].load(std::memory_order_relaxed) != ~0ULL)
return false;
}
return true;
}
};
struct alignas(ALIGNMENT) block_header
{
// Bit field layout:
// [63] - Free flag
// [62] - Memory mapped flag
// [61] - Coalesced flag
// [56-48] - Size class
// [47-0] - Block size
uint64_t data;
uint64_t magic;
block_header* prev_physical;
block_header* next_physical;
void init(const size_t sz, const uint8_t size_class, const bool is_free,
block_header *prev = nullptr, block_header *next = nullptr) noexcept
{
if (UNLIKELY(sz > (1ULL << 47)))
{
magic = 0;
data = 0;
prev_physical = nullptr;
next_physical = nullptr;
return;
}
magic = HEADER_MAGIC;
encode(sz, size_class, is_free);
prev_physical = prev;
next_physical = next;
}
ALWAYS_INLINE
void encode(const size_t size, const uint8_t size_class, const bool is_free) noexcept
{
data = (size & SIZE_MASK) |
(static_cast<uint64_t>(size_class) << 48) |
(static_cast<uint64_t>(is_free) << 63) |
MAGIC_VALUE;
}
ALWAYS_INLINE
bool is_valid() const noexcept
{
if (LIKELY(magic == HEADER_MAGIC &&
(data & MAGIC_MASK) == MAGIC_VALUE))
{
return size() <= (1ULL << 47) &&
(size_class() < SIZE_CLASSES || size_class() == 255);
}
return false;
}
ALWAYS_INLINE
void set_free(const bool is_free) noexcept
{
data = (data & ~(1ULL << 63)) | static_cast<uint64_t>(is_free) << 63;
}
ALWAYS_INLINE
void set_memory_mapped(const bool is_mmap) noexcept
{
data = (data & ~MMAP_FLAG) | static_cast<uint64_t>(is_mmap) << 62;
}
size_t size() const noexcept
{
return data & SIZE_MASK;
}
uint8_t size_class() const noexcept
{
return (data & CLASS_MASK) >> 48;
}
bool is_free() const noexcept
{
return data & 1ULL << 63;
}
bool is_memory_mapped() const noexcept
{
return data & MMAP_FLAG;
}
// Check if the block is perfectly aligned to the cache line size (64B)
// and verify if the pointer is corrupted or not
// The performance trade-offs are worth it
// Please note in mind that this DOES NOT check
// 1. Perfectly-aligned corrupted pointers
// 2. Maliciously-aligned pointers
// 3.
// Modified alignment check
static bool is_aligned(const void *ptr) noexcept
{
if (!is_base_aligned(ptr))
return false;
const auto header = reinterpret_cast<const block_header *>(
static_cast<const char *>(ptr) - sizeof(block_header));
if (!is_base_aligned(header))
return false;
if (header->magic != HEADER_MAGIC)
return false;
const size_t size_alignment = get_alignment_for_size(header->size());
return (reinterpret_cast<uintptr_t>(ptr) & (size_alignment - 1)) == 0;
}
bool try_coalesce() noexcept
{
if (is_memory_mapped() || size_class() < TINY_CLASSES)
return false;
auto coalesced = false;
if (next_physical && next_physical->is_free())
{
const size_t combined_size = size() + next_physical->size() + sizeof(block_header);
next_physical = next_physical->next_physical;
if (next_physical)
next_physical->prev_physical = this;
encode(combined_size, size_class(), true);
set_coalesced(true);
coalesced = true;
}
if (prev_physical && prev_physical->is_free())
{
const size_t combined_size = size() + prev_physical->size() + sizeof(block_header);
prev_physical->next_physical = next_physical;
if (next_physical)
next_physical->prev_physical = prev_physical;
prev_physical->encode(combined_size, prev_physical->size_class(), true);
prev_physical->set_coalesced(true);
coalesced = true;
}
return coalesced;
}
ALWAYS_INLINE
void set_coalesced(const bool is_coalesced) noexcept
{
data = (data & ~COALESCED_FLAG) | (static_cast<uint64_t>(is_coalesced) << 61);
}
ALWAYS_INLINE
bool is_coalesced() const noexcept
{
return data & COALESCED_FLAG;
}
};
struct alignas(PG_SIZE) pool
{
static constexpr size_t MIN_RETURN_SIZE = 64 * 1024;
static constexpr auto MEM_USAGE_THRESHOLD = 0.2;
bitmap bitmap;
uint8_t memory[PG_SIZE - sizeof(bitmap)]{};
ALWAYS_INLINE
void *allocate(const size_class &sc) noexcept
{
if (const size_t index = bitmap.find_free_block(sc.size);
index != ~static_cast<size_t>(0))
{
return memory + index * sc.slot_size;
}
return nullptr;
}
ALWAYS_INLINE
void deallocate(void* ptr, const size_class& sc) noexcept
{
const size_t offset = static_cast<uint8_t*>(ptr) - memory;
bitmap.mark_free(offset / sc.slot_size);
}
ALWAYS_INLINE
bool is_completely_free() const noexcept
{
return bitmap.is_completely_free();
}
ALWAYS_INLINE
void return_memory() noexcept
{
size_t free_space = 0;
#if defined(__AVX512F__)
const auto* current = reinterpret_cast<block_header*>(memory);
__m512i sum = _mm512_setzero_si512();
while (current)
{
if (current->is_free())
sum = _mm512_add_epi64(sum, _mm512_set1_epi64(current->size()));
current = current->next_physical;
}
free_space = _mm512_reduce_add_epi64(sum);
#elif defined(__AVX2__)
const auto* current = reinterpret_cast<block_header*>(memory);
// 4 accumulators gives the best throughput here
__m256i sum1 = _mm256_setzero_si256();
__m256i sum2 = _mm256_setzero_si256();
__m256i sum3 = _mm256_setzero_si256();
__m256i sum4 = _mm256_setzero_si256();
while (current)
{
block_header* next = current->next_physical;
if (next)
_mm_prefetch(reinterpret_cast<const char*>(next), _MM_HINT_T0);
// this is to reduce depend on chains
if (current->is_free())
{
__m256i size_vec = _mm256_set1_epi64x(current->size());
sum1 = _mm256_add_epi64(sum1, size_vec);
size_vec = _mm256_set1_epi64x(current->size() >> 1);
sum2 = _mm256_add_epi64(sum2, size_vec);
size_vec = _mm256_set1_epi64x(current->size() >> 2);
sum3 = _mm256_add_epi64(sum3, size_vec);
size_vec = _mm256_set1_epi64x(current->size() >> 3);
sum4 = _mm256_add_epi64(sum4, size_vec);
}
current = next;
}
// mash the accumulators together
sum1 = _mm256_add_epi64(sum1, _mm256_slli_epi64(sum2, 1));
sum3 = _mm256_add_epi64(sum3, _mm256_slli_epi64(sum4, 3));
sum1 = _mm256_add_epi64(sum1, _mm256_slli_epi64(sum3, 2));
// caclulate the total horizontal sum with the least possible instructions
__m128i sum_low = _mm256_extracti128_si256(sum1, 0);
__m128i sum_high = _mm256_extracti128_si256(sum1, 1);
__m128i sum = _mm_add_epi64(sum_low, sum_high);
sum = _mm_add_epi64(sum, _mm_shuffle_epi32(sum, _MM_SHUFFLE(1,0,3,2)));
free_space = _mm_cvtsi128_si64(sum);
#elif defined(__aarch64__)
auto* current = reinterpret_cast<block_header*>(memory);
uint64x2_t sum1 = vdupq_n_u64(0);
uint64x2_t sum2 = vdupq_n_u64(0);
uint64x2_t sum3 = vdupq_n_u64(0);
uint64x2_t sum4 = vdupq_n_u64(0);
while (current)
{
block_header* next = current->next_physical;
if (next)
{
prefetch(next);
}
if (current->is_free())
{
const uint64_t size = current->size();
sum1 = vaddq_u64(sum1, vdupq_n_u64(size));
sum2 = vaddq_u64(sum2, vdupq_n_u64(size >> 1));
sum3 = vaddq_u64(sum3, vdupq_n_u64(size >> 2));
sum4 = vaddq_u64(sum4, vdupq_n_u64(size >> 3));
}
current = next;
}
const uint64x2_t sum_12 = vaddq_u64(sum1, vshlq_n_u64(sum2, 1));
const uint64x2_t sum_34 = vaddq_u64(sum3, vshlq_n_u64(sum4, 3));
const uint64x2_t final_sum = vaddq_u64(sum_12, vshlq_n_u64(sum_34, 2));
free_space = vgetq_lane_u64(final_sum, 0) + vgetq_lane_u64(final_sum, 1);
#else
const auto* current = reinterpret_cast<block_header*>(memory);
while (current)
{
if (current->is_free())
free_space += current->size();
current = current->next_physical;
}
#endif
if (free_space >= MIN_RETURN_SIZE &&
static_cast<double>(free_space) / PG_SIZE >= (1.0 - MEM_USAGE_THRESHOLD))
{
current = reinterpret_cast<block_header*>(memory);
while (current)
{
if (current->is_free() && current->is_coalesced())
{
void* block_start = current + 1;
auto page_start = reinterpret_cast<void*>(
(reinterpret_cast<uintptr_t>(block_start) + PG_SIZE - 1) & ~(PG_SIZE - 1));
auto page_end = reinterpret_cast<void*>(
reinterpret_cast<uintptr_t>(block_start) + current->size() & ~(PG_SIZE - 1));
if (page_end > page_start)
{
#ifdef _WIN32
VirtualAlloc(page_start,
reinterpret_cast<char*>(page_end) -
reinterpret_cast<char*>(page_start),
MEM_RESET,
PAGE_READWRITE);
#elif defined(__APPLE__)
madvise(page_start,
static_cast<char*>(page_end) -
static_cast<char*>(page_start),
MADV_FREE);
#else
madvise(page_start,
reinterpret_cast<char*>(page_end) -
reinterpret_cast<char*>(page_start),
MADV_DONTNEED);
#endif
}
}
current = current->next_physical;
}
}
}
};
struct tiny_block_manager
{
struct alignas(PG_SIZE) tiny_pool
{
bitmap bitmap;
alignas(ALIGNMENT) uint8_t memory[PG_SIZE - sizeof(bitmap)]{};
ALWAYS_INLINE
void* allocate_tiny(const uint8_t size_class) noexcept
{
const size_t size = (size_class + 1) << 3;
const size_t slot_size = (size + sizeof(block_header) + ALIGNMENT - 1) & ~(ALIGNMENT - 1);
const size_t max_blocks = (PG_SIZE - sizeof(bitmap)) / slot_size;
if (const size_t index = bitmap.find_free_block(size);
index != ~static_cast<size_t>(0) && index < max_blocks)
{
uint8_t *block = memory + index * slot_size;
if (block + slot_size <= memory + (PG_SIZE - sizeof(bitmap)))
return block;
}
return nullptr;
}
ALWAYS_INLINE
void deallocate_tiny(void *ptr, const uint8_t size_class) noexcept
{
const size_t size = (size_class + 1) << 3;
const size_t slot_size = (size + sizeof(block_header) + ALIGNMENT - 1) & ~(ALIGNMENT - 1);
const size_t offset = static_cast<uint8_t *>(ptr) - memory;
const size_t index = offset / slot_size;
if (index * slot_size < PG_SIZE - sizeof(bitmap))
bitmap.mark_free(index);
}
};
};
struct pool_manager
{
struct pool_entry
{
pool* p;
size_t used_blocks;
};
alignas(CACHE_LINE_SIZE) pool_entry pools[SIZE_CLASSES][MAX_POOLS]{};
size_t pool_count[SIZE_CLASSES]{};
ALWAYS_INLINE
void* allocate(const uint8_t size_class) noexcept
{
const auto& sc = size_classes[size_class];
for (size_t i = 0; i < pool_count[size_class]; ++i)
{
auto&[p, used_blocks] = pools[size_class][i];
if (void* ptr = p->allocate(sc))
{
++used_blocks;
return ptr;
}
}
if (pool_count[size_class] < MAX_POOLS)
{
auto* new_pool = new (std::align_val_t{PG_SIZE}) pool();
auto&[p, used_blocks] = pools[size_class][pool_count[size_class]];
p = new_pool;
used_blocks = 1;
if (void* ptr = new_pool->allocate(sc))
{
++pool_count[size_class];
return ptr;
}
delete new_pool;
}
return nullptr;
}
ALWAYS_INLINE
void deallocate(void* ptr, const uint8_t size_class) noexcept
{
if (UNLIKELY((reinterpret_cast<uintptr_t>(ptr) & ~(PG_SIZE-1)) == 0))
return;
const auto& sc = size_classes[size_class];
if (UNLIKELY(size_class >= SIZE_CLASSES))
return;
for (size_t i = 0; i < pool_count[size_class]; ++i)
{
auto& entry = pools[size_class][i];
const auto* pool_start = reinterpret_cast<const char*>(entry.p);
if (const auto* pool_end = pool_start + PG_SIZE; ptr >= pool_start && ptr < pool_end)
{
entry.p->deallocate(ptr, sc);
if (--entry.used_blocks == 0)
{
delete entry.p;
entry = pools[size_class][--pool_count[size_class]];
}
return;
}
}
}
~pool_manager()
{
for (size_t sc = 0; sc < SIZE_CLASSES; ++sc)
{
const size_t count = pool_count[sc];
VECTORIZE_LOOP
for (size_t i = 0; i < count; ++i)
delete pools[sc][i].p;
}
}
};
struct alignas(CACHE_LINE_SIZE) large_block_cache_t
{
struct alignas(CACHE_LINE_SIZE) cache_entry
{
std::atomic<void *> ptr{nullptr};