-
Notifications
You must be signed in to change notification settings - Fork 4.8k
/
optimizer.cpp
9597 lines (8318 loc) · 335 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()
{
optLoopsMarked = false;
fgHasLoops = false;
loopAlignCandidates = 0;
/* Initialize the # of tracked loops to 0 */
optLoopCount = 0;
optLoopTable = nullptr;
optCurLoopEpoch = 0;
#ifdef DEBUG
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;
}
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).
//
// Notes:
// Depends on dominators, and fgReturnBlocks being set.
//
PhaseStatus Compiler::optSetBlockWeights()
{
noway_assert(opts.OptimizationEnabled());
assert(fgDomsComputed);
assert(fgReturnBlocksComputed);
#ifdef DEBUG
bool changed = false;
#endif
bool firstBBDominatesAllReturns = true;
const bool usingProfileWeights = fgIsUsingProfileWeights();
for (BasicBlock* const block : Blocks())
{
/* Blocks that can't be reached via the first block are rarely executed */
if (!fgReachable(fgFirstBB, block))
{
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)
{
if (!fgDominate(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)
{
INDEBUG(changed = 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);
}
}
}
}
}
#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
return PhaseStatus::MODIFIED_EVERYTHING;
}
//------------------------------------------------------------------------
// 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(fgReachable(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.
flowList* backedgeList = nullptr;
for (BasicBlock* const predBlock : begBlk->PredBlocks())
{
// Is this a back edge?
if (predBlock->bbNum >= begBlk->bbNum)
{
backedgeList = new (this, CMK_FlowList) flowList(predBlock, backedgeList);
#if MEASURE_BLOCK_SIZE
genFlowNodeCnt += 1;
genFlowNodeSize += sizeof(flowList);
#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())
{
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 (fgReachable(curBlk, begBlk) && fgReachable(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 (flowList* tmp = backedgeList; tmp != nullptr; tmp = tmp->flNext)
{
BasicBlock* backedge = tmp->getBlock();
reachable |= fgReachable(curBlk, backedge);
dominates |= fgDominate(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");
}
}
}
//------------------------------------------------------------------------
// optUnmarkLoopBlocks: Unmark the blocks between 'begBlk' and 'endBlk' as part of a loop.
//
// 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:
// 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 resetting the blocks bbWeight to their
// previous values.
//
void Compiler::optUnmarkLoopBlocks(BasicBlock* begBlk, BasicBlock* endBlk)
{
noway_assert(begBlk->bbNum <= endBlk->bbNum);
noway_assert(begBlk->isLoopHead());
noway_assert(!opts.MinOpts());
unsigned backEdgeCount = 0;
for (BasicBlock* const predBlock : begBlk->PredBlocks())
{
// Is this a backward edge? (from predBlock to begBlk)
if (begBlk->bbNum > predBlock->bbNum)
{
continue;
}
// We only consider back-edges that are BBJ_COND or BBJ_ALWAYS for loops.
if (!predBlock->KindIs(BBJ_COND, 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(fgReachable(begBlk, endBlk));
#ifdef DEBUG
if (verbose)
{
printf("\nUnmarking a loop from " FMT_BB " to " FMT_BB, begBlk->bbNum, endBlk->bbNum);
}
#endif
for (BasicBlock* const curBlk : BasicBlockRangeList(begBlk, endBlk))
{
// Stop if we go past the last block in the loop, as it may have been deleted.
if (curBlk->bbNum > endBlk->bbNum)
{
break;
}
// Don't change the block weight if it's known to be rarely run.
if (curBlk->isRunRarely())
{
continue;
}
// Don't change the block weight if it came from profile data.
if (curBlk->hasProfileWeight())
{
continue;
}
// Don't unmark blocks that are maximum weight.
if (curBlk->isMaxBBWeight())
{
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 (fgReachable(curBlk, begBlk) && fgReachable(begBlk, curBlk))
{
weight_t scale = 1.0 / BB_LOOP_WEIGHT_SCALE;
if (!fgDominate(curBlk, endBlk))
{
scale *= 2;
}
curBlk->scaleBBWeight(scale);
JITDUMP("\n " FMT_BB "(wt=" FMT_WT ")", curBlk->bbNum, curBlk->getBBWeight(this));
}
}
JITDUMP("\n");
begBlk->unmarkLoopAlign(this DEBUG_ARG("Removed loop"));
}
/*****************************************************************************************************
*
* 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 is 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++)
{
LoopDsc& loop = optLoopTable[loopNum];
// Some loops may have been already removed by loop unrolling or conditional folding.
if (loop.lpFlags & LPFLG_REMOVED)
{
continue;
}
// Avoid printing to the JitDump unless we're actually going to change something.
// If we call reportBefore, then we're going to change the loop table, and we should print the
// `reportAfter` info as well. Only print the `reportBefore` info once, if multiple changes to
// the table are made.
INDEBUG(bool reportedBefore = false);
auto reportBefore = [&]() {
#ifdef DEBUG
if (verbose && !reportedBefore)
{
printf("optUpdateLoopsBeforeRemoveBlock " FMT_BB " Before: ", block->bbNum);
optPrintLoopInfo(loopNum);
printf("\n");
reportedBefore = true;
}
#endif // DEBUG
};
auto reportAfter = [&]() {
#ifdef DEBUG
if (verbose && reportedBefore)
{
printf("optUpdateLoopsBeforeRemoveBlock " FMT_BB " After: ", block->bbNum);
optPrintLoopInfo(loopNum);
printf("\n");
}
#endif // DEBUG
};
if (block == loop.lpEntry || block == loop.lpBottom)
{
reportBefore();
optMarkLoopRemoved(loopNum);
reportAfter();
continue;
}
// If the loop is still in the table any block in the loop must be reachable.
noway_assert((loop.lpEntry != block) && (loop.lpBottom != block));
if (loop.lpExit == block)
{
reportBefore();
assert(loop.lpExitCnt == 1);
--loop.lpExitCnt;
loop.lpExit = nullptr;
}
// If `block` flows to the loop entry then the whole loop will become unreachable if it is the
// only non-loop predecessor.
switch (block->bbJumpKind)
{
case BBJ_NONE:
if (block->bbNext == loop.lpEntry)
{
removeLoop = true;
}
break;
case BBJ_COND:
if ((block->bbNext == loop.lpEntry) || (block->bbJumpDest == loop.lpEntry))
{
removeLoop = true;
}
break;
case BBJ_ALWAYS:
if (block->bbJumpDest == loop.lpEntry)
{
removeLoop = true;
}
break;
case BBJ_SWITCH:
for (BasicBlock* const bTarget : block->SwitchTargets())
{
if (bTarget == loop.lpEntry)
{
removeLoop = true;
break;
}
}
break;
default:
break;
}
if (removeLoop)
{
// Check if the entry has other predecessors outside the loop.
// TODO: Replace this when predecessors are available.
for (BasicBlock* const auxBlock : Blocks())
{
// Ignore blocks in the loop.
if (loop.lpContains(auxBlock))
{
continue;
}
switch (auxBlock->bbJumpKind)
{
case BBJ_NONE:
if (auxBlock->bbNext == loop.lpEntry)
{
removeLoop = false;
}
break;
case BBJ_COND:
if ((auxBlock->bbNext == loop.lpEntry) || (auxBlock->bbJumpDest == loop.lpEntry))
{
removeLoop = false;
}
break;
case BBJ_ALWAYS:
if (auxBlock->bbJumpDest == loop.lpEntry)
{
removeLoop = false;
}
break;
case BBJ_SWITCH:
for (BasicBlock* const bTarget : auxBlock->SwitchTargets())
{
if (bTarget == loop.lpEntry)
{
removeLoop = false;
break;
}
}
break;
default:
break;
}
}
if (removeLoop)
{
reportBefore();
optMarkLoopRemoved(loopNum);
}
}
else if (loop.lpHead == block)
{
reportBefore();
/* The loop has a new head - Just update the loop table */
loop.lpHead = block->bbPrev;
}
reportAfter();
}
if ((skipUnmarkLoop == false) && //
block->KindIs(BBJ_ALWAYS, BBJ_COND) && //
block->bbJumpDest->isLoopHead() && //
(block->bbJumpDest->bbNum <= block->bbNum) && //
fgDomsComputed && //
(fgCurBBEpochSize == fgDomBBcount + 1) && //
fgReachable(block->bbJumpDest, block))
{
optUnmarkLoopBlocks(block->bbJumpDest, block);
}
}
//------------------------------------------------------------------------
// optClearLoopIterInfo: Clear the info related to LPFLG_ITER loops in the loop table.
// The various fields related to iterators is known to be valid for loop cloning and unrolling,
// but becomes invalid afterwards. Clear the info that might be used incorrectly afterwards
// in JitDump or by subsequent phases.
//
void Compiler::optClearLoopIterInfo()
{
for (unsigned lnum = 0; lnum < optLoopCount; lnum++)
{
LoopDsc& loop = optLoopTable[lnum];
loop.lpFlags &= ~(LPFLG_ITER | LPFLG_CONST_INIT | LPFLG_SIMD_LIMIT | LPFLG_VAR_LIMIT | LPFLG_CONST_LIMIT |
LPFLG_ARRLEN_LIMIT);
loop.lpIterTree = nullptr;
loop.lpInitBlock = nullptr;
loop.lpConstInit = -1;
loop.lpTestTree = nullptr;
}
}
#ifdef DEBUG
/*****************************************************************************
*
* Print loop info in an uniform way.
*/
void Compiler::optPrintLoopInfo(const LoopDsc* loop, bool printVerbose /* = false */)
{
assert(optLoopTable != nullptr);
assert((&optLoopTable[0] <= loop) && (loop < &optLoopTable[optLoopCount]));
unsigned lnum = (unsigned)(loop - optLoopTable);
assert(lnum < optLoopCount);
assert(&optLoopTable[lnum] == loop);
if (loop->lpFlags & LPFLG_REMOVED)
{
// If a loop has been removed, it might be dangerous to print its fields (e.g., loop unrolling
// nulls out the lpHead field).
printf(FMT_LP " REMOVED", lnum);
return;
}
printf(FMT_LP ", from " FMT_BB " to " FMT_BB " (Head=" FMT_BB ", Entry=" FMT_BB, lnum, loop->lpTop->bbNum,
loop->lpBottom->bbNum, loop->lpHead->bbNum, loop->lpEntry->bbNum);
if (loop->lpExitCnt == 1)
{
printf(", Exit=" FMT_BB, loop->lpExit->bbNum);
}
else
{
printf(", ExitCnt=%d", loop->lpExitCnt);
}
if (loop->lpParent != BasicBlock::NOT_IN_LOOP)
{
printf(", parent=" FMT_LP, loop->lpParent);
}
printf(")");
if (printVerbose)
{
if (loop->lpChild != BasicBlock::NOT_IN_LOOP)
{
printf(", child loop = " FMT_LP, loop->lpChild);
}
if (loop->lpSibling != BasicBlock::NOT_IN_LOOP)
{
printf(", sibling loop = " FMT_LP, loop->lpSibling);
}
// If an iterator loop print the iterator and the initialization.
if (loop->lpFlags & LPFLG_ITER)
{
printf(" [over V%02u", loop->lpIterVar());
printf(" (");
printf(GenTree::OpName(loop->lpIterOper()));
printf(" %d)", loop->lpIterConst());
if (loop->lpFlags & LPFLG_CONST_INIT)
{
printf(" from %d", loop->lpConstInit);
}
if (loop->lpFlags & LPFLG_CONST_INIT)
{
if (loop->lpInitBlock != loop->lpHead)
{
printf(" (in " FMT_BB ")", loop->lpInitBlock->bbNum);
}
}
// If a simple test condition print operator and the limits */
printf(" %s", GenTree::OpName(loop->lpTestOper()));
if (loop->lpFlags & LPFLG_CONST_LIMIT)
{
printf(" %d", loop->lpConstLimit());
if (loop->lpFlags & LPFLG_SIMD_LIMIT)
{
printf(" (simd)");
}
}
if (loop->lpFlags & LPFLG_VAR_LIMIT)
{
printf(" V%02u", loop->lpVarLimit());
}
if (loop->lpFlags & LPFLG_ARRLEN_LIMIT)
{
ArrIndex* index = new (getAllocator(CMK_DebugOnly)) ArrIndex(getAllocator(CMK_DebugOnly));
if (loop->lpArrLenLimit(this, index))
{
printf(" ");
index->Print();
printf(".Length");
}
else
{
printf(" ???.Length");
}
}
printf("]");
}
// Print the flags
if (loop->lpFlags & LPFLG_CONTAINS_CALL)
{
printf(" call");
}
if (loop->lpFlags & LPFLG_HAS_PREHEAD)
{
printf(" prehead");
}
if (loop->lpFlags & LPFLG_DONT_UNROLL)
{
printf(" !unroll");
}
if (loop->lpFlags & LPFLG_ASGVARS_YES)
{
printf(" avyes");
}
if (loop->lpFlags & LPFLG_ASGVARS_INC)
{
printf(" avinc");
}
}
}
void Compiler::optPrintLoopInfo(unsigned lnum, bool printVerbose /* = false */)
{
assert(lnum < optLoopCount);
const LoopDsc& loop = optLoopTable[lnum];
optPrintLoopInfo(&loop, printVerbose);
}
//------------------------------------------------------------------------
// optPrintLoopTable: Print the loop table
//
void Compiler::optPrintLoopTable()
{
printf("\n*************** Natural loop table\n");
if (optLoopCount == 0)
{
printf("No loops\n");
}
else
{
for (unsigned loopInd = 0; loopInd < optLoopCount; loopInd++)
{
optPrintLoopInfo(loopInd, /* verbose */ true);
printf("\n");
}
}
printf("\n");
}
#endif // DEBUG
//------------------------------------------------------------------------
// optPopulateInitInfo: Populate loop init info in the loop table.
// We assume the iteration variable is initialized already and check appropriately.
// This only checks for the special case of a constant initialization.
//
// Arguments:
// loopInd - loop index
// initBlock - block in which the initialization lives.
// init - the tree that is supposed to initialize the loop iterator. Might be nullptr.
// iterVar - loop iteration variable.
//
// Return Value:
// "true" if a constant initializer was found.
//
// Operation:
// The 'init' tree is checked if its lhs is a local and rhs is a const.
//
bool Compiler::optPopulateInitInfo(unsigned loopInd, BasicBlock* initBlock, GenTree* init, unsigned iterVar)
{
if (init == nullptr)
{
return false;
}
// 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))
{
return false;
}
// We found an initializer in the `head` block. For this to be used, we need to make sure the
// "iterVar" initialization is never skipped. That is, every pred of ENTRY other than HEAD is in the loop.
for (BasicBlock* const predBlock : optLoopTable[loopInd].lpEntry->PredBlocks())
{
if ((predBlock != initBlock) && !optLoopTable[loopInd].lpContains(predBlock))
{
JITDUMP(FMT_LP ": initialization not guaranteed through `head` block; ignore constant initializer\n",
loopInd);
return false;
}
}
optLoopTable[loopInd].lpFlags |= LPFLG_CONST_INIT;
optLoopTable[loopInd].lpConstInit = (int)rhs->AsIntCon()->gtIconVal;
optLoopTable[loopInd].lpInitBlock = initBlock;
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->OperIsCompare());
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))
{