LLVM 22.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/SMLoc.h"
31#include "llvm/TableGen/Error.h"
35#include <memory>
36#include <string>
37#include <system_error>
38#include <utility>
39using namespace llvm;
40
42OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"),
43 cl::init("-"));
44
47 cl::desc("Dependency filename"),
48 cl::value_desc("filename"),
49 cl::init(""));
50
53
55IncludeDirs("I", cl::desc("Directory of include files"),
56 cl::value_desc("directory"), cl::Prefix);
57
59MacroNames("D", cl::desc("Name of the macro to be defined"),
60 cl::value_desc("macro name"), cl::Prefix);
61
62static cl::opt<bool>
63WriteIfChanged("write-if-changed", cl::desc("Only write output if it changed"));
64
65static cl::opt<bool>
66TimePhases("time-phases", cl::desc("Time phases of parser and backend"));
67
69 "long-string-literals",
70 cl::desc("when emitting large string tables, prefer string literals over "
71 "comma-separated char literals. This can be a readability and "
72 "compile-time performance win, but upsets some compilers"),
73 cl::Hidden, cl::init(true));
74
76 "no-warn-on-unused-template-args",
77 cl::desc("Disable unused template argument warnings."));
78
79static int reportError(const char *ProgName, Twine Msg) {
80 errs() << ProgName << ": " << Msg;
81 errs().flush();
82 return 1;
83}
84
85/// Create a dependency file for `-d` option.
86///
87/// This functionality is really only for the benefit of the build system.
88/// It is similar to GCC's `-M*` family of options.
89static int createDependencyFile(const TGParser &Parser, const char *argv0) {
90 if (OutputFilename == "-")
91 return reportError(argv0, "the option -d must be used together with -o\n");
92
93 std::error_code EC;
95 if (EC)
96 return reportError(argv0, "error opening " + DependFilename + ":" +
97 EC.message() + "\n");
98 DepOut.os() << OutputFilename << ":";
99 for (const auto &Dep : Parser.getDependencies()) {
100 DepOut.os() << ' ' << Dep;
101 }
102 DepOut.os() << "\n";
103 DepOut.keep();
104 return 0;
105}
106
107int llvm::TableGenMain(const char *argv0,
108 std::function<TableGenMainFn> MainFn) {
109 RecordKeeper Records;
110 TGTimer &Timer = Records.getTimer();
111
112 if (TimePhases)
113 Timer.startPhaseTiming();
114
115 // Parse the input file.
116
117 Timer.startTimer("Parse, build records");
120 if (std::error_code EC = FileOrErr.getError())
121 return reportError(argv0, "Could not open input file '" + InputFilename +
122 "': " + EC.message() + "\n");
123
124 Records.saveInputFilename(InputFilename);
125
126 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
127 SrcMgr.AddNewSourceBuffer(std::move(*FileOrErr), SMLoc());
128
129 // Record the location of the include directory so that the lexer can find
130 // it later.
131 SrcMgr.setIncludeDirs(IncludeDirs);
132 SrcMgr.setVirtualFileSystem(vfs::getRealFileSystem());
133
135
136 if (Parser.ParseFile())
137 return 1;
139
140 // Return early if any other errors were generated during parsing
141 // (e.g., assert failures).
142 if (ErrorsPrinted > 0)
143 return reportError(argv0, Twine(ErrorsPrinted) + " errors.\n");
144
145 // Write output to memory.
146 Timer.startBackendTimer("Backend overall");
147 std::string OutString;
148 raw_string_ostream Out(OutString);
149 unsigned status = 0;
150 // ApplyCallback will return true if it did not apply any callback. In that
151 // case, attempt to apply the MainFn.
152 if (TableGen::Emitter::ApplyCallback(Records, Out))
153 status = MainFn ? MainFn(Out, Records) : 1;
154 Timer.stopBackendTimer();
155 if (status)
156 return 1;
157
158 // Always write the depfile, even if the main output hasn't changed.
159 // If it's missing, Ninja considers the output dirty. If this was below
160 // the early exit below and someone deleted the .inc.d file but not the .inc
161 // file, tablegen would never write the depfile.
162 if (!DependFilename.empty()) {
163 if (int Ret = createDependencyFile(Parser, argv0))
164 return Ret;
165 }
166
167 Timer.startTimer("Write output");
168 bool WriteFile = true;
169 if (WriteIfChanged) {
170 // Only updates the real output file if there are any differences.
171 // This prevents recompilation of all the files depending on it if there
172 // aren't any.
173 if (auto ExistingOrErr =
174 MemoryBuffer::getFile(OutputFilename, /*IsText=*/true))
175 if (std::move(ExistingOrErr.get())->getBuffer() == OutString)
176 WriteFile = false;
177 }
178 if (WriteFile) {
179 std::error_code EC;
181 if (EC)
182 return reportError(argv0, "error opening " + OutputFilename + ": " +
183 EC.message() + "\n");
184 OutFile.os() << OutString;
185 if (ErrorsPrinted == 0)
186 OutFile.keep();
187 }
188
190 Timer.stopPhaseTiming();
191
192 if (ErrorsPrinted > 0)
193 return reportError(argv0, Twine(ErrorsPrinted) + " errors.\n");
194 return 0;
195}
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:89
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 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:79
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:23
const TGLexer::DependenciesSetTy & getDependencies() const
Definition TGParser.h:193
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:88
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
A raw_ostream that writes to an std::string.
bool ApplyCallback(const RecordKeeper &Records, raw_ostream &OS)
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:755
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.
unsigned ErrorsPrinted
Definition Error.cpp:25
cl::opt< bool > EmitLongStrLiterals
Controls emitting large character arrays as strings or character arrays.
SourceMgr SrcMgr
Definition Error.cpp:24
int TableGenMain(const char *argv0, std::function< TableGenMainFn > MainFn=nullptr)
Definition Main.cpp:107
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.