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 //===----------------------------------------------------------------------===//
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/Support/Streams.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 cerr << "Multiclass:\n";
52 cerr << "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, const std::string &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 + "' unknown!");
92 // Do not allow assignments like 'X = X'. This will just cause infinite loops
93 // in the resolution machinery.
95 if (VarInit *VI = dynamic_cast<VarInit*>(V))
96 if (VI->getName() == ValName)
99 // If we are assigning to a subset of the bits in the value... then we must be
100 // assigning to a field of BitsRecTy, which must have a BitsInit
103 if (!BitList.empty()) {
104 BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue());
106 return Error(Loc, "Value '" + ValName + "' is not a bits type");
108 // Convert the incoming value to a bits type of the appropriate size...
109 Init *BI = V->convertInitializerTo(new BitsRecTy(BitList.size()));
111 V->convertInitializerTo(new BitsRecTy(BitList.size()));
112 return Error(Loc, "Initializer is not compatible with bit range");
115 // We should have a BitsInit type now.
116 BitsInit *BInit = dynamic_cast<BitsInit*>(BI);
119 BitsInit *NewVal = new BitsInit(CurVal->getNumBits());
121 // Loop over bits, assigning values as appropriate.
122 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
123 unsigned Bit = BitList[i];
124 if (NewVal->getBit(Bit))
125 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
126 ValName + "' more than once");
127 NewVal->setBit(Bit, BInit->getBit(i));
130 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
131 if (NewVal->getBit(i) == 0)
132 NewVal->setBit(i, CurVal->getBit(i));
138 return Error(Loc, "Value '" + ValName + "' of type '" +
139 RV->getType()->getAsString() +
140 "' is incompatible with initializer '" + V->getAsString() +"'");
144 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
145 /// args as SubClass's template arguments.
146 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
147 Record *SC = SubClass.Rec;
148 // Add all of the values in the subclass into the current class.
149 const std::vector<RecordVal> &Vals = SC->getValues();
150 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
151 if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
154 const std::vector<std::string> &TArgs = SC->getTemplateArgs();
156 // Ensure that an appropriate number of template arguments are specified.
157 if (TArgs.size() < SubClass.TemplateArgs.size())
158 return Error(SubClass.RefLoc, "More template args specified than expected");
160 // Loop over all of the template arguments, setting them to the specified
161 // value or leaving them as the default if necessary.
162 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
163 if (i < SubClass.TemplateArgs.size()) {
164 // If a value is specified for this template arg, set it now.
165 if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(),
166 SubClass.TemplateArgs[i]))
170 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
173 CurRec->removeValue(TArgs[i]);
175 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
176 return Error(SubClass.RefLoc,"Value not specified for template argument #"
177 + utostr(i) + " (" + TArgs[i] + ") of subclass '" +
178 SC->getName() + "'!");
182 // Since everything went well, we can now set the "superclass" list for the
184 const std::vector<Record*> &SCs = SC->getSuperClasses();
185 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
186 if (CurRec->isSubClassOf(SCs[i]))
187 return Error(SubClass.RefLoc,
188 "Already subclass of '" + SCs[i]->getName() + "'!\n");
189 CurRec->addSuperClass(SCs[i]);
192 if (CurRec->isSubClassOf(SC))
193 return Error(SubClass.RefLoc,
194 "Already subclass of '" + SC->getName() + "'!\n");
195 CurRec->addSuperClass(SC);
199 /// AddSubMultiClass - Add SubMultiClass as a subclass to
200 /// CurMC, resolving its template args as SubMultiClass's
201 /// template arguments.
202 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
203 SubMultiClassReference &SubMultiClass) {
204 MultiClass *SMC = SubMultiClass.MC;
205 Record *CurRec = &CurMC->Rec;
207 const std::vector<RecordVal> &MCVals = CurRec->getValues();
209 // Add all of the values in the subclass into the current class.
210 const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
211 for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
212 if (AddValue(CurRec, SubMultiClass.RefLoc, SMCVals[i]))
215 int newDefStart = CurMC->DefPrototypes.size();
217 // Add all of the defs in the subclass into the current multiclass.
218 for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
219 iend = SMC->DefPrototypes.end();
222 // Clone the def and add it to the current multiclass
223 Record *NewDef = new Record(**i);
225 // Add all of the values in the superclass into the current def.
226 for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
227 if (AddValue(NewDef, SubMultiClass.RefLoc, MCVals[i]))
230 CurMC->DefPrototypes.push_back(NewDef);
233 const std::vector<std::string> &SMCTArgs = SMC->Rec.getTemplateArgs();
235 // Ensure that an appropriate number of template arguments are
237 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
238 return Error(SubMultiClass.RefLoc,
239 "More template args specified than expected");
241 // Loop over all of the template arguments, setting them to the specified
242 // value or leaving them as the default if necessary.
243 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
244 if (i < SubMultiClass.TemplateArgs.size()) {
245 // If a value is specified for this template arg, set it in the
247 if (SetValue(CurRec, SubMultiClass.RefLoc, SMCTArgs[i],
248 std::vector<unsigned>(),
249 SubMultiClass.TemplateArgs[i]))
253 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
256 CurRec->removeValue(SMCTArgs[i]);
258 // If a value is specified for this template arg, set it in the
260 for (MultiClass::RecordVector::iterator j =
261 CurMC->DefPrototypes.begin() + newDefStart,
262 jend = CurMC->DefPrototypes.end();
267 if (SetValue(Def, SubMultiClass.RefLoc, SMCTArgs[i],
268 std::vector<unsigned>(),
269 SubMultiClass.TemplateArgs[i]))
273 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
276 Def->removeValue(SMCTArgs[i]);
278 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
279 return Error(SubMultiClass.RefLoc,
280 "Value not specified for template argument #"
281 + utostr(i) + " (" + SMCTArgs[i] + ") of subclass '" +
282 SMC->Rec.getName() + "'!");
289 //===----------------------------------------------------------------------===//
291 //===----------------------------------------------------------------------===//
293 /// isObjectStart - Return true if this is a valid first token for an Object.
294 static bool isObjectStart(tgtok::TokKind K) {
295 return K == tgtok::Class || K == tgtok::Def ||
296 K == tgtok::Defm || K == tgtok::Let || K == tgtok::MultiClass;
299 /// ParseObjectName - If an object name is specified, return it. Otherwise,
300 /// return an anonymous name.
301 /// ObjectName ::= ID
302 /// ObjectName ::= /*empty*/
304 std::string TGParser::ParseObjectName() {
305 if (Lex.getCode() == tgtok::Id) {
306 std::string Ret = Lex.getCurStrVal();
311 static unsigned AnonCounter = 0;
312 return "anonymous."+utostr(AnonCounter++);
316 /// ParseClassID - Parse and resolve a reference to a class name. This returns
321 Record *TGParser::ParseClassID() {
322 if (Lex.getCode() != tgtok::Id) {
323 TokError("expected name for ClassID");
327 Record *Result = Records.getClass(Lex.getCurStrVal());
329 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
335 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
336 /// This returns null on error.
338 /// MultiClassID ::= ID
340 MultiClass *TGParser::ParseMultiClassID() {
341 if (Lex.getCode() != tgtok::Id) {
342 TokError("expected name for ClassID");
346 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
348 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
354 Record *TGParser::ParseDefmID() {
355 if (Lex.getCode() != tgtok::Id) {
356 TokError("expected multiclass name");
360 MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
362 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
372 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
373 /// subclass. This returns a SubClassRefTy with a null Record* on error.
375 /// SubClassRef ::= ClassID
376 /// SubClassRef ::= ClassID '<' ValueList '>'
378 SubClassReference TGParser::
379 ParseSubClassReference(Record *CurRec, bool isDefm) {
380 SubClassReference Result;
381 Result.RefLoc = Lex.getLoc();
384 Result.Rec = ParseDefmID();
386 Result.Rec = ParseClassID();
387 if (Result.Rec == 0) return Result;
389 // If there is no template arg list, we're done.
390 if (Lex.getCode() != tgtok::less)
392 Lex.Lex(); // Eat the '<'
394 if (Lex.getCode() == tgtok::greater) {
395 TokError("subclass reference requires a non-empty list of template values");
400 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
401 if (Result.TemplateArgs.empty()) {
402 Result.Rec = 0; // Error parsing value list.
406 if (Lex.getCode() != tgtok::greater) {
407 TokError("expected '>' in template value list");
416 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
417 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
418 /// Record* on error.
420 /// SubMultiClassRef ::= MultiClassID
421 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
423 SubMultiClassReference TGParser::
424 ParseSubMultiClassReference(MultiClass *CurMC) {
425 SubMultiClassReference Result;
426 Result.RefLoc = Lex.getLoc();
428 Result.MC = ParseMultiClassID();
429 if (Result.MC == 0) return Result;
431 // If there is no template arg list, we're done.
432 if (Lex.getCode() != tgtok::less)
434 Lex.Lex(); // Eat the '<'
436 if (Lex.getCode() == tgtok::greater) {
437 TokError("subclass reference requires a non-empty list of template values");
442 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
443 if (Result.TemplateArgs.empty()) {
444 Result.MC = 0; // Error parsing value list.
448 if (Lex.getCode() != tgtok::greater) {
449 TokError("expected '>' in template value list");
458 /// ParseRangePiece - Parse a bit/value range.
459 /// RangePiece ::= INTVAL
460 /// RangePiece ::= INTVAL '-' INTVAL
461 /// RangePiece ::= INTVAL INTVAL
462 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
463 if (Lex.getCode() != tgtok::IntVal) {
464 TokError("expected integer or bitrange");
467 int64_t Start = Lex.getCurIntVal();
471 return TokError("invalid range, cannot be negative");
473 switch (Lex.Lex()) { // eat first character.
475 Ranges.push_back(Start);
478 if (Lex.Lex() != tgtok::IntVal) {
479 TokError("expected integer value as end of range");
482 End = Lex.getCurIntVal();
485 End = -Lex.getCurIntVal();
489 return TokError("invalid range, cannot be negative");
494 for (; Start <= End; ++Start)
495 Ranges.push_back(Start);
497 for (; Start >= End; --Start)
498 Ranges.push_back(Start);
503 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
505 /// RangeList ::= RangePiece (',' RangePiece)*
507 std::vector<unsigned> TGParser::ParseRangeList() {
508 std::vector<unsigned> Result;
510 // Parse the first piece.
511 if (ParseRangePiece(Result))
512 return std::vector<unsigned>();
513 while (Lex.getCode() == tgtok::comma) {
514 Lex.Lex(); // Eat the comma.
516 // Parse the next range piece.
517 if (ParseRangePiece(Result))
518 return std::vector<unsigned>();
523 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
524 /// OptionalRangeList ::= '<' RangeList '>'
525 /// OptionalRangeList ::= /*empty*/
526 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
527 if (Lex.getCode() != tgtok::less)
530 SMLoc StartLoc = Lex.getLoc();
531 Lex.Lex(); // eat the '<'
533 // Parse the range list.
534 Ranges = ParseRangeList();
535 if (Ranges.empty()) return true;
537 if (Lex.getCode() != tgtok::greater) {
538 TokError("expected '>' at end of range list");
539 return Error(StartLoc, "to match this '<'");
541 Lex.Lex(); // eat the '>'.
545 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
546 /// OptionalBitList ::= '{' RangeList '}'
547 /// OptionalBitList ::= /*empty*/
548 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
549 if (Lex.getCode() != tgtok::l_brace)
552 SMLoc StartLoc = Lex.getLoc();
553 Lex.Lex(); // eat the '{'
555 // Parse the range list.
556 Ranges = ParseRangeList();
557 if (Ranges.empty()) return true;
559 if (Lex.getCode() != tgtok::r_brace) {
560 TokError("expected '}' at end of bit list");
561 return Error(StartLoc, "to match this '{'");
563 Lex.Lex(); // eat the '}'.
568 /// ParseType - Parse and return a tblgen type. This returns null on error.
570 /// Type ::= STRING // string type
571 /// Type ::= BIT // bit type
572 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
573 /// Type ::= INT // int type
574 /// Type ::= LIST '<' Type '>' // list<x> type
575 /// Type ::= CODE // code type
576 /// Type ::= DAG // dag type
577 /// Type ::= ClassID // Record Type
579 RecTy *TGParser::ParseType() {
580 switch (Lex.getCode()) {
581 default: TokError("Unknown token when expecting a type"); return 0;
582 case tgtok::String: Lex.Lex(); return new StringRecTy();
583 case tgtok::Bit: Lex.Lex(); return new BitRecTy();
584 case tgtok::Int: Lex.Lex(); return new IntRecTy();
585 case tgtok::Code: Lex.Lex(); return new CodeRecTy();
586 case tgtok::Dag: Lex.Lex(); return new DagRecTy();
588 if (Record *R = ParseClassID()) return new RecordRecTy(R);
591 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
592 TokError("expected '<' after bits type");
595 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
596 TokError("expected integer in bits<n> type");
599 uint64_t Val = Lex.getCurIntVal();
600 if (Lex.Lex() != tgtok::greater) { // Eat count.
601 TokError("expected '>' at end of bits<n> type");
604 Lex.Lex(); // Eat '>'
605 return new BitsRecTy(Val);
608 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
609 TokError("expected '<' after list type");
612 Lex.Lex(); // Eat '<'
613 RecTy *SubType = ParseType();
614 if (SubType == 0) return 0;
616 if (Lex.getCode() != tgtok::greater) {
617 TokError("expected '>' at end of list<ty> type");
620 Lex.Lex(); // Eat '>'
621 return new ListRecTy(SubType);
626 /// ParseIDValue - Parse an ID as a value and decode what it means.
628 /// IDValue ::= ID [def local value]
629 /// IDValue ::= ID [def template arg]
630 /// IDValue ::= ID [multiclass local value]
631 /// IDValue ::= ID [multiclass template argument]
632 /// IDValue ::= ID [def name]
634 Init *TGParser::ParseIDValue(Record *CurRec) {
635 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
636 std::string Name = Lex.getCurStrVal();
637 SMLoc Loc = Lex.getLoc();
639 return ParseIDValue(CurRec, Name, Loc);
642 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
643 /// has already been read.
644 Init *TGParser::ParseIDValue(Record *CurRec,
645 const std::string &Name, SMLoc NameLoc) {
647 if (const RecordVal *RV = CurRec->getValue(Name))
648 return new VarInit(Name, RV->getType());
650 std::string TemplateArgName = CurRec->getName()+":"+Name;
651 if (CurRec->isTemplateArg(TemplateArgName)) {
652 const RecordVal *RV = CurRec->getValue(TemplateArgName);
653 assert(RV && "Template arg doesn't exist??");
654 return new VarInit(TemplateArgName, RV->getType());
659 std::string MCName = CurMultiClass->Rec.getName()+"::"+Name;
660 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
661 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
662 assert(RV && "Template arg doesn't exist??");
663 return new VarInit(MCName, RV->getType());
667 if (Record *D = Records.getDef(Name))
668 return new DefInit(D);
670 Error(NameLoc, "Variable not defined: '" + Name + "'");
674 /// ParseOperation - Parse an operator. This returns null on error.
676 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
678 Init *TGParser::ParseOperation(Record *CurRec) {
679 switch (Lex.getCode()) {
681 TokError("unknown operation");
687 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
688 UnOpInit::UnaryOp Code;
691 switch (Lex.getCode()) {
692 default: assert(0 && "Unhandled code!");
694 Lex.Lex(); // eat the operation
695 Code = UnOpInit::CAST;
697 Type = ParseOperatorType();
700 TokError("did not get type for unary operator");
706 Lex.Lex(); // eat the operation
707 Code = UnOpInit::CAR;
710 Lex.Lex(); // eat the operation
711 Code = UnOpInit::CDR;
714 Lex.Lex(); // eat the operation
715 Code = UnOpInit::LNULL;
719 if (Lex.getCode() != tgtok::l_paren) {
720 TokError("expected '(' after unary operator");
723 Lex.Lex(); // eat the '('
725 Init *LHS = ParseValue(CurRec);
726 if (LHS == 0) return 0;
728 if (Code == UnOpInit::CAR
729 || Code == UnOpInit::CDR
730 || Code == UnOpInit::LNULL) {
731 ListInit *LHSl = dynamic_cast<ListInit*>(LHS);
732 StringInit *LHSs = dynamic_cast<StringInit*>(LHS);
733 TypedInit *LHSt = dynamic_cast<TypedInit*>(LHS);
734 if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
735 TokError("expected list or string type argument in unary operator");
739 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
740 StringRecTy *SType = dynamic_cast<StringRecTy*>(LHSt->getType());
741 if (LType == 0 && SType == 0) {
742 TokError("expected list or string type argumnet in unary operator");
747 if (Code == UnOpInit::CAR
748 || Code == UnOpInit::CDR) {
749 if (LHSl == 0 && LHSt == 0) {
750 TokError("expected list type argumnet in unary operator");
754 if (LHSl && LHSl->getSize() == 0) {
755 TokError("empty list argument in unary operator");
759 Init *Item = LHSl->getElement(0);
760 TypedInit *Itemt = dynamic_cast<TypedInit*>(Item);
762 TokError("untyped list element in unary operator");
765 if (Code == UnOpInit::CAR) {
766 Type = Itemt->getType();
769 Type = new ListRecTy(Itemt->getType());
773 assert(LHSt && "expected list type argument in unary operator");
774 ListRecTy *LType = dynamic_cast<ListRecTy*>(LHSt->getType());
776 TokError("expected list type argumnet in unary operator");
779 if (Code == UnOpInit::CAR) {
780 Type = LType->getElementType();
789 if (Lex.getCode() != tgtok::r_paren) {
790 TokError("expected ')' in unary operator");
793 Lex.Lex(); // eat the ')'
794 return (new UnOpInit(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
801 case tgtok::XStrConcat:
802 case tgtok::XNameConcat: { // Value ::= !binop '(' Value ',' Value ')'
803 BinOpInit::BinaryOp Code;
807 switch (Lex.getCode()) {
808 default: assert(0 && "Unhandled code!");
810 Lex.Lex(); // eat the operation
811 Code = BinOpInit::CONCAT;
812 Type = new DagRecTy();
815 Lex.Lex(); // eat the operation
816 Code = BinOpInit::SRA;
817 Type = new IntRecTy();
820 Lex.Lex(); // eat the operation
821 Code = BinOpInit::SRL;
822 Type = new IntRecTy();
825 Lex.Lex(); // eat the operation
826 Code = BinOpInit::SHL;
827 Type = new IntRecTy();
829 case tgtok::XStrConcat:
830 Lex.Lex(); // eat the operation
831 Code = BinOpInit::STRCONCAT;
832 Type = new StringRecTy();
834 case tgtok::XNameConcat:
835 Lex.Lex(); // eat the operation
836 Code = BinOpInit::NAMECONCAT;
838 Type = ParseOperatorType();
841 TokError("did not get type for binary operator");
847 if (Lex.getCode() != tgtok::l_paren) {
848 TokError("expected '(' after binary operator");
851 Lex.Lex(); // eat the '('
853 Init *LHS = ParseValue(CurRec);
854 if (LHS == 0) return 0;
856 if (Lex.getCode() != tgtok::comma) {
857 TokError("expected ',' in binary operator");
860 Lex.Lex(); // eat the ','
862 Init *RHS = ParseValue(CurRec);
863 if (RHS == 0) return 0;
865 if (Lex.getCode() != tgtok::r_paren) {
866 TokError("expected ')' in binary operator");
869 Lex.Lex(); // eat the ')'
870 return (new BinOpInit(Code, LHS, RHS, Type))->Fold(CurRec, CurMultiClass);
874 case tgtok::XForEach:
875 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
876 TernOpInit::TernaryOp Code;
880 tgtok::TokKind LexCode = Lex.getCode();
881 Lex.Lex(); // eat the operation
883 default: assert(0 && "Unhandled code!");
885 Code = TernOpInit::IF;
887 case tgtok::XForEach:
888 Code = TernOpInit::FOREACH;
891 Code = TernOpInit::SUBST;
894 if (Lex.getCode() != tgtok::l_paren) {
895 TokError("expected '(' after ternary operator");
898 Lex.Lex(); // eat the '('
900 Init *LHS = ParseValue(CurRec);
901 if (LHS == 0) return 0;
903 if (Lex.getCode() != tgtok::comma) {
904 TokError("expected ',' in ternary operator");
907 Lex.Lex(); // eat the ','
909 Init *MHS = ParseValue(CurRec);
910 if (MHS == 0) return 0;
912 if (Lex.getCode() != tgtok::comma) {
913 TokError("expected ',' in ternary operator");
916 Lex.Lex(); // eat the ','
918 Init *RHS = ParseValue(CurRec);
919 if (RHS == 0) return 0;
921 if (Lex.getCode() != tgtok::r_paren) {
922 TokError("expected ')' in binary operator");
925 Lex.Lex(); // eat the ')'
928 default: assert(0 && "Unhandled code!");
930 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
931 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
932 if (MHSt == 0 || RHSt == 0) {
933 TokError("could not get type for !if");
936 if (MHSt->getType()->typeIsConvertibleTo(RHSt->getType())) {
937 Type = RHSt->getType();
939 else if (RHSt->getType()->typeIsConvertibleTo(MHSt->getType())) {
940 Type = MHSt->getType();
943 TokError("inconsistent types for !if");
948 case tgtok::XForEach: {
949 TypedInit *MHSt = dynamic_cast<TypedInit *>(MHS);
951 TokError("could not get type for !foreach");
954 Type = MHSt->getType();
957 case tgtok::XSubst: {
958 TypedInit *RHSt = dynamic_cast<TypedInit *>(RHS);
960 TokError("could not get type for !subst");
963 Type = RHSt->getType();
967 return (new TernOpInit(Code, LHS, MHS, RHS, Type))->Fold(CurRec, CurMultiClass);
970 TokError("could not parse operation");
974 /// ParseOperatorType - Parse a type for an operator. This returns
977 /// OperatorType ::= '<' Type '>'
979 RecTy *TGParser::ParseOperatorType(void) {
982 if (Lex.getCode() != tgtok::less) {
983 TokError("expected type name for operator");
986 Lex.Lex(); // eat the <
991 TokError("expected type name for operator");
995 if (Lex.getCode() != tgtok::greater) {
996 TokError("expected type name for operator");
999 Lex.Lex(); // eat the >
1005 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1007 /// SimpleValue ::= IDValue
1008 /// SimpleValue ::= INTVAL
1009 /// SimpleValue ::= STRVAL+
1010 /// SimpleValue ::= CODEFRAGMENT
1011 /// SimpleValue ::= '?'
1012 /// SimpleValue ::= '{' ValueList '}'
1013 /// SimpleValue ::= ID '<' ValueListNE '>'
1014 /// SimpleValue ::= '[' ValueList ']'
1015 /// SimpleValue ::= '(' IDValue DagArgList ')'
1016 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1017 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1018 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1019 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1020 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1022 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType) {
1024 switch (Lex.getCode()) {
1025 default: TokError("Unknown token when parsing a value"); break;
1026 case tgtok::IntVal: R = new IntInit(Lex.getCurIntVal()); Lex.Lex(); break;
1027 case tgtok::StrVal: {
1028 std::string Val = Lex.getCurStrVal();
1031 // Handle multiple consecutive concatenated strings.
1032 while (Lex.getCode() == tgtok::StrVal) {
1033 Val += Lex.getCurStrVal();
1037 R = new StringInit(Val);
1040 case tgtok::CodeFragment:
1041 R = new CodeInit(Lex.getCurStrVal()); Lex.Lex(); break;
1042 case tgtok::question: R = new UnsetInit(); Lex.Lex(); break;
1044 SMLoc NameLoc = Lex.getLoc();
1045 std::string Name = Lex.getCurStrVal();
1046 if (Lex.Lex() != tgtok::less) // consume the Id.
1047 return ParseIDValue(CurRec, Name, NameLoc); // Value ::= IDValue
1049 // Value ::= ID '<' ValueListNE '>'
1050 if (Lex.Lex() == tgtok::greater) {
1051 TokError("expected non-empty value list");
1055 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1056 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1058 Record *Class = Records.getClass(Name);
1060 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1064 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1065 if (ValueList.empty()) return 0;
1067 if (Lex.getCode() != tgtok::greater) {
1068 TokError("expected '>' at end of value list");
1071 Lex.Lex(); // eat the '>'
1073 // Create the new record, set it as CurRec temporarily.
1074 static unsigned AnonCounter = 0;
1075 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),NameLoc);
1076 SubClassReference SCRef;
1077 SCRef.RefLoc = NameLoc;
1079 SCRef.TemplateArgs = ValueList;
1080 // Add info about the subclass to NewRec.
1081 if (AddSubClass(NewRec, SCRef))
1083 NewRec->resolveReferences();
1084 Records.addDef(NewRec);
1086 // The result of the expression is a reference to the new record.
1087 return new DefInit(NewRec);
1089 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1090 SMLoc BraceLoc = Lex.getLoc();
1091 Lex.Lex(); // eat the '{'
1092 std::vector<Init*> Vals;
1094 if (Lex.getCode() != tgtok::r_brace) {
1095 Vals = ParseValueList(CurRec);
1096 if (Vals.empty()) return 0;
1098 if (Lex.getCode() != tgtok::r_brace) {
1099 TokError("expected '}' at end of bit list value");
1102 Lex.Lex(); // eat the '}'
1104 BitsInit *Result = new BitsInit(Vals.size());
1105 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1106 Init *Bit = Vals[i]->convertInitializerTo(new BitRecTy());
1108 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1109 ") is not convertable to a bit");
1112 Result->setBit(Vals.size()-i-1, Bit);
1116 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1117 Lex.Lex(); // eat the '['
1118 std::vector<Init*> Vals;
1120 RecTy *DeducedEltTy = 0;
1121 ListRecTy *GivenListTy = 0;
1123 if (ItemType != 0) {
1124 ListRecTy *ListType = dynamic_cast<ListRecTy*>(ItemType);
1125 if (ListType == 0) {
1126 std::stringstream s;
1127 s << "Type mismatch for list, expected list type, got "
1128 << ItemType->getAsString();
1131 GivenListTy = ListType;
1134 if (Lex.getCode() != tgtok::r_square) {
1135 Vals = ParseValueList(CurRec, 0, GivenListTy ? GivenListTy->getElementType() : 0);
1136 if (Vals.empty()) return 0;
1138 if (Lex.getCode() != tgtok::r_square) {
1139 TokError("expected ']' at end of list value");
1142 Lex.Lex(); // eat the ']'
1144 RecTy *GivenEltTy = 0;
1145 if (Lex.getCode() == tgtok::less) {
1146 // Optional list element type
1147 Lex.Lex(); // eat the '<'
1149 GivenEltTy = ParseType();
1150 if (GivenEltTy == 0) {
1151 // Couldn't parse element type
1155 if (Lex.getCode() != tgtok::greater) {
1156 TokError("expected '>' at end of list element type");
1159 Lex.Lex(); // eat the '>'
1164 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1167 TypedInit *TArg = dynamic_cast<TypedInit*>(*i);
1169 TokError("Untyped list element");
1173 EltTy = resolveTypes(EltTy, TArg->getType());
1175 TokError("Incompatible types in list elements");
1180 EltTy = TArg->getType();
1184 if (GivenEltTy != 0) {
1186 // Verify consistency
1187 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1188 TokError("Incompatible types in list elements");
1196 if (ItemType == 0) {
1197 TokError("No type for list");
1200 DeducedEltTy = GivenListTy->getElementType();
1203 // Make sure the deduced type is compatible with the given type
1205 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1206 TokError("Element type mismatch for list");
1210 DeducedEltTy = EltTy;
1213 return new ListInit(Vals, DeducedEltTy);
1215 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1216 Lex.Lex(); // eat the '('
1217 if (Lex.getCode() != tgtok::Id
1218 && Lex.getCode() != tgtok::XCast
1219 && Lex.getCode() != tgtok::XNameConcat) {
1220 TokError("expected identifier in dag init");
1225 if (Lex.getCode() == tgtok::Id) {
1226 Operator = ParseIDValue(CurRec);
1227 if (Operator == 0) return 0;
1230 Operator = ParseOperation(CurRec);
1231 if (Operator == 0) return 0;
1234 // If the operator name is present, parse it.
1235 std::string OperatorName;
1236 if (Lex.getCode() == tgtok::colon) {
1237 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1238 TokError("expected variable name in dag operator");
1241 OperatorName = Lex.getCurStrVal();
1242 Lex.Lex(); // eat the VarName.
1245 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1246 if (Lex.getCode() != tgtok::r_paren) {
1247 DagArgs = ParseDagArgList(CurRec);
1248 if (DagArgs.empty()) return 0;
1251 if (Lex.getCode() != tgtok::r_paren) {
1252 TokError("expected ')' in dag init");
1255 Lex.Lex(); // eat the ')'
1257 return new DagInit(Operator, OperatorName, DagArgs);
1264 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1265 case tgtok::XConcat:
1269 case tgtok::XStrConcat:
1270 case tgtok::XNameConcat: // Value ::= !binop '(' Value ',' Value ')'
1272 case tgtok::XForEach:
1273 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1274 return ParseOperation(CurRec);
1282 /// ParseValue - Parse a tblgen value. This returns null on error.
1284 /// Value ::= SimpleValue ValueSuffix*
1285 /// ValueSuffix ::= '{' BitList '}'
1286 /// ValueSuffix ::= '[' BitList ']'
1287 /// ValueSuffix ::= '.' ID
1289 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType) {
1290 Init *Result = ParseSimpleValue(CurRec, ItemType);
1291 if (Result == 0) return 0;
1293 // Parse the suffixes now if present.
1295 switch (Lex.getCode()) {
1296 default: return Result;
1297 case tgtok::l_brace: {
1298 SMLoc CurlyLoc = Lex.getLoc();
1299 Lex.Lex(); // eat the '{'
1300 std::vector<unsigned> Ranges = ParseRangeList();
1301 if (Ranges.empty()) return 0;
1303 // Reverse the bitlist.
1304 std::reverse(Ranges.begin(), Ranges.end());
1305 Result = Result->convertInitializerBitRange(Ranges);
1307 Error(CurlyLoc, "Invalid bit range for value");
1312 if (Lex.getCode() != tgtok::r_brace) {
1313 TokError("expected '}' at end of bit range list");
1319 case tgtok::l_square: {
1320 SMLoc SquareLoc = Lex.getLoc();
1321 Lex.Lex(); // eat the '['
1322 std::vector<unsigned> Ranges = ParseRangeList();
1323 if (Ranges.empty()) return 0;
1325 Result = Result->convertInitListSlice(Ranges);
1327 Error(SquareLoc, "Invalid range for list slice");
1332 if (Lex.getCode() != tgtok::r_square) {
1333 TokError("expected ']' at end of list slice");
1340 if (Lex.Lex() != tgtok::Id) { // eat the .
1341 TokError("expected field identifier after '.'");
1344 if (!Result->getFieldType(Lex.getCurStrVal())) {
1345 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1346 Result->getAsString() + "'");
1349 Result = new FieldInit(Result, Lex.getCurStrVal());
1350 Lex.Lex(); // eat field name
1356 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1358 /// ParseDagArgList ::= Value (':' VARNAME)?
1359 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1360 std::vector<std::pair<llvm::Init*, std::string> >
1361 TGParser::ParseDagArgList(Record *CurRec) {
1362 std::vector<std::pair<llvm::Init*, std::string> > Result;
1365 Init *Val = ParseValue(CurRec);
1366 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1368 // If the variable name is present, add it.
1369 std::string VarName;
1370 if (Lex.getCode() == tgtok::colon) {
1371 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1372 TokError("expected variable name in dag literal");
1373 return std::vector<std::pair<llvm::Init*, std::string> >();
1375 VarName = Lex.getCurStrVal();
1376 Lex.Lex(); // eat the VarName.
1379 Result.push_back(std::make_pair(Val, VarName));
1381 if (Lex.getCode() != tgtok::comma) break;
1382 Lex.Lex(); // eat the ','
1389 /// ParseValueList - Parse a comma separated list of values, returning them as a
1390 /// vector. Note that this always expects to be able to parse at least one
1391 /// value. It returns an empty list if this is not possible.
1393 /// ValueList ::= Value (',' Value)
1395 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec, RecTy *EltTy) {
1396 std::vector<Init*> Result;
1397 RecTy *ItemType = EltTy;
1399 if (ArgsRec != 0 && EltTy == 0) {
1400 const std::vector<std::string> &TArgs = ArgsRec->getTemplateArgs();
1401 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1402 assert(RV && "Template argument record not found??");
1403 ItemType = RV->getType();
1406 Result.push_back(ParseValue(CurRec, ItemType));
1407 if (Result.back() == 0) return std::vector<Init*>();
1409 while (Lex.getCode() == tgtok::comma) {
1410 Lex.Lex(); // Eat the comma
1412 if (ArgsRec != 0 && EltTy == 0) {
1413 const std::vector<std::string> &TArgs = ArgsRec->getTemplateArgs();
1414 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1415 assert(RV && "Template argument record not found??");
1416 ItemType = RV->getType();
1419 Result.push_back(ParseValue(CurRec, ItemType));
1420 if (Result.back() == 0) return std::vector<Init*>();
1428 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1429 /// empty string on error. This can happen in a number of different context's,
1430 /// including within a def or in the template args for a def (which which case
1431 /// CurRec will be non-null) and within the template args for a multiclass (in
1432 /// which case CurRec will be null, but CurMultiClass will be set). This can
1433 /// also happen within a def that is within a multiclass, which will set both
1434 /// CurRec and CurMultiClass.
1436 /// Declaration ::= FIELD? Type ID ('=' Value)?
1438 std::string TGParser::ParseDeclaration(Record *CurRec,
1439 bool ParsingTemplateArgs) {
1440 // Read the field prefix if present.
1441 bool HasField = Lex.getCode() == tgtok::Field;
1442 if (HasField) Lex.Lex();
1444 RecTy *Type = ParseType();
1445 if (Type == 0) return "";
1447 if (Lex.getCode() != tgtok::Id) {
1448 TokError("Expected identifier in declaration");
1452 SMLoc IdLoc = Lex.getLoc();
1453 std::string DeclName = Lex.getCurStrVal();
1456 if (ParsingTemplateArgs) {
1458 DeclName = CurRec->getName() + ":" + DeclName;
1460 assert(CurMultiClass);
1463 DeclName = CurMultiClass->Rec.getName() + "::" + DeclName;
1467 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1470 // If a value is present, parse it.
1471 if (Lex.getCode() == tgtok::equal) {
1473 SMLoc ValLoc = Lex.getLoc();
1474 Init *Val = ParseValue(CurRec, Type);
1476 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1483 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1484 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1485 /// template args for a def, which may or may not be in a multiclass. If null,
1486 /// these are the template args for a multiclass.
1488 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1490 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1491 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1492 Lex.Lex(); // eat the '<'
1494 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1496 // Read the first declaration.
1497 std::string TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1498 if (TemplArg.empty())
1501 TheRecToAddTo->addTemplateArg(TemplArg);
1503 while (Lex.getCode() == tgtok::comma) {
1504 Lex.Lex(); // eat the ','
1506 // Read the following declarations.
1507 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1508 if (TemplArg.empty())
1510 TheRecToAddTo->addTemplateArg(TemplArg);
1513 if (Lex.getCode() != tgtok::greater)
1514 return TokError("expected '>' at end of template argument list");
1515 Lex.Lex(); // eat the '>'.
1520 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1522 /// BodyItem ::= Declaration ';'
1523 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1524 bool TGParser::ParseBodyItem(Record *CurRec) {
1525 if (Lex.getCode() != tgtok::Let) {
1526 if (ParseDeclaration(CurRec, false).empty())
1529 if (Lex.getCode() != tgtok::semi)
1530 return TokError("expected ';' after declaration");
1535 // LET ID OptionalRangeList '=' Value ';'
1536 if (Lex.Lex() != tgtok::Id)
1537 return TokError("expected field identifier after let");
1539 SMLoc IdLoc = Lex.getLoc();
1540 std::string FieldName = Lex.getCurStrVal();
1541 Lex.Lex(); // eat the field name.
1543 std::vector<unsigned> BitList;
1544 if (ParseOptionalBitList(BitList))
1546 std::reverse(BitList.begin(), BitList.end());
1548 if (Lex.getCode() != tgtok::equal)
1549 return TokError("expected '=' in let expression");
1550 Lex.Lex(); // eat the '='.
1552 RecordVal *Field = CurRec->getValue(FieldName);
1554 return TokError("Value '" + FieldName + "' unknown!");
1556 RecTy *Type = Field->getType();
1558 Init *Val = ParseValue(CurRec, Type);
1559 if (Val == 0) return true;
1561 if (Lex.getCode() != tgtok::semi)
1562 return TokError("expected ';' after let expression");
1565 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1568 /// ParseBody - Read the body of a class or def. Return true on error, false on
1572 /// Body ::= '{' BodyList '}'
1573 /// BodyList BodyItem*
1575 bool TGParser::ParseBody(Record *CurRec) {
1576 // If this is a null definition, just eat the semi and return.
1577 if (Lex.getCode() == tgtok::semi) {
1582 if (Lex.getCode() != tgtok::l_brace)
1583 return TokError("Expected ';' or '{' to start body");
1587 while (Lex.getCode() != tgtok::r_brace)
1588 if (ParseBodyItem(CurRec))
1596 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1597 /// optional ClassList followed by a Body. CurRec is the current def or class
1598 /// that is being parsed.
1600 /// ObjectBody ::= BaseClassList Body
1601 /// BaseClassList ::= /*empty*/
1602 /// BaseClassList ::= ':' BaseClassListNE
1603 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1605 bool TGParser::ParseObjectBody(Record *CurRec) {
1606 // If there is a baseclass list, read it.
1607 if (Lex.getCode() == tgtok::colon) {
1610 // Read all of the subclasses.
1611 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1614 if (SubClass.Rec == 0) return true;
1617 if (AddSubClass(CurRec, SubClass))
1620 if (Lex.getCode() != tgtok::comma) break;
1621 Lex.Lex(); // eat ','.
1622 SubClass = ParseSubClassReference(CurRec, false);
1626 // Process any variables on the let stack.
1627 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1628 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1629 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1630 LetStack[i][j].Bits, LetStack[i][j].Value))
1633 return ParseBody(CurRec);
1637 /// ParseDef - Parse and return a top level or multiclass def, return the record
1638 /// corresponding to it. This returns null on error.
1640 /// DefInst ::= DEF ObjectName ObjectBody
1642 llvm::Record *TGParser::ParseDef(MultiClass *CurMultiClass) {
1643 SMLoc DefLoc = Lex.getLoc();
1644 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1645 Lex.Lex(); // Eat the 'def' token.
1647 // Parse ObjectName and make a record for it.
1648 Record *CurRec = new Record(ParseObjectName(), DefLoc);
1650 if (!CurMultiClass) {
1651 // Top-level def definition.
1653 // Ensure redefinition doesn't happen.
1654 if (Records.getDef(CurRec->getName())) {
1655 Error(DefLoc, "def '" + CurRec->getName() + "' already defined");
1658 Records.addDef(CurRec);
1660 // Otherwise, a def inside a multiclass, add it to the multiclass.
1661 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1662 if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
1663 Error(DefLoc, "def '" + CurRec->getName() +
1664 "' already defined in this multiclass!");
1667 CurMultiClass->DefPrototypes.push_back(CurRec);
1670 if (ParseObjectBody(CurRec))
1673 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1674 CurRec->resolveReferences();
1676 // If ObjectBody has template arguments, it's an error.
1677 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1682 /// ParseClass - Parse a tblgen class definition.
1684 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1686 bool TGParser::ParseClass() {
1687 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1690 if (Lex.getCode() != tgtok::Id)
1691 return TokError("expected class name after 'class' keyword");
1693 Record *CurRec = Records.getClass(Lex.getCurStrVal());
1695 // If the body was previously defined, this is an error.
1696 if (!CurRec->getValues().empty() ||
1697 !CurRec->getSuperClasses().empty() ||
1698 !CurRec->getTemplateArgs().empty())
1699 return TokError("Class '" + CurRec->getName() + "' already defined");
1701 // If this is the first reference to this class, create and add it.
1702 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc());
1703 Records.addClass(CurRec);
1705 Lex.Lex(); // eat the name.
1707 // If there are template args, parse them.
1708 if (Lex.getCode() == tgtok::less)
1709 if (ParseTemplateArgList(CurRec))
1712 // Finally, parse the object body.
1713 return ParseObjectBody(CurRec);
1716 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
1719 /// LetList ::= LetItem (',' LetItem)*
1720 /// LetItem ::= ID OptionalRangeList '=' Value
1722 std::vector<LetRecord> TGParser::ParseLetList() {
1723 std::vector<LetRecord> Result;
1726 if (Lex.getCode() != tgtok::Id) {
1727 TokError("expected identifier in let definition");
1728 return std::vector<LetRecord>();
1730 std::string Name = Lex.getCurStrVal();
1731 SMLoc NameLoc = Lex.getLoc();
1732 Lex.Lex(); // Eat the identifier.
1734 // Check for an optional RangeList.
1735 std::vector<unsigned> Bits;
1736 if (ParseOptionalRangeList(Bits))
1737 return std::vector<LetRecord>();
1738 std::reverse(Bits.begin(), Bits.end());
1740 if (Lex.getCode() != tgtok::equal) {
1741 TokError("expected '=' in let expression");
1742 return std::vector<LetRecord>();
1744 Lex.Lex(); // eat the '='.
1746 Init *Val = ParseValue(0);
1747 if (Val == 0) return std::vector<LetRecord>();
1749 // Now that we have everything, add the record.
1750 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1752 if (Lex.getCode() != tgtok::comma)
1754 Lex.Lex(); // eat the comma.
1758 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
1759 /// different related productions.
1761 /// Object ::= LET LetList IN '{' ObjectList '}'
1762 /// Object ::= LET LetList IN Object
1764 bool TGParser::ParseTopLevelLet() {
1765 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1768 // Add this entry to the let stack.
1769 std::vector<LetRecord> LetInfo = ParseLetList();
1770 if (LetInfo.empty()) return true;
1771 LetStack.push_back(LetInfo);
1773 if (Lex.getCode() != tgtok::In)
1774 return TokError("expected 'in' at end of top-level 'let'");
1777 // If this is a scalar let, just handle it now
1778 if (Lex.getCode() != tgtok::l_brace) {
1779 // LET LetList IN Object
1782 } else { // Object ::= LETCommand '{' ObjectList '}'
1783 SMLoc BraceLoc = Lex.getLoc();
1784 // Otherwise, this is a group let.
1785 Lex.Lex(); // eat the '{'.
1787 // Parse the object list.
1788 if (ParseObjectList())
1791 if (Lex.getCode() != tgtok::r_brace) {
1792 TokError("expected '}' at end of top level let command");
1793 return Error(BraceLoc, "to match this '{'");
1798 // Outside this let scope, this let block is not active.
1799 LetStack.pop_back();
1803 /// ParseMultiClassDef - Parse a def in a multiclass context.
1805 /// MultiClassDef ::= DefInst
1807 bool TGParser::ParseMultiClassDef(MultiClass *CurMC) {
1808 if (Lex.getCode() != tgtok::Def)
1809 return TokError("expected 'def' in multiclass body");
1811 Record *D = ParseDef(CurMC);
1812 if (D == 0) return true;
1814 // Copy the template arguments for the multiclass into the def.
1815 const std::vector<std::string> &TArgs = CurMC->Rec.getTemplateArgs();
1817 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1818 const RecordVal *RV = CurMC->Rec.getValue(TArgs[i]);
1819 assert(RV && "Template arg doesn't exist?");
1826 /// ParseMultiClass - Parse a multiclass definition.
1828 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
1829 /// ':' BaseMultiClassList '{' MultiClassDef+ '}'
1831 bool TGParser::ParseMultiClass() {
1832 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1833 Lex.Lex(); // Eat the multiclass token.
1835 if (Lex.getCode() != tgtok::Id)
1836 return TokError("expected identifier after multiclass for name");
1837 std::string Name = Lex.getCurStrVal();
1839 if (MultiClasses.count(Name))
1840 return TokError("multiclass '" + Name + "' already defined");
1842 CurMultiClass = MultiClasses[Name] = new MultiClass(Name, Lex.getLoc());
1843 Lex.Lex(); // Eat the identifier.
1845 // If there are template args, parse them.
1846 if (Lex.getCode() == tgtok::less)
1847 if (ParseTemplateArgList(0))
1850 bool inherits = false;
1852 // If there are submulticlasses, parse them.
1853 if (Lex.getCode() == tgtok::colon) {
1858 // Read all of the submulticlasses.
1859 SubMultiClassReference SubMultiClass =
1860 ParseSubMultiClassReference(CurMultiClass);
1863 if (SubMultiClass.MC == 0) return true;
1866 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
1869 if (Lex.getCode() != tgtok::comma) break;
1870 Lex.Lex(); // eat ','.
1871 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
1875 if (Lex.getCode() != tgtok::l_brace) {
1877 return TokError("expected '{' in multiclass definition");
1879 if (Lex.getCode() != tgtok::semi)
1880 return TokError("expected ';' in multiclass definition");
1882 Lex.Lex(); // eat the ';'.
1885 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
1886 return TokError("multiclass must contain at least one def");
1888 while (Lex.getCode() != tgtok::r_brace)
1889 if (ParseMultiClassDef(CurMultiClass))
1892 Lex.Lex(); // eat the '}'.
1899 /// ParseDefm - Parse the instantiation of a multiclass.
1901 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
1903 bool TGParser::ParseDefm() {
1904 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
1905 if (Lex.Lex() != tgtok::Id) // eat the defm.
1906 return TokError("expected identifier after defm");
1908 SMLoc DefmPrefixLoc = Lex.getLoc();
1909 std::string DefmPrefix = Lex.getCurStrVal();
1910 if (Lex.Lex() != tgtok::colon)
1911 return TokError("expected ':' after defm identifier");
1916 SMLoc SubClassLoc = Lex.getLoc();
1917 SubClassReference Ref = ParseSubClassReference(0, true);
1920 if (Ref.Rec == 0) return true;
1922 // To instantiate a multiclass, we need to first get the multiclass, then
1923 // instantiate each def contained in the multiclass with the SubClassRef
1924 // template parameters.
1925 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
1926 assert(MC && "Didn't lookup multiclass correctly?");
1927 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
1929 // Verify that the correct number of template arguments were specified.
1930 const std::vector<std::string> &TArgs = MC->Rec.getTemplateArgs();
1931 if (TArgs.size() < TemplateVals.size())
1932 return Error(SubClassLoc,
1933 "more template args specified than multiclass expects");
1935 // Loop over all the def's in the multiclass, instantiating each one.
1936 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
1937 Record *DefProto = MC->DefPrototypes[i];
1939 // Add in the defm name
1940 std::string DefName = DefProto->getName();
1941 std::string::size_type idx = DefName.find("#NAME#");
1942 if (idx != std::string::npos) {
1943 DefName.replace(idx, 6, DefmPrefix);
1946 // Add the suffix to the defm name to get the new name.
1947 DefName = DefmPrefix + DefName;
1950 Record *CurRec = new Record(DefName, DefmPrefixLoc);
1952 SubClassReference Ref;
1953 Ref.RefLoc = DefmPrefixLoc;
1955 AddSubClass(CurRec, Ref);
1957 // Loop over all of the template arguments, setting them to the specified
1958 // value or leaving them as the default if necessary.
1959 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1960 // Check if a value is specified for this temp-arg.
1961 if (i < TemplateVals.size()) {
1963 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
1968 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
1971 CurRec->removeValue(TArgs[i]);
1973 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
1974 return Error(SubClassLoc,
1975 "value not specified for template argument #"+
1976 utostr(i) + " (" + TArgs[i] + ") of multiclassclass '" +
1977 MC->Rec.getName() + "'");
1981 // If the mdef is inside a 'let' expression, add to each def.
1982 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1983 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1984 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1985 LetStack[i][j].Bits, LetStack[i][j].Value)) {
1986 Error(DefmPrefixLoc, "when instantiating this defm");
1990 // Ensure redefinition doesn't happen.
1991 if (Records.getDef(CurRec->getName()))
1992 return Error(DefmPrefixLoc, "def '" + CurRec->getName() +
1993 "' already defined, instantiating defm with subdef '" +
1994 DefProto->getName() + "'");
1995 Records.addDef(CurRec);
1996 CurRec->resolveReferences();
1999 if (Lex.getCode() != tgtok::comma) break;
2000 Lex.Lex(); // eat ','.
2002 SubClassLoc = Lex.getLoc();
2003 Ref = ParseSubClassReference(0, true);
2006 if (Lex.getCode() != tgtok::semi)
2007 return TokError("expected ';' at end of defm");
2014 /// Object ::= ClassInst
2015 /// Object ::= DefInst
2016 /// Object ::= MultiClassInst
2017 /// Object ::= DefMInst
2018 /// Object ::= LETCommand '{' ObjectList '}'
2019 /// Object ::= LETCommand Object
2020 bool TGParser::ParseObject() {
2021 switch (Lex.getCode()) {
2022 default: assert(0 && "This is not an object");
2023 case tgtok::Let: return ParseTopLevelLet();
2024 case tgtok::Def: return ParseDef(0) == 0;
2025 case tgtok::Defm: return ParseDefm();
2026 case tgtok::Class: return ParseClass();
2027 case tgtok::MultiClass: return ParseMultiClass();
2032 /// ObjectList :== Object*
2033 bool TGParser::ParseObjectList() {
2034 while (isObjectStart(Lex.getCode())) {
2042 bool TGParser::ParseFile() {
2043 Lex.Lex(); // Prime the lexer.
2044 if (ParseObjectList()) return true;
2046 // If we have unread input at the end of the file, report it.
2047 if (Lex.getCode() == tgtok::Eof)
2050 return TokError("Unexpected input at top level");