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