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 ::= Value [ '#' Value ]*
310 /// ObjectName ::= /*empty*/
312 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
313 switch (Lex.getCode()) {
317 // These are all of the tokens that can begin an object body.
318 // Some of these can also begin values but we disallow those cases
319 // because they are unlikely to be useful.
320 return StringInit::get(GetNewAnonymousName());
328 CurRec = &CurMultiClass->Rec;
332 const TypedInit *CurRecName =
333 dynamic_cast<const TypedInit *>(CurRec->getNameInit());
335 TokError("Record name is not typed!");
338 Type = CurRecName->getType();
341 return ParseValue(CurRec, Type, ParseNameMode);
344 /// ParseClassID - Parse and resolve a reference to a class name. This returns
349 Record *TGParser::ParseClassID() {
350 if (Lex.getCode() != tgtok::Id) {
351 TokError("expected name for ClassID");
355 Record *Result = Records.getClass(Lex.getCurStrVal());
357 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
363 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
364 /// This returns null on error.
366 /// MultiClassID ::= ID
368 MultiClass *TGParser::ParseMultiClassID() {
369 if (Lex.getCode() != tgtok::Id) {
370 TokError("expected name for ClassID");
374 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
376 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
382 Record *TGParser::ParseDefmID() {
383 if (Lex.getCode() != tgtok::Id) {
384 TokError("expected multiclass name");
388 MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
390 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
399 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
400 /// subclass. This returns a SubClassRefTy with a null Record* on error.
402 /// SubClassRef ::= ClassID
403 /// SubClassRef ::= ClassID '<' ValueList '>'
405 SubClassReference TGParser::
406 ParseSubClassReference(Record *CurRec, bool isDefm) {
407 SubClassReference Result;
408 Result.RefLoc = Lex.getLoc();
411 Result.Rec = ParseDefmID();
413 Result.Rec = ParseClassID();
414 if (Result.Rec == 0) return Result;
416 // If there is no template arg list, we're done.
417 if (Lex.getCode() != tgtok::less)
419 Lex.Lex(); // Eat the '<'
421 if (Lex.getCode() == tgtok::greater) {
422 TokError("subclass reference requires a non-empty list of template values");
427 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
428 if (Result.TemplateArgs.empty()) {
429 Result.Rec = 0; // Error parsing value list.
433 if (Lex.getCode() != tgtok::greater) {
434 TokError("expected '>' in template value list");
443 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
444 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
445 /// Record* on error.
447 /// SubMultiClassRef ::= MultiClassID
448 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
450 SubMultiClassReference TGParser::
451 ParseSubMultiClassReference(MultiClass *CurMC) {
452 SubMultiClassReference Result;
453 Result.RefLoc = Lex.getLoc();
455 Result.MC = ParseMultiClassID();
456 if (Result.MC == 0) return Result;
458 // If there is no template arg list, we're done.
459 if (Lex.getCode() != tgtok::less)
461 Lex.Lex(); // Eat the '<'
463 if (Lex.getCode() == tgtok::greater) {
464 TokError("subclass reference requires a non-empty list of template values");
469 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
470 if (Result.TemplateArgs.empty()) {
471 Result.MC = 0; // Error parsing value list.
475 if (Lex.getCode() != tgtok::greater) {
476 TokError("expected '>' in template value list");
485 /// ParseRangePiece - Parse a bit/value range.
486 /// RangePiece ::= INTVAL
487 /// RangePiece ::= INTVAL '-' INTVAL
488 /// RangePiece ::= INTVAL INTVAL
489 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
490 if (Lex.getCode() != tgtok::IntVal) {
491 TokError("expected integer or bitrange");
494 int64_t Start = Lex.getCurIntVal();
498 return TokError("invalid range, cannot be negative");
500 switch (Lex.Lex()) { // eat first character.
502 Ranges.push_back(Start);
505 if (Lex.Lex() != tgtok::IntVal) {
506 TokError("expected integer value as end of range");
509 End = Lex.getCurIntVal();
512 End = -Lex.getCurIntVal();
516 return TokError("invalid range, cannot be negative");
521 for (; Start <= End; ++Start)
522 Ranges.push_back(Start);
524 for (; Start >= End; --Start)
525 Ranges.push_back(Start);
530 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
532 /// RangeList ::= RangePiece (',' RangePiece)*
534 std::vector<unsigned> TGParser::ParseRangeList() {
535 std::vector<unsigned> Result;
537 // Parse the first piece.
538 if (ParseRangePiece(Result))
539 return std::vector<unsigned>();
540 while (Lex.getCode() == tgtok::comma) {
541 Lex.Lex(); // Eat the comma.
543 // Parse the next range piece.
544 if (ParseRangePiece(Result))
545 return std::vector<unsigned>();
550 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
551 /// OptionalRangeList ::= '<' RangeList '>'
552 /// OptionalRangeList ::= /*empty*/
553 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
554 if (Lex.getCode() != tgtok::less)
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::greater) {
565 TokError("expected '>' at end of range list");
566 return Error(StartLoc, "to match this '<'");
568 Lex.Lex(); // eat the '>'.
572 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
573 /// OptionalBitList ::= '{' RangeList '}'
574 /// OptionalBitList ::= /*empty*/
575 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
576 if (Lex.getCode() != tgtok::l_brace)
579 SMLoc StartLoc = Lex.getLoc();
580 Lex.Lex(); // eat the '{'
582 // Parse the range list.
583 Ranges = ParseRangeList();
584 if (Ranges.empty()) return true;
586 if (Lex.getCode() != tgtok::r_brace) {
587 TokError("expected '}' at end of bit list");
588 return Error(StartLoc, "to match this '{'");
590 Lex.Lex(); // eat the '}'.
595 /// ParseType - Parse and return a tblgen type. This returns null on error.
597 /// Type ::= STRING // string type
598 /// Type ::= BIT // bit type
599 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
600 /// Type ::= INT // int type
601 /// Type ::= LIST '<' Type '>' // list<x> type
602 /// Type ::= CODE // code type
603 /// Type ::= DAG // dag type
604 /// Type ::= ClassID // Record Type
606 RecTy *TGParser::ParseType() {
607 switch (Lex.getCode()) {
608 default: TokError("Unknown token when expecting a type"); return 0;
609 case tgtok::String: Lex.Lex(); return StringRecTy::get();
610 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
611 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
612 case tgtok::Code: Lex.Lex(); return CodeRecTy::get();
613 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
615 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
618 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
619 TokError("expected '<' after bits type");
622 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
623 TokError("expected integer in bits<n> type");
626 uint64_t Val = Lex.getCurIntVal();
627 if (Lex.Lex() != tgtok::greater) { // Eat count.
628 TokError("expected '>' at end of bits<n> type");
631 Lex.Lex(); // Eat '>'
632 return BitsRecTy::get(Val);
635 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
636 TokError("expected '<' after list type");
639 Lex.Lex(); // Eat '<'
640 RecTy *SubType = ParseType();
641 if (SubType == 0) return 0;
643 if (Lex.getCode() != tgtok::greater) {
644 TokError("expected '>' at end of list<ty> type");
647 Lex.Lex(); // Eat '>'
648 return ListRecTy::get(SubType);
653 /// ParseIDValue - Parse an ID as a value and decode what it means.
655 /// IDValue ::= ID [def local value]
656 /// IDValue ::= ID [def template arg]
657 /// IDValue ::= ID [multiclass local value]
658 /// IDValue ::= ID [multiclass template argument]
659 /// IDValue ::= ID [def name]
661 Init *TGParser::ParseIDValue(Record *CurRec, IDParseMode Mode) {
662 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
663 std::string Name = Lex.getCurStrVal();
664 SMLoc Loc = Lex.getLoc();
666 return ParseIDValue(CurRec, Name, Loc);
669 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
670 /// has already been read.
671 Init *TGParser::ParseIDValue(Record *CurRec,
672 const std::string &Name, SMLoc NameLoc,
675 if (const RecordVal *RV = CurRec->getValue(Name))
676 return VarInit::get(Name, RV->getType());
678 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
681 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
684 if (CurRec->isTemplateArg(TemplateArgName)) {
685 const RecordVal *RV = CurRec->getValue(TemplateArgName);
686 assert(RV && "Template arg doesn't exist??");
687 return VarInit::get(TemplateArgName, RV->getType());
692 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
695 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
696 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
697 assert(RV && "Template arg doesn't exist??");
698 return VarInit::get(MCName, RV->getType());
702 if (Mode == ParseNameMode)
703 return StringInit::get(Name);
705 if (Record *D = Records.getDef(Name))
706 return DefInit::get(D);
708 if (Mode == ParseValueMode) {
709 Error(NameLoc, "Variable not defined: '" + Name + "'");
713 return StringInit::get(Name);
716 /// ParseOperation - Parse an operator. This returns null on error.
718 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
720 Init *TGParser::ParseOperation(Record *CurRec) {
721 switch (Lex.getCode()) {
723 TokError("unknown operation");
729 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
730 UnOpInit::UnaryOp Code;
733 switch (Lex.getCode()) {
734 default: assert(0 && "Unhandled code!");
736 Lex.Lex(); // eat the operation
737 Code = UnOpInit::CAST;
739 Type = ParseOperatorType();
742 TokError("did not get type for unary operator");
748 Lex.Lex(); // eat the operation
749 Code = UnOpInit::HEAD;
752 Lex.Lex(); // eat the operation
753 Code = UnOpInit::TAIL;
756 Lex.Lex(); // eat the operation
757 Code = UnOpInit::EMPTY;
758 Type = IntRecTy::get();
761 if (Lex.getCode() != tgtok::l_paren) {
762 TokError("expected '(' after unary operator");
765 Lex.Lex(); // eat the '('
767 Init *LHS = ParseValue(CurRec);
768 if (LHS == 0) return 0;
770 if (Code == UnOpInit::HEAD
771 || Code == UnOpInit::TAIL
772 || Code == UnOpInit::EMPTY) {
773 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
774 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
775 TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
776 if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
777 TokError("expected list or string type argument in unary operator");
781 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
782 StringRecTy *SType = dynamic_cast<StringRecTy*>(LHSt->getType());
783 if (LType == 0 && SType == 0) {
784 TokError("expected list or string type argumnet in unary operator");
789 if (Code == UnOpInit::HEAD
790 || Code == UnOpInit::TAIL) {
791 if (LHSl == 0 && LHSt == 0) {
792 TokError("expected list type argumnet in unary operator");
796 if (LHSl && LHSl->getSize() == 0) {
797 TokError("empty list argument in unary operator");
801 Init *Item = LHSl->getElement(0);
802 TypedInit *Itemt = dynamic_cast<TypedInit*>(Item);
804 TokError("untyped list element in unary operator");
807 if (Code == UnOpInit::HEAD) {
808 Type = Itemt->getType();
810 Type = ListRecTy::get(Itemt->getType());
813 assert(LHSt && "expected list type argument in unary operator");
814 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
816 TokError("expected list type argumnet in unary operator");
819 if (Code == UnOpInit::HEAD) {
820 Type = LType->getElementType();
828 if (Lex.getCode() != tgtok::r_paren) {
829 TokError("expected ')' in unary operator");
832 Lex.Lex(); // eat the ')'
833 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
841 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
842 tgtok::TokKind OpTok = Lex.getCode();
843 SMLoc OpLoc = Lex.getLoc();
844 Lex.Lex(); // eat the operation
846 BinOpInit::BinaryOp Code;
850 default: assert(0 && "Unhandled code!");
851 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
852 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
853 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
854 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
855 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
856 case tgtok::XStrConcat:
857 Code = BinOpInit::STRCONCAT;
858 Type = StringRecTy::get();
862 if (Lex.getCode() != tgtok::l_paren) {
863 TokError("expected '(' after binary operator");
866 Lex.Lex(); // eat the '('
868 SmallVector<Init*, 2> InitList;
870 InitList.push_back(ParseValue(CurRec));
871 if (InitList.back() == 0) return 0;
873 while (Lex.getCode() == tgtok::comma) {
874 Lex.Lex(); // eat the ','
876 InitList.push_back(ParseValue(CurRec));
877 if (InitList.back() == 0) return 0;
880 if (Lex.getCode() != tgtok::r_paren) {
881 TokError("expected ')' in operator");
884 Lex.Lex(); // eat the ')'
886 // We allow multiple operands to associative operators like !strconcat as
887 // shorthand for nesting them.
888 if (Code == BinOpInit::STRCONCAT) {
889 while (InitList.size() > 2) {
890 Init *RHS = InitList.pop_back_val();
891 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
892 ->Fold(CurRec, CurMultiClass);
893 InitList.back() = RHS;
897 if (InitList.size() == 2)
898 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
899 ->Fold(CurRec, CurMultiClass);
901 Error(OpLoc, "expected two operands to operator");
906 case tgtok::XForEach:
907 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
908 TernOpInit::TernaryOp Code;
911 tgtok::TokKind LexCode = Lex.getCode();
912 Lex.Lex(); // eat the operation
914 default: assert(0 && "Unhandled code!");
916 Code = TernOpInit::IF;
918 case tgtok::XForEach:
919 Code = TernOpInit::FOREACH;
922 Code = TernOpInit::SUBST;
925 if (Lex.getCode() != tgtok::l_paren) {
926 TokError("expected '(' after ternary operator");
929 Lex.Lex(); // eat the '('
931 Init *LHS = ParseValue(CurRec);
932 if (LHS == 0) return 0;
934 if (Lex.getCode() != tgtok::comma) {
935 TokError("expected ',' in ternary operator");
938 Lex.Lex(); // eat the ','
940 Init *MHS = ParseValue(CurRec);
941 if (MHS == 0) return 0;
943 if (Lex.getCode() != tgtok::comma) {
944 TokError("expected ',' in ternary operator");
947 Lex.Lex(); // eat the ','
949 Init *RHS = ParseValue(CurRec);
950 if (RHS == 0) return 0;
952 if (Lex.getCode() != tgtok::r_paren) {
953 TokError("expected ')' in binary operator");
956 Lex.Lex(); // eat the ')'
959 default: assert(0 && "Unhandled code!");
961 // FIXME: The `!if' operator doesn't handle non-TypedInit well at
962 // all. This can be made much more robust.
963 TypedInit *MHSt = dynamic_cast<TypedInit*>(MHS);
964 TypedInit *RHSt = dynamic_cast<TypedInit*>(RHS);
969 if (MHSt == 0 && RHSt == 0) {
970 BitsInit *MHSbits = dynamic_cast<BitsInit*>(MHS);
971 BitsInit *RHSbits = dynamic_cast<BitsInit*>(RHS);
973 if (MHSbits && RHSbits &&
974 MHSbits->getNumBits() == RHSbits->getNumBits()) {
975 Type = BitRecTy::get();
978 BitInit *MHSbit = dynamic_cast<BitInit*>(MHS);
979 BitInit *RHSbit = dynamic_cast<BitInit*>(RHS);
981 if (MHSbit && RHSbit) {
982 Type = BitRecTy::get();
986 } else if (MHSt != 0 && RHSt != 0) {
987 MHSTy = MHSt->getType();
988 RHSTy = RHSt->getType();
991 if (!MHSTy || !RHSTy) {
992 TokError("could not get type for !if");
996 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
998 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1001 TokError("inconsistent types for !if");
1006 case tgtok::XForEach: {
1007 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
1009 TokError("could not get type for !foreach");
1012 Type = MHSt->getType();
1015 case tgtok::XSubst: {
1016 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
1018 TokError("could not get type for !subst");
1021 Type = RHSt->getType();
1025 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1029 TokError("could not parse operation");
1033 /// ParseOperatorType - Parse a type for an operator. This returns
1036 /// OperatorType ::= '<' Type '>'
1038 RecTy *TGParser::ParseOperatorType() {
1041 if (Lex.getCode() != tgtok::less) {
1042 TokError("expected type name for operator");
1045 Lex.Lex(); // eat the <
1050 TokError("expected type name for operator");
1054 if (Lex.getCode() != tgtok::greater) {
1055 TokError("expected type name for operator");
1058 Lex.Lex(); // eat the >
1064 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1066 /// SimpleValue ::= IDValue
1067 /// SimpleValue ::= INTVAL
1068 /// SimpleValue ::= STRVAL+
1069 /// SimpleValue ::= CODEFRAGMENT
1070 /// SimpleValue ::= '?'
1071 /// SimpleValue ::= '{' ValueList '}'
1072 /// SimpleValue ::= ID '<' ValueListNE '>'
1073 /// SimpleValue ::= '[' ValueList ']'
1074 /// SimpleValue ::= '(' IDValue DagArgList ')'
1075 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1076 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1077 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1078 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1079 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1081 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1084 switch (Lex.getCode()) {
1085 default: TokError("Unknown token when parsing a value"); break;
1087 // This is a leading paste operation. This is deprecated but
1088 // still exists in some .td files. Ignore it.
1089 Lex.Lex(); // Skip '#'.
1090 return ParseSimpleValue(CurRec, ItemType, Mode);
1092 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1093 case tgtok::StrVal: {
1094 std::string Val = Lex.getCurStrVal();
1097 // Handle multiple consecutive concatenated strings.
1098 while (Lex.getCode() == tgtok::StrVal) {
1099 Val += Lex.getCurStrVal();
1103 R = StringInit::get(Val);
1106 case tgtok::CodeFragment:
1107 R = CodeInit::get(Lex.getCurStrVal());
1110 case tgtok::question:
1111 R = UnsetInit::get();
1115 SMLoc NameLoc = Lex.getLoc();
1116 std::string Name = Lex.getCurStrVal();
1117 if (Lex.Lex() != tgtok::less) // consume the Id.
1118 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1120 // Value ::= ID '<' ValueListNE '>'
1121 if (Lex.Lex() == tgtok::greater) {
1122 TokError("expected non-empty value list");
1126 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1127 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1129 Record *Class = Records.getClass(Name);
1131 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1135 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1136 if (ValueList.empty()) return 0;
1138 if (Lex.getCode() != tgtok::greater) {
1139 TokError("expected '>' at end of value list");
1142 Lex.Lex(); // eat the '>'
1144 // Create the new record, set it as CurRec temporarily.
1145 static unsigned AnonCounter = 0;
1146 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),
1149 SubClassReference SCRef;
1150 SCRef.RefLoc = NameLoc;
1152 SCRef.TemplateArgs = ValueList;
1153 // Add info about the subclass to NewRec.
1154 if (AddSubClass(NewRec, SCRef))
1156 NewRec->resolveReferences();
1157 Records.addDef(NewRec);
1159 // The result of the expression is a reference to the new record.
1160 return DefInit::get(NewRec);
1162 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1163 SMLoc BraceLoc = Lex.getLoc();
1164 Lex.Lex(); // eat the '{'
1165 std::vector<Init*> Vals;
1167 if (Lex.getCode() != tgtok::r_brace) {
1168 Vals = ParseValueList(CurRec);
1169 if (Vals.empty()) return 0;
1171 if (Lex.getCode() != tgtok::r_brace) {
1172 TokError("expected '}' at end of bit list value");
1175 Lex.Lex(); // eat the '}'
1177 SmallVector<Init *, 16> NewBits(Vals.size());
1179 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1180 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1182 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1183 ") is not convertable to a bit");
1186 NewBits[Vals.size()-i-1] = Bit;
1188 return BitsInit::get(NewBits);
1190 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1191 Lex.Lex(); // eat the '['
1192 std::vector<Init*> Vals;
1194 RecTy *DeducedEltTy = 0;
1195 ListRecTy *GivenListTy = 0;
1197 if (ItemType != 0) {
1198 ListRecTy *ListType = dynamic_cast<ListRecTy*>(ItemType);
1199 if (ListType == 0) {
1200 std::stringstream s;
1201 s << "Type mismatch for list, expected list type, got "
1202 << ItemType->getAsString();
1206 GivenListTy = ListType;
1209 if (Lex.getCode() != tgtok::r_square) {
1210 Vals = ParseValueList(CurRec, 0,
1211 GivenListTy ? GivenListTy->getElementType() : 0);
1212 if (Vals.empty()) return 0;
1214 if (Lex.getCode() != tgtok::r_square) {
1215 TokError("expected ']' at end of list value");
1218 Lex.Lex(); // eat the ']'
1220 RecTy *GivenEltTy = 0;
1221 if (Lex.getCode() == tgtok::less) {
1222 // Optional list element type
1223 Lex.Lex(); // eat the '<'
1225 GivenEltTy = ParseType();
1226 if (GivenEltTy == 0) {
1227 // Couldn't parse element type
1231 if (Lex.getCode() != tgtok::greater) {
1232 TokError("expected '>' at end of list element type");
1235 Lex.Lex(); // eat the '>'
1240 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1243 TypedInit *TArg = dynamic_cast<TypedInit*>(*i);
1245 TokError("Untyped list element");
1249 EltTy = resolveTypes(EltTy, TArg->getType());
1251 TokError("Incompatible types in list elements");
1255 EltTy = TArg->getType();
1259 if (GivenEltTy != 0) {
1261 // Verify consistency
1262 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1263 TokError("Incompatible types in list elements");
1271 if (ItemType == 0) {
1272 TokError("No type for list");
1275 DeducedEltTy = GivenListTy->getElementType();
1277 // Make sure the deduced type is compatible with the given type
1279 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1280 TokError("Element type mismatch for list");
1284 DeducedEltTy = EltTy;
1287 return ListInit::get(Vals, DeducedEltTy);
1289 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1290 Lex.Lex(); // eat the '('
1291 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1292 TokError("expected identifier in dag init");
1296 Init *Operator = ParseValue(CurRec);
1297 if (Operator == 0) return 0;
1299 // If the operator name is present, parse it.
1300 std::string OperatorName;
1301 if (Lex.getCode() == tgtok::colon) {
1302 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1303 TokError("expected variable name in dag operator");
1306 OperatorName = Lex.getCurStrVal();
1307 Lex.Lex(); // eat the VarName.
1310 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1311 if (Lex.getCode() != tgtok::r_paren) {
1312 DagArgs = ParseDagArgList(CurRec);
1313 if (DagArgs.empty()) return 0;
1316 if (Lex.getCode() != tgtok::r_paren) {
1317 TokError("expected ')' in dag init");
1320 Lex.Lex(); // eat the ')'
1322 return DagInit::get(Operator, OperatorName, DagArgs);
1328 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1329 case tgtok::XConcat:
1334 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1336 case tgtok::XForEach:
1337 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1338 return ParseOperation(CurRec);
1345 /// ParseValue - Parse a tblgen value. This returns null on error.
1347 /// Value ::= SimpleValue ValueSuffix*
1348 /// ValueSuffix ::= '{' BitList '}'
1349 /// ValueSuffix ::= '[' BitList ']'
1350 /// ValueSuffix ::= '.' ID
1352 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1353 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1354 if (Result == 0) return 0;
1356 // Parse the suffixes now if present.
1358 switch (Lex.getCode()) {
1359 default: return Result;
1360 case tgtok::l_brace: {
1361 if (Mode == ParseNameMode)
1362 // This is the beginning of the object body.
1365 SMLoc CurlyLoc = Lex.getLoc();
1366 Lex.Lex(); // eat the '{'
1367 std::vector<unsigned> Ranges = ParseRangeList();
1368 if (Ranges.empty()) return 0;
1370 // Reverse the bitlist.
1371 std::reverse(Ranges.begin(), Ranges.end());
1372 Result = Result->convertInitializerBitRange(Ranges);
1374 Error(CurlyLoc, "Invalid bit range for value");
1379 if (Lex.getCode() != tgtok::r_brace) {
1380 TokError("expected '}' at end of bit range list");
1386 case tgtok::l_square: {
1387 SMLoc SquareLoc = Lex.getLoc();
1388 Lex.Lex(); // eat the '['
1389 std::vector<unsigned> Ranges = ParseRangeList();
1390 if (Ranges.empty()) return 0;
1392 Result = Result->convertInitListSlice(Ranges);
1394 Error(SquareLoc, "Invalid range for list slice");
1399 if (Lex.getCode() != tgtok::r_square) {
1400 TokError("expected ']' at end of list slice");
1407 if (Lex.Lex() != tgtok::Id) { // eat the .
1408 TokError("expected field identifier after '.'");
1411 if (!Result->getFieldType(Lex.getCurStrVal())) {
1412 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1413 Result->getAsString() + "'");
1416 Result = FieldInit::get(Result, Lex.getCurStrVal());
1417 Lex.Lex(); // eat field name
1421 SMLoc PasteLoc = Lex.getLoc();
1423 // Create a !strconcat() operation, first casting each operand to
1424 // a string if necessary.
1426 TypedInit *LHS = dynamic_cast<TypedInit *>(Result);
1428 Error(PasteLoc, "LHS of paste is not typed!");
1432 if (LHS->getType() != StringRecTy::get()) {
1433 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1438 Lex.Lex(); // Eat the '#'.
1439 switch (Lex.getCode()) {
1442 case tgtok::l_brace:
1443 // These are all of the tokens that can begin an object body.
1444 // Some of these can also begin values but we disallow those cases
1445 // because they are unlikely to be useful.
1447 // Trailing paste, concat with an empty string.
1448 RHS = StringInit::get("");
1452 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1453 RHS = dynamic_cast<TypedInit *>(RHSResult);
1455 Error(PasteLoc, "RHS of paste is not typed!");
1459 if (RHS->getType() != StringRecTy::get()) {
1460 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1466 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1467 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1473 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1475 /// ParseDagArgList ::= Value (':' VARNAME)?
1476 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1477 std::vector<std::pair<llvm::Init*, std::string> >
1478 TGParser::ParseDagArgList(Record *CurRec) {
1479 std::vector<std::pair<llvm::Init*, std::string> > Result;
1482 Init *Val = ParseValue(CurRec);
1483 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1485 // If the variable name is present, add it.
1486 std::string VarName;
1487 if (Lex.getCode() == tgtok::colon) {
1488 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1489 TokError("expected variable name in dag literal");
1490 return std::vector<std::pair<llvm::Init*, std::string> >();
1492 VarName = Lex.getCurStrVal();
1493 Lex.Lex(); // eat the VarName.
1496 Result.push_back(std::make_pair(Val, VarName));
1498 if (Lex.getCode() != tgtok::comma) break;
1499 Lex.Lex(); // eat the ','
1506 /// ParseValueList - Parse a comma separated list of values, returning them as a
1507 /// vector. Note that this always expects to be able to parse at least one
1508 /// value. It returns an empty list if this is not possible.
1510 /// ValueList ::= Value (',' Value)
1512 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1514 std::vector<Init*> Result;
1515 RecTy *ItemType = EltTy;
1516 unsigned int ArgN = 0;
1517 if (ArgsRec != 0 && EltTy == 0) {
1518 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1519 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1521 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1524 assert(RV && "Template argument record not found??");
1525 ItemType = RV->getType();
1528 Result.push_back(ParseValue(CurRec, ItemType));
1529 if (Result.back() == 0) return std::vector<Init*>();
1531 while (Lex.getCode() == tgtok::comma) {
1532 Lex.Lex(); // Eat the comma
1534 if (ArgsRec != 0 && EltTy == 0) {
1535 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1536 if (ArgN >= TArgs.size()) {
1537 TokError("too many template arguments");
1538 return std::vector<Init*>();
1540 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1541 assert(RV && "Template argument record not found??");
1542 ItemType = RV->getType();
1545 Result.push_back(ParseValue(CurRec, ItemType));
1546 if (Result.back() == 0) return std::vector<Init*>();
1553 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1554 /// empty string on error. This can happen in a number of different context's,
1555 /// including within a def or in the template args for a def (which which case
1556 /// CurRec will be non-null) and within the template args for a multiclass (in
1557 /// which case CurRec will be null, but CurMultiClass will be set). This can
1558 /// also happen within a def that is within a multiclass, which will set both
1559 /// CurRec and CurMultiClass.
1561 /// Declaration ::= FIELD? Type ID ('=' Value)?
1563 Init *TGParser::ParseDeclaration(Record *CurRec,
1564 bool ParsingTemplateArgs) {
1565 // Read the field prefix if present.
1566 bool HasField = Lex.getCode() == tgtok::Field;
1567 if (HasField) Lex.Lex();
1569 RecTy *Type = ParseType();
1570 if (Type == 0) return 0;
1572 if (Lex.getCode() != tgtok::Id) {
1573 TokError("Expected identifier in declaration");
1577 SMLoc IdLoc = Lex.getLoc();
1578 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1581 if (ParsingTemplateArgs) {
1583 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1585 assert(CurMultiClass);
1588 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1593 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1596 // If a value is present, parse it.
1597 if (Lex.getCode() == tgtok::equal) {
1599 SMLoc ValLoc = Lex.getLoc();
1600 Init *Val = ParseValue(CurRec, Type);
1602 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1609 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1610 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1611 /// template args for a def, which may or may not be in a multiclass. If null,
1612 /// these are the template args for a multiclass.
1614 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1616 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1617 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1618 Lex.Lex(); // eat the '<'
1620 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1622 // Read the first declaration.
1623 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1627 TheRecToAddTo->addTemplateArg(TemplArg);
1629 while (Lex.getCode() == tgtok::comma) {
1630 Lex.Lex(); // eat the ','
1632 // Read the following declarations.
1633 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1636 TheRecToAddTo->addTemplateArg(TemplArg);
1639 if (Lex.getCode() != tgtok::greater)
1640 return TokError("expected '>' at end of template argument list");
1641 Lex.Lex(); // eat the '>'.
1646 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1648 /// BodyItem ::= Declaration ';'
1649 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1650 bool TGParser::ParseBodyItem(Record *CurRec) {
1651 if (Lex.getCode() != tgtok::Let) {
1652 if (ParseDeclaration(CurRec, false) == 0)
1655 if (Lex.getCode() != tgtok::semi)
1656 return TokError("expected ';' after declaration");
1661 // LET ID OptionalRangeList '=' Value ';'
1662 if (Lex.Lex() != tgtok::Id)
1663 return TokError("expected field identifier after let");
1665 SMLoc IdLoc = Lex.getLoc();
1666 std::string FieldName = Lex.getCurStrVal();
1667 Lex.Lex(); // eat the field name.
1669 std::vector<unsigned> BitList;
1670 if (ParseOptionalBitList(BitList))
1672 std::reverse(BitList.begin(), BitList.end());
1674 if (Lex.getCode() != tgtok::equal)
1675 return TokError("expected '=' in let expression");
1676 Lex.Lex(); // eat the '='.
1678 RecordVal *Field = CurRec->getValue(FieldName);
1680 return TokError("Value '" + FieldName + "' unknown!");
1682 RecTy *Type = Field->getType();
1684 Init *Val = ParseValue(CurRec, Type);
1685 if (Val == 0) return true;
1687 if (Lex.getCode() != tgtok::semi)
1688 return TokError("expected ';' after let expression");
1691 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1694 /// ParseBody - Read the body of a class or def. Return true on error, false on
1698 /// Body ::= '{' BodyList '}'
1699 /// BodyList BodyItem*
1701 bool TGParser::ParseBody(Record *CurRec) {
1702 // If this is a null definition, just eat the semi and return.
1703 if (Lex.getCode() == tgtok::semi) {
1708 if (Lex.getCode() != tgtok::l_brace)
1709 return TokError("Expected ';' or '{' to start body");
1713 while (Lex.getCode() != tgtok::r_brace)
1714 if (ParseBodyItem(CurRec))
1722 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1723 /// optional ClassList followed by a Body. CurRec is the current def or class
1724 /// that is being parsed.
1726 /// ObjectBody ::= BaseClassList Body
1727 /// BaseClassList ::= /*empty*/
1728 /// BaseClassList ::= ':' BaseClassListNE
1729 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1731 bool TGParser::ParseObjectBody(Record *CurRec) {
1732 // If there is a baseclass list, read it.
1733 if (Lex.getCode() == tgtok::colon) {
1736 // Read all of the subclasses.
1737 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1740 if (SubClass.Rec == 0) return true;
1743 if (AddSubClass(CurRec, SubClass))
1746 if (Lex.getCode() != tgtok::comma) break;
1747 Lex.Lex(); // eat ','.
1748 SubClass = ParseSubClassReference(CurRec, false);
1752 // Process any variables on the let stack.
1753 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1754 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1755 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1756 LetStack[i][j].Bits, LetStack[i][j].Value))
1759 return ParseBody(CurRec);
1762 /// ParseDef - Parse and return a top level or multiclass def, return the record
1763 /// corresponding to it. This returns null on error.
1765 /// DefInst ::= DEF ObjectName ObjectBody
1767 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1768 SMLoc DefLoc = Lex.getLoc();
1769 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1770 Lex.Lex(); // Eat the 'def' token.
1772 // Parse ObjectName and make a record for it.
1773 Record *CurRec = new Record(ParseObjectName(CurMultiClass), DefLoc, Records);
1775 if (!CurMultiClass) {
1776 // Top-level def definition.
1778 // Ensure redefinition doesn't happen.
1779 if (Records.getDef(CurRec->getName())) {
1780 Error(DefLoc, "def '" + CurRec->getNameInitAsString()
1781 + "' already defined");
1784 Records.addDef(CurRec);
1786 // Otherwise, a def inside a multiclass, add it to the multiclass.
1787 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1788 if (CurMultiClass->DefPrototypes[i]->getNameInit()
1789 == CurRec->getNameInit()) {
1790 Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
1791 "' already defined in this multiclass!");
1794 CurMultiClass->DefPrototypes.push_back(CurRec);
1797 if (ParseObjectBody(CurRec))
1800 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1801 // See Record::setName(). This resolve step will see any new name
1802 // for the def that might have been created when resolving
1803 // inheritance, values and arguments above.
1804 CurRec->resolveReferences();
1806 // If ObjectBody has template arguments, it's an error.
1807 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1809 if (CurMultiClass) {
1810 // Copy the template arguments for the multiclass into the def.
1811 const std::vector<Init *> &TArgs =
1812 CurMultiClass->Rec.getTemplateArgs();
1814 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1815 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1816 assert(RV && "Template arg doesn't exist?");
1817 CurRec->addValue(*RV);
1824 /// ParseClass - Parse a tblgen class definition.
1826 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1828 bool TGParser::ParseClass() {
1829 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1832 if (Lex.getCode() != tgtok::Id)
1833 return TokError("expected class name after 'class' keyword");
1835 Record *CurRec = Records.getClass(Lex.getCurStrVal());
1837 // If the body was previously defined, this is an error.
1838 if (CurRec->getValues().size() > 1 || // Account for NAME.
1839 !CurRec->getSuperClasses().empty() ||
1840 !CurRec->getTemplateArgs().empty())
1841 return TokError("Class '" + CurRec->getNameInitAsString()
1842 + "' already defined");
1844 // If this is the first reference to this class, create and add it.
1845 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
1846 Records.addClass(CurRec);
1848 Lex.Lex(); // eat the name.
1850 // If there are template args, parse them.
1851 if (Lex.getCode() == tgtok::less)
1852 if (ParseTemplateArgList(CurRec))
1855 // Finally, parse the object body.
1856 return ParseObjectBody(CurRec);
1859 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
1862 /// LetList ::= LetItem (',' LetItem)*
1863 /// LetItem ::= ID OptionalRangeList '=' Value
1865 std::vector<LetRecord> TGParser::ParseLetList() {
1866 std::vector<LetRecord> Result;
1869 if (Lex.getCode() != tgtok::Id) {
1870 TokError("expected identifier in let definition");
1871 return std::vector<LetRecord>();
1873 std::string Name = Lex.getCurStrVal();
1874 SMLoc NameLoc = Lex.getLoc();
1875 Lex.Lex(); // Eat the identifier.
1877 // Check for an optional RangeList.
1878 std::vector<unsigned> Bits;
1879 if (ParseOptionalRangeList(Bits))
1880 return std::vector<LetRecord>();
1881 std::reverse(Bits.begin(), Bits.end());
1883 if (Lex.getCode() != tgtok::equal) {
1884 TokError("expected '=' in let expression");
1885 return std::vector<LetRecord>();
1887 Lex.Lex(); // eat the '='.
1889 Init *Val = ParseValue(0);
1890 if (Val == 0) return std::vector<LetRecord>();
1892 // Now that we have everything, add the record.
1893 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1895 if (Lex.getCode() != tgtok::comma)
1897 Lex.Lex(); // eat the comma.
1901 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
1902 /// different related productions. This works inside multiclasses too.
1904 /// Object ::= LET LetList IN '{' ObjectList '}'
1905 /// Object ::= LET LetList IN Object
1907 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
1908 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1911 // Add this entry to the let stack.
1912 std::vector<LetRecord> LetInfo = ParseLetList();
1913 if (LetInfo.empty()) return true;
1914 LetStack.push_back(LetInfo);
1916 if (Lex.getCode() != tgtok::In)
1917 return TokError("expected 'in' at end of top-level 'let'");
1920 // If this is a scalar let, just handle it now
1921 if (Lex.getCode() != tgtok::l_brace) {
1922 // LET LetList IN Object
1923 if (ParseObject(CurMultiClass))
1925 } else { // Object ::= LETCommand '{' ObjectList '}'
1926 SMLoc BraceLoc = Lex.getLoc();
1927 // Otherwise, this is a group let.
1928 Lex.Lex(); // eat the '{'.
1930 // Parse the object list.
1931 if (ParseObjectList(CurMultiClass))
1934 if (Lex.getCode() != tgtok::r_brace) {
1935 TokError("expected '}' at end of top level let command");
1936 return Error(BraceLoc, "to match this '{'");
1941 // Outside this let scope, this let block is not active.
1942 LetStack.pop_back();
1946 /// ParseMultiClass - Parse a multiclass definition.
1948 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
1949 /// ':' BaseMultiClassList '{' MultiClassDef+ '}'
1951 bool TGParser::ParseMultiClass() {
1952 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1953 Lex.Lex(); // Eat the multiclass token.
1955 if (Lex.getCode() != tgtok::Id)
1956 return TokError("expected identifier after multiclass for name");
1957 std::string Name = Lex.getCurStrVal();
1959 if (MultiClasses.count(Name))
1960 return TokError("multiclass '" + Name + "' already defined");
1962 CurMultiClass = MultiClasses[Name] = new MultiClass(Name,
1963 Lex.getLoc(), Records);
1964 Lex.Lex(); // Eat the identifier.
1966 // If there are template args, parse them.
1967 if (Lex.getCode() == tgtok::less)
1968 if (ParseTemplateArgList(0))
1971 bool inherits = false;
1973 // If there are submulticlasses, parse them.
1974 if (Lex.getCode() == tgtok::colon) {
1979 // Read all of the submulticlasses.
1980 SubMultiClassReference SubMultiClass =
1981 ParseSubMultiClassReference(CurMultiClass);
1984 if (SubMultiClass.MC == 0) return true;
1987 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
1990 if (Lex.getCode() != tgtok::comma) break;
1991 Lex.Lex(); // eat ','.
1992 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
1996 if (Lex.getCode() != tgtok::l_brace) {
1998 return TokError("expected '{' in multiclass definition");
1999 else if (Lex.getCode() != tgtok::semi)
2000 return TokError("expected ';' in multiclass definition");
2002 Lex.Lex(); // eat the ';'.
2004 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2005 return TokError("multiclass must contain at least one def");
2007 while (Lex.getCode() != tgtok::r_brace) {
2008 switch (Lex.getCode()) {
2010 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2014 if (ParseObject(CurMultiClass))
2019 Lex.Lex(); // eat the '}'.
2027 InstantiateMulticlassDef(MultiClass &MC,
2030 SMLoc DefmPrefixLoc) {
2031 // We need to preserve DefProto so it can be reused for later
2032 // instantiations, so create a new Record to inherit from it.
2034 // Add in the defm name. If the defm prefix is empty, give each
2035 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2036 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2039 if (DefmPrefix == 0)
2040 DefmPrefix = StringInit::get(GetNewAnonymousName());
2042 Init *DefName = DefProto->getNameInit();
2044 StringInit *DefNameString = dynamic_cast<StringInit *>(DefName);
2046 if (DefNameString != 0) {
2047 // We have a fully expanded string so there are no operators to
2048 // resolve. We should concatenate the given prefix and name.
2050 BinOpInit::get(BinOpInit::STRCONCAT,
2051 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2052 StringRecTy::get())->Fold(DefProto, &MC),
2053 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2056 Record *CurRec = new Record(DefName, DefmPrefixLoc, Records);
2058 SubClassReference Ref;
2059 Ref.RefLoc = DefmPrefixLoc;
2061 AddSubClass(CurRec, Ref);
2063 if (DefNameString == 0) {
2064 // We must resolve references to NAME.
2065 if (SetValue(CurRec, Ref.RefLoc, "NAME", std::vector<unsigned>(),
2067 Error(DefmPrefixLoc, "Could not resolve "
2068 + CurRec->getNameInitAsString() + ":NAME to '"
2069 + DefmPrefix->getAsUnquotedString() + "'");
2073 RecordVal *DefNameRV = CurRec->getValue("NAME");
2074 CurRec->resolveReferencesTo(DefNameRV);
2077 if (!CurMultiClass) {
2078 // We do this after resolving NAME because before resolution, many
2079 // multiclass defs will have the same name expression. If we are
2080 // currently in a multiclass, it means this defm appears inside a
2081 // multiclass and its name won't be fully resolvable until we see
2082 // the top-level defm. Therefore, we don't add this to the
2083 // RecordKeeper at this point. If we did we could get duplicate
2084 // defs as more than one probably refers to NAME or some other
2085 // common internal placeholder.
2087 // Ensure redefinition doesn't happen.
2088 if (Records.getDef(CurRec->getNameInitAsString())) {
2089 Error(DefmPrefixLoc, "def '" + CurRec->getNameInitAsString() +
2090 "' already defined, instantiating defm with subdef '" +
2091 DefProto->getNameInitAsString() + "'");
2095 Records.addDef(CurRec);
2101 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2103 SMLoc DefmPrefixLoc,
2105 const std::vector<Init *> &TArgs,
2106 std::vector<Init *> &TemplateVals,
2108 // Loop over all of the template arguments, setting them to the specified
2109 // value or leaving them as the default if necessary.
2110 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2111 // Check if a value is specified for this temp-arg.
2112 if (i < TemplateVals.size()) {
2114 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2119 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2123 CurRec->removeValue(TArgs[i]);
2125 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2126 return Error(SubClassLoc, "value not specified for template argument #"+
2127 utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2128 + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2135 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2138 SMLoc DefmPrefixLoc) {
2139 // If the mdef is inside a 'let' expression, add to each def.
2140 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2141 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2142 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2143 LetStack[i][j].Bits, LetStack[i][j].Value))
2144 return Error(DefmPrefixLoc, "when instantiating this defm");
2146 // Don't create a top level definition for defm inside multiclasses,
2147 // instead, only update the prototypes and bind the template args
2148 // with the new created definition.
2149 if (CurMultiClass) {
2150 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2152 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2153 == CurRec->getNameInit())
2154 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2155 "' already defined in this multiclass!");
2156 CurMultiClass->DefPrototypes.push_back(CurRec);
2158 // Copy the template arguments for the multiclass into the new def.
2159 const std::vector<Init *> &TA =
2160 CurMultiClass->Rec.getTemplateArgs();
2162 for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2163 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2164 assert(RV && "Template arg doesn't exist?");
2165 CurRec->addValue(*RV);
2172 /// ParseDefm - Parse the instantiation of a multiclass.
2174 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2176 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2177 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2179 Init *DefmPrefix = 0;
2181 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2182 DefmPrefix = ParseObjectName(CurMultiClass);
2185 SMLoc DefmPrefixLoc = Lex.getLoc();
2186 if (Lex.getCode() != tgtok::colon)
2187 return TokError("expected ':' after defm identifier");
2189 // Keep track of the new generated record definitions.
2190 std::vector<Record*> NewRecDefs;
2192 // This record also inherits from a regular class (non-multiclass)?
2193 bool InheritFromClass = false;
2198 SMLoc SubClassLoc = Lex.getLoc();
2199 SubClassReference Ref = ParseSubClassReference(0, true);
2202 if (Ref.Rec == 0) return true;
2204 // To instantiate a multiclass, we need to first get the multiclass, then
2205 // instantiate each def contained in the multiclass with the SubClassRef
2206 // template parameters.
2207 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
2208 assert(MC && "Didn't lookup multiclass correctly?");
2209 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2211 // Verify that the correct number of template arguments were specified.
2212 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2213 if (TArgs.size() < TemplateVals.size())
2214 return Error(SubClassLoc,
2215 "more template args specified than multiclass expects");
2217 // Loop over all the def's in the multiclass, instantiating each one.
2218 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2219 Record *DefProto = MC->DefPrototypes[i];
2221 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix, DefmPrefixLoc);
2225 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmPrefixLoc, SubClassLoc,
2226 TArgs, TemplateVals, true/*Delete args*/))
2227 return Error(SubClassLoc, "could not instantiate def");
2229 if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmPrefixLoc))
2230 return Error(SubClassLoc, "could not instantiate def");
2232 NewRecDefs.push_back(CurRec);
2236 if (Lex.getCode() != tgtok::comma) break;
2237 Lex.Lex(); // eat ','.
2239 SubClassLoc = Lex.getLoc();
2241 // A defm can inherit from regular classes (non-multiclass) as
2242 // long as they come in the end of the inheritance list.
2243 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != 0);
2245 if (InheritFromClass)
2248 Ref = ParseSubClassReference(0, true);
2251 if (InheritFromClass) {
2252 // Process all the classes to inherit as if they were part of a
2253 // regular 'def' and inherit all record values.
2254 SubClassReference SubClass = ParseSubClassReference(0, false);
2257 if (SubClass.Rec == 0) return true;
2259 // Get the expanded definition prototypes and teach them about
2260 // the record values the current class to inherit has
2261 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2262 Record *CurRec = NewRecDefs[i];
2265 if (AddSubClass(CurRec, SubClass))
2268 // Process any variables on the let stack.
2269 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2270 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2271 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2272 LetStack[i][j].Bits, LetStack[i][j].Value))
2276 if (Lex.getCode() != tgtok::comma) break;
2277 Lex.Lex(); // eat ','.
2278 SubClass = ParseSubClassReference(0, false);
2283 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2284 // See Record::setName(). This resolve step will see any new
2285 // name for the def that might have been created when resolving
2286 // inheritance, values and arguments above.
2287 NewRecDefs[i]->resolveReferences();
2289 if (Lex.getCode() != tgtok::semi)
2290 return TokError("expected ';' at end of defm");
2297 /// Object ::= ClassInst
2298 /// Object ::= DefInst
2299 /// Object ::= MultiClassInst
2300 /// Object ::= DefMInst
2301 /// Object ::= LETCommand '{' ObjectList '}'
2302 /// Object ::= LETCommand Object
2303 bool TGParser::ParseObject(MultiClass *MC) {
2304 switch (Lex.getCode()) {
2306 return TokError("Expected class, def, defm, multiclass or let definition");
2307 case tgtok::Let: return ParseTopLevelLet(MC);
2308 case tgtok::Def: return ParseDef(MC);
2309 case tgtok::Defm: return ParseDefm(MC);
2310 case tgtok::Class: return ParseClass();
2311 case tgtok::MultiClass: return ParseMultiClass();
2316 /// ObjectList :== Object*
2317 bool TGParser::ParseObjectList(MultiClass *MC) {
2318 while (isObjectStart(Lex.getCode())) {
2319 if (ParseObject(MC))
2325 bool TGParser::ParseFile() {
2326 Lex.Lex(); // Prime the lexer.
2327 if (ParseObjectList()) return true;
2329 // If we have unread input at the end of the file, report it.
2330 if (Lex.getCode() == tgtok::Eof)
2333 return TokError("Unexpected input at top level");