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/DenseMapInfo.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/Twine.h"
18 #include "llvm/Config/llvm-config.h"
19 #include "llvm/Support/Casting.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/raw_ostream.h"
30 //===----------------------------------------------------------------------===//
31 // Support Code for the Semantic Actions.
32 //===----------------------------------------------------------------------===//
36 struct SubClassReference
{
38 Record
*Rec
= nullptr;
39 SmallVector
<ArgumentInit
*, 4> TemplateArgs
;
41 SubClassReference() = default;
43 bool isInvalid() const { return Rec
== nullptr; }
46 struct SubMultiClassReference
{
48 MultiClass
*MC
= nullptr;
49 SmallVector
<ArgumentInit
*, 4> TemplateArgs
;
51 SubMultiClassReference() = default;
53 bool isInvalid() const { return MC
== nullptr; }
57 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
58 LLVM_DUMP_METHOD
void SubMultiClassReference::dump() const {
59 errs() << "Multiclass:\n";
63 errs() << "Template args:\n";
64 for (Init
*TA
: TemplateArgs
)
69 } // end namespace llvm
71 static bool checkBitsConcrete(Record
&R
, const RecordVal
&RV
) {
72 BitsInit
*BV
= cast
<BitsInit
>(RV
.getValue());
73 for (unsigned i
= 0, e
= BV
->getNumBits(); i
!= e
; ++i
) {
74 Init
*Bit
= BV
->getBit(i
);
75 bool IsReference
= false;
76 if (auto VBI
= dyn_cast
<VarBitInit
>(Bit
)) {
77 if (auto VI
= dyn_cast
<VarInit
>(VBI
->getBitVar())) {
78 if (R
.getValue(VI
->getName()))
81 } else if (isa
<VarInit
>(Bit
)) {
84 if (!(IsReference
|| Bit
->isConcrete()))
90 static void checkConcrete(Record
&R
) {
91 for (const RecordVal
&RV
: R
.getValues()) {
92 // HACK: Disable this check for variables declared with 'field'. This is
93 // done merely because existing targets have legitimate cases of
94 // non-concrete variables in helper defs. Ideally, we'd introduce a
95 // 'maybe' or 'optional' modifier instead of this.
96 if (RV
.isNonconcreteOK())
99 if (Init
*V
= RV
.getValue()) {
100 bool Ok
= isa
<BitsInit
>(V
) ? checkBitsConcrete(R
, RV
) : V
->isConcrete();
102 PrintError(R
.getLoc(),
103 Twine("Initializer of '") + RV
.getNameInitAsString() +
104 "' in '" + R
.getNameInitAsString() +
105 "' could not be fully resolved: " +
106 RV
.getValue()->getAsString());
112 /// Return an Init with a qualifier prefix referring
113 /// to CurRec's name.
114 static Init
*QualifyName(Record
&CurRec
, Init
*Name
) {
115 RecordKeeper
&RK
= CurRec
.getRecords();
116 Init
*NewName
= BinOpInit::getStrConcat(
117 CurRec
.getNameInit(),
118 StringInit::get(RK
, CurRec
.isMultiClass() ? "::" : ":"));
119 NewName
= BinOpInit::getStrConcat(NewName
, Name
);
121 if (BinOpInit
*BinOp
= dyn_cast
<BinOpInit
>(NewName
))
122 NewName
= BinOp
->Fold(&CurRec
);
126 static Init
*QualifyName(MultiClass
*MC
, Init
*Name
) {
127 return QualifyName(MC
->Rec
, Name
);
130 /// Return the qualified version of the implicit 'NAME' template argument.
131 static Init
*QualifiedNameOfImplicitName(Record
&Rec
) {
132 return QualifyName(Rec
, StringInit::get(Rec
.getRecords(), "NAME"));
135 static Init
*QualifiedNameOfImplicitName(MultiClass
*MC
) {
136 return QualifiedNameOfImplicitName(MC
->Rec
);
139 Init
*TGVarScope::getVar(RecordKeeper
&Records
, MultiClass
*ParsingMultiClass
,
140 StringInit
*Name
, SMRange NameLoc
,
141 bool TrackReferenceLocs
) const {
142 // First, we search in local variables.
143 auto It
= Vars
.find(Name
->getValue());
144 if (It
!= Vars
.end())
147 auto FindValueInArgs
= [&](Record
*Rec
, StringInit
*Name
) -> Init
* {
150 Init
*ArgName
= QualifyName(*Rec
, Name
);
151 if (Rec
->isTemplateArg(ArgName
)) {
152 RecordVal
*RV
= Rec
->getValue(ArgName
);
153 assert(RV
&& "Template arg doesn't exist??");
155 if (TrackReferenceLocs
)
156 RV
->addReferenceLoc(NameLoc
);
157 return VarInit::get(ArgName
, RV
->getType());
159 return Name
->getValue() == "NAME"
160 ? VarInit::get(ArgName
, StringRecTy::get(Records
))
164 // If not found, we try to find the variable in additional variables like
165 // arguments, loop iterator, etc.
168 break; /* do nothing. */
171 // The variable is a record field?
172 if (RecordVal
*RV
= CurRec
->getValue(Name
)) {
173 if (TrackReferenceLocs
)
174 RV
->addReferenceLoc(NameLoc
);
175 return VarInit::get(Name
, RV
->getType());
178 // The variable is a class template argument?
179 if (CurRec
->isClass())
180 if (auto *V
= FindValueInArgs(CurRec
, Name
))
185 case SK_ForeachLoop
: {
186 // The variable is a loop iterator?
187 if (CurLoop
->IterVar
) {
188 VarInit
*IterVar
= dyn_cast
<VarInit
>(CurLoop
->IterVar
);
189 if (IterVar
&& IterVar
->getNameInit() == Name
)
194 case SK_MultiClass
: {
195 // The variable is a multiclass template argument?
197 if (auto *V
= FindValueInArgs(&CurMultiClass
->Rec
, Name
))
203 // Then, we try to find the name in parent scope.
205 return Parent
->getVar(Records
, ParsingMultiClass
, Name
, NameLoc
,
211 bool TGParser::AddValue(Record
*CurRec
, SMLoc Loc
, const RecordVal
&RV
) {
213 CurRec
= &CurMultiClass
->Rec
;
215 if (RecordVal
*ERV
= CurRec
->getValue(RV
.getNameInit())) {
216 // The value already exists in the class, treat this as a set.
217 if (ERV
->setValue(RV
.getValue()))
218 return Error(Loc
, "New definition of '" + RV
.getName() + "' of type '" +
219 RV
.getType()->getAsString() + "' is incompatible with " +
220 "previous definition of type '" +
221 ERV
->getType()->getAsString() + "'");
223 CurRec
->addValue(RV
);
229 /// Return true on error, false on success.
230 bool TGParser::SetValue(Record
*CurRec
, SMLoc Loc
, Init
*ValName
,
231 ArrayRef
<unsigned> BitList
, Init
*V
,
232 bool AllowSelfAssignment
, bool OverrideDefLoc
) {
233 if (!V
) return false;
235 if (!CurRec
) CurRec
= &CurMultiClass
->Rec
;
237 RecordVal
*RV
= CurRec
->getValue(ValName
);
239 return Error(Loc
, "Value '" + ValName
->getAsUnquotedString() +
242 // Do not allow assignments like 'X = X'. This will just cause infinite loops
243 // in the resolution machinery.
245 if (VarInit
*VI
= dyn_cast
<VarInit
>(V
))
246 if (VI
->getNameInit() == ValName
&& !AllowSelfAssignment
)
247 return Error(Loc
, "Recursion / self-assignment forbidden");
249 // If we are assigning to a subset of the bits in the value... then we must be
250 // assigning to a field of BitsRecTy, which must have a BitsInit
253 if (!BitList
.empty()) {
254 BitsInit
*CurVal
= dyn_cast
<BitsInit
>(RV
->getValue());
256 return Error(Loc
, "Value '" + ValName
->getAsUnquotedString() +
257 "' is not a bits type");
259 // Convert the incoming value to a bits type of the appropriate size...
260 Init
*BI
= V
->getCastTo(BitsRecTy::get(Records
, BitList
.size()));
262 return Error(Loc
, "Initializer is not compatible with bit range");
264 SmallVector
<Init
*, 16> NewBits(CurVal
->getNumBits());
266 // Loop over bits, assigning values as appropriate.
267 for (unsigned i
= 0, e
= BitList
.size(); i
!= e
; ++i
) {
268 unsigned Bit
= BitList
[i
];
270 return Error(Loc
, "Cannot set bit #" + Twine(Bit
) + " of value '" +
271 ValName
->getAsUnquotedString() + "' more than once");
272 NewBits
[Bit
] = BI
->getBit(i
);
275 for (unsigned i
= 0, e
= CurVal
->getNumBits(); i
!= e
; ++i
)
277 NewBits
[i
] = CurVal
->getBit(i
);
279 V
= BitsInit::get(Records
, NewBits
);
282 if (OverrideDefLoc
? RV
->setValue(V
, Loc
) : RV
->setValue(V
)) {
283 std::string InitType
;
284 if (BitsInit
*BI
= dyn_cast
<BitsInit
>(V
))
285 InitType
= (Twine("' of type bit initializer with length ") +
286 Twine(BI
->getNumBits())).str();
287 else if (TypedInit
*TI
= dyn_cast
<TypedInit
>(V
))
288 InitType
= (Twine("' of type '") + TI
->getType()->getAsString()).str();
289 return Error(Loc
, "Field '" + ValName
->getAsUnquotedString() +
290 "' of type '" + RV
->getType()->getAsString() +
291 "' is incompatible with value '" +
292 V
->getAsString() + InitType
+ "'");
297 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
298 /// args as SubClass's template arguments.
299 bool TGParser::AddSubClass(Record
*CurRec
, SubClassReference
&SubClass
) {
300 Record
*SC
= SubClass
.Rec
;
301 MapResolver
R(CurRec
);
303 // Loop over all the subclass record's fields. Add regular fields to the new
305 for (const RecordVal
&Field
: SC
->getValues())
306 if (!Field
.isTemplateArg())
307 if (AddValue(CurRec
, SubClass
.RefRange
.Start
, Field
))
310 if (resolveArgumentsOfClass(R
, SC
, SubClass
.TemplateArgs
,
311 SubClass
.RefRange
.Start
))
314 // Copy the subclass record's assertions to the new record.
315 CurRec
->appendAssertions(SC
);
317 // Copy the subclass record's dumps to the new record.
318 CurRec
->appendDumps(SC
);
321 if (CurRec
->isClass())
322 Name
= VarInit::get(QualifiedNameOfImplicitName(*CurRec
),
323 StringRecTy::get(Records
));
325 Name
= CurRec
->getNameInit();
326 R
.set(QualifiedNameOfImplicitName(*SC
), Name
);
328 CurRec
->resolveReferences(R
);
330 // Since everything went well, we can now set the "superclass" list for the
332 ArrayRef
<std::pair
<Record
*, SMRange
>> SCs
= SC
->getSuperClasses();
333 for (const auto &SCPair
: SCs
) {
334 if (CurRec
->isSubClassOf(SCPair
.first
))
335 return Error(SubClass
.RefRange
.Start
,
336 "Already subclass of '" + SCPair
.first
->getName() + "'!\n");
337 CurRec
->addSuperClass(SCPair
.first
, SCPair
.second
);
340 if (CurRec
->isSubClassOf(SC
))
341 return Error(SubClass
.RefRange
.Start
,
342 "Already subclass of '" + SC
->getName() + "'!\n");
343 CurRec
->addSuperClass(SC
, SubClass
.RefRange
);
347 bool TGParser::AddSubClass(RecordsEntry
&Entry
, SubClassReference
&SubClass
) {
349 return AddSubClass(Entry
.Rec
.get(), SubClass
);
354 for (auto &E
: Entry
.Loop
->Entries
) {
355 if (AddSubClass(E
, SubClass
))
362 /// AddSubMultiClass - Add SubMultiClass as a subclass to
363 /// CurMC, resolving its template args as SubMultiClass's
364 /// template arguments.
365 bool TGParser::AddSubMultiClass(MultiClass
*CurMC
,
366 SubMultiClassReference
&SubMultiClass
) {
367 MultiClass
*SMC
= SubMultiClass
.MC
;
370 if (resolveArgumentsOfMultiClass(
371 Substs
, SMC
, SubMultiClass
.TemplateArgs
,
372 VarInit::get(QualifiedNameOfImplicitName(CurMC
),
373 StringRecTy::get(Records
)),
374 SubMultiClass
.RefRange
.Start
))
377 // Add all of the defs in the subclass into the current multiclass.
378 return resolve(SMC
->Entries
, Substs
, false, &CurMC
->Entries
);
381 /// Add a record, foreach loop, or assertion to the current context.
382 bool TGParser::addEntry(RecordsEntry E
) {
383 assert((!!E
.Rec
+ !!E
.Loop
+ !!E
.Assertion
+ !!E
.Dump
) == 1 &&
384 "RecordsEntry has invalid number of items");
386 // If we are parsing a loop, add it to the loop's entries.
387 if (!Loops
.empty()) {
388 Loops
.back()->Entries
.push_back(std::move(E
));
392 // If it is a loop, then resolve and perform the loop.
395 return resolve(*E
.Loop
, Stack
, CurMultiClass
== nullptr,
396 CurMultiClass
? &CurMultiClass
->Entries
: nullptr);
399 // If we are parsing a multiclass, add it to the multiclass's entries.
401 CurMultiClass
->Entries
.push_back(std::move(E
));
405 // If it is an assertion, then it's a top-level one, so check it.
407 CheckAssert(E
.Assertion
->Loc
, E
.Assertion
->Condition
, E
.Assertion
->Message
);
412 dumpMessage(E
.Dump
->Loc
, E
.Dump
->Message
);
416 // It must be a record, so finish it off.
417 return addDefOne(std::move(E
.Rec
));
420 /// Resolve the entries in \p Loop, going over inner loops recursively
421 /// and making the given subsitutions of (name, value) pairs.
423 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
424 /// are added to the global record keeper.
425 bool TGParser::resolve(const ForeachLoop
&Loop
, SubstStack
&Substs
,
426 bool Final
, std::vector
<RecordsEntry
> *Dest
,
430 for (const auto &S
: Substs
)
431 R
.set(S
.first
, S
.second
);
432 Init
*List
= Loop
.ListValue
->resolveReferences(R
);
434 // For if-then-else blocks, we lower to a foreach loop whose list is a
435 // ternary selection between lists of different length. Since we don't
436 // have a means to track variable length record lists, we *must* resolve
437 // the condition here. We want to defer final resolution of the arms
438 // until the resulting records are finalized.
439 // e.g. !if(!exists<SchedWrite>("__does_not_exist__"), [1], [])
440 if (auto *TI
= dyn_cast
<TernOpInit
>(List
);
441 TI
&& TI
->getOpcode() == TernOpInit::IF
&& Final
) {
442 Init
*OldLHS
= TI
->getLHS();
444 Init
*LHS
= OldLHS
->resolveReferences(R
);
447 Twine("unable to resolve if condition '") +
448 LHS
->getAsString() + "' at end of containing scope");
451 Init
*MHS
= TI
->getMHS();
452 Init
*RHS
= TI
->getRHS();
453 List
= TernOpInit::get(TernOpInit::IF
, LHS
, MHS
, RHS
, TI
->getType())
457 auto LI
= dyn_cast
<ListInit
>(List
);
460 Dest
->emplace_back(std::make_unique
<ForeachLoop
>(Loop
.Loc
, Loop
.IterVar
,
462 return resolve(Loop
.Entries
, Substs
, Final
, &Dest
->back().Loop
->Entries
,
466 PrintError(Loop
.Loc
, Twine("attempting to loop over '") +
467 List
->getAsString() + "', expected a list");
472 for (auto *Elt
: *LI
) {
474 Substs
.emplace_back(Loop
.IterVar
->getNameInit(), Elt
);
475 Error
= resolve(Loop
.Entries
, Substs
, Final
, Dest
);
484 /// Resolve the entries in \p Source, going over loops recursively and
485 /// making the given substitutions of (name, value) pairs.
487 /// The resulting records are stored in \p Dest if non-null. Otherwise, they
488 /// are added to the global record keeper.
489 bool TGParser::resolve(const std::vector
<RecordsEntry
> &Source
,
490 SubstStack
&Substs
, bool Final
,
491 std::vector
<RecordsEntry
> *Dest
, SMLoc
*Loc
) {
493 for (auto &E
: Source
) {
495 Error
= resolve(*E
.Loop
, Substs
, Final
, Dest
);
497 } else if (E
.Assertion
) {
499 for (const auto &S
: Substs
)
500 R
.set(S
.first
, S
.second
);
501 Init
*Condition
= E
.Assertion
->Condition
->resolveReferences(R
);
502 Init
*Message
= E
.Assertion
->Message
->resolveReferences(R
);
505 Dest
->push_back(std::make_unique
<Record::AssertionInfo
>(
506 E
.Assertion
->Loc
, Condition
, Message
));
508 CheckAssert(E
.Assertion
->Loc
, Condition
, Message
);
512 for (const auto &S
: Substs
)
513 R
.set(S
.first
, S
.second
);
514 Init
*Message
= E
.Dump
->Message
->resolveReferences(R
);
518 std::make_unique
<Record::DumpInfo
>(E
.Dump
->Loc
, Message
));
520 dumpMessage(E
.Dump
->Loc
, Message
);
523 auto Rec
= std::make_unique
<Record
>(*E
.Rec
);
525 Rec
->appendLoc(*Loc
);
527 MapResolver
R(Rec
.get());
528 for (const auto &S
: Substs
)
529 R
.set(S
.first
, S
.second
);
530 Rec
->resolveReferences(R
);
533 Dest
->push_back(std::move(Rec
));
535 Error
= addDefOne(std::move(Rec
));
543 /// Resolve the record fully and add it to the record keeper.
544 bool TGParser::addDefOne(std::unique_ptr
<Record
> Rec
) {
545 Init
*NewName
= nullptr;
546 if (Record
*Prev
= Records
.getDef(Rec
->getNameInitAsString())) {
547 if (!Rec
->isAnonymous()) {
548 PrintError(Rec
->getLoc(),
549 "def already exists: " + Rec
->getNameInitAsString());
550 PrintNote(Prev
->getLoc(), "location of previous definition");
553 NewName
= Records
.getNewAnonymousName();
556 Rec
->resolveReferences(NewName
);
559 if (!isa
<StringInit
>(Rec
->getNameInit())) {
560 PrintError(Rec
->getLoc(), Twine("record name '") +
561 Rec
->getNameInit()->getAsString() +
562 "' could not be fully resolved");
566 // Check the assertions.
567 Rec
->checkRecordAssertions();
570 Rec
->emitRecordDumps();
572 // If ObjectBody has template arguments, it's an error.
573 assert(Rec
->getTemplateArgs().empty() && "How'd this get template args?");
575 for (DefsetRecord
*Defset
: Defsets
) {
576 DefInit
*I
= Rec
->getDefInit();
577 if (!I
->getType()->typeIsA(Defset
->EltTy
)) {
578 PrintError(Rec
->getLoc(), Twine("adding record of incompatible type '") +
579 I
->getType()->getAsString() +
581 PrintNote(Defset
->Loc
, "location of defset declaration");
584 Defset
->Elements
.push_back(I
);
587 Records
.addDef(std::move(Rec
));
591 bool TGParser::resolveArguments(Record
*Rec
, ArrayRef
<ArgumentInit
*> ArgValues
,
592 SMLoc Loc
, ArgValueHandler ArgValueHandler
) {
593 ArrayRef
<Init
*> ArgNames
= Rec
->getTemplateArgs();
594 assert(ArgValues
.size() <= ArgNames
.size() &&
595 "Too many template arguments allowed");
597 // Loop over the template arguments and handle the (name, value) pair.
598 SmallVector
<Init
*, 2> UnsolvedArgNames(ArgNames
);
599 for (auto *Arg
: ArgValues
) {
600 Init
*ArgName
= nullptr;
601 Init
*ArgValue
= Arg
->getValue();
602 if (Arg
->isPositional())
603 ArgName
= ArgNames
[Arg
->getIndex()];
605 ArgName
= Arg
->getName();
607 // We can only specify the template argument once.
608 if (!is_contained(UnsolvedArgNames
, ArgName
))
609 return Error(Loc
, "We can only specify the template argument '" +
610 ArgName
->getAsUnquotedString() + "' once");
612 ArgValueHandler(ArgName
, ArgValue
);
613 llvm::erase(UnsolvedArgNames
, ArgName
);
616 // For unsolved arguments, if there is no default value, complain.
617 for (auto *UnsolvedArgName
: UnsolvedArgNames
) {
618 Init
*Default
= Rec
->getValue(UnsolvedArgName
)->getValue();
619 if (!Default
->isComplete()) {
620 std::string Name
= UnsolvedArgName
->getAsUnquotedString();
621 Error(Loc
, "value not specified for template argument '" + Name
+ "'");
622 PrintNote(Rec
->getFieldLoc(Name
),
623 "declared in '" + Rec
->getNameInitAsString() + "'");
626 ArgValueHandler(UnsolvedArgName
, Default
);
632 /// Resolve the arguments of class and set them to MapResolver.
633 /// Returns true if failed.
634 bool TGParser::resolveArgumentsOfClass(MapResolver
&R
, Record
*Rec
,
635 ArrayRef
<ArgumentInit
*> ArgValues
,
637 return resolveArguments(Rec
, ArgValues
, Loc
,
638 [&](Init
*Name
, Init
*Value
) { R
.set(Name
, Value
); });
641 /// Resolve the arguments of multiclass and store them into SubstStack.
642 /// Returns true if failed.
643 bool TGParser::resolveArgumentsOfMultiClass(SubstStack
&Substs
, MultiClass
*MC
,
644 ArrayRef
<ArgumentInit
*> ArgValues
,
645 Init
*DefmName
, SMLoc Loc
) {
646 // Add an implicit argument NAME.
647 Substs
.emplace_back(QualifiedNameOfImplicitName(MC
), DefmName
);
648 return resolveArguments(
649 &MC
->Rec
, ArgValues
, Loc
,
650 [&](Init
*Name
, Init
*Value
) { Substs
.emplace_back(Name
, Value
); });
653 //===----------------------------------------------------------------------===//
655 //===----------------------------------------------------------------------===//
657 bool TGParser::consume(tgtok::TokKind K
) {
658 if (Lex
.getCode() == K
) {
665 /// ParseObjectName - If a valid object name is specified, return it. If no
666 /// name is specified, return the unset initializer. Return nullptr on parse
668 /// ObjectName ::= Value [ '#' Value ]*
669 /// ObjectName ::= /*empty*/
671 Init
*TGParser::ParseObjectName(MultiClass
*CurMultiClass
) {
672 switch (Lex
.getCode()) {
676 // These are all of the tokens that can begin an object body.
677 // Some of these can also begin values but we disallow those cases
678 // because they are unlikely to be useful.
679 return UnsetInit::get(Records
);
684 Record
*CurRec
= nullptr;
686 CurRec
= &CurMultiClass
->Rec
;
688 Init
*Name
= ParseValue(CurRec
, StringRecTy::get(Records
), ParseNameMode
);
693 Init
*NameStr
= QualifiedNameOfImplicitName(CurMultiClass
);
694 HasReferenceResolver
R(NameStr
);
695 Name
->resolveReferences(R
);
697 Name
= BinOpInit::getStrConcat(
698 VarInit::get(NameStr
, StringRecTy::get(Records
)), Name
);
704 /// ParseClassID - Parse and resolve a reference to a class name. This returns
709 Record
*TGParser::ParseClassID() {
710 if (Lex
.getCode() != tgtok::Id
) {
711 TokError("expected name for ClassID");
715 Record
*Result
= Records
.getClass(Lex
.getCurStrVal());
717 std::string
Msg("Couldn't find class '" + Lex
.getCurStrVal() + "'");
718 if (MultiClasses
[Lex
.getCurStrVal()].get())
719 TokError(Msg
+ ". Use 'defm' if you meant to use multiclass '" +
720 Lex
.getCurStrVal() + "'");
723 } else if (TrackReferenceLocs
) {
724 Result
->appendReferenceLoc(Lex
.getLocRange());
731 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
732 /// This returns null on error.
734 /// MultiClassID ::= ID
736 MultiClass
*TGParser::ParseMultiClassID() {
737 if (Lex
.getCode() != tgtok::Id
) {
738 TokError("expected name for MultiClassID");
742 MultiClass
*Result
= MultiClasses
[Lex
.getCurStrVal()].get();
744 TokError("Couldn't find multiclass '" + Lex
.getCurStrVal() + "'");
750 /// ParseSubClassReference - Parse a reference to a subclass or a
751 /// multiclass. This returns a SubClassRefTy with a null Record* on error.
753 /// SubClassRef ::= ClassID
754 /// SubClassRef ::= ClassID '<' ArgValueList '>'
756 SubClassReference
TGParser::
757 ParseSubClassReference(Record
*CurRec
, bool isDefm
) {
758 SubClassReference Result
;
759 Result
.RefRange
.Start
= Lex
.getLoc();
762 if (MultiClass
*MC
= ParseMultiClassID())
763 Result
.Rec
= &MC
->Rec
;
765 Result
.Rec
= ParseClassID();
767 if (!Result
.Rec
) return Result
;
769 // If there is no template arg list, we're done.
770 if (!consume(tgtok::less
)) {
771 Result
.RefRange
.End
= Lex
.getLoc();
775 if (ParseTemplateArgValueList(Result
.TemplateArgs
, CurRec
, Result
.Rec
)) {
776 Result
.Rec
= nullptr; // Error parsing value list.
780 if (CheckTemplateArgValues(Result
.TemplateArgs
, Result
.RefRange
.Start
,
782 Result
.Rec
= nullptr; // Error checking value list.
786 Result
.RefRange
.End
= Lex
.getLoc();
790 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
791 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
792 /// Record* on error.
794 /// SubMultiClassRef ::= MultiClassID
795 /// SubMultiClassRef ::= MultiClassID '<' ArgValueList '>'
797 SubMultiClassReference
TGParser::
798 ParseSubMultiClassReference(MultiClass
*CurMC
) {
799 SubMultiClassReference Result
;
800 Result
.RefRange
.Start
= Lex
.getLoc();
802 Result
.MC
= ParseMultiClassID();
803 if (!Result
.MC
) return Result
;
805 // If there is no template arg list, we're done.
806 if (!consume(tgtok::less
)) {
807 Result
.RefRange
.End
= Lex
.getLoc();
811 if (ParseTemplateArgValueList(Result
.TemplateArgs
, &CurMC
->Rec
,
813 Result
.MC
= nullptr; // Error parsing value list.
817 Result
.RefRange
.End
= Lex
.getLoc();
822 /// ParseSliceElement - Parse subscript or range
824 /// SliceElement ::= Value<list<int>>
825 /// SliceElement ::= Value<int>
826 /// SliceElement ::= Value<int> '...' Value<int>
827 /// SliceElement ::= Value<int> '-' Value<int> (deprecated)
828 /// SliceElement ::= Value<int> INTVAL(Negative; deprecated)
830 /// SliceElement is either IntRecTy, ListRecTy, or nullptr
832 TypedInit
*TGParser::ParseSliceElement(Record
*CurRec
) {
833 auto LHSLoc
= Lex
.getLoc();
834 auto *CurVal
= ParseValue(CurRec
);
837 auto *LHS
= cast
<TypedInit
>(CurVal
);
839 TypedInit
*RHS
= nullptr;
840 switch (Lex
.getCode()) {
841 case tgtok::dotdotdot
:
842 case tgtok::minus
: { // Deprecated
844 auto RHSLoc
= Lex
.getLoc();
845 CurVal
= ParseValue(CurRec
);
848 RHS
= cast
<TypedInit
>(CurVal
);
849 if (!isa
<IntRecTy
>(RHS
->getType())) {
851 "expected int...int, got " + Twine(RHS
->getType()->getAsString()));
856 case tgtok::IntVal
: { // Deprecated "-num"
857 auto i
= -Lex
.getCurIntVal();
859 TokError("invalid range, cannot be negative");
862 RHS
= IntInit::get(Records
, i
);
863 Lex
.Lex(); // eat IntVal
866 default: // Single value (IntRecTy or ListRecTy)
871 assert(isa
<IntRecTy
>(RHS
->getType()));
873 // Closed-interval range <LHS:IntRecTy>...<RHS:IntRecTy>
874 if (!isa
<IntRecTy
>(LHS
->getType())) {
876 "expected int...int, got " + Twine(LHS
->getType()->getAsString()));
880 return cast
<TypedInit
>(BinOpInit::get(BinOpInit::RANGEC
, LHS
, RHS
,
881 IntRecTy::get(Records
)->getListTy())
885 /// ParseSliceElements - Parse subscripts in square brackets.
887 /// SliceElements ::= ( SliceElement ',' )* SliceElement ','?
889 /// SliceElement is either IntRecTy, ListRecTy, or nullptr
891 /// Returns ListRecTy by defaut.
892 /// Returns IntRecTy if;
894 /// - SliceElements is Value<int> w/o trailing comma
896 TypedInit
*TGParser::ParseSliceElements(Record
*CurRec
, bool Single
) {
898 SmallVector
<Init
*, 2> Elems
; // int
899 SmallVector
<TypedInit
*, 2> Slices
; // list<int>
901 auto FlushElems
= [&] {
902 if (!Elems
.empty()) {
903 Slices
.push_back(ListInit::get(Elems
, IntRecTy::get(Records
)));
909 auto LHSLoc
= Lex
.getLoc();
910 CurVal
= ParseSliceElement(CurRec
);
913 auto *CurValTy
= CurVal
->getType();
915 if (auto *ListValTy
= dyn_cast
<ListRecTy
>(CurValTy
)) {
916 if (!isa
<IntRecTy
>(ListValTy
->getElementType())) {
918 "expected list<int>, got " + Twine(ListValTy
->getAsString()));
923 Slices
.push_back(CurVal
);
926 } else if (!isa
<IntRecTy
>(CurValTy
)) {
928 "unhandled type " + Twine(CurValTy
->getAsString()) + " in range");
932 if (Lex
.getCode() != tgtok::comma
)
935 Lex
.Lex(); // eat comma
937 // `[i,]` is not LISTELEM but LISTSLICE
940 Elems
.push_back(CurVal
);
942 } while (Lex
.getCode() != tgtok::r_square
);
949 Elems
.push_back(CurVal
);
954 // Concatenate lists in Slices
955 TypedInit
*Result
= nullptr;
956 for (auto *Slice
: Slices
) {
957 Result
= (Result
? cast
<TypedInit
>(BinOpInit::getListConcat(Result
, Slice
))
964 /// ParseRangePiece - Parse a bit/value range.
965 /// RangePiece ::= INTVAL
966 /// RangePiece ::= INTVAL '...' INTVAL
967 /// RangePiece ::= INTVAL '-' INTVAL
968 /// RangePiece ::= INTVAL INTVAL
969 // The last two forms are deprecated.
970 bool TGParser::ParseRangePiece(SmallVectorImpl
<unsigned> &Ranges
,
971 TypedInit
*FirstItem
) {
972 Init
*CurVal
= FirstItem
;
974 CurVal
= ParseValue(nullptr);
976 IntInit
*II
= dyn_cast_or_null
<IntInit
>(CurVal
);
978 return TokError("expected integer or bitrange");
980 int64_t Start
= II
->getValue();
984 return TokError("invalid range, cannot be negative");
986 switch (Lex
.getCode()) {
988 Ranges
.push_back(Start
);
991 case tgtok::dotdotdot
:
995 Init
*I_End
= ParseValue(nullptr);
996 IntInit
*II_End
= dyn_cast_or_null
<IntInit
>(I_End
);
998 TokError("expected integer value as end of range");
1002 End
= II_End
->getValue();
1005 case tgtok::IntVal
: {
1006 End
= -Lex
.getCurIntVal();
1012 return TokError("invalid range, cannot be negative");
1014 // Add to the range.
1016 for (; Start
<= End
; ++Start
)
1017 Ranges
.push_back(Start
);
1019 for (; Start
>= End
; --Start
)
1020 Ranges
.push_back(Start
);
1024 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
1026 /// RangeList ::= RangePiece (',' RangePiece)*
1028 void TGParser::ParseRangeList(SmallVectorImpl
<unsigned> &Result
) {
1029 // Parse the first piece.
1030 if (ParseRangePiece(Result
)) {
1034 while (consume(tgtok::comma
))
1035 // Parse the next range piece.
1036 if (ParseRangePiece(Result
)) {
1042 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
1043 /// OptionalRangeList ::= '<' RangeList '>'
1044 /// OptionalRangeList ::= /*empty*/
1045 bool TGParser::ParseOptionalRangeList(SmallVectorImpl
<unsigned> &Ranges
) {
1046 SMLoc StartLoc
= Lex
.getLoc();
1047 if (!consume(tgtok::less
))
1050 // Parse the range list.
1051 ParseRangeList(Ranges
);
1052 if (Ranges
.empty()) return true;
1054 if (!consume(tgtok::greater
)) {
1055 TokError("expected '>' at end of range list");
1056 return Error(StartLoc
, "to match this '<'");
1061 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
1062 /// OptionalBitList ::= '{' RangeList '}'
1063 /// OptionalBitList ::= /*empty*/
1064 bool TGParser::ParseOptionalBitList(SmallVectorImpl
<unsigned> &Ranges
) {
1065 SMLoc StartLoc
= Lex
.getLoc();
1066 if (!consume(tgtok::l_brace
))
1069 // Parse the range list.
1070 ParseRangeList(Ranges
);
1071 if (Ranges
.empty()) return true;
1073 if (!consume(tgtok::r_brace
)) {
1074 TokError("expected '}' at end of bit list");
1075 return Error(StartLoc
, "to match this '{'");
1080 /// ParseType - Parse and return a tblgen type. This returns null on error.
1082 /// Type ::= STRING // string type
1083 /// Type ::= CODE // code type
1084 /// Type ::= BIT // bit type
1085 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
1086 /// Type ::= INT // int type
1087 /// Type ::= LIST '<' Type '>' // list<x> type
1088 /// Type ::= DAG // dag type
1089 /// Type ::= ClassID // Record Type
1091 RecTy
*TGParser::ParseType() {
1092 switch (Lex
.getCode()) {
1093 default: TokError("Unknown token when expecting a type"); return nullptr;
1097 return StringRecTy::get(Records
);
1100 return BitRecTy::get(Records
);
1103 return IntRecTy::get(Records
);
1106 return DagRecTy::get(Records
);
1108 if (Record
*R
= ParseClassID())
1109 return RecordRecTy::get(R
);
1110 TokError("unknown class name");
1113 if (Lex
.Lex() != tgtok::less
) { // Eat 'bits'
1114 TokError("expected '<' after bits type");
1117 if (Lex
.Lex() != tgtok::IntVal
) { // Eat '<'
1118 TokError("expected integer in bits<n> type");
1121 uint64_t Val
= Lex
.getCurIntVal();
1122 if (Lex
.Lex() != tgtok::greater
) { // Eat count.
1123 TokError("expected '>' at end of bits<n> type");
1126 Lex
.Lex(); // Eat '>'
1127 return BitsRecTy::get(Records
, Val
);
1130 if (Lex
.Lex() != tgtok::less
) { // Eat 'bits'
1131 TokError("expected '<' after list type");
1134 Lex
.Lex(); // Eat '<'
1135 RecTy
*SubType
= ParseType();
1136 if (!SubType
) return nullptr;
1138 if (!consume(tgtok::greater
)) {
1139 TokError("expected '>' at end of list<ty> type");
1142 return ListRecTy::get(SubType
);
1148 Init
*TGParser::ParseIDValue(Record
*CurRec
, StringInit
*Name
, SMRange NameLoc
,
1150 if (Init
*I
= CurScope
->getVar(Records
, CurMultiClass
, Name
, NameLoc
,
1151 TrackReferenceLocs
))
1154 if (Mode
== ParseNameMode
)
1157 if (Init
*I
= Records
.getGlobal(Name
->getValue())) {
1158 // Add a reference to the global if it's a record.
1159 if (TrackReferenceLocs
) {
1160 if (auto *Def
= dyn_cast
<DefInit
>(I
))
1161 Def
->getDef()->appendReferenceLoc(NameLoc
);
1166 // Allow self-references of concrete defs, but delay the lookup so that we
1167 // get the correct type.
1168 if (CurRec
&& !CurRec
->isClass() && !CurMultiClass
&&
1169 CurRec
->getNameInit() == Name
)
1170 return UnOpInit::get(UnOpInit::CAST
, Name
, CurRec
->getType());
1172 Error(NameLoc
.Start
, "Variable not defined: '" + Name
->getValue() + "'");
1176 /// ParseOperation - Parse an operator. This returns null on error.
1178 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
1180 Init
*TGParser::ParseOperation(Record
*CurRec
, RecTy
*ItemType
) {
1181 switch (Lex
.getCode()) {
1183 TokError("unknown bang operator");
1186 case tgtok::XToLower
:
1187 case tgtok::XToUpper
:
1195 case tgtok::XGetDagOp
: { // Value ::= !unop '(' Value ')'
1196 UnOpInit::UnaryOp Code
;
1197 RecTy
*Type
= nullptr;
1199 switch (Lex
.getCode()) {
1200 default: llvm_unreachable("Unhandled code!");
1202 Lex
.Lex(); // eat the operation
1203 Code
= UnOpInit::CAST
;
1205 Type
= ParseOperatorType();
1208 TokError("did not get type for unary operator");
1214 Lex
.Lex(); // eat the operation
1215 Code
= UnOpInit::REPR
;
1216 Type
= StringRecTy::get(Records
);
1218 case tgtok::XToLower
:
1219 Lex
.Lex(); // eat the operation
1220 Code
= UnOpInit::TOLOWER
;
1221 Type
= StringRecTy::get(Records
);
1223 case tgtok::XToUpper
:
1224 Lex
.Lex(); // eat the operation
1225 Code
= UnOpInit::TOUPPER
;
1226 Type
= StringRecTy::get(Records
);
1229 Lex
.Lex(); // eat the operation
1230 Code
= UnOpInit::NOT
;
1231 Type
= IntRecTy::get(Records
);
1234 Lex
.Lex(); // eat the operation
1235 Code
= UnOpInit::LOG2
;
1236 Type
= IntRecTy::get(Records
);
1239 Lex
.Lex(); // eat the operation
1240 Code
= UnOpInit::HEAD
;
1243 Lex
.Lex(); // eat the operation
1244 Code
= UnOpInit::TAIL
;
1248 Code
= UnOpInit::SIZE
;
1249 Type
= IntRecTy::get(Records
);
1252 Lex
.Lex(); // eat the operation
1253 Code
= UnOpInit::EMPTY
;
1254 Type
= IntRecTy::get(Records
);
1256 case tgtok::XGetDagOp
:
1257 Lex
.Lex(); // eat the operation
1258 if (Lex
.getCode() == tgtok::less
) {
1259 // Parse an optional type suffix, so that you can say
1260 // !getdagop<BaseClass>(someDag) as a shorthand for
1261 // !cast<BaseClass>(!getdagop(someDag)).
1262 Type
= ParseOperatorType();
1265 TokError("did not get type for unary operator");
1269 if (!isa
<RecordRecTy
>(Type
)) {
1270 TokError("type for !getdagop must be a record type");
1271 // but keep parsing, to consume the operand
1274 Type
= RecordRecTy::get(Records
, {});
1276 Code
= UnOpInit::GETDAGOP
;
1279 if (!consume(tgtok::l_paren
)) {
1280 TokError("expected '(' after unary operator");
1284 Init
*LHS
= ParseValue(CurRec
);
1285 if (!LHS
) return nullptr;
1287 if (Code
== UnOpInit::EMPTY
|| Code
== UnOpInit::SIZE
) {
1288 ListInit
*LHSl
= dyn_cast
<ListInit
>(LHS
);
1289 StringInit
*LHSs
= dyn_cast
<StringInit
>(LHS
);
1290 DagInit
*LHSd
= dyn_cast
<DagInit
>(LHS
);
1291 TypedInit
*LHSt
= dyn_cast
<TypedInit
>(LHS
);
1292 if (!LHSl
&& !LHSs
&& !LHSd
&& !LHSt
) {
1293 TokError("expected string, list, or dag type argument in unary operator");
1297 ListRecTy
*LType
= dyn_cast
<ListRecTy
>(LHSt
->getType());
1298 StringRecTy
*SType
= dyn_cast
<StringRecTy
>(LHSt
->getType());
1299 DagRecTy
*DType
= dyn_cast
<DagRecTy
>(LHSt
->getType());
1300 if (!LType
&& !SType
&& !DType
) {
1301 TokError("expected string, list, or dag type argument in unary operator");
1307 if (Code
== UnOpInit::HEAD
|| Code
== UnOpInit::TAIL
) {
1308 ListInit
*LHSl
= dyn_cast
<ListInit
>(LHS
);
1309 TypedInit
*LHSt
= dyn_cast
<TypedInit
>(LHS
);
1310 if (!LHSl
&& !LHSt
) {
1311 TokError("expected list type argument in unary operator");
1315 ListRecTy
*LType
= dyn_cast
<ListRecTy
>(LHSt
->getType());
1317 TokError("expected list type argument in unary operator");
1322 if (LHSl
&& LHSl
->empty()) {
1323 TokError("empty list argument in unary operator");
1327 Init
*Item
= LHSl
->getElement(0);
1328 TypedInit
*Itemt
= dyn_cast
<TypedInit
>(Item
);
1330 TokError("untyped list element in unary operator");
1333 Type
= (Code
== UnOpInit::HEAD
) ? Itemt
->getType()
1334 : ListRecTy::get(Itemt
->getType());
1336 assert(LHSt
&& "expected list type argument in unary operator");
1337 ListRecTy
*LType
= dyn_cast
<ListRecTy
>(LHSt
->getType());
1338 Type
= (Code
== UnOpInit::HEAD
) ? LType
->getElementType() : LType
;
1342 if (!consume(tgtok::r_paren
)) {
1343 TokError("expected ')' in unary operator");
1346 return (UnOpInit::get(Code
, LHS
, Type
))->Fold(CurRec
);
1350 // Value ::= !isa '<' Type '>' '(' Value ')'
1351 Lex
.Lex(); // eat the operation
1353 RecTy
*Type
= ParseOperatorType();
1357 if (!consume(tgtok::l_paren
)) {
1358 TokError("expected '(' after type of !isa");
1362 Init
*LHS
= ParseValue(CurRec
);
1366 if (!consume(tgtok::r_paren
)) {
1367 TokError("expected ')' in !isa");
1371 return (IsAOpInit::get(Type
, LHS
))->Fold();
1374 case tgtok::XExists
: {
1375 // Value ::= !exists '<' Type '>' '(' Value ')'
1376 Lex
.Lex(); // eat the operation
1378 RecTy
*Type
= ParseOperatorType();
1382 if (!consume(tgtok::l_paren
)) {
1383 TokError("expected '(' after type of !exists");
1387 SMLoc ExprLoc
= Lex
.getLoc();
1388 Init
*Expr
= ParseValue(CurRec
);
1392 TypedInit
*ExprType
= dyn_cast
<TypedInit
>(Expr
);
1394 Error(ExprLoc
, "expected string type argument in !exists operator");
1398 RecordRecTy
*RecType
= dyn_cast
<RecordRecTy
>(ExprType
->getType());
1401 "expected string type argument in !exists operator, please "
1402 "use !isa instead");
1406 StringRecTy
*SType
= dyn_cast
<StringRecTy
>(ExprType
->getType());
1408 Error(ExprLoc
, "expected string type argument in !exists operator");
1412 if (!consume(tgtok::r_paren
)) {
1413 TokError("expected ')' in !exists");
1417 return (ExistsOpInit::get(Type
, Expr
))->Fold(CurRec
);
1420 case tgtok::XConcat
:
1437 case tgtok::XListConcat
:
1438 case tgtok::XListSplat
:
1439 case tgtok::XListRemove
:
1440 case tgtok::XStrConcat
:
1441 case tgtok::XInterleave
:
1442 case tgtok::XGetDagArg
:
1443 case tgtok::XGetDagName
:
1444 case tgtok::XSetDagOp
: { // Value ::= !binop '(' Value ',' Value ')'
1445 tgtok::TokKind OpTok
= Lex
.getCode();
1446 SMLoc OpLoc
= Lex
.getLoc();
1447 Lex
.Lex(); // eat the operation
1449 BinOpInit::BinaryOp Code
;
1451 default: llvm_unreachable("Unhandled code!");
1452 case tgtok::XConcat
: Code
= BinOpInit::CONCAT
; break;
1453 case tgtok::XADD
: Code
= BinOpInit::ADD
; break;
1454 case tgtok::XSUB
: Code
= BinOpInit::SUB
; break;
1455 case tgtok::XMUL
: Code
= BinOpInit::MUL
; break;
1456 case tgtok::XDIV
: Code
= BinOpInit::DIV
; break;
1457 case tgtok::XAND
: Code
= BinOpInit::AND
; break;
1458 case tgtok::XOR
: Code
= BinOpInit::OR
; break;
1459 case tgtok::XXOR
: Code
= BinOpInit::XOR
; break;
1460 case tgtok::XSRA
: Code
= BinOpInit::SRA
; break;
1461 case tgtok::XSRL
: Code
= BinOpInit::SRL
; break;
1462 case tgtok::XSHL
: Code
= BinOpInit::SHL
; break;
1463 case tgtok::XEq
: Code
= BinOpInit::EQ
; break;
1464 case tgtok::XNe
: Code
= BinOpInit::NE
; break;
1465 case tgtok::XLe
: Code
= BinOpInit::LE
; break;
1466 case tgtok::XLt
: Code
= BinOpInit::LT
; break;
1467 case tgtok::XGe
: Code
= BinOpInit::GE
; break;
1468 case tgtok::XGt
: Code
= BinOpInit::GT
; break;
1469 case tgtok::XListConcat
: Code
= BinOpInit::LISTCONCAT
; break;
1470 case tgtok::XListSplat
: Code
= BinOpInit::LISTSPLAT
; break;
1471 case tgtok::XListRemove
:
1472 Code
= BinOpInit::LISTREMOVE
;
1474 case tgtok::XStrConcat
: Code
= BinOpInit::STRCONCAT
; break;
1475 case tgtok::XInterleave
: Code
= BinOpInit::INTERLEAVE
; break;
1476 case tgtok::XSetDagOp
: Code
= BinOpInit::SETDAGOP
; break;
1477 case tgtok::XGetDagArg
:
1478 Code
= BinOpInit::GETDAGARG
;
1480 case tgtok::XGetDagName
:
1481 Code
= BinOpInit::GETDAGNAME
;
1485 RecTy
*Type
= nullptr;
1486 RecTy
*ArgType
= nullptr;
1489 llvm_unreachable("Unhandled code!");
1490 case tgtok::XConcat
:
1491 case tgtok::XSetDagOp
:
1492 Type
= DagRecTy::get(Records
);
1493 ArgType
= DagRecTy::get(Records
);
1495 case tgtok::XGetDagArg
:
1496 Type
= ParseOperatorType();
1498 TokError("did not get type for !getdagarg operator");
1501 ArgType
= DagRecTy::get(Records
);
1503 case tgtok::XGetDagName
:
1504 Type
= StringRecTy::get(Records
);
1505 ArgType
= DagRecTy::get(Records
);
1517 Type
= IntRecTy::get(Records
);
1518 ArgType
= IntRecTy::get(Records
);
1526 Type
= BitRecTy::get(Records
);
1527 // ArgType for the comparison operators is not yet known.
1529 case tgtok::XListConcat
:
1530 // We don't know the list type until we parse the first argument.
1533 case tgtok::XListSplat
:
1534 // Can't do any typechecking until we parse the first argument.
1536 case tgtok::XListRemove
:
1537 // We don't know the list type until we parse the first argument.
1540 case tgtok::XStrConcat
:
1541 Type
= StringRecTy::get(Records
);
1542 ArgType
= StringRecTy::get(Records
);
1544 case tgtok::XInterleave
:
1545 Type
= StringRecTy::get(Records
);
1546 // The first argument type is not yet known.
1549 if (Type
&& ItemType
&& !Type
->typeIsConvertibleTo(ItemType
)) {
1550 Error(OpLoc
, Twine("expected value of type '") +
1551 ItemType
->getAsString() + "', got '" +
1552 Type
->getAsString() + "'");
1556 if (!consume(tgtok::l_paren
)) {
1557 TokError("expected '(' after binary operator");
1561 SmallVector
<Init
*, 2> InitList
;
1563 // Note that this loop consumes an arbitrary number of arguments.
1564 // The actual count is checked later.
1566 SMLoc InitLoc
= Lex
.getLoc();
1567 InitList
.push_back(ParseValue(CurRec
, ArgType
));
1568 if (!InitList
.back()) return nullptr;
1570 TypedInit
*InitListBack
= dyn_cast
<TypedInit
>(InitList
.back());
1571 if (!InitListBack
) {
1572 Error(OpLoc
, Twine("expected value to be a typed value, got '" +
1573 InitList
.back()->getAsString() + "'"));
1576 RecTy
*ListType
= InitListBack
->getType();
1579 // Argument type must be determined from the argument itself.
1583 case BinOpInit::LISTCONCAT
:
1584 if (!isa
<ListRecTy
>(ArgType
)) {
1585 Error(InitLoc
, Twine("expected a list, got value of type '") +
1586 ArgType
->getAsString() + "'");
1590 case BinOpInit::LISTSPLAT
:
1591 if (ItemType
&& InitList
.size() == 1) {
1592 if (!isa
<ListRecTy
>(ItemType
)) {
1594 Twine("expected output type to be a list, got type '") +
1595 ItemType
->getAsString() + "'");
1598 if (!ArgType
->getListTy()->typeIsConvertibleTo(ItemType
)) {
1599 Error(OpLoc
, Twine("expected first arg type to be '") +
1600 ArgType
->getAsString() +
1601 "', got value of type '" +
1602 cast
<ListRecTy
>(ItemType
)
1609 if (InitList
.size() == 2 && !isa
<IntRecTy
>(ArgType
)) {
1610 Error(InitLoc
, Twine("expected second parameter to be an int, got "
1611 "value of type '") +
1612 ArgType
->getAsString() + "'");
1615 ArgType
= nullptr; // Broken invariant: types not identical.
1617 case BinOpInit::LISTREMOVE
:
1618 if (!isa
<ListRecTy
>(ArgType
)) {
1619 Error(InitLoc
, Twine("expected a list, got value of type '") +
1620 ArgType
->getAsString() + "'");
1626 if (!ArgType
->typeIsConvertibleTo(IntRecTy::get(Records
)) &&
1627 !ArgType
->typeIsConvertibleTo(StringRecTy::get(Records
)) &&
1628 !ArgType
->typeIsConvertibleTo(RecordRecTy::get(Records
, {}))) {
1629 Error(InitLoc
, Twine("expected bit, bits, int, string, or record; "
1630 "got value of type '") + ArgType
->getAsString() +
1635 case BinOpInit::GETDAGARG
: // The 2nd argument of !getdagarg could be
1641 if (!ArgType
->typeIsConvertibleTo(IntRecTy::get(Records
)) &&
1642 !ArgType
->typeIsConvertibleTo(StringRecTy::get(Records
))) {
1643 Error(InitLoc
, Twine("expected bit, bits, int, or string; "
1644 "got value of type '") + ArgType
->getAsString() +
1649 case BinOpInit::INTERLEAVE
:
1650 switch (InitList
.size()) {
1651 case 1: // First argument must be a list of strings or integers.
1652 if (ArgType
!= StringRecTy::get(Records
)->getListTy() &&
1653 !ArgType
->typeIsConvertibleTo(
1654 IntRecTy::get(Records
)->getListTy())) {
1655 Error(InitLoc
, Twine("expected list of string, int, bits, or bit; "
1656 "got value of type '") +
1657 ArgType
->getAsString() + "'");
1661 case 2: // Second argument must be a string.
1662 if (!isa
<StringRecTy
>(ArgType
)) {
1663 Error(InitLoc
, Twine("expected second argument to be a string, "
1664 "got value of type '") +
1665 ArgType
->getAsString() + "'");
1671 ArgType
= nullptr; // Broken invariant: types not identical.
1673 default: llvm_unreachable("other ops have fixed argument types");
1677 // Desired argument type is a known and in ArgType.
1678 RecTy
*Resolved
= resolveTypes(ArgType
, ListType
);
1680 Error(InitLoc
, Twine("expected value of type '") +
1681 ArgType
->getAsString() + "', got '" +
1682 ListType
->getAsString() + "'");
1685 if (Code
!= BinOpInit::ADD
&& Code
!= BinOpInit::SUB
&&
1686 Code
!= BinOpInit::AND
&& Code
!= BinOpInit::OR
&&
1687 Code
!= BinOpInit::XOR
&& Code
!= BinOpInit::SRA
&&
1688 Code
!= BinOpInit::SRL
&& Code
!= BinOpInit::SHL
&&
1689 Code
!= BinOpInit::MUL
&& Code
!= BinOpInit::DIV
)
1693 // Deal with BinOps whose arguments have different types, by
1694 // rewriting ArgType in between them.
1696 case BinOpInit::SETDAGOP
:
1697 // After parsing the first dag argument, switch to expecting
1698 // a record, with no restriction on its superclasses.
1699 ArgType
= RecordRecTy::get(Records
, {});
1701 case BinOpInit::GETDAGARG
:
1702 // After parsing the first dag argument, expect an index integer or a
1706 case BinOpInit::GETDAGNAME
:
1707 // After parsing the first dag argument, expect an index integer.
1708 ArgType
= IntRecTy::get(Records
);
1714 if (!consume(tgtok::comma
))
1718 if (!consume(tgtok::r_paren
)) {
1719 TokError("expected ')' in operator");
1723 // listconcat returns a list with type of the argument.
1724 if (Code
== BinOpInit::LISTCONCAT
)
1726 // listsplat returns a list of type of the *first* argument.
1727 if (Code
== BinOpInit::LISTSPLAT
)
1728 Type
= cast
<TypedInit
>(InitList
.front())->getType()->getListTy();
1729 // listremove returns a list with type of the argument.
1730 if (Code
== BinOpInit::LISTREMOVE
)
1733 // We allow multiple operands to associative operators like !strconcat as
1734 // shorthand for nesting them.
1735 if (Code
== BinOpInit::STRCONCAT
|| Code
== BinOpInit::LISTCONCAT
||
1736 Code
== BinOpInit::CONCAT
|| Code
== BinOpInit::ADD
||
1737 Code
== BinOpInit::AND
|| Code
== BinOpInit::OR
||
1738 Code
== BinOpInit::XOR
|| Code
== BinOpInit::MUL
) {
1739 while (InitList
.size() > 2) {
1740 Init
*RHS
= InitList
.pop_back_val();
1741 RHS
= (BinOpInit::get(Code
, InitList
.back(), RHS
, Type
))->Fold(CurRec
);
1742 InitList
.back() = RHS
;
1746 if (InitList
.size() == 2)
1747 return (BinOpInit::get(Code
, InitList
[0], InitList
[1], Type
))
1750 Error(OpLoc
, "expected two operands to operator");
1754 case tgtok::XForEach
:
1755 case tgtok::XFilter
: {
1756 return ParseOperationForEachFilter(CurRec
, ItemType
);
1759 case tgtok::XRange
: {
1760 SMLoc OpLoc
= Lex
.getLoc();
1761 Lex
.Lex(); // eat the operation
1763 if (!consume(tgtok::l_paren
)) {
1764 TokError("expected '(' after !range operator");
1768 SmallVector
<Init
*, 2> Args
;
1769 bool FirstArgIsList
= false;
1771 if (Args
.size() >= 3) {
1772 TokError("expected at most three values of integer");
1776 SMLoc InitLoc
= Lex
.getLoc();
1777 Args
.push_back(ParseValue(CurRec
));
1781 TypedInit
*ArgBack
= dyn_cast
<TypedInit
>(Args
.back());
1783 Error(OpLoc
, Twine("expected value to be a typed value, got '" +
1784 Args
.back()->getAsString() + "'"));
1788 RecTy
*ArgBackType
= ArgBack
->getType();
1789 if (!FirstArgIsList
|| Args
.size() == 1) {
1790 if (Args
.size() == 1 && isa
<ListRecTy
>(ArgBackType
)) {
1791 FirstArgIsList
= true; // Detect error if 2nd arg were present.
1792 } else if (isa
<IntRecTy
>(ArgBackType
)) {
1793 // Assume 2nd arg should be IntRecTy
1795 if (Args
.size() != 1)
1796 Error(InitLoc
, Twine("expected value of type 'int', got '" +
1797 ArgBackType
->getAsString() + "'"));
1799 Error(InitLoc
, Twine("expected list or int, got value of type '") +
1800 ArgBackType
->getAsString() + "'");
1804 // Don't come here unless 1st arg is ListRecTy.
1805 assert(isa
<ListRecTy
>(cast
<TypedInit
>(Args
[0])->getType()));
1806 Error(InitLoc
, Twine("expected one list, got extra value of type '") +
1807 ArgBackType
->getAsString() + "'");
1810 if (!consume(tgtok::comma
))
1814 if (!consume(tgtok::r_paren
)) {
1815 TokError("expected ')' in operator");
1819 Init
*LHS
, *MHS
, *RHS
;
1820 auto ArgCount
= Args
.size();
1821 assert(ArgCount
>= 1);
1822 auto *Arg0
= cast
<TypedInit
>(Args
[0]);
1823 auto *Arg0Ty
= Arg0
->getType();
1824 if (ArgCount
== 1) {
1825 if (isa
<ListRecTy
>(Arg0Ty
)) {
1826 // (0, !size(arg), 1)
1827 LHS
= IntInit::get(Records
, 0);
1828 MHS
= UnOpInit::get(UnOpInit::SIZE
, Arg0
, IntRecTy::get(Records
))
1830 RHS
= IntInit::get(Records
, 1);
1832 assert(isa
<IntRecTy
>(Arg0Ty
));
1834 LHS
= IntInit::get(Records
, 0);
1836 RHS
= IntInit::get(Records
, 1);
1839 assert(isa
<IntRecTy
>(Arg0Ty
));
1840 auto *Arg1
= cast
<TypedInit
>(Args
[1]);
1841 assert(isa
<IntRecTy
>(Arg1
->getType()));
1844 if (ArgCount
== 3) {
1845 // (start, end, step)
1846 auto *Arg2
= cast
<TypedInit
>(Args
[2]);
1847 assert(isa
<IntRecTy
>(Arg2
->getType()));
1851 RHS
= IntInit::get(Records
, 1);
1853 return TernOpInit::get(TernOpInit::RANGE
, LHS
, MHS
, RHS
,
1854 IntRecTy::get(Records
)->getListTy())
1858 case tgtok::XSetDagArg
:
1859 case tgtok::XSetDagName
:
1862 case tgtok::XSubst
: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1863 TernOpInit::TernaryOp Code
;
1864 RecTy
*Type
= nullptr;
1866 tgtok::TokKind LexCode
= Lex
.getCode();
1867 Lex
.Lex(); // eat the operation
1869 default: llvm_unreachable("Unhandled code!");
1871 Code
= TernOpInit::DAG
;
1872 Type
= DagRecTy::get(Records
);
1876 Code
= TernOpInit::IF
;
1879 Code
= TernOpInit::SUBST
;
1881 case tgtok::XSetDagArg
:
1882 Code
= TernOpInit::SETDAGARG
;
1883 Type
= DagRecTy::get(Records
);
1886 case tgtok::XSetDagName
:
1887 Code
= TernOpInit::SETDAGNAME
;
1888 Type
= DagRecTy::get(Records
);
1892 if (!consume(tgtok::l_paren
)) {
1893 TokError("expected '(' after ternary operator");
1897 Init
*LHS
= ParseValue(CurRec
);
1898 if (!LHS
) return nullptr;
1900 if (!consume(tgtok::comma
)) {
1901 TokError("expected ',' in ternary operator");
1905 SMLoc MHSLoc
= Lex
.getLoc();
1906 Init
*MHS
= ParseValue(CurRec
, ItemType
);
1910 if (!consume(tgtok::comma
)) {
1911 TokError("expected ',' in ternary operator");
1915 SMLoc RHSLoc
= Lex
.getLoc();
1916 Init
*RHS
= ParseValue(CurRec
, ItemType
);
1920 if (!consume(tgtok::r_paren
)) {
1921 TokError("expected ')' in binary operator");
1926 default: llvm_unreachable("Unhandled code!");
1928 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
1929 if (!MHSt
&& !isa
<UnsetInit
>(MHS
)) {
1930 Error(MHSLoc
, "could not determine type of the child list in !dag");
1933 if (MHSt
&& !isa
<ListRecTy
>(MHSt
->getType())) {
1934 Error(MHSLoc
, Twine("expected list of children, got type '") +
1935 MHSt
->getType()->getAsString() + "'");
1939 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
1940 if (!RHSt
&& !isa
<UnsetInit
>(RHS
)) {
1941 Error(RHSLoc
, "could not determine type of the name list in !dag");
1944 if (RHSt
&& StringRecTy::get(Records
)->getListTy() != RHSt
->getType()) {
1945 Error(RHSLoc
, Twine("expected list<string>, got type '") +
1946 RHSt
->getType()->getAsString() + "'");
1950 if (!MHSt
&& !RHSt
) {
1952 "cannot have both unset children and unset names in !dag");
1958 RecTy
*MHSTy
= nullptr;
1959 RecTy
*RHSTy
= nullptr;
1961 if (TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
))
1962 MHSTy
= MHSt
->getType();
1963 if (BitsInit
*MHSbits
= dyn_cast
<BitsInit
>(MHS
))
1964 MHSTy
= BitsRecTy::get(Records
, MHSbits
->getNumBits());
1965 if (isa
<BitInit
>(MHS
))
1966 MHSTy
= BitRecTy::get(Records
);
1968 if (TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
))
1969 RHSTy
= RHSt
->getType();
1970 if (BitsInit
*RHSbits
= dyn_cast
<BitsInit
>(RHS
))
1971 RHSTy
= BitsRecTy::get(Records
, RHSbits
->getNumBits());
1972 if (isa
<BitInit
>(RHS
))
1973 RHSTy
= BitRecTy::get(Records
);
1975 // For UnsetInit, it's typed from the other hand.
1976 if (isa
<UnsetInit
>(MHS
))
1978 if (isa
<UnsetInit
>(RHS
))
1981 if (!MHSTy
|| !RHSTy
) {
1982 TokError("could not get type for !if");
1986 Type
= resolveTypes(MHSTy
, RHSTy
);
1988 TokError(Twine("inconsistent types '") + MHSTy
->getAsString() +
1989 "' and '" + RHSTy
->getAsString() + "' for !if");
1994 case tgtok::XSubst
: {
1995 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
1997 TokError("could not get type for !subst");
2000 Type
= RHSt
->getType();
2003 case tgtok::XSetDagArg
: {
2004 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
2005 if (!MHSt
|| !isa
<IntRecTy
, StringRecTy
>(MHSt
->getType())) {
2006 Error(MHSLoc
, Twine("expected integer index or string name, got ") +
2007 (MHSt
? ("type '" + MHSt
->getType()->getAsString())
2008 : ("'" + MHS
->getAsString())) +
2014 case tgtok::XSetDagName
: {
2015 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
2016 if (!MHSt
|| !isa
<IntRecTy
, StringRecTy
>(MHSt
->getType())) {
2017 Error(MHSLoc
, Twine("expected integer index or string name, got ") +
2018 (MHSt
? ("type '" + MHSt
->getType()->getAsString())
2019 : ("'" + MHS
->getAsString())) +
2023 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
2024 // The name could be a string or unset.
2025 if (RHSt
&& !isa
<StringRecTy
>(RHSt
->getType())) {
2026 Error(RHSLoc
, Twine("expected string or unset name, got type '") +
2027 RHSt
->getType()->getAsString() + "'");
2033 return (TernOpInit::get(Code
, LHS
, MHS
, RHS
, Type
))->Fold(CurRec
);
2036 case tgtok::XSubstr
:
2037 return ParseOperationSubstr(CurRec
, ItemType
);
2040 return ParseOperationFind(CurRec
, ItemType
);
2043 return ParseOperationCond(CurRec
, ItemType
);
2045 case tgtok::XFoldl
: {
2046 // Value ::= !foldl '(' Value ',' Value ',' Id ',' Id ',' Expr ')'
2047 Lex
.Lex(); // eat the operation
2048 if (!consume(tgtok::l_paren
)) {
2049 TokError("expected '(' after !foldl");
2053 Init
*StartUntyped
= ParseValue(CurRec
);
2057 TypedInit
*Start
= dyn_cast
<TypedInit
>(StartUntyped
);
2059 TokError(Twine("could not get type of !foldl start: '") +
2060 StartUntyped
->getAsString() + "'");
2064 if (!consume(tgtok::comma
)) {
2065 TokError("expected ',' in !foldl");
2069 Init
*ListUntyped
= ParseValue(CurRec
);
2073 TypedInit
*List
= dyn_cast
<TypedInit
>(ListUntyped
);
2075 TokError(Twine("could not get type of !foldl list: '") +
2076 ListUntyped
->getAsString() + "'");
2080 ListRecTy
*ListType
= dyn_cast
<ListRecTy
>(List
->getType());
2082 TokError(Twine("!foldl list must be a list, but is of type '") +
2083 List
->getType()->getAsString());
2087 if (Lex
.getCode() != tgtok::comma
) {
2088 TokError("expected ',' in !foldl");
2092 if (Lex
.Lex() != tgtok::Id
) { // eat the ','
2093 TokError("third argument of !foldl must be an identifier");
2097 Init
*A
= StringInit::get(Records
, Lex
.getCurStrVal());
2098 if (CurRec
&& CurRec
->getValue(A
)) {
2099 TokError((Twine("left !foldl variable '") + A
->getAsString() +
2100 "' already defined")
2105 if (Lex
.Lex() != tgtok::comma
) { // eat the id
2106 TokError("expected ',' in !foldl");
2110 if (Lex
.Lex() != tgtok::Id
) { // eat the ','
2111 TokError("fourth argument of !foldl must be an identifier");
2115 Init
*B
= StringInit::get(Records
, Lex
.getCurStrVal());
2116 if (CurRec
&& CurRec
->getValue(B
)) {
2117 TokError((Twine("right !foldl variable '") + B
->getAsString() +
2118 "' already defined")
2123 if (Lex
.Lex() != tgtok::comma
) { // eat the id
2124 TokError("expected ',' in !foldl");
2127 Lex
.Lex(); // eat the ','
2129 // We need to create a temporary record to provide a scope for the
2131 std::unique_ptr
<Record
> ParseRecTmp
;
2132 Record
*ParseRec
= CurRec
;
2134 ParseRecTmp
= std::make_unique
<Record
>(".parse", ArrayRef
<SMLoc
>{}, Records
);
2135 ParseRec
= ParseRecTmp
.get();
2138 TGVarScope
*FoldScope
= PushScope(ParseRec
);
2139 ParseRec
->addValue(RecordVal(A
, Start
->getType(), RecordVal::FK_Normal
));
2141 RecordVal(B
, ListType
->getElementType(), RecordVal::FK_Normal
));
2142 Init
*ExprUntyped
= ParseValue(ParseRec
);
2143 ParseRec
->removeValue(A
);
2144 ParseRec
->removeValue(B
);
2145 PopScope(FoldScope
);
2149 TypedInit
*Expr
= dyn_cast
<TypedInit
>(ExprUntyped
);
2151 TokError("could not get type of !foldl expression");
2155 if (Expr
->getType() != Start
->getType()) {
2156 TokError(Twine("!foldl expression must be of same type as start (") +
2157 Start
->getType()->getAsString() + "), but is of type " +
2158 Expr
->getType()->getAsString());
2162 if (!consume(tgtok::r_paren
)) {
2163 TokError("expected ')' in fold operator");
2167 return FoldOpInit::get(Start
, List
, A
, B
, Expr
, Start
->getType())
2173 /// ParseOperatorType - Parse a type for an operator. This returns
2176 /// OperatorType ::= '<' Type '>'
2178 RecTy
*TGParser::ParseOperatorType() {
2179 RecTy
*Type
= nullptr;
2181 if (!consume(tgtok::less
)) {
2182 TokError("expected type name for operator");
2186 if (Lex
.getCode() == tgtok::Code
)
2187 TokError("the 'code' type is not allowed in bang operators; use 'string'");
2192 TokError("expected type name for operator");
2196 if (!consume(tgtok::greater
)) {
2197 TokError("expected type name for operator");
2204 /// Parse the !substr operation. Return null on error.
2206 /// Substr ::= !substr(string, start-int [, length-int]) => string
2207 Init
*TGParser::ParseOperationSubstr(Record
*CurRec
, RecTy
*ItemType
) {
2208 TernOpInit::TernaryOp Code
= TernOpInit::SUBSTR
;
2209 RecTy
*Type
= StringRecTy::get(Records
);
2211 Lex
.Lex(); // eat the operation
2213 if (!consume(tgtok::l_paren
)) {
2214 TokError("expected '(' after !substr operator");
2218 Init
*LHS
= ParseValue(CurRec
);
2222 if (!consume(tgtok::comma
)) {
2223 TokError("expected ',' in !substr operator");
2227 SMLoc MHSLoc
= Lex
.getLoc();
2228 Init
*MHS
= ParseValue(CurRec
);
2232 SMLoc RHSLoc
= Lex
.getLoc();
2234 if (consume(tgtok::comma
)) {
2235 RHSLoc
= Lex
.getLoc();
2236 RHS
= ParseValue(CurRec
);
2240 RHS
= IntInit::get(Records
, std::numeric_limits
<int64_t>::max());
2243 if (!consume(tgtok::r_paren
)) {
2244 TokError("expected ')' in !substr operator");
2248 if (ItemType
&& !Type
->typeIsConvertibleTo(ItemType
)) {
2249 Error(RHSLoc
, Twine("expected value of type '") +
2250 ItemType
->getAsString() + "', got '" +
2251 Type
->getAsString() + "'");
2254 TypedInit
*LHSt
= dyn_cast
<TypedInit
>(LHS
);
2255 if (!LHSt
&& !isa
<UnsetInit
>(LHS
)) {
2256 TokError("could not determine type of the string in !substr");
2259 if (LHSt
&& !isa
<StringRecTy
>(LHSt
->getType())) {
2260 TokError(Twine("expected string, got type '") +
2261 LHSt
->getType()->getAsString() + "'");
2265 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
2266 if (!MHSt
&& !isa
<UnsetInit
>(MHS
)) {
2267 TokError("could not determine type of the start position in !substr");
2270 if (MHSt
&& !isa
<IntRecTy
>(MHSt
->getType())) {
2271 Error(MHSLoc
, Twine("expected int, got type '") +
2272 MHSt
->getType()->getAsString() + "'");
2277 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
2278 if (!RHSt
&& !isa
<UnsetInit
>(RHS
)) {
2279 TokError("could not determine type of the length in !substr");
2282 if (RHSt
&& !isa
<IntRecTy
>(RHSt
->getType())) {
2283 TokError(Twine("expected int, got type '") +
2284 RHSt
->getType()->getAsString() + "'");
2289 return (TernOpInit::get(Code
, LHS
, MHS
, RHS
, Type
))->Fold(CurRec
);
2292 /// Parse the !find operation. Return null on error.
2294 /// Substr ::= !find(string, string [, start-int]) => int
2295 Init
*TGParser::ParseOperationFind(Record
*CurRec
, RecTy
*ItemType
) {
2296 TernOpInit::TernaryOp Code
= TernOpInit::FIND
;
2297 RecTy
*Type
= IntRecTy::get(Records
);
2299 Lex
.Lex(); // eat the operation
2301 if (!consume(tgtok::l_paren
)) {
2302 TokError("expected '(' after !find operator");
2306 Init
*LHS
= ParseValue(CurRec
);
2310 if (!consume(tgtok::comma
)) {
2311 TokError("expected ',' in !find operator");
2315 SMLoc MHSLoc
= Lex
.getLoc();
2316 Init
*MHS
= ParseValue(CurRec
);
2320 SMLoc RHSLoc
= Lex
.getLoc();
2322 if (consume(tgtok::comma
)) {
2323 RHSLoc
= Lex
.getLoc();
2324 RHS
= ParseValue(CurRec
);
2328 RHS
= IntInit::get(Records
, 0);
2331 if (!consume(tgtok::r_paren
)) {
2332 TokError("expected ')' in !find operator");
2336 if (ItemType
&& !Type
->typeIsConvertibleTo(ItemType
)) {
2337 Error(RHSLoc
, Twine("expected value of type '") +
2338 ItemType
->getAsString() + "', got '" +
2339 Type
->getAsString() + "'");
2342 TypedInit
*LHSt
= dyn_cast
<TypedInit
>(LHS
);
2343 if (!LHSt
&& !isa
<UnsetInit
>(LHS
)) {
2344 TokError("could not determine type of the source string in !find");
2347 if (LHSt
&& !isa
<StringRecTy
>(LHSt
->getType())) {
2348 TokError(Twine("expected string, got type '") +
2349 LHSt
->getType()->getAsString() + "'");
2353 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
2354 if (!MHSt
&& !isa
<UnsetInit
>(MHS
)) {
2355 TokError("could not determine type of the target string in !find");
2358 if (MHSt
&& !isa
<StringRecTy
>(MHSt
->getType())) {
2359 Error(MHSLoc
, Twine("expected string, got type '") +
2360 MHSt
->getType()->getAsString() + "'");
2365 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
2366 if (!RHSt
&& !isa
<UnsetInit
>(RHS
)) {
2367 TokError("could not determine type of the start position in !find");
2370 if (RHSt
&& !isa
<IntRecTy
>(RHSt
->getType())) {
2371 TokError(Twine("expected int, got type '") +
2372 RHSt
->getType()->getAsString() + "'");
2377 return (TernOpInit::get(Code
, LHS
, MHS
, RHS
, Type
))->Fold(CurRec
);
2380 /// Parse the !foreach and !filter operations. Return null on error.
2382 /// ForEach ::= !foreach(ID, list-or-dag, expr) => list<expr type>
2383 /// Filter ::= !foreach(ID, list, predicate) ==> list<list type>
2384 Init
*TGParser::ParseOperationForEachFilter(Record
*CurRec
, RecTy
*ItemType
) {
2385 SMLoc OpLoc
= Lex
.getLoc();
2386 tgtok::TokKind Operation
= Lex
.getCode();
2387 Lex
.Lex(); // eat the operation
2388 if (Lex
.getCode() != tgtok::l_paren
) {
2389 TokError("expected '(' after !foreach/!filter");
2393 if (Lex
.Lex() != tgtok::Id
) { // eat the '('
2394 TokError("first argument of !foreach/!filter must be an identifier");
2398 Init
*LHS
= StringInit::get(Records
, Lex
.getCurStrVal());
2399 Lex
.Lex(); // eat the ID.
2401 if (CurRec
&& CurRec
->getValue(LHS
)) {
2402 TokError((Twine("iteration variable '") + LHS
->getAsString() +
2403 "' is already defined")
2408 if (!consume(tgtok::comma
)) {
2409 TokError("expected ',' in !foreach/!filter");
2413 Init
*MHS
= ParseValue(CurRec
);
2417 if (!consume(tgtok::comma
)) {
2418 TokError("expected ',' in !foreach/!filter");
2422 TypedInit
*MHSt
= dyn_cast
<TypedInit
>(MHS
);
2424 TokError("could not get type of !foreach/!filter list or dag");
2428 RecTy
*InEltType
= nullptr;
2429 RecTy
*ExprEltType
= nullptr;
2432 if (ListRecTy
*InListTy
= dyn_cast
<ListRecTy
>(MHSt
->getType())) {
2433 InEltType
= InListTy
->getElementType();
2435 if (ListRecTy
*OutListTy
= dyn_cast
<ListRecTy
>(ItemType
)) {
2436 ExprEltType
= (Operation
== tgtok::XForEach
)
2437 ? OutListTy
->getElementType()
2438 : IntRecTy::get(Records
);
2441 "expected value of type '" +
2442 Twine(ItemType
->getAsString()) +
2443 "', but got list type");
2447 } else if (DagRecTy
*InDagTy
= dyn_cast
<DagRecTy
>(MHSt
->getType())) {
2448 if (Operation
== tgtok::XFilter
) {
2449 TokError("!filter must have a list argument");
2452 InEltType
= InDagTy
;
2453 if (ItemType
&& !isa
<DagRecTy
>(ItemType
)) {
2455 "expected value of type '" + Twine(ItemType
->getAsString()) +
2456 "', but got dag type");
2461 if (Operation
== tgtok::XForEach
)
2462 TokError("!foreach must have a list or dag argument");
2464 TokError("!filter must have a list argument");
2468 // We need to create a temporary record to provide a scope for the
2469 // iteration variable.
2470 std::unique_ptr
<Record
> ParseRecTmp
;
2471 Record
*ParseRec
= CurRec
;
2474 std::make_unique
<Record
>(".parse", ArrayRef
<SMLoc
>{}, Records
);
2475 ParseRec
= ParseRecTmp
.get();
2477 TGVarScope
*TempScope
= PushScope(ParseRec
);
2478 ParseRec
->addValue(RecordVal(LHS
, InEltType
, RecordVal::FK_Normal
));
2479 Init
*RHS
= ParseValue(ParseRec
, ExprEltType
);
2480 ParseRec
->removeValue(LHS
);
2481 PopScope(TempScope
);
2485 if (!consume(tgtok::r_paren
)) {
2486 TokError("expected ')' in !foreach/!filter");
2490 RecTy
*OutType
= InEltType
;
2491 if (Operation
== tgtok::XForEach
&& !IsDAG
) {
2492 TypedInit
*RHSt
= dyn_cast
<TypedInit
>(RHS
);
2494 TokError("could not get type of !foreach result expression");
2497 OutType
= RHSt
->getType()->getListTy();
2498 } else if (Operation
== tgtok::XFilter
) {
2499 OutType
= InEltType
->getListTy();
2502 return (TernOpInit::get((Operation
== tgtok::XForEach
) ? TernOpInit::FOREACH
2503 : TernOpInit::FILTER
,
2504 LHS
, MHS
, RHS
, OutType
))
2508 Init
*TGParser::ParseOperationCond(Record
*CurRec
, RecTy
*ItemType
) {
2509 Lex
.Lex(); // eat the operation 'cond'
2511 if (!consume(tgtok::l_paren
)) {
2512 TokError("expected '(' after !cond operator");
2516 // Parse through '[Case: Val,]+'
2517 SmallVector
<Init
*, 4> Case
;
2518 SmallVector
<Init
*, 4> Val
;
2520 if (consume(tgtok::r_paren
))
2523 Init
*V
= ParseValue(CurRec
);
2528 if (!consume(tgtok::colon
)) {
2529 TokError("expected ':' following a condition in !cond operator");
2533 V
= ParseValue(CurRec
, ItemType
);
2538 if (consume(tgtok::r_paren
))
2541 if (!consume(tgtok::comma
)) {
2542 TokError("expected ',' or ')' following a value in !cond operator");
2547 if (Case
.size() < 1) {
2548 TokError("there should be at least 1 'condition : value' in the !cond operator");
2553 RecTy
*Type
= nullptr;
2554 for (Init
*V
: Val
) {
2555 RecTy
*VTy
= nullptr;
2556 if (TypedInit
*Vt
= dyn_cast
<TypedInit
>(V
))
2557 VTy
= Vt
->getType();
2558 if (BitsInit
*Vbits
= dyn_cast
<BitsInit
>(V
))
2559 VTy
= BitsRecTy::get(Records
, Vbits
->getNumBits());
2560 if (isa
<BitInit
>(V
))
2561 VTy
= BitRecTy::get(Records
);
2563 if (Type
== nullptr) {
2564 if (!isa
<UnsetInit
>(V
))
2567 if (!isa
<UnsetInit
>(V
)) {
2568 RecTy
*RType
= resolveTypes(Type
, VTy
);
2570 TokError(Twine("inconsistent types '") + Type
->getAsString() +
2571 "' and '" + VTy
->getAsString() + "' for !cond");
2580 TokError("could not determine type for !cond from its arguments");
2583 return CondOpInit::get(Case
, Val
, Type
)->Fold(CurRec
);
2586 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
2588 /// SimpleValue ::= IDValue
2589 /// SimpleValue ::= INTVAL
2590 /// SimpleValue ::= STRVAL+
2591 /// SimpleValue ::= CODEFRAGMENT
2592 /// SimpleValue ::= '?'
2593 /// SimpleValue ::= '{' ValueList '}'
2594 /// SimpleValue ::= ID '<' ValueListNE '>'
2595 /// SimpleValue ::= '[' ValueList ']'
2596 /// SimpleValue ::= '(' IDValue DagArgList ')'
2597 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
2598 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
2599 /// SimpleValue ::= DIVTOK '(' Value ',' Value ')'
2600 /// SimpleValue ::= SUBTOK '(' Value ',' Value ')'
2601 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
2602 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
2603 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
2604 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
2605 /// SimpleValue ::= LISTSPLATTOK '(' Value ',' Value ')'
2606 /// SimpleValue ::= LISTREMOVETOK '(' Value ',' Value ')'
2607 /// SimpleValue ::= RANGE '(' Value ')'
2608 /// SimpleValue ::= RANGE '(' Value ',' Value ')'
2609 /// SimpleValue ::= RANGE '(' Value ',' Value ',' Value ')'
2610 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
2611 /// SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
2613 Init
*TGParser::ParseSimpleValue(Record
*CurRec
, RecTy
*ItemType
,
2616 tgtok::TokKind Code
= Lex
.getCode();
2618 // Parse bang operators.
2619 if (tgtok::isBangOperator(Code
))
2620 return ParseOperation(CurRec
, ItemType
);
2623 default: TokError("Unknown or reserved token when parsing a value"); break;
2625 case tgtok::TrueVal
:
2626 R
= IntInit::get(Records
, 1);
2629 case tgtok::FalseVal
:
2630 R
= IntInit::get(Records
, 0);
2634 R
= IntInit::get(Records
, Lex
.getCurIntVal());
2637 case tgtok::BinaryIntVal
: {
2638 auto BinaryVal
= Lex
.getCurBinaryIntVal();
2639 SmallVector
<Init
*, 16> Bits(BinaryVal
.second
);
2640 for (unsigned i
= 0, e
= BinaryVal
.second
; i
!= e
; ++i
)
2641 Bits
[i
] = BitInit::get(Records
, BinaryVal
.first
& (1LL << i
));
2642 R
= BitsInit::get(Records
, Bits
);
2646 case tgtok::StrVal
: {
2647 std::string Val
= Lex
.getCurStrVal();
2650 // Handle multiple consecutive concatenated strings.
2651 while (Lex
.getCode() == tgtok::StrVal
) {
2652 Val
+= Lex
.getCurStrVal();
2656 R
= StringInit::get(Records
, Val
);
2659 case tgtok::CodeFragment
:
2660 R
= StringInit::get(Records
, Lex
.getCurStrVal(), StringInit::SF_Code
);
2663 case tgtok::question
:
2664 R
= UnsetInit::get(Records
);
2668 SMRange NameLoc
= Lex
.getLocRange();
2669 StringInit
*Name
= StringInit::get(Records
, Lex
.getCurStrVal());
2670 tgtok::TokKind Next
= Lex
.Lex();
2671 if (Next
== tgtok::equal
) // Named argument.
2673 if (Next
!= tgtok::less
) // consume the Id.
2674 return ParseIDValue(CurRec
, Name
, NameLoc
, Mode
); // Value ::= IDValue
2676 // Value ::= CLASSID '<' ArgValueList '>' (CLASSID has been consumed)
2677 // This is supposed to synthesize a new anonymous definition, deriving
2678 // from the class with the template arguments, but no body.
2679 Record
*Class
= Records
.getClass(Name
->getValue());
2681 Error(NameLoc
.Start
,
2682 "Expected a class name, got '" + Name
->getValue() + "'");
2686 SmallVector
<ArgumentInit
*, 8> Args
;
2687 Lex
.Lex(); // consume the <
2688 if (ParseTemplateArgValueList(Args
, CurRec
, Class
))
2689 return nullptr; // Error parsing value list.
2691 if (CheckTemplateArgValues(Args
, NameLoc
.Start
, Class
))
2692 return nullptr; // Error checking template argument values.
2694 if (resolveArguments(Class
, Args
, NameLoc
.Start
))
2697 if (TrackReferenceLocs
)
2698 Class
->appendReferenceLoc(NameLoc
);
2699 return VarDefInit::get(Class
, Args
)->Fold();
2701 case tgtok::l_brace
: { // Value ::= '{' ValueList '}'
2702 SMLoc BraceLoc
= Lex
.getLoc();
2703 Lex
.Lex(); // eat the '{'
2704 SmallVector
<Init
*, 16> Vals
;
2706 if (Lex
.getCode() != tgtok::r_brace
) {
2707 ParseValueList(Vals
, CurRec
);
2708 if (Vals
.empty()) return nullptr;
2710 if (!consume(tgtok::r_brace
)) {
2711 TokError("expected '}' at end of bit list value");
2715 SmallVector
<Init
*, 16> NewBits
;
2717 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
2718 // first. We'll first read everything in to a vector, then we can reverse
2719 // it to get the bits in the correct order for the BitsInit value.
2720 for (unsigned i
= 0, e
= Vals
.size(); i
!= e
; ++i
) {
2721 // FIXME: The following two loops would not be duplicated
2722 // if the API was a little more orthogonal.
2724 // bits<n> values are allowed to initialize n bits.
2725 if (BitsInit
*BI
= dyn_cast
<BitsInit
>(Vals
[i
])) {
2726 for (unsigned i
= 0, e
= BI
->getNumBits(); i
!= e
; ++i
)
2727 NewBits
.push_back(BI
->getBit((e
- i
) - 1));
2730 // bits<n> can also come from variable initializers.
2731 if (VarInit
*VI
= dyn_cast
<VarInit
>(Vals
[i
])) {
2732 if (BitsRecTy
*BitsRec
= dyn_cast
<BitsRecTy
>(VI
->getType())) {
2733 for (unsigned i
= 0, e
= BitsRec
->getNumBits(); i
!= e
; ++i
)
2734 NewBits
.push_back(VI
->getBit((e
- i
) - 1));
2737 // Fallthrough to try convert this to a bit.
2739 // All other values must be convertible to just a single bit.
2740 Init
*Bit
= Vals
[i
]->getCastTo(BitRecTy::get(Records
));
2742 Error(BraceLoc
, "Element #" + Twine(i
) + " (" + Vals
[i
]->getAsString() +
2743 ") is not convertable to a bit");
2746 NewBits
.push_back(Bit
);
2748 std::reverse(NewBits
.begin(), NewBits
.end());
2749 return BitsInit::get(Records
, NewBits
);
2751 case tgtok::l_square
: { // Value ::= '[' ValueList ']'
2752 Lex
.Lex(); // eat the '['
2753 SmallVector
<Init
*, 16> Vals
;
2755 RecTy
*DeducedEltTy
= nullptr;
2756 ListRecTy
*GivenListTy
= nullptr;
2759 ListRecTy
*ListType
= dyn_cast
<ListRecTy
>(ItemType
);
2761 TokError(Twine("Encountered a list when expecting a ") +
2762 ItemType
->getAsString());
2765 GivenListTy
= ListType
;
2768 if (Lex
.getCode() != tgtok::r_square
) {
2769 ParseValueList(Vals
, CurRec
,
2770 GivenListTy
? GivenListTy
->getElementType() : nullptr);
2771 if (Vals
.empty()) return nullptr;
2773 if (!consume(tgtok::r_square
)) {
2774 TokError("expected ']' at end of list value");
2778 RecTy
*GivenEltTy
= nullptr;
2779 if (consume(tgtok::less
)) {
2780 // Optional list element type
2781 GivenEltTy
= ParseType();
2783 // Couldn't parse element type
2787 if (!consume(tgtok::greater
)) {
2788 TokError("expected '>' at end of list element type");
2794 RecTy
*EltTy
= nullptr;
2795 for (Init
*V
: Vals
) {
2796 TypedInit
*TArg
= dyn_cast
<TypedInit
>(V
);
2799 EltTy
= resolveTypes(EltTy
, TArg
->getType());
2801 TokError("Incompatible types in list elements");
2805 EltTy
= TArg
->getType();
2812 // Verify consistency
2813 if (!EltTy
->typeIsConvertibleTo(GivenEltTy
)) {
2814 TokError("Incompatible types in list elements");
2823 TokError("No type for list");
2826 DeducedEltTy
= GivenListTy
->getElementType();
2828 // Make sure the deduced type is compatible with the given type
2830 if (!EltTy
->typeIsConvertibleTo(GivenListTy
->getElementType())) {
2831 TokError(Twine("Element type mismatch for list: element type '") +
2832 EltTy
->getAsString() + "' not convertible to '" +
2833 GivenListTy
->getElementType()->getAsString());
2837 DeducedEltTy
= EltTy
;
2840 return ListInit::get(Vals
, DeducedEltTy
);
2842 case tgtok::l_paren
: { // Value ::= '(' IDValue DagArgList ')'
2843 Lex
.Lex(); // eat the '('
2844 if (Lex
.getCode() != tgtok::Id
&& Lex
.getCode() != tgtok::XCast
&&
2845 Lex
.getCode() != tgtok::question
&& Lex
.getCode() != tgtok::XGetDagOp
) {
2846 TokError("expected identifier in dag init");
2850 Init
*Operator
= ParseValue(CurRec
);
2851 if (!Operator
) return nullptr;
2853 // If the operator name is present, parse it.
2854 StringInit
*OperatorName
= nullptr;
2855 if (consume(tgtok::colon
)) {
2856 if (Lex
.getCode() != tgtok::VarName
) { // eat the ':'
2857 TokError("expected variable name in dag operator");
2860 OperatorName
= StringInit::get(Records
, Lex
.getCurStrVal());
2861 Lex
.Lex(); // eat the VarName.
2864 SmallVector
<std::pair
<llvm::Init
*, StringInit
*>, 8> DagArgs
;
2865 if (Lex
.getCode() != tgtok::r_paren
) {
2866 ParseDagArgList(DagArgs
, CurRec
);
2867 if (DagArgs
.empty()) return nullptr;
2870 if (!consume(tgtok::r_paren
)) {
2871 TokError("expected ')' in dag init");
2875 return DagInit::get(Operator
, OperatorName
, DagArgs
);
2882 /// ParseValue - Parse a TableGen value. This returns null on error.
2884 /// Value ::= SimpleValue ValueSuffix*
2885 /// ValueSuffix ::= '{' BitList '}'
2886 /// ValueSuffix ::= '[' SliceElements ']'
2887 /// ValueSuffix ::= '.' ID
2889 Init
*TGParser::ParseValue(Record
*CurRec
, RecTy
*ItemType
, IDParseMode Mode
) {
2890 SMLoc LHSLoc
= Lex
.getLoc();
2891 Init
*Result
= ParseSimpleValue(CurRec
, ItemType
, Mode
);
2892 if (!Result
) return nullptr;
2894 // Parse the suffixes now if present.
2896 switch (Lex
.getCode()) {
2897 default: return Result
;
2898 case tgtok::l_brace
: {
2899 if (Mode
== ParseNameMode
)
2900 // This is the beginning of the object body.
2903 SMLoc CurlyLoc
= Lex
.getLoc();
2904 Lex
.Lex(); // eat the '{'
2905 SmallVector
<unsigned, 16> Ranges
;
2906 ParseRangeList(Ranges
);
2907 if (Ranges
.empty()) return nullptr;
2909 // Reverse the bitlist.
2910 std::reverse(Ranges
.begin(), Ranges
.end());
2911 Result
= Result
->convertInitializerBitRange(Ranges
);
2913 Error(CurlyLoc
, "Invalid bit range for value");
2918 if (!consume(tgtok::r_brace
)) {
2919 TokError("expected '}' at end of bit range list");
2924 case tgtok::l_square
: {
2925 auto *LHS
= dyn_cast
<TypedInit
>(Result
);
2927 Error(LHSLoc
, "Invalid value, list expected");
2931 auto *LHSTy
= dyn_cast
<ListRecTy
>(LHS
->getType());
2933 Error(LHSLoc
, "Type '" + Twine(LHS
->getType()->getAsString()) +
2934 "' is invalid, list expected");
2938 Lex
.Lex(); // eat the '['
2939 TypedInit
*RHS
= ParseSliceElements(CurRec
, /*Single=*/true);
2943 if (isa
<ListRecTy
>(RHS
->getType())) {
2945 BinOpInit::get(BinOpInit::LISTSLICE
, LHS
, RHS
, LHSTy
)->Fold(CurRec
);
2947 Result
= BinOpInit::get(BinOpInit::LISTELEM
, LHS
, RHS
,
2948 LHSTy
->getElementType())
2955 if (!consume(tgtok::r_square
)) {
2956 TokError("expected ']' at end of list slice");
2962 if (Lex
.Lex() != tgtok::Id
) { // eat the .
2963 TokError("expected field identifier after '.'");
2966 SMRange FieldNameLoc
= Lex
.getLocRange();
2967 StringInit
*FieldName
= StringInit::get(Records
, Lex
.getCurStrVal());
2968 if (!Result
->getFieldType(FieldName
)) {
2969 TokError("Cannot access field '" + Lex
.getCurStrVal() + "' of value '" +
2970 Result
->getAsString() + "'");
2974 // Add a reference to this field if we know the record class.
2975 if (TrackReferenceLocs
) {
2976 if (auto *DI
= dyn_cast
<DefInit
>(Result
)) {
2977 DI
->getDef()->getValue(FieldName
)->addReferenceLoc(FieldNameLoc
);
2978 } else if (auto *TI
= dyn_cast
<TypedInit
>(Result
)) {
2979 if (auto *RecTy
= dyn_cast
<RecordRecTy
>(TI
->getType())) {
2980 for (Record
*R
: RecTy
->getClasses())
2981 if (auto *RV
= R
->getValue(FieldName
))
2982 RV
->addReferenceLoc(FieldNameLoc
);
2987 Result
= FieldInit::get(Result
, FieldName
)->Fold(CurRec
);
2988 Lex
.Lex(); // eat field name
2993 SMLoc PasteLoc
= Lex
.getLoc();
2994 TypedInit
*LHS
= dyn_cast
<TypedInit
>(Result
);
2996 Error(PasteLoc
, "LHS of paste is not typed!");
3000 // Check if it's a 'listA # listB'
3001 if (isa
<ListRecTy
>(LHS
->getType())) {
3002 Lex
.Lex(); // Eat the '#'.
3004 assert(Mode
== ParseValueMode
&& "encountered paste of lists in name");
3006 switch (Lex
.getCode()) {
3009 case tgtok::l_brace
:
3010 Result
= LHS
; // trailing paste, ignore.
3013 Init
*RHSResult
= ParseValue(CurRec
, ItemType
, ParseValueMode
);
3016 Result
= BinOpInit::getListConcat(LHS
, RHSResult
);
3022 // Create a !strconcat() operation, first casting each operand to
3023 // a string if necessary.
3024 if (LHS
->getType() != StringRecTy::get(Records
)) {
3025 auto CastLHS
= dyn_cast
<TypedInit
>(
3026 UnOpInit::get(UnOpInit::CAST
, LHS
, StringRecTy::get(Records
))
3030 Twine("can't cast '") + LHS
->getAsString() + "' to string");
3036 TypedInit
*RHS
= nullptr;
3038 Lex
.Lex(); // Eat the '#'.
3039 switch (Lex
.getCode()) {
3042 case tgtok::l_brace
:
3043 // These are all of the tokens that can begin an object body.
3044 // Some of these can also begin values but we disallow those cases
3045 // because they are unlikely to be useful.
3047 // Trailing paste, concat with an empty string.
3048 RHS
= StringInit::get(Records
, "");
3052 Init
*RHSResult
= ParseValue(CurRec
, nullptr, ParseNameMode
);
3055 RHS
= dyn_cast
<TypedInit
>(RHSResult
);
3057 Error(PasteLoc
, "RHS of paste is not typed!");
3061 if (RHS
->getType() != StringRecTy::get(Records
)) {
3062 auto CastRHS
= dyn_cast
<TypedInit
>(
3063 UnOpInit::get(UnOpInit::CAST
, RHS
, StringRecTy::get(Records
))
3067 Twine("can't cast '") + RHS
->getAsString() + "' to string");
3076 Result
= BinOpInit::getStrConcat(LHS
, RHS
);
3082 /// ParseDagArgList - Parse the argument list for a dag literal expression.
3084 /// DagArg ::= Value (':' VARNAME)?
3085 /// DagArg ::= VARNAME
3086 /// DagArgList ::= DagArg
3087 /// DagArgList ::= DagArgList ',' DagArg
3088 void TGParser::ParseDagArgList(
3089 SmallVectorImpl
<std::pair
<llvm::Init
*, StringInit
*>> &Result
,
3093 // DagArg ::= VARNAME
3094 if (Lex
.getCode() == tgtok::VarName
) {
3095 // A missing value is treated like '?'.
3096 StringInit
*VarName
= StringInit::get(Records
, Lex
.getCurStrVal());
3097 Result
.emplace_back(UnsetInit::get(Records
), VarName
);
3100 // DagArg ::= Value (':' VARNAME)?
3101 Init
*Val
= ParseValue(CurRec
);
3107 // If the variable name is present, add it.
3108 StringInit
*VarName
= nullptr;
3109 if (Lex
.getCode() == tgtok::colon
) {
3110 if (Lex
.Lex() != tgtok::VarName
) { // eat the ':'
3111 TokError("expected variable name in dag literal");
3115 VarName
= StringInit::get(Records
, Lex
.getCurStrVal());
3116 Lex
.Lex(); // eat the VarName.
3119 Result
.push_back(std::make_pair(Val
, VarName
));
3121 if (!consume(tgtok::comma
))
3126 /// ParseValueList - Parse a comma separated list of values, returning them
3127 /// in a vector. Note that this always expects to be able to parse at least one
3128 /// value. It returns an empty list if this is not possible.
3130 /// ValueList ::= Value (',' Value)
3132 void TGParser::ParseValueList(SmallVectorImpl
<Init
*> &Result
, Record
*CurRec
,
3135 Result
.push_back(ParseValue(CurRec
, ItemType
));
3136 if (!Result
.back()) {
3141 while (consume(tgtok::comma
)) {
3142 // ignore trailing comma for lists
3143 if (Lex
.getCode() == tgtok::r_square
)
3145 Result
.push_back(ParseValue(CurRec
, ItemType
));
3146 if (!Result
.back()) {
3153 // ParseTemplateArgValueList - Parse a template argument list with the syntax
3154 // shown, filling in the Result vector. The open angle has been consumed.
3155 // An empty argument list is allowed. Return false if okay, true if an
3156 // error was detected.
3158 // ArgValueList ::= '<' PostionalArgValueList [','] NamedArgValueList '>'
3159 // PostionalArgValueList ::= [Value {',' Value}*]
3160 // NamedArgValueList ::= [NameValue '=' Value {',' NameValue '=' Value}*]
3161 bool TGParser::ParseTemplateArgValueList(
3162 SmallVectorImpl
<ArgumentInit
*> &Result
, Record
*CurRec
, Record
*ArgsRec
) {
3163 assert(Result
.empty() && "Result vector is not empty");
3164 ArrayRef
<Init
*> TArgs
= ArgsRec
->getTemplateArgs();
3166 if (consume(tgtok::greater
)) // empty value list
3169 bool HasNamedArg
= false;
3170 unsigned ArgIndex
= 0;
3172 if (ArgIndex
>= TArgs
.size()) {
3173 TokError("Too many template arguments: " + utostr(ArgIndex
+ 1));
3177 SMLoc ValueLoc
= Lex
.getLoc();
3178 // If we are parsing named argument, we don't need to know the argument name
3179 // and argument type will be resolved after we know the name.
3180 Init
*Value
= ParseValue(
3182 HasNamedArg
? nullptr : ArgsRec
->getValue(TArgs
[ArgIndex
])->getType());
3186 // If we meet '=', then we are parsing named arguments.
3187 if (Lex
.getCode() == tgtok::equal
) {
3188 if (!isa
<StringInit
>(Value
))
3189 return Error(ValueLoc
,
3190 "The name of named argument should be a valid identifier");
3192 auto *Name
= cast
<StringInit
>(Value
);
3193 Init
*QualifiedName
= QualifyName(*ArgsRec
, Name
);
3194 auto *NamedArg
= ArgsRec
->getValue(QualifiedName
);
3196 return Error(ValueLoc
,
3197 "Argument " + Name
->getAsString() + " doesn't exist");
3199 Lex
.Lex(); // eat the '='.
3200 ValueLoc
= Lex
.getLoc();
3201 Value
= ParseValue(CurRec
, NamedArg
->getType());
3202 // Named value can't be uninitialized.
3203 if (isa
<UnsetInit
>(Value
))
3204 return Error(ValueLoc
,
3205 "The value of named argument should be initialized, "
3207 Value
->getAsString() + "'");
3209 Result
.push_back(ArgumentInit::get(Value
, QualifiedName
));
3212 // Positional arguments should be put before named arguments.
3214 return Error(ValueLoc
,
3215 "Positional argument should be put before named argument");
3217 Result
.push_back(ArgumentInit::get(Value
, ArgIndex
));
3220 if (consume(tgtok::greater
)) // end of argument list?
3222 if (!consume(tgtok::comma
))
3223 return TokError("Expected comma before next argument");
3228 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
3229 /// empty string on error. This can happen in a number of different contexts,
3230 /// including within a def or in the template args for a class (in which case
3231 /// CurRec will be non-null) and within the template args for a multiclass (in
3232 /// which case CurRec will be null, but CurMultiClass will be set). This can
3233 /// also happen within a def that is within a multiclass, which will set both
3234 /// CurRec and CurMultiClass.
3236 /// Declaration ::= FIELD? Type ID ('=' Value)?
3238 Init
*TGParser::ParseDeclaration(Record
*CurRec
,
3239 bool ParsingTemplateArgs
) {
3240 // Read the field prefix if present.
3241 bool HasField
= consume(tgtok::Field
);
3243 RecTy
*Type
= ParseType();
3244 if (!Type
) return nullptr;
3246 if (Lex
.getCode() != tgtok::Id
) {
3247 TokError("Expected identifier in declaration");
3251 std::string Str
= Lex
.getCurStrVal();
3252 if (Str
== "NAME") {
3253 TokError("'" + Str
+ "' is a reserved variable name");
3257 if (!ParsingTemplateArgs
&& CurScope
->varAlreadyDefined(Str
)) {
3258 TokError("local variable of this name already exists");
3262 SMLoc IdLoc
= Lex
.getLoc();
3263 Init
*DeclName
= StringInit::get(Records
, Str
);
3267 if (!ParsingTemplateArgs
) { // def, possibly in a multiclass
3268 BadField
= AddValue(CurRec
, IdLoc
,
3269 RecordVal(DeclName
, IdLoc
, Type
,
3270 HasField
? RecordVal::FK_NonconcreteOK
3271 : RecordVal::FK_Normal
));
3272 } else if (CurRec
) { // class template argument
3273 DeclName
= QualifyName(*CurRec
, DeclName
);
3275 AddValue(CurRec
, IdLoc
,
3276 RecordVal(DeclName
, IdLoc
, Type
, RecordVal::FK_TemplateArg
));
3277 } else { // multiclass template argument
3278 assert(CurMultiClass
&& "invalid context for template argument");
3279 DeclName
= QualifyName(CurMultiClass
, DeclName
);
3281 AddValue(CurRec
, IdLoc
,
3282 RecordVal(DeclName
, IdLoc
, Type
, RecordVal::FK_TemplateArg
));
3287 // If a value is present, parse it and set new field's value.
3288 if (consume(tgtok::equal
)) {
3289 SMLoc ValLoc
= Lex
.getLoc();
3290 Init
*Val
= ParseValue(CurRec
, Type
);
3292 SetValue(CurRec
, ValLoc
, DeclName
, std::nullopt
, Val
,
3293 /*AllowSelfAssignment=*/false, /*OverrideDefLoc=*/false)) {
3294 // Return the name, even if an error is thrown. This is so that we can
3295 // continue to make some progress, even without the value having been
3304 /// ParseForeachDeclaration - Read a foreach declaration, returning
3305 /// the name of the declared object or a NULL Init on error. Return
3306 /// the name of the parsed initializer list through ForeachListName.
3308 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
3309 /// ForeachDeclaration ::= ID '=' RangePiece
3310 /// ForeachDeclaration ::= ID '=' Value
3312 VarInit
*TGParser::ParseForeachDeclaration(Init
*&ForeachListValue
) {
3313 if (Lex
.getCode() != tgtok::Id
) {
3314 TokError("Expected identifier in foreach declaration");
3318 Init
*DeclName
= StringInit::get(Records
, Lex
.getCurStrVal());
3321 // If a value is present, parse it.
3322 if (!consume(tgtok::equal
)) {
3323 TokError("Expected '=' in foreach declaration");
3327 RecTy
*IterType
= nullptr;
3328 SmallVector
<unsigned, 16> Ranges
;
3330 switch (Lex
.getCode()) {
3331 case tgtok::l_brace
: { // '{' RangeList '}'
3332 Lex
.Lex(); // eat the '{'
3333 ParseRangeList(Ranges
);
3334 if (!consume(tgtok::r_brace
)) {
3335 TokError("expected '}' at end of bit range list");
3342 SMLoc ValueLoc
= Lex
.getLoc();
3343 Init
*I
= ParseValue(nullptr);
3347 TypedInit
*TI
= dyn_cast
<TypedInit
>(I
);
3348 if (TI
&& isa
<ListRecTy
>(TI
->getType())) {
3349 ForeachListValue
= I
;
3350 IterType
= cast
<ListRecTy
>(TI
->getType())->getElementType();
3355 if (ParseRangePiece(Ranges
, TI
))
3360 Error(ValueLoc
, "expected a list, got '" + I
->getAsString() + "'");
3361 if (CurMultiClass
) {
3362 PrintNote({}, "references to multiclass template arguments cannot be "
3363 "resolved at this time");
3370 if (!Ranges
.empty()) {
3371 assert(!IterType
&& "Type already initialized?");
3372 IterType
= IntRecTy::get(Records
);
3373 std::vector
<Init
*> Values
;
3374 for (unsigned R
: Ranges
)
3375 Values
.push_back(IntInit::get(Records
, R
));
3376 ForeachListValue
= ListInit::get(Values
, IterType
);
3382 return VarInit::get(DeclName
, IterType
);
3385 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
3386 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
3387 /// template args for a class. If null, these are the template args for a
3390 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
3392 bool TGParser::ParseTemplateArgList(Record
*CurRec
) {
3393 assert(Lex
.getCode() == tgtok::less
&& "Not a template arg list!");
3394 Lex
.Lex(); // eat the '<'
3396 Record
*TheRecToAddTo
= CurRec
? CurRec
: &CurMultiClass
->Rec
;
3398 // Read the first declaration.
3399 Init
*TemplArg
= ParseDeclaration(CurRec
, true/*templateargs*/);
3403 TheRecToAddTo
->addTemplateArg(TemplArg
);
3405 while (consume(tgtok::comma
)) {
3406 // Read the following declarations.
3407 SMLoc Loc
= Lex
.getLoc();
3408 TemplArg
= ParseDeclaration(CurRec
, true/*templateargs*/);
3412 if (TheRecToAddTo
->isTemplateArg(TemplArg
))
3413 return Error(Loc
, "template argument with the same name has already been "
3416 TheRecToAddTo
->addTemplateArg(TemplArg
);
3419 if (!consume(tgtok::greater
))
3420 return TokError("expected '>' at end of template argument list");
3424 /// ParseBodyItem - Parse a single item within the body of a def or class.
3426 /// BodyItem ::= Declaration ';'
3427 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
3428 /// BodyItem ::= Defvar
3429 /// BodyItem ::= Dump
3430 /// BodyItem ::= Assert
3432 bool TGParser::ParseBodyItem(Record
*CurRec
) {
3433 if (Lex
.getCode() == tgtok::Assert
)
3434 return ParseAssert(nullptr, CurRec
);
3436 if (Lex
.getCode() == tgtok::Defvar
)
3437 return ParseDefvar(CurRec
);
3439 if (Lex
.getCode() == tgtok::Dump
)
3440 return ParseDump(nullptr, CurRec
);
3442 if (Lex
.getCode() != tgtok::Let
) {
3443 if (!ParseDeclaration(CurRec
, false))
3446 if (!consume(tgtok::semi
))
3447 return TokError("expected ';' after declaration");
3451 // LET ID OptionalRangeList '=' Value ';'
3452 if (Lex
.Lex() != tgtok::Id
)
3453 return TokError("expected field identifier after let");
3455 SMLoc IdLoc
= Lex
.getLoc();
3456 StringInit
*FieldName
= StringInit::get(Records
, Lex
.getCurStrVal());
3457 Lex
.Lex(); // eat the field name.
3459 SmallVector
<unsigned, 16> BitList
;
3460 if (ParseOptionalBitList(BitList
))
3462 std::reverse(BitList
.begin(), BitList
.end());
3464 if (!consume(tgtok::equal
))
3465 return TokError("expected '=' in let expression");
3467 RecordVal
*Field
= CurRec
->getValue(FieldName
);
3469 return TokError("Value '" + FieldName
->getValue() + "' unknown!");
3471 RecTy
*Type
= Field
->getType();
3472 if (!BitList
.empty() && isa
<BitsRecTy
>(Type
)) {
3473 // When assigning to a subset of a 'bits' object, expect the RHS to have
3474 // the type of that subset instead of the type of the whole object.
3475 Type
= BitsRecTy::get(Records
, BitList
.size());
3478 Init
*Val
= ParseValue(CurRec
, Type
);
3479 if (!Val
) return true;
3481 if (!consume(tgtok::semi
))
3482 return TokError("expected ';' after let expression");
3484 return SetValue(CurRec
, IdLoc
, FieldName
, BitList
, Val
);
3487 /// ParseBody - Read the body of a class or def. Return true on error, false on
3491 /// Body ::= '{' BodyList '}'
3492 /// BodyList BodyItem*
3494 bool TGParser::ParseBody(Record
*CurRec
) {
3495 // If this is a null definition, just eat the semi and return.
3496 if (consume(tgtok::semi
))
3499 if (!consume(tgtok::l_brace
))
3500 return TokError("Expected '{' to start body or ';' for declaration only");
3502 while (Lex
.getCode() != tgtok::r_brace
)
3503 if (ParseBodyItem(CurRec
))
3509 // If we have a semicolon, print a gentle error.
3510 SMLoc SemiLoc
= Lex
.getLoc();
3511 if (consume(tgtok::semi
)) {
3512 PrintError(SemiLoc
, "A class or def body should not end with a semicolon");
3513 PrintNote("Semicolon ignored; remove to eliminate this error");
3519 /// Apply the current let bindings to \a CurRec.
3520 /// \returns true on error, false otherwise.
3521 bool TGParser::ApplyLetStack(Record
*CurRec
) {
3522 for (SmallVectorImpl
<LetRecord
> &LetInfo
: LetStack
)
3523 for (LetRecord
&LR
: LetInfo
)
3524 if (SetValue(CurRec
, LR
.Loc
, LR
.Name
, LR
.Bits
, LR
.Value
))
3529 /// Apply the current let bindings to the RecordsEntry.
3530 bool TGParser::ApplyLetStack(RecordsEntry
&Entry
) {
3532 return ApplyLetStack(Entry
.Rec
.get());
3534 // Let bindings are not applied to assertions.
3535 if (Entry
.Assertion
)
3538 // Let bindings are not applied to dumps.
3542 for (auto &E
: Entry
.Loop
->Entries
) {
3543 if (ApplyLetStack(E
))
3550 /// ParseObjectBody - Parse the body of a def or class. This consists of an
3551 /// optional ClassList followed by a Body. CurRec is the current def or class
3552 /// that is being parsed.
3554 /// ObjectBody ::= BaseClassList Body
3555 /// BaseClassList ::= /*empty*/
3556 /// BaseClassList ::= ':' BaseClassListNE
3557 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
3559 bool TGParser::ParseObjectBody(Record
*CurRec
) {
3560 // An object body introduces a new scope for local variables.
3561 TGVarScope
*ObjectScope
= PushScope(CurRec
);
3562 // If there is a baseclass list, read it.
3563 if (consume(tgtok::colon
)) {
3565 // Read all of the subclasses.
3566 SubClassReference SubClass
= ParseSubClassReference(CurRec
, false);
3569 if (!SubClass
.Rec
) return true;
3572 if (AddSubClass(CurRec
, SubClass
))
3575 if (!consume(tgtok::comma
))
3577 SubClass
= ParseSubClassReference(CurRec
, false);
3581 if (ApplyLetStack(CurRec
))
3584 bool Result
= ParseBody(CurRec
);
3585 PopScope(ObjectScope
);
3589 /// ParseDef - Parse and return a top level or multiclass record definition.
3590 /// Return false if okay, true if error.
3592 /// DefInst ::= DEF ObjectName ObjectBody
3594 bool TGParser::ParseDef(MultiClass
*CurMultiClass
) {
3595 SMLoc DefLoc
= Lex
.getLoc();
3596 assert(Lex
.getCode() == tgtok::Def
&& "Unknown tok");
3597 Lex
.Lex(); // Eat the 'def' token.
3599 // If the name of the def is an Id token, use that for the location.
3600 // Otherwise, the name is more complex and we use the location of the 'def'
3602 SMLoc NameLoc
= Lex
.getCode() == tgtok::Id
? Lex
.getLoc() : DefLoc
;
3604 // Parse ObjectName and make a record for it.
3605 std::unique_ptr
<Record
> CurRec
;
3606 Init
*Name
= ParseObjectName(CurMultiClass
);
3610 if (isa
<UnsetInit
>(Name
)) {
3611 CurRec
= std::make_unique
<Record
>(Records
.getNewAnonymousName(), DefLoc
,
3612 Records
, Record::RK_AnonymousDef
);
3614 CurRec
= std::make_unique
<Record
>(Name
, NameLoc
, Records
);
3617 if (ParseObjectBody(CurRec
.get()))
3620 return addEntry(std::move(CurRec
));
3623 /// ParseDefset - Parse a defset statement.
3625 /// Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
3627 bool TGParser::ParseDefset() {
3628 assert(Lex
.getCode() == tgtok::Defset
);
3629 Lex
.Lex(); // Eat the 'defset' token
3631 DefsetRecord Defset
;
3632 Defset
.Loc
= Lex
.getLoc();
3633 RecTy
*Type
= ParseType();
3636 if (!isa
<ListRecTy
>(Type
))
3637 return Error(Defset
.Loc
, "expected list type");
3638 Defset
.EltTy
= cast
<ListRecTy
>(Type
)->getElementType();
3640 if (Lex
.getCode() != tgtok::Id
)
3641 return TokError("expected identifier");
3642 StringInit
*DeclName
= StringInit::get(Records
, Lex
.getCurStrVal());
3643 if (Records
.getGlobal(DeclName
->getValue()))
3644 return TokError("def or global variable of this name already exists");
3646 if (Lex
.Lex() != tgtok::equal
) // Eat the identifier
3647 return TokError("expected '='");
3648 if (Lex
.Lex() != tgtok::l_brace
) // Eat the '='
3649 return TokError("expected '{'");
3650 SMLoc BraceLoc
= Lex
.getLoc();
3651 Lex
.Lex(); // Eat the '{'
3653 Defsets
.push_back(&Defset
);
3654 bool Err
= ParseObjectList(nullptr);
3659 if (!consume(tgtok::r_brace
)) {
3660 TokError("expected '}' at end of defset");
3661 return Error(BraceLoc
, "to match this '{'");
3664 Records
.addExtraGlobal(DeclName
->getValue(),
3665 ListInit::get(Defset
.Elements
, Defset
.EltTy
));
3669 /// ParseDefvar - Parse a defvar statement.
3671 /// Defvar ::= DEFVAR Id '=' Value ';'
3673 bool TGParser::ParseDefvar(Record
*CurRec
) {
3674 assert(Lex
.getCode() == tgtok::Defvar
);
3675 Lex
.Lex(); // Eat the 'defvar' token
3677 if (Lex
.getCode() != tgtok::Id
)
3678 return TokError("expected identifier");
3679 StringInit
*DeclName
= StringInit::get(Records
, Lex
.getCurStrVal());
3680 if (CurScope
->varAlreadyDefined(DeclName
->getValue()))
3681 return TokError("local variable of this name already exists");
3683 // The name should not be conflicted with existed field names.
3685 auto *V
= CurRec
->getValue(DeclName
->getValue());
3686 if (V
&& !V
->isTemplateArg())
3687 return TokError("field of this name already exists");
3690 // If this defvar is in the top level, the name should not be conflicted
3691 // with existed global names.
3692 if (CurScope
->isOutermost() && Records
.getGlobal(DeclName
->getValue()))
3693 return TokError("def or global variable of this name already exists");
3696 if (!consume(tgtok::equal
))
3697 return TokError("expected '='");
3699 Init
*Value
= ParseValue(CurRec
);
3703 if (!consume(tgtok::semi
))
3704 return TokError("expected ';'");
3706 if (!CurScope
->isOutermost())
3707 CurScope
->addVar(DeclName
->getValue(), Value
);
3709 Records
.addExtraGlobal(DeclName
->getValue(), Value
);
3714 /// ParseForeach - Parse a for statement. Return the record corresponding
3715 /// to it. This returns true on error.
3717 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
3718 /// Foreach ::= FOREACH Declaration IN Object
3720 bool TGParser::ParseForeach(MultiClass
*CurMultiClass
) {
3721 SMLoc Loc
= Lex
.getLoc();
3722 assert(Lex
.getCode() == tgtok::Foreach
&& "Unknown tok");
3723 Lex
.Lex(); // Eat the 'for' token.
3725 // Make a temporary object to record items associated with the for
3727 Init
*ListValue
= nullptr;
3728 VarInit
*IterName
= ParseForeachDeclaration(ListValue
);
3730 return TokError("expected declaration in for");
3732 if (!consume(tgtok::In
))
3733 return TokError("Unknown tok");
3735 // Create a loop object and remember it.
3736 auto TheLoop
= std::make_unique
<ForeachLoop
>(Loc
, IterName
, ListValue
);
3737 // A foreach loop introduces a new scope for local variables.
3738 TGVarScope
*ForeachScope
= PushScope(TheLoop
.get());
3739 Loops
.push_back(std::move(TheLoop
));
3741 if (Lex
.getCode() != tgtok::l_brace
) {
3742 // FOREACH Declaration IN Object
3743 if (ParseObject(CurMultiClass
))
3746 SMLoc BraceLoc
= Lex
.getLoc();
3747 // Otherwise, this is a group foreach.
3748 Lex
.Lex(); // eat the '{'.
3750 // Parse the object list.
3751 if (ParseObjectList(CurMultiClass
))
3754 if (!consume(tgtok::r_brace
)) {
3755 TokError("expected '}' at end of foreach command");
3756 return Error(BraceLoc
, "to match this '{'");
3760 PopScope(ForeachScope
);
3762 // Resolve the loop or store it for later resolution.
3763 std::unique_ptr
<ForeachLoop
> Loop
= std::move(Loops
.back());
3766 return addEntry(std::move(Loop
));
3769 /// ParseIf - Parse an if statement.
3771 /// If ::= IF Value THEN IfBody
3772 /// If ::= IF Value THEN IfBody ELSE IfBody
3774 bool TGParser::ParseIf(MultiClass
*CurMultiClass
) {
3775 SMLoc Loc
= Lex
.getLoc();
3776 assert(Lex
.getCode() == tgtok::If
&& "Unknown tok");
3777 Lex
.Lex(); // Eat the 'if' token.
3779 // Make a temporary object to record items associated with the for
3781 Init
*Condition
= ParseValue(nullptr);
3785 if (!consume(tgtok::Then
))
3786 return TokError("Unknown tok");
3788 // We have to be able to save if statements to execute later, and they have
3789 // to live on the same stack as foreach loops. The simplest implementation
3790 // technique is to convert each 'then' or 'else' clause *into* a foreach
3791 // loop, over a list of length 0 or 1 depending on the condition, and with no
3792 // iteration variable being assigned.
3794 ListInit
*EmptyList
= ListInit::get({}, BitRecTy::get(Records
));
3795 ListInit
*SingletonList
=
3796 ListInit::get({BitInit::get(Records
, true)}, BitRecTy::get(Records
));
3797 RecTy
*BitListTy
= ListRecTy::get(BitRecTy::get(Records
));
3799 // The foreach containing the then-clause selects SingletonList if
3800 // the condition is true.
3801 Init
*ThenClauseList
=
3802 TernOpInit::get(TernOpInit::IF
, Condition
, SingletonList
, EmptyList
,
3805 Loops
.push_back(std::make_unique
<ForeachLoop
>(Loc
, nullptr, ThenClauseList
));
3807 if (ParseIfBody(CurMultiClass
, "then"))
3810 std::unique_ptr
<ForeachLoop
> Loop
= std::move(Loops
.back());
3813 if (addEntry(std::move(Loop
)))
3816 // Now look for an optional else clause. The if-else syntax has the usual
3817 // dangling-else ambiguity, and by greedily matching an else here if we can,
3818 // we implement the usual resolution of pairing with the innermost unmatched
3820 if (consume(tgtok::ElseKW
)) {
3821 // The foreach containing the else-clause uses the same pair of lists as
3822 // above, but this time, selects SingletonList if the condition is *false*.
3823 Init
*ElseClauseList
=
3824 TernOpInit::get(TernOpInit::IF
, Condition
, EmptyList
, SingletonList
,
3828 std::make_unique
<ForeachLoop
>(Loc
, nullptr, ElseClauseList
));
3830 if (ParseIfBody(CurMultiClass
, "else"))
3833 Loop
= std::move(Loops
.back());
3836 if (addEntry(std::move(Loop
)))
3843 /// ParseIfBody - Parse the then-clause or else-clause of an if statement.
3845 /// IfBody ::= Object
3846 /// IfBody ::= '{' ObjectList '}'
3848 bool TGParser::ParseIfBody(MultiClass
*CurMultiClass
, StringRef Kind
) {
3849 // An if-statement introduces a new scope for local variables.
3850 TGVarScope
*BodyScope
= PushScope();
3852 if (Lex
.getCode() != tgtok::l_brace
) {
3854 if (ParseObject(CurMultiClass
))
3857 SMLoc BraceLoc
= Lex
.getLoc();
3859 Lex
.Lex(); // eat the '{'.
3861 // Parse the object list.
3862 if (ParseObjectList(CurMultiClass
))
3865 if (!consume(tgtok::r_brace
)) {
3866 TokError("expected '}' at end of '" + Kind
+ "' clause");
3867 return Error(BraceLoc
, "to match this '{'");
3871 PopScope(BodyScope
);
3875 /// ParseAssert - Parse an assert statement.
3877 /// Assert ::= ASSERT condition , message ;
3878 bool TGParser::ParseAssert(MultiClass
*CurMultiClass
, Record
*CurRec
) {
3879 assert(Lex
.getCode() == tgtok::Assert
&& "Unknown tok");
3880 Lex
.Lex(); // Eat the 'assert' token.
3882 SMLoc ConditionLoc
= Lex
.getLoc();
3883 Init
*Condition
= ParseValue(CurRec
);
3887 if (!consume(tgtok::comma
)) {
3888 TokError("expected ',' in assert statement");
3892 Init
*Message
= ParseValue(CurRec
);
3896 if (!consume(tgtok::semi
))
3897 return TokError("expected ';'");
3900 CurRec
->addAssertion(ConditionLoc
, Condition
, Message
);
3902 addEntry(std::make_unique
<Record::AssertionInfo
>(ConditionLoc
, Condition
,
3907 /// ParseClass - Parse a tblgen class definition.
3909 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
3911 bool TGParser::ParseClass() {
3912 assert(Lex
.getCode() == tgtok::Class
&& "Unexpected token!");
3915 if (Lex
.getCode() != tgtok::Id
)
3916 return TokError("expected class name after 'class' keyword");
3918 Record
*CurRec
= Records
.getClass(Lex
.getCurStrVal());
3920 // If the body was previously defined, this is an error.
3921 if (!CurRec
->getValues().empty() ||
3922 !CurRec
->getSuperClasses().empty() ||
3923 !CurRec
->getTemplateArgs().empty())
3924 return TokError("Class '" + CurRec
->getNameInitAsString() +
3925 "' already defined");
3927 CurRec
->updateClassLoc(Lex
.getLoc());
3929 // If this is the first reference to this class, create and add it.
3930 auto NewRec
= std::make_unique
<Record
>(Lex
.getCurStrVal(), Lex
.getLoc(),
3931 Records
, Record::RK_Class
);
3932 CurRec
= NewRec
.get();
3933 Records
.addClass(std::move(NewRec
));
3935 Lex
.Lex(); // eat the name.
3937 // A class definition introduces a new scope.
3938 TGVarScope
*ClassScope
= PushScope(CurRec
);
3939 // If there are template args, parse them.
3940 if (Lex
.getCode() == tgtok::less
)
3941 if (ParseTemplateArgList(CurRec
))
3944 if (ParseObjectBody(CurRec
))
3947 if (!NoWarnOnUnusedTemplateArgs
)
3948 CurRec
->checkUnusedTemplateArgs();
3950 PopScope(ClassScope
);
3954 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
3957 /// LetList ::= LetItem (',' LetItem)*
3958 /// LetItem ::= ID OptionalRangeList '=' Value
3960 void TGParser::ParseLetList(SmallVectorImpl
<LetRecord
> &Result
) {
3962 if (Lex
.getCode() != tgtok::Id
) {
3963 TokError("expected identifier in let definition");
3968 StringInit
*Name
= StringInit::get(Records
, Lex
.getCurStrVal());
3969 SMLoc NameLoc
= Lex
.getLoc();
3970 Lex
.Lex(); // Eat the identifier.
3972 // Check for an optional RangeList.
3973 SmallVector
<unsigned, 16> Bits
;
3974 if (ParseOptionalRangeList(Bits
)) {
3978 std::reverse(Bits
.begin(), Bits
.end());
3980 if (!consume(tgtok::equal
)) {
3981 TokError("expected '=' in let expression");
3986 Init
*Val
= ParseValue(nullptr);
3992 // Now that we have everything, add the record.
3993 Result
.emplace_back(Name
, Bits
, Val
, NameLoc
);
3994 } while (consume(tgtok::comma
));
3997 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
3998 /// different related productions. This works inside multiclasses too.
4000 /// Object ::= LET LetList IN '{' ObjectList '}'
4001 /// Object ::= LET LetList IN Object
4003 bool TGParser::ParseTopLevelLet(MultiClass
*CurMultiClass
) {
4004 assert(Lex
.getCode() == tgtok::Let
&& "Unexpected token");
4007 // Add this entry to the let stack.
4008 SmallVector
<LetRecord
, 8> LetInfo
;
4009 ParseLetList(LetInfo
);
4010 if (LetInfo
.empty()) return true;
4011 LetStack
.push_back(std::move(LetInfo
));
4013 if (!consume(tgtok::In
))
4014 return TokError("expected 'in' at end of top-level 'let'");
4016 // If this is a scalar let, just handle it now
4017 if (Lex
.getCode() != tgtok::l_brace
) {
4018 // LET LetList IN Object
4019 if (ParseObject(CurMultiClass
))
4021 } else { // Object ::= LETCommand '{' ObjectList '}'
4022 SMLoc BraceLoc
= Lex
.getLoc();
4023 // Otherwise, this is a group let.
4024 Lex
.Lex(); // eat the '{'.
4026 // A group let introduces a new scope for local variables.
4027 TGVarScope
*LetScope
= PushScope();
4029 // Parse the object list.
4030 if (ParseObjectList(CurMultiClass
))
4033 if (!consume(tgtok::r_brace
)) {
4034 TokError("expected '}' at end of top level let command");
4035 return Error(BraceLoc
, "to match this '{'");
4041 // Outside this let scope, this let block is not active.
4042 LetStack
.pop_back();
4046 /// ParseMultiClass - Parse a multiclass definition.
4048 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
4049 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
4050 /// MultiClassObject ::= Assert
4051 /// MultiClassObject ::= DefInst
4052 /// MultiClassObject ::= DefMInst
4053 /// MultiClassObject ::= Defvar
4054 /// MultiClassObject ::= Foreach
4055 /// MultiClassObject ::= If
4056 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
4057 /// MultiClassObject ::= LETCommand Object
4059 bool TGParser::ParseMultiClass() {
4060 assert(Lex
.getCode() == tgtok::MultiClass
&& "Unexpected token");
4061 Lex
.Lex(); // Eat the multiclass token.
4063 if (Lex
.getCode() != tgtok::Id
)
4064 return TokError("expected identifier after multiclass for name");
4065 std::string Name
= Lex
.getCurStrVal();
4068 MultiClasses
.insert(std::make_pair(Name
,
4069 std::make_unique
<MultiClass
>(Name
, Lex
.getLoc(),Records
)));
4072 return TokError("multiclass '" + Name
+ "' already defined");
4074 CurMultiClass
= Result
.first
->second
.get();
4075 Lex
.Lex(); // Eat the identifier.
4077 // A multiclass body introduces a new scope for local variables.
4078 TGVarScope
*MulticlassScope
= PushScope(CurMultiClass
);
4080 // If there are template args, parse them.
4081 if (Lex
.getCode() == tgtok::less
)
4082 if (ParseTemplateArgList(nullptr))
4085 bool inherits
= false;
4087 // If there are submulticlasses, parse them.
4088 if (consume(tgtok::colon
)) {
4091 // Read all of the submulticlasses.
4092 SubMultiClassReference SubMultiClass
=
4093 ParseSubMultiClassReference(CurMultiClass
);
4096 if (!SubMultiClass
.MC
) return true;
4099 if (AddSubMultiClass(CurMultiClass
, SubMultiClass
))
4102 if (!consume(tgtok::comma
))
4104 SubMultiClass
= ParseSubMultiClassReference(CurMultiClass
);
4108 if (Lex
.getCode() != tgtok::l_brace
) {
4110 return TokError("expected '{' in multiclass definition");
4111 if (!consume(tgtok::semi
))
4112 return TokError("expected ';' in multiclass definition");
4114 if (Lex
.Lex() == tgtok::r_brace
) // eat the '{'.
4115 return TokError("multiclass must contain at least one def");
4117 while (Lex
.getCode() != tgtok::r_brace
) {
4118 switch (Lex
.getCode()) {
4120 return TokError("expected 'assert', 'def', 'defm', 'defvar', 'dump', "
4121 "'foreach', 'if', or 'let' in multiclass body");
4128 case tgtok::Foreach
:
4131 if (ParseObject(CurMultiClass
))
4136 Lex
.Lex(); // eat the '}'.
4138 // If we have a semicolon, print a gentle error.
4139 SMLoc SemiLoc
= Lex
.getLoc();
4140 if (consume(tgtok::semi
)) {
4141 PrintError(SemiLoc
, "A multiclass body should not end with a semicolon");
4142 PrintNote("Semicolon ignored; remove to eliminate this error");
4146 if (!NoWarnOnUnusedTemplateArgs
)
4147 CurMultiClass
->Rec
.checkUnusedTemplateArgs();
4149 PopScope(MulticlassScope
);
4150 CurMultiClass
= nullptr;
4154 /// ParseDefm - Parse the instantiation of a multiclass.
4156 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
4158 bool TGParser::ParseDefm(MultiClass
*CurMultiClass
) {
4159 assert(Lex
.getCode() == tgtok::Defm
&& "Unexpected token!");
4160 Lex
.Lex(); // eat the defm
4162 Init
*DefmName
= ParseObjectName(CurMultiClass
);
4165 if (isa
<UnsetInit
>(DefmName
)) {
4166 DefmName
= Records
.getNewAnonymousName();
4168 DefmName
= BinOpInit::getStrConcat(
4169 VarInit::get(QualifiedNameOfImplicitName(CurMultiClass
),
4170 StringRecTy::get(Records
)),
4174 if (Lex
.getCode() != tgtok::colon
)
4175 return TokError("expected ':' after defm identifier");
4177 // Keep track of the new generated record definitions.
4178 std::vector
<RecordsEntry
> NewEntries
;
4180 // This record also inherits from a regular class (non-multiclass)?
4181 bool InheritFromClass
= false;
4186 SMLoc SubClassLoc
= Lex
.getLoc();
4187 SubClassReference Ref
= ParseSubClassReference(nullptr, true);
4190 if (!Ref
.Rec
) return true;
4192 // To instantiate a multiclass, we get the multiclass and then loop
4193 // through its template argument names. Substs contains a substitution
4194 // value for each argument, either the value specified or the default.
4195 // Then we can resolve the template arguments.
4196 MultiClass
*MC
= MultiClasses
[std::string(Ref
.Rec
->getName())].get();
4197 assert(MC
&& "Didn't lookup multiclass correctly?");
4200 if (resolveArgumentsOfMultiClass(Substs
, MC
, Ref
.TemplateArgs
, DefmName
,
4204 if (resolve(MC
->Entries
, Substs
, !CurMultiClass
&& Loops
.empty(),
4205 &NewEntries
, &SubClassLoc
))
4208 if (!consume(tgtok::comma
))
4211 if (Lex
.getCode() != tgtok::Id
)
4212 return TokError("expected identifier");
4214 SubClassLoc
= Lex
.getLoc();
4216 // A defm can inherit from regular classes (non-multiclasses) as
4217 // long as they come in the end of the inheritance list.
4218 InheritFromClass
= (Records
.getClass(Lex
.getCurStrVal()) != nullptr);
4220 if (InheritFromClass
)
4223 Ref
= ParseSubClassReference(nullptr, true);
4226 if (InheritFromClass
) {
4227 // Process all the classes to inherit as if they were part of a
4228 // regular 'def' and inherit all record values.
4229 SubClassReference SubClass
= ParseSubClassReference(nullptr, false);
4232 if (!SubClass
.Rec
) return true;
4234 // Get the expanded definition prototypes and teach them about
4235 // the record values the current class to inherit has
4236 for (auto &E
: NewEntries
) {
4238 if (AddSubClass(E
, SubClass
))
4242 if (!consume(tgtok::comma
))
4244 SubClass
= ParseSubClassReference(nullptr, false);
4248 for (auto &E
: NewEntries
) {
4249 if (ApplyLetStack(E
))
4252 addEntry(std::move(E
));
4255 if (!consume(tgtok::semi
))
4256 return TokError("expected ';' at end of defm");
4262 /// Object ::= ClassInst
4263 /// Object ::= DefInst
4264 /// Object ::= MultiClassInst
4265 /// Object ::= DefMInst
4266 /// Object ::= LETCommand '{' ObjectList '}'
4267 /// Object ::= LETCommand Object
4268 /// Object ::= Defset
4269 /// Object ::= Defvar
4270 /// Object ::= Assert
4272 bool TGParser::ParseObject(MultiClass
*MC
) {
4273 switch (Lex
.getCode()) {
4276 "Expected assert, class, def, defm, defset, dump, foreach, if, or let");
4277 case tgtok::Assert
: return ParseAssert(MC
);
4278 case tgtok::Def
: return ParseDef(MC
);
4279 case tgtok::Defm
: return ParseDefm(MC
);
4280 case tgtok::Defvar
: return ParseDefvar();
4282 return ParseDump(MC
);
4283 case tgtok::Foreach
: return ParseForeach(MC
);
4284 case tgtok::If
: return ParseIf(MC
);
4285 case tgtok::Let
: return ParseTopLevelLet(MC
);
4288 return TokError("defset is not allowed inside multiclass");
4289 return ParseDefset();
4292 return TokError("class is not allowed inside multiclass");
4294 return TokError("class is not allowed inside foreach loop");
4295 return ParseClass();
4296 case tgtok::MultiClass
:
4298 return TokError("multiclass is not allowed inside foreach loop");
4299 return ParseMultiClass();
4304 /// ObjectList :== Object*
4305 bool TGParser::ParseObjectList(MultiClass
*MC
) {
4306 while (tgtok::isObjectStart(Lex
.getCode())) {
4307 if (ParseObject(MC
))
4313 bool TGParser::ParseFile() {
4314 Lex
.Lex(); // Prime the lexer.
4315 TGVarScope
*GlobalScope
= PushScope();
4316 if (ParseObjectList())
4318 PopScope(GlobalScope
);
4320 // If we have unread input at the end of the file, report it.
4321 if (Lex
.getCode() == tgtok::Eof
)
4324 return TokError("Unexpected token at top level");
4327 // Check the types of the template argument values for a class
4328 // inheritance, multiclass invocation, or anonymous class invocation.
4329 // If necessary, replace an argument with a cast to the required type.
4330 // The argument count has already been checked.
4331 bool TGParser::CheckTemplateArgValues(
4332 SmallVectorImpl
<llvm::ArgumentInit
*> &Values
, SMLoc Loc
, Record
*ArgsRec
) {
4333 ArrayRef
<Init
*> TArgs
= ArgsRec
->getTemplateArgs();
4335 for (unsigned I
= 0, E
= Values
.size(); I
< E
; ++I
) {
4336 auto *Value
= Values
[I
];
4337 Init
*ArgName
= nullptr;
4338 if (Value
->isPositional())
4339 ArgName
= TArgs
[Value
->getIndex()];
4340 if (Value
->isNamed())
4341 ArgName
= Value
->getName();
4343 RecordVal
*Arg
= ArgsRec
->getValue(ArgName
);
4344 RecTy
*ArgType
= Arg
->getType();
4346 if (TypedInit
*ArgValue
= dyn_cast
<TypedInit
>(Value
->getValue())) {
4347 auto *CastValue
= ArgValue
->getCastTo(ArgType
);
4349 assert((!isa
<TypedInit
>(CastValue
) ||
4350 cast
<TypedInit
>(CastValue
)->getType()->typeIsA(ArgType
)) &&
4351 "result of template arg value cast has wrong type");
4352 Values
[I
] = Value
->cloneWithValue(CastValue
);
4354 PrintFatalError(Loc
, "Value specified for template argument '" +
4355 Arg
->getNameInitAsString() + "' is of type " +
4356 ArgValue
->getType()->getAsString() +
4357 "; expected type " + ArgType
->getAsString() +
4358 ": " + ArgValue
->getAsString());
4366 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
4367 LLVM_DUMP_METHOD
void RecordsEntry::dump() const {
4374 LLVM_DUMP_METHOD
void ForeachLoop::dump() const {
4375 errs() << "foreach " << IterVar
->getAsString() << " = "
4376 << ListValue
->getAsString() << " in {\n";
4378 for (const auto &E
: Entries
)
4384 LLVM_DUMP_METHOD
void MultiClass::dump() const {
4385 errs() << "Record:\n";
4388 errs() << "Defs:\n";
4389 for (const auto &E
: Entries
)
4394 bool TGParser::ParseDump(MultiClass
*CurMultiClass
, Record
*CurRec
) {
4395 // Location of the `dump` statement.
4396 SMLoc Loc
= Lex
.getLoc();
4397 assert(Lex
.getCode() == tgtok::Dump
&& "Unknown tok");
4398 Lex
.Lex(); // eat the operation
4400 Init
*Message
= ParseValue(CurRec
);
4404 // Allow to use dump directly on `defvar` and `def`, by wrapping
4405 // them with a `!repl`.
4406 if (isa
<DefInit
>(Message
))
4407 Message
= UnOpInit::get(UnOpInit::REPR
, Message
, StringRecTy::get(Records
))
4410 if (!consume(tgtok::semi
))
4411 return TokError("expected ';'");
4414 CurRec
->addDump(Loc
, Message
);
4416 addEntry(std::make_unique
<Record::DumpInfo
>(Loc
, Message
));