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