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/SmallVector.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/TableGen/Record.h"
23 //===----------------------------------------------------------------------===//
24 // Support Code for the Semantic Actions.
25 //===----------------------------------------------------------------------===//
28 struct SubClassReference {
31 std::vector<Init*> TemplateArgs;
32 SubClassReference() : Rec(nullptr) {}
34 bool isInvalid() const { return Rec == nullptr; }
37 struct SubMultiClassReference {
40 std::vector<Init*> TemplateArgs;
41 SubMultiClassReference() : MC(nullptr) {}
43 bool isInvalid() const { return MC == nullptr; }
47 void SubMultiClassReference::dump() const {
48 errs() << "Multiclass:\n";
52 errs() << "Template args:\n";
53 for (std::vector<Init *>::const_iterator i = TemplateArgs.begin(),
54 iend = TemplateArgs.end();
61 } // end namespace llvm
63 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
65 CurRec = &CurMultiClass->Rec;
67 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
68 // The value already exists in the class, treat this as a set.
69 if (ERV->setValue(RV.getValue()))
70 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
71 RV.getType()->getAsString() + "' is incompatible with " +
72 "previous definition of type '" +
73 ERV->getType()->getAsString() + "'");
81 /// Return true on error, false on success.
82 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
83 const std::vector<unsigned> &BitList, Init *V) {
86 if (!CurRec) CurRec = &CurMultiClass->Rec;
88 RecordVal *RV = CurRec->getValue(ValName);
90 return Error(Loc, "Value '" + ValName->getAsUnquotedString()
93 // Do not allow assignments like 'X = X'. This will just cause infinite loops
94 // in the resolution machinery.
96 if (VarInit *VI = dyn_cast<VarInit>(V))
97 if (VI->getNameInit() == ValName)
100 // If we are assigning to a subset of the bits in the value... then we must be
101 // assigning to a field of BitsRecTy, which must have a BitsInit
104 if (!BitList.empty()) {
105 BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
107 return Error(Loc, "Value '" + ValName->getAsUnquotedString()
108 + "' is not a bits type");
110 // Convert the incoming value to a bits type of the appropriate size...
111 Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size()));
113 return Error(Loc, "Initializer is not compatible with bit range");
116 // We should have a BitsInit type now.
117 BitsInit *BInit = dyn_cast<BitsInit>(BI);
118 assert(BInit != nullptr);
120 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
122 // Loop over bits, assigning values as appropriate.
123 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
124 unsigned Bit = BitList[i];
126 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
127 ValName->getAsUnquotedString() + "' more than once");
128 NewBits[Bit] = BInit->getBit(i);
131 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
133 NewBits[i] = CurVal->getBit(i);
135 V = BitsInit::get(NewBits);
138 if (RV->setValue(V)) {
139 std::string InitType = "";
140 if (BitsInit *BI = dyn_cast<BitsInit>(V)) {
141 InitType = (Twine("' of type bit initializer with length ") +
142 Twine(BI->getNumBits())).str();
144 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + "' of type '"
145 + RV->getType()->getAsString() +
146 "' is incompatible with initializer '" + V->getAsString()
153 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
154 /// args as SubClass's template arguments.
155 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
156 Record *SC = SubClass.Rec;
157 // Add all of the values in the subclass into the current class.
158 const std::vector<RecordVal> &Vals = SC->getValues();
159 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
160 if (AddValue(CurRec, SubClass.RefRange.Start, Vals[i]))
163 const std::vector<Init *> &TArgs = SC->getTemplateArgs();
165 // Ensure that an appropriate number of template arguments are specified.
166 if (TArgs.size() < SubClass.TemplateArgs.size())
167 return Error(SubClass.RefRange.Start,
168 "More template args specified than expected");
170 // Loop over all of the template arguments, setting them to the specified
171 // value or leaving them as the default if necessary.
172 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
173 if (i < SubClass.TemplateArgs.size()) {
174 // If a value is specified for this template arg, set it now.
175 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
176 std::vector<unsigned>(), SubClass.TemplateArgs[i]))
180 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
183 CurRec->removeValue(TArgs[i]);
185 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
186 return Error(SubClass.RefRange.Start,
187 "Value not specified for template argument #"
188 + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
189 + ") of subclass '" + SC->getNameInitAsString() + "'!");
193 // Since everything went well, we can now set the "superclass" list for the
195 const std::vector<Record*> &SCs = SC->getSuperClasses();
196 ArrayRef<SMRange> SCRanges = SC->getSuperClassRanges();
197 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
198 if (CurRec->isSubClassOf(SCs[i]))
199 return Error(SubClass.RefRange.Start,
200 "Already subclass of '" + SCs[i]->getName() + "'!\n");
201 CurRec->addSuperClass(SCs[i], SCRanges[i]);
204 if (CurRec->isSubClassOf(SC))
205 return Error(SubClass.RefRange.Start,
206 "Already subclass of '" + SC->getName() + "'!\n");
207 CurRec->addSuperClass(SC, SubClass.RefRange);
211 /// AddSubMultiClass - Add SubMultiClass as a subclass to
212 /// CurMC, resolving its template args as SubMultiClass's
213 /// template arguments.
214 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
215 SubMultiClassReference &SubMultiClass) {
216 MultiClass *SMC = SubMultiClass.MC;
217 Record *CurRec = &CurMC->Rec;
219 const std::vector<RecordVal> &MCVals = CurRec->getValues();
221 // Add all of the values in the subclass into the current class.
222 const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
223 for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
224 if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVals[i]))
227 unsigned newDefStart = CurMC->DefPrototypes.size();
229 // Add all of the defs in the subclass into the current multiclass.
230 for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
231 iend = SMC->DefPrototypes.end();
234 // Clone the def and add it to the current multiclass
235 auto NewDef = make_unique<Record>(**i);
237 // Add all of the values in the superclass into the current def.
238 for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
239 if (AddValue(NewDef.get(), SubMultiClass.RefRange.Start, MCVals[i]))
242 CurMC->DefPrototypes.push_back(std::move(NewDef));
245 const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
247 // Ensure that an appropriate number of template arguments are
249 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
250 return Error(SubMultiClass.RefRange.Start,
251 "More template args specified than expected");
253 // Loop over all of the template arguments, setting them to the specified
254 // value or leaving them as the default if necessary.
255 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
256 if (i < SubMultiClass.TemplateArgs.size()) {
257 // If a value is specified for this template arg, set it in the
259 if (SetValue(CurRec, SubMultiClass.RefRange.Start, SMCTArgs[i],
260 std::vector<unsigned>(),
261 SubMultiClass.TemplateArgs[i]))
265 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
268 CurRec->removeValue(SMCTArgs[i]);
270 // If a value is specified for this template arg, set it in the
272 for (MultiClass::RecordVector::iterator j =
273 CurMC->DefPrototypes.begin() + newDefStart,
274 jend = CurMC->DefPrototypes.end();
277 Record *Def = j->get();
279 if (SetValue(Def, SubMultiClass.RefRange.Start, SMCTArgs[i],
280 std::vector<unsigned>(),
281 SubMultiClass.TemplateArgs[i]))
285 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
288 Def->removeValue(SMCTArgs[i]);
290 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
291 return Error(SubMultiClass.RefRange.Start,
292 "Value not specified for template argument #"
293 + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
294 + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
301 /// ProcessForeachDefs - Given a record, apply all of the variable
302 /// values in all surrounding foreach loops, creating new records for
303 /// each combination of values.
304 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
308 // We want to instantiate a new copy of CurRec for each combination
309 // of nested loop iterator values. We don't want top instantiate
310 // any copies until we have values for each loop iterator.
312 return ProcessForeachDefs(CurRec, Loc, IterVals);
315 /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
316 /// apply each of the variable values in this loop and then process
318 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
319 // Recursively build a tuple of iterator values.
320 if (IterVals.size() != Loops.size()) {
321 assert(IterVals.size() < Loops.size());
322 ForeachLoop &CurLoop = Loops[IterVals.size()];
323 ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
325 Error(Loc, "Loop list is not a list");
329 // Process each value.
330 for (int64_t i = 0; i < List->getSize(); ++i) {
331 Init *ItemVal = List->resolveListElementReference(*CurRec, nullptr, i);
332 IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
333 if (ProcessForeachDefs(CurRec, Loc, IterVals))
340 // This is the bottom of the recursion. We have all of the iterator values
341 // for this point in the iteration space. Instantiate a new record to
342 // reflect this combination of values.
343 auto IterRec = make_unique<Record>(*CurRec);
345 // Set the iterator values now.
346 for (unsigned i = 0, e = IterVals.size(); i != e; ++i) {
347 VarInit *IterVar = IterVals[i].IterVar;
348 TypedInit *IVal = dyn_cast<TypedInit>(IterVals[i].IterValue);
350 return Error(Loc, "foreach iterator value is untyped");
352 IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
354 if (SetValue(IterRec.get(), Loc, IterVar->getName(),
355 std::vector<unsigned>(), IVal))
356 return Error(Loc, "when instantiating this def");
359 IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
362 IterRec->removeValue(IterVar->getName());
365 if (Records.getDef(IterRec->getNameInitAsString())) {
366 // If this record is anonymous, it's no problem, just generate a new name
367 if (!IterRec->isAnonymous())
368 return Error(Loc, "def already exists: " +IterRec->getNameInitAsString());
370 IterRec->setName(GetNewAnonymousName());
373 Record *IterRecSave = IterRec.get(); // Keep a copy before release.
374 Records.addDef(std::move(IterRec));
375 IterRecSave->resolveReferences();
379 //===----------------------------------------------------------------------===//
381 //===----------------------------------------------------------------------===//
383 /// isObjectStart - Return true if this is a valid first token for an Object.
384 static bool isObjectStart(tgtok::TokKind K) {
385 return K == tgtok::Class || K == tgtok::Def ||
386 K == tgtok::Defm || K == tgtok::Let ||
387 K == tgtok::MultiClass || K == tgtok::Foreach;
390 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
392 std::string TGParser::GetNewAnonymousName() {
393 unsigned Tmp = AnonCounter++; // MSVC2012 ICEs without this.
394 return "anonymous_" + utostr(Tmp);
397 /// ParseObjectName - If an object name is specified, return it. Otherwise,
399 /// ObjectName ::= Value [ '#' Value ]*
400 /// ObjectName ::= /*empty*/
402 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
403 switch (Lex.getCode()) {
407 // These are all of the tokens that can begin an object body.
408 // Some of these can also begin values but we disallow those cases
409 // because they are unlikely to be useful.
415 Record *CurRec = nullptr;
417 CurRec = &CurMultiClass->Rec;
419 RecTy *Type = nullptr;
421 const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
423 TokError("Record name is not typed!");
426 Type = CurRecName->getType();
429 return ParseValue(CurRec, Type, ParseNameMode);
432 /// ParseClassID - Parse and resolve a reference to a class name. This returns
437 Record *TGParser::ParseClassID() {
438 if (Lex.getCode() != tgtok::Id) {
439 TokError("expected name for ClassID");
443 Record *Result = Records.getClass(Lex.getCurStrVal());
445 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
451 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
452 /// This returns null on error.
454 /// MultiClassID ::= ID
456 MultiClass *TGParser::ParseMultiClassID() {
457 if (Lex.getCode() != tgtok::Id) {
458 TokError("expected name for MultiClassID");
462 auto it = MultiClasses.find(Lex.getCurStrVal());
463 if (it == MultiClasses.end())
464 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
470 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
471 /// subclass. This returns a SubClassRefTy with a null Record* on error.
473 /// SubClassRef ::= ClassID
474 /// SubClassRef ::= ClassID '<' ValueList '>'
476 SubClassReference TGParser::
477 ParseSubClassReference(Record *CurRec, bool isDefm) {
478 SubClassReference Result;
479 Result.RefRange.Start = Lex.getLoc();
482 if (MultiClass *MC = ParseMultiClassID())
483 Result.Rec = &MC->Rec;
485 Result.Rec = ParseClassID();
487 if (!Result.Rec) return Result;
489 // If there is no template arg list, we're done.
490 if (Lex.getCode() != tgtok::less) {
491 Result.RefRange.End = Lex.getLoc();
494 Lex.Lex(); // Eat the '<'
496 if (Lex.getCode() == tgtok::greater) {
497 TokError("subclass reference requires a non-empty list of template values");
498 Result.Rec = nullptr;
502 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
503 if (Result.TemplateArgs.empty()) {
504 Result.Rec = nullptr; // Error parsing value list.
508 if (Lex.getCode() != tgtok::greater) {
509 TokError("expected '>' in template value list");
510 Result.Rec = nullptr;
514 Result.RefRange.End = Lex.getLoc();
519 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
520 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
521 /// Record* on error.
523 /// SubMultiClassRef ::= MultiClassID
524 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
526 SubMultiClassReference TGParser::
527 ParseSubMultiClassReference(MultiClass *CurMC) {
528 SubMultiClassReference Result;
529 Result.RefRange.Start = Lex.getLoc();
531 Result.MC = ParseMultiClassID();
532 if (!Result.MC) return Result;
534 // If there is no template arg list, we're done.
535 if (Lex.getCode() != tgtok::less) {
536 Result.RefRange.End = Lex.getLoc();
539 Lex.Lex(); // Eat the '<'
541 if (Lex.getCode() == tgtok::greater) {
542 TokError("subclass reference requires a non-empty list of template values");
547 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
548 if (Result.TemplateArgs.empty()) {
549 Result.MC = nullptr; // Error parsing value list.
553 if (Lex.getCode() != tgtok::greater) {
554 TokError("expected '>' in template value list");
559 Result.RefRange.End = Lex.getLoc();
564 /// ParseRangePiece - Parse a bit/value range.
565 /// RangePiece ::= INTVAL
566 /// RangePiece ::= INTVAL '-' INTVAL
567 /// RangePiece ::= INTVAL INTVAL
568 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
569 if (Lex.getCode() != tgtok::IntVal) {
570 TokError("expected integer or bitrange");
573 int64_t Start = Lex.getCurIntVal();
577 return TokError("invalid range, cannot be negative");
579 switch (Lex.Lex()) { // eat first character.
581 Ranges.push_back(Start);
584 if (Lex.Lex() != tgtok::IntVal) {
585 TokError("expected integer value as end of range");
588 End = Lex.getCurIntVal();
591 End = -Lex.getCurIntVal();
595 return TokError("invalid range, cannot be negative");
600 for (; Start <= End; ++Start)
601 Ranges.push_back(Start);
603 for (; Start >= End; --Start)
604 Ranges.push_back(Start);
609 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
611 /// RangeList ::= RangePiece (',' RangePiece)*
613 std::vector<unsigned> TGParser::ParseRangeList() {
614 std::vector<unsigned> Result;
616 // Parse the first piece.
617 if (ParseRangePiece(Result))
618 return std::vector<unsigned>();
619 while (Lex.getCode() == tgtok::comma) {
620 Lex.Lex(); // Eat the comma.
622 // Parse the next range piece.
623 if (ParseRangePiece(Result))
624 return std::vector<unsigned>();
629 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
630 /// OptionalRangeList ::= '<' RangeList '>'
631 /// OptionalRangeList ::= /*empty*/
632 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
633 if (Lex.getCode() != tgtok::less)
636 SMLoc StartLoc = Lex.getLoc();
637 Lex.Lex(); // eat the '<'
639 // Parse the range list.
640 Ranges = ParseRangeList();
641 if (Ranges.empty()) return true;
643 if (Lex.getCode() != tgtok::greater) {
644 TokError("expected '>' at end of range list");
645 return Error(StartLoc, "to match this '<'");
647 Lex.Lex(); // eat the '>'.
651 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
652 /// OptionalBitList ::= '{' RangeList '}'
653 /// OptionalBitList ::= /*empty*/
654 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
655 if (Lex.getCode() != tgtok::l_brace)
658 SMLoc StartLoc = Lex.getLoc();
659 Lex.Lex(); // eat the '{'
661 // Parse the range list.
662 Ranges = ParseRangeList();
663 if (Ranges.empty()) return true;
665 if (Lex.getCode() != tgtok::r_brace) {
666 TokError("expected '}' at end of bit list");
667 return Error(StartLoc, "to match this '{'");
669 Lex.Lex(); // eat the '}'.
674 /// ParseType - Parse and return a tblgen type. This returns null on error.
676 /// Type ::= STRING // string type
677 /// Type ::= CODE // code type
678 /// Type ::= BIT // bit type
679 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
680 /// Type ::= INT // int type
681 /// Type ::= LIST '<' Type '>' // list<x> type
682 /// Type ::= DAG // dag type
683 /// Type ::= ClassID // Record Type
685 RecTy *TGParser::ParseType() {
686 switch (Lex.getCode()) {
687 default: TokError("Unknown token when expecting a type"); return nullptr;
688 case tgtok::String: Lex.Lex(); return StringRecTy::get();
689 case tgtok::Code: Lex.Lex(); return StringRecTy::get();
690 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
691 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
692 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
694 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
697 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
698 TokError("expected '<' after bits type");
701 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
702 TokError("expected integer in bits<n> type");
705 uint64_t Val = Lex.getCurIntVal();
706 if (Lex.Lex() != tgtok::greater) { // Eat count.
707 TokError("expected '>' at end of bits<n> type");
710 Lex.Lex(); // Eat '>'
711 return BitsRecTy::get(Val);
714 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
715 TokError("expected '<' after list type");
718 Lex.Lex(); // Eat '<'
719 RecTy *SubType = ParseType();
720 if (!SubType) return nullptr;
722 if (Lex.getCode() != tgtok::greater) {
723 TokError("expected '>' at end of list<ty> type");
726 Lex.Lex(); // Eat '>'
727 return ListRecTy::get(SubType);
732 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
733 /// has already been read.
734 Init *TGParser::ParseIDValue(Record *CurRec,
735 const std::string &Name, SMLoc NameLoc,
738 if (const RecordVal *RV = CurRec->getValue(Name))
739 return VarInit::get(Name, RV->getType());
741 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
744 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
747 if (CurRec->isTemplateArg(TemplateArgName)) {
748 const RecordVal *RV = CurRec->getValue(TemplateArgName);
749 assert(RV && "Template arg doesn't exist??");
750 return VarInit::get(TemplateArgName, RV->getType());
755 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
758 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
759 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
760 assert(RV && "Template arg doesn't exist??");
761 return VarInit::get(MCName, RV->getType());
765 // If this is in a foreach loop, make sure it's not a loop iterator
766 for (LoopVector::iterator i = Loops.begin(), iend = Loops.end();
769 VarInit *IterVar = dyn_cast<VarInit>(i->IterVar);
770 if (IterVar && IterVar->getName() == Name)
774 if (Mode == ParseNameMode)
775 return StringInit::get(Name);
777 if (Record *D = Records.getDef(Name))
778 return DefInit::get(D);
780 if (Mode == ParseValueMode) {
781 Error(NameLoc, "Variable not defined: '" + Name + "'");
785 return StringInit::get(Name);
788 /// ParseOperation - Parse an operator. This returns null on error.
790 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
792 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
793 switch (Lex.getCode()) {
795 TokError("unknown operation");
800 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
801 UnOpInit::UnaryOp Code;
802 RecTy *Type = nullptr;
804 switch (Lex.getCode()) {
805 default: llvm_unreachable("Unhandled code!");
807 Lex.Lex(); // eat the operation
808 Code = UnOpInit::CAST;
810 Type = ParseOperatorType();
813 TokError("did not get type for unary operator");
819 Lex.Lex(); // eat the operation
820 Code = UnOpInit::HEAD;
823 Lex.Lex(); // eat the operation
824 Code = UnOpInit::TAIL;
827 Lex.Lex(); // eat the operation
828 Code = UnOpInit::EMPTY;
829 Type = IntRecTy::get();
832 if (Lex.getCode() != tgtok::l_paren) {
833 TokError("expected '(' after unary operator");
836 Lex.Lex(); // eat the '('
838 Init *LHS = ParseValue(CurRec);
839 if (!LHS) return nullptr;
841 if (Code == UnOpInit::HEAD
842 || Code == UnOpInit::TAIL
843 || Code == UnOpInit::EMPTY) {
844 ListInit *LHSl = dyn_cast<ListInit>(LHS);
845 StringInit *LHSs = dyn_cast<StringInit>(LHS);
846 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
847 if (!LHSl && !LHSs && !LHSt) {
848 TokError("expected list or string type argument in unary operator");
852 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
853 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
854 if (!LType && !SType) {
855 TokError("expected list or string type argument in unary operator");
860 if (Code == UnOpInit::HEAD
861 || Code == UnOpInit::TAIL) {
862 if (!LHSl && !LHSt) {
863 TokError("expected list type argument in unary operator");
867 if (LHSl && LHSl->getSize() == 0) {
868 TokError("empty list argument in unary operator");
872 Init *Item = LHSl->getElement(0);
873 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
875 TokError("untyped list element in unary operator");
878 if (Code == UnOpInit::HEAD) {
879 Type = Itemt->getType();
881 Type = ListRecTy::get(Itemt->getType());
884 assert(LHSt && "expected list type argument in unary operator");
885 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
887 TokError("expected list type argument in unary operator");
890 if (Code == UnOpInit::HEAD) {
891 Type = LType->getElementType();
899 if (Lex.getCode() != tgtok::r_paren) {
900 TokError("expected ')' in unary operator");
903 Lex.Lex(); // eat the ')'
904 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
914 case tgtok::XListConcat:
915 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
916 tgtok::TokKind OpTok = Lex.getCode();
917 SMLoc OpLoc = Lex.getLoc();
918 Lex.Lex(); // eat the operation
920 BinOpInit::BinaryOp Code;
921 RecTy *Type = nullptr;
924 default: llvm_unreachable("Unhandled code!");
925 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
926 case tgtok::XADD: Code = BinOpInit::ADD; Type = IntRecTy::get(); break;
927 case tgtok::XAND: Code = BinOpInit::AND; Type = IntRecTy::get(); break;
928 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
929 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
930 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
931 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
932 case tgtok::XListConcat:
933 Code = BinOpInit::LISTCONCAT;
934 // We don't know the list type until we parse the first argument
936 case tgtok::XStrConcat:
937 Code = BinOpInit::STRCONCAT;
938 Type = StringRecTy::get();
942 if (Lex.getCode() != tgtok::l_paren) {
943 TokError("expected '(' after binary operator");
946 Lex.Lex(); // eat the '('
948 SmallVector<Init*, 2> InitList;
950 InitList.push_back(ParseValue(CurRec));
951 if (!InitList.back()) return nullptr;
953 while (Lex.getCode() == tgtok::comma) {
954 Lex.Lex(); // eat the ','
956 InitList.push_back(ParseValue(CurRec));
957 if (!InitList.back()) return nullptr;
960 if (Lex.getCode() != tgtok::r_paren) {
961 TokError("expected ')' in operator");
964 Lex.Lex(); // eat the ')'
966 // If we are doing !listconcat, we should know the type by now
967 if (OpTok == tgtok::XListConcat) {
968 if (VarInit *Arg0 = dyn_cast<VarInit>(InitList[0]))
969 Type = Arg0->getType();
970 else if (ListInit *Arg0 = dyn_cast<ListInit>(InitList[0]))
971 Type = Arg0->getType();
974 Error(OpLoc, "expected a list");
979 // We allow multiple operands to associative operators like !strconcat as
980 // shorthand for nesting them.
981 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT) {
982 while (InitList.size() > 2) {
983 Init *RHS = InitList.pop_back_val();
984 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
985 ->Fold(CurRec, CurMultiClass);
986 InitList.back() = RHS;
990 if (InitList.size() == 2)
991 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
992 ->Fold(CurRec, CurMultiClass);
994 Error(OpLoc, "expected two operands to operator");
999 case tgtok::XForEach:
1000 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1001 TernOpInit::TernaryOp Code;
1002 RecTy *Type = nullptr;
1004 tgtok::TokKind LexCode = Lex.getCode();
1005 Lex.Lex(); // eat the operation
1007 default: llvm_unreachable("Unhandled code!");
1009 Code = TernOpInit::IF;
1011 case tgtok::XForEach:
1012 Code = TernOpInit::FOREACH;
1015 Code = TernOpInit::SUBST;
1018 if (Lex.getCode() != tgtok::l_paren) {
1019 TokError("expected '(' after ternary operator");
1022 Lex.Lex(); // eat the '('
1024 Init *LHS = ParseValue(CurRec);
1025 if (!LHS) return nullptr;
1027 if (Lex.getCode() != tgtok::comma) {
1028 TokError("expected ',' in ternary operator");
1031 Lex.Lex(); // eat the ','
1033 Init *MHS = ParseValue(CurRec, ItemType);
1037 if (Lex.getCode() != tgtok::comma) {
1038 TokError("expected ',' in ternary operator");
1041 Lex.Lex(); // eat the ','
1043 Init *RHS = ParseValue(CurRec, ItemType);
1047 if (Lex.getCode() != tgtok::r_paren) {
1048 TokError("expected ')' in binary operator");
1051 Lex.Lex(); // eat the ')'
1054 default: llvm_unreachable("Unhandled code!");
1056 RecTy *MHSTy = nullptr;
1057 RecTy *RHSTy = nullptr;
1059 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1060 MHSTy = MHSt->getType();
1061 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1062 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1063 if (isa<BitInit>(MHS))
1064 MHSTy = BitRecTy::get();
1066 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1067 RHSTy = RHSt->getType();
1068 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1069 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1070 if (isa<BitInit>(RHS))
1071 RHSTy = BitRecTy::get();
1073 // For UnsetInit, it's typed from the other hand.
1074 if (isa<UnsetInit>(MHS))
1076 if (isa<UnsetInit>(RHS))
1079 if (!MHSTy || !RHSTy) {
1080 TokError("could not get type for !if");
1084 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1086 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1089 TokError("inconsistent types for !if");
1094 case tgtok::XForEach: {
1095 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1097 TokError("could not get type for !foreach");
1100 Type = MHSt->getType();
1103 case tgtok::XSubst: {
1104 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1106 TokError("could not get type for !subst");
1109 Type = RHSt->getType();
1113 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1119 /// ParseOperatorType - Parse a type for an operator. This returns
1122 /// OperatorType ::= '<' Type '>'
1124 RecTy *TGParser::ParseOperatorType() {
1125 RecTy *Type = nullptr;
1127 if (Lex.getCode() != tgtok::less) {
1128 TokError("expected type name for operator");
1131 Lex.Lex(); // eat the <
1136 TokError("expected type name for operator");
1140 if (Lex.getCode() != tgtok::greater) {
1141 TokError("expected type name for operator");
1144 Lex.Lex(); // eat the >
1150 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1152 /// SimpleValue ::= IDValue
1153 /// SimpleValue ::= INTVAL
1154 /// SimpleValue ::= STRVAL+
1155 /// SimpleValue ::= CODEFRAGMENT
1156 /// SimpleValue ::= '?'
1157 /// SimpleValue ::= '{' ValueList '}'
1158 /// SimpleValue ::= ID '<' ValueListNE '>'
1159 /// SimpleValue ::= '[' ValueList ']'
1160 /// SimpleValue ::= '(' IDValue DagArgList ')'
1161 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1162 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1163 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1164 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1165 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1166 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1167 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1169 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1172 switch (Lex.getCode()) {
1173 default: TokError("Unknown token when parsing a value"); break;
1175 // This is a leading paste operation. This is deprecated but
1176 // still exists in some .td files. Ignore it.
1177 Lex.Lex(); // Skip '#'.
1178 return ParseSimpleValue(CurRec, ItemType, Mode);
1179 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1180 case tgtok::BinaryIntVal: {
1181 auto BinaryVal = Lex.getCurBinaryIntVal();
1182 SmallVector<Init*, 16> Bits(BinaryVal.second);
1183 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
1184 Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
1185 R = BitsInit::get(Bits);
1189 case tgtok::StrVal: {
1190 std::string Val = Lex.getCurStrVal();
1193 // Handle multiple consecutive concatenated strings.
1194 while (Lex.getCode() == tgtok::StrVal) {
1195 Val += Lex.getCurStrVal();
1199 R = StringInit::get(Val);
1202 case tgtok::CodeFragment:
1203 R = StringInit::get(Lex.getCurStrVal());
1206 case tgtok::question:
1207 R = UnsetInit::get();
1211 SMLoc NameLoc = Lex.getLoc();
1212 std::string Name = Lex.getCurStrVal();
1213 if (Lex.Lex() != tgtok::less) // consume the Id.
1214 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1216 // Value ::= ID '<' ValueListNE '>'
1217 if (Lex.Lex() == tgtok::greater) {
1218 TokError("expected non-empty value list");
1222 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1223 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1225 Record *Class = Records.getClass(Name);
1227 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1231 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1232 if (ValueList.empty()) return nullptr;
1234 if (Lex.getCode() != tgtok::greater) {
1235 TokError("expected '>' at end of value list");
1238 Lex.Lex(); // eat the '>'
1239 SMLoc EndLoc = Lex.getLoc();
1241 // Create the new record, set it as CurRec temporarily.
1242 auto NewRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), NameLoc,
1243 Records, /*IsAnonymous=*/true);
1244 Record *NewRec = NewRecOwner.get(); // Keep a copy since we may release.
1245 SubClassReference SCRef;
1246 SCRef.RefRange = SMRange(NameLoc, EndLoc);
1248 SCRef.TemplateArgs = ValueList;
1249 // Add info about the subclass to NewRec.
1250 if (AddSubClass(NewRec, SCRef))
1253 if (!CurMultiClass) {
1254 NewRec->resolveReferences();
1255 Records.addDef(std::move(NewRecOwner));
1257 // This needs to get resolved once the multiclass template arguments are
1258 // known before any use.
1259 NewRec->setResolveFirst(true);
1260 // Otherwise, we're inside a multiclass, add it to the multiclass.
1261 CurMultiClass->DefPrototypes.push_back(std::move(NewRecOwner));
1263 // Copy the template arguments for the multiclass into the def.
1264 const std::vector<Init *> &TArgs =
1265 CurMultiClass->Rec.getTemplateArgs();
1267 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1268 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1269 assert(RV && "Template arg doesn't exist?");
1270 NewRec->addValue(*RV);
1273 // We can't return the prototype def here, instead return:
1274 // !cast<ItemType>(!strconcat(NAME, AnonName)).
1275 const RecordVal *MCNameRV = CurMultiClass->Rec.getValue("NAME");
1276 assert(MCNameRV && "multiclass record must have a NAME");
1278 return UnOpInit::get(UnOpInit::CAST,
1279 BinOpInit::get(BinOpInit::STRCONCAT,
1280 VarInit::get(MCNameRV->getName(),
1281 MCNameRV->getType()),
1282 NewRec->getNameInit(),
1283 StringRecTy::get()),
1284 Class->getDefInit()->getType());
1287 // The result of the expression is a reference to the new record.
1288 return DefInit::get(NewRec);
1290 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1291 SMLoc BraceLoc = Lex.getLoc();
1292 Lex.Lex(); // eat the '{'
1293 std::vector<Init*> Vals;
1295 if (Lex.getCode() != tgtok::r_brace) {
1296 Vals = ParseValueList(CurRec);
1297 if (Vals.empty()) return nullptr;
1299 if (Lex.getCode() != tgtok::r_brace) {
1300 TokError("expected '}' at end of bit list value");
1303 Lex.Lex(); // eat the '}'
1305 SmallVector<Init *, 16> NewBits;
1307 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
1308 // first. We'll first read everything in to a vector, then we can reverse
1309 // it to get the bits in the correct order for the BitsInit value.
1310 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1311 // FIXME: The following two loops would not be duplicated
1312 // if the API was a little more orthogonal.
1314 // bits<n> values are allowed to initialize n bits.
1315 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
1316 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
1317 NewBits.push_back(BI->getBit((e - i) - 1));
1320 // bits<n> can also come from variable initializers.
1321 if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
1322 if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
1323 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
1324 NewBits.push_back(VI->getBit((e - i) - 1));
1327 // Fallthrough to try convert this to a bit.
1329 // All other values must be convertible to just a single bit.
1330 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1332 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1333 ") is not convertable to a bit");
1336 NewBits.push_back(Bit);
1338 std::reverse(NewBits.begin(), NewBits.end());
1339 return BitsInit::get(NewBits);
1341 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1342 Lex.Lex(); // eat the '['
1343 std::vector<Init*> Vals;
1345 RecTy *DeducedEltTy = nullptr;
1346 ListRecTy *GivenListTy = nullptr;
1349 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1352 raw_string_ostream ss(s);
1353 ss << "Type mismatch for list, expected list type, got "
1354 << ItemType->getAsString();
1358 GivenListTy = ListType;
1361 if (Lex.getCode() != tgtok::r_square) {
1362 Vals = ParseValueList(CurRec, nullptr,
1363 GivenListTy ? GivenListTy->getElementType() : nullptr);
1364 if (Vals.empty()) return nullptr;
1366 if (Lex.getCode() != tgtok::r_square) {
1367 TokError("expected ']' at end of list value");
1370 Lex.Lex(); // eat the ']'
1372 RecTy *GivenEltTy = nullptr;
1373 if (Lex.getCode() == tgtok::less) {
1374 // Optional list element type
1375 Lex.Lex(); // eat the '<'
1377 GivenEltTy = ParseType();
1379 // Couldn't parse element type
1383 if (Lex.getCode() != tgtok::greater) {
1384 TokError("expected '>' at end of list element type");
1387 Lex.Lex(); // eat the '>'
1391 RecTy *EltTy = nullptr;
1392 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1395 TypedInit *TArg = dyn_cast<TypedInit>(*i);
1397 TokError("Untyped list element");
1401 EltTy = resolveTypes(EltTy, TArg->getType());
1403 TokError("Incompatible types in list elements");
1407 EltTy = TArg->getType();
1413 // Verify consistency
1414 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1415 TokError("Incompatible types in list elements");
1424 TokError("No type for list");
1427 DeducedEltTy = GivenListTy->getElementType();
1429 // Make sure the deduced type is compatible with the given type
1431 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1432 TokError("Element type mismatch for list");
1436 DeducedEltTy = EltTy;
1439 return ListInit::get(Vals, DeducedEltTy);
1441 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1442 Lex.Lex(); // eat the '('
1443 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1444 TokError("expected identifier in dag init");
1448 Init *Operator = ParseValue(CurRec);
1449 if (!Operator) return nullptr;
1451 // If the operator name is present, parse it.
1452 std::string OperatorName;
1453 if (Lex.getCode() == tgtok::colon) {
1454 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1455 TokError("expected variable name in dag operator");
1458 OperatorName = Lex.getCurStrVal();
1459 Lex.Lex(); // eat the VarName.
1462 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1463 if (Lex.getCode() != tgtok::r_paren) {
1464 DagArgs = ParseDagArgList(CurRec);
1465 if (DagArgs.empty()) return nullptr;
1468 if (Lex.getCode() != tgtok::r_paren) {
1469 TokError("expected ')' in dag init");
1472 Lex.Lex(); // eat the ')'
1474 return DagInit::get(Operator, OperatorName, DagArgs);
1480 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1481 case tgtok::XConcat:
1488 case tgtok::XListConcat:
1489 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1491 case tgtok::XForEach:
1492 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1493 return ParseOperation(CurRec, ItemType);
1500 /// ParseValue - Parse a tblgen value. This returns null on error.
1502 /// Value ::= SimpleValue ValueSuffix*
1503 /// ValueSuffix ::= '{' BitList '}'
1504 /// ValueSuffix ::= '[' BitList ']'
1505 /// ValueSuffix ::= '.' ID
1507 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1508 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1509 if (!Result) return nullptr;
1511 // Parse the suffixes now if present.
1513 switch (Lex.getCode()) {
1514 default: return Result;
1515 case tgtok::l_brace: {
1516 if (Mode == ParseNameMode || Mode == ParseForeachMode)
1517 // This is the beginning of the object body.
1520 SMLoc CurlyLoc = Lex.getLoc();
1521 Lex.Lex(); // eat the '{'
1522 std::vector<unsigned> Ranges = ParseRangeList();
1523 if (Ranges.empty()) return nullptr;
1525 // Reverse the bitlist.
1526 std::reverse(Ranges.begin(), Ranges.end());
1527 Result = Result->convertInitializerBitRange(Ranges);
1529 Error(CurlyLoc, "Invalid bit range for value");
1534 if (Lex.getCode() != tgtok::r_brace) {
1535 TokError("expected '}' at end of bit range list");
1541 case tgtok::l_square: {
1542 SMLoc SquareLoc = Lex.getLoc();
1543 Lex.Lex(); // eat the '['
1544 std::vector<unsigned> Ranges = ParseRangeList();
1545 if (Ranges.empty()) return nullptr;
1547 Result = Result->convertInitListSlice(Ranges);
1549 Error(SquareLoc, "Invalid range for list slice");
1554 if (Lex.getCode() != tgtok::r_square) {
1555 TokError("expected ']' at end of list slice");
1562 if (Lex.Lex() != tgtok::Id) { // eat the .
1563 TokError("expected field identifier after '.'");
1566 if (!Result->getFieldType(Lex.getCurStrVal())) {
1567 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1568 Result->getAsString() + "'");
1571 Result = FieldInit::get(Result, Lex.getCurStrVal());
1572 Lex.Lex(); // eat field name
1576 SMLoc PasteLoc = Lex.getLoc();
1578 // Create a !strconcat() operation, first casting each operand to
1579 // a string if necessary.
1581 TypedInit *LHS = dyn_cast<TypedInit>(Result);
1583 Error(PasteLoc, "LHS of paste is not typed!");
1587 if (LHS->getType() != StringRecTy::get()) {
1588 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1591 TypedInit *RHS = nullptr;
1593 Lex.Lex(); // Eat the '#'.
1594 switch (Lex.getCode()) {
1597 case tgtok::l_brace:
1598 // These are all of the tokens that can begin an object body.
1599 // Some of these can also begin values but we disallow those cases
1600 // because they are unlikely to be useful.
1602 // Trailing paste, concat with an empty string.
1603 RHS = StringInit::get("");
1607 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1608 RHS = dyn_cast<TypedInit>(RHSResult);
1610 Error(PasteLoc, "RHS of paste is not typed!");
1614 if (RHS->getType() != StringRecTy::get()) {
1615 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1621 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1622 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1628 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1630 /// DagArg ::= Value (':' VARNAME)?
1631 /// DagArg ::= VARNAME
1632 /// DagArgList ::= DagArg
1633 /// DagArgList ::= DagArgList ',' DagArg
1634 std::vector<std::pair<llvm::Init*, std::string> >
1635 TGParser::ParseDagArgList(Record *CurRec) {
1636 std::vector<std::pair<llvm::Init*, std::string> > Result;
1639 // DagArg ::= VARNAME
1640 if (Lex.getCode() == tgtok::VarName) {
1641 // A missing value is treated like '?'.
1642 Result.push_back(std::make_pair(UnsetInit::get(), Lex.getCurStrVal()));
1645 // DagArg ::= Value (':' VARNAME)?
1646 Init *Val = ParseValue(CurRec);
1648 return std::vector<std::pair<llvm::Init*, std::string> >();
1650 // If the variable name is present, add it.
1651 std::string VarName;
1652 if (Lex.getCode() == tgtok::colon) {
1653 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1654 TokError("expected variable name in dag literal");
1655 return std::vector<std::pair<llvm::Init*, std::string> >();
1657 VarName = Lex.getCurStrVal();
1658 Lex.Lex(); // eat the VarName.
1661 Result.push_back(std::make_pair(Val, VarName));
1663 if (Lex.getCode() != tgtok::comma) break;
1664 Lex.Lex(); // eat the ','
1671 /// ParseValueList - Parse a comma separated list of values, returning them as a
1672 /// vector. Note that this always expects to be able to parse at least one
1673 /// value. It returns an empty list if this is not possible.
1675 /// ValueList ::= Value (',' Value)
1677 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1679 std::vector<Init*> Result;
1680 RecTy *ItemType = EltTy;
1681 unsigned int ArgN = 0;
1682 if (ArgsRec && !EltTy) {
1683 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1684 if (!TArgs.size()) {
1685 TokError("template argument provided to non-template class");
1686 return std::vector<Init*>();
1688 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1690 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1693 assert(RV && "Template argument record not found??");
1694 ItemType = RV->getType();
1697 Result.push_back(ParseValue(CurRec, ItemType));
1698 if (!Result.back()) return std::vector<Init*>();
1700 while (Lex.getCode() == tgtok::comma) {
1701 Lex.Lex(); // Eat the comma
1703 if (ArgsRec && !EltTy) {
1704 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1705 if (ArgN >= TArgs.size()) {
1706 TokError("too many template arguments");
1707 return std::vector<Init*>();
1709 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1710 assert(RV && "Template argument record not found??");
1711 ItemType = RV->getType();
1714 Result.push_back(ParseValue(CurRec, ItemType));
1715 if (!Result.back()) return std::vector<Init*>();
1722 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1723 /// empty string on error. This can happen in a number of different context's,
1724 /// including within a def or in the template args for a def (which which case
1725 /// CurRec will be non-null) and within the template args for a multiclass (in
1726 /// which case CurRec will be null, but CurMultiClass will be set). This can
1727 /// also happen within a def that is within a multiclass, which will set both
1728 /// CurRec and CurMultiClass.
1730 /// Declaration ::= FIELD? Type ID ('=' Value)?
1732 Init *TGParser::ParseDeclaration(Record *CurRec,
1733 bool ParsingTemplateArgs) {
1734 // Read the field prefix if present.
1735 bool HasField = Lex.getCode() == tgtok::Field;
1736 if (HasField) Lex.Lex();
1738 RecTy *Type = ParseType();
1739 if (!Type) return nullptr;
1741 if (Lex.getCode() != tgtok::Id) {
1742 TokError("Expected identifier in declaration");
1746 SMLoc IdLoc = Lex.getLoc();
1747 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1750 if (ParsingTemplateArgs) {
1752 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1754 assert(CurMultiClass);
1757 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1762 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1765 // If a value is present, parse it.
1766 if (Lex.getCode() == tgtok::equal) {
1768 SMLoc ValLoc = Lex.getLoc();
1769 Init *Val = ParseValue(CurRec, Type);
1771 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1772 // Return the name, even if an error is thrown. This is so that we can
1773 // continue to make some progress, even without the value having been
1781 /// ParseForeachDeclaration - Read a foreach declaration, returning
1782 /// the name of the declared object or a NULL Init on error. Return
1783 /// the name of the parsed initializer list through ForeachListName.
1785 /// ForeachDeclaration ::= ID '=' '[' ValueList ']'
1786 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
1787 /// ForeachDeclaration ::= ID '=' RangePiece
1789 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1790 if (Lex.getCode() != tgtok::Id) {
1791 TokError("Expected identifier in foreach declaration");
1795 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1798 // If a value is present, parse it.
1799 if (Lex.getCode() != tgtok::equal) {
1800 TokError("Expected '=' in foreach declaration");
1803 Lex.Lex(); // Eat the '='
1805 RecTy *IterType = nullptr;
1806 std::vector<unsigned> Ranges;
1808 switch (Lex.getCode()) {
1809 default: TokError("Unknown token when expecting a range list"); return nullptr;
1810 case tgtok::l_square: { // '[' ValueList ']'
1811 Init *List = ParseSimpleValue(nullptr, nullptr, ParseForeachMode);
1812 ForeachListValue = dyn_cast<ListInit>(List);
1813 if (!ForeachListValue) {
1814 TokError("Expected a Value list");
1817 RecTy *ValueType = ForeachListValue->getType();
1818 ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1820 TokError("Value list is not of list type");
1823 IterType = ListType->getElementType();
1827 case tgtok::IntVal: { // RangePiece.
1828 if (ParseRangePiece(Ranges))
1833 case tgtok::l_brace: { // '{' RangeList '}'
1834 Lex.Lex(); // eat the '{'
1835 Ranges = ParseRangeList();
1836 if (Lex.getCode() != tgtok::r_brace) {
1837 TokError("expected '}' at end of bit range list");
1845 if (!Ranges.empty()) {
1846 assert(!IterType && "Type already initialized?");
1847 IterType = IntRecTy::get();
1848 std::vector<Init*> Values;
1849 for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
1850 Values.push_back(IntInit::get(Ranges[i]));
1851 ForeachListValue = ListInit::get(Values, IterType);
1857 return VarInit::get(DeclName, IterType);
1860 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1861 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1862 /// template args for a def, which may or may not be in a multiclass. If null,
1863 /// these are the template args for a multiclass.
1865 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1867 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1868 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1869 Lex.Lex(); // eat the '<'
1871 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1873 // Read the first declaration.
1874 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1878 TheRecToAddTo->addTemplateArg(TemplArg);
1880 while (Lex.getCode() == tgtok::comma) {
1881 Lex.Lex(); // eat the ','
1883 // Read the following declarations.
1884 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1887 TheRecToAddTo->addTemplateArg(TemplArg);
1890 if (Lex.getCode() != tgtok::greater)
1891 return TokError("expected '>' at end of template argument list");
1892 Lex.Lex(); // eat the '>'.
1897 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1899 /// BodyItem ::= Declaration ';'
1900 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1901 bool TGParser::ParseBodyItem(Record *CurRec) {
1902 if (Lex.getCode() != tgtok::Let) {
1903 if (!ParseDeclaration(CurRec, false))
1906 if (Lex.getCode() != tgtok::semi)
1907 return TokError("expected ';' after declaration");
1912 // LET ID OptionalRangeList '=' Value ';'
1913 if (Lex.Lex() != tgtok::Id)
1914 return TokError("expected field identifier after let");
1916 SMLoc IdLoc = Lex.getLoc();
1917 std::string FieldName = Lex.getCurStrVal();
1918 Lex.Lex(); // eat the field name.
1920 std::vector<unsigned> BitList;
1921 if (ParseOptionalBitList(BitList))
1923 std::reverse(BitList.begin(), BitList.end());
1925 if (Lex.getCode() != tgtok::equal)
1926 return TokError("expected '=' in let expression");
1927 Lex.Lex(); // eat the '='.
1929 RecordVal *Field = CurRec->getValue(FieldName);
1931 return TokError("Value '" + FieldName + "' unknown!");
1933 RecTy *Type = Field->getType();
1935 Init *Val = ParseValue(CurRec, Type);
1936 if (!Val) return true;
1938 if (Lex.getCode() != tgtok::semi)
1939 return TokError("expected ';' after let expression");
1942 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1945 /// ParseBody - Read the body of a class or def. Return true on error, false on
1949 /// Body ::= '{' BodyList '}'
1950 /// BodyList BodyItem*
1952 bool TGParser::ParseBody(Record *CurRec) {
1953 // If this is a null definition, just eat the semi and return.
1954 if (Lex.getCode() == tgtok::semi) {
1959 if (Lex.getCode() != tgtok::l_brace)
1960 return TokError("Expected ';' or '{' to start body");
1964 while (Lex.getCode() != tgtok::r_brace)
1965 if (ParseBodyItem(CurRec))
1973 /// \brief Apply the current let bindings to \a CurRec.
1974 /// \returns true on error, false otherwise.
1975 bool TGParser::ApplyLetStack(Record *CurRec) {
1976 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1977 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1978 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1979 LetStack[i][j].Bits, LetStack[i][j].Value))
1984 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1985 /// optional ClassList followed by a Body. CurRec is the current def or class
1986 /// that is being parsed.
1988 /// ObjectBody ::= BaseClassList Body
1989 /// BaseClassList ::= /*empty*/
1990 /// BaseClassList ::= ':' BaseClassListNE
1991 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1993 bool TGParser::ParseObjectBody(Record *CurRec) {
1994 // If there is a baseclass list, read it.
1995 if (Lex.getCode() == tgtok::colon) {
1998 // Read all of the subclasses.
1999 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
2002 if (!SubClass.Rec) return true;
2005 if (AddSubClass(CurRec, SubClass))
2008 if (Lex.getCode() != tgtok::comma) break;
2009 Lex.Lex(); // eat ','.
2010 SubClass = ParseSubClassReference(CurRec, false);
2014 if (ApplyLetStack(CurRec))
2017 return ParseBody(CurRec);
2020 /// ParseDef - Parse and return a top level or multiclass def, return the record
2021 /// corresponding to it. This returns null on error.
2023 /// DefInst ::= DEF ObjectName ObjectBody
2025 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
2026 SMLoc DefLoc = Lex.getLoc();
2027 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
2028 Lex.Lex(); // Eat the 'def' token.
2030 // Parse ObjectName and make a record for it.
2031 std::unique_ptr<Record> CurRecOwner;
2032 Init *Name = ParseObjectName(CurMultiClass);
2034 CurRecOwner = make_unique<Record>(Name, DefLoc, Records);
2036 CurRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), DefLoc,
2037 Records, /*IsAnonymous=*/true);
2038 Record *CurRec = CurRecOwner.get(); // Keep a copy since we may release.
2040 if (!CurMultiClass && Loops.empty()) {
2041 // Top-level def definition.
2043 // Ensure redefinition doesn't happen.
2044 if (Records.getDef(CurRec->getNameInitAsString()))
2045 return Error(DefLoc, "def '" + CurRec->getNameInitAsString()+
2046 "' already defined");
2047 Records.addDef(std::move(CurRecOwner));
2049 if (ParseObjectBody(CurRec))
2051 } else if (CurMultiClass) {
2052 // Parse the body before adding this prototype to the DefPrototypes vector.
2053 // That way implicit definitions will be added to the DefPrototypes vector
2054 // before this object, instantiated prior to defs derived from this object,
2055 // and this available for indirect name resolution when defs derived from
2056 // this object are instantiated.
2057 if (ParseObjectBody(CurRec))
2060 // Otherwise, a def inside a multiclass, add it to the multiclass.
2061 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
2062 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2063 == CurRec->getNameInit())
2064 return Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
2065 "' already defined in this multiclass!");
2066 CurMultiClass->DefPrototypes.push_back(std::move(CurRecOwner));
2067 } else if (ParseObjectBody(CurRec)) {
2071 if (!CurMultiClass) // Def's in multiclasses aren't really defs.
2072 // See Record::setName(). This resolve step will see any new name
2073 // for the def that might have been created when resolving
2074 // inheritance, values and arguments above.
2075 CurRec->resolveReferences();
2077 // If ObjectBody has template arguments, it's an error.
2078 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
2080 if (CurMultiClass) {
2081 // Copy the template arguments for the multiclass into the def.
2082 const std::vector<Init *> &TArgs =
2083 CurMultiClass->Rec.getTemplateArgs();
2085 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2086 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
2087 assert(RV && "Template arg doesn't exist?");
2088 CurRec->addValue(*RV);
2092 if (ProcessForeachDefs(CurRec, DefLoc)) {
2093 return Error(DefLoc, "Could not process loops for def" +
2094 CurRec->getNameInitAsString());
2100 /// ParseForeach - Parse a for statement. Return the record corresponding
2101 /// to it. This returns true on error.
2103 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2104 /// Foreach ::= FOREACH Declaration IN Object
2106 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2107 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2108 Lex.Lex(); // Eat the 'for' token.
2110 // Make a temporary object to record items associated with the for
2112 ListInit *ListValue = nullptr;
2113 VarInit *IterName = ParseForeachDeclaration(ListValue);
2115 return TokError("expected declaration in for");
2117 if (Lex.getCode() != tgtok::In)
2118 return TokError("Unknown tok");
2119 Lex.Lex(); // Eat the in
2121 // Create a loop object and remember it.
2122 Loops.push_back(ForeachLoop(IterName, ListValue));
2124 if (Lex.getCode() != tgtok::l_brace) {
2125 // FOREACH Declaration IN Object
2126 if (ParseObject(CurMultiClass))
2130 SMLoc BraceLoc = Lex.getLoc();
2131 // Otherwise, this is a group foreach.
2132 Lex.Lex(); // eat the '{'.
2134 // Parse the object list.
2135 if (ParseObjectList(CurMultiClass))
2138 if (Lex.getCode() != tgtok::r_brace) {
2139 TokError("expected '}' at end of foreach command");
2140 return Error(BraceLoc, "to match this '{'");
2142 Lex.Lex(); // Eat the }
2145 // We've processed everything in this loop.
2151 /// ParseClass - Parse a tblgen class definition.
2153 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2155 bool TGParser::ParseClass() {
2156 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2159 if (Lex.getCode() != tgtok::Id)
2160 return TokError("expected class name after 'class' keyword");
2162 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2164 // If the body was previously defined, this is an error.
2165 if (CurRec->getValues().size() > 1 || // Account for NAME.
2166 !CurRec->getSuperClasses().empty() ||
2167 !CurRec->getTemplateArgs().empty())
2168 return TokError("Class '" + CurRec->getNameInitAsString()
2169 + "' already defined");
2171 // If this is the first reference to this class, create and add it.
2172 auto NewRec = make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(),
2174 CurRec = NewRec.get();
2175 Records.addClass(std::move(NewRec));
2177 Lex.Lex(); // eat the name.
2179 // If there are template args, parse them.
2180 if (Lex.getCode() == tgtok::less)
2181 if (ParseTemplateArgList(CurRec))
2184 // Finally, parse the object body.
2185 return ParseObjectBody(CurRec);
2188 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2191 /// LetList ::= LetItem (',' LetItem)*
2192 /// LetItem ::= ID OptionalRangeList '=' Value
2194 std::vector<LetRecord> TGParser::ParseLetList() {
2195 std::vector<LetRecord> Result;
2198 if (Lex.getCode() != tgtok::Id) {
2199 TokError("expected identifier in let definition");
2200 return std::vector<LetRecord>();
2202 std::string Name = Lex.getCurStrVal();
2203 SMLoc NameLoc = Lex.getLoc();
2204 Lex.Lex(); // Eat the identifier.
2206 // Check for an optional RangeList.
2207 std::vector<unsigned> Bits;
2208 if (ParseOptionalRangeList(Bits))
2209 return std::vector<LetRecord>();
2210 std::reverse(Bits.begin(), Bits.end());
2212 if (Lex.getCode() != tgtok::equal) {
2213 TokError("expected '=' in let expression");
2214 return std::vector<LetRecord>();
2216 Lex.Lex(); // eat the '='.
2218 Init *Val = ParseValue(nullptr);
2219 if (!Val) return std::vector<LetRecord>();
2221 // Now that we have everything, add the record.
2222 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
2224 if (Lex.getCode() != tgtok::comma)
2226 Lex.Lex(); // eat the comma.
2230 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2231 /// different related productions. This works inside multiclasses too.
2233 /// Object ::= LET LetList IN '{' ObjectList '}'
2234 /// Object ::= LET LetList IN Object
2236 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2237 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2240 // Add this entry to the let stack.
2241 std::vector<LetRecord> LetInfo = ParseLetList();
2242 if (LetInfo.empty()) return true;
2243 LetStack.push_back(std::move(LetInfo));
2245 if (Lex.getCode() != tgtok::In)
2246 return TokError("expected 'in' at end of top-level 'let'");
2249 // If this is a scalar let, just handle it now
2250 if (Lex.getCode() != tgtok::l_brace) {
2251 // LET LetList IN Object
2252 if (ParseObject(CurMultiClass))
2254 } else { // Object ::= LETCommand '{' ObjectList '}'
2255 SMLoc BraceLoc = Lex.getLoc();
2256 // Otherwise, this is a group let.
2257 Lex.Lex(); // eat the '{'.
2259 // Parse the object list.
2260 if (ParseObjectList(CurMultiClass))
2263 if (Lex.getCode() != tgtok::r_brace) {
2264 TokError("expected '}' at end of top level let command");
2265 return Error(BraceLoc, "to match this '{'");
2270 // Outside this let scope, this let block is not active.
2271 LetStack.pop_back();
2275 /// ParseMultiClass - Parse a multiclass definition.
2277 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2278 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
2279 /// MultiClassObject ::= DefInst
2280 /// MultiClassObject ::= MultiClassInst
2281 /// MultiClassObject ::= DefMInst
2282 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
2283 /// MultiClassObject ::= LETCommand Object
2285 bool TGParser::ParseMultiClass() {
2286 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2287 Lex.Lex(); // Eat the multiclass token.
2289 if (Lex.getCode() != tgtok::Id)
2290 return TokError("expected identifier after multiclass for name");
2291 std::string Name = Lex.getCurStrVal();
2294 MultiClasses.insert(std::make_pair(Name,
2295 MultiClass(Name, Lex.getLoc(),Records)));
2297 return TokError("multiclass '" + Name + "' already defined");
2298 CurMultiClass = &Result.first->second;
2300 Lex.Lex(); // Eat the identifier.
2302 // If there are template args, parse them.
2303 if (Lex.getCode() == tgtok::less)
2304 if (ParseTemplateArgList(nullptr))
2307 bool inherits = false;
2309 // If there are submulticlasses, parse them.
2310 if (Lex.getCode() == tgtok::colon) {
2315 // Read all of the submulticlasses.
2316 SubMultiClassReference SubMultiClass =
2317 ParseSubMultiClassReference(CurMultiClass);
2320 if (!SubMultiClass.MC) return true;
2323 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2326 if (Lex.getCode() != tgtok::comma) break;
2327 Lex.Lex(); // eat ','.
2328 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2332 if (Lex.getCode() != tgtok::l_brace) {
2334 return TokError("expected '{' in multiclass definition");
2335 if (Lex.getCode() != tgtok::semi)
2336 return TokError("expected ';' in multiclass definition");
2337 Lex.Lex(); // eat the ';'.
2339 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2340 return TokError("multiclass must contain at least one def");
2342 while (Lex.getCode() != tgtok::r_brace) {
2343 switch (Lex.getCode()) {
2345 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2349 case tgtok::Foreach:
2350 if (ParseObject(CurMultiClass))
2355 Lex.Lex(); // eat the '}'.
2358 CurMultiClass = nullptr;
2363 InstantiateMulticlassDef(MultiClass &MC,
2366 SMRange DefmPrefixRange) {
2367 // We need to preserve DefProto so it can be reused for later
2368 // instantiations, so create a new Record to inherit from it.
2370 // Add in the defm name. If the defm prefix is empty, give each
2371 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2372 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2375 bool IsAnonymous = false;
2377 DefmPrefix = StringInit::get(GetNewAnonymousName());
2381 Init *DefName = DefProto->getNameInit();
2383 StringInit *DefNameString = dyn_cast<StringInit>(DefName);
2385 if (DefNameString) {
2386 // We have a fully expanded string so there are no operators to
2387 // resolve. We should concatenate the given prefix and name.
2389 BinOpInit::get(BinOpInit::STRCONCAT,
2390 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2391 StringRecTy::get())->Fold(DefProto, &MC),
2392 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2395 // Make a trail of SMLocs from the multiclass instantiations.
2396 SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
2397 Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2398 auto CurRec = make_unique<Record>(DefName, Locs, Records, IsAnonymous);
2400 SubClassReference Ref;
2401 Ref.RefRange = DefmPrefixRange;
2403 AddSubClass(CurRec.get(), Ref);
2405 // Set the value for NAME. We don't resolve references to it 'til later,
2406 // though, so that uses in nested multiclass names don't get
2408 if (SetValue(CurRec.get(), Ref.RefRange.Start, "NAME",
2409 std::vector<unsigned>(), DefmPrefix)) {
2410 Error(DefmPrefixRange.Start, "Could not resolve "
2411 + CurRec->getNameInitAsString() + ":NAME to '"
2412 + DefmPrefix->getAsUnquotedString() + "'");
2416 // If the DefNameString didn't resolve, we probably have a reference to
2417 // NAME and need to replace it. We need to do at least this much greedily,
2418 // otherwise nested multiclasses will end up with incorrect NAME expansions.
2419 if (!DefNameString) {
2420 RecordVal *DefNameRV = CurRec->getValue("NAME");
2421 CurRec->resolveReferencesTo(DefNameRV);
2424 if (!CurMultiClass) {
2425 // Now that we're at the top level, resolve all NAME references
2426 // in the resultant defs that weren't in the def names themselves.
2427 RecordVal *DefNameRV = CurRec->getValue("NAME");
2428 CurRec->resolveReferencesTo(DefNameRV);
2430 // Now that NAME references are resolved and we're at the top level of
2431 // any multiclass expansions, add the record to the RecordKeeper. If we are
2432 // currently in a multiclass, it means this defm appears inside a
2433 // multiclass and its name won't be fully resolvable until we see
2434 // the top-level defm. Therefore, we don't add this to the
2435 // RecordKeeper at this point. If we did we could get duplicate
2436 // defs as more than one probably refers to NAME or some other
2437 // common internal placeholder.
2439 // Ensure redefinition doesn't happen.
2440 if (Records.getDef(CurRec->getNameInitAsString())) {
2441 Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
2442 "' already defined, instantiating defm with subdef '" +
2443 DefProto->getNameInitAsString() + "'");
2447 Record *CurRecSave = CurRec.get(); // Keep a copy before we release.
2448 Records.addDef(std::move(CurRec));
2452 // FIXME This is bad but the ownership transfer to caller is pretty messy.
2453 // The unique_ptr in this function at least protects the exits above.
2454 return CurRec.release();
2457 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2459 SMLoc DefmPrefixLoc,
2461 const std::vector<Init *> &TArgs,
2462 std::vector<Init *> &TemplateVals,
2464 // Loop over all of the template arguments, setting them to the specified
2465 // value or leaving them as the default if necessary.
2466 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2467 // Check if a value is specified for this temp-arg.
2468 if (i < TemplateVals.size()) {
2470 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2475 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2479 CurRec->removeValue(TArgs[i]);
2481 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2482 return Error(SubClassLoc, "value not specified for template argument #"+
2483 utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2484 + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2491 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2494 SMLoc DefmPrefixLoc) {
2495 // If the mdef is inside a 'let' expression, add to each def.
2496 if (ApplyLetStack(CurRec))
2497 return Error(DefmPrefixLoc, "when instantiating this defm");
2499 // Don't create a top level definition for defm inside multiclasses,
2500 // instead, only update the prototypes and bind the template args
2501 // with the new created definition.
2504 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2506 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2507 == CurRec->getNameInit())
2508 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2509 "' already defined in this multiclass!");
2510 CurMultiClass->DefPrototypes.push_back(std::unique_ptr<Record>(CurRec));
2512 // Copy the template arguments for the multiclass into the new def.
2513 const std::vector<Init *> &TA =
2514 CurMultiClass->Rec.getTemplateArgs();
2516 for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2517 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2518 assert(RV && "Template arg doesn't exist?");
2519 CurRec->addValue(*RV);
2525 /// ParseDefm - Parse the instantiation of a multiclass.
2527 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2529 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2530 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2531 SMLoc DefmLoc = Lex.getLoc();
2532 Init *DefmPrefix = nullptr;
2534 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2535 DefmPrefix = ParseObjectName(CurMultiClass);
2538 SMLoc DefmPrefixEndLoc = Lex.getLoc();
2539 if (Lex.getCode() != tgtok::colon)
2540 return TokError("expected ':' after defm identifier");
2542 // Keep track of the new generated record definitions.
2543 std::vector<Record*> NewRecDefs;
2545 // This record also inherits from a regular class (non-multiclass)?
2546 bool InheritFromClass = false;
2551 SMLoc SubClassLoc = Lex.getLoc();
2552 SubClassReference Ref = ParseSubClassReference(nullptr, true);
2555 if (!Ref.Rec) return true;
2557 // To instantiate a multiclass, we need to first get the multiclass, then
2558 // instantiate each def contained in the multiclass with the SubClassRef
2559 // template parameters.
2560 auto it = MultiClasses.find(Ref.Rec->getName());
2561 assert(it != MultiClasses.end() && "Didn't lookup multiclass correctly?");
2562 MultiClass *MC = &it->second;
2563 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2565 // Verify that the correct number of template arguments were specified.
2566 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2567 if (TArgs.size() < TemplateVals.size())
2568 return Error(SubClassLoc,
2569 "more template args specified than multiclass expects");
2571 // Loop over all the def's in the multiclass, instantiating each one.
2572 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2573 Record *DefProto = MC->DefPrototypes[i].get();
2575 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix,
2581 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
2582 TArgs, TemplateVals, true/*Delete args*/))
2583 return Error(SubClassLoc, "could not instantiate def");
2585 if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmLoc))
2586 return Error(SubClassLoc, "could not instantiate def");
2588 // Defs that can be used by other definitions should be fully resolved
2590 if (DefProto->isResolveFirst() && !CurMultiClass) {
2591 CurRec->resolveReferences();
2592 CurRec->setResolveFirst(false);
2594 NewRecDefs.push_back(CurRec);
2598 if (Lex.getCode() != tgtok::comma) break;
2599 Lex.Lex(); // eat ','.
2601 if (Lex.getCode() != tgtok::Id)
2602 return TokError("expected identifier");
2604 SubClassLoc = Lex.getLoc();
2606 // A defm can inherit from regular classes (non-multiclass) as
2607 // long as they come in the end of the inheritance list.
2608 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
2610 if (InheritFromClass)
2613 Ref = ParseSubClassReference(nullptr, true);
2616 if (InheritFromClass) {
2617 // Process all the classes to inherit as if they were part of a
2618 // regular 'def' and inherit all record values.
2619 SubClassReference SubClass = ParseSubClassReference(nullptr, false);
2622 if (!SubClass.Rec) return true;
2624 // Get the expanded definition prototypes and teach them about
2625 // the record values the current class to inherit has
2626 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2627 Record *CurRec = NewRecDefs[i];
2630 if (AddSubClass(CurRec, SubClass))
2633 if (ApplyLetStack(CurRec))
2637 if (Lex.getCode() != tgtok::comma) break;
2638 Lex.Lex(); // eat ','.
2639 SubClass = ParseSubClassReference(nullptr, false);
2644 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2645 // See Record::setName(). This resolve step will see any new
2646 // name for the def that might have been created when resolving
2647 // inheritance, values and arguments above.
2648 NewRecDefs[i]->resolveReferences();
2650 if (Lex.getCode() != tgtok::semi)
2651 return TokError("expected ';' at end of defm");
2658 /// Object ::= ClassInst
2659 /// Object ::= DefInst
2660 /// Object ::= MultiClassInst
2661 /// Object ::= DefMInst
2662 /// Object ::= LETCommand '{' ObjectList '}'
2663 /// Object ::= LETCommand Object
2664 bool TGParser::ParseObject(MultiClass *MC) {
2665 switch (Lex.getCode()) {
2667 return TokError("Expected class, def, defm, multiclass or let definition");
2668 case tgtok::Let: return ParseTopLevelLet(MC);
2669 case tgtok::Def: return ParseDef(MC);
2670 case tgtok::Foreach: return ParseForeach(MC);
2671 case tgtok::Defm: return ParseDefm(MC);
2672 case tgtok::Class: return ParseClass();
2673 case tgtok::MultiClass: return ParseMultiClass();
2678 /// ObjectList :== Object*
2679 bool TGParser::ParseObjectList(MultiClass *MC) {
2680 while (isObjectStart(Lex.getCode())) {
2681 if (ParseObject(MC))
2687 bool TGParser::ParseFile() {
2688 Lex.Lex(); // Prime the lexer.
2689 if (ParseObjectList()) return true;
2691 // If we have unread input at the end of the file, report it.
2692 if (Lex.getCode() == tgtok::Eof)
2695 return TokError("Unexpected input at top level");