LLVM 24.0.0git
TGParser.h
Go to the documentation of this file.
1//===- TGParser.h - Parser for TableGen Files -------------------*- C++ -*-===//
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// This class represents the Parser for tablegen files.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_LIB_TABLEGEN_TGPARSER_H
14#define LLVM_LIB_TABLEGEN_TGPARSER_H
15
16#include "TGLexer.h"
17#include "llvm/TableGen/Error.h"
19#include <map>
20#include <optional>
21
22namespace llvm {
23class SourceMgr;
24class Twine;
25struct ForeachLoop;
26struct MultiClass;
27struct ClassReference;
29
30/// Specifies how a 'let' assignment interacts with the existing field value.
31/// - Replace: overwrite the field (default behavior).
32/// - Append: concatenate the new value after the existing value.
33/// - Prepend: concatenate the new value before the existing value.
34enum class LetMode { Replace, Append, Prepend };
35
36/// Parsed let mode keyword and field name (e.g. `let append x` yields
37/// Mode=Append, Name="x"; plain `let x` yields Mode=Replace, Name="x").
40 SMLoc Loc; // Source location of the field name.
41 std::string Name; // The field name being assigned.
42};
43
44struct LetRecord {
46 std::vector<unsigned> Bits;
47 const Init *Value;
52 : Name(N), Bits(B), Value(V), Loc(L), Mode(M) {}
53};
54
55/// RecordsEntry - Holds exactly one of a Record, ForeachLoop, or
56/// AssertionInfo.
58 std::unique_ptr<Record> Rec;
59 std::unique_ptr<ForeachLoop> Loop;
60 std::unique_ptr<Record::AssertionInfo> Assertion;
61 std::unique_ptr<Record::DumpInfo> Dump;
62
63 void dump() const;
64
65 RecordsEntry(std::unique_ptr<Record> Rec);
66 RecordsEntry(std::unique_ptr<ForeachLoop> Loop);
67 RecordsEntry(std::unique_ptr<Record::AssertionInfo> Assertion);
68 RecordsEntry(std::unique_ptr<Record::DumpInfo> Dump);
69};
70
71/// ForeachLoop - Record the iteration state associated with a for loop.
72/// This is used to instantiate items in the loop body.
73///
74/// IterVar is allowed to be null, in which case no iteration variable is
75/// defined in the loop at all. (This happens when a ForeachLoop is
76/// constructed by desugaring an if statement.)
81 std::vector<RecordsEntry> Entries;
82
83 void dump() const;
84
85 ForeachLoop(SMLoc Loc, const VarInit *IVar, const Init *LValue)
86 : Loc(Loc), IterVar(IVar), ListValue(LValue) {}
87};
88
94
95struct MultiClass {
96 Record Rec; // Placeholder for template args and Name.
97 std::vector<RecordsEntry> Entries;
98
99 void dump() const;
100
102 : Rec(Name, Loc, Records, Record::RK_MultiClass) {}
103};
104
106public:
108
109private:
110 ScopeKind Kind;
111 std::unique_ptr<TGVarScope> Parent;
112 // A scope to hold variable definitions from defvar.
113 std::map<std::string, const Init *, std::less<>> Vars;
114 Record *CurRec = nullptr;
115 ForeachLoop *CurLoop = nullptr;
116 MultiClass *CurMultiClass = nullptr;
117
118public:
119 TGVarScope(std::unique_ptr<TGVarScope> Parent)
120 : Kind(SK_Local), Parent(std::move(Parent)) {}
121 TGVarScope(std::unique_ptr<TGVarScope> Parent, Record *Rec)
122 : Kind(SK_Record), Parent(std::move(Parent)), CurRec(Rec) {}
123 TGVarScope(std::unique_ptr<TGVarScope> Parent, ForeachLoop *Loop)
124 : Kind(SK_ForeachLoop), Parent(std::move(Parent)), CurLoop(Loop) {}
125 TGVarScope(std::unique_ptr<TGVarScope> Parent, MultiClass *Multiclass)
126 : Kind(SK_MultiClass), Parent(std::move(Parent)),
127 CurMultiClass(Multiclass) {}
128
129 std::unique_ptr<TGVarScope> extractParent() {
130 // This is expected to be called just before we are destructed, so
131 // it doesn't much matter what state we leave 'parent' in.
132 return std::move(Parent);
133 }
134
135 const Init *getVar(RecordKeeper &Records, MultiClass *ParsingMultiClass,
136 const StringInit *Name, SMRange NameLoc,
137 bool TrackReferenceLocs) const;
138
139 bool varAlreadyDefined(StringRef Name) const {
140 // When we check whether a variable is already defined, for the purpose of
141 // reporting an error on redefinition, we don't look up to the parent
142 // scope, because it's all right to shadow an outer definition with an
143 // inner one.
144 return Vars.find(Name) != Vars.end();
145 }
146
147 void addVar(StringRef Name, const Init *I) {
148 bool Ins = Vars.try_emplace(Name.str(), I).second;
149 (void)Ins;
150 assert(Ins && "Local variable already exists");
151 }
152
153 bool isOutermost() const { return Parent == nullptr; }
154};
155
156class TGParser {
157 TGLexer Lex;
158 std::vector<SmallVector<LetRecord, 4>> LetStack;
159 std::map<std::string, std::unique_ptr<MultiClass>> MultiClasses;
160 std::map<std::string, const RecTy *> TypeAliases;
161
162 /// Loops - Keep track of any foreach loops we are within.
163 ///
164 std::vector<std::unique_ptr<ForeachLoop>> Loops;
165
167
168 /// CurMultiClass - If we are parsing a 'multiclass' definition, this is the
169 /// current value.
170 MultiClass *CurMultiClass;
171
172 /// CurScope - Innermost of the current nested scopes for 'defvar' variables.
173 std::unique_ptr<TGVarScope> CurScope;
174
175 // Record tracker
176 RecordKeeper &Records;
177
178 // A "named boolean" indicating how to parse identifiers. Usually
179 // identifiers map to some existing object but in special cases
180 // (e.g. parsing def names) no such object exists yet because we are
181 // in the middle of creating in. For those situations, allow the
182 // parser to ignore missing object errors.
183 enum IDParseMode {
184 ParseValueMode, // We are parsing a value we expect to look up.
185 ParseNameMode, // We are parsing a name of an object that does not yet
186 // exist.
187 };
188
189 bool NoWarnOnUnusedTemplateArgs = false;
190 bool TrackReferenceLocs = false;
191
192public:
194 const bool NoWarnOnUnusedTemplateArgs = false,
195 const bool TrackReferenceLocs = false)
196 : Lex(SM, Macros), CurMultiClass(nullptr), Records(records),
197 NoWarnOnUnusedTemplateArgs(NoWarnOnUnusedTemplateArgs),
198 TrackReferenceLocs(TrackReferenceLocs) {}
199
200 /// ParseFile - Main entrypoint for parsing a tblgen file. These parser
201 /// routines return true on error, or false on success.
202 bool ParseFile();
203
204 bool Error(SMLoc L, const Twine &Msg) const {
205 PrintError(L, Msg);
206 return true;
207 }
208 bool TokError(const Twine &Msg) const { return Error(Lex.getLoc(), Msg); }
209
211 CurScope = std::make_unique<TGVarScope>(std::move(CurScope));
212 // Returns a pointer to the new scope, so that the caller can pass it back
213 // to PopScope which will check by assertion that the pushes and pops
214 // match up properly.
215 return CurScope.get();
216 }
218 CurScope = std::make_unique<TGVarScope>(std::move(CurScope), Rec);
219 return CurScope.get();
220 }
222 CurScope = std::make_unique<TGVarScope>(std::move(CurScope), Loop);
223 return CurScope.get();
224 }
226 CurScope = std::make_unique<TGVarScope>(std::move(CurScope), Multiclass);
227 return CurScope.get();
228 }
229 void PopScope(TGVarScope *ExpectedStackTop) {
230 assert(ExpectedStackTop == CurScope.get() &&
231 "Mismatched pushes and pops of local variable scopes");
232 CurScope = CurScope->extractParent();
233 }
234
235private: // Semantic analysis methods.
236 bool AddValue(Record *TheRec, SMLoc Loc, const RecordVal &RV,
237 const Record *FromRec = nullptr);
238 /// Set the value of a RecordVal within the given record. If `OverrideDefLoc`
239 /// is set, the provided location overrides any existing location of the
240 /// RecordVal. An optional `Mode` specifies append/prepend concatenation.
241 bool SetValue(Record *TheRec, SMLoc Loc, const Init *ValName,
242 ArrayRef<unsigned> BitList, const Init *V,
243 bool OverrideDefLoc = true, LetMode Mode = LetMode::Replace);
244 bool AddParentClass(Record *Rec, ClassReference &ParentClass);
245 bool AddParentClass(RecordsEntry &Entry, ClassReference &ParentClass);
246 bool AddParentMultiClass(MultiClassReference &ParentMultiClass);
247
249
250 bool addEntry(RecordsEntry E);
251 bool resolve(const ForeachLoop &Loop, SubstStack &Stack, bool Final,
252 std::vector<RecordsEntry> *Dest, SMLoc *Loc = nullptr);
253 bool resolve(const std::vector<RecordsEntry> &Source, SubstStack &Substs,
254 bool Final, std::vector<RecordsEntry> *Dest,
255 SMLoc *Loc = nullptr);
256 bool addDefOne(std::unique_ptr<Record> Rec);
257
258 using ArgValueHandler = std::function<void(const Init *, const Init *)>;
259 bool resolveArguments(
260 const Record *Rec, ArrayRef<const ArgumentInit *> ArgValues, SMLoc Loc,
261 ArgValueHandler ArgValueHandler = [](const Init *, const Init *) {});
262 bool resolveArgumentsOfClass(MapResolver &R, const Record *Rec,
264 SMLoc Loc);
265 bool resolveArgumentsOfMultiClass(SubstStack &Substs, MultiClass *MC,
267 const Init *DefmName, SMLoc Loc);
268
269private: // Parser methods.
271 bool ParseObjectList();
272 bool ParseObject();
273 bool ParseClass();
274 bool ParseMultiClass();
275 bool ParseDefm();
276 bool ParseDef();
277 bool ParseDefset();
278 bool ParseDeftype();
279 bool ParseDefvar(Record *CurRec = nullptr);
280 bool ParseDump(Record *CurRec = nullptr);
281 bool ParseForeach();
282 bool ParseIf();
283 bool ParseIfBody(StringRef Kind);
284 bool ParseAssert(Record *CurRec = nullptr);
285 bool ParseTopLevelLet();
286 LetModeAndName ParseLetModeAndName();
287 void ParseLetList(SmallVectorImpl<LetRecord> &Result);
288
289 bool ParseObjectBody(Record *CurRec);
290 bool ParseBody(Record *CurRec);
291 bool ParseBodyItem(Record *CurRec);
292
293 bool ParseTemplateArgList(Record *CurRec);
294 bool ParseDeclaration(Record *CurRec, bool ParsingTemplateArgs);
295 const VarInit *ParseForeachDeclaration(const Init *&ForeachListValue);
296
297 ClassReference ParseClassReference(Record *CurRec, bool isDefm);
298 MultiClassReference ParseMultiClassReference();
299
300 const Init *ParseIDValue(Record *CurRec, const StringInit *Name,
301 SMRange NameLoc, IDParseMode Mode = ParseValueMode);
302 const Init *ParseSimpleValue(Record *CurRec, const RecTy *ItemType = nullptr,
303 IDParseMode Mode = ParseValueMode);
304 const Init *ParseValue(Record *CurRec, const RecTy *ItemType = nullptr,
305 IDParseMode Mode = ParseValueMode);
306 void ParseValueList(SmallVectorImpl<const Init *> &Result, Record *CurRec,
307 const RecTy *ItemType = nullptr);
308 bool ParseTemplateArgValueList(SmallVectorImpl<const ArgumentInit *> &Result,
309 SmallVectorImpl<SMLoc> &ArgLocs,
310 Record *CurRec, const Record *ArgsRec);
311 void ParseDagArgList(
312 SmallVectorImpl<std::pair<const Init *, const StringInit *>> &Result,
313 Record *CurRec);
314 bool ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges);
315 const TypedInit *ParseSliceElement(Record *CurRec);
316 const TypedInit *ParseSliceElements(Record *CurRec, bool Single = false);
317 void ParseRangeList(SmallVectorImpl<unsigned> &Result);
318 bool ParseRangePiece(SmallVectorImpl<unsigned> &Ranges,
319 const TypedInit *FirstItem = nullptr);
320 const RecTy *ParseType();
321 const Init *ParseOperation(Record *CurRec, const RecTy *ItemType);
322 const Init *ParseOperationSubstr(Record *CurRec, const RecTy *ItemType);
323 const Init *ParseOperationFind(Record *CurRec, const RecTy *ItemType);
324 const Init *ParseOperationListComprehension(Record *CurRec,
325 const RecTy *ItemType);
326 const Init *ParseOperationCond(Record *CurRec, const RecTy *ItemType);
327 const Init *ParseOperationSwitch(Record *CurRec, const RecTy *ItemType);
328 std::optional<const RecTy *> resolveInitTypes(ArrayRef<const Init *> Inits,
329 const Twine &ErrCtx);
330 const RecTy *ParseOperatorType();
331 const Init *ParseObjectName();
332 const Record *ParseClassID();
333 MultiClass *ParseMultiClassID();
334 bool ApplyLetStack(Record *CurRec);
335 bool ApplyLetStack(RecordsEntry &Entry);
336 bool CheckTemplateArgValues(SmallVectorImpl<const ArgumentInit *> &Values,
337 ArrayRef<SMLoc> ValuesLocs,
338 const Record *ArgsRec);
339};
340
341} // end namespace llvm
342
343#endif
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static void SetValue(Value *V, GenericValue Val, ExecutionContext &SF)
Definition Execution.cpp:41
#define I(x, y, z)
Definition MD5.cpp:57
static cl::opt< RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode > Mode("regalloc-enable-advisor", cl::Hidden, cl::init(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default), cl::desc("Enable regalloc advisor mode"), cl::values(clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Default, "default", "Default"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Release, "release", "precompiled"), clEnumValN(RegAllocEvictionAdvisorAnalysisLegacy::AdvisorMode::Development, "development", "for training")))
const char * Msg
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Represents a single loop in the control flow graph.
Definition LoopInfo.h:40
This class represents a field in a record, including its name, type, value, and source location.
Definition Record.h:1589
Represents a location in source code.
Definition SMLoc.h:22
Represents a range in source code.
Definition SMLoc.h:47
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This owns the files read by a parser, handles include stacks, and handles diagnostic wrangling.
Definition SourceMgr.h:34
"foo" - Represent an initialization by a string value.
Definition Record.h:715
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
TGLexer - TableGen Lexer class.
Definition TGLexer.h:193
void PopScope(TGVarScope *ExpectedStackTop)
Definition TGParser.h:229
bool Error(SMLoc L, const Twine &Msg) const
Definition TGParser.h:204
TGVarScope * PushScope(ForeachLoop *Loop)
Definition TGParser.h:221
TGVarScope * PushScope(Record *Rec)
Definition TGParser.h:217
bool TokError(const Twine &Msg) const
Definition TGParser.h:208
TGParser(SourceMgr &SM, ArrayRef< std::string > Macros, RecordKeeper &records, const bool NoWarnOnUnusedTemplateArgs=false, const bool TrackReferenceLocs=false)
Definition TGParser.h:193
TGVarScope * PushScope(MultiClass *Multiclass)
Definition TGParser.h:225
bool ParseFile()
ParseFile - Main entrypoint for parsing a tblgen file.
TGVarScope * PushScope()
Definition TGParser.h:210
TGVarScope(std::unique_ptr< TGVarScope > Parent, Record *Rec)
Definition TGParser.h:121
std::unique_ptr< TGVarScope > extractParent()
Definition TGParser.h:129
bool isOutermost() const
Definition TGParser.h:153
TGVarScope(std::unique_ptr< TGVarScope > Parent, ForeachLoop *Loop)
Definition TGParser.h:123
void addVar(StringRef Name, const Init *I)
Definition TGParser.h:147
bool varAlreadyDefined(StringRef Name) const
Definition TGParser.h:139
const Init * getVar(RecordKeeper &Records, MultiClass *ParsingMultiClass, const StringInit *Name, SMRange NameLoc, bool TrackReferenceLocs) const
Definition TGParser.cpp:139
TGVarScope(std::unique_ptr< TGVarScope > Parent, MultiClass *Multiclass)
Definition TGParser.h:125
TGVarScope(std::unique_ptr< TGVarScope > Parent)
Definition TGParser.h:119
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
'Opcode' - Represent a reference to an entire variable object.
Definition Record.h:1262
This is an optimization pass for GlobalISel generic memory operations.
RelativeUniformCounterPtr Values
Definition InstrProf.h:91
LLVM_ABI void PrintError(const Twine &Msg)
Definition Error.cpp:104
LetMode
Specifies how a 'let' assignment interacts with the existing field value.
Definition TGParser.h:34
ArrayRef(const T &OneElt) -> ArrayRef< T >
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1933
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:879
#define N
const RecTy * EltTy
Definition TGParser.h:91
SmallVector< Init *, 16 > Elements
Definition TGParser.h:92
ForeachLoop - Record the iteration state associated with a for loop.
Definition TGParser.h:77
ForeachLoop(SMLoc Loc, const VarInit *IVar, const Init *LValue)
Definition TGParser.h:85
std::vector< RecordsEntry > Entries
Definition TGParser.h:81
const Init * ListValue
Definition TGParser.h:80
void dump() const
const VarInit * IterVar
Definition TGParser.h:79
Parsed let mode keyword and field name (e.g.
Definition TGParser.h:38
std::string Name
Definition TGParser.h:41
LetRecord(const StringInit *N, ArrayRef< unsigned > B, const Init *V, SMLoc L, LetMode M=LetMode::Replace)
Definition TGParser.h:50
const Init * Value
Definition TGParser.h:47
const StringInit * Name
Definition TGParser.h:45
std::vector< unsigned > Bits
Definition TGParser.h:46
LetMode Mode
Definition TGParser.h:49
std::vector< RecordsEntry > Entries
Definition TGParser.h:97
void dump() const
MultiClass(StringRef Name, SMLoc Loc, RecordKeeper &Records)
Definition TGParser.h:101
RecordsEntry - Holds exactly one of a Record, ForeachLoop, or AssertionInfo.
Definition TGParser.h:57
std::unique_ptr< ForeachLoop > Loop
Definition TGParser.h:59
RecordsEntry(std::unique_ptr< Record > Rec)
Definition TGParser.cpp:37
std::unique_ptr< Record::AssertionInfo > Assertion
Definition TGParser.h:60
void dump() const
std::unique_ptr< Record::DumpInfo > Dump
Definition TGParser.h:61
std::unique_ptr< Record > Rec
Definition TGParser.h:58