forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptimizer.cpp
6076 lines (5301 loc) · 217 KB
/
optimizer.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.
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XX
XX Optimizer XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
/*****************************************************************************/
void Compiler::optInit()
{
fgHasLoops = false;
optLoopsRequirePreHeaders = false;
optNumNaturalLoopsFound = 0;
#ifdef DEBUG
loopAlignCandidates = 0;
loopsAligned = 0;
#endif
/* Keep track of the number of calls and indirect calls made by this method */
optCallCount = 0;
optIndirectCallCount = 0;
optNativeCallCount = 0;
optAssertionCount = 0;
optAssertionDep = nullptr;
optCSEstart = BAD_VAR_NUM;
optCSEcount = 0;
optCSECandidateCount = 0;
optCSEattempt = 0;
optCSEheuristic = nullptr;
}
DataFlow::DataFlow(Compiler* pCompiler) : m_pCompiler(pCompiler)
{
}
//------------------------------------------------------------------------
// optSetBlockWeights: adjust block weights, as follows:
// 1. A block that is not reachable from the entry block is marked "run rarely".
// 2. If we're not using profile weights, then any block with a non-zero weight
// that doesn't dominate all the return blocks has its weight dropped in half
// (but only if the first block *does* dominate all the returns).
//
// Returns:
// Suitable phase status
//
// Notes:
// Depends on dominators, and fgReturnBlocks being set.
//
PhaseStatus Compiler::optSetBlockWeights()
{
noway_assert(opts.OptimizationEnabled());
assert(m_domTree != nullptr);
assert(fgReturnBlocksComputed);
bool madeChanges = false;
bool firstBBDominatesAllReturns = true;
const bool usingProfileWeights = fgIsUsingProfileWeights();
// TODO-Quirk: Previously, this code ran on a dominator tree based only on
// regular flow. This meant that all handlers were not considered to be
// dominated by fgFirstBB. When those handlers could reach a return
// block that return was also not considered to be dominated by fgFirstBB.
// In practice the code below would then not make any changes for those
// functions. We emulate that behavior here.
for (EHblkDsc* eh : EHClauses(this))
{
BasicBlock* flowBlock = eh->ExFlowBlock();
for (BasicBlockList* retBlocks = fgReturnBlocks; retBlocks != nullptr; retBlocks = retBlocks->next)
{
if (m_dfsTree->Contains(flowBlock) && m_reachabilitySets->CanReach(flowBlock, retBlocks->block))
{
firstBBDominatesAllReturns = false;
break;
}
}
if (!firstBBDominatesAllReturns)
{
break;
}
}
for (BasicBlock* const block : Blocks())
{
// Blocks that can't be reached via the first block are rarely executed
if (!m_reachabilitySets->CanReach(fgFirstBB, block) && !block->isRunRarely())
{
madeChanges = true;
block->bbSetRunRarely();
}
if (!usingProfileWeights && firstBBDominatesAllReturns)
{
// If the weight is already zero (and thus rarely run), there's no point scaling it.
if (block->bbWeight != BB_ZERO_WEIGHT)
{
// If the block dominates all return blocks, leave the weight alone. Otherwise,
// scale the weight by 0.5 as a heuristic that some other path gets some of the dynamic flow.
// Note that `optScaleLoopBlocks` has a similar heuristic for loop blocks that don't dominate
// their loop back edge.
bool blockDominatesAllReturns = true; // Assume that we will dominate
for (BasicBlockList* retBlocks = fgReturnBlocks; retBlocks != nullptr; retBlocks = retBlocks->next)
{
// TODO-Quirk: Returns that are unreachable can just be ignored.
if (!m_dfsTree->Contains(retBlocks->block) || !m_domTree->Dominates(block, retBlocks->block))
{
blockDominatesAllReturns = false;
break;
}
}
if (block == fgFirstBB)
{
firstBBDominatesAllReturns = blockDominatesAllReturns;
// Don't scale the weight of the first block, since it is guaranteed to execute.
// If the first block does not dominate all the returns, we won't scale any of the function's
// block weights.
}
else
{
// If we are not using profile weight then we lower the weight
// of blocks that do not dominate a return block
//
if (!blockDominatesAllReturns)
{
madeChanges = true;
// TODO-Cleanup: we should use:
// block->scaleBBWeight(0.5);
// since we are inheriting "from ourselves", but that leads to asm diffs due to minutely
// different floating-point value in the calculation, and some code that compares weights
// for equality.
block->inheritWeightPercentage(block, 50);
}
}
}
}
}
return madeChanges ? PhaseStatus::MODIFIED_EVERYTHING : PhaseStatus::MODIFIED_NOTHING;
}
//------------------------------------------------------------------------
// optScaleLoopBlocks: Scale the weight of loop blocks from 'begBlk' to 'endBlk'.
//
// Arguments:
// begBlk - first block of range. Must be marked as a loop head (BBF_LOOP_HEAD).
// endBlk - last block of range (inclusive). Must be reachable from `begBlk`.
//
// Operation:
// Calculate the 'loop weight'. This is the amount to scale the weight of each block in the loop.
// Our heuristic is that loops are weighted eight times more than straight-line code
// (scale factor is BB_LOOP_WEIGHT_SCALE). If the loops are all properly formed this gives us these weights:
//
// 1 -- non-loop basic block
// 8 -- single loop nesting
// 64 -- double loop nesting
// 512 -- triple loop nesting
//
void Compiler::optScaleLoopBlocks(BasicBlock* begBlk, BasicBlock* endBlk)
{
noway_assert(begBlk->bbNum <= endBlk->bbNum);
noway_assert(begBlk->isLoopHead());
noway_assert(m_reachabilitySets->CanReach(begBlk, endBlk));
noway_assert(!opts.MinOpts());
#ifdef DEBUG
if (verbose)
{
printf("\nMarking a loop from " FMT_BB " to " FMT_BB, begBlk->bbNum, endBlk->bbNum);
}
#endif
// Build list of back edges for block begBlk.
FlowEdge* backedgeList = nullptr;
for (BasicBlock* const predBlock : begBlk->PredBlocks())
{
// Is this a back edge?
if (predBlock->bbNum >= begBlk->bbNum)
{
backedgeList = new (this, CMK_FlowEdge) FlowEdge(predBlock, backedgeList);
#if MEASURE_BLOCK_SIZE
genFlowNodeCnt += 1;
genFlowNodeSize += sizeof(FlowEdge);
#endif // MEASURE_BLOCK_SIZE
}
}
// At least one backedge must have been found (the one from endBlk).
noway_assert(backedgeList);
auto reportBlockWeight = [&](BasicBlock* blk, const char* message) {
#ifdef DEBUG
if (verbose)
{
printf("\n " FMT_BB "(wt=" FMT_WT ")%s", blk->bbNum, blk->getBBWeight(this), message);
}
#endif // DEBUG
};
for (BasicBlock* const curBlk : BasicBlockRangeList(begBlk, endBlk))
{
// Don't change the block weight if it came from profile data.
if (curBlk->hasProfileWeight() && fgHaveProfileData())
{
reportBlockWeight(curBlk, "; unchanged: has profile weight");
continue;
}
// Don't change the block weight if it's known to be rarely run.
if (curBlk->isRunRarely())
{
reportBlockWeight(curBlk, "; unchanged: run rarely");
continue;
}
// For curBlk to be part of a loop that starts at begBlk, curBlk must be reachable from begBlk and
// (since this is a loop) begBlk must likewise be reachable from curBlk.
if (m_reachabilitySets->CanReach(curBlk, begBlk) && m_reachabilitySets->CanReach(begBlk, curBlk))
{
// If `curBlk` reaches any of the back edge blocks we set `reachable`.
// If `curBlk` dominates any of the back edge blocks we set `dominates`.
bool reachable = false;
bool dominates = false;
for (FlowEdge* tmp = backedgeList; tmp != nullptr; tmp = tmp->getNextPredEdge())
{
BasicBlock* backedge = tmp->getSourceBlock();
reachable |= m_reachabilitySets->CanReach(curBlk, backedge);
dominates |= m_domTree->Dominates(curBlk, backedge);
if (dominates && reachable)
{
// No need to keep looking; we've already found all the info we need.
break;
}
}
if (reachable)
{
// If the block has BB_ZERO_WEIGHT, then it should be marked as rarely run, and skipped, above.
noway_assert(curBlk->bbWeight > BB_ZERO_WEIGHT);
weight_t scale = BB_LOOP_WEIGHT_SCALE;
if (!dominates)
{
// If `curBlk` reaches but doesn't dominate any back edge to `endBlk` then there must be at least
// some other path to `endBlk`, so don't give `curBlk` all the execution weight.
scale = scale / 2;
}
curBlk->scaleBBWeight(scale);
reportBlockWeight(curBlk, "");
}
else
{
reportBlockWeight(curBlk, "; unchanged: back edge unreachable");
}
}
else
{
reportBlockWeight(curBlk, "; unchanged: block not in loop");
}
}
}
//----------------------------------------------------------------------------------
// optIsLoopIncrTree: Check if loop is a tree of form v = v op const.
//
// Arguments:
// incr - The incr tree to be checked.
//
// Return Value:
// iterVar local num if the iterVar is found, otherwise BAD_VAR_NUM.
//
unsigned Compiler::optIsLoopIncrTree(GenTree* incr)
{
GenTree* incrVal;
genTreeOps updateOper;
unsigned iterVar = incr->IsLclVarUpdateTree(&incrVal, &updateOper);
if (iterVar != BAD_VAR_NUM)
{
// We have v = v op y type node.
switch (updateOper)
{
case GT_ADD:
case GT_SUB:
case GT_MUL:
case GT_RSH:
case GT_LSH:
break;
default:
return BAD_VAR_NUM;
}
// Increment should be by a const int.
// TODO-CQ: CLONE: allow variable increments.
if ((incrVal->gtOper != GT_CNS_INT) || (incrVal->TypeGet() != TYP_INT))
{
return BAD_VAR_NUM;
}
}
return iterVar;
}
//----------------------------------------------------------------------------------
// optIsLoopTestEvalIntoTemp:
// Pattern match if the test tree is computed into a tmp
// and the "tmp" is used as jump condition for loop termination.
//
// Arguments:
// testStmt - is the JTRUE statement that is of the form: jmpTrue (Vtmp != 0)
// where Vtmp contains the actual loop test result.
// newTestStmt - contains the statement that is the actual test stmt involving
// the loop iterator.
//
// Return Value:
// Returns true if a new test tree can be obtained.
//
// Operation:
// Scan if the current stmt is a jtrue with (Vtmp != 0) as condition
// Then returns the rhs for def of Vtmp as the "test" node.
//
// Note:
// This method just retrieves what it thinks is the "test" node,
// the callers are expected to verify that "iterVar" is used in the test.
//
bool Compiler::optIsLoopTestEvalIntoTemp(Statement* testStmt, Statement** newTestStmt)
{
GenTree* test = testStmt->GetRootNode();
if (test->gtOper != GT_JTRUE)
{
return false;
}
GenTree* relop = test->gtGetOp1();
noway_assert(relop->OperIsCompare());
GenTree* opr1 = relop->AsOp()->gtOp1;
GenTree* opr2 = relop->AsOp()->gtOp2;
// Make sure we have jtrue (vtmp != 0)
if ((relop->OperGet() == GT_NE) && (opr1->OperGet() == GT_LCL_VAR) && (opr2->OperGet() == GT_CNS_INT) &&
opr2->IsIntegralConst(0))
{
// Get the previous statement to get the def (rhs) of Vtmp to see
// if the "test" is evaluated into Vtmp.
Statement* prevStmt = testStmt->GetPrevStmt();
if (prevStmt == nullptr)
{
return false;
}
GenTree* tree = prevStmt->GetRootNode();
if (tree->OperIs(GT_STORE_LCL_VAR) && (tree->AsLclVar()->GetLclNum() == opr1->AsLclVar()->GetLclNum()) &&
tree->AsLclVar()->Data()->OperIsCompare())
{
*newTestStmt = prevStmt;
return true;
}
}
return false;
}
//----------------------------------------------------------------------------------
// optExtractInitTestIncr:
// Extract the "init", "test" and "incr" nodes of the loop.
//
// Arguments:
// pInitBlock - [IN/OUT] *pInitBlock is the loop head block on entry, and is set to the initBlock on exit,
// if `**ppInit` is non-null.
// cond - A BBJ_COND block that exits the loop
// header - Loop header block
// ppInit - [out] The init stmt of the loop if found.
// ppTest - [out] The test stmt of the loop if found.
// ppIncr - [out] The incr stmt of the loop if found.
//
// Return Value:
// The results are put in "ppInit", "ppTest" and "ppIncr" if the method
// returns true. Returns false if the information can't be extracted.
// Extracting the `init` is optional; if one is not found, *ppInit is set
// to nullptr. Return value will never be false if `init` is not found.
//
// Operation:
// Check if the "test" stmt is last stmt in an exiting BBJ_COND block of the loop. Try to find the "incr" stmt.
// Check previous stmt of "test" to get the "incr" stmt.
//
// Note:
// This method just retrieves what it thinks is the "test" node,
// the callers are expected to verify that "iterVar" is used in the test.
//
bool Compiler::optExtractInitTestIncr(
BasicBlock** pInitBlock, BasicBlock* cond, BasicBlock* header, GenTree** ppInit, GenTree** ppTest, GenTree** ppIncr)
{
assert(pInitBlock != nullptr);
assert(ppInit != nullptr);
assert(ppTest != nullptr);
assert(ppIncr != nullptr);
// Check if last two statements in the loop body are the increment of the iterator
// and the loop termination test.
noway_assert(cond->bbStmtList != nullptr);
Statement* testStmt = cond->lastStmt();
noway_assert(testStmt != nullptr && testStmt->GetNextStmt() == nullptr);
Statement* newTestStmt;
if (optIsLoopTestEvalIntoTemp(testStmt, &newTestStmt))
{
testStmt = newTestStmt;
}
// Check if we have the incr stmt before the test stmt, if we don't,
// check if incr is part of the loop "header".
Statement* incrStmt = testStmt->GetPrevStmt();
// If we've added profile instrumentation, we may need to skip past a BB counter update.
//
if (opts.jitFlags->IsSet(JitFlags::JIT_FLAG_BBINSTR) && (incrStmt != nullptr) &&
incrStmt->GetRootNode()->IsBlockProfileUpdate())
{
incrStmt = incrStmt->GetPrevStmt();
}
if (incrStmt == nullptr || (optIsLoopIncrTree(incrStmt->GetRootNode()) == BAD_VAR_NUM))
{
return false;
}
assert(testStmt != incrStmt);
// Find the last statement in the loop pre-header which we expect to be the initialization of
// the loop iterator.
BasicBlock* initBlock = *pInitBlock;
Statement* phdrStmt = initBlock->firstStmt();
if (phdrStmt == nullptr)
{
// When we build the loops, we canonicalize by introducing loop pre-headers for all loops.
// If we are rebuilding the loops, we would already have the pre-header block introduced
// the first time, which might be empty if no hoisting has yet occurred. In this case, look a
// little harder for the possible loop initialization statement.
if (initBlock->KindIs(BBJ_ALWAYS) && initBlock->TargetIs(header))
{
BasicBlock* uniquePred = initBlock->GetUniquePred(this);
if (uniquePred != nullptr)
{
initBlock = uniquePred;
phdrStmt = initBlock->firstStmt();
}
}
}
if (phdrStmt != nullptr)
{
Statement* initStmt = phdrStmt->GetPrevStmt();
noway_assert(initStmt != nullptr && (initStmt->GetNextStmt() == nullptr));
// If it is a duplicated loop condition, skip it.
if (initStmt->GetRootNode()->OperIs(GT_JTRUE))
{
bool doGetPrev = true;
#ifdef DEBUG
if (opts.optRepeat)
{
// Previous optimization passes may have inserted compiler-generated
// statements other than duplicated loop conditions.
doGetPrev = (initStmt->GetPrevStmt() != nullptr);
}
#endif // DEBUG
if (doGetPrev)
{
initStmt = initStmt->GetPrevStmt();
}
noway_assert(initStmt != nullptr);
}
*ppInit = initStmt->GetRootNode();
*pInitBlock = initBlock;
}
else
{
*ppInit = nullptr;
}
*ppTest = testStmt->GetRootNode();
*ppIncr = incrStmt->GetRootNode();
return true;
}
#ifdef DEBUG
void Compiler::optCheckPreds()
{
for (BasicBlock* const block : Blocks())
{
for (BasicBlock* const predBlock : block->PredBlocks())
{
// make sure this pred is part of the BB list
BasicBlock* bb;
for (bb = fgFirstBB; bb; bb = bb->Next())
{
if (bb == predBlock)
{
break;
}
}
noway_assert(bb);
switch (bb->GetKind())
{
case BBJ_COND:
if (bb->TrueTargetIs(block))
{
break;
}
noway_assert(bb->FalseTargetIs(block));
break;
case BBJ_EHFILTERRET:
case BBJ_ALWAYS:
case BBJ_EHCATCHRET:
noway_assert(bb->TargetIs(block));
break;
default:
break;
}
}
}
}
#endif // DEBUG
//------------------------------------------------------------------------
// optRedirectBlock: Replace the branch successors of a block based on a block map.
//
// Updates the successors of `blk`: if `blk2` is a branch successor of `blk`, and there is a mapping
// for `blk2->blk3` in `redirectMap`, change `blk` so that `blk3` is this branch successor.
//
// Arguments:
// blk - block to redirect
// redirectMap - block->block map specifying how the `blk` target will be redirected.
// predOption - specifies how to update the pred lists
//
// Notes:
// Pred lists for successors of `blk` may be changed, depending on `predOption`.
//
void Compiler::optRedirectBlock(BasicBlock* blk, BlockToBlockMap* redirectMap, RedirectBlockOption predOption)
{
const bool updatePreds = (predOption == RedirectBlockOption::UpdatePredLists);
const bool addPreds = (predOption == RedirectBlockOption::AddToPredLists);
BasicBlock* newJumpDest = nullptr;
switch (blk->GetKind())
{
case BBJ_THROW:
case BBJ_RETURN:
case BBJ_EHFILTERRET:
case BBJ_EHFAULTRET:
case BBJ_EHCATCHRET:
// These have no jump destination to update.
break;
case BBJ_CALLFINALLY:
if (addPreds && blk->bbFallsThrough())
{
fgAddRefPred(blk->Next(), blk);
}
FALLTHROUGH;
case BBJ_ALWAYS:
case BBJ_LEAVE:
case BBJ_CALLFINALLYRET:
// All of these have a single jump destination to update.
if (redirectMap->Lookup(blk->GetTarget(), &newJumpDest))
{
if (updatePreds)
{
fgRemoveRefPred(blk->GetTarget(), blk);
}
blk->SetTarget(newJumpDest);
if (updatePreds || addPreds)
{
fgAddRefPred(newJumpDest, blk);
}
}
else if (addPreds)
{
fgAddRefPred(blk->GetTarget(), blk);
}
break;
case BBJ_COND:
// Update jump taken when condition is true
if (redirectMap->Lookup(blk->GetTrueTarget(), &newJumpDest))
{
if (updatePreds)
{
fgRemoveRefPred(blk->GetTrueTarget(), blk);
}
blk->SetTrueTarget(newJumpDest);
if (updatePreds || addPreds)
{
fgAddRefPred(newJumpDest, blk);
}
}
else if (addPreds)
{
fgAddRefPred(blk->GetTrueTarget(), blk);
}
// Update jump taken when condition is false
if (redirectMap->Lookup(blk->GetFalseTarget(), &newJumpDest))
{
if (updatePreds)
{
fgRemoveRefPred(blk->GetFalseTarget(), blk);
}
blk->SetFalseTarget(newJumpDest);
if (updatePreds || addPreds)
{
fgAddRefPred(newJumpDest, blk);
}
}
else if (addPreds)
{
fgAddRefPred(blk->GetFalseTarget(), blk);
}
break;
case BBJ_EHFINALLYRET:
{
BBehfDesc* ehfDesc = blk->GetEhfTargets();
BasicBlock* newSucc = nullptr;
for (unsigned i = 0; i < ehfDesc->bbeCount; i++)
{
BasicBlock* const succ = ehfDesc->bbeSuccs[i];
if (redirectMap->Lookup(succ, &newSucc))
{
if (updatePreds)
{
fgRemoveRefPred(succ, blk);
}
if (updatePreds || addPreds)
{
fgAddRefPred(newSucc, blk);
}
ehfDesc->bbeSuccs[i] = newSucc;
}
else if (addPreds)
{
fgAddRefPred(succ, blk);
}
}
}
break;
case BBJ_SWITCH:
{
bool redirected = false;
for (unsigned i = 0; i < blk->GetSwitchTargets()->bbsCount; i++)
{
BasicBlock* const switchDest = blk->GetSwitchTargets()->bbsDstTab[i];
if (redirectMap->Lookup(switchDest, &newJumpDest))
{
if (updatePreds)
{
fgRemoveRefPred(switchDest, blk);
}
if (updatePreds || addPreds)
{
fgAddRefPred(newJumpDest, blk);
}
blk->GetSwitchTargets()->bbsDstTab[i] = newJumpDest;
redirected = true;
}
else if (addPreds)
{
fgAddRefPred(switchDest, blk);
}
}
// If any redirections happened, invalidate the switch table map for the switch.
if (redirected)
{
// Don't create a new map just to try to remove an entry.
BlockToSwitchDescMap* switchMap = GetSwitchDescMap(/* createIfNull */ false);
if (switchMap != nullptr)
{
switchMap->Remove(blk);
}
}
}
break;
default:
unreached();
}
}
//-----------------------------------------------------------------------------
// optIterSmallOverflow: Helper for loop unrolling. Determine if "i += const" will
// cause an overflow exception for the small types.
//
// Arguments:
// iterAtExit - iteration constant at loop exit
// incrType - type of increment
//
// Returns:
// true if overflow
//
// static
bool Compiler::optIterSmallOverflow(int iterAtExit, var_types incrType)
{
int type_MAX;
switch (incrType)
{
case TYP_BYTE:
type_MAX = SCHAR_MAX;
break;
case TYP_UBYTE:
type_MAX = UCHAR_MAX;
break;
case TYP_SHORT:
type_MAX = SHRT_MAX;
break;
case TYP_USHORT:
type_MAX = USHRT_MAX;
break;
case TYP_UINT: // Detected by checking for 32bit ....
case TYP_INT:
return false; // ... overflow same as done for TYP_INT
default:
NO_WAY("Bad type");
}
if (iterAtExit > type_MAX)
{
return true;
}
else
{
return false;
}
}
//-----------------------------------------------------------------------------
// optIterSmallUnderflow: Helper for loop unrolling. Determine if "i -= const" will
// cause an underflow exception for the small types.
//
// Arguments:
// iterAtExit - iteration constant at loop exit
// decrType - type of decrement
//
// Returns:
// true if overflow
//
// static
bool Compiler::optIterSmallUnderflow(int iterAtExit, var_types decrType)
{
int type_MIN;
switch (decrType)
{
case TYP_BYTE:
type_MIN = SCHAR_MIN;
break;
case TYP_SHORT:
type_MIN = SHRT_MIN;
break;
case TYP_UBYTE:
type_MIN = 0;
break;
case TYP_USHORT:
type_MIN = 0;
break;
case TYP_UINT: // Detected by checking for 32bit ....
case TYP_INT:
return false; // ... underflow same as done for TYP_INT
default:
NO_WAY("Bad type");
}
if (iterAtExit < type_MIN)
{
return true;
}
else
{
return false;
}
}
//-----------------------------------------------------------------------------
// optComputeLoopRep: Helper for loop unrolling. Computes the number of times
// the test block of a loop is executed.
//
// Arguments:
// constInit - loop constant initial value
// constLimit - loop constant limit
// iterInc - loop iteration increment
// iterOper - loop iteration increment operator (ADD, SUB, etc.)
// iterOperType - iteration operator type
// testOper - type of loop test (i.e. GT_LE, GT_GE, etc.)
// unsTest - true if test is unsigned
// iterCount - *iterCount is set to the iteration count, if the function returns `true`
//
// Returns:
// true if the loop has a constant repetition count, false if that cannot be proven
//
bool Compiler::optComputeLoopRep(int constInit,
int constLimit,
int iterInc,
genTreeOps iterOper,
var_types iterOperType,
genTreeOps testOper,
bool unsTest,
unsigned* iterCount)
{
noway_assert(genActualType(iterOperType) == TYP_INT);
__int64 constInitX;
__int64 constLimitX;
unsigned loopCount;
int iterSign;
// Using this, we can just do a signed comparison with other 32 bit values.
if (unsTest)
{
constLimitX = (unsigned int)constLimit;
}
else
{
constLimitX = (signed int)constLimit;
}
switch (iterOperType)
{
// For small types, the iteration operator will narrow these values if big
#define INIT_ITER_BY_TYPE(type) \
constInitX = (type)constInit; \
iterInc = (type)iterInc;
case TYP_BYTE:
INIT_ITER_BY_TYPE(signed char);
break;
case TYP_UBYTE:
INIT_ITER_BY_TYPE(unsigned char);
break;
case TYP_SHORT:
INIT_ITER_BY_TYPE(signed short);
break;
case TYP_USHORT:
INIT_ITER_BY_TYPE(unsigned short);
break;
// For the big types, 32 bit arithmetic is performed
case TYP_INT:
if (unsTest)
{
constInitX = (unsigned int)constInit;
}
else
{
constInitX = (signed int)constInit;
}
break;
default:
noway_assert(!"Bad type");
NO_WAY("Bad type");
}
// If iterInc is zero we have an infinite loop.
if (iterInc == 0)
{
return false;
}
iterSign = (iterInc > 0) ? +1 : -1;
loopCount = 0;
// bail if count is based on wrap-around math
if (iterInc > 0)
{
if (constLimitX < constInitX)
{
return false;
}
}
else if (constLimitX > constInitX)
{
return false;
}
// Compute the number of repetitions.
switch (testOper)
{
__int64 iterAtExitX;
case GT_EQ:
// Something like "for (i=init; i == lim; i++)" doesn't make any sense.
return false;
case GT_NE:
// Consider: "for (i = init; i != lim; i += const)"
// This is tricky since it may have a constant number of iterations or loop forever.
// We have to compute "(lim - init) mod iterInc" to see if it is zero.
// If "mod iterInc" is not zero then the limit test will miss and a wrap will occur
// which is probably not what the end user wanted, but it is legal.
if (iterInc > 0)
{
// Stepping by one, i.e. Mod with 1 is always zero.
if (iterInc != 1)
{
if (((constLimitX - constInitX) % iterInc) != 0)
{
return false;
}
}
}
else
{
// Stepping by -1, i.e. Mod with 1 is always zero.
if (iterInc != -1)
{
if (((constInitX - constLimitX) % (-iterInc)) != 0)
{
return false;
}
}
}
switch (iterOper)
{
case GT_SUB:
iterInc = -iterInc;
FALLTHROUGH;
case GT_ADD:
if (constInitX != constLimitX)
{
loopCount += (unsigned)((constLimitX - constInitX - iterSign) / iterInc) + 1;
}
iterAtExitX = (int)(constInitX + iterInc * (int)loopCount);
if (unsTest)
{
iterAtExitX = (unsigned)iterAtExitX;
}
// Check if iteration incr will cause overflow for small types
if (optIterSmallOverflow((int)iterAtExitX, iterOperType))
{
return false;
}
// iterator with 32bit overflow. Bad for TYP_(U)INT
if (iterAtExitX < constLimitX)
{
return false;
}
*iterCount = loopCount;
return true;
case GT_MUL:
case GT_DIV: