forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloopcloning.cpp
3047 lines (2776 loc) · 112 KB
/
loopcloning.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 LoopCloning XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#include "jitstd/algorithm.h"
#ifdef DEBUG
//--------------------------------------------------------------------------------------------------
// ArrIndex::Print - debug print an ArrIndex struct in form: `V01[V02][V03]`.
//
// Arguments:
// dim (Optional) Print up to but not including this dimension. Default: print all dimensions.
//
void ArrIndex::Print(unsigned dim /* = -1 */)
{
printf("V%02d", arrLcl);
for (unsigned i = 0; i < ((dim == (unsigned)-1) ? rank : dim); ++i)
{
printf("[V%02d]", indLcls.Get(i));
}
}
//--------------------------------------------------------------------------------------------------
// ArrIndex::PrintBoundsCheckNodes - debug print an ArrIndex struct bounds check node tree ids in
// form: `[000125][000113]`.
//
// Arguments:
// dim (Optional) Print up to but not including this dimension. Default: print all dimensions.
//
void ArrIndex::PrintBoundsCheckNodes(unsigned dim /* = -1 */)
{
for (unsigned i = 0; i < ((dim == (unsigned)-1) ? rank : dim); ++i)
{
Compiler::printTreeID(bndsChks.Get(i));
}
}
#endif // DEBUG
//--------------------------------------------------------------------------------------------------
// ToGenTree - Convert an arrLen operation into a GenTree node.
//
// Arguments:
// comp Compiler instance to allocate trees
// bb Basic block of the new tree
//
// Return Values:
// Returns the gen tree representation for arrLen or MD Array node as defined by
// the "type" member
//
// Notes:
// This tree produces a GT_IND(GT_INDEX_ADDR) node, the caller is supposed to morph it.
//
GenTree* LC_Array::ToGenTree(Compiler* comp, BasicBlock* bb)
{
// If jagged array
if (type == Jagged)
{
// Create a a[i][j][k].length type node.
GenTree* arr = comp->gtNewLclvNode(arrIndex->arrLcl, comp->lvaTable[arrIndex->arrLcl].lvType);
int rank = GetDimRank();
for (int i = 0; i < rank; ++i)
{
GenTree* idx = comp->gtNewLclvNode(arrIndex->indLcls[i], comp->lvaTable[arrIndex->indLcls[i]].lvType);
GenTree* arrAddr = comp->gtNewArrayIndexAddr(arr, idx, TYP_REF, NO_CLASS_HANDLE);
// Clear the range check flag and mark the index as non-faulting: we guarantee that all necessary range
// checking has already been done by the time this array index expression is invoked.
arrAddr->gtFlags &= ~GTF_INX_RNGCHK;
arrAddr->gtFlags |= GTF_INX_ADDR_NONNULL;
arr = comp->gtNewIndexIndir(arrAddr->AsIndexAddr());
// We don't really need to call morph here if we import arr[i] directly
// without gtNewArrayIndexAddr (but it's a bit of verbose).
arr = comp->fgMorphTree(arr);
}
// If asked for arrlen invoke arr length operator.
if (oper == ArrLen)
{
GenTree* arrLen = comp->gtNewArrLen(TYP_INT, arr, OFFSETOF__CORINFO_Array__length, bb);
// We already guaranteed (by a sequence of preceding checks) that the array length operator will not
// throw an exception because we null checked the base array.
// So, we should be able to do the following:
// arrLen->gtFlags &= ~GTF_EXCEPT;
// arrLen->gtFlags |= GTF_IND_NONFAULTING;
// However, we then end up with a mix of non-faulting array length operators as well as normal faulting
// array length operators in the slow-path of the cloned loops. CSE doesn't keep these separate, so bails
// out on creating CSEs on this very useful type of CSE, leading to CQ losses in the cloned loop fast path.
// TODO-CQ: fix this.
return arrLen;
}
else
{
assert(oper == None);
return arr;
}
}
else
{
// TODO-CQ: Optimize for MD Array.
assert(!"Optimize for MD Array");
}
return nullptr;
}
//--------------------------------------------------------------------------------------------------
// ToGenTree - Convert an "identifier" into a GenTree node.
//
// Arguments:
// comp Compiler instance to allocate trees
// bb Basic block of the new tree
//
// Return Values:
// Returns the gen tree representation for either a constant or a variable or an arrLen operation
// defined by the "type" member
//
GenTree* LC_Ident::ToGenTree(Compiler* comp, BasicBlock* bb)
{
// Convert to GenTree nodes.
switch (type)
{
case Const:
assert(constant <= INT32_MAX);
return comp->gtNewIconNode(constant);
case Var:
return comp->gtNewLclvNode(lclNum, comp->lvaTable[lclNum].lvType);
case ArrAccess:
return arrAccess.ToGenTree(comp, bb);
case Null:
return comp->gtNewIconNode(0, TYP_REF);
case ClassHandle:
return comp->gtNewIconHandleNode((size_t)clsHnd, GTF_ICON_CLASS_HDL);
case IndirOfLocal:
{
GenTree* addr = comp->gtNewLclvNode(lclNum, TYP_REF);
if (indirOffs != 0)
{
addr = comp->gtNewOperNode(GT_ADD, TYP_BYREF, addr,
comp->gtNewIconNode(static_cast<ssize_t>(indirOffs), TYP_I_IMPL));
}
GenTree* const indir = comp->gtNewIndir(TYP_I_IMPL, addr, GTF_IND_INVARIANT);
return indir;
}
case MethodAddr:
{
GenTreeIntCon* methodAddrHandle = comp->gtNewIconHandleNode((size_t)methAddr, GTF_ICON_FTN_ADDR);
INDEBUG(methodAddrHandle->gtTargetHandle = (size_t)targetMethHnd);
return methodAddrHandle;
}
case IndirOfMethodAddrSlot:
{
GenTreeIntCon* slot = comp->gtNewIconHandleNode((size_t)methAddr, GTF_ICON_FTN_ADDR);
INDEBUG(slot->gtTargetHandle = (size_t)targetMethHnd);
GenTree* indir = comp->gtNewIndir(TYP_I_IMPL, slot, GTF_IND_NONFAULTING | GTF_IND_INVARIANT);
return indir;
}
default:
assert(!"Could not convert LC_Ident to GenTree");
unreached();
break;
}
}
//--------------------------------------------------------------------------------------------------
// ToGenTree - Convert an "expression" into a GenTree node.
//
// Arguments:
// comp Compiler instance to allocate trees
// bb Basic block of the new tree
//
// Return Values:
// Returns the gen tree representation for either a constant or a variable or an arrLen operation
// defined by the "type" member
//
GenTree* LC_Expr::ToGenTree(Compiler* comp, BasicBlock* bb)
{
// Convert to GenTree nodes.
switch (type)
{
case Ident:
return ident.ToGenTree(comp, bb);
default:
assert(!"Could not convert LC_Expr to GenTree");
unreached();
break;
}
}
//--------------------------------------------------------------------------------------------------
// ToGenTree - Convert a "condition" into a GenTree node.
//
// Arguments:
// comp Compiler instance to allocate trees
// bb Basic block of the new tree
// invert `true` if the condition should be inverted
//
// Return Values:
// Returns the GenTree representation for the conditional operator on lhs and rhs trees
//
GenTree* LC_Condition::ToGenTree(Compiler* comp, BasicBlock* bb, bool invert)
{
GenTree* op1Tree = op1.ToGenTree(comp, bb);
GenTree* op2Tree = op2.ToGenTree(comp, bb);
assert(genTypeSize(genActualType(op1Tree->TypeGet())) == genTypeSize(genActualType(op2Tree->TypeGet())));
GenTree* result = comp->gtNewOperNode(invert ? GenTree::ReverseRelop(oper) : oper, TYP_INT, op1Tree, op2Tree);
if (compareUnsigned)
{
result->gtFlags |= GTF_UNSIGNED;
}
return result;
}
//--------------------------------------------------------------------------------------------------
// Evaluates - Evaluate a given loop cloning condition if it can be statically evaluated.
//
// Arguments:
// pResult OUT parameter. The evaluation result
//
// Return Values:
// Returns true if the condition can be statically evaluated. If the condition's result
// is statically unknown then return false. In other words, `*pResult` is valid only if the
// function returns true.
//
bool LC_Condition::Evaluates(bool* pResult)
{
switch (oper)
{
case GT_EQ:
case GT_GE:
case GT_LE:
// If op1 == op2 then equality should result in true.
if (op1 == op2)
{
*pResult = true;
return true;
}
break;
case GT_GT:
case GT_LT:
case GT_NE:
// If op1 == op2 then inequality should result in false.
if (op1 == op2)
{
*pResult = false;
return true;
}
break;
default:
// for all other 'oper' kinds, we will return false
break;
}
return false;
}
//--------------------------------------------------------------------------------------------------
// Combines - Check whether two conditions would combine to yield a single new condition.
//
// Arguments:
// cond The condition that is checked if it would combine with "*this" condition.
// newCond The resulting combined condition.
//
// Return Values:
// Returns true if "cond" combines with the "this" condition.
// "newCond" contains the combines condition.
//
// Operation:
// Check if both conditions are equal. If so, return just 1 of them.
// Reverse their operators and check if their reversed operands match. If so, return either of them.
//
// Notes:
// This is not a full-fledged expression optimizer, it is supposed
// to remove redundant conditions that are generated for optimization
// opportunities. Anything further should be implemented as needed.
// For example, for (i = beg; i < end; i += inc) a[i]. Then, the conditions
// would be: "beg >= 0, end <= a.len, inc > 0"
bool LC_Condition::Combines(const LC_Condition& cond, LC_Condition* newCond)
{
if (oper == cond.oper && op1 == cond.op1 && op2 == cond.op2)
{
*newCond = *this;
return true;
}
else if ((oper == GT_LT || oper == GT_LE || oper == GT_GT || oper == GT_GE) &&
GenTree::ReverseRelop(oper) == cond.oper && op1 == cond.op2 && op2 == cond.op1)
{
*newCond = *this;
return true;
}
return false;
}
//--------------------------------------------------------------------------------------------------
// GetLoopOptInfo - Retrieve the loop opt info candidate array.
//
// Arguments:
// loopNum the loop index.
//
// Return Values:
// Return the optInfo array member. The method doesn't allocate memory.
//
JitExpandArrayStack<LcOptInfo*>* LoopCloneContext::GetLoopOptInfo(unsigned loopNum)
{
return optInfo[loopNum];
}
//--------------------------------------------------------------------------------------------------
// CancelLoopOptInfo - Cancel loop cloning optimization for this loop.
//
// Arguments:
// loopNum the loop index.
//
// Return Values:
// None.
//
void LoopCloneContext::CancelLoopOptInfo(unsigned loopNum)
{
JITDUMP("Cancelling loop cloning for loop " FMT_LP "\n", loopNum);
optInfo[loopNum] = nullptr;
if (conditions[loopNum] != nullptr)
{
conditions[loopNum]->Reset();
conditions[loopNum] = nullptr;
}
}
//--------------------------------------------------------------------------------------------------
// EnsureLoopOptInfo - Retrieve the loop opt info candidate array, if it is not present, allocate
// memory.
//
// Arguments:
// loopNum the loop index.
//
// Return Values:
// The array of optimization candidates for the loop.
//
JitExpandArrayStack<LcOptInfo*>* LoopCloneContext::EnsureLoopOptInfo(unsigned loopNum)
{
if (optInfo[loopNum] == nullptr)
{
optInfo[loopNum] = new (alloc) JitExpandArrayStack<LcOptInfo*>(alloc, 4);
}
return optInfo[loopNum];
}
//--------------------------------------------------------------------------------------------------
// EnsureLoopOptInfo - Retrieve the loop cloning conditions candidate array,
// if it is not present, allocate memory.
//
// Arguments:
// loopNum the loop index.
//
// Return Values:
// The array of cloning conditions for the loop.
//
JitExpandArrayStack<LC_Condition>* LoopCloneContext::EnsureConditions(unsigned loopNum)
{
if (conditions[loopNum] == nullptr)
{
conditions[loopNum] = new (alloc) JitExpandArrayStack<LC_Condition>(alloc, 4);
}
return conditions[loopNum];
}
//--------------------------------------------------------------------------------------------------
// GetConditions - Get the cloning conditions array for the loop, no allocation.
//
// Arguments:
// loopNum the loop index.
//
// Return Values:
// The array of cloning conditions for the loop.
//
JitExpandArrayStack<LC_Condition>* LoopCloneContext::GetConditions(unsigned loopNum)
{
return conditions[loopNum];
}
//--------------------------------------------------------------------------------------------------
// EnsureArrayDerefs - Ensure an array of array dereferences is created if it doesn't exist.
//
// Arguments:
// loopNum the loop index.
//
// Return Values:
// The array of array dereferences for the loop.
//
JitExpandArrayStack<LC_Array>* LoopCloneContext::EnsureArrayDerefs(unsigned loopNum)
{
if (arrayDerefs[loopNum] == nullptr)
{
arrayDerefs[loopNum] = new (alloc) JitExpandArrayStack<LC_Array>(alloc, 4);
}
return arrayDerefs[loopNum];
}
//--------------------------------------------------------------------------------------------------
// EnsureObjDerefs - Ensure an array of object dereferences is created if it doesn't exist.
//
// Arguments:
// loopNum the loop index.
//
// Return Values:
// The array of object dereferences for the loop.
//
JitExpandArrayStack<LC_Ident>* LoopCloneContext::EnsureObjDerefs(unsigned loopNum)
{
if (objDerefs[loopNum] == nullptr)
{
objDerefs[loopNum] = new (alloc) JitExpandArrayStack<LC_Ident>(alloc, 4);
}
return objDerefs[loopNum];
}
//--------------------------------------------------------------------------------------------------
// HasBlockConditions - Check if there are block level conditions for the loop.
//
// Arguments:
// loopNum the loop index.
//
// Return Values:
// Return true if there are any block level conditions.
//
bool LoopCloneContext::HasBlockConditions(unsigned loopNum)
{
JitExpandArrayStack<JitExpandArrayStack<LC_Condition>*>* levelCond = blockConditions[loopNum];
if (levelCond == nullptr)
{
return false;
}
// Walk through each block to check if any of them has conditions.
for (unsigned i = 0; i < levelCond->Size(); ++i)
{
if ((*levelCond)[i]->Size() > 0)
{
return true;
}
}
return false;
}
//--------------------------------------------------------------------------------------------------
// GetBlockConditions - Return block level conditions for the loop.
//
// Arguments:
// loopNum the loop index.
//
// Return Values:
// Return block conditions.
//
JitExpandArrayStack<JitExpandArrayStack<LC_Condition>*>* LoopCloneContext::GetBlockConditions(unsigned loopNum)
{
assert(HasBlockConditions(loopNum));
return blockConditions[loopNum];
}
//--------------------------------------------------------------------------------------------------
// EnsureBlockConditions - Allocate block level conditions for the loop if not exists.
//
// Arguments:
// loopNum the loop index.
// condBlocks the number of block-level conditions for each loop, corresponding to the blocks
// created.
//
// Return Values:
// Return block conditions.
//
JitExpandArrayStack<JitExpandArrayStack<LC_Condition>*>* LoopCloneContext::EnsureBlockConditions(unsigned loopNum,
unsigned condBlocks)
{
if (blockConditions[loopNum] == nullptr)
{
blockConditions[loopNum] = new (alloc) JitExpandArrayStack<JitExpandArrayStack<LC_Condition>*>(alloc);
}
JitExpandArrayStack<JitExpandArrayStack<LC_Condition>*>* levelCond = blockConditions[loopNum];
// Iterate backwards to make sure the expand array stack reallocs just once here.
unsigned prevSize = levelCond->Size();
for (unsigned i = condBlocks; i > prevSize; i--)
{
levelCond->Set(i - 1, new (alloc) JitExpandArrayStack<LC_Condition>(alloc));
}
return levelCond;
}
#ifdef DEBUG
void LoopCloneContext::PrintBlockConditions(unsigned loopNum)
{
printf("Block conditions:\n");
JitExpandArrayStack<JitExpandArrayStack<LC_Condition>*>* blockConds = blockConditions[loopNum];
if (blockConds == nullptr || blockConds->Size() == 0)
{
printf("No block conditions\n");
return;
}
for (unsigned i = 0; i < blockConds->Size(); ++i)
{
PrintBlockLevelConditions(i, (*blockConds)[i]);
}
}
void LoopCloneContext::PrintBlockLevelConditions(unsigned level, JitExpandArrayStack<LC_Condition>* levelCond)
{
printf("%d = ", level);
for (unsigned j = 0; j < levelCond->Size(); ++j)
{
if (j != 0)
{
printf(" && ");
}
printf("(");
(*levelCond)[j].Print();
printf(")");
}
printf("\n");
}
#endif
//--------------------------------------------------------------------------------------------------
// EvaluateConditions - Evaluate the loop cloning conditions statically, if they can be evaluated.
//
// Arguments:
// loopNum the loop index.
// pAllTrue OUT parameter. `*pAllTrue` is set to `true` if all the cloning conditions statically
// evaluate to true.
// pAnyFalse OUT parameter. `*pAnyFalse` is set to `true` if some cloning condition statically
// evaluate to false.
// verbose verbose logging required.
//
// Return Values:
// None.
//
// Operation:
// For example, a condition like "V02 >= V02" statically evaluates to true. Caller should detect such
// conditions and remove them from the "conditions" array.
//
// Similarly, conditions like "V02 > V02" will evaluate to "false". In this case caller has to abort
// loop cloning optimization for the loop. Note that the assumption for conditions is that they will
// all be "AND"ed, so statically we know we will never take the fast path.
//
// Sometimes we simply can't say statically whether "V02 > V01.length" is true or false.
// In that case, `*pAllTrue` will be false because this condition doesn't evaluate to "true" and
// `*pAnyFalse` could be false if no other condition statically evaluates to "false".
//
// If `*pAnyFalse` is true, we set that and return, and `*pAllTrue` is not accurate, since the loop cloning
// needs to be aborted.
//
void LoopCloneContext::EvaluateConditions(unsigned loopNum, bool* pAllTrue, bool* pAnyFalse DEBUGARG(bool verbose))
{
bool allTrue = true;
bool anyFalse = false;
JitExpandArrayStack<LC_Condition>& conds = *conditions[loopNum];
JITDUMP("Evaluating %d loop cloning conditions for loop " FMT_LP "\n", conds.Size(), loopNum);
assert(conds.Size() > 0);
for (unsigned i = 0; i < conds.Size(); ++i)
{
#ifdef DEBUG
if (verbose)
{
printf("Considering condition %d: (", i);
conds[i].Print();
}
#endif
bool res = false;
// Check if this condition evaluates to true or false.
if (conds[i].Evaluates(&res))
{
JITDUMP(") evaluates to %s\n", dspBool(res));
if (!res)
{
anyFalse = true;
// Since this will force us to abort loop cloning, there is no need compute an accurate `allTrue`,
// so we can break out of the loop now.
break;
}
}
else
{
JITDUMP("), could not be evaluated\n");
allTrue = false;
}
}
JITDUMP("Evaluation result allTrue = %s, anyFalse = %s\n", dspBool(allTrue), dspBool(anyFalse));
*pAllTrue = allTrue;
*pAnyFalse = anyFalse;
}
//--------------------------------------------------------------------------------------------------
// OptimizeConditions - Evaluate the loop cloning conditions statically, if they can be evaluated
// then optimize the "conditions" array accordingly.
//
// Arguments:
// conds The conditions array to optimize.
//
// Return Values:
// None.
//
// Operation:
// For example, a condition like "V02 >= V02" statically evaluates to true. Remove such conditions
// from the "conditions" array.
//
// Similarly, conditions like "V02 > V02" will evaluate to "false". In this case abort loop cloning
// optimization for the loop.
//
// Sometimes, two conditions will combine together to yield a single condition, then remove a
// duplicate condition.
void LoopCloneContext::OptimizeConditions(JitExpandArrayStack<LC_Condition>& conds)
{
for (unsigned i = 0; i < conds.Size(); ++i)
{
// Check if the conditions evaluate.
bool result = false;
if (conds[i].Evaluates(&result))
{
// If statically known to be true, then remove this condition.
if (result)
{
conds.Remove(i);
--i;
continue;
}
else
{
// Some condition is statically false, then simply indicate
// not to clone this loop.
CancelLoopOptInfo(i);
break;
}
}
// Check for all other conditions[j], if it would combine with
// conditions[i].
for (unsigned j = i + 1; j < conds.Size(); ++j)
{
LC_Condition newCond;
if (conds[i].Combines(conds[j], &newCond))
{
conds.Remove(j);
conds[i] = newCond;
i = -1;
break;
}
}
}
#ifdef DEBUG
// Make sure we didn't miss some combining.
for (unsigned i = 0; i < conds.Size(); ++i)
{
for (unsigned j = 0; j < conds.Size(); ++j)
{
LC_Condition newCond;
if ((i != j) && conds[i].Combines(conds[j], &newCond))
{
assert(!"Loop cloning conditions can still be optimized further.");
}
}
}
#endif
}
//--------------------------------------------------------------------------------------------------
// OptimizeBlockConditions - Optimize block level conditions.
//
// Arguments:
// loopNum the loop index.
//
// Operation:
// Calls OptimizeConditions helper on block level conditions.
//
// Return Values:
// None.
//
void LoopCloneContext::OptimizeBlockConditions(unsigned loopNum DEBUGARG(bool verbose))
{
if (!HasBlockConditions(loopNum))
{
return;
}
JitExpandArrayStack<JitExpandArrayStack<LC_Condition>*>* levelCond = blockConditions[loopNum];
for (unsigned i = 0; i < levelCond->Size(); ++i)
{
OptimizeConditions(*((*levelCond)[i]));
}
#ifdef DEBUG
if (verbose)
{
printf("After optimizing block-level cloning conditions\n\t");
PrintConditions(loopNum);
printf("\n");
}
#endif
}
//--------------------------------------------------------------------------------------------------
// OptimizeConditions - Optimize cloning conditions.
//
// Arguments:
// loopNum the loop index.
// verbose verbose logging required.
//
// Operation:
// Calls OptimizeConditions helper on cloning conditions.
//
// Return Values:
// None.
//
void LoopCloneContext::OptimizeConditions(unsigned loopNum DEBUGARG(bool verbose))
{
#ifdef DEBUG
if (verbose)
{
printf("Before optimizing cloning conditions\n\t");
PrintConditions(loopNum);
printf("\n");
}
#endif
JitExpandArrayStack<LC_Condition>& conds = *conditions[loopNum];
OptimizeConditions(conds);
#ifdef DEBUG
if (verbose)
{
printf("After optimizing cloning conditions\n\t");
PrintConditions(loopNum);
printf("\n");
}
#endif
}
#ifdef DEBUG
//--------------------------------------------------------------------------------------------------
// PrintConditions - Print loop cloning conditions necessary to clone the loop.
//
// Arguments:
// loopNum the loop index.
//
// Return Values:
// None.
//
void LoopCloneContext::PrintConditions(unsigned loopNum)
{
if (conditions[loopNum] == nullptr)
{
printf("NO conditions");
return;
}
if (conditions[loopNum]->Size() == 0)
{
printf("Conditions were optimized away! Will always take cloned path.");
return;
}
for (unsigned i = 0; i < conditions[loopNum]->Size(); ++i)
{
if (i != 0)
{
printf(" && ");
}
printf("(");
(*conditions[loopNum])[i].Print();
printf(")");
}
}
#endif
//--------------------------------------------------------------------------------------------------
// GetLoopIterInfo: Get the analyzed loop iteration for a loop.
//
// Arguments:
// loopNum - Index of loop, as returned by FlowGraphNaturalLoop::GetIndex().
//
// Returns:
// The info, or nullptr if the loop iteration structure could not be
// analyzed.
//
NaturalLoopIterInfo* LoopCloneContext::GetLoopIterInfo(unsigned loopNum)
{
return iterInfo[loopNum];
}
//--------------------------------------------------------------------------------------------------
// SetLoopIterInfo: Set the analyzed loop iteration for a loop.
//
// Arguments:
// loopNum - Index of loop, as returned by FlowGraphNaturalLoop::GetIndex().
// info - Info to store
//
void LoopCloneContext::SetLoopIterInfo(unsigned loopNum, NaturalLoopIterInfo* info)
{
iterInfo[loopNum] = info;
}
//--------------------------------------------------------------------------------------------------
// CondToStmtInBlock: Convert an array of conditions to IR. Evaluate them into a JTRUE stmt and add it to
// a new block after `insertAfter`.
//
// Arguments:
// comp - Compiler instance
// conds - Array of conditions to evaluate into a JTRUE stmt
// slowPreheader - Branch here on condition failure
// insertAfter - Insert the conditions in a block after this block
//
// Notes:
// If any condition fails, branch to the `slowPreheader` block. There are two options here:
// 1. Generate all the conditions in a single block using bitwise `&` to merge them, e.g.:
// jmpTrue(cond1 & cond2 ... == 0) => slowPreheader
// In this form, we always execute all the conditions (there is no short-circuit evaluation).
// Since we expect that in the usual case all the conditions will fail, and we'll execute the
// loop fast path, the lack of short-circuit evaluation is not a problem. If the code is smaller
// and faster, this would be preferable.
// 2. Generate each condition in a separate block, e.g.:
// jmpTrue(!cond1) => slowPreheader
// jmpTrue(!cond2) => slowPreheader
// ...
// If this code is smaller/faster, this can be preferable. Also, the flow graph is more normal,
// and amenable to downstream flow optimizations.
//
// Which option we choose is currently compile-time determined.
//
// We assume that `insertAfter` is in the same loop (we can clone its loop
// number). If `insertAfter` is a fallthrough block then a predecessor
// link is added.
//
// Return Value:
// Last block added
//
BasicBlock* LoopCloneContext::CondToStmtInBlock(Compiler* comp,
JitExpandArrayStack<LC_Condition>& conds,
BasicBlock* slowPreheader,
BasicBlock* insertAfter)
{
noway_assert(conds.Size() > 0);
assert(slowPreheader != nullptr);
// For now assume high likelihood for the fast path,
// uniformly spread across the gating branches.
//
// For "normal" cloning this is probably ok. For GDV cloning this
// may be inaccurate. We should key off the type test likelihood(s).
//
const weight_t fastLikelihood = fastPathWeightScaleFactor;
// N = conds.Size() branches must all be true to execute the fast loop.
// Use the N'th root....
//
const weight_t fastLikelihoodPerBlock = exp(log(fastLikelihood) / (weight_t)conds.Size());
for (unsigned i = 0; i < conds.Size(); ++i)
{
BasicBlock* newBlk = comp->fgNewBBafter(BBJ_COND, insertAfter, /*extendRegion*/ true);
newBlk->inheritWeight(insertAfter);
JITDUMP("Adding " FMT_BB " -> " FMT_BB "\n", newBlk->bbNum, slowPreheader->bbNum);
FlowEdge* const trueEdge = comp->fgAddRefPred(slowPreheader, newBlk);
newBlk->SetTrueEdge(trueEdge);
trueEdge->setLikelihood(1 - fastLikelihoodPerBlock);
if (insertAfter->KindIs(BBJ_COND))
{
JITDUMP("Adding " FMT_BB " -> " FMT_BB "\n", insertAfter->bbNum, newBlk->bbNum);
FlowEdge* const falseEdge = comp->fgAddRefPred(newBlk, insertAfter);
insertAfter->SetFalseEdge(falseEdge);
falseEdge->setLikelihood(fastLikelihoodPerBlock);
}
JITDUMP("Adding conditions %u to " FMT_BB "\n", i, newBlk->bbNum);
GenTree* cond = conds[i].ToGenTree(comp, newBlk, /* invert */ true);
cond->gtFlags |= (GTF_RELOP_JMP_USED | GTF_DONT_CSE);
GenTree* jmpTrueTree = comp->gtNewOperNode(GT_JTRUE, TYP_VOID, cond);
Statement* stmt = comp->fgNewStmtFromTree(jmpTrueTree);
comp->fgInsertStmtAtEnd(newBlk, stmt);
insertAfter = newBlk;
}
return insertAfter;
}
//--------------------------------------------------------------------------------------------------
// Lcl - the current node's local variable.
//
// Arguments:
// None.
//
// Operation:
// If level is 0, then just return the array base. Else return the index variable on dim 'level'
//
// Return Values:
// The local variable in the node's level.
//
unsigned LC_ArrayDeref::Lcl()
{
unsigned lvl = level;
if (lvl == 0)
{
return array.arrIndex->arrLcl;
}
lvl--;
return array.arrIndex->indLcls[lvl];
}
//--------------------------------------------------------------------------------------------------
// HasChildren - Check if there are children to 'this' node.
//
// Arguments:
// None.
//
// Return Values:
// Return true if children are present.
//
bool LC_ArrayDeref::HasChildren()
{
return children != nullptr && children->Size() > 0;
}
//--------------------------------------------------------------------------------------------------
// DeriveLevelConditions - Generate conditions for each level of the tree.
//
// Arguments:
// conds An array of conditions for each level i.e., (level x conditions). This array will
// contain the conditions for the tree at the end of the method.
//
// Operation:
// level0 yields only (a != null) condition. All other levels yield two conditions:
// (level < a[...].length && a[...][level] != null)
//
// Return Values:
// None
//
void LC_ArrayDeref::DeriveLevelConditions(JitExpandArrayStack<JitExpandArrayStack<LC_Condition>*>* conds)
{
if (level == 0)
{
// For level 0, just push (a != null).
(*conds)[level]->Push(
LC_Condition(GT_NE, LC_Expr(LC_Ident::CreateVar(Lcl())), LC_Expr(LC_Ident::CreateNull())));
}
else
{
// Adjust for level0 having just 1 condition and push conditions (i >= 0) && (i < a.len).
// We fold the two compares into one using unsigned compare, since we know a.len is non-negative.
//
LC_Array arrLen = array;
arrLen.oper = LC_Array::ArrLen;
arrLen.dim = level - 1;
(*conds)[level * 2 - 1]->Push(LC_Condition(GT_LT, LC_Expr(LC_Ident::CreateVar(Lcl())),
LC_Expr(LC_Ident::CreateArrAccess(arrLen)), /*unsigned*/ true));
// Push condition (a[i] != null)
LC_Array arrTmp = array;
arrTmp.dim = level;
(*conds)[level * 2]->Push(
LC_Condition(GT_NE, LC_Expr(LC_Ident::CreateArrAccess(arrTmp)), LC_Expr(LC_Ident::CreateNull())));
}
// Invoke on the children recursively.
if (HasChildren())
{
for (unsigned i = 0; i < children->Size(); ++i)
{
(*children)[i]->DeriveLevelConditions(conds);
}
}
}
//--------------------------------------------------------------------------------------------------
// EnsureChildren - Create an array of child nodes if nullptr.
//
// Arguments:
// alloc CompAllocator instance
//
// Return Values:
// None
//