-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
promotiondecomposition.cpp
1699 lines (1518 loc) · 62.8 KB
/
promotiondecomposition.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 "promotion.h"
#include "jitstd/algorithm.h"
// Represents a list of statements; this is the result of store decomposition.
class DecompositionStatementList
{
GenTree* m_head = nullptr;
public:
void AddStatement(GenTree* stmt)
{
stmt->gtNext = m_head;
m_head = stmt;
}
GenTree* ToCommaTree(Compiler* comp)
{
if (m_head == nullptr)
{
return comp->gtNewNothingNode();
}
GenTree* tree = m_head;
for (GenTree* cur = m_head->gtNext; cur != nullptr; cur = cur->gtNext)
{
tree = comp->gtNewOperNode(GT_COMMA, TYP_VOID, cur, tree);
}
return tree;
}
};
// Represents a plan for decomposing a block operation into direct treatment of
// replacement fields and the remainder.
class DecompositionPlan
{
struct Entry
{
Replacement* ToReplacement;
Replacement* FromReplacement;
unsigned Offset;
var_types Type;
};
Promotion* m_promotion;
Compiler* m_compiler;
ReplaceVisitor* m_replacer;
AggregateInfoMap& m_aggregates;
PromotionLiveness* m_liveness;
GenTree* m_store;
GenTree* m_src;
bool m_dstInvolvesReplacements;
bool m_srcInvolvesReplacements;
ArrayStack<Entry> m_entries;
bool m_hasNonRemainderUseOfStructLocal = false;
public:
DecompositionPlan(Promotion* prom,
ReplaceVisitor* replacer,
AggregateInfoMap& aggregates,
PromotionLiveness* liveness,
GenTree* store,
GenTree* src,
bool dstInvolvesReplacements,
bool srcInvolvesReplacements)
: m_promotion(prom)
, m_compiler(prom->m_compiler)
, m_replacer(replacer)
, m_aggregates(aggregates)
, m_liveness(liveness)
, m_store(store)
, m_src(src)
, m_dstInvolvesReplacements(dstInvolvesReplacements)
, m_srcInvolvesReplacements(srcInvolvesReplacements)
, m_entries(prom->m_compiler->getAllocator(CMK_Promotion))
{
}
//------------------------------------------------------------------------
// CopyBetweenReplacements:
// Add an entry specifying to copy from a replacement into another replacement.
//
// Parameters:
// dstRep - The destination replacement.
// srcRep - The source replacement.
// offset - The offset this covers in the struct copy.
// type - The type of copy.
//
void CopyBetweenReplacements(Replacement* dstRep, Replacement* srcRep, unsigned offset)
{
m_entries.Push(Entry{dstRep, srcRep, offset, dstRep->AccessType});
}
//------------------------------------------------------------------------
// CopyToReplacement:
// Add an entry specifying to copy from the source into a replacement local.
//
// Parameters:
// dstLcl - The destination local to write.
// offset - The relative offset into the source.
// type - The type of copy.
//
void CopyToReplacement(Replacement* dstRep, unsigned offset)
{
m_entries.Push(Entry{dstRep, nullptr, offset, dstRep->AccessType});
}
//------------------------------------------------------------------------
// CopyFromReplacement:
// Add an entry specifying to copy from a replacement local into the destination.
//
// Parameters:
// srcLcl - The source local to copy from.
// offset - The relative offset into the destination to write.
// type - The type of copy.
//
void CopyFromReplacement(Replacement* srcRep, unsigned offset)
{
m_entries.Push(Entry{nullptr, srcRep, offset, srcRep->AccessType});
}
//------------------------------------------------------------------------
// InitReplacement:
// Add an entry specifying that a specified replacement local should be
// constant initialized.
//
// Parameters:
// dstLcl - The destination local.
// offset - The offset covered by this initialization.
// type - The type to initialize.
//
void InitReplacement(Replacement* dstRep, unsigned offset)
{
m_entries.Push(Entry{dstRep, nullptr, offset, dstRep->AccessType});
}
//------------------------------------------------------------------------
// MarkNonRemainderUseOfStructLocal:
// Mark that some of the destination replacements are being handled via a
// readback. This invalidates liveness information for the remainder
// because the struct local will now also be used for the readback.
//
void MarkNonRemainderUseOfStructLocal()
{
m_hasNonRemainderUseOfStructLocal = true;
}
//------------------------------------------------------------------------
// Finalize:
// Create IR to perform the full decomposed struct copy as specified by
// the entries that were added to the decomposition plan. Add the
// statements to the specified list.
//
// Parameters:
// statements - The list of statements to add to.
//
void Finalize(DecompositionStatementList* statements)
{
if (IsInit())
{
FinalizeInit(statements);
}
else
{
FinalizeCopy(statements);
}
}
//------------------------------------------------------------------------
// CanInitPrimitive:
// Check if we can handle initializing a primitive of the specified type.
// For example, we cannot directly initialize SIMD types to non-zero
// constants.
//
// Parameters:
// type - The primitive type
//
// Returns:
// True if so.
//
bool CanInitPrimitive(var_types type)
{
assert(IsInit());
if (varTypeIsGC(type) || varTypeIsSIMD(type))
{
return GetInitPattern() == 0;
}
return true;
}
private:
//------------------------------------------------------------------------
// IsInit:
// Check if this is an init block operation.
//
// Returns:
// True if so.
//
bool IsInit()
{
return m_src->IsConstInitVal();
}
//------------------------------------------------------------------------
// GetInitPattern:
// For an init block operation, get the pattern to init with.
//
// Returns:
// Byte pattern.
//
uint8_t GetInitPattern()
{
assert(IsInit());
GenTree* cns = m_src->OperIsInitVal() ? m_src->gtGetOp1() : m_src;
return uint8_t(cns->AsIntCon()->IconValue() & 0xFF);
}
//------------------------------------------------------------------------
// ComputeRemainder:
// Compute the remainder of the block operation that needs to be inited
// or copied after the replacements stored in the plan have been handled.
//
// Returns:
// Segments representing the remainder.
//
// Remarks:
// This function takes into account that insignificant padding does not
// need to be considered part of the remainder. For example, the last 4
// bytes of Span<T> on 64-bit are not returned as the remainder.
//
StructSegments ComputeRemainder()
{
ClassLayout* dstLayout = m_store->GetLayout(m_compiler);
StructSegments segments = m_promotion->SignificantSegments(dstLayout);
for (int i = 0; i < m_entries.Height(); i++)
{
const Entry& entry = m_entries.BottomRef(i);
segments.Subtract(StructSegments::Segment(entry.Offset, entry.Offset + genTypeSize(entry.Type)));
}
#ifdef DEBUG
if (m_compiler->verbose)
{
printf(" Block op remainder: ");
segments.Dump();
printf("\n");
}
#endif
return segments;
}
// Represents the strategy for handling the remainder part of the block
// operation.
struct RemainderStrategy
{
enum
{
NoRemainder,
Primitive,
FullBlock,
};
int Type;
unsigned PrimitiveOffset;
var_types PrimitiveType;
RemainderStrategy(int type, unsigned primitiveOffset = 0, var_types primitiveType = TYP_UNDEF)
: Type(type)
, PrimitiveOffset(primitiveOffset)
, PrimitiveType(primitiveType)
{
}
};
//------------------------------------------------------------------------
// DetermineRemainderStrategy:
// Determine the strategy to use to handle the remaining parts of the struct
// once replacements have been handled.
//
// Returns:
// Type describing how it should be handled; for example, by a full block
// copy (that may be redundant with some of the replacements, but covers
// the rest of the remainder); or by handling a specific 'hole' as a
// primitive.
//
RemainderStrategy DetermineRemainderStrategy(const StructDeaths& dstDeaths)
{
if (m_dstInvolvesReplacements && !m_hasNonRemainderUseOfStructLocal && dstDeaths.IsRemainderDying())
{
JITDUMP(" => Remainder strategy: do nothing (remainder dying)\n");
return RemainderStrategy(RemainderStrategy::NoRemainder);
}
StructSegments remainder = ComputeRemainder();
if (remainder.IsEmpty())
{
JITDUMP(" => Remainder strategy: do nothing (no remainder)\n");
return RemainderStrategy(RemainderStrategy::NoRemainder);
}
StructSegments::Segment segment;
// See if we can "plug the hole" with a single primitive.
if (remainder.CoveringSegment(&segment))
{
var_types primitiveType = TYP_UNDEF;
unsigned size = segment.End - segment.Start;
ClassLayout* dstLayout = m_store->GetLayout(m_compiler);
if ((size == TARGET_POINTER_SIZE) && ((segment.Start % TARGET_POINTER_SIZE) == 0))
{
primitiveType = dstLayout->GetGCPtrType(segment.Start / TARGET_POINTER_SIZE);
}
else if (!dstLayout->IntersectsGCPtr(segment.Start, size))
{
switch (size)
{
case 1:
primitiveType = TYP_UBYTE;
break;
case 2:
primitiveType = TYP_USHORT;
break;
case 4:
primitiveType = TYP_INT;
break;
#ifdef TARGET_64BIT
case 8:
primitiveType = TYP_LONG;
break;
#endif
#ifdef FEATURE_SIMD
case 16:
if (m_compiler->getPreferredVectorByteLength() >= 16)
{
primitiveType = TYP_SIMD16;
}
break;
#ifdef TARGET_XARCH
case 32:
if (m_compiler->getPreferredVectorByteLength() >= 32)
{
primitiveType = TYP_SIMD32;
}
break;
case 64:
if (m_compiler->getPreferredVectorByteLength() >= 64)
{
primitiveType = TYP_SIMD64;
}
break;
#endif
#endif
}
}
if (primitiveType != TYP_UNDEF)
{
if (!IsInit() || CanInitPrimitive(primitiveType))
{
JITDUMP(" => Remainder strategy: %s at +%03u\n", varTypeName(primitiveType), segment.Start);
return RemainderStrategy(RemainderStrategy::Primitive, segment.Start, primitiveType);
}
else
{
JITDUMP(" Cannot handle initing remainder as primitive of type %s\n", varTypeName(primitiveType));
}
}
}
JITDUMP(" => Remainder strategy: retain a full block op\n");
return RemainderStrategy(RemainderStrategy::FullBlock);
}
//------------------------------------------------------------------------
// FinalizeInit:
// Create IR to perform the decomposed initialization.
//
// Parameters:
// statements - List to add statements to.
//
void FinalizeInit(DecompositionStatementList* statements)
{
uint8_t initPattern = GetInitPattern();
StructDeaths deaths = m_liveness->GetDeathsForStructLocal(m_store->AsLclVarCommon());
AggregateInfo* agg = m_aggregates.Lookup(m_store->AsLclVarCommon()->GetLclNum());
assert((agg != nullptr) && (agg->Replacements.size() > 0));
Replacement* firstRep = agg->Replacements.data();
for (int i = 0; i < m_entries.Height(); i++)
{
const Entry& entry = m_entries.BottomRef(i);
assert(entry.ToReplacement != nullptr);
assert((entry.ToReplacement >= firstRep) && (entry.ToReplacement < firstRep + agg->Replacements.size()));
size_t replacementIndex = entry.ToReplacement - firstRep;
if (!deaths.IsReplacementDying((unsigned)replacementIndex))
{
GenTree* value = m_compiler->gtNewConWithPattern(entry.Type, initPattern);
GenTree* store = m_compiler->gtNewStoreLclVarNode(entry.ToReplacement->LclNum, value);
statements->AddStatement(store);
}
m_replacer->ClearNeedsReadBack(*entry.ToReplacement);
m_replacer->SetNeedsWriteBack(*entry.ToReplacement);
}
RemainderStrategy remainderStrategy = DetermineRemainderStrategy(deaths);
if (remainderStrategy.Type == RemainderStrategy::FullBlock)
{
statements->AddStatement(m_store);
}
else if (remainderStrategy.Type == RemainderStrategy::Primitive)
{
GenTree* value = m_compiler->gtNewConWithPattern(remainderStrategy.PrimitiveType, initPattern);
LocationAccess storeAccess;
storeAccess.InitializeLocal(m_store->AsLclVarCommon());
GenTree* store = storeAccess.CreateStore(remainderStrategy.PrimitiveOffset, remainderStrategy.PrimitiveType,
value, m_compiler);
statements->AddStatement(store);
}
}
//------------------------------------------------------------------------
// FinalizeCopy:
// Create IR to perform the decomposed copy.
//
// Parameters:
// statements - List to add statements to.
//
void FinalizeCopy(DecompositionStatementList* statements)
{
assert(m_store->OperIs(GT_STORE_LCL_VAR, GT_STORE_LCL_FLD, GT_STORE_BLK) &&
m_src->OperIs(GT_LCL_VAR, GT_LCL_FLD, GT_BLK));
StructDeaths dstDeaths;
if (m_dstInvolvesReplacements)
{
dstDeaths = m_liveness->GetDeathsForStructLocal(m_store->AsLclVarCommon());
}
RemainderStrategy remainderStrategy = DetermineRemainderStrategy(dstDeaths);
// If the remainder is a full block and is going to incur write barrier
// then avoid incurring multiple write barriers for each source
// replacement that is a GC pointer -- write them back to the struct
// first instead. That is, instead of:
//
// ▌ COMMA void
// ├──▌ STORE_BLK struct<Program+S, 32> <- write barrier
// │ ├──▌ LCL_VAR byref V01 arg1
// │ └──▌ LCL_VAR struct<Program+S, 32> V00 arg0
// └──▌ COMMA void
// ├──▌ STOREIND ref <- write barrier
// │ ├───▌ ADD byref
// │ │ ├──▌ LCL_VAR byref V01 arg1
// │ │ └──▌ CNS_INT long 8
// │ └──▌ LCL_VAR ref V05 tmp3
// └──▌ STOREIND ref <- write barrier
// ├──▌ ADD byref
// │ ├──▌ LCL_VAR byref V01 arg1
// │ └──▌ CNS_INT long 24
// └──▌ LCL_VAR ref V06 tmp4
//
// Produce:
//
// ▌ COMMA void
// ├──▌ STORE_LCL_FLD ref V00 arg0 [+8] <- no write barrier
// │ └──▌ LCL_VAR ref V05 tmp3
// └──▌ COMMA void
// ├──▌ STORE_LCL_FLD ref V00 arg0 [+24] <- no write barrier
// │ └──▌ LCL_VAR ref V06 tmp4
// └──▌ STORE_BLK struct<Program+S, 32> <- write barrier
// ├──▌ LCL_VAR byref V01 arg1 (last use)
// └──▌ LCL_VAR struct<Program+S, 32> V00 arg0
//
if ((remainderStrategy.Type == RemainderStrategy::FullBlock) && m_store->OperIs(GT_STORE_BLK) &&
m_store->AsBlk()->GetLayout()->HasGCPtr())
{
for (int i = 0; i < m_entries.Height(); i++)
{
const Entry& entry = m_entries.BottomRef(i);
if ((entry.FromReplacement != nullptr) && (entry.Type == TYP_REF))
{
Replacement* rep = entry.FromReplacement;
if (rep->NeedsWriteBack)
{
statements->AddStatement(
Promotion::CreateWriteBack(m_compiler, m_src->AsLclVarCommon()->GetLclNum(), *rep));
JITDUMP(" Will write back V%02u (%s) to avoid an additional write barrier\n", rep->LclNum,
rep->Description);
// The loop below will skip these replacements as an
// optimization if it is going to copy the struct
// anyway.
m_replacer->ClearNeedsWriteBack(*rep);
}
}
}
}
// We prefer to do the remainder at the end, if possible, since CQ
// analysis shows that this is best. However, handling the remainder
// may overwrite the destination with stale bits if the source has
// replacements (since handling the remainder copies from the struct,
// and the fresh values are usually in the replacement locals).
bool handleRemainderFirst = RemainderOverwritesDestinationWithStaleBits(remainderStrategy, dstDeaths);
GenTree* addr = nullptr;
target_ssize_t addrBaseOffs = 0;
FieldSeq* addrBaseOffsFldSeq = nullptr;
GenTreeFlags indirFlags = GTF_EMPTY;
if (m_store->OperIs(GT_STORE_BLK))
{
addr = m_store->AsIndir()->Addr();
indirFlags = m_store->gtFlags & GTF_IND_COPYABLE_FLAGS;
}
else if (m_src->OperIs(GT_BLK))
{
addr = m_src->AsIndir()->Addr();
indirFlags = m_src->gtFlags & GTF_IND_COPYABLE_FLAGS;
}
int numAddrUses = 0;
bool needsNullCheck = false;
if (addr != nullptr)
{
for (int i = 0; i < m_entries.Height(); i++)
{
if (!CanSkipEntry(m_entries.BottomRef(i), dstDeaths, remainderStrategy))
{
numAddrUses++;
}
}
if (remainderStrategy.Type != RemainderStrategy::NoRemainder)
{
numAddrUses++;
}
if (m_compiler->fgAddrCouldBeNull(addr))
{
if (handleRemainderFirst)
{
needsNullCheck = (remainderStrategy.Type == RemainderStrategy::Primitive) &&
m_compiler->fgIsBigOffset(remainderStrategy.PrimitiveOffset);
}
else
{
needsNullCheck = true;
// See if our first indirection will subsume the null check (usual case).
for (int i = 0; i < m_entries.Height(); i++)
{
if (CanSkipEntry(m_entries.BottomRef(i), dstDeaths, remainderStrategy))
{
continue;
}
const Entry& entry = m_entries.BottomRef(i);
assert((entry.FromReplacement == nullptr) || (entry.ToReplacement == nullptr));
needsNullCheck = m_compiler->fgIsBigOffset(entry.Offset);
break;
}
}
}
if (needsNullCheck)
{
numAddrUses++;
}
if (numAddrUses > 1)
{
m_compiler->gtPeelOffsets(&addr, &addrBaseOffs, &addrBaseOffsFldSeq);
if (CanReuseAddressForDecomposedStore(addr))
{
if (addr->OperIsLocalRead())
{
// We will introduce more uses of the address local, so it is
// no longer dying here.
addr->gtFlags &= ~GTF_VAR_DEATH;
}
}
else
{
unsigned addrLcl =
m_compiler->lvaGrabTemp(true DEBUGARG("Spilling address for field-by-field copy"));
statements->AddStatement(m_compiler->gtNewTempStore(addrLcl, addr));
addr = m_compiler->gtNewLclvNode(addrLcl, addr->TypeGet());
}
}
}
// Create helper types to create accesses.
LocationAccess* indirAccess = nullptr;
LocationAccess storeAccess;
if (m_store->OperIs(GT_STORE_BLK))
{
storeAccess.InitializeIndir(addr, addrBaseOffs, addrBaseOffsFldSeq, indirFlags, numAddrUses);
indirAccess = &storeAccess;
}
else
{
storeAccess.InitializeLocal(m_store->AsLclVarCommon());
}
LocationAccess srcAccess;
if (m_src->OperIs(GT_BLK))
{
srcAccess.InitializeIndir(addr, addrBaseOffs, addrBaseOffsFldSeq, indirFlags, numAddrUses);
indirAccess = &srcAccess;
}
else
{
srcAccess.InitializeLocal(m_src->AsLclVarCommon());
}
if (needsNullCheck)
{
assert(indirAccess != nullptr);
GenTree* nullCheck = indirAccess->CreateRead(0, TYP_BYTE, m_compiler);
statements->AddStatement(nullCheck);
}
if (handleRemainderFirst)
{
CopyRemainder(storeAccess, srcAccess, remainderStrategy, statements);
if (m_src->OperIs(GT_LCL_VAR, GT_LCL_FLD))
{
// We will introduce uses of the source below so this struct
// copy is no longer the last use if it was before.
m_src->gtFlags &= ~GTF_VAR_DEATH;
}
}
StructDeaths srcDeaths;
if (m_srcInvolvesReplacements)
{
srcDeaths = m_liveness->GetDeathsForStructLocal(m_src->AsLclVarCommon());
}
for (int i = 0; i < m_entries.Height(); i++)
{
const Entry& entry = m_entries.BottomRef(i);
if (entry.ToReplacement != nullptr)
{
m_replacer->ClearNeedsReadBack(*entry.ToReplacement);
m_replacer->SetNeedsWriteBack(*entry.ToReplacement);
}
if (CanSkipEntry(entry, dstDeaths, remainderStrategy DEBUGARG(/* dump */ true)))
{
continue;
}
GenTree* src;
if (entry.FromReplacement != nullptr)
{
src = m_compiler->gtNewLclvNode(entry.FromReplacement->LclNum, entry.Type);
if (entry.FromReplacement != nullptr)
{
AggregateInfo* srcAgg = m_aggregates.Lookup(m_src->AsLclVarCommon()->GetLclNum());
Replacement* firstRep = srcAgg->Replacements.data();
assert((entry.FromReplacement >= firstRep) &&
(entry.FromReplacement < (firstRep + srcAgg->Replacements.size())));
size_t replacementIndex = entry.FromReplacement - firstRep;
if (srcDeaths.IsReplacementDying((unsigned)replacementIndex))
{
src->gtFlags |= GTF_VAR_DEATH;
m_replacer->CheckForwardSubForLastUse(entry.FromReplacement->LclNum);
}
}
}
else
{
src = srcAccess.CreateRead(entry.Offset, entry.Type, m_compiler);
}
GenTree* store;
if (entry.ToReplacement != nullptr)
{
store = m_compiler->gtNewStoreLclVarNode(entry.ToReplacement->LclNum, src);
}
else
{
store = storeAccess.CreateStore(entry.Offset, entry.Type, src, m_compiler);
}
statements->AddStatement(store);
}
if (!handleRemainderFirst)
{
CopyRemainder(storeAccess, srcAccess, remainderStrategy, statements);
}
INDEBUG(storeAccess.CheckFullyUsed());
INDEBUG(srcAccess.CheckFullyUsed());
}
//------------------------------------------------------------------------
// CanSkipEntry:
// Check if the specified entry can be skipped because it is writing to a
// dead replacement or because the remainder would handle it anyway.
//
// Parameters:
// entry - The init/copy entry
// deaths - Liveness information for the destination; only valid if m_dstInvolvedReplacements is true.
// remainderStrategy - The strategy we are using for the remainder
// dump - Whether to JITDUMP decisions made
//
bool CanSkipEntry(const Entry& entry,
const StructDeaths& deaths,
const RemainderStrategy& remainderStrategy DEBUGARG(bool dump = false))
{
if (entry.ToReplacement != nullptr)
{
// Check if this entry is dying anyway.
assert(m_dstInvolvesReplacements);
AggregateInfo* agg = m_aggregates.Lookup(m_store->AsLclVarCommon()->GetLclNum());
assert((agg != nullptr) && (agg->Replacements.size() > 0));
Replacement* firstRep = agg->Replacements.data();
assert((entry.ToReplacement >= firstRep) && (entry.ToReplacement < (firstRep + agg->Replacements.size())));
size_t replacementIndex = entry.ToReplacement - firstRep;
if (deaths.IsReplacementDying((unsigned)replacementIndex))
{
#ifdef DEBUG
if (dump)
{
JITDUMP(" Skipping def of V%02u (%s); it is dying\n", entry.ToReplacement->LclNum,
entry.ToReplacement->Description);
}
#endif
return true;
}
}
else
{
// If the destination has replacements we still have usable
// liveness information for the remainder. This case happens if the
// source was also promoted.
if (m_dstInvolvesReplacements && !m_hasNonRemainderUseOfStructLocal && deaths.IsRemainderDying())
{
#ifdef DEBUG
if (dump)
{
JITDUMP(" Skipping write to dst+%03u; it is the remainder and the remainder is dying\n",
entry.Offset);
}
#endif
return true;
}
}
if (entry.FromReplacement != nullptr)
{
// Check if the remainder is going to handle it.
if ((remainderStrategy.Type == RemainderStrategy::FullBlock) && !entry.FromReplacement->NeedsWriteBack &&
(entry.ToReplacement == nullptr))
{
#ifdef DEBUG
if (dump)
{
JITDUMP(" Skipping dst+%03u <- V%02u (%s); it is up-to-date in its struct local and will be "
"handled as part of the remainder\n",
entry.Offset, entry.FromReplacement->LclNum, entry.FromReplacement->Description);
}
#endif
return true;
}
}
return false;
}
//------------------------------------------------------------------------
// CanReuseAddressForDecomposedStore: Check if it is safe to reuse the
// specified address node for each decomposed store of a block copy.
//
// Arguments:
// addrNode - The address node
//
// Return Value:
// True if the caller can reuse the address by cloning.
//
bool CanReuseAddressForDecomposedStore(GenTree* addrNode)
{
if (addrNode->OperIsLocalRead())
{
GenTreeLclVarCommon* lcl = addrNode->AsLclVarCommon();
unsigned lclNum = lcl->GetLclNum();
LclVarDsc* dsc = m_compiler->lvaGetDesc(lclNum);
if (dsc->IsAddressExposed())
{
// Address could be pointing to itself
return false;
}
// If we aren't writing a local here then since the address is not
// exposed it cannot change.
if (!m_store->OperIsLocalStore())
{
return true;
}
// Otherwise it could still be possible that the address is part of
// the struct we're writing.
unsigned dstLclNum = m_store->AsLclVarCommon()->GetLclNum();
if ((lclNum == dstLclNum) || (dsc->lvIsStructField && (dsc->lvParentLcl == dstLclNum)))
{
return false;
}
// It could also be one of the replacement locals we're going to write.
for (int i = 0; i < m_entries.Height(); i++)
{
const Entry& entry = m_entries.BottomRef(i);
if ((entry.ToReplacement != nullptr) && (entry.ToReplacement->LclNum == lclNum))
{
return false;
}
}
return true;
}
return addrNode->IsInvariant();
}
//------------------------------------------------------------------------
// RemainderOverwritesDestinationWithStaleBits:
// Check if handling the remainder is going to write stale bits to the
// destination.
//
// Parameters:
// remainderStrategy - The remainder strategy
// dstDeaths - Destination liveness
//
// Returns:
// True if so.
//
// Remarks:
// We usually prefer to write the remainder last as CQ analysis shows
// that to be most beneficial. However, if we do that we may overwrite
// the destination with stale bits. This occurs if the source has
// replacements. Handling the remainder copies from the source struct
// local, but the up-to-date values may be in its replacement locals. So
// we must take care to write the replacement locals _after_ the
// remainder has been written.
//
bool RemainderOverwritesDestinationWithStaleBits(const RemainderStrategy& remainderStrategy,
const StructDeaths& dstDeaths)
{
if (!m_srcInvolvesReplacements)
{
return false;
}
switch (remainderStrategy.Type)
{
case RemainderStrategy::FullBlock:
return true;
case RemainderStrategy::Primitive:
for (int i = 0; i < m_entries.Height(); i++)
{
const Entry& entry = m_entries.BottomRef(i);
if (entry.Offset + genTypeSize(entry.Type) <= remainderStrategy.PrimitiveOffset)
{
// Entry ends before remainder starts
continue;
}
// Remainder ends before entry starts
if (remainderStrategy.PrimitiveOffset + genTypeSize(remainderStrategy.PrimitiveType) <=
entry.Offset)
{
continue;
}
// Are we even going to write the entry?
if (!CanSkipEntry(entry, dstDeaths, remainderStrategy))
{
// Yep, so we need to be careful.
return true;
}
}
// No entry overlaps.
return false;
default:
return false;
}
}
// Helper class to create derived accesses off of a location: either a
// local, or as indirections off of an address.
class LocationAccess
{
GenTreeLclVarCommon* m_local = nullptr;
GenTree* m_addr = nullptr;
target_ssize_t m_addrBaseOffs = 0;
FieldSeq* m_addrBaseOffsFldSeq = nullptr;
GenTreeFlags m_indirFlags = GTF_EMPTY;
int m_numUsesLeft = -1;
public:
//------------------------------------------------------------------------
// InitializeIndir:
// Initialize this to represent an indirection.
//
// Parameters:
// addr - The address of the indirection
// addrBaseOffs - Base offset to add on top of the address.
// addrBaseOffsFldSeq - Field sequence for the base offset
// indirFlags - Indirection flags to add to created accesses
// numExpectedUses - Number of derived indirections that are expected to be created.
//
void InitializeIndir(GenTree* addr,
target_ssize_t addrBaseOffs,
FieldSeq* addrBaseOffsFldSeq,
GenTreeFlags indirFlags,
int numExpectedUses)
{
m_addr = addr;
m_addrBaseOffs = addrBaseOffs;
m_addrBaseOffsFldSeq = addrBaseOffsFldSeq;
m_indirFlags = indirFlags;
m_numUsesLeft = numExpectedUses;
}
//------------------------------------------------------------------------
// InitializeLocal:
// Initialize this to represent a local.
//
// Parameters:
// local - The local
//
void InitializeLocal(GenTreeLclVarCommon* local)
{
m_local = local;
}
//------------------------------------------------------------------------
// CreateRead:
// Create a read from this location.
//
// Parameters:
// offs - Offset
// type - Type of store
// comp - Compiler instance
//
// Returns:
// IR node to perform the read.
//
GenTree* CreateRead(unsigned offs, var_types type, Compiler* comp)
{
if (m_addr != nullptr)
{
GenTreeIndir* indir = comp->gtNewIndir(type, GrabAddress(offs, comp), GetIndirFlags(type));
return indir;
}
// Check if the source has a regularly promoted field at this offset.
unsigned fieldLclNum = FindRegularlyPromotedField(offs, comp);
if ((fieldLclNum != BAD_VAR_NUM) && (comp->lvaGetDesc(fieldLclNum)->TypeGet() == type))
{
return comp->gtNewLclvNode(fieldLclNum, type);
}
GenTreeLclFld* fld = comp->gtNewLclFldNode(m_local->GetLclNum(), type, m_local->GetLclOffs() + offs);
comp->lvaSetVarDoNotEnregister(m_local->GetLclNum() DEBUGARG(DoNotEnregisterReason::LocalField));
return fld;
}
//------------------------------------------------------------------------