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/TableGen/Record.h"
16 #include "llvm/ADT/StringExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/Support/CommandLine.h"
23 //===----------------------------------------------------------------------===//
24 // Support Code for the Semantic Actions.
25 //===----------------------------------------------------------------------===//
28 struct SubClassReference {
31 std::vector<Init*> TemplateArgs;
32 SubClassReference() : Rec(0) {}
34 bool isInvalid() const { return Rec == 0; }
37 struct SubMultiClassReference {
40 std::vector<Init*> TemplateArgs;
41 SubMultiClassReference() : MC(0) {}
43 bool isInvalid() const { return MC == 0; }
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.getName())) {
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 == 0) 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 = dynamic_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 = dynamic_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 V->convertInitializerTo(BitsRecTy::get(BitList.size()));
114 return Error(Loc, "Initializer is not compatible with bit range");
117 // We should have a BitsInit type now.
118 BitsInit *BInit = dynamic_cast<BitsInit*>(BI);
121 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
123 // Loop over bits, assigning values as appropriate.
124 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
125 unsigned Bit = BitList[i];
127 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
128 ValName->getAsUnquotedString() + "' more than once");
129 NewBits[Bit] = BInit->getBit(i);
132 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
134 NewBits[i] = CurVal->getBit(i);
136 V = BitsInit::get(NewBits);
140 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + "' of type '"
141 + RV->getType()->getAsString() +
142 "' is incompatible with initializer '" + V->getAsString()
147 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
148 /// args as SubClass's template arguments.
149 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
150 Record *SC = SubClass.Rec;
151 // Add all of the values in the subclass into the current class.
152 const std::vector<RecordVal> &Vals = SC->getValues();
153 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
154 if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
157 const std::vector<Init *> &TArgs = SC->getTemplateArgs();
159 // Ensure that an appropriate number of template arguments are specified.
160 if (TArgs.size() < SubClass.TemplateArgs.size())
161 return Error(SubClass.RefLoc, "More template args specified than expected");
163 // Loop over all of the template arguments, setting them to the specified
164 // value or leaving them as the default if necessary.
165 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
166 if (i < SubClass.TemplateArgs.size()) {
167 // If a value is specified for this template arg, set it now.
168 if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(),
169 SubClass.TemplateArgs[i]))
173 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
176 CurRec->removeValue(TArgs[i]);
178 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
179 return Error(SubClass.RefLoc,"Value not specified for template argument #"
180 + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
181 + ") of subclass '" + SC->getNameInitAsString() + "'!");
185 // Since everything went well, we can now set the "superclass" list for the
187 const std::vector<Record*> &SCs = SC->getSuperClasses();
188 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
189 if (CurRec->isSubClassOf(SCs[i]))
190 return Error(SubClass.RefLoc,
191 "Already subclass of '" + SCs[i]->getName() + "'!\n");
192 CurRec->addSuperClass(SCs[i]);
195 if (CurRec->isSubClassOf(SC))
196 return Error(SubClass.RefLoc,
197 "Already subclass of '" + SC->getName() + "'!\n");
198 CurRec->addSuperClass(SC);
202 /// AddSubMultiClass - Add SubMultiClass as a subclass to
203 /// CurMC, resolving its template args as SubMultiClass's
204 /// template arguments.
205 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
206 SubMultiClassReference &SubMultiClass) {
207 MultiClass *SMC = SubMultiClass.MC;
208 Record *CurRec = &CurMC->Rec;
210 const std::vector<RecordVal> &MCVals = CurRec->getValues();
212 // Add all of the values in the subclass into the current class.
213 const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
214 for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
215 if (AddValue(CurRec, SubMultiClass.RefLoc, SMCVals[i]))
218 int newDefStart = CurMC->DefPrototypes.size();
220 // Add all of the defs in the subclass into the current multiclass.
221 for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
222 iend = SMC->DefPrototypes.end();
225 // Clone the def and add it to the current multiclass
226 Record *NewDef = new Record(**i);
228 // Add all of the values in the superclass into the current def.
229 for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
230 if (AddValue(NewDef, SubMultiClass.RefLoc, MCVals[i]))
233 CurMC->DefPrototypes.push_back(NewDef);
236 const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
238 // Ensure that an appropriate number of template arguments are
240 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
241 return Error(SubMultiClass.RefLoc,
242 "More template args specified than expected");
244 // Loop over all of the template arguments, setting them to the specified
245 // value or leaving them as the default if necessary.
246 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
247 if (i < SubMultiClass.TemplateArgs.size()) {
248 // If a value is specified for this template arg, set it in the
250 if (SetValue(CurRec, SubMultiClass.RefLoc, SMCTArgs[i],
251 std::vector<unsigned>(),
252 SubMultiClass.TemplateArgs[i]))
256 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
259 CurRec->removeValue(SMCTArgs[i]);
261 // If a value is specified for this template arg, set it in the
263 for (MultiClass::RecordVector::iterator j =
264 CurMC->DefPrototypes.begin() + newDefStart,
265 jend = CurMC->DefPrototypes.end();
270 if (SetValue(Def, SubMultiClass.RefLoc, SMCTArgs[i],
271 std::vector<unsigned>(),
272 SubMultiClass.TemplateArgs[i]))
276 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
279 Def->removeValue(SMCTArgs[i]);
281 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
282 return Error(SubMultiClass.RefLoc,
283 "Value not specified for template argument #"
284 + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
285 + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
292 //===----------------------------------------------------------------------===//
294 //===----------------------------------------------------------------------===//
296 /// isObjectStart - Return true if this is a valid first token for an Object.
297 static bool isObjectStart(tgtok::TokKind K) {
298 return K == tgtok::Class || K == tgtok::Def ||
299 K == tgtok::Defm || K == tgtok::Let || K == tgtok::MultiClass;
302 static std::string GetNewAnonymousName() {
303 static unsigned AnonCounter = 0;
304 return "anonymous."+utostr(AnonCounter++);
307 /// ParseObjectName - If an object name is specified, return it. Otherwise,
308 /// return an anonymous name.
309 /// ObjectName ::= ID
310 /// ObjectName ::= /*empty*/
312 std::string TGParser::ParseObjectName() {
313 if (Lex.getCode() != tgtok::Id)
314 return GetNewAnonymousName();
316 std::string Ret = Lex.getCurStrVal();
322 /// ParseClassID - Parse and resolve a reference to a class name. This returns
327 Record *TGParser::ParseClassID() {
328 if (Lex.getCode() != tgtok::Id) {
329 TokError("expected name for ClassID");
333 Record *Result = Records.getClass(Lex.getCurStrVal());
335 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
341 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
342 /// This returns null on error.
344 /// MultiClassID ::= ID
346 MultiClass *TGParser::ParseMultiClassID() {
347 if (Lex.getCode() != tgtok::Id) {
348 TokError("expected name for ClassID");
352 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
354 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
360 Record *TGParser::ParseDefmID() {
361 if (Lex.getCode() != tgtok::Id) {
362 TokError("expected multiclass name");
366 MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
368 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
377 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
378 /// subclass. This returns a SubClassRefTy with a null Record* on error.
380 /// SubClassRef ::= ClassID
381 /// SubClassRef ::= ClassID '<' ValueList '>'
383 SubClassReference TGParser::
384 ParseSubClassReference(Record *CurRec, bool isDefm) {
385 SubClassReference Result;
386 Result.RefLoc = Lex.getLoc();
389 Result.Rec = ParseDefmID();
391 Result.Rec = ParseClassID();
392 if (Result.Rec == 0) return Result;
394 // If there is no template arg list, we're done.
395 if (Lex.getCode() != tgtok::less)
397 Lex.Lex(); // Eat the '<'
399 if (Lex.getCode() == tgtok::greater) {
400 TokError("subclass reference requires a non-empty list of template values");
405 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
406 if (Result.TemplateArgs.empty()) {
407 Result.Rec = 0; // Error parsing value list.
411 if (Lex.getCode() != tgtok::greater) {
412 TokError("expected '>' in template value list");
421 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
422 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
423 /// Record* on error.
425 /// SubMultiClassRef ::= MultiClassID
426 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
428 SubMultiClassReference TGParser::
429 ParseSubMultiClassReference(MultiClass *CurMC) {
430 SubMultiClassReference Result;
431 Result.RefLoc = Lex.getLoc();
433 Result.MC = ParseMultiClassID();
434 if (Result.MC == 0) return Result;
436 // If there is no template arg list, we're done.
437 if (Lex.getCode() != tgtok::less)
439 Lex.Lex(); // Eat the '<'
441 if (Lex.getCode() == tgtok::greater) {
442 TokError("subclass reference requires a non-empty list of template values");
447 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
448 if (Result.TemplateArgs.empty()) {
449 Result.MC = 0; // Error parsing value list.
453 if (Lex.getCode() != tgtok::greater) {
454 TokError("expected '>' in template value list");
463 /// ParseRangePiece - Parse a bit/value range.
464 /// RangePiece ::= INTVAL
465 /// RangePiece ::= INTVAL '-' INTVAL
466 /// RangePiece ::= INTVAL INTVAL
467 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
468 if (Lex.getCode() != tgtok::IntVal) {
469 TokError("expected integer or bitrange");
472 int64_t Start = Lex.getCurIntVal();
476 return TokError("invalid range, cannot be negative");
478 switch (Lex.Lex()) { // eat first character.
480 Ranges.push_back(Start);
483 if (Lex.Lex() != tgtok::IntVal) {
484 TokError("expected integer value as end of range");
487 End = Lex.getCurIntVal();
490 End = -Lex.getCurIntVal();
494 return TokError("invalid range, cannot be negative");
499 for (; Start <= End; ++Start)
500 Ranges.push_back(Start);
502 for (; Start >= End; --Start)
503 Ranges.push_back(Start);
508 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
510 /// RangeList ::= RangePiece (',' RangePiece)*
512 std::vector<unsigned> TGParser::ParseRangeList() {
513 std::vector<unsigned> Result;
515 // Parse the first piece.
516 if (ParseRangePiece(Result))
517 return std::vector<unsigned>();
518 while (Lex.getCode() == tgtok::comma) {
519 Lex.Lex(); // Eat the comma.
521 // Parse the next range piece.
522 if (ParseRangePiece(Result))
523 return std::vector<unsigned>();
528 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
529 /// OptionalRangeList ::= '<' RangeList '>'
530 /// OptionalRangeList ::= /*empty*/
531 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
532 if (Lex.getCode() != tgtok::less)
535 SMLoc StartLoc = Lex.getLoc();
536 Lex.Lex(); // eat the '<'
538 // Parse the range list.
539 Ranges = ParseRangeList();
540 if (Ranges.empty()) return true;
542 if (Lex.getCode() != tgtok::greater) {
543 TokError("expected '>' at end of range list");
544 return Error(StartLoc, "to match this '<'");
546 Lex.Lex(); // eat the '>'.
550 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
551 /// OptionalBitList ::= '{' RangeList '}'
552 /// OptionalBitList ::= /*empty*/
553 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
554 if (Lex.getCode() != tgtok::l_brace)
557 SMLoc StartLoc = Lex.getLoc();
558 Lex.Lex(); // eat the '{'
560 // Parse the range list.
561 Ranges = ParseRangeList();
562 if (Ranges.empty()) return true;
564 if (Lex.getCode() != tgtok::r_brace) {
565 TokError("expected '}' at end of bit list");
566 return Error(StartLoc, "to match this '{'");
568 Lex.Lex(); // eat the '}'.
573 /// ParseType - Parse and return a tblgen type. This returns null on error.
575 /// Type ::= STRING // string type
576 /// Type ::= BIT // bit type
577 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
578 /// Type ::= INT // int type
579 /// Type ::= LIST '<' Type '>' // list<x> type
580 /// Type ::= CODE // code type
581 /// Type ::= DAG // dag type
582 /// Type ::= ClassID // Record Type
584 RecTy *TGParser::ParseType() {
585 switch (Lex.getCode()) {
586 default: TokError("Unknown token when expecting a type"); return 0;
587 case tgtok::String: Lex.Lex(); return StringRecTy::get();
588 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
589 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
590 case tgtok::Code: Lex.Lex(); return CodeRecTy::get();
591 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
593 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
596 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
597 TokError("expected '<' after bits type");
600 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
601 TokError("expected integer in bits<n> type");
604 uint64_t Val = Lex.getCurIntVal();
605 if (Lex.Lex() != tgtok::greater) { // Eat count.
606 TokError("expected '>' at end of bits<n> type");
609 Lex.Lex(); // Eat '>'
610 return BitsRecTy::get(Val);
613 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
614 TokError("expected '<' after list type");
617 Lex.Lex(); // Eat '<'
618 RecTy *SubType = ParseType();
619 if (SubType == 0) return 0;
621 if (Lex.getCode() != tgtok::greater) {
622 TokError("expected '>' at end of list<ty> type");
625 Lex.Lex(); // Eat '>'
626 return ListRecTy::get(SubType);
631 /// ParseIDValue - Parse an ID as a value and decode what it means.
633 /// IDValue ::= ID [def local value]
634 /// IDValue ::= ID [def template arg]
635 /// IDValue ::= ID [multiclass local value]
636 /// IDValue ::= ID [multiclass template argument]
637 /// IDValue ::= ID [def name]
639 Init *TGParser::ParseIDValue(Record *CurRec, IDParseMode Mode) {
640 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
641 std::string Name = Lex.getCurStrVal();
642 SMLoc Loc = Lex.getLoc();
644 return ParseIDValue(CurRec, Name, Loc);
647 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
648 /// has already been read.
649 Init *TGParser::ParseIDValue(Record *CurRec,
650 const std::string &Name, SMLoc NameLoc,
653 if (const RecordVal *RV = CurRec->getValue(Name))
654 return VarInit::get(Name, RV->getType());
656 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
659 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
662 if (CurRec->isTemplateArg(TemplateArgName)) {
663 const RecordVal *RV = CurRec->getValue(TemplateArgName);
664 assert(RV && "Template arg doesn't exist??");
665 return VarInit::get(TemplateArgName, RV->getType());
670 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
673 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
674 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
675 assert(RV && "Template arg doesn't exist??");
676 return VarInit::get(MCName, RV->getType());
680 if (Record *D = Records.getDef(Name))
681 return DefInit::get(D);
683 Error(NameLoc, "Variable not defined: '" + Name + "'");
687 /// ParseOperation - Parse an operator. This returns null on error.
689 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
691 Init *TGParser::ParseOperation(Record *CurRec) {
692 switch (Lex.getCode()) {
694 TokError("unknown operation");
700 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
701 UnOpInit::UnaryOp Code;
704 switch (Lex.getCode()) {
705 default: assert(0 && "Unhandled code!");
707 Lex.Lex(); // eat the operation
708 Code = UnOpInit::CAST;
710 Type = ParseOperatorType();
713 TokError("did not get type for unary operator");
719 Lex.Lex(); // eat the operation
720 Code = UnOpInit::HEAD;
723 Lex.Lex(); // eat the operation
724 Code = UnOpInit::TAIL;
727 Lex.Lex(); // eat the operation
728 Code = UnOpInit::EMPTY;
729 Type = IntRecTy::get();
732 if (Lex.getCode() != tgtok::l_paren) {
733 TokError("expected '(' after unary operator");
736 Lex.Lex(); // eat the '('
738 Init *LHS = ParseValue(CurRec);
739 if (LHS == 0) return 0;
741 if (Code == UnOpInit::HEAD
742 || Code == UnOpInit::TAIL
743 || Code == UnOpInit::EMPTY) {
744 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
745 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
746 TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
747 if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
748 TokError("expected list or string type argument in unary operator");
752 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
753 StringRecTy *SType = dynamic_cast<StringRecTy*>(LHSt->getType());
754 if (LType == 0 && SType == 0) {
755 TokError("expected list or string type argumnet in unary operator");
760 if (Code == UnOpInit::HEAD
761 || Code == UnOpInit::TAIL) {
762 if (LHSl == 0 && LHSt == 0) {
763 TokError("expected list type argumnet in unary operator");
767 if (LHSl && LHSl->getSize() == 0) {
768 TokError("empty list argument in unary operator");
772 Init *Item = LHSl->getElement(0);
773 TypedInit *Itemt = dynamic_cast<TypedInit*>(Item);
775 TokError("untyped list element in unary operator");
778 if (Code == UnOpInit::HEAD) {
779 Type = Itemt->getType();
781 Type = ListRecTy::get(Itemt->getType());
784 assert(LHSt && "expected list type argument in unary operator");
785 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
787 TokError("expected list type argumnet in unary operator");
790 if (Code == UnOpInit::HEAD) {
791 Type = LType->getElementType();
799 if (Lex.getCode() != tgtok::r_paren) {
800 TokError("expected ')' in unary operator");
803 Lex.Lex(); // eat the ')'
804 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
812 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
813 tgtok::TokKind OpTok = Lex.getCode();
814 SMLoc OpLoc = Lex.getLoc();
815 Lex.Lex(); // eat the operation
817 BinOpInit::BinaryOp Code;
821 default: assert(0 && "Unhandled code!");
822 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
823 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
824 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
825 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
826 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
827 case tgtok::XStrConcat:
828 Code = BinOpInit::STRCONCAT;
829 Type = StringRecTy::get();
833 if (Lex.getCode() != tgtok::l_paren) {
834 TokError("expected '(' after binary operator");
837 Lex.Lex(); // eat the '('
839 SmallVector<Init*, 2> InitList;
841 InitList.push_back(ParseValue(CurRec));
842 if (InitList.back() == 0) return 0;
844 while (Lex.getCode() == tgtok::comma) {
845 Lex.Lex(); // eat the ','
847 InitList.push_back(ParseValue(CurRec));
848 if (InitList.back() == 0) return 0;
851 if (Lex.getCode() != tgtok::r_paren) {
852 TokError("expected ')' in operator");
855 Lex.Lex(); // eat the ')'
857 // We allow multiple operands to associative operators like !strconcat as
858 // shorthand for nesting them.
859 if (Code == BinOpInit::STRCONCAT) {
860 while (InitList.size() > 2) {
861 Init *RHS = InitList.pop_back_val();
862 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
863 ->Fold(CurRec, CurMultiClass);
864 InitList.back() = RHS;
868 if (InitList.size() == 2)
869 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
870 ->Fold(CurRec, CurMultiClass);
872 Error(OpLoc, "expected two operands to operator");
877 case tgtok::XForEach:
878 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
879 TernOpInit::TernaryOp Code;
882 tgtok::TokKind LexCode = Lex.getCode();
883 Lex.Lex(); // eat the operation
885 default: assert(0 && "Unhandled code!");
887 Code = TernOpInit::IF;
889 case tgtok::XForEach:
890 Code = TernOpInit::FOREACH;
893 Code = TernOpInit::SUBST;
896 if (Lex.getCode() != tgtok::l_paren) {
897 TokError("expected '(' after ternary operator");
900 Lex.Lex(); // eat the '('
902 Init *LHS = ParseValue(CurRec);
903 if (LHS == 0) return 0;
905 if (Lex.getCode() != tgtok::comma) {
906 TokError("expected ',' in ternary operator");
909 Lex.Lex(); // eat the ','
911 Init *MHS = ParseValue(CurRec);
912 if (MHS == 0) return 0;
914 if (Lex.getCode() != tgtok::comma) {
915 TokError("expected ',' in ternary operator");
918 Lex.Lex(); // eat the ','
920 Init *RHS = ParseValue(CurRec);
921 if (RHS == 0) return 0;
923 if (Lex.getCode() != tgtok::r_paren) {
924 TokError("expected ')' in binary operator");
927 Lex.Lex(); // eat the ')'
930 default: assert(0 && "Unhandled code!");
932 // FIXME: The `!if' operator doesn't handle non-TypedInit well at
933 // all. This can be made much more robust.
934 TypedInit *MHSt = dynamic_cast<TypedInit*>(MHS);
935 TypedInit *RHSt = dynamic_cast<TypedInit*>(RHS);
940 if (MHSt == 0 && RHSt == 0) {
941 BitsInit *MHSbits = dynamic_cast<BitsInit*>(MHS);
942 BitsInit *RHSbits = dynamic_cast<BitsInit*>(RHS);
944 if (MHSbits && RHSbits &&
945 MHSbits->getNumBits() == RHSbits->getNumBits()) {
946 Type = BitRecTy::get();
949 BitInit *MHSbit = dynamic_cast<BitInit*>(MHS);
950 BitInit *RHSbit = dynamic_cast<BitInit*>(RHS);
952 if (MHSbit && RHSbit) {
953 Type = BitRecTy::get();
957 } else if (MHSt != 0 && RHSt != 0) {
958 MHSTy = MHSt->getType();
959 RHSTy = RHSt->getType();
962 if (!MHSTy || !RHSTy) {
963 TokError("could not get type for !if");
967 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
969 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
972 TokError("inconsistent types for !if");
977 case tgtok::XForEach: {
978 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
980 TokError("could not get type for !foreach");
983 Type = MHSt->getType();
986 case tgtok::XSubst: {
987 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
989 TokError("could not get type for !subst");
992 Type = RHSt->getType();
996 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1000 TokError("could not parse operation");
1004 /// ParseOperatorType - Parse a type for an operator. This returns
1007 /// OperatorType ::= '<' Type '>'
1009 RecTy *TGParser::ParseOperatorType() {
1012 if (Lex.getCode() != tgtok::less) {
1013 TokError("expected type name for operator");
1016 Lex.Lex(); // eat the <
1021 TokError("expected type name for operator");
1025 if (Lex.getCode() != tgtok::greater) {
1026 TokError("expected type name for operator");
1029 Lex.Lex(); // eat the >
1035 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1037 /// SimpleValue ::= IDValue
1038 /// SimpleValue ::= INTVAL
1039 /// SimpleValue ::= STRVAL+
1040 /// SimpleValue ::= CODEFRAGMENT
1041 /// SimpleValue ::= '?'
1042 /// SimpleValue ::= '{' ValueList '}'
1043 /// SimpleValue ::= ID '<' ValueListNE '>'
1044 /// SimpleValue ::= '[' ValueList ']'
1045 /// SimpleValue ::= '(' IDValue DagArgList ')'
1046 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1047 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1048 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1049 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1050 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1052 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1055 switch (Lex.getCode()) {
1056 default: TokError("Unknown token when parsing a value"); break;
1057 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1058 case tgtok::StrVal: {
1059 std::string Val = Lex.getCurStrVal();
1062 // Handle multiple consecutive concatenated strings.
1063 while (Lex.getCode() == tgtok::StrVal) {
1064 Val += Lex.getCurStrVal();
1068 R = StringInit::get(Val);
1071 case tgtok::CodeFragment:
1072 R = CodeInit::get(Lex.getCurStrVal());
1075 case tgtok::question:
1076 R = UnsetInit::get();
1080 SMLoc NameLoc = Lex.getLoc();
1081 std::string Name = Lex.getCurStrVal();
1082 if (Lex.Lex() != tgtok::less) // consume the Id.
1083 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1085 // Value ::= ID '<' ValueListNE '>'
1086 if (Lex.Lex() == tgtok::greater) {
1087 TokError("expected non-empty value list");
1091 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1092 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1094 Record *Class = Records.getClass(Name);
1096 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1100 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1101 if (ValueList.empty()) return 0;
1103 if (Lex.getCode() != tgtok::greater) {
1104 TokError("expected '>' at end of value list");
1107 Lex.Lex(); // eat the '>'
1109 // Create the new record, set it as CurRec temporarily.
1110 static unsigned AnonCounter = 0;
1111 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),
1114 SubClassReference SCRef;
1115 SCRef.RefLoc = NameLoc;
1117 SCRef.TemplateArgs = ValueList;
1118 // Add info about the subclass to NewRec.
1119 if (AddSubClass(NewRec, SCRef))
1121 NewRec->resolveReferences();
1122 Records.addDef(NewRec);
1124 // The result of the expression is a reference to the new record.
1125 return DefInit::get(NewRec);
1127 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1128 SMLoc BraceLoc = Lex.getLoc();
1129 Lex.Lex(); // eat the '{'
1130 std::vector<Init*> Vals;
1132 if (Lex.getCode() != tgtok::r_brace) {
1133 Vals = ParseValueList(CurRec);
1134 if (Vals.empty()) return 0;
1136 if (Lex.getCode() != tgtok::r_brace) {
1137 TokError("expected '}' at end of bit list value");
1140 Lex.Lex(); // eat the '}'
1142 SmallVector<Init *, 16> NewBits(Vals.size());
1144 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1145 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1147 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1148 ") is not convertable to a bit");
1151 NewBits[Vals.size()-i-1] = Bit;
1153 return BitsInit::get(NewBits);
1155 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1156 Lex.Lex(); // eat the '['
1157 std::vector<Init*> Vals;
1159 RecTy *DeducedEltTy = 0;
1160 ListRecTy *GivenListTy = 0;
1162 if (ItemType != 0) {
1163 ListRecTy *ListType = dynamic_cast<ListRecTy*>(ItemType);
1164 if (ListType == 0) {
1165 std::stringstream s;
1166 s << "Type mismatch for list, expected list type, got "
1167 << ItemType->getAsString();
1171 GivenListTy = ListType;
1174 if (Lex.getCode() != tgtok::r_square) {
1175 Vals = ParseValueList(CurRec, 0,
1176 GivenListTy ? GivenListTy->getElementType() : 0);
1177 if (Vals.empty()) return 0;
1179 if (Lex.getCode() != tgtok::r_square) {
1180 TokError("expected ']' at end of list value");
1183 Lex.Lex(); // eat the ']'
1185 RecTy *GivenEltTy = 0;
1186 if (Lex.getCode() == tgtok::less) {
1187 // Optional list element type
1188 Lex.Lex(); // eat the '<'
1190 GivenEltTy = ParseType();
1191 if (GivenEltTy == 0) {
1192 // Couldn't parse element type
1196 if (Lex.getCode() != tgtok::greater) {
1197 TokError("expected '>' at end of list element type");
1200 Lex.Lex(); // eat the '>'
1205 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1208 TypedInit *TArg = dynamic_cast<TypedInit*>(*i);
1210 TokError("Untyped list element");
1214 EltTy = resolveTypes(EltTy, TArg->getType());
1216 TokError("Incompatible types in list elements");
1220 EltTy = TArg->getType();
1224 if (GivenEltTy != 0) {
1226 // Verify consistency
1227 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1228 TokError("Incompatible types in list elements");
1236 if (ItemType == 0) {
1237 TokError("No type for list");
1240 DeducedEltTy = GivenListTy->getElementType();
1242 // Make sure the deduced type is compatible with the given type
1244 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1245 TokError("Element type mismatch for list");
1249 DeducedEltTy = EltTy;
1252 return ListInit::get(Vals, DeducedEltTy);
1254 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1255 Lex.Lex(); // eat the '('
1256 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1257 TokError("expected identifier in dag init");
1261 Init *Operator = ParseValue(CurRec);
1262 if (Operator == 0) return 0;
1264 // If the operator name is present, parse it.
1265 std::string OperatorName;
1266 if (Lex.getCode() == tgtok::colon) {
1267 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1268 TokError("expected variable name in dag operator");
1271 OperatorName = Lex.getCurStrVal();
1272 Lex.Lex(); // eat the VarName.
1275 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1276 if (Lex.getCode() != tgtok::r_paren) {
1277 DagArgs = ParseDagArgList(CurRec);
1278 if (DagArgs.empty()) return 0;
1281 if (Lex.getCode() != tgtok::r_paren) {
1282 TokError("expected ')' in dag init");
1285 Lex.Lex(); // eat the ')'
1287 return DagInit::get(Operator, OperatorName, DagArgs);
1293 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1294 case tgtok::XConcat:
1299 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1301 case tgtok::XForEach:
1302 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1303 return ParseOperation(CurRec);
1310 /// ParseValue - Parse a tblgen value. This returns null on error.
1312 /// Value ::= SimpleValue ValueSuffix*
1313 /// ValueSuffix ::= '{' BitList '}'
1314 /// ValueSuffix ::= '[' BitList ']'
1315 /// ValueSuffix ::= '.' ID
1317 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1318 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1319 if (Result == 0) return 0;
1321 // Parse the suffixes now if present.
1323 switch (Lex.getCode()) {
1324 default: return Result;
1325 case tgtok::l_brace: {
1326 SMLoc CurlyLoc = Lex.getLoc();
1327 Lex.Lex(); // eat the '{'
1328 std::vector<unsigned> Ranges = ParseRangeList();
1329 if (Ranges.empty()) return 0;
1331 // Reverse the bitlist.
1332 std::reverse(Ranges.begin(), Ranges.end());
1333 Result = Result->convertInitializerBitRange(Ranges);
1335 Error(CurlyLoc, "Invalid bit range for value");
1340 if (Lex.getCode() != tgtok::r_brace) {
1341 TokError("expected '}' at end of bit range list");
1347 case tgtok::l_square: {
1348 SMLoc SquareLoc = Lex.getLoc();
1349 Lex.Lex(); // eat the '['
1350 std::vector<unsigned> Ranges = ParseRangeList();
1351 if (Ranges.empty()) return 0;
1353 Result = Result->convertInitListSlice(Ranges);
1355 Error(SquareLoc, "Invalid range for list slice");
1360 if (Lex.getCode() != tgtok::r_square) {
1361 TokError("expected ']' at end of list slice");
1368 if (Lex.Lex() != tgtok::Id) { // eat the .
1369 TokError("expected field identifier after '.'");
1372 if (!Result->getFieldType(Lex.getCurStrVal())) {
1373 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1374 Result->getAsString() + "'");
1377 Result = FieldInit::get(Result, Lex.getCurStrVal());
1378 Lex.Lex(); // eat field name
1384 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1386 /// ParseDagArgList ::= Value (':' VARNAME)?
1387 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1388 std::vector<std::pair<llvm::Init*, std::string> >
1389 TGParser::ParseDagArgList(Record *CurRec) {
1390 std::vector<std::pair<llvm::Init*, std::string> > Result;
1393 Init *Val = ParseValue(CurRec);
1394 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1396 // If the variable name is present, add it.
1397 std::string VarName;
1398 if (Lex.getCode() == tgtok::colon) {
1399 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1400 TokError("expected variable name in dag literal");
1401 return std::vector<std::pair<llvm::Init*, std::string> >();
1403 VarName = Lex.getCurStrVal();
1404 Lex.Lex(); // eat the VarName.
1407 Result.push_back(std::make_pair(Val, VarName));
1409 if (Lex.getCode() != tgtok::comma) break;
1410 Lex.Lex(); // eat the ','
1417 /// ParseValueList - Parse a comma separated list of values, returning them as a
1418 /// vector. Note that this always expects to be able to parse at least one
1419 /// value. It returns an empty list if this is not possible.
1421 /// ValueList ::= Value (',' Value)
1423 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1425 std::vector<Init*> Result;
1426 RecTy *ItemType = EltTy;
1427 unsigned int ArgN = 0;
1428 if (ArgsRec != 0 && EltTy == 0) {
1429 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1430 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1432 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1435 assert(RV && "Template argument record not found??");
1436 ItemType = RV->getType();
1439 Result.push_back(ParseValue(CurRec, ItemType));
1440 if (Result.back() == 0) return std::vector<Init*>();
1442 while (Lex.getCode() == tgtok::comma) {
1443 Lex.Lex(); // Eat the comma
1445 if (ArgsRec != 0 && EltTy == 0) {
1446 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1447 if (ArgN >= TArgs.size()) {
1448 TokError("too many template arguments");
1449 return std::vector<Init*>();
1451 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1452 assert(RV && "Template argument record not found??");
1453 ItemType = RV->getType();
1456 Result.push_back(ParseValue(CurRec, ItemType));
1457 if (Result.back() == 0) return std::vector<Init*>();
1464 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1465 /// empty string on error. This can happen in a number of different context's,
1466 /// including within a def or in the template args for a def (which which case
1467 /// CurRec will be non-null) and within the template args for a multiclass (in
1468 /// which case CurRec will be null, but CurMultiClass will be set). This can
1469 /// also happen within a def that is within a multiclass, which will set both
1470 /// CurRec and CurMultiClass.
1472 /// Declaration ::= FIELD? Type ID ('=' Value)?
1474 Init *TGParser::ParseDeclaration(Record *CurRec,
1475 bool ParsingTemplateArgs) {
1476 // Read the field prefix if present.
1477 bool HasField = Lex.getCode() == tgtok::Field;
1478 if (HasField) Lex.Lex();
1480 RecTy *Type = ParseType();
1481 if (Type == 0) return 0;
1483 if (Lex.getCode() != tgtok::Id) {
1484 TokError("Expected identifier in declaration");
1488 SMLoc IdLoc = Lex.getLoc();
1489 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1492 if (ParsingTemplateArgs) {
1494 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1496 assert(CurMultiClass);
1499 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1504 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1507 // If a value is present, parse it.
1508 if (Lex.getCode() == tgtok::equal) {
1510 SMLoc ValLoc = Lex.getLoc();
1511 Init *Val = ParseValue(CurRec, Type);
1513 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1520 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1521 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1522 /// template args for a def, which may or may not be in a multiclass. If null,
1523 /// these are the template args for a multiclass.
1525 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1527 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1528 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1529 Lex.Lex(); // eat the '<'
1531 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1533 // Read the first declaration.
1534 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1538 TheRecToAddTo->addTemplateArg(TemplArg);
1540 while (Lex.getCode() == tgtok::comma) {
1541 Lex.Lex(); // eat the ','
1543 // Read the following declarations.
1544 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1547 TheRecToAddTo->addTemplateArg(TemplArg);
1550 if (Lex.getCode() != tgtok::greater)
1551 return TokError("expected '>' at end of template argument list");
1552 Lex.Lex(); // eat the '>'.
1557 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1559 /// BodyItem ::= Declaration ';'
1560 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1561 bool TGParser::ParseBodyItem(Record *CurRec) {
1562 if (Lex.getCode() != tgtok::Let) {
1563 if (ParseDeclaration(CurRec, false) == 0)
1566 if (Lex.getCode() != tgtok::semi)
1567 return TokError("expected ';' after declaration");
1572 // LET ID OptionalRangeList '=' Value ';'
1573 if (Lex.Lex() != tgtok::Id)
1574 return TokError("expected field identifier after let");
1576 SMLoc IdLoc = Lex.getLoc();
1577 std::string FieldName = Lex.getCurStrVal();
1578 Lex.Lex(); // eat the field name.
1580 std::vector<unsigned> BitList;
1581 if (ParseOptionalBitList(BitList))
1583 std::reverse(BitList.begin(), BitList.end());
1585 if (Lex.getCode() != tgtok::equal)
1586 return TokError("expected '=' in let expression");
1587 Lex.Lex(); // eat the '='.
1589 RecordVal *Field = CurRec->getValue(FieldName);
1591 return TokError("Value '" + FieldName + "' unknown!");
1593 RecTy *Type = Field->getType();
1595 Init *Val = ParseValue(CurRec, Type);
1596 if (Val == 0) return true;
1598 if (Lex.getCode() != tgtok::semi)
1599 return TokError("expected ';' after let expression");
1602 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1605 /// ParseBody - Read the body of a class or def. Return true on error, false on
1609 /// Body ::= '{' BodyList '}'
1610 /// BodyList BodyItem*
1612 bool TGParser::ParseBody(Record *CurRec) {
1613 // If this is a null definition, just eat the semi and return.
1614 if (Lex.getCode() == tgtok::semi) {
1619 if (Lex.getCode() != tgtok::l_brace)
1620 return TokError("Expected ';' or '{' to start body");
1624 while (Lex.getCode() != tgtok::r_brace)
1625 if (ParseBodyItem(CurRec))
1633 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1634 /// optional ClassList followed by a Body. CurRec is the current def or class
1635 /// that is being parsed.
1637 /// ObjectBody ::= BaseClassList Body
1638 /// BaseClassList ::= /*empty*/
1639 /// BaseClassList ::= ':' BaseClassListNE
1640 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1642 bool TGParser::ParseObjectBody(Record *CurRec) {
1643 // If there is a baseclass list, read it.
1644 if (Lex.getCode() == tgtok::colon) {
1647 // Read all of the subclasses.
1648 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1651 if (SubClass.Rec == 0) return true;
1654 if (AddSubClass(CurRec, SubClass))
1657 if (Lex.getCode() != tgtok::comma) break;
1658 Lex.Lex(); // eat ','.
1659 SubClass = ParseSubClassReference(CurRec, false);
1663 // Process any variables on the let stack.
1664 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1665 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1666 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1667 LetStack[i][j].Bits, LetStack[i][j].Value))
1670 return ParseBody(CurRec);
1673 /// ParseDef - Parse and return a top level or multiclass def, return the record
1674 /// corresponding to it. This returns null on error.
1676 /// DefInst ::= DEF ObjectName ObjectBody
1678 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1679 SMLoc DefLoc = Lex.getLoc();
1680 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1681 Lex.Lex(); // Eat the 'def' token.
1683 // Parse ObjectName and make a record for it.
1684 Record *CurRec = new Record(ParseObjectName(), DefLoc, Records);
1686 if (!CurMultiClass) {
1687 // Top-level def definition.
1689 // Ensure redefinition doesn't happen.
1690 if (Records.getDef(CurRec->getName())) {
1691 Error(DefLoc, "def '" + CurRec->getNameInitAsString()
1692 + "' already defined");
1695 Records.addDef(CurRec);
1697 // Otherwise, a def inside a multiclass, add it to the multiclass.
1698 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1699 if (CurMultiClass->DefPrototypes[i]->getNameInit()
1700 == CurRec->getNameInit()) {
1701 Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
1702 "' already defined in this multiclass!");
1705 CurMultiClass->DefPrototypes.push_back(CurRec);
1708 if (ParseObjectBody(CurRec))
1711 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1712 // See Record::setName(). This resolve step will see any new name
1713 // for the def that might have been created when resolving
1714 // inheritance, values and arguments above.
1715 CurRec->resolveReferences();
1717 // If ObjectBody has template arguments, it's an error.
1718 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1720 if (CurMultiClass) {
1721 // Copy the template arguments for the multiclass into the def.
1722 const std::vector<Init *> &TArgs =
1723 CurMultiClass->Rec.getTemplateArgs();
1725 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1726 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1727 assert(RV && "Template arg doesn't exist?");
1728 CurRec->addValue(*RV);
1735 /// ParseClass - Parse a tblgen class definition.
1737 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1739 bool TGParser::ParseClass() {
1740 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1743 if (Lex.getCode() != tgtok::Id)
1744 return TokError("expected class name after 'class' keyword");
1746 Record *CurRec = Records.getClass(Lex.getCurStrVal());
1748 // If the body was previously defined, this is an error.
1749 if (CurRec->getValues().size() > 1 || // Account for NAME.
1750 !CurRec->getSuperClasses().empty() ||
1751 !CurRec->getTemplateArgs().empty())
1752 return TokError("Class '" + CurRec->getNameInitAsString()
1753 + "' already defined");
1755 // If this is the first reference to this class, create and add it.
1756 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
1757 Records.addClass(CurRec);
1759 Lex.Lex(); // eat the name.
1761 // If there are template args, parse them.
1762 if (Lex.getCode() == tgtok::less)
1763 if (ParseTemplateArgList(CurRec))
1766 // Finally, parse the object body.
1767 return ParseObjectBody(CurRec);
1770 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
1773 /// LetList ::= LetItem (',' LetItem)*
1774 /// LetItem ::= ID OptionalRangeList '=' Value
1776 std::vector<LetRecord> TGParser::ParseLetList() {
1777 std::vector<LetRecord> Result;
1780 if (Lex.getCode() != tgtok::Id) {
1781 TokError("expected identifier in let definition");
1782 return std::vector<LetRecord>();
1784 std::string Name = Lex.getCurStrVal();
1785 SMLoc NameLoc = Lex.getLoc();
1786 Lex.Lex(); // Eat the identifier.
1788 // Check for an optional RangeList.
1789 std::vector<unsigned> Bits;
1790 if (ParseOptionalRangeList(Bits))
1791 return std::vector<LetRecord>();
1792 std::reverse(Bits.begin(), Bits.end());
1794 if (Lex.getCode() != tgtok::equal) {
1795 TokError("expected '=' in let expression");
1796 return std::vector<LetRecord>();
1798 Lex.Lex(); // eat the '='.
1800 Init *Val = ParseValue(0);
1801 if (Val == 0) return std::vector<LetRecord>();
1803 // Now that we have everything, add the record.
1804 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1806 if (Lex.getCode() != tgtok::comma)
1808 Lex.Lex(); // eat the comma.
1812 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
1813 /// different related productions. This works inside multiclasses too.
1815 /// Object ::= LET LetList IN '{' ObjectList '}'
1816 /// Object ::= LET LetList IN Object
1818 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
1819 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1822 // Add this entry to the let stack.
1823 std::vector<LetRecord> LetInfo = ParseLetList();
1824 if (LetInfo.empty()) return true;
1825 LetStack.push_back(LetInfo);
1827 if (Lex.getCode() != tgtok::In)
1828 return TokError("expected 'in' at end of top-level 'let'");
1831 // If this is a scalar let, just handle it now
1832 if (Lex.getCode() != tgtok::l_brace) {
1833 // LET LetList IN Object
1834 if (ParseObject(CurMultiClass))
1836 } else { // Object ::= LETCommand '{' ObjectList '}'
1837 SMLoc BraceLoc = Lex.getLoc();
1838 // Otherwise, this is a group let.
1839 Lex.Lex(); // eat the '{'.
1841 // Parse the object list.
1842 if (ParseObjectList(CurMultiClass))
1845 if (Lex.getCode() != tgtok::r_brace) {
1846 TokError("expected '}' at end of top level let command");
1847 return Error(BraceLoc, "to match this '{'");
1852 // Outside this let scope, this let block is not active.
1853 LetStack.pop_back();
1857 /// ParseMultiClass - Parse a multiclass definition.
1859 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
1860 /// ':' BaseMultiClassList '{' MultiClassDef+ '}'
1862 bool TGParser::ParseMultiClass() {
1863 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1864 Lex.Lex(); // Eat the multiclass token.
1866 if (Lex.getCode() != tgtok::Id)
1867 return TokError("expected identifier after multiclass for name");
1868 std::string Name = Lex.getCurStrVal();
1870 if (MultiClasses.count(Name))
1871 return TokError("multiclass '" + Name + "' already defined");
1873 CurMultiClass = MultiClasses[Name] = new MultiClass(Name,
1874 Lex.getLoc(), Records);
1875 Lex.Lex(); // Eat the identifier.
1877 // If there are template args, parse them.
1878 if (Lex.getCode() == tgtok::less)
1879 if (ParseTemplateArgList(0))
1882 bool inherits = false;
1884 // If there are submulticlasses, parse them.
1885 if (Lex.getCode() == tgtok::colon) {
1890 // Read all of the submulticlasses.
1891 SubMultiClassReference SubMultiClass =
1892 ParseSubMultiClassReference(CurMultiClass);
1895 if (SubMultiClass.MC == 0) return true;
1898 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
1901 if (Lex.getCode() != tgtok::comma) break;
1902 Lex.Lex(); // eat ','.
1903 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
1907 if (Lex.getCode() != tgtok::l_brace) {
1909 return TokError("expected '{' in multiclass definition");
1910 else if (Lex.getCode() != tgtok::semi)
1911 return TokError("expected ';' in multiclass definition");
1913 Lex.Lex(); // eat the ';'.
1915 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
1916 return TokError("multiclass must contain at least one def");
1918 while (Lex.getCode() != tgtok::r_brace) {
1919 switch (Lex.getCode()) {
1921 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
1925 if (ParseObject(CurMultiClass))
1930 Lex.Lex(); // eat the '}'.
1938 InstantiateMulticlassDef(MultiClass &MC,
1940 const std::string &DefmPrefix,
1941 SMLoc DefmPrefixLoc) {
1942 // Add in the defm name. If the defm prefix is empty, give each
1943 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
1944 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
1946 std::string DefName = DefProto->getName();
1947 if (DefmPrefix.empty()) {
1948 DefName = GetNewAnonymousName();
1950 std::string::size_type idx = DefName.find("#NAME#");
1951 if (idx != std::string::npos) {
1952 DefName.replace(idx, 6, DefmPrefix);
1954 // Add the suffix to the defm name to get the new name.
1955 DefName = DefmPrefix + DefName;
1959 Record *CurRec = new Record(DefName, DefmPrefixLoc, Records);
1961 SubClassReference Ref;
1962 Ref.RefLoc = DefmPrefixLoc;
1964 AddSubClass(CurRec, Ref);
1969 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
1971 SMLoc DefmPrefixLoc,
1973 const std::vector<Init *> &TArgs,
1974 std::vector<Init *> &TemplateVals,
1976 // Loop over all of the template arguments, setting them to the specified
1977 // value or leaving them as the default if necessary.
1978 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1979 // Check if a value is specified for this temp-arg.
1980 if (i < TemplateVals.size()) {
1982 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
1987 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
1991 CurRec->removeValue(TArgs[i]);
1993 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
1994 return Error(SubClassLoc, "value not specified for template argument #"+
1995 utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
1996 + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2003 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2006 SMLoc DefmPrefixLoc) {
2007 // If the mdef is inside a 'let' expression, add to each def.
2008 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2009 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2010 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2011 LetStack[i][j].Bits, LetStack[i][j].Value))
2012 return Error(DefmPrefixLoc, "when instantiating this defm");
2014 // Ensure redefinition doesn't happen.
2015 if (Records.getDef(CurRec->getName()))
2016 return Error(DefmPrefixLoc, "def '" + CurRec->getName() +
2017 "' already defined, instantiating defm with subdef '" +
2018 DefProto->getName() + "'");
2020 // Don't create a top level definition for defm inside multiclasses,
2021 // instead, only update the prototypes and bind the template args
2022 // with the new created definition.
2023 if (CurMultiClass) {
2024 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2026 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2027 == CurRec->getNameInit())
2028 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2029 "' already defined in this multiclass!");
2030 CurMultiClass->DefPrototypes.push_back(CurRec);
2032 // Copy the template arguments for the multiclass into the new def.
2033 const std::vector<Init *> &TA =
2034 CurMultiClass->Rec.getTemplateArgs();
2036 for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2037 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2038 assert(RV && "Template arg doesn't exist?");
2039 CurRec->addValue(*RV);
2042 Records.addDef(CurRec);
2048 /// ParseDefm - Parse the instantiation of a multiclass.
2050 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2052 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2053 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2055 std::string DefmPrefix;
2056 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2057 DefmPrefix = Lex.getCurStrVal();
2058 Lex.Lex(); // Eat the defm prefix.
2061 SMLoc DefmPrefixLoc = Lex.getLoc();
2062 if (Lex.getCode() != tgtok::colon)
2063 return TokError("expected ':' after defm identifier");
2065 // Keep track of the new generated record definitions.
2066 std::vector<Record*> NewRecDefs;
2068 // This record also inherits from a regular class (non-multiclass)?
2069 bool InheritFromClass = false;
2074 SMLoc SubClassLoc = Lex.getLoc();
2075 SubClassReference Ref = ParseSubClassReference(0, true);
2078 if (Ref.Rec == 0) return true;
2080 // To instantiate a multiclass, we need to first get the multiclass, then
2081 // instantiate each def contained in the multiclass with the SubClassRef
2082 // template parameters.
2083 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
2084 assert(MC && "Didn't lookup multiclass correctly?");
2085 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2087 // Verify that the correct number of template arguments were specified.
2088 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2089 if (TArgs.size() < TemplateVals.size())
2090 return Error(SubClassLoc,
2091 "more template args specified than multiclass expects");
2093 // Loop over all the def's in the multiclass, instantiating each one.
2094 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2095 Record *DefProto = MC->DefPrototypes[i];
2097 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix, DefmPrefixLoc);
2099 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmPrefixLoc, SubClassLoc,
2100 TArgs, TemplateVals, true/*Delete args*/))
2101 return Error(SubClassLoc, "could not instantiate def");
2103 if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmPrefixLoc))
2104 return Error(SubClassLoc, "could not instantiate def");
2106 NewRecDefs.push_back(CurRec);
2110 if (Lex.getCode() != tgtok::comma) break;
2111 Lex.Lex(); // eat ','.
2113 SubClassLoc = Lex.getLoc();
2115 // A defm can inherit from regular classes (non-multiclass) as
2116 // long as they come in the end of the inheritance list.
2117 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != 0);
2119 if (InheritFromClass)
2122 Ref = ParseSubClassReference(0, true);
2125 if (InheritFromClass) {
2126 // Process all the classes to inherit as if they were part of a
2127 // regular 'def' and inherit all record values.
2128 SubClassReference SubClass = ParseSubClassReference(0, false);
2131 if (SubClass.Rec == 0) return true;
2133 // Get the expanded definition prototypes and teach them about
2134 // the record values the current class to inherit has
2135 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2136 Record *CurRec = NewRecDefs[i];
2139 if (AddSubClass(CurRec, SubClass))
2142 // Process any variables on the let stack.
2143 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2144 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2145 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2146 LetStack[i][j].Bits, LetStack[i][j].Value))
2150 if (Lex.getCode() != tgtok::comma) break;
2151 Lex.Lex(); // eat ','.
2152 SubClass = ParseSubClassReference(0, false);
2157 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2158 // See Record::setName(). This resolve step will see any new
2159 // name for the def that might have been created when resolving
2160 // inheritance, values and arguments above.
2161 NewRecDefs[i]->resolveReferences();
2163 if (Lex.getCode() != tgtok::semi)
2164 return TokError("expected ';' at end of defm");
2171 /// Object ::= ClassInst
2172 /// Object ::= DefInst
2173 /// Object ::= MultiClassInst
2174 /// Object ::= DefMInst
2175 /// Object ::= LETCommand '{' ObjectList '}'
2176 /// Object ::= LETCommand Object
2177 bool TGParser::ParseObject(MultiClass *MC) {
2178 switch (Lex.getCode()) {
2180 return TokError("Expected class, def, defm, multiclass or let definition");
2181 case tgtok::Let: return ParseTopLevelLet(MC);
2182 case tgtok::Def: return ParseDef(MC);
2183 case tgtok::Defm: return ParseDefm(MC);
2184 case tgtok::Class: return ParseClass();
2185 case tgtok::MultiClass: return ParseMultiClass();
2190 /// ObjectList :== Object*
2191 bool TGParser::ParseObjectList(MultiClass *MC) {
2192 while (isObjectStart(Lex.getCode())) {
2193 if (ParseObject(MC))
2199 bool TGParser::ParseFile() {
2200 Lex.Lex(); // Prime the lexer.
2201 if (ParseObjectList()) return true;
2203 // If we have unread input at the end of the file, report it.
2204 if (Lex.getCode() == tgtok::Eof)
2207 return TokError("Unexpected input at top level");