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