forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprestub.cpp
3550 lines (2963 loc) · 118 KB
/
prestub.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.
// ===========================================================================
// File: Prestub.cpp
//
// ===========================================================================
// This file contains the implementation for creating and using prestubs
// ===========================================================================
//
#include "common.h"
#include "vars.hpp"
#include "eeconfig.h"
#include "dllimport.h"
#include "comdelegate.h"
#include "dbginterface.h"
#include "stubgen.h"
#include "eventtrace.h"
#include "array.h"
#include "compile.h"
#include "ecall.h"
#include "virtualcallstub.h"
#ifdef FEATURE_PREJIT
#include "compile.h"
#endif
#ifdef FEATURE_INTERPRETER
#include "interpreter.h"
#endif
#ifdef FEATURE_COMINTEROP
#include "clrtocomcall.h"
#endif
#ifdef FEATURE_STACK_SAMPLING
#include "stacksampler.h"
#endif
#ifdef FEATURE_PERFMAP
#include "perfmap.h"
#endif
#include "methoddescbackpatchinfo.h"
#if defined(FEATURE_GDBJIT)
#include "gdbjit.h"
#endif // FEATURE_GDBJIT
#ifndef DACCESS_COMPILE
#if defined(FEATURE_JIT_PITCHING)
EXTERN_C void CheckStacksAndPitch();
EXTERN_C void SavePitchingCandidate(MethodDesc* pMD, ULONG sizeOfCode);
EXTERN_C void DeleteFromPitchingCandidate(MethodDesc* pMD);
EXTERN_C void MarkMethodNotPitchingCandidate(MethodDesc* pMD);
#endif
EXTERN_C void STDCALL ThePreStubPatch();
#if defined(HAVE_GCCOVER)
CrstStatic MethodDesc::m_GCCoverCrst;
void MethodDesc::Init()
{
m_GCCoverCrst.Init(CrstGCCover);
}
#endif
#define LOG_USING_R2R_CODE(method) LOG((LF_ZAP, LL_INFO10000, \
"ZAP: Using R2R precompiled code" FMT_ADDR " for %s.%s sig=\"%s\" (token %x).\n", \
DBG_ADDR(pCode), \
m_pszDebugClassName, \
m_pszDebugMethodName, \
m_pszDebugMethodSignature, \
GetMemberDef()));
//==========================================================================
PCODE MethodDesc::DoBackpatch(MethodTable * pMT, MethodTable *pDispatchingMT, BOOL fFullBackPatch)
{
CONTRACTL
{
STANDARD_VM_CHECK;
PRECONDITION(!ContainsGenericVariables());
PRECONDITION(pMT == GetMethodTable());
}
CONTRACTL_END;
bool isVersionableWithVtableSlotBackpatch = IsVersionableWithVtableSlotBackpatch();
LoaderAllocator *mdLoaderAllocator = isVersionableWithVtableSlotBackpatch ? GetLoaderAllocator() : nullptr;
// Only take the lock if the method is versionable with vtable slot backpatch, for recording slots and synchronizing with
// backpatching slots
MethodDescBackpatchInfoTracker::ConditionalLockHolderForGCCoop slotBackpatchLockHolder(
isVersionableWithVtableSlotBackpatch);
// Get the method entry point inside the lock above to synchronize with backpatching in
// MethodDesc::BackpatchEntryPointSlots()
PCODE pTarget = GetMethodEntryPoint();
PCODE pExpected;
if (isVersionableWithVtableSlotBackpatch)
{
_ASSERTE(pTarget == GetEntryPointToBackpatch_Locked());
pExpected = GetTemporaryEntryPoint();
if (pExpected == pTarget)
return pTarget;
// True interface methods are never backpatched and are not versionable with vtable slot backpatch
_ASSERTE(!(pMT->IsInterface() && !IsStatic()));
// Backpatching the funcptr stub:
// For methods versionable with vtable slot backpatch, a funcptr stub is guaranteed to point to the at-the-time
// current entry point shortly after creation, and backpatching it further is taken care of by
// MethodDesc::BackpatchEntryPointSlots()
// Backpatching the temporary entry point:
// The temporary entry point is never backpatched for methods versionable with vtable slot backpatch. New vtable
// slots inheriting the method will initially point to the temporary entry point and it must point to the prestub
// and come here for backpatching such that the new vtable slot can be discovered and recorded for future
// backpatching.
_ASSERTE(!HasNonVtableSlot());
}
else
{
_ASSERTE(pTarget == GetStableEntryPoint());
if (!HasTemporaryEntryPoint())
return pTarget;
pExpected = GetTemporaryEntryPoint();
if (pExpected == pTarget)
return pTarget;
// True interface methods are never backpatched
if (pMT->IsInterface() && !IsStatic())
return pTarget;
if (fFullBackPatch)
{
FuncPtrStubs * pFuncPtrStubs = GetLoaderAllocator()->GetFuncPtrStubsNoCreate();
if (pFuncPtrStubs != NULL)
{
Precode* pFuncPtrPrecode = pFuncPtrStubs->Lookup(this);
if (pFuncPtrPrecode != NULL)
{
// If there is a funcptr precode to patch, we are done for this round.
if (pFuncPtrPrecode->SetTargetInterlocked(pTarget))
return pTarget;
}
}
#ifndef HAS_COMPACT_ENTRYPOINTS
// Patch the fake entrypoint if necessary
Precode::GetPrecodeFromEntryPoint(pExpected)->SetTargetInterlocked(pTarget);
#endif // HAS_COMPACT_ENTRYPOINTS
}
if (HasNonVtableSlot())
return pTarget;
}
auto RecordAndBackpatchSlot = [&](MethodTable *patchedMT, DWORD slotIndex)
{
WRAPPER_NO_CONTRACT;
_ASSERTE(isVersionableWithVtableSlotBackpatch);
RecordAndBackpatchEntryPointSlot_Locked(
mdLoaderAllocator,
patchedMT->GetLoaderAllocator(),
patchedMT->GetSlotPtr(slotIndex),
EntryPointSlots::SlotType_Vtable,
pTarget);
};
BOOL fBackpatched = FALSE;
#define BACKPATCH(pPatchedMT) \
do \
{ \
if (pPatchedMT->GetSlot(dwSlot) == pExpected) \
{ \
if (isVersionableWithVtableSlotBackpatch) \
{ \
RecordAndBackpatchSlot(pPatchedMT, dwSlot); \
} \
else \
{ \
pPatchedMT->SetSlot(dwSlot, pTarget); \
} \
fBackpatched = TRUE; \
} \
} \
while(0)
// The owning slot has been updated already, so there is no need to backpatch it
_ASSERTE(pMT->GetSlot(GetSlot()) == pTarget);
if (pDispatchingMT != NULL && pDispatchingMT != pMT)
{
DWORD dwSlot = GetSlot();
BACKPATCH(pDispatchingMT);
if (fFullBackPatch)
{
//
// Backpatch the MethodTable that code:MethodTable::GetRestoredSlot() reads the value from.
// VSD reads the slot value using code:MethodTable::GetRestoredSlot(), and so we need to make sure
// that it returns the stable entrypoint eventually to avoid going through the slow path all the time.
//
MethodTable * pRestoredSlotMT = pDispatchingMT->GetRestoredSlotMT(dwSlot);
if (pRestoredSlotMT != pDispatchingMT)
{
BACKPATCH(pRestoredSlotMT);
}
}
}
if (IsMethodImpl())
{
MethodImpl::Iterator it(this);
while (it.IsValid())
{
DWORD dwSlot = it.GetSlot();
BACKPATCH(pMT);
if (pDispatchingMT != NULL && pDispatchingMT != pMT)
{
BACKPATCH(pDispatchingMT);
}
it.Next();
}
}
if (fFullBackPatch && !fBackpatched && IsDuplicate())
{
// If this is a duplicate, let's scan the rest of the VTable hunting for other hits.
unsigned numSlots = pMT->GetNumVirtuals();
for (DWORD dwSlot=0; dwSlot<numSlots; dwSlot++)
{
BACKPATCH(pMT);
if (pDispatchingMT != NULL && pDispatchingMT != pMT)
{
BACKPATCH(pDispatchingMT);
}
}
}
#undef BACKPATCH
return pTarget;
}
// <TODO> FIX IN BETA 2
//
// g_pNotificationTable is only modified by the DAC and therefore the
// optmizer can assume that it will always be its default value and has
// been seen to (on IA64 free builds) eliminate the code in DACNotifyCompilationFinished
// such that DAC notifications are no longer sent.
//
// TODO: fix this in Beta 2
// the RIGHT fix is to make g_pNotificationTable volatile, but currently
// we don't have DAC macros to do that. Additionally, there are a number
// of other places we should look at DAC definitions to determine if they
// should be also declared volatile.
//
// for now we just turn off optimization for these guys
#ifdef _MSC_VER
#pragma optimize("", off)
#endif
void DACNotifyCompilationFinished(MethodDesc *methodDesc, PCODE pCode)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_PREEMPTIVE;
}
CONTRACTL_END;
// Is the list active?
JITNotifications jn(g_pNotificationTable);
if (jn.IsActive())
{
// Get Module and mdToken
mdToken t = methodDesc->GetMemberDef();
Module *modulePtr = methodDesc->GetModule();
_ASSERTE(modulePtr);
// Are we listed?
USHORT jnt = jn.Requested((TADDR) modulePtr, t);
if (jnt & CLRDATA_METHNOTIFY_GENERATED)
{
// If so, throw an exception!
DACNotify::DoJITNotification(methodDesc, (TADDR)pCode);
}
}
}
#ifdef _MSC_VER
#pragma optimize("", on)
#endif
// </TODO>
PCODE MethodDesc::PrepareInitialCode(CallerGCMode callerGCMode)
{
STANDARD_VM_CONTRACT;
PrepareCodeConfig config(NativeCodeVersion(this), TRUE, TRUE);
config.SetCallerGCMode(callerGCMode);
return PrepareCode(&config);
}
PCODE MethodDesc::PrepareCode(PrepareCodeConfig* pConfig)
{
STANDARD_VM_CONTRACT;
// If other kinds of code need multi-versioning we could add more cases here,
// but for now generation of all other code/stubs occurs in other code paths
_ASSERTE(IsIL() || IsNoMetadata());
PCODE pCode = PrepareILBasedCode(pConfig);
#if defined(FEATURE_GDBJIT) && defined(TARGET_UNIX) && !defined(CROSSGEN_COMPILE)
NotifyGdb::MethodPrepared(this);
#endif
return pCode;
}
bool MayUsePrecompiledILStub()
{
if (g_pConfig->InteropValidatePinnedObjects())
return false;
if (CORProfilerTrackTransitions())
return false;
if (g_pConfig->InteropLogArguments())
return false;
return true;
}
PCODE MethodDesc::PrepareILBasedCode(PrepareCodeConfig* pConfig)
{
STANDARD_VM_CONTRACT;
PCODE pCode = NULL;
if (pConfig->MayUsePrecompiledCode())
{
#ifdef FEATURE_READYTORUN
if (IsDynamicMethod() && GetLoaderModule()->IsSystem() && MayUsePrecompiledILStub())
{
// Images produced using crossgen2 have non-shareable pinvoke stubs which can't be used with the IL
// stubs that the runtime generates (they take no secret parameter, and each pinvoke has a separate code)
if (GetModule()->IsReadyToRun() && !GetModule()->GetReadyToRunInfo()->HasNonShareablePInvokeStubs())
{
DynamicMethodDesc* stubMethodDesc = this->AsDynamicMethodDesc();
if (stubMethodDesc->IsILStub() && stubMethodDesc->IsPInvokeStub())
{
ILStubResolver* pStubResolver = stubMethodDesc->GetILStubResolver();
if (pStubResolver->GetStubType() == ILStubResolver::CLRToNativeInteropStub)
{
MethodDesc* pTargetMD = stubMethodDesc->GetILStubResolver()->GetStubTargetMethodDesc();
if (pTargetMD != NULL)
{
pCode = pTargetMD->GetPrecompiledR2RCode(pConfig);
if (pCode != NULL)
{
LOG_USING_R2R_CODE(this);
pConfig->SetNativeCode(pCode, &pCode);
}
}
}
}
}
}
#endif // FEATURE_READYTORUN
if (pCode == NULL)
pCode = GetPrecompiledCode(pConfig);
#ifdef FEATURE_PERFMAP
if (pCode != NULL)
PerfMap::LogPreCompiledMethod(this, pCode);
#endif
}
if (pCode == NULL)
{
LOG((LF_CLASSLOADER, LL_INFO1000000,
" In PrepareILBasedCode, calling JitCompileCode\n"));
pCode = JitCompileCode(pConfig);
}
else
{
DACNotifyCompilationFinished(this, pCode);
}
// Mark the code as hot in case the method ends up in the native image
g_IBCLogger.LogMethodCodeAccess(this);
return pCode;
}
PCODE MethodDesc::GetPrecompiledCode(PrepareCodeConfig* pConfig)
{
STANDARD_VM_CONTRACT;
PCODE pCode = NULL;
#ifdef FEATURE_PREJIT
pCode = GetPrecompiledNgenCode(pConfig);
#endif
if (pCode != NULL)
{
#ifdef FEATURE_CODE_VERSIONING
pConfig->SetGeneratedOrLoadedNewCode();
#endif
}
#ifdef FEATURE_READYTORUN
else
{
pCode = GetPrecompiledR2RCode(pConfig);
if (pCode != NULL)
{
LOG_USING_R2R_CODE(this);
#ifdef FEATURE_TIERED_COMPILATION
bool shouldTier = pConfig->GetMethodDesc()->IsEligibleForTieredCompilation();
#if !defined(TARGET_X86)
CallerGCMode callerGcMode = pConfig->GetCallerGCMode();
// If the method is eligible for tiering but is being
// called from a Preemptive GC Mode thread or the method
// has the UnmanagedCallersOnlyAttribute then the Tiered Compilation
// should be disabled.
if (shouldTier
&& (callerGcMode == CallerGCMode::Preemptive
|| (callerGcMode == CallerGCMode::Unknown
&& HasUnmanagedCallersOnlyAttribute())))
{
NativeCodeVersion codeVersion = pConfig->GetCodeVersion();
if (codeVersion.IsDefaultVersion())
{
pConfig->GetMethodDesc()->GetLoaderAllocator()->GetCallCountingManager()->DisableCallCounting(codeVersion);
}
codeVersion.SetOptimizationTier(NativeCodeVersion::OptimizationTierOptimized);
shouldTier = false;
}
#endif // !TARGET_X86
#endif // FEATURE_TIERED_COMPILATION
if (pConfig->SetNativeCode(pCode, &pCode))
{
#ifdef FEATURE_CODE_VERSIONING
pConfig->SetGeneratedOrLoadedNewCode();
#endif
#ifdef FEATURE_TIERED_COMPILATION
if (shouldTier)
{
_ASSERTE(pConfig->GetCodeVersion().GetOptimizationTier() == NativeCodeVersion::OptimizationTier0);
pConfig->SetShouldCountCalls();
}
#endif
}
}
}
#endif // FEATURE_READYTORUN
return pCode;
}
PCODE MethodDesc::GetPrecompiledNgenCode(PrepareCodeConfig* pConfig)
{
STANDARD_VM_CONTRACT;
PCODE pCode = NULL;
#ifdef FEATURE_PREJIT
pCode = GetPreImplementedCode();
#ifdef PROFILING_SUPPORTED
// The pre-existing cache search callbacks aren't implemented as you might expect.
// Instead of sending a cache search started for all methods, we only send the notification
// when we already know a pre-compiled version of the method exists. In the NGEN case we also
// don't send callbacks unless the method triggers the prestub which excludes a lot of methods.
// From the profiler's perspective this technique is only reliable/predictable when using profiler
// instrumented NGEN images (that virtually no profilers use). As-is the callback only
// gives an opportunity for the profiler to say whether or not it wants to use the ngen'ed
// code.
//
// Despite those oddities I am leaving this behavior as-is during refactoring because trying to
// improve it probably offers little value vs. the potential for compat issues and creating more
// complexity reasoning how the API behavior changed across runtime releases.
if (pCode != NULL)
{
BOOL fShouldSearchCache = TRUE;
{
BEGIN_PIN_PROFILER(CORProfilerTrackCacheSearches());
g_profControlBlock.pProfInterface->JITCachedFunctionSearchStarted((FunctionID)this, &fShouldSearchCache);
END_PIN_PROFILER();
}
if (!fShouldSearchCache)
{
SetNativeCodeInterlocked(NULL, pCode);
_ASSERTE(!IsPreImplemented());
pConfig->SetProfilerRejectedPrecompiledCode();
pCode = NULL;
}
}
#endif // PROFILING_SUPPORTED
if (pCode != NULL)
{
LOG((LF_ZAP, LL_INFO10000,
"ZAP: Using NGEN precompiled code " FMT_ADDR " for %s.%s sig=\"%s\" (token %x).\n",
DBG_ADDR(pCode),
m_pszDebugClassName,
m_pszDebugMethodName,
m_pszDebugMethodSignature,
GetMemberDef()));
TADDR pFixupList = GetFixupList();
if (pFixupList != NULL)
{
Module *pZapModule = GetZapModule();
_ASSERTE(pZapModule != NULL);
if (!pZapModule->FixupDelayList(pFixupList))
{
_ASSERTE(!"FixupDelayList failed");
ThrowHR(COR_E_BADIMAGEFORMAT);
}
}
#ifdef HAVE_GCCOVER
if (GCStress<cfg_instr_ngen>::IsEnabled())
SetupGcCoverage(pConfig->GetCodeVersion(), (BYTE*)pCode);
#endif // HAVE_GCCOVER
#ifdef PROFILING_SUPPORTED
/*
* This notifies the profiler that a search to find a
* cached jitted function has been made.
*/
{
BEGIN_PIN_PROFILER(CORProfilerTrackCacheSearches());
g_profControlBlock.pProfInterface->
JITCachedFunctionSearchFinished((FunctionID)this, COR_PRF_CACHED_FUNCTION_FOUND);
END_PIN_PROFILER();
}
#endif // PROFILING_SUPPORTED
}
#endif // FEATURE_PREJIT
return pCode;
}
PCODE MethodDesc::GetPrecompiledR2RCode(PrepareCodeConfig* pConfig)
{
STANDARD_VM_CONTRACT;
PCODE pCode = NULL;
#ifdef FEATURE_READYTORUN
Module * pModule = GetModule();
if (pModule->IsReadyToRun())
{
pCode = pModule->GetReadyToRunInfo()->GetEntryPoint(this, pConfig, TRUE /* fFixups */);
}
// Lookup in the entry point assembly for a R2R entrypoint (generics with large version bubble enabled)
if (pCode == NULL && HasClassOrMethodInstantiation() && SystemDomain::System()->DefaultDomain()->GetRootAssembly() != NULL)
{
pModule = SystemDomain::System()->DefaultDomain()->GetRootAssembly()->GetManifestModule();
_ASSERT(pModule != NULL);
if (pModule->IsReadyToRun() && pModule->IsInSameVersionBubble(GetModule()))
{
pCode = pModule->GetReadyToRunInfo()->GetEntryPoint(this, pConfig, TRUE /* fFixups */);
}
}
#endif
return pCode;
}
PCODE MethodDesc::GetMulticoreJitCode()
{
STANDARD_VM_CONTRACT;
PCODE pCode = NULL;
#ifdef FEATURE_MULTICOREJIT
// Quick check before calling expensive out of line function on this method's domain has code JITted by background thread
MulticoreJitManager & mcJitManager = GetAppDomain()->GetMulticoreJitManager();
if (mcJitManager.GetMulticoreJitCodeStorage().GetRemainingMethodCount() > 0)
{
if (MulticoreJitManager::IsMethodSupported(this))
{
pCode = mcJitManager.RequestMethodCode(this); // Query multi-core JIT manager for compiled code
}
}
#endif
return pCode;
}
COR_ILMETHOD_DECODER* MethodDesc::GetAndVerifyMetadataILHeader(PrepareCodeConfig* pConfig, COR_ILMETHOD_DECODER* pDecoderMemory)
{
STANDARD_VM_CONTRACT;
_ASSERTE(!IsNoMetadata());
COR_ILMETHOD_DECODER* pHeader = NULL;
COR_ILMETHOD* ilHeader = pConfig->GetILHeader();
if (ilHeader == NULL)
{
COMPlusThrowHR(COR_E_BADIMAGEFORMAT, BFA_BAD_IL);
}
COR_ILMETHOD_DECODER::DecoderStatus status = COR_ILMETHOD_DECODER::FORMAT_ERROR;
{
// Decoder ctor can AV on a malformed method header
AVInRuntimeImplOkayHolder AVOkay;
pHeader = new (pDecoderMemory) COR_ILMETHOD_DECODER(ilHeader, GetMDImport(), &status);
}
if (status == COR_ILMETHOD_DECODER::FORMAT_ERROR)
{
COMPlusThrowHR(COR_E_BADIMAGEFORMAT, BFA_BAD_IL);
}
return pHeader;
}
COR_ILMETHOD_DECODER* MethodDesc::GetAndVerifyNoMetadataILHeader()
{
STANDARD_VM_CONTRACT;
if (IsILStub())
{
ILStubResolver* pResolver = AsDynamicMethodDesc()->GetILStubResolver();
return pResolver->GetILHeader();
}
else
{
return NULL;
}
// NoMetadata currently doesn't verify the IL. I'm not sure if that was
// a deliberate decision in the past or not, but I've left the behavior
// as-is during refactoring.
}
COR_ILMETHOD_DECODER* MethodDesc::GetAndVerifyILHeader(PrepareCodeConfig* pConfig, COR_ILMETHOD_DECODER* pIlDecoderMemory)
{
STANDARD_VM_CONTRACT;
_ASSERTE(IsIL() || IsNoMetadata());
if (IsNoMetadata())
{
// The NoMetadata version already has a decoder to use, it doesn't need the stack allocated one
return GetAndVerifyNoMetadataILHeader();
}
else
{
return GetAndVerifyMetadataILHeader(pConfig, pIlDecoderMemory);
}
}
// ********************************************************************
// README!!
// ********************************************************************
// JitCompileCode is the thread safe way to invoke the JIT compiler
// If multiple threads get in here for the same config, ALL of them
// MUST return the SAME value for pcode.
//
// This function creates a DeadlockAware list of methods being jitted
// which prevents us from trying to JIT the same method more that once.
PCODE MethodDesc::JitCompileCode(PrepareCodeConfig* pConfig)
{
STANDARD_VM_CONTRACT;
LOG((LF_JIT, LL_INFO1000000,
"JitCompileCode(" FMT_ADDR ", %s) for %s:%s\n",
DBG_ADDR(this),
IsILStub() ? " TRUE" : "FALSE",
GetMethodTable()->GetDebugClassName(),
m_pszDebugMethodName));
#if defined(FEATURE_JIT_PITCHING)
CheckStacksAndPitch();
#endif
PCODE pCode = NULL;
{
// Enter the global lock which protects the list of all functions being JITd
JitListLock::LockHolder pJitLock(GetDomain()->GetJitLock());
// It is possible that another thread stepped in before we entered the global lock for the first time.
if ((pCode = pConfig->IsJitCancellationRequested()))
{
return pCode;
}
const char *description = "jit lock";
INDEBUG(description = m_pszDebugMethodName;)
ReleaseHolder<JitListLockEntry> pEntry(JitListLockEntry::Find(
pJitLock, pConfig->GetCodeVersion(), description));
// We have an entry now, we can release the global lock
pJitLock.Release();
// Take the entry lock
{
JitListLockEntry::LockHolder pEntryLock(pEntry, FALSE);
if (pEntryLock.DeadlockAwareAcquire())
{
if (pEntry->m_hrResultCode == S_FALSE)
{
// Nobody has jitted the method yet
}
else
{
// We came in to jit but someone beat us so return the
// jitted method!
// We can just fall through because we will notice below that
// the method has code.
// @todo: Note that we may have a failed HRESULT here -
// we might want to return an early error rather than
// repeatedly failing the jit.
}
}
else
{
// Taking this lock would cause a deadlock (presumably because we
// are involved in a class constructor circular dependency.) For
// instance, another thread may be waiting to run the class constructor
// that we are jitting, but is currently jitting this function.
//
// To remedy this, we want to go ahead and do the jitting anyway.
// The other threads contending for the lock will then notice that
// the jit finished while they were running class constructors, and abort their
// current jit effort.
//
// We don't have to do anything special right here since we
// can check HasNativeCode() to detect this case later.
//
// Note that at this point we don't have the lock, but that's OK because the
// thread which does have the lock is blocked waiting for us.
}
// It is possible that another thread stepped in before we entered the lock.
if ((pCode = pConfig->IsJitCancellationRequested()))
{
return pCode;
}
pCode = GetMulticoreJitCode();
if (pCode != NULL)
{
if (pConfig->SetNativeCode(pCode, &pCode))
{
#ifdef FEATURE_CODE_VERSIONING
pConfig->SetGeneratedOrLoadedNewCode();
#endif
#ifdef FEATURE_TIERED_COMPILATION
if (pConfig->GetMethodDesc()->IsEligibleForTieredCompilation() &&
pConfig->GetCodeVersion().GetOptimizationTier() == NativeCodeVersion::OptimizationTier0)
{
pConfig->SetShouldCountCalls();
}
#endif
}
pEntry->m_hrResultCode = S_OK;
return pCode;
}
else
{
return JitCompileCodeLockedEventWrapper(pConfig, pEntryLock);
}
}
}
}
PCODE MethodDesc::JitCompileCodeLockedEventWrapper(PrepareCodeConfig* pConfig, JitListLockEntry* pEntry)
{
STANDARD_VM_CONTRACT;
PCODE pCode = NULL;
ULONG sizeOfCode = 0;
CORJIT_FLAGS flags;
#ifdef PROFILING_SUPPORTED
{
BEGIN_PIN_PROFILER(CORProfilerTrackJITInfo());
// For methods with non-zero rejit id we send ReJITCompilationStarted, otherwise
// JITCompilationStarted. It isn't clear if this is the ideal policy for these
// notifications yet.
NativeCodeVersion nativeCodeVersion = pConfig->GetCodeVersion();
ReJITID rejitId = nativeCodeVersion.GetILCodeVersionId();
if (rejitId != 0)
{
_ASSERTE(!nativeCodeVersion.IsDefaultVersion());
g_profControlBlock.pProfInterface->ReJITCompilationStarted((FunctionID)this,
rejitId,
TRUE);
}
else
// If profiling, need to give a chance for a tool to examine and modify
// the IL before it gets to the JIT. This allows one to add probe calls for
// things like code coverage, performance, or whatever.
{
if (!IsNoMetadata())
{
g_profControlBlock.pProfInterface->JITCompilationStarted((FunctionID)this, TRUE);
}
else
{
unsigned int ilSize, unused;
CorInfoOptions corOptions;
LPCBYTE ilHeaderPointer = this->AsDynamicMethodDesc()->GetResolver()->GetCodeInfo(&ilSize, &unused, &corOptions, &unused);
g_profControlBlock.pProfInterface->DynamicMethodJITCompilationStarted((FunctionID)this, TRUE, ilHeaderPointer, ilSize);
}
if (nativeCodeVersion.IsDefaultVersion())
{
pConfig->SetProfilerMayHaveActivatedNonDefaultCodeVersion();
}
}
END_PIN_PROFILER();
}
#endif // PROFILING_SUPPORTED
if (!ETW_TRACING_CATEGORY_ENABLED(MICROSOFT_WINDOWS_DOTNETRUNTIME_PROVIDER_DOTNET_Context,
TRACE_LEVEL_VERBOSE,
CLR_JIT_KEYWORD))
{
pCode = JitCompileCodeLocked(pConfig, pEntry, &sizeOfCode, &flags);
}
else
{
SString namespaceOrClassName, methodName, methodSignature;
// Methods that may be interpreted defer this notification until it is certain
// we are jitting and not interpreting in CompileMethodWithEtwWrapper.
// Some further refactoring could consolidate the notification to always
// occur at the point the interpreter does it, but it might even better
// to fix the issues that cause us to avoid generating jit notifications
// for interpreted methods in the first place. The interpreter does generate
// a small stub of native code but no native-IL mapping.
#ifndef FEATURE_INTERPRETER
ETW::MethodLog::MethodJitting(this,
&namespaceOrClassName,
&methodName,
&methodSignature);
#endif
pCode = JitCompileCodeLocked(pConfig, pEntry, &sizeOfCode, &flags);
// Interpretted methods skip this notification
#ifdef FEATURE_INTERPRETER
if (Interpreter::InterpretationStubToMethodInfo(pCode) == NULL)
#endif
{
// Fire an ETW event to mark the end of JIT'ing
ETW::MethodLog::MethodJitted(this,
&namespaceOrClassName,
&methodName,
&methodSignature,
pCode,
pConfig);
}
}
#ifdef FEATURE_STACK_SAMPLING
StackSampler::RecordJittingInfo(this, flags);
#endif // FEATURE_STACK_SAMPLING
#ifdef PROFILING_SUPPORTED
{
BEGIN_PIN_PROFILER(CORProfilerTrackJITInfo());
// For methods with non-zero rejit id we send ReJITCompilationFinished, otherwise
// JITCompilationFinished. It isn't clear if this is the ideal policy for these
// notifications yet.
NativeCodeVersion nativeCodeVersion = pConfig->GetCodeVersion();
ReJITID rejitId = nativeCodeVersion.GetILCodeVersionId();
if (rejitId != 0)
{
_ASSERTE(!nativeCodeVersion.IsDefaultVersion());
g_profControlBlock.pProfInterface->ReJITCompilationFinished((FunctionID)this,
rejitId,
S_OK,
TRUE);
}
else
// Notify the profiler that JIT completed.
// Must do this after the address has been set.
// @ToDo: Why must we set the address before notifying the profiler ??
{
if (!IsNoMetadata())
{
g_profControlBlock.pProfInterface->
JITCompilationFinished((FunctionID)this,
pEntry->m_hrResultCode,
TRUE);
}
else
{
g_profControlBlock.pProfInterface->DynamicMethodJITCompilationFinished((FunctionID)this, pEntry->m_hrResultCode, TRUE);
}
if (nativeCodeVersion.IsDefaultVersion())
{
pConfig->SetProfilerMayHaveActivatedNonDefaultCodeVersion();
}
}
END_PIN_PROFILER();
}
#endif // PROFILING_SUPPORTED
#ifdef FEATURE_INTERPRETER
bool isJittedMethod = (Interpreter::InterpretationStubToMethodInfo(pCode) == NULL);
#endif
// Interpretted methods skip this notification
#ifdef FEATURE_INTERPRETER
if (isJittedMethod)
#endif
{
#ifdef FEATURE_PERFMAP
// Save the JIT'd method information so that perf can resolve JIT'd call frames.
PerfMap::LogJITCompiledMethod(this, pCode, sizeOfCode, pConfig);
#endif
}
#ifdef FEATURE_MULTICOREJIT
// Non-initial code versions and multicore jit initial compilation all skip this
if (pConfig->NeedsMulticoreJitNotification())
{
MulticoreJitManager & mcJitManager = GetAppDomain()->GetMulticoreJitManager();
if (mcJitManager.IsRecorderActive())
{
if (MulticoreJitManager::IsMethodSupported(this))
{
mcJitManager.RecordMethodJit(this); // Tell multi-core JIT manager to record method on successful JITting
}
}
}
#endif
#ifdef FEATURE_INTERPRETER
if (isJittedMethod)
#endif
{
// The notification will only occur if someone has registered for this method.
DACNotifyCompilationFinished(this, pCode);
}
return pCode;
}
PCODE MethodDesc::JitCompileCodeLocked(PrepareCodeConfig* pConfig, JitListLockEntry* pEntry, ULONG* pSizeOfCode, CORJIT_FLAGS* pFlags)
{
STANDARD_VM_CONTRACT;
PCODE pCode = NULL;
// The profiler may have changed the code on the callback. Need to
// pick up the new code.
//
// (don't want this for OSR, need to see how it works)
COR_ILMETHOD_DECODER ilDecoderTemp;
COR_ILMETHOD_DECODER *pilHeader = GetAndVerifyILHeader(pConfig, &ilDecoderTemp);
*pFlags = pConfig->GetJitCompilationFlags();
PCODE pOtherCode = NULL;
EX_TRY
{
#ifndef CROSSGEN_COMPILE
Thread::CurrentPrepareCodeConfigHolder threadPrepareCodeConfigHolder(GetThread(), pConfig);