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"
27#include "llvm/Support/Path.h"
28#include "llvm/Support/SMLoc.h"
33#include "llvm/TableGen/Error.h"
37#include <memory>
38#include <string>
39#include <system_error>
40#include <utility>
41using namespace llvm;
42
44OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"),
45 cl::init("-"));
46
49 cl::desc("Dependency filename"),
50 cl::value_desc("filename"),
51 cl::init(""));
52
55
57IncludeDirs("I", cl::desc("Directory of include files"),
58 cl::value_desc("directory"), cl::Prefix);
59
61MacroNames("D", cl::desc("Name of the macro to be defined"),
62 cl::value_desc("macro name"), cl::Prefix);
63
64static cl::opt<bool>
65WriteIfChanged("write-if-changed", cl::desc("Only write output if it changed"));
66
67static cl::opt<bool>
68TimePhases("time-phases", cl::desc("Time phases of parser and backend"));
69
71 "long-string-literals",
72 cl::desc("when emitting large string tables, prefer string literals over "
73 "comma-separated char literals. This can be a readability and "
74 "compile-time performance win, but upsets some compilers"),
75 cl::Hidden, cl::init(true));
76
78 "no-warn-on-unused-template-args",
79 cl::desc("Disable unused template argument warnings."));
80
81static int reportError(const char *ProgName, Twine Msg) {
82 errs() << ProgName << ": " << Msg;
83 errs().flush();
84 return 1;
85}
86
87/// Create a dependency file for `-d` option.
88///
89/// This functionality is really only for the benefit of the build system.
90/// It is similar to GCC's `-M*` family of options.
91static int createDependencyFile(const TGParser &Parser, const char *argv0) {
92 if (OutputFilename == "-")
93 return reportError(argv0, "the option -d must be used together with -o\n");
94
95 std::error_code EC;
97 if (EC)
98 return reportError(argv0, "error opening " + DependFilename + ":" +
99 EC.message() + "\n");
100 DepOut.os() << OutputFilename << ":";
101
102 // Emit the primary input file as a dependency. This matches C compilers like
103 // Clang and GCC. Without it, a .td file with no `include` directives would
104 // produce a depfile listing zero dependencies. CMake's
105 // `cmake_transform_depfile` then collapses that to a 0-byte file, which Ninja
106 // treats as a missing depfile and re-runs the rule on every incremental
107 // build.
108 if (InputFilename != "-")
109 DepOut.os() << ' ' << InputFilename;
110
111 for (const auto &Dep : Parser.getDependencies()) {
112 DepOut.os() << ' ' << Dep;
113 }
114 DepOut.os() << "\n";
115 DepOut.keep();
116 return 0;
117}
118
119static int WriteOutput(const char *argv0, StringRef Filename,
120 StringRef Content) {
121 if (WriteIfChanged) {
122 // Only updates the real output file if there are any differences.
123 // This prevents recompilation of all the files depending on it if there
124 // aren't any.
125 if (auto ExistingOrErr = MemoryBuffer::getFile(Filename, /*IsText=*/true))
126 if (std::move(ExistingOrErr.get())->getBuffer() == Content)
127 return 0;
128 }
129 std::error_code EC;
131 if (EC)
132 return reportError(argv0, "error opening " + Filename + ": " +
133 EC.message() + "\n");
134#ifdef __MVS__
135 // On z/OS, text files default to IBM-1047, but generated files are UTF-8.
136 // Tag the file as UTF-8 before any content is written.
137 if (Filename != "-") {
138 EC = setzOSFileTag(OutFile.os().get_fd(), CCSID_UTF_8, /*IsText=*/true);
139 if (EC)
140 return reportError(argv0, "error tagging " + Filename + ": " +
141 EC.message() + "\n");
142 }
143#endif
144 OutFile.os() << Content;
145 if (ErrorsPrinted == 0)
146 OutFile.keep();
147
148 return 0;
149}
150
151int llvm::TableGenMain(const char *argv0, MultiFileTableGenMainFn MainFn) {
152 RecordKeeper Records;
153 TGTimer &Timer = Records.getTimer();
154
155 if (TimePhases)
156 Timer.startPhaseTiming();
157
158 // Parse the input file.
159
160 Timer.startTimer("Parse, build records");
163 if (std::error_code EC = FileOrErr.getError())
164 return reportError(argv0, "Could not open input file '" + InputFilename +
165 "': " + EC.message() + "\n");
166
167 Records.saveInputFilename(InputFilename);
168
169 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
170 SrcMgr.AddNewSourceBuffer(std::move(*FileOrErr), SMLoc());
171
172 // Record the location of the include directory so that the lexer can find
173 // it later.
174 SrcMgr.setIncludeDirs(IncludeDirs);
175 SrcMgr.setVirtualFileSystem(vfs::getRealFileSystem());
176
178
179 if (Parser.ParseFile())
180 return 1;
182
183 // Return early if any other errors were generated during parsing
184 // (e.g., assert failures).
185 if (ErrorsPrinted > 0)
186 return reportError(argv0, Twine(ErrorsPrinted) + " errors.\n");
187
188 // Write output to memory.
189 Timer.startBackendTimer("Backend overall");
190 TableGenOutputFiles OutFiles;
191 unsigned status = 0;
192 // ApplyCallback will return true if it did not apply any callback. In that
193 // case, attempt to apply the MainFn.
195 if (TableGen::Emitter::ApplyCallback(Records, OutFiles, FilenamePrefix))
196 status = MainFn ? MainFn(OutFiles, Records) : 1;
197 Timer.stopBackendTimer();
198 if (status)
199 return 1;
200
201 // Always write the depfile, even if the main output hasn't changed.
202 // If it's missing, Ninja considers the output dirty. If this was below
203 // the early exit below and someone deleted the .inc.d file but not the .inc
204 // file, tablegen would never write the depfile.
205 if (!DependFilename.empty()) {
206 if (int Ret = createDependencyFile(Parser, argv0))
207 return Ret;
208 }
209
210 Timer.startTimer("Write output");
211 if (int Ret = WriteOutput(argv0, OutputFilename, OutFiles.MainFile))
212 return Ret;
213 for (auto [Suffix, Content] : OutFiles.AdditionalFiles) {
215 // TODO: Format using the split-file convention when writing to stdout?
216 if (Filename != "-") {
218 Filename.append(Suffix);
219 }
220 if (int Ret = WriteOutput(argv0, Filename, Content))
221 return Ret;
222 }
223
225 Timer.stopPhaseTiming();
226
227 if (ErrorsPrinted > 0)
228 return reportError(argv0, Twine(ErrorsPrinted) + " errors.\n");
229 return 0;
230}
231
232int llvm::TableGenMain(const char *argv0, TableGenMainFn MainFn) {
233 return TableGenMain(argv0, [&MainFn](TableGenOutputFiles &OutFiles,
234 const RecordKeeper &Records) {
235 std::string S;
236 raw_string_ostream OS(S);
237 int Res = MainFn(OS, Records);
238 OutFiles = {std::move(S), {}};
239 return Res;
240 });
241}
#define CCSID_UTF_8
Definition AutoConvert.h:28
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 int createDependencyFile(const TGParser &Parser, const char *argv0)
Create a dependency file for -d option.
Definition Main.cpp:91
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 cl::opt< std::string > InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"))
static int WriteOutput(const char *argv0, StringRef Filename, StringRef Content)
Definition Main.cpp:119
static cl::list< std::string > MacroNames("D", cl::desc("Name of the macro to be defined"), cl::value_desc("macro name"), cl::Prefix)
static int reportError(const char *ProgName, Twine Msg)
Definition Main.cpp:81
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
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
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
int get_fd() const
Return the file descriptor.
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
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:232
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
std::map< StringRef, std::string > AdditionalFiles
Definition Main.h:28
std::string MainFile
Definition Main.h:25