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