LLVM 23.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
21namespace llvm {
22class SourceMgr;
23class Twine;
24struct ForeachLoop;
25struct MultiClass;
28
29/// Specifies how a 'let' assignment interacts with the existing field value.
30/// - Replace: overwrite the field (default behavior).
31/// - Append: concatenate the new value after the existing value.
32/// - Prepend: concatenate the new value before the existing value.
33enum class LetMode { Replace, Append, Prepend };
34
35/// Parsed let mode keyword and field name (e.g. `let append x` yields
36/// Mode=Append, Name="x"; plain `let x` yields Mode=Replace, Name="x").
39 SMLoc Loc; // Source location of the field name.
40 std::string Name; // The field name being assigned.
41};
42
43struct LetRecord {
45 std::vector<unsigned> Bits;
46 const Init *Value;
51 : Name(N), Bits(B), Value(V), Loc(L), Mode(M) {}
52};
53
54/// RecordsEntry - Holds exactly one of a Record, ForeachLoop, or
55/// AssertionInfo.
57 std::unique_ptr<Record> Rec;
58 std::unique_ptr<ForeachLoop> Loop;
59 std::unique_ptr<Record::AssertionInfo> Assertion;
60 std::unique_ptr<Record::DumpInfo> Dump;
61
62 void dump() const;
63
64 RecordsEntry() = default;
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); }
210 return Lex.getDependencies();
211 }
212
214 CurScope = std::make_unique<TGVarScope>(std::move(CurScope));
215 // Returns a pointer to the new scope, so that the caller can pass it back
216 // to PopScope which will check by assertion that the pushes and pops
217 // match up properly.
218 return CurScope.get();
219 }
221 CurScope = std::make_unique<TGVarScope>(std::move(CurScope), Rec);
222 return CurScope.get();
223 }
225 CurScope = std::make_unique<TGVarScope>(std::move(CurScope), Loop);
226 return CurScope.get();
227 }
229 CurScope = std::make_unique<TGVarScope>(std::move(CurScope), Multiclass);
230 return CurScope.get();
231 }
232 void PopScope(TGVarScope *ExpectedStackTop) {
233 assert(ExpectedStackTop == CurScope.get() &&
234 "Mismatched pushes and pops of local variable scopes");
235 CurScope = CurScope->extractParent();
236 }
237
238private: // Semantic analysis methods.
239 bool AddValue(Record *TheRec, SMLoc Loc, const RecordVal &RV);
240 /// Set the value of a RecordVal within the given record. If `OverrideDefLoc`
241 /// is set, the provided location overrides any existing location of the
242 /// RecordVal. An optional `Mode` specifies append/prepend concatenation.
243 bool SetValue(Record *TheRec, SMLoc Loc, const Init *ValName,
244 ArrayRef<unsigned> BitList, const Init *V,
245 bool AllowSelfAssignment = false, bool OverrideDefLoc = true,
247 bool AddSubClass(Record *Rec, SubClassReference &SubClass);
248 bool AddSubClass(RecordsEntry &Entry, SubClassReference &SubClass);
249 bool AddSubMultiClass(MultiClass *CurMC,
250 SubMultiClassReference &SubMultiClass);
251
253
254 bool addEntry(RecordsEntry E);
255 bool resolve(const ForeachLoop &Loop, SubstStack &Stack, bool Final,
256 std::vector<RecordsEntry> *Dest, SMLoc *Loc = nullptr);
257 bool resolve(const std::vector<RecordsEntry> &Source, SubstStack &Substs,
258 bool Final, std::vector<RecordsEntry> *Dest,
259 SMLoc *Loc = nullptr);
260 bool addDefOne(std::unique_ptr<Record> Rec);
261
262 using ArgValueHandler = std::function<void(const Init *, const Init *)>;
263 bool resolveArguments(
264 const Record *Rec, ArrayRef<const ArgumentInit *> ArgValues, SMLoc Loc,
265 ArgValueHandler ArgValueHandler = [](const Init *, const Init *) {});
266 bool resolveArgumentsOfClass(MapResolver &R, const Record *Rec,
268 SMLoc Loc);
269 bool resolveArgumentsOfMultiClass(SubstStack &Substs, MultiClass *MC,
271 const Init *DefmName, SMLoc Loc);
272
273private: // Parser methods.
274 bool consume(tgtok::TokKind K);
275 bool ParseObjectList(MultiClass *MC = nullptr);
276 bool ParseObject(MultiClass *MC);
277 bool ParseClass();
278 bool ParseMultiClass();
279 bool ParseDefm(MultiClass *CurMultiClass);
280 bool ParseDef(MultiClass *CurMultiClass);
281 bool ParseDefset();
282 bool ParseDeftype();
283 bool ParseDefvar(Record *CurRec = nullptr);
284 bool ParseDump(MultiClass *CurMultiClass, Record *CurRec = nullptr);
285 bool ParseForeach(MultiClass *CurMultiClass);
286 bool ParseIf(MultiClass *CurMultiClass);
287 bool ParseIfBody(MultiClass *CurMultiClass, StringRef Kind);
288 bool ParseAssert(MultiClass *CurMultiClass, Record *CurRec = nullptr);
289 bool ParseTopLevelLet(MultiClass *CurMultiClass);
290 LetModeAndName ParseLetModeAndName();
291 void ParseLetList(SmallVectorImpl<LetRecord> &Result);
292
293 bool ParseObjectBody(Record *CurRec);
294 bool ParseBody(Record *CurRec);
295 bool ParseBodyItem(Record *CurRec);
296
297 bool ParseTemplateArgList(Record *CurRec);
298 const Init *ParseDeclaration(Record *CurRec, bool ParsingTemplateArgs);
299 const VarInit *ParseForeachDeclaration(const Init *&ForeachListValue);
300
301 SubClassReference ParseSubClassReference(Record *CurRec, bool isDefm);
302 SubMultiClassReference ParseSubMultiClassReference(MultiClass *CurMC);
303
304 const Init *ParseIDValue(Record *CurRec, const StringInit *Name,
305 SMRange NameLoc, IDParseMode Mode = ParseValueMode);
306 const Init *ParseSimpleValue(Record *CurRec, const RecTy *ItemType = nullptr,
307 IDParseMode Mode = ParseValueMode);
308 const Init *ParseValue(Record *CurRec, const RecTy *ItemType = nullptr,
309 IDParseMode Mode = ParseValueMode);
310 void ParseValueList(SmallVectorImpl<const Init *> &Result, Record *CurRec,
311 const RecTy *ItemType = nullptr);
312 bool ParseTemplateArgValueList(SmallVectorImpl<const ArgumentInit *> &Result,
313 SmallVectorImpl<SMLoc> &ArgLocs,
314 Record *CurRec, const Record *ArgsRec);
315 void ParseDagArgList(
316 SmallVectorImpl<std::pair<const Init *, const StringInit *>> &Result,
317 Record *CurRec);
318 bool ParseOptionalRangeList(SmallVectorImpl<unsigned> &Ranges);
319 bool ParseOptionalBitList(SmallVectorImpl<unsigned> &Ranges);
320 const TypedInit *ParseSliceElement(Record *CurRec);
321 const TypedInit *ParseSliceElements(Record *CurRec, bool Single = false);
322 void ParseRangeList(SmallVectorImpl<unsigned> &Result);
323 bool ParseRangePiece(SmallVectorImpl<unsigned> &Ranges,
324 const TypedInit *FirstItem = nullptr);
325 const RecTy *ParseType();
326 const Init *ParseOperation(Record *CurRec, const RecTy *ItemType);
327 const Init *ParseOperationSubstr(Record *CurRec, const RecTy *ItemType);
328 const Init *ParseOperationFind(Record *CurRec, const RecTy *ItemType);
329 const Init *ParseOperationForEachFilter(Record *CurRec,
330 const RecTy *ItemType);
331 const Init *ParseOperationCond(Record *CurRec, const RecTy *ItemType);
332 const RecTy *ParseOperatorType();
333 const Init *ParseObjectName(MultiClass *CurMultiClass);
334 const Record *ParseClassID();
335 MultiClass *ParseMultiClassID();
336 bool ApplyLetStack(Record *CurRec);
337 bool ApplyLetStack(RecordsEntry &Entry);
338 bool CheckTemplateArgValues(SmallVectorImpl<const ArgumentInit *> &Values,
339 ArrayRef<SMLoc> ValuesLocs,
340 const Record *ArgsRec);
341};
342
343} // end namespace llvm
344
345#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 constexpr unsigned SM(unsigned Version)
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")))
ArrayRef - 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:1541
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:37
"foo" - Represent an initialization by a string value.
Definition Record.h:696
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
TGLexer - TableGen Lexer class.
Definition TGLexer.h:192
std::set< std::string > DependenciesSetTy
Definition TGLexer.h:209
void PopScope(TGVarScope *ExpectedStackTop)
Definition TGParser.h:232
const TGLexer::DependenciesSetTy & getDependencies() const
Definition TGParser.h:209
bool Error(SMLoc L, const Twine &Msg) const
Definition TGParser.h:204
TGVarScope * PushScope(ForeachLoop *Loop)
Definition TGParser.h:224
TGVarScope * PushScope(Record *Rec)
Definition TGParser.h:220
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:228
bool ParseFile()
ParseFile - Main entrypoint for parsing a tblgen file.
TGVarScope * PushScope()
Definition TGParser.h:213
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:146
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:1220
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
void PrintError(const Twine &Msg)
Definition Error.cpp:104
LetMode
Specifies how a 'let' assignment interacts with the existing field value.
Definition TGParser.h:33
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:1917
Implement std::hash so that hash_code can be used in STL containers.
Definition BitVector.h:870
#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:37
std::string Name
Definition TGParser.h:40
LetRecord(const StringInit *N, ArrayRef< unsigned > B, const Init *V, SMLoc L, LetMode M=LetMode::Replace)
Definition TGParser.h:49
const Init * Value
Definition TGParser.h:46
const StringInit * Name
Definition TGParser.h:44
std::vector< unsigned > Bits
Definition TGParser.h:45
LetMode Mode
Definition TGParser.h:48
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:56
RecordsEntry()=default
std::unique_ptr< ForeachLoop > Loop
Definition TGParser.h:58
std::unique_ptr< Record::AssertionInfo > Assertion
Definition TGParser.h:59
void dump() const
std::unique_ptr< Record::DumpInfo > Dump
Definition TGParser.h:60
std::unique_ptr< Record > Rec
Definition TGParser.h:57