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/STLExtras.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/TableGen/Record.h"
24 //===----------------------------------------------------------------------===//
25 // Support Code for the Semantic Actions.
26 //===----------------------------------------------------------------------===//
29 struct SubClassReference {
32 std::vector<Init*> TemplateArgs;
33 SubClassReference() : Rec(nullptr) {}
35 bool isInvalid() const { return Rec == nullptr; }
38 struct SubMultiClassReference {
41 std::vector<Init*> TemplateArgs;
42 SubMultiClassReference() : MC(nullptr) {}
44 bool isInvalid() const { return MC == nullptr; }
48 void SubMultiClassReference::dump() const {
49 errs() << "Multiclass:\n";
53 errs() << "Template args:\n";
54 for (Init *TA : TemplateArgs) {
59 } // end namespace llvm
61 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
63 CurRec = &CurMultiClass->Rec;
65 if (RecordVal *ERV = CurRec->getValue(RV.getNameInit())) {
66 // The value already exists in the class, treat this as a set.
67 if (ERV->setValue(RV.getValue()))
68 return Error(Loc, "New definition of '" + RV.getName() + "' of type '" +
69 RV.getType()->getAsString() + "' is incompatible with " +
70 "previous definition of type '" +
71 ERV->getType()->getAsString() + "'");
79 /// Return true on error, false on success.
80 bool TGParser::SetValue(Record *CurRec, SMLoc Loc, Init *ValName,
81 const std::vector<unsigned> &BitList, Init *V) {
84 if (!CurRec) CurRec = &CurMultiClass->Rec;
86 RecordVal *RV = CurRec->getValue(ValName);
88 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
91 // Do not allow assignments like 'X = X'. This will just cause infinite loops
92 // in the resolution machinery.
94 if (VarInit *VI = dyn_cast<VarInit>(V))
95 if (VI->getNameInit() == ValName)
98 // If we are assigning to a subset of the bits in the value... then we must be
99 // assigning to a field of BitsRecTy, which must have a BitsInit
102 if (!BitList.empty()) {
103 BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
105 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
106 "' is not a bits type");
108 // Convert the incoming value to a bits type of the appropriate size...
109 Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size()));
111 return Error(Loc, "Initializer is not compatible with bit range");
114 // We should have a BitsInit type now.
115 BitsInit *BInit = cast<BitsInit>(BI);
117 SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
119 // Loop over bits, assigning values as appropriate.
120 for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
121 unsigned Bit = BitList[i];
123 return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
124 ValName->getAsUnquotedString() + "' more than once");
125 NewBits[Bit] = BInit->getBit(i);
128 for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
130 NewBits[i] = CurVal->getBit(i);
132 V = BitsInit::get(NewBits);
135 if (RV->setValue(V)) {
136 std::string InitType = "";
137 if (BitsInit *BI = dyn_cast<BitsInit>(V)) {
138 InitType = (Twine("' of type bit initializer with length ") +
139 Twine(BI->getNumBits())).str();
141 return Error(Loc, "Value '" + ValName->getAsUnquotedString() +
142 "' of type '" + RV->getType()->getAsString() +
143 "' is incompatible with initializer '" + V->getAsString() +
149 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
150 /// args as SubClass's template arguments.
151 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
152 Record *SC = SubClass.Rec;
153 // Add all of the values in the subclass into the current class.
154 const std::vector<RecordVal> &Vals = SC->getValues();
155 for (unsigned i = 0, e = Vals.size(); i != e; ++i)
156 if (AddValue(CurRec, SubClass.RefRange.Start, Vals[i]))
159 const std::vector<Init *> &TArgs = SC->getTemplateArgs();
161 // Ensure that an appropriate number of template arguments are specified.
162 if (TArgs.size() < SubClass.TemplateArgs.size())
163 return Error(SubClass.RefRange.Start,
164 "More template args specified than expected");
166 // Loop over all of the template arguments, setting them to the specified
167 // value or leaving them as the default if necessary.
168 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
169 if (i < SubClass.TemplateArgs.size()) {
170 // If a value is specified for this template arg, set it now.
171 if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
172 std::vector<unsigned>(), SubClass.TemplateArgs[i]))
176 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
179 CurRec->removeValue(TArgs[i]);
181 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
182 return Error(SubClass.RefRange.Start,
183 "Value not specified for template argument #" +
184 utostr(i) + " (" + TArgs[i]->getAsUnquotedString() +
185 ") of subclass '" + SC->getNameInitAsString() + "'!");
189 // Since everything went well, we can now set the "superclass" list for the
191 const std::vector<Record*> &SCs = SC->getSuperClasses();
192 ArrayRef<SMRange> SCRanges = SC->getSuperClassRanges();
193 for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
194 if (CurRec->isSubClassOf(SCs[i]))
195 return Error(SubClass.RefRange.Start,
196 "Already subclass of '" + SCs[i]->getName() + "'!\n");
197 CurRec->addSuperClass(SCs[i], SCRanges[i]);
200 if (CurRec->isSubClassOf(SC))
201 return Error(SubClass.RefRange.Start,
202 "Already subclass of '" + SC->getName() + "'!\n");
203 CurRec->addSuperClass(SC, SubClass.RefRange);
207 /// AddSubMultiClass - Add SubMultiClass as a subclass to
208 /// CurMC, resolving its template args as SubMultiClass's
209 /// template arguments.
210 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
211 SubMultiClassReference &SubMultiClass) {
212 MultiClass *SMC = SubMultiClass.MC;
213 Record *CurRec = &CurMC->Rec;
215 // Add all of the values in the subclass into the current class.
216 for (const auto &SMCVal : SMC->Rec.getValues())
217 if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVal))
220 unsigned newDefStart = CurMC->DefPrototypes.size();
222 // Add all of the defs in the subclass into the current multiclass.
223 for (const std::unique_ptr<Record> &R : SMC->DefPrototypes) {
224 // Clone the def and add it to the current multiclass
225 auto NewDef = make_unique<Record>(*R);
227 // Add all of the values in the superclass into the current def.
228 for (const auto &MCVal : CurRec->getValues())
229 if (AddValue(NewDef.get(), SubMultiClass.RefRange.Start, MCVal))
232 CurMC->DefPrototypes.push_back(std::move(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.RefRange.Start,
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.RefRange.Start, 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 (const auto &Def :
263 makeArrayRef(CurMC->DefPrototypes).slice(newDefStart)) {
264 if (SetValue(Def.get(), SubMultiClass.RefRange.Start, SMCTArgs[i],
265 std::vector<unsigned>(),
266 SubMultiClass.TemplateArgs[i]))
270 Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
273 Def->removeValue(SMCTArgs[i]);
275 } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
276 return Error(SubMultiClass.RefRange.Start,
277 "Value not specified for template argument #" +
278 utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString() +
279 ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
286 /// ProcessForeachDefs - Given a record, apply all of the variable
287 /// values in all surrounding foreach loops, creating new records for
288 /// each combination of values.
289 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
293 // We want to instantiate a new copy of CurRec for each combination
294 // of nested loop iterator values. We don't want top instantiate
295 // any copies until we have values for each loop iterator.
297 return ProcessForeachDefs(CurRec, Loc, IterVals);
300 /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
301 /// apply each of the variable values in this loop and then process
303 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
304 // Recursively build a tuple of iterator values.
305 if (IterVals.size() != Loops.size()) {
306 assert(IterVals.size() < Loops.size());
307 ForeachLoop &CurLoop = Loops[IterVals.size()];
308 ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
310 Error(Loc, "Loop list is not a list");
314 // Process each value.
315 for (int64_t i = 0; i < List->getSize(); ++i) {
316 Init *ItemVal = List->resolveListElementReference(*CurRec, nullptr, i);
317 IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
318 if (ProcessForeachDefs(CurRec, Loc, IterVals))
325 // This is the bottom of the recursion. We have all of the iterator values
326 // for this point in the iteration space. Instantiate a new record to
327 // reflect this combination of values.
328 auto IterRec = make_unique<Record>(*CurRec);
330 // Set the iterator values now.
331 for (unsigned i = 0, e = IterVals.size(); i != e; ++i) {
332 VarInit *IterVar = IterVals[i].IterVar;
333 TypedInit *IVal = dyn_cast<TypedInit>(IterVals[i].IterValue);
335 return Error(Loc, "foreach iterator value is untyped");
337 IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
339 if (SetValue(IterRec.get(), Loc, IterVar->getName(),
340 std::vector<unsigned>(), IVal))
341 return Error(Loc, "when instantiating this def");
344 IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
347 IterRec->removeValue(IterVar->getName());
350 if (Records.getDef(IterRec->getNameInitAsString())) {
351 // If this record is anonymous, it's no problem, just generate a new name
352 if (!IterRec->isAnonymous())
353 return Error(Loc, "def already exists: " +IterRec->getNameInitAsString());
355 IterRec->setName(GetNewAnonymousName());
358 Record *IterRecSave = IterRec.get(); // Keep a copy before release.
359 Records.addDef(std::move(IterRec));
360 IterRecSave->resolveReferences();
364 //===----------------------------------------------------------------------===//
366 //===----------------------------------------------------------------------===//
368 /// isObjectStart - Return true if this is a valid first token for an Object.
369 static bool isObjectStart(tgtok::TokKind K) {
370 return K == tgtok::Class || K == tgtok::Def ||
371 K == tgtok::Defm || K == tgtok::Let ||
372 K == tgtok::MultiClass || K == tgtok::Foreach;
375 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
377 std::string TGParser::GetNewAnonymousName() {
378 return "anonymous_" + utostr(AnonCounter++);
381 /// ParseObjectName - If an object name is specified, return it. Otherwise,
383 /// ObjectName ::= Value [ '#' Value ]*
384 /// ObjectName ::= /*empty*/
386 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
387 switch (Lex.getCode()) {
391 // These are all of the tokens that can begin an object body.
392 // Some of these can also begin values but we disallow those cases
393 // because they are unlikely to be useful.
399 Record *CurRec = nullptr;
401 CurRec = &CurMultiClass->Rec;
403 RecTy *Type = nullptr;
405 const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
407 TokError("Record name is not typed!");
410 Type = CurRecName->getType();
413 return ParseValue(CurRec, Type, ParseNameMode);
416 /// ParseClassID - Parse and resolve a reference to a class name. This returns
421 Record *TGParser::ParseClassID() {
422 if (Lex.getCode() != tgtok::Id) {
423 TokError("expected name for ClassID");
427 Record *Result = Records.getClass(Lex.getCurStrVal());
429 TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
435 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
436 /// This returns null on error.
438 /// MultiClassID ::= ID
440 MultiClass *TGParser::ParseMultiClassID() {
441 if (Lex.getCode() != tgtok::Id) {
442 TokError("expected name for MultiClassID");
446 MultiClass *Result = MultiClasses[Lex.getCurStrVal()].get();
448 TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
454 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
455 /// subclass. This returns a SubClassRefTy with a null Record* on error.
457 /// SubClassRef ::= ClassID
458 /// SubClassRef ::= ClassID '<' ValueList '>'
460 SubClassReference TGParser::
461 ParseSubClassReference(Record *CurRec, bool isDefm) {
462 SubClassReference Result;
463 Result.RefRange.Start = Lex.getLoc();
466 if (MultiClass *MC = ParseMultiClassID())
467 Result.Rec = &MC->Rec;
469 Result.Rec = ParseClassID();
471 if (!Result.Rec) return Result;
473 // If there is no template arg list, we're done.
474 if (Lex.getCode() != tgtok::less) {
475 Result.RefRange.End = Lex.getLoc();
478 Lex.Lex(); // Eat the '<'
480 if (Lex.getCode() == tgtok::greater) {
481 TokError("subclass reference requires a non-empty list of template values");
482 Result.Rec = nullptr;
486 Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
487 if (Result.TemplateArgs.empty()) {
488 Result.Rec = nullptr; // Error parsing value list.
492 if (Lex.getCode() != tgtok::greater) {
493 TokError("expected '>' in template value list");
494 Result.Rec = nullptr;
498 Result.RefRange.End = Lex.getLoc();
503 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
504 /// templated submulticlass. This returns a SubMultiClassRefTy with a null
505 /// Record* on error.
507 /// SubMultiClassRef ::= MultiClassID
508 /// SubMultiClassRef ::= MultiClassID '<' ValueList '>'
510 SubMultiClassReference TGParser::
511 ParseSubMultiClassReference(MultiClass *CurMC) {
512 SubMultiClassReference Result;
513 Result.RefRange.Start = Lex.getLoc();
515 Result.MC = ParseMultiClassID();
516 if (!Result.MC) return Result;
518 // If there is no template arg list, we're done.
519 if (Lex.getCode() != tgtok::less) {
520 Result.RefRange.End = Lex.getLoc();
523 Lex.Lex(); // Eat the '<'
525 if (Lex.getCode() == tgtok::greater) {
526 TokError("subclass reference requires a non-empty list of template values");
531 Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
532 if (Result.TemplateArgs.empty()) {
533 Result.MC = nullptr; // Error parsing value list.
537 if (Lex.getCode() != tgtok::greater) {
538 TokError("expected '>' in template value list");
543 Result.RefRange.End = Lex.getLoc();
548 /// ParseRangePiece - Parse a bit/value range.
549 /// RangePiece ::= INTVAL
550 /// RangePiece ::= INTVAL '-' INTVAL
551 /// RangePiece ::= INTVAL INTVAL
552 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
553 if (Lex.getCode() != tgtok::IntVal) {
554 TokError("expected integer or bitrange");
557 int64_t Start = Lex.getCurIntVal();
561 return TokError("invalid range, cannot be negative");
563 switch (Lex.Lex()) { // eat first character.
565 Ranges.push_back(Start);
568 if (Lex.Lex() != tgtok::IntVal) {
569 TokError("expected integer value as end of range");
572 End = Lex.getCurIntVal();
575 End = -Lex.getCurIntVal();
579 return TokError("invalid range, cannot be negative");
584 for (; Start <= End; ++Start)
585 Ranges.push_back(Start);
587 for (; Start >= End; --Start)
588 Ranges.push_back(Start);
593 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
595 /// RangeList ::= RangePiece (',' RangePiece)*
597 std::vector<unsigned> TGParser::ParseRangeList() {
598 std::vector<unsigned> Result;
600 // Parse the first piece.
601 if (ParseRangePiece(Result))
602 return std::vector<unsigned>();
603 while (Lex.getCode() == tgtok::comma) {
604 Lex.Lex(); // Eat the comma.
606 // Parse the next range piece.
607 if (ParseRangePiece(Result))
608 return std::vector<unsigned>();
613 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
614 /// OptionalRangeList ::= '<' RangeList '>'
615 /// OptionalRangeList ::= /*empty*/
616 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
617 if (Lex.getCode() != tgtok::less)
620 SMLoc StartLoc = Lex.getLoc();
621 Lex.Lex(); // eat the '<'
623 // Parse the range list.
624 Ranges = ParseRangeList();
625 if (Ranges.empty()) return true;
627 if (Lex.getCode() != tgtok::greater) {
628 TokError("expected '>' at end of range list");
629 return Error(StartLoc, "to match this '<'");
631 Lex.Lex(); // eat the '>'.
635 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
636 /// OptionalBitList ::= '{' RangeList '}'
637 /// OptionalBitList ::= /*empty*/
638 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
639 if (Lex.getCode() != tgtok::l_brace)
642 SMLoc StartLoc = Lex.getLoc();
643 Lex.Lex(); // eat the '{'
645 // Parse the range list.
646 Ranges = ParseRangeList();
647 if (Ranges.empty()) return true;
649 if (Lex.getCode() != tgtok::r_brace) {
650 TokError("expected '}' at end of bit list");
651 return Error(StartLoc, "to match this '{'");
653 Lex.Lex(); // eat the '}'.
658 /// ParseType - Parse and return a tblgen type. This returns null on error.
660 /// Type ::= STRING // string type
661 /// Type ::= CODE // code type
662 /// Type ::= BIT // bit type
663 /// Type ::= BITS '<' INTVAL '>' // bits<x> type
664 /// Type ::= INT // int type
665 /// Type ::= LIST '<' Type '>' // list<x> type
666 /// Type ::= DAG // dag type
667 /// Type ::= ClassID // Record Type
669 RecTy *TGParser::ParseType() {
670 switch (Lex.getCode()) {
671 default: TokError("Unknown token when expecting a type"); return nullptr;
672 case tgtok::String: Lex.Lex(); return StringRecTy::get();
673 case tgtok::Code: Lex.Lex(); return StringRecTy::get();
674 case tgtok::Bit: Lex.Lex(); return BitRecTy::get();
675 case tgtok::Int: Lex.Lex(); return IntRecTy::get();
676 case tgtok::Dag: Lex.Lex(); return DagRecTy::get();
678 if (Record *R = ParseClassID()) return RecordRecTy::get(R);
681 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
682 TokError("expected '<' after bits type");
685 if (Lex.Lex() != tgtok::IntVal) { // Eat '<'
686 TokError("expected integer in bits<n> type");
689 uint64_t Val = Lex.getCurIntVal();
690 if (Lex.Lex() != tgtok::greater) { // Eat count.
691 TokError("expected '>' at end of bits<n> type");
694 Lex.Lex(); // Eat '>'
695 return BitsRecTy::get(Val);
698 if (Lex.Lex() != tgtok::less) { // Eat 'bits'
699 TokError("expected '<' after list type");
702 Lex.Lex(); // Eat '<'
703 RecTy *SubType = ParseType();
704 if (!SubType) return nullptr;
706 if (Lex.getCode() != tgtok::greater) {
707 TokError("expected '>' at end of list<ty> type");
710 Lex.Lex(); // Eat '>'
711 return ListRecTy::get(SubType);
716 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
717 /// has already been read.
718 Init *TGParser::ParseIDValue(Record *CurRec,
719 const std::string &Name, SMLoc NameLoc,
722 if (const RecordVal *RV = CurRec->getValue(Name))
723 return VarInit::get(Name, RV->getType());
725 Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
728 TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
731 if (CurRec->isTemplateArg(TemplateArgName)) {
732 const RecordVal *RV = CurRec->getValue(TemplateArgName);
733 assert(RV && "Template arg doesn't exist??");
734 return VarInit::get(TemplateArgName, RV->getType());
739 Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
742 if (CurMultiClass->Rec.isTemplateArg(MCName)) {
743 const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
744 assert(RV && "Template arg doesn't exist??");
745 return VarInit::get(MCName, RV->getType());
749 // If this is in a foreach loop, make sure it's not a loop iterator
750 for (const auto &L : Loops) {
751 VarInit *IterVar = dyn_cast<VarInit>(L.IterVar);
752 if (IterVar && IterVar->getName() == Name)
756 if (Mode == ParseNameMode)
757 return StringInit::get(Name);
759 if (Record *D = Records.getDef(Name))
760 return DefInit::get(D);
762 if (Mode == ParseValueMode) {
763 Error(NameLoc, "Variable not defined: '" + Name + "'");
767 return StringInit::get(Name);
770 /// ParseOperation - Parse an operator. This returns null on error.
772 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
774 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
775 switch (Lex.getCode()) {
777 TokError("unknown operation");
782 case tgtok::XCast: { // Value ::= !unop '(' Value ')'
783 UnOpInit::UnaryOp Code;
784 RecTy *Type = nullptr;
786 switch (Lex.getCode()) {
787 default: llvm_unreachable("Unhandled code!");
789 Lex.Lex(); // eat the operation
790 Code = UnOpInit::CAST;
792 Type = ParseOperatorType();
795 TokError("did not get type for unary operator");
801 Lex.Lex(); // eat the operation
802 Code = UnOpInit::HEAD;
805 Lex.Lex(); // eat the operation
806 Code = UnOpInit::TAIL;
809 Lex.Lex(); // eat the operation
810 Code = UnOpInit::EMPTY;
811 Type = IntRecTy::get();
814 if (Lex.getCode() != tgtok::l_paren) {
815 TokError("expected '(' after unary operator");
818 Lex.Lex(); // eat the '('
820 Init *LHS = ParseValue(CurRec);
821 if (!LHS) return nullptr;
823 if (Code == UnOpInit::HEAD ||
824 Code == UnOpInit::TAIL ||
825 Code == UnOpInit::EMPTY) {
826 ListInit *LHSl = dyn_cast<ListInit>(LHS);
827 StringInit *LHSs = dyn_cast<StringInit>(LHS);
828 TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
829 if (!LHSl && !LHSs && !LHSt) {
830 TokError("expected list or string type argument in unary operator");
834 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
835 StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
836 if (!LType && !SType) {
837 TokError("expected list or string type argument in unary operator");
842 if (Code == UnOpInit::HEAD || Code == UnOpInit::TAIL) {
843 if (!LHSl && !LHSt) {
844 TokError("expected list type argument in unary operator");
848 if (LHSl && LHSl->getSize() == 0) {
849 TokError("empty list argument in unary operator");
853 Init *Item = LHSl->getElement(0);
854 TypedInit *Itemt = dyn_cast<TypedInit>(Item);
856 TokError("untyped list element in unary operator");
859 if (Code == UnOpInit::HEAD) {
860 Type = Itemt->getType();
862 Type = ListRecTy::get(Itemt->getType());
865 assert(LHSt && "expected list type argument in unary operator");
866 ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
868 TokError("expected list type argument in unary operator");
871 if (Code == UnOpInit::HEAD) {
872 Type = LType->getElementType();
880 if (Lex.getCode() != tgtok::r_paren) {
881 TokError("expected ')' in unary operator");
884 Lex.Lex(); // eat the ')'
885 return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
895 case tgtok::XListConcat:
896 case tgtok::XStrConcat: { // Value ::= !binop '(' Value ',' Value ')'
897 tgtok::TokKind OpTok = Lex.getCode();
898 SMLoc OpLoc = Lex.getLoc();
899 Lex.Lex(); // eat the operation
901 BinOpInit::BinaryOp Code;
902 RecTy *Type = nullptr;
905 default: llvm_unreachable("Unhandled code!");
906 case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
907 case tgtok::XADD: Code = BinOpInit::ADD; Type = IntRecTy::get(); break;
908 case tgtok::XAND: Code = BinOpInit::AND; Type = IntRecTy::get(); break;
909 case tgtok::XSRA: Code = BinOpInit::SRA; Type = IntRecTy::get(); break;
910 case tgtok::XSRL: Code = BinOpInit::SRL; Type = IntRecTy::get(); break;
911 case tgtok::XSHL: Code = BinOpInit::SHL; Type = IntRecTy::get(); break;
912 case tgtok::XEq: Code = BinOpInit::EQ; Type = BitRecTy::get(); break;
913 case tgtok::XListConcat:
914 Code = BinOpInit::LISTCONCAT;
915 // We don't know the list type until we parse the first argument
917 case tgtok::XStrConcat:
918 Code = BinOpInit::STRCONCAT;
919 Type = StringRecTy::get();
923 if (Lex.getCode() != tgtok::l_paren) {
924 TokError("expected '(' after binary operator");
927 Lex.Lex(); // eat the '('
929 SmallVector<Init*, 2> InitList;
931 InitList.push_back(ParseValue(CurRec));
932 if (!InitList.back()) return nullptr;
934 while (Lex.getCode() == tgtok::comma) {
935 Lex.Lex(); // eat the ','
937 InitList.push_back(ParseValue(CurRec));
938 if (!InitList.back()) return nullptr;
941 if (Lex.getCode() != tgtok::r_paren) {
942 TokError("expected ')' in operator");
945 Lex.Lex(); // eat the ')'
947 // If we are doing !listconcat, we should know the type by now
948 if (OpTok == tgtok::XListConcat) {
949 if (VarInit *Arg0 = dyn_cast<VarInit>(InitList[0]))
950 Type = Arg0->getType();
951 else if (ListInit *Arg0 = dyn_cast<ListInit>(InitList[0]))
952 Type = Arg0->getType();
955 Error(OpLoc, "expected a list");
960 // We allow multiple operands to associative operators like !strconcat as
961 // shorthand for nesting them.
962 if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT) {
963 while (InitList.size() > 2) {
964 Init *RHS = InitList.pop_back_val();
965 RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
966 ->Fold(CurRec, CurMultiClass);
967 InitList.back() = RHS;
971 if (InitList.size() == 2)
972 return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
973 ->Fold(CurRec, CurMultiClass);
975 Error(OpLoc, "expected two operands to operator");
980 case tgtok::XForEach:
981 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
982 TernOpInit::TernaryOp Code;
983 RecTy *Type = nullptr;
985 tgtok::TokKind LexCode = Lex.getCode();
986 Lex.Lex(); // eat the operation
988 default: llvm_unreachable("Unhandled code!");
990 Code = TernOpInit::IF;
992 case tgtok::XForEach:
993 Code = TernOpInit::FOREACH;
996 Code = TernOpInit::SUBST;
999 if (Lex.getCode() != tgtok::l_paren) {
1000 TokError("expected '(' after ternary operator");
1003 Lex.Lex(); // eat the '('
1005 Init *LHS = ParseValue(CurRec);
1006 if (!LHS) return nullptr;
1008 if (Lex.getCode() != tgtok::comma) {
1009 TokError("expected ',' in ternary operator");
1012 Lex.Lex(); // eat the ','
1014 Init *MHS = ParseValue(CurRec, ItemType);
1018 if (Lex.getCode() != tgtok::comma) {
1019 TokError("expected ',' in ternary operator");
1022 Lex.Lex(); // eat the ','
1024 Init *RHS = ParseValue(CurRec, ItemType);
1028 if (Lex.getCode() != tgtok::r_paren) {
1029 TokError("expected ')' in binary operator");
1032 Lex.Lex(); // eat the ')'
1035 default: llvm_unreachable("Unhandled code!");
1037 RecTy *MHSTy = nullptr;
1038 RecTy *RHSTy = nullptr;
1040 if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1041 MHSTy = MHSt->getType();
1042 if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1043 MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1044 if (isa<BitInit>(MHS))
1045 MHSTy = BitRecTy::get();
1047 if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1048 RHSTy = RHSt->getType();
1049 if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1050 RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1051 if (isa<BitInit>(RHS))
1052 RHSTy = BitRecTy::get();
1054 // For UnsetInit, it's typed from the other hand.
1055 if (isa<UnsetInit>(MHS))
1057 if (isa<UnsetInit>(RHS))
1060 if (!MHSTy || !RHSTy) {
1061 TokError("could not get type for !if");
1065 if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1067 } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1070 TokError("inconsistent types for !if");
1075 case tgtok::XForEach: {
1076 TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1078 TokError("could not get type for !foreach");
1081 Type = MHSt->getType();
1084 case tgtok::XSubst: {
1085 TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1087 TokError("could not get type for !subst");
1090 Type = RHSt->getType();
1094 return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1100 /// ParseOperatorType - Parse a type for an operator. This returns
1103 /// OperatorType ::= '<' Type '>'
1105 RecTy *TGParser::ParseOperatorType() {
1106 RecTy *Type = nullptr;
1108 if (Lex.getCode() != tgtok::less) {
1109 TokError("expected type name for operator");
1112 Lex.Lex(); // eat the <
1117 TokError("expected type name for operator");
1121 if (Lex.getCode() != tgtok::greater) {
1122 TokError("expected type name for operator");
1125 Lex.Lex(); // eat the >
1131 /// ParseSimpleValue - Parse a tblgen value. This returns null on error.
1133 /// SimpleValue ::= IDValue
1134 /// SimpleValue ::= INTVAL
1135 /// SimpleValue ::= STRVAL+
1136 /// SimpleValue ::= CODEFRAGMENT
1137 /// SimpleValue ::= '?'
1138 /// SimpleValue ::= '{' ValueList '}'
1139 /// SimpleValue ::= ID '<' ValueListNE '>'
1140 /// SimpleValue ::= '[' ValueList ']'
1141 /// SimpleValue ::= '(' IDValue DagArgList ')'
1142 /// SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1143 /// SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1144 /// SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1145 /// SimpleValue ::= SRATOK '(' Value ',' Value ')'
1146 /// SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1147 /// SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1148 /// SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1150 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1153 switch (Lex.getCode()) {
1154 default: TokError("Unknown token when parsing a value"); break;
1156 // This is a leading paste operation. This is deprecated but
1157 // still exists in some .td files. Ignore it.
1158 Lex.Lex(); // Skip '#'.
1159 return ParseSimpleValue(CurRec, ItemType, Mode);
1160 case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1161 case tgtok::BinaryIntVal: {
1162 auto BinaryVal = Lex.getCurBinaryIntVal();
1163 SmallVector<Init*, 16> Bits(BinaryVal.second);
1164 for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
1165 Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
1166 R = BitsInit::get(Bits);
1170 case tgtok::StrVal: {
1171 std::string Val = Lex.getCurStrVal();
1174 // Handle multiple consecutive concatenated strings.
1175 while (Lex.getCode() == tgtok::StrVal) {
1176 Val += Lex.getCurStrVal();
1180 R = StringInit::get(Val);
1183 case tgtok::CodeFragment:
1184 R = StringInit::get(Lex.getCurStrVal());
1187 case tgtok::question:
1188 R = UnsetInit::get();
1192 SMLoc NameLoc = Lex.getLoc();
1193 std::string Name = Lex.getCurStrVal();
1194 if (Lex.Lex() != tgtok::less) // consume the Id.
1195 return ParseIDValue(CurRec, Name, NameLoc, Mode); // Value ::= IDValue
1197 // Value ::= ID '<' ValueListNE '>'
1198 if (Lex.Lex() == tgtok::greater) {
1199 TokError("expected non-empty value list");
1203 // This is a CLASS<initvalslist> expression. This is supposed to synthesize
1204 // a new anonymous definition, deriving from CLASS<initvalslist> with no
1206 Record *Class = Records.getClass(Name);
1208 Error(NameLoc, "Expected a class name, got '" + Name + "'");
1212 std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1213 if (ValueList.empty()) return nullptr;
1215 if (Lex.getCode() != tgtok::greater) {
1216 TokError("expected '>' at end of value list");
1219 Lex.Lex(); // eat the '>'
1220 SMLoc EndLoc = Lex.getLoc();
1222 // Create the new record, set it as CurRec temporarily.
1223 auto NewRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), NameLoc,
1224 Records, /*IsAnonymous=*/true);
1225 Record *NewRec = NewRecOwner.get(); // Keep a copy since we may release.
1226 SubClassReference SCRef;
1227 SCRef.RefRange = SMRange(NameLoc, EndLoc);
1229 SCRef.TemplateArgs = ValueList;
1230 // Add info about the subclass to NewRec.
1231 if (AddSubClass(NewRec, SCRef))
1234 if (!CurMultiClass) {
1235 NewRec->resolveReferences();
1236 Records.addDef(std::move(NewRecOwner));
1238 // This needs to get resolved once the multiclass template arguments are
1239 // known before any use.
1240 NewRec->setResolveFirst(true);
1241 // Otherwise, we're inside a multiclass, add it to the multiclass.
1242 CurMultiClass->DefPrototypes.push_back(std::move(NewRecOwner));
1244 // Copy the template arguments for the multiclass into the def.
1245 for (Init *TArg : CurMultiClass->Rec.getTemplateArgs()) {
1246 const RecordVal *RV = CurMultiClass->Rec.getValue(TArg);
1247 assert(RV && "Template arg doesn't exist?");
1248 NewRec->addValue(*RV);
1251 // We can't return the prototype def here, instead return:
1252 // !cast<ItemType>(!strconcat(NAME, AnonName)).
1253 const RecordVal *MCNameRV = CurMultiClass->Rec.getValue("NAME");
1254 assert(MCNameRV && "multiclass record must have a NAME");
1256 return UnOpInit::get(UnOpInit::CAST,
1257 BinOpInit::get(BinOpInit::STRCONCAT,
1258 VarInit::get(MCNameRV->getName(),
1259 MCNameRV->getType()),
1260 NewRec->getNameInit(),
1261 StringRecTy::get()),
1262 Class->getDefInit()->getType());
1265 // The result of the expression is a reference to the new record.
1266 return DefInit::get(NewRec);
1268 case tgtok::l_brace: { // Value ::= '{' ValueList '}'
1269 SMLoc BraceLoc = Lex.getLoc();
1270 Lex.Lex(); // eat the '{'
1271 std::vector<Init*> Vals;
1273 if (Lex.getCode() != tgtok::r_brace) {
1274 Vals = ParseValueList(CurRec);
1275 if (Vals.empty()) return nullptr;
1277 if (Lex.getCode() != tgtok::r_brace) {
1278 TokError("expected '}' at end of bit list value");
1281 Lex.Lex(); // eat the '}'
1283 SmallVector<Init *, 16> NewBits;
1285 // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
1286 // first. We'll first read everything in to a vector, then we can reverse
1287 // it to get the bits in the correct order for the BitsInit value.
1288 for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1289 // FIXME: The following two loops would not be duplicated
1290 // if the API was a little more orthogonal.
1292 // bits<n> values are allowed to initialize n bits.
1293 if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
1294 for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
1295 NewBits.push_back(BI->getBit((e - i) - 1));
1298 // bits<n> can also come from variable initializers.
1299 if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
1300 if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
1301 for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
1302 NewBits.push_back(VI->getBit((e - i) - 1));
1305 // Fallthrough to try convert this to a bit.
1307 // All other values must be convertible to just a single bit.
1308 Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1310 Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1311 ") is not convertable to a bit");
1314 NewBits.push_back(Bit);
1316 std::reverse(NewBits.begin(), NewBits.end());
1317 return BitsInit::get(NewBits);
1319 case tgtok::l_square: { // Value ::= '[' ValueList ']'
1320 Lex.Lex(); // eat the '['
1321 std::vector<Init*> Vals;
1323 RecTy *DeducedEltTy = nullptr;
1324 ListRecTy *GivenListTy = nullptr;
1327 ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1330 raw_string_ostream ss(s);
1331 ss << "Type mismatch for list, expected list type, got "
1332 << ItemType->getAsString();
1336 GivenListTy = ListType;
1339 if (Lex.getCode() != tgtok::r_square) {
1340 Vals = ParseValueList(CurRec, nullptr,
1341 GivenListTy ? GivenListTy->getElementType() : nullptr);
1342 if (Vals.empty()) return nullptr;
1344 if (Lex.getCode() != tgtok::r_square) {
1345 TokError("expected ']' at end of list value");
1348 Lex.Lex(); // eat the ']'
1350 RecTy *GivenEltTy = nullptr;
1351 if (Lex.getCode() == tgtok::less) {
1352 // Optional list element type
1353 Lex.Lex(); // eat the '<'
1355 GivenEltTy = ParseType();
1357 // Couldn't parse element type
1361 if (Lex.getCode() != tgtok::greater) {
1362 TokError("expected '>' at end of list element type");
1365 Lex.Lex(); // eat the '>'
1369 RecTy *EltTy = nullptr;
1370 for (Init *V : Vals) {
1371 TypedInit *TArg = dyn_cast<TypedInit>(V);
1373 TokError("Untyped list element");
1377 EltTy = resolveTypes(EltTy, TArg->getType());
1379 TokError("Incompatible types in list elements");
1383 EltTy = TArg->getType();
1389 // Verify consistency
1390 if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1391 TokError("Incompatible types in list elements");
1400 TokError("No type for list");
1403 DeducedEltTy = GivenListTy->getElementType();
1405 // Make sure the deduced type is compatible with the given type
1407 if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1408 TokError("Element type mismatch for list");
1412 DeducedEltTy = EltTy;
1415 return ListInit::get(Vals, DeducedEltTy);
1417 case tgtok::l_paren: { // Value ::= '(' IDValue DagArgList ')'
1418 Lex.Lex(); // eat the '('
1419 if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1420 TokError("expected identifier in dag init");
1424 Init *Operator = ParseValue(CurRec);
1425 if (!Operator) return nullptr;
1427 // If the operator name is present, parse it.
1428 std::string OperatorName;
1429 if (Lex.getCode() == tgtok::colon) {
1430 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1431 TokError("expected variable name in dag operator");
1434 OperatorName = Lex.getCurStrVal();
1435 Lex.Lex(); // eat the VarName.
1438 std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1439 if (Lex.getCode() != tgtok::r_paren) {
1440 DagArgs = ParseDagArgList(CurRec);
1441 if (DagArgs.empty()) return nullptr;
1444 if (Lex.getCode() != tgtok::r_paren) {
1445 TokError("expected ')' in dag init");
1448 Lex.Lex(); // eat the ')'
1450 return DagInit::get(Operator, OperatorName, DagArgs);
1456 case tgtok::XCast: // Value ::= !unop '(' Value ')'
1457 case tgtok::XConcat:
1464 case tgtok::XListConcat:
1465 case tgtok::XStrConcat: // Value ::= !binop '(' Value ',' Value ')'
1467 case tgtok::XForEach:
1468 case tgtok::XSubst: { // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1469 return ParseOperation(CurRec, ItemType);
1476 /// ParseValue - Parse a tblgen value. This returns null on error.
1478 /// Value ::= SimpleValue ValueSuffix*
1479 /// ValueSuffix ::= '{' BitList '}'
1480 /// ValueSuffix ::= '[' BitList ']'
1481 /// ValueSuffix ::= '.' ID
1483 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1484 Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1485 if (!Result) return nullptr;
1487 // Parse the suffixes now if present.
1489 switch (Lex.getCode()) {
1490 default: return Result;
1491 case tgtok::l_brace: {
1492 if (Mode == ParseNameMode || Mode == ParseForeachMode)
1493 // This is the beginning of the object body.
1496 SMLoc CurlyLoc = Lex.getLoc();
1497 Lex.Lex(); // eat the '{'
1498 std::vector<unsigned> Ranges = ParseRangeList();
1499 if (Ranges.empty()) return nullptr;
1501 // Reverse the bitlist.
1502 std::reverse(Ranges.begin(), Ranges.end());
1503 Result = Result->convertInitializerBitRange(Ranges);
1505 Error(CurlyLoc, "Invalid bit range for value");
1510 if (Lex.getCode() != tgtok::r_brace) {
1511 TokError("expected '}' at end of bit range list");
1517 case tgtok::l_square: {
1518 SMLoc SquareLoc = Lex.getLoc();
1519 Lex.Lex(); // eat the '['
1520 std::vector<unsigned> Ranges = ParseRangeList();
1521 if (Ranges.empty()) return nullptr;
1523 Result = Result->convertInitListSlice(Ranges);
1525 Error(SquareLoc, "Invalid range for list slice");
1530 if (Lex.getCode() != tgtok::r_square) {
1531 TokError("expected ']' at end of list slice");
1538 if (Lex.Lex() != tgtok::Id) { // eat the .
1539 TokError("expected field identifier after '.'");
1542 if (!Result->getFieldType(Lex.getCurStrVal())) {
1543 TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1544 Result->getAsString() + "'");
1547 Result = FieldInit::get(Result, Lex.getCurStrVal());
1548 Lex.Lex(); // eat field name
1552 SMLoc PasteLoc = Lex.getLoc();
1554 // Create a !strconcat() operation, first casting each operand to
1555 // a string if necessary.
1557 TypedInit *LHS = dyn_cast<TypedInit>(Result);
1559 Error(PasteLoc, "LHS of paste is not typed!");
1563 if (LHS->getType() != StringRecTy::get()) {
1564 LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1567 TypedInit *RHS = nullptr;
1569 Lex.Lex(); // Eat the '#'.
1570 switch (Lex.getCode()) {
1573 case tgtok::l_brace:
1574 // These are all of the tokens that can begin an object body.
1575 // Some of these can also begin values but we disallow those cases
1576 // because they are unlikely to be useful.
1578 // Trailing paste, concat with an empty string.
1579 RHS = StringInit::get("");
1583 Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1584 RHS = dyn_cast<TypedInit>(RHSResult);
1586 Error(PasteLoc, "RHS of paste is not typed!");
1590 if (RHS->getType() != StringRecTy::get()) {
1591 RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1597 Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1598 StringRecTy::get())->Fold(CurRec, CurMultiClass);
1604 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1606 /// DagArg ::= Value (':' VARNAME)?
1607 /// DagArg ::= VARNAME
1608 /// DagArgList ::= DagArg
1609 /// DagArgList ::= DagArgList ',' DagArg
1610 std::vector<std::pair<llvm::Init*, std::string> >
1611 TGParser::ParseDagArgList(Record *CurRec) {
1612 std::vector<std::pair<llvm::Init*, std::string> > Result;
1615 // DagArg ::= VARNAME
1616 if (Lex.getCode() == tgtok::VarName) {
1617 // A missing value is treated like '?'.
1618 Result.push_back(std::make_pair(UnsetInit::get(), Lex.getCurStrVal()));
1621 // DagArg ::= Value (':' VARNAME)?
1622 Init *Val = ParseValue(CurRec);
1624 return std::vector<std::pair<llvm::Init*, std::string> >();
1626 // If the variable name is present, add it.
1627 std::string VarName;
1628 if (Lex.getCode() == tgtok::colon) {
1629 if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1630 TokError("expected variable name in dag literal");
1631 return std::vector<std::pair<llvm::Init*, std::string> >();
1633 VarName = Lex.getCurStrVal();
1634 Lex.Lex(); // eat the VarName.
1637 Result.push_back(std::make_pair(Val, VarName));
1639 if (Lex.getCode() != tgtok::comma) break;
1640 Lex.Lex(); // eat the ','
1647 /// ParseValueList - Parse a comma separated list of values, returning them as a
1648 /// vector. Note that this always expects to be able to parse at least one
1649 /// value. It returns an empty list if this is not possible.
1651 /// ValueList ::= Value (',' Value)
1653 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1655 std::vector<Init*> Result;
1656 RecTy *ItemType = EltTy;
1657 unsigned int ArgN = 0;
1658 if (ArgsRec && !EltTy) {
1659 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1660 if (TArgs.empty()) {
1661 TokError("template argument provided to non-template class");
1662 return std::vector<Init*>();
1664 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1666 errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1669 assert(RV && "Template argument record not found??");
1670 ItemType = RV->getType();
1673 Result.push_back(ParseValue(CurRec, ItemType));
1674 if (!Result.back()) return std::vector<Init*>();
1676 while (Lex.getCode() == tgtok::comma) {
1677 Lex.Lex(); // Eat the comma
1679 if (ArgsRec && !EltTy) {
1680 const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1681 if (ArgN >= TArgs.size()) {
1682 TokError("too many template arguments");
1683 return std::vector<Init*>();
1685 const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1686 assert(RV && "Template argument record not found??");
1687 ItemType = RV->getType();
1690 Result.push_back(ParseValue(CurRec, ItemType));
1691 if (!Result.back()) return std::vector<Init*>();
1698 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1699 /// empty string on error. This can happen in a number of different context's,
1700 /// including within a def or in the template args for a def (which which case
1701 /// CurRec will be non-null) and within the template args for a multiclass (in
1702 /// which case CurRec will be null, but CurMultiClass will be set). This can
1703 /// also happen within a def that is within a multiclass, which will set both
1704 /// CurRec and CurMultiClass.
1706 /// Declaration ::= FIELD? Type ID ('=' Value)?
1708 Init *TGParser::ParseDeclaration(Record *CurRec,
1709 bool ParsingTemplateArgs) {
1710 // Read the field prefix if present.
1711 bool HasField = Lex.getCode() == tgtok::Field;
1712 if (HasField) Lex.Lex();
1714 RecTy *Type = ParseType();
1715 if (!Type) return nullptr;
1717 if (Lex.getCode() != tgtok::Id) {
1718 TokError("Expected identifier in declaration");
1722 SMLoc IdLoc = Lex.getLoc();
1723 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1726 if (ParsingTemplateArgs) {
1728 DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1730 assert(CurMultiClass);
1733 DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1738 if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1741 // If a value is present, parse it.
1742 if (Lex.getCode() == tgtok::equal) {
1744 SMLoc ValLoc = Lex.getLoc();
1745 Init *Val = ParseValue(CurRec, Type);
1747 SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1748 // Return the name, even if an error is thrown. This is so that we can
1749 // continue to make some progress, even without the value having been
1757 /// ParseForeachDeclaration - Read a foreach declaration, returning
1758 /// the name of the declared object or a NULL Init on error. Return
1759 /// the name of the parsed initializer list through ForeachListName.
1761 /// ForeachDeclaration ::= ID '=' '[' ValueList ']'
1762 /// ForeachDeclaration ::= ID '=' '{' RangeList '}'
1763 /// ForeachDeclaration ::= ID '=' RangePiece
1765 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1766 if (Lex.getCode() != tgtok::Id) {
1767 TokError("Expected identifier in foreach declaration");
1771 Init *DeclName = StringInit::get(Lex.getCurStrVal());
1774 // If a value is present, parse it.
1775 if (Lex.getCode() != tgtok::equal) {
1776 TokError("Expected '=' in foreach declaration");
1779 Lex.Lex(); // Eat the '='
1781 RecTy *IterType = nullptr;
1782 std::vector<unsigned> Ranges;
1784 switch (Lex.getCode()) {
1785 default: TokError("Unknown token when expecting a range list"); return nullptr;
1786 case tgtok::l_square: { // '[' ValueList ']'
1787 Init *List = ParseSimpleValue(nullptr, nullptr, ParseForeachMode);
1788 ForeachListValue = dyn_cast<ListInit>(List);
1789 if (!ForeachListValue) {
1790 TokError("Expected a Value list");
1793 RecTy *ValueType = ForeachListValue->getType();
1794 ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1796 TokError("Value list is not of list type");
1799 IterType = ListType->getElementType();
1803 case tgtok::IntVal: { // RangePiece.
1804 if (ParseRangePiece(Ranges))
1809 case tgtok::l_brace: { // '{' RangeList '}'
1810 Lex.Lex(); // eat the '{'
1811 Ranges = ParseRangeList();
1812 if (Lex.getCode() != tgtok::r_brace) {
1813 TokError("expected '}' at end of bit range list");
1821 if (!Ranges.empty()) {
1822 assert(!IterType && "Type already initialized?");
1823 IterType = IntRecTy::get();
1824 std::vector<Init*> Values;
1825 for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
1826 Values.push_back(IntInit::get(Ranges[i]));
1827 ForeachListValue = ListInit::get(Values, IterType);
1833 return VarInit::get(DeclName, IterType);
1836 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1837 /// sequence of template-declarations in <>'s. If CurRec is non-null, these are
1838 /// template args for a def, which may or may not be in a multiclass. If null,
1839 /// these are the template args for a multiclass.
1841 /// TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1843 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1844 assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1845 Lex.Lex(); // eat the '<'
1847 Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1849 // Read the first declaration.
1850 Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1854 TheRecToAddTo->addTemplateArg(TemplArg);
1856 while (Lex.getCode() == tgtok::comma) {
1857 Lex.Lex(); // eat the ','
1859 // Read the following declarations.
1860 TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1863 TheRecToAddTo->addTemplateArg(TemplArg);
1866 if (Lex.getCode() != tgtok::greater)
1867 return TokError("expected '>' at end of template argument list");
1868 Lex.Lex(); // eat the '>'.
1873 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1875 /// BodyItem ::= Declaration ';'
1876 /// BodyItem ::= LET ID OptionalBitList '=' Value ';'
1877 bool TGParser::ParseBodyItem(Record *CurRec) {
1878 if (Lex.getCode() != tgtok::Let) {
1879 if (!ParseDeclaration(CurRec, false))
1882 if (Lex.getCode() != tgtok::semi)
1883 return TokError("expected ';' after declaration");
1888 // LET ID OptionalRangeList '=' Value ';'
1889 if (Lex.Lex() != tgtok::Id)
1890 return TokError("expected field identifier after let");
1892 SMLoc IdLoc = Lex.getLoc();
1893 std::string FieldName = Lex.getCurStrVal();
1894 Lex.Lex(); // eat the field name.
1896 std::vector<unsigned> BitList;
1897 if (ParseOptionalBitList(BitList))
1899 std::reverse(BitList.begin(), BitList.end());
1901 if (Lex.getCode() != tgtok::equal)
1902 return TokError("expected '=' in let expression");
1903 Lex.Lex(); // eat the '='.
1905 RecordVal *Field = CurRec->getValue(FieldName);
1907 return TokError("Value '" + FieldName + "' unknown!");
1909 RecTy *Type = Field->getType();
1911 Init *Val = ParseValue(CurRec, Type);
1912 if (!Val) return true;
1914 if (Lex.getCode() != tgtok::semi)
1915 return TokError("expected ';' after let expression");
1918 return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1921 /// ParseBody - Read the body of a class or def. Return true on error, false on
1925 /// Body ::= '{' BodyList '}'
1926 /// BodyList BodyItem*
1928 bool TGParser::ParseBody(Record *CurRec) {
1929 // If this is a null definition, just eat the semi and return.
1930 if (Lex.getCode() == tgtok::semi) {
1935 if (Lex.getCode() != tgtok::l_brace)
1936 return TokError("Expected ';' or '{' to start body");
1940 while (Lex.getCode() != tgtok::r_brace)
1941 if (ParseBodyItem(CurRec))
1949 /// \brief Apply the current let bindings to \a CurRec.
1950 /// \returns true on error, false otherwise.
1951 bool TGParser::ApplyLetStack(Record *CurRec) {
1952 for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1953 for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1954 if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1955 LetStack[i][j].Bits, LetStack[i][j].Value))
1960 /// ParseObjectBody - Parse the body of a def or class. This consists of an
1961 /// optional ClassList followed by a Body. CurRec is the current def or class
1962 /// that is being parsed.
1964 /// ObjectBody ::= BaseClassList Body
1965 /// BaseClassList ::= /*empty*/
1966 /// BaseClassList ::= ':' BaseClassListNE
1967 /// BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1969 bool TGParser::ParseObjectBody(Record *CurRec) {
1970 // If there is a baseclass list, read it.
1971 if (Lex.getCode() == tgtok::colon) {
1974 // Read all of the subclasses.
1975 SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1978 if (!SubClass.Rec) return true;
1981 if (AddSubClass(CurRec, SubClass))
1984 if (Lex.getCode() != tgtok::comma) break;
1985 Lex.Lex(); // eat ','.
1986 SubClass = ParseSubClassReference(CurRec, false);
1990 if (ApplyLetStack(CurRec))
1993 return ParseBody(CurRec);
1996 /// ParseDef - Parse and return a top level or multiclass def, return the record
1997 /// corresponding to it. This returns null on error.
1999 /// DefInst ::= DEF ObjectName ObjectBody
2001 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
2002 SMLoc DefLoc = Lex.getLoc();
2003 assert(Lex.getCode() == tgtok::Def && "Unknown tok");
2004 Lex.Lex(); // Eat the 'def' token.
2006 // Parse ObjectName and make a record for it.
2007 std::unique_ptr<Record> CurRecOwner;
2008 Init *Name = ParseObjectName(CurMultiClass);
2010 CurRecOwner = make_unique<Record>(Name, DefLoc, Records);
2012 CurRecOwner = llvm::make_unique<Record>(GetNewAnonymousName(), DefLoc,
2013 Records, /*IsAnonymous=*/true);
2014 Record *CurRec = CurRecOwner.get(); // Keep a copy since we may release.
2016 if (!CurMultiClass && Loops.empty()) {
2017 // Top-level def definition.
2019 // Ensure redefinition doesn't happen.
2020 if (Records.getDef(CurRec->getNameInitAsString()))
2021 return Error(DefLoc, "def '" + CurRec->getNameInitAsString()+
2022 "' already defined");
2023 Records.addDef(std::move(CurRecOwner));
2025 if (ParseObjectBody(CurRec))
2027 } else if (CurMultiClass) {
2028 // Parse the body before adding this prototype to the DefPrototypes vector.
2029 // That way implicit definitions will be added to the DefPrototypes vector
2030 // before this object, instantiated prior to defs derived from this object,
2031 // and this available for indirect name resolution when defs derived from
2032 // this object are instantiated.
2033 if (ParseObjectBody(CurRec))
2036 // Otherwise, a def inside a multiclass, add it to the multiclass.
2037 for (const auto &Proto : CurMultiClass->DefPrototypes)
2038 if (Proto->getNameInit() == CurRec->getNameInit())
2039 return Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
2040 "' already defined in this multiclass!");
2041 CurMultiClass->DefPrototypes.push_back(std::move(CurRecOwner));
2042 } else if (ParseObjectBody(CurRec)) {
2046 if (!CurMultiClass) // Def's in multiclasses aren't really defs.
2047 // See Record::setName(). This resolve step will see any new name
2048 // for the def that might have been created when resolving
2049 // inheritance, values and arguments above.
2050 CurRec->resolveReferences();
2052 // If ObjectBody has template arguments, it's an error.
2053 assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
2055 if (CurMultiClass) {
2056 // Copy the template arguments for the multiclass into the def.
2057 for (Init *TArg : CurMultiClass->Rec.getTemplateArgs()) {
2058 const RecordVal *RV = CurMultiClass->Rec.getValue(TArg);
2059 assert(RV && "Template arg doesn't exist?");
2060 CurRec->addValue(*RV);
2064 if (ProcessForeachDefs(CurRec, DefLoc)) {
2065 return Error(DefLoc, "Could not process loops for def" +
2066 CurRec->getNameInitAsString());
2072 /// ParseForeach - Parse a for statement. Return the record corresponding
2073 /// to it. This returns true on error.
2075 /// Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2076 /// Foreach ::= FOREACH Declaration IN Object
2078 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2079 assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2080 Lex.Lex(); // Eat the 'for' token.
2082 // Make a temporary object to record items associated with the for
2084 ListInit *ListValue = nullptr;
2085 VarInit *IterName = ParseForeachDeclaration(ListValue);
2087 return TokError("expected declaration in for");
2089 if (Lex.getCode() != tgtok::In)
2090 return TokError("Unknown tok");
2091 Lex.Lex(); // Eat the in
2093 // Create a loop object and remember it.
2094 Loops.push_back(ForeachLoop(IterName, ListValue));
2096 if (Lex.getCode() != tgtok::l_brace) {
2097 // FOREACH Declaration IN Object
2098 if (ParseObject(CurMultiClass))
2102 SMLoc BraceLoc = Lex.getLoc();
2103 // Otherwise, this is a group foreach.
2104 Lex.Lex(); // eat the '{'.
2106 // Parse the object list.
2107 if (ParseObjectList(CurMultiClass))
2110 if (Lex.getCode() != tgtok::r_brace) {
2111 TokError("expected '}' at end of foreach command");
2112 return Error(BraceLoc, "to match this '{'");
2114 Lex.Lex(); // Eat the }
2117 // We've processed everything in this loop.
2123 /// ParseClass - Parse a tblgen class definition.
2125 /// ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2127 bool TGParser::ParseClass() {
2128 assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2131 if (Lex.getCode() != tgtok::Id)
2132 return TokError("expected class name after 'class' keyword");
2134 Record *CurRec = Records.getClass(Lex.getCurStrVal());
2136 // If the body was previously defined, this is an error.
2137 if (CurRec->getValues().size() > 1 || // Account for NAME.
2138 !CurRec->getSuperClasses().empty() ||
2139 !CurRec->getTemplateArgs().empty())
2140 return TokError("Class '" + CurRec->getNameInitAsString() +
2141 "' already defined");
2143 // If this is the first reference to this class, create and add it.
2145 llvm::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records);
2146 CurRec = NewRec.get();
2147 Records.addClass(std::move(NewRec));
2149 Lex.Lex(); // eat the name.
2151 // If there are template args, parse them.
2152 if (Lex.getCode() == tgtok::less)
2153 if (ParseTemplateArgList(CurRec))
2156 // Finally, parse the object body.
2157 return ParseObjectBody(CurRec);
2160 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2163 /// LetList ::= LetItem (',' LetItem)*
2164 /// LetItem ::= ID OptionalRangeList '=' Value
2166 std::vector<LetRecord> TGParser::ParseLetList() {
2167 std::vector<LetRecord> Result;
2170 if (Lex.getCode() != tgtok::Id) {
2171 TokError("expected identifier in let definition");
2172 return std::vector<LetRecord>();
2174 std::string Name = Lex.getCurStrVal();
2175 SMLoc NameLoc = Lex.getLoc();
2176 Lex.Lex(); // Eat the identifier.
2178 // Check for an optional RangeList.
2179 std::vector<unsigned> Bits;
2180 if (ParseOptionalRangeList(Bits))
2181 return std::vector<LetRecord>();
2182 std::reverse(Bits.begin(), Bits.end());
2184 if (Lex.getCode() != tgtok::equal) {
2185 TokError("expected '=' in let expression");
2186 return std::vector<LetRecord>();
2188 Lex.Lex(); // eat the '='.
2190 Init *Val = ParseValue(nullptr);
2191 if (!Val) return std::vector<LetRecord>();
2193 // Now that we have everything, add the record.
2194 Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
2196 if (Lex.getCode() != tgtok::comma)
2198 Lex.Lex(); // eat the comma.
2202 /// ParseTopLevelLet - Parse a 'let' at top level. This can be a couple of
2203 /// different related productions. This works inside multiclasses too.
2205 /// Object ::= LET LetList IN '{' ObjectList '}'
2206 /// Object ::= LET LetList IN Object
2208 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2209 assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2212 // Add this entry to the let stack.
2213 std::vector<LetRecord> LetInfo = ParseLetList();
2214 if (LetInfo.empty()) return true;
2215 LetStack.push_back(std::move(LetInfo));
2217 if (Lex.getCode() != tgtok::In)
2218 return TokError("expected 'in' at end of top-level 'let'");
2221 // If this is a scalar let, just handle it now
2222 if (Lex.getCode() != tgtok::l_brace) {
2223 // LET LetList IN Object
2224 if (ParseObject(CurMultiClass))
2226 } else { // Object ::= LETCommand '{' ObjectList '}'
2227 SMLoc BraceLoc = Lex.getLoc();
2228 // Otherwise, this is a group let.
2229 Lex.Lex(); // eat the '{'.
2231 // Parse the object list.
2232 if (ParseObjectList(CurMultiClass))
2235 if (Lex.getCode() != tgtok::r_brace) {
2236 TokError("expected '}' at end of top level let command");
2237 return Error(BraceLoc, "to match this '{'");
2242 // Outside this let scope, this let block is not active.
2243 LetStack.pop_back();
2247 /// ParseMultiClass - Parse a multiclass definition.
2249 /// MultiClassInst ::= MULTICLASS ID TemplateArgList?
2250 /// ':' BaseMultiClassList '{' MultiClassObject+ '}'
2251 /// MultiClassObject ::= DefInst
2252 /// MultiClassObject ::= MultiClassInst
2253 /// MultiClassObject ::= DefMInst
2254 /// MultiClassObject ::= LETCommand '{' ObjectList '}'
2255 /// MultiClassObject ::= LETCommand Object
2257 bool TGParser::ParseMultiClass() {
2258 assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2259 Lex.Lex(); // Eat the multiclass token.
2261 if (Lex.getCode() != tgtok::Id)
2262 return TokError("expected identifier after multiclass for name");
2263 std::string Name = Lex.getCurStrVal();
2266 MultiClasses.insert(std::make_pair(Name,
2267 llvm::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
2270 return TokError("multiclass '" + Name + "' already defined");
2272 CurMultiClass = Result.first->second.get();
2273 Lex.Lex(); // Eat the identifier.
2275 // If there are template args, parse them.
2276 if (Lex.getCode() == tgtok::less)
2277 if (ParseTemplateArgList(nullptr))
2280 bool inherits = false;
2282 // If there are submulticlasses, parse them.
2283 if (Lex.getCode() == tgtok::colon) {
2288 // Read all of the submulticlasses.
2289 SubMultiClassReference SubMultiClass =
2290 ParseSubMultiClassReference(CurMultiClass);
2293 if (!SubMultiClass.MC) return true;
2296 if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2299 if (Lex.getCode() != tgtok::comma) break;
2300 Lex.Lex(); // eat ','.
2301 SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2305 if (Lex.getCode() != tgtok::l_brace) {
2307 return TokError("expected '{' in multiclass definition");
2308 if (Lex.getCode() != tgtok::semi)
2309 return TokError("expected ';' in multiclass definition");
2310 Lex.Lex(); // eat the ';'.
2312 if (Lex.Lex() == tgtok::r_brace) // eat the '{'.
2313 return TokError("multiclass must contain at least one def");
2315 while (Lex.getCode() != tgtok::r_brace) {
2316 switch (Lex.getCode()) {
2318 return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2322 case tgtok::Foreach:
2323 if (ParseObject(CurMultiClass))
2328 Lex.Lex(); // eat the '}'.
2331 CurMultiClass = nullptr;
2336 InstantiateMulticlassDef(MultiClass &MC,
2339 SMRange DefmPrefixRange) {
2340 // We need to preserve DefProto so it can be reused for later
2341 // instantiations, so create a new Record to inherit from it.
2343 // Add in the defm name. If the defm prefix is empty, give each
2344 // instantiated def a unique name. Otherwise, if "#NAME#" exists in the
2345 // name, substitute the prefix for #NAME#. Otherwise, use the defm name
2348 bool IsAnonymous = false;
2350 DefmPrefix = StringInit::get(GetNewAnonymousName());
2354 Init *DefName = DefProto->getNameInit();
2356 StringInit *DefNameString = dyn_cast<StringInit>(DefName);
2358 if (DefNameString) {
2359 // We have a fully expanded string so there are no operators to
2360 // resolve. We should concatenate the given prefix and name.
2362 BinOpInit::get(BinOpInit::STRCONCAT,
2363 UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2364 StringRecTy::get())->Fold(DefProto, &MC),
2365 DefName, StringRecTy::get())->Fold(DefProto, &MC);
2368 // Make a trail of SMLocs from the multiclass instantiations.
2369 SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
2370 Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2371 auto CurRec = make_unique<Record>(DefName, Locs, Records, IsAnonymous);
2373 SubClassReference Ref;
2374 Ref.RefRange = DefmPrefixRange;
2376 AddSubClass(CurRec.get(), Ref);
2378 // Set the value for NAME. We don't resolve references to it 'til later,
2379 // though, so that uses in nested multiclass names don't get
2381 if (SetValue(CurRec.get(), Ref.RefRange.Start, "NAME",
2382 std::vector<unsigned>(), DefmPrefix)) {
2383 Error(DefmPrefixRange.Start, "Could not resolve " +
2384 CurRec->getNameInitAsString() + ":NAME to '" +
2385 DefmPrefix->getAsUnquotedString() + "'");
2389 // If the DefNameString didn't resolve, we probably have a reference to
2390 // NAME and need to replace it. We need to do at least this much greedily,
2391 // otherwise nested multiclasses will end up with incorrect NAME expansions.
2392 if (!DefNameString) {
2393 RecordVal *DefNameRV = CurRec->getValue("NAME");
2394 CurRec->resolveReferencesTo(DefNameRV);
2397 if (!CurMultiClass) {
2398 // Now that we're at the top level, resolve all NAME references
2399 // in the resultant defs that weren't in the def names themselves.
2400 RecordVal *DefNameRV = CurRec->getValue("NAME");
2401 CurRec->resolveReferencesTo(DefNameRV);
2403 // Now that NAME references are resolved and we're at the top level of
2404 // any multiclass expansions, add the record to the RecordKeeper. If we are
2405 // currently in a multiclass, it means this defm appears inside a
2406 // multiclass and its name won't be fully resolvable until we see
2407 // the top-level defm. Therefore, we don't add this to the
2408 // RecordKeeper at this point. If we did we could get duplicate
2409 // defs as more than one probably refers to NAME or some other
2410 // common internal placeholder.
2412 // Ensure redefinition doesn't happen.
2413 if (Records.getDef(CurRec->getNameInitAsString())) {
2414 Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
2415 "' already defined, instantiating defm with subdef '" +
2416 DefProto->getNameInitAsString() + "'");
2420 Record *CurRecSave = CurRec.get(); // Keep a copy before we release.
2421 Records.addDef(std::move(CurRec));
2425 // FIXME This is bad but the ownership transfer to caller is pretty messy.
2426 // The unique_ptr in this function at least protects the exits above.
2427 return CurRec.release();
2430 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2432 SMLoc DefmPrefixLoc,
2434 const std::vector<Init *> &TArgs,
2435 std::vector<Init *> &TemplateVals,
2437 // Loop over all of the template arguments, setting them to the specified
2438 // value or leaving them as the default if necessary.
2439 for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2440 // Check if a value is specified for this temp-arg.
2441 if (i < TemplateVals.size()) {
2443 if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2448 CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2452 CurRec->removeValue(TArgs[i]);
2454 } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2455 return Error(SubClassLoc, "value not specified for template argument #" +
2456 utostr(i) + " (" + TArgs[i]->getAsUnquotedString() +
2457 ") of multiclassclass '" + MC.Rec.getNameInitAsString() +
2464 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2467 SMLoc DefmPrefixLoc) {
2468 // If the mdef is inside a 'let' expression, add to each def.
2469 if (ApplyLetStack(CurRec))
2470 return Error(DefmPrefixLoc, "when instantiating this defm");
2472 // Don't create a top level definition for defm inside multiclasses,
2473 // instead, only update the prototypes and bind the template args
2474 // with the new created definition.
2477 for (const auto &Proto : CurMultiClass->DefPrototypes)
2478 if (Proto->getNameInit() == CurRec->getNameInit())
2479 return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2480 "' already defined in this multiclass!");
2481 CurMultiClass->DefPrototypes.push_back(std::unique_ptr<Record>(CurRec));
2483 // Copy the template arguments for the multiclass into the new def.
2484 for (Init * TA : CurMultiClass->Rec.getTemplateArgs()) {
2485 const RecordVal *RV = CurMultiClass->Rec.getValue(TA);
2486 assert(RV && "Template arg doesn't exist?");
2487 CurRec->addValue(*RV);
2493 /// ParseDefm - Parse the instantiation of a multiclass.
2495 /// DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2497 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2498 assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2499 SMLoc DefmLoc = Lex.getLoc();
2500 Init *DefmPrefix = nullptr;
2502 if (Lex.Lex() == tgtok::Id) { // eat the defm.
2503 DefmPrefix = ParseObjectName(CurMultiClass);
2506 SMLoc DefmPrefixEndLoc = Lex.getLoc();
2507 if (Lex.getCode() != tgtok::colon)
2508 return TokError("expected ':' after defm identifier");
2510 // Keep track of the new generated record definitions.
2511 std::vector<Record*> NewRecDefs;
2513 // This record also inherits from a regular class (non-multiclass)?
2514 bool InheritFromClass = false;
2519 SMLoc SubClassLoc = Lex.getLoc();
2520 SubClassReference Ref = ParseSubClassReference(nullptr, true);
2523 if (!Ref.Rec) return true;
2525 // To instantiate a multiclass, we need to first get the multiclass, then
2526 // instantiate each def contained in the multiclass with the SubClassRef
2527 // template parameters.
2528 MultiClass *MC = MultiClasses[Ref.Rec->getName()].get();
2529 assert(MC && "Didn't lookup multiclass correctly?");
2530 std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2532 // Verify that the correct number of template arguments were specified.
2533 const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2534 if (TArgs.size() < TemplateVals.size())
2535 return Error(SubClassLoc,
2536 "more template args specified than multiclass expects");
2538 // Loop over all the def's in the multiclass, instantiating each one.
2539 for (const std::unique_ptr<Record> &DefProto : MC->DefPrototypes) {
2540 Record *CurRec = InstantiateMulticlassDef(*MC, DefProto.get(), DefmPrefix,
2546 if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
2547 TArgs, TemplateVals, true/*Delete args*/))
2548 return Error(SubClassLoc, "could not instantiate def");
2550 if (ResolveMulticlassDef(*MC, CurRec, DefProto.get(), DefmLoc))
2551 return Error(SubClassLoc, "could not instantiate def");
2553 // Defs that can be used by other definitions should be fully resolved
2555 if (DefProto->isResolveFirst() && !CurMultiClass) {
2556 CurRec->resolveReferences();
2557 CurRec->setResolveFirst(false);
2559 NewRecDefs.push_back(CurRec);
2563 if (Lex.getCode() != tgtok::comma) break;
2564 Lex.Lex(); // eat ','.
2566 if (Lex.getCode() != tgtok::Id)
2567 return TokError("expected identifier");
2569 SubClassLoc = Lex.getLoc();
2571 // A defm can inherit from regular classes (non-multiclass) as
2572 // long as they come in the end of the inheritance list.
2573 InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
2575 if (InheritFromClass)
2578 Ref = ParseSubClassReference(nullptr, true);
2581 if (InheritFromClass) {
2582 // Process all the classes to inherit as if they were part of a
2583 // regular 'def' and inherit all record values.
2584 SubClassReference SubClass = ParseSubClassReference(nullptr, false);
2587 if (!SubClass.Rec) return true;
2589 // Get the expanded definition prototypes and teach them about
2590 // the record values the current class to inherit has
2591 for (Record *CurRec : NewRecDefs) {
2593 if (AddSubClass(CurRec, SubClass))
2596 if (ApplyLetStack(CurRec))
2600 if (Lex.getCode() != tgtok::comma) break;
2601 Lex.Lex(); // eat ','.
2602 SubClass = ParseSubClassReference(nullptr, false);
2607 for (Record *CurRec : NewRecDefs)
2608 // See Record::setName(). This resolve step will see any new
2609 // name for the def that might have been created when resolving
2610 // inheritance, values and arguments above.
2611 CurRec->resolveReferences();
2613 if (Lex.getCode() != tgtok::semi)
2614 return TokError("expected ';' at end of defm");
2621 /// Object ::= ClassInst
2622 /// Object ::= DefInst
2623 /// Object ::= MultiClassInst
2624 /// Object ::= DefMInst
2625 /// Object ::= LETCommand '{' ObjectList '}'
2626 /// Object ::= LETCommand Object
2627 bool TGParser::ParseObject(MultiClass *MC) {
2628 switch (Lex.getCode()) {
2630 return TokError("Expected class, def, defm, multiclass or let definition");
2631 case tgtok::Let: return ParseTopLevelLet(MC);
2632 case tgtok::Def: return ParseDef(MC);
2633 case tgtok::Foreach: return ParseForeach(MC);
2634 case tgtok::Defm: return ParseDefm(MC);
2635 case tgtok::Class: return ParseClass();
2636 case tgtok::MultiClass: return ParseMultiClass();
2641 /// ObjectList :== Object*
2642 bool TGParser::ParseObjectList(MultiClass *MC) {
2643 while (isObjectStart(Lex.getCode())) {
2644 if (ParseObject(MC))
2650 bool TGParser::ParseFile() {
2651 Lex.Lex(); // Prime the lexer.
2652 if (ParseObjectList()) return true;
2654 // If we have unread input at the end of the file, report it.
2655 if (Lex.getCode() == tgtok::Eof)
2658 return TokError("Unexpected input at top level");