forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfgopt.cpp
6196 lines (5338 loc) · 214 KB
/
fgopt.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
#include "lower.h" // for LowerRange()
// Flowgraph Optimization
//------------------------------------------------------------------------
// fgDominate: Returns true if block `b1` dominates block `b2`.
//
// Arguments:
// b1, b2 -- Two blocks to compare.
//
// Return Value:
// true if `b1` dominates `b2`. If either b1 or b2 were created after dominators were calculated,
// but the dominator information still exists, try to determine if we can make a statement about
// b1 dominating b2 based on existing dominator information and other information, such as
// predecessor lists or loop information.
//
// Assumptions:
// -- Dominators have been calculated (`fgDomsComputed` is true).
//
bool Compiler::fgDominate(BasicBlock* b1, BasicBlock* b2)
{
noway_assert(fgDomsComputed);
assert(!fgCheapPredsValid);
//
// If the fgModified flag is false then we made some modifications to
// the flow graph, like adding a new block or changing a conditional branch
// into an unconditional branch.
//
// We can continue to use the dominator and reachable information to
// unmark loops as long as we haven't renumbered the blocks or we aren't
// asking for information about a new block.
//
if (b2->bbNum > fgDomBBcount)
{
if (b1 == b2)
{
return true;
}
for (BasicBlock* const predBlock : b2->PredBlocks())
{
if (!fgDominate(b1, predBlock))
{
return false;
}
}
return b2->bbPreds != nullptr;
}
if (b1->bbNum > fgDomBBcount)
{
// if b1 is a loop preheader and Succ is its only successor, then all predecessors of
// Succ either are b1 itself or are dominated by Succ. Under these conditions, b1
// dominates b2 if and only if Succ dominates b2 (or if b2 == b1, but we already tested
// for this case)
if (b1->bbFlags & BBF_LOOP_PREHEADER)
{
noway_assert(b1->bbFlags & BBF_INTERNAL);
noway_assert(b1->bbJumpKind == BBJ_NONE);
return fgDominate(b1->bbNext, b2);
}
// unknown dominators; err on the safe side and return false
return false;
}
/* Check if b1 dominates b2 */
unsigned numA = b1->bbNum;
noway_assert(numA <= fgDomBBcount);
unsigned numB = b2->bbNum;
noway_assert(numB <= fgDomBBcount);
// What we want to ask here is basically if A is in the middle of the path from B to the root (the entry node)
// in the dominator tree. Turns out that can be translated as:
//
// A dom B <-> preorder(A) <= preorder(B) && postorder(A) >= postorder(B)
//
// where the equality holds when you ask if A dominates itself.
bool treeDom =
fgDomTreePreOrder[numA] <= fgDomTreePreOrder[numB] && fgDomTreePostOrder[numA] >= fgDomTreePostOrder[numB];
return treeDom;
}
//------------------------------------------------------------------------
// fgReachable: Returns true if block `b1` can reach block `b2`.
//
// Arguments:
// b1, b2 -- Two blocks to compare.
//
// Return Value:
// true if `b1` can reach `b2` via some path. If either b1 or b2 were created after dominators were calculated,
// but the dominator information still exists, try to determine if we can make a statement about
// b1 reaching b2 based on existing reachability information and other information, such as
// predecessor lists.
//
// Assumptions:
// -- Dominators have been calculated (`fgDomsComputed` is true).
// -- Reachability information has been calculated (`fgReachabilitySetsValid` is true).
//
bool Compiler::fgReachable(BasicBlock* b1, BasicBlock* b2)
{
noway_assert(fgDomsComputed);
assert(!fgCheapPredsValid);
//
// If the fgModified flag is false then we made some modifications to
// the flow graph, like adding a new block or changing a conditional branch
// into an unconditional branch.
//
// We can continue to use the dominator and reachable information to
// unmark loops as long as we haven't renumbered the blocks or we aren't
// asking for information about a new block
//
if (b2->bbNum > fgDomBBcount)
{
if (b1 == b2)
{
return true;
}
for (BasicBlock* const predBlock : b2->PredBlocks())
{
if (fgReachable(b1, predBlock))
{
return true;
}
}
return false;
}
if (b1->bbNum > fgDomBBcount)
{
noway_assert(b1->bbJumpKind == BBJ_NONE || b1->bbJumpKind == BBJ_ALWAYS || b1->bbJumpKind == BBJ_COND);
if (b1->bbFallsThrough() && fgReachable(b1->bbNext, b2))
{
return true;
}
if (b1->bbJumpKind == BBJ_ALWAYS || b1->bbJumpKind == BBJ_COND)
{
return fgReachable(b1->bbJumpDest, b2);
}
return false;
}
/* Check if b1 can reach b2 */
assert(fgReachabilitySetsValid);
assert(BasicBlockBitSetTraits::GetSize(this) == fgDomBBcount + 1);
return BlockSetOps::IsMember(this, b2->bbReach, b1->bbNum);
}
//------------------------------------------------------------------------
// fgUpdateChangedFlowGraph: Update changed flow graph information.
//
// If the flow graph has changed, we need to recompute various information if we want to use it again.
//
// Arguments:
// computeDoms -- `true` if we should recompute dominators
//
void Compiler::fgUpdateChangedFlowGraph(const bool computePreds, const bool computeDoms)
{
// We need to clear this so we don't hit an assert calling fgRenumberBlocks().
fgDomsComputed = false;
JITDUMP("\nRenumbering the basic blocks for fgUpdateChangeFlowGraph\n");
fgRenumberBlocks();
if (computePreds) // This condition is only here until all phases don't require it.
{
fgComputePreds();
}
fgComputeEnterBlocksSet();
fgComputeReachabilitySets();
if (computeDoms)
{
fgComputeDoms();
}
}
//------------------------------------------------------------------------
// fgComputeReachabilitySets: Compute the bbReach sets.
//
// This can be called to recompute the bbReach sets after the flow graph changes, such as when the
// number of BasicBlocks change (and thus, the BlockSet epoch changes).
//
// This also sets the BBF_GC_SAFE_POINT flag on blocks.
//
// TODO-Throughput: This algorithm consumes O(n^2) because we're using dense bitsets to
// represent reachability. While this yields O(1) time queries, it bloats the memory usage
// for large code. We can do better if we try to approach reachability by
// computing the strongly connected components of the flow graph. That way we only need
// linear memory to label every block with its SCC.
//
// Assumptions:
// Assumes the predecessor lists are correct.
//
void Compiler::fgComputeReachabilitySets()
{
assert(fgComputePredsDone);
assert(!fgCheapPredsValid);
#ifdef DEBUG
fgReachabilitySetsValid = false;
#endif // DEBUG
for (BasicBlock* const block : Blocks())
{
// Initialize the per-block bbReach sets. It creates a new empty set,
// because the block epoch could change since the previous initialization
// and the old set could have wrong size.
block->bbReach = BlockSetOps::MakeEmpty(this);
/* Mark block as reaching itself */
BlockSetOps::AddElemD(this, block->bbReach, block->bbNum);
}
// Find the reachable blocks. Also, set BBF_GC_SAFE_POINT.
bool change;
BlockSet newReach(BlockSetOps::MakeEmpty(this));
do
{
change = false;
for (BasicBlock* const block : Blocks())
{
BlockSetOps::Assign(this, newReach, block->bbReach);
bool predGcSafe = (block->bbPreds != nullptr); // Do all of our predecessor blocks have a GC safe bit?
for (BasicBlock* const predBlock : block->PredBlocks())
{
/* Union the predecessor's reachability set into newReach */
BlockSetOps::UnionD(this, newReach, predBlock->bbReach);
if (!(predBlock->bbFlags & BBF_GC_SAFE_POINT))
{
predGcSafe = false;
}
}
if (predGcSafe)
{
block->bbFlags |= BBF_GC_SAFE_POINT;
}
if (!BlockSetOps::Equal(this, newReach, block->bbReach))
{
BlockSetOps::Assign(this, block->bbReach, newReach);
change = true;
}
}
} while (change);
#ifdef DEBUG
if (verbose)
{
printf("\nAfter computing reachability sets:\n");
fgDispReach();
}
fgReachabilitySetsValid = true;
#endif // DEBUG
}
//------------------------------------------------------------------------
// fgComputeEnterBlocksSet: Compute the entry blocks set.
//
// Initialize fgEnterBlks to the set of blocks for which we don't have explicit control
// flow edges. These are the entry basic block and each of the EH handler blocks.
// For ARM, also include the BBJ_ALWAYS block of a BBJ_CALLFINALLY/BBJ_ALWAYS pair,
// to avoid creating "retless" calls, since we need the BBJ_ALWAYS for the purpose
// of unwinding, even if the call doesn't return (due to an explicit throw, for example).
//
void Compiler::fgComputeEnterBlocksSet()
{
#ifdef DEBUG
fgEnterBlksSetValid = false;
#endif // DEBUG
fgEnterBlks = BlockSetOps::MakeEmpty(this);
#if defined(FEATURE_EH_FUNCLETS) && defined(TARGET_ARM)
fgAlwaysBlks = BlockSetOps::MakeEmpty(this);
#endif // defined(FEATURE_EH_FUNCLETS) && defined(TARGET_ARM)
/* Now set the entry basic block */
BlockSetOps::AddElemD(this, fgEnterBlks, fgFirstBB->bbNum);
assert(fgFirstBB->bbNum == 1);
if (compHndBBtabCount > 0)
{
/* Also 'or' in the handler basic blocks */
for (EHblkDsc* const HBtab : EHClauses(this))
{
if (HBtab->HasFilter())
{
BlockSetOps::AddElemD(this, fgEnterBlks, HBtab->ebdFilter->bbNum);
}
BlockSetOps::AddElemD(this, fgEnterBlks, HBtab->ebdHndBeg->bbNum);
}
}
#if defined(FEATURE_EH_FUNCLETS) && defined(TARGET_ARM)
// For ARM code, prevent creating retless calls by adding the BBJ_ALWAYS to the "fgAlwaysBlks" list.
for (BasicBlock* const block : Blocks())
{
if (block->bbJumpKind == BBJ_CALLFINALLY)
{
assert(block->isBBCallAlwaysPair());
// Don't remove the BBJ_ALWAYS block that is only here for the unwinder.
BlockSetOps::AddElemD(this, fgAlwaysBlks, block->bbNext->bbNum);
}
}
#endif // defined(FEATURE_EH_FUNCLETS) && defined(TARGET_ARM)
#ifdef DEBUG
if (verbose)
{
printf("Enter blocks: ");
BlockSetOps::Iter iter(this, fgEnterBlks);
unsigned bbNum = 0;
while (iter.NextElem(&bbNum))
{
printf(FMT_BB " ", bbNum);
}
printf("\n");
}
#endif // DEBUG
#ifdef DEBUG
fgEnterBlksSetValid = true;
#endif // DEBUG
}
//------------------------------------------------------------------------
// fgRemoveUnreachableBlocks: Remove unreachable blocks.
//
// Some blocks (marked with BBF_DONT_REMOVE) can't be removed even if unreachable, in which case they
// are converted to `throw` blocks. Internal throw helper blocks and the single return block (if any)
// are never considered unreachable.
//
// Return Value:
// Return true if changes were made that may cause additional blocks to be removable.
//
// Assumptions:
// The reachability sets must be computed and valid.
//
// Notes:
// Sets `fgHasLoops` if there are any loops in the function.
// Sets `BBF_LOOP_HEAD` flag on a block if that block is the target of a backward branch and the block can
// reach the source of the branch.
//
bool Compiler::fgRemoveUnreachableBlocks()
{
assert(!fgCheapPredsValid);
assert(fgReachabilitySetsValid);
bool hasLoops = false;
bool hasUnreachableBlocks = false;
bool changed = false;
/* Record unreachable blocks */
for (BasicBlock* const block : Blocks())
{
/* Internal throw blocks are also reachable */
if (fgIsThrowHlpBlk(block))
{
goto SKIP_BLOCK;
}
else if (block == genReturnBB)
{
// Don't remove statements for the genReturnBB block, as we might have special hookups there.
// For example, <BUGNUM> in VSW 364383, </BUGNUM>
// the profiler hookup needs to have the "void GT_RETURN" statement
// to properly set the info.compProfilerCallback flag.
goto SKIP_BLOCK;
}
else
{
// If any of the entry blocks can reach this block, then we skip it.
if (!BlockSetOps::IsEmptyIntersection(this, fgEnterBlks, block->bbReach))
{
goto SKIP_BLOCK;
}
#if defined(FEATURE_EH_FUNCLETS) && defined(TARGET_ARM)
if (!BlockSetOps::IsEmptyIntersection(this, fgAlwaysBlks, block->bbReach))
{
goto SKIP_BLOCK;
}
#endif // defined(FEATURE_EH_FUNCLETS) && defined(TARGET_ARM)
}
// Remove all the code for the block
fgUnreachableBlock(block);
// Make sure that the block was marked as removed */
noway_assert(block->bbFlags & BBF_REMOVED);
// Some blocks mark the end of trys and catches
// and can't be removed. We convert these into
// empty blocks of type BBJ_THROW
if (block->bbFlags & BBF_DONT_REMOVE)
{
bool bIsBBCallAlwaysPair = block->isBBCallAlwaysPair();
/* Unmark the block as removed, */
/* clear BBF_INTERNAL as well and set BBJ_IMPORTED */
// The successors may be unreachable after this change.
changed |= block->NumSucc() > 0;
block->bbFlags &= ~(BBF_REMOVED | BBF_INTERNAL);
block->bbFlags |= BBF_IMPORTED;
block->bbJumpKind = BBJ_THROW;
block->bbSetRunRarely();
#if defined(FEATURE_EH_FUNCLETS) && defined(TARGET_ARM)
// If this is a <BBJ_CALLFINALLY, BBJ_ALWAYS> pair, we have to clear BBF_FINALLY_TARGET flag on
// the target node (of BBJ_ALWAYS) since BBJ_CALLFINALLY node is getting converted to a BBJ_THROW.
if (bIsBBCallAlwaysPair)
{
noway_assert(block->bbNext->bbJumpKind == BBJ_ALWAYS);
fgClearFinallyTargetBit(block->bbNext->bbJumpDest);
}
#endif // defined(FEATURE_EH_FUNCLETS) && defined(TARGET_ARM)
}
else
{
/* We have to call fgRemoveBlock next */
hasUnreachableBlocks = true;
changed = true;
}
continue;
SKIP_BLOCK:;
if (block->bbJumpKind == BBJ_RETURN)
{
continue;
}
// Set BBF_LOOP_HEAD if we have backwards branches to this block.
unsigned blockNum = block->bbNum;
for (BasicBlock* const predBlock : block->PredBlocks())
{
if (blockNum <= predBlock->bbNum)
{
if (predBlock->bbJumpKind == BBJ_CALLFINALLY)
{
continue;
}
/* If block can reach predBlock then we have a loop head */
if (BlockSetOps::IsMember(this, predBlock->bbReach, blockNum))
{
hasLoops = true;
/* Set the BBF_LOOP_HEAD flag */
block->bbFlags |= BBF_LOOP_HEAD;
break;
}
}
}
}
fgHasLoops = hasLoops;
if (hasUnreachableBlocks)
{
// Now remove the unreachable blocks
for (BasicBlock* block = fgFirstBB; block != nullptr; block = block->bbNext)
{
// If we mark the block with BBF_REMOVED then
// we need to call fgRemovedBlock() on it
if (block->bbFlags & BBF_REMOVED)
{
fgRemoveBlock(block, true);
// When we have a BBJ_CALLFINALLY, BBJ_ALWAYS pair; fgRemoveBlock will remove
// both blocks, so we must advance 1 extra place in the block list
//
if (block->isBBCallAlwaysPair())
{
block = block->bbNext;
}
}
}
}
return changed;
}
//------------------------------------------------------------------------
// fgComputeReachability: Compute the dominator and reachable sets.
//
// Use `fgReachable()` to check reachability, `fgDominate()` to check dominance.
//
// Also, compute the list of return blocks `fgReturnBlocks` and set of enter blocks `fgEnterBlks`.
// Delete unreachable blocks.
//
// Via the call to `fgRemoveUnreachableBlocks`, determine if the flow graph has loops and set 'fgHasLoops'
// accordingly. Set the BBF_LOOP_HEAD flag on the block target of backwards branches.
//
// Assumptions:
// Assumes the predecessor lists are computed and correct.
//
void Compiler::fgComputeReachability()
{
#ifdef DEBUG
if (verbose)
{
printf("*************** In fgComputeReachability\n");
}
fgVerifyHandlerTab();
// Make sure that the predecessor lists are accurate
assert(fgComputePredsDone);
fgDebugCheckBBlist();
#endif // DEBUG
/* Create a list of all BBJ_RETURN blocks. The head of the list is 'fgReturnBlocks'. */
fgReturnBlocks = nullptr;
for (BasicBlock* const block : Blocks())
{
// If this is a BBJ_RETURN block, add it to our list of all BBJ_RETURN blocks. This list is only
// used to find return blocks.
if (block->bbJumpKind == BBJ_RETURN)
{
fgReturnBlocks = new (this, CMK_Reachability) BasicBlockList(block, fgReturnBlocks);
}
}
// Compute reachability and then delete blocks determined to be unreachable. If we delete blocks, we
// need to loop, as that might have caused more blocks to become unreachable. This can happen in the
// case where a call to a finally is unreachable and deleted (maybe the call to the finally is
// preceded by a throw or an infinite loop), making the blocks following the finally unreachable.
// However, all EH entry blocks are considered global entry blocks, causing the blocks following the
// call to the finally to stay rooted, until a second round of reachability is done.
// The dominator algorithm expects that all blocks can be reached from the fgEnterBlks set.
unsigned passNum = 1;
bool changed;
do
{
// Just to be paranoid, avoid infinite loops; fall back to minopts.
if (passNum > 10)
{
noway_assert(!"Too many unreachable block removal loops");
}
// Walk the flow graph, reassign block numbers to keep them in ascending order.
JITDUMP("\nRenumbering the basic blocks for fgComputeReachability pass #%u\n", passNum);
passNum++;
fgRenumberBlocks();
//
// Compute fgEnterBlks
//
fgComputeEnterBlocksSet();
//
// Compute bbReach
//
fgComputeReachabilitySets();
//
// Use reachability information to delete unreachable blocks.
// Also, determine if the flow graph has loops and set 'fgHasLoops' accordingly.
// Set the BBF_LOOP_HEAD flag on the block target of backwards branches.
//
changed = fgRemoveUnreachableBlocks();
} while (changed);
#ifdef DEBUG
if (verbose)
{
printf("\nAfter computing reachability:\n");
fgDispBasicBlocks(verboseTrees);
printf("\n");
}
fgVerifyHandlerTab();
fgDebugCheckBBlist(true);
#endif // DEBUG
//
// Now, compute the dominators
//
fgComputeDoms();
}
//-------------------------------------------------------------
// fgDfsInvPostOrder: Helper function for computing dominance information.
//
// In order to be able to compute dominance, we need to first get a DFS reverse post order sort on the basic flow
// graph for the dominance algorithm to operate correctly. The reason why we need the DFS sort is because we will
// build the dominance sets using the partial order induced by the DFS sorting. With this precondition not
// holding true, the algorithm doesn't work properly.
//
void Compiler::fgDfsInvPostOrder()
{
// NOTE: This algorithm only pays attention to the actual blocks. It ignores the imaginary entry block.
// visited : Once we run the DFS post order sort recursive algorithm, we mark the nodes we visited to avoid
// backtracking.
BlockSet visited(BlockSetOps::MakeEmpty(this));
// We begin by figuring out which basic blocks don't have incoming edges and mark them as
// start nodes. Later on we run the recursive algorithm for each node that we
// mark in this step.
BlockSet_ValRet_T startNodes = fgDomFindStartNodes();
// Make sure fgEnterBlks are still there in startNodes, even if they participate in a loop (i.e., there is
// an incoming edge into the block).
assert(fgEnterBlksSetValid);
BlockSetOps::UnionD(this, startNodes, fgEnterBlks);
assert(BlockSetOps::IsMember(this, startNodes, fgFirstBB->bbNum));
// Call the flowgraph DFS traversal helper.
unsigned postIndex = 1;
for (BasicBlock* const block : Blocks())
{
// If the block has no predecessors, and we haven't already visited it (because it's in fgEnterBlks but also
// reachable from the first block), go ahead and traverse starting from this block.
if (BlockSetOps::IsMember(this, startNodes, block->bbNum) &&
!BlockSetOps::IsMember(this, visited, block->bbNum))
{
fgDfsInvPostOrderHelper(block, visited, &postIndex);
}
}
// After the DFS reverse postorder is completed, we must have visited all the basic blocks.
noway_assert(postIndex == fgBBcount + 1);
noway_assert(fgBBNumMax == fgBBcount);
#ifdef DEBUG
if (0 && verbose)
{
printf("\nAfter doing a post order traversal of the BB graph, this is the ordering:\n");
for (unsigned i = 1; i <= fgBBNumMax; ++i)
{
printf("%02u -> " FMT_BB "\n", i, fgBBInvPostOrder[i]->bbNum);
}
printf("\n");
}
#endif // DEBUG
}
//-------------------------------------------------------------
// fgDomFindStartNodes: Helper for dominance computation to find the start nodes block set.
//
// The start nodes is a set that represents which basic blocks in the flow graph don't have incoming edges.
// We begin assuming everything is a start block and remove any block that is a successor of another.
//
// Returns:
// Block set of start nodes.
//
BlockSet_ValRet_T Compiler::fgDomFindStartNodes()
{
BlockSet startNodes(BlockSetOps::MakeFull(this));
for (BasicBlock* const block : Blocks())
{
for (BasicBlock* const succ : block->Succs(this))
{
BlockSetOps::RemoveElemD(this, startNodes, succ->bbNum);
}
}
#ifdef DEBUG
if (verbose)
{
printf("\nDominator computation start blocks (those blocks with no incoming edges):\n");
BlockSetOps::Iter iter(this, startNodes);
unsigned bbNum = 0;
while (iter.NextElem(&bbNum))
{
printf(FMT_BB " ", bbNum);
}
printf("\n");
}
#endif // DEBUG
return startNodes;
}
//------------------------------------------------------------------------
// fgDfsInvPostOrderHelper: Helper to assign post-order numbers to blocks.
//
// Arguments:
// block - The starting entry block
// visited - The set of visited blocks
// count - Pointer to the Dfs counter
//
// Notes:
// Compute a non-recursive DFS traversal of the flow graph using an
// evaluation stack to assign post-order numbers.
//
void Compiler::fgDfsInvPostOrderHelper(BasicBlock* block, BlockSet& visited, unsigned* count)
{
// Assume we haven't visited this node yet (callers ensure this).
assert(!BlockSetOps::IsMember(this, visited, block->bbNum));
// Allocate a local stack to hold the DFS traversal actions necessary
// to compute pre/post-ordering of the control flowgraph.
ArrayStack<DfsBlockEntry> stack(getAllocator(CMK_ArrayStack));
// Push the first block on the stack to seed the traversal.
stack.Push(DfsBlockEntry(DSS_Pre, block));
// Flag the node we just visited to avoid backtracking.
BlockSetOps::AddElemD(this, visited, block->bbNum);
// The search is terminated once all the actions have been processed.
while (!stack.Empty())
{
DfsBlockEntry current = stack.Pop();
BasicBlock* currentBlock = current.dfsBlock;
if (current.dfsStackState == DSS_Pre)
{
// This is a pre-visit that corresponds to the first time the
// node is encountered in the spanning tree and receives pre-order
// numberings. By pushing the post-action on the stack here we
// are guaranteed to only process it after all of its successors
// pre and post actions are processed.
stack.Push(DfsBlockEntry(DSS_Post, currentBlock));
for (BasicBlock* const succ : currentBlock->Succs(this))
{
// If this is a node we haven't seen before, go ahead and process
if (!BlockSetOps::IsMember(this, visited, succ->bbNum))
{
// Push a pre-visit action for this successor onto the stack and
// mark it as visited in case this block has multiple successors
// to the same node (multi-graph).
stack.Push(DfsBlockEntry(DSS_Pre, succ));
BlockSetOps::AddElemD(this, visited, succ->bbNum);
}
}
}
else
{
// This is a post-visit that corresponds to the last time the
// node is visited in the spanning tree and only happens after
// all descendents in the spanning tree have had pre and post
// actions applied.
assert(current.dfsStackState == DSS_Post);
unsigned invCount = fgBBcount - *count + 1;
assert(1 <= invCount && invCount <= fgBBNumMax);
fgBBInvPostOrder[invCount] = currentBlock;
currentBlock->bbPostOrderNum = invCount;
++(*count);
}
}
}
//------------------------------------------------------------------------
// fgComputeDoms: Computer dominators. Use `fgDominate()` to check dominance.
//
// Compute immediate dominators, the dominator tree and and its pre/post-order traversal numbers.
//
// Also sets BBF_DOMINATED_BY_EXCEPTIONAL_ENTRY flag on blocks dominated by exceptional entry blocks.
//
// Notes:
// Immediate dominator computation is based on "A Simple, Fast Dominance Algorithm"
// by Keith D. Cooper, Timothy J. Harvey, and Ken Kennedy.
//
void Compiler::fgComputeDoms()
{
assert(!fgCheapPredsValid);
#ifdef DEBUG
if (verbose)
{
printf("*************** In fgComputeDoms\n");
}
fgVerifyHandlerTab();
// Make sure that the predecessor lists are accurate.
// Also check that the blocks are properly, densely numbered (so calling fgRenumberBlocks is not necessary).
fgDebugCheckBBlist(true);
// Assert things related to the BlockSet epoch.
assert(fgBBcount == fgBBNumMax);
assert(BasicBlockBitSetTraits::GetSize(this) == fgBBNumMax + 1);
#endif // DEBUG
BlockSet processedBlks(BlockSetOps::MakeEmpty(this));
fgBBInvPostOrder = new (this, CMK_DominatorMemory) BasicBlock*[fgBBNumMax + 1]{};
fgDfsInvPostOrder();
noway_assert(fgBBInvPostOrder[0] == nullptr);
// flRoot and bbRoot represent an imaginary unique entry point in the flow graph.
// All the orphaned EH blocks and fgFirstBB will temporarily have its predecessors list
// (with bbRoot as the only basic block in it) set as flRoot.
// Later on, we clear their predecessors and let them to be nullptr again.
// Since we number basic blocks starting at one, the imaginary entry block is conveniently numbered as zero.
BasicBlock bbRoot;
bbRoot.bbPreds = nullptr;
bbRoot.bbNum = 0;
bbRoot.bbIDom = &bbRoot;
bbRoot.bbPostOrderNum = 0;
bbRoot.bbFlags = BBF_EMPTY;
flowList flRoot(&bbRoot, nullptr);
fgBBInvPostOrder[0] = &bbRoot;
// Mark both bbRoot and fgFirstBB processed
BlockSetOps::AddElemD(this, processedBlks, 0); // bbRoot == block #0
BlockSetOps::AddElemD(this, processedBlks, 1); // fgFirstBB == block #1
assert(fgFirstBB->bbNum == 1);
// Special case fgFirstBB to say its IDom is bbRoot.
fgFirstBB->bbIDom = &bbRoot;
BasicBlock* block = nullptr;
for (block = fgFirstBB->bbNext; block != nullptr; block = block->bbNext)
{
// If any basic block has no predecessors then we flag it as processed and temporarily
// mark its precedessor list to be flRoot. This makes the flowgraph connected,
// a precondition that is needed by the dominance algorithm to operate properly.
if (block->bbPreds == nullptr)
{
block->bbPreds = &flRoot;
block->bbIDom = &bbRoot;
BlockSetOps::AddElemD(this, processedBlks, block->bbNum);
}
else
{
block->bbIDom = nullptr;
}
}
// Mark the EH blocks as entry blocks and also flag them as processed.
if (compHndBBtabCount > 0)
{
for (EHblkDsc* const HBtab : EHClauses(this))
{
if (HBtab->HasFilter())
{
HBtab->ebdFilter->bbIDom = &bbRoot;
BlockSetOps::AddElemD(this, processedBlks, HBtab->ebdFilter->bbNum);
}
HBtab->ebdHndBeg->bbIDom = &bbRoot;
BlockSetOps::AddElemD(this, processedBlks, HBtab->ebdHndBeg->bbNum);
}
}
// Now proceed to compute the immediate dominators for each basic block.
bool changed = true;
while (changed)
{
changed = false;
// Process each actual block; don't process the imaginary predecessor block.
for (unsigned i = 1; i <= fgBBNumMax; ++i)
{
flowList* first = nullptr;
BasicBlock* newidom = nullptr;
block = fgBBInvPostOrder[i];
// If we have a block that has bbRoot as its bbIDom
// it means we flag it as processed and as an entry block so
// in this case we're all set.
if (block->bbIDom == &bbRoot)
{
continue;
}
// Pick up the first processed predecesor of the current block.
for (first = block->bbPreds; first != nullptr; first = first->flNext)
{
if (BlockSetOps::IsMember(this, processedBlks, first->getBlock()->bbNum))
{
break;
}
}
noway_assert(first != nullptr);
// We assume the first processed predecessor will be the
// immediate dominator and then compute the forward flow analysis.
newidom = first->getBlock();
for (flowList* p = block->bbPreds; p != nullptr; p = p->flNext)
{
if (p->getBlock() == first->getBlock())
{
continue;
}
if (p->getBlock()->bbIDom != nullptr)
{
// fgIntersectDom is basically the set intersection between
// the dominance sets of the new IDom and the current predecessor
// Since the nodes are ordered in DFS inverse post order and
// IDom induces a tree, fgIntersectDom actually computes
// the lowest common ancestor in the dominator tree.
newidom = fgIntersectDom(p->getBlock(), newidom);
}
}
// If the Immediate dominator changed, assign the new one
// to the current working basic block.
if (block->bbIDom != newidom)
{
noway_assert(newidom != nullptr);
block->bbIDom = newidom;
changed = true;
}
BlockSetOps::AddElemD(this, processedBlks, block->bbNum);
}
}
// As stated before, once we have computed immediate dominance we need to clear
// all the basic blocks whose predecessor list was set to flRoot. This
// reverts that and leaves the blocks the same as before.
for (BasicBlock* const block : Blocks())
{
if (block->bbPreds == &flRoot)
{
block->bbPreds = nullptr;
}
}
fgCompDominatedByExceptionalEntryBlocks();
#ifdef DEBUG
if (verbose)
{
fgDispDoms();
}
#endif
fgNumberDomTree(fgBuildDomTree());
fgModified = false;
fgDomBBcount = fgBBcount;
assert(fgBBcount == fgBBNumMax);
assert(BasicBlockBitSetTraits::GetSize(this) == fgDomBBcount + 1);
fgDomsComputed = true;
}
//------------------------------------------------------------------------
// fgBuildDomTree: Build the dominator tree for the current flowgraph.
//
// Returns:
// An array of dominator tree nodes, indexed by BasicBlock::bbNum.
//
// Notes:
// Immediate dominators must have already been computed in BasicBlock::bbIDom
// before calling this.
//
DomTreeNode* Compiler::fgBuildDomTree()
{
JITDUMP("\nInside fgBuildDomTree\n");
unsigned bbArraySize = fgBBNumMax + 1;
DomTreeNode* domTree = new (this, CMK_DominatorMemory) DomTreeNode[bbArraySize]{};
BasicBlock* imaginaryRoot = fgFirstBB->bbIDom;
if (imaginaryRoot != nullptr)