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