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/ADT/Twine.h"
19 #include "llvm/Config/llvm-config.h"
20 #include "llvm/Support/Casting.h"
21 #include "llvm/Support/Compiler.h"
22 #include "llvm/Support/ErrorHandling.h"
23 #include "llvm/Support/raw_ostream.h"
24 #include "llvm/Support/SourceMgr.h"
32 //===----------------------------------------------------------------------===//
33 // Support Code for the Semantic Actions.
34 //===----------------------------------------------------------------------===//
38 struct SubClassReference
{
41 SmallVector
<Init
*, 4> TemplateArgs
;
43 SubClassReference() : Rec(nullptr) {}
45 bool isInvalid() const { return Rec
== nullptr; }
48 struct SubMultiClassReference
{
51 SmallVector
<Init
*, 4> TemplateArgs
;
53 SubMultiClassReference() : MC(nullptr) {}
55 bool isInvalid() const { return MC
== nullptr; }
59 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
60 LLVM_DUMP_METHOD
void SubMultiClassReference::dump() const {
61 errs() << "Multiclass:\n";
65 errs() << "Template args:\n";
66 for (Init
*TA
: TemplateArgs
)
71 } // end namespace llvm
73 static bool checkBitsConcrete(Record
&R
, const RecordVal
&RV
) {
74 BitsInit
*BV
= cast
<BitsInit
>(RV
.getValue());
75 for (unsigned i
= 0, e
= BV
->getNumBits(); i
!= e
; ++i
) {
76 Init
*Bit
= BV
->getBit(i
);
77 bool IsReference
= false;
78 if (auto VBI
= dyn_cast
<VarBitInit
>(Bit
)) {
79 if (auto VI
= dyn_cast
<VarInit
>(VBI
->getBitVar())) {
80 if (R
.getValue(VI
->getName()))
83 } else if (isa
<VarInit
>(Bit
)) {
86 if (!(IsReference
|| Bit
->isConcrete()))
92 static void checkConcrete(Record
&R
) {
93 for (const RecordVal
&RV
: R
.getValues()) {
94 // HACK: Disable this check for variables declared with 'field'. This is
95 // done merely because existing targets have legitimate cases of
96 // non-concrete variables in helper defs. Ideally, we'd introduce a
97 // 'maybe' or 'optional' modifier instead of this.
98 if (RV
.isNonconcreteOK())
101 if (Init
*V
= RV
.getValue()) {
102 bool Ok
= isa
<BitsInit
>(V
) ? checkBitsConcrete(R
, RV
) : V
->isConcrete();
104 PrintError(R
.getLoc(),
105 Twine("Initializer of '") + RV
.getNameInitAsString() +
106 "' in '" + R
.getNameInitAsString() +
107 "' could not be fully resolved: " +
108 RV
.getValue()->getAsString());
114 /// Return an Init with a qualifier prefix referring
115 /// to CurRec's name.
116 static Init
*QualifyName(Record
&CurRec
, MultiClass
*CurMultiClass
,
117 Init
*Name
, StringRef Scoper
) {
119 BinOpInit::getStrConcat(CurRec
.getNameInit(), StringInit::get(Scoper
));
120 NewName
= BinOpInit::getStrConcat(NewName
, Name
);
121 if (CurMultiClass
&& Scoper
!= "::") {
122 Init
*Prefix
= BinOpInit::getStrConcat(CurMultiClass
->Rec
.getNameInit(),
123 StringInit::get("::"));
124 NewName
= BinOpInit::getStrConcat(Prefix
, NewName
);
127 if (BinOpInit
*BinOp
= dyn_cast
<BinOpInit
>(NewName
))
128 NewName
= BinOp
->Fold(&CurRec
);
132 /// Return the qualified version of the implicit 'NAME' template argument.
133 static Init
*QualifiedNameOfImplicitName(Record
&Rec
,
134 MultiClass
*MC
= nullptr) {
135 return QualifyName(Rec
, MC
, StringInit::get("NAME"), MC
? "::" : ":");
138 static Init
*QualifiedNameOfImplicitName(MultiClass
*MC
) {
139 return QualifiedNameOfImplicitName(MC
->Rec
, MC
);
142 bool TGParser::AddValue(Record
*CurRec
, SMLoc Loc
, const RecordVal
&RV
) {
144 CurRec
= &CurMultiClass
->Rec
;
146 if (RecordVal
*ERV
= CurRec
->getValue(RV
.getNameInit())) {
147 // The value already exists in the class, treat this as a set.
148 if (ERV
->setValue(RV
.getValue()))
149 return Error(Loc
, "New definition of '" + RV
.getName() + "' of type '" +
150 RV
.getType()->getAsString() + "' is incompatible with " +
151 "previous definition of type '" +
152 ERV
->getType()->getAsString() + "'");
154 CurRec
->addValue(RV
);
160 /// Return true on error, false on success.
161 bool TGParser::SetValue(Record
*CurRec
, SMLoc Loc
, Init
*ValName
,
162 ArrayRef
<unsigned> BitList
, Init
*V
,
163 bool AllowSelfAssignment
) {
164 if (!V
) return false;
166 if (!CurRec
) CurRec
= &CurMultiClass
->Rec
;
168 RecordVal
*RV
= CurRec
->getValue(ValName
);
170 return Error(Loc
, "Value '" + ValName
->getAsUnquotedString() +
173 // Do not allow assignments like 'X = X'. This will just cause infinite loops
174 // in the resolution machinery.
176 if (VarInit
*VI
= dyn_cast
<VarInit
>(V
))
177 if (VI
->getNameInit() == ValName
&& !AllowSelfAssignment
)
178 return Error(Loc
, "Recursion / self-assignment forbidden");
180 // If we are assigning to a subset of the bits in the value... then we must be
181 // assigning to a field of BitsRecTy, which must have a BitsInit
184 if (!BitList
.empty()) {
185 BitsInit
*CurVal
= dyn_cast
<BitsInit
>(RV
->getValue());
187 return Error(Loc
, "Value '" + ValName
->getAsUnquotedString() +
188 "' is not a bits type");
190 // Convert the incoming value to a bits type of the appropriate size...
191 Init
*BI
= V
->getCastTo(BitsRecTy::get(BitList
.size()));
193 return Error(Loc
, "Initializer is not compatible with bit range");
195 SmallVector
<Init
*, 16> NewBits(CurVal
->getNumBits());
197 // Loop over bits, assigning values as appropriate.
198 for (unsigned i
= 0, e
= BitList
.size(); i
!= e
; ++i
) {
199 unsigned Bit
= BitList
[i
];
201 return Error(Loc
, "Cannot set bit #" + Twine(Bit
) + " of value '" +
202 ValName
->getAsUnquotedString() + "' more than once");
203 NewBits
[Bit
] = BI
->getBit(i
);
206 for (unsigned i
= 0, e
= CurVal
->getNumBits(); i
!= e
; ++i
)
208 NewBits
[i
] = CurVal
->getBit(i
);
210 V
= BitsInit::get(NewBits
);
213 if (RV
->setValue(V
, Loc
)) {
214 std::string InitType
;
215 if (BitsInit
*BI
= dyn_cast
<BitsInit
>(V
))
216 InitType
= (Twine("' of type bit initializer with length ") +
217 Twine(BI
->getNumBits())).str();
218 else if (TypedInit
*TI
= dyn_cast
<TypedInit
>(V
))
219 InitType
= (Twine("' of type '") + TI
->getType()->getAsString()).str();
220 return Error(Loc
, "Field '" + ValName
->getAsUnquotedString() +
221 "' of type '" + RV
->getType()->getAsString() +
222 "' is incompatible with value '" +
223 V
->getAsString() + InitType
+ "'");
228 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
229 /// args as SubClass's template arguments.
230 bool TGParser::AddSubClass(Record
*CurRec
, SubClassReference
&SubClass
) {
231 Record
*SC
= SubClass
.Rec
;
232 MapResolver
R(CurRec
);
234 // Loop over all the subclass record's fields. Add template arguments
235 // to the resolver map. Add regular fields to the new record.
236 for (const RecordVal
&Field
: SC
->getValues()) {
237 if (Field
.isTemplateArg()) {
238 R
.set(Field
.getNameInit(), Field
.getValue());
240 if (AddValue(CurRec
, SubClass
.RefRange
.Start
, Field
))
245 ArrayRef
<Init
*> TArgs
= SC
->getTemplateArgs();
246 assert(SubClass
.TemplateArgs
.size() <= TArgs
.size() &&
247 "Too many template arguments allowed");
249 // Loop over the template argument names. If a value was specified,
250 // reset the map value. If not and there was no default, complain.
251 for (unsigned I
= 0, E
= TArgs
.size(); I
!= E
; ++I
) {
252 if (I
< SubClass
.TemplateArgs
.size())
253 R
.set(TArgs
[I
], SubClass
.TemplateArgs
[I
]);
254 else if (!R
.isComplete(TArgs
[I
]))
255 return Error(SubClass
.RefRange
.Start
,
256 "Value not specified for template argument '" +
257 TArgs
[I
]->getAsUnquotedString() + "' (#" + Twine(I
) +
258 ") of parent class '" + SC
->getNameInitAsString() + "'");
261 // Copy the subclass record's assertions to the new record.
262 CurRec
->appendAssertions(SC
);
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
);
298 for (auto &E
: Entry
.Loop
->Entries
) {
299 if (AddSubClass(E
, SubClass
))
306 /// AddSubMultiClass - Add SubMultiClass as a subclass to
307 /// CurMC, resolving its template args as SubMultiClass's
308 /// template arguments.
309 bool TGParser::AddSubMultiClass(MultiClass
*CurMC
,
310 SubMultiClassReference
&SubMultiClass
) {
311 MultiClass
*SMC
= SubMultiClass
.MC
;
313 ArrayRef
<Init
*> SMCTArgs
= SMC
->Rec
.getTemplateArgs();
314 if (SMCTArgs
.size() < SubMultiClass
.TemplateArgs
.size())
315 return Error(SubMultiClass
.RefRange
.Start
,
316 "More template args specified than expected");
318 // Prepare the mapping of template argument name to value, filling in default
319 // values if necessary.
320 SubstStack TemplateArgs
;
321 for (unsigned i
= 0, e
= SMCTArgs
.size(); i
!= e
; ++i
) {
322 if (i
< SubMultiClass
.TemplateArgs
.size()) {
323 TemplateArgs
.emplace_back(SMCTArgs
[i
], SubMultiClass
.TemplateArgs
[i
]);
325 Init
*Default
= SMC
->Rec
.getValue(SMCTArgs
[i
])->getValue();
326 if (!Default
->isComplete()) {
327 return Error(SubMultiClass
.RefRange
.Start
,
328 "value not specified for template argument #" + Twine(i
) +
329 " (" + SMCTArgs
[i
]->getAsUnquotedString() +
330 ") of multiclass '" + SMC
->Rec
.getNameInitAsString() +
333 TemplateArgs
.emplace_back(SMCTArgs
[i
], Default
);
337 TemplateArgs
.emplace_back(
338 QualifiedNameOfImplicitName(SMC
),
339 VarInit::get(QualifiedNameOfImplicitName(CurMC
), StringRecTy::get()));
341 // Add all of the defs in the subclass into the current multiclass.
342 return resolve(SMC
->Entries
, TemplateArgs
, false, &CurMC
->Entries
);
345 /// Add a record, foreach loop, or assertion to the current context.
346 bool TGParser::addEntry(RecordsEntry E
) {
347 assert((!!E
.Rec
+ !!E
.Loop
+ !!E
.Assertion
) == 1 &&
348 "RecordsEntry has invalid number of items");
350 // If we are parsing a loop, add it to the loop's entries.
351 if (!Loops
.empty()) {
352 Loops
.back()->Entries
.push_back(std::move(E
));
356 // If it is a loop, then resolve and perform the loop.
359 return resolve(*E
.Loop
, Stack
, CurMultiClass
== nullptr,
360 CurMultiClass
? &CurMultiClass
->Entries
: nullptr);
363 // If we are parsing a multiclass, add it to the multiclass's entries.
365 CurMultiClass
->Entries
.push_back(std::move(E
));
369 // If it is an assertion, then it's a top-level one, so check it.
371 CheckAssert(E
.Assertion
->Loc
, E
.Assertion
->Condition
, E
.Assertion
->Message
);
375 // It must be a record, so finish it off.
376 return addDefOne(std::move(E
.Rec
));
379 /// Resolve the entries in \p Loop, going over inner loops recursively
380 /// and making the given subsitutions of (name, value) pairs.
382 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
383 /// are added to the global record keeper.
384 bool TGParser::resolve(const ForeachLoop
&Loop
, SubstStack
&Substs
,
385 bool Final
, std::vector
<RecordsEntry
> *Dest
,
388 for (const auto &S
: Substs
)
389 R
.set(S
.first
, S
.second
);
390 Init
*List
= Loop
.ListValue
->resolveReferences(R
);
391 auto LI
= dyn_cast
<ListInit
>(List
);
394 Dest
->emplace_back(std::make_unique
<ForeachLoop
>(Loop
.Loc
, Loop
.IterVar
,
396 return resolve(Loop
.Entries
, Substs
, Final
, &Dest
->back().Loop
->Entries
,
400 PrintError(Loop
.Loc
, Twine("attempting to loop over '") +
401 List
->getAsString() + "', expected a list");
406 for (auto Elt
: *LI
) {
408 Substs
.emplace_back(Loop
.IterVar
->getNameInit(), Elt
);
409 Error
= resolve(Loop
.Entries
, Substs
, Final
, Dest
);
418 /// Resolve the entries in \p Source, going over loops recursively and
419 /// making the given substitutions of (name, value) pairs.
421 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
422 /// are added to the global record keeper.
423 bool TGParser::resolve(const std::vector
<RecordsEntry
> &Source
,
424 SubstStack
&Substs
, bool Final
,
425 std::vector
<RecordsEntry
> *Dest
, SMLoc
*Loc
) {
427 for (auto &E
: Source
) {
429 Error
= resolve(*E
.Loop
, Substs
, Final
, Dest
);
431 } else if (E
.Assertion
) {
433 for (const auto &S
: Substs
)
434 R
.set(S
.first
, S
.second
);
435 Init
*Condition
= E
.Assertion
->Condition
->resolveReferences(R
);
436 Init
*Message
= E
.Assertion
->Message
->resolveReferences(R
);
439 Dest
->push_back(std::make_unique
<Record::AssertionInfo
>(
440 E
.Assertion
->Loc
, Condition
, Message
));
442 CheckAssert(E
.Assertion
->Loc
, Condition
, Message
);
445 auto Rec
= std::make_unique
<Record
>(*E
.Rec
);
447 Rec
->appendLoc(*Loc
);
449 MapResolver
R(Rec
.get());
450 for (const auto &S
: Substs
)
451 R
.set(S
.first
, S
.second
);
452 Rec
->resolveReferences(R
);
455 Dest
->push_back(std::move(Rec
));
457 Error
= addDefOne(std::move(Rec
));
465 /// Resolve the record fully and add it to the record keeper.
466 bool TGParser::addDefOne(std::unique_ptr
<Record
> Rec
) {
467 Init
*NewName
= nullptr;
468 if (Record
*Prev
= Records
.getDef(Rec
->getNameInitAsString())) {
469 if (!Rec
->isAnonymous()) {
470 PrintError(Rec
->getLoc(),
471 "def already exists: " + Rec
->getNameInitAsString());
472 PrintNote(Prev
->getLoc(), "location of previous definition");
475 NewName
= Records
.getNewAnonymousName();
478 Rec
->resolveReferences(NewName
);
481 if (!isa
<StringInit
>(Rec
->getNameInit())) {
482 PrintError(Rec
->getLoc(), Twine("record name '") +
483 Rec
->getNameInit()->getAsString() +
484 "' could not be fully resolved");
488 // Check the assertions.
489 Rec
->checkRecordAssertions();
491 // If ObjectBody has template arguments, it's an error.
492 assert(Rec
->getTemplateArgs().empty() && "How'd this get template args?");
494 for (DefsetRecord
*Defset
: Defsets
) {
495 DefInit
*I
= Rec
->getDefInit();
496 if (!I
->getType()->typeIsA(Defset
->EltTy
)) {
497 PrintError(Rec
->getLoc(), Twine("adding record of incompatible type '") +
498 I
->getType()->getAsString() +
500 PrintNote(Defset
->Loc
, "location of defset declaration");
503 Defset
->Elements
.push_back(I
);
506 Records
.addDef(std::move(Rec
));
510 //===----------------------------------------------------------------------===//
512 //===----------------------------------------------------------------------===//
514 /// isObjectStart - Return true if this is a valid first token for a statement.
515 static bool isObjectStart(tgtok::TokKind K
) {
516 return K
== tgtok::Assert
|| K
== tgtok::Class
|| K
== tgtok::Def
||
517 K
== tgtok::Defm
|| K
== tgtok::Defset
|| K
== tgtok::Defvar
||
518 K
== tgtok::Foreach
|| K
== tgtok::If
|| K
== tgtok::Let
||
519 K
== tgtok::MultiClass
;
522 bool TGParser::consume(tgtok::TokKind K
) {
523 if (Lex
.getCode() == K
) {
530 /// ParseObjectName - If a valid object name is specified, return it. If no
531 /// name is specified, return the unset initializer. Return nullptr on parse
533 /// ObjectName ::= Value [ '#' Value ]*
534 /// ObjectName ::= /*empty*/
536 Init
*TGParser::ParseObjectName(MultiClass
*CurMultiClass
) {
537 switch (Lex
.getCode()) {
541 // These are all of the tokens that can begin an object body.
542 // Some of these can also begin values but we disallow those cases
543 // because they are unlikely to be useful.
544 return UnsetInit::get();
549 Record
*CurRec
= nullptr;
551 CurRec
= &CurMultiClass
->Rec
;
553 Init
*Name
= ParseValue(CurRec
, StringRecTy::get(), ParseNameMode
);
558 Init
*NameStr
= QualifiedNameOfImplicitName(CurMultiClass
);
559 HasReferenceResolver
R(NameStr
);
560 Name
->resolveReferences(R
);
562 Name
= BinOpInit::getStrConcat(VarInit::get(NameStr
, StringRecTy::get()),
569 /// ParseClassID - Parse and resolve a reference to a class name. This returns
574 Record
*TGParser::ParseClassID() {
575 if (Lex
.getCode() != tgtok::Id
) {
576 TokError("expected name for ClassID");
580 Record
*Result
= Records
.getClass(Lex
.getCurStrVal());
582 std::string
Msg("Couldn't find class '" + Lex
.getCurStrVal() + "'");
583 if (MultiClasses
[Lex
.getCurStrVal()].get())
584 TokError(Msg
+ ". Use 'defm' if you meant to use multiclass '" +
585 Lex
.getCurStrVal() + "'");
594 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
595 /// This returns null on error.
597 /// MultiClassID ::= ID
599 MultiClass
*TGParser::ParseMultiClassID() {
600 if (Lex
.getCode() != tgtok::Id
) {
601 TokError("expected name for MultiClassID");
605 MultiClass
*Result
= MultiClasses
[Lex
.getCurStrVal()].get();
607 TokError("Couldn't find multiclass '" + Lex
.getCurStrVal() + "'");
613 /// ParseSubClassReference - Parse a reference to a subclass or a
614 /// multiclass. This returns a SubClassRefTy with a null Record* on error.
616 /// SubClassRef ::= ClassID
617 /// SubClassRef ::= ClassID '<' ValueList '>'
619 SubClassReference
TGParser::
620 ParseSubClassReference(Record
*CurRec
, bool isDefm
) {
621 SubClassReference Result
;
622 Result
.RefRange
.Start
= Lex
.getLoc();
625 if (MultiClass
*MC
= ParseMultiClassID())
626 Result
.Rec
= &MC
->Rec
;
628 Result
.Rec
= ParseClassID();
630 if (!Result
.Rec
) return Result
;
632 // If there is no template arg list, we're done.
633 if (!consume(tgtok::less
)) {
634 Result
.RefRange
.End
= Lex
.getLoc();
638 if (ParseTemplateArgValueList(Result
.TemplateArgs
, CurRec
, Result
.Rec
)) {
639 Result
.Rec
= nullptr; // Error parsing value list.
643 if (CheckTemplateArgValues(Result
.TemplateArgs
, Result
.RefRange
.Start
,
645 Result
.Rec
= nullptr; // Error checking value list.
649 Result
.RefRange
.End
= Lex
.getLoc();
653 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
654 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
655 /// Record* on error.
657 /// SubMultiClassRef ::= MultiClassID
658 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
660 SubMultiClassReference
TGParser::
661 ParseSubMultiClassReference(MultiClass
*CurMC
) {
662 SubMultiClassReference Result
;
663 Result
.RefRange
.Start
= Lex
.getLoc();
665 Result
.MC
= ParseMultiClassID();
666 if (!Result
.MC
) return Result
;
668 // If there is no template arg list, we're done.
669 if (!consume(tgtok::less
)) {
670 Result
.RefRange
.End
= Lex
.getLoc();
674 if (ParseTemplateArgValueList(Result
.TemplateArgs
, &CurMC
->Rec
,
676 Result
.MC
= nullptr; // Error parsing value list.
680 Result
.RefRange
.End
= Lex
.getLoc();
685 /// ParseRangePiece - Parse a bit/value range.
686 /// RangePiece ::= INTVAL
687 /// RangePiece ::= INTVAL '...' INTVAL
688 /// RangePiece ::= INTVAL '-' INTVAL
689 /// RangePiece ::= INTVAL INTVAL
690 // The last two forms are deprecated.
691 bool TGParser::ParseRangePiece(SmallVectorImpl
<unsigned> &Ranges
,
692 TypedInit
*FirstItem
) {
693 Init
*CurVal
= FirstItem
;
695 CurVal
= ParseValue(nullptr);
697 IntInit
*II
= dyn_cast_or_null
<IntInit
>(CurVal
);
699 return TokError("expected integer or bitrange");
701 int64_t Start
= II
->getValue();
705 return TokError("invalid range, cannot be negative");
707 switch (Lex
.getCode()) {
709 Ranges
.push_back(Start
);
712 case tgtok::dotdotdot
:
716 Init
*I_End
= ParseValue(nullptr);
717 IntInit
*II_End
= dyn_cast_or_null
<IntInit
>(I_End
);
719 TokError("expected integer value as end of range");
723 End
= II_End
->getValue();
726 case tgtok::IntVal
: {
727 End
= -Lex
.getCurIntVal();
733 return TokError("invalid range, cannot be negative");
737 for (; Start
<= End
; ++Start
)
738 Ranges
.push_back(Start
);
740 for (; Start
>= End
; --Start
)
741 Ranges
.push_back(Start
);
745 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
747 /// RangeList ::= RangePiece (',' RangePiece)*
749 void TGParser::ParseRangeList(SmallVectorImpl
<unsigned> &Result
) {
750 // Parse the first piece.
751 if (ParseRangePiece(Result
)) {
755 while (consume(tgtok::comma
))
756 // Parse the next range piece.
757 if (ParseRangePiece(Result
)) {
763 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
764 /// OptionalRangeList ::= '<' RangeList '>'
765 /// OptionalRangeList ::= /*empty*/
766 bool TGParser::ParseOptionalRangeList(SmallVectorImpl
<unsigned> &Ranges
) {
767 SMLoc StartLoc
= Lex
.getLoc();
768 if (!consume(tgtok::less
))
771 // Parse the range list.
772 ParseRangeList(Ranges
);
773 if (Ranges
.empty()) return true;
775 if (!consume(tgtok::greater
)) {
776 TokError("expected '>' at end of range list");
777 return Error(StartLoc
, "to match this '<'");
782 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
783 /// OptionalBitList ::= '{' RangeList '}'
784 /// OptionalBitList ::= /*empty*/
785 bool TGParser::ParseOptionalBitList(SmallVectorImpl
<unsigned> &Ranges
) {
786 SMLoc StartLoc
= Lex
.getLoc();
787 if (!consume(tgtok::l_brace
))
790 // Parse the range list.
791 ParseRangeList(Ranges
);
792 if (Ranges
.empty()) return true;
794 if (!consume(tgtok::r_brace
)) {
795 TokError("expected '}' at end of bit list");
796 return Error(StartLoc
, "to match this '{'");
801 /// ParseType - Parse and return a tblgen type. This returns null on error.
803 /// Type ::= STRING // string type
804 /// Type ::= CODE // code type
805 /// Type ::= BIT // bit type
806 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
807 /// Type ::= INT // int type
808 /// Type ::= LIST '<' Type '>' // list<x> type
809 /// Type ::= DAG // dag type
810 /// Type ::= ClassID // Record Type
812 RecTy
*TGParser::ParseType() {
813 switch (Lex
.getCode()) {
814 default: TokError("Unknown token when expecting a type"); return nullptr;
816 case tgtok::Code
: Lex
.Lex(); return StringRecTy::get();
817 case tgtok::Bit
: Lex
.Lex(); return BitRecTy::get();
818 case tgtok::Int
: Lex
.Lex(); return IntRecTy::get();
819 case tgtok::Dag
: Lex
.Lex(); return DagRecTy::get();
821 if (Record
*R
= ParseClassID()) return RecordRecTy::get(R
);
822 TokError("unknown class name");
825 if (Lex
.Lex() != tgtok::less
) { // Eat 'bits'
826 TokError("expected '<' after bits type");
829 if (Lex
.Lex() != tgtok::IntVal
) { // Eat '<'
830 TokError("expected integer in bits<n> type");
833 uint64_t Val
= Lex
.getCurIntVal();
834 if (Lex
.Lex() != tgtok::greater
) { // Eat count.
835 TokError("expected '>' at end of bits<n> type");
838 Lex
.Lex(); // Eat '>'
839 return BitsRecTy::get(Val
);
842 if (Lex
.Lex() != tgtok::less
) { // Eat 'bits'
843 TokError("expected '<' after list type");
846 Lex
.Lex(); // Eat '<'
847 RecTy
*SubType
= ParseType();
848 if (!SubType
) return nullptr;
850 if (!consume(tgtok::greater
)) {
851 TokError("expected '>' at end of list<ty> type");
854 return ListRecTy::get(SubType
);
860 Init
*TGParser::ParseIDValue(Record
*CurRec
, StringInit
*Name
, SMLoc NameLoc
,
863 if (const RecordVal
*RV
= CurRec
->getValue(Name
))
864 return VarInit::get(Name
, RV
->getType());
867 if ((CurRec
&& CurRec
->isClass()) || CurMultiClass
) {
868 Init
*TemplateArgName
;
871 QualifyName(CurMultiClass
->Rec
, CurMultiClass
, Name
, "::");
873 TemplateArgName
= QualifyName(*CurRec
, CurMultiClass
, Name
, ":");
875 Record
*TemplateRec
= CurMultiClass
? &CurMultiClass
->Rec
: CurRec
;
876 if (TemplateRec
->isTemplateArg(TemplateArgName
)) {
877 const RecordVal
*RV
= TemplateRec
->getValue(TemplateArgName
);
878 assert(RV
&& "Template arg doesn't exist??");
879 return VarInit::get(TemplateArgName
, RV
->getType());
880 } else if (Name
->getValue() == "NAME") {
881 return VarInit::get(TemplateArgName
, StringRecTy::get());
886 if (Init
*I
= CurLocalScope
->getVar(Name
->getValue()))
889 // If this is in a foreach loop, make sure it's not a loop iterator
890 for (const auto &L
: Loops
) {
892 VarInit
*IterVar
= dyn_cast
<VarInit
>(L
->IterVar
);
893 if (IterVar
&& IterVar
->getNameInit() == Name
)
898 if (Mode
== ParseNameMode
)
901 if (Init
*I
= Records
.getGlobal(Name
->getValue()))
904 // Allow self-references of concrete defs, but delay the lookup so that we
905 // get the correct type.
906 if (CurRec
&& !CurRec
->isClass() && !CurMultiClass
&&
907 CurRec
->getNameInit() == Name
)
908 return UnOpInit::get(UnOpInit::CAST
, Name
, CurRec
->getType());
910 Error(NameLoc
, "Variable not defined: '" + Name
->getValue() + "'");
914 /// ParseOperation - Parse an operator. This returns null on error.
916 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
918 Init
*TGParser::ParseOperation(Record
*CurRec
, RecTy
*ItemType
) {
919 switch (Lex
.getCode()) {
921 TokError("unknown bang operator");
929 case tgtok::XGetDagOp
: { // Value ::= !unop '(' Value ')'
930 UnOpInit::UnaryOp Code
;
931 RecTy
*Type
= nullptr;
933 switch (Lex
.getCode()) {
934 default: llvm_unreachable("Unhandled code!");
936 Lex
.Lex(); // eat the operation
937 Code
= UnOpInit::CAST
;
939 Type
= ParseOperatorType();
942 TokError("did not get type for unary operator");
948 Lex
.Lex(); // eat the operation
949 Code
= UnOpInit::NOT
;
950 Type
= IntRecTy::get();
953 Lex
.Lex(); // eat the operation
954 Code
= UnOpInit::HEAD
;
957 Lex
.Lex(); // eat the operation
958 Code
= UnOpInit::TAIL
;
962 Code
= UnOpInit::SIZE
;
963 Type
= IntRecTy::get();
966 Lex
.Lex(); // eat the operation
967 Code
= UnOpInit::EMPTY
;
968 Type
= IntRecTy::get();
970 case tgtok::XGetDagOp
:
971 Lex
.Lex(); // eat the operation
972 if (Lex
.getCode() == tgtok::less
) {
973 // Parse an optional type suffix, so that you can say
974 // !getdagop<BaseClass>(someDag) as a shorthand for
975 // !cast<BaseClass>(!getdagop(someDag)).
976 Type
= ParseOperatorType();
979 TokError("did not get type for unary operator");
983 if (!isa
<RecordRecTy
>(Type
)) {
984 TokError("type for !getdagop must be a record type");
985 // but keep parsing, to consume the operand
988 Type
= RecordRecTy::get({});
990 Code
= UnOpInit::GETDAGOP
;
993 if (!consume(tgtok::l_paren
)) {
994 TokError("expected '(' after unary operator");
998 Init
*LHS
= ParseValue(CurRec
);
999 if (!LHS
) return nullptr;
1001 if (Code
== UnOpInit::EMPTY
|| Code
== UnOpInit::SIZE
) {
1002 ListInit
*LHSl
= dyn_cast
<ListInit
>(LHS
);
1003 StringInit
*LHSs
= dyn_cast
<StringInit
>(LHS
);
1004 DagInit
*LHSd
= dyn_cast
<DagInit
>(LHS
);
1005 TypedInit
*LHSt
= dyn_cast
<TypedInit
>(LHS
);
1006 if (!LHSl
&& !LHSs
&& !LHSd
&& !LHSt
) {
1007 TokError("expected string, list, or dag type argument in unary operator");
1011 ListRecTy
*LType
= dyn_cast
<ListRecTy
>(LHSt
->getType());
1012 StringRecTy
*SType
= dyn_cast
<StringRecTy
>(LHSt
->getType());
1013 DagRecTy
*DType
= dyn_cast
<DagRecTy
>(LHSt
->getType());
1014 if (!LType
&& !SType
&& !DType
) {
1015 TokError("expected string, list, or dag type argument in unary operator");
1021 if (Code
== UnOpInit::HEAD
|| Code
== UnOpInit::TAIL
) {
1022 ListInit
*LHSl
= dyn_cast
<ListInit
>(LHS
);
1023 TypedInit
*LHSt
= dyn_cast
<TypedInit
>(LHS
);
1024 if (!LHSl
&& !LHSt
) {
1025 TokError("expected list type argument in unary operator");
1029 ListRecTy
*LType
= dyn_cast
<ListRecTy
>(LHSt
->getType());
1031 TokError("expected list type argument in unary operator");
1036 if (LHSl
&& LHSl
->empty()) {
1037 TokError("empty list argument in unary operator");
1041 Init
*Item
= LHSl
->getElement(0);
1042 TypedInit
*Itemt
= dyn_cast
<TypedInit
>(Item
);
1044 TokError("untyped list element in unary operator");
1047 Type
= (Code
== UnOpInit::HEAD
) ? Itemt
->getType()
1048 : ListRecTy::get(Itemt
->getType());
1050 assert(LHSt
&& "expected list type argument in unary operator");
1051 ListRecTy
*LType
= dyn_cast
<ListRecTy
>(LHSt
->getType());
1052 Type
= (Code
== UnOpInit::HEAD
) ? LType
->getElementType() : LType
;
1056 if (!consume(tgtok::r_paren
)) {
1057 TokError("expected ')' in unary operator");
1060 return (UnOpInit::get(Code
, LHS
, Type
))->Fold(CurRec
);
1064 // Value ::= !isa '<' Type '>' '(' Value ')'
1065 Lex
.Lex(); // eat the operation
1067 RecTy
*Type
= ParseOperatorType();
1071 if (!consume(tgtok::l_paren
)) {
1072 TokError("expected '(' after type of !isa");
1076 Init
*LHS
= ParseValue(CurRec
);
1080 if (!consume(tgtok::r_paren
)) {
1081 TokError("expected ')' in !isa");
1085 return (IsAOpInit::get(Type
, LHS
))->Fold();
1088 case tgtok::XConcat
:
1104 case tgtok::XListConcat
:
1105 case tgtok::XListSplat
:
1106 case tgtok::XStrConcat
:
1107 case tgtok::XInterleave
:
1108 case tgtok::XSetDagOp
: { // Value ::= !binop '(' Value ',' Value ')'
1109 tgtok::TokKind OpTok
= Lex
.getCode();
1110 SMLoc OpLoc
= Lex
.getLoc();
1111 Lex
.Lex(); // eat the operation
1113 BinOpInit::BinaryOp Code
;
1115 default: llvm_unreachable("Unhandled code!");
1116 case tgtok::XConcat
: Code
= BinOpInit::CONCAT
; break;
1117 case tgtok::XADD
: Code
= BinOpInit::ADD
; break;
1118 case tgtok::XSUB
: Code
= BinOpInit::SUB
; break;
1119 case tgtok::XMUL
: Code
= BinOpInit::MUL
; break;
1120 case tgtok::XAND
: Code
= BinOpInit::AND
; break;
1121 case tgtok::XOR
: Code
= BinOpInit::OR
; break;
1122 case tgtok::XXOR
: Code
= BinOpInit::XOR
; break;
1123 case tgtok::XSRA
: Code
= BinOpInit::SRA
; break;
1124 case tgtok::XSRL
: Code
= BinOpInit::SRL
; break;
1125 case tgtok::XSHL
: Code
= BinOpInit::SHL
; break;
1126 case tgtok::XEq
: Code
= BinOpInit::EQ
; break;
1127 case tgtok::XNe
: Code
= BinOpInit::NE
; break;
1128 case tgtok::XLe
: Code
= BinOpInit::LE
; break;
1129 case tgtok::XLt
: Code
= BinOpInit::LT
; break;
1130 case tgtok::XGe
: Code
= BinOpInit::GE
; break;
1131 case tgtok::XGt
: Code
= BinOpInit::GT
; break;
1132 case tgtok::XListConcat
: Code
= BinOpInit::LISTCONCAT
; break;
1133 case tgtok::XListSplat
: Code
= BinOpInit::LISTSPLAT
; break;
1134 case tgtok::XStrConcat
: Code
= BinOpInit::STRCONCAT
; break;
1135 case tgtok::XInterleave
: Code
= BinOpInit::INTERLEAVE
; break;
1136 case tgtok::XSetDagOp
: Code
= BinOpInit::SETDAGOP
; break;
1139 RecTy
*Type
= nullptr;
1140 RecTy
*ArgType
= nullptr;
1143 llvm_unreachable("Unhandled code!");
1144 case tgtok::XConcat
:
1145 case tgtok::XSetDagOp
:
1146 Type
= DagRecTy::get();
1147 ArgType
= DagRecTy::get();
1158 Type
= IntRecTy::get();
1159 ArgType
= IntRecTy::get();
1167 Type
= BitRecTy::get();
1168 // ArgType for the comparison operators is not yet known.
1170 case tgtok::XListConcat
:
1171 // We don't know the list type until we parse the first argument
1174 case tgtok::XListSplat
:
1175 // Can't do any typechecking until we parse the first argument.
1177 case tgtok::XStrConcat
:
1178 Type
= StringRecTy::get();
1179 ArgType
= StringRecTy::get();
1181 case tgtok::XInterleave
:
1182 Type
= StringRecTy::get();
1183 // The first argument type is not yet known.
1186 if (Type
&& ItemType
&& !Type
->typeIsConvertibleTo(ItemType
)) {
1187 Error(OpLoc
, Twine("expected value of type '") +
1188 ItemType
->getAsString() + "', got '" +
1189 Type
->getAsString() + "'");
1193 if (!consume(tgtok::l_paren
)) {
1194 TokError("expected '(' after binary operator");
1198 SmallVector
<Init
*, 2> InitList
;
1200 // Note that this loop consumes an arbitrary number of arguments.
1201 // The actual count is checked later.
1203 SMLoc InitLoc
= Lex
.getLoc();
1204 InitList
.push_back(ParseValue(CurRec
, ArgType
));
1205 if (!InitList
.back()) return nullptr;
1207 TypedInit
*InitListBack
= dyn_cast
<TypedInit
>(InitList
.back());
1208 if (!InitListBack
) {
1209 Error(OpLoc
, Twine("expected value to be a typed value, got '" +
1210 InitList
.back()->getAsString() + "'"));
1213 RecTy
*ListType
= InitListBack
->getType();
1216 // Argument type must be determined from the argument itself.
1220 case BinOpInit::LISTCONCAT
:
1221 if (!isa
<ListRecTy
>(ArgType
)) {
1222 Error(InitLoc
, Twine("expected a list, got value of type '") +
1223 ArgType
->getAsString() + "'");
1227 case BinOpInit::LISTSPLAT
:
1228 if (ItemType
&& InitList
.size() == 1) {
1229 if (!isa
<ListRecTy
>(ItemType
)) {
1231 Twine("expected output type to be a list, got type '") +
1232 ItemType
->getAsString() + "'");
1235 if (!ArgType
->getListTy()->typeIsConvertibleTo(ItemType
)) {
1236 Error(OpLoc
, Twine("expected first arg type to be '") +
1237 ArgType
->getAsString() +
1238 "', got value of type '" +
1239 cast
<ListRecTy
>(ItemType
)
1246 if (InitList
.size() == 2 && !isa
<IntRecTy
>(ArgType
)) {
1247 Error(InitLoc
, Twine("expected second parameter to be an int, got "
1248 "value of type '") +
1249 ArgType
->getAsString() + "'");
1252 ArgType
= nullptr; // Broken invariant: types not identical.
1256 if (!ArgType
->typeIsConvertibleTo(IntRecTy::get()) &&
1257 !ArgType
->typeIsConvertibleTo(StringRecTy::get()) &&
1258 !ArgType
->typeIsConvertibleTo(RecordRecTy::get({}))) {
1259 Error(InitLoc
, Twine("expected bit, bits, int, string, or record; "
1260 "got value of type '") + ArgType
->getAsString() +
1269 if (!ArgType
->typeIsConvertibleTo(IntRecTy::get()) &&
1270 !ArgType
->typeIsConvertibleTo(StringRecTy::get())) {
1271 Error(InitLoc
, Twine("expected bit, bits, int, or string; "
1272 "got value of type '") + ArgType
->getAsString() +
1277 case BinOpInit::INTERLEAVE
:
1278 switch (InitList
.size()) {
1279 case 1: // First argument must be a list of strings or integers.
1280 if (ArgType
!= StringRecTy::get()->getListTy() &&
1281 !ArgType
->typeIsConvertibleTo(IntRecTy::get()->getListTy())) {
1282 Error(InitLoc
, Twine("expected list of string, int, bits, or bit; "
1283 "got value of type '") +
1284 ArgType
->getAsString() + "'");
1288 case 2: // Second argument must be a string.
1289 if (!isa
<StringRecTy
>(ArgType
)) {
1290 Error(InitLoc
, Twine("expected second argument to be a string, "
1291 "got value of type '") +
1292 ArgType
->getAsString() + "'");
1298 ArgType
= nullptr; // Broken invariant: types not identical.
1300 default: llvm_unreachable("other ops have fixed argument types");
1304 // Desired argument type is a known and in ArgType.
1305 RecTy
*Resolved
= resolveTypes(ArgType
, ListType
);
1307 Error(InitLoc
, Twine("expected value of type '") +
1308 ArgType
->getAsString() + "', got '" +
1309 ListType
->getAsString() + "'");
1312 if (Code
!= BinOpInit::ADD
&& Code
!= BinOpInit::SUB
&&
1313 Code
!= BinOpInit::AND
&& Code
!= BinOpInit::OR
&&
1314 Code
!= BinOpInit::XOR
&& Code
!= BinOpInit::SRA
&&
1315 Code
!= BinOpInit::SRL
&& Code
!= BinOpInit::SHL
&&
1316 Code
!= BinOpInit::MUL
)
1320 // Deal with BinOps whose arguments have different types, by
1321 // rewriting ArgType in between them.
1323 case BinOpInit::SETDAGOP
:
1324 // After parsing the first dag argument, switch to expecting
1325 // a record, with no restriction on its superclasses.
1326 ArgType
= RecordRecTy::get({});
1332 if (!consume(tgtok::comma
))
1336 if (!consume(tgtok::r_paren
)) {
1337 TokError("expected ')' in operator");
1341 // listconcat returns a list with type of the argument.
1342 if (Code
== BinOpInit::LISTCONCAT
)
1344 // listsplat returns a list of type of the *first* argument.
1345 if (Code
== BinOpInit::LISTSPLAT
)
1346 Type
= cast
<TypedInit
>(InitList
.front())->getType()->getListTy();
1348 // We allow multiple operands to associative operators like !strconcat as
1349 // shorthand for nesting them.
1350 if (Code
== BinOpInit::STRCONCAT
|| Code
== BinOpInit::LISTCONCAT
||
1351 Code
== BinOpInit::CONCAT
|| Code
== BinOpInit::ADD
||
1352 Code
== BinOpInit::AND
|| Code
== BinOpInit::OR
||
1353 Code
== BinOpInit::XOR
|| Code
== BinOpInit::MUL
) {
1354 while (InitList
.size() > 2) {
1355 Init
*RHS
= InitList
.pop_back_val();
1356 RHS
= (BinOpInit::get(Code
, InitList
.back(), RHS
, Type
))->Fold(CurRec
);
1357 InitList
.back() = RHS
;
1361 if (InitList
.size() == 2)
1362 return (BinOpInit::get(Code
, InitList
[0], InitList
[1], Type
))
1365 Error(OpLoc
, "expected two operands to operator");
1369 case tgtok::XForEach
:
1370 case tgtok::XFilter
: {
1371 return ParseOperationForEachFilter(CurRec
, ItemType
);
1376 case tgtok::XSubst
: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1377 TernOpInit::TernaryOp Code
;
1378 RecTy
*Type
= nullptr;
1380 tgtok::TokKind LexCode
= Lex
.getCode();
1381 Lex
.Lex(); // eat the operation
1383 default: llvm_unreachable("Unhandled code!");
1385 Code
= TernOpInit::DAG
;
1386 Type
= DagRecTy::get();
1390 Code
= TernOpInit::IF
;
1393 Code
= TernOpInit::SUBST
;
1396 if (!consume(tgtok::l_paren
)) {
1397 TokError("expected '(' after ternary operator");
1401 Init
*LHS
= ParseValue(CurRec
);
1402 if (!LHS
) return nullptr;
1404 if (!consume(tgtok::comma
)) {
1405 TokError("expected ',' in ternary operator");
1409 SMLoc MHSLoc
= Lex
.getLoc();
1410 Init
*MHS
= ParseValue(CurRec
, ItemType
);
1414 if (!consume(tgtok::comma
)) {
1415 TokError("expected ',' in ternary operator");
1419 SMLoc RHSLoc
= Lex
.getLoc();
1420 Init
*RHS
= ParseValue(CurRec
, ItemType
);
1424 if (!consume(tgtok::r_paren
)) {
1425 TokError("expected ')' in binary operator");
1430 default: llvm_unreachable("Unhandled code!");
1432 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
1433 if (!MHSt
&& !isa
<UnsetInit
>(MHS
)) {
1434 Error(MHSLoc
, "could not determine type of the child list in !dag");
1437 if (MHSt
&& !isa
<ListRecTy
>(MHSt
->getType())) {
1438 Error(MHSLoc
, Twine("expected list of children, got type '") +
1439 MHSt
->getType()->getAsString() + "'");
1443 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
1444 if (!RHSt
&& !isa
<UnsetInit
>(RHS
)) {
1445 Error(RHSLoc
, "could not determine type of the name list in !dag");
1448 if (RHSt
&& StringRecTy::get()->getListTy() != RHSt
->getType()) {
1449 Error(RHSLoc
, Twine("expected list<string>, got type '") +
1450 RHSt
->getType()->getAsString() + "'");
1454 if (!MHSt
&& !RHSt
) {
1456 "cannot have both unset children and unset names in !dag");
1462 RecTy
*MHSTy
= nullptr;
1463 RecTy
*RHSTy
= nullptr;
1465 if (TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
))
1466 MHSTy
= MHSt
->getType();
1467 if (BitsInit
*MHSbits
= dyn_cast
<BitsInit
>(MHS
))
1468 MHSTy
= BitsRecTy::get(MHSbits
->getNumBits());
1469 if (isa
<BitInit
>(MHS
))
1470 MHSTy
= BitRecTy::get();
1472 if (TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
))
1473 RHSTy
= RHSt
->getType();
1474 if (BitsInit
*RHSbits
= dyn_cast
<BitsInit
>(RHS
))
1475 RHSTy
= BitsRecTy::get(RHSbits
->getNumBits());
1476 if (isa
<BitInit
>(RHS
))
1477 RHSTy
= BitRecTy::get();
1479 // For UnsetInit, it's typed from the other hand.
1480 if (isa
<UnsetInit
>(MHS
))
1482 if (isa
<UnsetInit
>(RHS
))
1485 if (!MHSTy
|| !RHSTy
) {
1486 TokError("could not get type for !if");
1490 Type
= resolveTypes(MHSTy
, RHSTy
);
1492 TokError(Twine("inconsistent types '") + MHSTy
->getAsString() +
1493 "' and '" + RHSTy
->getAsString() + "' for !if");
1498 case tgtok::XSubst
: {
1499 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
1501 TokError("could not get type for !subst");
1504 Type
= RHSt
->getType();
1508 return (TernOpInit::get(Code
, LHS
, MHS
, RHS
, Type
))->Fold(CurRec
);
1511 case tgtok::XSubstr
:
1512 return ParseOperationSubstr(CurRec
, ItemType
);
1515 return ParseOperationFind(CurRec
, ItemType
);
1518 return ParseOperationCond(CurRec
, ItemType
);
1520 case tgtok::XFoldl
: {
1521 // Value ::= !foldl '(' Value ',' Value ',' Id ',' Id ',' Expr ')'
1522 Lex
.Lex(); // eat the operation
1523 if (!consume(tgtok::l_paren
)) {
1524 TokError("expected '(' after !foldl");
1528 Init
*StartUntyped
= ParseValue(CurRec
);
1532 TypedInit
*Start
= dyn_cast
<TypedInit
>(StartUntyped
);
1534 TokError(Twine("could not get type of !foldl start: '") +
1535 StartUntyped
->getAsString() + "'");
1539 if (!consume(tgtok::comma
)) {
1540 TokError("expected ',' in !foldl");
1544 Init
*ListUntyped
= ParseValue(CurRec
);
1548 TypedInit
*List
= dyn_cast
<TypedInit
>(ListUntyped
);
1550 TokError(Twine("could not get type of !foldl list: '") +
1551 ListUntyped
->getAsString() + "'");
1555 ListRecTy
*ListType
= dyn_cast
<ListRecTy
>(List
->getType());
1557 TokError(Twine("!foldl list must be a list, but is of type '") +
1558 List
->getType()->getAsString());
1562 if (Lex
.getCode() != tgtok::comma
) {
1563 TokError("expected ',' in !foldl");
1567 if (Lex
.Lex() != tgtok::Id
) { // eat the ','
1568 TokError("third argument of !foldl must be an identifier");
1572 Init
*A
= StringInit::get(Lex
.getCurStrVal());
1573 if (CurRec
&& CurRec
->getValue(A
)) {
1574 TokError((Twine("left !foldl variable '") + A
->getAsString() +
1575 "' already defined")
1580 if (Lex
.Lex() != tgtok::comma
) { // eat the id
1581 TokError("expected ',' in !foldl");
1585 if (Lex
.Lex() != tgtok::Id
) { // eat the ','
1586 TokError("fourth argument of !foldl must be an identifier");
1590 Init
*B
= StringInit::get(Lex
.getCurStrVal());
1591 if (CurRec
&& CurRec
->getValue(B
)) {
1592 TokError((Twine("right !foldl variable '") + B
->getAsString() +
1593 "' already defined")
1598 if (Lex
.Lex() != tgtok::comma
) { // eat the id
1599 TokError("expected ',' in !foldl");
1602 Lex
.Lex(); // eat the ','
1604 // We need to create a temporary record to provide a scope for the
1606 std::unique_ptr
<Record
> ParseRecTmp
;
1607 Record
*ParseRec
= CurRec
;
1609 ParseRecTmp
= std::make_unique
<Record
>(".parse", ArrayRef
<SMLoc
>{}, Records
);
1610 ParseRec
= ParseRecTmp
.get();
1613 ParseRec
->addValue(RecordVal(A
, Start
->getType(), RecordVal::FK_Normal
));
1614 ParseRec
->addValue(RecordVal(B
, ListType
->getElementType(),
1615 RecordVal::FK_Normal
));
1616 Init
*ExprUntyped
= ParseValue(ParseRec
);
1617 ParseRec
->removeValue(A
);
1618 ParseRec
->removeValue(B
);
1622 TypedInit
*Expr
= dyn_cast
<TypedInit
>(ExprUntyped
);
1624 TokError("could not get type of !foldl expression");
1628 if (Expr
->getType() != Start
->getType()) {
1629 TokError(Twine("!foldl expression must be of same type as start (") +
1630 Start
->getType()->getAsString() + "), but is of type " +
1631 Expr
->getType()->getAsString());
1635 if (!consume(tgtok::r_paren
)) {
1636 TokError("expected ')' in fold operator");
1640 return FoldOpInit::get(Start
, List
, A
, B
, Expr
, Start
->getType())
1646 /// ParseOperatorType - Parse a type for an operator. This returns
1649 /// OperatorType ::= '<' Type '>'
1651 RecTy
*TGParser::ParseOperatorType() {
1652 RecTy
*Type
= nullptr;
1654 if (!consume(tgtok::less
)) {
1655 TokError("expected type name for operator");
1659 if (Lex
.getCode() == tgtok::Code
)
1660 TokError("the 'code' type is not allowed in bang operators; use 'string'");
1665 TokError("expected type name for operator");
1669 if (!consume(tgtok::greater
)) {
1670 TokError("expected type name for operator");
1677 /// Parse the !substr operation. Return null on error.
1679 /// Substr ::= !substr(string, start-int [, length-int]) => string
1680 Init
*TGParser::ParseOperationSubstr(Record
*CurRec
, RecTy
*ItemType
) {
1681 TernOpInit::TernaryOp Code
= TernOpInit::SUBSTR
;
1682 RecTy
*Type
= StringRecTy::get();
1684 Lex
.Lex(); // eat the operation
1686 if (!consume(tgtok::l_paren
)) {
1687 TokError("expected '(' after !substr operator");
1691 Init
*LHS
= ParseValue(CurRec
);
1695 if (!consume(tgtok::comma
)) {
1696 TokError("expected ',' in !substr operator");
1700 SMLoc MHSLoc
= Lex
.getLoc();
1701 Init
*MHS
= ParseValue(CurRec
);
1705 SMLoc RHSLoc
= Lex
.getLoc();
1707 if (consume(tgtok::comma
)) {
1708 RHSLoc
= Lex
.getLoc();
1709 RHS
= ParseValue(CurRec
);
1713 RHS
= IntInit::get(std::numeric_limits
<int64_t>::max());
1716 if (!consume(tgtok::r_paren
)) {
1717 TokError("expected ')' in !substr operator");
1721 if (ItemType
&& !Type
->typeIsConvertibleTo(ItemType
)) {
1722 Error(RHSLoc
, Twine("expected value of type '") +
1723 ItemType
->getAsString() + "', got '" +
1724 Type
->getAsString() + "'");
1727 TypedInit
*LHSt
= dyn_cast
<TypedInit
>(LHS
);
1728 if (!LHSt
&& !isa
<UnsetInit
>(LHS
)) {
1729 TokError("could not determine type of the string in !substr");
1732 if (LHSt
&& !isa
<StringRecTy
>(LHSt
->getType())) {
1733 TokError(Twine("expected string, got type '") +
1734 LHSt
->getType()->getAsString() + "'");
1738 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
1739 if (!MHSt
&& !isa
<UnsetInit
>(MHS
)) {
1740 TokError("could not determine type of the start position in !substr");
1743 if (MHSt
&& !isa
<IntRecTy
>(MHSt
->getType())) {
1744 Error(MHSLoc
, Twine("expected int, got type '") +
1745 MHSt
->getType()->getAsString() + "'");
1750 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
1751 if (!RHSt
&& !isa
<UnsetInit
>(RHS
)) {
1752 TokError("could not determine type of the length in !substr");
1755 if (RHSt
&& !isa
<IntRecTy
>(RHSt
->getType())) {
1756 TokError(Twine("expected int, got type '") +
1757 RHSt
->getType()->getAsString() + "'");
1762 return (TernOpInit::get(Code
, LHS
, MHS
, RHS
, Type
))->Fold(CurRec
);
1765 /// Parse the !find operation. Return null on error.
1767 /// Substr ::= !find(string, string [, start-int]) => int
1768 Init
*TGParser::ParseOperationFind(Record
*CurRec
, RecTy
*ItemType
) {
1769 TernOpInit::TernaryOp Code
= TernOpInit::FIND
;
1770 RecTy
*Type
= IntRecTy::get();
1772 Lex
.Lex(); // eat the operation
1774 if (!consume(tgtok::l_paren
)) {
1775 TokError("expected '(' after !find operator");
1779 Init
*LHS
= ParseValue(CurRec
);
1783 if (!consume(tgtok::comma
)) {
1784 TokError("expected ',' in !find operator");
1788 SMLoc MHSLoc
= Lex
.getLoc();
1789 Init
*MHS
= ParseValue(CurRec
);
1793 SMLoc RHSLoc
= Lex
.getLoc();
1795 if (consume(tgtok::comma
)) {
1796 RHSLoc
= Lex
.getLoc();
1797 RHS
= ParseValue(CurRec
);
1801 RHS
= IntInit::get(0);
1804 if (!consume(tgtok::r_paren
)) {
1805 TokError("expected ')' in !find operator");
1809 if (ItemType
&& !Type
->typeIsConvertibleTo(ItemType
)) {
1810 Error(RHSLoc
, Twine("expected value of type '") +
1811 ItemType
->getAsString() + "', got '" +
1812 Type
->getAsString() + "'");
1815 TypedInit
*LHSt
= dyn_cast
<TypedInit
>(LHS
);
1816 if (!LHSt
&& !isa
<UnsetInit
>(LHS
)) {
1817 TokError("could not determine type of the source string in !find");
1820 if (LHSt
&& !isa
<StringRecTy
>(LHSt
->getType())) {
1821 TokError(Twine("expected string, got type '") +
1822 LHSt
->getType()->getAsString() + "'");
1826 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
1827 if (!MHSt
&& !isa
<UnsetInit
>(MHS
)) {
1828 TokError("could not determine type of the target string in !find");
1831 if (MHSt
&& !isa
<StringRecTy
>(MHSt
->getType())) {
1832 Error(MHSLoc
, Twine("expected string, got type '") +
1833 MHSt
->getType()->getAsString() + "'");
1838 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
1839 if (!RHSt
&& !isa
<UnsetInit
>(RHS
)) {
1840 TokError("could not determine type of the start position in !find");
1843 if (RHSt
&& !isa
<IntRecTy
>(RHSt
->getType())) {
1844 TokError(Twine("expected int, got type '") +
1845 RHSt
->getType()->getAsString() + "'");
1850 return (TernOpInit::get(Code
, LHS
, MHS
, RHS
, Type
))->Fold(CurRec
);
1853 /// Parse the !foreach and !filter operations. Return null on error.
1855 /// ForEach ::= !foreach(ID, list-or-dag, expr) => list<expr type>
1856 /// Filter ::= !foreach(ID, list, predicate) ==> list<list type>
1857 Init
*TGParser::ParseOperationForEachFilter(Record
*CurRec
, RecTy
*ItemType
) {
1858 SMLoc OpLoc
= Lex
.getLoc();
1859 tgtok::TokKind Operation
= Lex
.getCode();
1860 Lex
.Lex(); // eat the operation
1861 if (Lex
.getCode() != tgtok::l_paren
) {
1862 TokError("expected '(' after !foreach/!filter");
1866 if (Lex
.Lex() != tgtok::Id
) { // eat the '('
1867 TokError("first argument of !foreach/!filter must be an identifier");
1871 Init
*LHS
= StringInit::get(Lex
.getCurStrVal());
1872 Lex
.Lex(); // eat the ID.
1874 if (CurRec
&& CurRec
->getValue(LHS
)) {
1875 TokError((Twine("iteration variable '") + LHS
->getAsString() +
1876 "' is already defined")
1881 if (!consume(tgtok::comma
)) {
1882 TokError("expected ',' in !foreach/!filter");
1886 Init
*MHS
= ParseValue(CurRec
);
1890 if (!consume(tgtok::comma
)) {
1891 TokError("expected ',' in !foreach/!filter");
1895 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
1897 TokError("could not get type of !foreach/!filter list or dag");
1901 RecTy
*InEltType
= nullptr;
1902 RecTy
*ExprEltType
= nullptr;
1905 if (ListRecTy
*InListTy
= dyn_cast
<ListRecTy
>(MHSt
->getType())) {
1906 InEltType
= InListTy
->getElementType();
1908 if (ListRecTy
*OutListTy
= dyn_cast
<ListRecTy
>(ItemType
)) {
1909 ExprEltType
= (Operation
== tgtok::XForEach
)
1910 ? OutListTy
->getElementType()
1914 "expected value of type '" +
1915 Twine(ItemType
->getAsString()) +
1916 "', but got list type");
1920 } else if (DagRecTy
*InDagTy
= dyn_cast
<DagRecTy
>(MHSt
->getType())) {
1921 if (Operation
== tgtok::XFilter
) {
1922 TokError("!filter must have a list argument");
1925 InEltType
= InDagTy
;
1926 if (ItemType
&& !isa
<DagRecTy
>(ItemType
)) {
1928 "expected value of type '" + Twine(ItemType
->getAsString()) +
1929 "', but got dag type");
1934 if (Operation
== tgtok::XForEach
)
1935 TokError("!foreach must have a list or dag argument");
1937 TokError("!filter must have a list argument");
1941 // We need to create a temporary record to provide a scope for the
1942 // iteration variable.
1943 std::unique_ptr
<Record
> ParseRecTmp
;
1944 Record
*ParseRec
= CurRec
;
1947 std::make_unique
<Record
>(".parse", ArrayRef
<SMLoc
>{}, Records
);
1948 ParseRec
= ParseRecTmp
.get();
1951 ParseRec
->addValue(RecordVal(LHS
, InEltType
, RecordVal::FK_Normal
));
1952 Init
*RHS
= ParseValue(ParseRec
, ExprEltType
);
1953 ParseRec
->removeValue(LHS
);
1957 if (!consume(tgtok::r_paren
)) {
1958 TokError("expected ')' in !foreach/!filter");
1962 RecTy
*OutType
= InEltType
;
1963 if (Operation
== tgtok::XForEach
&& !IsDAG
) {
1964 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
1966 TokError("could not get type of !foreach result expression");
1969 OutType
= RHSt
->getType()->getListTy();
1970 } else if (Operation
== tgtok::XFilter
) {
1971 OutType
= InEltType
->getListTy();
1974 return (TernOpInit::get((Operation
== tgtok::XForEach
) ? TernOpInit::FOREACH
1975 : TernOpInit::FILTER
,
1976 LHS
, MHS
, RHS
, OutType
))
1980 Init
*TGParser::ParseOperationCond(Record
*CurRec
, RecTy
*ItemType
) {
1981 Lex
.Lex(); // eat the operation 'cond'
1983 if (!consume(tgtok::l_paren
)) {
1984 TokError("expected '(' after !cond operator");
1988 // Parse through '[Case: Val,]+'
1989 SmallVector
<Init
*, 4> Case
;
1990 SmallVector
<Init
*, 4> Val
;
1992 if (consume(tgtok::r_paren
))
1995 Init
*V
= ParseValue(CurRec
);
2000 if (!consume(tgtok::colon
)) {
2001 TokError("expected ':' following a condition in !cond operator");
2005 V
= ParseValue(CurRec
, ItemType
);
2010 if (consume(tgtok::r_paren
))
2013 if (!consume(tgtok::comma
)) {
2014 TokError("expected ',' or ')' following a value in !cond operator");
2019 if (Case
.size() < 1) {
2020 TokError("there should be at least 1 'condition : value' in the !cond operator");
2025 RecTy
*Type
= nullptr;
2026 for (Init
*V
: Val
) {
2027 RecTy
*VTy
= nullptr;
2028 if (TypedInit
*Vt
= dyn_cast
<TypedInit
>(V
))
2029 VTy
= Vt
->getType();
2030 if (BitsInit
*Vbits
= dyn_cast
<BitsInit
>(V
))
2031 VTy
= BitsRecTy::get(Vbits
->getNumBits());
2032 if (isa
<BitInit
>(V
))
2033 VTy
= BitRecTy::get();
2035 if (Type
== nullptr) {
2036 if (!isa
<UnsetInit
>(V
))
2039 if (!isa
<UnsetInit
>(V
)) {
2040 RecTy
*RType
= resolveTypes(Type
, VTy
);
2042 TokError(Twine("inconsistent types '") + Type
->getAsString() +
2043 "' and '" + VTy
->getAsString() + "' for !cond");
2052 TokError("could not determine type for !cond from its arguments");
2055 return CondOpInit::get(Case
, Val
, Type
)->Fold(CurRec
);
2058 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
2060 /// SimpleValue ::= IDValue
2061 /// SimpleValue ::= INTVAL
2062 /// SimpleValue ::= STRVAL+
2063 /// SimpleValue ::= CODEFRAGMENT
2064 /// SimpleValue ::= '?'
2065 /// SimpleValue ::= '{' ValueList '}'
2066 /// SimpleValue ::= ID '<' ValueListNE '>'
2067 /// SimpleValue ::= '[' ValueList ']'
2068 /// SimpleValue ::= '(' IDValue DagArgList ')'
2069 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
2070 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
2071 /// SimpleValue ::= SUBTOK '(' Value ',' Value ')'
2072 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
2073 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
2074 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
2075 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
2076 /// SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')'
2077 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
2078 /// SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
2080 Init
*TGParser::ParseSimpleValue(Record
*CurRec
, RecTy
*ItemType
,
2083 switch (Lex
.getCode()) {
2084 default: TokError("Unknown or reserved token when parsing a value"); break;
2086 case tgtok::TrueVal
:
2087 R
= IntInit::get(1);
2090 case tgtok::FalseVal
:
2091 R
= IntInit::get(0);
2095 R
= IntInit::get(Lex
.getCurIntVal());
2098 case tgtok::BinaryIntVal
: {
2099 auto BinaryVal
= Lex
.getCurBinaryIntVal();
2100 SmallVector
<Init
*, 16> Bits(BinaryVal
.second
);
2101 for (unsigned i
= 0, e
= BinaryVal
.second
; i
!= e
; ++i
)
2102 Bits
[i
] = BitInit::get(BinaryVal
.first
& (1LL << i
));
2103 R
= BitsInit::get(Bits
);
2107 case tgtok::StrVal
: {
2108 std::string Val
= Lex
.getCurStrVal();
2111 // Handle multiple consecutive concatenated strings.
2112 while (Lex
.getCode() == tgtok::StrVal
) {
2113 Val
+= Lex
.getCurStrVal();
2117 R
= StringInit::get(Val
);
2120 case tgtok::CodeFragment
:
2121 R
= StringInit::get(Lex
.getCurStrVal(), StringInit::SF_Code
);
2124 case tgtok::question
:
2125 R
= UnsetInit::get();
2129 SMLoc NameLoc
= Lex
.getLoc();
2130 StringInit
*Name
= StringInit::get(Lex
.getCurStrVal());
2131 if (Lex
.Lex() != tgtok::less
) // consume the Id.
2132 return ParseIDValue(CurRec
, Name
, NameLoc
, Mode
); // Value ::= IDValue
2134 // Value ::= CLASSID '<' ValueListNE '>' (CLASSID has been consumed)
2135 // This is supposed to synthesize a new anonymous definition, deriving
2136 // from the class with the template arguments, but no body.
2137 Record
*Class
= Records
.getClass(Name
->getValue());
2139 Error(NameLoc
, "Expected a class name, got '" + Name
->getValue() + "'");
2143 SmallVector
<Init
*, 8> Args
;
2144 Lex
.Lex(); // consume the <
2145 if (ParseTemplateArgValueList(Args
, CurRec
, Class
))
2146 return nullptr; // Error parsing value list.
2148 if (CheckTemplateArgValues(Args
, NameLoc
, Class
))
2149 return nullptr; // Error checking template argument values.
2151 // Loop through the arguments that were not specified and make sure
2152 // they have a complete value.
2153 ArrayRef
<Init
*> TArgs
= Class
->getTemplateArgs();
2154 for (unsigned I
= Args
.size(), E
= TArgs
.size(); I
< E
; ++I
) {
2155 RecordVal
*Arg
= Class
->getValue(TArgs
[I
]);
2156 if (!Arg
->getValue()->isComplete())
2157 Error(NameLoc
, "Value not specified for template argument '" +
2158 TArgs
[I
]->getAsUnquotedString() + "' (#" + Twine(I
) +
2159 ") of parent class '" +
2160 Class
->getNameInitAsString() + "'");
2164 return VarDefInit::get(Class
, Args
)->Fold();
2166 case tgtok::l_brace
: { // Value ::= '{' ValueList '}'
2167 SMLoc BraceLoc
= Lex
.getLoc();
2168 Lex
.Lex(); // eat the '{'
2169 SmallVector
<Init
*, 16> Vals
;
2171 if (Lex
.getCode() != tgtok::r_brace
) {
2172 ParseValueList(Vals
, CurRec
);
2173 if (Vals
.empty()) return nullptr;
2175 if (!consume(tgtok::r_brace
)) {
2176 TokError("expected '}' at end of bit list value");
2180 SmallVector
<Init
*, 16> NewBits
;
2182 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
2183 // first. We'll first read everything in to a vector, then we can reverse
2184 // it to get the bits in the correct order for the BitsInit value.
2185 for (unsigned i
= 0, e
= Vals
.size(); i
!= e
; ++i
) {
2186 // FIXME: The following two loops would not be duplicated
2187 // if the API was a little more orthogonal.
2189 // bits<n> values are allowed to initialize n bits.
2190 if (BitsInit
*BI
= dyn_cast
<BitsInit
>(Vals
[i
])) {
2191 for (unsigned i
= 0, e
= BI
->getNumBits(); i
!= e
; ++i
)
2192 NewBits
.push_back(BI
->getBit((e
- i
) - 1));
2195 // bits<n> can also come from variable initializers.
2196 if (VarInit
*VI
= dyn_cast
<VarInit
>(Vals
[i
])) {
2197 if (BitsRecTy
*BitsRec
= dyn_cast
<BitsRecTy
>(VI
->getType())) {
2198 for (unsigned i
= 0, e
= BitsRec
->getNumBits(); i
!= e
; ++i
)
2199 NewBits
.push_back(VI
->getBit((e
- i
) - 1));
2202 // Fallthrough to try convert this to a bit.
2204 // All other values must be convertible to just a single bit.
2205 Init
*Bit
= Vals
[i
]->getCastTo(BitRecTy::get());
2207 Error(BraceLoc
, "Element #" + Twine(i
) + " (" + Vals
[i
]->getAsString() +
2208 ") is not convertable to a bit");
2211 NewBits
.push_back(Bit
);
2213 std::reverse(NewBits
.begin(), NewBits
.end());
2214 return BitsInit::get(NewBits
);
2216 case tgtok::l_square
: { // Value ::= '[' ValueList ']'
2217 Lex
.Lex(); // eat the '['
2218 SmallVector
<Init
*, 16> Vals
;
2220 RecTy
*DeducedEltTy
= nullptr;
2221 ListRecTy
*GivenListTy
= nullptr;
2224 ListRecTy
*ListType
= dyn_cast
<ListRecTy
>(ItemType
);
2226 TokError(Twine("Encountered a list when expecting a ") +
2227 ItemType
->getAsString());
2230 GivenListTy
= ListType
;
2233 if (Lex
.getCode() != tgtok::r_square
) {
2234 ParseValueList(Vals
, CurRec
,
2235 GivenListTy
? GivenListTy
->getElementType() : nullptr);
2236 if (Vals
.empty()) return nullptr;
2238 if (!consume(tgtok::r_square
)) {
2239 TokError("expected ']' at end of list value");
2243 RecTy
*GivenEltTy
= nullptr;
2244 if (consume(tgtok::less
)) {
2245 // Optional list element type
2246 GivenEltTy
= ParseType();
2248 // Couldn't parse element type
2252 if (!consume(tgtok::greater
)) {
2253 TokError("expected '>' at end of list element type");
2259 RecTy
*EltTy
= nullptr;
2260 for (Init
*V
: Vals
) {
2261 TypedInit
*TArg
= dyn_cast
<TypedInit
>(V
);
2264 EltTy
= resolveTypes(EltTy
, TArg
->getType());
2266 TokError("Incompatible types in list elements");
2270 EltTy
= TArg
->getType();
2277 // Verify consistency
2278 if (!EltTy
->typeIsConvertibleTo(GivenEltTy
)) {
2279 TokError("Incompatible types in list elements");
2288 TokError("No type for list");
2291 DeducedEltTy
= GivenListTy
->getElementType();
2293 // Make sure the deduced type is compatible with the given type
2295 if (!EltTy
->typeIsConvertibleTo(GivenListTy
->getElementType())) {
2296 TokError(Twine("Element type mismatch for list: element type '") +
2297 EltTy
->getAsString() + "' not convertible to '" +
2298 GivenListTy
->getElementType()->getAsString());
2302 DeducedEltTy
= EltTy
;
2305 return ListInit::get(Vals
, DeducedEltTy
);
2307 case tgtok::l_paren
: { // Value ::= '(' IDValue DagArgList ')'
2308 Lex
.Lex(); // eat the '('
2309 if (Lex
.getCode() != tgtok::Id
&& Lex
.getCode() != tgtok::XCast
&&
2310 Lex
.getCode() != tgtok::question
&& Lex
.getCode() != tgtok::XGetDagOp
) {
2311 TokError("expected identifier in dag init");
2315 Init
*Operator
= ParseValue(CurRec
);
2316 if (!Operator
) return nullptr;
2318 // If the operator name is present, parse it.
2319 StringInit
*OperatorName
= nullptr;
2320 if (consume(tgtok::colon
)) {
2321 if (Lex
.getCode() != tgtok::VarName
) { // eat the ':'
2322 TokError("expected variable name in dag operator");
2325 OperatorName
= StringInit::get(Lex
.getCurStrVal());
2326 Lex
.Lex(); // eat the VarName.
2329 SmallVector
<std::pair
<llvm::Init
*, StringInit
*>, 8> DagArgs
;
2330 if (Lex
.getCode() != tgtok::r_paren
) {
2331 ParseDagArgList(DagArgs
, CurRec
);
2332 if (DagArgs
.empty()) return nullptr;
2335 if (!consume(tgtok::r_paren
)) {
2336 TokError("expected ')' in dag init");
2340 return DagInit::get(Operator
, OperatorName
, DagArgs
);
2348 case tgtok::XGetDagOp
: // Value ::= !unop '(' Value ')'
2350 case tgtok::XConcat
:
2368 case tgtok::XListConcat
:
2369 case tgtok::XListSplat
:
2370 case tgtok::XStrConcat
:
2371 case tgtok::XInterleave
:
2372 case tgtok::XSetDagOp
: // Value ::= !binop '(' Value ',' Value ')'
2376 case tgtok::XForEach
:
2377 case tgtok::XFilter
:
2379 case tgtok::XSubstr
:
2380 case tgtok::XFind
: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
2381 return ParseOperation(CurRec
, ItemType
);
2388 /// ParseValue - Parse a TableGen value. This returns null on error.
2390 /// Value ::= SimpleValue ValueSuffix*
2391 /// ValueSuffix ::= '{' BitList '}'
2392 /// ValueSuffix ::= '[' BitList ']'
2393 /// ValueSuffix ::= '.' ID
2395 Init
*TGParser::ParseValue(Record
*CurRec
, RecTy
*ItemType
, IDParseMode Mode
) {
2396 Init
*Result
= ParseSimpleValue(CurRec
, ItemType
, Mode
);
2397 if (!Result
) return nullptr;
2399 // Parse the suffixes now if present.
2401 switch (Lex
.getCode()) {
2402 default: return Result
;
2403 case tgtok::l_brace
: {
2404 if (Mode
== ParseNameMode
)
2405 // This is the beginning of the object body.
2408 SMLoc CurlyLoc
= Lex
.getLoc();
2409 Lex
.Lex(); // eat the '{'
2410 SmallVector
<unsigned, 16> Ranges
;
2411 ParseRangeList(Ranges
);
2412 if (Ranges
.empty()) return nullptr;
2414 // Reverse the bitlist.
2415 std::reverse(Ranges
.begin(), Ranges
.end());
2416 Result
= Result
->convertInitializerBitRange(Ranges
);
2418 Error(CurlyLoc
, "Invalid bit range for value");
2423 if (!consume(tgtok::r_brace
)) {
2424 TokError("expected '}' at end of bit range list");
2429 case tgtok::l_square
: {
2430 SMLoc SquareLoc
= Lex
.getLoc();
2431 Lex
.Lex(); // eat the '['
2432 SmallVector
<unsigned, 16> Ranges
;
2433 ParseRangeList(Ranges
);
2434 if (Ranges
.empty()) return nullptr;
2436 Result
= Result
->convertInitListSlice(Ranges
);
2438 Error(SquareLoc
, "Invalid range for list slice");
2443 if (!consume(tgtok::r_square
)) {
2444 TokError("expected ']' at end of list slice");
2450 if (Lex
.Lex() != tgtok::Id
) { // eat the .
2451 TokError("expected field identifier after '.'");
2454 StringInit
*FieldName
= StringInit::get(Lex
.getCurStrVal());
2455 if (!Result
->getFieldType(FieldName
)) {
2456 TokError("Cannot access field '" + Lex
.getCurStrVal() + "' of value '" +
2457 Result
->getAsString() + "'");
2460 Result
= FieldInit::get(Result
, FieldName
)->Fold(CurRec
);
2461 Lex
.Lex(); // eat field name
2466 SMLoc PasteLoc
= Lex
.getLoc();
2467 TypedInit
*LHS
= dyn_cast
<TypedInit
>(Result
);
2469 Error(PasteLoc
, "LHS of paste is not typed!");
2473 // Check if it's a 'listA # listB'
2474 if (isa
<ListRecTy
>(LHS
->getType())) {
2475 Lex
.Lex(); // Eat the '#'.
2477 assert(Mode
== ParseValueMode
&& "encountered paste of lists in name");
2479 switch (Lex
.getCode()) {
2482 case tgtok::l_brace
:
2483 Result
= LHS
; // trailing paste, ignore.
2486 Init
*RHSResult
= ParseValue(CurRec
, ItemType
, ParseValueMode
);
2489 Result
= BinOpInit::getListConcat(LHS
, RHSResult
);
2495 // Create a !strconcat() operation, first casting each operand to
2496 // a string if necessary.
2497 if (LHS
->getType() != StringRecTy::get()) {
2498 auto CastLHS
= dyn_cast
<TypedInit
>(
2499 UnOpInit::get(UnOpInit::CAST
, LHS
, StringRecTy::get())
2503 Twine("can't cast '") + LHS
->getAsString() + "' to string");
2509 TypedInit
*RHS
= nullptr;
2511 Lex
.Lex(); // Eat the '#'.
2512 switch (Lex
.getCode()) {
2515 case tgtok::l_brace
:
2516 // These are all of the tokens that can begin an object body.
2517 // Some of these can also begin values but we disallow those cases
2518 // because they are unlikely to be useful.
2520 // Trailing paste, concat with an empty string.
2521 RHS
= StringInit::get("");
2525 Init
*RHSResult
= ParseValue(CurRec
, nullptr, ParseNameMode
);
2528 RHS
= dyn_cast
<TypedInit
>(RHSResult
);
2530 Error(PasteLoc
, "RHS of paste is not typed!");
2534 if (RHS
->getType() != StringRecTy::get()) {
2535 auto CastRHS
= dyn_cast
<TypedInit
>(
2536 UnOpInit::get(UnOpInit::CAST
, RHS
, StringRecTy::get())
2540 Twine("can't cast '") + RHS
->getAsString() + "' to string");
2549 Result
= BinOpInit::getStrConcat(LHS
, RHS
);
2555 /// ParseDagArgList - Parse the argument list for a dag literal expression.
2557 /// DagArg ::= Value (':' VARNAME)?
2558 /// DagArg ::= VARNAME
2559 /// DagArgList ::= DagArg
2560 /// DagArgList ::= DagArgList ',' DagArg
2561 void TGParser::ParseDagArgList(
2562 SmallVectorImpl
<std::pair
<llvm::Init
*, StringInit
*>> &Result
,
2566 // DagArg ::= VARNAME
2567 if (Lex
.getCode() == tgtok::VarName
) {
2568 // A missing value is treated like '?'.
2569 StringInit
*VarName
= StringInit::get(Lex
.getCurStrVal());
2570 Result
.emplace_back(UnsetInit::get(), VarName
);
2573 // DagArg ::= Value (':' VARNAME)?
2574 Init
*Val
= ParseValue(CurRec
);
2580 // If the variable name is present, add it.
2581 StringInit
*VarName
= nullptr;
2582 if (Lex
.getCode() == tgtok::colon
) {
2583 if (Lex
.Lex() != tgtok::VarName
) { // eat the ':'
2584 TokError("expected variable name in dag literal");
2588 VarName
= StringInit::get(Lex
.getCurStrVal());
2589 Lex
.Lex(); // eat the VarName.
2592 Result
.push_back(std::make_pair(Val
, VarName
));
2594 if (!consume(tgtok::comma
))
2599 /// ParseValueList - Parse a comma separated list of values, returning them
2600 /// in a vector. Note that this always expects to be able to parse at least one
2601 /// value. It returns an empty list if this is not possible.
2603 /// ValueList ::= Value (',' Value)
2605 void TGParser::ParseValueList(SmallVectorImpl
<Init
*> &Result
, Record
*CurRec
,
2608 Result
.push_back(ParseValue(CurRec
, ItemType
));
2609 if (!Result
.back()) {
2614 while (consume(tgtok::comma
)) {
2615 // ignore trailing comma for lists
2616 if (Lex
.getCode() == tgtok::r_square
)
2618 Result
.push_back(ParseValue(CurRec
, ItemType
));
2619 if (!Result
.back()) {
2626 // ParseTemplateArgValueList - Parse a template argument list with the syntax
2627 // shown, filling in the Result vector. The open angle has been consumed.
2628 // An empty argument list is allowed. Return false if okay, true if an
2629 // error was detected.
2631 // TemplateArgList ::= '<' [Value {',' Value}*] '>'
2632 bool TGParser::ParseTemplateArgValueList(SmallVectorImpl
<Init
*> &Result
,
2633 Record
*CurRec
, Record
*ArgsRec
) {
2635 assert(Result
.empty() && "Result vector is not empty");
2636 ArrayRef
<Init
*> TArgs
= ArgsRec
->getTemplateArgs();
2637 unsigned ArgIndex
= 0;
2640 if (consume(tgtok::greater
)) // empty value list
2644 if (ArgIndex
>= TArgs
.size()) {
2645 TokError("Too many template arguments: " + utostr(ArgIndex
+ 1));
2648 const RecordVal
*Arg
= ArgsRec
->getValue(TArgs
[ArgIndex
]);
2649 assert(Arg
&& "Template argument record not found");
2651 ItemType
= Arg
->getType();
2652 Init
*Value
= ParseValue(CurRec
, ItemType
);
2655 Result
.push_back(Value
);
2657 if (consume(tgtok::greater
)) // end of argument list?
2659 if (!consume(tgtok::comma
))
2660 return TokError("Expected comma before next argument");
2665 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
2666 /// empty string on error. This can happen in a number of different contexts,
2667 /// including within a def or in the template args for a class (in which case
2668 /// CurRec will be non-null) and within the template args for a multiclass (in
2669 /// which case CurRec will be null, but CurMultiClass will be set). This can
2670 /// also happen within a def that is within a multiclass, which will set both
2671 /// CurRec and CurMultiClass.
2673 /// Declaration ::= FIELD? Type ID ('=' Value)?
2675 Init
*TGParser::ParseDeclaration(Record
*CurRec
,
2676 bool ParsingTemplateArgs
) {
2677 // Read the field prefix if present.
2678 bool HasField
= consume(tgtok::Field
);
2680 RecTy
*Type
= ParseType();
2681 if (!Type
) return nullptr;
2683 if (Lex
.getCode() != tgtok::Id
) {
2684 TokError("Expected identifier in declaration");
2688 std::string Str
= Lex
.getCurStrVal();
2689 if (Str
== "NAME") {
2690 TokError("'" + Str
+ "' is a reserved variable name");
2694 SMLoc IdLoc
= Lex
.getLoc();
2695 Init
*DeclName
= StringInit::get(Str
);
2699 if (!ParsingTemplateArgs
) { // def, possibly in a multiclass
2700 BadField
= AddValue(CurRec
, IdLoc
,
2701 RecordVal(DeclName
, IdLoc
, Type
,
2702 HasField
? RecordVal::FK_NonconcreteOK
2703 : RecordVal::FK_Normal
));
2705 } else if (CurRec
) { // class template argument
2706 DeclName
= QualifyName(*CurRec
, CurMultiClass
, DeclName
, ":");
2707 BadField
= AddValue(CurRec
, IdLoc
, RecordVal(DeclName
, IdLoc
, Type
,
2708 RecordVal::FK_TemplateArg
));
2710 } else { // multiclass template argument
2711 assert(CurMultiClass
&& "invalid context for template argument");
2712 DeclName
= QualifyName(CurMultiClass
->Rec
, CurMultiClass
, DeclName
, "::");
2713 BadField
= AddValue(CurRec
, IdLoc
, RecordVal(DeclName
, IdLoc
, Type
,
2714 RecordVal::FK_TemplateArg
));
2719 // If a value is present, parse it and set new field's value.
2720 if (consume(tgtok::equal
)) {
2721 SMLoc ValLoc
= Lex
.getLoc();
2722 Init
*Val
= ParseValue(CurRec
, Type
);
2724 SetValue(CurRec
, ValLoc
, DeclName
, None
, Val
))
2725 // Return the name, even if an error is thrown. This is so that we can
2726 // continue to make some progress, even without the value having been
2734 /// ParseForeachDeclaration - Read a foreach declaration, returning
2735 /// the name of the declared object or a NULL Init on error. Return
2736 /// the name of the parsed initializer list through ForeachListName.
2738 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
2739 /// ForeachDeclaration ::= ID '=' RangePiece
2740 /// ForeachDeclaration ::= ID '=' Value
2742 VarInit
*TGParser::ParseForeachDeclaration(Init
*&ForeachListValue
) {
2743 if (Lex
.getCode() != tgtok::Id
) {
2744 TokError("Expected identifier in foreach declaration");
2748 Init
*DeclName
= StringInit::get(Lex
.getCurStrVal());
2751 // If a value is present, parse it.
2752 if (!consume(tgtok::equal
)) {
2753 TokError("Expected '=' in foreach declaration");
2757 RecTy
*IterType
= nullptr;
2758 SmallVector
<unsigned, 16> Ranges
;
2760 switch (Lex
.getCode()) {
2761 case tgtok::l_brace
: { // '{' RangeList '}'
2762 Lex
.Lex(); // eat the '{'
2763 ParseRangeList(Ranges
);
2764 if (!consume(tgtok::r_brace
)) {
2765 TokError("expected '}' at end of bit range list");
2772 SMLoc ValueLoc
= Lex
.getLoc();
2773 Init
*I
= ParseValue(nullptr);
2777 TypedInit
*TI
= dyn_cast
<TypedInit
>(I
);
2778 if (TI
&& isa
<ListRecTy
>(TI
->getType())) {
2779 ForeachListValue
= I
;
2780 IterType
= cast
<ListRecTy
>(TI
->getType())->getElementType();
2785 if (ParseRangePiece(Ranges
, TI
))
2790 Error(ValueLoc
, "expected a list, got '" + I
->getAsString() + "'");
2791 if (CurMultiClass
) {
2792 PrintNote({}, "references to multiclass template arguments cannot be "
2793 "resolved at this time");
2800 if (!Ranges
.empty()) {
2801 assert(!IterType
&& "Type already initialized?");
2802 IterType
= IntRecTy::get();
2803 std::vector
<Init
*> Values
;
2804 for (unsigned R
: Ranges
)
2805 Values
.push_back(IntInit::get(R
));
2806 ForeachListValue
= ListInit::get(Values
, IterType
);
2812 return VarInit::get(DeclName
, IterType
);
2815 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
2816 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
2817 /// template args for a class. If null, these are the template args for a
2820 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
2822 bool TGParser::ParseTemplateArgList(Record
*CurRec
) {
2823 assert(Lex
.getCode() == tgtok::less
&& "Not a template arg list!");
2824 Lex
.Lex(); // eat the '<'
2826 Record
*TheRecToAddTo
= CurRec
? CurRec
: &CurMultiClass
->Rec
;
2828 // Read the first declaration.
2829 Init
*TemplArg
= ParseDeclaration(CurRec
, true/*templateargs*/);
2833 TheRecToAddTo
->addTemplateArg(TemplArg
);
2835 while (consume(tgtok::comma
)) {
2836 // Read the following declarations.
2837 SMLoc Loc
= Lex
.getLoc();
2838 TemplArg
= ParseDeclaration(CurRec
, true/*templateargs*/);
2842 if (TheRecToAddTo
->isTemplateArg(TemplArg
))
2843 return Error(Loc
, "template argument with the same name has already been "
2846 TheRecToAddTo
->addTemplateArg(TemplArg
);
2849 if (!consume(tgtok::greater
))
2850 return TokError("expected '>' at end of template argument list");
2854 /// ParseBodyItem - Parse a single item within the body of a def or class.
2856 /// BodyItem ::= Declaration ';'
2857 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
2858 /// BodyItem ::= Defvar
2859 /// BodyItem ::= Assert
2861 bool TGParser::ParseBodyItem(Record
*CurRec
) {
2862 if (Lex
.getCode() == tgtok::Assert
)
2863 return ParseAssert(nullptr, CurRec
);
2865 if (Lex
.getCode() == tgtok::Defvar
)
2866 return ParseDefvar();
2868 if (Lex
.getCode() != tgtok::Let
) {
2869 if (!ParseDeclaration(CurRec
, false))
2872 if (!consume(tgtok::semi
))
2873 return TokError("expected ';' after declaration");
2877 // LET ID OptionalRangeList '=' Value ';'
2878 if (Lex
.Lex() != tgtok::Id
)
2879 return TokError("expected field identifier after let");
2881 SMLoc IdLoc
= Lex
.getLoc();
2882 StringInit
*FieldName
= StringInit::get(Lex
.getCurStrVal());
2883 Lex
.Lex(); // eat the field name.
2885 SmallVector
<unsigned, 16> BitList
;
2886 if (ParseOptionalBitList(BitList
))
2888 std::reverse(BitList
.begin(), BitList
.end());
2890 if (!consume(tgtok::equal
))
2891 return TokError("expected '=' in let expression");
2893 RecordVal
*Field
= CurRec
->getValue(FieldName
);
2895 return TokError("Value '" + FieldName
->getValue() + "' unknown!");
2897 RecTy
*Type
= Field
->getType();
2898 if (!BitList
.empty() && isa
<BitsRecTy
>(Type
)) {
2899 // When assigning to a subset of a 'bits' object, expect the RHS to have
2900 // the type of that subset instead of the type of the whole object.
2901 Type
= BitsRecTy::get(BitList
.size());
2904 Init
*Val
= ParseValue(CurRec
, Type
);
2905 if (!Val
) return true;
2907 if (!consume(tgtok::semi
))
2908 return TokError("expected ';' after let expression");
2910 return SetValue(CurRec
, IdLoc
, FieldName
, BitList
, Val
);
2913 /// ParseBody - Read the body of a class or def. Return true on error, false on
2917 /// Body ::= '{' BodyList '}'
2918 /// BodyList BodyItem*
2920 bool TGParser::ParseBody(Record
*CurRec
) {
2921 // If this is a null definition, just eat the semi and return.
2922 if (consume(tgtok::semi
))
2925 if (!consume(tgtok::l_brace
))
2926 return TokError("Expected '{' to start body or ';' for declaration only");
2928 // An object body introduces a new scope for local variables.
2929 TGLocalVarScope
*BodyScope
= PushLocalScope();
2931 while (Lex
.getCode() != tgtok::r_brace
)
2932 if (ParseBodyItem(CurRec
))
2935 PopLocalScope(BodyScope
);
2940 // If we have a semicolon, print a gentle error.
2941 SMLoc SemiLoc
= Lex
.getLoc();
2942 if (consume(tgtok::semi
)) {
2943 PrintError(SemiLoc
, "A class or def body should not end with a semicolon");
2944 PrintNote("Semicolon ignored; remove to eliminate this error");
2950 /// Apply the current let bindings to \a CurRec.
2951 /// \returns true on error, false otherwise.
2952 bool TGParser::ApplyLetStack(Record
*CurRec
) {
2953 for (SmallVectorImpl
<LetRecord
> &LetInfo
: LetStack
)
2954 for (LetRecord
&LR
: LetInfo
)
2955 if (SetValue(CurRec
, LR
.Loc
, LR
.Name
, LR
.Bits
, LR
.Value
))
2960 /// Apply the current let bindings to the RecordsEntry.
2961 bool TGParser::ApplyLetStack(RecordsEntry
&Entry
) {
2963 return ApplyLetStack(Entry
.Rec
.get());
2965 // Let bindings are not applied to assertions.
2966 if (Entry
.Assertion
)
2969 for (auto &E
: Entry
.Loop
->Entries
) {
2970 if (ApplyLetStack(E
))
2977 /// ParseObjectBody - Parse the body of a def or class. This consists of an
2978 /// optional ClassList followed by a Body. CurRec is the current def or class
2979 /// that is being parsed.
2981 /// ObjectBody ::= BaseClassList Body
2982 /// BaseClassList ::= /*empty*/
2983 /// BaseClassList ::= ':' BaseClassListNE
2984 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
2986 bool TGParser::ParseObjectBody(Record
*CurRec
) {
2987 // If there is a baseclass list, read it.
2988 if (consume(tgtok::colon
)) {
2990 // Read all of the subclasses.
2991 SubClassReference SubClass
= ParseSubClassReference(CurRec
, false);
2994 if (!SubClass
.Rec
) return true;
2997 if (AddSubClass(CurRec
, SubClass
))
3000 if (!consume(tgtok::comma
))
3002 SubClass
= ParseSubClassReference(CurRec
, false);
3006 if (ApplyLetStack(CurRec
))
3009 return ParseBody(CurRec
);
3012 /// ParseDef - Parse and return a top level or multiclass record definition.
3013 /// Return false if okay, true if error.
3015 /// DefInst ::= DEF ObjectName ObjectBody
3017 bool TGParser::ParseDef(MultiClass
*CurMultiClass
) {
3018 SMLoc DefLoc
= Lex
.getLoc();
3019 assert(Lex
.getCode() == tgtok::Def
&& "Unknown tok");
3020 Lex
.Lex(); // Eat the 'def' token.
3022 // Parse ObjectName and make a record for it.
3023 std::unique_ptr
<Record
> CurRec
;
3024 Init
*Name
= ParseObjectName(CurMultiClass
);
3028 if (isa
<UnsetInit
>(Name
))
3029 CurRec
= std::make_unique
<Record
>(Records
.getNewAnonymousName(), DefLoc
, Records
,
3030 /*Anonymous=*/true);
3032 CurRec
= std::make_unique
<Record
>(Name
, DefLoc
, Records
);
3034 if (ParseObjectBody(CurRec
.get()))
3037 return addEntry(std::move(CurRec
));
3040 /// ParseDefset - Parse a defset statement.
3042 /// Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
3044 bool TGParser::ParseDefset() {
3045 assert(Lex
.getCode() == tgtok::Defset
);
3046 Lex
.Lex(); // Eat the 'defset' token
3048 DefsetRecord Defset
;
3049 Defset
.Loc
= Lex
.getLoc();
3050 RecTy
*Type
= ParseType();
3053 if (!isa
<ListRecTy
>(Type
))
3054 return Error(Defset
.Loc
, "expected list type");
3055 Defset
.EltTy
= cast
<ListRecTy
>(Type
)->getElementType();
3057 if (Lex
.getCode() != tgtok::Id
)
3058 return TokError("expected identifier");
3059 StringInit
*DeclName
= StringInit::get(Lex
.getCurStrVal());
3060 if (Records
.getGlobal(DeclName
->getValue()))
3061 return TokError("def or global variable of this name already exists");
3063 if (Lex
.Lex() != tgtok::equal
) // Eat the identifier
3064 return TokError("expected '='");
3065 if (Lex
.Lex() != tgtok::l_brace
) // Eat the '='
3066 return TokError("expected '{'");
3067 SMLoc BraceLoc
= Lex
.getLoc();
3068 Lex
.Lex(); // Eat the '{'
3070 Defsets
.push_back(&Defset
);
3071 bool Err
= ParseObjectList(nullptr);
3076 if (!consume(tgtok::r_brace
)) {
3077 TokError("expected '}' at end of defset");
3078 return Error(BraceLoc
, "to match this '{'");
3081 Records
.addExtraGlobal(DeclName
->getValue(),
3082 ListInit::get(Defset
.Elements
, Defset
.EltTy
));
3086 /// ParseDefvar - Parse a defvar statement.
3088 /// Defvar ::= DEFVAR Id '=' Value ';'
3090 bool TGParser::ParseDefvar() {
3091 assert(Lex
.getCode() == tgtok::Defvar
);
3092 Lex
.Lex(); // Eat the 'defvar' token
3094 if (Lex
.getCode() != tgtok::Id
)
3095 return TokError("expected identifier");
3096 StringInit
*DeclName
= StringInit::get(Lex
.getCurStrVal());
3097 if (CurLocalScope
) {
3098 if (CurLocalScope
->varAlreadyDefined(DeclName
->getValue()))
3099 return TokError("local variable of this name already exists");
3101 if (Records
.getGlobal(DeclName
->getValue()))
3102 return TokError("def or global variable of this name already exists");
3106 if (!consume(tgtok::equal
))
3107 return TokError("expected '='");
3109 Init
*Value
= ParseValue(nullptr);
3113 if (!consume(tgtok::semi
))
3114 return TokError("expected ';'");
3117 CurLocalScope
->addVar(DeclName
->getValue(), Value
);
3119 Records
.addExtraGlobal(DeclName
->getValue(), Value
);
3124 /// ParseForeach - Parse a for statement. Return the record corresponding
3125 /// to it. This returns true on error.
3127 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
3128 /// Foreach ::= FOREACH Declaration IN Object
3130 bool TGParser::ParseForeach(MultiClass
*CurMultiClass
) {
3131 SMLoc Loc
= Lex
.getLoc();
3132 assert(Lex
.getCode() == tgtok::Foreach
&& "Unknown tok");
3133 Lex
.Lex(); // Eat the 'for' token.
3135 // Make a temporary object to record items associated with the for
3137 Init
*ListValue
= nullptr;
3138 VarInit
*IterName
= ParseForeachDeclaration(ListValue
);
3140 return TokError("expected declaration in for");
3142 if (!consume(tgtok::In
))
3143 return TokError("Unknown tok");
3145 // Create a loop object and remember it.
3146 Loops
.push_back(std::make_unique
<ForeachLoop
>(Loc
, IterName
, ListValue
));
3148 // A foreach loop introduces a new scope for local variables.
3149 TGLocalVarScope
*ForeachScope
= PushLocalScope();
3151 if (Lex
.getCode() != tgtok::l_brace
) {
3152 // FOREACH Declaration IN Object
3153 if (ParseObject(CurMultiClass
))
3156 SMLoc BraceLoc
= Lex
.getLoc();
3157 // Otherwise, this is a group foreach.
3158 Lex
.Lex(); // eat the '{'.
3160 // Parse the object list.
3161 if (ParseObjectList(CurMultiClass
))
3164 if (!consume(tgtok::r_brace
)) {
3165 TokError("expected '}' at end of foreach command");
3166 return Error(BraceLoc
, "to match this '{'");
3170 PopLocalScope(ForeachScope
);
3172 // Resolve the loop or store it for later resolution.
3173 std::unique_ptr
<ForeachLoop
> Loop
= std::move(Loops
.back());
3176 return addEntry(std::move(Loop
));
3179 /// ParseIf - Parse an if statement.
3181 /// If ::= IF Value THEN IfBody
3182 /// If ::= IF Value THEN IfBody ELSE IfBody
3184 bool TGParser::ParseIf(MultiClass
*CurMultiClass
) {
3185 SMLoc Loc
= Lex
.getLoc();
3186 assert(Lex
.getCode() == tgtok::If
&& "Unknown tok");
3187 Lex
.Lex(); // Eat the 'if' token.
3189 // Make a temporary object to record items associated with the for
3191 Init
*Condition
= ParseValue(nullptr);
3195 if (!consume(tgtok::Then
))
3196 return TokError("Unknown tok");
3198 // We have to be able to save if statements to execute later, and they have
3199 // to live on the same stack as foreach loops. The simplest implementation
3200 // technique is to convert each 'then' or 'else' clause *into* a foreach
3201 // loop, over a list of length 0 or 1 depending on the condition, and with no
3202 // iteration variable being assigned.
3204 ListInit
*EmptyList
= ListInit::get({}, BitRecTy::get());
3205 ListInit
*SingletonList
= ListInit::get({BitInit::get(1)}, BitRecTy::get());
3206 RecTy
*BitListTy
= ListRecTy::get(BitRecTy::get());
3208 // The foreach containing the then-clause selects SingletonList if
3209 // the condition is true.
3210 Init
*ThenClauseList
=
3211 TernOpInit::get(TernOpInit::IF
, Condition
, SingletonList
, EmptyList
,
3214 Loops
.push_back(std::make_unique
<ForeachLoop
>(Loc
, nullptr, ThenClauseList
));
3216 if (ParseIfBody(CurMultiClass
, "then"))
3219 std::unique_ptr
<ForeachLoop
> Loop
= std::move(Loops
.back());
3222 if (addEntry(std::move(Loop
)))
3225 // Now look for an optional else clause. The if-else syntax has the usual
3226 // dangling-else ambiguity, and by greedily matching an else here if we can,
3227 // we implement the usual resolution of pairing with the innermost unmatched
3229 if (consume(tgtok::ElseKW
)) {
3230 // The foreach containing the else-clause uses the same pair of lists as
3231 // above, but this time, selects SingletonList if the condition is *false*.
3232 Init
*ElseClauseList
=
3233 TernOpInit::get(TernOpInit::IF
, Condition
, EmptyList
, SingletonList
,
3237 std::make_unique
<ForeachLoop
>(Loc
, nullptr, ElseClauseList
));
3239 if (ParseIfBody(CurMultiClass
, "else"))
3242 Loop
= std::move(Loops
.back());
3245 if (addEntry(std::move(Loop
)))
3252 /// ParseIfBody - Parse the then-clause or else-clause of an if statement.
3254 /// IfBody ::= Object
3255 /// IfBody ::= '{' ObjectList '}'
3257 bool TGParser::ParseIfBody(MultiClass
*CurMultiClass
, StringRef Kind
) {
3258 TGLocalVarScope
*BodyScope
= PushLocalScope();
3260 if (Lex
.getCode() != tgtok::l_brace
) {
3262 if (ParseObject(CurMultiClass
))
3265 SMLoc BraceLoc
= Lex
.getLoc();
3267 Lex
.Lex(); // eat the '{'.
3269 // Parse the object list.
3270 if (ParseObjectList(CurMultiClass
))
3273 if (!consume(tgtok::r_brace
)) {
3274 TokError("expected '}' at end of '" + Kind
+ "' clause");
3275 return Error(BraceLoc
, "to match this '{'");
3279 PopLocalScope(BodyScope
);
3283 /// ParseAssert - Parse an assert statement.
3285 /// Assert ::= ASSERT condition , message ;
3286 bool TGParser::ParseAssert(MultiClass
*CurMultiClass
, Record
*CurRec
) {
3287 assert(Lex
.getCode() == tgtok::Assert
&& "Unknown tok");
3288 Lex
.Lex(); // Eat the 'assert' token.
3290 SMLoc ConditionLoc
= Lex
.getLoc();
3291 Init
*Condition
= ParseValue(CurRec
);
3295 if (!consume(tgtok::comma
)) {
3296 TokError("expected ',' in assert statement");
3300 Init
*Message
= ParseValue(CurRec
);
3304 if (!consume(tgtok::semi
))
3305 return TokError("expected ';'");
3308 CurRec
->addAssertion(ConditionLoc
, Condition
, Message
);
3310 addEntry(std::make_unique
<Record::AssertionInfo
>(ConditionLoc
, Condition
,
3315 /// ParseClass - Parse a tblgen class definition.
3317 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
3319 bool TGParser::ParseClass() {
3320 assert(Lex
.getCode() == tgtok::Class
&& "Unexpected token!");
3323 if (Lex
.getCode() != tgtok::Id
)
3324 return TokError("expected class name after 'class' keyword");
3326 Record
*CurRec
= Records
.getClass(Lex
.getCurStrVal());
3328 // If the body was previously defined, this is an error.
3329 if (!CurRec
->getValues().empty() ||
3330 !CurRec
->getSuperClasses().empty() ||
3331 !CurRec
->getTemplateArgs().empty())
3332 return TokError("Class '" + CurRec
->getNameInitAsString() +
3333 "' already defined");
3335 // If this is the first reference to this class, create and add it.
3337 std::make_unique
<Record
>(Lex
.getCurStrVal(), Lex
.getLoc(), Records
,
3339 CurRec
= NewRec
.get();
3340 Records
.addClass(std::move(NewRec
));
3342 Lex
.Lex(); // eat the name.
3344 // If there are template args, parse them.
3345 if (Lex
.getCode() == tgtok::less
)
3346 if (ParseTemplateArgList(CurRec
))
3349 return ParseObjectBody(CurRec
);
3352 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
3355 /// LetList ::= LetItem (',' LetItem)*
3356 /// LetItem ::= ID OptionalRangeList '=' Value
3358 void TGParser::ParseLetList(SmallVectorImpl
<LetRecord
> &Result
) {
3360 if (Lex
.getCode() != tgtok::Id
) {
3361 TokError("expected identifier in let definition");
3366 StringInit
*Name
= StringInit::get(Lex
.getCurStrVal());
3367 SMLoc NameLoc
= Lex
.getLoc();
3368 Lex
.Lex(); // Eat the identifier.
3370 // Check for an optional RangeList.
3371 SmallVector
<unsigned, 16> Bits
;
3372 if (ParseOptionalRangeList(Bits
)) {
3376 std::reverse(Bits
.begin(), Bits
.end());
3378 if (!consume(tgtok::equal
)) {
3379 TokError("expected '=' in let expression");
3384 Init
*Val
= ParseValue(nullptr);
3390 // Now that we have everything, add the record.
3391 Result
.emplace_back(Name
, Bits
, Val
, NameLoc
);
3392 } while (consume(tgtok::comma
));
3395 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
3396 /// different related productions. This works inside multiclasses too.
3398 /// Object ::= LET LetList IN '{' ObjectList '}'
3399 /// Object ::= LET LetList IN Object
3401 bool TGParser::ParseTopLevelLet(MultiClass
*CurMultiClass
) {
3402 assert(Lex
.getCode() == tgtok::Let
&& "Unexpected token");
3405 // Add this entry to the let stack.
3406 SmallVector
<LetRecord
, 8> LetInfo
;
3407 ParseLetList(LetInfo
);
3408 if (LetInfo
.empty()) return true;
3409 LetStack
.push_back(std::move(LetInfo
));
3411 if (!consume(tgtok::In
))
3412 return TokError("expected 'in' at end of top-level 'let'");
3414 TGLocalVarScope
*LetScope
= PushLocalScope();
3416 // If this is a scalar let, just handle it now
3417 if (Lex
.getCode() != tgtok::l_brace
) {
3418 // LET LetList IN Object
3419 if (ParseObject(CurMultiClass
))
3421 } else { // Object ::= LETCommand '{' ObjectList '}'
3422 SMLoc BraceLoc
= Lex
.getLoc();
3423 // Otherwise, this is a group let.
3424 Lex
.Lex(); // eat the '{'.
3426 // Parse the object list.
3427 if (ParseObjectList(CurMultiClass
))
3430 if (!consume(tgtok::r_brace
)) {
3431 TokError("expected '}' at end of top level let command");
3432 return Error(BraceLoc
, "to match this '{'");
3436 PopLocalScope(LetScope
);
3438 // Outside this let scope, this let block is not active.
3439 LetStack
.pop_back();
3443 /// ParseMultiClass - Parse a multiclass definition.
3445 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
3446 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
3447 /// MultiClassObject ::= Assert
3448 /// MultiClassObject ::= DefInst
3449 /// MultiClassObject ::= DefMInst
3450 /// MultiClassObject ::= Defvar
3451 /// MultiClassObject ::= Foreach
3452 /// MultiClassObject ::= If
3453 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
3454 /// MultiClassObject ::= LETCommand Object
3456 bool TGParser::ParseMultiClass() {
3457 assert(Lex
.getCode() == tgtok::MultiClass
&& "Unexpected token");
3458 Lex
.Lex(); // Eat the multiclass token.
3460 if (Lex
.getCode() != tgtok::Id
)
3461 return TokError("expected identifier after multiclass for name");
3462 std::string Name
= Lex
.getCurStrVal();
3465 MultiClasses
.insert(std::make_pair(Name
,
3466 std::make_unique
<MultiClass
>(Name
, Lex
.getLoc(),Records
)));
3469 return TokError("multiclass '" + Name
+ "' already defined");
3471 CurMultiClass
= Result
.first
->second
.get();
3472 Lex
.Lex(); // Eat the identifier.
3474 // If there are template args, parse them.
3475 if (Lex
.getCode() == tgtok::less
)
3476 if (ParseTemplateArgList(nullptr))
3479 bool inherits
= false;
3481 // If there are submulticlasses, parse them.
3482 if (consume(tgtok::colon
)) {
3485 // Read all of the submulticlasses.
3486 SubMultiClassReference SubMultiClass
=
3487 ParseSubMultiClassReference(CurMultiClass
);
3490 if (!SubMultiClass
.MC
) return true;
3493 if (AddSubMultiClass(CurMultiClass
, SubMultiClass
))
3496 if (!consume(tgtok::comma
))
3498 SubMultiClass
= ParseSubMultiClassReference(CurMultiClass
);
3502 if (Lex
.getCode() != tgtok::l_brace
) {
3504 return TokError("expected '{' in multiclass definition");
3505 if (!consume(tgtok::semi
))
3506 return TokError("expected ';' in multiclass definition");
3508 if (Lex
.Lex() == tgtok::r_brace
) // eat the '{'.
3509 return TokError("multiclass must contain at least one def");
3511 // A multiclass body introduces a new scope for local variables.
3512 TGLocalVarScope
*MulticlassScope
= PushLocalScope();
3514 while (Lex
.getCode() != tgtok::r_brace
) {
3515 switch (Lex
.getCode()) {
3517 return TokError("expected 'assert', 'def', 'defm', 'defvar', "
3518 "'foreach', 'if', or 'let' in multiclass body");
3524 case tgtok::Foreach
:
3527 if (ParseObject(CurMultiClass
))
3532 Lex
.Lex(); // eat the '}'.
3534 // If we have a semicolon, print a gentle error.
3535 SMLoc SemiLoc
= Lex
.getLoc();
3536 if (consume(tgtok::semi
)) {
3537 PrintError(SemiLoc
, "A multiclass body should not end with a semicolon");
3538 PrintNote("Semicolon ignored; remove to eliminate this error");
3541 PopLocalScope(MulticlassScope
);
3544 CurMultiClass
= nullptr;
3548 /// ParseDefm - Parse the instantiation of a multiclass.
3550 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
3552 bool TGParser::ParseDefm(MultiClass
*CurMultiClass
) {
3553 assert(Lex
.getCode() == tgtok::Defm
&& "Unexpected token!");
3554 Lex
.Lex(); // eat the defm
3556 Init
*DefmName
= ParseObjectName(CurMultiClass
);
3559 if (isa
<UnsetInit
>(DefmName
)) {
3560 DefmName
= Records
.getNewAnonymousName();
3562 DefmName
= BinOpInit::getStrConcat(
3563 VarInit::get(QualifiedNameOfImplicitName(CurMultiClass
),
3564 StringRecTy::get()),
3568 if (Lex
.getCode() != tgtok::colon
)
3569 return TokError("expected ':' after defm identifier");
3571 // Keep track of the new generated record definitions.
3572 std::vector
<RecordsEntry
> NewEntries
;
3574 // This record also inherits from a regular class (non-multiclass)?
3575 bool InheritFromClass
= false;
3580 SMLoc SubClassLoc
= Lex
.getLoc();
3581 SubClassReference Ref
= ParseSubClassReference(nullptr, true);
3584 if (!Ref
.Rec
) return true;
3586 // To instantiate a multiclass, we get the multiclass and then loop
3587 // through its template argument names. Substs contains a substitution
3588 // value for each argument, either the value specified or the default.
3589 // Then we can resolve the template arguments.
3590 MultiClass
*MC
= MultiClasses
[std::string(Ref
.Rec
->getName())].get();
3591 assert(MC
&& "Didn't lookup multiclass correctly?");
3593 ArrayRef
<Init
*> TemplateVals
= Ref
.TemplateArgs
;
3594 ArrayRef
<Init
*> TArgs
= MC
->Rec
.getTemplateArgs();
3597 for (unsigned i
= 0, e
= TArgs
.size(); i
!= e
; ++i
) {
3598 if (i
< TemplateVals
.size()) {
3599 Substs
.emplace_back(TArgs
[i
], TemplateVals
[i
]);
3601 Init
*Default
= MC
->Rec
.getValue(TArgs
[i
])->getValue();
3602 if (!Default
->isComplete())
3603 return Error(SubClassLoc
,
3604 "value not specified for template argument '" +
3605 TArgs
[i
]->getAsUnquotedString() + "' (#" +
3606 Twine(i
) + ") of multiclass '" +
3607 MC
->Rec
.getNameInitAsString() + "'");
3608 Substs
.emplace_back(TArgs
[i
], Default
);
3612 Substs
.emplace_back(QualifiedNameOfImplicitName(MC
), DefmName
);
3614 if (resolve(MC
->Entries
, Substs
, !CurMultiClass
&& Loops
.empty(),
3615 &NewEntries
, &SubClassLoc
))
3618 if (!consume(tgtok::comma
))
3621 if (Lex
.getCode() != tgtok::Id
)
3622 return TokError("expected identifier");
3624 SubClassLoc
= Lex
.getLoc();
3626 // A defm can inherit from regular classes (non-multiclasses) as
3627 // long as they come in the end of the inheritance list.
3628 InheritFromClass
= (Records
.getClass(Lex
.getCurStrVal()) != nullptr);
3630 if (InheritFromClass
)
3633 Ref
= ParseSubClassReference(nullptr, true);
3636 if (InheritFromClass
) {
3637 // Process all the classes to inherit as if they were part of a
3638 // regular 'def' and inherit all record values.
3639 SubClassReference SubClass
= ParseSubClassReference(nullptr, false);
3642 if (!SubClass
.Rec
) return true;
3644 // Get the expanded definition prototypes and teach them about
3645 // the record values the current class to inherit has
3646 for (auto &E
: NewEntries
) {
3648 if (AddSubClass(E
, SubClass
))
3652 if (!consume(tgtok::comma
))
3654 SubClass
= ParseSubClassReference(nullptr, false);
3658 for (auto &E
: NewEntries
) {
3659 if (ApplyLetStack(E
))
3662 addEntry(std::move(E
));
3665 if (!consume(tgtok::semi
))
3666 return TokError("expected ';' at end of defm");
3672 /// Object ::= ClassInst
3673 /// Object ::= DefInst
3674 /// Object ::= MultiClassInst
3675 /// Object ::= DefMInst
3676 /// Object ::= LETCommand '{' ObjectList '}'
3677 /// Object ::= LETCommand Object
3678 /// Object ::= Defset
3679 /// Object ::= Defvar
3680 /// Object ::= Assert
3681 bool TGParser::ParseObject(MultiClass
*MC
) {
3682 switch (Lex
.getCode()) {
3685 "Expected assert, class, def, defm, defset, foreach, if, or let");
3686 case tgtok::Assert
: return ParseAssert(MC
);
3687 case tgtok::Def
: return ParseDef(MC
);
3688 case tgtok::Defm
: return ParseDefm(MC
);
3689 case tgtok::Defvar
: return ParseDefvar();
3690 case tgtok::Foreach
: return ParseForeach(MC
);
3691 case tgtok::If
: return ParseIf(MC
);
3692 case tgtok::Let
: return ParseTopLevelLet(MC
);
3695 return TokError("defset is not allowed inside multiclass");
3696 return ParseDefset();
3699 return TokError("class is not allowed inside multiclass");
3701 return TokError("class is not allowed inside foreach loop");
3702 return ParseClass();
3703 case tgtok::MultiClass
:
3705 return TokError("multiclass is not allowed inside foreach loop");
3706 return ParseMultiClass();
3711 /// ObjectList :== Object*
3712 bool TGParser::ParseObjectList(MultiClass
*MC
) {
3713 while (isObjectStart(Lex
.getCode())) {
3714 if (ParseObject(MC
))
3720 bool TGParser::ParseFile() {
3721 Lex
.Lex(); // Prime the lexer.
3722 if (ParseObjectList()) return true;
3724 // If we have unread input at the end of the file, report it.
3725 if (Lex
.getCode() == tgtok::Eof
)
3728 return TokError("Unexpected token at top level");
3731 // Check the types of the template argument values for a class
3732 // inheritance, multiclass invocation, or anonymous class invocation.
3733 // If necessary, replace an argument with a cast to the required type.
3734 // The argument count has already been checked.
3735 bool TGParser::CheckTemplateArgValues(SmallVectorImpl
<llvm::Init
*> &Values
,
3736 SMLoc Loc
, Record
*ArgsRec
) {
3738 ArrayRef
<Init
*> TArgs
= ArgsRec
->getTemplateArgs();
3740 for (unsigned I
= 0, E
= Values
.size(); I
< E
; ++I
) {
3741 RecordVal
*Arg
= ArgsRec
->getValue(TArgs
[I
]);
3742 RecTy
*ArgType
= Arg
->getType();
3743 auto *Value
= Values
[I
];
3745 if (TypedInit
*ArgValue
= dyn_cast
<TypedInit
>(Value
)) {
3746 auto *CastValue
= ArgValue
->getCastTo(ArgType
);
3748 assert((!isa
<TypedInit
>(CastValue
) ||
3749 cast
<TypedInit
>(CastValue
)->getType()->typeIsA(ArgType
)) &&
3750 "result of template arg value cast has wrong type");
3751 Values
[I
] = CastValue
;
3753 PrintFatalError(Loc
,
3754 "Value specified for template argument '" +
3755 Arg
->getNameInitAsString() + "' (#" + Twine(I
) +
3756 ") is of type " + ArgValue
->getType()->getAsString() +
3757 "; expected type " + ArgType
->getAsString() + ": " +
3758 ArgValue
->getAsString());
3766 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3767 LLVM_DUMP_METHOD
void RecordsEntry::dump() const {
3774 LLVM_DUMP_METHOD
void ForeachLoop::dump() const {
3775 errs() << "foreach " << IterVar
->getAsString() << " = "
3776 << ListValue
->getAsString() << " in {\n";
3778 for (const auto &E
: Entries
)
3784 LLVM_DUMP_METHOD
void MultiClass::dump() const {
3785 errs() << "Record:\n";
3788 errs() << "Defs:\n";
3789 for (const auto &E
: Entries
)