Repository navigation
Expand file tree
/
Copy pathAOTFunctionAnalyses.cpp
More file actions
1220 lines (1099 loc) · 48.1 KB
/
Copy pathAOTFunctionAnalyses.cpp
File metadata and controls
1220 lines (1099 loc) · 48.1 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
/*
* Copyright (C) 2026 Oven, Inc. All rights reserved.
* SPDX-License-Identifier: BSD-2-Clause
*/
#include "config.h"
#include "AOTFunctionAnalyses.h"
#if ENABLE(AOT)
#include "AOTBuildContext.h"
#include "AOTCurrentWork.h"
#include "AOTDiagnostics.h"
#include "AOTEffectsDeclared.h"
#include "AOTEffectsDescription.h"
#include "AOTEffectsOfOperands.h"
#include "AOTFlowResults.h"
#include "AOTThreshold.h"
#include <algorithm>
#include <atomic>
#include <bit>
#include <limits>
#include <utility>
#include <wtf/DataLog.h>
#include <wtf/StdLibExtras.h>
#include <wtf/StringPrintStream.h>
#include <wtf/text/MakeString.h>
namespace JSC { namespace AOT { namespace Typed {
namespace {
struct AnalysisWordHasher {
void add(uint64_t word)
{
hash = (hash ^ word) * 0x9e3779b97f4a7c15ull;
hash ^= hash >> 32;
}
void add(uint32_t first, uint32_t second) { add(static_cast<uint64_t>(first) << 32 | second); }
uint64_t hash { 0x243f6a8885a308d3ull };
};
struct DeclaredRowScan {
void reads(const MemoryLocation& location) { readHeaps.add(location.heap()); }
void writes(const MemoryLocation& location) { writtenHeaps.add(location.heap()); }
void readsAtPayload(AbstractHeap heap) { addAtPayload(readHeaps, heap); }
void writesAtPayload(AbstractHeap heap) { addAtPayload(writtenHeaps, heap); }
void readsAllHeaps() { readHeaps = allHeaps; }
void throws() { }
void collects() { }
void suspends() { }
void terminates() { }
void unknownCode() { writtenHeaps = allHeaps; }
void addAtPayload(AbstractHeapSet& heaps, AbstractHeap heap)
{
hasEffectAtPayload = true;
if (heap != AbstractHeap::ShapeWords)
heaps.add(heap);
}
AbstractHeapSet readHeaps;
AbstractHeapSet writtenHeaps;
bool hasEffectAtPayload { false };
};
} // anonymous namespace
template<typename Entry>
static DeclaredRowScan scanDeclaredRow(Entry entry)
{
DeclaredRowScan scan;
forEachDeclaredEffect(entry, scan);
return scan;
}
static EffectInputs inputsOfRule(Opcode opcode)
{
if (familyOf(opcode) == OperationFamily::RuntimeValidation)
return EffectInputs::Function;
if (effectRuleOf(opcode) == EffectRule::Access)
return EffectInputs::DefinitionsBehindCasts;
return EffectInputs::Operands;
}
enum class OptionalOperands : uint8_t { MayBeGiven, AreOmitted };
static OpcodeEffectFacts computeEffectFactsOf(Opcode opcode, OptionalOperands operands = OptionalOperands::MayBeGiven)
{
OpcodeEffectFacts facts { .inputs = inputsOfRule(opcode) };
if (effectRuleOf(opcode) != EffectRule::Declared)
return facts;
Effects bound = declaredBoundOf(opcode);
AbstractHeapSet heapsLeftAlone = operands == OptionalOperands::AreOmitted ? heapsWrittenForOptionalOperands(opcode) : AbstractHeapSet();
bound.writes.remove(heapsLeftAlone);
bool runsNoOperandCode = !mayRunOperandCode(opcode);
facts.staysWithinDeclaredBound = runsNoOperandCode && !bound.mayCallUnknownCode;
if (facts.staysWithinDeclaredBound)
facts.traits.atMost = EffectTraits(bound);
if (isRefinedByValue(opcode, bound) && heapsLeftAlone.isEmpty())
return facts;
DeclaredRowScan scan = scanDeclaredRow(opcode);
scan.writtenHeaps.remove(heapsLeftAlone);
if (!bound.mayCallUnknownCode) {
Effects least = bound;
least.reads = LocationMasks(scan.readHeaps);
least.writes = LocationMasks(scan.writtenHeaps);
facts.traits.atLeast = EffectTraits(least);
}
if (!bound.mayCallUnknownCode || bound.maySuspend) {
facts.mayExitSideways = bound.mayExitSideways();
facts.writtenHeaps = scan.writtenHeaps;
}
if (runsNoOperandCode)
facts.inputs = scan.hasEffectAtPayload ? EffectInputs::Payload : EffectInputs::Row;
return facts;
}
const OpcodeEffectFacts& effectFactsOf(Opcode opcode)
{
static const std::array<OpcodeEffectFacts, numberOfOpcodes>& factsOfOpcodes = *[] {
auto result = makeUniqueWithoutFastMallocCheck<std::array<OpcodeEffectFacts, numberOfOpcodes>>();
for (Opcode member : allMembersOf<Opcode>)
(*result)[static_cast<unsigned>(member)] = computeEffectFactsOf(member);
return result.release();
}();
return factsOfOpcodes[static_cast<unsigned>(opcode)];
}
const OpcodeEffectFacts& effectFactsOf(const Value& value)
{
return effectFactsOf(value.opcode);
}
static EffectInputs effectInputsOf(TerminatorKind kind)
{
static const std::array<EffectInputs, numberOfTerminatorKinds> inputsOfKinds = [] {
std::array<EffectInputs, numberOfTerminatorKinds> result { };
for (TerminatorKind member : allMembersOf<TerminatorKind>) {
bool isDescribedByRow = effectRuleOf(member) != EffectRule::Inline && !mayRunOperandCode(member) && !scanDeclaredRow(member).hasEffectAtPayload;
result[static_cast<unsigned>(member)] = isDescribedByRow ? EffectInputs::Row : EffectInputs::Operands;
}
return result;
}();
return inputsOfKinds[static_cast<unsigned>(kind)];
}
static EffectInputs effectInputsOf(const Value& value) { return effectFactsOf(value).inputs; }
static EffectInputs effectInputsOf(const Terminator& terminator) { return effectInputsOf(terminator.kind); }
static void addPayload(AnalysisWordHasher& hasher, const Instruction& instruction, std::optional<unsigned> wordLeftOut = std::nullopt)
{
static_assert(numberOfInlinePayloadWords == 3);
std::array<uint32_t, numberOfInlinePayloadWords> inlinePayload = instruction.inlinePayload();
if (wordLeftOut && *wordLeftOut < numberOfInlinePayloadWords)
inlinePayload[*wordLeftOut] = 0;
hasher.add(instruction.flags, inlinePayload[0]);
hasher.add(inlinePayload[1], inlinePayload[2]);
std::span<const uint32_t> outOfLinePayload = instruction.outOfLinePayload();
hasher.add(outOfLinePayload.size());
for (size_t index = 0; index < outOfLinePayload.size(); ++index)
hasher.add(wordLeftOut == index + numberOfInlinePayloadWords ? 0 : outOfLinePayload[index]);
}
static bool addDefinitionBehindCasts(AnalysisWordHasher& hasher, const Function& function, ValueID id)
{
for (size_t remainingSteps = function.values.size(); remainingSteps; --remainingSteps) {
const Value& definition = function.at(id);
if (!isCastOrConversion(definition.opcode)) {
hasher.add(static_cast<uint32_t>(definition.opcode));
addPayload(hasher, definition);
return true;
}
id = definition.operand(0);
if (!id)
return false;
}
return false;
}
static uint32_t firstPositionOf(const Instruction& instruction, uint32_t index)
{
ValueID operand = instruction.operand(index);
for (uint32_t earlier = 0; earlier < index; ++earlier) {
if (instruction.operand(earlier) == operand)
return earlier;
}
return index;
}
static bool addOperands(AnalysisWordHasher& hasher, const Function& function, const Instruction& instruction, EffectInputs inputs)
{
AOT_THRESHOLD(uint32_t, maxComparedOperands, 16);
uint32_t numberOfOperands = instruction.numberOfOperands();
bool outlivesRenumbering = numberOfOperands <= maxComparedOperands;
hasher.add(numberOfOperands);
for (uint32_t index = 0; index < numberOfOperands; ++index) {
ValueID operand = instruction.operand(index);
hasher.add(outlivesRenumbering ? firstPositionOf(instruction, index) : operand.index(), !!operand);
if (!operand)
continue;
const Value& definition = function.at(operand);
hasher.add(definition.type.index(), definition.expected().predicted().index());
if (inputs == EffectInputs::DefinitionsBehindCasts && !addDefinitionBehindCasts(hasher, function, operand))
return false;
}
return true;
}
static uint64_t finishStamp(AnalysisWordHasher& hasher, const Function& function, const Instruction& instruction, EffectInputs inputs, std::optional<unsigned> payloadWordLeftOut = std::nullopt)
{
switch (inputs) {
case EffectInputs::Row:
case EffectInputs::Function:
return 0;
case EffectInputs::Payload:
case EffectInputs::Operands:
case EffectInputs::DefinitionsBehindCasts:
break;
}
addPayload(hasher, instruction, payloadWordLeftOut);
if (inputs != EffectInputs::Payload && !addOperands(hasher, function, instruction, inputs))
return 0;
return hasher.hash && hasher.hash < std::numeric_limits<uint64_t>::max() - 1 ? hasher.hash : 1;
}
static uint64_t stampOf(const Function& function, const Value& value, EffectInputs inputs)
{
AnalysisWordHasher hasher;
hasher.add(static_cast<uint32_t>(value.opcode));
if (inputs != EffectInputs::Payload)
hasher.add(value.type.index(), value.expected().predicted().index());
// What a call does follows from its callees and operands. Its site tells it from every other call, and a thousand calls of one set of callees have one answer.
std::optional<unsigned> site = effectRuleOf(value.opcode) == EffectRule::Call ? PayloadWord::accessSite(value.opcode) : std::nullopt;
return finishStamp(hasher, function, value, inputs, site);
}
static uint64_t stampOf(const Function& function, const Terminator& terminator, EffectInputs inputs)
{
AnalysisWordHasher hasher;
hasher.add(numberOfOpcodes + static_cast<uint32_t>(terminator.kind));
return finishStamp(hasher, function, terminator, inputs);
}
static uint32_t hashOf(const EffectsOnEdges& effectsOnEdges)
{
AnalysisWordHasher hasher;
for (const Effects* effects : { &effectsOnEdges.normal, &effectsOnEdges.handler }) {
hasher.add(effects->reads.mixedWords());
hasher.add(effects->writes.mixedWords());
hasher.add(WTF::packBools(static_cast<bool>(effects->mayThrow), effects->mayThrowOtherThanStackOverflow(), effects->mayThrowByRule(), effects->mayCollect, effects->mayCallUnknownCode, effects->maySuspend, effects->mayBeTerminated));
}
return static_cast<uint32_t>(hasher.hash);
}
EffectsCache::EffectsCache(const EffectContext& context, const Function& function, Diagnostics* diagnosticsForOutdatedAnswers)
: m_context(context)
, m_function(function)
, m_diagnosticsForOutdatedAnswers(diagnosticsForOutdatedAnswers)
{
}
void EffectsCache::resizeToFunction()
{
m_values.resize(m_function.values.size());
m_terminators.resize(m_function.blocks.size());
m_stampsOfUsers.resize(m_function.values.size());
}
template<typename Carrier>
EffectsCache::EntryID EffectsCache::compute(const Carrier& carrier)
{
++m_numberOfComputedAnswers;
EffectsOnEdges effects = Typed::effectsOf(m_context, m_function, carrier);
uint32_t hash = hashOf(effects);
EffectTraitsOnEdges traits(effects);
EntryID entry = m_entries.findOrAdd(WTF::move(effects), hash);
if (entry.index() == m_traitsOfEntries.size())
m_traitsOfEntries.append(traits);
return entry;
}
template<typename Carrier>
void EffectsCache::answerAgain(Answer& answer, EntryID& entryOfRow, const Carrier& carrier)
{
answer.round = m_round;
EffectInputs inputs = effectInputsOf(carrier);
if (inputs == EffectInputs::Row) {
if (!entryOfRow)
entryOfRow = compute(carrier);
answer.stamp = 0;
answer.entry = entryOfRow;
return;
}
uint64_t stamp = stampOf(m_function, carrier, inputs);
if (stamp && stamp == answer.stamp) {
++m_numberOfKeptAnswers;
return;
}
answer.stamp = stamp;
if (!stamp) {
answer.entry = compute(carrier);
return;
}
if (auto kept = m_entryOfStamp.find(stamp); kept != m_entryOfStamp.end()) {
++m_numberOfKeptAnswers;
answer.entry = kept->value;
return;
}
answer.entry = compute(carrier);
m_entryOfStamp.add(stamp, answer.entry);
}
// Whoever edits a function tells the analyses before it asks them again. The build goes on with the answer that a build without the check goes by.
template<typename Carrier>
void EffectsCache::reportIfOutdated(const Answer& answer, const Carrier& carrier, BlockID block, ValueID value)
{
const EffectsOnEdges& kept = m_entries.at(answer.entry);
EffectsOnEdges fresh = Typed::effectsOf(m_context, m_function, carrier);
if (kept == fresh || m_didReportOutdatedAnswer)
return;
reportOutdatedAnswer(makeString("the pass asked for the effects of "_s, value ? makeString('v', value.index(), " ("_s, nameOf(m_function.at(value).opcode), ')') : makeString("the end of b"_s, block.index()), " after an edit that the analyses were not told of: they answered "_s, toString(kept), ", and the effects are "_s, toString(fresh)));
}
void EffectsCache::reportOutdatedAnswer(String&& detail) const
{
if (std::exchange(m_didReportOutdatedAnswer, true))
return;
const CurrentWork& work = currentWork();
uint32_t functionPlusOne = work.functionPlusOne.load(std::memory_order_relaxed);
m_diagnosticsForOutdatedAnswers->add(InternalError {
.kind = InternalErrorKind::VerificationFailedAfterPass,
.function = functionPlusOne ? FunctionID(functionPlusOne - 1) : FunctionID(),
.pass = work.pass.load(std::memory_order_relaxed),
.detail = WTF::move(detail),
});
}
EffectsCache::EntryID EffectsCache::entryOf(ValueID id)
{
RELEASE_ASSERT(id.index() < m_values.size());
Answer& answer = m_values[id.index()];
if (answer.round != m_round) {
const Value& value = m_function.at(id);
answerAgain(answer, m_entryOfOpcode[static_cast<unsigned>(value.opcode)], value);
} else if (m_diagnosticsForOutdatedAnswers) [[unlikely]]
reportIfOutdated(answer, m_function.at(id), { }, id);
return answer.entry;
}
EffectsCache::EntryID EffectsCache::entryOfTerminator(BlockID block)
{
RELEASE_ASSERT(block.index() < m_terminators.size());
Answer& answer = m_terminators[block.index()];
if (answer.round != m_round) {
const Terminator& terminator = m_function.at(block).terminator;
answerAgain(answer, m_entryOfTerminatorKind[static_cast<unsigned>(terminator.kind)], terminator);
} else if (m_diagnosticsForOutdatedAnswers) [[unlikely]]
reportIfOutdated(answer, m_function.at(block).terminator, block, { });
return answer.entry;
}
const EffectsOnEdges& EffectsCache::of(ValueID id) { return m_entries.at(entryOf(id)); }
const EffectsOnEdges& EffectsCache::ofTerminator(BlockID block) { return m_entries.at(entryOfTerminator(block)); }
EffectTraitsOnEdges EffectsCache::traitsOf(ValueID id) { return m_traitsOfEntries[entryOf(id).index()]; }
EffectTraitsOnEdges EffectsCache::traitsOfTerminator(BlockID block) { return m_traitsOfEntries[entryOfTerminator(block).index()]; }
uint64_t EffectsCache::stampInThisRoundOf(ValueID id, const Value& value)
{
RELEASE_ASSERT(id.index() < m_values.size() && id.index() < m_stampsOfUsers.size());
if (const Answer& answer = m_values[id.index()]; answer.round == m_round)
return answer.stamp;
StampInRound& kept = m_stampsOfUsers[id.index()];
if (kept.round != m_round) {
kept.round = m_round;
kept.stamp = stampOf(m_function, value, effectInputsOf(value));
}
return kept.stamp;
}
OperandSummary EffectsCache::summaryOfOperand(ValueID id, uint32_t operandIndex)
{
const Value& user = m_function.at(id);
switch (effectRuleOf(user.opcode)) {
case EffectRule::Declared:
case EffectRule::Operator:
return summarizeOperand(m_context, m_function, user, operandIndex);
case EffectRule::Access:
case EffectRule::Call:
case EffectRule::Builtin:
case EffectRule::Inline:
break;
}
uint64_t stamp = stampInThisRoundOf(id, user);
if (!stamp)
return summarizeOperand(m_context, m_function, user, operandIndex);
uint64_t key = stamp ^ (0x9e3779b97f4a7c15ull * (operandIndex + 1));
if (key >= std::numeric_limits<uint64_t>::max() - 1)
key = 1;
return m_operandSummaryOfStamp.ensure(key, [&] {
return summarizeOperand(m_context, m_function, user, operandIndex);
}).iterator->value;
}
template<typename Carrier>
const EffectsOnEdges* EffectsCache::findKept(const Vector<Answer>& answers, size_t index, EntryID entryOfRow, const Carrier& carrier) const
{
EffectInputs inputs = effectInputsOf(carrier);
if (inputs == EffectInputs::Row)
return entryOfRow ? &m_entries.at(entryOfRow) : nullptr;
if (index < answers.size() && answers[index].round == m_round)
return &m_entries.at(answers[index].entry);
uint64_t stamp = stampOf(m_function, carrier, inputs);
if (!stamp)
return nullptr;
auto kept = m_entryOfStamp.find(stamp);
return kept != m_entryOfStamp.end() ? &m_entries.at(kept->value) : nullptr;
}
const EffectsOnEdges* EffectsCache::findKept(ValueID id) const
{
const Value& value = m_function.at(id);
return findKept(m_values, id.index(), m_entryOfOpcode[static_cast<unsigned>(value.opcode)], value);
}
const EffectsOnEdges* EffectsCache::findKeptOfTerminator(BlockID block) const
{
const Terminator& terminator = m_function.at(block).terminator;
return findKept(m_terminators, block.index(), m_entryOfTerminatorKind[static_cast<unsigned>(terminator.kind)], terminator);
}
static AnalysisSet addDependentAnalyses(AnalysisSet set)
{
if (set.contains(FunctionAnalysis::ControlFlow))
set.add(allAnalyses);
if (set.contains(FunctionAnalysis::Dominators))
set.add({ FunctionAnalysis::NaturalLoops, FunctionAnalysis::Guards, FunctionAnalysis::FailedTests, FunctionAnalysis::Induction });
if (set.contains(FunctionAnalysis::NaturalLoops))
set.add(FunctionAnalysis::Induction);
if (set.contains(FunctionAnalysis::Cycles))
set.add({ FunctionAnalysis::Escape, FunctionAnalysis::Frequencies });
if (set.contains(FunctionAnalysis::UseLists))
set.add({ FunctionAnalysis::Liveness, FunctionAnalysis::Escape, FunctionAnalysis::Guards, FunctionAnalysis::Induction });
if (set.contains(FunctionAnalysis::Identities))
set.add({ FunctionAnalysis::Guards, FunctionAnalysis::FailedTests, FunctionAnalysis::Induction });
if (set.contains(FunctionAnalysis::Effects))
set.add({ FunctionAnalysis::Escape, FunctionAnalysis::EscapeHistory, FunctionAnalysis::Guards, FunctionAnalysis::Induction });
if (set.contains(FunctionAnalysis::Escape))
set.add({ FunctionAnalysis::EscapeHistory, FunctionAnalysis::Guards });
if (set.containsAny({ FunctionAnalysis::EscapeHistory, FunctionAnalysis::Frequencies }))
set.add(FunctionAnalysis::Guards);
return set;
}
FunctionAnalyses::FunctionAnalyses(const AnalysisContext& context, const Function& function)
: m_context(context)
, m_function(function)
, m_effectContext { context.program, context.effects ? *context.effects : m_unknownSummaries.emplace(), context.savedFrames == SavedFrames::AreOutOfReach ? UntestedStorage::LeavesReadKnown : UntestedStorage::MakesReadUnknown }
, m_effects(m_effectContext, function, context.build.options().verifiesAfterEveryPass ? &context.build.diagnostics() : nullptr)
, m_countsBuilds(context.build.options().logging.logsPhaseTimes)
, m_verifiesUpdates(context.build.options().verifiesAfterEveryPass)
{
}
FunctionAnalyses::FunctionAnalyses(const AnalysisContext& context, Function& function)
: FunctionAnalyses(context, std::as_const(function))
{
m_changes = function.changeLog();
if (m_changes)
return;
constexpr size_t entriesForEachValue = 64;
AOT_THRESHOLD(size_t, fewestEntries, 256);
m_ownChanges.setMaxNumberOfEntries(fewestEntries + entriesForEachValue * function.values.size());
m_changes = &m_ownChanges;
m_functionWithOwnChanges = &function;
function.attach(m_ownChanges);
}
ChangeLog& changeLogOf(FunctionAnalyses& analyses) { return analyses.changes(); }
FunctionAnalyses::~FunctionAnalyses()
{
if (m_functionWithOwnChanges)
m_functionWithOwnChanges->detach(m_ownChanges);
Statistics& statistics = m_context.build.statistics();
if (uint64_t numberOfComputedAnswers = m_effects.numberOfComputedAnswers())
statistics.count(StatisticID::EffectsComputed, numberOfComputedAnswers);
if (uint64_t numberOfKeptAnswers = m_effects.numberOfKeptAnswers())
statistics.count(StatisticID::EffectsKept, numberOfKeptAnswers);
if (m_numberOfBlocksReadToBuildControlFlowGraphs)
statistics.count(StatisticID::BlocksReadToBuildControlFlowGraphs, m_numberOfBlocksReadToBuildControlFlowGraphs);
}
void FunctionAnalyses::reportQuestionBeforeRepair() const
{
if (m_context.build.options().verifiesProgram)
m_context.build.diagnostics().add(InternalError { .kind = InternalErrorKind::QuestionBeforeRepair, .function = m_context.id, .pass = currentWork().pass.load(std::memory_order_relaxed) });
}
Subject FunctionAnalyses::subject(ValueID value) const
{
if (!m_context.id)
return { };
FunctionID known = m_context.id;
if (ProvisionalFunctions::contains(known))
known = m_function.derivation.source;
while (ProvisionalFunctions::contains(known))
known = m_context.program.at(known).derivation.source;
Subject result { .function = findFunctionAsRead(&m_context.program, known), .location = m_function.declarationLocation() };
if (!value)
return result;
SourceLocation location = m_function.locationOf(value);
if (hasModule(location))
result.location = location;
if (result.function == m_context.id)
result.value = value;
return result;
}
static constexpr unsigned indexOf(FunctionAnalysis analysis) { return std::countr_zero(static_cast<unsigned>(analysis)); }
static_assert(indexOf(FunctionAnalysis::Induction) + 1 == numberOfFunctionAnalyses);
using CountsByPass = std::array<std::atomic<uint64_t>, numberOfPasses>;
static constinit std::array<CountsByPass, numberOfFunctionAnalyses> buildsByAskingPass { };
static constinit std::array<CountsByPass, numberOfFunctionAnalyses> buildsByDroppingPass { };
static constinit std::array<std::atomic<uint64_t>, numberOfFunctionAnalyses> valuesOfAnalyzedFunctions { };
static constinit std::array<std::atomic<uint64_t>, numberOfFunctionAnalyses> blocksOfAnalyzedFunctions { };
static constinit std::atomic<uint64_t> numberOfKeptGraphs { 0 };
static constinit std::atomic<uint64_t> numberOfFormerGraphs { 0 };
static constinit std::atomic<uint64_t> numberOfKeptFrequencies { 0 };
static constinit std::atomic<uint64_t> numberOfFormerFrequencies { 0 };
static constinit CountsByPass useListUpdatesByChangingPass { };
static constinit std::atomic<uint64_t> valuesOfFunctionsWithUpdatedUseLists { 0 };
static constinit std::atomic<uint64_t> valuesReadByUseListUpdates { 0 };
static constinit std::array<std::atomic<uint64_t>, UseLists::numberOfReasonsToMakeAnew> useListsMadeAnewByReason { };
static constinit std::array<std::atomic<uint64_t>, UseLists::numberOfReasonsToMakeAnew> valuesOfUseListsMadeAnewByReason { };
void FunctionAnalyses::didBuild(FunctionAnalysis analysis)
{
if (!m_countsBuilds) [[likely]]
return;
unsigned index = indexOf(analysis);
buildsByAskingPass[index][static_cast<unsigned>(m_runningPass)].fetch_add(1, std::memory_order_relaxed);
buildsByDroppingPass[index][static_cast<unsigned>(m_passesThatDropped[index])].fetch_add(1, std::memory_order_relaxed);
valuesOfAnalyzedFunctions[index].fetch_add(m_function.values.size(), std::memory_order_relaxed);
blocksOfAnalyzedFunctions[index].fetch_add(m_function.blocks.size(), std::memory_order_relaxed);
}
void FunctionAnalyses::didBringUseListsUpToDate(const UseLists::Update& update)
{
if (update.madeAnewFor != UseLists::ReasonToMakeAnew::None) {
didBuild(FunctionAnalysis::UseLists);
if (m_countsBuilds) [[unlikely]] {
useListsMadeAnewByReason[static_cast<unsigned>(update.madeAnewFor)].fetch_add(1, std::memory_order_relaxed);
valuesOfUseListsMadeAnewByReason[static_cast<unsigned>(update.madeAnewFor)].fetch_add(update.numberOfValuesRead, std::memory_order_relaxed);
}
return;
}
if (m_verifiesUpdates) [[unlikely]]
verifyUseLists();
if (!m_countsBuilds) [[likely]]
return;
useListUpdatesByChangingPass[static_cast<unsigned>(m_passesThatDropped[indexOf(FunctionAnalysis::UseLists)])].fetch_add(1, std::memory_order_relaxed);
valuesOfFunctionsWithUpdatedUseLists.fetch_add(m_function.values.size(), std::memory_order_relaxed);
valuesReadByUseListUpdates.fetch_add(update.numberOfValuesRead, std::memory_order_relaxed);
}
void FunctionAnalyses::willDrop(AnalysisSet set)
{
if (!m_countsBuilds) [[likely]]
return;
for (FunctionAnalysis analysis : set & (computed() | heldControlFlowAnalyses()))
m_passesThatDropped[indexOf(analysis)] = m_runningPass;
}
ASCIILiteral sectionNameOf(FunctionAnalysis analysis)
{
switch (analysis) {
case FunctionAnalysis::ControlFlow:
return "control-flow"_s;
case FunctionAnalysis::Dominators:
return "dominators"_s;
case FunctionAnalysis::NaturalLoops:
return "natural-loops"_s;
case FunctionAnalysis::Cycles:
return "cycles"_s;
case FunctionAnalysis::UseLists:
return "use-lists"_s;
case FunctionAnalysis::Identities:
return "identities"_s;
case FunctionAnalysis::Liveness:
return "liveness"_s;
case FunctionAnalysis::Effects:
return "effects"_s;
case FunctionAnalysis::Escape:
return "escape"_s;
case FunctionAnalysis::EscapeHistory:
return "escape-history"_s;
case FunctionAnalysis::Frequencies:
return "frequencies"_s;
case FunctionAnalysis::Guards:
return "guards"_s;
case FunctionAnalysis::FailedTests:
return "failed-tests"_s;
case FunctionAnalysis::Induction:
return "induction"_s;
}
RELEASE_ASSERT_NOT_REACHED();
}
static uint64_t printAndResetCounts(PrintStream& out, CountsByPass& counts)
{
uint64_t total = 0;
for (unsigned pass = 0; pass < numberOfPasses; ++pass) {
uint64_t count = counts[pass].exchange(0, std::memory_order_relaxed);
if (!count)
continue;
total += count;
out.print(" ", nameOf(static_cast<PassID>(pass)), " ", count);
}
return total;
}
void FunctionAnalyses::logBuilds()
{
for (FunctionAnalysis analysis : allAnalyses) {
StringPrintStream askingPasses;
StringPrintStream droppingPasses;
uint64_t total = printAndResetCounts(askingPasses, buildsByAskingPass[indexOf(analysis)]);
printAndResetCounts(droppingPasses, buildsByDroppingPass[indexOf(analysis)]);
uint64_t values = valuesOfAnalyzedFunctions[indexOf(analysis)].exchange(0, std::memory_order_relaxed);
uint64_t blocks = blocksOfAnalyzedFunctions[indexOf(analysis)].exchange(0, std::memory_order_relaxed);
if (total)
dataLogLn("AOT analyses: ", sectionNameOf(analysis), " | built ", total, " | asked for by", askingPasses.toString(), " | dropped by", droppingPasses.toString(), " | over ", values, " values in ", blocks, " blocks");
}
uint64_t kept = numberOfKeptGraphs.exchange(0, std::memory_order_relaxed);
uint64_t former = numberOfFormerGraphs.exchange(0, std::memory_order_relaxed);
if (kept || former)
dataLogLn("AOT analyses: graphs compared with the function | the same ", kept, " | changed ", former);
uint64_t keptFrequencies = numberOfKeptFrequencies.exchange(0, std::memory_order_relaxed);
uint64_t formerFrequencies = numberOfFormerFrequencies.exchange(0, std::memory_order_relaxed);
if (keptFrequencies || formerFrequencies)
dataLogLn("AOT analyses: frequencies compared with the function | the same ", keptFrequencies, " | changed ", formerFrequencies);
StringPrintStream changingPasses;
uint64_t updates = printAndResetCounts(changingPasses, useListUpdatesByChangingPass);
uint64_t valuesHeld = valuesOfFunctionsWithUpdatedUseLists.exchange(0, std::memory_order_relaxed);
uint64_t valuesRead = valuesReadByUseListUpdates.exchange(0, std::memory_order_relaxed);
if (updates)
dataLogLn("AOT analyses: use-lists | brought up to date ", updates, " | behind", changingPasses.toString(), " | in functions of ", valuesHeld, " values | ", valuesRead, " of them read again");
static constexpr std::array<ASCIILiteral, UseLists::numberOfReasonsToMakeAnew> reasons { ""_s, "no log"_s, "nothing was kept for an update"_s, "changes forgotten"_s, "much has changed"_s, "much is gone"_s, "a change that the log does not have"_s };
StringPrintStream madeAnew;
for (unsigned reason = 0; reason < UseLists::numberOfReasonsToMakeAnew; ++reason) {
uint64_t values = valuesOfUseListsMadeAnewByReason[reason].exchange(0, std::memory_order_relaxed);
if (uint64_t count = useListsMadeAnewByReason[reason].exchange(0, std::memory_order_relaxed))
madeAnew.print(" | ", reasons[reason], " ", count, " over ", values, " values");
}
if (madeAnew.length())
dataLogLn("AOT analyses: use-lists | made anew where they were held", madeAnew.toString());
}
void FunctionAnalyses::dropResultsOfFormerGraph()
{
if (!m_controlFlow.mayDescribeFormerGraph) [[likely]]
return;
m_controlFlow.mayDescribeFormerGraph = false;
bool isSameGraph = m_controlFlow.cfg->describes(m_function);
if (m_countsBuilds) [[unlikely]]
(isSameGraph ? numberOfKeptGraphs : numberOfFormerGraphs).fetch_add(1, std::memory_order_relaxed);
if (isSameGraph)
return;
dropFrequencies();
m_controlFlow.naturalLoops.reset();
m_controlFlow.dominators.reset();
m_controlFlow.blockCycles.reset();
m_controlFlow.cfg.reset();
}
void FunctionAnalyses::dropFrequencies()
{
m_values.blockFrequencies.reset();
m_values.frequenciesMayDescribeFormerFunction = false;
}
void FunctionAnalyses::dropFrequenciesOfFormerFunction()
{
if (!m_values.frequenciesMayDescribeFormerFunction) [[likely]]
return;
dropResultsOfFormerGraph();
if (!m_values.frequenciesMayDescribeFormerFunction)
return;
willComputeValueAnalysis();
m_values.frequenciesMayDescribeFormerFunction = false;
bool isSameEstimate = m_values.blockFrequencies->describes(m_context, m_function);
if (m_countsBuilds) [[unlikely]]
(isSameEstimate ? numberOfKeptFrequencies : numberOfFormerFrequencies).fetch_add(1, std::memory_order_relaxed);
if (!isSameEstimate)
m_values.blockFrequencies.reset();
else if (m_verifiesUpdates) [[unlikely]]
verifyFrequencies();
}
CFG& FunctionAnalyses::cfg()
{
if (m_controlFlow.cfg && !m_controlFlow.mayDescribeFormerGraph) [[likely]] {
checkBlockCount();
return *m_controlFlow.cfg;
}
dropResultsOfFormerGraph();
if (!m_controlFlow.cfg) {
m_controlFlow.cfg.emplace(m_function);
m_numberOfBlocksReadToBuildControlFlowGraphs += m_function.blocks.size();
m_controlFlow.isReadByUseLists = false;
m_controlFlow.numberOfBlocks = m_function.blocks.size();
didBuild(FunctionAnalysis::ControlFlow);
}
checkBlockCount();
return *m_controlFlow.cfg;
}
Dominators& FunctionAnalyses::dominators()
{
dropResultsOfFormerGraph();
if (!m_controlFlow.dominators) {
m_controlFlow.dominators.emplace(cfg(), false);
didBuild(FunctionAnalysis::Dominators);
}
checkBlockCount();
return *m_controlFlow.dominators;
}
NaturalLoops& FunctionAnalyses::naturalLoops()
{
dropResultsOfFormerGraph();
if (!m_controlFlow.naturalLoops) {
m_controlFlow.naturalLoops.emplace(cfg(), dominators(), false);
didBuild(FunctionAnalysis::NaturalLoops);
}
checkBlockCount();
return *m_controlFlow.naturalLoops;
}
const BlockCycles& FunctionAnalyses::blockCycles()
{
dropResultsOfFormerGraph();
if (!m_controlFlow.blockCycles) {
m_controlFlow.blockCycles.emplace(cfg());
didBuild(FunctionAnalysis::Cycles);
}
checkBlockCount();
return *m_controlFlow.blockCycles;
}
void FunctionAnalyses::willComputeValueAnalysis()
{
if (!computed().containsAny(valueAnalyses))
m_values.numberOfValues = m_function.values.size();
m_values.mayHoldResults = true;
}
template<typename Result>
const Result& FunctionAnalyses::valueResult(std::optional<Result>& result, const Invocable<void()> auto& make)
{
if (!result) {
willComputeValueAnalysis();
make();
}
checkBlockCount();
checkValueCount();
return *result;
}
const UseLists& FunctionAnalyses::useLists()
{
if (m_values.useLists && m_values.useLists->isUpToDate() && !m_values.didDropBesideUseLists) [[likely]] {
checkBlockCount();
checkValueCount();
return *m_values.useLists;
}
if (!m_values.useLists) {
willComputeValueAnalysis();
m_values.useLists.emplace(m_function, cfg(), m_changes);
m_controlFlow.isReadByUseLists = true;
m_values.didDropBesideUseLists = false;
didBuild(FunctionAnalysis::UseLists);
} else if (!m_values.useLists->isUpToDate()) {
willComputeValueAnalysis();
const CFG& graph = cfg();
UseLists::Update update = m_values.useLists->bringUpToDate(graph, std::exchange(m_controlFlow.isReadByUseLists, true));
m_values.didDropBesideUseLists = false;
didBringUseListsUpToDate(update);
} else if (m_values.didDropBesideUseLists) [[unlikely]] {
m_values.didDropBesideUseLists = false;
if (m_verifiesUpdates)
verifyUseLists();
}
checkBlockCount();
checkValueCount();
return *m_values.useLists;
}
static constexpr bool reportsEveryChangeToUseListInputs(PassID pass) { return pass == PassID::EliminateDeadCode || pass == PassID::CompactBlocks; }
UseLists* FunctionAnalyses::updatingUseLists()
{
if (!m_values.useLists || m_values.useLists->mustBeMadeAnew() || !(m_everyChangeIsReported || reportsEveryChangeToUseListInputs(m_runningPass)))
return nullptr;
if (m_countsBuilds) [[unlikely]]
m_passesThatDropped[indexOf(FunctionAnalysis::UseLists)] = m_runningPass;
return &*m_values.useLists;
}
static constexpr EnumeratorBitSet<PassID, numberOfPasses> passesThatAskForIdentitiesOnlyBeforeEditing {
PassID::SimplifyControlFlow, PassID::RemoveTrivialParameters, PassID::PropagateBranchConditions, PassID::RemoveRedundantBarriers,
};
static constexpr bool asksForIdentitiesOnlyBeforeEditing(PassID pass) { return passesThatAskForIdentitiesOnlyBeforeEditing.contains(pass); }
static constexpr EnumeratorBitSet<PassID, numberOfPasses> passesThatMayCompleteIdentitiesLate {
PassID::FoldConstants, PassID::PropagateBranchConditions, PassID::HoistTestsIntoPredecessors, PassID::ThreadJumps, PassID::EliminateDeadCode,
PassID::EliminateRedundantReads, PassID::RetypeValues, PassID::CompactBlocks,
};
void FunctionAnalyses::dropIncompleteIdentitiesBeforePass()
{
if (asksForIdentitiesOnlyBeforeEditing(m_runningPass) || passesThatMayCompleteIdentitiesLate.contains(m_runningPass))
return;
willDrop(FunctionAnalysis::Identities);
m_values.identities.reset();
}
const ValueIdentities& FunctionAnalyses::identities()
{
auto evaluation = !m_changes || asksForIdentitiesOnlyBeforeEditing(m_runningPass) ? ValueIdentities::Evaluation::OnDemand : ValueIdentities::Evaluation::Complete;
if (!m_values.identities) {
willComputeValueAnalysis();
m_values.identities.emplace(m_function, cfg(), ValueIdentities::RepeatedWalks::StartAtFirstChangedBlock, &opcodesOfValues(), evaluation);
m_values.didUpdateIdentities = false;
didBuild(FunctionAnalysis::Identities);
if (m_verifiesUpdates && m_values.identities->isComplete()) [[unlikely]]
verifyIdentities(cfg());
} else {
if (!m_values.identities->isComplete()) {
m_values.identities->setGraph(&cfg());
if (evaluation == ValueIdentities::Evaluation::Complete)
m_values.identities->complete();
}
if (std::exchange(m_values.didUpdateIdentities, false) && m_verifiesUpdates) [[unlikely]]
verifyIdentities(cfg());
}
checkBlockCount();
checkValueCount();
return *m_values.identities;
}
ValueID FunctionAnalyses::identityOf(ValueID id)
{
if (!m_values.identities || !m_values.identities->isComplete() || m_values.didUpdateIdentities) [[unlikely]]
return identities().identityOf(id);
checkBlockCount();
checkValueCount();
return m_values.identities->identityOf(id);
}
const Liveness& FunctionAnalyses::liveness()
{
return valueResult(m_values.liveness, [&] {
LivenessOptions options;
options.opcodesOfValues = &opcodesOfValues();
m_values.liveness.emplace(m_function, cfg(), useLists(), options);
didBuild(FunctionAnalysis::Liveness);
if (m_verifiesUpdates) [[unlikely]]
verifyLiveness();
});
}
EffectsCache& FunctionAnalyses::effectsCache()
{
if (!m_values.hasEffects) {
willComputeValueAnalysis();
m_effects.resizeToFunction();
m_values.hasEffects = true;
}
RELEASE_ASSERT(m_effects.numberOfBlocks() == m_function.blocks.size());
checkValueCount();
return m_effects;
}
const EscapeAnalysis& FunctionAnalyses::escape()
{
return valueResult(m_values.escape, [&] {
cfg();
m_values.escape.emplace(*this);
});
}
EscapeAnalysisInputs FunctionAnalyses::inputsOfEscapeAnalysis()
{
return { m_context, m_effectContext, effectsCache(), m_function, cfg(), useLists(), subject(), m_runningPass != PassID::None };
}
const EscapeAnalysis& FunctionAnalyses::escapeWithLiveInstances()
{
escape();
if (!m_values.escape->hasLiveInstances()) {
m_values.escape->computeLiveInstances(cfg(), useLists(), [&]() -> const BlockCycles& {
return blockCycles();
}, m_context.onlyJudges() ? EscapeAnalysis::OutOfSight::Asked : EscapeAnalysis::OutOfSight::NotAsked);
}
return *m_values.escape;
}
const UseEffectHistory& FunctionAnalyses::escapeHistory()
{
return valueResult(m_values.escapeHistory, [&] {
escapeWithLiveInstances();
m_values.escapeHistory.emplace(*this);
didBuild(FunctionAnalysis::EscapeHistory);
});
}
const BlockFrequencies& FunctionAnalyses::blockFrequencies()
{
dropFrequenciesOfFormerFunction();
return valueResult(m_values.blockFrequencies, [&] {
m_values.blockFrequencies.emplace(m_context, m_function, cfg(), blockCycles());
didBuild(FunctionAnalysis::Frequencies);
});
}
const GuardAvailability& FunctionAnalyses::guards()
{
return valueResult(m_values.guards, [&] {
cfg();
useLists();
identities();
m_values.guards.emplace(*this);
didBuild(FunctionAnalysis::Guards);
});
}
const OpcodeSet& FunctionAnalyses::opcodesOfValues()
{
if (!m_values.opcodes || m_values.numberOfValuesWithCollectedOpcodes != m_function.values.size()) {
m_values.numberOfValuesWithCollectedOpcodes = m_function.values.size();
m_values.mayHoldResults = true;
OpcodeSet& opcodes = m_values.opcodes.emplace();
for (const Value& value : m_function.values)
opcodes.add(value.opcode);
}
return *m_values.opcodes;
}
const FailedTests& FunctionAnalyses::failedTests()
{
return valueResult(m_values.failedTests, [&] {
m_values.failedTests.emplace(*this);
didBuild(FunctionAnalysis::FailedTests);
});
}
const InductionVariables& FunctionAnalyses::inductionVariables()
{
return valueResult(m_values.inductionVariables, [&] {
m_values.inductionVariables.emplace(*this);
didBuild(FunctionAnalysis::Induction);
});
}
GuardState FunctionAnalyses::guardStateAt(ValueID guard, const Use& use)
{
switch (use.kind) {
case Use::Kind::Operand: {
const Value& user = m_function.at(use.user);
if (user.operandKind(use.operandIndex) == OperandKind::Guard)
return guards().stateAt(guard, user, useLists().pointOf(use));
return guards().stateAt(guard, useLists().pointOf(use));
}
case Use::Kind::TerminatorOperand:
return guards().stateAt(guard, useLists().pointOf(use));
case Use::Kind::EdgeArgument:
case Use::Kind::HandlerArgument:
case Use::Kind::BlockSubject:
return GuardState::Available;
}
RELEASE_ASSERT_NOT_REACHED();
}