LLVM 24.0.0git
Main.cpp
Go to the documentation of this file.
1//===- Main.cpp - Top-Level TableGen implementation -----------------------===//
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//
9// TableGen is a tool which can be used to build up a description of something,
10// then invoke one or more "tablegen backends" to emit information about the
11// description in some predefined format. In practice, this is used by the LLVM
12// code generators to automate generation of a code generator through a
13// high-level description of the target.
14//
15//===----------------------------------------------------------------------===//
16
17#include "llvm/TableGen/Main.h"
18#include "TGLexer.h"
19#include "TGParser.h"
20#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/Twine.h"
26#include "llvm/Support/Path.h"
27#include "llvm/Support/SMLoc.h"
32#include "llvm/TableGen/Error.h"
36#include <memory>
37#include <string>
38#include <system_error>
39#include <utility>
40using namespace llvm;
41
43OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"),
44 cl::init("-"));
45
48 cl::desc("Dependency filename"),
49 cl::value_desc("filename"),
50 cl::init(""));
51
54
56IncludeDirs("I", cl::desc("Directory of include files"),
57 cl::value_desc("directory"), cl::Prefix);
58
60MacroNames("D", cl::desc("Name of the macro to be defined"),
61 cl::value_desc("macro name"), cl::Prefix);
62
63static cl::opt<bool>
64WriteIfChanged("write-if-changed", cl::desc("Only write output if it changed"));
65
66static cl::opt<bool>
67TimePhases("time-phases", cl::desc("Time phases of parser and backend"));
68
70 "long-string-literals",
71 cl::desc("when emitting large string tables, prefer string literals over "
72 "comma-separated char literals. This can be a readability and "
73 "compile-time performance win, but upsets some compilers"),
74 cl::Hidden, cl::init(true));
75
77 "no-warn-on-unused-template-args",
78 cl::desc("Disable unused template argument warnings."));
79
80static cl::opt<bool> Preprocess("E", cl::desc("Write preprocessed output"));
81
82static int reportError(const char *ProgName, Twine Msg) {
83 errs() << ProgName << ": " << Msg;
84 errs().flush();
85 return 1;
86}
87
88namespace {
89/// Encapsulate file, line and column numbers from SourceMgr.
90struct SMCoords {
91 unsigned Buf = 0;
92 unsigned Line = 0;
93 unsigned Col = 0;
94 SMCoords() = default;
95 SMCoords(const SourceMgr &Mgr, SMLoc Loc) {
96 Buf = Mgr.FindBufferContainingLoc(Loc);
97 // TODO: Find a faster way to do this. For example we don't need the column
98 // number for every token, only the first token on each output line.
99 std::tie(Line, Col) = Mgr.getLineAndColumn(Loc, Buf);
100 }
101};
102} // end anonymous namespace
103
104/// Create preprocessed output for `-E` option.
105static int preprocessInput(TGLexer &Lex, raw_ostream &OS) {
106 SMCoords Last;
107 while (true) {
108 Lex.Lex();
109 if (Lex.getCode() == tgtok::Eof || Lex.getCode() == tgtok::Error)
110 break;
111 SMCoords This(SrcMgr, Lex.getLoc());
112 if (This.Buf == Last.Buf && This.Line == Last.Line) {
113 // Add a single space between tokens on the same line. This is overkill in
114 // many cases but at least it will parse correctly.
115 OS << ' ';
116 } else {
117 // Always start a new line when including a new file or popping back out
118 // to the previous file. This is just a heuristic to make the output look
119 // reasonably pretty.
120 if (Last.Buf)
121 OS << '\n';
122 // Indent the first token on a line to its original indentation, to make
123 // the output look pretty.
124 OS.indent(This.Col - 1);
125 }
126
127 const char *Start = Lex.getLoc().getPointer();
128 const char *End = Lex.getLocRange().End.getPointer();
129 StringRef Text(Start, End - Start);
130 OS << Text;
131
132 Last = This;
133 // A code block is the only kind of token that can span multiple lines.
134 // Record the line it ends on, so that a following token on that line stays
135 // on the same output line. Count '\n' characters to match how SourceMgr
136 // counts lines.
137 if (Lex.getCode() == tgtok::CodeFragment)
138 Last.Line += Text.count('\n');
139 }
140 if (Last.Buf != 0)
141 OS << '\n';
142 return Lex.getCode() == tgtok::Error;
143}
144
145/// Create a dependency file for `-d` option.
146///
147/// This functionality is really only for the benefit of the build system.
148/// It is similar to GCC's `-M*` family of options.
150 const char *argv0) {
151 if (OutputFilename == "-")
152 return reportError(argv0, "the option -d must be used together with -o\n");
153
154 std::error_code EC;
156 if (EC)
157 return reportError(argv0, "error opening " + DependFilename + ":" +
158 EC.message() + "\n");
159 DepOut.os() << OutputFilename << ":";
160
161 // Emit the primary input file as a dependency. This matches C compilers like
162 // Clang and GCC. Without it, a .td file with no `include` directives would
163 // produce a depfile listing zero dependencies. CMake's
164 // `cmake_transform_depfile` then collapses that to a 0-byte file, which Ninja
165 // treats as a missing depfile and re-runs the rule on every incremental
166 // build.
167 if (InputFilename != "-")
168 DepOut.os() << ' ' << InputFilename;
169
170 for (const auto &Dep : Dependencies) {
171 DepOut.os() << ' ' << Dep;
172 }
173 DepOut.os() << "\n";
174 DepOut.keep();
175 return 0;
176}
177
178static int WriteOutput(const char *argv0, StringRef Filename,
179 StringRef Content) {
180 if (WriteIfChanged) {
181 // Only updates the real output file if there are any differences.
182 // This prevents recompilation of all the files depending on it if there
183 // aren't any.
184 if (auto ExistingOrErr = MemoryBuffer::getFile(Filename, /*IsText=*/true))
185 if (std::move(ExistingOrErr.get())->getBuffer() == Content)
186 return 0;
187 }
188 std::error_code EC;
189 // On z/OS, text files default to IBM-1047, but generated files are UTF-8.
190 // OF_ForceUTF8 has no effect on other platforms.
191 ToolOutputFile OutFile(Filename, EC,
193 if (EC)
194 return reportError(argv0, "error opening " + Filename + ": " +
195 EC.message() + "\n");
196 OutFile.os() << Content;
197 if (ErrorsPrinted == 0)
198 OutFile.keep();
199
200 return 0;
201}
202
203int llvm::TableGenMain(const char *argv0, MultiFileTableGenMainFn MainFn) {
206 if (std::error_code EC = FileOrErr.getError())
207 return reportError(argv0, "Could not open input file '" + InputFilename +
208 "': " + EC.message() + "\n");
209
210 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
211 SrcMgr.AddNewSourceBuffer(std::move(*FileOrErr), SMLoc());
212
213 // Record the location of the include directory so that the lexer can find
214 // it later.
215 SrcMgr.setIncludeDirs(IncludeDirs);
216 SrcMgr.setVirtualFileSystem(vfs::getRealFileSystem());
217
218 if (Preprocess) {
220 std::string OutString;
221 raw_string_ostream Out(OutString);
222 if (int Ret = preprocessInput(Lex, Out))
223 return Ret;
224 // Return early if the lexer printed errors but still reached EOF (e.g., a
225 // NUL character in the source).
226 if (ErrorsPrinted > 0)
227 return reportError(argv0, Twine(ErrorsPrinted) + " errors.\n");
228 if (!DependFilename.empty()) {
229 if (int Ret = createDependencyFile(Lex.getDependencies(), argv0))
230 return Ret;
231 }
232 return WriteOutput(argv0, OutputFilename, OutString);
233 }
234
235 RecordKeeper Records;
236 Records.saveInputFilename(InputFilename);
237
238 TGTimer &Timer = Records.getTimer();
239 if (TimePhases)
240 Timer.startPhaseTiming();
241
242 // Parse the input file.
243
244 Timer.startTimer("Parse, build records");
245
247
248 if (Parser.ParseFile())
249 return 1;
251
252 // Return early if any other errors were generated during parsing
253 // (e.g., assert failures).
254 if (ErrorsPrinted > 0)
255 return reportError(argv0, Twine(ErrorsPrinted) + " errors.\n");
256
257 // Write output to memory.
258 Timer.startBackendTimer("Backend overall");
259 TableGenOutputFiles OutFiles;
260 unsigned status = 0;
261 // ApplyCallback will return true if it did not apply any callback. In that
262 // case, attempt to apply the MainFn.
264 if (TableGen::Emitter::ApplyCallback(Records, OutFiles, FilenamePrefix))
265 status = MainFn ? MainFn(OutFiles, Records) : 1;
266 Timer.stopBackendTimer();
267 if (status)
268 return 1;
269
270 // Always write the depfile, even if the main output hasn't changed.
271 // If it's missing, Ninja considers the output dirty. If this was below
272 // the early exit below and someone deleted the .inc.d file but not the .inc
273 // file, tablegen would never write the depfile.
274 if (!DependFilename.empty()) {
275 if (int Ret = createDependencyFile(Parser.getDependencies(), argv0))
276 return Ret;
277 }
278
279 Timer.startTimer("Write output");
280 if (int Ret = WriteOutput(argv0, OutputFilename, OutFiles.MainFile))
281 return Ret;
282 for (auto [Suffix, Content] : OutFiles.AdditionalFiles) {
284 // TODO: Format using the split-file convention when writing to stdout?
285 if (Filename != "-") {
287 Filename.append(Suffix);
288 }
289 if (int Ret = WriteOutput(argv0, Filename, Content))
290 return Ret;
291 }
292
294 Timer.stopPhaseTiming();
295
296 if (ErrorsPrinted > 0)
297 return reportError(argv0, Twine(ErrorsPrinted) + " errors.\n");
298 return 0;
299}
300
301int llvm::TableGenMain(const char *argv0, TableGenMainFn MainFn) {
302 return TableGenMain(argv0, [&MainFn](TableGenOutputFiles &OutFiles,
303 const RecordKeeper &Records) {
304 std::string S;
305 raw_string_ostream OS(S);
306 int Res = MainFn(OS, Records);
307 OutFiles = {std::move(S), {}};
308 return Res;
309 });
310}
Provides ErrorOr<T> smart pointer.
static cl::opt< bool > NoWarnOnUnusedTemplateArgs("no-warn-on-unused-template-args", cl::desc("Disable unused template argument warnings."))
static cl::list< std::string > IncludeDirs("I", cl::desc("Directory of include files"), cl::value_desc("directory"), cl::Prefix)
static cl::opt< bool > WriteIfChanged("write-if-changed", cl::desc("Only write output if it changed"))
static cl::opt< std::string > DependFilename("d", cl::desc("Dependency filename"), cl::value_desc("filename"), cl::init(""))
static cl::opt< std::string > OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::init("-"))
static cl::opt< bool > TimePhases("time-phases", cl::desc("Time phases of parser and backend"))
static int preprocessInput(TGLexer &Lex, raw_ostream &OS)
Create preprocessed output for -E option.
Definition Main.cpp:105
static cl::opt< std::string > InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"))
static int createDependencyFile(const TGLexer::DependenciesSetTy &Dependencies, const char *argv0)
Create a dependency file for -d option.
Definition Main.cpp:149
static int WriteOutput(const char *argv0, StringRef Filename, StringRef Content)
Definition Main.cpp:178
static cl::list< std::string > MacroNames("D", cl::desc("Name of the macro to be defined"), cl::value_desc("macro name"), cl::Prefix)
static cl::opt< bool > Preprocess("E", cl::desc("Write preprocessed output"))
static int reportError(const char *ProgName, Twine Msg)
Definition Main.cpp:82
static constexpr StringLiteral Filename
const char * Msg
Defines the virtual file system interface vfs::FileSystem.
Represents either an error or a value T.
Definition ErrorOr.h:56
std::error_code getError() const
Definition ErrorOr.h:152
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFileOrSTDIN(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, or open stdin if the Filename is "-".
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,...
Represents a location in source code.
Definition SMLoc.h:22
constexpr const char * getPointer() const
Definition SMLoc.h:33
SMLoc End
Definition SMLoc.h:49
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
LLVM_ABI std::pair< unsigned, unsigned > getLineAndColumn(SMLoc Loc, unsigned BufferID=0) const
Find the line and column number for the specified location in the specified file.
LLVM_ABI unsigned FindBufferContainingLoc(SMLoc Loc) const
Return the ID of the buffer containing the specified location.
Definition SourceMgr.cpp:97
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TGLexer - TableGen Lexer class.
Definition TGLexer.h:194
SMRange getLocRange() const
Definition TGLexer.cpp:97
tgtok::TokKind Lex()
Definition TGLexer.h:220
tgtok::TokKind getCode() const
Definition TGLexer.h:224
SMLoc getLoc() const
Definition TGLexer.cpp:95
std::set< std::string > DependenciesSetTy
Definition TGLexer.h:211
const DependenciesSetTy & getDependencies() const
Definition TGLexer.h:222
const TGLexer::DependenciesSetTy & getDependencies() const
Definition TGParser.h:210
bool ParseFile()
ParseFile - Main entrypoint for parsing a tblgen file.
This class is used to track the amount of time spent between invocations of its startTimer()/stopTime...
Definition Timer.h:87
LLVM_ABI void stopTimer()
Stop the timer.
Definition Timer.cpp:159
LLVM_ABI void startTimer()
Start the timer running.
Definition Timer.cpp:150
This class contains a raw_fd_ostream and adds a few extra features commonly needed for compiler-like ...
void keep()
Indicate that the tool's job wrt this output file has been successful and the file should not be dele...
raw_fd_ostream & os()
Return the contained raw_fd_ostream.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
This class implements an extremely fast bulk output stream that can only output to a stream.
Definition raw_ostream.h:53
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
A raw_ostream that writes to an std::string.
LLVM_ABI bool ApplyCallback(const RecordKeeper &Records, TableGenOutputFiles &OutFiles, StringRef FilenamePrefix)
Apply callback for any command line option registered above.
initializer< Ty > init(const Ty &Val)
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition FileSystem.h:793
@ OF_ForceUTF8
The file should be tagged as UTF-8 rather than the default IBM-1047 encoding.
Definition FileSystem.h:832
LLVM_ABI StringRef stem(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get stem.
Definition Path.cpp:596
LLVM_ABI void replace_extension(SmallVectorImpl< char > &path, const Twine &extension, Style style=Style::native)
Replace the file extension of path with extension.
Definition Path.cpp:491
LLVM_ABI IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI unsigned ErrorsPrinted
Definition Error.cpp:25
function_ref< bool(TableGenOutputFiles &OutFiles, const RecordKeeper &Records)> MultiFileTableGenMainFn
Perform the action using Records, and store output in OutFiles.
Definition Main.h:37
function_ref< bool(raw_ostream &OS, const RecordKeeper &Records)> TableGenMainFn
Returns true on error, false otherwise.
Definition Main.h:32
LLVM_ABI cl::opt< bool > EmitLongStrLiterals
Controls emitting large character arrays as strings or character arrays.
LLVM_ABI SourceMgr SrcMgr
Definition Error.cpp:24
LLVM_ABI int TableGenMain(const char *argv0, TableGenMainFn MainFn=nullptr)
Definition Main.cpp:301
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ End
Run the machine verifier once, at the end of the pipeline.
Definition CodeGen.h:320
std::map< StringRef, std::string > AdditionalFiles
Definition Main.h:28
std::string MainFile
Definition Main.h:25