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