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