This repository has been archived by the owner on Aug 10, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 564
/
Copy pathMemory.cpp
2961 lines (2610 loc) · 97.3 KB
/
Memory.cpp
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
/*
* Copyright 2010-2018 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <string.h>
#include <stdio.h>
#include <cstddef> // for offsetof
#include "Alloc.h"
#include "KAssert.h"
#include "Atomic.h"
#include "Exceptions.h"
#include "KString.h"
#include "Memory.h"
#include "MemoryPrivate.hpp"
#include "Natives.h"
#include "Porting.h"
#include "Runtime.h"
// If garbage collection algorithm for cyclic garbage to be used.
// We are using the Bacon's algorithm for GC, see
// http://researcher.watson.ibm.com/researcher/files/us-bacon/Bacon03Pure.pdf.
#define USE_GC 1
// Define to 1 to print all memory operations.
#define TRACE_MEMORY 0
// Define to 1 to print major GC events.
#define TRACE_GC 0
// Collect memory manager events statistics.
#define COLLECT_STATISTIC 0
#if COLLECT_STATISTIC
#include <algorithm>
#endif
namespace {
// Granularity of arena container chunks.
constexpr container_size_t kContainerAlignment = 1024;
// Single object alignment.
constexpr container_size_t kObjectAlignment = 8;
// Required e.g. for object size computations to be correct.
static_assert(sizeof(ContainerHeader) % kObjectAlignment == 0, "sizeof(ContainerHeader) is not aligned");
#if TRACE_MEMORY
#undef TRACE_GC
#define TRACE_GC 1
#define MEMORY_LOG(...) konan::consolePrintf(__VA_ARGS__);
#else
#define MEMORY_LOG(...)
#endif
#if TRACE_GC
#define GC_LOG(...) konan::consolePrintf(__VA_ARGS__);
#else
#define GC_LOG(...)
#endif
#if USE_GC
// Collection threshold default (collect after having so many elements in the
// release candidates set).
constexpr size_t kGcThreshold = 8 * 1024;
// Ergonomic thresholds.
// If GC to computations time ratio is above that value,
// increase GC threshold by 1.5 times.
constexpr double kGcToComputeRatioThreshold = 0.5;
// Never exceed this value when increasing GC threshold.
constexpr size_t kMaxErgonomicThreshold = 16 * 1024;
// Threshold of size for toFree set, triggering actual cycle collector.
constexpr size_t kMaxToFreeSize = 8 * 1024;
// How many elements in finalizer queue allowed before cleaning it up.
constexpr size_t kFinalizerQueueThreshold = 32;
// If allocated that much memory since last GC - force new GC.
constexpr size_t kMaxGcAllocThreshold = 8 * 1024 * 1024;
#endif // USE_GC
typedef KStdUnorderedSet<ContainerHeader*> ContainerHeaderSet;
typedef KStdVector<ContainerHeader*> ContainerHeaderList;
typedef KStdVector<KRef*> KRefPtrList;
typedef KStdDeque<ContainerHeader*> ContainerHeaderDeque;
// A little hack that allows to enable -O2 optimizations
// Prevents clang from replacing FrameOverlay struct
// with single pointer.
// Can be removed when FrameOverlay will become more complex.
FrameOverlay exportFrameOverlay;
// Current number of allocated containers.
volatile int allocCount = 0;
volatile int aliveMemoryStatesCount = 0;
KBoolean g_checkLeaks = KonanNeedDebugInfo;
// TODO: can we pass this variable as an explicit argument?
THREAD_LOCAL_VARIABLE MemoryState* memoryState = nullptr;
THREAD_LOCAL_VARIABLE FrameOverlay* currentFrame = nullptr;
#if COLLECT_STATISTIC
class MemoryStatistic {
public:
// UpdateRef per-object type counters.
uint64_t updateCounters[12][10];
// Alloc per container type counters.
uint64_t containerAllocs[2];
// Free per container type counters.
uint64_t objectAllocs[6];
// Histogram of allocation size distribution.
KStdUnorderedMap<int, int>* allocationHistogram;
// Number of allocation cache hits.
int allocCacheHit;
// Number of allocation cache misses.
int allocCacheMiss;
// Number of regular reference increments.
uint64_t addRefs;
// Number of atomic reference increments.
uint64_t atomicAddRefs;
// Number of regular reference decrements.
uint64_t releaseRefs;
// Number of atomic reference decrements.
uint64_t atomicReleaseRefs;
// Number of potential cycle candidates.
uint64_t releaseCyclicRefs;
// Map of array index to human readable name.
static constexpr const char* indexToName[] = {
"local ", "stack ", "perm ", "frozen", "shared", "null " };
void init() {
memset(containerAllocs, 0, sizeof(containerAllocs));
memset(objectAllocs, 0, sizeof(objectAllocs));
memset(updateCounters, 0, sizeof(updateCounters));
allocationHistogram = konanConstructInstance<KStdUnorderedMap<int, int>>();
allocCacheHit = 0;
allocCacheMiss = 0;
}
void deinit() {
konanDestructInstance(allocationHistogram);
allocationHistogram = nullptr;
}
void incAddRef(const ContainerHeader* header, bool atomic, int stack) {
if (atomic) atomicAddRefs++; else addRefs++;
}
void incReleaseRef(const ContainerHeader* header, bool atomic, bool cyclic, int stack) {
if (atomic) {
atomicReleaseRefs++;
} else {
if (cyclic) releaseCyclicRefs++; else releaseRefs++;
}
}
void incUpdateRef(const ObjHeader* objOld, const ObjHeader* objNew, int stack) {
updateCounters[toIndex(objOld, stack)][toIndex(objNew, stack)]++;
}
void incAlloc(size_t size, const ContainerHeader* header) {
containerAllocs[0]++;
++(*allocationHistogram)[size];
}
void incFree(const ContainerHeader* header) {
containerAllocs[1]++;
}
void incAlloc(size_t size, const ObjHeader* header) {
objectAllocs[toIndex(header, 0)]++;
}
static int toIndex(const ObjHeader* obj, int stack) {
if (reinterpret_cast<uintptr_t>(obj) > 1)
return toIndex(obj->container(), stack);
else
return 4 + stack * 6;
}
static int toIndex(const ContainerHeader* header, int stack) {
if (header == nullptr) return 2 + stack * 6; // permanent.
switch (header->tag()) {
case CONTAINER_TAG_LOCAL : return 0 + stack * 6;
case CONTAINER_TAG_STACK : return 1 + stack * 6;
case CONTAINER_TAG_FROZEN : return 3 + stack * 6;
case CONTAINER_TAG_SHARED : return 4 + stack * 6;
}
RuntimeAssert(false, "unknown container type");
return -1;
}
static double percents(uint64_t value, uint64_t all) {
return all == 0 ? 0 : ((double)value / (double)all) * 100.0;
}
void printStatistic() {
konan::consolePrintf("\nMemory manager statistic:\n\n");
konan::consolePrintf("Container alloc: %lld, free: %lld\n",
containerAllocs[0], containerAllocs[1]);
for (int i = 0; i < 6; i++) {
// Only local, shared and frozen can be allocated.
if (i == 0 || i == 3 || i == 4)
konan::consolePrintf("Object %s alloc: %lld\n", indexToName[i], objectAllocs[i]);
}
konan::consolePrintf("\n");
uint64_t allUpdateRefs = 0, heapUpdateRefs = 0, stackUpdateRefs = 0;
for (int i = 0; i < 12; i++) {
for (int j = 0; j < 12; j++) {
allUpdateRefs += updateCounters[i][j];
if (i < 6 && j < 6)
heapUpdateRefs += updateCounters[i][j];
if (i >= 6 && j >= 6)
stackUpdateRefs += updateCounters[i][j];
}
}
konan::consolePrintf("Total updates: %lld, stack: %lld(%.2lf%%), heap: %lld(%.2lf%%)\n",
allUpdateRefs,
stackUpdateRefs, percents(stackUpdateRefs, allUpdateRefs),
heapUpdateRefs, percents(heapUpdateRefs, allUpdateRefs));
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
if (updateCounters[i][j] != 0)
konan::consolePrintf("UpdateHeapRef[%s -> %s]: %lld (%.2lf%% of all, %.2lf%% of heap)\n",
indexToName[i], indexToName[j], updateCounters[i][j],
percents(updateCounters[i][j], allUpdateRefs),
percents(updateCounters[i][j], heapUpdateRefs));
}
}
for (int i = 6; i < 12; i++) {
for (int j = 6; j < 12; j++) {
if (updateCounters[i][j] != 0)
konan::consolePrintf("UpdateStackRef[%s -> %s]: %lld (%.2lf%% of all, %.2lf%% of stack)\n",
indexToName[i - 6], indexToName[j - 6],
updateCounters[i][j],
percents(updateCounters[i][j], allUpdateRefs),
percents(updateCounters[i][j], stackUpdateRefs));
}
}
konan::consolePrintf("\n");
konan::consolePrintf("Allocation histogram:\n");
KStdVector<int> keys(allocationHistogram->size());
int index = 0;
for (auto& it : *allocationHistogram) {
keys[index++] = it.first;
}
std::sort(keys.begin(), keys.end());
int perLine = 4;
int count = 0;
for (auto it : keys) {
konan::consolePrintf(
"%d bytes -> %d times ", it, (*allocationHistogram)[it]);
if (++count % perLine == (perLine - 1) || (count == keys.size()))
konan::consolePrintf("\n");
}
uint64_t allAddRefs = addRefs + atomicAddRefs;
uint64_t allReleases = releaseRefs + atomicReleaseRefs + releaseCyclicRefs;
konan::consolePrintf("AddRefs:\t%lld/%lld (%.2lf%% of atomic)\n"
"Releases:\t%lld/%lld (%.2lf%% of atomic)\n"
"ReleaseRefs affecting cycle collector : %lld (%.2lf%% of cyclic)\n",
addRefs, atomicAddRefs, percents(atomicAddRefs, allAddRefs),
releaseRefs, atomicReleaseRefs, percents(atomicReleaseRefs, allReleases),
releaseCyclicRefs, percents(releaseCyclicRefs, allReleases));
}
};
constexpr const char* MemoryStatistic::indexToName[];
#endif // COLLECT_STATISTIC
inline bool isPermanentOrFrozen(ContainerHeader* container) {
return container == nullptr || container->frozen();
}
inline bool isShareable(ContainerHeader* container) {
return container == nullptr || container->shareable();
}
void garbageCollect();
} // namespace
class ForeignRefManager {
public:
static ForeignRefManager* create() {
ForeignRefManager* result = konanConstructInstance<ForeignRefManager>();
result->addRef();
return result;
}
void addRef() {
atomicAdd(&refCount, 1);
}
void releaseRef() {
if (atomicAdd(&this->refCount, -1) == 0) {
// So the owning MemoryState has abandoned [this].
// Leaving the queued work items would result in memory leak.
// Luckily current thread has exclusive access to [this],
// so it can process the queue pretending like it takes ownership of all its objects:
this->processAbandoned();
konanDestructInstance(this);
}
}
bool tryReleaseRefOwned() {
if (atomicAdd(&this->refCount, -1) == 0) {
if (this->releaseList != nullptr) {
// There are no more holders of [this] to process the enqueued work items in [releaseRef].
// Revert the reference counter back and notify the caller to process and then retry:
atomicAdd(&this->refCount, 1);
return false;
}
konanDestructInstance(this);
}
return true;
}
void enqueueReleaseRef(ObjHeader* obj) {
ListNode* newListNode = konanConstructInstance<ListNode>();
newListNode->obj = obj;
while (true) {
ListNode* next = this->releaseList;
newListNode->next = next;
if (compareAndSet(&this->releaseList, next, newListNode)) break;
}
}
template <typename func>
void processEnqueuedReleaseRefsWith(func process) {
if (releaseList == nullptr) return;
ListNode* toProcess = nullptr;
while (true) {
toProcess = releaseList;
if (compareAndSet<ListNode*>(&this->releaseList, toProcess, nullptr)) break;
}
while (toProcess != nullptr) {
process(toProcess->obj);
ListNode* next = toProcess->next;
konanDestructInstance(toProcess);
toProcess = next;
}
}
private:
int refCount;
struct ListNode {
ObjHeader* obj;
ListNode* next;
};
ListNode* volatile releaseList;
void processAbandoned() {
if (this->releaseList != nullptr) {
bool hadNoRuntimeInitialized = (memoryState == nullptr);
if (hadNoRuntimeInitialized) {
Kotlin_initRuntimeIfNeeded(); // Required by ReleaseHeapRef.
}
processEnqueuedReleaseRefsWith([](ObjHeader* obj) {
ReleaseHeapRef(obj);
});
if (hadNoRuntimeInitialized) {
// This thread is likely not intended to run Kotlin code.
// In this case it has no chances to process the release-refs enqueued above using
// the general heuristics, so do this manually:
garbageCollect();
// TODO: how to handle subsequent processAbandoned() calls?
}
}
}
};
struct MemoryState {
#if TRACE_MEMORY
// Set of all containers.
ContainerHeaderSet* containers;
#endif
#if USE_GC
// Finalizer queue - linked list of containers scheduled for finalization.
ContainerHeader* finalizerQueue;
int finalizerQueueSize;
int finalizerQueueSuspendCount;
/*
* Typical scenario for GC is as following:
* we have 90% of objects with refcount = 0 which will be deleted during
* the first phase of the algorithm.
* We could mark them with a bit in order to tell the next two phases to skip them
* and thus requiring only one list, but the downside is that both of the
* next phases would iterate over the whole list of objects instead of only 10%.
*/
ContainerHeaderList* toFree; // List of all cycle candidates.
ContainerHeaderList* roots; // Real candidates excluding those with refcount = 0.
// How many GC suspend requests happened.
int gcSuspendCount;
// How many candidate elements in toRelease shall trigger collection.
size_t gcThreshold;
// If collection is in progress.
bool gcInProgress;
// Objects to be released.
ContainerHeaderList* toRelease;
ForeignRefManager* foreignRefManager;
bool gcErgonomics;
uint64_t lastGcTimestamp;
uint64_t allocSinceLastGc;
uint64_t allocSinceLastGcThreshold;
#endif // USE_GC
#if COLLECT_STATISTIC
#define CONTAINER_ALLOC_STAT(state, size, container) state->statistic.incAlloc(size, container);
#define CONTAINER_DESTROY_STAT(state, container) \
state->statistic.incFree(container);
#define OBJECT_ALLOC_STAT(state, size, object) \
state->statistic.incAlloc(size, object); \
state->statistic.incAddRef(object->container(), 0, 0);
#define UPDATE_REF_STAT(state, oldRef, newRef, slot, stack) \
state->statistic.incUpdateRef(oldRef, newRef, stack);
#define UPDATE_ADDREF_STAT(state, obj, atomic, stack) \
state->statistic.incAddRef(obj, atomic, stack);
#define UPDATE_RELEASEREF_STAT(state, obj, atomic, cyclic, stack) \
state->statistic.incReleaseRef(obj, atomic, cyclic, stack);
#define INIT_STAT(state) \
state->statistic.init();
#define DEINIT_STAT(state) \
state->statistic.deinit();
#define PRINT_STAT(state) \
state->statistic.printStatistic();
MemoryStatistic statistic;
#else
#define CONTAINER_ALLOC_STAT(state, size, container)
#define CONTAINER_DESTROY_STAT(state, container)
#define OBJECT_ALLOC_STAT(state, size, object)
#define UPDATE_REF_STAT(state, oldRef, newRef, slot, stack)
#define UPDATE_ADDREF_STAT(state, obj, atomic, stack)
#define UPDATE_RELEASEREF_STAT(state, obj, atomic, cyclic, stack)
#define INIT_STAT(state)
#define DEINIT_STAT(state)
#define PRINT_STAT(state)
#endif // COLLECT_STATISTIC
};
namespace {
#if TRACE_MEMORY
#define INIT_TRACE(state) \
memoryState->containers = konanConstructInstance<ContainerHeaderSet>();
#define DEINIT_TRACE(state) \
konanDestructInstance(memoryState->containers); \
memoryState->containers = nullptr;
#else
#define INIT_TRACE(state)
#define DEINIT_TRACE(state)
#endif
#define CONTAINER_ALLOC_TRACE(state, size, container) \
MEMORY_LOG("Container alloc %d at %p\n", size, container)
#define CONTAINER_DESTROY_TRACE(state, container) \
MEMORY_LOG("Container destroy %p\n", container)
#define OBJECT_ALLOC_TRACE(state, size, object) \
MEMORY_LOG("Object alloc %d at %p\n", size, object)
#define UPDATE_REF_TRACE(state, oldRef, newRef, slot, stack) \
MEMORY_LOG("UpdateRef %s*%p: %p -> %p\n", stack ? "stack " : "heap ", slot, oldRef, newRef)
// Events macro definitions.
// Called on worker's memory init.
#define INIT_EVENT(state) \
INIT_STAT(state) \
INIT_TRACE(state)
// Called on worker's memory deinit.
#define DEINIT_EVENT(state) \
DEINIT_STAT(state)
// Called on container allocation.
#define CONTAINER_ALLOC_EVENT(state, size, container) \
CONTAINER_ALLOC_STAT(state, size, container) \
CONTAINER_ALLOC_TRACE(state, size, container)
// Called on container destroy (memory is released to allocator).
#define CONTAINER_DESTROY_EVENT(state, container) \
CONTAINER_DESTROY_STAT(state, container) \
CONTAINER_DESTROY_TRACE(state, container)
// Object was just allocated.
#define OBJECT_ALLOC_EVENT(state, size, object) \
OBJECT_ALLOC_STAT(state, size, object) \
OBJECT_ALLOC_TRACE(state, size, object)
// Object is freed.
#define OBJECT_FREE_EVENT(state, size, object) \
OBJECT_FREE_STAT(state, size, object) \
OBJECT_FREE_TRACE(state, object)
// Reference in memory is being updated.
#define UPDATE_REF_EVENT(state, oldRef, newRef, slot, stack) \
UPDATE_REF_STAT(state, oldRef, newRef, slot, stack) \
UPDATE_REF_TRACE(state, oldRef, newRef, slot, stack)
// Infomation shall be printed as worker is exiting.
#define PRINT_EVENT(state) \
PRINT_STAT(state)
// Forward declarations.
void freeContainer(ContainerHeader* header) NO_INLINE;
#if USE_GC
void garbageCollect(MemoryState* state, bool force) NO_INLINE;
void rememberNewContainer(ContainerHeader* container);
#endif // USE_GC
// Class representing arbitrary placement container.
class Container {
public:
ContainerHeader* header() const { return header_; }
protected:
// Data where everything is being stored.
ContainerHeader* header_;
void SetHeader(ObjHeader* obj, const TypeInfo* type_info) {
obj->typeInfoOrMeta_ = const_cast<TypeInfo*>(type_info);
// Take into account typeInfo's immutability for ARC strategy.
if ((type_info->flags_ & TF_IMMUTABLE) != 0)
header_->refCount_ |= CONTAINER_TAG_FROZEN;
if ((type_info->flags_ & TF_ACYCLIC) != 0)
header_->setColorEvenIfGreen(CONTAINER_TAG_GC_GREEN);
}
};
// Container for a single object.
class ObjectContainer : public Container {
public:
// Single instance.
explicit ObjectContainer(MemoryState* state, const TypeInfo* type_info) {
Init(state, type_info);
}
// Object container shalln't have any dtor, as it's being freed by
// ::Release().
ObjHeader* GetPlace() const {
return reinterpret_cast<ObjHeader*>(header_ + 1);
}
private:
void Init(MemoryState* state, const TypeInfo* type_info);
};
class ArrayContainer : public Container {
public:
ArrayContainer(MemoryState* state, const TypeInfo* type_info, uint32_t elements) {
Init(state, type_info, elements);
}
// Array container shalln't have any dtor, as it's being freed by ::Release().
ArrayHeader* GetPlace() const {
return reinterpret_cast<ArrayHeader*>(header_ + 1);
}
private:
void Init(MemoryState* state, const TypeInfo* type_info, uint32_t elements);
};
// Class representing arena-style placement container.
// Container is used for reference counting, and it is assumed that objects
// with related placement will share container. Only
// whole container can be freed, individual objects are not taken into account.
class ArenaContainer;
struct ContainerChunk {
ContainerChunk* next;
ArenaContainer* arena;
// Then we have ContainerHeader here.
ContainerHeader* asHeader() {
return reinterpret_cast<ContainerHeader*>(this + 1);
}
};
class ArenaContainer {
public:
void Init();
void Deinit();
// Place individual object in this container.
ObjHeader* PlaceObject(const TypeInfo* type_info);
// Places an array of certain type in this container. Note that array_type_info
// is type info for an array, not for an individual element. Also note that exactly
// same operation could be used to place strings.
ArrayHeader* PlaceArray(const TypeInfo* array_type_info, container_size_t count);
ObjHeader** getSlot();
private:
void* place(container_size_t size);
bool allocContainer(container_size_t minSize);
void setHeader(ObjHeader* obj, const TypeInfo* typeInfo) {
obj->typeInfoOrMeta_ = const_cast<TypeInfo*>(typeInfo);
obj->setContainer(currentChunk_->asHeader());
// Here we do not take into account typeInfo's immutability for ARC strategy, as there's no ARC.
}
ContainerChunk* currentChunk_;
uint8_t* current_;
uint8_t* end_;
ArrayHeader* slots_;
uint32_t slotsCount_;
};
constexpr int kFrameOverlaySlots = sizeof(FrameOverlay) / sizeof(ObjHeader**);
inline bool isFreeable(const ContainerHeader* header) {
return header != nullptr && header->tag() != CONTAINER_TAG_STACK;
}
inline bool isArena(const ContainerHeader* header) {
return header != nullptr && header->stack();
}
inline bool isAggregatingFrozenContainer(const ContainerHeader* header) {
return header != nullptr && header->frozen() && header->objectCount() > 1;
}
inline bool isMarkedAsRemoved(ContainerHeader* container) {
return (reinterpret_cast<uintptr_t>(container) & 1) != 0;
}
inline ContainerHeader* markAsRemoved(ContainerHeader* container) {
return reinterpret_cast<ContainerHeader*>(reinterpret_cast<uintptr_t>(container) | 1);
}
inline ContainerHeader* clearRemoved(ContainerHeader* container) {
return reinterpret_cast<ContainerHeader*>(
reinterpret_cast<uintptr_t>(container) & ~static_cast<uintptr_t>(1));
}
inline container_size_t alignUp(container_size_t size, int alignment) {
return (size + alignment - 1) & ~(alignment - 1);
}
inline ContainerHeader* realShareableContainer(ContainerHeader* container) {
RuntimeAssert(container->shareable(), "Only makes sense on shareable objects");
return reinterpret_cast<ObjHeader*>(container + 1)->container();
}
inline uint32_t arrayObjectSize(const TypeInfo* typeInfo, uint32_t count) {
// Note: array body is aligned, but for size computation it is enough to align the sum.
static_assert(kObjectAlignment % alignof(KLong) == 0, "");
static_assert(kObjectAlignment % alignof(KDouble) == 0, "");
return alignUp(sizeof(ArrayHeader) - typeInfo->instanceSize_ * count, kObjectAlignment);
}
inline uint32_t arrayObjectSize(const ArrayHeader* obj) {
return arrayObjectSize(obj->type_info(), obj->count_);
}
// TODO: shall we do padding for alignment?
inline container_size_t objectSize(const ObjHeader* obj) {
const TypeInfo* type_info = obj->type_info();
container_size_t size = (type_info->instanceSize_ < 0 ?
// An array.
arrayObjectSize(obj->array())
:
type_info->instanceSize_);
return alignUp(size, kObjectAlignment);
}
template <typename func>
inline void traverseContainerObjectFields(ContainerHeader* container, func process) {
RuntimeAssert(!isAggregatingFrozenContainer(container), "Must not be called on such containers");
ObjHeader* obj = reinterpret_cast<ObjHeader*>(container + 1);
for (int object = 0; object < container->objectCount(); object++) {
const TypeInfo* typeInfo = obj->type_info();
if (typeInfo != theArrayTypeInfo) {
for (int index = 0; index < typeInfo->objOffsetsCount_; index++) {
ObjHeader** location = reinterpret_cast<ObjHeader**>(
reinterpret_cast<uintptr_t>(obj) + typeInfo->objOffsets_[index]);
process(location);
}
} else {
ArrayHeader* array = obj->array();
for (int index = 0; index < array->count_; index++) {
process(ArrayAddressOfElementAt(array, index));
}
}
obj = reinterpret_cast<ObjHeader*>(
reinterpret_cast<uintptr_t>(obj) + objectSize(obj));
}
}
template <typename func>
inline void traverseContainerReferredObjects(ContainerHeader* container, func process) {
traverseContainerObjectFields(container, [process](ObjHeader** location) {
ObjHeader* ref = *location;
if (ref != nullptr) process(ref);
});
}
inline FrameOverlay* asFrameOverlay(ObjHeader** slot) {
return reinterpret_cast<FrameOverlay*>(slot);
}
inline bool isRefCounted(KConstRef object) {
return isFreeable(object->container());
}
inline void lock(KInt* spinlock) {
while (compareAndSwap(spinlock, 0, 1) != 0) {}
}
inline void unlock(KInt* spinlock) {
RuntimeCheck(compareAndSwap(spinlock, 1, 0) == 1, "Must succeed");
}
inline bool canFreeze(ContainerHeader* container) {
if (IsStrictMemoryModel)
// In strict memory model we ignore permanent, frozen and shared object when recursively freezing.
return container != nullptr && !container->shareable();
else
// In relaxed memory model we ignore permanent and frozen object when recursively freezing.
return container != nullptr && !container->frozen();
}
inline bool isFreezableAtomic(ObjHeader* obj) {
return obj->type_info() == theFreezableAtomicReferenceTypeInfo;
}
inline bool isFreezableAtomic(ContainerHeader* container) {
RuntimeAssert(!isAggregatingFrozenContainer(container), "Must be single object");
ObjHeader* obj = reinterpret_cast<ObjHeader*>(container + 1);
return isFreezableAtomic(obj);
}
ContainerHeader* allocContainer(MemoryState* state, size_t size) {
ContainerHeader* result = nullptr;
#if USE_GC
// We recycle elements of finalizer queue for new allocations, to avoid trashing memory manager.
ContainerHeader* container = state != nullptr ? state->finalizerQueue : nullptr;
ContainerHeader* previous = nullptr;
while (container != nullptr) {
// TODO: shall it be == instead?
if (container->hasContainerSize() &&
container->containerSize() >= size && container->containerSize() <= size + 16) {
MEMORY_LOG("recycle %p for request %d\n", container, size)
result = container;
if (previous == nullptr)
state->finalizerQueue = container->nextLink();
else
previous->setNextLink(container->nextLink());
state->finalizerQueueSize--;
memset(container, 0, size);
break;
}
previous = container;
container = container->nextLink();
}
#endif
if (result == nullptr) {
#if USE_GC
if (state != nullptr)
state->allocSinceLastGc += size;
#endif
result = konanConstructSizedInstance<ContainerHeader>(alignUp(size, kObjectAlignment));
atomicAdd(&allocCount, 1);
}
if (state != nullptr) {
CONTAINER_ALLOC_EVENT(state, size, result);
#if TRACE_MEMORY
state->containers->insert(result);
#endif
}
return result;
}
ContainerHeader* allocAggregatingFrozenContainer(KStdVector<ContainerHeader*>& containers) {
auto componentSize = containers.size();
auto* superContainer = allocContainer(memoryState, sizeof(ContainerHeader) + sizeof(void*) * componentSize);
auto* place = reinterpret_cast<ContainerHeader**>(superContainer + 1);
for (auto* container : containers) {
*place++ = container;
// Set link to the new container.
auto* obj = reinterpret_cast<ObjHeader*>(container + 1);
obj->setContainer(superContainer);
MEMORY_LOG("Set fictitious frozen container for %p: %p\n", obj, superContainer);
}
superContainer->setObjectCount(componentSize);
superContainer->freeze();
return superContainer;
}
#if USE_GC
void processFinalizerQueue(MemoryState* state) {
// TODO: reuse elements of finalizer queue for new allocations.
while (state->finalizerQueue != nullptr) {
auto* container = state->finalizerQueue;
state->finalizerQueue = container->nextLink();
state->finalizerQueueSize--;
#if TRACE_MEMORY
state->containers->erase(container);
#endif
CONTAINER_DESTROY_EVENT(state, container)
konanFreeMemory(container);
atomicAdd(&allocCount, -1);
}
RuntimeAssert(state->finalizerQueueSize == 0, "Queue must be empty here");
}
bool hasExternalRefs(ContainerHeader* start, ContainerHeaderSet* visited) {
ContainerHeaderDeque toVisit;
toVisit.push_back(start);
while (!toVisit.empty()) {
auto* container = toVisit.front();
toVisit.pop_front();
visited->insert(container);
if (container->refCount() > 0) {
MEMORY_LOG("container %p with rc %d blocks transfer\n", container, container->refCount())
return true;
}
traverseContainerReferredObjects(container, [&toVisit, visited](ObjHeader* ref) {
auto* child = ref->container();
if (!isShareable(child) && (visited->count(child) == 0)) {
toVisit.push_front(child);
}
});
}
return false;
}
#endif // USE_GC
void scheduleDestroyContainer(MemoryState* state, ContainerHeader* container) {
#if USE_GC
RuntimeAssert(container != nullptr, "Cannot destroy null container");
container->setNextLink(state->finalizerQueue);
state->finalizerQueue = container;
state->finalizerQueueSize++;
// We cannot clean finalizer queue while in GC.
if (!state->gcInProgress && state->finalizerQueueSuspendCount == 0 &&
state->finalizerQueueSize >= kFinalizerQueueThreshold) {
processFinalizerQueue(state);
}
#else
konanFreeMemory(container);
atomicAdd(&allocCount, -1);
CONTAINER_DESTROY_EVENT(state, container);
#endif
}
void freeAggregatingFrozenContainer(ContainerHeader* container) {
auto* state = memoryState;
RuntimeAssert(isAggregatingFrozenContainer(container), "expected fictitious frozen container");
MEMORY_LOG("%p is fictitious frozen container\n", container);
RuntimeAssert(!container->buffered(), "frozen objects must not participate in GC")
#if USE_GC
// Forbid finalizerQueue handling.
++state->finalizerQueueSuspendCount;
#endif
// Special container for frozen objects.
ContainerHeader** subContainer = reinterpret_cast<ContainerHeader**>(container + 1);
MEMORY_LOG("Total subcontainers = %d\n", container->objectCount());
for (int i = 0; i < container->objectCount(); ++i) {
MEMORY_LOG("Freeing subcontainer %p\n", *subContainer);
freeContainer(*subContainer++);
}
#if USE_GC
--state->finalizerQueueSuspendCount;
#endif
scheduleDestroyContainer(state, container);
MEMORY_LOG("Freeing subcontainers done\n");
}
void runDeallocationHooks(ContainerHeader* container) {
ObjHeader* obj = reinterpret_cast<ObjHeader*>(container + 1);
for (int index = 0; index < container->objectCount(); index++) {
if (obj->has_meta_object()) {
ObjHeader::destroyMetaObject(&obj->typeInfoOrMeta_);
}
obj = reinterpret_cast<ObjHeader*>(
reinterpret_cast<uintptr_t>(obj) + objectSize(obj));
}
}
void freeContainer(ContainerHeader* container) {
RuntimeAssert(container != nullptr, "this kind of container shalln't be freed");
if (isAggregatingFrozenContainer(container)) {
freeAggregatingFrozenContainer(container);
return;
}
runDeallocationHooks(container);
// Now let's clean all object's fields in this container.
traverseContainerObjectFields(container, [container](ObjHeader** location) {
ZeroHeapRef(location);
});
// And release underlying memory.
if (isFreeable(container)) {
container->setColorEvenIfGreen(CONTAINER_TAG_GC_BLACK);
if (!container->buffered())
scheduleDestroyContainer(memoryState, container);
}
}
/**
* Do DFS cycle detection with three colors:
* - 'marked' bit as BLACK marker (object and its descendants processed)
* - 'seen' bit as GRAY marker (object is being processed)
* - not 'marked' and not 'seen' as WHITE marker (object is unprocessed)
* When we see GREY during DFS, it means we see cycle.
*/
void depthFirstTraversal(ContainerHeader* start, bool* hasCycles,
KRef* firstBlocker, KStdVector<ContainerHeader*>* order) {
ContainerHeaderDeque toVisit;
toVisit.push_back(start);
start->setSeen();
while (!toVisit.empty()) {
auto* container = toVisit.front();
toVisit.pop_front();
if (isMarkedAsRemoved(container)) {
container = clearRemoved(container);
// Mark BLACK.
container->resetSeen();
container->mark();
order->push_back(container);
continue;
}
toVisit.push_front(markAsRemoved(container));
traverseContainerReferredObjects(container, [container, hasCycles, firstBlocker, &order, &toVisit](ObjHeader* obj) {
if (*firstBlocker != nullptr)
return;
if (obj->has_meta_object() && ((obj->meta_object()->flags_ & MF_NEVER_FROZEN) != 0)) {
*firstBlocker = obj;
return;
}
ContainerHeader* objContainer = obj->container();
if (canFreeze(objContainer)) {
// Marked GREY, there's cycle.
if (objContainer->seen()) *hasCycles = true;
// Go deeper if WHITE.
if (!objContainer->seen() && !objContainer->marked()) {
// Mark GRAY.
objContainer->setSeen();
// Here we do rather interesting trick: when doing DFS we postpone processing references going from
// FreezableAtomic, so that in 'order' referred value will be seen as not actually belonging
// to the same SCC (unless there are other edges not going through FreezableAtomic reaching the same value).
if (isFreezableAtomic(container)) {
toVisit.push_back(objContainer);
} else {
toVisit.push_front(objContainer);
}
}
}
});
}
}
void traverseStronglyConnectedComponent(ContainerHeader* start,
KStdUnorderedMap<ContainerHeader*,
KStdVector<ContainerHeader*>> const* reversedEdges,
KStdVector<ContainerHeader*>* component) {
ContainerHeaderDeque toVisit;
toVisit.push_back(start);
start->mark();
while (!toVisit.empty()) {
auto* container = toVisit.front();
toVisit.pop_front();
component->push_back(container);
auto it = reversedEdges->find(container);