-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
optimizer.cpp
9535 lines (8216 loc) · 327 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
#pragma warning(disable : 4701)
#endif
/*****************************************************************************/
void Compiler::optInit()
{
optLoopsMarked = false;
fgHasLoops = false;
/* Initialize the # of tracked loops to 0 */
optLoopCount = 0;
optLoopTable = nullptr;
/* Keep track of the number of calls and indirect calls made by this method */
optCallCount = 0;
optIndirectCallCount = 0;
optNativeCallCount = 0;
optAssertionCount = 0;
optAssertionDep = nullptr;
#if FEATURE_ANYCSE
optCSECandidateTotal = 0;
optCSEstart = UINT_MAX;
optCSEcount = 0;
#endif // FEATURE_ANYCSE
}
DataFlow::DataFlow(Compiler* pCompiler) : m_pCompiler(pCompiler)
{
}
/*****************************************************************************
*
*/
void Compiler::optSetBlockWeights()
{
noway_assert(opts.OptimizationEnabled());
assert(fgDomsComputed);
#ifdef DEBUG
bool changed = false;
#endif
bool firstBBdomsRets = true;
BasicBlock* block;
for (block = fgFirstBB; (block != nullptr); block = block->bbNext)
{
/* Blocks that can't be reached via the first block are rarely executed */
if (!fgReachable(fgFirstBB, block))
{
block->bbSetRunRarely();
}
if (block->bbWeight != BB_ZERO_WEIGHT)
{
// Calculate our bbWeight:
//
// o BB_UNITY_WEIGHT if we dominate all BBJ_RETURN blocks
// o otherwise BB_UNITY_WEIGHT / 2
//
bool domsRets = true; // Assume that we will dominate
for (BasicBlockList* retBlocks = fgReturnBlocks; retBlocks != nullptr; retBlocks = retBlocks->next)
{
if (!fgDominate(block, retBlocks->block))
{
domsRets = false;
break;
}
}
if (block == fgFirstBB)
{
firstBBdomsRets = domsRets;
}
// If we are not using profile weight then we lower the weight
// of blocks that do not dominate a return block
//
if (firstBBdomsRets && (fgIsUsingProfileWeights() == false) && (domsRets == false))
{
#if DEBUG
changed = true;
#endif
block->modifyBBWeight(block->bbWeight / 2);
noway_assert(block->bbWeight);
}
}
}
#if DEBUG
if (changed && verbose)
{
printf("\nAfter optSetBlockWeights:\n");
fgDispBasicBlocks();
printf("\n");
}
/* Check that the flowgraph data (bbNum, bbRefs, bbPreds) is up-to-date */
fgDebugCheckBBlist();
#endif
}
/*****************************************************************************
*
* Marks the blocks between 'begBlk' and 'endBlk' as part of a loop.
*/
void Compiler::optMarkLoopBlocks(BasicBlock* begBlk, BasicBlock* endBlk, bool excludeEndBlk)
{
/* Calculate the 'loopWeight',
this is the amount to increase each block in the loop
Our heuristic is that loops are weighted eight times more
than straight line code.
Thus we increase each block by 7 times the weight of
the loop header block,
if the loops are all properly formed gives us:
(assuming that BB_LOOP_WEIGHT_SCALE is 8)
1 -- non loop basic block
8 -- single loop nesting
64 -- double loop nesting
512 -- triple loop nesting
*/
noway_assert(begBlk->bbNum <= endBlk->bbNum);
noway_assert(begBlk->isLoopHead());
noway_assert(fgReachable(begBlk, endBlk));
noway_assert(!opts.MinOpts());
#ifdef DEBUG
if (verbose)
{
printf("\nMarking a loop from " FMT_BB " to " FMT_BB, begBlk->bbNum,
excludeEndBlk ? endBlk->bbPrev->bbNum : endBlk->bbNum);
}
#endif
/* Build list of backedges for block begBlk */
flowList* backedgeList = nullptr;
for (flowList* pred = begBlk->bbPreds; pred != nullptr; pred = pred->flNext)
{
/* Is this a backedge? */
if (pred->getBlock()->bbNum >= begBlk->bbNum)
{
flowList* flow = new (this, CMK_FlowList) flowList(pred->getBlock(), backedgeList);
#if MEASURE_BLOCK_SIZE
genFlowNodeCnt += 1;
genFlowNodeSize += sizeof(flowList);
#endif // MEASURE_BLOCK_SIZE
backedgeList = flow;
}
}
/* At least one backedge must have been found (the one from endBlk) */
noway_assert(backedgeList);
BasicBlock* curBlk = begBlk;
while (true)
{
noway_assert(curBlk);
// For curBlk to be part of a loop that starts at begBlk
// curBlk must be reachable from begBlk and (since this is a loop)
// likewise begBlk must be reachable from curBlk.
//
if (fgReachable(curBlk, begBlk) && fgReachable(begBlk, curBlk))
{
/* If this block reaches any of the backedge blocks we set reachable */
/* If this block dominates any of the backedge blocks we set dominates */
bool reachable = false;
bool dominates = false;
for (flowList* tmp = backedgeList; tmp != nullptr; tmp = tmp->flNext)
{
BasicBlock* backedge = tmp->getBlock();
if (!curBlk->isRunRarely())
{
reachable |= fgReachable(curBlk, backedge);
dominates |= fgDominate(curBlk, backedge);
if (dominates && reachable)
{
break;
}
}
}
if (reachable)
{
noway_assert(curBlk->bbWeight > BB_ZERO_WEIGHT);
BasicBlock::weight_t weight;
if (curBlk->hasProfileWeight())
{
// We have real profile weights, so we aren't going to change this blocks weight
weight = curBlk->bbWeight;
}
else
{
if (dominates)
{
weight = curBlk->bbWeight * BB_LOOP_WEIGHT_SCALE;
}
else
{
weight = curBlk->bbWeight * (BB_LOOP_WEIGHT_SCALE / 2);
}
//
// The multiplication may have caused us to overflow
//
if (weight < curBlk->bbWeight)
{
// The multiplication caused us to overflow
weight = BB_MAX_WEIGHT;
}
//
// Set the new weight
//
curBlk->modifyBBWeight(weight);
}
#ifdef DEBUG
if (verbose)
{
printf("\n " FMT_BB "(wt=%s)", curBlk->bbNum, refCntWtd2str(curBlk->getBBWeight(this)));
}
#endif
}
}
/* Stop if we've reached the last block in the loop */
if (curBlk == endBlk)
{
break;
}
curBlk = curBlk->bbNext;
/* If we are excluding the endBlk then stop if we've reached endBlk */
if (excludeEndBlk && (curBlk == endBlk))
{
break;
}
}
}
/*****************************************************************************
*
* Unmark the blocks between 'begBlk' and 'endBlk' as part of a loop.
*/
void Compiler::optUnmarkLoopBlocks(BasicBlock* begBlk, BasicBlock* endBlk)
{
/* A set of blocks that were previously marked as a loop are now
to be unmarked, since we have decided that for some reason this
loop no longer exists.
Basically we are just reseting the blocks bbWeight to their
previous values.
*/
noway_assert(begBlk->bbNum <= endBlk->bbNum);
noway_assert(begBlk->isLoopHead());
noway_assert(!opts.MinOpts());
BasicBlock* curBlk;
unsigned backEdgeCount = 0;
for (flowList* pred = begBlk->bbPreds; pred != nullptr; pred = pred->flNext)
{
curBlk = pred->getBlock();
/* is this a backward edge? (from curBlk to begBlk) */
if (begBlk->bbNum > curBlk->bbNum)
{
continue;
}
/* We only consider back-edges that are BBJ_COND or BBJ_ALWAYS for loops */
if ((curBlk->bbJumpKind != BBJ_COND) && (curBlk->bbJumpKind != BBJ_ALWAYS))
{
continue;
}
backEdgeCount++;
}
/* Only unmark the loop blocks if we have exactly one loop back edge */
if (backEdgeCount != 1)
{
#ifdef DEBUG
if (verbose)
{
if (backEdgeCount > 0)
{
printf("\nNot removing loop at " FMT_BB ", due to an additional back edge", begBlk->bbNum);
}
else if (backEdgeCount == 0)
{
printf("\nNot removing loop at " FMT_BB ", due to no back edge", begBlk->bbNum);
}
}
#endif
return;
}
noway_assert(backEdgeCount == 1);
noway_assert(fgReachable(begBlk, endBlk));
#ifdef DEBUG
if (verbose)
{
printf("\nUnmarking loop at " FMT_BB, begBlk->bbNum);
}
#endif
curBlk = begBlk;
while (true)
{
noway_assert(curBlk);
// For curBlk to be part of a loop that starts at begBlk
// curBlk must be reachable from begBlk and (since this is a loop)
// likewise begBlk must be reachable from curBlk.
//
if (!curBlk->isRunRarely() && fgReachable(curBlk, begBlk) && fgReachable(begBlk, curBlk))
{
BasicBlock::weight_t weight = curBlk->bbWeight;
// Don't unmark blocks that are set to BB_MAX_WEIGHT
// Don't unmark blocks when we are using profile weights
//
if (!curBlk->isMaxBBWeight() && !curBlk->hasProfileWeight())
{
if (!fgDominate(curBlk, endBlk))
{
weight *= 2;
}
else
{
/* Merging of blocks can disturb the Dominates
information (see RAID #46649) */
if (weight < BB_LOOP_WEIGHT_SCALE)
{
weight *= 2;
}
}
// We can overflow here so check for it
if (weight < curBlk->bbWeight)
{
weight = BB_MAX_WEIGHT;
}
assert(weight >= BB_LOOP_WEIGHT_SCALE);
curBlk->modifyBBWeight(weight / BB_LOOP_WEIGHT_SCALE);
}
#ifdef DEBUG
if (verbose)
{
printf("\n " FMT_BB "(wt=%s)", curBlk->bbNum, refCntWtd2str(curBlk->getBBWeight(this)));
}
#endif
}
/* Stop if we've reached the last block in the loop */
if (curBlk == endBlk)
{
break;
}
curBlk = curBlk->bbNext;
/* Stop if we go past the last block in the loop, as it may have been deleted */
if (curBlk->bbNum > endBlk->bbNum)
{
break;
}
}
}
/*****************************************************************************************************
*
* Function called to update the loop table and bbWeight before removing a block
*/
void Compiler::optUpdateLoopsBeforeRemoveBlock(BasicBlock* block, bool skipUnmarkLoop)
{
if (!optLoopsMarked)
{
return;
}
noway_assert(!opts.MinOpts());
bool removeLoop = false;
/* If an unreachable block was part of a loop entry or bottom then the loop is unreachable */
/* Special case: the block was the head of a loop - or pointing to a loop entry */
for (unsigned loopNum = 0; loopNum < optLoopCount; loopNum++)
{
/* Some loops may have been already removed by
* loop unrolling or conditional folding */
if (optLoopTable[loopNum].lpFlags & LPFLG_REMOVED)
{
continue;
}
if (block == optLoopTable[loopNum].lpEntry || block == optLoopTable[loopNum].lpBottom)
{
optLoopTable[loopNum].lpFlags |= LPFLG_REMOVED;
continue;
}
#ifdef DEBUG
if (verbose)
{
printf("\nUpdateLoopsBeforeRemoveBlock Before: ");
optPrintLoopInfo(loopNum);
}
#endif
/* If the loop is still in the table
* any block in the loop must be reachable !!! */
noway_assert(optLoopTable[loopNum].lpEntry != block);
noway_assert(optLoopTable[loopNum].lpBottom != block);
if (optLoopTable[loopNum].lpExit == block)
{
optLoopTable[loopNum].lpExit = nullptr;
optLoopTable[loopNum].lpFlags &= ~LPFLG_ONE_EXIT;
;
}
/* If this points to the actual entry in the loop
* then the whole loop may become unreachable */
switch (block->bbJumpKind)
{
unsigned jumpCnt;
BasicBlock** jumpTab;
case BBJ_NONE:
case BBJ_COND:
if (block->bbNext == optLoopTable[loopNum].lpEntry)
{
removeLoop = true;
break;
}
if (block->bbJumpKind == BBJ_NONE)
{
break;
}
FALLTHROUGH;
case BBJ_ALWAYS:
noway_assert(block->bbJumpDest);
if (block->bbJumpDest == optLoopTable[loopNum].lpEntry)
{
removeLoop = true;
}
break;
case BBJ_SWITCH:
jumpCnt = block->bbJumpSwt->bbsCount;
jumpTab = block->bbJumpSwt->bbsDstTab;
do
{
noway_assert(*jumpTab);
if ((*jumpTab) == optLoopTable[loopNum].lpEntry)
{
removeLoop = true;
}
} while (++jumpTab, --jumpCnt);
break;
default:
break;
}
if (removeLoop)
{
/* Check if the entry has other predecessors outside the loop
* TODO: Replace this when predecessors are available */
BasicBlock* auxBlock;
for (auxBlock = fgFirstBB; auxBlock; auxBlock = auxBlock->bbNext)
{
/* Ignore blocks in the loop */
if (auxBlock->bbNum > optLoopTable[loopNum].lpHead->bbNum &&
auxBlock->bbNum <= optLoopTable[loopNum].lpBottom->bbNum)
{
continue;
}
switch (auxBlock->bbJumpKind)
{
unsigned jumpCnt;
BasicBlock** jumpTab;
case BBJ_NONE:
case BBJ_COND:
if (auxBlock->bbNext == optLoopTable[loopNum].lpEntry)
{
removeLoop = false;
break;
}
if (auxBlock->bbJumpKind == BBJ_NONE)
{
break;
}
FALLTHROUGH;
case BBJ_ALWAYS:
noway_assert(auxBlock->bbJumpDest);
if (auxBlock->bbJumpDest == optLoopTable[loopNum].lpEntry)
{
removeLoop = false;
}
break;
case BBJ_SWITCH:
jumpCnt = auxBlock->bbJumpSwt->bbsCount;
jumpTab = auxBlock->bbJumpSwt->bbsDstTab;
do
{
noway_assert(*jumpTab);
if ((*jumpTab) == optLoopTable[loopNum].lpEntry)
{
removeLoop = false;
}
} while (++jumpTab, --jumpCnt);
break;
default:
break;
}
}
if (removeLoop)
{
optLoopTable[loopNum].lpFlags |= LPFLG_REMOVED;
}
}
else if (optLoopTable[loopNum].lpHead == block)
{
/* The loop has a new head - Just update the loop table */
optLoopTable[loopNum].lpHead = block->bbPrev;
}
#ifdef DEBUG
if (verbose)
{
printf("\nUpdateLoopsBeforeRemoveBlock After: ");
optPrintLoopInfo(loopNum);
}
#endif
}
if ((skipUnmarkLoop == false) && ((block->bbJumpKind == BBJ_ALWAYS) || (block->bbJumpKind == BBJ_COND)) &&
(block->bbJumpDest->isLoopHead()) && (block->bbJumpDest->bbNum <= block->bbNum) && fgDomsComputed &&
(fgCurBBEpochSize == fgDomBBcount + 1) && fgReachable(block->bbJumpDest, block))
{
optUnmarkLoopBlocks(block->bbJumpDest, block);
}
}
#ifdef DEBUG
/*****************************************************************************
*
* Given the beginBlock of the loop, return the index of this loop
* to the loop table.
*/
unsigned Compiler::optFindLoopNumberFromBeginBlock(BasicBlock* begBlk)
{
unsigned lnum = 0;
for (lnum = 0; lnum < optLoopCount; lnum++)
{
if (optLoopTable[lnum].lpHead->bbNext == begBlk)
{
// Found the loop.
return lnum;
}
}
noway_assert(!"Loop number not found.");
return optLoopCount;
}
/*****************************************************************************
*
* Print loop info in an uniform way.
*/
void Compiler::optPrintLoopInfo(unsigned loopInd,
BasicBlock* lpHead,
BasicBlock* lpFirst,
BasicBlock* lpTop,
BasicBlock* lpEntry,
BasicBlock* lpBottom,
unsigned char lpExitCnt,
BasicBlock* lpExit,
unsigned parentLoop)
{
noway_assert(lpHead);
printf("L%02u, from " FMT_BB, loopInd, lpFirst->bbNum);
if (lpTop != lpFirst)
{
printf(" (loop top is " FMT_BB ")", lpTop->bbNum);
}
printf(" to " FMT_BB " (Head=" FMT_BB ", Entry=" FMT_BB ", ExitCnt=%d", lpBottom->bbNum, lpHead->bbNum,
lpEntry->bbNum, lpExitCnt);
if (lpExitCnt == 1)
{
printf(" at " FMT_BB, lpExit->bbNum);
}
if (parentLoop != BasicBlock::NOT_IN_LOOP)
{
printf(", parent loop = L%02u", parentLoop);
}
printf(")");
}
/*****************************************************************************
*
* Print loop information given the index of the loop in the loop table.
*/
void Compiler::optPrintLoopInfo(unsigned lnum)
{
noway_assert(lnum < optLoopCount);
LoopDsc* ldsc = &optLoopTable[lnum]; // lnum is the INDEX to the loop table.
optPrintLoopInfo(lnum, ldsc->lpHead, ldsc->lpFirst, ldsc->lpTop, ldsc->lpEntry, ldsc->lpBottom, ldsc->lpExitCnt,
ldsc->lpExit, ldsc->lpParent);
}
#endif
//------------------------------------------------------------------------
// optPopulateInitInfo: Populate loop init info in the loop table.
//
// Arguments:
// init - the tree that is supposed to initialize the loop iterator.
// iterVar - loop iteration variable.
//
// Return Value:
// "false" if the loop table could not be populated with the loop iterVar init info.
//
// Operation:
// The 'init' tree is checked if its lhs is a local and rhs is either
// a const or a local.
//
bool Compiler::optPopulateInitInfo(unsigned loopInd, GenTree* init, unsigned iterVar)
{
// Operator should be =
if (init->gtOper != GT_ASG)
{
return false;
}
GenTree* lhs = init->AsOp()->gtOp1;
GenTree* rhs = init->AsOp()->gtOp2;
// LHS has to be local and should equal iterVar.
if (lhs->gtOper != GT_LCL_VAR || lhs->AsLclVarCommon()->GetLclNum() != iterVar)
{
return false;
}
// RHS can be constant or local var.
// TODO-CQ: CLONE: Add arr length for descending loops.
if (rhs->gtOper == GT_CNS_INT && rhs->TypeGet() == TYP_INT)
{
optLoopTable[loopInd].lpFlags |= LPFLG_CONST_INIT;
optLoopTable[loopInd].lpConstInit = (int)rhs->AsIntCon()->gtIconVal;
}
else if (rhs->gtOper == GT_LCL_VAR)
{
optLoopTable[loopInd].lpFlags |= LPFLG_VAR_INIT;
optLoopTable[loopInd].lpVarInit = rhs->AsLclVarCommon()->GetLclNum();
}
else
{
return false;
}
return true;
}
//----------------------------------------------------------------------------------
// optCheckIterInLoopTest: Check if iter var is used in loop test.
//
// Arguments:
// test "jtrue" tree or an asg of the loop iter termination condition
// from/to blocks (beg, end) which are part of the loop.
// iterVar loop iteration variable.
// loopInd loop index.
//
// Operation:
// The test tree is parsed to check if "iterVar" matches the lhs of the condition
// and the rhs limit is extracted from the "test" tree. The limit information is
// added to the loop table.
//
// Return Value:
// "false" if the loop table could not be populated with the loop test info or
// if the test condition doesn't involve iterVar.
//
bool Compiler::optCheckIterInLoopTest(
unsigned loopInd, GenTree* test, BasicBlock* from, BasicBlock* to, unsigned iterVar)
{
// Obtain the relop from the "test" tree.
GenTree* relop;
if (test->gtOper == GT_JTRUE)
{
relop = test->gtGetOp1();
}
else
{
assert(test->gtOper == GT_ASG);
relop = test->gtGetOp2();
}
noway_assert(relop->OperKind() & GTK_RELOP);
GenTree* opr1 = relop->AsOp()->gtOp1;
GenTree* opr2 = relop->AsOp()->gtOp2;
GenTree* iterOp;
GenTree* limitOp;
// Make sure op1 or op2 is the iterVar.
if (opr1->gtOper == GT_LCL_VAR && opr1->AsLclVarCommon()->GetLclNum() == iterVar)
{
iterOp = opr1;
limitOp = opr2;
}
else if (opr2->gtOper == GT_LCL_VAR && opr2->AsLclVarCommon()->GetLclNum() == iterVar)
{
iterOp = opr2;
limitOp = opr1;
}
else
{
return false;
}
if (iterOp->gtType != TYP_INT)
{
return false;
}
// Mark the iterator node.
iterOp->gtFlags |= GTF_VAR_ITERATOR;
// Check what type of limit we have - constant, variable or arr-len.
if (limitOp->gtOper == GT_CNS_INT)
{
optLoopTable[loopInd].lpFlags |= LPFLG_CONST_LIMIT;
if ((limitOp->gtFlags & GTF_ICON_SIMD_COUNT) != 0)
{
optLoopTable[loopInd].lpFlags |= LPFLG_SIMD_LIMIT;
}
}
else if (limitOp->gtOper == GT_LCL_VAR &&
!optIsVarAssigned(from, to, nullptr, limitOp->AsLclVarCommon()->GetLclNum()))
{
optLoopTable[loopInd].lpFlags |= LPFLG_VAR_LIMIT;
}
else if (limitOp->gtOper == GT_ARR_LENGTH)
{
optLoopTable[loopInd].lpFlags |= LPFLG_ARRLEN_LIMIT;
}
else
{
return false;
}
// Save the type of the comparison between the iterator and the limit.
optLoopTable[loopInd].lpTestTree = relop;
return true;
}
//----------------------------------------------------------------------------------
// optIsLoopIncrTree: Check if loop is a tree of form v += 1 or v = v + 1
//
// Arguments:
// incr The incr tree to be checked. Whether incr tree is
// oper-equal(+=, -=...) type nodes or v=v+1 type ASG nodes.
//
// Operation:
// The test tree is parsed to check if "iterVar" matches the lhs of the condition
// and the rhs limit is extracted from the "test" tree. The limit information is
// added to the loop table.
//
// 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 asg 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;
}
//----------------------------------------------------------------------------------
// optComputeIterInfo: Check tree is loop increment of a lcl that is loop-invariant.
//
// Arguments:
// from, to - are blocks (beg, end) which are part of the loop.
// incr - tree that increments the loop iterator. v+=1 or v=v+1.
// pIterVar - see return value.
//
// Return Value:
// Returns true if iterVar "v" can be returned in "pIterVar", otherwise returns
// false.
//
// Operation:
// Check if the "incr" tree is a "v=v+1 or v+=1" type tree and make sure it is not
// assigned in the loop.
//
bool Compiler::optComputeIterInfo(GenTree* incr, BasicBlock* from, BasicBlock* to, unsigned* pIterVar)
{
unsigned iterVar = optIsLoopIncrTree(incr);
if (iterVar == BAD_VAR_NUM)
{
return false;
}
if (optIsVarAssigned(from, to, incr, iterVar))
{
JITDUMP("iterVar is assigned in loop\n");
return false;
}
*pIterVar = iterVar;
return true;
}
//----------------------------------------------------------------------------------
// 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->OperGet() == GT_ASG)
{
GenTree* lhs = tree->AsOp()->gtOp1;
GenTree* rhs = tree->AsOp()->gtOp2;
// Return as the new test node.
if (lhs->gtOper == GT_LCL_VAR && lhs->AsLclVarCommon()->GetLclNum() == opr1->AsLclVarCommon()->GetLclNum())
{
if (rhs->OperIsCompare())
{
*newTestStmt = prevStmt;
return true;
}
}
}
}
return false;
}
//----------------------------------------------------------------------------------
// optExtractInitTestIncr:
// Extract the "init", "test" and "incr" nodes of the loop.
//
// Arguments:
// head - Loop head block
// bottom - Loop bottom block
// top - Loop top block
// ppInit - The init stmt of the loop if found.
// ppTest - The test stmt of the loop if found.
// ppIncr - 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.
//
// Operation:
// Check if the "test" stmt is last stmt in the loop "bottom". If found good,
// "test" stmt is found. Try to find the "incr" stmt. Check previous stmt of
// "test" to get the "incr" stmt. If it is not found it could be a loop of the
// below form.
//