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