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
1837 lines (1630 loc) · 58.7 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-2017 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 "Memory.h"
#include "MemoryPrivate.hpp"
#include "Natives.h"
#include "Porting.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
// Collect memory manager events statistics.
#define COLLECT_STATISTIC 0
// Auto-adjust GC thresholds.
#define GC_ERGONOMICS 1
namespace {
// Granularity of arena container chunks.
constexpr container_size_t kContainerAlignment = 1024;
// Single object alignment.
constexpr container_size_t kObjectAlignment = 8;
#if TRACE_MEMORY
#define MEMORY_LOG(...) konan::consolePrintf(__VA_ARGS__);
#else
#define MEMORY_LOG(...)
#endif
#if USE_GC
// Collection threshold default (collect after having so many elements in the
// release candidates set).
constexpr size_t kGcThreshold = 4 * 1024;
#if GC_ERGONOMICS
// 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 = 1024 * 1024;
#endif // GC_ERGONOMICS
typedef KStdDeque<ContainerHeader*> ContainerHeaderDeque;
#endif
} // namespace
#if TRACE_MEMORY || USE_GC
typedef KStdUnorderedSet<ContainerHeader*> ContainerHeaderSet;
typedef KStdVector<ContainerHeader*> ContainerHeaderList;
typedef KStdVector<KRef*> KRefPtrList;
#endif
struct FrameOverlay {
ArenaContainer* arena;
};
// 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.
int allocCount = 0;
int aliveMemoryStatesCount = 0;
// Forward declarations.
void FreeContainer(ContainerHeader* header);
#if COLLECT_STATISTIC
class MemoryStatistic {
public:
// UpdateRef per-object type counters.
uint64_t updateCounters[4][4];
// Alloc per container type counters.
uint64_t containerAllocs[4][2];
// Free per container type counters.
uint64_t objectAllocs[4][2];
// Histogram of allocation size distribution.
KStdUnorderedMap<int, int>* allocationHistogram;
// Number of allocation cache hits.
int allocCacheHit;
// Number of allocation cache misses.
int allocCacheMiss;
// Map of array index to human readable name.
static constexpr const char* indexToName[] = { "normal", "stack ", "perm ", "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 incUpdateRef(const ObjHeader* objOld, const ObjHeader* objNew) {
updateCounters[toIndex(objOld)][toIndex(objNew)]++;
}
void incAlloc(size_t size, const ContainerHeader* header) {
containerAllocs[toIndex(header)][0]++;
++(*allocationHistogram)[size];
#if 0
auto queue = memoryState->finalizerQueue;
bool hit = false;
for (int i = 0; i < queue->size(); i++) {
auto container = (*queue)[i];
if (containerSize(container) == size) {
hit = true;
break;
}
}
if (hit)
allocCacheHit++;
else
allocCacheMiss++;
#endif // USE_GC
}
void incFree(const ContainerHeader* header) {
containerAllocs[toIndex(header)][1]++;
}
void incAlloc(size_t size, const ObjHeader* header) {
objectAllocs[toIndex(header)][0]++;
}
void incFree(const ObjHeader* header) {
objectAllocs[toIndex(header)][1]++;
}
static int toIndex(const ObjHeader* obj) {
if (obj == nullptr) return 3;
return toIndex(obj->container());
}
static int toIndex(const ContainerHeader* header) {
switch (header->tag()) {
case CONTAINER_TAG_NORMAL : return 0;
case CONTAINER_TAG_STACK : return 1;
case CONTAINER_TAG_PERMANENT: return 2;
}
RuntimeAssert(false, "unknown container type");
return -1;
}
void printStatistic() {
konan::consolePrintf("\nMemory manager statistic:\n\n");
for (int i = 0; i < 2; i++) {
konan::consolePrintf("Container %s alloc: %lld, free: %lld\n",
indexToName[i], containerAllocs[i][0],
containerAllocs[i][1]);
}
for (int i = 0; i < 2; i++) {
konan::consolePrintf("Object %s alloc: %lld, free: %lld\n",
indexToName[i], objectAllocs[i][0],
objectAllocs[i][1]);
}
konan::consolePrintf("\n");
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
konan::consolePrintf("UpdateRef[%s -> %s]: %lld\n",
indexToName[i], indexToName[j], updateCounters[i][j]);
}
}
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());
for (auto& it : keys) {
konan::consolePrintf(
"%d bytes -> %d times\n", it, (*allocationHistogram)[it]);
}
#if USE_GC
konan::consolePrintf(
"alloc cache: %d hits/%d misses\n", allocCacheHit, allocCacheMiss);
#endif // USE_GC
}
};
constexpr const char* MemoryStatistic::indexToName[];
#endif // COLLECT_STATISTIC
struct MemoryState {
#if TRACE_MEMORY
// Set of all containers.
ContainerHeaderSet* containers;
#endif
#if USE_GC
// Finalizer queue.
ContainerHeaderDeque* finalizerQueue;
/*
* 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 toFree shall trigger collection.
size_t gcThreshold;
// If collection is in progress.
bool gcInProgress;
int finalizerQueueSuspendCount;
#if GC_ERGONOMICS
uint64_t lastGcTimestamp;
#endif
#endif // USE_GC
#if COLLECT_STATISTIC
#define CONTAINER_ALLOC_STAT(state, size, container) state->statistic.incAlloc(size, container);
#define CONTAINER_FREE_STAT(state, container)
#define CONTAINER_DESTROY_STAT(state, container) \
state->statistic.incFree(container);
#define OBJECT_ALLOC_STAT(state, size, object) \
state->statistic.incAlloc(size, object);
#define OBJECT_FREE_STAT(state, size, object) \
state->statistic.incFree(object);
#define UPDATE_REF_STAT(state, oldRef, newRef, slot) \
state->statistic.incUpdateRef(oldRef, newRef);
#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_FREE_STAT(state, container)
#define CONTAINER_DESTROY_STAT(state, container)
#define OBJECT_ALLOC_STAT(state, size, object)
#define OBJECT_FREE_STAT(state, object)
#define UPDATE_REF_STAT(state, oldRef, newRef, slot)
#define INIT_STAT(state)
#define DEINIT_STAT(state)
#define PRINT_STAT(state)
#endif // COLLECT_STATISTIC
};
#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_FREE_TRACE(state, container) \
MEMORY_LOG("Container free %p\n", 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 OBJECT_FREE_TRACE(state, object) \
MEMORY_LOG("Object free %p\n", object)
#define UPDATE_REF_TRACE(state, oldRef, newRef, slot) \
MEMORY_LOG("UpdateRef *%p: %p -> %p\n", 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 freeing (memory is still in use).
#define CONTAINER_FREE_EVENT(state, container) \
CONTAINER_FREE_STAT(state, container) \
CONTAINER_FREE_TRACE(state, 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) \
UPDATE_REF_STAT(state, oldRef, newRef, slot) \
UPDATE_REF_TRACE(state, oldRef, newRef, slot)
// Infomation shall be printed as worker is exiting.
#define PRINT_EVENT(state) \
PRINT_STAT(state)
namespace {
// TODO: can we pass this variable as an explicit argument?
THREAD_LOCAL_VARIABLE MemoryState* memoryState = nullptr;
// TODO: use widely.
inline void EnsureRuntimeInitialized() {
RuntimeCheck(memoryState != nullptr, "Unable to execute Kotlin code on uninitialized thread");
}
constexpr int kFrameOverlaySlots = sizeof(FrameOverlay) / sizeof(ObjHeader**);
inline bool isFreeable(const ContainerHeader* header) {
return header->tag() < CONTAINER_TAG_PERMANENT;
}
inline bool isArena(const ContainerHeader* header) {
return header->stack();
}
inline bool isAggregatingFrozenContainer(const ContainerHeader* header) {
return header->frozen() && header->objectCount() > 1;
}
inline container_size_t alignUp(container_size_t size, int alignment) {
return (size + alignment - 1) & ~(alignment - 1);
}
// 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.
ArrayDataSizeBytes(obj->array()) + sizeof(ArrayHeader)
:
type_info->instanceSize_ + sizeof(ObjHeader));
return alignUp(size, kObjectAlignment);
}
inline bool isArenaSlot(ObjHeader** slot) {
return (reinterpret_cast<uintptr_t>(slot) & ARENA_BIT) != 0;
}
inline ObjHeader** asArenaSlot(ObjHeader** slot) {
return reinterpret_cast<ObjHeader**>(
reinterpret_cast<uintptr_t>(slot) & ~ARENA_BIT);
}
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");
}
} // namespace
void KRefSharedHolder::initRefOwner() {
RuntimeAssert(owner_ == nullptr, "Must be uninitialized");
owner_ = memoryState;
}
void KRefSharedHolder::verifyRefOwner() const {
// Note: checking for 'permanentOrFrozen()' and retrieving 'type_info()'
// are supposed to be correct even for unowned object.
if (owner_ != memoryState && !obj_->container()->permanentOrFrozen()) {
EnsureRuntimeInitialized();
// TODO: add some info about the owner.
ThrowIllegalObjectSharingException(obj_->type_info(), obj_);
}
}
extern "C" {
// Ensure LLVM never throws theStaticObjectsContainer away.
// TODO: although practically const, marking it as such makes LLVM crazy, fix it.
RUNTIME_USED ContainerHeader theStaticObjectsContainer = {
CONTAINER_TAG_PERMANENT | CONTAINER_TAG_INCREMENT,
0 /* Object count */
};
void objc_release(void* ptr);
void Kotlin_ObjCExport_releaseAssociatedObject(void* associatedObject);
RUNTIME_NORETURN void ThrowFreezingException(KRef toFreeze, KRef blocker);
} // extern "C"
inline 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 DeinitInstanceBody(const TypeInfo* typeInfo, void* body) {
for (int index = 0; index < typeInfo->objOffsetsCount_; index++) {
ObjHeader** location = reinterpret_cast<ObjHeader**>(
reinterpret_cast<uintptr_t>(body) + typeInfo->objOffsets_[index]);
UpdateRef(location, nullptr);
}
}
namespace {
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 + 1) + 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);
});
}
#if USE_GC
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 void processFinalizerQueue(MemoryState* state) {
// TODO: reuse elements of finalizer queue for new allocations.
while (!state->finalizerQueue->empty()) {
auto container = memoryState->finalizerQueue->back();
state->finalizerQueue->pop_back();
#if TRACE_MEMORY
state->containers->erase(container);
#endif
CONTAINER_DESTROY_EVENT(state, container)
konanFreeMemory(container);
atomicAdd(&allocCount, -1);
}
}
#endif
inline void scheduleDestroyContainer(
MemoryState* state, ContainerHeader* container) {
#if USE_GC
state->finalizerQueue->push_front(container);
// We cannot clean finalizer queue while in GC.
if (!state->gcInProgress && state->finalizerQueueSuspendCount == 0 && state->finalizerQueue->size() > 256) {
processFinalizerQueue(state);
}
#else
atomicAdd(&allocCount, -1);
CONTAINER_DESTROY_EVENT(state, container)
konanFreeMemory(container);
#endif
}
#if !USE_GC
template <bool Atomic>
inline void IncrementRC(ContainerHeader* container) {
container->incRefCount<Atomic>();
}
template <bool Atomic>
inline void DecrementRC(ContainerHeader* container, bool useCycleCollector) {
if (container->decRefCount<Atomic>() == 0) {
FreeContainer(container);
}
}
#else // USE_GC
inline uint32_t freeableSize(MemoryState* state) {
return state->toFree->size();
}
template <bool Atomic>
inline void IncrementRC(ContainerHeader* container) {
container->incRefCount<Atomic>();
container->setColor(CONTAINER_TAG_GC_BLACK);
}
template <bool Atomic>
inline void DecrementRC(ContainerHeader* container, bool useCycleCollector) {
if (container->decRefCount<Atomic>() == 0) {
FreeContainer(container);
} else if (!Atomic && useCycleCollector) { // Possible root.
// Do not use cycle collector for frozen objects, as we already detected possible cycles during
// freezing.
if (container->color() != CONTAINER_TAG_GC_PURPLE) {
container->setColor(CONTAINER_TAG_GC_PURPLE);
if (!container->buffered()) {
container->setBuffered();
auto state = memoryState;
state->toFree->push_back(container);
if (state->gcSuspendCount == 0 && freeableSize(state) >= state->gcThreshold) {
GarbageCollect();
}
}
}
}
}
inline void initThreshold(MemoryState* state, uint32_t gcThreshold) {
state->gcThreshold = gcThreshold;
state->toFree->reserve(gcThreshold);
}
#endif // USE_GC
#if TRACE_MEMORY || USE_GC
void dumpWorker(const char* prefix, ContainerHeader* header, ContainerHeaderSet* seen) {
MEMORY_LOG("%s: %p (%08x): %d refs\n", prefix, header, header->refCount_,
header->refCount_ >> CONTAINER_TAG_SHIFT)
seen->insert(header);
traverseContainerReferredObjects(header, [prefix, seen](ObjHeader* ref) {
auto child = ref->container();
RuntimeAssert(!isArena(child), "A reference to local object is encountered");
if (!child->permanent() && (seen->count(child) == 0)) {
dumpWorker(prefix, child, seen);
}
});
}
void dumpReachable(const char* prefix, const ContainerHeaderSet* roots) {
ContainerHeaderSet seen;
for (auto container : *roots) {
MEMORY_LOG("%p: %s%s%s\n", container,
container->frozen() ? "frozen " : "",
container->permanent() ? "permanent " : "",
container->stack() ? "stack " : "")
dumpWorker(prefix, container, &seen);
}
}
#endif
void MarkRoots(MemoryState*);
void DeleteCorpses(MemoryState*);
void ScanRoots(MemoryState*);
void CollectRoots(MemoryState*);
template<bool useColor>
void MarkGray(ContainerHeader* container) {
if (useColor) {
if (container->color() == CONTAINER_TAG_GC_GRAY) return;
} else {
if (container->marked()) return;
}
if (useColor) {
container->setColor(CONTAINER_TAG_GC_GRAY);
} else {
container->mark();
}
traverseContainerReferredObjects(container, [](ObjHeader* ref) {
auto childContainer = ref->container();
RuntimeAssert(!isArena(childContainer), "A reference to local object is encountered");
if (!childContainer->permanentOrFrozen()) {
childContainer->decRefCount<false>();
MarkGray<useColor>(childContainer);
}
});
}
void Scan(ContainerHeader* container);
template<bool useColor>
void ScanBlack(ContainerHeader* container) {
if (useColor) {
container->setColor(CONTAINER_TAG_GC_BLACK);
} else {
container->unMark();
}
traverseContainerReferredObjects(container, [](ObjHeader* ref) {
auto childContainer = ref->container();
RuntimeAssert(!isArena(childContainer), "A reference to local object is encountered");
if (!childContainer->permanentOrFrozen()) {
childContainer->incRefCount<false>();
if (useColor) {
if (childContainer->color() != CONTAINER_TAG_GC_BLACK)
ScanBlack<useColor>(childContainer);
} else {
if (childContainer->marked())
ScanBlack<useColor>(childContainer);
}
}
});
}
void CollectWhite(MemoryState*, ContainerHeader* container);
void CollectCycles(MemoryState* state) {
MarkRoots(state);
ScanRoots(state);
CollectRoots(state);
state->toFree->clear();
state->roots->clear();
}
void MarkRoots(MemoryState* state) {
for (auto container : *(state->toFree)) {
if (isMarkedAsRemoved(container))
continue;
auto color = container->color();
auto rcIsZero = container->refCount() == 0;
if (color == CONTAINER_TAG_GC_PURPLE && !rcIsZero) {
MarkGray<true>(container);
state->roots->push_back(container);
} else {
container->resetBuffered();
if (color == CONTAINER_TAG_GC_BLACK && rcIsZero) {
scheduleDestroyContainer(state, container);
}
}
}
}
void ScanRoots(MemoryState* state) {
for (auto container : *(state->roots)) {
Scan(container);
}
}
void CollectRoots(MemoryState* state) {
for (auto container : *(state->roots)) {
container->resetBuffered();
CollectWhite(state, container);
}
}
void Scan(ContainerHeader* container) {
if (container->color() != CONTAINER_TAG_GC_GRAY) return;
if (container->refCount() != 0) {
ScanBlack<true>(container);
return;
}
container->setColor(CONTAINER_TAG_GC_WHITE);
traverseContainerReferredObjects(container, [](ObjHeader* ref) {
auto childContainer = ref->container();
RuntimeAssert(!isArena(childContainer), "A reference to local object is encountered");
if (!childContainer->permanentOrFrozen()) {
Scan(childContainer);
}
});
}
void CollectWhite(MemoryState* state, ContainerHeader* container) {
if (container->color() != CONTAINER_TAG_GC_WHITE || container->buffered())
return;
container->setColor(CONTAINER_TAG_GC_BLACK);
traverseContainerObjectFields(container, [state](ObjHeader** location) {
auto ref = *location;
if (ref == nullptr) return;
auto childContainer = ref->container();
RuntimeAssert(!isArena(childContainer), "A reference to local object is encountered");
if (childContainer->permanentOrFrozen()) {
UpdateRef(location, nullptr);
} else {
CollectWhite(state, childContainer);
}
});
runDeallocationHooks(container);
scheduleDestroyContainer(state, container);
}
inline void AddRef(ContainerHeader* header) {
// Looking at container type we may want to skip AddRef() totally
// (non-escaping stack objects, constant objects).
switch (header->refCount_ & CONTAINER_TAG_MASK) {
case CONTAINER_TAG_STACK:
case CONTAINER_TAG_PERMANENT:
break;
case CONTAINER_TAG_NORMAL:
IncrementRC<false>(header);
break;
case CONTAINER_TAG_FROZEN:
IncrementRC<true>(header);
break;
default:
RuntimeAssert(false, "unknown container type");
break;
}
}
inline void Release(ContainerHeader* header, bool useCycleCollector) {
// Looking at container type we may want to skip Release() totally
// (non-escaping stack objects, constant objects).
switch (header->refCount_ & CONTAINER_TAG_MASK) {
case CONTAINER_TAG_PERMANENT:
case CONTAINER_TAG_STACK:
break;
case CONTAINER_TAG_NORMAL:
DecrementRC<false>(header, useCycleCollector);
break;
case CONTAINER_TAG_FROZEN:
DecrementRC<true>(header, useCycleCollector);
break;
default:
RuntimeAssert(false, "unknown container type");
break;
}
}
// We use first slot as place to store frame-local arena container.
// TODO: create ArenaContainer object on the stack, so that we don't
// do two allocations per frame (ArenaContainer + actual container).
inline ArenaContainer* initedArena(ObjHeader** auxSlot) {
auto frame = asFrameOverlay(auxSlot);
auto arena = frame->arena;
if (!arena) {
arena = konanConstructInstance<ArenaContainer>();
MEMORY_LOG("Initializing arena in %p\n", frame)
arena->Init();
frame->arena = arena;
}
return arena;
}
inline size_t containerSize(const ContainerHeader* container) {
size_t result = 0;
const ObjHeader* obj = reinterpret_cast<const ObjHeader*>(container + 1);
for (int object = 0; object < container->objectCount(); object++) {
size_t size = objectSize(obj);
result += size;
obj = reinterpret_cast<ObjHeader*>(
reinterpret_cast<uintptr_t>(obj) + size);
}
return result;
}
} // namespace
MetaObjHeader* ObjHeader::createMetaObject(TypeInfo** location) {
MetaObjHeader* meta = konanConstructInstance<MetaObjHeader>();
TypeInfo* typeInfo = *location;
meta->typeInfo_ = typeInfo;
#if KONAN_NO_THREADS
*location = reinterpret_cast<TypeInfo*>(meta);
#else
TypeInfo* old = __sync_val_compare_and_swap(location, typeInfo, reinterpret_cast<TypeInfo*>(meta));
if (old->typeInfo_ != old) {
// Someone installed a new meta-object since the check.
konanFreeMemory(meta);
meta = reinterpret_cast<MetaObjHeader*>(old);
}
#endif
return meta;
}
void ObjHeader::destroyMetaObject(TypeInfo** location) {
MetaObjHeader* meta = *(reinterpret_cast<MetaObjHeader**>(location));
*const_cast<const TypeInfo**>(location) = meta->typeInfo_;
if (meta->counter_ != nullptr) {
WeakReferenceCounterClear(meta->counter_);
UpdateRef(&meta->counter_, nullptr);
}
#ifdef KONAN_OBJC_INTEROP
Kotlin_ObjCExport_releaseAssociatedObject(meta->associatedObject_);
#endif
konanFreeMemory(meta);
}
ContainerHeader* AllocContainer(size_t size) {
auto state = memoryState;
#if USE_GC
// TODO: try to reuse elements of finalizer queue for new allocations, question
// is how to get actual size of container.
#endif
ContainerHeader* result = konanConstructSizedInstance<ContainerHeader>(alignUp(size, kObjectAlignment));
CONTAINER_ALLOC_EVENT(state, size, result);
#if TRACE_MEMORY
state->containers->insert(result);
#endif
atomicAdd(&allocCount, 1);
return result;
}
ContainerHeader* AllocAggregatingFrozenContainer(KStdVector<ContainerHeader*>& containers) {
auto componentSize = containers.size();
auto superContainer = AllocContainer(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->container_ = superContainer;
MEMORY_LOG("Set fictitious frozen container for %p: %p\n", obj, superContainer);
}
superContainer->setObjectCount(componentSize);
superContainer->freeze();
return superContainer;
}
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")
// Forbid finalizerQueue handling.
++state->finalizerQueueSuspendCount;
// 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++);
}
--state->finalizerQueueSuspendCount;
scheduleDestroyContainer(state, container);
MEMORY_LOG("Freeing subcontainers done\n");
}
void FreeContainer(ContainerHeader* container) {
RuntimeAssert(!container->permanent(), "this kind of container shalln't be freed");
auto state = memoryState;
CONTAINER_FREE_EVENT(state, container)
if (isAggregatingFrozenContainer(container)) {
FreeAggregatingFrozenContainer(container);
return;
}
runDeallocationHooks(container);
// Now let's clean all object's fields in this container.
traverseContainerObjectFields(container, [](ObjHeader** location) {
UpdateRef(location, nullptr);
});
// And release underlying memory.
if (isFreeable(container)) {
container->setColor(CONTAINER_TAG_GC_BLACK);
if (!container->buffered())
scheduleDestroyContainer(state, container);
}
}
void ObjectContainer::Init(const TypeInfo* typeInfo) {
RuntimeAssert(typeInfo->instanceSize_ >= 0, "Must be an object");
uint32_t alloc_size =
sizeof(ContainerHeader) + sizeof(ObjHeader) + typeInfo->instanceSize_;
header_ = AllocContainer(alloc_size);
if (header_) {
// One object in this container.
header_->setObjectCount(1);
// header->refCount_ is zero initialized by AllocContainer().
SetHeader(GetPlace(), typeInfo);
MEMORY_LOG("object at %p\n", GetPlace())
OBJECT_ALLOC_EVENT(memoryState, typeInfo->instanceSize_, GetPlace())
}
}
void ArrayContainer::Init(const TypeInfo* typeInfo, uint32_t elements) {
RuntimeAssert(typeInfo->instanceSize_ < 0, "Must be an array");
uint32_t alloc_size =
sizeof(ContainerHeader) + sizeof(ArrayHeader) -
typeInfo->instanceSize_ * elements;
header_ = AllocContainer(alloc_size);
RuntimeAssert(header_ != nullptr, "Cannot alloc memory");
if (header_) {
// One object in this container.
header_->setObjectCount(1);
// header->refCount_ is zero initialized by AllocContainer().
GetPlace()->count_ = elements;
SetHeader(GetPlace()->obj(), typeInfo);
MEMORY_LOG("array at %p\n", GetPlace())
OBJECT_ALLOC_EVENT(
memoryState, -typeInfo->instanceSize_ * elements, GetPlace()->obj())
}
}
// TODO: store arena containers in some reuseable data structure, similar to
// finalizer queue.
void ArenaContainer::Init() {
allocContainer(1024);
}
void ArenaContainer::Deinit() {
MEMORY_LOG("Arena::Deinit start: %p\n", this)
auto chunk = currentChunk_;
while (chunk != nullptr) {
// FreeContainer() doesn't release memory when CONTAINER_TAG_STACK is set.
MEMORY_LOG("Arena::Deinit free chunk %p\n", chunk)
FreeContainer(chunk->asHeader());
chunk = chunk->next;
}
chunk = currentChunk_;
while (chunk != nullptr) {
auto toRemove = chunk;
chunk = chunk->next;
konanFreeMemory(toRemove);
}
}
bool ArenaContainer::allocContainer(container_size_t minSize) {
auto size = minSize + sizeof(ContainerHeader) + sizeof(ContainerChunk);
size = alignUp(size, kContainerAlignment);
// TODO: keep simple cache of container chunks.
ContainerChunk* result = konanConstructSizedInstance<ContainerChunk>(size);
RuntimeAssert(result != nullptr, "Cannot alloc memory");
if (result == nullptr) return false;
result->next = currentChunk_;
result->arena = this;
result->asHeader()->refCount_ = (CONTAINER_TAG_STACK | CONTAINER_TAG_INCREMENT);
currentChunk_ = result;
current_ = reinterpret_cast<uint8_t*>(result->asHeader() + 1);
end_ = reinterpret_cast<uint8_t*>(result) + size;
return true;
}
void* ArenaContainer::place(container_size_t size) {
size = alignUp(size, kObjectAlignment);
// Fast path.