Allow binary and for tblgen math.
[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::XAND:
915   case tgtok::XSRA:
916   case tgtok::XSRL:
917   case tgtok::XSHL:
918   case tgtok::XEq:
919   case tgtok::XListConcat:
920   case tgtok::XStrConcat: {  // Value ::= !binop '(' Value ',' Value ')'
921     tgtok::TokKind OpTok = Lex.getCode();
922     SMLoc OpLoc = Lex.getLoc();
923     Lex.Lex();  // eat the operation
924
925     BinOpInit::BinaryOp Code;
926     RecTy *Type = nullptr;
927
928     switch (OpTok) {
929     default: llvm_unreachable("Unhandled code!");
930     case tgtok::XConcat: Code = BinOpInit::CONCAT;Type = DagRecTy::get(); break;
931     case tgtok::XADD:    Code = BinOpInit::ADD;   Type = IntRecTy::get(); break;
932     case tgtok::XAND:    Code = BinOpInit::AND;   Type = IntRecTy::get(); break;
933     case tgtok::XSRA:    Code = BinOpInit::SRA;   Type = IntRecTy::get(); break;
934     case tgtok::XSRL:    Code = BinOpInit::SRL;   Type = IntRecTy::get(); break;
935     case tgtok::XSHL:    Code = BinOpInit::SHL;   Type = IntRecTy::get(); break;
936     case tgtok::XEq:     Code = BinOpInit::EQ;    Type = BitRecTy::get(); break;
937     case tgtok::XListConcat:
938       Code = BinOpInit::LISTCONCAT;
939       // We don't know the list type until we parse the first argument
940       break;
941     case tgtok::XStrConcat:
942       Code = BinOpInit::STRCONCAT;
943       Type = StringRecTy::get();
944       break;
945     }
946
947     if (Lex.getCode() != tgtok::l_paren) {
948       TokError("expected '(' after binary operator");
949       return nullptr;
950     }
951     Lex.Lex();  // eat the '('
952
953     SmallVector<Init*, 2> InitList;
954
955     InitList.push_back(ParseValue(CurRec));
956     if (!InitList.back()) return nullptr;
957
958     while (Lex.getCode() == tgtok::comma) {
959       Lex.Lex();  // eat the ','
960
961       InitList.push_back(ParseValue(CurRec));
962       if (!InitList.back()) return nullptr;
963     }
964
965     if (Lex.getCode() != tgtok::r_paren) {
966       TokError("expected ')' in operator");
967       return nullptr;
968     }
969     Lex.Lex();  // eat the ')'
970
971     // If we are doing !listconcat, we should know the type by now
972     if (OpTok == tgtok::XListConcat) {
973       if (VarInit *Arg0 = dyn_cast<VarInit>(InitList[0]))
974         Type = Arg0->getType();
975       else if (ListInit *Arg0 = dyn_cast<ListInit>(InitList[0]))
976         Type = Arg0->getType();
977       else {
978         InitList[0]->dump();
979         Error(OpLoc, "expected a list");
980         return nullptr;
981       }
982     }
983
984     // We allow multiple operands to associative operators like !strconcat as
985     // shorthand for nesting them.
986     if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT) {
987       while (InitList.size() > 2) {
988         Init *RHS = InitList.pop_back_val();
989         RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))
990                            ->Fold(CurRec, CurMultiClass);
991         InitList.back() = RHS;
992       }
993     }
994
995     if (InitList.size() == 2)
996       return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
997         ->Fold(CurRec, CurMultiClass);
998
999     Error(OpLoc, "expected two operands to operator");
1000     return nullptr;
1001   }
1002
1003   case tgtok::XIf:
1004   case tgtok::XForEach:
1005   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1006     TernOpInit::TernaryOp Code;
1007     RecTy *Type = nullptr;
1008
1009     tgtok::TokKind LexCode = Lex.getCode();
1010     Lex.Lex();  // eat the operation
1011     switch (LexCode) {
1012     default: llvm_unreachable("Unhandled code!");
1013     case tgtok::XIf:
1014       Code = TernOpInit::IF;
1015       break;
1016     case tgtok::XForEach:
1017       Code = TernOpInit::FOREACH;
1018       break;
1019     case tgtok::XSubst:
1020       Code = TernOpInit::SUBST;
1021       break;
1022     }
1023     if (Lex.getCode() != tgtok::l_paren) {
1024       TokError("expected '(' after ternary operator");
1025       return nullptr;
1026     }
1027     Lex.Lex();  // eat the '('
1028
1029     Init *LHS = ParseValue(CurRec);
1030     if (!LHS) return nullptr;
1031
1032     if (Lex.getCode() != tgtok::comma) {
1033       TokError("expected ',' in ternary operator");
1034       return nullptr;
1035     }
1036     Lex.Lex();  // eat the ','
1037
1038     Init *MHS = ParseValue(CurRec, ItemType);
1039     if (!MHS)
1040       return nullptr;
1041
1042     if (Lex.getCode() != tgtok::comma) {
1043       TokError("expected ',' in ternary operator");
1044       return nullptr;
1045     }
1046     Lex.Lex();  // eat the ','
1047
1048     Init *RHS = ParseValue(CurRec, ItemType);
1049     if (!RHS)
1050       return nullptr;
1051
1052     if (Lex.getCode() != tgtok::r_paren) {
1053       TokError("expected ')' in binary operator");
1054       return nullptr;
1055     }
1056     Lex.Lex();  // eat the ')'
1057
1058     switch (LexCode) {
1059     default: llvm_unreachable("Unhandled code!");
1060     case tgtok::XIf: {
1061       RecTy *MHSTy = nullptr;
1062       RecTy *RHSTy = nullptr;
1063
1064       if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1065         MHSTy = MHSt->getType();
1066       if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1067         MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1068       if (isa<BitInit>(MHS))
1069         MHSTy = BitRecTy::get();
1070
1071       if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1072         RHSTy = RHSt->getType();
1073       if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1074         RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1075       if (isa<BitInit>(RHS))
1076         RHSTy = BitRecTy::get();
1077
1078       // For UnsetInit, it's typed from the other hand.
1079       if (isa<UnsetInit>(MHS))
1080         MHSTy = RHSTy;
1081       if (isa<UnsetInit>(RHS))
1082         RHSTy = MHSTy;
1083
1084       if (!MHSTy || !RHSTy) {
1085         TokError("could not get type for !if");
1086         return nullptr;
1087       }
1088
1089       if (MHSTy->typeIsConvertibleTo(RHSTy)) {
1090         Type = RHSTy;
1091       } else if (RHSTy->typeIsConvertibleTo(MHSTy)) {
1092         Type = MHSTy;
1093       } else {
1094         TokError("inconsistent types for !if");
1095         return nullptr;
1096       }
1097       break;
1098     }
1099     case tgtok::XForEach: {
1100       TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1101       if (!MHSt) {
1102         TokError("could not get type for !foreach");
1103         return nullptr;
1104       }
1105       Type = MHSt->getType();
1106       break;
1107     }
1108     case tgtok::XSubst: {
1109       TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1110       if (!RHSt) {
1111         TokError("could not get type for !subst");
1112         return nullptr;
1113       }
1114       Type = RHSt->getType();
1115       break;
1116     }
1117     }
1118     return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec,
1119                                                              CurMultiClass);
1120   }
1121   }
1122 }
1123
1124 /// ParseOperatorType - Parse a type for an operator.  This returns
1125 /// null on error.
1126 ///
1127 /// OperatorType ::= '<' Type '>'
1128 ///
1129 RecTy *TGParser::ParseOperatorType() {
1130   RecTy *Type = nullptr;
1131
1132   if (Lex.getCode() != tgtok::less) {
1133     TokError("expected type name for operator");
1134     return nullptr;
1135   }
1136   Lex.Lex();  // eat the <
1137
1138   Type = ParseType();
1139
1140   if (!Type) {
1141     TokError("expected type name for operator");
1142     return nullptr;
1143   }
1144
1145   if (Lex.getCode() != tgtok::greater) {
1146     TokError("expected type name for operator");
1147     return nullptr;
1148   }
1149   Lex.Lex();  // eat the >
1150
1151   return Type;
1152 }
1153
1154
1155 /// ParseSimpleValue - Parse a tblgen value.  This returns null on error.
1156 ///
1157 ///   SimpleValue ::= IDValue
1158 ///   SimpleValue ::= INTVAL
1159 ///   SimpleValue ::= STRVAL+
1160 ///   SimpleValue ::= CODEFRAGMENT
1161 ///   SimpleValue ::= '?'
1162 ///   SimpleValue ::= '{' ValueList '}'
1163 ///   SimpleValue ::= ID '<' ValueListNE '>'
1164 ///   SimpleValue ::= '[' ValueList ']'
1165 ///   SimpleValue ::= '(' IDValue DagArgList ')'
1166 ///   SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1167 ///   SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1168 ///   SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1169 ///   SimpleValue ::= SRATOK '(' Value ',' Value ')'
1170 ///   SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1171 ///   SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1172 ///   SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1173 ///
1174 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1175                                  IDParseMode Mode) {
1176   Init *R = nullptr;
1177   switch (Lex.getCode()) {
1178   default: TokError("Unknown token when parsing a value"); break;
1179   case tgtok::paste:
1180     // This is a leading paste operation.  This is deprecated but
1181     // still exists in some .td files.  Ignore it.
1182     Lex.Lex();  // Skip '#'.
1183     return ParseSimpleValue(CurRec, ItemType, Mode);
1184   case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1185   case tgtok::StrVal: {
1186     std::string Val = Lex.getCurStrVal();
1187     Lex.Lex();
1188
1189     // Handle multiple consecutive concatenated strings.
1190     while (Lex.getCode() == tgtok::StrVal) {
1191       Val += Lex.getCurStrVal();
1192       Lex.Lex();
1193     }
1194
1195     R = StringInit::get(Val);
1196     break;
1197   }
1198   case tgtok::CodeFragment:
1199     R = StringInit::get(Lex.getCurStrVal());
1200     Lex.Lex();
1201     break;
1202   case tgtok::question:
1203     R = UnsetInit::get();
1204     Lex.Lex();
1205     break;
1206   case tgtok::Id: {
1207     SMLoc NameLoc = Lex.getLoc();
1208     std::string Name = Lex.getCurStrVal();
1209     if (Lex.Lex() != tgtok::less)  // consume the Id.
1210       return ParseIDValue(CurRec, Name, NameLoc, Mode);    // Value ::= IDValue
1211
1212     // Value ::= ID '<' ValueListNE '>'
1213     if (Lex.Lex() == tgtok::greater) {
1214       TokError("expected non-empty value list");
1215       return nullptr;
1216     }
1217
1218     // This is a CLASS<initvalslist> expression.  This is supposed to synthesize
1219     // a new anonymous definition, deriving from CLASS<initvalslist> with no
1220     // body.
1221     Record *Class = Records.getClass(Name);
1222     if (!Class) {
1223       Error(NameLoc, "Expected a class name, got '" + Name + "'");
1224       return nullptr;
1225     }
1226
1227     std::vector<Init*> ValueList = ParseValueList(CurRec, Class);
1228     if (ValueList.empty()) return nullptr;
1229
1230     if (Lex.getCode() != tgtok::greater) {
1231       TokError("expected '>' at end of value list");
1232       return nullptr;
1233     }
1234     Lex.Lex();  // eat the '>'
1235     SMLoc EndLoc = Lex.getLoc();
1236
1237     // Create the new record, set it as CurRec temporarily.
1238     Record *NewRec = new Record(GetNewAnonymousName(), NameLoc, Records,
1239                                 /*IsAnonymous=*/true);
1240     SubClassReference SCRef;
1241     SCRef.RefRange = SMRange(NameLoc, EndLoc);
1242     SCRef.Rec = Class;
1243     SCRef.TemplateArgs = ValueList;
1244     // Add info about the subclass to NewRec.
1245     if (AddSubClass(NewRec, SCRef))
1246       return nullptr;
1247     if (!CurMultiClass) {
1248       NewRec->resolveReferences();
1249       Records.addDef(NewRec);
1250     } else {
1251       // Otherwise, we're inside a multiclass, add it to the multiclass.
1252       CurMultiClass->DefPrototypes.push_back(NewRec);
1253
1254       // Copy the template arguments for the multiclass into the def.
1255       const std::vector<Init *> &TArgs =
1256                                   CurMultiClass->Rec.getTemplateArgs();
1257
1258       for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
1259         const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
1260         assert(RV && "Template arg doesn't exist?");
1261         NewRec->addValue(*RV);
1262       }
1263
1264       // We can't return the prototype def here, instead return:
1265       // !cast<ItemType>(!strconcat(NAME, AnonName)).
1266       const RecordVal *MCNameRV = CurMultiClass->Rec.getValue("NAME");
1267       assert(MCNameRV && "multiclass record must have a NAME");
1268
1269       return UnOpInit::get(UnOpInit::CAST,
1270                            BinOpInit::get(BinOpInit::STRCONCAT,
1271                                           VarInit::get(MCNameRV->getName(),
1272                                                        MCNameRV->getType()),
1273                                           NewRec->getNameInit(),
1274                                           StringRecTy::get()),
1275                            Class->getDefInit()->getType());
1276     }
1277
1278     // The result of the expression is a reference to the new record.
1279     return DefInit::get(NewRec);
1280   }
1281   case tgtok::l_brace: {           // Value ::= '{' ValueList '}'
1282     SMLoc BraceLoc = Lex.getLoc();
1283     Lex.Lex(); // eat the '{'
1284     std::vector<Init*> Vals;
1285
1286     if (Lex.getCode() != tgtok::r_brace) {
1287       Vals = ParseValueList(CurRec);
1288       if (Vals.empty()) return nullptr;
1289     }
1290     if (Lex.getCode() != tgtok::r_brace) {
1291       TokError("expected '}' at end of bit list value");
1292       return nullptr;
1293     }
1294     Lex.Lex();  // eat the '}'
1295
1296     SmallVector<Init *, 16> NewBits(Vals.size());
1297
1298     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1299       Init *Bit = Vals[i]->convertInitializerTo(BitRecTy::get());
1300       if (!Bit) {
1301         Error(BraceLoc, "Element #" + utostr(i) + " (" + Vals[i]->getAsString()+
1302               ") is not convertable to a bit");
1303         return nullptr;
1304       }
1305       NewBits[Vals.size()-i-1] = Bit;
1306     }
1307     return BitsInit::get(NewBits);
1308   }
1309   case tgtok::l_square: {          // Value ::= '[' ValueList ']'
1310     Lex.Lex(); // eat the '['
1311     std::vector<Init*> Vals;
1312
1313     RecTy *DeducedEltTy = nullptr;
1314     ListRecTy *GivenListTy = nullptr;
1315
1316     if (ItemType) {
1317       ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1318       if (!ListType) {
1319         std::string s;
1320         raw_string_ostream ss(s);
1321         ss << "Type mismatch for list, expected list type, got "
1322            << ItemType->getAsString();
1323         TokError(ss.str());
1324         return nullptr;
1325       }
1326       GivenListTy = ListType;
1327     }
1328
1329     if (Lex.getCode() != tgtok::r_square) {
1330       Vals = ParseValueList(CurRec, nullptr,
1331                             GivenListTy ? GivenListTy->getElementType() : nullptr);
1332       if (Vals.empty()) return nullptr;
1333     }
1334     if (Lex.getCode() != tgtok::r_square) {
1335       TokError("expected ']' at end of list value");
1336       return nullptr;
1337     }
1338     Lex.Lex();  // eat the ']'
1339
1340     RecTy *GivenEltTy = nullptr;
1341     if (Lex.getCode() == tgtok::less) {
1342       // Optional list element type
1343       Lex.Lex();  // eat the '<'
1344
1345       GivenEltTy = ParseType();
1346       if (!GivenEltTy) {
1347         // Couldn't parse element type
1348         return nullptr;
1349       }
1350
1351       if (Lex.getCode() != tgtok::greater) {
1352         TokError("expected '>' at end of list element type");
1353         return nullptr;
1354       }
1355       Lex.Lex();  // eat the '>'
1356     }
1357
1358     // Check elements
1359     RecTy *EltTy = nullptr;
1360     for (std::vector<Init *>::iterator i = Vals.begin(), ie = Vals.end();
1361          i != ie;
1362          ++i) {
1363       TypedInit *TArg = dyn_cast<TypedInit>(*i);
1364       if (!TArg) {
1365         TokError("Untyped list element");
1366         return nullptr;
1367       }
1368       if (EltTy) {
1369         EltTy = resolveTypes(EltTy, TArg->getType());
1370         if (!EltTy) {
1371           TokError("Incompatible types in list elements");
1372           return nullptr;
1373         }
1374       } else {
1375         EltTy = TArg->getType();
1376       }
1377     }
1378
1379     if (GivenEltTy) {
1380       if (EltTy) {
1381         // Verify consistency
1382         if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1383           TokError("Incompatible types in list elements");
1384           return nullptr;
1385         }
1386       }
1387       EltTy = GivenEltTy;
1388     }
1389
1390     if (!EltTy) {
1391       if (!ItemType) {
1392         TokError("No type for list");
1393         return nullptr;
1394       }
1395       DeducedEltTy = GivenListTy->getElementType();
1396     } else {
1397       // Make sure the deduced type is compatible with the given type
1398       if (GivenListTy) {
1399         if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1400           TokError("Element type mismatch for list");
1401           return nullptr;
1402         }
1403       }
1404       DeducedEltTy = EltTy;
1405     }
1406
1407     return ListInit::get(Vals, DeducedEltTy);
1408   }
1409   case tgtok::l_paren: {         // Value ::= '(' IDValue DagArgList ')'
1410     Lex.Lex();   // eat the '('
1411     if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1412       TokError("expected identifier in dag init");
1413       return nullptr;
1414     }
1415
1416     Init *Operator = ParseValue(CurRec);
1417     if (!Operator) return nullptr;
1418
1419     // If the operator name is present, parse it.
1420     std::string OperatorName;
1421     if (Lex.getCode() == tgtok::colon) {
1422       if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1423         TokError("expected variable name in dag operator");
1424         return nullptr;
1425       }
1426       OperatorName = Lex.getCurStrVal();
1427       Lex.Lex();  // eat the VarName.
1428     }
1429
1430     std::vector<std::pair<llvm::Init*, std::string> > DagArgs;
1431     if (Lex.getCode() != tgtok::r_paren) {
1432       DagArgs = ParseDagArgList(CurRec);
1433       if (DagArgs.empty()) return nullptr;
1434     }
1435
1436     if (Lex.getCode() != tgtok::r_paren) {
1437       TokError("expected ')' in dag init");
1438       return nullptr;
1439     }
1440     Lex.Lex();  // eat the ')'
1441
1442     return DagInit::get(Operator, OperatorName, DagArgs);
1443   }
1444
1445   case tgtok::XHead:
1446   case tgtok::XTail:
1447   case tgtok::XEmpty:
1448   case tgtok::XCast:  // Value ::= !unop '(' Value ')'
1449   case tgtok::XConcat:
1450   case tgtok::XADD:
1451   case tgtok::XAND:
1452   case tgtok::XSRA:
1453   case tgtok::XSRL:
1454   case tgtok::XSHL:
1455   case tgtok::XEq:
1456   case tgtok::XListConcat:
1457   case tgtok::XStrConcat:   // Value ::= !binop '(' Value ',' Value ')'
1458   case tgtok::XIf:
1459   case tgtok::XForEach:
1460   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1461     return ParseOperation(CurRec, ItemType);
1462   }
1463   }
1464
1465   return R;
1466 }
1467
1468 /// ParseValue - Parse a tblgen value.  This returns null on error.
1469 ///
1470 ///   Value       ::= SimpleValue ValueSuffix*
1471 ///   ValueSuffix ::= '{' BitList '}'
1472 ///   ValueSuffix ::= '[' BitList ']'
1473 ///   ValueSuffix ::= '.' ID
1474 ///
1475 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
1476   Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
1477   if (!Result) return nullptr;
1478
1479   // Parse the suffixes now if present.
1480   while (1) {
1481     switch (Lex.getCode()) {
1482     default: return Result;
1483     case tgtok::l_brace: {
1484       if (Mode == ParseNameMode || Mode == ParseForeachMode)
1485         // This is the beginning of the object body.
1486         return Result;
1487
1488       SMLoc CurlyLoc = Lex.getLoc();
1489       Lex.Lex(); // eat the '{'
1490       std::vector<unsigned> Ranges = ParseRangeList();
1491       if (Ranges.empty()) return nullptr;
1492
1493       // Reverse the bitlist.
1494       std::reverse(Ranges.begin(), Ranges.end());
1495       Result = Result->convertInitializerBitRange(Ranges);
1496       if (!Result) {
1497         Error(CurlyLoc, "Invalid bit range for value");
1498         return nullptr;
1499       }
1500
1501       // Eat the '}'.
1502       if (Lex.getCode() != tgtok::r_brace) {
1503         TokError("expected '}' at end of bit range list");
1504         return nullptr;
1505       }
1506       Lex.Lex();
1507       break;
1508     }
1509     case tgtok::l_square: {
1510       SMLoc SquareLoc = Lex.getLoc();
1511       Lex.Lex(); // eat the '['
1512       std::vector<unsigned> Ranges = ParseRangeList();
1513       if (Ranges.empty()) return nullptr;
1514
1515       Result = Result->convertInitListSlice(Ranges);
1516       if (!Result) {
1517         Error(SquareLoc, "Invalid range for list slice");
1518         return nullptr;
1519       }
1520
1521       // Eat the ']'.
1522       if (Lex.getCode() != tgtok::r_square) {
1523         TokError("expected ']' at end of list slice");
1524         return nullptr;
1525       }
1526       Lex.Lex();
1527       break;
1528     }
1529     case tgtok::period:
1530       if (Lex.Lex() != tgtok::Id) {  // eat the .
1531         TokError("expected field identifier after '.'");
1532         return nullptr;
1533       }
1534       if (!Result->getFieldType(Lex.getCurStrVal())) {
1535         TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
1536                  Result->getAsString() + "'");
1537         return nullptr;
1538       }
1539       Result = FieldInit::get(Result, Lex.getCurStrVal());
1540       Lex.Lex();  // eat field name
1541       break;
1542
1543     case tgtok::paste:
1544       SMLoc PasteLoc = Lex.getLoc();
1545
1546       // Create a !strconcat() operation, first casting each operand to
1547       // a string if necessary.
1548
1549       TypedInit *LHS = dyn_cast<TypedInit>(Result);
1550       if (!LHS) {
1551         Error(PasteLoc, "LHS of paste is not typed!");
1552         return nullptr;
1553       }
1554   
1555       if (LHS->getType() != StringRecTy::get()) {
1556         LHS = UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get());
1557       }
1558
1559       TypedInit *RHS = nullptr;
1560
1561       Lex.Lex();  // Eat the '#'.
1562       switch (Lex.getCode()) { 
1563       case tgtok::colon:
1564       case tgtok::semi:
1565       case tgtok::l_brace:
1566         // These are all of the tokens that can begin an object body.
1567         // Some of these can also begin values but we disallow those cases
1568         // because they are unlikely to be useful.
1569        
1570         // Trailing paste, concat with an empty string.
1571         RHS = StringInit::get("");
1572         break;
1573
1574       default:
1575         Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
1576         RHS = dyn_cast<TypedInit>(RHSResult);
1577         if (!RHS) {
1578           Error(PasteLoc, "RHS of paste is not typed!");
1579           return nullptr;
1580         }
1581
1582         if (RHS->getType() != StringRecTy::get()) {
1583           RHS = UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get());
1584         }
1585   
1586         break;
1587       }
1588
1589       Result = BinOpInit::get(BinOpInit::STRCONCAT, LHS, RHS,
1590                               StringRecTy::get())->Fold(CurRec, CurMultiClass);
1591       break;
1592     }
1593   }
1594 }
1595
1596 /// ParseDagArgList - Parse the argument list for a dag literal expression.
1597 ///
1598 ///    DagArg     ::= Value (':' VARNAME)?
1599 ///    DagArg     ::= VARNAME
1600 ///    DagArgList ::= DagArg
1601 ///    DagArgList ::= DagArgList ',' DagArg
1602 std::vector<std::pair<llvm::Init*, std::string> >
1603 TGParser::ParseDagArgList(Record *CurRec) {
1604   std::vector<std::pair<llvm::Init*, std::string> > Result;
1605
1606   while (1) {
1607     // DagArg ::= VARNAME
1608     if (Lex.getCode() == tgtok::VarName) {
1609       // A missing value is treated like '?'.
1610       Result.push_back(std::make_pair(UnsetInit::get(), Lex.getCurStrVal()));
1611       Lex.Lex();
1612     } else {
1613       // DagArg ::= Value (':' VARNAME)?
1614       Init *Val = ParseValue(CurRec);
1615       if (!Val)
1616         return std::vector<std::pair<llvm::Init*, std::string> >();
1617
1618       // If the variable name is present, add it.
1619       std::string VarName;
1620       if (Lex.getCode() == tgtok::colon) {
1621         if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1622           TokError("expected variable name in dag literal");
1623           return std::vector<std::pair<llvm::Init*, std::string> >();
1624         }
1625         VarName = Lex.getCurStrVal();
1626         Lex.Lex();  // eat the VarName.
1627       }
1628
1629       Result.push_back(std::make_pair(Val, VarName));
1630     }
1631     if (Lex.getCode() != tgtok::comma) break;
1632     Lex.Lex(); // eat the ','
1633   }
1634
1635   return Result;
1636 }
1637
1638
1639 /// ParseValueList - Parse a comma separated list of values, returning them as a
1640 /// vector.  Note that this always expects to be able to parse at least one
1641 /// value.  It returns an empty list if this is not possible.
1642 ///
1643 ///   ValueList ::= Value (',' Value)
1644 ///
1645 std::vector<Init*> TGParser::ParseValueList(Record *CurRec, Record *ArgsRec,
1646                                             RecTy *EltTy) {
1647   std::vector<Init*> Result;
1648   RecTy *ItemType = EltTy;
1649   unsigned int ArgN = 0;
1650   if (ArgsRec && !EltTy) {
1651     const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1652     if (!TArgs.size()) {
1653       TokError("template argument provided to non-template class");
1654       return std::vector<Init*>();
1655     }
1656     const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1657     if (!RV) {
1658       errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
1659         << ")\n";
1660     }
1661     assert(RV && "Template argument record not found??");
1662     ItemType = RV->getType();
1663     ++ArgN;
1664   }
1665   Result.push_back(ParseValue(CurRec, ItemType));
1666   if (!Result.back()) return std::vector<Init*>();
1667
1668   while (Lex.getCode() == tgtok::comma) {
1669     Lex.Lex();  // Eat the comma
1670
1671     if (ArgsRec && !EltTy) {
1672       const std::vector<Init *> &TArgs = ArgsRec->getTemplateArgs();
1673       if (ArgN >= TArgs.size()) {
1674         TokError("too many template arguments");
1675         return std::vector<Init*>();
1676       }
1677       const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
1678       assert(RV && "Template argument record not found??");
1679       ItemType = RV->getType();
1680       ++ArgN;
1681     }
1682     Result.push_back(ParseValue(CurRec, ItemType));
1683     if (!Result.back()) return std::vector<Init*>();
1684   }
1685
1686   return Result;
1687 }
1688
1689
1690 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
1691 /// empty string on error.  This can happen in a number of different context's,
1692 /// including within a def or in the template args for a def (which which case
1693 /// CurRec will be non-null) and within the template args for a multiclass (in
1694 /// which case CurRec will be null, but CurMultiClass will be set).  This can
1695 /// also happen within a def that is within a multiclass, which will set both
1696 /// CurRec and CurMultiClass.
1697 ///
1698 ///  Declaration ::= FIELD? Type ID ('=' Value)?
1699 ///
1700 Init *TGParser::ParseDeclaration(Record *CurRec,
1701                                        bool ParsingTemplateArgs) {
1702   // Read the field prefix if present.
1703   bool HasField = Lex.getCode() == tgtok::Field;
1704   if (HasField) Lex.Lex();
1705
1706   RecTy *Type = ParseType();
1707   if (!Type) return nullptr;
1708
1709   if (Lex.getCode() != tgtok::Id) {
1710     TokError("Expected identifier in declaration");
1711     return nullptr;
1712   }
1713
1714   SMLoc IdLoc = Lex.getLoc();
1715   Init *DeclName = StringInit::get(Lex.getCurStrVal());
1716   Lex.Lex();
1717
1718   if (ParsingTemplateArgs) {
1719     if (CurRec) {
1720       DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
1721     } else {
1722       assert(CurMultiClass);
1723     }
1724     if (CurMultiClass)
1725       DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
1726                              "::");
1727   }
1728
1729   // Add the value.
1730   if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
1731     return nullptr;
1732
1733   // If a value is present, parse it.
1734   if (Lex.getCode() == tgtok::equal) {
1735     Lex.Lex();
1736     SMLoc ValLoc = Lex.getLoc();
1737     Init *Val = ParseValue(CurRec, Type);
1738     if (!Val ||
1739         SetValue(CurRec, ValLoc, DeclName, std::vector<unsigned>(), Val))
1740       // Return the name, even if an error is thrown.  This is so that we can
1741       // continue to make some progress, even without the value having been
1742       // initialized.
1743       return DeclName;
1744   }
1745
1746   return DeclName;
1747 }
1748
1749 /// ParseForeachDeclaration - Read a foreach declaration, returning
1750 /// the name of the declared object or a NULL Init on error.  Return
1751 /// the name of the parsed initializer list through ForeachListName.
1752 ///
1753 ///  ForeachDeclaration ::= ID '=' '[' ValueList ']'
1754 ///  ForeachDeclaration ::= ID '=' '{' RangeList '}'
1755 ///  ForeachDeclaration ::= ID '=' RangePiece
1756 ///
1757 VarInit *TGParser::ParseForeachDeclaration(ListInit *&ForeachListValue) {
1758   if (Lex.getCode() != tgtok::Id) {
1759     TokError("Expected identifier in foreach declaration");
1760     return nullptr;
1761   }
1762
1763   Init *DeclName = StringInit::get(Lex.getCurStrVal());
1764   Lex.Lex();
1765
1766   // If a value is present, parse it.
1767   if (Lex.getCode() != tgtok::equal) {
1768     TokError("Expected '=' in foreach declaration");
1769     return nullptr;
1770   }
1771   Lex.Lex();  // Eat the '='
1772
1773   RecTy *IterType = nullptr;
1774   std::vector<unsigned> Ranges;
1775
1776   switch (Lex.getCode()) {
1777   default: TokError("Unknown token when expecting a range list"); return nullptr;
1778   case tgtok::l_square: { // '[' ValueList ']'
1779     Init *List = ParseSimpleValue(nullptr, nullptr, ParseForeachMode);
1780     ForeachListValue = dyn_cast<ListInit>(List);
1781     if (!ForeachListValue) {
1782       TokError("Expected a Value list");
1783       return nullptr;
1784     }
1785     RecTy *ValueType = ForeachListValue->getType();
1786     ListRecTy *ListType = dyn_cast<ListRecTy>(ValueType);
1787     if (!ListType) {
1788       TokError("Value list is not of list type");
1789       return nullptr;
1790     }
1791     IterType = ListType->getElementType();
1792     break;
1793   }
1794
1795   case tgtok::IntVal: { // RangePiece.
1796     if (ParseRangePiece(Ranges))
1797       return nullptr;
1798     break;
1799   }
1800
1801   case tgtok::l_brace: { // '{' RangeList '}'
1802     Lex.Lex(); // eat the '{'
1803     Ranges = ParseRangeList();
1804     if (Lex.getCode() != tgtok::r_brace) {
1805       TokError("expected '}' at end of bit range list");
1806       return nullptr;
1807     }
1808     Lex.Lex();
1809     break;
1810   }
1811   }
1812
1813   if (!Ranges.empty()) {
1814     assert(!IterType && "Type already initialized?");
1815     IterType = IntRecTy::get();
1816     std::vector<Init*> Values;
1817     for (unsigned i = 0, e = Ranges.size(); i != e; ++i)
1818       Values.push_back(IntInit::get(Ranges[i]));
1819     ForeachListValue = ListInit::get(Values, IterType);
1820   }
1821
1822   if (!IterType)
1823     return nullptr;
1824
1825   return VarInit::get(DeclName, IterType);
1826 }
1827
1828 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
1829 /// sequence of template-declarations in <>'s.  If CurRec is non-null, these are
1830 /// template args for a def, which may or may not be in a multiclass.  If null,
1831 /// these are the template args for a multiclass.
1832 ///
1833 ///    TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
1834 ///
1835 bool TGParser::ParseTemplateArgList(Record *CurRec) {
1836   assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
1837   Lex.Lex(); // eat the '<'
1838
1839   Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
1840
1841   // Read the first declaration.
1842   Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1843   if (!TemplArg)
1844     return true;
1845
1846   TheRecToAddTo->addTemplateArg(TemplArg);
1847
1848   while (Lex.getCode() == tgtok::comma) {
1849     Lex.Lex(); // eat the ','
1850
1851     // Read the following declarations.
1852     TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
1853     if (!TemplArg)
1854       return true;
1855     TheRecToAddTo->addTemplateArg(TemplArg);
1856   }
1857
1858   if (Lex.getCode() != tgtok::greater)
1859     return TokError("expected '>' at end of template argument list");
1860   Lex.Lex(); // eat the '>'.
1861   return false;
1862 }
1863
1864
1865 /// ParseBodyItem - Parse a single item at within the body of a def or class.
1866 ///
1867 ///   BodyItem ::= Declaration ';'
1868 ///   BodyItem ::= LET ID OptionalBitList '=' Value ';'
1869 bool TGParser::ParseBodyItem(Record *CurRec) {
1870   if (Lex.getCode() != tgtok::Let) {
1871     if (!ParseDeclaration(CurRec, false))
1872       return true;
1873
1874     if (Lex.getCode() != tgtok::semi)
1875       return TokError("expected ';' after declaration");
1876     Lex.Lex();
1877     return false;
1878   }
1879
1880   // LET ID OptionalRangeList '=' Value ';'
1881   if (Lex.Lex() != tgtok::Id)
1882     return TokError("expected field identifier after let");
1883
1884   SMLoc IdLoc = Lex.getLoc();
1885   std::string FieldName = Lex.getCurStrVal();
1886   Lex.Lex();  // eat the field name.
1887
1888   std::vector<unsigned> BitList;
1889   if (ParseOptionalBitList(BitList))
1890     return true;
1891   std::reverse(BitList.begin(), BitList.end());
1892
1893   if (Lex.getCode() != tgtok::equal)
1894     return TokError("expected '=' in let expression");
1895   Lex.Lex();  // eat the '='.
1896
1897   RecordVal *Field = CurRec->getValue(FieldName);
1898   if (!Field)
1899     return TokError("Value '" + FieldName + "' unknown!");
1900
1901   RecTy *Type = Field->getType();
1902
1903   Init *Val = ParseValue(CurRec, Type);
1904   if (!Val) return true;
1905
1906   if (Lex.getCode() != tgtok::semi)
1907     return TokError("expected ';' after let expression");
1908   Lex.Lex();
1909
1910   return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
1911 }
1912
1913 /// ParseBody - Read the body of a class or def.  Return true on error, false on
1914 /// success.
1915 ///
1916 ///   Body     ::= ';'
1917 ///   Body     ::= '{' BodyList '}'
1918 ///   BodyList BodyItem*
1919 ///
1920 bool TGParser::ParseBody(Record *CurRec) {
1921   // If this is a null definition, just eat the semi and return.
1922   if (Lex.getCode() == tgtok::semi) {
1923     Lex.Lex();
1924     return false;
1925   }
1926
1927   if (Lex.getCode() != tgtok::l_brace)
1928     return TokError("Expected ';' or '{' to start body");
1929   // Eat the '{'.
1930   Lex.Lex();
1931
1932   while (Lex.getCode() != tgtok::r_brace)
1933     if (ParseBodyItem(CurRec))
1934       return true;
1935
1936   // Eat the '}'.
1937   Lex.Lex();
1938   return false;
1939 }
1940
1941 /// \brief Apply the current let bindings to \a CurRec.
1942 /// \returns true on error, false otherwise.
1943 bool TGParser::ApplyLetStack(Record *CurRec) {
1944   for (unsigned i = 0, e = LetStack.size(); i != e; ++i)
1945     for (unsigned j = 0, e = LetStack[i].size(); j != e; ++j)
1946       if (SetValue(CurRec, LetStack[i][j].Loc, LetStack[i][j].Name,
1947                    LetStack[i][j].Bits, LetStack[i][j].Value))
1948         return true;
1949   return false;
1950 }
1951
1952 /// ParseObjectBody - Parse the body of a def or class.  This consists of an
1953 /// optional ClassList followed by a Body.  CurRec is the current def or class
1954 /// that is being parsed.
1955 ///
1956 ///   ObjectBody      ::= BaseClassList Body
1957 ///   BaseClassList   ::= /*empty*/
1958 ///   BaseClassList   ::= ':' BaseClassListNE
1959 ///   BaseClassListNE ::= SubClassRef (',' SubClassRef)*
1960 ///
1961 bool TGParser::ParseObjectBody(Record *CurRec) {
1962   // If there is a baseclass list, read it.
1963   if (Lex.getCode() == tgtok::colon) {
1964     Lex.Lex();
1965
1966     // Read all of the subclasses.
1967     SubClassReference SubClass = ParseSubClassReference(CurRec, false);
1968     while (1) {
1969       // Check for error.
1970       if (!SubClass.Rec) return true;
1971
1972       // Add it.
1973       if (AddSubClass(CurRec, SubClass))
1974         return true;
1975
1976       if (Lex.getCode() != tgtok::comma) break;
1977       Lex.Lex(); // eat ','.
1978       SubClass = ParseSubClassReference(CurRec, false);
1979     }
1980   }
1981
1982   if (ApplyLetStack(CurRec))
1983     return true;
1984
1985   return ParseBody(CurRec);
1986 }
1987
1988 /// ParseDef - Parse and return a top level or multiclass def, return the record
1989 /// corresponding to it.  This returns null on error.
1990 ///
1991 ///   DefInst ::= DEF ObjectName ObjectBody
1992 ///
1993 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
1994   SMLoc DefLoc = Lex.getLoc();
1995   assert(Lex.getCode() == tgtok::Def && "Unknown tok");
1996   Lex.Lex();  // Eat the 'def' token.
1997
1998   // Parse ObjectName and make a record for it.
1999   Record *CurRec;
2000   Init *Name = ParseObjectName(CurMultiClass);
2001   if (Name)
2002     CurRec = new Record(Name, DefLoc, Records);
2003   else
2004     CurRec = new Record(GetNewAnonymousName(), DefLoc, Records,
2005                         /*IsAnonymous=*/true);
2006
2007   if (!CurMultiClass && Loops.empty()) {
2008     // Top-level def definition.
2009
2010     // Ensure redefinition doesn't happen.
2011     if (Records.getDef(CurRec->getNameInitAsString())) {
2012       Error(DefLoc, "def '" + CurRec->getNameInitAsString()
2013             + "' already defined");
2014       return true;
2015     }
2016     Records.addDef(CurRec);
2017
2018     if (ParseObjectBody(CurRec))
2019       return true;
2020   } else if (CurMultiClass) {
2021     // Parse the body before adding this prototype to the DefPrototypes vector.
2022     // That way implicit definitions will be added to the DefPrototypes vector
2023     // before this object, instantiated prior to defs derived from this object,
2024     // and this available for indirect name resolution when defs derived from
2025     // this object are instantiated.
2026     if (ParseObjectBody(CurRec))
2027       return true;
2028
2029     // Otherwise, a def inside a multiclass, add it to the multiclass.
2030     for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size(); i != e; ++i)
2031       if (CurMultiClass->DefPrototypes[i]->getNameInit()
2032           == CurRec->getNameInit()) {
2033         Error(DefLoc, "def '" + CurRec->getNameInitAsString() +
2034               "' already defined in this multiclass!");
2035         return true;
2036       }
2037     CurMultiClass->DefPrototypes.push_back(CurRec);
2038   } else if (ParseObjectBody(CurRec))
2039     return true;
2040
2041   if (!CurMultiClass)  // Def's in multiclasses aren't really defs.
2042     // See Record::setName().  This resolve step will see any new name
2043     // for the def that might have been created when resolving
2044     // inheritance, values and arguments above.
2045     CurRec->resolveReferences();
2046
2047   // If ObjectBody has template arguments, it's an error.
2048   assert(CurRec->getTemplateArgs().empty() && "How'd this get template args?");
2049
2050   if (CurMultiClass) {
2051     // Copy the template arguments for the multiclass into the def.
2052     const std::vector<Init *> &TArgs =
2053                                 CurMultiClass->Rec.getTemplateArgs();
2054
2055     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2056       const RecordVal *RV = CurMultiClass->Rec.getValue(TArgs[i]);
2057       assert(RV && "Template arg doesn't exist?");
2058       CurRec->addValue(*RV);
2059     }
2060   }
2061
2062   if (ProcessForeachDefs(CurRec, DefLoc)) {
2063     Error(DefLoc,
2064           "Could not process loops for def" + CurRec->getNameInitAsString());
2065     return true;
2066   }
2067
2068   return false;
2069 }
2070
2071 /// ParseForeach - Parse a for statement.  Return the record corresponding
2072 /// to it.  This returns true on error.
2073 ///
2074 ///   Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2075 ///   Foreach ::= FOREACH Declaration IN Object
2076 ///
2077 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2078   assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2079   Lex.Lex();  // Eat the 'for' token.
2080
2081   // Make a temporary object to record items associated with the for
2082   // loop.
2083   ListInit *ListValue = nullptr;
2084   VarInit *IterName = ParseForeachDeclaration(ListValue);
2085   if (!IterName)
2086     return TokError("expected declaration in for");
2087
2088   if (Lex.getCode() != tgtok::In)
2089     return TokError("Unknown tok");
2090   Lex.Lex();  // Eat the in
2091
2092   // Create a loop object and remember it.
2093   Loops.push_back(ForeachLoop(IterName, ListValue));
2094
2095   if (Lex.getCode() != tgtok::l_brace) {
2096     // FOREACH Declaration IN Object
2097     if (ParseObject(CurMultiClass))
2098       return true;
2099   }
2100   else {
2101     SMLoc BraceLoc = Lex.getLoc();
2102     // Otherwise, this is a group foreach.
2103     Lex.Lex();  // eat the '{'.
2104
2105     // Parse the object list.
2106     if (ParseObjectList(CurMultiClass))
2107       return true;
2108
2109     if (Lex.getCode() != tgtok::r_brace) {
2110       TokError("expected '}' at end of foreach command");
2111       return Error(BraceLoc, "to match this '{'");
2112     }
2113     Lex.Lex();  // Eat the }
2114   }
2115
2116   // We've processed everything in this loop.
2117   Loops.pop_back();
2118
2119   return false;
2120 }
2121
2122 /// ParseClass - Parse a tblgen class definition.
2123 ///
2124 ///   ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2125 ///
2126 bool TGParser::ParseClass() {
2127   assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2128   Lex.Lex();
2129
2130   if (Lex.getCode() != tgtok::Id)
2131     return TokError("expected class name after 'class' keyword");
2132
2133   Record *CurRec = Records.getClass(Lex.getCurStrVal());
2134   if (CurRec) {
2135     // If the body was previously defined, this is an error.
2136     if (CurRec->getValues().size() > 1 ||  // Account for NAME.
2137         !CurRec->getSuperClasses().empty() ||
2138         !CurRec->getTemplateArgs().empty())
2139       return TokError("Class '" + CurRec->getNameInitAsString()
2140                       + "' already defined");
2141   } else {
2142     // If this is the first reference to this class, create and add it.
2143     CurRec = new Record(Lex.getCurStrVal(), Lex.getLoc(), Records);
2144     Records.addClass(CurRec);
2145   }
2146   Lex.Lex(); // eat the name.
2147
2148   // If there are template args, parse them.
2149   if (Lex.getCode() == tgtok::less)
2150     if (ParseTemplateArgList(CurRec))
2151       return true;
2152
2153   // Finally, parse the object body.
2154   return ParseObjectBody(CurRec);
2155 }
2156
2157 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2158 /// of LetRecords.
2159 ///
2160 ///   LetList ::= LetItem (',' LetItem)*
2161 ///   LetItem ::= ID OptionalRangeList '=' Value
2162 ///
2163 std::vector<LetRecord> TGParser::ParseLetList() {
2164   std::vector<LetRecord> Result;
2165
2166   while (1) {
2167     if (Lex.getCode() != tgtok::Id) {
2168       TokError("expected identifier in let definition");
2169       return std::vector<LetRecord>();
2170     }
2171     std::string Name = Lex.getCurStrVal();
2172     SMLoc NameLoc = Lex.getLoc();
2173     Lex.Lex();  // Eat the identifier.
2174
2175     // Check for an optional RangeList.
2176     std::vector<unsigned> Bits;
2177     if (ParseOptionalRangeList(Bits))
2178       return std::vector<LetRecord>();
2179     std::reverse(Bits.begin(), Bits.end());
2180
2181     if (Lex.getCode() != tgtok::equal) {
2182       TokError("expected '=' in let expression");
2183       return std::vector<LetRecord>();
2184     }
2185     Lex.Lex();  // eat the '='.
2186
2187     Init *Val = ParseValue(nullptr);
2188     if (!Val) return std::vector<LetRecord>();
2189
2190     // Now that we have everything, add the record.
2191     Result.push_back(LetRecord(Name, Bits, Val, NameLoc));
2192
2193     if (Lex.getCode() != tgtok::comma)
2194       return Result;
2195     Lex.Lex();  // eat the comma.
2196   }
2197 }
2198
2199 /// ParseTopLevelLet - Parse a 'let' at top level.  This can be a couple of
2200 /// different related productions. This works inside multiclasses too.
2201 ///
2202 ///   Object ::= LET LetList IN '{' ObjectList '}'
2203 ///   Object ::= LET LetList IN Object
2204 ///
2205 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2206   assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2207   Lex.Lex();
2208
2209   // Add this entry to the let stack.
2210   std::vector<LetRecord> LetInfo = ParseLetList();
2211   if (LetInfo.empty()) return true;
2212   LetStack.push_back(LetInfo);
2213
2214   if (Lex.getCode() != tgtok::In)
2215     return TokError("expected 'in' at end of top-level 'let'");
2216   Lex.Lex();
2217
2218   // If this is a scalar let, just handle it now
2219   if (Lex.getCode() != tgtok::l_brace) {
2220     // LET LetList IN Object
2221     if (ParseObject(CurMultiClass))
2222       return true;
2223   } else {   // Object ::= LETCommand '{' ObjectList '}'
2224     SMLoc BraceLoc = Lex.getLoc();
2225     // Otherwise, this is a group let.
2226     Lex.Lex();  // eat the '{'.
2227
2228     // Parse the object list.
2229     if (ParseObjectList(CurMultiClass))
2230       return true;
2231
2232     if (Lex.getCode() != tgtok::r_brace) {
2233       TokError("expected '}' at end of top level let command");
2234       return Error(BraceLoc, "to match this '{'");
2235     }
2236     Lex.Lex();
2237   }
2238
2239   // Outside this let scope, this let block is not active.
2240   LetStack.pop_back();
2241   return false;
2242 }
2243
2244 /// ParseMultiClass - Parse a multiclass definition.
2245 ///
2246 ///  MultiClassInst ::= MULTICLASS ID TemplateArgList?
2247 ///                     ':' BaseMultiClassList '{' MultiClassObject+ '}'
2248 ///  MultiClassObject ::= DefInst
2249 ///  MultiClassObject ::= MultiClassInst
2250 ///  MultiClassObject ::= DefMInst
2251 ///  MultiClassObject ::= LETCommand '{' ObjectList '}'
2252 ///  MultiClassObject ::= LETCommand Object
2253 ///
2254 bool TGParser::ParseMultiClass() {
2255   assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2256   Lex.Lex();  // Eat the multiclass token.
2257
2258   if (Lex.getCode() != tgtok::Id)
2259     return TokError("expected identifier after multiclass for name");
2260   std::string Name = Lex.getCurStrVal();
2261
2262   if (MultiClasses.count(Name))
2263     return TokError("multiclass '" + Name + "' already defined");
2264
2265   CurMultiClass = MultiClasses[Name] = new MultiClass(Name, 
2266                                                       Lex.getLoc(), Records);
2267   Lex.Lex();  // Eat the identifier.
2268
2269   // If there are template args, parse them.
2270   if (Lex.getCode() == tgtok::less)
2271     if (ParseTemplateArgList(nullptr))
2272       return true;
2273
2274   bool inherits = false;
2275
2276   // If there are submulticlasses, parse them.
2277   if (Lex.getCode() == tgtok::colon) {
2278     inherits = true;
2279
2280     Lex.Lex();
2281
2282     // Read all of the submulticlasses.
2283     SubMultiClassReference SubMultiClass =
2284       ParseSubMultiClassReference(CurMultiClass);
2285     while (1) {
2286       // Check for error.
2287       if (!SubMultiClass.MC) return true;
2288
2289       // Add it.
2290       if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2291         return true;
2292
2293       if (Lex.getCode() != tgtok::comma) break;
2294       Lex.Lex(); // eat ','.
2295       SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2296     }
2297   }
2298
2299   if (Lex.getCode() != tgtok::l_brace) {
2300     if (!inherits)
2301       return TokError("expected '{' in multiclass definition");
2302     else if (Lex.getCode() != tgtok::semi)
2303       return TokError("expected ';' in multiclass definition");
2304     else
2305       Lex.Lex();  // eat the ';'.
2306   } else {
2307     if (Lex.Lex() == tgtok::r_brace)  // eat the '{'.
2308       return TokError("multiclass must contain at least one def");
2309
2310     while (Lex.getCode() != tgtok::r_brace) {
2311       switch (Lex.getCode()) {
2312         default:
2313           return TokError("expected 'let', 'def' or 'defm' in multiclass body");
2314         case tgtok::Let:
2315         case tgtok::Def:
2316         case tgtok::Defm:
2317         case tgtok::Foreach:
2318           if (ParseObject(CurMultiClass))
2319             return true;
2320          break;
2321       }
2322     }
2323     Lex.Lex();  // eat the '}'.
2324   }
2325
2326   CurMultiClass = nullptr;
2327   return false;
2328 }
2329
2330 Record *TGParser::
2331 InstantiateMulticlassDef(MultiClass &MC,
2332                          Record *DefProto,
2333                          Init *&DefmPrefix,
2334                          SMRange DefmPrefixRange) {
2335   // We need to preserve DefProto so it can be reused for later
2336   // instantiations, so create a new Record to inherit from it.
2337
2338   // Add in the defm name.  If the defm prefix is empty, give each
2339   // instantiated def a unique name.  Otherwise, if "#NAME#" exists in the
2340   // name, substitute the prefix for #NAME#.  Otherwise, use the defm name
2341   // as a prefix.
2342
2343   bool IsAnonymous = false;
2344   if (!DefmPrefix) {
2345     DefmPrefix = StringInit::get(GetNewAnonymousName());
2346     IsAnonymous = true;
2347   }
2348
2349   Init *DefName = DefProto->getNameInit();
2350
2351   StringInit *DefNameString = dyn_cast<StringInit>(DefName);
2352
2353   if (DefNameString) {
2354     // We have a fully expanded string so there are no operators to
2355     // resolve.  We should concatenate the given prefix and name.
2356     DefName =
2357       BinOpInit::get(BinOpInit::STRCONCAT,
2358                      UnOpInit::get(UnOpInit::CAST, DefmPrefix,
2359                                    StringRecTy::get())->Fold(DefProto, &MC),
2360                      DefName, StringRecTy::get())->Fold(DefProto, &MC);
2361   }
2362
2363   // Make a trail of SMLocs from the multiclass instantiations.
2364   SmallVector<SMLoc, 4> Locs(1, DefmPrefixRange.Start);
2365   Locs.append(DefProto->getLoc().begin(), DefProto->getLoc().end());
2366   Record *CurRec = new Record(DefName, Locs, Records, IsAnonymous);
2367
2368   SubClassReference Ref;
2369   Ref.RefRange = DefmPrefixRange;
2370   Ref.Rec = DefProto;
2371   AddSubClass(CurRec, Ref);
2372
2373   // Set the value for NAME. We don't resolve references to it 'til later,
2374   // though, so that uses in nested multiclass names don't get
2375   // confused.
2376   if (SetValue(CurRec, Ref.RefRange.Start, "NAME", std::vector<unsigned>(),
2377                DefmPrefix)) {
2378     Error(DefmPrefixRange.Start, "Could not resolve "
2379           + CurRec->getNameInitAsString() + ":NAME to '"
2380           + DefmPrefix->getAsUnquotedString() + "'");
2381     return nullptr;
2382   }
2383
2384   // If the DefNameString didn't resolve, we probably have a reference to
2385   // NAME and need to replace it. We need to do at least this much greedily,
2386   // otherwise nested multiclasses will end up with incorrect NAME expansions.
2387   if (!DefNameString) {
2388     RecordVal *DefNameRV = CurRec->getValue("NAME");
2389     CurRec->resolveReferencesTo(DefNameRV);
2390   }
2391
2392   if (!CurMultiClass) {
2393     // Now that we're at the top level, resolve all NAME references
2394     // in the resultant defs that weren't in the def names themselves.
2395     RecordVal *DefNameRV = CurRec->getValue("NAME");
2396     CurRec->resolveReferencesTo(DefNameRV);
2397
2398     // Now that NAME references are resolved and we're at the top level of
2399     // any multiclass expansions, add the record to the RecordKeeper. If we are
2400     // currently in a multiclass, it means this defm appears inside a
2401     // multiclass and its name won't be fully resolvable until we see
2402     // the top-level defm.  Therefore, we don't add this to the
2403     // RecordKeeper at this point.  If we did we could get duplicate
2404     // defs as more than one probably refers to NAME or some other
2405     // common internal placeholder.
2406
2407     // Ensure redefinition doesn't happen.
2408     if (Records.getDef(CurRec->getNameInitAsString())) {
2409       Error(DefmPrefixRange.Start, "def '" + CurRec->getNameInitAsString() +
2410             "' already defined, instantiating defm with subdef '" + 
2411             DefProto->getNameInitAsString() + "'");
2412       return nullptr;
2413     }
2414
2415     Records.addDef(CurRec);
2416   }
2417
2418   return CurRec;
2419 }
2420
2421 bool TGParser::ResolveMulticlassDefArgs(MultiClass &MC,
2422                                         Record *CurRec,
2423                                         SMLoc DefmPrefixLoc,
2424                                         SMLoc SubClassLoc,
2425                                         const std::vector<Init *> &TArgs,
2426                                         std::vector<Init *> &TemplateVals,
2427                                         bool DeleteArgs) {
2428   // Loop over all of the template arguments, setting them to the specified
2429   // value or leaving them as the default if necessary.
2430   for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
2431     // Check if a value is specified for this temp-arg.
2432     if (i < TemplateVals.size()) {
2433       // Set it now.
2434       if (SetValue(CurRec, DefmPrefixLoc, TArgs[i], std::vector<unsigned>(),
2435                    TemplateVals[i]))
2436         return true;
2437         
2438       // Resolve it next.
2439       CurRec->resolveReferencesTo(CurRec->getValue(TArgs[i]));
2440
2441       if (DeleteArgs)
2442         // Now remove it.
2443         CurRec->removeValue(TArgs[i]);
2444         
2445     } else if (!CurRec->getValue(TArgs[i])->getValue()->isComplete()) {
2446       return Error(SubClassLoc, "value not specified for template argument #"+
2447                    utostr(i) + " (" + TArgs[i]->getAsUnquotedString()
2448                    + ") of multiclassclass '" + MC.Rec.getNameInitAsString()
2449                    + "'");
2450     }
2451   }
2452   return false;
2453 }
2454
2455 bool TGParser::ResolveMulticlassDef(MultiClass &MC,
2456                                     Record *CurRec,
2457                                     Record *DefProto,
2458                                     SMLoc DefmPrefixLoc) {
2459   // If the mdef is inside a 'let' expression, add to each def.
2460   if (ApplyLetStack(CurRec))
2461     return Error(DefmPrefixLoc, "when instantiating this defm");
2462
2463   // Don't create a top level definition for defm inside multiclasses,
2464   // instead, only update the prototypes and bind the template args
2465   // with the new created definition.
2466   if (!CurMultiClass)
2467     return false;
2468   for (unsigned i = 0, e = CurMultiClass->DefPrototypes.size();
2469        i != e; ++i)
2470     if (CurMultiClass->DefPrototypes[i]->getNameInit()
2471         == CurRec->getNameInit())
2472       return Error(DefmPrefixLoc, "defm '" + CurRec->getNameInitAsString() +
2473                    "' already defined in this multiclass!");
2474   CurMultiClass->DefPrototypes.push_back(CurRec);
2475
2476   // Copy the template arguments for the multiclass into the new def.
2477   const std::vector<Init *> &TA =
2478     CurMultiClass->Rec.getTemplateArgs();
2479
2480   for (unsigned i = 0, e = TA.size(); i != e; ++i) {
2481     const RecordVal *RV = CurMultiClass->Rec.getValue(TA[i]);
2482     assert(RV && "Template arg doesn't exist?");
2483     CurRec->addValue(*RV);
2484   }
2485
2486   return false;
2487 }
2488
2489 /// ParseDefm - Parse the instantiation of a multiclass.
2490 ///
2491 ///   DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2492 ///
2493 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2494   assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2495   SMLoc DefmLoc = Lex.getLoc();
2496   Init *DefmPrefix = nullptr;
2497
2498   if (Lex.Lex() == tgtok::Id) {  // eat the defm.
2499     DefmPrefix = ParseObjectName(CurMultiClass);
2500   }
2501
2502   SMLoc DefmPrefixEndLoc = Lex.getLoc();
2503   if (Lex.getCode() != tgtok::colon)
2504     return TokError("expected ':' after defm identifier");
2505
2506   // Keep track of the new generated record definitions.
2507   std::vector<Record*> NewRecDefs;
2508
2509   // This record also inherits from a regular class (non-multiclass)?
2510   bool InheritFromClass = false;
2511
2512   // eat the colon.
2513   Lex.Lex();
2514
2515   SMLoc SubClassLoc = Lex.getLoc();
2516   SubClassReference Ref = ParseSubClassReference(nullptr, true);
2517
2518   while (1) {
2519     if (!Ref.Rec) return true;
2520
2521     // To instantiate a multiclass, we need to first get the multiclass, then
2522     // instantiate each def contained in the multiclass with the SubClassRef
2523     // template parameters.
2524     MultiClass *MC = MultiClasses[Ref.Rec->getName()];
2525     assert(MC && "Didn't lookup multiclass correctly?");
2526     std::vector<Init*> &TemplateVals = Ref.TemplateArgs;
2527
2528     // Verify that the correct number of template arguments were specified.
2529     const std::vector<Init *> &TArgs = MC->Rec.getTemplateArgs();
2530     if (TArgs.size() < TemplateVals.size())
2531       return Error(SubClassLoc,
2532                    "more template args specified than multiclass expects");
2533
2534     // Loop over all the def's in the multiclass, instantiating each one.
2535     for (unsigned i = 0, e = MC->DefPrototypes.size(); i != e; ++i) {
2536       Record *DefProto = MC->DefPrototypes[i];
2537
2538       Record *CurRec = InstantiateMulticlassDef(*MC, DefProto, DefmPrefix,
2539                                                 SMRange(DefmLoc,
2540                                                         DefmPrefixEndLoc));
2541       if (!CurRec)
2542         return true;
2543
2544       if (ResolveMulticlassDefArgs(*MC, CurRec, DefmLoc, SubClassLoc,
2545                                    TArgs, TemplateVals, true/*Delete args*/))
2546         return Error(SubClassLoc, "could not instantiate def");
2547
2548       if (ResolveMulticlassDef(*MC, CurRec, DefProto, DefmLoc))
2549         return Error(SubClassLoc, "could not instantiate def");
2550
2551       NewRecDefs.push_back(CurRec);
2552     }
2553
2554
2555     if (Lex.getCode() != tgtok::comma) break;
2556     Lex.Lex(); // eat ','.
2557
2558     if (Lex.getCode() != tgtok::Id)
2559       return TokError("expected identifier");
2560
2561     SubClassLoc = Lex.getLoc();
2562
2563     // A defm can inherit from regular classes (non-multiclass) as
2564     // long as they come in the end of the inheritance list.
2565     InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
2566
2567     if (InheritFromClass)
2568       break;
2569
2570     Ref = ParseSubClassReference(nullptr, true);
2571   }
2572
2573   if (InheritFromClass) {
2574     // Process all the classes to inherit as if they were part of a
2575     // regular 'def' and inherit all record values.
2576     SubClassReference SubClass = ParseSubClassReference(nullptr, false);
2577     while (1) {
2578       // Check for error.
2579       if (!SubClass.Rec) return true;
2580
2581       // Get the expanded definition prototypes and teach them about
2582       // the record values the current class to inherit has
2583       for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i) {
2584         Record *CurRec = NewRecDefs[i];
2585
2586         // Add it.
2587         if (AddSubClass(CurRec, SubClass))
2588           return true;
2589
2590         if (ApplyLetStack(CurRec))
2591           return true;
2592       }
2593
2594       if (Lex.getCode() != tgtok::comma) break;
2595       Lex.Lex(); // eat ','.
2596       SubClass = ParseSubClassReference(nullptr, false);
2597     }
2598   }
2599
2600   if (!CurMultiClass)
2601     for (unsigned i = 0, e = NewRecDefs.size(); i != e; ++i)
2602       // See Record::setName().  This resolve step will see any new
2603       // name for the def that might have been created when resolving
2604       // inheritance, values and arguments above.
2605       NewRecDefs[i]->resolveReferences();
2606
2607   if (Lex.getCode() != tgtok::semi)
2608     return TokError("expected ';' at end of defm");
2609   Lex.Lex();
2610
2611   return false;
2612 }
2613
2614 /// ParseObject
2615 ///   Object ::= ClassInst
2616 ///   Object ::= DefInst
2617 ///   Object ::= MultiClassInst
2618 ///   Object ::= DefMInst
2619 ///   Object ::= LETCommand '{' ObjectList '}'
2620 ///   Object ::= LETCommand Object
2621 bool TGParser::ParseObject(MultiClass *MC) {
2622   switch (Lex.getCode()) {
2623   default:
2624     return TokError("Expected class, def, defm, multiclass or let definition");
2625   case tgtok::Let:   return ParseTopLevelLet(MC);
2626   case tgtok::Def:   return ParseDef(MC);
2627   case tgtok::Foreach:   return ParseForeach(MC);
2628   case tgtok::Defm:  return ParseDefm(MC);
2629   case tgtok::Class: return ParseClass();
2630   case tgtok::MultiClass: return ParseMultiClass();
2631   }
2632 }
2633
2634 /// ParseObjectList
2635 ///   ObjectList :== Object*
2636 bool TGParser::ParseObjectList(MultiClass *MC) {
2637   while (isObjectStart(Lex.getCode())) {
2638     if (ParseObject(MC))
2639       return true;
2640   }
2641   return false;
2642 }
2643
2644 bool TGParser::ParseFile() {
2645   Lex.Lex(); // Prime the lexer.
2646   if (ParseObjectList()) return true;
2647
2648   // If we have unread input at the end of the file, report it.
2649   if (Lex.getCode() == tgtok::Eof)
2650     return false;
2651
2652   return TokError("Unexpected input at top level");
2653 }
2654