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.RefLoc, 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.RefLoc, "More template args specified than expected");
162 // Loop over all of the template arguments, setting them to the specified
163 // value or leaving them as the default if necessary.
164 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
165 if (i < SubClass.TemplateArgs.size()) {
166 // If a value is specified for this template arg, set it now.
167 if (SetValue(CurRec, SubClass.RefLoc, TArgs[i], std::vector<unsigned>(),
168 SubClass.TemplateArgs[i]))
172 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
175 CurRec->removeValue(TArgs[i]);
177 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
178 return Error(SubClass.RefLoc,"Value not specified for template argument #"
179 + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
180 + ") of subclass '" + SC->getNameInitAsString() + "'!");
184 // Since everything went well, we can now set the "superclass" list for the
186 const std::vector<Record*> &SCs = SC->getSuperClasses();
187 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
188 if (CurRec->isSubClassOf(SCs[i]))
189 return Error(SubClass.RefLoc,
190 "Already subclass of '" + SCs[i]->getName() + "'!\n");
191 CurRec->addSuperClass(SCs[i]);
194 if (CurRec->isSubClassOf(SC))
195 return Error(SubClass.RefLoc,
196 "Already subclass of '" + SC->getName() + "'!\n");
197 CurRec->addSuperClass(SC);
201 /// AddSubMultiClass - Add SubMultiClass as a subclass to
202 /// CurMC, resolving its template args as SubMultiClass's
203 /// template arguments.
204 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
205 SubMultiClassReference &SubMultiClass) {
206 MultiClass *SMC = SubMultiClass.MC;
207 Record *CurRec = &CurMC->Rec;
209 const std::vector<RecordVal> &MCVals = CurRec->getValues();
211 // Add all of the values in the subclass into the current class.
212 const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
213 for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
214 if (AddValue(CurRec, SubMultiClass.RefLoc, SMCVals[i]))
217 int newDefStart = CurMC->DefPrototypes.size();
219 // Add all of the defs in the subclass into the current multiclass.
220 for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
221 iend = SMC->DefPrototypes.end();
224 // Clone the def and add it to the current multiclass
225 Record *NewDef = new Record(**i);
227 // Add all of the values in the superclass into the current def.
228 for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
229 if (AddValue(NewDef, SubMultiClass.RefLoc, MCVals[i]))
232 CurMC->DefPrototypes.push_back(NewDef);
235 const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
237 // Ensure that an appropriate number of template arguments are
239 if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
240 return Error(SubMultiClass.RefLoc,
241 "More template args specified than expected");
243 // Loop over all of the template arguments, setting them to the specified
244 // value or leaving them as the default if necessary.
245 for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
246 if (i < SubMultiClass.TemplateArgs.size()) {
247 // If a value is specified for this template arg, set it in the
249 if (SetValue(CurRec, SubMultiClass.RefLoc, SMCTArgs[i],
250 std::vector<unsigned>(),
251 SubMultiClass.TemplateArgs[i]))
255 CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
258 CurRec->removeValue(SMCTArgs[i]);
260 // If a value is specified for this template arg, set it in the
262 for (MultiClass::RecordVector::iterator j =
263 CurMC->DefPrototypes.begin() + newDefStart,
264 jend = CurMC->DefPrototypes.end();
269 if (SetValue(Def, SubMultiClass.RefLoc, SMCTArgs[i],
270 std::vector<unsigned>(),
271 SubMultiClass.TemplateArgs[i]))
275 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
278 Def->removeValue(SMCTArgs[i]);
280 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
281 return Error(SubMultiClass.RefLoc,
282 "Value not specified for template argument #"
283 + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
284 + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
291 /// ProcessForeachDefs - Given a record, apply all of the variable
292 /// values in all surrounding foreach loops, creating new records for
293 /// each combination of values.
294 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
298 // We want to instantiate a new copy of CurRec for each combination
299 // of nested loop iterator values. We don't want top instantiate
300 // any copies until we have values for each loop iterator.
302 return ProcessForeachDefs(CurRec, Loc, IterVals);
305 /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
306 /// apply each of the variable values in this loop and then process
308 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
309 // Recursively build a tuple of iterator values.
310 if (IterVals.size() != Loops.size()) {
311 assert(IterVals.size() < Loops.size());
312 ForeachLoop &CurLoop = Loops[IterVals.size()];
313 ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
315 Error(Loc, "Loop list is not a list");
319 // Process each value.
320 for (int64_t i = 0; i < List->getSize(); ++i) {
321 Init *ItemVal = List->resolveListElementReference(*CurRec, 0, i);
322 IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
323 if (ProcessForeachDefs(CurRec, Loc, IterVals))
330 // This is the bottom of the recursion. We have all of the iterator values
331 // for this point in the iteration space. Instantiate a new record to
332 // reflect this combination of values.
333 Record *IterRec = new Record(*CurRec);
335 // Set the iterator values now.
336 for (unsigned i = 0, e = IterVals.size(); i != e; ++i) {
337 VarInit *IterVar = IterVals[i].IterVar;
338 TypedInit *IVal = dyn_cast<TypedInit>(IterVals[i].IterValue);
340 Error(Loc, "foreach iterator value is untyped");
344 IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
346 if (SetValue(IterRec, Loc, IterVar->getName(),
347 std::vector<unsigned>(), IVal)) {
348 Error(Loc, "when instantiating this def");
353 IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
356 IterRec->removeValue(IterVar->getName());
359 if (Records.getDef(IterRec->getNameInitAsString())) {
360 Error(Loc, "def already exists: " + IterRec->getNameInitAsString());
364 Records.addDef(IterRec);
365 IterRec->resolveReferences();
369 //===----------------------------------------------------------------------===//
371 //===----------------------------------------------------------------------===//
373 /// isObjectStart - Return true if this is a valid first token for an Object.
374 static bool isObjectStart(tgtok::TokKind K) {
375 return K == tgtok::Class || K == tgtok::Def ||
376 K == tgtok::Defm || K == tgtok::Let ||
377 K == tgtok::MultiClass || K == tgtok::Foreach;
380 static std::string GetNewAnonymousName() {
381 static unsigned AnonCounter = 0;
382 return "anonymous."+utostr(AnonCounter++);
385 /// ParseObjectName - If an object name is specified, return it. Otherwise,
386 /// return an anonymous name.
387 /// ObjectName ::= Value [ '#' Value ]*
388 /// ObjectName ::= /*empty*/
390 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
391 switch (Lex.getCode()) {
395 // These are all of the tokens that can begin an object body.
396 // Some of these can also begin values but we disallow those cases
397 // because they are unlikely to be useful.
398 return StringInit::get(GetNewAnonymousName());
405 CurRec = &CurMultiClass->Rec;
409 const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
411 TokError("Record name is not typed!");
414 Type = CurRecName->getType();
417 return ParseValue(CurRec, Type, ParseNameMode);
420 /// ParseClassID - Parse and resolve a reference to a class name. This returns
425 Record *TGParser::ParseClassID() {
426 if (Lex.getCode() != tgtok::Id) {
427 TokError("expected name for ClassID");
431 Record *Result = Records.getClass(Lex.getCurStrVal());
433 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
439 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
440 /// This returns null on error.
442 /// MultiClassID ::= ID
444 MultiClass *TGParser::ParseMultiClassID() {
445 if (Lex.getCode() != tgtok::Id) {
446 TokError("expected name for ClassID");
450 MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
452 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
458 Record *TGParser::ParseDefmID() {
459 if (Lex.getCode() != tgtok::Id) {
460 TokError("expected multiclass name");
464 MultiClass *MC = MultiClasses[Lex.getCurStrVal()];
466 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
475 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
476 /// subclass. This returns a SubClassRefTy with a null Record* on error.
478 /// SubClassRef ::= ClassID
479 /// SubClassRef ::= ClassID '<' ValueList '>'
481 SubClassReference TGParser::
482 ParseSubClassReference(Record *CurRec, bool isDefm) {
483 SubClassReference Result;
484 Result.RefLoc = Lex.getLoc();
487 Result.Rec = ParseDefmID();
489 Result.Rec = ParseClassID();
490 if (Result.Rec == 0) return Result;
492 // If there is no template arg list, we're done.
493 if (Lex.getCode() != tgtok::less)
495 Lex.Lex(); // Eat the '<'
497 if (Lex.getCode() == tgtok::greater) {
498 TokError("subclass reference requires a non-empty list of template values");
503 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
504 if (Result.TemplateArgs.empty()) {
505 Result.Rec = 0; // Error parsing value list.
509 if (Lex.getCode() != tgtok::greater) {
510 TokError("expected '>' in template value list");
519 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
520 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
521 /// Record* on error.
523 /// SubMultiClassRef ::= MultiClassID
524 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
526 SubMultiClassReference TGParser::
527 ParseSubMultiClassReference(MultiClass *CurMC) {
528 SubMultiClassReference Result;
529 Result.RefLoc = Lex.getLoc();
531 Result.MC = ParseMultiClassID();
532 if (Result.MC == 0) return Result;
534 // If there is no template arg list, we're done.
535 if (Lex.getCode() != tgtok::less)
537 Lex.Lex(); // Eat the '<'
539 if (Lex.getCode() == tgtok::greater) {
540 TokError("subclass reference requires a non-empty list of template values");
545 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
546 if (Result.TemplateArgs.empty()) {
547 Result.MC = 0; // Error parsing value list.
551 if (Lex.getCode() != tgtok::greater) {
552 TokError("expected '>' in template value list");
561 /// ParseRangePiece - Parse a bit/value range.
562 /// RangePiece ::= INTVAL
563 /// RangePiece ::= INTVAL '-' INTVAL
564 /// RangePiece ::= INTVAL INTVAL
565 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
566 if (Lex.getCode() != tgtok::IntVal) {
567 TokError("expected integer or bitrange");
570 int64_t Start = Lex.getCurIntVal();
574 return TokError("invalid range, cannot be negative");
576 switch (Lex.Lex()) { // eat first character.
578 Ranges.push_back(Start);
581 if (Lex.Lex() != tgtok::IntVal) {
582 TokError("expected integer value as end of range");
585 End = Lex.getCurIntVal();
588 End = -Lex.getCurIntVal();
592 return TokError("invalid range, cannot be negative");
597 for (; Start <= End; ++Start)
598 Ranges.push_back(Start);
600 for (; Start >= End; --Start)
601 Ranges.push_back(Start);
606 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
608 /// RangeList ::= RangePiece (',' RangePiece)*
610 std::vector<unsigned> TGParser::ParseRangeList() {
611 std::vector<unsigned> Result;
613 // Parse the first piece.
614 if (ParseRangePiece(Result))
615 return std::vector<unsigned>();
616 while (Lex.getCode() == tgtok::comma) {
617 Lex.Lex(); // Eat the comma.
619 // Parse the next range piece.
620 if (ParseRangePiece(Result))
621 return std::vector<unsigned>();
626 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
627 /// OptionalRangeList ::= '<' RangeList '>'
628 /// OptionalRangeList ::= /*empty*/
629 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
630 if (Lex.getCode() != tgtok::less)
633 SMLoc StartLoc = Lex.getLoc();
634 Lex.Lex(); // eat the '<'
636 // Parse the range list.
637 Ranges = ParseRangeList();
638 if (Ranges.empty()) return true;
640 if (Lex.getCode() != tgtok::greater) {
641 TokError("expected '>' at end of range list");
642 return Error(StartLoc, "to match this '<'");
644 Lex.Lex(); // eat the '>'.
648 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
649 /// OptionalBitList ::= '{' RangeList '}'
650 /// OptionalBitList ::= /*empty*/
651 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
652 if (Lex.getCode() != tgtok::l_brace)
655 SMLoc StartLoc = Lex.getLoc();
656 Lex.Lex(); // eat the '{'
658 // Parse the range list.
659 Ranges = ParseRangeList();
660 if (Ranges.empty()) return true;
662 if (Lex.getCode() != tgtok::r_brace) {
663 TokError("expected '}' at end of bit list");
664 return Error(StartLoc, "to match this '{'");
666 Lex.Lex(); // eat the '}'.
671 /// ParseType - Parse and return a tblgen type. This returns null on error.
673 /// Type ::= STRING // string type
674 /// Type ::= CODE // code type
675 /// Type ::= BIT // bit type
676 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
677 /// Type ::= INT // int type
678 /// Type ::= LIST '<' Type '>' // list<x> type
679 /// Type ::= DAG // dag type
680 /// Type ::= ClassID // Record Type
682 RecTy *TGParser::ParseType() {
683 switch (Lex.getCode()) {
684 default: TokError("Unknown token when expecting a type"); return 0;
685 case tgtok::String: Lex.Lex(); return StringRecTy::get();
686 case tgtok::Code: Lex.Lex(); return StringRecTy::get();
687 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
688 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
689 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
691 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
694 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
695 TokError("expected '<' after bits type");
698 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
699 TokError("expected integer in bits<n> type");
702 uint64_t Val = Lex.getCurIntVal();
703 if (Lex.Lex() != tgtok::greater) { // Eat count.
704 TokError("expected '>' at end of bits<n> type");
707 Lex.Lex(); // Eat '>'
708 return BitsRecTy::get(Val);
711 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
712 TokError("expected '<' after list type");
715 Lex.Lex(); // Eat '<'
716 RecTy *SubType = ParseType();
717 if (SubType == 0) return 0;
719 if (Lex.getCode() != tgtok::greater) {
720 TokError("expected '>' at end of list<ty> type");
723 Lex.Lex(); // Eat '>'
724 return ListRecTy::get(SubType);
729 /// ParseIDValue - Parse an ID as a value and decode what it means.
731 /// IDValue ::= ID [def local value]
732 /// IDValue ::= ID [def template arg]
733 /// IDValue ::= ID [multiclass local value]
734 /// IDValue ::= ID [multiclass template argument]
735 /// IDValue ::= ID [def name]
737 Init *TGParser::ParseIDValue(Record *CurRec, IDParseMode Mode) {
738 assert(Lex.getCode() == tgtok::Id && "Expected ID in ParseIDValue");
739 std::string Name = Lex.getCurStrVal();
740 SMLoc Loc = Lex.getLoc();
742 return ParseIDValue(CurRec, Name, Loc);
745 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
746 /// has already been read.
747 Init *TGParser::ParseIDValue(Record *CurRec,
748 const std::string &Name, SMLoc NameLoc,
751 if (const RecordVal *RV = CurRec->getValue(Name))
752 return VarInit::get(Name, RV->getType());
754 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
757 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
760 if (CurRec->isTemplateArg(TemplateArgName)) {
761 const RecordVal *RV = CurRec->getValue(TemplateArgName);
762 assert(RV && "Template arg doesn't exist??");
763 return VarInit::get(TemplateArgName, RV->getType());
768 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
771 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
772 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
773 assert(RV && "Template arg doesn't exist??");
774 return VarInit::get(MCName, RV->getType());
778 // If this is in a foreach loop, make sure it's not a loop iterator
779 for (LoopVector::iterator i = Loops.begin(), iend = Loops.end();
782 VarInit *IterVar = dyn_cast<VarInit>(i->IterVar);
783 if (IterVar && IterVar->getName() == Name)
787 if (Mode == ParseNameMode)
788 return StringInit::get(Name);
790 if (Record *D = Records.getDef(Name))
791 return DefInit::get(D);
793 if (Mode == ParseValueMode) {
794 Error(NameLoc, "Variable not defined: '" + Name + "'");
798 return StringInit::get(Name);
801 /// ParseOperation - Parse an operator. This returns null on error.
803 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
805 Init *TGParser::ParseOperation(Record *CurRec) {
806 switch (Lex.getCode()) {
808 TokError("unknown operation");
813 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
814 UnOpInit::UnaryOp Code;
817 switch (Lex.getCode()) {
818 default: llvm_unreachable("Unhandled code!");
820 Lex.Lex(); // eat the operation
821 Code = UnOpInit::CAST;
823 Type = ParseOperatorType();
826 TokError("did not get type for unary operator");
832 Lex.Lex(); // eat the operation
833 Code = UnOpInit::HEAD;
836 Lex.Lex(); // eat the operation
837 Code = UnOpInit::TAIL;
840 Lex.Lex(); // eat the operation
841 Code = UnOpInit::EMPTY;
842 Type = IntRecTy::get();
845 if (Lex.getCode() != tgtok::l_paren) {
846 TokError("expected '(' after unary operator");
849 Lex.Lex(); // eat the '('
851 Init *LHS = ParseValue(CurRec);
852 if (LHS == 0) return 0;
854 if (Code == UnOpInit::HEAD
855 || Code == UnOpInit::TAIL
856 || Code == UnOpInit::EMPTY) {
857 ListInit *LHSl = dyn_cast<ListInit>(LHS);
858 StringInit *LHSs = dyn_cast<StringInit>(LHS);
859 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
860 if (LHSl == 0 && LHSs == 0 && LHSt == 0) {
861 TokError("expected list or string type argument in unary operator");
865 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
866 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
867 if (LType == 0 && SType == 0) {
868 TokError("expected list or string type argumnet in unary operator");
873 if (Code == UnOpInit::HEAD
874 || Code == UnOpInit::TAIL) {
875 if (LHSl == 0 && LHSt == 0) {
876 TokError("expected list type argumnet in unary operator");
880 if (LHSl && LHSl->getSize() == 0) {
881 TokError("empty list argument in unary operator");
885 Init *Item = LHSl->getElement(0);
886 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
888 TokError("untyped list element in unary operator");
891 if (Code == UnOpInit::HEAD) {
892 Type = Itemt->getType();
894 Type = ListRecTy::get(Itemt->getType());
897 assert(LHSt && "expected list type argument in unary operator");
898 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
900 TokError("expected list type argumnet in unary operator");
903 if (Code == UnOpInit::HEAD) {
904 Type = LType->getElementType();
912 if (Lex.getCode() != tgtok::r_paren) {
913 TokError("expected ')' in unary operator");
916 Lex.Lex(); // eat the ')'
917 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
925 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
926 tgtok::TokKind OpTok = Lex.getCode();
927 SMLoc OpLoc = Lex.getLoc();
928 Lex.Lex(); // eat the operation
930 BinOpInit::BinaryOp Code;
934 default: llvm_unreachable("Unhandled code!");
935 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
936 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
937 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
938 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
939 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
940 case tgtok::XStrConcat:
941 Code = BinOpInit::STRCONCAT;
942 Type = StringRecTy::get();
946 if (Lex.getCode() != tgtok::l_paren) {
947 TokError("expected '(' after binary operator");
950 Lex.Lex(); // eat the '('
952 SmallVector<Init*, 2> InitList;
954 InitList.push_back(ParseValue(CurRec));
955 if (InitList.back() == 0) return 0;
957 while (Lex.getCode() == tgtok::comma) {
958 Lex.Lex(); // eat the ','
960 InitList.push_back(ParseValue(CurRec));
961 if (InitList.back() == 0) return 0;
964 if (Lex.getCode() != tgtok::r_paren) {
965 TokError("expected ')' in operator");
968 Lex.Lex(); // eat the ')'
970 // We allow multiple operands to associative operators like !strconcat as
971 // shorthand for nesting them.
972 if (Code == BinOpInit::STRCONCAT) {
973 while (InitList.size() > 2) {
974 Init *RHS = InitList.pop_back_val();
975 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
976 ->Fold(CurRec, CurMultiClass);
977 InitList.back() = RHS;
981 if (InitList.size() == 2)
982 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
983 ->Fold(CurRec, CurMultiClass);
985 Error(OpLoc, "expected two operands to operator");
990 case tgtok::XForEach:
991 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
992 TernOpInit::TernaryOp Code;
995 tgtok::TokKind LexCode = Lex.getCode();
996 Lex.Lex(); // eat the operation
998 default: llvm_unreachable("Unhandled code!");
1000 Code = TernOpInit::IF;
1002 case tgtok::XForEach:
1003 Code = TernOpInit::FOREACH;
1006 Code = TernOpInit::SUBST;
1009 if (Lex.getCode() != tgtok::l_paren) {
1010 TokError("expected '(' after ternary operator");
1013 Lex.Lex(); // eat the '('
1015 Init *LHS = ParseValue(CurRec);
1016 if (LHS == 0) return 0;
1018 if (Lex.getCode() != tgtok::comma) {
1019 TokError("expected ',' in ternary operator");
1022 Lex.Lex(); // eat the ','
1024 Init *MHS = ParseValue(CurRec);
1025 if (MHS == 0) return 0;
1027 if (Lex.getCode() != tgtok::comma) {
1028 TokError("expected ',' in ternary operator");
1031 Lex.Lex(); // eat the ','
1033 Init *RHS = ParseValue(CurRec);
1034 if (RHS == 0) return 0;
1036 if (Lex.getCode() != tgtok::r_paren) {
1037 TokError("expected ')' in binary operator");
1040 Lex.Lex(); // eat the ')'
1043 default: llvm_unreachable("Unhandled code!");
1048 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1049 MHSTy = MHSt->getType();
1050 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1051 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1052 if (isa<BitInit>(MHS))
1053 MHSTy = BitRecTy::get();
1055 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1056 RHSTy = RHSt->getType();
1057 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1058 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1059 if (isa<BitInit>(RHS))
1060 RHSTy = BitRecTy::get();
1062 // For UnsetInit, it's typed from the other hand.
1063 if (isa<UnsetInit>(MHS))
1065 if (isa<UnsetInit>(RHS))
1068 if (!MHSTy || !RHSTy) {
1069 TokError("could not get type for !if");
1073 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1075 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1078 TokError("inconsistent types for !if");
1083 case tgtok::XForEach: {
1084 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1086 TokError("could not get type for !foreach");
1089 Type = MHSt->getType();
1092 case tgtok::XSubst: {
1093 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1095 TokError("could not get type for !subst");
1098 Type = RHSt->getType();
1102 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1108 /// ParseOperatorType - Parse a type for an operator. This returns
1111 /// OperatorType ::= '<' Type '>'
1113 RecTy *TGParser::ParseOperatorType() {
1116 if (Lex.getCode() != tgtok::less) {
1117 TokError("expected type name for operator");
1120 Lex.Lex(); // eat the <
1125 TokError("expected type name for operator");
1129 if (Lex.getCode() != tgtok::greater) {
1130 TokError("expected type name for operator");
1133 Lex.Lex(); // eat the >
1139 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1141 /// SimpleValue ::= IDValue
1142 /// SimpleValue ::= INTVAL
1143 /// SimpleValue ::= STRVAL+
1144 /// SimpleValue ::= CODEFRAGMENT
1145 /// SimpleValue ::= '?'
1146 /// SimpleValue ::= '{' ValueList '}'
1147 /// SimpleValue ::= ID '<' ValueListNE '>'
1148 /// SimpleValue ::= '[' ValueList ']'
1149 /// SimpleValue ::= '(' IDValue DagArgList ')'
1150 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1151 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1152 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1153 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1154 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1156 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1159 switch (Lex.getCode()) {
1160 default: TokError("Unknown token when parsing a value"); break;
1162 // This is a leading paste operation. This is deprecated but
1163 // still exists in some .td files. Ignore it.
1164 Lex.Lex(); // Skip '#'.
1165 return ParseSimpleValue(CurRec, ItemType, Mode);
1166 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1167 case tgtok::StrVal: {
1168 std::string Val = Lex.getCurStrVal();
1171 // Handle multiple consecutive concatenated strings.
1172 while (Lex.getCode() == tgtok::StrVal) {
1173 Val += Lex.getCurStrVal();
1177 R = StringInit::get(Val);
1180 case tgtok::CodeFragment:
1181 R = StringInit::get(Lex.getCurStrVal());
1184 case tgtok::question:
1185 R = UnsetInit::get();
1189 SMLoc NameLoc = Lex.getLoc();
1190 std::string Name = Lex.getCurStrVal();
1191 if (Lex.Lex() != tgtok::less) // consume the Id.
1192 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1194 // Value ::= ID '<' ValueListNE '>'
1195 if (Lex.Lex() == tgtok::greater) {
1196 TokError("expected non-empty value list");
1200 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1201 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1203 Record *Class = Records.getClass(Name);
1205 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1209 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1210 if (ValueList.empty()) return 0;
1212 if (Lex.getCode() != tgtok::greater) {
1213 TokError("expected '>' at end of value list");
1216 Lex.Lex(); // eat the '>'
1218 // Create the new record, set it as CurRec temporarily.
1219 static unsigned AnonCounter = 0;
1220 Record *NewRec = new Record("anonymous.val."+utostr(AnonCounter++),
1223 SubClassReference SCRef;
1224 SCRef.RefLoc = NameLoc;
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:
1408 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1410 case tgtok::XForEach:
1411 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1412 return ParseOperation(CurRec);
1419 /// ParseValue - Parse a tblgen value. This returns null on error.
1421 /// Value ::= SimpleValue ValueSuffix*
1422 /// ValueSuffix ::= '{' BitList '}'
1423 /// ValueSuffix ::= '[' BitList ']'
1424 /// ValueSuffix ::= '.' ID
1426 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1427 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1428 if (Result == 0) return 0;
1430 // Parse the suffixes now if present.
1432 switch (Lex.getCode()) {
1433 default: return Result;
1434 case tgtok::l_brace: {
1435 if (Mode == ParseNameMode || Mode == ParseForeachMode)
1436 // This is the beginning of the object body.
1439 SMLoc CurlyLoc = Lex.getLoc();
1440 Lex.Lex(); // eat the '{'
1441 std::vector<unsigned> Ranges = ParseRangeList();
1442 if (Ranges.empty()) return 0;
1444 // Reverse the bitlist.
1445 std::reverse(Ranges.begin(), Ranges.end());
1446 Result = Result->convertInitializerBitRange(Ranges);
1448 Error(CurlyLoc, "Invalid bit range for value");
1453 if (Lex.getCode() != tgtok::r_brace) {
1454 TokError("expected '}' at end of bit range list");
1460 case tgtok::l_square: {
1461 SMLoc SquareLoc = Lex.getLoc();
1462 Lex.Lex(); // eat the '['
1463 std::vector<unsigned> Ranges = ParseRangeList();
1464 if (Ranges.empty()) return 0;
1466 Result = Result->convertInitListSlice(Ranges);
1468 Error(SquareLoc, "Invalid range for list slice");
1473 if (Lex.getCode() != tgtok::r_square) {
1474 TokError("expected ']' at end of list slice");
1481 if (Lex.Lex() != tgtok::Id) { // eat the .
1482 TokError("expected field identifier after '.'");
1485 if (!Result->getFieldType(Lex.getCurStrVal())) {
1486 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1487 Result->getAsString() + "'");
1490 Result = FieldInit::get(Result, Lex.getCurStrVal());
1491 Lex.Lex(); // eat field name
1495 SMLoc PasteLoc = Lex.getLoc();
1497 // Create a !strconcat() operation, first casting each operand to
1498 // a string if necessary.
1500 TypedInit *LHS = dyn_cast<TypedInit>(Result);
1502 Error(PasteLoc, "LHS of paste is not typed!");
1506 if (LHS->getType() != StringRecTy::get()) {
1507 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1512 Lex.Lex(); // Eat the '#'.
1513 switch (Lex.getCode()) {
1516 case tgtok::l_brace:
1517 // These are all of the tokens that can begin an object body.
1518 // Some of these can also begin values but we disallow those cases
1519 // because they are unlikely to be useful.
1521 // Trailing paste, concat with an empty string.
1522 RHS = StringInit::get("");
1526 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1527 RHS = dyn_cast<TypedInit>(RHSResult);
1529 Error(PasteLoc, "RHS of paste is not typed!");
1533 if (RHS->getType() != StringRecTy::get()) {
1534 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1540 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1541 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1547 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1549 /// ParseDagArgList ::= Value (':' VARNAME)?
1550 /// ParseDagArgList ::= ParseDagArgList ',' Value (':' VARNAME)?
1551 std::vector<std::pair<llvm::Init*, std::string> >
1552 TGParser::ParseDagArgList(Record *CurRec) {
1553 std::vector<std::pair<llvm::Init*, std::string> > Result;
1556 Init *Val = ParseValue(CurRec);
1557 if (Val == 0) return std::vector<std::pair<llvm::Init*, std::string> >();
1559 // If the variable name is present, add it.
1560 std::string VarName;
1561 if (Lex.getCode() == tgtok::colon) {
1562 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1563 TokError("expected variable name in dag literal");
1564 return std::vector<std::pair<llvm::Init*, std::string> >();
1566 VarName = Lex.getCurStrVal();
1567 Lex.Lex(); // eat the VarName.
1570 Result.push_back(std::make_pair(Val, VarName));
1572 if (Lex.getCode() != tgtok::comma) break;
1573 Lex.Lex(); // eat the ','
1580 /// ParseValueList - Parse a comma separated list of values, returning them as a
1581 /// vector. Note that this always expects to be able to parse at least one
1582 /// value. It returns an empty list if this is not possible.
1584 /// ValueList ::= Value (',' Value)
1586 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1588 std::vector<Init*> Result;
1589 RecTy *ItemType = EltTy;
1590 unsigned int ArgN = 0;
1591 if (ArgsRec != 0 && EltTy == 0) {
1592 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1593 if (!TArgs.size()) {
1594 TokError("template argument provided to non-template class");
1595 return std::vector<Init*>();
1597 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1599 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1602 assert(RV && "Template argument record not found??");
1603 ItemType = RV->getType();
1606 Result.push_back(ParseValue(CurRec, ItemType));
1607 if (Result.back() == 0) return std::vector<Init*>();
1609 while (Lex.getCode() == tgtok::comma) {
1610 Lex.Lex(); // Eat the comma
1612 if (ArgsRec != 0 && EltTy == 0) {
1613 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1614 if (ArgN >= TArgs.size()) {
1615 TokError("too many template arguments");
1616 return std::vector<Init*>();
1618 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1619 assert(RV && "Template argument record not found??");
1620 ItemType = RV->getType();
1623 Result.push_back(ParseValue(CurRec, ItemType));
1624 if (Result.back() == 0) return std::vector<Init*>();
1631 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1632 /// empty string on error. This can happen in a number of different context's,
1633 /// including within a def or in the template args for a def (which which case
1634 /// CurRec will be non-null) and within the template args for a multiclass (in
1635 /// which case CurRec will be null, but CurMultiClass will be set). This can
1636 /// also happen within a def that is within a multiclass, which will set both
1637 /// CurRec and CurMultiClass.
1639 /// Declaration ::= FIELD? Type ID ('=' Value)?
1641 Init *TGParser::ParseDeclaration(Record *CurRec,
1642 bool ParsingTemplateArgs) {
1643 // Read the field prefix if present.
1644 bool HasField = Lex.getCode() == tgtok::Field;
1645 if (HasField) Lex.Lex();
1647 RecTy *Type = ParseType();
1648 if (Type == 0) return 0;
1650 if (Lex.getCode() != tgtok::Id) {
1651 TokError("Expected identifier in declaration");
1655 SMLoc IdLoc = Lex.getLoc();
1656 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1659 if (ParsingTemplateArgs) {
1661 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1663 assert(CurMultiClass);
1666 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1671 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1674 // If a value is present, parse it.
1675 if (Lex.getCode() == tgtok::equal) {
1677 SMLoc ValLoc = Lex.getLoc();
1678 Init *Val = ParseValue(CurRec, Type);
1680 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1687 /// ParseForeachDeclaration - Read a foreach declaration, returning
1688 /// the name of the declared object or a NULL Init on error. Return
1689 /// the name of the parsed initializer list through ForeachListName.
1691 /// ForeachDeclaration ::= ID '=' '[' ValueList ']'
1692 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
1693 /// ForeachDeclaration ::= ID '=' RangePiece
1695 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1696 if (Lex.getCode() != tgtok::Id) {
1697 TokError("Expected identifier in foreach declaration");
1701 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1704 // If a value is present, parse it.
1705 if (Lex.getCode() != tgtok::equal) {
1706 TokError("Expected '=' in foreach declaration");
1709 Lex.Lex(); // Eat the '='
1711 RecTy *IterType = 0;
1712 std::vector<unsigned> Ranges;
1714 switch (Lex.getCode()) {
1715 default: TokError("Unknown token when expecting a range list"); return 0;
1716 case tgtok::l_square: { // '[' ValueList ']'
1717 Init *List = ParseSimpleValue(0, 0, ParseForeachMode);
1718 ForeachListValue = dyn_cast<ListInit>(List);
1719 if (ForeachListValue == 0) {
1720 TokError("Expected a Value list");
1723 RecTy *ValueType = ForeachListValue->getType();
1724 ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1725 if (ListType == 0) {
1726 TokError("Value list is not of list type");
1729 IterType = ListType->getElementType();
1733 case tgtok::IntVal: { // RangePiece.
1734 if (ParseRangePiece(Ranges))
1739 case tgtok::l_brace: { // '{' RangeList '}'
1740 Lex.Lex(); // eat the '{'
1741 Ranges = ParseRangeList();
1742 if (Lex.getCode() != tgtok::r_brace) {
1743 TokError("expected '}' at end of bit range list");
1751 if (!Ranges.empty()) {
1752 assert(!IterType && "Type already initialized?");
1753 IterType = IntRecTy::get();
1754 std::vector<Init*> Values;
1755 for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
1756 Values.push_back(IntInit::get(Ranges[i]));
1757 ForeachListValue = ListInit::get(Values, IterType);
1763 return VarInit::get(DeclName, IterType);
1766 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1767 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1768 /// template args for a def, which may or may not be in a multiclass. If null,
1769 /// these are the template args for a multiclass.
1771 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1773 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1774 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1775 Lex.Lex(); // eat the '<'
1777 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1779 // Read the first declaration.
1780 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1784 TheRecToAddTo->addTemplateArg(TemplArg);
1786 while (Lex.getCode() == tgtok::comma) {
1787 Lex.Lex(); // eat the ','
1789 // Read the following declarations.
1790 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1793 TheRecToAddTo->addTemplateArg(TemplArg);
1796 if (Lex.getCode() != tgtok::greater)
1797 return TokError("expected '>' at end of template argument list");
1798 Lex.Lex(); // eat the '>'.
1803 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1805 /// BodyItem ::= Declaration ';'
1806 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1807 bool TGParser::ParseBodyItem(Record *CurRec) {
1808 if (Lex.getCode() != tgtok::Let) {
1809 if (ParseDeclaration(CurRec, false) == 0)
1812 if (Lex.getCode() != tgtok::semi)
1813 return TokError("expected ';' after declaration");
1818 // LET ID OptionalRangeList '=' Value ';'
1819 if (Lex.Lex() != tgtok::Id)
1820 return TokError("expected field identifier after let");
1822 SMLoc IdLoc = Lex.getLoc();
1823 std::string FieldName = Lex.getCurStrVal();
1824 Lex.Lex(); // eat the field name.
1826 std::vector<unsigned> BitList;
1827 if (ParseOptionalBitList(BitList))
1829 std::reverse(BitList.begin(), BitList.end());
1831 if (Lex.getCode() != tgtok::equal)
1832 return TokError("expected '=' in let expression");
1833 Lex.Lex(); // eat the '='.
1835 RecordVal *Field = CurRec->getValue(FieldName);
1837 return TokError("Value '" + FieldName + "' unknown!");
1839 RecTy *Type = Field->getType();
1841 Init *Val = ParseValue(CurRec, Type);
1842 if (Val == 0) return true;
1844 if (Lex.getCode() != tgtok::semi)
1845 return TokError("expected ';' after let expression");
1848 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1851 /// ParseBody - Read the body of a class or def. Return true on error, false on
1855 /// Body ::= '{' BodyList '}'
1856 /// BodyList BodyItem*
1858 bool TGParser::ParseBody(Record *CurRec) {
1859 // If this is a null definition, just eat the semi and return.
1860 if (Lex.getCode() == tgtok::semi) {
1865 if (Lex.getCode() != tgtok::l_brace)
1866 return TokError("Expected ';' or '{' to start body");
1870 while (Lex.getCode() != tgtok::r_brace)
1871 if (ParseBodyItem(CurRec))
1879 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1880 /// optional ClassList followed by a Body. CurRec is the current def or class
1881 /// that is being parsed.
1883 /// ObjectBody ::= BaseClassList Body
1884 /// BaseClassList ::= /*empty*/
1885 /// BaseClassList ::= ':' BaseClassListNE
1886 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1888 bool TGParser::ParseObjectBody(Record *CurRec) {
1889 // If there is a baseclass list, read it.
1890 if (Lex.getCode() == tgtok::colon) {
1893 // Read all of the subclasses.
1894 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1897 if (SubClass.Rec == 0) return true;
1900 if (AddSubClass(CurRec, SubClass))
1903 if (Lex.getCode() != tgtok::comma) break;
1904 Lex.Lex(); // eat ','.
1905 SubClass = ParseSubClassReference(CurRec, false);
1909 // Process any variables on the let stack.
1910 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1911 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1912 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1913 LetStack[i][j].Bits, LetStack[i][j].Value))
1916 return ParseBody(CurRec);
1919 /// ParseDef - Parse and return a top level or multiclass def, return the record
1920 /// corresponding to it. This returns null on error.
1922 /// DefInst ::= DEF ObjectName ObjectBody
1924 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1925 SMLoc DefLoc = Lex.getLoc();
1926 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1927 Lex.Lex(); // Eat the 'def' token.
1929 // Parse ObjectName and make a record for it.
1930 Record *CurRec = new Record(ParseObjectName(CurMultiClass), DefLoc, Records);
1932 if (!CurMultiClass && Loops.empty()) {
1933 // Top-level def definition.
1935 // Ensure redefinition doesn't happen.
1936 if (Records.getDef(CurRec->getNameInitAsString())) {
1937 Error(DefLoc, "def '" + CurRec->getNameInitAsString()
1938 + "' already defined");
1941 Records.addDef(CurRec);
1942 } else if (CurMultiClass) {
1943 // Otherwise, a def inside a multiclass, add it to the multiclass.
1944 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
1945 if (CurMultiClass->DefPrototypes[i]->getNameInit()
1946 == CurRec->getNameInit()) {
1947 Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
1948 "' already defined in this multiclass!");
1951 CurMultiClass->DefPrototypes.push_back(CurRec);
1954 if (ParseObjectBody(CurRec))
1957 if (CurMultiClass == 0) // Def's in multiclasses aren't really defs.
1958 // See Record::setName(). This resolve step will see any new name
1959 // for the def that might have been created when resolving
1960 // inheritance, values and arguments above.
1961 CurRec->resolveReferences();
1963 // If ObjectBody has template arguments, it's an error.
1964 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
1966 if (CurMultiClass) {
1967 // Copy the template arguments for the multiclass into the def.
1968 const std::vector<Init *> &TArgs =
1969 CurMultiClass->Rec.getTemplateArgs();
1971 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1972 const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1973 assert(RV && "Template arg doesn't exist?");
1974 CurRec->addValue(*RV);
1978 if (ProcessForeachDefs(CurRec, DefLoc)) {
1980 "Could not process loops for def" + CurRec->getNameInitAsString());
1987 /// ParseForeach - Parse a for statement. Return the record corresponding
1988 /// to it. This returns true on error.
1990 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
1991 /// Foreach ::= FOREACH Declaration IN Object
1993 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
1994 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
1995 Lex.Lex(); // Eat the 'for' token.
1997 // Make a temporary object to record items associated with the for
1999 ListInit *ListValue = 0;
2000 VarInit *IterName = ParseForeachDeclaration(ListValue);
2002 return TokError("expected declaration in for");
2004 if (Lex.getCode() != tgtok::In)
2005 return TokError("Unknown tok");
2006 Lex.Lex(); // Eat the in
2008 // Create a loop object and remember it.
2009 Loops.push_back(ForeachLoop(IterName, ListValue));
2011 if (Lex.getCode() != tgtok::l_brace) {
2012 // FOREACH Declaration IN Object
2013 if (ParseObject(CurMultiClass))
2017 SMLoc BraceLoc = Lex.getLoc();
2018 // Otherwise, this is a group foreach.
2019 Lex.Lex(); // eat the '{'.
2021 // Parse the object list.
2022 if (ParseObjectList(CurMultiClass))
2025 if (Lex.getCode() != tgtok::r_brace) {
2026 TokError("expected '}' at end of foreach command");
2027 return Error(BraceLoc, "to match this '{'");
2029 Lex.Lex(); // Eat the }
2032 // We've processed everything in this loop.
2038 /// ParseClass - Parse a tblgen class definition.
2040 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2042 bool TGParser::ParseClass() {
2043 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2046 if (Lex.getCode() != tgtok::Id)
2047 return TokError("expected class name after 'class' keyword");
2049 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2051 // If the body was previously defined, this is an error.
2052 if (CurRec->getValues().size() > 1 || // Account for NAME.
2053 !CurRec->getSuperClasses().empty() ||
2054 !CurRec->getTemplateArgs().empty())
2055 return TokError("Class '" + CurRec->getNameInitAsString()
2056 + "' already defined");
2058 // If this is the first reference to this class, create and add it.
2059 CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
2060 Records.addClass(CurRec);
2062 Lex.Lex(); // eat the name.
2064 // If there are template args, parse them.
2065 if (Lex.getCode() == tgtok::less)
2066 if (ParseTemplateArgList(CurRec))
2069 // Finally, parse the object body.
2070 return ParseObjectBody(CurRec);
2073 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2076 /// LetList ::= LetItem (',' LetItem)*
2077 /// LetItem ::= ID OptionalRangeList '=' Value
2079 std::vector<LetRecord> TGParser::ParseLetList() {
2080 std::vector<LetRecord> Result;
2083 if (Lex.getCode() != tgtok::Id) {
2084 TokError("expected identifier in let definition");
2085 return std::vector<LetRecord>();
2087 std::string Name = Lex.getCurStrVal();
2088 SMLoc NameLoc = Lex.getLoc();
2089 Lex.Lex(); // Eat the identifier.
2091 // Check for an optional RangeList.
2092 std::vector<unsigned> Bits;
2093 if (ParseOptionalRangeList(Bits))
2094 return std::vector<LetRecord>();
2095 std::reverse(Bits.begin(), Bits.end());
2097 if (Lex.getCode() != tgtok::equal) {
2098 TokError("expected '=' in let expression");
2099 return std::vector<LetRecord>();
2101 Lex.Lex(); // eat the '='.
2103 Init *Val = ParseValue(0);
2104 if (Val == 0) return std::vector<LetRecord>();
2106 // Now that we have everything, add the record.
2107 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
2109 if (Lex.getCode() != tgtok::comma)
2111 Lex.Lex(); // eat the comma.
2115 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2116 /// different related productions. This works inside multiclasses too.
2118 /// Object ::= LET LetList IN '{' ObjectList '}'
2119 /// Object ::= LET LetList IN Object
2121 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2122 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2125 // Add this entry to the let stack.
2126 std::vector<LetRecord> LetInfo = ParseLetList();
2127 if (LetInfo.empty()) return true;
2128 LetStack.push_back(LetInfo);
2130 if (Lex.getCode() != tgtok::In)
2131 return TokError("expected 'in' at end of top-level 'let'");
2134 // If this is a scalar let, just handle it now
2135 if (Lex.getCode() != tgtok::l_brace) {
2136 // LET LetList IN Object
2137 if (ParseObject(CurMultiClass))
2139 } else { // Object ::= LETCommand '{' ObjectList '}'
2140 SMLoc BraceLoc = Lex.getLoc();
2141 // Otherwise, this is a group let.
2142 Lex.Lex(); // eat the '{'.
2144 // Parse the object list.
2145 if (ParseObjectList(CurMultiClass))
2148 if (Lex.getCode() != tgtok::r_brace) {
2149 TokError("expected '}' at end of top level let command");
2150 return Error(BraceLoc, "to match this '{'");
2155 // Outside this let scope, this let block is not active.
2156 LetStack.pop_back();
2160 /// ParseMultiClass - Parse a multiclass definition.
2162 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2163 /// ':' BaseMultiClassList '{' MultiClassDef+ '}'
2165 bool TGParser::ParseMultiClass() {
2166 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2167 Lex.Lex(); // Eat the multiclass token.
2169 if (Lex.getCode() != tgtok::Id)
2170 return TokError("expected identifier after multiclass for name");
2171 std::string Name = Lex.getCurStrVal();
2173 if (MultiClasses.count(Name))
2174 return TokError("multiclass '" + Name + "' already defined");
2176 CurMultiClass = MultiClasses[Name] = new MultiClass(Name,
2177 Lex.getLoc(), Records);
2178 Lex.Lex(); // Eat the identifier.
2180 // If there are template args, parse them.
2181 if (Lex.getCode() == tgtok::less)
2182 if (ParseTemplateArgList(0))
2185 bool inherits = false;
2187 // If there are submulticlasses, parse them.
2188 if (Lex.getCode() == tgtok::colon) {
2193 // Read all of the submulticlasses.
2194 SubMultiClassReference SubMultiClass =
2195 ParseSubMultiClassReference(CurMultiClass);
2198 if (SubMultiClass.MC == 0) return true;
2201 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2204 if (Lex.getCode() != tgtok::comma) break;
2205 Lex.Lex(); // eat ','.
2206 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2210 if (Lex.getCode() != tgtok::l_brace) {
2212 return TokError("expected '{' in multiclass definition");
2213 else if (Lex.getCode() != tgtok::semi)
2214 return TokError("expected ';' in multiclass definition");
2216 Lex.Lex(); // eat the ';'.
2218 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2219 return TokError("multiclass must contain at least one def");
2221 while (Lex.getCode() != tgtok::r_brace) {
2222 switch (Lex.getCode()) {
2224 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2228 case tgtok::Foreach:
2229 if (ParseObject(CurMultiClass))
2234 Lex.Lex(); // eat the '}'.
2242 InstantiateMulticlassDef(MultiClass &MC,
2245 SMLoc DefmPrefixLoc) {
2246 // We need to preserve DefProto so it can be reused for later
2247 // instantiations, so create a new Record to inherit from it.
2249 // Add in the defm name. If the defm prefix is empty, give each
2250 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2251 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2254 if (DefmPrefix == 0)
2255 DefmPrefix = StringInit::get(GetNewAnonymousName());
2257 Init *DefName = DefProto->getNameInit();
2259 StringInit *DefNameString = dyn_cast<StringInit>(DefName);
2261 if (DefNameString != 0) {
2262 // We have a fully expanded string so there are no operators to
2263 // resolve. We should concatenate the given prefix and name.
2265 BinOpInit::get(BinOpInit::STRCONCAT,
2266 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2267 StringRecTy::get())->Fold(DefProto, &MC),
2268 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2271 // Make a trail of SMLocs from the multiclass instantiations.
2272 SmallVector<SMLoc, 4> Locs(1, DefmPrefixLoc);
2273 Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2274 Record *CurRec = new Record(DefName, Locs, Records);
2276 SubClassReference Ref;
2277 Ref.RefLoc = DefmPrefixLoc;
2279 AddSubClass(CurRec, Ref);
2281 // Set the value for NAME. We don't resolve references to it 'til later,
2282 // though, so that uses in nested multiclass names don't get
2284 if (SetValue(CurRec, Ref.RefLoc, "NAME", std::vector<unsigned>(),
2286 Error(DefmPrefixLoc, "Could not resolve "
2287 + CurRec->getNameInitAsString() + ":NAME to '"
2288 + DefmPrefix->getAsUnquotedString() + "'");
2292 // If the DefNameString didn't resolve, we probably have a reference to
2293 // NAME and need to replace it. We need to do at least this much greedily,
2294 // otherwise nested multiclasses will end up with incorrect NAME expansions.
2295 if (DefNameString == 0) {
2296 RecordVal *DefNameRV = CurRec->getValue("NAME");
2297 CurRec->resolveReferencesTo(DefNameRV);
2300 if (!CurMultiClass) {
2301 // Now that we're at the top level, resolve all NAME references
2302 // in the resultant defs that weren't in the def names themselves.
2303 RecordVal *DefNameRV = CurRec->getValue("NAME");
2304 CurRec->resolveReferencesTo(DefNameRV);
2306 // Now that NAME references are resolved and we're at the top level of
2307 // any multiclass expansions, add the record to the RecordKeeper. If we are
2308 // currently in a multiclass, it means this defm appears inside a
2309 // multiclass and its name won't be fully resolvable until we see
2310 // the top-level defm. Therefore, we don't add this to the
2311 // RecordKeeper at this point. If we did we could get duplicate
2312 // defs as more than one probably refers to NAME or some other
2313 // common internal placeholder.
2315 // Ensure redefinition doesn't happen.
2316 if (Records.getDef(CurRec->getNameInitAsString())) {
2317 Error(DefmPrefixLoc, "def '" + CurRec->getNameInitAsString() +
2318 "' already defined, instantiating defm with subdef '" +
2319 DefProto->getNameInitAsString() + "'");
2323 Records.addDef(CurRec);
2329 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2331 SMLoc DefmPrefixLoc,
2333 const std::vector<Init *> &TArgs,
2334 std::vector<Init *> &TemplateVals,
2336 // Loop over all of the template arguments, setting them to the specified
2337 // value or leaving them as the default if necessary.
2338 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2339 // Check if a value is specified for this temp-arg.
2340 if (i < TemplateVals.size()) {
2342 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2347 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2351 CurRec->removeValue(TArgs[i]);
2353 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2354 return Error(SubClassLoc, "value not specified for template argument #"+
2355 utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2356 + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2363 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2366 SMLoc DefmPrefixLoc) {
2367 // If the mdef is inside a 'let' expression, add to each def.
2368 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2369 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2370 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2371 LetStack[i][j].Bits, LetStack[i][j].Value))
2372 return Error(DefmPrefixLoc, "when instantiating this defm");
2374 // Don't create a top level definition for defm inside multiclasses,
2375 // instead, only update the prototypes and bind the template args
2376 // with the new created definition.
2377 if (CurMultiClass) {
2378 for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2380 if (CurMultiClass->DefPrototypes[i]->getNameInit()
2381 == CurRec->getNameInit())
2382 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2383 "' already defined in this multiclass!");
2384 CurMultiClass->DefPrototypes.push_back(CurRec);
2386 // Copy the template arguments for the multiclass into the new def.
2387 const std::vector<Init *> &TA =
2388 CurMultiClass->Rec.getTemplateArgs();
2390 for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2391 const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2392 assert(RV && "Template arg doesn't exist?");
2393 CurRec->addValue(*RV);
2400 /// ParseDefm - Parse the instantiation of a multiclass.
2402 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2404 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2405 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2407 Init *DefmPrefix = 0;
2409 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2410 DefmPrefix = ParseObjectName(CurMultiClass);
2413 SMLoc DefmPrefixLoc = Lex.getLoc();
2414 if (Lex.getCode() != tgtok::colon)
2415 return TokError("expected ':' after defm identifier");
2417 // Keep track of the new generated record definitions.
2418 std::vector<Record*> NewRecDefs;
2420 // This record also inherits from a regular class (non-multiclass)?
2421 bool InheritFromClass = false;
2426 SMLoc SubClassLoc = Lex.getLoc();
2427 SubClassReference Ref = ParseSubClassReference(0, true);
2430 if (Ref.Rec == 0) return true;
2432 // To instantiate a multiclass, we need to first get the multiclass, then
2433 // instantiate each def contained in the multiclass with the SubClassRef
2434 // template parameters.
2435 MultiClass *MC = MultiClasses[Ref.Rec->getName()];
2436 assert(MC && "Didn't lookup multiclass correctly?");
2437 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2439 // Verify that the correct number of template arguments were specified.
2440 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2441 if (TArgs.size() < TemplateVals.size())
2442 return Error(SubClassLoc,
2443 "more template args specified than multiclass expects");
2445 // Loop over all the def's in the multiclass, instantiating each one.
2446 for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2447 Record *DefProto = MC->DefPrototypes[i];
2449 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix, DefmPrefixLoc);
2453 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmPrefixLoc, SubClassLoc,
2454 TArgs, TemplateVals, true/*Delete args*/))
2455 return Error(SubClassLoc, "could not instantiate def");
2457 if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmPrefixLoc))
2458 return Error(SubClassLoc, "could not instantiate def");
2460 NewRecDefs.push_back(CurRec);
2464 if (Lex.getCode() != tgtok::comma) break;
2465 Lex.Lex(); // eat ','.
2467 SubClassLoc = Lex.getLoc();
2469 // A defm can inherit from regular classes (non-multiclass) as
2470 // long as they come in the end of the inheritance list.
2471 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != 0);
2473 if (InheritFromClass)
2476 Ref = ParseSubClassReference(0, true);
2479 if (InheritFromClass) {
2480 // Process all the classes to inherit as if they were part of a
2481 // regular 'def' and inherit all record values.
2482 SubClassReference SubClass = ParseSubClassReference(0, false);
2485 if (SubClass.Rec == 0) return true;
2487 // Get the expanded definition prototypes and teach them about
2488 // the record values the current class to inherit has
2489 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2490 Record *CurRec = NewRecDefs[i];
2493 if (AddSubClass(CurRec, SubClass))
2496 // Process any variables on the let stack.
2497 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
2498 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
2499 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
2500 LetStack[i][j].Bits, LetStack[i][j].Value))
2504 if (Lex.getCode() != tgtok::comma) break;
2505 Lex.Lex(); // eat ','.
2506 SubClass = ParseSubClassReference(0, false);
2511 for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2512 // See Record::setName(). This resolve step will see any new
2513 // name for the def that might have been created when resolving
2514 // inheritance, values and arguments above.
2515 NewRecDefs[i]->resolveReferences();
2517 if (Lex.getCode() != tgtok::semi)
2518 return TokError("expected ';' at end of defm");
2525 /// Object ::= ClassInst
2526 /// Object ::= DefInst
2527 /// Object ::= MultiClassInst
2528 /// Object ::= DefMInst
2529 /// Object ::= LETCommand '{' ObjectList '}'
2530 /// Object ::= LETCommand Object
2531 bool TGParser::ParseObject(MultiClass *MC) {
2532 switch (Lex.getCode()) {
2534 return TokError("Expected class, def, defm, multiclass or let definition");
2535 case tgtok::Let: return ParseTopLevelLet(MC);
2536 case tgtok::Def: return ParseDef(MC);
2537 case tgtok::Foreach: return ParseForeach(MC);
2538 case tgtok::Defm: return ParseDefm(MC);
2539 case tgtok::Class: return ParseClass();
2540 case tgtok::MultiClass: return ParseMultiClass();
2545 /// ObjectList :== Object*
2546 bool TGParser::ParseObjectList(MultiClass *MC) {
2547 while (isObjectStart(Lex.getCode())) {
2548 if (ParseObject(MC))
2554 bool TGParser::ParseFile() {
2555 Lex.Lex(); // Prime the lexer.
2556 if (ParseObjectList()) return true;
2558 // If we have unread input at the end of the file, report it.
2559 if (Lex.getCode() == tgtok::Eof)
2562 return TokError("Unexpected input at top level");