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