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
/
liveness.cpp
2659 lines (2260 loc) · 91.6 KB
/
liveness.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.
// =================================================================================
// Code that works with liveness and related concepts (interference, debug scope)
// =================================================================================
#include "jitpch.h"
#ifdef _MSC_VER
#pragma hdrstop
#endif
#if !defined(_TARGET_64BIT_)
#include "decomposelongs.h"
#endif
#include "lower.h" // for LowerRange()
/*****************************************************************************
*
* Helper for Compiler::fgPerBlockLocalVarLiveness().
* The goal is to compute the USE and DEF sets for a basic block.
*/
void Compiler::fgMarkUseDef(GenTreeLclVarCommon* tree)
{
assert((tree->OperIsLocal() && (tree->OperGet() != GT_PHI_ARG)) || tree->OperIsLocalAddr());
const unsigned lclNum = tree->GetLclNum();
assert(lclNum < lvaCount);
LclVarDsc* const varDsc = &lvaTable[lclNum];
// We should never encounter a reference to a lclVar that has a zero refCnt.
if (varDsc->lvRefCnt() == 0 && (!varTypeIsPromotable(varDsc) || !varDsc->lvPromoted))
{
JITDUMP("Found reference to V%02u with zero refCnt.\n", lclNum);
assert(!"We should never encounter a reference to a lclVar that has a zero refCnt.");
varDsc->setLvRefCnt(1);
}
const bool isDef = (tree->gtFlags & GTF_VAR_DEF) != 0;
const bool isUse = !isDef || ((tree->gtFlags & GTF_VAR_USEASG) != 0);
if (varDsc->lvTracked)
{
assert(varDsc->lvVarIndex < lvaTrackedCount);
// We don't treat stores to tracked locals as modifications of ByrefExposed memory;
// Make sure no tracked local is addr-exposed, to make sure we don't incorrectly CSE byref
// loads aliasing it across a store to it.
assert(!varDsc->lvAddrExposed);
if (compRationalIRForm && (varDsc->lvType != TYP_STRUCT) && !varTypeIsMultiReg(varDsc))
{
// If this is an enregisterable variable that is not marked doNotEnregister,
// we should only see direct references (not ADDRs).
assert(varDsc->lvDoNotEnregister || tree->OperIs(GT_LCL_VAR, GT_STORE_LCL_VAR));
}
if (isUse && !VarSetOps::IsMember(this, fgCurDefSet, varDsc->lvVarIndex))
{
// This is an exposed use; add it to the set of uses.
VarSetOps::AddElemD(this, fgCurUseSet, varDsc->lvVarIndex);
}
if (isDef)
{
// This is a def, add it to the set of defs.
VarSetOps::AddElemD(this, fgCurDefSet, varDsc->lvVarIndex);
}
}
else
{
if (varDsc->lvAddrExposed)
{
// Reflect the effect on ByrefExposed memory
if (isUse)
{
fgCurMemoryUse |= memoryKindSet(ByrefExposed);
}
if (isDef)
{
fgCurMemoryDef |= memoryKindSet(ByrefExposed);
// We've found a store that modifies ByrefExposed
// memory but not GcHeap memory, so track their
// states separately.
byrefStatesMatchGcHeapStates = false;
}
}
if (varTypeIsStruct(varDsc))
{
lvaPromotionType promotionType = lvaGetPromotionType(varDsc);
if (promotionType != PROMOTION_TYPE_NONE)
{
VARSET_TP bitMask(VarSetOps::MakeEmpty(this));
for (unsigned i = varDsc->lvFieldLclStart; i < varDsc->lvFieldLclStart + varDsc->lvFieldCnt; ++i)
{
noway_assert(lvaTable[i].lvIsStructField);
if (lvaTable[i].lvTracked)
{
noway_assert(lvaTable[i].lvVarIndex < lvaTrackedCount);
VarSetOps::AddElemD(this, bitMask, lvaTable[i].lvVarIndex);
}
}
// For pure defs (i.e. not an "update" def which is also a use), add to the (all) def set.
if (!isUse)
{
assert(isDef);
VarSetOps::UnionD(this, fgCurDefSet, bitMask);
}
else if (!VarSetOps::IsSubset(this, bitMask, fgCurDefSet))
{
// Mark as used any struct fields that are not yet defined.
VarSetOps::UnionD(this, fgCurUseSet, bitMask);
}
}
}
}
}
/*****************************************************************************/
void Compiler::fgLocalVarLiveness()
{
#ifdef DEBUG
if (verbose)
{
printf("*************** In fgLocalVarLiveness()\n");
if (compRationalIRForm)
{
lvaTableDump();
}
}
#endif // DEBUG
// Init liveness data structures.
fgLocalVarLivenessInit();
EndPhase(PHASE_LCLVARLIVENESS_INIT);
// Make sure we haven't noted any partial last uses of promoted structs.
ClearPromotedStructDeathVars();
// Initialize the per-block var sets.
fgInitBlockVarSets();
fgLocalVarLivenessChanged = false;
do
{
/* Figure out use/def info for all basic blocks */
fgPerBlockLocalVarLiveness();
EndPhase(PHASE_LCLVARLIVENESS_PERBLOCK);
/* Live variable analysis. */
fgStmtRemoved = false;
fgInterBlockLocalVarLiveness();
} while (fgStmtRemoved && fgLocalVarLivenessChanged);
EndPhase(PHASE_LCLVARLIVENESS_INTERBLOCK);
}
/*****************************************************************************/
void Compiler::fgLocalVarLivenessInit()
{
JITDUMP("In fgLocalVarLivenessInit\n");
// Sort locals first, if we're optimizing
if (opts.OptimizationEnabled())
{
lvaSortByRefCount();
}
// We mark a lcl as must-init in a first pass of local variable
// liveness (Liveness1), then assertion prop eliminates the
// uninit-use of a variable Vk, asserting it will be init'ed to
// null. Then, in a second local-var liveness (Liveness2), the
// variable Vk is no longer live on entry to the method, since its
// uses have been replaced via constant propagation.
//
// This leads to a bug: since Vk is no longer live on entry, the
// register allocator sees Vk and an argument Vj as having
// disjoint lifetimes, and allocates them to the same register.
// But Vk is still marked "must-init", and this initialization (of
// the register) trashes the value in Vj.
//
// Therefore, initialize must-init to false for all variables in
// each liveness phase.
for (unsigned lclNum = 0; lclNum < lvaCount; ++lclNum)
{
lvaTable[lclNum].lvMustInit = false;
}
}
//------------------------------------------------------------------------
// fgPerNodeLocalVarLiveness:
// Set fgCurMemoryUse and fgCurMemoryDef when memory is read or updated
// Call fgMarkUseDef for any Local variables encountered
//
// Arguments:
// tree - The current node.
//
void Compiler::fgPerNodeLocalVarLiveness(GenTree* tree)
{
assert(tree != nullptr);
switch (tree->gtOper)
{
case GT_QMARK:
case GT_COLON:
// We never should encounter a GT_QMARK or GT_COLON node
noway_assert(!"unexpected GT_QMARK/GT_COLON");
break;
case GT_LCL_VAR:
case GT_LCL_FLD:
case GT_LCL_VAR_ADDR:
case GT_LCL_FLD_ADDR:
case GT_STORE_LCL_VAR:
case GT_STORE_LCL_FLD:
fgMarkUseDef(tree->AsLclVarCommon());
break;
case GT_CLS_VAR:
// For Volatile indirection, first mutate GcHeap/ByrefExposed.
// See comments in ValueNum.cpp (under case GT_CLS_VAR)
// This models Volatile reads as def-then-use of memory
// and allows for a CSE of a subsequent non-volatile read.
if ((tree->gtFlags & GTF_FLD_VOLATILE) != 0)
{
// For any Volatile indirection, we must handle it as a
// definition of GcHeap/ByrefExposed
fgCurMemoryDef |= memoryKindSet(GcHeap, ByrefExposed);
}
// If the GT_CLS_VAR is the lhs of an assignment, we'll handle it as a GcHeap/ByrefExposed def, when we get
// to the assignment.
// Otherwise, we treat it as a use here.
if ((tree->gtFlags & GTF_CLS_VAR_ASG_LHS) == 0)
{
fgCurMemoryUse |= memoryKindSet(GcHeap, ByrefExposed);
}
break;
case GT_IND:
// For Volatile indirection, first mutate GcHeap/ByrefExposed
// see comments in ValueNum.cpp (under case GT_CLS_VAR)
// This models Volatile reads as def-then-use of memory.
// and allows for a CSE of a subsequent non-volatile read
if ((tree->gtFlags & GTF_IND_VOLATILE) != 0)
{
// For any Volatile indirection, we must handle it as a
// definition of the GcHeap/ByrefExposed
fgCurMemoryDef |= memoryKindSet(GcHeap, ByrefExposed);
}
// If the GT_IND is the lhs of an assignment, we'll handle it
// as a memory def, when we get to assignment.
// Otherwise, we treat it as a use here.
if ((tree->gtFlags & GTF_IND_ASG_LHS) == 0)
{
GenTreeLclVarCommon* dummyLclVarTree = nullptr;
bool dummyIsEntire = false;
GenTree* addrArg = tree->AsOp()->gtOp1->gtEffectiveVal(/*commaOnly*/ true);
if (!addrArg->DefinesLocalAddr(this, /*width doesn't matter*/ 0, &dummyLclVarTree, &dummyIsEntire))
{
fgCurMemoryUse |= memoryKindSet(GcHeap, ByrefExposed);
}
else
{
// Defines a local addr
assert(dummyLclVarTree != nullptr);
fgMarkUseDef(dummyLclVarTree->AsLclVarCommon());
}
}
break;
// These should have been morphed away to become GT_INDs:
case GT_FIELD:
case GT_INDEX:
unreached();
break;
// We'll assume these are use-then-defs of memory.
case GT_LOCKADD:
case GT_XADD:
case GT_XCHG:
case GT_CMPXCHG:
fgCurMemoryUse |= memoryKindSet(GcHeap, ByrefExposed);
fgCurMemoryDef |= memoryKindSet(GcHeap, ByrefExposed);
fgCurMemoryHavoc |= memoryKindSet(GcHeap, ByrefExposed);
break;
case GT_MEMORYBARRIER:
// Simliar to any Volatile indirection, we must handle this as a definition of GcHeap/ByrefExposed
fgCurMemoryDef |= memoryKindSet(GcHeap, ByrefExposed);
break;
#ifdef FEATURE_HW_INTRINSICS
case GT_HWINTRINSIC:
{
GenTreeHWIntrinsic* hwIntrinsicNode = tree->AsHWIntrinsic();
// We can't call fgMutateGcHeap unless the block has recorded a MemoryDef
//
if (hwIntrinsicNode->OperIsMemoryStore())
{
// We currently handle this like a Volatile store, so it counts as a definition of GcHeap/ByrefExposed
fgCurMemoryDef |= memoryKindSet(GcHeap, ByrefExposed);
}
if (hwIntrinsicNode->OperIsMemoryLoad())
{
// This instruction loads from memory and we need to record this information
fgCurMemoryUse |= memoryKindSet(GcHeap, ByrefExposed);
}
break;
}
#endif
// For now, all calls read/write GcHeap/ByrefExposed, writes in their entirety. Might tighten this case later.
case GT_CALL:
{
GenTreeCall* call = tree->AsCall();
bool modHeap = true;
if (call->gtCallType == CT_HELPER)
{
CorInfoHelpFunc helpFunc = eeGetHelperNum(call->gtCallMethHnd);
if (!s_helperCallProperties.MutatesHeap(helpFunc) && !s_helperCallProperties.MayRunCctor(helpFunc))
{
modHeap = false;
}
}
if (modHeap)
{
fgCurMemoryUse |= memoryKindSet(GcHeap, ByrefExposed);
fgCurMemoryDef |= memoryKindSet(GcHeap, ByrefExposed);
fgCurMemoryHavoc |= memoryKindSet(GcHeap, ByrefExposed);
}
}
// If this is a p/invoke unmanaged call or if this is a tail-call
// and we have an unmanaged p/invoke call in the method,
// then we're going to run the p/invoke epilog.
// So we mark the FrameRoot as used by this instruction.
// This ensures that the block->bbVarUse will contain
// the FrameRoot local var if is it a tracked variable.
if ((tree->AsCall()->IsUnmanaged() || tree->AsCall()->IsTailCall()) && compMethodRequiresPInvokeFrame())
{
assert((!opts.ShouldUsePInvokeHelpers()) || (info.compLvFrameListRoot == BAD_VAR_NUM));
if (!opts.ShouldUsePInvokeHelpers())
{
/* Get the TCB local and mark it as used */
noway_assert(info.compLvFrameListRoot < lvaCount);
LclVarDsc* varDsc = &lvaTable[info.compLvFrameListRoot];
if (varDsc->lvTracked)
{
if (!VarSetOps::IsMember(this, fgCurDefSet, varDsc->lvVarIndex))
{
VarSetOps::AddElemD(this, fgCurUseSet, varDsc->lvVarIndex);
}
}
}
}
break;
default:
// Determine what memory locations it defines.
if (tree->OperIs(GT_ASG) || tree->OperIsBlkOp())
{
GenTreeLclVarCommon* dummyLclVarTree = nullptr;
if (tree->DefinesLocal(this, &dummyLclVarTree))
{
if (lvaVarAddrExposed(dummyLclVarTree->GetLclNum()))
{
fgCurMemoryDef |= memoryKindSet(ByrefExposed);
// We've found a store that modifies ByrefExposed
// memory but not GcHeap memory, so track their
// states separately.
byrefStatesMatchGcHeapStates = false;
}
}
else
{
// If it doesn't define a local, then it might update GcHeap/ByrefExposed.
fgCurMemoryDef |= memoryKindSet(GcHeap, ByrefExposed);
}
}
break;
}
}
/*****************************************************************************/
void Compiler::fgPerBlockLocalVarLiveness()
{
#ifdef DEBUG
if (verbose)
{
printf("*************** In fgPerBlockLocalVarLiveness()\n");
}
#endif // DEBUG
unsigned livenessVarEpoch = GetCurLVEpoch();
BasicBlock* block;
// If we don't require accurate local var lifetimes, things are simple.
if (!backendRequiresLocalVarLifetimes())
{
unsigned lclNum;
LclVarDsc* varDsc;
VARSET_TP liveAll(VarSetOps::MakeEmpty(this));
/* We simply make everything live everywhere */
for (lclNum = 0, varDsc = lvaTable; lclNum < lvaCount; lclNum++, varDsc++)
{
if (varDsc->lvTracked)
{
VarSetOps::AddElemD(this, liveAll, varDsc->lvVarIndex);
}
}
for (block = fgFirstBB; block; block = block->bbNext)
{
// Strictly speaking, the assignments for the "Def" cases aren't necessary here.
// The empty set would do as well. Use means "use-before-def", so as long as that's
// "all", this has the right effect.
VarSetOps::Assign(this, block->bbVarUse, liveAll);
VarSetOps::Assign(this, block->bbVarDef, liveAll);
VarSetOps::Assign(this, block->bbLiveIn, liveAll);
block->bbMemoryUse = fullMemoryKindSet;
block->bbMemoryDef = fullMemoryKindSet;
block->bbMemoryLiveIn = fullMemoryKindSet;
block->bbMemoryLiveOut = fullMemoryKindSet;
switch (block->bbJumpKind)
{
case BBJ_EHFINALLYRET:
case BBJ_THROW:
case BBJ_RETURN:
VarSetOps::AssignNoCopy(this, block->bbLiveOut, VarSetOps::MakeEmpty(this));
break;
default:
VarSetOps::Assign(this, block->bbLiveOut, liveAll);
break;
}
}
// In minopts, we don't explicitly build SSA or value-number; GcHeap and
// ByrefExposed implicitly (conservatively) change state at each instr.
byrefStatesMatchGcHeapStates = true;
return;
}
// Avoid allocations in the long case.
VarSetOps::AssignNoCopy(this, fgCurUseSet, VarSetOps::MakeEmpty(this));
VarSetOps::AssignNoCopy(this, fgCurDefSet, VarSetOps::MakeEmpty(this));
// GC Heap and ByrefExposed can share states unless we see a def of byref-exposed
// memory that is not a GC Heap def.
byrefStatesMatchGcHeapStates = true;
for (block = fgFirstBB; block; block = block->bbNext)
{
VarSetOps::ClearD(this, fgCurUseSet);
VarSetOps::ClearD(this, fgCurDefSet);
fgCurMemoryUse = emptyMemoryKindSet;
fgCurMemoryDef = emptyMemoryKindSet;
fgCurMemoryHavoc = emptyMemoryKindSet;
compCurBB = block;
if (block->IsLIR())
{
for (GenTree* node : LIR::AsRange(block).NonPhiNodes())
{
fgPerNodeLocalVarLiveness(node);
}
}
else
{
for (Statement* stmt : StatementList(block->FirstNonPhiDef()))
{
compCurStmt = stmt;
for (GenTree* node = stmt->GetTreeList(); node != nullptr; node = node->gtNext)
{
fgPerNodeLocalVarLiveness(node);
}
}
}
/* Get the TCB local and mark it as used */
if (block->bbJumpKind == BBJ_RETURN && compMethodRequiresPInvokeFrame())
{
assert((!opts.ShouldUsePInvokeHelpers()) || (info.compLvFrameListRoot == BAD_VAR_NUM));
if (!opts.ShouldUsePInvokeHelpers())
{
noway_assert(info.compLvFrameListRoot < lvaCount);
LclVarDsc* varDsc = &lvaTable[info.compLvFrameListRoot];
if (varDsc->lvTracked)
{
if (!VarSetOps::IsMember(this, fgCurDefSet, varDsc->lvVarIndex))
{
VarSetOps::AddElemD(this, fgCurUseSet, varDsc->lvVarIndex);
}
}
}
}
#ifdef DEBUG
if (verbose)
{
VARSET_TP allVars(VarSetOps::Union(this, fgCurUseSet, fgCurDefSet));
printf(FMT_BB, block->bbNum);
printf(" USE(%d)=", VarSetOps::Count(this, fgCurUseSet));
lvaDispVarSet(fgCurUseSet, allVars);
for (MemoryKind memoryKind : allMemoryKinds())
{
if ((fgCurMemoryUse & memoryKindSet(memoryKind)) != 0)
{
printf(" + %s", memoryKindNames[memoryKind]);
}
}
printf("\n DEF(%d)=", VarSetOps::Count(this, fgCurDefSet));
lvaDispVarSet(fgCurDefSet, allVars);
for (MemoryKind memoryKind : allMemoryKinds())
{
if ((fgCurMemoryDef & memoryKindSet(memoryKind)) != 0)
{
printf(" + %s", memoryKindNames[memoryKind]);
}
if ((fgCurMemoryHavoc & memoryKindSet(memoryKind)) != 0)
{
printf("*");
}
}
printf("\n\n");
}
#endif // DEBUG
VarSetOps::Assign(this, block->bbVarUse, fgCurUseSet);
VarSetOps::Assign(this, block->bbVarDef, fgCurDefSet);
block->bbMemoryUse = fgCurMemoryUse;
block->bbMemoryDef = fgCurMemoryDef;
block->bbMemoryHavoc = fgCurMemoryHavoc;
/* also initialize the IN set, just in case we will do multiple DFAs */
VarSetOps::AssignNoCopy(this, block->bbLiveIn, VarSetOps::MakeEmpty(this));
block->bbMemoryLiveIn = emptyMemoryKindSet;
}
noway_assert(livenessVarEpoch == GetCurLVEpoch());
#ifdef DEBUG
if (verbose)
{
printf("** Memory liveness computed, GcHeap states and ByrefExposed states %s\n",
(byrefStatesMatchGcHeapStates ? "match" : "diverge"));
}
#endif // DEBUG
}
// Helper functions to mark variables live over their entire scope
void Compiler::fgBeginScopeLife(VARSET_TP* inScope, VarScopeDsc* var)
{
assert(var);
LclVarDsc* lclVarDsc1 = &lvaTable[var->vsdVarNum];
if (lclVarDsc1->lvTracked)
{
VarSetOps::AddElemD(this, *inScope, lclVarDsc1->lvVarIndex);
}
}
void Compiler::fgEndScopeLife(VARSET_TP* inScope, VarScopeDsc* var)
{
assert(var);
LclVarDsc* lclVarDsc1 = &lvaTable[var->vsdVarNum];
if (lclVarDsc1->lvTracked)
{
VarSetOps::RemoveElemD(this, *inScope, lclVarDsc1->lvVarIndex);
}
}
/*****************************************************************************/
void Compiler::fgMarkInScope(BasicBlock* block, VARSET_VALARG_TP inScope)
{
#ifdef DEBUG
if (verbose)
{
printf("Scope info: block " FMT_BB " marking in scope: ", block->bbNum);
dumpConvertedVarSet(this, inScope);
printf("\n");
}
#endif // DEBUG
/* Record which vars are artifically kept alive for debugging */
VarSetOps::Assign(this, block->bbScope, inScope);
/* Being in scope implies a use of the variable. Add the var to bbVarUse
so that redoing fgLiveVarAnalysis() will work correctly */
VarSetOps::UnionD(this, block->bbVarUse, inScope);
/* Artifically mark all vars in scope as alive */
VarSetOps::UnionD(this, block->bbLiveIn, inScope);
VarSetOps::UnionD(this, block->bbLiveOut, inScope);
}
void Compiler::fgUnmarkInScope(BasicBlock* block, VARSET_VALARG_TP unmarkScope)
{
#ifdef DEBUG
if (verbose)
{
printf("Scope info: block " FMT_BB " UNmarking in scope: ", block->bbNum);
dumpConvertedVarSet(this, unmarkScope);
printf("\n");
}
#endif // DEBUG
assert(VarSetOps::IsSubset(this, unmarkScope, block->bbScope));
VarSetOps::DiffD(this, block->bbScope, unmarkScope);
VarSetOps::DiffD(this, block->bbVarUse, unmarkScope);
VarSetOps::DiffD(this, block->bbLiveIn, unmarkScope);
VarSetOps::DiffD(this, block->bbLiveOut, unmarkScope);
}
#ifdef DEBUG
void Compiler::fgDispDebugScopes()
{
printf("\nDebug scopes:\n");
BasicBlock* block;
for (block = fgFirstBB; block; block = block->bbNext)
{
printf(FMT_BB ": ", block->bbNum);
dumpConvertedVarSet(this, block->bbScope);
printf("\n");
}
}
#endif // DEBUG
/*****************************************************************************
*
* Mark variables live across their entire scope.
*/
#if defined(FEATURE_EH_FUNCLETS)
void Compiler::fgExtendDbgScopes()
{
compResetScopeLists();
#ifdef DEBUG
if (verbose)
{
printf("\nMarking vars alive over their entire scope :\n\n");
}
if (verbose)
{
compDispScopeLists();
}
#endif // DEBUG
VARSET_TP inScope(VarSetOps::MakeEmpty(this));
// Mark all tracked LocalVars live over their scope - walk the blocks
// keeping track of the current life, and assign it to the blocks.
for (BasicBlock* block = fgFirstBB; block; block = block->bbNext)
{
// If we get to a funclet, reset the scope lists and start again, since the block
// offsets will be out of order compared to the previous block.
if (block->bbFlags & BBF_FUNCLET_BEG)
{
compResetScopeLists();
VarSetOps::ClearD(this, inScope);
}
// Process all scopes up to the current offset
if (block->bbCodeOffs != BAD_IL_OFFSET)
{
compProcessScopesUntil(block->bbCodeOffs, &inScope, &Compiler::fgBeginScopeLife, &Compiler::fgEndScopeLife);
}
// Assign the current set of variables that are in scope to the block variables tracking this.
fgMarkInScope(block, inScope);
}
#ifdef DEBUG
if (verbose)
{
fgDispDebugScopes();
}
#endif // DEBUG
}
#else // !FEATURE_EH_FUNCLETS
void Compiler::fgExtendDbgScopes()
{
compResetScopeLists();
#ifdef DEBUG
if (verbose)
{
printf("\nMarking vars alive over their entire scope :\n\n");
compDispScopeLists();
}
#endif // DEBUG
VARSET_TP inScope(VarSetOps::MakeEmpty(this));
compProcessScopesUntil(0, &inScope, &Compiler::fgBeginScopeLife, &Compiler::fgEndScopeLife);
IL_OFFSET lastEndOffs = 0;
// Mark all tracked LocalVars live over their scope - walk the blocks
// keeping track of the current life, and assign it to the blocks.
BasicBlock* block;
for (block = fgFirstBB; block; block = block->bbNext)
{
// Find scopes becoming alive. If there is a gap in the instr
// sequence, we need to process any scopes on those missing offsets.
if (block->bbCodeOffs != BAD_IL_OFFSET)
{
if (lastEndOffs != block->bbCodeOffs)
{
noway_assert(lastEndOffs < block->bbCodeOffs);
compProcessScopesUntil(block->bbCodeOffs, &inScope, &Compiler::fgBeginScopeLife,
&Compiler::fgEndScopeLife);
}
else
{
while (VarScopeDsc* varScope = compGetNextEnterScope(block->bbCodeOffs))
{
fgBeginScopeLife(&inScope, varScope);
}
}
}
// Assign the current set of variables that are in scope to the block variables tracking this.
fgMarkInScope(block, inScope);
// Find scopes going dead.
if (block->bbCodeOffsEnd != BAD_IL_OFFSET)
{
VarScopeDsc* varScope;
while ((varScope = compGetNextExitScope(block->bbCodeOffsEnd)) != nullptr)
{
fgEndScopeLife(&inScope, varScope);
}
lastEndOffs = block->bbCodeOffsEnd;
}
}
/* Everything should be out of scope by the end of the method. But if the
last BB got removed, then inScope may not be empty. */
noway_assert(VarSetOps::IsEmpty(this, inScope) || lastEndOffs < info.compILCodeSize);
}
#endif // !FEATURE_EH_FUNCLETS
/*****************************************************************************
*
* For debuggable code, we allow redundant assignments to vars
* by marking them live over their entire scope.
*/
void Compiler::fgExtendDbgLifetimes()
{
#ifdef DEBUG
if (verbose)
{
printf("*************** In fgExtendDbgLifetimes()\n");
}
#endif // DEBUG
noway_assert(opts.compDbgCode && (info.compVarScopesCount > 0));
/*-------------------------------------------------------------------------
* Extend the lifetimes over the entire reported scope of the variable.
*/
fgExtendDbgScopes();
/*-------------------------------------------------------------------------
* Partly update liveness info so that we handle any funky BBF_INTERNAL
* blocks inserted out of sequence.
*/
#ifdef DEBUG
if (verbose && 0)
{
fgDispBBLiveness();
}
#endif
fgLiveVarAnalysis(true);
/* For compDbgCode, we prepend an empty BB which will hold the
initializations of variables which are in scope at IL offset 0 (but
not initialized by the IL code). Since they will currently be
marked as live on entry to fgFirstBB, unmark the liveness so that
the following code will know to add the initializations. */
assert(fgFirstBBisScratch());
VARSET_TP trackedArgs(VarSetOps::MakeEmpty(this));
for (unsigned argNum = 0; argNum < info.compArgsCount; argNum++)
{
LclVarDsc* argDsc = lvaTable + argNum;
if (argDsc->lvPromoted)
{
lvaPromotionType promotionType = lvaGetPromotionType(argDsc);
if (promotionType == PROMOTION_TYPE_INDEPENDENT)
{
noway_assert(argDsc->lvFieldCnt == 1); // We only handle one field here
unsigned fieldVarNum = argDsc->lvFieldLclStart;
argDsc = lvaTable + fieldVarNum;
}
}
noway_assert(argDsc->lvIsParam);
if (argDsc->lvTracked)
{
noway_assert(!VarSetOps::IsMember(this, trackedArgs, argDsc->lvVarIndex)); // Each arg should define a
// different bit.
VarSetOps::AddElemD(this, trackedArgs, argDsc->lvVarIndex);
}
}
// Don't unmark struct locals, either.
VARSET_TP noUnmarkVars(trackedArgs);
for (unsigned i = 0; i < lvaCount; i++)
{
LclVarDsc* varDsc = &lvaTable[i];
if (varTypeIsStruct(varDsc) && varDsc->lvTracked)
{
VarSetOps::AddElemD(this, noUnmarkVars, varDsc->lvVarIndex);
}
}
fgUnmarkInScope(fgFirstBB, VarSetOps::Diff(this, fgFirstBB->bbScope, noUnmarkVars));
/*-------------------------------------------------------------------------
* As we keep variables artifically alive over their entire scope,
* we need to also artificially initialize them if the scope does
* not exactly match the real lifetimes, or they will contain
* garbage until they are initialized by the IL code.
*/
VARSET_TP initVars(VarSetOps::MakeEmpty(this)); // Vars which are artificially made alive
for (BasicBlock* block = fgFirstBB; block; block = block->bbNext)
{
VarSetOps::ClearD(this, initVars);
switch (block->bbJumpKind)
{
case BBJ_NONE:
PREFIX_ASSUME(block->bbNext != nullptr);
VarSetOps::UnionD(this, initVars, block->bbNext->bbScope);
break;
case BBJ_ALWAYS:
case BBJ_EHCATCHRET:
case BBJ_EHFILTERRET:
VarSetOps::UnionD(this, initVars, block->bbJumpDest->bbScope);
break;
case BBJ_CALLFINALLY:
if (!(block->bbFlags & BBF_RETLESS_CALL))
{
assert(block->isBBCallAlwaysPair());
PREFIX_ASSUME(block->bbNext != nullptr);
VarSetOps::UnionD(this, initVars, block->bbNext->bbScope);
}
VarSetOps::UnionD(this, initVars, block->bbJumpDest->bbScope);
break;
case BBJ_COND:
PREFIX_ASSUME(block->bbNext != nullptr);
VarSetOps::UnionD(this, initVars, block->bbNext->bbScope);
VarSetOps::UnionD(this, initVars, block->bbJumpDest->bbScope);
break;
case BBJ_SWITCH:
{
BasicBlock** jmpTab;
unsigned jmpCnt;
jmpCnt = block->bbJumpSwt->bbsCount;
jmpTab = block->bbJumpSwt->bbsDstTab;
do
{
VarSetOps::UnionD(this, initVars, (*jmpTab)->bbScope);
} while (++jmpTab, --jmpCnt);
}
break;
case BBJ_EHFINALLYRET:
case BBJ_RETURN:
break;
case BBJ_THROW:
/* We don't have to do anything as we mark
* all vars live on entry to a catch handler as
* volatile anyway
*/
break;
default:
noway_assert(!"Unexpected bbJumpKind");
break;
}
/* If the var is already live on entry to the current BB,
we would have already initialized it. So ignore bbLiveIn */
VarSetOps::DiffD(this, initVars, block->bbLiveIn);
/* Add statements initializing the vars, if there are any to initialize */
VarSetOps::Iter iter(this, initVars);
unsigned varIndex = 0;
while (iter.NextElem(&varIndex))
{
/* Create initialization tree */
unsigned varNum = lvaTrackedIndexToLclNum(varIndex);
LclVarDsc* varDsc = lvaGetDesc(varNum);
var_types type = varDsc->TypeGet();
// Don't extend struct lifetimes -- they aren't enregistered, anyway.
if (type == TYP_STRUCT)
{
continue;
}
// If we haven't already done this ...
if (!fgLocalVarLivenessDone)
{
// Create a "zero" node
GenTree* zero = gtNewZeroConNode(genActualType(type));
// Create initialization node
if (!block->IsLIR())
{
GenTree* varNode = gtNewLclvNode(varNum, type);
GenTree* initNode = gtNewAssignNode(varNode, zero);
// Create a statement for the initializer, sequence it, and append it to the current BB.
Statement* initStmt = gtNewStmt(initNode);
gtSetStmtInfo(initStmt);
fgSetStmtSeq(initStmt);
fgInsertStmtNearEnd(block, initStmt);
}
else