This repository has been archived by the owner on Jan 23, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
optcse.cpp
2766 lines (2327 loc) · 88.7 KB
/
optcse.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.
// See the LICENSE file in the project root for more information.
/*XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XX
XX OptCSE XX
XX XX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
*/
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
/*****************************************************************************/
#if FEATURE_ANYCSE
/*****************************************************************************/
/* static */
const size_t Compiler::s_optCSEhashSize = EXPSET_SZ * 2;
/*****************************************************************************
*
* We've found all the candidates, build the index for easy access.
*/
void Compiler::optCSEstop()
{
if (optCSECandidateCount == 0)
{
return;
}
CSEdsc* dsc;
CSEdsc** ptr;
unsigned cnt;
optCSEtab = new (this, CMK_CSE) CSEdsc*[optCSECandidateCount]();
for (cnt = s_optCSEhashSize, ptr = optCSEhash; cnt; cnt--, ptr++)
{
for (dsc = *ptr; dsc; dsc = dsc->csdNextInBucket)
{
if (dsc->csdIndex)
{
noway_assert((unsigned)dsc->csdIndex <= optCSECandidateCount);
if (optCSEtab[dsc->csdIndex - 1] == nullptr)
{
optCSEtab[dsc->csdIndex - 1] = dsc;
}
}
}
}
#ifdef DEBUG
for (cnt = 0; cnt < optCSECandidateCount; cnt++)
{
noway_assert(optCSEtab[cnt] != nullptr);
}
#endif
}
/*****************************************************************************
*
* Return the descriptor for the CSE with the given index.
*/
inline Compiler::CSEdsc* Compiler::optCSEfindDsc(unsigned index)
{
noway_assert(index);
noway_assert(index <= optCSECandidateCount);
noway_assert(optCSEtab[index - 1]);
return optCSEtab[index - 1];
}
/*****************************************************************************
*
* For a previously marked CSE, decrement the use counts and unmark it
*/
void Compiler::optUnmarkCSE(GenTreePtr tree)
{
if (!IS_CSE_INDEX(tree->gtCSEnum))
{
// This tree is not a CSE candidate, so there is nothing
// to do.
return;
}
unsigned CSEnum = GET_CSE_INDEX(tree->gtCSEnum);
CSEdsc* desc;
// make sure it's been initialized
noway_assert(optCSEweight <= BB_MAX_WEIGHT);
/* Is this a CSE use? */
if (IS_CSE_USE(tree->gtCSEnum))
{
desc = optCSEfindDsc(CSEnum);
#ifdef DEBUG
if (verbose)
{
printf("Unmark CSE use #%02d at ", CSEnum);
printTreeID(tree);
printf(": %3d -> %3d\n", desc->csdUseCount, desc->csdUseCount - 1);
}
#endif
/* Reduce the nested CSE's 'use' count */
noway_assert(desc->csdUseCount > 0);
if (desc->csdUseCount > 0)
{
desc->csdUseCount -= 1;
if (desc->csdUseWtCnt < optCSEweight)
{
desc->csdUseWtCnt = 0;
}
else
{
desc->csdUseWtCnt -= optCSEweight;
}
}
}
else
{
desc = optCSEfindDsc(CSEnum);
#ifdef DEBUG
if (verbose)
{
printf("Unmark CSE def #%02d at ", CSEnum);
printTreeID(tree);
printf(": %3d -> %3d\n", desc->csdDefCount, desc->csdDefCount - 1);
}
#endif
/* Reduce the nested CSE's 'def' count */
noway_assert(desc->csdDefCount > 0);
if (desc->csdDefCount > 0)
{
desc->csdDefCount -= 1;
if (desc->csdDefWtCnt < optCSEweight)
{
desc->csdDefWtCnt = 0;
}
else
{
desc->csdDefWtCnt -= optCSEweight;
}
}
}
tree->gtCSEnum = NO_CSE;
}
Compiler::fgWalkResult Compiler::optHasNonCSEChild(GenTreePtr* pTree, fgWalkData* data)
{
if (*pTree == data->pCallbackData)
{
return WALK_CONTINUE;
}
if ((*pTree)->gtFlags & GTF_DONT_CSE)
{
// Fix 392756 WP7 Crossgen
// Don't propagate the GTF_DONT_CSE flag up from a GT_CNS_INT
//
// During codegen optGetArrayRefScaleAndIndex() makes the assumption that op2 of a GT_MUL node
// is a constant and is not capable of handling CSE'ing the elemSize constant into a lclvar.
// Hence to prevent the constant from becoming a CSE we have marked it as NO_CSE, but this
// should not prevent tree's above the constant from becoming CSE's.
//
if ((*pTree)->gtOper == GT_CNS_INT)
{
return WALK_SKIP_SUBTREES;
}
return WALK_ABORT;
}
return WALK_SKIP_SUBTREES;
}
Compiler::fgWalkResult Compiler::optPropagateNonCSE(GenTreePtr* pTree, fgWalkData* data)
{
GenTree* tree = *pTree;
Compiler* comp = data->compiler;
/* Calls get DONT_CSE implicitly */
if (tree->OperGet() == GT_CALL)
{
if (!IsSharedStaticHelper(tree))
{
tree->gtFlags |= GTF_DONT_CSE;
}
}
if ((tree->gtFlags & GTF_DONT_CSE) == 0)
{
/* Propagate the DONT_CSE flag from child to parent */
if (comp->fgWalkTreePre(&tree, optHasNonCSEChild, tree) == WALK_ABORT)
{
tree->gtFlags |= GTF_DONT_CSE;
}
}
return WALK_CONTINUE;
}
/*****************************************************************************
*
* Helper passed to Compiler::fgWalkAllTreesPre() to unmark nested CSE's.
*/
/* static */
Compiler::fgWalkResult Compiler::optUnmarkCSEs(GenTreePtr* pTree, fgWalkData* data)
{
GenTreePtr tree = *pTree;
Compiler* comp = data->compiler;
GenTreePtr keepList = (GenTreePtr)(data->pCallbackData);
// We may have a non-NULL side effect list that is being kept
//
if (keepList)
{
GenTreePtr keptTree = keepList;
while (keptTree->OperGet() == GT_COMMA)
{
assert(keptTree->OperKind() & GTK_SMPOP);
GenTreePtr op1 = keptTree->gtOp.gtOp1;
GenTreePtr op2 = keptTree->gtGetOp2();
// For the GT_COMMA case the op1 is part of the orginal CSE tree
// that is being kept because it contains some side-effect
//
if (tree == op1)
{
// This tree and all of its sub trees are being kept
return WALK_SKIP_SUBTREES;
}
// For the GT_COMMA case the op2 are the remaining side-effects of the orginal CSE tree
// which can again be another GT_COMMA or the final side-effect part
//
keptTree = op2;
}
if (tree == keptTree)
{
// This tree and all of its sub trees are being kept
return WALK_SKIP_SUBTREES;
}
}
// This node is being removed from the graph of GenTreePtr
// Call optUnmarkCSE and decrement the LclVar ref counts.
comp->optUnmarkCSE(tree);
assert(!IS_CSE_INDEX(tree->gtCSEnum));
/* Look for any local variable references */
if (tree->gtOper == GT_LCL_VAR)
{
unsigned lclNum;
LclVarDsc* varDsc;
/* This variable ref is going away, decrease its ref counts */
lclNum = tree->gtLclVarCommon.gtLclNum;
assert(lclNum < comp->lvaCount);
varDsc = comp->lvaTable + lclNum;
// make sure it's been initialized
assert(comp->optCSEweight <= BB_MAX_WEIGHT);
/* Decrement its lvRefCnt and lvRefCntWtd */
varDsc->decRefCnts(comp->optCSEweight, comp);
}
return WALK_CONTINUE;
}
Compiler::fgWalkResult Compiler::optCSE_MaskHelper(GenTreePtr* pTree, fgWalkData* walkData)
{
GenTree* tree = *pTree;
Compiler* comp = walkData->compiler;
optCSE_MaskData* pUserData = (optCSE_MaskData*)(walkData->pCallbackData);
if (IS_CSE_INDEX(tree->gtCSEnum))
{
unsigned cseIndex = GET_CSE_INDEX(tree->gtCSEnum);
unsigned cseBit = genCSEnum2bit(cseIndex);
if (IS_CSE_DEF(tree->gtCSEnum))
{
BitVecOps::AddElemD(comp->cseTraits, pUserData->CSE_defMask, cseBit);
}
else
{
BitVecOps::AddElemD(comp->cseTraits, pUserData->CSE_useMask, cseBit);
}
}
return WALK_CONTINUE;
}
// This functions walks all the node for an given tree
// and return the mask of CSE defs and uses for the tree
//
void Compiler::optCSE_GetMaskData(GenTreePtr tree, optCSE_MaskData* pMaskData)
{
pMaskData->CSE_defMask = BitVecOps::MakeEmpty(cseTraits);
pMaskData->CSE_useMask = BitVecOps::MakeEmpty(cseTraits);
fgWalkTreePre(&tree, optCSE_MaskHelper, (void*)pMaskData);
}
//------------------------------------------------------------------------
// optCSE_canSwap: Determine if the execution order of two nodes can be swapped.
//
// Arguments:
// op1 - The first node
// op2 - The second node
//
// Return Value:
// Return true iff it safe to swap the execution order of 'op1' and 'op2',
// considering only the locations of the CSE defs and uses.
//
// Assumptions:
// 'op1' currently occurse before 'op2' in the execution order.
//
bool Compiler::optCSE_canSwap(GenTree* op1, GenTree* op2)
{
// op1 and op2 must be non-null.
assert(op1 != nullptr);
assert(op2 != nullptr);
bool canSwap = true; // the default result unless proven otherwise.
optCSE_MaskData op1MaskData;
optCSE_MaskData op2MaskData;
optCSE_GetMaskData(op1, &op1MaskData);
optCSE_GetMaskData(op2, &op2MaskData);
// We cannot swap if op1 contains a CSE def that is used by op2
if (!BitVecOps::IsEmptyIntersection(cseTraits, op1MaskData.CSE_defMask, op2MaskData.CSE_useMask))
{
canSwap = false;
}
else
{
// We also cannot swap if op2 contains a CSE def that is used by op1.
if (!BitVecOps::IsEmptyIntersection(cseTraits, op2MaskData.CSE_defMask, op1MaskData.CSE_useMask))
{
canSwap = false;
}
}
return canSwap;
}
//------------------------------------------------------------------------
// optCSE_canSwap: Determine if the execution order of a node's operands can be swapped.
//
// Arguments:
// tree - The node of interest
//
// Return Value:
// Return true iff it safe to swap the execution order of the operands of 'tree',
// considering only the locations of the CSE defs and uses.
//
bool Compiler::optCSE_canSwap(GenTreePtr tree)
{
// We must have a binary treenode with non-null op1 and op2
assert((tree->OperKind() & GTK_SMPOP) != 0);
GenTreePtr op1 = tree->gtOp.gtOp1;
GenTreePtr op2 = tree->gtGetOp2();
return optCSE_canSwap(op1, op2);
}
/*****************************************************************************
*
* Compare function passed to qsort() by CSE_Heuristic::SortCandidates
* when (CodeOptKind() != Compiler::SMALL_CODE)
*/
/* static */
int __cdecl Compiler::optCSEcostCmpEx(const void* op1, const void* op2)
{
CSEdsc* dsc1 = *(CSEdsc**)op1;
CSEdsc* dsc2 = *(CSEdsc**)op2;
GenTreePtr exp1 = dsc1->csdTree;
GenTreePtr exp2 = dsc2->csdTree;
int diff;
diff = (int)(exp2->gtCostEx - exp1->gtCostEx);
if (diff != 0)
{
return diff;
}
// Sort the higher Use Counts toward the top
diff = (int)(dsc2->csdUseWtCnt - dsc1->csdUseWtCnt);
if (diff != 0)
{
return diff;
}
// With the same use count, Sort the lower Def Counts toward the top
diff = (int)(dsc1->csdDefWtCnt - dsc2->csdDefWtCnt);
if (diff != 0)
{
return diff;
}
// In order to ensure that we have a stable sort, we break ties using the csdIndex
return (int)(dsc1->csdIndex - dsc2->csdIndex);
}
/*****************************************************************************
*
* Compare function passed to qsort() by CSE_Heuristic::SortCandidates
* when (CodeOptKind() == Compiler::SMALL_CODE)
*/
/* static */
int __cdecl Compiler::optCSEcostCmpSz(const void* op1, const void* op2)
{
CSEdsc* dsc1 = *(CSEdsc**)op1;
CSEdsc* dsc2 = *(CSEdsc**)op2;
GenTreePtr exp1 = dsc1->csdTree;
GenTreePtr exp2 = dsc2->csdTree;
int diff;
diff = (int)(exp2->gtCostSz - exp1->gtCostSz);
if (diff != 0)
{
return diff;
}
// Sort the higher Use Counts toward the top
diff = (int)(dsc2->csdUseCount - dsc1->csdUseCount);
if (diff != 0)
{
return diff;
}
// With the same use count, Sort the lower Def Counts toward the top
diff = (int)(dsc1->csdDefCount - dsc2->csdDefCount);
if (diff != 0)
{
return diff;
}
// In order to ensure that we have a stable sort, we break ties using the csdIndex
return (int)(dsc1->csdIndex - dsc2->csdIndex);
}
/*****************************************************************************/
#if FEATURE_VALNUM_CSE
/*****************************************************************************/
/*****************************************************************************
*
* Initialize the Value Number CSE tracking logic.
*/
void Compiler::optValnumCSE_Init()
{
#ifdef DEBUG
optCSEtab = nullptr;
#endif
// Init traits and full/empty bitvectors. This will be used to track the
// individual cse indexes.
cseTraits = new (getAllocator()) BitVecTraits(EXPSET_SZ, this);
cseFull = BitVecOps::MakeFull(cseTraits);
/* Allocate and clear the hash bucket table */
optCSEhash = new (this, CMK_CSE) CSEdsc*[s_optCSEhashSize]();
optCSECandidateCount = 0;
optDoCSE = false; // Stays false until we find duplicate CSE tree
// optCseCheckedBoundMap is unused in most functions, allocated only when used
optCseCheckedBoundMap = nullptr;
}
/*****************************************************************************
*
* Assign an index to the given expression (adding it to the lookup table,
* if necessary). Returns the index or 0 if the expression can not be a CSE.
*/
unsigned Compiler::optValnumCSE_Index(GenTreePtr tree, GenTreePtr stmt)
{
unsigned key;
unsigned hash;
unsigned hval;
CSEdsc* hashDsc;
ValueNum vnlib = tree->GetVN(VNK_Liberal);
/* Compute the hash value for the expression */
key = (unsigned)vnlib;
hash = key;
hash *= (unsigned)(s_optCSEhashSize + 1);
hash >>= 7;
hval = hash % s_optCSEhashSize;
/* Look for a matching index in the hash table */
bool newCSE = false;
for (hashDsc = optCSEhash[hval]; hashDsc; hashDsc = hashDsc->csdNextInBucket)
{
if (hashDsc->csdHashValue == key)
{
treeStmtLstPtr newElem;
/* Have we started the list of matching nodes? */
if (hashDsc->csdTreeList == nullptr)
{
// Create the new element based upon the matching hashDsc element.
newElem = new (this, CMK_TreeStatementList) treeStmtLst;
newElem->tslTree = hashDsc->csdTree;
newElem->tslStmt = hashDsc->csdStmt;
newElem->tslBlock = hashDsc->csdBlock;
newElem->tslNext = nullptr;
/* Start the list with the first CSE candidate recorded */
hashDsc->csdTreeList = newElem;
hashDsc->csdTreeLast = newElem;
}
noway_assert(hashDsc->csdTreeList);
/* Append this expression to the end of the list */
newElem = new (this, CMK_TreeStatementList) treeStmtLst;
newElem->tslTree = tree;
newElem->tslStmt = stmt;
newElem->tslBlock = compCurBB;
newElem->tslNext = nullptr;
hashDsc->csdTreeLast->tslNext = newElem;
hashDsc->csdTreeLast = newElem;
optDoCSE = true; // Found a duplicate CSE tree
/* Have we assigned a CSE index? */
if (hashDsc->csdIndex == 0)
{
newCSE = true;
break;
}
#if 0
// Use this to see if this Value Number base CSE is also a lexical CSE
bool treeMatch = GenTree::Compare(hashDsc->csdTree, tree, true);
#endif
assert(FitsIn<signed char>(hashDsc->csdIndex));
tree->gtCSEnum = ((signed char)hashDsc->csdIndex);
return hashDsc->csdIndex;
}
}
if (!newCSE)
{
/* Not found, create a new entry (unless we have too many already) */
if (optCSECandidateCount < MAX_CSE_CNT)
{
hashDsc = new (this, CMK_CSE) CSEdsc;
hashDsc->csdHashValue = key;
hashDsc->csdIndex = 0;
hashDsc->csdLiveAcrossCall = 0;
hashDsc->csdDefCount = 0;
hashDsc->csdUseCount = 0;
hashDsc->csdDefWtCnt = 0;
hashDsc->csdUseWtCnt = 0;
hashDsc->csdTree = tree;
hashDsc->csdStmt = stmt;
hashDsc->csdBlock = compCurBB;
hashDsc->csdTreeList = nullptr;
/* Append the entry to the hash bucket */
hashDsc->csdNextInBucket = optCSEhash[hval];
optCSEhash[hval] = hashDsc;
}
return 0;
}
else // newCSE is true
{
/* We get here only after finding a matching CSE */
/* Create a new CSE (unless we have the maximum already) */
if (optCSECandidateCount == MAX_CSE_CNT)
{
return 0;
}
C_ASSERT((signed char)MAX_CSE_CNT == MAX_CSE_CNT);
unsigned CSEindex = ++optCSECandidateCount;
// EXPSET_TP CSEmask = genCSEnum2bit(CSEindex);
/* Record the new CSE index in the hashDsc */
hashDsc->csdIndex = CSEindex;
/* Update the gtCSEnum field in the original tree */
noway_assert(hashDsc->csdTreeList->tslTree->gtCSEnum == 0);
assert(FitsIn<signed char>(CSEindex));
hashDsc->csdTreeList->tslTree->gtCSEnum = ((signed char)CSEindex);
noway_assert(((unsigned)hashDsc->csdTreeList->tslTree->gtCSEnum) == CSEindex);
tree->gtCSEnum = ((signed char)CSEindex);
#ifdef DEBUG
if (verbose)
{
EXPSET_TP tempMask = BitVecOps::MakeSingleton(cseTraits, genCSEnum2bit(CSEindex));
printf("\nCSE candidate #%02u, vn=", CSEindex);
vnPrint(vnlib, 0);
printf(" cseMask=%s in BB%02u, [cost=%2u, size=%2u]: \n", genES2str(cseTraits, tempMask), compCurBB->bbNum,
tree->gtCostEx, tree->gtCostSz);
gtDispTree(tree);
}
#endif // DEBUG
return CSEindex;
}
}
/*****************************************************************************
*
* Locate CSE candidates and assign indices to them
* return 0 if no CSE candidates were found
* Also initialize bbCseIn, bbCseout and bbCseGen sets for all blocks
*/
unsigned Compiler::optValnumCSE_Locate()
{
// Locate CSE candidates and assign them indices
for (BasicBlock* block = fgFirstBB; block; block = block->bbNext)
{
GenTreePtr stmt;
GenTreePtr tree;
/* Make the block publicly available */
compCurBB = block;
/* Ensure that the BBF_VISITED and BBF_MARKED flag are clear */
/* Everyone who uses these flags are required to clear afterwards */
noway_assert((block->bbFlags & (BBF_VISITED | BBF_MARKED)) == 0);
/* Walk the statement trees in this basic block */
for (stmt = block->FirstNonPhiDef(); stmt; stmt = stmt->gtNext)
{
noway_assert(stmt->gtOper == GT_STMT);
/* We walk the tree in the forwards direction (bottom up) */
bool stmtHasArrLenCandidate = false;
for (tree = stmt->gtStmt.gtStmtList; tree; tree = tree->gtNext)
{
if (tree->OperIsCompare() && stmtHasArrLenCandidate)
{
// Check if this compare is a function of (one of) the checked
// bound candidate(s); we may want to update its value number.
// if the array length gets CSEd
optCseUpdateCheckedBoundMap(tree);
}
if (!optIsCSEcandidate(tree))
{
continue;
}
ValueNum vnlib = tree->GetVN(VNK_Liberal);
if (ValueNumStore::isReservedVN(vnlib))
{
continue;
}
// Don't CSE constant values, instead let the Value Number
// based Assertion Prop phase handle them.
//
if (vnStore->IsVNConstant(vnlib))
{
continue;
}
/* Assign an index to this expression */
unsigned CSEindex = optValnumCSE_Index(tree, stmt);
if (CSEindex != 0)
{
noway_assert(((unsigned)tree->gtCSEnum) == CSEindex);
}
if (IS_CSE_INDEX(CSEindex) && (tree->OperGet() == GT_ARR_LENGTH))
{
stmtHasArrLenCandidate = true;
}
}
}
}
/* We're done if there were no interesting expressions */
if (!optDoCSE)
{
return 0;
}
/* We're finished building the expression lookup table */
optCSEstop();
return 1;
}
//------------------------------------------------------------------------
// optCseUpdateCheckedBoundMap: Check if this compare is a tractable function of
// a checked bound that is a CSE candidate, and insert
// an entry in the optCseCheckedBoundMap if so. This facilitates
// subsequently updating the compare's value number if
// the bound gets CSEd.
//
// Arguments:
// compare - The compare node to check
void Compiler::optCseUpdateCheckedBoundMap(GenTreePtr compare)
{
assert(compare->OperIsCompare());
ValueNum compareVN = compare->gtVNPair.GetConservative();
VNFuncApp cmpVNFuncApp;
if (!vnStore->GetVNFunc(compareVN, &cmpVNFuncApp) ||
(cmpVNFuncApp.m_func != GetVNFuncForOper(compare->OperGet(), compare->IsUnsigned())))
{
// Value numbering inferred this compare as something other
// than its own operator; leave its value number alone.
return;
}
// Now look for a checked bound feeding the compare
ValueNumStore::CompareCheckedBoundArithInfo info;
GenTreePtr boundParent = nullptr;
if (vnStore->IsVNCompareCheckedBound(compareVN))
{
// Simple compare of an bound against something else.
vnStore->GetCompareCheckedBound(compareVN, &info);
boundParent = compare;
}
else if (vnStore->IsVNCompareCheckedBoundArith(compareVN))
{
// Compare of a bound +/- some offset to something else.
GenTreePtr op1 = compare->gtGetOp1();
GenTreePtr op2 = compare->gtGetOp2();
vnStore->GetCompareCheckedBoundArithInfo(compareVN, &info);
if (GetVNFuncForOper(op1->OperGet(), op1->IsUnsigned()) == (VNFunc)info.arrOper)
{
// The arithmetic node is the bound's parent.
boundParent = op1;
}
else if (GetVNFuncForOper(op2->OperGet(), op2->IsUnsigned()) == (VNFunc)info.arrOper)
{
// The arithmetic node is the bound's parent.
boundParent = op2;
}
}
if (boundParent != nullptr)
{
GenTreePtr bound = nullptr;
// Find which child of boundParent is the bound. Abort if neither
// conservative value number matches the one from the compare VN.
GenTreePtr child1 = boundParent->gtGetOp1();
if ((info.vnBound == child1->gtVNPair.GetConservative()) && IS_CSE_INDEX(child1->gtCSEnum))
{
bound = child1;
}
else
{
GenTreePtr child2 = boundParent->gtGetOp2();
if ((info.vnBound == child2->gtVNPair.GetConservative()) && IS_CSE_INDEX(child2->gtCSEnum))
{
bound = child2;
}
}
if (bound != nullptr)
{
// Found a checked bound feeding a compare that is a tractable function of it;
// record this in the map so we can update the compare VN if the bound
// node gets CSEd.
if (optCseCheckedBoundMap == nullptr)
{
// Allocate map on first use.
optCseCheckedBoundMap = new (getAllocator()) NodeToNodeMap(getAllocator());
}
optCseCheckedBoundMap->Set(bound, compare);
}
}
}
/*****************************************************************************
*
* Compute each blocks bbCseGen
* This is the bitset that represents the CSEs that are generated within the block
*/
void Compiler::optValnumCSE_InitDataFlow()
{
for (BasicBlock* block = fgFirstBB; block; block = block->bbNext)
{
GenTreePtr stmt;
GenTreePtr tree;
/* Initialize the blocks's bbCseIn set */
bool init_to_zero = false;
if (block == fgFirstBB)
{
/* Clear bbCseIn for the entry block */
init_to_zero = true;
}
#if !CSE_INTO_HANDLERS
else
{
if (bbIsHandlerBeg(block))
{
/* Clear everything on entry to filters or handlers */
init_to_zero = true;
}
}
#endif
if (init_to_zero)
{
/* Initialize to {ZERO} prior to dataflow */
block->bbCseIn = BitVecOps::MakeEmpty(cseTraits);
}
else
{
/* Initialize to {ALL} prior to dataflow */
block->bbCseIn = BitVecOps::MakeCopy(cseTraits, cseFull);
}
block->bbCseOut = BitVecOps::MakeCopy(cseTraits, cseFull);
/* Initialize to {ZERO} prior to locating the CSE candidates */
block->bbCseGen = BitVecOps::MakeEmpty(cseTraits);
}
// We walk the set of CSE candidates and set the bit corresponsing to the CSEindex
// in the block's bbCseGen bitset
//
for (unsigned cnt = 0; cnt < optCSECandidateCount; cnt++)
{
CSEdsc* dsc = optCSEtab[cnt];
unsigned CSEindex = dsc->csdIndex;
treeStmtLstPtr lst = dsc->csdTreeList;
noway_assert(lst);
while (lst != nullptr)
{
BasicBlock* block = lst->tslBlock;
BitVecOps::AddElemD(cseTraits, block->bbCseGen, genCSEnum2bit(CSEindex));
lst = lst->tslNext;
}
}
#ifdef DEBUG
// Dump out the bbCseGen information that we just created
//
if (verbose)
{
bool headerPrinted = false;
for (BasicBlock* block = fgFirstBB; block; block = block->bbNext)
{
if (block->bbCseGen != nullptr)
{
if (!headerPrinted)
{
printf("\nBlocks that generate CSE def/uses\n");
headerPrinted = true;
}
printf("BB%02u", block->bbNum);
printf(" cseGen = %s\n", genES2str(cseTraits, block->bbCseGen));
}
}
}
fgDebugCheckLinks();
#endif // DEBUG
}
/*****************************************************************************
*
* CSE Dataflow, so that all helper methods for dataflow are in a single place
*
*/
class CSE_DataFlow
{
BitVecTraits* m_pBitVecTraits;
EXPSET_TP m_preMergeOut;
public:
CSE_DataFlow(Compiler* pCompiler) : m_pBitVecTraits(pCompiler->cseTraits), m_preMergeOut(BitVecOps::UninitVal())
{
}
// At the start of the merge function of the dataflow equations, initialize premerge state (to detect changes.)
void StartMerge(BasicBlock* block)
{
BitVecOps::Assign(m_pBitVecTraits, m_preMergeOut, block->bbCseOut);
}
// During merge, perform the actual merging of the predecessor's (since this is a forward analysis) dataflow flags.
void Merge(BasicBlock* block, BasicBlock* predBlock, flowList* preds)
{
BitVecOps::IntersectionD(m_pBitVecTraits, block->bbCseIn, predBlock->bbCseOut);
}
// At the end of the merge store results of the dataflow equations, in a postmerge state.
bool EndMerge(BasicBlock* block)
{
BitVecOps::DataFlowD(m_pBitVecTraits, block->bbCseOut, block->bbCseGen, block->bbCseIn);
return !BitVecOps::Equal(m_pBitVecTraits, block->bbCseOut, m_preMergeOut);
}
};
/*****************************************************************************
*
* Perform a DataFlow forward analysis using the block CSE bitsets:
* Inputs:
* bbCseGen - Exact CSEs that are become available within the block
* bbCseIn - Maximal estimate of CSEs that are/could be available at input to the block
* bbCseOut - Maximal estimate of CSEs that are/could be available at exit to the block
*
* Outputs:
* bbCseIn - Computed CSEs that are available at input to the block
* bbCseOut - Computed CSEs that are available at exit to the block
*/
void Compiler::optValnumCSE_DataFlow()