-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
fginline.cpp
2021 lines (1746 loc) · 75.3 KB
/
fginline.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
// Flowgraph Inline Support
/*****************************************************************************/
//------------------------------------------------------------------------
// fgCheckForInlineDepthAndRecursion: compute depth of the candidate, and
// check for recursion.
//
// Return Value:
// The depth of the inline candidate. The root method is a depth 0, top-level
// candidates at depth 1, etc.
//
// Notes:
// We generally disallow recursive inlines by policy. However, they are
// supported by the underlying machinery.
//
// Likewise the depth limit is a policy consideration, and serves mostly
// as a safeguard to prevent runaway inlining of small methods.
//
unsigned Compiler::fgCheckInlineDepthAndRecursion(InlineInfo* inlineInfo)
{
BYTE* candidateCode = inlineInfo->inlineCandidateInfo->methInfo.ILCode;
InlineContext* inlineContext = inlineInfo->inlineCandidateInfo->inlinersContext;
InlineResult* inlineResult = inlineInfo->inlineResult;
// There should be a context for all candidates.
assert(inlineContext != nullptr);
int depth = 0;
for (; inlineContext != nullptr; inlineContext = inlineContext->GetParent())
{
assert(inlineContext->GetCode() != nullptr);
depth++;
if (inlineContext->GetCode() == candidateCode)
{
// This inline candidate has the same IL code buffer as an already
// inlined method does.
inlineResult->NoteFatal(InlineObservation::CALLSITE_IS_RECURSIVE);
// No need to note CALLSITE_DEPTH we're already rejecting this candidate
return depth;
}
if (depth > InlineStrategy::IMPLEMENTATION_MAX_INLINE_DEPTH)
{
break;
}
}
inlineResult->NoteInt(InlineObservation::CALLSITE_DEPTH, depth);
return depth;
}
class SubstitutePlaceholdersAndDevirtualizeWalker : public GenTreeVisitor<SubstitutePlaceholdersAndDevirtualizeWalker>
{
bool m_madeChanges = false;
public:
enum
{
DoPreOrder = true,
DoPostOrder = true,
UseExecutionOrder = true,
};
SubstitutePlaceholdersAndDevirtualizeWalker(Compiler* comp) : GenTreeVisitor(comp)
{
}
bool MadeChanges()
{
return m_madeChanges;
}
fgWalkResult PreOrderVisit(GenTree** use, GenTree* user)
{
GenTree* tree = *use;
// All the operations here and in the corresponding postorder
// callback (LateDevirtualization) are triggered by GT_CALL or
// GT_RET_EXPR trees, and these (should) have the call side
// effect flag.
//
// So bail out for any trees that don't have this flag.
if ((tree->gtFlags & GTF_CALL) == 0)
{
return fgWalkResult::WALK_SKIP_SUBTREES;
}
if (tree->OperIs(GT_RET_EXPR))
{
UpdateInlineReturnExpressionPlaceHolder(use, user);
}
#if FEATURE_MULTIREG_RET
#if defined(DEBUG)
// Make sure we don't have a tree like so: V05 = (, , , retExpr);
// Since we only look one level above for the parent for '=' and
// do not check if there is a series of COMMAs. See above.
// Importer and FlowGraph will not generate such a tree, so just
// leaving an assert in here. This can be fixed by looking ahead
// when we visit GT_ASG similar to AttachStructInlineeToAsg.
//
if (tree->OperGet() == GT_ASG)
{
GenTree* value = tree->AsOp()->gtOp2;
if (value->OperGet() == GT_COMMA)
{
GenTree* effectiveValue = value->gtEffectiveVal(/*commaOnly*/ true);
noway_assert(
!varTypeIsStruct(effectiveValue) || (effectiveValue->OperGet() != GT_RET_EXPR) ||
!m_compiler->IsMultiRegReturnedType(effectiveValue->AsRetExpr()->gtInlineCandidate->gtRetClsHnd,
CorInfoCallConvExtension::Managed));
}
}
#endif // defined(DEBUG)
#endif // FEATURE_MULTIREG_RET
return fgWalkResult::WALK_CONTINUE;
}
fgWalkResult PostOrderVisit(GenTree** use, GenTree* user)
{
LateDevirtualization(use, user);
return fgWalkResult::WALK_CONTINUE;
}
private:
//------------------------------------------------------------------------
// UpdateInlineReturnExpressionPlaceHolder: replace an
// inline return expression placeholder if there is one.
//
// Arguments:
// use -- edge for the tree that is a GT_RET_EXPR node
// parent -- node containing the edge
//
// Returns:
// fgWalkResult indicating the walk should continue; that
// is we wish to fully explore the tree.
//
// Notes:
// Looks for GT_RET_EXPR nodes that arose from tree splitting done
// during importation for inline candidates, and replaces them.
//
// For successful inlines, substitutes the return value expression
// from the inline body for the GT_RET_EXPR.
//
// For failed inlines, rejoins the original call into the tree from
// whence it was split during importation.
//
// The code doesn't actually know if the corresponding inline
// succeeded or not; it relies on the fact that gtInlineCandidate
// initially points back at the call and is modified in place to
// the inlinee return expression if the inline is successful (see
// tail end of fgInsertInlineeBlocks for the update of iciCall).
//
// If the return type is a struct type and we're on a platform
// where structs can be returned in multiple registers, ensure the
// call has a suitable parent.
//
// If the original call type and the substitution type are different
// the functions makes necessary updates. It could happen if there was
// an implicit conversion in the inlinee body.
//
void UpdateInlineReturnExpressionPlaceHolder(GenTree** use, GenTree* parent)
{
CORINFO_CLASS_HANDLE retClsHnd = NO_CLASS_HANDLE;
while ((*use)->OperIs(GT_RET_EXPR))
{
GenTree* tree = *use;
// We are going to copy the tree from the inlinee,
// so record the handle now.
//
if (varTypeIsStruct(tree))
{
retClsHnd = tree->AsRetExpr()->gtInlineCandidate->gtRetClsHnd;
}
// Skip through chains of GT_RET_EXPRs (say from nested inlines)
// to the actual tree to use.
//
BasicBlock* inlineeBB = nullptr;
GenTree* inlineCandidate = tree;
do
{
GenTreeRetExpr* retExpr = inlineCandidate->AsRetExpr();
inlineCandidate = retExpr->gtSubstExpr;
inlineeBB = retExpr->gtSubstBB;
} while (inlineCandidate->OperIs(GT_RET_EXPR));
// We might as well try and fold the return value. Eg returns of
// constant bools will have CASTS. This folding may uncover more
// GT_RET_EXPRs, so we loop around until we've got something distinct.
//
inlineCandidate = m_compiler->gtFoldExpr(inlineCandidate);
var_types retType = tree->TypeGet();
#ifdef DEBUG
if (m_compiler->verbose)
{
printf("\nReplacing the return expression placeholder ");
Compiler::printTreeID(tree);
printf(" with ");
Compiler::printTreeID(inlineCandidate);
printf("\n");
// Dump out the old return expression placeholder it will be overwritten by the ReplaceWith below
m_compiler->gtDispTree(tree);
}
#endif // DEBUG
var_types newType = inlineCandidate->TypeGet();
// If we end up swapping type we may need to retype the tree:
if (retType != newType)
{
if ((retType == TYP_BYREF) && (tree->OperGet() == GT_IND))
{
// - in an RVA static if we've reinterpreted it as a byref;
assert(newType == TYP_I_IMPL);
JITDUMP("Updating type of the return GT_IND expression to TYP_BYREF\n");
inlineCandidate->gtType = TYP_BYREF;
}
}
*use = inlineCandidate;
m_madeChanges = true;
if (inlineeBB != nullptr)
{
// IR may potentially contain nodes that requires mandatory BB flags to be set.
// Propagate those flags from the containing BB.
m_compiler->compCurBB->bbFlags |= inlineeBB->bbFlags & BBF_COPY_PROPAGATE;
}
#ifdef DEBUG
if (m_compiler->verbose)
{
printf("\nInserting the inline return expression\n");
m_compiler->gtDispTree(inlineCandidate);
printf("\n");
}
#endif // DEBUG
}
// If an inline was rejected and the call returns a struct, we may
// have deferred some work when importing call for cases where the
// struct is returned in multiple registers.
//
// See the bail-out clauses in impFixupCallStructReturn for inline
// candidates.
//
// Do the deferred work now.
if (retClsHnd != NO_CLASS_HANDLE)
{
Compiler::structPassingKind howToReturnStruct;
var_types returnType =
m_compiler->getReturnTypeForStruct(retClsHnd, CorInfoCallConvExtension::Managed, &howToReturnStruct);
switch (howToReturnStruct)
{
#if FEATURE_MULTIREG_RET
// Force multi-reg nodes into the "lcl = node()" form if necessary.
//
case Compiler::SPK_ByValue:
case Compiler::SPK_ByValueAsHfa:
{
// See assert below, we only look one level above for an asg parent.
if (parent->OperIs(GT_ASG))
{
// The inlinee can only be the RHS.
assert(parent->gtGetOp2() == *use);
AttachStructInlineeToAsg(parent->AsOp(), retClsHnd);
}
else
{
// Just assign the inlinee to a variable to keep it simple.
*use = AssignStructInlineeToVar(*use, retClsHnd);
}
m_madeChanges = true;
}
break;
#endif // FEATURE_MULTIREG_RET
case Compiler::SPK_EnclosingType:
case Compiler::SPK_PrimitiveType:
// No work needs to be done, the call has struct type and should keep it.
break;
case Compiler::SPK_ByReference:
// We should have already added the return buffer
// when we first imported the call
break;
default:
noway_assert(!"Unexpected struct passing kind");
break;
}
}
}
#if FEATURE_MULTIREG_RET
//------------------------------------------------------------------------
// AttachStructInlineeToAsg: Update an "ASG(..., inlinee)" tree.
//
// Morphs inlinees that are multi-reg nodes into the (only) supported shape
// of "lcl = node()", either by marking the LHS local "lvIsMultiRegRet" or
// assigning the node into a temp and using that as the RHS.
//
// Arguments:
// asg - The assignment with the inlinee on the RHS
// retClsHnd - The struct handle for the inlinee
//
void AttachStructInlineeToAsg(GenTreeOp* asg, CORINFO_CLASS_HANDLE retClsHnd)
{
assert(asg->OperIs(GT_ASG));
GenTree* dst = asg->gtGetOp1();
GenTree* inlinee = asg->gtGetOp2();
// We need to force all assignments from multi-reg nodes into the "lcl = node()" form.
if (inlinee->IsMultiRegNode())
{
// Special case: we already have a local, the only thing to do is mark it appropriately. Except
// if it may turn into an indirection.
if (dst->OperIs(GT_LCL_VAR) && !m_compiler->lvaIsImplicitByRefLocal(dst->AsLclVar()->GetLclNum()))
{
m_compiler->lvaGetDesc(dst->AsLclVar())->lvIsMultiRegRet = true;
}
else
{
// Here, we assign our node into a fresh temp and then use that temp as the new value.
asg->gtOp2 = AssignStructInlineeToVar(inlinee, retClsHnd);
}
}
}
//------------------------------------------------------------------------
// AssignStructInlineeToVar: Assign the struct inlinee to a temp local.
//
// Arguments:
// inlinee - The inlinee of the RET_EXPR node
// retClsHnd - The struct class handle of the type of the inlinee.
//
// Return Value:
// Value representing the freshly assigned temp.
//
GenTree* AssignStructInlineeToVar(GenTree* inlinee, CORINFO_CLASS_HANDLE retClsHnd)
{
assert(!inlinee->OperIs(GT_MKREFANY, GT_RET_EXPR));
unsigned lclNum = m_compiler->lvaGrabTemp(false DEBUGARG("RetBuf for struct inline return candidates."));
LclVarDsc* varDsc = m_compiler->lvaGetDesc(lclNum);
m_compiler->lvaSetStruct(lclNum, retClsHnd, false);
// Sink the assignment below any COMMAs: this is required for multi-reg nodes.
GenTree* src = inlinee;
GenTree* lastComma = nullptr;
while (src->OperIs(GT_COMMA))
{
lastComma = src;
src = src->AsOp()->gtOp2;
}
// When assigning a multi-register value to a local var, make sure the variable is marked as lvIsMultiRegRet.
if (src->IsMultiRegNode())
{
varDsc->lvIsMultiRegRet = true;
}
GenTree* dst = m_compiler->gtNewLclvNode(lclNum, varDsc->TypeGet());
GenTree* asg = m_compiler->gtNewBlkOpNode(dst, src);
// If inlinee was comma, new inlinee is (, , , lcl = inlinee).
if (inlinee->OperIs(GT_COMMA))
{
lastComma->AsOp()->gtOp2 = asg;
asg = inlinee;
}
// Block morphing does not support (promoted) locals under commas, as such, instead of "COMMA(asg, lcl)" we
// do "OBJ(COMMA(asg, ADDR(LCL)))". TODO-1stClassStructs: improve block morphing and delete this workaround.
//
GenTree* lcl = m_compiler->gtNewLclvNode(lclNum, varDsc->TypeGet());
GenTree* addr = m_compiler->gtNewOperNode(GT_ADDR, TYP_I_IMPL, lcl);
addr = m_compiler->gtNewOperNode(GT_COMMA, addr->TypeGet(), asg, addr);
GenTree* obj = m_compiler->gtNewObjNode(varDsc->GetLayout(), addr);
return obj;
}
#endif // FEATURE_MULTIREG_RET
//------------------------------------------------------------------------
// LateDevirtualization: re-examine calls after inlining to see if we
// can do more devirtualization
//
// Arguments:
// pTree -- pointer to tree to examine for updates
// parent -- parent node containing the pTree edge
//
// Returns:
// fgWalkResult indicating the walk should continue; that
// is we wish to fully explore the tree.
//
// Notes:
// We used to check this opportunistically in the preorder callback for
// calls where the `obj` was fed by a return, but we now re-examine
// all calls.
//
// Late devirtualization (and eventually, perhaps, other type-driven
// opts like cast optimization) can happen now because inlining or other
// optimizations may have provided more accurate types than we saw when
// first importing the trees.
//
// It would be nice to screen candidate sites based on the likelihood
// that something has changed. Otherwise we'll waste some time retrying
// an optimization that will just fail again.
void LateDevirtualization(GenTree** pTree, GenTree* parent)
{
GenTree* tree = *pTree;
// In some (rare) cases the parent node of tree will be smashed to a NOP during
// the preorder by AttachStructToInlineeArg.
//
// jit\Methodical\VT\callconv\_il_reljumper3 for x64 linux
//
// If so, just bail out here.
if (tree == nullptr)
{
assert((parent != nullptr) && parent->OperGet() == GT_NOP);
return;
}
if (tree->OperGet() == GT_CALL)
{
GenTreeCall* call = tree->AsCall();
bool tryLateDevirt = call->IsVirtual() && (call->gtCallType == CT_USER_FUNC);
#ifdef DEBUG
tryLateDevirt = tryLateDevirt && (JitConfig.JitEnableLateDevirtualization() == 1);
#endif // DEBUG
if (tryLateDevirt)
{
#ifdef DEBUG
if (m_compiler->verbose)
{
printf("**** Late devirt opportunity\n");
m_compiler->gtDispTree(call);
}
#endif // DEBUG
CORINFO_CONTEXT_HANDLE context = nullptr;
CORINFO_METHOD_HANDLE method = call->gtCallMethHnd;
unsigned methodFlags = 0;
const bool isLateDevirtualization = true;
const bool explicitTailCall = call->IsTailPrefixedCall();
if ((call->gtCallMoreFlags & GTF_CALL_M_HAS_LATE_DEVIRT_INFO) != 0)
{
context = call->gtLateDevirtualizationInfo->exactContextHnd;
// Note: we might call this multiple times for the same trees.
// If the devirtualization below succeeds, the call becomes
// non-virtual and we won't get here again. If it does not
// succeed we might get here again so we keep the late devirt
// info.
}
m_compiler->impDevirtualizeCall(call, nullptr, &method, &methodFlags, &context, nullptr,
isLateDevirtualization, explicitTailCall);
m_madeChanges = true;
}
}
else if (tree->OperGet() == GT_ASG)
{
// If we're assigning to a ref typed local that has one definition,
// we may be able to sharpen the type for the local.
GenTree* const effLhs = tree->gtGetOp1()->gtEffectiveVal();
if ((effLhs->OperGet() == GT_LCL_VAR) && (effLhs->TypeGet() == TYP_REF))
{
const unsigned lclNum = effLhs->AsLclVarCommon()->GetLclNum();
LclVarDsc* lcl = m_compiler->lvaGetDesc(lclNum);
if (lcl->lvSingleDef)
{
GenTree* rhs = tree->gtGetOp2();
bool isExact = false;
bool isNonNull = false;
CORINFO_CLASS_HANDLE newClass = m_compiler->gtGetClassHandle(rhs, &isExact, &isNonNull);
if (newClass != NO_CLASS_HANDLE)
{
m_compiler->lvaUpdateClass(lclNum, newClass, isExact);
m_madeChanges = true;
}
}
}
// If we created a self-assignment (say because we are sharing return spill temps)
// we can remove it.
//
GenTree* const lhs = tree->gtGetOp1();
GenTree* const rhs = tree->gtGetOp2();
if (lhs->OperIs(GT_LCL_VAR) && GenTree::Compare(lhs, rhs))
{
m_compiler->gtUpdateNodeSideEffects(tree);
assert((tree->gtFlags & GTF_SIDE_EFFECT) == GTF_ASG);
JITDUMP("... removing self-assignment\n");
DISPTREE(tree);
tree->gtBashToNOP();
m_madeChanges = true;
}
}
else if (tree->OperGet() == GT_JTRUE)
{
// See if this jtrue is now foldable.
BasicBlock* block = m_compiler->compCurBB;
GenTree* condTree = tree->AsOp()->gtOp1;
assert(tree == block->lastStmt()->GetRootNode());
if (condTree->OperGet() == GT_CNS_INT)
{
JITDUMP(" ... found foldable jtrue at [%06u] in " FMT_BB "\n", m_compiler->dspTreeID(tree),
block->bbNum);
// We have a constant operand, and should have the all clear to optimize.
// Update side effects on the tree, assert there aren't any, and bash to nop.
m_compiler->gtUpdateNodeSideEffects(tree);
assert((tree->gtFlags & GTF_SIDE_EFFECT) == 0);
tree->gtBashToNOP();
m_madeChanges = true;
if (!condTree->IsIntegralConst(0))
{
block->bbJumpKind = BBJ_ALWAYS;
m_compiler->fgRemoveRefPred(block->bbNext, block);
}
else
{
block->bbJumpKind = BBJ_NONE;
m_compiler->fgRemoveRefPred(block->bbJumpDest, block);
}
}
}
else
{
*pTree = m_compiler->gtFoldExpr(tree);
m_madeChanges = true;
}
}
};
//------------------------------------------------------------------------
// fgInline - expand inline candidates
//
// Returns:
// phase status indicating if anything was modified
//
// Notes:
// Inline candidates are identified during importation and candidate calls
// must be top-level expressions. In input IR, the result of the call (if any)
// is consumed elsewhere by a GT_RET_EXPR node.
//
// For successful inlines, calls are replaced by a sequence of argument setup
// instructions, the inlined method body, and return value cleanup. Note
// Inlining may introduce new inline candidates. These are processed in a
// depth-first fashion, as the inliner walks the IR in statement order.
//
// After inline expansion in a statement, the statement tree
// is walked to locate GT_RET_EXPR nodes. These are replaced by either
// * the original call tree, if the inline failed
// * the return value tree from the inlinee, if the inline succeeded
//
// This replacement happens in preorder; on the postorder side of the same
// tree walk, we look for opportunities to devirtualize or optimize now that
// we know the context for the newly supplied return value tree.
//
// Inline arguments may be directly substituted into the body of the inlinee
// in some cases. See impInlineFetchArg.
//
PhaseStatus Compiler::fgInline()
{
if (!opts.OptEnabled(CLFLG_INLINING))
{
return PhaseStatus::MODIFIED_NOTHING;
}
#ifdef DEBUG
fgPrintInlinedMethods =
JitConfig.JitPrintInlinedMethods().contains(info.compMethodHnd, info.compClassHnd, &info.compMethodInfo->args);
#endif // DEBUG
noway_assert(fgFirstBB != nullptr);
BasicBlock* block = fgFirstBB;
SubstitutePlaceholdersAndDevirtualizeWalker walker(this);
bool madeChanges = false;
do
{
// Make the current basic block address available globally
compCurBB = block;
for (Statement* const stmt : block->Statements())
{
#if defined(DEBUG) || defined(INLINE_DATA)
// In debug builds we want the inline tree to show all failed
// inlines. Some inlines may fail very early and never make it to
// candidate stage. So scan the tree looking for those early failures.
fgWalkTreePre(stmt->GetRootNodePointer(), fgFindNonInlineCandidate, stmt);
#endif
// See if we need to replace some return value place holders.
// Also, see if this replacement enables further devirtualization.
//
// Note we are doing both preorder and postorder work in this walker.
//
// The preorder callback is responsible for replacing GT_RET_EXPRs
// with the appropriate expansion (call or inline result).
// Replacement may introduce subtrees with GT_RET_EXPR and so
// we rely on the preorder to recursively process those as well.
//
// On the way back up, the postorder callback then re-examines nodes for
// possible further optimization, as the (now complete) GT_RET_EXPR
// replacement may have enabled optimizations by providing more
// specific types for trees or variables.
walker.WalkTree(stmt->GetRootNodePointer(), nullptr);
GenTree* expr = stmt->GetRootNode();
// The importer ensures that all inline candidates are
// statement expressions. So see if we have a call.
if (expr->IsCall())
{
GenTreeCall* call = expr->AsCall();
// We do. Is it an inline candidate?
//
// Note we also process GuardeDevirtualizationCandidates here as we've
// split off GT_RET_EXPRs for them even when they are not inline candidates
// as we need similar processing to ensure they get patched back to where
// they belong.
if (call->IsInlineCandidate() || call->IsGuardedDevirtualizationCandidate())
{
InlineResult inlineResult(this, call, stmt, "fgInline");
fgMorphStmt = stmt;
fgMorphCallInline(call, &inlineResult);
// If there's a candidate to process, we will make changes
madeChanges = true;
// fgMorphCallInline may have updated the
// statement expression to a GT_NOP if the
// call returned a value, regardless of
// whether the inline succeeded or failed.
//
// If so, remove the GT_NOP and continue
// on with the next statement.
if (stmt->GetRootNode()->IsNothingNode())
{
fgRemoveStmt(block, stmt);
continue;
}
}
}
// See if stmt is of the form GT_COMMA(call, nop)
// If yes, we can get rid of GT_COMMA.
if (expr->OperGet() == GT_COMMA && expr->AsOp()->gtOp1->OperGet() == GT_CALL &&
expr->AsOp()->gtOp2->OperGet() == GT_NOP)
{
madeChanges = true;
stmt->SetRootNode(expr->AsOp()->gtOp1);
}
}
block = block->bbNext;
} while (block);
madeChanges |= walker.MadeChanges();
#ifdef DEBUG
// Check that we should not have any inline candidate or return value place holder left.
block = fgFirstBB;
noway_assert(block);
do
{
for (Statement* const stmt : block->Statements())
{
// Call Compiler::fgDebugCheckInlineCandidates on each node
fgWalkTreePre(stmt->GetRootNodePointer(), fgDebugCheckInlineCandidates);
}
block = block->bbNext;
} while (block);
fgVerifyHandlerTab();
if (verbose || fgPrintInlinedMethods)
{
JITDUMP("**************** Inline Tree");
printf("\n");
m_inlineStrategy->Dump(verbose || JitConfig.JitPrintInlinedMethodsVerbose());
}
#endif // DEBUG
if (madeChanges)
{
// Optional quirk to keep this as zero diff. Some downstream phases are bbNum sensitive
// but rely on the ambient bbNums.
//
fgRenumberBlocks();
}
return madeChanges ? PhaseStatus::MODIFIED_EVERYTHING : PhaseStatus::MODIFIED_NOTHING;
}
//------------------------------------------------------------------------------
// fgMorphCallInline: attempt to inline a call
//
// Arguments:
// call - call expression to inline, inline candidate
// inlineResult - result tracking and reporting
//
// Notes:
// Attempts to inline the call.
//
// If successful, callee's IR is inserted in place of the call, and
// is marked with an InlineContext.
//
// If unsuccessful, the transformations done in anticipation of a
// possible inline are undone, and the candidate flag on the call
// is cleared.
//
void Compiler::fgMorphCallInline(GenTreeCall* call, InlineResult* inlineResult)
{
bool inliningFailed = false;
InlineCandidateInfo* inlCandInfo = call->gtInlineCandidateInfo;
// Is this call an inline candidate?
if (call->IsInlineCandidate())
{
InlineContext* createdContext = nullptr;
// Attempt the inline
fgMorphCallInlineHelper(call, inlineResult, &createdContext);
// We should have made up our minds one way or another....
assert(inlineResult->IsDecided());
// If we failed to inline, we have a bit of work to do to cleanup
if (inlineResult->IsFailure())
{
if (createdContext != nullptr)
{
// We created a context before we got to the failure, so mark
// it as failed in the tree.
createdContext->SetFailed(inlineResult);
}
else
{
#ifdef DEBUG
// In debug we always put all inline attempts into the inline tree.
InlineContext* ctx =
m_inlineStrategy->NewContext(call->gtInlineCandidateInfo->inlinersContext, fgMorphStmt, call);
ctx->SetFailed(inlineResult);
#endif
}
inliningFailed = true;
// Clear the Inline Candidate flag so we can ensure later we tried
// inlining all candidates.
//
call->gtFlags &= ~GTF_CALL_INLINE_CANDIDATE;
}
}
else
{
// This wasn't an inline candidate. So it must be a GDV candidate.
assert(call->IsGuardedDevirtualizationCandidate());
// We already know we can't inline this call, so don't even bother to try.
inliningFailed = true;
}
// If we failed to inline (or didn't even try), do some cleanup.
if (inliningFailed)
{
if (call->gtReturnType != TYP_VOID)
{
JITDUMP("Inlining [%06u] failed, so bashing " FMT_STMT " to NOP\n", dspTreeID(call), fgMorphStmt->GetID());
// Detach the GT_CALL tree from the original statement by
// hanging a "nothing" node to it. Later the "nothing" node will be removed
// and the original GT_CALL tree will be picked up by the GT_RET_EXPR node.
inlCandInfo->retExpr->gtSubstExpr = call;
inlCandInfo->retExpr->gtSubstBB = compCurBB;
noway_assert(fgMorphStmt->GetRootNode() == call);
fgMorphStmt->SetRootNode(gtNewNothingNode());
}
}
}
//------------------------------------------------------------------------------
// fgMorphCallInlineHelper: Helper to attempt to inline a call
//
// Arguments:
// call - call expression to inline, inline candidate
// result - result to set to success or failure
// createdContext - The context that was created if the inline attempt got to the inliner.
//
// Notes:
// Attempts to inline the call.
//
// If successful, callee's IR is inserted in place of the call, and
// is marked with an InlineContext.
//
// If unsuccessful, the transformations done in anticipation of a
// possible inline are undone, and the candidate flag on the call
// is cleared.
//
// If a context was created because we got to the importer then it is output by this function.
// If the inline succeeded, this context will already be marked as successful. If it failed and
// a context is returned, then it will not have been marked as success or failed.
//
void Compiler::fgMorphCallInlineHelper(GenTreeCall* call, InlineResult* result, InlineContext** createdContext)
{
// Don't expect any surprises here.
assert(result->IsCandidate());
if (lvaCount >= MAX_LV_NUM_COUNT_FOR_INLINING)
{
// For now, attributing this to call site, though it's really
// more of a budget issue (lvaCount currently includes all
// caller and prospective callee locals). We still might be
// able to inline other callees into this caller, or inline
// this callee in other callers.
result->NoteFatal(InlineObservation::CALLSITE_TOO_MANY_LOCALS);
return;
}
if (call->IsVirtual())
{
result->NoteFatal(InlineObservation::CALLSITE_IS_VIRTUAL);
return;
}
// Re-check this because guarded devirtualization may allow these through.
if (gtIsRecursiveCall(call) && call->IsImplicitTailCall())
{
result->NoteFatal(InlineObservation::CALLSITE_IMPLICIT_REC_TAIL_CALL);
return;
}
// impMarkInlineCandidate() is expected not to mark tail prefixed calls
// and recursive tail calls as inline candidates.
noway_assert(!call->IsTailPrefixedCall());
noway_assert(!call->IsImplicitTailCall() || !gtIsRecursiveCall(call));
//
// Calling inlinee's compiler to inline the method.
//
unsigned const startVars = lvaCount;
unsigned const startBBNumMax = fgBBNumMax;
#ifdef DEBUG
if (verbose)
{
printf("Expanding INLINE_CANDIDATE in statement ");
printStmtID(fgMorphStmt);
printf(" in " FMT_BB ":\n", compCurBB->bbNum);
gtDispStmt(fgMorphStmt);
if (call->IsImplicitTailCall())
{
printf("Note: candidate is implicit tail call\n");
}
}
#endif
impInlineRoot()->m_inlineStrategy->NoteAttempt(result);
//
// Invoke the compiler to inline the call.
//
fgInvokeInlineeCompiler(call, result, createdContext);
if (result->IsFailure())
{
// Undo some changes made during the inlining attempt.
// Zero out the used locals
memset((void*)(lvaTable + startVars), 0, (lvaCount - startVars) * sizeof(*lvaTable));
for (unsigned i = startVars; i < lvaCount; i++)
{
new (&lvaTable[i], jitstd::placement_t()) LclVarDsc(); // call the constructor.
}
// Reset local var count and max bb num
lvaCount = startVars;
fgBBNumMax = startBBNumMax;
#ifdef DEBUG
for (BasicBlock* block : Blocks())
{
assert(block->bbNum <= fgBBNumMax);
}
#endif
}
}
#if defined(DEBUG) || defined(INLINE_DATA)
//------------------------------------------------------------------------
// fgFindNonInlineCandidate: tree walk helper to ensure that a tree node
// that is not an inline candidate is noted as a failed inline.
//
// Arguments:
// pTree - pointer to pointer tree node being walked
// data - contextual data for the walk
//
// Return Value:
// walk result
//
// Note:
// Invokes fgNoteNonInlineCandidate on the nodes it finds.
Compiler::fgWalkResult Compiler::fgFindNonInlineCandidate(GenTree** pTree, fgWalkData* data)
{
GenTree* tree = *pTree;
if (tree->gtOper == GT_CALL)
{
Compiler* compiler = data->compiler;
Statement* stmt = (Statement*)data->pCallbackData;
GenTreeCall* call = tree->AsCall();
compiler->fgNoteNonInlineCandidate(stmt, call);
}
return WALK_CONTINUE;
}
//------------------------------------------------------------------------
// fgNoteNonInlineCandidate: account for inlining failures in calls
// not marked as inline candidates.
//
// Arguments:
// stmt - statement containing the call
// call - the call itself
//
// Notes:
// Used in debug only to try and place descriptions of inline failures
// into the proper context in the inline tree.
void Compiler::fgNoteNonInlineCandidate(Statement* stmt, GenTreeCall* call)
{
if (call->IsInlineCandidate() || call->IsGuardedDevirtualizationCandidate())
{
return;
}
InlineResult inlineResult(this, call, nullptr, "fgNoteNonInlineCandidate", false);
InlineObservation currentObservation = InlineObservation::CALLSITE_NOT_CANDIDATE;
// Try and recover the reason left behind when the jit decided
// this call was not a candidate.
InlineObservation priorObservation = call->gtInlineObservation;
if (InlIsValidObservation(priorObservation))
{
currentObservation = priorObservation;
}
// Propagate the prior failure observation to this result.
inlineResult.NotePriorFailure(currentObservation);