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