forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathasync.cpp
More file actions
3109 lines (2667 loc) · 121 KB
/
Copy pathasync.cpp
File metadata and controls
3109 lines (2667 loc) · 121 KB
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.
//
// This file implements the transformation of C# async methods into state
// machines. The following key operations are performed:
//
// 1. Early, after import but before inlining: for async calls that require
// ExecutionContext/SynchronizationContext save/restore semantics, capture and
// restore calls are inserted around the async call site. This ensures proper
// context flow across await boundaries when the continuation may run on
// different threads or synchronization contexts. The captured contexts
// are stored in temporary locals and restored after the async call completes,
// with special handling for calls inside try regions using try-finally blocks.
//
// Later, right before lowering the actual transformation to a state machine is
// performed:
//
// 2. Each async call becomes a suspension point where execution can pause and
// return to the caller, accompanied by a resumption point where execution can
// continue when the awaited operation completes.
//
// 3. When suspending at a suspension point a continuation object is created that contains:
// - All live local variables
// - State number to identify which await is being resumed
// - Return value from the awaited operation (filled in by the callee later)
// - Exception information if an exception occurred
// - Resumption function pointer
// - Flags containing additional information
//
// 4. The method entry is modified to include dispatch logic that checks for an
// incoming continuation and jumps to the appropriate resumption point.
//
// 5. Special handling is included for:
// - Exception propagation across await boundaries
// - Return value management for different types (primitives, references, structs)
// - Tiered compilation and On-Stack Replacement (OSR)
// - Optimized state capture based on variable liveness analysis
//
// The transformation ensures that the semantics of the original async method are
// preserved while enabling efficient suspension and resumption of execution.
//
#include "jitpch.h"
#include "jitstd/algorithm.h"
#include "async.h"
//------------------------------------------------------------------------
// Compiler::SaveAsyncContexts:
// Insert code in async methods that saves and restores contexts.
//
// Returns:
// Suitable phase status.
//
// Remarks:
// This inserts code to save the current ExecutionContext and
// SynchronizationContext at the beginning of async functions, and code that
// restores these contexts at the end. Additionally inserts uses of each of
// these context at async calls to model the fact that on suspension, these
// locals will be used there.
//
PhaseStatus Compiler::SaveAsyncContexts()
{
if ((info.compMethodInfo->options & CORINFO_ASYNC_SAVE_CONTEXTS) == 0)
{
return PhaseStatus::MODIFIED_NOTHING;
}
// Create locals for ExecutionContext and SynchronizationContext
lvaAsyncExecutionContextVar = lvaGrabTemp(false DEBUGARG("Async ExecutionContext"));
lvaGetDesc(lvaAsyncExecutionContextVar)->lvType = TYP_REF;
lvaAsyncSynchronizationContextVar = lvaGrabTemp(false DEBUGARG("Async SynchronizationContext"));
lvaGetDesc(lvaAsyncSynchronizationContextVar)->lvType = TYP_REF;
if (opts.IsOSR())
{
lvaGetDesc(lvaAsyncExecutionContextVar)->lvIsOSRLocal = true;
lvaGetDesc(lvaAsyncSynchronizationContextVar)->lvIsOSRLocal = true;
}
// Create try-fault structure. This is actually a try-finally, but we
// manually insert the restore code in a (merged) return block, so EH wise
// we only need to restore on fault.
BasicBlock* const tryBegBB = fgSplitBlockAtBeginning(fgFirstBB);
BasicBlock* const tryLastBB = fgLastBB;
// Create fault handler block
BasicBlock* faultBB = fgNewBBafter(BBJ_EHFAULTRET, tryLastBB, false);
faultBB->bbRefs = 1; // Artificial ref count
faultBB->inheritWeightPercentage(tryBegBB, 0);
// Add a new EH table entry. It encloses all others, so placing it at the
// end is the right thing to do.
unsigned XTnew = compHndBBtabCount;
EHblkDsc* newEntry = fgTryAddEHTableEntries(XTnew);
if (newEntry == nullptr)
{
IMPL_LIMITATION("too many exception clauses");
}
// Initialize the new entry
asyncContextRestoreEHID = impInlineRoot()->compEHID++;
newEntry->ebdID = asyncContextRestoreEHID;
newEntry->ebdHandlerType = EH_HANDLER_FAULT;
newEntry->ebdTryBeg = tryBegBB;
newEntry->ebdTryLast = tryLastBB;
newEntry->ebdHndBeg = faultBB;
newEntry->ebdHndLast = faultBB;
newEntry->ebdTyp = 0; // unused for fault
newEntry->ebdEnclosingTryIndex = EHblkDsc::NO_ENCLOSING_INDEX;
newEntry->ebdEnclosingHndIndex = EHblkDsc::NO_ENCLOSING_INDEX;
newEntry->ebdTryBegOffset = tryBegBB->bbCodeOffs;
newEntry->ebdTryEndOffset = tryLastBB->bbCodeOffsEnd;
newEntry->ebdFilterBegOffset = 0;
newEntry->ebdHndBegOffset = 0;
newEntry->ebdHndEndOffset = 0;
// Set flags on new region
tryBegBB->SetFlags(BBF_DONT_REMOVE | BBF_IMPORTED);
faultBB->SetFlags(BBF_DONT_REMOVE | BBF_IMPORTED);
faultBB->bbCatchTyp = BBCT_FAULT;
tryBegBB->setTryIndex(XTnew);
tryBegBB->clearHndIndex();
faultBB->clearTryIndex();
faultBB->setHndIndex(XTnew);
// Walk user code blocks and set try index
for (BasicBlock* tmpBB = tryBegBB->Next(); tmpBB != faultBB; tmpBB = tmpBB->Next())
{
if (!tmpBB->hasTryIndex())
{
tmpBB->setTryIndex(XTnew);
}
}
// Walk EH table and update enclosing try indices
for (unsigned XTnum = 0; XTnum < XTnew; XTnum++)
{
EHblkDsc* HBtab = &compHndBBtab[XTnum];
if (HBtab->ebdEnclosingTryIndex == EHblkDsc::NO_ENCLOSING_INDEX)
{
HBtab->ebdEnclosingTryIndex = (unsigned short)XTnew;
}
}
JITDUMP("Created EH descriptor EH#%u for try/fault wrapping body to save/restore async contexts\n", XTnew);
INDEBUG(fgVerifyHandlerTab());
// Get async helper methods
CORINFO_ASYNC_INFO* asyncInfo = eeGetAsyncInfo();
// Insert CaptureContexts call before the try (keep it before so the
// try/finally can be removed if there is no exception side effects).
// For OSR, we did this in the tier0 method.
if (!opts.IsOSR())
{
GenTreeCall* captureCall = gtNewCallNode(CT_USER_FUNC, asyncInfo->captureContextsMethHnd, TYP_VOID);
captureCall->gtArgs.PushFront(this,
NewCallArg::Primitive(gtNewLclAddrNode(lvaAsyncSynchronizationContextVar, 0)));
captureCall->gtArgs.PushFront(this, NewCallArg::Primitive(gtNewLclAddrNode(lvaAsyncExecutionContextVar, 0)));
lvaGetDesc(lvaAsyncSynchronizationContextVar)->lvHasLdAddrOp = true;
lvaGetDesc(lvaAsyncExecutionContextVar)->lvHasLdAddrOp = true;
#ifdef FEATURE_READYTORUN
CORINFO_CONST_LOOKUP captureEntryPoint;
info.compCompHnd->getFunctionEntryPoint(asyncInfo->captureContextsMethHnd, &captureEntryPoint);
captureCall->setEntryPoint(captureEntryPoint);
#endif
CORINFO_CALL_INFO callInfo = {};
callInfo.hMethod = captureCall->gtCallMethHnd;
callInfo.methodFlags = info.compCompHnd->getMethodAttribs(callInfo.hMethod);
impMarkInlineCandidate(captureCall, MAKE_METHODCONTEXT(callInfo.hMethod), false, &callInfo, compInlineContext);
Statement* captureStmt = fgNewStmtFromTree(captureCall);
fgInsertStmtAtBeg(fgFirstBB, captureStmt);
JITDUMP("Inserted capture\n");
DISPSTMT(captureStmt);
}
// Insert RestoreContexts call in fault (exceptional case)
// First argument: resumed = (continuation != null)
GenTree* resumed;
if (compIsForInlining())
{
resumed = gtNewFalse();
}
else
{
GenTree* continuation = gtNewLclvNode(lvaAsyncContinuationArg, TYP_REF);
GenTree* null = gtNewNull();
resumed = gtNewOperNode(GT_NE, TYP_INT, continuation, null);
}
GenTreeCall* restoreCall = gtNewCallNode(CT_USER_FUNC, asyncInfo->restoreContextsMethHnd, TYP_VOID);
restoreCall->gtArgs.PushFront(this,
NewCallArg::Primitive(gtNewLclVarNode(lvaAsyncSynchronizationContextVar, TYP_REF)));
restoreCall->gtArgs.PushFront(this, NewCallArg::Primitive(gtNewLclVarNode(lvaAsyncExecutionContextVar, TYP_REF)));
restoreCall->gtArgs.PushFront(this, NewCallArg::Primitive(resumed));
#ifdef FEATURE_READYTORUN
{
CORINFO_CONST_LOOKUP restoreEntryPoint;
info.compCompHnd->getFunctionEntryPoint(asyncInfo->restoreContextsMethHnd, &restoreEntryPoint);
restoreCall->setEntryPoint(restoreEntryPoint);
}
#endif
Statement* restoreStmt = fgNewStmtFromTree(restoreCall);
fgInsertStmtAtEnd(faultBB, restoreStmt);
// Now insert uses of the new contexts to all async calls (modelling the
// fact that on suspension, we restore the context from those values). Also
// convert BBJ_RETURNs into an exit to a block outside the region.
BasicBlock* newReturnBB = nullptr;
unsigned mergedReturnLcl = BAD_VAR_NUM;
for (BasicBlock* block : Blocks())
{
if (!compIsForInlining())
{
AddContextArgsToAsyncCalls(block);
}
if (!block->KindIs(BBJ_RETURN) || (block == newReturnBB))
{
continue;
}
JITDUMP("Merging BBJ_RETURN block " FMT_BB "\n", block->bbNum);
if (newReturnBB == nullptr)
{
newReturnBB = CreateReturnBB(&mergedReturnLcl);
newReturnBB->inheritWeightPercentage(block, 0);
}
// When inlining we do merging during import, so we do not need to do
// any storing there.
if (!compIsForInlining())
{
// Store return value to common local
Statement* retStmt = block->lastStmt();
assert((retStmt != nullptr) && retStmt->GetRootNode()->OperIs(GT_RETURN));
if (mergedReturnLcl != BAD_VAR_NUM)
{
GenTree* retVal = retStmt->GetRootNode()->AsOp()->GetReturnValue();
Statement* insertAfter = retStmt;
GenTree* storeRetVal = gtNewTempStore(mergedReturnLcl, retVal, CHECK_SPILL_NONE, &insertAfter,
retStmt->GetDebugInfo(), block);
Statement* storeStmt = fgNewStmtFromTree(storeRetVal);
fgInsertStmtAtEnd(block, storeStmt);
JITDUMP("Inserted store to common return local\n");
DISPSTMT(storeStmt);
}
retStmt->GetRootNode()->gtBashToNOP();
}
// Jump to new shared restore + return block
block->SetKindAndTargetEdge(BBJ_ALWAYS, fgAddRefPred(newReturnBB, block));
fgReturnCount--;
}
if (newReturnBB != nullptr)
{
newReturnBB->bbWeight = newReturnBB->computeIncomingWeight();
}
// After merging of returns we have at most 1 return (and we may have 0, if
// there were no returns before due to infinite loops or exceptions).
assert(fgReturnCount <= 1);
return PhaseStatus::MODIFIED_EVERYTHING;
}
//------------------------------------------------------------------------
// Compiler::AddContextArgsToAsyncCalls:
// Add uses of the saved ExecutionContext and SynchronizationContext to all
// async calls.
//
// Remarks:
// This models the fact that calls have uses of the saved contexts on
// suspension. The async transformation will later move the uses into the
// suspension code path.
//
void Compiler::AddContextArgsToAsyncCalls(BasicBlock* block)
{
struct Visitor : GenTreeVisitor<Visitor>
{
enum
{
DoPreOrder = true,
};
Visitor(Compiler* comp)
: GenTreeVisitor(comp)
{
}
fgWalkResult PreOrderVisit(GenTree** use, GenTree* user)
{
GenTree* tree = *use;
if ((tree->gtFlags & GTF_CALL) == 0)
{
return WALK_SKIP_SUBTREES;
}
if (!tree->IsCall() || !tree->AsCall()->IsAsync())
{
return WALK_CONTINUE;
}
GenTreeCall* call = tree->AsCall();
GenTree* execCtx = m_compiler->gtNewLclVarNode(m_compiler->lvaAsyncExecutionContextVar, TYP_REF);
GenTree* syncCtx = m_compiler->gtNewLclVarNode(m_compiler->lvaAsyncSynchronizationContextVar, TYP_REF);
JITDUMP("Adding exec context [%06u], sync context [%06u] to async call [%06u]\n", dspTreeID(execCtx),
dspTreeID(syncCtx), dspTreeID(call));
call->gtArgs.PushFront(m_compiler,
NewCallArg::Primitive(syncCtx).WellKnown(WellKnownArg::AsyncSynchronizationContext));
call->gtArgs.PushFront(m_compiler,
NewCallArg::Primitive(execCtx).WellKnown(WellKnownArg::AsyncExecutionContext));
return WALK_CONTINUE;
}
};
Visitor visitor(this);
for (Statement* stmt : block->Statements())
{
visitor.WalkTree(stmt->GetRootNodePointer(), nullptr);
}
}
//------------------------------------------------------------------------
// Compiler::CreateReturnBB:
// Create a new return block to exit the async method.
//
// Parameters:
// mergedReturnLcl - [out] The local created to hold the merged return value.
// BAD_VAR_NUM if the async method does not return a result.
//
// Returns:
// A new basic block that restores contexts and returns a merged result.
//
BasicBlock* Compiler::CreateReturnBB(unsigned* mergedReturnLcl)
{
BasicBlock* newReturnBB = fgNewBBafter(BBJ_RETURN, fgLastBB, /* extendRegion */ false);
newReturnBB->bbTryIndex = 0; // EH region
newReturnBB->bbHndIndex = 0;
fgReturnCount++;
JITDUMP("Created new BBJ_RETURN block " FMT_BB "\n", newReturnBB->bbNum);
// Insert "restore" call
CORINFO_ASYNC_INFO* asyncInfo = eeGetAsyncInfo();
GenTree* resumed;
if (compIsForInlining())
{
resumed = gtNewFalse();
}
else
{
GenTree* continuation = gtNewLclvNode(lvaAsyncContinuationArg, TYP_REF);
GenTree* null = gtNewNull();
resumed = gtNewOperNode(GT_NE, TYP_INT, continuation, null);
}
GenTreeCall* restoreCall = gtNewCallNode(CT_USER_FUNC, asyncInfo->restoreContextsMethHnd, TYP_VOID);
restoreCall->gtArgs.PushFront(this,
NewCallArg::Primitive(gtNewLclVarNode(lvaAsyncSynchronizationContextVar, TYP_REF)));
restoreCall->gtArgs.PushFront(this, NewCallArg::Primitive(gtNewLclVarNode(lvaAsyncExecutionContextVar, TYP_REF)));
restoreCall->gtArgs.PushFront(this, NewCallArg::Primitive(resumed));
#ifdef FEATURE_READYTORUN
{
CORINFO_CONST_LOOKUP restoreEntryPoint;
info.compCompHnd->getFunctionEntryPoint(asyncInfo->restoreContextsMethHnd, &restoreEntryPoint);
restoreCall->setEntryPoint(restoreEntryPoint);
}
#endif
// This restore is an inline candidate (unlike the fault one)
CORINFO_CALL_INFO callInfo = {};
callInfo.hMethod = restoreCall->gtCallMethHnd;
callInfo.methodFlags = info.compCompHnd->getMethodAttribs(callInfo.hMethod);
impMarkInlineCandidate(restoreCall, MAKE_METHODCONTEXT(callInfo.hMethod), false, &callInfo, compInlineContext);
Statement* restoreStmt = fgNewStmtFromTree(restoreCall);
fgInsertStmtAtEnd(newReturnBB, restoreStmt);
JITDUMP("Inserted restore statement in return block\n");
DISPSTMT(restoreStmt);
if (!compIsForInlining())
{
*mergedReturnLcl = BAD_VAR_NUM;
GenTree* ret;
if (compMethodHasRetVal())
{
*mergedReturnLcl = lvaGrabTemp(false DEBUGARG("Async merged return local"));
var_types retLclType = compMethodReturnsRetBufAddr() ? TYP_BYREF : genActualType(info.compRetType);
if (varTypeIsStruct(retLclType))
{
lvaSetStruct(*mergedReturnLcl, info.compMethodInfo->args.retTypeClass, false);
if (compMethodReturnsMultiRegRetType())
{
lvaGetDesc(*mergedReturnLcl)->lvIsMultiRegRet = true;
}
}
else
{
lvaGetDesc(*mergedReturnLcl)->lvType = retLclType;
}
GenTree* retTemp = gtNewLclVarNode(*mergedReturnLcl);
ret = gtNewOperNode(GT_RETURN, retTemp->TypeGet(), retTemp);
}
else
{
ret = new (this, GT_RETURN) GenTreeOp(GT_RETURN, TYP_VOID);
}
Statement* retStmt = fgNewStmtFromTree(ret);
fgInsertStmtAtEnd(newReturnBB, retStmt);
JITDUMP("Inserted return statement in return block\n");
DISPSTMT(retStmt);
}
return newReturnBB;
}
//------------------------------------------------------------------------
// DefaultValueAnalysis:
// Computes which tracked locals have their default (zero) value at each
// basic block entry. A tracked local that still has its default value at a
// suspension point does not need to be hoisted into the continuation.
//
// The analysis has two phases:
// 1. Per-block: compute which tracked locals are mutated (assigned a
// non-default value or have their address taken) in each block.
// 2. Inter-block: forward dataflow to propagate default value information
// across blocks. At merge points the sets are unioned (a local is mutated
// if it is mutated on any incoming path).
//
class DefaultValueAnalysis
{
Compiler* m_compiler;
VARSET_TP* m_mutatedVars; // Per-block set of locals mutated to non-default.
VARSET_TP* m_mutatedVarsIn; // Per-block set of locals mutated to non-default on entry.
// DataFlow::ForwardAnalysis callback used in Phase 2.
class DataFlowCallback
{
DefaultValueAnalysis& m_analysis;
Compiler* m_compiler;
VARSET_TP m_preMergeIn;
public:
DataFlowCallback(DefaultValueAnalysis& analysis, Compiler* compiler)
: m_analysis(analysis)
, m_compiler(compiler)
, m_preMergeIn(VarSetOps::UninitVal())
{
}
void StartMerge(BasicBlock* block)
{
// Save the current in set for change detection later.
VarSetOps::Assign(m_compiler, m_preMergeIn, m_analysis.m_mutatedVarsIn[block->bbNum]);
}
void Merge(BasicBlock* block, BasicBlock* predBlock, unsigned dupCount)
{
// The out set of a predecessor is its in set plus the locals
// mutated in that block: mutatedOut = mutatedIn | mutated.
VarSetOps::UnionD(m_compiler, m_analysis.m_mutatedVarsIn[block->bbNum],
m_analysis.m_mutatedVarsIn[predBlock->bbNum]);
VarSetOps::UnionD(m_compiler, m_analysis.m_mutatedVarsIn[block->bbNum],
m_analysis.m_mutatedVars[predBlock->bbNum]);
}
void MergeHandler(BasicBlock* block, BasicBlock* firstTryBlock, BasicBlock* lastTryBlock)
{
// A handler can be reached from any point in the try region.
// A local is mutated at handler entry if it was mutated at try
// entry or mutated anywhere within the try region.
for (BasicBlock* tryBlock = firstTryBlock; tryBlock != lastTryBlock->Next(); tryBlock = tryBlock->Next())
{
VarSetOps::UnionD(m_compiler, m_analysis.m_mutatedVarsIn[block->bbNum],
m_analysis.m_mutatedVarsIn[tryBlock->bbNum]);
VarSetOps::UnionD(m_compiler, m_analysis.m_mutatedVarsIn[block->bbNum],
m_analysis.m_mutatedVars[tryBlock->bbNum]);
}
}
bool EndMerge(BasicBlock* block)
{
return !VarSetOps::Equal(m_compiler, m_preMergeIn, m_analysis.m_mutatedVarsIn[block->bbNum]);
}
};
public:
DefaultValueAnalysis(Compiler* compiler)
: m_compiler(compiler)
, m_mutatedVars(nullptr)
, m_mutatedVarsIn(nullptr)
{
}
void Run();
const VARSET_TP& GetMutatedVarsIn(BasicBlock* block) const;
private:
void ComputePerBlockMutatedVars();
void ComputeInterBlockDefaultValues();
#ifdef DEBUG
void DumpMutatedVars();
void DumpMutatedVarsIn();
#endif
};
//------------------------------------------------------------------------
// DefaultValueAnalysis::Run:
// Run the default value analysis: compute per-block mutation sets, then
// propagate default value information forward through the flow graph.
//
void DefaultValueAnalysis::Run()
{
#ifdef DEBUG
static ConfigMethodRange s_range;
s_range.EnsureInit(JitConfig.JitAsyncDefaultValueAnalysisRange());
if (!s_range.Contains(m_compiler->info.compMethodHash()))
{
JITDUMP("Default value analysis disabled because of method range\n");
m_mutatedVarsIn = m_compiler->fgAllocateTypeForEachBlk<VARSET_TP>(CMK_Async);
for (BasicBlock* block : m_compiler->Blocks())
{
VarSetOps::AssignNoCopy(m_compiler, m_mutatedVarsIn[block->bbNum], VarSetOps::MakeFull(m_compiler));
}
return;
}
#endif
ComputePerBlockMutatedVars();
ComputeInterBlockDefaultValues();
}
//------------------------------------------------------------------------
// DefaultValueAnalysis::GetMutatedVarsIn:
// Get the set of tracked locals that have been mutated to a non-default
// value on entry to the specified block.
//
// Parameters:
// block - The basic block.
//
// Returns:
// The VARSET_TP of tracked locals mutated on entry. A local NOT in this
// set is guaranteed to have its default value.
//
const VARSET_TP& DefaultValueAnalysis::GetMutatedVarsIn(BasicBlock* block) const
{
assert(m_mutatedVarsIn != nullptr);
return m_mutatedVarsIn[block->bbNum];
}
//------------------------------------------------------------------------
// IsDefaultValue:
// Check if a node represents a default (zero) value.
//
// Parameters:
// node - The node to check.
//
// Returns:
// True if the node is a constant zero value (integral, floating-point, or
// vector).
//
static bool IsDefaultValue(GenTree* node)
{
return node->IsIntegralConst(0) || node->IsFloatPositiveZero() || node->IsVectorZero();
}
//------------------------------------------------------------------------
//------------------------------------------------------------------------
// UpdateMutatedLocal:
// If the given node is a local store or LCL_ADDR, and the local is tracked,
// mark it as mutated in the provided set. Stores of a default (zero) value
// are not considered mutations.
//
// Parameters:
// compiler - The compiler instance.
// node - The IR node to check.
// mutated - [in/out] The set to update.
//
static void UpdateMutatedLocal(Compiler* compiler, GenTree* node, VARSET_TP& mutated)
{
if (node->OperIsLocalStore())
{
// If this is a zero initialization then we do not need to consider it
// mutated if we know the prolog will zero it anyway (otherwise we
// could be skipping this explicit zero init on resumption).
// We could improve this a bit by still skipping it but inserting
// explicit zero init on resumption, but these cases seem to be rare
// and that would require tracking additional information.
if (IsDefaultValue(node->AsLclVarCommon()->Data()) &&
!compiler->fgVarNeedsExplicitZeroInit(node->AsLclVarCommon()->GetLclNum(), /* bbInALoop */ false,
/* bbIsReturn */ false))
{
return;
}
}
else if (node->OperIs(GT_LCL_ADDR))
{
// Fall through
}
else
{
return;
}
LclVarDsc* varDsc = compiler->lvaGetDesc(node->AsLclVarCommon());
if (varDsc->lvTracked)
{
VarSetOps::AddElemD(compiler, mutated, varDsc->lvVarIndex);
return;
}
// For promoted structs the parent may not be tracked but the field locals
// are. When the parent is mutated, all tracked fields must be marked as
// mutated as well.
if (varDsc->lvPromoted)
{
for (unsigned i = 0; i < varDsc->lvFieldCnt; i++)
{
LclVarDsc* fieldDsc = compiler->lvaGetDesc(varDsc->lvFieldLclStart + i);
if (fieldDsc->lvTracked)
{
VarSetOps::AddElemD(compiler, mutated, fieldDsc->lvVarIndex);
}
}
}
}
//------------------------------------------------------------------------
// DefaultValueAnalysis::ComputePerBlockMutatedVars:
// Phase 1: For each reachable basic block compute the set of tracked locals
// that are mutated to a non-default value.
//
// A tracked local is considered mutated if:
// - It has a store (STORE_LCL_VAR / STORE_LCL_FLD) whose data operand is
// not a zero constant.
// - It has a LCL_ADDR use (address taken that we cannot reason about).
//
void DefaultValueAnalysis::ComputePerBlockMutatedVars()
{
m_mutatedVars = m_compiler->fgAllocateTypeForEachBlk<VARSET_TP>(CMK_Async);
for (unsigned i = 0; i <= m_compiler->fgBBNumMax; i++)
{
VarSetOps::AssignNoCopy(m_compiler, m_mutatedVars[i], VarSetOps::MakeEmpty(m_compiler));
}
const FlowGraphDfsTree* dfsTree = m_compiler->m_dfsTree;
for (unsigned i = 0; i < dfsTree->GetPostOrderCount(); i++)
{
BasicBlock* block = dfsTree->GetPostOrder(i);
VARSET_TP& mutated = m_mutatedVars[block->bbNum];
for (GenTree* node : LIR::AsRange(block))
{
UpdateMutatedLocal(m_compiler, node, mutated);
}
}
JITDUMP("Default value analysis: per-block mutated vars\n");
DBEXEC(m_compiler->verbose, DumpMutatedVars());
}
//------------------------------------------------------------------------
// DefaultValueAnalysis::ComputeInterBlockDefaultValues:
// Phase 2: Forward dataflow to compute for each block the set of tracked
// locals that have been mutated to a non-default value on entry.
//
// Transfer function: mutatedOut[B] = mutatedIn[B] | mutated[B]
// Merge: mutatedIn[B] = union of mutatedOut[pred] for all preds
//
// At entry, only parameters and OSR locals are considered mutated.
//
void DefaultValueAnalysis::ComputeInterBlockDefaultValues()
{
m_mutatedVarsIn = m_compiler->fgAllocateTypeForEachBlk<VARSET_TP>(CMK_Async);
for (unsigned i = 0; i <= m_compiler->fgBBNumMax; i++)
{
VarSetOps::AssignNoCopy(m_compiler, m_mutatedVarsIn[i], VarSetOps::MakeEmpty(m_compiler));
}
// Parameters and OSR locals are considered mutated at method entry.
for (unsigned i = 0; i < m_compiler->lvaTrackedCount; i++)
{
unsigned lclNum = m_compiler->lvaTrackedToVarNum[i];
LclVarDsc* varDsc = m_compiler->lvaGetDesc(lclNum);
if (varDsc->lvIsParam || varDsc->lvIsOSRLocal)
{
VarSetOps::AddElemD(m_compiler, m_mutatedVarsIn[m_compiler->fgFirstBB->bbNum], varDsc->lvVarIndex);
}
}
DataFlowCallback callback(*this, m_compiler);
DataFlow flow(m_compiler);
flow.ForwardAnalysis(callback);
JITDUMP("Default value analysis: per-block mutated vars on entry\n");
DBEXEC(m_compiler->verbose, DumpMutatedVarsIn());
}
#ifdef DEBUG
//------------------------------------------------------------------------
// DefaultValueAnalysis::DumpMutatedVars:
// Debug helper to print the per-block mutated variable sets.
//
void DefaultValueAnalysis::DumpMutatedVars()
{
const FlowGraphDfsTree* dfsTree = m_compiler->m_dfsTree;
for (unsigned i = 0; i < dfsTree->GetPostOrderCount(); i++)
{
BasicBlock* block = dfsTree->GetPostOrder(i);
if (!VarSetOps::IsEmpty(m_compiler, m_mutatedVars[block->bbNum]))
{
printf(" " FMT_BB " mutated: ", block->bbNum);
VarSetOps::Iter iter(m_compiler, m_mutatedVars[block->bbNum]);
unsigned varIndex = 0;
const char* sep = "";
while (iter.NextElem(&varIndex))
{
unsigned lclNum = m_compiler->lvaTrackedToVarNum[varIndex];
printf("%sV%02u", sep, lclNum);
sep = " ";
}
printf("\n");
}
}
}
//------------------------------------------------------------------------
// DefaultValueAnalysis::DumpMutatedVarsIn:
// Debug helper to print the per-block mutated-on-entry variable sets.
//
void DefaultValueAnalysis::DumpMutatedVarsIn()
{
const FlowGraphDfsTree* dfsTree = m_compiler->m_dfsTree;
for (unsigned i = dfsTree->GetPostOrderCount(); i > 0; i--)
{
BasicBlock* block = dfsTree->GetPostOrder(i - 1);
printf(" " FMT_BB " mutated on entry: ", block->bbNum);
if (VarSetOps::IsEmpty(m_compiler, m_mutatedVarsIn[block->bbNum]))
{
printf("<none>");
}
else
{
VarSetOps::Iter iter(m_compiler, m_mutatedVarsIn[block->bbNum]);
unsigned varIndex = 0;
const char* sep = "";
while (iter.NextElem(&varIndex))
{
unsigned lclNum = m_compiler->lvaTrackedToVarNum[varIndex];
printf("%sV%02u", sep, lclNum);
sep = " ";
}
}
printf("\n");
}
}
#endif
class AsyncLiveness
{
Compiler* m_compiler;
TreeLifeUpdater<false> m_updater;
unsigned m_numVars;
DefaultValueAnalysis& m_defaultValueAnalysis;
VARSET_TP m_mutatedValues;
public:
AsyncLiveness(Compiler* comp, DefaultValueAnalysis& defaultValueAnalysis)
: m_compiler(comp)
, m_updater(comp)
, m_numVars(comp->lvaCount)
, m_defaultValueAnalysis(defaultValueAnalysis)
, m_mutatedValues(VarSetOps::MakeEmpty(comp))
{
}
void StartBlock(BasicBlock* block);
void Update(GenTree* node);
bool IsLive(unsigned lclNum);
template <typename Functor>
void GetLiveLocals(jitstd::vector<LiveLocalInfo>& liveLocals, Functor includeLocal);
private:
bool IsLocalCaptureUnnecessary(unsigned lclNum);
};
//------------------------------------------------------------------------
// AsyncLiveness::StartBlock:
// Indicate that we are now starting a new block, and do relevant liveness
// updates for it.
//
// Parameters:
// block - The block that we are starting.
//
void AsyncLiveness::StartBlock(BasicBlock* block)
{
VarSetOps::Assign(m_compiler, m_compiler->compCurLife, block->bbLiveIn);
VarSetOps::Assign(m_compiler, m_mutatedValues, m_defaultValueAnalysis.GetMutatedVarsIn(block));
}
//------------------------------------------------------------------------
// AsyncLiveness::Update:
// Update liveness to be consistent with the specified node having been
// executed.
//
// Parameters:
// node - The node.
//
void AsyncLiveness::Update(GenTree* node)
{
m_updater.UpdateLife<true>(node);
UpdateMutatedLocal(m_compiler, node, m_mutatedValues);
}
//------------------------------------------------------------------------
// AsyncLiveness::IsLocalCaptureUnnecessary:
// Check if capturing a specified local can be skipped.
//
// Parameters:
// lclNum - The local
//
// Returns:
// True if the local should not be captured. Even without liveness
//
bool AsyncLiveness::IsLocalCaptureUnnecessary(unsigned lclNum)
{
#if FEATURE_FIXED_OUT_ARGS
if (lclNum == m_compiler->lvaOutgoingArgSpaceVar)
{
return true;
}
#endif
if (lclNum == m_compiler->info.compRetBuffArg)
{
return true;
}
if (lclNum == m_compiler->lvaGSSecurityCookie)
{
// Initialized in prolog
return true;
}
if (lclNum == m_compiler->info.compLvFrameListRoot)
{
return true;
}
if (lclNum == m_compiler->lvaInlinedPInvokeFrameVar)
{
return true;
}
if (lclNum == m_compiler->lvaRetAddrVar)
{
return true;
}
if (lclNum == m_compiler->lvaAsyncContinuationArg)
{
return true;
}
return false;
}
//------------------------------------------------------------------------
// AsyncLiveness::IsLive:
// Check if the specified local is live at this point and should be captured.
//
// Parameters:
// lclNum - The local
//
// Returns:
// True if the local is live and capturing it is necessary.
//
bool AsyncLiveness::IsLive(unsigned lclNum)
{
if (IsLocalCaptureUnnecessary(lclNum))
{
return false;
}
LclVarDsc* dsc = m_compiler->lvaGetDesc(lclNum);
if (dsc->TypeIs(TYP_BYREF) && !dsc->IsImplicitByRef())
{
// Even if these are address exposed we expect them to be dead at
// suspension points. TODO: It would be good to somehow verify these
// aren't obviously live, if the JIT creates live ranges that span a
// suspension point then this makes it quite hard to diagnose that.
return false;
}
if ((dsc->TypeIs(TYP_STRUCT) || dsc->IsImplicitByRef()) && dsc->GetLayout()->HasGCByRef())
{
// Same as above
return false;
}
if (m_compiler->opts.compDbgCode && (lclNum < m_compiler->info.compLocalsCount))
{
// Keep all IL locals in debug codegen
return true;
}
if (dsc->lvRefCnt(RCS_NORMAL) == 0)
{
return false;
}
Compiler::lvaPromotionType promoType = m_compiler->lvaGetPromotionType(dsc);
if (promoType == Compiler::PROMOTION_TYPE_INDEPENDENT)
{
// Independently promoted structs are handled only through their
// fields.
return false;
}
if (promoType == Compiler::PROMOTION_TYPE_DEPENDENT)
{
// Dependently promoted structs are handled only through the base
// struct local.
//
// A dependently promoted struct is live if any of its fields are live.
bool anyLive = false;
bool anyMutated = false;
for (unsigned i = 0; i < dsc->lvFieldCnt; i++)
{
LclVarDsc* fieldDsc = m_compiler->lvaGetDesc(dsc->lvFieldLclStart + i);
anyLive |=
!fieldDsc->lvTracked || VarSetOps::IsMember(m_compiler, m_compiler->compCurLife, fieldDsc->lvVarIndex);
anyMutated |=
!fieldDsc->lvTracked || VarSetOps::IsMember(m_compiler, m_mutatedValues, fieldDsc->lvVarIndex);
}
return anyLive && anyMutated;
}
if (dsc->lvIsStructField && (m_compiler->lvaGetParentPromotionType(dsc) == Compiler::PROMOTION_TYPE_DEPENDENT))
{
return false;
}
if (!dsc->lvTracked)
{
return true;
}
if (!VarSetOps::IsMember(m_compiler, m_compiler->compCurLife, dsc->lvVarIndex))
{
return false;
}
if (!VarSetOps::IsMember(m_compiler, m_mutatedValues, dsc->lvVarIndex))
{
return false;
}
return true;