LLVM 23.0.0git
PrintPasses.cpp
Go to the documentation of this file.
1//===- PrintPasses.cpp ----------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
11#include "llvm/Support/Errc.h"
16#include <unordered_set>
17
18using namespace llvm;
19
20// Print IR out before/after specified passes.
22 PrintBefore("print-before",
23 llvm::cl::desc("Print IR before specified passes"),
25
27 PrintAfter("print-after", llvm::cl::desc("Print IR after specified passes"),
29
30static cl::opt<bool> PrintBeforeAll("print-before-all",
31 llvm::cl::desc("Print IR before each pass"),
32 cl::init(false), cl::Hidden);
33static cl::opt<bool> PrintAfterAll("print-after-all",
34 llvm::cl::desc("Print IR after each pass"),
35 cl::init(false), cl::Hidden);
36
37// Print out the IR after passes, similar to -print-after-all except that it
38// only prints the IR after passes that change the IR. Those passes that do not
39// make changes to the IR are reported as not making any changes. In addition,
40// the initial IR is also reported. Other hidden options affect the output from
41// this option. -filter-passes will limit the output to the named passes that
42// actually change the IR and other passes are reported as filtered out. The
43// specified passes will either be reported as making no changes (with no IR
44// reported) or the changed IR will be reported. Also, the -filter-print-funcs
45// and -print-module-scope options will do similar filtering based on function
46// name, reporting changed IRs as functions(or modules if -print-module-scope is
47// specified) for a particular function or indicating that the IR has been
48// filtered out. The extra options can be combined, allowing only changed IRs
49// for certain passes on certain functions to be reported in different formats,
50// with the rest being reported as filtered out. The -print-before-changed
51// option will print the IR as it was before each pass that changed it. The
52// optional value of quiet will only report when the IR changes, suppressing all
53// other messages, including the initial IR. The values "diff" and "diff-quiet"
54// will present the changes in a form similar to a patch, in either verbose or
55// quiet mode, respectively. The lines that are removed and added are prefixed
56// with '-' and '+', respectively. The -filter-print-funcs and -filter-passes
57// can be used to filter the output. This reporter relies on the linux diff
58// utility to do comparisons and insert the prefixes. For systems that do not
59// have the necessary facilities, the error message will be shown in place of
60// the expected output.
62 "print-changed", cl::desc("Print changed IRs"), cl::Hidden,
65 clEnumValN(ChangePrinter::Quiet, "quiet", "Run in quiet mode"),
67 "Display patch-like changes"),
69 "Display patch-like changes in quiet mode"),
71 "Display patch-like changes with color"),
73 "Display patch-like changes in quiet mode with color"),
75 "Create a website with graphical changes"),
77 "Create a website with graphical changes in quiet mode"),
78 // Sentinel value for unspecified option.
80
81// An option for specifying the diff used by print-changed=[diff | diff-quiet]
83 DiffBinary("print-changed-diff-path", cl::Hidden, cl::init("diff"),
84 cl::desc("system diff used by change reporters"));
85
86static cl::opt<bool>
87 PrintModuleScope("print-module-scope",
88 cl::desc("When printing IR for print-[before|after]{-all} "
89 "always print a module IR"),
90 cl::init(false), cl::Hidden);
91
93 "print-loop-func-scope",
94 cl::desc("When printing IR for print-[before|after]{-all} "
95 "for a loop pass, always print function IR"),
96 cl::init(false), cl::Hidden);
97
98// See the description for -print-changed for an explanation of the use
99// of this option.
101 "filter-passes", cl::value_desc("pass names"),
102 cl::desc("Only consider IR changes for passes whose names "
103 "match the specified value. No-op without -print-changed"),
105
107 PrintFuncsList("filter-print-funcs", cl::value_desc("function names"),
108 cl::desc("Only print IR for functions whose name "
109 "match this for all print-[before|after][-all] "
110 "options"),
112
113/// This is a helper to determine whether to print IR before or
114/// after a pass.
115
117 return PrintBeforeAll || !PrintBefore.empty();
118}
119
121 return PrintAfterAll || !PrintAfter.empty();
122}
123
125 ArrayRef<std::string> PassesToPrint) {
126 return llvm::is_contained(PassesToPrint, PassID);
127}
128
130
132
136
140
141std::vector<std::string> llvm::printBeforePasses() {
142 return std::vector<std::string>(PrintBefore);
143}
144
145std::vector<std::string> llvm::printAfterPasses() {
146 return std::vector<std::string>(PrintAfter);
147}
148
150
152
154 static std::unordered_set<std::string> Set(FilterPasses.begin(),
155 FilterPasses.end());
156 return Set.empty() || Set.count(std::string(PassName));
157}
158
159bool llvm::isFilterPassesEmpty() { return FilterPasses.empty(); }
160
162 static std::unordered_set<std::string> PrintFuncNames(PrintFuncsList.begin(),
163 PrintFuncsList.end());
164 return PrintFuncNames.empty() ||
165 PrintFuncNames.count(std::string(FunctionName));
166}
167
169 unsigned N) {
170 std::error_code RC;
171 for (unsigned I = 0; I < N; ++I) {
172 std::error_code EC = sys::fs::remove(FileName[I]);
173 if (EC)
174 RC = EC;
175 }
176 return RC;
177}
178
181 SmallVector<std::string> &FileName) {
182 assert(FD.size() >= SR.size() && FileName.size() == FD.size() &&
183 "Unexpected array sizes");
184 std::error_code EC;
185 unsigned I = 0;
186 for (; I < FD.size(); ++I) {
187 if (FD[I] == -1) {
189 EC = sys::fs::createTemporaryFile("tmpfile", "txt", FD[I], SV);
190 if (EC)
191 break;
192 FileName[I] = Twine(SV).str();
193 }
194 if (I < SR.size()) {
195 EC = sys::fs::openFileForWrite(FileName[I], FD[I]);
196 if (EC)
197 break;
198 raw_fd_ostream OutStream(FD[I], /*shouldClose=*/true);
199 if (FD[I] == -1) {
201 break;
202 }
203 OutStream << SR[I];
204 }
205 }
206 if (EC && I > 0)
207 // clean up created temporary files
208 cleanUpTempFilesImpl(FileName, I);
209 return EC;
210}
211
213 return cleanUpTempFilesImpl(FileName, FileName.size());
214}
215
216std::string llvm::doSystemDiff(StringRef Before, StringRef After,
217 StringRef OldLineFormat, StringRef NewLineFormat,
218 StringRef UnchangedLineFormat) {
219 auto BypassSandbox = sys::sandbox::scopedDisable();
220
221 // Store the 2 bodies into temporary files and call diff on them
222 // to get the body of the node.
223 static SmallVector<int> FD{-1, -1, -1};
224 SmallVector<StringRef> SR{Before, After};
225 static SmallVector<std::string> FileName{"", "", ""};
226 if (prepareTempFiles(FD, SR, FileName))
227 return "Unable to create temporary file.";
228
230 if (!DiffExe)
231 return "Unable to find diff executable.";
232
233 SmallString<128> OLF, NLF, ULF;
234 ("--old-line-format=" + OldLineFormat).toVector(OLF);
235 ("--new-line-format=" + NewLineFormat).toVector(NLF);
236 ("--unchanged-line-format=" + UnchangedLineFormat).toVector(ULF);
237
238 StringRef Args[] = {DiffBinary, "-w", "-d", OLF,
239 NLF, ULF, FileName[0], FileName[1]};
240 std::optional<StringRef> Redirects[] = {std::nullopt, StringRef(FileName[2]),
241 std::nullopt};
242 int Result = sys::ExecuteAndWait(*DiffExe, Args, std::nullopt, Redirects);
243 if (Result < 0)
244 return "Error executing system diff.";
245 std::string Diff;
246 auto B = MemoryBuffer::getFile(FileName[2]);
247 if (B && *B)
248 Diff = (*B)->getBuffer().str();
249 else
250 return "Unable to read result.";
251
252 if (cleanUpTempFiles(FileName))
253 return "Unable to remove temporary file.";
254
255 return Diff;
256}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
#define I(x, y, z)
Definition MD5.cpp:57
static bool shouldPrintBeforeOrAfterPass(StringRef PassID, ArrayRef< std::string > PassesToPrint)
static cl::opt< bool > PrintBeforeAll("print-before-all", llvm::cl::desc("Print IR before each pass"), cl::init(false), cl::Hidden)
static cl::opt< bool > PrintModuleScope("print-module-scope", cl::desc("When printing IR for print-[before|after]{-all} " "always print a module IR"), cl::init(false), cl::Hidden)
static cl::list< std::string > PrintBefore("print-before", llvm::cl::desc("Print IR before specified passes"), cl::CommaSeparated, cl::Hidden)
static cl::list< std::string > FilterPasses("filter-passes", cl::value_desc("pass names"), cl::desc("Only consider IR changes for passes whose names " "match the specified value. No-op without -print-changed"), cl::CommaSeparated, cl::Hidden)
static cl::list< std::string > PrintAfter("print-after", llvm::cl::desc("Print IR after specified passes"), cl::CommaSeparated, cl::Hidden)
static cl::opt< bool > LoopPrintFuncScope("print-loop-func-scope", cl::desc("When printing IR for print-[before|after]{-all} " "for a loop pass, always print function IR"), cl::init(false), cl::Hidden)
static cl::opt< bool > PrintAfterAll("print-after-all", llvm::cl::desc("Print IR after each pass"), cl::init(false), cl::Hidden)
static cl::opt< std::string > DiffBinary("print-changed-diff-path", cl::Hidden, cl::init("diff"), cl::desc("system diff used by change reporters"))
std::error_code cleanUpTempFilesImpl(ArrayRef< std::string > FileName, unsigned N)
static cl::list< std::string > PrintFuncsList("filter-print-funcs", cl::value_desc("function names"), cl::desc("Only print IR for functions whose name " "match this for all print-[before|after][-all] " "options"), cl::CommaSeparated, cl::Hidden)
static const char PassName[]
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
Get the array size.
Definition ArrayRef.h:141
Represents either an error or a value T.
Definition ErrorOr.h:56
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
LLVM_ABI std::string str() const
Return the twine contents as a std::string.
Definition Twine.cpp:17
A raw_ostream that writes to a file descriptor.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
LLVM_ABI std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
std::error_code openFileForWrite(const Twine &Name, int &ResultFD, CreationDisposition Disp=CD_CreateAlways, OpenFlags Flags=OF_None, unsigned Mode=0666)
Opens the file with the given name in a write-only or read-write mode, returning its open file descri...
LLVM_ABI std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD, SmallVectorImpl< char > &ResultPath, OpenFlags Flags=OF_None)
Create a file in the system temporary directory.
Definition Path.cpp:926
ScopedSetting scopedDisable()
Definition IOSandbox.h:36
LLVM_ABI ErrorOr< std::string > findProgramByName(StringRef Name, ArrayRef< StringRef > Paths={})
Find the first executable file Name in Paths.
LLVM_ABI int ExecuteAndWait(StringRef Program, ArrayRef< StringRef > Args, std::optional< ArrayRef< StringRef > > Env=std::nullopt, ArrayRef< std::optional< StringRef > > Redirects={}, unsigned SecondsToWait=0, unsigned MemoryLimit=0, std::string *ErrMsg=nullptr, bool *ExecutionFailed=nullptr, std::optional< ProcessStatistics > *ProcStat=nullptr, BitVector *AffinityMask=nullptr)
This function executes the program using the arguments provided.
Definition Program.cpp:32
This is an optimization pass for GlobalISel generic memory operations.
std::error_code prepareTempFiles(SmallVector< int > &FD, ArrayRef< StringRef > SR, SmallVector< std::string > &FileName)
bool forcePrintModuleIR()
std::error_code make_error_code(BitcodeError E)
std::vector< std::string > printAfterPasses()
bool shouldPrintBeforeAll()
bool shouldPrintAfterAll()
cl::opt< ChangePrinter > PrintChanged
@ io_error
Definition Errc.h:58
std::vector< std::string > printBeforePasses()
bool shouldPrintBeforeSomePass()
This is a helper to determine whether to print IR before or after a pass.
bool shouldPrintAfterSomePass()
bool isFunctionInPrintList(StringRef FunctionName)
bool isPassInPrintList(StringRef PassName)
std::error_code cleanUpTempFiles(ArrayRef< std::string > FileName)
std::string doSystemDiff(StringRef Before, StringRef After, StringRef OldLineFormat, StringRef NewLineFormat, StringRef UnchangedLineFormat)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1946
bool shouldPrintBeforePass(StringRef PassID)
bool shouldPrintAfterPass(StringRef PassID)
bool isFilterPassesEmpty()
bool forcePrintFuncIR()
#define N