a9de4eac9d32073dac4f354349bd98855bf3d5f8
[oota-llvm.git] / lib / TableGen / TGParser.cpp
1 //===- TGParser.cpp - Parser for TableGen Files ---------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Implement the Parser for TableGen.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "TGParser.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/TableGen/Record.h"
19 #include <algorithm>
20 #include <sstream>
21 using namespace llvm;
22
23 //===----------------------------------------------------------------------===//
24 // Support Code for the Semantic Actions.
25 //===----------------------------------------------------------------------===//
26
27 namespace llvm {
28 struct SubClassReference {
29   SMRange RefRange;
30   Record *Rec;
31   std::vector<Init*> TemplateArgs;
32   SubClassReference() : Rec(nullptr) {}
33
34   bool isInvalid() const { return Rec == nullptr; }
35 };
36
37 struct SubMultiClassReference {
38   SMRange RefRange;
39   MultiClass *MC;
40   std::vector<Init*> TemplateArgs;
41   SubMultiClassReference() : MC(nullptr) {}
42
43   bool isInvalid() const { return MC == nullptr; }
44   void dump() const;
45 };
46
47 void SubMultiClassReference::dump() const {
48   errs() << "Multiclass:\n";
49
50   MC->dump();
51
52   errs() << "Template args:\n";
53   for (std::vector<Init *>::const_iterator i = TemplateArgs.begin(),
54          iend = TemplateArgs.end();
55        i != iend;
56        ++i) {
57     (*i)->dump();
58   }
59 }
60
61 } // end namespace llvm
62
63 bool TGParser::AddValue(Record *CurRec, SMLoc Loc, const RecordVal &RV) {
64   if (!CurRec)
65     CurRec = &CurMultiClass->Rec;
66
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() + "'");
74   } else {
75     CurRec->addValue(RV);
76   }
77   return false;
78 }
79
80 /// SetValue -
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) {
84   if (!V) return false;
85
86   if (!CurRec) CurRec = &CurMultiClass->Rec;
87
88   RecordVal *RV = CurRec->getValue(ValName);
89   if (!RV)
90     return Error(Loc, "Value '" + ValName->getAsUnquotedString()
91                  + "' unknown!");
92
93   // Do not allow assignments like 'X = X'.  This will just cause infinite loops
94   // in the resolution machinery.
95   if (BitList.empty())
96     if (VarInit *VI = dyn_cast<VarInit>(V))
97       if (VI->getNameInit() == ValName)
98         return false;
99
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
102   // initializer.
103   //
104   if (!BitList.empty()) {
105     BitsInit *CurVal = dyn_cast<BitsInit>(RV->getValue());
106     if (!CurVal)
107       return Error(Loc, "Value '" + ValName->getAsUnquotedString()
108                    + "' is not a bits type");
109
110     // Convert the incoming value to a bits type of the appropriate size...
111     Init *BI = V->convertInitializerTo(BitsRecTy::get(BitList.size()));
112     if (!BI) {
113       return Error(Loc, "Initializer is not compatible with bit range");
114     }
115
116     // We should have a BitsInit type now.
117     BitsInit *BInit = dyn_cast<BitsInit>(BI);
118     assert(BInit != nullptr);
119
120     SmallVector<Init *, 16> NewBits(CurVal->getNumBits());
121
122     // Loop over bits, assigning values as appropriate.
123     for (unsigned i = 0, e = BitList.size(); i != e; ++i) {
124       unsigned Bit = BitList[i];
125       if (NewBits[Bit])
126         return Error(Loc, "Cannot set bit #" + utostr(Bit) + " of value '" +
127                      ValName->getAsUnquotedString() + "' more than once");
128       NewBits[Bit] = BInit->getBit(i);
129     }
130
131     for (unsigned i = 0, e = CurVal->getNumBits(); i != e; ++i)
132       if (!NewBits[i])
133         NewBits[i] = CurVal->getBit(i);
134
135     V = BitsInit::get(NewBits);
136   }
137
138   if (RV->setValue(V)) {
139     std::string InitType = "";
140     if (BitsInit *BI = dyn_cast<BitsInit>(V)) {
141       InitType = (Twine("' of type bit initializer with length ") +
142                   Twine(BI->getNumBits())).str();
143     }
144     return Error(Loc, "Value '" + ValName->getAsUnquotedString() + "' of type '"
145                  + RV->getType()->getAsString() +
146                  "' is incompatible with initializer '" + V->getAsString()
147                  + InitType
148                  + "'");
149   }
150   return false;
151 }
152
153 /// AddSubClass - Add SubClass as a subclass to CurRec, resolving its template
154 /// args as SubClass's template arguments.
155 bool TGParser::AddSubClass(Record *CurRec, SubClassReference &SubClass) {
156   Record *SC = SubClass.Rec;
157   // Add all of the values in the subclass into the current class.
158   const std::vector<RecordVal> &Vals = SC->getValues();
159   for (unsigned i = 0, e = Vals.size(); i != e; ++i)
160     if (AddValue(CurRec, SubClass.RefRange.Start, Vals[i]))
161       return true;
162
163   const std::vector<Init *> &TArgs = SC->getTemplateArgs();
164
165   // Ensure that an appropriate number of template arguments are specified.
166   if (TArgs.size() < SubClass.TemplateArgs.size())
167     return Error(SubClass.RefRange.Start,
168                  "More template args specified than expected");
169
170   // Loop over all of the template arguments, setting them to the specified
171   // value or leaving them as the default if necessary.
172   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
173     if (i < SubClass.TemplateArgs.size()) {
174       // If a value is specified for this template arg, set it now.
175       if (SetValue(CurRec, SubClass.RefRange.Start, TArgs[i],
176                    std::vector<unsigned>(), SubClass.TemplateArgs[i]))
177         return true;
178
179       // Resolve it next.
180       CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
181
182       // Now remove it.
183       CurRec->removeValue(TArgs[i]);
184
185     } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
186       return Error(SubClass.RefRange.Start,
187                    "Value not specified for template argument #"
188                    + utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
189                    + ") of subclass '" + SC->getNameInitAsString() + "'!");
190     }
191   }
192
193   // Since everything went well, we can now set the "superclass" list for the
194   // current record.
195   const std::vector<Record*> &SCs = SC->getSuperClasses();
196   ArrayRef<SMRange> SCRanges = SC->getSuperClassRanges();
197   for (unsigned i = 0, e = SCs.size(); i != e; ++i) {
198     if (CurRec->isSubClassOf(SCs[i]))
199       return Error(SubClass.RefRange.Start,
200                    "Already subclass of '" + SCs[i]->getName() + "'!\n");
201     CurRec->addSuperClass(SCs[i], SCRanges[i]);
202   }
203
204   if (CurRec->isSubClassOf(SC))
205     return Error(SubClass.RefRange.Start,
206                  "Already subclass of '" + SC->getName() + "'!\n");
207   CurRec->addSuperClass(SC, SubClass.RefRange);
208   return false;
209 }
210
211 /// AddSubMultiClass - Add SubMultiClass as a subclass to
212 /// CurMC, resolving its template args as SubMultiClass's
213 /// template arguments.
214 bool TGParser::AddSubMultiClass(MultiClass *CurMC,
215                                 SubMultiClassReference &SubMultiClass) {
216   MultiClass *SMC = SubMultiClass.MC;
217   Record *CurRec = &CurMC->Rec;
218
219   const std::vector<RecordVal> &MCVals = CurRec->getValues();
220
221   // Add all of the values in the subclass into the current class.
222   const std::vector<RecordVal> &SMCVals = SMC->Rec.getValues();
223   for (unsigned i = 0, e = SMCVals.size(); i != e; ++i)
224     if (AddValue(CurRec, SubMultiClass.RefRange.Start, SMCVals[i]))
225       return true;
226
227   int newDefStart = CurMC->DefPrototypes.size();
228
229   // Add all of the defs in the subclass into the current multiclass.
230   for (MultiClass::RecordVector::const_iterator i = SMC->DefPrototypes.begin(),
231          iend = SMC->DefPrototypes.end();
232        i != iend;
233        ++i) {
234     // Clone the def and add it to the current multiclass
235     Record *NewDef = new Record(**i);
236
237     // Add all of the values in the superclass into the current def.
238     for (unsigned i = 0, e = MCVals.size(); i != e; ++i)
239       if (AddValue(NewDef, SubMultiClass.RefRange.Start, MCVals[i]))
240         return true;
241
242     CurMC->DefPrototypes.push_back(NewDef);
243   }
244
245   const std::vector<Init *> &SMCTArgs = SMC->Rec.getTemplateArgs();
246
247   // Ensure that an appropriate number of template arguments are
248   // specified.
249   if (SMCTArgs.size() < SubMultiClass.TemplateArgs.size())
250     return Error(SubMultiClass.RefRange.Start,
251                  "More template args specified than expected");
252
253   // Loop over all of the template arguments, setting them to the specified
254   // value or leaving them as the default if necessary.
255   for (unsigned i = 0, e = SMCTArgs.size(); i != e; ++i) {
256     if (i < SubMultiClass.TemplateArgs.size()) {
257       // If a value is specified for this template arg, set it in the
258       // superclass now.
259       if (SetValue(CurRec, SubMultiClass.RefRange.Start, SMCTArgs[i],
260                    std::vector<unsigned>(),
261                    SubMultiClass.TemplateArgs[i]))
262         return true;
263
264       // Resolve it next.
265       CurRec->resolveReferencesTo(CurRec->getValue(SMCTArgs[i]));
266
267       // Now remove it.
268       CurRec->removeValue(SMCTArgs[i]);
269
270       // If a value is specified for this template arg, set it in the
271       // new defs now.
272       for (MultiClass::RecordVector::iterator j =
273              CurMC->DefPrototypes.begin() + newDefStart,
274              jend = CurMC->DefPrototypes.end();
275            j != jend;
276            ++j) {
277         Record *Def = *j;
278
279         if (SetValue(Def, SubMultiClass.RefRange.Start, SMCTArgs[i],
280                      std::vector<unsigned>(),
281                      SubMultiClass.TemplateArgs[i]))
282           return true;
283
284         // Resolve it next.
285         Def->resolveReferencesTo(Def->getValue(SMCTArgs[i]));
286
287         // Now remove it
288         Def->removeValue(SMCTArgs[i]);
289       }
290     } else if (!CurRec->getValue(SMCTArgs[i])->getValue()->isComplete()) {
291       return Error(SubMultiClass.RefRange.Start,
292                    "Value not specified for template argument #"
293                    + utostr(i) + " (" + SMCTArgs[i]->getAsUnquotedString()
294                    + ") of subclass '" + SMC->Rec.getNameInitAsString() + "'!");
295     }
296   }
297
298   return false;
299 }
300
301 /// ProcessForeachDefs - Given a record, apply all of the variable
302 /// values in all surrounding foreach loops, creating new records for
303 /// each combination of values.
304 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc) {
305   if (Loops.empty())
306     return false;
307
308   // We want to instantiate a new copy of CurRec for each combination
309   // of nested loop iterator values.  We don't want top instantiate
310   // any copies until we have values for each loop iterator.
311   IterSet IterVals;
312   return ProcessForeachDefs(CurRec, Loc, IterVals);
313 }
314
315 /// ProcessForeachDefs - Given a record, a loop and a loop iterator,
316 /// apply each of the variable values in this loop and then process
317 /// subloops.
318 bool TGParser::ProcessForeachDefs(Record *CurRec, SMLoc Loc, IterSet &IterVals){
319   // Recursively build a tuple of iterator values.
320   if (IterVals.size() != Loops.size()) {
321     assert(IterVals.size() < Loops.size());
322     ForeachLoop &CurLoop = Loops[IterVals.size()];
323     ListInit *List = dyn_cast<ListInit>(CurLoop.ListValue);
324     if (!List) {
325       Error(Loc, "Loop list is not a list");
326       return true;
327     }
328
329     // Process each value.
330     for (int64_t i = 0; i < List->getSize(); ++i) {
331       Init *ItemVal = List->resolveListElementReference(*CurRec, nullptr, i);
332       IterVals.push_back(IterRecord(CurLoop.IterVar, ItemVal));
333       if (ProcessForeachDefs(CurRec, Loc, IterVals))
334         return true;
335       IterVals.pop_back();
336     }
337     return false;
338   }
339
340   // This is the bottom of the recursion. We have all of the iterator values
341   // for this point in the iteration space.  Instantiate a new record to
342   // reflect this combination of values.
343   Record *IterRec = new Record(*CurRec);
344
345   // Set the iterator values now.
346   for (unsigned i = 0, e = IterVals.size(); i != e; ++i) {
347     VarInit *IterVar = IterVals[i].IterVar;
348     TypedInit *IVal = dyn_cast<TypedInit>(IterVals[i].IterValue);
349     if (!IVal) {
350       Error(Loc, "foreach iterator value is untyped");
351       return true;
352     }
353
354     IterRec->addValue(RecordVal(IterVar->getName(), IVal->getType(), false));
355
356     if (SetValue(IterRec, Loc, IterVar->getName(),
357                  std::vector<unsigned>(), IVal)) {
358       Error(Loc, "when instantiating this def");
359       return true;
360     }
361
362     // Resolve it next.
363     IterRec->resolveReferencesTo(IterRec->getValue(IterVar->getName()));
364
365     // Remove it.
366     IterRec->removeValue(IterVar->getName());
367   }
368
369   if (Records.getDef(IterRec->getNameInitAsString())) {
370     // If this record is anonymous, it's no problem, just generate a new name
371     if (IterRec->isAnonymous())
372       IterRec->setName(GetNewAnonymousName());
373     else {
374       Error(Loc, "def already exists: " + IterRec->getNameInitAsString());
375       return true;
376     }
377   }
378
379   Records.addDef(IterRec);
380   IterRec->resolveReferences();
381   return false;
382 }
383
384 //===----------------------------------------------------------------------===//
385 // Parser Code
386 //===----------------------------------------------------------------------===//
387
388 /// isObjectStart - Return true if this is a valid first token for an Object.
389 static bool isObjectStart(tgtok::TokKind K) {
390   return K == tgtok::Class || K == tgtok::Def ||
391          K == tgtok::Defm || K == tgtok::Let ||
392          K == tgtok::MultiClass || K == tgtok::Foreach;
393 }
394
395 /// GetNewAnonymousName - Generate a unique anonymous name that can be used as
396 /// an identifier.
397 std::string TGParser::GetNewAnonymousName() {
398   unsigned Tmp = AnonCounter++; // MSVC2012 ICEs without this.
399   return "anonymous_" + utostr(Tmp);
400 }
401
402 /// ParseObjectName - If an object name is specified, return it.  Otherwise,
403 /// return 0.
404 ///   ObjectName ::= Value [ '#' Value ]*
405 ///   ObjectName ::= /*empty*/
406 ///
407 Init *TGParser::ParseObjectName(MultiClass *CurMultiClass) {
408   switch (Lex.getCode()) {
409   case tgtok::colon:
410   case tgtok::semi:
411   case tgtok::l_brace:
412     // These are all of the tokens that can begin an object body.
413     // Some of these can also begin values but we disallow those cases
414     // because they are unlikely to be useful.
415     return nullptr;
416   default:
417     break;
418   }
419
420   Record *CurRec = nullptr;
421   if (CurMultiClass)
422     CurRec = &CurMultiClass->Rec;
423
424   RecTy *Type = nullptr;
425   if (CurRec) {
426     const TypedInit *CurRecName = dyn_cast<TypedInit>(CurRec->getNameInit());
427     if (!CurRecName) {
428       TokError("Record name is not typed!");
429       return nullptr;
430     }
431     Type = CurRecName->getType();
432   }
433
434   return ParseValue(CurRec, Type, ParseNameMode);
435 }
436
437 /// ParseClassID - Parse and resolve a reference to a class name.  This returns
438 /// null on error.
439 ///
440 ///    ClassID ::= ID
441 ///
442 Record *TGParser::ParseClassID() {
443   if (Lex.getCode() != tgtok::Id) {
444     TokError("expected name for ClassID");
445     return nullptr;
446   }
447
448   Record *Result = Records.getClass(Lex.getCurStrVal());
449   if (!Result)
450     TokError("Couldn't find class '" + Lex.getCurStrVal() + "'");
451
452   Lex.Lex();
453   return Result;
454 }
455
456 /// ParseMultiClassID - Parse and resolve a reference to a multiclass name.
457 /// This returns null on error.
458 ///
459 ///    MultiClassID ::= ID
460 ///
461 MultiClass *TGParser::ParseMultiClassID() {
462   if (Lex.getCode() != tgtok::Id) {
463     TokError("expected name for MultiClassID");
464     return nullptr;
465   }
466
467   MultiClass *Result = MultiClasses[Lex.getCurStrVal()];
468   if (!Result)
469     TokError("Couldn't find multiclass '" + Lex.getCurStrVal() + "'");
470
471   Lex.Lex();
472   return Result;
473 }
474
475 /// ParseSubClassReference - Parse a reference to a subclass or to a templated
476 /// subclass.  This returns a SubClassRefTy with a null Record* on error.
477 ///
478 ///  SubClassRef ::= ClassID
479 ///  SubClassRef ::= ClassID '<' ValueList '>'
480 ///
481 SubClassReference TGParser::
482 ParseSubClassReference(Record *CurRec, bool isDefm) {
483   SubClassReference Result;
484   Result.RefRange.Start = Lex.getLoc();
485
486   if (isDefm) {
487     if (MultiClass *MC = ParseMultiClassID())
488       Result.Rec = &MC->Rec;
489   } else {
490     Result.Rec = ParseClassID();
491   }
492   if (!Result.Rec) return Result;
493
494   // If there is no template arg list, we're done.
495   if (Lex.getCode() != tgtok::less) {
496     Result.RefRange.End = Lex.getLoc();
497     return Result;
498   }
499   Lex.Lex();  // Eat the '<'
500
501   if (Lex.getCode() == tgtok::greater) {
502     TokError("subclass reference requires a non-empty list of template values");
503     Result.Rec = nullptr;
504     return Result;
505   }
506
507   Result.TemplateArgs = ParseValueList(CurRec, Result.Rec);
508   if (Result.TemplateArgs.empty()) {
509     Result.Rec = nullptr;   // Error parsing value list.
510     return Result;
511   }
512
513   if (Lex.getCode() != tgtok::greater) {
514     TokError("expected '>' in template value list");
515     Result.Rec = nullptr;
516     return Result;
517   }
518   Lex.Lex();
519   Result.RefRange.End = Lex.getLoc();
520
521   return Result;
522 }
523
524 /// ParseSubMultiClassReference - Parse a reference to a subclass or to a
525 /// templated submulticlass.  This returns a SubMultiClassRefTy with a null
526 /// Record* on error.
527 ///
528 ///  SubMultiClassRef ::= MultiClassID
529 ///  SubMultiClassRef ::= MultiClassID '<' ValueList '>'
530 ///
531 SubMultiClassReference TGParser::
532 ParseSubMultiClassReference(MultiClass *CurMC) {
533   SubMultiClassReference Result;
534   Result.RefRange.Start = Lex.getLoc();
535
536   Result.MC = ParseMultiClassID();
537   if (!Result.MC) return Result;
538
539   // If there is no template arg list, we're done.
540   if (Lex.getCode() != tgtok::less) {
541     Result.RefRange.End = Lex.getLoc();
542     return Result;
543   }
544   Lex.Lex();  // Eat the '<'
545
546   if (Lex.getCode() == tgtok::greater) {
547     TokError("subclass reference requires a non-empty list of template values");
548     Result.MC = nullptr;
549     return Result;
550   }
551
552   Result.TemplateArgs = ParseValueList(&CurMC->Rec, &Result.MC->Rec);
553   if (Result.TemplateArgs.empty()) {
554     Result.MC = nullptr;   // Error parsing value list.
555     return Result;
556   }
557
558   if (Lex.getCode() != tgtok::greater) {
559     TokError("expected '>' in template value list");
560     Result.MC = nullptr;
561     return Result;
562   }
563   Lex.Lex();
564   Result.RefRange.End = Lex.getLoc();
565
566   return Result;
567 }
568
569 /// ParseRangePiece - Parse a bit/value range.
570 ///   RangePiece ::= INTVAL
571 ///   RangePiece ::= INTVAL '-' INTVAL
572 ///   RangePiece ::= INTVAL INTVAL
573 bool TGParser::ParseRangePiece(std::vector<unsigned> &Ranges) {
574   if (Lex.getCode() != tgtok::IntVal) {
575     TokError("expected integer or bitrange");
576     return true;
577   }
578   int64_t Start = Lex.getCurIntVal();
579   int64_t End;
580
581   if (Start < 0)
582     return TokError("invalid range, cannot be negative");
583
584   switch (Lex.Lex()) {  // eat first character.
585   default:
586     Ranges.push_back(Start);
587     return false;
588   case tgtok::minus:
589     if (Lex.Lex() != tgtok::IntVal) {
590       TokError("expected integer value as end of range");
591       return true;
592     }
593     End = Lex.getCurIntVal();
594     break;
595   case tgtok::IntVal:
596     End = -Lex.getCurIntVal();
597     break;
598   }
599   if (End < 0)
600     return TokError("invalid range, cannot be negative");
601   Lex.Lex();
602
603   // Add to the range.
604   if (Start < End) {
605     for (; Start <= End; ++Start)
606       Ranges.push_back(Start);
607   } else {
608     for (; Start >= End; --Start)
609       Ranges.push_back(Start);
610   }
611   return false;
612 }
613
614 /// ParseRangeList - Parse a list of scalars and ranges into scalar values.
615 ///
616 ///   RangeList ::= RangePiece (',' RangePiece)*
617 ///
618 std::vector<unsigned> TGParser::ParseRangeList() {
619   std::vector<unsigned> Result;
620
621   // Parse the first piece.
622   if (ParseRangePiece(Result))
623     return std::vector<unsigned>();
624   while (Lex.getCode() == tgtok::comma) {
625     Lex.Lex();  // Eat the comma.
626
627     // Parse the next range piece.
628     if (ParseRangePiece(Result))
629       return std::vector<unsigned>();
630   }
631   return Result;
632 }
633
634 /// ParseOptionalRangeList - Parse either a range list in <>'s or nothing.
635 ///   OptionalRangeList ::= '<' RangeList '>'
636 ///   OptionalRangeList ::= /*empty*/
637 bool TGParser::ParseOptionalRangeList(std::vector<unsigned> &Ranges) {
638   if (Lex.getCode() != tgtok::less)
639     return false;
640
641   SMLoc StartLoc = Lex.getLoc();
642   Lex.Lex(); // eat the '<'
643
644   // Parse the range list.
645   Ranges = ParseRangeList();
646   if (Ranges.empty()) return true;
647
648   if (Lex.getCode() != tgtok::greater) {
649     TokError("expected '>' at end of range list");
650     return Error(StartLoc, "to match this '<'");
651   }
652   Lex.Lex();   // eat the '>'.
653   return false;
654 }
655
656 /// ParseOptionalBitList - Parse either a bit list in {}'s or nothing.
657 ///   OptionalBitList ::= '{' RangeList '}'
658 ///   OptionalBitList ::= /*empty*/
659 bool TGParser::ParseOptionalBitList(std::vector<unsigned> &Ranges) {
660   if (Lex.getCode() != tgtok::l_brace)
661     return false;
662
663   SMLoc StartLoc = Lex.getLoc();
664   Lex.Lex(); // eat the '{'
665
666   // Parse the range list.
667   Ranges = ParseRangeList();
668   if (Ranges.empty()) return true;
669
670   if (Lex.getCode() != tgtok::r_brace) {
671     TokError("expected '}' at end of bit list");
672     return Error(StartLoc, "to match this '{'");
673   }
674   Lex.Lex();   // eat the '}'.
675   return false;
676 }
677
678
679 /// ParseType - Parse and return a tblgen type.  This returns null on error.
680 ///
681 ///   Type ::= STRING                       // string type
682 ///   Type ::= CODE                         // code type
683 ///   Type ::= BIT                          // bit type
684 ///   Type ::= BITS '<' INTVAL '>'          // bits<x> type
685 ///   Type ::= INT                          // int type
686 ///   Type ::= LIST '<' Type '>'            // list<x> type
687 ///   Type ::= DAG                          // dag type
688 ///   Type ::= ClassID                      // Record Type
689 ///
690 RecTy *TGParser::ParseType() {
691   switch (Lex.getCode()) {
692   default: TokError("Unknown token when expecting a type"); return nullptr;
693   case tgtok::String: Lex.Lex(); return StringRecTy::get();
694   case tgtok::Code:   Lex.Lex(); return StringRecTy::get();
695   case tgtok::Bit:    Lex.Lex(); return BitRecTy::get();
696   case tgtok::Int:    Lex.Lex(); return IntRecTy::get();
697   case tgtok::Dag:    Lex.Lex(); return DagRecTy::get();
698   case tgtok::Id:
699     if (Record *R = ParseClassID()) return RecordRecTy::get(R);
700     return nullptr;
701   case tgtok::Bits: {
702     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
703       TokError("expected '<' after bits type");
704       return nullptr;
705     }
706     if (Lex.Lex() != tgtok::IntVal) {  // Eat '<'
707       TokError("expected integer in bits<n> type");
708       return nullptr;
709     }
710     uint64_t Val = Lex.getCurIntVal();
711     if (Lex.Lex() != tgtok::greater) {  // Eat count.
712       TokError("expected '>' at end of bits<n> type");
713       return nullptr;
714     }
715     Lex.Lex();  // Eat '>'
716     return BitsRecTy::get(Val);
717   }
718   case tgtok::List: {
719     if (Lex.Lex() != tgtok::less) { // Eat 'bits'
720       TokError("expected '<' after list type");
721       return nullptr;
722     }
723     Lex.Lex();  // Eat '<'
724     RecTy *SubType = ParseType();
725     if (!SubType) return nullptr;
726
727     if (Lex.getCode() != tgtok::greater) {
728       TokError("expected '>' at end of list<ty> type");
729       return nullptr;
730     }
731     Lex.Lex();  // Eat '>'
732     return ListRecTy::get(SubType);
733   }
734   }
735 }
736
737 /// ParseIDValue - This is just like ParseIDValue above, but it assumes the ID
738 /// has already been read.
739 Init *TGParser::ParseIDValue(Record *CurRec,
740                              const std::string &Name, SMLoc NameLoc,
741                              IDParseMode Mode) {
742   if (CurRec) {
743     if (const RecordVal *RV = CurRec->getValue(Name))
744       return VarInit::get(Name, RV->getType());
745
746     Init *TemplateArgName = QualifyName(*CurRec, CurMultiClass, Name, ":");
747
748     if (CurMultiClass)
749       TemplateArgName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
750                                     "::");
751
752     if (CurRec->isTemplateArg(TemplateArgName)) {
753       const RecordVal *RV = CurRec->getValue(TemplateArgName);
754       assert(RV && "Template arg doesn't exist??");
755       return VarInit::get(TemplateArgName, RV->getType());
756     }
757   }
758
759   if (CurMultiClass) {
760     Init *MCName = QualifyName(CurMultiClass->Rec, CurMultiClass, Name,
761                                "::");
762
763     if (CurMultiClass->Rec.isTemplateArg(MCName)) {
764       const RecordVal *RV = CurMultiClass->Rec.getValue(MCName);
765       assert(RV && "Template arg doesn't exist??");
766       return VarInit::get(MCName, RV->getType());
767     }
768   }
769
770   // If this is in a foreach loop, make sure it's not a loop iterator
771   for (LoopVector::iterator i = Loops.begin(), iend = Loops.end();
772        i != iend;
773        ++i) {
774     VarInit *IterVar = dyn_cast<VarInit>(i->IterVar);
775     if (IterVar && IterVar->getName() == Name)
776       return IterVar;
777   }
778
779   if (Mode == ParseNameMode)
780     return StringInit::get(Name);
781
782   if (Record *D = Records.getDef(Name))
783     return DefInit::get(D);
784
785   if (Mode == ParseValueMode) {
786     Error(NameLoc, "Variable not defined: '" + Name + "'");
787     return nullptr;
788   }
789   
790   return StringInit::get(Name);
791 }
792
793 /// ParseOperation - Parse an operator.  This returns null on error.
794 ///
795 /// Operation ::= XOperator ['<' Type '>'] '(' Args ')'
796 ///
797 Init *TGParser::ParseOperation(Record *CurRec, RecTy *ItemType) {
798   switch (Lex.getCode()) {
799   default:
800     TokError("unknown operation");
801     return nullptr;
802   case tgtok::XHead:
803   case tgtok::XTail:
804   case tgtok::XEmpty:
805   case tgtok::XCast: {  // Value ::= !unop '(' Value ')'
806     UnOpInit::UnaryOp Code;
807     RecTy *Type = nullptr;
808
809     switch (Lex.getCode()) {
810     default: llvm_unreachable("Unhandled code!");
811     case tgtok::XCast:
812       Lex.Lex();  // eat the operation
813       Code = UnOpInit::CAST;
814
815       Type = ParseOperatorType();
816
817       if (!Type) {
818         TokError("did not get type for unary operator");
819         return nullptr;
820       }
821
822       break;
823     case tgtok::XHead:
824       Lex.Lex();  // eat the operation
825       Code = UnOpInit::HEAD;
826       break;
827     case tgtok::XTail:
828       Lex.Lex();  // eat the operation
829       Code = UnOpInit::TAIL;
830       break;
831     case tgtok::XEmpty:
832       Lex.Lex();  // eat the operation
833       Code = UnOpInit::EMPTY;
834       Type = IntRecTy::get();
835       break;
836     }
837     if (Lex.getCode() != tgtok::l_paren) {
838       TokError("expected '(' after unary operator");
839       return nullptr;
840     }
841     Lex.Lex();  // eat the '('
842
843     Init *LHS = ParseValue(CurRec);
844     if (!LHS) return nullptr;
845
846     if (Code == UnOpInit::HEAD
847         || Code == UnOpInit::TAIL
848         || Code == UnOpInit::EMPTY) {
849       ListInit *LHSl = dyn_cast<ListInit>(LHS);
850       StringInit *LHSs = dyn_cast<StringInit>(LHS);
851       TypedInit *LHSt = dyn_cast<TypedInit>(LHS);
852       if (!LHSl && !LHSs && !LHSt) {
853         TokError("expected list or string type argument in unary operator");
854         return nullptr;
855       }
856       if (LHSt) {
857         ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
858         StringRecTy *SType = dyn_cast<StringRecTy>(LHSt->getType());
859         if (!LType && !SType) {
860           TokError("expected list or string type argument in unary operator");
861           return nullptr;
862         }
863       }
864
865       if (Code == UnOpInit::HEAD
866           || Code == UnOpInit::TAIL) {
867         if (!LHSl && !LHSt) {
868           TokError("expected list type argument in unary operator");
869           return nullptr;
870         }
871
872         if (LHSl && LHSl->getSize() == 0) {
873           TokError("empty list argument in unary operator");
874           return nullptr;
875         }
876         if (LHSl) {
877           Init *Item = LHSl->getElement(0);
878           TypedInit *Itemt = dyn_cast<TypedInit>(Item);
879           if (!Itemt) {
880             TokError("untyped list element in unary operator");
881             return nullptr;
882           }
883           if (Code == UnOpInit::HEAD) {
884             Type = Itemt->getType();
885           } else {
886             Type = ListRecTy::get(Itemt->getType());
887           }
888         } else {
889           assert(LHSt && "expected list type argument in unary operator");
890           ListRecTy *LType = dyn_cast<ListRecTy>(LHSt->getType());
891           if (!LType) {
892             TokError("expected list type argument in unary operator");
893             return nullptr;
894           }
895           if (Code == UnOpInit::HEAD) {
896             Type = LType->getElementType();
897           } else {
898             Type = LType;
899           }
900         }
901       }
902     }
903
904     if (Lex.getCode() != tgtok::r_paren) {
905       TokError("expected ')' in unary operator");
906       return nullptr;
907     }
908     Lex.Lex();  // eat the ')'
909     return (UnOpInit::get(Code, LHS, Type))->Fold(CurRec, CurMultiClass);
910   }
911
912   case tgtok::XConcat:
913   case tgtok::XADD:
914   case tgtok::XSRA:
915   case tgtok::XSRL:
916   case tgtok::XSHL:
917   case tgtok::XEq:
918   case tgtok::XListConcat:
919   case tgtok::XStrConcat: {  // Value ::= !binop '(' Value ',' Value ')'
920     tgtok::TokKind OpTok = Lex.getCode();
921     SMLoc OpLoc = Lex.getLoc();
922     Lex.Lex();  // eat the operation
923
924     BinOpInit::BinaryOp Code;
925     RecTy *Type = nullptr;
926
927     switch (OpTok) {
928     default: llvm_unreachable("Unhandled code!");
929     case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
930     case tgtok::XADD:    Code = BinOpInit::ADD;   Type = IntRecTy::get(); break;
931     case tgtok::XSRA:    Code = BinOpInit::SRA;   Type = IntRecTy::get(); break;
932     case tgtok::XSRL:    Code = BinOpInit::SRL;   Type = IntRecTy::get(); break;
933     case tgtok::XSHL:    Code = BinOpInit::SHL;   Type = IntRecTy::get(); break;
934     case tgtok::XEq:     Code = BinOpInit::EQ;    Type = BitRecTy::get(); break;
935     case tgtok::XListConcat:
936       Code = BinOpInit::LISTCONCAT;
937       // We don't know the list type until we parse the first argument
938       break;
939     case tgtok::XStrConcat:
940       Code = BinOpInit::STRCONCAT;
941       Type = StringRecTy::get();
942       break;
943     }
944
945     if (Lex.getCode() != tgtok::l_paren) {
946       TokError("expected '(' after binary operator");
947       return nullptr;
948     }
949     Lex.Lex();  // eat the '('
950
951     SmallVector<Init*, 2> InitList;
952
953     InitList.push_back(ParseValue(CurRec));
954     if (!InitList.back()) return nullptr;
955
956     while (Lex.getCode() == tgtok::comma) {
957       Lex.Lex();  // eat the ','
958
959       InitList.push_back(ParseValue(CurRec));
960       if (!InitList.back()) return nullptr;
961     }
962
963     if (Lex.getCode() != tgtok::r_paren) {
964       TokError("expected ')' in operator");
965       return nullptr;
966     }
967     Lex.Lex();  // eat the ')'
968
969     // If we are doing !listconcat, we should know the type by now
970     if (OpTok == tgtok::XListConcat) {
971       if (VarInit *Arg0 = dyn_cast<VarInit>(InitList[0]))
972         Type = Arg0->getType();
973       else if (ListInit *Arg0 = dyn_cast<ListInit>(InitList[0]))
974         Type = Arg0->getType();
975       else {
976         InitList[0]->dump();
977         Error(OpLoc, "expected a list");
978         return nullptr;
979       }
980     }
981
982     // We allow multiple operands to associative operators like !strconcat as
983     // shorthand for nesting them.
984     if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT) {
985       while (InitList.size() > 2) {
986         Init *RHS = InitList.pop_back_val();
987         RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
988                            ->Fold(CurRec, CurMultiClass);
989         InitList.back() = RHS;
990       }
991     }
992
993     if (InitList.size() == 2)
994       return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
995         ->Fold(CurRec, CurMultiClass);
996
997     Error(OpLoc, "expected two operands to operator");
998     return nullptr;
999   }
1000
1001   case tgtok::XIf:
1002   case tgtok::XForEach:
1003   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1004     TernOpInit::TernaryOp Code;
1005     RecTy *Type = nullptr;
1006
1007     tgtok::TokKind LexCode = Lex.getCode();
1008     Lex.Lex();  // eat the operation
1009     switch (LexCode) {
1010     default: llvm_unreachable("Unhandled code!");
1011     case tgtok::XIf:
1012       Code = TernOpInit::IF;
1013       break;
1014     case tgtok::XForEach:
1015       Code = TernOpInit::FOREACH;
1016       break;
1017     case tgtok::XSubst:
1018       Code = TernOpInit::SUBST;
1019       break;
1020     }
1021     if (Lex.getCode() != tgtok::l_paren) {
1022       TokError("expected '(' after ternary operator");
1023       return nullptr;
1024     }
1025     Lex.Lex();  // eat the '('
1026
1027     Init *LHS = ParseValue(CurRec);
1028     if (!LHS) return nullptr;
1029
1030     if (Lex.getCode() != tgtok::comma) {
1031       TokError("expected ',' in ternary operator");
1032       return nullptr;
1033     }
1034     Lex.Lex();  // eat the ','
1035
1036     Init *MHS = ParseValue(CurRec, ItemType);
1037     if (!MHS)
1038       return nullptr;
1039
1040     if (Lex.getCode() != tgtok::comma) {
1041       TokError("expected ',' in ternary operator");
1042       return nullptr;
1043     }
1044     Lex.Lex();  // eat the ','
1045
1046     Init *RHS = ParseValue(CurRec, ItemType);
1047     if (!RHS)
1048       return nullptr;
1049
1050     if (Lex.getCode() != tgtok::r_paren) {
1051       TokError("expected ')' in binary operator");
1052       return nullptr;
1053     }
1054     Lex.Lex();  // eat the ')'
1055
1056     switch (LexCode) {
1057     default: llvm_unreachable("Unhandled code!");
1058     case tgtok::XIf: {
1059       RecTy *MHSTy = nullptr;
1060       RecTy *RHSTy = nullptr;
1061
1062       if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1063         MHSTy = MHSt->getType();
1064       if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1065         MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1066       if (isa<BitInit>(MHS))
1067         MHSTy = BitRecTy::get();
1068
1069       if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1070         RHSTy = RHSt->getType();
1071       if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1072         RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1073       if (isa<BitInit>(RHS))
1074         RHSTy = BitRecTy::get();
1075
1076       // For UnsetInit, it's typed from the other hand.
1077       if (isa<UnsetInit>(MHS))
1078         MHSTy = RHSTy;
1079       if (isa<UnsetInit>(RHS))
1080         RHSTy = MHSTy;
1081
1082       if (!MHSTy || !RHSTy) {
1083         TokError("could not get type for !if");
1084         return nullptr;
1085       }
1086
1087       if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1088         Type = RHSTy;
1089       } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1090         Type = MHSTy;
1091       } else {
1092         TokError("inconsistent types for !if");
1093         return nullptr;
1094       }
1095       break;
1096     }
1097     case tgtok::XForEach: {
1098       TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1099       if (!MHSt) {
1100         TokError("could not get type for !foreach");
1101         return nullptr;
1102       }
1103       Type = MHSt->getType();
1104       break;
1105     }
1106     case tgtok::XSubst: {
1107       TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1108       if (!RHSt) {
1109         TokError("could not get type for !subst");
1110         return nullptr;
1111       }
1112       Type = RHSt->getType();
1113       break;
1114     }
1115     }
1116     return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1117                                                              CurMultiClass);
1118   }
1119   }
1120 }
1121
1122 /// ParseOperatorType - Parse a type for an operator.  This returns
1123 /// null on error.
1124 ///
1125 /// OperatorType ::= '<' Type '>'
1126 ///
1127 RecTy *TGParser::ParseOperatorType() {
1128   RecTy *Type = nullptr;
1129
1130   if (Lex.getCode() != tgtok::less) {
1131     TokError("expected type name for operator");
1132     return nullptr;
1133   }
1134   Lex.Lex();  // eat the <
1135
1136   Type = ParseType();
1137
1138   if (!Type) {
1139     TokError("expected type name for operator");
1140     return nullptr;
1141   }
1142
1143   if (Lex.getCode() != tgtok::greater) {
1144     TokError("expected type name for operator");
1145     return nullptr;
1146   }
1147   Lex.Lex();  // eat the >
1148
1149   return Type;
1150 }
1151
1152
1153 /// ParseSimpleValue - Parse a tblgen value.  This returns null on error.
1154 ///
1155 ///   SimpleValue ::= IDValue
1156 ///   SimpleValue ::= INTVAL
1157 ///   SimpleValue ::= STRVAL+
1158 ///   SimpleValue ::= CODEFRAGMENT
1159 ///   SimpleValue ::= '?'
1160 ///   SimpleValue ::= '{' ValueList '}'
1161 ///   SimpleValue ::= ID '<' ValueListNE '>'
1162 ///   SimpleValue ::= '[' ValueList ']'
1163 ///   SimpleValue ::= '(' IDValue DagArgList ')'
1164 ///   SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1165 ///   SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1166 ///   SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1167 ///   SimpleValue ::= SRATOK '(' Value ',' Value ')'
1168 ///   SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1169 ///   SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1170 ///   SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1171 ///
1172 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1173                                  IDParseMode Mode) {
1174   Init *R = nullptr;
1175   switch (Lex.getCode()) {
1176   default: TokError("Unknown token when parsing a value"); break;
1177   case tgtok::paste:
1178     // This is a leading paste operation.  This is deprecated but
1179     // still exists in some .td files.  Ignore it.
1180     Lex.Lex();  // Skip '#'.
1181     return ParseSimpleValue(CurRec, ItemType, Mode);
1182   case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1183   case tgtok::StrVal: {
1184     std::string Val = Lex.getCurStrVal();
1185     Lex.Lex();
1186
1187     // Handle multiple consecutive concatenated strings.
1188     while (Lex.getCode() == tgtok::StrVal) {
1189       Val += Lex.getCurStrVal();
1190       Lex.Lex();
1191     }
1192
1193     R = StringInit::get(Val);
1194     break;
1195   }
1196   case tgtok::CodeFragment:
1197     R = StringInit::get(Lex.getCurStrVal());
1198     Lex.Lex();
1199     break;
1200   case tgtok::question:
1201     R = UnsetInit::get();
1202     Lex.Lex();
1203     break;
1204   case tgtok::Id: {
1205     SMLoc NameLoc = Lex.getLoc();
1206     std::string Name = Lex.getCurStrVal();
1207     if (Lex.Lex() != tgtok::less)  // consume the Id.
1208       return ParseIDValue(CurRec, Name, NameLoc, Mode);    // Value ::= IDValue
1209
1210     // Value ::= ID '<' ValueListNE '>'
1211     if (Lex.Lex() == tgtok::greater) {
1212       TokError("expected non-empty value list");
1213       return nullptr;
1214     }
1215
1216     // This is a CLASS<initvalslist> expression.  This is supposed to synthesize
1217     // a new anonymous definition, deriving from CLASS<initvalslist> with no
1218     // body.
1219     Record *Class = Records.getClass(Name);
1220     if (!Class) {
1221       Error(NameLoc, "Expected a class name, got '" + Name + "'");
1222       return nullptr;
1223     }
1224
1225     std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1226     if (ValueList.empty()) return nullptr;
1227
1228     if (Lex.getCode() != tgtok::greater) {
1229       TokError("expected '>' at end of value list");
1230       return nullptr;
1231     }
1232     Lex.Lex();  // eat the '>'
1233     SMLoc EndLoc = Lex.getLoc();
1234
1235     // Create the new record, set it as CurRec temporarily.
1236     Record *NewRec = new Record(GetNewAnonymousName(), NameLoc, Records,
1237                                 /*IsAnonymous=*/true);
1238     SubClassReference SCRef;
1239     SCRef.RefRange = SMRange(NameLoc, EndLoc);
1240     SCRef.Rec = Class;
1241     SCRef.TemplateArgs = ValueList;
1242     // Add info about the subclass to NewRec.
1243     if (AddSubClass(NewRec, SCRef))
1244       return nullptr;
1245     if (!CurMultiClass) {
1246       NewRec->resolveReferences();
1247       Records.addDef(NewRec);
1248     } else {
1249       // Otherwise, we're inside a multiclass, add it to the multiclass.
1250       CurMultiClass->DefPrototypes.push_back(NewRec);
1251
1252       // Copy the template arguments for the multiclass into the def.
1253       const std::vector<Init *> &TArgs =
1254                                   CurMultiClass->Rec.getTemplateArgs();
1255
1256       for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1257         const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1258         assert(RV && "Template arg doesn't exist?");
1259         NewRec->addValue(*RV);
1260       }
1261
1262       // We can't return the prototype def here, instead return:
1263       // !cast<ItemType>(!strconcat(NAME, AnonName)).
1264       const RecordVal *MCNameRV = CurMultiClass->Rec.getValue("NAME");
1265       assert(MCNameRV && "multiclass record must have a NAME");
1266
1267       return UnOpInit::get(UnOpInit::CAST,
1268                            BinOpInit::get(BinOpInit::STRCONCAT,
1269                                           VarInit::get(MCNameRV->getName(),
1270                                                        MCNameRV->getType()),
1271                                           NewRec->getNameInit(),
1272                                           StringRecTy::get()),
1273                            Class->getDefInit()->getType());
1274     }
1275
1276     // The result of the expression is a reference to the new record.
1277     return DefInit::get(NewRec);
1278   }
1279   case tgtok::l_brace: {           // Value ::= '{' ValueList '}'
1280     SMLoc BraceLoc = Lex.getLoc();
1281     Lex.Lex(); // eat the '{'
1282     std::vector<Init*> Vals;
1283
1284     if (Lex.getCode() != tgtok::r_brace) {
1285       Vals = ParseValueList(CurRec);
1286       if (Vals.empty()) return nullptr;
1287     }
1288     if (Lex.getCode() != tgtok::r_brace) {
1289       TokError("expected '}' at end of bit list value");
1290       return nullptr;
1291     }
1292     Lex.Lex();  // eat the '}'
1293
1294     SmallVector<Init *, 16> NewBits(Vals.size());
1295
1296     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1297       Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1298       if (!Bit) {
1299         Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1300               ") is not convertable to a bit");
1301         return nullptr;
1302       }
1303       NewBits[Vals.size()-i-1] = Bit;
1304     }
1305     return BitsInit::get(NewBits);
1306   }
1307   case tgtok::l_square: {          // Value ::= '[' ValueList ']'
1308     Lex.Lex(); // eat the '['
1309     std::vector<Init*> Vals;
1310
1311     RecTy *DeducedEltTy = nullptr;
1312     ListRecTy *GivenListTy = nullptr;
1313
1314     if (ItemType) {
1315       ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1316       if (!ListType) {
1317         std::string s;
1318         raw_string_ostream ss(s);
1319         ss << "Type mismatch for list, expected list type, got "
1320            << ItemType->getAsString();
1321         TokError(ss.str());
1322         return nullptr;
1323       }
1324       GivenListTy = ListType;
1325     }
1326
1327     if (Lex.getCode() != tgtok::r_square) {
1328       Vals = ParseValueList(CurRec, nullptr,
1329                             GivenListTy ? GivenListTy->getElementType() : nullptr);
1330       if (Vals.empty()) return nullptr;
1331     }
1332     if (Lex.getCode() != tgtok::r_square) {
1333       TokError("expected ']' at end of list value");
1334       return nullptr;
1335     }
1336     Lex.Lex();  // eat the ']'
1337
1338     RecTy *GivenEltTy = nullptr;
1339     if (Lex.getCode() == tgtok::less) {
1340       // Optional list element type
1341       Lex.Lex();  // eat the '<'
1342
1343       GivenEltTy = ParseType();
1344       if (!GivenEltTy) {
1345         // Couldn't parse element type
1346         return nullptr;
1347       }
1348
1349       if (Lex.getCode() != tgtok::greater) {
1350         TokError("expected '>' at end of list element type");
1351         return nullptr;
1352       }
1353       Lex.Lex();  // eat the '>'
1354     }
1355
1356     // Check elements
1357     RecTy *EltTy = nullptr;
1358     for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1359          i != ie;
1360          ++i) {
1361       TypedInit *TArg = dyn_cast<TypedInit>(*i);
1362       if (!TArg) {
1363         TokError("Untyped list element");
1364         return nullptr;
1365       }
1366       if (EltTy) {
1367         EltTy = resolveTypes(EltTy, TArg->getType());
1368         if (!EltTy) {
1369           TokError("Incompatible types in list elements");
1370           return nullptr;
1371         }
1372       } else {
1373         EltTy = TArg->getType();
1374       }
1375     }
1376
1377     if (GivenEltTy) {
1378       if (EltTy) {
1379         // Verify consistency
1380         if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1381           TokError("Incompatible types in list elements");
1382           return nullptr;
1383         }
1384       }
1385       EltTy = GivenEltTy;
1386     }
1387
1388     if (!EltTy) {
1389       if (!ItemType) {
1390         TokError("No type for list");
1391         return nullptr;
1392       }
1393       DeducedEltTy = GivenListTy->getElementType();
1394     } else {
1395       // Make sure the deduced type is compatible with the given type
1396       if (GivenListTy) {
1397         if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1398           TokError("Element type mismatch for list");
1399           return nullptr;
1400         }
1401       }
1402       DeducedEltTy = EltTy;
1403     }
1404
1405     return ListInit::get(Vals, DeducedEltTy);
1406   }
1407   case tgtok::l_paren: {         // Value ::= '(' IDValue DagArgList ')'
1408     Lex.Lex();   // eat the '('
1409     if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1410       TokError("expected identifier in dag init");
1411       return nullptr;
1412     }
1413
1414     Init *Operator = ParseValue(CurRec);
1415     if (!Operator) return nullptr;
1416
1417     // If the operator name is present, parse it.
1418     std::string OperatorName;
1419     if (Lex.getCode() == tgtok::colon) {
1420       if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1421         TokError("expected variable name in dag operator");
1422         return nullptr;
1423       }
1424       OperatorName = Lex.getCurStrVal();
1425       Lex.Lex();  // eat the VarName.
1426     }
1427
1428     std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1429     if (Lex.getCode() != tgtok::r_paren) {
1430       DagArgs = ParseDagArgList(CurRec);
1431       if (DagArgs.empty()) return nullptr;
1432     }
1433
1434     if (Lex.getCode() != tgtok::r_paren) {
1435       TokError("expected ')' in dag init");
1436       return nullptr;
1437     }
1438     Lex.Lex();  // eat the ')'
1439
1440     return DagInit::get(Operator, OperatorName, DagArgs);
1441   }
1442
1443   case tgtok::XHead:
1444   case tgtok::XTail:
1445   case tgtok::XEmpty:
1446   case tgtok::XCast:  // Value ::= !unop '(' Value ')'
1447   case tgtok::XConcat:
1448   case tgtok::XADD:
1449   case tgtok::XSRA:
1450   case tgtok::XSRL:
1451   case tgtok::XSHL:
1452   case tgtok::XEq:
1453   case tgtok::XListConcat:
1454   case tgtok::XStrConcat:   // Value ::= !binop '(' Value ',' Value ')'
1455   case tgtok::XIf:
1456   case tgtok::XForEach:
1457   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1458     return ParseOperation(CurRec, ItemType);
1459   }
1460   }
1461
1462   return R;
1463 }
1464
1465 /// ParseValue - Parse a tblgen value.  This returns null on error.
1466 ///
1467 ///   Value       ::= SimpleValue ValueSuffix*
1468 ///   ValueSuffix ::= '{' BitList '}'
1469 ///   ValueSuffix ::= '[' BitList ']'
1470 ///   ValueSuffix ::= '.' ID
1471 ///
1472 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1473   Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1474   if (!Result) return nullptr;
1475
1476   // Parse the suffixes now if present.
1477   while (1) {
1478     switch (Lex.getCode()) {
1479     default: return Result;
1480     case tgtok::l_brace: {
1481       if (Mode == ParseNameMode || Mode == ParseForeachMode)
1482         // This is the beginning of the object body.
1483         return Result;
1484
1485       SMLoc CurlyLoc = Lex.getLoc();
1486       Lex.Lex(); // eat the '{'
1487       std::vector<unsigned> Ranges = ParseRangeList();
1488       if (Ranges.empty()) return nullptr;
1489
1490       // Reverse the bitlist.
1491       std::reverse(Ranges.begin(), Ranges.end());
1492       Result = Result->convertInitializerBitRange(Ranges);
1493       if (!Result) {
1494         Error(CurlyLoc, "Invalid bit range for value");
1495         return nullptr;
1496       }
1497
1498       // Eat the '}'.
1499       if (Lex.getCode() != tgtok::r_brace) {
1500         TokError("expected '}' at end of bit range list");
1501         return nullptr;
1502       }
1503       Lex.Lex();
1504       break;
1505     }
1506     case tgtok::l_square: {
1507       SMLoc SquareLoc = Lex.getLoc();
1508       Lex.Lex(); // eat the '['
1509       std::vector<unsigned> Ranges = ParseRangeList();
1510       if (Ranges.empty()) return nullptr;
1511
1512       Result = Result->convertInitListSlice(Ranges);
1513       if (!Result) {
1514         Error(SquareLoc, "Invalid range for list slice");
1515         return nullptr;
1516       }
1517
1518       // Eat the ']'.
1519       if (Lex.getCode() != tgtok::r_square) {
1520         TokError("expected ']' at end of list slice");
1521         return nullptr;
1522       }
1523       Lex.Lex();
1524       break;
1525     }
1526     case tgtok::period:
1527       if (Lex.Lex() != tgtok::Id) {  // eat the .
1528         TokError("expected field identifier after '.'");
1529         return nullptr;
1530       }
1531       if (!Result->getFieldType(Lex.getCurStrVal())) {
1532         TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1533                  Result->getAsString() + "'");
1534         return nullptr;
1535       }
1536       Result = FieldInit::get(Result, Lex.getCurStrVal());
1537       Lex.Lex();  // eat field name
1538       break;
1539
1540     case tgtok::paste:
1541       SMLoc PasteLoc = Lex.getLoc();
1542
1543       // Create a !strconcat() operation, first casting each operand to
1544       // a string if necessary.
1545
1546       TypedInit *LHS = dyn_cast<TypedInit>(Result);
1547       if (!LHS) {
1548         Error(PasteLoc, "LHS of paste is not typed!");
1549         return nullptr;
1550       }
1551   
1552       if (LHS->getType() != StringRecTy::get()) {
1553         LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1554       }
1555
1556       TypedInit *RHS = nullptr;
1557
1558       Lex.Lex();  // Eat the '#'.
1559       switch (Lex.getCode()) { 
1560       case tgtok::colon:
1561       case tgtok::semi:
1562       case tgtok::l_brace:
1563         // These are all of the tokens that can begin an object body.
1564         // Some of these can also begin values but we disallow those cases
1565         // because they are unlikely to be useful.
1566        
1567         // Trailing paste, concat with an empty string.
1568         RHS = StringInit::get("");
1569         break;
1570
1571       default:
1572         Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1573         RHS = dyn_cast<TypedInit>(RHSResult);
1574         if (!RHS) {
1575           Error(PasteLoc, "RHS of paste is not typed!");
1576           return nullptr;
1577         }
1578
1579         if (RHS->getType() != StringRecTy::get()) {
1580           RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1581         }
1582   
1583         break;
1584       }
1585
1586       Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1587                               StringRecTy::get())->Fold(CurRec, CurMultiClass);
1588       break;
1589     }
1590   }
1591 }
1592
1593 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1594 ///
1595 ///    DagArg     ::= Value (':' VARNAME)?
1596 ///    DagArg     ::= VARNAME
1597 ///    DagArgList ::= DagArg
1598 ///    DagArgList ::= DagArgList ',' DagArg
1599 std::vector<std::pair<llvm::Init*, std::string> >
1600 TGParser::ParseDagArgList(Record *CurRec) {
1601   std::vector<std::pair<llvm::Init*, std::string> > Result;
1602
1603   while (1) {
1604     // DagArg ::= VARNAME
1605     if (Lex.getCode() == tgtok::VarName) {
1606       // A missing value is treated like '?'.
1607       Result.push_back(std::make_pair(UnsetInit::get(), Lex.getCurStrVal()));
1608       Lex.Lex();
1609     } else {
1610       // DagArg ::= Value (':' VARNAME)?
1611       Init *Val = ParseValue(CurRec);
1612       if (!Val)
1613         return std::vector<std::pair<llvm::Init*, std::string> >();
1614
1615       // If the variable name is present, add it.
1616       std::string VarName;
1617       if (Lex.getCode() == tgtok::colon) {
1618         if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1619           TokError("expected variable name in dag literal");
1620           return std::vector<std::pair<llvm::Init*, std::string> >();
1621         }
1622         VarName = Lex.getCurStrVal();
1623         Lex.Lex();  // eat the VarName.
1624       }
1625
1626       Result.push_back(std::make_pair(Val, VarName));
1627     }
1628     if (Lex.getCode() != tgtok::comma) break;
1629     Lex.Lex(); // eat the ','
1630   }
1631
1632   return Result;
1633 }
1634
1635
1636 /// ParseValueList - Parse a comma separated list of values, returning them as a
1637 /// vector.  Note that this always expects to be able to parse at least one
1638 /// value.  It returns an empty list if this is not possible.
1639 ///
1640 ///   ValueList ::= Value (',' Value)
1641 ///
1642 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1643                                             RecTy *EltTy) {
1644   std::vector<Init*> Result;
1645   RecTy *ItemType = EltTy;
1646   unsigned int ArgN = 0;
1647   if (ArgsRec && !EltTy) {
1648     const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1649     if (!TArgs.size()) {
1650       TokError("template argument provided to non-template class");
1651       return std::vector<Init*>();
1652     }
1653     const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1654     if (!RV) {
1655       errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1656         << ")\n";
1657     }
1658     assert(RV && "Template argument record not found??");
1659     ItemType = RV->getType();
1660     ++ArgN;
1661   }
1662   Result.push_back(ParseValue(CurRec, ItemType));
1663   if (!Result.back()) return std::vector<Init*>();
1664
1665   while (Lex.getCode() == tgtok::comma) {
1666     Lex.Lex();  // Eat the comma
1667
1668     if (ArgsRec && !EltTy) {
1669       const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1670       if (ArgN >= TArgs.size()) {
1671         TokError("too many template arguments");
1672         return std::vector<Init*>();
1673       }
1674       const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1675       assert(RV && "Template argument record not found??");
1676       ItemType = RV->getType();
1677       ++ArgN;
1678     }
1679     Result.push_back(ParseValue(CurRec, ItemType));
1680     if (!Result.back()) return std::vector<Init*>();
1681   }
1682
1683   return Result;
1684 }
1685
1686
1687 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1688 /// empty string on error.  This can happen in a number of different context's,
1689 /// including within a def or in the template args for a def (which which case
1690 /// CurRec will be non-null) and within the template args for a multiclass (in
1691 /// which case CurRec will be null, but CurMultiClass will be set).  This can
1692 /// also happen within a def that is within a multiclass, which will set both
1693 /// CurRec and CurMultiClass.
1694 ///
1695 ///  Declaration ::= FIELD? Type ID ('=' Value)?
1696 ///
1697 Init *TGParser::ParseDeclaration(Record *CurRec,
1698                                        bool ParsingTemplateArgs) {
1699   // Read the field prefix if present.
1700   bool HasField = Lex.getCode() == tgtok::Field;
1701   if (HasField) Lex.Lex();
1702
1703   RecTy *Type = ParseType();
1704   if (!Type) return nullptr;
1705
1706   if (Lex.getCode() != tgtok::Id) {
1707     TokError("Expected identifier in declaration");
1708     return nullptr;
1709   }
1710
1711   SMLoc IdLoc = Lex.getLoc();
1712   Init *DeclName = StringInit::get(Lex.getCurStrVal());
1713   Lex.Lex();
1714
1715   if (ParsingTemplateArgs) {
1716     if (CurRec) {
1717       DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1718     } else {
1719       assert(CurMultiClass);
1720     }
1721     if (CurMultiClass)
1722       DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1723                              "::");
1724   }
1725
1726   // Add the value.
1727   if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1728     return nullptr;
1729
1730   // If a value is present, parse it.
1731   if (Lex.getCode() == tgtok::equal) {
1732     Lex.Lex();
1733     SMLoc ValLoc = Lex.getLoc();
1734     Init *Val = ParseValue(CurRec, Type);
1735     if (!Val ||
1736         SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1737       // Return the name, even if an error is thrown.  This is so that we can
1738       // continue to make some progress, even without the value having been
1739       // initialized.
1740       return DeclName;
1741   }
1742
1743   return DeclName;
1744 }
1745
1746 /// ParseForeachDeclaration - Read a foreach declaration, returning
1747 /// the name of the declared object or a NULL Init on error.  Return
1748 /// the name of the parsed initializer list through ForeachListName.
1749 ///
1750 ///  ForeachDeclaration ::= ID '=' '[' ValueList ']'
1751 ///  ForeachDeclaration ::= ID '=' '{' RangeList '}'
1752 ///  ForeachDeclaration ::= ID '=' RangePiece
1753 ///
1754 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1755   if (Lex.getCode() != tgtok::Id) {
1756     TokError("Expected identifier in foreach declaration");
1757     return nullptr;
1758   }
1759
1760   Init *DeclName = StringInit::get(Lex.getCurStrVal());
1761   Lex.Lex();
1762
1763   // If a value is present, parse it.
1764   if (Lex.getCode() != tgtok::equal) {
1765     TokError("Expected '=' in foreach declaration");
1766     return nullptr;
1767   }
1768   Lex.Lex();  // Eat the '='
1769
1770   RecTy *IterType = nullptr;
1771   std::vector<unsigned> Ranges;
1772
1773   switch (Lex.getCode()) {
1774   default: TokError("Unknown token when expecting a range list"); return nullptr;
1775   case tgtok::l_square: { // '[' ValueList ']'
1776     Init *List = ParseSimpleValue(nullptr, nullptr, ParseForeachMode);
1777     ForeachListValue = dyn_cast<ListInit>(List);
1778     if (!ForeachListValue) {
1779       TokError("Expected a Value list");
1780       return nullptr;
1781     }
1782     RecTy *ValueType = ForeachListValue->getType();
1783     ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1784     if (!ListType) {
1785       TokError("Value list is not of list type");
1786       return nullptr;
1787     }
1788     IterType = ListType->getElementType();
1789     break;
1790   }
1791
1792   case tgtok::IntVal: { // RangePiece.
1793     if (ParseRangePiece(Ranges))
1794       return nullptr;
1795     break;
1796   }
1797
1798   case tgtok::l_brace: { // '{' RangeList '}'
1799     Lex.Lex(); // eat the '{'
1800     Ranges = ParseRangeList();
1801     if (Lex.getCode() != tgtok::r_brace) {
1802       TokError("expected '}' at end of bit range list");
1803       return nullptr;
1804     }
1805     Lex.Lex();
1806     break;
1807   }
1808   }
1809
1810   if (!Ranges.empty()) {
1811     assert(!IterType && "Type already initialized?");
1812     IterType = IntRecTy::get();
1813     std::vector<Init*> Values;
1814     for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
1815       Values.push_back(IntInit::get(Ranges[i]));
1816     ForeachListValue = ListInit::get(Values, IterType);
1817   }
1818
1819   if (!IterType)
1820     return nullptr;
1821
1822   return VarInit::get(DeclName, IterType);
1823 }
1824
1825 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1826 /// sequence of template-declarations in <>'s.  If CurRec is non-null, these are
1827 /// template args for a def, which may or may not be in a multiclass.  If null,
1828 /// these are the template args for a multiclass.
1829 ///
1830 ///    TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1831 ///
1832 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1833   assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1834   Lex.Lex(); // eat the '<'
1835
1836   Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1837
1838   // Read the first declaration.
1839   Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1840   if (!TemplArg)
1841     return true;
1842
1843   TheRecToAddTo->addTemplateArg(TemplArg);
1844
1845   while (Lex.getCode() == tgtok::comma) {
1846     Lex.Lex(); // eat the ','
1847
1848     // Read the following declarations.
1849     TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1850     if (!TemplArg)
1851       return true;
1852     TheRecToAddTo->addTemplateArg(TemplArg);
1853   }
1854
1855   if (Lex.getCode() != tgtok::greater)
1856     return TokError("expected '>' at end of template argument list");
1857   Lex.Lex(); // eat the '>'.
1858   return false;
1859 }
1860
1861
1862 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1863 ///
1864 ///   BodyItem ::= Declaration ';'
1865 ///   BodyItem ::= LET ID OptionalBitList '=' Value ';'
1866 bool TGParser::ParseBodyItem(Record *CurRec) {
1867   if (Lex.getCode() != tgtok::Let) {
1868     if (!ParseDeclaration(CurRec, false))
1869       return true;
1870
1871     if (Lex.getCode() != tgtok::semi)
1872       return TokError("expected ';' after declaration");
1873     Lex.Lex();
1874     return false;
1875   }
1876
1877   // LET ID OptionalRangeList '=' Value ';'
1878   if (Lex.Lex() != tgtok::Id)
1879     return TokError("expected field identifier after let");
1880
1881   SMLoc IdLoc = Lex.getLoc();
1882   std::string FieldName = Lex.getCurStrVal();
1883   Lex.Lex();  // eat the field name.
1884
1885   std::vector<unsigned> BitList;
1886   if (ParseOptionalBitList(BitList))
1887     return true;
1888   std::reverse(BitList.begin(), BitList.end());
1889
1890   if (Lex.getCode() != tgtok::equal)
1891     return TokError("expected '=' in let expression");
1892   Lex.Lex();  // eat the '='.
1893
1894   RecordVal *Field = CurRec->getValue(FieldName);
1895   if (!Field)
1896     return TokError("Value '" + FieldName + "' unknown!");
1897
1898   RecTy *Type = Field->getType();
1899
1900   Init *Val = ParseValue(CurRec, Type);
1901   if (!Val) return true;
1902
1903   if (Lex.getCode() != tgtok::semi)
1904     return TokError("expected ';' after let expression");
1905   Lex.Lex();
1906
1907   return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1908 }
1909
1910 /// ParseBody - Read the body of a class or def.  Return true on error, false on
1911 /// success.
1912 ///
1913 ///   Body     ::= ';'
1914 ///   Body     ::= '{' BodyList '}'
1915 ///   BodyList BodyItem*
1916 ///
1917 bool TGParser::ParseBody(Record *CurRec) {
1918   // If this is a null definition, just eat the semi and return.
1919   if (Lex.getCode() == tgtok::semi) {
1920     Lex.Lex();
1921     return false;
1922   }
1923
1924   if (Lex.getCode() != tgtok::l_brace)
1925     return TokError("Expected ';' or '{' to start body");
1926   // Eat the '{'.
1927   Lex.Lex();
1928
1929   while (Lex.getCode() != tgtok::r_brace)
1930     if (ParseBodyItem(CurRec))
1931       return true;
1932
1933   // Eat the '}'.
1934   Lex.Lex();
1935   return false;
1936 }
1937
1938 /// \brief Apply the current let bindings to \a CurRec.
1939 /// \returns true on error, false otherwise.
1940 bool TGParser::ApplyLetStack(Record *CurRec) {
1941   for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1942     for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1943       if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1944                    LetStack[i][j].Bits, LetStack[i][j].Value))
1945         return true;
1946   return false;
1947 }
1948
1949 /// ParseObjectBody - Parse the body of a def or class.  This consists of an
1950 /// optional ClassList followed by a Body.  CurRec is the current def or class
1951 /// that is being parsed.
1952 ///
1953 ///   ObjectBody      ::= BaseClassList Body
1954 ///   BaseClassList   ::= /*empty*/
1955 ///   BaseClassList   ::= ':' BaseClassListNE
1956 ///   BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1957 ///
1958 bool TGParser::ParseObjectBody(Record *CurRec) {
1959   // If there is a baseclass list, read it.
1960   if (Lex.getCode() == tgtok::colon) {
1961     Lex.Lex();
1962
1963     // Read all of the subclasses.
1964     SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1965     while (1) {
1966       // Check for error.
1967       if (!SubClass.Rec) return true;
1968
1969       // Add it.
1970       if (AddSubClass(CurRec, SubClass))
1971         return true;
1972
1973       if (Lex.getCode() != tgtok::comma) break;
1974       Lex.Lex(); // eat ','.
1975       SubClass = ParseSubClassReference(CurRec, false);
1976     }
1977   }
1978
1979   if (ApplyLetStack(CurRec))
1980     return true;
1981
1982   return ParseBody(CurRec);
1983 }
1984
1985 /// ParseDef - Parse and return a top level or multiclass def, return the record
1986 /// corresponding to it.  This returns null on error.
1987 ///
1988 ///   DefInst ::= DEF ObjectName ObjectBody
1989 ///
1990 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1991   SMLoc DefLoc = Lex.getLoc();
1992   assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1993   Lex.Lex();  // Eat the 'def' token.
1994
1995   // Parse ObjectName and make a record for it.
1996   Record *CurRec;
1997   Init *Name = ParseObjectName(CurMultiClass);
1998   if (Name)
1999     CurRec = new Record(Name, DefLoc, Records);
2000   else
2001     CurRec = new Record(GetNewAnonymousName(), DefLoc, Records,
2002                         /*IsAnonymous=*/true);
2003
2004   if (!CurMultiClass && Loops.empty()) {
2005     // Top-level def definition.
2006
2007     // Ensure redefinition doesn't happen.
2008     if (Records.getDef(CurRec->getNameInitAsString())) {
2009       Error(DefLoc, "def '" + CurRec->getNameInitAsString()
2010             + "' already defined");
2011       return true;
2012     }
2013     Records.addDef(CurRec);
2014
2015     if (ParseObjectBody(CurRec))
2016       return true;
2017   } else if (CurMultiClass) {
2018     // Parse the body before adding this prototype to the DefPrototypes vector.
2019     // That way implicit definitions will be added to the DefPrototypes vector
2020     // before this object, instantiated prior to defs derived from this object,
2021     // and this available for indirect name resolution when defs derived from
2022     // this object are instantiated.
2023     if (ParseObjectBody(CurRec))
2024       return true;
2025
2026     // Otherwise, a def inside a multiclass, add it to the multiclass.
2027     for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
2028       if (CurMultiClass->DefPrototypes[i]->getNameInit()
2029           == CurRec->getNameInit()) {
2030         Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
2031               "' already defined in this multiclass!");
2032         return true;
2033       }
2034     CurMultiClass->DefPrototypes.push_back(CurRec);
2035   } else if (ParseObjectBody(CurRec))
2036     return true;
2037
2038   if (!CurMultiClass)  // Def's in multiclasses aren't really defs.
2039     // See Record::setName().  This resolve step will see any new name
2040     // for the def that might have been created when resolving
2041     // inheritance, values and arguments above.
2042     CurRec->resolveReferences();
2043
2044   // If ObjectBody has template arguments, it's an error.
2045   assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
2046
2047   if (CurMultiClass) {
2048     // Copy the template arguments for the multiclass into the def.
2049     const std::vector<Init *> &TArgs =
2050                                 CurMultiClass->Rec.getTemplateArgs();
2051
2052     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2053       const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
2054       assert(RV && "Template arg doesn't exist?");
2055       CurRec->addValue(*RV);
2056     }
2057   }
2058
2059   if (ProcessForeachDefs(CurRec, DefLoc)) {
2060     Error(DefLoc,
2061           "Could not process loops for def" + CurRec->getNameInitAsString());
2062     return true;
2063   }
2064
2065   return false;
2066 }
2067
2068 /// ParseForeach - Parse a for statement.  Return the record corresponding
2069 /// to it.  This returns true on error.
2070 ///
2071 ///   Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2072 ///   Foreach ::= FOREACH Declaration IN Object
2073 ///
2074 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2075   assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2076   Lex.Lex();  // Eat the 'for' token.
2077
2078   // Make a temporary object to record items associated with the for
2079   // loop.
2080   ListInit *ListValue = nullptr;
2081   VarInit *IterName = ParseForeachDeclaration(ListValue);
2082   if (!IterName)
2083     return TokError("expected declaration in for");
2084
2085   if (Lex.getCode() != tgtok::In)
2086     return TokError("Unknown tok");
2087   Lex.Lex();  // Eat the in
2088
2089   // Create a loop object and remember it.
2090   Loops.push_back(ForeachLoop(IterName, ListValue));
2091
2092   if (Lex.getCode() != tgtok::l_brace) {
2093     // FOREACH Declaration IN Object
2094     if (ParseObject(CurMultiClass))
2095       return true;
2096   }
2097   else {
2098     SMLoc BraceLoc = Lex.getLoc();
2099     // Otherwise, this is a group foreach.
2100     Lex.Lex();  // eat the '{'.
2101
2102     // Parse the object list.
2103     if (ParseObjectList(CurMultiClass))
2104       return true;
2105
2106     if (Lex.getCode() != tgtok::r_brace) {
2107       TokError("expected '}' at end of foreach command");
2108       return Error(BraceLoc, "to match this '{'");
2109     }
2110     Lex.Lex();  // Eat the }
2111   }
2112
2113   // We've processed everything in this loop.
2114   Loops.pop_back();
2115
2116   return false;
2117 }
2118
2119 /// ParseClass - Parse a tblgen class definition.
2120 ///
2121 ///   ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2122 ///
2123 bool TGParser::ParseClass() {
2124   assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2125   Lex.Lex();
2126
2127   if (Lex.getCode() != tgtok::Id)
2128     return TokError("expected class name after 'class' keyword");
2129
2130   Record *CurRec = Records.getClass(Lex.getCurStrVal());
2131   if (CurRec) {
2132     // If the body was previously defined, this is an error.
2133     if (CurRec->getValues().size() > 1 ||  // Account for NAME.
2134         !CurRec->getSuperClasses().empty() ||
2135         !CurRec->getTemplateArgs().empty())
2136       return TokError("Class '" + CurRec->getNameInitAsString()
2137                       + "' already defined");
2138   } else {
2139     // If this is the first reference to this class, create and add it.
2140     CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
2141     Records.addClass(CurRec);
2142   }
2143   Lex.Lex(); // eat the name.
2144
2145   // If there are template args, parse them.
2146   if (Lex.getCode() == tgtok::less)
2147     if (ParseTemplateArgList(CurRec))
2148       return true;
2149
2150   // Finally, parse the object body.
2151   return ParseObjectBody(CurRec);
2152 }
2153
2154 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2155 /// of LetRecords.
2156 ///
2157 ///   LetList ::= LetItem (',' LetItem)*
2158 ///   LetItem ::= ID OptionalRangeList '=' Value
2159 ///
2160 std::vector<LetRecord> TGParser::ParseLetList() {
2161   std::vector<LetRecord> Result;
2162
2163   while (1) {
2164     if (Lex.getCode() != tgtok::Id) {
2165       TokError("expected identifier in let definition");
2166       return std::vector<LetRecord>();
2167     }
2168     std::string Name = Lex.getCurStrVal();
2169     SMLoc NameLoc = Lex.getLoc();
2170     Lex.Lex();  // Eat the identifier.
2171
2172     // Check for an optional RangeList.
2173     std::vector<unsigned> Bits;
2174     if (ParseOptionalRangeList(Bits))
2175       return std::vector<LetRecord>();
2176     std::reverse(Bits.begin(), Bits.end());
2177
2178     if (Lex.getCode() != tgtok::equal) {
2179       TokError("expected '=' in let expression");
2180       return std::vector<LetRecord>();
2181     }
2182     Lex.Lex();  // eat the '='.
2183
2184     Init *Val = ParseValue(nullptr);
2185     if (!Val) return std::vector<LetRecord>();
2186
2187     // Now that we have everything, add the record.
2188     Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
2189
2190     if (Lex.getCode() != tgtok::comma)
2191       return Result;
2192     Lex.Lex();  // eat the comma.
2193   }
2194 }
2195
2196 /// ParseTopLevelLet - Parse a 'let' at top level.  This can be a couple of
2197 /// different related productions. This works inside multiclasses too.
2198 ///
2199 ///   Object ::= LET LetList IN '{' ObjectList '}'
2200 ///   Object ::= LET LetList IN Object
2201 ///
2202 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2203   assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2204   Lex.Lex();
2205
2206   // Add this entry to the let stack.
2207   std::vector<LetRecord> LetInfo = ParseLetList();
2208   if (LetInfo.empty()) return true;
2209   LetStack.push_back(LetInfo);
2210
2211   if (Lex.getCode() != tgtok::In)
2212     return TokError("expected 'in' at end of top-level 'let'");
2213   Lex.Lex();
2214
2215   // If this is a scalar let, just handle it now
2216   if (Lex.getCode() != tgtok::l_brace) {
2217     // LET LetList IN Object
2218     if (ParseObject(CurMultiClass))
2219       return true;
2220   } else {   // Object ::= LETCommand '{' ObjectList '}'
2221     SMLoc BraceLoc = Lex.getLoc();
2222     // Otherwise, this is a group let.
2223     Lex.Lex();  // eat the '{'.
2224
2225     // Parse the object list.
2226     if (ParseObjectList(CurMultiClass))
2227       return true;
2228
2229     if (Lex.getCode() != tgtok::r_brace) {
2230       TokError("expected '}' at end of top level let command");
2231       return Error(BraceLoc, "to match this '{'");
2232     }
2233     Lex.Lex();
2234   }
2235
2236   // Outside this let scope, this let block is not active.
2237   LetStack.pop_back();
2238   return false;
2239 }
2240
2241 /// ParseMultiClass - Parse a multiclass definition.
2242 ///
2243 ///  MultiClassInst ::= MULTICLASS ID TemplateArgList?
2244 ///                     ':' BaseMultiClassList '{' MultiClassObject+ '}'
2245 ///  MultiClassObject ::= DefInst
2246 ///  MultiClassObject ::= MultiClassInst
2247 ///  MultiClassObject ::= DefMInst
2248 ///  MultiClassObject ::= LETCommand '{' ObjectList '}'
2249 ///  MultiClassObject ::= LETCommand Object
2250 ///
2251 bool TGParser::ParseMultiClass() {
2252   assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2253   Lex.Lex();  // Eat the multiclass token.
2254
2255   if (Lex.getCode() != tgtok::Id)
2256     return TokError("expected identifier after multiclass for name");
2257   std::string Name = Lex.getCurStrVal();
2258
2259   if (MultiClasses.count(Name))
2260     return TokError("multiclass '" + Name + "' already defined");
2261
2262   CurMultiClass = MultiClasses[Name] = new MultiClass(Name, 
2263                                                       Lex.getLoc(), Records);
2264   Lex.Lex();  // Eat the identifier.
2265
2266   // If there are template args, parse them.
2267   if (Lex.getCode() == tgtok::less)
2268     if (ParseTemplateArgList(nullptr))
2269       return true;
2270
2271   bool inherits = false;
2272
2273   // If there are submulticlasses, parse them.
2274   if (Lex.getCode() == tgtok::colon) {
2275     inherits = true;
2276
2277     Lex.Lex();
2278
2279     // Read all of the submulticlasses.
2280     SubMultiClassReference SubMultiClass =
2281       ParseSubMultiClassReference(CurMultiClass);
2282     while (1) {
2283       // Check for error.
2284       if (!SubMultiClass.MC) return true;
2285
2286       // Add it.
2287       if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2288         return true;
2289
2290       if (Lex.getCode() != tgtok::comma) break;
2291       Lex.Lex(); // eat ','.
2292       SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2293     }
2294   }
2295
2296   if (Lex.getCode() != tgtok::l_brace) {
2297     if (!inherits)
2298       return TokError("expected '{' in multiclass definition");
2299     else if (Lex.getCode() != tgtok::semi)
2300       return TokError("expected ';' in multiclass definition");
2301     else
2302       Lex.Lex();  // eat the ';'.
2303   } else {
2304     if (Lex.Lex() == tgtok::r_brace)  // eat the '{'.
2305       return TokError("multiclass must contain at least one def");
2306
2307     while (Lex.getCode() != tgtok::r_brace) {
2308       switch (Lex.getCode()) {
2309         default:
2310           return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2311         case tgtok::Let:
2312         case tgtok::Def:
2313         case tgtok::Defm:
2314         case tgtok::Foreach:
2315           if (ParseObject(CurMultiClass))
2316             return true;
2317          break;
2318       }
2319     }
2320     Lex.Lex();  // eat the '}'.
2321   }
2322
2323   CurMultiClass = nullptr;
2324   return false;
2325 }
2326
2327 Record *TGParser::
2328 InstantiateMulticlassDef(MultiClass &MC,
2329                          Record *DefProto,
2330                          Init *&DefmPrefix,
2331                          SMRange DefmPrefixRange) {
2332   // We need to preserve DefProto so it can be reused for later
2333   // instantiations, so create a new Record to inherit from it.
2334
2335   // Add in the defm name.  If the defm prefix is empty, give each
2336   // instantiated def a unique name.  Otherwise, if "#NAME#" exists in the
2337   // name, substitute the prefix for #NAME#.  Otherwise, use the defm name
2338   // as a prefix.
2339
2340   bool IsAnonymous = false;
2341   if (!DefmPrefix) {
2342     DefmPrefix = StringInit::get(GetNewAnonymousName());
2343     IsAnonymous = true;
2344   }
2345
2346   Init *DefName = DefProto->getNameInit();
2347
2348   StringInit *DefNameString = dyn_cast<StringInit>(DefName);
2349
2350   if (DefNameString) {
2351     // We have a fully expanded string so there are no operators to
2352     // resolve.  We should concatenate the given prefix and name.
2353     DefName =
2354       BinOpInit::get(BinOpInit::STRCONCAT,
2355                      UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2356                                    StringRecTy::get())->Fold(DefProto, &MC),
2357                      DefName, StringRecTy::get())->Fold(DefProto, &MC);
2358   }
2359
2360   // Make a trail of SMLocs from the multiclass instantiations.
2361   SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
2362   Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2363   Record *CurRec = new Record(DefName, Locs, Records, IsAnonymous);
2364
2365   SubClassReference Ref;
2366   Ref.RefRange = DefmPrefixRange;
2367   Ref.Rec = DefProto;
2368   AddSubClass(CurRec, Ref);
2369
2370   // Set the value for NAME. We don't resolve references to it 'til later,
2371   // though, so that uses in nested multiclass names don't get
2372   // confused.
2373   if (SetValue(CurRec, Ref.RefRange.Start, "NAME", std::vector<unsigned>(),
2374                DefmPrefix)) {
2375     Error(DefmPrefixRange.Start, "Could not resolve "
2376           + CurRec->getNameInitAsString() + ":NAME to '"
2377           + DefmPrefix->getAsUnquotedString() + "'");
2378     return nullptr;
2379   }
2380
2381   // If the DefNameString didn't resolve, we probably have a reference to
2382   // NAME and need to replace it. We need to do at least this much greedily,
2383   // otherwise nested multiclasses will end up with incorrect NAME expansions.
2384   if (!DefNameString) {
2385     RecordVal *DefNameRV = CurRec->getValue("NAME");
2386     CurRec->resolveReferencesTo(DefNameRV);
2387   }
2388
2389   if (!CurMultiClass) {
2390     // Now that we're at the top level, resolve all NAME references
2391     // in the resultant defs that weren't in the def names themselves.
2392     RecordVal *DefNameRV = CurRec->getValue("NAME");
2393     CurRec->resolveReferencesTo(DefNameRV);
2394
2395     // Now that NAME references are resolved and we're at the top level of
2396     // any multiclass expansions, add the record to the RecordKeeper. If we are
2397     // currently in a multiclass, it means this defm appears inside a
2398     // multiclass and its name won't be fully resolvable until we see
2399     // the top-level defm.  Therefore, we don't add this to the
2400     // RecordKeeper at this point.  If we did we could get duplicate
2401     // defs as more than one probably refers to NAME or some other
2402     // common internal placeholder.
2403
2404     // Ensure redefinition doesn't happen.
2405     if (Records.getDef(CurRec->getNameInitAsString())) {
2406       Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
2407             "' already defined, instantiating defm with subdef '" + 
2408             DefProto->getNameInitAsString() + "'");
2409       return nullptr;
2410     }
2411
2412     Records.addDef(CurRec);
2413   }
2414
2415   return CurRec;
2416 }
2417
2418 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2419                                         Record *CurRec,
2420                                         SMLoc DefmPrefixLoc,
2421                                         SMLoc SubClassLoc,
2422                                         const std::vector<Init *> &TArgs,
2423                                         std::vector<Init *> &TemplateVals,
2424                                         bool DeleteArgs) {
2425   // Loop over all of the template arguments, setting them to the specified
2426   // value or leaving them as the default if necessary.
2427   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2428     // Check if a value is specified for this temp-arg.
2429     if (i < TemplateVals.size()) {
2430       // Set it now.
2431       if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2432                    TemplateVals[i]))
2433         return true;
2434         
2435       // Resolve it next.
2436       CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2437
2438       if (DeleteArgs)
2439         // Now remove it.
2440         CurRec->removeValue(TArgs[i]);
2441         
2442     } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2443       return Error(SubClassLoc, "value not specified for template argument #"+
2444                    utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2445                    + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2446                    + "'");
2447     }
2448   }
2449   return false;
2450 }
2451
2452 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2453                                     Record *CurRec,
2454                                     Record *DefProto,
2455                                     SMLoc DefmPrefixLoc) {
2456   // If the mdef is inside a 'let' expression, add to each def.
2457   if (ApplyLetStack(CurRec))
2458     return Error(DefmPrefixLoc, "when instantiating this defm");
2459
2460   // Don't create a top level definition for defm inside multiclasses,
2461   // instead, only update the prototypes and bind the template args
2462   // with the new created definition.
2463   if (!CurMultiClass)
2464     return false;
2465   for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2466        i != e; ++i)
2467     if (CurMultiClass->DefPrototypes[i]->getNameInit()
2468         == CurRec->getNameInit())
2469       return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2470                    "' already defined in this multiclass!");
2471   CurMultiClass->DefPrototypes.push_back(CurRec);
2472
2473   // Copy the template arguments for the multiclass into the new def.
2474   const std::vector<Init *> &TA =
2475     CurMultiClass->Rec.getTemplateArgs();
2476
2477   for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2478     const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2479     assert(RV && "Template arg doesn't exist?");
2480     CurRec->addValue(*RV);
2481   }
2482
2483   return false;
2484 }
2485
2486 /// ParseDefm - Parse the instantiation of a multiclass.
2487 ///
2488 ///   DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2489 ///
2490 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2491   assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2492   SMLoc DefmLoc = Lex.getLoc();
2493   Init *DefmPrefix = nullptr;
2494
2495   if (Lex.Lex() == tgtok::Id) {  // eat the defm.
2496     DefmPrefix = ParseObjectName(CurMultiClass);
2497   }
2498
2499   SMLoc DefmPrefixEndLoc = Lex.getLoc();
2500   if (Lex.getCode() != tgtok::colon)
2501     return TokError("expected ':' after defm identifier");
2502
2503   // Keep track of the new generated record definitions.
2504   std::vector<Record*> NewRecDefs;
2505
2506   // This record also inherits from a regular class (non-multiclass)?
2507   bool InheritFromClass = false;
2508
2509   // eat the colon.
2510   Lex.Lex();
2511
2512   SMLoc SubClassLoc = Lex.getLoc();
2513   SubClassReference Ref = ParseSubClassReference(nullptr, true);
2514
2515   while (1) {
2516     if (!Ref.Rec) return true;
2517
2518     // To instantiate a multiclass, we need to first get the multiclass, then
2519     // instantiate each def contained in the multiclass with the SubClassRef
2520     // template parameters.
2521     MultiClass *MC = MultiClasses[Ref.Rec->getName()];
2522     assert(MC && "Didn't lookup multiclass correctly?");
2523     std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2524
2525     // Verify that the correct number of template arguments were specified.
2526     const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2527     if (TArgs.size() < TemplateVals.size())
2528       return Error(SubClassLoc,
2529                    "more template args specified than multiclass expects");
2530
2531     // Loop over all the def's in the multiclass, instantiating each one.
2532     for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2533       Record *DefProto = MC->DefPrototypes[i];
2534
2535       Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix,
2536                                                 SMRange(DefmLoc,
2537                                                         DefmPrefixEndLoc));
2538       if (!CurRec)
2539         return true;
2540
2541       if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
2542                                    TArgs, TemplateVals, true/*Delete args*/))
2543         return Error(SubClassLoc, "could not instantiate def");
2544
2545       if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmLoc))
2546         return Error(SubClassLoc, "could not instantiate def");
2547
2548       NewRecDefs.push_back(CurRec);
2549     }
2550
2551
2552     if (Lex.getCode() != tgtok::comma) break;
2553     Lex.Lex(); // eat ','.
2554
2555     if (Lex.getCode() != tgtok::Id)
2556       return TokError("expected identifier");
2557
2558     SubClassLoc = Lex.getLoc();
2559
2560     // A defm can inherit from regular classes (non-multiclass) as
2561     // long as they come in the end of the inheritance list.
2562     InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
2563
2564     if (InheritFromClass)
2565       break;
2566
2567     Ref = ParseSubClassReference(nullptr, true);
2568   }
2569
2570   if (InheritFromClass) {
2571     // Process all the classes to inherit as if they were part of a
2572     // regular 'def' and inherit all record values.
2573     SubClassReference SubClass = ParseSubClassReference(nullptr, false);
2574     while (1) {
2575       // Check for error.
2576       if (!SubClass.Rec) return true;
2577
2578       // Get the expanded definition prototypes and teach them about
2579       // the record values the current class to inherit has
2580       for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2581         Record *CurRec = NewRecDefs[i];
2582
2583         // Add it.
2584         if (AddSubClass(CurRec, SubClass))
2585           return true;
2586
2587         if (ApplyLetStack(CurRec))
2588           return true;
2589       }
2590
2591       if (Lex.getCode() != tgtok::comma) break;
2592       Lex.Lex(); // eat ','.
2593       SubClass = ParseSubClassReference(nullptr, false);
2594     }
2595   }
2596
2597   if (!CurMultiClass)
2598     for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2599       // See Record::setName().  This resolve step will see any new
2600       // name for the def that might have been created when resolving
2601       // inheritance, values and arguments above.
2602       NewRecDefs[i]->resolveReferences();
2603
2604   if (Lex.getCode() != tgtok::semi)
2605     return TokError("expected ';' at end of defm");
2606   Lex.Lex();
2607
2608   return false;
2609 }
2610
2611 /// ParseObject
2612 ///   Object ::= ClassInst
2613 ///   Object ::= DefInst
2614 ///   Object ::= MultiClassInst
2615 ///   Object ::= DefMInst
2616 ///   Object ::= LETCommand '{' ObjectList '}'
2617 ///   Object ::= LETCommand Object
2618 bool TGParser::ParseObject(MultiClass *MC) {
2619   switch (Lex.getCode()) {
2620   default:
2621     return TokError("Expected class, def, defm, multiclass or let definition");
2622   case tgtok::Let:   return ParseTopLevelLet(MC);
2623   case tgtok::Def:   return ParseDef(MC);
2624   case tgtok::Foreach:   return ParseForeach(MC);
2625   case tgtok::Defm:  return ParseDefm(MC);
2626   case tgtok::Class: return ParseClass();
2627   case tgtok::MultiClass: return ParseMultiClass();
2628   }
2629 }
2630
2631 /// ParseObjectList
2632 ///   ObjectList :== Object*
2633 bool TGParser::ParseObjectList(MultiClass *MC) {
2634   while (isObjectStart(Lex.getCode())) {
2635     if (ParseObject(MC))
2636       return true;
2637   }
2638   return false;
2639 }
2640
2641 bool TGParser::ParseFile() {
2642   Lex.Lex(); // Prime the lexer.
2643   if (ParseObjectList()) return true;
2644
2645   // If we have unread input at the end of the file, report it.
2646   if (Lex.getCode() == tgtok::Eof)
2647     return false;
2648
2649   return TokError("Unexpected input at top level");
2650 }
2651