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