-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
indirectcalltransformer.cpp
1577 lines (1388 loc) · 63.3 KB
/
indirectcalltransformer.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 "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
// The IndirectCallTransformer transforms indirect calls that involve fat function
// pointers, guarded devirtualization candidates, or runtime lookup with dynamic dictionary expansion.
// These transformations introduce control flow and so can't easily be done in the importer.
//
// A fat function pointer is a pointer with the second least significant bit
// (aka FAT_POINTER_MASK) set. If the bit is set, the pointer (after clearing the bit)
// actually points to a tuple <method pointer, instantiation argument> where
// instantiationArgument is a hidden first argument required by method pointer.
//
// Fat pointers are used in NativeAOT as a replacement for instantiating stubs,
// because NativeAOT can't generate stubs in runtime.
//
// The JIT is responsible for emitting code to check the bit at runtime, branching
// to one of two call sites.
//
// When the bit is not set, the code should execute the original indirect call.
//
// When the bit is set, the code should mask off the bit, use the resulting pointer
// to load the real target address and the extra argument, and then call indirect
// via the target, passing the extra argument.
//
// before:
// current block
// {
// previous statements
// transforming statement
// {
// call with GTF_CALL_M_FAT_POINTER_CHECK flag set in function ptr
// }
// subsequent statements
// }
//
// after:
// current block
// {
// previous statements
// } BBJ_ALWAYS check block
// check block
// {
// jump to else if function ptr has the FAT_POINTER_MASK bit set.
// } BBJ_COND then block, else block
// then block
// {
// original statement
// } BBJ_ALWAYS remainder block
// else block
// {
// clear FAT_POINTER_MASK bit
// load actual function pointer
// load instantiation argument
// create newArgList = (instantiation argument, original argList)
// call (actual function pointer, newArgList)
// } BBJ_ALWAYS remainder block
// remainder block
// {
// subsequent statements
// }
//
class IndirectCallTransformer
{
public:
IndirectCallTransformer(Compiler* compiler)
: compiler(compiler)
{
}
//------------------------------------------------------------------------
// Run: run transformation for each block.
//
// Returns:
// Count of calls transformed.
int Run()
{
int count = 0;
for (BasicBlock* const block : compiler->Blocks())
{
count += TransformBlock(block);
}
return count;
}
private:
//------------------------------------------------------------------------
// TransformBlock: look through statements and transform statements with
// particular indirect calls
//
// Returns:
// Count of calls transformed.
//
int TransformBlock(BasicBlock* block)
{
int count = 0;
for (Statement* const stmt : block->Statements())
{
if (compiler->doesMethodHaveFatPointer() && ContainsFatCalli(stmt))
{
FatPointerCallTransformer transformer(compiler, block, stmt);
transformer.Run();
count++;
}
else if (compiler->doesMethodHaveGuardedDevirtualization() &&
ContainsGuardedDevirtualizationCandidate(stmt))
{
GuardedDevirtualizationTransformer transformer(compiler, block, stmt);
transformer.Run();
count++;
}
}
return count;
}
//------------------------------------------------------------------------
// ContainsFatCalli: check does this statement contain fat pointer call.
//
// Checks fatPointerCandidate in form of call() or lclVar = call().
//
// Return Value:
// true if contains, false otherwise.
//
bool ContainsFatCalli(Statement* stmt)
{
GenTree* fatPointerCandidate = stmt->GetRootNode();
if (fatPointerCandidate->OperIs(GT_STORE_LCL_VAR))
{
fatPointerCandidate = fatPointerCandidate->AsLclVar()->Data();
}
return fatPointerCandidate->IsCall() && fatPointerCandidate->AsCall()->IsFatPointerCandidate();
}
//------------------------------------------------------------------------
// ContainsGuardedDevirtualizationCandidate: check does this statement contain a virtual
// call that we'd like to guardedly devirtualize?
//
// Return Value:
// true if contains, false otherwise.
//
// Notes:
// calls are hoisted to top level ... (we hope)
bool ContainsGuardedDevirtualizationCandidate(Statement* stmt)
{
GenTree* candidate = stmt->GetRootNode();
return candidate->IsCall() && candidate->AsCall()->IsGuardedDevirtualizationCandidate();
}
class Transformer
{
public:
Transformer(Compiler* compiler, BasicBlock* block, Statement* stmt)
: compiler(compiler)
, currBlock(block)
, stmt(stmt)
{
remainderBlock = nullptr;
checkBlock = nullptr;
thenBlock = nullptr;
elseBlock = nullptr;
origCall = nullptr;
likelihood = HIGH_PROBABILITY;
}
//------------------------------------------------------------------------
// Run: transform the statement as described above.
//
virtual void Run()
{
Transform();
}
void Transform()
{
JITDUMP("*** %s: transforming " FMT_STMT "\n", Name(), stmt->GetID());
FixupRetExpr();
ClearFlag();
CreateRemainder();
assert(GetChecksCount() > 0);
for (uint8_t i = 0; i < GetChecksCount(); i++)
{
CreateCheck(i);
CreateThen(i);
}
CreateElse();
RemoveOldStatement();
SetWeights();
ChainFlow();
}
protected:
virtual const char* Name() = 0;
virtual void ClearFlag() = 0;
virtual GenTreeCall* GetCall(Statement* callStmt) = 0;
virtual void FixupRetExpr() = 0;
//------------------------------------------------------------------------
// CreateRemainder: split current block at the call stmt and
// insert statements after the call into remainderBlock.
//
void CreateRemainder()
{
remainderBlock = compiler->fgSplitBlockAfterStatement(currBlock, stmt);
remainderBlock->SetFlags(BBF_INTERNAL);
// We will be adding more blocks after currBlock, so remove edge to remainderBlock.
//
compiler->fgRemoveRefPred(currBlock->GetTargetEdge());
}
virtual void CreateCheck(uint8_t checkIdx) = 0;
//------------------------------------------------------------------------
// CreateAndInsertBasicBlock: ask compiler to create new basic block.
// and insert in into the basic block list.
//
// Arguments:
// jumpKind - jump kind for the new basic block
// insertAfter - basic block, after which compiler has to insert the new one.
// flagsSource - basic block to copy BBF_SPLIT_GAINED flags from
//
// Return Value:
// new basic block.
BasicBlock* CreateAndInsertBasicBlock(BBKinds jumpKind, BasicBlock* insertAfter, BasicBlock* flagsSource)
{
BasicBlock* block = compiler->fgNewBBafter(jumpKind, insertAfter, true);
block->SetFlags(BBF_IMPORTED);
if (flagsSource != nullptr)
{
block->CopyFlags(flagsSource, BBF_SPLIT_GAINED);
}
return block;
}
virtual void CreateThen(uint8_t checkIdx) = 0;
virtual void CreateElse() = 0;
//------------------------------------------------------------------------
// GetChecksCount: Get number of Check-Then pairs
//
virtual UINT8 GetChecksCount()
{
return 1;
}
//------------------------------------------------------------------------
// RemoveOldStatement: remove original stmt from current block.
//
void RemoveOldStatement()
{
compiler->fgRemoveStmt(currBlock, stmt);
}
//------------------------------------------------------------------------
// SetWeights: set weights for new blocks.
//
virtual void SetWeights()
{
remainderBlock->inheritWeight(currBlock);
checkBlock->inheritWeight(currBlock);
thenBlock->inheritWeightPercentage(currBlock, likelihood);
elseBlock->inheritWeightPercentage(currBlock, 100 - likelihood);
}
//------------------------------------------------------------------------
// ChainFlow: link new blocks into correct cfg.
//
virtual void ChainFlow()
{
assert(compiler->fgPredsComputed);
// currBlock
if (checkBlock != currBlock)
{
assert(currBlock->KindIs(BBJ_ALWAYS));
FlowEdge* const newEdge = compiler->fgAddRefPred(checkBlock, currBlock);
currBlock->SetTargetEdge(newEdge);
}
// checkBlock
// Todo: get likelihoods right
//
assert(checkBlock->KindIs(BBJ_ALWAYS));
FlowEdge* const thenEdge = compiler->fgAddRefPred(thenBlock, checkBlock);
thenEdge->setLikelihood(0.5);
FlowEdge* const elseEdge = compiler->fgAddRefPred(elseBlock, checkBlock);
elseEdge->setLikelihood(0.5);
checkBlock->SetCond(elseEdge, thenEdge);
// thenBlock
{
assert(thenBlock->KindIs(BBJ_ALWAYS));
FlowEdge* const newEdge = compiler->fgAddRefPred(remainderBlock, thenBlock);
thenBlock->SetTargetEdge(newEdge);
}
// elseBlock
{
assert(elseBlock->KindIs(BBJ_ALWAYS));
FlowEdge* const newEdge = compiler->fgAddRefPred(remainderBlock, elseBlock);
elseBlock->SetTargetEdge(newEdge);
}
}
Compiler* compiler;
BasicBlock* currBlock;
BasicBlock* remainderBlock;
BasicBlock* checkBlock;
BasicBlock* thenBlock;
BasicBlock* elseBlock;
Statement* stmt;
GenTreeCall* origCall;
unsigned likelihood;
const int HIGH_PROBABILITY = 80;
};
class FatPointerCallTransformer final : public Transformer
{
public:
FatPointerCallTransformer(Compiler* compiler, BasicBlock* block, Statement* stmt)
: Transformer(compiler, block, stmt)
{
doesReturnValue = stmt->GetRootNode()->OperIs(GT_STORE_LCL_VAR);
origCall = GetCall(stmt);
fptrAddress = origCall->gtCallAddr;
pointerType = fptrAddress->TypeGet();
}
protected:
virtual const char* Name()
{
return "FatPointerCall";
}
//------------------------------------------------------------------------
// GetCall: find a call in a statement.
//
// Arguments:
// callStmt - the statement with the call inside.
//
// Return Value:
// call tree node pointer.
virtual GenTreeCall* GetCall(Statement* callStmt)
{
GenTree* tree = callStmt->GetRootNode();
GenTreeCall* call = nullptr;
if (doesReturnValue)
{
assert(tree->OperIs(GT_STORE_LCL_VAR));
call = tree->AsLclVar()->Data()->AsCall();
}
else
{
call = tree->AsCall(); // call with void return type.
}
return call;
}
//------------------------------------------------------------------------
// ClearFlag: clear fat pointer candidate flag from the original call.
//
virtual void ClearFlag()
{
origCall->ClearFatPointerCandidate();
}
// FixupRetExpr: no action needed as we handle this in the importer.
virtual void FixupRetExpr()
{
}
//------------------------------------------------------------------------
// CreateCheck: create check block, that checks fat pointer bit set.
//
virtual void CreateCheck(uint8_t checkIdx)
{
assert(checkIdx == 0);
checkBlock = CreateAndInsertBasicBlock(BBJ_ALWAYS, currBlock, currBlock);
GenTree* fatPointerMask = new (compiler, GT_CNS_INT) GenTreeIntCon(TYP_I_IMPL, FAT_POINTER_MASK);
GenTree* fptrAddressCopy = compiler->gtCloneExpr(fptrAddress);
GenTree* fatPointerAnd = compiler->gtNewOperNode(GT_AND, TYP_I_IMPL, fptrAddressCopy, fatPointerMask);
GenTree* zero = new (compiler, GT_CNS_INT) GenTreeIntCon(TYP_I_IMPL, 0);
GenTree* fatPointerCmp = compiler->gtNewOperNode(GT_NE, TYP_INT, fatPointerAnd, zero);
GenTree* jmpTree = compiler->gtNewOperNode(GT_JTRUE, TYP_VOID, fatPointerCmp);
Statement* jmpStmt = compiler->fgNewStmtFromTree(jmpTree, stmt->GetDebugInfo());
compiler->fgInsertStmtAtEnd(checkBlock, jmpStmt);
}
//------------------------------------------------------------------------
// CreateThen: create then block, that is executed if the check succeeds.
// This simply executes the original call.
//
virtual void CreateThen(uint8_t checkIdx)
{
assert(remainderBlock != nullptr);
thenBlock = CreateAndInsertBasicBlock(BBJ_ALWAYS, checkBlock, currBlock);
Statement* copyOfOriginalStmt = compiler->gtCloneStmt(stmt);
compiler->fgInsertStmtAtEnd(thenBlock, copyOfOriginalStmt);
}
//------------------------------------------------------------------------
// CreateElse: create else block, that is executed if call address is fat pointer.
//
virtual void CreateElse()
{
elseBlock = CreateAndInsertBasicBlock(BBJ_ALWAYS, thenBlock, currBlock);
GenTree* fixedFptrAddress = GetFixedFptrAddress();
GenTree* actualCallAddress = compiler->gtNewIndir(pointerType, fixedFptrAddress);
GenTree* hiddenArgument = GetHiddenArgument(fixedFptrAddress);
Statement* fatStmt = CreateFatCallStmt(actualCallAddress, hiddenArgument);
compiler->fgInsertStmtAtEnd(elseBlock, fatStmt);
}
//------------------------------------------------------------------------
// GetFixedFptrAddress: clear fat pointer bit from fat pointer address.
//
// Return Value:
// address without fat pointer bit set.
GenTree* GetFixedFptrAddress()
{
GenTree* fptrAddressCopy = compiler->gtCloneExpr(fptrAddress);
GenTree* fatPointerMask = new (compiler, GT_CNS_INT) GenTreeIntCon(TYP_I_IMPL, FAT_POINTER_MASK);
return compiler->gtNewOperNode(GT_SUB, pointerType, fptrAddressCopy, fatPointerMask);
}
//------------------------------------------------------------------------
// GetHiddenArgument: load hidden argument.
//
// Arguments:
// fixedFptrAddress - pointer to the tuple <methodPointer, instantiationArgument>
//
// Return Value:
// generic context hidden argument.
GenTree* GetHiddenArgument(GenTree* fixedFptrAddress)
{
GenTree* fixedFptrAddressCopy = compiler->gtCloneExpr(fixedFptrAddress);
GenTree* wordSize = new (compiler, GT_CNS_INT) GenTreeIntCon(TYP_I_IMPL, genTypeSize(TYP_I_IMPL));
GenTree* hiddenArgumentPtr = compiler->gtNewOperNode(GT_ADD, pointerType, fixedFptrAddressCopy, wordSize);
return compiler->gtNewIndir(fixedFptrAddressCopy->TypeGet(), hiddenArgumentPtr);
}
//------------------------------------------------------------------------
// CreateFatCallStmt: create call with fixed call address and hidden argument in the args list.
//
// Arguments:
// actualCallAddress - fixed call address
// hiddenArgument - generic context hidden argument
//
// Return Value:
// created call node.
Statement* CreateFatCallStmt(GenTree* actualCallAddress, GenTree* hiddenArgument)
{
Statement* fatStmt = compiler->gtCloneStmt(stmt);
GenTreeCall* fatCall = GetCall(fatStmt);
fatCall->gtCallAddr = actualCallAddress;
fatCall->gtArgs.InsertInstParam(compiler, hiddenArgument);
return fatStmt;
}
private:
const int FAT_POINTER_MASK = 0x2;
GenTree* fptrAddress;
var_types pointerType;
bool doesReturnValue;
};
class GuardedDevirtualizationTransformer final : public Transformer
{
public:
GuardedDevirtualizationTransformer(Compiler* compiler, BasicBlock* block, Statement* stmt)
: Transformer(compiler, block, stmt)
, returnTemp(BAD_VAR_NUM)
{
}
//------------------------------------------------------------------------
// Run: transform the statement as described above.
//
virtual void Run()
{
origCall = GetCall(stmt);
JITDUMP("\n----------------\n\n*** %s contemplating [%06u] in " FMT_BB " \n", Name(),
compiler->dspTreeID(origCall), currBlock->bbNum);
// We currently need inline candidate info to guarded devirt.
//
if (!origCall->IsInlineCandidate())
{
JITDUMP("*** %s Bailing on [%06u] -- not an inline candidate\n", Name(), compiler->dspTreeID(origCall));
ClearFlag();
return;
}
likelihood = origCall->GetGDVCandidateInfo(0)->likelihood;
assert((likelihood >= 0) && (likelihood <= 100));
JITDUMP("Likelihood of correct guess is %u\n", likelihood);
// TODO: implement chaining for multiple GDV candidates
const bool canChainGdv =
(GetChecksCount() == 1) && ((origCall->gtCallMoreFlags & GTF_CALL_M_GUARDED_DEVIRT_EXACT) == 0);
if (canChainGdv)
{
compiler->Metrics.GDV++;
if (GetChecksCount() > 1)
{
compiler->Metrics.MultiGuessGDV++;
}
const bool isChainedGdv = (origCall->gtCallMoreFlags & GTF_CALL_M_GUARDED_DEVIRT_CHAIN) != 0;
if (isChainedGdv)
{
JITDUMP("Expansion will chain to the previous GDV\n");
}
Transform();
if (isChainedGdv)
{
compiler->Metrics.ChainedGDV++;
TransformForChainedGdv();
}
// Look ahead and see if there's another Gdv we might chain to this one.
//
ScoutForChainedGdv();
}
else
{
JITDUMP("Expansion will not chain to the previous GDV due to multiple type checks\n");
Transform();
}
}
protected:
virtual const char* Name()
{
return "GuardedDevirtualization";
}
//------------------------------------------------------------------------
// GetCall: find a call in a statement.
//
// Arguments:
// callStmt - the statement with the call inside.
//
// Return Value:
// call tree node pointer.
virtual GenTreeCall* GetCall(Statement* callStmt)
{
GenTree* tree = callStmt->GetRootNode();
assert(tree->IsCall());
GenTreeCall* call = tree->AsCall();
return call;
}
virtual void ClearFlag()
{
// We remove the GDV flag from the call in the CreateElse
}
virtual UINT8 GetChecksCount()
{
return origCall->GetInlineCandidatesCount();
}
virtual void ChainFlow()
{
assert(compiler->fgPredsComputed);
// Chaining is done in-place.
}
virtual void SetWeights()
{
// remainderBlock has the same weight as the original block.
remainderBlock->inheritWeight(currBlock);
// The rest of the weights are assigned in-place.
}
//------------------------------------------------------------------------
// CreateCheck: create check block and check method table
//
virtual void CreateCheck(uint8_t checkIdx)
{
if (checkIdx == 0)
{
// There's no need for a new block here. We can just append to currBlock.
//
checkBlock = currBlock;
checkFallsThrough = false;
}
else
{
// In case of multiple checks, append to the previous thenBlock block
// (Set jump target of new checkBlock in CreateThen())
BasicBlock* prevCheckBlock = checkBlock;
checkBlock = CreateAndInsertBasicBlock(BBJ_ALWAYS, thenBlock, currBlock);
checkFallsThrough = false;
// We computed the "then" likelihood in CreateThen, so we
// just use that to figure out the "else" likelihood.
//
assert(prevCheckBlock->KindIs(BBJ_ALWAYS));
assert(prevCheckBlock->JumpsToNext());
FlowEdge* const prevCheckThenEdge = prevCheckBlock->GetTargetEdge();
weight_t checkLikelihood = max(0.0, 1.0 - prevCheckThenEdge->getLikelihood());
JITDUMP("Level %u Check block " FMT_BB " success likelihood " FMT_WT "\n", checkIdx, checkBlock->bbNum,
checkLikelihood);
// prevCheckBlock is expected to jump to this new check (if its type check doesn't succeed)
//
FlowEdge* const prevCheckCheckEdge = compiler->fgAddRefPred(checkBlock, prevCheckBlock);
prevCheckCheckEdge->setLikelihood(checkLikelihood);
checkBlock->inheritWeight(prevCheckBlock);
checkBlock->scaleBBWeight(checkLikelihood);
prevCheckBlock->SetCond(prevCheckCheckEdge, prevCheckThenEdge);
}
// Find last arg with a side effect. All args with any effect
// before that will need to be spilled.
CallArg* lastSideEffArg = nullptr;
for (CallArg& arg : origCall->gtArgs.Args())
{
if ((arg.GetNode()->gtFlags & GTF_SIDE_EFFECT) != 0)
{
lastSideEffArg = &arg;
}
}
if (lastSideEffArg != nullptr)
{
for (CallArg& arg : origCall->gtArgs.Args())
{
GenTree* argNode = arg.GetNode();
if (((argNode->gtFlags & GTF_ALL_EFFECT) != 0) || compiler->gtHasLocalsWithAddrOp(argNode))
{
SpillArgToTempBeforeGuard(&arg);
}
if (&arg == lastSideEffArg)
{
break;
}
}
}
CallArg* thisArg = origCall->gtArgs.GetThisArg();
// We spill 'this' if it is complex, regardless of side effects. It
// is going to be used multiple times due to the guard.
if (!thisArg->GetNode()->IsLocal())
{
SpillArgToTempBeforeGuard(thisArg);
}
GenTree* thisTree = compiler->gtCloneExpr(thisArg->GetNode());
// Remember the current last statement. If we're doing a chained GDV, we'll clone/copy
// all the code in the check block up to and including this statement.
//
// Note it's important that we clone/copy the temp assign above, if we created one,
// because flow along the "cold path" is going to bypass the check block.
//
lastStmt = checkBlock->lastStmt();
// In case if GDV candidates are "exact" (e.g. we have the full list of classes implementing
// the given interface in the app - NativeAOT only at this moment) we assume the last
// check will always be true, so we just simplify the block to BBJ_ALWAYS
const bool isLastCheck = (checkIdx == origCall->GetInlineCandidatesCount() - 1);
if (isLastCheck && ((origCall->gtCallMoreFlags & GTF_CALL_M_GUARDED_DEVIRT_EXACT) != 0))
{
assert(checkBlock->KindIs(BBJ_ALWAYS));
checkFallsThrough = true;
return;
}
InlineCandidateInfo* guardedInfo = origCall->GetGDVCandidateInfo(checkIdx);
// Create comparison. On success we will jump to do the indirect call.
GenTree* compare;
if (guardedInfo->guardedClassHandle != NO_CLASS_HANDLE)
{
// Find target method table
//
GenTree* methodTable = compiler->gtNewMethodTableLookup(thisTree);
CORINFO_CLASS_HANDLE clsHnd = guardedInfo->guardedClassHandle;
GenTree* targetMethodTable = compiler->gtNewIconEmbClsHndNode(clsHnd);
compare = compiler->gtNewOperNode(GT_NE, TYP_INT, targetMethodTable, methodTable);
compiler->Metrics.ClassGDV++;
}
else
{
assert(origCall->IsVirtualVtable() || origCall->IsDelegateInvoke());
// We reuse the target except if this is a chained GDV, in
// which case the check will be moved into the success case of
// a previous GDV and thus may not execute when we hit the cold
// path.
if (origCall->IsVirtualVtable())
{
GenTree* tarTree = compiler->fgExpandVirtualVtableCallTarget(origCall);
CORINFO_METHOD_HANDLE methHnd = guardedInfo->guardedMethodHandle;
CORINFO_CONST_LOOKUP lookup;
compiler->info.compCompHnd->getFunctionEntryPoint(methHnd, &lookup);
GenTree* compareTarTree = CreateTreeForLookup(methHnd, lookup);
compare = compiler->gtNewOperNode(GT_NE, TYP_INT, compareTarTree, tarTree);
}
else
{
GenTree* offset =
compiler->gtNewIconNode((ssize_t)compiler->eeGetEEInfo()->offsetOfDelegateFirstTarget,
TYP_I_IMPL);
GenTree* tarTree = compiler->gtNewOperNode(GT_ADD, TYP_BYREF, thisTree, offset);
tarTree = compiler->gtNewIndir(TYP_I_IMPL, tarTree, GTF_IND_INVARIANT);
CORINFO_METHOD_HANDLE methHnd = guardedInfo->guardedMethodHandle;
CORINFO_CONST_LOOKUP lookup;
compiler->info.compCompHnd->getFunctionFixedEntryPoint(methHnd, false, &lookup);
GenTree* compareTarTree = CreateTreeForLookup(methHnd, lookup);
compare = compiler->gtNewOperNode(GT_NE, TYP_INT, compareTarTree, tarTree);
}
compiler->Metrics.MethodGDV++;
}
GenTree* jmpTree = compiler->gtNewOperNode(GT_JTRUE, TYP_VOID, compare);
Statement* jmpStmt = compiler->fgNewStmtFromTree(jmpTree, stmt->GetDebugInfo());
compiler->fgInsertStmtAtEnd(checkBlock, jmpStmt);
}
//------------------------------------------------------------------------
// SpillArgToTempBeforeGuard: spill an argument into a temp in the guard/check block.
//
// Parameters
// arg - The arg to create a temp and local store for.
//
void SpillArgToTempBeforeGuard(CallArg* arg)
{
unsigned tmpNum = compiler->lvaGrabTemp(true DEBUGARG("guarded devirt arg temp"));
GenTree* const argNode = arg->GetNode();
GenTree* store = compiler->gtNewTempStore(tmpNum, argNode);
if (argNode->TypeIs(TYP_REF))
{
bool isExact = false;
bool isNonNull = false;
CORINFO_CLASS_HANDLE cls = compiler->gtGetClassHandle(argNode, &isExact, &isNonNull);
if (cls != NO_CLASS_HANDLE)
{
compiler->lvaSetClass(tmpNum, cls, isExact);
}
}
Statement* storeStmt = compiler->fgNewStmtFromTree(store, stmt->GetDebugInfo());
compiler->fgInsertStmtAtEnd(checkBlock, storeStmt);
arg->SetEarlyNode(compiler->gtNewLclVarNode(tmpNum));
}
//------------------------------------------------------------------------
// FixupRetExpr: set up to repair return value placeholder from call
//
virtual void FixupRetExpr()
{
// If call returns a value, we need to copy it to a temp, and
// bash the associated GT_RET_EXPR to refer to the temp instead
// of the call.
//
// Note implicit by-ref returns should have already been converted
// so any struct copy we induce here should be cheap.
InlineCandidateInfo* const inlineInfo = origCall->GetGDVCandidateInfo(0);
if (!origCall->TypeIs(TYP_VOID))
{
// If there's a spill temp already associated with this inline candidate,
// use that instead of allocating a new temp.
//
returnTemp = inlineInfo->preexistingSpillTemp;
if (returnTemp != BAD_VAR_NUM)
{
JITDUMP("Reworking call(s) to return value via a existing return temp V%02u\n", returnTemp);
// We will be introducing multiple defs for this temp, so make sure
// it is no longer marked as single def.
//
// Otherwise, we could make an incorrect type deduction. Say the
// original call site returns a B, but after we devirtualize along the
// GDV happy path we see that method returns a D. We can't then assume that
// the return temp is type D, because we don't know what type the fallback
// path returns. So we have to stick with the current type for B as the
// return type.
//
// Note local vars always live in the root method's symbol table. So we
// need to use the root compiler for lookup here.
//
LclVarDsc* const returnTempLcl = compiler->impInlineRoot()->lvaGetDesc(returnTemp);
if (returnTempLcl->lvSingleDef == 1)
{
// In this case it's ok if we already updated the type assuming single def,
// we just don't want any further updates.
//
JITDUMP("Return temp V%02u is no longer a single def temp\n", returnTemp);
returnTempLcl->lvSingleDef = 0;
}
}
else
{
returnTemp = compiler->lvaGrabTemp(false DEBUGARG("guarded devirt return temp"));
JITDUMP("Reworking call(s) to return value via a new temp V%02u\n", returnTemp);
}
if (varTypeIsStruct(origCall))
{
compiler->lvaSetStruct(returnTemp, origCall->gtRetClsHnd, false);
}
GenTree* tempTree = compiler->gtNewLclvNode(returnTemp, origCall->TypeGet());
JITDUMP("Linking GT_RET_EXPR [%06u] to refer to temp V%02u\n", compiler->dspTreeID(inlineInfo->retExpr),
returnTemp);
inlineInfo->retExpr->gtSubstExpr = tempTree;
}
else if (inlineInfo->retExpr != nullptr)
{
// We still oddly produce GT_RET_EXPRs for some void
// returning calls. Just bash the ret expr to a NOP.
//
// Todo: consider bagging creation of these RET_EXPRs. The only possible
// benefit they provide is stitching back larger trees for failed inlines
// of void-returning methods. But then the calls likely sit in commas and
// the benefit of a larger tree is unclear.
JITDUMP("Linking GT_RET_EXPR [%06u] for VOID return to NOP\n",
compiler->dspTreeID(inlineInfo->retExpr));
inlineInfo->retExpr->gtSubstExpr = compiler->gtNewNothingNode();
}
else
{
// We do not produce GT_RET_EXPRs for CTOR calls, so there is nothing to patch.
}
}
//------------------------------------------------------------------------
// Devirtualize origCall using the given inline candidate
//
void DevirtualizeCall(BasicBlock* block, uint8_t candidateId)
{
InlineCandidateInfo* inlineInfo = origCall->GetGDVCandidateInfo(candidateId);
CORINFO_CLASS_HANDLE clsHnd = inlineInfo->guardedClassHandle;
//
// Copy the 'this' for the devirtualized call to a new temp. For
// class-based GDV this will allow us to set the exact type on that
// temp. For delegate GDV, this will be the actual 'this' object
// stored in the delegate.
//
const unsigned thisTemp = compiler->lvaGrabTemp(false DEBUGARG("guarded devirt this exact temp"));
GenTree* clonedObj = compiler->gtCloneExpr(origCall->gtArgs.GetThisArg()->GetNode());
GenTree* newThisObj;
if (origCall->IsDelegateInvoke())
{
GenTree* offset =
compiler->gtNewIconNode((ssize_t)compiler->eeGetEEInfo()->offsetOfDelegateInstance, TYP_I_IMPL);
newThisObj = compiler->gtNewOperNode(GT_ADD, TYP_BYREF, clonedObj, offset);
newThisObj = compiler->gtNewIndir(TYP_REF, newThisObj);
}
else
{
newThisObj = clonedObj;
}
GenTree* store = compiler->gtNewTempStore(thisTemp, newThisObj);
if (clsHnd != NO_CLASS_HANDLE)
{
compiler->lvaSetClass(thisTemp, clsHnd, true);
}
else
{
compiler->lvaSetClass(thisTemp,
compiler->info.compCompHnd->getMethodClass(inlineInfo->guardedMethodHandle));
}
compiler->fgNewStmtAtEnd(block, store);
// Clone call for the devirtualized case. Note we must use the
// special candidate helper and we need to use the new 'this'.
GenTreeCall* call = compiler->gtCloneCandidateCall(origCall);
call->gtArgs.GetThisArg()->SetEarlyNode(compiler->gtNewLclvNode(thisTemp, TYP_REF));
INDEBUG(call->SetIsGuarded());
JITDUMP("Direct call [%06u] in block " FMT_BB "\n", compiler->dspTreeID(call), block->bbNum);
CORINFO_METHOD_HANDLE methodHnd = inlineInfo->guardedMethodHandle;
CORINFO_CONTEXT_HANDLE context = inlineInfo->exactContextHandle;
if (clsHnd != NO_CLASS_HANDLE)
{
// If we devirtualized an array interface call,
// pass the original method handle and original context handle to the devirtualizer.
//
if (inlineInfo->arrayInterface)
{
methodHnd = call->gtCallMethHnd;
context = inlineInfo->originalContextHandle;
}
// Then invoke impDevirtualizeCall to actually transform the call for us,
// given the original (base) method and the exact guarded class. It should succeed.
//
unsigned methodFlags = compiler->info.compCompHnd->getMethodAttribs(methodHnd);
const bool isLateDevirtualization = true;
const bool explicitTailCall = (call->AsCall()->gtCallMoreFlags & GTF_CALL_M_EXPLICIT_TAILCALL) != 0;
CORINFO_CONTEXT_HANDLE contextInput = context;
compiler->impDevirtualizeCall(call, nullptr, &methodHnd, &methodFlags, &contextInput, &context,
isLateDevirtualization, explicitTailCall);
}
else
{
// Otherwise we know the exact method already, so just change
// the call as necessary here.
call->gtFlags &= ~GTF_CALL_VIRT_KIND_MASK;
call->gtCallMethHnd = methodHnd = inlineInfo->guardedMethodHandle;
call->gtCallType = CT_USER_FUNC;
INDEBUG(call->gtCallDebugFlags |= GTF_CALL_MD_DEVIRTUALIZED);
call->gtCallMoreFlags &= ~GTF_CALL_M_DELEGATE_INV;
// TODO-GDV: To support R2R we need to get the entry point
// here. We should unify with the tail of impDevirtualizeCall.
if (origCall->IsVirtual())
{
// Virtual calls include an implicit null check, which we may
// now need to make explicit.
bool isExact;
bool objIsNonNull;
compiler->gtGetClassHandle(newThisObj, &isExact, &objIsNonNull);
if (!objIsNonNull)
{
call->gtFlags |= GTF_CALL_NULLCHECK;
}
}
context = MAKE_METHODCONTEXT(methodHnd);
}
// We know this call can devirtualize or we would not have set up GDV here.
// So above code should succeed in devirtualizing.
//
assert(!call->IsVirtual() && !call->IsDelegateInvoke());
// If this call is in tail position, see if we've created a recursive tail call
// candidate...
//
if (call->CanTailCall() && compiler->gtIsRecursiveCall(methodHnd))
{
compiler->setMethodHasRecursiveTailcall();
block->SetFlags(BBF_RECURSIVE_TAILCALL);
JITDUMP("[%06u] is a recursive call in tail position\n", compiler->dspTreeID(call));
}
else
{
JITDUMP("[%06u] is%s in tail position and is%s recursive\n", compiler->dspTreeID(call),
call->CanTailCall() ? "" : " not", compiler->gtIsRecursiveCall(methodHnd) ? "" : " not");
}
// If the devirtualizer was unable to transform the call to invoke the unboxed entry, the inline info
// we set up may be invalid. We won't be able to inline anyways. So demote the call as an inline candidate.
//
CORINFO_METHOD_HANDLE unboxedMethodHnd = inlineInfo->guardedMethodUnboxedEntryHandle;
if ((unboxedMethodHnd != nullptr) && (methodHnd != unboxedMethodHnd))
{
// Demote this call to a non-inline candidate
//
JITDUMP("Devirtualization was unable to use the unboxed entry; so marking call (to boxed entry) as not "
"inlineable\n");
call->gtFlags &= ~GTF_CALL_INLINE_CANDIDATE;
call->ClearInlineInfo();
if (returnTemp != BAD_VAR_NUM)