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