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 //===----------------------------------------------------------------------===//
18 #include "llvm/ADT/StringExtras.h"
21 //===----------------------------------------------------------------------===//
22 // Support Code for the Semantic Actions.
23 //===----------------------------------------------------------------------===//
27 Record Rec; // Placeholder for template args and Name.
28 std::vector<Record*> DefPrototypes;
30 MultiClass(const std::string &Name, TGLoc Loc) : Rec(Name, Loc) {}
33 struct SubClassReference {
36 std::vector<Init*> TemplateArgs;
37 SubClassReference() : Rec(0) {}
39 bool isInvalid() const { return Rec == 0; }
42 } // end namespace llvm
44 bool TGParser::AddValue(Record *CurRec, TGLoc Loc, const RecordVal &RV) {
46 CurRec = &CurMultiClass->Rec;
48 if (RecordVal *ERV = CurRec->getValue(RV.getName())) {
49 // The value already exists in the class, treat this as a set.
50 if (ERV->setValue(RV.getValue()))
51 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
52 RV.getType()->getAsString() + "' is incompatible with " +
53 "previous definition of type '" +
54 ERV->getType()->getAsString() + "'");
62 /// Return true on error, false on success.
63 bool TGParser::SetValue(Record *CurRec, TGLoc Loc, const std::string &ValName,
64 const std::vector<unsigned> &BitList, Init *V) {
67 if (CurRec == 0) CurRec = &CurMultiClass->Rec;
69 RecordVal *RV = CurRec->getValue(ValName);
71 return Error(Loc, "Value '" + ValName + "' unknown!");
73 // Do not allow assignments like 'X = X'. This will just cause infinite loops
74 // in the resolution machinery.
76 if (VarInit *VI = dynamic_cast<VarInit*>(V))
77 if (VI->getName() == ValName)
80 // If we are assigning to a subset of the bits in the value... then we must be
81 // assigning to a field of BitsRecTy, which must have a BitsInit
84 if (!BitList.empty()) {
85 BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue());
87 return Error(Loc, "Value '" + ValName + "' is not a bits type");
89 // Convert the incoming value to a bits type of the appropriate size...
90 Init *BI = V->convertInitializerTo(new BitsRecTy(BitList.size()));
92 V->convertInitializerTo(new BitsRecTy(BitList.size()));
93 return Error(Loc, "Initializer is not compatible with bit range");
96 // We should have a BitsInit type now.
97 BitsInit *BInit = dynamic_cast<BitsInit*>(BI);
100 BitsInit *NewVal = new BitsInit(CurVal->getNumBits());
102 // Loop over bits, assigning values as appropriate.
103 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
104 unsigned Bit = BitList[i];
105 if (NewVal->getBit(Bit))
106 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
107 ValName + "' more than once");
108 NewVal->setBit(Bit, BInit->getBit(i));
111 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
112 if (NewVal->getBit(i) == 0)
113 NewVal->setBit(i, CurVal->getBit(i));
119 return Error(Loc, "Value '" + ValName + "' of type '" +
120 RV->getType()->getAsString() +
121 "' is incompatible with initializer '" + V->getAsString() +"'");
125 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
126 /// args as SubClass's template arguments.
127 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
128 Record *SC = SubClass.Rec;
129 // Add all of the values in the subclass into the current class.
130 const std::vector<RecordVal> &Vals = SC->getValues();
131 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
132 if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
135 const std::vector<std::string> &TArgs = SC->getTemplateArgs();
137 // Ensure that an appropriate number of template arguments are specified.
138 if (TArgs.size() < SubClass.TemplateArgs.size())
139 return Error(SubClass.RefLoc, "More template args specified than expected");
141 // Loop over all of the template arguments, setting them to the specified
142 // value or leaving them as the default if necessary.
143 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
144 if (i < SubClass.TemplateArgs.size()) {
145 // If a value is specified for this template arg, set it now.
146 if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(),
147 SubClass.TemplateArgs[i]))
151 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
154 CurRec->removeValue(TArgs[i]);
156 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
157 return Error(SubClass.RefLoc,"Value not specified for template argument #"
158 + utostr(i) + " (" + TArgs[i] + ") of subclass '" +
159 SC->getName() + "'!");
163 // Since everything went well, we can now set the "superclass" list for the
165 const std::vector<Record*> &SCs = SC->getSuperClasses();
166 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
167 if (CurRec->isSubClassOf(SCs[i]))
168 return Error(SubClass.RefLoc,
169 "Already subclass of '" + SCs[i]->getName() + "'!\n");
170 CurRec->addSuperClass(SCs[i]);
173 if (CurRec->isSubClassOf(SC))
174 return Error(SubClass.RefLoc,
175 "Already subclass of '" + SC->getName() + "'!\n");
176 CurRec->addSuperClass(SC);
180 //===----------------------------------------------------------------------===//
182 //===----------------------------------------------------------------------===//
184 /// isObjectStart - Return true if this is a valid first token for an Object.
185 static bool isObjectStart(tgtok::TokKind K) {
186 return K == tgtok::Class || K == tgtok::Def ||
187 K == tgtok::Defm || K == tgtok::Let || K == tgtok::MultiClass;
190 /// ParseObjectName - If an object name is specified, return it. Otherwise,
191 /// return an anonymous name.
192 /// ObjectName ::= ID
193 /// ObjectName ::= /*empty*/
195 std::string TGParser::ParseObjectName() {
196 if (Lex.getCode() == tgtok::Id) {
197 std::string Ret = Lex.getCurStrVal();
202 static unsigned AnonCounter = 0;
203 return "anonymous."+utostr(AnonCounter++);
207 /// ParseClassID - Parse and resolve a reference to a class name. This returns
212 Record *TGParser::ParseClassID() {
213 if (Lex.getCode() != tgtok::Id) {
214 TokError("expected name for ClassID");
218 Record *Result = Records.getClass(Lex.getCurStrVal());
220 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
226 Record *TGParser::ParseDefmID() {
227 if (Lex.getCode() != tgtok::Id) {
228 TokError("expected multiclass name");
232 MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
234 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
244 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
245 /// subclass. This returns a SubClassRefTy with a null Record* on error.
247 /// SubClassRef ::= ClassID
248 /// SubClassRef ::= ClassID '<' ValueList '>'
250 SubClassReference TGParser::
251 ParseSubClassReference(Record *CurRec, bool isDefm) {
252 SubClassReference Result;
253 Result.RefLoc = Lex.getLoc();
256 Result.Rec = ParseDefmID();
258 Result.Rec = ParseClassID();
259 if (Result.Rec == 0) return Result;
261 // If there is no template arg list, we're done.
262 if (Lex.getCode() != tgtok::less)
264 Lex.Lex(); // Eat the '<'
266 if (Lex.getCode() == tgtok::greater) {
267 TokError("subclass reference requires a non-empty list of template values");
272 Result.TemplateArgs = ParseValueList(CurRec);
273 if (Result.TemplateArgs.empty()) {
274 Result.Rec = 0; // Error parsing value list.
278 if (Lex.getCode() != tgtok::greater) {
279 TokError("expected '>' in template value list");
288 /// ParseRangePiece - Parse a bit/value range.
289 /// RangePiece ::= INTVAL
290 /// RangePiece ::= INTVAL '-' INTVAL
291 /// RangePiece ::= INTVAL INTVAL
292 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
293 if (Lex.getCode() != tgtok::IntVal) {
294 TokError("expected integer or bitrange");
297 int64_t Start = Lex.getCurIntVal();
301 return TokError("invalid range, cannot be negative");
303 switch (Lex.Lex()) { // eat first character.
305 Ranges.push_back(Start);
308 if (Lex.Lex() != tgtok::IntVal) {
309 TokError("expected integer value as end of range");
312 End = Lex.getCurIntVal();
315 End = -Lex.getCurIntVal();
319 return TokError("invalid range, cannot be negative");
324 for (; Start <= End; ++Start)
325 Ranges.push_back(Start);
327 for (; Start >= End; --Start)
328 Ranges.push_back(Start);
333 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
335 /// RangeList ::= RangePiece (',' RangePiece)*
337 std::vector<unsigned> TGParser::ParseRangeList() {
338 std::vector<unsigned> Result;
340 // Parse the first piece.
341 if (ParseRangePiece(Result))
342 return std::vector<unsigned>();
343 while (Lex.getCode() == tgtok::comma) {
344 Lex.Lex(); // Eat the comma.
346 // Parse the next range piece.
347 if (ParseRangePiece(Result))
348 return std::vector<unsigned>();
353 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
354 /// OptionalRangeList ::= '<' RangeList '>'
355 /// OptionalRangeList ::= /*empty*/
356 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
357 if (Lex.getCode() != tgtok::less)
360 TGLoc StartLoc = Lex.getLoc();
361 Lex.Lex(); // eat the '<'
363 // Parse the range list.
364 Ranges = ParseRangeList();
365 if (Ranges.empty()) return true;
367 if (Lex.getCode() != tgtok::greater) {
368 TokError("expected '>' at end of range list");
369 return Error(StartLoc, "to match this '<'");
371 Lex.Lex(); // eat the '>'.
375 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
376 /// OptionalBitList ::= '{' RangeList '}'
377 /// OptionalBitList ::= /*empty*/
378 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
379 if (Lex.getCode() != tgtok::l_brace)
382 TGLoc StartLoc = Lex.getLoc();
383 Lex.Lex(); // eat the '{'
385 // Parse the range list.
386 Ranges = ParseRangeList();
387 if (Ranges.empty()) return true;
389 if (Lex.getCode() != tgtok::r_brace) {
390 TokError("expected '}' at end of bit list");
391 return Error(StartLoc, "to match this '{'");
393 Lex.Lex(); // eat the '}'.
398 /// ParseType - Parse and return a tblgen type. This returns null on error.
400 /// Type ::= STRING // string type
401 /// Type ::= BIT // bit type
402 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
403 /// Type ::= INT // int type
404 /// Type ::= LIST '<' Type '>' // list<x> type
405 /// Type ::= CODE // code type
406 /// Type ::= DAG // dag type
407 /// Type ::= ClassID // Record Type
409 RecTy *TGParser::ParseType() {
410 switch (Lex.getCode()) {
411 default: TokError("Unknown token when expecting a type"); return 0;
412 case tgtok::String: Lex.Lex(); return new StringRecTy();
413 case tgtok::Bit: Lex.Lex(); return new BitRecTy();
414 case tgtok::Int: Lex.Lex(); return new IntRecTy();
415 case tgtok::Code: Lex.Lex(); return new CodeRecTy();
416 case tgtok::Dag: Lex.Lex(); return new DagRecTy();
418 if (Record *R = ParseClassID()) return new RecordRecTy(R);
421 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
422 TokError("expected '<' after bits type");
425 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
426 TokError("expected integer in bits<n> type");
429 uint64_t Val = Lex.getCurIntVal();
430 if (Lex.Lex() != tgtok::greater) { // Eat count.
431 TokError("expected '>' at end of bits<n> type");
434 Lex.Lex(); // Eat '>'
435 return new BitsRecTy(Val);
438 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
439 TokError("expected '<' after list type");
442 Lex.Lex(); // Eat '<'
443 RecTy *SubType = ParseType();
444 if (SubType == 0) return 0;
446 if (Lex.getCode() != tgtok::greater) {
447 TokError("expected '>' at end of list<ty> type");
450 Lex.Lex(); // Eat '>'
451 return new ListRecTy(SubType);
456 /// ParseIDValue - Parse an ID as a value and decode what it means.
458 /// IDValue ::= ID [def local value]
459 /// IDValue ::= ID [def template arg]
460 /// IDValue ::= ID [multiclass local value]
461 /// IDValue ::= ID [multiclass template argument]
462 /// IDValue ::= ID [def name]
464 Init *TGParser::ParseIDValue(Record *CurRec) {
465 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
466 std::string Name = Lex.getCurStrVal();
467 TGLoc Loc = Lex.getLoc();
469 return ParseIDValue(CurRec, Name, Loc);
472 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
473 /// has already been read.
474 Init *TGParser::ParseIDValue(Record *CurRec,
475 const std::string &Name, TGLoc NameLoc) {
477 if (const RecordVal *RV = CurRec->getValue(Name))
478 return new VarInit(Name, RV->getType());
480 std::string TemplateArgName = CurRec->getName()+":"+Name;
481 if (CurRec->isTemplateArg(TemplateArgName)) {
482 const RecordVal *RV = CurRec->getValue(TemplateArgName);
483 assert(RV && "Template arg doesn't exist??");
484 return new VarInit(TemplateArgName, RV->getType());
489 std::string MCName = CurMultiClass->Rec.getName()+"::"+Name;
490 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
491 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
492 assert(RV && "Template arg doesn't exist??");
493 return new VarInit(MCName, RV->getType());
497 if (Record *D = Records.getDef(Name))
498 return new DefInit(D);
500 Error(NameLoc, "Variable not defined: '" + Name + "'");
504 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
506 /// SimpleValue ::= IDValue
507 /// SimpleValue ::= INTVAL
508 /// SimpleValue ::= STRVAL+
509 /// SimpleValue ::= CODEFRAGMENT
510 /// SimpleValue ::= '?'
511 /// SimpleValue ::= '{' ValueList '}'
512 /// SimpleValue ::= ID '<' ValueListNE '>'
513 /// SimpleValue ::= '[' ValueList ']'
514 /// SimpleValue ::= '(' IDValue DagArgList ')'
515 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
516 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
517 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
518 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
519 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
521 Init *TGParser::ParseSimpleValue(Record *CurRec) {
523 switch (Lex.getCode()) {
524 default: TokError("Unknown token when parsing a value"); break;
525 case tgtok::IntVal: R = new IntInit(Lex.getCurIntVal()); Lex.Lex(); break;
526 case tgtok::StrVal: {
527 std::string Val = Lex.getCurStrVal();
530 // Handle multiple consequtive concatenated strings.
531 while (Lex.getCode() == tgtok::StrVal) {
532 Val += Lex.getCurStrVal();
536 R = new StringInit(Val);
539 case tgtok::CodeFragment:
540 R = new CodeInit(Lex.getCurStrVal()); Lex.Lex(); break;
541 case tgtok::question: R = new UnsetInit(); Lex.Lex(); break;
543 TGLoc NameLoc = Lex.getLoc();
544 std::string Name = Lex.getCurStrVal();
545 if (Lex.Lex() != tgtok::less) // consume the Id.
546 return ParseIDValue(CurRec, Name, NameLoc); // Value ::= IDValue
548 // Value ::= ID '<' ValueListNE '>'
549 if (Lex.Lex() == tgtok::greater) {
550 TokError("expected non-empty value list");
553 std::vector<Init*> ValueList = ParseValueList(CurRec);
554 if (ValueList.empty()) return 0;
556 if (Lex.getCode() != tgtok::greater) {
557 TokError("expected '>' at end of value list");
560 Lex.Lex(); // eat the '>'
562 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
563 // a new anonymous definition, deriving from CLASS<initvalslist> with no
565 Record *Class = Records.getClass(Name);
567 Error(NameLoc, "Expected a class name, got '" + Name + "'");
571 // Create the new record, set it as CurRec temporarily.
572 static unsigned AnonCounter = 0;
573 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),NameLoc);
574 SubClassReference SCRef;
575 SCRef.RefLoc = NameLoc;
577 SCRef.TemplateArgs = ValueList;
578 // Add info about the subclass to NewRec.
579 if (AddSubClass(NewRec, SCRef))
581 NewRec->resolveReferences();
582 Records.addDef(NewRec);
584 // The result of the expression is a reference to the new record.
585 return new DefInit(NewRec);
587 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
588 TGLoc BraceLoc = Lex.getLoc();
589 Lex.Lex(); // eat the '{'
590 std::vector<Init*> Vals;
592 if (Lex.getCode() != tgtok::r_brace) {
593 Vals = ParseValueList(CurRec);
594 if (Vals.empty()) return 0;
596 if (Lex.getCode() != tgtok::r_brace) {
597 TokError("expected '}' at end of bit list value");
600 Lex.Lex(); // eat the '}'
602 BitsInit *Result = new BitsInit(Vals.size());
603 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
604 Init *Bit = Vals[i]->convertInitializerTo(new BitRecTy());
606 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
607 ") is not convertable to a bit");
610 Result->setBit(Vals.size()-i-1, Bit);
614 case tgtok::l_square: { // Value ::= '[' ValueList ']'
615 Lex.Lex(); // eat the '['
616 std::vector<Init*> Vals;
618 if (Lex.getCode() != tgtok::r_square) {
619 Vals = ParseValueList(CurRec);
620 if (Vals.empty()) return 0;
622 if (Lex.getCode() != tgtok::r_square) {
623 TokError("expected ']' at end of list value");
626 Lex.Lex(); // eat the ']'
627 return new ListInit(Vals);
629 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
630 Lex.Lex(); // eat the '('
631 if (Lex.getCode() != tgtok::Id) {
632 TokError("expected identifier in dag init");
636 Init *Operator = ParseIDValue(CurRec);
637 if (Operator == 0) return 0;
639 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
640 if (Lex.getCode() != tgtok::r_paren) {
641 DagArgs = ParseDagArgList(CurRec);
642 if (DagArgs.empty()) return 0;
645 if (Lex.getCode() != tgtok::r_paren) {
646 TokError("expected ')' in dag init");
649 Lex.Lex(); // eat the ')'
651 return new DagInit(Operator, DagArgs);
657 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
658 BinOpInit::BinaryOp Code;
659 switch (Lex.getCode()) {
660 default: assert(0 && "Unhandled code!");
661 case tgtok::XConcat: Code = BinOpInit::CONCAT; break;
662 case tgtok::XSRA: Code = BinOpInit::SRA; break;
663 case tgtok::XSRL: Code = BinOpInit::SRL; break;
664 case tgtok::XSHL: Code = BinOpInit::SHL; break;
665 case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break;
667 Lex.Lex(); // eat the operation
668 if (Lex.getCode() != tgtok::l_paren) {
669 TokError("expected '(' after binary operator");
672 Lex.Lex(); // eat the '('
674 Init *LHS = ParseValue(CurRec);
675 if (LHS == 0) return 0;
677 if (Lex.getCode() != tgtok::comma) {
678 TokError("expected ',' in binary operator");
681 Lex.Lex(); // eat the ','
683 Init *RHS = ParseValue(CurRec);
684 if (RHS == 0) return 0;
686 if (Lex.getCode() != tgtok::r_paren) {
687 TokError("expected ')' in binary operator");
690 Lex.Lex(); // eat the ')'
691 return (new BinOpInit(Code, LHS, RHS))->Fold();
698 /// ParseValue - Parse a tblgen value. This returns null on error.
700 /// Value ::= SimpleValue ValueSuffix*
701 /// ValueSuffix ::= '{' BitList '}'
702 /// ValueSuffix ::= '[' BitList ']'
703 /// ValueSuffix ::= '.' ID
705 Init *TGParser::ParseValue(Record *CurRec) {
706 Init *Result = ParseSimpleValue(CurRec);
707 if (Result == 0) return 0;
709 // Parse the suffixes now if present.
711 switch (Lex.getCode()) {
712 default: return Result;
713 case tgtok::l_brace: {
714 TGLoc CurlyLoc = Lex.getLoc();
715 Lex.Lex(); // eat the '{'
716 std::vector<unsigned> Ranges = ParseRangeList();
717 if (Ranges.empty()) return 0;
719 // Reverse the bitlist.
720 std::reverse(Ranges.begin(), Ranges.end());
721 Result = Result->convertInitializerBitRange(Ranges);
723 Error(CurlyLoc, "Invalid bit range for value");
728 if (Lex.getCode() != tgtok::r_brace) {
729 TokError("expected '}' at end of bit range list");
735 case tgtok::l_square: {
736 TGLoc SquareLoc = Lex.getLoc();
737 Lex.Lex(); // eat the '['
738 std::vector<unsigned> Ranges = ParseRangeList();
739 if (Ranges.empty()) return 0;
741 Result = Result->convertInitListSlice(Ranges);
743 Error(SquareLoc, "Invalid range for list slice");
748 if (Lex.getCode() != tgtok::r_square) {
749 TokError("expected ']' at end of list slice");
756 if (Lex.Lex() != tgtok::Id) { // eat the .
757 TokError("expected field identifier after '.'");
760 if (!Result->getFieldType(Lex.getCurStrVal())) {
761 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
762 Result->getAsString() + "'");
765 Result = new FieldInit(Result, Lex.getCurStrVal());
766 Lex.Lex(); // eat field name
772 /// ParseDagArgList - Parse the argument list for a dag literal expression.
774 /// ParseDagArgList ::= Value (':' VARNAME)?
775 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
776 std::vector<std::pair<llvm::Init*, std::string> >
777 TGParser::ParseDagArgList(Record *CurRec) {
778 std::vector<std::pair<llvm::Init*, std::string> > Result;
781 Init *Val = ParseValue(CurRec);
782 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
784 // If the variable name is present, add it.
786 if (Lex.getCode() == tgtok::colon) {
787 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
788 TokError("expected variable name in dag literal");
789 return std::vector<std::pair<llvm::Init*, std::string> >();
791 VarName = Lex.getCurStrVal();
792 Lex.Lex(); // eat the VarName.
795 Result.push_back(std::make_pair(Val, VarName));
797 if (Lex.getCode() != tgtok::comma) break;
798 Lex.Lex(); // eat the ','
805 /// ParseValueList - Parse a comma separated list of values, returning them as a
806 /// vector. Note that this always expects to be able to parse at least one
807 /// value. It returns an empty list if this is not possible.
809 /// ValueList ::= Value (',' Value)
811 std::vector<Init*> TGParser::ParseValueList(Record *CurRec) {
812 std::vector<Init*> Result;
813 Result.push_back(ParseValue(CurRec));
814 if (Result.back() == 0) return std::vector<Init*>();
816 while (Lex.getCode() == tgtok::comma) {
817 Lex.Lex(); // Eat the comma
819 Result.push_back(ParseValue(CurRec));
820 if (Result.back() == 0) return std::vector<Init*>();
828 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
829 /// empty string on error. This can happen in a number of different context's,
830 /// including within a def or in the template args for a def (which which case
831 /// CurRec will be non-null) and within the template args for a multiclass (in
832 /// which case CurRec will be null, but CurMultiClass will be set). This can
833 /// also happen within a def that is within a multiclass, which will set both
834 /// CurRec and CurMultiClass.
836 /// Declaration ::= FIELD? Type ID ('=' Value)?
838 std::string TGParser::ParseDeclaration(Record *CurRec,
839 bool ParsingTemplateArgs) {
840 // Read the field prefix if present.
841 bool HasField = Lex.getCode() == tgtok::Field;
842 if (HasField) Lex.Lex();
844 RecTy *Type = ParseType();
845 if (Type == 0) return "";
847 if (Lex.getCode() != tgtok::Id) {
848 TokError("Expected identifier in declaration");
852 TGLoc IdLoc = Lex.getLoc();
853 std::string DeclName = Lex.getCurStrVal();
856 if (ParsingTemplateArgs) {
858 DeclName = CurRec->getName() + ":" + DeclName;
860 assert(CurMultiClass);
863 DeclName = CurMultiClass->Rec.getName() + "::" + DeclName;
867 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
870 // If a value is present, parse it.
871 if (Lex.getCode() == tgtok::equal) {
873 TGLoc ValLoc = Lex.getLoc();
874 Init *Val = ParseValue(CurRec);
876 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
883 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
884 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
885 /// template args for a def, which may or may not be in a multiclass. If null,
886 /// these are the template args for a multiclass.
888 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
890 bool TGParser::ParseTemplateArgList(Record *CurRec) {
891 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
892 Lex.Lex(); // eat the '<'
894 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
896 // Read the first declaration.
897 std::string TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
898 if (TemplArg.empty())
901 TheRecToAddTo->addTemplateArg(TemplArg);
903 while (Lex.getCode() == tgtok::comma) {
904 Lex.Lex(); // eat the ','
906 // Read the following declarations.
907 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
908 if (TemplArg.empty())
910 TheRecToAddTo->addTemplateArg(TemplArg);
913 if (Lex.getCode() != tgtok::greater)
914 return TokError("expected '>' at end of template argument list");
915 Lex.Lex(); // eat the '>'.
920 /// ParseBodyItem - Parse a single item at within the body of a def or class.
922 /// BodyItem ::= Declaration ';'
923 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
924 bool TGParser::ParseBodyItem(Record *CurRec) {
925 if (Lex.getCode() != tgtok::Let) {
926 if (ParseDeclaration(CurRec, false).empty())
929 if (Lex.getCode() != tgtok::semi)
930 return TokError("expected ';' after declaration");
935 // LET ID OptionalRangeList '=' Value ';'
936 if (Lex.Lex() != tgtok::Id)
937 return TokError("expected field identifier after let");
939 TGLoc IdLoc = Lex.getLoc();
940 std::string FieldName = Lex.getCurStrVal();
941 Lex.Lex(); // eat the field name.
943 std::vector<unsigned> BitList;
944 if (ParseOptionalBitList(BitList))
946 std::reverse(BitList.begin(), BitList.end());
948 if (Lex.getCode() != tgtok::equal)
949 return TokError("expected '=' in let expression");
950 Lex.Lex(); // eat the '='.
952 Init *Val = ParseValue(CurRec);
953 if (Val == 0) return true;
955 if (Lex.getCode() != tgtok::semi)
956 return TokError("expected ';' after let expression");
959 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
962 /// ParseBody - Read the body of a class or def. Return true on error, false on
966 /// Body ::= '{' BodyList '}'
967 /// BodyList BodyItem*
969 bool TGParser::ParseBody(Record *CurRec) {
970 // If this is a null definition, just eat the semi and return.
971 if (Lex.getCode() == tgtok::semi) {
976 if (Lex.getCode() != tgtok::l_brace)
977 return TokError("Expected ';' or '{' to start body");
981 while (Lex.getCode() != tgtok::r_brace)
982 if (ParseBodyItem(CurRec))
990 /// ParseObjectBody - Parse the body of a def or class. This consists of an
991 /// optional ClassList followed by a Body. CurRec is the current def or class
992 /// that is being parsed.
994 /// ObjectBody ::= BaseClassList Body
995 /// BaseClassList ::= /*empty*/
996 /// BaseClassList ::= ':' BaseClassListNE
997 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
999 bool TGParser::ParseObjectBody(Record *CurRec) {
1000 // If there is a baseclass list, read it.
1001 if (Lex.getCode() == tgtok::colon) {
1004 // Read all of the subclasses.
1005 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1008 if (SubClass.Rec == 0) return true;
1011 if (AddSubClass(CurRec, SubClass))
1014 if (Lex.getCode() != tgtok::comma) break;
1015 Lex.Lex(); // eat ','.
1016 SubClass = ParseSubClassReference(CurRec, false);
1020 // Process any variables on the let stack.
1021 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1022 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1023 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1024 LetStack[i][j].Bits, LetStack[i][j].Value))
1027 return ParseBody(CurRec);
1031 /// ParseDef - Parse and return a top level or multiclass def, return the record
1032 /// corresponding to it. This returns null on error.
1034 /// DefInst ::= DEF ObjectName ObjectBody
1036 llvm::Record *TGParser::ParseDef(MultiClass *CurMultiClass) {
1037 TGLoc DefLoc = Lex.getLoc();
1038 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1039 Lex.Lex(); // Eat the 'def' token.
1041 // Parse ObjectName and make a record for it.
1042 Record *CurRec = new Record(ParseObjectName(), DefLoc);
1044 if (!CurMultiClass) {
1045 // Top-level def definition.
1047 // Ensure redefinition doesn't happen.
1048 if (Records.getDef(CurRec->getName())) {
1049 Error(DefLoc, "def '" + CurRec->getName() + "' already defined");
1052 Records.addDef(CurRec);
1054 // Otherwise, a def inside a multiclass, add it to the multiclass.
1055 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1056 if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
1057 Error(DefLoc, "def '" + CurRec->getName() +
1058 "' already defined in this multiclass!");
1061 CurMultiClass->DefPrototypes.push_back(CurRec);
1064 if (ParseObjectBody(CurRec))
1067 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1068 CurRec->resolveReferences();
1070 // If ObjectBody has template arguments, it's an error.
1071 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1076 /// ParseClass - Parse a tblgen class definition.
1078 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1080 bool TGParser::ParseClass() {
1081 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1084 if (Lex.getCode() != tgtok::Id)
1085 return TokError("expected class name after 'class' keyword");
1087 Record *CurRec = Records.getClass(Lex.getCurStrVal());
1089 // If the body was previously defined, this is an error.
1090 if (!CurRec->getValues().empty() ||
1091 !CurRec->getSuperClasses().empty() ||
1092 !CurRec->getTemplateArgs().empty())
1093 return TokError("Class '" + CurRec->getName() + "' already defined");
1095 // If this is the first reference to this class, create and add it.
1096 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc());
1097 Records.addClass(CurRec);
1099 Lex.Lex(); // eat the name.
1101 // If there are template args, parse them.
1102 if (Lex.getCode() == tgtok::less)
1103 if (ParseTemplateArgList(CurRec))
1106 // Finally, parse the object body.
1107 return ParseObjectBody(CurRec);
1110 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
1113 /// LetList ::= LetItem (',' LetItem)*
1114 /// LetItem ::= ID OptionalRangeList '=' Value
1116 std::vector<LetRecord> TGParser::ParseLetList() {
1117 std::vector<LetRecord> Result;
1120 if (Lex.getCode() != tgtok::Id) {
1121 TokError("expected identifier in let definition");
1122 return std::vector<LetRecord>();
1124 std::string Name = Lex.getCurStrVal();
1125 TGLoc NameLoc = Lex.getLoc();
1126 Lex.Lex(); // Eat the identifier.
1128 // Check for an optional RangeList.
1129 std::vector<unsigned> Bits;
1130 if (ParseOptionalRangeList(Bits))
1131 return std::vector<LetRecord>();
1132 std::reverse(Bits.begin(), Bits.end());
1134 if (Lex.getCode() != tgtok::equal) {
1135 TokError("expected '=' in let expression");
1136 return std::vector<LetRecord>();
1138 Lex.Lex(); // eat the '='.
1140 Init *Val = ParseValue(0);
1141 if (Val == 0) return std::vector<LetRecord>();
1143 // Now that we have everything, add the record.
1144 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1146 if (Lex.getCode() != tgtok::comma)
1148 Lex.Lex(); // eat the comma.
1152 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
1153 /// different related productions.
1155 /// Object ::= LET LetList IN '{' ObjectList '}'
1156 /// Object ::= LET LetList IN Object
1158 bool TGParser::ParseTopLevelLet() {
1159 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1162 // Add this entry to the let stack.
1163 std::vector<LetRecord> LetInfo = ParseLetList();
1164 if (LetInfo.empty()) return true;
1165 LetStack.push_back(LetInfo);
1167 if (Lex.getCode() != tgtok::In)
1168 return TokError("expected 'in' at end of top-level 'let'");
1171 // If this is a scalar let, just handle it now
1172 if (Lex.getCode() != tgtok::l_brace) {
1173 // LET LetList IN Object
1176 } else { // Object ::= LETCommand '{' ObjectList '}'
1177 TGLoc BraceLoc = Lex.getLoc();
1178 // Otherwise, this is a group let.
1179 Lex.Lex(); // eat the '{'.
1181 // Parse the object list.
1182 if (ParseObjectList())
1185 if (Lex.getCode() != tgtok::r_brace) {
1186 TokError("expected '}' at end of top level let command");
1187 return Error(BraceLoc, "to match this '{'");
1192 // Outside this let scope, this let block is not active.
1193 LetStack.pop_back();
1197 /// ParseMultiClassDef - Parse a def in a multiclass context.
1199 /// MultiClassDef ::= DefInst
1201 bool TGParser::ParseMultiClassDef(MultiClass *CurMC) {
1202 if (Lex.getCode() != tgtok::Def)
1203 return TokError("expected 'def' in multiclass body");
1205 Record *D = ParseDef(CurMC);
1206 if (D == 0) return true;
1208 // Copy the template arguments for the multiclass into the def.
1209 const std::vector<std::string> &TArgs = CurMC->Rec.getTemplateArgs();
1211 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1212 const RecordVal *RV = CurMC->Rec.getValue(TArgs[i]);
1213 assert(RV && "Template arg doesn't exist?");
1220 /// ParseMultiClass - Parse a multiclass definition.
1222 /// MultiClassInst ::= MULTICLASS ID TemplateArgList? '{' MultiClassDef+ '}'
1224 bool TGParser::ParseMultiClass() {
1225 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1226 Lex.Lex(); // Eat the multiclass token.
1228 if (Lex.getCode() != tgtok::Id)
1229 return TokError("expected identifier after multiclass for name");
1230 std::string Name = Lex.getCurStrVal();
1232 if (MultiClasses.count(Name))
1233 return TokError("multiclass '" + Name + "' already defined");
1235 CurMultiClass = MultiClasses[Name] = new MultiClass(Name, Lex.getLoc());
1236 Lex.Lex(); // Eat the identifier.
1238 // If there are template args, parse them.
1239 if (Lex.getCode() == tgtok::less)
1240 if (ParseTemplateArgList(0))
1243 if (Lex.getCode() != tgtok::l_brace)
1244 return TokError("expected '{' in multiclass definition");
1246 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
1247 return TokError("multiclass must contain at least one def");
1249 while (Lex.getCode() != tgtok::r_brace)
1250 if (ParseMultiClassDef(CurMultiClass))
1253 Lex.Lex(); // eat the '}'.
1259 /// ParseDefm - Parse the instantiation of a multiclass.
1261 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
1263 bool TGParser::ParseDefm() {
1264 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
1265 if (Lex.Lex() != tgtok::Id) // eat the defm.
1266 return TokError("expected identifier after defm");
1268 TGLoc DefmPrefixLoc = Lex.getLoc();
1269 std::string DefmPrefix = Lex.getCurStrVal();
1270 if (Lex.Lex() != tgtok::colon)
1271 return TokError("expected ':' after defm identifier");
1276 TGLoc SubClassLoc = Lex.getLoc();
1277 SubClassReference Ref = ParseSubClassReference(0, true);
1278 if (Ref.Rec == 0) return true;
1280 if (Lex.getCode() != tgtok::semi)
1281 return TokError("expected ';' at end of defm");
1284 // To instantiate a multiclass, we need to first get the multiclass, then
1285 // instantiate each def contained in the multiclass with the SubClassRef
1286 // template parameters.
1287 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
1288 assert(MC && "Didn't lookup multiclass correctly?");
1289 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
1291 // Verify that the correct number of template arguments were specified.
1292 const std::vector<std::string> &TArgs = MC->Rec.getTemplateArgs();
1293 if (TArgs.size() < TemplateVals.size())
1294 return Error(SubClassLoc,
1295 "more template args specified than multiclass expects");
1297 // Loop over all the def's in the multiclass, instantiating each one.
1298 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
1299 Record *DefProto = MC->DefPrototypes[i];
1301 // Add the suffix to the defm name to get the new name.
1302 Record *CurRec = new Record(DefmPrefix + DefProto->getName(),DefmPrefixLoc);
1304 SubClassReference Ref;
1305 Ref.RefLoc = DefmPrefixLoc;
1307 AddSubClass(CurRec, Ref);
1309 // Loop over all of the template arguments, setting them to the specified
1310 // value or leaving them as the default if necessary.
1311 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1312 if (i < TemplateVals.size()) { // A value is specified for this temp-arg?
1314 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
1319 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
1322 CurRec->removeValue(TArgs[i]);
1324 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
1325 return Error(SubClassLoc, "value not specified for template argument #"+
1326 utostr(i) + " (" + TArgs[i] + ") of multiclassclass '" +
1327 MC->Rec.getName() + "'");
1331 // If the mdef is inside a 'let' expression, add to each def.
1332 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1333 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1334 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1335 LetStack[i][j].Bits, LetStack[i][j].Value)) {
1336 Error(DefmPrefixLoc, "when instantiating this defm");
1341 // Ensure redefinition doesn't happen.
1342 if (Records.getDef(CurRec->getName()))
1343 return Error(DefmPrefixLoc, "def '" + CurRec->getName() +
1344 "' already defined, instantiating defm with subdef '" +
1345 DefProto->getName() + "'");
1346 Records.addDef(CurRec);
1347 CurRec->resolveReferences();
1354 /// Object ::= ClassInst
1355 /// Object ::= DefInst
1356 /// Object ::= MultiClassInst
1357 /// Object ::= DefMInst
1358 /// Object ::= LETCommand '{' ObjectList '}'
1359 /// Object ::= LETCommand Object
1360 bool TGParser::ParseObject() {
1361 switch (Lex.getCode()) {
1362 default: assert(0 && "This is not an object");
1363 case tgtok::Let: return ParseTopLevelLet();
1364 case tgtok::Def: return ParseDef(0) == 0;
1365 case tgtok::Defm: return ParseDefm();
1366 case tgtok::Class: return ParseClass();
1367 case tgtok::MultiClass: return ParseMultiClass();
1372 /// ObjectList :== Object*
1373 bool TGParser::ParseObjectList() {
1374 while (isObjectStart(Lex.getCode())) {
1382 bool TGParser::ParseFile() {
1383 Lex.Lex(); // Prime the lexer.
1384 if (ParseObjectList()) return true;
1386 // If we have unread input at the end of the file, report it.
1387 if (Lex.getCode() == tgtok::Eof)
1390 return TokError("Unexpected input at top level");