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::XMUL:
1027   case tgtok::XAND:
1028   case tgtok::XOR:
1029   case tgtok::XSRA:
1030   case tgtok::XSRL:
1031   case tgtok::XSHL:
1032   case tgtok::XEq:
1033   case tgtok::XNe:
1034   case tgtok::XLe:
1035   case tgtok::XLt:
1036   case tgtok::XGe:
1037   case tgtok::XGt:
1038   case tgtok::XListConcat:
1039   case tgtok::XStrConcat: {  // Value ::= !binop '(' Value ',' Value ')'
1040     tgtok::TokKind OpTok = Lex.getCode();
1041     SMLoc OpLoc = Lex.getLoc();
1042     Lex.Lex();  // eat the operation
1043 
1044     BinOpInit::BinaryOp Code;
1045     switch (OpTok) {
1046     default: llvm_unreachable("Unhandled code!");
1047     case tgtok::XConcat: Code = BinOpInit::CONCAT; break;
1048     case tgtok::XADD:    Code = BinOpInit::ADD; break;
1049     case tgtok::XMUL:    Code = BinOpInit::MUL; break;
1050     case tgtok::XAND:    Code = BinOpInit::AND; break;
1051     case tgtok::XOR:     Code = BinOpInit::OR; break;
1052     case tgtok::XSRA:    Code = BinOpInit::SRA; break;
1053     case tgtok::XSRL:    Code = BinOpInit::SRL; break;
1054     case tgtok::XSHL:    Code = BinOpInit::SHL; break;
1055     case tgtok::XEq:     Code = BinOpInit::EQ; break;
1056     case tgtok::XNe:     Code = BinOpInit::NE; break;
1057     case tgtok::XLe:     Code = BinOpInit::LE; break;
1058     case tgtok::XLt:     Code = BinOpInit::LT; break;
1059     case tgtok::XGe:     Code = BinOpInit::GE; break;
1060     case tgtok::XGt:     Code = BinOpInit::GT; break;
1061     case tgtok::XListConcat: Code = BinOpInit::LISTCONCAT; break;
1062     case tgtok::XStrConcat: Code = BinOpInit::STRCONCAT; break;
1063     }
1064 
1065     RecTy *Type = nullptr;
1066     RecTy *ArgType = nullptr;
1067     switch (OpTok) {
1068     default:
1069       llvm_unreachable("Unhandled code!");
1070     case tgtok::XConcat:
1071       Type = DagRecTy::get();
1072       ArgType = DagRecTy::get();
1073       break;
1074     case tgtok::XAND:
1075     case tgtok::XOR:
1076     case tgtok::XSRA:
1077     case tgtok::XSRL:
1078     case tgtok::XSHL:
1079     case tgtok::XADD:
1080     case tgtok::XMUL:
1081       Type = IntRecTy::get();
1082       ArgType = IntRecTy::get();
1083       break;
1084     case tgtok::XEq:
1085     case tgtok::XNe:
1086       Type = BitRecTy::get();
1087       // ArgType for Eq / Ne is not known at this point
1088       break;
1089     case tgtok::XLe:
1090     case tgtok::XLt:
1091     case tgtok::XGe:
1092     case tgtok::XGt:
1093       Type = BitRecTy::get();
1094       ArgType = IntRecTy::get();
1095       break;
1096     case tgtok::XListConcat:
1097       // We don't know the list type until we parse the first argument
1098       ArgType = ItemType;
1099       break;
1100     case tgtok::XStrConcat:
1101       Type = StringRecTy::get();
1102       ArgType = StringRecTy::get();
1103       break;
1104     }
1105 
1106     if (Type && ItemType && !Type->typeIsConvertibleTo(ItemType)) {
1107       Error(OpLoc, Twine("expected value of type '") +
1108                    ItemType->getAsString() + "', got '" +
1109                    Type->getAsString() + "'");
1110       return nullptr;
1111     }
1112 
1113     if (Lex.getCode() != tgtok::l_paren) {
1114       TokError("expected '(' after binary operator");
1115       return nullptr;
1116     }
1117     Lex.Lex();  // eat the '('
1118 
1119     SmallVector<Init*, 2> InitList;
1120 
1121     for (;;) {
1122       SMLoc InitLoc = Lex.getLoc();
1123       InitList.push_back(ParseValue(CurRec, ArgType));
1124       if (!InitList.back()) return nullptr;
1125 
1126       // All BinOps require their arguments to be of compatible types.
1127       TypedInit *TI = dyn_cast<TypedInit>(InitList.back());
1128       if (!ArgType) {
1129         ArgType = TI->getType();
1130 
1131         switch (Code) {
1132         case BinOpInit::LISTCONCAT:
1133           if (!isa<ListRecTy>(ArgType)) {
1134             Error(InitLoc, Twine("expected a list, got value of type '") +
1135                            ArgType->getAsString() + "'");
1136             return nullptr;
1137           }
1138           break;
1139         case BinOpInit::EQ:
1140         case BinOpInit::NE:
1141           if (!ArgType->typeIsConvertibleTo(IntRecTy::get()) &&
1142               !ArgType->typeIsConvertibleTo(StringRecTy::get())) {
1143             Error(InitLoc, Twine("expected int, bits, or string; got value of "
1144                                  "type '") + ArgType->getAsString() + "'");
1145             return nullptr;
1146           }
1147           break;
1148         default: llvm_unreachable("other ops have fixed argument types");
1149         }
1150       } else {
1151         RecTy *Resolved = resolveTypes(ArgType, TI->getType());
1152         if (!Resolved) {
1153           Error(InitLoc, Twine("expected value of type '") +
1154                          ArgType->getAsString() + "', got '" +
1155                          TI->getType()->getAsString() + "'");
1156           return nullptr;
1157         }
1158         if (Code != BinOpInit::ADD && Code != BinOpInit::AND &&
1159             Code != BinOpInit::OR && Code != BinOpInit::SRA &&
1160             Code != BinOpInit::SRL && Code != BinOpInit::SHL &&
1161             Code != BinOpInit::MUL)
1162           ArgType = Resolved;
1163       }
1164 
1165       if (Lex.getCode() != tgtok::comma)
1166         break;
1167       Lex.Lex();  // eat the ','
1168     }
1169 
1170     if (Lex.getCode() != tgtok::r_paren) {
1171       TokError("expected ')' in operator");
1172       return nullptr;
1173     }
1174     Lex.Lex();  // eat the ')'
1175 
1176     if (Code == BinOpInit::LISTCONCAT)
1177       Type = ArgType;
1178 
1179     // We allow multiple operands to associative operators like !strconcat as
1180     // shorthand for nesting them.
1181     if (Code == BinOpInit::STRCONCAT || Code == BinOpInit::LISTCONCAT ||
1182         Code == BinOpInit::CONCAT || Code == BinOpInit::ADD ||
1183         Code == BinOpInit::AND || Code == BinOpInit::OR ||
1184         Code == BinOpInit::MUL) {
1185       while (InitList.size() > 2) {
1186         Init *RHS = InitList.pop_back_val();
1187         RHS = (BinOpInit::get(Code, InitList.back(), RHS, Type))->Fold(CurRec);
1188         InitList.back() = RHS;
1189       }
1190     }
1191 
1192     if (InitList.size() == 2)
1193       return (BinOpInit::get(Code, InitList[0], InitList[1], Type))
1194           ->Fold(CurRec);
1195 
1196     Error(OpLoc, "expected two operands to operator");
1197     return nullptr;
1198   }
1199 
1200   case tgtok::XForEach: { // Value ::= !foreach '(' Id ',' Value ',' Value ')'
1201     SMLoc OpLoc = Lex.getLoc();
1202     Lex.Lex(); // eat the operation
1203     if (Lex.getCode() != tgtok::l_paren) {
1204       TokError("expected '(' after !foreach");
1205       return nullptr;
1206     }
1207 
1208     if (Lex.Lex() != tgtok::Id) { // eat the '('
1209       TokError("first argument of !foreach must be an identifier");
1210       return nullptr;
1211     }
1212 
1213     Init *LHS = StringInit::get(Lex.getCurStrVal());
1214 
1215     if (CurRec && CurRec->getValue(LHS)) {
1216       TokError((Twine("iteration variable '") + LHS->getAsString() +
1217                 "' already defined")
1218                    .str());
1219       return nullptr;
1220     }
1221 
1222     if (Lex.Lex() != tgtok::comma) { // eat the id
1223       TokError("expected ',' in ternary operator");
1224       return nullptr;
1225     }
1226     Lex.Lex();  // eat the ','
1227 
1228     Init *MHS = ParseValue(CurRec);
1229     if (!MHS)
1230       return nullptr;
1231 
1232     if (Lex.getCode() != tgtok::comma) {
1233       TokError("expected ',' in ternary operator");
1234       return nullptr;
1235     }
1236     Lex.Lex();  // eat the ','
1237 
1238     TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1239     if (!MHSt) {
1240       TokError("could not get type of !foreach input");
1241       return nullptr;
1242     }
1243 
1244     RecTy *InEltType = nullptr;
1245     RecTy *OutEltType = nullptr;
1246     bool IsDAG = false;
1247 
1248     if (ListRecTy *InListTy = dyn_cast<ListRecTy>(MHSt->getType())) {
1249       InEltType = InListTy->getElementType();
1250       if (ItemType) {
1251         if (ListRecTy *OutListTy = dyn_cast<ListRecTy>(ItemType)) {
1252           OutEltType = OutListTy->getElementType();
1253         } else {
1254           Error(OpLoc,
1255                 "expected value of type '" + Twine(ItemType->getAsString()) +
1256                 "', but got !foreach of list type");
1257           return nullptr;
1258         }
1259       }
1260     } else if (DagRecTy *InDagTy = dyn_cast<DagRecTy>(MHSt->getType())) {
1261       InEltType = InDagTy;
1262       if (ItemType && !isa<DagRecTy>(ItemType)) {
1263         Error(OpLoc,
1264               "expected value of type '" + Twine(ItemType->getAsString()) +
1265               "', but got !foreach of dag type");
1266         return nullptr;
1267       }
1268       IsDAG = true;
1269     } else {
1270       TokError("!foreach must have list or dag input");
1271       return nullptr;
1272     }
1273 
1274     // We need to create a temporary record to provide a scope for the iteration
1275     // variable while parsing top-level foreach's.
1276     std::unique_ptr<Record> ParseRecTmp;
1277     Record *ParseRec = CurRec;
1278     if (!ParseRec) {
1279       ParseRecTmp = make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1280       ParseRec = ParseRecTmp.get();
1281     }
1282 
1283     ParseRec->addValue(RecordVal(LHS, InEltType, false));
1284     Init *RHS = ParseValue(ParseRec, OutEltType);
1285     ParseRec->removeValue(LHS);
1286     if (!RHS)
1287       return nullptr;
1288 
1289     if (Lex.getCode() != tgtok::r_paren) {
1290       TokError("expected ')' in binary operator");
1291       return nullptr;
1292     }
1293     Lex.Lex();  // eat the ')'
1294 
1295     RecTy *OutType;
1296     if (IsDAG) {
1297       OutType = InEltType;
1298     } else {
1299       TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1300       if (!RHSt) {
1301         TokError("could not get type of !foreach result");
1302         return nullptr;
1303       }
1304       OutType = RHSt->getType()->getListTy();
1305     }
1306 
1307     return (TernOpInit::get(TernOpInit::FOREACH, LHS, MHS, RHS, OutType))
1308         ->Fold(CurRec);
1309   }
1310 
1311   case tgtok::XDag:
1312   case tgtok::XIf:
1313   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
1314     TernOpInit::TernaryOp Code;
1315     RecTy *Type = nullptr;
1316 
1317     tgtok::TokKind LexCode = Lex.getCode();
1318     Lex.Lex();  // eat the operation
1319     switch (LexCode) {
1320     default: llvm_unreachable("Unhandled code!");
1321     case tgtok::XDag:
1322       Code = TernOpInit::DAG;
1323       Type = DagRecTy::get();
1324       ItemType = nullptr;
1325       break;
1326     case tgtok::XIf:
1327       Code = TernOpInit::IF;
1328       break;
1329     case tgtok::XSubst:
1330       Code = TernOpInit::SUBST;
1331       break;
1332     }
1333     if (Lex.getCode() != tgtok::l_paren) {
1334       TokError("expected '(' after ternary operator");
1335       return nullptr;
1336     }
1337     Lex.Lex();  // eat the '('
1338 
1339     Init *LHS = ParseValue(CurRec);
1340     if (!LHS) return nullptr;
1341 
1342     if (Lex.getCode() != tgtok::comma) {
1343       TokError("expected ',' in ternary operator");
1344       return nullptr;
1345     }
1346     Lex.Lex();  // eat the ','
1347 
1348     SMLoc MHSLoc = Lex.getLoc();
1349     Init *MHS = ParseValue(CurRec, ItemType);
1350     if (!MHS)
1351       return nullptr;
1352 
1353     if (Lex.getCode() != tgtok::comma) {
1354       TokError("expected ',' in ternary operator");
1355       return nullptr;
1356     }
1357     Lex.Lex();  // eat the ','
1358 
1359     SMLoc RHSLoc = Lex.getLoc();
1360     Init *RHS = ParseValue(CurRec, ItemType);
1361     if (!RHS)
1362       return nullptr;
1363 
1364     if (Lex.getCode() != tgtok::r_paren) {
1365       TokError("expected ')' in binary operator");
1366       return nullptr;
1367     }
1368     Lex.Lex();  // eat the ')'
1369 
1370     switch (LexCode) {
1371     default: llvm_unreachable("Unhandled code!");
1372     case tgtok::XDag: {
1373       TypedInit *MHSt = dyn_cast<TypedInit>(MHS);
1374       if (!MHSt && !isa<UnsetInit>(MHS)) {
1375         Error(MHSLoc, "could not determine type of the child list in !dag");
1376         return nullptr;
1377       }
1378       if (MHSt && !isa<ListRecTy>(MHSt->getType())) {
1379         Error(MHSLoc, Twine("expected list of children, got type '") +
1380                           MHSt->getType()->getAsString() + "'");
1381         return nullptr;
1382       }
1383 
1384       TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1385       if (!RHSt && !isa<UnsetInit>(RHS)) {
1386         Error(RHSLoc, "could not determine type of the name list in !dag");
1387         return nullptr;
1388       }
1389       if (RHSt && StringRecTy::get()->getListTy() != RHSt->getType()) {
1390         Error(RHSLoc, Twine("expected list<string>, got type '") +
1391                           RHSt->getType()->getAsString() + "'");
1392         return nullptr;
1393       }
1394 
1395       if (!MHSt && !RHSt) {
1396         Error(MHSLoc,
1397               "cannot have both unset children and unset names in !dag");
1398         return nullptr;
1399       }
1400       break;
1401     }
1402     case tgtok::XIf: {
1403       RecTy *MHSTy = nullptr;
1404       RecTy *RHSTy = nullptr;
1405 
1406       if (TypedInit *MHSt = dyn_cast<TypedInit>(MHS))
1407         MHSTy = MHSt->getType();
1408       if (BitsInit *MHSbits = dyn_cast<BitsInit>(MHS))
1409         MHSTy = BitsRecTy::get(MHSbits->getNumBits());
1410       if (isa<BitInit>(MHS))
1411         MHSTy = BitRecTy::get();
1412 
1413       if (TypedInit *RHSt = dyn_cast<TypedInit>(RHS))
1414         RHSTy = RHSt->getType();
1415       if (BitsInit *RHSbits = dyn_cast<BitsInit>(RHS))
1416         RHSTy = BitsRecTy::get(RHSbits->getNumBits());
1417       if (isa<BitInit>(RHS))
1418         RHSTy = BitRecTy::get();
1419 
1420       // For UnsetInit, it's typed from the other hand.
1421       if (isa<UnsetInit>(MHS))
1422         MHSTy = RHSTy;
1423       if (isa<UnsetInit>(RHS))
1424         RHSTy = MHSTy;
1425 
1426       if (!MHSTy || !RHSTy) {
1427         TokError("could not get type for !if");
1428         return nullptr;
1429       }
1430 
1431       Type = resolveTypes(MHSTy, RHSTy);
1432       if (!Type) {
1433         TokError(Twine("inconsistent types '") + MHSTy->getAsString() +
1434                  "' and '" + RHSTy->getAsString() + "' for !if");
1435         return nullptr;
1436       }
1437       break;
1438     }
1439     case tgtok::XSubst: {
1440       TypedInit *RHSt = dyn_cast<TypedInit>(RHS);
1441       if (!RHSt) {
1442         TokError("could not get type for !subst");
1443         return nullptr;
1444       }
1445       Type = RHSt->getType();
1446       break;
1447     }
1448     }
1449     return (TernOpInit::get(Code, LHS, MHS, RHS, Type))->Fold(CurRec);
1450   }
1451 
1452   case tgtok::XCond:
1453     return ParseOperationCond(CurRec, ItemType);
1454 
1455   case tgtok::XFoldl: {
1456     // Value ::= !foldl '(' Id ',' Id ',' Value ',' Value ',' Value ')'
1457     Lex.Lex(); // eat the operation
1458     if (Lex.getCode() != tgtok::l_paren) {
1459       TokError("expected '(' after !foldl");
1460       return nullptr;
1461     }
1462     Lex.Lex(); // eat the '('
1463 
1464     Init *StartUntyped = ParseValue(CurRec);
1465     if (!StartUntyped)
1466       return nullptr;
1467 
1468     TypedInit *Start = dyn_cast<TypedInit>(StartUntyped);
1469     if (!Start) {
1470       TokError(Twine("could not get type of !foldl start: '") +
1471                StartUntyped->getAsString() + "'");
1472       return nullptr;
1473     }
1474 
1475     if (Lex.getCode() != tgtok::comma) {
1476       TokError("expected ',' in !foldl");
1477       return nullptr;
1478     }
1479     Lex.Lex(); // eat the ','
1480 
1481     Init *ListUntyped = ParseValue(CurRec);
1482     if (!ListUntyped)
1483       return nullptr;
1484 
1485     TypedInit *List = dyn_cast<TypedInit>(ListUntyped);
1486     if (!List) {
1487       TokError(Twine("could not get type of !foldl list: '") +
1488                ListUntyped->getAsString() + "'");
1489       return nullptr;
1490     }
1491 
1492     ListRecTy *ListType = dyn_cast<ListRecTy>(List->getType());
1493     if (!ListType) {
1494       TokError(Twine("!foldl list must be a list, but is of type '") +
1495                List->getType()->getAsString());
1496       return nullptr;
1497     }
1498 
1499     if (Lex.getCode() != tgtok::comma) {
1500       TokError("expected ',' in !foldl");
1501       return nullptr;
1502     }
1503 
1504     if (Lex.Lex() != tgtok::Id) { // eat the ','
1505       TokError("third argument of !foldl must be an identifier");
1506       return nullptr;
1507     }
1508 
1509     Init *A = StringInit::get(Lex.getCurStrVal());
1510     if (CurRec && CurRec->getValue(A)) {
1511       TokError((Twine("left !foldl variable '") + A->getAsString() +
1512                 "' already defined")
1513                    .str());
1514       return nullptr;
1515     }
1516 
1517     if (Lex.Lex() != tgtok::comma) { // eat the id
1518       TokError("expected ',' in !foldl");
1519       return nullptr;
1520     }
1521 
1522     if (Lex.Lex() != tgtok::Id) { // eat the ','
1523       TokError("fourth argument of !foldl must be an identifier");
1524       return nullptr;
1525     }
1526 
1527     Init *B = StringInit::get(Lex.getCurStrVal());
1528     if (CurRec && CurRec->getValue(B)) {
1529       TokError((Twine("right !foldl variable '") + B->getAsString() +
1530                 "' already defined")
1531                    .str());
1532       return nullptr;
1533     }
1534 
1535     if (Lex.Lex() != tgtok::comma) { // eat the id
1536       TokError("expected ',' in !foldl");
1537       return nullptr;
1538     }
1539     Lex.Lex(); // eat the ','
1540 
1541     // We need to create a temporary record to provide a scope for the iteration
1542     // variable while parsing top-level foreach's.
1543     std::unique_ptr<Record> ParseRecTmp;
1544     Record *ParseRec = CurRec;
1545     if (!ParseRec) {
1546       ParseRecTmp = make_unique<Record>(".parse", ArrayRef<SMLoc>{}, Records);
1547       ParseRec = ParseRecTmp.get();
1548     }
1549 
1550     ParseRec->addValue(RecordVal(A, Start->getType(), false));
1551     ParseRec->addValue(RecordVal(B, ListType->getElementType(), false));
1552     Init *ExprUntyped = ParseValue(ParseRec);
1553     ParseRec->removeValue(A);
1554     ParseRec->removeValue(B);
1555     if (!ExprUntyped)
1556       return nullptr;
1557 
1558     TypedInit *Expr = dyn_cast<TypedInit>(ExprUntyped);
1559     if (!Expr) {
1560       TokError("could not get type of !foldl expression");
1561       return nullptr;
1562     }
1563 
1564     if (Expr->getType() != Start->getType()) {
1565       TokError(Twine("!foldl expression must be of same type as start (") +
1566                Start->getType()->getAsString() + "), but is of type " +
1567                Expr->getType()->getAsString());
1568       return nullptr;
1569     }
1570 
1571     if (Lex.getCode() != tgtok::r_paren) {
1572       TokError("expected ')' in fold operator");
1573       return nullptr;
1574     }
1575     Lex.Lex(); // eat the ')'
1576 
1577     return FoldOpInit::get(Start, List, A, B, Expr, Start->getType())
1578         ->Fold(CurRec);
1579   }
1580   }
1581 }
1582 
1583 /// ParseOperatorType - Parse a type for an operator.  This returns
1584 /// null on error.
1585 ///
1586 /// OperatorType ::= '<' Type '>'
1587 ///
1588 RecTy *TGParser::ParseOperatorType() {
1589   RecTy *Type = nullptr;
1590 
1591   if (Lex.getCode() != tgtok::less) {
1592     TokError("expected type name for operator");
1593     return nullptr;
1594   }
1595   Lex.Lex();  // eat the <
1596 
1597   Type = ParseType();
1598 
1599   if (!Type) {
1600     TokError("expected type name for operator");
1601     return nullptr;
1602   }
1603 
1604   if (Lex.getCode() != tgtok::greater) {
1605     TokError("expected type name for operator");
1606     return nullptr;
1607   }
1608   Lex.Lex();  // eat the >
1609 
1610   return Type;
1611 }
1612 
1613 Init *TGParser::ParseOperationCond(Record *CurRec, RecTy *ItemType) {
1614   Lex.Lex();  // eat the operation 'cond'
1615 
1616   if (Lex.getCode() != tgtok::l_paren) {
1617      TokError("expected '(' after !cond operator");
1618      return nullptr;
1619   }
1620   Lex.Lex();  // eat the '('
1621 
1622   // Parse through '[Case: Val,]+'
1623   SmallVector<Init *, 4> Case;
1624   SmallVector<Init *, 4> Val;
1625   while (true) {
1626     if (Lex.getCode() == tgtok::r_paren) {
1627       Lex.Lex(); // eat the ')'
1628       break;
1629     }
1630 
1631     Init *V = ParseValue(CurRec);
1632     if (!V)
1633       return nullptr;
1634     Case.push_back(V);
1635 
1636     if (Lex.getCode() != tgtok::colon) {
1637       TokError("expected ':'  following a condition in !cond operator");
1638       return nullptr;
1639     }
1640     Lex.Lex(); // eat the ':'
1641 
1642     V = ParseValue(CurRec, ItemType);
1643     if (!V)
1644       return nullptr;
1645     Val.push_back(V);
1646 
1647     if (Lex.getCode() == tgtok::r_paren) {
1648       Lex.Lex(); // eat the ')'
1649       break;
1650     }
1651 
1652     if (Lex.getCode() != tgtok::comma) {
1653       TokError("expected ',' or ')' following a value in !cond operator");
1654       return nullptr;
1655     }
1656     Lex.Lex();  // eat the ','
1657   }
1658 
1659   if (Case.size() < 1) {
1660     TokError("there should be at least 1 'condition : value' in the !cond operator");
1661     return nullptr;
1662   }
1663 
1664   // resolve type
1665   RecTy *Type = nullptr;
1666   for (Init *V : Val) {
1667     RecTy *VTy = nullptr;
1668     if (TypedInit *Vt = dyn_cast<TypedInit>(V))
1669       VTy = Vt->getType();
1670     if (BitsInit *Vbits = dyn_cast<BitsInit>(V))
1671       VTy = BitsRecTy::get(Vbits->getNumBits());
1672     if (isa<BitInit>(V))
1673       VTy = BitRecTy::get();
1674 
1675     if (Type == nullptr) {
1676       if (!isa<UnsetInit>(V))
1677         Type = VTy;
1678     } else {
1679       if (!isa<UnsetInit>(V)) {
1680         RecTy *RType = resolveTypes(Type, VTy);
1681         if (!RType) {
1682           TokError(Twine("inconsistent types '") + Type->getAsString() +
1683                          "' and '" + VTy->getAsString() + "' for !cond");
1684           return nullptr;
1685         }
1686         Type = RType;
1687       }
1688     }
1689   }
1690 
1691   if (!Type) {
1692     TokError("could not determine type for !cond from its arguments");
1693     return nullptr;
1694   }
1695   return CondOpInit::get(Case, Val, Type)->Fold(CurRec);
1696 }
1697 
1698 /// ParseSimpleValue - Parse a tblgen value.  This returns null on error.
1699 ///
1700 ///   SimpleValue ::= IDValue
1701 ///   SimpleValue ::= INTVAL
1702 ///   SimpleValue ::= STRVAL+
1703 ///   SimpleValue ::= CODEFRAGMENT
1704 ///   SimpleValue ::= '?'
1705 ///   SimpleValue ::= '{' ValueList '}'
1706 ///   SimpleValue ::= ID '<' ValueListNE '>'
1707 ///   SimpleValue ::= '[' ValueList ']'
1708 ///   SimpleValue ::= '(' IDValue DagArgList ')'
1709 ///   SimpleValue ::= CONCATTOK '(' Value ',' Value ')'
1710 ///   SimpleValue ::= ADDTOK '(' Value ',' Value ')'
1711 ///   SimpleValue ::= SHLTOK '(' Value ',' Value ')'
1712 ///   SimpleValue ::= SRATOK '(' Value ',' Value ')'
1713 ///   SimpleValue ::= SRLTOK '(' Value ',' Value ')'
1714 ///   SimpleValue ::= LISTCONCATTOK '(' Value ',' Value ')'
1715 ///   SimpleValue ::= STRCONCATTOK '(' Value ',' Value ')'
1716 ///   SimpleValue ::= COND '(' [Value ':' Value,]+ ')'
1717 ///
1718 Init *TGParser::ParseSimpleValue(Record *CurRec, RecTy *ItemType,
1719                                  IDParseMode Mode) {
1720   Init *R = nullptr;
1721   switch (Lex.getCode()) {
1722   default: TokError("Unknown token when parsing a value"); break;
1723   case tgtok::paste:
1724     // This is a leading paste operation.  This is deprecated but
1725     // still exists in some .td files.  Ignore it.
1726     Lex.Lex();  // Skip '#'.
1727     return ParseSimpleValue(CurRec, ItemType, Mode);
1728   case tgtok::IntVal: R = IntInit::get(Lex.getCurIntVal()); Lex.Lex(); break;
1729   case tgtok::BinaryIntVal: {
1730     auto BinaryVal = Lex.getCurBinaryIntVal();
1731     SmallVector<Init*, 16> Bits(BinaryVal.second);
1732     for (unsigned i = 0, e = BinaryVal.second; i != e; ++i)
1733       Bits[i] = BitInit::get(BinaryVal.first & (1LL << i));
1734     R = BitsInit::get(Bits);
1735     Lex.Lex();
1736     break;
1737   }
1738   case tgtok::StrVal: {
1739     std::string Val = Lex.getCurStrVal();
1740     Lex.Lex();
1741 
1742     // Handle multiple consecutive concatenated strings.
1743     while (Lex.getCode() == tgtok::StrVal) {
1744       Val += Lex.getCurStrVal();
1745       Lex.Lex();
1746     }
1747 
1748     R = StringInit::get(Val);
1749     break;
1750   }
1751   case tgtok::CodeFragment:
1752     R = CodeInit::get(Lex.getCurStrVal(), Lex.getLoc());
1753     Lex.Lex();
1754     break;
1755   case tgtok::question:
1756     R = UnsetInit::get();
1757     Lex.Lex();
1758     break;
1759   case tgtok::Id: {
1760     SMLoc NameLoc = Lex.getLoc();
1761     StringInit *Name = StringInit::get(Lex.getCurStrVal());
1762     if (Lex.Lex() != tgtok::less)  // consume the Id.
1763       return ParseIDValue(CurRec, Name, NameLoc, Mode);    // Value ::= IDValue
1764 
1765     // Value ::= ID '<' ValueListNE '>'
1766     if (Lex.Lex() == tgtok::greater) {
1767       TokError("expected non-empty value list");
1768       return nullptr;
1769     }
1770 
1771     // This is a CLASS<initvalslist> expression.  This is supposed to synthesize
1772     // a new anonymous definition, deriving from CLASS<initvalslist> with no
1773     // body.
1774     Record *Class = Records.getClass(Name->getValue());
1775     if (!Class) {
1776       Error(NameLoc, "Expected a class name, got '" + Name->getValue() + "'");
1777       return nullptr;
1778     }
1779 
1780     SmallVector<Init *, 8> Args;
1781     ParseValueList(Args, CurRec, Class);
1782     if (Args.empty()) return nullptr;
1783 
1784     if (Lex.getCode() != tgtok::greater) {
1785       TokError("expected '>' at end of value list");
1786       return nullptr;
1787     }
1788     Lex.Lex();  // eat the '>'
1789 
1790     // Typecheck the template arguments list
1791     ArrayRef<Init *> ExpectedArgs = Class->getTemplateArgs();
1792     if (ExpectedArgs.size() < Args.size()) {
1793       Error(NameLoc,
1794             "More template args specified than expected");
1795       return nullptr;
1796     }
1797 
1798     for (unsigned i = 0, e = ExpectedArgs.size(); i != e; ++i) {
1799       RecordVal *ExpectedArg = Class->getValue(ExpectedArgs[i]);
1800       if (i < Args.size()) {
1801         if (TypedInit *TI = dyn_cast<TypedInit>(Args[i])) {
1802           RecTy *ExpectedType = ExpectedArg->getType();
1803           if (!TI->getType()->typeIsConvertibleTo(ExpectedType)) {
1804             Error(NameLoc,
1805                   "Value specified for template argument #" + Twine(i) + " (" +
1806                   ExpectedArg->getNameInitAsString() + ") is of type '" +
1807                   TI->getType()->getAsString() + "', expected '" +
1808                   ExpectedType->getAsString() + "': " + TI->getAsString());
1809             return nullptr;
1810           }
1811           continue;
1812         }
1813       } else if (ExpectedArg->getValue()->isComplete())
1814         continue;
1815 
1816       Error(NameLoc,
1817             "Value not specified for template argument #" + Twine(i) + " (" +
1818             ExpectedArgs[i]->getAsUnquotedString() + ")");
1819       return nullptr;
1820     }
1821 
1822     return VarDefInit::get(Class, Args)->Fold();
1823   }
1824   case tgtok::l_brace: {           // Value ::= '{' ValueList '}'
1825     SMLoc BraceLoc = Lex.getLoc();
1826     Lex.Lex(); // eat the '{'
1827     SmallVector<Init*, 16> Vals;
1828 
1829     if (Lex.getCode() != tgtok::r_brace) {
1830       ParseValueList(Vals, CurRec);
1831       if (Vals.empty()) return nullptr;
1832     }
1833     if (Lex.getCode() != tgtok::r_brace) {
1834       TokError("expected '}' at end of bit list value");
1835       return nullptr;
1836     }
1837     Lex.Lex();  // eat the '}'
1838 
1839     SmallVector<Init *, 16> NewBits;
1840 
1841     // As we parse { a, b, ... }, 'a' is the highest bit, but we parse it
1842     // first.  We'll first read everything in to a vector, then we can reverse
1843     // it to get the bits in the correct order for the BitsInit value.
1844     for (unsigned i = 0, e = Vals.size(); i != e; ++i) {
1845       // FIXME: The following two loops would not be duplicated
1846       //        if the API was a little more orthogonal.
1847 
1848       // bits<n> values are allowed to initialize n bits.
1849       if (BitsInit *BI = dyn_cast<BitsInit>(Vals[i])) {
1850         for (unsigned i = 0, e = BI->getNumBits(); i != e; ++i)
1851           NewBits.push_back(BI->getBit((e - i) - 1));
1852         continue;
1853       }
1854       // bits<n> can also come from variable initializers.
1855       if (VarInit *VI = dyn_cast<VarInit>(Vals[i])) {
1856         if (BitsRecTy *BitsRec = dyn_cast<BitsRecTy>(VI->getType())) {
1857           for (unsigned i = 0, e = BitsRec->getNumBits(); i != e; ++i)
1858             NewBits.push_back(VI->getBit((e - i) - 1));
1859           continue;
1860         }
1861         // Fallthrough to try convert this to a bit.
1862       }
1863       // All other values must be convertible to just a single bit.
1864       Init *Bit = Vals[i]->getCastTo(BitRecTy::get());
1865       if (!Bit) {
1866         Error(BraceLoc, "Element #" + Twine(i) + " (" + Vals[i]->getAsString() +
1867               ") is not convertable to a bit");
1868         return nullptr;
1869       }
1870       NewBits.push_back(Bit);
1871     }
1872     std::reverse(NewBits.begin(), NewBits.end());
1873     return BitsInit::get(NewBits);
1874   }
1875   case tgtok::l_square: {          // Value ::= '[' ValueList ']'
1876     Lex.Lex(); // eat the '['
1877     SmallVector<Init*, 16> Vals;
1878 
1879     RecTy *DeducedEltTy = nullptr;
1880     ListRecTy *GivenListTy = nullptr;
1881 
1882     if (ItemType) {
1883       ListRecTy *ListType = dyn_cast<ListRecTy>(ItemType);
1884       if (!ListType) {
1885         TokError(Twine("Type mismatch for list, expected list type, got ") +
1886                  ItemType->getAsString());
1887         return nullptr;
1888       }
1889       GivenListTy = ListType;
1890     }
1891 
1892     if (Lex.getCode() != tgtok::r_square) {
1893       ParseValueList(Vals, CurRec, nullptr,
1894                      GivenListTy ? GivenListTy->getElementType() : nullptr);
1895       if (Vals.empty()) return nullptr;
1896     }
1897     if (Lex.getCode() != tgtok::r_square) {
1898       TokError("expected ']' at end of list value");
1899       return nullptr;
1900     }
1901     Lex.Lex();  // eat the ']'
1902 
1903     RecTy *GivenEltTy = nullptr;
1904     if (Lex.getCode() == tgtok::less) {
1905       // Optional list element type
1906       Lex.Lex();  // eat the '<'
1907 
1908       GivenEltTy = ParseType();
1909       if (!GivenEltTy) {
1910         // Couldn't parse element type
1911         return nullptr;
1912       }
1913 
1914       if (Lex.getCode() != tgtok::greater) {
1915         TokError("expected '>' at end of list element type");
1916         return nullptr;
1917       }
1918       Lex.Lex();  // eat the '>'
1919     }
1920 
1921     // Check elements
1922     RecTy *EltTy = nullptr;
1923     for (Init *V : Vals) {
1924       TypedInit *TArg = dyn_cast<TypedInit>(V);
1925       if (TArg) {
1926         if (EltTy) {
1927           EltTy = resolveTypes(EltTy, TArg->getType());
1928           if (!EltTy) {
1929             TokError("Incompatible types in list elements");
1930             return nullptr;
1931           }
1932         } else {
1933           EltTy = TArg->getType();
1934         }
1935       }
1936     }
1937 
1938     if (GivenEltTy) {
1939       if (EltTy) {
1940         // Verify consistency
1941         if (!EltTy->typeIsConvertibleTo(GivenEltTy)) {
1942           TokError("Incompatible types in list elements");
1943           return nullptr;
1944         }
1945       }
1946       EltTy = GivenEltTy;
1947     }
1948 
1949     if (!EltTy) {
1950       if (!ItemType) {
1951         TokError("No type for list");
1952         return nullptr;
1953       }
1954       DeducedEltTy = GivenListTy->getElementType();
1955     } else {
1956       // Make sure the deduced type is compatible with the given type
1957       if (GivenListTy) {
1958         if (!EltTy->typeIsConvertibleTo(GivenListTy->getElementType())) {
1959           TokError(Twine("Element type mismatch for list: element type '") +
1960                    EltTy->getAsString() + "' not convertible to '" +
1961                    GivenListTy->getElementType()->getAsString());
1962           return nullptr;
1963         }
1964       }
1965       DeducedEltTy = EltTy;
1966     }
1967 
1968     return ListInit::get(Vals, DeducedEltTy);
1969   }
1970   case tgtok::l_paren: {         // Value ::= '(' IDValue DagArgList ')'
1971     Lex.Lex();   // eat the '('
1972     if (Lex.getCode() != tgtok::Id && Lex.getCode() != tgtok::XCast) {
1973       TokError("expected identifier in dag init");
1974       return nullptr;
1975     }
1976 
1977     Init *Operator = ParseValue(CurRec);
1978     if (!Operator) return nullptr;
1979 
1980     // If the operator name is present, parse it.
1981     StringInit *OperatorName = nullptr;
1982     if (Lex.getCode() == tgtok::colon) {
1983       if (Lex.Lex() != tgtok::VarName) { // eat the ':'
1984         TokError("expected variable name in dag operator");
1985         return nullptr;
1986       }
1987       OperatorName = StringInit::get(Lex.getCurStrVal());
1988       Lex.Lex();  // eat the VarName.
1989     }
1990 
1991     SmallVector<std::pair<llvm::Init*, StringInit*>, 8> DagArgs;
1992     if (Lex.getCode() != tgtok::r_paren) {
1993       ParseDagArgList(DagArgs, CurRec);
1994       if (DagArgs.empty()) return nullptr;
1995     }
1996 
1997     if (Lex.getCode() != tgtok::r_paren) {
1998       TokError("expected ')' in dag init");
1999       return nullptr;
2000     }
2001     Lex.Lex();  // eat the ')'
2002 
2003     return DagInit::get(Operator, OperatorName, DagArgs);
2004   }
2005 
2006   case tgtok::XHead:
2007   case tgtok::XTail:
2008   case tgtok::XSize:
2009   case tgtok::XEmpty:
2010   case tgtok::XCast:  // Value ::= !unop '(' Value ')'
2011   case tgtok::XIsA:
2012   case tgtok::XConcat:
2013   case tgtok::XDag:
2014   case tgtok::XADD:
2015   case tgtok::XMUL:
2016   case tgtok::XAND:
2017   case tgtok::XOR:
2018   case tgtok::XSRA:
2019   case tgtok::XSRL:
2020   case tgtok::XSHL:
2021   case tgtok::XEq:
2022   case tgtok::XNe:
2023   case tgtok::XLe:
2024   case tgtok::XLt:
2025   case tgtok::XGe:
2026   case tgtok::XGt:
2027   case tgtok::XListConcat:
2028   case tgtok::XStrConcat:   // Value ::= !binop '(' Value ',' Value ')'
2029   case tgtok::XIf:
2030   case tgtok::XCond:
2031   case tgtok::XFoldl:
2032   case tgtok::XForEach:
2033   case tgtok::XSubst: {  // Value ::= !ternop '(' Value ',' Value ',' Value ')'
2034     return ParseOperation(CurRec, ItemType);
2035   }
2036   }
2037 
2038   return R;
2039 }
2040 
2041 /// ParseValue - Parse a tblgen value.  This returns null on error.
2042 ///
2043 ///   Value       ::= SimpleValue ValueSuffix*
2044 ///   ValueSuffix ::= '{' BitList '}'
2045 ///   ValueSuffix ::= '[' BitList ']'
2046 ///   ValueSuffix ::= '.' ID
2047 ///
2048 Init *TGParser::ParseValue(Record *CurRec, RecTy *ItemType, IDParseMode Mode) {
2049   Init *Result = ParseSimpleValue(CurRec, ItemType, Mode);
2050   if (!Result) return nullptr;
2051 
2052   // Parse the suffixes now if present.
2053   while (true) {
2054     switch (Lex.getCode()) {
2055     default: return Result;
2056     case tgtok::l_brace: {
2057       if (Mode == ParseNameMode)
2058         // This is the beginning of the object body.
2059         return Result;
2060 
2061       SMLoc CurlyLoc = Lex.getLoc();
2062       Lex.Lex(); // eat the '{'
2063       SmallVector<unsigned, 16> Ranges;
2064       ParseRangeList(Ranges);
2065       if (Ranges.empty()) return nullptr;
2066 
2067       // Reverse the bitlist.
2068       std::reverse(Ranges.begin(), Ranges.end());
2069       Result = Result->convertInitializerBitRange(Ranges);
2070       if (!Result) {
2071         Error(CurlyLoc, "Invalid bit range for value");
2072         return nullptr;
2073       }
2074 
2075       // Eat the '}'.
2076       if (Lex.getCode() != tgtok::r_brace) {
2077         TokError("expected '}' at end of bit range list");
2078         return nullptr;
2079       }
2080       Lex.Lex();
2081       break;
2082     }
2083     case tgtok::l_square: {
2084       SMLoc SquareLoc = Lex.getLoc();
2085       Lex.Lex(); // eat the '['
2086       SmallVector<unsigned, 16> Ranges;
2087       ParseRangeList(Ranges);
2088       if (Ranges.empty()) return nullptr;
2089 
2090       Result = Result->convertInitListSlice(Ranges);
2091       if (!Result) {
2092         Error(SquareLoc, "Invalid range for list slice");
2093         return nullptr;
2094       }
2095 
2096       // Eat the ']'.
2097       if (Lex.getCode() != tgtok::r_square) {
2098         TokError("expected ']' at end of list slice");
2099         return nullptr;
2100       }
2101       Lex.Lex();
2102       break;
2103     }
2104     case tgtok::period: {
2105       if (Lex.Lex() != tgtok::Id) {  // eat the .
2106         TokError("expected field identifier after '.'");
2107         return nullptr;
2108       }
2109       StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2110       if (!Result->getFieldType(FieldName)) {
2111         TokError("Cannot access field '" + Lex.getCurStrVal() + "' of value '" +
2112                  Result->getAsString() + "'");
2113         return nullptr;
2114       }
2115       Result = FieldInit::get(Result, FieldName)->Fold(CurRec);
2116       Lex.Lex();  // eat field name
2117       break;
2118     }
2119 
2120     case tgtok::paste:
2121       SMLoc PasteLoc = Lex.getLoc();
2122       TypedInit *LHS = dyn_cast<TypedInit>(Result);
2123       if (!LHS) {
2124         Error(PasteLoc, "LHS of paste is not typed!");
2125         return nullptr;
2126       }
2127 
2128       // Check if it's a 'listA # listB'
2129       if (isa<ListRecTy>(LHS->getType())) {
2130         Lex.Lex();  // Eat the '#'.
2131 
2132         switch (Lex.getCode()) {
2133         case tgtok::colon:
2134         case tgtok::semi:
2135         case tgtok::l_brace:
2136           Result = LHS; // trailing paste, ignore.
2137           break;
2138         default:
2139           Init *RHSResult = ParseValue(CurRec, ItemType, ParseNameMode);
2140           Result = BinOpInit::getListConcat(LHS, RHSResult);
2141         }
2142         break;
2143       }
2144 
2145       // Create a !strconcat() operation, first casting each operand to
2146       // a string if necessary.
2147       if (LHS->getType() != StringRecTy::get()) {
2148         LHS = dyn_cast<TypedInit>(
2149             UnOpInit::get(UnOpInit::CAST, LHS, StringRecTy::get())
2150                 ->Fold(CurRec));
2151         if (!LHS) {
2152           Error(PasteLoc, Twine("can't cast '") + LHS->getAsString() +
2153                               "' to string");
2154           return nullptr;
2155         }
2156       }
2157 
2158       TypedInit *RHS = nullptr;
2159 
2160       Lex.Lex();  // Eat the '#'.
2161       switch (Lex.getCode()) {
2162       case tgtok::colon:
2163       case tgtok::semi:
2164       case tgtok::l_brace:
2165         // These are all of the tokens that can begin an object body.
2166         // Some of these can also begin values but we disallow those cases
2167         // because they are unlikely to be useful.
2168 
2169         // Trailing paste, concat with an empty string.
2170         RHS = StringInit::get("");
2171         break;
2172 
2173       default:
2174         Init *RHSResult = ParseValue(CurRec, nullptr, ParseNameMode);
2175         RHS = dyn_cast<TypedInit>(RHSResult);
2176         if (!RHS) {
2177           Error(PasteLoc, "RHS of paste is not typed!");
2178           return nullptr;
2179         }
2180 
2181         if (RHS->getType() != StringRecTy::get()) {
2182           RHS = dyn_cast<TypedInit>(
2183               UnOpInit::get(UnOpInit::CAST, RHS, StringRecTy::get())
2184                   ->Fold(CurRec));
2185           if (!RHS) {
2186             Error(PasteLoc, Twine("can't cast '") + RHS->getAsString() +
2187                                 "' to string");
2188             return nullptr;
2189           }
2190         }
2191 
2192         break;
2193       }
2194 
2195       Result = BinOpInit::getStrConcat(LHS, RHS);
2196       break;
2197     }
2198   }
2199 }
2200 
2201 /// ParseDagArgList - Parse the argument list for a dag literal expression.
2202 ///
2203 ///    DagArg     ::= Value (':' VARNAME)?
2204 ///    DagArg     ::= VARNAME
2205 ///    DagArgList ::= DagArg
2206 ///    DagArgList ::= DagArgList ',' DagArg
2207 void TGParser::ParseDagArgList(
2208     SmallVectorImpl<std::pair<llvm::Init*, StringInit*>> &Result,
2209     Record *CurRec) {
2210 
2211   while (true) {
2212     // DagArg ::= VARNAME
2213     if (Lex.getCode() == tgtok::VarName) {
2214       // A missing value is treated like '?'.
2215       StringInit *VarName = StringInit::get(Lex.getCurStrVal());
2216       Result.emplace_back(UnsetInit::get(), VarName);
2217       Lex.Lex();
2218     } else {
2219       // DagArg ::= Value (':' VARNAME)?
2220       Init *Val = ParseValue(CurRec);
2221       if (!Val) {
2222         Result.clear();
2223         return;
2224       }
2225 
2226       // If the variable name is present, add it.
2227       StringInit *VarName = nullptr;
2228       if (Lex.getCode() == tgtok::colon) {
2229         if (Lex.Lex() != tgtok::VarName) { // eat the ':'
2230           TokError("expected variable name in dag literal");
2231           Result.clear();
2232           return;
2233         }
2234         VarName = StringInit::get(Lex.getCurStrVal());
2235         Lex.Lex();  // eat the VarName.
2236       }
2237 
2238       Result.push_back(std::make_pair(Val, VarName));
2239     }
2240     if (Lex.getCode() != tgtok::comma) break;
2241     Lex.Lex(); // eat the ','
2242   }
2243 }
2244 
2245 /// ParseValueList - Parse a comma separated list of values, returning them as a
2246 /// vector.  Note that this always expects to be able to parse at least one
2247 /// value.  It returns an empty list if this is not possible.
2248 ///
2249 ///   ValueList ::= Value (',' Value)
2250 ///
2251 void TGParser::ParseValueList(SmallVectorImpl<Init*> &Result, Record *CurRec,
2252                               Record *ArgsRec, RecTy *EltTy) {
2253   RecTy *ItemType = EltTy;
2254   unsigned int ArgN = 0;
2255   if (ArgsRec && !EltTy) {
2256     ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2257     if (TArgs.empty()) {
2258       TokError("template argument provided to non-template class");
2259       Result.clear();
2260       return;
2261     }
2262     const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2263     if (!RV) {
2264       errs() << "Cannot find template arg " << ArgN << " (" << TArgs[ArgN]
2265         << ")\n";
2266     }
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   while (Lex.getCode() == tgtok::comma) {
2278     Lex.Lex();  // Eat the comma
2279 
2280     if (ArgsRec && !EltTy) {
2281       ArrayRef<Init *> TArgs = ArgsRec->getTemplateArgs();
2282       if (ArgN >= TArgs.size()) {
2283         TokError("too many template arguments");
2284         Result.clear();
2285         return;
2286       }
2287       const RecordVal *RV = ArgsRec->getValue(TArgs[ArgN]);
2288       assert(RV && "Template argument record not found??");
2289       ItemType = RV->getType();
2290       ++ArgN;
2291     }
2292     Result.push_back(ParseValue(CurRec, ItemType));
2293     if (!Result.back()) {
2294       Result.clear();
2295       return;
2296     }
2297   }
2298 }
2299 
2300 /// ParseDeclaration - Read a declaration, returning the name of field ID, or an
2301 /// empty string on error.  This can happen in a number of different context's,
2302 /// including within a def or in the template args for a def (which which case
2303 /// CurRec will be non-null) and within the template args for a multiclass (in
2304 /// which case CurRec will be null, but CurMultiClass will be set).  This can
2305 /// also happen within a def that is within a multiclass, which will set both
2306 /// CurRec and CurMultiClass.
2307 ///
2308 ///  Declaration ::= FIELD? Type ID ('=' Value)?
2309 ///
2310 Init *TGParser::ParseDeclaration(Record *CurRec,
2311                                        bool ParsingTemplateArgs) {
2312   // Read the field prefix if present.
2313   bool HasField = Lex.getCode() == tgtok::Field;
2314   if (HasField) Lex.Lex();
2315 
2316   RecTy *Type = ParseType();
2317   if (!Type) return nullptr;
2318 
2319   if (Lex.getCode() != tgtok::Id) {
2320     TokError("Expected identifier in declaration");
2321     return nullptr;
2322   }
2323 
2324   std::string Str = Lex.getCurStrVal();
2325   if (Str == "NAME") {
2326     TokError("'" + Str + "' is a reserved variable name");
2327     return nullptr;
2328   }
2329 
2330   SMLoc IdLoc = Lex.getLoc();
2331   Init *DeclName = StringInit::get(Str);
2332   Lex.Lex();
2333 
2334   if (ParsingTemplateArgs) {
2335     if (CurRec)
2336       DeclName = QualifyName(*CurRec, CurMultiClass, DeclName, ":");
2337     else
2338       assert(CurMultiClass);
2339     if (CurMultiClass)
2340       DeclName = QualifyName(CurMultiClass->Rec, CurMultiClass, DeclName,
2341                              "::");
2342   }
2343 
2344   // Add the value.
2345   if (AddValue(CurRec, IdLoc, RecordVal(DeclName, Type, HasField)))
2346     return nullptr;
2347 
2348   // If a value is present, parse it.
2349   if (Lex.getCode() == tgtok::equal) {
2350     Lex.Lex();
2351     SMLoc ValLoc = Lex.getLoc();
2352     Init *Val = ParseValue(CurRec, Type);
2353     if (!Val ||
2354         SetValue(CurRec, ValLoc, DeclName, None, Val))
2355       // Return the name, even if an error is thrown.  This is so that we can
2356       // continue to make some progress, even without the value having been
2357       // initialized.
2358       return DeclName;
2359   }
2360 
2361   return DeclName;
2362 }
2363 
2364 /// ParseForeachDeclaration - Read a foreach declaration, returning
2365 /// the name of the declared object or a NULL Init on error.  Return
2366 /// the name of the parsed initializer list through ForeachListName.
2367 ///
2368 ///  ForeachDeclaration ::= ID '=' '{' RangeList '}'
2369 ///  ForeachDeclaration ::= ID '=' RangePiece
2370 ///  ForeachDeclaration ::= ID '=' Value
2371 ///
2372 VarInit *TGParser::ParseForeachDeclaration(Init *&ForeachListValue) {
2373   if (Lex.getCode() != tgtok::Id) {
2374     TokError("Expected identifier in foreach declaration");
2375     return nullptr;
2376   }
2377 
2378   Init *DeclName = StringInit::get(Lex.getCurStrVal());
2379   Lex.Lex();
2380 
2381   // If a value is present, parse it.
2382   if (Lex.getCode() != tgtok::equal) {
2383     TokError("Expected '=' in foreach declaration");
2384     return nullptr;
2385   }
2386   Lex.Lex();  // Eat the '='
2387 
2388   RecTy *IterType = nullptr;
2389   SmallVector<unsigned, 16> Ranges;
2390 
2391   switch (Lex.getCode()) {
2392   case tgtok::IntVal: { // RangePiece.
2393     if (ParseRangePiece(Ranges))
2394       return nullptr;
2395     break;
2396   }
2397 
2398   case tgtok::l_brace: { // '{' RangeList '}'
2399     Lex.Lex(); // eat the '{'
2400     ParseRangeList(Ranges);
2401     if (Lex.getCode() != tgtok::r_brace) {
2402       TokError("expected '}' at end of bit range list");
2403       return nullptr;
2404     }
2405     Lex.Lex();
2406     break;
2407   }
2408 
2409   default: {
2410     SMLoc ValueLoc = Lex.getLoc();
2411     Init *I = ParseValue(nullptr);
2412     TypedInit *TI = dyn_cast<TypedInit>(I);
2413     if (!TI || !isa<ListRecTy>(TI->getType())) {
2414       std::string Type;
2415       if (TI)
2416         Type = (Twine("' of type '") + TI->getType()->getAsString()).str();
2417       Error(ValueLoc, "expected a list, got '" + I->getAsString() + Type + "'");
2418       if (CurMultiClass)
2419         PrintNote({}, "references to multiclass template arguments cannot be "
2420                       "resolved at this time");
2421       return nullptr;
2422     }
2423     ForeachListValue = I;
2424     IterType = cast<ListRecTy>(TI->getType())->getElementType();
2425     break;
2426   }
2427   }
2428 
2429   if (!Ranges.empty()) {
2430     assert(!IterType && "Type already initialized?");
2431     IterType = IntRecTy::get();
2432     std::vector<Init*> Values;
2433     for (unsigned R : Ranges)
2434       Values.push_back(IntInit::get(R));
2435     ForeachListValue = ListInit::get(Values, IterType);
2436   }
2437 
2438   if (!IterType)
2439     return nullptr;
2440 
2441   return VarInit::get(DeclName, IterType);
2442 }
2443 
2444 /// ParseTemplateArgList - Read a template argument list, which is a non-empty
2445 /// sequence of template-declarations in <>'s.  If CurRec is non-null, these are
2446 /// template args for a def, which may or may not be in a multiclass.  If null,
2447 /// these are the template args for a multiclass.
2448 ///
2449 ///    TemplateArgList ::= '<' Declaration (',' Declaration)* '>'
2450 ///
2451 bool TGParser::ParseTemplateArgList(Record *CurRec) {
2452   assert(Lex.getCode() == tgtok::less && "Not a template arg list!");
2453   Lex.Lex(); // eat the '<'
2454 
2455   Record *TheRecToAddTo = CurRec ? CurRec : &CurMultiClass->Rec;
2456 
2457   // Read the first declaration.
2458   Init *TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2459   if (!TemplArg)
2460     return true;
2461 
2462   TheRecToAddTo->addTemplateArg(TemplArg);
2463 
2464   while (Lex.getCode() == tgtok::comma) {
2465     Lex.Lex(); // eat the ','
2466 
2467     // Read the following declarations.
2468     SMLoc Loc = Lex.getLoc();
2469     TemplArg = ParseDeclaration(CurRec, true/*templateargs*/);
2470     if (!TemplArg)
2471       return true;
2472 
2473     if (TheRecToAddTo->isTemplateArg(TemplArg))
2474       return Error(Loc, "template argument with the same name has already been "
2475                         "defined");
2476 
2477     TheRecToAddTo->addTemplateArg(TemplArg);
2478   }
2479 
2480   if (Lex.getCode() != tgtok::greater)
2481     return TokError("expected '>' at end of template argument list");
2482   Lex.Lex(); // eat the '>'.
2483   return false;
2484 }
2485 
2486 /// ParseBodyItem - Parse a single item at within the body of a def or class.
2487 ///
2488 ///   BodyItem ::= Declaration ';'
2489 ///   BodyItem ::= LET ID OptionalBitList '=' Value ';'
2490 bool TGParser::ParseBodyItem(Record *CurRec) {
2491   if (Lex.getCode() != tgtok::Let) {
2492     if (!ParseDeclaration(CurRec, false))
2493       return true;
2494 
2495     if (Lex.getCode() != tgtok::semi)
2496       return TokError("expected ';' after declaration");
2497     Lex.Lex();
2498     return false;
2499   }
2500 
2501   // LET ID OptionalRangeList '=' Value ';'
2502   if (Lex.Lex() != tgtok::Id)
2503     return TokError("expected field identifier after let");
2504 
2505   SMLoc IdLoc = Lex.getLoc();
2506   StringInit *FieldName = StringInit::get(Lex.getCurStrVal());
2507   Lex.Lex();  // eat the field name.
2508 
2509   SmallVector<unsigned, 16> BitList;
2510   if (ParseOptionalBitList(BitList))
2511     return true;
2512   std::reverse(BitList.begin(), BitList.end());
2513 
2514   if (Lex.getCode() != tgtok::equal)
2515     return TokError("expected '=' in let expression");
2516   Lex.Lex();  // eat the '='.
2517 
2518   RecordVal *Field = CurRec->getValue(FieldName);
2519   if (!Field)
2520     return TokError("Value '" + FieldName->getValue() + "' unknown!");
2521 
2522   RecTy *Type = Field->getType();
2523 
2524   Init *Val = ParseValue(CurRec, Type);
2525   if (!Val) return true;
2526 
2527   if (Lex.getCode() != tgtok::semi)
2528     return TokError("expected ';' after let expression");
2529   Lex.Lex();
2530 
2531   return SetValue(CurRec, IdLoc, FieldName, BitList, Val);
2532 }
2533 
2534 /// ParseBody - Read the body of a class or def.  Return true on error, false on
2535 /// success.
2536 ///
2537 ///   Body     ::= ';'
2538 ///   Body     ::= '{' BodyList '}'
2539 ///   BodyList BodyItem*
2540 ///
2541 bool TGParser::ParseBody(Record *CurRec) {
2542   // If this is a null definition, just eat the semi and return.
2543   if (Lex.getCode() == tgtok::semi) {
2544     Lex.Lex();
2545     return false;
2546   }
2547 
2548   if (Lex.getCode() != tgtok::l_brace)
2549     return TokError("Expected ';' or '{' to start body");
2550   // Eat the '{'.
2551   Lex.Lex();
2552 
2553   while (Lex.getCode() != tgtok::r_brace)
2554     if (ParseBodyItem(CurRec))
2555       return true;
2556 
2557   // Eat the '}'.
2558   Lex.Lex();
2559   return false;
2560 }
2561 
2562 /// Apply the current let bindings to \a CurRec.
2563 /// \returns true on error, false otherwise.
2564 bool TGParser::ApplyLetStack(Record *CurRec) {
2565   for (SmallVectorImpl<LetRecord> &LetInfo : LetStack)
2566     for (LetRecord &LR : LetInfo)
2567       if (SetValue(CurRec, LR.Loc, LR.Name, LR.Bits, LR.Value))
2568         return true;
2569   return false;
2570 }
2571 
2572 bool TGParser::ApplyLetStack(RecordsEntry &Entry) {
2573   if (Entry.Rec)
2574     return ApplyLetStack(Entry.Rec.get());
2575 
2576   for (auto &E : Entry.Loop->Entries) {
2577     if (ApplyLetStack(E))
2578       return true;
2579   }
2580 
2581   return false;
2582 }
2583 
2584 /// ParseObjectBody - Parse the body of a def or class.  This consists of an
2585 /// optional ClassList followed by a Body.  CurRec is the current def or class
2586 /// that is being parsed.
2587 ///
2588 ///   ObjectBody      ::= BaseClassList Body
2589 ///   BaseClassList   ::= /*empty*/
2590 ///   BaseClassList   ::= ':' BaseClassListNE
2591 ///   BaseClassListNE ::= SubClassRef (',' SubClassRef)*
2592 ///
2593 bool TGParser::ParseObjectBody(Record *CurRec) {
2594   // If there is a baseclass list, read it.
2595   if (Lex.getCode() == tgtok::colon) {
2596     Lex.Lex();
2597 
2598     // Read all of the subclasses.
2599     SubClassReference SubClass = ParseSubClassReference(CurRec, false);
2600     while (true) {
2601       // Check for error.
2602       if (!SubClass.Rec) return true;
2603 
2604       // Add it.
2605       if (AddSubClass(CurRec, SubClass))
2606         return true;
2607 
2608       if (Lex.getCode() != tgtok::comma) break;
2609       Lex.Lex(); // eat ','.
2610       SubClass = ParseSubClassReference(CurRec, false);
2611     }
2612   }
2613 
2614   if (ApplyLetStack(CurRec))
2615     return true;
2616 
2617   return ParseBody(CurRec);
2618 }
2619 
2620 /// ParseDef - Parse and return a top level or multiclass def, return the record
2621 /// corresponding to it.  This returns null on error.
2622 ///
2623 ///   DefInst ::= DEF ObjectName ObjectBody
2624 ///
2625 bool TGParser::ParseDef(MultiClass *CurMultiClass) {
2626   SMLoc DefLoc = Lex.getLoc();
2627   assert(Lex.getCode() == tgtok::Def && "Unknown tok");
2628   Lex.Lex();  // Eat the 'def' token.
2629 
2630   // Parse ObjectName and make a record for it.
2631   std::unique_ptr<Record> CurRec;
2632   Init *Name = ParseObjectName(CurMultiClass);
2633   if (!Name)
2634     return true;
2635 
2636   if (isa<UnsetInit>(Name))
2637     CurRec = make_unique<Record>(Records.getNewAnonymousName(), DefLoc, Records,
2638                                  /*Anonymous=*/true);
2639   else
2640     CurRec = make_unique<Record>(Name, DefLoc, Records);
2641 
2642   if (ParseObjectBody(CurRec.get()))
2643     return true;
2644 
2645   return addEntry(std::move(CurRec));
2646 }
2647 
2648 /// ParseDefset - Parse a defset statement.
2649 ///
2650 ///   Defset ::= DEFSET Type Id '=' '{' ObjectList '}'
2651 ///
2652 bool TGParser::ParseDefset() {
2653   assert(Lex.getCode() == tgtok::Defset);
2654   Lex.Lex(); // Eat the 'defset' token
2655 
2656   DefsetRecord Defset;
2657   Defset.Loc = Lex.getLoc();
2658   RecTy *Type = ParseType();
2659   if (!Type)
2660     return true;
2661   if (!isa<ListRecTy>(Type))
2662     return Error(Defset.Loc, "expected list type");
2663   Defset.EltTy = cast<ListRecTy>(Type)->getElementType();
2664 
2665   if (Lex.getCode() != tgtok::Id)
2666     return TokError("expected identifier");
2667   StringInit *DeclName = StringInit::get(Lex.getCurStrVal());
2668   if (Records.getGlobal(DeclName->getValue()))
2669     return TokError("def or global variable of this name already exists");
2670 
2671   if (Lex.Lex() != tgtok::equal) // Eat the identifier
2672     return TokError("expected '='");
2673   if (Lex.Lex() != tgtok::l_brace) // Eat the '='
2674     return TokError("expected '{'");
2675   SMLoc BraceLoc = Lex.getLoc();
2676   Lex.Lex(); // Eat the '{'
2677 
2678   Defsets.push_back(&Defset);
2679   bool Err = ParseObjectList(nullptr);
2680   Defsets.pop_back();
2681   if (Err)
2682     return true;
2683 
2684   if (Lex.getCode() != tgtok::r_brace) {
2685     TokError("expected '}' at end of defset");
2686     return Error(BraceLoc, "to match this '{'");
2687   }
2688   Lex.Lex();  // Eat the '}'
2689 
2690   Records.addExtraGlobal(DeclName->getValue(),
2691                          ListInit::get(Defset.Elements, Defset.EltTy));
2692   return false;
2693 }
2694 
2695 /// ParseForeach - Parse a for statement.  Return the record corresponding
2696 /// to it.  This returns true on error.
2697 ///
2698 ///   Foreach ::= FOREACH Declaration IN '{ ObjectList '}'
2699 ///   Foreach ::= FOREACH Declaration IN Object
2700 ///
2701 bool TGParser::ParseForeach(MultiClass *CurMultiClass) {
2702   SMLoc Loc = Lex.getLoc();
2703   assert(Lex.getCode() == tgtok::Foreach && "Unknown tok");
2704   Lex.Lex();  // Eat the 'for' token.
2705 
2706   // Make a temporary object to record items associated with the for
2707   // loop.
2708   Init *ListValue = nullptr;
2709   VarInit *IterName = ParseForeachDeclaration(ListValue);
2710   if (!IterName)
2711     return TokError("expected declaration in for");
2712 
2713   if (Lex.getCode() != tgtok::In)
2714     return TokError("Unknown tok");
2715   Lex.Lex();  // Eat the in
2716 
2717   // Create a loop object and remember it.
2718   Loops.push_back(llvm::make_unique<ForeachLoop>(Loc, IterName, ListValue));
2719 
2720   if (Lex.getCode() != tgtok::l_brace) {
2721     // FOREACH Declaration IN Object
2722     if (ParseObject(CurMultiClass))
2723       return true;
2724   } else {
2725     SMLoc BraceLoc = Lex.getLoc();
2726     // Otherwise, this is a group foreach.
2727     Lex.Lex();  // eat the '{'.
2728 
2729     // Parse the object list.
2730     if (ParseObjectList(CurMultiClass))
2731       return true;
2732 
2733     if (Lex.getCode() != tgtok::r_brace) {
2734       TokError("expected '}' at end of foreach command");
2735       return Error(BraceLoc, "to match this '{'");
2736     }
2737     Lex.Lex();  // Eat the }
2738   }
2739 
2740   // Resolve the loop or store it for later resolution.
2741   std::unique_ptr<ForeachLoop> Loop = std::move(Loops.back());
2742   Loops.pop_back();
2743 
2744   return addEntry(std::move(Loop));
2745 }
2746 
2747 /// ParseClass - Parse a tblgen class definition.
2748 ///
2749 ///   ClassInst ::= CLASS ID TemplateArgList? ObjectBody
2750 ///
2751 bool TGParser::ParseClass() {
2752   assert(Lex.getCode() == tgtok::Class && "Unexpected token!");
2753   Lex.Lex();
2754 
2755   if (Lex.getCode() != tgtok::Id)
2756     return TokError("expected class name after 'class' keyword");
2757 
2758   Record *CurRec = Records.getClass(Lex.getCurStrVal());
2759   if (CurRec) {
2760     // If the body was previously defined, this is an error.
2761     if (!CurRec->getValues().empty() ||
2762         !CurRec->getSuperClasses().empty() ||
2763         !CurRec->getTemplateArgs().empty())
2764       return TokError("Class '" + CurRec->getNameInitAsString() +
2765                       "' already defined");
2766   } else {
2767     // If this is the first reference to this class, create and add it.
2768     auto NewRec =
2769         llvm::make_unique<Record>(Lex.getCurStrVal(), Lex.getLoc(), Records,
2770                                   /*Class=*/true);
2771     CurRec = NewRec.get();
2772     Records.addClass(std::move(NewRec));
2773   }
2774   Lex.Lex(); // eat the name.
2775 
2776   // If there are template args, parse them.
2777   if (Lex.getCode() == tgtok::less)
2778     if (ParseTemplateArgList(CurRec))
2779       return true;
2780 
2781   return ParseObjectBody(CurRec);
2782 }
2783 
2784 /// ParseLetList - Parse a non-empty list of assignment expressions into a list
2785 /// of LetRecords.
2786 ///
2787 ///   LetList ::= LetItem (',' LetItem)*
2788 ///   LetItem ::= ID OptionalRangeList '=' Value
2789 ///
2790 void TGParser::ParseLetList(SmallVectorImpl<LetRecord> &Result) {
2791   while (true) {
2792     if (Lex.getCode() != tgtok::Id) {
2793       TokError("expected identifier in let definition");
2794       Result.clear();
2795       return;
2796     }
2797 
2798     StringInit *Name = StringInit::get(Lex.getCurStrVal());
2799     SMLoc NameLoc = Lex.getLoc();
2800     Lex.Lex();  // Eat the identifier.
2801 
2802     // Check for an optional RangeList.
2803     SmallVector<unsigned, 16> Bits;
2804     if (ParseOptionalRangeList(Bits)) {
2805       Result.clear();
2806       return;
2807     }
2808     std::reverse(Bits.begin(), Bits.end());
2809 
2810     if (Lex.getCode() != tgtok::equal) {
2811       TokError("expected '=' in let expression");
2812       Result.clear();
2813       return;
2814     }
2815     Lex.Lex();  // eat the '='.
2816 
2817     Init *Val = ParseValue(nullptr);
2818     if (!Val) {
2819       Result.clear();
2820       return;
2821     }
2822 
2823     // Now that we have everything, add the record.
2824     Result.emplace_back(Name, Bits, Val, NameLoc);
2825 
2826     if (Lex.getCode() != tgtok::comma)
2827       return;
2828     Lex.Lex();  // eat the comma.
2829   }
2830 }
2831 
2832 /// ParseTopLevelLet - Parse a 'let' at top level.  This can be a couple of
2833 /// different related productions. This works inside multiclasses too.
2834 ///
2835 ///   Object ::= LET LetList IN '{' ObjectList '}'
2836 ///   Object ::= LET LetList IN Object
2837 ///
2838 bool TGParser::ParseTopLevelLet(MultiClass *CurMultiClass) {
2839   assert(Lex.getCode() == tgtok::Let && "Unexpected token");
2840   Lex.Lex();
2841 
2842   // Add this entry to the let stack.
2843   SmallVector<LetRecord, 8> LetInfo;
2844   ParseLetList(LetInfo);
2845   if (LetInfo.empty()) return true;
2846   LetStack.push_back(std::move(LetInfo));
2847 
2848   if (Lex.getCode() != tgtok::In)
2849     return TokError("expected 'in' at end of top-level 'let'");
2850   Lex.Lex();
2851 
2852   // If this is a scalar let, just handle it now
2853   if (Lex.getCode() != tgtok::l_brace) {
2854     // LET LetList IN Object
2855     if (ParseObject(CurMultiClass))
2856       return true;
2857   } else {   // Object ::= LETCommand '{' ObjectList '}'
2858     SMLoc BraceLoc = Lex.getLoc();
2859     // Otherwise, this is a group let.
2860     Lex.Lex();  // eat the '{'.
2861 
2862     // Parse the object list.
2863     if (ParseObjectList(CurMultiClass))
2864       return true;
2865 
2866     if (Lex.getCode() != tgtok::r_brace) {
2867       TokError("expected '}' at end of top level let command");
2868       return Error(BraceLoc, "to match this '{'");
2869     }
2870     Lex.Lex();
2871   }
2872 
2873   // Outside this let scope, this let block is not active.
2874   LetStack.pop_back();
2875   return false;
2876 }
2877 
2878 /// ParseMultiClass - Parse a multiclass definition.
2879 ///
2880 ///  MultiClassInst ::= MULTICLASS ID TemplateArgList?
2881 ///                     ':' BaseMultiClassList '{' MultiClassObject+ '}'
2882 ///  MultiClassObject ::= DefInst
2883 ///  MultiClassObject ::= MultiClassInst
2884 ///  MultiClassObject ::= DefMInst
2885 ///  MultiClassObject ::= LETCommand '{' ObjectList '}'
2886 ///  MultiClassObject ::= LETCommand Object
2887 ///
2888 bool TGParser::ParseMultiClass() {
2889   assert(Lex.getCode() == tgtok::MultiClass && "Unexpected token");
2890   Lex.Lex();  // Eat the multiclass token.
2891 
2892   if (Lex.getCode() != tgtok::Id)
2893     return TokError("expected identifier after multiclass for name");
2894   std::string Name = Lex.getCurStrVal();
2895 
2896   auto Result =
2897     MultiClasses.insert(std::make_pair(Name,
2898                     llvm::make_unique<MultiClass>(Name, Lex.getLoc(),Records)));
2899 
2900   if (!Result.second)
2901     return TokError("multiclass '" + Name + "' already defined");
2902 
2903   CurMultiClass = Result.first->second.get();
2904   Lex.Lex();  // Eat the identifier.
2905 
2906   // If there are template args, parse them.
2907   if (Lex.getCode() == tgtok::less)
2908     if (ParseTemplateArgList(nullptr))
2909       return true;
2910 
2911   bool inherits = false;
2912 
2913   // If there are submulticlasses, parse them.
2914   if (Lex.getCode() == tgtok::colon) {
2915     inherits = true;
2916 
2917     Lex.Lex();
2918 
2919     // Read all of the submulticlasses.
2920     SubMultiClassReference SubMultiClass =
2921       ParseSubMultiClassReference(CurMultiClass);
2922     while (true) {
2923       // Check for error.
2924       if (!SubMultiClass.MC) return true;
2925 
2926       // Add it.
2927       if (AddSubMultiClass(CurMultiClass, SubMultiClass))
2928         return true;
2929 
2930       if (Lex.getCode() != tgtok::comma) break;
2931       Lex.Lex(); // eat ','.
2932       SubMultiClass = ParseSubMultiClassReference(CurMultiClass);
2933     }
2934   }
2935 
2936   if (Lex.getCode() != tgtok::l_brace) {
2937     if (!inherits)
2938       return TokError("expected '{' in multiclass definition");
2939     if (Lex.getCode() != tgtok::semi)
2940       return TokError("expected ';' in multiclass definition");
2941     Lex.Lex();  // eat the ';'.
2942   } else {
2943     if (Lex.Lex() == tgtok::r_brace)  // eat the '{'.
2944       return TokError("multiclass must contain at least one def");
2945 
2946     while (Lex.getCode() != tgtok::r_brace) {
2947       switch (Lex.getCode()) {
2948       default:
2949         return TokError("expected 'let', 'def', 'defm' or 'foreach' in "
2950                         "multiclass body");
2951       case tgtok::Let:
2952       case tgtok::Def:
2953       case tgtok::Defm:
2954       case tgtok::Foreach:
2955         if (ParseObject(CurMultiClass))
2956           return true;
2957         break;
2958       }
2959     }
2960     Lex.Lex();  // eat the '}'.
2961   }
2962 
2963   CurMultiClass = nullptr;
2964   return false;
2965 }
2966 
2967 /// ParseDefm - Parse the instantiation of a multiclass.
2968 ///
2969 ///   DefMInst ::= DEFM ID ':' DefmSubClassRef ';'
2970 ///
2971 bool TGParser::ParseDefm(MultiClass *CurMultiClass) {
2972   assert(Lex.getCode() == tgtok::Defm && "Unexpected token!");
2973   Lex.Lex(); // eat the defm
2974 
2975   Init *DefmName = ParseObjectName(CurMultiClass);
2976   if (!DefmName)
2977     return true;
2978   if (isa<UnsetInit>(DefmName)) {
2979     DefmName = Records.getNewAnonymousName();
2980     if (CurMultiClass)
2981       DefmName = BinOpInit::getStrConcat(
2982           VarInit::get(QualifiedNameOfImplicitName(CurMultiClass),
2983                        StringRecTy::get()),
2984           DefmName);
2985   }
2986 
2987   if (Lex.getCode() != tgtok::colon)
2988     return TokError("expected ':' after defm identifier");
2989 
2990   // Keep track of the new generated record definitions.
2991   std::vector<RecordsEntry> NewEntries;
2992 
2993   // This record also inherits from a regular class (non-multiclass)?
2994   bool InheritFromClass = false;
2995 
2996   // eat the colon.
2997   Lex.Lex();
2998 
2999   SMLoc SubClassLoc = Lex.getLoc();
3000   SubClassReference Ref = ParseSubClassReference(nullptr, true);
3001 
3002   while (true) {
3003     if (!Ref.Rec) return true;
3004 
3005     // To instantiate a multiclass, we need to first get the multiclass, then
3006     // instantiate each def contained in the multiclass with the SubClassRef
3007     // template parameters.
3008     MultiClass *MC = MultiClasses[Ref.Rec->getName()].get();
3009     assert(MC && "Didn't lookup multiclass correctly?");
3010     ArrayRef<Init*> TemplateVals = Ref.TemplateArgs;
3011 
3012     // Verify that the correct number of template arguments were specified.
3013     ArrayRef<Init *> TArgs = MC->Rec.getTemplateArgs();
3014     if (TArgs.size() < TemplateVals.size())
3015       return Error(SubClassLoc,
3016                    "more template args specified than multiclass expects");
3017 
3018     SubstStack Substs;
3019     for (unsigned i = 0, e = TArgs.size(); i != e; ++i) {
3020       if (i < TemplateVals.size()) {
3021         Substs.emplace_back(TArgs[i], TemplateVals[i]);
3022       } else {
3023         Init *Default = MC->Rec.getValue(TArgs[i])->getValue();
3024         if (!Default->isComplete()) {
3025           return Error(SubClassLoc,
3026                        "value not specified for template argument #" +
3027                            Twine(i) + " (" + TArgs[i]->getAsUnquotedString() +
3028                            ") of multiclass '" + MC->Rec.getNameInitAsString() +
3029                            "'");
3030         }
3031         Substs.emplace_back(TArgs[i], Default);
3032       }
3033     }
3034 
3035     Substs.emplace_back(QualifiedNameOfImplicitName(MC), DefmName);
3036 
3037     if (resolve(MC->Entries, Substs, CurMultiClass == nullptr, &NewEntries,
3038                 &SubClassLoc))
3039       return true;
3040 
3041     if (Lex.getCode() != tgtok::comma) break;
3042     Lex.Lex(); // eat ','.
3043 
3044     if (Lex.getCode() != tgtok::Id)
3045       return TokError("expected identifier");
3046 
3047     SubClassLoc = Lex.getLoc();
3048 
3049     // A defm can inherit from regular classes (non-multiclass) as
3050     // long as they come in the end of the inheritance list.
3051     InheritFromClass = (Records.getClass(Lex.getCurStrVal()) != nullptr);
3052 
3053     if (InheritFromClass)
3054       break;
3055 
3056     Ref = ParseSubClassReference(nullptr, true);
3057   }
3058 
3059   if (InheritFromClass) {
3060     // Process all the classes to inherit as if they were part of a
3061     // regular 'def' and inherit all record values.
3062     SubClassReference SubClass = ParseSubClassReference(nullptr, false);
3063     while (true) {
3064       // Check for error.
3065       if (!SubClass.Rec) return true;
3066 
3067       // Get the expanded definition prototypes and teach them about
3068       // the record values the current class to inherit has
3069       for (auto &E : NewEntries) {
3070         // Add it.
3071         if (AddSubClass(E, SubClass))
3072           return true;
3073       }
3074 
3075       if (Lex.getCode() != tgtok::comma) break;
3076       Lex.Lex(); // eat ','.
3077       SubClass = ParseSubClassReference(nullptr, false);
3078     }
3079   }
3080 
3081   for (auto &E : NewEntries) {
3082     if (ApplyLetStack(E))
3083       return true;
3084 
3085     addEntry(std::move(E));
3086   }
3087 
3088   if (Lex.getCode() != tgtok::semi)
3089     return TokError("expected ';' at end of defm");
3090   Lex.Lex();
3091 
3092   return false;
3093 }
3094 
3095 /// ParseObject
3096 ///   Object ::= ClassInst
3097 ///   Object ::= DefInst
3098 ///   Object ::= MultiClassInst
3099 ///   Object ::= DefMInst
3100 ///   Object ::= LETCommand '{' ObjectList '}'
3101 ///   Object ::= LETCommand Object
3102 bool TGParser::ParseObject(MultiClass *MC) {
3103   switch (Lex.getCode()) {
3104   default:
3105     return TokError("Expected class, def, defm, defset, multiclass, let or "
3106                     "foreach");
3107   case tgtok::Let:   return ParseTopLevelLet(MC);
3108   case tgtok::Def:   return ParseDef(MC);
3109   case tgtok::Foreach:   return ParseForeach(MC);
3110   case tgtok::Defm:  return ParseDefm(MC);
3111   case tgtok::Defset:
3112     if (MC)
3113       return TokError("defset is not allowed inside multiclass");
3114     return ParseDefset();
3115   case tgtok::Class:
3116     if (MC)
3117       return TokError("class is not allowed inside multiclass");
3118     if (!Loops.empty())
3119       return TokError("class is not allowed inside foreach loop");
3120     return ParseClass();
3121   case tgtok::MultiClass:
3122     if (!Loops.empty())
3123       return TokError("multiclass is not allowed inside foreach loop");
3124     return ParseMultiClass();
3125   }
3126 }
3127 
3128 /// ParseObjectList
3129 ///   ObjectList :== Object*
3130 bool TGParser::ParseObjectList(MultiClass *MC) {
3131   while (isObjectStart(Lex.getCode())) {
3132     if (ParseObject(MC))
3133       return true;
3134   }
3135   return false;
3136 }
3137 
3138 bool TGParser::ParseFile() {
3139   Lex.Lex(); // Prime the lexer.
3140   if (ParseObjectList()) return true;
3141 
3142   // If we have unread input at the end of the file, report it.
3143   if (Lex.getCode() == tgtok::Eof)
3144     return false;
3145 
3146   return TokError("Unexpected input at top level");
3147 }
3148 
3149 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3150 LLVM_DUMP_METHOD void RecordsEntry::dump() const {
3151   if (Loop)
3152     Loop->dump();
3153   if (Rec)
3154     Rec->dump();
3155 }
3156 
3157 LLVM_DUMP_METHOD void ForeachLoop::dump() const {
3158   errs() << "foreach " << IterVar->getAsString() << " = "
3159          << ListValue->getAsString() << " in {\n";
3160 
3161   for (const auto &E : Entries)
3162     E.dump();
3163 
3164   errs() << "}\n";
3165 }
3166 
3167 LLVM_DUMP_METHOD void MultiClass::dump() const {
3168   errs() << "Record:\n";
3169   Rec.dump();
3170 
3171   errs() << "Defs:\n";
3172   for (const auto &E : Entries)
3173     E.dump();
3174 }
3175 #endif
3176