-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathMetadataCache.h
1626 lines (1364 loc) · 57 KB
/
MetadataCache.h
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
//===--- MetadataCache.h - Implements the metadata cache --------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_RUNTIME_METADATACACHE_H
#define SWIFT_RUNTIME_METADATACACHE_H
#include "swift/Runtime/AtomicWaitQueue.h"
#include "swift/Runtime/Concurrent.h"
#include "swift/Runtime/Metadata.h"
#include "swift/Threading/Mutex.h"
#include "swift/shims/Visibility.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/STLExtras.h"
#include <atomic>
#include <condition_variable>
#include <optional>
#include <tuple>
#ifndef SWIFT_DEBUG_RUNTIME
#define SWIFT_DEBUG_RUNTIME 0
#endif
namespace swift {
RelativeWitnessTable *lookThroughOptionalConditionalWitnessTable(const RelativeWitnessTable *);
#if !SWIFT_STDLIB_PASSTHROUGH_METADATA_ALLOCATOR
class MetadataAllocator : public llvm::AllocatorBase<MetadataAllocator> {
private:
uint16_t Tag;
public:
constexpr MetadataAllocator(uint16_t tag) : Tag(tag) {}
MetadataAllocator() = delete;
void Reset() {}
/// Get the location of the allocator's initial statically allocated pool.
/// The return values are start and size. If there is no statically allocated
/// pool, the return values are NULL, 0.
static std::tuple<const void *, size_t> InitialPoolLocation();
SWIFT_RETURNS_NONNULL SWIFT_NODISCARD
void *Allocate(size_t size, size_t alignment);
using AllocatorBase<MetadataAllocator>::Allocate;
void Deallocate(const void *Ptr, size_t size, size_t Alignment);
using AllocatorBase<MetadataAllocator>::Deallocate;
void PrintStats() const {}
MetadataAllocator withTag(uint16_t Tag) {
MetadataAllocator Allocator = *this;
Allocator.Tag = Tag;
return Allocator;
}
};
#else
class MetadataAllocator {
public:
MetadataAllocator(uint16_t tag) {}
static std::tuple<const void *, size_t> InitialPoolLocation() {
return {nullptr, 0};
}
SWIFT_RETURNS_NONNULL SWIFT_NODISCARD
void *Allocate(size_t size, size_t alignment) {
if (alignment < sizeof(void*)) alignment = sizeof(void*);
void *ptr = nullptr;
if (SWIFT_UNLIKELY(posix_memalign(&ptr, alignment, size) != 0 || !ptr)) {
swift::crash("Could not allocate memory for type metadata.");
}
return ptr;
}
void Deallocate(const void *ptr, size_t size = 0, size_t Alignment = 0) {
return free(const_cast<void *>(ptr));
}
};
#endif
template <uint16_t StaticTag>
class TaggedMetadataAllocator : public MetadataAllocator {
public:
constexpr TaggedMetadataAllocator() : MetadataAllocator(StaticTag) {}
};
using RawPrivateMetadataState = uint8_t;
enum class PrivateMetadataState : RawPrivateMetadataState {
/// The metadata is being allocated.
Allocating,
/// The metadata has been allocated, but is not yet complete for
/// external layout: that is, it does not have a size.
Abstract,
/// The metadata has a complete external layout, but may not have
/// been fully initialized.
LayoutComplete,
/// The metadata has a complete external layout and has been fully
/// initialized, but has not yet satisfied its transitive completeness
/// requirements.
NonTransitiveComplete,
/// The metadata is fully complete. There should no longer be waiters.
Complete
};
inline bool operator<(PrivateMetadataState lhs, PrivateMetadataState rhs) {
return RawPrivateMetadataState(lhs) < RawPrivateMetadataState(rhs);
}
inline bool operator<=(PrivateMetadataState lhs, PrivateMetadataState rhs) {
return RawPrivateMetadataState(lhs) <= RawPrivateMetadataState(rhs);
}
inline bool operator>(PrivateMetadataState lhs, PrivateMetadataState rhs) {
return RawPrivateMetadataState(lhs) > RawPrivateMetadataState(rhs);
}
inline bool operator>=(PrivateMetadataState lhs, PrivateMetadataState rhs) {
return RawPrivateMetadataState(lhs) >= RawPrivateMetadataState(rhs);
}
inline bool satisfies(PrivateMetadataState state, MetadataState requirement) {
switch (requirement) {
case MetadataState::Abstract:
return state >= PrivateMetadataState::Abstract;
case MetadataState::LayoutComplete:
return state >= PrivateMetadataState::LayoutComplete;
case MetadataState::NonTransitiveComplete:
return state >= PrivateMetadataState::NonTransitiveComplete;
case MetadataState::Complete:
return state >= PrivateMetadataState::Complete;
}
swift_unreachable("unsupported requirement kind");
}
inline MetadataState getAccomplishedRequestState(PrivateMetadataState state) {
switch (state) {
case PrivateMetadataState::Allocating:
swift_unreachable("cannot call on allocating state");
case PrivateMetadataState::Abstract:
return MetadataState::Abstract;
case PrivateMetadataState::LayoutComplete:
return MetadataState::LayoutComplete;
case PrivateMetadataState::NonTransitiveComplete:
return MetadataState::NonTransitiveComplete;
case PrivateMetadataState::Complete:
return MetadataState::Complete;
}
swift_unreachable("bad state");
}
struct MetadataStateWithDependency {
/// The current state of the metadata.
PrivateMetadataState NewState;
/// The known dependency that the metadata has, if any.
MetadataDependency Dependency;
};
/// A typedef for simple global caches with stable addresses for the entries.
template <class EntryTy, uint16_t Tag>
using SimpleGlobalCache =
StableAddressConcurrentReadableHashMap<EntryTy,
TaggedMetadataAllocator<Tag>>;
struct ConcurrencyControl {
using LockType = SmallMutex;
LockType Lock;
};
template <class EntryType, uint16_t Tag>
class LockingConcurrentMapStorage {
// This class must fit within
// TargetGenericMetadataInstantiationCache::PrivateData. On 32-bit archs, that
// space is not large enough to accommodate a Mutex along with everything
// else. There, use a SmallMutex to squeeze into the available space.
using MutexTy = std::conditional_t<sizeof(void *) == 8 && sizeof(Mutex) <= 56,
Mutex, SmallMutex>;
StableAddressConcurrentReadableHashMap<EntryType,
TaggedMetadataAllocator<Tag>, MutexTy>
Map;
ConcurrencyControl Concurrency;
public:
LockingConcurrentMapStorage() {}
ConcurrencyControl &getConcurrency() { return Concurrency; }
template <class KeyType, class... ArgTys>
std::pair<EntryType*, bool>
getOrInsert(KeyType key, ArgTys &&...args) {
return Map.getOrInsert(key, args...);
}
template <class KeyType>
EntryType *find(KeyType key) {
return Map.find(key);
}
/// A default implementation for resolveEntry that assumes that the
/// key type is a lookup key for the map.
template <class KeyType>
EntryType *resolveExistingEntry(KeyType key) {
auto entry = Map.find(key);
assert(entry && "entry doesn't already exist!");
return entry;
}
};
/// A map for which there is a phase of initialization that is guaranteed
/// to be performed exclusively.
///
/// In addition to the requirements of ConcurrentMap, the entry type must
/// provide the following members:
///
/// /// An encapsulation of the status of the entry. The result type
/// /// of most operations.
/// using Status = ...;
///
/// /// Given that this is not the thread currently responsible for
/// /// initializing the entry, wait for the entry to complete.
/// Status await(ConcurrencyControl &concurrency, ArgTys...);
///
/// /// Perform allocation. If this returns a status, initialization
/// /// is skipped.
/// Optional<Status>
/// beginAllocation(WaitQueue::Worker &worker, ArgTys...);
///
/// /// Attempt to initialize an entry. This is called once for the entry,
/// /// immediately after construction, by the thread that successfully
/// /// constructed the entry.
/// Status beginInitialization(WaitQueue::Worker &worker, ArgTys...);
///
/// /// Perform a checkDependency operation. This only needs to be
/// /// implemented if checkDependency is called on the map.
/// MetadataStateWithDependency
/// checkDependency(ConcurrencyControl &concurrency, ArgTys...);
template <class EntryType,
class StorageType = LockingConcurrentMapStorage<EntryType, true>>
class LockingConcurrentMap {
StorageType Storage;
using Status = typename EntryType::Status;
using WaitQueue = typename EntryType::WaitQueue;
using Worker = typename WaitQueue::Worker;
using Waiter = typename WaitQueue::Waiter;
public:
LockingConcurrentMap() = default;
template <class KeyType, class... ArgTys>
std::pair<EntryType*, Status>
getOrInsert(KeyType key, ArgTys &&...args) {
Worker worker(Storage.getConcurrency().Lock);
auto result = Storage.getOrInsert(key, worker, args...);
auto entry = result.first;
// If we are not inserting the entry, we need to potentially block on
// currently satisfies our conditions.
if (!result.second) {
auto status =
entry->await(Storage.getConcurrency(), std::forward<ArgTys>(args)...);
return { entry, status };
}
// Okay, we inserted. We are responsible for allocating and
// subsequently trying to initialize the entry.
// Insertion should have called worker.createQueue(); tell the Worker
// object that we published it.
worker.flagCreatedQueueIsPublished();
// Allocation. This can fast-path and bypass initialization by returning
// a status.
if (auto status = entry->beginAllocation(worker, args...)) {
return { entry, *status };
}
// Initialization.
auto status = entry->beginInitialization(worker,
std::forward<ArgTys>(args)...);
return { entry, status };
}
template <class KeyType>
EntryType *find(KeyType key) {
return Storage.find(key);
}
/// Given that an entry already exists, await it.
template <class KeyType, class... ArgTys>
Status await(KeyType key, ArgTys &&...args) {
EntryType *entry = Storage.resolveExistingEntry(key);
return entry->await(Storage.getConcurrency(),
std::forward<ArgTys>(args)...);
}
/// If an entry already exists, await it; otherwise report failure.
template <class KeyType, class... ArgTys>
std::optional<Status> tryAwaitExisting(KeyType key, ArgTys &&...args) {
EntryType *entry = Storage.find(key);
if (!entry)
return std::nullopt;
return entry->await(Storage.getConcurrency(),
std::forward<ArgTys>(args)...);
}
/// Given that an entry already exists, check whether it has an active
/// dependency.
template <class KeyType, class... ArgTys>
MetadataStateWithDependency
checkDependency(KeyType key, ArgTys &&...args) {
EntryType *entry = Storage.resolveExistingEntry(key);
return entry->checkDependency(Storage.getConcurrency(),
std::forward<ArgTys>(args)...);
}
};
/// A base class for metadata cache entries which supports an unfailing
/// one-phase allocation strategy that should not be done by trial.
///
/// In addition to the requirements of ConcurrentMap, subclasses should
/// provide:
///
/// /// Allocate the cached entry. This is not allowed to fail.
/// ValueType allocate(ArgTys...);
template <class Impl, class ValueType>
class SimpleLockingCacheEntryBase {
public:
using WaitQueue = SimpleAtomicWaitQueue<ConcurrencyControl::LockType>;
private:
static_assert(std::is_pointer<ValueType>::value,
"value type must be a pointer type");
static const uintptr_t IsWaitQueue = 1;
static WaitQueue *getAsWaitQueue(uintptr_t value) {
if (value & IsWaitQueue)
return reinterpret_cast<WaitQueue*>(value & ~IsWaitQueue);
return nullptr;
}
static ValueType castAsValue(uintptr_t value) {
assert(!(value & IsWaitQueue));
return reinterpret_cast<ValueType>(value);
}
std::atomic<uintptr_t> Value;
protected:
Impl &asImpl() { return static_cast<Impl &>(*this); }
const Impl &asImpl() const { return static_cast<const Impl &>(*this); }
SimpleLockingCacheEntryBase(WaitQueue::Worker &worker)
: Value(reinterpret_cast<uintptr_t>(worker.createQueue()) | IsWaitQueue) {}
public:
using Status = ValueType;
template <class... ArgTys>
Status await(ConcurrencyControl &concurrency, ArgTys &&...args) {
WaitQueue::Waiter waiter(concurrency.Lock);
// Load the value. If this is not a queue, we're done.
auto value = Value.load(std::memory_order_acquire);
if (getAsWaitQueue(value)) {
bool waited = waiter.tryReloadAndWait([&] {
// We can use a relaxed load because we're already ordered
// by the lock.
value = Value.load(std::memory_order_relaxed);
return getAsWaitQueue(value);
});
if (waited) {
// This load can be relaxed because we acquired the wait queue
// lock, which was released by the worker thread after
// initializing Value to the value.
value = Value.load(std::memory_order_relaxed);
assert(!getAsWaitQueue(value));
}
}
return castAsValue(value);
}
template <class... ArgTys>
std::optional<Status> beginAllocation(WaitQueue::Worker &worker,
ArgTys &&...args) {
// Delegate to the implementation class.
ValueType origValue =
asImpl().allocate(std::forward<ArgTys>(args)...);
auto value = reinterpret_cast<uintptr_t>(origValue);
assert(!getAsWaitQueue(value) && "allocate returned an unaligned value");
// Publish the value, which unpublishes the queue.
worker.finishAndUnpublishQueue([&] {
Value.store(value, std::memory_order_release);
});
return origValue;
}
template <class... ArgTys>
Status beginInitialization(WaitQueue::Worker &worker,
ArgTys &&...args) {
swift_unreachable("beginAllocation always short-circuits");
}
};
/// A summary of the information from a generic signature that's
/// sufficient to compare arguments.
template<typename Runtime>
struct GenericSignatureLayout {
uint16_t NumKeyParameters = 0;
uint16_t NumWitnessTables = 0;
uint16_t NumPacks = 0;
uint16_t NumShapeClasses = 0;
const GenericPackShapeDescriptor *PackShapeDescriptors = nullptr;
GenericSignatureLayout(const RuntimeGenericSignature<Runtime> &sig)
: NumPacks(sig.getGenericPackShapeHeader().NumPacks),
NumShapeClasses(sig.getGenericPackShapeHeader().NumShapeClasses),
PackShapeDescriptors(sig.getGenericPackShapeDescriptors().data()) {
#ifndef NDEBUG
unsigned packIdx = 0;
#endif
for (const auto &gp : sig.getParams()) {
if (gp.hasKeyArgument()) {
#ifndef NDEBUG
if (gp.getKind() == GenericParamKind::TypePack) {
assert(packIdx < NumPacks);
assert(PackShapeDescriptors[packIdx].Kind
== GenericPackKind::Metadata);
assert(PackShapeDescriptors[packIdx].Index
== NumShapeClasses + NumKeyParameters);
assert(PackShapeDescriptors[packIdx].ShapeClass
< NumShapeClasses);
++packIdx;
}
#endif
++NumKeyParameters;
}
}
for (const auto &reqt : sig.getRequirements()) {
if (reqt.Flags.hasKeyArgument() &&
reqt.getKind() == GenericRequirementKind::Protocol) {
#ifndef NDEBUG
if (reqt.getFlags().isPackRequirement()) {
assert(packIdx < NumPacks);
assert(PackShapeDescriptors[packIdx].Kind
== GenericPackKind::WitnessTable);
assert(PackShapeDescriptors[packIdx].Index
== NumShapeClasses + NumKeyParameters + NumWitnessTables);
assert(PackShapeDescriptors[packIdx].ShapeClass
< NumShapeClasses);
++packIdx;
}
#endif
++NumWitnessTables;
}
}
#ifndef NDEBUG
assert(packIdx == NumPacks);
#endif
}
size_t sizeInWords() const {
return NumShapeClasses + NumKeyParameters + NumWitnessTables;
}
friend bool operator==(const GenericSignatureLayout<Runtime> &lhs,
const GenericSignatureLayout<Runtime> &rhs) {
if (lhs.NumKeyParameters != rhs.NumKeyParameters ||
lhs.NumWitnessTables != rhs.NumWitnessTables ||
lhs.NumShapeClasses != rhs.NumShapeClasses ||
lhs.NumPacks != rhs.NumPacks) {
return false;
}
for (unsigned i = 0; i < lhs.NumPacks; ++i) {
const auto &lhsElt = lhs.PackShapeDescriptors[i];
const auto &rhsElt = rhs.PackShapeDescriptors[i];
if (lhsElt.Kind != rhsElt.Kind ||
lhsElt.Index != rhsElt.Index ||
lhsElt.ShapeClass != rhsElt.ShapeClass)
return false;
}
return true;
}
friend bool operator!=(const GenericSignatureLayout<Runtime> &lhs,
const GenericSignatureLayout<Runtime> &rhs) {
return !(lhs == rhs);
}
};
/// A key value as provided to the concurrent map.
class MetadataCacheKey {
const void * const *Data;
GenericSignatureLayout<InProcess> Layout;
uint32_t Hash;
public:
/// Compare two witness tables, which may involving checking the
/// contents of their conformance descriptors.
static bool areWitnessTablesEqual(const WitnessTable *awt,
const WitnessTable *bwt) {
if (awt == bwt)
return true;
#if SWIFT_STDLIB_USE_RELATIVE_PROTOCOL_WITNESS_TABLES
auto *aDescription = lookThroughOptionalConditionalWitnessTable(
reinterpret_cast<const RelativeWitnessTable*>(awt))->getDescription();
auto *bDescription = lookThroughOptionalConditionalWitnessTable(
reinterpret_cast<const RelativeWitnessTable*>(bwt))->getDescription();
#else
auto *aDescription = awt->getDescription();
auto *bDescription = bwt->getDescription();
#endif
return areConformanceDescriptorsEqual(aDescription, bDescription);
}
static void installGenericArguments(uint16_t numKeyArguments, uint16_t numPacks,
const GenericPackShapeDescriptor *packShapeDescriptors,
const void **dst, const void * const *src);
/// Compare two conformance descriptors, checking their contents if necessary.
static bool areConformanceDescriptorsEqual(
const ProtocolConformanceDescriptor *aDescription,
const ProtocolConformanceDescriptor *bDescription) {
if (aDescription == bDescription)
return true;
if (!aDescription->isSynthesizedNonUnique() ||
!bDescription->isSynthesizedNonUnique())
return aDescription == bDescription;
auto aType = aDescription->getCanonicalTypeMetadata();
auto bType = bDescription->getCanonicalTypeMetadata();
if (!aType || !bType)
return aDescription == bDescription;
return (aType == bType &&
aDescription->getProtocol() == bDescription->getProtocol());
}
private:
static bool areMetadataPacksEqual(const void *lhsPtr,
const void *rhsPtr,
uintptr_t count) {
MetadataPackPointer lhs(lhsPtr);
MetadataPackPointer rhs(rhsPtr);
// lhs is the user-supplied key, which might be on the stack.
// rhs is the stored key in the cache.
assert(rhs.getLifetime() == PackLifetime::OnHeap);
auto *lhsElt = lhs.getElements();
auto *rhsElt = rhs.getElements();
for (uintptr_t i = 0; i < count; ++i) {
if (lhsElt[i] != rhsElt[i])
return false;
}
return true;
}
static bool areWitnessTablePacksEqual(const void *lhsPtr,
const void *rhsPtr,
uintptr_t count) {
WitnessTablePackPointer lhs(lhsPtr);
WitnessTablePackPointer rhs(rhsPtr);
// lhs is the user-supplied key, which might be on the stack.
// rhs is the stored key in the cache.
assert(rhs.getLifetime() == PackLifetime::OnHeap);
auto *lhsElt = lhs.getElements();
auto *rhsElt = rhs.getElements();
for (uintptr_t i = 0; i < count; ++i) {
if (!areWitnessTablesEqual(lhsElt[i], rhsElt[i]))
return false;
}
return true;
}
public:
MetadataCacheKey(const GenericSignatureLayout<InProcess> &layout,
const void *const *data)
: Data(data), Layout(layout), Hash(computeHash()) {}
MetadataCacheKey(const GenericSignatureLayout<InProcess> &layout,
const void *const *data, uint32_t hash)
: Data(data), Layout(layout), Hash(hash) {}
bool operator==(const MetadataCacheKey &rhs) const {
// Compare the hashes.
if (hash() != rhs.hash()) return false;
// Fast path the case where they're bytewise identical. That's nearly always
// the case if the hashes are the same, and we can skip the slower deep
// comparison.
auto *adata = begin();
auto *bdata = rhs.begin();
auto asize = (uintptr_t)end() - (uintptr_t)adata;
auto bsize = (uintptr_t)rhs.end() - (uintptr_t)bdata;
// If sizes don't match, they can never be equal.
if (asize != bsize)
return false;
// If sizes match, see if the bytes match. If they do, then the contents
// must necessarily match. Otherwise do a deep comparison.
if (memcmp(adata, bdata, asize) == 0)
return true;
// Compare the layouts.
if (Layout != rhs.Layout) return false;
// Compare the content.
const uintptr_t *packCounts = reinterpret_cast<const uintptr_t *>(adata);
unsigned argIdx = 0;
// Compare pack lengths for shape classes.
for (unsigned i = 0; i != Layout.NumShapeClasses; ++i) {
if (adata[argIdx] != bdata[argIdx])
return false;
++argIdx;
}
auto *packs = Layout.PackShapeDescriptors;
unsigned packIdx = 0;
// Compare generic arguments for key parameters.
for (unsigned i = 0; i != Layout.NumKeyParameters; ++i) {
// Is this entry a metadata pack?
if (packIdx < Layout.NumPacks &&
packs[packIdx].Kind == GenericPackKind::Metadata &&
argIdx == packs[packIdx].Index) {
assert(packs[packIdx].ShapeClass < Layout.NumShapeClasses);
uintptr_t count = packCounts[packs[packIdx].ShapeClass];
if (!areMetadataPacksEqual(adata[argIdx], bdata[argIdx], count))
return false;
++packIdx;
++argIdx;
continue;
}
if (adata[argIdx] != bdata[argIdx])
return false;
++argIdx;
}
// Compare witness tables.
for (unsigned i = 0; i != Layout.NumWitnessTables; ++i) {
// Is this entry a witness table pack?
if (packIdx < Layout.NumPacks &&
packs[packIdx].Kind == GenericPackKind::WitnessTable &&
argIdx == packs[packIdx].Index) {
assert(packs[packIdx].ShapeClass < Layout.NumShapeClasses);
uintptr_t count = packCounts[packs[packIdx].ShapeClass];
if (!areWitnessTablePacksEqual(adata[argIdx], bdata[argIdx], count))
return false;
++packIdx;
++argIdx;
continue;
}
if (!areWitnessTablesEqual((const WitnessTable *)adata[argIdx],
(const WitnessTable *)bdata[argIdx]))
return false;
++argIdx;
}
assert(packIdx == Layout.NumPacks && "Missed a pack");
return true;
}
uint32_t hash() const {
return Hash;
}
const GenericSignatureLayout<InProcess> &layout() const { return Layout; }
friend llvm::hash_code hash_value(const MetadataCacheKey &key) {
return key.Hash;
}
const void * const *begin() const { return Data; }
const void * const *end() const { return Data + size(); }
unsigned size() const { return Layout.sizeInWords(); }
void installInto(const void **buffer) const {
MetadataCacheKey::installGenericArguments(
Layout.sizeInWords(),
Layout.NumPacks,
Layout.PackShapeDescriptors,
buffer, Data);
}
private:
uint32_t computeHash() const {
size_t H = 0x56ba80d1u * Layout.NumKeyParameters;
auto *packs = Layout.PackShapeDescriptors;
unsigned packIdx = 0;
auto update = [&H](uintptr_t value) {
H = (H >> 10) | (H << ((sizeof(uintptr_t) * 8) - 10));
H ^= (value ^ (value >> 19));
};
// FIXME: The first NumShapeClasses entries are pack counts;
// incorporate them into the hash
for (unsigned i = Layout.NumShapeClasses,
e = Layout.NumShapeClasses + Layout.NumKeyParameters;
i != e; ++i) {
// Is this entry a metadata pack?
if (packIdx < Layout.NumPacks &&
packs[packIdx].Kind == GenericPackKind::Metadata &&
i == packs[packIdx].Index) {
assert(packs[packIdx].ShapeClass < Layout.NumShapeClasses);
auto count = reinterpret_cast<uintptr_t>(Data[packs[packIdx].ShapeClass]);
++packIdx;
MetadataPackPointer pack(Data[i]);
for (unsigned j = 0; j < count; ++j)
update(reinterpret_cast<uintptr_t>(pack.getElements()[j]));
continue;
}
update(reinterpret_cast<uintptr_t>(Data[i]));
}
H *= 0x27d4eb2d;
// Rotate right by 10 and then truncate to 32 bits.
return uint32_t((H >> 10) | (H << ((sizeof(uintptr_t) * 8) - 10)));
}
};
/// A helper class for ConcurrentMap entry types which allows trailing objects
/// objects and automatically implements the getExtraAllocationSize methods
/// in terms of numTrailingObjects calls.
///
/// For each trailing object type T, the subclass must provide:
/// size_t numTrailingObjects(OverloadToken<T>) const;
/// static size_t numTrailingObjects(OverloadToken<T>, ...) const;
/// where the arguments to the latter are the arguments to getOrInsert,
/// including the key.
template <class Impl, class... Objects>
struct ConcurrentMapTrailingObjectsEntry
: swift::ABI::TrailingObjects<Impl, Objects...> {
protected:
using TrailingObjects =
swift::ABI::TrailingObjects<Impl, Objects...>;
Impl &asImpl() { return static_cast<Impl &>(*this); }
const Impl &asImpl() const { return static_cast<const Impl &>(*this); }
template<typename T>
using OverloadToken = typename TrailingObjects::template OverloadToken<T>;
public:
template <class KeyType, class... Args>
static size_t getExtraAllocationSize(const KeyType &key,
Args &&...args) {
return TrailingObjects::template additionalSizeToAlloc<Objects...>(
Impl::numTrailingObjects(OverloadToken<Objects>(), key, args...)...);
}
size_t getExtraAllocationSize() const {
return TrailingObjects::template additionalSizeToAlloc<Objects...>(
asImpl().numTrailingObjects(OverloadToken<Objects>())...);
}
};
/// Reserve the runtime extra space to use for its own tracking.
struct PrivateMetadataCompletionContext {
MetadataCompletionContext Public;
};
/// The alignment required for objects that will be stored in
/// PrivateMetadataTrackingInfo.
const size_t PrivateMetadataTrackingAlignment = 16;
/// The wait queue object that we create for metadata that are
/// being actively initialized right now.
struct alignas(PrivateMetadataTrackingAlignment) MetadataWaitQueue :
public AtomicWaitQueue<MetadataWaitQueue, ConcurrencyControl::LockType> {
/// A pointer to the completion context being used to complete this
/// metadata. This is only actually filled in if:
///
/// - the initializing thread is unable to complete the metadata,
/// but its request doesn't need it to, and
/// - the current completion context is non-zero. (Completion contexts
/// are initially zeroed, so this only happens if the initialization
/// actually stores to the context, which is uncommon.)
///
/// This should only be touched by the initializing thread, i.e. the
/// thread that holds the lock embedded in this object.
std::unique_ptr<PrivateMetadataCompletionContext> PersistentContext;
/// The dependency that is currently blocking this initialization.
/// This should only be touched while holding the global lock
/// for this metadata cache.
MetadataDependency BlockingDependency;
class Worker : public AtomicWaitQueue::Worker {
using super = AtomicWaitQueue::Worker;
PrivateMetadataState State = PrivateMetadataState::Allocating;
public:
Worker(ConcurrencyControl::LockType &globalLock) : super(globalLock) {}
void flagCreatedQueueIsPublished() {
// This method is called after successfully inserting an entry into
// the atomic storage, at a point that just assumes that a queue
// was created. However, we may not have created a queue if the
// metadata was completed during construction.
//
// Testing CurrentQueue to see if we published a queue is generally
// suspect because we might be looping and calling createQueue()
// on each iteration. However, the metadata cache system won't do
// this, at least on the path leading to the call to this method,
// so this works in this one case.
if (CurrentQueue) {
assert(State < PrivateMetadataState::Complete);
super::flagCreatedQueueIsPublished();
} else {
assert(State == PrivateMetadataState::Complete);
}
}
void setState(PrivateMetadataState newState) {
// It would be nice to assert isWorkerThread() here, but we need
// this to be callable before we've published the queue.
State = newState;
}
PrivateMetadataState getState() const {
assert(isWorkerThread() || State == PrivateMetadataState::Complete);
return State;
}
};
};
/// A record used to store information about an attempt to
/// complete a metadata when there's no active worker thread.
struct alignas(PrivateMetadataTrackingAlignment) SuspendedMetadataCompletion {
MetadataDependency BlockingDependency;
std::unique_ptr<PrivateMetadataCompletionContext> PersistentContext;
SuspendedMetadataCompletion(MetadataDependency blockingDependency,
PrivateMetadataCompletionContext *context)
: BlockingDependency(blockingDependency),
PersistentContext(context) {}
};
class PrivateMetadataTrackingInfo {
public:
using RawType = uintptr_t;
private:
enum : RawType {
StateMask = 0x7,
PointerIsWaitQueueMask = 0x8,
AllBitsMask = StateMask | PointerIsWaitQueueMask,
PointerMask = ~AllBitsMask,
};
static_assert(AllBitsMask < PrivateMetadataTrackingAlignment,
"too many bits for alignment");
RawType Data;
public:
// Some std::atomic implementations require a default constructor
// for no apparent reason.
PrivateMetadataTrackingInfo() : Data(0) {}
explicit PrivateMetadataTrackingInfo(PrivateMetadataState state)
: Data(RawType(state)) {}
explicit PrivateMetadataTrackingInfo(PrivateMetadataState state,
MetadataWaitQueue *queue)
: Data(RawType(state) | reinterpret_cast<RawType>(queue)
| PointerIsWaitQueueMask) {
assert(queue);
assert(!(reinterpret_cast<RawType>(queue) & AllBitsMask));
}
explicit PrivateMetadataTrackingInfo(PrivateMetadataState state,
SuspendedMetadataCompletion *suspended)
: Data(RawType(state) | reinterpret_cast<RawType>(suspended)) {
assert(!(reinterpret_cast<RawType>(suspended) & AllBitsMask));
}
static PrivateMetadataTrackingInfo
initial(MetadataWaitQueue::Worker &worker,
PrivateMetadataState initialState) {
worker.setState(initialState);
if (initialState != PrivateMetadataState::Complete)
return PrivateMetadataTrackingInfo(initialState, worker.createQueue());
return PrivateMetadataTrackingInfo(initialState);
}
PrivateMetadataState getState() const {
return PrivateMetadataState(Data & StateMask);
}
/// Does the state mean that we've allocated metadata?
bool hasAllocatedMetadata() const {
return getState() != PrivateMetadataState::Allocating;
}
bool isComplete() const {
return getState() == PrivateMetadataState::Complete;
}
bool hasWaitQueue() const {
return Data & PointerIsWaitQueueMask;
}
MetadataWaitQueue *getWaitQueue() const {
if (hasWaitQueue())
return reinterpret_cast<MetadataWaitQueue*>(Data & PointerMask);
return nullptr;
}
SuspendedMetadataCompletion *getSuspendedCompletion() const {
if (!hasWaitQueue())
return reinterpret_cast<SuspendedMetadataCompletion*>(Data & PointerMask);
return nullptr;
}
/// Return the blocking dependency for this metadata. Should only
/// be called while holding the global lock for the metadata cache.
MetadataDependency getBlockingDependency_locked() const {
if (auto queue = getWaitQueue())
return queue->BlockingDependency;
if (auto dependency = getSuspendedCompletion())
return dependency->BlockingDependency;
return MetadataDependency();
}
bool satisfies(MetadataState requirement) {
return swift::satisfies(getState(), requirement);
}
enum CheckResult {
/// The request is satisfied.
Satisfied,
/// The request is not satisfied, and the requesting thread
/// should report that immediately.
Unsatisfied,
/// The request is not satisfied, and the requesting thread
/// must wait for another thread to complete the initialization.
Wait,
/// The request is not satisfied, and the requesting thread
/// should try to complete the initialization itself.
Resume,
};
CheckResult check(MetadataRequest request) {
switch (getState()) {
// Always wait if the metadata is still allocating. Non-blocking
// requests still need to allocate abstract metadata that
// downstream consumers can report a dependency on.
case PrivateMetadataState::Allocating:
return Wait;
// We never need to do anything if we're complete. This is the