-
Notifications
You must be signed in to change notification settings - Fork 4.9k
/
Copy pathfgprofile.cpp
3672 lines (3204 loc) · 124 KB
/
fgprofile.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"
#ifdef _MSC_VER
#pragma hdrstop
#endif
// Flowgraph Profile Support
//------------------------------------------------------------------------
// fgHaveProfileData: check if profile data is available
//
// Returns:
// true if so
//
// Note:
// This now returns true for inlinees. We might consider preserving the
// old behavior for crossgen, since crossgen BBINSTRs still do inlining
// and don't instrument the inlinees.
//
// Thus if BBINSTR and BBOPT do the same inlines (which can happen)
// profile data for an inlinee (if available) will not fully reflect
// the behavior of the inlinee when called from this method.
//
// If this inlinee was not inlined by the BBINSTR run then the
// profile data for the inlinee will reflect this method's influence.
//
// * for ALWAYS_INLINE and FORCE_INLINE cases it is unlikely we'll find
// any profile data, as BBINSTR and BBOPT callers will both inline;
// only indirect callers will invoke the instrumented version to run.
// * for DISCRETIONARY_INLINE cases we may or may not find relevant
// data, depending, but chances are the data is relevant.
//
// TieredPGO data comes from Tier0 methods, which currently do not do
// any inlining; thus inlinee profile data should be available and
// representative.
//
bool Compiler::fgHaveProfileData()
{
if (compIsForImportOnly())
{
return false;
}
return (fgPgoSchema != nullptr);
}
//------------------------------------------------------------------------
// fgComputeProfileScale: determine how much scaling to apply
// to raw profile count data.
//
// Notes:
// Scaling is only needed for inlinees, and the results of this
// computation are recorded in fields of impInlineInfo.
//
void Compiler::fgComputeProfileScale()
{
// Only applicable to inlinees
assert(compIsForInlining());
// Have we already determined the scale?
if (impInlineInfo->profileScaleState != InlineInfo::ProfileScaleState::UNDETERMINED)
{
return;
}
// No, not yet -- try and compute the scale.
JITDUMP("Computing inlinee profile scale:\n");
// Call site has profile weight?
//
// Todo: handle case of unprofiled caller invoking profiled callee.
//
const BasicBlock* callSiteBlock = impInlineInfo->iciBlock;
if (!callSiteBlock->hasProfileWeight())
{
JITDUMP(" ... call site not profiled\n");
impInlineInfo->profileScaleState = InlineInfo::ProfileScaleState::UNAVAILABLE;
return;
}
const BasicBlock::weight_t callSiteWeight = callSiteBlock->bbWeight;
// Call site has zero count?
//
// Todo: perhaps retain some semblance of callee profile data,
// possibly scaled down severely.
//
if (callSiteWeight == 0)
{
JITDUMP(" ... zero call site count\n");
impInlineInfo->profileScaleState = InlineInfo::ProfileScaleState::UNAVAILABLE;
return;
}
// Callee has profile data?
//
if (!fgHaveProfileData())
{
JITDUMP(" ... no callee profile data\n");
impInlineInfo->profileScaleState = InlineInfo::ProfileScaleState::UNAVAILABLE;
return;
}
// Find callee's unscaled entry weight.
//
// Ostensibly this should be fgCalledCount for the callee, but that's not available
// as it requires some analysis.
//
// For most callees it will be the same as the entry block count.
//
if (!fgFirstBB->hasProfileWeight())
{
JITDUMP(" ... no callee profile data for entry block\n");
impInlineInfo->profileScaleState = InlineInfo::ProfileScaleState::UNAVAILABLE;
return;
}
// Note when/if we early do normalization this may need to change.
//
BasicBlock::weight_t const calleeWeight = fgFirstBB->bbWeight;
// If profile data reflects a complete single run we can expect
// calleeWeight >= callSiteWeight.
//
// However if our profile is just a subset of execution we may
// not see this.
//
// So, we are willing to scale the callee counts down or up as
// needed to match the call site.
//
if (calleeWeight == BB_ZERO_WEIGHT)
{
JITDUMP(" ... callee entry count is zero\n");
impInlineInfo->profileScaleState = InlineInfo::ProfileScaleState::UNAVAILABLE;
return;
}
// Hence, scale can be somewhat arbitrary...
//
const double scale = ((double)callSiteWeight) / calleeWeight;
impInlineInfo->profileScaleFactor = scale;
impInlineInfo->profileScaleState = InlineInfo::ProfileScaleState::KNOWN;
JITDUMP(" call site count " FMT_WT " callee entry count " FMT_WT " scale " FMT_WT "\n", callSiteWeight,
calleeWeight, scale);
}
//------------------------------------------------------------------------
// fgGetProfileWeightForBasicBlock: obtain profile data for a block
//
// Arguments:
// offset - IL offset of the block
// weightWB - [OUT] weight obtained
//
// Returns:
// true if data was found
//
bool Compiler::fgGetProfileWeightForBasicBlock(IL_OFFSET offset, BasicBlock::weight_t* weightWB)
{
noway_assert(weightWB != nullptr);
BasicBlock::weight_t weight = 0;
#ifdef DEBUG
unsigned hashSeed = fgStressBBProf();
if (hashSeed != 0)
{
unsigned hash = (info.compMethodHash() * hashSeed) ^ (offset * 1027);
// We need to especially stress the procedure splitting codepath. Therefore
// one third the time we should return a weight of zero.
// Otherwise we should return some random weight (usually between 0 and 288).
// The below gives a weight of zero, 44% of the time
if (hash % 3 == 0)
{
weight = BB_ZERO_WEIGHT;
}
else if (hash % 11 == 0)
{
weight = (BasicBlock::weight_t)(hash % 23) * (hash % 29) * (hash % 31);
}
else
{
weight = (BasicBlock::weight_t)(hash % 17) * (hash % 19);
}
// The first block is never given a weight of zero
if ((offset == 0) && (weight == BB_ZERO_WEIGHT))
{
weight = (BasicBlock::weight_t)1 + (hash % 5);
}
*weightWB = weight;
return true;
}
#endif // DEBUG
if (!fgHaveProfileData())
{
return false;
}
for (UINT32 i = 0; i < fgPgoSchemaCount; i++)
{
if ((fgPgoSchema[i].InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::BasicBlockIntCount) &&
((IL_OFFSET)fgPgoSchema[i].ILOffset == offset))
{
*weightWB = (BasicBlock::weight_t) * (uint32_t*)(fgPgoData + fgPgoSchema[i].Offset);
return true;
}
}
*weightWB = 0;
return true;
}
typedef jitstd::vector<ICorJitInfo::PgoInstrumentationSchema> Schema;
//------------------------------------------------------------------------
// Instrumentor: base class for count and class instrumentation
//
class Instrumentor
{
protected:
Compiler* m_comp;
unsigned m_schemaCount;
unsigned m_instrCount;
protected:
Instrumentor(Compiler* comp) : m_comp(comp), m_schemaCount(0), m_instrCount(0)
{
}
public:
virtual bool ShouldProcess(BasicBlock* block)
{
return false;
}
virtual void Prepare(bool preImport)
{
}
virtual void BuildSchemaElements(BasicBlock* block, Schema& schema)
{
}
virtual void Instrument(BasicBlock* block, Schema& schema, BYTE* profileMemory)
{
}
virtual void InstrumentMethodEntry(Schema& schema, BYTE* profileMemory)
{
}
virtual void SuppressProbes()
{
}
unsigned SchemaCount()
{
return m_schemaCount;
}
unsigned InstrCount()
{
return m_instrCount;
}
};
//------------------------------------------------------------------------
// NonInstrumentor: instrumentor that does not instrument anything
//
class NonInstrumentor : public Instrumentor
{
public:
NonInstrumentor(Compiler* comp) : Instrumentor(comp)
{
}
};
//------------------------------------------------------------------------
// BlockCountInstrumentor: instrumentor that adds a counter to each
// non-internal imported basic block
//
class BlockCountInstrumentor : public Instrumentor
{
private:
BasicBlock* m_entryBlock;
public:
BlockCountInstrumentor(Compiler* comp) : Instrumentor(comp), m_entryBlock(nullptr)
{
}
bool ShouldProcess(BasicBlock* block) override
{
return ((block->bbFlags & (BBF_INTERNAL | BBF_IMPORTED)) == BBF_IMPORTED);
}
void Prepare(bool isPreImport) override;
void BuildSchemaElements(BasicBlock* block, Schema& schema) override;
void Instrument(BasicBlock* block, Schema& schema, BYTE* profileMemory) override;
void InstrumentMethodEntry(Schema& schema, BYTE* profileMemory) override;
};
//------------------------------------------------------------------------
// BlockCountInstrumentor::Prepare: prepare for count instrumentation
//
// Arguments:
// preImport - true if this is the prepare call that happens before
// importation
//
void BlockCountInstrumentor::Prepare(bool preImport)
{
if (preImport)
{
return;
}
#ifdef DEBUG
// Set schema index to invalid value
//
for (BasicBlock* block = m_comp->fgFirstBB; (block != nullptr); block = block->bbNext)
{
block->bbCountSchemaIndex = -1;
}
#endif
}
//------------------------------------------------------------------------
// BlockCountInstrumentor::BuildSchemaElements: create schema elements for a block counter
//
// Arguments:
// block -- block to instrument
// schema -- schema that we're building
//
void BlockCountInstrumentor::BuildSchemaElements(BasicBlock* block, Schema& schema)
{
// Remember the schema index for this block.
//
assert(block->bbCountSchemaIndex == -1);
block->bbCountSchemaIndex = (int)schema.size();
// Assign the current block's IL offset into the profile data
// (make sure IL offset is sane)
//
IL_OFFSET offset = block->bbCodeOffs;
assert((int)offset >= 0);
ICorJitInfo::PgoInstrumentationSchema schemaElem;
schemaElem.Count = 1;
schemaElem.Other = 0;
schemaElem.InstrumentationKind = ICorJitInfo::PgoInstrumentationKind::BasicBlockIntCount;
schemaElem.ILOffset = offset;
schemaElem.Offset = 0;
schema.push_back(schemaElem);
m_schemaCount++;
// If this is the entry block, remember it for later.
// Note it might not be fgFirstBB, if we have a scratchBB.
//
if (offset == 0)
{
assert(m_entryBlock == nullptr);
m_entryBlock = block;
}
}
//------------------------------------------------------------------------
// BlockCountInstrumentor::Instrument: add counter probe to block
//
// Arguments:
// block -- block of interest
// schema -- instrumentation schema
// profileMemory -- profile data slab
//
void BlockCountInstrumentor::Instrument(BasicBlock* block, Schema& schema, BYTE* profileMemory)
{
const int schemaIndex = (int)block->bbCountSchemaIndex;
assert(block->bbCodeOffs == (IL_OFFSET)schema[schemaIndex].ILOffset);
assert(schema[schemaIndex].InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::BasicBlockIntCount);
size_t addrOfCurrentExecutionCount = (size_t)(schema[schemaIndex].Offset + profileMemory);
// Read Basic-Block count value
GenTree* valueNode =
m_comp->gtNewIndOfIconHandleNode(TYP_INT, addrOfCurrentExecutionCount, GTF_ICON_BBC_PTR, false);
// Increment value by 1
GenTree* rhsNode = m_comp->gtNewOperNode(GT_ADD, TYP_INT, valueNode, m_comp->gtNewIconNode(1));
// Write new Basic-Block count value
GenTree* lhsNode = m_comp->gtNewIndOfIconHandleNode(TYP_INT, addrOfCurrentExecutionCount, GTF_ICON_BBC_PTR, false);
GenTree* asgNode = m_comp->gtNewAssignNode(lhsNode, rhsNode);
m_comp->fgNewStmtAtBeg(block, asgNode);
m_instrCount++;
}
//------------------------------------------------------------------------
// BlockCountInstrumentor::InstrumentMethodEntry: add any special method entry instrumentation
//
// Arguments:
// schema -- instrumentation schema
// profileMemory -- profile data slab
//
// Notes:
// When prejitting, add the method entry callback node
//
void BlockCountInstrumentor::InstrumentMethodEntry(Schema& schema, BYTE* profileMemory)
{
Compiler::Options& opts = m_comp->opts;
Compiler::Info& info = m_comp->info;
// Nothing to do, if not prejitting.
//
if (!opts.jitFlags->IsSet(JitFlags::JIT_FLAG_PREJIT))
{
return;
}
// Find the address of the entry block's counter.
//
assert(m_entryBlock != nullptr);
assert(m_entryBlock->bbCodeOffs == 0);
const int firstSchemaIndex = (int)m_entryBlock->bbCountSchemaIndex;
assert((IL_OFFSET)schema[firstSchemaIndex].ILOffset == 0);
assert(schema[firstSchemaIndex].InstrumentationKind == ICorJitInfo::PgoInstrumentationKind::BasicBlockIntCount);
const size_t addrOfFirstExecutionCount = (size_t)(schema[firstSchemaIndex].Offset + profileMemory);
GenTree* arg;
#ifdef FEATURE_READYTORUN_COMPILER
if (opts.IsReadyToRun())
{
mdMethodDef currentMethodToken = info.compCompHnd->getMethodDefFromMethod(info.compMethodHnd);
CORINFO_RESOLVED_TOKEN resolvedToken;
resolvedToken.tokenContext = MAKE_METHODCONTEXT(info.compMethodHnd);
resolvedToken.tokenScope = info.compScopeHnd;
resolvedToken.token = currentMethodToken;
resolvedToken.tokenType = CORINFO_TOKENKIND_Method;
info.compCompHnd->resolveToken(&resolvedToken);
arg = m_comp->impTokenToHandle(&resolvedToken);
}
else
#endif
{
arg = m_comp->gtNewIconEmbMethHndNode(info.compMethodHnd);
}
// We want to call CORINFO_HELP_BBT_FCN_ENTER just one time,
// the first time this method is called. So make the call conditional
// on the entry block's profile count.
//
GenTreeCall::Use* args = m_comp->gtNewCallArgs(arg);
GenTree* call = m_comp->gtNewHelperCallNode(CORINFO_HELP_BBT_FCN_ENTER, TYP_VOID, args);
// Read Basic-Block count value
//
GenTree* valueNode = m_comp->gtNewIndOfIconHandleNode(TYP_INT, addrOfFirstExecutionCount, GTF_ICON_BBC_PTR, false);
// Compare Basic-Block count value against zero
//
GenTree* relop = m_comp->gtNewOperNode(GT_NE, TYP_INT, valueNode, m_comp->gtNewIconNode(0, TYP_INT));
GenTree* colon = new (m_comp, GT_COLON) GenTreeColon(TYP_VOID, m_comp->gtNewNothingNode(), call);
GenTree* cond = m_comp->gtNewQmarkNode(TYP_VOID, relop, colon);
Statement* stmt = m_comp->gtNewStmt(cond);
// Add this check into the scratch block entry so we only do the check once per call.
// If we put it in block we may be putting it inside a loop.
//
m_comp->fgEnsureFirstBBisScratch();
m_comp->fgInsertStmtAtEnd(m_comp->fgFirstBB, stmt);
}
//------------------------------------------------------------------------
// SpanningTreeVisitor: abstract class for computations done while
// evolving a spanning tree.
//
class SpanningTreeVisitor
{
public:
// To save visitors a bit of work, we also note
// for non-tree edges whether the edge postdominates
// the source, dominates the target, or is a critical edge.
//
enum class EdgeKind
{
Unknown,
PostdominatesSource,
DominatesTarget,
CriticalEdge
};
virtual void Badcode() = 0;
virtual void VisitBlock(BasicBlock* block) = 0;
virtual void VisitTreeEdge(BasicBlock* source, BasicBlock* target) = 0;
virtual void VisitNonTreeEdge(BasicBlock* source, BasicBlock* target, EdgeKind kind) = 0;
};
//------------------------------------------------------------------------
// WalkSpanningTree: evolve a "maximal cost" depth first spanning tree,
// invoking the visitor as each edge is classified, or each node is first
// discovered.
//
// Arguments:
// visitor - visitor to notify
//
// Notes:
// We only have rudimentary weights at this stage, and so in practice
// we use a depth-first spanning tree (DFST) where we try to steer
// the DFS to preferentially visit "higher" cost edges.
//
// Since instrumentation happens after profile incorporation
// we could in principle use profile weights to steer the DFS or to build
// a true maximum weight tree. However we are relying on being able to
// rebuild the exact same spanning tree "later on" when doing a subsequent
// profile reconstruction. So, we restrict ourselves to just using
// information apparent in the IL.
//
void Compiler::WalkSpanningTree(SpanningTreeVisitor* visitor)
{
// Inlinee compilers build their blocks in the root compiler's
// graph. So for BlockSets and NumSucc, we use the root compiler instance.
//
Compiler* const comp = impInlineRoot();
comp->NewBasicBlockEpoch();
// We will track visited or queued nodes with a bit vector.
//
BlockSet marked = BlockSetOps::MakeEmpty(comp);
// And nodes to visit with a bit vector and stack.
//
ArrayStack<BasicBlock*> stack(getAllocator(CMK_Pgo));
// Scratch vector for visiting successors of blocks with
// multiple successors.
//
// Bit vector to track progress through those successors.
//
ArrayStack<BasicBlock*> scratch(getAllocator(CMK_Pgo));
BlockSet processed = BlockSetOps::MakeEmpty(comp);
// Push the method entry and all EH handler region entries on the stack.
// (push method entry last so it's visited first).
//
// Note inlinees are "contaminated" with root method EH structures.
// We know the inlinee itself doesn't have EH, so we only look at
// handlers for root methods.
//
// If we ever want to support inlining methods with EH, we'll
// have to revisit this.
//
if (!compIsForInlining())
{
EHblkDsc* HBtab = compHndBBtab;
unsigned XTnum = 0;
for (; XTnum < compHndBBtabCount; XTnum++, HBtab++)
{
BasicBlock* hndBegBB = HBtab->ebdHndBeg;
stack.Push(hndBegBB);
BlockSetOps::AddElemD(comp, marked, hndBegBB->bbNum);
}
}
stack.Push(fgFirstBB);
BlockSetOps::AddElemD(comp, marked, fgFirstBB->bbNum);
unsigned nBlocks = 0;
while (!stack.Empty())
{
BasicBlock* const block = stack.Pop();
// Visit the block.
//
assert(BlockSetOps::IsMember(comp, marked, block->bbNum));
visitor->VisitBlock(block);
nBlocks++;
switch (block->bbJumpKind)
{
case BBJ_CALLFINALLY:
{
// Just queue up the continuation block,
// unless the finally doesn't return, in which
// case we really should treat this block as a throw,
// and so this block would get instrumented.
//
// Since our keying scheme is IL based and this
// block has no IL offset, we'd need to invent
// some new keying scheme. For now we just
// ignore this (rare) case.
//
if (block->isBBCallAlwaysPair())
{
// This block should be the only pred of the continuation.
//
BasicBlock* const target = block->bbNext;
assert(!BlockSetOps::IsMember(comp, marked, target->bbNum));
visitor->VisitTreeEdge(block, target);
stack.Push(target);
BlockSetOps::AddElemD(comp, marked, target->bbNum);
}
}
break;
case BBJ_RETURN:
case BBJ_THROW:
{
// Pseudo-edge back to method entry.
//
// Note if the throw is caught locally this will over-state the profile
// count for method entry. But we likely don't care too much about
// profiles for methods that throw lots of exceptions.
//
BasicBlock* const target = fgFirstBB;
assert(BlockSetOps::IsMember(comp, marked, target->bbNum));
visitor->VisitNonTreeEdge(block, target, SpanningTreeVisitor::EdgeKind::PostdominatesSource);
}
break;
case BBJ_EHFINALLYRET:
case BBJ_EHCATCHRET:
case BBJ_EHFILTERRET:
case BBJ_LEAVE:
{
// See if we're leaving an EH handler region.
//
bool isInTry = false;
unsigned const regionIndex = ehGetMostNestedRegionIndex(block, &isInTry);
if (isInTry)
{
// No, we're leaving a try or catch, not a handler.
// Treat this as a normal edge.
//
BasicBlock* const target = block->bbJumpDest;
// In some bad IL cases we may not have a target.
// In others we may see something other than LEAVE be most-nested in a try.
//
if (target == nullptr)
{
JITDUMP("No jump dest for " FMT_BB ", suspect bad code\n", block->bbNum);
visitor->Badcode();
}
else if (block->bbJumpKind != BBJ_LEAVE)
{
JITDUMP("EH RET in " FMT_BB " most-nested in try, suspect bad code\n", block->bbNum);
visitor->Badcode();
}
else
{
if (BlockSetOps::IsMember(comp, marked, target->bbNum))
{
visitor->VisitNonTreeEdge(block, target,
SpanningTreeVisitor::EdgeKind::PostdominatesSource);
}
else
{
visitor->VisitTreeEdge(block, target);
stack.Push(target);
BlockSetOps::AddElemD(comp, marked, target->bbNum);
}
}
}
else
{
// Pseudo-edge back to handler entry.
//
EHblkDsc* const dsc = ehGetBlockHndDsc(block);
BasicBlock* const target = dsc->ebdHndBeg;
assert(BlockSetOps::IsMember(comp, marked, target->bbNum));
visitor->VisitNonTreeEdge(block, target, SpanningTreeVisitor::EdgeKind::PostdominatesSource);
}
}
break;
default:
{
// If this block is a control flow fork, we want to
// preferentially visit critical edges first; if these
// edges end up in the DFST then instrumentation will
// require edge splitting.
//
// We also want to preferentially visit edges to rare
// successors last, if this block is non-rare.
//
// It's not immediately clear if we should pass comp or this
// to NumSucc here (for inlinees).
//
// It matters for FINALLYRET and for SWITCHES. Currently
// we handle the first one specially, and it seems possible
// things will just work for switches either way, but it
// might work a bit better using the root compiler.
//
const unsigned numSucc = block->NumSucc(comp);
if (numSucc == 1)
{
// Not a fork. Just visit the sole successor.
//
BasicBlock* const target = block->GetSucc(0, comp);
if (BlockSetOps::IsMember(comp, marked, target->bbNum))
{
// We can't instrument in the call always pair tail block
// so treat this as a critical edge.
//
visitor->VisitNonTreeEdge(block, target,
block->isBBCallAlwaysPairTail()
? SpanningTreeVisitor::EdgeKind::CriticalEdge
: SpanningTreeVisitor::EdgeKind::PostdominatesSource);
}
else
{
visitor->VisitTreeEdge(block, target);
stack.Push(target);
BlockSetOps::AddElemD(comp, marked, target->bbNum);
}
}
else
{
// A block with multiple successors.
//
// Because we're using a stack up above, we work in reverse
// order of "cost" here -- so we first consider rare,
// then normal, then critical.
//
// That is, all things being equal we'd prefer to
// have critical edges be tree edges, and
// edges from non-rare to rare be non-tree edges.
//
scratch.Reset();
BlockSetOps::ClearD(comp, processed);
for (unsigned i = 0; i < numSucc; i++)
{
BasicBlock* const succ = block->GetSucc(i, comp);
scratch.Push(succ);
}
// Rare successors of non-rare blocks
//
for (unsigned i = 0; i < numSucc; i++)
{
BasicBlock* const target = scratch.Top(i);
if (BlockSetOps::IsMember(comp, processed, i))
{
continue;
}
if (block->isRunRarely() || !target->isRunRarely())
{
continue;
}
BlockSetOps::AddElemD(comp, processed, i);
if (BlockSetOps::IsMember(comp, marked, target->bbNum))
{
visitor->VisitNonTreeEdge(block, target,
target->bbRefs > 1
? SpanningTreeVisitor::EdgeKind::CriticalEdge
: SpanningTreeVisitor::EdgeKind::DominatesTarget);
}
else
{
visitor->VisitTreeEdge(block, target);
stack.Push(target);
BlockSetOps::AddElemD(comp, marked, target->bbNum);
}
}
// Non-critical edges
//
for (unsigned i = 0; i < numSucc; i++)
{
BasicBlock* const target = scratch.Top(i);
if (BlockSetOps::IsMember(comp, processed, i))
{
continue;
}
if (target->bbRefs != 1)
{
continue;
}
BlockSetOps::AddElemD(comp, processed, i);
if (BlockSetOps::IsMember(comp, marked, target->bbNum))
{
visitor->VisitNonTreeEdge(block, target, SpanningTreeVisitor::EdgeKind::DominatesTarget);
}
else
{
visitor->VisitTreeEdge(block, target);
stack.Push(target);
BlockSetOps::AddElemD(comp, marked, target->bbNum);
}
}
// Critical edges
//
for (unsigned i = 0; i < numSucc; i++)
{
BasicBlock* const target = scratch.Top(i);
if (BlockSetOps::IsMember(comp, processed, i))
{
continue;
}
BlockSetOps::AddElemD(comp, processed, i);
if (BlockSetOps::IsMember(comp, marked, target->bbNum))
{
visitor->VisitNonTreeEdge(block, target, SpanningTreeVisitor::EdgeKind::CriticalEdge);
}
else
{
visitor->VisitTreeEdge(block, target);
stack.Push(target);
BlockSetOps::AddElemD(comp, marked, target->bbNum);
}
}
// Verify we processed each successor.
//
assert(numSucc == BlockSetOps::Count(comp, processed));
}
}
break;
}
}
}
//------------------------------------------------------------------------
// EfficientEdgeCountInstrumentor: instrumentor that adds a counter to
// selective edges.
//
// Based on "Optimally Profiling and Tracing Programs,"
// Ball and Larus PLDI '92.
//
class EfficientEdgeCountInstrumentor : public Instrumentor, public SpanningTreeVisitor
{
private:
// A particular edge probe. These are linked
// on the source block via bbSparseProbeList.
//
struct Probe
{
BasicBlock* target;
Probe* next;
int schemaIndex;
EdgeKind kind;
};
Probe* NewProbe(BasicBlock* source, BasicBlock* target)
{
Probe* p = new (m_comp, CMK_Pgo) Probe();
p->target = target;
p->kind = EdgeKind::Unknown;
p->schemaIndex = -1;
p->next = (Probe*)source->bbSparseProbeList;
source->bbSparseProbeList = p;
m_probeCount++;
return p;
}
void NewSourceProbe(BasicBlock* source, BasicBlock* target)
{
JITDUMP("[%u] New probe for " FMT_BB " -> " FMT_BB " [source]\n", m_probeCount, source->bbNum, target->bbNum);
Probe* p = NewProbe(source, target);
p->kind = EdgeKind::PostdominatesSource;
}
void NewTargetProbe(BasicBlock* source, BasicBlock* target)
{
JITDUMP("[%u] New probe for " FMT_BB " -> " FMT_BB " [target]\n", m_probeCount, source->bbNum, target->bbNum);
Probe* p = NewProbe(source, target);
p->kind = EdgeKind::DominatesTarget;
}
void NewEdgeProbe(BasicBlock* source, BasicBlock* target)
{
JITDUMP("[%u] New probe for " FMT_BB " -> " FMT_BB " [edge]\n", m_probeCount, source->bbNum, target->bbNum);
Probe* p = NewProbe(source, target);
p->kind = EdgeKind::CriticalEdge;
m_edgeProbeCount++;
}
unsigned m_blockCount;
unsigned m_probeCount;
unsigned m_edgeProbeCount;
bool m_badcode;
public:
EfficientEdgeCountInstrumentor(Compiler* comp)
: Instrumentor(comp)
, SpanningTreeVisitor()
, m_blockCount(0)
, m_probeCount(0)
, m_edgeProbeCount(0)
, m_badcode(false)
{
}
void Prepare(bool isPreImport) override;
bool ShouldProcess(BasicBlock* block) override
{
return ((block->bbFlags & BBF_IMPORTED) == BBF_IMPORTED);
}
void BuildSchemaElements(BasicBlock* block, Schema& schema) override;
void Instrument(BasicBlock* block, Schema& schema, BYTE* profileMemory) override;
void Badcode() override
{
m_badcode = true;
}
void VisitBlock(BasicBlock* block) override
{
m_blockCount++;
block->bbSparseProbeList = nullptr;
}
void VisitTreeEdge(BasicBlock* source, BasicBlock* target) override
{
}
void VisitNonTreeEdge(BasicBlock* source, BasicBlock* target, SpanningTreeVisitor::EdgeKind kind) override
{
switch (kind)
{
case EdgeKind::PostdominatesSource:
NewSourceProbe(source, target);
break;
case EdgeKind::DominatesTarget:
NewTargetProbe(source, target);
break;
case EdgeKind::CriticalEdge:
NewEdgeProbe(source, target);
break;
default:
assert(!"unexpected kind");
break;
}
}
};
//------------------------------------------------------------------------
// EfficientEdgeCountInstrumentor:Prepare: analyze the flow graph to
// determine which edges should be instrumented.
//
// Arguments:
// preImport - true if this is the prepare call that happens before
// importation
//
// Notes:
// Build a (maximum weight) spanning tree and designate the non-tree
// edges as the ones needing instrumentation.
//
// For non-critical edges, instrumentation happens in either the
// predecessor or successor blocks.
//
// Note we may only schematize and instrument a subset of the full
// set of instrumentation envisioned here, if the method is partially
// imported, as subsequent "passes" will bypass un-imported blocks.
//
// It might be preferable to export the full schema but only
// selectively instrument; this would make merging and importing
// of data simpler, as all schemas for a method would agree, no
// matter what importer-level opts were applied.
//
void EfficientEdgeCountInstrumentor::Prepare(bool preImport)
{
if (!preImport)
{
// If we saw badcode in the preimport prepare, we would expect
// compilation to blow up in the importer. So if we end up back
// here postimport with badcode set, something is wrong.
//
assert(!m_badcode);
return;
}
JITDUMP("\nEfficientEdgeCountInstrumentor: preparing for instrumentation\n");
m_comp->WalkSpanningTree(this);