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