forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfgbasic.cpp
6902 lines (5944 loc) · 251 KB
/
fgbasic.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 Construction and Maintenance
void Compiler::fgInit()
{
impInit();
/* Initialization for fgWalkTreePre() and fgWalkTreePost() */
fgFirstBBScratch = nullptr;
#ifdef DEBUG
fgPrintInlinedMethods = false;
#endif // DEBUG
/* We haven't yet computed the bbPreds lists */
fgPredsComputed = false;
/* We haven't yet computed the edge weight */
fgEdgeWeightsComputed = false;
fgHaveValidEdgeWeights = false;
fgSlopUsedInEdgeWeights = false;
fgRangeUsedInEdgeWeights = true;
fgCalledCount = BB_ZERO_WEIGHT;
/* Initialize the basic block list */
fgFirstBB = nullptr;
fgLastBB = nullptr;
fgFirstColdBlock = nullptr;
fgEntryBB = nullptr;
fgOSREntryBB = nullptr;
fgEntryBBExtraRefs = 0;
#if defined(FEATURE_EH_FUNCLETS)
fgFirstFuncletBB = nullptr;
fgFuncletsCreated = false;
#endif // FEATURE_EH_FUNCLETS
fgBBcount = 0;
#ifdef DEBUG
fgBBOrder = nullptr;
#endif // DEBUG
fgMightHaveNaturalLoops = false;
fgBBNumMax = 0;
fgEdgeCount = 0;
fgDomBBcount = 0;
fgBBVarSetsInited = false;
fgReturnCount = 0;
m_dfsTree = nullptr;
m_loops = nullptr;
m_loopSideEffects = nullptr;
m_blockToLoop = nullptr;
m_domTree = nullptr;
m_reachabilitySets = nullptr;
// Initialize BlockSet data.
fgCurBBEpoch = 0;
fgCurBBEpochSize = 0;
fgBBSetCountInSizeTUnits = 0;
genReturnBB = nullptr;
genReturnLocal = BAD_VAR_NUM;
/* We haven't reached the global morphing phase */
fgGlobalMorph = false;
fgGlobalMorphDone = false;
fgModified = false;
#ifdef DEBUG
fgSafeBasicBlockCreation = true;
fgSafeFlowEdgeCreation = true;
#endif // DEBUG
fgLocalVarLivenessDone = false;
fgIsDoingEarlyLiveness = false;
fgDidEarlyLiveness = false;
/* Statement list is not threaded yet */
fgNodeThreading = NodeThreading::None;
// Initialize the logic for adding code. This is used to insert code such
// as the code that raises an exception when an array range check fails.
fgAddCodeList = nullptr;
fgAddCodeDscMap = nullptr;
/* Keep track of the max count of pointer arguments */
fgPtrArgCntMax = 0;
/* This global flag is set whenever we remove a statement */
fgStmtRemoved = false;
// This global flag is set when we create throw helper blocks
fgRngChkThrowAdded = false;
/* Keep track of whether or not EH statements have been optimized */
fgOptimizedFinally = false;
/* We will record a list of all BBJ_RETURN blocks here */
fgReturnBlocks = nullptr;
fgUsedSharedTemps = nullptr;
#if !defined(FEATURE_EH_FUNCLETS)
ehMaxHndNestingCount = 0;
#endif // !FEATURE_EH_FUNCLETS
/* Init the fgBigOffsetMorphingTemps to be BAD_VAR_NUM. */
for (int i = 0; i < TYP_COUNT; i++)
{
fgBigOffsetMorphingTemps[i] = BAD_VAR_NUM;
}
fgNoStructPromotion = false;
fgNoStructParamPromotion = false;
optValnumCSE_phase = false; // referenced in fgMorphSmpOp()
#ifdef DEBUG
fgNormalizeEHDone = false;
#endif // DEBUG
#ifdef DEBUG
if (!compIsForInlining())
{
const int noStructPromotionValue = JitConfig.JitNoStructPromotion();
assert(0 <= noStructPromotionValue && noStructPromotionValue <= 2);
if (noStructPromotionValue == 1)
{
fgNoStructPromotion = true;
}
if (noStructPromotionValue == 2)
{
fgNoStructParamPromotion = true;
}
}
#endif // DEBUG
#ifdef FEATURE_SIMD
fgPreviousCandidateSIMDFieldStoreStmt = nullptr;
#endif
fgHasSwitch = false;
fgPgoDisabled = false;
fgPgoSchema = nullptr;
fgPgoData = nullptr;
fgPgoSchemaCount = 0;
fgNumProfileRuns = 0;
fgPgoBlockCounts = 0;
fgPgoEdgeCounts = 0;
fgPgoClassProfiles = 0;
fgPgoMethodProfiles = 0;
fgPgoInlineePgo = 0;
fgPgoInlineeNoPgo = 0;
fgPgoInlineeNoPgoSingleBlock = 0;
fgCountInstrumentor = nullptr;
fgHistogramInstrumentor = nullptr;
fgValueInstrumentor = nullptr;
fgPredListSortVector = nullptr;
fgCanonicalizedFirstBB = false;
}
//------------------------------------------------------------------------
// fgEnsureFirstBBisScratch: Ensure that fgFirstBB is a scratch BasicBlock
//
// Returns:
// True, if a new basic block was allocated.
//
// Notes:
// This should be called before adding on-entry initialization code to
// the method, to ensure that fgFirstBB is not part of a loop.
//
// Does nothing, if fgFirstBB is already a scratch BB. After calling this,
// fgFirstBB may already contain code. Callers have to be careful
// that they do not mess up the order of things added to this block and
// inadvertently change semantics.
//
// We maintain the invariant that a scratch BB ends with BBJ_ALWAYS,
// so that when adding independent bits of initialization,
// callers can generally append to the fgFirstBB block without worrying
// about what code is there already.
//
// Can be called at any time, and can be called multiple times.
//
bool Compiler::fgEnsureFirstBBisScratch()
{
// Have we already allocated a scratch block?
if (fgFirstBBisScratch())
{
return false;
}
assert(fgFirstBBScratch == nullptr);
BasicBlock* block;
if (fgFirstBB != nullptr)
{
// The first block has an implicit ref count which we must
// remove. Note the ref count could be greater than one, if
// the first block is not scratch and is targeted by a
// branch.
assert(fgFirstBB->bbRefs >= 1);
fgFirstBB->bbRefs--;
block = BasicBlock::New(this);
// If we have profile data the new block will inherit fgFirstBlock's weight
if (fgFirstBB->hasProfileWeight())
{
block->inheritWeight(fgFirstBB);
}
// The new scratch bb will fall through to the old first bb
FlowEdge* const edge = fgAddRefPred(fgFirstBB, block);
block->SetKindAndTargetEdge(BBJ_ALWAYS, edge);
fgInsertBBbefore(fgFirstBB, block);
}
else
{
noway_assert(fgLastBB == nullptr);
block = BasicBlock::New(this, BBJ_ALWAYS);
fgFirstBB = block;
fgLastBB = block;
}
noway_assert(fgLastBB != nullptr);
// Set the expected flags
block->SetFlags(BBF_INTERNAL | BBF_IMPORTED | BBF_NONE_QUIRK);
// This new first BB has an implicit ref, and no others.
//
// But if we call this early, before fgLinkBasicBlocks,
// defer and let it handle adding the implicit ref.
//
block->bbRefs = fgPredsComputed ? 1 : 0;
fgFirstBBScratch = fgFirstBB;
#ifdef DEBUG
if (verbose)
{
printf("New scratch " FMT_BB "\n", block->bbNum);
}
#endif
return true;
}
//------------------------------------------------------------------------
// fgFirstBBisScratch: Check if fgFirstBB is a scratch block
//
// Returns:
// true if fgFirstBB is a scratch block.
//
bool Compiler::fgFirstBBisScratch()
{
if (fgFirstBBScratch != nullptr)
{
assert(fgFirstBBScratch == fgFirstBB);
assert(fgFirstBBScratch->HasFlag(BBF_INTERNAL));
if (fgPredsComputed)
{
assert(fgFirstBBScratch->countOfInEdges() == 1);
}
// Normally, the first scratch block is a fall-through block. However, if the block after it was an empty
// BBJ_ALWAYS block, it might get removed, and the code that removes it will make the first scratch block
// a BBJ_ALWAYS block.
assert(fgFirstBBScratch->KindIs(BBJ_ALWAYS));
return true;
}
else
{
return false;
}
}
//------------------------------------------------------------------------
// fgBBisScratch: Check if a given block is a scratch block.
//
// Arguments:
// block - block in question
//
// Returns:
// true if this block is the first block and is a scratch block.
//
bool Compiler::fgBBisScratch(BasicBlock* block)
{
return fgFirstBBisScratch() && (block == fgFirstBB);
}
/*
Removes a block from the return block list
*/
void Compiler::fgRemoveReturnBlock(BasicBlock* block)
{
if (fgReturnBlocks == nullptr)
{
return;
}
if (fgReturnBlocks->block == block)
{
// It's the 1st entry, assign new head of list.
fgReturnBlocks = fgReturnBlocks->next;
return;
}
for (BasicBlockList* retBlocks = fgReturnBlocks; retBlocks->next != nullptr; retBlocks = retBlocks->next)
{
if (retBlocks->next->block == block)
{
// Found it; splice it out.
retBlocks->next = retBlocks->next->next;
return;
}
}
}
//------------------------------------------------------------------------
// fgConvertBBToThrowBB: Change a given block to a throw block.
//
// Arguments:
// block - block in question
//
void Compiler::fgConvertBBToThrowBB(BasicBlock* block)
{
JITDUMP("Converting " FMT_BB " to BBJ_THROW\n", block->bbNum);
assert(fgPredsComputed);
// Ordering of the following operations matters.
// First, if we are looking at the first block of a callfinally pair, remove the pairing.
// Don't actually remove the BBJ_CALLFINALLYRET as that might affect block iteration in
// the callers.
if (block->isBBCallFinallyPair())
{
BasicBlock* const leaveBlock = block->Next();
fgPrepareCallFinallyRetForRemoval(leaveBlock);
}
// Scrub this block from the pred lists of any successors
fgRemoveBlockAsPred(block);
// Update jump kind after the scrub.
block->SetKindAndTargetEdge(BBJ_THROW);
block->RemoveFlags(BBF_RETLESS_CALL); // no longer a BBJ_CALLFINALLY
// Any block with a throw is rare
block->bbSetRunRarely();
}
/*****************************************************************************
* fgChangeSwitchBlock:
*
* We have a BBJ_SWITCH jump at 'oldSwitchBlock' and we want to move this
* switch jump over to 'newSwitchBlock'. All of the blocks that are jumped
* to from jumpTab[] need to have their predecessor lists updated by removing
* the 'oldSwitchBlock' and adding 'newSwitchBlock'.
*/
void Compiler::fgChangeSwitchBlock(BasicBlock* oldSwitchBlock, BasicBlock* newSwitchBlock)
{
noway_assert(oldSwitchBlock != nullptr);
noway_assert(newSwitchBlock != nullptr);
noway_assert(oldSwitchBlock->KindIs(BBJ_SWITCH));
assert(fgPredsComputed);
// Walk the switch's jump table, updating the predecessor for each branch.
BBswtDesc* swtDesc = oldSwitchBlock->GetSwitchTargets();
for (unsigned i = 0; i < swtDesc->bbsCount; i++)
{
FlowEdge* succEdge = swtDesc->bbsDstTab[i];
assert(succEdge != nullptr);
if (succEdge->getSourceBlock() != oldSwitchBlock)
{
// swtDesc can have duplicate targets, so we may have updated this edge already
//
assert(succEdge->getSourceBlock() == newSwitchBlock);
assert(succEdge->getDupCount() > 1);
}
else
{
// Redirect edge's source block from oldSwitchBlock to newSwitchBlock,
// and keep successor block's pred list in order
//
fgReplacePred(succEdge, newSwitchBlock);
}
}
if (m_switchDescMap != nullptr)
{
SwitchUniqueSuccSet uniqueSuccSet;
// If already computed and cached the unique descriptors for the old block, let's
// update those for the new block.
if (m_switchDescMap->Lookup(oldSwitchBlock, &uniqueSuccSet))
{
m_switchDescMap->Set(newSwitchBlock, uniqueSuccSet, BlockToSwitchDescMap::Overwrite);
}
else
{
fgInvalidateSwitchDescMapEntry(newSwitchBlock);
}
fgInvalidateSwitchDescMapEntry(oldSwitchBlock);
}
}
//------------------------------------------------------------------------
// fgChangeEhfBlock: We have a BBJ_EHFINALLYRET block at 'oldBlock' and we want to move this
// to 'newBlock'. All of the 'oldBlock' successors need to have their predecessor lists updated
// by removing edges to 'oldBlock' and adding edges to 'newBlock'.
//
// Arguments:
// oldBlock - previous BBJ_EHFINALLYRET block
// newBlock - block that is replacing 'oldBlock'
//
void Compiler::fgChangeEhfBlock(BasicBlock* oldBlock, BasicBlock* newBlock)
{
assert(oldBlock != nullptr);
assert(newBlock != nullptr);
assert(oldBlock->KindIs(BBJ_EHFINALLYRET));
assert(fgPredsComputed);
BBehfDesc* ehfDesc = oldBlock->GetEhfTargets();
for (unsigned i = 0; i < ehfDesc->bbeCount; i++)
{
FlowEdge* succEdge = ehfDesc->bbeSuccs[i];
fgReplacePred(succEdge, newBlock);
}
}
//------------------------------------------------------------------------
// fgReplaceEhfSuccessor: update BBJ_EHFINALLYRET block so that all control
// that previously flowed to oldSucc now flows to newSucc. It is assumed
// that oldSucc is currently a successor of `block`. We only allow a successor
// block to appear once in the successor list. Thus, if the new successor
// already exists in the list, we simply remove the old successor.
//
// Arguments:
// block - BBJ_EHFINALLYRET block
// newSucc - new successor
// oldSucc - old successor
//
void Compiler::fgReplaceEhfSuccessor(BasicBlock* block, BasicBlock* oldSucc, BasicBlock* newSucc)
{
assert(block != nullptr);
assert(oldSucc != nullptr);
assert(newSucc != nullptr);
assert(block->KindIs(BBJ_EHFINALLYRET));
assert(fgPredsComputed);
BBehfDesc* const ehfDesc = block->GetEhfTargets();
const unsigned succCount = ehfDesc->bbeCount;
FlowEdge** const succTab = ehfDesc->bbeSuccs;
// Walk the successor table looking for the old successor, which we expect to find only once.
unsigned oldSuccNum = UINT_MAX;
unsigned newSuccNum = UINT_MAX;
for (unsigned i = 0; i < succCount; i++)
{
assert(succTab[i]->getSourceBlock() == block);
if (succTab[i]->getDestinationBlock() == newSucc)
{
assert(newSuccNum == UINT_MAX);
newSuccNum = i;
}
if (succTab[i]->getDestinationBlock() == oldSucc)
{
assert(oldSuccNum == UINT_MAX);
oldSuccNum = i;
}
}
noway_assert((oldSuccNum != UINT_MAX) && "Did not find oldSucc in succTab[]");
if (newSuccNum != UINT_MAX)
{
// The new successor is already in the table; simply remove the old one.
fgRemoveEhfSuccessor(block, oldSuccNum);
JITDUMP("Remove existing BBJ_EHFINALLYRET " FMT_BB " successor " FMT_BB "; replacement successor " FMT_BB
" already exists in list\n",
block->bbNum, oldSucc->bbNum, newSucc->bbNum);
}
else
{
// Remove the old edge [block => oldSucc]
//
fgRemoveAllRefPreds(oldSucc, block);
// Create the new edge [block => newSucc]
//
FlowEdge* const newEdge = fgAddRefPred(newSucc, block);
// Replace the old one with the new one.
//
succTab[oldSuccNum] = newEdge;
JITDUMP("Replace BBJ_EHFINALLYRET " FMT_BB " successor " FMT_BB " with " FMT_BB "\n", block->bbNum,
oldSucc->bbNum, newSucc->bbNum);
}
}
//------------------------------------------------------------------------
// fgRemoveEhfSuccessor: update BBJ_EHFINALLYRET block to remove the successor at `succIndex`
// in the block's jump table.
// Updates the predecessor list of the successor, if necessary.
//
// Arguments:
// block - BBJ_EHFINALLYRET block
// succIndex - index of the successor in block->GetEhfTargets()->bbeSuccs
//
void Compiler::fgRemoveEhfSuccessor(BasicBlock* block, const unsigned succIndex)
{
assert(block != nullptr);
assert(block->KindIs(BBJ_EHFINALLYRET));
assert(fgPredsComputed);
BBehfDesc* const ehfDesc = block->GetEhfTargets();
const unsigned succCount = ehfDesc->bbeCount;
FlowEdge** succTab = ehfDesc->bbeSuccs;
assert(succIndex < succCount);
FlowEdge* succEdge = succTab[succIndex];
fgRemoveRefPred(succEdge);
// If succEdge not the last entry, move everything after in the table down one slot.
if ((succIndex + 1) < succCount)
{
memmove_s(&succTab[succIndex], (succCount - succIndex) * sizeof(FlowEdge*), &succTab[succIndex + 1],
(succCount - succIndex - 1) * sizeof(FlowEdge*));
}
#ifdef DEBUG
// We only expect to see a successor once in the table.
for (unsigned i = succIndex; i < (succCount - 1); i++)
{
assert(succTab[i]->getDestinationBlock() != succEdge->getDestinationBlock());
}
#endif // DEBUG
ehfDesc->bbeCount--;
}
//------------------------------------------------------------------------
// fgRemoveEhfSuccessor: Removes `succEdge` from its BBJ_EHFINALLYRET source block's jump table.
// Updates the predecessor list of the successor block, if necessary.
//
// Arguments:
// block - BBJ_EHFINALLYRET block
// succEdge - FlowEdge* to be removed from predecessor block's jump table
//
void Compiler::fgRemoveEhfSuccessor(FlowEdge* succEdge)
{
assert(succEdge != nullptr);
assert(fgPredsComputed);
BasicBlock* block = succEdge->getSourceBlock();
assert(block != nullptr);
assert(block->KindIs(BBJ_EHFINALLYRET));
fgRemoveRefPred(succEdge);
BBehfDesc* const ehfDesc = block->GetEhfTargets();
const unsigned succCount = ehfDesc->bbeCount;
FlowEdge** succTab = ehfDesc->bbeSuccs;
bool found = false;
// Search succTab for succEdge so we can splice it out of the table.
for (unsigned i = 0; i < succCount; i++)
{
if (succTab[i] == succEdge)
{
// If succEdge not the last entry, move everything after in the table down one slot.
if ((i + 1) < succCount)
{
memmove_s(&succTab[i], (succCount - i) * sizeof(FlowEdge*), &succTab[i + 1],
(succCount - i - 1) * sizeof(FlowEdge*));
}
found = true;
#ifdef DEBUG
// We only expect to see a successor once in the table.
for (; i < (succCount - 1); i++)
{
assert(succTab[i]->getDestinationBlock() != succEdge->getDestinationBlock());
}
#endif // DEBUG
}
}
assert(found);
ehfDesc->bbeCount--;
}
//------------------------------------------------------------------------
// Compiler::fgReplaceJumpTarget: For a given block, replace the target 'oldTarget' with 'newTarget'.
//
// Arguments:
// block - the block in which a jump target will be replaced.
// newTarget - the new branch target of the block.
// oldTarget - the old branch target of the block.
//
// Notes:
// 1. Only branches are changed: BBJ_ALWAYS, the non-fallthrough path of BBJ_COND, BBJ_SWITCH, etc.
// We assert for other jump kinds.
// 2. All branch targets found are updated. If there are multiple ways for a block
// to reach 'oldTarget' (e.g., multiple arms of a switch), all of them are changed.
// 3. The predecessor lists are updated.
// 4. If any switch table entry was updated, the switch table "unique successor" cache is invalidated.
//
void Compiler::fgReplaceJumpTarget(BasicBlock* block, BasicBlock* oldTarget, BasicBlock* newTarget)
{
assert(block != nullptr);
assert(fgPredsComputed);
switch (block->GetKind())
{
case BBJ_CALLFINALLY:
case BBJ_CALLFINALLYRET:
case BBJ_ALWAYS:
case BBJ_EHCATCHRET:
case BBJ_EHFILTERRET:
case BBJ_LEAVE: // This function can be called before import, so we still have BBJ_LEAVE
assert(block->TargetIs(oldTarget));
fgRedirectTargetEdge(block, newTarget);
break;
case BBJ_COND:
if (block->TrueTargetIs(oldTarget))
{
if (block->FalseEdgeIs(block->GetTrueEdge()))
{
// Branch was degenerate, simplify it first
//
fgRemoveConditionalJump(block);
assert(block->KindIs(BBJ_ALWAYS));
assert(block->TargetIs(oldTarget));
fgRedirectTargetEdge(block, newTarget);
}
else
{
fgRedirectTrueEdge(block, newTarget);
}
}
else
{
// Already degenerate cases should have taken the true path above
//
assert(block->FalseTargetIs(oldTarget));
assert(!block->TrueEdgeIs(block->GetFalseEdge()));
fgRedirectFalseEdge(block, newTarget);
}
if (block->KindIs(BBJ_COND) && block->TrueEdgeIs(block->GetFalseEdge()))
{
// Block became degenerate, simplify
//
fgRemoveConditionalJump(block);
assert(block->KindIs(BBJ_ALWAYS));
assert(block->TargetIs(newTarget));
}
break;
case BBJ_SWITCH:
{
unsigned const jumpCnt = block->GetSwitchTargets()->bbsCount;
FlowEdge** const jumpTab = block->GetSwitchTargets()->bbsDstTab;
bool existingEdge = false;
FlowEdge* oldEdge = nullptr;
FlowEdge* newEdge = nullptr;
bool changed = false;
for (unsigned i = 0; i < jumpCnt; i++)
{
if (jumpTab[i]->getDestinationBlock() == newTarget)
{
// The new target already has an edge from this switch statement.
// We'll need to add the likelihood from the edge we're redirecting
// to the existing edge. Note that if there is no existing edge,
// then we'll copy the likelihood from the existing edge we pass to
// `fgAddRefPred`. Note also that we can visit the same edge multiple
// times if there are multiple switch cases with the same target. The
// edge has a dup count and a single likelihood for all the possible
// paths to the target, so we only want to add the likelihood once
// despite visiting the duplicated edges in the `jumpTab` array
// multiple times.
existingEdge = true;
}
if (jumpTab[i]->getDestinationBlock() == oldTarget)
{
assert((oldEdge == nullptr) || (oldEdge == jumpTab[i]));
oldEdge = jumpTab[i];
fgRemoveRefPred(oldEdge);
newEdge = fgAddRefPred(newTarget, block, oldEdge);
jumpTab[i] = newEdge;
changed = true;
}
}
if (existingEdge)
{
assert(oldEdge != nullptr);
assert(oldEdge->getSourceBlock() == block);
assert(oldEdge->getDestinationBlock() == oldTarget);
assert(newEdge != nullptr);
assert(newEdge->getSourceBlock() == block);
assert(newEdge->getDestinationBlock() == newTarget);
if (newEdge->hasLikelihood() && oldEdge->hasLikelihood())
{
newEdge->addLikelihood(oldEdge->getLikelihood());
}
}
assert(changed);
InvalidateUniqueSwitchSuccMap();
break;
}
case BBJ_EHFINALLYRET:
fgReplaceEhfSuccessor(block, oldTarget, newTarget);
break;
default:
assert(!"Block doesn't have a jump target!");
unreached();
break;
}
}
//------------------------------------------------------------------------
// fgReplacePred: redirects the given edge to a new predecessor block
//
// Arguments:
// edge - the edge whose source block we want to update
// newPred - the new predecessor block for edge
//
// Notes:
//
// This function assumes that all branches from the predecessor (practically, that all
// switch cases that target the successor block) are changed to branch from the new predecessor,
// with the same dup count.
//
// Note that the successor block's bbRefs is not changed, since it has the same number of
// references as before, just from a different predecessor block.
//
// Also note this may cause sorting of the pred list.
//
void Compiler::fgReplacePred(FlowEdge* edge, BasicBlock* const newPred)
{
assert(edge != nullptr);
assert(newPred != nullptr);
assert(edge->getSourceBlock() != newPred);
edge->setSourceBlock(newPred);
// We may now need to reorder the pred list.
//
BasicBlock* succBlock = edge->getDestinationBlock();
assert(succBlock != nullptr);
succBlock->ensurePredListOrder(this);
}
/*****************************************************************************
* For a block that is in a handler region, find the first block of the most-nested
* handler containing the block.
*/
BasicBlock* Compiler::fgFirstBlockOfHandler(BasicBlock* block)
{
assert(block->hasHndIndex());
return ehGetDsc(block->getHndIndex())->ebdHndBeg;
}
#ifdef DEBUG
//------------------------------------------------------------------------
// fgInvalidateBBLookup: In non-Release builds, set fgBBs to a dummy value.
// After calling this, fgInitBBLookup must be called before using fgBBs again.
//
void Compiler::fgInvalidateBBLookup()
{
fgBBs = (BasicBlock**)0xCDCD;
}
#endif // DEBUG
/*****************************************************************************
*
* The following helps find a basic block given its PC offset.
*/
void Compiler::fgInitBBLookup()
{
BasicBlock** dscBBptr;
/* Allocate the basic block table */
dscBBptr = fgBBs = new (this, CMK_BasicBlock) BasicBlock*[fgBBcount];
/* Walk all the basic blocks, filling in the table */
for (BasicBlock* const block : Blocks())
{
*dscBBptr++ = block;
}
noway_assert(dscBBptr == fgBBs + fgBBcount);
}
BasicBlock* Compiler::fgLookupBB(unsigned addr)
{
unsigned lo;
unsigned hi;
/* Do a binary search */
for (lo = 0, hi = fgBBcount - 1;;)
{
AGAIN:;
if (lo > hi)
{
break;
}
unsigned mid = (lo + hi) / 2;
BasicBlock* dsc = fgBBs[mid];
// We introduce internal blocks for BBJ_CALLFINALLY. Skip over these.
while (dsc->HasFlag(BBF_INTERNAL))
{
dsc = dsc->Next();
mid++;
// We skipped over too many, Set hi back to the original mid - 1
if (mid > hi)
{
mid = (lo + hi) / 2;
hi = mid - 1;
goto AGAIN;
}
}
unsigned pos = dsc->bbCodeOffs;
if (pos < addr)
{
if ((lo == hi) && (lo == (fgBBcount - 1)))
{
noway_assert(addr == dsc->bbCodeOffsEnd);
return nullptr; // NULL means the end of method
}
lo = mid + 1;
continue;
}
if (pos > addr)
{
hi = mid - 1;
continue;
}
return dsc;
}
#ifdef DEBUG
printf("ERROR: Couldn't find basic block at offset %04X\n", addr);
#endif // DEBUG
NO_WAY("fgLookupBB failed.");
}
//------------------------------------------------------------------------
// FgStack: simple stack model for the inlinee's evaluation stack.
//
// Model the inputs available to various operations in the inline body.
// Tracks constants, arguments, array lengths.
class FgStack
{
public:
FgStack() : slot0(SLOT_INVALID), slot1(SLOT_INVALID), depth(0)
{
// Empty
}
enum FgSlot
{
SLOT_INVALID = UINT_MAX,
SLOT_UNKNOWN = 0,
SLOT_CONSTANT = 1,
SLOT_ARRAYLEN = 2,
SLOT_ARGUMENT = 3
};
void Clear()
{
depth = 0;
}
void PushUnknown()
{
Push(SLOT_UNKNOWN);
}
void PushConstant()
{
Push(SLOT_CONSTANT);
}
void PushArrayLen()
{
Push(SLOT_ARRAYLEN);
}
void PushArgument(unsigned arg)
{
Push((FgSlot)(SLOT_ARGUMENT + arg));
}
FgSlot GetSlot0() const
{
return depth >= 1 ? slot0 : FgSlot::SLOT_UNKNOWN;
}
FgSlot GetSlot1() const
{
return depth >= 2 ? slot1 : FgSlot::SLOT_UNKNOWN;
}
FgSlot Top(const int n = 0)
{
if (n == 0)
{
return depth >= 1 ? slot0 : SLOT_UNKNOWN;
}
if (n == 1)
{
return depth == 2 ? slot1 : SLOT_UNKNOWN;
}
unreached();
}
static bool IsConstant(FgSlot value)
{
return value == SLOT_CONSTANT;
}
static bool IsConstantOrConstArg(FgSlot value, InlineInfo* info)
{
return IsConstant(value) || IsConstArgument(value, info);
}
static bool IsArrayLen(FgSlot value)
{
return value == SLOT_ARRAYLEN;
}
static bool IsArgument(FgSlot value)
{
return value >= SLOT_ARGUMENT;
}
static bool IsConstArgument(FgSlot value, InlineInfo* info)
{
if ((info == nullptr) || !IsArgument(value))
{
return false;
}
const unsigned argNum = value - SLOT_ARGUMENT;
if (argNum < info->argCnt)
{
return info->inlArgInfo[argNum].argIsInvariant;
}
return false;
}
static bool IsExactArgument(FgSlot value, InlineInfo* info)
{
if ((info == nullptr) || !IsArgument(value))
{
return false;
}
const unsigned argNum = value - SLOT_ARGUMENT;
if (argNum < info->argCnt)
{
return info->inlArgInfo[argNum].argIsExact;
}
return false;
}