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;
1398 unsigned int ArgN = 0;
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 if (ArgN >= TArgs.size()) {
1415 TokError("too many template arguments");
1416 return std::vector<Init*>();
1418 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1419 assert(RV && "Template argument record not found??");
1420 ItemType = RV->getType();
1423 Result.push_back(ParseValue(CurRec, ItemType));
1424 if (Result.back() == 0) return std::vector<Init*>();
1432 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1433 /// empty string on error. This can happen in a number of different context's,
1434 /// including within a def or in the template args for a def (which which case
1435 /// CurRec will be non-null) and within the template args for a multiclass (in
1436 /// which case CurRec will be null, but CurMultiClass will be set). This can
1437 /// also happen within a def that is within a multiclass, which will set both
1438 /// CurRec and CurMultiClass.
1440 /// Declaration ::= FIELD? Type ID ('=' Value)?
1442 std::string TGParser::ParseDeclaration(Record *CurRec,
1443 bool ParsingTemplateArgs) {
1444 // Read the field prefix if present.
1445 bool HasField = Lex.getCode() == tgtok::Field;
1446 if (HasField) Lex.Lex();
1448 RecTy *Type = ParseType();
1449 if (Type == 0) return "";
1451 if (Lex.getCode() != tgtok::Id) {
1452 TokError("Expected identifier in declaration");
1456 SMLoc IdLoc = Lex.getLoc();
1457 std::string DeclName = Lex.getCurStrVal();
1460 if (ParsingTemplateArgs) {
1462 DeclName = CurRec->getName() + ":" + DeclName;
1464 assert(CurMultiClass);
1467 DeclName = CurMultiClass->Rec.getName() + "::" + DeclName;
1471 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1474 // If a value is present, parse it.
1475 if (Lex.getCode() == tgtok::equal) {
1477 SMLoc ValLoc = Lex.getLoc();
1478 Init *Val = ParseValue(CurRec, Type);
1480 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1487 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1488 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1489 /// template args for a def, which may or may not be in a multiclass. If null,
1490 /// these are the template args for a multiclass.
1492 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1494 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1495 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1496 Lex.Lex(); // eat the '<'
1498 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1500 // Read the first declaration.
1501 std::string TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1502 if (TemplArg.empty())
1505 TheRecToAddTo->addTemplateArg(TemplArg);
1507 while (Lex.getCode() == tgtok::comma) {
1508 Lex.Lex(); // eat the ','
1510 // Read the following declarations.
1511 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1512 if (TemplArg.empty())
1514 TheRecToAddTo->addTemplateArg(TemplArg);
1517 if (Lex.getCode() != tgtok::greater)
1518 return TokError("expected '>' at end of template argument list");
1519 Lex.Lex(); // eat the '>'.
1524 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1526 /// BodyItem ::= Declaration ';'
1527 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1528 bool TGParser::ParseBodyItem(Record *CurRec) {
1529 if (Lex.getCode() != tgtok::Let) {
1530 if (ParseDeclaration(CurRec, false).empty())
1533 if (Lex.getCode() != tgtok::semi)
1534 return TokError("expected ';' after declaration");
1539 // LET ID OptionalRangeList '=' Value ';'
1540 if (Lex.Lex() != tgtok::Id)
1541 return TokError("expected field identifier after let");
1543 SMLoc IdLoc = Lex.getLoc();
1544 std::string FieldName = Lex.getCurStrVal();
1545 Lex.Lex(); // eat the field name.
1547 std::vector<unsigned> BitList;
1548 if (ParseOptionalBitList(BitList))
1550 std::reverse(BitList.begin(), BitList.end());
1552 if (Lex.getCode() != tgtok::equal)
1553 return TokError("expected '=' in let expression");
1554 Lex.Lex(); // eat the '='.
1556 RecordVal *Field = CurRec->getValue(FieldName);
1558 return TokError("Value '" + FieldName + "' unknown!");
1560 RecTy *Type = Field->getType();
1562 Init *Val = ParseValue(CurRec, Type);
1563 if (Val == 0) return true;
1565 if (Lex.getCode() != tgtok::semi)
1566 return TokError("expected ';' after let expression");
1569 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1572 /// ParseBody - Read the body of a class or def. Return true on error, false on
1576 /// Body ::= '{' BodyList '}'
1577 /// BodyList BodyItem*
1579 bool TGParser::ParseBody(Record *CurRec) {
1580 // If this is a null definition, just eat the semi and return.
1581 if (Lex.getCode() == tgtok::semi) {
1586 if (Lex.getCode() != tgtok::l_brace)
1587 return TokError("Expected ';' or '{' to start body");
1591 while (Lex.getCode() != tgtok::r_brace)
1592 if (ParseBodyItem(CurRec))
1600 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1601 /// optional ClassList followed by a Body. CurRec is the current def or class
1602 /// that is being parsed.
1604 /// ObjectBody ::= BaseClassList Body
1605 /// BaseClassList ::= /*empty*/
1606 /// BaseClassList ::= ':' BaseClassListNE
1607 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1609 bool TGParser::ParseObjectBody(Record *CurRec) {
1610 // If there is a baseclass list, read it.
1611 if (Lex.getCode() == tgtok::colon) {
1614 // Read all of the subclasses.
1615 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1618 if (SubClass.Rec == 0) return true;
1621 if (AddSubClass(CurRec, SubClass))
1624 if (Lex.getCode() != tgtok::comma) break;
1625 Lex.Lex(); // eat ','.
1626 SubClass = ParseSubClassReference(CurRec, false);
1630 // Process any variables on the let stack.
1631 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1632 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1633 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1634 LetStack[i][j].Bits, LetStack[i][j].Value))
1637 return ParseBody(CurRec);
1641 /// ParseDef - Parse and return a top level or multiclass def, return the record
1642 /// corresponding to it. This returns null on error.
1644 /// DefInst ::= DEF ObjectName ObjectBody
1646 llvm::Record *TGParser::ParseDef(MultiClass *CurMultiClass) {
1647 SMLoc DefLoc = Lex.getLoc();
1648 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1649 Lex.Lex(); // Eat the 'def' token.
1651 // Parse ObjectName and make a record for it.
1652 Record *CurRec = new Record(ParseObjectName(), DefLoc);
1654 if (!CurMultiClass) {
1655 // Top-level def definition.
1657 // Ensure redefinition doesn't happen.
1658 if (Records.getDef(CurRec->getName())) {
1659 Error(DefLoc, "def '" + CurRec->getName() + "' already defined");
1662 Records.addDef(CurRec);
1664 // Otherwise, a def inside a multiclass, add it to the multiclass.
1665 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1666 if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
1667 Error(DefLoc, "def '" + CurRec->getName() +
1668 "' already defined in this multiclass!");
1671 CurMultiClass->DefPrototypes.push_back(CurRec);
1674 if (ParseObjectBody(CurRec))
1677 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1678 CurRec->resolveReferences();
1680 // If ObjectBody has template arguments, it's an error.
1681 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1686 /// ParseClass - Parse a tblgen class definition.
1688 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1690 bool TGParser::ParseClass() {
1691 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1694 if (Lex.getCode() != tgtok::Id)
1695 return TokError("expected class name after 'class' keyword");
1697 Record *CurRec = Records.getClass(Lex.getCurStrVal());
1699 // If the body was previously defined, this is an error.
1700 if (!CurRec->getValues().empty() ||
1701 !CurRec->getSuperClasses().empty() ||
1702 !CurRec->getTemplateArgs().empty())
1703 return TokError("Class '" + CurRec->getName() + "' already defined");
1705 // If this is the first reference to this class, create and add it.
1706 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc());
1707 Records.addClass(CurRec);
1709 Lex.Lex(); // eat the name.
1711 // If there are template args, parse them.
1712 if (Lex.getCode() == tgtok::less)
1713 if (ParseTemplateArgList(CurRec))
1716 // Finally, parse the object body.
1717 return ParseObjectBody(CurRec);
1720 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
1723 /// LetList ::= LetItem (',' LetItem)*
1724 /// LetItem ::= ID OptionalRangeList '=' Value
1726 std::vector<LetRecord> TGParser::ParseLetList() {
1727 std::vector<LetRecord> Result;
1730 if (Lex.getCode() != tgtok::Id) {
1731 TokError("expected identifier in let definition");
1732 return std::vector<LetRecord>();
1734 std::string Name = Lex.getCurStrVal();
1735 SMLoc NameLoc = Lex.getLoc();
1736 Lex.Lex(); // Eat the identifier.
1738 // Check for an optional RangeList.
1739 std::vector<unsigned> Bits;
1740 if (ParseOptionalRangeList(Bits))
1741 return std::vector<LetRecord>();
1742 std::reverse(Bits.begin(), Bits.end());
1744 if (Lex.getCode() != tgtok::equal) {
1745 TokError("expected '=' in let expression");
1746 return std::vector<LetRecord>();
1748 Lex.Lex(); // eat the '='.
1750 Init *Val = ParseValue(0);
1751 if (Val == 0) return std::vector<LetRecord>();
1753 // Now that we have everything, add the record.
1754 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1756 if (Lex.getCode() != tgtok::comma)
1758 Lex.Lex(); // eat the comma.
1762 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
1763 /// different related productions.
1765 /// Object ::= LET LetList IN '{' ObjectList '}'
1766 /// Object ::= LET LetList IN Object
1768 bool TGParser::ParseTopLevelLet() {
1769 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1772 // Add this entry to the let stack.
1773 std::vector<LetRecord> LetInfo = ParseLetList();
1774 if (LetInfo.empty()) return true;
1775 LetStack.push_back(LetInfo);
1777 if (Lex.getCode() != tgtok::In)
1778 return TokError("expected 'in' at end of top-level 'let'");
1781 // If this is a scalar let, just handle it now
1782 if (Lex.getCode() != tgtok::l_brace) {
1783 // LET LetList IN Object
1786 } else { // Object ::= LETCommand '{' ObjectList '}'
1787 SMLoc BraceLoc = Lex.getLoc();
1788 // Otherwise, this is a group let.
1789 Lex.Lex(); // eat the '{'.
1791 // Parse the object list.
1792 if (ParseObjectList())
1795 if (Lex.getCode() != tgtok::r_brace) {
1796 TokError("expected '}' at end of top level let command");
1797 return Error(BraceLoc, "to match this '{'");
1802 // Outside this let scope, this let block is not active.
1803 LetStack.pop_back();
1807 /// ParseMultiClassDef - Parse a def in a multiclass context.
1809 /// MultiClassDef ::= DefInst
1811 bool TGParser::ParseMultiClassDef(MultiClass *CurMC) {
1812 if (Lex.getCode() != tgtok::Def)
1813 return TokError("expected 'def' in multiclass body");
1815 Record *D = ParseDef(CurMC);
1816 if (D == 0) return true;
1818 // Copy the template arguments for the multiclass into the def.
1819 const std::vector<std::string> &TArgs = CurMC->Rec.getTemplateArgs();
1821 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1822 const RecordVal *RV = CurMC->Rec.getValue(TArgs[i]);
1823 assert(RV && "Template arg doesn't exist?");
1830 /// ParseMultiClass - Parse a multiclass definition.
1832 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
1833 /// ':' BaseMultiClassList '{' MultiClassDef+ '}'
1835 bool TGParser::ParseMultiClass() {
1836 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1837 Lex.Lex(); // Eat the multiclass token.
1839 if (Lex.getCode() != tgtok::Id)
1840 return TokError("expected identifier after multiclass for name");
1841 std::string Name = Lex.getCurStrVal();
1843 if (MultiClasses.count(Name))
1844 return TokError("multiclass '" + Name + "' already defined");
1846 CurMultiClass = MultiClasses[Name] = new MultiClass(Name, Lex.getLoc());
1847 Lex.Lex(); // Eat the identifier.
1849 // If there are template args, parse them.
1850 if (Lex.getCode() == tgtok::less)
1851 if (ParseTemplateArgList(0))
1854 bool inherits = false;
1856 // If there are submulticlasses, parse them.
1857 if (Lex.getCode() == tgtok::colon) {
1862 // Read all of the submulticlasses.
1863 SubMultiClassReference SubMultiClass =
1864 ParseSubMultiClassReference(CurMultiClass);
1867 if (SubMultiClass.MC == 0) return true;
1870 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
1873 if (Lex.getCode() != tgtok::comma) break;
1874 Lex.Lex(); // eat ','.
1875 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
1879 if (Lex.getCode() != tgtok::l_brace) {
1881 return TokError("expected '{' in multiclass definition");
1883 if (Lex.getCode() != tgtok::semi)
1884 return TokError("expected ';' in multiclass definition");
1886 Lex.Lex(); // eat the ';'.
1889 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
1890 return TokError("multiclass must contain at least one def");
1892 while (Lex.getCode() != tgtok::r_brace)
1893 if (ParseMultiClassDef(CurMultiClass))
1896 Lex.Lex(); // eat the '}'.
1903 /// ParseDefm - Parse the instantiation of a multiclass.
1905 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
1907 bool TGParser::ParseDefm() {
1908 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
1909 if (Lex.Lex() != tgtok::Id) // eat the defm.
1910 return TokError("expected identifier after defm");
1912 SMLoc DefmPrefixLoc = Lex.getLoc();
1913 std::string DefmPrefix = Lex.getCurStrVal();
1914 if (Lex.Lex() != tgtok::colon)
1915 return TokError("expected ':' after defm identifier");
1920 SMLoc SubClassLoc = Lex.getLoc();
1921 SubClassReference Ref = ParseSubClassReference(0, true);
1924 if (Ref.Rec == 0) return true;
1926 // To instantiate a multiclass, we need to first get the multiclass, then
1927 // instantiate each def contained in the multiclass with the SubClassRef
1928 // template parameters.
1929 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
1930 assert(MC && "Didn't lookup multiclass correctly?");
1931 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
1933 // Verify that the correct number of template arguments were specified.
1934 const std::vector<std::string> &TArgs = MC->Rec.getTemplateArgs();
1935 if (TArgs.size() < TemplateVals.size())
1936 return Error(SubClassLoc,
1937 "more template args specified than multiclass expects");
1939 // Loop over all the def's in the multiclass, instantiating each one.
1940 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
1941 Record *DefProto = MC->DefPrototypes[i];
1943 // Add in the defm name
1944 std::string DefName = DefProto->getName();
1945 std::string::size_type idx = DefName.find("#NAME#");
1946 if (idx != std::string::npos) {
1947 DefName.replace(idx, 6, DefmPrefix);
1950 // Add the suffix to the defm name to get the new name.
1951 DefName = DefmPrefix + DefName;
1954 Record *CurRec = new Record(DefName, DefmPrefixLoc);
1956 SubClassReference Ref;
1957 Ref.RefLoc = DefmPrefixLoc;
1959 AddSubClass(CurRec, Ref);
1961 // Loop over all of the template arguments, setting them to the specified
1962 // value or leaving them as the default if necessary.
1963 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1964 // Check if a value is specified for this temp-arg.
1965 if (i < TemplateVals.size()) {
1967 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
1972 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
1975 CurRec->removeValue(TArgs[i]);
1977 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
1978 return Error(SubClassLoc,
1979 "value not specified for template argument #"+
1980 utostr(i) + " (" + TArgs[i] + ") of multiclassclass '" +
1981 MC->Rec.getName() + "'");
1985 // If the mdef is inside a 'let' expression, add to each def.
1986 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1987 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1988 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1989 LetStack[i][j].Bits, LetStack[i][j].Value)) {
1990 Error(DefmPrefixLoc, "when instantiating this defm");
1994 // Ensure redefinition doesn't happen.
1995 if (Records.getDef(CurRec->getName()))
1996 return Error(DefmPrefixLoc, "def '" + CurRec->getName() +
1997 "' already defined, instantiating defm with subdef '" +
1998 DefProto->getName() + "'");
1999 Records.addDef(CurRec);
2000 CurRec->resolveReferences();
2003 if (Lex.getCode() != tgtok::comma) break;
2004 Lex.Lex(); // eat ','.
2006 SubClassLoc = Lex.getLoc();
2007 Ref = ParseSubClassReference(0, true);
2010 if (Lex.getCode() != tgtok::semi)
2011 return TokError("expected ';' at end of defm");
2018 /// Object ::= ClassInst
2019 /// Object ::= DefInst
2020 /// Object ::= MultiClassInst
2021 /// Object ::= DefMInst
2022 /// Object ::= LETCommand '{' ObjectList '}'
2023 /// Object ::= LETCommand Object
2024 bool TGParser::ParseObject() {
2025 switch (Lex.getCode()) {
2026 default: assert(0 && "This is not an object");
2027 case tgtok::Let: return ParseTopLevelLet();
2028 case tgtok::Def: return ParseDef(0) == 0;
2029 case tgtok::Defm: return ParseDefm();
2030 case tgtok::Class: return ParseClass();
2031 case tgtok::MultiClass: return ParseMultiClass();
2036 /// ObjectList :== Object*
2037 bool TGParser::ParseObjectList() {
2038 while (isObjectStart(Lex.getCode())) {
2046 bool TGParser::ParseFile() {
2047 Lex.Lex(); // Prime the lexer.
2048 if (ParseObjectList()) return true;
2050 // If we have unread input at the end of the file, report it.
2051 if (Lex.getCode() == tgtok::Eof)
2054 return TokError("Unexpected input at top level");