forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStandardInstrumentations.cpp
2147 lines (1873 loc) · 74.1 KB
/
StandardInstrumentations.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
//===- Standard pass instrumentations handling ----------------*- C++ -*--===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
/// \file
///
/// This file defines IR-printing pass instrumentation callbacks as well as
/// StandardInstrumentations class that manages standard pass instrumentations.
///
//===----------------------------------------------------------------------===//
#include "llvm/Passes/StandardInstrumentations.h"
#include "llvm/ADT/Any.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Analysis/CallGraphSCCPass.h"
#include "llvm/Analysis/LazyCallGraph.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PassInstrumentation.h"
#include "llvm/IR/PassManager.h"
#include "llvm/IR/PrintPasses.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/FormatVariadic.h"
#include "llvm/Support/GraphWriter.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/Regex.h"
#include "llvm/Support/raw_ostream.h"
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
using namespace llvm;
cl::opt<bool> PreservedCFGCheckerInstrumentation::VerifyPreservedCFG(
"verify-cfg-preserved", cl::Hidden,
#ifdef NDEBUG
cl::init(false)
#else
cl::init(true)
#endif
);
// An option that prints out the IR after passes, similar to
// -print-after-all except that it only prints the IR after passes that
// change the IR. Those passes that do not make changes to the IR are
// reported as not making any changes. In addition, the initial IR is
// also reported. Other hidden options affect the output from this
// option. -filter-passes will limit the output to the named passes
// that actually change the IR and other passes are reported as filtered out.
// The specified passes will either be reported as making no changes (with
// no IR reported) or the changed IR will be reported. Also, the
// -filter-print-funcs and -print-module-scope options will do similar
// filtering based on function name, reporting changed IRs as functions(or
// modules if -print-module-scope is specified) for a particular function
// or indicating that the IR has been filtered out. The extra options
// can be combined, allowing only changed IRs for certain passes on certain
// functions to be reported in different formats, with the rest being
// reported as filtered out. The -print-before-changed option will print
// the IR as it was before each pass that changed it. The optional
// value of quiet will only report when the IR changes, suppressing
// all other messages, including the initial IR. The values "diff" and
// "diff-quiet" will present the changes in a form similar to a patch, in
// either verbose or quiet mode, respectively. The lines that are removed
// and added are prefixed with '-' and '+', respectively. The
// -filter-print-funcs and -filter-passes can be used to filter the output.
// This reporter relies on the linux diff utility to do comparisons and
// insert the prefixes. For systems that do not have the necessary
// facilities, the error message will be shown in place of the expected output.
//
enum class ChangePrinter {
NoChangePrinter,
PrintChangedVerbose,
PrintChangedQuiet,
PrintChangedDiffVerbose,
PrintChangedDiffQuiet,
PrintChangedColourDiffVerbose,
PrintChangedColourDiffQuiet,
PrintChangedDotCfgVerbose,
PrintChangedDotCfgQuiet
};
static cl::opt<ChangePrinter> PrintChanged(
"print-changed", cl::desc("Print changed IRs"), cl::Hidden,
cl::ValueOptional, cl::init(ChangePrinter::NoChangePrinter),
cl::values(
clEnumValN(ChangePrinter::PrintChangedQuiet, "quiet",
"Run in quiet mode"),
clEnumValN(ChangePrinter::PrintChangedDiffVerbose, "diff",
"Display patch-like changes"),
clEnumValN(ChangePrinter::PrintChangedDiffQuiet, "diff-quiet",
"Display patch-like changes in quiet mode"),
clEnumValN(ChangePrinter::PrintChangedColourDiffVerbose, "cdiff",
"Display patch-like changes with color"),
clEnumValN(ChangePrinter::PrintChangedColourDiffQuiet, "cdiff-quiet",
"Display patch-like changes in quiet mode with color"),
clEnumValN(ChangePrinter::PrintChangedDotCfgVerbose, "dot-cfg",
"Create a website with graphical changes"),
clEnumValN(ChangePrinter::PrintChangedDotCfgQuiet, "dot-cfg-quiet",
"Create a website with graphical changes in quiet mode"),
// Sentinel value for unspecified option.
clEnumValN(ChangePrinter::PrintChangedVerbose, "", "")));
// An option that supports the -print-changed option. See
// the description for -print-changed for an explanation of the use
// of this option. Note that this option has no effect without -print-changed.
static cl::list<std::string>
PrintPassesList("filter-passes", cl::value_desc("pass names"),
cl::desc("Only consider IR changes for passes whose names "
"match for the print-changed option"),
cl::CommaSeparated, cl::Hidden);
// An option that supports the -print-changed option. See
// the description for -print-changed for an explanation of the use
// of this option. Note that this option has no effect without -print-changed.
static cl::opt<bool>
PrintChangedBefore("print-before-changed",
cl::desc("Print before passes that change them"),
cl::init(false), cl::Hidden);
// An option for specifying the diff used by print-changed=[diff | diff-quiet]
static cl::opt<std::string>
DiffBinary("print-changed-diff-path", cl::Hidden, cl::init("diff"),
cl::desc("system diff used by change reporters"));
// An option for specifying the dot used by
// print-changed=[dot-cfg | dot-cfg-quiet]
static cl::opt<std::string>
DotBinary("print-changed-dot-path", cl::Hidden, cl::init("dot"),
cl::desc("system dot used by change reporters"));
// An option that determines the colour used for elements that are only
// in the before part. Must be a colour named in appendix J of
// https://graphviz.org/pdf/dotguide.pdf
cl::opt<std::string>
BeforeColour("dot-cfg-before-color",
cl::desc("Color for dot-cfg before elements."), cl::Hidden,
cl::init("red"));
// An option that determines the colour used for elements that are only
// in the after part. Must be a colour named in appendix J of
// https://graphviz.org/pdf/dotguide.pdf
cl::opt<std::string> AfterColour("dot-cfg-after-color",
cl::desc("Color for dot-cfg after elements."),
cl::Hidden, cl::init("forestgreen"));
// An option that determines the colour used for elements that are in both
// the before and after parts. Must be a colour named in appendix J of
// https://graphviz.org/pdf/dotguide.pdf
cl::opt<std::string>
CommonColour("dot-cfg-common-color",
cl::desc("Color for dot-cfg common elements."), cl::Hidden,
cl::init("black"));
// An option that determines where the generated website file (named
// passes.html) and the associated pdf files (named diff_*.pdf) are saved.
static cl::opt<std::string> DotCfgDir(
"dot-cfg-dir",
cl::desc("Generate dot files into specified directory for changed IRs"),
cl::Hidden, cl::init("./"));
namespace {
// Perform a system based diff between \p Before and \p After, using
// \p OldLineFormat, \p NewLineFormat, and \p UnchangedLineFormat
// to control the formatting of the output. Return an error message
// for any failures instead of the diff.
std::string doSystemDiff(StringRef Before, StringRef After,
StringRef OldLineFormat, StringRef NewLineFormat,
StringRef UnchangedLineFormat) {
StringRef SR[2]{Before, After};
// Store the 2 bodies into temporary files and call diff on them
// to get the body of the node.
const unsigned NumFiles = 3;
static std::string FileName[NumFiles];
static int FD[NumFiles]{-1, -1, -1};
for (unsigned I = 0; I < NumFiles; ++I) {
if (FD[I] == -1) {
SmallVector<char, 200> SV;
std::error_code EC =
sys::fs::createTemporaryFile("tmpdiff", "txt", FD[I], SV);
if (EC)
return "Unable to create temporary file.";
FileName[I] = Twine(SV).str();
}
// The third file is used as the result of the diff.
if (I == NumFiles - 1)
break;
std::error_code EC = sys::fs::openFileForWrite(FileName[I], FD[I]);
if (EC)
return "Unable to open temporary file for writing.";
raw_fd_ostream OutStream(FD[I], /*shouldClose=*/true);
if (FD[I] == -1)
return "Error opening file for writing.";
OutStream << SR[I];
}
static ErrorOr<std::string> DiffExe = sys::findProgramByName(DiffBinary);
if (!DiffExe)
return "Unable to find diff executable.";
SmallString<128> OLF = formatv("--old-line-format={0}", OldLineFormat);
SmallString<128> NLF = formatv("--new-line-format={0}", NewLineFormat);
SmallString<128> ULF =
formatv("--unchanged-line-format={0}", UnchangedLineFormat);
StringRef Args[] = {DiffBinary, "-w", "-d", OLF,
NLF, ULF, FileName[0], FileName[1]};
Optional<StringRef> Redirects[] = {None, StringRef(FileName[2]), None};
int Result = sys::ExecuteAndWait(*DiffExe, Args, None, Redirects);
if (Result < 0)
return "Error executing system diff.";
std::string Diff;
auto B = MemoryBuffer::getFile(FileName[2]);
if (B && *B)
Diff = (*B)->getBuffer().str();
else
return "Unable to read result.";
// Clean up.
for (const std::string &I : FileName) {
std::error_code EC = sys::fs::remove(I);
if (EC)
return "Unable to remove temporary file.";
}
return Diff;
}
/// Extract Module out of \p IR unit. May return nullptr if \p IR does not match
/// certain global filters. Will never return nullptr if \p Force is true.
const Module *unwrapModule(Any IR, bool Force = false) {
if (any_isa<const Module *>(IR))
return any_cast<const Module *>(IR);
if (any_isa<const Function *>(IR)) {
const Function *F = any_cast<const Function *>(IR);
if (!Force && !isFunctionInPrintList(F->getName()))
return nullptr;
return F->getParent();
}
if (any_isa<const LazyCallGraph::SCC *>(IR)) {
const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
for (const LazyCallGraph::Node &N : *C) {
const Function &F = N.getFunction();
if (Force || (!F.isDeclaration() && isFunctionInPrintList(F.getName()))) {
return F.getParent();
}
}
assert(!Force && "Expected a module");
return nullptr;
}
if (any_isa<const Loop *>(IR)) {
const Loop *L = any_cast<const Loop *>(IR);
const Function *F = L->getHeader()->getParent();
if (!Force && !isFunctionInPrintList(F->getName()))
return nullptr;
return F->getParent();
}
llvm_unreachable("Unknown IR unit");
}
void printIR(raw_ostream &OS, const Function *F) {
if (!isFunctionInPrintList(F->getName()))
return;
OS << *F;
}
void printIR(raw_ostream &OS, const Module *M) {
if (isFunctionInPrintList("*") || forcePrintModuleIR()) {
M->print(OS, nullptr);
} else {
for (const auto &F : M->functions()) {
printIR(OS, &F);
}
}
}
void printIR(raw_ostream &OS, const LazyCallGraph::SCC *C) {
for (const LazyCallGraph::Node &N : *C) {
const Function &F = N.getFunction();
if (!F.isDeclaration() && isFunctionInPrintList(F.getName())) {
F.print(OS);
}
}
}
void printIR(raw_ostream &OS, const Loop *L) {
const Function *F = L->getHeader()->getParent();
if (!isFunctionInPrintList(F->getName()))
return;
printLoop(const_cast<Loop &>(*L), OS);
}
std::string getIRName(Any IR) {
if (any_isa<const Module *>(IR))
return "[module]";
if (any_isa<const Function *>(IR)) {
const Function *F = any_cast<const Function *>(IR);
return F->getName().str();
}
if (any_isa<const LazyCallGraph::SCC *>(IR)) {
const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
return C->getName();
}
if (any_isa<const Loop *>(IR)) {
const Loop *L = any_cast<const Loop *>(IR);
std::string S;
raw_string_ostream OS(S);
L->print(OS, /*Verbose*/ false, /*PrintNested*/ false);
return OS.str();
}
llvm_unreachable("Unknown wrapped IR type");
}
bool moduleContainsFilterPrintFunc(const Module &M) {
return any_of(M.functions(),
[](const Function &F) {
return isFunctionInPrintList(F.getName());
}) ||
isFunctionInPrintList("*");
}
bool sccContainsFilterPrintFunc(const LazyCallGraph::SCC &C) {
return any_of(C,
[](const LazyCallGraph::Node &N) {
return isFunctionInPrintList(N.getName());
}) ||
isFunctionInPrintList("*");
}
bool shouldPrintIR(Any IR) {
if (any_isa<const Module *>(IR)) {
const Module *M = any_cast<const Module *>(IR);
return moduleContainsFilterPrintFunc(*M);
}
if (any_isa<const Function *>(IR)) {
const Function *F = any_cast<const Function *>(IR);
return isFunctionInPrintList(F->getName());
}
if (any_isa<const LazyCallGraph::SCC *>(IR)) {
const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
return sccContainsFilterPrintFunc(*C);
}
if (any_isa<const Loop *>(IR)) {
const Loop *L = any_cast<const Loop *>(IR);
return isFunctionInPrintList(L->getHeader()->getParent()->getName());
}
llvm_unreachable("Unknown wrapped IR type");
}
/// Generic IR-printing helper that unpacks a pointer to IRUnit wrapped into
/// llvm::Any and does actual print job.
void unwrapAndPrint(raw_ostream &OS, Any IR) {
if (!shouldPrintIR(IR))
return;
if (forcePrintModuleIR()) {
auto *M = unwrapModule(IR);
assert(M && "should have unwrapped module");
printIR(OS, M);
return;
}
if (any_isa<const Module *>(IR)) {
const Module *M = any_cast<const Module *>(IR);
printIR(OS, M);
return;
}
if (any_isa<const Function *>(IR)) {
const Function *F = any_cast<const Function *>(IR);
printIR(OS, F);
return;
}
if (any_isa<const LazyCallGraph::SCC *>(IR)) {
const LazyCallGraph::SCC *C = any_cast<const LazyCallGraph::SCC *>(IR);
printIR(OS, C);
return;
}
if (any_isa<const Loop *>(IR)) {
const Loop *L = any_cast<const Loop *>(IR);
printIR(OS, L);
return;
}
llvm_unreachable("Unknown wrapped IR type");
}
// Return true when this is a pass for which changes should be ignored
bool isIgnored(StringRef PassID) {
return isSpecialPass(PassID,
{"PassManager", "PassAdaptor", "AnalysisManagerProxy",
"DevirtSCCRepeatedPass", "ModuleInlinerWrapperPass"});
}
std::string makeHTMLReady(StringRef SR) {
std::string S;
while (true) {
StringRef Clean =
SR.take_until([](char C) { return C == '<' || C == '>'; });
S.append(Clean.str());
SR = SR.drop_front(Clean.size());
if (SR.size() == 0)
return S;
S.append(SR[0] == '<' ? "<" : ">");
SR = SR.drop_front();
}
llvm_unreachable("problems converting string to HTML");
}
// Return the module when that is the appropriate level of comparison for \p IR.
const Module *getModuleForComparison(Any IR) {
if (any_isa<const Module *>(IR))
return any_cast<const Module *>(IR);
if (any_isa<const LazyCallGraph::SCC *>(IR))
return any_cast<const LazyCallGraph::SCC *>(IR)
->begin()
->getFunction()
.getParent();
return nullptr;
}
} // namespace
template <typename T> ChangeReporter<T>::~ChangeReporter() {
assert(BeforeStack.empty() && "Problem with Change Printer stack.");
}
template <typename T>
bool ChangeReporter<T>::isInterestingFunction(const Function &F) {
return isFunctionInPrintList(F.getName());
}
template <typename T>
bool ChangeReporter<T>::isInterestingPass(StringRef PassID) {
if (isIgnored(PassID))
return false;
static std::unordered_set<std::string> PrintPassNames(PrintPassesList.begin(),
PrintPassesList.end());
return PrintPassNames.empty() || PrintPassNames.count(PassID.str());
}
// Return true when this is a pass on IR for which printing
// of changes is desired.
template <typename T>
bool ChangeReporter<T>::isInteresting(Any IR, StringRef PassID) {
if (!isInterestingPass(PassID))
return false;
if (any_isa<const Function *>(IR))
return isInterestingFunction(*any_cast<const Function *>(IR));
return true;
}
template <typename T>
void ChangeReporter<T>::saveIRBeforePass(Any IR, StringRef PassID) {
// Always need to place something on the stack because invalidated passes
// are not given the IR so it cannot be determined whether the pass was for
// something that was filtered out.
BeforeStack.emplace_back();
if (!isInteresting(IR, PassID))
return;
// Is this the initial IR?
if (InitialIR) {
InitialIR = false;
if (VerboseMode)
handleInitialIR(IR);
}
// Save the IR representation on the stack.
T &Data = BeforeStack.back();
generateIRRepresentation(IR, PassID, Data);
}
template <typename T>
void ChangeReporter<T>::handleIRAfterPass(Any IR, StringRef PassID) {
assert(!BeforeStack.empty() && "Unexpected empty stack encountered.");
std::string Name = getIRName(IR);
if (isIgnored(PassID)) {
if (VerboseMode)
handleIgnored(PassID, Name);
} else if (!isInteresting(IR, PassID)) {
if (VerboseMode)
handleFiltered(PassID, Name);
} else {
// Get the before rep from the stack
T &Before = BeforeStack.back();
// Create the after rep
T After;
generateIRRepresentation(IR, PassID, After);
// Was there a change in IR?
if (Before == After) {
if (VerboseMode)
omitAfter(PassID, Name);
} else
handleAfter(PassID, Name, Before, After, IR);
}
BeforeStack.pop_back();
}
template <typename T>
void ChangeReporter<T>::handleInvalidatedPass(StringRef PassID) {
assert(!BeforeStack.empty() && "Unexpected empty stack encountered.");
// Always flag it as invalidated as we cannot determine when
// a pass for a filtered function is invalidated since we do not
// get the IR in the call. Also, the output is just alternate
// forms of the banner anyway.
if (VerboseMode)
handleInvalidated(PassID);
BeforeStack.pop_back();
}
template <typename T>
void ChangeReporter<T>::registerRequiredCallbacks(
PassInstrumentationCallbacks &PIC) {
PIC.registerBeforeNonSkippedPassCallback(
[this](StringRef P, Any IR) { saveIRBeforePass(IR, P); });
PIC.registerAfterPassCallback(
[this](StringRef P, Any IR, const PreservedAnalyses &) {
handleIRAfterPass(IR, P);
});
PIC.registerAfterPassInvalidatedCallback(
[this](StringRef P, const PreservedAnalyses &) {
handleInvalidatedPass(P);
});
}
template <typename T>
TextChangeReporter<T>::TextChangeReporter(bool Verbose)
: ChangeReporter<T>(Verbose), Out(dbgs()) {}
template <typename T> void TextChangeReporter<T>::handleInitialIR(Any IR) {
// Always print the module.
// Unwrap and print directly to avoid filtering problems in general routines.
auto *M = unwrapModule(IR, /*Force=*/true);
assert(M && "Expected module to be unwrapped when forced.");
Out << "*** IR Dump At Start ***\n";
M->print(Out, nullptr);
}
template <typename T>
void TextChangeReporter<T>::omitAfter(StringRef PassID, std::string &Name) {
Out << formatv("*** IR Dump After {0} on {1} omitted because no change ***\n",
PassID, Name);
}
template <typename T>
void TextChangeReporter<T>::handleInvalidated(StringRef PassID) {
Out << formatv("*** IR Pass {0} invalidated ***\n", PassID);
}
template <typename T>
void TextChangeReporter<T>::handleFiltered(StringRef PassID,
std::string &Name) {
SmallString<20> Banner =
formatv("*** IR Dump After {0} on {1} filtered out ***\n", PassID, Name);
Out << Banner;
}
template <typename T>
void TextChangeReporter<T>::handleIgnored(StringRef PassID, std::string &Name) {
Out << formatv("*** IR Pass {0} on {1} ignored ***\n", PassID, Name);
}
IRChangedPrinter::~IRChangedPrinter() = default;
void IRChangedPrinter::registerCallbacks(PassInstrumentationCallbacks &PIC) {
if (PrintChanged == ChangePrinter::PrintChangedVerbose ||
PrintChanged == ChangePrinter::PrintChangedQuiet)
TextChangeReporter<std::string>::registerRequiredCallbacks(PIC);
}
void IRChangedPrinter::generateIRRepresentation(Any IR, StringRef PassID,
std::string &Output) {
raw_string_ostream OS(Output);
unwrapAndPrint(OS, IR);
OS.str();
}
void IRChangedPrinter::handleAfter(StringRef PassID, std::string &Name,
const std::string &Before,
const std::string &After, Any) {
// Report the IR before the changes when requested.
if (PrintChangedBefore)
Out << "*** IR Dump Before " << PassID << " on " << Name << " ***\n"
<< Before;
// We might not get anything to print if we only want to print a specific
// function but it gets deleted.
if (After.empty()) {
Out << "*** IR Deleted After " << PassID << " on " << Name << " ***\n";
return;
}
Out << "*** IR Dump After " << PassID << " on " << Name << " ***\n" << After;
}
template <typename T>
void OrderedChangedData<T>::report(
const OrderedChangedData &Before, const OrderedChangedData &After,
function_ref<void(const T *, const T *)> HandlePair) {
const auto &BFD = Before.getData();
const auto &AFD = After.getData();
std::vector<std::string>::const_iterator BI = Before.getOrder().begin();
std::vector<std::string>::const_iterator BE = Before.getOrder().end();
std::vector<std::string>::const_iterator AI = After.getOrder().begin();
std::vector<std::string>::const_iterator AE = After.getOrder().end();
auto HandlePotentiallyRemovedData = [&](std::string S) {
// The order in LLVM may have changed so check if still exists.
if (!AFD.count(S)) {
// This has been removed.
HandlePair(&BFD.find(*BI)->getValue(), nullptr);
}
};
auto HandleNewData = [&](std::vector<const T *> &Q) {
// Print out any queued up new sections
for (const T *NBI : Q)
HandlePair(nullptr, NBI);
Q.clear();
};
// Print out the data in the after order, with before ones interspersed
// appropriately (ie, somewhere near where they were in the before list).
// Start at the beginning of both lists. Loop through the
// after list. If an element is common, then advance in the before list
// reporting the removed ones until the common one is reached. Report any
// queued up new ones and then report the common one. If an element is not
// common, then enqueue it for reporting. When the after list is exhausted,
// loop through the before list, reporting any removed ones. Finally,
// report the rest of the enqueued new ones.
std::vector<const T *> NewDataQueue;
while (AI != AE) {
if (!BFD.count(*AI)) {
// This section is new so place it in the queue. This will cause it
// to be reported after deleted sections.
NewDataQueue.emplace_back(&AFD.find(*AI)->getValue());
++AI;
continue;
}
// This section is in both; advance and print out any before-only
// until we get to it.
while (*BI != *AI) {
HandlePotentiallyRemovedData(*BI);
++BI;
}
// Report any new sections that were queued up and waiting.
HandleNewData(NewDataQueue);
const T &AData = AFD.find(*AI)->getValue();
const T &BData = BFD.find(*AI)->getValue();
HandlePair(&BData, &AData);
++BI;
++AI;
}
// Check any remaining before sections to see if they have been removed
while (BI != BE) {
HandlePotentiallyRemovedData(*BI);
++BI;
}
HandleNewData(NewDataQueue);
}
template <typename T>
void IRComparer<T>::compare(
bool CompareModule,
std::function<void(bool InModule, unsigned Minor,
const FuncDataT<T> &Before, const FuncDataT<T> &After)>
CompareFunc) {
if (!CompareModule) {
// Just handle the single function.
assert(Before.getData().size() == 1 && After.getData().size() == 1 &&
"Expected only one function.");
CompareFunc(false, 0, Before.getData().begin()->getValue(),
After.getData().begin()->getValue());
return;
}
unsigned Minor = 0;
FuncDataT<T> Missing("");
IRDataT<T>::report(Before, After,
[&](const FuncDataT<T> *B, const FuncDataT<T> *A) {
assert((B || A) && "Both functions cannot be missing.");
if (!B)
B = &Missing;
else if (!A)
A = &Missing;
CompareFunc(true, Minor++, *B, *A);
});
}
template <typename T> void IRComparer<T>::analyzeIR(Any IR, IRDataT<T> &Data) {
if (const Module *M = getModuleForComparison(IR)) {
// Create data for each existing/interesting function in the module.
for (const Function &F : *M)
generateFunctionData(Data, F);
return;
}
const Function *F = nullptr;
if (any_isa<const Function *>(IR))
F = any_cast<const Function *>(IR);
else {
assert(any_isa<const Loop *>(IR) && "Unknown IR unit.");
const Loop *L = any_cast<const Loop *>(IR);
F = L->getHeader()->getParent();
}
assert(F && "Unknown IR unit.");
generateFunctionData(Data, *F);
}
template <typename T>
bool IRComparer<T>::generateFunctionData(IRDataT<T> &Data, const Function &F) {
if (!F.isDeclaration() && isFunctionInPrintList(F.getName())) {
FuncDataT<T> FD(F.getEntryBlock().getName().str());
for (const auto &B : F) {
FD.getOrder().emplace_back(B.getName());
FD.getData().insert({B.getName(), B});
}
Data.getOrder().emplace_back(F.getName());
Data.getData().insert({F.getName(), FD});
return true;
}
return false;
}
PrintIRInstrumentation::~PrintIRInstrumentation() {
assert(ModuleDescStack.empty() && "ModuleDescStack is not empty at exit");
}
void PrintIRInstrumentation::pushModuleDesc(StringRef PassID, Any IR) {
const Module *M = unwrapModule(IR);
ModuleDescStack.emplace_back(M, getIRName(IR), PassID);
}
PrintIRInstrumentation::PrintModuleDesc
PrintIRInstrumentation::popModuleDesc(StringRef PassID) {
assert(!ModuleDescStack.empty() && "empty ModuleDescStack");
PrintModuleDesc ModuleDesc = ModuleDescStack.pop_back_val();
assert(std::get<2>(ModuleDesc).equals(PassID) && "malformed ModuleDescStack");
return ModuleDesc;
}
void PrintIRInstrumentation::printBeforePass(StringRef PassID, Any IR) {
if (isIgnored(PassID))
return;
// Saving Module for AfterPassInvalidated operations.
// Note: here we rely on a fact that we do not change modules while
// traversing the pipeline, so the latest captured module is good
// for all print operations that has not happen yet.
if (shouldPrintAfterPass(PassID))
pushModuleDesc(PassID, IR);
if (!shouldPrintBeforePass(PassID))
return;
if (!shouldPrintIR(IR))
return;
dbgs() << "*** IR Dump Before " << PassID << " on " << getIRName(IR)
<< " ***\n";
unwrapAndPrint(dbgs(), IR);
}
void PrintIRInstrumentation::printAfterPass(StringRef PassID, Any IR) {
if (isIgnored(PassID))
return;
if (!shouldPrintAfterPass(PassID))
return;
const Module *M;
std::string IRName;
StringRef StoredPassID;
std::tie(M, IRName, StoredPassID) = popModuleDesc(PassID);
assert(StoredPassID == PassID && "mismatched PassID");
if (!shouldPrintIR(IR))
return;
dbgs() << "*** IR Dump After " << PassID << " on " << IRName << " ***\n";
unwrapAndPrint(dbgs(), IR);
}
void PrintIRInstrumentation::printAfterPassInvalidated(StringRef PassID) {
StringRef PassName = PIC->getPassNameForClassName(PassID);
if (!shouldPrintAfterPass(PassName))
return;
if (isIgnored(PassID))
return;
const Module *M;
std::string IRName;
StringRef StoredPassID;
std::tie(M, IRName, StoredPassID) = popModuleDesc(PassID);
assert(StoredPassID == PassID && "mismatched PassID");
// Additional filtering (e.g. -filter-print-func) can lead to module
// printing being skipped.
if (!M)
return;
SmallString<20> Banner =
formatv("*** IR Dump After {0} on {1} (invalidated) ***", PassID, IRName);
dbgs() << Banner << "\n";
printIR(dbgs(), M);
}
bool PrintIRInstrumentation::shouldPrintBeforePass(StringRef PassID) {
if (shouldPrintBeforeAll())
return true;
StringRef PassName = PIC->getPassNameForClassName(PassID);
return is_contained(printBeforePasses(), PassName);
}
bool PrintIRInstrumentation::shouldPrintAfterPass(StringRef PassID) {
if (shouldPrintAfterAll())
return true;
StringRef PassName = PIC->getPassNameForClassName(PassID);
return is_contained(printAfterPasses(), PassName);
}
void PrintIRInstrumentation::registerCallbacks(
PassInstrumentationCallbacks &PIC) {
this->PIC = &PIC;
// BeforePass callback is not just for printing, it also saves a Module
// for later use in AfterPassInvalidated.
if (shouldPrintBeforeSomePass() || shouldPrintAfterSomePass())
PIC.registerBeforeNonSkippedPassCallback(
[this](StringRef P, Any IR) { this->printBeforePass(P, IR); });
if (shouldPrintAfterSomePass()) {
PIC.registerAfterPassCallback(
[this](StringRef P, Any IR, const PreservedAnalyses &) {
this->printAfterPass(P, IR);
});
PIC.registerAfterPassInvalidatedCallback(
[this](StringRef P, const PreservedAnalyses &) {
this->printAfterPassInvalidated(P);
});
}
}
void OptNoneInstrumentation::registerCallbacks(
PassInstrumentationCallbacks &PIC) {
PIC.registerShouldRunOptionalPassCallback(
[this](StringRef P, Any IR) { return this->shouldRun(P, IR); });
}
bool OptNoneInstrumentation::shouldRun(StringRef PassID, Any IR) {
const Function *F = nullptr;
if (any_isa<const Function *>(IR)) {
F = any_cast<const Function *>(IR);
} else if (any_isa<const Loop *>(IR)) {
F = any_cast<const Loop *>(IR)->getHeader()->getParent();
}
bool ShouldRun = !(F && F->hasOptNone());
if (!ShouldRun && DebugLogging) {
errs() << "Skipping pass " << PassID << " on " << F->getName()
<< " due to optnone attribute\n";
}
return ShouldRun;
}
void OptBisectInstrumentation::registerCallbacks(
PassInstrumentationCallbacks &PIC) {
if (!OptBisector->isEnabled())
return;
PIC.registerShouldRunOptionalPassCallback([](StringRef PassID, Any IR) {
return isIgnored(PassID) || OptBisector->checkPass(PassID, getIRName(IR));
});
}
raw_ostream &PrintPassInstrumentation::print() {
if (Opts.Indent) {
assert(Indent >= 0);
dbgs().indent(Indent);
}
return dbgs();
}
void PrintPassInstrumentation::registerCallbacks(
PassInstrumentationCallbacks &PIC) {
if (!Enabled)
return;
std::vector<StringRef> SpecialPasses;
if (!Opts.Verbose) {
SpecialPasses.emplace_back("PassManager");
SpecialPasses.emplace_back("PassAdaptor");
}
PIC.registerBeforeSkippedPassCallback([this, SpecialPasses](StringRef PassID,
Any IR) {
assert(!isSpecialPass(PassID, SpecialPasses) &&
"Unexpectedly skipping special pass");
print() << "Skipping pass: " << PassID << " on " << getIRName(IR) << "\n";
});
PIC.registerBeforeNonSkippedPassCallback([this, SpecialPasses](
StringRef PassID, Any IR) {
if (isSpecialPass(PassID, SpecialPasses))
return;
print() << "Running pass: " << PassID << " on " << getIRName(IR) << "\n";
Indent += 2;
});
PIC.registerAfterPassCallback(
[this, SpecialPasses](StringRef PassID, Any IR,
const PreservedAnalyses &) {
if (isSpecialPass(PassID, SpecialPasses))
return;
Indent -= 2;
});
PIC.registerAfterPassInvalidatedCallback(
[this, SpecialPasses](StringRef PassID, Any IR) {
if (isSpecialPass(PassID, SpecialPasses))
return;
Indent -= 2;
});
if (!Opts.SkipAnalyses) {
PIC.registerBeforeAnalysisCallback([this](StringRef PassID, Any IR) {
print() << "Running analysis: " << PassID << " on " << getIRName(IR)
<< "\n";
Indent += 2;
});
PIC.registerAfterAnalysisCallback(
[this](StringRef PassID, Any IR) { Indent -= 2; });
PIC.registerAnalysisInvalidatedCallback([this](StringRef PassID, Any IR) {
print() << "Invalidating analysis: " << PassID << " on " << getIRName(IR)
<< "\n";
});
PIC.registerAnalysesClearedCallback([this](StringRef IRName) {
print() << "Clearing all analysis results for: " << IRName << "\n";
});
}
}
PreservedCFGCheckerInstrumentation::CFG::CFG(const Function *F,
bool TrackBBLifetime) {
if (TrackBBLifetime)
BBGuards = DenseMap<intptr_t, BBGuard>(F->size());
for (const auto &BB : *F) {
if (BBGuards)
BBGuards->try_emplace(intptr_t(&BB), &BB);
for (auto *Succ : successors(&BB)) {
Graph[&BB][Succ]++;
if (BBGuards)
BBGuards->try_emplace(intptr_t(Succ), Succ);
}
}
}
static void printBBName(raw_ostream &out, const BasicBlock *BB) {
if (BB->hasName()) {
out << BB->getName() << "<" << BB << ">";
return;
}
if (!BB->getParent()) {
out << "unnamed_removed<" << BB << ">";
return;
}
if (BB->isEntryBlock()) {
out << "entry"