-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathcallcounting.cpp
1399 lines (1169 loc) · 49.8 KB
/
callcounting.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#include "common.h"
#ifdef FEATURE_TIERED_COMPILATION
#include "callcounting.h"
#include "threadsuspend.h"
#ifndef DACCESS_COMPILE
extern "C" void STDCALL OnCallCountThresholdReachedStub();
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// CallCountingStub
#ifndef DACCESS_COMPILE
const PCODE CallCountingStub::TargetForThresholdReached = (PCODE)GetEEFuncEntryPoint(OnCallCountThresholdReachedStub);
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// CallCountingManager::CallCountingInfo
#ifndef DACCESS_COMPILE
CallCountingManager::CallCountingInfo::CallCountingInfo(NativeCodeVersion codeVersion)
: m_codeVersion(codeVersion),
m_callCountingStub(nullptr),
m_remainingCallCount(0),
m_stage(Stage::Disabled)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(!codeVersion.IsNull());
}
CallCountingManager::CallCountingInfo *
CallCountingManager::CallCountingInfo::CreateWithCallCountingDisabled(NativeCodeVersion codeVersion)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
return new CallCountingInfo(codeVersion);
}
CallCountingManager::CallCountingInfo::CallCountingInfo(NativeCodeVersion codeVersion, CallCount callCountThreshold)
: m_codeVersion(codeVersion),
m_callCountingStub(nullptr),
m_remainingCallCount(callCountThreshold),
m_stage(Stage::StubIsNotActive)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(!codeVersion.IsNull());
_ASSERTE(callCountThreshold != 0);
}
CallCountingManager::CallCountingInfo::~CallCountingInfo()
{
WRAPPER_NO_CONTRACT;
_ASSERTE(m_stage == Stage::Complete);
_ASSERTE(m_callCountingStub == nullptr);
}
#endif // !DACCESS_COMPILE
CallCountingManager::PTR_CallCountingInfo CallCountingManager::CallCountingInfo::From(PTR_CallCount remainingCallCountCell)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(remainingCallCountCell != nullptr);
return PTR_CallCountingInfo(dac_cast<TADDR>(remainingCallCountCell) - offsetof(CallCountingInfo, m_remainingCallCount));
}
NativeCodeVersion CallCountingManager::CallCountingInfo::GetCodeVersion() const
{
WRAPPER_NO_CONTRACT;
return m_codeVersion;
}
#ifndef DACCESS_COMPILE
const CallCountingStub *CallCountingManager::CallCountingInfo::GetCallCountingStub() const
{
WRAPPER_NO_CONTRACT;
_ASSERTE(m_stage != Stage::Disabled);
return m_callCountingStub;
}
void CallCountingManager::CallCountingInfo::SetCallCountingStub(const CallCountingStub *callCountingStub)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(g_pConfig->TieredCompilation_UseCallCountingStubs());
_ASSERTE(m_stage == Stage::StubIsNotActive);
_ASSERTE(m_callCountingStub == nullptr);
_ASSERTE(callCountingStub != nullptr);
++s_callCountingStubCount;
m_callCountingStub = callCountingStub;
}
void CallCountingManager::CallCountingInfo::ClearCallCountingStub()
{
WRAPPER_NO_CONTRACT;
_ASSERTE(m_stage == Stage::StubIsNotActive || m_stage == Stage::Complete);
_ASSERTE(m_callCountingStub != nullptr);
m_callCountingStub = nullptr;
// The total and completed stub counts are updated along with deleting stubs
}
PTR_CallCount CallCountingManager::CallCountingInfo::GetRemainingCallCountCell()
{
WRAPPER_NO_CONTRACT;
_ASSERTE(m_stage != Stage::Disabled);
//_ASSERTE(m_callCountingStub != nullptr);
return &m_remainingCallCount;
}
#endif // !DACCESS_COMPILE
CallCountingManager::CallCountingInfo::Stage CallCountingManager::CallCountingInfo::GetStage() const
{
WRAPPER_NO_CONTRACT;
return m_stage;
}
#ifndef DACCESS_COMPILE
FORCEINLINE void CallCountingManager::CallCountingInfo::SetStage(Stage stage)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(m_stage != Stage::Disabled);
_ASSERTE(stage <= Stage::Complete);
switch (stage)
{
case Stage::StubIsNotActive:
_ASSERTE(m_stage == Stage::StubMayBeActive);
_ASSERTE(m_callCountingStub != nullptr);
_ASSERTE(s_activeCallCountingStubCount != 0);
--s_activeCallCountingStubCount;
break;
case Stage::StubMayBeActive:
_ASSERTE(m_callCountingStub != nullptr);
FALLTHROUGH;
case Stage::PendingCompletion:
_ASSERTE(m_stage == Stage::StubIsNotActive || m_stage == Stage::StubMayBeActive);
if (m_stage == Stage::StubIsNotActive && m_callCountingStub != nullptr)
{
++s_activeCallCountingStubCount;
}
break;
case Stage::Complete:
_ASSERTE(m_stage != Stage::Complete);
if (m_callCountingStub != nullptr)
{
if (m_stage != Stage::StubIsNotActive)
{
_ASSERTE(s_activeCallCountingStubCount != 0);
--s_activeCallCountingStubCount;
}
++s_completedCallCountingStubCount;
}
break;
default:
UNREACHABLE();
}
m_stage = stage;
}
#endif
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// CallCountingManager::CallCountingInfo::CodeVersionHashTraits
CallCountingManager::CallCountingInfo::CodeVersionHashTraits::key_t
CallCountingManager::CallCountingInfo::CodeVersionHashTraits::GetKey(const element_t &e)
{
WRAPPER_NO_CONTRACT;
return e->GetCodeVersion();
}
BOOL CallCountingManager::CallCountingInfo::CodeVersionHashTraits::Equals(const key_t &k1, const key_t &k2)
{
WRAPPER_NO_CONTRACT;
return k1 == k2;
}
CallCountingManager::CallCountingInfo::CodeVersionHashTraits::count_t
CallCountingManager::CallCountingInfo::CodeVersionHashTraits::Hash(const key_t &k)
{
WRAPPER_NO_CONTRACT;
return (count_t)dac_cast<TADDR>(k.GetMethodDesc()) + k.GetVersionId();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// CallCountingManager::CallCountingStubAllocator
CallCountingManager::CallCountingStubAllocator::CallCountingStubAllocator() : m_heap(nullptr)
{
WRAPPER_NO_CONTRACT;
}
CallCountingManager::CallCountingStubAllocator::~CallCountingStubAllocator()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
#ifndef DACCESS_COMPILE
LoaderHeap *heap = m_heap;
if (heap != nullptr)
{
delete m_heap;
}
#endif
}
#ifndef DACCESS_COMPILE
void CallCountingManager::CallCountingStubAllocator::Reset()
{
WRAPPER_NO_CONTRACT;
this->~CallCountingStubAllocator();
new(this) CallCountingStubAllocator();
}
const CallCountingStub *CallCountingManager::CallCountingStubAllocator::AllocateStub(
CallCount *remainingCallCountCell,
PCODE targetForMethod)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
LoaderHeap *heap = m_heap;
if (heap == nullptr)
{
heap = AllocateHeap();
}
SIZE_T sizeInBytes = sizeof(CallCountingStub);
AllocMemHolder<void> allocationAddressHolder(heap->AllocAlignedMem(sizeInBytes, 1));
CallCountingStub *stub = (CallCountingStub*)(void*)allocationAddressHolder;
allocationAddressHolder.SuppressRelease();
stub->Initialize(targetForMethod, remainingCallCountCell);
return stub;
}
#if defined(TARGET_ARM64) && defined(TARGET_UNIX)
#define ENUM_PAGE_SIZE(size) \
extern "C" void CallCountingStubCode##size(); \
extern "C" void CallCountingStubCode##size##_End();
ENUM_PAGE_SIZES
#undef ENUM_PAGE_SIZE
#else
extern "C" void CallCountingStubCode();
extern "C" void CallCountingStubCode_End();
#endif
#ifdef TARGET_X86
extern "C" size_t CallCountingStubCode_RemainingCallCountCell_Offset;
extern "C" size_t CallCountingStubCode_TargetForMethod_Offset;
extern "C" size_t CallCountingStubCode_TargetForThresholdReached_Offset;
#define SYMBOL_VALUE(name) ((size_t)&name)
#endif
#if defined(TARGET_ARM64) && defined(TARGET_UNIX)
void (*CallCountingStub::CallCountingStubCode)();
#endif
#ifndef DACCESS_COMPILE
void CallCountingStub::StaticInitialize()
{
#if defined(TARGET_ARM64) && defined(TARGET_UNIX)
int pageSize = GetStubCodePageSize();
#define ENUM_PAGE_SIZE(size) \
case size: \
CallCountingStubCode = CallCountingStubCode##size; \
_ASSERTE((SIZE_T)((BYTE*)CallCountingStubCode##size##_End - (BYTE*)CallCountingStubCode##size) <= CallCountingStub::CodeSize); \
break;
switch (pageSize)
{
ENUM_PAGE_SIZES
default:
EEPOLICY_HANDLE_FATAL_ERROR_WITH_MESSAGE(COR_E_EXECUTIONENGINE, W("Unsupported OS page size"));
}
#undef ENUM_PAGE_SIZE
#else
_ASSERTE((SIZE_T)((BYTE*)CallCountingStubCode_End - (BYTE*)CallCountingStubCode) <= CallCountingStub::CodeSize);
#endif
}
#endif // DACCESS_COMPILE
void CallCountingStub::GenerateCodePage(BYTE* pageBase, BYTE* pageBaseRX, SIZE_T pageSize)
{
#ifdef TARGET_X86
int totalCodeSize = (pageSize / CallCountingStub::CodeSize) * CallCountingStub::CodeSize;
for (int i = 0; i < totalCodeSize; i += CallCountingStub::CodeSize)
{
memcpy(pageBase + i, (const void*)CallCountingStubCode, CallCountingStub::CodeSize);
// Set absolute addresses of the slots in the stub
BYTE* pCounterSlot = pageBaseRX + i + pageSize + offsetof(CallCountingStubData, RemainingCallCountCell);
*(BYTE**)(pageBase + i + SYMBOL_VALUE(CallCountingStubCode_RemainingCallCountCell_Offset)) = pCounterSlot;
BYTE* pTargetSlot = pageBaseRX + i + pageSize + offsetof(CallCountingStubData, TargetForMethod);
*(BYTE**)(pageBase + i + SYMBOL_VALUE(CallCountingStubCode_TargetForMethod_Offset)) = pTargetSlot;
BYTE* pCountReachedZeroSlot = pageBaseRX + i + pageSize + offsetof(CallCountingStubData, TargetForThresholdReached);
*(BYTE**)(pageBase + i + SYMBOL_VALUE(CallCountingStubCode_TargetForThresholdReached_Offset)) = pCountReachedZeroSlot;
}
#else // TARGET_X86
FillStubCodePage(pageBase, (const void*)PCODEToPINSTR((PCODE)CallCountingStubCode), CallCountingStub::CodeSize, pageSize);
#endif
}
NOINLINE LoaderHeap *CallCountingManager::CallCountingStubAllocator::AllocateHeap()
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
_ASSERTE(m_heap == nullptr);
LoaderHeap *heap = new LoaderHeap(0, 0, &m_heapRangeList, UnlockedLoaderHeap::HeapKind::Interleaved, true /* fUnlocked */, CallCountingStub::GenerateCodePage, CallCountingStub::CodeSize);
m_heap = heap;
return heap;
}
#endif // !DACCESS_COMPILE
bool CallCountingManager::CallCountingStubAllocator::IsStub(TADDR entryPoint)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(entryPoint != NULL);
return !!m_heapRangeList.IsInRange(entryPoint);
}
#ifdef DACCESS_COMPILE
void CallCountingManager::CallCountingStubAllocator::EnumerateHeapRanges(CLRDataEnumMemoryFlags flags)
{
WRAPPER_NO_CONTRACT;
m_heapRangeList.EnumMemoryRegions(flags);
}
#endif // DACCESS_COMPILE
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// CallCountingManager::MethodDescForwarderStubHashTraits
CallCountingManager::MethodDescForwarderStubHashTraits::key_t
CallCountingManager::MethodDescForwarderStubHashTraits::GetKey(const element_t &e)
{
WRAPPER_NO_CONTRACT;
return e->GetMethodDesc();
}
BOOL CallCountingManager::MethodDescForwarderStubHashTraits::Equals(const key_t &k1, const key_t &k2)
{
WRAPPER_NO_CONTRACT;
return k1 == k2;
}
CallCountingManager::MethodDescForwarderStubHashTraits::count_t
CallCountingManager::MethodDescForwarderStubHashTraits::Hash(const key_t &k)
{
WRAPPER_NO_CONTRACT;
return (count_t)(size_t)k;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// CallCountingManager::CallCountingManagerHashTraits
CallCountingManager::CallCountingManagerHashTraits::key_t
CallCountingManager::CallCountingManagerHashTraits::GetKey(const element_t &e)
{
WRAPPER_NO_CONTRACT;
return e;
}
BOOL CallCountingManager::CallCountingManagerHashTraits::Equals(const key_t &k1, const key_t &k2)
{
WRAPPER_NO_CONTRACT;
return k1 == k2;
}
CallCountingManager::CallCountingManagerHashTraits::count_t
CallCountingManager::CallCountingManagerHashTraits::Hash(const key_t &k)
{
WRAPPER_NO_CONTRACT;
return (count_t)dac_cast<TADDR>(k);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// CallCountingManager
CallCountingManager::PTR_CallCountingManagerHash CallCountingManager::s_callCountingManagers = PTR_NULL;
COUNT_T CallCountingManager::s_callCountingStubCount = 0;
COUNT_T CallCountingManager::s_activeCallCountingStubCount = 0;
COUNT_T CallCountingManager::s_completedCallCountingStubCount = 0;
CallCountingManager::CallCountingManager()
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
#ifndef DACCESS_COMPILE
CodeVersionManager::LockHolder codeVersioningLockHolder;
s_callCountingManagers->Add(this);
#endif
}
CallCountingManager::~CallCountingManager()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
#ifndef DACCESS_COMPILE
CodeVersionManager::LockHolder codeVersioningLockHolder;
for (auto itEnd = m_callCountingInfoByCodeVersionHash.End(), it = m_callCountingInfoByCodeVersionHash.Begin();
it != itEnd;
++it)
{
CallCountingInfo *callCountingInfo = *it;
delete callCountingInfo;
}
s_callCountingManagers->Remove(this);
#endif
}
#ifndef DACCESS_COMPILE
void CallCountingManager::StaticInitialize()
{
WRAPPER_NO_CONTRACT;
s_callCountingManagers = PTR_CallCountingManagerHash(new CallCountingManagerHash());
CallCountingStub::StaticInitialize();
}
#endif
bool CallCountingManager::IsCallCountingEnabled(NativeCodeVersion codeVersion)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
_ASSERTE(!codeVersion.IsNull());
_ASSERTE(codeVersion.IsDefaultVersion());
_ASSERTE(codeVersion.GetMethodDesc()->IsEligibleForTieredCompilation());
CodeVersionManager::LockHolder codeVersioningLockHolder;
PTR_CallCountingInfo callCountingInfo = m_callCountingInfoByCodeVersionHash.Lookup(codeVersion);
return callCountingInfo == NULL || callCountingInfo->GetStage() != CallCountingInfo::Stage::Disabled;
}
#ifndef DACCESS_COMPILE
void CallCountingManager::DisableCallCounting(NativeCodeVersion codeVersion)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
MODE_ANY;
}
CONTRACTL_END;
_ASSERTE(!codeVersion.IsNull());
_ASSERTE(codeVersion.IsDefaultVersion());
_ASSERTE(codeVersion.GetMethodDesc()->IsEligibleForTieredCompilation());
CodeVersionManager::LockHolder codeVersioningLockHolder;
CallCountingInfo *callCountingInfo = m_callCountingInfoByCodeVersionHash.Lookup(codeVersion);
if (callCountingInfo != nullptr)
{
// Call counting may already have been disabled due to the possibility of concurrent or reentering JIT of the same
// native code version of a method. The call counting info is created with call counting enabled or disabled and it
// cannot be changed thereafter for consistency in dependents of the info.
_ASSERTE(callCountingInfo->GetStage() == CallCountingInfo::Stage::Disabled);
return;
}
NewHolder<CallCountingInfo> callCountingInfoHolder = CallCountingInfo::CreateWithCallCountingDisabled(codeVersion);
m_callCountingInfoByCodeVersionHash.Add(callCountingInfoHolder);
callCountingInfoHolder.SuppressRelease();
}
// Returns true if the code entry point was updated to reflect the active code version, false otherwise. In normal paths, the
// code entry point is not updated only when the use of call counting stubs is disabled, as in that case returning to the
// prestub is necessary for further call counting. On exception, the code entry point may or may not have been updated and it's
// up to the caller to decide how to proceed.
bool CallCountingManager::SetCodeEntryPoint(
NativeCodeVersion activeCodeVersion,
PCODE codeEntryPoint,
bool wasMethodCalled,
bool *createTieringBackgroundWorkerRef)
{
CONTRACTL
{
THROWS;
GC_NOTRIGGER;
PRECONDITION(!activeCodeVersion.IsNull());
MODE_ANY;
}
CONTRACTL_END;
MethodDesc *methodDesc = activeCodeVersion.GetMethodDesc();
_ASSERTE(!methodDesc->MayHaveEntryPointSlotsToBackpatch() || MethodDescBackpatchInfoTracker::IsLockOwnedByCurrentThread());
_ASSERTE(CodeVersionManager::IsLockOwnedByCurrentThread());
_ASSERTE(
activeCodeVersion ==
methodDesc->GetCodeVersionManager()->GetActiveILCodeVersion(methodDesc).GetActiveNativeCodeVersion(methodDesc));
_ASSERTE(codeEntryPoint != NULL);
_ASSERTE(codeEntryPoint == activeCodeVersion.GetNativeCode());
_ASSERTE(!wasMethodCalled || createTieringBackgroundWorkerRef != nullptr);
_ASSERTE(createTieringBackgroundWorkerRef == nullptr || !*createTieringBackgroundWorkerRef);
if (!methodDesc->IsEligibleForTieredCompilation() ||
(
// For a default code version that is not tier 0, call counting will have been disabled by this time (checked
// below). Avoid the redundant and not-insignificant expense of GetOptimizationTier() on a default code version.
!activeCodeVersion.IsDefaultVersion() &&
activeCodeVersion.IsFinalTier()
) ||
!g_pConfig->TieredCompilation_CallCounting())
{
methodDesc->SetCodeEntryPoint(codeEntryPoint);
return true;
}
const CallCountingStub *callCountingStub;
CallCountingManager *callCountingManager = methodDesc->GetLoaderAllocator()->GetCallCountingManager();
CallCountingInfoByCodeVersionHash &callCountingInfoByCodeVersionHash =
callCountingManager->m_callCountingInfoByCodeVersionHash;
CallCountingInfo *callCountingInfo = callCountingInfoByCodeVersionHash.Lookup(activeCodeVersion);
do
{
if (callCountingInfo != nullptr)
{
_ASSERTE(callCountingInfo->GetCodeVersion() == activeCodeVersion);
CallCountingInfo::Stage callCountingStage = callCountingInfo->GetStage();
if (callCountingStage >= CallCountingInfo::Stage::PendingCompletion)
{
// Call counting is disabled, complete, or pending completion. The pending completion stage here would be
// relatively rare, let it be handled elsewhere.
methodDesc->SetCodeEntryPoint(codeEntryPoint);
return true;
}
_ASSERTE(!activeCodeVersion.IsFinalTier());
// If the tiering delay is active, postpone further work
if (GetAppDomain()
->GetTieredCompilationManager()
->TrySetCodeEntryPointAndRecordMethodForCallCounting(methodDesc, codeEntryPoint))
{
if (callCountingStage == CallCountingInfo::Stage::StubMayBeActive)
{
callCountingInfo->SetStage(CallCountingInfo::Stage::StubIsNotActive);
}
return true;
}
do
{
if (!wasMethodCalled)
{
break;
}
CallCount remainingCallCount = --*callCountingInfo->GetRemainingCallCountCell();
if (remainingCallCount != 0)
{
break;
}
callCountingInfo->SetStage(CallCountingInfo::Stage::PendingCompletion);
if (!activeCodeVersion.GetILCodeVersion().HasAnyOptimizedNativeCodeVersion(activeCodeVersion))
{
GetAppDomain()
->GetTieredCompilationManager()
->AsyncPromoteToTier1(activeCodeVersion, createTieringBackgroundWorkerRef);
}
methodDesc->SetCodeEntryPoint(codeEntryPoint);
callCountingInfo->SetStage(CallCountingInfo::Stage::Complete);
return true;
} while (false);
callCountingStub = callCountingInfo->GetCallCountingStub();
if (callCountingStub != nullptr)
{
break;
}
}
else
{
_ASSERTE(!activeCodeVersion.IsFinalTier());
// If the tiering delay is active, postpone further work
if (GetAppDomain()
->GetTieredCompilationManager()
->TrySetCodeEntryPointAndRecordMethodForCallCounting(methodDesc, codeEntryPoint))
{
return true;
}
CallCount callCountThreshold = g_pConfig->TieredCompilation_CallCountThreshold();
_ASSERTE(callCountThreshold != 0);
// Let's tier up all cast helpers faster than other methods. This is because we want to import them as
// direct calls in codegen and they need to be promoted earlier than their callers.
if (methodDesc->GetMethodTable() == g_pCastHelpers)
{
callCountThreshold = max(1, (CallCount)(callCountThreshold / 2));
}
NewHolder<CallCountingInfo> callCountingInfoHolder = new CallCountingInfo(activeCodeVersion, callCountThreshold);
callCountingInfoByCodeVersionHash.Add(callCountingInfoHolder);
callCountingInfo = callCountingInfoHolder.Extract();
}
if (!g_pConfig->TieredCompilation_UseCallCountingStubs())
{
// Call counting is not yet complete, so reset or don't set the code entry point to continue counting calls
if (wasMethodCalled)
{
return false;
}
// This path is reached after activating a code version when publishing its code entry point. The method may
// currently be pointing to the code entry point of a different code version, so an explicit reset is necessary.
methodDesc->ResetCodeEntryPoint();
return true;
}
callCountingStub =
callCountingManager->m_callCountingStubAllocator.AllocateStub(
callCountingInfo->GetRemainingCallCountCell(),
codeEntryPoint);
callCountingInfo->SetCallCountingStub(callCountingStub);
} while (false);
PCODE callCountingCodeEntryPoint = callCountingStub->GetEntryPoint();
if (methodDesc->MayHaveEntryPointSlotsToBackpatch())
{
// The call counting stub should not be the entry point that is called first in the process of a call
// - Stubs should be deletable. Many methods will have call counting stubs associated with them, and although the memory
// involved is typically insignificant compared to the average memory overhead per method, by steady-state it would
// otherwise be unnecessary memory overhead serving no purpose.
// - In order to be able to delete a stub, the jitted code of a method cannot be allowed to load the stub as the entry
// point of a callee into a register in a GC-safe point that allows for the stub to be deleted before the register is
// reused to call the stub. On some processor architectures, perhaps the JIT can guarantee that it would not load the
// entry point into a register before the call, but this is not possible on arm32 or arm64. Rather, perhaps the
// region containing the load and call would not be considered GC-safe. Calls are considered GC-safe points, and this
// may cause many methods that are currently fully interruptible to have to be partially interruptible and record
// extra GC info instead. This would be nontrivial and there would be tradeoffs.
// - For any method that may have an entry point slot that would be backpatched with the call counting stub's entry
// point, a small forwarder stub (precode) is created. The forwarder stub has loader allocator lifetime and forwards to
// the larger call counting stub. This is a simple solution for now and seems to have negligible impact.
// - Reusing FuncPtrStubs was considered. FuncPtrStubs are currently not used as a code entry point for a virtual or
// interface method and may be bypassed. For example, a call may call through the vtable slot, or a devirtualized call
// may call through a FuncPtrStub. The target of a FuncPtrStub is a code entry point and is backpatched when a
// method's active code entry point changes. Mixing the current use of FuncPtrStubs with the use as a forwarder for
// call counting does not seem trivial and would likely complicate its use. There may not be much gain in reusing
// FuncPtrStubs, as typically, they are created for only a small percentage of virtual/interface methods.
MethodDescForwarderStubHash &methodDescForwarderStubHash = callCountingManager->m_methodDescForwarderStubHash;
Precode *forwarderStub = methodDescForwarderStubHash.Lookup(methodDesc);
if (forwarderStub == nullptr)
{
AllocMemTracker forwarderStubAllocationTracker;
forwarderStub =
Precode::Allocate(
methodDesc->GetPrecodeType(),
methodDesc,
methodDesc->GetLoaderAllocator(),
&forwarderStubAllocationTracker);
methodDescForwarderStubHash.Add(forwarderStub);
forwarderStubAllocationTracker.SuppressRelease();
}
forwarderStub->SetTargetInterlocked(callCountingCodeEntryPoint, false);
callCountingCodeEntryPoint = forwarderStub->GetEntryPoint();
}
else
{
_ASSERTE(methodDesc->IsVersionableWithPrecode());
}
methodDesc->SetCodeEntryPoint(callCountingCodeEntryPoint);
callCountingInfo->SetStage(CallCountingInfo::Stage::StubMayBeActive);
return true;
}
extern "C" PCODE STDCALL OnCallCountThresholdReached(TransitionBlock *transitionBlock, TADDR stubIdentifyingToken)
{
WRAPPER_NO_CONTRACT;
return CallCountingManager::OnCallCountThresholdReached(transitionBlock, stubIdentifyingToken);
}
PCODE CallCountingManager::OnCallCountThresholdReached(TransitionBlock *transitionBlock, TADDR stubIdentifyingToken)
{
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_GC_TRIGGERS;
STATIC_CONTRACT_MODE_COOPERATIVE;
PCODE codeEntryPoint = NULL;
BEGIN_PRESERVE_LAST_ERROR;
MAKE_CURRENT_THREAD_AVAILABLE();
#ifdef _DEBUG
Thread::ObjectRefFlush(CURRENT_THREAD);
#endif
// Get the code version from the call counting stub/info in cooperative GC mode to synchronize with deletion. The stub/info
// may be deleted only when the runtime is suspended, so when we are in cooperative GC mode it is safe to read from them.
NativeCodeVersion codeVersion =
CallCountingInfo::From(CallCountingStub::From(stubIdentifyingToken)->GetRemainingCallCountCell())->GetCodeVersion();
MethodDesc *methodDesc = codeVersion.GetMethodDesc();
FrameWithCookie<CallCountingHelperFrame> frameWithCookie(transitionBlock, methodDesc);
CallCountingHelperFrame *frame = &frameWithCookie;
frame->Push(CURRENT_THREAD);
INSTALL_MANAGED_EXCEPTION_DISPATCHER;
INSTALL_UNWIND_AND_CONTINUE_HANDLER;
// The switch to preemptive GC mode no longer guarantees that the stub/info will be valid. Only the code version will be
// used going forward under appropriate locking to synchronize further with deletion.
GCX_PREEMP_THREAD_EXISTS(CURRENT_THREAD);
_ASSERTE(!codeVersion.IsFinalTier());
codeEntryPoint = codeVersion.GetNativeCode();
do
{
{
CallCountingManager *callCountingManager = methodDesc->GetLoaderAllocator()->GetCallCountingManager();
CodeVersionManager::LockHolder codeVersioningLockHolder;
CallCountingInfo *callCountingInfo = callCountingManager->m_callCountingInfoByCodeVersionHash.Lookup(codeVersion);
if (callCountingInfo == nullptr)
{
break;
}
CallCountingInfo::Stage callCountingStage = callCountingInfo->GetStage();
if (callCountingStage >= CallCountingInfo::Stage::PendingCompletion)
{
break;
}
// Fully completing call counting for a method is relative expensive. Call counting with stubs is relatively cheap.
// Since many methods will typically reach the call count threshold at roughly the same time (a perf spike),
// delegate as much of the overhead as possible to the background. This significantly decreases the degree of the
// perf spike.
callCountingManager->m_callCountingInfosPendingCompletion.Append(callCountingInfo);
callCountingInfo->SetStage(CallCountingInfo::Stage::PendingCompletion);
}
GetAppDomain()->GetTieredCompilationManager()->AsyncCompleteCallCounting();
} while (false);
UNINSTALL_UNWIND_AND_CONTINUE_HANDLER;
UNINSTALL_MANAGED_EXCEPTION_DISPATCHER;
frame->Pop(CURRENT_THREAD);
END_PRESERVE_LAST_ERROR;
return codeEntryPoint;
}
COUNT_T CallCountingManager::GetCountOfCodeVersionsPendingCompletion()
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_PREEMPTIVE;
}
CONTRACTL_END;
COUNT_T count = 0;
CodeVersionManager::LockHolder codeVersioningLockHolder;
for (auto itEnd = s_callCountingManagers->End(), it = s_callCountingManagers->Begin(); it != itEnd; ++it)
{
CallCountingManager *callCountingManager = *it;
count += callCountingManager->m_callCountingInfosPendingCompletion.GetCount();
}
return count;
}
void CallCountingManager::CompleteCallCounting()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_PREEMPTIVE;
}
CONTRACTL_END;
_ASSERTE(GetThreadNULLOk() == TieredCompilationManager::GetBackgroundWorkerThread());
AppDomain *appDomain = GetAppDomain();
TieredCompilationManager *tieredCompilationManager = appDomain->GetTieredCompilationManager();
CodeVersionManager *codeVersionManager = appDomain->GetCodeVersionManager();
MethodDescBackpatchInfoTracker::ConditionalLockHolder slotBackpatchLockHolder;
CodeVersionManager::LockHolder codeVersioningLockHolder;
for (auto itEnd = s_callCountingManagers->End(), it = s_callCountingManagers->Begin(); it != itEnd; ++it)
{
CallCountingManager *callCountingManager = *it;
SArray<CallCountingInfo *> &callCountingInfosPendingCompletion =
callCountingManager->m_callCountingInfosPendingCompletion;
COUNT_T callCountingInfoCount = callCountingInfosPendingCompletion.GetCount();
if (callCountingInfoCount == 0)
{
continue;
}
CallCountingInfo **callCountingInfos = callCountingInfosPendingCompletion.GetElements();
for (COUNT_T i = 0; i < callCountingInfoCount; ++i)
{
CallCountingInfo *callCountingInfo = callCountingInfos[i];
CallCountingInfo::Stage callCountingStage = callCountingInfo->GetStage();
if (callCountingStage != CallCountingInfo::Stage::PendingCompletion)
{
continue;
}
NativeCodeVersion codeVersion = callCountingInfo->GetCodeVersion();
MethodDesc *methodDesc = codeVersion.GetMethodDesc();
_ASSERTE(codeVersionManager == methodDesc->GetCodeVersionManager());
EX_TRY
{
if (!codeVersion.GetILCodeVersion().HasAnyOptimizedNativeCodeVersion(codeVersion))
{
bool createTieringBackgroundWorker = false;
tieredCompilationManager->AsyncPromoteToTier1(codeVersion, &createTieringBackgroundWorker);
_ASSERTE(!createTieringBackgroundWorker); // the current thread is the background worker thread
}
// The active code version may have changed externally after the call counting stub was activated,
// deactivating the call counting stub without our knowledge. Check the active code version and determine
// what needs to be done.
NativeCodeVersion activeCodeVersion =
codeVersionManager->GetActiveILCodeVersion(methodDesc).GetActiveNativeCodeVersion(methodDesc);
do
{
if (activeCodeVersion == codeVersion)
{
methodDesc->SetCodeEntryPoint(activeCodeVersion.GetNativeCode());
break;
}
// There is at least one case where the IL code version is changed inside the code versioning lock, the
// lock is released and reacquired, then the method's code entry point is reset. So if this path is
// reached between those locks, the method would still be pointing to the call counting stub. Once the
// stub is marked as complete, it may be deleted, so in all cases update the method's code entry point
// to ensure that the method is no longer pointing to the call counting stub.
if (!activeCodeVersion.IsNull())
{
PCODE activeNativeCode = activeCodeVersion.GetNativeCode();
if (activeNativeCode != NULL)
{
methodDesc->SetCodeEntryPoint(activeNativeCode);
break;
}
}
methodDesc->ResetCodeEntryPoint();
} while (false);
callCountingInfo->SetStage(CallCountingInfo::Stage::Complete);
}
EX_CATCH
{
// Avoid abandoning call counting completion for all recorded call counting infos on exception. Since this
// is happening on a background thread, following the general policy so far, the exception will be caught,
// logged, and ignored anyway, so make an attempt to complete call counting for each item. Individual items
// that fail will result in those code versions not getting promoted (similar to elsewhere).
STRESS_LOG1(LF_TIEREDCOMPILATION, LL_WARNING, "CallCountingManager::CompleteCallCounting: "
"Exception, hr=0x%x\n",
GET_EXCEPTION()->GetHR());
}
EX_END_CATCH(RethrowTerminalExceptions);
}
callCountingInfosPendingCompletion.Clear();
if (callCountingInfosPendingCompletion.GetAllocation() > 64)
{
callCountingInfosPendingCompletion.Trim();
EX_TRY
{
callCountingInfosPendingCompletion.Preallocate(64);
}
EX_CATCH
{
}
EX_END_CATCH(RethrowTerminalExceptions);
}
}
}
void CallCountingManager::StopAndDeleteAllCallCountingStubs()
{
CONTRACTL
{
THROWS;
GC_TRIGGERS;
MODE_PREEMPTIVE;
}
CONTRACTL_END;
_ASSERTE(GetThreadNULLOk() == TieredCompilationManager::GetBackgroundWorkerThread());
// If a number of call counting stubs have completed, we can try to delete them to reclaim some memory. Deleting
// involves suspending the runtime and will delete all call counting stubs, and after that some call counting stubs may
// be recreated in the foreground. The threshold is to decrease the impact of both of those overheads.
COUNT_T deleteCallCountingStubsAfter = g_pConfig->TieredCompilation_DeleteCallCountingStubsAfter();
if (deleteCallCountingStubsAfter == 0 || s_completedCallCountingStubCount < deleteCallCountingStubsAfter)
{
return;
}
TieredCompilationManager *tieredCompilationManager = GetAppDomain()->GetTieredCompilationManager();
ThreadSuspend::SuspendEE(ThreadSuspend::SUSPEND_OTHER);
struct AutoRestartEE
{
~AutoRestartEE()
{
WRAPPER_NO_CONTRACT;
ThreadSuspend::RestartEE(false, true);
}
} autoRestartEE;