1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // Implement the Parser for TableGen.
11 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/None.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Config/llvm-config.h"
19 #include "llvm/Support/Casting.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/raw_ostream.h"
23 #include "llvm/TableGen/Record.h"
30 //===----------------------------------------------------------------------===//
31 // Support Code for the Semantic Actions.
32 //===----------------------------------------------------------------------===//
36 struct SubClassReference
{
39 SmallVector
<Init
*, 4> TemplateArgs
;
41 SubClassReference() : Rec(nullptr) {}
43 bool isInvalid() const { return Rec
== nullptr; }
46 struct SubMultiClassReference
{
49 SmallVector
<Init
*, 4> TemplateArgs
;
51 SubMultiClassReference() : MC(nullptr) {}
53 bool isInvalid() const { return MC
== nullptr; }
57 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
58 LLVM_DUMP_METHOD
void SubMultiClassReference::dump() const {
59 errs() << "Multiclass:\n";
63 errs() << "Template args:\n";
64 for (Init
*TA
: TemplateArgs
)
69 } // end namespace llvm
71 static bool checkBitsConcrete(Record
&R
, const RecordVal
&RV
) {
72 BitsInit
*BV
= cast
<BitsInit
>(RV
.getValue());
73 for (unsigned i
= 0, e
= BV
->getNumBits(); i
!= e
; ++i
) {
74 Init
*Bit
= BV
->getBit(i
);
75 bool IsReference
= false;
76 if (auto VBI
= dyn_cast
<VarBitInit
>(Bit
)) {
77 if (auto VI
= dyn_cast
<VarInit
>(VBI
->getBitVar())) {
78 if (R
.getValue(VI
->getName()))
81 } else if (isa
<VarInit
>(Bit
)) {
84 if (!(IsReference
|| Bit
->isConcrete()))
90 static void checkConcrete(Record
&R
) {
91 for (const RecordVal
&RV
: R
.getValues()) {
92 // HACK: Disable this check for variables declared with 'field'. This is
93 // done merely because existing targets have legitimate cases of
94 // non-concrete variables in helper defs. Ideally, we'd introduce a
95 // 'maybe' or 'optional' modifier instead of this.
99 if (Init
*V
= RV
.getValue()) {
100 bool Ok
= isa
<BitsInit
>(V
) ? checkBitsConcrete(R
, RV
) : V
->isConcrete();
102 PrintError(R
.getLoc(),
103 Twine("Initializer of '") + RV
.getNameInitAsString() +
104 "' in '" + R
.getNameInitAsString() +
105 "' could not be fully resolved: " +
106 RV
.getValue()->getAsString());
112 /// Return an Init with a qualifier prefix referring
113 /// to CurRec's name.
114 static Init
*QualifyName(Record
&CurRec
, MultiClass
*CurMultiClass
,
115 Init
*Name
, StringRef Scoper
) {
117 BinOpInit::getStrConcat(CurRec
.getNameInit(), StringInit::get(Scoper
));
118 NewName
= BinOpInit::getStrConcat(NewName
, Name
);
119 if (CurMultiClass
&& Scoper
!= "::") {
120 Init
*Prefix
= BinOpInit::getStrConcat(CurMultiClass
->Rec
.getNameInit(),
121 StringInit::get("::"));
122 NewName
= BinOpInit::getStrConcat(Prefix
, NewName
);
125 if (BinOpInit
*BinOp
= dyn_cast
<BinOpInit
>(NewName
))
126 NewName
= BinOp
->Fold(&CurRec
);
130 /// Return the qualified version of the implicit 'NAME' template argument.
131 static Init
*QualifiedNameOfImplicitName(Record
&Rec
,
132 MultiClass
*MC
= nullptr) {
133 return QualifyName(Rec
, MC
, StringInit::get("NAME"), MC
? "::" : ":");
136 static Init
*QualifiedNameOfImplicitName(MultiClass
*MC
) {
137 return QualifiedNameOfImplicitName(MC
->Rec
, MC
);
140 bool TGParser::AddValue(Record
*CurRec
, SMLoc Loc
, const RecordVal
&RV
) {
142 CurRec
= &CurMultiClass
->Rec
;
144 if (RecordVal
*ERV
= CurRec
->getValue(RV
.getNameInit())) {
145 // The value already exists in the class, treat this as a set.
146 if (ERV
->setValue(RV
.getValue()))
147 return Error(Loc
, "New definition of '" + RV
.getName() + "' of type '" +
148 RV
.getType()->getAsString() + "' is incompatible with " +
149 "previous definition of type '" +
150 ERV
->getType()->getAsString() + "'");
152 CurRec
->addValue(RV
);
158 /// Return true on error, false on success.
159 bool TGParser::SetValue(Record
*CurRec
, SMLoc Loc
, Init
*ValName
,
160 ArrayRef
<unsigned> BitList
, Init
*V
,
161 bool AllowSelfAssignment
) {
162 if (!V
) return false;
164 if (!CurRec
) CurRec
= &CurMultiClass
->Rec
;
166 RecordVal
*RV
= CurRec
->getValue(ValName
);
168 return Error(Loc
, "Value '" + ValName
->getAsUnquotedString() +
171 // Do not allow assignments like 'X = X'. This will just cause infinite loops
172 // in the resolution machinery.
174 if (VarInit
*VI
= dyn_cast
<VarInit
>(V
))
175 if (VI
->getNameInit() == ValName
&& !AllowSelfAssignment
)
176 return Error(Loc
, "Recursion / self-assignment forbidden");
178 // If we are assigning to a subset of the bits in the value... then we must be
179 // assigning to a field of BitsRecTy, which must have a BitsInit
182 if (!BitList
.empty()) {
183 BitsInit
*CurVal
= dyn_cast
<BitsInit
>(RV
->getValue());
185 return Error(Loc
, "Value '" + ValName
->getAsUnquotedString() +
186 "' is not a bits type");
188 // Convert the incoming value to a bits type of the appropriate size...
189 Init
*BI
= V
->getCastTo(BitsRecTy::get(BitList
.size()));
191 return Error(Loc
, "Initializer is not compatible with bit range");
193 SmallVector
<Init
*, 16> NewBits(CurVal
->getNumBits());
195 // Loop over bits, assigning values as appropriate.
196 for (unsigned i
= 0, e
= BitList
.size(); i
!= e
; ++i
) {
197 unsigned Bit
= BitList
[i
];
199 return Error(Loc
, "Cannot set bit #" + Twine(Bit
) + " of value '" +
200 ValName
->getAsUnquotedString() + "' more than once");
201 NewBits
[Bit
] = BI
->getBit(i
);
204 for (unsigned i
= 0, e
= CurVal
->getNumBits(); i
!= e
; ++i
)
206 NewBits
[i
] = CurVal
->getBit(i
);
208 V
= BitsInit::get(NewBits
);
211 if (RV
->setValue(V
)) {
212 std::string InitType
;
213 if (BitsInit
*BI
= dyn_cast
<BitsInit
>(V
))
214 InitType
= (Twine("' of type bit initializer with length ") +
215 Twine(BI
->getNumBits())).str();
216 else if (TypedInit
*TI
= dyn_cast
<TypedInit
>(V
))
217 InitType
= (Twine("' of type '") + TI
->getType()->getAsString()).str();
218 return Error(Loc
, "Value '" + ValName
->getAsUnquotedString() +
219 "' of type '" + RV
->getType()->getAsString() +
220 "' is incompatible with initializer '" +
221 V
->getAsString() + InitType
+ "'");
226 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
227 /// args as SubClass's template arguments.
228 bool TGParser::AddSubClass(Record
*CurRec
, SubClassReference
&SubClass
) {
229 Record
*SC
= SubClass
.Rec
;
230 // Add all of the values in the subclass into the current class.
231 for (const RecordVal
&Val
: SC
->getValues())
232 if (AddValue(CurRec
, SubClass
.RefRange
.Start
, Val
))
235 ArrayRef
<Init
*> TArgs
= SC
->getTemplateArgs();
237 // Ensure that an appropriate number of template arguments are specified.
238 if (TArgs
.size() < SubClass
.TemplateArgs
.size())
239 return Error(SubClass
.RefRange
.Start
,
240 "More template args specified than expected");
242 // Loop over all of the template arguments, setting them to the specified
243 // value or leaving them as the default if necessary.
244 MapResolver
R(CurRec
);
246 for (unsigned i
= 0, e
= TArgs
.size(); i
!= e
; ++i
) {
247 if (i
< SubClass
.TemplateArgs
.size()) {
248 // If a value is specified for this template arg, set it now.
249 if (SetValue(CurRec
, SubClass
.RefRange
.Start
, TArgs
[i
],
250 None
, SubClass
.TemplateArgs
[i
]))
252 } else if (!CurRec
->getValue(TArgs
[i
])->getValue()->isComplete()) {
253 return Error(SubClass
.RefRange
.Start
,
254 "Value not specified for template argument #" +
255 Twine(i
) + " (" + TArgs
[i
]->getAsUnquotedString() +
256 ") of subclass '" + SC
->getNameInitAsString() + "'!");
259 R
.set(TArgs
[i
], CurRec
->getValue(TArgs
[i
])->getValue());
261 CurRec
->removeValue(TArgs
[i
]);
265 if (CurRec
->isClass())
267 VarInit::get(QualifiedNameOfImplicitName(*CurRec
), StringRecTy::get());
269 Name
= CurRec
->getNameInit();
270 R
.set(QualifiedNameOfImplicitName(*SC
), Name
);
272 CurRec
->resolveReferences(R
);
274 // Since everything went well, we can now set the "superclass" list for the
276 ArrayRef
<std::pair
<Record
*, SMRange
>> SCs
= SC
->getSuperClasses();
277 for (const auto &SCPair
: SCs
) {
278 if (CurRec
->isSubClassOf(SCPair
.first
))
279 return Error(SubClass
.RefRange
.Start
,
280 "Already subclass of '" + SCPair
.first
->getName() + "'!\n");
281 CurRec
->addSuperClass(SCPair
.first
, SCPair
.second
);
284 if (CurRec
->isSubClassOf(SC
))
285 return Error(SubClass
.RefRange
.Start
,
286 "Already subclass of '" + SC
->getName() + "'!\n");
287 CurRec
->addSuperClass(SC
, SubClass
.RefRange
);
291 bool TGParser::AddSubClass(RecordsEntry
&Entry
, SubClassReference
&SubClass
) {
293 return AddSubClass(Entry
.Rec
.get(), SubClass
);
295 for (auto &E
: Entry
.Loop
->Entries
) {
296 if (AddSubClass(E
, SubClass
))
303 /// AddSubMultiClass - Add SubMultiClass as a subclass to
304 /// CurMC, resolving its template args as SubMultiClass's
305 /// template arguments.
306 bool TGParser::AddSubMultiClass(MultiClass
*CurMC
,
307 SubMultiClassReference
&SubMultiClass
) {
308 MultiClass
*SMC
= SubMultiClass
.MC
;
310 ArrayRef
<Init
*> SMCTArgs
= SMC
->Rec
.getTemplateArgs();
311 if (SMCTArgs
.size() < SubMultiClass
.TemplateArgs
.size())
312 return Error(SubMultiClass
.RefRange
.Start
,
313 "More template args specified than expected");
315 // Prepare the mapping of template argument name to value, filling in default
316 // values if necessary.
317 SubstStack TemplateArgs
;
318 for (unsigned i
= 0, e
= SMCTArgs
.size(); i
!= e
; ++i
) {
319 if (i
< SubMultiClass
.TemplateArgs
.size()) {
320 TemplateArgs
.emplace_back(SMCTArgs
[i
], SubMultiClass
.TemplateArgs
[i
]);
322 Init
*Default
= SMC
->Rec
.getValue(SMCTArgs
[i
])->getValue();
323 if (!Default
->isComplete()) {
324 return Error(SubMultiClass
.RefRange
.Start
,
325 "value not specified for template argument #" + Twine(i
) +
326 " (" + SMCTArgs
[i
]->getAsUnquotedString() +
327 ") of multiclass '" + SMC
->Rec
.getNameInitAsString() +
330 TemplateArgs
.emplace_back(SMCTArgs
[i
], Default
);
334 TemplateArgs
.emplace_back(
335 QualifiedNameOfImplicitName(SMC
),
336 VarInit::get(QualifiedNameOfImplicitName(CurMC
), StringRecTy::get()));
338 // Add all of the defs in the subclass into the current multiclass.
339 return resolve(SMC
->Entries
, TemplateArgs
, false, &CurMC
->Entries
);
342 /// Add a record or foreach loop to the current context (global record keeper,
343 /// current inner-most foreach loop, or multiclass).
344 bool TGParser::addEntry(RecordsEntry E
) {
345 assert(!E
.Rec
|| !E
.Loop
);
347 if (!Loops
.empty()) {
348 Loops
.back()->Entries
.push_back(std::move(E
));
354 return resolve(*E
.Loop
, Stack
, CurMultiClass
== nullptr,
355 CurMultiClass
? &CurMultiClass
->Entries
: nullptr);
359 CurMultiClass
->Entries
.push_back(std::move(E
));
363 return addDefOne(std::move(E
.Rec
));
366 /// Resolve the entries in \p Loop, going over inner loops recursively
367 /// and making the given subsitutions of (name, value) pairs.
369 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
370 /// are added to the global record keeper.
371 bool TGParser::resolve(const ForeachLoop
&Loop
, SubstStack
&Substs
,
372 bool Final
, std::vector
<RecordsEntry
> *Dest
,
375 for (const auto &S
: Substs
)
376 R
.set(S
.first
, S
.second
);
377 Init
*List
= Loop
.ListValue
->resolveReferences(R
);
378 auto LI
= dyn_cast
<ListInit
>(List
);
381 Dest
->emplace_back(make_unique
<ForeachLoop
>(Loop
.Loc
, Loop
.IterVar
,
383 return resolve(Loop
.Entries
, Substs
, Final
, &Dest
->back().Loop
->Entries
,
387 PrintError(Loop
.Loc
, Twine("attempting to loop over '") +
388 List
->getAsString() + "', expected a list");
393 for (auto Elt
: *LI
) {
394 Substs
.emplace_back(Loop
.IterVar
->getNameInit(), Elt
);
395 Error
= resolve(Loop
.Entries
, Substs
, Final
, Dest
);
403 /// Resolve the entries in \p Source, going over loops recursively and
404 /// making the given substitutions of (name, value) pairs.
406 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
407 /// are added to the global record keeper.
408 bool TGParser::resolve(const std::vector
<RecordsEntry
> &Source
,
409 SubstStack
&Substs
, bool Final
,
410 std::vector
<RecordsEntry
> *Dest
, SMLoc
*Loc
) {
412 for (auto &E
: Source
) {
414 Error
= resolve(*E
.Loop
, Substs
, Final
, Dest
);
416 auto Rec
= make_unique
<Record
>(*E
.Rec
);
418 Rec
->appendLoc(*Loc
);
420 MapResolver
R(Rec
.get());
421 for (const auto &S
: Substs
)
422 R
.set(S
.first
, S
.second
);
423 Rec
->resolveReferences(R
);
426 Dest
->push_back(std::move(Rec
));
428 Error
= addDefOne(std::move(Rec
));
436 /// Resolve the record fully and add it to the record keeper.
437 bool TGParser::addDefOne(std::unique_ptr
<Record
> Rec
) {
438 if (Record
*Prev
= Records
.getDef(Rec
->getNameInitAsString())) {
439 if (!Rec
->isAnonymous()) {
440 PrintError(Rec
->getLoc(),
441 "def already exists: " + Rec
->getNameInitAsString());
442 PrintNote(Prev
->getLoc(), "location of previous definition");
445 Rec
->setName(Records
.getNewAnonymousName());
448 Rec
->resolveReferences();
451 if (!isa
<StringInit
>(Rec
->getNameInit())) {
452 PrintError(Rec
->getLoc(), Twine("record name '") +
453 Rec
->getNameInit()->getAsString() +
454 "' could not be fully resolved");
458 // If ObjectBody has template arguments, it's an error.
459 assert(Rec
->getTemplateArgs().empty() && "How'd this get template args?");
461 for (DefsetRecord
*Defset
: Defsets
) {
462 DefInit
*I
= Rec
->getDefInit();
463 if (!I
->getType()->typeIsA(Defset
->EltTy
)) {
464 PrintError(Rec
->getLoc(), Twine("adding record of incompatible type '") +
465 I
->getType()->getAsString() +
467 PrintNote(Defset
->Loc
, "location of defset declaration");
470 Defset
->Elements
.push_back(I
);
473 Records
.addDef(std::move(Rec
));
477 //===----------------------------------------------------------------------===//
479 //===----------------------------------------------------------------------===//
481 /// isObjectStart - Return true if this is a valid first token for an Object.
482 static bool isObjectStart(tgtok::TokKind K
) {
483 return K
== tgtok::Class
|| K
== tgtok::Def
|| K
== tgtok::Defm
||
484 K
== tgtok::Let
|| K
== tgtok::MultiClass
|| K
== tgtok::Foreach
||
488 /// ParseObjectName - If a valid object name is specified, return it. If no
489 /// name is specified, return the unset initializer. Return nullptr on parse
491 /// ObjectName ::= Value [ '#' Value ]*
492 /// ObjectName ::= /*empty*/
494 Init
*TGParser::ParseObjectName(MultiClass
*CurMultiClass
) {
495 switch (Lex
.getCode()) {
499 // These are all of the tokens that can begin an object body.
500 // Some of these can also begin values but we disallow those cases
501 // because they are unlikely to be useful.
502 return UnsetInit::get();
507 Record
*CurRec
= nullptr;
509 CurRec
= &CurMultiClass
->Rec
;
511 Init
*Name
= ParseValue(CurRec
, StringRecTy::get(), ParseNameMode
);
516 Init
*NameStr
= QualifiedNameOfImplicitName(CurMultiClass
);
517 HasReferenceResolver
R(NameStr
);
518 Name
->resolveReferences(R
);
520 Name
= BinOpInit::getStrConcat(VarInit::get(NameStr
, StringRecTy::get()),
527 /// ParseClassID - Parse and resolve a reference to a class name. This returns
532 Record
*TGParser::ParseClassID() {
533 if (Lex
.getCode() != tgtok::Id
) {
534 TokError("expected name for ClassID");
538 Record
*Result
= Records
.getClass(Lex
.getCurStrVal());
540 TokError("Couldn't find class '" + Lex
.getCurStrVal() + "'");
546 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
547 /// This returns null on error.
549 /// MultiClassID ::= ID
551 MultiClass
*TGParser::ParseMultiClassID() {
552 if (Lex
.getCode() != tgtok::Id
) {
553 TokError("expected name for MultiClassID");
557 MultiClass
*Result
= MultiClasses
[Lex
.getCurStrVal()].get();
559 TokError("Couldn't find multiclass '" + Lex
.getCurStrVal() + "'");
565 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
566 /// subclass. This returns a SubClassRefTy with a null Record* on error.
568 /// SubClassRef ::= ClassID
569 /// SubClassRef ::= ClassID '<' ValueList '>'
571 SubClassReference
TGParser::
572 ParseSubClassReference(Record
*CurRec
, bool isDefm
) {
573 SubClassReference Result
;
574 Result
.RefRange
.Start
= Lex
.getLoc();
577 if (MultiClass
*MC
= ParseMultiClassID())
578 Result
.Rec
= &MC
->Rec
;
580 Result
.Rec
= ParseClassID();
582 if (!Result
.Rec
) return Result
;
584 // If there is no template arg list, we're done.
585 if (Lex
.getCode() != tgtok::less
) {
586 Result
.RefRange
.End
= Lex
.getLoc();
589 Lex
.Lex(); // Eat the '<'
591 if (Lex
.getCode() == tgtok::greater
) {
592 TokError("subclass reference requires a non-empty list of template values");
593 Result
.Rec
= nullptr;
597 ParseValueList(Result
.TemplateArgs
, CurRec
, Result
.Rec
);
598 if (Result
.TemplateArgs
.empty()) {
599 Result
.Rec
= nullptr; // Error parsing value list.
603 if (Lex
.getCode() != tgtok::greater
) {
604 TokError("expected '>' in template value list");
605 Result
.Rec
= nullptr;
609 Result
.RefRange
.End
= Lex
.getLoc();
614 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
615 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
616 /// Record* on error.
618 /// SubMultiClassRef ::= MultiClassID
619 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
621 SubMultiClassReference
TGParser::
622 ParseSubMultiClassReference(MultiClass
*CurMC
) {
623 SubMultiClassReference Result
;
624 Result
.RefRange
.Start
= Lex
.getLoc();
626 Result
.MC
= ParseMultiClassID();
627 if (!Result
.MC
) return Result
;
629 // If there is no template arg list, we're done.
630 if (Lex
.getCode() != tgtok::less
) {
631 Result
.RefRange
.End
= Lex
.getLoc();
634 Lex
.Lex(); // Eat the '<'
636 if (Lex
.getCode() == tgtok::greater
) {
637 TokError("subclass reference requires a non-empty list of template values");
642 ParseValueList(Result
.TemplateArgs
, &CurMC
->Rec
, &Result
.MC
->Rec
);
643 if (Result
.TemplateArgs
.empty()) {
644 Result
.MC
= nullptr; // Error parsing value list.
648 if (Lex
.getCode() != tgtok::greater
) {
649 TokError("expected '>' in template value list");
654 Result
.RefRange
.End
= Lex
.getLoc();
659 /// ParseRangePiece - Parse a bit/value range.
660 /// RangePiece ::= INTVAL
661 /// RangePiece ::= INTVAL '-' INTVAL
662 /// RangePiece ::= INTVAL INTVAL
663 bool TGParser::ParseRangePiece(SmallVectorImpl
<unsigned> &Ranges
) {
664 if (Lex
.getCode() != tgtok::IntVal
) {
665 TokError("expected integer or bitrange");
668 int64_t Start
= Lex
.getCurIntVal();
672 return TokError("invalid range, cannot be negative");
674 switch (Lex
.Lex()) { // eat first character.
676 Ranges
.push_back(Start
);
679 if (Lex
.Lex() != tgtok::IntVal
) {
680 TokError("expected integer value as end of range");
683 End
= Lex
.getCurIntVal();
686 End
= -Lex
.getCurIntVal();
690 return TokError("invalid range, cannot be negative");
695 for (; Start
<= End
; ++Start
)
696 Ranges
.push_back(Start
);
698 for (; Start
>= End
; --Start
)
699 Ranges
.push_back(Start
);
703 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
705 /// RangeList ::= RangePiece (',' RangePiece)*
707 void TGParser::ParseRangeList(SmallVectorImpl
<unsigned> &Result
) {
708 // Parse the first piece.
709 if (ParseRangePiece(Result
)) {
713 while (Lex
.getCode() == tgtok::comma
) {
714 Lex
.Lex(); // Eat the comma.
716 // Parse the next range piece.
717 if (ParseRangePiece(Result
)) {
724 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
725 /// OptionalRangeList ::= '<' RangeList '>'
726 /// OptionalRangeList ::= /*empty*/
727 bool TGParser::ParseOptionalRangeList(SmallVectorImpl
<unsigned> &Ranges
) {
728 if (Lex
.getCode() != tgtok::less
)
731 SMLoc StartLoc
= Lex
.getLoc();
732 Lex
.Lex(); // eat the '<'
734 // Parse the range list.
735 ParseRangeList(Ranges
);
736 if (Ranges
.empty()) return true;
738 if (Lex
.getCode() != tgtok::greater
) {
739 TokError("expected '>' at end of range list");
740 return Error(StartLoc
, "to match this '<'");
742 Lex
.Lex(); // eat the '>'.
746 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
747 /// OptionalBitList ::= '{' RangeList '}'
748 /// OptionalBitList ::= /*empty*/
749 bool TGParser::ParseOptionalBitList(SmallVectorImpl
<unsigned> &Ranges
) {
750 if (Lex
.getCode() != tgtok::l_brace
)
753 SMLoc StartLoc
= Lex
.getLoc();
754 Lex
.Lex(); // eat the '{'
756 // Parse the range list.
757 ParseRangeList(Ranges
);
758 if (Ranges
.empty()) return true;
760 if (Lex
.getCode() != tgtok::r_brace
) {
761 TokError("expected '}' at end of bit list");
762 return Error(StartLoc
, "to match this '{'");
764 Lex
.Lex(); // eat the '}'.
768 /// ParseType - Parse and return a tblgen type. This returns null on error.
770 /// Type ::= STRING // string type
771 /// Type ::= CODE // code type
772 /// Type ::= BIT // bit type
773 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
774 /// Type ::= INT // int type
775 /// Type ::= LIST '<' Type '>' // list<x> type
776 /// Type ::= DAG // dag type
777 /// Type ::= ClassID // Record Type
779 RecTy
*TGParser::ParseType() {
780 switch (Lex
.getCode()) {
781 default: TokError("Unknown token when expecting a type"); return nullptr;
782 case tgtok::String
: Lex
.Lex(); return StringRecTy::get();
783 case tgtok::Code
: Lex
.Lex(); return CodeRecTy::get();
784 case tgtok::Bit
: Lex
.Lex(); return BitRecTy::get();
785 case tgtok::Int
: Lex
.Lex(); return IntRecTy::get();
786 case tgtok::Dag
: Lex
.Lex(); return DagRecTy::get();
788 if (Record
*R
= ParseClassID()) return RecordRecTy::get(R
);
789 TokError("unknown class name");
792 if (Lex
.Lex() != tgtok::less
) { // Eat 'bits'
793 TokError("expected '<' after bits type");
796 if (Lex
.Lex() != tgtok::IntVal
) { // Eat '<'
797 TokError("expected integer in bits<n> type");
800 uint64_t Val
= Lex
.getCurIntVal();
801 if (Lex
.Lex() != tgtok::greater
) { // Eat count.
802 TokError("expected '>' at end of bits<n> type");
805 Lex
.Lex(); // Eat '>'
806 return BitsRecTy::get(Val
);
809 if (Lex
.Lex() != tgtok::less
) { // Eat 'bits'
810 TokError("expected '<' after list type");
813 Lex
.Lex(); // Eat '<'
814 RecTy
*SubType
= ParseType();
815 if (!SubType
) return nullptr;
817 if (Lex
.getCode() != tgtok::greater
) {
818 TokError("expected '>' at end of list<ty> type");
821 Lex
.Lex(); // Eat '>'
822 return ListRecTy::get(SubType
);
827 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
828 /// has already been read.
829 Init
*TGParser::ParseIDValue(Record
*CurRec
, StringInit
*Name
, SMLoc NameLoc
,
832 if (const RecordVal
*RV
= CurRec
->getValue(Name
))
833 return VarInit::get(Name
, RV
->getType());
836 if ((CurRec
&& CurRec
->isClass()) || CurMultiClass
) {
837 Init
*TemplateArgName
;
840 QualifyName(CurMultiClass
->Rec
, CurMultiClass
, Name
, "::");
842 TemplateArgName
= QualifyName(*CurRec
, CurMultiClass
, Name
, ":");
844 Record
*TemplateRec
= CurMultiClass
? &CurMultiClass
->Rec
: CurRec
;
845 if (TemplateRec
->isTemplateArg(TemplateArgName
)) {
846 const RecordVal
*RV
= TemplateRec
->getValue(TemplateArgName
);
847 assert(RV
&& "Template arg doesn't exist??");
848 return VarInit::get(TemplateArgName
, RV
->getType());
849 } else if (Name
->getValue() == "NAME") {
850 return VarInit::get(TemplateArgName
, StringRecTy::get());
854 // If this is in a foreach loop, make sure it's not a loop iterator
855 for (const auto &L
: Loops
) {
856 VarInit
*IterVar
= dyn_cast
<VarInit
>(L
->IterVar
);
857 if (IterVar
&& IterVar
->getNameInit() == Name
)
861 if (Mode
== ParseNameMode
)
864 if (Init
*I
= Records
.getGlobal(Name
->getValue()))
867 // Allow self-references of concrete defs, but delay the lookup so that we
868 // get the correct type.
869 if (CurRec
&& !CurRec
->isClass() && !CurMultiClass
&&
870 CurRec
->getNameInit() == Name
)
871 return UnOpInit::get(UnOpInit::CAST
, Name
, CurRec
->getType());
873 Error(NameLoc
, "Variable not defined: '" + Name
->getValue() + "'");
877 /// ParseOperation - Parse an operator. This returns null on error.
879 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
881 Init
*TGParser::ParseOperation(Record
*CurRec
, RecTy
*ItemType
) {
882 switch (Lex
.getCode()) {
884 TokError("unknown operation");
890 case tgtok::XCast
: { // Value ::= !unop '(' Value ')'
891 UnOpInit::UnaryOp Code
;
892 RecTy
*Type
= nullptr;
894 switch (Lex
.getCode()) {
895 default: llvm_unreachable("Unhandled code!");
897 Lex
.Lex(); // eat the operation
898 Code
= UnOpInit::CAST
;
900 Type
= ParseOperatorType();
903 TokError("did not get type for unary operator");
909 Lex
.Lex(); // eat the operation
910 Code
= UnOpInit::HEAD
;
913 Lex
.Lex(); // eat the operation
914 Code
= UnOpInit::TAIL
;
918 Code
= UnOpInit::SIZE
;
919 Type
= IntRecTy::get();
922 Lex
.Lex(); // eat the operation
923 Code
= UnOpInit::EMPTY
;
924 Type
= IntRecTy::get();
927 if (Lex
.getCode() != tgtok::l_paren
) {
928 TokError("expected '(' after unary operator");
931 Lex
.Lex(); // eat the '('
933 Init
*LHS
= ParseValue(CurRec
);
934 if (!LHS
) return nullptr;
936 if (Code
== UnOpInit::HEAD
||
937 Code
== UnOpInit::TAIL
||
938 Code
== UnOpInit::EMPTY
) {
939 ListInit
*LHSl
= dyn_cast
<ListInit
>(LHS
);
940 StringInit
*LHSs
= dyn_cast
<StringInit
>(LHS
);
941 TypedInit
*LHSt
= dyn_cast
<TypedInit
>(LHS
);
942 if (!LHSl
&& !LHSs
&& !LHSt
) {
943 TokError("expected list or string type argument in unary operator");
947 ListRecTy
*LType
= dyn_cast
<ListRecTy
>(LHSt
->getType());
948 StringRecTy
*SType
= dyn_cast
<StringRecTy
>(LHSt
->getType());
949 if (!LType
&& !SType
) {
950 TokError("expected list or string type argument in unary operator");
955 if (Code
== UnOpInit::HEAD
|| Code
== UnOpInit::TAIL
||
956 Code
== UnOpInit::SIZE
) {
957 if (!LHSl
&& !LHSt
) {
958 TokError("expected list type argument in unary operator");
963 if (Code
== UnOpInit::HEAD
|| Code
== UnOpInit::TAIL
) {
964 if (LHSl
&& LHSl
->empty()) {
965 TokError("empty list argument in unary operator");
969 Init
*Item
= LHSl
->getElement(0);
970 TypedInit
*Itemt
= dyn_cast
<TypedInit
>(Item
);
972 TokError("untyped list element in unary operator");
975 Type
= (Code
== UnOpInit::HEAD
) ? Itemt
->getType()
976 : ListRecTy::get(Itemt
->getType());
978 assert(LHSt
&& "expected list type argument in unary operator");
979 ListRecTy
*LType
= dyn_cast
<ListRecTy
>(LHSt
->getType());
981 TokError("expected list type argument in unary operator");
984 Type
= (Code
== UnOpInit::HEAD
) ? LType
->getElementType() : LType
;
989 if (Lex
.getCode() != tgtok::r_paren
) {
990 TokError("expected ')' in unary operator");
993 Lex
.Lex(); // eat the ')'
994 return (UnOpInit::get(Code
, LHS
, Type
))->Fold(CurRec
);
998 // Value ::= !isa '<' Type '>' '(' Value ')'
999 Lex
.Lex(); // eat the operation
1001 RecTy
*Type
= ParseOperatorType();
1005 if (Lex
.getCode() != tgtok::l_paren
) {
1006 TokError("expected '(' after type of !isa");
1009 Lex
.Lex(); // eat the '('
1011 Init
*LHS
= ParseValue(CurRec
);
1015 if (Lex
.getCode() != tgtok::r_paren
) {
1016 TokError("expected ')' in !isa");
1019 Lex
.Lex(); // eat the ')'
1021 return (IsAOpInit::get(Type
, LHS
))->Fold();
1024 case tgtok::XConcat
:
1037 case tgtok::XListConcat
:
1038 case tgtok::XStrConcat
: { // Value ::= !binop '(' Value ',' Value ')'
1039 tgtok::TokKind OpTok
= Lex
.getCode();
1040 SMLoc OpLoc
= Lex
.getLoc();
1041 Lex
.Lex(); // eat the operation
1043 BinOpInit::BinaryOp Code
;
1045 default: llvm_unreachable("Unhandled code!");
1046 case tgtok::XConcat
: Code
= BinOpInit::CONCAT
; break;
1047 case tgtok::XADD
: Code
= BinOpInit::ADD
; break;
1048 case tgtok::XAND
: Code
= BinOpInit::AND
; break;
1049 case tgtok::XOR
: Code
= BinOpInit::OR
; break;
1050 case tgtok::XSRA
: Code
= BinOpInit::SRA
; break;
1051 case tgtok::XSRL
: Code
= BinOpInit::SRL
; break;
1052 case tgtok::XSHL
: Code
= BinOpInit::SHL
; break;
1053 case tgtok::XEq
: Code
= BinOpInit::EQ
; break;
1054 case tgtok::XNe
: Code
= BinOpInit::NE
; break;
1055 case tgtok::XLe
: Code
= BinOpInit::LE
; break;
1056 case tgtok::XLt
: Code
= BinOpInit::LT
; break;
1057 case tgtok::XGe
: Code
= BinOpInit::GE
; break;
1058 case tgtok::XGt
: Code
= BinOpInit::GT
; break;
1059 case tgtok::XListConcat
: Code
= BinOpInit::LISTCONCAT
; break;
1060 case tgtok::XStrConcat
: Code
= BinOpInit::STRCONCAT
; break;
1063 RecTy
*Type
= nullptr;
1064 RecTy
*ArgType
= nullptr;
1067 llvm_unreachable("Unhandled code!");
1068 case tgtok::XConcat
:
1069 Type
= DagRecTy::get();
1070 ArgType
= DagRecTy::get();
1078 Type
= IntRecTy::get();
1079 ArgType
= IntRecTy::get();
1083 Type
= BitRecTy::get();
1084 // ArgType for Eq / Ne is not known at this point
1090 Type
= BitRecTy::get();
1091 ArgType
= IntRecTy::get();
1093 case tgtok::XListConcat
:
1094 // We don't know the list type until we parse the first argument
1097 case tgtok::XStrConcat
:
1098 Type
= StringRecTy::get();
1099 ArgType
= StringRecTy::get();
1103 if (Type
&& ItemType
&& !Type
->typeIsConvertibleTo(ItemType
)) {
1104 Error(OpLoc
, Twine("expected value of type '") +
1105 ItemType
->getAsString() + "', got '" +
1106 Type
->getAsString() + "'");
1110 if (Lex
.getCode() != tgtok::l_paren
) {
1111 TokError("expected '(' after binary operator");
1114 Lex
.Lex(); // eat the '('
1116 SmallVector
<Init
*, 2> InitList
;
1119 SMLoc InitLoc
= Lex
.getLoc();
1120 InitList
.push_back(ParseValue(CurRec
, ArgType
));
1121 if (!InitList
.back()) return nullptr;
1123 // All BinOps require their arguments to be of compatible types.
1124 TypedInit
*TI
= dyn_cast
<TypedInit
>(InitList
.back());
1126 ArgType
= TI
->getType();
1129 case BinOpInit::LISTCONCAT
:
1130 if (!isa
<ListRecTy
>(ArgType
)) {
1131 Error(InitLoc
, Twine("expected a list, got value of type '") +
1132 ArgType
->getAsString() + "'");
1138 if (!ArgType
->typeIsConvertibleTo(IntRecTy::get()) &&
1139 !ArgType
->typeIsConvertibleTo(StringRecTy::get())) {
1140 Error(InitLoc
, Twine("expected int, bits, or string; got value of "
1141 "type '") + ArgType
->getAsString() + "'");
1145 default: llvm_unreachable("other ops have fixed argument types");
1148 RecTy
*Resolved
= resolveTypes(ArgType
, TI
->getType());
1150 Error(InitLoc
, Twine("expected value of type '") +
1151 ArgType
->getAsString() + "', got '" +
1152 TI
->getType()->getAsString() + "'");
1155 if (Code
!= BinOpInit::ADD
&& Code
!= BinOpInit::AND
&&
1156 Code
!= BinOpInit::OR
&& Code
!= BinOpInit::SRA
&&
1157 Code
!= BinOpInit::SRL
&& Code
!= BinOpInit::SHL
)
1161 if (Lex
.getCode() != tgtok::comma
)
1163 Lex
.Lex(); // eat the ','
1166 if (Lex
.getCode() != tgtok::r_paren
) {
1167 TokError("expected ')' in operator");
1170 Lex
.Lex(); // eat the ')'
1172 if (Code
== BinOpInit::LISTCONCAT
)
1175 // We allow multiple operands to associative operators like !strconcat as
1176 // shorthand for nesting them.
1177 if (Code
== BinOpInit::STRCONCAT
|| Code
== BinOpInit::LISTCONCAT
||
1178 Code
== BinOpInit::CONCAT
|| Code
== BinOpInit::ADD
||
1179 Code
== BinOpInit::AND
|| Code
== BinOpInit::OR
) {
1180 while (InitList
.size() > 2) {
1181 Init
*RHS
= InitList
.pop_back_val();
1182 RHS
= (BinOpInit::get(Code
, InitList
.back(), RHS
, Type
))->Fold(CurRec
);
1183 InitList
.back() = RHS
;
1187 if (InitList
.size() == 2)
1188 return (BinOpInit::get(Code
, InitList
[0], InitList
[1], Type
))
1191 Error(OpLoc
, "expected two operands to operator");
1195 case tgtok::XForEach
: { // Value ::= !foreach '(' Id ',' Value ',' Value ')'
1196 SMLoc OpLoc
= Lex
.getLoc();
1197 Lex
.Lex(); // eat the operation
1198 if (Lex
.getCode() != tgtok::l_paren
) {
1199 TokError("expected '(' after !foreach");
1203 if (Lex
.Lex() != tgtok::Id
) { // eat the '('
1204 TokError("first argument of !foreach must be an identifier");
1208 Init
*LHS
= StringInit::get(Lex
.getCurStrVal());
1210 if (CurRec
&& CurRec
->getValue(LHS
)) {
1211 TokError((Twine("iteration variable '") + LHS
->getAsString() +
1212 "' already defined")
1217 if (Lex
.Lex() != tgtok::comma
) { // eat the id
1218 TokError("expected ',' in ternary operator");
1221 Lex
.Lex(); // eat the ','
1223 Init
*MHS
= ParseValue(CurRec
);
1227 if (Lex
.getCode() != tgtok::comma
) {
1228 TokError("expected ',' in ternary operator");
1231 Lex
.Lex(); // eat the ','
1233 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
1235 TokError("could not get type of !foreach input");
1239 RecTy
*InEltType
= nullptr;
1240 RecTy
*OutEltType
= nullptr;
1243 if (ListRecTy
*InListTy
= dyn_cast
<ListRecTy
>(MHSt
->getType())) {
1244 InEltType
= InListTy
->getElementType();
1246 if (ListRecTy
*OutListTy
= dyn_cast
<ListRecTy
>(ItemType
)) {
1247 OutEltType
= OutListTy
->getElementType();
1250 "expected value of type '" + Twine(ItemType
->getAsString()) +
1251 "', but got !foreach of list type");
1255 } else if (DagRecTy
*InDagTy
= dyn_cast
<DagRecTy
>(MHSt
->getType())) {
1256 InEltType
= InDagTy
;
1257 if (ItemType
&& !isa
<DagRecTy
>(ItemType
)) {
1259 "expected value of type '" + Twine(ItemType
->getAsString()) +
1260 "', but got !foreach of dag type");
1265 TokError("!foreach must have list or dag input");
1269 // We need to create a temporary record to provide a scope for the iteration
1270 // variable while parsing top-level foreach's.
1271 std::unique_ptr
<Record
> ParseRecTmp
;
1272 Record
*ParseRec
= CurRec
;
1274 ParseRecTmp
= make_unique
<Record
>(".parse", ArrayRef
<SMLoc
>{}, Records
);
1275 ParseRec
= ParseRecTmp
.get();
1278 ParseRec
->addValue(RecordVal(LHS
, InEltType
, false));
1279 Init
*RHS
= ParseValue(ParseRec
, OutEltType
);
1280 ParseRec
->removeValue(LHS
);
1284 if (Lex
.getCode() != tgtok::r_paren
) {
1285 TokError("expected ')' in binary operator");
1288 Lex
.Lex(); // eat the ')'
1292 OutType
= InEltType
;
1294 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
1296 TokError("could not get type of !foreach result");
1299 OutType
= RHSt
->getType()->getListTy();
1302 return (TernOpInit::get(TernOpInit::FOREACH
, LHS
, MHS
, RHS
, OutType
))
1308 case tgtok::XSubst
: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1309 TernOpInit::TernaryOp Code
;
1310 RecTy
*Type
= nullptr;
1312 tgtok::TokKind LexCode
= Lex
.getCode();
1313 Lex
.Lex(); // eat the operation
1315 default: llvm_unreachable("Unhandled code!");
1317 Code
= TernOpInit::DAG
;
1318 Type
= DagRecTy::get();
1322 Code
= TernOpInit::IF
;
1325 Code
= TernOpInit::SUBST
;
1328 if (Lex
.getCode() != tgtok::l_paren
) {
1329 TokError("expected '(' after ternary operator");
1332 Lex
.Lex(); // eat the '('
1334 Init
*LHS
= ParseValue(CurRec
);
1335 if (!LHS
) return nullptr;
1337 if (Lex
.getCode() != tgtok::comma
) {
1338 TokError("expected ',' in ternary operator");
1341 Lex
.Lex(); // eat the ','
1343 SMLoc MHSLoc
= Lex
.getLoc();
1344 Init
*MHS
= ParseValue(CurRec
, ItemType
);
1348 if (Lex
.getCode() != tgtok::comma
) {
1349 TokError("expected ',' in ternary operator");
1352 Lex
.Lex(); // eat the ','
1354 SMLoc RHSLoc
= Lex
.getLoc();
1355 Init
*RHS
= ParseValue(CurRec
, ItemType
);
1359 if (Lex
.getCode() != tgtok::r_paren
) {
1360 TokError("expected ')' in binary operator");
1363 Lex
.Lex(); // eat the ')'
1366 default: llvm_unreachable("Unhandled code!");
1368 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
1369 if (!MHSt
&& !isa
<UnsetInit
>(MHS
)) {
1370 Error(MHSLoc
, "could not determine type of the child list in !dag");
1373 if (MHSt
&& !isa
<ListRecTy
>(MHSt
->getType())) {
1374 Error(MHSLoc
, Twine("expected list of children, got type '") +
1375 MHSt
->getType()->getAsString() + "'");
1379 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
1380 if (!RHSt
&& !isa
<UnsetInit
>(RHS
)) {
1381 Error(RHSLoc
, "could not determine type of the name list in !dag");
1384 if (RHSt
&& StringRecTy::get()->getListTy() != RHSt
->getType()) {
1385 Error(RHSLoc
, Twine("expected list<string>, got type '") +
1386 RHSt
->getType()->getAsString() + "'");
1390 if (!MHSt
&& !RHSt
) {
1392 "cannot have both unset children and unset names in !dag");
1398 RecTy
*MHSTy
= nullptr;
1399 RecTy
*RHSTy
= nullptr;
1401 if (TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
))
1402 MHSTy
= MHSt
->getType();
1403 if (BitsInit
*MHSbits
= dyn_cast
<BitsInit
>(MHS
))
1404 MHSTy
= BitsRecTy::get(MHSbits
->getNumBits());
1405 if (isa
<BitInit
>(MHS
))
1406 MHSTy
= BitRecTy::get();
1408 if (TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
))
1409 RHSTy
= RHSt
->getType();
1410 if (BitsInit
*RHSbits
= dyn_cast
<BitsInit
>(RHS
))
1411 RHSTy
= BitsRecTy::get(RHSbits
->getNumBits());
1412 if (isa
<BitInit
>(RHS
))
1413 RHSTy
= BitRecTy::get();
1415 // For UnsetInit, it's typed from the other hand.
1416 if (isa
<UnsetInit
>(MHS
))
1418 if (isa
<UnsetInit
>(RHS
))
1421 if (!MHSTy
|| !RHSTy
) {
1422 TokError("could not get type for !if");
1426 Type
= resolveTypes(MHSTy
, RHSTy
);
1428 TokError(Twine("inconsistent types '") + MHSTy
->getAsString() +
1429 "' and '" + RHSTy
->getAsString() + "' for !if");
1434 case tgtok::XSubst
: {
1435 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
1437 TokError("could not get type for !subst");
1440 Type
= RHSt
->getType();
1444 return (TernOpInit::get(Code
, LHS
, MHS
, RHS
, Type
))->Fold(CurRec
);
1448 return ParseOperationCond(CurRec
, ItemType
);
1450 case tgtok::XFoldl
: {
1451 // Value ::= !foldl '(' Id ',' Id ',' Value ',' Value ',' Value ')'
1452 Lex
.Lex(); // eat the operation
1453 if (Lex
.getCode() != tgtok::l_paren
) {
1454 TokError("expected '(' after !foldl");
1457 Lex
.Lex(); // eat the '('
1459 Init
*StartUntyped
= ParseValue(CurRec
);
1463 TypedInit
*Start
= dyn_cast
<TypedInit
>(StartUntyped
);
1465 TokError(Twine("could not get type of !foldl start: '") +
1466 StartUntyped
->getAsString() + "'");
1470 if (Lex
.getCode() != tgtok::comma
) {
1471 TokError("expected ',' in !foldl");
1474 Lex
.Lex(); // eat the ','
1476 Init
*ListUntyped
= ParseValue(CurRec
);
1480 TypedInit
*List
= dyn_cast
<TypedInit
>(ListUntyped
);
1482 TokError(Twine("could not get type of !foldl list: '") +
1483 ListUntyped
->getAsString() + "'");
1487 ListRecTy
*ListType
= dyn_cast
<ListRecTy
>(List
->getType());
1489 TokError(Twine("!foldl list must be a list, but is of type '") +
1490 List
->getType()->getAsString());
1494 if (Lex
.getCode() != tgtok::comma
) {
1495 TokError("expected ',' in !foldl");
1499 if (Lex
.Lex() != tgtok::Id
) { // eat the ','
1500 TokError("third argument of !foldl must be an identifier");
1504 Init
*A
= StringInit::get(Lex
.getCurStrVal());
1505 if (CurRec
&& CurRec
->getValue(A
)) {
1506 TokError((Twine("left !foldl variable '") + A
->getAsString() +
1507 "' already defined")
1512 if (Lex
.Lex() != tgtok::comma
) { // eat the id
1513 TokError("expected ',' in !foldl");
1517 if (Lex
.Lex() != tgtok::Id
) { // eat the ','
1518 TokError("fourth argument of !foldl must be an identifier");
1522 Init
*B
= StringInit::get(Lex
.getCurStrVal());
1523 if (CurRec
&& CurRec
->getValue(B
)) {
1524 TokError((Twine("right !foldl variable '") + B
->getAsString() +
1525 "' already defined")
1530 if (Lex
.Lex() != tgtok::comma
) { // eat the id
1531 TokError("expected ',' in !foldl");
1534 Lex
.Lex(); // eat the ','
1536 // We need to create a temporary record to provide a scope for the iteration
1537 // variable while parsing top-level foreach's.
1538 std::unique_ptr
<Record
> ParseRecTmp
;
1539 Record
*ParseRec
= CurRec
;
1541 ParseRecTmp
= make_unique
<Record
>(".parse", ArrayRef
<SMLoc
>{}, Records
);
1542 ParseRec
= ParseRecTmp
.get();
1545 ParseRec
->addValue(RecordVal(A
, Start
->getType(), false));
1546 ParseRec
->addValue(RecordVal(B
, ListType
->getElementType(), false));
1547 Init
*ExprUntyped
= ParseValue(ParseRec
);
1548 ParseRec
->removeValue(A
);
1549 ParseRec
->removeValue(B
);
1553 TypedInit
*Expr
= dyn_cast
<TypedInit
>(ExprUntyped
);
1555 TokError("could not get type of !foldl expression");
1559 if (Expr
->getType() != Start
->getType()) {
1560 TokError(Twine("!foldl expression must be of same type as start (") +
1561 Start
->getType()->getAsString() + "), but is of type " +
1562 Expr
->getType()->getAsString());
1566 if (Lex
.getCode() != tgtok::r_paren
) {
1567 TokError("expected ')' in fold operator");
1570 Lex
.Lex(); // eat the ')'
1572 return FoldOpInit::get(Start
, List
, A
, B
, Expr
, Start
->getType())
1578 /// ParseOperatorType - Parse a type for an operator. This returns
1581 /// OperatorType ::= '<' Type '>'
1583 RecTy
*TGParser::ParseOperatorType() {
1584 RecTy
*Type
= nullptr;
1586 if (Lex
.getCode() != tgtok::less
) {
1587 TokError("expected type name for operator");
1590 Lex
.Lex(); // eat the <
1595 TokError("expected type name for operator");
1599 if (Lex
.getCode() != tgtok::greater
) {
1600 TokError("expected type name for operator");
1603 Lex
.Lex(); // eat the >
1608 Init
*TGParser::ParseOperationCond(Record
*CurRec
, RecTy
*ItemType
) {
1609 Lex
.Lex(); // eat the operation 'cond'
1611 if (Lex
.getCode() != tgtok::l_paren
) {
1612 TokError("expected '(' after !cond operator");
1615 Lex
.Lex(); // eat the '('
1617 // Parse through '[Case: Val,]+'
1618 SmallVector
<Init
*, 4> Case
;
1619 SmallVector
<Init
*, 4> Val
;
1621 if (Lex
.getCode() == tgtok::r_paren
) {
1622 Lex
.Lex(); // eat the ')'
1626 Init
*V
= ParseValue(CurRec
);
1631 if (Lex
.getCode() != tgtok::colon
) {
1632 TokError("expected ':' following a condition in !cond operator");
1635 Lex
.Lex(); // eat the ':'
1637 V
= ParseValue(CurRec
, ItemType
);
1642 if (Lex
.getCode() == tgtok::r_paren
) {
1643 Lex
.Lex(); // eat the ')'
1647 if (Lex
.getCode() != tgtok::comma
) {
1648 TokError("expected ',' or ')' following a value in !cond operator");
1651 Lex
.Lex(); // eat the ','
1654 if (Case
.size() < 1) {
1655 TokError("there should be at least 1 'condition : value' in the !cond operator");
1660 RecTy
*Type
= nullptr;
1661 for (Init
*V
: Val
) {
1662 RecTy
*VTy
= nullptr;
1663 if (TypedInit
*Vt
= dyn_cast
<TypedInit
>(V
))
1664 VTy
= Vt
->getType();
1665 if (BitsInit
*Vbits
= dyn_cast
<BitsInit
>(V
))
1666 VTy
= BitsRecTy::get(Vbits
->getNumBits());
1667 if (isa
<BitInit
>(V
))
1668 VTy
= BitRecTy::get();
1670 if (Type
== nullptr) {
1671 if (!isa
<UnsetInit
>(V
))
1674 if (!isa
<UnsetInit
>(V
)) {
1675 RecTy
*RType
= resolveTypes(Type
, VTy
);
1677 TokError(Twine("inconsistent types '") + Type
->getAsString() +
1678 "' and '" + VTy
->getAsString() + "' for !cond");
1687 TokError("could not determine type for !cond from its arguments");
1690 return CondOpInit::get(Case
, Val
, Type
)->Fold(CurRec
);
1693 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1695 /// SimpleValue ::= IDValue
1696 /// SimpleValue ::= INTVAL
1697 /// SimpleValue ::= STRVAL+
1698 /// SimpleValue ::= CODEFRAGMENT
1699 /// SimpleValue ::= '?'
1700 /// SimpleValue ::= '{' ValueList '}'
1701 /// SimpleValue ::= ID '<' ValueListNE '>'
1702 /// SimpleValue ::= '[' ValueList ']'
1703 /// SimpleValue ::= '(' IDValue DagArgList ')'
1704 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1705 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1706 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1707 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1708 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1709 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1710 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1711 /// SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
1713 Init
*TGParser::ParseSimpleValue(Record
*CurRec
, RecTy
*ItemType
,
1716 switch (Lex
.getCode()) {
1717 default: TokError("Unknown token when parsing a value"); break;
1719 // This is a leading paste operation. This is deprecated but
1720 // still exists in some .td files. Ignore it.
1721 Lex
.Lex(); // Skip '#'.
1722 return ParseSimpleValue(CurRec
, ItemType
, Mode
);
1723 case tgtok::IntVal
: R
= IntInit::get(Lex
.getCurIntVal()); Lex
.Lex(); break;
1724 case tgtok::BinaryIntVal
: {
1725 auto BinaryVal
= Lex
.getCurBinaryIntVal();
1726 SmallVector
<Init
*, 16> Bits(BinaryVal
.second
);
1727 for (unsigned i
= 0, e
= BinaryVal
.second
; i
!= e
; ++i
)
1728 Bits
[i
] = BitInit::get(BinaryVal
.first
& (1LL << i
));
1729 R
= BitsInit::get(Bits
);
1733 case tgtok::StrVal
: {
1734 std::string Val
= Lex
.getCurStrVal();
1737 // Handle multiple consecutive concatenated strings.
1738 while (Lex
.getCode() == tgtok::StrVal
) {
1739 Val
+= Lex
.getCurStrVal();
1743 R
= StringInit::get(Val
);
1746 case tgtok::CodeFragment
:
1747 R
= CodeInit::get(Lex
.getCurStrVal());
1750 case tgtok::question
:
1751 R
= UnsetInit::get();
1755 SMLoc NameLoc
= Lex
.getLoc();
1756 StringInit
*Name
= StringInit::get(Lex
.getCurStrVal());
1757 if (Lex
.Lex() != tgtok::less
) // consume the Id.
1758 return ParseIDValue(CurRec
, Name
, NameLoc
, Mode
); // Value ::= IDValue
1760 // Value ::= ID '<' ValueListNE '>'
1761 if (Lex
.Lex() == tgtok::greater
) {
1762 TokError("expected non-empty value list");
1766 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1767 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1769 Record
*Class
= Records
.getClass(Name
->getValue());
1771 Error(NameLoc
, "Expected a class name, got '" + Name
->getValue() + "'");
1775 SmallVector
<Init
*, 8> Args
;
1776 ParseValueList(Args
, CurRec
, Class
);
1777 if (Args
.empty()) return nullptr;
1779 if (Lex
.getCode() != tgtok::greater
) {
1780 TokError("expected '>' at end of value list");
1783 Lex
.Lex(); // eat the '>'
1785 // Typecheck the template arguments list
1786 ArrayRef
<Init
*> ExpectedArgs
= Class
->getTemplateArgs();
1787 if (ExpectedArgs
.size() < Args
.size()) {
1789 "More template args specified than expected");
1793 for (unsigned i
= 0, e
= ExpectedArgs
.size(); i
!= e
; ++i
) {
1794 RecordVal
*ExpectedArg
= Class
->getValue(ExpectedArgs
[i
]);
1795 if (i
< Args
.size()) {
1796 if (TypedInit
*TI
= dyn_cast
<TypedInit
>(Args
[i
])) {
1797 RecTy
*ExpectedType
= ExpectedArg
->getType();
1798 if (!TI
->getType()->typeIsConvertibleTo(ExpectedType
)) {
1800 "Value specified for template argument #" + Twine(i
) + " (" +
1801 ExpectedArg
->getNameInitAsString() + ") is of type '" +
1802 TI
->getType()->getAsString() + "', expected '" +
1803 ExpectedType
->getAsString() + "': " + TI
->getAsString());
1808 } else if (ExpectedArg
->getValue()->isComplete())
1812 "Value not specified for template argument #" + Twine(i
) + " (" +
1813 ExpectedArgs
[i
]->getAsUnquotedString() + ")");
1817 return VarDefInit::get(Class
, Args
)->Fold();
1819 case tgtok::l_brace
: { // Value ::= '{' ValueList '}'
1820 SMLoc BraceLoc
= Lex
.getLoc();
1821 Lex
.Lex(); // eat the '{'
1822 SmallVector
<Init
*, 16> Vals
;
1824 if (Lex
.getCode() != tgtok::r_brace
) {
1825 ParseValueList(Vals
, CurRec
);
1826 if (Vals
.empty()) return nullptr;
1828 if (Lex
.getCode() != tgtok::r_brace
) {
1829 TokError("expected '}' at end of bit list value");
1832 Lex
.Lex(); // eat the '}'
1834 SmallVector
<Init
*, 16> NewBits
;
1836 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
1837 // first. We'll first read everything in to a vector, then we can reverse
1838 // it to get the bits in the correct order for the BitsInit value.
1839 for (unsigned i
= 0, e
= Vals
.size(); i
!= e
; ++i
) {
1840 // FIXME: The following two loops would not be duplicated
1841 // if the API was a little more orthogonal.
1843 // bits<n> values are allowed to initialize n bits.
1844 if (BitsInit
*BI
= dyn_cast
<BitsInit
>(Vals
[i
])) {
1845 for (unsigned i
= 0, e
= BI
->getNumBits(); i
!= e
; ++i
)
1846 NewBits
.push_back(BI
->getBit((e
- i
) - 1));
1849 // bits<n> can also come from variable initializers.
1850 if (VarInit
*VI
= dyn_cast
<VarInit
>(Vals
[i
])) {
1851 if (BitsRecTy
*BitsRec
= dyn_cast
<BitsRecTy
>(VI
->getType())) {
1852 for (unsigned i
= 0, e
= BitsRec
->getNumBits(); i
!= e
; ++i
)
1853 NewBits
.push_back(VI
->getBit((e
- i
) - 1));
1856 // Fallthrough to try convert this to a bit.
1858 // All other values must be convertible to just a single bit.
1859 Init
*Bit
= Vals
[i
]->getCastTo(BitRecTy::get());
1861 Error(BraceLoc
, "Element #" + Twine(i
) + " (" + Vals
[i
]->getAsString() +
1862 ") is not convertable to a bit");
1865 NewBits
.push_back(Bit
);
1867 std::reverse(NewBits
.begin(), NewBits
.end());
1868 return BitsInit::get(NewBits
);
1870 case tgtok::l_square
: { // Value ::= '[' ValueList ']'
1871 Lex
.Lex(); // eat the '['
1872 SmallVector
<Init
*, 16> Vals
;
1874 RecTy
*DeducedEltTy
= nullptr;
1875 ListRecTy
*GivenListTy
= nullptr;
1878 ListRecTy
*ListType
= dyn_cast
<ListRecTy
>(ItemType
);
1880 TokError(Twine("Type mismatch for list, expected list type, got ") +
1881 ItemType
->getAsString());
1884 GivenListTy
= ListType
;
1887 if (Lex
.getCode() != tgtok::r_square
) {
1888 ParseValueList(Vals
, CurRec
, nullptr,
1889 GivenListTy
? GivenListTy
->getElementType() : nullptr);
1890 if (Vals
.empty()) return nullptr;
1892 if (Lex
.getCode() != tgtok::r_square
) {
1893 TokError("expected ']' at end of list value");
1896 Lex
.Lex(); // eat the ']'
1898 RecTy
*GivenEltTy
= nullptr;
1899 if (Lex
.getCode() == tgtok::less
) {
1900 // Optional list element type
1901 Lex
.Lex(); // eat the '<'
1903 GivenEltTy
= ParseType();
1905 // Couldn't parse element type
1909 if (Lex
.getCode() != tgtok::greater
) {
1910 TokError("expected '>' at end of list element type");
1913 Lex
.Lex(); // eat the '>'
1917 RecTy
*EltTy
= nullptr;
1918 for (Init
*V
: Vals
) {
1919 TypedInit
*TArg
= dyn_cast
<TypedInit
>(V
);
1922 EltTy
= resolveTypes(EltTy
, TArg
->getType());
1924 TokError("Incompatible types in list elements");
1928 EltTy
= TArg
->getType();
1935 // Verify consistency
1936 if (!EltTy
->typeIsConvertibleTo(GivenEltTy
)) {
1937 TokError("Incompatible types in list elements");
1946 TokError("No type for list");
1949 DeducedEltTy
= GivenListTy
->getElementType();
1951 // Make sure the deduced type is compatible with the given type
1953 if (!EltTy
->typeIsConvertibleTo(GivenListTy
->getElementType())) {
1954 TokError(Twine("Element type mismatch for list: element type '") +
1955 EltTy
->getAsString() + "' not convertible to '" +
1956 GivenListTy
->getElementType()->getAsString());
1960 DeducedEltTy
= EltTy
;
1963 return ListInit::get(Vals
, DeducedEltTy
);
1965 case tgtok::l_paren
: { // Value ::= '(' IDValue DagArgList ')'
1966 Lex
.Lex(); // eat the '('
1967 if (Lex
.getCode() != tgtok::Id
&& Lex
.getCode() != tgtok::XCast
) {
1968 TokError("expected identifier in dag init");
1972 Init
*Operator
= ParseValue(CurRec
);
1973 if (!Operator
) return nullptr;
1975 // If the operator name is present, parse it.
1976 StringInit
*OperatorName
= nullptr;
1977 if (Lex
.getCode() == tgtok::colon
) {
1978 if (Lex
.Lex() != tgtok::VarName
) { // eat the ':'
1979 TokError("expected variable name in dag operator");
1982 OperatorName
= StringInit::get(Lex
.getCurStrVal());
1983 Lex
.Lex(); // eat the VarName.
1986 SmallVector
<std::pair
<llvm::Init
*, StringInit
*>, 8> DagArgs
;
1987 if (Lex
.getCode() != tgtok::r_paren
) {
1988 ParseDagArgList(DagArgs
, CurRec
);
1989 if (DagArgs
.empty()) return nullptr;
1992 if (Lex
.getCode() != tgtok::r_paren
) {
1993 TokError("expected ')' in dag init");
1996 Lex
.Lex(); // eat the ')'
1998 return DagInit::get(Operator
, OperatorName
, DagArgs
);
2005 case tgtok::XCast
: // Value ::= !unop '(' Value ')'
2007 case tgtok::XConcat
:
2021 case tgtok::XListConcat
:
2022 case tgtok::XStrConcat
: // Value ::= !binop '(' Value ',' Value ')'
2026 case tgtok::XForEach
:
2027 case tgtok::XSubst
: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
2028 return ParseOperation(CurRec
, ItemType
);
2035 /// ParseValue - Parse a tblgen value. This returns null on error.
2037 /// Value ::= SimpleValue ValueSuffix*
2038 /// ValueSuffix ::= '{' BitList '}'
2039 /// ValueSuffix ::= '[' BitList ']'
2040 /// ValueSuffix ::= '.' ID
2042 Init
*TGParser::ParseValue(Record
*CurRec
, RecTy
*ItemType
, IDParseMode Mode
) {
2043 Init
*Result
= ParseSimpleValue(CurRec
, ItemType
, Mode
);
2044 if (!Result
) return nullptr;
2046 // Parse the suffixes now if present.
2048 switch (Lex
.getCode()) {
2049 default: return Result
;
2050 case tgtok::l_brace
: {
2051 if (Mode
== ParseNameMode
)
2052 // This is the beginning of the object body.
2055 SMLoc CurlyLoc
= Lex
.getLoc();
2056 Lex
.Lex(); // eat the '{'
2057 SmallVector
<unsigned, 16> Ranges
;
2058 ParseRangeList(Ranges
);
2059 if (Ranges
.empty()) return nullptr;
2061 // Reverse the bitlist.
2062 std::reverse(Ranges
.begin(), Ranges
.end());
2063 Result
= Result
->convertInitializerBitRange(Ranges
);
2065 Error(CurlyLoc
, "Invalid bit range for value");
2070 if (Lex
.getCode() != tgtok::r_brace
) {
2071 TokError("expected '}' at end of bit range list");
2077 case tgtok::l_square
: {
2078 SMLoc SquareLoc
= Lex
.getLoc();
2079 Lex
.Lex(); // eat the '['
2080 SmallVector
<unsigned, 16> Ranges
;
2081 ParseRangeList(Ranges
);
2082 if (Ranges
.empty()) return nullptr;
2084 Result
= Result
->convertInitListSlice(Ranges
);
2086 Error(SquareLoc
, "Invalid range for list slice");
2091 if (Lex
.getCode() != tgtok::r_square
) {
2092 TokError("expected ']' at end of list slice");
2098 case tgtok::period
: {
2099 if (Lex
.Lex() != tgtok::Id
) { // eat the .
2100 TokError("expected field identifier after '.'");
2103 StringInit
*FieldName
= StringInit::get(Lex
.getCurStrVal());
2104 if (!Result
->getFieldType(FieldName
)) {
2105 TokError("Cannot access field '" + Lex
.getCurStrVal() + "' of value '" +
2106 Result
->getAsString() + "'");
2109 Result
= FieldInit::get(Result
, FieldName
)->Fold(CurRec
);
2110 Lex
.Lex(); // eat field name
2115 SMLoc PasteLoc
= Lex
.getLoc();
2117 // Create a !strconcat() operation, first casting each operand to
2118 // a string if necessary.
2120 TypedInit
*LHS
= dyn_cast
<TypedInit
>(Result
);
2122 Error(PasteLoc
, "LHS of paste is not typed!");
2126 if (LHS
->getType() != StringRecTy::get()) {
2127 LHS
= dyn_cast
<TypedInit
>(
2128 UnOpInit::get(UnOpInit::CAST
, LHS
, StringRecTy::get())
2131 Error(PasteLoc
, Twine("can't cast '") + LHS
->getAsString() +
2137 TypedInit
*RHS
= nullptr;
2139 Lex
.Lex(); // Eat the '#'.
2140 switch (Lex
.getCode()) {
2143 case tgtok::l_brace
:
2144 // These are all of the tokens that can begin an object body.
2145 // Some of these can also begin values but we disallow those cases
2146 // because they are unlikely to be useful.
2148 // Trailing paste, concat with an empty string.
2149 RHS
= StringInit::get("");
2153 Init
*RHSResult
= ParseValue(CurRec
, nullptr, ParseNameMode
);
2154 RHS
= dyn_cast
<TypedInit
>(RHSResult
);
2156 Error(PasteLoc
, "RHS of paste is not typed!");
2160 if (RHS
->getType() != StringRecTy::get()) {
2161 RHS
= dyn_cast
<TypedInit
>(
2162 UnOpInit::get(UnOpInit::CAST
, RHS
, StringRecTy::get())
2165 Error(PasteLoc
, Twine("can't cast '") + RHS
->getAsString() +
2174 Result
= BinOpInit::getStrConcat(LHS
, RHS
);
2180 /// ParseDagArgList - Parse the argument list for a dag literal expression.
2182 /// DagArg ::= Value (':' VARNAME)?
2183 /// DagArg ::= VARNAME
2184 /// DagArgList ::= DagArg
2185 /// DagArgList ::= DagArgList ',' DagArg
2186 void TGParser::ParseDagArgList(
2187 SmallVectorImpl
<std::pair
<llvm::Init
*, StringInit
*>> &Result
,
2191 // DagArg ::= VARNAME
2192 if (Lex
.getCode() == tgtok::VarName
) {
2193 // A missing value is treated like '?'.
2194 StringInit
*VarName
= StringInit::get(Lex
.getCurStrVal());
2195 Result
.emplace_back(UnsetInit::get(), VarName
);
2198 // DagArg ::= Value (':' VARNAME)?
2199 Init
*Val
= ParseValue(CurRec
);
2205 // If the variable name is present, add it.
2206 StringInit
*VarName
= nullptr;
2207 if (Lex
.getCode() == tgtok::colon
) {
2208 if (Lex
.Lex() != tgtok::VarName
) { // eat the ':'
2209 TokError("expected variable name in dag literal");
2213 VarName
= StringInit::get(Lex
.getCurStrVal());
2214 Lex
.Lex(); // eat the VarName.
2217 Result
.push_back(std::make_pair(Val
, VarName
));
2219 if (Lex
.getCode() != tgtok::comma
) break;
2220 Lex
.Lex(); // eat the ','
2224 /// ParseValueList - Parse a comma separated list of values, returning them as a
2225 /// vector. Note that this always expects to be able to parse at least one
2226 /// value. It returns an empty list if this is not possible.
2228 /// ValueList ::= Value (',' Value)
2230 void TGParser::ParseValueList(SmallVectorImpl
<Init
*> &Result
, Record
*CurRec
,
2231 Record
*ArgsRec
, RecTy
*EltTy
) {
2232 RecTy
*ItemType
= EltTy
;
2233 unsigned int ArgN
= 0;
2234 if (ArgsRec
&& !EltTy
) {
2235 ArrayRef
<Init
*> TArgs
= ArgsRec
->getTemplateArgs();
2236 if (TArgs
.empty()) {
2237 TokError("template argument provided to non-template class");
2241 const RecordVal
*RV
= ArgsRec
->getValue(TArgs
[ArgN
]);
2243 errs() << "Cannot find template arg " << ArgN
<< " (" << TArgs
[ArgN
]
2246 assert(RV
&& "Template argument record not found??");
2247 ItemType
= RV
->getType();
2250 Result
.push_back(ParseValue(CurRec
, ItemType
));
2251 if (!Result
.back()) {
2256 while (Lex
.getCode() == tgtok::comma
) {
2257 Lex
.Lex(); // Eat the comma
2259 if (ArgsRec
&& !EltTy
) {
2260 ArrayRef
<Init
*> TArgs
= ArgsRec
->getTemplateArgs();
2261 if (ArgN
>= TArgs
.size()) {
2262 TokError("too many template arguments");
2266 const RecordVal
*RV
= ArgsRec
->getValue(TArgs
[ArgN
]);
2267 assert(RV
&& "Template argument record not found??");
2268 ItemType
= RV
->getType();
2271 Result
.push_back(ParseValue(CurRec
, ItemType
));
2272 if (!Result
.back()) {
2279 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
2280 /// empty string on error. This can happen in a number of different context's,
2281 /// including within a def or in the template args for a def (which which case
2282 /// CurRec will be non-null) and within the template args for a multiclass (in
2283 /// which case CurRec will be null, but CurMultiClass will be set). This can
2284 /// also happen within a def that is within a multiclass, which will set both
2285 /// CurRec and CurMultiClass.
2287 /// Declaration ::= FIELD? Type ID ('=' Value)?
2289 Init
*TGParser::ParseDeclaration(Record
*CurRec
,
2290 bool ParsingTemplateArgs
) {
2291 // Read the field prefix if present.
2292 bool HasField
= Lex
.getCode() == tgtok::Field
;
2293 if (HasField
) Lex
.Lex();
2295 RecTy
*Type
= ParseType();
2296 if (!Type
) return nullptr;
2298 if (Lex
.getCode() != tgtok::Id
) {
2299 TokError("Expected identifier in declaration");
2303 std::string Str
= Lex
.getCurStrVal();
2304 if (Str
== "NAME") {
2305 TokError("'" + Str
+ "' is a reserved variable name");
2309 SMLoc IdLoc
= Lex
.getLoc();
2310 Init
*DeclName
= StringInit::get(Str
);
2313 if (ParsingTemplateArgs
) {
2315 DeclName
= QualifyName(*CurRec
, CurMultiClass
, DeclName
, ":");
2317 assert(CurMultiClass
);
2319 DeclName
= QualifyName(CurMultiClass
->Rec
, CurMultiClass
, DeclName
,
2324 if (AddValue(CurRec
, IdLoc
, RecordVal(DeclName
, Type
, HasField
)))
2327 // If a value is present, parse it.
2328 if (Lex
.getCode() == tgtok::equal
) {
2330 SMLoc ValLoc
= Lex
.getLoc();
2331 Init
*Val
= ParseValue(CurRec
, Type
);
2333 SetValue(CurRec
, ValLoc
, DeclName
, None
, Val
))
2334 // Return the name, even if an error is thrown. This is so that we can
2335 // continue to make some progress, even without the value having been
2343 /// ParseForeachDeclaration - Read a foreach declaration, returning
2344 /// the name of the declared object or a NULL Init on error. Return
2345 /// the name of the parsed initializer list through ForeachListName.
2347 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
2348 /// ForeachDeclaration ::= ID '=' RangePiece
2349 /// ForeachDeclaration ::= ID '=' Value
2351 VarInit
*TGParser::ParseForeachDeclaration(Init
*&ForeachListValue
) {
2352 if (Lex
.getCode() != tgtok::Id
) {
2353 TokError("Expected identifier in foreach declaration");
2357 Init
*DeclName
= StringInit::get(Lex
.getCurStrVal());
2360 // If a value is present, parse it.
2361 if (Lex
.getCode() != tgtok::equal
) {
2362 TokError("Expected '=' in foreach declaration");
2365 Lex
.Lex(); // Eat the '='
2367 RecTy
*IterType
= nullptr;
2368 SmallVector
<unsigned, 16> Ranges
;
2370 switch (Lex
.getCode()) {
2371 case tgtok::IntVal
: { // RangePiece.
2372 if (ParseRangePiece(Ranges
))
2377 case tgtok::l_brace
: { // '{' RangeList '}'
2378 Lex
.Lex(); // eat the '{'
2379 ParseRangeList(Ranges
);
2380 if (Lex
.getCode() != tgtok::r_brace
) {
2381 TokError("expected '}' at end of bit range list");
2389 SMLoc ValueLoc
= Lex
.getLoc();
2390 Init
*I
= ParseValue(nullptr);
2391 TypedInit
*TI
= dyn_cast
<TypedInit
>(I
);
2392 if (!TI
|| !isa
<ListRecTy
>(TI
->getType())) {
2395 Type
= (Twine("' of type '") + TI
->getType()->getAsString()).str();
2396 Error(ValueLoc
, "expected a list, got '" + I
->getAsString() + Type
+ "'");
2398 PrintNote({}, "references to multiclass template arguments cannot be "
2399 "resolved at this time");
2402 ForeachListValue
= I
;
2403 IterType
= cast
<ListRecTy
>(TI
->getType())->getElementType();
2408 if (!Ranges
.empty()) {
2409 assert(!IterType
&& "Type already initialized?");
2410 IterType
= IntRecTy::get();
2411 std::vector
<Init
*> Values
;
2412 for (unsigned R
: Ranges
)
2413 Values
.push_back(IntInit::get(R
));
2414 ForeachListValue
= ListInit::get(Values
, IterType
);
2420 return VarInit::get(DeclName
, IterType
);
2423 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
2424 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
2425 /// template args for a def, which may or may not be in a multiclass. If null,
2426 /// these are the template args for a multiclass.
2428 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
2430 bool TGParser::ParseTemplateArgList(Record
*CurRec
) {
2431 assert(Lex
.getCode() == tgtok::less
&& "Not a template arg list!");
2432 Lex
.Lex(); // eat the '<'
2434 Record
*TheRecToAddTo
= CurRec
? CurRec
: &CurMultiClass
->Rec
;
2436 // Read the first declaration.
2437 Init
*TemplArg
= ParseDeclaration(CurRec
, true/*templateargs*/);
2441 TheRecToAddTo
->addTemplateArg(TemplArg
);
2443 while (Lex
.getCode() == tgtok::comma
) {
2444 Lex
.Lex(); // eat the ','
2446 // Read the following declarations.
2447 SMLoc Loc
= Lex
.getLoc();
2448 TemplArg
= ParseDeclaration(CurRec
, true/*templateargs*/);
2452 if (TheRecToAddTo
->isTemplateArg(TemplArg
))
2453 return Error(Loc
, "template argument with the same name has already been "
2456 TheRecToAddTo
->addTemplateArg(TemplArg
);
2459 if (Lex
.getCode() != tgtok::greater
)
2460 return TokError("expected '>' at end of template argument list");
2461 Lex
.Lex(); // eat the '>'.
2465 /// ParseBodyItem - Parse a single item at within the body of a def or class.
2467 /// BodyItem ::= Declaration ';'
2468 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
2469 bool TGParser::ParseBodyItem(Record
*CurRec
) {
2470 if (Lex
.getCode() != tgtok::Let
) {
2471 if (!ParseDeclaration(CurRec
, false))
2474 if (Lex
.getCode() != tgtok::semi
)
2475 return TokError("expected ';' after declaration");
2480 // LET ID OptionalRangeList '=' Value ';'
2481 if (Lex
.Lex() != tgtok::Id
)
2482 return TokError("expected field identifier after let");
2484 SMLoc IdLoc
= Lex
.getLoc();
2485 StringInit
*FieldName
= StringInit::get(Lex
.getCurStrVal());
2486 Lex
.Lex(); // eat the field name.
2488 SmallVector
<unsigned, 16> BitList
;
2489 if (ParseOptionalBitList(BitList
))
2491 std::reverse(BitList
.begin(), BitList
.end());
2493 if (Lex
.getCode() != tgtok::equal
)
2494 return TokError("expected '=' in let expression");
2495 Lex
.Lex(); // eat the '='.
2497 RecordVal
*Field
= CurRec
->getValue(FieldName
);
2499 return TokError("Value '" + FieldName
->getValue() + "' unknown!");
2501 RecTy
*Type
= Field
->getType();
2503 Init
*Val
= ParseValue(CurRec
, Type
);
2504 if (!Val
) return true;
2506 if (Lex
.getCode() != tgtok::semi
)
2507 return TokError("expected ';' after let expression");
2510 return SetValue(CurRec
, IdLoc
, FieldName
, BitList
, Val
);
2513 /// ParseBody - Read the body of a class or def. Return true on error, false on
2517 /// Body ::= '{' BodyList '}'
2518 /// BodyList BodyItem*
2520 bool TGParser::ParseBody(Record
*CurRec
) {
2521 // If this is a null definition, just eat the semi and return.
2522 if (Lex
.getCode() == tgtok::semi
) {
2527 if (Lex
.getCode() != tgtok::l_brace
)
2528 return TokError("Expected ';' or '{' to start body");
2532 while (Lex
.getCode() != tgtok::r_brace
)
2533 if (ParseBodyItem(CurRec
))
2541 /// Apply the current let bindings to \a CurRec.
2542 /// \returns true on error, false otherwise.
2543 bool TGParser::ApplyLetStack(Record
*CurRec
) {
2544 for (SmallVectorImpl
<LetRecord
> &LetInfo
: LetStack
)
2545 for (LetRecord
&LR
: LetInfo
)
2546 if (SetValue(CurRec
, LR
.Loc
, LR
.Name
, LR
.Bits
, LR
.Value
))
2551 bool TGParser::ApplyLetStack(RecordsEntry
&Entry
) {
2553 return ApplyLetStack(Entry
.Rec
.get());
2555 for (auto &E
: Entry
.Loop
->Entries
) {
2556 if (ApplyLetStack(E
))
2563 /// ParseObjectBody - Parse the body of a def or class. This consists of an
2564 /// optional ClassList followed by a Body. CurRec is the current def or class
2565 /// that is being parsed.
2567 /// ObjectBody ::= BaseClassList Body
2568 /// BaseClassList ::= /*empty*/
2569 /// BaseClassList ::= ':' BaseClassListNE
2570 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
2572 bool TGParser::ParseObjectBody(Record
*CurRec
) {
2573 // If there is a baseclass list, read it.
2574 if (Lex
.getCode() == tgtok::colon
) {
2577 // Read all of the subclasses.
2578 SubClassReference SubClass
= ParseSubClassReference(CurRec
, false);
2581 if (!SubClass
.Rec
) return true;
2584 if (AddSubClass(CurRec
, SubClass
))
2587 if (Lex
.getCode() != tgtok::comma
) break;
2588 Lex
.Lex(); // eat ','.
2589 SubClass
= ParseSubClassReference(CurRec
, false);
2593 if (ApplyLetStack(CurRec
))
2596 return ParseBody(CurRec
);
2599 /// ParseDef - Parse and return a top level or multiclass def, return the record
2600 /// corresponding to it. This returns null on error.
2602 /// DefInst ::= DEF ObjectName ObjectBody
2604 bool TGParser::ParseDef(MultiClass
*CurMultiClass
) {
2605 SMLoc DefLoc
= Lex
.getLoc();
2606 assert(Lex
.getCode() == tgtok::Def
&& "Unknown tok");
2607 Lex
.Lex(); // Eat the 'def' token.
2609 // Parse ObjectName and make a record for it.
2610 std::unique_ptr
<Record
> CurRec
;
2611 Init
*Name
= ParseObjectName(CurMultiClass
);
2615 if (isa
<UnsetInit
>(Name
))
2616 CurRec
= make_unique
<Record
>(Records
.getNewAnonymousName(), DefLoc
, Records
,
2617 /*Anonymous=*/true);
2619 CurRec
= make_unique
<Record
>(Name
, DefLoc
, Records
);
2621 if (ParseObjectBody(CurRec
.get()))
2624 return addEntry(std::move(CurRec
));
2627 /// ParseDefset - Parse a defset statement.
2629 /// Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
2631 bool TGParser::ParseDefset() {
2632 assert(Lex
.getCode() == tgtok::Defset
);
2633 Lex
.Lex(); // Eat the 'defset' token
2635 DefsetRecord Defset
;
2636 Defset
.Loc
= Lex
.getLoc();
2637 RecTy
*Type
= ParseType();
2640 if (!isa
<ListRecTy
>(Type
))
2641 return Error(Defset
.Loc
, "expected list type");
2642 Defset
.EltTy
= cast
<ListRecTy
>(Type
)->getElementType();
2644 if (Lex
.getCode() != tgtok::Id
)
2645 return TokError("expected identifier");
2646 StringInit
*DeclName
= StringInit::get(Lex
.getCurStrVal());
2647 if (Records
.getGlobal(DeclName
->getValue()))
2648 return TokError("def or global variable of this name already exists");
2650 if (Lex
.Lex() != tgtok::equal
) // Eat the identifier
2651 return TokError("expected '='");
2652 if (Lex
.Lex() != tgtok::l_brace
) // Eat the '='
2653 return TokError("expected '{'");
2654 SMLoc BraceLoc
= Lex
.getLoc();
2655 Lex
.Lex(); // Eat the '{'
2657 Defsets
.push_back(&Defset
);
2658 bool Err
= ParseObjectList(nullptr);
2663 if (Lex
.getCode() != tgtok::r_brace
) {
2664 TokError("expected '}' at end of defset");
2665 return Error(BraceLoc
, "to match this '{'");
2667 Lex
.Lex(); // Eat the '}'
2669 Records
.addExtraGlobal(DeclName
->getValue(),
2670 ListInit::get(Defset
.Elements
, Defset
.EltTy
));
2674 /// ParseForeach - Parse a for statement. Return the record corresponding
2675 /// to it. This returns true on error.
2677 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2678 /// Foreach ::= FOREACH Declaration IN Object
2680 bool TGParser::ParseForeach(MultiClass
*CurMultiClass
) {
2681 SMLoc Loc
= Lex
.getLoc();
2682 assert(Lex
.getCode() == tgtok::Foreach
&& "Unknown tok");
2683 Lex
.Lex(); // Eat the 'for' token.
2685 // Make a temporary object to record items associated with the for
2687 Init
*ListValue
= nullptr;
2688 VarInit
*IterName
= ParseForeachDeclaration(ListValue
);
2690 return TokError("expected declaration in for");
2692 if (Lex
.getCode() != tgtok::In
)
2693 return TokError("Unknown tok");
2694 Lex
.Lex(); // Eat the in
2696 // Create a loop object and remember it.
2697 Loops
.push_back(llvm::make_unique
<ForeachLoop
>(Loc
, IterName
, ListValue
));
2699 if (Lex
.getCode() != tgtok::l_brace
) {
2700 // FOREACH Declaration IN Object
2701 if (ParseObject(CurMultiClass
))
2704 SMLoc BraceLoc
= Lex
.getLoc();
2705 // Otherwise, this is a group foreach.
2706 Lex
.Lex(); // eat the '{'.
2708 // Parse the object list.
2709 if (ParseObjectList(CurMultiClass
))
2712 if (Lex
.getCode() != tgtok::r_brace
) {
2713 TokError("expected '}' at end of foreach command");
2714 return Error(BraceLoc
, "to match this '{'");
2716 Lex
.Lex(); // Eat the }
2719 // Resolve the loop or store it for later resolution.
2720 std::unique_ptr
<ForeachLoop
> Loop
= std::move(Loops
.back());
2723 return addEntry(std::move(Loop
));
2726 /// ParseClass - Parse a tblgen class definition.
2728 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2730 bool TGParser::ParseClass() {
2731 assert(Lex
.getCode() == tgtok::Class
&& "Unexpected token!");
2734 if (Lex
.getCode() != tgtok::Id
)
2735 return TokError("expected class name after 'class' keyword");
2737 Record
*CurRec
= Records
.getClass(Lex
.getCurStrVal());
2739 // If the body was previously defined, this is an error.
2740 if (!CurRec
->getValues().empty() ||
2741 !CurRec
->getSuperClasses().empty() ||
2742 !CurRec
->getTemplateArgs().empty())
2743 return TokError("Class '" + CurRec
->getNameInitAsString() +
2744 "' already defined");
2746 // If this is the first reference to this class, create and add it.
2748 llvm::make_unique
<Record
>(Lex
.getCurStrVal(), Lex
.getLoc(), Records
,
2750 CurRec
= NewRec
.get();
2751 Records
.addClass(std::move(NewRec
));
2753 Lex
.Lex(); // eat the name.
2755 // If there are template args, parse them.
2756 if (Lex
.getCode() == tgtok::less
)
2757 if (ParseTemplateArgList(CurRec
))
2760 return ParseObjectBody(CurRec
);
2763 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2766 /// LetList ::= LetItem (',' LetItem)*
2767 /// LetItem ::= ID OptionalRangeList '=' Value
2769 void TGParser::ParseLetList(SmallVectorImpl
<LetRecord
> &Result
) {
2771 if (Lex
.getCode() != tgtok::Id
) {
2772 TokError("expected identifier in let definition");
2777 StringInit
*Name
= StringInit::get(Lex
.getCurStrVal());
2778 SMLoc NameLoc
= Lex
.getLoc();
2779 Lex
.Lex(); // Eat the identifier.
2781 // Check for an optional RangeList.
2782 SmallVector
<unsigned, 16> Bits
;
2783 if (ParseOptionalRangeList(Bits
)) {
2787 std::reverse(Bits
.begin(), Bits
.end());
2789 if (Lex
.getCode() != tgtok::equal
) {
2790 TokError("expected '=' in let expression");
2794 Lex
.Lex(); // eat the '='.
2796 Init
*Val
= ParseValue(nullptr);
2802 // Now that we have everything, add the record.
2803 Result
.emplace_back(Name
, Bits
, Val
, NameLoc
);
2805 if (Lex
.getCode() != tgtok::comma
)
2807 Lex
.Lex(); // eat the comma.
2811 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2812 /// different related productions. This works inside multiclasses too.
2814 /// Object ::= LET LetList IN '{' ObjectList '}'
2815 /// Object ::= LET LetList IN Object
2817 bool TGParser::ParseTopLevelLet(MultiClass
*CurMultiClass
) {
2818 assert(Lex
.getCode() == tgtok::Let
&& "Unexpected token");
2821 // Add this entry to the let stack.
2822 SmallVector
<LetRecord
, 8> LetInfo
;
2823 ParseLetList(LetInfo
);
2824 if (LetInfo
.empty()) return true;
2825 LetStack
.push_back(std::move(LetInfo
));
2827 if (Lex
.getCode() != tgtok::In
)
2828 return TokError("expected 'in' at end of top-level 'let'");
2831 // If this is a scalar let, just handle it now
2832 if (Lex
.getCode() != tgtok::l_brace
) {
2833 // LET LetList IN Object
2834 if (ParseObject(CurMultiClass
))
2836 } else { // Object ::= LETCommand '{' ObjectList '}'
2837 SMLoc BraceLoc
= Lex
.getLoc();
2838 // Otherwise, this is a group let.
2839 Lex
.Lex(); // eat the '{'.
2841 // Parse the object list.
2842 if (ParseObjectList(CurMultiClass
))
2845 if (Lex
.getCode() != tgtok::r_brace
) {
2846 TokError("expected '}' at end of top level let command");
2847 return Error(BraceLoc
, "to match this '{'");
2852 // Outside this let scope, this let block is not active.
2853 LetStack
.pop_back();
2857 /// ParseMultiClass - Parse a multiclass definition.
2859 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2860 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
2861 /// MultiClassObject ::= DefInst
2862 /// MultiClassObject ::= MultiClassInst
2863 /// MultiClassObject ::= DefMInst
2864 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
2865 /// MultiClassObject ::= LETCommand Object
2867 bool TGParser::ParseMultiClass() {
2868 assert(Lex
.getCode() == tgtok::MultiClass
&& "Unexpected token");
2869 Lex
.Lex(); // Eat the multiclass token.
2871 if (Lex
.getCode() != tgtok::Id
)
2872 return TokError("expected identifier after multiclass for name");
2873 std::string Name
= Lex
.getCurStrVal();
2876 MultiClasses
.insert(std::make_pair(Name
,
2877 llvm::make_unique
<MultiClass
>(Name
, Lex
.getLoc(),Records
)));
2880 return TokError("multiclass '" + Name
+ "' already defined");
2882 CurMultiClass
= Result
.first
->second
.get();
2883 Lex
.Lex(); // Eat the identifier.
2885 // If there are template args, parse them.
2886 if (Lex
.getCode() == tgtok::less
)
2887 if (ParseTemplateArgList(nullptr))
2890 bool inherits
= false;
2892 // If there are submulticlasses, parse them.
2893 if (Lex
.getCode() == tgtok::colon
) {
2898 // Read all of the submulticlasses.
2899 SubMultiClassReference SubMultiClass
=
2900 ParseSubMultiClassReference(CurMultiClass
);
2903 if (!SubMultiClass
.MC
) return true;
2906 if (AddSubMultiClass(CurMultiClass
, SubMultiClass
))
2909 if (Lex
.getCode() != tgtok::comma
) break;
2910 Lex
.Lex(); // eat ','.
2911 SubMultiClass
= ParseSubMultiClassReference(CurMultiClass
);
2915 if (Lex
.getCode() != tgtok::l_brace
) {
2917 return TokError("expected '{' in multiclass definition");
2918 if (Lex
.getCode() != tgtok::semi
)
2919 return TokError("expected ';' in multiclass definition");
2920 Lex
.Lex(); // eat the ';'.
2922 if (Lex
.Lex() == tgtok::r_brace
) // eat the '{'.
2923 return TokError("multiclass must contain at least one def");
2925 while (Lex
.getCode() != tgtok::r_brace
) {
2926 switch (Lex
.getCode()) {
2928 return TokError("expected 'let', 'def', 'defm' or 'foreach' in "
2933 case tgtok::Foreach
:
2934 if (ParseObject(CurMultiClass
))
2939 Lex
.Lex(); // eat the '}'.
2942 CurMultiClass
= nullptr;
2946 /// ParseDefm - Parse the instantiation of a multiclass.
2948 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2950 bool TGParser::ParseDefm(MultiClass
*CurMultiClass
) {
2951 assert(Lex
.getCode() == tgtok::Defm
&& "Unexpected token!");
2952 Lex
.Lex(); // eat the defm
2954 Init
*DefmName
= ParseObjectName(CurMultiClass
);
2957 if (isa
<UnsetInit
>(DefmName
)) {
2958 DefmName
= Records
.getNewAnonymousName();
2960 DefmName
= BinOpInit::getStrConcat(
2961 VarInit::get(QualifiedNameOfImplicitName(CurMultiClass
),
2962 StringRecTy::get()),
2966 if (Lex
.getCode() != tgtok::colon
)
2967 return TokError("expected ':' after defm identifier");
2969 // Keep track of the new generated record definitions.
2970 std::vector
<RecordsEntry
> NewEntries
;
2972 // This record also inherits from a regular class (non-multiclass)?
2973 bool InheritFromClass
= false;
2978 SMLoc SubClassLoc
= Lex
.getLoc();
2979 SubClassReference Ref
= ParseSubClassReference(nullptr, true);
2982 if (!Ref
.Rec
) return true;
2984 // To instantiate a multiclass, we need to first get the multiclass, then
2985 // instantiate each def contained in the multiclass with the SubClassRef
2986 // template parameters.
2987 MultiClass
*MC
= MultiClasses
[Ref
.Rec
->getName()].get();
2988 assert(MC
&& "Didn't lookup multiclass correctly?");
2989 ArrayRef
<Init
*> TemplateVals
= Ref
.TemplateArgs
;
2991 // Verify that the correct number of template arguments were specified.
2992 ArrayRef
<Init
*> TArgs
= MC
->Rec
.getTemplateArgs();
2993 if (TArgs
.size() < TemplateVals
.size())
2994 return Error(SubClassLoc
,
2995 "more template args specified than multiclass expects");
2998 for (unsigned i
= 0, e
= TArgs
.size(); i
!= e
; ++i
) {
2999 if (i
< TemplateVals
.size()) {
3000 Substs
.emplace_back(TArgs
[i
], TemplateVals
[i
]);
3002 Init
*Default
= MC
->Rec
.getValue(TArgs
[i
])->getValue();
3003 if (!Default
->isComplete()) {
3004 return Error(SubClassLoc
,
3005 "value not specified for template argument #" +
3006 Twine(i
) + " (" + TArgs
[i
]->getAsUnquotedString() +
3007 ") of multiclass '" + MC
->Rec
.getNameInitAsString() +
3010 Substs
.emplace_back(TArgs
[i
], Default
);
3014 Substs
.emplace_back(QualifiedNameOfImplicitName(MC
), DefmName
);
3016 if (resolve(MC
->Entries
, Substs
, CurMultiClass
== nullptr, &NewEntries
,
3020 if (Lex
.getCode() != tgtok::comma
) break;
3021 Lex
.Lex(); // eat ','.
3023 if (Lex
.getCode() != tgtok::Id
)
3024 return TokError("expected identifier");
3026 SubClassLoc
= Lex
.getLoc();
3028 // A defm can inherit from regular classes (non-multiclass) as
3029 // long as they come in the end of the inheritance list.
3030 InheritFromClass
= (Records
.getClass(Lex
.getCurStrVal()) != nullptr);
3032 if (InheritFromClass
)
3035 Ref
= ParseSubClassReference(nullptr, true);
3038 if (InheritFromClass
) {
3039 // Process all the classes to inherit as if they were part of a
3040 // regular 'def' and inherit all record values.
3041 SubClassReference SubClass
= ParseSubClassReference(nullptr, false);
3044 if (!SubClass
.Rec
) return true;
3046 // Get the expanded definition prototypes and teach them about
3047 // the record values the current class to inherit has
3048 for (auto &E
: NewEntries
) {
3050 if (AddSubClass(E
, SubClass
))
3054 if (Lex
.getCode() != tgtok::comma
) break;
3055 Lex
.Lex(); // eat ','.
3056 SubClass
= ParseSubClassReference(nullptr, false);
3060 for (auto &E
: NewEntries
) {
3061 if (ApplyLetStack(E
))
3064 addEntry(std::move(E
));
3067 if (Lex
.getCode() != tgtok::semi
)
3068 return TokError("expected ';' at end of defm");
3075 /// Object ::= ClassInst
3076 /// Object ::= DefInst
3077 /// Object ::= MultiClassInst
3078 /// Object ::= DefMInst
3079 /// Object ::= LETCommand '{' ObjectList '}'
3080 /// Object ::= LETCommand Object
3081 bool TGParser::ParseObject(MultiClass
*MC
) {
3082 switch (Lex
.getCode()) {
3084 return TokError("Expected class, def, defm, defset, multiclass, let or "
3086 case tgtok::Let
: return ParseTopLevelLet(MC
);
3087 case tgtok::Def
: return ParseDef(MC
);
3088 case tgtok::Foreach
: return ParseForeach(MC
);
3089 case tgtok::Defm
: return ParseDefm(MC
);
3092 return TokError("defset is not allowed inside multiclass");
3093 return ParseDefset();
3096 return TokError("class is not allowed inside multiclass");
3098 return TokError("class is not allowed inside foreach loop");
3099 return ParseClass();
3100 case tgtok::MultiClass
:
3102 return TokError("multiclass is not allowed inside foreach loop");
3103 return ParseMultiClass();
3108 /// ObjectList :== Object*
3109 bool TGParser::ParseObjectList(MultiClass
*MC
) {
3110 while (isObjectStart(Lex
.getCode())) {
3111 if (ParseObject(MC
))
3117 bool TGParser::ParseFile() {
3118 Lex
.Lex(); // Prime the lexer.
3119 if (ParseObjectList()) return true;
3121 // If we have unread input at the end of the file, report it.
3122 if (Lex
.getCode() == tgtok::Eof
)
3125 return TokError("Unexpected input at top level");
3128 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3129 LLVM_DUMP_METHOD
void RecordsEntry::dump() const {
3136 LLVM_DUMP_METHOD
void ForeachLoop::dump() const {
3137 errs() << "foreach " << IterVar
->getAsString() << " = "
3138 << ListValue
->getAsString() << " in {\n";
3140 for (const auto &E
: Entries
)
3146 LLVM_DUMP_METHOD
void MultiClass::dump() const {
3147 errs() << "Record:\n";
3150 errs() << "Defs:\n";
3151 for (const auto &E
: Entries
)