LLVM 20.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"
30#include "llvm/TableGen/Error.h"
33#include <memory>
34#include <string>
35#include <system_error>
36#include <utility>
37using namespace llvm;
38
40OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"),
41 cl::init("-"));
42
45 cl::desc("Dependency filename"),
46 cl::value_desc("filename"),
47 cl::init(""));
48
51
53IncludeDirs("I", cl::desc("Directory of include files"),
54 cl::value_desc("directory"), cl::Prefix);
55
57MacroNames("D", cl::desc("Name of the macro to be defined"),
58 cl::value_desc("macro name"), cl::Prefix);
59
60static cl::opt<bool>
61WriteIfChanged("write-if-changed", cl::desc("Only write output if it changed"));
62
63static cl::opt<bool>
64TimePhases("time-phases", cl::desc("Time phases of parser and backend"));
65
67 "no-warn-on-unused-template-args",
68 cl::desc("Disable unused template argument warnings."));
69
70static int reportError(const char *ProgName, Twine Msg) {
71 errs() << ProgName << ": " << Msg;
72 errs().flush();
73 return 1;
74}
75
76/// Create a dependency file for `-d` option.
77///
78/// This functionality is really only for the benefit of the build system.
79/// It is similar to GCC's `-M*` family of options.
80static int createDependencyFile(const TGParser &Parser, const char *argv0) {
81 if (OutputFilename == "-")
82 return reportError(argv0, "the option -d must be used together with -o\n");
83
84 std::error_code EC;
86 if (EC)
87 return reportError(argv0, "error opening " + DependFilename + ":" +
88 EC.message() + "\n");
89 DepOut.os() << OutputFilename << ":";
90 for (const auto &Dep : Parser.getDependencies()) {
91 DepOut.os() << ' ' << Dep;
92 }
93 DepOut.os() << "\n";
94 DepOut.keep();
95 return 0;
96}
97
98int llvm::TableGenMain(const char *argv0,
99 std::function<TableGenMainFn> MainFn) {
100 RecordKeeper Records;
101
102 if (TimePhases)
103 Records.startPhaseTiming();
104
105 // Parse the input file.
106
107 Records.startTimer("Parse, build records");
110 if (std::error_code EC = FileOrErr.getError())
111 return reportError(argv0, "Could not open input file '" + InputFilename +
112 "': " + EC.message() + "\n");
113
114 Records.saveInputFilename(InputFilename);
115
116 // Tell SrcMgr about this buffer, which is what TGParser will pick up.
117 SrcMgr.AddNewSourceBuffer(std::move(*FileOrErr), SMLoc());
118
119 // Record the location of the include directory so that the lexer can find
120 // it later.
122
124
125 if (Parser.ParseFile())
126 return 1;
127 Records.stopTimer();
128
129 // Write output to memory.
130 Records.startBackendTimer("Backend overall");
131 std::string OutString;
132 raw_string_ostream Out(OutString);
133 unsigned status = 0;
135 if (ActionFn)
136 ActionFn(Records, Out);
137 else if (MainFn)
138 status = MainFn(Out, Records);
139 else
140 return 1;
141 Records.stopBackendTimer();
142 if (status)
143 return 1;
144
145 // Always write the depfile, even if the main output hasn't changed.
146 // If it's missing, Ninja considers the output dirty. If this was below
147 // the early exit below and someone deleted the .inc.d file but not the .inc
148 // file, tablegen would never write the depfile.
149 if (!DependFilename.empty()) {
150 if (int Ret = createDependencyFile(Parser, argv0))
151 return Ret;
152 }
153
154 Records.startTimer("Write output");
155 bool WriteFile = true;
156 if (WriteIfChanged) {
157 // Only updates the real output file if there are any differences.
158 // This prevents recompilation of all the files depending on it if there
159 // aren't any.
160 if (auto ExistingOrErr =
161 MemoryBuffer::getFile(OutputFilename, /*IsText=*/true))
162 if (std::move(ExistingOrErr.get())->getBuffer() == OutString)
163 WriteFile = false;
164 }
165 if (WriteFile) {
166 std::error_code EC;
168 if (EC)
169 return reportError(argv0, "error opening " + OutputFilename + ": " +
170 EC.message() + "\n");
171 OutFile.os() << OutString;
172 if (ErrorsPrinted == 0)
173 OutFile.keep();
174 }
175
176 Records.stopTimer();
177 Records.stopPhaseTiming();
178
179 if (ErrorsPrinted > 0)
180 return reportError(argv0, Twine(ErrorsPrinted) + " errors.\n");
181 return 0;
182}
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:80
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:70
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
void setIncludeDirs(const std::vector< std::string > &Dirs)
Definition: SourceMgr.h:106
unsigned AddNewSourceBuffer(std::unique_ptr< MemoryBuffer > F, SMLoc IncludeLoc)
Add a new source buffer to this source manager.
Definition: SourceMgr.h:144
const TGLexer::DependenciesSetTy & getDependencies() const
Definition: TGParser.h:197
bool ParseFile()
ParseFile - Main entrypoint for parsing a tblgen file.
Definition: TGParser.cpp:4362
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:81
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
ManagedStatic< cl::opt< FnT >, OptCreatorT > Action
void(*)(RecordKeeper &Records, raw_ostream &OS) FnT
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition: FileSystem.h:758
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
unsigned ErrorsPrinted
Definition: Error.cpp:25
SourceMgr SrcMgr
Definition: Error.cpp:24
int TableGenMain(const char *argv0, std::function< TableGenMainFn > MainFn=nullptr)
Definition: Main.cpp:98
raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.