1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implement the Parser for TableGen.
12 //===----------------------------------------------------------------------===//
16 #include "llvm/ADT/StringExtras.h"
19 //===----------------------------------------------------------------------===//
20 // Support Code for the Semantic Actions.
21 //===----------------------------------------------------------------------===//
25 Record Rec; // Placeholder for template args and Name.
26 std::vector<Record*> DefPrototypes;
28 MultiClass(const std::string &Name) : Rec(Name) {}
31 struct SubClassReference {
32 TGParser::LocTy RefLoc;
34 std::vector<Init*> TemplateArgs;
35 SubClassReference() : RefLoc(0), Rec(0) {}
37 bool isInvalid() const { return Rec == 0; }
40 } // end namespace llvm
42 bool TGParser::AddValue(Record *CurRec, LocTy Loc, const RecordVal &RV) {
44 CurRec = &CurMultiClass->Rec;
46 if (RecordVal *ERV = CurRec->getValue(RV.getName())) {
47 // The value already exists in the class, treat this as a set.
48 if (ERV->setValue(RV.getValue()))
49 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
50 RV.getType()->getAsString() + "' is incompatible with " +
51 "previous definition of type '" +
52 ERV->getType()->getAsString() + "'");
60 /// Return true on error, false on success.
61 bool TGParser::SetValue(Record *CurRec, LocTy Loc, const std::string &ValName,
62 const std::vector<unsigned> &BitList, Init *V) {
65 if (CurRec == 0) CurRec = &CurMultiClass->Rec;
67 RecordVal *RV = CurRec->getValue(ValName);
69 return Error(Loc, "Value '" + ValName + "' unknown!");
71 // Do not allow assignments like 'X = X'. This will just cause infinite loops
72 // in the resolution machinery.
74 if (VarInit *VI = dynamic_cast<VarInit*>(V))
75 if (VI->getName() == ValName)
78 // If we are assigning to a subset of the bits in the value... then we must be
79 // assigning to a field of BitsRecTy, which must have a BitsInit
82 if (!BitList.empty()) {
83 BitsInit *CurVal = dynamic_cast<BitsInit*>(RV->getValue());
85 return Error(Loc, "Value '" + ValName + "' is not a bits type");
87 // Convert the incoming value to a bits type of the appropriate size...
88 Init *BI = V->convertInitializerTo(new BitsRecTy(BitList.size()));
90 V->convertInitializerTo(new BitsRecTy(BitList.size()));
91 return Error(Loc, "Initializer is not compatible with bit range");
94 // We should have a BitsInit type now.
95 BitsInit *BInit = dynamic_cast<BitsInit*>(BI);
98 BitsInit *NewVal = new BitsInit(CurVal->getNumBits());
100 // Loop over bits, assigning values as appropriate.
101 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
102 unsigned Bit = BitList[i];
103 if (NewVal->getBit(Bit))
104 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
105 ValName + "' more than once");
106 NewVal->setBit(Bit, BInit->getBit(i));
109 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
110 if (NewVal->getBit(i) == 0)
111 NewVal->setBit(i, CurVal->getBit(i));
117 return Error(Loc, "Value '" + ValName + "' of type '" +
118 RV->getType()->getAsString() +
119 "' is incompatible with initializer ''"); // FIXME: Add init!
123 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
124 /// args as SubClass's template arguments.
125 bool TGParser::AddSubClass(Record *CurRec, class SubClassReference &SubClass) {
126 Record *SC = SubClass.Rec;
127 // Add all of the values in the subclass into the current class.
128 const std::vector<RecordVal> &Vals = SC->getValues();
129 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
130 if (AddValue(CurRec, SubClass.RefLoc, Vals[i]))
133 const std::vector<std::string> &TArgs = SC->getTemplateArgs();
135 // Ensure that an appropriate number of template arguments are specified.
136 if (TArgs.size() < SubClass.TemplateArgs.size())
137 return Error(SubClass.RefLoc, "More template args specified than expected");
139 // Loop over all of the template arguments, setting them to the specified
140 // value or leaving them as the default if necessary.
141 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
142 if (i < SubClass.TemplateArgs.size()) {
143 // If a value is specified for this template arg, set it now.
144 if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(),
145 SubClass.TemplateArgs[i]))
149 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
152 CurRec->removeValue(TArgs[i]);
154 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
155 return Error(SubClass.RefLoc,"Value not specified for template argument #"
156 + utostr(i) + " (" + TArgs[i] + ") of subclass '" +
157 SC->getName() + "'!");
161 // Since everything went well, we can now set the "superclass" list for the
163 const std::vector<Record*> &SCs = SC->getSuperClasses();
164 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
165 if (CurRec->isSubClassOf(SCs[i]))
166 return Error(SubClass.RefLoc,
167 "Already subclass of '" + SCs[i]->getName() + "'!\n");
168 CurRec->addSuperClass(SCs[i]);
171 if (CurRec->isSubClassOf(SC))
172 return Error(SubClass.RefLoc,
173 "Already subclass of '" + SC->getName() + "'!\n");
174 CurRec->addSuperClass(SC);
178 //===----------------------------------------------------------------------===//
180 //===----------------------------------------------------------------------===//
182 /// isObjectStart - Return true if this is a valid first token for an Object.
183 static bool isObjectStart(tgtok::TokKind K) {
184 return K == tgtok::Class || K == tgtok::Def ||
185 K == tgtok::Defm || K == tgtok::Let || K == tgtok::MultiClass;
188 /// ParseObjectName - If an object name is specified, return it. Otherwise,
189 /// return an anonymous name.
190 /// ObjectName ::= ID
191 /// ObjectName ::= /*empty*/
193 std::string TGParser::ParseObjectName() {
194 if (Lex.getCode() == tgtok::Id) {
195 std::string Ret = Lex.getCurStrVal();
200 static unsigned AnonCounter = 0;
201 return "anonymous."+utostr(AnonCounter++);
205 /// ParseClassID - Parse and resolve a reference to a class name. This returns
210 Record *TGParser::ParseClassID() {
211 if (Lex.getCode() != tgtok::Id) {
212 TokError("expected name for ClassID");
216 Record *Result = Records.getClass(Lex.getCurStrVal());
218 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
224 Record *TGParser::ParseDefmID() {
225 if (Lex.getCode() != tgtok::Id) {
226 TokError("expected multiclass name");
230 MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
232 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
242 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
243 /// subclass. This returns a SubClassRefTy with a null Record* on error.
245 /// SubClassRef ::= ClassID
246 /// SubClassRef ::= ClassID '<' ValueList '>'
248 SubClassReference TGParser::
249 ParseSubClassReference(Record *CurRec, bool isDefm) {
250 SubClassReference Result;
251 Result.RefLoc = Lex.getLoc();
254 Result.Rec = ParseDefmID();
256 Result.Rec = ParseClassID();
257 if (Result.Rec == 0) return Result;
259 // If there is no template arg list, we're done.
260 if (Lex.getCode() != tgtok::less)
262 Lex.Lex(); // Eat the '<'
264 if (Lex.getCode() == tgtok::greater) {
265 TokError("subclass reference requires a non-empty list of template values");
270 Result.TemplateArgs = ParseValueList(CurRec);
271 if (Result.TemplateArgs.empty()) {
272 Result.Rec = 0; // Error parsing value list.
276 if (Lex.getCode() != tgtok::greater) {
277 TokError("expected '>' in template value list");
286 /// ParseRangePiece - Parse a bit/value range.
287 /// RangePiece ::= INTVAL
288 /// RangePiece ::= INTVAL '-' INTVAL
289 /// RangePiece ::= INTVAL INTVAL
290 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
291 assert(Lex.getCode() == tgtok::IntVal && "Invalid range");
292 int Start = Lex.getCurIntVal();
296 return TokError("invalid range, cannot be negative");
298 switch (Lex.Lex()) { // eat first character.
300 Ranges.push_back(Start);
303 if (Lex.Lex() != tgtok::IntVal) {
304 TokError("expected integer value as end of range");
307 End = Lex.getCurIntVal();
310 End = -Lex.getCurIntVal();
314 return TokError("invalid range, cannot be negative");
319 for (; Start <= End; ++Start)
320 Ranges.push_back(Start);
322 for (; Start >= End; --Start)
323 Ranges.push_back(Start);
328 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
330 /// RangeList ::= RangePiece (',' RangePiece)*
332 std::vector<unsigned> TGParser::ParseRangeList() {
333 std::vector<unsigned> Result;
335 // Parse the first piece.
336 if (ParseRangePiece(Result))
337 return std::vector<unsigned>();
338 while (Lex.getCode() == tgtok::comma) {
339 Lex.Lex(); // Eat the comma.
341 // Parse the next range piece.
342 if (ParseRangePiece(Result))
343 return std::vector<unsigned>();
348 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
349 /// OptionalRangeList ::= '<' RangeList '>'
350 /// OptionalRangeList ::= /*empty*/
351 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
352 if (Lex.getCode() != tgtok::less)
355 LocTy StartLoc = Lex.getLoc();
356 Lex.Lex(); // eat the '<'
358 // Parse the range list.
359 Ranges = ParseRangeList();
360 if (Ranges.empty()) return true;
362 if (Lex.getCode() != tgtok::greater) {
363 TokError("expected '>' at end of range list");
364 return Error(StartLoc, "to match this '<'");
366 Lex.Lex(); // eat the '>'.
370 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
371 /// OptionalBitList ::= '{' RangeList '}'
372 /// OptionalBitList ::= /*empty*/
373 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
374 if (Lex.getCode() != tgtok::l_brace)
377 LocTy StartLoc = Lex.getLoc();
378 Lex.Lex(); // eat the '{'
380 // Parse the range list.
381 Ranges = ParseRangeList();
382 if (Ranges.empty()) return true;
384 if (Lex.getCode() != tgtok::r_brace) {
385 TokError("expected '}' at end of bit list");
386 return Error(StartLoc, "to match this '{'");
388 Lex.Lex(); // eat the '}'.
393 /// ParseType - Parse and return a tblgen type. This returns null on error.
395 /// Type ::= STRING // string type
396 /// Type ::= BIT // bit type
397 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
398 /// Type ::= INT // int type
399 /// Type ::= LIST '<' Type '>' // list<x> type
400 /// Type ::= CODE // code type
401 /// Type ::= DAG // dag type
402 /// Type ::= ClassID // Record Type
404 RecTy *TGParser::ParseType() {
405 switch (Lex.getCode()) {
406 default: TokError("Unknown token when expecting a type"); return 0;
407 case tgtok::String: Lex.Lex(); return new StringRecTy();
408 case tgtok::Bit: Lex.Lex(); return new BitRecTy();
409 case tgtok::Int: Lex.Lex(); return new IntRecTy();
410 case tgtok::Code: Lex.Lex(); return new CodeRecTy();
411 case tgtok::Dag: Lex.Lex(); return new DagRecTy();
413 if (Record *R = ParseClassID()) return new RecordRecTy(R);
416 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
417 TokError("expected '<' after bits type");
420 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
421 TokError("expected integer in bits<n> type");
424 unsigned Val = Lex.getCurIntVal();
425 if (Lex.Lex() != tgtok::greater) { // Eat count.
426 TokError("expected '>' at end of bits<n> type");
429 Lex.Lex(); // Eat '>'
430 return new BitsRecTy(Val);
433 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
434 TokError("expected '<' after list type");
437 Lex.Lex(); // Eat '<'
438 RecTy *SubType = ParseType();
439 if (SubType == 0) return 0;
441 if (Lex.getCode() != tgtok::greater) {
442 TokError("expected '>' at end of list<ty> type");
445 Lex.Lex(); // Eat '>'
446 return new ListRecTy(SubType);
451 /// ParseIDValue - Parse an ID as a value and decode what it means.
453 /// IDValue ::= ID [def local value]
454 /// IDValue ::= ID [def template arg]
455 /// IDValue ::= ID [multiclass local value]
456 /// IDValue ::= ID [multiclass template argument]
457 /// IDValue ::= ID [def name]
459 Init *TGParser::ParseIDValue(Record *CurRec) {
460 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
461 std::string Name = Lex.getCurStrVal();
462 LocTy Loc = Lex.getLoc();
464 return ParseIDValue(CurRec, Name, Loc);
467 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
468 /// has already been read.
469 Init *TGParser::ParseIDValue(Record *CurRec,
470 const std::string &Name, LocTy NameLoc) {
472 if (const RecordVal *RV = CurRec->getValue(Name))
473 return new VarInit(Name, RV->getType());
475 std::string TemplateArgName = CurRec->getName()+":"+Name;
476 if (CurRec->isTemplateArg(TemplateArgName)) {
477 const RecordVal *RV = CurRec->getValue(TemplateArgName);
478 assert(RV && "Template arg doesn't exist??");
479 return new VarInit(TemplateArgName, RV->getType());
484 std::string MCName = CurMultiClass->Rec.getName()+"::"+Name;
485 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
486 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
487 assert(RV && "Template arg doesn't exist??");
488 return new VarInit(MCName, RV->getType());
492 if (Record *D = Records.getDef(Name))
493 return new DefInit(D);
495 Error(NameLoc, "Variable not defined: '" + Name + "'");
499 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
501 /// SimpleValue ::= IDValue
502 /// SimpleValue ::= INTVAL
503 /// SimpleValue ::= STRVAL
504 /// SimpleValue ::= CODEFRAGMENT
505 /// SimpleValue ::= '?'
506 /// SimpleValue ::= '{' ValueList '}'
507 /// SimpleValue ::= ID '<' ValueListNE '>'
508 /// SimpleValue ::= '[' ValueList ']'
509 /// SimpleValue ::= '(' IDValue DagArgList ')'
510 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
511 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
512 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
513 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
514 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
516 Init *TGParser::ParseSimpleValue(Record *CurRec) {
518 switch (Lex.getCode()) {
519 default: TokError("Unknown token when parsing a value"); break;
520 case tgtok::IntVal: R = new IntInit(Lex.getCurIntVal()); Lex.Lex(); break;
521 case tgtok::StrVal: R = new StringInit(Lex.getCurStrVal()); Lex.Lex(); break;
522 case tgtok::CodeFragment:
523 R = new CodeInit(Lex.getCurStrVal()); Lex.Lex(); break;
524 case tgtok::question: R = new UnsetInit(); Lex.Lex(); break;
526 LocTy NameLoc = Lex.getLoc();
527 std::string Name = Lex.getCurStrVal();
528 if (Lex.Lex() != tgtok::less) // consume the Id.
529 return ParseIDValue(CurRec, Name, NameLoc); // Value ::= IDValue
531 // Value ::= ID '<' ValueListNE '>'
532 if (Lex.Lex() == tgtok::greater) {
533 TokError("expected non-empty value list");
536 std::vector<Init*> ValueList = ParseValueList(CurRec);
537 if (ValueList.empty()) return 0;
539 if (Lex.getCode() != tgtok::greater) {
540 TokError("expected '>' at end of value list");
543 Lex.Lex(); // eat the '>'
545 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
546 // a new anonymous definition, deriving from CLASS<initvalslist> with no
548 Record *Class = Records.getClass(Name);
550 Error(NameLoc, "Expected a class name, got '" + Name + "'");
554 // Create the new record, set it as CurRec temporarily.
555 static unsigned AnonCounter = 0;
556 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++));
557 SubClassReference SCRef;
558 SCRef.RefLoc = NameLoc;
560 SCRef.TemplateArgs = ValueList;
561 // Add info about the subclass to NewRec.
562 if (AddSubClass(NewRec, SCRef))
564 NewRec->resolveReferences();
565 Records.addDef(NewRec);
567 // The result of the expression is a reference to the new record.
568 return new DefInit(NewRec);
570 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
571 LocTy BraceLoc = Lex.getLoc();
572 Lex.Lex(); // eat the '{'
573 std::vector<Init*> Vals;
575 if (Lex.getCode() != tgtok::r_brace) {
576 Vals = ParseValueList(CurRec);
577 if (Vals.empty()) return 0;
579 if (Lex.getCode() != tgtok::r_brace) {
580 TokError("expected '}' at end of bit list value");
583 Lex.Lex(); // eat the '}'
585 BitsInit *Result = new BitsInit(Vals.size());
586 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
587 Init *Bit = Vals[i]->convertInitializerTo(new BitRecTy());
589 // FIXME: Include value in error.
590 Error(BraceLoc, "Element #" + utostr(i) + " ("/* << *Vals[i]
591 <<*/ ") is not convertable to a bit");
594 Result->setBit(Vals.size()-i-1, Bit);
598 case tgtok::l_square: { // Value ::= '[' ValueList ']'
599 Lex.Lex(); // eat the '['
600 std::vector<Init*> Vals;
602 if (Lex.getCode() != tgtok::r_square) {
603 Vals = ParseValueList(CurRec);
604 if (Vals.empty()) return 0;
606 if (Lex.getCode() != tgtok::r_square) {
607 TokError("expected ']' at end of list value");
610 Lex.Lex(); // eat the ']'
611 return new ListInit(Vals);
613 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
614 Lex.Lex(); // eat the '('
615 Init *Operator = ParseIDValue(CurRec);
616 if (Operator == 0) return 0;
618 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
619 if (Lex.getCode() != tgtok::r_paren) {
620 DagArgs = ParseDagArgList(CurRec);
621 if (DagArgs.empty()) return 0;
624 if (Lex.getCode() != tgtok::r_paren) {
625 TokError("expected ')' in dag init");
628 Lex.Lex(); // eat the ')'
630 return new DagInit(Operator, DagArgs);
636 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
637 BinOpInit::BinaryOp Code;
638 switch (Lex.getCode()) {
639 default: assert(0 && "Unhandled code!");
640 case tgtok::XConcat: Code = BinOpInit::CONCAT; break;
641 case tgtok::XSRA: Code = BinOpInit::SRA; break;
642 case tgtok::XSRL: Code = BinOpInit::SRL; break;
643 case tgtok::XSHL: Code = BinOpInit::SHL; break;
644 case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break;
646 Lex.Lex(); // eat the operation
647 if (Lex.getCode() != tgtok::l_paren) {
648 TokError("expected '(' after binary operator");
651 Lex.Lex(); // eat the '('
653 Init *LHS = ParseValue(CurRec);
654 if (LHS == 0) return 0;
656 if (Lex.getCode() != tgtok::comma) {
657 TokError("expected ',' in binary operator");
660 Lex.Lex(); // eat the ','
662 Init *RHS = ParseValue(CurRec);
663 if (RHS == 0) return 0;
665 if (Lex.getCode() != tgtok::r_paren) {
666 TokError("expected ')' in binary operator");
669 Lex.Lex(); // eat the ')'
670 return (new BinOpInit(Code, LHS, RHS))->Fold();
677 /// ParseValue - Parse a tblgen value. This returns null on error.
679 /// Value ::= SimpleValue ValueSuffix*
680 /// ValueSuffix ::= '{' BitList '}'
681 /// ValueSuffix ::= '[' BitList ']'
682 /// ValueSuffix ::= '.' ID
684 Init *TGParser::ParseValue(Record *CurRec) {
685 Init *Result = ParseSimpleValue(CurRec);
686 if (Result == 0) return 0;
688 // Parse the suffixes now if present.
690 switch (Lex.getCode()) {
691 default: return Result;
692 case tgtok::l_brace: {
693 LocTy CurlyLoc = Lex.getLoc();
694 Lex.Lex(); // eat the '{'
695 std::vector<unsigned> Ranges = ParseRangeList();
696 if (Ranges.empty()) return 0;
698 // Reverse the bitlist.
699 std::reverse(Ranges.begin(), Ranges.end());
700 Result = Result->convertInitializerBitRange(Ranges);
702 Error(CurlyLoc, "Invalid bit range for value");
707 if (Lex.getCode() != tgtok::r_brace) {
708 TokError("expected '}' at end of bit range list");
714 case tgtok::l_square: {
715 LocTy SquareLoc = Lex.getLoc();
716 Lex.Lex(); // eat the '['
717 std::vector<unsigned> Ranges = ParseRangeList();
718 if (Ranges.empty()) return 0;
720 Result = Result->convertInitListSlice(Ranges);
722 Error(SquareLoc, "Invalid range for list slice");
727 if (Lex.getCode() != tgtok::r_square) {
728 TokError("expected ']' at end of list slice");
735 if (Lex.Lex() != tgtok::Id) { // eat the .
736 TokError("expected field identifier after '.'");
739 if (!Result->getFieldType(Lex.getCurStrVal())) {
740 // FIXME INCLUDE VALUE IN ERROR.
741 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
745 Result = new FieldInit(Result, Lex.getCurStrVal());
746 Lex.Lex(); // eat field name
752 /// ParseDagArgList - Parse the argument list for a dag literal expression.
754 /// ParseDagArgList ::= Value (':' VARNAME)?
755 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
756 std::vector<std::pair<llvm::Init*, std::string> >
757 TGParser::ParseDagArgList(Record *CurRec) {
758 std::vector<std::pair<llvm::Init*, std::string> > Result;
761 Init *Val = ParseValue(CurRec);
762 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
764 // If the variable name is present, add it.
766 if (Lex.getCode() == tgtok::colon) {
767 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
768 TokError("expected variable name in dag literal");
769 return std::vector<std::pair<llvm::Init*, std::string> >();
771 VarName = Lex.getCurStrVal();
772 Lex.Lex(); // eat the VarName.
775 Result.push_back(std::make_pair(Val, VarName));
777 if (Lex.getCode() != tgtok::comma) break;
778 Lex.Lex(); // eat the ','
785 /// ParseValueList - Parse a comma separated list of values, returning them as a
786 /// vector. Note that this always expects to be able to parse at least one
787 /// value. It returns an empty list if this is not possible.
789 /// ValueList ::= Value (',' Value)
791 std::vector<Init*> TGParser::ParseValueList(Record *CurRec) {
792 std::vector<Init*> Result;
793 Result.push_back(ParseValue(CurRec));
794 if (Result.back() == 0) return std::vector<Init*>();
796 while (Lex.getCode() == tgtok::comma) {
797 Lex.Lex(); // Eat the comma
799 Result.push_back(ParseValue(CurRec));
800 if (Result.back() == 0) return std::vector<Init*>();
808 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
809 /// empty string on error. This can happen in a number of different context's,
810 /// including within a def or in the template args for a def (which which case
811 /// CurRec will be non-null) and within the template args for a multiclass (in
812 /// which case CurRec will be null, but CurMultiClass will be set). This can
813 /// also happen within a def that is within a multiclass, which will set both
814 /// CurRec and CurMultiClass.
816 /// Declaration ::= FIELD? Type ID ('=' Value)?
818 std::string TGParser::ParseDeclaration(Record *CurRec,
819 bool ParsingTemplateArgs) {
820 // Read the field prefix if present.
821 bool HasField = Lex.getCode() == tgtok::Field;
822 if (HasField) Lex.Lex();
824 RecTy *Type = ParseType();
825 if (Type == 0) return "";
827 if (Lex.getCode() != tgtok::Id) {
828 TokError("Expected identifier in declaration");
832 LocTy IdLoc = Lex.getLoc();
833 std::string DeclName = Lex.getCurStrVal();
836 if (ParsingTemplateArgs) {
838 DeclName = CurRec->getName() + ":" + DeclName;
840 assert(CurMultiClass);
843 DeclName = CurMultiClass->Rec.getName() + "::" + DeclName;
847 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
850 // If a value is present, parse it.
851 if (Lex.getCode() == tgtok::equal) {
853 LocTy ValLoc = Lex.getLoc();
854 Init *Val = ParseValue(CurRec);
856 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
863 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
864 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
865 /// template args for a def, which may or may not be in a multiclass. If null,
866 /// these are the template args for a multiclass.
868 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
870 bool TGParser::ParseTemplateArgList(Record *CurRec) {
871 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
872 Lex.Lex(); // eat the '<'
874 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
876 // Read the first declaration.
877 std::string TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
878 if (TemplArg.empty())
881 TheRecToAddTo->addTemplateArg(TemplArg);
883 while (Lex.getCode() == tgtok::comma) {
884 Lex.Lex(); // eat the ','
886 // Read the following declarations.
887 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
888 if (TemplArg.empty())
890 TheRecToAddTo->addTemplateArg(TemplArg);
893 if (Lex.getCode() != tgtok::greater)
894 return TokError("expected '>' at end of template argument list");
895 Lex.Lex(); // eat the '>'.
900 /// ParseBodyItem - Parse a single item at within the body of a def or class.
902 /// BodyItem ::= Declaration ';'
903 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
904 bool TGParser::ParseBodyItem(Record *CurRec) {
905 if (Lex.getCode() != tgtok::Let) {
906 if (ParseDeclaration(CurRec, false).empty())
909 if (Lex.getCode() != tgtok::semi)
910 return TokError("expected ';' after declaration");
915 // LET ID OptionalRangeList '=' Value ';'
916 if (Lex.Lex() != tgtok::Id)
917 return TokError("expected field identifier after let");
919 LocTy IdLoc = Lex.getLoc();
920 std::string FieldName = Lex.getCurStrVal();
921 Lex.Lex(); // eat the field name.
923 std::vector<unsigned> BitList;
924 if (ParseOptionalBitList(BitList))
926 std::reverse(BitList.begin(), BitList.end());
928 if (Lex.getCode() != tgtok::equal)
929 return TokError("expected '=' in let expression");
930 Lex.Lex(); // eat the '='.
932 Init *Val = ParseValue(CurRec);
933 if (Val == 0) return true;
935 if (Lex.getCode() != tgtok::semi)
936 return TokError("expected ';' after let expression");
939 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
942 /// ParseBody - Read the body of a class or def. Return true on error, false on
946 /// Body ::= '{' BodyList '}'
947 /// BodyList BodyItem*
949 bool TGParser::ParseBody(Record *CurRec) {
950 // If this is a null definition, just eat the semi and return.
951 if (Lex.getCode() == tgtok::semi) {
956 if (Lex.getCode() != tgtok::l_brace)
957 return TokError("Expected ';' or '{' to start body");
961 while (Lex.getCode() != tgtok::r_brace)
962 if (ParseBodyItem(CurRec))
970 /// ParseObjectBody - Parse the body of a def or class. This consists of an
971 /// optional ClassList followed by a Body. CurRec is the current def or class
972 /// that is being parsed.
974 /// ObjectBody ::= BaseClassList Body
975 /// BaseClassList ::= /*empty*/
976 /// BaseClassList ::= ':' BaseClassListNE
977 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
979 bool TGParser::ParseObjectBody(Record *CurRec) {
980 // If there is a baseclass list, read it.
981 if (Lex.getCode() == tgtok::colon) {
984 // Read all of the subclasses.
985 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
988 if (SubClass.Rec == 0) return true;
991 if (AddSubClass(CurRec, SubClass))
994 if (Lex.getCode() != tgtok::comma) break;
995 Lex.Lex(); // eat ','.
996 SubClass = ParseSubClassReference(CurRec, false);
1000 // Process any variables on the let stack.
1001 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1002 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1003 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1004 LetStack[i][j].Bits, LetStack[i][j].Value))
1007 return ParseBody(CurRec);
1011 /// ParseDef - Parse and return a top level or multiclass def, return the record
1012 /// corresponding to it. This returns null on error.
1014 /// DefInst ::= DEF ObjectName ObjectBody
1016 llvm::Record *TGParser::ParseDef(MultiClass *CurMultiClass) {
1017 LocTy DefLoc = Lex.getLoc();
1018 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1019 Lex.Lex(); // Eat the 'def' token.
1021 // Parse ObjectName and make a record for it.
1022 Record *CurRec = new Record(ParseObjectName());
1024 if (!CurMultiClass) {
1025 // Top-level def definition.
1027 // Ensure redefinition doesn't happen.
1028 if (Records.getDef(CurRec->getName())) {
1029 Error(DefLoc, "def '" + CurRec->getName() + "' already defined");
1032 Records.addDef(CurRec);
1034 // Otherwise, a def inside a multiclass, add it to the multiclass.
1035 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1036 if (CurMultiClass->DefPrototypes[i]->getName() == CurRec->getName()) {
1037 Error(DefLoc, "def '" + CurRec->getName() +
1038 "' already defined in this multiclass!");
1041 CurMultiClass->DefPrototypes.push_back(CurRec);
1044 if (ParseObjectBody(CurRec))
1047 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1048 CurRec->resolveReferences();
1050 // If ObjectBody has template arguments, it's an error.
1051 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1056 /// ParseClass - Parse a tblgen class definition.
1058 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
1060 bool TGParser::ParseClass() {
1061 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
1064 if (Lex.getCode() != tgtok::Id)
1065 return TokError("expected class name after 'class' keyword");
1067 Record *CurRec = Records.getClass(Lex.getCurStrVal());
1069 // If the body was previously defined, this is an error.
1070 if (!CurRec->getValues().empty() ||
1071 !CurRec->getSuperClasses().empty() ||
1072 !CurRec->getTemplateArgs().empty())
1073 return TokError("Class '" + CurRec->getName() + "' already defined");
1075 // If this is the first reference to this class, create and add it.
1076 CurRec = new Record(Lex.getCurStrVal());
1077 Records.addClass(CurRec);
1079 Lex.Lex(); // eat the name.
1081 // If there are template args, parse them.
1082 if (Lex.getCode() == tgtok::less)
1083 if (ParseTemplateArgList(CurRec))
1086 // Finally, parse the object body.
1087 return ParseObjectBody(CurRec);
1090 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
1093 /// LetList ::= LetItem (',' LetItem)*
1094 /// LetItem ::= ID OptionalRangeList '=' Value
1096 std::vector<LetRecord> TGParser::ParseLetList() {
1097 std::vector<LetRecord> Result;
1100 if (Lex.getCode() != tgtok::Id) {
1101 TokError("expected identifier in let definition");
1102 return std::vector<LetRecord>();
1104 std::string Name = Lex.getCurStrVal();
1105 LocTy NameLoc = Lex.getLoc();
1106 Lex.Lex(); // Eat the identifier.
1108 // Check for an optional RangeList.
1109 std::vector<unsigned> Bits;
1110 if (ParseOptionalRangeList(Bits))
1111 return std::vector<LetRecord>();
1112 std::reverse(Bits.begin(), Bits.end());
1114 if (Lex.getCode() != tgtok::equal) {
1115 TokError("expected '=' in let expression");
1116 return std::vector<LetRecord>();
1118 Lex.Lex(); // eat the '='.
1120 Init *Val = ParseValue(0);
1121 if (Val == 0) return std::vector<LetRecord>();
1123 // Now that we have everything, add the record.
1124 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
1126 if (Lex.getCode() != tgtok::comma)
1128 Lex.Lex(); // eat the comma.
1132 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
1133 /// different related productions.
1135 /// Object ::= LET LetList IN '{' ObjectList '}'
1136 /// Object ::= LET LetList IN Object
1138 bool TGParser::ParseTopLevelLet() {
1139 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
1142 // Add this entry to the let stack.
1143 std::vector<LetRecord> LetInfo = ParseLetList();
1144 if (LetInfo.empty()) return true;
1145 LetStack.push_back(LetInfo);
1147 if (Lex.getCode() != tgtok::In)
1148 return TokError("expected 'in' at end of top-level 'let'");
1151 // If this is a scalar let, just handle it now
1152 if (Lex.getCode() != tgtok::l_brace) {
1153 // LET LetList IN Object
1156 } else { // Object ::= LETCommand '{' ObjectList '}'
1157 LocTy BraceLoc = Lex.getLoc();
1158 // Otherwise, this is a group let.
1159 Lex.Lex(); // eat the '{'.
1161 // Parse the object list.
1162 if (ParseObjectList())
1165 if (Lex.getCode() != tgtok::r_brace) {
1166 TokError("expected '}' at end of top level let command");
1167 return Error(BraceLoc, "to match this '{'");
1172 // Outside this let scope, this let block is not active.
1173 LetStack.pop_back();
1177 /// ParseMultiClassDef - Parse a def in a multiclass context.
1179 /// MultiClassDef ::= DefInst
1181 bool TGParser::ParseMultiClassDef(MultiClass *CurMC) {
1182 if (Lex.getCode() != tgtok::Def)
1183 return TokError("expected 'def' in multiclass body");
1185 Record *D = ParseDef(CurMC);
1186 if (D == 0) return true;
1188 // Copy the template arguments for the multiclass into the def.
1189 const std::vector<std::string> &TArgs = CurMC->Rec.getTemplateArgs();
1191 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1192 const RecordVal *RV = CurMC->Rec.getValue(TArgs[i]);
1193 assert(RV && "Template arg doesn't exist?");
1200 /// ParseMultiClass - Parse a multiclass definition.
1202 /// MultiClassInst ::= MULTICLASS ID TemplateArgList? '{' MultiClassDef+ '}'
1204 bool TGParser::ParseMultiClass() {
1205 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
1206 Lex.Lex(); // Eat the multiclass token.
1208 if (Lex.getCode() != tgtok::Id)
1209 return TokError("expected identifier after multiclass for name");
1210 std::string Name = Lex.getCurStrVal();
1212 if (MultiClasses.count(Name))
1213 return TokError("multiclass '" + Name + "' already defined");
1215 CurMultiClass = MultiClasses[Name] = new MultiClass(Name);
1216 Lex.Lex(); // Eat the identifier.
1218 // If there are template args, parse them.
1219 if (Lex.getCode() == tgtok::less)
1220 if (ParseTemplateArgList(0))
1223 if (Lex.getCode() != tgtok::l_brace)
1224 return TokError("expected '{' in multiclass definition");
1226 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
1227 return TokError("multiclass must contain at least one def");
1229 while (Lex.getCode() != tgtok::r_brace)
1230 if (ParseMultiClassDef(CurMultiClass))
1233 Lex.Lex(); // eat the '}'.
1239 /// ParseDefm - Parse the instantiation of a multiclass.
1241 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
1243 bool TGParser::ParseDefm() {
1244 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
1245 if (Lex.Lex() != tgtok::Id) // eat the defm.
1246 return TokError("expected identifier after defm");
1248 LocTy DefmPrefixLoc = Lex.getLoc();
1249 std::string DefmPrefix = Lex.getCurStrVal();
1250 if (Lex.Lex() != tgtok::colon)
1251 return TokError("expected ':' after defm identifier");
1256 LocTy SubClassLoc = Lex.getLoc();
1257 SubClassReference Ref = ParseSubClassReference(0, true);
1258 if (Ref.Rec == 0) return true;
1260 if (Lex.getCode() != tgtok::semi)
1261 return TokError("expected ';' at end of defm");
1264 // To instantiate a multiclass, we need to first get the multiclass, then
1265 // instantiate each def contained in the multiclass with the SubClassRef
1266 // template parameters.
1267 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
1268 assert(MC && "Didn't lookup multiclass correctly?");
1269 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
1271 // Verify that the correct number of template arguments were specified.
1272 const std::vector<std::string> &TArgs = MC->Rec.getTemplateArgs();
1273 if (TArgs.size() < TemplateVals.size())
1274 return Error(SubClassLoc,
1275 "more template args specified than multiclass expects");
1277 // Loop over all the def's in the multiclass, instantiating each one.
1278 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
1279 Record *DefProto = MC->DefPrototypes[i];
1281 // Add the suffix to the defm name to get the new name.
1282 Record *CurRec = new Record(DefmPrefix + DefProto->getName());
1284 SubClassReference Ref;
1285 Ref.RefLoc = DefmPrefixLoc;
1287 AddSubClass(CurRec, Ref);
1289 // Loop over all of the template arguments, setting them to the specified
1290 // value or leaving them as the default if necessary.
1291 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1292 if (i < TemplateVals.size()) { // A value is specified for this temp-arg?
1294 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
1299 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
1302 CurRec->removeValue(TArgs[i]);
1304 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
1305 return Error(SubClassLoc, "value not specified for template argument #"+
1306 utostr(i) + " (" + TArgs[i] + ") of multiclassclass '" +
1307 MC->Rec.getName() + "'");
1311 // If the mdef is inside a 'let' expression, add to each def.
1312 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1313 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1314 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1315 LetStack[i][j].Bits, LetStack[i][j].Value)) {
1316 Error(DefmPrefixLoc, "when instantiating this defm");
1321 // Ensure redefinition doesn't happen.
1322 if (Records.getDef(CurRec->getName()))
1323 return Error(DefmPrefixLoc, "def '" + CurRec->getName() +
1324 "' already defined, instantiating defm with subdef '" +
1325 DefProto->getName() + "'");
1326 Records.addDef(CurRec);
1327 CurRec->resolveReferences();
1334 /// Object ::= ClassInst
1335 /// Object ::= DefInst
1336 /// Object ::= MultiClassInst
1337 /// Object ::= DefMInst
1338 /// Object ::= LETCommand '{' ObjectList '}'
1339 /// Object ::= LETCommand Object
1340 bool TGParser::ParseObject() {
1341 switch (Lex.getCode()) {
1342 default: assert(0 && "This is not an object");
1343 case tgtok::Let: return ParseTopLevelLet();
1344 case tgtok::Def: return ParseDef(0) == 0;
1345 case tgtok::Defm: return ParseDefm();
1346 case tgtok::Class: return ParseClass();
1347 case tgtok::MultiClass: return ParseMultiClass();
1352 /// ObjectList :== Object*
1353 bool TGParser::ParseObjectList() {
1354 while (isObjectStart(Lex.getCode())) {
1362 bool TGParser::ParseFile() {
1363 Lex.Lex(); // Prime the lexer.
1364 if (ParseObjectList()) return true;
1366 // If we have unread input at the end of the file, report it.
1367 if (Lex.getCode() == tgtok::Eof)
1370 return TokError("Unexpected input at top level");