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