1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implement the Parser for TableGen.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/TableGen/Record.h"
24 //===----------------------------------------------------------------------===//
25 // Support Code for the Semantic Actions.
26 //===----------------------------------------------------------------------===//
29 struct SubClassReference {
32 std::vector<Init*> TemplateArgs;
33 SubClassReference() : Rec(nullptr) {}
35 bool isInvalid() const { return Rec == nullptr; }
38 struct SubMultiClassReference {
41 std::vector<Init*> TemplateArgs;
42 SubMultiClassReference() : MC(nullptr) {}
44 bool isInvalid() const { return MC == nullptr; }
48 void SubMultiClassReference::dump() const {
49 errs() << "Multiclass:\n";
53 errs() << "Template args:\n";
54 for (Init *TA : TemplateArgs)
58 } // end namespace llvm
60 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
62 CurRec = &CurMultiClass->Rec;
64 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
65 // The value already exists in the class, treat this as a set.
66 if (ERV->setValue(RV.getValue()))
67 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
68 RV.getType()->getAsString() + "' is incompatible with " +
69 "previous definition of type '" +
70 ERV->getType()->getAsString() + "'");
78 /// Return true on error, false on success.
79 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
80 const std::vector<unsigned> &BitList, Init *V,
81 bool AllowSelfAssignment) {
84 if (!CurRec) CurRec = &CurMultiClass->Rec;
86 RecordVal *RV = CurRec->getValue(ValName);
88 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
91 // Do not allow assignments like 'X = X'. This will just cause infinite loops
92 // in the resolution machinery.
94 if (VarInit *VI = dyn_cast<VarInit>(V))
95 if (VI->getNameInit() == ValName && !AllowSelfAssignment)
98 // If we are assigning to a subset of the bits in the value... then we must be
99 // assigning to a field of BitsRecTy, which must have a BitsInit
102 if (!BitList.empty()) {
103 BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
105 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
106 "' is not a bits type");
108 // Convert the incoming value to a bits type of the appropriate size...
109 Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size()));
111 return Error(Loc, "Initializer is not compatible with bit range");
113 // We should have a BitsInit type now.
114 BitsInit *BInit = cast<BitsInit>(BI);
116 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
118 // Loop over bits, assigning values as appropriate.
119 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
120 unsigned Bit = BitList[i];
122 return Error(Loc, "Cannot set bit #" + Twine(Bit) + " of value '" +
123 ValName->getAsUnquotedString() + "' more than once");
124 NewBits[Bit] = BInit->getBit(i);
127 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
129 NewBits[i] = CurVal->getBit(i);
131 V = BitsInit::get(NewBits);
134 if (RV->setValue(V)) {
135 std::string InitType = "";
136 if (BitsInit *BI = dyn_cast<BitsInit>(V))
137 InitType = (Twine("' of type bit initializer with length ") +
138 Twine(BI->getNumBits())).str();
139 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
140 "' of type '" + RV->getType()->getAsString() +
141 "' is incompatible with initializer '" + V->getAsString() +
147 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
148 /// args as SubClass's template arguments.
149 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
150 Record *SC = SubClass.Rec;
151 // Add all of the values in the subclass into the current class.
152 for (const RecordVal &Val : SC->getValues())
153 if (AddValue(CurRec, SubClass.RefRange.Start, Val))
156 ArrayRef<Init *> TArgs = SC->getTemplateArgs();
158 // Ensure that an appropriate number of template arguments are specified.
159 if (TArgs.size() < SubClass.TemplateArgs.size())
160 return Error(SubClass.RefRange.Start,
161 "More template args specified than expected");
163 // Loop over all of the template arguments, setting them to the specified
164 // value or leaving them as the default if necessary.
165 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
166 if (i < SubClass.TemplateArgs.size()) {
167 // If a value is specified for this template arg, set it now.
168 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
169 std::vector<unsigned>(), SubClass.TemplateArgs[i]))
173 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
176 CurRec->removeValue(TArgs[i]);
178 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
179 return Error(SubClass.RefRange.Start,
180 "Value not specified for template argument #" +
181 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
182 ") of subclass '" + SC->getNameInitAsString() + "'!");
186 // Since everything went well, we can now set the "superclass" list for the
188 ArrayRef<Record *> SCs = SC->getSuperClasses();
189 ArrayRef<SMRange> SCRanges = SC->getSuperClassRanges();
190 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
191 if (CurRec->isSubClassOf(SCs[i]))
192 return Error(SubClass.RefRange.Start,
193 "Already subclass of '" + SCs[i]->getName() + "'!\n");
194 CurRec->addSuperClass(SCs[i], SCRanges[i]);
197 if (CurRec->isSubClassOf(SC))
198 return Error(SubClass.RefRange.Start,
199 "Already subclass of '" + SC->getName() + "'!\n");
200 CurRec->addSuperClass(SC, SubClass.RefRange);
204 /// AddSubMultiClass - Add SubMultiClass as a subclass to
205 /// CurMC, resolving its template args as SubMultiClass's
206 /// template arguments.
207 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
208 SubMultiClassReference &SubMultiClass) {
209 MultiClass *SMC = SubMultiClass.MC;
210 Record *CurRec = &CurMC->Rec;
212 // Add all of the values in the subclass into the current class.
213 for (const auto &SMCVal : SMC->Rec.getValues())
214 if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVal))
217 unsigned newDefStart = CurMC->DefPrototypes.size();
219 // Add all of the defs in the subclass into the current multiclass.
220 for (const std::unique_ptr<Record> &R : SMC->DefPrototypes) {
221 // Clone the def and add it to the current multiclass
222 auto NewDef = make_unique<Record>(*R);
224 // Add all of the values in the superclass into the current def.
225 for (const auto &MCVal : CurRec->getValues())
226 if (AddValue(NewDef.get(), SubMultiClass.RefRange.Start, MCVal))
229 CurMC->DefPrototypes.push_back(std::move(NewDef));
232 ArrayRef<Init *> SMCTArgs = SMC->Rec.getTemplateArgs();
234 // Ensure that an appropriate number of template arguments are
236 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
237 return Error(SubMultiClass.RefRange.Start,
238 "More template args specified than expected");
240 // Loop over all of the template arguments, setting them to the specified
241 // value or leaving them as the default if necessary.
242 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
243 if (i < SubMultiClass.TemplateArgs.size()) {
244 // If a value is specified for this template arg, set it in the
246 if (SetValue(CurRec, SubMultiClass.RefRange.Start, SMCTArgs[i],
247 std::vector<unsigned>(),
248 SubMultiClass.TemplateArgs[i]))
252 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
255 CurRec->removeValue(SMCTArgs[i]);
257 // If a value is specified for this template arg, set it in the
259 for (const auto &Def :
260 makeArrayRef(CurMC->DefPrototypes).slice(newDefStart)) {
261 if (SetValue(Def.get(), SubMultiClass.RefRange.Start, SMCTArgs[i],
262 std::vector<unsigned>(),
263 SubMultiClass.TemplateArgs[i]))
267 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
270 Def->removeValue(SMCTArgs[i]);
272 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
273 return Error(SubMultiClass.RefRange.Start,
274 "Value not specified for template argument #" +
275 Twine(i) + " (" + SMCTArgs[i]->getAsUnquotedString() +
276 ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
283 /// ProcessForeachDefs - Given a record, apply all of the variable
284 /// values in all surrounding foreach loops, creating new records for
285 /// each combination of values.
286 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
290 // We want to instantiate a new copy of CurRec for each combination
291 // of nested loop iterator values. We don't want top instantiate
292 // any copies until we have values for each loop iterator.
294 return ProcessForeachDefs(CurRec, Loc, IterVals);
297 /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
298 /// apply each of the variable values in this loop and then process
300 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
301 // Recursively build a tuple of iterator values.
302 if (IterVals.size() != Loops.size()) {
303 assert(IterVals.size() < Loops.size());
304 ForeachLoop &CurLoop = Loops[IterVals.size()];
305 ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
307 Error(Loc, "Loop list is not a list");
311 // Process each value.
312 for (unsigned i = 0; i < List->size(); ++i) {
313 Init *ItemVal = List->resolveListElementReference(*CurRec, nullptr, i);
314 IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
315 if (ProcessForeachDefs(CurRec, Loc, IterVals))
322 // This is the bottom of the recursion. We have all of the iterator values
323 // for this point in the iteration space. Instantiate a new record to
324 // reflect this combination of values.
325 auto IterRec = make_unique<Record>(*CurRec);
327 // Set the iterator values now.
328 for (IterRecord &IR : IterVals) {
329 VarInit *IterVar = IR.IterVar;
330 TypedInit *IVal = dyn_cast<TypedInit>(IR.IterValue);
332 return Error(Loc, "foreach iterator value is untyped");
334 IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
336 if (SetValue(IterRec.get(), Loc, IterVar->getName(),
337 std::vector<unsigned>(), IVal))
338 return Error(Loc, "when instantiating this def");
341 IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
344 IterRec->removeValue(IterVar->getName());
347 if (Records.getDef(IterRec->getNameInitAsString())) {
348 // If this record is anonymous, it's no problem, just generate a new name
349 if (!IterRec->isAnonymous())
350 return Error(Loc, "def already exists: " +IterRec->getNameInitAsString());
352 IterRec->setName(GetNewAnonymousName());
355 Record *IterRecSave = IterRec.get(); // Keep a copy before release.
356 Records.addDef(std::move(IterRec));
357 IterRecSave->resolveReferences();
361 //===----------------------------------------------------------------------===//
363 //===----------------------------------------------------------------------===//
365 /// isObjectStart - Return true if this is a valid first token for an Object.
366 static bool isObjectStart(tgtok::TokKind K) {
367 return K == tgtok::Class || K == tgtok::Def ||
368 K == tgtok::Defm || K == tgtok::Let ||
369 K == tgtok::MultiClass || K == tgtok::Foreach;
372 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
374 std::string TGParser::GetNewAnonymousName() {
375 return "anonymous_" + utostr(AnonCounter++);
378 /// ParseObjectName - If an object name is specified, return it. Otherwise,
380 /// ObjectName ::= Value [ '#' Value ]*
381 /// ObjectName ::= /*empty*/
383 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
384 switch (Lex.getCode()) {
388 // These are all of the tokens that can begin an object body.
389 // Some of these can also begin values but we disallow those cases
390 // because they are unlikely to be useful.
396 Record *CurRec = nullptr;
398 CurRec = &CurMultiClass->Rec;
400 RecTy *Type = nullptr;
402 const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
404 TokError("Record name is not typed!");
407 Type = CurRecName->getType();
410 return ParseValue(CurRec, Type, ParseNameMode);
413 /// ParseClassID - Parse and resolve a reference to a class name. This returns
418 Record *TGParser::ParseClassID() {
419 if (Lex.getCode() != tgtok::Id) {
420 TokError("expected name for ClassID");
424 Record *Result = Records.getClass(Lex.getCurStrVal());
426 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
432 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
433 /// This returns null on error.
435 /// MultiClassID ::= ID
437 MultiClass *TGParser::ParseMultiClassID() {
438 if (Lex.getCode() != tgtok::Id) {
439 TokError("expected name for MultiClassID");
443 MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
445 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
451 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
452 /// subclass. This returns a SubClassRefTy with a null Record* on error.
454 /// SubClassRef ::= ClassID
455 /// SubClassRef ::= ClassID '<' ValueList '>'
457 SubClassReference TGParser::
458 ParseSubClassReference(Record *CurRec, bool isDefm) {
459 SubClassReference Result;
460 Result.RefRange.Start = Lex.getLoc();
463 if (MultiClass *MC = ParseMultiClassID())
464 Result.Rec = &MC->Rec;
466 Result.Rec = ParseClassID();
468 if (!Result.Rec) return Result;
470 // If there is no template arg list, we're done.
471 if (Lex.getCode() != tgtok::less) {
472 Result.RefRange.End = Lex.getLoc();
475 Lex.Lex(); // Eat the '<'
477 if (Lex.getCode() == tgtok::greater) {
478 TokError("subclass reference requires a non-empty list of template values");
479 Result.Rec = nullptr;
483 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
484 if (Result.TemplateArgs.empty()) {
485 Result.Rec = nullptr; // Error parsing value list.
489 if (Lex.getCode() != tgtok::greater) {
490 TokError("expected '>' in template value list");
491 Result.Rec = nullptr;
495 Result.RefRange.End = Lex.getLoc();
500 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
501 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
502 /// Record* on error.
504 /// SubMultiClassRef ::= MultiClassID
505 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
507 SubMultiClassReference TGParser::
508 ParseSubMultiClassReference(MultiClass *CurMC) {
509 SubMultiClassReference Result;
510 Result.RefRange.Start = Lex.getLoc();
512 Result.MC = ParseMultiClassID();
513 if (!Result.MC) return Result;
515 // If there is no template arg list, we're done.
516 if (Lex.getCode() != tgtok::less) {
517 Result.RefRange.End = Lex.getLoc();
520 Lex.Lex(); // Eat the '<'
522 if (Lex.getCode() == tgtok::greater) {
523 TokError("subclass reference requires a non-empty list of template values");
528 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
529 if (Result.TemplateArgs.empty()) {
530 Result.MC = nullptr; // Error parsing value list.
534 if (Lex.getCode() != tgtok::greater) {
535 TokError("expected '>' in template value list");
540 Result.RefRange.End = Lex.getLoc();
545 /// ParseRangePiece - Parse a bit/value range.
546 /// RangePiece ::= INTVAL
547 /// RangePiece ::= INTVAL '-' INTVAL
548 /// RangePiece ::= INTVAL INTVAL
549 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
550 if (Lex.getCode() != tgtok::IntVal) {
551 TokError("expected integer or bitrange");
554 int64_t Start = Lex.getCurIntVal();
558 return TokError("invalid range, cannot be negative");
560 switch (Lex.Lex()) { // eat first character.
562 Ranges.push_back(Start);
565 if (Lex.Lex() != tgtok::IntVal) {
566 TokError("expected integer value as end of range");
569 End = Lex.getCurIntVal();
572 End = -Lex.getCurIntVal();
576 return TokError("invalid range, cannot be negative");
581 for (; Start <= End; ++Start)
582 Ranges.push_back(Start);
584 for (; Start >= End; --Start)
585 Ranges.push_back(Start);
589 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
591 /// RangeList ::= RangePiece (',' RangePiece)*
593 std::vector<unsigned> TGParser::ParseRangeList() {
594 std::vector<unsigned> Result;
596 // Parse the first piece.
597 if (ParseRangePiece(Result))
598 return std::vector<unsigned>();
599 while (Lex.getCode() == tgtok::comma) {
600 Lex.Lex(); // Eat the comma.
602 // Parse the next range piece.
603 if (ParseRangePiece(Result))
604 return std::vector<unsigned>();
609 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
610 /// OptionalRangeList ::= '<' RangeList '>'
611 /// OptionalRangeList ::= /*empty*/
612 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
613 if (Lex.getCode() != tgtok::less)
616 SMLoc StartLoc = Lex.getLoc();
617 Lex.Lex(); // eat the '<'
619 // Parse the range list.
620 Ranges = ParseRangeList();
621 if (Ranges.empty()) return true;
623 if (Lex.getCode() != tgtok::greater) {
624 TokError("expected '>' at end of range list");
625 return Error(StartLoc, "to match this '<'");
627 Lex.Lex(); // eat the '>'.
631 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
632 /// OptionalBitList ::= '{' RangeList '}'
633 /// OptionalBitList ::= /*empty*/
634 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
635 if (Lex.getCode() != tgtok::l_brace)
638 SMLoc StartLoc = Lex.getLoc();
639 Lex.Lex(); // eat the '{'
641 // Parse the range list.
642 Ranges = ParseRangeList();
643 if (Ranges.empty()) return true;
645 if (Lex.getCode() != tgtok::r_brace) {
646 TokError("expected '}' at end of bit list");
647 return Error(StartLoc, "to match this '{'");
649 Lex.Lex(); // eat the '}'.
654 /// ParseType - Parse and return a tblgen type. This returns null on error.
656 /// Type ::= STRING // string type
657 /// Type ::= CODE // code type
658 /// Type ::= BIT // bit type
659 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
660 /// Type ::= INT // int type
661 /// Type ::= LIST '<' Type '>' // list<x> type
662 /// Type ::= DAG // dag type
663 /// Type ::= ClassID // Record Type
665 RecTy *TGParser::ParseType() {
666 switch (Lex.getCode()) {
667 default: TokError("Unknown token when expecting a type"); return nullptr;
668 case tgtok::String: Lex.Lex(); return StringRecTy::get();
669 case tgtok::Code: Lex.Lex(); return StringRecTy::get();
670 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
671 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
672 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
674 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
677 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
678 TokError("expected '<' after bits type");
681 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
682 TokError("expected integer in bits<n> type");
685 uint64_t Val = Lex.getCurIntVal();
686 if (Lex.Lex() != tgtok::greater) { // Eat count.
687 TokError("expected '>' at end of bits<n> type");
690 Lex.Lex(); // Eat '>'
691 return BitsRecTy::get(Val);
694 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
695 TokError("expected '<' after list type");
698 Lex.Lex(); // Eat '<'
699 RecTy *SubType = ParseType();
700 if (!SubType) return nullptr;
702 if (Lex.getCode() != tgtok::greater) {
703 TokError("expected '>' at end of list<ty> type");
706 Lex.Lex(); // Eat '>'
707 return ListRecTy::get(SubType);
712 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
713 /// has already been read.
714 Init *TGParser::ParseIDValue(Record *CurRec,
715 const std::string &Name, SMLoc NameLoc,
718 if (const RecordVal *RV = CurRec->getValue(Name))
719 return VarInit::get(Name, RV->getType());
721 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
724 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
727 if (CurRec->isTemplateArg(TemplateArgName)) {
728 const RecordVal *RV = CurRec->getValue(TemplateArgName);
729 assert(RV && "Template arg doesn't exist??");
730 return VarInit::get(TemplateArgName, RV->getType());
735 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
738 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
739 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
740 assert(RV && "Template arg doesn't exist??");
741 return VarInit::get(MCName, RV->getType());
745 // If this is in a foreach loop, make sure it's not a loop iterator
746 for (const auto &L : Loops) {
747 VarInit *IterVar = dyn_cast<VarInit>(L.IterVar);
748 if (IterVar && IterVar->getName() == Name)
752 if (Mode == ParseNameMode)
753 return StringInit::get(Name);
755 if (Record *D = Records.getDef(Name))
756 return DefInit::get(D);
758 if (Mode == ParseValueMode) {
759 Error(NameLoc, "Variable not defined: '" + Name + "'");
763 return StringInit::get(Name);
766 /// ParseOperation - Parse an operator. This returns null on error.
768 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
770 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
771 switch (Lex.getCode()) {
773 TokError("unknown operation");
778 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
779 UnOpInit::UnaryOp Code;
780 RecTy *Type = nullptr;
782 switch (Lex.getCode()) {
783 default: llvm_unreachable("Unhandled code!");
785 Lex.Lex(); // eat the operation
786 Code = UnOpInit::CAST;
788 Type = ParseOperatorType();
791 TokError("did not get type for unary operator");
797 Lex.Lex(); // eat the operation
798 Code = UnOpInit::HEAD;
801 Lex.Lex(); // eat the operation
802 Code = UnOpInit::TAIL;
805 Lex.Lex(); // eat the operation
806 Code = UnOpInit::EMPTY;
807 Type = IntRecTy::get();
810 if (Lex.getCode() != tgtok::l_paren) {
811 TokError("expected '(' after unary operator");
814 Lex.Lex(); // eat the '('
816 Init *LHS = ParseValue(CurRec);
817 if (!LHS) return nullptr;
819 if (Code == UnOpInit::HEAD ||
820 Code == UnOpInit::TAIL ||
821 Code == UnOpInit::EMPTY) {
822 ListInit *LHSl = dyn_cast<ListInit>(LHS);
823 StringInit *LHSs = dyn_cast<StringInit>(LHS);
824 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
825 if (!LHSl && !LHSs && !LHSt) {
826 TokError("expected list or string type argument in unary operator");
830 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
831 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
832 if (!LType && !SType) {
833 TokError("expected list or string type argument in unary operator");
838 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
839 if (!LHSl && !LHSt) {
840 TokError("expected list type argument in unary operator");
844 if (LHSl && LHSl->empty()) {
845 TokError("empty list argument in unary operator");
849 Init *Item = LHSl->getElement(0);
850 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
852 TokError("untyped list element in unary operator");
855 Type = (Code == UnOpInit::HEAD) ? Itemt->getType()
856 : ListRecTy::get(Itemt->getType());
858 assert(LHSt && "expected list type argument in unary operator");
859 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
861 TokError("expected list type argument in unary operator");
864 Type = (Code == UnOpInit::HEAD) ? LType->getElementType() : LType;
869 if (Lex.getCode() != tgtok::r_paren) {
870 TokError("expected ')' in unary operator");
873 Lex.Lex(); // eat the ')'
874 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
884 case tgtok::XListConcat:
885 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
886 tgtok::TokKind OpTok = Lex.getCode();
887 SMLoc OpLoc = Lex.getLoc();
888 Lex.Lex(); // eat the operation
890 BinOpInit::BinaryOp Code;
891 RecTy *Type = nullptr;
894 default: llvm_unreachable("Unhandled code!");
895 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
896 case tgtok::XADD: Code = BinOpInit::ADD; Type = IntRecTy::get(); break;
897 case tgtok::XAND: Code = BinOpInit::AND; Type = IntRecTy::get(); break;
898 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
899 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
900 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
901 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
902 case tgtok::XListConcat:
903 Code = BinOpInit::LISTCONCAT;
904 // We don't know the list type until we parse the first argument
906 case tgtok::XStrConcat:
907 Code = BinOpInit::STRCONCAT;
908 Type = StringRecTy::get();
912 if (Lex.getCode() != tgtok::l_paren) {
913 TokError("expected '(' after binary operator");
916 Lex.Lex(); // eat the '('
918 SmallVector<Init*, 2> InitList;
920 InitList.push_back(ParseValue(CurRec));
921 if (!InitList.back()) return nullptr;
923 while (Lex.getCode() == tgtok::comma) {
924 Lex.Lex(); // eat the ','
926 InitList.push_back(ParseValue(CurRec));
927 if (!InitList.back()) return nullptr;
930 if (Lex.getCode() != tgtok::r_paren) {
931 TokError("expected ')' in operator");
934 Lex.Lex(); // eat the ')'
936 // If we are doing !listconcat, we should know the type by now
937 if (OpTok == tgtok::XListConcat) {
938 if (VarInit *Arg0 = dyn_cast<VarInit>(InitList[0]))
939 Type = Arg0->getType();
940 else if (ListInit *Arg0 = dyn_cast<ListInit>(InitList[0]))
941 Type = Arg0->getType();
944 Error(OpLoc, "expected a list");
949 // We allow multiple operands to associative operators like !strconcat as
950 // shorthand for nesting them.
951 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT) {
952 while (InitList.size() > 2) {
953 Init *RHS = InitList.pop_back_val();
954 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
955 ->Fold(CurRec, CurMultiClass);
956 InitList.back() = RHS;
960 if (InitList.size() == 2)
961 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
962 ->Fold(CurRec, CurMultiClass);
964 Error(OpLoc, "expected two operands to operator");
969 case tgtok::XForEach:
970 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
971 TernOpInit::TernaryOp Code;
972 RecTy *Type = nullptr;
974 tgtok::TokKind LexCode = Lex.getCode();
975 Lex.Lex(); // eat the operation
977 default: llvm_unreachable("Unhandled code!");
979 Code = TernOpInit::IF;
981 case tgtok::XForEach:
982 Code = TernOpInit::FOREACH;
985 Code = TernOpInit::SUBST;
988 if (Lex.getCode() != tgtok::l_paren) {
989 TokError("expected '(' after ternary operator");
992 Lex.Lex(); // eat the '('
994 Init *LHS = ParseValue(CurRec);
995 if (!LHS) return nullptr;
997 if (Lex.getCode() != tgtok::comma) {
998 TokError("expected ',' in ternary operator");
1001 Lex.Lex(); // eat the ','
1003 Init *MHS = ParseValue(CurRec, ItemType);
1007 if (Lex.getCode() != tgtok::comma) {
1008 TokError("expected ',' in ternary operator");
1011 Lex.Lex(); // eat the ','
1013 Init *RHS = ParseValue(CurRec, ItemType);
1017 if (Lex.getCode() != tgtok::r_paren) {
1018 TokError("expected ')' in binary operator");
1021 Lex.Lex(); // eat the ')'
1024 default: llvm_unreachable("Unhandled code!");
1026 RecTy *MHSTy = nullptr;
1027 RecTy *RHSTy = nullptr;
1029 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1030 MHSTy = MHSt->getType();
1031 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1032 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1033 if (isa<BitInit>(MHS))
1034 MHSTy = BitRecTy::get();
1036 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1037 RHSTy = RHSt->getType();
1038 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1039 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1040 if (isa<BitInit>(RHS))
1041 RHSTy = BitRecTy::get();
1043 // For UnsetInit, it's typed from the other hand.
1044 if (isa<UnsetInit>(MHS))
1046 if (isa<UnsetInit>(RHS))
1049 if (!MHSTy || !RHSTy) {
1050 TokError("could not get type for !if");
1054 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1056 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1059 TokError("inconsistent types for !if");
1064 case tgtok::XForEach: {
1065 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1067 TokError("could not get type for !foreach");
1070 Type = MHSt->getType();
1073 case tgtok::XSubst: {
1074 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1076 TokError("could not get type for !subst");
1079 Type = RHSt->getType();
1083 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1089 /// ParseOperatorType - Parse a type for an operator. This returns
1092 /// OperatorType ::= '<' Type '>'
1094 RecTy *TGParser::ParseOperatorType() {
1095 RecTy *Type = nullptr;
1097 if (Lex.getCode() != tgtok::less) {
1098 TokError("expected type name for operator");
1101 Lex.Lex(); // eat the <
1106 TokError("expected type name for operator");
1110 if (Lex.getCode() != tgtok::greater) {
1111 TokError("expected type name for operator");
1114 Lex.Lex(); // eat the >
1120 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1122 /// SimpleValue ::= IDValue
1123 /// SimpleValue ::= INTVAL
1124 /// SimpleValue ::= STRVAL+
1125 /// SimpleValue ::= CODEFRAGMENT
1126 /// SimpleValue ::= '?'
1127 /// SimpleValue ::= '{' ValueList '}'
1128 /// SimpleValue ::= ID '<' ValueListNE '>'
1129 /// SimpleValue ::= '[' ValueList ']'
1130 /// SimpleValue ::= '(' IDValue DagArgList ')'
1131 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1132 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1133 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1134 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1135 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1136 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1137 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1139 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1142 switch (Lex.getCode()) {
1143 default: TokError("Unknown token when parsing a value"); break;
1145 // This is a leading paste operation. This is deprecated but
1146 // still exists in some .td files. Ignore it.
1147 Lex.Lex(); // Skip '#'.
1148 return ParseSimpleValue(CurRec, ItemType, Mode);
1149 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1150 case tgtok::BinaryIntVal: {
1151 auto BinaryVal = Lex.getCurBinaryIntVal();
1152 SmallVector<Init*, 16> Bits(BinaryVal.second);
1153 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
1154 Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
1155 R = BitsInit::get(Bits);
1159 case tgtok::StrVal: {
1160 std::string Val = Lex.getCurStrVal();
1163 // Handle multiple consecutive concatenated strings.
1164 while (Lex.getCode() == tgtok::StrVal) {
1165 Val += Lex.getCurStrVal();
1169 R = StringInit::get(Val);
1172 case tgtok::CodeFragment:
1173 R = StringInit::get(Lex.getCurStrVal());
1176 case tgtok::question:
1177 R = UnsetInit::get();
1181 SMLoc NameLoc = Lex.getLoc();
1182 std::string Name = Lex.getCurStrVal();
1183 if (Lex.Lex() != tgtok::less) // consume the Id.
1184 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1186 // Value ::= ID '<' ValueListNE '>'
1187 if (Lex.Lex() == tgtok::greater) {
1188 TokError("expected non-empty value list");
1192 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1193 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1195 Record *Class = Records.getClass(Name);
1197 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1201 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1202 if (ValueList.empty()) return nullptr;
1204 if (Lex.getCode() != tgtok::greater) {
1205 TokError("expected '>' at end of value list");
1208 Lex.Lex(); // eat the '>'
1209 SMLoc EndLoc = Lex.getLoc();
1211 // Create the new record, set it as CurRec temporarily.
1212 auto NewRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), NameLoc,
1213 Records, /*IsAnonymous=*/true);
1214 Record *NewRec = NewRecOwner.get(); // Keep a copy since we may release.
1215 SubClassReference SCRef;
1216 SCRef.RefRange = SMRange(NameLoc, EndLoc);
1218 SCRef.TemplateArgs = ValueList;
1219 // Add info about the subclass to NewRec.
1220 if (AddSubClass(NewRec, SCRef))
1223 if (!CurMultiClass) {
1224 NewRec->resolveReferences();
1225 Records.addDef(std::move(NewRecOwner));
1227 // This needs to get resolved once the multiclass template arguments are
1228 // known before any use.
1229 NewRec->setResolveFirst(true);
1230 // Otherwise, we're inside a multiclass, add it to the multiclass.
1231 CurMultiClass->DefPrototypes.push_back(std::move(NewRecOwner));
1233 // Copy the template arguments for the multiclass into the def.
1234 for (Init *TArg : CurMultiClass->Rec.getTemplateArgs()) {
1235 const RecordVal *RV = CurMultiClass->Rec.getValue(TArg);
1236 assert(RV && "Template arg doesn't exist?");
1237 NewRec->addValue(*RV);
1240 // We can't return the prototype def here, instead return:
1241 // !cast<ItemType>(!strconcat(NAME, AnonName)).
1242 const RecordVal *MCNameRV = CurMultiClass->Rec.getValue("NAME");
1243 assert(MCNameRV && "multiclass record must have a NAME");
1245 return UnOpInit::get(UnOpInit::CAST,
1246 BinOpInit::get(BinOpInit::STRCONCAT,
1247 VarInit::get(MCNameRV->getName(),
1248 MCNameRV->getType()),
1249 NewRec->getNameInit(),
1250 StringRecTy::get()),
1251 Class->getDefInit()->getType());
1254 // The result of the expression is a reference to the new record.
1255 return DefInit::get(NewRec);
1257 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1258 SMLoc BraceLoc = Lex.getLoc();
1259 Lex.Lex(); // eat the '{'
1260 std::vector<Init*> Vals;
1262 if (Lex.getCode() != tgtok::r_brace) {
1263 Vals = ParseValueList(CurRec);
1264 if (Vals.empty()) return nullptr;
1266 if (Lex.getCode() != tgtok::r_brace) {
1267 TokError("expected '}' at end of bit list value");
1270 Lex.Lex(); // eat the '}'
1272 SmallVector<Init *, 16> NewBits;
1274 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
1275 // first. We'll first read everything in to a vector, then we can reverse
1276 // it to get the bits in the correct order for the BitsInit value.
1277 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1278 // FIXME: The following two loops would not be duplicated
1279 // if the API was a little more orthogonal.
1281 // bits<n> values are allowed to initialize n bits.
1282 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
1283 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
1284 NewBits.push_back(BI->getBit((e - i) - 1));
1287 // bits<n> can also come from variable initializers.
1288 if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
1289 if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
1290 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
1291 NewBits.push_back(VI->getBit((e - i) - 1));
1294 // Fallthrough to try convert this to a bit.
1296 // All other values must be convertible to just a single bit.
1297 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1299 Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
1300 ") is not convertable to a bit");
1303 NewBits.push_back(Bit);
1305 std::reverse(NewBits.begin(), NewBits.end());
1306 return BitsInit::get(NewBits);
1308 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1309 Lex.Lex(); // eat the '['
1310 std::vector<Init*> Vals;
1312 RecTy *DeducedEltTy = nullptr;
1313 ListRecTy *GivenListTy = nullptr;
1316 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1318 TokError(Twine("Type mismatch for list, expected list type, got ") +
1319 ItemType->getAsString());
1322 GivenListTy = ListType;
1325 if (Lex.getCode() != tgtok::r_square) {
1326 Vals = ParseValueList(CurRec, nullptr,
1327 GivenListTy ? GivenListTy->getElementType() : nullptr);
1328 if (Vals.empty()) return nullptr;
1330 if (Lex.getCode() != tgtok::r_square) {
1331 TokError("expected ']' at end of list value");
1334 Lex.Lex(); // eat the ']'
1336 RecTy *GivenEltTy = nullptr;
1337 if (Lex.getCode() == tgtok::less) {
1338 // Optional list element type
1339 Lex.Lex(); // eat the '<'
1341 GivenEltTy = ParseType();
1343 // Couldn't parse element type
1347 if (Lex.getCode() != tgtok::greater) {
1348 TokError("expected '>' at end of list element type");
1351 Lex.Lex(); // eat the '>'
1355 RecTy *EltTy = nullptr;
1356 for (Init *V : Vals) {
1357 TypedInit *TArg = dyn_cast<TypedInit>(V);
1359 TokError("Untyped list element");
1363 EltTy = resolveTypes(EltTy, TArg->getType());
1365 TokError("Incompatible types in list elements");
1369 EltTy = TArg->getType();
1375 // Verify consistency
1376 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1377 TokError("Incompatible types in list elements");
1386 TokError("No type for list");
1389 DeducedEltTy = GivenListTy->getElementType();
1391 // Make sure the deduced type is compatible with the given type
1393 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1394 TokError("Element type mismatch for list");
1398 DeducedEltTy = EltTy;
1401 return ListInit::get(Vals, DeducedEltTy);
1403 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1404 Lex.Lex(); // eat the '('
1405 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1406 TokError("expected identifier in dag init");
1410 Init *Operator = ParseValue(CurRec);
1411 if (!Operator) return nullptr;
1413 // If the operator name is present, parse it.
1414 std::string OperatorName;
1415 if (Lex.getCode() == tgtok::colon) {
1416 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1417 TokError("expected variable name in dag operator");
1420 OperatorName = Lex.getCurStrVal();
1421 Lex.Lex(); // eat the VarName.
1424 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1425 if (Lex.getCode() != tgtok::r_paren) {
1426 DagArgs = ParseDagArgList(CurRec);
1427 if (DagArgs.empty()) return nullptr;
1430 if (Lex.getCode() != tgtok::r_paren) {
1431 TokError("expected ')' in dag init");
1434 Lex.Lex(); // eat the ')'
1436 return DagInit::get(Operator, OperatorName, DagArgs);
1442 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1443 case tgtok::XConcat:
1450 case tgtok::XListConcat:
1451 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1453 case tgtok::XForEach:
1454 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1455 return ParseOperation(CurRec, ItemType);
1462 /// ParseValue - Parse a tblgen value. This returns null on error.
1464 /// Value ::= SimpleValue ValueSuffix*
1465 /// ValueSuffix ::= '{' BitList '}'
1466 /// ValueSuffix ::= '[' BitList ']'
1467 /// ValueSuffix ::= '.' ID
1469 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1470 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1471 if (!Result) return nullptr;
1473 // Parse the suffixes now if present.
1475 switch (Lex.getCode()) {
1476 default: return Result;
1477 case tgtok::l_brace: {
1478 if (Mode == ParseNameMode || Mode == ParseForeachMode)
1479 // This is the beginning of the object body.
1482 SMLoc CurlyLoc = Lex.getLoc();
1483 Lex.Lex(); // eat the '{'
1484 std::vector<unsigned> Ranges = ParseRangeList();
1485 if (Ranges.empty()) return nullptr;
1487 // Reverse the bitlist.
1488 std::reverse(Ranges.begin(), Ranges.end());
1489 Result = Result->convertInitializerBitRange(Ranges);
1491 Error(CurlyLoc, "Invalid bit range for value");
1496 if (Lex.getCode() != tgtok::r_brace) {
1497 TokError("expected '}' at end of bit range list");
1503 case tgtok::l_square: {
1504 SMLoc SquareLoc = Lex.getLoc();
1505 Lex.Lex(); // eat the '['
1506 std::vector<unsigned> Ranges = ParseRangeList();
1507 if (Ranges.empty()) return nullptr;
1509 Result = Result->convertInitListSlice(Ranges);
1511 Error(SquareLoc, "Invalid range for list slice");
1516 if (Lex.getCode() != tgtok::r_square) {
1517 TokError("expected ']' at end of list slice");
1524 if (Lex.Lex() != tgtok::Id) { // eat the .
1525 TokError("expected field identifier after '.'");
1528 if (!Result->getFieldType(Lex.getCurStrVal())) {
1529 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1530 Result->getAsString() + "'");
1533 Result = FieldInit::get(Result, Lex.getCurStrVal());
1534 Lex.Lex(); // eat field name
1538 SMLoc PasteLoc = Lex.getLoc();
1540 // Create a !strconcat() operation, first casting each operand to
1541 // a string if necessary.
1543 TypedInit *LHS = dyn_cast<TypedInit>(Result);
1545 Error(PasteLoc, "LHS of paste is not typed!");
1549 if (LHS->getType() != StringRecTy::get()) {
1550 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1553 TypedInit *RHS = nullptr;
1555 Lex.Lex(); // Eat the '#'.
1556 switch (Lex.getCode()) {
1559 case tgtok::l_brace:
1560 // These are all of the tokens that can begin an object body.
1561 // Some of these can also begin values but we disallow those cases
1562 // because they are unlikely to be useful.
1564 // Trailing paste, concat with an empty string.
1565 RHS = StringInit::get("");
1569 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1570 RHS = dyn_cast<TypedInit>(RHSResult);
1572 Error(PasteLoc, "RHS of paste is not typed!");
1576 if (RHS->getType() != StringRecTy::get()) {
1577 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1583 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1584 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1590 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1592 /// DagArg ::= Value (':' VARNAME)?
1593 /// DagArg ::= VARNAME
1594 /// DagArgList ::= DagArg
1595 /// DagArgList ::= DagArgList ',' DagArg
1596 std::vector<std::pair<llvm::Init*, std::string> >
1597 TGParser::ParseDagArgList(Record *CurRec) {
1598 std::vector<std::pair<llvm::Init*, std::string> > Result;
1601 // DagArg ::= VARNAME
1602 if (Lex.getCode() == tgtok::VarName) {
1603 // A missing value is treated like '?'.
1604 Result.emplace_back(UnsetInit::get(), Lex.getCurStrVal());
1607 // DagArg ::= Value (':' VARNAME)?
1608 Init *Val = ParseValue(CurRec);
1610 return std::vector<std::pair<llvm::Init*, std::string> >();
1612 // If the variable name is present, add it.
1613 std::string VarName;
1614 if (Lex.getCode() == tgtok::colon) {
1615 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1616 TokError("expected variable name in dag literal");
1617 return std::vector<std::pair<llvm::Init*, std::string> >();
1619 VarName = Lex.getCurStrVal();
1620 Lex.Lex(); // eat the VarName.
1623 Result.push_back(std::make_pair(Val, VarName));
1625 if (Lex.getCode() != tgtok::comma) break;
1626 Lex.Lex(); // eat the ','
1633 /// ParseValueList - Parse a comma separated list of values, returning them as a
1634 /// vector. Note that this always expects to be able to parse at least one
1635 /// value. It returns an empty list if this is not possible.
1637 /// ValueList ::= Value (',' Value)
1639 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1641 std::vector<Init*> Result;
1642 RecTy *ItemType = EltTy;
1643 unsigned int ArgN = 0;
1644 if (ArgsRec && !EltTy) {
1645 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
1646 if (TArgs.empty()) {
1647 TokError("template argument provided to non-template class");
1648 return std::vector<Init*>();
1650 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1652 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1655 assert(RV && "Template argument record not found??");
1656 ItemType = RV->getType();
1659 Result.push_back(ParseValue(CurRec, ItemType));
1660 if (!Result.back()) return std::vector<Init*>();
1662 while (Lex.getCode() == tgtok::comma) {
1663 Lex.Lex(); // Eat the comma
1665 if (ArgsRec && !EltTy) {
1666 ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
1667 if (ArgN >= TArgs.size()) {
1668 TokError("too many template arguments");
1669 return std::vector<Init*>();
1671 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1672 assert(RV && "Template argument record not found??");
1673 ItemType = RV->getType();
1676 Result.push_back(ParseValue(CurRec, ItemType));
1677 if (!Result.back()) return std::vector<Init*>();
1684 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1685 /// empty string on error. This can happen in a number of different context's,
1686 /// including within a def or in the template args for a def (which which case
1687 /// CurRec will be non-null) and within the template args for a multiclass (in
1688 /// which case CurRec will be null, but CurMultiClass will be set). This can
1689 /// also happen within a def that is within a multiclass, which will set both
1690 /// CurRec and CurMultiClass.
1692 /// Declaration ::= FIELD? Type ID ('=' Value)?
1694 Init *TGParser::ParseDeclaration(Record *CurRec,
1695 bool ParsingTemplateArgs) {
1696 // Read the field prefix if present.
1697 bool HasField = Lex.getCode() == tgtok::Field;
1698 if (HasField) Lex.Lex();
1700 RecTy *Type = ParseType();
1701 if (!Type) return nullptr;
1703 if (Lex.getCode() != tgtok::Id) {
1704 TokError("Expected identifier in declaration");
1708 SMLoc IdLoc = Lex.getLoc();
1709 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1712 if (ParsingTemplateArgs) {
1714 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1716 assert(CurMultiClass);
1718 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1723 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1726 // If a value is present, parse it.
1727 if (Lex.getCode() == tgtok::equal) {
1729 SMLoc ValLoc = Lex.getLoc();
1730 Init *Val = ParseValue(CurRec, Type);
1732 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1733 // Return the name, even if an error is thrown. This is so that we can
1734 // continue to make some progress, even without the value having been
1742 /// ParseForeachDeclaration - Read a foreach declaration, returning
1743 /// the name of the declared object or a NULL Init on error. Return
1744 /// the name of the parsed initializer list through ForeachListName.
1746 /// ForeachDeclaration ::= ID '=' '[' ValueList ']'
1747 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
1748 /// ForeachDeclaration ::= ID '=' RangePiece
1750 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1751 if (Lex.getCode() != tgtok::Id) {
1752 TokError("Expected identifier in foreach declaration");
1756 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1759 // If a value is present, parse it.
1760 if (Lex.getCode() != tgtok::equal) {
1761 TokError("Expected '=' in foreach declaration");
1764 Lex.Lex(); // Eat the '='
1766 RecTy *IterType = nullptr;
1767 std::vector<unsigned> Ranges;
1769 switch (Lex.getCode()) {
1770 default: TokError("Unknown token when expecting a range list"); return nullptr;
1771 case tgtok::l_square: { // '[' ValueList ']'
1772 Init *List = ParseSimpleValue(nullptr, nullptr, ParseForeachMode);
1773 ForeachListValue = dyn_cast<ListInit>(List);
1774 if (!ForeachListValue) {
1775 TokError("Expected a Value list");
1778 RecTy *ValueType = ForeachListValue->getType();
1779 ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1781 TokError("Value list is not of list type");
1784 IterType = ListType->getElementType();
1788 case tgtok::IntVal: { // RangePiece.
1789 if (ParseRangePiece(Ranges))
1794 case tgtok::l_brace: { // '{' RangeList '}'
1795 Lex.Lex(); // eat the '{'
1796 Ranges = ParseRangeList();
1797 if (Lex.getCode() != tgtok::r_brace) {
1798 TokError("expected '}' at end of bit range list");
1806 if (!Ranges.empty()) {
1807 assert(!IterType && "Type already initialized?");
1808 IterType = IntRecTy::get();
1809 std::vector<Init*> Values;
1810 for (unsigned R : Ranges)
1811 Values.push_back(IntInit::get(R));
1812 ForeachListValue = ListInit::get(Values, IterType);
1818 return VarInit::get(DeclName, IterType);
1821 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1822 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1823 /// template args for a def, which may or may not be in a multiclass. If null,
1824 /// these are the template args for a multiclass.
1826 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1828 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1829 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1830 Lex.Lex(); // eat the '<'
1832 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1834 // Read the first declaration.
1835 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1839 TheRecToAddTo->addTemplateArg(TemplArg);
1841 while (Lex.getCode() == tgtok::comma) {
1842 Lex.Lex(); // eat the ','
1844 // Read the following declarations.
1845 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1848 TheRecToAddTo->addTemplateArg(TemplArg);
1851 if (Lex.getCode() != tgtok::greater)
1852 return TokError("expected '>' at end of template argument list");
1853 Lex.Lex(); // eat the '>'.
1858 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1860 /// BodyItem ::= Declaration ';'
1861 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1862 bool TGParser::ParseBodyItem(Record *CurRec) {
1863 if (Lex.getCode() != tgtok::Let) {
1864 if (!ParseDeclaration(CurRec, false))
1867 if (Lex.getCode() != tgtok::semi)
1868 return TokError("expected ';' after declaration");
1873 // LET ID OptionalRangeList '=' Value ';'
1874 if (Lex.Lex() != tgtok::Id)
1875 return TokError("expected field identifier after let");
1877 SMLoc IdLoc = Lex.getLoc();
1878 std::string FieldName = Lex.getCurStrVal();
1879 Lex.Lex(); // eat the field name.
1881 std::vector<unsigned> BitList;
1882 if (ParseOptionalBitList(BitList))
1884 std::reverse(BitList.begin(), BitList.end());
1886 if (Lex.getCode() != tgtok::equal)
1887 return TokError("expected '=' in let expression");
1888 Lex.Lex(); // eat the '='.
1890 RecordVal *Field = CurRec->getValue(FieldName);
1892 return TokError("Value '" + FieldName + "' unknown!");
1894 RecTy *Type = Field->getType();
1896 Init *Val = ParseValue(CurRec, Type);
1897 if (!Val) return true;
1899 if (Lex.getCode() != tgtok::semi)
1900 return TokError("expected ';' after let expression");
1903 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1906 /// ParseBody - Read the body of a class or def. Return true on error, false on
1910 /// Body ::= '{' BodyList '}'
1911 /// BodyList BodyItem*
1913 bool TGParser::ParseBody(Record *CurRec) {
1914 // If this is a null definition, just eat the semi and return.
1915 if (Lex.getCode() == tgtok::semi) {
1920 if (Lex.getCode() != tgtok::l_brace)
1921 return TokError("Expected ';' or '{' to start body");
1925 while (Lex.getCode() != tgtok::r_brace)
1926 if (ParseBodyItem(CurRec))
1934 /// \brief Apply the current let bindings to \a CurRec.
1935 /// \returns true on error, false otherwise.
1936 bool TGParser::ApplyLetStack(Record *CurRec) {
1937 for (std::vector<LetRecord> &LetInfo : LetStack)
1938 for (LetRecord &LR : LetInfo)
1939 if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
1944 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1945 /// optional ClassList followed by a Body. CurRec is the current def or class
1946 /// that is being parsed.
1948 /// ObjectBody ::= BaseClassList Body
1949 /// BaseClassList ::= /*empty*/
1950 /// BaseClassList ::= ':' BaseClassListNE
1951 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1953 bool TGParser::ParseObjectBody(Record *CurRec) {
1954 // If there is a baseclass list, read it.
1955 if (Lex.getCode() == tgtok::colon) {
1958 // Read all of the subclasses.
1959 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1962 if (!SubClass.Rec) return true;
1965 if (AddSubClass(CurRec, SubClass))
1968 if (Lex.getCode() != tgtok::comma) break;
1969 Lex.Lex(); // eat ','.
1970 SubClass = ParseSubClassReference(CurRec, false);
1974 if (ApplyLetStack(CurRec))
1977 return ParseBody(CurRec);
1980 /// ParseDef - Parse and return a top level or multiclass def, return the record
1981 /// corresponding to it. This returns null on error.
1983 /// DefInst ::= DEF ObjectName ObjectBody
1985 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1986 SMLoc DefLoc = Lex.getLoc();
1987 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1988 Lex.Lex(); // Eat the 'def' token.
1990 // Parse ObjectName and make a record for it.
1991 std::unique_ptr<Record> CurRecOwner;
1992 Init *Name = ParseObjectName(CurMultiClass);
1994 CurRecOwner = make_unique<Record>(Name, DefLoc, Records);
1996 CurRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), DefLoc,
1997 Records, /*IsAnonymous=*/true);
1998 Record *CurRec = CurRecOwner.get(); // Keep a copy since we may release.
2000 if (!CurMultiClass && Loops.empty()) {
2001 // Top-level def definition.
2003 // Ensure redefinition doesn't happen.
2004 if (Records.getDef(CurRec->getNameInitAsString()))
2005 return Error(DefLoc, "def '" + CurRec->getNameInitAsString()+
2006 "' already defined");
2007 Records.addDef(std::move(CurRecOwner));
2009 if (ParseObjectBody(CurRec))
2011 } else if (CurMultiClass) {
2012 // Parse the body before adding this prototype to the DefPrototypes vector.
2013 // That way implicit definitions will be added to the DefPrototypes vector
2014 // before this object, instantiated prior to defs derived from this object,
2015 // and this available for indirect name resolution when defs derived from
2016 // this object are instantiated.
2017 if (ParseObjectBody(CurRec))
2020 // Otherwise, a def inside a multiclass, add it to the multiclass.
2021 for (const auto &Proto : CurMultiClass->DefPrototypes)
2022 if (Proto->getNameInit() == CurRec->getNameInit())
2023 return Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
2024 "' already defined in this multiclass!");
2025 CurMultiClass->DefPrototypes.push_back(std::move(CurRecOwner));
2026 } else if (ParseObjectBody(CurRec)) {
2030 if (!CurMultiClass) // Def's in multiclasses aren't really defs.
2031 // See Record::setName(). This resolve step will see any new name
2032 // for the def that might have been created when resolving
2033 // inheritance, values and arguments above.
2034 CurRec->resolveReferences();
2036 // If ObjectBody has template arguments, it's an error.
2037 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
2039 if (CurMultiClass) {
2040 // Copy the template arguments for the multiclass into the def.
2041 for (Init *TArg : CurMultiClass->Rec.getTemplateArgs()) {
2042 const RecordVal *RV = CurMultiClass->Rec.getValue(TArg);
2043 assert(RV && "Template arg doesn't exist?");
2044 CurRec->addValue(*RV);
2048 if (ProcessForeachDefs(CurRec, DefLoc))
2049 return Error(DefLoc, "Could not process loops for def" +
2050 CurRec->getNameInitAsString());
2055 /// ParseForeach - Parse a for statement. Return the record corresponding
2056 /// to it. This returns true on error.
2058 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2059 /// Foreach ::= FOREACH Declaration IN Object
2061 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2062 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2063 Lex.Lex(); // Eat the 'for' token.
2065 // Make a temporary object to record items associated with the for
2067 ListInit *ListValue = nullptr;
2068 VarInit *IterName = ParseForeachDeclaration(ListValue);
2070 return TokError("expected declaration in for");
2072 if (Lex.getCode() != tgtok::In)
2073 return TokError("Unknown tok");
2074 Lex.Lex(); // Eat the in
2076 // Create a loop object and remember it.
2077 Loops.push_back(ForeachLoop(IterName, ListValue));
2079 if (Lex.getCode() != tgtok::l_brace) {
2080 // FOREACH Declaration IN Object
2081 if (ParseObject(CurMultiClass))
2084 SMLoc BraceLoc = Lex.getLoc();
2085 // Otherwise, this is a group foreach.
2086 Lex.Lex(); // eat the '{'.
2088 // Parse the object list.
2089 if (ParseObjectList(CurMultiClass))
2092 if (Lex.getCode() != tgtok::r_brace) {
2093 TokError("expected '}' at end of foreach command");
2094 return Error(BraceLoc, "to match this '{'");
2096 Lex.Lex(); // Eat the }
2099 // We've processed everything in this loop.
2105 /// ParseClass - Parse a tblgen class definition.
2107 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2109 bool TGParser::ParseClass() {
2110 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2113 if (Lex.getCode() != tgtok::Id)
2114 return TokError("expected class name after 'class' keyword");
2116 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2118 // If the body was previously defined, this is an error.
2119 if (CurRec->getValues().size() > 1 || // Account for NAME.
2120 !CurRec->getSuperClasses().empty() ||
2121 !CurRec->getTemplateArgs().empty())
2122 return TokError("Class '" + CurRec->getNameInitAsString() +
2123 "' already defined");
2125 // If this is the first reference to this class, create and add it.
2127 llvm::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records);
2128 CurRec = NewRec.get();
2129 Records.addClass(std::move(NewRec));
2131 Lex.Lex(); // eat the name.
2133 // If there are template args, parse them.
2134 if (Lex.getCode() == tgtok::less)
2135 if (ParseTemplateArgList(CurRec))
2138 // Finally, parse the object body.
2139 return ParseObjectBody(CurRec);
2142 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2145 /// LetList ::= LetItem (',' LetItem)*
2146 /// LetItem ::= ID OptionalRangeList '=' Value
2148 std::vector<LetRecord> TGParser::ParseLetList() {
2149 std::vector<LetRecord> Result;
2152 if (Lex.getCode() != tgtok::Id) {
2153 TokError("expected identifier in let definition");
2154 return std::vector<LetRecord>();
2156 std::string Name = Lex.getCurStrVal();
2157 SMLoc NameLoc = Lex.getLoc();
2158 Lex.Lex(); // Eat the identifier.
2160 // Check for an optional RangeList.
2161 std::vector<unsigned> Bits;
2162 if (ParseOptionalRangeList(Bits))
2163 return std::vector<LetRecord>();
2164 std::reverse(Bits.begin(), Bits.end());
2166 if (Lex.getCode() != tgtok::equal) {
2167 TokError("expected '=' in let expression");
2168 return std::vector<LetRecord>();
2170 Lex.Lex(); // eat the '='.
2172 Init *Val = ParseValue(nullptr);
2173 if (!Val) return std::vector<LetRecord>();
2175 // Now that we have everything, add the record.
2176 Result.emplace_back(std::move(Name), std::move(Bits), Val, NameLoc);
2178 if (Lex.getCode() != tgtok::comma)
2180 Lex.Lex(); // eat the comma.
2184 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2185 /// different related productions. This works inside multiclasses too.
2187 /// Object ::= LET LetList IN '{' ObjectList '}'
2188 /// Object ::= LET LetList IN Object
2190 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2191 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2194 // Add this entry to the let stack.
2195 std::vector<LetRecord> LetInfo = ParseLetList();
2196 if (LetInfo.empty()) return true;
2197 LetStack.push_back(std::move(LetInfo));
2199 if (Lex.getCode() != tgtok::In)
2200 return TokError("expected 'in' at end of top-level 'let'");
2203 // If this is a scalar let, just handle it now
2204 if (Lex.getCode() != tgtok::l_brace) {
2205 // LET LetList IN Object
2206 if (ParseObject(CurMultiClass))
2208 } else { // Object ::= LETCommand '{' ObjectList '}'
2209 SMLoc BraceLoc = Lex.getLoc();
2210 // Otherwise, this is a group let.
2211 Lex.Lex(); // eat the '{'.
2213 // Parse the object list.
2214 if (ParseObjectList(CurMultiClass))
2217 if (Lex.getCode() != tgtok::r_brace) {
2218 TokError("expected '}' at end of top level let command");
2219 return Error(BraceLoc, "to match this '{'");
2224 // Outside this let scope, this let block is not active.
2225 LetStack.pop_back();
2229 /// ParseMultiClass - Parse a multiclass definition.
2231 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2232 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
2233 /// MultiClassObject ::= DefInst
2234 /// MultiClassObject ::= MultiClassInst
2235 /// MultiClassObject ::= DefMInst
2236 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
2237 /// MultiClassObject ::= LETCommand Object
2239 bool TGParser::ParseMultiClass() {
2240 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2241 Lex.Lex(); // Eat the multiclass token.
2243 if (Lex.getCode() != tgtok::Id)
2244 return TokError("expected identifier after multiclass for name");
2245 std::string Name = Lex.getCurStrVal();
2248 MultiClasses.insert(std::make_pair(Name,
2249 llvm::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
2252 return TokError("multiclass '" + Name + "' already defined");
2254 CurMultiClass = Result.first->second.get();
2255 Lex.Lex(); // Eat the identifier.
2257 // If there are template args, parse them.
2258 if (Lex.getCode() == tgtok::less)
2259 if (ParseTemplateArgList(nullptr))
2262 bool inherits = false;
2264 // If there are submulticlasses, parse them.
2265 if (Lex.getCode() == tgtok::colon) {
2270 // Read all of the submulticlasses.
2271 SubMultiClassReference SubMultiClass =
2272 ParseSubMultiClassReference(CurMultiClass);
2275 if (!SubMultiClass.MC) return true;
2278 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2281 if (Lex.getCode() != tgtok::comma) break;
2282 Lex.Lex(); // eat ','.
2283 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2287 if (Lex.getCode() != tgtok::l_brace) {
2289 return TokError("expected '{' in multiclass definition");
2290 if (Lex.getCode() != tgtok::semi)
2291 return TokError("expected ';' in multiclass definition");
2292 Lex.Lex(); // eat the ';'.
2294 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2295 return TokError("multiclass must contain at least one def");
2297 while (Lex.getCode() != tgtok::r_brace) {
2298 switch (Lex.getCode()) {
2300 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2304 case tgtok::Foreach:
2305 if (ParseObject(CurMultiClass))
2310 Lex.Lex(); // eat the '}'.
2313 CurMultiClass = nullptr;
2317 Record *TGParser::InstantiateMulticlassDef(MultiClass &MC, Record *DefProto,
2319 SMRange DefmPrefixRange,
2320 ArrayRef<Init *> TArgs,
2321 std::vector<Init *> &TemplateVals) {
2322 // We need to preserve DefProto so it can be reused for later
2323 // instantiations, so create a new Record to inherit from it.
2325 // Add in the defm name. If the defm prefix is empty, give each
2326 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2327 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2330 bool IsAnonymous = false;
2332 DefmPrefix = StringInit::get(GetNewAnonymousName());
2336 Init *DefName = DefProto->getNameInit();
2337 StringInit *DefNameString = dyn_cast<StringInit>(DefName);
2339 if (DefNameString) {
2340 // We have a fully expanded string so there are no operators to
2341 // resolve. We should concatenate the given prefix and name.
2343 BinOpInit::get(BinOpInit::STRCONCAT,
2344 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2345 StringRecTy::get())->Fold(DefProto, &MC),
2346 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2349 // Make a trail of SMLocs from the multiclass instantiations.
2350 SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
2351 Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2352 auto CurRec = make_unique<Record>(DefName, Locs, Records, IsAnonymous);
2354 SubClassReference Ref;
2355 Ref.RefRange = DefmPrefixRange;
2357 AddSubClass(CurRec.get(), Ref);
2359 // Set the value for NAME. We don't resolve references to it 'til later,
2360 // though, so that uses in nested multiclass names don't get
2362 if (SetValue(CurRec.get(), Ref.RefRange.Start, "NAME",
2363 std::vector<unsigned>(), DefmPrefix,
2364 /*AllowSelfAssignment*/true)) {
2365 Error(DefmPrefixRange.Start, "Could not resolve " +
2366 CurRec->getNameInitAsString() + ":NAME to '" +
2367 DefmPrefix->getAsUnquotedString() + "'");
2371 // If the DefNameString didn't resolve, we probably have a reference to
2372 // NAME and need to replace it. We need to do at least this much greedily,
2373 // otherwise nested multiclasses will end up with incorrect NAME expansions.
2374 if (!DefNameString) {
2375 RecordVal *DefNameRV = CurRec->getValue("NAME");
2376 CurRec->resolveReferencesTo(DefNameRV);
2379 if (!CurMultiClass) {
2380 // Now that we're at the top level, resolve all NAME references
2381 // in the resultant defs that weren't in the def names themselves.
2382 RecordVal *DefNameRV = CurRec->getValue("NAME");
2383 CurRec->resolveReferencesTo(DefNameRV);
2385 // Check if the name is a complex pattern.
2386 // If so, resolve it.
2387 DefName = CurRec->getNameInit();
2388 DefNameString = dyn_cast<StringInit>(DefName);
2390 // OK the pattern is more complex than simply using NAME.
2391 // Let's use the heavy weaponery.
2392 if (!DefNameString) {
2393 ResolveMulticlassDefArgs(MC, CurRec.get(), DefmPrefixRange.Start,
2394 Lex.getLoc(), TArgs, TemplateVals,
2395 false/*Delete args*/);
2396 DefName = CurRec->getNameInit();
2397 DefNameString = dyn_cast<StringInit>(DefName);
2400 DefName = DefName->convertInitializerTo(StringRecTy::get());
2402 // We ran out of options here...
2403 DefNameString = dyn_cast<StringInit>(DefName);
2404 if (!DefNameString) {
2405 PrintFatalError(CurRec->getLoc()[CurRec->getLoc().size() - 1],
2406 DefName->getAsUnquotedString() + " is not a string.");
2410 CurRec->setName(DefName);
2413 // Now that NAME references are resolved and we're at the top level of
2414 // any multiclass expansions, add the record to the RecordKeeper. If we are
2415 // currently in a multiclass, it means this defm appears inside a
2416 // multiclass and its name won't be fully resolvable until we see
2417 // the top-level defm. Therefore, we don't add this to the
2418 // RecordKeeper at this point. If we did we could get duplicate
2419 // defs as more than one probably refers to NAME or some other
2420 // common internal placeholder.
2422 // Ensure redefinition doesn't happen.
2423 if (Records.getDef(CurRec->getNameInitAsString())) {
2424 Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
2425 "' already defined, instantiating defm with subdef '" +
2426 DefProto->getNameInitAsString() + "'");
2430 Record *CurRecSave = CurRec.get(); // Keep a copy before we release.
2431 Records.addDef(std::move(CurRec));
2435 // FIXME This is bad but the ownership transfer to caller is pretty messy.
2436 // The unique_ptr in this function at least protects the exits above.
2437 return CurRec.release();
2440 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC, Record *CurRec,
2441 SMLoc DefmPrefixLoc, SMLoc SubClassLoc,
2442 ArrayRef<Init *> TArgs,
2443 std::vector<Init *> &TemplateVals,
2445 // Loop over all of the template arguments, setting them to the specified
2446 // value or leaving them as the default if necessary.
2447 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2448 // Check if a value is specified for this temp-arg.
2449 if (i < TemplateVals.size()) {
2451 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2456 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2460 CurRec->removeValue(TArgs[i]);
2462 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2463 return Error(SubClassLoc, "value not specified for template argument #" +
2464 Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
2465 ") of multiclassclass '" + MC.Rec.getNameInitAsString() +
2472 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2475 SMLoc DefmPrefixLoc) {
2476 // If the mdef is inside a 'let' expression, add to each def.
2477 if (ApplyLetStack(CurRec))
2478 return Error(DefmPrefixLoc, "when instantiating this defm");
2480 // Don't create a top level definition for defm inside multiclasses,
2481 // instead, only update the prototypes and bind the template args
2482 // with the new created definition.
2485 for (const auto &Proto : CurMultiClass->DefPrototypes)
2486 if (Proto->getNameInit() == CurRec->getNameInit())
2487 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2488 "' already defined in this multiclass!");
2489 CurMultiClass->DefPrototypes.push_back(std::unique_ptr<Record>(CurRec));
2491 // Copy the template arguments for the multiclass into the new def.
2492 for (Init * TA : CurMultiClass->Rec.getTemplateArgs()) {
2493 const RecordVal *RV = CurMultiClass->Rec.getValue(TA);
2494 assert(RV && "Template arg doesn't exist?");
2495 CurRec->addValue(*RV);
2501 /// ParseDefm - Parse the instantiation of a multiclass.
2503 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2505 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2506 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2507 SMLoc DefmLoc = Lex.getLoc();
2508 Init *DefmPrefix = nullptr;
2510 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2511 DefmPrefix = ParseObjectName(CurMultiClass);
2514 SMLoc DefmPrefixEndLoc = Lex.getLoc();
2515 if (Lex.getCode() != tgtok::colon)
2516 return TokError("expected ':' after defm identifier");
2518 // Keep track of the new generated record definitions.
2519 std::vector<Record*> NewRecDefs;
2521 // This record also inherits from a regular class (non-multiclass)?
2522 bool InheritFromClass = false;
2527 SMLoc SubClassLoc = Lex.getLoc();
2528 SubClassReference Ref = ParseSubClassReference(nullptr, true);
2531 if (!Ref.Rec) return true;
2533 // To instantiate a multiclass, we need to first get the multiclass, then
2534 // instantiate each def contained in the multiclass with the SubClassRef
2535 // template parameters.
2536 MultiClass *MC = MultiClasses[Ref.Rec->getName()].get();
2537 assert(MC && "Didn't lookup multiclass correctly?");
2538 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2540 // Verify that the correct number of template arguments were specified.
2541 ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs();
2542 if (TArgs.size() < TemplateVals.size())
2543 return Error(SubClassLoc,
2544 "more template args specified than multiclass expects");
2546 // Loop over all the def's in the multiclass, instantiating each one.
2547 for (const std::unique_ptr<Record> &DefProto : MC->DefPrototypes) {
2548 // The record name construction goes as follow:
2549 // - If the def name is a string, prepend the prefix.
2550 // - If the def name is a more complex pattern, use that pattern.
2551 // As a result, the record is instanciated before resolving
2552 // arguments, as it would make its name a string.
2553 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto.get(), DefmPrefix,
2556 TArgs, TemplateVals);
2560 // Now that the record is instanciated, we can resolve arguments.
2561 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
2562 TArgs, TemplateVals, true/*Delete args*/))
2563 return Error(SubClassLoc, "could not instantiate def");
2565 if (ResolveMulticlassDef(*MC, CurRec, DefProto.get(), DefmLoc))
2566 return Error(SubClassLoc, "could not instantiate def");
2568 // Defs that can be used by other definitions should be fully resolved
2570 if (DefProto->isResolveFirst() && !CurMultiClass) {
2571 CurRec->resolveReferences();
2572 CurRec->setResolveFirst(false);
2574 NewRecDefs.push_back(CurRec);
2578 if (Lex.getCode() != tgtok::comma) break;
2579 Lex.Lex(); // eat ','.
2581 if (Lex.getCode() != tgtok::Id)
2582 return TokError("expected identifier");
2584 SubClassLoc = Lex.getLoc();
2586 // A defm can inherit from regular classes (non-multiclass) as
2587 // long as they come in the end of the inheritance list.
2588 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
2590 if (InheritFromClass)
2593 Ref = ParseSubClassReference(nullptr, true);
2596 if (InheritFromClass) {
2597 // Process all the classes to inherit as if they were part of a
2598 // regular 'def' and inherit all record values.
2599 SubClassReference SubClass = ParseSubClassReference(nullptr, false);
2602 if (!SubClass.Rec) return true;
2604 // Get the expanded definition prototypes and teach them about
2605 // the record values the current class to inherit has
2606 for (Record *CurRec : NewRecDefs) {
2608 if (AddSubClass(CurRec, SubClass))
2611 if (ApplyLetStack(CurRec))
2615 if (Lex.getCode() != tgtok::comma) break;
2616 Lex.Lex(); // eat ','.
2617 SubClass = ParseSubClassReference(nullptr, false);
2622 for (Record *CurRec : NewRecDefs)
2623 // See Record::setName(). This resolve step will see any new
2624 // name for the def that might have been created when resolving
2625 // inheritance, values and arguments above.
2626 CurRec->resolveReferences();
2628 if (Lex.getCode() != tgtok::semi)
2629 return TokError("expected ';' at end of defm");
2636 /// Object ::= ClassInst
2637 /// Object ::= DefInst
2638 /// Object ::= MultiClassInst
2639 /// Object ::= DefMInst
2640 /// Object ::= LETCommand '{' ObjectList '}'
2641 /// Object ::= LETCommand Object
2642 bool TGParser::ParseObject(MultiClass *MC) {
2643 switch (Lex.getCode()) {
2645 return TokError("Expected class, def, defm, multiclass or let definition");
2646 case tgtok::Let: return ParseTopLevelLet(MC);
2647 case tgtok::Def: return ParseDef(MC);
2648 case tgtok::Foreach: return ParseForeach(MC);
2649 case tgtok::Defm: return ParseDefm(MC);
2650 case tgtok::Class: return ParseClass();
2651 case tgtok::MultiClass: return ParseMultiClass();
2656 /// ObjectList :== Object*
2657 bool TGParser::ParseObjectList(MultiClass *MC) {
2658 while (isObjectStart(Lex.getCode())) {
2659 if (ParseObject(MC))
2665 bool TGParser::ParseFile() {
2666 Lex.Lex(); // Prime the lexer.
2667 if (ParseObjectList()) return true;
2669 // If we have unread input at the end of the file, report it.
2670 if (Lex.getCode() == tgtok::Eof)
2673 return TokError("Unexpected input at top level");