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 int 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(NewDef.release());
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();
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 Record *IterRec = new 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 Error(Loc, "foreach iterator value is untyped");
355 IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
357 if (SetValue(IterRec, Loc, IterVar->getName(),
358 std::vector<unsigned>(), IVal)) {
359 Error(Loc, "when instantiating this def");
365 IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
368 IterRec->removeValue(IterVar->getName());
371 if (Records.getDef(IterRec->getNameInitAsString())) {
372 // If this record is anonymous, it's no problem, just generate a new name
373 if (IterRec->isAnonymous())
374 IterRec->setName(GetNewAnonymousName());
376 Error(Loc, "def already exists: " + IterRec->getNameInitAsString());
382 Records.addDef(IterRec);
383 IterRec->resolveReferences();
387 //===----------------------------------------------------------------------===//
389 //===----------------------------------------------------------------------===//
391 /// isObjectStart - Return true if this is a valid first token for an Object.
392 static bool isObjectStart(tgtok::TokKind K) {
393 return K == tgtok::Class || K == tgtok::Def ||
394 K == tgtok::Defm || K == tgtok::Let ||
395 K == tgtok::MultiClass || K == tgtok::Foreach;
398 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
400 std::string TGParser::GetNewAnonymousName() {
401 unsigned Tmp = AnonCounter++; // MSVC2012 ICEs without this.
402 return "anonymous_" + utostr(Tmp);
405 /// ParseObjectName - If an object name is specified, return it. Otherwise,
407 /// ObjectName ::= Value [ '#' Value ]*
408 /// ObjectName ::= /*empty*/
410 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
411 switch (Lex.getCode()) {
415 // These are all of the tokens that can begin an object body.
416 // Some of these can also begin values but we disallow those cases
417 // because they are unlikely to be useful.
423 Record *CurRec = nullptr;
425 CurRec = &CurMultiClass->Rec;
427 RecTy *Type = nullptr;
429 const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
431 TokError("Record name is not typed!");
434 Type = CurRecName->getType();
437 return ParseValue(CurRec, Type, ParseNameMode);
440 /// ParseClassID - Parse and resolve a reference to a class name. This returns
445 Record *TGParser::ParseClassID() {
446 if (Lex.getCode() != tgtok::Id) {
447 TokError("expected name for ClassID");
451 Record *Result = Records.getClass(Lex.getCurStrVal());
453 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
459 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
460 /// This returns null on error.
462 /// MultiClassID ::= ID
464 MultiClass *TGParser::ParseMultiClassID() {
465 if (Lex.getCode() != tgtok::Id) {
466 TokError("expected name for MultiClassID");
470 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
472 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
478 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
479 /// subclass. This returns a SubClassRefTy with a null Record* on error.
481 /// SubClassRef ::= ClassID
482 /// SubClassRef ::= ClassID '<' ValueList '>'
484 SubClassReference TGParser::
485 ParseSubClassReference(Record *CurRec, bool isDefm) {
486 SubClassReference Result;
487 Result.RefRange.Start = Lex.getLoc();
490 if (MultiClass *MC = ParseMultiClassID())
491 Result.Rec = &MC->Rec;
493 Result.Rec = ParseClassID();
495 if (!Result.Rec) return Result;
497 // If there is no template arg list, we're done.
498 if (Lex.getCode() != tgtok::less) {
499 Result.RefRange.End = Lex.getLoc();
502 Lex.Lex(); // Eat the '<'
504 if (Lex.getCode() == tgtok::greater) {
505 TokError("subclass reference requires a non-empty list of template values");
506 Result.Rec = nullptr;
510 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
511 if (Result.TemplateArgs.empty()) {
512 Result.Rec = nullptr; // Error parsing value list.
516 if (Lex.getCode() != tgtok::greater) {
517 TokError("expected '>' in template value list");
518 Result.Rec = nullptr;
522 Result.RefRange.End = Lex.getLoc();
527 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
528 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
529 /// Record* on error.
531 /// SubMultiClassRef ::= MultiClassID
532 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
534 SubMultiClassReference TGParser::
535 ParseSubMultiClassReference(MultiClass *CurMC) {
536 SubMultiClassReference Result;
537 Result.RefRange.Start = Lex.getLoc();
539 Result.MC = ParseMultiClassID();
540 if (!Result.MC) return Result;
542 // If there is no template arg list, we're done.
543 if (Lex.getCode() != tgtok::less) {
544 Result.RefRange.End = Lex.getLoc();
547 Lex.Lex(); // Eat the '<'
549 if (Lex.getCode() == tgtok::greater) {
550 TokError("subclass reference requires a non-empty list of template values");
555 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
556 if (Result.TemplateArgs.empty()) {
557 Result.MC = nullptr; // Error parsing value list.
561 if (Lex.getCode() != tgtok::greater) {
562 TokError("expected '>' in template value list");
567 Result.RefRange.End = Lex.getLoc();
572 /// ParseRangePiece - Parse a bit/value range.
573 /// RangePiece ::= INTVAL
574 /// RangePiece ::= INTVAL '-' INTVAL
575 /// RangePiece ::= INTVAL INTVAL
576 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
577 if (Lex.getCode() != tgtok::IntVal) {
578 TokError("expected integer or bitrange");
581 int64_t Start = Lex.getCurIntVal();
585 return TokError("invalid range, cannot be negative");
587 switch (Lex.Lex()) { // eat first character.
589 Ranges.push_back(Start);
592 if (Lex.Lex() != tgtok::IntVal) {
593 TokError("expected integer value as end of range");
596 End = Lex.getCurIntVal();
599 End = -Lex.getCurIntVal();
603 return TokError("invalid range, cannot be negative");
608 for (; Start <= End; ++Start)
609 Ranges.push_back(Start);
611 for (; Start >= End; --Start)
612 Ranges.push_back(Start);
617 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
619 /// RangeList ::= RangePiece (',' RangePiece)*
621 std::vector<unsigned> TGParser::ParseRangeList() {
622 std::vector<unsigned> Result;
624 // Parse the first piece.
625 if (ParseRangePiece(Result))
626 return std::vector<unsigned>();
627 while (Lex.getCode() == tgtok::comma) {
628 Lex.Lex(); // Eat the comma.
630 // Parse the next range piece.
631 if (ParseRangePiece(Result))
632 return std::vector<unsigned>();
637 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
638 /// OptionalRangeList ::= '<' RangeList '>'
639 /// OptionalRangeList ::= /*empty*/
640 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
641 if (Lex.getCode() != tgtok::less)
644 SMLoc StartLoc = Lex.getLoc();
645 Lex.Lex(); // eat the '<'
647 // Parse the range list.
648 Ranges = ParseRangeList();
649 if (Ranges.empty()) return true;
651 if (Lex.getCode() != tgtok::greater) {
652 TokError("expected '>' at end of range list");
653 return Error(StartLoc, "to match this '<'");
655 Lex.Lex(); // eat the '>'.
659 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
660 /// OptionalBitList ::= '{' RangeList '}'
661 /// OptionalBitList ::= /*empty*/
662 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
663 if (Lex.getCode() != tgtok::l_brace)
666 SMLoc StartLoc = Lex.getLoc();
667 Lex.Lex(); // eat the '{'
669 // Parse the range list.
670 Ranges = ParseRangeList();
671 if (Ranges.empty()) return true;
673 if (Lex.getCode() != tgtok::r_brace) {
674 TokError("expected '}' at end of bit list");
675 return Error(StartLoc, "to match this '{'");
677 Lex.Lex(); // eat the '}'.
682 /// ParseType - Parse and return a tblgen type. This returns null on error.
684 /// Type ::= STRING // string type
685 /// Type ::= CODE // code type
686 /// Type ::= BIT // bit type
687 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
688 /// Type ::= INT // int type
689 /// Type ::= LIST '<' Type '>' // list<x> type
690 /// Type ::= DAG // dag type
691 /// Type ::= ClassID // Record Type
693 RecTy *TGParser::ParseType() {
694 switch (Lex.getCode()) {
695 default: TokError("Unknown token when expecting a type"); return nullptr;
696 case tgtok::String: Lex.Lex(); return StringRecTy::get();
697 case tgtok::Code: Lex.Lex(); return StringRecTy::get();
698 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
699 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
700 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
702 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
705 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
706 TokError("expected '<' after bits type");
709 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
710 TokError("expected integer in bits<n> type");
713 uint64_t Val = Lex.getCurIntVal();
714 if (Lex.Lex() != tgtok::greater) { // Eat count.
715 TokError("expected '>' at end of bits<n> type");
718 Lex.Lex(); // Eat '>'
719 return BitsRecTy::get(Val);
722 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
723 TokError("expected '<' after list type");
726 Lex.Lex(); // Eat '<'
727 RecTy *SubType = ParseType();
728 if (!SubType) return nullptr;
730 if (Lex.getCode() != tgtok::greater) {
731 TokError("expected '>' at end of list<ty> type");
734 Lex.Lex(); // Eat '>'
735 return ListRecTy::get(SubType);
740 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
741 /// has already been read.
742 Init *TGParser::ParseIDValue(Record *CurRec,
743 const std::string &Name, SMLoc NameLoc,
746 if (const RecordVal *RV = CurRec->getValue(Name))
747 return VarInit::get(Name, RV->getType());
749 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
752 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
755 if (CurRec->isTemplateArg(TemplateArgName)) {
756 const RecordVal *RV = CurRec->getValue(TemplateArgName);
757 assert(RV && "Template arg doesn't exist??");
758 return VarInit::get(TemplateArgName, RV->getType());
763 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
766 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
767 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
768 assert(RV && "Template arg doesn't exist??");
769 return VarInit::get(MCName, RV->getType());
773 // If this is in a foreach loop, make sure it's not a loop iterator
774 for (LoopVector::iterator i = Loops.begin(), iend = Loops.end();
777 VarInit *IterVar = dyn_cast<VarInit>(i->IterVar);
778 if (IterVar && IterVar->getName() == Name)
782 if (Mode == ParseNameMode)
783 return StringInit::get(Name);
785 if (Record *D = Records.getDef(Name))
786 return DefInit::get(D);
788 if (Mode == ParseValueMode) {
789 Error(NameLoc, "Variable not defined: '" + Name + "'");
793 return StringInit::get(Name);
796 /// ParseOperation - Parse an operator. This returns null on error.
798 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
800 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
801 switch (Lex.getCode()) {
803 TokError("unknown operation");
808 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
809 UnOpInit::UnaryOp Code;
810 RecTy *Type = nullptr;
812 switch (Lex.getCode()) {
813 default: llvm_unreachable("Unhandled code!");
815 Lex.Lex(); // eat the operation
816 Code = UnOpInit::CAST;
818 Type = ParseOperatorType();
821 TokError("did not get type for unary operator");
827 Lex.Lex(); // eat the operation
828 Code = UnOpInit::HEAD;
831 Lex.Lex(); // eat the operation
832 Code = UnOpInit::TAIL;
835 Lex.Lex(); // eat the operation
836 Code = UnOpInit::EMPTY;
837 Type = IntRecTy::get();
840 if (Lex.getCode() != tgtok::l_paren) {
841 TokError("expected '(' after unary operator");
844 Lex.Lex(); // eat the '('
846 Init *LHS = ParseValue(CurRec);
847 if (!LHS) return nullptr;
849 if (Code == UnOpInit::HEAD
850 || Code == UnOpInit::TAIL
851 || Code == UnOpInit::EMPTY) {
852 ListInit *LHSl = dyn_cast<ListInit>(LHS);
853 StringInit *LHSs = dyn_cast<StringInit>(LHS);
854 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
855 if (!LHSl && !LHSs && !LHSt) {
856 TokError("expected list or string type argument in unary operator");
860 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
861 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
862 if (!LType && !SType) {
863 TokError("expected list or string type argument in unary operator");
868 if (Code == UnOpInit::HEAD
869 || Code == UnOpInit::TAIL) {
870 if (!LHSl && !LHSt) {
871 TokError("expected list type argument in unary operator");
875 if (LHSl && LHSl->getSize() == 0) {
876 TokError("empty list argument in unary operator");
880 Init *Item = LHSl->getElement(0);
881 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
883 TokError("untyped list element in unary operator");
886 if (Code == UnOpInit::HEAD) {
887 Type = Itemt->getType();
889 Type = ListRecTy::get(Itemt->getType());
892 assert(LHSt && "expected list type argument in unary operator");
893 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
895 TokError("expected list type argument in unary operator");
898 if (Code == UnOpInit::HEAD) {
899 Type = LType->getElementType();
907 if (Lex.getCode() != tgtok::r_paren) {
908 TokError("expected ')' in unary operator");
911 Lex.Lex(); // eat the ')'
912 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
922 case tgtok::XListConcat:
923 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
924 tgtok::TokKind OpTok = Lex.getCode();
925 SMLoc OpLoc = Lex.getLoc();
926 Lex.Lex(); // eat the operation
928 BinOpInit::BinaryOp Code;
929 RecTy *Type = nullptr;
932 default: llvm_unreachable("Unhandled code!");
933 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
934 case tgtok::XADD: Code = BinOpInit::ADD; Type = IntRecTy::get(); break;
935 case tgtok::XAND: Code = BinOpInit::AND; Type = IntRecTy::get(); break;
936 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
937 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
938 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
939 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
940 case tgtok::XListConcat:
941 Code = BinOpInit::LISTCONCAT;
942 // We don't know the list type until we parse the first argument
944 case tgtok::XStrConcat:
945 Code = BinOpInit::STRCONCAT;
946 Type = StringRecTy::get();
950 if (Lex.getCode() != tgtok::l_paren) {
951 TokError("expected '(' after binary operator");
954 Lex.Lex(); // eat the '('
956 SmallVector<Init*, 2> InitList;
958 InitList.push_back(ParseValue(CurRec));
959 if (!InitList.back()) return nullptr;
961 while (Lex.getCode() == tgtok::comma) {
962 Lex.Lex(); // eat the ','
964 InitList.push_back(ParseValue(CurRec));
965 if (!InitList.back()) return nullptr;
968 if (Lex.getCode() != tgtok::r_paren) {
969 TokError("expected ')' in operator");
972 Lex.Lex(); // eat the ')'
974 // If we are doing !listconcat, we should know the type by now
975 if (OpTok == tgtok::XListConcat) {
976 if (VarInit *Arg0 = dyn_cast<VarInit>(InitList[0]))
977 Type = Arg0->getType();
978 else if (ListInit *Arg0 = dyn_cast<ListInit>(InitList[0]))
979 Type = Arg0->getType();
982 Error(OpLoc, "expected a list");
987 // We allow multiple operands to associative operators like !strconcat as
988 // shorthand for nesting them.
989 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT) {
990 while (InitList.size() > 2) {
991 Init *RHS = InitList.pop_back_val();
992 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
993 ->Fold(CurRec, CurMultiClass);
994 InitList.back() = RHS;
998 if (InitList.size() == 2)
999 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
1000 ->Fold(CurRec, CurMultiClass);
1002 Error(OpLoc, "expected two operands to operator");
1007 case tgtok::XForEach:
1008 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1009 TernOpInit::TernaryOp Code;
1010 RecTy *Type = nullptr;
1012 tgtok::TokKind LexCode = Lex.getCode();
1013 Lex.Lex(); // eat the operation
1015 default: llvm_unreachable("Unhandled code!");
1017 Code = TernOpInit::IF;
1019 case tgtok::XForEach:
1020 Code = TernOpInit::FOREACH;
1023 Code = TernOpInit::SUBST;
1026 if (Lex.getCode() != tgtok::l_paren) {
1027 TokError("expected '(' after ternary operator");
1030 Lex.Lex(); // eat the '('
1032 Init *LHS = ParseValue(CurRec);
1033 if (!LHS) return nullptr;
1035 if (Lex.getCode() != tgtok::comma) {
1036 TokError("expected ',' in ternary operator");
1039 Lex.Lex(); // eat the ','
1041 Init *MHS = ParseValue(CurRec, ItemType);
1045 if (Lex.getCode() != tgtok::comma) {
1046 TokError("expected ',' in ternary operator");
1049 Lex.Lex(); // eat the ','
1051 Init *RHS = ParseValue(CurRec, ItemType);
1055 if (Lex.getCode() != tgtok::r_paren) {
1056 TokError("expected ')' in binary operator");
1059 Lex.Lex(); // eat the ')'
1062 default: llvm_unreachable("Unhandled code!");
1064 RecTy *MHSTy = nullptr;
1065 RecTy *RHSTy = nullptr;
1067 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1068 MHSTy = MHSt->getType();
1069 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1070 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1071 if (isa<BitInit>(MHS))
1072 MHSTy = BitRecTy::get();
1074 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1075 RHSTy = RHSt->getType();
1076 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1077 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1078 if (isa<BitInit>(RHS))
1079 RHSTy = BitRecTy::get();
1081 // For UnsetInit, it's typed from the other hand.
1082 if (isa<UnsetInit>(MHS))
1084 if (isa<UnsetInit>(RHS))
1087 if (!MHSTy || !RHSTy) {
1088 TokError("could not get type for !if");
1092 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1094 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1097 TokError("inconsistent types for !if");
1102 case tgtok::XForEach: {
1103 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1105 TokError("could not get type for !foreach");
1108 Type = MHSt->getType();
1111 case tgtok::XSubst: {
1112 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1114 TokError("could not get type for !subst");
1117 Type = RHSt->getType();
1121 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1127 /// ParseOperatorType - Parse a type for an operator. This returns
1130 /// OperatorType ::= '<' Type '>'
1132 RecTy *TGParser::ParseOperatorType() {
1133 RecTy *Type = nullptr;
1135 if (Lex.getCode() != tgtok::less) {
1136 TokError("expected type name for operator");
1139 Lex.Lex(); // eat the <
1144 TokError("expected type name for operator");
1148 if (Lex.getCode() != tgtok::greater) {
1149 TokError("expected type name for operator");
1152 Lex.Lex(); // eat the >
1158 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1160 /// SimpleValue ::= IDValue
1161 /// SimpleValue ::= INTVAL
1162 /// SimpleValue ::= STRVAL+
1163 /// SimpleValue ::= CODEFRAGMENT
1164 /// SimpleValue ::= '?'
1165 /// SimpleValue ::= '{' ValueList '}'
1166 /// SimpleValue ::= ID '<' ValueListNE '>'
1167 /// SimpleValue ::= '[' ValueList ']'
1168 /// SimpleValue ::= '(' IDValue DagArgList ')'
1169 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1170 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1171 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1172 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1173 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1174 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1175 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1177 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1180 switch (Lex.getCode()) {
1181 default: TokError("Unknown token when parsing a value"); break;
1183 // This is a leading paste operation. This is deprecated but
1184 // still exists in some .td files. Ignore it.
1185 Lex.Lex(); // Skip '#'.
1186 return ParseSimpleValue(CurRec, ItemType, Mode);
1187 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1188 case tgtok::BinaryIntVal: {
1189 auto BinaryVal = Lex.getCurBinaryIntVal();
1190 SmallVector<Init*, 16> Bits(BinaryVal.second);
1191 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
1192 Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
1193 R = BitsInit::get(Bits);
1197 case tgtok::StrVal: {
1198 std::string Val = Lex.getCurStrVal();
1201 // Handle multiple consecutive concatenated strings.
1202 while (Lex.getCode() == tgtok::StrVal) {
1203 Val += Lex.getCurStrVal();
1207 R = StringInit::get(Val);
1210 case tgtok::CodeFragment:
1211 R = StringInit::get(Lex.getCurStrVal());
1214 case tgtok::question:
1215 R = UnsetInit::get();
1219 SMLoc NameLoc = Lex.getLoc();
1220 std::string Name = Lex.getCurStrVal();
1221 if (Lex.Lex() != tgtok::less) // consume the Id.
1222 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1224 // Value ::= ID '<' ValueListNE '>'
1225 if (Lex.Lex() == tgtok::greater) {
1226 TokError("expected non-empty value list");
1230 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1231 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1233 Record *Class = Records.getClass(Name);
1235 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1239 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1240 if (ValueList.empty()) return nullptr;
1242 if (Lex.getCode() != tgtok::greater) {
1243 TokError("expected '>' at end of value list");
1246 Lex.Lex(); // eat the '>'
1247 SMLoc EndLoc = Lex.getLoc();
1249 // Create the new record, set it as CurRec temporarily.
1250 Record *NewRec = new Record(GetNewAnonymousName(), NameLoc, Records,
1251 /*IsAnonymous=*/true);
1252 SubClassReference SCRef;
1253 SCRef.RefRange = SMRange(NameLoc, EndLoc);
1255 SCRef.TemplateArgs = ValueList;
1256 // Add info about the subclass to NewRec.
1257 if (AddSubClass(NewRec, SCRef)) {
1261 if (!CurMultiClass) {
1262 NewRec->resolveReferences();
1263 Records.addDef(NewRec);
1265 // This needs to get resolved once the multiclass template arguments are
1266 // known before any use.
1267 NewRec->setResolveFirst(true);
1268 // Otherwise, we're inside a multiclass, add it to the multiclass.
1269 CurMultiClass->DefPrototypes.push_back(NewRec);
1271 // Copy the template arguments for the multiclass into the def.
1272 const std::vector<Init *> &TArgs =
1273 CurMultiClass->Rec.getTemplateArgs();
1275 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1276 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1277 assert(RV && "Template arg doesn't exist?");
1278 NewRec->addValue(*RV);
1281 // We can't return the prototype def here, instead return:
1282 // !cast<ItemType>(!strconcat(NAME, AnonName)).
1283 const RecordVal *MCNameRV = CurMultiClass->Rec.getValue("NAME");
1284 assert(MCNameRV && "multiclass record must have a NAME");
1286 return UnOpInit::get(UnOpInit::CAST,
1287 BinOpInit::get(BinOpInit::STRCONCAT,
1288 VarInit::get(MCNameRV->getName(),
1289 MCNameRV->getType()),
1290 NewRec->getNameInit(),
1291 StringRecTy::get()),
1292 Class->getDefInit()->getType());
1295 // The result of the expression is a reference to the new record.
1296 return DefInit::get(NewRec);
1298 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1299 SMLoc BraceLoc = Lex.getLoc();
1300 Lex.Lex(); // eat the '{'
1301 std::vector<Init*> Vals;
1303 if (Lex.getCode() != tgtok::r_brace) {
1304 Vals = ParseValueList(CurRec);
1305 if (Vals.empty()) return nullptr;
1307 if (Lex.getCode() != tgtok::r_brace) {
1308 TokError("expected '}' at end of bit list value");
1311 Lex.Lex(); // eat the '}'
1313 SmallVector<Init *, 16> NewBits;
1315 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
1316 // first. We'll first read everything in to a vector, then we can reverse
1317 // it to get the bits in the correct order for the BitsInit value.
1318 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1319 // FIXME: The following two loops would not be duplicated
1320 // if the API was a little more orthogonal.
1322 // bits<n> values are allowed to initialize n bits.
1323 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
1324 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
1325 NewBits.push_back(BI->getBit((e - i) - 1));
1328 // bits<n> can also come from variable initializers.
1329 if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
1330 if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
1331 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
1332 NewBits.push_back(VI->getBit((e - i) - 1));
1335 // Fallthrough to try convert this to a bit.
1337 // All other values must be convertible to just a single bit.
1338 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1340 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1341 ") is not convertable to a bit");
1344 NewBits.push_back(Bit);
1346 std::reverse(NewBits.begin(), NewBits.end());
1347 return BitsInit::get(NewBits);
1349 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1350 Lex.Lex(); // eat the '['
1351 std::vector<Init*> Vals;
1353 RecTy *DeducedEltTy = nullptr;
1354 ListRecTy *GivenListTy = nullptr;
1357 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1360 raw_string_ostream ss(s);
1361 ss << "Type mismatch for list, expected list type, got "
1362 << ItemType->getAsString();
1366 GivenListTy = ListType;
1369 if (Lex.getCode() != tgtok::r_square) {
1370 Vals = ParseValueList(CurRec, nullptr,
1371 GivenListTy ? GivenListTy->getElementType() : nullptr);
1372 if (Vals.empty()) return nullptr;
1374 if (Lex.getCode() != tgtok::r_square) {
1375 TokError("expected ']' at end of list value");
1378 Lex.Lex(); // eat the ']'
1380 RecTy *GivenEltTy = nullptr;
1381 if (Lex.getCode() == tgtok::less) {
1382 // Optional list element type
1383 Lex.Lex(); // eat the '<'
1385 GivenEltTy = ParseType();
1387 // Couldn't parse element type
1391 if (Lex.getCode() != tgtok::greater) {
1392 TokError("expected '>' at end of list element type");
1395 Lex.Lex(); // eat the '>'
1399 RecTy *EltTy = nullptr;
1400 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1403 TypedInit *TArg = dyn_cast<TypedInit>(*i);
1405 TokError("Untyped list element");
1409 EltTy = resolveTypes(EltTy, TArg->getType());
1411 TokError("Incompatible types in list elements");
1415 EltTy = TArg->getType();
1421 // Verify consistency
1422 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1423 TokError("Incompatible types in list elements");
1432 TokError("No type for list");
1435 DeducedEltTy = GivenListTy->getElementType();
1437 // Make sure the deduced type is compatible with the given type
1439 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1440 TokError("Element type mismatch for list");
1444 DeducedEltTy = EltTy;
1447 return ListInit::get(Vals, DeducedEltTy);
1449 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1450 Lex.Lex(); // eat the '('
1451 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1452 TokError("expected identifier in dag init");
1456 Init *Operator = ParseValue(CurRec);
1457 if (!Operator) return nullptr;
1459 // If the operator name is present, parse it.
1460 std::string OperatorName;
1461 if (Lex.getCode() == tgtok::colon) {
1462 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1463 TokError("expected variable name in dag operator");
1466 OperatorName = Lex.getCurStrVal();
1467 Lex.Lex(); // eat the VarName.
1470 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1471 if (Lex.getCode() != tgtok::r_paren) {
1472 DagArgs = ParseDagArgList(CurRec);
1473 if (DagArgs.empty()) return nullptr;
1476 if (Lex.getCode() != tgtok::r_paren) {
1477 TokError("expected ')' in dag init");
1480 Lex.Lex(); // eat the ')'
1482 return DagInit::get(Operator, OperatorName, DagArgs);
1488 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1489 case tgtok::XConcat:
1496 case tgtok::XListConcat:
1497 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1499 case tgtok::XForEach:
1500 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1501 return ParseOperation(CurRec, ItemType);
1508 /// ParseValue - Parse a tblgen value. This returns null on error.
1510 /// Value ::= SimpleValue ValueSuffix*
1511 /// ValueSuffix ::= '{' BitList '}'
1512 /// ValueSuffix ::= '[' BitList ']'
1513 /// ValueSuffix ::= '.' ID
1515 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1516 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1517 if (!Result) return nullptr;
1519 // Parse the suffixes now if present.
1521 switch (Lex.getCode()) {
1522 default: return Result;
1523 case tgtok::l_brace: {
1524 if (Mode == ParseNameMode || Mode == ParseForeachMode)
1525 // This is the beginning of the object body.
1528 SMLoc CurlyLoc = Lex.getLoc();
1529 Lex.Lex(); // eat the '{'
1530 std::vector<unsigned> Ranges = ParseRangeList();
1531 if (Ranges.empty()) return nullptr;
1533 // Reverse the bitlist.
1534 std::reverse(Ranges.begin(), Ranges.end());
1535 Result = Result->convertInitializerBitRange(Ranges);
1537 Error(CurlyLoc, "Invalid bit range for value");
1542 if (Lex.getCode() != tgtok::r_brace) {
1543 TokError("expected '}' at end of bit range list");
1549 case tgtok::l_square: {
1550 SMLoc SquareLoc = Lex.getLoc();
1551 Lex.Lex(); // eat the '['
1552 std::vector<unsigned> Ranges = ParseRangeList();
1553 if (Ranges.empty()) return nullptr;
1555 Result = Result->convertInitListSlice(Ranges);
1557 Error(SquareLoc, "Invalid range for list slice");
1562 if (Lex.getCode() != tgtok::r_square) {
1563 TokError("expected ']' at end of list slice");
1570 if (Lex.Lex() != tgtok::Id) { // eat the .
1571 TokError("expected field identifier after '.'");
1574 if (!Result->getFieldType(Lex.getCurStrVal())) {
1575 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1576 Result->getAsString() + "'");
1579 Result = FieldInit::get(Result, Lex.getCurStrVal());
1580 Lex.Lex(); // eat field name
1584 SMLoc PasteLoc = Lex.getLoc();
1586 // Create a !strconcat() operation, first casting each operand to
1587 // a string if necessary.
1589 TypedInit *LHS = dyn_cast<TypedInit>(Result);
1591 Error(PasteLoc, "LHS of paste is not typed!");
1595 if (LHS->getType() != StringRecTy::get()) {
1596 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1599 TypedInit *RHS = nullptr;
1601 Lex.Lex(); // Eat the '#'.
1602 switch (Lex.getCode()) {
1605 case tgtok::l_brace:
1606 // These are all of the tokens that can begin an object body.
1607 // Some of these can also begin values but we disallow those cases
1608 // because they are unlikely to be useful.
1610 // Trailing paste, concat with an empty string.
1611 RHS = StringInit::get("");
1615 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1616 RHS = dyn_cast<TypedInit>(RHSResult);
1618 Error(PasteLoc, "RHS of paste is not typed!");
1622 if (RHS->getType() != StringRecTy::get()) {
1623 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1629 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1630 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1636 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1638 /// DagArg ::= Value (':' VARNAME)?
1639 /// DagArg ::= VARNAME
1640 /// DagArgList ::= DagArg
1641 /// DagArgList ::= DagArgList ',' DagArg
1642 std::vector<std::pair<llvm::Init*, std::string> >
1643 TGParser::ParseDagArgList(Record *CurRec) {
1644 std::vector<std::pair<llvm::Init*, std::string> > Result;
1647 // DagArg ::= VARNAME
1648 if (Lex.getCode() == tgtok::VarName) {
1649 // A missing value is treated like '?'.
1650 Result.push_back(std::make_pair(UnsetInit::get(), Lex.getCurStrVal()));
1653 // DagArg ::= Value (':' VARNAME)?
1654 Init *Val = ParseValue(CurRec);
1656 return std::vector<std::pair<llvm::Init*, std::string> >();
1658 // If the variable name is present, add it.
1659 std::string VarName;
1660 if (Lex.getCode() == tgtok::colon) {
1661 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1662 TokError("expected variable name in dag literal");
1663 return std::vector<std::pair<llvm::Init*, std::string> >();
1665 VarName = Lex.getCurStrVal();
1666 Lex.Lex(); // eat the VarName.
1669 Result.push_back(std::make_pair(Val, VarName));
1671 if (Lex.getCode() != tgtok::comma) break;
1672 Lex.Lex(); // eat the ','
1679 /// ParseValueList - Parse a comma separated list of values, returning them as a
1680 /// vector. Note that this always expects to be able to parse at least one
1681 /// value. It returns an empty list if this is not possible.
1683 /// ValueList ::= Value (',' Value)
1685 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1687 std::vector<Init*> Result;
1688 RecTy *ItemType = EltTy;
1689 unsigned int ArgN = 0;
1690 if (ArgsRec && !EltTy) {
1691 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1692 if (!TArgs.size()) {
1693 TokError("template argument provided to non-template class");
1694 return std::vector<Init*>();
1696 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1698 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1701 assert(RV && "Template argument record not found??");
1702 ItemType = RV->getType();
1705 Result.push_back(ParseValue(CurRec, ItemType));
1706 if (!Result.back()) return std::vector<Init*>();
1708 while (Lex.getCode() == tgtok::comma) {
1709 Lex.Lex(); // Eat the comma
1711 if (ArgsRec && !EltTy) {
1712 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1713 if (ArgN >= TArgs.size()) {
1714 TokError("too many template arguments");
1715 return std::vector<Init*>();
1717 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1718 assert(RV && "Template argument record not found??");
1719 ItemType = RV->getType();
1722 Result.push_back(ParseValue(CurRec, ItemType));
1723 if (!Result.back()) return std::vector<Init*>();
1730 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1731 /// empty string on error. This can happen in a number of different context's,
1732 /// including within a def or in the template args for a def (which which case
1733 /// CurRec will be non-null) and within the template args for a multiclass (in
1734 /// which case CurRec will be null, but CurMultiClass will be set). This can
1735 /// also happen within a def that is within a multiclass, which will set both
1736 /// CurRec and CurMultiClass.
1738 /// Declaration ::= FIELD? Type ID ('=' Value)?
1740 Init *TGParser::ParseDeclaration(Record *CurRec,
1741 bool ParsingTemplateArgs) {
1742 // Read the field prefix if present.
1743 bool HasField = Lex.getCode() == tgtok::Field;
1744 if (HasField) Lex.Lex();
1746 RecTy *Type = ParseType();
1747 if (!Type) return nullptr;
1749 if (Lex.getCode() != tgtok::Id) {
1750 TokError("Expected identifier in declaration");
1754 SMLoc IdLoc = Lex.getLoc();
1755 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1758 if (ParsingTemplateArgs) {
1760 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1762 assert(CurMultiClass);
1765 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1770 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1773 // If a value is present, parse it.
1774 if (Lex.getCode() == tgtok::equal) {
1776 SMLoc ValLoc = Lex.getLoc();
1777 Init *Val = ParseValue(CurRec, Type);
1779 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1780 // Return the name, even if an error is thrown. This is so that we can
1781 // continue to make some progress, even without the value having been
1789 /// ParseForeachDeclaration - Read a foreach declaration, returning
1790 /// the name of the declared object or a NULL Init on error. Return
1791 /// the name of the parsed initializer list through ForeachListName.
1793 /// ForeachDeclaration ::= ID '=' '[' ValueList ']'
1794 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
1795 /// ForeachDeclaration ::= ID '=' RangePiece
1797 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1798 if (Lex.getCode() != tgtok::Id) {
1799 TokError("Expected identifier in foreach declaration");
1803 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1806 // If a value is present, parse it.
1807 if (Lex.getCode() != tgtok::equal) {
1808 TokError("Expected '=' in foreach declaration");
1811 Lex.Lex(); // Eat the '='
1813 RecTy *IterType = nullptr;
1814 std::vector<unsigned> Ranges;
1816 switch (Lex.getCode()) {
1817 default: TokError("Unknown token when expecting a range list"); return nullptr;
1818 case tgtok::l_square: { // '[' ValueList ']'
1819 Init *List = ParseSimpleValue(nullptr, nullptr, ParseForeachMode);
1820 ForeachListValue = dyn_cast<ListInit>(List);
1821 if (!ForeachListValue) {
1822 TokError("Expected a Value list");
1825 RecTy *ValueType = ForeachListValue->getType();
1826 ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1828 TokError("Value list is not of list type");
1831 IterType = ListType->getElementType();
1835 case tgtok::IntVal: { // RangePiece.
1836 if (ParseRangePiece(Ranges))
1841 case tgtok::l_brace: { // '{' RangeList '}'
1842 Lex.Lex(); // eat the '{'
1843 Ranges = ParseRangeList();
1844 if (Lex.getCode() != tgtok::r_brace) {
1845 TokError("expected '}' at end of bit range list");
1853 if (!Ranges.empty()) {
1854 assert(!IterType && "Type already initialized?");
1855 IterType = IntRecTy::get();
1856 std::vector<Init*> Values;
1857 for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
1858 Values.push_back(IntInit::get(Ranges[i]));
1859 ForeachListValue = ListInit::get(Values, IterType);
1865 return VarInit::get(DeclName, IterType);
1868 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1869 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1870 /// template args for a def, which may or may not be in a multiclass. If null,
1871 /// these are the template args for a multiclass.
1873 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1875 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1876 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1877 Lex.Lex(); // eat the '<'
1879 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1881 // Read the first declaration.
1882 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1886 TheRecToAddTo->addTemplateArg(TemplArg);
1888 while (Lex.getCode() == tgtok::comma) {
1889 Lex.Lex(); // eat the ','
1891 // Read the following declarations.
1892 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1895 TheRecToAddTo->addTemplateArg(TemplArg);
1898 if (Lex.getCode() != tgtok::greater)
1899 return TokError("expected '>' at end of template argument list");
1900 Lex.Lex(); // eat the '>'.
1905 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1907 /// BodyItem ::= Declaration ';'
1908 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1909 bool TGParser::ParseBodyItem(Record *CurRec) {
1910 if (Lex.getCode() != tgtok::Let) {
1911 if (!ParseDeclaration(CurRec, false))
1914 if (Lex.getCode() != tgtok::semi)
1915 return TokError("expected ';' after declaration");
1920 // LET ID OptionalRangeList '=' Value ';'
1921 if (Lex.Lex() != tgtok::Id)
1922 return TokError("expected field identifier after let");
1924 SMLoc IdLoc = Lex.getLoc();
1925 std::string FieldName = Lex.getCurStrVal();
1926 Lex.Lex(); // eat the field name.
1928 std::vector<unsigned> BitList;
1929 if (ParseOptionalBitList(BitList))
1931 std::reverse(BitList.begin(), BitList.end());
1933 if (Lex.getCode() != tgtok::equal)
1934 return TokError("expected '=' in let expression");
1935 Lex.Lex(); // eat the '='.
1937 RecordVal *Field = CurRec->getValue(FieldName);
1939 return TokError("Value '" + FieldName + "' unknown!");
1941 RecTy *Type = Field->getType();
1943 Init *Val = ParseValue(CurRec, Type);
1944 if (!Val) return true;
1946 if (Lex.getCode() != tgtok::semi)
1947 return TokError("expected ';' after let expression");
1950 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1953 /// ParseBody - Read the body of a class or def. Return true on error, false on
1957 /// Body ::= '{' BodyList '}'
1958 /// BodyList BodyItem*
1960 bool TGParser::ParseBody(Record *CurRec) {
1961 // If this is a null definition, just eat the semi and return.
1962 if (Lex.getCode() == tgtok::semi) {
1967 if (Lex.getCode() != tgtok::l_brace)
1968 return TokError("Expected ';' or '{' to start body");
1972 while (Lex.getCode() != tgtok::r_brace)
1973 if (ParseBodyItem(CurRec))
1981 /// \brief Apply the current let bindings to \a CurRec.
1982 /// \returns true on error, false otherwise.
1983 bool TGParser::ApplyLetStack(Record *CurRec) {
1984 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1985 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1986 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1987 LetStack[i][j].Bits, LetStack[i][j].Value))
1992 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1993 /// optional ClassList followed by a Body. CurRec is the current def or class
1994 /// that is being parsed.
1996 /// ObjectBody ::= BaseClassList Body
1997 /// BaseClassList ::= /*empty*/
1998 /// BaseClassList ::= ':' BaseClassListNE
1999 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
2001 bool TGParser::ParseObjectBody(Record *CurRec) {
2002 // If there is a baseclass list, read it.
2003 if (Lex.getCode() == tgtok::colon) {
2006 // Read all of the subclasses.
2007 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
2010 if (!SubClass.Rec) return true;
2013 if (AddSubClass(CurRec, SubClass))
2016 if (Lex.getCode() != tgtok::comma) break;
2017 Lex.Lex(); // eat ','.
2018 SubClass = ParseSubClassReference(CurRec, false);
2022 if (ApplyLetStack(CurRec))
2025 return ParseBody(CurRec);
2028 /// ParseDef - Parse and return a top level or multiclass def, return the record
2029 /// corresponding to it. This returns null on error.
2031 /// DefInst ::= DEF ObjectName ObjectBody
2033 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
2034 SMLoc DefLoc = Lex.getLoc();
2035 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
2036 Lex.Lex(); // Eat the 'def' token.
2038 // Parse ObjectName and make a record for it.
2040 bool CurRecOwnershipTransferred = false;
2041 Init *Name = ParseObjectName(CurMultiClass);
2043 CurRec = new Record(Name, DefLoc, Records);
2045 CurRec = new Record(GetNewAnonymousName(), DefLoc, Records,
2046 /*IsAnonymous=*/true);
2048 if (!CurMultiClass && Loops.empty()) {
2049 // Top-level def definition.
2051 // Ensure redefinition doesn't happen.
2052 if (Records.getDef(CurRec->getNameInitAsString())) {
2053 Error(DefLoc, "def '" + CurRec->getNameInitAsString()
2054 + "' already defined");
2058 Records.addDef(CurRec);
2059 CurRecOwnershipTransferred = true;
2061 if (ParseObjectBody(CurRec))
2063 } else if (CurMultiClass) {
2064 // Parse the body before adding this prototype to the DefPrototypes vector.
2065 // That way implicit definitions will be added to the DefPrototypes vector
2066 // before this object, instantiated prior to defs derived from this object,
2067 // and this available for indirect name resolution when defs derived from
2068 // this object are instantiated.
2069 if (ParseObjectBody(CurRec)) {
2074 // Otherwise, a def inside a multiclass, add it to the multiclass.
2075 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
2076 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2077 == CurRec->getNameInit()) {
2078 Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
2079 "' already defined in this multiclass!");
2083 CurMultiClass->DefPrototypes.push_back(CurRec);
2084 CurRecOwnershipTransferred = true;
2085 } else if (ParseObjectBody(CurRec)) {
2090 if (!CurMultiClass) // Def's in multiclasses aren't really defs.
2091 // See Record::setName(). This resolve step will see any new name
2092 // for the def that might have been created when resolving
2093 // inheritance, values and arguments above.
2094 CurRec->resolveReferences();
2096 // If ObjectBody has template arguments, it's an error.
2097 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
2099 if (CurMultiClass) {
2100 // Copy the template arguments for the multiclass into the def.
2101 const std::vector<Init *> &TArgs =
2102 CurMultiClass->Rec.getTemplateArgs();
2104 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2105 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
2106 assert(RV && "Template arg doesn't exist?");
2107 CurRec->addValue(*RV);
2111 if (ProcessForeachDefs(CurRec, DefLoc)) {
2113 "Could not process loops for def" + CurRec->getNameInitAsString());
2114 if (!CurRecOwnershipTransferred)
2119 if (!CurRecOwnershipTransferred)
2124 /// ParseForeach - Parse a for statement. Return the record corresponding
2125 /// to it. This returns true on error.
2127 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2128 /// Foreach ::= FOREACH Declaration IN Object
2130 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2131 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2132 Lex.Lex(); // Eat the 'for' token.
2134 // Make a temporary object to record items associated with the for
2136 ListInit *ListValue = nullptr;
2137 VarInit *IterName = ParseForeachDeclaration(ListValue);
2139 return TokError("expected declaration in for");
2141 if (Lex.getCode() != tgtok::In)
2142 return TokError("Unknown tok");
2143 Lex.Lex(); // Eat the in
2145 // Create a loop object and remember it.
2146 Loops.push_back(ForeachLoop(IterName, ListValue));
2148 if (Lex.getCode() != tgtok::l_brace) {
2149 // FOREACH Declaration IN Object
2150 if (ParseObject(CurMultiClass))
2154 SMLoc BraceLoc = Lex.getLoc();
2155 // Otherwise, this is a group foreach.
2156 Lex.Lex(); // eat the '{'.
2158 // Parse the object list.
2159 if (ParseObjectList(CurMultiClass))
2162 if (Lex.getCode() != tgtok::r_brace) {
2163 TokError("expected '}' at end of foreach command");
2164 return Error(BraceLoc, "to match this '{'");
2166 Lex.Lex(); // Eat the }
2169 // We've processed everything in this loop.
2175 /// ParseClass - Parse a tblgen class definition.
2177 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2179 bool TGParser::ParseClass() {
2180 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2183 if (Lex.getCode() != tgtok::Id)
2184 return TokError("expected class name after 'class' keyword");
2186 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2188 // If the body was previously defined, this is an error.
2189 if (CurRec->getValues().size() > 1 || // Account for NAME.
2190 !CurRec->getSuperClasses().empty() ||
2191 !CurRec->getTemplateArgs().empty())
2192 return TokError("Class '" + CurRec->getNameInitAsString()
2193 + "' already defined");
2195 // If this is the first reference to this class, create and add it.
2196 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
2197 Records.addClass(CurRec);
2199 Lex.Lex(); // eat the name.
2201 // If there are template args, parse them.
2202 if (Lex.getCode() == tgtok::less)
2203 if (ParseTemplateArgList(CurRec))
2206 // Finally, parse the object body.
2207 return ParseObjectBody(CurRec);
2210 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2213 /// LetList ::= LetItem (',' LetItem)*
2214 /// LetItem ::= ID OptionalRangeList '=' Value
2216 std::vector<LetRecord> TGParser::ParseLetList() {
2217 std::vector<LetRecord> Result;
2220 if (Lex.getCode() != tgtok::Id) {
2221 TokError("expected identifier in let definition");
2222 return std::vector<LetRecord>();
2224 std::string Name = Lex.getCurStrVal();
2225 SMLoc NameLoc = Lex.getLoc();
2226 Lex.Lex(); // Eat the identifier.
2228 // Check for an optional RangeList.
2229 std::vector<unsigned> Bits;
2230 if (ParseOptionalRangeList(Bits))
2231 return std::vector<LetRecord>();
2232 std::reverse(Bits.begin(), Bits.end());
2234 if (Lex.getCode() != tgtok::equal) {
2235 TokError("expected '=' in let expression");
2236 return std::vector<LetRecord>();
2238 Lex.Lex(); // eat the '='.
2240 Init *Val = ParseValue(nullptr);
2241 if (!Val) return std::vector<LetRecord>();
2243 // Now that we have everything, add the record.
2244 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
2246 if (Lex.getCode() != tgtok::comma)
2248 Lex.Lex(); // eat the comma.
2252 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2253 /// different related productions. This works inside multiclasses too.
2255 /// Object ::= LET LetList IN '{' ObjectList '}'
2256 /// Object ::= LET LetList IN Object
2258 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2259 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2262 // Add this entry to the let stack.
2263 std::vector<LetRecord> LetInfo = ParseLetList();
2264 if (LetInfo.empty()) return true;
2265 LetStack.push_back(std::move(LetInfo));
2267 if (Lex.getCode() != tgtok::In)
2268 return TokError("expected 'in' at end of top-level 'let'");
2271 // If this is a scalar let, just handle it now
2272 if (Lex.getCode() != tgtok::l_brace) {
2273 // LET LetList IN Object
2274 if (ParseObject(CurMultiClass))
2276 } else { // Object ::= LETCommand '{' ObjectList '}'
2277 SMLoc BraceLoc = Lex.getLoc();
2278 // Otherwise, this is a group let.
2279 Lex.Lex(); // eat the '{'.
2281 // Parse the object list.
2282 if (ParseObjectList(CurMultiClass))
2285 if (Lex.getCode() != tgtok::r_brace) {
2286 TokError("expected '}' at end of top level let command");
2287 return Error(BraceLoc, "to match this '{'");
2292 // Outside this let scope, this let block is not active.
2293 LetStack.pop_back();
2297 /// ParseMultiClass - Parse a multiclass definition.
2299 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2300 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
2301 /// MultiClassObject ::= DefInst
2302 /// MultiClassObject ::= MultiClassInst
2303 /// MultiClassObject ::= DefMInst
2304 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
2305 /// MultiClassObject ::= LETCommand Object
2307 bool TGParser::ParseMultiClass() {
2308 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2309 Lex.Lex(); // Eat the multiclass token.
2311 if (Lex.getCode() != tgtok::Id)
2312 return TokError("expected identifier after multiclass for name");
2313 std::string Name = Lex.getCurStrVal();
2315 if (MultiClasses.count(Name))
2316 return TokError("multiclass '" + Name + "' already defined");
2318 CurMultiClass = MultiClasses[Name] = new MultiClass(Name,
2319 Lex.getLoc(), Records);
2320 Lex.Lex(); // Eat the identifier.
2322 // If there are template args, parse them.
2323 if (Lex.getCode() == tgtok::less)
2324 if (ParseTemplateArgList(nullptr))
2327 bool inherits = false;
2329 // If there are submulticlasses, parse them.
2330 if (Lex.getCode() == tgtok::colon) {
2335 // Read all of the submulticlasses.
2336 SubMultiClassReference SubMultiClass =
2337 ParseSubMultiClassReference(CurMultiClass);
2340 if (!SubMultiClass.MC) return true;
2343 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2346 if (Lex.getCode() != tgtok::comma) break;
2347 Lex.Lex(); // eat ','.
2348 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2352 if (Lex.getCode() != tgtok::l_brace) {
2354 return TokError("expected '{' in multiclass definition");
2355 else if (Lex.getCode() != tgtok::semi)
2356 return TokError("expected ';' in multiclass definition");
2358 Lex.Lex(); // eat the ';'.
2360 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2361 return TokError("multiclass must contain at least one def");
2363 while (Lex.getCode() != tgtok::r_brace) {
2364 switch (Lex.getCode()) {
2366 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2370 case tgtok::Foreach:
2371 if (ParseObject(CurMultiClass))
2376 Lex.Lex(); // eat the '}'.
2379 CurMultiClass = nullptr;
2384 InstantiateMulticlassDef(MultiClass &MC,
2387 SMRange DefmPrefixRange) {
2388 // We need to preserve DefProto so it can be reused for later
2389 // instantiations, so create a new Record to inherit from it.
2391 // Add in the defm name. If the defm prefix is empty, give each
2392 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2393 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2396 bool IsAnonymous = false;
2398 DefmPrefix = StringInit::get(GetNewAnonymousName());
2402 Init *DefName = DefProto->getNameInit();
2404 StringInit *DefNameString = dyn_cast<StringInit>(DefName);
2406 if (DefNameString) {
2407 // We have a fully expanded string so there are no operators to
2408 // resolve. We should concatenate the given prefix and name.
2410 BinOpInit::get(BinOpInit::STRCONCAT,
2411 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2412 StringRecTy::get())->Fold(DefProto, &MC),
2413 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2416 // Make a trail of SMLocs from the multiclass instantiations.
2417 SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
2418 Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2419 Record *CurRec = new Record(DefName, Locs, Records, IsAnonymous);
2421 SubClassReference Ref;
2422 Ref.RefRange = DefmPrefixRange;
2424 AddSubClass(CurRec, Ref);
2426 // Set the value for NAME. We don't resolve references to it 'til later,
2427 // though, so that uses in nested multiclass names don't get
2429 if (SetValue(CurRec, Ref.RefRange.Start, "NAME", std::vector<unsigned>(),
2431 Error(DefmPrefixRange.Start, "Could not resolve "
2432 + CurRec->getNameInitAsString() + ":NAME to '"
2433 + DefmPrefix->getAsUnquotedString() + "'");
2438 // If the DefNameString didn't resolve, we probably have a reference to
2439 // NAME and need to replace it. We need to do at least this much greedily,
2440 // otherwise nested multiclasses will end up with incorrect NAME expansions.
2441 if (!DefNameString) {
2442 RecordVal *DefNameRV = CurRec->getValue("NAME");
2443 CurRec->resolveReferencesTo(DefNameRV);
2446 if (!CurMultiClass) {
2447 // Now that we're at the top level, resolve all NAME references
2448 // in the resultant defs that weren't in the def names themselves.
2449 RecordVal *DefNameRV = CurRec->getValue("NAME");
2450 CurRec->resolveReferencesTo(DefNameRV);
2452 // Now that NAME references are resolved and we're at the top level of
2453 // any multiclass expansions, add the record to the RecordKeeper. If we are
2454 // currently in a multiclass, it means this defm appears inside a
2455 // multiclass and its name won't be fully resolvable until we see
2456 // the top-level defm. Therefore, we don't add this to the
2457 // RecordKeeper at this point. If we did we could get duplicate
2458 // defs as more than one probably refers to NAME or some other
2459 // common internal placeholder.
2461 // Ensure redefinition doesn't happen.
2462 if (Records.getDef(CurRec->getNameInitAsString())) {
2463 Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
2464 "' already defined, instantiating defm with subdef '" +
2465 DefProto->getNameInitAsString() + "'");
2470 Records.addDef(CurRec);
2476 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2478 SMLoc DefmPrefixLoc,
2480 const std::vector<Init *> &TArgs,
2481 std::vector<Init *> &TemplateVals,
2483 // Loop over all of the template arguments, setting them to the specified
2484 // value or leaving them as the default if necessary.
2485 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2486 // Check if a value is specified for this temp-arg.
2487 if (i < TemplateVals.size()) {
2489 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2494 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2498 CurRec->removeValue(TArgs[i]);
2500 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2501 return Error(SubClassLoc, "value not specified for template argument #"+
2502 utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2503 + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2510 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2513 SMLoc DefmPrefixLoc) {
2514 // If the mdef is inside a 'let' expression, add to each def.
2515 if (ApplyLetStack(CurRec))
2516 return Error(DefmPrefixLoc, "when instantiating this defm");
2518 // Don't create a top level definition for defm inside multiclasses,
2519 // instead, only update the prototypes and bind the template args
2520 // with the new created definition.
2523 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2525 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2526 == CurRec->getNameInit())
2527 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2528 "' already defined in this multiclass!");
2529 CurMultiClass->DefPrototypes.push_back(CurRec);
2531 // Copy the template arguments for the multiclass into the new def.
2532 const std::vector<Init *> &TA =
2533 CurMultiClass->Rec.getTemplateArgs();
2535 for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2536 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2537 assert(RV && "Template arg doesn't exist?");
2538 CurRec->addValue(*RV);
2544 /// ParseDefm - Parse the instantiation of a multiclass.
2546 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2548 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2549 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2550 SMLoc DefmLoc = Lex.getLoc();
2551 Init *DefmPrefix = nullptr;
2553 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2554 DefmPrefix = ParseObjectName(CurMultiClass);
2557 SMLoc DefmPrefixEndLoc = Lex.getLoc();
2558 if (Lex.getCode() != tgtok::colon)
2559 return TokError("expected ':' after defm identifier");
2561 // Keep track of the new generated record definitions.
2562 std::vector<Record*> NewRecDefs;
2564 // This record also inherits from a regular class (non-multiclass)?
2565 bool InheritFromClass = false;
2570 SMLoc SubClassLoc = Lex.getLoc();
2571 SubClassReference Ref = ParseSubClassReference(nullptr, true);
2574 if (!Ref.Rec) return true;
2576 // To instantiate a multiclass, we need to first get the multiclass, then
2577 // instantiate each def contained in the multiclass with the SubClassRef
2578 // template parameters.
2579 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
2580 assert(MC && "Didn't lookup multiclass correctly?");
2581 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2583 // Verify that the correct number of template arguments were specified.
2584 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2585 if (TArgs.size() < TemplateVals.size())
2586 return Error(SubClassLoc,
2587 "more template args specified than multiclass expects");
2589 // Loop over all the def's in the multiclass, instantiating each one.
2590 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2591 Record *DefProto = MC->DefPrototypes[i];
2593 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix,
2599 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
2600 TArgs, TemplateVals, true/*Delete args*/))
2601 return Error(SubClassLoc, "could not instantiate def");
2603 if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmLoc))
2604 return Error(SubClassLoc, "could not instantiate def");
2606 // Defs that can be used by other definitions should be fully resolved
2608 if (DefProto->isResolveFirst() && !CurMultiClass) {
2609 CurRec->resolveReferences();
2610 CurRec->setResolveFirst(false);
2612 NewRecDefs.push_back(CurRec);
2616 if (Lex.getCode() != tgtok::comma) break;
2617 Lex.Lex(); // eat ','.
2619 if (Lex.getCode() != tgtok::Id)
2620 return TokError("expected identifier");
2622 SubClassLoc = Lex.getLoc();
2624 // A defm can inherit from regular classes (non-multiclass) as
2625 // long as they come in the end of the inheritance list.
2626 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
2628 if (InheritFromClass)
2631 Ref = ParseSubClassReference(nullptr, true);
2634 if (InheritFromClass) {
2635 // Process all the classes to inherit as if they were part of a
2636 // regular 'def' and inherit all record values.
2637 SubClassReference SubClass = ParseSubClassReference(nullptr, false);
2640 if (!SubClass.Rec) return true;
2642 // Get the expanded definition prototypes and teach them about
2643 // the record values the current class to inherit has
2644 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2645 Record *CurRec = NewRecDefs[i];
2648 if (AddSubClass(CurRec, SubClass))
2651 if (ApplyLetStack(CurRec))
2655 if (Lex.getCode() != tgtok::comma) break;
2656 Lex.Lex(); // eat ','.
2657 SubClass = ParseSubClassReference(nullptr, false);
2662 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2663 // See Record::setName(). This resolve step will see any new
2664 // name for the def that might have been created when resolving
2665 // inheritance, values and arguments above.
2666 NewRecDefs[i]->resolveReferences();
2668 if (Lex.getCode() != tgtok::semi)
2669 return TokError("expected ';' at end of defm");
2676 /// Object ::= ClassInst
2677 /// Object ::= DefInst
2678 /// Object ::= MultiClassInst
2679 /// Object ::= DefMInst
2680 /// Object ::= LETCommand '{' ObjectList '}'
2681 /// Object ::= LETCommand Object
2682 bool TGParser::ParseObject(MultiClass *MC) {
2683 switch (Lex.getCode()) {
2685 return TokError("Expected class, def, defm, multiclass or let definition");
2686 case tgtok::Let: return ParseTopLevelLet(MC);
2687 case tgtok::Def: return ParseDef(MC);
2688 case tgtok::Foreach: return ParseForeach(MC);
2689 case tgtok::Defm: return ParseDefm(MC);
2690 case tgtok::Class: return ParseClass();
2691 case tgtok::MultiClass: return ParseMultiClass();
2696 /// ObjectList :== Object*
2697 bool TGParser::ParseObjectList(MultiClass *MC) {
2698 while (isObjectStart(Lex.getCode())) {
2699 if (ParseObject(MC))
2705 bool TGParser::ParseFile() {
2706 Lex.Lex(); // Prime the lexer.
2707 if (ParseObjectList()) return true;
2709 // If we have unread input at the end of the file, report it.
2710 if (Lex.getCode() == tgtok::Eof)
2713 return TokError("Unexpected input at top level");