1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Implement the Parser for TableGen.
12 //===----------------------------------------------------------------------===//
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/TableGen/Record.h"
23 //===----------------------------------------------------------------------===//
24 // Support Code for the Semantic Actions.
25 //===----------------------------------------------------------------------===//
28 struct SubClassReference {
31 std::vector<Init*> TemplateArgs;
32 SubClassReference() : Rec(0) {}
34 bool isInvalid() const { return Rec == 0; }
37 struct SubMultiClassReference {
40 std::vector<Init*> TemplateArgs;
41 SubMultiClassReference() : MC(0) {}
43 bool isInvalid() const { return MC == 0; }
47 void SubMultiClassReference::dump() const {
48 errs() << "Multiclass:\n";
52 errs() << "Template args:\n";
53 for (std::vector<Init *>::const_iterator i = TemplateArgs.begin(),
54 iend = TemplateArgs.end();
61 } // end namespace llvm
63 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
65 CurRec = &CurMultiClass->Rec;
67 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
68 // The value already exists in the class, treat this as a set.
69 if (ERV->setValue(RV.getValue()))
70 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
71 RV.getType()->getAsString() + "' is incompatible with " +
72 "previous definition of type '" +
73 ERV->getType()->getAsString() + "'");
81 /// Return true on error, false on success.
82 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
83 const std::vector<unsigned> &BitList, Init *V) {
86 if (CurRec == 0) CurRec = &CurMultiClass->Rec;
88 RecordVal *RV = CurRec->getValue(ValName);
90 return Error(Loc, "Value '" + ValName->getAsUnquotedString()
93 // Do not allow assignments like 'X = X'. This will just cause infinite loops
94 // in the resolution machinery.
96 if (VarInit *VI = dyn_cast<VarInit>(V))
97 if (VI->getNameInit() == ValName)
100 // If we are assigning to a subset of the bits in the value... then we must be
101 // assigning to a field of BitsRecTy, which must have a BitsInit
104 if (!BitList.empty()) {
105 BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
107 return Error(Loc, "Value '" + ValName->getAsUnquotedString()
108 + "' is not a bits type");
110 // Convert the incoming value to a bits type of the appropriate size...
111 Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size()));
113 return Error(Loc, "Initializer is not compatible with bit range");
116 // We should have a BitsInit type now.
117 BitsInit *BInit = dyn_cast<BitsInit>(BI);
120 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
122 // Loop over bits, assigning values as appropriate.
123 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
124 unsigned Bit = BitList[i];
126 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
127 ValName->getAsUnquotedString() + "' more than once");
128 NewBits[Bit] = BInit->getBit(i);
131 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
133 NewBits[i] = CurVal->getBit(i);
135 V = BitsInit::get(NewBits);
139 return Error(Loc, "Value '" + ValName->getAsUnquotedString() + "' of type '"
140 + RV->getType()->getAsString() +
141 "' is incompatible with initializer '" + V->getAsString()
146 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
147 /// args as SubClass's template arguments.
148 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
149 Record *SC = SubClass.Rec;
150 // Add all of the values in the subclass into the current class.
151 const std::vector<RecordVal> &Vals = SC->getValues();
152 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
153 if (AddValue(CurRec, SubClass.RefRange.Start, Vals[i]))
156 const std::vector<Init *> &TArgs = SC->getTemplateArgs();
158 // Ensure that an appropriate number of template arguments are specified.
159 if (TArgs.size() < SubClass.TemplateArgs.size())
160 return Error(SubClass.RefRange.Start,
161 "More template args specified than expected");
163 // Loop over all of the template arguments, setting them to the specified
164 // value or leaving them as the default if necessary.
165 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
166 if (i < SubClass.TemplateArgs.size()) {
167 // If a value is specified for this template arg, set it now.
168 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
169 std::vector<unsigned>(), SubClass.TemplateArgs[i]))
173 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
176 CurRec->removeValue(TArgs[i]);
178 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
179 return Error(SubClass.RefRange.Start,
180 "Value not specified for template argument #"
181 + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
182 + ") of subclass '" + SC->getNameInitAsString() + "'!");
186 // Since everything went well, we can now set the "superclass" list for the
188 const std::vector<Record*> &SCs = SC->getSuperClasses();
189 ArrayRef<SMRange> SCRanges = SC->getSuperClassRanges();
190 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
191 if (CurRec->isSubClassOf(SCs[i]))
192 return Error(SubClass.RefRange.Start,
193 "Already subclass of '" + SCs[i]->getName() + "'!\n");
194 CurRec->addSuperClass(SCs[i], SCRanges[i]);
197 if (CurRec->isSubClassOf(SC))
198 return Error(SubClass.RefRange.Start,
199 "Already subclass of '" + SC->getName() + "'!\n");
200 CurRec->addSuperClass(SC, SubClass.RefRange);
204 /// AddSubMultiClass - Add SubMultiClass as a subclass to
205 /// CurMC, resolving its template args as SubMultiClass's
206 /// template arguments.
207 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
208 SubMultiClassReference &SubMultiClass) {
209 MultiClass *SMC = SubMultiClass.MC;
210 Record *CurRec = &CurMC->Rec;
212 const std::vector<RecordVal> &MCVals = CurRec->getValues();
214 // Add all of the values in the subclass into the current class.
215 const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
216 for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
217 if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVals[i]))
220 int newDefStart = CurMC->DefPrototypes.size();
222 // Add all of the defs in the subclass into the current multiclass.
223 for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
224 iend = SMC->DefPrototypes.end();
227 // Clone the def and add it to the current multiclass
228 Record *NewDef = new Record(**i);
230 // Add all of the values in the superclass into the current def.
231 for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
232 if (AddValue(NewDef, SubMultiClass.RefRange.Start, MCVals[i]))
235 CurMC->DefPrototypes.push_back(NewDef);
238 const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
240 // Ensure that an appropriate number of template arguments are
242 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
243 return Error(SubMultiClass.RefRange.Start,
244 "More template args specified than expected");
246 // Loop over all of the template arguments, setting them to the specified
247 // value or leaving them as the default if necessary.
248 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
249 if (i < SubMultiClass.TemplateArgs.size()) {
250 // If a value is specified for this template arg, set it in the
252 if (SetValue(CurRec, SubMultiClass.RefRange.Start, SMCTArgs[i],
253 std::vector<unsigned>(),
254 SubMultiClass.TemplateArgs[i]))
258 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
261 CurRec->removeValue(SMCTArgs[i]);
263 // If a value is specified for this template arg, set it in the
265 for (MultiClass::RecordVector::iterator j =
266 CurMC->DefPrototypes.begin() + newDefStart,
267 jend = CurMC->DefPrototypes.end();
272 if (SetValue(Def, SubMultiClass.RefRange.Start, SMCTArgs[i],
273 std::vector<unsigned>(),
274 SubMultiClass.TemplateArgs[i]))
278 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
281 Def->removeValue(SMCTArgs[i]);
283 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
284 return Error(SubMultiClass.RefRange.Start,
285 "Value not specified for template argument #"
286 + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
287 + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
294 /// ProcessForeachDefs - Given a record, apply all of the variable
295 /// values in all surrounding foreach loops, creating new records for
296 /// each combination of values.
297 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
301 // We want to instantiate a new copy of CurRec for each combination
302 // of nested loop iterator values. We don't want top instantiate
303 // any copies until we have values for each loop iterator.
305 return ProcessForeachDefs(CurRec, Loc, IterVals);
308 /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
309 /// apply each of the variable values in this loop and then process
311 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
312 // Recursively build a tuple of iterator values.
313 if (IterVals.size() != Loops.size()) {
314 assert(IterVals.size() < Loops.size());
315 ForeachLoop &CurLoop = Loops[IterVals.size()];
316 ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
318 Error(Loc, "Loop list is not a list");
322 // Process each value.
323 for (int64_t i = 0; i < List->getSize(); ++i) {
324 Init *ItemVal = List->resolveListElementReference(*CurRec, 0, i);
325 IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
326 if (ProcessForeachDefs(CurRec, Loc, IterVals))
333 // This is the bottom of the recursion. We have all of the iterator values
334 // for this point in the iteration space. Instantiate a new record to
335 // reflect this combination of values.
336 Record *IterRec = new Record(*CurRec);
338 // Set the iterator values now.
339 for (unsigned i = 0, e = IterVals.size(); i != e; ++i) {
340 VarInit *IterVar = IterVals[i].IterVar;
341 TypedInit *IVal = dyn_cast<TypedInit>(IterVals[i].IterValue);
343 Error(Loc, "foreach iterator value is untyped");
347 IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
349 if (SetValue(IterRec, Loc, IterVar->getName(),
350 std::vector<unsigned>(), IVal)) {
351 Error(Loc, "when instantiating this def");
356 IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
359 IterRec->removeValue(IterVar->getName());
362 if (Records.getDef(IterRec->getNameInitAsString())) {
363 Error(Loc, "def already exists: " + IterRec->getNameInitAsString());
367 Records.addDef(IterRec);
368 IterRec->resolveReferences();
372 //===----------------------------------------------------------------------===//
374 //===----------------------------------------------------------------------===//
376 /// isObjectStart - Return true if this is a valid first token for an Object.
377 static bool isObjectStart(tgtok::TokKind K) {
378 return K == tgtok::Class || K == tgtok::Def ||
379 K == tgtok::Defm || K == tgtok::Let ||
380 K == tgtok::MultiClass || K == tgtok::Foreach;
383 static std::string GetNewAnonymousName() {
384 static unsigned AnonCounter = 0;
385 unsigned Tmp = AnonCounter++; // MSVC2012 ICEs without this.
386 return "anonymous." + utostr(Tmp);
389 /// ParseObjectName - If an object name is specified, return it. Otherwise,
391 /// ObjectName ::= Value [ '#' Value ]*
392 /// ObjectName ::= /*empty*/
394 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
395 switch (Lex.getCode()) {
399 // These are all of the tokens that can begin an object body.
400 // Some of these can also begin values but we disallow those cases
401 // because they are unlikely to be useful.
409 CurRec = &CurMultiClass->Rec;
413 const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
415 TokError("Record name is not typed!");
418 Type = CurRecName->getType();
421 return ParseValue(CurRec, Type, ParseNameMode);
424 /// ParseClassID - Parse and resolve a reference to a class name. This returns
429 Record *TGParser::ParseClassID() {
430 if (Lex.getCode() != tgtok::Id) {
431 TokError("expected name for ClassID");
435 Record *Result = Records.getClass(Lex.getCurStrVal());
437 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
443 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
444 /// This returns null on error.
446 /// MultiClassID ::= ID
448 MultiClass *TGParser::ParseMultiClassID() {
449 if (Lex.getCode() != tgtok::Id) {
450 TokError("expected name for MultiClassID");
454 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
456 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
462 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
463 /// subclass. This returns a SubClassRefTy with a null Record* on error.
465 /// SubClassRef ::= ClassID
466 /// SubClassRef ::= ClassID '<' ValueList '>'
468 SubClassReference TGParser::
469 ParseSubClassReference(Record *CurRec, bool isDefm) {
470 SubClassReference Result;
471 Result.RefRange.Start = Lex.getLoc();
474 if (MultiClass *MC = ParseMultiClassID())
475 Result.Rec = &MC->Rec;
477 Result.Rec = ParseClassID();
479 if (Result.Rec == 0) return Result;
481 // If there is no template arg list, we're done.
482 if (Lex.getCode() != tgtok::less) {
483 Result.RefRange.End = Lex.getLoc();
486 Lex.Lex(); // Eat the '<'
488 if (Lex.getCode() == tgtok::greater) {
489 TokError("subclass reference requires a non-empty list of template values");
494 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
495 if (Result.TemplateArgs.empty()) {
496 Result.Rec = 0; // Error parsing value list.
500 if (Lex.getCode() != tgtok::greater) {
501 TokError("expected '>' in template value list");
506 Result.RefRange.End = Lex.getLoc();
511 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
512 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
513 /// Record* on error.
515 /// SubMultiClassRef ::= MultiClassID
516 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
518 SubMultiClassReference TGParser::
519 ParseSubMultiClassReference(MultiClass *CurMC) {
520 SubMultiClassReference Result;
521 Result.RefRange.Start = Lex.getLoc();
523 Result.MC = ParseMultiClassID();
524 if (Result.MC == 0) return Result;
526 // If there is no template arg list, we're done.
527 if (Lex.getCode() != tgtok::less) {
528 Result.RefRange.End = Lex.getLoc();
531 Lex.Lex(); // Eat the '<'
533 if (Lex.getCode() == tgtok::greater) {
534 TokError("subclass reference requires a non-empty list of template values");
539 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
540 if (Result.TemplateArgs.empty()) {
541 Result.MC = 0; // Error parsing value list.
545 if (Lex.getCode() != tgtok::greater) {
546 TokError("expected '>' in template value list");
551 Result.RefRange.End = Lex.getLoc();
556 /// ParseRangePiece - Parse a bit/value range.
557 /// RangePiece ::= INTVAL
558 /// RangePiece ::= INTVAL '-' INTVAL
559 /// RangePiece ::= INTVAL INTVAL
560 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
561 if (Lex.getCode() != tgtok::IntVal) {
562 TokError("expected integer or bitrange");
565 int64_t Start = Lex.getCurIntVal();
569 return TokError("invalid range, cannot be negative");
571 switch (Lex.Lex()) { // eat first character.
573 Ranges.push_back(Start);
576 if (Lex.Lex() != tgtok::IntVal) {
577 TokError("expected integer value as end of range");
580 End = Lex.getCurIntVal();
583 End = -Lex.getCurIntVal();
587 return TokError("invalid range, cannot be negative");
592 for (; Start <= End; ++Start)
593 Ranges.push_back(Start);
595 for (; Start >= End; --Start)
596 Ranges.push_back(Start);
601 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
603 /// RangeList ::= RangePiece (',' RangePiece)*
605 std::vector<unsigned> TGParser::ParseRangeList() {
606 std::vector<unsigned> Result;
608 // Parse the first piece.
609 if (ParseRangePiece(Result))
610 return std::vector<unsigned>();
611 while (Lex.getCode() == tgtok::comma) {
612 Lex.Lex(); // Eat the comma.
614 // Parse the next range piece.
615 if (ParseRangePiece(Result))
616 return std::vector<unsigned>();
621 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
622 /// OptionalRangeList ::= '<' RangeList '>'
623 /// OptionalRangeList ::= /*empty*/
624 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
625 if (Lex.getCode() != tgtok::less)
628 SMLoc StartLoc = Lex.getLoc();
629 Lex.Lex(); // eat the '<'
631 // Parse the range list.
632 Ranges = ParseRangeList();
633 if (Ranges.empty()) return true;
635 if (Lex.getCode() != tgtok::greater) {
636 TokError("expected '>' at end of range list");
637 return Error(StartLoc, "to match this '<'");
639 Lex.Lex(); // eat the '>'.
643 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
644 /// OptionalBitList ::= '{' RangeList '}'
645 /// OptionalBitList ::= /*empty*/
646 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
647 if (Lex.getCode() != tgtok::l_brace)
650 SMLoc StartLoc = Lex.getLoc();
651 Lex.Lex(); // eat the '{'
653 // Parse the range list.
654 Ranges = ParseRangeList();
655 if (Ranges.empty()) return true;
657 if (Lex.getCode() != tgtok::r_brace) {
658 TokError("expected '}' at end of bit list");
659 return Error(StartLoc, "to match this '{'");
661 Lex.Lex(); // eat the '}'.
666 /// ParseType - Parse and return a tblgen type. This returns null on error.
668 /// Type ::= STRING // string type
669 /// Type ::= CODE // code type
670 /// Type ::= BIT // bit type
671 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
672 /// Type ::= INT // int type
673 /// Type ::= LIST '<' Type '>' // list<x> type
674 /// Type ::= DAG // dag type
675 /// Type ::= ClassID // Record Type
677 RecTy *TGParser::ParseType() {
678 switch (Lex.getCode()) {
679 default: TokError("Unknown token when expecting a type"); return 0;
680 case tgtok::String: Lex.Lex(); return StringRecTy::get();
681 case tgtok::Code: Lex.Lex(); return StringRecTy::get();
682 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
683 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
684 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
686 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
689 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
690 TokError("expected '<' after bits type");
693 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
694 TokError("expected integer in bits<n> type");
697 uint64_t Val = Lex.getCurIntVal();
698 if (Lex.Lex() != tgtok::greater) { // Eat count.
699 TokError("expected '>' at end of bits<n> type");
702 Lex.Lex(); // Eat '>'
703 return BitsRecTy::get(Val);
706 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
707 TokError("expected '<' after list type");
710 Lex.Lex(); // Eat '<'
711 RecTy *SubType = ParseType();
712 if (SubType == 0) return 0;
714 if (Lex.getCode() != tgtok::greater) {
715 TokError("expected '>' at end of list<ty> type");
718 Lex.Lex(); // Eat '>'
719 return ListRecTy::get(SubType);
724 /// ParseIDValue - Parse an ID as a value and decode what it means.
726 /// IDValue ::= ID [def local value]
727 /// IDValue ::= ID [def template arg]
728 /// IDValue ::= ID [multiclass local value]
729 /// IDValue ::= ID [multiclass template argument]
730 /// IDValue ::= ID [def name]
732 Init *TGParser::ParseIDValue(Record *CurRec, IDParseMode Mode) {
733 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
734 std::string Name = Lex.getCurStrVal();
735 SMLoc Loc = Lex.getLoc();
737 return ParseIDValue(CurRec, Name, Loc);
740 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
741 /// has already been read.
742 Init *TGParser::ParseIDValue(Record *CurRec,
743 const std::string &Name, SMLoc NameLoc,
746 if (const RecordVal *RV = CurRec->getValue(Name))
747 return VarInit::get(Name, RV->getType());
749 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
752 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
755 if (CurRec->isTemplateArg(TemplateArgName)) {
756 const RecordVal *RV = CurRec->getValue(TemplateArgName);
757 assert(RV && "Template arg doesn't exist??");
758 return VarInit::get(TemplateArgName, RV->getType());
763 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
766 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
767 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
768 assert(RV && "Template arg doesn't exist??");
769 return VarInit::get(MCName, RV->getType());
773 // If this is in a foreach loop, make sure it's not a loop iterator
774 for (LoopVector::iterator i = Loops.begin(), iend = Loops.end();
777 VarInit *IterVar = dyn_cast<VarInit>(i->IterVar);
778 if (IterVar && IterVar->getName() == Name)
782 if (Mode == ParseNameMode)
783 return StringInit::get(Name);
785 if (Record *D = Records.getDef(Name))
786 return DefInit::get(D);
788 if (Mode == ParseValueMode) {
789 Error(NameLoc, "Variable not defined: '" + Name + "'");
793 return StringInit::get(Name);
796 /// ParseOperation - Parse an operator. This returns null on error.
798 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
800 Init *TGParser::ParseOperation(Record *CurRec) {
801 switch (Lex.getCode()) {
803 TokError("unknown operation");
808 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
809 UnOpInit::UnaryOp Code;
812 switch (Lex.getCode()) {
813 default: llvm_unreachable("Unhandled code!");
815 Lex.Lex(); // eat the operation
816 Code = UnOpInit::CAST;
818 Type = ParseOperatorType();
821 TokError("did not get type for unary operator");
827 Lex.Lex(); // eat the operation
828 Code = UnOpInit::HEAD;
831 Lex.Lex(); // eat the operation
832 Code = UnOpInit::TAIL;
835 Lex.Lex(); // eat the operation
836 Code = UnOpInit::EMPTY;
837 Type = IntRecTy::get();
840 if (Lex.getCode() != tgtok::l_paren) {
841 TokError("expected '(' after unary operator");
844 Lex.Lex(); // eat the '('
846 Init *LHS = ParseValue(CurRec);
847 if (LHS == 0) return 0;
849 if (Code == UnOpInit::HEAD
850 || Code == UnOpInit::TAIL
851 || Code == UnOpInit::EMPTY) {
852 ListInit *LHSl = dyn_cast<ListInit>(LHS);
853 StringInit *LHSs = dyn_cast<StringInit>(LHS);
854 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
855 if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
856 TokError("expected list or string type argument in unary operator");
860 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
861 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
862 if (LType == 0 && SType == 0) {
863 TokError("expected list or string type argumnet in unary operator");
868 if (Code == UnOpInit::HEAD
869 || Code == UnOpInit::TAIL) {
870 if (LHSl == 0 && LHSt == 0) {
871 TokError("expected list type argumnet in unary operator");
875 if (LHSl && LHSl->getSize() == 0) {
876 TokError("empty list argument in unary operator");
880 Init *Item = LHSl->getElement(0);
881 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
883 TokError("untyped list element in unary operator");
886 if (Code == UnOpInit::HEAD) {
887 Type = Itemt->getType();
889 Type = ListRecTy::get(Itemt->getType());
892 assert(LHSt && "expected list type argument in unary operator");
893 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
895 TokError("expected list type argumnet in unary operator");
898 if (Code == UnOpInit::HEAD) {
899 Type = LType->getElementType();
907 if (Lex.getCode() != tgtok::r_paren) {
908 TokError("expected ')' in unary operator");
911 Lex.Lex(); // eat the ')'
912 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
921 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
922 tgtok::TokKind OpTok = Lex.getCode();
923 SMLoc OpLoc = Lex.getLoc();
924 Lex.Lex(); // eat the operation
926 BinOpInit::BinaryOp Code;
930 default: llvm_unreachable("Unhandled code!");
931 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
932 case tgtok::XADD: Code = BinOpInit::ADD; Type = IntRecTy::get(); break;
933 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
934 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
935 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
936 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
937 case tgtok::XStrConcat:
938 Code = BinOpInit::STRCONCAT;
939 Type = StringRecTy::get();
943 if (Lex.getCode() != tgtok::l_paren) {
944 TokError("expected '(' after binary operator");
947 Lex.Lex(); // eat the '('
949 SmallVector<Init*, 2> InitList;
951 InitList.push_back(ParseValue(CurRec));
952 if (InitList.back() == 0) return 0;
954 while (Lex.getCode() == tgtok::comma) {
955 Lex.Lex(); // eat the ','
957 InitList.push_back(ParseValue(CurRec));
958 if (InitList.back() == 0) return 0;
961 if (Lex.getCode() != tgtok::r_paren) {
962 TokError("expected ')' in operator");
965 Lex.Lex(); // eat the ')'
967 // We allow multiple operands to associative operators like !strconcat as
968 // shorthand for nesting them.
969 if (Code == BinOpInit::STRCONCAT) {
970 while (InitList.size() > 2) {
971 Init *RHS = InitList.pop_back_val();
972 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
973 ->Fold(CurRec, CurMultiClass);
974 InitList.back() = RHS;
978 if (InitList.size() == 2)
979 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
980 ->Fold(CurRec, CurMultiClass);
982 Error(OpLoc, "expected two operands to operator");
987 case tgtok::XForEach:
988 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
989 TernOpInit::TernaryOp Code;
992 tgtok::TokKind LexCode = Lex.getCode();
993 Lex.Lex(); // eat the operation
995 default: llvm_unreachable("Unhandled code!");
997 Code = TernOpInit::IF;
999 case tgtok::XForEach:
1000 Code = TernOpInit::FOREACH;
1003 Code = TernOpInit::SUBST;
1006 if (Lex.getCode() != tgtok::l_paren) {
1007 TokError("expected '(' after ternary operator");
1010 Lex.Lex(); // eat the '('
1012 Init *LHS = ParseValue(CurRec);
1013 if (LHS == 0) return 0;
1015 if (Lex.getCode() != tgtok::comma) {
1016 TokError("expected ',' in ternary operator");
1019 Lex.Lex(); // eat the ','
1021 Init *MHS = ParseValue(CurRec);
1022 if (MHS == 0) return 0;
1024 if (Lex.getCode() != tgtok::comma) {
1025 TokError("expected ',' in ternary operator");
1028 Lex.Lex(); // eat the ','
1030 Init *RHS = ParseValue(CurRec);
1031 if (RHS == 0) return 0;
1033 if (Lex.getCode() != tgtok::r_paren) {
1034 TokError("expected ')' in binary operator");
1037 Lex.Lex(); // eat the ')'
1040 default: llvm_unreachable("Unhandled code!");
1045 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1046 MHSTy = MHSt->getType();
1047 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1048 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1049 if (isa<BitInit>(MHS))
1050 MHSTy = BitRecTy::get();
1052 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1053 RHSTy = RHSt->getType();
1054 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1055 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1056 if (isa<BitInit>(RHS))
1057 RHSTy = BitRecTy::get();
1059 // For UnsetInit, it's typed from the other hand.
1060 if (isa<UnsetInit>(MHS))
1062 if (isa<UnsetInit>(RHS))
1065 if (!MHSTy || !RHSTy) {
1066 TokError("could not get type for !if");
1070 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1072 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1075 TokError("inconsistent types for !if");
1080 case tgtok::XForEach: {
1081 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1083 TokError("could not get type for !foreach");
1086 Type = MHSt->getType();
1089 case tgtok::XSubst: {
1090 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1092 TokError("could not get type for !subst");
1095 Type = RHSt->getType();
1099 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1105 /// ParseOperatorType - Parse a type for an operator. This returns
1108 /// OperatorType ::= '<' Type '>'
1110 RecTy *TGParser::ParseOperatorType() {
1113 if (Lex.getCode() != tgtok::less) {
1114 TokError("expected type name for operator");
1117 Lex.Lex(); // eat the <
1122 TokError("expected type name for operator");
1126 if (Lex.getCode() != tgtok::greater) {
1127 TokError("expected type name for operator");
1130 Lex.Lex(); // eat the >
1136 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1138 /// SimpleValue ::= IDValue
1139 /// SimpleValue ::= INTVAL
1140 /// SimpleValue ::= STRVAL+
1141 /// SimpleValue ::= CODEFRAGMENT
1142 /// SimpleValue ::= '?'
1143 /// SimpleValue ::= '{' ValueList '}'
1144 /// SimpleValue ::= ID '<' ValueListNE '>'
1145 /// SimpleValue ::= '[' ValueList ']'
1146 /// SimpleValue ::= '(' IDValue DagArgList ')'
1147 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1148 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1149 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1150 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1151 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1152 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1154 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1157 switch (Lex.getCode()) {
1158 default: TokError("Unknown token when parsing a value"); break;
1160 // This is a leading paste operation. This is deprecated but
1161 // still exists in some .td files. Ignore it.
1162 Lex.Lex(); // Skip '#'.
1163 return ParseSimpleValue(CurRec, ItemType, Mode);
1164 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1165 case tgtok::StrVal: {
1166 std::string Val = Lex.getCurStrVal();
1169 // Handle multiple consecutive concatenated strings.
1170 while (Lex.getCode() == tgtok::StrVal) {
1171 Val += Lex.getCurStrVal();
1175 R = StringInit::get(Val);
1178 case tgtok::CodeFragment:
1179 R = StringInit::get(Lex.getCurStrVal());
1182 case tgtok::question:
1183 R = UnsetInit::get();
1187 SMLoc NameLoc = Lex.getLoc();
1188 std::string Name = Lex.getCurStrVal();
1189 if (Lex.Lex() != tgtok::less) // consume the Id.
1190 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1192 // Value ::= ID '<' ValueListNE '>'
1193 if (Lex.Lex() == tgtok::greater) {
1194 TokError("expected non-empty value list");
1198 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1199 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1201 Record *Class = Records.getClass(Name);
1203 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1207 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1208 if (ValueList.empty()) return 0;
1210 if (Lex.getCode() != tgtok::greater) {
1211 TokError("expected '>' at end of value list");
1214 Lex.Lex(); // eat the '>'
1215 SMLoc EndLoc = Lex.getLoc();
1217 // Create the new record, set it as CurRec temporarily.
1218 static unsigned AnonCounter = 0;
1219 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),
1222 /*IsAnonymous=*/true);
1223 SubClassReference SCRef;
1224 SCRef.RefRange = SMRange(NameLoc, EndLoc);
1226 SCRef.TemplateArgs = ValueList;
1227 // Add info about the subclass to NewRec.
1228 if (AddSubClass(NewRec, SCRef))
1230 NewRec->resolveReferences();
1231 Records.addDef(NewRec);
1233 // The result of the expression is a reference to the new record.
1234 return DefInit::get(NewRec);
1236 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1237 SMLoc BraceLoc = Lex.getLoc();
1238 Lex.Lex(); // eat the '{'
1239 std::vector<Init*> Vals;
1241 if (Lex.getCode() != tgtok::r_brace) {
1242 Vals = ParseValueList(CurRec);
1243 if (Vals.empty()) return 0;
1245 if (Lex.getCode() != tgtok::r_brace) {
1246 TokError("expected '}' at end of bit list value");
1249 Lex.Lex(); // eat the '}'
1251 SmallVector<Init *, 16> NewBits(Vals.size());
1253 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1254 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1256 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1257 ") is not convertable to a bit");
1260 NewBits[Vals.size()-i-1] = Bit;
1262 return BitsInit::get(NewBits);
1264 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1265 Lex.Lex(); // eat the '['
1266 std::vector<Init*> Vals;
1268 RecTy *DeducedEltTy = 0;
1269 ListRecTy *GivenListTy = 0;
1271 if (ItemType != 0) {
1272 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1273 if (ListType == 0) {
1274 std::stringstream s;
1275 s << "Type mismatch for list, expected list type, got "
1276 << ItemType->getAsString();
1280 GivenListTy = ListType;
1283 if (Lex.getCode() != tgtok::r_square) {
1284 Vals = ParseValueList(CurRec, 0,
1285 GivenListTy ? GivenListTy->getElementType() : 0);
1286 if (Vals.empty()) return 0;
1288 if (Lex.getCode() != tgtok::r_square) {
1289 TokError("expected ']' at end of list value");
1292 Lex.Lex(); // eat the ']'
1294 RecTy *GivenEltTy = 0;
1295 if (Lex.getCode() == tgtok::less) {
1296 // Optional list element type
1297 Lex.Lex(); // eat the '<'
1299 GivenEltTy = ParseType();
1300 if (GivenEltTy == 0) {
1301 // Couldn't parse element type
1305 if (Lex.getCode() != tgtok::greater) {
1306 TokError("expected '>' at end of list element type");
1309 Lex.Lex(); // eat the '>'
1314 for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1317 TypedInit *TArg = dyn_cast<TypedInit>(*i);
1319 TokError("Untyped list element");
1323 EltTy = resolveTypes(EltTy, TArg->getType());
1325 TokError("Incompatible types in list elements");
1329 EltTy = TArg->getType();
1333 if (GivenEltTy != 0) {
1335 // Verify consistency
1336 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1337 TokError("Incompatible types in list elements");
1345 if (ItemType == 0) {
1346 TokError("No type for list");
1349 DeducedEltTy = GivenListTy->getElementType();
1351 // Make sure the deduced type is compatible with the given type
1353 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1354 TokError("Element type mismatch for list");
1358 DeducedEltTy = EltTy;
1361 return ListInit::get(Vals, DeducedEltTy);
1363 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1364 Lex.Lex(); // eat the '('
1365 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1366 TokError("expected identifier in dag init");
1370 Init *Operator = ParseValue(CurRec);
1371 if (Operator == 0) return 0;
1373 // If the operator name is present, parse it.
1374 std::string OperatorName;
1375 if (Lex.getCode() == tgtok::colon) {
1376 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1377 TokError("expected variable name in dag operator");
1380 OperatorName = Lex.getCurStrVal();
1381 Lex.Lex(); // eat the VarName.
1384 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1385 if (Lex.getCode() != tgtok::r_paren) {
1386 DagArgs = ParseDagArgList(CurRec);
1387 if (DagArgs.empty()) return 0;
1390 if (Lex.getCode() != tgtok::r_paren) {
1391 TokError("expected ')' in dag init");
1394 Lex.Lex(); // eat the ')'
1396 return DagInit::get(Operator, OperatorName, DagArgs);
1402 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1403 case tgtok::XConcat:
1409 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1411 case tgtok::XForEach:
1412 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1413 return ParseOperation(CurRec);
1420 /// ParseValue - Parse a tblgen value. This returns null on error.
1422 /// Value ::= SimpleValue ValueSuffix*
1423 /// ValueSuffix ::= '{' BitList '}'
1424 /// ValueSuffix ::= '[' BitList ']'
1425 /// ValueSuffix ::= '.' ID
1427 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1428 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1429 if (Result == 0) return 0;
1431 // Parse the suffixes now if present.
1433 switch (Lex.getCode()) {
1434 default: return Result;
1435 case tgtok::l_brace: {
1436 if (Mode == ParseNameMode || Mode == ParseForeachMode)
1437 // This is the beginning of the object body.
1440 SMLoc CurlyLoc = Lex.getLoc();
1441 Lex.Lex(); // eat the '{'
1442 std::vector<unsigned> Ranges = ParseRangeList();
1443 if (Ranges.empty()) return 0;
1445 // Reverse the bitlist.
1446 std::reverse(Ranges.begin(), Ranges.end());
1447 Result = Result->convertInitializerBitRange(Ranges);
1449 Error(CurlyLoc, "Invalid bit range for value");
1454 if (Lex.getCode() != tgtok::r_brace) {
1455 TokError("expected '}' at end of bit range list");
1461 case tgtok::l_square: {
1462 SMLoc SquareLoc = Lex.getLoc();
1463 Lex.Lex(); // eat the '['
1464 std::vector<unsigned> Ranges = ParseRangeList();
1465 if (Ranges.empty()) return 0;
1467 Result = Result->convertInitListSlice(Ranges);
1469 Error(SquareLoc, "Invalid range for list slice");
1474 if (Lex.getCode() != tgtok::r_square) {
1475 TokError("expected ']' at end of list slice");
1482 if (Lex.Lex() != tgtok::Id) { // eat the .
1483 TokError("expected field identifier after '.'");
1486 if (!Result->getFieldType(Lex.getCurStrVal())) {
1487 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1488 Result->getAsString() + "'");
1491 Result = FieldInit::get(Result, Lex.getCurStrVal());
1492 Lex.Lex(); // eat field name
1496 SMLoc PasteLoc = Lex.getLoc();
1498 // Create a !strconcat() operation, first casting each operand to
1499 // a string if necessary.
1501 TypedInit *LHS = dyn_cast<TypedInit>(Result);
1503 Error(PasteLoc, "LHS of paste is not typed!");
1507 if (LHS->getType() != StringRecTy::get()) {
1508 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1513 Lex.Lex(); // Eat the '#'.
1514 switch (Lex.getCode()) {
1517 case tgtok::l_brace:
1518 // These are all of the tokens that can begin an object body.
1519 // Some of these can also begin values but we disallow those cases
1520 // because they are unlikely to be useful.
1522 // Trailing paste, concat with an empty string.
1523 RHS = StringInit::get("");
1527 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1528 RHS = dyn_cast<TypedInit>(RHSResult);
1530 Error(PasteLoc, "RHS of paste is not typed!");
1534 if (RHS->getType() != StringRecTy::get()) {
1535 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1541 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1542 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1548 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1550 /// DagArg ::= Value (':' VARNAME)?
1551 /// DagArg ::= VARNAME
1552 /// DagArgList ::= DagArg
1553 /// DagArgList ::= DagArgList ',' DagArg
1554 std::vector<std::pair<llvm::Init*, std::string> >
1555 TGParser::ParseDagArgList(Record *CurRec) {
1556 std::vector<std::pair<llvm::Init*, std::string> > Result;
1559 // DagArg ::= VARNAME
1560 if (Lex.getCode() == tgtok::VarName) {
1561 // A missing value is treated like '?'.
1562 Result.push_back(std::make_pair(UnsetInit::get(), Lex.getCurStrVal()));
1565 // DagArg ::= Value (':' VARNAME)?
1566 Init *Val = ParseValue(CurRec);
1568 return std::vector<std::pair<llvm::Init*, std::string> >();
1570 // If the variable name is present, add it.
1571 std::string VarName;
1572 if (Lex.getCode() == tgtok::colon) {
1573 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1574 TokError("expected variable name in dag literal");
1575 return std::vector<std::pair<llvm::Init*, std::string> >();
1577 VarName = Lex.getCurStrVal();
1578 Lex.Lex(); // eat the VarName.
1581 Result.push_back(std::make_pair(Val, VarName));
1583 if (Lex.getCode() != tgtok::comma) break;
1584 Lex.Lex(); // eat the ','
1591 /// ParseValueList - Parse a comma separated list of values, returning them as a
1592 /// vector. Note that this always expects to be able to parse at least one
1593 /// value. It returns an empty list if this is not possible.
1595 /// ValueList ::= Value (',' Value)
1597 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1599 std::vector<Init*> Result;
1600 RecTy *ItemType = EltTy;
1601 unsigned int ArgN = 0;
1602 if (ArgsRec != 0 && EltTy == 0) {
1603 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1604 if (!TArgs.size()) {
1605 TokError("template argument provided to non-template class");
1606 return std::vector<Init*>();
1608 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1610 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1613 assert(RV && "Template argument record not found??");
1614 ItemType = RV->getType();
1617 Result.push_back(ParseValue(CurRec, ItemType));
1618 if (Result.back() == 0) return std::vector<Init*>();
1620 while (Lex.getCode() == tgtok::comma) {
1621 Lex.Lex(); // Eat the comma
1623 if (ArgsRec != 0 && EltTy == 0) {
1624 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1625 if (ArgN >= TArgs.size()) {
1626 TokError("too many template arguments");
1627 return std::vector<Init*>();
1629 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1630 assert(RV && "Template argument record not found??");
1631 ItemType = RV->getType();
1634 Result.push_back(ParseValue(CurRec, ItemType));
1635 if (Result.back() == 0) return std::vector<Init*>();
1642 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1643 /// empty string on error. This can happen in a number of different context's,
1644 /// including within a def or in the template args for a def (which which case
1645 /// CurRec will be non-null) and within the template args for a multiclass (in
1646 /// which case CurRec will be null, but CurMultiClass will be set). This can
1647 /// also happen within a def that is within a multiclass, which will set both
1648 /// CurRec and CurMultiClass.
1650 /// Declaration ::= FIELD? Type ID ('=' Value)?
1652 Init *TGParser::ParseDeclaration(Record *CurRec,
1653 bool ParsingTemplateArgs) {
1654 // Read the field prefix if present.
1655 bool HasField = Lex.getCode() == tgtok::Field;
1656 if (HasField) Lex.Lex();
1658 RecTy *Type = ParseType();
1659 if (Type == 0) return 0;
1661 if (Lex.getCode() != tgtok::Id) {
1662 TokError("Expected identifier in declaration");
1666 SMLoc IdLoc = Lex.getLoc();
1667 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1670 if (ParsingTemplateArgs) {
1672 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1674 assert(CurMultiClass);
1677 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1682 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1685 // If a value is present, parse it.
1686 if (Lex.getCode() == tgtok::equal) {
1688 SMLoc ValLoc = Lex.getLoc();
1689 Init *Val = ParseValue(CurRec, Type);
1691 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1698 /// ParseForeachDeclaration - Read a foreach declaration, returning
1699 /// the name of the declared object or a NULL Init on error. Return
1700 /// the name of the parsed initializer list through ForeachListName.
1702 /// ForeachDeclaration ::= ID '=' '[' ValueList ']'
1703 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
1704 /// ForeachDeclaration ::= ID '=' RangePiece
1706 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1707 if (Lex.getCode() != tgtok::Id) {
1708 TokError("Expected identifier in foreach declaration");
1712 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1715 // If a value is present, parse it.
1716 if (Lex.getCode() != tgtok::equal) {
1717 TokError("Expected '=' in foreach declaration");
1720 Lex.Lex(); // Eat the '='
1722 RecTy *IterType = 0;
1723 std::vector<unsigned> Ranges;
1725 switch (Lex.getCode()) {
1726 default: TokError("Unknown token when expecting a range list"); return 0;
1727 case tgtok::l_square: { // '[' ValueList ']'
1728 Init *List = ParseSimpleValue(0, 0, ParseForeachMode);
1729 ForeachListValue = dyn_cast<ListInit>(List);
1730 if (ForeachListValue == 0) {
1731 TokError("Expected a Value list");
1734 RecTy *ValueType = ForeachListValue->getType();
1735 ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1736 if (ListType == 0) {
1737 TokError("Value list is not of list type");
1740 IterType = ListType->getElementType();
1744 case tgtok::IntVal: { // RangePiece.
1745 if (ParseRangePiece(Ranges))
1750 case tgtok::l_brace: { // '{' RangeList '}'
1751 Lex.Lex(); // eat the '{'
1752 Ranges = ParseRangeList();
1753 if (Lex.getCode() != tgtok::r_brace) {
1754 TokError("expected '}' at end of bit range list");
1762 if (!Ranges.empty()) {
1763 assert(!IterType && "Type already initialized?");
1764 IterType = IntRecTy::get();
1765 std::vector<Init*> Values;
1766 for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
1767 Values.push_back(IntInit::get(Ranges[i]));
1768 ForeachListValue = ListInit::get(Values, IterType);
1774 return VarInit::get(DeclName, IterType);
1777 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1778 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1779 /// template args for a def, which may or may not be in a multiclass. If null,
1780 /// these are the template args for a multiclass.
1782 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1784 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1785 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1786 Lex.Lex(); // eat the '<'
1788 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1790 // Read the first declaration.
1791 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1795 TheRecToAddTo->addTemplateArg(TemplArg);
1797 while (Lex.getCode() == tgtok::comma) {
1798 Lex.Lex(); // eat the ','
1800 // Read the following declarations.
1801 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1804 TheRecToAddTo->addTemplateArg(TemplArg);
1807 if (Lex.getCode() != tgtok::greater)
1808 return TokError("expected '>' at end of template argument list");
1809 Lex.Lex(); // eat the '>'.
1814 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1816 /// BodyItem ::= Declaration ';'
1817 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1818 bool TGParser::ParseBodyItem(Record *CurRec) {
1819 if (Lex.getCode() != tgtok::Let) {
1820 if (ParseDeclaration(CurRec, false) == 0)
1823 if (Lex.getCode() != tgtok::semi)
1824 return TokError("expected ';' after declaration");
1829 // LET ID OptionalRangeList '=' Value ';'
1830 if (Lex.Lex() != tgtok::Id)
1831 return TokError("expected field identifier after let");
1833 SMLoc IdLoc = Lex.getLoc();
1834 std::string FieldName = Lex.getCurStrVal();
1835 Lex.Lex(); // eat the field name.
1837 std::vector<unsigned> BitList;
1838 if (ParseOptionalBitList(BitList))
1840 std::reverse(BitList.begin(), BitList.end());
1842 if (Lex.getCode() != tgtok::equal)
1843 return TokError("expected '=' in let expression");
1844 Lex.Lex(); // eat the '='.
1846 RecordVal *Field = CurRec->getValue(FieldName);
1848 return TokError("Value '" + FieldName + "' unknown!");
1850 RecTy *Type = Field->getType();
1852 Init *Val = ParseValue(CurRec, Type);
1853 if (Val == 0) return true;
1855 if (Lex.getCode() != tgtok::semi)
1856 return TokError("expected ';' after let expression");
1859 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1862 /// ParseBody - Read the body of a class or def. Return true on error, false on
1866 /// Body ::= '{' BodyList '}'
1867 /// BodyList BodyItem*
1869 bool TGParser::ParseBody(Record *CurRec) {
1870 // If this is a null definition, just eat the semi and return.
1871 if (Lex.getCode() == tgtok::semi) {
1876 if (Lex.getCode() != tgtok::l_brace)
1877 return TokError("Expected ';' or '{' to start body");
1881 while (Lex.getCode() != tgtok::r_brace)
1882 if (ParseBodyItem(CurRec))
1890 /// \brief Apply the current let bindings to \a CurRec.
1891 /// \returns true on error, false otherwise.
1892 bool TGParser::ApplyLetStack(Record *CurRec) {
1893 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1894 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1895 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1896 LetStack[i][j].Bits, LetStack[i][j].Value))
1901 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1902 /// optional ClassList followed by a Body. CurRec is the current def or class
1903 /// that is being parsed.
1905 /// ObjectBody ::= BaseClassList Body
1906 /// BaseClassList ::= /*empty*/
1907 /// BaseClassList ::= ':' BaseClassListNE
1908 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1910 bool TGParser::ParseObjectBody(Record *CurRec) {
1911 // If there is a baseclass list, read it.
1912 if (Lex.getCode() == tgtok::colon) {
1915 // Read all of the subclasses.
1916 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1919 if (SubClass.Rec == 0) return true;
1922 if (AddSubClass(CurRec, SubClass))
1925 if (Lex.getCode() != tgtok::comma) break;
1926 Lex.Lex(); // eat ','.
1927 SubClass = ParseSubClassReference(CurRec, false);
1931 if (ApplyLetStack(CurRec))
1934 return ParseBody(CurRec);
1937 /// ParseDef - Parse and return a top level or multiclass def, return the record
1938 /// corresponding to it. This returns null on error.
1940 /// DefInst ::= DEF ObjectName ObjectBody
1942 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1943 SMLoc DefLoc = Lex.getLoc();
1944 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1945 Lex.Lex(); // Eat the 'def' token.
1947 // Parse ObjectName and make a record for it.
1949 Init *Name = ParseObjectName(CurMultiClass);
1951 CurRec = new Record(Name, DefLoc, Records);
1953 CurRec = new Record(GetNewAnonymousName(), DefLoc, Records,
1954 /*IsAnonymous=*/true);
1956 if (!CurMultiClass && Loops.empty()) {
1957 // Top-level def definition.
1959 // Ensure redefinition doesn't happen.
1960 if (Records.getDef(CurRec->getNameInitAsString())) {
1961 Error(DefLoc, "def '" + CurRec->getNameInitAsString()
1962 + "' already defined");
1965 Records.addDef(CurRec);
1966 } else if (CurMultiClass) {
1967 // Otherwise, a def inside a multiclass, add it to the multiclass.
1968 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1969 if (CurMultiClass->DefPrototypes[i]->getNameInit()
1970 == CurRec->getNameInit()) {
1971 Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
1972 "' already defined in this multiclass!");
1975 CurMultiClass->DefPrototypes.push_back(CurRec);
1978 if (ParseObjectBody(CurRec))
1981 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1982 // See Record::setName(). This resolve step will see any new name
1983 // for the def that might have been created when resolving
1984 // inheritance, values and arguments above.
1985 CurRec->resolveReferences();
1987 // If ObjectBody has template arguments, it's an error.
1988 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1990 if (CurMultiClass) {
1991 // Copy the template arguments for the multiclass into the def.
1992 const std::vector<Init *> &TArgs =
1993 CurMultiClass->Rec.getTemplateArgs();
1995 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1996 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1997 assert(RV && "Template arg doesn't exist?");
1998 CurRec->addValue(*RV);
2002 if (ProcessForeachDefs(CurRec, DefLoc)) {
2004 "Could not process loops for def" + CurRec->getNameInitAsString());
2011 /// ParseForeach - Parse a for statement. Return the record corresponding
2012 /// to it. This returns true on error.
2014 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2015 /// Foreach ::= FOREACH Declaration IN Object
2017 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2018 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2019 Lex.Lex(); // Eat the 'for' token.
2021 // Make a temporary object to record items associated with the for
2023 ListInit *ListValue = 0;
2024 VarInit *IterName = ParseForeachDeclaration(ListValue);
2026 return TokError("expected declaration in for");
2028 if (Lex.getCode() != tgtok::In)
2029 return TokError("Unknown tok");
2030 Lex.Lex(); // Eat the in
2032 // Create a loop object and remember it.
2033 Loops.push_back(ForeachLoop(IterName, ListValue));
2035 if (Lex.getCode() != tgtok::l_brace) {
2036 // FOREACH Declaration IN Object
2037 if (ParseObject(CurMultiClass))
2041 SMLoc BraceLoc = Lex.getLoc();
2042 // Otherwise, this is a group foreach.
2043 Lex.Lex(); // eat the '{'.
2045 // Parse the object list.
2046 if (ParseObjectList(CurMultiClass))
2049 if (Lex.getCode() != tgtok::r_brace) {
2050 TokError("expected '}' at end of foreach command");
2051 return Error(BraceLoc, "to match this '{'");
2053 Lex.Lex(); // Eat the }
2056 // We've processed everything in this loop.
2062 /// ParseClass - Parse a tblgen class definition.
2064 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2066 bool TGParser::ParseClass() {
2067 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2070 if (Lex.getCode() != tgtok::Id)
2071 return TokError("expected class name after 'class' keyword");
2073 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2075 // If the body was previously defined, this is an error.
2076 if (CurRec->getValues().size() > 1 || // Account for NAME.
2077 !CurRec->getSuperClasses().empty() ||
2078 !CurRec->getTemplateArgs().empty())
2079 return TokError("Class '" + CurRec->getNameInitAsString()
2080 + "' already defined");
2082 // If this is the first reference to this class, create and add it.
2083 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
2084 Records.addClass(CurRec);
2086 Lex.Lex(); // eat the name.
2088 // If there are template args, parse them.
2089 if (Lex.getCode() == tgtok::less)
2090 if (ParseTemplateArgList(CurRec))
2093 // Finally, parse the object body.
2094 return ParseObjectBody(CurRec);
2097 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2100 /// LetList ::= LetItem (',' LetItem)*
2101 /// LetItem ::= ID OptionalRangeList '=' Value
2103 std::vector<LetRecord> TGParser::ParseLetList() {
2104 std::vector<LetRecord> Result;
2107 if (Lex.getCode() != tgtok::Id) {
2108 TokError("expected identifier in let definition");
2109 return std::vector<LetRecord>();
2111 std::string Name = Lex.getCurStrVal();
2112 SMLoc NameLoc = Lex.getLoc();
2113 Lex.Lex(); // Eat the identifier.
2115 // Check for an optional RangeList.
2116 std::vector<unsigned> Bits;
2117 if (ParseOptionalRangeList(Bits))
2118 return std::vector<LetRecord>();
2119 std::reverse(Bits.begin(), Bits.end());
2121 if (Lex.getCode() != tgtok::equal) {
2122 TokError("expected '=' in let expression");
2123 return std::vector<LetRecord>();
2125 Lex.Lex(); // eat the '='.
2127 Init *Val = ParseValue(0);
2128 if (Val == 0) return std::vector<LetRecord>();
2130 // Now that we have everything, add the record.
2131 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
2133 if (Lex.getCode() != tgtok::comma)
2135 Lex.Lex(); // eat the comma.
2139 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2140 /// different related productions. This works inside multiclasses too.
2142 /// Object ::= LET LetList IN '{' ObjectList '}'
2143 /// Object ::= LET LetList IN Object
2145 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2146 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2149 // Add this entry to the let stack.
2150 std::vector<LetRecord> LetInfo = ParseLetList();
2151 if (LetInfo.empty()) return true;
2152 LetStack.push_back(LetInfo);
2154 if (Lex.getCode() != tgtok::In)
2155 return TokError("expected 'in' at end of top-level 'let'");
2158 // If this is a scalar let, just handle it now
2159 if (Lex.getCode() != tgtok::l_brace) {
2160 // LET LetList IN Object
2161 if (ParseObject(CurMultiClass))
2163 } else { // Object ::= LETCommand '{' ObjectList '}'
2164 SMLoc BraceLoc = Lex.getLoc();
2165 // Otherwise, this is a group let.
2166 Lex.Lex(); // eat the '{'.
2168 // Parse the object list.
2169 if (ParseObjectList(CurMultiClass))
2172 if (Lex.getCode() != tgtok::r_brace) {
2173 TokError("expected '}' at end of top level let command");
2174 return Error(BraceLoc, "to match this '{'");
2179 // Outside this let scope, this let block is not active.
2180 LetStack.pop_back();
2184 /// ParseMultiClass - Parse a multiclass definition.
2186 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2187 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
2188 /// MultiClassObject ::= DefInst
2189 /// MultiClassObject ::= MultiClassInst
2190 /// MultiClassObject ::= DefMInst
2191 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
2192 /// MultiClassObject ::= LETCommand Object
2194 bool TGParser::ParseMultiClass() {
2195 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2196 Lex.Lex(); // Eat the multiclass token.
2198 if (Lex.getCode() != tgtok::Id)
2199 return TokError("expected identifier after multiclass for name");
2200 std::string Name = Lex.getCurStrVal();
2202 if (MultiClasses.count(Name))
2203 return TokError("multiclass '" + Name + "' already defined");
2205 CurMultiClass = MultiClasses[Name] = new MultiClass(Name,
2206 Lex.getLoc(), Records);
2207 Lex.Lex(); // Eat the identifier.
2209 // If there are template args, parse them.
2210 if (Lex.getCode() == tgtok::less)
2211 if (ParseTemplateArgList(0))
2214 bool inherits = false;
2216 // If there are submulticlasses, parse them.
2217 if (Lex.getCode() == tgtok::colon) {
2222 // Read all of the submulticlasses.
2223 SubMultiClassReference SubMultiClass =
2224 ParseSubMultiClassReference(CurMultiClass);
2227 if (SubMultiClass.MC == 0) return true;
2230 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2233 if (Lex.getCode() != tgtok::comma) break;
2234 Lex.Lex(); // eat ','.
2235 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2239 if (Lex.getCode() != tgtok::l_brace) {
2241 return TokError("expected '{' in multiclass definition");
2242 else if (Lex.getCode() != tgtok::semi)
2243 return TokError("expected ';' in multiclass definition");
2245 Lex.Lex(); // eat the ';'.
2247 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2248 return TokError("multiclass must contain at least one def");
2250 while (Lex.getCode() != tgtok::r_brace) {
2251 switch (Lex.getCode()) {
2253 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2257 case tgtok::Foreach:
2258 if (ParseObject(CurMultiClass))
2263 Lex.Lex(); // eat the '}'.
2271 InstantiateMulticlassDef(MultiClass &MC,
2274 SMRange DefmPrefixRange) {
2275 // We need to preserve DefProto so it can be reused for later
2276 // instantiations, so create a new Record to inherit from it.
2278 // Add in the defm name. If the defm prefix is empty, give each
2279 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2280 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2283 bool IsAnonymous = false;
2284 if (DefmPrefix == 0) {
2285 DefmPrefix = StringInit::get(GetNewAnonymousName());
2289 Init *DefName = DefProto->getNameInit();
2291 StringInit *DefNameString = dyn_cast<StringInit>(DefName);
2293 if (DefNameString != 0) {
2294 // We have a fully expanded string so there are no operators to
2295 // resolve. We should concatenate the given prefix and name.
2297 BinOpInit::get(BinOpInit::STRCONCAT,
2298 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2299 StringRecTy::get())->Fold(DefProto, &MC),
2300 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2303 // Make a trail of SMLocs from the multiclass instantiations.
2304 SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
2305 Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2306 Record *CurRec = new Record(DefName, Locs, Records, IsAnonymous);
2308 SubClassReference Ref;
2309 Ref.RefRange = DefmPrefixRange;
2311 AddSubClass(CurRec, Ref);
2313 // Set the value for NAME. We don't resolve references to it 'til later,
2314 // though, so that uses in nested multiclass names don't get
2316 if (SetValue(CurRec, Ref.RefRange.Start, "NAME", std::vector<unsigned>(),
2318 Error(DefmPrefixRange.Start, "Could not resolve "
2319 + CurRec->getNameInitAsString() + ":NAME to '"
2320 + DefmPrefix->getAsUnquotedString() + "'");
2324 // If the DefNameString didn't resolve, we probably have a reference to
2325 // NAME and need to replace it. We need to do at least this much greedily,
2326 // otherwise nested multiclasses will end up with incorrect NAME expansions.
2327 if (DefNameString == 0) {
2328 RecordVal *DefNameRV = CurRec->getValue("NAME");
2329 CurRec->resolveReferencesTo(DefNameRV);
2332 if (!CurMultiClass) {
2333 // Now that we're at the top level, resolve all NAME references
2334 // in the resultant defs that weren't in the def names themselves.
2335 RecordVal *DefNameRV = CurRec->getValue("NAME");
2336 CurRec->resolveReferencesTo(DefNameRV);
2338 // Now that NAME references are resolved and we're at the top level of
2339 // any multiclass expansions, add the record to the RecordKeeper. If we are
2340 // currently in a multiclass, it means this defm appears inside a
2341 // multiclass and its name won't be fully resolvable until we see
2342 // the top-level defm. Therefore, we don't add this to the
2343 // RecordKeeper at this point. If we did we could get duplicate
2344 // defs as more than one probably refers to NAME or some other
2345 // common internal placeholder.
2347 // Ensure redefinition doesn't happen.
2348 if (Records.getDef(CurRec->getNameInitAsString())) {
2349 Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
2350 "' already defined, instantiating defm with subdef '" +
2351 DefProto->getNameInitAsString() + "'");
2355 Records.addDef(CurRec);
2361 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2363 SMLoc DefmPrefixLoc,
2365 const std::vector<Init *> &TArgs,
2366 std::vector<Init *> &TemplateVals,
2368 // Loop over all of the template arguments, setting them to the specified
2369 // value or leaving them as the default if necessary.
2370 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2371 // Check if a value is specified for this temp-arg.
2372 if (i < TemplateVals.size()) {
2374 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2379 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2383 CurRec->removeValue(TArgs[i]);
2385 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2386 return Error(SubClassLoc, "value not specified for template argument #"+
2387 utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2388 + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2395 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2398 SMLoc DefmPrefixLoc) {
2399 // If the mdef is inside a 'let' expression, add to each def.
2400 if (ApplyLetStack(CurRec))
2401 return Error(DefmPrefixLoc, "when instantiating this defm");
2403 // Don't create a top level definition for defm inside multiclasses,
2404 // instead, only update the prototypes and bind the template args
2405 // with the new created definition.
2408 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2410 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2411 == CurRec->getNameInit())
2412 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2413 "' already defined in this multiclass!");
2414 CurMultiClass->DefPrototypes.push_back(CurRec);
2416 // Copy the template arguments for the multiclass into the new def.
2417 const std::vector<Init *> &TA =
2418 CurMultiClass->Rec.getTemplateArgs();
2420 for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2421 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2422 assert(RV && "Template arg doesn't exist?");
2423 CurRec->addValue(*RV);
2429 /// ParseDefm - Parse the instantiation of a multiclass.
2431 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2433 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2434 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2435 SMLoc DefmLoc = Lex.getLoc();
2436 Init *DefmPrefix = 0;
2438 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2439 DefmPrefix = ParseObjectName(CurMultiClass);
2442 SMLoc DefmPrefixEndLoc = Lex.getLoc();
2443 if (Lex.getCode() != tgtok::colon)
2444 return TokError("expected ':' after defm identifier");
2446 // Keep track of the new generated record definitions.
2447 std::vector<Record*> NewRecDefs;
2449 // This record also inherits from a regular class (non-multiclass)?
2450 bool InheritFromClass = false;
2455 SMLoc SubClassLoc = Lex.getLoc();
2456 SubClassReference Ref = ParseSubClassReference(0, true);
2459 if (Ref.Rec == 0) return true;
2461 // To instantiate a multiclass, we need to first get the multiclass, then
2462 // instantiate each def contained in the multiclass with the SubClassRef
2463 // template parameters.
2464 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
2465 assert(MC && "Didn't lookup multiclass correctly?");
2466 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2468 // Verify that the correct number of template arguments were specified.
2469 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2470 if (TArgs.size() < TemplateVals.size())
2471 return Error(SubClassLoc,
2472 "more template args specified than multiclass expects");
2474 // Loop over all the def's in the multiclass, instantiating each one.
2475 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2476 Record *DefProto = MC->DefPrototypes[i];
2478 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix,
2484 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
2485 TArgs, TemplateVals, true/*Delete args*/))
2486 return Error(SubClassLoc, "could not instantiate def");
2488 if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmLoc))
2489 return Error(SubClassLoc, "could not instantiate def");
2491 NewRecDefs.push_back(CurRec);
2495 if (Lex.getCode() != tgtok::comma) break;
2496 Lex.Lex(); // eat ','.
2498 SubClassLoc = Lex.getLoc();
2500 // A defm can inherit from regular classes (non-multiclass) as
2501 // long as they come in the end of the inheritance list.
2502 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != 0);
2504 if (InheritFromClass)
2507 Ref = ParseSubClassReference(0, true);
2510 if (InheritFromClass) {
2511 // Process all the classes to inherit as if they were part of a
2512 // regular 'def' and inherit all record values.
2513 SubClassReference SubClass = ParseSubClassReference(0, false);
2516 if (SubClass.Rec == 0) return true;
2518 // Get the expanded definition prototypes and teach them about
2519 // the record values the current class to inherit has
2520 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2521 Record *CurRec = NewRecDefs[i];
2524 if (AddSubClass(CurRec, SubClass))
2527 if (ApplyLetStack(CurRec))
2531 if (Lex.getCode() != tgtok::comma) break;
2532 Lex.Lex(); // eat ','.
2533 SubClass = ParseSubClassReference(0, false);
2538 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2539 // See Record::setName(). This resolve step will see any new
2540 // name for the def that might have been created when resolving
2541 // inheritance, values and arguments above.
2542 NewRecDefs[i]->resolveReferences();
2544 if (Lex.getCode() != tgtok::semi)
2545 return TokError("expected ';' at end of defm");
2552 /// Object ::= ClassInst
2553 /// Object ::= DefInst
2554 /// Object ::= MultiClassInst
2555 /// Object ::= DefMInst
2556 /// Object ::= LETCommand '{' ObjectList '}'
2557 /// Object ::= LETCommand Object
2558 bool TGParser::ParseObject(MultiClass *MC) {
2559 switch (Lex.getCode()) {
2561 return TokError("Expected class, def, defm, multiclass or let definition");
2562 case tgtok::Let: return ParseTopLevelLet(MC);
2563 case tgtok::Def: return ParseDef(MC);
2564 case tgtok::Foreach: return ParseForeach(MC);
2565 case tgtok::Defm: return ParseDefm(MC);
2566 case tgtok::Class: return ParseClass();
2567 case tgtok::MultiClass: return ParseMultiClass();
2572 /// ObjectList :== Object*
2573 bool TGParser::ParseObjectList(MultiClass *MC) {
2574 while (isObjectStart(Lex.getCode())) {
2575 if (ParseObject(MC))
2581 bool TGParser::ParseFile() {
2582 Lex.Lex(); // Prime the lexer.
2583 if (ParseObjectList()) return true;
2585 // If we have unread input at the end of the file, report it.
2586 if (Lex.getCode() == tgtok::Eof)
2589 return TokError("Unexpected input at top level");