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