forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathssabuilder.cpp
1500 lines (1320 loc) · 56.9 KB
/
ssabuilder.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.
#include "jitpch.h"
#include "ssaconfig.h"
#include "ssarenamestate.h"
#include "ssabuilder.h"
// =================================================================================
// SSA
// =================================================================================
PhaseStatus Compiler::fgSsaBuild()
{
// If this is not the first invocation, reset data structures for SSA.
if (fgSsaPassesCompleted > 0)
{
fgResetForSsa();
}
SsaBuilder builder(this);
builder.Build();
fgSsaPassesCompleted++;
fgSsaValid = true;
#ifdef DEBUG
JitTestCheckSSA();
#endif // DEBUG
return PhaseStatus::MODIFIED_EVERYTHING;
}
void Compiler::fgResetForSsa()
{
for (unsigned i = 0; i < lvaCount; ++i)
{
lvaTable[i].lvPerSsaData.Reset();
}
lvMemoryPerSsaData.Reset();
for (MemoryKind memoryKind : allMemoryKinds())
{
m_memorySsaMap[memoryKind] = nullptr;
}
if (m_outlinedCompositeSsaNums != nullptr)
{
m_outlinedCompositeSsaNums->Reset();
}
for (BasicBlock* const blk : Blocks())
{
// Eliminate phis.
for (MemoryKind memoryKind : allMemoryKinds())
{
blk->bbMemorySsaPhiFunc[memoryKind] = nullptr;
}
if (blk->bbStmtList != nullptr)
{
Statement* last = blk->lastStmt();
blk->bbStmtList = blk->FirstNonPhiDef();
if (blk->bbStmtList != nullptr)
{
blk->bbStmtList->SetPrevStmt(last);
}
}
for (Statement* const stmt : blk->Statements())
{
for (GenTree* const tree : stmt->TreeList())
{
if (tree->IsAnyLocal())
{
tree->AsLclVarCommon()->SetSsaNum(SsaConfig::RESERVED_SSA_NUM);
}
}
}
}
}
/**
* Constructor for the SSA builder.
*
* @param pCompiler Current compiler instance.
*
* @remarks Initializes the class and member pointers/objects that use constructors.
*/
SsaBuilder::SsaBuilder(Compiler* pCompiler)
: m_pCompiler(pCompiler)
, m_allocator(pCompiler->getAllocator(CMK_SSA))
, m_visitedTraits(0, pCompiler) // at this point we do not know the size, SetupBBRoot can add a block
, m_renameStack(m_allocator, pCompiler->lvaCount)
{
}
//------------------------------------------------------------------------
// ComputeDominanceFrontiers: Compute flow graph dominance frontiers
//
// Arguments:
// postOrder - an array containing all flow graph blocks
// count - the number of blocks in the postOrder array
// mapDF - a caller provided hashtable that will be populated
// with blocks and their dominance frontiers (only those
// blocks that have non-empty frontiers will be included)
//
// Notes:
// Recall that the dominance frontier of a block B is the set of blocks
// B3 such that there exists some B2 s.t. B3 is a successor of B2, and
// B dominates B2. Note that this dominance need not be strict -- B2
// and B may be the same node.
// See "A simple, fast dominance algorithm", by Cooper, Harvey, and Kennedy.
//
void SsaBuilder::ComputeDominanceFrontiers(BasicBlock** postOrder, int count, BlkToBlkVectorMap* mapDF)
{
DBG_SSA_JITDUMP("Computing DF:\n");
for (int i = 0; i < count; ++i)
{
BasicBlock* block = postOrder[i];
DBG_SSA_JITDUMP("Considering block " FMT_BB ".\n", block->bbNum);
// Recall that B3 is in the dom frontier of B1 if there exists a B2
// such that B1 dom B2, !(B1 dom B3), and B3 is an immediate successor
// of B2. (Note that B1 might be the same block as B2.)
// In that definition, we're considering "block" to be B3, and trying
// to find B1's. To do so, first we consider the predecessors of "block",
// searching for candidate B2's -- "block" is obviously an immediate successor
// of its immediate predecessors. If there are zero or one preds, then there
// is no pred, or else the single pred dominates "block", so no B2 exists.
FlowEdge* blockPreds = m_pCompiler->BlockPredsWithEH(block);
// If block has 0/1 predecessor, skip, apart from handler entry blocks
// that are always in the dominance frontier of its enclosed blocks.
if (!m_pCompiler->bbIsHandlerBeg(block) &&
((blockPreds == nullptr) || (blockPreds->getNextPredEdge() == nullptr)))
{
DBG_SSA_JITDUMP(" Has %d preds; skipping.\n", blockPreds == nullptr ? 0 : 1);
continue;
}
// Otherwise, there are > 1 preds. Each is a candidate B2 in the definition --
// *unless* it dominates "block"/B3.
FlowGraphDfsTree* dfsTree = m_pCompiler->m_dfsTree;
FlowGraphDominatorTree* domTree = m_pCompiler->m_domTree;
for (FlowEdge* pred = blockPreds; pred != nullptr; pred = pred->getNextPredEdge())
{
BasicBlock* predBlock = pred->getSourceBlock();
DBG_SSA_JITDUMP(" Considering predecessor " FMT_BB ".\n", predBlock->bbNum);
if (!dfsTree->Contains(predBlock))
{
DBG_SSA_JITDUMP(" Unreachable node\n");
continue;
}
// If we've found a B2, then consider the possible B1's. We start with
// B2, since a block dominates itself, then traverse upwards in the dominator
// tree, stopping when we reach the root, or the immediate dominator of "block"/B3.
// (Note that we are guaranteed to encounter this immediate dominator of "block"/B3:
// a predecessor must be dominated by B3's immediate dominator.)
// Along this way, make "block"/B3 part of the dom frontier of the B1.
// When we reach this immediate dominator, the definition no longer applies, since this
// potential B1 *does* dominate "block"/B3, so we stop.
for (BasicBlock* b1 = predBlock; (b1 != nullptr) && (b1 != block->bbIDom); // !root && !loop
b1 = b1->bbIDom)
{
DBG_SSA_JITDUMP(" Adding " FMT_BB " to dom frontier of pred dom " FMT_BB ".\n", block->bbNum,
b1->bbNum);
BlkVector& b1DF = *mapDF->Emplace(b1, m_allocator);
// It's possible to encounter the same DF multiple times, ensure that we don't add duplicates.
if (b1DF.empty() || (b1DF.back() != block))
{
b1DF.push_back(block);
}
}
}
}
#ifdef DEBUG
if (m_pCompiler->verboseSsa)
{
printf("\nComputed DF:\n");
for (int i = 0; i < count; ++i)
{
BasicBlock* b = postOrder[i];
printf("Block " FMT_BB " := {", b->bbNum);
BlkVector* bDF = mapDF->LookupPointer(b);
if (bDF != nullptr)
{
int index = 0;
for (BasicBlock* f : *bDF)
{
printf("%s" FMT_BB, (index++ == 0) ? "" : ",", f->bbNum);
}
}
printf("}\n");
}
}
#endif
}
//------------------------------------------------------------------------
// ComputeIteratedDominanceFrontier: Compute the iterated dominance frontier
// for the specified block.
//
// Arguments:
// b - the block to computed the frontier for
// mapDF - a map containing the dominance frontiers of all blocks
// bIDF - a caller provided vector where the IDF is to be stored
//
// Notes:
// The iterated dominance frontier is formed by a closure operation:
// the IDF of B is the smallest set that includes B's dominance frontier,
// and also includes the dominance frontier of all elements of the set.
//
void SsaBuilder::ComputeIteratedDominanceFrontier(BasicBlock* b, const BlkToBlkVectorMap* mapDF, BlkVector* bIDF)
{
assert(bIDF->empty());
BlkVector* bDF = mapDF->LookupPointer(b);
if (bDF != nullptr)
{
// Compute IDF(b) - start by adding DF(b) to IDF(b).
bIDF->reserve(bDF->size());
BitVecOps::ClearD(&m_visitedTraits, m_visited);
for (BasicBlock* f : *bDF)
{
BitVecOps::AddElemD(&m_visitedTraits, m_visited, f->bbPostorderNum);
bIDF->push_back(f);
}
// Now for each block f from IDF(b) add DF(f) to IDF(b). This may result in new
// blocks being added to IDF(b) and the process repeats until no more new blocks
// are added. Note that since we keep adding to bIDF we can't use iterators as
// they may get invalidated. This happens to be a convenient way to avoid having
// to track newly added blocks in a separate set.
for (size_t newIndex = 0; newIndex < bIDF->size(); newIndex++)
{
BasicBlock* f = (*bIDF)[newIndex];
BlkVector* fDF = mapDF->LookupPointer(f);
if (fDF != nullptr)
{
for (BasicBlock* ff : *fDF)
{
if (BitVecOps::TryAddElemD(&m_visitedTraits, m_visited, ff->bbPostorderNum))
{
bIDF->push_back(ff);
}
}
}
}
}
#ifdef DEBUG
if (m_pCompiler->verboseSsa)
{
printf("IDF(" FMT_BB ") := {", b->bbNum);
int index = 0;
for (BasicBlock* f : *bIDF)
{
printf("%s" FMT_BB, (index++ == 0) ? "" : ",", f->bbNum);
}
printf("}\n");
}
#endif
}
/**
* Returns the phi GT_PHI node if the variable already has a phi node.
*
* @param block The block for which the existence of a phi node needs to be checked.
* @param lclNum The lclNum for which the occurrence of a phi node needs to be checked.
*
* @return If there is a phi node for the lclNum, returns the GT_PHI tree, else NULL.
*/
static GenTree* GetPhiNode(BasicBlock* block, unsigned lclNum)
{
// Walk the statements for phi nodes.
for (Statement* const stmt : block->Statements())
{
// A prefix of the statements of the block are phi definition nodes. If we complete processing
// that prefix, exit.
if (!stmt->IsPhiDefnStmt())
{
break;
}
GenTree* tree = stmt->GetRootNode();
if (tree->AsLclVar()->GetLclNum() == lclNum)
{
return tree->AsLclVar()->Data();
}
}
return nullptr;
}
//------------------------------------------------------------------------
// InsertPhi: Insert a new GT_PHI statement.
//
// Arguments:
// block - The block where to insert the statement
// lclNum - The variable number
//
void SsaBuilder::InsertPhi(BasicBlock* block, unsigned lclNum)
{
var_types type = m_pCompiler->lvaGetDesc(lclNum)->TypeGet();
// PHIs and all the associated nodes do not generate any code so the costs are always 0
GenTree* phi = new (m_pCompiler, GT_PHI) GenTreePhi(type);
phi->SetCosts(0, 0);
GenTree* store = m_pCompiler->gtNewStoreLclVarNode(lclNum, phi);
store->SetCosts(0, 0);
store->gtType = type; // TODO-ASG-Cleanup: delete. This quirk avoided diffs from costing-induced tail dup.
// Create the statement and chain everything in linear order - PHI, STORE_LCL_VAR.
Statement* stmt = m_pCompiler->gtNewStmt(store);
stmt->SetTreeList(phi);
phi->gtNext = store;
store->gtPrev = phi;
#ifdef DEBUG
unsigned seqNum = 1;
for (GenTree* const node : stmt->TreeList())
{
node->gtSeqNum = seqNum++;
}
#endif // DEBUG
m_pCompiler->fgInsertStmtAtBeg(block, stmt);
JITDUMP("Added PHI definition for V%02u at start of " FMT_BB ".\n", lclNum, block->bbNum);
}
//------------------------------------------------------------------------
// AddPhiArg: Ensure an existing GT_PHI node contains an appropriate PhiArg
// for an ssa def arriving via pred
//
// Arguments:
// block - The block that contains the statement
// stmt - The statement that contains the GT_PHI node
// lclNum - The variable number
// ssaNum - The SSA number
// pred - The predecessor block
//
void SsaBuilder::AddPhiArg(
BasicBlock* block, Statement* stmt, GenTreePhi* phi, unsigned lclNum, unsigned ssaNum, BasicBlock* pred)
{
// If there's already a phi arg for this pred, it had better have
// matching ssaNum, unless this block is a handler entry.
//
const bool isHandlerEntry = m_pCompiler->bbIsHandlerBeg(block);
for (GenTreePhi::Use& use : phi->Uses())
{
GenTreePhiArg* const phiArg = use.GetNode()->AsPhiArg();
if (phiArg->gtPredBB == pred)
{
if (phiArg->GetSsaNum() == ssaNum)
{
// We already have this (pred, ssaNum) phiArg
return;
}
// Add another ssaNum for this pred?
// Should only be possible at handler entries.
//
noway_assert(isHandlerEntry);
}
}
// Didn't find a match, add a new phi arg
//
var_types type = m_pCompiler->lvaGetDesc(lclNum)->TypeGet();
GenTree* phiArg = new (m_pCompiler, GT_PHI_ARG) GenTreePhiArg(type, lclNum, ssaNum, pred);
// Costs are not relevant for PHI args.
phiArg->SetCosts(0, 0);
// The argument order doesn't matter so just insert at the front of the list because
// it's easier. It's also easier to insert in linear order since the first argument
// will be first in linear order as well.
phi->gtUses = new (m_pCompiler, CMK_ASTNode) GenTreePhi::Use(phiArg, phi->gtUses);
GenTree* head = stmt->GetTreeList();
assert(head->OperIs(GT_PHI, GT_PHI_ARG));
stmt->SetTreeList(phiArg);
phiArg->gtNext = head;
head->gtPrev = phiArg;
LclVarDsc* const varDsc = m_pCompiler->lvaGetDesc(lclNum);
LclSsaVarDsc* const ssaDesc = varDsc->GetPerSsaData(ssaNum);
ssaDesc->AddPhiUse(block);
#ifdef DEBUG
unsigned seqNum = 1;
for (GenTree* const node : stmt->TreeList())
{
node->gtSeqNum = seqNum++;
}
#endif // DEBUG
DBG_SSA_JITDUMP("Added PHI arg u:%d for V%02u from " FMT_BB " in " FMT_BB ".\n", ssaNum, lclNum, pred->bbNum,
block->bbNum);
}
/**
* Inserts phi functions at DF(b) for variables v that are live after the phi
* insertion point i.e., v in live-in(b).
*
* To do so, the function computes liveness, dominance frontier and inserts a phi node,
* if we have var v in def(b) and live-in(l) and l is in DF(b).
*/
void SsaBuilder::InsertPhiFunctions()
{
JITDUMP("*************** In SsaBuilder::InsertPhiFunctions()\n");
FlowGraphDfsTree* dfsTree = m_pCompiler->m_dfsTree;
BasicBlock** postOrder = dfsTree->GetPostOrder();
unsigned count = dfsTree->GetPostOrderCount();
// Compute dominance frontier.
BlkToBlkVectorMap mapDF(m_allocator);
ComputeDominanceFrontiers(postOrder, count, &mapDF);
EndPhase(PHASE_BUILD_SSA_DF);
// Use the same IDF vector for all blocks to avoid unnecessary memory allocations
BlkVector blockIDF(m_allocator);
JITDUMP("Inserting phi functions:\n");
for (unsigned i = 0; i < count; ++i)
{
BasicBlock* block = postOrder[i];
DBG_SSA_JITDUMP("Considering dominance frontier of block " FMT_BB ":\n", block->bbNum);
blockIDF.clear();
ComputeIteratedDominanceFrontier(block, &mapDF, &blockIDF);
if (blockIDF.empty())
{
continue;
}
// For each local var number "lclNum" that "block" assigns to...
VarSetOps::Iter defVars(m_pCompiler, block->bbVarDef);
unsigned varIndex = 0;
while (defVars.NextElem(&varIndex))
{
unsigned lclNum = m_pCompiler->lvaTrackedIndexToLclNum(varIndex);
DBG_SSA_JITDUMP(" Considering local var V%02u:\n", lclNum);
if (!m_pCompiler->lvaInSsa(lclNum))
{
DBG_SSA_JITDUMP(" Skipping because it is excluded.\n");
continue;
}
// For each block "bbInDomFront" that is in the dominance frontier of "block"...
for (BasicBlock* bbInDomFront : blockIDF)
{
DBG_SSA_JITDUMP(" Considering " FMT_BB " in dom frontier of " FMT_BB ":\n", bbInDomFront->bbNum,
block->bbNum);
// Check if variable "lclNum" is live in block "*iterBlk".
if (!VarSetOps::IsMember(m_pCompiler, bbInDomFront->bbLiveIn, varIndex))
{
continue;
}
// Check if we've already inserted a phi node.
if (GetPhiNode(bbInDomFront, lclNum) == nullptr)
{
// We have a variable i that is defined in block j and live at l, and l belongs to dom frontier of
// j. So insert a phi node at l.
InsertPhi(bbInDomFront, lclNum);
}
}
}
// Now make a similar phi definition if the block defines memory.
if (block->bbMemoryDef != emptyMemoryKindSet)
{
// For each block "bbInDomFront" that is in the dominance frontier of "block".
for (BasicBlock* bbInDomFront : blockIDF)
{
DBG_SSA_JITDUMP(" Considering " FMT_BB " in dom frontier of " FMT_BB " for Memory phis:\n",
bbInDomFront->bbNum, block->bbNum);
for (MemoryKind memoryKind : allMemoryKinds())
{
if ((memoryKind == GcHeap) && m_pCompiler->byrefStatesMatchGcHeapStates)
{
// Share the PhiFunc with ByrefExposed.
assert(memoryKind > ByrefExposed);
bbInDomFront->bbMemorySsaPhiFunc[memoryKind] = bbInDomFront->bbMemorySsaPhiFunc[ByrefExposed];
continue;
}
// Check if this memoryKind is defined in this block.
if ((block->bbMemoryDef & memoryKindSet(memoryKind)) == 0)
{
continue;
}
// Check if memoryKind is live into block "*iterBlk".
if ((bbInDomFront->bbMemoryLiveIn & memoryKindSet(memoryKind)) == 0)
{
continue;
}
// Check if we've already inserted a phi node.
if (bbInDomFront->bbMemorySsaPhiFunc[memoryKind] == nullptr)
{
// We have a variable i that is defined in block j and live at l, and l belongs to dom frontier
// of
// j. So insert a phi node at l.
JITDUMP("Inserting phi definition for %s at start of " FMT_BB ".\n",
memoryKindNames[memoryKind], bbInDomFront->bbNum);
bbInDomFront->bbMemorySsaPhiFunc[memoryKind] = BasicBlock::EmptyMemoryPhiDef;
}
}
}
}
}
EndPhase(PHASE_BUILD_SSA_INSERT_PHIS);
}
//------------------------------------------------------------------------
// RenameDef: Rename a local or memory definition generated by a store/GT_CALL node.
//
// Arguments:
// defNode - The store/GT_CALL node that generates the definition
// block - The basic block that contains `defNode`
//
void SsaBuilder::RenameDef(GenTree* defNode, BasicBlock* block)
{
assert(defNode->OperIsStore() || defNode->OperIs(GT_CALL));
GenTreeLclVarCommon* lclNode;
bool isFullDef = false;
ssize_t offset = 0;
unsigned storeSize = 0;
bool isLocal = defNode->DefinesLocal(m_pCompiler, &lclNode, &isFullDef, &offset, &storeSize);
if (isLocal)
{
// This should have been marked as definition.
assert(((lclNode->gtFlags & GTF_VAR_DEF) != 0) && (((lclNode->gtFlags & GTF_VAR_USEASG) != 0) == !isFullDef));
unsigned lclNum = lclNode->GetLclNum();
LclVarDsc* varDsc = m_pCompiler->lvaGetDesc(lclNum);
if (m_pCompiler->lvaInSsa(lclNum))
{
lclNode->SetSsaNum(RenamePushDef(defNode, block, lclNum, isFullDef));
assert(!varDsc->IsAddressExposed()); // Cannot define SSA memory.
return;
}
if (varDsc->lvPromoted)
{
for (unsigned index = 0; index < varDsc->lvFieldCnt; index++)
{
unsigned fieldLclNum = varDsc->lvFieldLclStart + index;
LclVarDsc* fieldVarDsc = m_pCompiler->lvaGetDesc(fieldLclNum);
if (m_pCompiler->lvaInSsa(fieldLclNum))
{
ssize_t fieldStoreOffset;
unsigned fieldStoreSize;
unsigned ssaNum = SsaConfig::RESERVED_SSA_NUM;
// Fast-path the common case of an "entire" store.
if (isFullDef)
{
ssaNum = RenamePushDef(defNode, block, fieldLclNum, /* defIsFull */ true);
}
else if (m_pCompiler->gtStoreDefinesField(fieldVarDsc, offset, storeSize, &fieldStoreOffset,
&fieldStoreSize))
{
ssaNum = RenamePushDef(defNode, block, fieldLclNum,
ValueNumStore::LoadStoreIsEntire(genTypeSize(fieldVarDsc),
fieldStoreOffset, fieldStoreSize));
}
if (ssaNum != SsaConfig::RESERVED_SSA_NUM)
{
lclNode->SetSsaNum(m_pCompiler, index, ssaNum);
}
}
}
}
}
else if (defNode->OperIs(GT_CALL))
{
// If the current def is a call we either know the call is pure or else has arbitrary memory definitions,
// the memory effect of the call is captured by the live out state from the block and doesn't need special
// handling here. If we ever change liveness to more carefully model call effects (from interprecedural
// information) we might need to revisit this.
return;
}
// Figure out if "defNode" may make a new GC heap state (if we care for this block).
if (((block->bbMemoryHavoc & memoryKindSet(GcHeap)) == 0) && m_pCompiler->ehBlockHasExnFlowDsc(block))
{
bool isAddrExposedLocal = isLocal && m_pCompiler->lvaVarAddrExposed(lclNode->GetLclNum());
bool hasByrefHavoc = ((block->bbMemoryHavoc & memoryKindSet(ByrefExposed)) != 0);
if (!isLocal || (isAddrExposedLocal && !hasByrefHavoc))
{
// It *may* define byref memory in a non-havoc way. Make a new SSA # -- associate with this node.
unsigned ssaNum = m_pCompiler->lvMemoryPerSsaData.AllocSsaNum(m_allocator);
if (!hasByrefHavoc)
{
m_renameStack.PushMemory(ByrefExposed, block, ssaNum);
m_pCompiler->GetMemorySsaMap(ByrefExposed)->Set(defNode, ssaNum);
#ifdef DEBUG
if (m_pCompiler->verboseSsa)
{
printf("Node ");
Compiler::printTreeID(defNode);
printf(" (in try block) may define memory; ssa # = %d.\n", ssaNum);
}
#endif // DEBUG
// Now add this SSA # to all phis of the reachable catch blocks.
AddMemoryDefToEHSuccessorPhis(ByrefExposed, block, ssaNum);
}
if (!isLocal)
{
// Add a new def for GcHeap as well
if (m_pCompiler->byrefStatesMatchGcHeapStates)
{
// GcHeap and ByrefExposed share the same stacks, SsaMap, and phis
assert(!hasByrefHavoc);
assert(*m_pCompiler->GetMemorySsaMap(GcHeap)->LookupPointer(defNode) == ssaNum);
assert(block->bbMemorySsaPhiFunc[GcHeap] == block->bbMemorySsaPhiFunc[ByrefExposed]);
}
else
{
if (!hasByrefHavoc)
{
// Allocate a distinct defnum for the GC Heap
ssaNum = m_pCompiler->lvMemoryPerSsaData.AllocSsaNum(m_allocator);
}
m_renameStack.PushMemory(GcHeap, block, ssaNum);
m_pCompiler->GetMemorySsaMap(GcHeap)->Set(defNode, ssaNum);
AddMemoryDefToEHSuccessorPhis(GcHeap, block, ssaNum);
}
}
}
}
}
//------------------------------------------------------------------------
// RenamePushDef: Create and push a new definition on the renaming stack.
//
// Arguments:
// defNode - The store node for the definition
// block - The block in which it occurs
// lclNum - Number of the local being defined
// isFullDef - Whether the def is "entire"
//
// Return Value:
// The pushed SSA number.
//
unsigned SsaBuilder::RenamePushDef(GenTree* defNode, BasicBlock* block, unsigned lclNum, bool isFullDef)
{
// Promoted variables are not in SSA, only their fields are.
assert(m_pCompiler->lvaInSsa(lclNum) && !m_pCompiler->lvaGetDesc(lclNum)->lvPromoted);
LclVarDsc* const varDsc = m_pCompiler->lvaGetDesc(lclNum);
unsigned const ssaNum =
varDsc->lvPerSsaData.AllocSsaNum(m_allocator, block, !defNode->IsCall() ? defNode->AsLclVarCommon() : nullptr);
if (!isFullDef)
{
// This is a partial definition of a variable. The node records only the SSA number
// of the def. The SSA number of the old definition (the "use" portion) will be
// recorded in the SSA descriptor.
LclSsaVarDsc* const ssaDesc = varDsc->GetPerSsaData(ssaNum);
unsigned const useSsaNum = m_renameStack.Top(lclNum);
ssaDesc->SetUseDefSsaNum(useSsaNum);
LclSsaVarDsc* const useSsaDesc = varDsc->GetPerSsaData(useSsaNum);
useSsaDesc->AddUse(block);
}
m_renameStack.Push(block, lclNum, ssaNum);
// If necessary, add SSA name to the arg list of a phi def in any handlers for try
// blocks that "block" is within. (But only do this for "real" definitions, not phis.)
if (!defNode->IsPhiDefn() && block->HasPotentialEHSuccs(m_pCompiler))
{
AddDefToEHSuccessorPhis(block, lclNum, ssaNum);
}
return ssaNum;
}
//------------------------------------------------------------------------
// RenameLclUse: Rename a use of a local variable.
//
// Arguments:
// lclNode - A GT_LCL_VAR or GT_LCL_FLD node that is not a definition
// block - basic block containing the use
//
void SsaBuilder::RenameLclUse(GenTreeLclVarCommon* lclNode, BasicBlock* block)
{
assert((lclNode->gtFlags & GTF_VAR_DEF) == 0);
unsigned const lclNum = lclNode->GetLclNum();
LclVarDsc* const lclVar = m_pCompiler->lvaGetDesc(lclNum);
unsigned ssaNum;
if (!m_pCompiler->lvaInSsa(lclNum))
{
ssaNum = SsaConfig::RESERVED_SSA_NUM;
}
else
{
// Promoted variables are not in SSA, only their fields are.
assert(!lclVar->lvPromoted);
ssaNum = m_renameStack.Top(lclNum);
LclSsaVarDsc* const ssaDesc = lclVar->GetPerSsaData(ssaNum);
ssaDesc->AddUse(block);
}
lclNode->SetSsaNum(ssaNum);
}
void SsaBuilder::AddDefToEHSuccessorPhis(BasicBlock* block, unsigned lclNum, unsigned ssaNum)
{
assert(block->HasPotentialEHSuccs(m_pCompiler));
assert(m_pCompiler->lvaTable[lclNum].lvTracked);
DBG_SSA_JITDUMP("Definition of local V%02u/d:%d in block " FMT_BB
" has potential EH successors; adding as phi arg to EH successors\n",
lclNum, ssaNum, block->bbNum);
unsigned lclIndex = m_pCompiler->lvaTable[lclNum].lvVarIndex;
block->VisitEHSuccs(m_pCompiler, [=](BasicBlock* succ) {
// Is "lclNum" live on entry to the handler?
if (!VarSetOps::IsMember(m_pCompiler, succ->bbLiveIn, lclIndex))
{
return BasicBlockVisit::Continue;
}
#ifdef DEBUG
bool phiFound = false;
#endif
// A prefix of blocks statements will be SSA definitions. Search those for "lclNum".
for (Statement* const stmt : succ->Statements())
{
// If the tree is not an SSA def, break out of the loop: we're done.
if (!stmt->IsPhiDefnStmt())
{
break;
}
GenTreeLclVar* phiDef = stmt->GetRootNode()->AsLclVar();
assert(phiDef->IsPhiDefn());
if (phiDef->GetLclNum() == lclNum)
{
// It's the definition for the right local. Add "ssaNum" to the RHS.
AddPhiArg(succ, stmt, phiDef->Data()->AsPhi(), lclNum, ssaNum, block);
#ifdef DEBUG
phiFound = true;
#endif
break;
}
}
assert(phiFound);
return BasicBlockVisit::Continue;
});
}
void SsaBuilder::AddMemoryDefToEHSuccessorPhis(MemoryKind memoryKind, BasicBlock* block, unsigned ssaNum)
{
assert(block->HasPotentialEHSuccs(m_pCompiler));
// Don't do anything for a compiler-inserted BBJ_CALLFINALLYRET that is a "leave helper".
if (block->isBBCallFinallyPairTail())
{
return;
}
// Otherwise...
DBG_SSA_JITDUMP("Definition of %s/d:%d in block " FMT_BB
" has potential EH successors; adding as phi arg to EH successors.\n",
memoryKindNames[memoryKind], ssaNum, block->bbNum);
block->VisitEHSuccs(m_pCompiler, [=](BasicBlock* succ) {
// Is memoryKind live on entry to the handler?
if ((succ->bbMemoryLiveIn & memoryKindSet(memoryKind)) == 0)
{
return BasicBlockVisit::Continue;
}
// Add "ssaNum" to the phi args of memoryKind.
BasicBlock::MemoryPhiArg*& handlerMemoryPhi = succ->bbMemorySsaPhiFunc[memoryKind];
#if DEBUG
if (m_pCompiler->byrefStatesMatchGcHeapStates)
{
// When sharing phis for GcHeap and ByrefExposed, callers should ask to add phis
// for ByrefExposed only.
assert(memoryKind != GcHeap);
if (memoryKind == ByrefExposed)
{
// The GcHeap and ByrefExposed phi funcs should always be in sync.
assert(handlerMemoryPhi == succ->bbMemorySsaPhiFunc[GcHeap]);
}
}
#endif
if (handlerMemoryPhi == BasicBlock::EmptyMemoryPhiDef)
{
handlerMemoryPhi = new (m_pCompiler) BasicBlock::MemoryPhiArg(ssaNum);
}
else
{
#ifdef DEBUG
BasicBlock::MemoryPhiArg* curArg = succ->bbMemorySsaPhiFunc[memoryKind];
while (curArg != nullptr)
{
assert(curArg->GetSsaNum() != ssaNum);
curArg = curArg->m_nextArg;
}
#endif // DEBUG
handlerMemoryPhi = new (m_pCompiler) BasicBlock::MemoryPhiArg(ssaNum, handlerMemoryPhi);
}
DBG_SSA_JITDUMP(" Added phi arg u:%d for %s to phi defn in handler block " FMT_BB ".\n", ssaNum,
memoryKindNames[memoryKind], memoryKind, succ->bbNum);
if ((memoryKind == ByrefExposed) && m_pCompiler->byrefStatesMatchGcHeapStates)
{
// Share the phi between GcHeap and ByrefExposed.
succ->bbMemorySsaPhiFunc[GcHeap] = handlerMemoryPhi;
}
return BasicBlockVisit::Continue;
});
}
//------------------------------------------------------------------------
// BlockRenameVariables: Rename all definitions and uses within a block.
//
// Arguments:
// block - The block
//
void SsaBuilder::BlockRenameVariables(BasicBlock* block)
{
// First handle the incoming memory states.
for (MemoryKind memoryKind : allMemoryKinds())
{
if ((memoryKind == GcHeap) && m_pCompiler->byrefStatesMatchGcHeapStates)
{
// ByrefExposed and GcHeap share any phi this block may have,
assert(block->bbMemorySsaPhiFunc[memoryKind] == block->bbMemorySsaPhiFunc[ByrefExposed]);
// so we will have already allocated a defnum for it if needed.
assert(memoryKind > ByrefExposed);
block->bbMemorySsaNumIn[memoryKind] = m_renameStack.TopMemory(ByrefExposed);
}
else
{
// Is there an Phi definition for memoryKind at the start of this block?
if (block->bbMemorySsaPhiFunc[memoryKind] != nullptr)
{
unsigned ssaNum = m_pCompiler->lvMemoryPerSsaData.AllocSsaNum(m_allocator);
m_renameStack.PushMemory(memoryKind, block, ssaNum);
DBG_SSA_JITDUMP("Ssa # for %s phi on entry to " FMT_BB " is %d.\n", memoryKindNames[memoryKind],
block->bbNum, ssaNum);
block->bbMemorySsaNumIn[memoryKind] = ssaNum;
}
else
{
block->bbMemorySsaNumIn[memoryKind] = m_renameStack.TopMemory(memoryKind);
}
}
}
// Walk the statements of the block and rename definitions and uses.
for (Statement* const stmt : block->Statements())
{
for (GenTree* const tree : stmt->TreeList())
{
if (tree->OperIsStore() || tree->OperIs(GT_CALL))
{
RenameDef(tree, block);
}
// PHI_ARG nodes already have SSA numbers so we only need to check LCL_VAR and LCL_FLD nodes.
else if (tree->OperIs(GT_LCL_VAR, GT_LCL_FLD))
{
RenameLclUse(tree->AsLclVarCommon(), block);
}
}
}
// Now handle the final memory states.
for (MemoryKind memoryKind : allMemoryKinds())
{
MemoryKindSet memorySet = memoryKindSet(memoryKind);
// If the block defines memory, allocate an SSA variable for the final memory state in the block.
// (This may be redundant with the last SSA var explicitly created, but there's no harm in that.)
if ((memoryKind == GcHeap) && m_pCompiler->byrefStatesMatchGcHeapStates)
{
// We've already allocated the SSA num and propagated it to shared phis, if needed,
// when processing ByrefExposed.
assert(memoryKind > ByrefExposed);
assert(((block->bbMemoryDef & memorySet) != 0) ==
((block->bbMemoryDef & memoryKindSet(ByrefExposed)) != 0));
block->bbMemorySsaNumOut[memoryKind] = m_renameStack.TopMemory(ByrefExposed);
}
else
{
if ((block->bbMemoryDef & memorySet) != 0)
{
unsigned ssaNum = m_pCompiler->lvMemoryPerSsaData.AllocSsaNum(m_allocator);
m_renameStack.PushMemory(memoryKind, block, ssaNum);
if (block->HasPotentialEHSuccs(m_pCompiler))
{
AddMemoryDefToEHSuccessorPhis(memoryKind, block, ssaNum);
}
block->bbMemorySsaNumOut[memoryKind] = ssaNum;
}
else
{
block->bbMemorySsaNumOut[memoryKind] = m_renameStack.TopMemory(memoryKind);
}
}
DBG_SSA_JITDUMP("Ssa # for %s on entry to " FMT_BB " is %d; on exit is %d.\n", memoryKindNames[memoryKind],
block->bbNum, block->bbMemorySsaNumIn[memoryKind], block->bbMemorySsaNumOut[memoryKind]);
}
}
//------------------------------------------------------------------------
// AddPhiArgsToSuccessors: Add GT_PHI_ARG nodes to the GT_PHI nodes within block's successors.
//
// Arguments:
// block - The block
//
void SsaBuilder::AddPhiArgsToSuccessors(BasicBlock* block)
{
block->VisitAllSuccs(m_pCompiler, [this, block](BasicBlock* succ) {
// Walk the statements for phi nodes.
for (Statement* const stmt : succ->Statements())
{
// A prefix of the statements of the block are phi definition nodes. If we complete processing
// that prefix, exit.
if (!stmt->IsPhiDefnStmt())
{
break;
}
GenTreeLclVar* store = stmt->GetRootNode()->AsLclVar();
GenTreePhi* phi = store->Data()->AsPhi();
unsigned lclNum = store->GetLclNum();
unsigned ssaNum = m_renameStack.Top(lclNum);
AddPhiArg(succ, stmt, phi, lclNum, ssaNum, block);
}
// Now handle memory.
for (MemoryKind memoryKind : allMemoryKinds())
{
BasicBlock::MemoryPhiArg*& succMemoryPhi = succ->bbMemorySsaPhiFunc[memoryKind];
if (succMemoryPhi != nullptr)
{
if ((memoryKind == GcHeap) && m_pCompiler->byrefStatesMatchGcHeapStates)
{
// We've already propagated the "out" number to the phi shared with ByrefExposed,
// but still need to update bbMemorySsaPhiFunc to be in sync between GcHeap and ByrefExposed.
assert(memoryKind > ByrefExposed);
assert(block->bbMemorySsaNumOut[memoryKind] == block->bbMemorySsaNumOut[ByrefExposed]);
assert((succ->bbMemorySsaPhiFunc[ByrefExposed] == succMemoryPhi) ||
(succ->bbMemorySsaPhiFunc[ByrefExposed]->m_nextArg ==
(succMemoryPhi == BasicBlock::EmptyMemoryPhiDef ? nullptr : succMemoryPhi)));
succMemoryPhi = succ->bbMemorySsaPhiFunc[ByrefExposed];