xref: /freebsd/contrib/llvm-project/llvm/lib/TableGen/Main.cpp (revision 77013d11e6483b970af25e13c9b892075742f7e5)
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 "TGParser.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Support/FileSystem.h"
22 #include "llvm/Support/MemoryBuffer.h"
23 #include "llvm/Support/ToolOutputFile.h"
24 #include "llvm/TableGen/Error.h"
25 #include "llvm/TableGen/Record.h"
26 #include <algorithm>
27 #include <cstdio>
28 #include <system_error>
29 using namespace llvm;
30 
31 static cl::opt<std::string>
32 OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"),
33                cl::init("-"));
34 
35 static cl::opt<std::string>
36 DependFilename("d",
37                cl::desc("Dependency filename"),
38                cl::value_desc("filename"),
39                cl::init(""));
40 
41 static cl::opt<std::string>
42 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
43 
44 static cl::list<std::string>
45 IncludeDirs("I", cl::desc("Directory of include files"),
46             cl::value_desc("directory"), cl::Prefix);
47 
48 static cl::list<std::string>
49 MacroNames("D", cl::desc("Name of the macro to be defined"),
50             cl::value_desc("macro name"), cl::Prefix);
51 
52 static cl::opt<bool>
53 WriteIfChanged("write-if-changed", cl::desc("Only write output if it changed"));
54 
55 static cl::opt<bool>
56 TimePhases("time-phases", cl::desc("Time phases of parser and backend"));
57 
58 static int reportError(const char *ProgName, Twine Msg) {
59   errs() << ProgName << ": " << Msg;
60   errs().flush();
61   return 1;
62 }
63 
64 /// Create a dependency file for `-d` option.
65 ///
66 /// This functionality is really only for the benefit of the build system.
67 /// It is similar to GCC's `-M*` family of options.
68 static int createDependencyFile(const TGParser &Parser, const char *argv0) {
69   if (OutputFilename == "-")
70     return reportError(argv0, "the option -d must be used together with -o\n");
71 
72   std::error_code EC;
73   ToolOutputFile DepOut(DependFilename, EC, sys::fs::OF_None);
74   if (EC)
75     return reportError(argv0, "error opening " + DependFilename + ":" +
76                                   EC.message() + "\n");
77   DepOut.os() << OutputFilename << ":";
78   for (const auto &Dep : Parser.getDependencies()) {
79     DepOut.os() << ' ' << Dep;
80   }
81   DepOut.os() << "\n";
82   DepOut.keep();
83   return 0;
84 }
85 
86 int llvm::TableGenMain(const char *argv0, TableGenMainFn *MainFn) {
87   RecordKeeper Records;
88 
89   if (TimePhases)
90     Records.startPhaseTiming();
91 
92   // Parse the input file.
93 
94   Records.startTimer("Parse, build records");
95   ErrorOr<std::unique_ptr<MemoryBuffer>> FileOrErr =
96       MemoryBuffer::getFileOrSTDIN(InputFilename);
97   if (std::error_code EC = FileOrErr.getError())
98     return reportError(argv0, "Could not open input file '" + InputFilename +
99                                   "': " + EC.message() + "\n");
100 
101   Records.saveInputFilename(InputFilename);
102 
103   // Tell SrcMgr about this buffer, which is what TGParser will pick up.
104   SrcMgr.AddNewSourceBuffer(std::move(*FileOrErr), SMLoc());
105 
106   // Record the location of the include directory so that the lexer can find
107   // it later.
108   SrcMgr.setIncludeDirs(IncludeDirs);
109 
110   TGParser Parser(SrcMgr, MacroNames, Records);
111 
112   if (Parser.ParseFile())
113     return 1;
114   Records.stopTimer();
115 
116   // Write output to memory.
117   Records.startBackendTimer("Backend overall");
118   std::string OutString;
119   raw_string_ostream Out(OutString);
120   unsigned status = MainFn(Out, Records);
121   Records.stopBackendTimer();
122   if (status)
123     return 1;
124 
125   // Always write the depfile, even if the main output hasn't changed.
126   // If it's missing, Ninja considers the output dirty.  If this was below
127   // the early exit below and someone deleted the .inc.d file but not the .inc
128   // file, tablegen would never write the depfile.
129   if (!DependFilename.empty()) {
130     if (int Ret = createDependencyFile(Parser, argv0))
131       return Ret;
132   }
133 
134   Records.startTimer("Write output");
135   bool WriteFile = true;
136   if (WriteIfChanged) {
137     // Only updates the real output file if there are any differences.
138     // This prevents recompilation of all the files depending on it if there
139     // aren't any.
140     if (auto ExistingOrErr = MemoryBuffer::getFile(OutputFilename))
141       if (std::move(ExistingOrErr.get())->getBuffer() == Out.str())
142         WriteFile = false;
143   }
144   if (WriteFile) {
145     std::error_code EC;
146     ToolOutputFile OutFile(OutputFilename, EC, sys::fs::OF_None);
147     if (EC)
148       return reportError(argv0, "error opening " + OutputFilename + ": " +
149                                     EC.message() + "\n");
150     OutFile.os() << Out.str();
151     if (ErrorsPrinted == 0)
152       OutFile.keep();
153   }
154 
155   Records.stopTimer();
156   Records.stopPhaseTiming();
157 
158   if (ErrorsPrinted > 0)
159     return reportError(argv0, Twine(ErrorsPrinted) + " errors.\n");
160   return 0;
161 }
162